repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/iwidgets/sample/shell.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/iwidgets/sample/shell.rb
#!/usr/bin/env ruby
require 'tk'
require 'tkextlib/iwidgets'
sh = Tk::Iwidgets::Shell.new(:modality=>:application,
:padx=>20, :pady=>20, :title=>'Shell')
TkButton.new(:text=>'ACTIVATE', :padx=>7, :pady=>7,
:command=>proc{puts sh.activate}).pack(:padx=>10, :pady=>10)
TkLabel.new(sh.child_site, :text=>'SHELL').pack
TkButton.new(sh.child_site, :text=>'YES',
:command=>proc{sh.deactivate 'press YES'}).pack(:fill=>:x)
TkButton.new(sh.child_site, :text=>'NO',
:command=>proc{sh.deactivate 'press NO'}).pack(:fill=>:x)
Tk.mainloop
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/mixlib-cli-1.6.0/lib/mixlib/cli/version.rb
|
<gh_stars>0
module Mixlib
module CLI
VERSION = "1.6.0"
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/winrm-1.8.1/spec/matchers.rb
|
# encoding: UTF-8
require 'rspec/expectations'
# rspec matchers
module WinRMSpecs
def self.stdout(output)
output[:data].collect do |i|
i[:stdout]
end.join('\r\n').gsub(/(\\r\\n)+$/, '')
end
def self.stderr(output)
output[:data].collect do |i|
i[:stderr]
end.join('\r\n').gsub(/(\\r\\n)+$/, '')
end
end
RSpec::Matchers.define :have_stdout_match do |expected_stdout|
match do |actual_output|
!expected_stdout.match(WinRMSpecs.stdout(actual_output)).nil?
end
failure_message do |actual_output|
"expected that '#{WinRMSpecs.stdout(actual_output)}' would match #{expected_stdout}"
end
end
RSpec::Matchers.define :have_stderr_match do |expected_stderr|
match do |actual_output|
!expected_stderr.match(WinRMSpecs.stderr(actual_output)).nil?
end
failure_message do |actual_output|
"expected that '#{WinRMSpecs.stderr(actual_output)}' would match #{expected_stderr}"
end
end
RSpec::Matchers.define :have_no_stdout do
match do |actual_output|
stdout = WinRMSpecs.stdout(actual_output)
stdout == '\r\n' || stdout == ''
end
failure_message do |actual_output|
"expected that '#{WinRMSpecs.stdout(actual_output)}' would have no stdout"
end
end
RSpec::Matchers.define :have_no_stderr do
match do |actual_output|
stderr = WinRMSpecs.stderr(actual_output)
stderr == '\r\n' || stderr == ''
end
failure_message do |actual_output|
"expected that '#{WinRMSpecs.stderr(actual_output)}' would have no stderr"
end
end
RSpec::Matchers.define :have_exit_code do |expected_exit_code|
match do |actual_output|
expected_exit_code == actual_output[:exitcode]
end
failure_message do |actual_output|
"expected exit code #{expected_exit_code}, but got #{actual_output[:exitcode]}"
end
end
RSpec::Matchers.define :be_a_uid do
match do |actual|
# WinRM1.1 returns uuid's prefixed with 'uuid:' where as later versions do not
actual && actual.to_s.match(/^(uuid:)*\w{8}-\w{4}-\w{4}-\w{4}-\w{12}$/)
end
failure_message do |actual|
"expected a uid, but got '#{actual}'"
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/sample/pty/shl.rb
|
#
# old-fashioned 'shl' like program
# by <NAME>
#
# commands:
# c creates new shell
# C-z suspends shell
# p lists all shell
# 0,1,... choose shell
# q quit
require 'pty'
$shells = []
$n_shells = 0
$r_pty = nil
$w_pty = nil
def writer
system "stty -echo raw"
begin
while true
c = STDIN.getc
if c == 26 then # C-z
$reader.raise(nil)
return 'Suspend'
end
$w_pty.print c.chr
$w_pty.flush
end
rescue
$reader.raise(nil)
return 'Exit'
ensure
system "stty echo -raw"
end
end
$reader = Thread.new {
while true
begin
next if $r_pty.nil?
c = $r_pty.getc
if c.nil? then
Thread.stop
end
print c.chr
STDOUT.flush
rescue
Thread.stop
end
end
}
# $reader.raise(nil)
while true
print ">> "
STDOUT.flush
case gets
when /^c/i
$shells[$n_shells] = PTY.spawn("/bin/csh")
$r_pty,$w_pty = $shells[$n_shells]
$n_shells += 1
$reader.run
if writer == 'Exit'
$n_shells -= 1
$shells[$n_shells] = nil
end
when /^p/i
for i in 0..$n_shells
unless $shells[i].nil?
print i,"\n"
end
end
when /^([0-9]+)/
n = $1.to_i
if $shells[n].nil?
print "\##{i} doesn't exist\n"
else
$r_pty,$w_pty = $shells[n]
$reader.run
if writer == 'Exit' then
$shells[n] = nil
end
end
when /^q/i
exit
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/rubygems/test_gem_remote_fetcher.rb
|
# frozen_string_literal: false
require 'rubygems/test_case'
require 'webrick'
begin
require 'webrick/https'
rescue LoadError => e
raise unless (e.respond_to?(:path) && e.path == 'openssl') ||
e.message =~ / -- openssl$/
end
require 'rubygems/remote_fetcher'
require 'rubygems/package'
require 'minitest/mock'
# = Testing Proxy Settings
#
# These tests check the proper proxy server settings by running two
# web servers. The web server at http://localhost:#{SERVER_PORT}
# represents the normal gem server and returns a gemspec with a rake
# version of 0.4.11. The web server at http://localhost:#{PROXY_PORT}
# represents the proxy server and returns a different dataset where
# rake has version 0.4.2. This allows us to detect which server is
# returning the data.
#
# Note that the proxy server is not a *real* proxy server. But our
# software doesn't really care, as long as we hit the proxy URL when a
# proxy is configured.
class TestGemRemoteFetcher < Gem::TestCase
include Gem::DefaultUserInteraction
SERVER_DATA = <<-EOY
--- !ruby/object:Gem::Cache
gems:
rake-0.4.11: !ruby/object:Gem::Specification
rubygems_version: "0.7"
specification_version: 1
name: rake
version: !ruby/object:Gem::Version
version: 0.4.11
date: 2004-11-12
summary: Ruby based make-like utility.
require_paths:
- lib
author: <NAME>
email: <EMAIL>
homepage: http://rake.rubyforge.org
rubyforge_project: rake
description: Rake is a Make-like program implemented in Ruby. Tasks and dependencies are specified in standard Ruby syntax.
autorequire:
default_executable: rake
bindir: bin
has_rdoc: true
required_ruby_version: !ruby/object:Gem::Version::Requirement
requirements:
-
- ">"
- !ruby/object:Gem::Version
version: 0.0.0
version:
platform: ruby
files:
- README
test_files: []
library_stubs:
rdoc_options:
extra_rdoc_files:
executables:
- rake
extensions: []
requirements: []
dependencies: []
EOY
PROXY_DATA = SERVER_DATA.gsub(/0.4.11/, '0.4.2')
DIR = File.expand_path(File.dirname(__FILE__))
# Generated via:
# x = OpenSSL::PKey::DH.new(2048) # wait a while...
# x.to_s => pem
# x.priv_key.to_s => hex for OpenSSL::BN.new
TEST_KEY_DH2048 = OpenSSL::PKey::DH.new <<-_end_of_pem_
-----BEGIN DH PARAMETERS-----
<KEY>
-----END DH PARAMETERS-----
_end_of_pem_
TEST_KEY_DH2048.priv_key = OpenSSL::BN.new("108911488509734781344423639" \
"5585749502236089033416160524030987005037540379474123441273555416835" \
"4725688238369352738266590757370603937618499698665047757588998555345" \
"3446251978586372525530219375408331096098220027413238477359960428372" \
"0195464393332338164504352015535549496585792320286513563739305843396" \
"9294344974028713065472959376197728193162272314514335882399554394661" \
"5306385003430991221886779612878793446851681835397455333989268503748" \
"7862488679178398716189205737442996155432191656080664090596502674943" \
"7902481557157485795980326766117882761941455140582265347052939604724" \
"964857770053363840471912215799994973597613931991572884", 16)
def setup
@proxies = %w[https_proxy http_proxy HTTP_PROXY http_proxy_user HTTP_PROXY_USER http_proxy_pass HTTP_PROXY_PASS no_proxy NO_PROXY]
@old_proxies = @proxies.map {|k| ENV[k] }
@proxies.each {|k| ENV[k] = nil }
super
self.class.start_servers
self.class.enable_yaml = true
self.class.enable_zip = false
base_server_uri = "http://localhost:#{self.class.normal_server_port}"
@proxy_uri = "http://localhost:#{self.class.proxy_server_port}"
@server_uri = base_server_uri + "/yaml"
@server_z_uri = base_server_uri + "/yaml.Z"
# REFACTOR: copied from test_gem_dependency_installer.rb
@gems_dir = File.join @tempdir, 'gems'
@cache_dir = File.join @gemhome, "cache"
FileUtils.mkdir @gems_dir
# TODO: why does the remote fetcher need it written to disk?
@a1, @a1_gem = util_gem 'a', '1' do |s| s.executables << 'a_bin' end
@a1.loaded_from = File.join(@gemhome, 'specifications', @a1.full_name)
Gem::RemoteFetcher.fetcher = nil
@fetcher = Gem::RemoteFetcher.fetcher
end
def teardown
@fetcher.close_all
self.class.stop_servers
super
Gem.configuration[:http_proxy] = nil
@proxies.each_with_index {|k, i| ENV[k] = @old_proxies[i] }
end
def test_self_fetcher
fetcher = Gem::RemoteFetcher.fetcher
refute_nil fetcher
assert_kind_of Gem::RemoteFetcher, fetcher
end
def test_self_fetcher_with_proxy
proxy_uri = 'http://proxy.example.com'
Gem.configuration[:http_proxy] = proxy_uri
Gem::RemoteFetcher.fetcher = nil
fetcher = Gem::RemoteFetcher.fetcher
refute_nil fetcher
assert_kind_of Gem::RemoteFetcher, fetcher
assert_equal proxy_uri, fetcher.instance_variable_get(:@proxy).to_s
end
def test_fetch_size_bad_uri
fetcher = Gem::RemoteFetcher.new nil
@fetcher = fetcher
e = assert_raises ArgumentError do
fetcher.fetch_size 'gems.example.com/yaml'
end
assert_equal 'uri scheme is invalid: nil', e.message
end
def test_fetch_size_socket_error
fetcher = Gem::RemoteFetcher.new nil
@fetcher = fetcher
def fetcher.request(uri, request_class, last_modified = nil)
raise SocketError, "tarded"
end
uri = 'http://gems.example.com/yaml'
e = assert_raises Gem::RemoteFetcher::FetchError do
fetcher.fetch_size uri
end
assert_equal "SocketError: tarded (#{uri})", e.message
end
def test_no_proxy
use_ui @ui do
assert_data_from_server @fetcher.fetch_path(@server_uri)
assert_equal SERVER_DATA.size, @fetcher.fetch_size(@server_uri)
end
end
def test_api_endpoint
uri = URI.parse "http://example.com/foo"
target = MiniTest::Mock.new
target.expect :target, "gems.example.com"
dns = MiniTest::Mock.new
dns.expect :getresource, target, [String, Object]
fetch = Gem::RemoteFetcher.new nil, dns
assert_equal URI.parse("http://gems.example.com/foo"), fetch.api_endpoint(uri)
target.verify
dns.verify
end
def test_api_endpoint_ignores_trans_domain_values
uri = URI.parse "http://gems.example.com/foo"
target = MiniTest::Mock.new
target.expect :target, "blah.com"
dns = MiniTest::Mock.new
dns.expect :getresource, target, [String, Object]
fetch = Gem::RemoteFetcher.new nil, dns
assert_equal URI.parse("http://gems.example.com/foo"), fetch.api_endpoint(uri)
target.verify
dns.verify
end
def test_api_endpoint_ignores_trans_domain_values_that_starts_with_original
uri = URI.parse "http://example.com/foo"
target = MiniTest::Mock.new
target.expect :target, "example.combadguy.com"
dns = MiniTest::Mock.new
dns.expect :getresource, target, [String, Object]
fetch = Gem::RemoteFetcher.new nil, dns
assert_equal URI.parse("http://example.com/foo"), fetch.api_endpoint(uri)
target.verify
dns.verify
end
def test_api_endpoint_ignores_trans_domain_values_that_end_with_original
uri = URI.parse "http://example.com/foo"
target = MiniTest::Mock.new
target.expect :target, "badexample.com"
dns = MiniTest::Mock.new
dns.expect :getresource, target, [String, Object]
fetch = Gem::RemoteFetcher.new nil, dns
assert_equal URI.parse("http://example.com/foo"), fetch.api_endpoint(uri)
target.verify
dns.verify
end
def test_api_endpoint_timeout_warning
uri = URI.parse "http://gems.example.com/foo"
dns = MiniTest::Mock.new
def dns.getresource arg, *rest
raise Resolv::ResolvError.new('timeout!')
end
fetch = Gem::RemoteFetcher.new nil, dns
begin
old_verbose, Gem.configuration.verbose = Gem.configuration.verbose, 1
endpoint = use_ui @ui do
fetch.api_endpoint(uri)
end
ensure
Gem.configuration.verbose = old_verbose
end
assert_equal uri, endpoint
assert_equal "Getting SRV record failed: timeout!\n", @ui.output
dns.verify
end
def test_cache_update_path
uri = URI 'http://example/file'
path = File.join @tempdir, 'file'
fetcher = util_fuck_with_fetcher 'hello'
data = fetcher.cache_update_path uri, path
assert_equal 'hello', data
assert_equal 'hello', File.read(path)
end
def test_cache_update_path_no_update
uri = URI 'http://example/file'
path = File.join @tempdir, 'file'
fetcher = util_fuck_with_fetcher 'hello'
data = fetcher.cache_update_path uri, path, false
assert_equal 'hello', data
refute_path_exists path
end
def util_fuck_with_fetcher data, blow = false
fetcher = Gem::RemoteFetcher.fetcher
fetcher.instance_variable_set :@test_data, data
unless blow then
def fetcher.fetch_path arg, *rest
@test_arg = arg
@test_data
end
else
def fetcher.fetch_path arg, *rest
# OMG I'm such an ass
class << self; remove_method :fetch_path; end
def self.fetch_path arg, *rest
@test_arg = arg
@test_data
end
raise Gem::RemoteFetcher::FetchError.new("haha!", nil)
end
end
fetcher
end
def test_download
a1_data = nil
File.open @a1_gem, 'rb' do |fp|
a1_data = fp.read
end
fetcher = util_fuck_with_fetcher a1_data
a1_cache_gem = @a1.cache_file
assert_equal a1_cache_gem, fetcher.download(@a1, 'http://gems.example.com')
assert_equal("http://gems.example.com/gems/a-1.gem",
fetcher.instance_variable_get(:@test_arg).to_s)
assert File.exist?(a1_cache_gem)
end
def test_download_with_auth
a1_data = nil
File.open @a1_gem, 'rb' do |fp|
a1_data = fp.read
end
fetcher = util_fuck_with_fetcher a1_data
a1_cache_gem = @a1.cache_file
assert_equal a1_cache_gem, fetcher.download(@a1, 'http://user:password@gems.<EMAIL>')
assert_equal("http://user:password@gems.example.com/gems/a-1.gem",
fetcher.instance_variable_get(:@test_arg).to_s)
assert File.exist?(a1_cache_gem)
end
def test_download_with_encoded_auth
a1_data = nil
File.open @a1_gem, 'rb' do |fp|
a1_data = fp.read
end
fetcher = util_fuck_with_fetcher a1_data
a1_cache_gem = @a1.cache_file
assert_equal a1_cache_gem, fetcher.download(@a1, 'http://user:%25pas%25sword@gems.example.com')
assert_equal("http://user:%25pas%25sword@gems.example.com/gems/a-1.gem",
fetcher.instance_variable_get(:@test_arg).to_s)
assert File.exist?(a1_cache_gem)
end
def test_download_cached
FileUtils.mv @a1_gem, @cache_dir
inst = Gem::RemoteFetcher.fetcher
assert_equal @a1.cache_file, inst.download(@a1, 'http://gems.example.com')
end
def test_download_local
FileUtils.mv @a1_gem, @tempdir
local_path = File.join @tempdir, @a1.file_name
inst = nil
Dir.chdir @tempdir do
inst = Gem::RemoteFetcher.fetcher
end
assert_equal @a1.cache_file, inst.download(@a1, local_path)
end
def test_download_local_space
space_path = File.join @tempdir, 'space path'
FileUtils.mkdir space_path
FileUtils.mv @a1_gem, space_path
local_path = File.join space_path, @a1.file_name
inst = nil
Dir.chdir @tempdir do
inst = Gem::RemoteFetcher.fetcher
end
assert_equal @a1.cache_file, inst.download(@a1, local_path)
end
def test_download_install_dir
a1_data = File.open @a1_gem, 'rb' do |fp|
fp.read
end
fetcher = util_fuck_with_fetcher a1_data
install_dir = File.join @tempdir, 'more_gems'
a1_cache_gem = File.join install_dir, "cache", @a1.file_name
FileUtils.mkdir_p(File.dirname(a1_cache_gem))
actual = fetcher.download(@a1, 'http://gems.example.com', install_dir)
assert_equal a1_cache_gem, actual
assert_equal("http://gems.example.com/gems/a-1.gem",
fetcher.instance_variable_get(:@test_arg).to_s)
assert File.exist?(a1_cache_gem)
end
unless win_platform? # File.chmod doesn't work
def test_download_local_read_only
FileUtils.mv @a1_gem, @tempdir
local_path = File.join @tempdir, @a1.file_name
inst = nil
FileUtils.chmod 0555, @a1.cache_dir
Dir.chdir @tempdir do
inst = Gem::RemoteFetcher.fetcher
end
assert_equal(File.join(@tempdir, @a1.file_name),
inst.download(@a1, local_path))
ensure
FileUtils.chmod 0755, @a1.cache_dir
end
def test_download_read_only
FileUtils.chmod 0555, @a1.cache_dir
FileUtils.chmod 0555, @gemhome
fetcher = util_fuck_with_fetcher File.read(@a1_gem)
fetcher.download(@a1, 'http://gems.example.com')
a1_cache_gem = File.join Gem.user_dir, "cache", @a1.file_name
assert File.exist? a1_cache_gem
ensure
FileUtils.chmod 0755, @gemhome
FileUtils.chmod 0755, @a1.cache_dir
end
end
def test_download_platform_legacy
original_platform = 'old-platform'
e1, e1_gem = util_gem 'e', '1' do |s|
s.platform = Gem::Platform::CURRENT
s.instance_variable_set :@original_platform, original_platform
end
e1.loaded_from = File.join(@gemhome, 'specifications', e1.full_name)
e1_data = nil
File.open e1_gem, 'rb' do |fp|
e1_data = fp.read
end
fetcher = util_fuck_with_fetcher e1_data, :blow_chunks
e1_cache_gem = e1.cache_file
assert_equal e1_cache_gem, fetcher.download(e1, 'http://gems.example.com')
assert_equal("http://gems.example.com/gems/#{e1.original_name}.gem",
fetcher.instance_variable_get(:@test_arg).to_s)
assert File.exist?(e1_cache_gem)
end
def test_download_same_file
FileUtils.mv @a1_gem, @tempdir
local_path = File.join @tempdir, @a1.file_name
inst = nil
Dir.chdir @tempdir do
inst = Gem::RemoteFetcher.fetcher
end
cache_path = @a1.cache_file
FileUtils.mv local_path, cache_path
gem = Gem::Package.new cache_path
assert_equal cache_path, inst.download(gem.spec, cache_path)
end
def test_download_unsupported
inst = Gem::RemoteFetcher.fetcher
e = assert_raises ArgumentError do
inst.download @a1, 'ftp://gems.rubyforge.org'
end
assert_equal 'unsupported URI scheme ftp', e.message
end
def test_download_to_cache
@a2, @a2_gem = util_gem 'a', '2'
util_setup_spec_fetcher @a1, @a2
@fetcher.instance_variable_set :@a1, @a1
@fetcher.instance_variable_set :@a2, @a2
def @fetcher.fetch_path uri, mtime = nil, head = false
case uri.request_uri
when /#{@a1.spec_name}/ then
Gem.deflate Marshal.dump @a1
when /#{@a2.spec_name}/ then
Gem.deflate Marshal.dump @a2
else
uri.to_s
end
end
gem = Gem::RemoteFetcher.fetcher.download_to_cache dep 'a'
assert_equal @a2.file_name, File.basename(gem)
end
def test_fetch_path_gzip
fetcher = Gem::RemoteFetcher.new nil
@fetcher = fetcher
def fetcher.fetch_http(uri, mtime, head = nil)
Gem.gzip 'foo'
end
assert_equal 'foo', fetcher.fetch_path(@uri + 'foo.gz')
end
def test_fetch_path_gzip_unmodified
fetcher = Gem::RemoteFetcher.new nil
@fetcher = fetcher
def fetcher.fetch_http(uri, mtime, head = nil)
nil
end
assert_equal nil, fetcher.fetch_path(@uri + 'foo.gz', Time.at(0))
end
def test_fetch_path_io_error
fetcher = Gem::RemoteFetcher.new nil
@fetcher = fetcher
def fetcher.fetch_http(*)
raise EOFError
end
url = 'http://example.com/uri'
e = assert_raises Gem::RemoteFetcher::FetchError do
fetcher.fetch_path url
end
assert_equal "EOFError: EOFError (#{url})", e.message
assert_equal url, e.uri
end
def test_fetch_path_socket_error
fetcher = Gem::RemoteFetcher.new nil
@fetcher = fetcher
def fetcher.fetch_http(uri, mtime, head = nil)
raise SocketError
end
url = 'http://example.com/uri'
e = assert_raises Gem::RemoteFetcher::FetchError do
fetcher.fetch_path url
end
assert_equal "SocketError: SocketError (#{url})", e.message
assert_equal url, e.uri
end
def test_fetch_path_system_call_error
fetcher = Gem::RemoteFetcher.new nil
@fetcher = fetcher
def fetcher.fetch_http(uri, mtime = nil, head = nil)
raise Errno::ECONNREFUSED, 'connect(2)'
end
url = 'http://example.com/uri'
e = assert_raises Gem::RemoteFetcher::FetchError do
fetcher.fetch_path url
end
assert_match %r|ECONNREFUSED:.*connect\(2\) \(#{Regexp.escape url}\)\z|,
e.message
assert_equal url, e.uri
end
def test_fetch_path_unmodified
fetcher = Gem::RemoteFetcher.new nil
@fetcher = fetcher
def fetcher.fetch_http(uri, mtime, head = nil)
nil
end
assert_equal nil, fetcher.fetch_path(URI.parse(@gem_repo), Time.at(0))
end
def test_implicit_no_proxy
use_ui @ui do
ENV['http_proxy'] = 'http://fakeurl:12345'
fetcher = Gem::RemoteFetcher.new :no_proxy
@fetcher = fetcher
assert_data_from_server fetcher.fetch_path(@server_uri)
end
end
def test_implicit_proxy
use_ui @ui do
ENV['http_proxy'] = @proxy_uri
fetcher = Gem::RemoteFetcher.new nil
@fetcher = fetcher
assert_data_from_proxy fetcher.fetch_path(@server_uri)
end
end
def test_implicit_upper_case_proxy
use_ui @ui do
ENV['HTTP_PROXY'] = @proxy_uri
fetcher = Gem::RemoteFetcher.new nil
@fetcher = fetcher
assert_data_from_proxy fetcher.fetch_path(@server_uri)
end
end
def test_implicit_proxy_no_env
use_ui @ui do
fetcher = Gem::RemoteFetcher.new nil
@fetcher = fetcher
assert_data_from_server fetcher.fetch_path(@server_uri)
end
end
def test_fetch_http
fetcher = Gem::RemoteFetcher.new nil
@fetcher = fetcher
url = 'http://gems.example.com/redirect'
def fetcher.request(uri, request_class, last_modified = nil)
url = 'http://gems.example.com/redirect'
unless defined? @requested then
@requested = true
res = Net::HTTPMovedPermanently.new nil, 301, nil
res.add_field 'Location', url
res
else
res = Net::HTTPOK.new nil, 200, nil
def res.body() 'real_path' end
res
end
end
data = fetcher.fetch_http URI.parse(url)
assert_equal 'real_path', data
end
def test_fetch_http_redirects
fetcher = Gem::RemoteFetcher.new nil
@fetcher = fetcher
url = 'http://gems.example.com/redirect'
def fetcher.request(uri, request_class, last_modified = nil)
url = 'http://gems.example.com/redirect'
res = Net::HTTPMovedPermanently.new nil, 301, nil
res.add_field 'Location', url
res
end
e = assert_raises Gem::RemoteFetcher::FetchError do
fetcher.fetch_http URI.parse(url)
end
assert_equal "too many redirects (#{url})", e.message
end
def test_fetch_http_with_additional_headers
ENV["http_proxy"] = @proxy_uri
ENV["no_proxy"] = URI::parse(@server_uri).host
fetcher = Gem::RemoteFetcher.new nil, nil, {"X-Captain" => "murphy"}
@fetcher = fetcher
assert_equal "murphy", fetcher.fetch_path(@server_uri)
end
def test_fetch_s3
fetcher = Gem::RemoteFetcher.new nil
@fetcher = fetcher
url = 's3://testuser:testpass@my-bucket/gems/specs.4.8.gz'
$fetched_uri = nil
def fetcher.request(uri, request_class, last_modified = nil)
$fetched_uri = uri
res = Net::HTTPOK.new nil, 200, nil
def res.body() 'success' end
res
end
def fetcher.s3_expiration
1395098371
end
data = fetcher.fetch_s3 URI.parse(url)
assert_equal 'https://my-bucket.s3.amazonaws.com/gems/specs.4.8.gz?AWSAccessKeyId=testuser&Expires=1395098371&Signature=eUTr7NkpZEet%2BJySE%2BfH6qukroI%3D', $fetched_uri.to_s
assert_equal 'success', data
ensure
$fetched_uri = nil
end
def test_fetch_s3_no_creds
fetcher = Gem::RemoteFetcher.new nil
@fetcher = fetcher
url = 's3://my-bucket/gems/specs.4.8.gz'
e = assert_raises Gem::RemoteFetcher::FetchError do
fetcher.fetch_s3 URI.parse(url)
end
assert_match "credentials needed", e.message
end
def test_observe_no_proxy_env_single_host
use_ui @ui do
ENV["http_proxy"] = @proxy_uri
ENV["no_proxy"] = URI::parse(@server_uri).host
fetcher = Gem::RemoteFetcher.new nil
@fetcher = fetcher
assert_data_from_server fetcher.fetch_path(@server_uri)
end
end
def test_observe_no_proxy_env_list
use_ui @ui do
ENV["http_proxy"] = @proxy_uri
ENV["no_proxy"] = "fakeurl.com, #{URI::parse(@server_uri).host}"
fetcher = Gem::RemoteFetcher.new nil
@fetcher = fetcher
assert_data_from_server fetcher.fetch_path(@server_uri)
end
end
def test_request_block
fetcher = Gem::RemoteFetcher.new nil
@fetcher = fetcher
assert_throws :block_called do
fetcher.request URI('http://example'), Net::HTTP::Get do |req|
assert_kind_of Net::HTTPGenericRequest, req
throw :block_called
end
end
end
def test_yaml_error_on_size
use_ui @ui do
self.class.enable_yaml = false
fetcher = Gem::RemoteFetcher.new nil
@fetcher = fetcher
assert_error { fetcher.size }
end
end
def test_ssl_connection
ssl_server = self.class.start_ssl_server
temp_ca_cert = File.join(DIR, 'ca_cert.pem')
with_configured_fetcher(":ssl_ca_cert: #{temp_ca_cert}") do |fetcher|
fetcher.fetch_path("https://localhost:#{ssl_server.config[:Port]}/yaml")
end
end
def test_ssl_client_cert_auth_connection
skip 'openssl is missing' unless defined?(OpenSSL::SSL)
ssl_server = self.class.start_ssl_server({
:SSLVerifyClient =>
OpenSSL::SSL::VERIFY_PEER|OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT})
temp_ca_cert = File.join(DIR, 'ca_cert.pem')
temp_client_cert = File.join(DIR, 'client.pem')
with_configured_fetcher(
":ssl_ca_cert: #{temp_ca_cert}\n" +
":ssl_client_cert: #{temp_client_cert}\n") do |fetcher|
fetcher.fetch_path("https://localhost:#{ssl_server.config[:Port]}/yaml")
end
end
def test_do_not_allow_invalid_client_cert_auth_connection
skip 'openssl is missing' unless defined?(OpenSSL::SSL)
ssl_server = self.class.start_ssl_server({
:SSLVerifyClient =>
OpenSSL::SSL::VERIFY_PEER|OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT})
temp_ca_cert = File.join(DIR, 'ca_cert.pem')
temp_client_cert = File.join(DIR, 'invalid_client.pem')
with_configured_fetcher(
":ssl_ca_cert: #{temp_ca_cert}\n" +
":ssl_client_cert: #{temp_client_cert}\n") do |fetcher|
assert_raises Gem::RemoteFetcher::FetchError do
fetcher.fetch_path("https://localhost:#{ssl_server.config[:Port]}/yaml")
end
end
end
def test_do_not_allow_insecure_ssl_connection_by_default
ssl_server = self.class.start_ssl_server
with_configured_fetcher do |fetcher|
assert_raises Gem::RemoteFetcher::FetchError do
fetcher.fetch_path("https://localhost:#{ssl_server.config[:Port]}/yaml")
end
end
end
def test_ssl_connection_allow_verify_none
ssl_server = self.class.start_ssl_server
with_configured_fetcher(":ssl_verify_mode: 0") do |fetcher|
fetcher.fetch_path("https://localhost:#{ssl_server.config[:Port]}/yaml")
end
end
def test_do_not_follow_insecure_redirect
ssl_server = self.class.start_ssl_server
temp_ca_cert = File.join(DIR, 'ca_cert.pem'),
with_configured_fetcher(":ssl_ca_cert: #{temp_ca_cert}") do |fetcher|
assert_raises Gem::RemoteFetcher::FetchError do
fetcher.fetch_path("https://localhost:#{ssl_server.config[:Port]}/insecure_redirect?to=#{@server_uri}")
end
end
end
def with_configured_fetcher(config_str = nil, &block)
if config_str
temp_conf = File.join @tempdir, '.gemrc'
File.open temp_conf, 'w' do |fp|
fp.puts config_str
end
Gem.configuration = Gem::ConfigFile.new %W[--config-file #{temp_conf}]
end
fetcher = Gem::RemoteFetcher.new
yield fetcher
ensure
fetcher.close_all
Gem.configuration = nil
end
def assert_error(exception_class=Exception)
got_exception = false
begin
yield
rescue exception_class
got_exception = true
end
assert got_exception, "Expected exception conforming to #{exception_class}"
end
def assert_data_from_server(data)
assert_match(/0\.4\.11/, data, "Data is not from server")
end
def assert_data_from_proxy(data)
assert_match(/0\.4\.2/, data, "Data is not from proxy")
end
class NilLog < WEBrick::Log
def log(level, data) #Do nothing
end
end
class << self
attr_reader :normal_server, :proxy_server
attr_accessor :enable_zip, :enable_yaml
def start_servers
@normal_server ||= start_server(SERVER_DATA)
@proxy_server ||= start_server(PROXY_DATA)
@enable_yaml = true
@enable_zip = false
@ssl_server = nil
@ssl_server_thread = nil
end
def stop_servers
if @normal_server
@normal_server.kill.join
@normal_server = nil
end
if @proxy_server
@proxy_server.kill.join
@proxy_server = nil
end
if @ssl_server
@ssl_server.stop
@ssl_server = nil
end
if @ssl_server_thread
@ssl_server_thread.kill.join
@ssl_server_thread = nil
end
end
def normal_server_port
@normal_server[:server].config[:Port]
end
def proxy_server_port
@proxy_server[:server].config[:Port]
end
DIR = File.expand_path(File.dirname(__FILE__))
def start_ssl_server(config = {})
raise MiniTest::Skip, 'openssl not installed' unless
defined?(OpenSSL::SSL)
null_logger = NilLog.new
server = WEBrick::HTTPServer.new({
:Port => 0,
:Logger => null_logger,
:AccessLog => [],
:SSLEnable => true,
:SSLCACertificateFile => File.join(DIR, 'ca_cert.pem'),
:SSLCertificate => cert('ssl_cert.pem'),
:SSLPrivateKey => key('ssl_key.pem'),
:SSLVerifyClient => nil,
:SSLCertName => nil
}.merge(config))
server.mount_proc("/yaml") { |req, res|
res.body = "--- true\n"
}
server.mount_proc("/insecure_redirect") { |req, res|
res.set_redirect(WEBrick::HTTPStatus::MovedPermanently, req.query['to'])
}
server.ssl_context.tmp_dh_callback = proc { TEST_KEY_DH2048 }
t = Thread.new do
begin
server.start
rescue Exception => ex
abort ex.message
puts "ERROR during server thread: #{ex.message}"
ensure
server.shutdown
end
end
while server.status != :Running
sleep 0.1
unless t.alive?
t.join
raise
end
end
@ssl_server = server
@ssl_server_thread = t
server
end
private
def start_server(data)
null_logger = NilLog.new
s = WEBrick::HTTPServer.new(
:Port => 0,
:DocumentRoot => nil,
:Logger => null_logger,
:AccessLog => null_logger
)
s.mount_proc("/kill") { |req, res| s.shutdown }
s.mount_proc("/yaml") { |req, res|
if req["X-Captain"]
res.body = req["X-Captain"]
elsif @enable_yaml
res.body = data
res['Content-Type'] = 'text/plain'
res['content-length'] = data.size
else
res.status = "404"
res.body = "<h1>NOT FOUND</h1>"
res['Content-Type'] = 'text/html'
end
}
s.mount_proc("/yaml.Z") { |req, res|
if @enable_zip
res.body = Zlib::Deflate.deflate(data)
res['Content-Type'] = 'text/plain'
else
res.status = "404"
res.body = "<h1>NOT FOUND</h1>"
res['Content-Type'] = 'text/html'
end
}
th = Thread.new do
begin
s.start
rescue Exception => ex
abort "ERROR during server thread: #{ex.message}"
ensure
s.shutdown
end
end
th[:server] = s
th
end
def cert(filename)
OpenSSL::X509::Certificate.new(File.read(File.join(DIR, filename)))
end
def key(filename)
OpenSSL::PKey::RSA.new(File.read(File.join(DIR, filename)))
end
end
def test_correct_for_windows_path
path = "/C:/WINDOWS/Temp/gems"
assert_equal "C:/WINDOWS/Temp/gems", @fetcher.correct_for_windows_path(path)
path = "/home/skillet"
assert_equal "/home/skillet", @fetcher.correct_for_windows_path(path)
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/test/test_filter.rb
|
<reponame>arnab0073/idea<filename>.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/test/test_filter.rb
require File.expand_path('setup', File.dirname(__FILE__))
module TestLogging
class TestFilter < Test::Unit::TestCase
include LoggingTestCase
def setup
super
::Logging::init
@lf = ::Logging::Filters::Level.new :debug, :warn
end
def test_level_filter_includes_selected_level
debug_evt = event_for_level(:debug)
warn_evt = event_for_level(:warn)
assert_same debug_evt, @lf.allow(debug_evt), "Debug messages should be allowed"
assert_same warn_evt, @lf.allow(warn_evt), "Warn messages should be allowed"
end
def test_level_filter_excludes_unselected_level
event = event_for_level(:info)
assert_nil @lf.allow(event), "Info messages should be disallowed"
end
def event_for_level(level)
::Logging::LogEvent.new('logger', ::Logging::LEVELS[level.to_s],
'message', false)
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/optparse/test_reqarg.rb
|
<reponame>arnab0073/idea<filename>.rvm/src/ruby-2.3.0/test/optparse/test_reqarg.rb
# frozen_string_literal: false
require_relative 'test_optparse'
module TestOptionParser::ReqArg
class Def1 < TestOptionParser
include ReqArg
def setup
super
@opt.def_option("-xVAL") {|x| @flag = x}
@opt.def_option("--option=VAL") {|x| @flag = x}
@opt.def_option("--regexp=REGEXP", Regexp) {|x| @reopt = x}
@reopt = nil
end
end
class Def2 < TestOptionParser
include ReqArg
def setup
super
@opt.def_option("-x", "--option=VAL") {|x| @flag = x}
end
end
class Def3 < TestOptionParser
include ReqArg
def setup
super
@opt.def_option("--option=VAL", "-x") {|x| @flag = x}
end
end
class Def4 < TestOptionParser
include ReqArg
def setup
super
@opt.def_option("-xVAL", "--option=VAL") {|x| @flag = x}
end
end
def test_short
assert_raise(OptionParser::MissingArgument) {@opt.parse!(%w"-x")}
assert_equal(%w"", no_error {@opt.parse!(%w"-x foo")})
assert_equal("foo", @flag)
assert_equal(%w"", no_error {@opt.parse!(%w"-xbar")})
assert_equal("bar", @flag)
assert_equal(%w"", no_error {@opt.parse!(%w"-x=")})
assert_equal("=", @flag)
end
def test_abbrev
assert_raise(OptionParser::MissingArgument) {@opt.parse!(%w"-o")}
assert_equal(%w"", no_error {@opt.parse!(%w"-o foo")})
assert_equal("foo", @flag)
assert_equal(%w"", no_error {@opt.parse!(%w"-obar")})
assert_equal("bar", @flag)
assert_equal(%w"", no_error {@opt.parse!(%w"-o=")})
assert_equal("=", @flag)
end
def test_long
assert_raise(OptionParser::MissingArgument) {@opt.parse!(%w"--opt")}
assert_equal(%w"", no_error {@opt.parse!(%w"--opt foo")})
assert_equal("foo", @flag)
assert_equal(%w"foo", no_error {@opt.parse!(%w"--opt= foo")})
assert_equal("", @flag)
assert_equal(%w"", no_error {@opt.parse!(%w"--opt=foo")})
assert_equal("foo", @flag)
end
class TestOptionParser::WithPattern < TestOptionParser
def test_pattern
pat = num = nil
@opt.def_option("--pattern=VAL", /(\w+)(?:\s*:\s*(\w+))?/) {|x, y, z| pat = [x, y, z]}
@opt.def_option("-T NUM", /\A[1-4]\z/) {|n| num = n}
no_error {@opt.parse!(%w"--pattern=key:val")}
assert_equal(%w"key:val key val", pat, '[ruby-list:45645]')
no_error {@opt.parse!(%w"-T 4")}
assert_equal("4", num, '[ruby-dev:37514]')
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/test_forwardable.rb
|
<gh_stars>0
# frozen_string_literal: false
require 'test/unit'
require 'forwardable'
class TestForwardable < Test::Unit::TestCase
RECEIVER = BasicObject.new
RETURNED1 = BasicObject.new
RETURNED2 = BasicObject.new
class << RECEIVER
def delegated1
RETURNED1
end
def delegated2
RETURNED2
end
end
def test_def_instance_delegator
%i[def_delegator def_instance_delegator].each do |m|
cls = forwardable_class do
__send__ m, :@receiver, :delegated1
end
assert_same RETURNED1, cls.new.delegated1
end
end
def test_def_instance_delegators
%i[def_delegators def_instance_delegators].each do |m|
cls = forwardable_class do
__send__ m, :@receiver, :delegated1, :delegated2
end
assert_same RETURNED1, cls.new.delegated1
assert_same RETURNED2, cls.new.delegated2
end
end
def test_instance_delegate
%i[delegate instance_delegate].each do |m|
cls = forwardable_class do
__send__ m, delegated1: :@receiver, delegated2: :@receiver
end
assert_same RETURNED1, cls.new.delegated1
assert_same RETURNED2, cls.new.delegated2
cls = forwardable_class do
__send__ m, %i[delegated1 delegated2] => :@receiver
end
assert_same RETURNED1, cls.new.delegated1
assert_same RETURNED2, cls.new.delegated2
end
end
def test_def_single_delegator
%i[def_delegator def_single_delegator].each do |m|
cls = single_forwardable_class do
__send__ m, :@receiver, :delegated1
end
assert_same RETURNED1, cls.delegated1
end
end
def test_def_single_delegators
%i[def_delegators def_single_delegators].each do |m|
cls = single_forwardable_class do
__send__ m, :@receiver, :delegated1, :delegated2
end
assert_same RETURNED1, cls.delegated1
assert_same RETURNED2, cls.delegated2
end
end
def test_single_delegate
%i[delegate single_delegate].each do |m|
cls = single_forwardable_class do
__send__ m, delegated1: :@receiver, delegated2: :@receiver
end
assert_same RETURNED1, cls.delegated1
assert_same RETURNED2, cls.delegated2
cls = single_forwardable_class do
__send__ m, %i[delegated1 delegated2] => :@receiver
end
assert_same RETURNED1, cls.delegated1
assert_same RETURNED2, cls.delegated2
end
end
class Foo
extend Forwardable
def_delegator :bar, :baz
class Exception
end
end
def test_backtrace_adjustment
e = assert_raise(NameError) {
Foo.new.baz
}
assert_not_match(/\/forwardable\.rb/, e.backtrace[0])
end
class Foo2 < BasicObject
extend ::Forwardable
def_delegator :bar, :baz
end
def test_basicobject_subclass
bug11616 = '[ruby-core:71176] [Bug #11616]'
assert_raise_with_message(NameError, /`bar'/, bug11616) {
Foo2.new.baz
}
end
private
def forwardable_class(&block)
Class.new do
extend Forwardable
def initialize
@receiver = RECEIVER
end
class_exec(&block)
end
end
def single_forwardable_class(&block)
Class.new do
extend SingleForwardable
@receiver = RECEIVER
class_exec(&block)
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/-ext-/string/test_enc_associate.rb
|
<filename>.rvm/src/ruby-2.3.0/test/-ext-/string/test_enc_associate.rb
# frozen_string_literal: false
require 'test/unit'
require "-test-/string"
class Test_StrEncAssociate < Test::Unit::TestCase
def test_frozen
s = Bug::String.new("abc")
s.force_encoding(Encoding::US_ASCII)
s.freeze
assert_raise(RuntimeError) {s.associate_encoding!(Encoding::US_ASCII)}
assert_raise(RuntimeError) {s.associate_encoding!(Encoding::UTF_8)}
end
Encoding.list.select(&:dummy?).each do |enc|
enc = enc.name.tr('-', '_')
define_method("test_dummy_encoding_index_#{enc}") do
assert_separately(["-r-test-/string", "-", enc], <<-"end;") #do
enc = Encoding.const_get(ARGV[0])
index = Bug::String.encoding_index(enc)
assert(index < 0xffff, "<%#x> expected but was\n<%#x>" % [index & 0xffff, index])
end;
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/lib/rubygems/commands/which_command.rb
|
<reponame>arnab0073/idea
# frozen_string_literal: false
require 'rubygems/command'
class Gem::Commands::WhichCommand < Gem::Command
def initialize
super 'which', 'Find the location of a library file you can require',
:search_gems_first => false, :show_all => false
add_option '-a', '--[no-]all', 'show all matching files' do |show_all, options|
options[:show_all] = show_all
end
add_option '-g', '--[no-]gems-first',
'search gems before non-gems' do |gems_first, options|
options[:search_gems_first] = gems_first
end
end
def arguments # :nodoc:
"FILE name of file to find"
end
def defaults_str # :nodoc:
"--no-gems-first --no-all"
end
def description # :nodoc:
<<-EOF
The which command is like the shell which command and shows you where
the file you wish to require lives.
You can use the which command to help determine why you are requiring a
version you did not expect or to look at the content of a file you are
requiring to see why it does not behave as you expect.
EOF
end
def execute
found = true
options[:args].each do |arg|
arg = arg.sub(/#{Regexp.union(*Gem.suffixes)}$/, '')
dirs = $LOAD_PATH
spec = Gem::Specification.find_by_path arg
if spec then
if options[:search_gems_first] then
dirs = spec.full_require_paths + $LOAD_PATH
else
dirs = $LOAD_PATH + spec.full_require_paths
end
end
# TODO: this is totally redundant and stupid
paths = find_paths arg, dirs
if paths.empty? then
alert_error "Can't find ruby library file or shared library #{arg}"
found &&= false
else
say paths
end
end
terminate_interaction 1 unless found
end
def find_paths(package_name, dirs)
result = []
dirs.each do |dir|
Gem.suffixes.each do |ext|
full_path = File.join dir, "#{package_name}#{ext}"
if File.exist? full_path and not File.directory? full_path then
result << full_path
return result unless options[:show_all]
end
end
end
result
end
def usage # :nodoc:
"#{program_name} FILE [FILE ...]"
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/blt/tabnotebook.rb
|
#
# tkextlib/blt/tabnotebook.rb
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tkextlib/blt.rb'
require 'tkextlib/blt/tabset.rb'
module Tk::BLT
class Tabnotebook < Tabset
TkCommandNames = ['::blt::tabnotebook'.freeze].freeze
WidgetClassName = 'Tabnotebook'.freeze
WidgetClassNames[WidgetClassName] ||= self
class Tab < Tk::BLT::Tabset::Tab
def self.new(parent, pos=nil, name=nil, keys={})
if pos.kind_of?(Hash)
keys = pos
name = nil
pos = nil
end
if name.kind_of?(Hash)
keys = name
name = nil
end
obj = nil
TabID_TBL.mutex.synchronize{
if name && TabID_TBL[parent.path] && TabID_TBL[parent.path][name]
obj = TabID_TBL[parent.path][name]
if pos
if pos.to_s == 'end'
obj.move_after('end')
else
obj.move_before(pos)
end
end
obj.configure if keys && ! keys.empty?
else
(obj = self.allocate).instance_eval{
initialize(parent, pos, name, keys)
TabID_TBL[@tpath] = {} unless TabID_TBL[@tpath]
TabID_TBL[@tpath][@id] = self
}
end
}
obj
end
def initialize(parent, pos, name, keys)
@t = parent
@tpath = parent.path
if name
@path = @id = name
unless (list(tk_call(@tpath, 'tab', 'names', @id)).empty?)
if pos
idx = tk_call(@tpath, 'index', @id)
if pos.to_s == 'end'
tk_call(@tpath, 'move', idx, 'after', 'end')
else
tk_call(@tpath, 'move', idx, 'before', pos)
end
end
tk_call(@tpath, 'tab', 'configure', @id, keys)
else
fail ArgumentError, "can't find tab \"#{@id}\" in #{@t}"
end
else
pos = 'end' unless pos
@path = @id = tk_call(@tpath, 'insert', pos, keys)
end
end
end
#######################################
def get_tab(index)
if (idx = tk_send_without_enc('id', tagindex(index))).empty?
nil
else
Tk::BLT::Tabset::Tab.id2obj(self, idx)
end
end
alias get_id get_tab
def get_tabobj(index)
if (idx = tk_send_without_enc('id', tagindex(index))).empty?
nil
else
Tk::BLT::Tabnotebook::Tab.new(self, nil, idx)
end
end
alias index_name index
def insert(pos=nil, keys={})
if pos.kind_of?(Hash)
keys = pos
pos = nil
end
pos = 'end' if pos.nil?
Tk::BLT::Tabnotebook::Tab.new(self, nil,
tk_send('insert', tagindex(pos), keys))
end
undef :insert_tabs
undef :tab_pageheight, :tab_pagewidth
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/nori-2.6.0/spec/spec_helper.rb
|
<reponame>arnab0073/idea<filename>.rvm/gems/ruby-2.3.0/gems/nori-2.6.0/spec/spec_helper.rb<gh_stars>100-1000
require "bundler"
Bundler.require :default, :development
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/winrm-1.8.1/spec/winrm_primitives_spec.rb
|
<reponame>arnab0073/idea
# encoding: UTF-8
describe 'winrm client primitives' do
before(:all) do
@winrm = winrm_connection
end
describe 'open and close shell', integration: true do
it 'should #open_shell and #close_shell' do
sid = @winrm.open_shell
expect(sid).to be_a_uid
expect(@winrm.close_shell(sid)).to be true
end
it 'should #run_command and #cleanup_command' do
sid = @winrm.open_shell
cmd_id = @winrm.run_command(sid, 'ipconfig', %w(/all))
expect(sid).to be_a_uid
expect(@winrm.cleanup_command(sid, cmd_id)).to be true
@winrm.close_shell(sid)
end
it 'should #get_command_output' do
sid = @winrm.open_shell
cmd_id = @winrm.run_command(sid, 'ipconfig', %w(/all))
output = @winrm.get_command_output(sid, cmd_id)
expect(output).to have_exit_code 0
expect(output).to have_stdout_match(/.+/)
expect(output).to have_no_stderr
@winrm.cleanup_command(sid, cmd_id)
@winrm.close_shell(sid)
end
it 'should #get_command_output with a block' do
sid = @winrm.open_shell
cmd_id = @winrm.run_command(sid, 'ipconfig', %w(/all))
outvar = ''
@winrm.get_command_output(sid, cmd_id) do |stdout, _stderr|
outvar << stdout
end
expect(outvar).to match(/Windows IP Configuration/)
@winrm.cleanup_command(sid, cmd_id)
@winrm.close_shell(sid)
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/tests/helper.rb
|
ENV['FOG_RC'] = ENV['FOG_RC'] || File.expand_path('../.fog', __FILE__)
ENV['FOG_CREDENTIAL'] = ENV['FOG_CREDENTIAL'] || 'default'
require 'fog'
require 'fog/bin' # for available_providers and registered_providers
Excon.defaults.merge!(:debug_request => true, :debug_response => true)
require File.expand_path(File.join(File.dirname(__FILE__), 'helpers', 'mock_helper'))
# This overrides the default 600 seconds timeout during live test runs
if Fog.mocking?
FOG_TESTING_TIMEOUT = ENV['FOG_TEST_TIMEOUT'] || 2000
Fog.timeout = 2000
Fog::Logger.warning "Setting default fog timeout to #{Fog.timeout} seconds"
# These sets of tests do not behave nicely when running mocked tests
Thread.current[:tags] << '-xenserver'
Thread.current[:tags] << '-joyent'
Thread.current[:tags] << '-dreamhost'
else
FOG_TESTING_TIMEOUT = Fog.timeout
end
def lorem_file
File.open(File.dirname(__FILE__) + '/lorem.txt', 'r')
end
def array_differences(array_a, array_b)
(array_a - array_b) | (array_b - array_a)
end
# check to see which credentials are available and add others to the skipped tags list
all_providers = Fog.registered_providers.map {|provider| provider.downcase}
# Manually remove these providers since they are local applications, not lacking credentials
all_providers = all_providers - ["libvirt", "openvz"]
available_providers = Fog.available_providers.map {|provider| provider.downcase}
unavailable_providers = all_providers - available_providers
if !ENV['PROVIDER'].nil? && unavailable_providers.include?(ENV['PROVIDER'])
Fog::Formatador.display_line("[red]Requested provider #{ENV['PROVIDER']} is not available.[/]" +
"[red]Check if .fog file has correct configuration (see '#{Fog.credentials_path}')[/]")
exit(0)
end
for provider in unavailable_providers
Fog::Formatador.display_line("[yellow]Skipping tests for [bold]#{provider}[/] [yellow]due to lacking credentials (add some to '#{Fog.credentials_path}' to run them)[/]")
end
# mark libvirt tests pending if not setup
begin
require('libvirt')
rescue LoadError
Fog::Formatador.display_line("[yellow]Skipping tests for [bold]libvirt[/] [yellow]due to missing `ruby-libvirt` gem.[/]")
Thread.current[:tags] << '-libvirt'
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/iwidgets/selectiondialog.rb
|
<reponame>arnab0073/idea<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/iwidgets/selectiondialog.rb
#
# tkextlib/iwidgets/selectiondialog.rb
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tkextlib/iwidgets.rb'
module Tk
module Iwidgets
class Selectiondialog < Tk::Iwidgets::Dialog
end
end
end
class Tk::Iwidgets::Selectiondialog
TkCommandNames = ['::iwidgets::selectiondialog'.freeze].freeze
WidgetClassName = 'Selectiondialog'.freeze
WidgetClassNames[WidgetClassName] ||= self
def child_site
window(tk_call(@path, 'childsite'))
end
def clear_items
tk_call(@path, 'clear', 'items')
self
end
def clear_selection
tk_call(@path, 'clear', 'selection')
self
end
def get
tk_call(@path, 'get')
end
def insert_items(idx, *args)
tk_call(@path, 'insert', 'items', idx, *args)
end
def insert_selection(pos, text)
tk_call(@path, 'insert', 'selection', pos, text)
end
def select_item
tk_call(@path, 'selectitem')
self
end
# based on Tk::Listbox ( and TkTextWin )
def curselection
list(tk_send_without_enc('curselection'))
end
def delete(first, last=None)
tk_send_without_enc('delete', first, last)
self
end
def index(idx)
tk_send_without_enc('index', idx).to_i
end
def nearest(y)
tk_send_without_enc('nearest', y).to_i
end
def scan_mark(x, y)
tk_send_without_enc('scan', 'mark', x, y)
self
end
def scan_dragto(x, y)
tk_send_without_enc('scan', 'dragto', x, y)
self
end
def selection_anchor(index)
tk_send_without_enc('selection', 'anchor', index)
self
end
def selection_clear(first, last=None)
tk_send_without_enc('selection', 'clear', first, last)
self
end
def selection_includes(index)
bool(tk_send_without_enc('selection', 'includes', index))
end
def selection_set(first, last=None)
tk_send_without_enc('selection', 'set', first, last)
self
end
def size
tk_send_without_enc('size').to_i
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/lib/weakref.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/lib/weakref.rb
require "delegate"
require 'thread'
# Weak Reference class that allows a referenced object to be
# garbage-collected. A WeakRef may be used exactly like the object it
# references.
#
# Usage:
#
# foo = Object.new
# foo = Object.new
# p foo.to_s # original's class
# foo = WeakRef.new(foo)
# p foo.to_s # should be same class
# ObjectSpace.garbage_collect
# p foo.to_s # should raise exception (recycled)
class WeakRef < Delegator
##
# RefError is raised when a referenced object has been recycled by the
# garbage collector
class RefError < StandardError
end
@@id_map = {} # obj -> [ref,...]
@@id_rev_map = {} # ref -> obj
@@mutex = Mutex.new
@@final = lambda {|id|
@@mutex.synchronize {
rids = @@id_map[id]
if rids
for rid in rids
@@id_rev_map.delete(rid)
end
@@id_map.delete(id)
end
rid = @@id_rev_map[id]
if rid
@@id_rev_map.delete(id)
@@id_map[rid].delete(id)
@@id_map.delete(rid) if @@id_map[rid].empty?
end
}
}
##
# Creates a weak reference to +orig+
def initialize(orig)
@__id = orig.object_id
ObjectSpace.define_finalizer orig, @@final
ObjectSpace.define_finalizer self, @@final
@@mutex.synchronize {
@@id_map[@__id] = [] unless @@id_map[@__id]
}
@@id_map[@__id].push self.object_id
@@id_rev_map[self.object_id] = @__id
super
end
def __getobj__ # :nodoc:
unless @@id_rev_map[self.object_id] == @__id
Kernel::raise RefError, "Invalid Reference - probably recycled", Kernel::caller(2)
end
begin
ObjectSpace._id2ref(@__id)
rescue RangeError
Kernel::raise RefError, "Invalid Reference - probably recycled", Kernel::caller(2)
end
end
def __setobj__(obj) # :nodoc:
end
##
# Returns true if the referenced object is still alive.
def weakref_alive?
@@id_rev_map[self.object_id] == @__id
end
end
if __FILE__ == $0
# require 'thread'
foo = Object.new
p foo.to_s # original's class
foo = WeakRef.new(foo)
p foo.to_s # should be same class
ObjectSpace.garbage_collect
ObjectSpace.garbage_collect
p foo.to_s # should raise exception (recycled)
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/digest/digest_conf.rb
|
# frozen_string_literal: false
def digest_conf(name, hdr = name, funcs = nil, types = nil)
unless with_config("bundled-#{name}")
cc = with_config("common-digest")
if cc == true or /\b#{name}\b/ =~ cc
if File.exist?("#$srcdir/#{name}cc.h") and
have_header("CommonCrypto/CommonDigest.h")
$defs << "-D#{name.upcase}_USE_COMMONDIGEST"
return :commondigest
end
end
dir_config("openssl")
pkg_config("openssl")
require File.expand_path('../../openssl/deprecation', __FILE__)
if have_library("crypto")
funcs ||= name.upcase
funcs = Array(funcs)
types ||= funcs
hdr = "openssl/#{hdr}.h"
if funcs.all? {|func| OpenSSL.check_func("#{func}_Transform", hdr)} &&
types.all? {|type| have_type("#{type}_CTX", hdr)}
$defs << "-D#{name.upcase}_USE_OPENSSL"
return :ossl
end
end
end
$objs << "#{name}.#{$OBJEXT}"
return
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/resolv/test_resource.rb
|
# frozen_string_literal: false
require 'test/unit'
require 'resolv'
class TestResolvResource < Test::Unit::TestCase
def setup
address = "192.168.0.1"
@name1 = Resolv::DNS::Resource::IN::A.new(address)
@name1.instance_variable_set(:@ttl, 100)
@name2 = Resolv::DNS::Resource::IN::A.new(address)
end
def test_equality
bug10857 = '[ruby-core:68128] [Bug #10857]'
assert_equal(@name1, @name2, bug10857)
end
def test_hash
bug10857 = '[ruby-core:68128] [Bug #10857]'
assert_equal(@name1.hash, @name2.hash, bug10857)
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tk/scrollbox.rb
|
<reponame>arnab0073/idea
#
# tk/scrollbox.rb - Tk Listbox with Scrollbar
# as an example of Composite Widget
# by <NAME> <<EMAIL>>
#
require 'tk'
require 'tk/listbox'
class TkScrollbox<Tk::Listbox
include TkComposite
def initialize_composite(keys=nil)
#list = Tk::Listbox.new(@frame)
# -> use current TkListbox class
list = TkListbox.new(@frame)
#scroll = Tk::Scrollbar.new(@frame)
# -> use current TkScrollbar class
scroll = TkScrollbar.new(@frame)
@path = list.path
=begin
list.configure 'yscroll', scroll.path+" set"
list.pack 'side'=>'left','fill'=>'both','expand'=>'yes'
scroll.configure 'command', list.path+" yview"
scroll.pack 'side'=>'right','fill'=>'y'
=end
list.yscrollbar(scroll)
list.pack('side'=>'left','fill'=>'both','expand'=>'yes')
scroll.pack('side'=>'right','fill'=>'y')
delegate('DEFAULT', list)
delegate('foreground', list)
delegate('background', list, scroll)
delegate('borderwidth', @frame)
delegate('relief', @frame)
configure keys if keys
end
private :initialize_composite
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/-test-/bug-3571/extconf.rb
|
# frozen_string_literal: false
create_makefile("-test-/bug-3571/bug")
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/mini_portile2-2.1.0/test/test_cook.rb
|
<reponame>arnab0073/idea
require File.expand_path('../helper', __FILE__)
class TestCook < TestCase
attr_accessor :assets_path, :tar_path, :recipe
def with_custom_git_dir(dir)
old = ENV['GIT_DIR']
ENV['GIT_DIR'] = dir
yield
ensure
ENV['GIT_DIR'] = old
end
def before_all
super
@assets_path = File.expand_path("../assets", __FILE__)
@tar_path = File.expand_path("../../tmp/test mini portile-1.0.0.tar.gz", __FILE__)
# remove any previous test files
FileUtils.rm_rf("tmp")
create_tar(@tar_path, @assets_path)
start_webrick(File.dirname(@tar_path))
@recipe = MiniPortile.new("test mini portile", "1.0.0").tap do |recipe|
recipe.files << "http://localhost:#{HTTP_PORT}/#{ERB::Util.url_encode(File.basename(@tar_path))}"
recipe.patch_files << File.join(@assets_path, "patch 1.diff")
recipe.configure_options << "--option=\"path with 'space'\""
git_dir = File.join(@assets_path, "git")
with_custom_git_dir(git_dir) do
recipe.cook
end
end
end
def after_all
super
stop_webrick
# leave test files for inspection
end
def test_download
download = "ports/archives/test%20mini%20portile-1.0.0.tar.gz"
assert File.exist?(download), download
end
def test_untar
configure = File.join(work_dir, "configure")
assert File.exist?(configure), configure
assert_match( /^#!\/bin\/sh/, IO.read(configure) )
end
def test_patch
patch1 = File.join(work_dir, "patch 1.txt")
assert File.exist?(patch1), patch1
assert_match( /^\tchange 1/, IO.read(patch1) )
end
def test_configure
txt = File.join(work_dir, "configure.txt")
assert File.exist?(txt), txt
opts = recipe.configure_options + ["--prefix=#{recipe.path}"]
assert_equal( opts.inspect, IO.read(txt).chomp )
end
def test_compile
txt = File.join(work_dir, "compile.txt")
assert File.exist?(txt), txt
assert_equal( ["all"].inspect, IO.read(txt).chomp )
end
def test_install
txt = File.join(work_dir, "install.txt")
assert File.exist?(txt), txt
assert_equal( ["install"].inspect, IO.read(txt).chomp )
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/puma-1.6.3/lib/puma/app/status.rb
|
<filename>.rvm/gems/ruby-2.3.0/gems/puma-1.6.3/lib/puma/app/status.rb
module Puma
module App
class Status
def initialize(server, cli)
@server = server
@cli = cli
@auth_token = nil
end
OK_STATUS = '{ "status": "ok" }'.freeze
attr_accessor :auth_token
def authenticate(env)
return true unless @auth_token
env['QUERY_STRING'].to_s.split(/&;/).include?("token=#{@auth_token}")
end
def call(env)
unless authenticate(env)
return rack_response(403, 'Invalid auth token', 'text/plain')
end
case env['PATH_INFO']
when "/stop"
@server.stop
return rack_response(200, OK_STATUS)
when "/halt"
@server.halt
return rack_response(200, OK_STATUS)
when "/restart"
if @cli and @cli.restart_on_stop!
@server.begin_restart
return rack_response(200, OK_STATUS)
else
return rack_response(200, '{ "status": "not configured" }')
end
when "/stats"
b = @server.backlog
r = @server.running
return rack_response(200, %Q!{ "backlog": #{b}, "running": #{r} }!)
end
rack_response 404, "Unsupported action", 'text/plain'
end
private
def rack_response(status, body, content_type='application/json')
[status, { 'Content-Type' => content_type, 'Content-Length' => body.bytesize.to_s }, [body]]
end
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/specifications/little-plugger-1.1.4.gemspec
|
<gh_stars>0
# -*- encoding: utf-8 -*-
# stub: little-plugger 1.1.4 ruby lib
Gem::Specification.new do |s|
s.name = "little-plugger"
s.version = "1.1.4"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib"]
s.authors = ["<NAME>"]
s.date = "2015-08-28"
s.description = "LittlePlugger is a module that provides Gem based plugin management.\nBy extending your own class or module with LittlePlugger you can easily\nmanage the loading and initializing of plugins provided by other gems."
s.email = "<EMAIL>"
s.extra_rdoc_files = ["History.txt", "README.rdoc"]
s.files = ["History.txt", "README.rdoc"]
s.homepage = "http://gemcutter.org/gems/little-plugger"
s.rdoc_options = ["--main", "README.rdoc"]
s.rubyforge_project = "little-plugger"
s.rubygems_version = "2.5.1"
s.summary = "LittlePlugger is a module that provides Gem based plugin management."
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_development_dependency(%q<rspec>, ["~> 3.3"])
else
s.add_dependency(%q<rspec>, ["~> 3.3"])
end
else
s.add_dependency(%q<rspec>, ["~> 3.3"])
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/tests/google/models/compute/region_tests.rb
|
<reponame>arnab0073/idea<gh_stars>1-10
Shindo.tests("Fog::Compute[:google] | region model", ['google']) do
@regions = Fog::Compute[:google].regions
tests('success') do
tests('#up').succeeds do
region = @regions.get @regions.all.first.name
region.up?
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/multi_json-1.12.1/lib/multi_json/adapter.rb
|
<filename>.rvm/gems/ruby-2.3.0/gems/multi_json-1.12.1/lib/multi_json/adapter.rb<gh_stars>1-10
require 'singleton'
require 'multi_json/options'
module MultiJson
class Adapter
extend Options
include Singleton
class << self
def defaults(action, value)
metaclass = class << self; self; end
metaclass.instance_eval do
define_method("default_#{action}_options") { value }
end
end
def load(string, options = {})
fail self::ParseError if blank?(string)
string = string.read if string.respond_to?(:read)
instance.load(string, cached_load_options(options))
end
def dump(object, options = {})
instance.dump(object, cached_dump_options(options))
end
private
def blank?(input)
input.nil? || /\A\s*\z/ === input
rescue ArgumentError # invalid byte sequence in UTF-8
false
end
def cached_dump_options(options)
OptionsCache.fetch(:dump, options) do
dump_options(options).merge(MultiJson.dump_options(options)).merge!(options)
end
end
def cached_load_options(options)
OptionsCache.fetch(:load, options) do
load_options(options).merge(MultiJson.load_options(options)).merge!(options)
end
end
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/net-ssh-2.6.8/test/authentication/test_session.rb
|
<reponame>arnab0073/idea
require 'common'
require 'net/ssh/authentication/session'
module Authentication
class TestSession < Test::Unit::TestCase
include Net::SSH::Transport::Constants
include Net::SSH::Authentication::Constants
def test_constructor_should_set_defaults
assert_equal %w(none publickey hostbased password keyboard-interactive), session.auth_methods
assert_equal session.auth_methods, session.allowed_auth_methods
end
def test_authenticate_should_continue_if_method_disallowed
transport.expect do |t, packet|
assert_equal SERVICE_REQUEST, packet.type
assert_equal "ssh-userauth", packet.read_string
t.return(SERVICE_ACCEPT)
end
Net::SSH::Authentication::Methods::Publickey.any_instance.expects(:authenticate).with("next service", "username", "password").raises(Net::SSH::Authentication::DisallowedMethod)
Net::SSH::Authentication::Methods::Hostbased.any_instance.expects(:authenticate).with("next service", "username", "password").returns(true)
Net::SSH::Authentication::Methods::None.any_instance.expects(:authenticate).with("next service", "username", "password").returns(false)
assert session.authenticate("next service", "username", "password")
end
def test_authenticate_should_raise_error_if_service_request_fails
transport.expect do |t, packet|
assert_equal SERVICE_REQUEST, packet.type
assert_equal "ssh-userauth", packet.read_string
t.return(255)
end
assert_raises(Net::SSH::Exception) { session.authenticate("next service", "username", "password") }
end
def test_authenticate_should_return_false_if_all_auth_methods_fail
transport.expect do |t, packet|
assert_equal SERVICE_REQUEST, packet.type
assert_equal "ssh-userauth", packet.read_string
t.return(SERVICE_ACCEPT)
end
Net::SSH::Authentication::Methods::Publickey.any_instance.expects(:authenticate).with("next service", "username", "password").returns(false)
Net::SSH::Authentication::Methods::Hostbased.any_instance.expects(:authenticate).with("next service", "username", "password").returns(false)
Net::SSH::Authentication::Methods::Password.any_instance.expects(:authenticate).with("next service", "username", "password").returns(false)
Net::SSH::Authentication::Methods::KeyboardInteractive.any_instance.expects(:authenticate).with("next service", "username", "password").returns(false)
Net::SSH::Authentication::Methods::None.any_instance.expects(:authenticate).with("next service", "username", "password").returns(false)
assert_equal false, session.authenticate("next service", "username", "password")
end
def test_next_message_should_silently_handle_USERAUTH_BANNER_packets
transport.return(USERAUTH_BANNER, :string, "Howdy, folks!")
transport.return(SERVICE_ACCEPT)
assert_equal SERVICE_ACCEPT, session.next_message.type
end
def test_next_message_should_understand_USERAUTH_FAILURE
transport.return(USERAUTH_FAILURE, :string, "a,b,c", :bool, false)
packet = session.next_message
assert_equal USERAUTH_FAILURE, packet.type
assert_equal %w(a b c), session.allowed_auth_methods
end
(60..79).each do |type|
define_method("test_next_message_should_return_packets_of_type_#{type}") do
transport.return(type)
assert_equal type, session.next_message.type
end
end
def test_next_message_should_understand_USERAUTH_SUCCESS
transport.return(USERAUTH_SUCCESS)
assert !transport.hints[:authenticated]
assert_equal USERAUTH_SUCCESS, session.next_message.type
assert transport.hints[:authenticated]
end
def test_next_message_should_raise_error_on_unrecognized_packet_types
transport.return(1)
assert_raises(Net::SSH::Exception) { session.next_message }
end
def test_expect_message_should_raise_exception_if_next_packet_is_not_expected_type
transport.return(SERVICE_ACCEPT)
assert_raises(Net::SSH::Exception) { session.expect_message(USERAUTH_BANNER) }
end
def test_expect_message_should_return_packet_if_next_packet_is_expected_type
transport.return(SERVICE_ACCEPT)
assert_equal SERVICE_ACCEPT, session.expect_message(SERVICE_ACCEPT).type
end
private
def session(options={})
@session ||= Net::SSH::Authentication::Session.new(transport(options), options)
end
def transport(options={})
@transport ||= MockTransport.new(options)
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/puma-1.6.3/lib/puma/rack_patch.rb
|
require 'rack/commonlogger'
module Rack
# Patch CommonLogger to use after_reply.
#
# Simply request this file and CommonLogger will be a bit more
# efficient.
class CommonLogger
remove_method :call
def call(env)
began_at = Time.now
status, header, body = @app.call(env)
header = Utils::HeaderHash.new(header)
if ary = env['rack.after_reply']
ary << lambda { log(env, status, header, began_at) }
else
body = BodyProxy.new(body) { log(env, status, header, began_at) }
end
[status, header, body]
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/systemu-2.6.5/samples/d.rb
|
#
# the cwd can be supplied
#
require 'systemu'
require 'tmpdir'
pwd = %q( ruby -e" STDERR.puts Dir.pwd " )
status = systemu pwd, 2=>(stderr=''), :cwd=>Dir.tmpdir
puts stderr
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/knife-windows-1.4.1/spec/spec_helper.rb
|
<reponame>arnab0073/idea
# Author:: <NAME> (<<EMAIL>>)
# Copyright:: Copyright (c) 2012-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.
#
def windows?
!!(RUBY_PLATFORM =~ /mswin|mingw|windows/)
end
require_relative '../lib/chef/knife/core/windows_bootstrap_context'
require_relative '../lib/chef/knife/bootstrap_windows_winrm'
require_relative '../lib/chef/knife/bootstrap_windows_ssh'
require_relative '../lib/chef/knife/wsman_test'
if windows?
require 'ruby-wmi'
end
def windows2012?
is_win2k12 = false
if windows?
this_operating_system = WMI::Win32_OperatingSystem.find(:first)
os_version = this_operating_system.send('Version')
# The operating system version is a string in the following form
# that can be split into components based on the '.' delimiter:
# MajorVersionNumber.MinorVersionNumber.BuildNumber
os_version_components = os_version.split('.')
if os_version_components.length < 2
raise 'WMI returned a Windows version from Win32_OperatingSystem.Version ' +
'with an unexpected format. The Windows version could not be determined.'
end
# Windows 6.2 is Windows Server 2012, so test the major and
# minor version components
is_win2k12 = os_version_components[0] == '6' && os_version_components[1] == '2'
end
is_win2k12
end
def chef_gte_12?
Chef::VERSION.split('.').first.to_i >= 12
end
def chef_gte_12_5?
Chef::VERSION.split('.')[0..1].join('.').to_f >= 12.5
end
def chef_gte_12_6?
Chef::VERSION.split('.')[0..1].join('.').to_f >= 12.6
end
def chef_lt_12?
Chef::VERSION.split('.').first.to_i < 12
end
def chef_eq_11?
Chef::VERSION.split('.').first.to_i == 11
end
def sample_data(file_name)
file = File.expand_path(File.dirname("spec/assets/*"))+"/#{file_name}"
File.read(file)
end
RSpec.configure do |config|
config.run_all_when_everything_filtered = true
config.filter_run :focus => true
config.filter_run_excluding :windows_only => true unless windows?
config.filter_run_excluding :windows_2012_only => true unless windows2012?
config.filter_run_excluding :chef_gte_12_only => true unless chef_gte_12?
config.filter_run_excluding :chef_gte_12_5_only => true unless chef_gte_12_5?
config.filter_run_excluding :chef_gte_12_6_only => true unless chef_gte_12_6?
config.filter_run_excluding :chef_lt_12_5_only => true if chef_gte_12_5?
config.filter_run_excluding :chef_lt_12_only => true unless chef_lt_12?
config.filter_run_excluding :if_chef_11 => true if chef_eq_11?
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/fcntl/extconf.rb
|
<reponame>arnab0073/idea
# frozen_string_literal: false
require 'mkmf'
create_makefile('fcntl')
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/test/net/imap/test_imap_response_parser.rb
|
require "net/imap"
require "test/unit"
class IMAPResponseParserTest < Test::Unit::TestCase
def setup
@do_not_reverse_lookup = Socket.do_not_reverse_lookup
Socket.do_not_reverse_lookup = true
if Net::IMAP.respond_to?(:max_flag_count)
@max_flag_count = Net::IMAP.max_flag_count
Net::IMAP.max_flag_count = 3
end
end
def teardown
Socket.do_not_reverse_lookup = @do_not_reverse_lookup
if Net::IMAP.respond_to?(:max_flag_count)
Net::IMAP.max_flag_count = @max_flag_count
end
end
def test_flag_list_safe
parser = Net::IMAP::ResponseParser.new
response = lambda {
$SAFE = 1
parser.parse(<<EOF.gsub(/\n/, "\r\n").taint)
* LIST (\\HasChildren) "." "INBOX"
EOF
}.call
assert_equal [:Haschildren], response.data.attr
end
def test_flag_list_too_many_flags
parser = Net::IMAP::ResponseParser.new
assert_nothing_raised do
3.times do |i|
parser.parse(<<EOF.gsub(/\n/, "\r\n").taint)
* LIST (\\Foo#{i}) "." "INBOX"
EOF
end
end
assert_raise(Net::IMAP::FlagCountError) do
parser.parse(<<EOF.gsub(/\n/, "\r\n").taint)
* LIST (\\Foo3) "." "INBOX"
EOF
end
end
def test_flag_list_many_same_flags
parser = Net::IMAP::ResponseParser.new
assert_nothing_raised do
100.times do
parser.parse(<<EOF.gsub(/\n/, "\r\n").taint)
* LIST (\\Foo) "." "INBOX"
EOF
end
end
end
def test_flag_xlist_inbox
parser = Net::IMAP::ResponseParser.new
response = parser.parse(<<EOF.gsub(/\n/, "\r\n").taint)
* XLIST (\\Inbox) "." "INBOX"
EOF
assert_equal [:Inbox], response.data.attr
end
def test_resp_text_code
parser = Net::IMAP::ResponseParser.new
response = parser.parse(<<EOF.gsub(/\n/, "\r\n").taint)
* OK [CLOSED] Previous mailbox closed.
EOF
assert_equal "CLOSED", response.data.code.name
end
def test_search_response
parser = Net::IMAP::ResponseParser.new
response = parser.parse(<<EOF.gsub(/\n/, "\r\n").taint)
* SEARCH
EOF
assert_equal [], response.data
response = parser.parse(<<EOF.gsub(/\n/, "\r\n").taint)
* SEARCH 1
EOF
assert_equal [1], response.data
response = parser.parse(<<EOF.gsub(/\n/, "\r\n").taint)
* SEARCH 1 2 3
EOF
assert_equal [1, 2, 3], response.data
end
def test_search_response_of_yahoo
parser = Net::IMAP::ResponseParser.new
response = parser.parse(<<EOF.gsub(/\n/, "\r\n").taint)
* SEARCH 1
EOF
assert_equal [1], response.data
response = parser.parse(<<EOF.gsub(/\n/, "\r\n").taint)
* SEARCH 1 2 3
EOF
assert_equal [1, 2, 3], response.data
end
def test_msg_att_extra_space
parser = Net::IMAP::ResponseParser.new
response = parser.parse(<<EOF.gsub(/\n/, "\r\n").taint)
* 1 FETCH (UID 92285)
EOF
assert_equal 92285, response.data.attr["UID"]
response = parser.parse(<<EOF.gsub(/\n/, "\r\n").taint)
* 1 FETCH (UID 92285 )
EOF
assert_equal 92285, response.data.attr["UID"]
response = parser.parse(<<EOF.gsub(/\n/, "\r\n").taint)
* 1 FETCH (UID 92285 )
EOF
end
# [Bug #8281]
def test_acl
parser = Net::IMAP::ResponseParser.new
response = parser.parse(<<EOF.gsub(/\n/, "\r\n").taint)
* ACL "INBOX/share" "<EMAIL>" lrswickxteda
EOF
assert_equal("ACL", response.name)
assert_equal(1, response.data.length)
assert_equal("INBOX/share", response.data[0].mailbox)
assert_equal("<EMAIL>",
response.data[0].user)
assert_equal("lrswickxteda", response.data[0].rights)
end
# [Bug #8415]
def test_capability
parser = Net::IMAP::ResponseParser.new
response = parser.parse("* CAPABILITY st11p00mm-iscream009 1Q49 XAPPLEPUSHSERVICE IMAP4 IMAP4rev1 SASL-IR AUTH=ATOKEN AUTH=PLAIN\r\n")
assert_equal("CAPABILITY", response.name)
assert_equal("AUTH=PLAIN", response.data.last)
response = parser.parse("* CAPABILITY st11p00mm-iscream009 1Q49 XAPPLEPUSHSERVICE IMAP4 IMAP4rev1 SASL-IR AUTH=ATOKEN AUTH=PLAIN \r\n")
assert_equal("CAPABILITY", response.name)
assert_equal("AUTH=PLAIN", response.data.last)
end
end
|
arnab0073/idea
|
.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/rubygems-bundler-1.4.4/rubygems-bundler.gemspec
|
<reponame>arnab0073/idea
#!/usr/bin/env ruby
# -*- encoding: utf-8 -*-
Kernel.load File.expand_path("../lib/rubygems-bundler/version.rb", __FILE__)
Gem::Specification.new do |s|
s.name = "rubygems-bundler"
s.version = RubygemsBundler::VERSION
s.authors = ["<NAME>", "<NAME>"]
s.email = ["<EMAIL>", "<EMAIL>"]
s.homepage = "http://mpapis.github.com/rubygems-bundler"
s.summary = %q{Stop using bundle exec}
s.description = %q{Stop using bundle exec. Integrate Rubygems and Bundler. Make rubygems generate bundler aware executable wrappers.}
s.license = 'Apache-2.0'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.add_dependency "bundler-unload", ">=1.0.2"
s.add_dependency "executable-hooks", ">=1.3.2"
s.add_development_dependency "tf"
#s.add_development_dependency "smf-gem"
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/ruby/test_continuation.rb
|
<filename>.rvm/src/ruby-2.3.0/test/ruby/test_continuation.rb
# frozen_string_literal: false
require 'test/unit'
EnvUtil.suppress_warning {require 'continuation'}
require 'fiber'
class TestContinuation < Test::Unit::TestCase
def test_create
assert_equal(:ok, callcc{:ok})
assert_equal(:ok, callcc{|c| c.call :ok})
end
def test_call
assert_equal(:ok, callcc{|c| c.call :ok})
ary = []
ary << callcc{|c|
@cont = c
:a
}
@cont.call :b if ary.length < 3
assert_equal([:a, :b, :b], ary)
end
def test_check_localvars
vv = 0
@v = 0
@ary = []
[1, 2, 3].each{|i|
callcc {|k| @k = k}
@v += 1
vv += 1
}
@ary << [vv, @v]
@k.call if @v < 10
assert_equal((3..10).map{|e| [e, e]}, @ary)
end
def test_error
cont = callcc{|c| c}
assert_raise(RuntimeError){
Thread.new{cont.call}.join
}
assert_raise(LocalJumpError){
callcc
}
assert_raise(RuntimeError){
c = nil
Fiber.new do
callcc {|c2| c = c2 }
end.resume
c.call
}
end
def test_ary_flatten
assert_normal_exit %q{
require 'continuation'
n = 0
o = Object.new
def o.to_ary() callcc {|k| $k = k; [1,2,3]} end
[10,20,o,30,o,40].flatten.inspect
n += 1
$k.call if n < 100
}, '[ruby-dev:34798]'
end
def test_marshal_dump
assert_normal_exit %q{
require 'continuation'
n = 0
o = Object.new
def o.marshal_dump() callcc {|k| $k = k }; "fofof" end
a = [1,2,3,o,4,5,6]
Marshal.dump(a).inspect
n += 1
$k.call if n < 100
}, '[ruby-dev:34802]'
end
def tracing_with_set_trace_func
orig_thread = Thread.current
cont = nil
func = lambda do |*args|
if orig_thread == Thread.current
if cont
@memo += 1
c = cont
cont = nil
c.call(nil)
end
end
end
cont = callcc { |cc| cc }
if cont
set_trace_func(func)
else
set_trace_func(nil)
end
end
def test_tracing_with_set_trace_func
@memo = 0
tracing_with_set_trace_func
tracing_with_set_trace_func
tracing_with_set_trace_func
assert_equal 3, @memo
end
def tracing_with_thread_set_trace_func
cont = nil
func = lambda do |*args|
if cont
@memo += 1
c = cont
cont = nil
c.call(nil)
end
end
cont = callcc { |cc| cc }
if cont
Thread.current.set_trace_func(func)
else
Thread.current.set_trace_func(nil)
end
end
def test_tracing_with_thread_set_trace_func
@memo = 0
tracing_with_thread_set_trace_func
tracing_with_thread_set_trace_func
tracing_with_thread_set_trace_func
assert_equal 3, @memo
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/lib/rdoc/i18n.rb
|
<gh_stars>10-100
# frozen_string_literal: false
##
# This module provides i18n realated features.
module RDoc::I18n
autoload :Locale, 'rdoc/i18n/locale'
autoload :Text, 'rdoc/i18n/text'
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/tcllib/canvas_zoom.rb
|
<reponame>arnab0073/idea<gh_stars>1-10
#
# tkextlib/tcllib/canvas.rb
# by <NAME> (<EMAIL>)
#
# * Part of tcllib extension
# *
#
require 'tk'
require 'tkextlib/tcllib.rb'
# TkPackage.require('widget::canvas_zoom', '0.1')
TkPackage.require('widget::canvas_zoom')
module Tk::Tcllib
module Widget
class Canvas_Zoom < Canvas
TkCommandNames = ['::widget::canvas_zoom'.freeze].freeze
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/tool/gem-unpack.rb
|
<reponame>arnab0073/idea<filename>.rvm/src/ruby-2.3.0/tool/gem-unpack.rb
require 'rubygems'
require 'rubygems/package'
def Gem.unpack(file, dir = nil)
policy = Gem::Security::LowSecurity
(policy = policy.dup).ui = Gem::SilentUI.new
pkg = Gem::Package.new(file)
pkg.security_policy = policy
spec = pkg.spec
target = spec.full_name
target = File.join(dir, target) if dir
pkg.extract_files target
spec_file = File.join(target, "#{spec.name}.gemspec")
open(spec_file, 'wb') do |f|
f.print spec.to_ruby
end
puts "Unpacked #{file}"
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/iwidgets/sample/dateentry.rb
|
#!/usr/bin/env ruby
require 'tk'
require 'tkextlib/iwidgets'
Tk::Iwidgets::Dateentry.new.pack
Tk.mainloop
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/fileutils/test_verbose.rb
|
<reponame>arnab0073/idea
# frozen_string_literal: false
# $Id: test_verbose.rb 53141 2015-12-16 05:07:31Z naruse $
require 'test/unit'
require 'fileutils'
require_relative 'visibility_tests'
class TestFileUtilsVerbose < Test::Unit::TestCase
include FileUtils::Verbose
include TestFileUtils::Visibility
def setup
super
@fu_module = FileUtils::Verbose
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/rest-client-1.6.9/lib/restclient/version.rb
|
module RestClient
VERSION = '1.6.9' unless defined?(self::VERSION)
def self.version
VERSION
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/version.rb
|
#
# release date of tkextlib
#
module Tk
Tkextlib_RELEASE_DATE = '2010-02-01'.freeze
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/rubyntlm-0.6.0/spec/support/shared/examples/net/ntlm/int_shared.rb
|
shared_examples_for 'an integer field' do |values|
subject do
described_class.new({
:value => values[:default],
:active => true
})
end
context '#serialize' do
it 'should serialize properly with an integer value' do
expect(subject.serialize).to eq(values[:default_hex])
end
it 'should raise an Exception for a String' do
subject.value = 'A'
expect {subject.serialize}.to raise_error
end
it 'should raise an Exception for Nil' do
subject.value = nil
expect {subject.serialize}.to raise_error
end
end
context '#parse' do
it "should parse a raw #{values[:bits].to_s}-bit integer from a string" do
expect(subject.parse(values[:alt_hex])).to eq(values[:size])
expect(subject.value).to eq(values[:alt])
end
it "should use an offset to find the #{values[:bits].to_s}-bit integer in the string" do
expect(subject.parse("Value:#{values[:alt_hex]}",6)).to eq(values[:size])
expect(subject.value).to eq(values[:alt])
end
it 'should return 0 and not change the value if the string is not big enough' do
expect(subject.parse(values[:small])).to eq(0)
expect(subject.value).to eq(values[:default])
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/tool/instruction.rb
|
<filename>.rvm/src/ruby-2.3.0/tool/instruction.rb
#!./miniruby
# -*- coding: us-ascii -*-
#
#
require 'erb'
$:.unshift(File.dirname(__FILE__))
require 'vpath'
class RubyVM
class Instruction
def initialize name, opes, pops, rets, comm, body, tvars, sp_inc,
orig = self, defopes = [], type = nil,
nsc = [], psc = [[], []]
@name = name
@opes = opes # [[type, name], ...]
@pops = pops # [[type, name], ...]
@rets = rets # [[type, name], ...]
@comm = comm # {:c => category, :e => en desc, :j => ja desc}
@body = body # '...'
@orig = orig
@defopes = defopes
@type = type
@tvars = tvars
@nextsc = nsc
@pushsc = psc
@sc = []
@unifs = []
@optimized = []
@is_sc = false
@sp_inc = sp_inc
end
def add_sc sci
@sc << sci
sci.set_sc
end
attr_reader :name, :opes, :pops, :rets
attr_reader :body, :comm
attr_reader :nextsc, :pushsc
attr_reader :orig, :defopes, :type
attr_reader :sc
attr_reader :unifs, :optimized
attr_reader :is_sc
attr_reader :tvars
attr_reader :sp_inc
def set_sc
@is_sc = true
end
def add_unif insns
@unifs << insns
end
def add_optimized insn
@optimized << insn
end
def sp_increase_c_expr
if(pops.any?{|t, v| v == '...'} ||
rets.any?{|t, v| v == '...'})
# user definition
raise "no sp increase definition" if @sp_inc.nil?
ret = "int inc = 0;\n"
@opes.each_with_index{|(t, v), i|
if (t == 'rb_num_t' && ((re = /\b#{v}\b/n) =~ @sp_inc)) ||
(@defopes.any?{|t, val| re =~ val})
ret << " int #{v} = FIX2INT(opes[#{i}]);\n"
elsif (t == 'CALL_INFO' && ((re = /\b#{v}\b/n) =~ @sp_inc))
ret << " CALL_INFO #{v} = (CALL_INFO)(opes[#{i}]);\n"
end
}
@defopes.each_with_index{|((t, var), val), i|
if t == 'rb_num_t' && val != '*' && /\b#{var}\b/ =~ @sp_inc
ret << " #{t} #{var} = #{val};\n"
end
}
ret << " #{@sp_inc};\n"
ret << " return depth + inc;"
ret
else
"return depth + #{rets.size - pops.size};"
end
end
def inspect
"#<Instruction:#{@name}>"
end
end
class InstructionsLoader
def initialize opts = {}
@insns = []
@insn_map = {}
@vpath = opts[:VPATH] || File
@use_const = opts[:use_const]
@verbose = opts[:verbose]
@destdir = opts[:destdir]
(@vm_opts = load_vm_opts).each {|k, v|
@vm_opts[k] = opts[k] if opts.key?(k)
}
load_insns_def opts[:"insns.def"] || 'insns.def'
load_opt_operand_def opts[:"opope.def"] || 'defs/opt_operand.def'
load_insn_unification_def opts[:"unif.def"] || 'defs/opt_insn_unif.def'
make_stackcaching_insns if vm_opt?('STACK_CACHING')
end
attr_reader :vpath
attr_reader :destdir
%w[use_const verbose].each do |attr|
attr_reader attr
alias_method "#{attr}?", attr
remove_method attr
end
def [](s)
@insn_map[s.to_s]
end
def each
@insns.each{|insn|
yield insn
}
end
def size
@insns.size
end
###
private
def vm_opt? name
@vm_opts[name]
end
def load_vm_opts file = nil
file ||= 'vm_opts.h'
opts = {}
vpath.open(file) do |f|
f.grep(/^\#define\s+OPT_([A-Z_]+)\s+(\d+)/) do
opts[$1] = !$2.to_i.zero?
end
end
opts
end
SKIP_COMMENT_PATTERN = Regexp.compile(Regexp.escape('/** ##skip'))
include Enumerable
def add_insn insn
@insns << insn
@insn_map[insn.name] = insn
end
def make_insn name, opes, pops, rets, comm, body, sp_inc
add_insn Instruction.new(name, opes, pops, rets, comm, body, [], sp_inc)
end
# str -> [[type, var], ...]
def parse_vars line
raise unless /\((.*?)\)/ =~ line
vars = $1.split(',')
vars.map!{|v|
if /\s*(\S+)\s+(\S+)\s*/ =~ v
type = $1
var = $2
elsif /\s*\.\.\.\s*/ =~ v
type = var = '...'
else
raise
end
[type, var]
}
vars
end
def parse_comment comm
c = 'others'
j = ''
e = ''
comm.each_line{|line|
case line
when /@c (.+)/
c = $1
when /@e (.+)/
e = $1
when /@e\s*$/
e = ''
when /@j (.+)$/
j = $1
when /@j\s*$/
j = ''
end
}
{ :c => c,
:e => e,
:j => j,
}
end
def load_insns_def file
body = insn = opes = pops = rets = nil
comment = ''
vpath.open(file) {|f|
f.instance_variable_set(:@line_no, 0)
class << f
def line_no
@line_no
end
def gets
@line_no += 1
super
end
end
while line = f.gets
line.chomp!
case line
when SKIP_COMMENT_PATTERN
while line = f.gets.chomp
if /\s+\*\/$/ =~ line
break
end
end
# collect instruction comment
when /^\/\*\*$/
while line = f.gets
if /\s+\*\/\s*$/ =~ line
break
else
comment << line
end
end
# start instruction body
when /^DEFINE_INSN$/
insn = f.gets.chomp
opes = parse_vars(f.gets.chomp)
pops = parse_vars(f.gets.chomp).reverse
rets_str = f.gets.chomp
rets = parse_vars(rets_str).reverse
comment = parse_comment(comment)
insn_in = true
body = ''
sp_inc = rets_str[%r"//\s*(.+)", 1]
raise unless /^\{$/ =~ f.gets.chomp
line_no = f.line_no
# end instruction body
when /^\}/
if insn_in
body.instance_variable_set(:@line_no, line_no)
body.instance_variable_set(:@file, f.path)
insn = make_insn(insn, opes, pops, rets, comment, body, sp_inc)
insn_in = false
comment = ''
end
else
if insn_in
body << line + "\n"
end
end
end
}
end
## opt op
def load_opt_operand_def file
vpath.foreach(file) {|line|
line = line.gsub(/\#.*/, '').strip
next if line.length == 0
break if /__END__/ =~ line
/(\S+)\s+(.+)/ =~ line
insn = $1
opts = $2
add_opt_operand insn, opts.split(/,/).map{|e| e.strip}
} if file
end
def label_escape label
label.gsub(/\(/, '_O_').
gsub(/\)/, '_C_').
gsub(/\*/, '_WC_')
end
def add_opt_operand insn_name, opts
insn = @insn_map[insn_name]
opes = insn.opes
if opes.size != opts.size
raise "operand size mismatch for #{insn.name} (opes: #{opes.size}, opts: #{opts.size})"
end
ninsn = insn.name + '_OP_' + opts.map{|e| label_escape(e)}.join('_')
nopes = []
defv = []
opts.each_with_index{|e, i|
if e == '*'
nopes << opes[i]
end
defv << [opes[i], e]
}
make_insn_operand_optimized(insn, ninsn, nopes, defv)
end
def make_insn_operand_optimized orig_insn, name, opes, defopes
comm = orig_insn.comm.dup
comm[:c] = 'optimize'
add_insn insn = Instruction.new(
name, opes, orig_insn.pops, orig_insn.rets, comm,
orig_insn.body, orig_insn.tvars, orig_insn.sp_inc,
orig_insn, defopes)
orig_insn.add_optimized insn
end
## insn unif
def load_insn_unification_def file
vpath.foreach(file) {|line|
line = line.gsub(/\#.*/, '').strip
next if line.length == 0
break if /__END__/ =~ line
make_unified_insns line.split.map{|e|
raise "unknown insn: #{e}" unless @insn_map[e]
@insn_map[e]
}
} if file
end
def all_combination sets
ret = sets.shift.map{|e| [e]}
sets.each{|set|
prev = ret
ret = []
prev.each{|ary|
set.each{|e|
eary = ary.dup
eary << e
ret << eary
}
}
}
ret
end
def make_unified_insns insns
if vm_opt?('UNIFY_ALL_COMBINATION')
insn_sets = insns.map{|insn|
[insn] + insn.optimized
}
all_combination(insn_sets).each{|insns_set|
make_unified_insn_each insns_set
}
else
make_unified_insn_each insns
end
end
def mk_private_val vals, i, redef
vals.dup.map{|v|
# v[0] : type
# v[1] : var name
v = v.dup
if v[0] != '...'
redef[v[1]] = v[0]
v[1] = "#{v[1]}_#{i}"
end
v
}
end
def mk_private_val2 vals, i, redef
vals.dup.map{|v|
# v[0][0] : type
# v[0][1] : var name
# v[1] : default val
pv = v.dup
v = pv[0] = pv[0].dup
if v[0] != '...'
redef[v[1]] = v[0]
v[1] = "#{v[1]}_#{i}"
end
pv
}
end
def make_unified_insn_each insns
names = []
opes = []
pops = []
rets = []
comm = {
:c => 'optimize',
:e => 'unified insn',
:j => 'unified insn',
}
body = ''
passed = []
tvars = []
defopes = []
sp_inc = ''
insns.each_with_index{|insn, i|
names << insn.name
redef_vars = {}
e_opes = mk_private_val(insn.opes, i, redef_vars)
e_pops = mk_private_val(insn.pops, i, redef_vars)
e_rets = mk_private_val(insn.rets, i, redef_vars)
# ToDo: fix it
e_defs = mk_private_val2(insn.defopes, i, redef_vars)
passed_vars = []
while pvar = e_pops.pop
rvar = rets.pop
if rvar
raise "unsupported unif insn: #{insns.inspect}" if rvar[0] == '...'
passed_vars << [pvar, rvar]
tvars << rvar
else
e_pops.push pvar
break
end
end
opes.concat e_opes
pops.concat e_pops
rets.concat e_rets
defopes.concat e_defs
sp_inc += "#{insn.sp_inc}"
body += "{ /* unif: #{i} */\n" +
passed_vars.map{|rpvars|
pv = rpvars[0]
rv = rpvars[1]
"#define #{pv[1]} #{rv[1]}"
}.join("\n") +
"\n" +
redef_vars.map{|v, type|
"#define #{v} #{v}_#{i}"
}.join("\n") + "\n" +
insn.body +
passed_vars.map{|rpvars|
"#undef #{rpvars[0][1]}"
}.join("\n") +
"\n" +
redef_vars.keys.map{|v|
"#undef #{v}"
}.join("\n") +
"\n}\n"
}
tvars_ary = []
tvars.each{|tvar|
unless opes.any?{|var|
var[1] == tvar[1]
} || defopes.any?{|pvar|
pvar[0][1] == tvar[1]
}
tvars_ary << tvar
end
}
add_insn insn = Instruction.new("UNIFIED_" + names.join('_'),
opes, pops, rets.reverse, comm, body,
tvars_ary, sp_inc)
insn.defopes.replace defopes
insns[0].add_unif [insn, insns]
end
## sc
SPECIAL_INSN_FOR_SC_AFTER = {
/\Asend/ => [:a],
/\Aend/ => [:a],
/\Ayield/ => [:a],
/\Aclassdef/ => [:a],
/\Amoduledef/ => [:a],
}
FROM_SC = [[], [:a], [:b], [:a, :b], [:b, :a]]
def make_stackcaching_insns
pops = rets = nil
@insns.dup.each{|insn|
opops = insn.pops
orets = insn.rets
oopes = insn.opes
ocomm = insn.comm
oname = insn.name
after = SPECIAL_INSN_FOR_SC_AFTER.find {|k, v| k =~ oname}
insns = []
FROM_SC.each{|from|
name, pops, rets, pushs1, pushs2, nextsc =
*calc_stack(insn, from, after, opops, orets)
make_insn_sc(insn, name, oopes, pops, rets, [pushs1, pushs2], nextsc)
}
}
end
def make_insn_sc orig_insn, name, opes, pops, rets, pushs, nextsc
comm = orig_insn.comm.dup
comm[:c] = 'optimize(sc)'
scinsn = Instruction.new(
name, opes, pops, rets, comm,
orig_insn.body, orig_insn.tvars, orig_insn.sp_inc,
orig_insn, orig_insn.defopes, :sc, nextsc, pushs)
add_insn scinsn
orig_insn.add_sc scinsn
end
def self.complement_name st
"#{st[0] ? st[0] : 'x'}#{st[1] ? st[1] : 'x'}"
end
def add_stack_value st
len = st.length
if len == 0
st[0] = :a
[nil, :a]
elsif len == 1
if st[0] == :a
st[1] = :b
else
st[1] = :a
end
[nil, st[1]]
else
st[0], st[1] = st[1], st[0]
[st[1], st[1]]
end
end
def calc_stack insn, ofrom, oafter, opops, orets
from = ofrom.dup
pops = opops.dup
rets = orets.dup
rest_scr = ofrom.dup
pushs_before = []
pushs= []
pops.each_with_index{|e, i|
if e[0] == '...'
pushs_before = from
from = []
end
r = from.pop
break unless r
pops[i] = pops[i].dup << r
}
if oafter
from = oafter
from.each_with_index{|r, i|
rets[i] = rets[i].dup << r if rets[i]
}
else
rets = rets.reverse
rets.each_with_index{|e, i|
break if e[0] == '...'
pushed, r = add_stack_value from
rets[i] = rets[i].dup << r
if pushed
if rest_scr.pop
pushs << pushed
end
if i - 2 >= 0
rets[i-2].pop
end
end
}
end
if false #|| insn.name =~ /test3/
p ofrom
p pops
p rets
p pushs_before
p pushs
p from
exit
end
ret = ["#{insn.name}_SC_#{InstructionsLoader.complement_name(ofrom)}_#{complement_name(from)}",
pops, rets, pushs_before, pushs, from]
end
end
class SourceCodeGenerator
def initialize insns
@insns = insns
end
attr_reader :insns
def generate
raise "should not reach here"
end
def vpath
@insns.vpath
end
def verbose?
@insns.verbose?
end
def use_const?
@insns.use_const?
end
def build_string
@lines = []
yield
@lines.join("\n")
end
EMPTY_STRING = ''.freeze
def commit str = EMPTY_STRING
@lines << str
end
def comment str
@lines << str if verbose?
end
def output_path(fn)
d = @insns.destdir
fn = File.join(d, fn) if d
fn
end
end
###################################################################
# vm.inc
class VmBodyGenerator < SourceCodeGenerator
# vm.inc
def generate
vm_body = ''
@insns.each{|insn|
vm_body << "\n"
vm_body << make_insn_def(insn)
}
src = vpath.read('template/vm.inc.tmpl')
ERB.new(src).result(binding)
end
def generate_from_insnname insnname
make_insn_def @insns[insnname.to_s]
end
#######
private
def make_header_prepare_stack insn
comment " /* prepare stack status */"
push_ba = insn.pushsc
raise "unsupport" if push_ba[0].size > 0 && push_ba[1].size > 0
n = 0
push_ba.each {|pushs| n += pushs.length}
commit " CHECK_VM_STACK_OVERFLOW_FOR_INSN(REG_CFP, #{n});" if n > 0
push_ba.each{|pushs|
pushs.each{|r|
commit " PUSH(SCREG(#{r}));"
}
}
end
def make_header_operands insn
comment " /* declare and get from iseq */"
vars = insn.opes
n = 0
ops = []
vars.each_with_index{|(type, var), i|
if type == '...'
break
end
# skip make operands when body has no reference to this operand
# TODO: really needed?
re = /\b#{var}\b/n
if re =~ insn.body or re =~ insn.sp_inc or insn.rets.any?{|t, v| re =~ v} or re =~ 'ic' or re =~ 'ci' or re =~ 'cc'
ops << " #{type} #{var} = (#{type})GET_OPERAND(#{i+1});"
end
n += 1
}
@opn = n
# reverse or not?
# ops.join
commit ops.reverse
end
def make_header_default_operands insn
vars = insn.defopes
vars.each{|e|
next if e[1] == '*'
if use_const?
commit " const #{e[0][0]} #{e[0][1]} = #{e[1]};"
else
commit " #define #{e[0][1]} #{e[1]}"
end
}
end
def make_footer_default_operands insn
comment " /* declare and initialize default opes */"
if use_const?
commit
else
vars = insn.defopes
vars.each{|e|
next if e[1] == '*'
commit "#undef #{e[0][1]}"
}
end
end
def make_header_stack_pops insn
comment " /* declare and pop from stack */"
n = 0
pops = []
vars = insn.pops
vars.each_with_index{|iter, i|
type, var, r = *iter
if type == '...'
break
end
if r
pops << " #{type} #{var} = SCREG(#{r});"
else
pops << " #{type} #{var} = TOPN(#{n});"
n += 1
end
}
@popn = n
# reverse or not?
commit pops.reverse
end
def make_header_temporary_vars insn
comment " /* declare temporary vars */"
insn.tvars.each{|var|
commit " #{var[0]} #{var[1]};"
}
end
def make_header_stack_val insn
comment "/* declare stack push val */"
vars = insn.opes + insn.pops + insn.defopes.map{|e| e[0]}
insn.rets.each{|var|
if vars.all?{|e| e[1] != var[1]} && var[1] != '...'
commit " #{var[0]} #{var[1]};"
end
}
end
def make_header_analysis insn
commit " COLLECT_USAGE_INSN(BIN(#{insn.name}));"
insn.opes.each_with_index{|op, i|
commit " COLLECT_USAGE_OPERAND(BIN(#{insn.name}), #{i}, #{op[1]});"
}
end
def make_header_pc insn
commit " ADD_PC(1+#{@opn});"
commit " PREFETCH(GET_PC());"
end
def make_header_popn insn
comment " /* management */"
commit " POPN(#{@popn});" if @popn > 0
end
def make_header_debug insn
comment " /* for debug */"
commit " DEBUG_ENTER_INSN(\"#{insn.name}\");"
end
def make_header_defines insn
commit " #define CURRENT_INSN_#{insn.name} 1"
commit " #define INSN_IS_SC() #{insn.sc ? 0 : 1}"
commit " #define INSN_LABEL(lab) LABEL_#{insn.name}_##lab"
commit " #define LABEL_IS_SC(lab) LABEL_##lab##_###{insn.sc.size == 0 ? 't' : 'f'}"
end
def each_footer_stack_val insn
insn.rets.reverse_each{|v|
break if v[1] == '...'
yield v
}
end
def make_footer_stack_val insn
comment " /* push stack val */"
n = 0
each_footer_stack_val(insn){|v|
n += 1 unless v[2]
}
commit " CHECK_VM_STACK_OVERFLOW_FOR_INSN(REG_CFP, #{n});" if n > 0
each_footer_stack_val(insn){|v|
if v[2]
commit " SCREG(#{v[2]}) = #{v[1]};"
else
commit " PUSH(#{v[1]});"
end
}
end
def make_footer_undefs insn
commit "#undef CURRENT_INSN_#{insn.name}"
commit "#undef INSN_IS_SC"
commit "#undef INSN_LABEL"
commit "#undef LABEL_IS_SC"
end
def make_header insn
commit "INSN_ENTRY(#{insn.name}){"
make_header_prepare_stack insn
commit "{"
make_header_stack_val insn
make_header_default_operands insn
make_header_operands insn
make_header_stack_pops insn
make_header_temporary_vars insn
#
make_header_debug insn
make_header_pc insn
make_header_popn insn
make_header_defines insn
make_header_analysis insn
commit "{"
end
def make_footer insn
make_footer_stack_val insn
make_footer_default_operands insn
make_footer_undefs insn
commit " END_INSN(#{insn.name});}}}"
end
def make_insn_def insn
build_string do
make_header insn
if line = insn.body.instance_variable_get(:@line_no)
file = insn.body.instance_variable_get(:@file)
commit "#line #{line+1} \"#{file}\""
commit insn.body
commit '#line __CURRENT_LINE__ "__CURRENT_FILE__"'
else
insn.body
end
make_footer(insn)
end
end
end
###################################################################
# vmtc.inc
class VmTCIncGenerator < SourceCodeGenerator
def generate
insns_table = build_string do
@insns.each{|insn|
commit " LABEL_PTR(#{insn.name}),"
}
end
insn_end_table = build_string do
@insns.each{|insn|
commit " ELABEL_PTR(#{insn.name}),\n"
}
end
ERB.new(vpath.read('template/vmtc.inc.tmpl')).result(binding)
end
end
###################################################################
# insns_info.inc
class InsnsInfoIncGenerator < SourceCodeGenerator
def generate
insns_info_inc
end
###
private
def op2typesig op
case op
when /^OFFSET/
"TS_OFFSET"
when /^rb_num_t/
"TS_NUM"
when /^lindex_t/
"TS_LINDEX"
when /^VALUE/
"TS_VALUE"
when /^ID/
"TS_ID"
when /GENTRY/
"TS_GENTRY"
when /^IC/
"TS_IC"
when /^CALL_INFO/
"TS_CALLINFO"
when /^CALL_CACHE/
"TS_CALLCACHE"
when /^\.\.\./
"TS_VARIABLE"
when /^CDHASH/
"TS_CDHASH"
when /^ISEQ/
"TS_ISEQ"
when /rb_insn_func_t/
"TS_FUNCPTR"
else
raise "unknown op type: #{op}"
end
end
TYPE_CHARS = {
'TS_OFFSET' => 'O',
'TS_NUM' => 'N',
'TS_LINDEX' => 'L',
'TS_VALUE' => 'V',
'TS_ID' => 'I',
'TS_GENTRY' => 'G',
'TS_IC' => 'K',
'TS_CALLINFO' => 'C',
'TS_CALLCACHE' => 'E',
'TS_CDHASH' => 'H',
'TS_ISEQ' => 'S',
'TS_VARIABLE' => '.',
'TS_FUNCPTR' => 'F',
}
# insns_info.inc
def insns_info_inc
# insn_type_chars
insn_type_chars = TYPE_CHARS.map{|t, c|
"#define #{t} '#{c}'"
}.join("\n")
# insn_names
insn_names = ''
@insns.each{|insn|
insn_names << " \"#{insn.name}\",\n"
}
# operands info
operands_info = ''
operands_num_info = ''
@insns.each{|insn|
opes = insn.opes
operands_info << ' '
ot = opes.map{|type, var|
TYPE_CHARS.fetch(op2typesig(type))
}
operands_info << "\"#{ot.join}\"" << ",\n"
num = opes.size + 1
operands_num_info << " #{num},\n"
}
# stack num
stack_num_info = ''
@insns.each{|insn|
num = insn.rets.size
stack_num_info << " #{num},\n"
}
# stack increase
stack_increase = ''
@insns.each{|insn|
stack_increase << <<-EOS
case BIN(#{insn.name}):{
#{insn.sp_increase_c_expr}
}
EOS
}
ERB.new(vpath.read('template/insns_info.inc.tmpl')).result(binding)
end
end
###################################################################
# insns.inc
class InsnsIncGenerator < SourceCodeGenerator
def generate
i=0
insns = build_string do
@insns.each{|insn|
commit " %-30s = %d," % ["BIN(#{insn.name})", i]
i+=1
}
end
ERB.new(vpath.read('template/insns.inc.tmpl')).result(binding)
end
end
###################################################################
# minsns.inc
class MInsnsIncGenerator < SourceCodeGenerator
def generate
i=0
defs = build_string do
@insns.each{|insn|
commit " rb_define_const(mYarvInsns, %-30s, INT2FIX(%d));" %
["\"I#{insn.name}\"", i]
i+=1
}
end
ERB.new(vpath.read('template/minsns.inc.tmpl')).result(binding)
end
end
###################################################################
# optinsn.inc
class OptInsnIncGenerator < SourceCodeGenerator
def generate
optinsn_inc
end
###
private
def val_as_type op
type = op[0][0]
val = op[1]
case type
when /^long/, /^rb_num_t/, /^lindex_t/
"INT2FIX(#{val})"
when /^VALUE/
val
when /^ID/
"INT2FIX(#{val})"
when /^ISEQ/, /^rb_insn_func_t/
val
when /GENTRY/
raise
when /^\.\.\./
raise
else
raise "type: #{type}"
end
end
# optinsn.inc
def optinsn_inc
rule = ''
opt_insns_map = Hash.new{|h, k| h[k] = []}
@insns.each{|insn|
next if insn.defopes.size == 0
next if insn.type == :sc
next if /^UNIFIED/ =~ insn.name.to_s
originsn = insn.orig
opt_insns_map[originsn] << insn
}
rule = build_string do
opt_insns_map.each{|originsn, optinsns|
commit "case BIN(#{originsn.name}):"
optinsns.sort_by{|opti|
opti.defopes.find_all{|e| e[1] == '*'}.size
}.each{|opti|
commit " if("
i = 0
commit " " + opti.defopes.map{|opinfo|
i += 1
next if opinfo[1] == '*'
"insnobj->operands[#{i-1}] == #{val_as_type(opinfo)}"
}.compact.join('&& ')
commit " ){"
idx = 0
n = 0
opti.defopes.each{|opinfo|
if opinfo[1] == '*'
if idx != n
commit " insnobj->operands[#{idx}] = insnobj->operands[#{n}];"
end
idx += 1
else
# skip
end
n += 1
}
commit " insnobj->insn_id = BIN(#{opti.name});"
commit " insnobj->operand_size = #{idx};"
commit " break;\n }\n"
}
commit " break;";
}
end
ERB.new(vpath.read('template/optinsn.inc.tmpl')).result(binding)
end
end
###################################################################
# optunifs.inc
class OptUnifsIncGenerator < SourceCodeGenerator
def generate
unif_insns_each = ''
unif_insns = ''
unif_insns_data = []
insns = @insns.find_all{|insn| !insn.is_sc}
insns.each{|insn|
size = insn.unifs.size
if size > 0
insn.unifs.sort_by{|unif| -unif[1].size}.each_with_index{|unif, i|
uni_insn, uni_insns = *unif
uni_insns = uni_insns[1..-1]
unif_insns_each << "static const int UNIFIED_#{insn.name}_#{i}[] = {" +
" BIN(#{uni_insn.name}), #{uni_insns.size + 2},\n " +
uni_insns.map{|e| "BIN(#{e.name})"}.join(", ") + "};\n"
}
else
end
if size > 0
unif_insns << "static const int *const UNIFIED_#{insn.name}[] = {(int *)#{size+1},\n"
unif_insns << (0...size).map{|e| " UNIFIED_#{insn.name}_#{e}"}.join(",\n") + "};\n"
unif_insns_data << " UNIFIED_#{insn.name}"
else
unif_insns_data << " 0"
end
}
unif_insns_data = "static const int *const *const unified_insns_data[] = {\n" +
unif_insns_data.join(",\n") + "};\n"
ERB.new(vpath.read('template/optunifs.inc.tmpl')).result(binding)
end
end
###################################################################
# opt_sc.inc
class OptSCIncGenerator < SourceCodeGenerator
def generate
sc_insn_info = []
@insns.each{|insn|
insns = insn.sc
if insns.size > 0
insns = ['SC_ERROR'] + insns.map{|e| " BIN(#{e.name})"}
else
insns = Array.new(6){'SC_ERROR'}
end
sc_insn_info << " {\n#{insns.join(",\n")}}"
}
sc_insn_info = sc_insn_info.join(",\n")
sc_insn_next = @insns.map{|insn|
" SCS_#{InstructionsLoader.complement_name(insn.nextsc).upcase}" +
(verbose? ? " /* #{insn.name} */" : '')
}.join(",\n")
ERB.new(vpath.read('template/opt_sc.inc.tmpl')).result(binding)
end
end
###################################################################
# yasmdata.rb
class YASMDataRbGenerator < SourceCodeGenerator
def generate
insn_id2no = ''
@insns.each_with_index{|insn, i|
insn_id2no << " :#{insn.name} => #{i},\n"
}
ERB.new(vpath.read('template/yasmdata.rb.tmpl')).result(binding)
end
end
###################################################################
# yarvarch.*
class YARVDocGenerator < SourceCodeGenerator
def generate
end
def desc lang
d = ''
i = 0
cat = nil
@insns.each{|insn|
seq = insn.opes.map{|t,v| v}.join(' ')
before = insn.pops.reverse.map{|t,v| v}.join(' ')
after = insn.rets.reverse.map{|t,v| v}.join(' ')
if cat != insn.comm[:c]
d << "** #{insn.comm[:c]}\n\n"
cat = insn.comm[:c]
end
d << "*** #{insn.name}\n"
d << "\n"
d << insn.comm[lang] + "\n\n"
d << ":instruction sequence: 0x%02x #{seq}\n" % i
d << ":stack: #{before} => #{after}\n\n"
i+=1
}
d
end
def desc_ja
d = desc :j
ERB.new(vpath.read('template/yarvarch.ja')).result(binding)
end
def desc_en
d = desc :e
ERB.new(vpath.read('template/yarvarch.en')).result(binding)
end
end
class SourceCodeGenerator
Files = { # codes
'vm.inc' => VmBodyGenerator,
'vmtc.inc' => VmTCIncGenerator,
'insns.inc' => InsnsIncGenerator,
'insns_info.inc' => InsnsInfoIncGenerator,
# 'minsns.inc' => MInsnsIncGenerator,
'optinsn.inc' => OptInsnIncGenerator,
'optunifs.inc' => OptUnifsIncGenerator,
'opt_sc.inc' => OptSCIncGenerator,
'yasmdata.rb' => YASMDataRbGenerator,
}
def generate args = []
args = Files.keys if args.empty?
args.each{|fn|
s = Files[fn].new(@insns).generate
open(output_path(fn), 'w') {|f| f.puts(s)}
}
end
def self.def_options(opt)
opts = {
:"insns.def" => 'insns.def',
:"opope.def" => 'defs/opt_operand.def',
:"unif.def" => 'defs/opt_insn_unif.def',
}
opt.on("-Dname", /\AOPT_(\w+)\z/, "enable VM option") {|s, v|
opts[v] = true
}
opt.on("--enable=name[,name...]", Array,
"enable VM options (without OPT_ prefix)") {|*a|
a.each {|v| opts[v] = true}
}
opt.on("-Uname", /\AOPT_(\w+)\z/, "disable VM option") {|s, v|
opts[v] = false
}
opt.on("--disable=name[,name...]", Array,
"disable VM options (without OPT_ prefix)") {|*a|
a.each {|v| opts[v] = false}
}
opt.on("-i", "--insnsdef=FILE", "--instructions-def",
"instructions definition file") {|n|
opts[:insns_def] = n
}
opt.on("-o", "--opt-operanddef=FILE", "--opt-operand-def",
"vm option: operand definition file") {|n|
opts[:opope_def] = n
}
opt.on("-u", "--opt-insnunifdef=FILE", "--opt-insn-unif-def",
"vm option: instruction unification file") {|n|
opts[:unif_def] = n
}
opt.on("-C", "--[no-]use-const",
"use consts for default operands instead of macros") {|v|
opts[:use_const] = v
}
opt.on("-d", "--destdir", "--output-directory=DIR",
"make output file underneath DIR") {|v|
opts[:destdir] = v
}
opt.on("-V", "--[no-]verbose") {|v|
opts[:verbose] = v
}
vpath = VPath.new
vpath.def_options(opt)
proc {
opts[:VPATH] = vpath
build opts
}
end
def self.build opts, vpath = ['./']
opts[:VPATH] ||= VPath.new(*vpath)
self.new InstructionsLoader.new(opts)
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/iwidgets/hierarchy.rb
|
#
# tkextlib/iwidgets/hierarchy.rb
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tk/text'
require 'tkextlib/iwidgets.rb'
module Tk
module Iwidgets
class Hierarchy < Tk::Iwidgets::Scrolledwidget
end
end
end
class Tk::Iwidgets::Hierarchy
ItemConfCMD = ['tag'.freeze, 'configure'.freeze].freeze
include TkTextTagConfig
TkCommandNames = ['::iwidgets::hierarchy'.freeze].freeze
WidgetClassName = 'Hierarchy'.freeze
WidgetClassNames[WidgetClassName] ||= self
####################################
include Tk::ValidateConfigure
class QueryCommand < TkValidateCommand
class ValidateArgs < TkUtil::CallbackSubst
KEY_TBL = [ [?n, ?s, :node], nil ]
PROC_TBL = [ [?s, TkComm.method(:string) ], nil ]
=begin
# for Ruby m17n :: ?x --> String --> char-code ( getbyte(0) )
KEY_TBL.map!{|inf|
if inf.kind_of?(Array)
inf[0] = inf[0].getbyte(0) if inf[0].kind_of?(String)
inf[1] = inf[1].getbyte(0) if inf[1].kind_of?(String)
end
inf
}
PROC_TBL.map!{|inf|
if inf.kind_of?(Array)
inf[0] = inf[0].getbyte(0) if inf[0].kind_of?(String)
end
inf
}
=end
_setup_subst_table(KEY_TBL, PROC_TBL);
def self.ret_val(val)
val
end
end
def self._config_keys
# array of config-option key (string or symbol)
['querycommand']
end
end
class IndicatorCommand < TkValidateCommand
class ValidateArgs < TkUtil::CallbackSubst
KEY_TBL = [
[ ?n, ?s, :node ],
[ ?s, ?b, :status ],
nil
]
PROC_TBL = [
[ ?s, TkComm.method(:string) ],
[ ?b, TkComm.method(:bool) ],
nil
]
=begin
# for Ruby m17n :: ?x --> String --> char-code ( getbyte(0) )
KEY_TBL.map!{|inf|
if inf.kind_of?(Array)
inf[0] = inf[0].getbyte(0) if inf[0].kind_of?(String)
inf[1] = inf[1].getbyte(0) if inf[1].kind_of?(String)
end
inf
}
PROC_TBL.map!{|inf|
if inf.kind_of?(Array)
inf[0] = inf[0].getbyte(0) if inf[0].kind_of?(String)
end
inf
}
=end
_setup_subst_table(KEY_TBL, PROC_TBL);
def self.ret_val(val)
val
end
end
def self._config_keys
# array of config-option key (string or symbol)
['iconcommand', 'icondblcommand', 'imagedblcommand']
end
end
class IconCommand < TkValidateCommand
class ValidateArgs < TkUtil::CallbackSubst
KEY_TBL = [
[ ?n, ?s, :node ],
[ ?i, ?s, :icon ],
nil
]
PROC_TBL = [ [ ?s, TkComm.method(:string) ], nil ]
=begin
# for Ruby m17n :: ?x --> String --> char-code ( getbyte(0) )
KEY_TBL.map!{|inf|
if inf.kind_of?(Array)
inf[0] = inf[0].getbyte(0) if inf[0].kind_of?(String)
inf[1] = inf[1].getbyte(0) if inf[1].kind_of?(String)
end
inf
}
PROC_TBL.map!{|inf|
if inf.kind_of?(Array)
inf[0] = inf[0].getbyte(0) if inf[0].kind_of?(String)
end
inf
}
=end
_setup_subst_table(KEY_TBL, PROC_TBL);
def self.ret_val(val)
val
end
end
def self._config_keys
# array of config-option key (string or symbol)
['dblclickcommand', 'imagecommand', 'selectcommand']
end
end
def __validation_class_list
super() << QueryCommand << IndicatorCommand << IconCommand
end
Tk::ValidateConfigure.__def_validcmd(binding, QueryCommand)
Tk::ValidateConfigure.__def_validcmd(binding, IndicatorCommand)
Tk::ValidateConfigure.__def_validcmd(binding, IconCommand)
####################################
def __boolval_optkeys
super() << 'alwaysquery' << 'expanded' << 'filter'
end
private :__boolval_optkeys
def __strval_optkeys
super() << 'markbackground' << 'markforeground' << 'textbackground'
end
private :__strval_optkeys
def __font_optkeys
super() << 'textfont'
end
private :__font_optkeys
def clear
tk_call(@path, 'clear')
self
end
def collapse(node)
tk_call(@path, 'collapse')
self
end
def current
tk_call(@path, 'current')
end
def draw(mode=None)
case mode
when None
# do nothing
when 'now', :now
mode = '-now'
when 'eventually', :eventually
mode = '-eventually'
when String, Symbol
mode = mode.to_s
mode = '-' << mode if mode[0] != ?-
end
tk_call(@path, 'draw', mode)
end
def expand(node)
tk_call(@path, 'expand', node)
self
end
def expanded?(node)
bool(tk_call(@path, 'expanded', node))
end
def exp_state
list(tk_call(@path, 'expState'))
end
alias expand_state exp_state
alias expanded_list exp_state
def mark_clear
tk_call(@path, 'mark', 'clear')
self
end
def mark_add(*nodes)
tk_call(@path, 'mark', 'add', *nodes)
self
end
def mark_remove(*nodes)
tk_call(@path, 'mark', 'remove', *nodes)
self
end
def mark_get
list(tk_call(@path, 'mark', 'get'))
end
def refresh(node)
tk_call(@path, 'refresh', node)
self
end
def prune(node)
tk_call(@path, 'prune', node)
self
end
def selection_clear
tk_call(@path, 'selection', 'clear')
self
end
def selection_add(*nodes)
tk_call(@path, 'selection', 'add', *nodes)
self
end
def selection_remove(*nodes)
tk_call(@path, 'selection', 'remove', *nodes)
self
end
def selection_get
list(tk_call(@path, 'selection', 'get'))
end
def toggle(node)
tk_call(@path, 'toggle', node)
self
end
# based on Tk::Text widget
def bbox(index)
list(tk_send_without_enc('bbox', _get_eval_enc_str(index)))
end
def compare(idx1, op, idx2)
bool(tk_send_without_enc('compare', _get_eval_enc_str(idx1),
op, _get_eval_enc_str(idx2)))
end
def debug
bool(tk_send_without_enc('debug'))
end
def debug=(boolean)
tk_send_without_enc('debug', boolean)
#self
boolean
end
def delete(first, last=None)
tk_send_without_enc('delete', first, last)
self
end
def dlineinfo(index)
list(tk_send_without_enc('dlineinfo', _get_eval_enc_str(index)))
end
def get(*index)
_fromUTF8(tk_send_without_enc('get', *index))
end
def index(index)
tk_send_without_enc('index', _get_eval_enc_str(index))
end
def insert(index, chars, *tags)
if tags[0].kind_of? Array
# multiple chars-taglist argument :: str, [tag,...], str, [tag,...], ...
args = [chars]
while tags.size > 0
args << tags.shift.collect{|x|_get_eval_string(x)}.join(' ') # taglist
args << tags.shift if tags.size > 0 # chars
end
super(index, *args)
else
# single chars-taglist argument :: str, tag, tag, ...
if tags.size == 0
super(index, chars)
else
super(index, chars, tags.collect{|x|_get_eval_string(x)}.join(' '))
end
end
end
def scan_mark(x, y)
tk_send_without_enc('scan', 'mark', x, y)
self
end
def scan_dragto(x, y)
tk_send_without_enc('scan', 'dragto', x, y)
self
end
def see(index)
tk_send_without_enc('see', index)
self
end
# based on tk/scrollable.rb
def xview(*index)
if index.size == 0
list(tk_send_without_enc('xview'))
else
tk_send_without_enc('xview', *index)
self
end
end
def xview_moveto(*index)
xview('moveto', *index)
end
def xview_scroll(*index)
xview('scroll', *index)
end
def yview(*index)
if index.size == 0
list(tk_send_without_enc('yview'))
else
tk_send_without_enc('yview', *index)
self
end
end
def yview_moveto(*index)
yview('moveto', *index)
end
def yview_scroll(*index)
yview('scroll', *index)
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/rubyntlm-0.6.0/spec/support/shared/examples/net/ntlm/fieldset_shared.rb
|
shared_examples_for 'a fieldset' do |fields|
subject(:fieldset_class) do
Class.new(described_class)
end
context 'the class' do
it { should respond_to :string }
it { should respond_to :int16LE }
it { should respond_to :int32LE }
it { should respond_to :int64LE }
it { should respond_to :security_buffer }
it { should respond_to :prototypes }
it { should respond_to :names }
it { should respond_to :types }
it { should respond_to :opts }
context 'adding a String Field' do
before(:each) do
fieldset_class.string(:test_string, { :value => 'Test'})
end
it 'should set the prototypes correctly' do
expect(fieldset_class.prototypes).to include([:test_string, Net::NTLM::String, {:value=>"Test"}])
end
it 'should set the names correctly' do
expect(fieldset_class.names).to include(:test_string)
end
it 'should set the types correctly' do
expect(fieldset_class.types).to include(Net::NTLM::String)
end
it 'should set the opts correctly' do
expect(fieldset_class.opts).to include({:value => 'Test'})
end
context 'when creating an instance' do
let(:fieldset_object) do
fieldset_class.new
end
it 'should have the new accessor' do
expect(fieldset_object).to respond_to(:test_string)
end
it 'should have the correct default value' do
expect(fieldset_object.test_string).to eq('Test')
end
end
end
context 'adding a Int16LE Field' do
before(:each) do
fieldset_class.int16LE(:test_int, { :value => 15})
end
it 'should set the prototypes correctly' do
expect(fieldset_class.prototypes).to include([:test_int, Net::NTLM::Int16LE, {:value=>15}])
end
it 'should set the names correctly' do
expect(fieldset_class.names).to include(:test_int)
end
it 'should set the types correctly' do
expect(fieldset_class.types).to include(Net::NTLM::Int16LE)
end
it 'should set the opts correctly' do
expect(fieldset_class.opts).to include({:value => 15})
end
context 'when creating an instance' do
let(:fieldset_object) do
fieldset_class.new
end
it 'should have the new accessor' do
expect(fieldset_object).to respond_to(:test_int)
end
it 'should have the correct default value' do
expect(fieldset_object.test_int).to eq(15)
end
end
end
context 'adding a Int32LE Field' do
before(:each) do
fieldset_class.int32LE(:test_int, { :value => 15})
end
it 'should set the prototypes correctly' do
expect(fieldset_class.prototypes).to include([:test_int, Net::NTLM::Int32LE, {:value=>15}])
end
it 'should set the names correctly' do
expect(fieldset_class.names).to include(:test_int)
end
it 'should set the types correctly' do
expect(fieldset_class.types).to include(Net::NTLM::Int32LE)
end
it 'should set the opts correctly' do
expect(fieldset_class.opts).to include({:value => 15})
end
context 'when creating an instance' do
let(:fieldset_object) do
fieldset_class.new
end
it 'should have the new accessor' do
expect(fieldset_object).to respond_to(:test_int)
end
it 'should have the correct default value' do
expect(fieldset_object.test_int).to eq(15)
end
end
end
context 'adding a Int64LE Field' do
before(:each) do
fieldset_class.int64LE(:test_int, { :value => 15})
end
it 'should set the prototypes correctly' do
expect(fieldset_class.prototypes).to include([:test_int, Net::NTLM::Int64LE, {:value=>15}])
end
it 'should set the names correctly' do
expect(fieldset_class.names).to include(:test_int)
end
it 'should set the types correctly' do
expect(fieldset_class.types).to include(Net::NTLM::Int64LE)
end
it 'should set the opts correctly' do
expect(fieldset_class.opts).to include({:value => 15})
end
context 'when creating an instance' do
let(:fieldset_object) do
fieldset_class.new
end
it 'should have the new accessor' do
expect(fieldset_object).to respond_to(:test_int)
end
it 'should have the correct default value' do
expect(fieldset_object.test_int).to eq(15)
end
end
end
context 'adding a SecurityBuffer Field' do
before(:each) do
fieldset_class.security_buffer(:test_buffer, { :value => 15})
end
it 'should set the prototypes correctly' do
expect(fieldset_class.prototypes).to include([:test_buffer, Net::NTLM::SecurityBuffer, {:value=>15}])
end
it 'should set the names correctly' do
expect(fieldset_class.names).to include(:test_buffer)
end
it 'should set the types correctly' do
expect(fieldset_class.types).to include(Net::NTLM::SecurityBuffer)
end
it 'should set the opts correctly' do
expect(fieldset_class.opts).to include({:value => 15})
end
context 'when creating an instance' do
let(:fieldset_object) do
fieldset_class.new
end
it 'should have the new accessor' do
expect(fieldset_object).to respond_to :test_buffer
end
it 'should have the correct default value' do
expect(fieldset_object.test_buffer).to eq(15)
end
end
end
end
context 'an instance' do
subject(:fieldset_object) do
# FieldSet Base Class and Message Base Class
# have no fields by default and thus cannot be initialized
# currently. Clumsy workaround for now.
if described_class.names.empty?
described_class.string(:test_string, { :value => 'Test', :active => true, :size => 4})
end
described_class.new
end
it { should respond_to :serialize }
it { should respond_to :parse }
it { should respond_to :size }
it { should respond_to :enable }
it { should respond_to :disable }
context 'fields' do
fields.each do |field|
it { should respond_to field[:name] }
context "#{field[:name]}" do
it "should be a #{field[:class].to_s}" do
expect(fieldset_object[field[:name]].class).to eq(field[:class])
end
it "should have a default value of #{field[:value]}" do
expect(fieldset_object[field[:name]].value).to eq(field[:value])
end
it "should have active set to #{field[:active]}" do
expect(fieldset_object[field[:name]].active).to eq(field[:active])
end
end
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/cmd_res_test.rb
|
require 'tk'
TkOptionDB.readfile(File.expand_path('cmd_resource',
File.dirname(__FILE__)))
f = TkFrame.new(:class=>'BtnFrame').pack
b = TkButton.new(:parent=>f, :widgetname=>'hello').pack
cmd1 = TkOptionDB.new_proc_class(b, [:show_msg, :bye_msg], 3)
cmd2 = TkOptionDB.new_proc_class(:ZZZ, [:show_msg, :bye_msg], 3, false, cmd1)
cmd3 = TkOptionDB.new_proc_class(:ZZZ, [:show_msg, :bye_msg], 3, false, b)
cmd4 = TkOptionDB.new_proc_class(:BTN_CMD, [:show_msg, :bye_msg], 3){
def self.__check_proc_string__(str)
"{|arg| print [arg, $SAFE].inspect, ': '; Proc.new#{str}.call(arg)}"
end
}
cmd1.show_msg('cmd1')
cmd2.show_msg('cmd2')
cmd3.show_msg('cmd3')
cmd4.show_msg('cmd4')
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/benchmark/bm_io_select3.rb
|
# IO.select performance. a lot of fd
ios = []
nr = 100
max = Process.getrlimit(Process::RLIMIT_NOFILE)[0]
puts "max fd: #{max} (results not apparent with <= 1024 max fd)"
(max - 10).times do
r, w = IO.pipe
r.close
ios.push w
end
nr.times do
IO.select nil, ios
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/lib/logging/layouts.rb
|
module Logging
module Layouts; end
require libpath('logging/layouts/basic')
require libpath('logging/layouts/parseable')
require libpath('logging/layouts/pattern')
end # Logging
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/iwidgets/labeledwidget.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/iwidgets/labeledwidget.rb
#
# tkextlib/iwidgets/labeledwidget.rb
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tkextlib/iwidgets.rb'
module Tk
module Iwidgets
class Labeledwidget < Tk::Itk::Widget
end
end
end
class Tk::Iwidgets::Labeledwidget
extend TkCore
TkCommandNames = ['::iwidgets::labeledwidget'.freeze].freeze
WidgetClassName = 'Labeledwidget'.freeze
WidgetClassNames[WidgetClassName] ||= self
def __strval_optkeys
super() << 'labeltext'
end
private :__strval_optkeys
def __tkvariable_optkeys
super() << 'labelvariable'
end
private :__tkvariable_optkeys
def __font_optkeys
super() << 'labelfont'
end
private :__font_optkeys
def self.alignlabels(*wins)
tk_call('::iwidgets::Labeledwidget::alignlabels', *wins)
end
def child_site
window(tk_call(@path, 'childsite'))
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/test_observer.rb
|
# frozen_string_literal: false
require 'test/unit'
require 'observer'
class TestObserver < Test::Unit::TestCase
class TestObservable
include Observable
def notify(*args)
changed
notify_observers(*args)
end
end
class TestWatcher
def initialize(observable)
@notifications = []
observable.add_observer(self)
end
attr_reader :notifications
def update(*args)
@notifications << args
end
end
def test_observers
observable = TestObservable.new
assert_equal(0, observable.count_observers)
watcher1 = TestWatcher.new(observable)
assert_equal(1, observable.count_observers)
observable.notify("test", 123)
watcher2 = TestWatcher.new(observable)
assert_equal(2, observable.count_observers)
observable.notify(42)
assert_equal([["test", 123], [42]], watcher1.notifications)
assert_equal([[42]], watcher2.notifications)
observable.delete_observer(watcher1)
assert_equal(1, observable.count_observers)
observable.notify(:cats)
assert_equal([["test", 123], [42]], watcher1.notifications)
assert_equal([[42], [:cats]], watcher2.notifications)
observable.delete_observers
assert_equal(0, observable.count_observers)
observable.notify("nope")
assert_equal([["test", 123], [42]], watcher1.notifications)
assert_equal([[42], [:cats]], watcher2.notifications)
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/gyoku-1.3.1/spec/gyoku/hash_spec.rb
|
require "spec_helper"
describe Gyoku::Hash do
describe ".to_xml" do
describe "returns SOAP request compatible XML" do
it "for a simple Hash" do
expect(to_xml(:some => "user")).to eq("<some>user</some>")
end
it "for a nested Hash" do
expect(to_xml(:some => { :new => "user" })).to eq("<some><new>user</new></some>")
end
context "with key_converter" do
it "expect all keys change" do
expect(to_xml({:some => { :new => "user" }}, {key_converter: :camelcase})).to eq("<Some><New>user</New></Some>")
end
it "and key_to_convert option should change only key" do
hash = {:some => { :new => "user", :age => 20 }}
options = {key_converter: :camelcase, key_to_convert: "some"}
result = "<Some><new>user</new><age>20</age></Some>"
expect(to_xml(hash, options)).to eq(result)
hash = {:some => { :new => "user", :age => 20 }}
options = {key_converter: :camelcase, key_to_convert: "new"}
result = "<some><New>user</New><age>20</age></some>"
expect(to_xml(hash, options)).to eq(result)
end
it "with except option, dont convert this key" do
hash = {:some => { :new => "user", :age => 20 }}
options = {key_converter: :camelcase, except: "some"}
result = "<some><New>user</New><Age>20</Age></some>"
expect(to_xml(hash, options)).to eq(result)
end
end
it "for a Hash with multiple keys" do
expect(to_xml(:all => "users", :before => "whatever")).to include(
"<all>users</all>",
"<before>whatever</before>"
)
end
it "for a Hash containing an Array" do
expect(to_xml(:some => ["user", "gorilla"])).to eq("<some>user</some><some>gorilla</some>")
end
it "for a Hash containing an Array of Hashes" do
expect(to_xml(:some => [{ :new => "user" }, { :old => "gorilla" }])).
to eq("<some><new>user</new></some><some><old>gorilla</old></some>")
end
end
it "converts Hash key Symbols to lowerCamelCase" do
expect(to_xml(:find_or_create => "user")).to eq("<findOrCreate>user</findOrCreate>")
end
it "does not convert Hash key Strings" do
expect(to_xml("find_or_create" => "user")).to eq("<find_or_create>user</find_or_create>")
end
it "converts DateTime objects to xs:dateTime compliant Strings" do
expect(to_xml(:before => DateTime.new(2012, 03, 22, 16, 22, 33))).
to eq("<before>2012-03-22T16:22:33+00:00</before>")
end
it "converts Objects responding to to_datetime to xs:dateTime compliant Strings" do
singleton = Object.new
def singleton.to_datetime
DateTime.new(2012, 03, 22, 16, 22, 33)
end
expect(to_xml(:before => singleton)).to eq("<before>2012-03-22T16:22:33+00:00</before>")
end
it "calls to_s on Strings even if they respond to to_datetime" do
singleton = "gorilla"
def singleton.to_datetime
DateTime.new(2012, 03, 22, 16, 22, 33)
end
expect(to_xml(:name => singleton)).to eq("<name>gorilla</name>")
end
it "properly serializes nil values" do
expect(to_xml(:some => nil)).to eq('<some xsi:nil="true"/>')
end
it "creates self-closing tags for Hash keys ending with a forward slash" do
expect(to_xml("self-closing/" => nil)).to eq('<self-closing/>')
end
it "calls to_s on any other Object" do
[666, true, false].each do |object|
expect(to_xml(:some => object)).to eq("<some>#{object}</some>")
end
end
it "defaults to escape special characters" do
result = to_xml(:some => { :nested => "<tag />" }, :tag => "<tag />")
expect(result).to include("<tag><tag /></tag>")
expect(result).to include("<some><nested><tag /></nested></some>")
end
it "does not escape special characters for keys marked with an exclamation mark" do
result = to_xml(:some => { :nested! => "<tag />" }, :tag! => "<tag />")
expect(result).to include("<tag><tag /></tag>")
expect(result).to include("<some><nested><tag /></nested></some>")
end
it "preserves the order of Hash keys and values specified through :order!" do
hash = { :find_user => { :name => "Lucy", :id => 666, :order! => [:id, :name] } }
result = "<findUser><id>666</id><name>Lucy</name></findUser>"
expect(to_xml(hash)).to eq(result)
hash = { :find_user => { :mname => "in the", :lname => "Sky", :fname => "Lucy", :order! => [:fname, :mname, :lname] } }
result = "<findUser><fname>Lucy</fname><mname>in the</mname><lname>Sky</lname></findUser>"
expect(to_xml(hash)).to eq(result)
end
it "preserves the order of Hash keys and values specified through 'order!' (as a string key)" do
hash = { :find_user => { :name => "Lucy", :id => 666, 'order!' => [:id, :name] } }
result = "<findUser><id>666</id><name>Lucy</name></findUser>"
expect(to_xml(hash)).to eq(result)
hash = { :find_user => { :mname => "in the", :lname => "Sky", :fname => "Lucy", 'order!' => [:fname, :mname, :lname] } }
result = "<findUser><fname>Lucy</fname><mname>in the</mname><lname>Sky</lname></findUser>"
expect(to_xml(hash)).to eq(result)
end
it "uses :order! symbol values for ordering but leaves the string key 'order!' if both are present" do
hash = { :find_user => { :name => "Lucy", :id => 666, 'order!' => 'value', :order! => [:id, :name, 'order!'] } }
result = "<findUser><id>666</id><name>Lucy</name><order>value</order></findUser>"
expect(to_xml(hash)).to eq(result)
end
it "raises if the :order! Array is missing Hash keys" do
hash = { :name => "Lucy", :id => 666, :order! => [:name] }
expect { to_xml(hash) }.to raise_error(ArgumentError, "Missing elements in :order! [:id]")
end
it "raises if the :order! Array contains missing Hash keys" do
hash = { :by_name => { :first_name => "Lucy", :last_name => "Sky", :order! => [:first_name, :middle_name, :last_name] } }
expect { to_xml(hash) }.to raise_error(ArgumentError, "Spurious elements in :order! [:middle_name]")
end
it "adds attributes to Hash keys specified through :attributes!" do
hash = { :find_user => { :person => "Lucy", :attributes! => { :person => { :id => 666 } } } }
result = '<findUser><person id="666">Lucy</person></findUser>'
expect(to_xml(hash)).to eq(result)
hash = { :find_user => { :person => "Lucy", :attributes! => { :person => { :id => 666, :city => "Hamburg" } } } }
expect(to_xml(hash)).to include('id="666"', 'city="Hamburg"')
end
it "adds attributes to duplicate Hash keys specified through :attributes!" do
hash = { :find_user => { :person => ["Lucy", "Anna"], :attributes! => { :person => { :id => [1, 3] } } } }
result = '<findUser><person id="1">Lucy</person><person id="3">Anna</person></findUser>'
expect(to_xml(hash)).to eq(result)
hash = { :find_user => { :person => ["Lucy", "Anna"], :attributes! => { :person => { :active => "true" } } } }
result = '<findUser><person active="true">Lucy</person><person active="true">Anna</person></findUser>'
expect(to_xml(hash)).to eq(result)
end
it "skips attribute for element without attributes if there are fewer attributes than elements" do
hash = { :find_user => { :person => ["Lucy", "Anna", "Beth"], :attributes! => { :person => { :id => [1, 3] } } } }
result = '<findUser><person id="1">Lucy</person><person id="3">Anna</person><person>Beth</person></findUser>'
expect(to_xml(hash)).to eq(result)
end
it "adds attributes to self-closing tags" do
hash = {
"category/" => "",
:attributes! => { "category/" => { :id => 1 } }
}
expect(to_xml(hash)).to eq('<category id="1"/>')
end
it "recognizes @attribute => value along :attributes!" do
hash = {
"category" => {
:content! => "users",
:@id => 1
}
}
expect(to_xml(hash)).to eq('<category id="1">users</category>')
end
it "recognizes @attribute => value along :attributes! in selfclosed tags" do
hash = {
"category/" => {
:@id => 1
}
}
expect(to_xml(hash)).to eq('<category id="1"/>')
end
it ":@attribute => value takes over :attributes!" do
hash = {
"category/" => {
:@id => 1
},
:attributes! => {
"category/" => {
'id' => 2, # will be ignored
'type' => 'admins'
}
}
}
# attribute order is undefined
expect(['<category id="1" type="admins"/>','<category type="admins" id="1"/>']).to include to_xml(hash)
# with symbols
hash = {
"category/" => {
:@id => 1
},
:attributes! => {
"category/" => {
:id => 2, # will be ignored
:type => 'admins'
}
}
}
expect(['<category id="1" type="admins"/>','<category type="admins" id="1"/>']).to include to_xml(hash)
end
it "recognizes :content! => value as tag content" do
hash = {
"category" => {
:content! => "users"
}
}
expect(to_xml(hash)).to eq("<category>users</category>")
end
it "recognizes :content! => value as tag content with value Fixnum" do
hash = {
"category" => {
:content! => 666
}
}
expect(to_xml(hash)).to eq("<category>666</category>")
end
it "recognizes :content! => value as tag content with value true" do
hash = {
"category" => {
:content! => true
}
}
expect(to_xml(hash)).to eq("<category>true</category>")
end
it "recognizes :content! => value as tag content with value false" do
hash = {
"category" => {
:content! => false
}
}
expect(to_xml(hash)).to eq("<category>false</category>")
end
it "recognizes :content! => value as tag content with value DateTime" do
hash = {
"before" => {
:content! => DateTime.new(2012, 03, 22, 16, 22, 33)
}
}
expect(to_xml(hash)).to eq("<before>2012-03-22T16:22:33+00:00</before>")
end
it "ignores :content! if self-closing mark present" do
hash = {
"category/" => {
:content! => "users"
}
}
expect(to_xml(hash)).to eq("<category/>")
end
it "recognizes array of attributes" do
hash = {
"category" => [{:@name => 'one'}, {:@name => 'two'}]
}
expect(to_xml(hash)).to eq('<category name="one"></category><category name="two"></category>')
# issue #31.
hash = {
:order! => ['foo', 'bar'],
'foo' => { :@foo => 'foo' },
'bar' => { :@bar => 'bar', 'baz' => { } },
}
expect(to_xml(hash)).to eq('<foo foo="foo"></foo><bar bar="bar"><baz></baz></bar>')
end
it "recognizes array of attributes with content in each" do
hash = {
"foo" => [{:@name => "bar", :content! => 'gyoku'}, {:@name => "baz", :@some => "attr", :content! => 'rocks!'}]
}
expect([
'<foo name="bar">gyoku</foo><foo name="baz" some="attr">rocks!</foo>',
'<foo name="bar">gyoku</foo><foo some="attr" name="baz">rocks!</foo>'
]).to include to_xml(hash)
end
it "recognizes array of attributes but ignores content in each if selfclosing" do
hash = {
"foo/" => [{:@name => "bar", :content! => 'gyoku'}, {:@name => "baz", :@some => "attr", :content! => 'rocks!'}]
}
expect([
'<foo name="bar"/><foo name="baz" some="attr"/>',
'<foo name="bar"/><foo some="attr" name="baz"/>'
]).to include to_xml(hash)
end
it "recognizes array of attributes with selfclosing tag" do
hash = {
"category/" => [{:@name => 'one'}, {:@name => 'two'}]
}
expect(to_xml(hash)).to eq('<category name="one"/><category name="two"/>')
end
context "with :element_form_default set to :qualified and a :namespace" do
it "adds the given :namespace to every element" do
hash = { :first => { "first_name" => "Lucy" }, ":second" => { :":first_name" => "Anna" }, "v2:third" => { "v2:firstName" => "Danie" } }
result = to_xml hash, :element_form_default => :qualified, :namespace => :v1
expect(result).to include(
"<v1:first><v1:first_name>Lucy</v1:first_name></v1:first>",
"<second><firstName>Anna</firstName></second>",
"<v2:third><v2:firstName>Danie</v2:firstName></v2:third>"
)
end
it "adds given :namespace to every element in an array" do
hash = { :array => [ :first => "Lucy", :second => "Anna" ]}
result = to_xml hash, :element_form_default => :qualified, :namespace => :v1
expect(result).to include("<v1:array>", "<v1:first>Lucy</v1:first>", "<v1:second>Anna</v1:second>")
end
end
it "does not remove special keys from the original Hash" do
hash = {
:persons => {
:first => "Lucy",
:second => "Anna",
:order! => [:second, :first],
:attributes! => { :first => { :first => true } }
},
:countries => [:de, :us],
:order! => [:countries, :persons],
:attributes! => { :countries => { :array => true } }
}
to_xml(hash)
expect(hash).to eq({
:persons => {
:first => "Lucy",
:second => "Anna",
:order! => [:second, :first],
:attributes! => { :first => { :first => true } }
},
:countries => [:de, :us],
:order! => [:countries, :persons],
:attributes! => { :countries => { :array => true } }
})
end
end
it "doesn't modify original hash parameter by deleting its attribute keys" do
hash = { :person => {:name => "Johnny", :surname => "Bravo", :"@xsi:type" => "People"} }
to_xml(hash)
expect(hash).to eq({:person=>{:name=>"Johnny", :surname=>"Bravo", :"@xsi:type"=>"People"}})
end
def to_xml(hash, options = {})
Gyoku::Hash.to_xml hash, options
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/curses/mouse.rb
|
#!/usr/local/bin/ruby
require "curses"
include Curses
def show_message(*msgs)
message = msgs.join
width = message.length + 6
win = Window.new(5, width,
(lines - 5) / 2, (cols - width) / 2)
win.keypad = true
win.attron(color_pair(COLOR_RED)){
win.box(?|, ?-, ?+)
}
win.setpos(2, 3)
win.addstr(message)
win.refresh
win.getch
win.close
end
init_screen
start_color
init_pair(COLOR_BLUE,COLOR_BLUE,COLOR_WHITE)
init_pair(COLOR_RED,COLOR_RED,COLOR_WHITE)
crmode
noecho
stdscr.keypad(true)
begin
mousemask(BUTTON1_CLICKED|BUTTON2_CLICKED|BUTTON3_CLICKED|BUTTON4_CLICKED)
setpos((lines - 5) / 2, (cols - 10) / 2)
attron(color_pair(COLOR_BLUE)|A_BOLD){
addstr("click")
}
refresh
while( true )
c = getch
case c
when KEY_MOUSE
m = getmouse
if( m )
show_message("getch = #{c.inspect}, ",
"mouse event = #{'0x%x' % m.bstate}, ",
"axis = (#{m.x},#{m.y},#{m.z})")
end
break
end
end
refresh
ensure
close_screen
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/winrm-1.8.1/spec/issue_59_spec.rb
|
<gh_stars>0
# encoding: UTF-8
describe 'issue 59', integration: true do
before(:all) do
@winrm = winrm_connection
end
describe 'long running script without output' do
let(:logged_output) { StringIO.new }
let(:logger) { Logging.logger(logged_output) }
it 'should not error' do
@winrm.set_timeout(1)
@winrm.logger = logger
out = @winrm.powershell('$ProgressPreference="SilentlyContinue";sleep 3; Write-Host "Hello"')
expect(out).to have_exit_code 0
expect(out).to have_stdout_match(/Hello/)
expect(out).to have_no_stderr
expect(logged_output.string).to match(/retrying receive request/)
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/net-ssh-2.6.8/test/transport/kex/test_diffie_hellman_group_exchange_sha256.rb
|
<filename>.rvm/gems/ruby-2.3.0/gems/net-ssh-2.6.8/test/transport/kex/test_diffie_hellman_group_exchange_sha256.rb
require 'common'
require 'net/ssh/transport/kex/diffie_hellman_group_exchange_sha1'
module Transport; module Kex
class TestDiffieHellmanGroupExchangeSHA256 < TestDiffieHellmanGroupExchangeSHA1
private
def subject
Net::SSH::Transport::Kex::DiffieHellmanGroupExchangeSHA256
end
def session_id
@session_id ||= begin
buffer = Net::SSH::Buffer.from(:string, packet_data[:client_version_string],
:string, packet_data[:server_version_string],
:string, packet_data[:client_algorithm_packet],
:string, packet_data[:server_algorithm_packet],
:string, Net::SSH::Buffer.from(:key, server_key),
:long, 1024,
:long, 1024,
:long, 8192,
:bignum, dh.dh.p,
:bignum, dh.dh.g,
:bignum, dh.dh.pub_key,
:bignum, server_dh_pubkey,
:bignum, shared_secret)
OpenSSL::Digest::SHA256.digest(buffer.to_s)
end
end
end
end; end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/ext/-test-/file/extconf.rb
|
<gh_stars>0
# frozen_string_literal: false
$INCFLAGS << " -I$(topdir) -I$(top_srcdir)"
headers = %w[sys/param.h sys/mount.h sys/vfs.h].select {|h| have_header(h)}
if have_type("struct statfs", headers)
have_struct_member("struct statfs", "f_fstypename", headers)
have_struct_member("struct statfs", "f_type", headers)
end
headers = %w[sys/statvfs.h].select {|h| have_header(h)}
if have_type("struct statvfs", headers)
have_struct_member("struct statvfs", "f_fstypename", headers)
have_struct_member("struct statvfs", "f_basetype", headers)
have_struct_member("struct statvfs", "f_type", headers)
end
$srcs = Dir[File.join($srcdir, "*.{#{SRC_EXT.join(%q{,})}}")]
inits = $srcs.map {|s| File.basename(s, ".*")}
inits.delete("init")
inits.map! {|s|"X(#{s})"}
$defs << "-DTEST_INIT_FUNCS(X)=\"#{inits.join(' ')}\""
create_makefile("-test-/file")
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/lib/rdoc/comment.rb
|
<gh_stars>0
# frozen_string_literal: false
##
# A comment holds the text comment for a RDoc::CodeObject and provides a
# unified way of cleaning it up and parsing it into an RDoc::Markup::Document.
#
# Each comment may have a different markup format set by #format=. By default
# 'rdoc' is used. The :markup: directive tells RDoc which format to use.
#
# See RDoc::Markup@Other+directives for instructions on adding an alternate
# format.
class RDoc::Comment
include RDoc::Text
##
# The format of this comment. Defaults to RDoc::Markup
attr_reader :format
##
# The RDoc::TopLevel this comment was found in
attr_accessor :location
##
# For duck-typing when merging classes at load time
alias file location # :nodoc:
##
# The text for this comment
attr_reader :text
##
# Overrides the content returned by #parse. Use when there is no #text
# source for this comment
attr_writer :document
##
# Creates a new comment with +text+ that is found in the RDoc::TopLevel
# +location+.
def initialize text = nil, location = nil
@location = location
@text = text
@document = nil
@format = 'rdoc'
@normalized = false
end
##
#--
# TODO deep copy @document
def initialize_copy copy # :nodoc:
@text = copy.text.dup
end
def == other # :nodoc:
self.class === other and
other.text == @text and other.location == @location
end
##
# Look for a 'call-seq' in the comment to override the normal parameter
# handling. The :call-seq: is indented from the baseline. All lines of the
# same indentation level and prefix are consumed.
#
# For example, all of the following will be used as the :call-seq:
#
# # :call-seq:
# # ARGF.readlines(sep=$/) -> array
# # ARGF.readlines(limit) -> array
# # ARGF.readlines(sep, limit) -> array
# #
# # ARGF.to_a(sep=$/) -> array
# # ARGF.to_a(limit) -> array
# # ARGF.to_a(sep, limit) -> array
def extract_call_seq method
# we must handle situations like the above followed by an unindented first
# comment. The difficulty is to make sure not to match lines starting
# with ARGF at the same indent, but that are after the first description
# paragraph.
if @text =~ /^\s*:?call-seq:(.*?(?:\S).*?)^\s*$/m then
all_start, all_stop = $~.offset(0)
seq_start, seq_stop = $~.offset(1)
# we get the following lines that start with the leading word at the
# same indent, even if they have blank lines before
if $1 =~ /(^\s*\n)+^(\s*\w+)/m then
leading = $2 # ' * ARGF' in the example above
re = %r%
\A(
(^\s*\n)+
(^#{Regexp.escape leading}.*?\n)+
)+
^\s*$
%xm
if @text[seq_stop..-1] =~ re then
all_stop = seq_stop + $~.offset(0).last
seq_stop = seq_stop + $~.offset(1).last
end
end
seq = @text[seq_start..seq_stop]
seq.gsub!(/^\s*(\S|\n)/m, '\1')
@text.slice! all_start...all_stop
method.call_seq = seq.chomp
elsif @text.sub!(/^\s*:?call-seq:(.*?)(^\s*$|\z)/m, '') then
seq = $1
seq.gsub!(/^\s*/, '')
method.call_seq = seq
end
method
end
##
# A comment is empty if its text String is empty.
def empty?
@text.empty?
end
##
# HACK dubious
def force_encoding encoding
@text.force_encoding encoding
end
##
# Sets the format of this comment and resets any parsed document
def format= format
@format = format
@document = nil
end
def inspect # :nodoc:
location = @location ? @location.relative_name : '(unknown)'
"#<%s:%x %s %p>" % [self.class, object_id, location, @text]
end
##
# Normalizes the text. See RDoc::Text#normalize_comment for details
def normalize
return self unless @text
return self if @normalized # TODO eliminate duplicate normalization
@text = normalize_comment @text
@normalized = true
self
end
##
# Was this text normalized?
def normalized? # :nodoc:
@normalized
end
##
# Parses the comment into an RDoc::Markup::Document. The parsed document is
# cached until the text is changed.
def parse
return @document if @document
@document = super @text, @format
@document.file = @location
@document
end
##
# Removes private sections from this comment. Private sections are flush to
# the comment marker and start with <tt>--</tt> and end with <tt>++</tt>.
# For C-style comments, a private marker may not start at the opening of the
# comment.
#
# /*
# *--
# * private
# *++
# * public
# */
def remove_private
# Workaround for gsub encoding for Ruby 1.9.2 and earlier
empty = ''
empty.force_encoding @text.encoding if Object.const_defined? :Encoding
@text = @text.gsub(%r%^\s*([#*]?)--.*?^\s*(\1)\+\+\n?%m, empty)
@text = @text.sub(%r%^\s*[#*]?--.*%m, '')
end
##
# Replaces this comment's text with +text+ and resets the parsed document.
#
# An error is raised if the comment contains a document but no text.
def text= text
raise RDoc::Error, 'replacing document-only comment is not allowed' if
@text.nil? and @document
@document = nil
@text = text
end
##
# Returns true if this comment is in TomDoc format.
def tomdoc?
@format == 'tomdoc'
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/net-ssh-multi-1.2.0/test/multi_test.rb
|
<reponame>arnab0073/idea
require 'common'
require 'net/ssh/multi'
class MultiTest < Test::Unit::TestCase
def test_start_with_block_should_yield_session_and_then_close
Net::SSH::Multi::Session.any_instance.expects(:loop)
Net::SSH::Multi::Session.any_instance.expects(:close)
yielded = false
Net::SSH::Multi.start do |session|
yielded = true
assert_instance_of Net::SSH::Multi::Session, session
end
end
def test_start_without_block_should_return_open_session
Net::SSH::Multi::Session.any_instance.expects(:loop).never
Net::SSH::Multi::Session.any_instance.expects(:close).never
assert_instance_of Net::SSH::Multi::Session, Net::SSH::Multi.start
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/optparse/test_bash_completion.rb
|
<filename>.rvm/src/ruby-2.3.0/test/optparse/test_bash_completion.rb
# frozen_string_literal: false
require 'test/unit'
require 'optparse'
class TestOptionParser < Test::Unit::TestCase
end
class TestOptionParser::BashCompletion < Test::Unit::TestCase
def setup
@opt = OptionParser.new
@opt.define("-z", "zzz") {}
@opt.define("--foo") {}
@opt.define("--bar=BAR") {}
@opt.define("--for=TYPE", [:hello, :help, :zot]) {}
end
def test_empty
assert_equal([], @opt.candidate(""))
end
def test_one_hyphen
assert_equal(%w[-z --foo --bar= --for=], @opt.candidate("-"))
end
def test_two_hyphen
assert_equal(%w[--foo --bar= --for=], @opt.candidate("--"))
end
def test_long_f
assert_equal(%w[--foo --for=], @opt.candidate("--f"))
end
def test_long_for_option
assert_equal(%w[--for=], @opt.candidate("--for"))
end
def test_long_for_option_args
assert_equal(%w[hello help zot], @opt.candidate("--for="))
end
def test_long_for_option_complete
assert_equal(%w[hello help], @opt.candidate("--for=h"))
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/mathn/rational/extconf.rb
|
require "mkmf"
create_makefile "mathn/rational"
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/tool/rbinstall.rb
|
#!./miniruby
begin
load "./rbconfig.rb"
rescue LoadError
CONFIG = Hash.new {""}
else
include RbConfig
$".unshift File.expand_path("./rbconfig.rb")
end
srcdir = File.expand_path('../..', __FILE__)
unless defined?(CROSS_COMPILING) and CROSS_COMPILING
$:.replace([srcdir+"/lib", Dir.pwd])
end
require 'fileutils'
require 'shellwords'
require 'optparse'
require 'optparse/shellwords'
require 'ostruct'
require 'rubygems'
begin
require "zlib"
rescue LoadError
$" << "zlib.rb"
end
STDOUT.sync = true
File.umask(077)
def parse_args(argv = ARGV)
$mantype = 'doc'
$destdir = nil
$extout = nil
$make = 'make'
$mflags = []
$install = []
$installed_list = nil
$dryrun = false
$rdocdir = nil
$data_mode = 0644
$prog_mode = 0755
$dir_mode = nil
$script_mode = nil
$strip = false
$cmdtype = (if File::ALT_SEPARATOR == '\\'
File.exist?("rubystub.exe") ? 'exe' : 'cmd'
end)
mflags = []
opt = OptionParser.new
opt.on('-n', '--dry-run') {$dryrun = true}
opt.on('--dest-dir=DIR') {|dir| $destdir = dir}
opt.on('--extout=DIR') {|dir| $extout = (dir unless dir.empty?)}
opt.on('--make=COMMAND') {|make| $make = make}
opt.on('--mantype=MAN') {|man| $mantype = man}
opt.on('--make-flags=FLAGS', '--mflags', Shellwords) do |v|
if arg = v.first
arg.insert(0, '-') if /\A[^-][^=]*\Z/ =~ arg
end
$mflags.concat(v)
end
opt.on('-i', '--install=TYPE', $install_procs.keys) do |ins|
$install << ins
end
opt.on('--data-mode=OCTAL-MODE', OptionParser::OctalInteger) do |mode|
$data_mode = mode
end
opt.on('--prog-mode=OCTAL-MODE', OptionParser::OctalInteger) do |mode|
$prog_mode = mode
end
opt.on('--dir-mode=OCTAL-MODE', OptionParser::OctalInteger) do |mode|
$dir_mode = mode
end
opt.on('--script-mode=OCTAL-MODE', OptionParser::OctalInteger) do |mode|
$script_mode = mode
end
opt.on('--installed-list [FILENAME]') {|name| $installed_list = name}
opt.on('--rdoc-output [DIR]') {|dir| $rdocdir = dir}
opt.on('--cmd-type=TYPE', %w[cmd plain]) {|cmd| $cmdtype = (cmd unless cmd == 'plain')}
opt.on('--[no-]strip') {|strip| $strip = strip}
opt.order!(argv) do |v|
case v
when /\AINSTALL[-_]([-\w]+)=(.*)/
argv.unshift("--#{$1.tr('_', '-')}=#{$2}")
when /\A\w[-\w+]*=\z/
mflags << v
when /\A\w[-\w+]*\z/
$install << v.intern
else
raise OptionParser::InvalidArgument, v
end
end rescue abort "#{$!.message}\n#{opt.help}"
unless defined?(RbConfig)
puts opt.help
exit
end
$make, *rest = Shellwords.shellwords($make)
$mflags.unshift(*rest) unless rest.empty?
$mflags.unshift(*mflags)
def $mflags.set?(flag)
grep(/\A-(?!-).*#{flag.chr}/i) { return true }
false
end
def $mflags.defined?(var)
grep(/\A#{var}=(.*)/) {return block_given? ? yield($1) : $1}
false
end
if $mflags.set?(?n)
$dryrun = true
else
$mflags << '-n' if $dryrun
end
$destdir ||= $mflags.defined?("DESTDIR")
if $extout ||= $mflags.defined?("EXTOUT")
RbConfig.expand($extout)
end
$continue = $mflags.set?(?k)
if $installed_list ||= $mflags.defined?('INSTALLED_LIST')
RbConfig.expand($installed_list, RbConfig::CONFIG)
$installed_list = open($installed_list, "ab")
$installed_list.sync = true
end
$rdocdir ||= $mflags.defined?('RDOCOUT')
$dir_mode ||= $prog_mode | 0700
$script_mode ||= $prog_mode
end
$install_procs = Hash.new {[]}
def install?(*types, &block)
$install_procs[:all] <<= block
types.each do |type|
$install_procs[type] <<= block
end
end
def strip_file(files)
if !defined?($strip_command) and (cmd = CONFIG["STRIP"])
case cmd
when "", "true", ":" then return
else $strip_command = Shellwords.shellwords(cmd)
end
elsif !$strip_command
return
end
system(*($strip_command + [files].flatten))
end
def install(src, dest, options = {})
options = options.clone
strip = options.delete(:strip)
options[:preserve] = true
d = with_destdir(dest)
super(src, d, options)
srcs = Array(src)
if strip
d = srcs.map {|s| File.join(d, File.basename(s))} if $made_dirs[dest]
strip_file(d)
end
if $installed_list
dest = srcs.map {|s| File.join(dest, File.basename(s))} if $made_dirs[dest]
$installed_list.puts dest
end
end
def ln_sf(src, dest)
super(src, with_destdir(dest))
$installed_list.puts dest if $installed_list
end
$made_dirs = {}
def makedirs(dirs)
dirs = fu_list(dirs)
dirs.collect! do |dir|
realdir = with_destdir(dir)
realdir unless $made_dirs.fetch(dir) do
$made_dirs[dir] = true
$installed_list.puts(File.join(dir, "")) if $installed_list
File.directory?(realdir)
end
end.compact!
super(dirs, :mode => $dir_mode) unless dirs.empty?
end
FalseProc = proc {false}
def path_matcher(pat)
if pat and !pat.empty?
proc {|f| pat.any? {|n| File.fnmatch?(n, f)}}
else
FalseProc
end
end
def install_recursive(srcdir, dest, options = {})
opts = options.clone
noinst = opts.delete(:no_install)
glob = opts.delete(:glob) || "*"
maxdepth = opts.delete(:maxdepth)
subpath = (srcdir.size+1)..-1
prune = []
skip = []
if noinst
if Array === noinst
prune = noinst.grep(/#{File::SEPARATOR}/o).map!{|f| f.chomp(File::SEPARATOR)}
skip = noinst.grep(/\A[^#{File::SEPARATOR}]*\z/o)
else
if noinst.index(File::SEPARATOR)
prune = [noinst]
else
skip = [noinst]
end
end
end
skip |= %w"#*# *~ *.old *.bak *.orig *.rej *.diff *.patch *.core"
prune = path_matcher(prune)
skip = path_matcher(skip)
File.directory?(srcdir) or return rescue return
paths = [[srcdir, dest, 0]]
found = []
while file = paths.shift
found << file
file, d, dir = *file
if dir
depth = dir + 1
next if maxdepth and maxdepth < depth
files = []
Dir.foreach(file) do |f|
src = File.join(file, f)
d = File.join(dest, dir = src[subpath])
stat = File.lstat(src) rescue next
if stat.directory?
files << [src, d, depth] if maxdepth != depth and /\A\./ !~ f and !prune[dir]
elsif stat.symlink?
# skip
else
files << [src, d, false] if File.fnmatch?(glob, f) and !skip[f]
end
end
paths.insert(0, *files)
end
end
for src, d, dir in found
if dir
makedirs(d)
else
makedirs(d[/.*(?=\/)/m])
if block_given?
yield src, d, opts
else
install src, d, opts
end
end
end
end
def open_for_install(path, mode)
data = open(realpath = with_destdir(path), "rb") {|f| f.read} rescue nil
newdata = yield
unless $dryrun
unless newdata == data
open(realpath, "wb", mode) {|f| f.write newdata}
end
File.chmod(mode, realpath)
end
$installed_list.puts path if $installed_list
end
def with_destdir(dir)
return dir if !$destdir or $destdir.empty?
dir = dir.sub(/\A\w:/, '') if File::PATH_SEPARATOR == ';'
$destdir + dir
end
def without_destdir(dir)
return dir if !$destdir or $destdir.empty? or !dir.start_with?($destdir)
dir = dir.sub(/\A\w:/, '') if File::PATH_SEPARATOR == ';'
dir[$destdir.size..-1]
end
def prepare(mesg, basedir, subdirs=nil)
return unless basedir
case
when !subdirs
dirs = basedir
when subdirs.size == 0
subdirs = nil
when subdirs.size == 1
dirs = [basedir = File.join(basedir, subdirs)]
subdirs = nil
else
dirs = [basedir, *subdirs.collect {|dir| File.join(basedir, dir)}]
end
printf("installing %-18s %s%s\n", "#{mesg}:", basedir,
(subdirs ? " (#{subdirs.join(', ')})" : ""))
makedirs(dirs)
end
def CONFIG.[](name, mandatory = false)
value = super(name)
if mandatory
raise "CONFIG['#{name}'] must be set" if !value or value.empty?
end
value
end
exeext = CONFIG["EXEEXT"]
ruby_install_name = CONFIG["ruby_install_name", true]
rubyw_install_name = CONFIG["rubyw_install_name"]
goruby_install_name = "go" + ruby_install_name
bindir = CONFIG["bindir", true]
libdir = CONFIG[CONFIG.fetch("libdirname", "libdir"), true]
rubyhdrdir = CONFIG["rubyhdrdir", true]
archhdrdir = CONFIG["rubyarchhdrdir"] || (rubyhdrdir + "/" + CONFIG['arch'])
rubylibdir = CONFIG["rubylibdir", true]
archlibdir = CONFIG["rubyarchdir", true]
sitelibdir = CONFIG["sitelibdir"]
sitearchlibdir = CONFIG["sitearchdir"]
vendorlibdir = CONFIG["vendorlibdir"]
vendorarchlibdir = CONFIG["vendorarchdir"]
mandir = CONFIG["mandir", true]
docdir = CONFIG["docdir", true]
configure_args = Shellwords.shellwords(CONFIG["configure_args"])
enable_shared = CONFIG["ENABLE_SHARED"] == 'yes'
dll = CONFIG["LIBRUBY_SO", enable_shared]
lib = CONFIG["LIBRUBY", true]
arc = CONFIG["LIBRUBY_A", true]
config_h = File.read(CONFIG["EXTOUT"]+"/include/"+CONFIG["arch"]+"/ruby/config.h")
load_relative = config_h[/^\s*#\s*define\s+LOAD_RELATIVE\s+(\d+)/, 1].to_i.nonzero?
install?(:local, :arch, :bin, :'bin-arch') do
prepare "binary commands", bindir
install ruby_install_name+exeext, bindir, :mode => $prog_mode, :strip => $strip
if rubyw_install_name and !rubyw_install_name.empty?
install rubyw_install_name+exeext, bindir, :mode => $prog_mode, :strip => $strip
end
if File.exist? goruby_install_name+exeext
install goruby_install_name+exeext, bindir, :mode => $prog_mode, :strip => $strip
end
if enable_shared and dll != lib
install dll, bindir, :mode => $prog_mode, :strip => $strip
end
end
install?(:local, :arch, :lib) do
prepare "base libraries", libdir
install lib, libdir, :mode => $prog_mode, :strip => $strip unless lib == arc
install arc, libdir, :mode => $data_mode
if dll == lib and dll != arc
for link in CONFIG["LIBRUBY_ALIASES"].split
ln_sf(dll, File.join(libdir, link))
end
end
prepare "arch files", archlibdir
install "rbconfig.rb", archlibdir, :mode => $data_mode
if CONFIG["ARCHFILE"]
for file in CONFIG["ARCHFILE"].split
install file, archlibdir, :mode => $data_mode
end
end
end
install?(:local, :arch, :data) do
pc = CONFIG["ruby_pc"]
if pc and File.file?(pc) and File.size?(pc)
prepare "pkgconfig data", pkgconfigdir = File.join(libdir, "pkgconfig")
install pc, pkgconfigdir, :mode => $data_mode
end
end
install?(:ext, :arch, :'ext-arch') do
prepare "extension objects", archlibdir
noinst = %w[-* -*/] | (CONFIG["no_install_files"] || "").split
install_recursive("#{$extout}/#{CONFIG['arch']}", archlibdir, :no_install => noinst, :mode => $prog_mode, :strip => $strip)
prepare "extension objects", sitearchlibdir
prepare "extension objects", vendorarchlibdir
end
install?(:ext, :arch, :hdr, :'arch-hdr') do
prepare "extension headers", archhdrdir
install_recursive("#{$extout}/include/#{CONFIG['arch']}", archhdrdir, :glob => "*.h", :mode => $data_mode)
end
install?(:ext, :comm, :'ext-comm') do
prepare "extension scripts", rubylibdir
install_recursive("#{$extout}/common", rubylibdir, :mode => $data_mode)
prepare "extension scripts", sitelibdir
prepare "extension scripts", vendorlibdir
end
install?(:ext, :comm, :hdr, :'comm-hdr') do
hdrdir = rubyhdrdir + "/ruby"
prepare "extension headers", hdrdir
install_recursive("#{$extout}/include/ruby", hdrdir, :glob => "*.h", :mode => $data_mode)
end
install?(:doc, :rdoc) do
if $rdocdir
ridatadir = File.join(CONFIG['ridir'], CONFIG['ruby_version'], "system")
prepare "rdoc", ridatadir
install_recursive($rdocdir, ridatadir, :mode => $data_mode)
end
end
install?(:doc, :capi) do
prepare "capi-docs", docdir
install_recursive "doc/capi", docdir+"/capi", :mode => $data_mode
end
if load_relative
PROLOG_SCRIPT = <<EOS
#!/bin/sh\n# -*- ruby -*-
bindir="${0%/*}"
EOS
if CONFIG["LIBRUBY_RELATIVE"] != 'yes' and libpathenv = CONFIG["LIBPATHENV"]
pathsep = File::PATH_SEPARATOR
PROLOG_SCRIPT << <<EOS
prefix="${bindir%/bin}"
export #{libpathenv}="$prefix/lib${#{libpathenv}:+#{pathsep}$#{libpathenv}}"
EOS
end
PROLOG_SCRIPT << %Q[exec "$bindir/#{ruby_install_name}" -x "$0" "$@"\n]
else
PROLOG_SCRIPT = nil
end
install?(:local, :comm, :bin, :'bin-comm') do
prepare "command scripts", bindir
ruby_shebang = File.join(bindir, ruby_install_name)
if File::ALT_SEPARATOR
ruby_bin = ruby_shebang.tr(File::SEPARATOR, File::ALT_SEPARATOR)
if $cmdtype == 'exe'
stub = File.open("rubystub.exe", "rb") {|f| f.read} << "\n" rescue nil
end
end
if trans = CONFIG["program_transform_name"]
exp = []
trans.gsub!(/\$\$/, '$')
trans.scan(%r[\G[\s;]*(/(?:\\.|[^/])*/)?([sy])(\\?\W)((?:(?!\3)(?:\\.|.))*)\3((?:(?!\3)(?:\\.|.))*)\3([gi]*)]) do
|addr, cmd, sep, pat, rep, opt|
addr &&= Regexp.new(addr[/\A\/(.*)\/\z/, 1])
case cmd
when 's'
next if pat == '^' and rep.empty?
exp << [addr, (opt.include?('g') ? :gsub! : :sub!),
Regexp.new(pat, opt.include?('i')), rep.gsub(/&/){'\&'}]
when 'y'
exp << [addr, :tr!, Regexp.quote(pat), rep]
end
end
trans = proc do |base|
exp.each {|addr, opt, pat, rep| base.__send__(opt, pat, rep) if !addr or addr =~ base}
base
end
elsif /ruby/ =~ ruby_install_name
trans = proc {|base| ruby_install_name.sub(/ruby/, base)}
else
trans = proc {|base| base}
end
prebatch = ':""||{ ""=> %q<-*- ruby -*-'"\n"
postbatch = PROLOG_SCRIPT ? "};{\n#{PROLOG_SCRIPT.sub(/\A(?:#.*\n)*/, '')}" : ''
postbatch << ">,\n}\n"
postbatch.gsub!(/(?=\n)/, ' #')
install_recursive(File.join(srcdir, "bin"), bindir, :maxdepth => 1) do |src, cmd|
cmd = cmd.sub(/[^\/]*\z/m) {|n| RbConfig.expand(trans[n])}
shebang, body = open(src, "rb") do |f|
next f.gets, f.read
end
shebang or raise "empty file - #{src}"
if PROLOG_SCRIPT and !$cmdtype
shebang.sub!(/\A(\#!.*?ruby\b)?/) {PROLOG_SCRIPT + ($1 || "#!ruby\n")}
else
shebang.sub!(/\A(\#!.*?ruby\b)?/) {"#!" + ruby_shebang + ($1 ? "" : "\n")}
end
shebang.sub!(/\r$/, '')
body.gsub!(/\r$/, '')
cmd << ".#{$cmdtype}" if $cmdtype
open_for_install(cmd, $script_mode) do
case $cmdtype
when "exe"
stub + shebang + body
when "cmd"
prebatch + <<"/EOH" << postbatch << shebang << body
@"%~dp0#{ruby_install_name}" -x "%~f0" %*
@exit /b %ERRORLEVEL%
/EOH
else
shebang + body
end
end
end
end
install?(:local, :comm, :lib) do
prepare "library scripts", rubylibdir
noinst = %w[README* *.txt *.rdoc *.gemspec]
install_recursive(File.join(srcdir, "lib"), rubylibdir, :no_install => noinst, :mode => $data_mode)
end
install?(:local, :comm, :hdr, :'comm-hdr') do
prepare "common headers", rubyhdrdir
noinst = []
unless RUBY_PLATFORM =~ /mswin|mingw|bccwin/
noinst << "win32.h"
end
noinst = nil if noinst.empty?
install_recursive(File.join(srcdir, "include"), rubyhdrdir, :no_install => noinst, :glob => "*.h", :mode => $data_mode)
end
install?(:local, :comm, :man) do
mdocs = Dir["#{srcdir}/man/*.[1-9]"]
prepare "manpages", mandir, ([] | mdocs.collect {|mdoc| mdoc[/\d+$/]}).sort.collect {|sec| "man#{sec}"}
case $mantype
when /\.(?:(gz)|bz2)\z/
compress = $1 ? "gzip" : "bzip2"
suffix = $&
end
mandir = File.join(mandir, "man")
has_goruby = File.exist?(goruby_install_name+exeext)
require File.join(srcdir, "tool/mdoc2man.rb") if /\Adoc\b/ !~ $mantype
mdocs.each do |mdoc|
next unless File.file?(mdoc) and open(mdoc){|fh| fh.read(1) == '.'}
base = File.basename(mdoc)
if base == "goruby.1"
next unless has_goruby
end
destdir = mandir + (section = mdoc[/\d+$/])
destname = ruby_install_name.sub(/ruby/, base.chomp(".#{section}"))
destfile = File.join(destdir, "#{destname}.#{section}")
if /\Adoc\b/ =~ $mantype
if compress
w = open(mdoc) {|f|
stdin = STDIN.dup
STDIN.reopen(f)
begin
destfile << suffix
IO.popen(compress) {|f| f.read}
ensure
STDIN.reopen(stdin)
stdin.close
end
}
open_for_install(destfile, $data_mode) {w}
else
install mdoc, destfile, :mode => $data_mode
end
else
class << (w = [])
alias print push
end
open(mdoc) {|r| Mdoc2Man.mdoc2man(r, w)}
w = w.join("")
if compress
require 'tmpdir'
Dir.mktmpdir("man") {|d|
dest = File.join(d, File.basename(destfile))
File.open(dest, "wb") {|f| f.write w}
if system(compress, dest)
w = File.open(dest+suffix, "rb") {|f| f.read}
destfile << suffix
end
}
end
open_for_install(destfile, $data_mode) {w}
end
end
end
module RbInstall
module Specs
class FileCollector
def initialize(base_dir)
@base_dir = base_dir
end
def collect
(ruby_libraries + built_libraries).sort
end
private
def type
/\/(ext|lib)?\/.*?\z/ =~ @base_dir
$1
end
def ruby_libraries
case type
when "ext"
prefix = "#{$extout}/common/"
base = "#{prefix}#{relative_base}"
when "lib"
base = @base_dir
prefix = base.sub(/lib\/.*?\z/, "") + "lib/"
end
Dir.glob("#{base}{.rb,/**/*.rb}").collect do |ruby_source|
remove_prefix(prefix, ruby_source)
end
end
def built_libraries
case type
when "ext"
prefix = "#{$extout}/#{CONFIG['arch']}/"
base = "#{prefix}#{relative_base}"
dlext = CONFIG['DLEXT']
Dir.glob("#{base}{.#{dlext},/**/*.#{dlext}}").collect do |built_library|
remove_prefix(prefix, built_library)
end
when "lib"
[]
end
end
def relative_base
/\/#{Regexp.escape(type)}\/(.*?)\z/ =~ @base_dir
$1
end
def remove_prefix(prefix, string)
string.sub(/\A#{Regexp.escape(prefix)}/, "")
end
end
class Reader < Struct.new(:src)
def gemspec
@gemspec ||= begin
spec = Gem::Specification.load(src) || raise("invalid spec in #{src}")
file_collector = FileCollector.new(File.dirname(src))
spec.files = file_collector.collect
spec
end
end
def spec_source
@gemspec.to_ruby
end
end
end
class UnpackedInstaller < Gem::Installer
module DirPackage
def extract_files(destination_dir, pattern = "*")
path = File.dirname(@gem.path)
return if path == destination_dir
File.chmod(0700, destination_dir)
mode = pattern == "bin/*" ? $script_mode : $data_mode
install_recursive(path, without_destdir(destination_dir),
:glob => pattern,
:no_install => "*.gemspec",
:mode => mode)
File.chmod($dir_mode, destination_dir)
end
end
def initialize(spec, *options)
super(spec.loaded_from, *options)
@package.extend(DirPackage).spec = spec
end
def write_cache_file
end
end
end
class Gem::Installer
install = instance_method(:install)
define_method(:install) do
spec.post_install_message = nil
install.bind(self).call
end
generate_bin_script = instance_method(:generate_bin_script)
define_method(:generate_bin_script) do |filename, bindir|
generate_bin_script.bind(self).call(filename, bindir)
File.chmod($script_mode, File.join(bindir, formatted_program_filename(filename)))
end
end
# :startdoc:
install?(:ext, :comm, :gem) do
gem_dir = Gem.default_dir
directories = Gem.ensure_gem_subdirectories(gem_dir, :mode => $dir_mode)
prepare "default gems", gem_dir, directories
spec_dir = File.join(gem_dir, directories.grep(/^spec/)[0])
default_spec_dir = "#{spec_dir}/default"
makedirs(default_spec_dir)
gems = {}
Dir.glob(srcdir+"/{lib,ext}/**/*.gemspec").each do |src|
specgen = RbInstall::Specs::Reader.new(src)
gems[specgen.gemspec.name] ||= specgen
end
gems.sort.each do |name, specgen|
gemspec = specgen.gemspec
full_name = "#{gemspec.name}-#{gemspec.version}"
puts "#{" "*30}#{gemspec.name} #{gemspec.version}"
gemspec_path = File.join(default_spec_dir, "#{full_name}.gemspec")
open_for_install(gemspec_path, $data_mode) do
specgen.spec_source
end
unless gemspec.executables.empty? then
bin_dir = File.join(gem_dir, 'gems', full_name, 'bin')
makedirs(bin_dir)
execs = gemspec.executables.map {|exec| File.join(srcdir, 'bin', exec)}
install(execs, bin_dir, :mode => $script_mode)
end
end
end
install?(:ext, :comm, :gem) do
gem_dir = Gem.default_dir
directories = Gem.ensure_gem_subdirectories(gem_dir, :mode => $dir_mode)
prepare "bundle gems", gem_dir, directories
install_dir = with_destdir(gem_dir)
installed_gems = {}
options = {
:install_dir => install_dir,
:bin_dir => with_destdir(bindir),
:domain => :local,
:ignore_dependencies => true,
:dir_mode => $dir_mode,
:data_mode => $data_mode,
:prog_mode => $prog_mode,
:wrappers => true,
:format_executable => true,
}
Gem::Specification.each_spec([srcdir+'/gems/*']) do |spec|
ins = RbInstall::UnpackedInstaller.new(spec, options)
puts "#{" "*30}#{spec.name} #{spec.version}"
ins.install
File.chmod($data_mode, File.join(install_dir, "specifications", "#{spec.full_name}.gemspec"))
installed_gems[spec.full_name] = true
end
installed_gems, gems = Dir.glob(srcdir+'/gems/*.gem').partition {|gem| installed_gems.key?(File.basename(gem, '.gem'))}
unless installed_gems.empty?
install installed_gems, gem_dir+"/cache"
end
next if gems.empty?
if defined?(Zlib)
Gem.instance_variable_set(:@ruby, with_destdir(File.join(bindir, ruby_install_name)))
gems.each do |gem|
Gem.install(gem, Gem::Requirement.default, options)
gemname = File.basename(gem)
puts "#{" "*30}#{gemname}"
end
# fix directory permissions
# TODO: Gem.install should accept :dir_mode option or something
File.chmod($dir_mode, *Dir.glob(install_dir+"/**/"))
# fix .gemspec permissions
File.chmod($data_mode, *Dir.glob(install_dir+"/specifications/*.gemspec"))
else
puts "skip installing bundle gems because of lacking zlib"
end
end
parse_args()
include FileUtils
include FileUtils::NoWrite if $dryrun
@fileutils_output = STDOUT
@fileutils_label = ''
all = $install.delete(:all)
$install << :local << :ext if $install.empty?
installs = $install.map do |inst|
if !(procs = $install_procs[inst]) || procs.empty?
next warn("unknown install target - #{inst}")
end
procs
end
installs.flatten!
installs.uniq!
installs |= $install_procs[:all] if all
installs.each do |block|
dir = Dir.pwd
begin
block.call
ensure
Dir.chdir(dir)
end
end
# vi:set sw=2:
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/lib/ohai/plugins/groovy.rb
|
#
# Author:: <NAME> <<EMAIL>>
# Copyright:: Copyright (c) 2009 VMware, 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.
#
provides "languages/groovy"
require_plugin "languages"
output = nil
groovy = Mash.new
status, stdout, stderr = run_command(:no_status_check => true, :command => "groovy -v")
if status == 0
output = stdout.split
if output.length >= 2
groovy[:version] = output[2]
end
languages[:groovy] = groovy if groovy[:version]
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/treectrl/outlook-folders.rb
|
<reponame>arnab0073/idea
#
# Demo: Outlook Express folder list
#
def demoOutlookFolders(t)
init_pics('outlook-*')
height = t.font.metrics(:linespace) + 2
height = 18 if height < 18
t.configure(:itemheight=>height, :selectmode=>:browse, :showlines=>true,
:showroot=>true, :showrootbutton=>false, :showbuttons=>true)
if $HasColumnCreate
t.column_create(:text=>'Folders')
else
t.column_configure(0, :text=>'Folders')
end
t.element_create('e1', :image)
t.element_create('e2', :text, :lines=>1,
:fill=>[@SystemHighlightText, ['selected', 'focus']])
t.element_create('e3', :text, :lines=>1, :font=>t.font.dup.weight(:bold),
:fill=>[@SystemHighlightText, ['selected', 'focus']])
t.element_create('e4', :text, :fill=>'blue')
t.element_create('e5', :image, :image=>@images['outlook-folder'])
t.element_create('e6', :rect, :showfocus=>true,
:fill=>[
@SystemHighlight, ['selected', 'focus'],
'gray', ['selected', '!focus']
])
# image + text
s = t.style_create('s1')
t.style_elements(s, ['e6', 'e1', 'e2'])
t.style_layout(s, 'e1', :expand=>:ns)
t.style_layout(s, 'e2', :padx=>[4,0], :expand=>:ns, :squeeze=>:x)
t.style_layout(s, 'e6', :union=>['e2'], :iexpand=>:ns, :ipadx=>2)
# image + text + text
s = t.style_create('s2')
t.style_elements(s, ['e6', 'e1', 'e3', 'e4'])
t.style_layout(s, 'e1', :expand=>:ns)
t.style_layout(s, 'e3', :padx=>4, :expand=>:ns, :squeeze=>:x)
t.style_layout(s, 'e4', :expand=>:ns)
t.style_layout(s, 'e6', :union=>['e3'], :iexpand=>:ns, :ipadx=>2)
# folder + text
s = t.style_create('s3')
t.style_elements(s, ['e6', 'e5', 'e2'])
t.style_layout(s, 'e5', :expand=>:ns)
t.style_layout(s, 'e2', :padx=>[4,0], :expand=>:ns, :squeeze=>:x)
t.style_layout(s, 'e6', :union=>['e2'], :iexpand=>:ns, :ipadx=>2)
# folder + text + text
s = t.style_create('s4')
t.style_elements(s, ['e6', 'e5', 'e3', 'e4'])
t.style_layout(s, 'e5', :expand=>:ns)
t.style_layout(s, 'e3', :padx=>4, :expand=>:ns, :squeeze=>:x)
t.style_layout(s, 'e4', :expand=>:ns)
t.style_layout(s, 'e6', :union=>['e3'], :iexpand=>:ns, :ipadx=>2)
t.item_style_set(:root, 0, 's1')
t.item_complex(:root,
[
['e1', {:image=>@images['outlook-main']}],
['e2', {:text=>'Outlook Express'}]
])
parentList = [:root, '', '', '', '', '', '']
parent = :root
[
[0, :local, "Local Folders", true, 0],
[1, :inbox, 'Inbox', false, 5],
[1, :outbox, 'Outbox', false, 0],
[1, :sent, "Sent Items", false, 0],
[1, :deleted, "Deleted Items", false, 50],
[1, :draft, 'Drafts', false, 0],
[1, :folder, "Messages to Dad", false, 0],
[1, :folder, "Messages to Sis", false, 0],
[1, :folder, "Messages to Me", false, 0],
[2, :folder, "2001", false, 0],
[2, :folder, "2000", false, 0],
[2, :folder, "1999", false, 0],
[0, :server, "news.gmane.org", true, 0],
[1, :group, "gmane.comp.lang.lua.general", false, 498]
].each{|depth, img, text, button, unread|
if $Version_1_1_OrLater
item = t.item_create(:button=>button)
else
item = t.item_create
t.item_hasbutton(item, button)
end
if img == :folder
if unread != 0
t.item_style_set(item, 0, 's4')
t.item_complex(item,
[['e3', {:text=>text}], ['e4', {:text=>"(#{unread})"}]])
else
t.item_style_set(item, 0, 's3')
t.item_complex(item, [['e2', {:text=>text}]])
end
else
if unread != 0
t.item_style_set(item, 0, 's2')
t.item_complex(item,
[
['e1', {:image=>@images["outlook-#{img}"]}],
['e3', {:text=>text}],
['e4', {:text=>"(#{unread})"}]
])
else
t.item_style_set(item, 0, 's1')
t.item_complex(item,
[
['e1', {:image=>@images["outlook-#{img}"]}],
['e2', {:text=>text}]
])
end
end
t.item_lastchild(parentList[depth], item)
depth += 1
parentList[depth] = item
}
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/gssapi-1.2.0/examples/gss_iov_server.rb
|
#!/usr/bin/env ruby
$: << '../lib'
$: << '.'
#require 'gssapi/heimdal'
require 'gssapi'
require 'gss_iov_helpers'
require 'base64'
require 'socket'
class GssIovServer
include GssIOVHelpers
def initialize
@host = 'example.org'
@service = "host"
@keytab = "#{ENV['HOME']}/.gssapi/krb5.keytab" # this is optional, but probably required if not running as root
@port = 8082
@tcpsrv = TCPServer.new(@host, @port)
end
def runner
loop do
puts "Listening on port #{@port}"
Thread.start(@tcpsrv.accept) do |s|
init_krb
handshake(s)
begin
emsg = (s.gets.chomp)
puts "---> Received: #{emsg}"
msg = iov_decrypt(emsg)
puts "===> Received: #{msg}"
end while msg != 'exit'
print(s, "Closing Socket\n")
s.close
puts "Closed...."
end
end
end
private
def init_krb
@gss = GSSAPI::Simple.new(@host, @service, @keytab)
@gss.acquire_credentials
puts "HELLO"
end
def handshake(sock)
print(sock, "Accepted Connection\n")
stok = sock.gets.chomp
print(sock, "Received string#{stok}\n")
otok = @gss.accept_context(Base64.strict_decode64(stok.chomp))
sock.write("#{Base64.strict_encode64(otok)}\n")
end
# Decrypt message
def msg_dec(msg)
@gss.unwrap_message(Base64.strict_decode64(msg.chomp))
end
end
gserv = GssIovServer.new
gserv.runner
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/psych/test_document.rb
|
<reponame>arnab0073/idea
# frozen_string_literal: false
require_relative 'helper'
module Psych
class TestDocument < TestCase
def setup
super
@stream = Psych.parse_stream(<<-eoyml)
%YAML 1.1
%TAG ! tag:tenderlovemaking.com,2009:
--- !fun
eoyml
@doc = @stream.children.first
end
def test_parse_tag
assert_equal([['!', 'tag:tenderlovemaking.com,2009:']],
@doc.tag_directives)
end
def test_emit_tag
assert_match('%TAG ! tag:tenderlovemaking.com,2009:', @stream.yaml)
end
def test_emit_multitag
@doc.tag_directives << ['!!', 'foo.com,2009:']
yaml = @stream.yaml
assert_match('%TAG ! tag:tenderlovemaking.com,2009:', yaml)
assert_match('%TAG !! foo.com,2009:', yaml)
end
def test_emit_bad_tag
assert_raises(RuntimeError) do
@doc.tag_directives = [['!']]
@stream.yaml
end
end
def test_parse_version
assert_equal([1,1], @doc.version)
end
def test_emit_version
assert_match('%YAML 1.1', @stream.yaml)
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/tkimg.rb
|
#
# TkImg extension support
# by <NAME> (<EMAIL>)
#
require 'tk'
# call setup script for general 'tkextlib' libraries
require 'tkextlib/setup.rb'
# call setup script
require 'tkextlib/tkimg/setup.rb'
# load all image format handlers
#TkPackage.require('Img', '1.3')
TkPackage.require('Img')
module Tk
module Img
PACKAGE_NAME = 'Img'.freeze
def self.package_name
PACKAGE_NAME
end
def self.package_version
begin
TkPackage.require('Img')
rescue
''
end
end
end
end
# autoload
autoload :TkPixmapImage, 'tkextlib/tkimg/pixmap'
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/dl/callback/extconf.rb
|
require 'mkmf'
if compiled?("dl")
callbacks = (0..8).map{|i| "callback-#{i}"}.unshift("callback")
callback_srcs = callbacks.map{|basename| "#{basename}.c"}
callback_objs = callbacks.map{|basename| "#{basename}.o"}
$distcleanfiles << '$(SRCS)'
$srcs = callback_srcs
$objs = callback_objs
$INCFLAGS << " -I$(srcdir)/.."
create_makefile("dl/callback")
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/gems/did_you_mean-1.0.0/test/test_helper.rb
|
<reponame>arnab0073/idea
require 'minitest/autorun'
require 'minitest/unit'
require 'did_you_mean'
module DidYouMean::TestHelper
def assert_correction(expected, array)
assert_equal [expected], array, "Expected #{array.inspect} to only include #{expected.inspect}"
end
end
MiniTest::Test.include(DidYouMean::TestHelper)
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/continuation/extconf.rb
|
require 'mkmf'
create_makefile('continuation')
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/examples/hierarchies.rb
|
# :stopdoc:
#
# Loggers exist in a hierarchical relationship defined by their names. Each
# logger has a parent (except for the root logger). A logger can zero or
# more children. This parent/child relationship is determined by the Ruby
# namespace separator '::'.
#
# root
# |-- Foo
# | |-- Foo::Bar
# | `-- Foo::Baz
# |-- ActiveRecord
# | `-- ActiveRecord::Base
# |-- ActiveSupport
# | `-- ActiveSupport::Base
# `-- Rails
#
# A logger inherits its log level from its parent. This level can be set for
# each logger in the system. Setting the level on a logger affects all it's
# children and grandchildren, etc. unless the child has it's own level set.
#
# Loggers also have a property called "additivity", and by default it is set
# to true for all loggers. This property enables a logger to pass log events
# up to its parent.
#
# If a logger does not have an appender and its additivity is true, it will
# pass all log events up to its parent who will then try to send the log
# event to its appenders. The parent will do the same thing, passing the log
# event up the chain till the root logger is reached or some parent logger
# has its additivity set to false.
#
# So, if the root logger is the only one with an appender, all loggers can
# still output log events to the appender because of additivity. A logger
# will ALWAYS send log events to its own appenders regardless of its
# additivity.
#
# The show_configuration method can be used to dump the logging hierarchy.
#
require 'logging'
Logging.logger.root.level = :debug
foo = Logging.logger['Foo']
bar = Logging.logger['Foo::Bar']
baz = Logging.logger['Foo::Baz']
# configure the Foo logger
foo.level = 'warn'
foo.appenders = Logging.appenders.stdout
# since Foo is the parent of Foo::Bar and Foo::Baz, these loggers all have
# their level set to warn
foo.warn 'this is a warning, not a ticket'
bar.info 'this message will not be logged'
baz.info 'nor will this message'
bar.error 'but this error message will be logged'
# let's demonstrate additivity of loggers
Logging.logger.root.appenders = Logging.appenders.stdout
baz.warn 'this message will be logged twice - once by Foo and once by root'
foo.additive = false
bar.warn "foo is no longer passing log events up to it's parent"
# let's look at the logger hierarchy
puts '='*76
Logging.show_configuration
# :startdoc:
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/socket/test_udp.rb
|
<filename>.rvm/src/ruby-2.3.0/test/socket/test_udp.rb<gh_stars>10-100
# frozen_string_literal: true
begin
require "socket"
require "test/unit"
rescue LoadError
end
class TestSocket_UDPSocket < Test::Unit::TestCase
def test_open
assert_nothing_raised { UDPSocket.open {} }
assert_nothing_raised { UDPSocket.open(Socket::AF_INET) {} }
assert_nothing_raised { UDPSocket.open("AF_INET") {} }
assert_nothing_raised { UDPSocket.open(:AF_INET) {} }
end
def test_connect
s = UDPSocket.new
host = Object.new
class << host; self end.send(:define_method, :to_str) {
s.close
"127.0.0.1"
}
assert_raise(IOError, "[ruby-dev:25045]") {
s.connect(host, 1)
}
end
def test_bind
s = UDPSocket.new
host = Object.new
class << host; self end.send(:define_method, :to_str) {
s.close
"127.0.0.1"
}
assert_raise(IOError, "[ruby-dev:25057]") {
s.bind(host, 2000)
}
ensure
s.close if s && !s.closed?
end
def test_bind_addrinuse
host = "127.0.0.1"
in_use = UDPSocket.new
in_use.bind(host, 0)
port = in_use.addr[1]
s = UDPSocket.new
e = assert_raise(Errno::EADDRINUSE) do
s.bind(host, port)
end
assert_match "bind(2) for \"#{host}\" port #{port}", e.message
ensure
in_use.close if in_use
s.close if s
end
def test_send_too_long
u = UDPSocket.new
e = assert_raise(Errno::EMSGSIZE) do
u.send "\0" * 100_000, 0, "127.0.0.1", 7 # echo
end
assert_match 'for "127.0.0.1" port 7', e.message
ensure
u.close if u
end
def test_bind_no_memory_leak
assert_no_memory_leak(["-rsocket"], <<-"end;", <<-"end;", rss: true)
s = UDPSocket.new
s.close
end;
100_000.times {begin s.bind("127.0.0.1", 1) rescue IOError; end}
end;
end
def test_connect_no_memory_leak
assert_no_memory_leak(["-rsocket"], <<-"end;", <<-"end;", rss: true)
s = UDPSocket.new
s.close
end;
100_000.times {begin s.connect("127.0.0.1", 1) rescue IOError; end}
end;
end
def test_send_no_memory_leak
assert_no_memory_leak(["-rsocket"], <<-"end;", <<-"end;", rss: true)
s = UDPSocket.new
s.close
end;
100_000.times {begin s.send("\0"*100, 0, "127.0.0.1", 1) rescue IOError; end}
end;
end
end if defined?(UDPSocket)
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/examples/rails4.rb
|
<gh_stars>100-1000
# :stopdoc:
#
# Rails 4 allows you to hook up multiple loggers (even those external to this gem)
# so you can use a single Rails.logger statement. For Rails developers, this is
# easier because if you ever change logging frameworks, you don't have to change
# all of your app code.
#
# See http://railsware.com/blog/2014/08/07/rails-logging-into-several-backends/
#
require 'logging'
log = Logging.logger(STDOUT)
log.level = :warn
Rails.logger.extend(ActiveSupport::Logger.broadcast(log))
Rails.logger.debug "this debug message will not be output by the logger"
Rails.logger.warn "this is your last warning"
# :startdoc:
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/lib/xmlrpc/httpserver.rb
|
#
# Implements a simple HTTP-server by using <NAME> (<EMAIL>)
# ruby-generic-server.
#
# Copyright (C) 2001, 2002, 2003 by <NAME> (<EMAIL>)
#
# $Id: httpserver.rb 29726 2010-11-08 20:59:01Z marcandre $
#
require "gserver"
class HttpServer < GServer
##
# handle_obj specifies the object, that receives calls to request_handler
# and ip_auth_handler
def initialize(handle_obj, port = 8080, host = DEFAULT_HOST, maxConnections = 4,
stdlog = $stdout, audit = true, debug = true)
@handler = handle_obj
super(port, host, maxConnections, stdlog, audit, debug)
end
private
# Constants -----------------------------------------------
CRLF = "\r\n"
HTTP_PROTO = "HTTP/1.0"
SERVER_NAME = "HttpServer (Ruby #{RUBY_VERSION})"
DEFAULT_HEADER = {
"Server" => SERVER_NAME
}
##
# Mapping of status code and error message
#
StatusCodeMapping = {
200 => "OK",
400 => "Bad Request",
403 => "Forbidden",
405 => "Method Not Allowed",
411 => "Length Required",
500 => "Internal Server Error"
}
# Classes -------------------------------------------------
class Request
attr_reader :data, :header, :method, :path, :proto
def initialize(data, method=nil, path=nil, proto=nil)
@header, @data = Table.new, data
@method, @path, @proto = method, path, proto
end
def content_length
len = @header['Content-Length']
return nil if len.nil?
return len.to_i
end
end
class Response
attr_reader :header
attr_accessor :body, :status, :status_message
def initialize(status=200)
@status = status
@status_message = nil
@header = Table.new
end
end
##
# a case-insensitive Hash class for HTTP header
#
class Table
include Enumerable
def initialize(hash={})
@hash = hash
update(hash)
end
def [](key)
@hash[key.to_s.capitalize]
end
def []=(key, value)
@hash[key.to_s.capitalize] = value
end
def update(hash)
hash.each {|k,v| self[k] = v}
self
end
def each
@hash.each {|k,v| yield k.capitalize, v }
end
def writeTo(port)
each { |k,v| port << "#{k}: #{v}" << CRLF }
end
end # class Table
# Helper Methods ------------------------------------------
def http_header(header=nil)
new_header = Table.new(DEFAULT_HEADER)
new_header.update(header) unless header.nil?
new_header["Connection"] = "close"
new_header["Date"] = http_date(Time.now)
new_header
end
def http_date( aTime )
aTime.gmtime.strftime( "%a, %d %b %Y %H:%M:%S GMT" )
end
def http_resp(status_code, status_message=nil, header=nil, body=nil)
status_message ||= StatusCodeMapping[status_code]
str = ""
str << "#{HTTP_PROTO} #{status_code} #{status_message}" << CRLF
http_header(header).writeTo(str)
str << CRLF
str << body unless body.nil?
str
end
# Main Serve Loop -----------------------------------------
def serve(io)
# perform IP authentification
unless @handler.ip_auth_handler(io)
io << http_resp(403, "Forbidden")
return
end
# parse first line
if io.gets =~ /^(\S+)\s+(\S+)\s+(\S+)/
request = Request.new(io, $1, $2, $3)
else
io << http_resp(400, "Bad Request")
return
end
# parse HTTP headers
while (line=io.gets) !~ /^(\n|\r)/
if line =~ /^([\w-]+):\s*(.*)$/
request.header[$1] = $2.strip
end
end
io.binmode
response = Response.new
# execute request handler
@handler.request_handler(request, response)
# write response back to the client
io << http_resp(response.status, response.status_message,
response.header, response.body)
rescue Exception
io << http_resp(500, "Internal Server Error")
end
end # class HttpServer
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/psych/lib/psych/handler.rb
|
module Psych
###
# Psych::Handler is an abstract base class that defines the events used
# when dealing with Psych::Parser. Clients who want to use Psych::Parser
# should implement a class that inherits from Psych::Handler and define
# events that they can handle.
#
# Psych::Handler defines all events that Psych::Parser can possibly send to
# event handlers.
#
# See Psych::Parser for more details
class Handler
###
# Configuration options for dumping YAML.
class DumperOptions
attr_accessor :line_width, :indentation, :canonical
def initialize
@line_width = 0
@indentation = 2
@canonical = false
end
end
# Default dumping options
OPTIONS = DumperOptions.new
###
# Called with +encoding+ when the YAML stream starts. This method is
# called once per stream. A stream may contain multiple documents.
#
# See the constants in Psych::Parser for the possible values of +encoding+.
def start_stream encoding
end
###
# Called when the document starts with the declared +version+,
# +tag_directives+, if the document is +implicit+.
#
# +version+ will be an array of integers indicating the YAML version being
# dealt with, +tag_directives+ is a list of tuples indicating the prefix
# and suffix of each tag, and +implicit+ is a boolean indicating whether
# the document is started implicitly.
#
# === Example
#
# Given the following YAML:
#
# %YAML 1.1
# %TAG ! tag:tenderlovemaking.com,2009:
# --- !squee
#
# The parameters for start_document must be this:
#
# version # => [1, 1]
# tag_directives # => [["!", "tag:tenderlovemaking.com,2009:"]]
# implicit # => false
def start_document version, tag_directives, implicit
end
###
# Called with the document ends. +implicit+ is a boolean value indicating
# whether or not the document has an implicit ending.
#
# === Example
#
# Given the following YAML:
#
# ---
# hello world
#
# +implicit+ will be true. Given this YAML:
#
# ---
# hello world
# ...
#
# +implicit+ will be false.
def end_document implicit
end
###
# Called when an alias is found to +anchor+. +anchor+ will be the name
# of the anchor found.
#
# === Example
#
# Here we have an example of an array that references itself in YAML:
#
# --- &ponies
# - first element
# - *ponies
#
# &ponies is the achor, *ponies is the alias. In this case, alias is
# called with "ponies".
def alias anchor
end
###
# Called when a scalar +value+ is found. The scalar may have an
# +anchor+, a +tag+, be implicitly +plain+ or implicitly +quoted+
#
# +value+ is the string value of the scalar
# +anchor+ is an associated anchor or nil
# +tag+ is an associated tag or nil
# +plain+ is a boolean value
# +quoted+ is a boolean value
# +style+ is an integer idicating the string style
#
# See the constants in Psych::Nodes::Scalar for the possible values of
# +style+
#
# === Example
#
# Here is a YAML document that exercises most of the possible ways this
# method can be called:
#
# ---
# - !str "foo"
# - &anchor fun
# - many
# lines
# - |
# many
# newlines
#
# The above YAML document contains a list with four strings. Here are
# the parameters sent to this method in the same order:
#
# # value anchor tag plain quoted style
# ["foo", nil, "!str", false, false, 3 ]
# ["fun", "anchor", nil, true, false, 1 ]
# ["many lines", nil, nil, true, false, 1 ]
# ["many\nnewlines\n", nil, nil, false, true, 4 ]
#
def scalar value, anchor, tag, plain, quoted, style
end
###
# Called when a sequence is started.
#
# +anchor+ is the anchor associated with the sequence or nil.
# +tag+ is the tag associated with the sequence or nil.
# +implicit+ a boolean indicating whether or not the sequence was implicitly
# started.
# +style+ is an integer indicating the list style.
#
# See the constants in Psych::Nodes::Sequence for the possible values of
# +style+.
#
# === Example
#
# Here is a YAML document that exercises most of the possible ways this
# method can be called:
#
# ---
# - !!seq [
# a
# ]
# - &pewpew
# - b
#
# The above YAML document consists of three lists, an outer list that
# contains two inner lists. Here is a matrix of the parameters sent
# to represent these lists:
#
# # anchor tag implicit style
# [nil, nil, true, 1 ]
# [nil, "tag:yaml.org,2002:seq", false, 2 ]
# ["pewpew", nil, true, 1 ]
def start_sequence anchor, tag, implicit, style
end
###
# Called when a sequence ends.
def end_sequence
end
###
# Called when a map starts.
#
# +anchor+ is the anchor associated with the map or +nil+.
# +tag+ is the tag associated with the map or +nil+.
# +implicit+ is a boolean indicating whether or not the map was implicitly
# started.
# +style+ is an integer indicating the mapping style.
#
# See the constants in Psych::Nodes::Mapping for the possible values of
# +style+.
#
# === Example
#
# Here is a YAML document that exercises most of the possible ways this
# method can be called:
#
# ---
# k: !!map { hello: world }
# v: &pewpew
# hello: world
#
# The above YAML document consists of three maps, an outer map that contains
# two inner maps. Below is a matrix of the parameters sent in order to
# represent these three maps:
#
# # anchor tag implicit style
# [nil, nil, true, 1 ]
# [nil, "tag:yaml.org,2002:map", false, 2 ]
# ["pewpew", nil, true, 1 ]
def start_mapping anchor, tag, implicit, style
end
###
# Called when a map ends
def end_mapping
end
###
# Called when an empty event happens. (Which, as far as I can tell, is
# never).
def empty
end
###
# Called when the YAML stream ends
def end_stream
end
###
# Is this handler a streaming handler?
def streaming?
false
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tk/entry.rb
|
#
# tk/entry.rb - Tk entry classes
# by <NAME> <<EMAIL>>
require 'tk'
require 'tk/label'
require 'tk/scrollable'
require 'tk/validation'
class Tk::Entry<Tk::Label
include X_Scrollable
include TkValidation
TkCommandNames = ['entry'.freeze].freeze
WidgetClassName = 'Entry'.freeze
WidgetClassNames[WidgetClassName] ||= self
#def create_self(keys)
# super(__conv_vcmd_on_hash_kv(keys))
#end
#private :create_self
def __strval_optkeys
super() + ['show', 'disabledbackground', 'readonlybackground']
end
private :__strval_optkeys
def bbox(index)
list(tk_send_without_enc('bbox', index))
end
def cursor
number(tk_send_without_enc('index', 'insert'))
end
alias icursor cursor
def cursor=(index)
tk_send_without_enc('icursor', index)
#self
index
end
alias icursor= cursor=
def index(idx)
number(tk_send_without_enc('index', idx))
end
def insert(pos,text)
tk_send_without_enc('insert', pos, _get_eval_enc_str(text))
self
end
def delete(first, last=None)
tk_send_without_enc('delete', first, last)
self
end
def mark(pos)
tk_send_without_enc('scan', 'mark', pos)
self
end
def dragto(pos)
tk_send_without_enc('scan', 'dragto', pos)
self
end
def selection_adjust(index)
tk_send_without_enc('selection', 'adjust', index)
self
end
def selection_clear
tk_send_without_enc('selection', 'clear')
self
end
def selection_from(index)
tk_send_without_enc('selection', 'from', index)
self
end
def selection_present()
bool(tk_send_without_enc('selection', 'present'))
end
def selection_range(s, e)
tk_send_without_enc('selection', 'range', s, e)
self
end
def selection_to(index)
tk_send_without_enc('selection', 'to', index)
self
end
def invoke_validate
bool(tk_send_without_enc('validate'))
end
def validate(mode = nil)
if mode
configure 'validate', mode
else
invoke_validate
end
end
def value
_fromUTF8(tk_send_without_enc('get'))
end
def value= (val)
tk_send_without_enc('delete', 0, 'end')
tk_send_without_enc('insert', 0, _get_eval_enc_str(val))
val
end
alias get value
alias set value=
def [](*args)
self.value[*args]
end
def []=(*args)
val = args.pop
str = self.value
str[*args] = val
self.value = str
val
end
end
#TkEntry = Tk::Entry unless Object.const_defined? :TkEntry
#Tk.__set_toplevel_aliases__(:Tk, Tk::Entry, :TkEntry)
Tk.__set_loaded_toplevel_aliases__('tk/entry.rb', :Tk, Tk::Entry, :TkEntry)
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tk/root.rb
|
#
# tk/root.rb : treat root widget
#
require 'tk'
require 'tk/wm'
require 'tk/menuspec'
class Tk::Root<TkWindow
include Wm
include TkMenuSpec
def __methodcall_optkeys # { key=>method, ... }
TOPLEVEL_METHODCALL_OPTKEYS
end
private :__methodcall_optkeys
def Root.new(keys=nil, &b)
unless TkCore::INTERP.tk_windows['.']
TkCore::INTERP.tk_windows['.'] =
super(:without_creating=>true, :widgetname=>'.'){}
end
root = TkCore::INTERP.tk_windows['.']
keys = _symbolkey2str(keys)
# wm commands
root.instance_eval{
__methodcall_optkeys.each{|key, method|
value = keys.delete(key.to_s)
self.__send__(method, value) if value
}
}
if keys # wm commands ( for backward comaptibility )
keys.each{|k,v|
if v.kind_of? Array
root.__send__(k,*v)
else
root.__send__(k,v)
end
}
end
if block_given?
if TkCore::WITH_RUBY_VM ### Ruby 1.9 !!!!
root.instance_exec(root, &b)
else
root.instance_eval(&b)
end
end
root
end
WidgetClassName = 'Tk'.freeze
WidgetClassNames[WidgetClassName] ||= self
def self.to_eval
# self::WidgetClassName
'.'
end
def create_self
@path = '.'
end
private :create_self
def path
"."
end
def add_menu(menu_info, tearoff=false, opts=nil)
# See tk/menuspec.rb for menu_info.
# opts is a hash of default configs for all of cascade menus.
# Configs of menu_info can override it.
if tearoff.kind_of?(Hash)
opts = tearoff
tearoff = false
end
_create_menubutton(self, menu_info, tearoff, opts)
end
def add_menubar(menu_spec, tearoff=false, opts=nil)
# See tk/menuspec.rb for menu_spec.
# opts is a hash of default configs for all of cascade menus.
# Configs of menu_spec can override it.
menu_spec.each{|info| add_menu(info, tearoff, opts)}
self.menu
end
def Root.destroy
TkCore::INTERP._invoke('destroy', '.')
end
end
TkRoot = Tk::Root unless Object.const_defined? :TkRoot
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/little-plugger-1.1.4/spec/little-plugger_spec.rb
|
require File.join(File.dirname(__FILE__), %w[spec_helper])
describe LittlePlugger do
it "converts a string from camel-case to underscore" do
expect(LittlePlugger.underscore('FooBarBaz')).to eq('foo_bar_baz')
expect(LittlePlugger.underscore('CouchDB')).to eq('couch_db')
expect(LittlePlugger.underscore('FOOBar')).to eq('foo_bar')
expect(LittlePlugger.underscore('Foo::Bar::BazBuz')).to eq('foo/bar/baz_buz')
end
it "generates a default plugin path" do
expect(LittlePlugger.default_plugin_path(LittlePlugger)).to eq('little_plugger/plugins')
expect(LittlePlugger.default_plugin_path(Process::Status)).to eq('process/status/plugins')
end
it "generates a default plugin module" do
expect(LittlePlugger.default_plugin_module('little_plugger')).to eq(LittlePlugger)
expect {LittlePlugger.default_plugin_module('little_plugger/plugins')}.to \
raise_error(NameError, /uninitialized constant (LittlePlugger::)?Plugins/)
expect(LittlePlugger.default_plugin_module('process/status')).to eq(Process::Status)
end
end
# EOF
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/net-ssh-multi-1.2.0/lib/net/ssh/multi/session_actions.rb
|
module Net; module SSH; module Multi
# This module represents the actions that are available on session
# collections. Any class that includes this module needs only provide a
# +servers+ method that returns a list of Net::SSH::Multi::Server
# instances, and the rest just works. See Net::SSH::Multi::Session and
# Net::SSH::Multi::Subsession for consumers of this module.
module SessionActions
# Returns the session that is the "master". This defaults to +self+, but
# classes that include this module may wish to change this if they are
# subsessions that depend on a master session.
def master
self
end
# Connections are normally established lazily, as soon as they are needed.
# This method forces all servers in the current container to have their
# connections established immediately, blocking until the connections have
# been made.
def connect!
sessions
self
end
# Returns +true+ if any server in the current container has an open SSH
# session that is currently processing any channels. If +include_invisible+
# is +false+ (the default) then invisible channels (such as those created
# by port forwarding) will not be counted; otherwise, they will be.
def busy?(include_invisible=false)
servers.any? { |server| server.busy?(include_invisible) }
end
# Returns an array of all SSH sessions, blocking until all sessions have
# connected.
def sessions
threads = servers.map { |server| Thread.new { server.session(true) } if server.session.nil? }
threads.each { |thread| thread.join if thread }
servers.map { |server| server.session }.compact
end
# Sends a global request to the sessions for all contained servers
# (see #sessions). This can be used to (e.g.) ping the remote servers to
# prevent them from timing out.
#
# session.send_global_request("<EMAIL>")
#
# If a block is given, it will be invoked when the server responds, with
# two arguments: the Net::SSH connection that is responding, and a boolean
# indicating whether the request succeeded or not.
def send_global_request(type, *extra, &callback)
sessions.each { |ssh| ssh.send_global_request(type, *extra, &callback) }
self
end
# Asks all sessions for all contained servers (see #sessions) to open a
# new channel. When each server responds, the +on_confirm+ block will be
# invoked with a single argument, the channel object for that server. This
# means that the block will be invoked one time for each session.
#
# All new channels will be collected and returned, aggregated into a new
# Net::SSH::Multi::Channel instance.
#
# Note that the channels are "enhanced" slightly--they have two properties
# set on them automatically, to make dealing with them in a multi-session
# environment slightly easier:
#
# * :server => the Net::SSH::Multi::Server instance that spawned the channel
# * :host => the host name of the server
#
# Having access to these things lets you more easily report which host
# (e.g.) data was received from:
#
# session.open_channel do |channel|
# channel.exec "command" do |ch, success|
# ch.on_data do |ch, data|
# puts "got data #{data} from #{ch[:host]}"
# end
# end
# end
def open_channel(type="session", *extra, &on_confirm)
channels = sessions.map do |ssh|
ssh.open_channel(type, *extra) do |c|
c[:server] = c.connection[:server]
c[:host] = c.connection[:server].host
on_confirm[c] if on_confirm
end
end
Multi::Channel.new(master, channels)
end
# A convenience method for executing a command on multiple hosts and
# either displaying or capturing the output. It opens a channel on all
# active sessions (see #open_channel and #active_sessions), and then
# executes a command on each channel (Net::SSH::Connection::Channel#exec).
#
# If a block is given, it will be invoked whenever data is received across
# the channel, with three arguments: the channel object, a symbol identifying
# which output stream the data was received on (+:stdout+ or +:stderr+)
# and a string containing the data that was received:
#
# session.exec("command") do |ch, stream, data|
# puts "[#{ch[:host]} : #{stream}] #{data}"
# end
#
# If no block is given, all output will be written to +$stdout+ or
# +$stderr+, as appropriate.
#
# Note that #exec will also capture the exit status of the process in the
# +:exit_status+ property of each channel. Since #exec returns all of the
# channels in a Net::SSH::Multi::Channel object, you can check for the
# exit status like this:
#
# channel = session.exec("command") { ... }
# channel.wait
#
# if channel.any? { |c| c[:exit_status] != 0 }
# puts "executing failed on at least one host!"
# end
def exec(command, &block)
open_channel do |channel|
channel.exec(command) do |ch, success|
raise "could not execute command: #{command.inspect} (#{ch[:host]})" unless success
channel.on_data do |ch, data|
if block
block.call(ch, :stdout, data)
else
data.chomp.each_line do |line|
$stdout.puts("[#{ch[:host]}] #{line}")
end
end
end
channel.on_extended_data do |ch, type, data|
if block
block.call(ch, :stderr, data)
else
data.chomp.each_line do |line|
$stderr.puts("[#{ch[:host]}] #{line}")
end
end
end
channel.on_request("exit-status") do |ch, data|
ch[:exit_status] = data.read_long
end
end
end
end
end
end; end; end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/examples/loggers.rb
|
# :stopdoc:
#
# Multiple loggers can be created and each can be configured with it's own
# log level and appenders. So one logger can be configured to output debug
# messages, and all the others can be left at the info or warn level. This
# makes it easier to debug specific portions of your code.
#
require 'logging'
# all loggers inherit the log level of the "root" logger
# but specific loggers can be given their own level
Logging.logger.root.level = :warn
# similarly, the root appender will be used by all loggers
Logging.logger.root.appenders = Logging.appenders.file('output.log')
log1 = Logging.logger['Log1']
log2 = Logging.logger['Log2']
log3 = Logging.logger['Log3']
# you can use strings or symbols to set the log level
log3.level = 'debug'
log1.info "this message will not get logged"
log2.info "nor will this message"
log3.info "but this message will get logged"
# :startdoc:
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/rubyntlm-0.6.0/lib/net/ntlm/message/type0.rb
|
<filename>.rvm/gems/ruby-2.3.0/gems/rubyntlm-0.6.0/lib/net/ntlm/message/type0.rb
module Net
module NTLM
class Message
# sub class definitions
class Type0 < Message
string :sign, {:size => 8, :value => SSP_SIGN}
int32LE :type, {:value => 0}
end
end
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/lib/logging/utils.rb
|
<reponame>arnab0073/idea
require 'thread'
require 'rbconfig'
# --------------------------------------------------------------------------
class String
# call-seq:
# shrink( width, ellipses = '...' ) #=> string
#
# Shrink the size of the current string to the given _width_ by removing
# characters from the middle of the string and replacing them with
# _ellipses_. If the _width_ is greater than the length of the string, the
# string is returned unchanged. If the _width_ is less than the length of
# the _ellipses_, then the _ellipses_ are returned.
#
def shrink( width, ellipses = '...')
raise ArgumentError, "width cannot be negative: #{width}" if width < 0
return self if length <= width
remove = length - width + ellipses.length
return ellipses.dup if remove >= length
left_end = (length + 1 - remove) / 2
right_start = left_end + remove
left = self[0,left_end]
right = self[right_start,length-right_start]
left << ellipses << right
end
end
# --------------------------------------------------------------------------
class Module
# call-seq:
# logger_name #=> string
#
# Returns a predictable logger name for the current module or class. If
# used within an anonymous class, the first non-anonymous class name will
# be used as the logger name. If used within a meta-class, the name of the
# actual class will be used as the logger name. If used within an
# anonymous module, the string 'anonymous' will be returned.
#
def logger_name
return name unless name.nil? or name.empty?
# check if this is a metaclass (or eigenclass)
if ancestors.include? Class
inspect =~ %r/#<Class:([^#>]+)>/
return $1
end
# see if we have a superclass
if respond_to? :superclass
return superclass.logger_name
end
# we are an anonymous module
::Logging.log_internal(-2) {
'cannot return a predictable, unique name for anonymous modules'
}
return 'anonymous'
end
end
# --------------------------------------------------------------------------
class File
# Returns <tt>true</tt> if another process holds an exclusive lock on the
# file. Returns <tt>false</tt> if this is not the case.
#
# If a <tt>block</tt> of code is passed to this method, it will be run iff
# this process can obtain an exclusive lock on the file. The block will be
# run while this lock is held, and the exclusive lock will be released when
# the method returns.
#
# The exclusive lock is requested in a non-blocking mode. This method will
# return immediately (and the block will not be executed) if an exclusive
# lock cannot be obtained.
#
def flock?
status = flock(LOCK_EX|LOCK_NB)
case status
when false; true
when 0; block_given? ? yield : false
else
raise SystemCallError, "flock failed with status: #{status}"
end
ensure
flock LOCK_UN
end
# Execute a <tt>block</tt> in the context of a shared lock on this file. A
# shared lock will be obtained on the file, the block executed, and the lock
# released.
#
def flock_sh
flock LOCK_SH
yield
ensure
flock LOCK_UN
end
# :stopdoc:
conf = defined?(RbConfig) ? RbConfig::CONFIG : Config::CONFIG
if conf['host_os'] =~ /mswin|windows|cygwin|mingw/i
# don't lock files on windows
undef :flock?, :flock_sh
def flock?() yield; end
def flock_sh() yield; end
end
# :startdoc:
end
# --------------------------------------------------------------------------
module FileUtils
# Concatenate the contents of the _src_ file to the end of the _dest_ file.
# If the _dest_ file does not exist, then the _src_ file is copied to the
# _dest_ file using +copy_file+.
#
def concat( src, dest )
if File.exist?(dest)
bufsize = File.stat(dest).blksize || 8192
buffer = String.new
File.open(dest, 'a') { |d|
File.open(src, 'r') { |r|
while bytes = r.read(bufsize, buffer)
d.syswrite bytes
end
}
}
else
copy_file(src, dest)
end
end
module_function :concat
end
# --------------------------------------------------------------------------
class ReentrantMutex < Mutex
def initialize
super
@locker = nil
end
alias_method :original_synchronize, :synchronize
def synchronize
if @locker == Thread.current
yield
else
original_synchronize {
begin
@locker = Thread.current
yield
ensure
@locker = nil
end
}
end
end
end # ReentrantMutex
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/blt.rb
|
#
# BLT support
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tk/variable'
# call setup script for general 'tkextlib' libraries
require 'tkextlib/setup.rb'
# call setup script
require 'tkextlib/blt/setup.rb'
# load all image format handlers
#TkPackage.require('BLT', '2.4')
TkPackage.require('BLT')
module Tk
module BLT
TkComm::TkExtlibAutoloadModule.unshift(self)
# Require autoload-symbols which is a same name as widget classname.
# Those are used at TkComm._genobj_for_tkwidget method.
extend TkCore
VERSION = tk_call('set', 'blt_version')
PATCH_LEVEL = tk_call('set', 'blt_patchLevel')
begin
lib = TkCore::INTERP._invoke('set', 'blt_library')
rescue
lib = ''
end
LIBRARY = TkVarAccess.new('blt_library', lib)
begin
lib = TkCore::INTERP._invoke('set', 'blt_libPath')
rescue
lib = ''
end
LIB_PATH = TkVarAccess.new('blt_libPath', lib)
PACKAGE_NAME = 'BLT'.freeze
def self.package_name
PACKAGE_NAME
end
def self.package_version
begin
TkPackage.require('BLT')
rescue
''
end
end
####################################################
def self.beep(percent = 50)
tk_call('::blt::beep', percent)
end
def self.bgexec(*args)
if args[0].kind_of?(TkVariable)
var = args.shift
else
var = TkVariable.new
end
params = [var]
params.concat(hash_kv(args.shift, true)) if args[0].kind_of?(Hash)
params << '--' if args[0] =~ /^\s*-[^-]/
params.concat(args)
tk_call('::blt::bgexec', *params)
var
end
def self.detach_bgexec(*args)
if args[0].kind_of?(TkVariable)
var = args.shift
else
var = TkVariable.new
end
params = [var]
params.concat(hash_kv(args.shift, true)) if args[0].kind_of?(Hash)
params << '--' if args[0] =~ /^\s*-[^-]/
params.concat(args)
params << '&'
[var, tk_split_list(tk_call('::blt::bgexec', *params))]
end
def self.bltdebug(lvl = nil)
if lvl
tk_call('::blt::bltdebug', lvl)
else
number(tk_call('::blt::bltdebug'))
end
end
def self.crc32_file(name)
tk_call_without_enc('::blt::crc32', name)
end
def self.crc32_data(dat)
tk_call_without_enc('::blt::crc32', '-data', dat)
end
####################################################
def self.active_legend(graph)
tk_call_without_enc('Blt_ActiveLegend', graph)
end
def self.crosshairs(graph)
tk_call_without_enc('Blt_Crosshairs', graph)
end
def self.zoom_stack(graph)
tk_call_without_enc('Blt_ZoomStack', graph)
end
def self.print_key(graph)
tk_call_without_enc('Blt_PrintKey', graph)
end
def self.closest_point(graph)
tk_call_without_enc('Blt_ClosestPoint', graph)
end
module GraphCommand
def active_legend
tk_call_without_enc('Blt_ActiveLegend', @path)
self
end
def crosshairs
tk_call_without_enc('Blt_Crosshairs', @path)
self
end
def zoom_stack
tk_call_without_enc('Blt_ZoomStack', @path)
self
end
def print_key
tk_call_without_enc('Blt_PrintKey', @path)
self
end
def closest_point
tk_call_without_enc('Blt_ClosestPoint', @path)
self
end
end
####################################################
autoload :PlotComponent,'tkextlib/blt/component.rb'
autoload :Barchart, 'tkextlib/blt/barchart.rb'
autoload :Bitmap, 'tkextlib/blt/bitmap.rb'
autoload :Busy, 'tkextlib/blt/busy.rb'
autoload :Container, 'tkextlib/blt/container.rb'
autoload :CutBuffer, 'tkextlib/blt/cutbuffer.rb'
autoload :DragDrop, 'tkextlib/blt/dragdrop.rb'
autoload :EPS, 'tkextlib/blt/eps.rb'
autoload :Htext, 'tkextlib/blt/htext.rb'
autoload :Graph, 'tkextlib/blt/graph.rb'
autoload :Spline, 'tkextlib/blt/spline.rb'
autoload :Stripchart, 'tkextlib/blt/stripchart.rb'
autoload :Table, 'tkextlib/blt/table.rb'
autoload :Tabnotebook, 'tkextlib/blt/tabnotebook.rb'
autoload :Tabset, 'tkextlib/blt/tabset.rb'
autoload :Ted, 'tkextlib/blt/ted.rb'
autoload :Tile, 'tkextlib/blt/tile.rb'
autoload :Tree, 'tkextlib/blt/tree.rb'
autoload :TreeView, 'tkextlib/blt/treeview.rb'
autoload :Hiertable, 'tkextlib/blt/treeview.rb'
# Hierbox is obsolete
autoload :Vector, 'tkextlib/blt/vector.rb'
autoload :VectorAccess, 'tkextlib/blt/vector.rb'
autoload :Watch, 'tkextlib/blt/watch.rb'
autoload :Winop, 'tkextlib/blt/winop.rb'
autoload :WinOp, 'tkextlib/blt/winop.rb'
# Unix only
autoload :DnD, 'tkextlib/blt/unix_dnd.rb'
# Windows only
autoload :Printer, 'tkextlib/blt/win_printer.rb'
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/lib/xmlrpc/server.rb
|
<gh_stars>0
=begin
= xmlrpc/server.rb
Copyright (C) 2001, 2002, 2003, 2005 by <NAME> (<EMAIL>)
Released under the same term of license as Ruby.
= Classes
* ((<XMLRPC::BasicServer>))
* ((<XMLRPC::CGIServer>))
* ((<XMLRPC::ModRubyServer>))
* ((<XMLRPC::Server>))
* ((<XMLRPC::WEBrickServlet>))
= XMLRPC::BasicServer
== Description
Is the base class for all XML-RPC server-types (CGI, standalone).
You can add handler and set a default handler.
Do not use this server, as this is/should be an abstract class.
=== How the method to call is found
The arity (number of accepted arguments) of a handler (method or (({Proc})) object) is
compared to the given arguments submitted by the client for a RPC ((-Remote Procedure Call-)).
A handler is only called if it accepts the number of arguments, otherwise the search
for another handler will go on. When at the end no handler was found,
the ((<default_handler|XMLRPC::BasicServer#set_default_handler>)) will be called.
With this technique it is possible to do overloading by number of parameters, but
only for (({Proc})) handler, because you cannot define two methods of the same name in
the same class.
== Class Methods
--- XMLRPC::BasicServer.new( class_delim="." )
Creates a new (({XMLRPC::BasicServer})) instance, which should not be
done, because (({XMLRPC::BasicServer})) is an abstract class. This
method should be called from a subclass indirectly by a (({super})) call
in the method (({initialize})). The paramter ((|class_delim|)) is used
in ((<add_handler|XMLRPC::BasicServer#add_handler>)) when an object is
added as handler, to delimit the object-prefix and the method-name.
== Instance Methods
--- XMLRPC::BasicServer#add_handler( name, signature=nil, help=nil ) { aBlock }
Adds ((|aBlock|)) to the list of handlers, with ((|name|)) as the name of the method.
Parameters ((|signature|)) and ((|help|)) are used by the Introspection method if specified,
where ((|signature|)) is either an Array containing strings each representing a type of it's
signature (the first is the return value) or an Array of Arrays if the method has multiple
signatures. Value type-names are "int, boolean, double, string, dateTime.iso8601, base64, array, struct".
Parameter ((|help|)) is a String with informations about how to call this method etc.
A handler method or code-block can return the types listed at
((<XMLRPC::Client#call|URL:client.html#index:0>)).
When a method fails, it can tell it the client by throwing an
(({XMLRPC::FaultException})) like in this example:
s.add_handler("michael.div") do |a,b|
if b == 0
raise XMLRPC::FaultException.new(1, "division by zero")
else
a / b
end
end
The client gets in the case of (({b==0})) an object back of type
(({XMLRPC::FaultException})) that has a ((|faultCode|)) and ((|faultString|))
field.
--- XMLRPC::BasicServer#add_handler( prefix, obj )
This is the second form of ((<add_handler|XMLRPC::BasicServer#add_handler>)).
To add an object write:
server.add_handler("michael", MyHandlerClass.new)
All public methods of (({MyHandlerClass})) are accessible to
the XML-RPC clients by (('michael."name of method"')). This is
where the ((|class_delim|)) in ((<new|XMLRPC::BasicServer.new>))
has it's role, a XML-RPC method-name is defined by
((|prefix|)) + ((|class_delim|)) + (('"name of method"')).
--- XMLRPC::BasicServer#add_handler( interface, obj )
This is the third form of ((<add_handler|XMLRPC::BasicServer#add_handler>)).
Use (({XMLRPC::interface})) to generate an ServiceInterface object, which
represents an interface (with signature and help text) for a handler class.
Parameter ((|interface|)) must be of type (({XMLRPC::ServiceInterface})).
Adds all methods of ((|obj|)) which are defined in ((|interface|)) to the
server.
This is the recommended way of adding services to a server!
--- XMLRPC::BasicServer#get_default_handler
Returns the default-handler, which is called when no handler for
a method-name is found.
It is a (({Proc})) object or (({nil})).
--- XMLRPC::BasicServer#set_default_handler ( &handler )
Sets ((|handler|)) as the default-handler, which is called when
no handler for a method-name is found. ((|handler|)) is a code-block.
The default-handler is called with the (XML-RPC) method-name as first argument, and
the other arguments are the parameters given by the client-call.
If no block is specified the default of (({XMLRPC::BasicServer})) is used, which raises a
XMLRPC::FaultException saying "method missing".
--- XMLRPC::BasicServer#set_writer( writer )
Sets the XML writer to use for generating XML output.
Should be an instance of a class from module (({XMLRPC::XMLWriter})).
If this method is not called, then (({XMLRPC::Config::DEFAULT_WRITER})) is used.
--- XMLRPC::BasicServer#set_parser( parser )
Sets the XML parser to use for parsing XML documents.
Should be an instance of a class from module (({XMLRPC::XMLParser})).
If this method is not called, then (({XMLRPC::Config::DEFAULT_PARSER})) is used.
--- XMLRPC::BasicServer#add_introspection
Adds the introspection handlers "system.listMethods", "system.methodSignature" and "system.methodHelp",
where only the first one works.
--- XMLRPC::BasicServer#add_multicall
Adds the multi-call handler "system.multicall".
--- XMLRPC::BasicServer#get_service_hook
Returns the service-hook, which is called on each service request (RPC) unless it's (({nil})).
--- XMLRPC::BasicServer#set_service_hook ( &handler )
A service-hook is called for each service request (RPC).
You can use a service-hook for example to wrap existing methods and catch exceptions of them or
convert values to values recognized by XMLRPC. You can disable it by passing (({nil})) as parameter
((|handler|)) .
The service-hook is called with a (({Proc})) object and with the parameters for this (({Proc})).
An example:
server.set_service_hook {|obj, *args|
begin
ret = obj.call(*args) # call the original service-method
# could convert the return value
rescue
# rescue exceptions
end
}
=end
require "xmlrpc/parser"
require "xmlrpc/create"
require "xmlrpc/config"
require "xmlrpc/utils" # ParserWriterChooseMixin
module XMLRPC
class BasicServer
include ParserWriterChooseMixin
include ParseContentType
ERR_METHOD_MISSING = 1
ERR_UNCAUGHT_EXCEPTION = 2
ERR_MC_WRONG_PARAM = 3
ERR_MC_MISSING_PARAMS = 4
ERR_MC_MISSING_METHNAME = 5
ERR_MC_RECURSIVE_CALL = 6
ERR_MC_WRONG_PARAM_PARAMS = 7
ERR_MC_EXPECTED_STRUCT = 8
def initialize(class_delim=".")
@handler = []
@default_handler = nil
@service_hook = nil
@class_delim = class_delim
@create = nil
@parser = nil
add_multicall if Config::ENABLE_MULTICALL
add_introspection if Config::ENABLE_INTROSPECTION
end
def add_handler(prefix, obj_or_signature=nil, help=nil, &block)
if block_given?
# proc-handler
@handler << [prefix, block, obj_or_signature, help]
else
if prefix.kind_of? String
# class-handler
raise ArgumentError, "Expected non-nil value" if obj_or_signature.nil?
@handler << [prefix + @class_delim, obj_or_signature]
elsif prefix.kind_of? XMLRPC::Service::BasicInterface
# class-handler with interface
# add all methods
@handler += prefix.get_methods(obj_or_signature, @class_delim)
else
raise ArgumentError, "Wrong type for parameter 'prefix'"
end
end
self
end
def get_service_hook
@service_hook
end
def set_service_hook(&handler)
@service_hook = handler
self
end
def get_default_handler
@default_handler
end
def set_default_handler (&handler)
@default_handler = handler
self
end
def add_multicall
add_handler("system.multicall", %w(array array), "Multicall Extension") do |arrStructs|
unless arrStructs.is_a? Array
raise XMLRPC::FaultException.new(ERR_MC_WRONG_PARAM, "system.multicall expects an array")
end
arrStructs.collect {|call|
if call.is_a? Hash
methodName = call["methodName"]
params = call["params"]
if params.nil?
multicall_fault(ERR_MC_MISSING_PARAMS, "Missing params")
elsif methodName.nil?
multicall_fault(ERR_MC_MISSING_METHNAME, "Missing methodName")
else
if methodName == "system.multicall"
multicall_fault(ERR_MC_RECURSIVE_CALL, "Recursive system.multicall forbidden")
else
unless params.is_a? Array
multicall_fault(ERR_MC_WRONG_PARAM_PARAMS, "Parameter params have to be an Array")
else
ok, val = call_method(methodName, *params)
if ok
# correct return value
[val]
else
# exception
multicall_fault(val.faultCode, val.faultString)
end
end
end
end
else
multicall_fault(ERR_MC_EXPECTED_STRUCT, "system.multicall expected struct")
end
}
end # end add_handler
self
end
def add_introspection
add_handler("system.listMethods",%w(array), "List methods available on this XML-RPC server") do
methods = []
@handler.each do |name, obj|
if obj.kind_of? Proc
methods << name
else
obj.class.public_instance_methods(false).each do |meth|
methods << "#{name}#{meth}"
end
end
end
methods
end
add_handler("system.methodSignature", %w(array string), "Returns method signature") do |meth|
sigs = []
@handler.each do |name, obj, sig|
if obj.kind_of? Proc and sig != nil and name == meth
if sig[0].kind_of? Array
# sig contains multiple signatures, e.g. [["array"], ["array", "string"]]
sig.each {|s| sigs << s}
else
# sig is a single signature, e.g. ["array"]
sigs << sig
end
end
end
sigs.uniq! || sigs # remove eventually duplicated signatures
end
add_handler("system.methodHelp", %w(string string), "Returns help on using this method") do |meth|
help = nil
@handler.each do |name, obj, sig, hlp|
if obj.kind_of? Proc and name == meth
help = hlp
break
end
end
help || ""
end
self
end
def process(data)
method, params = parser().parseMethodCall(data)
handle(method, *params)
end
private # --------------------------------------------------------------
def multicall_fault(nr, str)
{"faultCode" => nr, "faultString" => str}
end
#
# method dispatch
#
def dispatch(methodname, *args)
for name, obj in @handler
if obj.kind_of? Proc
next unless methodname == name
else
next unless methodname =~ /^#{name}(.+)$/
next unless obj.respond_to? $1
obj = obj.method($1)
end
if check_arity(obj, args.size)
if @service_hook.nil?
return obj.call(*args)
else
return @service_hook.call(obj, *args)
end
end
end
if @default_handler.nil?
raise XMLRPC::FaultException.new(ERR_METHOD_MISSING, "Method #{methodname} missing or wrong number of parameters!")
else
@default_handler.call(methodname, *args)
end
end
#
# returns true, if the arity of "obj" matches
#
def check_arity(obj, n_args)
ary = obj.arity
if ary >= 0
n_args == ary
else
n_args >= (ary+1).abs
end
end
def call_method(methodname, *args)
begin
[true, dispatch(methodname, *args)]
rescue XMLRPC::FaultException => e
[false, e]
rescue Exception => e
[false, XMLRPC::FaultException.new(ERR_UNCAUGHT_EXCEPTION, "Uncaught exception #{e.message} in method #{methodname}")]
end
end
#
#
#
def handle(methodname, *args)
create().methodResponse(*call_method(methodname, *args))
end
end
=begin
= XMLRPC::CGIServer
== Synopsis
require "xmlrpc/server"
s = XMLRPC::CGIServer.new
s.add_handler("michael.add") do |a,b|
a + b
end
s.add_handler("michael.div") do |a,b|
if b == 0
raise XMLRPC::FaultException.new(1, "division by zero")
else
a / b
end
end
s.set_default_handler do |name, *args|
raise XMLRPC::FaultException.new(-99, "Method #{name} missing" +
" or wrong number of parameters!")
end
s.serve
== Description
Implements a CGI-based XML-RPC server.
== Superclass
((<XMLRPC::BasicServer>))
== Class Methods
--- XMLRPC::CGIServer.new( *a )
Creates a new (({XMLRPC::CGIServer})) instance. All parameters given
are by-passed to ((<XMLRPC::BasicServer.new>)). You can only create
((*one*)) (({XMLRPC::CGIServer})) instance, because more than one makes
no sense.
== Instance Methods
--- XMLRPC::CGIServer#serve
Call this after you have added all you handlers to the server.
This method processes a XML-RPC methodCall and sends the answer
back to the client.
Make sure that you don't write to standard-output in a handler, or in
any other part of your program, this would case a CGI-based server to fail!
=end
class CGIServer < BasicServer
@@obj = nil
def CGIServer.new(*a)
@@obj = super(*a) if @@obj.nil?
@@obj
end
def initialize(*a)
super(*a)
end
def serve
catch(:exit_serve) {
length = ENV['CONTENT_LENGTH'].to_i
http_error(405, "Method Not Allowed") unless ENV['REQUEST_METHOD'] == "POST"
http_error(400, "Bad Request") unless parse_content_type(ENV['CONTENT_TYPE']).first == "text/xml"
http_error(411, "Length Required") unless length > 0
# TODO: do we need a call to binmode?
$stdin.binmode if $stdin.respond_to? :binmode
data = $stdin.read(length)
http_error(400, "Bad Request") if data.nil? or data.bytesize != length
http_write(process(data), "Content-type" => "text/xml; charset=utf-8")
}
end
private
def http_error(status, message)
err = "#{status} #{message}"
msg = <<-"MSGEND"
<html>
<head>
<title>#{err}</title>
</head>
<body>
<h1>#{err}</h1>
<p>Unexpected error occured while processing XML-RPC request!</p>
</body>
</html>
MSGEND
http_write(msg, "Status" => err, "Content-type" => "text/html")
throw :exit_serve # exit from the #serve method
end
def http_write(body, header)
h = {}
header.each {|key, value| h[key.to_s.capitalize] = value}
h['Status'] ||= "200 OK"
h['Content-length'] ||= body.bytesize.to_s
str = ""
h.each {|key, value| str << "#{key}: #{value}\r\n"}
str << "\r\n#{body}"
print str
end
end
=begin
= XMLRPC::ModRubyServer
== Description
Implements a XML-RPC server, which works with Apache mod_ruby.
Use it in the same way as CGIServer!
== Superclass
((<XMLRPC::BasicServer>))
=end
class ModRubyServer < BasicServer
def initialize(*a)
@ap = Apache::request
super(*a)
end
def serve
catch(:exit_serve) {
header = {}
@ap.headers_in.each {|key, value| header[key.capitalize] = value}
length = header['Content-length'].to_i
http_error(405, "Method Not Allowed") unless @ap.request_method == "POST"
http_error(400, "Bad Request") unless parse_content_type(header['Content-type']).first == "text/xml"
http_error(411, "Length Required") unless length > 0
# TODO: do we need a call to binmode?
@ap.binmode
data = @ap.read(length)
http_error(400, "Bad Request") if data.nil? or data.bytesize != length
http_write(process(data), 200, "Content-type" => "text/xml; charset=utf-8")
}
end
private
def http_error(status, message)
err = "#{status} #{message}"
msg = <<-"MSGEND"
<html>
<head>
<title>#{err}</title>
</head>
<body>
<h1>#{err}</h1>
<p>Unexpected error occured while processing XML-RPC request!</p>
</body>
</html>
MSGEND
http_write(msg, status, "Status" => err, "Content-type" => "text/html")
throw :exit_serve # exit from the #serve method
end
def http_write(body, status, header)
h = {}
header.each {|key, value| h[key.to_s.capitalize] = value}
h['Status'] ||= "200 OK"
h['Content-length'] ||= body.bytesize.to_s
h.each {|key, value| @ap.headers_out[key] = value }
@ap.content_type = h["Content-type"]
@ap.status = status.to_i
@ap.send_http_header
@ap.print body
end
end
=begin
= XMLRPC::Server
== Synopsis
require "xmlrpc/server"
s = XMLRPC::Server.new(8080)
s.add_handler("michael.add") do |a,b|
a + b
end
s.add_handler("michael.div") do |a,b|
if b == 0
raise XMLRPC::FaultException.new(1, "division by zero")
else
a / b
end
end
s.set_default_handler do |name, *args|
raise XMLRPC::FaultException.new(-99, "Method #{name} missing" +
" or wrong number of parameters!")
end
s.serve
== Description
Implements a standalone XML-RPC server. The method (({serve}))) is left if a SIGHUP is sent to the
program.
== Superclass
((<XMLRPC::WEBrickServlet>))
== Class Methods
--- XMLRPC::Server.new( port=8080, host="127.0.0.1", maxConnections=4, stdlog=$stdout, audit=true, debug=true, *a )
Creates a new (({XMLRPC::Server})) instance, which is a XML-RPC server listening on
port ((|port|)) and accepts requests for the host ((|host|)), which is by default only the localhost.
The server is not started, to start it you have to call ((<serve|XMLRPC::Server#serve>)).
Parameters ((|audit|)) and ((|debug|)) are obsolete!
All additionally given parameters in ((|*a|)) are by-passed to ((<XMLRPC::BasicServer.new>)).
== Instance Methods
--- XMLRPC::Server#serve
Call this after you have added all you handlers to the server.
This method starts the server to listen for XML-RPC requests and answer them.
--- XMLRPC::Server#shutdown
Stops and shuts the server down.
=end
class WEBrickServlet < BasicServer; end # forward declaration
class Server < WEBrickServlet
def initialize(port=8080, host="127.0.0.1", maxConnections=4, stdlog=$stdout, audit=true, debug=true, *a)
super(*a)
require 'webrick'
@server = WEBrick::HTTPServer.new(:Port => port, :BindAddress => host, :MaxClients => maxConnections,
:Logger => WEBrick::Log.new(stdlog))
@server.mount("/", self)
end
def serve
signals = %w[INT TERM HUP] & Signal.list.keys
signals.each { |signal| trap(signal) { @server.shutdown } }
@server.start
end
def shutdown
@server.shutdown
end
end
=begin
= XMLRPC::WEBrickServlet
== Synopsis
require "webrick"
require "xmlrpc/server"
s = XMLRPC::WEBrickServlet.new
s.add_handler("michael.add") do |a,b|
a + b
end
s.add_handler("michael.div") do |a,b|
if b == 0
raise XMLRPC::FaultException.new(1, "division by zero")
else
a / b
end
end
s.set_default_handler do |name, *args|
raise XMLRPC::FaultException.new(-99, "Method #{name} missing" +
" or wrong number of parameters!")
end
httpserver = WEBrick::HTTPServer.new(:Port => 8080)
httpserver.mount("/RPC2", s)
trap("HUP") { httpserver.shutdown } # use 1 instead of "HUP" on Windows
httpserver.start
== Instance Methods
--- XMLRPC::WEBrickServlet#set_valid_ip( *ip_addr )
Specifies the valid IP addresses that are allowed to connect to the server.
Each IP is either a (({String})) or a (({Regexp})).
--- XMLRPC::WEBrickServlet#get_valid_ip
Return the via method ((<set_valid_ip|XMLRPC::Server#set_valid_ip>)) specified
valid IP addresses.
== Description
Implements a servlet for use with WEBrick, a pure Ruby (HTTP-) server framework.
== Superclass
((<XMLRPC::BasicServer>))
=end
class WEBrickServlet < BasicServer
def initialize(*a)
super
require "webrick/httpstatus"
@valid_ip = nil
end
# deprecated from WEBrick/1.2.2.
# but does not break anything.
def require_path_info?
false
end
def get_instance(config, *options)
# TODO: set config & options
self
end
def set_valid_ip(*ip_addr)
if ip_addr.size == 1 and ip_addr[0].nil?
@valid_ip = nil
else
@valid_ip = ip_addr
end
end
def get_valid_ip
@valid_ip
end
def service(request, response)
if @valid_ip
raise WEBrick::HTTPStatus::Forbidden unless @valid_ip.any? { |ip| request.peeraddr[3] =~ ip }
end
if request.request_method != "POST"
raise WEBrick::HTTPStatus::MethodNotAllowed,
"unsupported method `#{request.request_method}'."
end
if parse_content_type(request['Content-type']).first != "text/xml"
raise WEBrick::HTTPStatus::BadRequest
end
length = (request['Content-length'] || 0).to_i
raise WEBrick::HTTPStatus::LengthRequired unless length > 0
data = request.body
if data.nil? or data.bytesize != length
raise WEBrick::HTTPStatus::BadRequest
end
resp = process(data)
if resp.nil? or resp.bytesize <= 0
raise WEBrick::HTTPStatus::InternalServerError
end
response.status = 200
response['Content-Length'] = resp.bytesize
response['Content-Type'] = "text/xml; charset=utf-8"
response.body = resp
end
end
end # module XMLRPC
=begin
= History
$Id: server.rb 32947 2011-08-12 08:06:49Z shugo $
=end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/mixlib-shellout-1.6.1/lib/mixlib/shellout.rb
|
#--
# Author:: <NAME> (<<EMAIL>>)
# Copyright:: Copyright (c) 2010, 2011 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 'etc'
require 'tmpdir'
require 'fcntl'
require 'mixlib/shellout/exceptions'
module Mixlib
class ShellOut
READ_WAIT_TIME = 0.01
READ_SIZE = 4096
DEFAULT_READ_TIMEOUT = 600
DEFAULT_ENVIRONMENT = {'LC_ALL' => 'C'}
if RUBY_PLATFORM =~ /mswin|mingw32|windows/
require 'mixlib/shellout/windows'
include ShellOut::Windows
else
require 'mixlib/shellout/unix'
include ShellOut::Unix
end
# User the command will run as. Normally set via options passed to new
attr_accessor :user
attr_accessor :domain
attr_accessor :password
attr_accessor :with_logon
# Group the command will run as. Normally set via options passed to new
attr_accessor :group
# Working directory for the subprocess. Normally set via options to new
attr_accessor :cwd
# An Array of acceptable exit codes. #error? (and #error!) use this list
# to determine if the command was successful. Normally set via options to new
attr_accessor :valid_exit_codes
# When live_stdout is set, the stdout of the subprocess will be copied to it
# as the subprocess is running.
attr_accessor :live_stdout
# When live_stderr is set, the stderr of the subprocess will be copied to it
# as the subprocess is running.
attr_accessor :live_stderr
# ShellOut will push data from :input down the stdin of the subprocss.
# Normally set via options passed to new.
# Default: nil
attr_accessor :input
# If a logger is set, ShellOut will log a message before it executes the
# command.
attr_accessor :logger
# The log level at which ShellOut should log.
attr_accessor :log_level
# A string which will be prepended to the log message.
attr_accessor :log_tag
# The command to be executed.
attr_reader :command
# The umask that will be set for the subcommand.
attr_reader :umask
# Environment variables that will be set for the subcommand. Refer to the
# documentation of new to understand how ShellOut interprets this.
attr_reader :environment
# The maximum time this command is allowed to run. Usually set via options
# to new
attr_writer :timeout
# The amount of time the subcommand took to execute
attr_reader :execution_time
# Data written to stdout by the subprocess
attr_reader :stdout
# Data written to stderr by the subprocess
attr_reader :stderr
# A Process::Status (or ducktype) object collected when the subprocess is
# reaped.
attr_reader :status
attr_reader :stdin_pipe, :stdout_pipe, :stderr_pipe, :process_status_pipe
# === Arguments:
# Takes a single command, or a list of command fragments. These are used
# as arguments to Kernel.exec. See the Kernel.exec documentation for more
# explanation of how arguments are evaluated. The last argument can be an
# options Hash.
# === Options:
# If the last argument is a Hash, it is removed from the list of args passed
# to exec and used as an options hash. The following options are available:
# * +user+: the user the commmand should run as. if an integer is given, it is
# used as a uid. A string is treated as a username and resolved to a uid
# with Etc.getpwnam
# * +group+: the group the command should run as. works similarly to +user+
# * +cwd+: the directory to chdir to before running the command
# * +umask+: a umask to set before running the command. If given as an Integer,
# be sure to use two leading zeros so it's parsed as Octal. A string will
# be treated as an octal integer
# * +returns+: one or more Integer values to use as valid exit codes for the
# subprocess. This only has an effect if you call +error!+ after
# +run_command+.
# * +environment+: a Hash of environment variables to set before the command
# is run. By default, the environment will *always* be set to 'LC_ALL' => 'C'
# to prevent issues with multibyte characters in Ruby 1.8. To avoid this,
# use :environment => nil for *no* extra environment settings, or
# :environment => {'LC_ALL'=>nil, ...} to set other environment settings
# without changing the locale.
# * +timeout+: a Numeric value for the number of seconds to wait on the
# child process before raising an Exception. This is calculated as the
# total amount of time that ShellOut waited on the child process without
# receiving any output (i.e., IO.select returned nil). Default is 60
# seconds. Note: the stdlib Timeout library is not used.
# === Examples:
# Invoke find(1) to search for .rb files:
# find = Mixlib::ShellOut.new("find . -name '*.rb'")
# find.run_command
# # If all went well, the results are on +stdout+
# puts find.stdout
# # find(1) prints diagnostic info to STDERR:
# puts "error messages" + find.stderr
# # Raise an exception if it didn't exit with 0
# find.error!
# Run a command as the +www+ user with no extra ENV settings from +/tmp+
# cmd = Mixlib::ShellOut.new("apachectl", "start", :user => 'www', :env => nil, :cwd => '/tmp')
# cmd.run_command # etc.
def initialize(*command_args)
@stdout, @stderr = '', ''
@live_stdout = @live_stderr = nil
@input = nil
@log_level = :debug
@log_tag = nil
@environment = DEFAULT_ENVIRONMENT
@cwd = nil
@valid_exit_codes = [0]
@terminate_reason = nil
if command_args.last.is_a?(Hash)
parse_options(command_args.pop)
end
@command = command_args.size == 1 ? command_args.first : command_args
end
# Returns the stream that both is being used by both live_stdout and live_stderr, or nil
def live_stream
live_stdout == live_stderr ? live_stdout : nil
end
# A shortcut for setting both live_stdout and live_stderr, so that both the
# stdout and stderr from the subprocess will be copied to the same stream as
# the subprocess is running.
def live_stream=(stream)
@live_stdout = @live_stderr = stream
end
# Set the umask that the subprocess will have. If given as a string, it
# will be converted to an integer by String#oct.
def umask=(new_umask)
@umask = (new_umask.respond_to?(:oct) ? new_umask.oct : new_umask.to_i) & 007777
end
# The uid that the subprocess will switch to. If the user attribute was
# given as a username, it is converted to a uid by Etc.getpwnam
def uid
return nil unless user
user.kind_of?(Integer) ? user : Etc.getpwnam(user.to_s).uid
end
# The gid that the subprocess will switch to. If the group attribute is
# given as a group name, it is converted to a gid by Etc.getgrnam
def gid
return nil unless group
group.kind_of?(Integer) ? group : Etc.getgrnam(group.to_s).gid
end
def timeout
@timeout || DEFAULT_READ_TIMEOUT
end
# Creates a String showing the output of the command, including a banner
# showing the exact command executed. Used by +invalid!+ to show command
# results when the command exited with an unexpected status.
def format_for_exception
msg = ""
msg << "#{@terminate_reason}\n" if @terminate_reason
msg << "---- Begin output of #{command} ----\n"
msg << "STDOUT: #{stdout.strip}\n"
msg << "STDERR: #{stderr.strip}\n"
msg << "---- End output of #{command} ----\n"
msg << "Ran #{command} returned #{status.exitstatus}" if status
msg
end
# The exit status of the subprocess. Will be nil if the command is still
# running or died without setting an exit status (e.g., terminated by
# `kill -9`).
def exitstatus
@status && @status.exitstatus
end
# Run the command, writing the command's standard out and standard error
# to +stdout+ and +stderr+, and saving its exit status object to +status+
# === Returns
# returns +self+; +stdout+, +stderr+, +status+, and +exitstatus+ will be
# populated with results of the command
# === Raises
# * Errno::EACCES when you are not privileged to execute the command
# * Errno::ENOENT when the command is not available on the system (or not
# in the current $PATH)
# * CommandTimeout when the command does not complete
# within +timeout+ seconds (default: 600s)
def run_command
if logger
log_message = (log_tag.nil? ? "" : "#@log_tag ") << "sh(#@command)"
logger.send(log_level, log_message)
end
super
end
# Checks the +exitstatus+ against the set of +valid_exit_codes+.
# === Returns
# +true+ if +exitstatus+ is not in the list of +valid_exit_codes+, false
# otherwise.
def error?
!Array(valid_exit_codes).include?(exitstatus)
end
# If #error? is true, calls +invalid!+, which raises an Exception.
# === Returns
# nil::: always returns nil when it does not raise
# === Raises
# ::ShellCommandFailed::: via +invalid!+
def error!
invalid!("Expected process to exit with #{valid_exit_codes.inspect}, but received '#{exitstatus}'") if error?
end
# Raises a ShellCommandFailed exception, appending the
# command's stdout, stderr, and exitstatus to the exception message.
# === Arguments
# +msg+: A String to use as the basis of the exception message. The
# default explanation is very generic, providing a more informative message
# is highly encouraged.
# === Raises
# ShellCommandFailed always
def invalid!(msg=nil)
msg ||= "Command produced unexpected results"
raise ShellCommandFailed, msg + "\n" + format_for_exception
end
def inspect
"<#{self.class.name}##{object_id}: command: '#@command' process_status: #{@status.inspect} " +
"stdout: '#{stdout.strip}' stderr: '#{stderr.strip}' child_pid: #{@child_pid.inspect} " +
"environment: #{@environment.inspect} timeout: #{timeout} user: #@user group: #@group working_dir: #@cwd >"
end
private
def parse_options(opts)
opts.each do |option, setting|
case option.to_s
when 'cwd'
self.cwd = setting
when 'domain'
self.domain = setting
when 'password'
self.password = setting
when 'user'
self.user = setting
self.with_logon = setting
when 'group'
self.group = setting
when 'umask'
self.umask = setting
when 'timeout'
self.timeout = setting
when 'returns'
self.valid_exit_codes = Array(setting)
when 'live_stream'
self.live_stdout = self.live_stderr = setting
when 'live_stdout'
self.live_stdout = setting
when 'live_stderr'
self.live_stderr = setting
when 'input'
self.input = setting
when 'logger'
self.logger = setting
when 'log_level'
self.log_level = setting
when 'log_tag'
self.log_tag = setting
when 'environment', 'env'
# Set the LC_ALL from the parent process if the user wanted
# to use the default.
if setting && setting.has_key?("LC_ALL") && setting['LC_ALL'].nil?
setting['LC_ALL'] = ENV['LC_ALL']
end
# passing :environment => nil means don't set any new ENV vars
@environment = setting.nil? ? {} : @environment.dup.merge!(setting)
else
raise InvalidCommandOption, "option '#{option.inspect}' is not a valid option for #{self.class.name}"
end
end
validate_options(opts)
end
def validate_options(opts)
super
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/gem_prelude.rb
|
if defined?(Gem)
require 'rubygems.rb'
begin
require 'did_you_mean'
rescue LoadError
end if defined?(DidYouMean)
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/gems/did_you_mean-1.0.0/test/correctable/class_name_test.rb
|
require 'test_helper'
module ACRONYM
end
class Project
def self.bo0k
Bo0k
end
end
class Book
class TableOfContents; end
def tableof_contents
TableofContents
end
class Page
def tableof_contents
TableofContents
end
def self.tableof_contents
TableofContents
end
end
end
class ClassNameTest < Minitest::Test
def test_corrections
error = assert_raises(NameError) { ::Bo0k }
assert_correction "Book", error.corrections
end
def test_corrections_include_case_specific_class_name
error = assert_raises(NameError) { ::Acronym }
assert_correction "ACRONYM", error.corrections
end
def test_corrections_include_top_level_class_name
error = assert_raises(NameError) { Project.bo0k }
assert_correction "Book", error.corrections
end
def test_names_in_corrections_have_namespaces
error = assert_raises(NameError) { ::Book::TableofContents }
assert_correction "Book::TableOfContents", error.corrections
end
def test_corrections_candidates_for_names_in_upper_level_scopes
error = assert_raises(NameError) { Book::Page.tableof_contents }
assert_correction "Book::TableOfContents", error.corrections
end
def test_corrections_should_work_from_within_instance_method
error = assert_raises(NameError) { ::Book.new.tableof_contents }
assert_correction "Book::TableOfContents", error.corrections
end
def test_corrections_should_work_from_within_instance_method_on_nested_class
error = assert_raises(NameError) { ::Book::Page.new.tableof_contents }
assert_correction "Book::TableOfContents", error.corrections
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/lib/ohai/plugins/azure.rb
|
provides "azure"
azure_metadata_from_hints = hint?('azure')
if azure_metadata_from_hints
Ohai::Log.debug("azure_metadata_from_hints is present.")
azure Mash.new
azure_metadata_from_hints.each {|k, v| azure[k] = v }
else
Ohai::Log.debug("No hints present for azure.")
false
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/net-ssh-3.1.1/lib/net/ssh/known_hosts.rb
|
<gh_stars>1-10
require 'strscan'
require 'openssl'
require 'base64'
require 'net/ssh/buffer'
module Net; module SSH
# Represents the result of a search in known hosts
# see search_for
class HostKeys < Array
attr_reader :host
def initialize(host_keys, host, known_hosts, options = {})
super(host_keys)
@host = host
@known_hosts = known_hosts
@options = options
end
def add_host_key(key)
@known_hosts.add(@host, key, @options)
push(key)
end
end
# Searches an OpenSSH-style known-host file for a given host, and returns all
# matching keys. This is used to implement host-key verification, as well as
# to determine what key a user prefers to use for a given host.
#
# This is used internally by Net::SSH, and will never need to be used directly
# by consumers of the library.
class KnownHosts
if defined?(OpenSSL::PKey::EC)
SUPPORTED_TYPE = %w(ssh-rsa ssh-dss
ecdsa-sha2-nistp256
ecdsa-sha2-nistp384
ecdsa-sha2-nistp521)
else
SUPPORTED_TYPE = %w(ssh-rsa ssh-dss)
end
class <<self
# Searches all known host files (see KnownHosts.hostfiles) for all keys
# of the given host. Returns an enumerable of keys found.
def search_for(host, options={})
HostKeys.new(search_in(hostfiles(options), host), host, self, options)
end
# Search for all known keys for the given host, in every file given in
# the +files+ array. Returns the list of keys.
def search_in(files, host)
files.map { |file| KnownHosts.new(file).keys_for(host) }.flatten
end
# Looks in the given +options+ hash for the :user_known_hosts_file and
# :global_known_hosts_file keys, and returns an array of all known
# hosts files. If the :user_known_hosts_file key is not set, the
# default is returned (~/.ssh/known_hosts and ~/.ssh/known_hosts2). If
# :global_known_hosts_file is not set, the default is used
# (/etc/ssh/ssh_known_hosts and /etc/ssh/ssh_known_hosts2).
#
# If you only want the user known host files, you can pass :user as
# the second option.
def hostfiles(options, which=:all)
files = []
if which == :all || which == :user
files += Array(options[:user_known_hosts_file] || %w(~/.ssh/known_hosts ~/.ssh/known_hosts2))
end
if which == :all || which == :global
files += Array(options[:global_known_hosts_file] || %w(/etc/ssh/ssh_known_hosts /etc/ssh/ssh_known_hosts2))
end
return files
end
# Looks in all user known host files (see KnownHosts.hostfiles) and tries to
# add an entry for the given host and key to the first file it is able
# to.
def add(host, key, options={})
hostfiles(options, :user).each do |file|
begin
KnownHosts.new(file).add(host, key)
return
rescue SystemCallError
# try the next hostfile
end
end
end
end
# The host-key file name that this KnownHosts instance will use to search
# for keys.
attr_reader :source
# Instantiate a new KnownHosts instance that will search the given known-hosts
# file. The path is expanded file File.expand_path.
def initialize(source)
@source = File.expand_path(source)
end
# Returns an array of all keys that are known to be associatd with the
# given host. The +host+ parameter is either the domain name or ip address
# of the host, or both (comma-separated). Additionally, if a non-standard
# port is being used, it may be specified by putting the host (or ip, or
# both) in square brackets, and appending the port outside the brackets
# after a colon. Possible formats for +host+, then, are;
#
# "net.ssh.test"
# "1.2.3.4"
# "net.ssh.test,1.2.3.4"
# "[net.ssh.test]:5555"
# "[1,2,3,4]:5555"
# "[net.ssh.test]:5555,[1.2.3.4]:5555
def keys_for(host)
keys = []
return keys unless File.readable?(source)
entries = host.split(/,/)
File.open(source) do |file|
scanner = StringScanner.new("")
file.each_line do |line|
scanner.string = line
scanner.skip(/\s*/)
next if scanner.match?(/$|#/)
hostlist = scanner.scan(/\S+/).split(/,/)
found = entries.all? { |entry| hostlist.include?(entry) } ||
known_host_hash?(hostlist, entries, scanner)
next unless found
scanner.skip(/\s*/)
type = scanner.scan(/\S+/)
next unless SUPPORTED_TYPE.include?(type)
scanner.skip(/\s*/)
blob = scanner.rest.unpack("m*").first
keys << Net::SSH::Buffer.new(blob).read_key
end
end
keys
end
# Indicates whether one of the entries matches an hostname that has been
# stored as a HMAC-SHA1 hash in the known hosts.
def known_host_hash?(hostlist, entries, scanner)
if hostlist.size == 1 && hostlist.first =~ /\A\|1(\|.+){2}\z/
chunks = hostlist.first.split(/\|/)
salt = Base64.decode64(chunks[2])
digest = OpenSSL::Digest.new('sha1')
entries.each do |entry|
hmac = OpenSSL::HMAC.digest(digest, salt, entry)
return true if Base64.encode64(hmac).chomp == chunks[3]
end
end
false
end
# Tries to append an entry to the current source file for the given host
# and key. If it is unable to (because the file is not writable, for
# instance), an exception will be raised.
def add(host, key)
File.open(source, "a") do |file|
blob = [Net::SSH::Buffer.from(:key, key).to_s].pack("m*").gsub(/\s/, "")
file.puts "#{host} #{key.ssh_type} #{blob}"
end
end
end
end; end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/tile/tentry.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/tile/tentry.rb
#
# tentry widget
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tkextlib/tile.rb'
module Tk
module Tile
class TEntry < Tk::Entry
end
Entry = TEntry
end
end
class Tk::Tile::TEntry < Tk::Entry
include Tk::Tile::TileWidget
if Tk::Tile::USE_TTK_NAMESPACE
TkCommandNames = ['::ttk::entry'.freeze].freeze
else
TkCommandNames = ['::tentry'.freeze].freeze
end
WidgetClassName = 'TEntry'.freeze
WidgetClassNames[WidgetClassName] ||= self
def __optkey_aliases
{:vcmd=>:validatecommand, :invcmd=>:invalidcommand}
end
private :__optkey_aliases
def __boolval_optkeys
super() << 'exportselection'
end
private :__boolval_optkeys
def __strval_optkeys
super() << 'show'
end
private :__strval_optkeys
def self.style(*args)
[self::WidgetClassName, *(args.map!{|a| _get_eval_string(a)})].join('.')
end
end
#Tk.__set_toplevel_aliases__(:Ttk, Tk::Tile::Entry, :TkEntry)
Tk.__set_loaded_toplevel_aliases__('tkextlib/tile/tentry.rb',
:Ttk, Tk::Tile::Entry, :TkEntry)
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/ruby/test_integer.rb
|
# frozen_string_literal: false
require 'test/unit'
class TestInteger < Test::Unit::TestCase
BDSIZE = 0x4000000000000000.coerce(0)[0].size
def self.bdsize(x)
((x + 1) / 8 + BDSIZE) / BDSIZE * BDSIZE
end
def bdsize(x)
self.class.bdsize(x)
end
def test_aref
# assert_equal(1, (1 << 0x40000000)[0x40000000], "[ruby-dev:31271]")
# assert_equal(0, (-1 << 0x40000001)[0x40000000], "[ruby-dev:31271]")
big_zero = 0x40000000.coerce(0)[0]
assert_equal(0, (-0x40000002)[big_zero], "[ruby-dev:31271]")
assert_equal(1, 0x400000001[big_zero], "[ruby-dev:31271]")
end
def test_pow
assert_not_equal(0, begin
0**-1
rescue
nil
end, "[ruby-dev:32084] [ruby-dev:34547]")
end
def test_lshift
assert_equal(0, 1 << -0x40000000)
assert_equal(0, 1 << -0x40000001)
assert_equal(0, 1 << -0x80000000)
assert_equal(0, 1 << -0x80000001)
# assert_equal(bdsize(0x80000000), (1 << 0x80000000).size)
end
def test_rshift
# assert_equal(bdsize(0x40000001), (1 >> -0x40000001).size)
assert_predicate((1 >> 0x80000000), :zero?)
assert_predicate((1 >> 0xffffffff), :zero?)
assert_predicate((1 >> 0x100000000), :zero?)
# assert_equal((1 << 0x40000000), (1 >> -0x40000000))
# assert_equal((1 << 0x40000001), (1 >> -0x40000001))
end
def test_Integer
assert_raise(ArgumentError) {Integer("0x-1")}
assert_raise(ArgumentError) {Integer("-0x-1")}
assert_raise(ArgumentError) {Integer("0x 123")}
assert_raise(ArgumentError) {Integer("0x 123")}
assert_raise(ArgumentError) {Integer("0x0x5")}
assert_raise(ArgumentError) {Integer("0x0x000000005")}
assert_nothing_raised(ArgumentError) {
assert_equal(1540841, "0x0x5".to_i(36))
}
assert_raise(ArgumentError) { Integer("--0") }
assert_raise(ArgumentError) { Integer("-+0") }
assert_raise(ArgumentError) { Integer("++1") }
assert_raise(ArgumentError) { Integer("") }
assert_raise(ArgumentError) { Integer("10 x") }
assert_raise(ArgumentError) { Integer("1__2") }
assert_raise(ArgumentError) { Integer("1z") }
assert_raise(ArgumentError) { Integer("46116860184273__87904") }
assert_raise(ArgumentError) { Integer("4611686018427387904_") }
assert_raise(ArgumentError) { Integer("4611686018427387904 :") }
assert_equal(0x4000000000000000, Integer("46_11_686_0184273_87904"))
assert_raise(ArgumentError) { Integer("\0") }
assert_nothing_raised(ArgumentError, "[ruby-core:13873]") {
assert_equal(0, Integer("0 "))
}
assert_nothing_raised(ArgumentError, "[ruby-core:14139]") {
assert_equal(0377, Integer("0_3_7_7"))
}
assert_raise(ArgumentError, "[ruby-core:14139]") {Integer("0__3_7_7")}
assert_equal(1234, Integer(1234))
assert_equal(1, Integer(1.234))
# base argument
assert_equal(1234, Integer("1234", 10))
assert_equal(668, Integer("1234", 8))
assert_equal(4660, Integer("1234", 16))
assert_equal(49360, Integer("1234", 36))
# decimal, not octal
assert_equal(1234, Integer("01234", 10))
assert_raise(ArgumentError) { Integer("0x123", 10) }
assert_raise(ArgumentError) { Integer(1234, 10) }
assert_raise(ArgumentError) { Integer(12.34, 10) }
assert_raise(ArgumentError) { Integer(Object.new, 1) }
assert_raise(ArgumentError) { Integer(1, 1, 1) }
assert_equal(2 ** 50, Integer(2.0 ** 50))
assert_raise(TypeError) { Integer(nil) }
bug6192 = '[ruby-core:43566]'
assert_raise(Encoding::CompatibilityError, bug6192) {Integer("0".encode("utf-16be"))}
assert_raise(Encoding::CompatibilityError, bug6192) {Integer("0".encode("utf-16le"))}
assert_raise(Encoding::CompatibilityError, bug6192) {Integer("0".encode("utf-32be"))}
assert_raise(Encoding::CompatibilityError, bug6192) {Integer("0".encode("utf-32le"))}
assert_raise(Encoding::CompatibilityError, bug6192) {Integer("0".encode("iso-2022-jp"))}
end
def test_int_p
assert_not_predicate(1.0, :integer?)
assert_predicate(1, :integer?)
end
def test_odd_p_even_p
Fixnum.class_eval do
alias odd_bak odd?
alias even_bak even?
remove_method :odd?, :even?
end
assert_predicate(1, :odd?)
assert_not_predicate(2, :odd?)
assert_not_predicate(1, :even?)
assert_predicate(2, :even?)
ensure
Fixnum.class_eval do
alias odd? odd_bak
alias even? even_bak
remove_method :odd_bak, :even_bak
end
end
def test_succ
assert_equal(2, 1.send(:succ))
Fixnum.class_eval do
alias succ_bak succ
remove_method :succ
end
assert_equal(2, 1.succ)
assert_equal(4294967297, 4294967296.succ)
ensure
Fixnum.class_eval do
alias succ succ_bak
remove_method :succ_bak
end
end
def test_chr
assert_equal("a", "a".ord.chr)
assert_raise(RangeError) { (-1).chr }
assert_raise(RangeError) { 0x100.chr }
end
def test_upto
a = []
1.upto(3) {|x| a << x }
assert_equal([1, 2, 3], a)
a = []
1.upto(0) {|x| a << x }
assert_equal([], a)
y = 2**30 - 1
a = []
y.upto(y+2) {|x| a << x }
assert_equal([y, y+1, y+2], a)
end
def test_downto
a = []
-1.downto(-3) {|x| a << x }
assert_equal([-1, -2, -3], a)
a = []
1.downto(2) {|x| a << x }
assert_equal([], a)
y = -(2**30)
a = []
y.downto(y-2) {|x| a << x }
assert_equal([y, y-1, y-2], a)
end
def test_times
(2**32).times do |i|
break if i == 2
end
end
def test_round
assert_equal(11111, 11111.round)
assert_equal(Fixnum, 11111.round.class)
assert_equal(11111, 11111.round(0))
assert_equal(Fixnum, 11111.round(0).class)
assert_equal(11111.0, 11111.round(1))
assert_equal(Float, 11111.round(1).class)
assert_equal(11111.0, 11111.round(2))
assert_equal(Float, 11111.round(2).class)
assert_equal(11110, 11111.round(-1))
assert_equal(Fixnum, 11111.round(-1).class)
assert_equal(11100, 11111.round(-2))
assert_equal(Fixnum, 11111.round(-2).class)
assert_equal(1111_1111_1111_1111_1111_1111_1111_1110, 1111_1111_1111_1111_1111_1111_1111_1111.round(-1))
assert_equal(Bignum, 1111_1111_1111_1111_1111_1111_1111_1111.round(-1).class)
assert_equal(-1111_1111_1111_1111_1111_1111_1111_1110, (-1111_1111_1111_1111_1111_1111_1111_1111).round(-1))
assert_equal(Bignum, (-1111_1111_1111_1111_1111_1111_1111_1111).round(-1).class)
end
def test_bitwise_and_with_integer_mimic_object
def (obj = Object.new).to_int
10
end
assert_raise(TypeError, '[ruby-core:39491]') { 3 & obj }
def obj.coerce(other)
[other, 10]
end
assert_equal(3 & 10, 3 & obj)
end
def test_bitwise_or_with_integer_mimic_object
def (obj = Object.new).to_int
10
end
assert_raise(TypeError, '[ruby-core:39491]') { 3 | obj }
def obj.coerce(other)
[other, 10]
end
assert_equal(3 | 10, 3 | obj)
end
def test_bitwise_xor_with_integer_mimic_object
def (obj = Object.new).to_int
10
end
assert_raise(TypeError, '[ruby-core:39491]') { 3 ^ obj }
def obj.coerce(other)
[other, 10]
end
assert_equal(3 ^ 10, 3 ^ obj)
end
def test_bit_length
assert_equal(13, (-2**12-1).bit_length)
assert_equal(12, (-2**12).bit_length)
assert_equal(12, (-2**12+1).bit_length)
assert_equal(9, -0x101.bit_length)
assert_equal(8, -0x100.bit_length)
assert_equal(8, -0xff.bit_length)
assert_equal(1, -2.bit_length)
assert_equal(0, -1.bit_length)
assert_equal(0, 0.bit_length)
assert_equal(1, 1.bit_length)
assert_equal(8, 0xff.bit_length)
assert_equal(9, 0x100.bit_length)
assert_equal(9, 0x101.bit_length)
assert_equal(12, (2**12-1).bit_length)
assert_equal(13, (2**12).bit_length)
assert_equal(13, (2**12+1).bit_length)
assert_equal(10001, (-2**10000-1).bit_length)
assert_equal(10000, (-2**10000).bit_length)
assert_equal(10000, (-2**10000+1).bit_length)
assert_equal(10000, (2**10000-1).bit_length)
assert_equal(10001, (2**10000).bit_length)
assert_equal(10001, (2**10000+1).bit_length)
2.upto(1000) {|i|
n = 2**i
assert_equal(i+1, (-n-1).bit_length, "(#{-n-1}).bit_length")
assert_equal(i, (-n).bit_length, "(#{-n}).bit_length")
assert_equal(i, (-n+1).bit_length, "(#{-n+1}).bit_length")
assert_equal(i, (n-1).bit_length, "#{n-1}.bit_length")
assert_equal(i+1, (n).bit_length, "#{n}.bit_length")
assert_equal(i+1, (n+1).bit_length, "#{n+1}.bit_length")
}
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/rubyntlm-0.6.0/spec/lib/net/ntlm/int64_le_spec.rb
|
require 'spec_helper'
describe Net::NTLM::Int64LE do
int_values = {
:default => 5294967295,
:default_hex => [5294967295 & 0x00000000ffffffff, 5294967295 >> 32].pack("V2"),
:alt => 5294967294,
:alt_hex => [5294967294 & 0x00000000ffffffff, 5294967294 >> 32].pack("V2"),
:small => "\x5C\x24\x10\x0f",
:size => 8,
:bits => 64
}
it_behaves_like 'a field', 252716124, false
it_behaves_like 'an integer field', int_values
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/nori-2.6.0/lib/nori/core_ext.rb
|
<gh_stars>100-1000
require "nori/core_ext/object"
require "nori/core_ext/string"
require "nori/core_ext/hash"
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/lib/rdoc/markup/hard_break.rb
|
<gh_stars>10-100
# frozen_string_literal: false
##
# A hard-break in the middle of a paragraph.
class RDoc::Markup::HardBreak
@instance = new
##
# RDoc::Markup::HardBreak is a singleton
def self.new
@instance
end
##
# Calls #accept_hard_break on +visitor+
def accept visitor
visitor.accept_hard_break self
end
def == other # :nodoc:
self.class === other
end
def pretty_print q # :nodoc:
q.text "[break]"
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/bwidget/selectcolor.rb
|
#
# tkextlib/bwidget/selectcolor.rb
# by <NAME> (<EMAIL>)
#
require 'tk'
require 'tkextlib/bwidget.rb'
require 'tkextlib/bwidget/messagedlg'
module Tk
module BWidget
class SelectColor < Tk::BWidget::MessageDlg
class Dialog < Tk::BWidget::SelectColor
end
class Menubutton < Tk::Menubutton
end
MenuButton = Menubutton
end
end
end
class Tk::BWidget::SelectColor
extend Tk
TkCommandNames = ['SelectColor'.freeze].freeze
WidgetClassName = 'SelectColor'.freeze
WidgetClassNames[WidgetClassName] ||= self
def dialog(keys={})
newkeys = @keys.dup
newkeys.update(_symbolkey2str(keys))
tk_call('SelectColor::dialog', @path, *hash_kv(newkeys))
end
def menu(*args)
if args[-1].kind_of?(Hash)
keys = args.pop
else
keys = {}
end
place = args.flatten
newkeys = @keys.dup
newkeys.update(_symbolkey2str(keys))
tk_call('SelectColor::menu', @path, place, *hash_kv(newkeys))
end
def self.set_color(idx, color)
tk_call('SelectColor::setcolor', idx, color)
end
end
class Tk::BWidget::SelectColor::Dialog
def create_self(keys)
super(keys)
@keys['type'] = 'dialog'
end
def create
@keys['type'] = 'dialog' # 'dialog' type returns color
tk_call(Tk::BWidget::SelectColor::TkCommandNames[0],
@path, *hash_kv(@keys))
end
end
class Tk::BWidget::SelectColor::Menubutton
def create_self(keys)
keys = {} unless keys
keys = _symbolkey2str(keys)
keys['type'] = 'menubutton' # 'toolbar' type returns widget path
window(tk_call(Tk::BWidget::SelectColor::TkCommandNames[0],
@path, *hash_kv(keys)))
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/socket/test_sockopt.rb
|
# frozen_string_literal: true
require 'test/unit'
require 'socket'
class TestSocketOption < Test::Unit::TestCase
def test_new
data = [1].pack("i")
sockopt = Socket::Option.new(:INET, :SOCKET, :KEEPALIVE, data)
assert_equal(Socket::AF_INET, sockopt.family)
assert_equal(Socket::SOL_SOCKET, sockopt.level)
assert_equal(Socket::SO_KEEPALIVE, sockopt.optname)
assert_equal(Socket::SO_KEEPALIVE, sockopt.optname)
assert_equal(data, sockopt.data)
end
def test_bool
opt = Socket::Option.bool(:INET, :SOCKET, :KEEPALIVE, true)
assert_equal(1, opt.int)
opt = Socket::Option.bool(:INET, :SOCKET, :KEEPALIVE, false)
assert_equal(0, opt.int)
opt = Socket::Option.int(:INET, :SOCKET, :KEEPALIVE, 0)
assert_equal(false, opt.bool)
opt = Socket::Option.int(:INET, :SOCKET, :KEEPALIVE, 1)
assert_equal(true, opt.bool)
opt = Socket::Option.int(:INET, :SOCKET, :KEEPALIVE, 2)
assert_equal(true, opt.bool)
end
def test_ipv4_multicast_loop
sockopt = Socket::Option.ipv4_multicast_loop(128)
assert_equal('#<Socket::Option: INET IP MULTICAST_LOOP 128>', sockopt.inspect)
assert_equal(Socket::AF_INET, sockopt.family)
assert_equal(Socket::IPPROTO_IP, sockopt.level)
assert_equal(Socket::IP_MULTICAST_LOOP, sockopt.optname)
assert_equal(128, sockopt.ipv4_multicast_loop)
end
def test_ipv4_multicast_loop_size
expected_size = Socket.open(:INET, :DGRAM) {|s|
s.getsockopt(:IP, :MULTICAST_LOOP).to_s.bytesize
}
assert_equal(expected_size, Socket::Option.ipv4_multicast_loop(0).to_s.bytesize)
end
def test_ipv4_multicast_ttl
sockopt = Socket::Option.ipv4_multicast_ttl(128)
assert_equal('#<Socket::Option: INET IP MULTICAST_TTL 128>', sockopt.inspect)
assert_equal(Socket::AF_INET, sockopt.family)
assert_equal(Socket::IPPROTO_IP, sockopt.level)
assert_equal(Socket::IP_MULTICAST_TTL, sockopt.optname)
assert_equal(128, sockopt.ipv4_multicast_ttl)
end
def test_ipv4_multicast_ttl_size
expected_size = Socket.open(:INET, :DGRAM) {|s|
s.getsockopt(:IP, :MULTICAST_TTL).to_s.bytesize
}
assert_equal(expected_size, Socket::Option.ipv4_multicast_ttl(0).to_s.bytesize)
end
def test_unpack
sockopt = Socket::Option.new(:INET, :SOCKET, :KEEPALIVE, [1].pack("i"))
assert_equal([1], sockopt.unpack("i"))
assert_equal([1], sockopt.data.unpack("i"))
end
end
|
arnab0073/idea
|
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/google/core.rb
|
<filename>.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/google/core.rb
require 'fog/core'
require 'fog/xml'
module Fog
module Google
extend Fog::Provider
service(:compute, 'Compute')
service(:dns, 'DNS')
service(:monitoring, 'Monitoring')
service(:storage, 'Storage')
service(:sql, 'SQL')
class Mock
def self.etag
hex(32)
end
def self.hex(length)
max = ('f' * length).to_i(16)
rand(max).to_s(16)
end
end
module Shared
attr_reader :project, :api_version, :api_url
##
# Initializes shared attributes
#
# @param [String] project Google Cloud Project
# @param [String] api_version Google API version
# @param [String] base_url Google API base url
# @return [void]
def shared_initialize(project, api_version, base_url)
@project = project
@api_version = api_version
@api_url = base_url + api_version + '/projects/'
end
##
# Initializes the Google API Client
#
# @param [Hash] options Google API options
# @option options [String] :google_client_email A @developer.gserviceaccount.com email address to use
# @option options [String] :google_key_location The location of a pkcs12 key file
# @option options [String] :google_key_string The content of the pkcs12 key file
# @option options [String] :google_json_key_location The location of a JSON key file
# @option options [String] :google_json_key_string The content of the JSON key file
# @option options [String] :google_api_scope_url The access scope URLs
# @option options [String] :app_name The app name to set in the user agent
# @option options [String] :app_version The app version to set in the user agent
# @option options [Google::APIClient] :google_client Existing Google API Client
# @return [Google::APIClient] Google API Client
# @raises [ArgumentError] If there is any missing argument
def initialize_google_client(options)
# NOTE: loaded here to avoid requiring this as a core Fog dependency
begin
require 'google/api_client'
rescue LoadError => error
Fog::Logger.warning('Please install the google-api-client gem before using this provider')
raise error
end
# User can provide an existing Google API Client
client = options[:google_client]
return client unless client.nil?
# Create a signing key
signing_key = create_signing_key(options)
# Validate required arguments
unless options[:google_client_email]
raise ArgumentError.new('Missing required arguments: google_client_email')
end
unless options[:google_api_scope_url]
raise ArgumentError.new('Missing required arguments: google_api_scope_url')
end
# Create a new Google API Client
self.new_pk12_google_client(
options[:google_client_email],
signing_key,
options[:google_api_scope_url],
options[:app_name],
options[:app_version]
)
end
##
# Creates a Google signing key
#
def create_signing_key(options)
if options[:google_json_key_location] || options[:google_json_key_string]
if options[:google_json_key_location]
json_key_location = File.expand_path(options[:google_json_key_location])
json_key = File.open(json_key_location, 'r') { |file| file.read }
else
json_key = options[:google_json_key_string]
end
json_key_hash = Fog::JSON.decode(json_key)
unless json_key_hash.has_key?('client_email') || json_key_hash.has_key?('private_key')
raise ArgumentError.new('Invalid Google JSON key')
end
options[:google_client_email] = json_key_hash['client_email']
::Google::APIClient::KeyUtils.load_from_pem(json_key_hash['private_key'], 'notasecret')
elsif options[:google_key_location] || options[:google_key_string]
if options[:google_key_location]
google_key = File.expand_path(options[:google_key_location])
else
google_key = options[:google_key_string]
end
::Google::APIClient::KeyUtils.load_from_pkcs12(google_key, 'notasecret')
else
raise ArgumentError.new('Missing required arguments: google_key_location, google_key_string, ' \
'google_json_key_location or google_json_key_string')
end
end
##
# Create a Google API Client with a user email and a pkcs12 key
#
# @param [String] google_client_email A <EMAIL> email address to use
# @param [OpenSSL::PKey] signing_key The private key for signing
# @param [String] google_api_scope_url Access scope URLs
# @param [String] app_name The app name to set in the user agent
# @param [String] app_version The app version to set in the user agent
# @return [Google::APIClient] Google API Client
def new_pk12_google_client(google_client_email, signing_key, google_api_scope_url, app_name = nil, app_version = nil)
application_name = app_name.nil? ? 'fog' : "#{app_name}/#{app_version || '0.0.0'} fog"
api_client_options = {
:application_name => application_name,
:application_version => Fog::VERSION,
}
client = ::Google::APIClient.new(api_client_options)
client.authorization = Signet::OAuth2::Client.new(
{
:audience => 'https://accounts.google.com/o/oauth2/token',
:auth_provider_x509_cert_url => 'https://www.googleapis.com/oauth2/v1/certs',
:client_x509_cert_url => "https://www.googleapis.com/robot/v1/metadata/x509/#{google_client_email}",
:issuer => google_client_email,
:scope => google_api_scope_url,
:signing_key => signing_key,
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
}
)
client.authorization.fetch_access_token!
client
end
##
# Executes a request and wraps it in a result object
#
# @param [Google::APIClient::Method] api_method The method object or the RPC name of the method being executed
# @param [Hash] parameters The parameters to send to the method
# @param [Hash] body_object The body object of the request
# @return [Excon::Response] The result from the API
def request(api_method, parameters, body_object = nil)
client_parms = {
:api_method => api_method,
:parameters => parameters,
}
client_parms[:body_object] = body_object if body_object
result = @client.execute(client_parms)
build_excon_response(result.body.nil? || result.body.empty? ? nil : Fog::JSON.decode(result.body), result.status)
end
##
# Builds an Excon response
#
# @param [Hash] Response body
# @param [Integer] Response status
# @return [Excon::Response] Excon response
def build_excon_response(body, status = 200)
response = Excon::Response.new(:body => body, :status => status)
if body && body.has_key?('error')
msg = 'Google Cloud did not return an error message'
if body['error'].kind_of?(Hash)
response.status = body['error']['code']
if body['error'].has_key?('errors')
msg = body['error']['errors'].map{ |error| error['message'] }.join(', ')
elsif body['error'].has_key?('message')
msg = body['error']['message']
end
elsif body['error'].kind_of?(Array)
msg = body['error'].map{ |error| error['code'] }.join(', ')
end
case response.status
when 404
raise Fog::Errors::NotFound.new(msg)
else
raise Fog::Errors::Error.new(msg)
end
end
response
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/gems/did_you_mean-1.0.0/lib/did_you_mean/verbose_formatter.rb
|
# -*- frozen-string-literal: true -*-
require 'did_you_mean/formatter'
module DidYouMean
module VerboseFormatter
prepend_features DidYouMean::Formatter
def to_s
return "" if @corrections.empty?
output = "\n\n Did you mean? ".dup
output << @corrections.join("\n ")
output << "\n "
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/lib/rexml/light/node.rb
|
require 'rexml/xmltokens'
# [ :element, parent, name, attributes, children* ]
# a = Node.new
# a << "B" # => <a>B</a>
# a.b # => <a>B<b/></a>
# a.b[1] # => <a>B<b/><b/><a>
# a.b[1]["x"] = "y" # => <a>B<b/><b x="y"/></a>
# a.b[0].c # => <a>B<b><c/></b><b x="y"/></a>
# a.b.c << "D" # => <a>B<b><c>D</c></b><b x="y"/></a>
module REXML
module Light
# Represents a tagged XML element. Elements are characterized by
# having children, attributes, and names, and can themselves be
# children.
class Node
NAMESPLIT = /^(?:(#{XMLTokens::NCNAME_STR}):)?(#{XMLTokens::NCNAME_STR})/u
PARENTS = [ :element, :document, :doctype ]
# Create a new element.
def initialize node=nil
@node = node
if node.kind_of? String
node = [ :text, node ]
elsif node.nil?
node = [ :document, nil, nil ]
elsif node[0] == :start_element
node[0] = :element
elsif node[0] == :start_doctype
node[0] = :doctype
elsif node[0] == :start_document
node[0] = :document
end
end
def size
if PARENTS.include? @node[0]
@node[-1].size
else
0
end
end
def each( &block )
size.times { |x| yield( at(x+4) ) }
end
def name
at(2)
end
def name=( name_str, ns=nil )
pfx = ''
pfx = "#{prefix(ns)}:" if ns
_old_put(2, "#{pfx}#{name_str}")
end
def parent=( node )
_old_put(1,node)
end
def local_name
namesplit
@name
end
def local_name=( name_str )
_old_put( 1, "#@prefix:#{name_str}" )
end
def prefix( namespace=nil )
prefix_of( self, namespace )
end
def namespace( prefix=prefix() )
namespace_of( self, prefix )
end
def namespace=( namespace )
@prefix = prefix( namespace )
pfx = ''
pfx = "#@prefix:" if @prefix.size > 0
_old_put(1, "#{pfx}#@name")
end
def []( reference, ns=nil )
if reference.kind_of? String
pfx = ''
pfx = "#{prefix(ns)}:" if ns
at(3)["#{pfx}#{reference}"]
elsif reference.kind_of? Range
_old_get( Range.new(4+reference.begin, reference.end, reference.exclude_end?) )
else
_old_get( 4+reference )
end
end
def =~( path )
XPath.match( self, path )
end
# Doesn't handle namespaces yet
def []=( reference, ns, value=nil )
if reference.kind_of? String
value = ns unless value
at( 3 )[reference] = value
elsif reference.kind_of? Range
_old_put( Range.new(3+reference.begin, reference.end, reference.exclude_end?), ns )
else
if value
_old_put( 4+reference, ns, value )
else
_old_put( 4+reference, ns )
end
end
end
# Append a child to this element, optionally under a provided namespace.
# The namespace argument is ignored if the element argument is an Element
# object. Otherwise, the element argument is a string, the namespace (if
# provided) is the namespace the element is created in.
def << element
if node_type() == :text
at(-1) << element
else
newnode = Node.new( element )
newnode.parent = self
self.push( newnode )
end
at(-1)
end
def node_type
_old_get(0)
end
def text=( foo )
replace = at(4).kind_of?(String)? 1 : 0
self._old_put(4,replace, normalizefoo)
end
def root
context = self
context = context.at(1) while context.at(1)
end
def has_name?( name, namespace = '' )
at(3) == name and namespace() == namespace
end
def children
self
end
def parent
at(1)
end
def to_s
end
private
def namesplit
return if @name.defined?
at(2) =~ NAMESPLIT
@prefix = '' || $1
@name = $2
end
def namespace_of( node, prefix=nil )
if not prefix
name = at(2)
name =~ NAMESPLIT
prefix = $1
end
to_find = 'xmlns'
to_find = "xmlns:#{prefix}" if not prefix.nil?
ns = at(3)[ to_find ]
ns ? ns : namespace_of( @node[0], prefix )
end
def prefix_of( node, namespace=nil )
if not namespace
name = node.name
name =~ NAMESPLIT
$1
else
ns = at(3).find { |k,v| v == namespace }
ns ? ns : prefix_of( node.parent, namespace )
end
end
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/lib/rexml/functions.rb
|
# frozen_string_literal: false
module REXML
# If you add a method, keep in mind two things:
# (1) the first argument will always be a list of nodes from which to
# filter. In the case of context methods (such as position), the function
# should return an array with a value for each child in the array.
# (2) all method calls from XML will have "-" replaced with "_".
# Therefore, in XML, "local-name()" is identical (and actually becomes)
# "local_name()"
module Functions
@@context = nil
@@namespace_context = {}
@@variables = {}
def Functions::namespace_context=(x) ; @@namespace_context=x ; end
def Functions::variables=(x) ; @@variables=x ; end
def Functions::namespace_context ; @@namespace_context ; end
def Functions::variables ; @@variables ; end
def Functions::context=(value); @@context = value; end
def Functions::text( )
if @@context[:node].node_type == :element
return @@context[:node].find_all{|n| n.node_type == :text}.collect{|n| n.value}
elsif @@context[:node].node_type == :text
return @@context[:node].value
else
return false
end
end
# Returns the last node of the given list of nodes.
def Functions::last( )
@@context[:size]
end
def Functions::position( )
@@context[:index]
end
# Returns the size of the given list of nodes.
def Functions::count( node_set )
node_set.size
end
# Since REXML is non-validating, this method is not implemented as it
# requires a DTD
def Functions::id( object )
end
# UNTESTED
def Functions::local_name( node_set=nil )
get_namespace( node_set ) do |node|
return node.local_name
end
end
def Functions::namespace_uri( node_set=nil )
get_namespace( node_set ) {|node| node.namespace}
end
def Functions::name( node_set=nil )
get_namespace( node_set ) do |node|
node.expanded_name
end
end
# Helper method.
def Functions::get_namespace( node_set = nil )
if node_set == nil
yield @@context[:node] if defined? @@context[:node].namespace
else
if node_set.respond_to? :each
node_set.each { |node| yield node if defined? node.namespace }
elsif node_set.respond_to? :namespace
yield node_set
end
end
end
# A node-set is converted to a string by returning the string-value of the
# node in the node-set that is first in document order. If the node-set is
# empty, an empty string is returned.
#
# A number is converted to a string as follows
#
# NaN is converted to the string NaN
#
# positive zero is converted to the string 0
#
# negative zero is converted to the string 0
#
# positive infinity is converted to the string Infinity
#
# negative infinity is converted to the string -Infinity
#
# if the number is an integer, the number is represented in decimal form
# as a Number with no decimal point and no leading zeros, preceded by a
# minus sign (-) if the number is negative
#
# otherwise, the number is represented in decimal form as a Number
# including a decimal point with at least one digit before the decimal
# point and at least one digit after the decimal point, preceded by a
# minus sign (-) if the number is negative; there must be no leading zeros
# before the decimal point apart possibly from the one required digit
# immediately before the decimal point; beyond the one required digit
# after the decimal point there must be as many, but only as many, more
# digits as are needed to uniquely distinguish the number from all other
# IEEE 754 numeric values.
#
# The boolean false value is converted to the string false. The boolean
# true value is converted to the string true.
#
# An object of a type other than the four basic types is converted to a
# string in a way that is dependent on that type.
def Functions::string( object=nil )
#object = @context unless object
if object.instance_of? Array
string( object[0] )
elsif defined? object.node_type
if object.node_type == :attribute
object.value
elsif object.node_type == :element || object.node_type == :document
string_value(object)
else
object.to_s
end
elsif object.nil?
return ""
else
object.to_s
end
end
# A node-set is converted to a string by
# returning the concatenation of the string-value
# of each of the children of the node in the
# node-set that is first in document order.
# If the node-set is empty, an empty string is returned.
def Functions::string_value( o )
rv = ""
o.children.each { |e|
if e.node_type == :text
rv << e.to_s
elsif e.node_type == :element
rv << string_value( e )
end
}
rv
end
# UNTESTED
def Functions::concat( *objects )
objects.join
end
# Fixed by <NAME>
def Functions::starts_with( string, test )
string(string).index(string(test)) == 0
end
# Fixed by <NAME>
def Functions::contains( string, test )
string(string).include?(string(test))
end
# Kouhei fixed this
def Functions::substring_before( string, test )
ruby_string = string(string)
ruby_index = ruby_string.index(string(test))
if ruby_index.nil?
""
else
ruby_string[ 0...ruby_index ]
end
end
# Kouhei fixed this too
def Functions::substring_after( string, test )
ruby_string = string(string)
return $1 if ruby_string =~ /#{test}(.*)/
""
end
# Take equal portions of <NAME> and <NAME>; mix
# vigorously, and pour into a tall, chilled glass. Serves 10,000.
def Functions::substring( string, start, length=nil )
ruby_string = string(string)
ruby_length = if length.nil?
ruby_string.length.to_f
else
number(length)
end
ruby_start = number(start)
# Handle the special cases
return '' if (
ruby_length.nan? or
ruby_start.nan? or
ruby_start.infinite?
)
infinite_length = ruby_length.infinite? == 1
ruby_length = ruby_string.length if infinite_length
# Now, get the bounds. The XPath bounds are 1..length; the ruby bounds
# are 0..length. Therefore, we have to offset the bounds by one.
ruby_start = ruby_start.round - 1
ruby_length = ruby_length.round
if ruby_start < 0
ruby_length += ruby_start unless infinite_length
ruby_start = 0
end
return '' if ruby_length <= 0
ruby_string[ruby_start,ruby_length]
end
# UNTESTED
def Functions::string_length( string )
string(string).length
end
# UNTESTED
def Functions::normalize_space( string=nil )
string = string(@@context[:node]) if string.nil?
if string.kind_of? Array
string.collect{|x| string.to_s.strip.gsub(/\s+/um, ' ') if string}
else
string.to_s.strip.gsub(/\s+/um, ' ')
end
end
# This is entirely Mike Stok's beast
def Functions::translate( string, tr1, tr2 )
from = string(tr1)
to = string(tr2)
# the map is our translation table.
#
# if a character occurs more than once in the
# from string then we ignore the second &
# subsequent mappings
#
# if a character maps to nil then we delete it
# in the output. This happens if the from
# string is longer than the to string
#
# there's nothing about - or ^ being special in
# http://www.w3.org/TR/xpath#function-translate
# so we don't build ranges or negated classes
map = Hash.new
0.upto(from.length - 1) { |pos|
from_char = from[pos]
unless map.has_key? from_char
map[from_char] =
if pos < to.length
to[pos]
else
nil
end
end
}
if ''.respond_to? :chars
string(string).chars.collect { |c|
if map.has_key? c then map[c] else c end
}.compact.join
else
string(string).unpack('U*').collect { |c|
if map.has_key? c then map[c] else c end
}.compact.pack('U*')
end
end
# UNTESTED
def Functions::boolean( object=nil )
if object.kind_of? String
if object =~ /\d+/u
return object.to_f != 0
else
return object.size > 0
end
elsif object.kind_of? Array
object = object.find{|x| x and true}
end
return object ? true : false
end
# UNTESTED
def Functions::not( object )
not boolean( object )
end
# UNTESTED
def Functions::true( )
true
end
# UNTESTED
def Functions::false( )
false
end
# UNTESTED
def Functions::lang( language )
lang = false
node = @@context[:node]
attr = nil
until node.nil?
if node.node_type == :element
attr = node.attributes["xml:lang"]
unless attr.nil?
lang = compare_language(string(language), attr)
break
else
end
end
node = node.parent
end
lang
end
def Functions::compare_language lang1, lang2
lang2.downcase.index(lang1.downcase) == 0
end
# a string that consists of optional whitespace followed by an optional
# minus sign followed by a Number followed by whitespace is converted to
# the IEEE 754 number that is nearest (according to the IEEE 754
# round-to-nearest rule) to the mathematical value represented by the
# string; any other string is converted to NaN
#
# boolean true is converted to 1; boolean false is converted to 0
#
# a node-set is first converted to a string as if by a call to the string
# function and then converted in the same way as a string argument
#
# an object of a type other than the four basic types is converted to a
# number in a way that is dependent on that type
def Functions::number( object=nil )
object = @@context[:node] unless object
case object
when true
Float(1)
when false
Float(0)
when Array
number(string( object ))
when Numeric
object.to_f
else
str = string( object )
# If XPath ever gets scientific notation...
#if str =~ /^\s*-?(\d*\.?\d+|\d+\.)([Ee]\d*)?\s*$/
if str =~ /^\s*-?(\d*\.?\d+|\d+\.)\s*$/
str.to_f
else
(0.0 / 0.0)
end
end
end
def Functions::sum( nodes )
nodes = [nodes] unless nodes.kind_of? Array
nodes.inject(0) { |r,n| r + number(string(n)) }
end
def Functions::floor( number )
number(number).floor
end
def Functions::ceiling( number )
number(number).ceil
end
def Functions::round( number )
begin
number(number).round
rescue FloatDomainError
number(number)
end
end
def Functions::processing_instruction( node )
node.node_type == :processing_instruction
end
def Functions::method_missing( id )
puts "METHOD MISSING #{id.id2name}"
XPath.match( @@context[:node], id.id2name )
end
end
end
|
arnab0073/idea
|
.rvm/src/ruby-2.3.0/test/fileutils/visibility_tests.rb
|
# frozen_string_literal: false
require 'test/unit'
require 'fileutils'
class TestFileUtils < Test::Unit::TestCase
end
##
# These tests are reused in the FileUtils::Verbose, FileUtils::NoWrite and
# FileUtils::DryRun tests
module TestFileUtils::Visibility
FileUtils::METHODS.each do |m|
define_method "test_singleton_visibility_#{m}" do
assert @fu_module.respond_to?(m, true),
"FileUtils::Verbose.#{m} is not defined"
assert @fu_module.respond_to?(m, false),
"FileUtils::Verbose.#{m} is not public"
end
define_method "test_visibility_#{m}" do
assert respond_to?(m, true),
"FileUtils::Verbose\##{m} is not defined"
assert @fu_module.private_method_defined?(m),
"FileUtils::Verbose\##{m} is not private"
end
end
FileUtils::StreamUtils_.private_instance_methods.each do |m|
define_method "test_singleton_visibility_#{m}" do
assert @fu_module.respond_to?(m, true),
"FileUtils::Verbose\##{m} is not defined"
end
define_method "test_visibility_#{m}" do
assert respond_to?(m, true),
"FileUtils::Verbose\##{m} is not defined"
end
end
end
|
arnab0073/idea
|
.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/rvm-1.11.3.9/lib/rvm/errors.rb
|
module RVM
# Generic error in RVM
class Error < StandardError; end
# Generic error with the shell command output attached.
# The RVM::Shell::Result instance is available via +#result+.
class ErrorWithResult < Error
attr_reader :result
def initialize(result, message = nil)
@result = result
super message
end
end
# Something occurred while processing the command and RVM couldn't parse the results.
class IncompleteCommandError < Error; end
# The given action can't replace the env for the current process.
# Typically raised by RVM::Environment#gemset_use when the gemset
# is for another, incompatible ruby interpreter.
#
# Provides access to the output of the shell command via +#result+.
class IncompatibleRubyError < ErrorWithResult; end
# Called when tools.path_identifier is called on a dir with an untrusted rvmrc.
class ErrorLoadingRVMRC < Error; end
end
|
arnab0073/idea
|
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tk/textimage.rb
|
<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tk/textimage.rb<gh_stars>1-10
#
# tk/textimage.rb - treat Tk text image object
#
require 'tk'
require 'tk/text'
class TkTextImage<TkObject
include Tk::Text::IndexModMethods
def initialize(parent, index, keys)
#unless parent.kind_of?(Tk::Text)
# fail ArgumentError, "expect Tk::Text for 1st argument"
#end
@t = parent
if index == 'end' || index == :end
@path = TkTextMark.new(@t, tk_call(@t.path, 'index', 'end - 1 chars'))
elsif index.kind_of? TkTextMark
if tk_call_without_enc(@t.path,'index',index.path) == tk_call_without_enc(@t.path,'index','end')
@path = TkTextMark.new(@t, tk_call_without_enc(@t.path, 'index',
'end - 1 chars'))
else
@path = TkTextMark.new(@t, tk_call_without_enc(@t.path, 'index',
index.path))
end
else
@path = TkTextMark.new(@t, tk_call_without_enc(@t.path, 'index',
_get_eval_enc_str(index)))
end
@path.gravity = 'left'
@index = @path.path
@id = tk_call_without_enc(@t.path, 'image', 'create', @index,
*hash_kv(keys, true)).freeze
@path.gravity = 'right'
end
def id
Tk::Text::IndexString.new(@id)
end
def mark
@path
end
def [](slot)
cget(slot)
end
def []=(slot, value)
configure(slot, value)
value
end
def cget(slot)
@t.image_cget(@index, slot)
end
def cget_strict(slot)
@t.image_cget_strict(@index, slot)
end
def configure(slot, value=None)
@t.image_configure(@index, slot, value)
self
end
# def configure(slot, value)
# tk_call @t.path, 'image', 'configure', @index, "-#{slot}", value
# end
def configinfo(slot = nil)
@t.image_configinfo(@index, slot)
end
def current_configinfo(slot = nil)
@t.current_image_configinfo(@index, slot)
end
def image
img = tk_call_without_enc(@t.path, 'image', 'cget', @index, '-image')
TkImage::Tk_IMGTBL[img]? TkImage::Tk_IMGTBL[img] : img
end
def image=(value)
tk_call_without_enc(@t.path, 'image', 'configure', @index, '-image',
_get_eval_enc_str(value))
#self
value
end
end
TktImage = TkTextImage
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.