repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
arnab0073/idea
.rvm/src/ruby-2.3.0/ext/psych/lib/psych/nodes/node.rb
<reponame>arnab0073/idea<filename>.rvm/src/ruby-2.3.0/ext/psych/lib/psych/nodes/node.rb # frozen_string_literal: false require 'stringio' require 'psych/class_loader' require 'psych/scalar_scanner' module Psych module Nodes ### # The base class for any Node in a YAML parse tree. This class should # never be instantiated. class Node include Enumerable # The children of this node attr_reader :children # An associated tag attr_reader :tag # Create a new Psych::Nodes::Node def initialize @children = [] end ### # Iterate over each node in the tree. Yields each node to +block+ depth # first. def each &block return enum_for :each unless block_given? Visitors::DepthFirst.new(block).accept self end ### # Convert this node to Ruby. # # See also Psych::Visitors::ToRuby def to_ruby Visitors::ToRuby.create.accept(self) end alias :transform :to_ruby ### # Convert this node to YAML. # # See also Psych::Visitors::Emitter def yaml io = nil, options = {} real_io = io || StringIO.new(''.encode('utf-8')) Visitors::Emitter.new(real_io, options).accept self return real_io.string unless io io end alias :to_yaml :yaml end end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/mixlib-log-1.6.0/spec/mixlib/log_spec.rb
<reponame>arnab0073/idea # # Author:: <NAME> (<<EMAIL>>) # Author:: <NAME> (<<EMAIL>>) # Copyright:: Copyright (c) 2008 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'tempfile' require 'stringio' require File.expand_path(File.join(File.dirname(__FILE__), "..", "spec_helper")) class LoggerLike attr_accessor :level attr_reader :messages def initialize @messages = "" end [:debug, :info, :warn, :error, :fatal].each do |method_name| class_eval(<<-E) def #{method_name}(message) @messages << message end E end end describe Mixlib::Log do # Since we are testing class behaviour for an instance variable # that gets set once, we need to reset it prior to each example [cb] before(:each) do Logit.reset! end it "creates a logger using an IO object" do io = StringIO.new Logit.init(io) Logit << "foo" io.string.should match(/foo/) end it "creates a logger with a file name" do Tempfile.open("chef-test-log") do |tempfile| Logit.init(tempfile.path) Logit << "bar" tempfile.rewind tempfile.read.should match(/bar/) end end it "uses the logger provided when initialized with a logger like object" do logger = LoggerLike.new Logit.init(logger) Logit.debug "qux" logger.messages.should match(/qux/) end it "should re-initialize the logger if init is called again" do first_logdev, second_logdev = StringIO.new, StringIO.new Logit.init(first_logdev) Logit.fatal "FIRST" first_logdev.string.should match(/FIRST/) Logit.init(second_logdev) Logit.fatal "SECOND" first_logdev.string.should_not match(/SECOND/) second_logdev.string.should match(/SECOND/) end it "should set the log level using the binding form, with :debug, :info, :warn, :error, or :fatal" do levels = { :debug => Logger::DEBUG, :info => Logger::INFO, :warn => Logger::WARN, :error => Logger::ERROR, :fatal => Logger::FATAL } levels.each do |symbol, constant| Logit.level = symbol Logit.logger.level.should == constant Logit.level.should == symbol end end it "passes blocks to the underlying logger object" do logdev = StringIO.new Logit.init(logdev) Logit.fatal { "the_message" } logdev.string.should match(/the_message/) end it "should set the log level using the method form, with :debug, :info, :warn, :error, or :fatal" do levels = { :debug => Logger::DEBUG, :info => Logger::INFO, :warn => Logger::WARN, :error => Logger::ERROR, :fatal => Logger::FATAL } levels.each do |symbol, constant| Logit.level(symbol) Logit.logger.level.should == constant end end it "should raise an ArgumentError if you try and set the level to something strange using the binding form" do lambda { Logit.level = :the_roots }.should raise_error(ArgumentError) end it "should raise an ArgumentError if you try and set the level to something strange using the method form" do lambda { Logit.level(:the_roots) }.should raise_error(ArgumentError) end it "should pass other method calls directly to logger" do Logit.level = :debug Logit.should be_debug lambda { Logit.debug("Gimme some sugar!") }.should_not raise_error end it "should default to STDOUT if init is called with no arguments" do logger_mock = Struct.new(:formatter, :level).new Logger.stub!(:new).and_return(logger_mock) Logger.should_receive(:new).with(STDOUT).and_return(logger_mock) Logit.init end it "should have by default a base log level of warn" do logger_mock = Struct.new(:formatter, :level).new Logger.stub!(:new).and_return(logger_mock) Logit.init Logit.level.should eql(:warn) end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkconsole.rb
<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkconsole.rb # # tkconsole.rb - load tk/console.rb # require 'tk/console'
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tk/console.rb
# # tk/console.rb : control the console on system without a real console # require 'tk' module TkConsole include Tk extend Tk TkCommandNames = ['console'.freeze, 'consoleinterp'.freeze].freeze def self.create TkCore::INTERP._create_console end self.create # initialize console def self.title(str=None) tk_call 'console', str end def self.hide tk_call_without_enc('console', 'hide') end def self.show tk_call_without_enc('console', 'show') end def self.eval(tcl_script) # # supports a Tcl script only # I have no idea to support a Ruby script seamlessly. # _fromUTF8(tk_call_without_enc('console', 'eval', _get_eval_enc_str(tcl_script))) end def self.maininterp_eval(tcl_script) # # supports a Tcl script only # I have no idea to support a Ruby script seamlessly. # _fromUTF8(tk_call_without_enc('consoleinterp', 'eval', _get_eval_enc_str(tcl_script))) end def self.maininterp_record(tcl_script) # # supports a Tcl script only # I have no idea to support a Ruby script seamlessly. # _fromUTF8(tk_call_without_enc('consoleinterp', 'record', _get_eval_enc_str(tcl_script))) end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/mixlib-log-1.6.0/lib/mixlib/log/version.rb
module Mixlib module Log VERSION = "1.6.0" end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/fiddle/lib/fiddle.rb
require 'fiddle.so' require 'fiddle/function' require 'fiddle/closure' require 'dl' unless Object.const_defined?(:DL) module Fiddle # A reference to DL::CPtr Pointer = DL::CPtr if WINDOWS # Returns the last win32 +Error+ of the current executing +Thread+ or nil # if none def self.win32_last_error Thread.current[:__FIDDLE_WIN32_LAST_ERROR__] end # Sets the last win32 +Error+ of the current executing +Thread+ to +error+ def self.win32_last_error= error Thread.current[:__FIDDLE_WIN32_LAST_ERROR__] = error end end # Returns the last +Error+ of the current executing +Thread+ or nil if none def self.last_error Thread.current[:__FIDDLE_LAST_ERROR__] end # Sets the last +Error+ of the current executing +Thread+ to +error+ def self.last_error= error Thread.current[:__DL2_LAST_ERROR__] = error Thread.current[:__FIDDLE_LAST_ERROR__] = error end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/benchmark/bm_vm1_block.rb
<filename>.rvm/src/ruby-1.9.3-p551/benchmark/bm_vm1_block.rb<gh_stars>0 def m yield end i=0 while i<30_000_000 # while loop 1 i+=1 m{ } end
arnab0073/idea
.rvm/src/ruby-2.3.0/lib/rdoc/markup/to_markdown.rb
# frozen_string_literal: false # :markup: markdown ## # Outputs parsed markup as Markdown class RDoc::Markup::ToMarkdown < RDoc::Markup::ToRdoc ## # Creates a new formatter that will output Markdown format text def initialize markup = nil super @headings[1] = ['# ', ''] @headings[2] = ['## ', ''] @headings[3] = ['### ', ''] @headings[4] = ['#### ', ''] @headings[5] = ['##### ', ''] @headings[6] = ['###### ', ''] add_special_RDOCLINK add_special_TIDYLINK @hard_break = " \n" end ## # Maps attributes to HTML sequences def init_tags add_tag :BOLD, '**', '**' add_tag :EM, '*', '*' add_tag :TT, '`', '`' end ## # Adds a newline to the output def handle_special_HARD_BREAK special " \n" end ## # Finishes consumption of `list` def accept_list_end list @res << "\n" super end ## # Finishes consumption of `list_item` def accept_list_item_end list_item width = case @list_type.last when :BULLET then 4 when :NOTE, :LABEL then use_prefix 4 else @list_index[-1] = @list_index.last.succ 4 end @indent -= width end ## # Prepares the visitor for consuming `list_item` def accept_list_item_start list_item type = @list_type.last case type when :NOTE, :LABEL then bullets = Array(list_item.label).map do |label| attributes(label).strip end.join "\n" bullets << "\n:" @prefix = ' ' * @indent @indent += 4 @prefix << bullets + (' ' * (@indent - 1)) else bullet = type == :BULLET ? '*' : @list_index.last.to_s + '.' @prefix = (' ' * @indent) + bullet.ljust(4) @indent += 4 end end ## # Prepares the visitor for consuming `list` def accept_list_start list case list.type when :BULLET, :LABEL, :NOTE then @list_index << nil when :LALPHA, :NUMBER, :UALPHA then @list_index << 1 else raise RDoc::Error, "invalid list type #{list.type}" end @list_width << 4 @list_type << list.type end ## # Adds `rule` to the output def accept_rule rule use_prefix or @res << ' ' * @indent @res << '-' * 3 @res << "\n" end ## # Outputs `verbatim` indented 4 columns def accept_verbatim verbatim indent = ' ' * (@indent + 4) verbatim.parts.each do |part| @res << indent unless part == "\n" @res << part end @res << "\n" unless @res =~ /\n\z/ end ## # Creates a Markdown-style URL from +url+ with +text+. def gen_url url, text scheme, url, = parse_url url "[#{text.sub(%r{^#{scheme}:/*}i, '')}](#{url})" end ## # Handles <tt>rdoc-</tt> type links for footnotes. def handle_rdoc_link url case url when /^rdoc-ref:/ then $' when /^rdoc-label:footmark-(\d+)/ then "[^#{$1}]:" when /^rdoc-label:foottext-(\d+)/ then "[^#{$1}]" when /^rdoc-label:label-/ then gen_url url, $' when /^rdoc-image:/ then "![](#{$'})" when /^rdoc-[a-z]+:/ then $' end end ## # Converts the RDoc markup tidylink into a Markdown.style link. def handle_special_TIDYLINK special text = special.text return text unless text =~ /\{(.*?)\}\[(.*?)\]/ or text =~ /(\S+)\[(.*?)\]/ label = $1 url = $2 if url =~ /^rdoc-label:foot/ then handle_rdoc_link url else gen_url url, label end end ## # Converts the rdoc-...: links into a Markdown.style links. def handle_special_RDOCLINK special handle_rdoc_link special.text end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/demos-en/bind.rb
<reponame>arnab0073/idea # bind.rb # # This demonstration script creates a text widget with bindings set # up for hypertext-like effects. # # text (tag bindings) widget demo (called by 'widget') # # toplevel widget if defined?($bind_demo) && $bind_demo $bind_demo.destroy $bind_demo = nil end # demo toplevel widget $bind_demo = TkToplevel.new {|w| title("Text Demonstration - Tag Bindings") iconname("bind") positionWindow(w) } base_frame = TkFrame.new($bind_demo).pack(:fill=>:both, :expand=>true) # frame TkFrame.new(base_frame) {|frame| TkButton.new(frame) { text 'Dismiss' command proc{ tmppath = $bind_demo $bind_demo = nil tmppath.destroy } }.pack('side'=>'left', 'expand'=>'yes') TkButton.new(frame) { text 'Show Code' command proc{showCode 'bind'} }.pack('side'=>'left', 'expand'=>'yes') }.pack('side'=>'bottom', 'fill'=>'x', 'pady'=>'2m') # bind def tag_binding_for_bind_demo(tag, enter_style, leave_style) tag.bind('Any-Enter', proc{tag.configure enter_style}) tag.bind('Any-Leave', proc{tag.configure leave_style}) end # text txt = TkText.new(base_frame){|t| # setgrid 'true' #width 60 #height 24 font $font wrap 'word' TkScrollbar.new(base_frame) {|s| pack('side'=>'right', 'fill'=>'y') command proc{|*args| t.yview(*args)} t.yscrollcommand proc{|first,last| s.set first,last} } pack('expand'=>'yes', 'fill'=>'both') # if TkWinfo.depth($root).to_i > 1 tagstyle_bold = {'background'=>'#43ce80', 'relief'=>'raised', 'borderwidth'=>1} tagstyle_normal = {'background'=>'', 'relief'=>'flat'} else tagstyle_bold = {'foreground'=>'white', 'background'=>'black'} tagstyle_normal = {'foreground'=>'', 'background'=>''} end # insert text insert 'insert', "The same tag mechanism that controls display styles in text widgets can also be used to associate Tcl commands with regions of text, so that mouse or keyboard actions on the text cause particular Tcl commands to be invoked. For example, in the text below the descriptions of the canvas demonstrations have been tagged. When you move the mouse over a demo description the description lights up, and when you press button 1 over a description then that particular demonstration is invoked. " insert('end', '1. Samples of all the different types of items that can be created in canvas widgets.', (d1 = TkTextTag.new(t)) ) insert('end', "\n\n") insert('end', '2. A simple two-dimensional plot that allows you to adjust the positions of the data points.', (d2 = TkTextTag.new(t)) ) insert('end', "\n\n") insert('end', '3. Anchoring and justification modes for text items.', (d3 = TkTextTag.new(t)) ) insert('end', "\n\n") insert('end', '4. An editor for arrow-head shapes for line items.', (d4 = TkTextTag.new(t)) ) insert('end', "\n\n") insert('end', '5. A ruler with facilities for editing tab stops.', (d5 = TkTextTag.new(t)) ) insert('end', "\n\n") insert('end', '6. A grid that demonstrates how canvases can be scrolled.', (d6 = TkTextTag.new(t)) ) # binding [d1, d2, d3, d4, d5, d6].each{|tag| tag_binding_for_bind_demo(tag, tagstyle_bold, tagstyle_normal) } d1.bind('1', proc{ eval_samplecode(`cat #{[$demo_dir,'items.rb'].join(File::Separator)}`, 'items.rb') }) d2.bind('1', proc{ eval_samplecode(`cat #{[$demo_dir,'plot.rb'].join(File::Separator)}`, 'plot.rb') }) d3.bind('1', proc{ eval_samplecode(`cat #{[$demo_dir,'ctext.rb'].join(File::Separator)}`, 'ctext.rb') }) d4.bind('1', proc{ eval_samplecode(`cat #{[$demo_dir,'arrow.rb'].join(File::Separator)}`, 'arrow.rb') }) d5.bind('1', proc{ eval_samplecode(`cat #{[$demo_dir,'ruler.rb'].join(File::Separator)}`, 'ruler.rb') }) d6.bind('1', proc{ eval_samplecode(`cat #{[$demo_dir,'cscroll.rb'].join(File::Separator)}`, 'cscroll.rb') }) TkTextMarkInsert.new(t, '0.0') configure('state','disabled') } txt.width 60 txt.height 24
arnab0073/idea
.rvm/src/ruby-2.3.0/ext/tk/sample/tkextlib/bwidget/manager.rb
# frozen_string_literal: false # # manager demo --- called from demo.rb # unless Object.const_defined?('DemoVar') fail RuntimeError, "This is NOT a stand alone script. This script is called from 'demo.rb'. " end module DemoManager @@progress = TkVariable.new(false) @@status = TkVariable.new('Compute in progress...') @@homogeneous = TkVariable.new(false) @@constw = TkVariable.new @@afterobj = nil def self.create(nb) frame = nb.insert('end', 'demoManager', :text=>'Manager') topf = TkFrame.new(frame) titf1 = Tk::BWidget::TitleFrame.new(topf, :text=>"MainFrame") titf2 = Tk::BWidget::TitleFrame.new(topf, :text=>"NoteBook") titf3 = Tk::BWidget::TitleFrame.new(frame, :text=>"Paned & ScrolledWindow") _mainframe(titf1.get_frame) _notebook(titf2.get_frame) _paned(titf3.get_frame) Tk.pack(titf1, titf2, :padx=>4, :side=>:left, :fill=>:both, :expand=>true) Tk.pack(topf, :fill=>:x, :pady=>2) Tk.pack(titf3, :pady=>2, :padx=>4, :fill=>:both, :expand=>true) frame end def self._mainframe(parent) labf1 = Tk::BWidget::LabelFrame.new(parent, :text=>'Toolbar', :side=>:top, :anchor=>:w, :relief=>:sunken, :borderwidth=>2) subf = labf1.get_frame chk1 = TkCheckbutton.new(subf, :text=>'View toolbar 1', :variable=>DemoVar.toolbar1, :command=>proc{ DemoVar.mainframe.show_toolbar( 0, DemoVar.toolbar1.value ) }) chk2 = TkCheckbutton.new(subf, :text=>'View toolbar 2', :variable=>DemoVar.toolbar2, :command=>proc{ DemoVar.mainframe.show_toolbar( 1, DemoVar.toolbar2.value ) }) Tk.pack(chk1, chk2, :anchor=>:w, :fill=>:x) labf1.pack(:fill=>:both) labf2 = Tk::BWidget::LabelFrame.new(parent, :text=>'Status bar', :side=>:top, :anchor=>:w, :relief=>:sunken, :borderwidth=>2) subf = labf2.get_frame chk1 = TkCheckbutton.new(subf, :text=>"Show Progress\nindicator", :justify=>:left, :variable=>@@progress, :command=>proc{ _show_progress }) chk1.pack(:anchor=>:w, :fill=>:x) Tk.pack(labf1, labf2, :side=>:left, :padx=>4, :fill=>:both) end def self._notebook(parent) TkCheckbutton.new(parent, :text=>'Homogeneous label', :variable=>@@homogeneous, :command=>proc{ DemoVar.notebook[:homogeneous] = @@homogeneous.value }).pack(:side=>:left, :anchor=>:n, :fill=>:x) end def self._paned(parent) pw1 = Tk::BWidget::PanedWindow.new(parent, :side=>:top) pane = pw1.add(:minsize=>100) pw2 = Tk::BWidget::PanedWindow.new(pane, :side=>:left) pane1 = pw2.add(:minsize=>100) pane2 = pw2.add(:minsize=>100) pane3 = pw1.add(:minsize=>100) [pane1, pane2].each{|pane| sw = Tk::BWidget::ScrolledWindow.new(pane) lb = TkListbox.new(sw, :height=>8, :width=>20, :highlightthickness=>0) (1..8).each{|i| lb.insert('end', "Valur #{i}") } sw.set_widget(lb) sw.pack(:fill=>:both, :expand=>true) } sw = Tk::BWidget::ScrolledWindow.new(pane3, :relief=>:sunken, :borderwidth=>2) sf = Tk::BWidget::ScrollableFrame.new(sw) sw.set_widget(sf) subf = sf.get_frame lab = TkLabel.new(subf, :text=>'This is a ScrollableFrame') chk = TkCheckbutton.new(subf, :text=>'Constrained with', :variable=>@@constw, :command=>proc{ sf['constrainedwidth'] = @@constw.value }) lab.pack chk.pack(:anchor=>:w) chk.bind('FocusIn', proc{sf.see(chk)}) (0..20).each{|i| ent = TkEntry.new(subf, :width=>50).pack(:fill=>:x, :pady=>4) ent.bind('FocusIn', proc{sf.see(ent)}) ent.insert('end', "Text field #{i}") } Tk.pack(sw, pw2, pw1, :fill=>:both, :expand=>true) end def self._show_progress unless @@afterobj @@afterobj = TkTimer.new(30, -1, proc{_update_progress}) end if @@progress.bool DemoVar.status.value = 'Compute in progress...' DemoVar.prgindic.value = 0 DemoVar.mainframe.show_statusbar(:progression) @@afterobj.start unless @@afterobj.running? else DemoVar.status.value = '' DemoVar.mainframe.show_statusbar(:status) @@afterobj.stop end end def self._update_progress if @@progress.bool if DemoVar.prgindic.numeric < 100 DemoVar.prgindic.numeric += 5 else @@progress.value = false DemoVar.mainframe.show_statusbar(:status) DemoVar.status.value = 'Done' @@afterobj.stop Tk.after(500, proc{ DemoVar.status.value = '' }) end else @@afterobj.stop end end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/benchmark/bm_vm_thread_pass_flood.rb
<filename>.rvm/src/ruby-1.9.3-p551/benchmark/bm_vm_thread_pass_flood.rb 1000.times{ Thread.new{loop{Thread.pass}} } i=0 while i<10000 i += 1 end
arnab0073/idea
.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/executable-hooks-1.3.2/lib/executable-hooks/uninstaller.rb
<filename>.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/executable-hooks-1.3.2/lib/executable-hooks/uninstaller.rb require 'executable-hooks/wrapper' require 'executable-hooks/regenerate_binstubs_command' module ExecutableHooks def self.uninstall Gem.configuration[:custom_shebang] = "$env #{Gem.default_exec_format % "ruby"}" RegenerateBinstubsCommand.new.execute_no_wrapper Wrapper.uninstall end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/cloudstack/models/compute/public_ip_address.rb
module Fog module Compute class Cloudstack class PublicIpAddress < Fog::Model identity :id, :aliases => 'id' attribute :network_id, :aliases => 'networkid' attribute :associated_network_id, :aliases => 'associatednetworkid' attribute :physical_network_id, :aliases => 'physicalnetworkid' attribute :ip_address, :aliases => 'ipaddress' attribute :mac_address, :aliases => 'macaddress' attribute :state, :aliases => 'state' attribute :traffic_type, :aliases => 'traffictype' attribute :is_default, :aliases => 'isdefault', :type => :boolean attribute :is_source_nat, :aliases => 'issourcenat', :type => :boolean attribute :is_static_nat, :aliases => 'isstaticnat', :type => :boolean attribute :is_system, :aliases => 'issytem', :type => :boolean attribute :is_portable, :aliases => 'isportable', :type => :boolean attribute :allocated, :aliases => 'allocated', :type => :time attribute :zone_id, :aliases => 'zone_id' attribute :domain_id, :aliases => 'domain_id' attribute :tags, :type => :array attribute :type def save requires :display_text, :name options = { 'displaytext' => display_text, 'name' => name, 'customized' => is_customized, 'disksize' => disk_size, 'domain_id' => domain_id, 'storagetype' => storage_type, 'tags' => tags } response = service.associate_ip_address(options) merge_attributes(response['associateipaddressresponse']) end def destroy requires :id response = service.disassociate_ip_address('id' => id ) success_status = response['disassociateipaddressresponse']['success'] success_status == 'true' end end end end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/winrm-1.8.1/spec/output_spec.rb
<reponame>arnab0073/idea # encoding: UTF-8 describe WinRM::Output, unit: true do subject { WinRM::Output.new } context 'when there is no output' do describe '#stdout' do it 'is empty' do expect(subject.stdout).to be_empty end end describe '#stderr' do it 'is empty' do expect(subject.stderr).to be_empty end end describe '#output' do it 'is empty' do expect(subject.output).to be_empty end end end context 'when there is only one line' do describe '#stdout' do it 'is equal to that line' do subject[:data] << { stdout: 'foo' } expect(subject.stdout).to eq('foo') end end describe '#stderr' do it 'is equal to that line' do subject[:data] << { stderr: 'foo' } expect(subject.stderr).to eq('foo') end end describe '#output' do it 'is equal to stdout' do subject[:data] << { stdout: 'foo' } expect(subject.output).to eq('foo') end it 'is equal to stderr' do subject[:data] << { stderr: 'foo' } expect(subject.output).to eq('foo') end end end context 'when there is one line of each type' do before(:each) do subject[:data] << { stdout: 'foo' } subject[:data] << { stderr: 'bar' } end describe '#stdout' do it 'is equal to that line' do expect(subject.stdout).to eq('foo') end end describe '#stderr' do it 'is equal to that line' do expect(subject.stderr).to eq('bar') end end describe '#output' do it 'is equal to stdout + stderr' do expect(subject.output).to eq('foobar') end end end context 'when there are multiple lines' do before(:each) do subject[:data] << { stdout: 'I can have a newline\nanywhere, ' } subject[:data] << { stderr: 'I can also have stderr' } subject[:data] << { stdout: 'or stdout', stderr: ' and stderr' } subject[:data] << {} subject[:data] << { stdout: ' or nothing! (above)' } end describe '#stdout' do it 'is equal to that line' do expect(subject.stdout).to eq( 'I can have a newline\nanywhere, or stdout or nothing! (above)') end end describe '#stderr' do it 'is equal to that line' do expect(subject.stderr).to eq('I can also have stderr and stderr') end end describe '#output' do it 'is equal to stdout + stderr' do expect(subject.output).to eq( 'I can have a newline\nanywhere, I can also have stderror stdout ' \ 'and stderr or nothing! (above)') end end end pending 'parse CLIXML errors and convert to Strings and/or Exceptions' end
arnab0073/idea
.rvm/src/ruby-2.3.0/test/rubygems/rubygems_plugin.rb
<reponame>arnab0073/idea # frozen_string_literal: false require 'rubygems/command_manager' ## # This is an example of exactly what NOT to do. # # DO NOT include code like this in your rubygems_plugin.rb class Gem::Commands::InterruptCommand < Gem::Command def initialize super('interrupt', 'Raises an Interrupt Exception', {}) end def execute raise Interrupt, "Interrupt exception" end end Gem::CommandManager.instance.register_command :interrupt
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/tool/merger.rb
#! /bin/ruby # This needs ruby 1.9 and subversion. # run this in a repository to commit. require 'date' require 'tempfile' $repos = 'svn+ssh://<EMAIL>@ci.ruby-lang.org/ruby/' ENV['LC_ALL'] = 'C' def help puts <<-end simple backport ruby #$0 1234 range backport ruby #$0 1234:5678 backport from other branch ruby #$0 17502 mvm revision increment ruby #$0 revisionup tagging ruby #$0 tag * all operations shall be applied to the working directory. end end def version v = p = nil open 'version.h', 'rb' do |f| f.each_line do |l| case l when /^#define RUBY_VERSION "(\d)\.(\d)\.(\d)"$/ v = $~.captures when /^#define RUBY_PATCHLEVEL (-?\d+)$/ p = $1 end end end return v, p end def interactive str loop do yield STDERR.puts str case STDIN.gets when /\Aa/i then exit when /\Ar/i then redo when /\Ay/i then break else exit end end end def version_up d = DateTime.now d = d.new_offset(Rational(9,24)) # we need server locale (i.e. japanese) time system *%w'svn revert version.h' v, p = version teeny = v[2] case v when %w/1 9 2/ teeny = 1 end p = p.to_i if p != -1 p += 1 end str = open 'version.h', 'rb' do |f| f.read end [%W[RUBY_VERSION "#{v.join '.'}"], %W[RUBY_VERSION_CODE #{v.join ''}], %W[RUBY_VERSION_MAJOR #{v[0]}], %W[RUBY_VERSION_MINOR #{v[1]}], %W[RUBY_VERSION_TEENY #{teeny}], %W[RUBY_RELEASE_DATE "#{d.strftime '%Y-%m-%d'}"], %W[RUBY_RELEASE_CODE #{d.strftime '%Y%m%d'}], %W[RUBY_PATCHLEVEL #{p}], %W[RUBY_RELEASE_YEAR #{d.year}], %W[RUBY_RELEASE_MONTH #{d.month}], %W[RUBY_RELEASE_DAY #{d.day}], ].each do |(k, i)| str.sub! /^(#define\s+#{k}\s+).*$/, "\\1#{i}" end str.sub! /\s+\z/m, '' fn = sprintf 'version.h.tmp.%032b', rand(1 << 31) File.rename 'version.h', fn open 'version.h', 'wb' do |f| f.puts str end File.unlink fn end def tag intv_p = false v, p = version x = v.join('_') y = $repos + 'branches/ruby_' + x z = 'v' + x + '_' + p w = $repos + 'tags/' + z if intv_p interactive "OK? svn cp -m \"add tag #{z}\" #{y} #{w} ([y]es|[a]bort|[r]etry)" do end end system *%w'svn cp -m' + ["add tag #{z}"] + [y, w] end def default_merge_branch %r{^URL: .*/branches/ruby_1_8_} =~ `svn info` ? 'branches/ruby_1_8' : 'trunk' end case ARGV[0] when "up", /\A(ver|version|rev|revision|lv|level|patch\s*level)\s*up/ version_up system 'svn diff version.h' when "tag" tag :interactive when nil, "-h", "--help" help exit else q = $repos + (ARGV[1] || default_merge_branch) revs = ARGV[0].split /,\s*/ log = '' log_svn = '' revs.each do |rev| case rev when /\A\d+:\d+\z/ r = ['-r', rev] when /\A\d+\z/ r = ['-c', rev] when nil then puts "#$0 revision" exit end l = IO.popen %w'svn diff' + r + %w'--diff-cmd=diff -x -pU0' + [File.join(q, 'ChangeLog')] do |f| f.read end log << l log_svn << l.lines.grep(/^\+\t/).join.gsub(/^\+/, '').gsub(/^\t\*/, "\n\t\*") if log_svn.empty? log_svn = IO.popen %w'svn log ' + r + [q] do |f| f.read end end a = %w'svn merge --accept=postpone' + r + [q] STDERR.puts a.join(' ') system(*a) system *%w'svn revert ChangeLog' if /^\+/ =~ l end if /^\+/ =~ log system *%w'svn revert ChangeLog' IO.popen %w'patch -p0', 'wb' do |f| f.write log.gsub(/\+(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [ 123][0-9] [012][0-9]:[0-5][0-9]:[0-5][0-9] \d\d\d\d/, # this format-time-string was from the file local variables of ChangeLog '+'+Time.now.strftime('%a %b %e %H:%M:%S %Y')) end system *%w'touch ChangeLog' # needed somehow, don't know why... else STDERR.puts '*** You should write ChangeLog NOW!!! ***' end version_up f = Tempfile.new 'merger.rb' f.printf "merge revision(s) %s:\n", ARGV[0] f.write log_svn f.flush f.close f.open # avoid gc interactive 'conflicts resolved? (y:yes, a:abort, r:retry, otherwise abort)' do f.rewind IO.popen('-', 'wb') do |g| if g g << `svn stat` g << "\n\n" g << f.read g << "\n\n" g << `svn diff --diff-cmd=diff -x -upw` else exec 'less' end end Process.waitall end if system *%w'svn ci -F' + [f.path] # tag :interactive # no longer needed. system 'rm -f subversion.commitlog' else puts 'commit failed; try again.' end f.close end
arnab0073/idea
.rvm/src/ruby-2.3.0/test/psych/test_tree_builder.rb
# frozen_string_literal: false require_relative 'helper' module Psych class TestTreeBuilder < TestCase def setup super @parser = Psych::Parser.new TreeBuilder.new @parser.parse(<<-eoyml) %YAML 1.1 --- - foo - { bar : &A !!str baz, boo : *A } - *A eoyml @tree = @parser.handler.root end def test_stream assert_instance_of Nodes::Stream, @tree end def test_documents assert_equal 1, @tree.children.length assert_instance_of Nodes::Document, @tree.children.first doc = @tree.children.first assert_equal [1,1], doc.version assert_equal [], doc.tag_directives assert_equal false, doc.implicit end def test_sequence doc = @tree.children.first assert_equal 1, doc.children.length seq = doc.children.first assert_instance_of Nodes::Sequence, seq assert_nil seq.anchor assert_nil seq.tag assert_equal true, seq.implicit assert_equal Nodes::Sequence::BLOCK, seq.style end def test_scalar doc = @tree.children.first seq = doc.children.first assert_equal 3, seq.children.length scalar = seq.children.first assert_instance_of Nodes::Scalar, scalar assert_equal 'foo', scalar.value assert_nil scalar.anchor assert_nil scalar.tag assert_equal true, scalar.plain assert_equal false, scalar.quoted assert_equal Nodes::Scalar::PLAIN, scalar.style end def test_mapping doc = @tree.children.first seq = doc.children.first map = seq.children[1] assert_instance_of Nodes::Mapping, map end def test_alias doc = @tree.children.first seq = doc.children.first assert_equal 3, seq.children.length al = seq.children[2] assert_instance_of Nodes::Alias, al assert_equal 'A', al.anchor end end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tktext.rb
# # tktext.rb - load tk/text.rb # require 'tk/text'
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkdialog.rb
# # tkdialog.rb - load tk/dialog.rb # require 'tk/dialog'
arnab0073/idea
.rvm/src/ruby-2.3.0/test/-ext-/bignum/test_big2str.rb
# frozen_string_literal: false require 'test/unit' require "-test-/bignum" class TestBignum < Test::Unit::TestCase class TestBig2str < Test::Unit::TestCase SIZEOF_BDIGIT = Bignum::SIZEOF_BDIGIT BITSPERDIG = Bignum::BITSPERDIG BDIGMAX = (1 << BITSPERDIG) - 1 def test_big2str_generic x = 10**1000 assert_equal("1" + "0" * 1000, x.big2str_generic(10)) end def test_big2str_poweroftwo e = BITSPERDIG*2 x = 0b10**e assert_equal("1" + "0" * e, x.big2str_poweroftwo(2)) end def test_big2str_gmp x = 10**1000 assert_equal("1" + "0" * 1000, x.big2str_gmp(10)) rescue NotImplementedError end end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/itk/setup.rb
# # setup.rb -- setup script before calling TkPackage.require() # # If you need some setup operations (for example, add a library path # to the library search path) before using Tcl/Tk library packages # wrapped by Ruby scripts in this directory, please write the setup # operations in this file. # # set [incr Tk] library directory # ENV['ITK_LIBRARY'] = '/usr/local/ActiveTcl/lib/itk3.2/'
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/puma-1.6.3/lib/puma/jruby_restart.rb
<filename>.rvm/gems/ruby-2.3.0/gems/puma-1.6.3/lib/puma/jruby_restart.rb require 'ffi' module Puma module JRubyRestart extend FFI::Library ffi_lib 'c' attach_function :execlp, [:string, :varargs], :int attach_function :chdir, [:string], :int def self.chdir_exec(dir, cmd, *argv) chdir(dir) argv.unshift(cmd) argv = ([:string] * argv.size).zip(argv).flatten argv <<:int argv << 0 execlp(cmd, *argv) raise SystemCallError.new(FFI.errno) end end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/vu/canvSticker.rb
<reponame>arnab0073/idea #!/usr/bin/env ruby require 'tk' require 'tkextlib/vu/charts' ####################################### Tk.root.geometry('+30+30') delay = 2000 c = TkCanvas.new.pack begin st = Tk::Vu::TkcSticker.new(c, 0, 0, 10, 10) rescue Tk.messageBox(:type=>'ok', :title=>"No sticker Item", :message=>"This build of vu does not include the sticker item") exit end #st.delete steps = [] steps << proc{ # I used a 75dpi screen for testing, but others should make no difference! puts 'You\'ll see a small upright rectangle with "He" inside.' st = Tk::Vu::TkcSticker.new(c, '6m', '10m', '13m', '27m', :text=>'Hello') } steps << proc{ puts 'You\'ll see the whole "Hello" drawn rotated 90 degrees.' st[:orient] = :vertical } steps << proc{ puts 'The rectangle shrinks and the text is clipped to "Hell"' #st.coords('6m', '10m', '13m', '20m') st.coords('6m', '10m', '13m', '17m') } steps << proc{ puts 'Now you\'ll read "ello"' st[:lefttrunc] = true } steps << proc{ puts 'Enlarging the rectangle shows the complete "Hello" again' st.scale(0, 0, 3, 3) } steps << proc{ puts 'This time the text is repeated: "Hello", approx. 5mm space, "Hello"' st[:space] = '5m' } steps << proc{ puts 'A vertical bar appears in the lower right region and text jumps to the left.' st.configure(:anchor=>:n, :relw=>0.3, :relh=>0.7, :relx=>0.6, :rely=>0.3, :bar=>'red') } steps << proc{ puts 'Paint the backgound.' st[:fill] = 'yellow' } steps << proc{ puts "Let's test stippling." st[:stipple] = 'gray25' } steps << proc{ puts 'Finally a large outline forces a single "Hello" and shrinks the bar.' st[:width] = '6m' } Tk.root.bind('q', proc{exit}) TkTimer.new(delay, 1, *steps).start Tk.mainloop
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/bwidget/statusbar.rb
<reponame>arnab0073/idea<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/bwidget/statusbar.rb # # tkextlib/bwidget/statusbar.rb # by <NAME> (<EMAIL>) # require 'tk' require 'tk/frame' require 'tkextlib/bwidget.rb' module Tk module BWidget class StatusBar < TkWindow end end end class Tk::BWidget::StatusBar TkCommandNames = ['StatusBar'.freeze].freeze WidgetClassName = 'StatusBar'.freeze WidgetClassNames[WidgetClassName] ||= self def __boolval_optkeys super() << 'showresize' << 'showseparator' << 'showresizesep' end private :__boolval_optkeys def add(win, keys={}) tk_send('add', win, keys) self end def remove(*wins) tk_send('remove', *wins) self end def remove_with_destroy(*wins) tk_send('remove', '-destroy', *wins) self end def delete(*wins) # same to 'remove_with_destroy' tk_send('delete', *wins) self end def get_frame(&b) win = window(tk_send_without_enc('getframe')) if b if TkCore::WITH_RUBY_VM ### Ruby 1.9 !!!! win.instance_exec(self, &b) else win.instance_eval(&b) end end win end def items simplelist(tk_send('items')).map{|w| window(w)} end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/spec/unit/plugins/darwin/system_profiler_spec.rb
<gh_stars>0 # # Author:: <NAME> (<<EMAIL>>) # Copyright:: Copyright (c) 2012 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper.rb') require File.expand_path("#{File.dirname(__FILE__)}/system_profiler_output.rb") begin require 'plist' rescue LoadError => e puts "The darwin systemprofile plugin spec tests will fail without the 'plist' library/gem.\n\n" raise e end describe Ohai::System, "Darwin system_profiler plugin", :unix_only do before(:each) do @ohai = Ohai::System.new @ohai.stub!(:require_plugin).and_return(true) end it "should return the right serial number" do mini_cmd = "system_profiler -xml -detailLevel mini SPParallelATAData SPAudioData SPBluetoothData" mini_cmd += " SPCardReaderData SPDiagnosticsData SPDiscBurningData SPEthernetData SPFibreChannelData" mini_cmd += " SPFireWireData SPDisplaysData SPHardwareRAIDData SPMemoryData SPModemData SPNetworkData" mini_cmd += " SPPCIData SPParallelSCSIData SPPrintersSoftwareData SPPrintersData SPSASData SPSerialATAData" mini_cmd += " SPSoftwareData SPThunderboltData SPUSBData SPWWANData SPAirPortData" full_cmd = "system_profiler -xml -detailLevel full SPHardwareDataType" @ohai.stub!(:popen4).with(full_cmd).and_yield(nil, StringIO.new, StringIO.new(SystemProfilerOutput::Full), nil) @ohai.stub!(:popen4).with(mini_cmd).and_yield(nil, StringIO.new, StringIO.new(SystemProfilerOutput::Mini), nil) @ohai._require_plugin("darwin::system_profiler") @ohai['system_profile'][18]["_items"][0]["serial_number"].should == 'ABCDEFG12345' end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/specifications/excon-0.49.0.gemspec
<reponame>arnab0073/idea # -*- encoding: utf-8 -*- # stub: excon 0.49.0 ruby lib Gem::Specification.new do |s| s.name = "excon" s.version = "0.49.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.require_paths = ["lib"] s.authors = ["dpiddy (<NAME>)", "geemus (<NAME>)", "nextmat (<NAME>)"] s.date = "2016-03-28" s.description = "EXtended http(s) CONnections" s.email = "<EMAIL>" s.extra_rdoc_files = ["README.md"] s.files = ["README.md"] s.homepage = "https://github.com/excon/excon" s.licenses = ["MIT"] s.rdoc_options = ["--charset=UTF-8"] s.rubyforge_project = "excon" s.rubygems_version = "2.5.1" s.summary = "speed, persistence, http(s)" s.installed_by_version = "2.5.1" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 2 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<activesupport>, [">= 0"]) s.add_development_dependency(%q<delorean>, [">= 0"]) s.add_development_dependency(%q<eventmachine>, [">= 1.0.4"]) s.add_development_dependency(%q<open4>, [">= 0"]) s.add_development_dependency(%q<rake>, [">= 0"]) s.add_development_dependency(%q<rdoc>, [">= 0"]) s.add_development_dependency(%q<shindo>, [">= 0"]) s.add_development_dependency(%q<sinatra>, [">= 0"]) s.add_development_dependency(%q<sinatra-contrib>, [">= 0"]) s.add_development_dependency(%q<json>, [">= 1.8.2"]) else s.add_dependency(%q<activesupport>, [">= 0"]) s.add_dependency(%q<delorean>, [">= 0"]) s.add_dependency(%q<eventmachine>, [">= 1.0.4"]) s.add_dependency(%q<open4>, [">= 0"]) s.add_dependency(%q<rake>, [">= 0"]) s.add_dependency(%q<rdoc>, [">= 0"]) s.add_dependency(%q<shindo>, [">= 0"]) s.add_dependency(%q<sinatra>, [">= 0"]) s.add_dependency(%q<sinatra-contrib>, [">= 0"]) s.add_dependency(%q<json>, [">= 1.8.2"]) end else s.add_dependency(%q<activesupport>, [">= 0"]) s.add_dependency(%q<delorean>, [">= 0"]) s.add_dependency(%q<eventmachine>, [">= 1.0.4"]) s.add_dependency(%q<open4>, [">= 0"]) s.add_dependency(%q<rake>, [">= 0"]) s.add_dependency(%q<rdoc>, [">= 0"]) s.add_dependency(%q<shindo>, [">= 0"]) s.add_dependency(%q<sinatra>, [">= 0"]) s.add_dependency(%q<sinatra-contrib>, [">= 0"]) s.add_dependency(%q<json>, [">= 1.8.2"]) end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/bin.rb
<reponame>arnab0073/idea<filename>.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/bin.rb require 'fog/core/credentials' module Fog class << self def available_providers @available_providers ||= Fog.providers.values.select {|provider| Kernel.const_get(provider).available?}.sort end def registered_providers @registered_providers ||= Fog.providers.values.sort end end class Bin class << self def available? availability = true for service in services begin service = self.class_for(service) availability &&= service.requirements.all? { |requirement| Fog.credentials.include?(requirement) } rescue ArgumentError => e Fog::Logger.warning(e.message) availability = false rescue => e availability = false end end if availability for service in services for collection in self.class_for(service).collections unless self.respond_to?(collection) self.class_eval <<-EOS, __FILE__, __LINE__ def self.#{collection} self[:#{service}].#{collection} end EOS end end end end availability end def collections services.map {|service| self[service].collections}.flatten.sort_by {|service| service.to_s} end end end end require 'fog/bin/atmos' require 'fog/bin/aws' require 'fog/bin/bluebox' require 'fog/bin/brightbox' require 'fog/bin/cloudstack' require 'fog/bin/clodo' require 'fog/bin/digitalocean' require 'fog/bin/dnsimple' require 'fog/bin/dnsmadeeasy' require 'fog/bin/fogdocker' require 'fog/bin/dreamhost' require 'fog/bin/dynect' require 'fog/bin/ecloud' require 'fog/bin/glesys' require 'fog/bin/go_grid' require 'fog/bin/google' require 'fog/bin/hp' require 'fog/bin/ibm' require 'fog/bin/internet_archive' require 'fog/bin/joyent' require 'fog/bin/libvirt' require 'fog/bin/linode' require 'fog/bin/local' require 'fog/bin/bare_metal_cloud' require 'fog/bin/ninefold' require 'fog/bin/rackspace' require 'fog/bin/rage4' require 'fog/bin/riakcs' require 'fog/bin/openstack' require 'fog/bin/ovirt' require 'fog/bin/powerdns' require 'fog/bin/profitbricks' require 'fog/bin/sakuracloud' require 'fog/bin/serverlove' require 'fog/bin/softlayer' require 'fog/bin/storm_on_demand' require 'fog/bin/terremark' require 'fog/bin/vcloud' require 'fog/bin/vcloud_director' require 'fog/bin/vmfusion' require 'fog/bin/vsphere' require 'fog/bin/voxel' require 'fog/bin/xenserver' require 'fog/bin/zerigo' require 'fog/bin/cloudsigma' require 'fog/bin/openvz' require 'fog/bin/opennebula'
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/test/net/smtp/test_smtp.rb
<gh_stars>0 require 'net/smtp' require 'minitest/autorun' module Net class TestSMTP < MiniTest::Unit::TestCase def test_critical smtp = Net::SMTP.new 'localhost', 25 assert_raises RuntimeError do smtp.send :critical do raise 'fail on purpose' end end assert_kind_of Net::SMTP::Response, smtp.send(:critical), '[Bug #9125]' end def test_esmtp smtp = Net::SMTP.new 'localhost', 25 assert smtp.esmtp assert smtp.esmtp? smtp.esmtp = 'omg' assert_equal 'omg', smtp.esmtp assert_equal 'omg', smtp.esmtp? end end end
arnab0073/idea
.rvm/src/ruby-2.3.0/gems/test-unit-3.1.5/lib/test/unit/version.rb
module Test module Unit VERSION = '3.1.5' end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/rubyntlm-0.6.0/lib/net/ntlm/blob.rb
module Net module NTLM BLOB_SIGN = 0x00000101 class Blob < FieldSet int32LE :blob_signature, {:value => BLOB_SIGN} int32LE :reserved, {:value => 0} int64LE :timestamp, {:value => 0} string :challenge, {:value => "", :size => 8} int32LE :unknown1, {:value => 0} string :target_info, {:value => "", :size => 0} int32LE :unknown2, {:value => 0} def parse(str, offset=0) # 28 is the length of all fields before the variable-length # target_info field. if str.size > 28 enable(:target_info) # Grab everything except the last 4 bytes (which will be :unknown2) self[:target_info].value = str[28..-5] end super end end end end
arnab0073/idea
.rvm/src/ruby-2.3.0/ext/psych/lib/psych_jars.rb
# frozen_string_literal: false require 'psych/versions' require 'psych.jar' require 'jar-dependencies' require_jar('org.yaml', 'snakeyaml', Psych::DEFAULT_SNAKEYAML_VERSION)
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/net-ssh-multi-1.2.0/lib/net/ssh/multi/channel.rb
<reponame>arnab0073/idea<filename>.rvm/gems/ruby-2.3.0/gems/net-ssh-multi-1.2.0/lib/net/ssh/multi/channel.rb<gh_stars>1-10 module Net; module SSH; module Multi # Net::SSH::Multi::Channel encapsulates a collection of Net::SSH::Connection::Channel # instances from multiple different connections. It allows for operations to # be performed on all contained channels, simultaneously, using an interface # mostly identical to Net::SSH::Connection::Channel itself. # # You typically obtain a Net::SSH::Multi::Channel instance via # Net::SSH::Multi::Session#open_channel or Net::SSH::Multi::Session#exec, # though there is nothing stopping you from instantiating one yourself with # a handful of Net::SSH::Connection::Channel objects (though they should be # associated with connections managed by a Net::SSH::Multi::Session object # for consistent behavior). # # channel = session.open_channel do |ch| # # ... # end # # channel.wait class Channel include Enumerable # The Net::SSH::Multi::Session instance that controls this channel collection. attr_reader :connection # The collection of Net::SSH::Connection::Channel instances that this multi-channel aggregates. attr_reader :channels # A Hash of custom properties that may be set and queried on this object. attr_reader :properties # Instantiate a new Net::SSH::Multi::Channel instance, controlled by the # given +connection+ (a Net::SSH::Multi::Session object) and wrapping the # given +channels+ (Net::SSH::Connection::Channel instances). # # You will typically never call this directly; rather, you'll get your # multi-channel references via Net::SSH::Multi::Session#open_channel and # friends. def initialize(connection, channels) @connection = connection @channels = channels @properties = {} end # Iterate over each component channel object, yielding each in order to the # associated block. def each @channels.each { |channel| yield channel } end # Retrieve the property (see #properties) with the given +key+. # # host = channel[:host] def [](key) @properties[key] end # Set the property (see #properties) with the given +key+ to the given # +value+. # # channel[:visited] = true def []=(key, value) @properties[key] = value end # Perform an +exec+ command on all component channels. The block, if given, # is passed to each component channel, so it will (potentially) be invoked # once for every channel in the collection. The block will receive two # parameters: the specific channel object being operated on, and a boolean # indicating whether the exec succeeded or not. # # channel.exec "ls -l" do |ch, success| # # ... # end # # See the documentation in Net::SSH for Net::SSH::Connection::Channel#exec # for more information on how to work with the callback. def exec(command, &block) channels.each { |channel| channel.exec(command, &block) } self end # Perform a +request_pty+ command on all component channels. The block, if # given, is passed to each component channel, so it will (potentially) be # invoked once for every channel in the collection. The block will # receive two parameters: the specific channel object being operated on, # and a boolean indicating whether the pty request succeeded or not. # # channel.request_pty do |ch, success| # # ... # end # # See the documentation in Net::SSH for # Net::SSH::Connection::Channel#request_pty for more information on how to # work with the callback. def request_pty(opts={}, &block) channels.each { |channel| channel.request_pty(opts, &block) } self end # Send the given +data+ to each component channel. It will be sent to the # remote process, typically being received on the process' +stdin+ stream. # # channel.send_data "password\n" def send_data(data) channels.each { |channel| channel.send_data(data) } self end # Returns true as long as any of the component channels are active. # # connection.loop { channel.active? } def active? channels.any? { |channel| channel.active? } end # Runs the connection's event loop until the channel is no longer active # (see #active?). # # channel.exec "something" # channel.wait def wait connection.loop { active? } self end # Closes all component channels. def close channels.each { |channel| channel.close } self end # Tells the remote process for each component channel not to expect any # further data from this end of the channel. def eof! channels.each { |channel| channel.eof! } self end # Registers a callback on all component channels, to be invoked when the # remote process emits data (usually on its +stdout+ stream). The block # will be invoked with two arguments: the specific channel object, and the # data that was received. # # channel.on_data do |ch, data| # puts "got data: #{data}" # end def on_data(&block) channels.each { |channel| channel.on_data(&block) } self end # Registers a callback on all component channels, to be invoked when the # remote process emits "extended" data (typically on its +stderr+ stream). # The block will be invoked with three arguments: the specific channel # object, an integer describing the data type (usually a 1 for +stderr+) # and the data that was received. # # channel.on_extended_data do |ch, type, data| # puts "got extended data: #{data}" # end def on_extended_data(&block) channels.each { |channel| channel.on_extended_data(&block) } self end # Registers a callback on all component channels, to be invoked during the # idle portion of the connection event loop. The callback will be invoked # with one argument: the specific channel object being processed. # # channel.on_process do |ch| # # ... # end def on_process(&block) channels.each { |channel| channel.on_process(&block) } self end # Registers a callback on all component channels, to be invoked when the # remote server terminates the channel. The callback will be invoked # with one argument: the specific channel object being closed. # # channel.on_close do |ch| # # ... # end def on_close(&block) channels.each { |channel| channel.on_close(&block) } self end # Registers a callback on all component channels, to be invoked when the # remote server has no further data to send. The callback will be invoked # with one argument: the specific channel object being marked EOF. # # channel.on_eof do |ch| # # ... # end def on_eof(&block) channels.each { |channel| channel.on_eof(&block) } self end # Registers a callback on all component channels, to be invoked when the # remote server is unable to open the channel. The callback will be # invoked with three arguments: the channel object that couldn't be # opened, a description of the error (as a string), and an integer code # representing the error. # # channel.on_open_failed do |ch, description, code| # # ... # end def on_open_failed(&block) channels.each { |channel| channel.on_open_failed(&block) } self end # Registers a callback on all component channels, to be invoked when the # remote server sends a channel request of the given +type+. The callback # will be invoked with two arguments: the specific channel object receiving # the request, and a Net::SSH::Buffer instance containing the request-specific # data. # # channel.on_request("exit-status") do |ch, data| # puts "exited with #{data.read_long}" # end def on_request(type, &block) channels.each { |channel| channel.on_request(type, &block) } self end end end; end; end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/demos-en/vscale.rb
# vscale.rb # # This demonstration script shows an example with a vertical scale. require "tkcanvas" if defined?($vscale_demo) && $vscale_demo $vscale_demo.destroy $vscale_demo = nil end $vscale_demo = TkToplevel.new {|w| title("Vertical Scale Demonstration") iconname("vscale") } positionWindow($vscale_demo) base_frame = TkFrame.new($vscale_demo).pack(:fill=>:both, :expand=>true) msg = TkLabel.new(base_frame) { font $font wraplength '3.5i' justify 'left' text "An arrow and a vertical scale are displayed below. If you click or drag mouse button 1 in the scale, you can change the size of the arrow." } msg.pack('side'=>'top', 'padx'=>'.5c') TkFrame.new(base_frame) {|frame| TkButton.new(frame) { text 'Dismiss' command proc { tmppath = $vscale_demo $vscale_demo = nil tmppath.destroy } }.pack('side'=>'left', 'expand'=>'yes') TkButton.new(frame) { text 'Show Code' command proc { showCode 'vscale' } }.pack('side'=>'left', 'expand'=>'yes') }.pack('side'=>'bottom', 'fill'=>'x', 'pady'=>'2m') def setHeight(w, height) height = height + 21 y2 = height - 30 if y2 < 21 y2 = 21 end w.coords 'poly',15,20,35,20,35,y2,45,y2,25,height,5,y2,15,y2,15,20 w.coords 'line',15,20,35,20,35,y2,45,y2,25,height,5,y2,15,y2,15,20 end TkFrame.new(base_frame) {|frame| borderwidth 10 canvas = TkCanvas.new(frame) {|c| width 50 height 50 bd 0 highlightthickness 0 TkcPolygon.new(c, 0, 0, 1, 1, 2, 2) { fill 'SeaGreen3' tags 'poly' } TkcLine.new(c, 0, 0, 1, 1, 2, 2, 0, 0) { fill 'black' tags 'line' } }.pack('side'=>'left', 'anchor'=>'nw', 'fill'=>'y') scale = TkScale.new(frame) { orient 'vertical' length 284 from 0 to 250 command proc{|value| setHeight(canvas, value)} tickinterval 50 }.pack('side'=>'left', 'anchor'=>'ne') scale.set 75 }.pack
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/gem_prelude.rb
require 'rubygems.rb' if defined?(Gem)
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/net-ssh-multi-1.2.0/test/test_all.rb
# $ ruby -Ilib -Itest -rrubygems test/test_all.rb # $ ruby -Ilib -Itest -rrubygems test/channel_test.rb Dir["#{File.dirname(__FILE__)}/**/*_test.rb"].each do |file| load(file) end
arnab0073/idea
.rvm/src/ruby-2.3.0/lib/rubygems/resolver/molinillo/lib/molinillo.rb
<reponame>arnab0073/idea # frozen_string_literal: false require 'rubygems/resolver/molinillo/lib/molinillo/gem_metadata' require 'rubygems/resolver/molinillo/lib/molinillo/errors' require 'rubygems/resolver/molinillo/lib/molinillo/resolver' require 'rubygems/resolver/molinillo/lib/molinillo/modules/ui' require 'rubygems/resolver/molinillo/lib/molinillo/modules/specification_provider'
arnab0073/idea
.rvm/src/ruby-2.3.0/tool/rbuninstall.rb
<reponame>arnab0073/idea<filename>.rvm/src/ruby-2.3.0/tool/rbuninstall.rb #! /usr/bin/ruby -nl BEGIN { $dryrun = false $tty = STDOUT.tty? until ARGV.empty? case ARGV[0] when /\A--destdir=(.*)/ $destdir = $1 when /\A-n\z/ $dryrun = true when /\A--(?:no-)?tty\z/ $tty = !$1 else break end ARGV.shift end $dirs = [] $files = [] } list = ($_.chomp!('/') ? $dirs : $files) $_ = File.join($destdir, $_) if $destdir list << $_ END { status = true $\ = ors = (!$dryrun and $tty) ? "\e[K\r" : "\n" $files.each do |file| print "rm #{file}" unless $dryrun begin File.unlink(file) rescue Errno::ENOENT rescue status = false puts $! end end end unlink = {} $dirs.each do |dir| unlink[dir] = true end while dir = $dirs.pop print "rmdir #{dir}" unless $dryrun begin begin unlink.delete(dir) Dir.rmdir(dir) rescue Errno::ENOTDIR raise unless File.symlink?(dir) File.unlink(dir) end rescue Errno::ENOENT, Errno::ENOTEMPTY rescue status = false puts $! else parent = File.dirname(dir) $dirs.push(parent) unless parent == dir or unlink[parent] end end end $\ = nil print ors.chomp exit(status) }
arnab0073/idea
.rvm/src/ruby-2.3.0/lib/rdoc/i18n/locale.rb
# frozen_string_literal: false ## # A message container for a locale. # # This object provides the following two features: # # * Loads translated messages from .po file. # * Translates a message into the locale. class RDoc::I18n::Locale @@locales = {} # :nodoc: class << self ## # Returns the locale object for +locale_name+. def [](locale_name) @@locales[locale_name] ||= new(locale_name) end ## # Sets the locale object for +locale_name+. # # Normally, this method is not used. This method is useful for # testing. def []=(locale_name, locale) @@locales[locale_name] = locale end end ## # The name of the locale. It uses IETF language tag format # +[language[_territory][.codeset][@modifier]]+. # # See also {BCP 47 - Tags for Identifying # Languages}[http://tools.ietf.org/rfc/bcp/bcp47.txt]. attr_reader :name ## # Creates a new locale object for +name+ locale. +name+ must # follow IETF language tag format. def initialize(name) @name = name @messages = {} end ## # Loads translation messages from +locale_directory+/+@name+/rdoc.po # or +locale_directory+/+@name+.po. The former has high priority. # # This method requires gettext gem for parsing .po file. If you # don't have gettext gem, this method doesn't load .po file. This # method warns and returns +false+. # # Returns +true+ if succeeded, +false+ otherwise. def load(locale_directory) return false if @name.nil? po_file_candidates = [ File.join(locale_directory, @name, 'rdoc.po'), File.join(locale_directory, "#{@name}.po"), ] po_file = po_file_candidates.find do |po_file_candidate| File.exist?(po_file_candidate) end return false unless po_file begin require 'gettext/po_parser' require 'gettext/mo' rescue LoadError warn('Need gettext gem for i18n feature:') warn(' gem install gettext') return false end po_parser = GetText::POParser.new messages = GetText::MO.new po_parser.report_warning = false po_parser.parse_file(po_file, messages) @messages.merge!(messages) true end ## # Translates the +message+ into locale. If there is no tranlsation # messages for +message+ in locale, +message+ itself is returned. def translate(message) @messages[message] || message end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/-test-/win32/dln/extconf.rb
if $mingw or $mswin $objs = ["dlntest.o"] testdll = "$(topdir)/dlntest.dll" $cleanfiles << testdll config_string('cleanobjs') {|t| $cleanfiles.concat(t.gsub(/\$\*/, 'dlntest').split)} create_makefile("-test-/win32/dln") m = File.read("Makefile") dlntestlib = "dlntest.#{$LIBEXT}" m.sub!(/^OBJS =.*/) {"#{$&} #{dlntestlib}"} FileUtils.rm_f(RbConfig.expand(testdll.dup)) open("Makefile", "wb") do |mf| mf.puts m, "\n" sodir = $extout ? "$(RUBYARCHDIR)/" : '' mf.print "#{sodir}$(DLLIB): #{dlntestlib}" mf.puts mf.puts "#{dlntestlib}: $(topdir)/dlntest.dll" mf.puts if $mingw mf.puts "$(topdir)/dlntest.dll: DEFFILE := $(srcdir)/libdlntest.def" mf.puts "$(topdir)/dlntest.dll: DLDFLAGS += -Wl,--out-implib,#{dlntestlib}" end mf.puts depend_rules("$(topdir)/dlntest.dll: libdlntest.o libdlntest.def") mf.puts "\t$(ECHO) linking shared-object $(@F)\n" mf.print "\t-$(Q)$(RM) $@\n" mf.print "\t-$(Q)$(MAKEDIRS) $(@D)\n" if $extout link_so = LINK_SO.gsub(/^/, "\t$(Q) ") link_so.sub!(/\$\(LOCAL_LIBS\)/, '') link_so.gsub!(/-\$\(arch\)/, '') link_so.gsub!(/:.so=/, ':.dll=') link_so.sub!(/\$\(OBJS\)/, "libdlntest.#{$OBJEXT}") link_so.sub!(/\$\(DEFFILE\)/, "$(srcdir)/libdlntest.def") mf.puts link_so mf.puts end end
arnab0073/idea
.rvm/src/ruby-2.3.0/lib/rubygems/deprecate.rb
<reponame>arnab0073/idea<filename>.rvm/src/ruby-2.3.0/lib/rubygems/deprecate.rb # frozen_string_literal: false ## # Provides a single method +deprecate+ to be used to declare when # something is going away. # # class Legacy # def self.klass_method # # ... # end # # def instance_method # # ... # end # # extend Gem::Deprecate # deprecate :instance_method, "X.z", 2011, 4 # # class << self # extend Gem::Deprecate # deprecate :klass_method, :none, 2011, 4 # end # end module Gem::Deprecate def self.skip # :nodoc: @skip ||= false end def self.skip= v # :nodoc: @skip = v end ## # Temporarily turn off warnings. Intended for tests only. def skip_during Gem::Deprecate.skip, original = true, Gem::Deprecate.skip yield ensure Gem::Deprecate.skip = original end ## # Simple deprecation method that deprecates +name+ by wrapping it up # in a dummy method. It warns on each call to the dummy method # telling the user of +repl+ (unless +repl+ is :none) and the # year/month that it is planned to go away. def deprecate name, repl, year, month class_eval { old = "_deprecated_#{name}" alias_method old, name define_method name do |*args, &block| klass = self.kind_of? Module target = klass ? "#{self}." : "#{self.class}#" msg = [ "NOTE: #{target}#{name} is deprecated", repl == :none ? " with no replacement" : "; use #{repl} instead", ". It will be removed on or after %4d-%02d-01." % [year, month], "\n#{target}#{name} called from #{Gem.location_of_caller.join(":")}", ] warn "#{msg.join}." unless Gem::Deprecate.skip send old, *args, &block end } end module_function :deprecate, :skip_during end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/ttk_wrapper.rb
#!/usr/bin/env ruby # # ttk_wrapper.rb -- use Ttk widgets as default on old Ruby/Tk scripts # # by <NAME> (<EMAIL>) # version = '0.1.3' # ########################################################################## # parse commandline arguments ########################################################################## require 'optparse' opt = OptionParser.new("Usage: #{$0} [options] rubytk_script" << "\n " << "Ruby/Tk script wrapper. Use Ttk widgets as default.") opt.version = version OPTS = {} OPTS[:themedir] = [] OPTS[:rb_theme] = [] OPTS[:theme] = 'default' opt.on('-l', '--list', 'list available theme names'){|v| OPTS[:list] = true} opt.on('-t', '--theme theme', 'theme name'){|v| OPTS[:theme] = v} opt.on('-d', '--themedir themes_dir', 'directory of theme definitions'){|v| OPTS[:themedir] << v } opt.on('-r', '--rubytheme rb_theme', 'theme definition file (ruby script)'){|v| OPTS[:rb_theme] << v } opt.on('-v', '--verbose', 'print verbose messages'){|v| OPTS[:verbose] = true} opt.parse!(ARGV) ########################################################################## # load Ttk (Tile) extension ########################################################################## require 'tk' begin require 'tkextlib/tile' Tk.default_widget_set = :Ttk rescue LoadError if OPTS[:verbose] print "warning: fail to load 'Ttk' extension. use standard widgets.\n" end end if OPTS[:verbose] print "current default widget set is '#{Tk.default_widget_set}'\n" end ########################################################################## # define Tcl/Tk procedures for compatibility. # those are required when want to use themes included # in "sample/tkextlib/tile/demo.rb". ########################################################################## Tk::Tile.__define_LoadImages_proc_for_compatibility__! Tk::Tile::Style.__define_wrapper_proc_for_compatibility__! ########################################################################## # use themes defined on the demo of Ttk (Tile) extension ########################################################################## demodir = File.dirname(__FILE__) demo_themesdir = File.expand_path(File.join(demodir, 'tkextlib', 'tile', 'themes')) Tk::AUTO_PATH.lappend(*OPTS[:themedir]) unless OPTS[:themedir].empty? Tk::AUTO_PATH.lappend('.', demodir, demo_themesdir) OPTS[:themedir] << demo_themesdir print "theme-dirs: #{OPTS[:themedir].inspect}\n" if OPTS[:verbose] OPTS[:themedir].each{|themesdir| if File.directory?(themesdir) Dir.foreach(themesdir){|name| next if name == '.' || name == '..' path = File.join(themesdir, name) Tk::AUTO_PATH.lappend(path) if File.directory?(path) } end } # This forces an update of the available packages list. It's required # for package names to find the themes in demos/themes/*.tcl Tk.ip_eval("#{TkPackage.unknown_proc} Tcl #{TkPackage.provide('Tcl')}") # load themes written in Ruby. themes_by_ruby = [File.join(demo_themesdir, 'kroc.rb')] themes_by_ruby.concat OPTS[:rb_theme] print "ruby-themes: #{themes_by_ruby.inspect}\n" if OPTS[:verbose] themes_by_ruby.each{|f| begin load(f, true) rescue LoadError print "fail to load \"#{f}\"\n" if OPTS[:verbose] end } ########################################################################## # ignore unsupported options of Ttk widgets ########################################################################## TkConfigMethod.__set_IGNORE_UNKNOWN_CONFIGURE_OPTION__! true TkItemConfigMethod.__set_IGNORE_UNKNOWN_CONFIGURE_OPTION__! true ########################################################################## # set theme of widget style ########################################################################## if OPTS[:list] || OPTS[:verbose] print "supported theme names: #{Tk::Tile.themes.inspect}\n" exit if OPTS[:list] && ARGV.empty? end print "use theme: \"#{OPTS[:theme]}\"\n" if OPTS[:theme] && OPTS[:verbose] #setTheme(OPTS[:theme]) if OPTS[:theme] Tk::Tile.set_theme(OPTS[:theme]) if OPTS[:theme] ########################################################################## # replace $0 and $RPAGRAM_NAME ########################################################################## # When the expand_path of the target script is long, ruby sometimes # fails to set the path to $0 (the path string is trimmed). # The following replaces $0 and $PROGNAME to avoid such trouble. progname_obj = $0.dup $program_name = progname_obj alias $REAL_PROGRAM_NAME $0 alias $PROGRAM_NAME $program_name alias $0 $program_name trace_var(:$program_name){|val| unless progname_obj.object_id == val.object_id progname_obj.replace(val.to_s) $program_name = progname_obj end } ########################################################################## # load script ########################################################################## if (path = ARGV.shift) && (script = File.expand_path(path)) print "load script \"#{script}\"\n" if OPTS[:verbose] $0 = script load(script) else print "Error: no script is given.\n" print opt.help exit(1) end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/ohai-6.18.0/spec/unit/plugins/gce_spec.rb
# # Author:: <NAME> (<EMAIL>) # 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 CONDIT"Net::HTTP Response"NS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper.rb') require 'ohai/mixin/gce_metadata' describe Ohai::System, "plugin gce" do before(:each) do @ohai = Ohai::System.new @ohai.stub!(:require_plugin).and_return(true) end shared_examples_for "!gce" do it "should NOT attempt to fetch the gce metadata" do Ohai::Mixin::GCEMetadata.should_not_receive(:http_client) @ohai._require_plugin("gce") end end shared_examples_for "gce" do before(:each) do @http_client = mock("Net::HTTP client") Ohai::Mixin::GCEMetadata.stub(:http_client).and_return(@http_client) IO.stub!(:select).and_return([[],[1],[]]) t = mock("connection") t.stub!(:connect_nonblock).and_raise(Errno::EINPROGRESS) Socket.stub!(:new).and_return(t) Socket.stub!(:pack_sockaddr_in).and_return(nil) end it "should recursively fetch metadata" do @http_client.should_receive(:get). with("/0.1/meta-data/"). and_return(mock("Net::HTTPOK", :body => "domain\nhostname\ndescription", :code=>"200")) @http_client.should_receive(:get). with("/0.1/meta-data/domain"). and_return(mock("Net::HTTPOK", :body => "test-domain", :code=>"200")) @http_client.should_receive(:get). with("/0.1/meta-data/hostname"). and_return(mock("Net::HTTPOK", :body => "test-host", :code=>"200")) @http_client.should_receive(:get). with("/0.1/meta-data/description"). and_return(mock("Net::HTTPOK", :body => "test-description", :code=>"200")) @ohai._require_plugin("gce") @ohai[:gce].should_not be_nil @ohai[:gce]['hostname'].should == "test-host" @ohai[:gce]['domain'].should == "test-domain" @ohai[:gce]['description'].should == "test-description" end it "should properly parse json metadata" do @http_client.should_receive(:get). with("/0.1/meta-data/"). and_return(mock("Net::HTTP Response", :body => "attached-disks\n", :code=>"200")) @http_client.should_receive(:get). with("/0.1/meta-data/attached-disks"). and_return(mock("Net::HTTP Response", :body => '{"disks":[{"deviceName":"boot", "index":0,"mode":"READ_WRITE","type":"EPHEMERAL"}]}', :code=>"200")) @ohai._require_plugin("gce") @ohai[:gce].should_not be_nil @ohai[:gce]['attached_disks'].should eq({"disks"=>[{"deviceName"=>"boot", "index"=>0,"mode"=>"READ_WRITE", "type"=>"EPHEMERAL"}]}) end end describe "with dmi and metadata address connected" do it_should_behave_like "gce" before(:each) do File.should_receive(:read).with('/sys/firmware/dmi/entries/1-0/raw').and_return('Google') end end describe "without dmi and metadata address connected" do it_should_behave_like "!gce" before(:each) do File.should_receive(:read).with('/sys/firmware/dmi/entries/1-0/raw').and_return('Test') end end describe "with hint file" do it_should_behave_like "gce" before(:each) do File.stub!(:exist?).with('/etc/chef/ohai/hints/gce.json').and_return(true) File.stub!(:read).with('/etc/chef/ohai/hints/gce.json').and_return('') File.stub!(:exist?).with('C:\chef\ohai\hints/gce.json').and_return(true) File.stub!(:read).with('C:\chef\ohai\hints/gce.json').and_return('') end end describe "without hint file" do it_should_behave_like "!gce" before(:each) do File.stub!(:exist?).with('/etc/chef/ohai/hints/gce.json').and_return(false) File.stub!(:exist?).with('C:\chef\ohai\hints/gce.json').and_return(false) end end describe "with ec2 cloud file" do it_should_behave_like "!gce" before(:each) do File.stub!(:exist?).with('/etc/chef/ohai/hints/ec2.json').and_return(true) File.stub!(:read).with('/etc/chef/ohai/hints/ec2.json').and_return('') File.stub!(:exist?).with('C:\chef\ohai\hints/ec2.json').and_return(true) File.stub!(:read).with('C:\chef\ohai\hints/ec2.json').and_return('') end end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/remote-ip_sample.rb
<gh_stars>1-10 #!/usr/bin/env ruby require 'remote-tk' puts <<EOM This sample controls the other Tk interpreter (Ruby/Tk, Tcl/Tk, and so on) which running on the other process. For this purpose, Ruby/Tk uses Tcl/Tk's 'send' command. Availability of the command depends on your GUI environment. If this script doesn't work, please check your environment (see Tcl/Tk FAQ). EOM #' unless (wish = TkWinfo.interps.find{|ip| ip =~ /^wish/}) puts '' puts 'Please start "wish" (Tcl/Tk shell) before running this sample script.' exit 1 end ip = RemoteTkIp.new(wish) ip.eval_proc{TkButton.new(:command=>proc{puts 'This procesure is on the controller-ip (Ruby/Tk)'}, :text=>'print on Ruby/Tk (controller-ip)').pack(:fill=>:x)} ip.eval_proc{TkButton.new(:command=>'puts {This procesure is on the remote-ip (wish)}', :text=>'print on wish (remote-ip)').pack(:fill=>:x)} # If your remote-ip is Ruby/Tk, you can control the remote Ruby by # 'ruby' or 'ruby_eval' or 'ruby_cmd' on the Tk interpreter. if ip.is_rubytk? ip.eval_proc{TkButton.new(:command=>'ruby {p 111; p Array.new(3,"ruby")}', :text=>'ruby cmd on the remote-ip').pack(:fill=>:x)} end ip.eval_proc{TkButton.new(:command=>'exit', :text=>'QUIT').pack(:fill=>:x)} TkButton.new(:command=>proc{exit}, :text=>'QUIT', :padx=>10, :pady=>7).pack(:padx=>10, :pady=>7) Tk.mainloop
arnab0073/idea
.rvm/src/ruby-2.3.0/test/openssl/test_ns_spki.rb
# frozen_string_literal: false require_relative 'utils' if defined?(OpenSSL::TestUtils) class OpenSSL::TestNSSPI < Test::Unit::TestCase def setup # This request data is adopt from the specification of # "Netscape Extensions for User Key Generation". # -- http://wp.netscape.com/eng/security/comm4-keygen.html @b64 = "MIHFMHEwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAnX0TILJrOMUue+PtwBRE6XfV" @b64 << "WtKQbsshxk5ZhcUwcwyvcnIq9b82QhJdoACdD34rqfCAIND46fXKQUnb0mvKzQID" @b64 << "AQABFhFNb3ppbGxhSXNNeUZyaWVuZDANBgkqhkiG9w0BAQQFAANBAAKv2Eex2n/S" @b64 << "r/7iJNroWlSzSMtTiQTEB+ADWHGj9u1xrUrOilq/o2cuQxIfZcNZkYAkWP4DubqW" @b64 << "i0//rgBvmco=" end def test_build_data key1 = OpenSSL::TestUtils::TEST_KEY_RSA1024 key2 = OpenSSL::TestUtils::TEST_KEY_RSA2048 spki = OpenSSL::Netscape::SPKI.new spki.challenge = "RandomString" spki.public_key = key1.public_key spki.sign(key1, OpenSSL::Digest::SHA1.new) assert(spki.verify(spki.public_key)) assert(spki.verify(key1.public_key)) assert(!spki.verify(key2.public_key)) der = spki.to_der spki = OpenSSL::Netscape::SPKI.new(der) assert_equal("RandomString", spki.challenge) assert_equal(key1.public_key.to_der, spki.public_key.to_der) assert(spki.verify(spki.public_key)) assert_not_nil(spki.to_text) end def test_decode_data spki = OpenSSL::Netscape::SPKI.new(@b64) assert_equal(@b64, spki.to_pem) assert_equal(@b64.unpack("m").first, spki.to_der) assert_equal("MozillaIsMyFriend", spki.challenge) assert_equal(OpenSSL::PKey::RSA, spki.public_key.class) spki = OpenSSL::Netscape::SPKI.new(@b64.unpack("m").first) assert_equal(@b64, spki.to_pem) assert_equal(@b64.unpack("m").first, spki.to_der) assert_equal("MozillaIsMyFriend", spki.challenge) assert_equal(OpenSSL::PKey::RSA, spki.public_key.class) end end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/nori-2.6.0/lib/nori/core_ext/hash.rb
require "uri" class Nori module CoreExt module Hash # @param key<Object> The key for the param. # @param value<Object> The value for the param. # # @return <String> This key value pair as a param # # @example normalize_param(:name, "<NAME>") #=> "name=Bob%20Jones" def normalize_param(key, value) if value.is_a?(Array) normalize_array_params(key, value) elsif value.is_a?(Hash) normalize_hash_params(key, value) else normalize_simple_type_params(key, value) end end # @return <String> The hash as attributes for an XML tag. # # @example # { :one => 1, "two"=>"TWO" }.to_xml_attributes # #=> 'one="1" two="TWO"' def to_xml_attributes map do |k, v| %{#{k.to_s.snakecase.sub(/^(.{1,1})/) { |m| m.downcase }}="#{v}"} end.join(' ') end private def normalize_simple_type_params(key, value) ["#{key}=#{encode_simple_value(value)}"] end def normalize_array_params(key, array) array.map do |element| normalize_param("#{key}[]", element) end end def normalize_hash_params(key, hash) hash.map do |nested_key, element| normalize_param("#{key}[#{nested_key}]", element) end end def encode_simple_value(value) URI.encode(value.to_s, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]")) end end end end Hash.send :include, Nori::CoreExt::Hash
arnab0073/idea
.rvm/src/ruby-2.3.0/lib/rdoc/meta_method.rb
# frozen_string_literal: false ## # MetaMethod represents a meta-programmed method class RDoc::MetaMethod < RDoc::AnyMethod end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/systemu-2.6.5/samples/f.rb
# # if a block is specified then it is passed the child pid and run in a # background thread. note that this thread will __not__ be blocked during the # execution of the command so it may do useful work such as killing the child # if execution time passes a certain threshold # require 'systemu' looper = %q( ruby -e" loop{ STDERR.puts Time.now.to_i; sleep 1 } " ) status, stdout, stderr = systemu looper do |cid| sleep 3 Process.kill 9, cid end p status p stderr
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkextlib/tcllib/tkpiechart.rb
<gh_stars>1-10 # # tkextlib/tcllib/tkpiechart.rb # by <NAME> (<EMAIL>) # # * Part of tcllib extension # * Create 2D or 3D pies with labels in Tcl canvases # require 'tk' require 'tk/canvas' require 'tkextlib/tcllib.rb' # TkPackage.require('tkpiechart', '6.6') TkPackage.require('tkpiechart') module Tk module Tcllib module Tkpiechart end end end module Tk::Tcllib::Tkpiechart PACKAGE_NAME = 'tkpiechart'.freeze def self.package_name PACKAGE_NAME end def self.package_version begin TkPackage.require('tkpiechart') rescue '' end end module ConfigMethod include TkConfigMethod def __pathname self.path + ';' + self.tag end private :__pathname def __cget_cmd ['::switched::cget', self.tag] end def __config_cmd ['::switched::configure', self.tag] end private :__config_cmd def __configinfo_struct {:key=>0, :alias=>nil, :db_name=>nil, :db_class=>nil, :default_value=>1, :current_value=>2} end private :__configinfo_struct def __boolval_optkeys super() << 'select' << 'autoupdate' << 'selectable' end private :__boolval_optkeys def __strval_optkeys super() << 'bordercolor' << 'textbackground' << 'widestvaluetext' << 'title' end private :__strval_optkeys def __listval_optkeys super() << 'colors' end private :__listval_optkeys end #################################### class PieChartObj < TkcItem include ConfigMethod def __font_optkeys ['titlefont'] end private :__font_optkeys end #################################### class Pie < TkcItem include ConfigMethod def create_self(x, y, width, height, keys=None) if keys and keys != None @tag_key = tk_call_without_enc('::stooop::new', 'pie', @c, x, y, *hash_kv(keys, true)) else @tag_key = tk_call_without_enc('::stooop::new', 'pie', @c, x, y) end @slice_tbl = {} id = "pie(#{@tag_key})" @tag = @tag_pie = TkcNamedTag(@c, id) @tag_slices = TkcNamedTag(@c, "pieSlices(#{@tag_key})") id end private :create_self def tag_key @tag_key end def tag @tag end def canvas @c end def _entry_slice(slice) @slice_tbl[slice.to_eval] = slice end def _delete_slice(slice) @slice_tbl.delete(slice.to_eval) end def delete tk_call_without_enc('::stooop::delete', @tag_key) CItemID_TBL.mutex.synchronize{ CItemID_TBL[@path].delete(@id) if CItemID_TBL[@path] } self end def new_slice(text=None) Slice.new(self, text) end def delete_slice(slice) unless slice.kind_of?(Slice) unless (slice = @slice_tbl[slice]) return tk_call_without_enc('pie::deleteSlice', @tag_key, slice) end end unless slice.kind_of?(Slice) && slice.pie == self fail ArgumentError, "argument is not a slice of self" end slice.delete end def selected_slices tk_split_simplelist(tk_call_without_enc('pie::selectedSlices', @tag_key)).collect{|slice| @slice_tbl[slice] || Slice.new(:no_create, self, slice) } end end #################################### class Slice < TkcItem include ConfigMethod def __config_cmd ['::switched::configure', self.tag] end private :__config_cmd #------------------------ def initialize(pie, *args) unless pie.kind_of?(Pie) && pie != :no_create fail ArgumentError, "expects TkPiechart::Pie for 1st argument" end if pie == :no_create @pie, @tag_key = args else text = args[0] || None @pie = pie @tag_key = tk_call_without_enc('pie::newSlice', @pie.tag_key, text) end @parent = @c = @pie.canvas @path = @parent.path @pie._entry_slice(self) @id = "slices(#{@tag_key})" @tag = TkcNamedTag.new(@pie.canvas, @id) CItemID_TBL.mutex.synchronize{ CItemID_TBL[@path] = {} unless CItemID_TBL[@path] CItemID_TBL[@path][@id] = self } end def tag_key @tag_key end def tag @tag end def pie @pie end def delete tk_call_without_enc('pie::deleteSlice', @pie.tag_key, @tag_key) CItemID_TBL.mutex.synchronize{ CItemID_TBL[@path].delete(@id) if CItemID_TBL[@path] } @pie._delete_slice(self) self end def size(share, disp=None) tk_call_without_enc('pie::sizeSlice', @pie.tag_key, @tag_key, share, disp) self end def label(text) tk_call_without_enc('pie::labelSlice', @pie.tag_key, @tag_key, text) self end end #################################### class BoxLabeler < TkcItem include ConfigMethod def __config_cmd ['::switched::configure', self.tag] end private :__config_cmd #------------------------ def create_self(keys=None) if keys and keys != None @tag_key = tk_call_without_enc('::stooop::new', 'pieBoxLabeler', *hash_kv(keys, true)) else @tag_key = tk_call_without_enc('::stooop::new', 'pieBoxLabeler') end id = "pieBoxLabeler(#{@tag_key})" @tag = TkcNamedTag(@c, id) id end private :create_self end #################################### class PeripheralLabeler < TkcItem include ConfigMethod def __font_optkeys ['font', 'smallfont'] end private :__font_optkeys def __config_cmd ['::switched::configure', self.tag] end private :__config_cmd #------------------------ def create_self(keys=None) if keys and keys != None @tag_key = tk_call_without_enc('::stooop::new', 'piePeripheralLabeler', *hash_kv(keys, true)) else @tag_key = tk_call_without_enc('::stooop::new', 'piePeripheralLabeler') end id = "piePeripheralLabeler(#{@tag_key})" @tag = TkcNamedTag(@c, id) id end private :create_self end #################################### class Label < TkcItem include ConfigMethod def __config_cmd ['::switched::configure', self.tag] end private :__config_cmd #------------------------ def create_self(x, y, keys=None) if keys and keys != None @tag_key = tk_call_without_enc('::stooop::new', 'canvasLabel', @c, x, y, width, height, *hash_kv(keys, true)) else @tag_key = tk_call_without_enc('::stooop::new', 'canvasLabel', @c, x, y, width, height) end id = "canvasLabel(#{@tag_key})" @tag = TkcNamedTag(@c, id) id end private :create_self end end
arnab0073/idea
.rvm/src/ruby-2.3.0/lib/rubygems/resolver/specification.rb
<reponame>arnab0073/idea<gh_stars>0 # frozen_string_literal: false ## # A Resolver::Specification contains a subset of the information # contained in a Gem::Specification. Only the information necessary for # dependency resolution in the resolver is included. class Gem::Resolver::Specification ## # The dependencies of the gem for this specification attr_reader :dependencies ## # The name of the gem for this specification attr_reader :name ## # The platform this gem works on. attr_reader :platform ## # The set this specification came from. attr_reader :set ## # The source for this specification attr_reader :source ## # The Gem::Specification for this Resolver::Specification. # # Implementers, note that #install updates @spec, so be sure to cache the # Gem::Specification in @spec when overriding. attr_reader :spec ## # The version of the gem for this specification. attr_reader :version ## # Sets default instance variables for the specification. def initialize @dependencies = nil @name = nil @platform = nil @set = nil @source = nil @version = nil end ## # Fetches development dependencies if the source does not provide them by # default (see APISpecification). def fetch_development_dependencies # :nodoc: end ## # The name and version of the specification. # # Unlike Gem::Specification#full_name, the platform is not included. def full_name "#{@name}-#{@version}" end ## # Installs this specification using the Gem::Installer +options+. The # install method yields a Gem::Installer instance, which indicates the # gem will be installed, or +nil+, which indicates the gem is already # installed. # # After installation #spec is updated to point to the just-installed # specification. def install options = {} require 'rubygems/installer' destination = options[:install_dir] || Gem.dir Gem.ensure_gem_subdirectories destination gem = source.download spec, destination installer = Gem::Installer.at gem, options yield installer if block_given? @spec = installer.install end ## # Returns true if this specification is installable on this platform. def installable_platform? Gem::Platform.match spec.platform end def local? # :nodoc: false end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8/ext/nokogiri/extconf.rb
<reponame>arnab0073/idea # :stopdoc: ENV['RC_ARCHS'] = '' if RUBY_PLATFORM =~ /darwin/ require 'mkmf' ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..', '..')) # # functions # def windows? RbConfig::CONFIG['target_os'] =~ /mingw32|mswin/ end def solaris? RbConfig::CONFIG['target_os'] =~ /solaris/ end def darwin? RbConfig::CONFIG['target_os'] =~ /darwin/ end def nix? ! (windows? || solaris? || darwin?) end def sh_export_path path # because libxslt 1.1.29 configure.in uses AC_PATH_TOOL which treats ":" # as a $PATH separator, we need to convert windows paths from # # C:/path/to/foo # # to # # /C/path/to/foo # # which is sh-compatible, in order to find things properly during # configuration if windows? match = Regexp.new("^([A-Z]):(/.*)").match(path) if match && match.length == 3 return File.join("/", match[1], match[2]) end end path end def do_help print <<HELP usage: ruby #{$0} [options] --disable-clean Do not clean out intermediate files after successful build. --disable-static Do not statically link bundled libraries. --with-iconv-dir=DIR Use the iconv library placed under DIR. --with-zlib-dir=DIR Use the zlib library placed under DIR. --use-system-libraries Use system libraries intead of building and using the bundled libraries. --with-xml2-dir=DIR / --with-xml2-config=CONFIG --with-xslt-dir=DIR / --with-xslt-config=CONFIG --with-exslt-dir=DIR / --with-exslt-config=CONFIG Use libxml2/libxslt/libexslt as specified. --enable-cross-build Do cross-build. HELP exit! 0 end def do_clean require 'pathname' require 'fileutils' root = Pathname(ROOT) pwd = Pathname(Dir.pwd) # Skip if this is a development work tree unless (root + '.git').exist? message "Cleaning files only used during build.\n" # (root + 'tmp') cannot be removed at this stage because # nokogiri.so is yet to be copied to lib. # clean the ports build directory Pathname.glob(pwd.join('tmp', '*', 'ports')) do |dir| FileUtils.rm_rf(dir, verbose: true) end if enable_config('static') # ports installation can be safely removed if statically linked. FileUtils.rm_rf(root + 'ports', verbose: true) else FileUtils.rm_rf(root + 'ports' + 'archives', verbose: true) end end exit! 0 end # The gem version constraint in the Rakefile is not respected at install time. # Keep this version in sync with the one in the Rakefile ! require 'rubygems' gem 'pkg-config', '~> 1.1.7' require 'pkg-config' message "Using pkg-config version #{PKGConfig::VERSION}\n" def package_config pkg, options={} package = pkg_config(pkg) return package if package return nil unless PKGConfig.have_package(pkg) cflags = PKGConfig.cflags(pkg) ldflags = PKGConfig.libs_only_L(pkg) libs = PKGConfig.libs_only_l(pkg) Logging::message "PKGConfig package configuration for %s\n", pkg Logging::message "cflags: %s\nldflags: %s\nlibs: %s\n\n", cflags, ldflags, libs [cflags, ldflags, libs] end def nokogiri_try_compile args = if defined?(RUBY_VERSION) && RUBY_VERSION <= "1.9.2" ["int main() {return 0;}"] else ["int main() {return 0;}", "", {werror: true}] end try_compile(*args) end def check_libxml_version version=nil source = if version.nil? <<-SRC #include <libxml/xmlversion.h> SRC else version_int = sprintf "%d%2.2d%2.2d", *(version.split(".")) <<-SRC #include <libxml/xmlversion.h> #if LIBXML_VERSION < #{version_int} #error libxml2 is older than #{version} #endif SRC end try_cpp source end def add_cflags(flags) print "checking if the C compiler accepts #{flags}... " with_cflags("#{$CFLAGS} #{flags}") do if nokogiri_try_compile puts 'yes' true else puts 'no' false end end end def preserving_globals values = [ $arg_config, $CFLAGS, $CPPFLAGS, $LDFLAGS, $LIBPATH, $libs ].map(&:dup) yield ensure $arg_config, $CFLAGS, $CPPFLAGS, $LDFLAGS, $LIBPATH, $libs = values end def asplode(lib) abort "-----\n#{lib} is missing. Please locate mkmf.log to investigate how it is failing.\n-----" end def have_iconv?(using = nil) checking_for(using ? "iconv using #{using}" : 'iconv') do ['', '-liconv'].any? do |opt| preserving_globals do yield if block_given? try_link(<<-'SRC', opt) #include <stdlib.h> #include <iconv.h> int main(void) { iconv_t cd = iconv_open("", ""); iconv(cd, NULL, NULL, NULL, NULL); return EXIT_SUCCESS; } SRC end end end end def iconv_configure_flags # If --with-iconv-dir or --with-opt-dir is given, it should be # the first priority %w[iconv opt].each do |name| if (config = preserving_globals { dir_config(name) }).any? && have_iconv?("--with-#{name}-* flags") { dir_config(name) } idirs, ldirs = config.map do |dirs| Array(dirs).flat_map do |dir| dir.split(File::PATH_SEPARATOR) end if dirs end return [ '--with-iconv=yes', *("CPPFLAGS=#{idirs.map { |dir| '-I' << dir }.join(' ')}" if idirs), *("LDFLAGS=#{ldirs.map { |dir| '-L' << dir }.join(' ')}" if ldirs), ] end end if have_iconv? return ['--with-iconv=yes'] end if (config = preserving_globals { package_config('libiconv') }) && have_iconv?('pkg-config libiconv') { package_config('libiconv') } cflags, ldflags, libs = config return [ '--with-iconv=yes', "CPPFLAGS=#{cflags}", "LDFLAGS=#{ldflags}", "LIBS=#{libs}", ] end asplode "libiconv" end # When using rake-compiler-dock on Windows, the underlying Virtualbox shared # folders don't support symlinks, but libiconv expects it for a build on # Linux. We work around this limitation by using the temp dir for cooking. def chdir_for_build build_dir = ENV['RCD_HOST_RUBY_PLATFORM'].to_s =~ /mingw|mswin|cygwin/ ? '/tmp' : '.' Dir.chdir(build_dir) do yield end end def process_recipe(name, version, static_p, cross_p) MiniPortile.new(name, version).tap do |recipe| recipe.target = portsdir = File.join(ROOT, "ports") # Prefer host_alias over host in order to use i586-mingw32msvc as # correct compiler prefix for cross build, but use host if not set. recipe.host = RbConfig::CONFIG["host_alias"].empty? ? RbConfig::CONFIG["host"] : RbConfig::CONFIG["host_alias"] recipe.patch_files = Dir[File.join(ROOT, "patches", name, "*.patch")].sort yield recipe env = Hash.new do |hash, key| hash[key] = "#{ENV[key]}" # (ENV[key].dup rescue '') end recipe.configure_options.flatten! recipe.configure_options.delete_if do |option| case option when /\A(\w+)=(.*)\z/ env[$1] = $2 true else false end end if static_p recipe.configure_options += [ "--disable-shared", "--enable-static", ] env['CFLAGS'] = "-fPIC #{env['CFLAGS']}" else recipe.configure_options += [ "--enable-shared", "--disable-static", ] end if cross_p recipe.configure_options += [ "--target=#{recipe.host}", "--host=#{recipe.host}", ] end if RbConfig::CONFIG['target_cpu'] == 'universal' %w[CFLAGS LDFLAGS].each do |key| unless env[key].include?('-arch') env[key] << ' ' << RbConfig::CONFIG['ARCH_FLAG'] end end end recipe.configure_options += env.map do |key, value| "#{key}=#{value}" end message <<-"EOS" ************************************************************************ IMPORTANT NOTICE: Building Nokogiri with a packaged version of #{name}-#{version}#{'.' if recipe.patch_files.empty?} EOS unless recipe.patch_files.empty? message "with the following patches applied:\n" recipe.patch_files.each do |patch| message "\t- %s\n" % File.basename(patch) end end message <<-"EOS" Team Nokogiri will keep on doing their best to provide security updates in a timely manner, but if this is a concern for you and want to use the system library instead; abort this installation process and reinstall nokogiri as follows: gem install nokogiri -- --use-system-libraries [--with-xml2-config=/path/to/xml2-config] [--with-xslt-config=/path/to/xslt-config] If you are using Bundler, tell it to use the option: bundle config build.nokogiri --use-system-libraries bundle install EOS message <<-"EOS" if name == 'libxml2' Note, however, that nokogiri is not fully compatible with arbitrary versions of libxml2 provided by OS/package vendors. EOS message <<-"EOS" ************************************************************************ EOS checkpoint = "#{recipe.target}/#{recipe.name}-#{recipe.version}-#{recipe.host}.installed" unless File.exist?(checkpoint) chdir_for_build do recipe.cook end FileUtils.touch checkpoint end recipe.activate end end def lib_a(ldflag) case ldflag when /\A-l(.+)/ "lib#{$1}.#{$LIBEXT}" end end def using_system_libraries? arg_config('--use-system-libraries', !!ENV['NOKOGIRI_USE_SYSTEM_LIBRARIES']) end # # monkey patches # # Workaround for Ruby bug #8074, introduced in Ruby 2.0.0, fixed in Ruby 2.1.0 # https://bugs.ruby-lang.org/issues/8074 @libdir_basename = "lib" if RUBY_VERSION < '2.1.0' # # main # case when arg_config('--help') do_help when arg_config('--clean') do_clean end RbConfig::MAKEFILE_CONFIG['CC'] = ENV['CC'] if ENV['CC'] # use same c compiler for libxml and libxslt ENV['CC'] = RbConfig::MAKEFILE_CONFIG['CC'] # TODO: deprecate MacRuby: https://github.com/sparklemotion/nokogiri/issues/1474 if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'macruby' $LIBRUBYARG_STATIC.gsub!(/-static/, '') end $LIBS << " #{ENV["LIBS"]}" # Read CFLAGS from ENV and make sure compiling works. add_cflags(ENV["CFLAGS"]) if windows? $CFLAGS << " -DXP_WIN -DXP_WIN32 -DUSE_INCLUDED_VASPRINTF" end if solaris? $CFLAGS << " -DUSE_INCLUDED_VASPRINTF" end if darwin? # Let Apple LLVM/clang 5.1 ignore unknown compiler flags add_cflags("-Wno-error=unused-command-line-argument-hard-error-in-future") end if nix? $CFLAGS << " -g -DXP_UNIX" end if RUBY_PLATFORM =~ /mingw/i # Work around a character escaping bug in MSYS by passing an arbitrary # double quoted parameter to gcc. See https://sourceforge.net/p/mingw/bugs/2142 $CPPFLAGS << ' "-Idummypath"' end if RbConfig::MAKEFILE_CONFIG['CC'] =~ /gcc/ $CFLAGS << " -O3" unless $CFLAGS[/-O\d/] $CFLAGS << " -Wall -Wcast-qual -Wwrite-strings -Wconversion -Wmissing-noreturn -Winline" end case when using_system_libraries? message "Building nokogiri using system libraries.\n" dir_config('zlib') # Using system libraries means we rely on the system libxml2 with # regard to the iconv support. dir_config('xml2').any? or package_config('libxml-2.0') dir_config('xslt').any? or package_config('libxslt') dir_config('exslt').any? or package_config('libexslt') check_libxml_version or abort "ERROR: cannot discover where libxml2 is located on your system. please make sure `pkg-config` is installed." check_libxml_version("2.6.21") or abort "ERROR: libxml2 version 2.6.21 or later is required!" check_libxml_version("2.9.3") or warn "WARNING: libxml2 version 2.9.3 or later is highly recommended, but proceeding anyway." else message "Building nokogiri using packaged libraries.\n" # The gem version constraint in the Rakefile is not respected at install time. # Keep this version in sync with the one in the Rakefile ! require 'rubygems' gem 'mini_portile2', '~> 2.1.0' require 'mini_portile2' message "Using mini_portile version #{MiniPortile::VERSION}\n" require 'yaml' static_p = enable_config('static', true) or message "Static linking is disabled.\n" dir_config('zlib') dependencies = YAML.load_file(File.join(ROOT, "dependencies.yml")) cross_build_p = enable_config("cross-build") if cross_build_p || windows? zlib_recipe = process_recipe("zlib", dependencies["zlib"]["version"], static_p, cross_build_p) do |recipe| recipe.files = [{ url: "http://zlib.net/#{recipe.name}-#{recipe.version}.tar.gz", md5: dependencies["zlib"]["md5"] }] class << recipe attr_accessor :cross_build_p def configure Dir.chdir work_path do mk = File.read 'win32/Makefile.gcc' File.open 'win32/Makefile.gcc', 'wb' do |f| f.puts "BINARY_PATH = #{path}/bin" f.puts "LIBRARY_PATH = #{path}/lib" f.puts "INCLUDE_PATH = #{path}/include" mk.sub!(/^PREFIX\s*=\s*$/, "PREFIX = #{host}-") if cross_build_p f.puts mk end end end def configured? Dir.chdir work_path do !! (File.read('win32/Makefile.gcc') =~ /^BINARY_PATH/) end end def compile execute "compile", "make -f win32/Makefile.gcc" end def install execute "install", "make -f win32/Makefile.gcc install" end end recipe.cross_build_p = cross_build_p end libiconv_recipe = process_recipe("libiconv", dependencies["libiconv"]["version"], static_p, cross_build_p) do |recipe| recipe.files = [{ url: "http://ftp.gnu.org/pub/gnu/libiconv/#{recipe.name}-#{recipe.version}.tar.gz", md5: dependencies["libiconv"]["md5"] }] recipe.configure_options += [ "CPPFLAGS=-Wall", "CFLAGS=-O2 -g", "CXXFLAGS=-O2 -g", "LDFLAGS=" ] end else if darwin? && !have_header('iconv.h') abort <<'EOM'.chomp ----- The file "iconv.h" is missing in your build environment, which means you haven't installed Xcode Command Line Tools properly. To install Command Line Tools, try running `xcode-select --install` on terminal and follow the instructions. If it fails, open Xcode.app, select from the menu "Xcode" - "Open Developer Tool" - "More Developer Tools" to open the developer site, download the installer for your OS version and run it. ----- EOM end end unless windows? preserving_globals { have_library('z', 'gzdopen', 'zlib.h') } or abort 'zlib is missing; necessary for building libxml2' end libxml2_recipe = process_recipe("libxml2", dependencies["libxml2"]["version"], static_p, cross_build_p) do |recipe| recipe.files = [{ url: "http://xmlsoft.org/sources/#{recipe.name}-#{recipe.version}.tar.gz", md5: dependencies["libxml2"]["md5"] }] recipe.configure_options += [ "--without-python", "--without-readline", *(zlib_recipe ? ["--with-zlib=#{zlib_recipe.path}", "CFLAGS=-I#{zlib_recipe.path}/include"] : []), *(libiconv_recipe ? "--with-iconv=#{libiconv_recipe.path}" : iconv_configure_flags), "--with-c14n", "--with-debug", "--with-threads" ] end libxslt_recipe = process_recipe("libxslt", dependencies["libxslt"]["version"], static_p, cross_build_p) do |recipe| recipe.files = [{ url: "http://xmlsoft.org/sources/#{recipe.name}-#{recipe.version}.tar.gz", md5: dependencies["libxslt"]["md5"] }] recipe.configure_options += [ "--without-python", "--without-crypto", "--with-debug", "--with-libxml-prefix=#{sh_export_path(libxml2_recipe.path)}" ] end $CFLAGS << ' ' << '-DNOKOGIRI_USE_PACKAGED_LIBRARIES' $LIBPATH = ["#{zlib_recipe.path}/lib"] | $LIBPATH if zlib_recipe $LIBPATH = ["#{libiconv_recipe.path}/lib"] | $LIBPATH if libiconv_recipe have_lzma = preserving_globals { have_library('lzma') } $libs = $libs.shellsplit.tap do |libs| [libxml2_recipe, libxslt_recipe].each do |recipe| libname = recipe.name[/\Alib(.+)\z/, 1] File.join(recipe.path, "bin", "#{libname}-config").tap do |config| # call config scripts explicit with 'sh' for compat with Windows $CPPFLAGS = `sh #{config} --cflags`.strip << ' ' << $CPPFLAGS `sh #{config} --libs`.strip.shellsplit.each do |arg| case arg when /\A-L(.+)\z/ # Prioritize ports' directories if $1.start_with?(ROOT + '/') $LIBPATH = [$1] | $LIBPATH else $LIBPATH = $LIBPATH | [$1] end when /\A-l./ libs.unshift(arg) else $LDFLAGS << ' ' << arg.shellescape end end end # Defining a macro that expands to a C string; double quotes are significant. $CPPFLAGS << ' ' << "-DNOKOGIRI_#{recipe.name.upcase}_PATH=\"#{recipe.path}\"".inspect $CPPFLAGS << ' ' << "-DNOKOGIRI_#{recipe.name.upcase}_PATCHES=\"#{recipe.patch_files.map { |path| File.basename(path) }.join(' ')}\"".inspect case libname when 'xml2' # xslt-config --libs or pkg-config libxslt --libs does not include # -llzma, so we need to add it manually when linking statically. if static_p && have_lzma # Add it at the end; GH #988 libs << '-llzma' end when 'xslt' # xslt-config does not have a flag to emit options including # -lexslt, so add it manually. libs.unshift('-lexslt') end end end.shelljoin if static_p $libs = $libs.shellsplit.map do |arg| case arg when '-lxml2' File.join(libxml2_recipe.path, 'lib', lib_a(arg)) when '-lxslt', '-lexslt' File.join(libxslt_recipe.path, 'lib', lib_a(arg)) else arg end end.shelljoin end end { "xml2" => ['xmlParseDoc', 'libxml/parser.h'], "xslt" => ['xsltParseStylesheetDoc', 'libxslt/xslt.h'], "exslt" => ['exsltFuncRegister', 'libexslt/exslt.h'], }.each do |lib, (func, header)| have_func(func, header) || have_library(lib, func, header) || have_library("lib#{lib}", func, header) or asplode("lib#{lib}") end have_func('xmlHasFeature') or abort "xmlHasFeature() is missing." have_func('xmlFirstElementChild') have_func('xmlRelaxNGSetParserStructuredErrors') have_func('xmlRelaxNGSetParserStructuredErrors') have_func('xmlRelaxNGSetValidStructuredErrors') have_func('xmlSchemaSetValidStructuredErrors') have_func('xmlSchemaSetParserStructuredErrors') if ENV['CPUPROFILE'] unless find_library('profiler', 'ProfilerEnable', *LIB_DIRS) abort "google performance tools are not installed" end end create_makefile('nokogiri/nokogiri') if enable_config('clean', true) # Do not clean if run in a development work tree. File.open('Makefile', 'at') do |mk| mk.print <<EOF all: clean-ports clean-ports: $(DLLIB) -$(Q)$(RUBY) $(srcdir)/extconf.rb --clean --#{static_p ? 'enable' : 'disable'}-static EOF end end # :startdoc:
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/tests/brightbox/models/compute/database_server_tests.rb
<reponame>arnab0073/idea Shindo.tests("Fog::Compute[:brightbox] | DatabaseServer model", ["brightbox"]) do pending if Fog.mocking? @service = Fog::Compute[:brightbox] tests("success") do tests("#create") do test("a new database server is returned") do @database_server = @service.database_servers.create !@database_server.nil? end test("state is not nil") do !@database_server.state.nil? end test("database_version is not nil") do !@database_server.database_version.nil? end test("admin_username is not nil") do !@database_server.admin_username.nil? end test("admin_password is not nil") do !@database_server.admin_password.nil? end end @sample_identifier = @database_server.id pending if @sample_identifier.nil? tests("#all") do test("returns results") do @database_servers = @service.database_servers.all @database_servers.any? do |dbs| dbs.identity == @database_server.identity end end end tests("#get('#{@sample_identifier}')") do @database_server = @service.database_servers.get(@sample_identifier) @database_server.wait_for { ready? } test("admin_username is not nil") do !@database_server.admin_username.nil? end test("admin_password is nil") do @database_server.admin_password.nil? end end @database_server.wait_for { ready? } tests("#snapshot") do # Very messy but there is no feedback about if snapshotting or what the ID will be existing_snapshots = @service.database_snapshots.all.map { |snapshot| snapshot.identity } test do @database_server.snapshot end current_snapshots = @service.database_snapshots.all.map { |snapshot| snapshot.identity } snapshot_id = (current_snapshots - existing_snapshots).last @snapshot = @service.database_snapshots.get(snapshot_id) @snapshot.wait_for { ready? } @snapshot.destroy end # Can no longer destroy when snapshotting tests("#destroy") do @database_server.destroy end end end
arnab0073/idea
.rvm/src/ruby-2.3.0/test/mkmf/test_find_executable.rb
# frozen_string_literal: false require_relative 'base' class TestMkmf class TestFindExecutable < TestMkmf def setup super @path, ENV["PATH"] = ENV["PATH"], @tmpdir end def teardown ENV["PATH"] = @path super end def test_find_executable bug2669 = '[ruby-core:27912]' name = "foobar#{$$}#{rand(1000)}" exts = mkmf {self.class::CONFIG['EXECUTABLE_EXTS']}.split stdout.filter {|s| s.sub(name, "<executable>")} exts[0] ||= "" exts.each do |ext| full = name+ext begin open(full, "w") {|ff| ff.chmod(0755)} result = mkmf {find_executable(name)} ensure File.unlink(full) end assert_equal("#{@tmpdir}/#{name}#{ext}", result, bug2669) end end def test_find_executable_dir name = "foobar#{$$}#{rand(1000)}" exts = mkmf {self.class::CONFIG['EXECUTABLE_EXTS']}.split stdout.filter {|s| s.sub(name, "<executable>")} exts[0] ||= "" exts.each do |ext| full = name+ext begin Dir.mkdir(full) result = mkmf {find_executable(name)} ensure Dir.rmdir(full) end assert_nil(result) end end end end
arnab0073/idea
.rvm/src/ruby-2.3.0/test/rubygems/test_config.rb
<reponame>arnab0073/idea<gh_stars>1-10 # frozen_string_literal: false require 'rubygems/test_case' require 'rubygems' class TestConfig < Gem::TestCase def test_datadir util_make_gems spec = Gem::Specification.find_by_name("a") spec.activate assert_equal "#{spec.full_gem_path}/data/a", Gem.datadir('a') end def test_good_rake_path_is_escaped path = Gem::TestCase.class_eval('@@good_rake') assert_match(/#{Gem.ruby} "[^"]*good_rake.rb"/, path) end def test_bad_rake_path_is_escaped path = Gem::TestCase.class_eval('@@bad_rake') assert_match(/#{Gem.ruby} "[^"]*bad_rake.rb"/, path) end end
arnab0073/idea
.rvm/src/ruby-2.3.0/ext/tk/sample/tkextlib/tkHTML/hv.rb
<gh_stars>0 #!/usr/bin/env ruby # frozen_string_literal: false # # This script implements the "hv" application. Type "hv FILE" to # view FILE as HTML. # # This application is used for testing the HTML widget. It can # also server as an example of how to use the HTML widget. # require 'tk' require 'tkextlib/tkHTML' root = TkRoot.new(:title=>'HTML File Viewer', :iconname=>'HV') file = ARGV[0] # # These images are used in place of GIFs or of form elements # biggray = TkPhotoImage.new(:data=><<'EOD') R0lGODdhPAA+APAAALi4uAAAACwAAAAAPAA+AAACQISPqcvtD6OctNqLs968+w+G4kiW5omm 6sq27gvH8kzX9o3n+s73/g8MCofEovGITCqXzKbzCY1Kp9Sq9YrNFgsAO/// EOD smgray = TkPhotoImage.new(:data=><<'EOD') R0lGODdhOAAYAPAAALi4uAAAACwAAAAAOAAYAAACI4SPqcvtD6OctNqLs968+w+G4kiW5omm 6sq27gvH8kzX9m0VADv/ EOD nogifbig = TkPhotoImage.new(:data=><<'EOD') R0lGODdhJAAkAPEAAACQkADQ0PgAAAAAACwAAAAAJAAkAAACmISPqcsQD6OcdJqKM71PeK15 AsSJH0iZY1CqqKSurfsGsex08XuTuU7L9HywHWZILAaVJssvgoREk5PolFo1XrHZ29IZ8oo0 HKEYVDYbyc/jFhz2otvdcyZdF68qeKh2DZd3AtS0QWcDSDgWKJXY+MXS9qY4+JA2+Vho+YPp FzSjiTIEWslDQ1rDhPOY2sXVOgeb2kBbu1AAADv/ EOD nogifsm = TkPhotoImage.new(:data=><<'EOD') R0lGODdhEAAQAPEAAACQkADQ0PgAAAAAACwAAAAAEAAQAAACNISPacHtD4IQz80QJ60as25d 3idKZdR0IIOm2ta0Lhw/Lz2S1JqvK8ozbTKlEIVYceWSjwIAO/// EOD # # define variables # ul_hyper = TkVariable.new(0) show_tbl = TkVariable.new(0) show_img = TkVariable.new(1) # # A font chooser routine. # # html[:fontcommand] = pick_font pick_font = proc{|size, attrs| puts "FontCmd: #{size} #{attrs}" [ ((attrs =~ /fixed/)? 'courier': 'charter'), (12 * (1.2**(size.to_f - 4.0))).to_i, ((attrs =~ /italic/)? 'italic': 'roman'), ((attrs =~ /bold/)? 'bold': 'normal') ].join(' ') } # # This routine is called for each form element # form_cmd = proc{|n, cmd, style, *args| # puts "FormCmd: $n $cmd $args" case cmd when 'select', 'textarea', 'input' TkLabel.new(:widgetname=>args[0], :image=>nogifsm) end } # # This routine is called for every <IMG> markup # images = {} old_imgs = {} big_imgs = {} hotkey = {} move_big_image = proc{|b| if big_imgs.key?(b) b.copy(big_imgs[b]) big_imgs[b].delete big_imgs.delete(b) Tk.update end } image_cmd = proc{|*args| if show_img.bool smgray else fn = args[0] if old_imgs.key?(fn) images[fn] = old_imgs[fn] old_imgs.delete(fn) images[fn] else begin img = TkPhotoImage.new(:file=>fn) rescue smgray else if img.width * img.height > 20000 b = TkPhotoImage.new(:width=>img.width, :height=>img.height) big_imgs[b] = img img = b Tk.after_idle(proc{ move_big_image.call(b) }) end images[fn] = img img end end end } # # This routine is called for every <SCRIPT> markup # script_cmd = proc{|*args| # puts "ScriptCmd: #{args.inspect}" } # This routine is called for every <APPLET> markup # applet_cmd = proc{|w, arglist| # puts "AppletCmd: w=#{w} arglist=#{arglist}" TkLabel.new(w, :text=>"The Applet #{w}", :bd=>2, :relief=>raised) } # # Construct the main HTML viewer # html = Tk::HTML_Widget.new(:padx=>5, :pady=>9, :formcommand=>form_cmd, :imagecommand=>image_cmd, :scriptcommand=>script_cmd, :appletcommand=>applet_cmd, :underlinehyperlinks=>0, :bg=>'white', :tablerelief=>:raised) vscr = html.yscrollbar(TkScrollbar.new) hscr = html.xscrollbar(TkScrollbar.new) Tk.grid(html, vscr, :sticky=>:news) Tk.grid(hscr, :sticky=>:ew) Tk.root.grid_columnconfigure(0, :weight=>1) Tk.root.grid_columnconfigure(1, :weight=>0) Tk.root.grid_rowconfigure(0, :weight=>1) Tk.root.grid_rowconfigure(1, :weight=>0) # # This procedure is called when the user clicks on a hyperlink. # priv = {} last_file = '' # Read a file # read_file = proc{|name| begin fp = open(name, 'r') ret = fp.read(File.size(name)) rescue ret = nil fp = nil Tk.messageBox(:icon=>'error', :message=>"fail to open '#{name}'", :type=>:ok) ensure fp.close if fp end ret } # Clear the screen. # clear_screen = proc{ html.clear old_imgs.clear big_imgs.clear hotkey.clear images.each{|k, v| old_imgs[k] = v } images.clear } # Load a file into the HTML widget # load_file = proc{|name| if (doc = read_file.call(name)) clear_screen.call last_file = name html.configure(:base=>name) html.parse(doc) old_imgs.clear end } href_binding = proc{|x, y| # koba & dg marking text html.selection_clear priv['mark'] = "@#{x},#{y}" lst = html.href(x, y) unless lst.size.zero? lnk, target = lst if lnk != "" if lnk =~ /^#{last_file}#(.*)$/ html.yview($1) else load_file.call(lnk) end end end } html.clipping_window.bind('1', href_binding, '%x %y') # marking text with the mouse and copying to the clipboard just with tkhtml2.0 working html.clipping_window.bind('B1-Motion', proc{|w, x, y| w.selection_set(priv['mark'], "@#{x},#{y}") TkClipboard.clear # avoid tkhtml0.0 errors # anyone can fix this for tkhtml0.0 begin TkClipboard.append(TkSelection.get) rescue end }, '%W %x %y') # This procedure is called when the user selects the File/Open # menu option. # last_dir = Dir.pwd sel_load = proc{ filetypes = [ ['Html Files', ['.html', '.htm']], ['All Files', '*'] ] f = Tk.getOpenFile(:initialdir=>last_dir, :filetypes=>filetypes) if f != '' load_file.call(f) last_dir = File.dirname(f) end } # Refresh the current file. # refresh = proc{|*args| load_file.call(last_file) } # This binding changes the cursor when the mouse move over # top of a hyperlink. # Tk::HTML_Widget::ClippingWindow.bind('Motion', proc{|w, x, y| parent = w.winfo_parent url = parent.href(x, y) unless url.empty? parent[:cursor] = 'hand2' else parent[:cursor] = '' end }, '%W %x %y') # # Setup menu # menu_spec = [ [['File', 0], ['Open', sel_load, 0], ['Refresh', refresh, 0], '---', ['Exit', proc{exit}, 1]], [['View', 0], ['Underline Hyperlinks', ul_hyper], ['Show Table Structure', show_tbl], ['Show Images', show_img]] ] mbar = Tk.root.add_menubar(menu_spec) # # Setup trace # ul_hyper.trace('w', proc{ html[:underlinehyperlinks] = ul_hyper.value refresh.call }) show_tbl.trace('w', proc{ if show_tbl.bool html[:tablerelief] = :flat else html[:tablerelief] = :raised end refresh.call }) show_img.trace('w', refresh) # If an arguent was specified, read it into the HTML widget. # Tk.update if file && file != "" load_file.call(file) end ##################################### Tk.mainloop
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/nori-2.6.0/spec/nori/core_ext/hash_spec.rb
require "spec_helper" describe Hash do describe "#normalize_param" do it "should have specs" end describe "#to_xml_attributes" do it "should turn the hash into xml attributes" do attrs = { :one => "ONE", "two" => "TWO" }.to_xml_attributes expect(attrs).to match(/one="ONE"/m) expect(attrs).to match(/two="TWO"/m) end it "should preserve _ in hash keys" do attrs = { :some_long_attribute => "with short value", :crash => :burn, :merb => "uses extlib" }.to_xml_attributes expect(attrs).to match(/some_long_attribute="with short value"/) expect(attrs).to match(/merb="uses extlib"/) expect(attrs).to match(/crash="burn"/) end end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/test/layouts/test_color_pattern.rb
<filename>.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/test/layouts/test_color_pattern.rb require File.expand_path('../../setup', __FILE__) module TestLogging module TestLayouts class TestColorPattern < Test::Unit::TestCase include LoggingTestCase CS = ::Logging::ColorScheme def setup super ::Logging.color_scheme :levels, :levels => { :debug => :blue, :info => :green, :warn => :yellow, :error => :red, :fatal => :cyan } ::Logging.color_scheme :lines, :lines => { :debug => :blue, :info => :green, :warn => :yellow, :error => :red, :fatal => :cyan }, :date => :blue, :logger => :cyan ::Logging.color_scheme :tokens, :date => :blue, :logger => :green, :message => :magenta @levels = Logging::LEVELS end def test_level_coloring layout = Logging.layouts.pattern(:color_scheme => :levels) event = Logging::LogEvent.new('ArrayLogger', @levels['info'], 'log message', false) rgxp = Regexp.new(Regexp.escape("#{CS::GREEN}INFO #{CS::RESET}")) assert_match rgxp, layout.format(event) event.level = @levels['debug'] rgxp = Regexp.new(Regexp.escape("#{CS::BLUE}DEBUG#{CS::RESET}")) assert_match rgxp, layout.format(event) event.level = @levels['error'] rgxp = Regexp.new(Regexp.escape("#{CS::RED}ERROR#{CS::RESET}")) assert_match rgxp, layout.format(event) end def test_multiple_level_coloring layout = Logging.layouts.pattern(:pattern => '%.1l, %5l -- %c: %m\n', :color_scheme => :levels) event = Logging::LogEvent.new('ArrayLogger', @levels['info'], 'log message', false) rgxp = Regexp.new(Regexp.escape("#{CS::GREEN}I#{CS::RESET}, #{CS::GREEN} INFO#{CS::RESET}")) assert_match rgxp, layout.format(event) event.level = @levels['debug'] rgxp = Regexp.new(Regexp.escape("#{CS::BLUE}D#{CS::RESET}, #{CS::BLUE}DEBUG#{CS::RESET}")) assert_match rgxp, layout.format(event) event.level = @levels['error'] rgxp = Regexp.new(Regexp.escape("#{CS::RED}E#{CS::RESET}, #{CS::RED}ERROR#{CS::RESET}")) assert_match rgxp, layout.format(event) end def test_line_coloring layout = Logging.layouts.pattern(:color_scheme => :lines) event = Logging::LogEvent.new('ArrayLogger', @levels['info'], 'log message', false) rgxp = Regexp.new('^'+Regexp.escape(CS::GREEN)+'.*?'+Regexp.escape(CS::RESET)+'$', Regexp::MULTILINE) assert_match rgxp, layout.format(event) event.level = @levels['error'] rgxp = Regexp.new('^'+Regexp.escape(CS::RED)+'.*?'+Regexp.escape(CS::RESET)+'$', Regexp::MULTILINE) assert_match rgxp, layout.format(event) event.level = @levels['warn'] rgxp = Regexp.new('^'+Regexp.escape(CS::YELLOW)+'.*?'+Regexp.escape(CS::RESET)+'$', Regexp::MULTILINE) assert_match rgxp, layout.format(event) end def test_token_coloring layout = Logging.layouts.pattern(:color_scheme => :tokens) event = Logging::LogEvent.new('ArrayLogger', @levels['info'], 'log message', false) rgxp = Regexp.new( '^\['+Regexp.escape(CS::BLUE)+'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}'+Regexp.escape(CS::RESET)+ '\] INFO -- '+Regexp.escape(CS::GREEN)+'ArrayLogger'+Regexp.escape(CS::RESET)+ ' : '+Regexp.escape(CS::MAGENTA)+'log message'+Regexp.escape(CS::RESET) ) assert_match rgxp, layout.format(event) end end # TestColorPattern end # TestLayouts end # TestLogging
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tkpalette.rb
<gh_stars>10-100 # # tkpalette.rb - load tk/palette.rb # require 'tk/palette'
arnab0073/idea
.rvm/src/ruby-2.3.0/ext/psych/lib/psych/visitors/visitor.rb
<reponame>arnab0073/idea # frozen_string_literal: false module Psych module Visitors class Visitor def accept target visit target end private DISPATCH = Hash.new do |hash, klass| hash[klass] = "visit_#{klass.name.gsub('::', '_')}" end def visit target send DISPATCH[target.class], target end end end end
arnab0073/idea
.rvm/src/ruby-2.3.0/test/open-uri/test_ssl.rb
<reponame>arnab0073/idea # frozen_string_literal: true require 'test/unit' require 'open-uri' require 'stringio' require 'webrick' begin require 'openssl' require 'webrick/https' require_relative '../openssl/utils' rescue LoadError end require 'webrick/httpproxy' class TestOpenURISSL < Test::Unit::TestCase end class TestOpenURISSL NullLog = Object.new def NullLog.<<(arg) end def with_https(log_tester=lambda {|log| assert_equal([], log) }) log = [] logger = WEBrick::Log.new(log, WEBrick::BasicLog::WARN) Dir.mktmpdir {|dr| srv = WEBrick::HTTPServer.new({ :DocumentRoot => dr, :ServerType => Thread, :Logger => logger, :AccessLog => [[NullLog, ""]], :SSLEnable => true, :SSLCertificate => OpenSSL::X509::Certificate.new(SERVER_CERT), :SSLPrivateKey => OpenSSL::PKey::RSA.new(SERVER_KEY), :SSLTmpDhCallback => proc { OpenSSL::TestUtils::TEST_KEY_DH1024 }, :BindAddress => '127.0.0.1', :Port => 0}) _, port, _, host = srv.listeners[0].addr threads = [] server_thread = srv.start threads << Thread.new { server_thread.join if log_tester log_tester.call(log) end } threads << Thread.new { begin yield srv, dr, "https://#{host}:#{port}", server_thread, log, threads ensure srv.shutdown end } assert_join_threads(threads) } end def setup @proxies = %w[http_proxy HTTP_PROXY https_proxy HTTPS_PROXY ftp_proxy FTP_PROXY no_proxy] @old_proxies = @proxies.map {|k| ENV[k] } @proxies.each {|k| ENV[k] = nil } end def teardown @proxies.each_with_index {|k, i| ENV[k] = @old_proxies[i] } end def setup_validation(srv, dr) cacert_filename = "#{dr}/cacert.pem" open(cacert_filename, "w") {|f| f << CA_CERT } srv.mount_proc("/data", lambda { |req, res| res.body = "ddd" } ) cacert_filename end def test_validation_success with_https {|srv, dr, url| cacert_filename = setup_validation(srv, dr) open("#{url}/data", :ssl_ca_cert => cacert_filename) {|f| assert_equal("200", f.status[0]) assert_equal("ddd", f.read) } } end def test_validation_noverify with_https {|srv, dr, url| setup_validation(srv, dr) open("#{url}/data", :ssl_verify_mode => OpenSSL::SSL::VERIFY_NONE) {|f| assert_equal("200", f.status[0]) assert_equal("ddd", f.read) } } end def test_validation_failure unless /mswin|mingw/ =~ RUBY_PLATFORM # on Windows, Errno::ECONNRESET will be raised, and it'll be eaten by # WEBrick log_tester = lambda {|server_log| assert_equal(1, server_log.length) assert_match(/ERROR OpenSSL::SSL::SSLError:/, server_log[0]) } end with_https(log_tester) {|srv, dr, url, server_thread, server_log| setup_validation(srv, dr) assert_raise(OpenSSL::SSL::SSLError) { open("#{url}/data") {} } } end def with_https_proxy(proxy_log_tester=lambda {|proxy_log, proxy_access_log| assert_equal([], proxy_log) }) proxy_log = [] proxy_logger = WEBrick::Log.new(proxy_log, WEBrick::BasicLog::WARN) with_https {|srv, dr, url, server_thread, server_log, threads| srv.mount_proc("/proxy", lambda { |req, res| res.body = "proxy" } ) cacert_filename = "#{dr}/cacert.pem" open(cacert_filename, "w") {|f| f << CA_CERT } cacert_directory = "#{dr}/certs" Dir.mkdir cacert_directory hashed_name = "%08x.0" % OpenSSL::X509::Certificate.new(CA_CERT).subject.hash open("#{cacert_directory}/#{hashed_name}", "w") {|f| f << CA_CERT } proxy = WEBrick::HTTPProxyServer.new({ :ServerType => Thread, :Logger => proxy_logger, :AccessLog => [[proxy_access_log=[], WEBrick::AccessLog::COMMON_LOG_FORMAT]], :BindAddress => '127.0.0.1', :Port => 0}) _, proxy_port, _, proxy_host = proxy.listeners[0].addr proxy_thread = proxy.start threads << Thread.new { proxy_thread.join if proxy_log_tester proxy_log_tester.call(proxy_log, proxy_access_log) end } begin yield srv, dr, url, cacert_filename, cacert_directory, proxy_host, proxy_port ensure proxy.shutdown end } end def test_proxy_cacert_file url = nil proxy_log_tester = lambda {|proxy_log, proxy_access_log| assert_equal(1, proxy_access_log.length) assert_match(%r[CONNECT #{url.sub(%r{\Ahttps://}, '')} ], proxy_access_log[0]) assert_equal([], proxy_log) } with_https_proxy(proxy_log_tester) {|srv, dr, url_, cacert_filename, cacert_directory, proxy_host, proxy_port| url = url_ open("#{url}/proxy", :proxy=>"http://#{proxy_host}:#{proxy_port}/", :ssl_ca_cert => cacert_filename) {|f| assert_equal("200", f.status[0]) assert_equal("proxy", f.read) } } end def test_proxy_cacert_dir url = nil proxy_log_tester = lambda {|proxy_log, proxy_access_log| assert_equal(1, proxy_access_log.length) assert_match(%r[CONNECT #{url.sub(%r{\Ahttps://}, '')} ], proxy_access_log[0]) assert_equal([], proxy_log) } with_https_proxy(proxy_log_tester) {|srv, dr, url_, cacert_filename, cacert_directory, proxy_host, proxy_port| url = url_ open("#{url}/proxy", :proxy=>"http://#{proxy_host}:#{proxy_port}/", :ssl_ca_cert => cacert_directory) {|f| assert_equal("200", f.status[0]) assert_equal("proxy", f.read) } } end end if defined?(OpenSSL::TestUtils) if defined?(OpenSSL::TestUtils) # mkdir demoCA demoCA/private demoCA/newcerts # touch demoCA/index.txt # echo 00 > demoCA/serial # openssl req -new -keyout demoCA/private/cakey.pem -out demoCA/careq.pem # openssl ca -out demoCA/cacert.pem -startdate 090101000000Z -enddate 491231235959Z -batch -keyfile demoCA/private/cakey.pem -selfsign -infiles demoCA/careq.pem # cp /etc/ssl/openssl.cnf openssl-server.cnf # Debian # vi openssl-server.cnf # enable "nsCertType = server" # mkdir server # openssl genrsa -des3 -out server/server.key 1024 # openssl rsa -in server/server.key -out server/servernopass.key # openssl req -new -days 365 -key server/servernopass.key -out server/csr.pem # openssl ca -config openssl-server.cnf -startdate 090101000000Z -enddate 491231235959Z -in server/csr.pem -keyfile demoCA/private/cakey.pem -cert demoCA/cacert.pem -out server/cert.pem # demoCA/cacert.pem => TestOpenURISSL::CA_CERT # server/cert.pem => TestOpenURISSL::SERVER_CERT # server/servernopass.key => TestOpenURISSL::SERVER_KEY TestOpenURISSL::CA_CERT = <<'End' Certificate: Data: Version: 3 (0x2) Serial Number: 0 (0x0) Signature Algorithm: sha1WithRSAEncryption Issuer: C=JP, ST=Tokyo, O=RubyTest, CN=Ruby Test CA Validity Not Before: Jan 1 00:00:00 2009 GMT Not After : Dec 31 23:59:59 2049 GMT Subject: C=JP, ST=Tokyo, O=RubyTest, CN=Ruby Test CA Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public Key: (1024 bit) Modulus (1024 bit): 00:9f:58:19:39:bc:ea:0c:b8:c3:5d:12:a7:d8:20: fc00:db20:35b:7399::5:3f:56:f6:75:b6:6c:23: fc00:e968:6179::de52:7100:00:b4:16:19:1c:9c:2c: fdf8:f53e:61e4::18:7b:60:93:86:ae:89:ab: 20:82:9a:b6:72:14:3c:4d:a9:0b:6c:34:79:9e:d3: 14:82:6d:c9:3b:90:d9:5e:68:6f:8c:b5:d8:09:f4: fc00:e968:6179::de52:7100:df:cf:90:36:65:57:dc: ad:fc00:db20:35b:7399::5:42:e9:1c:4e:1e:cb: 36:c1:44:4e:ab:9a:b2:73:6d Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:FALSE Netscape Comment: OpenSSL Generated Certificate X509v3 Subject Key Identifier: 24:6F:03:A3:EE:06:51:75:B2:BA:FC:3A:38:59:BF:ED:87:CD:E8:7F X509v3 Authority Key Identifier: keyid:24:6F:03:A3:EE:06:51:75:B2:BA:FC:3A:38:59:BF:ED:87:CD:E8:7F Signature Algorithm: sha1WithRSAEncryption 13:eb:db:ca:cd:90:f2:09:9e:d9:72:70:5e:42:5d:11:84:ce: 00:1d:c4:2f:41:d2:3e:16:e5:d4:97:1f:43:a9:a7:9c:fa:60: c4:35:96:f2:f6:0d:13:6d:0f:36:dd:59:03:08:ee:2e:a6:df: 9e:d8:6d:ca:72:8f:02:c2:2b:53:7b:12:7f:55:81:6c:9e:7d: e7:40:7e:f8:f5:75:0d:4b:a0:8d:ee:a4:d9:e8:5f:06:c9:86: 66:71:70:6c:41:81:6a:dd:a4:4f:a3:c1:ac:70:d4:78:1b:23: 30:2f:a5:ef:98:ee:d4:62:80:fd:bf:d4:7a:9b:8e:2d:18:e5: 00:46 -----BEGIN CERTIFICATE----- <KEY> -----END CERTIFICATE----- End TestOpenURISSL::SERVER_CERT = <<'End' Certificate: Data: Version: 3 (0x2) Serial Number: 1 (0x1) Signature Algorithm: sha1WithRSAEncryption Issuer: C=JP, ST=Tokyo, O=RubyTest, CN=Ruby Test CA Validity Not Before: Jan 1 00:00:00 2009 GMT Not After : Dec 31 23:59:59 2049 GMT Subject: C=JP, ST=Tokyo, O=RubyTest, CN=127.0.0.1 Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public Key: (1024 bit) Modulus (1024 bit): 00:bb:bd:74:69:53:58:50:24:79:f2:eb:db:8b:97: e4:69:a4:dd:48:0c:40:35:62:42:b3:35:8c:96:2a: 62:76:98:b5:2a:e0:f8:78:33:b6:ff:f8:55:bf:44: 69:21:d7:b5:0e:bd:8a:dd:31:1b:88:d5:b4:5e:7a: 82:e0:ba:99:6c:04:76:e9:ff:e6:f8:f5:06:8e:7e: a4:db:db:eb:43:44:12:a7:ca:ca:2b:aa:5f:83:10: e2:9e:35:55:e8:e8:af:be:c8:7d:bb:c2:d4:aa:c1: 1c:57:0b:c0:0c:3a:1d:6e:23:a9:03:26:7c:ea:8c: f0:86:61:ce:f1:ff:42:c7:23 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:FALSE Netscape Cert Type: SSL Server Netscape Comment: OpenSSL Generated Certificate X509v3 Subject Key Identifier: 7F:17:5A:58:88:96:E1:1F:44:EA:FF:AD:C6:2E:90:E2:95:32:DD:F0 X509v3 Authority Key Identifier: keyid:24:6F:03:A3:EE:06:51:75:B2:BA:FC:3A:38:59:BF:ED:87:CD:E8:7F Signature Algorithm: sha1WithRSAEncryption 9a:34:99:ea:76:a2:ed:f0:f7:a7:75:3b:81:fb:75:57:93:c1: 27:b6:1e:7a:38:67:95:be:58:42:9a:0a:dd:2b:23:fb:85:42: 80:34:bf:b9:0e:9c:5e:5a:dc:2d:25:8c:68:02:a2:c7:7f:c0: eb:f3:e0:61:e2:05:e5:7e:c1:e0:33:1c:76:65:23:2c:25:08: f6:5a:11:b9:d4:f7:e3:80:bb:b0:ce:76:1a:56:22:af:e2:4a: e1:7e:a4:60:f3:fd:9c:53:46:51:57:32:6b:05:53:80:5c:a5: 61:93:87:ae:06:a8:a2:ba:4d:a1:b7:1b:0f:8f:82:0a:e8:b3: ea:63 -----BEGIN CERTIFICATE----- MIICkTCCAfqgAwIBAgIBATANBgkqhkiG9w0BAQUFADBHMQswCQYDVQQGEwJKUDEO MAwGA1UECBMFVG9reW8xETAPBgNVBAoTCFJ1YnlUZXN0MRUwEwYDVQQDEwxSdWJ5 IFRlc3QgQ0EwHhcNMDkwMTAxMDAwMDAwWhcNNDkxMjMxMjM1OTU5WjBEMQswCQYD V<KEY> -----END CERTIFICATE----- End TestOpenURISSL::SERVER_KEY = <<'End' Private-Key: (1024 bit) modulus: 00:bb:bd:74:69:53:58:50:24:79:f2:eb:db:8b:97: e4:69:a4:dd:48:0c:40:35:62:42:b3:35:8c:96:2a: 62:76:98:b5:2a:e0:f8:78:33:b6:ff:f8:55:bf:44: 69:21:d7:b5:0e:bd:8a:dd:31:1b:88:d5:b4:5e:7a: 82:e0:ba:99:6c:04:76:e9:ff:e6:f8:f5:06:8e:7e: a4:db:db:eb:43:44:12:a7:ca:ca:2b:aa:5f:83:10: e2:9e:35:55:e8:e8:af:be:c8:7d:bb:c2:d4:aa:c1: 1c:57:0b:c0:0c:3a:1d:6e:23:a9:03:26:7c:ea:8c: fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:23 publicExponent: 65537 (0x10001) privateExponent: 00:af:3a:ec:17:0a:f5:d9:07:d2:d3:4c:15:c5:3b: 66:b4:bc:6e:d5:ba:a9:8b:aa:45:3b:63:f5:ee:8b: 6d:0f:e9:04:e0:1a:cf:8f:d2:25:32:d1:a5:a7:3a: c1:2e:17:5a:25:82:00:c4:e7:fb:1d:42:ea:71:6c: c4:0f:e1:db:23:ff:1e:d6:c8:d6:60:ca:2d:06:fc: 54:3c:03:d4:09:96:bb:38:7a:22:a1:61:2c:f7:d0: d0:90:6c:9f:61:ba:61:30:5a:aa:64:ad:43:3a:53: 38:e8:ba:cc:8c:51:3e:68:3e:3a:6a:0f:5d:5d:e0: d6:df:f2:54:93:d3:14:22:a1 prime1: fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b:21:29:d5:40:a6:11:ec: 4c:ae:4d:08:2a:71:18:ac:d1:3e:40:2f:12:41:59: 12:09:e2:f7:c2:d7:6b:0a:96:0a:06:e3:90:6a:4e: fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b:ab:d0:5a:29:7a:e4:72: 1a:ee:46:a0:8b prime2: 00:ce:57:5e:31:e9:c9:a8:5b:1f:55:af:67:e2:49: 2a:af:90:b6:02:c0:32:2f:ca:ae:1e:de:47:81:73: a8:f8:37:53:70:93:24:62:77:d4:b8:80:30:9f:65: 26:20:46:ae:5a:65:6e:6d:af:68:4c:8d:e8:3c:f3: d1:d1:d9:6e:c9 exponent1: 03:f1:02:b8:f2:82:26:5d:08:4d:30:83:de:e7:c5: c0:69:53:4b:0c:90:e3:53:c3:1e:e8:ed:01:28:15: fdf8:f53e:61e4::18:d7:27:98:b0:37:ec:4f: 00:c5:a9:9c:42:27:37:8a:ff:c2:96:d3:1a:8c:87: c2:22:75:d3 exponent2: fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:2d:e9:9f:ea:3a:36:52: fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:9c:c3:19:c1:3d:bc:db: 77:e7:b1:90:a6:67:ac:6b:ff:a6:e5:bd:47:d3:d9: 56:ff:36:d7:8c:4c:8b:d9:28:3a:2f:1c:9d:d4:57: 5e:b7:c5:a1 coefficient: 45:50:47:66:56:e9:21:d9:40:0e:af:3f:f2:05:77: ab:e7:08:40:97:88:2a:51:b3:7e:86:b0:b2:03:2e: 6d:36:3f:46:42:97:7d:5a:a2:93:6c:05:c2:8b:8b: 2d:af:d5:7d:75:e9:70:f0:2d:21:e3:b9:cf:4d:9a: c4:97:e2:79 -----BEGIN RSA PRIVATE KEY----- <KEY> -----END RSA PRIVATE KEY----- End end
arnab0073/idea
.rvm/src/ruby-2.3.0/ext/win32ole/sample/excel2.rb
<filename>.rvm/src/ruby-2.3.0/ext/win32ole/sample/excel2.rb # frozen_string_literal: false require 'win32ole' # -4100 is the value for the Excel constant xl3DColumn. ChartTypeVal = -4100; # Creates OLE object to Excel excel = WIN32OLE.new("excel.application") # Create and rotate the chart excel.visible = TRUE; excel.Workbooks.Add(); excel.Range("a1").value = 3; excel.Range("a2").value = 2; excel.Range("a3").value = 1; excel.Range("a1:a3").Select(); excelchart = excel.Charts.Add(); excelchart.type = ChartTypeVal; i = 0 i.step(180, 10) do |rot| excelchart.rotation=rot; sleep 0.1 end # Done, bye print "Now quit Excel... Please enter." gets excel.ActiveWorkbook.Close(0); excel.Quit();
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/benchmark/bm_vm2_unif1.rb
i = 0 def m a, b end while i<6_000_000 # benchmark loop 2 i+=1 m 100, 200 end
arnab0073/idea
.rvm/src/ruby-2.3.0/gems/did_you_mean-1.0.0/lib/did_you_mean/extra_features.rb
<filename>.rvm/src/ruby-2.3.0/gems/did_you_mean-1.0.0/lib/did_you_mean/extra_features.rb require 'did_you_mean' module DidYouMean TRACE = TracePoint.trace(:raise) do |tp| e = tp.raised_exception if SPELL_CHECKERS.include?(e.class.to_s) && !e.instance_variable_defined?(:@frame_binding) e.instance_variable_set(:@frame_binding, tp.binding) end end NameError.send(:attr, :frame_binding) end require 'did_you_mean/extra_features/initializer_name_correction' require 'did_you_mean/extra_features/ivar_name_correction'
arnab0073/idea
.rvm/src/ruby-2.3.0/gems/did_you_mean-1.0.0/test/correctable/method_name_test.rb
<reponame>arnab0073/idea require 'test_helper' class MethodNameTest < Minitest::Test class User def friends; end def first_name; end def descendants; end def call_incorrect_private_method raiae NoMethodError end protected def the_protected_method; end private def friend; end def the_private_method; end class << self def load; end end end module UserModule def from_module; end end def setup @user = User.new.extend(UserModule) end def test_corrections_include_instance_method error = assert_raises(NoMethodError){ @user.flrst_name } assert_correction :first_name, error.corrections assert_match "Did you mean? first_name", error.to_s end def test_corrections_include_private_method error = assert_raises(NoMethodError){ @user.friend } assert_correction :friends, error.corrections assert_match "Did you mean? friends", error.to_s end def test_corrections_include_method_from_module error = assert_raises(NoMethodError){ @user.fr0m_module } assert_correction :from_module, error.corrections assert_match "Did you mean? from_module", error.to_s end def test_corrections_include_class_method error = assert_raises(NoMethodError){ User.l0ad } assert_correction :load, error.corrections assert_match "Did you mean? load", error.to_s end def test_private_methods_should_not_be_suggested error = assert_raises(NoMethodError){ User.new.the_protected_method } refute_includes error.corrections, :the_protected_method error = assert_raises(NoMethodError){ User.new.the_private_method } refute_includes error.corrections, :the_private_method end def test_corrections_when_private_method_is_called_with_args error = assert_raises(NoMethodError){ @user.call_incorrect_private_method } assert_correction :raise, error.corrections assert_match "Did you mean? raise", error.to_s end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/fog-aws-0.9.2/lib/fog/aws.rb
<reponame>arnab0073/idea require 'fog/core' require 'fog/xml' require 'fog/json' require File.expand_path('../aws/version', __FILE__) module Fog module CDN autoload :AWS, File.expand_path('../aws/cdn', __FILE__) end module Compute autoload :AWS, File.expand_path('../aws/compute', __FILE__) end module DNS autoload :AWS, File.expand_path('../aws/dns', __FILE__) end module Storage autoload :AWS, File.expand_path('../aws/storage', __FILE__) end module AWS extend Fog::Provider autoload :CredentialFetcher, File.expand_path('../aws/credential_fetcher', __FILE__) autoload :Errors, File.expand_path('../aws/errors', __FILE__) autoload :Mock, File.expand_path('../aws/mock', __FILE__) autoload :SignatureV4, File.expand_path('../aws/signaturev4', __FILE__) # Services autoload :AutoScaling, File.expand_path('../aws/auto_scaling', __FILE__) autoload :CloudFormation, File.expand_path('../aws/cloud_formation', __FILE__) autoload :CloudWatch, File.expand_path('../aws/cloud_watch', __FILE__) autoload :DataPipeline, File.expand_path('../aws/data_pipeline', __FILE__) autoload :DynamoDB, File.expand_path('../aws/dynamodb', __FILE__) autoload :ECS, File.expand_path('../aws/ecs', __FILE__) autoload :ELB, File.expand_path('../aws/elb', __FILE__) autoload :EMR, File.expand_path('../aws/emr', __FILE__) autoload :ElasticBeanstalk, File.expand_path('../aws/beanstalk', __FILE__) autoload :Elasticache, File.expand_path('../aws/elasticache', __FILE__) autoload :Federation, File.expand_path('../aws/federation', __FILE__) autoload :Glacier, File.expand_path('../aws/glacier', __FILE__) autoload :IAM, File.expand_path('../aws/iam', __FILE__) autoload :Kinesis, File.expand_path('../aws/kinesis', __FILE__) autoload :KMS, File.expand_path('../aws/kms', __FILE__) autoload :Lambda, File.expand_path('../aws/lambda', __FILE__) autoload :RDS, File.expand_path('../aws/rds', __FILE__) autoload :Redshift, File.expand_path('../aws/redshift', __FILE__) autoload :SES, File.expand_path('../aws/ses', __FILE__) autoload :SNS, File.expand_path('../aws/sns', __FILE__) autoload :SQS, File.expand_path('../aws/sqs', __FILE__) autoload :STS, File.expand_path('../aws/sts', __FILE__) autoload :SimpleDB, File.expand_path('../aws/simpledb', __FILE__) service(:auto_scaling, 'AutoScaling') service(:beanstalk, 'ElasticBeanstalk') service(:cdn, 'CDN') service(:cloud_formation, 'CloudFormation') service(:cloud_watch, 'CloudWatch') service(:compute, 'Compute') service(:data_pipeline, 'DataPipeline') service(:dns, 'DNS') service(:dynamodb, 'DynamoDB') service(:elasticache, 'Elasticache') service(:ecs, 'ECS') service(:elb, 'ELB') service(:emr, 'EMR') service(:federation, 'Federation') service(:glacier, 'Glacier') service(:iam, 'IAM') service(:kinesis, 'Kinesis') service(:kms, 'KMS') service(:lambda, 'Lambda') service(:rds, 'RDS') service(:redshift, 'Redshift') service(:ses, 'SES') service(:simpledb, 'SimpleDB') service(:sns, 'SNS') service(:sqs, 'SQS') service(:storage, 'Storage') service(:sts, 'STS') def self.indexed_param(key, values) params = {} unless key.include?('%d') key << '.%d' end [*values].each_with_index do |value, index| if value.respond_to?('keys') k = format(key, index + 1) value.each do | vkey, vvalue | params["#{k}.#{vkey}"] = vvalue end else params[format(key, index + 1)] = value end end params end def self.serialize_keys(key, value, options = {}) case value when Hash value.each do | k, v | options.merge!(serialize_keys("#{key}.#{k}", v)) end return options when Array value.each_with_index do | it, idx | options.merge!(serialize_keys("#{key}.member.#{(idx + 1)}", it)) end return options else return {key => value} end end def self.indexed_request_param(name, values) idx = -1 Array(values).reduce({}) do |params, value| params["#{name}.#{idx += 1}"] = value params end end def self.indexed_filters(filters) params = {} filters.keys.each_with_index do |key, key_index| key_index += 1 params[format('Filter.%d.Name', key_index)] = key [*filters[key]].each_with_index do |value, value_index| value_index += 1 params[format('Filter.%d.Value.%d', key_index, value_index)] = value end end params end def self.escape(string) string.gsub(/([^a-zA-Z0-9_.\-~]+)/) { "%" + $1.unpack("H2" * $1.bytesize).join("%").upcase } end def self.signed_params_v4(params, headers, options={}) date = Fog::Time.now params = params.merge('Version' => options[:version]) headers = headers.merge('Host' => options[:host], 'x-amz-date' => date.to_iso8601_basic) headers['x-amz-security-token'] = options[:aws_session_token] if options[:aws_session_token] query = options[:query] || {} if !options[:body] body = '' for key in params.keys.sort unless (value = params[key]).nil? body << "#{key}=#{escape(value.to_s)}&" end end body.chop! else body = options[:body] end headers['Authorization'] = options[:signer].sign({:method => options[:method], :headers => headers, :body => body, :query => query, :path => options[:path]}, date) return body, headers end def self.signed_params(params, options = {}) params.merge!({ 'AWSAccessKeyId' => options[:aws_access_key_id], 'SignatureMethod' => 'HmacSHA256', 'SignatureVersion' => '2', 'Timestamp' => Time.now.utc.strftime("%Y-%m-%dT%H:%M:%SZ"), 'Version' => options[:version] }) params.merge!({ 'SecurityToken' => options[:aws_session_token] }) if options[:aws_session_token] body = '' for key in params.keys.sort unless (value = params[key]).nil? body << "#{key}=#{escape(value.to_s)}&" end end string_to_sign = "POST\n#{options[:host]}:#{options[:port]}\n#{options[:path]}\n" << body.chop signed_string = options[:hmac].sign(string_to_sign) body << "Signature=#{escape(Base64.encode64(signed_string).chomp!)}" body end def self.parse_security_group_options(group_name, options) options ||= Hash.new if group_name.is_a?(Hash) options = group_name elsif group_name if options.key?('GroupName') raise Fog::Compute::AWS::Error, 'Arguments specified both group_name and GroupName in options' end options = options.clone options['GroupName'] = group_name end name_specified = options.key?('GroupName') && !options['GroupName'].nil? group_id_specified = options.key?('GroupId') && !options['GroupId'].nil? unless name_specified || group_id_specified raise Fog::Compute::AWS::Error, 'Neither GroupName nor GroupId specified' end if name_specified && group_id_specified options.delete('GroupName') end options end def self.json_response?(response) return false unless response && response.headers response.get_header('Content-Type') =~ %r{application/.*json.*}i ? true : false end def self.regions @regions ||= ['ap-northeast-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'eu-central-1', 'eu-west-1', 'us-east-1', 'us-west-1', 'us-west-2', 'sa-east-1', 'cn-north-1', 'us-gov-west-1'] end def self.validate_region!(region, host=nil) if (!host || host.end_with?('.amazonaws.com')) && !regions.include?(region) raise ArgumentError, "Unknown region: #{region.inspect}" end end end end
arnab0073/idea
.rvm/src/ruby-2.3.0/test/-ext-/funcall/test_passing_block.rb
<filename>.rvm/src/ruby-2.3.0/test/-ext-/funcall/test_passing_block.rb # frozen_string_literal: false require 'test/unit' class TestFuncall < Test::Unit::TestCase module Relay def self.target(*args, &block) yield(*args) if block end end require '-test-/funcall/funcall' def test_with_funcall2 ok = nil Relay.with_funcall2("feature#4504") {|arg| ok = arg || true} assert_nil(ok) end def test_with_funcall_passing_block ok = nil Relay.with_funcall_passing_block("feature#4504") {|arg| ok = arg || true} assert_equal("feature#4504", ok) end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/demos-en/clrpick.rb
# clrpick.rb # # This demonstration script prompts the user to select a color. # # widget demo prompts the user to select a color (called by 'widget') # # Note: don't support ttk_wrapper. work with standard widgets only. # # toplevel widget if defined?($clrpick_demo) && $clrpick_demo $clrpick_demo.destroy $clrpick_demo = nil end # demo toplevel widget $clrpick_demo = TkToplevel.new {|w| title("Color Selection Dialogs") iconname("colors") positionWindow(w) } base_frame = TkFrame.new($clrpick_demo).pack(:fill=>:both, :expand=>true) # label #TkLabel.new($clrpick_demo,'font'=>$font,'wraplength'=>'4i','justify'=>'left', Tk::Label.new($clrpick_demo,'font'=>$font,'wraplength'=>'4i','justify'=>'left', 'text'=>"Press the buttons below to choose the foreground and background colors for the widgets in this window.").pack('side'=>'top') # frame #TkFrame.new($clrpick_demo) {|frame| Tk::Frame.new($clrpick_demo) {|frame| # TkButton.new(frame) { Tk::Button.new(frame) { text 'Dismiss' command proc{ tmppath = $clrpick_demo $clrpick_demo = nil tmppath.destroy } }.pack('side'=>'left', 'expand'=>'yes') # TkButton.new(frame) { Tk::Button.new(frame) { text 'Show Code' command proc{showCode 'clrpick'} }.pack('side'=>'left', 'expand'=>'yes') }.pack('side'=>'bottom', 'fill'=>'x', 'pady'=>'2m') # button # TkButton.new($clrpick_demo, 'text'=>'Set background color ...') {|b| Tk::Button.new($clrpick_demo, 'text'=>'Set background color ...') {|b| command(proc{setColor $clrpick_demo, b, 'background', ['background', 'highlightbackground']}) pack('side'=>'top', 'anchor'=>'c', 'pady'=>'2m') } # TkButton.new($clrpick_demo, 'text'=>'Set foreground color ...') {|b| Tk::Button.new($clrpick_demo, 'text'=>'Set foreground color ...') {|b| command(proc{setColor $clrpick_demo, b, 'foreground', ['foreground']}) pack('side'=>'top', 'anchor'=>'c', 'pady'=>'2m') } def setColor(w,button,name,options) w.grab initialColor = button[name] color = Tk.chooseColor('title'=>"Choose a #{name} color", 'parent'=>w, 'initialcolor'=>initialColor) if color != "" setColor_helper(w,options,color) end w.grab('release') end def setColor_helper(w, options, color) options.each{|opt| begin w[opt] = color rescue end } TkWinfo.children(w).each{|child| setColor_helper child, options, color } end
arnab0073/idea
.rvm/src/ruby-2.3.0/ext/psych/lib/psych/syntax_error.rb
<gh_stars>10-100 # frozen_string_literal: false require 'psych/exception' module Psych class SyntaxError < Psych::Exception attr_reader :file, :line, :column, :offset, :problem, :context def initialize file, line, col, offset, problem, context err = [problem, context].compact.join ' ' filename = file || '<unknown>' message = "(%s): %s at line %d column %d" % [filename, err, line, col] @file = file @line = line @column = col @offset = offset @problem = problem @context = context super(message) end end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/lib/logging/filter.rb
<gh_stars>100-1000 module Logging # The `Filter` class allows for filtering messages based on event # properties independently of the standard minimum-level restriction. # # All other Filters inherit from this class, and must override the # `allow` method to return the event if it should be allowed into the log. # Otherwise the `allow` method should return `nil`. class Filter # Returns the event if it should be allowed into the log. Returns `nil` if # the event should _not_ be allowed into the log. Subclasses should override # this method and provide their own filtering semantics. def allow( event ) event end end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/openstack/baremetal.rb
require 'fog/openstack/core' module Fog module Baremetal class OpenStack < Fog::Service SUPPORTED_VERSIONS = /(.)*/ requires :openstack_auth_url recognizes :openstack_auth_token, :openstack_management_url, :persistent, :openstack_service_type, :openstack_service_name, :openstack_tenant, :openstack_api_key, :openstack_username, :current_user, :current_tenant, :openstack_endpoint_type, :openstack_region ## MODELS # model_path 'fog/openstack/models/baremetal' model :chassis collection :chassis_collection model :driver collection :drivers model :node collection :nodes model :port collection :ports ## REQUESTS # request_path 'fog/openstack/requests/baremetal' # Node requests request :create_node request :delete_node request :get_node request :list_nodes request :list_nodes_detailed request :patch_node # Chassis requests request :create_chassis request :delete_chassis request :get_chassis request :list_chassis request :list_chassis_detailed request :patch_chassis # Driver requests request :get_driver request :get_driver_properties request :list_drivers # Port requests request :create_port request :delete_port request :get_port request :list_ports request :list_ports_detailed request :patch_port ## TODO not implemented API requests: ## Chassis # request :list_chassis_nodes # request :list_chassis_nodes_details ## Node requests # request :validate_node # request :set_maintenance # request :unset_maintenance # request :get_boot_device # request :set_boot_device # request :list_supported_boot_devices # request :list_node_states # request :set_power_state # request :provision_node # request :get_console_info # request :change_console_state # request :get_vendor_passthru_methods ## Driver requests # request :get_vendor_passthru_methods class Mock def self.data @data ||= Hash.new do |hash, key| chassis_uuid = Fog::UUID.uuid instance_uuid = Fog::UUID.uuid node_uuid = Fog::UUID.uuid hash[key] = { :chassis_collection => [ { "created_at" => "2000-01-01T12:00:00", "description" => "Sample chassis", "extra" => {}, "links" => [ { "href" => "http://localhost:6385/v1/chassis/eaaca217-e7d8-47b4-bb41-3f99f20eed89", "rel" => "self" }, { "href" => "http://localhost:6385/chassis/eaaca217-e7d8-47b4-bb41-3f99f20eed89", "rel" => "bookmark" } ], "nodes" => [ { "href" => "http://localhost:6385/v1/chassis/eaaca217-e7d8-47b4-bb41-3f99f20eed89/nodes", "rel" => "self" }, { "href" => "http://localhost:6385/chassis/eaaca217-e7d8-47b4-bb41-3f99f20eed89/nodes", "rel" => "bookmark" } ], "updated_at" => "2000-01-01T12:00:00", "uuid" => chassis_uuid } ], :drivers => [ { "hosts" => [ "fake-host" ], "name" => "sample-driver" } ], :nodes => [{ "chassis_uuid" => chassis_uuid, "console_enabled" => false, "created_at" => "2000-01-01T12:00:00", "driver" => "sample-driver", "driver_info" => {}, "extra" => {}, "instance_info" => {}, "instance_uuid" => instance_uuid, "last_error" => nil, "links" => [ { "href" => "http://localhost:6385/v1/nodes/1be26c0b-03f2-4d2e-ae87-c02d7f33c123", "rel" => "self" }, { "href" => "http://localhost:6385/nodes/1be26c0b-03f2-4d2e-ae87-c02d7f33c123", "rel" => "bookmark" } ], "maintenance" => false, "maintenance_reason" => nil, "ports" => [ { "href" => "http://localhost:6385/v1/nodes/1be26c0b-03f2-4d2e-ae87-c02d7f33c123/ports", "rel" => "self" }, { "href" => "http://localhost:6385/nodes/1be26c0b-03f2-4d2e-ae87-c02d7f33c123/ports", "rel" => "bookmark" } ], "power_state" => "power on", "properties" => { "cpus" => "1", "local_gb" => "10", "memory_mb" => "1024" }, "provision_state" => "active", "provision_updated_at" => "2000-01-01T12:00:00", "reservation" => nil, "target_power_state" => nil, "target_provision_state" => nil, "updated_at" => "2000-01-01T12:00:00", "uuid" => node_uuid }], :ports => [{ "address" => "fe:54:00:77:07:d9", "created_at" => "2014-12-23T19:35:30.734116", "extra" => { "foo" => "bar" }, "links" => [ { "href" => "http://localhost:6385/v1/ports/27e3153e-d5bf-4b7e-b517-fb518e17f34c", "rel" => "self" }, { "href" => "http://localhost:6385/ports/27e3153e-d5bf-4b7e-b517-fb518e17f34c", "rel" => "bookmark" } ], "node_uuid" => "7ae81bb3-dec3-4289-8d6c-da80bd8001ae", "updated_at" => "2014-12-23T19:35:30.734119", "uuid" => "27e3153e-d5bf-4b7e-b517-fb518e17f34c" }] } end end def self.reset @data = nil end def initialize(options={}) @openstack_username = options[:openstack_username] @openstack_tenant = options[:openstack_tenant] @openstack_auth_uri = URI.parse(options[:openstack_auth_url]) @auth_token = <PASSWORD>::Mock.random_base64(64) @auth_token_expiration = (Time.now.utc + 86400).iso8601 management_url = URI.parse(options[:openstack_auth_url]) management_url.port = 9292 management_url.path = '/v1' @openstack_management_url = management_url.to_s @data ||= { :users => {} } unless @data[:users].find {|u| u['name'] == options[:openstack_username]} id = Fog::Mock.random_numbers(6).to_s @data[:users][id] = { 'id' => id, 'name' => options[:openstack_username], 'email' => "#{options[:openstack_username]}<EMAIL>", 'tenantId' => Fog::Mock.random_numbers(6).to_s, 'enabled' => true } end end def data self.class.data[@openstack_username] end def reset_data self.class.data.delete(@openstack_username) end def credentials { :provider => 'openstack', :openstack_auth_url => @openstack_auth_uri.to_s, :openstack_auth_token => <PASSWORD>, :openstack_region => @openstack_region, :openstack_management_url => @openstack_management_url } end end class Real attr_reader :current_user attr_reader :current_tenant def initialize(options={}) @openstack_auth_token = options[:openstack_auth_token] unless @openstack_auth_token missing_credentials = Array.new @openstack_api_key = options[:openstack_api_key] @openstack_username = options[:openstack_username] missing_credentials << :openstack_api_key unless @openstack_api_key missing_credentials << :openstack_username unless @openstack_username raise ArgumentError, "Missing required arguments: #{missing_credentials.join(', ')}" unless missing_credentials.empty? end @openstack_tenant = options[:openstack_tenant] @openstack_auth_uri = URI.parse(options[:openstack_auth_url]) @openstack_management_url = options[:openstack_management_url] @openstack_must_reauthenticate = false @openstack_service_type = options[:openstack_service_type] || ['baremetal'] @openstack_service_name = options[:openstack_service_name] @openstack_endpoint_type = options[:openstack_endpoint_type] || 'adminURL' @openstack_region = options[:openstack_region] @connection_options = options[:connection_options] || {} @current_user = options[:current_user] @current_tenant = options[:current_tenant] authenticate @persistent = options[:persistent] || false @connection = Fog::Core::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options) end def credentials { :provider => 'openstack', :openstack_auth_url => @openstack_auth_uri.to_s, :openstack_auth_token => @auth_token, :openstack_management_url => @openstack_management_url, :current_user => @current_user, :current_tenant => @current_tenant } end def reload @connection.reset end def request(params) begin response = @connection.request(params.merge({ :headers => { 'Content-Type' => 'application/json', 'X-Auth-Token' => @auth_token }.merge!(params[:headers] || {}), :path => "#{@path}/#{params[:path]}"#, })) rescue Excon::Errors::Unauthorized => error if error.response.body != 'Bad username or password' # token expiration @openstack_must_reauthenticate = true authenticate retry else # bad credentials raise error end rescue Excon::Errors::HTTPStatusError => error raise case error when Excon::Errors::NotFound Fog::Compute::OpenStack::NotFound.slurp(error) else error end end unless response.body.empty? response.body = Fog::JSON.decode(response.body) end response end private def authenticate if !@openstack_management_url || @openstack_must_reauthenticate options = { :openstack_tenant => @openstack_tenant, :openstack_api_key => @openstack_api_key, :openstack_username => @openstack_username, :openstack_auth_uri => @openstack_auth_uri, :openstack_region => @openstack_region, :openstack_auth_token => @openstack_must_reauthenticate ? nil : @openstack_auth_token, :openstack_service_type => @openstack_service_type, :openstack_service_name => @openstack_service_name, :openstack_endpoint_type => @openstack_endpoint_type } credentials = Fog::OpenStack.authenticate_v2(options, @connection_options) @current_user = credentials[:user] @current_tenant = credentials[:tenant] @openstack_must_reauthenticate = false @auth_token = credentials[:token] @openstack_management_url = credentials[:server_management_url] uri = URI.parse(@openstack_management_url) else @auth_token = <PASSWORD>token uri = URI.parse(@openstack_management_url) end @host = uri.host @path = uri.path @path.sub!(/\/$/, '') unless @path.match(SUPPORTED_VERSIONS) @path = "/" + Fog::OpenStack.get_supported_version(SUPPORTED_VERSIONS, uri, @auth_token, @connection_options) end @port = uri.port @scheme = uri.scheme true end end end end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/gssapi-1.2.0/examples/gss_client.rb
<reponame>arnab0073/idea require 'gssapi' require 'base64' require 'socket' host = 'example.org' service = 'host' sock = TCPSocket.new(host, 8082) cli = GSSAPI::Simple.new(host, service) tok = cli.init_context stok = Base64.strict_encode64(tok) sock.write("#{stok}\n") # send initial token stok = sock.gets.chomp # get back continuation token ctx = cli.init_context(Base64.strict_decode64(stok.chomp)) # complete security context puts "Connection #{(ctx ? 'succeeded' : 'failed')}" begin print "> " msg = STDIN.gets.chomp emsg = cli.wrap_message(msg) sock.write("#{Base64.strict_encode64(emsg)}\n") end while msg != 'exit' sock.close
arnab0073/idea
.rvm/src/ruby-2.3.0/lib/rubygems/commands/cert_command.rb
# frozen_string_literal: false require 'rubygems/command' require 'rubygems/security' begin require 'openssl' rescue LoadError => e raise unless (e.respond_to?(:path) && e.path == 'openssl') || e.message =~ / -- openssl$/ end class Gem::Commands::CertCommand < Gem::Command def initialize super 'cert', 'Manage RubyGems certificates and signing settings', :add => [], :remove => [], :list => [], :build => [], :sign => [] OptionParser.accept OpenSSL::X509::Certificate do |certificate| begin OpenSSL::X509::Certificate.new File.read certificate rescue Errno::ENOENT raise OptionParser::InvalidArgument, "#{certificate}: does not exist" rescue OpenSSL::X509::CertificateError raise OptionParser::InvalidArgument, "#{certificate}: invalid X509 certificate" end end OptionParser.accept OpenSSL::PKey::RSA do |key_file| begin passphrase = ENV['GEM_PRIVATE_KEY_PASSPHRASE'] key = OpenSSL::PKey::RSA.new File.read(key_file), passphrase rescue Errno::ENOENT raise OptionParser::InvalidArgument, "#{key_file}: does not exist" rescue OpenSSL::PKey::RSAError raise OptionParser::InvalidArgument, "#{key_file}: invalid RSA key" end raise OptionParser::InvalidArgument, "#{key_file}: private key not found" unless key.private? key end add_option('-a', '--add CERT', OpenSSL::X509::Certificate, 'Add a trusted certificate.') do |cert, options| options[:add] << cert end add_option('-l', '--list [FILTER]', 'List trusted certificates where the', 'subject contains FILTER') do |filter, options| filter ||= '' options[:list] << filter end add_option('-r', '--remove FILTER', 'Remove trusted certificates where the', 'subject contains FILTER') do |filter, options| options[:remove] << filter end add_option('-b', '--build EMAIL_ADDR', 'Build private key and self-signed', 'certificate for EMAIL_ADDR') do |email_address, options| options[:build] << email_address end add_option('-C', '--certificate CERT', OpenSSL::X509::Certificate, 'Signing certificate for --sign') do |cert, options| options[:issuer_cert] = cert end add_option('-K', '--private-key KEY', OpenSSL::PKey::RSA, 'Key for --sign or --build') do |key, options| options[:key] = key end add_option('-s', '--sign CERT', 'Signs CERT with the key from -K', 'and the certificate from -C') do |cert_file, options| raise OptionParser::InvalidArgument, "#{cert_file}: does not exist" unless File.file? cert_file options[:sign] << cert_file end end def add_certificate certificate # :nodoc: Gem::Security.trust_dir.trust_cert certificate say "Added '#{certificate.subject}'" end def execute options[:add].each do |certificate| add_certificate certificate end options[:remove].each do |filter| remove_certificates_matching filter end options[:list].each do |filter| list_certificates_matching filter end options[:build].each do |name| build name end sign_certificates unless options[:sign].empty? end def build name key, key_path = build_key cert_path = build_cert name, key say "Certificate: #{cert_path}" if key_path say "Private Key: #{key_path}" say "Don't forget to move the key file to somewhere private!" end end def build_cert name, key # :nodoc: cert = Gem::Security.create_cert_email name, key Gem::Security.write cert, "gem-public_cert.pem" end def build_key # :nodoc: return options[:key] if options[:key] passphrase = ask_for_password 'Passphrase for your Private Key:' say "\n" passphrase_confirmation = ask_for_password 'Please repeat the passphrase for your Private Key:' say "\n" raise Gem::CommandLineError, "Passphrase and passphrase confirmation don't match" unless passphrase == passphrase_confirmation key = Gem::Security.create_key key_path = Gem::Security.write key, "gem-private_key.pem", 0600, passphrase return key, key_path end def certificates_matching filter return enum_for __method__, filter unless block_given? Gem::Security.trusted_certificates.select do |certificate, _| subject = certificate.subject.to_s subject.downcase.index filter end.sort_by do |certificate, _| certificate.subject.to_a.map { |name, data,| [name, data] } end.each do |certificate, path| yield certificate, path end end def description # :nodoc: <<-EOF The cert command manages signing keys and certificates for creating signed gems. Your signing certificate and private key are typically stored in ~/.gem/gem-public_cert.pem and ~/.gem/gem-private_key.pem respectively. To build a certificate for signing gems: gem cert --build you@example If you already have an RSA key, or are creating a new certificate for an existing key: gem cert --build you@example --private-key /path/to/key.pem If you wish to trust a certificate you can add it to the trust list with: gem cert --add /path/to/cert.pem You can list trusted certificates with: gem cert --list or: gem cert --list cert_subject_substring If you wish to remove a previously trusted certificate: gem cert --remove cert_subject_substring To sign another gem author's certificate: gem cert --sign /path/to/other_cert.pem For further reading on signing gems see `ri Gem::Security`. EOF end def list_certificates_matching filter # :nodoc: certificates_matching filter do |certificate, _| # this could probably be formatted more gracefully say certificate.subject.to_s end end def load_default_cert cert_file = File.join Gem.default_cert_path cert = File.read cert_file options[:issuer_cert] = OpenSSL::X509::Certificate.new cert rescue Errno::ENOENT alert_error \ "--certificate not specified and ~/.gem/gem-public_cert.pem does not exist" terminate_interaction 1 rescue OpenSSL::X509::CertificateError alert_error \ "--certificate not specified and ~/.gem/gem-public_cert.pem is not valid" terminate_interaction 1 end def load_default_key key_file = File.join Gem.default_key_path key = File.read key_file passphrase = ENV['<PASSWORD>KEY_<PASSWORD>'] options[:key] = OpenSSL::PKey::RSA.new key, passphrase rescue Errno::ENOENT alert_error \ "--private-key not specified and ~/.gem/gem-private_key.pem does not exist" terminate_interaction 1 rescue OpenSSL::PKey::RSAError alert_error \ "--private-key not specified and ~/.gem/gem-private_key.pem is not valid" terminate_interaction 1 end def load_defaults # :nodoc: load_default_cert unless options[:issuer_cert] load_default_key unless options[:key] end def remove_certificates_matching filter # :nodoc: certificates_matching filter do |certificate, path| FileUtils.rm path say "Removed '#{certificate.subject}'" end end def sign cert_file cert = File.read cert_file cert = OpenSSL::X509::Certificate.new cert permissions = File.stat(cert_file).mode & 0777 issuer_cert = options[:issuer_cert] issuer_key = options[:key] cert = Gem::Security.sign cert, issuer_key, issuer_cert Gem::Security.write cert, cert_file, permissions end def sign_certificates # :nodoc: load_defaults unless options[:sign].empty? options[:sign].each do |cert_file| sign cert_file end end end if defined?(OpenSSL::SSL)
arnab0073/idea
.rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems/rubygems-bundler-1.4.4/lib/rubygems_executable_plugin.rb
Gem.execute do |original_file| require 'rubygems' begin require 'rubygems-bundler/noexec' rescue LoadError warn "unable to load rubygems-bundler/noexec" if ENV.key?('NOEXEC_DEBUG') end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/io/wait/extconf.rb
<gh_stars>10-100 require 'mkmf' target = "io/wait" unless macro_defined?("DOSISH", "#include <ruby.h>") have_header(ioctl_h = "sys/ioctl.h") or ioctl_h = nil fionread = %w[sys/ioctl.h sys/filio.h sys/socket.h].find do |h| have_macro("FIONREAD", [h, ioctl_h].compact) end if fionread $defs << "-DFIONREAD_HEADER=\"<#{fionread}>\"" create_makefile(target) end else if have_func("rb_w32_ioctlsocket", "ruby.h") have_func("rb_w32_is_socket", "ruby.h") create_makefile(target) end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/demos-en/twind.rb
<reponame>arnab0073/idea # twind.rb # # This demonstration script creates a text widget with a bunch of # embedded windows. # # text (embedded windows) widget demo (called by 'widget') # # toplevel widget if defined?($twind_demo) && $twind_demo $twind_demo.destroy $twind_demo = nil end # demo toplevel widget $twind_demo = TkToplevel.new {|w| title("Text Demonstration - Embedded Windows") iconname("Embedded Windows") positionWindow(w) } base_frame = TkFrame.new($twind_demo).pack(:fill=>:both, :expand=>true) # frame $twind_buttons = TkFrame.new(base_frame) {|frame| TkButton.new(frame) { text 'Dismiss' command proc{ tmppath = $twind_demo $twind_demo = nil tmppath.destroy } }.pack('side'=>'left', 'expand'=>'yes') TkButton.new(frame) { text 'Show Code' command proc{showCode 'twind'} }.pack('side'=>'left', 'expand'=>'yes') } $twind_buttons.pack('side'=>'bottom', 'fill'=>'x', 'pady'=>'2m') # frame $twind_text = nil TkFrame.new(base_frame, 'highlightthickness'=>2, 'borderwidth'=>2, 'relief'=>'sunken') {|f| $twind_text = TkText.new(f, 'setgrid'=>'true', 'font'=>$font, 'width'=>'70', 'height'=>35, 'wrap'=>'word', 'highlightthickness'=>0, 'borderwidth'=>0 ){|t| TkScrollbar.new(f) {|s| command proc{|*args| t.yview(*args)} t.yscrollcommand proc{|first,last| s.set first,last} }.pack('side'=>'right', 'fill'=>'y') }.pack('expand'=>'yes', 'fill'=>'both') }.pack('expand'=>'yes', 'fill'=>'both') # $tag_center = TkTextTag.new($twind_text, 'justify' =>'center', 'spacing1'=>'5m', 'spacing3'=>'5m' ) $tag_buttons = TkTextTag.new($twind_text, 'lmargin1'=>'1c', 'lmargin2'=>'1c', 'rmargin' =>'1c', 'spacing1'=>'3m', 'spacing2'=>0, 'spacing3'=>0 ) $twind_text.insert('end', "A text widget can contain other widgets embedded ") $twind_text.insert('end', "it. These are called \"embedded windows\", ") $twind_text.insert('end', "and they can consist of arbitrary widgets. ") $twind_text.insert('end', "For example, here are two embedded button ") $twind_text.insert('end', "widgets. You can click on the first button to ") TkTextWindow.new($twind_text, 'end', 'window'=>TkButton.new($twind_text) { #text 'ON' text 'Turn On' command proc{textWindOn $twind_text,$twind_buttons} cursor 'top_left_arrow' }) $twind_text.insert('end', " horizontal scrolling, which also turns off ") $twind_text.insert('end', "word wrapping. Or, you can click on the second ") $twind_text.insert('end', "button to\n") TkTextWindow.new($twind_text, 'end', 'window'=>TkButton.new($twind_text) { #text 'OFF' text 'Turn Off' command proc{textWindOff $twind_text} cursor 'top_left_arrow' }) $twind_text.insert('end', " horizontal scrolling and turn back on word wrapping.\n\n") $twind_text.insert('end', "Or, here is another example. If you ") TkTextWindow.new($twind_text, 'end', 'window'=>TkButton.new($twind_text) { text 'Click Here' command proc{textWindPlot $twind_text} cursor 'top_left_arrow' }) $twind_text.insert('end', " a canvas displaying an x-y plot will appear right here.") $mark_plot = TkTextMark.new($twind_text, 'insert') $mark_plot.gravity='left' $twind_text.insert('end', " You can drag the data points around with the mouse, ") $twind_text.insert('end', "or you can click here to ") TkTextWindow.new($twind_text, 'end', 'window'=>TkButton.new($twind_text) { text 'Delete' command proc{textWindDel $twind_text} cursor 'top_left_arrow' }) $twind_text.insert('end', " the plot again.\n\n") $twind_text.insert('end', "You may also find it useful to put embedded windows in ") $twind_text.insert('end', "a text without any actual text. In this case the ") $twind_text.insert('end', "text widget acts like a geometry manager. For ") $twind_text.insert('end', "example, here is a collection of buttons laid out ") $twind_text.insert('end', "neatly into rows by the text widget. These buttons ") $twind_text.insert('end', "can be used to change the background color of the ") $twind_text.insert('end', "text widget (\"Default\" restores the color to ") $twind_text.insert('end', "its default). If you click on the button labeled ") $twind_text.insert('end', "\"Short\", it changes to a longer string so that ") $twind_text.insert('end', "you can see how the text widget automatically ") $twind_text.insert('end', "changes the layout. Click on the button again ") $twind_text.insert('end', "to restore the short string.\n") TkTextWindow.new($twind_text, 'end', 'window'=>TkButton.new($twind_text) {|b| text 'Default' command proc{embDefBg $twind_text} cursor 'top_left_arrow' $tag_buttons.add('end') }, 'padx'=>3 ) embToggle = TkVariable.new('Short') TkTextWindow.new($twind_text, 'end', 'window'=>TkCheckButton.new($twind_text) { textvariable embToggle indicatoron 0 variable embToggle onvalue 'A much longer string' offvalue 'Short' cursor 'top_left_arrow' pady 5 padx 2 }, 'padx'=>3, 'pady'=>2 ) [ 'AntiqueWhite3', 'Bisque1', 'Bisque2', 'Bisque3', 'Bisque4', 'SlateBlue3', 'RoyalBlue1', 'SteelBlue2', 'DeepSkyBlue3', 'LightBlue1', 'DarkSlateGray1', 'Aquamarine2', 'DarkSeaGreen2', 'SeaGreen1', 'Yellow1', 'IndianRed1', 'IndianRed2', 'Tan1', 'Tan4' ].each{|twind_color| TkTextWindow.new($twind_text, 'end', 'window'=>TkButton.new($twind_text) { text twind_color cursor 'top_left_arrow' command proc{$twind_text.bg twind_color} }, 'padx'=>3, 'pady'=>2 ) } # def textWindOn (w,f) if defined? $twind_scroll begin $twind_scroll.destroy rescue end $twind_scroll = nil end base = TkWinfo.parent( TkWinfo.parent(w) ) $twind_scroll = TkScrollbar.new(base) {|s| orient 'horizontal' command proc{|*args| w.xview(*args)} w.xscrollcommand proc{|first,last| s.set first,last} w.wrap 'none' pack('after'=>f, 'side'=>'bottom', 'fill'=>'x') } return nil end def textWindOff (w) if defined? $twind_scroll begin $twind_scroll.destroy rescue end $twind_scroll = nil end w.xscrollcommand '' w.wrap 'word' end def textWindPlot (t) if (defined? $twind_plot) && TkWinfo.exist?($twind_plot) return end $twind_plot = TkCanvas.new(t) { relief 'sunken' width 450 height 300 cursor 'top_left_arrow' } if $tk_version =~ /^4.*/ font = '-Adobe-Helvetica-Medium-R-Normal--*-180-*-*-*-*-*-*' else font = 'Helvetica 18' end TkcLine.new($twind_plot, 100, 250, 400, 250, 'width'=>2) TkcLine.new($twind_plot, 100, 250, 100, 50, 'width'=>2) TkcText.new($twind_plot, 225, 20, 'text'=>"A Simple Plot", 'font'=>font, 'fill'=>'brown') (0..10).each {|i| x = 100 + (i * 30) TkcLine.new($twind_plot, x, 250, x, 245, 'width'=>2) TkcText.new($twind_plot, x, 254, 'text'=>10*i, 'font'=>font, 'anchor'=>'n') } (0..5).each {|i| y = 250 - (i * 40) TkcLine.new($twind_plot, 100, y, 105, y, 'width'=>2) TkcText.new($twind_plot, 96, y, 'text'=>"#{i*50}.0", 'font'=>font, 'anchor'=>'e') } for xx, yy in [[12,56],[20,94],[33,98],[32,120],[61,180],[75,160],[98,223]] x = 100 + (3*xx) y = 250 - (4*yy)/5 item = TkcOval.new($twind_plot, x-6, y-6, x+6, y+6, 'width'=>1, 'outline'=>'black', 'fill'=>'SkyBlue2') item.addtag 'point' end $twind_plot.itembind('point', 'Any-Enter', proc{$twind_plot.itemconfigure 'current', 'fill', 'red'}) $twind_plot.itembind('point', 'Any-Leave', proc{$twind_plot.itemconfigure 'current', 'fill', 'SkyBlue2'}) $twind_plot.itembind('point', '1', proc{|x,y| embPlotDown $twind_plot,x,y}, "%x %y") $twind_plot.itembind('point', 'ButtonRelease-1', proc{$twind_plot.dtag 'selected'}) $twind_plot.bind('B1-Motion', proc{|x,y| embPlotMove $twind_plot,x,y}, "%x %y") while ($twind_text.get($mark_plot) =~ /[ \t\n]/) $twind_text.delete $mark_plot end $twind_text.insert $mark_plot,"\n" TkTextWindow.new($twind_text, $mark_plot, 'window'=>$twind_plot) $tag_center.add $mark_plot $twind_text.insert $mark_plot,"\n" end $embPlot = {'lastX'=>0, 'lastY'=>0} def embPlotDown (w, x, y) w.dtag 'selected' w.addtag_withtag 'selected', 'current' w.raise 'current' $embPlot['lastX'] = x $embPlot['lastY'] = y end def embPlotMove (w, x, y) w.move 'selected', x - $embPlot['lastX'], y - $embPlot['lastY'] $embPlot['lastX'] = x $embPlot['lastY'] = y end def textWindDel (w) if (defined? $twind_text) && TkWinfo.exist?($twind_plot) $twind_text.delete $twind_plot $twind_plot = nil while ($twind_text.get($mark_plot) =~ /[ \t\n]/) $twind_text.delete $mark_plot end $twind_text.insert $mark_plot," " end end def embDefBg (w) w['background'] = w.configinfo('background')[3] end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/win32ole/sample/ienavi2.rb
<filename>.rvm/src/ruby-1.9.3-p551/ext/win32ole/sample/ienavi2.rb require 'win32ole' class IEHandler attr_reader :loop def initialize @urls = [] @loop = true end def method_missing(event, *args) case event when "BeforeNavigate2" puts "Now Navigate #{args[1]}..." end end def onNavigateComplete2(pdisp, url) @urls << url end def onOnQuit puts "Now Stop IE..." @loop = false end def put_urls puts "You Navigated the URLs ..." @urls.each_with_index do |url, i| puts "(#{i+1}) #{url}" end end end ie = WIN32OLE.new('InternetExplorer.Application') ie.visible = true ie.gohome ev = WIN32OLE_EVENT.new(ie) ev.handler = IEHandler.new while (ev.handler.loop) WIN32OLE_EVENT.message_loop end ev.handler.put_urls
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/propagate.rb
#!/usr/bin/env ruby require 'tk' TkLabel.new(:text=>"Please click the bottom frame").pack f = TkFrame.new(:width=>400, :height=>100, :background=>'yellow', :relief=>'ridge', :borderwidth=>5).pack # TkPack.propagate(f, false) # <== important!! f.pack_propagate(false) # <== important!! list = (1..3).collect{|n| TkButton.new(f, :text=>"button#{'-X'*n}"){ command proc{ puts "button#{'-X'*n}" self.unpack } } } list.unshift(nil) f.bind('1', proc{ w = list.shift w.unpack if w list.push(w) list[0].pack(:expand=>true, :anchor=>:center) if list[0] }) Tk.mainloop
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/iwidgets/sample/hyperhelp.rb
<gh_stars>10-100 #!/usr/bin/env ruby require 'tk' require 'tkextlib/iwidgets' mainloop = Thread.new{Tk.mainloop} dir = '/usr/local/ActiveTcl/demos/IWidgets/html/' href = [ 'hyperhelp.n', 'buttonbox.n', 'calendar.n' ] hh = Tk::Iwidgets::Hyperhelp.new(:topics=>href, :helpdir=>dir) hh.show_topic('hyperhelp.n') hh.activate mainloop.join
arnab0073/idea
.rvm/gems/ruby-2.3.0/specifications/winrm-1.8.1.gemspec
<gh_stars>0 # -*- encoding: utf-8 -*- # stub: winrm 1.8.1 ruby lib Gem::Specification.new do |s| s.name = "winrm" s.version = "1.8.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.require_paths = ["lib"] s.authors = ["<NAME>", "<NAME>"] s.date = "2016-05-06" s.description = " Ruby library for Windows Remote Management\n" s.email = ["<EMAIL>", "<EMAIL>"] s.executables = ["rwinrm"] s.extra_rdoc_files = ["README.md", "LICENSE"] s.files = ["LICENSE", "README.md", "bin/rwinrm"] s.homepage = "https://github.com/WinRb/WinRM" s.licenses = ["Apache-2.0"] s.rdoc_options = ["-x", "test/", "-x", "examples/"] s.required_ruby_version = Gem::Requirement.new(">= 1.9.0") s.rubygems_version = "2.5.1" s.summary = "Ruby library for Windows Remote 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_runtime_dependency(%q<gssapi>, ["~> 1.2"]) s.add_runtime_dependency(%q<httpclient>, [">= 2.2.0.2", "~> 2.2"]) s.add_runtime_dependency(%q<rubyntlm>, ["~> 0.6.0"]) s.add_runtime_dependency(%q<logging>, ["< 3.0", ">= 1.6.1"]) s.add_runtime_dependency(%q<nori>, ["~> 2.0"]) s.add_runtime_dependency(%q<gyoku>, ["~> 1.0"]) s.add_runtime_dependency(%q<builder>, [">= 2.1.2"]) s.add_development_dependency(%q<rspec>, ["~> 3.2"]) s.add_development_dependency(%q<rake>, ["~> 10.3"]) s.add_development_dependency(%q<rubocop>, ["~> 0.28"]) s.add_development_dependency(%q<pry>, [">= 0"]) else s.add_dependency(%q<gssapi>, ["~> 1.2"]) s.add_dependency(%q<httpclient>, [">= 2.2.0.2", "~> 2.2"]) s.add_dependency(%q<rubyntlm>, ["~> 0.6.0"]) s.add_dependency(%q<logging>, ["< 3.0", ">= 1.6.1"]) s.add_dependency(%q<nori>, ["~> 2.0"]) s.add_dependency(%q<gyoku>, ["~> 1.0"]) s.add_dependency(%q<builder>, [">= 2.1.2"]) s.add_dependency(%q<rspec>, ["~> 3.2"]) s.add_dependency(%q<rake>, ["~> 10.3"]) s.add_dependency(%q<rubocop>, ["~> 0.28"]) s.add_dependency(%q<pry>, [">= 0"]) end else s.add_dependency(%q<gssapi>, ["~> 1.2"]) s.add_dependency(%q<httpclient>, [">= 2.2.0.2", "~> 2.2"]) s.add_dependency(%q<rubyntlm>, ["~> 0.6.0"]) s.add_dependency(%q<logging>, ["< 3.0", ">= 1.6.1"]) s.add_dependency(%q<nori>, ["~> 2.0"]) s.add_dependency(%q<gyoku>, ["~> 1.0"]) s.add_dependency(%q<builder>, [">= 2.1.2"]) s.add_dependency(%q<rspec>, ["~> 3.2"]) s.add_dependency(%q<rake>, ["~> 10.3"]) s.add_dependency(%q<rubocop>, ["~> 0.28"]) s.add_dependency(%q<pry>, [">= 0"]) end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/lib/logging/layouts/basic.rb
module Logging::Layouts # Accessor / Factory for the Basic layout. # def self.basic( *args ) return ::Logging::Layouts::Basic if args.empty? ::Logging::Layouts::Basic.new(*args) end # The +Basic+ layout class provides methods for simple formatting of log # events. The resulting string follows the format below. # # LEVEL LoggerName : log message # # _LEVEL_ is the log level of the event. _LoggerName_ is the name of the # logger that generated the event. <em>log message</em> is the message # or object that was passed to the logger. If multiple message or objects # were passed to the logger then each will be printed on its own line with # the format show above. # class Basic < ::Logging::Layout # call-seq: # format( event ) # # Returns a string representation of the given logging _event_. See the # class documentation for details about the formatting used. # def format( event ) obj = format_obj(event.data) sprintf("%*s %s : %s\n", ::Logging::MAX_LEVEL_LENGTH, ::Logging::LNAMES[event.level], event.logger, obj) end end # Basic end # Logging::Layouts
arnab0073/idea
.rvm/src/ruby-2.3.0/lib/rdoc/class_module.rb
# frozen_string_literal: false ## # ClassModule is the base class for objects representing either a class or a # module. class RDoc::ClassModule < RDoc::Context ## # 1:: # RDoc 3.7 # * Added visibility, singleton and file to attributes # * Added file to constants # * Added file to includes # * Added file to methods # 2:: # RDoc 3.13 # * Added extends # 3:: # RDoc 4.0 # * Added sections # * Added in_files # * Added parent name # * Complete Constant dump MARSHAL_VERSION = 3 # :nodoc: ## # Constants that are aliases for this class or module attr_accessor :constant_aliases ## # Comment and the location it came from. Use #add_comment to add comments attr_accessor :comment_location attr_accessor :diagram # :nodoc: ## # Class or module this constant is an alias for attr_accessor :is_alias_for ## # Return a RDoc::ClassModule of class +class_type+ that is a copy # of module +module+. Used to promote modules to classes. #-- # TODO move to RDoc::NormalClass (I think) def self.from_module class_type, mod klass = class_type.new mod.name mod.comment_location.each do |comment, location| klass.add_comment comment, location end klass.parent = mod.parent klass.section = mod.section klass.viewer = mod.viewer klass.attributes.concat mod.attributes klass.method_list.concat mod.method_list klass.aliases.concat mod.aliases klass.external_aliases.concat mod.external_aliases klass.constants.concat mod.constants klass.includes.concat mod.includes klass.extends.concat mod.extends klass.methods_hash.update mod.methods_hash klass.constants_hash.update mod.constants_hash klass.current_section = mod.current_section klass.in_files.concat mod.in_files klass.sections.concat mod.sections klass.unmatched_alias_lists = mod.unmatched_alias_lists klass.current_section = mod.current_section klass.visibility = mod.visibility klass.classes_hash.update mod.classes_hash klass.modules_hash.update mod.modules_hash klass.metadata.update mod.metadata klass.document_self = mod.received_nodoc ? nil : mod.document_self klass.document_children = mod.document_children klass.force_documentation = mod.force_documentation klass.done_documenting = mod.done_documenting # update the parent of all children (klass.attributes + klass.method_list + klass.aliases + klass.external_aliases + klass.constants + klass.includes + klass.extends + klass.classes + klass.modules).each do |obj| obj.parent = klass obj.full_name = nil end klass end ## # Creates a new ClassModule with +name+ with optional +superclass+ # # This is a constructor for subclasses, and must never be called directly. def initialize(name, superclass = nil) @constant_aliases = [] @diagram = nil @is_alias_for = nil @name = name @superclass = superclass @comment_location = [] # [[comment, location]] super() end ## # Adds +comment+ to this ClassModule's list of comments at +location+. This # method is preferred over #comment= since it allows ri data to be updated # across multiple runs. def add_comment comment, location return unless document_self original = comment comment = case comment when RDoc::Comment then comment.normalize else normalize_comment comment end @comment_location.delete_if { |(_, l)| l == location } @comment_location << [comment, location] self.comment = original end def add_things my_things, other_things # :nodoc: other_things.each do |group, things| my_things[group].each { |thing| yield false, thing } if my_things.include? group things.each do |thing| yield true, thing end end end ## # Ancestors list for this ClassModule: the list of included modules # (classes will add their superclass if any). # # Returns the included classes or modules, not the includes # themselves. The returned values are either String or # RDoc::NormalModule instances (see RDoc::Include#module). # # The values are returned in reverse order of their inclusion, # which is the order suitable for searching methods/attributes # in the ancestors. The superclass, if any, comes last. def ancestors includes.map { |i| i.module }.reverse end def aref_prefix # :nodoc: raise NotImplementedError, "missing aref_prefix for #{self.class}" end ## # HTML fragment reference for this module or class. See # RDoc::NormalClass#aref and RDoc::NormalModule#aref def aref "#{aref_prefix}-#{full_name}" end ## # Ancestors of this class or module only alias direct_ancestors ancestors ## # Clears the comment. Used by the Ruby parser. def clear_comment @comment = '' end ## # This method is deprecated, use #add_comment instead. # # Appends +comment+ to the current comment, but separated by a rule. Works # more like <tt>+=</tt>. def comment= comment # :nodoc: comment = case comment when RDoc::Comment then comment.normalize else normalize_comment comment end comment = "#{@comment}\n---\n#{comment}" unless @comment.empty? super comment end ## # Prepares this ClassModule for use by a generator. # # See RDoc::Store#complete def complete min_visibility update_aliases remove_nodoc_children update_includes remove_invisible min_visibility end ## # Does this ClassModule or any of its methods have document_self set? def document_self_or_methods document_self || method_list.any?{ |m| m.document_self } end ## # Does this class or module have a comment with content or is # #received_nodoc true? def documented? return true if @received_nodoc return false if @comment_location.empty? @comment_location.any? { |comment, _| not comment.empty? } end ## # Iterates the ancestors of this class or module for which an # RDoc::ClassModule exists. def each_ancestor # :yields: module return enum_for __method__ unless block_given? ancestors.each do |mod| next if String === mod next if self == mod yield mod end end ## # Looks for a symbol in the #ancestors. See Context#find_local_symbol. def find_ancestor_local_symbol symbol each_ancestor do |m| res = m.find_local_symbol(symbol) return res if res end nil end ## # Finds a class or module with +name+ in this namespace or its descendants def find_class_named name return self if full_name == name return self if @name == name @classes.values.find do |klass| next if klass == self klass.find_class_named name end end ## # Return the fully qualified name of this class or module def full_name @full_name ||= if RDoc::ClassModule === parent then "#{parent.full_name}::#{@name}" else @name end end ## # TODO: filter included items by #display? def marshal_dump # :nodoc: attrs = attributes.sort.map do |attr| next unless attr.display? [ attr.name, attr.rw, attr.visibility, attr.singleton, attr.file_name, ] end.compact method_types = methods_by_type.map do |type, visibilities| visibilities = visibilities.map do |visibility, methods| method_names = methods.map do |method| next unless method.display? [method.name, method.file_name] end.compact [visibility, method_names.uniq] end [type, visibilities] end [ MARSHAL_VERSION, @name, full_name, @superclass, parse(@comment_location), attrs, constants.select { |constant| constant.display? }, includes.map do |incl| next unless incl.display? [incl.name, parse(incl.comment), incl.file_name] end.compact, method_types, extends.map do |ext| next unless ext.display? [ext.name, parse(ext.comment), ext.file_name] end.compact, @sections.values, @in_files.map do |tl| tl.relative_name end, parent.full_name, parent.class, ] end def marshal_load array # :nodoc: initialize_visibility initialize_methods_etc @current_section = nil @document_self = true @done_documenting = false @parent = nil @temporary_section = nil @visibility = nil @classes = {} @modules = {} @name = array[1] @full_name = array[2] @superclass = array[3] @comment = array[4] @comment_location = if RDoc::Markup::Document === @comment.parts.first then @comment else RDoc::Markup::Document.new @comment end array[5].each do |name, rw, visibility, singleton, file| singleton ||= false visibility ||= :public attr = RDoc::Attr.new nil, name, rw, nil, singleton add_attribute attr attr.visibility = visibility attr.record_location RDoc::TopLevel.new file end array[6].each do |constant, comment, file| case constant when RDoc::Constant then add_constant constant else constant = add_constant RDoc::Constant.new(constant, nil, comment) constant.record_location RDoc::TopLevel.new file end end array[7].each do |name, comment, file| incl = add_include RDoc::Include.new(name, comment) incl.record_location RDoc::TopLevel.new file end array[8].each do |type, visibilities| visibilities.each do |visibility, methods| @visibility = visibility methods.each do |name, file| method = RDoc::AnyMethod.new nil, name method.singleton = true if type == 'class' method.record_location RDoc::TopLevel.new file add_method method end end end array[9].each do |name, comment, file| ext = add_extend RDoc::Extend.new(name, comment) ext.record_location RDoc::TopLevel.new file end if array[9] # Support Marshal version 1 sections = (array[10] || []).map do |section| [section.title, section] end @sections = Hash[*sections.flatten] @current_section = add_section nil @in_files = [] (array[11] || []).each do |filename| record_location RDoc::TopLevel.new filename end @parent_name = array[12] @parent_class = array[13] end ## # Merges +class_module+ into this ClassModule. # # The data in +class_module+ is preferred over the receiver. def merge class_module @parent = class_module.parent @parent_name = class_module.parent_name other_document = parse class_module.comment_location if other_document then document = parse @comment_location document = document.merge other_document @comment = @comment_location = document end cm = class_module other_files = cm.in_files merge_collections attributes, cm.attributes, other_files do |add, attr| if add then add_attribute attr else @attributes.delete attr @methods_hash.delete attr.pretty_name end end merge_collections constants, cm.constants, other_files do |add, const| if add then add_constant const else @constants.delete const @constants_hash.delete const.name end end merge_collections includes, cm.includes, other_files do |add, incl| if add then add_include incl else @includes.delete incl end end @includes.uniq! # clean up merge_collections extends, cm.extends, other_files do |add, ext| if add then add_extend ext else @extends.delete ext end end @extends.uniq! # clean up merge_collections method_list, cm.method_list, other_files do |add, meth| if add then add_method meth else @method_list.delete meth @methods_hash.delete meth.pretty_name end end merge_sections cm self end ## # Merges collection +mine+ with +other+ preferring other. +other_files+ is # used to help determine which items should be deleted. # # Yields whether the item should be added or removed (true or false) and the # item to be added or removed. # # merge_collections things, other.things, other.in_files do |add, thing| # if add then # # add the thing # else # # remove the thing # end # end def merge_collections mine, other, other_files, &block # :nodoc: my_things = mine. group_by { |thing| thing.file } other_things = other.group_by { |thing| thing.file } remove_things my_things, other_files, &block add_things my_things, other_things, &block end ## # Merges the comments in this ClassModule with the comments in the other # ClassModule +cm+. def merge_sections cm # :nodoc: my_sections = sections.group_by { |section| section.title } other_sections = cm.sections.group_by { |section| section.title } other_files = cm.in_files remove_things my_sections, other_files do |_, section| @sections.delete section.title end other_sections.each do |group, sections| if my_sections.include? group my_sections[group].each do |my_section| other_section = cm.sections_hash[group] my_comments = my_section.comments other_comments = other_section.comments other_files = other_section.in_files merge_collections my_comments, other_comments, other_files do |add, comment| if add then my_section.add_comment comment else my_section.remove_comment comment end end end else sections.each do |section| add_section group, section.comments end end end end ## # Does this object represent a module? def module? false end ## # Allows overriding the initial name. # # Used for modules and classes that are constant aliases. def name= new_name @name = new_name end ## # Parses +comment_location+ into an RDoc::Markup::Document composed of # multiple RDoc::Markup::Documents with their file set. def parse comment_location case comment_location when String then super when Array then docs = comment_location.map do |comment, location| doc = super comment doc.file = location doc end RDoc::Markup::Document.new(*docs) when RDoc::Comment then doc = super comment_location.text, comment_location.format doc.file = comment_location.location doc when RDoc::Markup::Document then return comment_location else raise ArgumentError, "unknown comment class #{comment_location.class}" end end ## # Path to this class or module for use with HTML generator output. def path http_url @store.rdoc.generator.class_dir end ## # Name to use to generate the url: # modules and classes that are aliases for another # module or class return the name of the latter. def name_for_path is_alias_for ? is_alias_for.full_name : full_name end ## # Returns the classes and modules that are not constants # aliasing another class or module. For use by formatters # only (caches its result). def non_aliases @non_aliases ||= classes_and_modules.reject { |cm| cm.is_alias_for } end ## # Updates the child modules or classes of class/module +parent+ by # deleting the ones that have been removed from the documentation. # # +parent_hash+ is either <tt>parent.modules_hash</tt> or # <tt>parent.classes_hash</tt> and +all_hash+ is ::all_modules_hash or # ::all_classes_hash. def remove_nodoc_children prefix = self.full_name + '::' modules_hash.each_key do |name| full_name = prefix + name modules_hash.delete name unless @store.modules_hash[full_name] end classes_hash.each_key do |name| full_name = prefix + name classes_hash.delete name unless @store.classes_hash[full_name] end end def remove_things my_things, other_files # :nodoc: my_things.delete_if do |file, things| next false unless other_files.include? file things.each do |thing| yield false, thing end true end end ## # Search record used by RDoc::Generator::JsonIndex def search_record [ name, full_name, full_name, '', path, '', snippet(@comment_location), ] end ## # Sets the store for this class or module and its contained code objects. def store= store super @attributes .each do |attr| attr.store = store end @constants .each do |const| const.store = store end @includes .each do |incl| incl.store = store end @extends .each do |ext| ext.store = store end @method_list.each do |meth| meth.store = store end end ## # Get the superclass of this class. Attempts to retrieve the superclass # object, returns the name if it is not known. def superclass @store.find_class_named(@superclass) || @superclass end ## # Set the superclass of this class to +superclass+ def superclass=(superclass) raise NoMethodError, "#{full_name} is a module" if module? @superclass = superclass end def to_s # :nodoc: if is_alias_for then "#{self.class.name} #{self.full_name} -> #{is_alias_for}" else super end end ## # 'module' or 'class' def type module? ? 'module' : 'class' end ## # Updates the child modules & classes by replacing the ones that are # aliases through a constant. # # The aliased module/class is replaced in the children and in # RDoc::Store#modules_hash or RDoc::Store#classes_hash # by a copy that has <tt>RDoc::ClassModule#is_alias_for</tt> set to # the aliased module/class, and this copy is added to <tt>#aliases</tt> # of the aliased module/class. # # Formatters can use the #non_aliases method to retrieve children that # are not aliases, for instance to list the namespace content, since # the aliased modules are included in the constants of the class/module, # that are listed separately. def update_aliases constants.each do |const| next unless cm = const.is_alias_for cm_alias = cm.dup cm_alias.name = const.name # Don't move top-level aliases under Object, they look ugly there unless RDoc::TopLevel === cm_alias.parent then cm_alias.parent = self cm_alias.full_name = nil # force update for new parent end cm_alias.aliases.clear cm_alias.is_alias_for = cm if cm.module? then @store.modules_hash[cm_alias.full_name] = cm_alias modules_hash[const.name] = cm_alias else @store.classes_hash[cm_alias.full_name] = cm_alias classes_hash[const.name] = cm_alias end cm.aliases << cm_alias end end ## # Deletes from #includes those whose module has been removed from the # documentation. #-- # FIXME: includes are not reliably removed, see _possible_bug test case def update_includes includes.reject! do |include| mod = include.module !(String === mod) && @store.modules_hash[mod.full_name].nil? end includes.uniq! end ## # Deletes from #extends those whose module has been removed from the # documentation. #-- # FIXME: like update_includes, extends are not reliably removed def update_extends extends.reject! do |ext| mod = ext.module !(String === mod) && @store.modules_hash[mod.full_name].nil? end extends.uniq! end end
arnab0073/idea
.rvm/src/ruby-2.3.0/test/rubygems/plugin/exception/rubygems_plugin.rb
# frozen_string_literal: false TestGem::TEST_PLUGIN_EXCEPTION = :loaded raise Exception.new('boom')
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/net-ssh-multi-1.2.0/lib/net/ssh/multi/server.rb
require 'net/ssh' module Net; module SSH; module Multi # Encapsulates the connection information for a single remote server, as well # as the Net::SSH session corresponding to that information. You'll rarely # need to instantiate one of these directly: instead, you should use # Net::SSH::Multi::Session#use. class Server include Comparable # The Net::SSH::Multi::Session instance that manages this server instance. attr_reader :master # The host name (or IP address) of the server to connect to. attr_reader :host # The user name to use when logging into the server. attr_reader :user # The Hash of additional options to pass to Net::SSH when connecting # (including things like :password, and so forth). attr_reader :options # The Net::SSH::Gateway instance to use to establish the connection. Will # be +nil+ if the connection should be established without a gateway. attr_reader :gateway # Creates a new Server instance with the given connection information. The # +master+ argument must be a reference to the Net::SSH::Multi::Session # instance that will manage this server reference. The +options+ hash must # conform to the options described for Net::SSH::start, with two additions: # # * :via => a Net::SSH::Gateway instance to use when establishing a # connection to this server. # * :user => the name of the user to use when logging into this server. # # The +host+ argument may include the username and port number, in which # case those values take precedence over similar values given in the +options+: # # server = Net::SSH::Multi::Server.new(session, 'user@host:1234') # puts server.user #-> user # puts server.port #-> 1234 def initialize(master, host, options={}) @master = master @options = options.dup @user, @host, port = host.match(/^(?:([^;,:=]+)@|)(.*?)(?::(\d+)|)$/)[1,3] user_opt, port_opt = @options.delete(:user), @options.delete(:port) @user = @user || user_opt || master.default_user port ||= port_opt @options[:port] = port.to_i if port @gateway = @options.delete(:via) @failed = false end # Returns the value of the server property with the given +key+. Server # properties are described via the +:properties+ key in the options hash # when defining the Server. def [](key) (options[:properties] || {})[key] end # Sets the given key/value pair in the +:properties+ key in the options # hash. If the options hash has no :properties key, it will be created. def []=(key, value) (options[:properties] ||= {})[key] = value end # Returns the port number to use for this connection. def port options[:port] || 22 end # Gives server definitions a sort order, and allows comparison. def <=>(server) [host, port, user] <=> [server.host, server.port, server.user] end alias :eql? :== # Generates a +Fixnum+ hash value for this object. This function has the # property that +a.eql?(b)+ implies +a.hash == b.hash+. The # hash value is used by class +Hash+. Any hash value that exceeds the # capacity of a +Fixnum+ will be truncated before being used. def hash @hash ||= [host, user, port].hash end # Returns a human-readable representation of this server instance. def to_s @to_s ||= begin s = "#{user}@#{host}" s << ":#{options[:port]}" if options[:port] s end end # Returns a human-readable representation of this server instance. def inspect @inspect ||= "#<%s:0x%x %s>" % [self.class.name, object_id, to_s] end # Returns +true+ if this server has ever failed a connection attempt. def failed? @failed end # Indicates (by default) that this server has just failed a connection # attempt. If +flag+ is false, this can be used to reset the failed flag # so that a retry may be attempted. def fail!(flag=true) @failed = flag end # Returns the Net::SSH session object for this server. If +require_session+ # is false and the session has not previously been created, this will # return +nil+. If +require_session+ is true, the session will be instantiated # if it has not already been instantiated, via the +gateway+ if one is # given, or directly (via Net::SSH::start) otherwise. # # if server.session.nil? # puts "connecting..." # server.session(true) # end # # Note that the sessions returned by this are "enhanced" slightly, to make # them easier to deal with in a multi-session environment: they have a # :server property automatically set on them, that refers to this object # (the Server instance that spawned them). # # assert_equal server, server.session[:server] def session(require_session=false) return @session if @session || !require_session @session ||= master.next_session(self) end # Returns +true+ if the session has been opened, and the session is currently # busy (as defined by Net::SSH::Connection::Session#busy?). def busy?(include_invisible=false) session && session.busy?(include_invisible) end # Closes this server's session. If the session has not yet been opened, # this does nothing. def close session.close if session ensure master.server_closed(self) if session @session = nil end public # but not published, e.g., these are used internally only... # Indicate that the session currently in use by this server instance # should be replaced by the given +session+ argument. This is used when # a pending session has been "realized". Note that this does not # actually replace the session--see #update_session! for that. def replace_session(session) #:nodoc: @ready_session = session end # If a new session has been made ready (see #replace_session), this # will replace the current session with the "ready" session. This # method is called from the event loop to ensure that sessions are # swapped in at the appropriate point (instead of in the middle of an # event poll). def update_session! #:nodoc: if @ready_session @session, @ready_session = @ready_session, nil end end # Returns a new session object based on this server's connection # criteria. Note that this will not associate the session with the # server, and should not be called directly; it is called internally # from Net::SSH::Multi::Session when a new session is required. def new_session #:nodoc: session = if gateway gateway.ssh(host, user, options) else Net::SSH.start(host, user, options) end session[:server] = self session rescue ::Timeout::Error => error raise Net::SSH::ConnectionTimeout.new("#{error.message} for #{host}") rescue Net::SSH::AuthenticationFailed => error raise Net::SSH::AuthenticationFailed.new("#{error.message}@#{host}") end # Closes all open channels on this server's session. If the session has # not yet been opened, this does nothing. def close_channels #:nodoc: session.channels.each { |id, channel| channel.close } if session end # Runs the session's preprocess action, if the session has been opened. def preprocess #:nodoc: session.preprocess if session end # Returns all registered readers on the session, or an empty array if the # session is not open. def readers #:nodoc: return [] unless session session.listeners.keys.reject { |io| io.closed? } end # Returns all registered and pending writers on the session, or an empty # array if the session is not open. def writers #:nodoc: readers.select do |io| io.respond_to?(:pending_write?) && io.pending_write? end end # Runs the post-process action on the session, if the session has been # opened. Only the +readers+ and +writers+ that actually belong to this # session will be postprocessed by this server. def postprocess(readers, writers) #:nodoc: return true unless session listeners = session.listeners.keys session.postprocess(listeners & readers, listeners & writers) end end end; end; end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/net-ssh-2.2.2/test/test_buffer.rb
require 'common' require 'net/ssh/buffer' class TestBuffer < Test::Unit::TestCase def test_constructor_should_initialize_buffer_to_empty_by_default buffer = new assert buffer.empty? assert_equal 0, buffer.position end def test_constructor_with_string_should_initialize_buffer_to_the_string buffer = new("hello") assert !buffer.empty? assert_equal "hello", buffer.to_s assert_equal 0, buffer.position end def test_from_should_require_an_even_number_of_arguments assert_raises(ArgumentError) { Net::SSH::Buffer.from("this") } end def test_from_should_build_new_buffer_from_definition buffer = Net::SSH::Buffer.from(:byte, 1, :long, 2, :int64, 3, :string, "4", :bool, true, :bool, false, :bignum, OpenSSL::BN.new("1234567890", 10), :raw, "something") assert_equal "\1\0\0\0\2\0\0\0\0\0\0\0\3\0\0\0\0014\1\0\000\000\000\004I\226\002\322something", buffer.to_s end def test_from_with_array_argument_should_write_multiple_of_the_given_type buffer = Net::SSH::Buffer.from(:byte, [1,2,3,4,5]) assert_equal "\1\2\3\4\5", buffer.to_s end def test_read_without_argument_should_read_to_end buffer = new("hello world") assert_equal "hello world", buffer.read assert buffer.eof? assert_equal 11, buffer.position end def test_read_with_argument_that_is_less_than_length_should_read_that_many_bytes buffer = new "hello world" assert_equal "hello", buffer.read(5) assert_equal 5, buffer.position end def test_read_with_argument_that_is_more_than_length_should_read_no_more_than_length buffer = new "hello world" assert_equal "hello world", buffer.read(500) assert_equal 11, buffer.position end def test_read_at_eof_should_return_empty_string buffer = new "hello" buffer.position = 5 assert_equal "", buffer.read end def test_consume_without_argument_should_resize_buffer_to_start_at_position buffer = new "hello world" buffer.read(5) assert_equal 5, buffer.position assert_equal 11, buffer.length buffer.consume! assert_equal 0, buffer.position assert_equal 6, buffer.length assert_equal " world", buffer.to_s end def test_consume_with_argument_should_resize_buffer_starting_at_n buffer = new "hello world" assert_equal 0, buffer.position buffer.consume!(5) assert_equal 0, buffer.position assert_equal 6, buffer.length assert_equal " world", buffer.to_s end def test_read_bang_should_read_and_consume_and_return_read_portion buffer = new "hello world" assert_equal "hello", buffer.read!(5) assert_equal 0, buffer.position assert_equal 6, buffer.length assert_equal " world", buffer.to_s end def test_available_should_return_length_after_position_to_end_of_string buffer = new "hello world" buffer.read(5) assert_equal 6, buffer.available end def test_clear_bang_should_reset_buffer_contents_and_counters buffer = new "hello world" buffer.read(5) buffer.clear! assert_equal 0, buffer.length assert_equal 0, buffer.position assert_equal "", buffer.to_s end def test_append_should_append_argument_without_changing_position_and_should_return_self buffer = new "hello world" buffer.read(5) buffer.append(" again") assert_equal 5, buffer.position assert_equal 12, buffer.available assert_equal 17, buffer.length assert_equal "hello world again", buffer.to_s end def test_remainder_as_buffer_should_return_a_new_buffer_filled_with_the_text_after_the_current_position buffer = new "hello world" buffer.read(6) b2 = buffer.remainder_as_buffer assert_equal 6, buffer.position assert_equal 0, b2.position assert_equal "world", b2.to_s end def test_read_int64_should_return_8_byte_integer buffer = new "\xff\xee\xdd\xcc\xbb\xaa\x99\x88" assert_equal 0xffeeddccbbaa9988, buffer.read_int64 assert_equal 8, buffer.position end def test_read_int64_should_return_nil_on_partial_read buffer = new "\0\0\0\0\0\0\0" assert_nil buffer.read_int64 assert buffer.eof? end def test_read_long_should_return_4_byte_integer buffer = new "\xff\xee\xdd\xcc\xbb\xaa\x99\x88" assert_equal 0xffeeddcc, buffer.read_long assert_equal 4, buffer.position end def test_read_long_should_return_nil_on_partial_read buffer = new "\0\0\0" assert_nil buffer.read_long assert buffer.eof? end def test_read_byte_should_return_single_byte_integer buffer = new "\xfe\xdc" assert_equal 0xfe, buffer.read_byte assert_equal 1, buffer.position end def test_read_byte_should_return_nil_at_eof assert_nil new.read_byte end def test_read_string_should_read_length_and_data_from_buffer buffer = new "\0\0\0\x0bhello world" assert_equal "hello world", buffer.read_string end def test_read_string_should_return_nil_if_4_byte_length_cannot_be_read assert_nil new("\0\1").read_string end def test_read_bool_should_return_true_if_non_zero_byte_is_read buffer = new "\1\2\3\4\5\6" 6.times { assert_equal true, buffer.read_bool } end def test_read_bool_should_return_false_if_zero_byte_is_read buffer = new "\0" assert_equal false, buffer.read_bool end def test_read_bool_should_return_nil_at_eof assert_nil new.read_bool end def test_read_bignum_should_read_openssl_formatted_bignum buffer = new("\000\000\000\004I\226\002\322") assert_equal OpenSSL::BN.new("1234567890", 10), buffer.read_bignum end def test_read_bignum_should_return_nil_if_length_cannot_be_read assert_nil new("\0\1\2").read_bignum end def test_read_key_blob_should_read_dsa_keys random_dss { |buffer| buffer.read_keyblob("ssh-dss") } end def test_read_key_blob_should_read_rsa_keys random_rsa { |buffer| buffer.read_keyblob("ssh-rsa") } end def test_read_key_should_read_dsa_key_type_and_keyblob random_dss do |buffer| b2 = Net::SSH::Buffer.from(:string, "ssh-dss", :raw, buffer) b2.read_key end end def test_read_key_should_read_rsa_key_type_and_keyblob random_rsa do |buffer| b2 = Net::SSH::Buffer.from(:string, "ssh-rsa", :raw, buffer) b2.read_key end end def test_read_buffer_should_read_a_string_and_return_it_wrapped_in_a_buffer buffer = new("\0\0\0\x0bhello world") b2 = buffer.read_buffer assert_equal 0, b2.position assert_equal 11, b2.length assert_equal "hello world", b2.read end def test_read_to_should_return_nil_if_pattern_does_not_exist_in_buffer buffer = new("one two three") assert_nil buffer.read_to("\n") end def test_read_to_should_grok_string_patterns buffer = new("one two three") assert_equal "one tw", buffer.read_to("tw") assert_equal 6, buffer.position end def test_read_to_should_grok_regex_patterns buffer = new("one two three") assert_equal "one tw", buffer.read_to(/tw/) assert_equal 6, buffer.position end def test_read_to_should_grok_fixnum_patterns buffer = new("one two three") assert_equal "one tw", buffer.read_to(?w) assert_equal 6, buffer.position end def test_reset_bang_should_reset_position_to_0 buffer = new("hello world") buffer.read(5) assert_equal 5, buffer.position buffer.reset! assert_equal 0, buffer.position end def test_write_should_write_arguments_directly_to_end_buffer buffer = new("start") buffer.write "hello", " ", "world" assert_equal "starthello world", buffer.to_s assert_equal 0, buffer.position end def test_write_int64_should_write_arguments_as_8_byte_integers_to_end_of_buffer buffer = new("start") buffer.write_int64 0xffeeddccbbaa9988, 0x7766554433221100 assert_equal "start\xff\xee\xdd\xcc\xbb\xaa\x99\x88\x77\x66\x55\x44\x33\x22\x11\x00", buffer.to_s end def test_write_long_should_write_arguments_as_4_byte_integers_to_end_of_buffer buffer = new("start") buffer.write_long 0xffeeddcc, 0xbbaa9988 assert_equal "start\xff\xee\xdd\xcc\xbb\xaa\x99\x88", buffer.to_s end def test_write_byte_should_write_arguments_as_1_byte_integers_to_end_of_buffer buffer = new("start") buffer.write_byte 1, 2, 3, 4, 5 assert_equal "start\1\2\3\4\5", buffer.to_s end def test_write_bool_should_write_arguments_as_1_byte_boolean_values_to_end_of_buffer buffer = new("start") buffer.write_bool nil, false, true, 1, Object.new assert_equal "start\0\0\1\1\1", buffer.to_s end def test_write_bignum_should_write_arguments_as_ssh_formatted_bignum_values_to_end_of_buffer buffer = new("start") buffer.write_bignum OpenSSL::BN.new('1234567890', 10) assert_equal "start\000\000\000\004I\226\002\322", buffer.to_s end def test_write_dss_key_should_write_argument_to_end_of_buffer buffer = new("start") key = OpenSSL::PKey::DSA.new key.p = <KEY> key.q = 0x7766554433221100 key.g = <KEY> key.pub_key = 0xeeccaa8866442200 buffer.write_key(key) assert_equal "start\0\0\0\7ssh-dss\0\0\0\011\0\xff\xee\xdd\xcc\xbb\xaa\x99\x88\0\0\0\010\x77\x66\x55\x44\x33\x22\x11\x00\0\0\0\011\0\xff\xdd\xbb\x99\x77\x55\x33\x11\0\0\0\011\0\xee\xcc\xaa\x88\x66\x44\x22\x00", buffer.to_s end def test_write_rsa_key_should_write_argument_to_end_of_buffer buffer = new("start") key = OpenSSL::PKey::RSA.new key.e = 0xffeeddccbbaa9988 key.n = 0x7766554433221100 buffer.write_key(key) assert_equal "start\0\0\0\7ssh-rsa\0\0\0\011\0\xff\xee\xdd\xcc\xbb\xaa\x99\x88\0\0\0\010\x77\x66\x55\x44\x33\x22\x11\x00", buffer.to_s end private def random_rsa n1 = OpenSSL::BN.new(rand(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF).to_s, 10) n2 = OpenSSL::BN.new(rand(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF).to_s, 10) buffer = Net::SSH::Buffer.from(:bignum, [n1, n2]) key = yield(buffer) assert_equal "ssh-rsa", key.ssh_type assert_equal n1, key.e assert_equal n2, key.n end def random_dss n1 = OpenSSL::BN.new(rand(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF).to_s, 10) n2 = OpenSSL::BN.new(rand(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF).to_s, 10) n3 = OpenSSL::BN.new(rand(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF).to_s, 10) n4 = OpenSSL::BN.new(rand(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF).to_s, 10) buffer = Net::SSH::Buffer.from(:bignum, [n1, n2, n3, n4]) key = yield(buffer) assert_equal "ssh-dss", key.ssh_type assert_equal n1, key.p assert_equal n2, key.q assert_equal n3, key.g assert_equal n4, key.pub_key end def new(*args) Net::SSH::Buffer.new(*args) end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/logging-2.1.0/examples/classes.rb
# :stopdoc: # # The Logging framework is very good about figuring out predictable names # for loggers regardless of what object is used to create them. The name is # the class name or module name of whatever is passed to the logger bracket # method. The following lines all return the exact same logger instance: # # ary = Array.new # Logging.logger[ary] # Logging.logger[Array] # Logging.logger['Array'] # Logging.logger[:Array] # # So, if you want each class to have it's own logger this is very easy to # do. # require 'logging' Logging.logger.root.appenders = Logging.appenders.stdout Logging.logger.root.level = :info class Foo attr_reader :log def initialize() @log = Logging.logger[self]; end end class Foo::Bar attr_reader :log def initialize() @log = Logging.logger[self]; end end foo = Foo.new.log bar = Foo::Bar.new.log # you'll notice in these log messages that the logger names were taken # from the class names of the Foo and Foo::Bar instances foo.info 'this message came from Foo' bar.warn 'this is a warning from Foo::Bar' # :startdoc:
arnab0073/idea
.rvm/rubies/ruby-1.9.3-p551/lib/ruby/gems/1.9.1/specifications/io-console-0.3.gemspec
<filename>.rvm/rubies/ruby-1.9.3-p551/lib/ruby/gems/1.9.1/specifications/io-console-0.3.gemspec Gem::Specification.new do |s| s.name = "io-console" s.version = "0.3" s.summary = "This io-console is bundled with Ruby" s.executables = [] end
arnab0073/idea
.rvm/src/ruby-2.3.0/test/test_mutex_m.rb
# frozen_string_literal: false require 'test/unit' require 'thread' require 'mutex_m' class TestMutexM < Test::Unit::TestCase def test_cv_wait o = Object.new o.instance_variable_set(:@foo, nil) o.extend(Mutex_m) c = ConditionVariable.new t = Thread.start { o.synchronize do until foo = o.instance_variable_get(:@foo) c.wait(o) end foo end } sleep(0.0001) o.synchronize do o.instance_variable_set(:@foo, "abc") end c.signal assert_equal "abc", t.value end end
arnab0073/idea
.rvm/src/ruby-2.3.0/tool/vcs.rb
# vcs require 'fileutils' ENV.delete('PWD') unless File.respond_to? :realpath require 'pathname' def File.realpath(arg) Pathname(arg).realpath.to_s end end def IO.pread(*args) STDERR.puts(*args.inspect) if $DEBUG popen(*args) {|f|f.read} end if RUBY_VERSION < "2.0" class IO @orig_popen = method(:popen) if defined?(fork) def self.popen(command, *rest, &block) opts = rest.last if opts.kind_of?(Hash) dir = opts.delete(:chdir) rest.pop if opts.empty? end if block @orig_popen.call("-", *rest) do |f| if f yield(f) else Dir.chdir(dir) if dir exec(*command) end end else f = @orig_popen.call("-", *rest) unless f Dir.chdir(dir) if dir exec(*command) end f end end else require 'shellwords' def self.popen(command, *rest, &block) opts = rest.last if opts.kind_of?(Hash) dir = opts.delete(:chdir) rest.pop if opts.empty? end command = command.shelljoin if Array === command Dir.chdir(dir || ".") do @orig_popen.call(command, *rest, &block) end end end end end class VCS class NotFoundError < RuntimeError; end @@dirs = [] def self.register(dir) @@dirs << [dir, self] end def self.detect(path) @@dirs.each do |dir, klass| return klass.new(path) if File.directory?(File.join(path, dir)) prev = path loop { curr = File.realpath(File.join(prev, '..')) break if curr == prev # stop at the root directory return klass.new(path) if File.directory?(File.join(curr, dir)) prev = curr } end raise VCS::NotFoundError, "does not seem to be under a vcs: #{path}" end def self.local_path?(path) String === path or path.respond_to?(:to_path) end def initialize(path) @srcdir = path super() end NullDevice = defined?(IO::NULL) ? IO::NULL : %w[/dev/null NUL NIL: NL:].find {|dev| File.exist?(dev)} # return a pair of strings, the last revision and the last revision in which # +path+ was modified. def get_revisions(path) if self.class.local_path?(path) path = relative_to(path) end last, changed, modified, *rest = ( begin if NullDevice save_stderr = STDERR.dup STDERR.reopen NullDevice, 'w' end self.class.get_revisions(path, @srcdir) ensure if save_stderr STDERR.reopen save_stderr save_stderr.close end end ) last or raise VCS::NotFoundError, "last revision not found" changed or raise VCS::NotFoundError, "changed revision not found" if modified /\A(\d+)-(\d+)-(\d+)\D(\d+):(\d+):(\d+(?:\.\d+)?)\s*(?:Z|([-+]\d\d)(\d\d))\z/ =~ modified or raise "unknown time format - #{modified}" match = $~[1..6].map { |x| x.to_i } off = $7 ? "#{$7}:#{$8}" : "+00:00" match << off begin modified = Time.new(*match) rescue ArgumentError modified = Time.utc(*$~[1..6]) + $7.to_i * 3600 + $8.to_i * 60 end end return last, changed, modified, *rest end def modified(path) last, changed, modified, *rest = get_revisions(path) modified end def relative_to(path) if path srcdir = File.realpath(@srcdir) path = File.realdirpath(path) list1 = srcdir.split(%r{/}) list2 = path.split(%r{/}) while !list1.empty? && !list2.empty? && list1.first == list2.first list1.shift list2.shift end if list1.empty? && list2.empty? "." else ([".."] * list1.length + list2).join("/") end else '.' end end def after_export(dir) end class SVN < self register(".svn") def self.get_revisions(path, srcdir = nil) if srcdir and local_path?(path) path = File.join(srcdir, path) end if srcdir info_xml = IO.pread(%W"svn info --xml #{srcdir}") info_xml = nil unless info_xml[/<url>(.*)<\/url>/, 1] == path.to_s end info_xml ||= IO.pread(%W"svn info --xml #{path}") _, last, _, changed, _ = info_xml.split(/revision="(\d+)"/) modified = info_xml[/<date>([^<>]*)/, 1] branch = info_xml[%r'<relative-url>\^/(?:branches/|tags/)?([^<>]+)', 1] [last, changed, modified, branch] end def self.search_root(path) return unless local_path?(path) parent = File.realpath(path) begin parent = File.dirname(wkdir = parent) return wkdir if File.directory?(wkdir + "/.svn") end until parent == wkdir end def get_info @info ||= IO.pread(%W"svn info --xml #{@srcdir}") end def url unless @url url = get_info[/<root>(.*)<\/root>/, 1] @url = URI.parse(url+"/") if url end @url end def wcroot unless @wcroot info = get_info @wcroot = info[/<wcroot-abspath>(.*)<\/wcroot-abspath>/, 1] @wcroot ||= self.class.search_root(@srcdir) end @wcroot end def branch(name) url + "branches/#{name}" end def tag(name) url + "tags/#{name}" end def trunk url + "trunk" end def branch_list(pat) IO.popen(%W"svn ls #{branch('')}") do |f| f.each do |line| line.chomp! line.chomp!('/') yield(line) if File.fnmatch?(pat, line) end end end def grep(pat, tag, *files, &block) cmd = %W"svn cat" files.map! {|n| File.join(tag, n)} if tag set = block.binding.eval("proc {|match| $~ = match}") IO.popen([cmd, *files]) do |f| f.grep(pat) do |s| set[$~] yield s end end end def export(revision, url, dir, keep_temp = false) if @srcdir and (rootdir = wcroot) srcdir = File.realpath(@srcdir) rootdir << "/" if srcdir.start_with?(rootdir) subdir = srcdir[rootdir.size..-1] subdir = nil if subdir.empty? FileUtils.mkdir_p(svndir = dir+"/.svn") FileUtils.ln_s(Dir.glob(rootdir+"/.svn/*"), svndir) system("svn", "-q", "revert", "-R", subdir || ".", :chdir => dir) or return false FileUtils.rm_rf(svndir) unless keep_temp if subdir tmpdir = Dir.mktmpdir("tmp-co.", "#{dir}/#{subdir}") File.rename(tmpdir, tmpdir = "#{dir}/#{File.basename(tmpdir)}") FileUtils.mv(Dir.glob("#{dir}/#{subdir}/{.[^.]*,..?*,*}"), tmpdir) begin Dir.rmdir("#{dir}/#{subdir}") end until (subdir = File.dirname(subdir)) == '.' FileUtils.mv(Dir.glob("#{tmpdir}/#{subdir}/{.[^.]*,..?*,*}"), dir) Dir.rmdir(tmpdir) end return true end end IO.popen(%W"svn export -r #{revision} #{url} #{dir}") do |pipe| pipe.each {|line| /^A/ =~ line or yield line} end $?.success? end def after_export(dir) FileUtils.rm_rf(dir+"/.svn") end end class GIT < self register(".git") def self.get_revisions(path, srcdir = nil) gitcmd = %W[git] logcmd = gitcmd + %W[log -n1 --date=iso] logcmd << "--grep=^ *git-svn-id: .*@[0-9][0-9]*" idpat = /git-svn-id: .*?@(\d+) \S+\Z/ log = IO.pread(logcmd, :chdir => srcdir) commit = log[/\Acommit (\w+)/, 1] last = log[idpat, 1] if path cmd = logcmd cmd += [path] unless path == '.' log = IO.pread(cmd, :chdir => srcdir) changed = log[idpat, 1] else changed = last end modified = log[/^Date:\s+(.*)/, 1] branch = IO.pread(gitcmd + %W[symbolic-ref HEAD], :chdir => srcdir)[%r'\A(?:refs/heads/)?(.+)', 1] title = IO.pread(gitcmd + %W[log --format=%s -n1 #{commit}..HEAD], :chdir => srcdir) title = nil if title.empty? [last, changed, modified, branch, title] end Branch = Struct.new(:to_str) def branch(name) Branch.new(name) end alias tag branch def trunk branch("trunk") end def stable cmd = %W"git for-each-ref --format=\%(refname:short) refs/heads/ruby_[0-9]*" branch(IO.pread(cmd, :chdir => srcdir)[/.*^(ruby_\d+_\d+)$/m, 1]) end def branch_list(pat) cmd = %W"git for-each-ref --format=\%(refname:short) refs/heads/#{pat}" IO.popen(cmd, :chdir => srcdir) {|f| f.each {|line| line.chomp! yield line } } end def grep(pat, tag, *files, &block) cmd = %W[git grep -h --perl-regexp #{tag} --] set = block.binding.eval("proc {|match| $~ = match}") IO.popen([cmd, *files], :chdir => srcdir) do |f| f.grep(pat) do |s| set[$~] yield s end end end def export(revision, url, dir, keep_temp = false) ret = system("git", "clone", "-s", (@srcdir || '.'), "-b", url, dir) FileUtils.rm_rf("#{dir}/.git") if ret and !keep_temp ret end def after_export(dir) FileUtils.rm_rf("#{dir}/.git") end end end
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/racc/cparse/extconf.rb
# $Id: extconf.rb 25189 2009-10-02 12:04:37Z akr $ require 'mkmf' have_func('rb_block_call', 'ruby/ruby.h') create_makefile 'racc/cparse'
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/-test-/st/numhash/extconf.rb
<reponame>arnab0073/idea<filename>.rvm/src/ruby-1.9.3-p551/ext/-test-/st/numhash/extconf.rb<gh_stars>0 create_makefile("-test-/st/numhash")
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tk/scrollbar.rb
<filename>.rvm/src/ruby-1.9.3-p551/ext/tk/lib/tk/scrollbar.rb<gh_stars>1-10 # # tk/scrollbar.rb : treat scrollbar widget # require 'tk' class Tk::Scrollbar<TkWindow TkCommandNames = ['scrollbar'.freeze].freeze WidgetClassName = 'Scrollbar'.freeze WidgetClassNames[WidgetClassName] ||= self def create_self(keys) @assigned = [] @scroll_proc = proc{|*args| if self.orient == 'horizontal' @assigned.each{|w| w.xview(*args)} else # 'vertical' @assigned.each{|w| w.yview(*args)} end } if keys and keys != None unless TkConfigMethod.__IGNORE_UNKNOWN_CONFIGURE_OPTION__ #tk_call_without_enc('scrollbar', @path, *hash_kv(keys, true)) tk_call_without_enc(self.class::TkCommandNames[0], @path, *hash_kv(keys, true)) else begin tk_call_without_enc(self.class::TkCommandNames[0], @path, *hash_kv(keys, true)) rescue tk_call_without_enc(self.class::TkCommandNames[0], @path) keys = __check_available_configure_options(keys) unless keys.empty? begin tk_call_without_enc('destroy', @path) rescue # cannot destroy configure(keys) else # re-create widget tk_call_without_enc(self.class::TkCommandNames[0], @path, *hash_kv(keys, true)) end end end end else #tk_call_without_enc('scrollbar', @path) tk_call_without_enc(self.class::TkCommandNames[0], @path) end end private :create_self def propagate_set(src_win, first, last) self.set(first, last) if self.orient == 'horizontal' @assigned.each{|w| w.xview('moveto', first) if w != src_win} else # 'vertical' @assigned.each{|w| w.yview('moveto', first) if w != src_win} end end def assign(*wins) begin self.command(@scroll_proc) if self.cget('command').cmd != @scroll_proc rescue Exception self.command(@scroll_proc) end orient = self.orient wins.each{|w| @assigned << w unless @assigned.index(w) if orient == 'horizontal' w.xscrollcommand proc{|first, last| self.propagate_set(w, first, last)} else # 'vertical' w.yscrollcommand proc{|first, last| self.propagate_set(w, first, last)} end } Tk.update # avoid scrollbar trouble self end def assigned_list begin return @assigned.dup if self.cget('command').cmd == @scroll_proc rescue Exception end fail RuntimeError, "not depend on the assigned_list" end def configure(*args) ret = super(*args) # Tk.update # avoid scrollbar trouble ret end #def delta(deltax=None, deltay=None) def delta(deltax, deltay) number(tk_send_without_enc('delta', deltax, deltay)) end #def fraction(x=None, y=None) def fraction(x, y) number(tk_send_without_enc('fraction', x, y)) end def identify(x, y) tk_send_without_enc('identify', x, y) end def get #ary1 = tk_send('get').split #ary2 = [] #for i in ary1 # ary2.push number(i) #end #ary2 list(tk_send_without_enc('get')) end def set(first, last) tk_send_without_enc('set', first, last) self end def activate(element=None) tk_send_without_enc('activate', element) end def moveto(fraction) tk_send_without_enc('moveto', fraction) self end def scroll(*args) tk_send_without_enc('scroll', *args) self end def scroll_units(num) scroll(num, 'units') self end def scroll_pages(num) scroll(num, 'pages') self end end #TkScrollbar = Tk::Scrollbar unless Object.const_defined? :TkScrollbar #Tk.__set_toplevel_aliases__(:Tk, Tk::Scrollbar, :TkScrollbar) Tk.__set_loaded_toplevel_aliases__('tk/scrollbar.rb', :Tk, Tk::Scrollbar, :TkScrollbar) class Tk::XScrollbar<Tk::Scrollbar def create_self(keys) keys = {} unless keys keys['orient'] = 'horizontal' super(keys) end private :create_self end #TkXScrollbar = Tk::XScrollbar unless Object.const_defined? :TkXScrollbar #Tk.__set_toplevel_aliases__(:Tk, Tk::XScrollbar, :TkXScrollbar) Tk.__set_loaded_toplevel_aliases__('tk/scrollbar.rb', :Tk, Tk::XScrollbar, :TkXScrollbar) class Tk::YScrollbar<Tk::Scrollbar def create_self(keys) keys = {} unless keys keys['orient'] = 'vertical' super(keys) end private :create_self end #TkYScrollbar = Tk::YScrollbar unless Object.const_defined? :TkYScrollbar #Tk.__set_toplevel_aliases__(:Tk, Tk::YScrollbar, :TkYScrollbar) Tk.__set_loaded_toplevel_aliases__('tk/scrollbar.rb', :Tk, Tk::YScrollbar, :TkYScrollbar)
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/fog-1.29.0/lib/fog/xenserver/requests/compute/create_sr.rb
module Fog module Compute class XenServer class Real # # Create a storage repository (SR) # # @see http://docs.vmd.citrix.com/XenServer/6.0.0/1.0/en_gb/api/?c=SR # # @param [String] host_ref host reference # @param [String] name_label repository label # @param [String] type storage repository type # @param [String] name_description storage repository description # @param [Hash] device_config used to specify block device path, like # { :device => /dev/sdb } for example # @param [String] physical_size '0' will use the whole device (FIXME # needs confirmation) # @param [String] content_type the type of the SR's content. # According to Citrix documentation, used only to distinguish ISO # libraries from other SRs. Set it to 'iso' for storage repositories # that store a library of ISOs, 'user' or '' (empty) otherwise. # @see http://docs.vmd.citrix.com/XenServer/6.1.0/1.0/en_gb/reference.html#cli-xe-commands_sr # @param [String] shared # # @return [String] an OpaqueRef to the storage repository def create_sr( host_ref, name_label, type = '', name_description = '', device_config = {}, physical_size = '0', content_type = 'user', shared = false, sm_config = {} ) if host_ref.is_a?(Hash) config = host_ref extra_params = name_label [:physical_size, :name, :description, :type, :content_type, :shared, :sm_config].each do |attribute| raise "Missing Argument in first param: #{attribute}" if config[attribute].nil? end [:host_ref, :device_config].each do |attribute| raise "Missing Argument in second param: #{attribute}" if extra_params[attribute].nil? end @connection.request({ :parser => Fog::Parsers::XenServer::Base.new, :method => 'SR.create' }, extra_params[:host_ref], extra_params[:device_config], config[:physical_size], config[:name], config[:description], config[:type], config[:content_type], config[:shared], config[:sm_config]) else Fog::Logger.deprecation( 'This api is deprecated. The expected params are two hashes of attributes.' ) @connection.request( {:parser => Fog::Parsers::XenServer::Base.new, :method => 'SR.create'}, host_ref, device_config || {}, physical_size || '0', name_label, name_description || '', type, content_type, shared || false, sm_config || {} ) end end end class Mock def create_sr( host_ref, name_label, type, name_description = nil, device_config = {}, physical_size = '0', content_type = nil, shared = false, sm_config = {} ) Fog::Mock.not_implemented end end end end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/winrm-1.8.1/spec/issue_184_spec.rb
<gh_stars>0 # encoding: UTF-8 require 'winrm/winrm_service' require 'rexml/document' require 'erb' require 'base64' describe 'issue 184', unit: true do let(:shell_id) { 'shell-123' } let(:command_id) { 123 } let(:test_data_xml_template) do ERB.new(File.read('spec/stubs/responses/get_command_output_response.xml.erb')) end let(:service) do WinRM::WinRMWebService.new( 'http://dummy/wsman', :plaintext, user: 'dummy', pass: '<PASSWORD>') end describe 'response doc stdout with invalid UTF-8 characters' do let(:test_data_stdout) { 'ffff' } # Base64-decodes to '}\xF7\xDF', an invalid sequence let(:test_data_stderr) { '' } let(:test_data_xml) { test_data_xml_template.result(binding) } before do allow(service).to receive(:send_get_output_message).and_return( REXML::Document.new(test_data_xml) ) end it 'does not raise an ArgumentError: invalid byte sequence in UTF-8' do begin expect( service.get_command_output(shell_id, command_id) ).not_to raise_error rescue RSpec::Expectations::ExpectationNotMetError => e expect(e.message).not_to include 'ArgumentError' end end it 'does not have an empty stdout' do expect( service.get_command_output(shell_id, command_id)[:data][0][:stdout] ).not_to be_empty end end describe 'response doc stdout with valid UTF-8' do let(:test_data_raw) { '✓1234-äöü' } let(:test_data_stdout) { Base64.encode64(test_data_raw) } let(:test_data_stderr) { '' } let(:test_data_xml) { test_data_xml_template.result(binding) } before do allow(service).to receive(:send_get_output_message).and_return( REXML::Document.new(test_data_xml) ) end it 'decodes to match input data' do expect( service.get_command_output(shell_id, command_id)[:data][0][:stdout] ).to eq(test_data_raw) end end end
arnab0073/idea
.rvm/src/ruby-2.3.0/gems/did_you_mean-1.0.0/lib/did_you_mean/extra_features/initializer_name_correction.rb
# -*- frozen-string-literal: true -*- module DidYouMean module ExtraFeatures module InitializerNameCorrection def method_added(name) super distance = Levenshtein.distance(name.to_s, 'initialize') if distance != 0 && distance <= 2 warn "warning: #{name} might be misspelled, perhaps you meant initialize?" end end end ::Class.prepend(InitializerNameCorrection) end end
arnab0073/idea
.rvm/src/ruby-2.3.0/bootstraptest/test_fork.rb
<gh_stars>10-100 assert_equal '0', %q{ begin GC.stress = true pid = fork {} Process.wait pid $?.to_i rescue NotImplementedError 0 end }, '[ruby-dev:32404]' assert_finish 10, %q{ begin children = (1..10).map{ Thread.start{fork{}}.value } while !children.empty? and pid = Process.wait children.delete(pid) end rescue NotImplementedError end }, '[ruby-core:22158]' assert_normal_exit(<<'End', '[ruby-dev:37934]') main = Thread.current Thread.new { sleep 0.01 until main.stop?; Thread.kill main } Process.setrlimit(:NPROC, 1) if defined?(Process::RLIMIT_NPROC) fork {} End assert_equal 'ok', %q{ begin r, w = IO.pipe if pid1 = fork w.close r.read(1) Process.kill("USR1", pid1) _, s = Process.wait2(pid1) s.success? ? :ok : :ng else r.close if pid2 = fork trap("USR1") { Time.now.to_s; Process.kill("USR2", pid2) } w.close Process.wait2(pid2) else w.close sleep 0.2 end exit true end rescue NotImplementedError :ok end }, '[ruby-core:28924]' assert_equal '[1, 2]', %q{ a = [] main = Thread.current trap(:INT) { a.push(1).size == 2 and main.wakeup } trap(:TERM) { a.push(2).size == 2 and main.wakeup } pid = $$ begin pid = fork do Process.kill(:INT, pid) Process.kill(:TERM, pid) end Process.wait(pid) 100.times {break if a.size > 1; sleep 0.001} a.sort rescue NotImplementedError [1, 2] end }, '[ruby-dev:44005] [Ruby 1.9 - Bug #4950]'
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/knife-windows-1.4.1/spec/unit/knife/winrm_session_spec.rb
<gh_stars>0 # # Author:: <NAME> <<EMAIL>> # Copyright:: Copyright (c) 2015-2016 Chef Software, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'spec_helper' require 'dummy_winrm_service' Chef::Knife::Winrm.load_deps describe Chef::Knife::WinrmSession do let(:winrm_service) { Dummy::WinRMService.new } let(:options) { { transport: :plaintext } } before do @original_config = Chef::Config.hash_dup allow(WinRM::WinRMWebService).to receive(:new).and_return(winrm_service) allow(winrm_service).to receive(:set_timeout) end after do Chef::Config.configuration = @original_config end subject { Chef::Knife::WinrmSession.new(options) } describe "#initialize" do context "when a proxy is configured" do let(:proxy_uri) { 'blah.com' } let(:ssl_policy) { double('DefaultSSLPolicy', :set_custom_certs => nil) } before do Chef::Config[:http_proxy] = proxy_uri end it "sets the http_proxy to the configured proxy" do subject expect(ENV['HTTP_PROXY']).to eq("http://#{proxy_uri}") end it "sets the ssl policy on the winrm client" do expect(Chef::HTTP::DefaultSSLPolicy).to receive(:new) .with(winrm_service.xfer.httpcli.ssl_config) .and_return(ssl_policy) expect(ssl_policy).to receive(:set_custom_certs) subject end end end describe "#relay_command" do it "run command and display commands output" do expect(winrm_service).to receive(:open_shell).ordered expect(winrm_service).to receive(:run_command).ordered expect(winrm_service).to receive(:get_command_output).ordered.and_return({}) expect(winrm_service).to receive(:cleanup_command).ordered expect(winrm_service).to receive(:close_shell).ordered subject.relay_command("cmd.exe echo 'hi'") end end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/specifications/ohai-6.18.0.gemspec
<gh_stars>0 # -*- encoding: utf-8 -*- # stub: ohai 6.18.0 ruby lib Gem::Specification.new do |s| s.name = "ohai" s.version = "6.18.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.require_paths = ["lib"] s.authors = ["<NAME>"] s.date = "2013-07-19" s.description = "Ohai profiles your system and emits JSON" s.email = "<EMAIL>" s.executables = ["ohai"] s.files = ["bin/ohai"] s.homepage = "http://wiki.opscode.com/display/chef/Ohai" s.rubygems_version = "2.5.1" s.summary = "Ohai profiles your system and emits JSON" s.installed_by_version = "2.5.1" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<systemu>, [">= 0"]) s.add_runtime_dependency(%q<yajl-ruby>, [">= 0"]) s.add_runtime_dependency(%q<mixlib-cli>, [">= 0"]) s.add_runtime_dependency(%q<mixlib-config>, [">= 0"]) s.add_runtime_dependency(%q<mixlib-log>, [">= 0"]) s.add_runtime_dependency(%q<mixlib-shellout>, [">= 0"]) s.add_runtime_dependency(%q<ipaddress>, [">= 0"]) s.add_development_dependency(%q<rake>, [">= 0"]) s.add_development_dependency(%q<rspec-core>, [">= 0"]) s.add_development_dependency(%q<rspec-expectations>, [">= 0"]) s.add_development_dependency(%q<rspec-mocks>, [">= 0"]) s.add_development_dependency(%q<rspec_junit_formatter>, [">= 0"]) else s.add_dependency(%q<systemu>, [">= 0"]) s.add_dependency(%q<yajl-ruby>, [">= 0"]) s.add_dependency(%q<mixlib-cli>, [">= 0"]) s.add_dependency(%q<mixlib-config>, [">= 0"]) s.add_dependency(%q<mixlib-log>, [">= 0"]) s.add_dependency(%q<mixlib-shellout>, [">= 0"]) s.add_dependency(%q<ipaddress>, [">= 0"]) s.add_dependency(%q<rake>, [">= 0"]) s.add_dependency(%q<rspec-core>, [">= 0"]) s.add_dependency(%q<rspec-expectations>, [">= 0"]) s.add_dependency(%q<rspec-mocks>, [">= 0"]) s.add_dependency(%q<rspec_junit_formatter>, [">= 0"]) end else s.add_dependency(%q<systemu>, [">= 0"]) s.add_dependency(%q<yajl-ruby>, [">= 0"]) s.add_dependency(%q<mixlib-cli>, [">= 0"]) s.add_dependency(%q<mixlib-config>, [">= 0"]) s.add_dependency(%q<mixlib-log>, [">= 0"]) s.add_dependency(%q<mixlib-shellout>, [">= 0"]) s.add_dependency(%q<ipaddress>, [">= 0"]) s.add_dependency(%q<rake>, [">= 0"]) s.add_dependency(%q<rspec-core>, [">= 0"]) s.add_dependency(%q<rspec-expectations>, [">= 0"]) s.add_dependency(%q<rspec-mocks>, [">= 0"]) s.add_dependency(%q<rspec_junit_formatter>, [">= 0"]) end end
arnab0073/idea
.rvm/gems/ruby-2.3.0/gems/systemu-2.6.5/samples/a.rb
<reponame>arnab0073/idea # # systemu can be used on any platform to return status, stdout, and stderr of # any command. unlike other methods like open3/popen4 there is zero danger of # full pipes or threading issues hanging your process or subprocess. # require 'systemu' date = %q( ruby -e" t = Time.now; STDOUT.puts t; STDERR.puts t " ) status, stdout, stderr = systemu date p [ status, stdout, stderr ]
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/tk/sample/tkextlib/tcllib/plotdemos3.rb
#!/usr/bin/ruby require 'tk' require 'tkextlib/tcllib/plotchart' ############################### # Set up a strip chart ############################### Tk::Tcllib::Plotchart::Stripchart.new([0.0, 100.0, 10.0], [0.0, 100.0, 20.0], :background=>'white', :width=>400, :height=>200){|chart| title "Aha!" pack(:fill=>:both, :side=>:top) series1 = Tk::Tcllib::Plotchart::PlotSeries.new(chart) series2 = Tk::Tcllib::Plotchart::PlotSeries.new(chart) xd = 15.0 yd = 30.0 TkTimer.new(500, -1, proc{|obj| # obj --> TkTimer object xold, yold = obj.return_value xnew = xold + xd ynew = yold + (rand() - 0.5) * yd ynew2 = yold + (rand() - 0.5) * 2.0 * yd series1.plot(xnew, ynew) series2.plot(xnew, ynew2) obj.stop if xnew >= 200 [xnew, ynew] # return_value }).start(100, proc{ [0.0, 50.0] }) # init return_value } ############################### # Set up an isometric plot ############################### Tk::Tcllib::Plotchart::IsometricPlot.new([0.0, 100.0], [0.0, 200.0], :noaxes, :background=>'white', :width=>400, :height=>200){|chart| pack(:fill=>:both, :side=>:top) set_zoom_pan chart.plot('rectangle', [10.0, 10.0, 50.0, 50.0], 'green') chart.plot('filled-rectangle', [20.0, 20.0, 40.0, 40.0], 'red') chart.plot('filled-circle', [70.0, 70.0, 40.0], 'yellow') chart.plot('circle', [70.0, 70.0, 42.0]) } ############################### # Check the symbols ############################### TkToplevel.new(:title=>'h'){|h| Tk::Tcllib::Plotchart::XYPlot.new(h, [0.0, 100.0, 10.0], [0.0, 100.0, 20.0], :bg=>'white', :width=>400, :height=>200){|chart| pack(:fill=>:both) yconfig(:format=>"%12.2e") series1 = Tk::Tcllib::Plotchart::PlotSeries.new(chart, :colour=>'red', :type=>:symbol) series2 = Tk::Tcllib::Plotchart::PlotSeries.new(chart, :colour=>'green', :type=>:both) x = 5.0 %w(plus cross circle up down dot upfilled downfilled).each{|sym| series1.dataconfig(:symbol=>sym) series2.dataconfig(:symbol=>sym) series1.plot(x, 50.0) series2.plot(x, 20) x += 10 } } } ############################## Tk.mainloop
arnab0073/idea
.rvm/src/ruby-2.3.0/ext/tk/lib/tk/texttag.rb
# frozen_string_literal: false # # tk/texttag.rb - methods for treating text tags # require 'tk' require 'tk/text' require 'tk/tagfont' class TkTextTag<TkObject include TkTreatTagFont include Tk::Text::IndexModMethods TTagID_TBL = TkCore::INTERP.create_table (Tk_TextTag_ID = ['tag'.freeze, TkUtil.untrust('00000')]).instance_eval{ @mutex = Mutex.new def mutex; @mutex; end freeze } TkCore::INTERP.init_ip_env{ TTagID_TBL.mutex.synchronize{ TTagID_TBL.clear } } def TkTextTag.id2obj(text, id) tpath = text.path TTagID_TBL.mutex.synchronize{ if TTagID_TBL[tpath] TTagID_TBL[tpath][id]? TTagID_TBL[tpath][id]: id else id end } end def initialize(parent, *args) #unless parent.kind_of?(TkText) # fail ArgumentError, "expect TkText for 1st argument" #end @parent = @t = parent @tpath = parent.path Tk_TextTag_ID.mutex.synchronize{ # @path = @id = Tk_TextTag_ID.join('') @path = @id = Tk_TextTag_ID.join(TkCore::INTERP._ip_id_).freeze Tk_TextTag_ID[1].succ! } TTagID_TBL.mutex.synchronize{ TTagID_TBL[@id] = self TTagID_TBL[@tpath] = {} unless TTagID_TBL[@tpath] TTagID_TBL[@tpath][@id] = self } #tk_call @t.path, "tag", "configure", @id, *hash_kv(keys) if args != [] keys = args.pop if keys.kind_of?(Hash) add(*args) if args != [] configure(keys) else args.push keys add(*args) end end @t._addtag id, self end def id Tk::Text::IndexString.new(@id) end def exist? #if ( tk_split_simplelist(_fromUTF8(tk_call_without_enc(@t.path, 'tag', 'names'))).find{|id| id == @id } ) if ( tk_split_simplelist(tk_call_without_enc(@t.path, 'tag', 'names'), false, true).find{|id| id == @id } ) true else false end end def first Tk::Text::IndexString.new(@id + '.first') end def last Tk::Text::IndexString.new(@id + '.last') end def add(*indices) tk_call_without_enc(@t.path, 'tag', 'add', @id, *(indices.collect{|idx| _get_eval_enc_str(idx)})) self end def remove(*indices) tk_call_without_enc(@t.path, 'tag', 'remove', @id, *(indices.collect{|idx| _get_eval_enc_str(idx)})) self end def ranges l = tk_split_simplelist(tk_call_without_enc(@t.path, 'tag', 'ranges', @id)) r = [] while key=l.shift r.push [Tk::Text::IndexString.new(key), Tk::Text::IndexString.new(l.shift)] end r end def nextrange(first, last=None) simplelist(tk_call_without_enc(@t.path, 'tag', 'nextrange', @id, _get_eval_enc_str(first), _get_eval_enc_str(last))).collect{|idx| Tk::Text::IndexString.new(idx) } end def prevrange(first, last=None) simplelist(tk_call_without_enc(@t.path, 'tag', 'prevrange', @id, _get_eval_enc_str(first), _get_eval_enc_str(last))).collect{|idx| Tk::Text::IndexString.new(idx) } end def [](key) cget key end def []=(key,val) configure key, val val end def cget_tkstring(key) @t.tag_cget_tkstring @id, key end def cget(key) @t.tag_cget @id, key end def cget_strict(key) @t.tag_cget_strict @id, key end =begin def cget(key) case key.to_s when 'text', 'label', 'show', 'data', 'file' _fromUTF8(tk_call_without_enc(@t.path, 'tag', 'cget', @id, "-#{key}")) when 'font', 'kanjifont' #fnt = tk_tcl2ruby(tk_call(@t.path, 'tag', 'cget', @id, "-#{key}")) fnt = tk_tcl2ruby(_fromUTF8(tk_call_without_enc(@t.path, 'tag', 'cget', @id, '-font'))) unless fnt.kind_of?(TkFont) fnt = tagfontobj(@id, fnt) end if key.to_s == 'kanjifont' && JAPANIZED_TK && TK_VERSION =~ /^4\.*/ # obsolete; just for compatibility fnt.kanji_font else fnt end else tk_tcl2ruby(_fromUTF8(tk_call_without_enc(@t.path, 'tag', 'cget', @id, "-#{key}"))) end end =end def configure(key, val=None) @t.tag_configure @id, key, val end # def configure(key, val=None) # if key.kind_of?(Hash) # tk_call @t.path, 'tag', 'configure', @id, *hash_kv(key) # else # tk_call @t.path, 'tag', 'configure', @id, "-#{key}", val # end # end # def configure(key, value) # if value == FALSE # value = "0" # elsif value.kind_of?(Proc) # value = install_cmd(value) # end # tk_call @t.path, 'tag', 'configure', @id, "-#{key}", value # end def configinfo(key=nil) @t.tag_configinfo @id, key end def current_configinfo(key=nil) @t.current_tag_configinfo @id, key end #def bind(seq, cmd=Proc.new, *args) # _bind([@t.path, 'tag', 'bind', @id], seq, cmd, *args) # self #end def bind(seq, *args) # if args[0].kind_of?(Proc) || args[0].kind_of?(Method) if TkComm._callback_entry?(args[0]) || !block_given? cmd = args.shift else cmd = Proc.new end _bind([@t.path, 'tag', 'bind', @id], seq, cmd, *args) self end #def bind_append(seq, cmd=Proc.new, *args) # _bind_append([@t.path, 'tag', 'bind', @id], seq, cmd, *args) # self #end def bind_append(seq, *args) # if args[0].kind_of?(Proc) || args[0].kind_of?(Method) if TkComm._callback_entry?(args[0]) || !block_given? cmd = args.shift else cmd = Proc.new end _bind_append([@t.path, 'tag', 'bind', @id], seq, cmd, *args) self end def bind_remove(seq) _bind_remove([@t.path, 'tag', 'bind', @id], seq) self end def bindinfo(context=nil) _bindinfo([@t.path, 'tag', 'bind', @id], context) end def raise(above=None) tk_call_without_enc(@t.path, 'tag', 'raise', @id, _get_eval_enc_str(above)) self end def lower(below=None) tk_call_without_enc(@t.path, 'tag', 'lower', @id, _get_eval_enc_str(below)) self end def destroy tk_call_without_enc(@t.path, 'tag', 'delete', @id) TTagID_TBL.mutex.synchronize{ TTagID_TBL[@tpath].delete(@id) if TTagID_TBL[@tpath] } self end end TktTag = TkTextTag class TkTextNamedTag<TkTextTag def self.new(parent, name, *args) tagobj = nil TTagID_TBL.mutex.synchronize{ if TTagID_TBL[parent.path] && TTagID_TBL[parent.path][name] tagobj = TTagID_TBL[parent.path][name] else # super(parent, name, *args) (tagobj = self.allocate).instance_eval{ @parent = @t = parent @tpath = parent.path @path = @id = name TTagID_TBL[@id] = self TTagID_TBL[@tpath] = {} unless TTagID_TBL[@tpath] TTagID_TBL[@tpath][@id] = self unless TTagID_TBL[@tpath][@id] @t._addtag @id, self } end } if args != [] keys = args.pop if keys.kind_of?(Hash) tagobj.add(*args) if args != [] tagobj.configure(keys) else args.push keys tagobj.add(*args) end end tagobj end def initialize(parent, name, *args) # dummy:: not called by 'new' method #unless parent.kind_of?(Tk::Text) # fail ArgumentError, "expect Tk::Text for 1st argument" #end @parent = @t = parent @tpath = parent.path @path = @id = name #if mode # tk_call @t.path, "addtag", @id, *args #end if args != [] keys = args.pop if keys.kind_of?(Hash) add(*args) if args != [] configure(keys) else args.push keys add(*args) end end @t._addtag @id, self end end TktNamedTag = TkTextNamedTag class TkTextTagSel<TkTextNamedTag def self.new(parent, *args) super(parent, 'sel', *args) end end TktTagSel = TkTextTagSel
arnab0073/idea
.rvm/src/ruby-1.9.3-p551/ext/curses/view.rb
<filename>.rvm/src/ruby-1.9.3-p551/ext/curses/view.rb #!/usr/local/bin/ruby require "curses" include Curses # # main # if ARGV.size != 1 then printf("usage: view file\n"); exit end begin fp = open(ARGV[0], "r") rescue raise "cannot open file: #{ARGV[1]}" end # signal(SIGINT, finish) init_screen #keypad(stdscr, TRUE) nonl cbreak noecho #scrollok(stdscr, TRUE) # slurp the file data_lines = [] fp.each_line { |l| data_lines.push(l) } fp.close lptr = 0 while TRUE i = 0 while i < lines setpos(i, 0) #clrtoeol addstr(data_lines[lptr + i]) #if data_lines[lptr + i] i += 1 end refresh explicit = FALSE n = 0 while TRUE c = getch if c =~ /[0-9]/ n = 10 * n + c.to_i else break end end n = 1 if !explicit && n == 0 case c when "n" #when KEY_DOWN i = 0 while i < n if lptr + lines < data_lines.size then lptr += 1 else break end i += 1 end #wscrl(i) when "p" #when KEY_UP i = 0 while i < n if lptr > 0 then lptr -= 1 else break end i += 1 end #wscrl(-i) when "q" break end end close_screen