repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/contrib/compositepublisher.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/contrib/compositepublisher.rb
#!/usr/bin/env ruby module Rake # Manage several publishers as a single entity. class CompositePublisher def initialize @publishers = [] end # Add a publisher to the composite. def add(pub) @publishers << pub end # Upload all the individual publishers. def upload @publishers.each { |p| p.upload } end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/contrib/ftptools.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/contrib/ftptools.rb
#!/usr/bin/env ruby # = Tools for FTP uploading. # # This file is still under development and is not released for general # use. require 'date' require 'net/ftp' module Rake # :nodoc: #################################################################### # <b>Note:</b> <em> Not released for general use.</em> class FtpFile attr_reader :name, :size, :owner, :group, :time def self.date @date_class ||= Date end def self.time @time_class ||= Time end def initialize(path, entry) @path = path @mode, line, @owner, @group, size, d1, d2, d3, @name = entry.split(' ') @size = size.to_i @time = determine_time(d1, d2, d3) end def path File.join(@path, @name) end def directory? @mode[0] == ?d end def mode parse_mode(@mode) end def symlink? @mode[0] == ?l end private # -------------------------------------------------------- def parse_mode(m) result = 0 (1..9).each do |i| result = 2*result + ((m[i]==?-) ? 0 : 1) end result end def determine_time(d1, d2, d3) now = self.class.time.now if /:/ =~ d3 h, m = d3.split(':') result = Time.parse("#{d1} #{d2} #{now.year} #{d3}") if result > now result = Time.parse("#{d1} #{d2} #{now.year-1} #{d3}") end else result = Time.parse("#{d1} #{d2} #{d3}") end result # elements = ParseDate.parsedate("#{d1} #{d2} #{d3}") # if elements[0].nil? # today = self.class.date.today # if elements[1] > today.month # elements[0] = today.year - 1 # else # elements[0] = today.year # end # end # elements = elements.collect { |el| el.nil? ? 0 : el } # Time.mktime(*elements[0,7]) end end #################################################################### # Manage the uploading of files to an FTP account. class FtpUploader # Log uploads to standard output when true. attr_accessor :verbose class << FtpUploader # Create an uploader and pass it to the given block as +up+. # When the block is complete, close the uploader. def connect(path, host, account, password) up = self.new(path, host, account, password) begin yield(up) ensure up.close end end end # Create an FTP uploader targetting the directory +path+ on +host+ # using the given account and password. +path+ will be the root # path of the uploader. def initialize(path, host, account, password) @created = Hash.new @path = path @ftp = Net::FTP.new(host, account, password) makedirs(@path) @ftp.chdir(@path) end # Create the directory +path+ in the uploader root path. def makedirs(path) route = [] File.split(path).each do |dir| route << dir current_dir = File.join(route) if @created[current_dir].nil? @created[current_dir] = true puts "Creating Directory #{current_dir}" if @verbose @ftp.mkdir(current_dir) rescue nil end end end # Upload all files matching +wildcard+ to the uploader's root # path. def upload_files(wildcard) Dir[wildcard].each do |fn| upload(fn) end end # Close the uploader. def close @ftp.close end private # -------------------------------------------------------- # Upload a single file to the uploader's root path. def upload(file) puts "Uploading #{file}" if @verbose dir = File.dirname(file) makedirs(dir) @ftp.putbinaryfile(file, file) unless File.directory?(file) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/contrib/publisher.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/contrib/publisher.rb
#!/usr/bin/env ruby # Copyright 2003, 2004, 2005, 2006, 2007, 2008 by Jim Weirich (jim@weirichhouse.org) # All rights reserved. # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. # Configuration information about an upload host system. # * name :: Name of host system. # * webdir :: Base directory for the web information for the # application. The application name (APP) is appended to # this directory before using. # * pkgdir :: Directory on the host system where packages can be # placed. HostInfo = Struct.new(:name, :webdir, :pkgdir) # Manage several publishers as a single entity. class CompositePublisher def initialize @publishers = [] end # Add a publisher to the composite. def add(pub) @publishers << pub end # Upload all the individual publishers. def upload @publishers.each { |p| p.upload } end end # Publish an entire directory to an existing remote directory using # SSH. class SshDirPublisher def initialize(host, remote_dir, local_dir) @host = host @remote_dir = remote_dir @local_dir = local_dir end def upload run %{scp -rq #{@local_dir}/* #{@host}:#{@remote_dir}} end end # Publish an entire directory to a fresh remote directory using SSH. class SshFreshDirPublisher < SshDirPublisher def upload run %{ssh #{@host} rm -rf #{@remote_dir}} rescue nil run %{ssh #{@host} mkdir #{@remote_dir}} super end end # Publish a list of files to an existing remote directory. class SshFilePublisher # Create a publisher using the give host information. def initialize(host, remote_dir, local_dir, *files) @host = host @remote_dir = remote_dir @local_dir = local_dir @files = files end # Upload the local directory to the remote directory. def upload @files.each do |fn| run %{scp -q #{@local_dir}/#{fn} #{@host}:#{@remote_dir}} end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/contrib/sshpublisher.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/contrib/sshpublisher.rb
#!/usr/bin/env ruby require 'rake/contrib/compositepublisher' module Rake # Publish an entire directory to an existing remote directory using # SSH. class SshDirPublisher def initialize(host, remote_dir, local_dir) @host = host @remote_dir = remote_dir @local_dir = local_dir end def upload sh %{scp -rq #{@local_dir}/* #{@host}:#{@remote_dir}} end end # Publish an entire directory to a fresh remote directory using SSH. class SshFreshDirPublisher < SshDirPublisher def upload sh %{ssh #{@host} rm -rf #{@remote_dir}} rescue nil sh %{ssh #{@host} mkdir #{@remote_dir}} super end end # Publish a list of files to an existing remote directory. class SshFilePublisher # Create a publisher using the give host information. def initialize(host, remote_dir, local_dir, *files) @host = host @remote_dir = remote_dir @local_dir = local_dir @files = files end # Upload the local directory to the remote directory. def upload @files.each do |fn| sh %{scp -q #{@local_dir}/#{fn} #{@host}:#{@remote_dir}} end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/contrib/sys.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/contrib/sys.rb
#!/usr/bin/env ruby #-- # Copyright 2003, 2004, 2005, 2006, 2007, 2008 by Jim Weirich (jim@weirichhouse.org) # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #++ # begin require 'ftools' rescue LoadError end require 'rbconfig' ###################################################################### # Sys provides a number of file manipulation tools for the convenience # of writing Rakefiles. All commands in this module will announce # their activity on standard output if the $verbose flag is set # ($verbose = true is the default). You can control this by globally # setting $verbose or by using the +verbose+ and +quiet+ methods. # # Sys has been deprecated in favor of the FileUtils module available # in Ruby 1.8. # module Sys RUBY = Config::CONFIG['ruby_install_name'] # Install all the files matching +wildcard+ into the +dest_dir+ # directory. The permission mode is set to +mode+. def install(wildcard, dest_dir, mode) Dir[wildcard].each do |fn| File.install(fn, dest_dir, mode, $verbose) end end # Run the system command +cmd+. def run(cmd) log cmd system(cmd) or fail "Command Failed: [#{cmd}]" end # Run a Ruby interpreter with the given arguments. def ruby(*args) run "#{RUBY} #{args.join(' ')}" end # Copy a single file from +file_name+ to +dest_file+. def copy(file_name, dest_file) log "Copying file #{file_name} to #{dest_file}" File.copy(file_name, dest_file) end # Copy all files matching +wildcard+ into the directory +dest_dir+. def copy_files(wildcard, dest_dir) for_matching_files(wildcard, dest_dir) { |from, to| copy(from, to) } end # Link +file_name+ to +dest_file+. def link(file_name, dest_file) log "Linking file #{file_name} to #{dest_file}" File.link(file_name, dest_file) end # Link all files matching +wildcard+ into the directory +dest_dir+. def link_files(wildcard, dest_dir) for_matching_files(wildcard, dest_dir) { |from, to| link(from, to) } end # Symlink +file_name+ to +dest_file+. def symlink(file_name, dest_file) log "Symlinking file #{file_name} to #{dest_file}" File.symlink(file_name, dest_file) end # Symlink all files matching +wildcard+ into the directory +dest_dir+. def symlink_files(wildcard, dest_dir) for_matching_files(wildcard, dest_dir) { |from, to| link(from, to) } end # Remove all files matching +wildcard+. If a matching file is a # directory, it must be empty to be removed. used +delete_all+ to # recursively delete directories. def delete(*wildcards) wildcards.each do |wildcard| Dir[wildcard].each do |fn| if File.directory?(fn) log "Deleting directory #{fn}" Dir.delete(fn) else log "Deleting file #{fn}" File.delete(fn) end end end end # Recursively delete all files and directories matching +wildcard+. def delete_all(*wildcards) wildcards.each do |wildcard| Dir[wildcard].each do |fn| next if ! File.exist?(fn) if File.directory?(fn) Dir["#{fn}/*"].each do |subfn| next if subfn=='.' || subfn=='..' delete_all(subfn) end log "Deleting directory #{fn}" Dir.delete(fn) else log "Deleting file #{fn}" File.delete(fn) end end end end # Make the directories given in +dirs+. def makedirs(*dirs) dirs.each do |fn| log "Making directory #{fn}" File.makedirs(fn) end end # Make +dir+ the current working directory for the duration of # executing the given block. def indir(dir) olddir = Dir.pwd Dir.chdir(dir) yield ensure Dir.chdir(olddir) end # Split a file path into individual directory names. # # For example: # split_all("a/b/c") => ['a', 'b', 'c'] def split_all(path) head, tail = File.split(path) return [tail] if head == '.' || tail == '/' return [head, tail] if head == '/' return split_all(head) + [tail] end # Write a message to standard out if $verbose is enabled. def log(msg) print " " if $trace && $verbose puts msg if $verbose end # Perform a block with $verbose disabled. def quiet(&block) with_verbose(false, &block) end # Perform a block with $verbose enabled. def verbose(&block) with_verbose(true, &block) end # Perform a block with each file matching a set of wildcards. def for_files(*wildcards) wildcards.each do |wildcard| Dir[wildcard].each do |fn| yield(fn) end end end extend(self) private # ---------------------------------------------------------- def for_matching_files(wildcard, dest_dir) Dir[wildcard].each do |fn| dest_file = File.join(dest_dir, fn) parent = File.dirname(dest_file) makedirs(parent) if ! File.directory?(parent) yield(fn, dest_file) end end def with_verbose(v) oldverbose = $verbose $verbose = v yield ensure $verbose = oldverbose end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/loaders/makefile.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/lib/rake/loaders/makefile.rb
#!/usr/bin/env ruby module Rake # Makefile loader to be used with the import file loader. class MakefileLoader SPACE_MARK = "__&NBSP;__" # Load the makefile dependencies in +fn+. def load(fn) open(fn) do |mf| lines = mf.read lines.gsub!(/\\ /, SPACE_MARK) lines.gsub!(/#[^\n]*\n/m, "") lines.gsub!(/\\\n/, ' ') lines.split("\n").each do |line| process_line(line) end end end private # Process one logical line of makefile data. def process_line(line) file_tasks, args = line.split(':') return if args.nil? dependents = args.split.map { |d| respace(d) } file_tasks.strip.split.each do |file_task| file_task = respace(file_task) file file_task => dependents end end def respace(str) str.gsub(/#{SPACE_MARK}/, ' ') end end # Install the handler Rake.application.add_loader('mf', MakefileLoader.new) end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/doc/jamis.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/rake-0.8.7/doc/jamis.rb
module RDoc module Page FONTS = "\"Bitstream Vera Sans\", Verdana, Arial, Helvetica, sans-serif" STYLE = <<CSS a { color: #00F; text-decoration: none; } a:hover { color: #77F; text-decoration: underline; } body, td, p { font-family: %fonts%; background: #FFF; color: #000; margin: 0px; font-size: small; } #content { margin: 2em; } #description p { margin-bottom: 0.5em; } .sectiontitle { margin-top: 1em; margin-bottom: 1em; padding: 0.5em; padding-left: 2em; background: #005; color: #FFF; font-weight: bold; border: 1px dotted black; } .attr-rw { padding-left: 1em; padding-right: 1em; text-align: center; color: #055; } .attr-name { font-weight: bold; } .attr-desc { } .attr-value { font-family: monospace; } .file-title-prefix { font-size: large; } .file-title { font-size: large; font-weight: bold; background: #005; color: #FFF; } .banner { background: #005; color: #FFF; border: 1px solid black; padding: 1em; } .banner td { background: transparent; color: #FFF; } h1 a, h2 a, .sectiontitle a, .banner a { color: #FF0; } h1 a:hover, h2 a:hover, .sectiontitle a:hover, .banner a:hover { color: #FF7; } .dyn-source { display: none; background: #FFE; color: #000; border: 1px dotted black; margin: 0.5em 2em 0.5em 2em; padding: 0.5em; } .dyn-source .cmt { color: #00F; font-style: italic; } .dyn-source .kw { color: #070; font-weight: bold; } .method { margin-left: 1em; margin-right: 1em; margin-bottom: 1em; } .description pre { padding: 0.5em; border: 1px dotted black; background: #FFE; } .method .title { font-family: monospace; font-size: large; border-bottom: 1px dashed black; margin-bottom: 0.3em; padding-bottom: 0.1em; } .method .description, .method .sourcecode { margin-left: 1em; } .description p, .sourcecode p { margin-bottom: 0.5em; } .method .sourcecode p.source-link { text-indent: 0em; margin-top: 0.5em; } .method .aka { margin-top: 0.3em; margin-left: 1em; font-style: italic; text-indent: 2em; } h1 { padding: 1em; border: 1px solid black; font-size: x-large; font-weight: bold; color: #FFF; background: #007; } h2 { padding: 0.5em 1em 0.5em 1em; border: 1px solid black; font-size: large; font-weight: bold; color: #FFF; background: #009; } h3, h4, h5, h6 { padding: 0.2em 1em 0.2em 1em; border: 1px dashed black; color: #000; background: #AAF; } .sourcecode > pre { padding: 0.5em; border: 1px dotted black; background: #FFE; } CSS XHTML_PREAMBLE = %{<?xml version="1.0" encoding="%charset%"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> } HEADER = XHTML_PREAMBLE + <<ENDHEADER <html> <head> <title>%title%</title> <meta http-equiv="Content-Type" content="text/html; charset=%charset%" /> <link rel="stylesheet" href="%style_url%" type="text/css" media="screen" /> <script language="JavaScript" type="text/javascript"> // <![CDATA[ function toggleSource( id ) { var elem var link if( document.getElementById ) { elem = document.getElementById( id ) link = document.getElementById( "l_" + id ) } else if ( document.all ) { elem = eval( "document.all." + id ) link = eval( "document.all.l_" + id ) } else return false; if( elem.style.display == "block" ) { elem.style.display = "none" link.innerHTML = "show source" } else { elem.style.display = "block" link.innerHTML = "hide source" } } function openCode( url ) { window.open( url, "SOURCE_CODE", "width=400,height=400,scrollbars=yes" ) } // ]]> </script> </head> <body> ENDHEADER FILE_PAGE = <<HTML <table border='0' cellpadding='0' cellspacing='0' width="100%" class='banner'> <tr><td> <table width="100%" border='0' cellpadding='0' cellspacing='0'><tr> <td class="file-title" colspan="2"><span class="file-title-prefix">File</span><br />%short_name%</td> <td align="right"> <table border='0' cellspacing="0" cellpadding="2"> <tr> <td>Path:</td> <td>%full_path% IF:cvsurl &nbsp;(<a href="%cvsurl%">CVS</a>) ENDIF:cvsurl </td> </tr> <tr> <td>Modified:</td> <td>%dtm_modified%</td> </tr> </table> </td></tr> </table> </td></tr> </table><br> HTML ################################################################### CLASS_PAGE = <<HTML <table width="100%" border='0' cellpadding='0' cellspacing='0' class='banner'><tr> <td class="file-title"><span class="file-title-prefix">%classmod%</span><br />%full_name%</td> <td align="right"> <table cellspacing=0 cellpadding=2> <tr valign="top"> <td>In:</td> <td> START:infiles HREF:full_path_url:full_path: IF:cvsurl &nbsp;(<a href="%cvsurl%">CVS</a>) ENDIF:cvsurl END:infiles </td> </tr> IF:parent <tr> <td>Parent:</td> <td> IF:par_url <a href="%par_url%"> ENDIF:par_url %parent% IF:par_url </a> ENDIF:par_url </td> </tr> ENDIF:parent </table> </td> </tr> </table> HTML ################################################################### METHOD_LIST = <<HTML <div id="content"> IF:diagram <table cellpadding='0' cellspacing='0' border='0' width="100%"><tr><td align="center"> %diagram% </td></tr></table> ENDIF:diagram IF:description <div class="description">%description%</div> ENDIF:description IF:requires <div class="sectiontitle">Required Files</div> <ul> START:requires <li>HREF:aref:name:</li> END:requires </ul> ENDIF:requires IF:toc <div class="sectiontitle">Contents</div> <ul> START:toc <li><a href="#%href%">%secname%</a></li> END:toc </ul> ENDIF:toc IF:methods <div class="sectiontitle">Methods</div> <ul> START:methods <li>HREF:aref:name:</li> END:methods </ul> ENDIF:methods IF:includes <div class="sectiontitle">Included Modules</div> <ul> START:includes <li>HREF:aref:name:</li> END:includes </ul> ENDIF:includes START:sections IF:sectitle <div class="sectiontitle"><a nem="%secsequence%">%sectitle%</a></div> IF:seccomment <div class="description"> %seccomment% </div> ENDIF:seccomment ENDIF:sectitle IF:classlist <div class="sectiontitle">Classes and Modules</div> %classlist% ENDIF:classlist IF:constants <div class="sectiontitle">Constants</div> <table border='0' cellpadding='5'> START:constants <tr valign='top'> <td class="attr-name">%name%</td> <td>=</td> <td class="attr-value">%value%</td> </tr> IF:desc <tr valign='top'> <td>&nbsp;</td> <td colspan="2" class="attr-desc">%desc%</td> </tr> ENDIF:desc END:constants </table> ENDIF:constants IF:attributes <div class="sectiontitle">Attributes</div> <table border='0' cellpadding='5'> START:attributes <tr valign='top'> <td class='attr-rw'> IF:rw [%rw%] ENDIF:rw </td> <td class='attr-name'>%name%</td> <td class='attr-desc'>%a_desc%</td> </tr> END:attributes </table> ENDIF:attributes IF:method_list START:method_list IF:methods <div class="sectiontitle">%type% %category% methods</div> START:methods <div class="method"> <div class="title"> IF:callseq <a name="%aref%"></a><b>%callseq%</b> ENDIF:callseq IFNOT:callseq <a name="%aref%"></a><b>%name%</b>%params% ENDIF:callseq IF:codeurl [ <a href="javascript:openCode('%codeurl%')">source</a> ] ENDIF:codeurl </div> IF:m_desc <div class="description"> %m_desc% </div> ENDIF:m_desc IF:aka <div class="aka"> This method is also aliased as START:aka <a href="%aref%">%name%</a> END:aka </div> ENDIF:aka IF:sourcecode <div class="sourcecode"> <p class="source-link">[ <a href="javascript:toggleSource('%aref%_source')" id="l_%aref%_source">show source</a> ]</p> <div id="%aref%_source" class="dyn-source"> <pre> %sourcecode% </pre> </div> </div> ENDIF:sourcecode </div> END:methods ENDIF:methods END:method_list ENDIF:method_list END:sections </div> HTML FOOTER = <<ENDFOOTER </body> </html> ENDFOOTER BODY = HEADER + <<ENDBODY !INCLUDE! <!-- banner header --> <div id="bodyContent"> #{METHOD_LIST} </div> #{FOOTER} ENDBODY ########################## Source code ########################## SRC_PAGE = XHTML_PREAMBLE + <<HTML <html> <head><title>%title%</title> <meta http-equiv="Content-Type" content="text/html; charset=%charset%"> <style> .ruby-comment { color: green; font-style: italic } .ruby-constant { color: #4433aa; font-weight: bold; } .ruby-identifier { color: #222222; } .ruby-ivar { color: #2233dd; } .ruby-keyword { color: #3333FF; font-weight: bold } .ruby-node { color: #777777; } .ruby-operator { color: #111111; } .ruby-regexp { color: #662222; } .ruby-value { color: #662222; font-style: italic } .kw { color: #3333FF; font-weight: bold } .cmt { color: green; font-style: italic } .str { color: #662222; font-style: italic } .re { color: #662222; } </style> </head> <body bgcolor="white"> <pre>%code%</pre> </body> </html> HTML ########################## Index ################################ FR_INDEX_BODY = <<HTML !INCLUDE! HTML FILE_INDEX = XHTML_PREAMBLE + <<HTML <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=%charset%"> <style> <!-- body { background-color: #EEE; font-family: #{FONTS}; color: #000; margin: 0px; } .banner { background: #005; color: #FFF; padding: 0.2em; font-size: small; font-weight: bold; text-align: center; } .entries { margin: 0.25em 1em 0 1em; font-size: x-small; } a { color: #00F; text-decoration: none; white-space: nowrap; } a:hover { color: #77F; text-decoration: underline; } --> </style> <base target="docwin"> </head> <body> <div class="banner">%list_title%</div> <div class="entries"> START:entries <a href="%href%">%name%</a><br> END:entries </div> </body></html> HTML CLASS_INDEX = FILE_INDEX METHOD_INDEX = FILE_INDEX INDEX = XHTML_PREAMBLE + <<HTML <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>%title%</title> <meta http-equiv="Content-Type" content="text/html; charset=%charset%"> </head> <frameset cols="20%,*"> <frameset rows="15%,35%,50%"> <frame src="fr_file_index.html" title="Files" name="Files" /> <frame src="fr_class_index.html" name="Classes" /> <frame src="fr_method_index.html" name="Methods" /> </frameset> IF:inline_source <frame src="%initial_page%" name="docwin"> ENDIF:inline_source IFNOT:inline_source <frameset rows="80%,20%"> <frame src="%initial_page%" name="docwin"> <frame src="blank.html" name="source"> </frameset> ENDIF:inline_source <noframes> <body bgcolor="white"> Click <a href="html/index.html">here</a> for a non-frames version of this page. </body> </noframes> </frameset> </html> HTML end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/sources-0.0.1/lib/sources.rb
tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/sources-0.0.1/lib/sources.rb
module Gem @sources = ["http://gems.rubyforge.org"] def self.sources @sources end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/abbrev.rb
tools/jruby-1.5.1/lib/ruby/1.8/abbrev.rb
#!/usr/bin/env ruby =begin # # Copyright (c) 2001,2003 Akinori MUSHA <knu@iDaemons.org> # # All rights reserved. You can redistribute and/or modify it under # the same terms as Ruby. # # $Idaemons: /home/cvs/rb/abbrev.rb,v 1.2 2001/05/30 09:37:45 knu Exp $ # $RoughId: abbrev.rb,v 1.4 2003/10/14 19:45:42 knu Exp $ # $Id: abbrev.rb 11708 2007-02-12 23:01:19Z shyouhei $ =end # Calculate the set of unique abbreviations for a given set of strings. # # require 'abbrev' # require 'pp' # # pp Abbrev::abbrev(['ruby', 'rules']).sort # # <i>Generates:</i> # # [["rub", "ruby"], # ["ruby", "ruby"], # ["rul", "rules"], # ["rule", "rules"], # ["rules", "rules"]] # # Also adds an +abbrev+ method to class +Array+. module Abbrev # Given a set of strings, calculate the set of unambiguous # abbreviations for those strings, and return a hash where the keys # are all the possible abbreviations and the values are the full # strings. Thus, given input of "car" and "cone", the keys pointing # to "car" would be "ca" and "car", while those pointing to "cone" # would be "co", "con", and "cone". # # The optional +pattern+ parameter is a pattern or a string. Only # those input strings matching the pattern, or begging the string, # are considered for inclusion in the output hash def abbrev(words, pattern = nil) table = {} seen = Hash.new(0) if pattern.is_a?(String) pattern = /^#{Regexp.quote(pattern)}/ # regard as a prefix end words.each do |word| next if (abbrev = word).empty? while (len = abbrev.rindex(/[\w\W]\z/)) > 0 abbrev = word[0,len] next if pattern && pattern !~ abbrev case seen[abbrev] += 1 when 1 table[abbrev] = word when 2 table.delete(abbrev) else break end end end words.each do |word| next if pattern && pattern !~ word table[word] = word end table end module_function :abbrev end class Array # Calculates the set of unambiguous abbreviations for the strings in # +self+. If passed a pattern or a string, only the strings matching # the pattern or starting with the string are considered. # # %w{ car cone }.abbrev #=> { "ca" => "car", "car" => "car", # "co" => "cone", "con" => cone", # "cone" => "cone" } def abbrev(pattern = nil) Abbrev::abbrev(self, pattern) end end if $0 == __FILE__ while line = gets hash = line.split.abbrev hash.sort.each do |k, v| puts "#{k} => #{v}" end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rubyunit.rb
tools/jruby-1.5.1/lib/ruby/1.8/rubyunit.rb
# Author:: Nathaniel Talbott. # Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved. # License:: Ruby license. require 'runit/testcase' require 'test/unit'
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/parsearg.rb
tools/jruby-1.5.1/lib/ruby/1.8/parsearg.rb
# # parsearg.rb - parse arguments # $Release Version: $ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Yasuo OHBA(SHL Japan Inc. Technology Dept.) # # -- # # # warn "Warning:#{caller[0].sub(/:in `.*'\z/, '')}: parsearg is deprecated after Ruby 1.8.1; use optparse instead" $RCS_ID=%q$Header$ require "getopts" def printUsageAndExit() if $USAGE eval($USAGE) end exit() end def setParenthesis(ex, opt, c) if opt != "" ex = sprintf("%s$OPT_%s%s", ex, opt, c) else ex = sprintf("%s%s", ex, c) end return ex end def setOrAnd(ex, opt, c) if opt != "" ex = sprintf("%s$OPT_%s %s%s ", ex, opt, c, c) else ex = sprintf("%s %s%s ", ex, c, c) end return ex end def setExpression(ex, opt, op) if !op ex = sprintf("%s$OPT_%s", ex, opt) return ex end case op.chr when "(", ")" ex = setParenthesis(ex, opt, op.chr) when "|", "&" ex = setOrAnd(ex, opt, op.chr) else return nil end return ex end # parseArgs is obsolete. Use OptionParser instead. def parseArgs(argc, nopt, single_opts, *opts) if (noOptions = getopts(single_opts, *opts)) == nil printUsageAndExit() end if nopt ex = nil pos = 0 for o in nopt.split(/[()|&]/) pos += o.length ex = setExpression(ex, o, nopt[pos]) pos += 1 end begin if !eval(ex) printUsageAndExit() end rescue print "Format Error!! : \"" + nopt + "\"\t[parseArgs]\n" exit!(-1) end end if ARGV.length < argc printUsageAndExit() end return noOptions end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/find.rb
tools/jruby-1.5.1/lib/ruby/1.8/find.rb
# # find.rb: the Find module for processing all files under a given directory. # # # The +Find+ module supports the top-down traversal of a set of file paths. # # For example, to total the size of all files under your home directory, # ignoring anything in a "dot" directory (e.g. $HOME/.ssh): # # require 'find' # # total_size = 0 # # Find.find(ENV["HOME"]) do |path| # if FileTest.directory?(path) # if File.basename(path)[0] == ?. # Find.prune # Don't look any further into this directory. # else # next # end # else # total_size += FileTest.size(path) # end # end # module Find # # Calls the associated block with the name of every file and directory listed # as arguments, then recursively on their subdirectories, and so on. # # See the +Find+ module documentation for an example. # def find(*paths) # :yield: path paths.collect!{|d| d.dup} while file = paths.shift catch(:prune) do yield file.dup.taint next unless File.exist? file begin if File.lstat(file).directory? then d = Dir.open(file) begin for f in d next if f == "." or f == ".." if File::ALT_SEPARATOR and file =~ /^(?:[\/\\]|[A-Za-z]:[\/\\]?)$/ then f = file + f elsif file == "/" then f = "/" + f else f = File.join(file, f) end paths.unshift f.untaint end ensure d.close end end rescue Errno::ENOENT, Errno::EACCES end end end end # # Skips the current file or directory, restarting the loop with the next # entry. If the current file is a directory, that directory will not be # recursively entered. Meaningful only within the block associated with # Find::find. # # See the +Find+ module documentation for an example. # def prune throw :prune end module_function :find, :prune end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/tsort.rb
tools/jruby-1.5.1/lib/ruby/1.8/tsort.rb
#!/usr/bin/env ruby #-- # tsort.rb - provides a module for topological sorting and strongly connected components. #++ # # # TSort implements topological sorting using Tarjan's algorithm for # strongly connected components. # # TSort is designed to be able to be used with any object which can be # interpreted as a directed graph. # # TSort requires two methods to interpret an object as a graph, # tsort_each_node and tsort_each_child. # # * tsort_each_node is used to iterate for all nodes over a graph. # * tsort_each_child is used to iterate for child nodes of a given node. # # The equality of nodes are defined by eql? and hash since # TSort uses Hash internally. # # == A Simple Example # # The following example demonstrates how to mix the TSort module into an # existing class (in this case, Hash). Here, we're treating each key in # the hash as a node in the graph, and so we simply alias the required # #tsort_each_node method to Hash's #each_key method. For each key in the # hash, the associated value is an array of the node's child nodes. This # choice in turn leads to our implementation of the required #tsort_each_child # method, which fetches the array of child nodes and then iterates over that # array using the user-supplied block. # # require 'tsort' # # class Hash # include TSort # alias tsort_each_node each_key # def tsort_each_child(node, &block) # fetch(node).each(&block) # end # end # # {1=>[2, 3], 2=>[3], 3=>[], 4=>[]}.tsort # #=> [3, 2, 1, 4] # # {1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}.strongly_connected_components # #=> [[4], [2, 3], [1]] # # == A More Realistic Example # # A very simple `make' like tool can be implemented as follows: # # require 'tsort' # # class Make # def initialize # @dep = {} # @dep.default = [] # end # # def rule(outputs, inputs=[], &block) # triple = [outputs, inputs, block] # outputs.each {|f| @dep[f] = [triple]} # @dep[triple] = inputs # end # # def build(target) # each_strongly_connected_component_from(target) {|ns| # if ns.length != 1 # fs = ns.delete_if {|n| Array === n} # raise TSort::Cyclic.new("cyclic dependencies: #{fs.join ', '}") # end # n = ns.first # if Array === n # outputs, inputs, block = n # inputs_time = inputs.map {|f| File.mtime f}.max # begin # outputs_time = outputs.map {|f| File.mtime f}.min # rescue Errno::ENOENT # outputs_time = nil # end # if outputs_time == nil || # inputs_time != nil && outputs_time <= inputs_time # sleep 1 if inputs_time != nil && inputs_time.to_i == Time.now.to_i # block.call # end # end # } # end # # def tsort_each_child(node, &block) # @dep[node].each(&block) # end # include TSort # end # # def command(arg) # print arg, "\n" # system arg # end # # m = Make.new # m.rule(%w[t1]) { command 'date > t1' } # m.rule(%w[t2]) { command 'date > t2' } # m.rule(%w[t3]) { command 'date > t3' } # m.rule(%w[t4], %w[t1 t3]) { command 'cat t1 t3 > t4' } # m.rule(%w[t5], %w[t4 t2]) { command 'cat t4 t2 > t5' } # m.build('t5') # # == Bugs # # * 'tsort.rb' is wrong name because this library uses # Tarjan's algorithm for strongly connected components. # Although 'strongly_connected_components.rb' is correct but too long. # # == References # # R. E. Tarjan, "Depth First Search and Linear Graph Algorithms", # <em>SIAM Journal on Computing</em>, Vol. 1, No. 2, pp. 146-160, June 1972. # module TSort class Cyclic < StandardError end # # Returns a topologically sorted array of nodes. # The array is sorted from children to parents, i.e. # the first element has no child and the last node has no parent. # # If there is a cycle, TSort::Cyclic is raised. # def tsort result = [] tsort_each {|element| result << element} result end # # The iterator version of the #tsort method. # <tt><em>obj</em>.tsort_each</tt> is similar to <tt><em>obj</em>.tsort.each</tt>, but # modification of _obj_ during the iteration may lead to unexpected results. # # #tsort_each returns +nil+. # If there is a cycle, TSort::Cyclic is raised. # def tsort_each # :yields: node each_strongly_connected_component {|component| if component.size == 1 yield component.first else raise Cyclic.new("topological sort failed: #{component.inspect}") end } end # # Returns strongly connected components as an array of arrays of nodes. # The array is sorted from children to parents. # Each elements of the array represents a strongly connected component. # def strongly_connected_components result = [] each_strongly_connected_component {|component| result << component} result end # # The iterator version of the #strongly_connected_components method. # <tt><em>obj</em>.each_strongly_connected_component</tt> is similar to # <tt><em>obj</em>.strongly_connected_components.each</tt>, but # modification of _obj_ during the iteration may lead to unexpected results. # # # #each_strongly_connected_component returns +nil+. # def each_strongly_connected_component # :yields: nodes id_map = {} stack = [] tsort_each_node {|node| unless id_map.include? node each_strongly_connected_component_from(node, id_map, stack) {|c| yield c } end } nil end # # Iterates over strongly connected component in the subgraph reachable from # _node_. # # Return value is unspecified. # # #each_strongly_connected_component_from doesn't call #tsort_each_node. # def each_strongly_connected_component_from(node, id_map={}, stack=[]) # :yields: nodes minimum_id = node_id = id_map[node] = id_map.size stack_length = stack.length stack << node tsort_each_child(node) {|child| if id_map.include? child child_id = id_map[child] minimum_id = child_id if child_id && child_id < minimum_id else sub_minimum_id = each_strongly_connected_component_from(child, id_map, stack) {|c| yield c } minimum_id = sub_minimum_id if sub_minimum_id < minimum_id end } if node_id == minimum_id component = stack.slice!(stack_length .. -1) component.each {|n| id_map[n] = nil} yield component end minimum_id end # # Should be implemented by a extended class. # # #tsort_each_node is used to iterate for all nodes over a graph. # def tsort_each_node # :yields: node raise NotImplementedError.new end # # Should be implemented by a extended class. # # #tsort_each_child is used to iterate for child nodes of _node_. # def tsort_each_child(node) # :yields: child raise NotImplementedError.new end end if __FILE__ == $0 require 'test/unit' class TSortHash < Hash # :nodoc: include TSort alias tsort_each_node each_key def tsort_each_child(node, &block) fetch(node).each(&block) end end class TSortArray < Array # :nodoc: include TSort alias tsort_each_node each_index def tsort_each_child(node, &block) fetch(node).each(&block) end end class TSortTest < Test::Unit::TestCase # :nodoc: def test_dag h = TSortHash[{1=>[2, 3], 2=>[3], 3=>[]}] assert_equal([3, 2, 1], h.tsort) assert_equal([[3], [2], [1]], h.strongly_connected_components) end def test_cycle h = TSortHash[{1=>[2], 2=>[3, 4], 3=>[2], 4=>[]}] assert_equal([[4], [2, 3], [1]], h.strongly_connected_components.map {|nodes| nodes.sort}) assert_raise(TSort::Cyclic) { h.tsort } end def test_array a = TSortArray[[1], [0], [0], [2]] assert_equal([[0, 1], [2], [3]], a.strongly_connected_components.map {|nodes| nodes.sort}) a = TSortArray[[], [0]] assert_equal([[0], [1]], a.strongly_connected_components.map {|nodes| nodes.sort}) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/webrick.rb
tools/jruby-1.5.1/lib/ruby/1.8/webrick.rb
# # WEBrick -- WEB server toolkit. # # Author: IPR -- Internet Programming with Ruby -- writers # Copyright (c) 2000 TAKAHASHI Masayoshi, GOTOU YUUZOU # Copyright (c) 2002 Internet Programming with Ruby writers. All rights # reserved. # # $IPR: webrick.rb,v 1.12 2002/10/01 17:16:31 gotoyuzo Exp $ require 'webrick/compat.rb' require 'webrick/version.rb' require 'webrick/config.rb' require 'webrick/log.rb' require 'webrick/server.rb' require 'webrick/utils.rb' require 'webrick/accesslog' require 'webrick/htmlutils.rb' require 'webrick/httputils.rb' require 'webrick/cookie.rb' require 'webrick/httpversion.rb' require 'webrick/httpstatus.rb' require 'webrick/httprequest.rb' require 'webrick/httpresponse.rb' require 'webrick/httpserver.rb' require 'webrick/httpservlet.rb' require 'webrick/httpauth.rb'
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/ping.rb
tools/jruby-1.5.1/lib/ruby/1.8/ping.rb
# # = ping.rb: Check a host for upness # # Author:: Yukihiro Matsumoto # Documentation:: Konrad Meyer # # Performs the function of the basic network testing tool, ping. # See: Ping. # require 'timeout' require "socket" # # Ping contains routines to test for the reachability of remote hosts. # Currently the only routine implemented is pingecho(). # # Ping.pingecho uses a TCP echo (not an ICMP echo) to determine if the # remote host is reachable. This is usually adequate to tell that a remote # host is available to telnet, ftp, or ssh to. # # Warning: Ping.pingecho may block for a long time if DNS resolution is # slow. Requiring 'resolv-replace' allows non-blocking name resolution. # # Usage: # # require 'ping' # # puts "'jimmy' is alive and kicking" if Ping.pingecho('jimmy', 10) # module Ping # # Return true if we can open a connection to the hostname or IP address # +host+ on port +service+ (which defaults to the "echo" port) waiting up # to +timeout+ seconds. # # Example: # # require 'ping' # # Ping.pingecho "google.com", 10, 80 # def pingecho(host, timeout=5, service="echo") begin timeout(timeout) do s = TCPSocket.new(host, service) s.close end rescue Errno::ECONNREFUSED return true rescue Timeout::Error, StandardError return false end return true end module_function :pingecho end if $0 == __FILE__ host = ARGV[0] host ||= "localhost" printf("%s alive? - %s\n", host, Ping::pingecho(host, 5)) end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/open-uri.rb
tools/jruby-1.5.1/lib/ruby/1.8/open-uri.rb
require 'uri' require 'stringio' require 'time' module Kernel private alias open_uri_original_open open # :nodoc: # makes possible to open various resources including URIs. # If the first argument respond to `open' method, # the method is called with the rest arguments. # # If the first argument is a string which begins with xxx://, # it is parsed by URI.parse. If the parsed object respond to `open' method, # the method is called with the rest arguments. # # Otherwise original open is called. # # Since open-uri.rb provides URI::HTTP#open, URI::HTTPS#open and # URI::FTP#open, # Kernel[#.]open can accepts such URIs and strings which begins with # http://, https:// and ftp://. # In these case, the opened file object is extended by OpenURI::Meta. def open(name, *rest, &block) # :doc: if name.respond_to?(:open) name.open(*rest, &block) elsif name.respond_to?(:to_str) && %r{\A[A-Za-z][A-Za-z0-9+\-\.]*://} =~ name && (uri = URI.parse(name)).respond_to?(:open) uri.open(*rest, &block) else open_uri_original_open(name, *rest, &block) end end module_function :open end # OpenURI is an easy-to-use wrapper for net/http, net/https and net/ftp. # #== Example # # It is possible to open http/https/ftp URL as usual like opening a file: # # open("http://www.ruby-lang.org/") {|f| # f.each_line {|line| p line} # } # # The opened file has several methods for meta information as follows since # it is extended by OpenURI::Meta. # # open("http://www.ruby-lang.org/en") {|f| # f.each_line {|line| p line} # p f.base_uri # <URI::HTTP:0x40e6ef2 URL:http://www.ruby-lang.org/en/> # p f.content_type # "text/html" # p f.charset # "iso-8859-1" # p f.content_encoding # [] # p f.last_modified # Thu Dec 05 02:45:02 UTC 2002 # } # # Additional header fields can be specified by an optional hash argument. # # open("http://www.ruby-lang.org/en/", # "User-Agent" => "Ruby/#{RUBY_VERSION}", # "From" => "foo@bar.invalid", # "Referer" => "http://www.ruby-lang.org/") {|f| # # ... # } # # The environment variables such as http_proxy, https_proxy and ftp_proxy # are in effect by default. :proxy => nil disables proxy. # # open("http://www.ruby-lang.org/en/raa.html", :proxy => nil) {|f| # # ... # } # # URI objects can be opened in a similar way. # # uri = URI.parse("http://www.ruby-lang.org/en/") # uri.open {|f| # # ... # } # # URI objects can be read directly. The returned string is also extended by # OpenURI::Meta. # # str = uri.read # p str.base_uri # # Author:: Tanaka Akira <akr@m17n.org> module OpenURI Options = { :proxy => true, :progress_proc => true, :content_length_proc => true, :http_basic_authentication => true, } def OpenURI.check_options(options) # :nodoc: options.each {|k, v| next unless Symbol === k unless Options.include? k raise ArgumentError, "unrecognized option: #{k}" end } end def OpenURI.scan_open_optional_arguments(*rest) # :nodoc: if !rest.empty? && (String === rest.first || Integer === rest.first) mode = rest.shift if !rest.empty? && Integer === rest.first perm = rest.shift end end return mode, perm, rest end def OpenURI.open_uri(name, *rest) # :nodoc: uri = URI::Generic === name ? name : URI.parse(name) mode, perm, rest = OpenURI.scan_open_optional_arguments(*rest) options = rest.shift if !rest.empty? && Hash === rest.first raise ArgumentError.new("extra arguments") if !rest.empty? options ||= {} OpenURI.check_options(options) unless mode == nil || mode == 'r' || mode == 'rb' || mode == File::RDONLY raise ArgumentError.new("invalid access mode #{mode} (#{uri.class} resource is read only.)") end io = open_loop(uri, options) if block_given? begin yield io ensure io.close end else io end end def OpenURI.open_loop(uri, options) # :nodoc: case opt_proxy = options.fetch(:proxy, true) when true find_proxy = lambda {|u| u.find_proxy} when nil, false find_proxy = lambda {|u| nil} when String opt_proxy = URI.parse(opt_proxy) find_proxy = lambda {|u| opt_proxy} when URI::Generic find_proxy = lambda {|u| opt_proxy} else raise ArgumentError.new("Invalid proxy option: #{opt_proxy}") end uri_set = {} buf = nil while true redirect = catch(:open_uri_redirect) { buf = Buffer.new uri.buffer_open(buf, find_proxy.call(uri), options) nil } if redirect if redirect.relative? # Although it violates RFC2616, Location: field may have relative # URI. It is converted to absolute URI using uri as a base URI. redirect = uri + redirect end unless OpenURI.redirectable?(uri, redirect) raise "redirection forbidden: #{uri} -> #{redirect}" end if options.include? :http_basic_authentication # send authentication only for the URI directly specified. options = options.dup options.delete :http_basic_authentication end uri = redirect raise "HTTP redirection loop: #{uri}" if uri_set.include? uri.to_s uri_set[uri.to_s] = true else break end end io = buf.io io.base_uri = uri io end def OpenURI.redirectable?(uri1, uri2) # :nodoc: # This test is intended to forbid a redirection from http://... to # file:///etc/passwd. # However this is ad hoc. It should be extensible/configurable. uri1.scheme.downcase == uri2.scheme.downcase || (/\A(?:http|ftp)\z/i =~ uri1.scheme && /\A(?:http|ftp)\z/i =~ uri2.scheme) end def OpenURI.open_http(buf, target, proxy, options) # :nodoc: if proxy raise "Non-HTTP proxy URI: #{proxy}" if proxy.class != URI::HTTP end if target.userinfo && "1.9.0" <= RUBY_VERSION # don't raise for 1.8 because compatibility. raise ArgumentError, "userinfo not supported. [RFC3986]" end require 'net/http' klass = Net::HTTP if URI::HTTP === target # HTTP or HTTPS if proxy klass = Net::HTTP::Proxy(proxy.host, proxy.port) end target_host = target.host target_port = target.port request_uri = target.request_uri else # FTP over HTTP proxy target_host = proxy.host target_port = proxy.port request_uri = target.to_s end http = klass.new(target_host, target_port) if target.class == URI::HTTPS require 'net/https' http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_PEER store = OpenSSL::X509::Store.new store.set_default_paths http.cert_store = store end header = {} options.each {|k, v| header[k] = v if String === k } resp = nil http.start { req = Net::HTTP::Get.new(request_uri, header) if options.include? :http_basic_authentication user, pass = options[:http_basic_authentication] req.basic_auth user, pass end http.request(req) {|response| resp = response if options[:content_length_proc] && Net::HTTPSuccess === resp if resp.key?('Content-Length') options[:content_length_proc].call(resp['Content-Length'].to_i) else options[:content_length_proc].call(nil) end end resp.read_body {|str| buf << str if options[:progress_proc] && Net::HTTPSuccess === resp options[:progress_proc].call(buf.size) end } } } io = buf.io io.rewind io.status = [resp.code, resp.message] resp.each {|name,value| buf.io.meta_add_field name, value } case resp when Net::HTTPSuccess when Net::HTTPMovedPermanently, # 301 Net::HTTPFound, # 302 Net::HTTPSeeOther, # 303 Net::HTTPTemporaryRedirect # 307 throw :open_uri_redirect, URI.parse(resp['location']) else raise OpenURI::HTTPError.new(io.status.join(' '), io) end end class HTTPError < StandardError def initialize(message, io) super(message) @io = io end attr_reader :io end class Buffer # :nodoc: def initialize @io = StringIO.new @size = 0 end attr_reader :size StringMax = 10240 def <<(str) @io << str @size += str.length if StringIO === @io && StringMax < @size require 'tempfile' io = Tempfile.new('open-uri') io.binmode Meta.init io, @io if @io.respond_to? :meta io << @io.string @io = io end end def io Meta.init @io unless @io.respond_to? :meta @io end end # Mixin for holding meta-information. module Meta def Meta.init(obj, src=nil) # :nodoc: obj.extend Meta obj.instance_eval { @base_uri = nil @meta = {} } if src obj.status = src.status obj.base_uri = src.base_uri src.meta.each {|name, value| obj.meta_add_field(name, value) } end end # returns an Array which consists status code and message. attr_accessor :status # returns a URI which is base of relative URIs in the data. # It may differ from the URI supplied by a user because redirection. attr_accessor :base_uri # returns a Hash which represents header fields. # The Hash keys are downcased for canonicalization. attr_reader :meta def meta_add_field(name, value) # :nodoc: @meta[name.downcase] = value end # returns a Time which represents Last-Modified field. def last_modified if v = @meta['last-modified'] Time.httpdate(v) else nil end end RE_LWS = /[\r\n\t ]+/n RE_TOKEN = %r{[^\x00- ()<>@,;:\\"/\[\]?={}\x7f]+}n RE_QUOTED_STRING = %r{"(?:[\r\n\t !#-\[\]-~\x80-\xff]|\\[\x00-\x7f])*"}n RE_PARAMETERS = %r{(?:;#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?=#{RE_LWS}?(?:#{RE_TOKEN}|#{RE_QUOTED_STRING})#{RE_LWS}?)*}n def content_type_parse # :nodoc: v = @meta['content-type'] # The last (?:;#{RE_LWS}?)? matches extra ";" which violates RFC2045. if v && %r{\A#{RE_LWS}?(#{RE_TOKEN})#{RE_LWS}?/(#{RE_TOKEN})#{RE_LWS}?(#{RE_PARAMETERS})(?:;#{RE_LWS}?)?\z}no =~ v type = $1.downcase subtype = $2.downcase parameters = [] $3.scan(/;#{RE_LWS}?(#{RE_TOKEN})#{RE_LWS}?=#{RE_LWS}?(?:(#{RE_TOKEN})|(#{RE_QUOTED_STRING}))/no) {|att, val, qval| val = qval.gsub(/[\r\n\t !#-\[\]-~\x80-\xff]+|(\\[\x00-\x7f])/) { $1 ? $1[1,1] : $& } if qval parameters << [att.downcase, val] } ["#{type}/#{subtype}", *parameters] else nil end end # returns "type/subtype" which is MIME Content-Type. # It is downcased for canonicalization. # Content-Type parameters are stripped. def content_type type, *parameters = content_type_parse type || 'application/octet-stream' end # returns a charset parameter in Content-Type field. # It is downcased for canonicalization. # # If charset parameter is not given but a block is given, # the block is called and its result is returned. # It can be used to guess charset. # # If charset parameter and block is not given, # nil is returned except text type in HTTP. # In that case, "iso-8859-1" is returned as defined by RFC2616 3.7.1. def charset type, *parameters = content_type_parse if pair = parameters.assoc('charset') pair.last.downcase elsif block_given? yield elsif type && %r{\Atext/} =~ type && @base_uri && /\Ahttp\z/i =~ @base_uri.scheme "iso-8859-1" # RFC2616 3.7.1 else nil end end # returns a list of encodings in Content-Encoding field # as an Array of String. # The encodings are downcased for canonicalization. def content_encoding v = @meta['content-encoding'] if v && %r{\A#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?(?:,#{RE_LWS}?#{RE_TOKEN}#{RE_LWS}?)*}o =~ v v.scan(RE_TOKEN).map {|content_coding| content_coding.downcase} else [] end end end # Mixin for HTTP and FTP URIs. module OpenRead # OpenURI::OpenRead#open provides `open' for URI::HTTP and URI::FTP. # # OpenURI::OpenRead#open takes optional 3 arguments as: # OpenURI::OpenRead#open([mode [, perm]] [, options]) [{|io| ... }] # # `mode', `perm' is same as Kernel#open. # # However, `mode' must be read mode because OpenURI::OpenRead#open doesn't # support write mode (yet). # Also `perm' is just ignored because it is meaningful only for file # creation. # # `options' must be a hash. # # Each pairs which key is a string in the hash specify a extra header # field for HTTP. # I.e. it is ignored for FTP without HTTP proxy. # # The hash may include other options which key is a symbol: # # [:proxy] # Synopsis: # :proxy => "http://proxy.foo.com:8000/" # :proxy => URI.parse("http://proxy.foo.com:8000/") # :proxy => true # :proxy => false # :proxy => nil # # If :proxy option is specified, the value should be String, URI, # boolean or nil. # When String or URI is given, it is treated as proxy URI. # When true is given or the option itself is not specified, # environment variable `scheme_proxy' is examined. # `scheme' is replaced by `http', `https' or `ftp'. # When false or nil is given, the environment variables are ignored and # connection will be made to a server directly. # # [:http_basic_authentication] # Synopsis: # :http_basic_authentication=>[user, password] # # If :http_basic_authentication is specified, # the value should be an array which contains 2 strings: # username and password. # It is used for HTTP Basic authentication defined by RFC 2617. # # [:content_length_proc] # Synopsis: # :content_length_proc => lambda {|content_length| ... } # # If :content_length_proc option is specified, the option value procedure # is called before actual transfer is started. # It takes one argument which is expected content length in bytes. # # If two or more transfer is done by HTTP redirection, the procedure # is called only one for a last transfer. # # When expected content length is unknown, the procedure is called with # nil. # It is happen when HTTP response has no Content-Length header. # # [:progress_proc] # Synopsis: # :progress_proc => lambda {|size| ...} # # If :progress_proc option is specified, the proc is called with one # argument each time when `open' gets content fragment from network. # The argument `size' `size' is a accumulated transfered size in bytes. # # If two or more transfer is done by HTTP redirection, the procedure # is called only one for a last transfer. # # :progress_proc and :content_length_proc are intended to be used for # progress bar. # For example, it can be implemented as follows using Ruby/ProgressBar. # # pbar = nil # open("http://...", # :content_length_proc => lambda {|t| # if t && 0 < t # pbar = ProgressBar.new("...", t) # pbar.file_transfer_mode # end # }, # :progress_proc => lambda {|s| # pbar.set s if pbar # }) {|f| ... } # # OpenURI::OpenRead#open returns an IO like object if block is not given. # Otherwise it yields the IO object and return the value of the block. # The IO object is extended with OpenURI::Meta. def open(*rest, &block) OpenURI.open_uri(self, *rest, &block) end # OpenURI::OpenRead#read([options]) reads a content referenced by self and # returns the content as string. # The string is extended with OpenURI::Meta. # The argument `options' is same as OpenURI::OpenRead#open. def read(options={}) self.open(options) {|f| str = f.read Meta.init str, f str } end end end module URI class Generic # returns a proxy URI. # The proxy URI is obtained from environment variables such as http_proxy, # ftp_proxy, no_proxy, etc. # If there is no proper proxy, nil is returned. # # Note that capitalized variables (HTTP_PROXY, FTP_PROXY, NO_PROXY, etc.) # are examined too. # # But http_proxy and HTTP_PROXY is treated specially under CGI environment. # It's because HTTP_PROXY may be set by Proxy: header. # So HTTP_PROXY is not used. # http_proxy is not used too if the variable is case insensitive. # CGI_HTTP_PROXY can be used instead. def find_proxy name = self.scheme.downcase + '_proxy' proxy_uri = nil if name == 'http_proxy' && ENV.include?('REQUEST_METHOD') # CGI? # HTTP_PROXY conflicts with *_proxy for proxy settings and # HTTP_* for header information in CGI. # So it should be careful to use it. pairs = ENV.reject {|k, v| /\Ahttp_proxy\z/i !~ k } case pairs.length when 0 # no proxy setting anyway. proxy_uri = nil when 1 k, v = pairs.shift if k == 'http_proxy' && ENV[k.upcase] == nil # http_proxy is safe to use because ENV is case sensitive. proxy_uri = ENV[name] else proxy_uri = nil end else # http_proxy is safe to use because ENV is case sensitive. proxy_uri = ENV.to_hash[name] end if !proxy_uri # Use CGI_HTTP_PROXY. cf. libwww-perl. proxy_uri = ENV["CGI_#{name.upcase}"] end elsif name == 'http_proxy' unless proxy_uri = ENV[name] if proxy_uri = ENV[name.upcase] warn 'The environment variable HTTP_PROXY is discouraged. Use http_proxy.' end end else proxy_uri = ENV[name] || ENV[name.upcase] end if proxy_uri && self.host require 'socket' begin addr = IPSocket.getaddress(self.host) proxy_uri = nil if /\A127\.|\A::1\z/ =~ addr rescue SocketError end end if proxy_uri proxy_uri = URI.parse(proxy_uri) name = 'no_proxy' if no_proxy = ENV[name] || ENV[name.upcase] no_proxy.scan(/([^:,]*)(?::(\d+))?/) {|host, port| if /(\A|\.)#{Regexp.quote host}\z/i =~ self.host && (!port || self.port == port.to_i) proxy_uri = nil break end } end proxy_uri else nil end end end class HTTP def buffer_open(buf, proxy, options) # :nodoc: OpenURI.open_http(buf, self, proxy, options) end include OpenURI::OpenRead end class FTP def buffer_open(buf, proxy, options) # :nodoc: if proxy OpenURI.open_http(buf, self, proxy, options) return end require 'net/ftp' directories = self.path.split(%r{/}, -1) directories.shift if directories[0] == '' # strip a field before leading slash directories.each {|d| d.gsub!(/%([0-9A-Fa-f][0-9A-Fa-f])/) { [$1].pack("H2") } } unless filename = directories.pop raise ArgumentError, "no filename: #{self.inspect}" end directories.each {|d| if /[\r\n]/ =~ d raise ArgumentError, "invalid directory: #{d.inspect}" end } if /[\r\n]/ =~ filename raise ArgumentError, "invalid filename: #{filename.inspect}" end typecode = self.typecode if typecode && /\A[aid]\z/ !~ typecode raise ArgumentError, "invalid typecode: #{typecode.inspect}" end # The access sequence is defined by RFC 1738 ftp = Net::FTP.open(self.host) # todo: extract user/passwd from .netrc. user = 'anonymous' passwd = nil user, passwd = self.userinfo.split(/:/) if self.userinfo ftp.login(user, passwd) directories.each {|cwd| ftp.voidcmd("CWD #{cwd}") } if typecode # xxx: typecode D is not handled. ftp.voidcmd("TYPE #{typecode.upcase}") end if options[:content_length_proc] options[:content_length_proc].call(ftp.size(filename)) end ftp.retrbinary("RETR #{filename}", 4096) { |str| buf << str options[:progress_proc].call(buf.size) if options[:progress_proc] } ftp.close buf.io.rewind end include OpenURI::OpenRead end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/getoptlong.rb
tools/jruby-1.5.1/lib/ruby/1.8/getoptlong.rb
# # GetoptLong for Ruby # # Copyright (C) 1998, 1999, 2000 Motoyuki Kasahara. # # You may redistribute and/or modify this library under the same license # terms as Ruby. # # See GetoptLong for documentation. # # Additional documents and the latest version of `getoptlong.rb' can be # found at http://www.sra.co.jp/people/m-kasahr/ruby/getoptlong/ # The GetoptLong class allows you to parse command line options similarly to # the GNU getopt_long() C library call. Note, however, that GetoptLong is a # pure Ruby implementation. # # GetoptLong allows for POSIX-style options like <tt>--file</tt> as well # as single letter options like <tt>-f</tt> # # The empty option <tt>--</tt> (two minus symbols) is used to end option # processing. This can be particularly important if options have optional # arguments. # # Here is a simple example of usage: # # # == Synopsis # # # # hello: greets user, demonstrates command line parsing # # # # == Usage # # # # hello [OPTION] ... DIR # # # # -h, --help: # # show help # # # # --repeat x, -n x: # # repeat x times # # # # --name [name]: # # greet user by name, if name not supplied default is John # # # # DIR: The directory in which to issue the greeting. # # require 'getoptlong' # require 'rdoc/usage' # # opts = GetoptLong.new( # [ '--help', '-h', GetoptLong::NO_ARGUMENT ], # [ '--repeat', '-n', GetoptLong::REQUIRED_ARGUMENT ], # [ '--name', GetoptLong::OPTIONAL_ARGUMENT ] # ) # # dir = nil # name = nil # repetitions = 1 # opts.each do |opt, arg| # case opt # when '--help' # RDoc::usage # when '--repeat' # repetitions = arg.to_i # when '--name' # if arg == '' # name = 'John' # else # name = arg # end # end # end # # if ARGV.length != 1 # puts "Missing dir argument (try --help)" # exit 0 # end # # dir = ARGV.shift # # Dir.chdir(dir) # for i in (1..repetitions) # print "Hello" # if name # print ", #{name}" # end # puts # end # # Example command line: # # hello -n 6 --name -- /tmp # class GetoptLong # # Orderings. # ORDERINGS = [REQUIRE_ORDER = 0, PERMUTE = 1, RETURN_IN_ORDER = 2] # # Argument flags. # ARGUMENT_FLAGS = [NO_ARGUMENT = 0, REQUIRED_ARGUMENT = 1, OPTIONAL_ARGUMENT = 2] # # Status codes. # STATUS_YET, STATUS_STARTED, STATUS_TERMINATED = 0, 1, 2 # # Error types. # class Error < StandardError; end class AmbigousOption < Error; end class NeedlessArgument < Error; end class MissingArgument < Error; end class InvalidOption < Error; end # # Set up option processing. # # The options to support are passed to new() as an array of arrays. # Each sub-array contains any number of String option names which carry # the same meaning, and one of the following flags: # # GetoptLong::NO_ARGUMENT :: Option does not take an argument. # # GetoptLong::REQUIRED_ARGUMENT :: Option always takes an argument. # # GetoptLong::OPTIONAL_ARGUMENT :: Option may or may not take an argument. # # The first option name is considered to be the preferred (canonical) name. # Other than that, the elements of each sub-array can be in any order. # def initialize(*arguments) # # Current ordering. # if ENV.include?('POSIXLY_CORRECT') @ordering = REQUIRE_ORDER else @ordering = PERMUTE end # # Hash table of option names. # Keys of the table are option names, and their values are canonical # names of the options. # @canonical_names = Hash.new # # Hash table of argument flags. # Keys of the table are option names, and their values are argument # flags of the options. # @argument_flags = Hash.new # # Whether error messages are output to $deferr. # @quiet = FALSE # # Status code. # @status = STATUS_YET # # Error code. # @error = nil # # Error message. # @error_message = nil # # Rest of catenated short options. # @rest_singles = '' # # List of non-option-arguments. # Append them to ARGV when option processing is terminated. # @non_option_arguments = Array.new if 0 < arguments.length set_options(*arguments) end end # # Set the handling of the ordering of options and arguments. # A RuntimeError is raised if option processing has already started. # # The supplied value must be a member of GetoptLong::ORDERINGS. It alters # the processing of options as follows: # # <b>REQUIRE_ORDER</b> : # # Options are required to occur before non-options. # # Processing of options ends as soon as a word is encountered that has not # been preceded by an appropriate option flag. # # For example, if -a and -b are options which do not take arguments, # parsing command line arguments of '-a one -b two' would result in # 'one', '-b', 'two' being left in ARGV, and only ('-a', '') being # processed as an option/arg pair. # # This is the default ordering, if the environment variable # POSIXLY_CORRECT is set. (This is for compatibility with GNU getopt_long.) # # <b>PERMUTE</b> : # # Options can occur anywhere in the command line parsed. This is the # default behavior. # # Every sequence of words which can be interpreted as an option (with or # without argument) is treated as an option; non-option words are skipped. # # For example, if -a does not require an argument and -b optionally takes # an argument, parsing '-a one -b two three' would result in ('-a','') and # ('-b', 'two') being processed as option/arg pairs, and 'one','three' # being left in ARGV. # # If the ordering is set to PERMUTE but the environment variable # POSIXLY_CORRECT is set, REQUIRE_ORDER is used instead. This is for # compatibility with GNU getopt_long. # # <b>RETURN_IN_ORDER</b> : # # All words on the command line are processed as options. Words not # preceded by a short or long option flag are passed as arguments # with an option of '' (empty string). # # For example, if -a requires an argument but -b does not, a command line # of '-a one -b two three' would result in option/arg pairs of ('-a', 'one') # ('-b', ''), ('', 'two'), ('', 'three') being processed. # def ordering=(ordering) # # The method is failed if option processing has already started. # if @status != STATUS_YET set_error(ArgumentError, "argument error") raise RuntimeError, "invoke ordering=, but option processing has already started" end # # Check ordering. # if !ORDERINGS.include?(ordering) raise ArgumentError, "invalid ordering `#{ordering}'" end if ordering == PERMUTE && ENV.include?('POSIXLY_CORRECT') @ordering = REQUIRE_ORDER else @ordering = ordering end end # # Return ordering. # attr_reader :ordering # # Set options. Takes the same argument as GetoptLong.new. # # Raises a RuntimeError if option processing has already started. # def set_options(*arguments) # # The method is failed if option processing has already started. # if @status != STATUS_YET raise RuntimeError, "invoke set_options, but option processing has already started" end # # Clear tables of option names and argument flags. # @canonical_names.clear @argument_flags.clear arguments.each do |arg| # # Each argument must be an Array. # if !arg.is_a?(Array) raise ArgumentError, "the option list contains non-Array argument" end # # Find an argument flag and it set to `argument_flag'. # argument_flag = nil arg.each do |i| if ARGUMENT_FLAGS.include?(i) if argument_flag != nil raise ArgumentError, "too many argument-flags" end argument_flag = i end end raise ArgumentError, "no argument-flag" if argument_flag == nil canonical_name = nil arg.each do |i| # # Check an option name. # next if i == argument_flag begin if !i.is_a?(String) || i !~ /^-([^-]|-.+)$/ raise ArgumentError, "an invalid option `#{i}'" end if (@canonical_names.include?(i)) raise ArgumentError, "option redefined `#{i}'" end rescue @canonical_names.clear @argument_flags.clear raise end # # Register the option (`i') to the `@canonical_names' and # `@canonical_names' Hashes. # if canonical_name == nil canonical_name = i end @canonical_names[i] = canonical_name @argument_flags[i] = argument_flag end raise ArgumentError, "no option name" if canonical_name == nil end return self end # # Set/Unset `quiet' mode. # attr_writer :quiet # # Return the flag of `quiet' mode. # attr_reader :quiet # # `quiet?' is an alias of `quiet'. # alias quiet? quiet # # Explicitly terminate option processing. # def terminate return nil if @status == STATUS_TERMINATED raise RuntimeError, "an error has occured" if @error != nil @status = STATUS_TERMINATED @non_option_arguments.reverse_each do |argument| ARGV.unshift(argument) end @canonical_names = nil @argument_flags = nil @rest_singles = nil @non_option_arguments = nil return self end # # Returns true if option processing has terminated, false otherwise. # def terminated? return @status == STATUS_TERMINATED end # # Set an error (protected). # def set_error(type, message) $deferr.print("#{$0}: #{message}\n") if !@quiet @error = type @error_message = message @canonical_names = nil @argument_flags = nil @rest_singles = nil @non_option_arguments = nil raise type, message end protected :set_error # # Examine whether an option processing is failed. # attr_reader :error # # `error?' is an alias of `error'. # alias error? error # Return the appropriate error message in POSIX-defined format. # If no error has occurred, returns nil. # def error_message return @error_message end # # Get next option name and its argument, as an Array of two elements. # # The option name is always converted to the first (preferred) # name given in the original options to GetoptLong.new. # # Example: ['--option', 'value'] # # Returns nil if the processing is complete (as determined by # STATUS_TERMINATED). # def get option_name, option_argument = nil, '' # # Check status. # return nil if @error != nil case @status when STATUS_YET @status = STATUS_STARTED when STATUS_TERMINATED return nil end # # Get next option argument. # if 0 < @rest_singles.length argument = '-' + @rest_singles elsif (ARGV.length == 0) terminate return nil elsif @ordering == PERMUTE while 0 < ARGV.length && ARGV[0] !~ /^-./ @non_option_arguments.push(ARGV.shift) end if ARGV.length == 0 terminate return nil end argument = ARGV.shift elsif @ordering == REQUIRE_ORDER if (ARGV[0] !~ /^-./) terminate return nil end argument = ARGV.shift else argument = ARGV.shift end # # Check the special argument `--'. # `--' indicates the end of the option list. # if argument == '--' && @rest_singles.length == 0 terminate return nil end # # Check for long and short options. # if argument =~ /^(--[^=]+)/ && @rest_singles.length == 0 # # This is a long style option, which start with `--'. # pattern = $1 if @canonical_names.include?(pattern) option_name = pattern else # # The option `option_name' is not registered in `@canonical_names'. # It may be an abbreviated. # match_count = 0 @canonical_names.each_key do |key| if key.index(pattern) == 0 option_name = key match_count += 1 end end if 2 <= match_count set_error(AmbigousOption, "option `#{argument}' is ambiguous") elsif match_count == 0 set_error(InvalidOption, "unrecognized option `#{argument}'") end end # # Check an argument to the option. # if @argument_flags[option_name] == REQUIRED_ARGUMENT if argument =~ /=(.*)$/ option_argument = $1 elsif 0 < ARGV.length option_argument = ARGV.shift else set_error(MissingArgument, "option `#{argument}' requires an argument") end elsif @argument_flags[option_name] == OPTIONAL_ARGUMENT if argument =~ /=(.*)$/ option_argument = $1 elsif 0 < ARGV.length && ARGV[0] !~ /^-./ option_argument = ARGV.shift else option_argument = '' end elsif argument =~ /=(.*)$/ set_error(NeedlessArgument, "option `#{option_name}' doesn't allow an argument") end elsif argument =~ /^(-(.))(.*)/ # # This is a short style option, which start with `-' (not `--'). # Short options may be catenated (e.g. `-l -g' is equivalent to # `-lg'). # option_name, ch, @rest_singles = $1, $2, $3 if @canonical_names.include?(option_name) # # The option `option_name' is found in `@canonical_names'. # Check its argument. # if @argument_flags[option_name] == REQUIRED_ARGUMENT if 0 < @rest_singles.length option_argument = @rest_singles @rest_singles = '' elsif 0 < ARGV.length option_argument = ARGV.shift else # 1003.2 specifies the format of this message. set_error(MissingArgument, "option requires an argument -- #{ch}") end elsif @argument_flags[option_name] == OPTIONAL_ARGUMENT if 0 < @rest_singles.length option_argument = @rest_singles @rest_singles = '' elsif 0 < ARGV.length && ARGV[0] !~ /^-./ option_argument = ARGV.shift else option_argument = '' end end else # # This is an invalid option. # 1003.2 specifies the format of this message. # if ENV.include?('POSIXLY_CORRECT') set_error(InvalidOption, "illegal option -- #{ch}") else set_error(InvalidOption, "invalid option -- #{ch}") end end else # # This is a non-option argument. # Only RETURN_IN_ORDER falled into here. # return '', argument end return @canonical_names[option_name], option_argument end # # `get_option' is an alias of `get'. # alias get_option get # Iterator version of `get'. # # The block is called repeatedly with two arguments: # The first is the option name. # The second is the argument which followed it (if any). # Example: ('--opt', 'value') # # The option name is always converted to the first (preferred) # name given in the original options to GetoptLong.new. # def each loop do option_name, option_argument = get_option break if option_name == nil yield option_name, option_argument end end # # `each_option' is an alias of `each'. # alias each_option each end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/thread.rb
tools/jruby-1.5.1/lib/ruby/1.8/thread.rb
# # NOTE: # This file is overwritten by ext/thread/lib/thread.rb unless ruby # is configured with --disable-fastthread. # # thread.rb - thread support classes # $Date$ # by Yukihiro Matsumoto <matz@netlab.co.jp> # # Copyright (C) 2001 Yukihiro Matsumoto # Copyright (C) 2000 Network Applied Communication Laboratory, Inc. # Copyright (C) 2000 Information-technology Promotion Agency, Japan # unless defined? Thread fail "Thread not available for this ruby interpreter" end class Thread # # Wraps a block in Thread.critical, restoring the original value upon exit # from the critical section. # def Thread.exclusive _old = Thread.critical begin Thread.critical = true return yield ensure Thread.critical = _old end end end # # Mutex implements a simple semaphore that can be used to coordinate access to # shared data from multiple concurrent threads. # # Example: # # require 'thread' # semaphore = Mutex.new # # a = Thread.new { # semaphore.synchronize { # # access shared resource # } # } # # b = Thread.new { # semaphore.synchronize { # # access shared resource # } # } # class Mutex # # Creates a new Mutex # def initialize @waiting = [] @locked = false; @waiting.taint # enable tainted comunication self.taint end # # Returns +true+ if this lock is currently held by some thread. # def locked? @locked end # # Attempts to obtain the lock and returns immediately. Returns +true+ if the # lock was granted. # def try_lock result = false Thread.critical = true unless @locked @locked = true result = true end Thread.critical = false result end # # Attempts to grab the lock and waits if it isn't available. # def lock while (Thread.critical = true; @locked) @waiting.push Thread.current Thread.stop end @locked = true Thread.critical = false self end # # Releases the lock. Returns +nil+ if ref wasn't locked. # def unlock return unless @locked Thread.critical = true @locked = false begin t = @waiting.shift t.wakeup if t rescue ThreadError retry end Thread.critical = false begin t.run if t rescue ThreadError end self end # # Obtains a lock, runs the block, and releases the lock when the block # completes. See the example under Mutex. # def synchronize lock begin yield ensure unlock end end # # If the mutex is locked, unlocks the mutex, wakes one waiting thread, and # yields in a critical section. # def exclusive_unlock return unless @locked Thread.exclusive do @locked = false begin t = @waiting.shift t.wakeup if t rescue ThreadError retry end yield end self end end # # ConditionVariable objects augment class Mutex. Using condition variables, # it is possible to suspend while in the middle of a critical section until a # resource becomes available. # # Example: # # require 'thread' # # mutex = Mutex.new # resource = ConditionVariable.new # # a = Thread.new { # mutex.synchronize { # # Thread 'a' now needs the resource # resource.wait(mutex) # # 'a' can now have the resource # } # } # # b = Thread.new { # mutex.synchronize { # # Thread 'b' has finished using the resource # resource.signal # } # } # class ConditionVariable # # Creates a new ConditionVariable # def initialize @waiters = [] end # # Releases the lock held in +mutex+ and waits; reacquires the lock on wakeup. # def wait(mutex) begin mutex.exclusive_unlock do @waiters.push(Thread.current) Thread.stop end self ensure mutex.lock end end # # Wakes up the first thread in line waiting for this lock. # def signal begin t = @waiters.shift t.run if t self rescue ThreadError retry end end # # Wakes up all threads waiting for this lock. # def broadcast waiters0 = nil Thread.exclusive do waiters0 = @waiters.dup @waiters.clear end for t in waiters0 begin t.run rescue ThreadError end end self end end # # This class provides a way to synchronize communication between threads. # # Example: # # require 'thread' # # queue = Queue.new # # producer = Thread.new do # 5.times do |i| # sleep rand(i) # simulate expense # queue << i # puts "#{i} produced" # end # end # # consumer = Thread.new do # 5.times do |i| # value = queue.pop # sleep rand(i/2) # simulate expense # puts "consumed #{value}" # end # end # # consumer.join # class Queue # # Creates a new queue. # def initialize @que = [] @waiting = [] @que.taint # enable tainted comunication @waiting.taint self.taint end # # Pushes +obj+ to the queue. # def push(obj) Thread.critical = true @que.push obj begin t = @waiting.shift t.wakeup if t rescue ThreadError retry ensure Thread.critical = false end begin t.run if t rescue ThreadError end end # # Alias of push # alias << push # # Alias of push # alias enq push # # Retrieves data from the queue. If the queue is empty, the calling thread is # suspended until data is pushed onto the queue. If +non_block+ is true, the # thread isn't suspended, and an exception is raised. # def pop(non_block=false) while (Thread.critical = true; @que.empty?) raise ThreadError, "queue empty" if non_block @waiting.push Thread.current Thread.stop end @que.shift ensure Thread.critical = false end # # Alias of pop # alias shift pop # # Alias of pop # alias deq pop # # Returns +true+ is the queue is empty. # def empty? @que.empty? end # # Removes all objects from the queue. # def clear @que.clear end # # Returns the length of the queue. # def length @que.length end # # Alias of length. # alias size length # # Returns the number of threads waiting on the queue. # def num_waiting @waiting.size end end # # This class represents queues of specified size capacity. The push operation # may be blocked if the capacity is full. # # See Queue for an example of how a SizedQueue works. # class SizedQueue<Queue # # Creates a fixed-length queue with a maximum size of +max+. # def initialize(max) raise ArgumentError, "queue size must be positive" unless max > 0 @max = max @queue_wait = [] @queue_wait.taint # enable tainted comunication super() end # # Returns the maximum size of the queue. # def max @max end # # Sets the maximum size of the queue. # def max=(max) Thread.critical = true if max <= @max @max = max Thread.critical = false else diff = max - @max @max = max Thread.critical = false diff.times do begin t = @queue_wait.shift t.run if t rescue ThreadError retry end end end max end # # Pushes +obj+ to the queue. If there is no space left in the queue, waits # until space becomes available. # def push(obj) Thread.critical = true while @que.length >= @max @queue_wait.push Thread.current Thread.stop Thread.critical = true end super end # # Alias of push # alias << push # # Alias of push # alias enq push # # Retrieves data from the queue and runs a waiting thread, if any. # def pop(*args) retval = super Thread.critical = true if @que.length < @max begin t = @queue_wait.shift t.wakeup if t rescue ThreadError retry ensure Thread.critical = false end begin t.run if t rescue ThreadError end end retval end # # Alias of pop # alias shift pop # # Alias of pop # alias deq pop # # Returns the number of threads waiting on the queue. # def num_waiting @waiting.size + @queue_wait.size end end # Documentation comments: # - How do you make RDoc inherit documentation from superclass?
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/securerandom.rb
tools/jruby-1.5.1/lib/ruby/1.8/securerandom.rb
# = Secure random number generator interface. # # This library is an interface for secure random number generator which is # suitable for generating session key in HTTP cookies, etc. # # It supports following secure random number generators. # # * openssl # * /dev/urandom # # == Example # # # random hexadecimal string. # p SecureRandom.hex(10) #=> "52750b30ffbc7de3b362" # p SecureRandom.hex(10) #=> "92b15d6c8dc4beb5f559" # p SecureRandom.hex(11) #=> "6aca1b5c58e4863e6b81b8" # p SecureRandom.hex(12) #=> "94b2fff3e7fd9b9c391a2306" # p SecureRandom.hex(13) #=> "39b290146bea6ce975c37cfc23" # ... # # # random base64 string. # p SecureRandom.base64(10) #=> "EcmTPZwWRAozdA==" # p SecureRandom.base64(10) #=> "9b0nsevdwNuM/w==" # p SecureRandom.base64(10) #=> "KO1nIU+p9DKxGg==" # p SecureRandom.base64(11) #=> "l7XEiFja+8EKEtY=" # p SecureRandom.base64(12) #=> "7kJSM/MzBJI+75j8" # p SecureRandom.base64(13) #=> "vKLJ0tXBHqQOuIcSIg==" # ... # # # random binary string. # p SecureRandom.random_bytes(10) #=> "\016\t{\370g\310pbr\301" # p SecureRandom.random_bytes(10) #=> "\323U\030TO\234\357\020\a\337" # ... begin require 'openssl' rescue LoadError end module SecureRandom # SecureRandom.random_bytes generates a random binary string. # # The argument n specifies the length of the result string. # # If n is not specified, 16 is assumed. # It may be larger in future. # # If secure random number generator is not available, # NotImplementedError is raised. def self.random_bytes(n=nil) n ||= 16 if defined? OpenSSL::Random return OpenSSL::Random.random_bytes(n) end if !defined?(@has_urandom) || @has_urandom @has_urandom = false flags = File::RDONLY flags |= File::NONBLOCK if defined? File::NONBLOCK flags |= File::NOCTTY if defined? File::NOCTTY flags |= File::NOFOLLOW if defined? File::NOFOLLOW begin File.open("/dev/urandom", flags) {|f| unless f.stat.chardev? raise Errno::ENOENT end @has_urandom = true ret = f.readpartial(n) if ret.length != n raise NotImplementedError, "Unexpected partial read from random device" end return ret } rescue Errno::ENOENT raise NotImplementedError, "No random device" end end raise NotImplementedError, "No random device" end # SecureRandom.hex generates a random hex string. # # The argument n specifies the length of the random length. # The length of the result string is twice of n. # # If n is not specified, 16 is assumed. # It may be larger in future. # # If secure random number generator is not available, # NotImplementedError is raised. def self.hex(n=nil) random_bytes(n).unpack("H*")[0] end # SecureRandom.base64 generates a random base64 string. # # The argument n specifies the length of the random length. # The length of the result string is about 4/3 of n. # # If n is not specified, 16 is assumed. # It may be larger in future. # # If secure random number generator is not available, # NotImplementedError is raised. def self.base64(n=nil) [random_bytes(n)].pack("m*").delete("\n") end # SecureRandom.random_number generates a random number. # # If an positive integer is given as n, # SecureRandom.random_number returns an integer: # 0 <= SecureRandom.random_number(n) < n. # # If 0 is given or an argument is not given, # SecureRandom.random_number returns an float: # 0.0 <= SecureRandom.random_number() < 1.0. def self.random_number(n=0) if 0 < n hex = n.to_s(16) hex = '0' + hex if (hex.length & 1) == 1 bin = [hex].pack("H*") mask = bin[0] mask |= mask >> 1 mask |= mask >> 2 mask |= mask >> 4 begin rnd = SecureRandom.random_bytes(bin.length) rnd[0] = (rnd[0] & mask).chr end until rnd < bin rnd.unpack("H*")[0].hex else # assumption: Float::MANT_DIG <= 64 i64 = SecureRandom.random_bytes(8).unpack("Q")[0] Math.ldexp(i64 >> (64-Float::MANT_DIG), -Float::MANT_DIG) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/mailread.rb
tools/jruby-1.5.1/lib/ruby/1.8/mailread.rb
# The Mail class represents an internet mail message (as per RFC822, RFC2822) # with headers and a body. class Mail # Create a new Mail where +f+ is either a stream which responds to gets(), # or a path to a file. If +f+ is a path it will be opened. # # The whole message is read so it can be made available through the #header, # #[] and #body methods. # # The "From " line is ignored if the mail is in mbox format. def initialize(f) unless defined? f.gets f = open(f, "r") opened = true end @header = {} @body = [] begin while line = f.gets() line.chop! next if /^From /=~line # skip From-line break if /^$/=~line # end of header if /^(\S+?):\s*(.*)/=~line (attr = $1).capitalize! @header[attr] = $2 elsif attr line.sub!(/^\s*/, '') @header[attr] += "\n" + line end end return unless line while line = f.gets() break if /^From /=~line @body.push(line) end ensure f.close if opened end end # Return the headers as a Hash. def header return @header end # Return the message body as an Array of lines def body return @body end # Return the header corresponding to +field+. # # Matching is case-insensitive. def [](field) @header[field.capitalize] end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/dl.rb
tools/jruby-1.5.1/lib/ruby/1.8/dl.rb
warn "DL: This is only a partial implementation, and it's likely broken" require 'ffi' module DL TypeMap = { '0' => :void, 'C' => :char, 'H' => :short, 'I' => :int, 'L' => :long, 'F' => :float, 'D' => :double, 'S' => :string, 's' => :pointer, 'p' => :pointer, 'P' => :pointer, 'c' => :pointer, 'h' => :pointer, 'i' => :pointer, 'l' => :pointer, 'f' => :pointer, 'd' => :pointer, } Char2TypeName = { '0' => 'void', 'C' => 'char', 'H' => 'short', 'I' => 'int', 'L' => 'long', 'F' => 'float', 'D' => 'double', 'S' => 'const char *', 's' => 'char *', 'p' => 'void *', 'P' => 'void *', 'c' => 'char *', 'h' => 'short *', 'i' => 'int *', 'l' => 'long *', 'f' => 'float *', 'd' => 'double *', 'A' => '[]', 'a' => '[]', } FFITypes = { 'c' => FFI::Type::INT8, 'h' => FFI::Type::INT16, 'i' => FFI::Type::INT32, 'l' => FFI::Type::LONG, 'f' => FFI::Type::FLOAT32, 'd' => FFI::Type::FLOAT64, 'p' => FFI::Type::POINTER, 's' => FFI::Type::STRING, } RTLD_LAZY = FFI::DynamicLibrary::RTLD_LAZY RTLD_GLOBAL = FFI::DynamicLibrary::RTLD_GLOBAL RTLD_NOW = FFI::DynamicLibrary::RTLD_NOW class DLError < StandardError end class DLTypeError < DLError end def self.find_type(type) ffi_type = TypeMap[type] raise DLTypeError.new("Unknown type '#{type}'") unless ffi_type FFI.find_type(ffi_type) end def self.align(offset, align) mask = align - 1; off = offset; ((off & mask) != 0) ? (off & ~mask) + align : off end def self.sizeof(type) type = type.split(//) i = 0 size = 0 while i < type.length t = type[i] i += 1 count = String.new while i < type.length && type[i] =~ /[0123456789]/ count << type[i] i += 1 end n = count.empty? ? 1 : count.to_i ffi_type = FFITypes[t.downcase] raise DLTypeError.new("unexpected type '#{t}'") unless ffi_type if t.upcase == t size = align(size, ffi_type.alignment) + n * ffi_type.size else size += n * ffi_type.size end end size end class Handle def initialize(libname, flags = RTLD_LAZY | RTLD_GLOBAL) @lib = FFI::DynamicLibrary.open(libname, flags) raise RuntimeError, "Could not open #{libname}" unless @lib @open = true begin yield(self) ensure self.close end if block_given? end def close raise "Closing #{self} not allowed" unless @enable_close @open = false end def sym(func, prototype = "0") raise "Closed handle" unless @open address = @lib.find_function(func) Symbol.new(address, prototype, func) if address && !address.null? end def [](func, ty = nil) sym(func, ty || "0") end def enable_close @enable_close = true end def disable_close @enable_close = false end end def self.find_return_type(type) # Restrict types to the known-supported ones raise "Unsupported return type '#{type}'" unless type =~ /[0CHILFDPS]/ DL.find_type(type) end def self.find_param_type(type) # Restrict types to the known-supported ones raise "Unsupported parameter type '#{type}'" unless type =~ /[CHILFDPS]/ DL.find_type(type) end class Symbol attr_reader :name, :proto def initialize(address, type = nil, name = nil) @address = address @name = name @proto = type rt = DL.find_return_type(type[0].chr) arg_types = [] type[1..-1].each_byte { |t| arg_types << DL.find_param_type(t.chr) } if type.length > 1 @invoker = FFI::Invoker.new(address, arg_types, rt, "default") if rt == FFI::NativeType::POINTER def self.call(*args) [ PtrData.new(@invoker.call(*args)), args ] end end end def call(*args) [ @invoker.call(*args), args ] end def cproto cproto = @proto[1..-1].split(//).map { |t| Symbol.char2type(t) }.join(', ') "#{Symbol.char2type(@proto[0].chr)} #{@name}(#{cproto})" end def inspect "#<DL::Symbol func=0x#{@address.address.to_s(16)} '#{cproto}'>" end def to_s cproto end def to_i @address.address.to_i end def self.char2type(ch) Char2TypeName[ch] end end class PtrData def initialize(addr, size = nil, sym = nil) @ptr = addr end def self.malloc(size, free = nil) self.new(FFI::MemoryPointer.new(size)) end def null? @ptr.null? end def to_ptr @ptr end def struct!(type, *members) builder = FFI::StructLayoutBuilder.new i = 0 members.each do |name| t = type[i].chr i += 1 if i < type.length && type[i] =~ /[0123456789]/ raise DLTypeError.new("array fields not supported in struct") end if t =~ /[CHILFDPS]/ builder.add_field(name, DL.find_type(t)) else raise DLTypeError.new("Unsupported type '#{t}") end end @layout = builder.build self end def [](name) @layout.get(@ptr, name) end def []=(name, value) @layout.put(@ptr, name, value) end def size @layout ? @layout.size : @ptr.total end end def self.dlopen(libname) Handle.new(libname) end def self.malloc(size, free = nil) PtrData.malloc(size, free) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/optparse.rb
tools/jruby-1.5.1/lib/ruby/1.8/optparse.rb
# # optparse.rb - command-line option analysis with the OptionParser class. # # Author:: Nobu Nakada # Documentation:: Nobu Nakada and Gavin Sinclair. # # See OptionParser for documentation. # # == Developer Documentation (not for RDoc output) # # === Class tree # # - OptionParser:: front end # - OptionParser::Switch:: each switches # - OptionParser::List:: options list # - OptionParser::ParseError:: errors on parsing # - OptionParser::AmbiguousOption # - OptionParser::NeedlessArgument # - OptionParser::MissingArgument # - OptionParser::InvalidOption # - OptionParser::InvalidArgument # - OptionParser::AmbiguousArgument # # === Object relationship diagram # # +--------------+ # | OptionParser |<>-----+ # +--------------+ | +--------+ # | ,-| Switch | # on_head -------->+---------------+ / +--------+ # accept/reject -->| List |<|>- # | |<|>- +----------+ # on ------------->+---------------+ `-| argument | # : : | class | # +---------------+ |==========| # on_tail -------->| | |pattern | # +---------------+ |----------| # OptionParser.accept ->| DefaultList | |converter | # reject |(shared between| +----------+ # | all instances)| # +---------------+ # # == OptionParser # # === Introduction # # OptionParser is a class for command-line option analysis. It is much more # advanced, yet also easier to use, than GetoptLong, and is a more Ruby-oriented # solution. # # === Features # # 1. The argument specification and the code to handle it are written in the # same place. # 2. It can output an option summary; you don't need to maintain this string # separately. # 3. Optional and mandatory arguments are specified very gracefully. # 4. Arguments can be automatically converted to a specified class. # 5. Arguments can be restricted to a certain set. # # All of these features are demonstrated in the examples below. # # === Minimal example # # require 'optparse' # # options = {} # OptionParser.new do |opts| # opts.banner = "Usage: example.rb [options]" # # opts.on("-v", "--[no-]verbose", "Run verbosely") do |v| # options[:verbose] = v # end # end.parse! # # p options # p ARGV # # === Complete example # # The following example is a complete Ruby program. You can run it and see the # effect of specifying various options. This is probably the best way to learn # the features of +optparse+. # # require 'optparse' # require 'optparse/time' # require 'ostruct' # require 'pp' # # class OptparseExample # # CODES = %w[iso-2022-jp shift_jis euc-jp utf8 binary] # CODE_ALIASES = { "jis" => "iso-2022-jp", "sjis" => "shift_jis" } # # # # # Return a structure describing the options. # # # def self.parse(args) # # The options specified on the command line will be collected in *options*. # # We set default values here. # options = OpenStruct.new # options.library = [] # options.inplace = false # options.encoding = "utf8" # options.transfer_type = :auto # options.verbose = false # # opts = OptionParser.new do |opts| # opts.banner = "Usage: example.rb [options]" # # opts.separator "" # opts.separator "Specific options:" # # # Mandatory argument. # opts.on("-r", "--require LIBRARY", # "Require the LIBRARY before executing your script") do |lib| # options.library << lib # end # # # Optional argument; multi-line description. # opts.on("-i", "--inplace [EXTENSION]", # "Edit ARGV files in place", # " (make backup if EXTENSION supplied)") do |ext| # options.inplace = true # options.extension = ext || '' # options.extension.sub!(/\A\.?(?=.)/, ".") # Ensure extension begins with dot. # end # # # Cast 'delay' argument to a Float. # opts.on("--delay N", Float, "Delay N seconds before executing") do |n| # options.delay = n # end # # # Cast 'time' argument to a Time object. # opts.on("-t", "--time [TIME]", Time, "Begin execution at given time") do |time| # options.time = time # end # # # Cast to octal integer. # opts.on("-F", "--irs [OCTAL]", OptionParser::OctalInteger, # "Specify record separator (default \\0)") do |rs| # options.record_separator = rs # end # # # List of arguments. # opts.on("--list x,y,z", Array, "Example 'list' of arguments") do |list| # options.list = list # end # # # Keyword completion. We are specifying a specific set of arguments (CODES # # and CODE_ALIASES - notice the latter is a Hash), and the user may provide # # the shortest unambiguous text. # code_list = (CODE_ALIASES.keys + CODES).join(',') # opts.on("--code CODE", CODES, CODE_ALIASES, "Select encoding", # " (#{code_list})") do |encoding| # options.encoding = encoding # end # # # Optional argument with keyword completion. # opts.on("--type [TYPE]", [:text, :binary, :auto], # "Select transfer type (text, binary, auto)") do |t| # options.transfer_type = t # end # # # Boolean switch. # opts.on("-v", "--[no-]verbose", "Run verbosely") do |v| # options.verbose = v # end # # opts.separator "" # opts.separator "Common options:" # # # No argument, shows at tail. This will print an options summary. # # Try it and see! # opts.on_tail("-h", "--help", "Show this message") do # puts opts # exit # end # # # Another typical switch to print the version. # opts.on_tail("--version", "Show version") do # puts OptionParser::Version.join('.') # exit # end # end # # opts.parse!(args) # options # end # parse() # # end # class OptparseExample # # options = OptparseExample.parse(ARGV) # pp options # # === Further documentation # # The above examples should be enough to learn how to use this class. If you # have any questions, email me (gsinclair@soyabean.com.au) and I will update # this document. # class OptionParser # :stopdoc: # This is faked to avoid revision changes on every update RCSID = %w[Id: optparse.rb 99999 2009-02-20 11:43:35Z shyouhei ][1..-1].each {|s| s.freeze}.freeze Version = (RCSID[1].split('.').collect {|s| s.to_i}.extend(Comparable).freeze if RCSID[1]) LastModified = (Time.gm(*RCSID[2, 2].join('-').scan(/\d+/).collect {|s| s.to_i}) if RCSID[2]) Release = RCSID[2] NoArgument = [NO_ARGUMENT = :NONE, nil].freeze RequiredArgument = [REQUIRED_ARGUMENT = :REQUIRED, true].freeze OptionalArgument = [OPTIONAL_ARGUMENT = :OPTIONAL, false].freeze # :startdoc: # # Keyword completion module. This allows partial arguments to be specified # and resolved against a list of acceptable values. # module Completion def complete(key, icase = false, pat = nil) pat ||= Regexp.new('\A' + Regexp.quote(key).gsub(/\w+\b/, '\&\w*'), icase) canon, sw, k, v, cn = nil candidates = [] each do |k, *v| (if Regexp === k kn = nil k === key else kn = defined?(k.id2name) ? k.id2name : k pat === kn end) or next v << k if v.empty? candidates << [k, v, kn] end candidates = candidates.sort_by {|k, v, kn| kn.size} if candidates.size == 1 canon, sw, * = candidates[0] elsif candidates.size > 1 canon, sw, cn = candidates.shift candidates.each do |k, v, kn| next if sw == v if String === cn and String === kn if cn.rindex(kn, 0) canon, sw, cn = k, v, kn next elsif kn.rindex(cn, 0) next end end throw :ambiguous, key end end if canon block_given? or return key, *sw yield(key, *sw) end end def convert(opt = nil, val = nil, *) val end end # # Map from option/keyword string to object with completion. # class OptionMap < Hash include Completion end # # Individual switch class. Not important to the user. # # Defined within Switch are several Switch-derived classes: NoArgument, # RequiredArgument, etc. # class Switch attr_reader :pattern, :conv, :short, :long, :arg, :desc, :block # # Guesses argument style from +arg+. Returns corresponding # OptionParser::Switch class (OptionalArgument, etc.). # def self.guess(arg) case arg when "" t = self when /\A=?\[/ t = Switch::OptionalArgument when /\A\s+\[/ t = Switch::PlacedArgument else t = Switch::RequiredArgument end self >= t or incompatible_argument_styles(arg, t) t end def self.incompatible_argument_styles(arg, t) raise ArgumentError, "#{arg}: incompatible argument styles\n #{self}, #{t}" end def self.pattern NilClass end def initialize(pattern = nil, conv = nil, short = nil, long = nil, arg = nil, desc = ([] if short or long), block = Proc.new) raise if Array === pattern @pattern, @conv, @short, @long, @arg, @desc, @block = pattern, conv, short, long, arg, desc, block end # # Parses +arg+ and returns rest of +arg+ and matched portion to the # argument pattern. Yields when the pattern doesn't match substring. # def parse_arg(arg) pattern or return nil, arg unless m = pattern.match(arg) yield(InvalidArgument, arg) return arg, nil end if String === m m = [s = m] else m = m.to_a s = m[0] return nil, m unless String === s end raise InvalidArgument, arg unless arg.rindex(s, 0) return nil, m if s.length == arg.length yield(InvalidArgument, arg) # didn't match whole arg return arg[s.length..-1], m end private :parse_arg # # Parses argument, converts and returns +arg+, +block+ and result of # conversion. Yields at semi-error condition instead of raising an # exception. # def conv_arg(arg, val = nil) if conv val = conv.call(*val) else val = proc {|val| val}.call(*val) end return arg, block, val end private :conv_arg # # Produces the summary text. Each line of the summary is yielded to the # block (without newline). # # +sdone+:: Already summarized short style options keyed hash. # +ldone+:: Already summarized long style options keyed hash. # +width+:: Width of left side (option part). In other words, the right # side (description part) starts after +width+ columns. # +max+:: Maximum width of left side -> the options are filled within # +max+ columns. # +indent+:: Prefix string indents all summarized lines. # def summarize(sdone = [], ldone = [], width = 1, max = width - 1, indent = "") sopts, lopts, s = [], [], nil @short.each {|s| sdone.fetch(s) {sopts << s}; sdone[s] = true} if @short @long.each {|s| ldone.fetch(s) {lopts << s}; ldone[s] = true} if @long return if sopts.empty? and lopts.empty? # completely hidden left = [sopts.join(', ')] right = desc.dup while s = lopts.shift l = left[-1].length + s.length l += arg.length if left.size == 1 && arg l < max or sopts.empty? or left << '' left[-1] << if left[-1].empty? then ' ' * 4 else ', ' end << s end left[0] << arg if arg mlen = left.collect {|s| s.length}.max.to_i while mlen > width and l = left.shift mlen = left.collect {|s| s.length}.max.to_i if l.length == mlen yield(indent + l) end while begin l = left.shift; r = right.shift; l or r end l = l.to_s.ljust(width) + ' ' + r if r and !r.empty? yield(indent + l) end self end def add_banner(to) # :nodoc: unless @short or @long s = desc.join to << " [" + s + "]..." unless s.empty? end to end def match_nonswitch?(str) # :nodoc: @pattern =~ str unless @short or @long end # # Main name of the switch. # def switch_name (long.first || short.first).sub(/\A-+(?:\[no-\])?/, '') end # # Switch that takes no arguments. # class NoArgument < self # # Raises an exception if any arguments given. # def parse(arg, argv) yield(NeedlessArgument, arg) if arg conv_arg(arg) end def self.incompatible_argument_styles(*) end def self.pattern Object end end # # Switch that takes an argument. # class RequiredArgument < self # # Raises an exception if argument is not present. # def parse(arg, argv) unless arg raise MissingArgument if argv.empty? arg = argv.shift end conv_arg(*parse_arg(arg) {|*exc| raise(*exc)}) end end # # Switch that can omit argument. # class OptionalArgument < self # # Parses argument if given, or uses default value. # def parse(arg, argv, &error) if arg conv_arg(*parse_arg(arg, &error)) else conv_arg(arg) end end end # # Switch that takes an argument, which does not begin with '-'. # class PlacedArgument < self # # Returns nil if argument is not present or begins with '-'. # def parse(arg, argv, &error) if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0])) return nil, block, nil end opt = (val = parse_arg(val, &error))[1] val = conv_arg(*val) if opt and !arg argv.shift else val[0] = nil end val end end end # # Simple option list providing mapping from short and/or long option # string to OptionParser::Switch and mapping from acceptable argument to # matching pattern and converter pair. Also provides summary feature. # class List # Map from acceptable argument types to pattern and converter pairs. attr_reader :atype # Map from short style option switches to actual switch objects. attr_reader :short # Map from long style option switches to actual switch objects. attr_reader :long # List of all switches and summary string. attr_reader :list # # Just initializes all instance variables. # def initialize @atype = {} @short = OptionMap.new @long = OptionMap.new @list = [] end # # See OptionParser.accept. # def accept(t, pat = /.*/nm, &block) if pat pat.respond_to?(:match) or raise TypeError, "has no `match'" else pat = t if t.respond_to?(:match) end unless block block = pat.method(:convert).to_proc if pat.respond_to?(:convert) end @atype[t] = [pat, block] end # # See OptionParser.reject. # def reject(t) @atype.delete(t) end # # Adds +sw+ according to +sopts+, +lopts+ and +nlopts+. # # +sw+:: OptionParser::Switch instance to be added. # +sopts+:: Short style option list. # +lopts+:: Long style option list. # +nlopts+:: Negated long style options list. # def update(sw, sopts, lopts, nsw = nil, nlopts = nil) o = nil sopts.each {|o| @short[o] = sw} if sopts lopts.each {|o| @long[o] = sw} if lopts nlopts.each {|o| @long[o] = nsw} if nsw and nlopts used = @short.invert.update(@long.invert) @list.delete_if {|o| Switch === o and !used[o]} end private :update # # Inserts +switch+ at the head of the list, and associates short, long # and negated long options. Arguments are: # # +switch+:: OptionParser::Switch instance to be inserted. # +short_opts+:: List of short style options. # +long_opts+:: List of long style options. # +nolong_opts+:: List of long style options with "no-" prefix. # # prepend(switch, short_opts, long_opts, nolong_opts) # def prepend(*args) update(*args) @list.unshift(args[0]) end # # Appends +switch+ at the tail of the list, and associates short, long # and negated long options. Arguments are: # # +switch+:: OptionParser::Switch instance to be inserted. # +short_opts+:: List of short style options. # +long_opts+:: List of long style options. # +nolong_opts+:: List of long style options with "no-" prefix. # # append(switch, short_opts, long_opts, nolong_opts) # def append(*args) update(*args) @list.push(args[0]) end # # Searches +key+ in +id+ list. The result is returned or yielded if a # block is given. If it isn't found, nil is returned. # def search(id, key) if list = __send__(id) val = list.fetch(key) {return nil} block_given? ? yield(val) : val end end # # Searches list +id+ for +opt+ and the optional patterns for completion # +pat+. If +icase+ is true, the search is case insensitive. The result # is returned or yielded if a block is given. If it isn't found, nil is # returned. # def complete(id, opt, icase = false, *pat, &block) __send__(id).complete(opt, icase, *pat, &block) end # # Iterates over each option, passing the option to the +block+. # def each_option(&block) list.each(&block) end # # Creates the summary table, passing each line to the +block+ (without # newline). The arguments +args+ are passed along to the summarize # method which is called on every option. # def summarize(*args, &block) sum = [] list.reverse_each do |opt| if opt.respond_to?(:summarize) # perhaps OptionParser::Switch s = [] opt.summarize(*args) {|l| s << l} sum.concat(s.reverse) elsif !opt or opt.empty? sum << "" elsif opt.respond_to?(:each_line) sum.concat([*opt.each_line].reverse) else sum.concat([*opt.each].reverse) end end sum.reverse_each(&block) end def add_banner(to) # :nodoc: list.each do |opt| if opt.respond_to?(:add_banner) opt.add_banner(to) end end to end end # # Hash with completion search feature. See OptionParser::Completion. # class CompletingHash < Hash include Completion # # Completion for hash key. # def match(key) return key, *fetch(key) { raise AmbiguousArgument, catch(:ambiguous) {return complete(key)} } end end # :stopdoc: # # Enumeration of acceptable argument styles. Possible values are: # # NO_ARGUMENT:: The switch takes no arguments. (:NONE) # REQUIRED_ARGUMENT:: The switch requires an argument. (:REQUIRED) # OPTIONAL_ARGUMENT:: The switch requires an optional argument. (:OPTIONAL) # # Use like --switch=argument (long style) or -Xargument (short style). For # short style, only portion matched to argument pattern is dealed as # argument. # ArgumentStyle = {} NoArgument.each {|el| ArgumentStyle[el] = Switch::NoArgument} RequiredArgument.each {|el| ArgumentStyle[el] = Switch::RequiredArgument} OptionalArgument.each {|el| ArgumentStyle[el] = Switch::OptionalArgument} ArgumentStyle.freeze # # Switches common used such as '--', and also provides default # argument classes # DefaultList = List.new DefaultList.short['-'] = Switch::NoArgument.new {} DefaultList.long[''] = Switch::NoArgument.new {throw :terminate} # # Default options for ARGV, which never appear in option summary. # Officious = {} # # --help # Shows option summary. # Officious['help'] = proc do |parser| Switch::NoArgument.new do puts parser.help exit end end # # --version # Shows version string if Version is defined. # Officious['version'] = proc do |parser| Switch::OptionalArgument.new do |pkg| if pkg begin require 'optparse/version' rescue LoadError else show_version(*pkg.split(/,/)) or abort("#{parser.program_name}: no version found in package #{pkg}") exit end end v = parser.ver or abort("#{parser.program_name}: version unknown") puts v exit end end # :startdoc: # # Class methods # # # Initializes a new instance and evaluates the optional block in context # of the instance. Arguments +args+ are passed to #new, see there for # description of parameters. # # This method is *deprecated*, its behavior corresponds to the older #new # method. # def self.with(*args, &block) opts = new(*args) opts.instance_eval(&block) opts end # # Returns an incremented value of +default+ according to +arg+. # def self.inc(arg, default = nil) case arg when Integer arg.nonzero? when nil default.to_i + 1 end end def inc(*args) self.class.inc(*args) end # # Initializes the instance and yields itself if called with a block. # # +banner+:: Banner message. # +width+:: Summary width. # +indent+:: Summary indent. # def initialize(banner = nil, width = 32, indent = ' ' * 4) @stack = [DefaultList, List.new, List.new] @program_name = nil @banner = banner @summary_width = width @summary_indent = indent @default_argv = ARGV add_officious yield self if block_given? end def add_officious # :nodoc: list = base() Officious.each do |opt, block| list.long[opt] ||= block.call(self) end end # # Terminates option parsing. Optional parameter +arg+ is a string pushed # back to be the first non-option argument. # def terminate(arg = nil) self.class.terminate(arg) end def self.terminate(arg = nil) throw :terminate, arg end @stack = [DefaultList] def self.top() DefaultList end # # Directs to accept specified class +t+. The argument string is passed to # the block in which it should be converted to the desired class. # # +t+:: Argument class specifier, any object including Class. # +pat+:: Pattern for argument, defaults to +t+ if it responds to match. # # accept(t, pat, &block) # def accept(*args, &blk) top.accept(*args, &blk) end # # See #accept. # def self.accept(*args, &blk) top.accept(*args, &blk) end # # Directs to reject specified class argument. # # +t+:: Argument class specifier, any object including Class. # # reject(t) # def reject(*args, &blk) top.reject(*args, &blk) end # # See #reject. # def self.reject(*args, &blk) top.reject(*args, &blk) end # # Instance methods # # Heading banner preceding summary. attr_writer :banner # Program name to be emitted in error message and default banner, # defaults to $0. attr_writer :program_name # Width for option list portion of summary. Must be Numeric. attr_accessor :summary_width # Indentation for summary. Must be String (or have + String method). attr_accessor :summary_indent # Strings to be parsed in default. attr_accessor :default_argv # # Heading banner preceding summary. # def banner unless @banner @banner = "Usage: #{program_name} [options]" visit(:add_banner, @banner) end @banner end # # Program name to be emitted in error message and default banner, defaults # to $0. # def program_name @program_name || File.basename($0, '.*') end # for experimental cascading :-) alias set_banner banner= alias set_program_name program_name= alias set_summary_width summary_width= alias set_summary_indent summary_indent= # Version attr_writer :version # Release code attr_writer :release # # Version # def version @version || (defined?(::Version) && ::Version) end # # Release code # def release @release || (defined?(::Release) && ::Release) || (defined?(::RELEASE) && ::RELEASE) end # # Returns version string from program_name, version and release. # def ver if v = version str = "#{program_name} #{[v].join('.')}" str << " (#{v})" if v = release str end end def warn(mesg = $!) super("#{program_name}: #{mesg}") end def abort(mesg = $!) super("#{program_name}: #{mesg}") end # # Subject of #on / #on_head, #accept / #reject # def top @stack[-1] end # # Subject of #on_tail. # def base @stack[1] end # # Pushes a new List. # def new @stack.push(List.new) if block_given? yield self else self end end # # Removes the last List. # def remove @stack.pop end # # Puts option summary into +to+ and returns +to+. Yields each line if # a block is given. # # +to+:: Output destination, which must have method <<. Defaults to []. # +width+:: Width of left side, defaults to @summary_width. # +max+:: Maximum length allowed for left side, defaults to +width+ - 1. # +indent+:: Indentation, defaults to @summary_indent. # def summarize(to = [], width = @summary_width, max = width - 1, indent = @summary_indent, &blk) blk ||= proc {|l| to << (l.index($/, -1) ? l : l + $/)} visit(:summarize, {}, {}, width, max, indent, &blk) to end # # Returns option summary string. # def help; summarize(banner.to_s.sub(/\n?\z/, "\n")) end alias to_s help # # Returns option summary list. # def to_a; summarize(banner.to_a.dup) end # # Checks if an argument is given twice, in which case an ArgumentError is # raised. Called from OptionParser#switch only. # # +obj+:: New argument. # +prv+:: Previously specified argument. # +msg+:: Exception message. # def notwice(obj, prv, msg) unless !prv or prv == obj begin raise ArgumentError, "argument #{msg} given twice: #{obj}" rescue $@[0, 2] = nil raise end end obj end private :notwice # # Creates an OptionParser::Switch from the parameters. The parsed argument # value is passed to the given block, where it can be processed. # # See at the beginning of OptionParser for some full examples. # # +opts+ can include the following elements: # # [Argument style:] # One of the following: # :NONE, :REQUIRED, :OPTIONAL # # [Argument pattern:] # Acceptable option argument format, must be pre-defined with # OptionParser.accept or OptionParser#accept, or Regexp. This can appear # once or assigned as String if not present, otherwise causes an # ArgumentError. Examples: # Float, Time, Array # # [Possible argument values:] # Hash or Array. # [:text, :binary, :auto] # %w[iso-2022-jp shift_jis euc-jp utf8 binary] # { "jis" => "iso-2022-jp", "sjis" => "shift_jis" } # # [Long style switch:] # Specifies a long style switch which takes a mandatory, optional or no # argument. It's a string of the following form: # "--switch=MANDATORY" or "--switch MANDATORY" # "--switch[=OPTIONAL]" # "--switch" # # [Short style switch:] # Specifies short style switch which takes a mandatory, optional or no # argument. It's a string of the following form: # "-xMANDATORY" # "-x[OPTIONAL]" # "-x" # There is also a special form which matches character range (not full # set of regular expression): # "-[a-z]MANDATORY" # "-[a-z][OPTIONAL]" # "-[a-z]" # # [Argument style and description:] # Instead of specifying mandatory or optional arguments directly in the # switch parameter, this separate parameter can be used. # "=MANDATORY" # "=[OPTIONAL]" # # [Description:] # Description string for the option. # "Run verbosely" # # [Handler:] # Handler for the parsed argument value. Either give a block or pass a # Proc or Method as an argument. # def make_switch(opts, block = nil) short, long, nolong, style, pattern, conv, not_pattern, not_conv, not_style = [], [], [] ldesc, sdesc, desc, arg = [], [], [] default_style = Switch::NoArgument default_pattern = nil klass = nil o = nil n, q, a = nil opts.each do |o| # argument class next if search(:atype, o) do |pat, c| klass = notwice(o, klass, 'type') if not_style and not_style != Switch::NoArgument not_pattern, not_conv = pat, c else default_pattern, conv = pat, c end end # directly specified pattern(any object possible to match) if !(String === o) and o.respond_to?(:match) pattern = notwice(o, pattern, 'pattern') conv = pattern.method(:convert).to_proc if pattern.respond_to?(:convert) next end # anything others case o when Proc, Method block = notwice(o, block, 'block') when Array, Hash case pattern when CompletingHash when nil pattern = CompletingHash.new conv = pattern.method(:convert).to_proc if pattern.respond_to?(:convert) else raise ArgumentError, "argument pattern given twice" end o.each {|(o, *v)| pattern[o] = v.fetch(0) {o}} when Module raise ArgumentError, "unsupported argument type: #{o}" when *ArgumentStyle.keys style = notwice(ArgumentStyle[o], style, 'style') when /^--no-([^\[\]=\s]*)(.+)?/ q, a = $1, $2 o = notwice(a ? Object : TrueClass, klass, 'type') not_pattern, not_conv = search(:atype, o) unless not_style not_style = (not_style || default_style).guess(arg = a) if a default_style = Switch::NoArgument default_pattern, conv = search(:atype, FalseClass) unless default_pattern ldesc << "--no-#{q}" long << 'no-' + (q = q.downcase) nolong << q when /^--\[no-\]([^\[\]=\s]*)(.+)?/ q, a = $1, $2 o = notwice(a ? Object : TrueClass, klass, 'type') if a default_style = default_style.guess(arg = a) default_pattern, conv = search(:atype, o) unless default_pattern end ldesc << "--[no-]#{q}" long << (o = q.downcase) not_pattern, not_conv = search(:atype, FalseClass) unless not_style not_style = Switch::NoArgument nolong << 'no-' + o when /^--([^\[\]=\s]*)(.+)?/ q, a = $1, $2 if a o = notwice(NilClass, klass, 'type') default_style = default_style.guess(arg = a) default_pattern, conv = search(:atype, o) unless default_pattern end ldesc << "--#{q}" long << (o = q.downcase) when /^-(\[\^?\]?(?:[^\\\]]|\\.)*\])(.+)?/ q, a = $1, $2 o = notwice(Object, klass, 'type') if a default_style = default_style.guess(arg = a) default_pattern, conv = search(:atype, o) unless default_pattern end sdesc << "-#{q}" short << Regexp.new(q) when /^-(.)(.+)?/ q, a = $1, $2 if a o = notwice(NilClass, klass, 'type') default_style = default_style.guess(arg = a) default_pattern, conv = search(:atype, o) unless default_pattern end sdesc << "-#{q}" short << q when /^=/ style = notwice(default_style.guess(arg = o), style, 'style') default_pattern, conv = search(:atype, Object) unless default_pattern else desc.push(o) end end default_pattern, conv = search(:atype, default_style.pattern) unless default_pattern if !(short.empty? and long.empty?)
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
true
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/English.rb
tools/jruby-1.5.1/lib/ruby/1.8/English.rb
# Include the English library file in a Ruby script, and you can # reference the global variables such as \VAR{\$\_} using less # cryptic names, listed in the following table.% \vref{tab:english}. # # Without 'English': # # $\ = ' -- ' # "waterbuffalo" =~ /buff/ # print $", $', $$, "\n" # # With English: # # require "English" # # $OUTPUT_FIELD_SEPARATOR = ' -- ' # "waterbuffalo" =~ /buff/ # print $LOADED_FEATURES, $POSTMATCH, $PID, "\n" # The exception object passed to +raise+. alias $ERROR_INFO $! # The stack backtrace generated by the last # exception. <tt>See Kernel.caller</tt> for details. Thread local. alias $ERROR_POSITION $@ # The default separator pattern used by <tt>String.split</tt>. May be # set from the command line using the <tt>-F</tt> flag. alias $FS $; # The default separator pattern used by <tt>String.split</tt>. May be # set from the command line using the <tt>-F</tt> flag. alias $FIELD_SEPARATOR $; # The separator string output between the parameters to methods such # as <tt>Kernel.print</tt> and <tt>Array.join</tt>. Defaults to +nil+, # which adds no text. alias $OFS $, # The separator string output between the parameters to methods such # as <tt>Kernel.print</tt> and <tt>Array.join</tt>. Defaults to +nil+, # which adds no text. alias $OUTPUT_FIELD_SEPARATOR $, # The input record separator (newline by default). This is the value # that routines such as <tt>Kernel.gets</tt> use to determine record # boundaries. If set to +nil+, +gets+ will read the entire file. alias $RS $/ # The input record separator (newline by default). This is the value # that routines such as <tt>Kernel.gets</tt> use to determine record # boundaries. If set to +nil+, +gets+ will read the entire file. alias $INPUT_RECORD_SEPARATOR $/ # The string appended to the output of every call to methods such as # <tt>Kernel.print</tt> and <tt>IO.write</tt>. The default value is # +nil+. alias $ORS $\ # The string appended to the output of every call to methods such as # <tt>Kernel.print</tt> and <tt>IO.write</tt>. The default value is # +nil+. alias $OUTPUT_RECORD_SEPARATOR $\ # The number of the last line read from the current input file. alias $INPUT_LINE_NUMBER $. # The number of the last line read from the current input file. alias $NR $. # The last line read by <tt>Kernel.gets</tt> or # <tt>Kernel.readline</tt>. Many string-related functions in the # +Kernel+ module operate on <tt>$_</tt> by default. The variable is # local to the current scope. Thread local. alias $LAST_READ_LINE $_ # The destination of output for <tt>Kernel.print</tt> # and <tt>Kernel.printf</tt>. The default value is # <tt>$stdout</tt>. alias $DEFAULT_OUTPUT $> # An object that provides access to the concatenation # of the contents of all the files # given as command-line arguments, or <tt>$stdin</tt> # (in the case where there are no # arguments). <tt>$<</tt> supports methods similar to a # +File+ object: # +inmode+, +close+, # <tt>closed?</tt>, +each+, # <tt>each_byte</tt>, <tt>each_line</tt>, # +eof+, <tt>eof?</tt>, +file+, # +filename+, +fileno+, # +getc+, +gets+, +lineno+, # <tt>lineno=</tt>, +path+, # +pos+, <tt>pos=</tt>, # +read+, +readchar+, # +readline+, +readlines+, # +rewind+, +seek+, +skip+, # +tell+, <tt>to_a</tt>, <tt>to_i</tt>, # <tt>to_io</tt>, <tt>to_s</tt>, along with the # methods in +Enumerable+. The method +file+ # returns a +File+ object for the file currently # being read. This may change as <tt>$<</tt> reads # through the files on the command line. Read only. alias $DEFAULT_INPUT $< # The process number of the program being executed. Read only. alias $PID $$ # The process number of the program being executed. Read only. alias $PROCESS_ID $$ # The exit status of the last child process to terminate. Read # only. Thread local. alias $CHILD_STATUS $? # A +MatchData+ object that encapsulates the results of a successful # pattern match. The variables <tt>$&</tt>, <tt>$`</tt>, <tt>$'</tt>, # and <tt>$1</tt> to <tt>$9</tt> are all derived from # <tt>$~</tt>. Assigning to <tt>$~</tt> changes the values of these # derived variables. This variable is local to the current # scope. Thread local. alias $LAST_MATCH_INFO $~ # If set to any value apart from +nil+ or +false+, all pattern matches # will be case insensitive, string comparisons will ignore case, and # string hash values will be case insensitive. Deprecated alias $IGNORECASE $= # An array of strings containing the command-line # options from the invocation of the program. Options # used by the Ruby interpreter will have been # removed. Read only. Also known simply as +ARGV+. alias $ARGV $* # The string matched by the last successful pattern # match. This variable is local to the current # scope. Read only. Thread local. alias $MATCH $& # The string preceding the match in the last # successful pattern match. This variable is local to # the current scope. Read only. Thread local. alias $PREMATCH $` # The string following the match in the last # successful pattern match. This variable is local to # the current scope. Read only. Thread local. alias $POSTMATCH $' # The contents of the highest-numbered group matched in the last # successful pattern match. Thus, in <tt>"cat" =~ /(c|a)(t|z)/</tt>, # <tt>$+</tt> will be set to "t". This variable is local to the # current scope. Read only. Thread local. alias $LAST_PAREN_MATCH $+
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/logger.rb
tools/jruby-1.5.1/lib/ruby/1.8/logger.rb
# logger.rb - simple logging utility # Copyright (C) 2000-2003, 2005 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>. require 'monitor' # Simple logging utility. # # Author:: NAKAMURA, Hiroshi <nakahiro@sarion.co.jp> # Documentation:: NAKAMURA, Hiroshi and Gavin Sinclair # License:: # You can redistribute it and/or modify it under the same terms of Ruby's # license; either the dual license version in 2003, or any later version. # Revision:: $Id: logger.rb 22285 2009-02-13 10:19:04Z shyouhei $ # # == Description # # The Logger class provides a simple but sophisticated logging utility that # anyone can use because it's included in the Ruby 1.8.x standard library. # # The HOWTOs below give a code-based overview of Logger's usage, but the basic # concept is as follows. You create a Logger object (output to a file or # elsewhere), and use it to log messages. The messages will have varying # levels (+info+, +error+, etc), reflecting their varying importance. The # levels, and their meanings, are: # # +FATAL+:: an unhandleable error that results in a program crash # +ERROR+:: a handleable error condition # +WARN+:: a warning # +INFO+:: generic (useful) information about system operation # +DEBUG+:: low-level information for developers # # So each message has a level, and the Logger itself has a level, which acts # as a filter, so you can control the amount of information emitted from the # logger without having to remove actual messages. # # For instance, in a production system, you may have your logger(s) set to # +INFO+ (or +WARN+ if you don't want the log files growing large with # repetitive information). When you are developing it, though, you probably # want to know about the program's internal state, and would set them to # +DEBUG+. # # === Example # # A simple example demonstrates the above explanation: # # log = Logger.new(STDOUT) # log.level = Logger::WARN # # log.debug("Created logger") # log.info("Program started") # log.warn("Nothing to do!") # # begin # File.each_line(path) do |line| # unless line =~ /^(\w+) = (.*)$/ # log.error("Line in wrong format: #{line}") # end # end # rescue => err # log.fatal("Caught exception; exiting") # log.fatal(err) # end # # Because the Logger's level is set to +WARN+, only the warning, error, and # fatal messages are recorded. The debug and info messages are silently # discarded. # # === Features # # There are several interesting features that Logger provides, like # auto-rolling of log files, setting the format of log messages, and # specifying a program name in conjunction with the message. The next section # shows you how to achieve these things. # # # == HOWTOs # # === How to create a logger # # The options below give you various choices, in more or less increasing # complexity. # # 1. Create a logger which logs messages to STDERR/STDOUT. # # logger = Logger.new(STDERR) # logger = Logger.new(STDOUT) # # 2. Create a logger for the file which has the specified name. # # logger = Logger.new('logfile.log') # # 3. Create a logger for the specified file. # # file = File.open('foo.log', File::WRONLY | File::APPEND) # # To create new (and to remove old) logfile, add File::CREAT like; # # file = open('foo.log', File::WRONLY | File::APPEND | File::CREAT) # logger = Logger.new(file) # # 4. Create a logger which ages logfile once it reaches a certain size. Leave # 10 "old log files" and each file is about 1,024,000 bytes. # # logger = Logger.new('foo.log', 10, 1024000) # # 5. Create a logger which ages logfile daily/weekly/monthly. # # logger = Logger.new('foo.log', 'daily') # logger = Logger.new('foo.log', 'weekly') # logger = Logger.new('foo.log', 'monthly') # # === How to log a message # # Notice the different methods (+fatal+, +error+, +info+) being used to log # messages of various levels. Other methods in this family are +warn+ and # +debug+. +add+ is used below to log a message of an arbitrary (perhaps # dynamic) level. # # 1. Message in block. # # logger.fatal { "Argument 'foo' not given." } # # 2. Message as a string. # # logger.error "Argument #{ @foo } mismatch." # # 3. With progname. # # logger.info('initialize') { "Initializing..." } # # 4. With severity. # # logger.add(Logger::FATAL) { 'Fatal error!' } # # === How to close a logger # # logger.close # # === Setting severity threshold # # 1. Original interface. # # logger.sev_threshold = Logger::WARN # # 2. Log4r (somewhat) compatible interface. # # logger.level = Logger::INFO # # DEBUG < INFO < WARN < ERROR < FATAL < UNKNOWN # # # == Format # # Log messages are rendered in the output stream in a certain format. The # default format and a sample are shown below: # # Log format: # SeverityID, [Date Time mSec #pid] SeverityLabel -- ProgName: message # # Log sample: # I, [Wed Mar 03 02:34:24 JST 1999 895701 #19074] INFO -- Main: info. # # You may change the date and time format in this manner: # # logger.datetime_format = "%Y-%m-%d %H:%M:%S" # # e.g. "2004-01-03 00:54:26" # # There is currently no supported way to change the overall format, but you may # have some luck hacking the Format constant. # class Logger VERSION = "1.2.6" # this is faked to avoid the svn ID changing with every update ProgName = "logger.rb/99999" class Error < RuntimeError; end class ShiftingError < Error; end # Logging severity. module Severity DEBUG = 0 INFO = 1 WARN = 2 ERROR = 3 FATAL = 4 UNKNOWN = 5 end include Severity # Logging severity threshold (e.g. <tt>Logger::INFO</tt>). attr_accessor :level # Logging program name. attr_accessor :progname # Logging date-time format (string passed to +strftime+). def datetime_format=(datetime_format) @default_formatter.datetime_format = datetime_format end def datetime_format @default_formatter.datetime_format end # Logging formatter. formatter#call is invoked with 4 arguments; severity, # time, progname and msg for each log. Bear in mind that time is a Time and # msg is an Object that user passed and it could not be a String. It is # expected to return a logdev#write-able Object. Default formatter is used # when no formatter is set. attr_accessor :formatter alias sev_threshold level alias sev_threshold= level= # Returns +true+ iff the current severity level allows for the printing of # +DEBUG+ messages. def debug?; @level <= DEBUG; end # Returns +true+ iff the current severity level allows for the printing of # +INFO+ messages. def info?; @level <= INFO; end # Returns +true+ iff the current severity level allows for the printing of # +WARN+ messages. def warn?; @level <= WARN; end # Returns +true+ iff the current severity level allows for the printing of # +ERROR+ messages. def error?; @level <= ERROR; end # Returns +true+ iff the current severity level allows for the printing of # +FATAL+ messages. def fatal?; @level <= FATAL; end # # === Synopsis # # Logger.new(name, shift_age = 7, shift_size = 1048576) # Logger.new(name, shift_age = 'weekly') # # === Args # # +logdev+:: # The log device. This is a filename (String) or IO object (typically # +STDOUT+, +STDERR+, or an open file). # +shift_age+:: # Number of old log files to keep, *or* frequency of rotation (+daily+, # +weekly+ or +monthly+). # +shift_size+:: # Maximum logfile size (only applies when +shift_age+ is a number). # # === Description # # Create an instance. # def initialize(logdev, shift_age = 0, shift_size = 1048576) @progname = nil @level = DEBUG @default_formatter = Formatter.new @formatter = nil @logdev = nil if logdev @logdev = LogDevice.new(logdev, :shift_age => shift_age, :shift_size => shift_size) end end # # === Synopsis # # Logger#add(severity, message = nil, progname = nil) { ... } # # === Args # # +severity+:: # Severity. Constants are defined in Logger namespace: +DEBUG+, +INFO+, # +WARN+, +ERROR+, +FATAL+, or +UNKNOWN+. # +message+:: # The log message. A String or Exception. # +progname+:: # Program name string. Can be omitted. Treated as a message if no +message+ and # +block+ are given. # +block+:: # Can be omitted. Called to get a message string if +message+ is nil. # # === Return # # +true+ if successful, +false+ otherwise. # # When the given severity is not high enough (for this particular logger), log # no message, and return +true+. # # === Description # # Log a message if the given severity is high enough. This is the generic # logging method. Users will be more inclined to use #debug, #info, #warn, # #error, and #fatal. # # <b>Message format</b>: +message+ can be any object, but it has to be # converted to a String in order to log it. Generally, +inspect+ is used # if the given object is not a String. # A special case is an +Exception+ object, which will be printed in detail, # including message, class, and backtrace. See #msg2str for the # implementation if required. # # === Bugs # # * Logfile is not locked. # * Append open does not need to lock file. # * But on the OS which supports multi I/O, records possibly be mixed. # def add(severity, message = nil, progname = nil, &block) severity ||= UNKNOWN if @logdev.nil? or severity < @level return true end progname ||= @progname if message.nil? if block_given? message = yield else message = progname progname = @progname end end @logdev.write( format_message(format_severity(severity), Time.now, progname, message)) true end alias log add # # Dump given message to the log device without any formatting. If no log # device exists, return +nil+. # def <<(msg) unless @logdev.nil? @logdev.write(msg) end end # # Log a +DEBUG+ message. # # See #info for more information. # def debug(progname = nil, &block) add(DEBUG, nil, progname, &block) end # # Log an +INFO+ message. # # The message can come either from the +progname+ argument or the +block+. If # both are provided, then the +block+ is used as the message, and +progname+ # is used as the program name. # # === Examples # # logger.info("MainApp") { "Received connection from #{ip}" } # # ... # logger.info "Waiting for input from user" # # ... # logger.info { "User typed #{input}" } # # You'll probably stick to the second form above, unless you want to provide a # program name (which you can do with <tt>Logger#progname=</tt> as well). # # === Return # # See #add. # def info(progname = nil, &block) add(INFO, nil, progname, &block) end # # Log a +WARN+ message. # # See #info for more information. # def warn(progname = nil, &block) add(WARN, nil, progname, &block) end # # Log an +ERROR+ message. # # See #info for more information. # def error(progname = nil, &block) add(ERROR, nil, progname, &block) end # # Log a +FATAL+ message. # # See #info for more information. # def fatal(progname = nil, &block) add(FATAL, nil, progname, &block) end # # Log an +UNKNOWN+ message. This will be printed no matter what the logger # level. # # See #info for more information. # def unknown(progname = nil, &block) add(UNKNOWN, nil, progname, &block) end # # Close the logging device. # def close @logdev.close if @logdev end private # Severity label for logging. (max 5 char) SEV_LABEL = %w(DEBUG INFO WARN ERROR FATAL ANY) def format_severity(severity) SEV_LABEL[severity] || 'ANY' end def format_message(severity, datetime, progname, msg) (@formatter || @default_formatter).call(severity, datetime, progname, msg) end class Formatter Format = "%s, [%s#%d] %5s -- %s: %s\n" attr_accessor :datetime_format def initialize @datetime_format = nil end def call(severity, time, progname, msg) Format % [severity[0..0], format_datetime(time), $$, severity, progname, msg2str(msg)] end private def format_datetime(time) if @datetime_format.nil? time.strftime("%Y-%m-%dT%H:%M:%S.") << "%06d " % time.usec else time.strftime(@datetime_format) end end def msg2str(msg) case msg when ::String msg when ::Exception "#{ msg.message } (#{ msg.class })\n" << (msg.backtrace || []).join("\n") else msg.inspect end end end class LogDevice attr_reader :dev attr_reader :filename class LogDeviceMutex include MonitorMixin end def initialize(log = nil, opt = {}) @dev = @filename = @shift_age = @shift_size = nil @mutex = LogDeviceMutex.new if log.respond_to?(:write) and log.respond_to?(:close) @dev = log else @dev = open_logfile(log) @dev.sync = true @filename = log @shift_age = opt[:shift_age] || 7 @shift_size = opt[:shift_size] || 1048576 end end def write(message) @mutex.synchronize do if @shift_age and @dev.respond_to?(:stat) begin check_shift_log rescue raise Logger::ShiftingError.new("Shifting failed. #{$!}") end end @dev.write(message) end end def close @mutex.synchronize do @dev.close end end private def open_logfile(filename) if (FileTest.exist?(filename)) open(filename, (File::WRONLY | File::APPEND)) else create_logfile(filename) end end def create_logfile(filename) logdev = open(filename, (File::WRONLY | File::APPEND | File::CREAT)) logdev.sync = true add_log_header(logdev) logdev end def add_log_header(file) file.write( "# Logfile created on %s by %s\n" % [Time.now.to_s, Logger::ProgName] ) end SiD = 24 * 60 * 60 def check_shift_log if @shift_age.is_a?(Integer) # Note: always returns false if '0'. if @filename && (@shift_age > 0) && (@dev.stat.size > @shift_size) shift_log_age end else now = Time.now if @dev.stat.mtime <= previous_period_end(now) shift_log_period(now) end end end def shift_log_age (@shift_age-3).downto(0) do |i| if FileTest.exist?("#{@filename}.#{i}") File.rename("#{@filename}.#{i}", "#{@filename}.#{i+1}") end end @dev.close File.rename("#{@filename}", "#{@filename}.0") @dev = create_logfile(@filename) return true end def shift_log_period(now) postfix = previous_period_end(now).strftime("%Y%m%d") # YYYYMMDD age_file = "#{@filename}.#{postfix}" if FileTest.exist?(age_file) raise RuntimeError.new("'#{ age_file }' already exists.") end @dev.close File.rename("#{@filename}", age_file) @dev = create_logfile(@filename) return true end def previous_period_end(now) case @shift_age when /^daily$/ eod(now - 1 * SiD) when /^weekly$/ eod(now - ((now.wday + 1) * SiD)) when /^monthly$/ eod(now - now.mday * SiD) else now end end def eod(t) Time.mktime(t.year, t.month, t.mday, 23, 59, 59) end end # # == Description # # Application -- Add logging support to your application. # # == Usage # # 1. Define your application class as a sub-class of this class. # 2. Override 'run' method in your class to do many things. # 3. Instantiate it and invoke 'start'. # # == Example # # class FooApp < Application # def initialize(foo_app, application_specific, arguments) # super('FooApp') # Name of the application. # end # # def run # ... # log(WARN, 'warning', 'my_method1') # ... # @log.error('my_method2') { 'Error!' } # ... # end # end # # status = FooApp.new(....).start # class Application include Logger::Severity attr_reader :appname attr_reader :logdev # # == Synopsis # # Application.new(appname = '') # # == Args # # +appname+:: Name of the application. # # == Description # # Create an instance. Log device is +STDERR+ by default. This can be # changed with #set_log. # def initialize(appname = nil) @appname = appname @log = Logger.new(STDERR) @log.progname = @appname @level = @log.level end # # Start the application. Return the status code. # def start status = -1 begin log(INFO, "Start of #{ @appname }.") status = run rescue log(FATAL, "Detected an exception. Stopping ... #{$!} (#{$!.class})\n" << $@.join("\n")) ensure log(INFO, "End of #{ @appname }. (status: #{ status.to_s })") end status end # # Sets the log device for this application. See the class Logger for an # explanation of the arguments. # def set_log(logdev, shift_age = 0, shift_size = 1024000) @log = Logger.new(logdev, shift_age, shift_size) @log.progname = @appname @log.level = @level end def log=(logdev) set_log(logdev) end # # Set the logging threshold, just like <tt>Logger#level=</tt>. # def level=(level) @level = level @log.level = @level end # # See Logger#add. This application's +appname+ is used. # def log(severity, message = nil, &block) @log.add(severity, message, @appname, &block) if @log end private def run raise RuntimeError.new('Method run must be defined in the derived class.') end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/mathn.rb
tools/jruby-1.5.1/lib/ruby/1.8/mathn.rb
# # mathn.rb - # $Release Version: 0.5 $ # $Revision: 1.1.1.1.4.1 $ # $Date: 1998/01/16 12:36:05 $ # by Keiju ISHITSUKA(SHL Japan Inc.) # # -- # # # require "complex.rb" require "rational.rb" require "matrix.rb" class Integer def gcd2(int) a = self.abs b = int.abs a, b = b, a if a < b pd_a = a.prime_division pd_b = b.prime_division gcd = 1 for pair in pd_a as = pd_b.assoc(pair[0]) if as gcd *= as[0] ** [as[1], pair[1]].min end end return gcd end def Integer.from_prime_division(pd) value = 1 for prime, index in pd value *= prime**index end value end def prime_division raise ZeroDivisionError if self == 0 ps = Prime.new value = self pv = [] for prime in ps count = 0 while (value1, mod = value.divmod(prime) mod) == 0 value = value1 count += 1 end if count != 0 pv.push [prime, count] end break if prime * prime >= value end if value > 1 pv.push [value, 1] end return pv end end class Prime include Enumerable def initialize @seed = 1 @primes = [] @counts = [] end def succ i = -1 size = @primes.size while i < size if i == -1 @seed += 1 i += 1 else while @seed > @counts[i] @counts[i] += @primes[i] end if @seed != @counts[i] i += 1 else i = -1 end end end @primes.push @seed @counts.push @seed + @seed return @seed end alias next succ def each loop do yield succ end end end class Fixnum alias / quo end class Bignum alias / quo end class Rational Unify = true def inspect format "%s/%s", numerator.inspect, denominator.inspect end alias power! ** def ** (other) if other.kind_of?(Rational) other2 = other if self < 0 return Complex.new!(self, 0) ** other elsif other == 0 return Rational(1,1) elsif self == 0 return Rational(0,1) elsif self == 1 return Rational(1,1) end npd = numerator.prime_division dpd = denominator.prime_division if other < 0 other = -other npd, dpd = dpd, npd end for elm in npd elm[1] = elm[1] * other if !elm[1].kind_of?(Integer) and elm[1].denominator != 1 return Float(self) ** other2 end elm[1] = elm[1].to_i end for elm in dpd elm[1] = elm[1] * other if !elm[1].kind_of?(Integer) and elm[1].denominator != 1 return Float(self) ** other2 end elm[1] = elm[1].to_i end num = Integer.from_prime_division(npd) den = Integer.from_prime_division(dpd) Rational(num,den) elsif other.kind_of?(Integer) if other > 0 num = numerator ** other den = denominator ** other elsif other < 0 num = denominator ** -other den = numerator ** -other elsif other == 0 num = 1 den = 1 end Rational.new!(num, den) elsif other.kind_of?(Float) Float(self) ** other else x , y = other.coerce(self) x ** y end end def power2(other) if other.kind_of?(Rational) if self < 0 return Complex(self, 0) ** other elsif other == 0 return Rational(1,1) elsif self == 0 return Rational(0,1) elsif self == 1 return Rational(1,1) end dem = nil x = self.denominator.to_f.to_i neard = self.denominator.to_f ** (1.0/other.denominator.to_f) loop do if (neard**other.denominator == self.denominator) dem = neaed break end end nearn = self.numerator.to_f ** (1.0/other.denominator.to_f) Rational(num,den) elsif other.kind_of?(Integer) if other > 0 num = numerator ** other den = denominator ** other elsif other < 0 num = denominator ** -other den = numerator ** -other elsif other == 0 num = 1 den = 1 end Rational.new!(num, den) elsif other.kind_of?(Float) Float(self) ** other else x , y = other.coerce(self) x ** y end end end module Math def sqrt(a) if a.kind_of?(Complex) abs = sqrt(a.real*a.real + a.image*a.image) # if not abs.kind_of?(Rational) # return a**Rational(1,2) # end x = sqrt((a.real + abs)/Rational(2)) y = sqrt((-a.real + abs)/Rational(2)) # if !(x.kind_of?(Rational) and y.kind_of?(Rational)) # return a**Rational(1,2) # end if a.image >= 0 Complex(x, y) else Complex(x, -y) end elsif a >= 0 rsqrt(a) else Complex(0,rsqrt(-a)) end end def rsqrt(a) if a.kind_of?(Float) sqrt!(a) elsif a.kind_of?(Rational) rsqrt(a.numerator)/rsqrt(a.denominator) else src = a max = 2 ** 32 byte_a = [src & 0xffffffff] # ruby's bug while (src >= max) and (src >>= 32) byte_a.unshift src & 0xffffffff end answer = 0 main = 0 side = 0 for elm in byte_a main = (main << 32) + elm side <<= 16 if answer != 0 if main * 4 < side * side applo = main.div(side) else applo = ((sqrt!(side * side + 4 * main) - side)/2.0).to_i + 1 end else applo = sqrt!(main).to_i + 1 end while (x = (side + applo) * applo) > main applo -= 1 end main -= x answer = (answer << 16) + applo side += applo * 2 end if main == 0 answer else sqrt!(a) end end end module_function :sqrt module_function :rsqrt end class Complex Unify = true end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/Win32API.rb
tools/jruby-1.5.1/lib/ruby/1.8/Win32API.rb
require 'rbconfig' raise LoadError.new("Win32API only supported on win32") unless Config::CONFIG['host_os'] =~ /mswin/ require 'ffi-internal.so' class Win32API SUFFIXES = $KCODE == 'UTF8' ? [ '', 'W', 'A' ] : [ '', 'A', 'W' ] TypeDefs = { '0' => FFI::Type::VOID, 'V' => FFI::Type::VOID, 'P' => FFI::Type::WIN32PTR, 'I' => FFI::Type::INT, 'N' => FFI::Type::INT, 'L' => FFI::Type::INT, } def self.find_type(name) code = TypeDefs[name] || TypeDefs[name.upcase] raise TypeError, "Unable to resolve type '#{name}'" unless code return code end def self.map_types(spec) if spec.kind_of?(String) spec.split(//) elsif spec.kind_of?(Array) spec else raise ArgumentError.new("invalid parameter types specification") end.map { |c| self.find_type(c) } end def self.map_library_name(lib) # Mangle the library name to reflect the native library naming conventions if lib && File.basename(lib) == lib ext = ".#{FFI::Platform::LIBSUFFIX}" lib = FFI::Platform::LIBPREFIX + lib unless lib =~ /^#{FFI::Platform::LIBPREFIX}/ lib += ext unless lib =~ /#{ext}/ end lib end def initialize(lib, func, params, ret='L', calltype = :stdcall) @lib = lib @func = func @params = params @return = ret # # Attach the method as 'call', so it gets all the froody arity-splitting optimizations # @lib = FFI::DynamicLibrary.open(Win32API.map_library_name(lib), FFI::DynamicLibrary::RTLD_LAZY | FFI::DynamicLibrary::RTLD_GLOBAL) SUFFIXES.each do |suffix| sym = @lib.find_function(func.to_s + suffix) if sym options = { :convention => calltype } @ffi_func = FFI::Function.new(Win32API.find_type(ret), Win32API.map_types(params), sym, options) @ffi_func.attach(self, :call) self.instance_eval("alias :Call :call") break end end raise LoadError.new("Could not locate #{func}") unless @ffi_func end def inspect params = [] if @params.kind_of?(String) @params.each_byte { |c| params << TypeDefs[c.chr] } else params = @params.map { |p| TypeDefs[p]} end "#<Win32API::#{@func} library=#{@lib} function=#{@func} parameters=[ #{params.join(',')} ], return=#{Win32API.find_type(@return)}>" end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/cgi-lib.rb
tools/jruby-1.5.1/lib/ruby/1.8/cgi-lib.rb
warn "Warning:#{caller[0].sub(/:in `.*'\z/, '')}: cgi-lib is deprecated after Ruby 1.8.1; use cgi instead" =begin = simple CGI support library = example == get form values require "cgi-lib.rb" query = CGI.new query['field'] # <== value of 'field' query.keys # <== array of fields and query has Hash class methods == get cookie values require "cgi-lib.rb" query = CGI.new query.cookie['name'] # <== cookie value of 'name' query.cookie.keys # <== all cookie names and query.cookie has Hash class methods == print HTTP header and HTML string to $> require "cgi-lib.rb" CGI::print{ CGI::tag("HTML"){ CGI::tag("HEAD"){ CGI::tag("TITLE"){"TITLE"} } + CGI::tag("BODY"){ CGI::tag("FORM", {"ACTION"=>"test.rb", "METHOD"=>"POST"}){ CGI::tag("INPUT", {"TYPE"=>"submit", "VALUE"=>"submit"}) } + CGI::tag("HR") } } } == make raw cookie string require "cgi-lib.rb" cookie1 = CGI::cookie({'name' => 'name', 'value' => 'value', 'path' => 'path', # optional 'domain' => 'domain', # optional 'expires' => Time.now, # optional 'secure' => true # optional }) CGI::print("Content-Type: text/html", cookie1, cookie2){ "string" } == print HTTP header and string to $> require "cgi-lib.rb" CGI::print{ "string" } # == CGI::print("Content-Type: text/html"){ "string" } CGI::print("Content-Type: text/html", cookie1, cookie2){ "string" } === NPH (no-parse-header) mode require "cgi-lib.rb" CGI::print("nph"){ "string" } # == CGI::print("nph", "Content-Type: text/html"){ "string" } CGI::print("nph", "Content-Type: text/html", cookie1, cookie2){ "string" } == make HTML tag string require "cgi-lib.rb" CGI::tag("element", {"attribute_name"=>"attribute_value"}){"content"} == make HTTP header string require "cgi-lib.rb" CGI::header # == CGI::header("Content-Type: text/html") CGI::header("Content-Type: text/html", cookie1, cookie2) === NPH (no-parse-header) mode CGI::header("nph") # == CGI::header("nph", "Content-Type: text/html") CGI::header("nph", "Content-Type: text/html", cookie1, cookie2) == escape url encode require "cgi-lib.rb" url_encoded_string = CGI::escape("string") == unescape url encoded require "cgi-lib.rb" string = CGI::unescape("url encoded string") == escape HTML &"<> require "cgi-lib.rb" CGI::escapeHTML("string") =end require "delegate" class CGI < SimpleDelegator CR = "\015" LF = "\012" EOL = CR + LF RFC822_DAYS = %w[ Sun Mon Tue Wed Thu Fri Sat ] RFC822_MONTHS = %w[ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ] # make rfc1123 date string def CGI::rfc1123_date(time) t = time.clone.gmtime return format("%s, %.2d %s %d %.2d:%.2d:%.2d GMT", RFC822_DAYS[t.wday], t.day, RFC822_MONTHS[t.month-1], t.year, t.hour, t.min, t.sec) end # escape url encode def CGI::escape(str) str.gsub(/[^a-zA-Z0-9_\-.]/n){ sprintf("%%%02X", $&.unpack("C")[0]) } end # unescape url encoded def CGI::unescape(str) str.gsub(/\+/, ' ').gsub(/%([0-9a-fA-F]{2})/){ [$1.hex].pack("c") } end # escape HTML def CGI::escapeHTML(str) str.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;") end # offline mode. read name=value pairs on standard input. def read_from_cmdline require "shellwords.rb" words = Shellwords.shellwords( if not ARGV.empty? ARGV.join(' ') else STDERR.print "(offline mode: enter name=value pairs on standard input)\n" if STDIN.tty? readlines.join(' ').gsub(/\n/, '') end.gsub(/\\=/, '%3D').gsub(/\\&/, '%26')) if words.find{|x| x =~ /=/} then words.join('&') else words.join('+') end end def initialize(input = $stdin) @inputs = {} @cookie = {} case ENV['REQUEST_METHOD'] when "GET" ENV['QUERY_STRING'] or "" when "POST" input.read(Integer(ENV['CONTENT_LENGTH'])) or "" else read_from_cmdline end.split(/[&;]/).each do |x| key, val = x.split(/=/,2).collect{|x|CGI::unescape(x)} if @inputs.include?(key) @inputs[key] += "\0" + (val or "") else @inputs[key] = (val or "") end end super(@inputs) if ENV.has_key?('HTTP_COOKIE') or ENV.has_key?('COOKIE') (ENV['HTTP_COOKIE'] or ENV['COOKIE']).split(/; /).each do |x| key, val = x.split(/=/,2) key = CGI::unescape(key) val = val.split(/&/).collect{|x|CGI::unescape(x)}.join("\0") if @cookie.include?(key) @cookie[key] += "\0" + val else @cookie[key] = val end end end end attr("inputs") attr("cookie") # make HTML tag string def CGI::tag(element, attributes = {}) "<" + escapeHTML(element) + attributes.collect{|name, value| " " + escapeHTML(name) + '="' + escapeHTML(value) + '"' }.to_s + ">" + (iterator? ? yield.to_s + "</" + escapeHTML(element) + ">" : "") end # make raw cookie string def CGI::cookie(options) "Set-Cookie: " + options['name'] + '=' + escape(options['value']) + (options['domain'] ? '; domain=' + options['domain'] : '') + (options['path'] ? '; path=' + options['path'] : '') + (options['expires'] ? '; expires=' + rfc1123_date(options['expires']) : '') + (options['secure'] ? '; secure' : '') end # make HTTP header string def CGI::header(*options) if defined?(MOD_RUBY) options.each{|option| option.sub(/(.*?): (.*)/){ Apache::request.headers_out[$1] = $2 } } Apache::request.send_http_header '' else if options.delete("nph") or (ENV['SERVER_SOFTWARE'] =~ /IIS/) [(ENV['SERVER_PROTOCOL'] or "HTTP/1.0") + " 200 OK", "Date: " + rfc1123_date(Time.now), "Server: " + (ENV['SERVER_SOFTWARE'] or ""), "Connection: close"] + (options.empty? ? ["Content-Type: text/html"] : options) else options.empty? ? ["Content-Type: text/html"] : options end.join(EOL) + EOL + EOL end end # print HTTP header and string to $> def CGI::print(*options) $>.print CGI::header(*options) + yield.to_s end # print message to $> def CGI::message(message, title = "", header = ["Content-Type: text/html"]) if message.kind_of?(Hash) title = message['title'] header = message['header'] message = message['body'] end CGI::print(*header){ CGI::tag("HTML"){ CGI::tag("HEAD"){ CGI.tag("TITLE"){ title } } + CGI::tag("BODY"){ message } } } true end # print error message to $> and exit def CGI::error CGI::message({'title'=>'ERROR', 'body'=> CGI::tag("PRE"){ "ERROR: " + CGI::tag("STRONG"){ escapeHTML($!.to_s) } + "\n" + escapeHTML($@.join("\n")) } }) exit end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/readbytes.rb
tools/jruby-1.5.1/lib/ruby/1.8/readbytes.rb
# TruncatedDataError is raised when IO#readbytes fails to read enough data. class TruncatedDataError<IOError def initialize(mesg, data) # :nodoc: @data = data super(mesg) end # The read portion of an IO#readbytes attempt. attr_reader :data end class IO # Reads exactly +n+ bytes. # # If the data read is nil an EOFError is raised. # # If the data read is too short a TruncatedDataError is raised and the read # data is obtainable via its #data method. def readbytes(n) str = read(n) if str == nil raise EOFError, "End of file reached" end if str.size < n raise TruncatedDataError.new("data truncated", str) end str end end if __FILE__ == $0 begin loop do print STDIN.readbytes(6) end rescue TruncatedDataError p $!.data raise end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/thwait.rb
tools/jruby-1.5.1/lib/ruby/1.8/thwait.rb
# # thwait.rb - thread synchronization class # $Release Version: 0.9 $ # $Revision: 1.3 $ # $Date: 1998/06/26 03:19:34 $ # by Keiju ISHITSUKA(Nihpon Rational Software Co.,Ltd.) # # -- # feature: # provides synchronization for multiple threads. # # class methods: # * ThreadsWait.all_waits(thread1,...) # waits until all of specified threads are terminated. # if a block is supplied for the method, evaluates it for # each thread termination. # * th = ThreadsWait.new(thread1,...) # creates synchronization object, specifying thread(s) to wait. # # methods: # * th.threads # list threads to be synchronized # * th.empty? # is there any thread to be synchronized. # * th.finished? # is there already terminated thread. # * th.join(thread1,...) # wait for specified thread(s). # * th.join_nowait(threa1,...) # specifies thread(s) to wait. non-blocking. # * th.next_wait # waits until any of specified threads is terminated. # * th.all_waits # waits until all of specified threads are terminated. # if a block is supplied for the method, evaluates it for # each thread termination. # require "thread.rb" require "e2mmap.rb" # # This class watches for termination of multiple threads. Basic functionality # (wait until specified threads have terminated) can be accessed through the # class method ThreadsWait::all_waits. Finer control can be gained using # instance methods. # # Example: # # ThreadsWait.all_wait(thr1, thr2, ...) do |t| # STDERR.puts "Thread #{t} has terminated." # end # class ThreadsWait RCS_ID='-$Id: thwait.rb,v 1.3 1998/06/26 03:19:34 keiju Exp keiju $-' Exception2MessageMapper.extend_to(binding) def_exception("ErrNoWaitingThread", "No threads for waiting.") def_exception("ErrNoFinishedThread", "No finished threads.") # # Waits until all specified threads have terminated. If a block is provided, # it is executed for each thread termination. # def ThreadsWait.all_waits(*threads) # :yield: thread tw = ThreadsWait.new(*threads) if block_given? tw.all_waits do |th| yield th end else tw.all_waits end end # # Creates a ThreadsWait object, specifying the threads to wait on. # Non-blocking. # def initialize(*threads) @threads = [] @wait_queue = Queue.new join_nowait(*threads) unless threads.empty? end # Returns the array of threads in the wait queue. attr :threads # # Returns +true+ if there are no threads to be synchronized. # def empty? @threads.empty? end # # Returns +true+ if any thread has terminated. # def finished? !@wait_queue.empty? end # # Waits for specified threads to terminate. # def join(*threads) join_nowait(*threads) next_wait end # # Specifies the threads that this object will wait for, but does not actually # wait. # def join_nowait(*threads) threads.flatten! @threads.concat threads for th in threads Thread.start(th) do |t| begin t.join ensure @wait_queue.push t end end end end # # Waits until any of the specified threads has terminated, and returns the one # that does. # # If there is no thread to wait, raises +ErrNoWaitingThread+. If +nonblock+ # is true, and there is no terminated thread, raises +ErrNoFinishedThread+. # def next_wait(nonblock = nil) ThreadsWait.fail ErrNoWaitingThread if @threads.empty? begin @threads.delete(th = @wait_queue.pop(nonblock)) th rescue ThreadError ThreadsWait.fail ErrNoFinishedThread end end # # Waits until all of the specified threads are terminated. If a block is # supplied for the method, it is executed for each thread termination. # # Raises exceptions in the same manner as +next_wait+. # def all_waits until @threads.empty? th = next_wait yield th if block_given? end end end ThWait = ThreadsWait # Documentation comments: # - Source of documentation is evenly split between Nutshell, existing # comments, and my own rephrasing. # - I'm not particularly confident that the comments are all exactly correct. # - The history, etc., up the top appears in the RDoc output. Perhaps it would # be better to direct that not to appear, and put something else there # instead.
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/profiler.rb
tools/jruby-1.5.1/lib/ruby/1.8/profiler.rb
module Profiler__ # internal values @@start = @@stack = @@map = nil PROFILE_PROC = proc{|event, file, line, id, binding, klass| case event when "call", "c-call" now = Process.times[0] @@stack.push [now, 0.0] when "return", "c-return" now = Process.times[0] key = [klass, id] if tick = @@stack.pop data = (@@map[key] ||= [0, 0.0, 0.0, key]) data[0] += 1 cost = now - tick[0] data[1] += cost data[2] += cost - tick[1] @@stack[-1][1] += cost if @@stack[-1] end end } module_function def start_profile @@start = Process.times[0] @@stack = [] @@map = {} set_trace_func PROFILE_PROC end def stop_profile set_trace_func nil end def print_profile(f) stop_profile total = Process.times[0] - @@start if total == 0 then total = 0.01 end data = @@map.values data.sort!{|a,b| b[2] <=> a[2]} sum = 0 f.printf " %% cumulative self self total\n" f.printf " time seconds seconds calls ms/call ms/call name\n" for d in data sum += d[2] f.printf "%6.2f %8.2f %8.2f %8d ", d[2]/total*100, sum, d[2], d[0] f.printf "%8.2f %8.2f %s\n", d[2]*1000/d[0], d[1]*1000/d[0], get_name(*d[3]) end f.printf "%6.2f %8.2f %8.2f %8d ", 0.0, total, 0.0, 1 # ??? f.printf "%8.2f %8.2f %s\n", 0.0, total*1000, "#toplevel" # ??? end def get_name(klass, id) name = klass.to_s || "" if klass.kind_of? Class name += "#" else name += "." end name + id.id2name end private :get_name end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/expect.rb
tools/jruby-1.5.1/lib/ruby/1.8/expect.rb
$expect_verbose = false class IO def expect(pat,timeout=9999999) buf = '' case pat when String e_pat = Regexp.new(Regexp.quote(pat)) when Regexp e_pat = pat end while true if !IO.select([self],nil,nil,timeout) or eof? then result = nil break end c = getc.chr buf << c if $expect_verbose STDOUT.print c STDOUT.flush end if mat=e_pat.match(buf) then result = [buf,*mat.to_a[1..-1]] break end end if block_given? then yield result else return result end nil end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/importenv.rb
tools/jruby-1.5.1/lib/ruby/1.8/importenv.rb
# importenv.rb -- imports environment variables as global variables, Perlish ;( # # Usage: # # require 'importenv' # p $USER # $USER = "matz" # p ENV["USER"] warn "Warning:#{caller[0].sub(/:in `.*'\z/, '')}: importenv is deprecated after Ruby 1.8.1 (no replacement)" for k,v in ENV next unless /^[a-zA-Z][_a-zA-Z0-9]*/ =~ k eval <<EOS $#{k} = v trace_var "$#{k}", proc{|v| ENV[%q!#{k}!] = v $#{k} = v if v == nil untrace_var "$#{k}" end } EOS end if __FILE__ == $0 p $TERM $TERM = nil p $TERM p ENV["TERM"] $TERM = "foo" p ENV["TERM"] end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/resolv.rb
tools/jruby-1.5.1/lib/ruby/1.8/resolv.rb
require 'socket' require 'fcntl' require 'timeout' require 'thread' begin require 'securerandom' rescue LoadError end # Resolv is a thread-aware DNS resolver library written in Ruby. Resolv can # handle multiple DNS requests concurrently without blocking. The ruby # interpreter. # # See also resolv-replace.rb to replace the libc resolver with # Resolv. # # Resolv can look up various DNS resources using the DNS module directly. # # Examples: # # p Resolv.getaddress "www.ruby-lang.org" # p Resolv.getname "210.251.121.214" # # Resolv::DNS.open do |dns| # ress = dns.getresources "www.ruby-lang.org", Resolv::DNS::Resource::IN::A # p ress.map { |r| r.address } # ress = dns.getresources "ruby-lang.org", Resolv::DNS::Resource::IN::MX # p ress.map { |r| [r.exchange.to_s, r.preference] } # end # # # == Bugs # # * NIS is not supported. # * /etc/nsswitch.conf is not supported. class Resolv ## # Looks up the first IP address for +name+. def self.getaddress(name) DefaultResolver.getaddress(name) end ## # Looks up all IP address for +name+. def self.getaddresses(name) DefaultResolver.getaddresses(name) end ## # Iterates over all IP addresses for +name+. def self.each_address(name, &block) DefaultResolver.each_address(name, &block) end ## # Looks up the hostname of +address+. def self.getname(address) DefaultResolver.getname(address) end ## # Looks up all hostnames for +address+. def self.getnames(address) DefaultResolver.getnames(address) end ## # Iterates over all hostnames for +address+. def self.each_name(address, &proc) DefaultResolver.each_name(address, &proc) end ## # Creates a new Resolv using +resolvers+. def initialize(resolvers=[Hosts.new, DNS.new]) @resolvers = resolvers end ## # Looks up the first IP address for +name+. def getaddress(name) each_address(name) {|address| return address} raise ResolvError.new("no address for #{name}") end ## # Looks up all IP address for +name+. def getaddresses(name) ret = [] each_address(name) {|address| ret << address} return ret end ## # Iterates over all IP addresses for +name+. def each_address(name) if AddressRegex =~ name yield name return end yielded = false @resolvers.each {|r| r.each_address(name) {|address| yield address.to_s yielded = true } return if yielded } end ## # Looks up the hostname of +address+. def getname(address) each_name(address) {|name| return name} raise ResolvError.new("no name for #{address}") end ## # Looks up all hostnames for +address+. def getnames(address) ret = [] each_name(address) {|name| ret << name} return ret end ## # Iterates over all hostnames for +address+. def each_name(address) yielded = false @resolvers.each {|r| r.each_name(address) {|name| yield name.to_s yielded = true } return if yielded } end ## # Indicates a failure to resolve a name or address. class ResolvError < StandardError; end ## # Indicates a timeout resolving a name or address. class ResolvTimeout < TimeoutError; end ## # DNS::Hosts is a hostname resolver that uses the system hosts file. class Hosts require 'rbconfig' if /mswin32|cygwin|mingw|bccwin/ =~ RUBY_PLATFORM || ::Config::CONFIG['host_os'] =~ /mswin/ require 'win32/resolv' DefaultFileName = Win32::Resolv.get_hosts_path else DefaultFileName = '/etc/hosts' end ## # Creates a new DNS::Hosts, using +filename+ for its data source. def initialize(filename = DefaultFileName) @filename = filename @mutex = Mutex.new @initialized = nil end def lazy_initialize # :nodoc: @mutex.synchronize { unless @initialized @name2addr = {} @addr2name = {} open(@filename) {|f| f.each {|line| line.sub!(/#.*/, '') addr, hostname, *aliases = line.split(/\s+/) next unless addr addr.untaint hostname.untaint @addr2name[addr] = [] unless @addr2name.include? addr @addr2name[addr] << hostname @addr2name[addr] += aliases @name2addr[hostname] = [] unless @name2addr.include? hostname @name2addr[hostname] << addr aliases.each {|n| n.untaint @name2addr[n] = [] unless @name2addr.include? n @name2addr[n] << addr } } } @name2addr.each {|name, arr| arr.reverse!} @initialized = true end } self end ## # Gets the IP address of +name+ from the hosts file. def getaddress(name) each_address(name) {|address| return address} raise ResolvError.new("#{@filename} has no name: #{name}") end ## # Gets all IP addresses for +name+ from the hosts file. def getaddresses(name) ret = [] each_address(name) {|address| ret << address} return ret end ## # Iterates over all IP addresses for +name+ retrieved from the hosts file. def each_address(name, &proc) lazy_initialize if @name2addr.include?(name) @name2addr[name].each(&proc) end end ## # Gets the hostname of +address+ from the hosts file. def getname(address) each_name(address) {|name| return name} raise ResolvError.new("#{@filename} has no address: #{address}") end ## # Gets all hostnames for +address+ from the hosts file. def getnames(address) ret = [] each_name(address) {|name| ret << name} return ret end ## # Iterates over all hostnames for +address+ retrieved from the hosts file. def each_name(address, &proc) lazy_initialize if @addr2name.include?(address) @addr2name[address].each(&proc) end end end ## # Resolv::DNS is a DNS stub resolver. # # Information taken from the following places: # # * STD0013 # * RFC 1035 # * ftp://ftp.isi.edu/in-notes/iana/assignments/dns-parameters # * etc. class DNS ## # Default DNS Port Port = 53 ## # Default DNS UDP packet size UDPSize = 512 ## # Group of DNS resolver threads (obsolete) DNSThreadGroup = ThreadGroup.new ## # Creates a new DNS resolver. See Resolv::DNS.new for argument details. # # Yields the created DNS resolver to the block, if given, otherwise # returns it. def self.open(*args) dns = new(*args) return dns unless block_given? begin yield dns ensure dns.close end end ## # Creates a new DNS resolver. # # +config_info+ can be: # # nil:: Uses /etc/resolv.conf. # String:: Path to a file using /etc/resolv.conf's format. # Hash:: Must contain :nameserver, :search and :ndots keys. # # Example: # # Resolv::DNS.new(:nameserver => ['210.251.121.21'], # :search => ['ruby-lang.org'], # :ndots => 1) def initialize(config_info=nil) @mutex = Mutex.new @config = Config.new(config_info) @initialized = nil end def lazy_initialize # :nodoc: @mutex.synchronize { unless @initialized @config.lazy_initialize @initialized = true end } self end ## # Closes the DNS resolver. def close @mutex.synchronize { if @initialized @initialized = false end } end ## # Gets the IP address of +name+ from the DNS resolver. # # +name+ can be a Resolv::DNS::Name or a String. Retrieved address will # be a Resolv::IPv4 or Resolv::IPv6 def getaddress(name) each_address(name) {|address| return address} raise ResolvError.new("DNS result has no information for #{name}") end ## # Gets all IP addresses for +name+ from the DNS resolver. # # +name+ can be a Resolv::DNS::Name or a String. Retrieved addresses will # be a Resolv::IPv4 or Resolv::IPv6 def getaddresses(name) ret = [] each_address(name) {|address| ret << address} return ret end ## # Iterates over all IP addresses for +name+ retrieved from the DNS # resolver. # # +name+ can be a Resolv::DNS::Name or a String. Retrieved addresses will # be a Resolv::IPv4 or Resolv::IPv6 def each_address(name) each_resource(name, Resource::IN::A) {|resource| yield resource.address} each_resource(name, Resource::IN::AAAA) {|resource| yield resource.address} end ## # Gets the hostname for +address+ from the DNS resolver. # # +address+ must be a Resolv::IPv4, Resolv::IPv6 or a String. Retrieved # name will be a Resolv::DNS::Name. def getname(address) each_name(address) {|name| return name} raise ResolvError.new("DNS result has no information for #{address}") end ## # Gets all hostnames for +address+ from the DNS resolver. # # +address+ must be a Resolv::IPv4, Resolv::IPv6 or a String. Retrieved # names will be Resolv::DNS::Name instances. def getnames(address) ret = [] each_name(address) {|name| ret << name} return ret end ## # Iterates over all hostnames for +address+ retrieved from the DNS # resolver. # # +address+ must be a Resolv::IPv4, Resolv::IPv6 or a String. Retrieved # names will be Resolv::DNS::Name instances. def each_name(address) case address when Name ptr = address when IPv4::Regex ptr = IPv4.create(address).to_name when IPv6::Regex ptr = IPv6.create(address).to_name else raise ResolvError.new("cannot interpret as address: #{address}") end each_resource(ptr, Resource::IN::PTR) {|resource| yield resource.name} end ## # Look up the +typeclass+ DNS resource of +name+. # # +name+ must be a Resolv::DNS::Name or a String. # # +typeclass+ should be one of the following: # # * Resolv::DNS::Resource::IN::A # * Resolv::DNS::Resource::IN::AAAA # * Resolv::DNS::Resource::IN::ANY # * Resolv::DNS::Resource::IN::CNAME # * Resolv::DNS::Resource::IN::HINFO # * Resolv::DNS::Resource::IN::MINFO # * Resolv::DNS::Resource::IN::MX # * Resolv::DNS::Resource::IN::NS # * Resolv::DNS::Resource::IN::PTR # * Resolv::DNS::Resource::IN::SOA # * Resolv::DNS::Resource::IN::TXT # * Resolv::DNS::Resource::IN::WKS # # Returned resource is represented as a Resolv::DNS::Resource instance, # i.e. Resolv::DNS::Resource::IN::A. def getresource(name, typeclass) each_resource(name, typeclass) {|resource| return resource} raise ResolvError.new("DNS result has no information for #{name}") end ## # Looks up all +typeclass+ DNS resources for +name+. See #getresource for # argument details. def getresources(name, typeclass) ret = [] each_resource(name, typeclass) {|resource| ret << resource} return ret end ## # Iterates over all +typeclass+ DNS resources for +name+. See # #getresource for argument details. def each_resource(name, typeclass, &proc) lazy_initialize requester = make_requester senders = {} begin @config.resolv(name) {|candidate, tout, nameserver| msg = Message.new msg.rd = 1 msg.add_question(candidate, typeclass) unless sender = senders[[candidate, nameserver]] sender = senders[[candidate, nameserver]] = requester.sender(msg, candidate, nameserver) end reply, reply_name = requester.request(sender, tout) case reply.rcode when RCode::NoError extract_resources(reply, reply_name, typeclass, &proc) return when RCode::NXDomain raise Config::NXDomain.new(reply_name.to_s) else raise Config::OtherResolvError.new(reply_name.to_s) end } ensure requester.close end end def make_requester # :nodoc: if nameserver = @config.single? Requester::ConnectedUDP.new(nameserver) else Requester::UnconnectedUDP.new end end def extract_resources(msg, name, typeclass) # :nodoc: if typeclass < Resource::ANY n0 = Name.create(name) msg.each_answer {|n, ttl, data| yield data if n0 == n } end yielded = false n0 = Name.create(name) msg.each_answer {|n, ttl, data| if n0 == n case data when typeclass yield data yielded = true when Resource::CNAME n0 = data.name end end } return if yielded msg.each_answer {|n, ttl, data| if n0 == n case data when typeclass yield data end end } end if defined? SecureRandom def self.random(arg) # :nodoc: begin SecureRandom.random_number(arg) rescue NotImplementedError rand(arg) end end else def self.random(arg) # :nodoc: rand(arg) end end def self.rangerand(range) # :nodoc: base = range.begin len = range.end - range.begin if !range.exclude_end? len += 1 end base + random(len) end RequestID = {} RequestIDMutex = Mutex.new def self.allocate_request_id(host, port) # :nodoc: id = nil RequestIDMutex.synchronize { h = (RequestID[[host, port]] ||= {}) begin id = rangerand(0x0000..0xffff) end while h[id] h[id] = true } id end def self.free_request_id(host, port, id) # :nodoc: RequestIDMutex.synchronize { key = [host, port] if h = RequestID[key] h.delete id if h.empty? RequestID.delete key end end } end def self.bind_random_port(udpsock, is_ipv6=false) # :nodoc: begin port = rangerand(1024..65535) udpsock.bind(is_ipv6 ? "::" : "", port) rescue Errno::EADDRINUSE retry end end class Requester # :nodoc: def initialize @senders = {} @sock = nil end def request(sender, tout) timelimit = Time.now + tout sender.send while (now = Time.now) < timelimit timeout = timelimit - now if !IO.select([@sock], nil, nil, timeout) raise ResolvTimeout end reply, from = recv_reply begin msg = Message.decode(reply) rescue DecodeError next # broken DNS message ignored end if s = @senders[[from,msg.id]] break else # unexpected DNS message ignored end end return msg, s.data end def close sock = @sock @sock = nil sock.close if sock end class Sender # :nodoc: def initialize(msg, data, sock) @msg = msg @data = data @sock = sock end end class UnconnectedUDP < Requester # :nodoc: def initialize super() @sock = UDPSocket.new @sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) if defined? Fcntl::F_SETFD DNS.bind_random_port(@sock) end def recv_reply reply, from = @sock.recvfrom(UDPSize) return reply, [from[3],from[1]] end def sender(msg, data, host, port=Port) service = [host, port] id = DNS.allocate_request_id(host, port) request = msg.encode request[0,2] = [id].pack('n') return @senders[[service, id]] = Sender.new(request, data, @sock, host, port) end def close super @senders.each_key {|service, id| DNS.free_request_id(service[0], service[1], id) } end class Sender < Requester::Sender # :nodoc: def initialize(msg, data, sock, host, port) super(msg, data, sock) @host = host @port = port end attr_reader :data def send @sock.send(@msg, 0, @host, @port) end end end class ConnectedUDP < Requester # :nodoc: def initialize(host, port=Port) super() @host = host @port = port is_ipv6 = host.index(':') @sock = UDPSocket.new(is_ipv6 ? Socket::AF_INET6 : Socket::AF_INET) DNS.bind_random_port(@sock, is_ipv6) @sock.connect(host, port) @sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) if defined? Fcntl::F_SETFD end def recv_reply reply = @sock.recv(UDPSize) return reply, nil end def sender(msg, data, host=@host, port=@port) unless host == @host && port == @port raise RequestError.new("host/port don't match: #{host}:#{port}") end id = DNS.allocate_request_id(@host, @port) request = msg.encode request[0,2] = [id].pack('n') return @senders[[nil,id]] = Sender.new(request, data, @sock) end def close super @senders.each_key {|from, id| DNS.free_request_id(@host, @port, id) } end class Sender < Requester::Sender # :nodoc: def send @sock.send(@msg, 0) end attr_reader :data end end class TCP < Requester # :nodoc: def initialize(host, port=Port) super() @host = host @port = port @sock = TCPSocket.new(@host, @port) @sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) if defined? Fcntl::F_SETFD @senders = {} end def recv_reply len = @sock.read(2).unpack('n')[0] reply = @sock.read(len) return reply, nil end def sender(msg, data, host=@host, port=@port) unless host == @host && port == @port raise RequestError.new("host/port don't match: #{host}:#{port}") end id = DNS.allocate_request_id(@host, @port) request = msg.encode request[0,2] = [request.length, id].pack('nn') return @senders[[nil,id]] = Sender.new(request, data, @sock) end class Sender < Requester::Sender # :nodoc: def send @sock.print(@msg) @sock.flush end attr_reader :data end def close super @senders.each_key {|from,id| DNS.free_request_id(@host, @port, id) } end end ## # Indicates a problem with the DNS request. class RequestError < StandardError end end class Config # :nodoc: def initialize(config_info=nil) @mutex = Mutex.new @config_info = config_info @initialized = nil end def Config.parse_resolv_conf(filename) nameserver = [] search = nil ndots = 1 open(filename) {|f| f.each {|line| line.sub!(/[#;].*/, '') keyword, *args = line.split(/\s+/) args.each { |arg| arg.untaint } next unless keyword case keyword when 'nameserver' nameserver += args when 'domain' next if args.empty? search = [args[0]] when 'search' next if args.empty? search = args when 'options' args.each {|arg| case arg when /\Andots:(\d+)\z/ ndots = $1.to_i end } end } } return { :nameserver => nameserver, :search => search, :ndots => ndots } end def Config.default_config_hash(filename="/etc/resolv.conf") if File.exist? filename config_hash = Config.parse_resolv_conf(filename) else require 'rbconfig' if /mswin32|cygwin|mingw|bccwin/ =~ RUBY_PLATFORM || ::Config::CONFIG['host_os'] =~ /mswin/ require 'win32/resolv' search, nameserver = Win32::Resolv.get_resolv_info config_hash = {} config_hash[:nameserver] = nameserver if nameserver config_hash[:search] = [search].flatten if search end end config_hash end def lazy_initialize @mutex.synchronize { unless @initialized @nameserver = [] @search = nil @ndots = 1 case @config_info when nil config_hash = Config.default_config_hash when String config_hash = Config.parse_resolv_conf(@config_info) when Hash config_hash = @config_info.dup if String === config_hash[:nameserver] config_hash[:nameserver] = [config_hash[:nameserver]] end if String === config_hash[:search] config_hash[:search] = [config_hash[:search]] end else raise ArgumentError.new("invalid resolv configuration: #{@config_info.inspect}") end @nameserver = config_hash[:nameserver] if config_hash.include? :nameserver @search = config_hash[:search] if config_hash.include? :search @ndots = config_hash[:ndots] if config_hash.include? :ndots @nameserver = ['0.0.0.0'] if @nameserver.empty? if @search @search = @search.map {|arg| Label.split(arg) } else hostname = Socket.gethostname if /\./ =~ hostname @search = [Label.split($')] else @search = [[]] end end if !@nameserver.kind_of?(Array) || !@nameserver.all? {|ns| String === ns } raise ArgumentError.new("invalid nameserver config: #{@nameserver.inspect}") end if !@search.kind_of?(Array) || !@search.all? {|ls| ls.all? {|l| Label::Str === l } } raise ArgumentError.new("invalid search config: #{@search.inspect}") end if !@ndots.kind_of?(Integer) raise ArgumentError.new("invalid ndots config: #{@ndots.inspect}") end @initialized = true end } self end def single? lazy_initialize if @nameserver.length == 1 return @nameserver[0] else return nil end end def generate_candidates(name) candidates = nil name = Name.create(name) if name.absolute? candidates = [name] else if @ndots <= name.length - 1 candidates = [Name.new(name.to_a)] else candidates = [] end candidates.concat(@search.map {|domain| Name.new(name.to_a + domain)}) end return candidates end InitialTimeout = 5 def generate_timeouts ts = [InitialTimeout] ts << ts[-1] * 2 / @nameserver.length ts << ts[-1] * 2 ts << ts[-1] * 2 return ts end def resolv(name) candidates = generate_candidates(name) timeouts = generate_timeouts begin candidates.each {|candidate| begin timeouts.each {|tout| @nameserver.each {|nameserver| begin yield candidate, tout, nameserver rescue ResolvTimeout end } } raise ResolvError.new("DNS resolv timeout: #{name}") rescue NXDomain end } rescue ResolvError end end ## # Indicates no such domain was found. class NXDomain < ResolvError end ## # Indicates some other unhandled resolver error was encountered. class OtherResolvError < ResolvError end end module OpCode # :nodoc: Query = 0 IQuery = 1 Status = 2 Notify = 4 Update = 5 end module RCode # :nodoc: NoError = 0 FormErr = 1 ServFail = 2 NXDomain = 3 NotImp = 4 Refused = 5 YXDomain = 6 YXRRSet = 7 NXRRSet = 8 NotAuth = 9 NotZone = 10 BADVERS = 16 BADSIG = 16 BADKEY = 17 BADTIME = 18 BADMODE = 19 BADNAME = 20 BADALG = 21 end ## # Indicates that the DNS response was unable to be decoded. class DecodeError < StandardError end ## # Indicates that the DNS request was unable to be encoded. class EncodeError < StandardError end module Label # :nodoc: def self.split(arg) labels = [] arg.scan(/[^\.]+/) {labels << Str.new($&)} return labels end class Str # :nodoc: def initialize(string) @string = string @downcase = string.downcase end attr_reader :string, :downcase def to_s return @string end def inspect return "#<#{self.class} #{self.to_s}>" end def ==(other) return @downcase == other.downcase end def eql?(other) return self == other end def hash return @downcase.hash end end end ## # A representation of a DNS name. class Name ## # Creates a new DNS name from +arg+. +arg+ can be: # # Name:: returns +arg+. # String:: Creates a new Name. def self.create(arg) case arg when Name return arg when String return Name.new(Label.split(arg), /\.\z/ =~ arg ? true : false) else raise ArgumentError.new("cannot interpret as DNS name: #{arg.inspect}") end end def initialize(labels, absolute=true) # :nodoc: @labels = labels @absolute = absolute end def inspect # :nodoc: "#<#{self.class}: #{self.to_s}#{@absolute ? '.' : ''}>" end ## # True if this name is absolute. def absolute? return @absolute end def ==(other) # :nodoc: return false unless Name === other return @labels.join == other.to_a.join && @absolute == other.absolute? end alias eql? == # :nodoc: ## # Returns true if +other+ is a subdomain. # # Example: # # domain = Resolv::DNS::Name.create("y.z") # p Resolv::DNS::Name.create("w.x.y.z").subdomain_of?(domain) #=> true # p Resolv::DNS::Name.create("x.y.z").subdomain_of?(domain) #=> true # p Resolv::DNS::Name.create("y.z").subdomain_of?(domain) #=> false # p Resolv::DNS::Name.create("z").subdomain_of?(domain) #=> false # p Resolv::DNS::Name.create("x.y.z.").subdomain_of?(domain) #=> false # p Resolv::DNS::Name.create("w.z").subdomain_of?(domain) #=> false # def subdomain_of?(other) raise ArgumentError, "not a domain name: #{other.inspect}" unless Name === other return false if @absolute != other.absolute? other_len = other.length return false if @labels.length <= other_len return @labels[-other_len, other_len] == other.to_a end def hash # :nodoc: return @labels.hash ^ @absolute.hash end def to_a # :nodoc: return @labels end def length # :nodoc: return @labels.length end def [](i) # :nodoc: return @labels[i] end ## # returns the domain name as a string. # # The domain name doesn't have a trailing dot even if the name object is # absolute. # # Example: # # p Resolv::DNS::Name.create("x.y.z.").to_s #=> "x.y.z" # p Resolv::DNS::Name.create("x.y.z").to_s #=> "x.y.z" def to_s return @labels.join('.') end end class Message # :nodoc: @@identifier = -1 def initialize(id = (@@identifier += 1) & 0xffff) @id = id @qr = 0 @opcode = 0 @aa = 0 @tc = 0 @rd = 0 # recursion desired @ra = 0 # recursion available @rcode = 0 @question = [] @answer = [] @authority = [] @additional = [] end attr_accessor :id, :qr, :opcode, :aa, :tc, :rd, :ra, :rcode attr_reader :question, :answer, :authority, :additional def ==(other) return @id == other.id && @qr == other.qr && @opcode == other.opcode && @aa == other.aa && @tc == other.tc && @rd == other.rd && @ra == other.ra && @rcode == other.rcode && @question == other.question && @answer == other.answer && @authority == other.authority && @additional == other.additional end def add_question(name, typeclass) @question << [Name.create(name), typeclass] end def each_question @question.each {|name, typeclass| yield name, typeclass } end def add_answer(name, ttl, data) @answer << [Name.create(name), ttl, data] end def each_answer @answer.each {|name, ttl, data| yield name, ttl, data } end def add_authority(name, ttl, data) @authority << [Name.create(name), ttl, data] end def each_authority @authority.each {|name, ttl, data| yield name, ttl, data } end def add_additional(name, ttl, data) @additional << [Name.create(name), ttl, data] end def each_additional @additional.each {|name, ttl, data| yield name, ttl, data } end def each_resource each_answer {|name, ttl, data| yield name, ttl, data} each_authority {|name, ttl, data| yield name, ttl, data} each_additional {|name, ttl, data| yield name, ttl, data} end def encode return MessageEncoder.new {|msg| msg.put_pack('nnnnnn', @id, (@qr & 1) << 15 | (@opcode & 15) << 11 | (@aa & 1) << 10 | (@tc & 1) << 9 | (@rd & 1) << 8 | (@ra & 1) << 7 | (@rcode & 15), @question.length, @answer.length, @authority.length, @additional.length) @question.each {|q| name, typeclass = q msg.put_name(name) msg.put_pack('nn', typeclass::TypeValue, typeclass::ClassValue) } [@answer, @authority, @additional].each {|rr| rr.each {|r| name, ttl, data = r msg.put_name(name) msg.put_pack('nnN', data.class::TypeValue, data.class::ClassValue, ttl) msg.put_length16 {data.encode_rdata(msg)} } } }.to_s end class MessageEncoder # :nodoc: def initialize @data = '' @names = {} yield self end def to_s return @data end def put_bytes(d) @data << d end def put_pack(template, *d) @data << d.pack(template) end def put_length16 length_index = @data.length @data << "\0\0" data_start = @data.length yield data_end = @data.length @data[length_index, 2] = [data_end - data_start].pack("n") end def put_string(d) self.put_pack("C", d.length) @data << d end def put_string_list(ds) ds.each {|d| self.put_string(d) } end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
true
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/tracer.rb
tools/jruby-1.5.1/lib/ruby/1.8/tracer.rb
# # tracer.rb - # $Release Version: 0.2$ # $Revision: 1.8 $ # $Date: 1998/05/19 03:42:49 $ # by Keiju ISHITSUKA(Nippon Rational Inc.) # # -- # # # # # tracer main class # class Tracer @RCS_ID='-$Id: tracer.rb,v 1.8 1998/05/19 03:42:49 keiju Exp keiju $-' @stdout = STDOUT @verbose = false class << self attr :verbose, true alias verbose? verbose attr :stdout, true end EVENT_SYMBOL = { "line" => "-", "call" => ">", "return" => "<", "class" => "C", "end" => "E", "c-call" => ">", "c-return" => "<", } def initialize @threads = Hash.new if defined? Thread.main @threads[Thread.main.object_id] = 0 else @threads[Thread.current.object_id] = 0 end @get_line_procs = {} @filters = [] end def stdout Tracer.stdout end def on if block_given? on begin yield ensure off end else set_trace_func method(:trace_func).to_proc stdout.print "Trace on\n" if Tracer.verbose? end end def off set_trace_func nil stdout.print "Trace off\n" if Tracer.verbose? end def add_filter(p = proc) @filters.push p end def set_get_line_procs(file, p = proc) @get_line_procs[file] = p end def get_line(file, line) if p = @get_line_procs[file] return p.call(line) end unless list = SCRIPT_LINES__[file] begin f = open(file) begin SCRIPT_LINES__[file] = list = f.readlines ensure f.close end rescue SCRIPT_LINES__[file] = list = [] end end if l = list[line - 1] l else "-\n" end end def get_thread_no if no = @threads[Thread.current.object_id] no else @threads[Thread.current.object_id] = @threads.size end end def trace_func(event, file, line, id, binding, klass, *) return if file == __FILE__ for p in @filters return unless p.call event, file, line, id, binding, klass end saved_crit = Thread.critical Thread.critical = true stdout.printf("#%d:%s:%d:%s:%s: %s", get_thread_no, file, line, klass || '', EVENT_SYMBOL[event], get_line(file, line)) Thread.critical = saved_crit end Single = new def Tracer.on if block_given? Single.on{yield} else Single.on end end def Tracer.off Single.off end def Tracer.set_get_line_procs(file_name, p = proc) Single.set_get_line_procs(file_name, p) end def Tracer.add_filter(p = proc) Single.add_filter(p) end end SCRIPT_LINES__ = {} unless defined? SCRIPT_LINES__ if $0 == __FILE__ # direct call $0 = ARGV[0] ARGV.shift Tracer.on require $0 elsif caller(0).size == 2 # HACK for JRUBY-4484 Tracer.on end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/sync.rb
tools/jruby-1.5.1/lib/ruby/1.8/sync.rb
# # sync.rb - 2 phase lock with counter # $Release Version: 1.0$ # $Revision: 22457 $ # $Date: 2009-02-20 01:41:12 +0900 (Fri, 20 Feb 2009) $ # by Keiju ISHITSUKA(keiju@ishitsuka.com) # # -- # Sync_m, Synchronizer_m # Usage: # obj.extend(Sync_m) # or # class Foo # include Sync_m # : # end # # Sync_m#sync_mode # Sync_m#sync_locked?, locked? # Sync_m#sync_shared?, shared? # Sync_m#sync_exclusive?, sync_exclusive? # Sync_m#sync_try_lock, try_lock # Sync_m#sync_lock, lock # Sync_m#sync_unlock, unlock # # Sync, Synchronicer: # include Sync_m # Usage: # sync = Sync.new # # Sync#mode # Sync#locked? # Sync#shared? # Sync#exclusive? # Sync#try_lock(mode) -- mode = :EX, :SH, :UN # Sync#lock(mode) -- mode = :EX, :SH, :UN # Sync#unlock # Sync#synchronize(mode) {...} # # unless defined? Thread fail "Thread not available for this ruby interpreter" end require 'thread' module Sync_m RCS_ID='-$Header$-' # lock mode UN = :UN SH = :SH EX = :EX # exceptions class Err < StandardError def Err.Fail(*opt) Thread.critical = false fail self, sprintf(self::Message, *opt) end class UnknownLocker < Err Message = "Thread(%s) not locked." def UnknownLocker.Fail(th) super(th.inspect) end end class LockModeFailer < Err Message = "Unknown lock mode(%s)" def LockModeFailer.Fail(mode) if mode.id2name mode = id2name end super(mode) end end end def Sync_m.define_aliases(cl) cl.module_eval %q{ alias locked? sync_locked? alias shared? sync_shared? alias exclusive? sync_exclusive? alias lock sync_lock alias unlock sync_unlock alias try_lock sync_try_lock alias synchronize sync_synchronize } end def Sync_m.append_features(cl) super unless cl.instance_of?(Module) # do nothing for Modules # make aliases and include the proper module. define_aliases(cl) end end def Sync_m.extend_object(obj) super obj.sync_extended end def sync_extended unless (defined? locked? and defined? shared? and defined? exclusive? and defined? lock and defined? unlock and defined? try_lock and defined? synchronize) Sync_m.define_aliases(class<<self;self;end) end sync_initialize end # accessing def sync_locked? @sync_mutex.synchronize { @sync_mode != UN } end def sync_shared? @sync_mutex.synchronize { @sync_mode == SH } end def sync_exclusive? @sync_mutex.synchronize { @sync_mode == EX } end # locking methods. def sync_try_lock(m = EX) return sync_unlock if m == UN @sync_mutex.synchronize do sync_try_lock_sub(m) end end def sync_lock(m = EX) return sync_unlock if m == UN @sync_mutex.synchronize do until sync_try_lock_sub(m) if @sync_sh_lockers.include? Thread.current @sync_upgrade_n_waiting += 1 begin @sync_upgrade_cond.wait(@sync_mutex) ensure @sync_upgrade_n_waiting -= 1 end else @sync_cond.wait(@sync_mutex) end end end self end def sync_unlock(m = EX) @sync_mutex.synchronize do case @sync_mode when UN Err::UnknownLocker.Fail(Thread.current) when SH # downgrade EX unlock requests in SH mode m = SH if m == EX when EX # upgrade SH unlock requests in EX mode # (necessary to balance lock request upgrades) m = EX if m == SH end runnable = false case m when UN Err::UnknownLocker.Fail(Thread.current) when EX if @sync_ex_locker == Thread.current @sync_ex_count -= 1 if @sync_ex_count.zero? @sync_ex_locker = nil if @sync_sh_lockers.include? Thread.current @sync_mode = SH else @sync_mode = UN end runnable = true end else Err::UnknownLocker.Fail(Thread.current) end when SH count = @sync_sh_lockers[Thread.current] Err::UnknownLocker.Fail(Thread.current) if count.nil? count -= 1 if count.zero? @sync_sh_lockers.delete Thread.current if @sync_sh_lockers.empty? and @sync_mode == SH @sync_mode = UN runnable = true end else @sync_sh_lockers[Thread.current] = count end end if runnable if @sync_upgrade_n_waiting.nonzero? @sync_upgrade_cond.signal else @sync_cond.signal end end end self end def sync_synchronize(mode = EX) begin sync_lock(mode) yield ensure sync_unlock end end def sync_mode @sync_mutex.synchronize { @sync_mode } end private def sync_initialize @sync_mutex = Mutex.new @sync_mode = UN @sync_cond = ConditionVariable.new @sync_upgrade_cond = ConditionVariable.new @sync_upgrade_n_waiting = 0 @sync_sh_lockers = Hash.new @sync_ex_locker = nil @sync_ex_count = 0 end def initialize(*args) sync_initialize super end def sync_try_lock_sub(m) case m when SH case @sync_mode when UN, SH @sync_mode = SH count = @sync_sh_lockers[Thread.current] || 0 @sync_sh_lockers[Thread.current] = count + 1 true when EX # in EX mode, lock will upgrade to EX lock if @sync_ex_locker == Thread.current @sync_ex_count += 1 true else false end end when EX if @sync_mode == UN or @sync_mode == SH && @sync_sh_lockers.size == 1 && @sync_sh_lockers.include?(Thread.current) or @sync_mode == EX && @sync_ex_locker == Thread.current @sync_mode = EX @sync_ex_locker = Thread.current @sync_ex_count += 1 true else false end else Err::LockModeFailer.Fail mode end end end Synchronizer_m = Sync_m class Sync #Sync_m.extend_class self include Sync_m def initialize super end end Synchronizer = Sync
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/ftools.rb
tools/jruby-1.5.1/lib/ruby/1.8/ftools.rb
# # = ftools.rb: Extra tools for the File class # # Author:: WATANABE, Hirofumi # Documentation:: Zachary Landau # # This library can be distributed under the terms of the Ruby license. # You can freely distribute/modify this library. # # It is included in the Ruby standard library. # # == Description # # ftools adds several (class, not instance) methods to the File class, for # copying, moving, deleting, installing, and comparing files, as well as # creating a directory path. See the File class for details. # # FileUtils contains all or nearly all the same functionality and more, and # is a recommended option over ftools # # When you # # require 'ftools' # # then the File class aquires some utility methods for copying, moving, and # deleting files, and more. # # See the method descriptions below, and consider using FileUtils as it is # more comprehensive. # class File end class << File BUFSIZE = 8 * 1024 # # If +to+ is a valid directory, +from+ will be appended to +to+, adding # and escaping backslashes as necessary. Otherwise, +to+ will be returned. # Useful for appending +from+ to +to+ only if the filename was not specified # in +to+. # def catname(from, to) if directory? to join to.sub(%r([/\\]$), ''), basename(from) else to end end # # Copies a file +from+ to +to+. If +to+ is a directory, copies +from+ # to <tt>to/from</tt>. # def syscopy(from, to) to = catname(from, to) fmode = stat(from).mode tpath = to not_exist = !exist?(tpath) from = open(from, "rb") to = open(to, "wb") begin while true to.syswrite from.sysread(BUFSIZE) end rescue EOFError ret = true rescue ret = false ensure to.close from.close end chmod(fmode, tpath) if not_exist ret end # # Copies a file +from+ to +to+ using #syscopy. If +to+ is a directory, # copies +from+ to <tt>to/from</tt>. If +verbose+ is true, <tt>from -> to</tt> # is printed. # def copy(from, to, verbose = false) $stderr.print from, " -> ", catname(from, to), "\n" if verbose syscopy from, to end alias cp copy # # Moves a file +from+ to +to+ using #syscopy. If +to+ is a directory, # copies from +from+ to <tt>to/from</tt>. If +verbose+ is true, <tt>from -> # to</tt> is printed. # def move(from, to, verbose = false) to = catname(from, to) $stderr.print from, " -> ", to, "\n" if verbose if RUBY_PLATFORM =~ /djgpp|(cyg|ms|bcc)win|mingw/ and file? to unlink to end fstat = stat(from) begin rename from, to rescue begin symlink readlink(from), to and unlink from rescue from_stat = stat(from) syscopy from, to and unlink from utime(from_stat.atime, from_stat.mtime, to) begin chown(fstat.uid, fstat.gid, to) rescue end end end end alias mv move # # Returns +true+ if and only if the contents of files +from+ and +to+ are # identical. If +verbose+ is +true+, <tt>from <=> to</tt> is printed. # def compare(from, to, verbose = false) $stderr.print from, " <=> ", to, "\n" if verbose return false if stat(from).size != stat(to).size from = open(from, "rb") to = open(to, "rb") ret = false fr = tr = '' begin while fr == tr fr = from.read(BUFSIZE) if fr tr = to.read(fr.size) else ret = to.read(BUFSIZE) ret = !ret || ret.length == 0 break end end rescue ret = false ensure to.close from.close end ret end alias cmp compare # # Removes a list of files. Each parameter should be the name of the file to # delete. If the last parameter isn't a String, verbose mode will be enabled. # Returns the number of files deleted. # def safe_unlink(*files) verbose = if files[-1].is_a? String then false else files.pop end files.each do |file| begin unlink file $stderr.print "removing ", file, "\n" if verbose rescue Errno::EACCES # for Windows continue if symlink? file begin mode = stat(file).mode o_chmod mode | 0200, file unlink file $stderr.print "removing ", file, "\n" if verbose rescue o_chmod mode, file rescue nil end rescue end end end alias rm_f safe_unlink # # Creates a directory and all its parent directories. # For example, # # File.makedirs '/usr/lib/ruby' # # causes the following directories to be made, if they do not exist. # * /usr # * /usr/lib # * /usr/lib/ruby # # You can pass several directories, each as a parameter. If the last # parameter isn't a String, verbose mode will be enabled. # def makedirs(*dirs) verbose = if dirs[-1].is_a? String then false else dirs.pop end mode = 0755 for dir in dirs parent = dirname(dir) next if parent == dir or directory? dir makedirs parent unless directory? parent $stderr.print "mkdir ", dir, "\n" if verbose if basename(dir) != "" begin Dir.mkdir dir, mode rescue SystemCallError raise unless directory? dir end end end end alias mkpath makedirs alias o_chmod chmod vsave, $VERBOSE = $VERBOSE, false # # Changes permission bits on +files+ to the bit pattern represented # by +mode+. If the last parameter isn't a String, verbose mode will # be enabled. # # File.chmod 0755, 'somecommand' # File.chmod 0644, 'my.rb', 'your.rb', true # def chmod(mode, *files) verbose = if files[-1].is_a? String then false else files.pop end $stderr.printf "chmod %04o %s\n", mode, files.join(" ") if verbose o_chmod mode, *files end $VERBOSE = vsave # # If +src+ is not the same as +dest+, copies it and changes the permission # mode to +mode+. If +dest+ is a directory, destination is <tt>dest/src</tt>. # If +mode+ is not set, default is used. If +verbose+ is set to true, the # name of each file copied will be printed. # def install(from, to, mode = nil, verbose = false) to = catname(from, to) unless exist? to and cmp from, to safe_unlink to if exist? to cp from, to, verbose chmod mode, to, verbose if mode end end end # vi:set sw=2:
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/ostruct.rb
tools/jruby-1.5.1/lib/ruby/1.8/ostruct.rb
# # = ostruct.rb: OpenStruct implementation # # Author:: Yukihiro Matsumoto # Documentation:: Gavin Sinclair # # OpenStruct allows the creation of data objects with arbitrary attributes. # See OpenStruct for an example. # # # OpenStruct allows you to create data objects and set arbitrary attributes. # For example: # # require 'ostruct' # # record = OpenStruct.new # record.name = "John Smith" # record.age = 70 # record.pension = 300 # # puts record.name # -> "John Smith" # puts record.address # -> nil # # It is like a hash with a different way to access the data. In fact, it is # implemented with a hash, and you can initialize it with one. # # hash = { "country" => "Australia", :population => 20_000_000 } # data = OpenStruct.new(hash) # # p data # -> <OpenStruct country="Australia" population=20000000> # class OpenStruct # # Create a new OpenStruct object. The optional +hash+, if given, will # generate attributes and values. For example. # # require 'ostruct' # hash = { "country" => "Australia", :population => 20_000_000 } # data = OpenStruct.new(hash) # # p data # -> <OpenStruct country="Australia" population=20000000> # # By default, the resulting OpenStruct object will have no attributes. # def initialize(hash=nil) @table = {} if hash for k,v in hash @table[k.to_sym] = v new_ostruct_member(k) end end end # Duplicate an OpenStruct object members. def initialize_copy(orig) super @table = @table.dup end def marshal_dump @table end def marshal_load(x) @table = x @table.each_key{|key| new_ostruct_member(key)} end def modifiable if self.frozen? raise TypeError, "can't modify frozen #{self.class}", caller(2) end @table end protected :modifiable def new_ostruct_member(name) name = name.to_sym unless self.respond_to?(name) class << self; self; end.class_eval do define_method(name) { @table[name] } define_method("#{name}=") { |x| modifiable[name] = x } end end name end def method_missing(mid, *args) # :nodoc: mname = mid.id2name len = args.length if mname.chomp!('=') if len != 1 raise ArgumentError, "wrong number of arguments (#{len} for 1)", caller(1) end modifiable[new_ostruct_member(mname)] = args[0] elsif len == 0 @table[mid] else raise NoMethodError, "undefined method `#{mname}' for #{self}", caller(1) end end # # Remove the named field from the object. # def delete_field(name) @table.delete name.to_sym end InspectKey = :__inspect_key__ # :nodoc: # # Returns a string containing a detailed summary of the keys and values. # def inspect str = "#<#{self.class}" ids = (Thread.current[InspectKey] ||= []) if ids.include?(object_id) return str << ' ...>' end ids << object_id begin first = true for k,v in @table str << "," unless first first = false str << " #{k}=#{v.inspect}" end return str << '>' ensure ids.pop end end alias :to_s :inspect attr_reader :table # :nodoc: protected :table # # Compare this object and +other+ for equality. # def ==(other) return false unless(other.kind_of?(OpenStruct)) return @table == other.table end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/benchmark.rb
tools/jruby-1.5.1/lib/ruby/1.8/benchmark.rb
=begin # # benchmark.rb - a performance benchmarking library # # $Id: benchmark.rb 15425 2008-02-10 15:24:56Z naruse $ # # Created by Gotoken (gotoken@notwork.org). # # Documentation by Gotoken (original RD), Lyle Johnson (RDoc conversion), and # Gavin Sinclair (editing). # =end # == Overview # # The Benchmark module provides methods for benchmarking Ruby code, giving # detailed reports on the time taken for each task. # # The Benchmark module provides methods to measure and report the time # used to execute Ruby code. # # * Measure the time to construct the string given by the expression # <tt>"a"*1_000_000</tt>: # # require 'benchmark' # # puts Benchmark.measure { "a"*1_000_000 } # # On my machine (FreeBSD 3.2 on P5, 100MHz) this generates: # # 1.166667 0.050000 1.216667 ( 0.571355) # # This report shows the user CPU time, system CPU time, the sum of # the user and system CPU times, and the elapsed real time. The unit # of time is seconds. # # * Do some experiments sequentially using the #bm method: # # require 'benchmark' # # n = 50000 # Benchmark.bm do |x| # x.report { for i in 1..n; a = "1"; end } # x.report { n.times do ; a = "1"; end } # x.report { 1.upto(n) do ; a = "1"; end } # end # # The result: # # user system total real # 1.033333 0.016667 1.016667 ( 0.492106) # 1.483333 0.000000 1.483333 ( 0.694605) # 1.516667 0.000000 1.516667 ( 0.711077) # # * Continuing the previous example, put a label in each report: # # require 'benchmark' # # n = 50000 # Benchmark.bm(7) do |x| # x.report("for:") { for i in 1..n; a = "1"; end } # x.report("times:") { n.times do ; a = "1"; end } # x.report("upto:") { 1.upto(n) do ; a = "1"; end } # end # # The result: # # user system total real # for: 1.050000 0.000000 1.050000 ( 0.503462) # times: 1.533333 0.016667 1.550000 ( 0.735473) # upto: 1.500000 0.016667 1.516667 ( 0.711239) # # # * The times for some benchmarks depend on the order in which items # are run. These differences are due to the cost of memory # allocation and garbage collection. To avoid these discrepancies, # the #bmbm method is provided. For example, to compare ways to # sort an array of floats: # # require 'benchmark' # # array = (1..1000000).map { rand } # # Benchmark.bmbm do |x| # x.report("sort!") { array.dup.sort! } # x.report("sort") { array.dup.sort } # end # # The result: # # Rehearsal ----------------------------------------- # sort! 11.928000 0.010000 11.938000 ( 12.756000) # sort 13.048000 0.020000 13.068000 ( 13.857000) # ------------------------------- total: 25.006000sec # # user system total real # sort! 12.959000 0.010000 12.969000 ( 13.793000) # sort 12.007000 0.000000 12.007000 ( 12.791000) # # # * Report statistics of sequential experiments with unique labels, # using the #benchmark method: # # require 'benchmark' # # n = 50000 # Benchmark.benchmark(" "*7 + CAPTION, 7, FMTSTR, ">total:", ">avg:") do |x| # tf = x.report("for:") { for i in 1..n; a = "1"; end } # tt = x.report("times:") { n.times do ; a = "1"; end } # tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end } # [tf+tt+tu, (tf+tt+tu)/3] # end # # The result: # # user system total real # for: 1.016667 0.016667 1.033333 ( 0.485749) # times: 1.450000 0.016667 1.466667 ( 0.681367) # upto: 1.533333 0.000000 1.533333 ( 0.722166) # >total: 4.000000 0.033333 4.033333 ( 1.889282) # >avg: 1.333333 0.011111 1.344444 ( 0.629761) module Benchmark BENCHMARK_VERSION = "2002-04-25" #:nodoc" def Benchmark::times() # :nodoc: Process::times() end # Invokes the block with a <tt>Benchmark::Report</tt> object, which # may be used to collect and report on the results of individual # benchmark tests. Reserves <i>label_width</i> leading spaces for # labels on each line. Prints _caption_ at the top of the # report, and uses _fmt_ to format each line. # If the block returns an array of # <tt>Benchmark::Tms</tt> objects, these will be used to format # additional lines of output. If _label_ parameters are # given, these are used to label these extra lines. # # _Note_: Other methods provide a simpler interface to this one, and are # suitable for nearly all benchmarking requirements. See the examples in # Benchmark, and the #bm and #bmbm methods. # # Example: # # require 'benchmark' # include Benchmark # we need the CAPTION and FMTSTR constants # # n = 50000 # Benchmark.benchmark(" "*7 + CAPTION, 7, FMTSTR, ">total:", ">avg:") do |x| # tf = x.report("for:") { for i in 1..n; a = "1"; end } # tt = x.report("times:") { n.times do ; a = "1"; end } # tu = x.report("upto:") { 1.upto(n) do ; a = "1"; end } # [tf+tt+tu, (tf+tt+tu)/3] # end # # <i>Generates:</i> # # user system total real # for: 1.016667 0.016667 1.033333 ( 0.485749) # times: 1.450000 0.016667 1.466667 ( 0.681367) # upto: 1.533333 0.000000 1.533333 ( 0.722166) # >total: 4.000000 0.033333 4.033333 ( 1.889282) # >avg: 1.333333 0.011111 1.344444 ( 0.629761) # def benchmark(caption = "", label_width = nil, fmtstr = nil, *labels) # :yield: report sync = STDOUT.sync STDOUT.sync = true label_width ||= 0 fmtstr ||= FMTSTR raise ArgumentError, "no block" unless iterator? print caption results = yield(Report.new(label_width, fmtstr)) Array === results and results.grep(Tms).each {|t| print((labels.shift || t.label || "").ljust(label_width), t.format(fmtstr)) } STDOUT.sync = sync end # A simple interface to the #benchmark method, #bm is generates sequential reports # with labels. The parameters have the same meaning as for #benchmark. # # require 'benchmark' # # n = 50000 # Benchmark.bm(7) do |x| # x.report("for:") { for i in 1..n; a = "1"; end } # x.report("times:") { n.times do ; a = "1"; end } # x.report("upto:") { 1.upto(n) do ; a = "1"; end } # end # # <i>Generates:</i> # # user system total real # for: 1.050000 0.000000 1.050000 ( 0.503462) # times: 1.533333 0.016667 1.550000 ( 0.735473) # upto: 1.500000 0.016667 1.516667 ( 0.711239) # def bm(label_width = 0, *labels, &blk) # :yield: report benchmark(" "*label_width + CAPTION, label_width, FMTSTR, *labels, &blk) end # Sometimes benchmark results are skewed because code executed # earlier encounters different garbage collection overheads than # that run later. #bmbm attempts to minimize this effect by running # the tests twice, the first time as a rehearsal in order to get the # runtime environment stable, the second time for # real. <tt>GC.start</tt> is executed before the start of each of # the real timings; the cost of this is not included in the # timings. In reality, though, there's only so much that #bmbm can # do, and the results are not guaranteed to be isolated from garbage # collection and other effects. # # Because #bmbm takes two passes through the tests, it can # calculate the required label width. # # require 'benchmark' # # array = (1..1000000).map { rand } # # Benchmark.bmbm do |x| # x.report("sort!") { array.dup.sort! } # x.report("sort") { array.dup.sort } # end # # <i>Generates:</i> # # Rehearsal ----------------------------------------- # sort! 11.928000 0.010000 11.938000 ( 12.756000) # sort 13.048000 0.020000 13.068000 ( 13.857000) # ------------------------------- total: 25.006000sec # # user system total real # sort! 12.959000 0.010000 12.969000 ( 13.793000) # sort 12.007000 0.000000 12.007000 ( 12.791000) # # #bmbm yields a Benchmark::Job object and returns an array of # Benchmark::Tms objects. # def bmbm(width = 0, &blk) # :yield: job job = Job.new(width) yield(job) width = job.width sync = STDOUT.sync STDOUT.sync = true # rehearsal print "Rehearsal " puts '-'*(width+CAPTION.length - "Rehearsal ".length) list = [] job.list.each{|label,item| print(label.ljust(width)) res = Benchmark::measure(&item) print res.format() list.push res } sum = Tms.new; list.each{|i| sum += i} ets = sum.format("total: %tsec") printf("%s %s\n\n", "-"*(width+CAPTION.length-ets.length-1), ets) # take print ' '*width, CAPTION list = [] ary = [] job.list.each{|label,item| GC::start print label.ljust(width) res = Benchmark::measure(&item) print res.format() ary.push res list.push [label, res] } STDOUT.sync = sync ary end # # Returns the time used to execute the given block as a # Benchmark::Tms object. # def measure(label = "") # :yield: t0, r0 = Benchmark.times, Time.now yield t1, r1 = Benchmark.times, Time.now Benchmark::Tms.new(t1.utime - t0.utime, t1.stime - t0.stime, t1.cutime - t0.cutime, t1.cstime - t0.cstime, r1.to_f - r0.to_f, label) end # # Returns the elapsed real time used to execute the given block. # def realtime(&blk) # :yield: r0 = Time.now yield r1 = Time.now r1.to_f - r0.to_f end # # A Job is a sequence of labelled blocks to be processed by the # Benchmark.bmbm method. It is of little direct interest to the user. # class Job # :nodoc: # # Returns an initialized Job instance. # Usually, one doesn't call this method directly, as new # Job objects are created by the #bmbm method. # _width_ is a initial value for the label offset used in formatting; # the #bmbm method passes its _width_ argument to this constructor. # def initialize(width) @width = width @list = [] end # # Registers the given label and block pair in the job list. # def item(label = "", &blk) # :yield: raise ArgumentError, "no block" unless block_given? label += ' ' w = label.length @width = w if @width < w @list.push [label, blk] self end alias report item # An array of 2-element arrays, consisting of label and block pairs. attr_reader :list # Length of the widest label in the #list, plus one. attr_reader :width end module_function :benchmark, :measure, :realtime, :bm, :bmbm # # This class is used by the Benchmark.benchmark and Benchmark.bm methods. # It is of little direct interest to the user. # class Report # :nodoc: # # Returns an initialized Report instance. # Usually, one doesn't call this method directly, as new # Report objects are created by the #benchmark and #bm methods. # _width_ and _fmtstr_ are the label offset and # format string used by Tms#format. # def initialize(width = 0, fmtstr = nil) @width, @fmtstr = width, fmtstr end # # Prints the _label_ and measured time for the block, # formatted by _fmt_. See Tms#format for the # formatting rules. # def item(label = "", *fmt, &blk) # :yield: print label.ljust(@width) res = Benchmark::measure(&blk) print res.format(@fmtstr, *fmt) res end alias report item end # # A data object, representing the times associated with a benchmark # measurement. # class Tms CAPTION = " user system total real\n" FMTSTR = "%10.6u %10.6y %10.6t %10.6r\n" # User CPU time attr_reader :utime # System CPU time attr_reader :stime # User CPU time of children attr_reader :cutime # System CPU time of children attr_reader :cstime # Elapsed real time attr_reader :real # Total time, that is _utime_ + _stime_ + _cutime_ + _cstime_ attr_reader :total # Label attr_reader :label # # Returns an initialized Tms object which has # _u_ as the user CPU time, _s_ as the system CPU time, # _cu_ as the children's user CPU time, _cs_ as the children's # system CPU time, _real_ as the elapsed real time and _l_ # as the label. # def initialize(u = 0.0, s = 0.0, cu = 0.0, cs = 0.0, real = 0.0, l = nil) @utime, @stime, @cutime, @cstime, @real, @label = u, s, cu, cs, real, l @total = @utime + @stime + @cutime + @cstime end # # Returns a new Tms object whose times are the sum of the times for this # Tms object, plus the time required to execute the code block (_blk_). # def add(&blk) # :yield: self + Benchmark::measure(&blk) end # # An in-place version of #add. # def add! t = Benchmark::measure(&blk) @utime = utime + t.utime @stime = stime + t.stime @cutime = cutime + t.cutime @cstime = cstime + t.cstime @real = real + t.real self end # # Returns a new Tms object obtained by memberwise summation # of the individual times for this Tms object with those of the other # Tms object. # This method and #/() are useful for taking statistics. # def +(other); memberwise(:+, other) end # # Returns a new Tms object obtained by memberwise subtraction # of the individual times for the other Tms object from those of this # Tms object. # def -(other); memberwise(:-, other) end # # Returns a new Tms object obtained by memberwise multiplication # of the individual times for this Tms object by _x_. # def *(x); memberwise(:*, x) end # # Returns a new Tms object obtained by memberwise division # of the individual times for this Tms object by _x_. # This method and #+() are useful for taking statistics. # def /(x); memberwise(:/, x) end # # Returns the contents of this Tms object as # a formatted string, according to a format string # like that passed to Kernel.format. In addition, #format # accepts the following extensions: # # <tt>%u</tt>:: Replaced by the user CPU time, as reported by Tms#utime. # <tt>%y</tt>:: Replaced by the system CPU time, as reported by #stime (Mnemonic: y of "s*y*stem") # <tt>%U</tt>:: Replaced by the children's user CPU time, as reported by Tms#cutime # <tt>%Y</tt>:: Replaced by the children's system CPU time, as reported by Tms#cstime # <tt>%t</tt>:: Replaced by the total CPU time, as reported by Tms#total # <tt>%r</tt>:: Replaced by the elapsed real time, as reported by Tms#real # <tt>%n</tt>:: Replaced by the label string, as reported by Tms#label (Mnemonic: n of "*n*ame") # # If _fmtstr_ is not given, FMTSTR is used as default value, detailing the # user, system and real elapsed time. # def format(arg0 = nil, *args) fmtstr = (arg0 || FMTSTR).dup fmtstr.gsub!(/(%[-+\.\d]*)n/){"#{$1}s" % label} fmtstr.gsub!(/(%[-+\.\d]*)u/){"#{$1}f" % utime} fmtstr.gsub!(/(%[-+\.\d]*)y/){"#{$1}f" % stime} fmtstr.gsub!(/(%[-+\.\d]*)U/){"#{$1}f" % cutime} fmtstr.gsub!(/(%[-+\.\d]*)Y/){"#{$1}f" % cstime} fmtstr.gsub!(/(%[-+\.\d]*)t/){"#{$1}f" % total} fmtstr.gsub!(/(%[-+\.\d]*)r/){"(#{$1}f)" % real} arg0 ? Kernel::format(fmtstr, *args) : fmtstr end # # Same as #format. # def to_s format end # # Returns a new 6-element array, consisting of the # label, user CPU time, system CPU time, children's # user CPU time, children's system CPU time and elapsed # real time. # def to_a [@label, @utime, @stime, @cutime, @cstime, @real] end protected def memberwise(op, x) case x when Benchmark::Tms Benchmark::Tms.new(utime.__send__(op, x.utime), stime.__send__(op, x.stime), cutime.__send__(op, x.cutime), cstime.__send__(op, x.cstime), real.__send__(op, x.real) ) else Benchmark::Tms.new(utime.__send__(op, x), stime.__send__(op, x), cutime.__send__(op, x), cstime.__send__(op, x), real.__send__(op, x) ) end end end # The default caption string (heading above the output times). CAPTION = Benchmark::Tms::CAPTION # The default format string used to display times. See also Benchmark::Tms#format. FMTSTR = Benchmark::Tms::FMTSTR end if __FILE__ == $0 include Benchmark n = ARGV[0].to_i.nonzero? || 50000 puts %Q([#{n} times iterations of `a = "1"']) benchmark(" " + CAPTION, 7, FMTSTR) do |x| x.report("for:") {for i in 1..n; a = "1"; end} # Benchmark::measure x.report("times:") {n.times do ; a = "1"; end} x.report("upto:") {1.upto(n) do ; a = "1"; end} end benchmark do [ measure{for i in 1..n; a = "1"; end}, # Benchmark::measure measure{n.times do ; a = "1"; end}, measure{1.upto(n) do ; a = "1"; end} ] end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/set.rb
tools/jruby-1.5.1/lib/ruby/1.8/set.rb
#!/usr/bin/env ruby #-- # set.rb - defines the Set class #++ # Copyright (c) 2002-2008 Akinori MUSHA <knu@iDaemons.org> # # Documentation by Akinori MUSHA and Gavin Sinclair. # # All rights reserved. You can redistribute and/or modify it under the same # terms as Ruby. # # $Id: set.rb 17051 2008-06-09 09:20:43Z knu $ # # == Overview # # This library provides the Set class, which deals with a collection # of unordered values with no duplicates. It is a hybrid of Array's # intuitive inter-operation facilities and Hash's fast lookup. If you # need to keep values ordered, use the SortedSet class. # # The method +to_set+ is added to Enumerable for convenience. # # See the Set class for an example of usage. # # Set implements a collection of unordered values with no duplicates. # This is a hybrid of Array's intuitive inter-operation facilities and # Hash's fast lookup. # # Several methods accept any Enumerable object (implementing +each+) # for greater flexibility: new, replace, merge, subtract, |, &, -, ^. # # The equality of each couple of elements is determined according to # Object#eql? and Object#hash, since Set uses Hash as storage. # # Finally, if you are using class Set, you can also use Enumerable#to_set # for convenience. # # == Example # # require 'set' # s1 = Set.new [1, 2] # -> #<Set: {1, 2}> # s2 = [1, 2].to_set # -> #<Set: {1, 2}> # s1 == s2 # -> true # s1.add("foo") # -> #<Set: {1, 2, "foo"}> # s1.merge([2, 6]) # -> #<Set: {6, 1, 2, "foo"}> # s1.subset? s2 # -> false # s2.subset? s1 # -> true # # == Contact # # - Akinori MUSHA <knu@iDaemons.org> (current maintainer) # class Set include Enumerable # Creates a new set containing the given objects. def self.[](*ary) new(ary) end # Creates a new set containing the elements of the given enumerable # object. # # If a block is given, the elements of enum are preprocessed by the # given block. def initialize(enum = nil, &block) # :yields: o @hash ||= Hash.new enum.nil? and return if block enum.each { |o| add(block[o]) } else merge(enum) end end # Copy internal hash. def initialize_copy(orig) @hash = orig.instance_eval{@hash}.dup end # Returns the number of elements. def size @hash.size end alias length size # Returns true if the set contains no elements. def empty? @hash.empty? end # Removes all elements and returns self. def clear @hash.clear self end # Replaces the contents of the set with the contents of the given # enumerable object and returns self. def replace(enum) if enum.class == self.class @hash.replace(enum.instance_eval { @hash }) else enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" clear enum.each { |o| add(o) } end self end # Converts the set to an array. The order of elements is uncertain. def to_a @hash.keys end def flatten_merge(set, seen = Set.new) set.each { |e| if e.is_a?(Set) if seen.include?(e_id = e.object_id) raise ArgumentError, "tried to flatten recursive Set" end seen.add(e_id) flatten_merge(e, seen) seen.delete(e_id) else add(e) end } self end protected :flatten_merge # Returns a new set that is a copy of the set, flattening each # containing set recursively. def flatten self.class.new.flatten_merge(self) end # Equivalent to Set#flatten, but replaces the receiver with the # result in place. Returns nil if no modifications were made. def flatten! if detect { |e| e.is_a?(Set) } replace(flatten()) else nil end end # Returns true if the set contains the given object. def include?(o) @hash.include?(o) end alias member? include? # Returns true if the set is a superset of the given set. def superset?(set) set.is_a?(Set) or raise ArgumentError, "value must be a set" return false if size < set.size set.all? { |o| include?(o) } end # Returns true if the set is a proper superset of the given set. def proper_superset?(set) set.is_a?(Set) or raise ArgumentError, "value must be a set" return false if size <= set.size set.all? { |o| include?(o) } end # Returns true if the set is a subset of the given set. def subset?(set) set.is_a?(Set) or raise ArgumentError, "value must be a set" return false if set.size < size all? { |o| set.include?(o) } end # Returns true if the set is a proper subset of the given set. def proper_subset?(set) set.is_a?(Set) or raise ArgumentError, "value must be a set" return false if set.size <= size all? { |o| set.include?(o) } end # Calls the given block once for each element in the set, passing # the element as parameter. Returns an enumerator if no block is # given. def each block_given? or return enum_for(__method__) @hash.each_key { |o| yield(o) } self end # Adds the given object to the set and returns self. Use +merge+ to # add several elements at once. def add(o) @hash[o] = true self end alias << add # Adds the given object to the set and returns self. If the # object is already in the set, returns nil. def add?(o) if include?(o) nil else add(o) end end # Deletes the given object from the set and returns self. Use +subtract+ to # delete several items at once. def delete(o) @hash.delete(o) self end # Deletes the given object from the set and returns self. If the # object is not in the set, returns nil. def delete?(o) if include?(o) delete(o) else nil end end # Deletes every element of the set for which block evaluates to # true, and returns self. def delete_if to_a.each { |o| @hash.delete(o) if yield(o) } self end # Do collect() destructively. def collect! set = self.class.new each { |o| set << yield(o) } replace(set) end alias map! collect! # Equivalent to Set#delete_if, but returns nil if no changes were # made. def reject! n = size delete_if { |o| yield(o) } size == n ? nil : self end # Merges the elements of the given enumerable object to the set and # returns self. def merge(enum) if enum.is_a?(Set) @hash.update(enum.instance_eval { @hash }) else enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" enum.each { |o| add(o) } end self end # Deletes every element that appears in the given enumerable object # and returns self. def subtract(enum) enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" enum.each { |o| delete(o) } self end # Returns a new set built by merging the set and the elements of the # given enumerable object. def |(enum) enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" dup.merge(enum) end alias + | ## alias union | ## # Returns a new set built by duplicating the set, removing every # element that appears in the given enumerable object. def -(enum) enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" dup.subtract(enum) end alias difference - ## # Returns a new set containing elements common to the set and the # given enumerable object. def &(enum) enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" n = self.class.new enum.each { |o| n.add(o) if include?(o) } n end alias intersection & ## # Returns a new set containing elements exclusive between the set # and the given enumerable object. (set ^ enum) is equivalent to # ((set | enum) - (set & enum)). def ^(enum) enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" n = Set.new(enum) each { |o| if n.include?(o) then n.delete(o) else n.add(o) end } n end # Returns true if two sets are equal. The equality of each couple # of elements is defined according to Object#eql?. def ==(set) equal?(set) and return true set.is_a?(Set) && size == set.size or return false hash = @hash.dup set.all? { |o| hash.include?(o) } end def hash # :nodoc: @hash.hash end def eql?(o) # :nodoc: return false unless o.is_a?(Set) @hash.eql?(o.instance_eval{@hash}) end # Classifies the set by the return value of the given block and # returns a hash of {value => set of elements} pairs. The block is # called once for each element of the set, passing the element as # parameter. # # e.g.: # # require 'set' # files = Set.new(Dir.glob("*.rb")) # hash = files.classify { |f| File.mtime(f).year } # p hash # => {2000=>#<Set: {"a.rb", "b.rb"}>, # # 2001=>#<Set: {"c.rb", "d.rb", "e.rb"}>, # # 2002=>#<Set: {"f.rb"}>} def classify # :yields: o h = {} each { |i| x = yield(i) (h[x] ||= self.class.new).add(i) } h end # Divides the set into a set of subsets according to the commonality # defined by the given block. # # If the arity of the block is 2, elements o1 and o2 are in common # if block.call(o1, o2) is true. Otherwise, elements o1 and o2 are # in common if block.call(o1) == block.call(o2). # # e.g.: # # require 'set' # numbers = Set[1, 3, 4, 6, 9, 10, 11] # set = numbers.divide { |i,j| (i - j).abs == 1 } # p set # => #<Set: {#<Set: {1}>, # # #<Set: {11, 9, 10}>, # # #<Set: {3, 4}>, # # #<Set: {6}>}> def divide(&func) if func.arity == 2 require 'tsort' class << dig = {} # :nodoc: include TSort alias tsort_each_node each_key def tsort_each_child(node, &block) fetch(node).each(&block) end end each { |u| dig[u] = a = [] each{ |v| func.call(u, v) and a << v } } set = Set.new() dig.each_strongly_connected_component { |css| set.add(self.class.new(css)) } set else Set.new(classify(&func).values) end end InspectKey = :__inspect_key__ # :nodoc: # Returns a string containing a human-readable representation of the # set. ("#<Set: {element1, element2, ...}>") def inspect ids = (Thread.current[InspectKey] ||= []) if ids.include?(object_id) return sprintf('#<%s: {...}>', self.class.name) end begin ids << object_id return sprintf('#<%s: {%s}>', self.class, to_a.inspect[1..-2]) ensure ids.pop end end def pretty_print(pp) # :nodoc: pp.text sprintf('#<%s: {', self.class.name) pp.nest(1) { pp.seplist(self) { |o| pp.pp o } } pp.text "}>" end def pretty_print_cycle(pp) # :nodoc: pp.text sprintf('#<%s: {%s}>', self.class.name, empty? ? '' : '...') end end # SortedSet implements a set which elements are sorted in order. See Set. class SortedSet < Set @@setup = false class << self def [](*ary) # :nodoc: new(ary) end def setup # :nodoc: @@setup and return module_eval { # a hack to shut up warning alias old_init initialize remove_method :old_init } begin require 'rbtree' module_eval %{ def initialize(*args, &block) @hash = RBTree.new super end } rescue LoadError module_eval %{ def initialize(*args, &block) @keys = nil super end def clear @keys = nil super end def replace(enum) @keys = nil super end def add(o) @keys = nil @hash[o] = true self end alias << add def delete(o) @keys = nil @hash.delete(o) self end def delete_if n = @hash.size super @keys = nil if @hash.size != n self end def merge(enum) @keys = nil super end def each block_given? or return enum_for(__method__) to_a.each { |o| yield(o) } self end def to_a (@keys = @hash.keys).sort! unless @keys @keys end } end @@setup = true end end def initialize(*args, &block) # :nodoc: SortedSet.setup initialize(*args, &block) end end module Enumerable # Makes a set from the enumerable object with given arguments. # Needs to +require "set"+ to use this method. def to_set(klass = Set, *args, &block) klass.new(self, *args, &block) end end # =begin # == RestricedSet class # RestricedSet implements a set with restrictions defined by a given # block. # # === Super class # Set # # === Class Methods # --- RestricedSet::new(enum = nil) { |o| ... } # --- RestricedSet::new(enum = nil) { |rset, o| ... } # Creates a new restricted set containing the elements of the given # enumerable object. Restrictions are defined by the given block. # # If the block's arity is 2, it is called with the RestrictedSet # itself and an object to see if the object is allowed to be put in # the set. # # Otherwise, the block is called with an object to see if the object # is allowed to be put in the set. # # === Instance Methods # --- restriction_proc # Returns the restriction procedure of the set. # # =end # # class RestricedSet < Set # def initialize(*args, &block) # @proc = block or raise ArgumentError, "missing a block" # # if @proc.arity == 2 # instance_eval %{ # def add(o) # @hash[o] = true if @proc.call(self, o) # self # end # alias << add # # def add?(o) # if include?(o) || !@proc.call(self, o) # nil # else # @hash[o] = true # self # end # end # # def replace(enum) # enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" # clear # enum.each { |o| add(o) } # # self # end # # def merge(enum) # enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" # enum.each { |o| add(o) } # # self # end # } # else # instance_eval %{ # def add(o) # if @proc.call(o) # @hash[o] = true # end # self # end # alias << add # # def add?(o) # if include?(o) || !@proc.call(o) # nil # else # @hash[o] = true # self # end # end # } # end # # super(*args) # end # # def restriction_proc # @proc # end # end if $0 == __FILE__ eval DATA.read, nil, $0, __LINE__+4 end __END__ require 'test/unit' class TC_Set < Test::Unit::TestCase def test_aref assert_nothing_raised { Set[] Set[nil] Set[1,2,3] } assert_equal(0, Set[].size) assert_equal(1, Set[nil].size) assert_equal(1, Set[[]].size) assert_equal(1, Set[[nil]].size) set = Set[2,4,6,4] assert_equal(Set.new([2,4,6]), set) end def test_s_new assert_nothing_raised { Set.new() Set.new(nil) Set.new([]) Set.new([1,2]) Set.new('a'..'c') Set.new('XYZ') } assert_raises(ArgumentError) { Set.new(false) } assert_raises(ArgumentError) { Set.new(1) } assert_raises(ArgumentError) { Set.new(1,2) } assert_equal(0, Set.new().size) assert_equal(0, Set.new(nil).size) assert_equal(0, Set.new([]).size) assert_equal(1, Set.new([nil]).size) ary = [2,4,6,4] set = Set.new(ary) ary.clear assert_equal(false, set.empty?) assert_equal(3, set.size) ary = [1,2,3] s = Set.new(ary) { |o| o * 2 } assert_equal([2,4,6], s.sort) end def test_clone set1 = Set.new set2 = set1.clone set1 << 'abc' assert_equal(Set.new, set2) end def test_dup set1 = Set[1,2] set2 = set1.dup assert_not_same(set1, set2) assert_equal(set1, set2) set1.add(3) assert_not_equal(set1, set2) end def test_size assert_equal(0, Set[].size) assert_equal(2, Set[1,2].size) assert_equal(2, Set[1,2,1].size) end def test_empty? assert_equal(true, Set[].empty?) assert_equal(false, Set[1, 2].empty?) end def test_clear set = Set[1,2] ret = set.clear assert_same(set, ret) assert_equal(true, set.empty?) end def test_replace set = Set[1,2] ret = set.replace('a'..'c') assert_same(set, ret) assert_equal(Set['a','b','c'], set) end def test_to_a set = Set[1,2,3,2] ary = set.to_a assert_equal([1,2,3], ary.sort) end def test_flatten # test1 set1 = Set[ 1, Set[ 5, Set[7, Set[0] ], Set[6,2], 1 ], 3, Set[3,4] ] set2 = set1.flatten set3 = Set.new(0..7) assert_not_same(set2, set1) assert_equal(set3, set2) # test2; destructive orig_set1 = set1 set1.flatten! assert_same(orig_set1, set1) assert_equal(set3, set1) # test3; multiple occurrences of a set in an set set1 = Set[1, 2] set2 = Set[set1, Set[set1, 4], 3] assert_nothing_raised { set2.flatten! } assert_equal(Set.new(1..4), set2) # test4; recursion set2 = Set[] set1 = Set[1, set2] set2.add(set1) assert_raises(ArgumentError) { set1.flatten! } # test5; miscellaneous empty = Set[] set = Set[Set[empty, "a"],Set[empty, "b"]] assert_nothing_raised { set.flatten } set1 = empty.merge(Set["no_more", set]) assert_nil(Set.new(0..31).flatten!) x = Set[Set[],Set[1,2]].flatten! y = Set[1,2] assert_equal(x, y) end def test_include? set = Set[1,2,3] assert_equal(true, set.include?(1)) assert_equal(true, set.include?(2)) assert_equal(true, set.include?(3)) assert_equal(false, set.include?(0)) assert_equal(false, set.include?(nil)) set = Set["1",nil,"2",nil,"0","1",false] assert_equal(true, set.include?(nil)) assert_equal(true, set.include?(false)) assert_equal(true, set.include?("1")) assert_equal(false, set.include?(0)) assert_equal(false, set.include?(true)) end def test_superset? set = Set[1,2,3] assert_raises(ArgumentError) { set.superset?() } assert_raises(ArgumentError) { set.superset?(2) } assert_raises(ArgumentError) { set.superset?([2]) } assert_equal(true, set.superset?(Set[])) assert_equal(true, set.superset?(Set[1,2])) assert_equal(true, set.superset?(Set[1,2,3])) assert_equal(false, set.superset?(Set[1,2,3,4])) assert_equal(false, set.superset?(Set[1,4])) assert_equal(true, Set[].superset?(Set[])) end def test_proper_superset? set = Set[1,2,3] assert_raises(ArgumentError) { set.proper_superset?() } assert_raises(ArgumentError) { set.proper_superset?(2) } assert_raises(ArgumentError) { set.proper_superset?([2]) } assert_equal(true, set.proper_superset?(Set[])) assert_equal(true, set.proper_superset?(Set[1,2])) assert_equal(false, set.proper_superset?(Set[1,2,3])) assert_equal(false, set.proper_superset?(Set[1,2,3,4])) assert_equal(false, set.proper_superset?(Set[1,4])) assert_equal(false, Set[].proper_superset?(Set[])) end def test_subset? set = Set[1,2,3] assert_raises(ArgumentError) { set.subset?() } assert_raises(ArgumentError) { set.subset?(2) } assert_raises(ArgumentError) { set.subset?([2]) } assert_equal(true, set.subset?(Set[1,2,3,4])) assert_equal(true, set.subset?(Set[1,2,3])) assert_equal(false, set.subset?(Set[1,2])) assert_equal(false, set.subset?(Set[])) assert_equal(true, Set[].subset?(Set[1])) assert_equal(true, Set[].subset?(Set[])) end def test_proper_subset? set = Set[1,2,3] assert_raises(ArgumentError) { set.proper_subset?() } assert_raises(ArgumentError) { set.proper_subset?(2) } assert_raises(ArgumentError) { set.proper_subset?([2]) } assert_equal(true, set.proper_subset?(Set[1,2,3,4])) assert_equal(false, set.proper_subset?(Set[1,2,3])) assert_equal(false, set.proper_subset?(Set[1,2])) assert_equal(false, set.proper_subset?(Set[])) assert_equal(false, Set[].proper_subset?(Set[])) end def test_each ary = [1,3,5,7,10,20] set = Set.new(ary) ret = set.each { |o| } assert_same(set, ret) e = set.each assert_instance_of(Enumerable::Enumerator, e) assert_nothing_raised { set.each { |o| ary.delete(o) or raise "unexpected element: #{o}" } ary.empty? or raise "forgotten elements: #{ary.join(', ')}" } end def test_add set = Set[1,2,3] ret = set.add(2) assert_same(set, ret) assert_equal(Set[1,2,3], set) ret = set.add?(2) assert_nil(ret) assert_equal(Set[1,2,3], set) ret = set.add(4) assert_same(set, ret) assert_equal(Set[1,2,3,4], set) ret = set.add?(5) assert_same(set, ret) assert_equal(Set[1,2,3,4,5], set) end def test_delete set = Set[1,2,3] ret = set.delete(4) assert_same(set, ret) assert_equal(Set[1,2,3], set) ret = set.delete?(4) assert_nil(ret) assert_equal(Set[1,2,3], set) ret = set.delete(2) assert_equal(set, ret) assert_equal(Set[1,3], set) ret = set.delete?(1) assert_equal(set, ret) assert_equal(Set[3], set) end def test_delete_if set = Set.new(1..10) ret = set.delete_if { |i| i > 10 } assert_same(set, ret) assert_equal(Set.new(1..10), set) set = Set.new(1..10) ret = set.delete_if { |i| i % 3 == 0 } assert_same(set, ret) assert_equal(Set[1,2,4,5,7,8,10], set) end def test_collect! set = Set[1,2,3,'a','b','c',-1..1,2..4] ret = set.collect! { |i| case i when Numeric i * 2 when String i.upcase else nil end } assert_same(set, ret) assert_equal(Set[2,4,6,'A','B','C',nil], set) end def test_reject! set = Set.new(1..10) ret = set.reject! { |i| i > 10 } assert_nil(ret) assert_equal(Set.new(1..10), set) ret = set.reject! { |i| i % 3 == 0 } assert_same(set, ret) assert_equal(Set[1,2,4,5,7,8,10], set) end def test_merge set = Set[1,2,3] ret = set.merge([2,4,6]) assert_same(set, ret) assert_equal(Set[1,2,3,4,6], set) end def test_subtract set = Set[1,2,3] ret = set.subtract([2,4,6]) assert_same(set, ret) assert_equal(Set[1,3], set) end def test_plus set = Set[1,2,3] ret = set + [2,4,6] assert_not_same(set, ret) assert_equal(Set[1,2,3,4,6], ret) end def test_minus set = Set[1,2,3] ret = set - [2,4,6] assert_not_same(set, ret) assert_equal(Set[1,3], ret) end def test_and set = Set[1,2,3,4] ret = set & [2,4,6] assert_not_same(set, ret) assert_equal(Set[2,4], ret) end def test_xor set = Set[1,2,3,4] ret = set ^ [2,4,5,5] assert_not_same(set, ret) assert_equal(Set[1,3,5], ret) end def test_eq set1 = Set[2,3,1] set2 = Set[1,2,3] assert_equal(set1, set1) assert_equal(set1, set2) assert_not_equal(Set[1], [1]) set1 = Class.new(Set)["a", "b"] set2 = Set["a", "b", set1] set1 = set1.add(set1.clone) # assert_equal(set1, set2) # assert_equal(set2, set1) assert_equal(set2, set2.clone) assert_equal(set1.clone, set1) assert_not_equal(Set[Exception.new,nil], Set[Exception.new,Exception.new], "[ruby-dev:26127]") end # def test_hash # end # def test_eql? # end def test_classify set = Set.new(1..10) ret = set.classify { |i| i % 3 } assert_equal(3, ret.size) assert_instance_of(Hash, ret) ret.each_value { |value| assert_instance_of(Set, value) } assert_equal(Set[3,6,9], ret[0]) assert_equal(Set[1,4,7,10], ret[1]) assert_equal(Set[2,5,8], ret[2]) end def test_divide set = Set.new(1..10) ret = set.divide { |i| i % 3 } assert_equal(3, ret.size) n = 0 ret.each { |s| n += s.size } assert_equal(set.size, n) assert_equal(set, ret.flatten) set = Set[7,10,5,11,1,3,4,9,0] ret = set.divide { |a,b| (a - b).abs == 1 } assert_equal(4, ret.size) n = 0 ret.each { |s| n += s.size } assert_equal(set.size, n) assert_equal(set, ret.flatten) ret.each { |s| if s.include?(0) assert_equal(Set[0,1], s) elsif s.include?(3) assert_equal(Set[3,4,5], s) elsif s.include?(7) assert_equal(Set[7], s) elsif s.include?(9) assert_equal(Set[9,10,11], s) else raise "unexpected group: #{s.inspect}" end } end def test_inspect set1 = Set[1] assert_equal('#<Set: {1}>', set1.inspect) set2 = Set[Set[0], 1, 2, set1] assert_equal(false, set2.inspect.include?('#<Set: {...}>')) set1.add(set2) assert_equal(true, set1.inspect.include?('#<Set: {...}>')) end # def test_pretty_print # end # def test_pretty_print_cycle # end end class TC_SortedSet < Test::Unit::TestCase def test_sortedset s = SortedSet[4,5,3,1,2] assert_equal([1,2,3,4,5], s.to_a) prev = nil s.each { |o| assert(prev < o) if prev; prev = o } assert_not_nil(prev) s.map! { |o| -2 * o } assert_equal([-10,-8,-6,-4,-2], s.to_a) prev = nil ret = s.each { |o| assert(prev < o) if prev; prev = o } assert_not_nil(prev) assert_same(s, ret) s = SortedSet.new([2,1,3]) { |o| o * -2 } assert_equal([-6,-4,-2], s.to_a) s = SortedSet.new(['one', 'two', 'three', 'four']) a = [] ret = s.delete_if { |o| a << o; o.start_with?('t') } assert_same(s, ret) assert_equal(['four', 'one'], s.to_a) assert_equal(['four', 'one', 'three', 'two'], a) s = SortedSet.new(['one', 'two', 'three', 'four']) a = [] ret = s.reject! { |o| a << o; o.start_with?('t') } assert_same(s, ret) assert_equal(['four', 'one'], s.to_a) assert_equal(['four', 'one', 'three', 'two'], a) s = SortedSet.new(['one', 'two', 'three', 'four']) a = [] ret = s.reject! { |o| a << o; false } assert_same(nil, ret) assert_equal(['four', 'one', 'three', 'two'], s.to_a) assert_equal(['four', 'one', 'three', 'two'], a) end end class TC_Enumerable < Test::Unit::TestCase def test_to_set ary = [2,5,4,3,2,1,3] set = ary.to_set assert_instance_of(Set, set) assert_equal([1,2,3,4,5], set.sort) set = ary.to_set { |o| o * -2 } assert_instance_of(Set, set) assert_equal([-10,-8,-6,-4,-2], set.sort) set = ary.to_set(SortedSet) assert_instance_of(SortedSet, set) assert_equal([1,2,3,4,5], set.to_a) set = ary.to_set(SortedSet) { |o| o * -2 } assert_instance_of(SortedSet, set) assert_equal([-10,-8,-6,-4,-2], set.sort) end end # class TC_RestricedSet < Test::Unit::TestCase # def test_s_new # assert_raises(ArgumentError) { RestricedSet.new } # # s = RestricedSet.new([-1,2,3]) { |o| o > 0 } # assert_equal([2,3], s.sort) # end # # def test_restriction_proc # s = RestricedSet.new([-1,2,3]) { |o| o > 0 } # # f = s.restriction_proc # assert_instance_of(Proc, f) # assert(f[1]) # assert(!f[0]) # end # # def test_replace # s = RestricedSet.new(-3..3) { |o| o > 0 } # assert_equal([1,2,3], s.sort) # # s.replace([-2,0,3,4,5]) # assert_equal([3,4,5], s.sort) # end # # def test_merge # s = RestricedSet.new { |o| o > 0 } # s.merge(-5..5) # assert_equal([1,2,3,4,5], s.sort) # # s.merge([10,-10,-8,8]) # assert_equal([1,2,3,4,5,8,10], s.sort) # end # end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/time.rb
tools/jruby-1.5.1/lib/ruby/1.8/time.rb
# # == Introduction # # This library extends the Time class: # * conversion between date string and time object. # * date-time defined by RFC 2822 # * HTTP-date defined by RFC 2616 # * dateTime defined by XML Schema Part 2: Datatypes (ISO 8601) # * various formats handled by Date._parse (string to time only) # # == Design Issues # # === Specialized interface # # This library provides methods dedicated to special purposes: # * RFC 2822, RFC 2616 and XML Schema. # * They makes usual life easier. # # === Doesn't depend on strftime # # This library doesn't use +strftime+. Especially #rfc2822 doesn't depend # on +strftime+ because: # # * %a and %b are locale sensitive # # Since they are locale sensitive, they may be replaced to # invalid weekday/month name in some locales. # Since ruby-1.6 doesn't invoke setlocale by default, # the problem doesn't arise until some external library invokes setlocale. # Ruby/GTK is the example of such library. # # * %z is not portable # # %z is required to generate zone in date-time of RFC 2822 # but it is not portable. # # == Revision Information # # $Id$ # require 'parsedate' # # Implements the extensions to the Time class that are described in the # documentation for the time.rb library. # class Time class << Time ZoneOffset = { 'UTC' => 0, # ISO 8601 'Z' => 0, # RFC 822 'UT' => 0, 'GMT' => 0, 'EST' => -5, 'EDT' => -4, 'CST' => -6, 'CDT' => -5, 'MST' => -7, 'MDT' => -6, 'PST' => -8, 'PDT' => -7, # Following definition of military zones is original one. # See RFC 1123 and RFC 2822 for the error in RFC 822. 'A' => +1, 'B' => +2, 'C' => +3, 'D' => +4, 'E' => +5, 'F' => +6, 'G' => +7, 'H' => +8, 'I' => +9, 'K' => +10, 'L' => +11, 'M' => +12, 'N' => -1, 'O' => -2, 'P' => -3, 'Q' => -4, 'R' => -5, 'S' => -6, 'T' => -7, 'U' => -8, 'V' => -9, 'W' => -10, 'X' => -11, 'Y' => -12, } def zone_offset(zone, year=self.now.year) off = nil zone = zone.upcase if /\A([+-])(\d\d):?(\d\d)\z/ =~ zone off = ($1 == '-' ? -1 : 1) * ($2.to_i * 60 + $3.to_i) * 60 elsif /\A[+-]\d\d\z/ =~ zone off = zone.to_i * 3600 elsif ZoneOffset.include?(zone) off = ZoneOffset[zone] * 3600 elsif ((t = self.local(year, 1, 1)).zone.upcase == zone rescue false) off = t.utc_offset elsif ((t = self.local(year, 7, 1)).zone.upcase == zone rescue false) off = t.utc_offset end off end def zone_utc?(zone) # * +0000 means localtime. [RFC 2822] # * GMT is a localtime abbreviation in Europe/London, etc. if /\A(?:-00:00|-0000|-00|UTC|Z|UT)\z/i =~ zone true else false end end private :zone_utc? LeapYearMonthDays = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] CommonYearMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def month_days(y, m) if ((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0) LeapYearMonthDays[m-1] else CommonYearMonthDays[m-1] end end private :month_days def apply_offset(year, mon, day, hour, min, sec, off) if off < 0 off = -off off, o = off.divmod(60) if o != 0 then sec += o; o, sec = sec.divmod(60); off += o end off, o = off.divmod(60) if o != 0 then min += o; o, min = min.divmod(60); off += o end off, o = off.divmod(24) if o != 0 then hour += o; o, hour = hour.divmod(24); off += o end if off != 0 day += off if month_days(year, mon) < day mon += 1 if 12 < mon mon = 1 year += 1 end day = 1 end end elsif 0 < off off, o = off.divmod(60) if o != 0 then sec -= o; o, sec = sec.divmod(60); off -= o end off, o = off.divmod(60) if o != 0 then min -= o; o, min = min.divmod(60); off -= o end off, o = off.divmod(24) if o != 0 then hour -= o; o, hour = hour.divmod(24); off -= o end if off != 0 then day -= off if day < 1 mon -= 1 if mon < 1 year -= 1 mon = 12 end day = month_days(year, mon) end end end return year, mon, day, hour, min, sec end private :apply_offset def make_time(year, mon, day, hour, min, sec, sec_fraction, zone, now) usec = nil usec = (sec_fraction * 1000000).to_i if sec_fraction if now begin break if year; year = now.year break if mon; mon = now.mon break if day; day = now.day break if hour; hour = now.hour break if min; min = now.min break if sec; sec = now.sec break if sec_fraction; usec = now.tv_usec end until true end year ||= 1970 mon ||= 1 day ||= 1 hour ||= 0 min ||= 0 sec ||= 0 usec ||= 0 off = nil off = zone_offset(zone, year) if zone if off year, mon, day, hour, min, sec = apply_offset(year, mon, day, hour, min, sec, off) t = self.utc(year, mon, day, hour, min, sec, usec) t.localtime if !zone_utc?(zone) t else self.local(year, mon, day, hour, min, sec, usec) end end private :make_time # # Parses +date+ using Date._parse and converts it to a Time object. # # If a block is given, the year described in +date+ is converted by the # block. For example: # # Time.parse(...) {|y| y < 100 ? (y >= 69 ? y + 1900 : y + 2000) : y} # # If the upper components of the given time are broken or missing, they are # supplied with those of +now+. For the lower components, the minimum # values (1 or 0) are assumed if broken or missing. For example: # # # Suppose it is "Thu Nov 29 14:33:20 GMT 2001" now and # # your timezone is GMT: # Time.parse("16:30") #=> Thu Nov 29 16:30:00 GMT 2001 # Time.parse("7/23") #=> Mon Jul 23 00:00:00 GMT 2001 # Time.parse("Aug 31") #=> Fri Aug 31 00:00:00 GMT 2001 # # Since there are numerous conflicts among locally defined timezone # abbreviations all over the world, this method is not made to # understand all of them. For example, the abbreviation "CST" is # used variously as: # # -06:00 in America/Chicago, # -05:00 in America/Havana, # +08:00 in Asia/Harbin, # +09:30 in Australia/Darwin, # +10:30 in Australia/Adelaide, # etc. # # Based on the fact, this method only understands the timezone # abbreviations described in RFC 822 and the system timezone, in the # order named. (i.e. a definition in RFC 822 overrides the system # timezone definition.) The system timezone is taken from # <tt>Time.local(year, 1, 1).zone</tt> and # <tt>Time.local(year, 7, 1).zone</tt>. # If the extracted timezone abbreviation does not match any of them, # it is ignored and the given time is regarded as a local time. # # ArgumentError is raised if Date._parse cannot extract information from # +date+ or Time class cannot represent specified date. # # This method can be used as fail-safe for other parsing methods as: # # Time.rfc2822(date) rescue Time.parse(date) # Time.httpdate(date) rescue Time.parse(date) # Time.xmlschema(date) rescue Time.parse(date) # # A failure for Time.parse should be checked, though. # def parse(date, now=self.now) d = Date._parse(date, false) year = d[:year] year = yield(year) if year && block_given? make_time(year, d[:mon], d[:mday], d[:hour], d[:min], d[:sec], d[:sec_fraction], d[:zone], now) end MonthValue = { 'JAN' => 1, 'FEB' => 2, 'MAR' => 3, 'APR' => 4, 'MAY' => 5, 'JUN' => 6, 'JUL' => 7, 'AUG' => 8, 'SEP' => 9, 'OCT' =>10, 'NOV' =>11, 'DEC' =>12 } # # Parses +date+ as date-time defined by RFC 2822 and converts it to a Time # object. The format is identical to the date format defined by RFC 822 and # updated by RFC 1123. # # ArgumentError is raised if +date+ is not compliant with RFC 2822 # or Time class cannot represent specified date. # # See #rfc2822 for more information on this format. # def rfc2822(date) if /\A\s* (?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s*,\s*)? (\d{1,2})\s+ (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+ (\d{2,})\s+ (\d{2})\s* :\s*(\d{2})\s* (?::\s*(\d{2}))?\s+ ([+-]\d{4}| UT|GMT|EST|EDT|CST|CDT|MST|MDT|PST|PDT|[A-IK-Z])/ix =~ date # Since RFC 2822 permit comments, the regexp has no right anchor. day = $1.to_i mon = MonthValue[$2.upcase] year = $3.to_i hour = $4.to_i min = $5.to_i sec = $6 ? $6.to_i : 0 zone = $7 # following year completion is compliant with RFC 2822. year = if year < 50 2000 + year elsif year < 1000 1900 + year else year end year, mon, day, hour, min, sec = apply_offset(year, mon, day, hour, min, sec, zone_offset(zone)) t = self.utc(year, mon, day, hour, min, sec) t.localtime if !zone_utc?(zone) t else raise ArgumentError.new("not RFC 2822 compliant date: #{date.inspect}") end end alias rfc822 rfc2822 # # Parses +date+ as HTTP-date defined by RFC 2616 and converts it to a Time # object. # # ArgumentError is raised if +date+ is not compliant with RFC 2616 or Time # class cannot represent specified date. # # See #httpdate for more information on this format. # def httpdate(date) if /\A\s* (?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),\x20 (\d{2})\x20 (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\x20 (\d{4})\x20 (\d{2}):(\d{2}):(\d{2})\x20 GMT \s*\z/ix =~ date self.rfc2822(date) elsif /\A\s* (?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday),\x20 (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d)\x20 (\d\d):(\d\d):(\d\d)\x20 GMT \s*\z/ix =~ date self.parse(date) elsif /\A\s* (?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\x20 (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\x20 (\d\d|\x20\d)\x20 (\d\d):(\d\d):(\d\d)\x20 (\d{4}) \s*\z/ix =~ date self.utc($6.to_i, MonthValue[$1.upcase], $2.to_i, $3.to_i, $4.to_i, $5.to_i) else raise ArgumentError.new("not RFC 2616 compliant date: #{date.inspect}") end end # # Parses +date+ as dateTime defined by XML Schema and converts it to a Time # object. The format is restricted version of the format defined by ISO # 8601. # # ArgumentError is raised if +date+ is not compliant with the format or Time # class cannot represent specified date. # # See #xmlschema for more information on this format. # def xmlschema(date) if /\A\s* (-?\d+)-(\d\d)-(\d\d) T (\d\d):(\d\d):(\d\d) (\.\d*)? (Z|[+-]\d\d:\d\d)? \s*\z/ix =~ date year = $1.to_i mon = $2.to_i day = $3.to_i hour = $4.to_i min = $5.to_i sec = $6.to_i usec = 0 usec = ($7[1..-1] + '000000')[0,6].to_i if $7 if $8 zone = $8 year, mon, day, hour, min, sec = apply_offset(year, mon, day, hour, min, sec, zone_offset(zone)) self.utc(year, mon, day, hour, min, sec, usec) else self.local(year, mon, day, hour, min, sec, usec) end else raise ArgumentError.new("invalid date: #{date.inspect}") end end alias iso8601 xmlschema end # class << self # # Returns a string which represents the time as date-time defined by RFC 2822: # # day-of-week, DD month-name CCYY hh:mm:ss zone # # where zone is [+-]hhmm. # # If +self+ is a UTC time, -0000 is used as zone. # def rfc2822 sprintf('%s, %02d %s %d %02d:%02d:%02d ', RFC2822_DAY_NAME[wday], day, RFC2822_MONTH_NAME[mon-1], year, hour, min, sec) + if utc? '-0000' else off = utc_offset sign = off < 0 ? '-' : '+' sprintf('%s%02d%02d', sign, *(off.abs / 60).divmod(60)) end end alias rfc822 rfc2822 RFC2822_DAY_NAME = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ] RFC2822_MONTH_NAME = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] # # Returns a string which represents the time as rfc1123-date of HTTP-date # defined by RFC 2616: # # day-of-week, DD month-name CCYY hh:mm:ss GMT # # Note that the result is always UTC (GMT). # def httpdate t = dup.utc sprintf('%s, %02d %s %d %02d:%02d:%02d GMT', RFC2822_DAY_NAME[t.wday], t.day, RFC2822_MONTH_NAME[t.mon-1], t.year, t.hour, t.min, t.sec) end # # Returns a string which represents the time as dateTime defined by XML # Schema: # # CCYY-MM-DDThh:mm:ssTZD # CCYY-MM-DDThh:mm:ss.sssTZD # # where TZD is Z or [+-]hh:mm. # # If self is a UTC time, Z is used as TZD. [+-]hh:mm is used otherwise. # # +fractional_seconds+ specifies a number of digits of fractional seconds. # Its default value is 0. # def xmlschema(fraction_digits=0) sprintf('%d-%02d-%02dT%02d:%02d:%02d', year, mon, day, hour, min, sec) + if fraction_digits == 0 '' elsif fraction_digits <= 6 '.' + sprintf('%06d', usec)[0, fraction_digits] else '.' + sprintf('%06d', usec) + '0' * (fraction_digits - 6) end + if utc? 'Z' else off = utc_offset sign = off < 0 ? '-' : '+' sprintf('%s%02d:%02d', sign, *(off.abs / 60).divmod(60)) end end alias iso8601 xmlschema end if __FILE__ == $0 require 'test/unit' class TimeExtentionTest < Test::Unit::TestCase # :nodoc: def test_rfc822 assert_equal(Time.utc(1976, 8, 26, 14, 30) + 4 * 3600, Time.rfc2822("26 Aug 76 14:30 EDT")) assert_equal(Time.utc(1976, 8, 27, 9, 32) + 7 * 3600, Time.rfc2822("27 Aug 76 09:32 PDT")) end def test_rfc2822 assert_equal(Time.utc(1997, 11, 21, 9, 55, 6) + 6 * 3600, Time.rfc2822("Fri, 21 Nov 1997 09:55:06 -0600")) assert_equal(Time.utc(2003, 7, 1, 10, 52, 37) - 2 * 3600, Time.rfc2822("Tue, 1 Jul 2003 10:52:37 +0200")) assert_equal(Time.utc(1997, 11, 21, 10, 1, 10) + 6 * 3600, Time.rfc2822("Fri, 21 Nov 1997 10:01:10 -0600")) assert_equal(Time.utc(1997, 11, 21, 11, 0, 0) + 6 * 3600, Time.rfc2822("Fri, 21 Nov 1997 11:00:00 -0600")) assert_equal(Time.utc(1997, 11, 24, 14, 22, 1) + 8 * 3600, Time.rfc2822("Mon, 24 Nov 1997 14:22:01 -0800")) begin Time.at(-1) rescue ArgumentError # ignore else assert_equal(Time.utc(1969, 2, 13, 23, 32, 54) + 3 * 3600 + 30 * 60, Time.rfc2822("Thu, 13 Feb 1969 23:32:54 -0330")) assert_equal(Time.utc(1969, 2, 13, 23, 32, 0) + 3 * 3600 + 30 * 60, Time.rfc2822(" Thu, 13 Feb 1969 23:32 -0330 (Newfoundland Time)")) end assert_equal(Time.utc(1997, 11, 21, 9, 55, 6), Time.rfc2822("21 Nov 97 09:55:06 GMT")) assert_equal(Time.utc(1997, 11, 21, 9, 55, 6) + 6 * 3600, Time.rfc2822("Fri, 21 Nov 1997 09 : 55 : 06 -0600")) assert_raise(ArgumentError) { # inner comment is not supported. Time.rfc2822("Fri, 21 Nov 1997 09(comment): 55 : 06 -0600") } end def test_rfc2616 t = Time.utc(1994, 11, 6, 8, 49, 37) assert_equal(t, Time.httpdate("Sun, 06 Nov 1994 08:49:37 GMT")) assert_equal(t, Time.httpdate("Sunday, 06-Nov-94 08:49:37 GMT")) assert_equal(t, Time.httpdate("Sun Nov 6 08:49:37 1994")) assert_equal(Time.utc(1995, 11, 15, 6, 25, 24), Time.httpdate("Wed, 15 Nov 1995 06:25:24 GMT")) assert_equal(Time.utc(1995, 11, 15, 4, 58, 8), Time.httpdate("Wed, 15 Nov 1995 04:58:08 GMT")) assert_equal(Time.utc(1994, 11, 15, 8, 12, 31), Time.httpdate("Tue, 15 Nov 1994 08:12:31 GMT")) assert_equal(Time.utc(1994, 12, 1, 16, 0, 0), Time.httpdate("Thu, 01 Dec 1994 16:00:00 GMT")) assert_equal(Time.utc(1994, 10, 29, 19, 43, 31), Time.httpdate("Sat, 29 Oct 1994 19:43:31 GMT")) assert_equal(Time.utc(1994, 11, 15, 12, 45, 26), Time.httpdate("Tue, 15 Nov 1994 12:45:26 GMT")) assert_equal(Time.utc(1999, 12, 31, 23, 59, 59), Time.httpdate("Fri, 31 Dec 1999 23:59:59 GMT")) end def test_rfc3339 t = Time.utc(1985, 4, 12, 23, 20, 50, 520000) s = "1985-04-12T23:20:50.52Z" assert_equal(t, Time.iso8601(s)) assert_equal(s, t.iso8601(2)) t = Time.utc(1996, 12, 20, 0, 39, 57) s = "1996-12-19T16:39:57-08:00" assert_equal(t, Time.iso8601(s)) # There is no way to generate time string with arbitrary timezone. s = "1996-12-20T00:39:57Z" assert_equal(t, Time.iso8601(s)) assert_equal(s, t.iso8601) t = Time.utc(1990, 12, 31, 23, 59, 60) s = "1990-12-31T23:59:60Z" assert_equal(t, Time.iso8601(s)) # leap second is representable only if timezone file has it. s = "1990-12-31T15:59:60-08:00" assert_equal(t, Time.iso8601(s)) begin Time.at(-1) rescue ArgumentError # ignore else t = Time.utc(1937, 1, 1, 11, 40, 27, 870000) s = "1937-01-01T12:00:27.87+00:20" assert_equal(t, Time.iso8601(s)) end end # http://www.w3.org/TR/xmlschema-2/ def test_xmlschema assert_equal(Time.utc(1999, 5, 31, 13, 20, 0) + 5 * 3600, Time.xmlschema("1999-05-31T13:20:00-05:00")) assert_equal(Time.local(2000, 1, 20, 12, 0, 0), Time.xmlschema("2000-01-20T12:00:00")) assert_equal(Time.utc(2000, 1, 20, 12, 0, 0), Time.xmlschema("2000-01-20T12:00:00Z")) assert_equal(Time.utc(2000, 1, 20, 12, 0, 0) - 12 * 3600, Time.xmlschema("2000-01-20T12:00:00+12:00")) assert_equal(Time.utc(2000, 1, 20, 12, 0, 0) + 13 * 3600, Time.xmlschema("2000-01-20T12:00:00-13:00")) assert_equal(Time.utc(2000, 3, 4, 23, 0, 0) - 3 * 3600, Time.xmlschema("2000-03-04T23:00:00+03:00")) assert_equal(Time.utc(2000, 3, 4, 20, 0, 0), Time.xmlschema("2000-03-04T20:00:00Z")) assert_equal(Time.local(2000, 1, 15, 0, 0, 0), Time.xmlschema("2000-01-15T00:00:00")) assert_equal(Time.local(2000, 2, 15, 0, 0, 0), Time.xmlschema("2000-02-15T00:00:00")) assert_equal(Time.local(2000, 1, 15, 12, 0, 0), Time.xmlschema("2000-01-15T12:00:00")) assert_equal(Time.utc(2000, 1, 16, 12, 0, 0), Time.xmlschema("2000-01-16T12:00:00Z")) assert_equal(Time.local(2000, 1, 1, 12, 0, 0), Time.xmlschema("2000-01-01T12:00:00")) assert_equal(Time.utc(1999, 12, 31, 23, 0, 0), Time.xmlschema("1999-12-31T23:00:00Z")) assert_equal(Time.local(2000, 1, 16, 12, 0, 0), Time.xmlschema("2000-01-16T12:00:00")) assert_equal(Time.local(2000, 1, 16, 0, 0, 0), Time.xmlschema("2000-01-16T00:00:00")) assert_equal(Time.utc(2000, 1, 12, 12, 13, 14), Time.xmlschema("2000-01-12T12:13:14Z")) assert_equal(Time.utc(2001, 4, 17, 19, 23, 17, 300000), Time.xmlschema("2001-04-17T19:23:17.3Z")) end def test_encode_xmlschema t = Time.utc(2001, 4, 17, 19, 23, 17, 300000) assert_equal("2001-04-17T19:23:17Z", t.xmlschema) assert_equal("2001-04-17T19:23:17.3Z", t.xmlschema(1)) assert_equal("2001-04-17T19:23:17.300000Z", t.xmlschema(6)) assert_equal("2001-04-17T19:23:17.3000000Z", t.xmlschema(7)) t = Time.utc(2001, 4, 17, 19, 23, 17, 123456) assert_equal("2001-04-17T19:23:17.1234560Z", t.xmlschema(7)) assert_equal("2001-04-17T19:23:17.123456Z", t.xmlschema(6)) assert_equal("2001-04-17T19:23:17.12345Z", t.xmlschema(5)) assert_equal("2001-04-17T19:23:17.1Z", t.xmlschema(1)) begin Time.at(-1) rescue ArgumentError # ignore else t = Time.utc(1960, 12, 31, 23, 0, 0, 123456) assert_equal("1960-12-31T23:00:00.123456Z", t.xmlschema(6)) end assert_equal(249, Time.xmlschema("2008-06-05T23:49:23.000249+09:00").usec) end def test_completion now = Time.local(2001,11,29,21,26,35) assert_equal(Time.local( 2001,11,29,21,12), Time.parse("2001/11/29 21:12", now)) assert_equal(Time.local( 2001,11,29), Time.parse("2001/11/29", now)) assert_equal(Time.local( 2001,11,29), Time.parse( "11/29", now)) #assert_equal(Time.local(2001,11,1), Time.parse("Nov", now)) assert_equal(Time.local( 2001,11,29,10,22), Time.parse( "10:22", now)) end def test_invalid # They were actually used in some web sites. assert_raise(ArgumentError) { Time.httpdate("1 Dec 2001 10:23:57 GMT") } assert_raise(ArgumentError) { Time.httpdate("Sat, 1 Dec 2001 10:25:42 GMT") } assert_raise(ArgumentError) { Time.httpdate("Sat, 1-Dec-2001 10:53:55 GMT") } assert_raise(ArgumentError) { Time.httpdate("Saturday, 01-Dec-2001 10:15:34 GMT") } assert_raise(ArgumentError) { Time.httpdate("Saturday, 01-Dec-101 11:10:07 GMT") } assert_raise(ArgumentError) { Time.httpdate("Fri, 30 Nov 2001 21:30:00 JST") } # They were actually used in some mails. assert_raise(ArgumentError) { Time.rfc2822("01-5-20") } assert_raise(ArgumentError) { Time.rfc2822("7/21/00") } assert_raise(ArgumentError) { Time.rfc2822("2001-8-28") } assert_raise(ArgumentError) { Time.rfc2822("00-5-6 1:13:06") } assert_raise(ArgumentError) { Time.rfc2822("2001-9-27 9:36:49") } assert_raise(ArgumentError) { Time.rfc2822("2000-12-13 11:01:11") } assert_raise(ArgumentError) { Time.rfc2822("2001/10/17 04:29:55") } assert_raise(ArgumentError) { Time.rfc2822("9/4/2001 9:23:19 PM") } assert_raise(ArgumentError) { Time.rfc2822("01 Nov 2001 09:04:31") } assert_raise(ArgumentError) { Time.rfc2822("13 Feb 2001 16:4 GMT") } assert_raise(ArgumentError) { Time.rfc2822("01 Oct 00 5:41:19 PM") } assert_raise(ArgumentError) { Time.rfc2822("2 Jul 00 00:51:37 JST") } assert_raise(ArgumentError) { Time.rfc2822("01 11 2001 06:55:57 -0500") } assert_raise(ArgumentError) { Time.rfc2822("18 \343\366\356\341\370 2000") } assert_raise(ArgumentError) { Time.rfc2822("Fri, Oct 2001 18:53:32") } assert_raise(ArgumentError) { Time.rfc2822("Fri, 2 Nov 2001 03:47:54") } assert_raise(ArgumentError) { Time.rfc2822("Fri, 27 Jul 2001 11.14.14 +0200") } assert_raise(ArgumentError) { Time.rfc2822("Thu, 2 Nov 2000 04:13:53 -600") } assert_raise(ArgumentError) { Time.rfc2822("Wed, 5 Apr 2000 22:57:09 JST") } assert_raise(ArgumentError) { Time.rfc2822("Mon, 11 Sep 2000 19:47:33 00000") } assert_raise(ArgumentError) { Time.rfc2822("Fri, 28 Apr 2000 20:40:47 +-900") } assert_raise(ArgumentError) { Time.rfc2822("Fri, 19 Jan 2001 8:15:36 AM -0500") } assert_raise(ArgumentError) { Time.rfc2822("Thursday, Sep 27 2001 7:42:35 AM EST") } assert_raise(ArgumentError) { Time.rfc2822("3/11/2001 1:31:57 PM Pacific Daylight Time") } assert_raise(ArgumentError) { Time.rfc2822("Mi, 28 Mrz 2001 11:51:36") } assert_raise(ArgumentError) { Time.rfc2822("P, 30 sept 2001 23:03:14") } assert_raise(ArgumentError) { Time.rfc2822("fr, 11 aug 2000 18:39:22") } assert_raise(ArgumentError) { Time.rfc2822("Fr, 21 Sep 2001 17:44:03 -1000") } assert_raise(ArgumentError) { Time.rfc2822("Mo, 18 Jun 2001 19:21:40 -1000") } assert_raise(ArgumentError) { Time.rfc2822("l\366, 12 aug 2000 18:53:20") } assert_raise(ArgumentError) { Time.rfc2822("l\366, 26 maj 2001 00:15:58") } assert_raise(ArgumentError) { Time.rfc2822("Dom, 30 Sep 2001 17:36:30") } assert_raise(ArgumentError) { Time.rfc2822("%&, 31 %2/ 2000 15:44:47 -0500") } assert_raise(ArgumentError) { Time.rfc2822("dom, 26 ago 2001 03:57:07 -0300") } assert_raise(ArgumentError) { Time.rfc2822("ter, 04 set 2001 16:27:58 -0300") } assert_raise(ArgumentError) { Time.rfc2822("Wen, 3 oct 2001 23:17:49 -0400") } assert_raise(ArgumentError) { Time.rfc2822("Wen, 3 oct 2001 23:17:49 -0400") } assert_raise(ArgumentError) { Time.rfc2822("ele, 11 h: 2000 12:42:15 -0500") } assert_raise(ArgumentError) { Time.rfc2822("Tue, 14 Aug 2001 3:55:3 +0200") } assert_raise(ArgumentError) { Time.rfc2822("Fri, 25 Aug 2000 9:3:48 +0800") } assert_raise(ArgumentError) { Time.rfc2822("Fri, 1 Dec 2000 0:57:50 EST") } assert_raise(ArgumentError) { Time.rfc2822("Mon, 7 May 2001 9:39:51 +0200") } assert_raise(ArgumentError) { Time.rfc2822("Wed, 1 Aug 2001 16:9:15 +0200") } assert_raise(ArgumentError) { Time.rfc2822("Wed, 23 Aug 2000 9:17:36 +0800") } assert_raise(ArgumentError) { Time.rfc2822("Fri, 11 Aug 2000 10:4:42 +0800") } assert_raise(ArgumentError) { Time.rfc2822("Sat, 15 Sep 2001 13:22:2 +0300") } assert_raise(ArgumentError) { Time.rfc2822("Wed,16 \276\305\324\302 2001 20:06:25 +0800") } assert_raise(ArgumentError) { Time.rfc2822("Wed,7 \312\256\322\273\324\302 2001 23:47:22 +0800") } assert_raise(ArgumentError) { Time.rfc2822("=?iso-8859-1?Q?(=C5=DA),?= 10 2 2001 23:32:26 +0900 (JST)") } assert_raise(ArgumentError) { Time.rfc2822("\307\341\314\343\332\311, 30 \344\346\335\343\310\321 2001 10:01:06") } assert_raise(ArgumentError) { Time.rfc2822("=?iso-8859-1?Q?(=BF=E5),?= 12 =?iso-8859-1?Q?9=B7=EE?= 2001 14:52:41\n+0900 (JST)") } end def test_zone_0000 assert_equal(true, Time.parse("2000-01-01T00:00:00Z").utc?) assert_equal(true, Time.parse("2000-01-01T00:00:00-00:00").utc?) assert_equal(false, Time.parse("2000-01-01T00:00:00+00:00").utc?) assert_equal(false, Time.parse("Sat, 01 Jan 2000 00:00:00 GMT").utc?) assert_equal(true, Time.parse("Sat, 01 Jan 2000 00:00:00 -0000").utc?) assert_equal(false, Time.parse("Sat, 01 Jan 2000 00:00:00 +0000").utc?) assert_equal(false, Time.rfc2822("Sat, 01 Jan 2000 00:00:00 GMT").utc?) assert_equal(true, Time.rfc2822("Sat, 01 Jan 2000 00:00:00 -0000").utc?) assert_equal(false, Time.rfc2822("Sat, 01 Jan 2000 00:00:00 +0000").utc?) assert_equal(true, Time.rfc2822("Sat, 01 Jan 2000 00:00:00 UTC").utc?) end def test_parse_leap_second t = Time.utc(1998,12,31,23,59,59) assert_equal(t, Time.parse("Thu Dec 31 23:59:59 UTC 1998")) assert_equal(t, Time.parse("Fri Dec 31 23:59:59 -0000 1998"));t.localtime assert_equal(t, Time.parse("Fri Jan 1 08:59:59 +0900 1999")) assert_equal(t, Time.parse("Fri Jan 1 00:59:59 +0100 1999")) assert_equal(t, Time.parse("Fri Dec 31 23:59:59 +0000 1998")) assert_equal(t, Time.parse("Fri Dec 31 22:59:59 -0100 1998"));t.utc t += 1 assert_equal(t, Time.parse("Thu Dec 31 23:59:60 UTC 1998")) assert_equal(t, Time.parse("Fri Dec 31 23:59:60 -0000 1998"));t.localtime assert_equal(t, Time.parse("Fri Jan 1 08:59:60 +0900 1999")) assert_equal(t, Time.parse("Fri Jan 1 00:59:60 +0100 1999")) assert_equal(t, Time.parse("Fri Dec 31 23:59:60 +0000 1998")) assert_equal(t, Time.parse("Fri Dec 31 22:59:60 -0100 1998"));t.utc t += 1 if t.sec == 60 assert_equal(t, Time.parse("Thu Jan 1 00:00:00 UTC 1999")) assert_equal(t, Time.parse("Fri Jan 1 00:00:00 -0000 1999"));t.localtime assert_equal(t, Time.parse("Fri Jan 1 09:00:00 +0900 1999")) assert_equal(t, Time.parse("Fri Jan 1 01:00:00 +0100 1999")) assert_equal(t, Time.parse("Fri Jan 1 00:00:00 +0000 1999")) assert_equal(t, Time.parse("Fri Dec 31 23:00:00 -0100 1998")) end def test_rfc2822_leap_second t = Time.utc(1998,12,31,23,59,59) assert_equal(t, Time.rfc2822("Thu, 31 Dec 1998 23:59:59 UTC")) assert_equal(t, Time.rfc2822("Fri, 31 Dec 1998 23:59:59 -0000"));t.localtime assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 08:59:59 +0900")) assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 00:59:59 +0100")) assert_equal(t, Time.rfc2822("Fri, 31 Dec 1998 23:59:59 +0000")) assert_equal(t, Time.rfc2822("Fri, 31 Dec 1998 22:59:59 -0100"));t.utc t += 1 assert_equal(t, Time.rfc2822("Thu, 31 Dec 1998 23:59:60 UTC")) assert_equal(t, Time.rfc2822("Fri, 31 Dec 1998 23:59:60 -0000"));t.localtime assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 08:59:60 +0900")) assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 00:59:60 +0100")) assert_equal(t, Time.rfc2822("Fri, 31 Dec 1998 23:59:60 +0000")) assert_equal(t, Time.rfc2822("Fri, 31 Dec 1998 22:59:60 -0100"));t.utc t += 1 if t.sec == 60 assert_equal(t, Time.rfc2822("Thu, 1 Jan 1999 00:00:00 UTC")) assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 00:00:00 -0000"));t.localtime assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 09:00:00 +0900")) assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 01:00:00 +0100")) assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 00:00:00 +0000")) assert_equal(t, Time.rfc2822("Fri, 31 Dec 1998 23:00:00 -0100")) end def test_xmlschema_leap_second t = Time.utc(1998,12,31,23,59,59) assert_equal(t, Time.xmlschema("1998-12-31T23:59:59Z")) assert_equal(t, Time.xmlschema("1998-12-31T23:59:59-00:00"));t.localtime assert_equal(t, Time.xmlschema("1999-01-01T08:59:59+09:00")) assert_equal(t, Time.xmlschema("1999-01-01T00:59:59+01:00")) assert_equal(t, Time.xmlschema("1998-12-31T23:59:59+00:00")) assert_equal(t, Time.xmlschema("1998-12-31T22:59:59-01:00"));t.utc t += 1 assert_equal(t, Time.xmlschema("1998-12-31T23:59:60Z")) assert_equal(t, Time.xmlschema("1998-12-31T23:59:60-00:00"));t.localtime assert_equal(t, Time.xmlschema("1999-01-01T08:59:60+09:00")) assert_equal(t, Time.xmlschema("1999-01-01T00:59:60+01:00")) assert_equal(t, Time.xmlschema("1998-12-31T23:59:60+00:00")) assert_equal(t, Time.xmlschema("1998-12-31T22:59:60-01:00"));t.utc t += 1 if t.sec == 60 assert_equal(t, Time.xmlschema("1999-01-01T00:00:00Z")) assert_equal(t, Time.xmlschema("1999-01-01T00:00:00-00:00"));t.localtime assert_equal(t, Time.xmlschema("1999-01-01T09:00:00+09:00")) assert_equal(t, Time.xmlschema("1999-01-01T01:00:00+01:00")) assert_equal(t, Time.xmlschema("1999-01-01T00:00:00+00:00")) assert_equal(t, Time.xmlschema("1998-12-31T23:00:00-01:00")) end def test_ruby_talk_152866 t = Time::xmlschema('2005-08-30T22:48:00-07:00') assert_equal(31, t.day) assert_equal(8, t.mon) end def test_parse_fraction assert_equal(500000, Time.parse("2000-01-01T00:00:00.5+00:00").tv_usec) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/finalize.rb
tools/jruby-1.5.1/lib/ruby/1.8/finalize.rb
#-- # finalizer.rb - # $Release Version: 0.3$ # $Revision: 1.4 $ # $Date: 1998/02/27 05:34:33 $ # by Keiju ISHITSUKA #++ # # Usage: # # add dependency R_method(obj, dependant) # add(obj, dependant, method = :finalize, *opt) # add_dependency(obj, dependant, method = :finalize, *opt) # # delete dependency R_method(obj, dependant) # delete(obj_or_id, dependant, method = :finalize) # delete_dependency(obj_or_id, dependant, method = :finalize) # # delete dependency R_*(obj, dependant) # delete_all_dependency(obj_or_id, dependant) # # delete dependency R_method(*, dependant) # delete_by_dependant(dependant, method = :finalize) # # delete dependency R_*(*, dependant) # delete_all_by_dependant(dependant) # # delete all dependency R_*(*, *) # delete_all # # finalize the dependant connected by dependency R_method(obj, dependtant). # finalize(obj_or_id, dependant, method = :finalize) # finalize_dependency(obj_or_id, dependant, method = :finalize) # # finalize all dependants connected by dependency R_*(obj, dependtant). # finalize_all_dependency(obj_or_id, dependant) # # finalize the dependant connected by dependency R_method(*, dependtant). # finalize_by_dependant(dependant, method = :finalize) # # finalize all dependants connected by dependency R_*(*, dependant). # finalize_all_by_dependant(dependant) # # finalize all dependency registered to the Finalizer. # finalize_all # # stop invoking Finalizer on GC. # safe{..} # module Finalizer RCS_ID='-$Id: finalize.rb,v 1.4 1998/02/27 05:34:33 keiju Exp keiju $-' class <<self # @dependency: {id => [[dependant, method, *opt], ...], ...} # add dependency R_method(obj, dependant) def add_dependency(obj, dependant, method = :finalize, *opt) ObjectSpace.call_finalizer(obj) method = method.intern unless method.kind_of?(Integer) assoc = [dependant, method].concat(opt) if dep = @dependency[obj.object_id] dep.push assoc else @dependency[obj.object_id] = [assoc] end end alias add add_dependency # delete dependency R_method(obj, dependant) def delete_dependency(id, dependant, method = :finalize) id = id.object_id unless id.kind_of?(Integer) method = method.intern unless method.kind_of?(Integer) for assoc in @dependency[id] assoc.delete_if do |d, m, *o| d == dependant && m == method end @dependency.delete(id) if assoc.empty? end end alias delete delete_dependency # delete dependency R_*(obj, dependant) def delete_all_dependency(id, dependant) id = id.object_id unless id.kind_of?(Integer) method = method.intern unless method.kind_of?(Integer) for assoc in @dependency[id] assoc.delete_if do |d, m, *o| d == dependant end @dependency.delete(id) if assoc.empty? end end # delete dependency R_method(*, dependant) def delete_by_dependant(dependant, method = :finalize) method = method.intern unless method.kind_of?(Integer) for id in @dependency.keys delete(id, dependant, method) end end # delete dependency R_*(*, dependant) def delete_all_by_dependant(dependant) for id in @dependency.keys delete_all_dependency(id, dependant) end end # finalize the depandant connected by dependency R_method(obj, dependtant) def finalize_dependency(id, dependant, method = :finalize) id = id.object_id unless id.kind_of?(Integer) method = method.intern unless method.kind_of?(Integer) for assocs in @dependency[id] assocs.delete_if do |d, m, *o| d.send(m, id, *o) if ret = d == dependant && m == method ret end @dependency.delete(id) if assoc.empty? end end alias finalize finalize_dependency # finalize all dependants connected by dependency R_*(obj, dependtant) def finalize_all_dependency(id, dependant) id = id.object_id unless id.kind_of?(Integer) method = method.intern unless method.kind_of?(Integer) for assoc in @dependency[id] assoc.delete_if do |d, m, *o| d.send(m, id, *o) if ret = d == dependant end @dependency.delete(id) if assoc.empty? end end # finalize the dependant connected by dependency R_method(*, dependtant) def finalize_by_dependant(dependant, method = :finalize) method = method.intern unless method.kind_of?(Integer) for id in @dependency.keys finalize(id, dependant, method) end end # finalize all dependants connected by dependency R_*(*, dependtant) def finalize_all_by_dependant(dependant) for id in @dependency.keys finalize_all_dependency(id, dependant) end end # finalize all dependants registered to the Finalizer. def finalize_all for id, assocs in @dependency for dependant, method, *opt in assocs dependant.send(method, id, *opt) end assocs.clear end end # method to call finalize_* safely. def safe old_status = Thread.critical Thread.critical = true ObjectSpace.remove_finalizer(@proc) begin yield ensure ObjectSpace.add_finalizer(@proc) Thread.critical = old_status end end private # registering function to ObjectSpace#add_finalizer def final_of(id) if assocs = @dependency.delete(id) for dependant, method, *opt in assocs dependant.send(method, id, *opt) end end end end @dependency = Hash.new @proc = proc{|id| final_of(id)} ObjectSpace.add_finalizer(@proc) end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/fileutils.rb
tools/jruby-1.5.1/lib/ruby/1.8/fileutils.rb
# # = fileutils.rb # # Copyright (c) 2000-2006 Minero Aoki # # This program is free software. # You can distribute/modify this program under the same terms of ruby. # # == module FileUtils # # Namespace for several file utility methods for copying, moving, removing, etc. # # === Module Functions # # cd(dir, options) # cd(dir, options) {|dir| .... } # pwd() # mkdir(dir, options) # mkdir(list, options) # mkdir_p(dir, options) # mkdir_p(list, options) # rmdir(dir, options) # rmdir(list, options) # ln(old, new, options) # ln(list, destdir, options) # ln_s(old, new, options) # ln_s(list, destdir, options) # ln_sf(src, dest, options) # cp(src, dest, options) # cp(list, dir, options) # cp_r(src, dest, options) # cp_r(list, dir, options) # mv(src, dest, options) # mv(list, dir, options) # rm(list, options) # rm_r(list, options) # rm_rf(list, options) # install(src, dest, mode = <src's>, options) # chmod(mode, list, options) # chmod_R(mode, list, options) # chown(user, group, list, options) # chown_R(user, group, list, options) # touch(list, options) # # The <tt>options</tt> parameter is a hash of options, taken from the list # <tt>:force</tt>, <tt>:noop</tt>, <tt>:preserve</tt>, and <tt>:verbose</tt>. # <tt>:noop</tt> means that no changes are made. The other two are obvious. # Each method documents the options that it honours. # # All methods that have the concept of a "source" file or directory can take # either one file or a list of files in that argument. See the method # documentation for examples. # # There are some `low level' methods, which do not accept any option: # # copy_entry(src, dest, preserve = false, dereference = false) # copy_file(src, dest, preserve = false, dereference = true) # copy_stream(srcstream, deststream) # remove_entry(path, force = false) # remove_entry_secure(path, force = false) # remove_file(path, force = false) # compare_file(path_a, path_b) # compare_stream(stream_a, stream_b) # uptodate?(file, cmp_list) # # == module FileUtils::Verbose # # This module has all methods of FileUtils module, but it outputs messages # before acting. This equates to passing the <tt>:verbose</tt> flag to methods # in FileUtils. # # == module FileUtils::NoWrite # # This module has all methods of FileUtils module, but never changes # files/directories. This equates to passing the <tt>:noop</tt> flag to methods # in FileUtils. # # == module FileUtils::DryRun # # This module has all methods of FileUtils module, but never changes # files/directories. This equates to passing the <tt>:noop</tt> and # <tt>:verbose</tt> flags to methods in FileUtils. # module FileUtils def self.private_module_function(name) #:nodoc: module_function name private_class_method name end # This hash table holds command options. OPT_TABLE = {} #:nodoc: internal use only # # Options: (none) # # Returns the name of the current directory. # def pwd Dir.pwd end module_function :pwd alias getwd pwd module_function :getwd # # Options: verbose # # Changes the current directory to the directory +dir+. # # If this method is called with block, resumes to the old # working directory after the block execution finished. # # FileUtils.cd('/', :verbose => true) # chdir and report it # def cd(dir, options = {}, &block) # :yield: dir fu_check_options options, OPT_TABLE['cd'] fu_output_message "cd #{dir}" if options[:verbose] Dir.chdir(dir, &block) fu_output_message 'cd -' if options[:verbose] and block end module_function :cd alias chdir cd module_function :chdir OPT_TABLE['cd'] = OPT_TABLE['chdir'] = [:verbose] # # Options: (none) # # Returns true if +newer+ is newer than all +old_list+. # Non-existent files are older than any file. # # FileUtils.uptodate?('hello.o', %w(hello.c hello.h)) or \ # system 'make hello.o' # def uptodate?(new, old_list, options = nil) raise ArgumentError, 'uptodate? does not accept any option' if options return false unless File.exist?(new) new_time = File.mtime(new) old_list.each do |old| if File.exist?(old) return false unless new_time > File.mtime(old) end end true end module_function :uptodate? # # Options: mode noop verbose # # Creates one or more directories. # # FileUtils.mkdir 'test' # FileUtils.mkdir %w( tmp data ) # FileUtils.mkdir 'notexist', :noop => true # Does not really create. # FileUtils.mkdir 'tmp', :mode => 0700 # def mkdir(list, options = {}) fu_check_options options, OPT_TABLE['mkdir'] list = fu_list(list) fu_output_message "mkdir #{options[:mode] ? ('-m %03o ' % options[:mode]) : ''}#{list.join ' '}" if options[:verbose] return if options[:noop] list.each do |dir| fu_mkdir dir, options[:mode] end end module_function :mkdir OPT_TABLE['mkdir'] = [:mode, :noop, :verbose] # # Options: mode noop verbose # # Creates a directory and all its parent directories. # For example, # # FileUtils.mkdir_p '/usr/local/lib/ruby' # # causes to make following directories, if it does not exist. # * /usr # * /usr/local # * /usr/local/lib # * /usr/local/lib/ruby # # You can pass several directories at a time in a list. # def mkdir_p(list, options = {}) fu_check_options options, OPT_TABLE['mkdir_p'] list = fu_list(list) fu_output_message "mkdir -p #{options[:mode] ? ('-m %03o ' % options[:mode]) : ''}#{list.join ' '}" if options[:verbose] return *list if options[:noop] list.map {|path| path.sub(%r</\z>, '') }.each do |path| # optimize for the most common case begin fu_mkdir path, options[:mode] next rescue SystemCallError next if File.directory?(path) end stack = [] until path == stack.last # dirname("/")=="/", dirname("C:/")=="C:/" stack.push path path = File.dirname(path) end stack.reverse_each do |path| begin fu_mkdir path, options[:mode] rescue SystemCallError => err raise unless File.directory?(path) end end end return *list end module_function :mkdir_p alias mkpath mkdir_p alias makedirs mkdir_p module_function :mkpath module_function :makedirs OPT_TABLE['mkdir_p'] = OPT_TABLE['mkpath'] = OPT_TABLE['makedirs'] = [:mode, :noop, :verbose] def fu_mkdir(path, mode) #:nodoc: path = path.sub(%r</\z>, '') if mode Dir.mkdir path, mode File.chmod mode, path else Dir.mkdir path end end private_module_function :fu_mkdir # # Options: noop, verbose # # Removes one or more directories. # # FileUtils.rmdir 'somedir' # FileUtils.rmdir %w(somedir anydir otherdir) # # Does not really remove directory; outputs message. # FileUtils.rmdir 'somedir', :verbose => true, :noop => true # def rmdir(list, options = {}) fu_check_options options, OPT_TABLE['rmdir'] list = fu_list(list) fu_output_message "rmdir #{list.join ' '}" if options[:verbose] return if options[:noop] list.each do |dir| Dir.rmdir dir.sub(%r</\z>, '') end end module_function :rmdir OPT_TABLE['rmdir'] = [:noop, :verbose] # # Options: force noop verbose # # <b><tt>ln(old, new, options = {})</tt></b> # # Creates a hard link +new+ which points to +old+. # If +new+ already exists and it is a directory, creates a link +new/old+. # If +new+ already exists and it is not a directory, raises Errno::EEXIST. # But if :force option is set, overwrite +new+. # # FileUtils.ln 'gcc', 'cc', :verbose => true # FileUtils.ln '/usr/bin/emacs21', '/usr/bin/emacs' # # <b><tt>ln(list, destdir, options = {})</tt></b> # # Creates several hard links in a directory, with each one pointing to the # item in +list+. If +destdir+ is not a directory, raises Errno::ENOTDIR. # # include FileUtils # cd '/sbin' # FileUtils.ln %w(cp mv mkdir), '/bin' # Now /sbin/cp and /bin/cp are linked. # def ln(src, dest, options = {}) fu_check_options options, OPT_TABLE['ln'] fu_output_message "ln#{options[:force] ? ' -f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose] return if options[:noop] fu_each_src_dest0(src, dest) do |s,d| remove_file d, true if options[:force] File.link s, d end end module_function :ln alias link ln module_function :link OPT_TABLE['ln'] = OPT_TABLE['link'] = [:force, :noop, :verbose] # # Options: force noop verbose # # <b><tt>ln_s(old, new, options = {})</tt></b> # # Creates a symbolic link +new+ which points to +old+. If +new+ already # exists and it is a directory, creates a symbolic link +new/old+. If +new+ # already exists and it is not a directory, raises Errno::EEXIST. But if # :force option is set, overwrite +new+. # # FileUtils.ln_s '/usr/bin/ruby', '/usr/local/bin/ruby' # FileUtils.ln_s 'verylongsourcefilename.c', 'c', :force => true # # <b><tt>ln_s(list, destdir, options = {})</tt></b> # # Creates several symbolic links in a directory, with each one pointing to the # item in +list+. If +destdir+ is not a directory, raises Errno::ENOTDIR. # # If +destdir+ is not a directory, raises Errno::ENOTDIR. # # FileUtils.ln_s Dir.glob('bin/*.rb'), '/home/aamine/bin' # def ln_s(src, dest, options = {}) fu_check_options options, OPT_TABLE['ln_s'] fu_output_message "ln -s#{options[:force] ? 'f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose] return if options[:noop] fu_each_src_dest0(src, dest) do |s,d| remove_file d, true if options[:force] File.symlink s, d end end module_function :ln_s alias symlink ln_s module_function :symlink OPT_TABLE['ln_s'] = OPT_TABLE['symlink'] = [:force, :noop, :verbose] # # Options: noop verbose # # Same as # #ln_s(src, dest, :force) # def ln_sf(src, dest, options = {}) fu_check_options options, OPT_TABLE['ln_sf'] options = options.dup options[:force] = true ln_s src, dest, options end module_function :ln_sf OPT_TABLE['ln_sf'] = [:noop, :verbose] # # Options: preserve noop verbose # # Copies a file content +src+ to +dest+. If +dest+ is a directory, # copies +src+ to +dest/src+. # # If +src+ is a list of files, then +dest+ must be a directory. # # FileUtils.cp 'eval.c', 'eval.c.org' # FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6' # FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6', :verbose => true # FileUtils.cp 'symlink', 'dest' # copy content, "dest" is not a symlink # def cp(src, dest, options = {}) fu_check_options options, OPT_TABLE['cp'] fu_output_message "cp#{options[:preserve] ? ' -p' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose] return if options[:noop] fu_each_src_dest(src, dest) do |s, d| copy_file s, d, options[:preserve] end end module_function :cp alias copy cp module_function :copy OPT_TABLE['cp'] = OPT_TABLE['copy'] = [:preserve, :noop, :verbose] # # Options: preserve noop verbose dereference_root remove_destination # # Copies +src+ to +dest+. If +src+ is a directory, this method copies # all its contents recursively. If +dest+ is a directory, copies # +src+ to +dest/src+. # # +src+ can be a list of files. # # # Installing ruby library "mylib" under the site_ruby # FileUtils.rm_r site_ruby + '/mylib', :force # FileUtils.cp_r 'lib/', site_ruby + '/mylib' # # # Examples of copying several files to target directory. # FileUtils.cp_r %w(mail.rb field.rb debug/), site_ruby + '/tmail' # FileUtils.cp_r Dir.glob('*.rb'), '/home/aamine/lib/ruby', :noop => true, :verbose => true # # # If you want to copy all contents of a directory instead of the # # directory itself, c.f. src/x -> dest/x, src/y -> dest/y, # # use following code. # FileUtils.cp_r 'src/.', 'dest' # cp_r('src', 'dest') makes src/dest, # # but this doesn't. # def cp_r(src, dest, options = {}) fu_check_options options, OPT_TABLE['cp_r'] fu_output_message "cp -r#{options[:preserve] ? 'p' : ''}#{options[:remove_destination] ? ' --remove-destination' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose] return if options[:noop] options[:dereference_root] = true unless options.key?(:dereference_root) fu_each_src_dest(src, dest) do |s, d| copy_entry s, d, options[:preserve], options[:dereference_root], options[:remove_destination] end end module_function :cp_r OPT_TABLE['cp_r'] = [:preserve, :noop, :verbose, :dereference_root, :remove_destination] # # Copies a file system entry +src+ to +dest+. # If +src+ is a directory, this method copies its contents recursively. # This method preserves file types, c.f. symlink, directory... # (FIFO, device files and etc. are not supported yet) # # Both of +src+ and +dest+ must be a path name. # +src+ must exist, +dest+ must not exist. # # If +preserve+ is true, this method preserves owner, group, permissions # and modified time. # # If +dereference_root+ is true, this method dereference tree root. # # If +remove_destination+ is true, this method removes each destination file before copy. # def copy_entry(src, dest, preserve = false, dereference_root = false, remove_destination = false) Entry_.new(src, nil, dereference_root).traverse do |ent| destent = Entry_.new(dest, ent.rel, false) File.unlink destent.path if remove_destination && File.file?(destent.path) ent.copy destent.path ent.copy_metadata destent.path if preserve end end module_function :copy_entry # # Copies file contents of +src+ to +dest+. # Both of +src+ and +dest+ must be a path name. # def copy_file(src, dest, preserve = false, dereference = true) ent = Entry_.new(src, nil, dereference) ent.copy_file dest ent.copy_metadata dest if preserve end module_function :copy_file # # Copies stream +src+ to +dest+. # +src+ must respond to #read(n) and # +dest+ must respond to #write(str). # def copy_stream(src, dest) fu_copy_stream0 src, dest, fu_stream_blksize(src, dest) end module_function :copy_stream # # Options: force noop verbose # # Moves file(s) +src+ to +dest+. If +file+ and +dest+ exist on the different # disk partition, the file is copied instead. # # FileUtils.mv 'badname.rb', 'goodname.rb' # FileUtils.mv 'stuff.rb', '/notexist/lib/ruby', :force => true # no error # # FileUtils.mv %w(junk.txt dust.txt), '/home/aamine/.trash/' # FileUtils.mv Dir.glob('test*.rb'), 'test', :noop => true, :verbose => true # def mv(src, dest, options = {}) fu_check_options options, OPT_TABLE['mv'] fu_output_message "mv#{options[:force] ? ' -f' : ''} #{[src,dest].flatten.join ' '}" if options[:verbose] return if options[:noop] fu_each_src_dest(src, dest) do |s, d| destent = Entry_.new(d, nil, true) begin if destent.exist? if destent.directory? raise Errno::EEXIST, dest else destent.remove_file if rename_cannot_overwrite_file? end end begin File.rename s, d rescue Errno::EXDEV copy_entry s, d, true if options[:secure] remove_entry_secure s, options[:force] else remove_entry s, options[:force] end end rescue SystemCallError raise unless options[:force] end end end module_function :mv alias move mv module_function :move OPT_TABLE['mv'] = OPT_TABLE['move'] = [:force, :noop, :verbose, :secure] def rename_cannot_overwrite_file? #:nodoc: /djgpp|cygwin|mswin|mingw|bccwin|wince|emx|java/ =~ RUBY_PLATFORM end private_module_function :rename_cannot_overwrite_file? # # Options: force noop verbose # # Remove file(s) specified in +list+. This method cannot remove directories. # All StandardErrors are ignored when the :force option is set. # # FileUtils.rm %w( junk.txt dust.txt ) # FileUtils.rm Dir.glob('*.so') # FileUtils.rm 'NotExistFile', :force => true # never raises exception # def rm(list, options = {}) fu_check_options options, OPT_TABLE['rm'] list = fu_list(list) fu_output_message "rm#{options[:force] ? ' -f' : ''} #{list.join ' '}" if options[:verbose] return if options[:noop] list.each do |path| remove_file path, options[:force] end end module_function :rm alias remove rm module_function :remove OPT_TABLE['rm'] = OPT_TABLE['remove'] = [:force, :noop, :verbose] # # Options: noop verbose # # Equivalent to # # #rm(list, :force => true) # def rm_f(list, options = {}) fu_check_options options, OPT_TABLE['rm_f'] options = options.dup options[:force] = true rm list, options end module_function :rm_f alias safe_unlink rm_f module_function :safe_unlink OPT_TABLE['rm_f'] = OPT_TABLE['safe_unlink'] = [:noop, :verbose] # # Options: force noop verbose secure # # remove files +list+[0] +list+[1]... If +list+[n] is a directory, # removes its all contents recursively. This method ignores # StandardError when :force option is set. # # FileUtils.rm_r Dir.glob('/tmp/*') # FileUtils.rm_r '/', :force => true # :-) # # WARNING: This method causes local vulnerability # if one of parent directories or removing directory tree are world # writable (including /tmp, whose permission is 1777), and the current # process has strong privilege such as Unix super user (root), and the # system has symbolic link. For secure removing, read the documentation # of #remove_entry_secure carefully, and set :secure option to true. # Default is :secure=>false. # # NOTE: This method calls #remove_entry_secure if :secure option is set. # See also #remove_entry_secure. # def rm_r(list, options = {}) fu_check_options options, OPT_TABLE['rm_r'] # options[:secure] = true unless options.key?(:secure) list = fu_list(list) fu_output_message "rm -r#{options[:force] ? 'f' : ''} #{list.join ' '}" if options[:verbose] return if options[:noop] list.each do |path| if options[:secure] remove_entry_secure path, options[:force] else remove_entry path, options[:force] end end end module_function :rm_r OPT_TABLE['rm_r'] = [:force, :noop, :verbose, :secure] # # Options: noop verbose secure # # Equivalent to # # #rm_r(list, :force => true) # # WARNING: This method causes local vulnerability. # Read the documentation of #rm_r first. # def rm_rf(list, options = {}) fu_check_options options, OPT_TABLE['rm_rf'] options = options.dup options[:force] = true rm_r list, options end module_function :rm_rf alias rmtree rm_rf module_function :rmtree OPT_TABLE['rm_rf'] = OPT_TABLE['rmtree'] = [:noop, :verbose, :secure] # # This method removes a file system entry +path+. +path+ shall be a # regular file, a directory, or something. If +path+ is a directory, # remove it recursively. This method is required to avoid TOCTTOU # (time-of-check-to-time-of-use) local security vulnerability of #rm_r. # #rm_r causes security hole when: # # * Parent directory is world writable (including /tmp). # * Removing directory tree includes world writable directory. # * The system has symbolic link. # # To avoid this security hole, this method applies special preprocess. # If +path+ is a directory, this method chown(2) and chmod(2) all # removing directories. This requires the current process is the # owner of the removing whole directory tree, or is the super user (root). # # WARNING: You must ensure that *ALL* parent directories are not # world writable. Otherwise this method does not work. # Only exception is temporary directory like /tmp and /var/tmp, # whose permission is 1777. # # WARNING: Only the owner of the removing directory tree, or Unix super # user (root) should invoke this method. Otherwise this method does not # work. # # For details of this security vulnerability, see Perl's case: # # http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2005-0448 # http://www.cve.mitre.org/cgi-bin/cvename.cgi?name=CAN-2004-0452 # # For fileutils.rb, this vulnerability is reported in [ruby-dev:26100]. # def remove_entry_secure(path, force = false) unless fu_have_symlink? remove_entry path, force return end fullpath = File.expand_path(path) st = File.lstat(fullpath) unless st.directory? File.unlink fullpath return end # is a directory. parent_st = File.stat(File.dirname(fullpath)) unless fu_world_writable?(parent_st) remove_entry path, force return end unless parent_st.sticky? raise ArgumentError, "parent directory is world writable, FileUtils#remove_entry_secure does not work; abort: #{path.inspect} (parent directory mode #{'%o' % parent_st.mode})" end # freeze tree root euid = Process.euid File.open(fullpath + '/.') {|f| unless fu_stat_identical_entry?(st, f.stat) # symlink (TOC-to-TOU attack?) File.unlink fullpath return end f.chown euid, -1 f.chmod 0700 } # ---- tree root is frozen ---- root = Entry_.new(path) root.preorder_traverse do |ent| if ent.directory? ent.chown euid, -1 ent.chmod 0700 end end root.postorder_traverse do |ent| begin ent.remove rescue raise unless force end end rescue raise unless force end module_function :remove_entry_secure def fu_world_writable?(st) (st.mode & 0002) != 0 end private_module_function :fu_world_writable? def fu_have_symlink? #:nodoc File.symlink nil, nil rescue NotImplementedError return false rescue return true end private_module_function :fu_have_symlink? def fu_stat_identical_entry?(a, b) #:nodoc: a.dev == b.dev and a.ino == b.ino end private_module_function :fu_stat_identical_entry? # # This method removes a file system entry +path+. # +path+ might be a regular file, a directory, or something. # If +path+ is a directory, remove it recursively. # # See also #remove_entry_secure. # def remove_entry(path, force = false) Entry_.new(path).postorder_traverse do |ent| begin ent.remove rescue raise unless force end end rescue raise unless force end module_function :remove_entry # # Removes a file +path+. # This method ignores StandardError if +force+ is true. # def remove_file(path, force = false) Entry_.new(path).remove_file rescue raise unless force end module_function :remove_file # # Removes a directory +dir+ and its contents recursively. # This method ignores StandardError if +force+ is true. # def remove_dir(path, force = false) remove_entry path, force # FIXME?? check if it is a directory end module_function :remove_dir # # Returns true if the contents of a file A and a file B are identical. # # FileUtils.compare_file('somefile', 'somefile') #=> true # FileUtils.compare_file('/bin/cp', '/bin/mv') #=> maybe false # def compare_file(a, b) return false unless File.size(a) == File.size(b) File.open(a, 'rb') {|fa| File.open(b, 'rb') {|fb| return compare_stream(fa, fb) } } end module_function :compare_file alias identical? compare_file alias cmp compare_file module_function :identical? module_function :cmp # # Returns true if the contents of a stream +a+ and +b+ are identical. # def compare_stream(a, b) bsize = fu_stream_blksize(a, b) sa = sb = nil while sa == sb sa = a.read(bsize) sb = b.read(bsize) unless sa and sb if sa.nil? and sb.nil? return true end end end false end module_function :compare_stream # # Options: mode preserve noop verbose # # If +src+ is not same as +dest+, copies it and changes the permission # mode to +mode+. If +dest+ is a directory, destination is +dest+/+src+. # This method removes destination before copy. # # FileUtils.install 'ruby', '/usr/local/bin/ruby', :mode => 0755, :verbose => true # FileUtils.install 'lib.rb', '/usr/local/lib/ruby/site_ruby', :verbose => true # def install(src, dest, options = {}) fu_check_options options, OPT_TABLE['install'] fu_output_message "install -c#{options[:preserve] && ' -p'}#{options[:mode] ? (' -m 0%o' % options[:mode]) : ''} #{[src,dest].flatten.join ' '}" if options[:verbose] return if options[:noop] fu_each_src_dest(src, dest) do |s, d| unless File.exist?(d) and compare_file(s, d) remove_file d, true st = File.stat(s) if options[:preserve] copy_file s, d File.utime st.atime, st.mtime, d if options[:preserve] File.chmod options[:mode], d if options[:mode] end end end module_function :install OPT_TABLE['install'] = [:mode, :preserve, :noop, :verbose] # # Options: noop verbose # # Changes permission bits on the named files (in +list+) to the bit pattern # represented by +mode+. # # FileUtils.chmod 0755, 'somecommand' # FileUtils.chmod 0644, %w(my.rb your.rb his.rb her.rb) # FileUtils.chmod 0755, '/usr/bin/ruby', :verbose => true # def chmod(mode, list, options = {}) fu_check_options options, OPT_TABLE['chmod'] list = fu_list(list) fu_output_message sprintf('chmod %o %s', mode, list.join(' ')) if options[:verbose] return if options[:noop] list.each do |path| Entry_.new(path).chmod mode end end module_function :chmod OPT_TABLE['chmod'] = [:noop, :verbose] # # Options: noop verbose force # # Changes permission bits on the named files (in +list+) # to the bit pattern represented by +mode+. # # FileUtils.chmod_R 0700, "/tmp/app.#{$$}" # def chmod_R(mode, list, options = {}) fu_check_options options, OPT_TABLE['chmod_R'] list = fu_list(list) fu_output_message sprintf('chmod -R%s %o %s', (options[:force] ? 'f' : ''), mode, list.join(' ')) if options[:verbose] return if options[:noop] list.each do |root| Entry_.new(root).traverse do |ent| begin ent.chmod mode rescue raise unless options[:force] end end end end module_function :chmod_R OPT_TABLE['chmod_R'] = [:noop, :verbose, :force] # # Options: noop verbose # # Changes owner and group on the named files (in +list+) # to the user +user+ and the group +group+. +user+ and +group+ # may be an ID (Integer/String) or a name (String). # If +user+ or +group+ is nil, this method does not change # the attribute. # # FileUtils.chown 'root', 'staff', '/usr/local/bin/ruby' # FileUtils.chown nil, 'bin', Dir.glob('/usr/bin/*'), :verbose => true # def chown(user, group, list, options = {}) fu_check_options options, OPT_TABLE['chown'] list = fu_list(list) fu_output_message sprintf('chown %s%s', [user,group].compact.join(':') + ' ', list.join(' ')) if options[:verbose] return if options[:noop] uid = fu_get_uid(user) gid = fu_get_gid(group) list.each do |path| Entry_.new(path).chown uid, gid end end module_function :chown OPT_TABLE['chown'] = [:noop, :verbose] # # Options: noop verbose force # # Changes owner and group on the named files (in +list+) # to the user +user+ and the group +group+ recursively. # +user+ and +group+ may be an ID (Integer/String) or # a name (String). If +user+ or +group+ is nil, this # method does not change the attribute. # # FileUtils.chown_R 'www', 'www', '/var/www/htdocs' # FileUtils.chown_R 'cvs', 'cvs', '/var/cvs', :verbose => true # def chown_R(user, group, list, options = {}) fu_check_options options, OPT_TABLE['chown_R'] list = fu_list(list) fu_output_message sprintf('chown -R%s %s%s', (options[:force] ? 'f' : ''), [user,group].compact.join(':') + ' ', list.join(' ')) if options[:verbose] return if options[:noop] uid = fu_get_uid(user) gid = fu_get_gid(group) return unless uid or gid list.each do |root| Entry_.new(root).traverse do |ent| begin ent.chown uid, gid rescue raise unless options[:force] end end end end module_function :chown_R OPT_TABLE['chown_R'] = [:noop, :verbose, :force] begin require 'etc' def fu_get_uid(user) #:nodoc: return nil unless user user = user.to_s if /\A\d+\z/ =~ user then user.to_i else Etc.getpwnam(user).uid end end private_module_function :fu_get_uid def fu_get_gid(group) #:nodoc: return nil unless group group = group.to_s if /\A\d+\z/ =~ group then group.to_i else Etc.getgrnam(group).gid end end private_module_function :fu_get_gid rescue LoadError # need Win32 support??? def fu_get_uid(user) #:nodoc: user # FIXME end private_module_function :fu_get_uid def fu_get_gid(group) #:nodoc: group # FIXME end private_module_function :fu_get_gid end # # Options: noop verbose # # Updates modification time (mtime) and access time (atime) of file(s) in # +list+. Files are created if they don't exist. # # FileUtils.touch 'timestamp' # FileUtils.touch Dir.glob('*.c'); system 'make' # def touch(list, options = {}) fu_check_options options, OPT_TABLE['touch'] list = fu_list(list) created = nocreate = options[:nocreate] t = options[:mtime] if options[:verbose] fu_output_message "touch #{nocreate ? ' -c' : ''}#{t ? t.strftime(' -t %Y%m%d%H%M.%S') : ''}#{list.join ' '}" end return if options[:noop] list.each do |path| created = nocreate begin File.utime(t, t, path) rescue Errno::ENOENT raise if created File.open(path, 'a') { ; } created = true retry if t end end end module_function :touch OPT_TABLE['touch'] = [:noop, :verbose, :mtime, :nocreate] private module StreamUtils_ private def fu_windows? /mswin|mingw|bccwin|wince|emx|java/ =~ RUBY_PLATFORM end def fu_copy_stream0(src, dest, blksize) #:nodoc: # FIXME: readpartial? while s = src.read(blksize) dest.write s end end def fu_stream_blksize(*streams) streams.each do |s| next unless s.respond_to?(:stat) size = fu_blksize(s.stat) return size if size end fu_default_blksize() end def fu_blksize(st) s = st.blksize return nil unless s return nil if s == 0 s end def fu_default_blksize 1024 end end include StreamUtils_ extend StreamUtils_ class Entry_ #:nodoc: internal use only include StreamUtils_ def initialize(a, b = nil, deref = false) @prefix = @rel = @path = nil if b @prefix = a @rel = b else @path = a end @deref = deref @stat = nil @lstat = nil end def inspect "\#<#{self.class} #{path()}>" end def path if @path @path.to_str else join(@prefix, @rel) end end def prefix @prefix || @path end def rel @rel end def dereference? @deref end def exist? lstat! ? true : false end def file? s = lstat! s and s.file? end def directory? s = lstat! s and s.directory? end def symlink? s = lstat! s and s.symlink? end def chardev? s = lstat! s and s.chardev? end def blockdev? s = lstat! s and s.blockdev? end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
true
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/observer.rb
tools/jruby-1.5.1/lib/ruby/1.8/observer.rb
# # observer.rb implements the _Observer_ object-oriented design pattern. The # following documentation is copied, with modifications, from "Programming # Ruby", by Hunt and Thomas; http://www.rubycentral.com/book/lib_patterns.html. # # == About # # The Observer pattern, also known as Publish/Subscribe, provides a simple # mechanism for one object to inform a set of interested third-party objects # when its state changes. # # == Mechanism # # In the Ruby implementation, the notifying class mixes in the +Observable+ # module, which provides the methods for managing the associated observer # objects. # # The observers must implement the +update+ method to receive notifications. # # The observable object must: # * assert that it has +changed+ # * call +notify_observers+ # # == Example # # The following example demonstrates this nicely. A +Ticker+, when run, # continually receives the stock +Price+ for its +@symbol+. A +Warner+ is a # general observer of the price, and two warners are demonstrated, a +WarnLow+ # and a +WarnHigh+, which print a warning if the price is below or above their # set limits, respectively. # # The +update+ callback allows the warners to run without being explicitly # called. The system is set up with the +Ticker+ and several observers, and the # observers do their duty without the top-level code having to interfere. # # Note that the contract between publisher and subscriber (observable and # observer) is not declared or enforced. The +Ticker+ publishes a time and a # price, and the warners receive that. But if you don't ensure that your # contracts are correct, nothing else can warn you. # # require "observer" # # class Ticker ### Periodically fetch a stock price. # include Observable # # def initialize(symbol) # @symbol = symbol # end # # def run # lastPrice = nil # loop do # price = Price.fetch(@symbol) # print "Current price: #{price}\n" # if price != lastPrice # changed # notify observers # lastPrice = price # notify_observers(Time.now, price) # end # sleep 1 # end # end # end # # class Price ### A mock class to fetch a stock price (60 - 140). # def Price.fetch(symbol) # 60 + rand(80) # end # end # # class Warner ### An abstract observer of Ticker objects. # def initialize(ticker, limit) # @limit = limit # ticker.add_observer(self) # end # end # # class WarnLow < Warner # def update(time, price) # callback for observer # if price < @limit # print "--- #{time.to_s}: Price below #@limit: #{price}\n" # end # end # end # # class WarnHigh < Warner # def update(time, price) # callback for observer # if price > @limit # print "+++ #{time.to_s}: Price above #@limit: #{price}\n" # end # end # end # # ticker = Ticker.new("MSFT") # WarnLow.new(ticker, 80) # WarnHigh.new(ticker, 120) # ticker.run # # Produces: # # Current price: 83 # Current price: 75 # --- Sun Jun 09 00:10:25 CDT 2002: Price below 80: 75 # Current price: 90 # Current price: 134 # +++ Sun Jun 09 00:10:25 CDT 2002: Price above 120: 134 # Current price: 134 # Current price: 112 # Current price: 79 # --- Sun Jun 09 00:10:25 CDT 2002: Price below 80: 79 # # Implements the Observable design pattern as a mixin so that other objects can # be notified of changes in state. See observer.rb for details and an example. # module Observable # # Add +observer+ as an observer on this object. +observer+ will now receive # notifications. # def add_observer(observer) @observer_peers = [] unless defined? @observer_peers unless observer.respond_to? :update raise NoMethodError, "observer needs to respond to `update'" end @observer_peers.push observer end # # Delete +observer+ as an observer on this object. It will no longer receive # notifications. # def delete_observer(observer) @observer_peers.delete observer if defined? @observer_peers end # # Delete all observers associated with this object. # def delete_observers @observer_peers.clear if defined? @observer_peers end # # Return the number of observers associated with this object. # def count_observers if defined? @observer_peers @observer_peers.size else 0 end end # # Set the changed state of this object. Notifications will be sent only if # the changed +state+ is +true+. # def changed(state=true) @observer_state = state end # # Query the changed state of this object. # def changed? if defined? @observer_state and @observer_state true else false end end # # If this object's changed state is +true+, invoke the update method in each # currently associated observer in turn, passing it the given arguments. The # changed state is then set to +false+. # def notify_observers(*arg) if defined? @observer_state and @observer_state if defined? @observer_peers for i in @observer_peers.dup i.update(*arg) end end @observer_state = false end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/csv.rb
tools/jruby-1.5.1/lib/ruby/1.8/csv.rb
# CSV -- module for generating/parsing CSV data. # Copyright (C) 2000-2004 NAKAMURA, Hiroshi <nakahiro@sarion.co.jp>. # $Id: csv.rb 11708 2007-02-12 23:01:19Z shyouhei $ # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. class CSV class IllegalFormatError < RuntimeError; end # deprecated class Cell < String def initialize(data = "", is_null = false) super(is_null ? "" : data) end def data to_s end end # deprecated class Row < Array end # Open a CSV formatted file for reading or writing. # # For reading. # # EXAMPLE 1 # CSV.open('csvfile.csv', 'r') do |row| # p row # end # # EXAMPLE 2 # reader = CSV.open('csvfile.csv', 'r') # row1 = reader.shift # row2 = reader.shift # if row2.empty? # p 'row2 not find.' # end # reader.close # # ARGS # filename: filename to parse. # col_sep: Column separator. ?, by default. If you want to separate # fields with semicolon, give ?; here. # row_sep: Row separator. nil by default. nil means "\r\n or \n". If you # want to separate records with \r, give ?\r here. # # RETURNS # reader instance. To get parse result, see CSV::Reader#each. # # # For writing. # # EXAMPLE 1 # CSV.open('csvfile.csv', 'w') do |writer| # writer << ['r1c1', 'r1c2'] # writer << ['r2c1', 'r2c2'] # writer << [nil, nil] # end # # EXAMPLE 2 # writer = CSV.open('csvfile.csv', 'w') # writer << ['r1c1', 'r1c2'] << ['r2c1', 'r2c2'] << [nil, nil] # writer.close # # ARGS # filename: filename to generate. # col_sep: Column separator. ?, by default. If you want to separate # fields with semicolon, give ?; here. # row_sep: Row separator. nil by default. nil means "\r\n or \n". If you # want to separate records with \r, give ?\r here. # # RETURNS # writer instance. See CSV::Writer#<< and CSV::Writer#add_row to know how # to generate CSV string. # def CSV.open(path, mode, fs = nil, rs = nil, &block) if mode == 'r' or mode == 'rb' open_reader(path, mode, fs, rs, &block) elsif mode == 'w' or mode == 'wb' open_writer(path, mode, fs, rs, &block) else raise ArgumentError.new("'mode' must be 'r', 'rb', 'w', or 'wb'") end end def CSV.foreach(path, rs = nil, &block) open_reader(path, 'r', ',', rs, &block) end def CSV.read(path, length = nil, offset = nil) CSV.parse(IO.read(path, length, offset)) end def CSV.readlines(path, rs = nil) reader = open_reader(path, 'r', ',', rs) begin reader.collect { |row| row } ensure reader.close end end def CSV.generate(path, fs = nil, rs = nil, &block) open_writer(path, 'w', fs, rs, &block) end # Parse lines from given string or stream. Return rows as an Array of Arrays. def CSV.parse(str_or_readable, fs = nil, rs = nil, &block) if File.exist?(str_or_readable) STDERR.puts("CSV.parse(filename) is deprecated." + " Use CSV.open(filename, 'r') instead.") return open_reader(str_or_readable, 'r', fs, rs, &block) end if block CSV::Reader.parse(str_or_readable, fs, rs) do |row| yield(row) end nil else CSV::Reader.create(str_or_readable, fs, rs).collect { |row| row } end end # Parse a line from given string. Bear in mind it parses ONE LINE. Rest of # the string is ignored for example "a,b\r\nc,d" => ['a', 'b'] and the # second line 'c,d' is ignored. # # If you don't know whether a target string to parse is exactly 1 line or # not, use CSV.parse_row instead of this method. def CSV.parse_line(src, fs = nil, rs = nil) fs ||= ',' if fs.is_a?(Fixnum) fs = fs.chr end if !rs.nil? and rs.is_a?(Fixnum) rs = rs.chr end idx = 0 res_type = :DT_COLSEP row = [] begin while res_type == :DT_COLSEP res_type, idx, cell = parse_body(src, idx, fs, rs) row << cell end rescue IllegalFormatError return [] end row end # Create a line from cells. each cell is stringified by to_s. def CSV.generate_line(row, fs = nil, rs = nil) if row.size == 0 return '' end fs ||= ',' if fs.is_a?(Fixnum) fs = fs.chr end if !rs.nil? and rs.is_a?(Fixnum) rs = rs.chr end res_type = :DT_COLSEP result_str = '' idx = 0 while true generate_body(row[idx], result_str, fs, rs) idx += 1 if (idx == row.size) break end generate_separator(:DT_COLSEP, result_str, fs, rs) end result_str end # Parse a line from string. Consider using CSV.parse_line instead. # To parse lines in CSV string, see EXAMPLE below. # # EXAMPLE # src = "a,b\r\nc,d\r\ne,f" # idx = 0 # begin # parsed = [] # parsed_cells, idx = CSV.parse_row(src, idx, parsed) # puts "Parsed #{ parsed_cells } cells." # p parsed # end while parsed_cells > 0 # # ARGS # src: a CSV data to be parsed. Must respond '[](idx)'. # src[](idx) must return a char. (Not a string such as 'a', but 97). # src[](idx_out_of_bounds) must return nil. A String satisfies this # requirement. # idx: index of parsing location of 'src'. 0 origin. # out_dev: buffer for parsed cells. Must respond '<<(aString)'. # col_sep: Column separator. ?, by default. If you want to separate # fields with semicolon, give ?; here. # row_sep: Row separator. nil by default. nil means "\r\n or \n". If you # want to separate records with \r, give ?\r here. # # RETURNS # parsed_cells: num of parsed cells. # idx: index of next parsing location of 'src'. # def CSV.parse_row(src, idx, out_dev, fs = nil, rs = nil) fs ||= ',' if fs.is_a?(Fixnum) fs = fs.chr end if !rs.nil? and rs.is_a?(Fixnum) rs = rs.chr end idx_backup = idx parsed_cells = 0 res_type = :DT_COLSEP begin while res_type != :DT_ROWSEP res_type, idx, cell = parse_body(src, idx, fs, rs) if res_type == :DT_EOS if idx == idx_backup #((parsed_cells == 0) and cell.nil?) return 0, 0 end res_type = :DT_ROWSEP end parsed_cells += 1 out_dev << cell end rescue IllegalFormatError return 0, 0 end return parsed_cells, idx end # Convert a line from cells data to string. Consider using CSV.generate_line # instead. To generate multi-row CSV string, see EXAMPLE below. # # EXAMPLE # row1 = ['a', 'b'] # row2 = ['c', 'd'] # row3 = ['e', 'f'] # src = [row1, row2, row3] # buf = '' # src.each do |row| # parsed_cells = CSV.generate_row(row, 2, buf) # puts "Created #{ parsed_cells } cells." # end # p buf # # ARGS # src: an Array of String to be converted to CSV string. Must respond to # 'size' and '[](idx)'. src[idx] must return String. # cells: num of cells in a line. # out_dev: buffer for generated CSV string. Must respond to '<<(string)'. # col_sep: Column separator. ?, by default. If you want to separate # fields with semicolon, give ?; here. # row_sep: Row separator. nil by default. nil means "\r\n or \n". If you # want to separate records with \r, give ?\r here. # # RETURNS # parsed_cells: num of converted cells. # def CSV.generate_row(src, cells, out_dev, fs = nil, rs = nil) fs ||= ',' if fs.is_a?(Fixnum) fs = fs.chr end if !rs.nil? and rs.is_a?(Fixnum) rs = rs.chr end src_size = src.size if (src_size == 0) if cells == 0 generate_separator(:DT_ROWSEP, out_dev, fs, rs) end return 0 end res_type = :DT_COLSEP parsed_cells = 0 generate_body(src[parsed_cells], out_dev, fs, rs) parsed_cells += 1 while ((parsed_cells < cells) and (parsed_cells != src_size)) generate_separator(:DT_COLSEP, out_dev, fs, rs) generate_body(src[parsed_cells], out_dev, fs, rs) parsed_cells += 1 end if (parsed_cells == cells) generate_separator(:DT_ROWSEP, out_dev, fs, rs) else generate_separator(:DT_COLSEP, out_dev, fs, rs) end parsed_cells end # Private class methods. class << self private def open_reader(path, mode, fs, rs, &block) file = File.open(path, mode) if block begin CSV::Reader.parse(file, fs, rs) do |row| yield(row) end ensure file.close end nil else reader = CSV::Reader.create(file, fs, rs) reader.close_on_terminate reader end end def open_writer(path, mode, fs, rs, &block) file = File.open(path, mode) if block begin CSV::Writer.generate(file, fs, rs) do |writer| yield(writer) end ensure file.close end nil else writer = CSV::Writer.create(file, fs, rs) writer.close_on_terminate writer end end def parse_body(src, idx, fs, rs) fs_str = fs fs_size = fs_str.size rs_str = rs || "\n" rs_size = rs_str.size fs_idx = rs_idx = 0 cell = Cell.new state = :ST_START quoted = cr = false c = nil last_idx = idx while c = src[idx] unless quoted fschar = (c == fs_str[fs_idx]) rschar = (c == rs_str[rs_idx]) # simple 1 char backtrack if !fschar and c == fs_str[0] fs_idx = 0 fschar = true if state == :ST_START state = :ST_DATA elsif state == :ST_QUOTE raise IllegalFormatError end end if !rschar and c == rs_str[0] rs_idx = 0 rschar = true if state == :ST_START state = :ST_DATA elsif state == :ST_QUOTE raise IllegalFormatError end end end if c == ?" fs_idx = rs_idx = 0 if cr raise IllegalFormatError end cell << src[last_idx, (idx - last_idx)] last_idx = idx if state == :ST_DATA if quoted last_idx += 1 quoted = false state = :ST_QUOTE else raise IllegalFormatError end elsif state == :ST_QUOTE cell << c.chr last_idx += 1 quoted = true state = :ST_DATA else # :ST_START quoted = true last_idx += 1 state = :ST_DATA end elsif fschar or rschar if fschar fs_idx += 1 end if rschar rs_idx += 1 end sep = nil if fs_idx == fs_size if state == :ST_START and rs_idx > 0 and fs_idx < rs_idx state = :ST_DATA end cell << src[last_idx, (idx - last_idx - (fs_size - 1))] last_idx = idx fs_idx = rs_idx = 0 if cr raise IllegalFormatError end sep = :DT_COLSEP elsif rs_idx == rs_size if state == :ST_START and fs_idx > 0 and rs_idx < fs_idx state = :ST_DATA end if !(rs.nil? and cr) cell << src[last_idx, (idx - last_idx - (rs_size - 1))] last_idx = idx end fs_idx = rs_idx = 0 sep = :DT_ROWSEP end if sep if state == :ST_DATA return sep, idx + 1, cell; elsif state == :ST_QUOTE return sep, idx + 1, cell; else # :ST_START return sep, idx + 1, nil end end elsif rs.nil? and c == ?\r # special \r treatment for backward compatibility fs_idx = rs_idx = 0 if cr raise IllegalFormatError end cell << src[last_idx, (idx - last_idx)] last_idx = idx if quoted state = :ST_DATA else cr = true end else fs_idx = rs_idx = 0 if state == :ST_DATA or state == :ST_START if cr raise IllegalFormatError end state = :ST_DATA else # :ST_QUOTE raise IllegalFormatError end end idx += 1 end if state == :ST_START if fs_idx > 0 or rs_idx > 0 state = :ST_DATA else return :DT_EOS, idx, nil end elsif quoted raise IllegalFormatError elsif cr raise IllegalFormatError end cell << src[last_idx, (idx - last_idx)] last_idx = idx return :DT_EOS, idx, cell end def generate_body(cell, out_dev, fs, rs) if cell.nil? # empty else cell = cell.to_s row_data = cell.dup if (row_data.gsub!('"', '""') or row_data.index(fs) or (rs and row_data.index(rs)) or (/[\r\n]/ =~ row_data) or (cell.empty?)) out_dev << '"' << row_data << '"' else out_dev << row_data end end end def generate_separator(type, out_dev, fs, rs) case type when :DT_COLSEP out_dev << fs when :DT_ROWSEP out_dev << (rs || "\n") end end end # CSV formatted string/stream reader. # # EXAMPLE # read CSV lines untill the first column is 'stop'. # # CSV::Reader.parse(File.open('bigdata', 'rb')) do |row| # p row # break if !row[0].is_null && row[0].data == 'stop' # end # class Reader include Enumerable # Parse CSV data and get lines. Given block is called for each parsed row. # Block value is always nil. Rows are not cached for performance reason. def Reader.parse(str_or_readable, fs = ',', rs = nil, &block) reader = Reader.create(str_or_readable, fs, rs) if block reader.each do |row| yield(row) end reader.close nil else reader end end # Returns reader instance. def Reader.create(str_or_readable, fs = ',', rs = nil) case str_or_readable when IO IOReader.new(str_or_readable, fs, rs) when String StringReader.new(str_or_readable, fs, rs) else IOReader.new(str_or_readable, fs, rs) end end def each while true row = [] parsed_cells = get_row(row) if parsed_cells == 0 break end yield(row) end nil end def shift row = [] parsed_cells = get_row(row) row end def close terminate end private def initialize(dev) raise RuntimeError.new('Do not instanciate this class directly.') end def get_row(row) raise NotImplementedError.new('Method get_row must be defined in a derived class.') end def terminate # Define if needed. end end class StringReader < Reader def initialize(string, fs = ',', rs = nil) @fs = fs @rs = rs @dev = string @idx = 0 if @dev[0, 3] == "\xef\xbb\xbf" @idx += 3 end end private def get_row(row) parsed_cells, next_idx = CSV.parse_row(@dev, @idx, row, @fs, @rs) if parsed_cells == 0 and next_idx == 0 and @idx != @dev.size raise IllegalFormatError.new end @idx = next_idx parsed_cells end end class IOReader < Reader def initialize(io, fs = ',', rs = nil) @io = io @fs = fs @rs = rs @dev = CSV::IOBuf.new(@io) @idx = 0 if @dev[0] == 0xef and @dev[1] == 0xbb and @dev[2] == 0xbf @idx += 3 end @close_on_terminate = false end # Tell this reader to close the IO when terminated (Triggered by invoking # CSV::IOReader#close). def close_on_terminate @close_on_terminate = true end private def get_row(row) parsed_cells, next_idx = CSV.parse_row(@dev, @idx, row, @fs, @rs) if parsed_cells == 0 and next_idx == 0 and !@dev.is_eos? raise IllegalFormatError.new end dropped = @dev.drop(next_idx) @idx = next_idx - dropped parsed_cells end def terminate if @close_on_terminate @io.close end if @dev @dev.close end end end # CSV formatted string/stream writer. # # EXAMPLE # Write rows to 'csvout' file. # # outfile = File.open('csvout', 'wb') # CSV::Writer.generate(outfile) do |csv| # csv << ['c1', nil, '', '"', "\r\n", 'c2'] # ... # end # # outfile.close # class Writer # Given block is called with the writer instance. str_or_writable must # handle '<<(string)'. def Writer.generate(str_or_writable, fs = ',', rs = nil, &block) writer = Writer.create(str_or_writable, fs, rs) if block yield(writer) writer.close nil else writer end end # str_or_writable must handle '<<(string)'. def Writer.create(str_or_writable, fs = ',', rs = nil) BasicWriter.new(str_or_writable, fs, rs) end # dump CSV stream to the device. argument must be an Array of String. def <<(row) CSV.generate_row(row, row.size, @dev, @fs, @rs) self end alias add_row << def close terminate end private def initialize(dev) raise RuntimeError.new('Do not instanciate this class directly.') end def terminate # Define if needed. end end class BasicWriter < Writer def initialize(str_or_writable, fs = ',', rs = nil) @fs = fs @rs = rs @dev = str_or_writable @close_on_terminate = false end # Tell this writer to close the IO when terminated (Triggered by invoking # CSV::BasicWriter#close). def close_on_terminate @close_on_terminate = true end private def terminate if @close_on_terminate @dev.close end end end private # Buffered stream. # # EXAMPLE 1 -- an IO. # class MyBuf < StreamBuf # # Do initialize myself before a super class. Super class might call my # # method 'read'. (Could be awful for C++ user. :-) # def initialize(s) # @s = s # super() # end # # # define my own 'read' method. # # CAUTION: Returning nil means EnfOfStream. # def read(size) # @s.read(size) # end # # # release buffers. in Ruby which has GC, you do not have to call this... # def terminate # @s = nil # super() # end # end # # buf = MyBuf.new(STDIN) # my_str = '' # p buf[0, 0] # => '' (null string) # p buf[0] # => 97 (char code of 'a') # p buf[0, 1] # => 'a' # my_str = buf[0, 5] # p my_str # => 'abcde' (5 chars) # p buf[0, 6] # => "abcde\n" (6 chars) # p buf[0, 7] # => "abcde\n" (6 chars) # p buf.drop(3) # => 3 (dropped chars) # p buf.get(0, 2) # => 'de' (2 chars) # p buf.is_eos? # => false (is not EOS here) # p buf.drop(5) # => 3 (dropped chars) # p buf.is_eos? # => true (is EOS here) # p buf[0] # => nil (is EOS here) # # EXAMPLE 2 -- String. # This is a conceptual example. No pros with this. # # class StrBuf < StreamBuf # def initialize(s) # @str = s # @idx = 0 # super() # end # # def read(size) # str = @str[@idx, size] # @idx += str.size # str # end # end # class StreamBuf # get a char or a partial string from the stream. # idx: index of a string to specify a start point of a string to get. # unlike String instance, idx < 0 returns nil. # n: size of a string to get. # returns char at idx if n == nil. # returns a partial string, from idx to (idx + n) if n != nil. at EOF, # the string size could not equal to arg n. def [](idx, n = nil) if idx < 0 return nil end if (idx_is_eos?(idx)) if n and (@offset + idx == buf_size(@cur_buf)) # Like a String, 'abc'[4, 1] returns nil and # 'abc'[3, 1] returns '' not nil. return '' else return nil end end my_buf = @cur_buf my_offset = @offset next_idx = idx while (my_offset + next_idx >= buf_size(my_buf)) if (my_buf == @buf_tail_idx) unless add_buf break end end next_idx = my_offset + next_idx - buf_size(my_buf) my_buf += 1 my_offset = 0 end loc = my_offset + next_idx if !n return @buf_list[my_buf][loc] # Fixnum of char code. elsif (loc + n - 1 < buf_size(my_buf)) return @buf_list[my_buf][loc, n] # String. else # should do loop insted of (tail) recursive call... res = @buf_list[my_buf][loc, BufSize] size_added = buf_size(my_buf) - loc if size_added > 0 idx += size_added n -= size_added ret = self[idx, n] if ret res << ret end end return res end end alias get [] # drop a string from the stream. # returns dropped size. at EOF, dropped size might not equals to arg n. # Once you drop the head of the stream, access to the dropped part via [] # or get returns nil. def drop(n) if is_eos? return 0 end size_dropped = 0 while (n > 0) if !@is_eos or (@cur_buf != @buf_tail_idx) if (@offset + n < buf_size(@cur_buf)) size_dropped += n @offset += n n = 0 else size = buf_size(@cur_buf) - @offset size_dropped += size n -= size @offset = 0 unless rel_buf unless add_buf break end @cur_buf = @buf_tail_idx end end end end size_dropped end def is_eos? return idx_is_eos?(0) end # WARN: Do not instantiate this class directly. Define your own class # which derives this class and define 'read' instance method. def initialize @buf_list = [] @cur_buf = @buf_tail_idx = -1 @offset = 0 @is_eos = false add_buf @cur_buf = @buf_tail_idx end protected def terminate while (rel_buf); end end # protected method 'read' must be defined in derived classes. # CAUTION: Returning a string which size is not equal to 'size' means # EnfOfStream. When it is not at EOS, you must block the callee, try to # read and return the sized string. def read(size) # raise EOFError raise NotImplementedError.new('Method read must be defined in a derived class.') end private def buf_size(idx) @buf_list[idx].size end def add_buf if @is_eos return false end begin str_read = read(BufSize) rescue EOFError str_read = nil rescue terminate raise end if str_read.nil? @is_eos = true @buf_list.push('') @buf_tail_idx += 1 false else @buf_list.push(str_read) @buf_tail_idx += 1 true end end def rel_buf if (@cur_buf < 0) return false end @buf_list[@cur_buf] = nil if (@cur_buf == @buf_tail_idx) @cur_buf = -1 return false else @cur_buf += 1 return true end end def idx_is_eos?(idx) (@is_eos and ((@cur_buf < 0) or (@cur_buf == @buf_tail_idx))) end BufSize = 1024 * 8 end # Buffered IO. # # EXAMPLE # # File 'bigdata' could be a giga-byte size one! # buf = CSV::IOBuf.new(File.open('bigdata', 'rb')) # CSV::Reader.new(buf).each do |row| # p row # break if row[0].data == 'admin' # end # class IOBuf < StreamBuf def initialize(s) @s = s super() end def close terminate end private def read(size) @s.read(size) end def terminate super() end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/kconv.rb
tools/jruby-1.5.1/lib/ruby/1.8/kconv.rb
# # kconv.rb - Kanji Converter. # # $Id: kconv.rb 11708 2007-02-12 23:01:19Z shyouhei $ # # ---- # # kconv.rb implements the Kconv class for Kanji Converter. Additionally, # some methods in String classes are added to allow easy conversion. # require 'nkf' # # Kanji Converter for Ruby. # module Kconv # # Public Constants # #Constant of Encoding # Auto-Detect AUTO = NKF::AUTO # ISO-2022-JP JIS = NKF::JIS # EUC-JP EUC = NKF::EUC # Shift_JIS SJIS = NKF::SJIS # BINARY BINARY = NKF::BINARY # NOCONV NOCONV = NKF::NOCONV # ASCII ASCII = NKF::ASCII # UTF-8 UTF8 = NKF::UTF8 # UTF-16 UTF16 = NKF::UTF16 # UTF-32 UTF32 = NKF::UTF32 # UNKNOWN UNKNOWN = NKF::UNKNOWN # # Private Constants # # Revision of kconv.rb REVISION = %q$Revision: 11708 $ #Regexp of Encoding # Regexp of Shift_JIS string (private constant) RegexpShiftjis = /\A(?: [\x00-\x7f\xa1-\xdf] | [\x81-\x9f\xe0-\xfc][\x40-\x7e\x80-\xfc] )*\z/nx # Regexp of EUC-JP string (private constant) RegexpEucjp = /\A(?: [\x00-\x7f] | \x8e [\xa1-\xdf] | \x8f [\xa1-\xfe] [\xa1-\xfe] | [\xa1-\xfe] [\xa1-\xfe] )*\z/nx # Regexp of UTF-8 string (private constant) RegexpUtf8 = /\A(?: [\x00-\x7f] | [\xc2-\xdf] [\x80-\xbf] | \xe0 [\xa0-\xbf] [\x80-\xbf] | [\xe1-\xef] [\x80-\xbf] [\x80-\xbf] | \xf0 [\x90-\xbf] [\x80-\xbf] [\x80-\xbf] | [\xf1-\xf3] [\x80-\xbf] [\x80-\xbf] [\x80-\xbf] | \xf4 [\x80-\x8f] [\x80-\xbf] [\x80-\xbf] )*\z/nx # # Public Methods # # call-seq: # Kconv.kconv(str, out_code, in_code = Kconv::AUTO) # # Convert <code>str</code> to out_code. # <code>out_code</code> and <code>in_code</code> are given as constants of Kconv. # # *Note* # This method decode MIME encoded string and # convert halfwidth katakana to fullwidth katakana. # If you don't want to decode them, use NKF.nkf. def kconv(str, out_code, in_code = AUTO) opt = '-' case in_code when ::NKF::JIS opt << 'J' when ::NKF::EUC opt << 'E' when ::NKF::SJIS opt << 'S' when ::NKF::UTF8 opt << 'W' when ::NKF::UTF16 opt << 'W16' end case out_code when ::NKF::JIS opt << 'j' when ::NKF::EUC opt << 'e' when ::NKF::SJIS opt << 's' when ::NKF::UTF8 opt << 'w' when ::NKF::UTF16 opt << 'w16' when ::NKF::NOCONV return str end opt = '' if opt == '-' ::NKF::nkf(opt, str) end module_function :kconv # # Encode to # # call-seq: # Kconv.tojis(str) -> string # # Convert <code>str</code> to ISO-2022-JP # # *Note* # This method decode MIME encoded string and # convert halfwidth katakana to fullwidth katakana. # If you don't want it, use NKF.nkf('-jxm0', str). def tojis(str) ::NKF::nkf('-jm', str) end module_function :tojis # call-seq: # Kconv.toeuc(str) -> string # # Convert <code>str</code> to EUC-JP # # *Note* # This method decode MIME encoded string and # convert halfwidth katakana to fullwidth katakana. # If you don't want it, use NKF.nkf('-exm0', str). def toeuc(str) ::NKF::nkf('-em', str) end module_function :toeuc # call-seq: # Kconv.tosjis(str) -> string # # Convert <code>str</code> to Shift_JIS # # *Note* # This method decode MIME encoded string and # convert halfwidth katakana to fullwidth katakana. # If you don't want it, use NKF.nkf('-sxm0', str). def tosjis(str) ::NKF::nkf('-sm', str) end module_function :tosjis # call-seq: # Kconv.toutf8(str) -> string # # Convert <code>str</code> to UTF-8 # # *Note* # This method decode MIME encoded string and # convert halfwidth katakana to fullwidth katakana. # If you don't want it, use NKF.nkf('-wxm0', str). def toutf8(str) ::NKF::nkf('-wm', str) end module_function :toutf8 # call-seq: # Kconv.toutf16(str) -> string # # Convert <code>str</code> to UTF-16 # # *Note* # This method decode MIME encoded string and # convert halfwidth katakana to fullwidth katakana. # If you don't want it, use NKF.nkf('-w16xm0', str). def toutf16(str) ::NKF::nkf('-w16m', str) end module_function :toutf16 # # guess # # call-seq: # Kconv.guess(str) -> integer # # Guess input encoding by NKF.guess2 def guess(str) ::NKF::guess(str) end module_function :guess # call-seq: # Kconv.guess_old(str) -> integer # # Guess input encoding by NKF.guess1 def guess_old(str) ::NKF::guess1(str) end module_function :guess_old # # isEncoding # # call-seq: # Kconv.iseuc(str) -> obj or nil # # Returns whether input encoding is EUC-JP or not. # # *Note* don't expect this return value is MatchData. def iseuc(str) RegexpEucjp.match( str ) end module_function :iseuc # call-seq: # Kconv.issjis(str) -> obj or nil # # Returns whether input encoding is Shift_JIS or not. # # *Note* don't expect this return value is MatchData. def issjis(str) RegexpShiftjis.match( str ) end module_function :issjis # call-seq: # Kconv.isutf8(str) -> obj or nil # # Returns whether input encoding is UTF-8 or not. # # *Note* don't expect this return value is MatchData. def isutf8(str) RegexpUtf8.match( str ) end module_function :isutf8 end class String # call-seq: # String#kconv(out_code, in_code = Kconv::AUTO) # # Convert <code>self</code> to out_code. # <code>out_code</code> and <code>in_code</code> are given as constants of Kconv. # # *Note* # This method decode MIME encoded string and # convert halfwidth katakana to fullwidth katakana. # If you don't want to decode them, use NKF.nkf. def kconv(out_code, in_code=Kconv::AUTO) Kconv::kconv(self, out_code, in_code) end # # to Encoding # # call-seq: # String#tojis -> string # # Convert <code>self</code> to ISO-2022-JP # # *Note* # This method decode MIME encoded string and # convert halfwidth katakana to fullwidth katakana. # If you don't want it, use NKF.nkf('-jxm0', str). def tojis; Kconv.tojis(self) end # call-seq: # String#toeuc -> string # # Convert <code>self</code> to EUC-JP # # *Note* # This method decode MIME encoded string and # convert halfwidth katakana to fullwidth katakana. # If you don't want it, use NKF.nkf('-exm0', str). def toeuc; Kconv.toeuc(self) end # call-seq: # String#tosjis -> string # # Convert <code>self</code> to Shift_JIS # # *Note* # This method decode MIME encoded string and # convert halfwidth katakana to fullwidth katakana. # If you don't want it, use NKF.nkf('-sxm0', str). def tosjis; Kconv.tosjis(self) end # call-seq: # String#toutf8 -> string # # Convert <code>self</code> to UTF-8 # # *Note* # This method decode MIME encoded string and # convert halfwidth katakana to fullwidth katakana. # If you don't want it, use NKF.nkf('-wxm0', str). def toutf8; Kconv.toutf8(self) end # call-seq: # String#toutf16 -> string # # Convert <code>self</code> to UTF-16 # # *Note* # This method decode MIME encoded string and # convert halfwidth katakana to fullwidth katakana. # If you don't want it, use NKF.nkf('-w16xm0', str). def toutf16; Kconv.toutf16(self) end # # is Encoding # # call-seq: # String#iseuc -> obj or nil # # Returns whether <code>self</code>'s encoding is EUC-JP or not. # # *Note* don't expect this return value is MatchData. def iseuc; Kconv.iseuc(self) end # call-seq: # String#issjis -> obj or nil # # Returns whether <code>self</code>'s encoding is Shift_JIS or not. # # *Note* don't expect this return value is MatchData. def issjis; Kconv.issjis(self) end # call-seq: # String#isutf8 -> obj or nil # # Returns whether <code>self</code>'s encoding is UTF-8 or not. # # *Note* don't expect this return value is MatchData. def isutf8; Kconv.isutf8(self) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/irb.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb.rb
# # irb.rb - irb main module # $Release Version: 0.9.5 $ # $Revision: 24483 $ # $Date: 2009-08-09 17:44:15 +0900 (Sun, 09 Aug 2009) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "e2mmap" require "irb/init" require "irb/context" require "irb/extend-command" #require "irb/workspace" require "irb/ruby-lex" require "irb/input-method" require "irb/locale" STDOUT.sync = true module IRB @RCS_ID='-$Id: irb.rb 24483 2009-08-09 08:44:15Z shyouhei $-' class Abort < Exception;end # @CONF = {} def IRB.conf @CONF end # IRB version method def IRB.version if v = @CONF[:VERSION] then return v end require "irb/version" rv = @RELEASE_VERSION.sub(/\.0/, "") @CONF[:VERSION] = format("irb %s(%s)", rv, @LAST_UPDATE_DATE) end def IRB.CurrentContext IRB.conf[:MAIN_CONTEXT] end # initialize IRB and start TOP_LEVEL irb def IRB.start(ap_path = nil) $0 = File::basename(ap_path, ".rb") if ap_path IRB.setup(ap_path) if @CONF[:SCRIPT] irb = Irb.new(nil, @CONF[:SCRIPT]) else irb = Irb.new end @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] @CONF[:MAIN_CONTEXT] = irb.context trap("SIGINT") do irb.signal_handle end begin catch(:IRB_EXIT) do irb.eval_input end ensure irb_at_exit end # print "\n" end def IRB.irb_at_exit @CONF[:AT_EXIT].each{|hook| hook.call} end def IRB.irb_exit(irb, ret) throw :IRB_EXIT, ret end def IRB.irb_abort(irb, exception = Abort) if defined? Thread irb.context.thread.raise exception, "abort then interrupt!!" else raise exception, "abort then interrupt!!" end end # # irb interpriter main routine # class Irb def initialize(workspace = nil, input_method = nil, output_method = nil) @context = Context.new(self, workspace, input_method, output_method) @context.main.extend ExtendCommandBundle @signal_status = :IN_IRB @scanner = RubyLex.new @scanner.exception_on_syntax_error = false end attr_reader :context attr_accessor :scanner def eval_input @scanner.set_prompt do |ltype, indent, continue, line_no| if ltype f = @context.prompt_s elsif continue f = @context.prompt_c elsif indent > 0 f = @context.prompt_n else @context.prompt_i f = @context.prompt_i end f = "" unless f if @context.prompting? @context.io.prompt = p = prompt(f, ltype, indent, line_no) else @context.io.prompt = p = "" end if @context.auto_indent_mode unless ltype ind = prompt(@context.prompt_i, ltype, indent, line_no)[/.*\z/].size + indent * 2 - p.size ind += 2 if continue @context.io.prompt = p + " " * ind if ind > 0 end end end @scanner.set_input(@context.io) do signal_status(:IN_INPUT) do if l = @context.io.gets print l if @context.verbose? else if @context.ignore_eof? and @context.io.readable_atfer_eof? l = "\n" if @context.verbose? printf "Use \"exit\" to leave %s\n", @context.ap_name end end end l end end @scanner.each_top_level_statement do |line, line_no| signal_status(:IN_EVAL) do begin line.untaint @context.evaluate(line, line_no) output_value if @context.echo? exc = nil rescue Interrupt => exc rescue SystemExit, SignalException raise rescue Exception => exc end if exc print exc.class, ": ", exc, "\n" if exc.backtrace[0] =~ /irb(2)?(\/.*|-.*|\.rb)?:/ && exc.class.to_s !~ /^IRB/ irb_bug = true else irb_bug = false end messages = [] lasts = [] levels = 0 for m in exc.backtrace m = @context.workspace.filter_backtrace(m) unless irb_bug if m if messages.size < @context.back_trace_limit messages.push "\tfrom "+m else lasts.push "\tfrom "+m if lasts.size > @context.back_trace_limit lasts.shift levels += 1 end end end end print messages.join("\n"), "\n" unless lasts.empty? printf "... %d levels...\n", levels if levels > 0 print lasts.join("\n") end print "Maybe IRB bug!!\n" if irb_bug end if $SAFE > 2 abort "Error: irb does not work for $SAFE level higher than 2" end end end end def suspend_name(path = nil, name = nil) @context.irb_path, back_path = path, @context.irb_path if path @context.irb_name, back_name = name, @context.irb_name if name begin yield back_path, back_name ensure @context.irb_path = back_path if path @context.irb_name = back_name if name end end def suspend_workspace(workspace) @context.workspace, back_workspace = workspace, @context.workspace begin yield back_workspace ensure @context.workspace = back_workspace end end def suspend_input_method(input_method) back_io = @context.io @context.instance_eval{@io = input_method} begin yield back_io ensure @context.instance_eval{@io = back_io} end end def suspend_context(context) @context, back_context = context, @context begin yield back_context ensure @context = back_context end end def signal_handle unless @context.ignore_sigint? print "\nabort!!\n" if @context.verbose? exit end case @signal_status when :IN_INPUT print "^C\n" raise RubyLex::TerminateLineInput when :IN_EVAL IRB.irb_abort(self) when :IN_LOAD IRB.irb_abort(self, LoadAbort) when :IN_IRB # ignore else # ignore other cases as well end end def signal_status(status) return yield if @signal_status == :IN_LOAD signal_status_back = @signal_status @signal_status = status begin yield ensure @signal_status = signal_status_back end end def prompt(prompt, ltype, indent, line_no) p = prompt.dup p.gsub!(/%([0-9]+)?([a-zA-Z])/) do case $2 when "N" @context.irb_name when "m" @context.main.to_s when "M" @context.main.inspect when "l" ltype when "i" if $1 format("%" + $1 + "d", indent) else indent.to_s end when "n" if $1 format("%" + $1 + "d", line_no) else line_no.to_s end when "%" "%" end end p end def output_value if @context.inspect? printf @context.return_format, @context.last_value.inspect else printf @context.return_format, @context.last_value end end def inspect ary = [] for iv in instance_variables case iv when "@signal_status" ary.push format("%s=:%s", iv, @signal_status.id2name) when "@context" ary.push format("%s=%s", iv, eval(iv).__to_s__) else ary.push format("%s=%s", iv, eval(iv)) end end format("#<%s: %s>", self.class, ary.join(", ")) end end # Singleton method def @CONF.inspect IRB.version unless self[:VERSION] array = [] for k, v in sort{|a1, a2| a1[0].id2name <=> a2[0].id2name} case k when :MAIN_CONTEXT, :__TMP__EHV__ array.push format("CONF[:%s]=...myself...", k.id2name) when :PROMPT s = v.collect{ |kk, vv| ss = vv.collect{|kkk, vvv| ":#{kkk.id2name}=>#{vvv.inspect}"} format(":%s=>{%s}", kk.id2name, ss.join(", ")) } array.push format("CONF[:%s]={%s}", k.id2name, s.join(", ")) else array.push format("CONF[:%s]=%s", k.id2name, v.inspect) end end array.join("\n") end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/Env.rb
tools/jruby-1.5.1/lib/ruby/1.8/Env.rb
# Env.rb -- imports environment variables as global variables, Perlish ;( # Usage: # # require 'Env' # p $USER # $USER = "matz" # p ENV["USER"] require 'importenv' if __FILE__ == $0 p $TERM $TERM = nil p $TERM p ENV["TERM"] $TERM = "foo" p ENV["TERM"] end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/base64.rb
tools/jruby-1.5.1/lib/ruby/1.8/base64.rb
# # = base64.rb: methods for base64-encoding and -decoding stings # # Author:: Yukihiro Matsumoto # Documentation:: Dave Thomas and Gavin Sinclair # # Until Ruby 1.8.1, these methods were defined at the top-level. Now # they are in the Base64 module but included in the top-level, where # their usage is deprecated. # # See Base64 for documentation. # require "kconv" # The Base64 module provides for the encoding (#encode64) and decoding # (#decode64) of binary data using a Base64 representation. # # The following particular features are also provided: # - encode into lines of a given length (#b64encode) # - decode the special format specified in RFC2047 for the # representation of email headers (decode_b) # # == Example # # A simple encoding and decoding. # # require "base64" # # enc = Base64.encode64('Send reinforcements') # # -> "U2VuZCByZWluZm9yY2VtZW50cw==\n" # plain = Base64.decode64(enc) # # -> "Send reinforcements" # # The purpose of using base64 to encode data is that it translates any # binary data into purely printable characters. It is specified in # RFC 2045 (http://www.faqs.org/rfcs/rfc2045.html). module Base64 module_function # Returns the Base64-decoded version of +str+. # # require 'base64' # str = 'VGhpcyBpcyBsaW5lIG9uZQpUaGlzIG' + # 'lzIGxpbmUgdHdvClRoaXMgaXMgbGlu' + # 'ZSB0aHJlZQpBbmQgc28gb24uLi4K' # puts Base64.decode64(str) # # <i>Generates:</i> # # This is line one # This is line two # This is line three # And so on... def decode64(str) str.unpack("m")[0] end # Decodes text formatted using a subset of RFC2047 (the one used for # mime-encoding mail headers). # # Only supports an encoding type of 'b' (base 64), and only supports # the character sets ISO-2022-JP and SHIFT_JIS (so the only two # encoded word sequences recognized are <tt>=?ISO-2022-JP?B?...=</tt> and # <tt>=?SHIFT_JIS?B?...=</tt>). Recognition of these sequences is case # insensitive. def decode_b(str) str.gsub!(/=\?ISO-2022-JP\?B\?([!->@-~]+)\?=/i) { decode64($1) } str = Kconv::toeuc(str) str.gsub!(/=\?SHIFT_JIS\?B\?([!->@-~]+)\?=/i) { decode64($1) } str = Kconv::toeuc(str) str.gsub!(/\n/, ' ') str.gsub!(/\0/, '') str end # Returns the Base64-encoded version of +str+. # # require 'base64' # Base64.b64encode("Now is the time for all good coders\nto learn Ruby") # # <i>Generates:</i> # # Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwgZ29vZCBjb2RlcnMKdG8gbGVhcm4g # UnVieQ== def encode64(bin) [bin].pack("m") end # _Prints_ the Base64 encoded version of +bin+ (a +String+) in lines of # +len+ (default 60) characters. # # require 'base64' # data = "Now is the time for all good coders\nto learn Ruby" # Base64.b64encode(data) # # <i>Generates:</i> # # Tm93IGlzIHRoZSB0aW1lIGZvciBhbGwgZ29vZCBjb2RlcnMKdG8gbGVhcm4g # UnVieQ== def b64encode(bin, len = 60) encode64(bin).scan(/.{1,#{len}}/) do print $&, "\n" end end module Deprecated # :nodoc: include Base64 for m in Base64.private_instance_methods(false) module_eval %{ def #{m}(*args) warn("\#{caller(1)[0]}: #{m} is deprecated; use Base64.#{m} instead") super end } end end end include Base64::Deprecated
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/un.rb
tools/jruby-1.5.1/lib/ruby/1.8/un.rb
# # = un.rb # # Copyright (c) 2003 WATANABE Hirofumi <eban@ruby-lang.org> # # This program is free software. # You can distribute/modify this program under the same terms of Ruby. # # == Utilities to replace common UNIX commands in Makefiles etc # # == SYNOPSIS # # ruby -run -e cp -- [OPTION] SOURCE DEST # ruby -run -e ln -- [OPTION] TARGET LINK_NAME # ruby -run -e mv -- [OPTION] SOURCE DEST # ruby -run -e rm -- [OPTION] FILE # ruby -run -e mkdir -- [OPTION] DIRS # ruby -run -e rmdir -- [OPTION] DIRS # ruby -run -e install -- [OPTION] SOURCE DEST # ruby -run -e chmod -- [OPTION] OCTAL-MODE FILE # ruby -run -e touch -- [OPTION] FILE # ruby -run -e help [COMMAND] require "fileutils" require "optparse" module FileUtils # @fileutils_label = "" @fileutils_output = $stdout end def setup(options = "") ARGV.map! do |x| case x when /^-/ x.delete "^-#{options}v" when /[*?\[{]/ Dir[x] else x end end ARGV.flatten! ARGV.delete_if{|x| x == "-"} opt_hash = {} OptionParser.new do |o| options.scan(/.:?/) do |s| o.on("-" + s.tr(":", " ")) do |val| opt_hash[s.delete(":").intern] = val end end o.on("-v") do opt_hash[:verbose] = true end o.parse! end yield ARGV, opt_hash end ## # Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY # # ruby -run -e cp -- [OPTION] SOURCE DEST # # -p preserve file attributes if possible # -r copy recursively # -v verbose # def cp setup("pr") do |argv, options| cmd = "cp" cmd += "_r" if options.delete :r options[:preserve] = true if options.delete :p dest = argv.pop argv = argv[0] if argv.size == 1 FileUtils.send cmd, argv, dest, options end end ## # Create a link to the specified TARGET with LINK_NAME. # # ruby -run -e ln -- [OPTION] TARGET LINK_NAME # # -s make symbolic links instead of hard links # -f remove existing destination files # -v verbose # def ln setup("sf") do |argv, options| cmd = "ln" cmd += "_s" if options.delete :s options[:force] = true if options.delete :f dest = argv.pop argv = argv[0] if argv.size == 1 FileUtils.send cmd, argv, dest, options end end ## # Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY. # # ruby -run -e mv -- [OPTION] SOURCE DEST # # -v verbose # def mv setup do |argv, options| dest = argv.pop argv = argv[0] if argv.size == 1 FileUtils.mv argv, dest, options end end ## # Remove the FILE # # ruby -run -e rm -- [OPTION] FILE # # -f ignore nonexistent files # -r remove the contents of directories recursively # -v verbose # def rm setup("fr") do |argv, options| cmd = "rm" cmd += "_r" if options.delete :r options[:force] = true if options.delete :f FileUtils.send cmd, argv, options end end ## # Create the DIR, if they do not already exist. # # ruby -run -e mkdir -- [OPTION] DIR # # -p no error if existing, make parent directories as needed # -v verbose # def mkdir setup("p") do |argv, options| cmd = "mkdir" cmd += "_p" if options.delete :p FileUtils.send cmd, argv, options end end ## # Remove the DIR. # # ruby -run -e rmdir -- [OPTION] DIR # # -v verbose # def rmdir setup do |argv, options| FileUtils.rmdir argv, options end end ## # Copy SOURCE to DEST. # # ruby -run -e install -- [OPTION] SOURCE DEST # # -p apply access/modification times of SOURCE files to # corresponding destination files # -m set permission mode (as in chmod), instead of 0755 # -v verbose # def install setup("pm:") do |argv, options| options[:mode] = (mode = options.delete :m) ? mode.oct : 0755 options[:preserve] = true if options.delete :p dest = argv.pop argv = argv[0] if argv.size == 1 FileUtils.install argv, dest, options end end ## # Change the mode of each FILE to OCTAL-MODE. # # ruby -run -e chmod -- [OPTION] OCTAL-MODE FILE # # -v verbose # def chmod setup do |argv, options| mode = argv.shift.oct FileUtils.chmod mode, argv, options end end ## # Update the access and modification times of each FILE to the current time. # # ruby -run -e touch -- [OPTION] FILE # # -v verbose # def touch setup do |argv, options| FileUtils.touch argv, options end end ## # Display help message. # # ruby -run -e help [COMMAND] # def help setup do |argv,| all = argv.empty? open(__FILE__) do |me| while me.gets("##\n") if help = me.gets("\n\n") if all or argv.delete help[/-e \w+/].sub(/-e /, "") print help.gsub(/^# ?/, "") end end end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/eregex.rb
tools/jruby-1.5.1/lib/ruby/1.8/eregex.rb
# this is just a proof of concept toy. class RegOr def initialize(re1, re2) @re1 = re1 @re2 = re2 end def =~ (str) @re1 =~ str or @re2 =~ str end end class RegAnd def initialize(re1, re2) @re1 = re1 @re2 = re2 end def =~ (str) @re1 =~ str and @re2 =~ str end end class Regexp def |(other) RegOr.new(self, other) end def &(other) RegAnd.new(self, other) end end if __FILE__ == $0 p "abc" =~ /b/|/c/ p "abc" =~ /b/&/c/ end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/md5.rb
tools/jruby-1.5.1/lib/ruby/1.8/md5.rb
# just for compatibility; requiring "md5" is obsoleted # # $RoughId: md5.rb,v 1.4 2001/07/13 15:38:27 knu Exp $ # $Id: md5.rb 12007 2007-03-06 10:09:51Z knu $ require 'digest/md5' class MD5 < Digest::MD5 class << self alias orig_new new def new(str = nil) if str orig_new.update(str) else orig_new end end def md5(*args) new(*args) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/uri.rb
tools/jruby-1.5.1/lib/ruby/1.8/uri.rb
# # URI support for Ruby # # Author:: Akira Yamada <akira@ruby-lang.org> # Documentation:: Akira Yamada <akira@ruby-lang.org>, Dmitry V. Sabanin <sdmitry@lrn.ru> # License:: # Copyright (c) 2001 akira yamada <akira@ruby-lang.org> # You can redistribute it and/or modify it under the same term as Ruby. # Revision:: $Id: uri.rb 16038 2008-04-15 09:41:47Z kazu $ # # See URI for documentation # module URI # :stopdoc: VERSION_CODE = '000911'.freeze VERSION = VERSION_CODE.scan(/../).collect{|n| n.to_i}.join('.').freeze # :startdoc: end require 'uri/common' require 'uri/generic' require 'uri/ftp' require 'uri/http' require 'uri/https' require 'uri/ldap' require 'uri/ldaps' require 'uri/mailto'
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/debug.rb
tools/jruby-1.5.1/lib/ruby/1.8/debug.rb
# Copyright (C) 2000 Network Applied Communication Laboratory, Inc. # Copyright (C) 2000 Information-technology Promotion Agency, Japan # Copyright (C) 2000-2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org> if $SAFE > 0 STDERR.print "-r debug.rb is not available in safe mode\n" exit 1 end require 'tracer' require 'pp' class Tracer def Tracer.trace_func(*vars) Single.trace_func(*vars) end end SCRIPT_LINES__ = {} unless defined? SCRIPT_LINES__ class DEBUGGER__ class Mutex def initialize @locker = nil @waiting = [] @locked = false; end def locked? @locked end def lock return if Thread.critical return if @locker == Thread.current while (Thread.critical = true; @locked) @waiting.push Thread.current Thread.stop end @locked = true @locker = Thread.current Thread.critical = false self end def unlock return if Thread.critical return unless @locked unless @locker == Thread.current raise RuntimeError, "unlocked by other" end Thread.critical = true t = @waiting.shift @locked = false @locker = nil Thread.critical = false t.run if t self end end MUTEX = Mutex.new class Context DEBUG_LAST_CMD = [] begin require 'readline' def readline(prompt, hist) Readline::readline(prompt, hist) end rescue LoadError def readline(prompt, hist) STDOUT.print prompt STDOUT.flush line = STDIN.gets exit unless line line.chomp! line end USE_READLINE = false end def initialize if Thread.current == Thread.main @stop_next = 1 else @stop_next = 0 end @last_file = nil @file = nil @line = nil @no_step = nil @frames = [] @finish_pos = 0 @trace = false @catch = "StandardError" @suspend_next = false end def stop_next(n=1) @stop_next = n end def set_suspend @suspend_next = true end def clear_suspend @suspend_next = false end def suspend_all DEBUGGER__.suspend end def resume_all DEBUGGER__.resume end def check_suspend return if Thread.critical while (Thread.critical = true; @suspend_next) DEBUGGER__.waiting.push Thread.current @suspend_next = false Thread.stop end Thread.critical = false end def trace? @trace end def set_trace(arg) @trace = arg end def stdout DEBUGGER__.stdout end def break_points DEBUGGER__.break_points end def display DEBUGGER__.display end def context(th) DEBUGGER__.context(th) end def set_trace_all(arg) DEBUGGER__.set_trace(arg) end def set_last_thread(th) DEBUGGER__.set_last_thread(th) end def debug_eval(str, binding) begin val = eval(str, binding) rescue StandardError, ScriptError => e at = eval("caller(1)", binding) stdout.printf "%s:%s\n", at.shift, e.to_s.sub(/\(eval\):1:(in `.*?':)?/, '') for i in at stdout.printf "\tfrom %s\n", i end throw :debug_error end end def debug_silent_eval(str, binding) begin eval(str, binding) rescue StandardError, ScriptError nil end end def var_list(ary, binding) ary.sort! for v in ary stdout.printf " %s => %s\n", v, eval(v, binding).inspect end end def debug_variable_info(input, binding) case input when /^\s*g(?:lobal)?\s*$/ var_list(global_variables, binding) when /^\s*l(?:ocal)?\s*$/ var_list(eval("local_variables", binding), binding) when /^\s*i(?:nstance)?\s+/ obj = debug_eval($', binding) var_list(obj.instance_variables, obj.instance_eval{binding()}) when /^\s*c(?:onst(?:ant)?)?\s+/ obj = debug_eval($', binding) unless obj.kind_of? Module stdout.print "Should be Class/Module: ", $', "\n" else var_list(obj.constants, obj.module_eval{binding()}) end end end def debug_method_info(input, binding) case input when /^i(:?nstance)?\s+/ obj = debug_eval($', binding) len = 0 for v in obj.methods.sort len += v.size + 1 if len > 70 len = v.size + 1 stdout.print "\n" end stdout.print v, " " end stdout.print "\n" else obj = debug_eval(input, binding) unless obj.kind_of? Module stdout.print "Should be Class/Module: ", input, "\n" else len = 0 for v in obj.instance_methods(false).sort len += v.size + 1 if len > 70 len = v.size + 1 stdout.print "\n" end stdout.print v, " " end stdout.print "\n" end end end def thnum num = DEBUGGER__.instance_eval{@thread_list[Thread.current]} unless num DEBUGGER__.make_thread_list num = DEBUGGER__.instance_eval{@thread_list[Thread.current]} end num end def debug_command(file, line, id, binding) MUTEX.lock # This is removed, since JRuby doesn't support continuations # unless defined?($debugger_restart) and $debugger_restart # callcc{|c| $debugger_restart = c} # end set_last_thread(Thread.current) frame_pos = 0 binding_file = file binding_line = line previous_line = nil if ENV['EMACS'] stdout.printf "\032\032%s:%d:\n", binding_file, binding_line else stdout.printf "%s:%d:%s", binding_file, binding_line, line_at(binding_file, binding_line) end @frames[0] = [binding, file, line, id] display_expressions(binding) prompt = true while prompt and input = readline("(rdb:%d) "%thnum(), true) catch(:debug_error) do if input == "" next unless DEBUG_LAST_CMD[0] input = DEBUG_LAST_CMD[0] stdout.print input, "\n" else DEBUG_LAST_CMD[0] = input end case input when /^\s*tr(?:ace)?(?:\s+(on|off))?(?:\s+(all))?$/ if defined?( $2 ) if $1 == 'on' set_trace_all true else set_trace_all false end elsif defined?( $1 ) if $1 == 'on' set_trace true else set_trace false end end if trace? stdout.print "Trace on.\n" else stdout.print "Trace off.\n" end when /^\s*b(?:reak)?\s+(?:(.+):)?([^.:]+)$/ pos = $2 if $1 klass = debug_silent_eval($1, binding) file = $1 end if pos =~ /^\d+$/ pname = pos pos = pos.to_i else pname = pos = pos.intern.id2name end break_points.push [true, 0, klass || file, pos] stdout.printf "Set breakpoint %d at %s:%s\n", break_points.size, klass || file, pname when /^\s*b(?:reak)?\s+(.+)[#.]([^.:]+)$/ pos = $2.intern.id2name klass = debug_eval($1, binding) break_points.push [true, 0, klass, pos] stdout.printf "Set breakpoint %d at %s.%s\n", break_points.size, klass, pos when /^\s*wat(?:ch)?\s+(.+)$/ exp = $1 break_points.push [true, 1, exp] stdout.printf "Set watchpoint %d:%s\n", break_points.size, exp when /^\s*b(?:reak)?$/ if break_points.find{|b| b[1] == 0} n = 1 stdout.print "Breakpoints:\n" for b in break_points if b[0] and b[1] == 0 stdout.printf " %d %s:%s\n", n, b[2], b[3] end n += 1 end end if break_points.find{|b| b[1] == 1} n = 1 stdout.print "\n" stdout.print "Watchpoints:\n" for b in break_points if b[0] and b[1] == 1 stdout.printf " %d %s\n", n, b[2] end n += 1 end end if break_points.size == 0 stdout.print "No breakpoints\n" else stdout.print "\n" end when /^\s*del(?:ete)?(?:\s+(\d+))?$/ pos = $1 unless pos input = readline("Clear all breakpoints? (y/n) ", false) if input == "y" for b in break_points b[0] = false end end else pos = pos.to_i if break_points[pos-1] break_points[pos-1][0] = false else stdout.printf "Breakpoint %d is not defined\n", pos end end when /^\s*disp(?:lay)?\s+(.+)$/ exp = $1 display.push [true, exp] stdout.printf "%d: ", display.size display_expression(exp, binding) when /^\s*disp(?:lay)?$/ display_expressions(binding) when /^\s*undisp(?:lay)?(?:\s+(\d+))?$/ pos = $1 unless pos input = readline("Clear all expressions? (y/n) ", false) if input == "y" for d in display d[0] = false end end else pos = pos.to_i if display[pos-1] display[pos-1][0] = false else stdout.printf "Display expression %d is not defined\n", pos end end when /^\s*c(?:ont)?$/ prompt = false when /^\s*s(?:tep)?(?:\s+(\d+))?$/ if $1 lev = $1.to_i else lev = 1 end @stop_next = lev prompt = false when /^\s*n(?:ext)?(?:\s+(\d+))?$/ if $1 lev = $1.to_i else lev = 1 end @stop_next = lev @no_step = @frames.size - frame_pos prompt = false when /^\s*w(?:here)?$/, /^\s*f(?:rame)?$/ display_frames(frame_pos) when /^\s*l(?:ist)?(?:\s+(.+))?$/ if not $1 b = previous_line ? previous_line + 10 : binding_line - 5 e = b + 9 elsif $1 == '-' b = previous_line ? previous_line - 10 : binding_line - 5 e = b + 9 else b, e = $1.split(/[-,]/) if e b = b.to_i e = e.to_i else b = b.to_i - 5 e = b + 9 end end previous_line = b display_list(b, e, binding_file, binding_line) when /^\s*up(?:\s+(\d+))?$/ previous_line = nil if $1 lev = $1.to_i else lev = 1 end frame_pos += lev if frame_pos >= @frames.size frame_pos = @frames.size - 1 stdout.print "At toplevel\n" end binding, binding_file, binding_line = @frames[frame_pos] stdout.print format_frame(frame_pos) when /^\s*down(?:\s+(\d+))?$/ previous_line = nil if $1 lev = $1.to_i else lev = 1 end frame_pos -= lev if frame_pos < 0 frame_pos = 0 stdout.print "At stack bottom\n" end binding, binding_file, binding_line = @frames[frame_pos] stdout.print format_frame(frame_pos) when /^\s*fin(?:ish)?$/ if frame_pos == @frames.size stdout.print "\"finish\" not meaningful in the outermost frame.\n" else @finish_pos = @frames.size - frame_pos frame_pos = 0 prompt = false end when /^\s*cat(?:ch)?(?:\s+(.+))?$/ if $1 excn = $1 if excn == 'off' @catch = nil stdout.print "Clear catchpoint.\n" else @catch = excn stdout.printf "Set catchpoint %s.\n", @catch end else if @catch stdout.printf "Catchpoint %s.\n", @catch else stdout.print "No catchpoint.\n" end end when /^\s*q(?:uit)?$/ input = readline("Really quit? (y/n) ", false) if input == "y" exit! # exit -> exit!: No graceful way to stop threads... end when /^\s*v(?:ar)?\s+/ debug_variable_info($', binding) when /^\s*m(?:ethod)?\s+/ debug_method_info($', binding) when /^\s*th(?:read)?\s+/ if DEBUGGER__.debug_thread_info($', binding) == :cont prompt = false end when /^\s*pp\s+/ PP.pp(debug_eval($', binding), stdout) when /^\s*p\s+/ stdout.printf "%s\n", debug_eval($', binding).inspect when /^\s*r(?:estart)?$/ stdout.print "JRuby doesn't support the command restart, since it depends on continuations" # $debugger_restart.call when /^\s*h(?:elp)?$/ debug_print_help() else v = debug_eval(input, binding) stdout.printf "%s\n", v.inspect end end end MUTEX.unlock resume_all end def debug_print_help stdout.print <<EOHELP Debugger help v.-0.002b Commands b[reak] [file:|class:]<line|method> b[reak] [class.]<line|method> set breakpoint to some position wat[ch] <expression> set watchpoint to some expression cat[ch] (<exception>|off) set catchpoint to an exception b[reak] list breakpoints cat[ch] show catchpoint del[ete][ nnn] delete some or all breakpoints disp[lay] <expression> add expression into display expression list undisp[lay][ nnn] delete one particular or all display expressions c[ont] run until program ends or hit breakpoint s[tep][ nnn] step (into methods) one line or till line nnn n[ext][ nnn] go over one line or till line nnn w[here] display frames f[rame] alias for where l[ist][ (-|nn-mm)] list program, - lists backwards nn-mm lists given lines up[ nn] move to higher frame down[ nn] move to lower frame fin[ish] return to outer frame tr[ace] (on|off) set trace mode of current thread tr[ace] (on|off) all set trace mode of all threads q[uit] exit from debugger v[ar] g[lobal] show global variables v[ar] l[ocal] show local variables v[ar] i[nstance] <object> show instance variables of object v[ar] c[onst] <object> show constants of object m[ethod] i[nstance] <obj> show methods of object m[ethod] <class|module> show instance methods of class or module th[read] l[ist] list all threads th[read] c[ur[rent]] show current thread th[read] [sw[itch]] <nnn> switch thread context to nnn th[read] stop <nnn> stop thread nnn th[read] resume <nnn> resume thread nnn p expression evaluate expression and print its value h[elp] print this help <everything else> evaluate EOHELP end def display_expressions(binding) n = 1 for d in display if d[0] stdout.printf "%d: ", n display_expression(d[1], binding) end n += 1 end end def display_expression(exp, binding) stdout.printf "%s = %s\n", exp, debug_silent_eval(exp, binding).to_s end def frame_set_pos(file, line) if @frames[0] @frames[0][1] = file @frames[0][2] = line end end def display_frames(pos) 0.upto(@frames.size - 1) do |n| if n == pos stdout.print "--> " else stdout.print " " end stdout.print format_frame(n) end end def format_frame(pos) bind, file, line, id = @frames[pos] sprintf "#%d %s:%s%s\n", pos + 1, file, line, (id ? ":in `#{id.id2name}'" : "") end def display_list(b, e, file, line) stdout.printf "[%d, %d] in %s\n", b, e, file if lines = SCRIPT_LINES__[file] and lines != true n = 0 b.upto(e) do |n| if n > 0 && lines[n-1] if n == line stdout.printf "=> %d %s\n", n, lines[n-1].chomp else stdout.printf " %d %s\n", n, lines[n-1].chomp end end end else stdout.printf "No sourcefile available for %s\n", file end end def line_at(file, line) lines = SCRIPT_LINES__[file] if lines return "\n" if lines == true line = lines[line-1] return "\n" unless line return line end return "\n" end def debug_funcname(id) if id.nil? "toplevel" else id.id2name end end def check_break_points(file, klass, pos, binding, id) return false if break_points.empty? n = 1 for b in break_points if b[0] # valid if b[1] == 0 # breakpoint if (b[2] == file and b[3] == pos) or (klass and b[2] == klass and b[3] == pos) stdout.printf "Breakpoint %d, %s at %s:%s\n", n, debug_funcname(id), file, pos return true end elsif b[1] == 1 # watchpoint if debug_silent_eval(b[2], binding) stdout.printf "Watchpoint %d, %s at %s:%s\n", n, debug_funcname(id), file, pos return true end end end n += 1 end return false end def excn_handle(file, line, id, binding) if $!.class <= SystemExit set_trace_func nil exit end if @catch and ($!.class.ancestors.find { |e| e.to_s == @catch }) stdout.printf "%s:%d: `%s' (%s)\n", file, line, $!, $!.class fs = @frames.size tb = caller(0)[-fs..-1] if tb for i in tb stdout.printf "\tfrom %s\n", i end end suspend_all debug_command(file, line, id, binding) end end def trace_func(event, file, line, id, binding, klass) Tracer.trace_func(event, file, line, id, binding, klass) if trace? context(Thread.current).check_suspend @file = file @line = line case event when 'line' frame_set_pos(file, line) if !@no_step or @frames.size == @no_step @stop_next -= 1 @stop_next = -1 if @stop_next < 0 elsif @frames.size < @no_step @stop_next = 0 # break here before leaving... else # nothing to do. skipped. end if @stop_next == 0 or check_break_points(file, nil, line, binding, id) @no_step = nil suspend_all debug_command(file, line, id, binding) end when 'call' @frames.unshift [binding, file, line, id] if check_break_points(file, klass, id.id2name, binding, id) suspend_all debug_command(file, line, id, binding) end when 'c-call' frame_set_pos(file, line) when 'class' @frames.unshift [binding, file, line, id] when 'return', 'end' if @frames.size == @finish_pos @stop_next = 1 @finish_pos = 0 end @frames.shift when 'end' @frames.shift when 'raise' excn_handle(file, line, id, binding) end @last_file = file end end trap("INT") { DEBUGGER__.interrupt } @last_thread = Thread::main @max_thread = 1 @thread_list = {Thread::main => 1} @break_points = [] @display = [] @waiting = [] @stdout = STDOUT class << DEBUGGER__ def stdout @stdout end def stdout=(s) @stdout = s end def display @display end def break_points @break_points end def waiting @waiting end def set_trace( arg ) saved_crit = Thread.critical Thread.critical = true make_thread_list for th, in @thread_list context(th).set_trace arg end Thread.critical = saved_crit arg end def set_last_thread(th) @last_thread = th end def suspend saved_crit = Thread.critical Thread.critical = true make_thread_list for th, in @thread_list next if th == Thread.current context(th).set_suspend end Thread.critical = saved_crit # Schedule other threads to suspend as soon as possible. Thread.pass unless Thread.critical end def resume saved_crit = Thread.critical Thread.critical = true make_thread_list for th, in @thread_list next if th == Thread.current context(th).clear_suspend end waiting.each do |th| th.run end waiting.clear Thread.critical = saved_crit # Schedule other threads to restart as soon as possible. Thread.pass end def context(thread=Thread.current) c = thread[:__debugger_data__] unless c thread[:__debugger_data__] = c = Context.new end c end def interrupt context(@last_thread).stop_next end def get_thread(num) th = @thread_list.index(num) unless th @stdout.print "No thread ##{num}\n" throw :debug_error end th end def thread_list(num) th = get_thread(num) if th == Thread.current @stdout.print "+" else @stdout.print " " end @stdout.printf "%d ", num @stdout.print th.inspect, "\t" file = context(th).instance_eval{@file} if file @stdout.print file,":",context(th).instance_eval{@line} end @stdout.print "\n" end def thread_list_all for th in @thread_list.values.sort thread_list(th) end end def make_thread_list hash = {} for th in Thread::list if @thread_list.key? th hash[th] = @thread_list[th] else @max_thread += 1 hash[th] = @max_thread end end @thread_list = hash end def debug_thread_info(input, binding) case input when /^l(?:ist)?/ make_thread_list thread_list_all when /^c(?:ur(?:rent)?)?$/ make_thread_list thread_list(@thread_list[Thread.current]) when /^(?:sw(?:itch)?\s+)?(\d+)/ make_thread_list th = get_thread($1.to_i) if th == Thread.current @stdout.print "It's the current thread.\n" else thread_list(@thread_list[th]) context(th).stop_next th.run return :cont end when /^stop\s+(\d+)/ make_thread_list th = get_thread($1.to_i) if th == Thread.current @stdout.print "It's the current thread.\n" elsif th.stop? @stdout.print "Already stopped.\n" else thread_list(@thread_list[th]) context(th).suspend end when /^resume\s+(\d+)/ make_thread_list th = get_thread($1.to_i) if th == Thread.current @stdout.print "It's the current thread.\n" elsif !th.stop? @stdout.print "Already running." else thread_list(@thread_list[th]) th.run end end end end stdout.printf "Debug.rb\n" stdout.printf "Emacs support available.\n\n" set_trace_func proc { |event, file, line, id, binding, klass, *rest| DEBUGGER__.context.trace_func event, file, line, id, binding, klass } end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/drb.rb
tools/jruby-1.5.1/lib/ruby/1.8/drb.rb
require 'drb/drb'
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/matrix.rb
tools/jruby-1.5.1/lib/ruby/1.8/matrix.rb
#!/usr/local/bin/ruby #-- # matrix.rb - # $Release Version: 1.0$ # $Revision: 1.11 $ # $Date: 1999/10/06 11:01:53 $ # Original Version from Smalltalk-80 version # on July 23, 1985 at 8:37:17 am # by Keiju ISHITSUKA #++ # # = matrix.rb # # An implementation of Matrix and Vector classes. # # Author:: Keiju ISHITSUKA # Documentation:: Gavin Sinclair (sourced from <i>Ruby in a Nutshell</i> (Matsumoto, O'Reilly)) # # See classes Matrix and Vector for documentation. # require "e2mmap.rb" module ExceptionForMatrix # :nodoc: extend Exception2MessageMapper def_e2message(TypeError, "wrong argument type %s (expected %s)") def_e2message(ArgumentError, "Wrong # of arguments(%d for %d)") def_exception("ErrDimensionMismatch", "\#{self.name} dimension mismatch") def_exception("ErrNotRegular", "Not Regular Matrix") def_exception("ErrOperationNotDefined", "This operation(%s) can\\'t defined") end # # The +Matrix+ class represents a mathematical matrix, and provides methods for creating # special-case matrices (zero, identity, diagonal, singular, vector), operating on them # arithmetically and algebraically, and determining their mathematical properties (trace, rank, # inverse, determinant). # # Note that although matrices should theoretically be rectangular, this is not # enforced by the class. # # Also note that the determinant of integer matrices may be incorrectly calculated unless you # also <tt>require 'mathn'</tt>. This may be fixed in the future. # # == Method Catalogue # # To create a matrix: # * <tt> Matrix[*rows] </tt> # * <tt> Matrix.[](*rows) </tt> # * <tt> Matrix.rows(rows, copy = true) </tt> # * <tt> Matrix.columns(columns) </tt> # * <tt> Matrix.diagonal(*values) </tt> # * <tt> Matrix.scalar(n, value) </tt> # * <tt> Matrix.identity(n) </tt> # * <tt> Matrix.unit(n) </tt> # * <tt> Matrix.I(n) </tt> # * <tt> Matrix.zero(n) </tt> # * <tt> Matrix.row_vector(row) </tt> # * <tt> Matrix.column_vector(column) </tt> # # To access Matrix elements/columns/rows/submatrices/properties: # * <tt> [](i, j) </tt> # * <tt> #row_size </tt> # * <tt> #column_size </tt> # * <tt> #row(i) </tt> # * <tt> #column(j) </tt> # * <tt> #collect </tt> # * <tt> #map </tt> # * <tt> #minor(*param) </tt> # # Properties of a matrix: # * <tt> #regular? </tt> # * <tt> #singular? </tt> # * <tt> #square? </tt> # # Matrix arithmetic: # * <tt> *(m) </tt> # * <tt> +(m) </tt> # * <tt> -(m) </tt> # * <tt> #/(m) </tt> # * <tt> #inverse </tt> # * <tt> #inv </tt> # * <tt> ** </tt> # # Matrix functions: # * <tt> #determinant </tt> # * <tt> #det </tt> # * <tt> #rank </tt> # * <tt> #trace </tt> # * <tt> #tr </tt> # * <tt> #transpose </tt> # * <tt> #t </tt> # # Conversion to other data types: # * <tt> #coerce(other) </tt> # * <tt> #row_vectors </tt> # * <tt> #column_vectors </tt> # * <tt> #to_a </tt> # # String representations: # * <tt> #to_s </tt> # * <tt> #inspect </tt> # class Matrix @RCS_ID='-$Id: matrix.rb,v 1.11 1999/10/06 11:01:53 keiju Exp keiju $-' # extend Exception2MessageMapper include ExceptionForMatrix # instance creations private_class_method :new # # Creates a matrix where each argument is a row. # Matrix[ [25, 93], [-1, 66] ] # => 25 93 # -1 66 # def Matrix.[](*rows) new(:init_rows, rows, false) end # # Creates a matrix where +rows+ is an array of arrays, each of which is a row # of the matrix. If the optional argument +copy+ is false, use the given # arrays as the internal structure of the matrix without copying. # Matrix.rows([[25, 93], [-1, 66]]) # => 25 93 # -1 66 # def Matrix.rows(rows, copy = true) new(:init_rows, rows, copy) end # # Creates a matrix using +columns+ as an array of column vectors. # Matrix.columns([[25, 93], [-1, 66]]) # => 25 -1 # 93 66 # def Matrix.columns(columns) rows = (0 ... columns[0].size).collect {|i| (0 ... columns.size).collect {|j| columns[j][i] } } Matrix.rows(rows, false) end # # Creates a matrix where the diagonal elements are composed of +values+. # Matrix.diagonal(9, 5, -3) # => 9 0 0 # 0 5 0 # 0 0 -3 # def Matrix.diagonal(*values) size = values.size rows = (0 ... size).collect {|j| row = Array.new(size).fill(0, 0, size) row[j] = values[j] row } rows(rows, false) end # # Creates an +n+ by +n+ diagonal matrix where each diagonal element is # +value+. # Matrix.scalar(2, 5) # => 5 0 # 0 5 # def Matrix.scalar(n, value) Matrix.diagonal(*Array.new(n).fill(value, 0, n)) end # # Creates an +n+ by +n+ identity matrix. # Matrix.identity(2) # => 1 0 # 0 1 # def Matrix.identity(n) Matrix.scalar(n, 1) end class << Matrix alias unit identity alias I identity end # # Creates an +n+ by +n+ zero matrix. # Matrix.zero(2) # => 0 0 # 0 0 # def Matrix.zero(n) Matrix.scalar(n, 0) end # # Creates a single-row matrix where the values of that row are as given in # +row+. # Matrix.row_vector([4,5,6]) # => 4 5 6 # def Matrix.row_vector(row) case row when Vector Matrix.rows([row.to_a], false) when Array Matrix.rows([row.dup], false) else Matrix.rows([[row]], false) end end # # Creates a single-column matrix where the values of that column are as given # in +column+. # Matrix.column_vector([4,5,6]) # => 4 # 5 # 6 # def Matrix.column_vector(column) case column when Vector Matrix.columns([column.to_a]) when Array Matrix.columns([column]) else Matrix.columns([[column]]) end end # # This method is used by the other methods that create matrices, and is of no # use to general users. # def initialize(init_method, *argv) self.send(init_method, *argv) end def init_rows(rows, copy) if copy @rows = rows.collect{|row| row.dup} else @rows = rows end self end private :init_rows # # Returns element (+i+,+j+) of the matrix. That is: row +i+, column +j+. # def [](i, j) @rows[i][j] end # # Returns the number of rows. # def row_size @rows.size end # # Returns the number of columns. Note that it is possible to construct a # matrix with uneven columns (e.g. Matrix[ [1,2,3], [4,5] ]), but this is # mathematically unsound. This method uses the first row to determine the # result. # def column_size @rows[0].size end # # Returns row vector number +i+ of the matrix as a Vector (starting at 0 like # an array). When a block is given, the elements of that vector are iterated. # def row(i, &block) # :yield: e if block_given? @rows[i].each(&block) else Vector.elements(@rows[i]) end end # # Returns column vector number +j+ of the matrix as a Vector (starting at 0 # like an array). When a block is given, the elements of that vector are # iterated. # def column(j) # :yield: e if block_given? row_size.times do |i| yield @rows[i][j] end else col = (0 ... row_size).collect {|i| @rows[i][j] } Vector.elements(col, false) end end # # Returns a matrix that is the result of iteration of the given block over all # elements of the matrix. # Matrix[ [1,2], [3,4] ].collect { |i| i**2 } # => 1 4 # 9 16 # def collect(&block) # :yield: e rows = @rows.collect{|row| row.collect(&block)} Matrix.rows(rows, false) end alias map collect # # Returns a section of the matrix. The parameters are either: # * start_row, nrows, start_col, ncols; OR # * col_range, row_range # # Matrix.diagonal(9, 5, -3).minor(0..1, 0..2) # => 9 0 0 # 0 5 0 # def minor(*param) case param.size when 2 from_row = param[0].first size_row = param[0].end - from_row size_row += 1 unless param[0].exclude_end? from_col = param[1].first size_col = param[1].end - from_col size_col += 1 unless param[1].exclude_end? when 4 from_row, size_row, from_col, size_col = param else Matrix.Raise ArgumentError, param.inspect end rows = @rows[from_row, size_row].collect{ |row| row[from_col, size_col] } Matrix.rows(rows, false) end #-- # TESTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ # # Returns +true+ if this is a regular matrix. # def regular? square? and rank == column_size end # # Returns +true+ is this is a singular (i.e. non-regular) matrix. # def singular? not regular? end # # Returns +true+ is this is a square matrix. See note in column_size about this # being unreliable, though. # def square? column_size == row_size end #-- # OBJECT METHODS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ # # Returns +true+ if and only if the two matrices contain equal elements. # def ==(other) return false unless Matrix === other other.compare_by_row_vectors(@rows) end def eql?(other) return false unless Matrix === other other.compare_by_row_vectors(@rows, :eql?) end # # Not really intended for general consumption. # def compare_by_row_vectors(rows, comparison = :==) return false unless @rows.size == rows.size @rows.size.times do |i| return false unless @rows[i].send(comparison, rows[i]) end true end # # Returns a clone of the matrix, so that the contents of each do not reference # identical objects. # def clone Matrix.rows(@rows) end # # Returns a hash-code for the matrix. # def hash @rows.hash end #-- # ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ # # Matrix multiplication. # Matrix[[2,4], [6,8]] * Matrix.identity(2) # => 2 4 # 6 8 # def *(m) # m is matrix or vector or number case(m) when Numeric rows = @rows.collect { |row| row.collect { |e| e * m } } return Matrix.rows(rows, false) when Vector m = Matrix.column_vector(m) r = self * m return r.column(0) when Matrix Matrix.Raise ErrDimensionMismatch if column_size != m.row_size rows = (0 ... row_size).collect {|i| (0 ... m.column_size).collect {|j| (0 ... column_size).inject(0) do |vij, k| vij + self[i, k] * m[k, j] end } } return Matrix.rows(rows, false) else x, y = m.coerce(self) return x * y end end # # Matrix addition. # Matrix.scalar(2,5) + Matrix[[1,0], [-4,7]] # => 6 0 # -4 12 # def +(m) case m when Numeric Matrix.Raise ErrOperationNotDefined, "+" when Vector m = Matrix.column_vector(m) when Matrix else x, y = m.coerce(self) return x + y end Matrix.Raise ErrDimensionMismatch unless row_size == m.row_size and column_size == m.column_size rows = (0 ... row_size).collect {|i| (0 ... column_size).collect {|j| self[i, j] + m[i, j] } } Matrix.rows(rows, false) end # # Matrix subtraction. # Matrix[[1,5], [4,2]] - Matrix[[9,3], [-4,1]] # => -8 2 # 8 1 # def -(m) case m when Numeric Matrix.Raise ErrOperationNotDefined, "-" when Vector m = Matrix.column_vector(m) when Matrix else x, y = m.coerce(self) return x - y end Matrix.Raise ErrDimensionMismatch unless row_size == m.row_size and column_size == m.column_size rows = (0 ... row_size).collect {|i| (0 ... column_size).collect {|j| self[i, j] - m[i, j] } } Matrix.rows(rows, false) end # # Matrix division (multiplication by the inverse). # Matrix[[7,6], [3,9]] / Matrix[[2,9], [3,1]] # => -7 1 # -3 -6 # def /(other) case other when Numeric rows = @rows.collect { |row| row.collect { |e| e / other } } return Matrix.rows(rows, false) when Matrix return self * other.inverse else x, y = other.coerce(self) return x / y end end # # Returns the inverse of the matrix. # Matrix[[1, 2], [2, 1]].inverse # => -1 1 # 0 -1 # def inverse Matrix.Raise ErrDimensionMismatch unless square? Matrix.I(row_size).inverse_from(self) end alias inv inverse # # Not for public consumption? # def inverse_from(src) size = row_size a = src.to_a size.times do |k| i = k akk = a[k][k].abs (k+1 ... size).each do |j| v = a[j][k].abs if v > akk i = j akk = v end end Matrix.Raise ErrNotRegular if akk == 0 if i != k a[i], a[k] = a[k], a[i] @rows[i], @rows[k] = @rows[k], @rows[i] end akk = a[k][k] size.times do |i| next if i == k q = a[i][k] / akk a[i][k] = 0 (k + 1 ... size).each do |j| a[i][j] -= a[k][j] * q end size.times do |j| @rows[i][j] -= @rows[k][j] * q end end (k + 1 ... size).each do |j| a[k][j] /= akk end size.times do |j| @rows[k][j] /= akk end end self end #alias reciprocal inverse # # Matrix exponentiation. Defined for integer powers only. Equivalent to # multiplying the matrix by itself N times. # Matrix[[7,6], [3,9]] ** 2 # => 67 96 # 48 99 # def ** (other) if other.kind_of?(Integer) x = self if other <= 0 x = self.inverse return Matrix.identity(self.column_size) if other == 0 other = -other end z = x n = other - 1 while n != 0 while (div, mod = n.divmod(2) mod == 0) x = x * x n = div end z *= x n -= 1 end z elsif other.kind_of?(Float) || defined?(Rational) && other.kind_of?(Rational) Matrix.Raise ErrOperationNotDefined, "**" else Matrix.Raise ErrOperationNotDefined, "**" end end #-- # MATRIX FUNCTIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ # # Returns the determinant of the matrix. If the matrix is not square, the # result is 0. # Matrix[[7,6], [3,9]].determinant # => 63 # def determinant return 0 unless square? size = row_size a = to_a det = 1 size.times do |k| if (akk = a[k][k]) == 0 i = (k+1 ... size).find {|i| a[i][k] != 0 } return 0 if i.nil? a[i], a[k] = a[k], a[i] akk = a[k][k] det *= -1 end (k + 1 ... size).each do |i| q = a[i][k] / akk (k + 1 ... size).each do |j| a[i][j] -= a[k][j] * q end end det *= akk end det end alias det determinant # # Returns the rank of the matrix. Beware that using Float values, with their # usual lack of precision, can affect the value returned by this method. Use # Rational values instead if this is important to you. # Matrix[[7,6], [3,9]].rank # => 2 # def rank if column_size > row_size a = transpose.to_a a_column_size = row_size a_row_size = column_size else a = to_a a_column_size = column_size a_row_size = row_size end rank = 0 a_column_size.times do |k| if (akk = a[k][k]) == 0 i = (k+1 ... a_row_size).find {|i| a[i][k] != 0 } if i a[i], a[k] = a[k], a[i] akk = a[k][k] else i = (k+1 ... a_column_size).find {|i| a[k][i] != 0 } next if i.nil? (k ... a_column_size).each do |j| a[j][k], a[j][i] = a[j][i], a[j][k] end akk = a[k][k] end end (k + 1 ... a_row_size).each do |i| q = a[i][k] / akk (k + 1... a_column_size).each do |j| a[i][j] -= a[k][j] * q end end rank += 1 end return rank end # # Returns the trace (sum of diagonal elements) of the matrix. # Matrix[[7,6], [3,9]].trace # => 16 # def trace (0...column_size).inject(0) do |tr, i| tr + @rows[i][i] end end alias tr trace # # Returns the transpose of the matrix. # Matrix[[1,2], [3,4], [5,6]] # => 1 2 # 3 4 # 5 6 # Matrix[[1,2], [3,4], [5,6]].transpose # => 1 3 5 # 2 4 6 # def transpose Matrix.columns(@rows) end alias t transpose #-- # CONVERTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ # # FIXME: describe #coerce. # def coerce(other) case other when Numeric return Scalar.new(other), self else raise TypeError, "#{self.class} can't be coerced into #{other.class}" end end # # Returns an array of the row vectors of the matrix. See Vector. # def row_vectors (0 ... row_size).collect {|i| row(i) } end # # Returns an array of the column vectors of the matrix. See Vector. # def column_vectors (0 ... column_size).collect {|i| column(i) } end # # Returns an array of arrays that describe the rows of the matrix. # def to_a @rows.collect{|row| row.dup} end #-- # PRINTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ # # Overrides Object#to_s # def to_s "Matrix[" + @rows.collect{ |row| "[" + row.collect{|e| e.to_s}.join(", ") + "]" }.join(", ")+"]" end # # Overrides Object#inspect # def inspect "Matrix"+@rows.inspect end # Private CLASS class Scalar < Numeric # :nodoc: include ExceptionForMatrix def initialize(value) @value = value end # ARITHMETIC def +(other) case other when Numeric Scalar.new(@value + other) when Vector, Matrix Scalar.Raise WrongArgType, other.class, "Numeric or Scalar" when Scalar Scalar.new(@value + other.value) else x, y = other.coerce(self) x + y end end def -(other) case other when Numeric Scalar.new(@value - other) when Vector, Matrix Scalar.Raise WrongArgType, other.class, "Numeric or Scalar" when Scalar Scalar.new(@value - other.value) else x, y = other.coerce(self) x - y end end def *(other) case other when Numeric Scalar.new(@value * other) when Vector, Matrix other.collect{|e| @value * e} else x, y = other.coerce(self) x * y end end def / (other) case other when Numeric Scalar.new(@value / other) when Vector Scalar.Raise WrongArgType, other.class, "Numeric or Scalar or Matrix" when Matrix self * other.inverse else x, y = other.coerce(self) x / y end end def ** (other) case other when Numeric Scalar.new(@value ** other) when Vector Scalar.Raise WrongArgType, other.class, "Numeric or Scalar or Matrix" when Matrix other.powered_by(self) else x, y = other.coerce(self) x ** y end end end end # # The +Vector+ class represents a mathematical vector, which is useful in its own right, and # also constitutes a row or column of a Matrix. # # == Method Catalogue # # To create a Vector: # * <tt> Vector.[](*array) </tt> # * <tt> Vector.elements(array, copy = true) </tt> # # To access elements: # * <tt> [](i) </tt> # # To enumerate the elements: # * <tt> #each2(v) </tt> # * <tt> #collect2(v) </tt> # # Vector arithmetic: # * <tt> *(x) "is matrix or number" </tt> # * <tt> +(v) </tt> # * <tt> -(v) </tt> # # Vector functions: # * <tt> #inner_product(v) </tt> # * <tt> #collect </tt> # * <tt> #map </tt> # * <tt> #map2(v) </tt> # * <tt> #r </tt> # * <tt> #size </tt> # # Conversion to other data types: # * <tt> #covector </tt> # * <tt> #to_a </tt> # * <tt> #coerce(other) </tt> # # String representations: # * <tt> #to_s </tt> # * <tt> #inspect </tt> # class Vector include ExceptionForMatrix #INSTANCE CREATION private_class_method :new # # Creates a Vector from a list of elements. # Vector[7, 4, ...] # def Vector.[](*array) new(:init_elements, array, copy = false) end # # Creates a vector from an Array. The optional second argument specifies # whether the array itself or a copy is used internally. # def Vector.elements(array, copy = true) new(:init_elements, array, copy) end # # For internal use. # def initialize(method, array, copy) self.send(method, array, copy) end # # For internal use. # def init_elements(array, copy) if copy @elements = array.dup else @elements = array end end # ACCESSING # # Returns element number +i+ (starting at zero) of the vector. # def [](i) @elements[i] end # # Returns the number of elements in the vector. # def size @elements.size end #-- # ENUMERATIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ # # Iterate over the elements of this vector and +v+ in conjunction. # def each2(v) # :yield: e1, e2 Vector.Raise ErrDimensionMismatch if size != v.size size.times do |i| yield @elements[i], v[i] end end # # Collects (as in Enumerable#collect) over the elements of this vector and +v+ # in conjunction. # def collect2(v) # :yield: e1, e2 Vector.Raise ErrDimensionMismatch if size != v.size (0 ... size).collect do |i| yield @elements[i], v[i] end end #-- # COMPARING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ # # Returns +true+ iff the two vectors have the same elements in the same order. # def ==(other) return false unless Vector === other other.compare_by(@elements) end def eql?(other) return false unless Vector === other other.compare_by(@elements, :eql?) end # # For internal use. # def compare_by(elements, comparison = :==) @elements.send(comparison, elements) end # # Return a copy of the vector. # def clone Vector.elements(@elements) end # # Return a hash-code for the vector. # def hash @elements.hash end #-- # ARITHMETIC -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ # # Multiplies the vector by +x+, where +x+ is a number or another vector. # def *(x) case x when Numeric els = @elements.collect{|e| e * x} Vector.elements(els, false) when Matrix Matrix.column_vector(self) * x else s, x = x.coerce(self) s * x end end # # Vector addition. # def +(v) case v when Vector Vector.Raise ErrDimensionMismatch if size != v.size els = collect2(v) { |v1, v2| v1 + v2 } Vector.elements(els, false) when Matrix Matrix.column_vector(self) + v else s, x = v.coerce(self) s + x end end # # Vector subtraction. # def -(v) case v when Vector Vector.Raise ErrDimensionMismatch if size != v.size els = collect2(v) { |v1, v2| v1 - v2 } Vector.elements(els, false) when Matrix Matrix.column_vector(self) - v else s, x = v.coerce(self) s - x end end #-- # VECTOR FUNCTIONS -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ # # Returns the inner product of this vector with the other. # Vector[4,7].inner_product Vector[10,1] => 47 # def inner_product(v) Vector.Raise ErrDimensionMismatch if size != v.size p = 0 each2(v) { |v1, v2| p += v1 * v2 } p end # # Like Array#collect. # def collect(&block) # :yield: e els = @elements.collect(&block) Vector.elements(els, false) end alias map collect # # Like Vector#collect2, but returns a Vector instead of an Array. # def map2(v, &block) # :yield: e1, e2 els = collect2(v, &block) Vector.elements(els, false) end # # Returns the modulus (Pythagorean distance) of the vector. # Vector[5,8,2].r => 9.643650761 # def r Math.sqrt(@elements.inject(0) {|v, e| v + e*e}) end #-- # CONVERTING #++ # # Creates a single-row matrix from this vector. # def covector Matrix.row_vector(self) end # # Returns the elements of the vector in an array. # def to_a @elements.dup end # # FIXME: describe Vector#coerce. # def coerce(other) case other when Numeric return Scalar.new(other), self else raise TypeError, "#{self.class} can't be coerced into #{other.class}" end end #-- # PRINTING -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- #++ # # Overrides Object#to_s # def to_s "Vector[" + @elements.join(", ") + "]" end # # Overrides Object#inspect # def inspect str = "Vector"+@elements.inspect end end # Documentation comments: # - Matrix#coerce and Vector#coerce need to be documented
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/open3.rb
tools/jruby-1.5.1/lib/ruby/1.8/open3.rb
# # = open3.rb: Popen, but with stderr, too # # Author:: Yukihiro Matsumoto # Documentation:: Konrad Meyer # # Open3 gives you access to stdin, stdout, and stderr when running other # programs. # # # Open3 grants you access to stdin, stdout, and stderr when running another # program. Example: # # require "open3" # include Open3 # # stdin, stdout, stderr = popen3('nroff -man') # # Open3.popen3 can also take a block which will receive stdin, stdout and # stderr as parameters. This ensures stdin, stdout and stderr are closed # once the block exits. Example: # # require "open3" # # Open3.popen3('nroff -man') { |stdin, stdout, stderr| ... } # module Open3 # # Open stdin, stdout, and stderr streams and start external executable. # Non-block form: # # require 'open3' # # [stdin, stdout, stderr] = Open3.popen3(cmd) # # Block form: # # require 'open3' # # Open3.popen3(cmd) { |stdin, stdout, stderr| ... } # # The parameter +cmd+ is passed directly to Kernel#exec. # def popen3(*cmd, &p) IO::popen3(*cmd, &p) # pw = IO::pipe # pipe[0] for read, pipe[1] for write # pr = IO::pipe # pe = IO::pipe # # pid = fork{ # # child # fork{ # # grandchild # pw[1].close # STDIN.reopen(pw[0]) # pw[0].close # # pr[0].close # STDOUT.reopen(pr[1]) # pr[1].close # # pe[0].close # STDERR.reopen(pe[1]) # pe[1].close # # exec(*cmd) # } # exit!(0) # } # # pw[0].close # pr[1].close # pe[1].close # Process.waitpid(pid) # pi = [pw[1], pr[0], pe[0]] # pw[1].sync = true # if defined? yield # begin # return yield(*pi) # ensure # pi.each{|p| p.close unless p.closed?} # end # end # pi end module_function :popen3 end if $0 == __FILE__ a = Open3.popen3("nroff -man") Thread.start do while line = gets a[0].print line end a[0].close end while line = a[1].gets print ":", line end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/jcode.rb
tools/jruby-1.5.1/lib/ruby/1.8/jcode.rb
# jcode.rb - ruby code to handle japanese (EUC/SJIS) string if $VERBOSE && $KCODE == "NONE" warn "Warning: $KCODE is NONE." end $vsave, $VERBOSE = $VERBOSE, false class String warn "feel free for some warnings:\n" if $VERBOSE def _regex_quote(str) str.gsub(/(\\[\[\]\-\\])|\\(.)|([\[\]\\])/) do $1 || $2 || '\\' + $3 end end private :_regex_quote PATTERN_SJIS = '[\x81-\x9f\xe0-\xef][\x40-\x7e\x80-\xfc]' PATTERN_EUC = '[\xa1-\xfe][\xa1-\xfe]' PATTERN_UTF8 = '[\xc0-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf]' RE_SJIS = Regexp.new(PATTERN_SJIS, 0, 'n') RE_EUC = Regexp.new(PATTERN_EUC, 0, 'n') RE_UTF8 = Regexp.new(PATTERN_UTF8, 0, 'n') SUCC = {} SUCC['s'] = Hash.new(1) for i in 0 .. 0x3f SUCC['s'][i.chr] = 0x40 - i end SUCC['s']["\x7e"] = 0x80 - 0x7e SUCC['s']["\xfd"] = 0x100 - 0xfd SUCC['s']["\xfe"] = 0x100 - 0xfe SUCC['s']["\xff"] = 0x100 - 0xff SUCC['e'] = Hash.new(1) for i in 0 .. 0xa0 SUCC['e'][i.chr] = 0xa1 - i end SUCC['e']["\xfe"] = 2 SUCC['u'] = Hash.new(1) for i in 0 .. 0x7f SUCC['u'][i.chr] = 0x80 - i end SUCC['u']["\xbf"] = 0x100 - 0xbf def mbchar? case $KCODE[0] when ?s, ?S self =~ RE_SJIS when ?e, ?E self =~ RE_EUC when ?u, ?U self =~ RE_UTF8 else nil end end def end_regexp case $KCODE[0] when ?s, ?S /#{PATTERN_SJIS}$/on when ?e, ?E /#{PATTERN_EUC}$/on when ?u, ?U /#{PATTERN_UTF8}$/on else /.$/on end end alias original_succ! succ! private :original_succ! alias original_succ succ private :original_succ def succ! reg = end_regexp if $KCODE != 'NONE' && self =~ reg succ_table = SUCC[$KCODE[0,1].downcase] begin self[-1] += succ_table[self[-1]] self[-2] += 1 if self[-1] == 0 end while self !~ reg self else original_succ! end end def succ str = self.dup str.succ! or str end private def _expand_ch str a = [] str.scan(/(?:\\(.)|([^\\]))-(?:\\(.)|([^\\]))|(?:\\(.)|(.))/m) do from = $1 || $2 to = $3 || $4 one = $5 || $6 if one a.push one elsif from.length != to.length next elsif from.length == 1 from[0].upto(to[0]) { |c| a.push c.chr } else from.upto(to) { |c| a.push c } end end a end def expand_ch_hash from, to h = {} afrom = _expand_ch(from) ato = _expand_ch(to) afrom.each_with_index do |x,i| h[x] = ato[i] || ato[-1] end h end HashCache = {} TrPatternCache = {} DeletePatternCache = {} SqueezePatternCache = {} public def tr!(from, to) return nil if from == "" return self.delete!(from) if to == "" pattern = TrPatternCache[from] ||= /[#{_regex_quote(from)}]/ if from[0] == ?^ last = /.$/.match(to)[0] self.gsub!(pattern, last) else h = HashCache[from + "1-0" + to] ||= expand_ch_hash(from, to) self.gsub!(pattern) do |c| h[c] end end end def tr(from, to) (str = self.dup).tr!(from, to) or str end def delete!(del) return nil if del == "" self.gsub!(DeletePatternCache[del] ||= /[#{_regex_quote(del)}]+/, '') end def delete(del) (str = self.dup).delete!(del) or str end def squeeze!(del=nil) return nil if del == "" pattern = if del SqueezePatternCache[del] ||= /([#{_regex_quote(del)}])\1+/ else /(.|\n)\1+/ end self.gsub!(pattern, '\1') end def squeeze(del=nil) (str = self.dup).squeeze!(del) or str end def tr_s!(from, to) return self.delete!(from) if to.length == 0 pattern = SqueezePatternCache[from] ||= /([#{_regex_quote(from)}])\1*/ if from[0] == ?^ last = /.$/.match(to)[0] self.gsub!(pattern, last) else h = HashCache[from + "1-0" + to] ||= expand_ch_hash(from, to) self.gsub!(pattern) do h[$1] end end end def tr_s(from, to) (str = self.dup).tr_s!(from,to) or str end def chop! self.gsub!(/(?:.|\r?\n)\z/, '') end def chop (str = self.dup).chop! or str end def jlength self.gsub(/[^\Wa-zA-Z_\d]/, ' ').length end alias jsize jlength def jcount(str) self.delete("^#{str}").jlength end def each_char if block_given? scan(/./m) do |x| yield x end else scan(/./m) end end end $VERBOSE = $vsave
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/gserver.rb
tools/jruby-1.5.1/lib/ruby/1.8/gserver.rb
# # Copyright (C) 2001 John W. Small All Rights Reserved # # Author:: John W. Small # Documentation:: Gavin Sinclair # Licence:: Freeware. # # See the class GServer for documentation. # require "socket" require "thread" # # GServer implements a generic server, featuring thread pool management, # simple logging, and multi-server management. See HttpServer in # <tt>xmlrpc/httpserver.rb</tt> in the Ruby standard library for an example of # GServer in action. # # Any kind of application-level server can be implemented using this class. # It accepts multiple simultaneous connections from clients, up to an optional # maximum number. Several _services_ (i.e. one service per TCP port) can be # run simultaneously, and stopped at any time through the class method # <tt>GServer.stop(port)</tt>. All the threading issues are handled, saving # you the effort. All events are optionally logged, but you can provide your # own event handlers if you wish. # # === Example # # Using GServer is simple. Below we implement a simple time server, run it, # query it, and shut it down. Try this code in +irb+: # # require 'gserver' # # # # # A server that returns the time in seconds since 1970. # # # class TimeServer < GServer # def initialize(port=10001, *args) # super(port, *args) # end # def serve(io) # io.puts(Time.now.to_i) # end # end # # # Run the server with logging enabled (it's a separate thread). # server = TimeServer.new # server.audit = true # Turn logging on. # server.start # # # *** Now point your browser to http://localhost:10001 to see it working *** # # # See if it's still running. # GServer.in_service?(10001) # -> true # server.stopped? # -> false # # # Shut the server down gracefully. # server.shutdown # # # Alternatively, stop it immediately. # GServer.stop(10001) # # or, of course, "server.stop". # # All the business of accepting connections and exception handling is taken # care of. All we have to do is implement the method that actually serves the # client. # # === Advanced # # As the example above shows, the way to use GServer is to subclass it to # create a specific server, overriding the +serve+ method. You can override # other methods as well if you wish, perhaps to collect statistics, or emit # more detailed logging. # # connecting # disconnecting # starting # stopping # # The above methods are only called if auditing is enabled. # # You can also override +log+ and +error+ if, for example, you wish to use a # more sophisticated logging system. # class GServer DEFAULT_HOST = "127.0.0.1" def serve(io) end @@services = {} # Hash of opened ports, i.e. services @@servicesMutex = Mutex.new def GServer.stop(port, host = DEFAULT_HOST) @@servicesMutex.synchronize { @@services[host][port].stop } end def GServer.in_service?(port, host = DEFAULT_HOST) @@services.has_key?(host) and @@services[host].has_key?(port) end def stop @connectionsMutex.synchronize { if @tcpServerThread @tcpServerThread.raise "stop" end } end def stopped? @tcpServerThread == nil end def shutdown @shutdown = true end def connections @connections.size end def join @tcpServerThread.join if @tcpServerThread end attr_reader :port, :host, :maxConnections attr_accessor :stdlog, :audit, :debug def connecting(client) addr = client.peeraddr log("#{self.class.to_s} #{@host}:#{@port} client:#{addr[1]} " + "#{addr[2]}<#{addr[3]}> connect") true end def disconnecting(clientPort) log("#{self.class.to_s} #{@host}:#{@port} " + "client:#{clientPort} disconnect") end protected :connecting, :disconnecting def starting() log("#{self.class.to_s} #{@host}:#{@port} start") end def stopping() log("#{self.class.to_s} #{@host}:#{@port} stop") end protected :starting, :stopping def error(detail) log(detail.backtrace.join("\n")) end def log(msg) if @stdlog @stdlog.puts("[#{Time.new.ctime}] %s" % msg) @stdlog.flush end end protected :error, :log def initialize(port, host = DEFAULT_HOST, maxConnections = 4, stdlog = $stderr, audit = false, debug = false) @tcpServerThread = nil @port = port @host = host @maxConnections = maxConnections @connections = [] @connectionsMutex = Mutex.new @connectionsCV = ConditionVariable.new @stdlog = stdlog @audit = audit @debug = debug end def start(maxConnections = -1) raise "running" if !stopped? @shutdown = false @maxConnections = maxConnections if maxConnections > 0 @@servicesMutex.synchronize { if GServer.in_service?(@port,@host) raise "Port already in use: #{host}:#{@port}!" end @tcpServer = TCPServer.new(@host,@port) @port = @tcpServer.addr[1] @@services[@host] = {} unless @@services.has_key?(@host) @@services[@host][@port] = self; } @tcpServerThread = Thread.new { begin starting if @audit while !@shutdown @connectionsMutex.synchronize { while @connections.size >= @maxConnections @connectionsCV.wait(@connectionsMutex) end } client = @tcpServer.accept @connections << Thread.new(client) { |myClient| begin myPort = myClient.peeraddr[1] serve(myClient) if !@audit or connecting(myClient) rescue => detail error(detail) if @debug ensure begin myClient.close rescue end @connectionsMutex.synchronize { @connections.delete(Thread.current) @connectionsCV.signal } disconnecting(myPort) if @audit end } end rescue => detail error(detail) if @debug ensure begin @tcpServer.close rescue end if @shutdown @connectionsMutex.synchronize { while @connections.size > 0 @connectionsCV.wait(@connectionsMutex) end } else @connections.each { |c| c.raise "stop" } end @tcpServerThread = nil @@servicesMutex.synchronize { @@services[@host].delete(@port) } stopping if @audit end } self end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/sha1.rb
tools/jruby-1.5.1/lib/ruby/1.8/sha1.rb
# just for compatibility; requiring "sha1" is obsoleted # # $RoughId: sha1.rb,v 1.4 2001/07/13 15:38:27 knu Exp $ # $Id: sha1.rb 12007 2007-03-06 10:09:51Z knu $ require 'digest/sha1' class SHA1 < Digest::SHA1 class << self alias orig_new new def new(str = nil) if str orig_new.update(str) else orig_new end end def sha1(*args) new(*args) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rss.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss.rb
# Copyright (c) 2003-2007 Kouhei Sutou. You can redistribute it and/or # modify it under the same terms as Ruby. # # Author:: Kouhei Sutou <kou@cozmixng.org> # Tutorial:: http://www.cozmixng.org/~rwiki/?cmd=view;name=RSS+Parser%3A%3ATutorial.en require 'rss/1.0' require 'rss/2.0' require 'rss/atom' require 'rss/content' require 'rss/dublincore' require 'rss/image' require 'rss/itunes' require 'rss/slash' require 'rss/syndication' require 'rss/taxonomy' require 'rss/trackback' require "rss/maker"
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/complex.rb
tools/jruby-1.5.1/lib/ruby/1.8/complex.rb
# # complex.rb - # $Release Version: 0.5 $ # $Revision: 1.3 $ # $Date: 1998/07/08 10:05:28 $ # by Keiju ISHITSUKA(SHL Japan Inc.) # # ---- # # complex.rb implements the Complex class for complex numbers. Additionally, # some methods in other Numeric classes are redefined or added to allow greater # interoperability with Complex numbers. # # Complex numbers can be created in the following manner: # - <tt>Complex(a, b)</tt> # - <tt>Complex.polar(radius, theta)</tt> # # Additionally, note the following: # - <tt>Complex::I</tt> (the mathematical constant <i>i</i>) # - <tt>Numeric#im</tt> (e.g. <tt>5.im -> 0+5i</tt>) # # The following +Math+ module methods are redefined to handle Complex arguments. # They will work as normal with non-Complex arguments. # sqrt exp cos sin tan log log10 # cosh sinh tanh acos asin atan atan2 acosh asinh atanh # # # Numeric is a built-in class on which Fixnum, Bignum, etc., are based. Here # some methods are added so that all number types can be treated to some extent # as Complex numbers. # class Numeric # # Returns a Complex number <tt>(0,<i>self</i>)</tt>. # def im Complex(0, self) end # # The real part of a complex number, i.e. <i>self</i>. # def real self end # # The imaginary part of a complex number, i.e. 0. # def image 0 end alias imag image # # See Complex#arg. # def arg Math.atan2!(0, self) end alias angle arg # # See Complex#polar. # def polar return abs, arg end # # See Complex#conjugate (short answer: returns <i>self</i>). # def conjugate self end alias conj conjugate end # # Creates a Complex number. +a+ and +b+ should be Numeric. The result will be # <tt>a+bi</tt>. # def Complex(a, b = 0) if b == 0 and (a.kind_of?(Complex) or defined? Complex::Unify) a else Complex.new( a.real-b.imag, a.imag+b.real ) end end # # The complex number class. See complex.rb for an overview. # class Complex < Numeric @RCS_ID='-$Id: complex.rb,v 1.3 1998/07/08 10:05:28 keiju Exp keiju $-' undef step undef div, divmod undef floor, truncate, ceil, round def Complex.generic?(other) # :nodoc: other.kind_of?(Integer) or other.kind_of?(Float) or (defined?(Rational) and other.kind_of?(Rational)) end # # Creates a +Complex+ number in terms of +r+ (radius) and +theta+ (angle). # def Complex.polar(r, theta) Complex(r*Math.cos(theta), r*Math.sin(theta)) end # # Creates a +Complex+ number <tt>a</tt>+<tt>b</tt><i>i</i>. # def Complex.new!(a, b=0) new(a,b) end def initialize(a, b) raise TypeError, "non numeric 1st arg `#{a.inspect}'" if !a.kind_of? Numeric raise TypeError, "`#{a.inspect}' for 1st arg" if a.kind_of? Complex raise TypeError, "non numeric 2nd arg `#{b.inspect}'" if !b.kind_of? Numeric raise TypeError, "`#{b.inspect}' for 2nd arg" if b.kind_of? Complex @real = a @image = b end # # Addition with real or complex number. # def + (other) if other.kind_of?(Complex) re = @real + other.real im = @image + other.image Complex(re, im) elsif Complex.generic?(other) Complex(@real + other, @image) else x , y = other.coerce(self) x + y end end # # Subtraction with real or complex number. # def - (other) if other.kind_of?(Complex) re = @real - other.real im = @image - other.image Complex(re, im) elsif Complex.generic?(other) Complex(@real - other, @image) else x , y = other.coerce(self) x - y end end # # Multiplication with real or complex number. # def * (other) if other.kind_of?(Complex) re = @real*other.real - @image*other.image im = @real*other.image + @image*other.real Complex(re, im) elsif Complex.generic?(other) Complex(@real * other, @image * other) else x , y = other.coerce(self) x * y end end # # Division by real or complex number. # def / (other) if other.kind_of?(Complex) self*other.conjugate/other.abs2 elsif Complex.generic?(other) Complex(@real/other, @image/other) else x, y = other.coerce(self) x/y end end def quo(other) Complex(@real.quo(1), @image.quo(1)) / other end # # Raise this complex number to the given (real or complex) power. # def ** (other) if other == 0 return Complex(1) end if other.kind_of?(Complex) r, theta = polar ore = other.real oim = other.image nr = Math.exp!(ore*Math.log!(r) - oim * theta) ntheta = theta*ore + oim*Math.log!(r) Complex.polar(nr, ntheta) elsif other.kind_of?(Integer) if other > 0 x = self z = x n = other - 1 while n != 0 while (div, mod = n.divmod(2) mod == 0) x = Complex(x.real*x.real - x.image*x.image, 2*x.real*x.image) n = div end z *= x n -= 1 end z else if defined? Rational (Rational(1) / self) ** -other else self ** Float(other) end end elsif Complex.generic?(other) r, theta = polar Complex.polar(r**other, theta*other) else x, y = other.coerce(self) x**y end end # # Remainder after division by a real or complex number. # def % (other) if other.kind_of?(Complex) Complex(@real % other.real, @image % other.image) elsif Complex.generic?(other) Complex(@real % other, @image % other) else x , y = other.coerce(self) x % y end end #-- # def divmod(other) # if other.kind_of?(Complex) # rdiv, rmod = @real.divmod(other.real) # idiv, imod = @image.divmod(other.image) # return Complex(rdiv, idiv), Complex(rmod, rmod) # elsif Complex.generic?(other) # Complex(@real.divmod(other), @image.divmod(other)) # else # x , y = other.coerce(self) # x.divmod(y) # end # end #++ # # Absolute value (aka modulus): distance from the zero point on the complex # plane. # def abs Math.hypot(@real, @image) end # # Square of the absolute value. # def abs2 @real*@real + @image*@image end # # Argument (angle from (1,0) on the complex plane). # def arg Math.atan2!(@image, @real) end alias angle arg # # Returns the absolute value _and_ the argument. # def polar return abs, arg end # # Complex conjugate (<tt>z + z.conjugate = 2 * z.real</tt>). # def conjugate Complex(@real, -@image) end alias conj conjugate # # Compares the absolute values of the two numbers. # def <=> (other) self.abs <=> other.abs end # # Test for numerical equality (<tt>a == a + 0<i>i</i></tt>). # def == (other) if other.kind_of?(Complex) @real == other.real and @image == other.image elsif Complex.generic?(other) @real == other and @image == 0 else other == self end end # # Attempts to coerce +other+ to a Complex number. # def coerce(other) if Complex.generic?(other) return Complex.new!(other), self else super end end # # FIXME # def denominator @real.denominator.lcm(@image.denominator) end # # FIXME # def numerator cd = denominator Complex(@real.numerator*(cd/@real.denominator), @image.numerator*(cd/@image.denominator)) end # # Standard string representation of the complex number. # def to_s if @real != 0 if defined?(Rational) and @image.kind_of?(Rational) and @image.denominator != 1 if @image >= 0 @real.to_s+"+("+@image.to_s+")i" else @real.to_s+"-("+(-@image).to_s+")i" end else if @image >= 0 @real.to_s+"+"+@image.to_s+"i" else @real.to_s+"-"+(-@image).to_s+"i" end end else if defined?(Rational) and @image.kind_of?(Rational) and @image.denominator != 1 "("+@image.to_s+")i" else @image.to_s+"i" end end end # # Returns a hash code for the complex number. # def hash @real.hash ^ @image.hash end # # Returns "<tt>Complex(<i>real</i>, <i>image</i>)</tt>". # def inspect sprintf("Complex(%s, %s)", @real.inspect, @image.inspect) end # # +I+ is the imaginary number. It exists at point (0,1) on the complex plane. # I = Complex(0,1) # The real part of a complex number. attr :real # The imaginary part of a complex number. attr :image alias imag image end class Integer unless defined?(1.numerator) def numerator() self end def denominator() 1 end def gcd(other) min = self.abs max = other.abs while min > 0 tmp = min min = max % min max = tmp end max end def lcm(other) if self.zero? or other.zero? 0 else (self.div(self.gcd(other)) * other).abs end end end end module Math alias sqrt! sqrt alias exp! exp alias log! log alias log10! log10 alias cos! cos alias sin! sin alias tan! tan alias cosh! cosh alias sinh! sinh alias tanh! tanh alias acos! acos alias asin! asin alias atan! atan alias atan2! atan2 alias acosh! acosh alias asinh! asinh alias atanh! atanh # Redefined to handle a Complex argument. def sqrt(z) if Complex.generic?(z) if z >= 0 sqrt!(z) else Complex(0,sqrt!(-z)) end else if z.image < 0 sqrt(z.conjugate).conjugate else r = z.abs x = z.real Complex( sqrt!((r+x)/2), sqrt!((r-x)/2) ) end end end # Redefined to handle a Complex argument. def exp(z) if Complex.generic?(z) exp!(z) else Complex(exp!(z.real) * cos!(z.image), exp!(z.real) * sin!(z.image)) end end # Redefined to handle a Complex argument. def cos(z) if Complex.generic?(z) cos!(z) else Complex(cos!(z.real)*cosh!(z.image), -sin!(z.real)*sinh!(z.image)) end end # Redefined to handle a Complex argument. def sin(z) if Complex.generic?(z) sin!(z) else Complex(sin!(z.real)*cosh!(z.image), cos!(z.real)*sinh!(z.image)) end end # Redefined to handle a Complex argument. def tan(z) if Complex.generic?(z) tan!(z) else sin(z)/cos(z) end end def sinh(z) if Complex.generic?(z) sinh!(z) else Complex( sinh!(z.real)*cos!(z.image), cosh!(z.real)*sin!(z.image) ) end end def cosh(z) if Complex.generic?(z) cosh!(z) else Complex( cosh!(z.real)*cos!(z.image), sinh!(z.real)*sin!(z.image) ) end end def tanh(z) if Complex.generic?(z) tanh!(z) else sinh(z)/cosh(z) end end # Redefined to handle a Complex argument. def log(z) if Complex.generic?(z) and z >= 0 log!(z) else r, theta = z.polar Complex(log!(r.abs), theta) end end # Redefined to handle a Complex argument. def log10(z) if Complex.generic?(z) log10!(z) else log(z)/log!(10) end end def acos(z) if Complex.generic?(z) and z >= -1 and z <= 1 acos!(z) else -1.0.im * log( z + 1.0.im * sqrt(1.0-z*z) ) end end def asin(z) if Complex.generic?(z) and z >= -1 and z <= 1 asin!(z) else -1.0.im * log( 1.0.im * z + sqrt(1.0-z*z) ) end end def atan(z) if Complex.generic?(z) atan!(z) else 1.0.im * log( (1.0.im+z) / (1.0.im-z) ) / 2.0 end end def atan2(y,x) if Complex.generic?(y) and Complex.generic?(x) atan2!(y,x) else -1.0.im * log( (x+1.0.im*y) / sqrt(x*x+y*y) ) end end def acosh(z) if Complex.generic?(z) and z >= 1 acosh!(z) else log( z + sqrt(z*z-1.0) ) end end def asinh(z) if Complex.generic?(z) asinh!(z) else log( z + sqrt(1.0+z*z) ) end end def atanh(z) if Complex.generic?(z) and z >= -1 and z <= 1 atanh!(z) else log( (1.0+z) / (1.0-z) ) / 2.0 end end module_function :sqrt! module_function :sqrt module_function :exp! module_function :exp module_function :log! module_function :log module_function :log10! module_function :log10 module_function :cosh! module_function :cosh module_function :cos! module_function :cos module_function :sinh! module_function :sinh module_function :sin! module_function :sin module_function :tan! module_function :tan module_function :tanh! module_function :tanh module_function :acos! module_function :acos module_function :asin! module_function :asin module_function :atan! module_function :atan module_function :atan2! module_function :atan2 module_function :acosh! module_function :acosh module_function :asinh! module_function :asinh module_function :atanh! module_function :atanh end # Documentation comments: # - source: original (researched from pickaxe) # - a couple of fixme's # - RDoc output for Bignum etc. is a bit short, with nothing but an # (undocumented) alias. No big deal.
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/forwardable.rb
tools/jruby-1.5.1/lib/ruby/1.8/forwardable.rb
# = forwardable - Support for the Delegation Pattern # # $Release Version: 1.1$ # $Revision: 16857 $ # $Date: 2008-06-06 17:05:24 +0900 (Fri, 06 Jun 2008) $ # by Keiju ISHITSUKA(keiju@ishitsuka.com) # # Documentation by James Edward Gray II and Gavin Sinclair # # == Introduction # # This library allows you delegate method calls to an object, on a method by # method basis. You can use Forwardable to setup this delegation at the class # level, or SingleForwardable to handle it at the object level. # # == Notes # # Be advised, RDoc will not detect delegated methods. # # <b>forwardable.rb provides single-method delegation via the # def_delegator() and def_delegators() methods. For full-class # delegation via DelegateClass(), see delegate.rb.</b> # # == Examples # # === Forwardable # # Forwardable makes building a new class based on existing work, with a proper # interface, almost trivial. We want to rely on what has come before obviously, # but with delegation we can take just the methods we need and even rename them # as appropriate. In many cases this is preferable to inheritance, which gives # us the entire old interface, even if much of it isn't needed. # # class Queue # extend Forwardable # # def initialize # @q = [ ] # prepare delegate object # end # # # setup preferred interface, enq() and deq()... # def_delegator :@q, :push, :enq # def_delegator :@q, :shift, :deq # # # support some general Array methods that fit Queues well # def_delegators :@q, :clear, :first, :push, :shift, :size # end # # q = Queue.new # q.enq 1, 2, 3, 4, 5 # q.push 6 # # q.shift # => 1 # while q.size > 0 # puts q.deq # end # # q.enq "Ruby", "Perl", "Python" # puts q.first # q.clear # puts q.first # # <i>Prints:</i> # # 2 # 3 # 4 # 5 # 6 # Ruby # nil # # === SingleForwardable # # printer = String.new # printer.extend SingleForwardable # prepare object for delegation # printer.def_delegator "STDOUT", "puts" # add delegation for STDOUT.puts() # printer.puts "Howdy!" # # <i>Prints:</i> # # Howdy! # # The Forwardable module provides delegation of specified # methods to a designated object, using the methods #def_delegator # and #def_delegators. # # For example, say you have a class RecordCollection which # contains an array <tt>@records</tt>. You could provide the lookup method # #record_number(), which simply calls #[] on the <tt>@records</tt> # array, like this: # # class RecordCollection # extend Forwardable # def_delegator :@records, :[], :record_number # end # # Further, if you wish to provide the methods #size, #<<, and #map, # all of which delegate to @records, this is how you can do it: # # class RecordCollection # # extend Forwardable, but we did that above # def_delegators :@records, :size, :<<, :map # end # # Also see the example at forwardable.rb. # module Forwardable @debug = nil class<<self # force Forwardable to show up in stack backtraces of delegated methods attr_accessor :debug end # # Shortcut for defining multiple delegator methods, but with no # provision for using a different name. The following two code # samples have the same effect: # # def_delegators :@records, :size, :<<, :map # # def_delegator :@records, :size # def_delegator :@records, :<< # def_delegator :@records, :map # # See the examples at Forwardable and forwardable.rb. # def def_instance_delegators(accessor, *methods) for method in methods def_instance_delegator(accessor, method) end end # # Defines a method _method_ which delegates to _obj_ (i.e. it calls # the method of the same name in _obj_). If _new_name_ is # provided, it is used as the name for the delegate method. # # See the examples at Forwardable and forwardable.rb. # def def_instance_delegator(accessor, method, ali = method) accessor = accessor.id2name if accessor.kind_of?(Integer) method = method.id2name if method.kind_of?(Integer) ali = ali.id2name if ali.kind_of?(Integer) module_eval(<<-EOS, "(__FORWARDABLE__)", 1) def #{ali}(*args, &block) begin #{accessor}.__send__(:#{method}, *args, &block) rescue Exception $@.delete_if{|s| /^\\(__FORWARDABLE__\\):/ =~ s} unless Forwardable::debug Kernel::raise end end EOS end alias def_delegators def_instance_delegators alias def_delegator def_instance_delegator end # # The SingleForwardable module provides delegation of specified # methods to a designated object, using the methods #def_delegator # and #def_delegators. This module is similar to Forwardable, but it works on # objects themselves, instead of their defining classes. # # Also see the example at forwardable.rb. # module SingleForwardable # # Shortcut for defining multiple delegator methods, but with no # provision for using a different name. The following two code # samples have the same effect: # # single_forwardable.def_delegators :@records, :size, :<<, :map # # single_forwardable.def_delegator :@records, :size # single_forwardable.def_delegator :@records, :<< # single_forwardable.def_delegator :@records, :map # # See the example at forwardable.rb. # def def_singleton_delegators(accessor, *methods) for method in methods def_singleton_delegator(accessor, method) end end # # Defines a method _method_ which delegates to _obj_ (i.e. it calls # the method of the same name in _obj_). If _new_name_ is # provided, it is used as the name for the delegate method. # # See the example at forwardable.rb. # def def_singleton_delegator(accessor, method, ali = method) accessor = accessor.id2name if accessor.kind_of?(Integer) method = method.id2name if method.kind_of?(Integer) ali = ali.id2name if ali.kind_of?(Integer) instance_eval(<<-EOS, "(__FORWARDABLE__)", 1) def #{ali}(*args, &block) begin #{accessor}.__send__(:#{method}, *args,&block) rescue Exception $@.delete_if{|s| /^\\(__FORWARDABLE__\\):/ =~ s} unless Forwardable::debug Kernel::raise end end EOS end alias def_delegators def_singleton_delegators alias def_delegator def_singleton_delegator end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/shell.rb
tools/jruby-1.5.1/lib/ruby/1.8/shell.rb
# # shell.rb - # $Release Version: 0.6.0 $ # $Revision: 1.8 $ # $Date: 2001/03/19 09:01:11 $ # by Keiju ISHITSUKA(Nippon Rational Inc.) # # -- # # # require "e2mmap" require "thread" require "shell/error" require "shell/command-processor" require "shell/process-controller" class Shell @RCS_ID='-$Id: shell.rb,v 1.8 2001/03/19 09:01:11 keiju Exp keiju $-' include Error extend Exception2MessageMapper # @cascade = true # debug: true -> normal debug # debug: 1 -> eval definition debug # debug: 2 -> detail inspect debug @debug = false @verbose = true class << Shell attr :cascade, true attr :debug, true attr :verbose, true # alias cascade? cascade alias debug? debug alias verbose? verbose @verbose = true def debug=(val) @debug = val @verbose = val if val end def cd(path) sh = new sh.cd path sh end def default_system_path if @default_system_path @default_system_path else ENV["PATH"].split(":") end end def default_system_path=(path) @default_system_path = path end def default_record_separator if @default_record_separator @default_record_separator else $/ end end def default_record_separator=(rs) @default_record_separator = rs end end def initialize @cwd = Dir.pwd @dir_stack = [] @umask = nil @system_path = Shell.default_system_path @record_separator = Shell.default_record_separator @command_processor = CommandProcessor.new(self) @process_controller = ProcessController.new(self) @verbose = Shell.verbose @debug = Shell.debug end attr_reader :system_path def system_path=(path) @system_path = path rehash end attr :umask, true attr :record_separator, true attr :verbose, true attr :debug, true def debug=(val) @debug = val @verbose = val if val end alias verbose? verbose alias debug? debug attr_reader :command_processor attr_reader :process_controller def expand_path(path) File.expand_path(path, @cwd) end # Most Shell commands are defined via CommandProcessor # # Dir related methods # # Shell#cwd/dir/getwd/pwd # Shell#chdir/cd # Shell#pushdir/pushd # Shell#popdir/popd # Shell#mkdir # Shell#rmdir attr :cwd alias dir cwd alias getwd cwd alias pwd cwd attr :dir_stack alias dirs dir_stack # If called as iterator, it restores the current directory when the # block ends. def chdir(path = nil) if iterator? cwd_old = @cwd begin chdir(path) yield ensure chdir(cwd_old) end else path = "~" unless path @cwd = expand_path(path) notify "current dir: #{@cwd}" rehash self end end alias cd chdir def pushdir(path = nil) if iterator? pushdir(path) begin yield ensure popdir end elsif path @dir_stack.push @cwd chdir path notify "dir stack: [#{@dir_stack.join ', '}]" self else if pop = @dir_stack.pop @dir_stack.push @cwd chdir pop notify "dir stack: [#{@dir_stack.join ', '}]" self else Shell.Fail DirStackEmpty end end end alias pushd pushdir def popdir if pop = @dir_stack.pop chdir pop notify "dir stack: [#{@dir_stack.join ', '}]" self else Shell.Fail DirStackEmpty end end alias popd popdir # # process management # def jobs @process_controller.jobs end def kill(sig, command) @process_controller.kill_job(sig, command) end # # command definitions # def Shell.def_system_command(command, path = command) CommandProcessor.def_system_command(command, path) end def Shell.undef_system_command(command) CommandProcessor.undef_system_command(command) end def Shell.alias_command(ali, command, *opts, &block) CommandProcessor.alias_command(ali, command, *opts, &block) end def Shell.unalias_command(ali) CommandProcessor.unalias_command(ali) end def Shell.install_system_commands(pre = "sys_") CommandProcessor.install_system_commands(pre) end # def inspect if debug.kind_of?(Integer) && debug > 2 super else to_s end end def self.notify(*opts, &block) Thread.exclusive do if opts[-1].kind_of?(String) yorn = verbose? else yorn = opts.pop end return unless yorn _head = true print opts.collect{|mes| mes = mes.dup yield mes if iterator? if _head _head = false "shell: " + mes else " " + mes end }.join("\n")+"\n" end end CommandProcessor.initialize CommandProcessor.run_config end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/shellwords.rb
tools/jruby-1.5.1/lib/ruby/1.8/shellwords.rb
# # shellwords.rb: Manipulates strings a la UNIX Bourne shell # # # This module manipulates strings according to the word parsing rules # of the UNIX Bourne shell. # # The shellwords() function was originally a port of shellwords.pl, # but modified to conform to POSIX / SUSv3 (IEEE Std 1003.1-2001). # # Authors: # - Wakou Aoyama # - Akinori MUSHA <knu@iDaemons.org> # # Contact: # - Akinori MUSHA <knu@iDaemons.org> (current maintainer) # module Shellwords # # Splits a string into an array of tokens in the same way the UNIX # Bourne shell does. # # argv = Shellwords.split('here are "two words"') # argv #=> ["here", "are", "two words"] # # +String#shellsplit+ is a shorthand for this function. # # argv = 'here are "two words"'.shellsplit # argv #=> ["here", "are", "two words"] # def shellsplit(line) line = String.new(line) rescue raise(ArgumentError, "Argument must be a string") line.lstrip! words = [] until line.empty? field = '' loop do if line.sub!(/\A"(([^"\\]|\\.)*)"/, '') then snippet = $1.gsub(/\\(.)/, '\1') elsif line =~ /\A"/ then raise ArgumentError, "Unmatched double quote: #{line}" elsif line.sub!(/\A'([^']*)'/, '') then snippet = $1 elsif line =~ /\A'/ then raise ArgumentError, "Unmatched single quote: #{line}" elsif line.sub!(/\A\\(.)?/, '') then snippet = $1 || '\\' elsif line.sub!(/\A([^\s\\'"]+)/, '') then snippet = $1 else line.lstrip! break end field.concat(snippet) end words.push(field) end words end alias shellwords shellsplit module_function :shellsplit, :shellwords class << self alias split shellsplit end # # Escapes a string so that it can be safely used in a Bourne shell # command line. # # Note that a resulted string should be used unquoted and is not # intended for use in double quotes nor in single quotes. # # open("| grep #{Shellwords.escape(pattern)} file") { |pipe| # # ... # } # # +String#shellescape+ is a shorthand for this function. # # open("| grep #{pattern.shellescape} file") { |pipe| # # ... # } # def shellescape(str) # An empty argument will be skipped, so return empty quotes. return "''" if str.empty? str = str.dup # Process as a single byte sequence because not all shell # implementations are multibyte aware. str.gsub!(/([^A-Za-z0-9_\-.,:\/@\n])/n, "\\\\\\1") # A LF cannot be escaped with a backslash because a backslash + LF # combo is regarded as line continuation and simply ignored. str.gsub!(/\n/, "'\n'") return str end module_function :shellescape class << self alias escape shellescape end # # Builds a command line string from an argument list +array+ joining # all elements escaped for Bourne shell and separated by a space. # # open('|' + Shellwords.join(['grep', pattern, *files])) { |pipe| # # ... # } # # +Array#shelljoin+ is a shorthand for this function. # # open('|' + ['grep', pattern, *files].shelljoin) { |pipe| # # ... # } # def shelljoin(array) array.map { |arg| shellescape(arg) }.join(' ') end module_function :shelljoin class << self alias join shelljoin end end class String # # call-seq: # str.shellsplit => array # # Splits +str+ into an array of tokens in the same way the UNIX # Bourne shell does. See +Shellwords::shellsplit+ for details. # def shellsplit Shellwords.split(self) end # # call-seq: # str.shellescape => string # # Escapes +str+ so that it can be safely used in a Bourne shell # command line. See +Shellwords::shellescape+ for details. # def shellescape Shellwords.escape(self) end end class Array # # call-seq: # array.shelljoin => string # # Builds a command line string from an argument list +array+ joining # all elements escaped for Bourne shell and separated by a space. # See +Shellwords::shelljoin+ for details. # def shelljoin Shellwords.join(self) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/pathname.rb
tools/jruby-1.5.1/lib/ruby/1.8/pathname.rb
# # = pathname.rb # # Object-Oriented Pathname Class # # Author:: Tanaka Akira <akr@m17n.org> # Documentation:: Author and Gavin Sinclair # # For documentation, see class Pathname. # # <tt>pathname.rb</tt> is distributed with Ruby since 1.8.0. # # # == Pathname # # Pathname represents a pathname which locates a file in a filesystem. # The pathname depends on OS: Unix, Windows, etc. # Pathname library works with pathnames of local OS. # However non-Unix pathnames are supported experimentally. # # It does not represent the file itself. # A Pathname can be relative or absolute. It's not until you try to # reference the file that it even matters whether the file exists or not. # # Pathname is immutable. It has no method for destructive update. # # The value of this class is to manipulate file path information in a neater # way than standard Ruby provides. The examples below demonstrate the # difference. *All* functionality from File, FileTest, and some from Dir and # FileUtils is included, in an unsurprising way. It is essentially a facade for # all of these, and more. # # == Examples # # === Example 1: Using Pathname # # require 'pathname' # p = Pathname.new("/usr/bin/ruby") # size = p.size # 27662 # isdir = p.directory? # false # dir = p.dirname # Pathname:/usr/bin # base = p.basename # Pathname:ruby # dir, base = p.split # [Pathname:/usr/bin, Pathname:ruby] # data = p.read # p.open { |f| _ } # p.each_line { |line| _ } # # === Example 2: Using standard Ruby # # p = "/usr/bin/ruby" # size = File.size(p) # 27662 # isdir = File.directory?(p) # false # dir = File.dirname(p) # "/usr/bin" # base = File.basename(p) # "ruby" # dir, base = File.split(p) # ["/usr/bin", "ruby"] # data = File.read(p) # File.open(p) { |f| _ } # File.foreach(p) { |line| _ } # # === Example 3: Special features # # p1 = Pathname.new("/usr/lib") # Pathname:/usr/lib # p2 = p1 + "ruby/1.8" # Pathname:/usr/lib/ruby/1.8 # p3 = p1.parent # Pathname:/usr # p4 = p2.relative_path_from(p3) # Pathname:lib/ruby/1.8 # pwd = Pathname.pwd # Pathname:/home/gavin # pwd.absolute? # true # p5 = Pathname.new "." # Pathname:. # p5 = p5 + "music/../articles" # Pathname:music/../articles # p5.cleanpath # Pathname:articles # p5.realpath # Pathname:/home/gavin/articles # p5.children # [Pathname:/home/gavin/articles/linux, ...] # # == Breakdown of functionality # # === Core methods # # These methods are effectively manipulating a String, because that's all a path # is. Except for #mountpoint?, #children, and #realpath, they don't access the # filesystem. # # - + # - #join # - #parent # - #root? # - #absolute? # - #relative? # - #relative_path_from # - #each_filename # - #cleanpath # - #realpath # - #children # - #mountpoint? # # === File status predicate methods # # These methods are a facade for FileTest: # - #blockdev? # - #chardev? # - #directory? # - #executable? # - #executable_real? # - #exist? # - #file? # - #grpowned? # - #owned? # - #pipe? # - #readable? # - #world_readable? # - #readable_real? # - #setgid? # - #setuid? # - #size # - #size? # - #socket? # - #sticky? # - #symlink? # - #writable? # - #world_writable? # - #writable_real? # - #zero? # # === File property and manipulation methods # # These methods are a facade for File: # - #atime # - #ctime # - #mtime # - #chmod(mode) # - #lchmod(mode) # - #chown(owner, group) # - #lchown(owner, group) # - #fnmatch(pattern, *args) # - #fnmatch?(pattern, *args) # - #ftype # - #make_link(old) # - #open(*args, &block) # - #readlink # - #rename(to) # - #stat # - #lstat # - #make_symlink(old) # - #truncate(length) # - #utime(atime, mtime) # - #basename(*args) # - #dirname # - #extname # - #expand_path(*args) # - #split # # === Directory methods # # These methods are a facade for Dir: # - Pathname.glob(*args) # - Pathname.getwd / Pathname.pwd # - #rmdir # - #entries # - #each_entry(&block) # - #mkdir(*args) # - #opendir(*args) # # === IO # # These methods are a facade for IO: # - #each_line(*args, &block) # - #read(*args) # - #readlines(*args) # - #sysopen(*args) # # === Utilities # # These methods are a mixture of Find, FileUtils, and others: # - #find(&block) # - #mkpath # - #rmtree # - #unlink / #delete # # # == Method documentation # # As the above section shows, most of the methods in Pathname are facades. The # documentation for these methods generally just says, for instance, "See # FileTest.writable?", as you should be familiar with the original method # anyway, and its documentation (e.g. through +ri+) will contain more # information. In some cases, a brief description will follow. # class Pathname # :stopdoc: if RUBY_VERSION < "1.9" TO_PATH = :to_str else # to_path is implemented so Pathname objects are usable with File.open, etc. TO_PATH = :to_path end # :startdoc: # # Create a Pathname object from the given String (or String-like object). # If +path+ contains a NUL character (<tt>\0</tt>), an ArgumentError is raised. # def initialize(path) path = path.__send__(TO_PATH) if path.respond_to? TO_PATH @path = path.dup if /\0/ =~ @path raise ArgumentError, "pathname contains \\0: #{@path.inspect}" end self.taint if @path.tainted? end def freeze() super; @path.freeze; self end def taint() super; @path.taint; self end def untaint() super; @path.untaint; self end # # Compare this pathname with +other+. The comparison is string-based. # Be aware that two different paths (<tt>foo.txt</tt> and <tt>./foo.txt</tt>) # can refer to the same file. # def ==(other) return false unless Pathname === other other.to_s == @path end alias === == alias eql? == # Provides for comparing pathnames, case-sensitively. def <=>(other) return nil unless Pathname === other @path.tr('/', "\0") <=> other.to_s.tr('/', "\0") end def hash # :nodoc: @path.hash end # Return the path as a String. def to_s @path.dup end # to_path is implemented so Pathname objects are usable with File.open, etc. alias_method TO_PATH, :to_s def inspect # :nodoc: "#<#{self.class}:#{@path}>" end # Return a pathname which is substituted by String#sub. def sub(pattern, *rest, &block) if block path = @path.sub(pattern, *rest) {|*args| begin old = Thread.current[:pathname_sub_matchdata] Thread.current[:pathname_sub_matchdata] = $~ eval("$~ = Thread.current[:pathname_sub_matchdata]", block.binding) ensure Thread.current[:pathname_sub_matchdata] = old end yield *args } else path = @path.sub(pattern, *rest) end self.class.new(path) end if File::ALT_SEPARATOR SEPARATOR_PAT = /[#{Regexp.quote File::ALT_SEPARATOR}#{Regexp.quote File::SEPARATOR}]/ else SEPARATOR_PAT = /#{Regexp.quote File::SEPARATOR}/ end # chop_basename(path) -> [pre-basename, basename] or nil def chop_basename(path) base = File.basename(path) if /\A#{SEPARATOR_PAT}?\z/ =~ base return nil else return path[0, path.rindex(base)], base end end private :chop_basename # split_names(path) -> prefix, [name, ...] def split_names(path) names = [] while r = chop_basename(path) path, basename = r names.unshift basename end return path, names end private :split_names def prepend_prefix(prefix, relpath) if relpath.empty? File.dirname(prefix) elsif /#{SEPARATOR_PAT}/ =~ prefix prefix = File.dirname(prefix) prefix = File.join(prefix, "") if File.basename(prefix + 'a') != 'a' prefix + relpath else prefix + relpath end end private :prepend_prefix # Returns clean pathname of +self+ with consecutive slashes and useless dots # removed. The filesystem is not accessed. # # If +consider_symlink+ is +true+, then a more conservative algorithm is used # to avoid breaking symbolic linkages. This may retain more <tt>..</tt> # entries than absolutely necessary, but without accessing the filesystem, # this can't be avoided. See #realpath. # def cleanpath(consider_symlink=false) if consider_symlink cleanpath_conservative else cleanpath_aggressive end end # # Clean the path simply by resolving and removing excess "." and ".." entries. # Nothing more, nothing less. # def cleanpath_aggressive path = @path names = [] pre = path while r = chop_basename(pre) pre, base = r case base when '.' when '..' names.unshift base else if names[0] == '..' names.shift else names.unshift base end end end if /#{SEPARATOR_PAT}/o =~ File.basename(pre) names.shift while names[0] == '..' end self.class.new(prepend_prefix(pre, File.join(*names))) end private :cleanpath_aggressive # has_trailing_separator?(path) -> bool def has_trailing_separator?(path) if r = chop_basename(path) pre, basename = r pre.length + basename.length < path.length else false end end private :has_trailing_separator? # add_trailing_separator(path) -> path def add_trailing_separator(path) if File.basename(path + 'a') == 'a' path else File.join(path, "") # xxx: Is File.join is appropriate to add separator? end end private :add_trailing_separator def del_trailing_separator(path) if r = chop_basename(path) pre, basename = r pre + basename elsif /#{SEPARATOR_PAT}+\z/o =~ path $` + File.dirname(path)[/#{SEPARATOR_PAT}*\z/o] else path end end private :del_trailing_separator def cleanpath_conservative path = @path names = [] pre = path while r = chop_basename(pre) pre, base = r names.unshift base if base != '.' end if /#{SEPARATOR_PAT}/o =~ File.basename(pre) names.shift while names[0] == '..' end if names.empty? self.class.new(File.dirname(pre)) else if names.last != '..' && File.basename(path) == '.' names << '.' end result = prepend_prefix(pre, File.join(*names)) if /\A(?:\.|\.\.)\z/ !~ names.last && has_trailing_separator?(path) self.class.new(add_trailing_separator(result)) else self.class.new(result) end end end private :cleanpath_conservative def realpath_rec(prefix, unresolved, h) resolved = [] until unresolved.empty? n = unresolved.shift if n == '.' next elsif n == '..' resolved.pop else path = prepend_prefix(prefix, File.join(*(resolved + [n]))) if h.include? path if h[path] == :resolving raise Errno::ELOOP.new(path) else prefix, *resolved = h[path] end else # This check is JRuby-specific for accessing files inside a jar if File.symlink?(path) h[path] = :resolving link_prefix, link_names = split_names(File.readlink(path)) if link_prefix == '' prefix, *resolved = h[path] = realpath_rec(prefix, resolved + link_names, h) else prefix, *resolved = h[path] = realpath_rec(link_prefix, link_names, h) end else resolved << n h[path] = [prefix, *resolved] end end end end return prefix, *resolved end private :realpath_rec # # Returns a real (absolute) pathname of +self+ in the actual filesystem. # The real pathname doesn't contain symlinks or useless dots. # # No arguments should be given; the old behaviour is *obsoleted*. # def realpath path = @path prefix, names = split_names(path) if prefix == '' prefix, names2 = split_names(Dir.pwd) names = names2 + names end prefix, *names = realpath_rec(prefix, names, {}) self.class.new(prepend_prefix(prefix, File.join(*names))) end # #parent returns the parent directory. # # This is same as <tt>self + '..'</tt>. def parent self + '..' end # #mountpoint? returns +true+ if <tt>self</tt> points to a mountpoint. def mountpoint? begin stat1 = self.lstat stat2 = self.parent.lstat stat1.dev == stat2.dev && stat1.ino == stat2.ino || stat1.dev != stat2.dev rescue Errno::ENOENT false end end # # #root? is a predicate for root directories. I.e. it returns +true+ if the # pathname consists of consecutive slashes. # # It doesn't access actual filesystem. So it may return +false+ for some # pathnames which points to roots such as <tt>/usr/..</tt>. # def root? !!(chop_basename(@path) == nil && /#{SEPARATOR_PAT}/o =~ @path) end # Predicate method for testing whether a path is absolute. # It returns +true+ if the pathname begins with a slash. def absolute? !relative? end # The opposite of #absolute? def relative? path = @path while r = chop_basename(path) path, basename = r end # enebo: mild hack for windows drive letters. Any kook trying # to create a relative path that starts like 'c:/' will be in trouble # so it is not the best solution... path == '' && @path !~ /\A[a-zA-Z]:/ end # # Iterates over each component of the path. # # Pathname.new("/usr/bin/ruby").each_filename {|filename| ... } # # yields "usr", "bin", and "ruby". # def each_filename # :yield: filename prefix, names = split_names(@path) names.each {|filename| yield filename } nil end # Iterates over and yields a new Pathname object # for each element in the given path in descending order. # # Pathname.new('/path/to/some/file.rb').descend {|v| p v} # #<Pathname:/> # #<Pathname:/path> # #<Pathname:/path/to> # #<Pathname:/path/to/some> # #<Pathname:/path/to/some/file.rb> # # Pathname.new('path/to/some/file.rb').descend {|v| p v} # #<Pathname:path> # #<Pathname:path/to> # #<Pathname:path/to/some> # #<Pathname:path/to/some/file.rb> # # It doesn't access actual filesystem. # # This method is available since 1.8.5. # def descend vs = [] ascend {|v| vs << v } vs.reverse_each {|v| yield v } nil end # Iterates over and yields a new Pathname object # for each element in the given path in ascending order. # # Pathname.new('/path/to/some/file.rb').ascend {|v| p v} # #<Pathname:/path/to/some/file.rb> # #<Pathname:/path/to/some> # #<Pathname:/path/to> # #<Pathname:/path> # #<Pathname:/> # # Pathname.new('path/to/some/file.rb').ascend {|v| p v} # #<Pathname:path/to/some/file.rb> # #<Pathname:path/to/some> # #<Pathname:path/to> # #<Pathname:path> # # It doesn't access actual filesystem. # # This method is available since 1.8.5. # def ascend path = @path yield self while r = chop_basename(path) path, name = r break if path.empty? yield self.class.new(del_trailing_separator(path)) end end # # Pathname#+ appends a pathname fragment to this one to produce a new Pathname # object. # # p1 = Pathname.new("/usr") # Pathname:/usr # p2 = p1 + "bin/ruby" # Pathname:/usr/bin/ruby # p3 = p1 + "/etc/passwd" # Pathname:/etc/passwd # # This method doesn't access the file system; it is pure string manipulation. # def +(other) other = Pathname.new(other) unless Pathname === other Pathname.new(plus(@path, other.to_s)) end def plus(path1, path2) # -> path prefix2 = path2 index_list2 = [] basename_list2 = [] while r2 = chop_basename(prefix2) prefix2, basename2 = r2 index_list2.unshift prefix2.length basename_list2.unshift basename2 end return path2 if prefix2 != '' prefix1 = path1 while true while !basename_list2.empty? && basename_list2.first == '.' index_list2.shift basename_list2.shift end break unless r1 = chop_basename(prefix1) prefix1, basename1 = r1 next if basename1 == '.' if basename1 == '..' || basename_list2.empty? || basename_list2.first != '..' prefix1 = prefix1 + basename1 break end index_list2.shift basename_list2.shift end r1 = chop_basename(prefix1) if !r1 && /#{SEPARATOR_PAT}/o =~ File.basename(prefix1) while !basename_list2.empty? && basename_list2.first == '..' index_list2.shift basename_list2.shift end end if !basename_list2.empty? suffix2 = path2[index_list2.first..-1] r1 ? File.join(prefix1, suffix2) : prefix1 + suffix2 else r1 ? prefix1 : File.dirname(prefix1) end end private :plus # # Pathname#join joins pathnames. # # <tt>path0.join(path1, ..., pathN)</tt> is the same as # <tt>path0 + path1 + ... + pathN</tt>. # def join(*args) args.unshift self result = args.pop result = Pathname.new(result) unless Pathname === result return result if result.absolute? args.reverse_each {|arg| arg = Pathname.new(arg) unless Pathname === arg result = arg + result return result if result.absolute? } result end # # Returns the children of the directory (files and subdirectories, not # recursive) as an array of Pathname objects. By default, the returned # pathnames will have enough information to access the files. If you set # +with_directory+ to +false+, then the returned pathnames will contain the # filename only. # # For example: # p = Pathname("/usr/lib/ruby/1.8") # p.children # # -> [ Pathname:/usr/lib/ruby/1.8/English.rb, # Pathname:/usr/lib/ruby/1.8/Env.rb, # Pathname:/usr/lib/ruby/1.8/abbrev.rb, ... ] # p.children(false) # # -> [ Pathname:English.rb, Pathname:Env.rb, Pathname:abbrev.rb, ... ] # # Note that the result never contain the entries <tt>.</tt> and <tt>..</tt> in # the directory because they are not children. # # This method has existed since 1.8.1. # def children(with_directory=true) with_directory = false if @path == '.' result = [] Dir.foreach(@path) {|e| next if e == '.' || e == '..' if with_directory result << self.class.new(File.join(@path, e)) else result << self.class.new(e) end } result end # # #relative_path_from returns a relative path from the argument to the # receiver. If +self+ is absolute, the argument must be absolute too. If # +self+ is relative, the argument must be relative too. # # #relative_path_from doesn't access the filesystem. It assumes no symlinks. # # ArgumentError is raised when it cannot find a relative path. # # This method has existed since 1.8.1. # def relative_path_from(base_directory) dest_directory = self.cleanpath.to_s base_directory = base_directory.cleanpath.to_s dest_prefix = dest_directory dest_names = [] while r = chop_basename(dest_prefix) dest_prefix, basename = r dest_names.unshift basename if basename != '.' end base_prefix = base_directory base_names = [] while r = chop_basename(base_prefix) base_prefix, basename = r base_names.unshift basename if basename != '.' end if dest_prefix != base_prefix raise ArgumentError, "different prefix: #{dest_prefix.inspect} and #{base_directory.inspect}" end while !dest_names.empty? && !base_names.empty? && dest_names.first == base_names.first dest_names.shift base_names.shift end if base_names.include? '..' raise ArgumentError, "base_directory has ..: #{base_directory.inspect}" end base_names.fill('..') relpath_names = base_names + dest_names if relpath_names.empty? Pathname.new('.') else Pathname.new(File.join(*relpath_names)) end end end class Pathname # * IO * # # #each_line iterates over the line in the file. It yields a String object # for each line. # # This method has existed since 1.8.1. # def each_line(*args, &block) # :yield: line IO.foreach(@path, *args, &block) end # Pathname#foreachline is *obsoleted* at 1.8.1. Use #each_line. def foreachline(*args, &block) warn "Pathname#foreachline is obsoleted. Use Pathname#each_line." each_line(*args, &block) end # See <tt>IO.read</tt>. Returns all the bytes from the file, or the first +N+ # if specified. def read(*args) IO.read(@path, *args) end # See <tt>IO.readlines</tt>. Returns all the lines from the file. def readlines(*args) IO.readlines(@path, *args) end # See <tt>IO.sysopen</tt>. def sysopen(*args) IO.sysopen(@path, *args) end end class Pathname # * File * # See <tt>File.atime</tt>. Returns last access time. def atime() File.atime(@path) end # See <tt>File.ctime</tt>. Returns last (directory entry, not file) change time. def ctime() File.ctime(@path) end # See <tt>File.mtime</tt>. Returns last modification time. def mtime() File.mtime(@path) end # See <tt>File.chmod</tt>. Changes permissions. def chmod(mode) File.chmod(mode, @path) end # See <tt>File.lchmod</tt>. def lchmod(mode) File.lchmod(mode, @path) end # See <tt>File.chown</tt>. Change owner and group of file. def chown(owner, group) File.chown(owner, group, @path) end # See <tt>File.lchown</tt>. def lchown(owner, group) File.lchown(owner, group, @path) end # See <tt>File.fnmatch</tt>. Return +true+ if the receiver matches the given # pattern. def fnmatch(pattern, *args) File.fnmatch(pattern, @path, *args) end # See <tt>File.fnmatch?</tt> (same as #fnmatch). def fnmatch?(pattern, *args) File.fnmatch?(pattern, @path, *args) end # See <tt>File.ftype</tt>. Returns "type" of file ("file", "directory", # etc). def ftype() File.ftype(@path) end # See <tt>File.link</tt>. Creates a hard link. def make_link(old) File.link(old, @path) end # See <tt>File.open</tt>. Opens the file for reading or writing. def open(*args, &block) # :yield: file File.open(@path, *args, &block) end # See <tt>File.readlink</tt>. Read symbolic link. def readlink() self.class.new(File.readlink(@path)) end # See <tt>File.rename</tt>. Rename the file. def rename(to) File.rename(@path, to) end # See <tt>File.stat</tt>. Returns a <tt>File::Stat</tt> object. def stat() File.stat(@path) end # See <tt>File.lstat</tt>. def lstat() File.lstat(@path) end # See <tt>File.symlink</tt>. Creates a symbolic link. def make_symlink(old) File.symlink(old, @path) end # See <tt>File.truncate</tt>. Truncate the file to +length+ bytes. def truncate(length) File.truncate(@path, length) end # See <tt>File.utime</tt>. Update the access and modification times. def utime(atime, mtime) File.utime(atime, mtime, @path) end # See <tt>File.basename</tt>. Returns the last component of the path. def basename(*args) self.class.new(File.basename(@path, *args)) end # See <tt>File.dirname</tt>. Returns all but the last component of the path. def dirname() self.class.new(File.dirname(@path)) end # See <tt>File.extname</tt>. Returns the file's extension. def extname() File.extname(@path) end # See <tt>File.expand_path</tt>. def expand_path(*args) self.class.new(File.expand_path(@path, *args)) end # See <tt>File.split</tt>. Returns the #dirname and the #basename in an # Array. def split() File.split(@path).map {|f| self.class.new(f) } end # Pathname#link is confusing and *obsoleted* because the receiver/argument # order is inverted to corresponding system call. def link(old) warn 'Pathname#link is obsoleted. Use Pathname#make_link.' File.link(old, @path) end # Pathname#symlink is confusing and *obsoleted* because the receiver/argument # order is inverted to corresponding system call. def symlink(old) warn 'Pathname#symlink is obsoleted. Use Pathname#make_symlink.' File.symlink(old, @path) end end class Pathname # * FileTest * # See <tt>FileTest.blockdev?</tt>. def blockdev?() FileTest.blockdev?(@path) end # See <tt>FileTest.chardev?</tt>. def chardev?() FileTest.chardev?(@path) end # See <tt>FileTest.executable?</tt>. def executable?() FileTest.executable?(@path) end # See <tt>FileTest.executable_real?</tt>. def executable_real?() FileTest.executable_real?(@path) end # See <tt>FileTest.exist?</tt>. def exist?() FileTest.exist?(@path) end # See <tt>FileTest.grpowned?</tt>. def grpowned?() FileTest.grpowned?(@path) end # See <tt>FileTest.directory?</tt>. def directory?() FileTest.directory?(@path) end # See <tt>FileTest.file?</tt>. def file?() FileTest.file?(@path) end # See <tt>FileTest.pipe?</tt>. def pipe?() FileTest.pipe?(@path) end # See <tt>FileTest.socket?</tt>. def socket?() FileTest.socket?(@path) end # See <tt>FileTest.owned?</tt>. def owned?() FileTest.owned?(@path) end # See <tt>FileTest.readable?</tt>. def readable?() FileTest.readable?(@path) end # See <tt>FileTest.world_readable?</tt>. def world_readable?() FileTest.world_readable?(@path) end # See <tt>FileTest.readable_real?</tt>. def readable_real?() FileTest.readable_real?(@path) end # See <tt>FileTest.setuid?</tt>. def setuid?() FileTest.setuid?(@path) end # See <tt>FileTest.setgid?</tt>. def setgid?() FileTest.setgid?(@path) end # See <tt>FileTest.size</tt>. def size() FileTest.size(@path) end # See <tt>FileTest.size?</tt>. def size?() FileTest.size?(@path) end # See <tt>FileTest.sticky?</tt>. def sticky?() FileTest.sticky?(@path) end # See <tt>FileTest.symlink?</tt>. def symlink?() FileTest.symlink?(@path) end # See <tt>FileTest.writable?</tt>. def writable?() FileTest.writable?(@path) end # See <tt>FileTest.world_writable?</tt>. def world_writable?() FileTest.world_writable?(@path) end # See <tt>FileTest.writable_real?</tt>. def writable_real?() FileTest.writable_real?(@path) end # See <tt>FileTest.zero?</tt>. def zero?() FileTest.zero?(@path) end end class Pathname # * Dir * # See <tt>Dir.glob</tt>. Returns or yields Pathname objects. def Pathname.glob(*args) # :yield: p if block_given? Dir.glob(*args) {|f| yield self.new(f) } else Dir.glob(*args).map {|f| self.new(f) } end end # See <tt>Dir.getwd</tt>. Returns the current working directory as a Pathname. def Pathname.getwd() self.new(Dir.getwd) end class << self; alias pwd getwd end # Pathname#chdir is *obsoleted* at 1.8.1. def chdir(&block) warn "Pathname#chdir is obsoleted. Use Dir.chdir." Dir.chdir(@path, &block) end # Pathname#chroot is *obsoleted* at 1.8.1. def chroot warn "Pathname#chroot is obsoleted. Use Dir.chroot." Dir.chroot(@path) end # Return the entries (files and subdirectories) in the directory, each as a # Pathname object. def entries() Dir.entries(@path).map {|f| self.class.new(f) } end # Iterates over the entries (files and subdirectories) in the directory. It # yields a Pathname object for each entry. # # This method has existed since 1.8.1. def each_entry(&block) # :yield: p Dir.foreach(@path) {|f| yield self.class.new(f) } end # Pathname#dir_foreach is *obsoleted* at 1.8.1. def dir_foreach(*args, &block) warn "Pathname#dir_foreach is obsoleted. Use Pathname#each_entry." each_entry(*args, &block) end # See <tt>Dir.mkdir</tt>. Create the referenced directory. def mkdir(*args) Dir.mkdir(@path, *args) end # See <tt>Dir.rmdir</tt>. Remove the referenced directory. def rmdir() Dir.rmdir(@path) end # See <tt>Dir.open</tt>. def opendir(&block) # :yield: dir Dir.open(@path, &block) end end class Pathname # * Find * # # Pathname#find is an iterator to traverse a directory tree in a depth first # manner. It yields a Pathname for each file under "this" directory. # # Since it is implemented by <tt>find.rb</tt>, <tt>Find.prune</tt> can be used # to control the traverse. # # If +self+ is <tt>.</tt>, yielded pathnames begin with a filename in the # current directory, not <tt>./</tt>. # def find(&block) # :yield: p require 'find' if @path == '.' Find.find(@path) {|f| yield self.class.new(f.sub(%r{\A\./}, '')) } else Find.find(@path) {|f| yield self.class.new(f) } end end end class Pathname # * FileUtils * # See <tt>FileUtils.mkpath</tt>. Creates a full path, including any # intermediate directories that don't yet exist. def mkpath require 'fileutils' FileUtils.mkpath(@path) nil end # See <tt>FileUtils.rm_r</tt>. Deletes a directory and all beneath it. def rmtree # The name "rmtree" is borrowed from File::Path of Perl. # File::Path provides "mkpath" and "rmtree". require 'fileutils' FileUtils.rm_r(@path) nil end end class Pathname # * mixed * # Removes a file or directory, using <tt>File.unlink</tt> or # <tt>Dir.unlink</tt> as necessary. def unlink() begin Dir.unlink @path rescue Errno::ENOTDIR File.unlink @path end end alias delete unlink # This method is *obsoleted* at 1.8.1. Use #each_line or #each_entry. def foreach(*args, &block) warn "Pathname#foreach is obsoleted. Use each_line or each_entry." if FileTest.directory? @path # For polymorphism between Dir.foreach and IO.foreach, # Pathname#foreach doesn't yield Pathname object. Dir.foreach(@path, *args, &block) else IO.foreach(@path, *args, &block) end end end module Kernel # create a pathname object. # # This method is available since 1.8.5. def Pathname(path) # :doc: Pathname.new(path) end private :Pathname end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/getopts.rb
tools/jruby-1.5.1/lib/ruby/1.8/getopts.rb
# # getopts.rb - # $Release Version: $ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Yasuo OHBA(SHL Japan Inc. Technology Dept.) # # -- # this is obsolete; use getoptlong # # 2000-03-21 # modified by Minero Aoki <aamine@dp.u-netsurf.ne.jp> # # 2002-03-05 # rewritten by Akinori MUSHA <knu@ruby-lang.org> # warn "Warning:#{caller[0].sub(/:in `.*'\z/, '')}: getopts is deprecated after Ruby 1.8.1; use optparse instead" if caller[0] and $VERBOSE $RCS_ID=%q$Header$ # getopts is obsolete. Use GetoptLong. def getopts(single_options, *options) boolopts = {} valopts = {} # # set defaults # single_options.scan(/.:?/) do |opt| if opt.size == 1 boolopts[opt] = false else valopts[opt[0, 1]] = nil end end if single_options options.each do |arg| opt, val = arg.split(':', 2) if val valopts[opt] = val.empty? ? nil : val else boolopts[opt] = false end end # # scan # c = 0 argv = ARGV while arg = argv.shift case arg when /\A--(.*)/ if $1.empty? # xinit -- -bpp 24 break end opt, val = $1.split('=', 2) if opt.size == 1 argv.unshift arg return nil elsif valopts.key? opt # imclean --src +trash valopts[opt] = val || argv.shift or return nil elsif boolopts.key? opt # ruby --verbose boolopts[opt] = true else argv.unshift arg return nil end c += 1 when /\A-(.+)/ opts = $1 until opts.empty? opt = opts.slice!(0, 1) if valopts.key? opt val = opts if val.empty? # ruby -e 'p $:' valopts[opt] = argv.shift or return nil else # cc -ohello ... valopts[opt] = val end c += 1 break elsif boolopts.key? opt boolopts[opt] = true # ruby -h c += 1 else argv.unshift arg return nil end end else argv.unshift arg break end end # # set # $OPT = {} boolopts.each do |opt, val| $OPT[opt] = val sopt = opt.gsub(/[^A-Za-z0-9_]/, '_') eval "$OPT_#{sopt} = val" end valopts.each do |opt, val| $OPT[opt] = val sopt = opt.gsub(/[^A-Za-z0-9_]/, '_') eval "$OPT_#{sopt} = val" end c end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/mkmf.rb
tools/jruby-1.5.1/lib/ruby/1.8/mkmf.rb
enabled=false # uncomment this to play with experimental mkmf support #enabled=true # JRuby does not support mkmf yet, so we fail hard here with a useful message if !enabled warn "WARNING: JRuby does not support native extensions or the `mkmf' library.\n Check http://kenai.com/projects/jruby/pages/Home for alternatives." else # We're missing this in our rbconfig module Config def Config::expand(val, config = CONFIG) val.gsub!(/\$\$|\$\(([^()]+)\)|\$\{([^{}]+)\}/) do |var| if !(v = $1 || $2) '$' elsif key = config[v = v[/\A[^:]+(?=(?::(.*?)=(.*))?\z)/]] pat, sub = $1, $2 config[v] = false Config::expand(key, config) config[v] = key key = key.gsub(/#{Regexp.quote(pat)}(?=\s|\z)/n) {sub} if pat key else var end end val end end # module to create Makefile for extension modules # invoke like: ruby -r mkmf extconf.rb require 'rbconfig' require 'fileutils' require 'shellwords' CONFIG = Config::MAKEFILE_CONFIG ORIG_LIBPATH = ENV['LIB'] CXX_EXT = %w[cc cxx cpp] if /mswin|bccwin|mingw|msdosdjgpp|human|os2/ !~ CONFIG['build_os'] CXX_EXT.concat(%w[C]) end SRC_EXT = %w[c m].concat(CXX_EXT) $static = $config_h = nil $default_static = $static unless defined? $configure_args $configure_args = {} args = CONFIG["configure_args"] if ENV["CONFIGURE_ARGS"] args << " " << ENV["CONFIGURE_ARGS"] end for arg in Shellwords::shellwords(args) arg, val = arg.split('=', 2) next unless arg arg.tr!('_', '-') if arg.sub!(/^(?!--)/, '--') val or next arg.downcase! end next if /^--(?:top|topsrc|src|cur)dir$/ =~ arg $configure_args[arg] = val || true end for arg in ARGV arg, val = arg.split('=', 2) next unless arg arg.tr!('_', '-') if arg.sub!(/^(?!--)/, '--') val or next arg.downcase! end $configure_args[arg] = val || true end end $libdir = CONFIG["libdir"] $rubylibdir = CONFIG["rubylibdir"] $archdir = CONFIG["archdir"] $sitedir = CONFIG["sitedir"] $sitelibdir = CONFIG["sitelibdir"] $sitearchdir = CONFIG["sitearchdir"] $vendordir = CONFIG["vendordir"] $vendorlibdir = CONFIG["vendorlibdir"] $vendorarchdir = CONFIG["vendorarchdir"] $mswin = /mswin/ =~ RUBY_PLATFORM $bccwin = /bccwin/ =~ RUBY_PLATFORM $mingw = /mingw/ =~ RUBY_PLATFORM $cygwin = /cygwin/ =~ RUBY_PLATFORM $human = /human/ =~ RUBY_PLATFORM $netbsd = /netbsd/ =~ RUBY_PLATFORM $os2 = /os2/ =~ RUBY_PLATFORM $beos = /beos/ =~ RUBY_PLATFORM $solaris = /solaris/ =~ RUBY_PLATFORM $dest_prefix_pattern = (File::PATH_SEPARATOR == ';' ? /\A([[:alpha:]]:)?/ : /\A/) # :stopdoc: def config_string(key, config = CONFIG) s = config[key] and !s.empty? and block_given? ? yield(s) : s end def dir_re(dir) Regexp.new('\$(?:\('+dir+'\)|\{'+dir+'\})(?:\$(?:\(target_prefix\)|\{target_prefix\}))?') end INSTALL_DIRS = [ [dir_re('commondir'), "$(RUBYCOMMONDIR)"], [dir_re('sitedir'), "$(RUBYCOMMONDIR)"], [dir_re('vendordir'), "$(RUBYCOMMONDIR)"], [dir_re('rubylibdir'), "$(RUBYLIBDIR)"], [dir_re('archdir'), "$(RUBYARCHDIR)"], [dir_re('sitelibdir'), "$(RUBYLIBDIR)"], [dir_re('vendorlibdir'), "$(RUBYLIBDIR)"], [dir_re('sitearchdir'), "$(RUBYARCHDIR)"], [dir_re('bindir'), "$(BINDIR)"], [dir_re('vendorarchdir'), "$(RUBYARCHDIR)"], ] def install_dirs(target_prefix = nil) if $extout dirs = [ ['BINDIR', '$(extout)/bin'], ['RUBYCOMMONDIR', '$(extout)/common'], ['RUBYLIBDIR', '$(RUBYCOMMONDIR)$(target_prefix)'], ['RUBYARCHDIR', '$(extout)/$(arch)$(target_prefix)'], ['extout', "#$extout"], ['extout_prefix', "#$extout_prefix"], ] elsif $extmk dirs = [ ['BINDIR', '$(bindir)'], ['RUBYCOMMONDIR', '$(rubylibdir)'], ['RUBYLIBDIR', '$(rubylibdir)$(target_prefix)'], ['RUBYARCHDIR', '$(archdir)$(target_prefix)'], ] elsif $configure_args.has_key?('--vendor') dirs = [ ['BINDIR', '$(bindir)'], ['RUBYCOMMONDIR', '$(vendordir)$(target_prefix)'], ['RUBYLIBDIR', '$(vendorlibdir)$(target_prefix)'], ['RUBYARCHDIR', '$(vendorarchdir)$(target_prefix)'], ] else dirs = [ ['BINDIR', '$(bindir)'], ['RUBYCOMMONDIR', '$(sitedir)$(target_prefix)'], ['RUBYLIBDIR', '$(sitelibdir)$(target_prefix)'], ['RUBYARCHDIR', '$(sitearchdir)$(target_prefix)'], ] end dirs << ['target_prefix', (target_prefix ? "/#{target_prefix}" : "")] dirs end def map_dir(dir, map = nil) map ||= INSTALL_DIRS map.inject(dir) {|dir, (orig, new)| dir.gsub(orig, new)} end topdir = File.dirname(libdir = File.dirname(__FILE__)) extdir = File.expand_path("ext", topdir) $extmk = File.expand_path($0)[0, extdir.size+1] == extdir+"/" if not $extmk and File.exist?(($hdrdir = Config::CONFIG["archdir"]) + "/ruby.h") $topdir = $hdrdir elsif File.exist?(($hdrdir = ($top_srcdir ||= topdir)) + "/ruby.h") and File.exist?(($topdir ||= Config::CONFIG["topdir"]) + "/config.h") else abort "mkmf.rb can't find header files for ruby at #{$hdrdir}/ruby.h" end OUTFLAG = CONFIG['OUTFLAG'] CPPOUTFILE = CONFIG['CPPOUTFILE'] CONFTEST_C = "conftest.c" class String # Wraps a string in escaped quotes if it contains whitespace. def quote /\s/ =~ self ? "\"#{self}\"" : "#{self}" end # Generates a string used as cpp macro name. def tr_cpp strip.upcase.tr_s("^A-Z0-9_", "_") end end class Array # Wraps all strings in escaped quotes if they contain whitespace. def quote map {|s| s.quote} end end def rm_f(*files) FileUtils.rm_f(Dir[files.join("\0")]) end # Returns time stamp of the +target+ file if it exists and is newer # than or equal to all of +times+. def modified?(target, times) (t = File.mtime(target)) rescue return nil Array === times or times = [times] t if times.all? {|n| n <= t} end def merge_libs(*libs) libs.inject([]) do |x, y| xy = x & y xn = yn = 0 y = y.inject([]) {|ary, e| ary.last == e ? ary : ary << e} y.each_with_index do |v, yi| if xy.include?(v) xi = [x.index(v), xn].max() x[xi, 1] = y[yn..yi] xn, yn = xi + (yi - yn + 1), yi + 1 end end x.concat(y[yn..-1] || []) end end # This is a custom logging module. It generates an mkmf.log file when you # run your extconf.rb script. This can be useful for debugging unexpected # failures. # # This module and its associated methods are meant for internal use only. # module Logging @log = nil @logfile = 'mkmf.log' @orgerr = $stderr.dup @orgout = $stdout.dup @postpone = 0 @quiet = $extmk def self::open @log ||= File::open(@logfile, 'w') @log.sync = true $stderr.reopen(@log) $stdout.reopen(@log) yield ensure $stderr.reopen(@orgerr) $stdout.reopen(@orgout) end def self::message(*s) @log ||= File::open(@logfile, 'w') @log.sync = true @log.printf(*s) end def self::logfile file @logfile = file if @log and not @log.closed? @log.flush @log.close @log = nil end end def self::postpone tmplog = "mkmftmp#{@postpone += 1}.log" open do log, *save = @log, @logfile, @orgout, @orgerr @log, @logfile, @orgout, @orgerr = nil, tmplog, log, log begin log.print(open {yield}) @log.close File::open(tmplog) {|t| FileUtils.copy_stream(t, log)} ensure @log, @logfile, @orgout, @orgerr = log, *save @postpone -= 1 rm_f tmplog end end end class << self attr_accessor :quiet end end def xsystem command varpat = /\$\((\w+)\)|\$\{(\w+)\}/ if varpat =~ command vars = Hash.new {|h, k| h[k] = ''; ENV[k]} command = command.dup nil while command.gsub!(varpat) {vars[$1||$2]} end Logging::open do puts command.quote system(command) end end def xpopen command, *mode, &block Logging::open do case mode[0] when nil, /^r/ puts "#{command} |" else puts "| #{command}" end IO.popen(command, *mode, &block) end end def log_src(src) src = src.split(/^/) fmt = "%#{src.size.to_s.size}d: %s" Logging::message <<"EOM" checked program was: /* begin */ EOM src.each_with_index {|line, no| Logging::message fmt, no+1, line} Logging::message <<"EOM" /* end */ EOM end def create_tmpsrc(src) src = yield(src) if block_given? src = src.gsub(/[ \t]+$/, '').gsub(/\A\n+|^\n+$/, '').sub(/[^\n]\z/, "\\&\n") open(CONFTEST_C, "wb") do |cfile| cfile.print src end src end def try_do(src, command, &b) src = create_tmpsrc(src, &b) xsystem(command) ensure log_src(src) end def link_command(ldflags, opt="", libpath=$DEFLIBPATH|$LIBPATH) conf = Config::CONFIG.merge('hdrdir' => $hdrdir.quote, 'src' => CONFTEST_C, 'INCFLAGS' => $INCFLAGS, 'CPPFLAGS' => $CPPFLAGS, 'CFLAGS' => "#$CFLAGS", 'ARCH_FLAG' => "#$ARCH_FLAG", 'LDFLAGS' => "#$LDFLAGS #{ldflags}", 'LIBPATH' => libpathflag(libpath), 'LOCAL_LIBS' => "#$LOCAL_LIBS #$libs", 'LIBS' => "#$LIBRUBYARG_STATIC #{opt} #$LIBS") Config::expand(TRY_LINK.dup, conf) end def cc_command(opt="") conf = Config::CONFIG.merge('hdrdir' => $hdrdir.quote, 'srcdir' => $srcdir.quote) Config::expand("$(CC) #$INCFLAGS #$CPPFLAGS #$CFLAGS #$ARCH_FLAG #{opt} -c #{CONFTEST_C}", conf) end def cpp_command(outfile, opt="") conf = Config::CONFIG.merge('hdrdir' => $hdrdir.quote, 'srcdir' => $srcdir.quote) Config::expand("$(CPP) #$INCFLAGS #$CPPFLAGS #$CFLAGS #{opt} #{CONFTEST_C} #{outfile}", conf) end def libpathflag(libpath=$DEFLIBPATH|$LIBPATH) libpath.map{|x| case x when "$(topdir)", /\A\./ LIBPATHFLAG else LIBPATHFLAG+RPATHFLAG end % x.quote }.join end def try_link0(src, opt="", &b) try_do(src, link_command("", opt), &b) end def try_link(src, opt="", &b) try_link0(src, opt, &b) ensure rm_f "conftest*", "c0x32*" end def try_compile(src, opt="", &b) try_do(src, cc_command(opt), &b) ensure rm_f "conftest*" end def try_cpp(src, opt="", &b) try_do(src, cpp_command(CPPOUTFILE, opt), &b) ensure rm_f "conftest*" end def cpp_include(header) if header header = [header] unless header.kind_of? Array header.map {|h| "#include <#{h}>\n"}.join else "" end end def with_cppflags(flags) cppflags = $CPPFLAGS $CPPFLAGS = flags ret = yield ensure $CPPFLAGS = cppflags unless ret end def with_cflags(flags) cflags = $CFLAGS $CFLAGS = flags ret = yield ensure $CFLAGS = cflags unless ret end def with_ldflags(flags) ldflags = $LDFLAGS $LDFLAGS = flags ret = yield ensure $LDFLAGS = ldflags unless ret end def try_static_assert(expr, headers = nil, opt = "", &b) headers = cpp_include(headers) try_compile(<<SRC, opt, &b) #{COMMON_HEADERS} #{headers} /*top*/ int conftest_const[(#{expr}) ? 1 : -1]; SRC end def try_constant(const, headers = nil, opt = "", &b) includes = cpp_include(headers) if CROSS_COMPILING if try_static_assert("#{const} > 0", headers, opt) # positive constant elsif try_static_assert("#{const} < 0", headers, opt) neg = true const = "-(#{const})" elsif try_static_assert("#{const} == 0", headers, opt) return 0 else # not a constant return nil end upper = 1 lower = 0 until try_static_assert("#{const} <= #{upper}", headers, opt) lower = upper upper <<= 1 end return nil unless lower while upper > lower + 1 mid = (upper + lower) / 2 if try_static_assert("#{const} > #{mid}", headers, opt) lower = mid else upper = mid end end upper = -upper if neg return upper else src = %{#{COMMON_HEADERS} #{includes} #include <stdio.h> /*top*/ int conftest_const = (int)(#{const}); int main() {printf("%d\\n", conftest_const); return 0;} } if try_link0(src, opt, &b) xpopen("./conftest") do |f| return Integer(f.gets) end end end nil end def try_func(func, libs, headers = nil, &b) headers = cpp_include(headers) try_link(<<"SRC", libs, &b) or try_link(<<"SRC", libs, &b) #{COMMON_HEADERS} #{headers} /*top*/ int main() { return 0; } int t() { void ((*volatile p)()); p = (void ((*)()))#{func}; return 0; } SRC #{headers} /*top*/ int main() { return 0; } int t() { #{func}(); return 0; } SRC end def try_var(var, headers = nil, &b) headers = cpp_include(headers) try_compile(<<"SRC", &b) #{COMMON_HEADERS} #{headers} /*top*/ int main() { return 0; } int t() { const volatile void *volatile p; p = &(&#{var})[0]; return 0; } SRC end def egrep_cpp(pat, src, opt = "", &b) src = create_tmpsrc(src, &b) xpopen(cpp_command('', opt)) do |f| if Regexp === pat puts(" ruby -ne 'print if #{pat.inspect}'") f.grep(pat) {|l| puts "#{f.lineno}: #{l}" return true } false else puts(" egrep '#{pat}'") begin stdin = $stdin.dup $stdin.reopen(f) system("egrep", pat) ensure $stdin.reopen(stdin) end end end ensure rm_f "conftest*" log_src(src) end # This is used internally by the have_macro? method. def macro_defined?(macro, src, opt = "", &b) src = src.sub(/[^\n]\z/, "\\&\n") try_compile(src + <<"SRC", opt, &b) /*top*/ #ifndef #{macro} # error >>>>>> #{macro} undefined <<<<<< #endif SRC end def try_run(src, opt = "", &b) if try_link0(src, opt, &b) xsystem("./conftest") else nil end ensure rm_f "conftest*" end def install_files(mfile, ifiles, map = nil, srcprefix = nil) ifiles or return ifiles.empty? and return srcprefix ||= '$(srcdir)' Config::expand(srcdir = srcprefix.dup) dirs = [] path = Hash.new {|h, i| h[i] = dirs.push([i])[-1]} ifiles.each do |files, dir, prefix| dir = map_dir(dir, map) prefix &&= %r|\A#{Regexp.quote(prefix)}/?| if /\A\.\// =~ files # install files which are in current working directory. files = files[2..-1] len = nil else # install files which are under the $(srcdir). files = File.join(srcdir, files) len = srcdir.size end f = nil Dir.glob(files) do |f| f[0..len] = "" if len case File.basename(f) when *$NONINSTALLFILES next end d = File.dirname(f) d.sub!(prefix, "") if prefix d = (d.empty? || d == ".") ? dir : File.join(dir, d) f = File.join(srcprefix, f) if len path[d] << f end unless len or f d = File.dirname(files) d.sub!(prefix, "") if prefix d = (d.empty? || d == ".") ? dir : File.join(dir, d) path[d] << files end end dirs end def install_rb(mfile, dest, srcdir = nil) install_files(mfile, [["lib/**/*.rb", dest, "lib"]], nil, srcdir) end def append_library(libs, lib) # :no-doc: format(LIBARG, lib) + " " + libs end def message(*s) unless Logging.quiet and not $VERBOSE printf(*s) $stdout.flush end end # This emits a string to stdout that allows users to see the results of the # various have* and find* methods as they are tested. # # Internal use only. # def checking_for(m, fmt = nil) f = caller[0][/in `(.*)'$/, 1] and f << ": " #` for vim m = "checking #{/\Acheck/ =~ f ? '' : 'for '}#{m}... " message "%s", m a = r = nil Logging::postpone do r = yield a = (fmt ? fmt % r : r ? "yes" : "no") << "\n" "#{f}#{m}-------------------- #{a}\n" end message(a) Logging::message "--------------------\n\n" r end def checking_message(target, place = nil, opt = nil) [["in", place], ["with", opt]].inject("#{target}") do |msg, (pre, noun)| if noun [[:to_str], [:join, ","], [:to_s]].each do |meth, *args| if noun.respond_to?(meth) break noun = noun.send(meth, *args) end end msg << " #{pre} #{noun}" unless noun.empty? end msg end end # :startdoc: # Returns whether or not +macro+ is defined either in the common header # files or within any +headers+ you provide. # # Any options you pass to +opt+ are passed along to the compiler. # def have_macro(macro, headers = nil, opt = "", &b) checking_for checking_message(macro, headers, opt) do macro_defined?(macro, cpp_include(headers), opt, &b) end end # Returns whether or not the given entry point +func+ can be found within # +lib+. If +func+ is nil, the 'main()' entry point is used by default. # If found, it adds the library to list of libraries to be used when linking # your extension. # # If +headers+ are provided, it will include those header files as the # header files it looks in when searching for +func+. # # The real name of the library to be linked can be altered by # '--with-FOOlib' configuration option. # def have_library(lib, func = nil, headers = nil, &b) func = "main" if !func or func.empty? lib = with_config(lib+'lib', lib) checking_for checking_message("#{func}()", LIBARG%lib) do if COMMON_LIBS.include?(lib) true else libs = append_library($libs, lib) if try_func(func, libs, headers, &b) $libs = libs true else false end end end end # Returns whether or not the entry point +func+ can be found within the library # +lib+ in one of the +paths+ specified, where +paths+ is an array of strings. # If +func+ is nil , then the main() function is used as the entry point. # # If +lib+ is found, then the path it was found on is added to the list of # library paths searched and linked against. # def find_library(lib, func, *paths, &b) func = "main" if !func or func.empty? lib = with_config(lib+'lib', lib) paths = paths.collect {|path| path.split(File::PATH_SEPARATOR)}.flatten checking_for "#{func}() in #{LIBARG%lib}" do libpath = $LIBPATH libs = append_library($libs, lib) begin until r = try_func(func, libs, &b) or paths.empty? $LIBPATH = libpath | [paths.shift] end if r $libs = libs libpath = nil end ensure $LIBPATH = libpath if libpath end r end end # Returns whether or not the function +func+ can be found in the common # header files, or within any +headers+ that you provide. If found, a # macro is passed as a preprocessor constant to the compiler using the # function name, in uppercase, prepended with 'HAVE_'. # # For example, if have_func('foo') returned true, then the HAVE_FOO # preprocessor macro would be passed to the compiler. # def have_func(func, headers = nil, &b) checking_for checking_message("#{func}()", headers) do if try_func(func, $libs, headers, &b) $defs.push(format("-DHAVE_%s", func.tr_cpp)) true else false end end end # Returns whether or not the variable +var+ can be found in the common # header files, or within any +headers+ that you provide. If found, a # macro is passed as a preprocessor constant to the compiler using the # variable name, in uppercase, prepended with 'HAVE_'. # # For example, if have_var('foo') returned true, then the HAVE_FOO # preprocessor macro would be passed to the compiler. # def have_var(var, headers = nil, &b) checking_for checking_message(var, headers) do if try_var(var, headers, &b) $defs.push(format("-DHAVE_%s", var.tr_cpp)) true else false end end end # Returns whether or not the given +header+ file can be found on your system. # If found, a macro is passed as a preprocessor constant to the compiler using # the header file name, in uppercase, prepended with 'HAVE_'. # # For example, if have_header('foo.h') returned true, then the HAVE_FOO_H # preprocessor macro would be passed to the compiler. # def have_header(header, &b) checking_for header do if try_cpp(cpp_include(header), &b) $defs.push(format("-DHAVE_%s", header.tr("a-z./\055", "A-Z___"))) true else false end end end # Instructs mkmf to search for the given +header+ in any of the +paths+ # provided, and returns whether or not it was found in those paths. # # If the header is found then the path it was found on is added to the list # of included directories that are sent to the compiler (via the -I switch). # def find_header(header, *paths) message = checking_message(header, paths) header = cpp_include(header) checking_for message do if try_cpp(header) true else found = false paths.each do |dir| opt = "-I#{dir}".quote if try_cpp(header, opt) $INCFLAGS << " " << opt found = true break end end found end end end # Returns whether or not the struct of type +type+ contains +member+. If # it does not, or the struct type can't be found, then false is returned. You # may optionally specify additional +headers+ in which to look for the struct # (in addition to the common header files). # # If found, a macro is passed as a preprocessor constant to the compiler using # the member name, in uppercase, prepended with 'HAVE_ST_'. # # For example, if have_struct_member('struct foo', 'bar') returned true, then the # HAVE_ST_BAR preprocessor macro would be passed to the compiler. # def have_struct_member(type, member, headers = nil, &b) checking_for checking_message("#{type}.#{member}", headers) do if try_compile(<<"SRC", &b) #{COMMON_HEADERS} #{cpp_include(headers)} /*top*/ int main() { return 0; } int s = (char *)&((#{type}*)0)->#{member} - (char *)0; SRC $defs.push(format("-DHAVE_ST_%s", member.tr_cpp)) true else false end end end def try_type(type, headers = nil, opt = "", &b) if try_compile(<<"SRC", opt, &b) #{COMMON_HEADERS} #{cpp_include(headers)} /*top*/ typedef #{type} conftest_type; int conftestval[sizeof(conftest_type)?1:-1]; SRC $defs.push(format("-DHAVE_TYPE_%s", type.tr_cpp)) true else false end end # Returns whether or not the static type +type+ is defined. You may # optionally pass additional +headers+ to check against in addition to the # common header files. # # You may also pass additional flags to +opt+ which are then passed along to # the compiler. # # If found, a macro is passed as a preprocessor constant to the compiler using # the type name, in uppercase, prepended with 'HAVE_TYPE_'. # # For example, if have_type('foo') returned true, then the HAVE_TYPE_FOO # preprocessor macro would be passed to the compiler. # def have_type(type, headers = nil, opt = "", &b) checking_for checking_message(type, headers, opt) do try_type(type, headers, opt, &b) end end # Returns where the static type +type+ is defined. # # You may also pass additional flags to +opt+ which are then passed along to # the compiler. # # See also +have_type+. # def find_type(type, opt, *headers, &b) opt ||= "" fmt = "not found" def fmt.%(x) x ? x.respond_to?(:join) ? x.join(",") : x : self end checking_for checking_message(type, nil, opt), fmt do headers.find do |h| try_type(type, h, opt, &b) end end end def try_const(const, headers = nil, opt = "", &b) const, type = *const if try_compile(<<"SRC", opt, &b) #{COMMON_HEADERS} #{cpp_include(headers)} /*top*/ typedef #{type || 'int'} conftest_type; conftest_type conftestval = #{type ? '' : '(int)'}#{const}; SRC $defs.push(format("-DHAVE_CONST_%s", const.tr_cpp)) true else false end end # Returns whether or not the constant +const+ is defined. You may # optionally pass the +type+ of +const+ as <code>[const, type]</code>, # like as: # # have_const(%w[PTHREAD_MUTEX_INITIALIZER pthread_mutex_t], "pthread.h") # # You may also pass additional +headers+ to check against in addition # to the common header files, and additional flags to +opt+ which are # then passed along to the compiler. # # If found, a macro is passed as a preprocessor constant to the compiler using # the type name, in uppercase, prepended with 'HAVE_CONST_'. # # For example, if have_const('foo') returned true, then the HAVE_CONST_FOO # preprocessor macro would be passed to the compiler. # def have_const(const, headers = nil, opt = "", &b) checking_for checking_message([*const].compact.join(' '), headers, opt) do try_const(const, headers, opt, &b) end end # Returns the size of the given +type+. You may optionally specify additional # +headers+ to search in for the +type+. # # If found, a macro is passed as a preprocessor constant to the compiler using # the type name, in uppercase, prepended with 'SIZEOF_', followed by the type # name, followed by '=X' where 'X' is the actual size. # # For example, if check_sizeof('mystruct') returned 12, then the # SIZEOF_MYSTRUCT=12 preprocessor macro would be passed to the compiler. # def check_sizeof(type, headers = nil, &b) expr = "sizeof(#{type})" fmt = "%d" def fmt.%(x) x ? super : "failed" end checking_for checking_message("size of #{type}", headers), fmt do if size = try_constant(expr, headers, &b) $defs.push(format("-DSIZEOF_%s=%d", type.tr_cpp, size)) size end end end # :stopdoc: # Used internally by the what_type? method to determine if +type+ is a scalar # pointer. def scalar_ptr_type?(type, member = nil, headers = nil, &b) try_compile(<<"SRC", &b) # pointer #{COMMON_HEADERS} #{cpp_include(headers)} /*top*/ volatile #{type} conftestval; int main() { return 0; } int t() {return (int)(1-*(conftestval#{member ? ".#{member}" : ""}));} SRC end # Used internally by the what_type? method to determine if +type+ is a scalar # pointer. def scalar_type?(type, member = nil, headers = nil, &b) try_compile(<<"SRC", &b) # pointer #{COMMON_HEADERS} #{cpp_include(headers)} /*top*/ volatile #{type} conftestval; int main() { return 0; } int t() {return (int)(1-(conftestval#{member ? ".#{member}" : ""}));} SRC end def what_type?(type, member = nil, headers = nil, &b) m = "#{type}" name = type if member m << "." << member name = "(((#{type} *)0)->#{member})" end fmt = "seems %s" def fmt.%(x) x ? super : "unknown" end checking_for checking_message(m, headers), fmt do if scalar_ptr_type?(type, member, headers, &b) if try_static_assert("sizeof(*#{name}) == 1", headers) "string" end elsif scalar_type?(type, member, headers, &b) if try_static_assert("sizeof(#{name}) > sizeof(long)", headers) "long long" elsif try_static_assert("sizeof(#{name}) > sizeof(int)", headers) "long" elsif try_static_assert("sizeof(#{name}) > sizeof(short)", headers) "int" elsif try_static_assert("sizeof(#{name}) > 1", headers) "short" else "char" end end end end # This method is used internally by the find_executable method. # # Internal use only. # def find_executable0(bin, path = nil) ext = config_string('EXEEXT') if File.expand_path(bin) == bin return bin if File.executable?(bin) ext and File.executable?(file = bin + ext) and return file return nil end if path ||= ENV['PATH'] path = path.split(File::PATH_SEPARATOR) else path = %w[/usr/local/bin /usr/ucb /usr/bin /bin] end file = nil path.each do |dir| return file if File.executable?(file = File.join(dir, bin)) return file if ext and File.executable?(file << ext) end nil end # :startdoc: # Searches for the executable +bin+ on +path+. The default path is your # PATH environment variable. If that isn't defined, it will resort to # searching /usr/local/bin, /usr/ucb, /usr/bin and /bin. # # If found, it will return the full path, including the executable name, # of where it was found. # # Note that this method does not actually affect the generated Makefile. # def find_executable(bin, path = nil) checking_for checking_message(bin, path) do find_executable0(bin, path) end end # :stopdoc: def arg_config(config, *defaults, &block) $arg_config << [config, *defaults] defaults << nil if !block and defaults.empty? $configure_args.fetch(config.tr('_', '-'), *defaults, &block) end # :startdoc: # Tests for the presence of a --with-<tt>config</tt> or --without-<tt>config</tt> # option. Returns true if the with option is given, false if the without # option is given, and the default value otherwise. # # This can be useful for adding custom definitions, such as debug information. # # Example: # # if with_config("debug") # $defs.push("-DOSSL_DEBUG") unless $defs.include? "-DOSSL_DEBUG" # end # def with_config(config, *defaults) config = config.sub(/^--with[-_]/, '') val = arg_config("--with-"+config) do if arg_config("--without-"+config) false elsif block_given? yield(config, *defaults) else break *defaults end end case val when "yes" true when "no" false else val end end # Tests for the presence of an --enable-<tt>config</tt> or # --disable-<tt>config</tt> option. Returns true if the enable option is given, # false if the disable option is given, and the default value otherwise. # # This can be useful for adding custom definitions, such as debug information. # # Example: # # if enable_config("debug") # $defs.push("-DOSSL_DEBUG") unless $defs.include? "-DOSSL_DEBUG" # end # def enable_config(config, *defaults) if arg_config("--enable-"+config) true elsif arg_config("--disable-"+config) false elsif block_given? yield(config, *defaults) else return *defaults end end # Generates a header file consisting of the various macro definitions generated # by other methods such as have_func and have_header. These are then wrapped in # a custom #ifndef based on the +header+ file name, which defaults to # 'extconf.h'. # # For example: # # # extconf.rb # require 'mkmf' # have_func('realpath') # have_header('sys/utime.h') # create_header # create_makefile('foo') # # The above script would generate the following extconf.h file: # # #ifndef EXTCONF_H # #define EXTCONF_H # #define HAVE_REALPATH 1 # #define HAVE_SYS_UTIME_H 1 # #endif # # Given that the create_header method generates a file based on definitions # set earlier in your extconf.rb file, you will probably want to make this # one of the last methods you call in your script. # def create_header(header = "extconf.h") message "creating %s\n", header sym = header.tr("a-z./\055", "A-Z___") hdr = ["#ifndef #{sym}\n#define #{sym}\n"] for line in $defs case line when /^-D([^=]+)(?:=(.*))?/ hdr << "#define #$1 #{$2 ? Shellwords.shellwords($2)[0] : 1}\n" when /^-U(.*)/ hdr << "#undef #$1\n" end end hdr << "#endif\n" hdr = hdr.join unless (IO.read(header) == hdr rescue false) open(header, "w") do |hfile| hfile.write(hdr) end end $extconf_h = header end # Sets a +target+ name that the user can then use to configure various 'with' # options with on the command line by using that name. For example, if the # target is set to "foo", then the user could use the --with-foo-dir command # line option. # # You may pass along additional 'include' or 'lib' defaults via the +idefault+ # and +ldefault+ parameters, respectively. # # Note that dir_config only adds to the list of places to search for libraries # and include files. It does not link the libraries into your application. # def dir_config(target, idefault=nil, ldefault=nil) if dir = with_config(target + "-dir", (idefault unless ldefault)) defaults = Array === dir ? dir : dir.split(File::PATH_SEPARATOR) idefault = ldefault = nil end idir = with_config(target + "-include", idefault) $arg_config.last[1] ||= "${#{target}-dir}/include" ldir = with_config(target + "-lib", ldefault) $arg_config.last[1] ||= "${#{target}-dir}/lib" idirs = idir ? Array === idir ? idir : idir.split(File::PATH_SEPARATOR) : [] if defaults idirs.concat(defaults.collect {|dir| dir + "/include"}) idir = ([idir] + idirs).compact.join(File::PATH_SEPARATOR) end unless idirs.empty? idirs.collect! {|dir| "-I" + dir} idirs -= Shellwords.shellwords($CPPFLAGS) unless idirs.empty? $CPPFLAGS = (idirs.quote << $CPPFLAGS).join(" ") end end ldirs = ldir ? Array === ldir ? ldir : ldir.split(File::PATH_SEPARATOR) : [] if defaults ldirs.concat(defaults.collect {|dir| dir + "/lib"}) ldir = ([ldir] + ldirs).compact.join(File::PATH_SEPARATOR) end $LIBPATH = ldirs | $LIBPATH [idir, ldir] end # :stopdoc: # Handles meta information about installed libraries. Uses your platform's # pkg-config program if it has one. def pkg_config(pkg)
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
true
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/pstore.rb
tools/jruby-1.5.1/lib/ruby/1.8/pstore.rb
# = PStore -- Transactional File Storage for Ruby Objects # # pstore.rb - # originally by matz # documentation by Kev Jackson and James Edward Gray II # # See PStore for documentation. require "fileutils" require "digest/md5" # # PStore implements a file based persistence mechanism based on a Hash. User # code can store hierarchies of Ruby objects (values) into the data store file # by name (keys). An object hierarchy may be just a single object. User code # may later read values back from the data store or even update data, as needed. # # The transactional behavior ensures that any changes succeed or fail together. # This can be used to ensure that the data store is not left in a transitory # state, where some values were updated but others were not. # # Behind the scenes, Ruby objects are stored to the data store file with # Marshal. That carries the usual limitations. Proc objects cannot be # marshalled, for example. # # == Usage example: # # require "pstore" # # # a mock wiki object... # class WikiPage # def initialize( page_name, author, contents ) # @page_name = page_name # @revisions = Array.new # # add_revision(author, contents) # end # # attr_reader :page_name # # def add_revision( author, contents ) # @revisions << { :created => Time.now, # :author => author, # :contents => contents } # end # # def wiki_page_references # [@page_name] + @revisions.last[:contents].scan(/\b(?:[A-Z]+[a-z]+){2,}/) # end # # # ... # end # # # create a new page... # home_page = WikiPage.new( "HomePage", "James Edward Gray II", # "A page about the JoysOfDocumentation..." ) # # # then we want to update page data and the index together, or not at all... # wiki = PStore.new("wiki_pages.pstore") # wiki.transaction do # begin transaction; do all of this or none of it # # store page... # wiki[home_page.page_name] = home_page # # ensure that an index has been created... # wiki[:wiki_index] ||= Array.new # # update wiki index... # wiki[:wiki_index].push(*home_page.wiki_page_references) # end # commit changes to wiki data store file # # ### Some time later... ### # # # read wiki data... # wiki.transaction(true) do # begin read-only transaction, no changes allowed # wiki.roots.each do |data_root_name| # p data_root_name # p wiki[data_root_name] # end # end # class PStore binmode = defined?(File::BINARY) ? File::BINARY : 0 RDWR_ACCESS = File::RDWR | File::CREAT | binmode RD_ACCESS = File::RDONLY | binmode WR_ACCESS = File::WRONLY | File::CREAT | File::TRUNC | binmode # The error type thrown by all PStore methods. class Error < StandardError end # # To construct a PStore object, pass in the _file_ path where you would like # the data to be stored. # def initialize(file) dir = File::dirname(file) unless File::directory? dir raise PStore::Error, format("directory %s does not exist", dir) end if File::exist? file and not File::readable? file raise PStore::Error, format("file %s not readable", file) end @transaction = false @filename = file @abort = false end # Raises PStore::Error if the calling code is not in a PStore#transaction. def in_transaction raise PStore::Error, "not in transaction" unless @transaction end # # Raises PStore::Error if the calling code is not in a PStore#transaction or # if the code is in a read-only PStore#transaction. # def in_transaction_wr() in_transaction() raise PStore::Error, "in read-only transaction" if @rdonly end private :in_transaction, :in_transaction_wr # # Retrieves a value from the PStore file data, by _name_. The hierarchy of # Ruby objects stored under that root _name_ will be returned. # # *WARNING*: This method is only valid in a PStore#transaction. It will # raise PStore::Error if called at any other time. # def [](name) in_transaction @table[name] end # # This method is just like PStore#[], save that you may also provide a # _default_ value for the object. In the event the specified _name_ is not # found in the data store, your _default_ will be returned instead. If you do # not specify a default, PStore::Error will be raised if the object is not # found. # # *WARNING*: This method is only valid in a PStore#transaction. It will # raise PStore::Error if called at any other time. # def fetch(name, default=PStore::Error) in_transaction unless @table.key? name if default==PStore::Error raise PStore::Error, format("undefined root name `%s'", name) else return default end end @table[name] end # # Stores an individual Ruby object or a hierarchy of Ruby objects in the data # store file under the root _name_. Assigning to a _name_ already in the data # store clobbers the old data. # # == Example: # # require "pstore" # # store = PStore.new("data_file.pstore") # store.transaction do # begin transaction # # load some data into the store... # store[:single_object] = "My data..." # store[:obj_heirarchy] = { "Kev Jackson" => ["rational.rb", "pstore.rb"], # "James Gray" => ["erb.rb", "pstore.rb"] } # end # commit changes to data store file # # *WARNING*: This method is only valid in a PStore#transaction and it cannot # be read-only. It will raise PStore::Error if called at any other time. # def []=(name, value) in_transaction_wr() @table[name] = value end # # Removes an object hierarchy from the data store, by _name_. # # *WARNING*: This method is only valid in a PStore#transaction and it cannot # be read-only. It will raise PStore::Error if called at any other time. # def delete(name) in_transaction_wr() @table.delete name end # # Returns the names of all object hierarchies currently in the store. # # *WARNING*: This method is only valid in a PStore#transaction. It will # raise PStore::Error if called at any other time. # def roots in_transaction @table.keys end # # Returns true if the supplied _name_ is currently in the data store. # # *WARNING*: This method is only valid in a PStore#transaction. It will # raise PStore::Error if called at any other time. # def root?(name) in_transaction @table.key? name end # Returns the path to the data store file. def path @filename end # # Ends the current PStore#transaction, committing any changes to the data # store immediately. # # == Example: # # require "pstore" # # store = PStore.new("data_file.pstore") # store.transaction do # begin transaction # # load some data into the store... # store[:one] = 1 # store[:two] = 2 # # store.commit # end transaction here, committing changes # # store[:three] = 3 # this change is never reached # end # # *WARNING*: This method is only valid in a PStore#transaction. It will # raise PStore::Error if called at any other time. # def commit in_transaction @abort = false throw :pstore_abort_transaction end # # Ends the current PStore#transaction, discarding any changes to the data # store. # # == Example: # # require "pstore" # # store = PStore.new("data_file.pstore") # store.transaction do # begin transaction # store[:one] = 1 # this change is not applied, see below... # store[:two] = 2 # this change is not applied, see below... # # store.abort # end transaction here, discard all changes # # store[:three] = 3 # this change is never reached # end # # *WARNING*: This method is only valid in a PStore#transaction. It will # raise PStore::Error if called at any other time. # def abort in_transaction @abort = true throw :pstore_abort_transaction end # # Opens a new transaction for the data store. Code executed inside a block # passed to this method may read and write data to and from the data store # file. # # At the end of the block, changes are committed to the data store # automatically. You may exit the transaction early with a call to either # PStore#commit or PStore#abort. See those methods for details about how # changes are handled. Raising an uncaught Exception in the block is # equivalent to calling PStore#abort. # # If _read_only_ is set to +true+, you will only be allowed to read from the # data store during the transaction and any attempts to change the data will # raise a PStore::Error. # # Note that PStore does not support nested transactions. # def transaction(read_only=false) # :yields: pstore raise PStore::Error, "nested transaction" if @transaction begin @rdonly = read_only @abort = false @transaction = true value = nil new_file = @filename + ".new" content = nil unless read_only file = File.open(@filename, RDWR_ACCESS) file.flock(File::LOCK_EX) commit_new(file) if FileTest.exist?(new_file) content = file.read() else begin file = File.open(@filename, RD_ACCESS) file.flock(File::LOCK_SH) content = (File.open(new_file, RD_ACCESS) {|n| n.read} rescue file.read()) rescue Errno::ENOENT content = "" end end if content != "" @table = load(content) if !read_only size = content.size md5 = Digest::MD5.digest(content) end else @table = {} end content = nil # unreference huge data begin catch(:pstore_abort_transaction) do value = yield(self) end rescue Exception @abort = true raise ensure if !read_only and !@abort tmp_file = @filename + ".tmp" content = dump(@table) if !md5 || size != content.size || md5 != Digest::MD5.digest(content) File.open(tmp_file, WR_ACCESS) {|t| t.write(content)} File.rename(tmp_file, new_file) commit_new(file) end content = nil # unreference huge data end end ensure @table = nil @transaction = false file.close if file end value end # This method is just a wrapped around Marshal.dump. def dump(table) # :nodoc: Marshal::dump(table) end # This method is just a wrapped around Marshal.load. def load(content) # :nodoc: Marshal::load(content) end # This method is just a wrapped around Marshal.load. def load_file(file) # :nodoc: Marshal::load(file) end private # Commits changes to the data store file. def commit_new(f) f.truncate(0) f.rewind new_file = @filename + ".new" File.open(new_file, RD_ACCESS) do |nf| FileUtils.copy_stream(nf, f) end File.unlink(new_file) end end # :enddoc: if __FILE__ == $0 db = PStore.new("/tmp/foo") db.transaction do p db.roots ary = db["root"] = [1,2,3,4] ary[1] = [1,1.5] end 1000.times do db.transaction do db["root"][0] += 1 p db["root"][0] end end db.transaction(true) do p db["root"] end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/prettyprint.rb
tools/jruby-1.5.1/lib/ruby/1.8/prettyprint.rb
# $Id$ # This class implements a pretty printing algorithm. It finds line breaks and # nice indentations for grouped structure. # # By default, the class assumes that primitive elements are strings and each # byte in the strings have single column in width. But it can be used for # other situations by giving suitable arguments for some methods: # * newline object and space generation block for PrettyPrint.new # * optional width argument for PrettyPrint#text # * PrettyPrint#breakable # # There are several candidate uses: # * text formatting using proportional fonts # * multibyte characters which has columns different to number of bytes # * non-string formatting # # == Bugs # * Box based formatting? # * Other (better) model/algorithm? # # == References # Christian Lindig, Strictly Pretty, March 2000, # http://www.st.cs.uni-sb.de/~lindig/papers/#pretty # # Philip Wadler, A prettier printer, March 1998, # http://homepages.inf.ed.ac.uk/wadler/topics/language-design.html#prettier # # == Author # Tanaka Akira <akr@m17n.org> # class PrettyPrint # This is a convenience method which is same as follows: # # begin # q = PrettyPrint.new(output, maxwidth, newline, &genspace) # ... # q.flush # output # end # def PrettyPrint.format(output='', maxwidth=79, newline="\n", genspace=lambda {|n| ' ' * n}) q = PrettyPrint.new(output, maxwidth, newline, &genspace) yield q q.flush output end # This is similar to PrettyPrint::format but the result has no breaks. # # +maxwidth+, +newline+ and +genspace+ are ignored. # # The invocation of +breakable+ in the block doesn't break a line and is # treated as just an invocation of +text+. # def PrettyPrint.singleline_format(output='', maxwidth=nil, newline=nil, genspace=nil) q = SingleLine.new(output) yield q output end # Creates a buffer for pretty printing. # # +output+ is an output target. If it is not specified, '' is assumed. It # should have a << method which accepts the first argument +obj+ of # PrettyPrint#text, the first argument +sep+ of PrettyPrint#breakable, the # first argument +newline+ of PrettyPrint.new, and the result of a given # block for PrettyPrint.new. # # +maxwidth+ specifies maximum line length. If it is not specified, 79 is # assumed. However actual outputs may overflow +maxwidth+ if long # non-breakable texts are provided. # # +newline+ is used for line breaks. "\n" is used if it is not specified. # # The block is used to generate spaces. {|width| ' ' * width} is used if it # is not given. # def initialize(output='', maxwidth=79, newline="\n", &genspace) @output = output @maxwidth = maxwidth @newline = newline @genspace = genspace || lambda {|n| ' ' * n} @output_width = 0 @buffer_width = 0 @buffer = [] root_group = Group.new(0) @group_stack = [root_group] @group_queue = GroupQueue.new(root_group) @indent = 0 end attr_reader :output, :maxwidth, :newline, :genspace attr_reader :indent, :group_queue def current_group @group_stack.last end # first? is a predicate to test the call is a first call to first? with # current group. # # It is useful to format comma separated values as: # # q.group(1, '[', ']') { # xxx.each {|yyy| # unless q.first? # q.text ',' # q.breakable # end # ... pretty printing yyy ... # } # } # # first? is obsoleted in 1.8.2. # def first? warn "PrettyPrint#first? is obsoleted at 1.8.2." current_group.first? end def break_outmost_groups while @maxwidth < @output_width + @buffer_width return unless group = @group_queue.deq until group.breakables.empty? data = @buffer.shift @output_width = data.output(@output, @output_width) @buffer_width -= data.width end while !@buffer.empty? && Text === @buffer.first text = @buffer.shift @output_width = text.output(@output, @output_width) @buffer_width -= text.width end end end # This adds +obj+ as a text of +width+ columns in width. # # If +width+ is not specified, obj.length is used. # def text(obj, width=obj.length) if @buffer.empty? @output << obj @output_width += width else text = @buffer.last unless Text === text text = Text.new @buffer << text end text.add(obj, width) @buffer_width += width break_outmost_groups end end def fill_breakable(sep=' ', width=sep.length) group { breakable sep, width } end # This tells "you can break a line here if necessary", and a +width+\-column # text +sep+ is inserted if a line is not broken at the point. # # If +sep+ is not specified, " " is used. # # If +width+ is not specified, +sep.length+ is used. You will have to # specify this when +sep+ is a multibyte character, for example. # def breakable(sep=' ', width=sep.length) group = @group_stack.last if group.break? flush @output << @newline @output << @genspace.call(@indent) @output_width = @indent @buffer_width = 0 else @buffer << Breakable.new(sep, width, self) @buffer_width += width break_outmost_groups end end # Groups line break hints added in the block. The line break hints are all # to be used or not. # # If +indent+ is specified, the method call is regarded as nested by # nest(indent) { ... }. # # If +open_obj+ is specified, <tt>text open_obj, open_width</tt> is called # before grouping. If +close_obj+ is specified, <tt>text close_obj, # close_width</tt> is called after grouping. # def group(indent=0, open_obj='', close_obj='', open_width=open_obj.length, close_width=close_obj.length) text open_obj, open_width group_sub { nest(indent) { yield } } text close_obj, close_width end def group_sub group = Group.new(@group_stack.last.depth + 1) @group_stack.push group @group_queue.enq group begin yield ensure @group_stack.pop if group.breakables.empty? @group_queue.delete group end end end # Increases left margin after newline with +indent+ for line breaks added in # the block. # def nest(indent) @indent += indent begin yield ensure @indent -= indent end end # outputs buffered data. # def flush @buffer.each {|data| @output_width = data.output(@output, @output_width) } @buffer.clear @buffer_width = 0 end class Text def initialize @objs = [] @width = 0 end attr_reader :width def output(out, output_width) @objs.each {|obj| out << obj} output_width + @width end def add(obj, width) @objs << obj @width += width end end class Breakable def initialize(sep, width, q) @obj = sep @width = width @pp = q @indent = q.indent @group = q.current_group @group.breakables.push self end attr_reader :obj, :width, :indent def output(out, output_width) @group.breakables.shift if @group.break? out << @pp.newline out << @pp.genspace.call(@indent) @indent else @pp.group_queue.delete @group if @group.breakables.empty? out << @obj output_width + @width end end end class Group def initialize(depth) @depth = depth @breakables = [] @break = false end attr_reader :depth, :breakables def break @break = true end def break? @break end def first? if defined? @first false else @first = false true end end end class GroupQueue def initialize(*groups) @queue = [] groups.each {|g| enq g} end def enq(group) depth = group.depth @queue << [] until depth < @queue.length @queue[depth] << group end def deq @queue.each {|gs| (gs.length-1).downto(0) {|i| unless gs[i].breakables.empty? group = gs.slice!(i, 1).first group.break return group end } gs.each {|group| group.break} gs.clear } return nil end def delete(group) @queue[group.depth].delete(group) end end class SingleLine def initialize(output, maxwidth=nil, newline=nil) @output = output @first = [true] end def text(obj, width=nil) @output << obj end def breakable(sep=' ', width=nil) @output << sep end def nest(indent) yield end def group(indent=nil, open_obj='', close_obj='', open_width=nil, close_width=nil) @first.push true @output << open_obj yield @output << close_obj @first.pop end def flush end def first? result = @first[-1] @first[-1] = false result end end end if __FILE__ == $0 require 'test/unit' class WadlerExample < Test::Unit::TestCase # :nodoc: def setup @tree = Tree.new("aaaa", Tree.new("bbbbb", Tree.new("ccc"), Tree.new("dd")), Tree.new("eee"), Tree.new("ffff", Tree.new("gg"), Tree.new("hhh"), Tree.new("ii"))) end def hello(width) PrettyPrint.format('', width) {|hello| hello.group { hello.group { hello.group { hello.group { hello.text 'hello' hello.breakable; hello.text 'a' } hello.breakable; hello.text 'b' } hello.breakable; hello.text 'c' } hello.breakable; hello.text 'd' } } end def test_hello_00_06 expected = <<'End'.chomp hello a b c d End assert_equal(expected, hello(0)) assert_equal(expected, hello(6)) end def test_hello_07_08 expected = <<'End'.chomp hello a b c d End assert_equal(expected, hello(7)) assert_equal(expected, hello(8)) end def test_hello_09_10 expected = <<'End'.chomp hello a b c d End out = hello(9); assert_equal(expected, out) out = hello(10); assert_equal(expected, out) end def test_hello_11_12 expected = <<'End'.chomp hello a b c d End assert_equal(expected, hello(11)) assert_equal(expected, hello(12)) end def test_hello_13 expected = <<'End'.chomp hello a b c d End assert_equal(expected, hello(13)) end def tree(width) PrettyPrint.format('', width) {|q| @tree.show(q)} end def test_tree_00_19 expected = <<'End'.chomp aaaa[bbbbb[ccc, dd], eee, ffff[gg, hhh, ii]] End assert_equal(expected, tree(0)) assert_equal(expected, tree(19)) end def test_tree_20_22 expected = <<'End'.chomp aaaa[bbbbb[ccc, dd], eee, ffff[gg, hhh, ii]] End assert_equal(expected, tree(20)) assert_equal(expected, tree(22)) end def test_tree_23_43 expected = <<'End'.chomp aaaa[bbbbb[ccc, dd], eee, ffff[gg, hhh, ii]] End assert_equal(expected, tree(23)) assert_equal(expected, tree(43)) end def test_tree_44 assert_equal(<<'End'.chomp, tree(44)) aaaa[bbbbb[ccc, dd], eee, ffff[gg, hhh, ii]] End end def tree_alt(width) PrettyPrint.format('', width) {|q| @tree.altshow(q)} end def test_tree_alt_00_18 expected = <<'End'.chomp aaaa[ bbbbb[ ccc, dd ], eee, ffff[ gg, hhh, ii ] ] End assert_equal(expected, tree_alt(0)) assert_equal(expected, tree_alt(18)) end def test_tree_alt_19_20 expected = <<'End'.chomp aaaa[ bbbbb[ ccc, dd ], eee, ffff[ gg, hhh, ii ] ] End assert_equal(expected, tree_alt(19)) assert_equal(expected, tree_alt(20)) end def test_tree_alt_20_49 expected = <<'End'.chomp aaaa[ bbbbb[ ccc, dd ], eee, ffff[ gg, hhh, ii ] ] End assert_equal(expected, tree_alt(21)) assert_equal(expected, tree_alt(49)) end def test_tree_alt_50 expected = <<'End'.chomp aaaa[ bbbbb[ ccc, dd ], eee, ffff[ gg, hhh, ii ] ] End assert_equal(expected, tree_alt(50)) end class Tree # :nodoc: def initialize(string, *children) @string = string @children = children end def show(q) q.group { q.text @string q.nest(@string.length) { unless @children.empty? q.text '[' q.nest(1) { first = true @children.each {|t| if first first = false else q.text ',' q.breakable end t.show(q) } } q.text ']' end } } end def altshow(q) q.group { q.text @string unless @children.empty? q.text '[' q.nest(2) { q.breakable first = true @children.each {|t| if first first = false else q.text ',' q.breakable end t.altshow(q) } } q.breakable q.text ']' end } end end end class StrictPrettyExample < Test::Unit::TestCase # :nodoc: def prog(width) PrettyPrint.format('', width) {|q| q.group { q.group {q.nest(2) { q.text "if"; q.breakable; q.group { q.nest(2) { q.group {q.text "a"; q.breakable; q.text "=="} q.breakable; q.text "b"}}}} q.breakable q.group {q.nest(2) { q.text "then"; q.breakable; q.group { q.nest(2) { q.group {q.text "a"; q.breakable; q.text "<<"} q.breakable; q.text "2"}}}} q.breakable q.group {q.nest(2) { q.text "else"; q.breakable; q.group { q.nest(2) { q.group {q.text "a"; q.breakable; q.text "+"} q.breakable; q.text "b"}}}}} } end def test_00_04 expected = <<'End'.chomp if a == b then a << 2 else a + b End assert_equal(expected, prog(0)) assert_equal(expected, prog(4)) end def test_05 expected = <<'End'.chomp if a == b then a << 2 else a + b End assert_equal(expected, prog(5)) end def test_06 expected = <<'End'.chomp if a == b then a << 2 else a + b End assert_equal(expected, prog(6)) end def test_07 expected = <<'End'.chomp if a == b then a << 2 else a + b End assert_equal(expected, prog(7)) end def test_08 expected = <<'End'.chomp if a == b then a << 2 else a + b End assert_equal(expected, prog(8)) end def test_09 expected = <<'End'.chomp if a == b then a << 2 else a + b End assert_equal(expected, prog(9)) end def test_10 expected = <<'End'.chomp if a == b then a << 2 else a + b End assert_equal(expected, prog(10)) end def test_11_31 expected = <<'End'.chomp if a == b then a << 2 else a + b End assert_equal(expected, prog(11)) assert_equal(expected, prog(15)) assert_equal(expected, prog(31)) end def test_32 expected = <<'End'.chomp if a == b then a << 2 else a + b End assert_equal(expected, prog(32)) end end class TailGroup < Test::Unit::TestCase # :nodoc: def test_1 out = PrettyPrint.format('', 10) {|q| q.group { q.group { q.text "abc" q.breakable q.text "def" } q.group { q.text "ghi" q.breakable q.text "jkl" } } } assert_equal("abc defghi\njkl", out) end end class NonString < Test::Unit::TestCase # :nodoc: def format(width) PrettyPrint.format([], width, 'newline', lambda {|n| "#{n} spaces"}) {|q| q.text(3, 3) q.breakable(1, 1) q.text(3, 3) } end def test_6 assert_equal([3, "newline", "0 spaces", 3], format(6)) end def test_7 assert_equal([3, 1, 3], format(7)) end end class Fill < Test::Unit::TestCase # :nodoc: def format(width) PrettyPrint.format('', width) {|q| q.group { q.text 'abc' q.fill_breakable q.text 'def' q.fill_breakable q.text 'ghi' q.fill_breakable q.text 'jkl' q.fill_breakable q.text 'mno' q.fill_breakable q.text 'pqr' q.fill_breakable q.text 'stu' } } end def test_00_06 expected = <<'End'.chomp abc def ghi jkl mno pqr stu End assert_equal(expected, format(0)) assert_equal(expected, format(6)) end def test_07_10 expected = <<'End'.chomp abc def ghi jkl mno pqr stu End assert_equal(expected, format(7)) assert_equal(expected, format(10)) end def test_11_14 expected = <<'End'.chomp abc def ghi jkl mno pqr stu End assert_equal(expected, format(11)) assert_equal(expected, format(14)) end def test_15_18 expected = <<'End'.chomp abc def ghi jkl mno pqr stu End assert_equal(expected, format(15)) assert_equal(expected, format(18)) end def test_19_22 expected = <<'End'.chomp abc def ghi jkl mno pqr stu End assert_equal(expected, format(19)) assert_equal(expected, format(22)) end def test_23_26 expected = <<'End'.chomp abc def ghi jkl mno pqr stu End assert_equal(expected, format(23)) assert_equal(expected, format(26)) end def test_27 expected = <<'End'.chomp abc def ghi jkl mno pqr stu End assert_equal(expected, format(27)) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/generator.rb
tools/jruby-1.5.1/lib/ruby/1.8/generator.rb
# Because generator is needed by Enumerator in 1.8.7 mode, we moved generator # logic to src/bultin/generator_internal.rb and require that here and from # within JRuby, so that Enumerator works even without stdlib present. require 'generator_internal'
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/profile.rb
tools/jruby-1.5.1/lib/ruby/1.8/profile.rb
require 'profiler' END { Profiler__::print_profile(STDERR) } Profiler__::start_profile
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/erb.rb
tools/jruby-1.5.1/lib/ruby/1.8/erb.rb
# = ERB -- Ruby Templating # # Author:: Masatoshi SEKI # Documentation:: James Edward Gray II and Gavin Sinclair # # See ERB for primary documentation and ERB::Util for a couple of utility # routines. # # Copyright (c) 1999-2000,2002,2003 Masatoshi SEKI # # You can redistribute it and/or modify it under the same terms as Ruby. # # = ERB -- Ruby Templating # # == Introduction # # ERB provides an easy to use but powerful templating system for Ruby. Using # ERB, actual Ruby code can be added to any plain text document for the # purposes of generating document information details and/or flow control. # # A very simple example is this: # # require 'erb' # # x = 42 # template = ERB.new <<-EOF # The value of x is: <%= x %> # EOF # puts template.result(binding) # # <em>Prints:</em> The value of x is: 42 # # More complex examples are given below. # # # == Recognized Tags # # ERB recognizes certain tags in the provided template and converts them based # on the rules below: # # <% Ruby code -- inline with output %> # <%= Ruby expression -- replace with result %> # <%# comment -- ignored -- useful in testing %> # % a line of Ruby code -- treated as <% line %> (optional -- see ERB.new) # %% replaced with % if first thing on a line and % processing is used # <%% or %%> -- replace with <% or %> respectively # # All other text is passed through ERB filtering unchanged. # # # == Options # # There are several settings you can change when you use ERB: # * the nature of the tags that are recognized; # * the value of <tt>$SAFE</tt> under which the template is run; # * the binding used to resolve local variables in the template. # # See the ERB.new and ERB#result methods for more detail. # # # == Examples # # === Plain Text # # ERB is useful for any generic templating situation. Note that in this example, we use the # convenient "% at start of line" tag, and we quote the template literally with # <tt>%q{...}</tt> to avoid trouble with the backslash. # # require "erb" # # # Create template. # template = %q{ # From: James Edward Gray II <james@grayproductions.net> # To: <%= to %> # Subject: Addressing Needs # # <%= to[/\w+/] %>: # # Just wanted to send a quick note assuring that your needs are being # addressed. # # I want you to know that my team will keep working on the issues, # especially: # # <%# ignore numerous minor requests -- focus on priorities %> # % priorities.each do |priority| # * <%= priority %> # % end # # Thanks for your patience. # # James Edward Gray II # }.gsub(/^ /, '') # # message = ERB.new(template, 0, "%<>") # # # Set up template data. # to = "Community Spokesman <spokesman@ruby_community.org>" # priorities = [ "Run Ruby Quiz", # "Document Modules", # "Answer Questions on Ruby Talk" ] # # # Produce result. # email = message.result # puts email # # <i>Generates:</i> # # From: James Edward Gray II <james@grayproductions.net> # To: Community Spokesman <spokesman@ruby_community.org> # Subject: Addressing Needs # # Community: # # Just wanted to send a quick note assuring that your needs are being addressed. # # I want you to know that my team will keep working on the issues, especially: # # * Run Ruby Quiz # * Document Modules # * Answer Questions on Ruby Talk # # Thanks for your patience. # # James Edward Gray II # # === Ruby in HTML # # ERB is often used in <tt>.rhtml</tt> files (HTML with embedded Ruby). Notice the need in # this example to provide a special binding when the template is run, so that the instance # variables in the Product object can be resolved. # # require "erb" # # # Build template data class. # class Product # def initialize( code, name, desc, cost ) # @code = code # @name = name # @desc = desc # @cost = cost # # @features = [ ] # end # # def add_feature( feature ) # @features << feature # end # # # Support templating of member data. # def get_binding # binding # end # # # ... # end # # # Create template. # template = %{ # <html> # <head><title>Ruby Toys -- <%= @name %></title></head> # <body> # # <h1><%= @name %> (<%= @code %>)</h1> # <p><%= @desc %></p> # # <ul> # <% @features.each do |f| %> # <li><b><%= f %></b></li> # <% end %> # </ul> # # <p> # <% if @cost < 10 %> # <b>Only <%= @cost %>!!!</b> # <% else %> # Call for a price, today! # <% end %> # </p> # # </body> # </html> # }.gsub(/^ /, '') # # rhtml = ERB.new(template) # # # Set up template data. # toy = Product.new( "TZ-1002", # "Rubysapien", # "Geek's Best Friend! Responds to Ruby commands...", # 999.95 ) # toy.add_feature("Listens for verbal commands in the Ruby language!") # toy.add_feature("Ignores Perl, Java, and all C variants.") # toy.add_feature("Karate-Chop Action!!!") # toy.add_feature("Matz signature on left leg.") # toy.add_feature("Gem studded eyes... Rubies, of course!") # # # Produce result. # rhtml.run(toy.get_binding) # # <i>Generates (some blank lines removed):</i> # # <html> # <head><title>Ruby Toys -- Rubysapien</title></head> # <body> # # <h1>Rubysapien (TZ-1002)</h1> # <p>Geek's Best Friend! Responds to Ruby commands...</p> # # <ul> # <li><b>Listens for verbal commands in the Ruby language!</b></li> # <li><b>Ignores Perl, Java, and all C variants.</b></li> # <li><b>Karate-Chop Action!!!</b></li> # <li><b>Matz signature on left leg.</b></li> # <li><b>Gem studded eyes... Rubies, of course!</b></li> # </ul> # # <p> # Call for a price, today! # </p> # # </body> # </html> # # # == Notes # # There are a variety of templating solutions available in various Ruby projects: # * ERB's big brother, eRuby, works the same but is written in C for speed; # * Amrita (smart at producing HTML/XML); # * cs/Template (written in C for speed); # * RDoc, distributed with Ruby, uses its own template engine, which can be reused elsewhere; # * and others; search the RAA. # # Rails, the web application framework, uses ERB to create views. # class ERB Revision = '$Date: 2009-02-24 02:44:50 +0900 (Tue, 24 Feb 2009) $' #' # Returns revision information for the erb.rb module. def self.version "erb.rb [2.1.0 #{ERB::Revision.split[1]}]" end end #-- # ERB::Compiler class ERB class Compiler # :nodoc: class PercentLine # :nodoc: def initialize(str) @value = str end attr_reader :value alias :to_s :value def empty? @value.empty? end end class Scanner # :nodoc: @scanner_map = {} def self.regist_scanner(klass, trim_mode, percent) @scanner_map[[trim_mode, percent]] = klass end def self.default_scanner=(klass) @default_scanner = klass end def self.make_scanner(src, trim_mode, percent) klass = @scanner_map.fetch([trim_mode, percent], @default_scanner) klass.new(src, trim_mode, percent) end def initialize(src, trim_mode, percent) @src = src @stag = nil end attr_accessor :stag def scan; end end class TrimScanner < Scanner # :nodoc: def initialize(src, trim_mode, percent) super @trim_mode = trim_mode @percent = percent if @trim_mode == '>' @scan_line = self.method(:trim_line1) elsif @trim_mode == '<>' @scan_line = self.method(:trim_line2) elsif @trim_mode == '-' @scan_line = self.method(:explicit_trim_line) else @scan_line = self.method(:scan_line) end end attr_accessor :stag def scan(&block) @stag = nil if @percent @src.each do |line| percent_line(line, &block) end else @scan_line.call(@src, &block) end nil end def percent_line(line, &block) if @stag || line[0] != ?% return @scan_line.call(line, &block) end line[0] = '' if line[0] == ?% @scan_line.call(line, &block) else yield(PercentLine.new(line.chomp)) end end def scan_line(line) line.scan(/(.*?)(<%%|%%>|<%=|<%#|<%|%>|\n|\z)/m) do |tokens| tokens.each do |token| next if token.empty? yield(token) end end end def trim_line1(line) line.scan(/(.*?)(<%%|%%>|<%=|<%#|<%|%>\n|%>|\n|\z)/m) do |tokens| tokens.each do |token| next if token.empty? if token == "%>\n" yield('%>') yield(:cr) else yield(token) end end end end def trim_line2(line) head = nil line.scan(/(.*?)(<%%|%%>|<%=|<%#|<%|%>\n|%>|\n|\z)/m) do |tokens| tokens.each do |token| next if token.empty? head = token unless head if token == "%>\n" yield('%>') if is_erb_stag?(head) yield(:cr) else yield("\n") end head = nil else yield(token) head = nil if token == "\n" end end end end def explicit_trim_line(line) line.scan(/(.*?)(^[ \t]*<%\-|<%\-|<%%|%%>|<%=|<%#|<%|-%>\n|-%>|%>|\z)/m) do |tokens| tokens.each do |token| next if token.empty? if @stag.nil? && /[ \t]*<%-/ =~ token yield('<%') elsif @stag && token == "-%>\n" yield('%>') yield(:cr) elsif @stag && token == '-%>' yield('%>') else yield(token) end end end end ERB_STAG = %w(<%= <%# <%) def is_erb_stag?(s) ERB_STAG.member?(s) end end Scanner.default_scanner = TrimScanner class SimpleScanner < Scanner # :nodoc: def scan @src.scan(/(.*?)(<%%|%%>|<%=|<%#|<%|%>|\n|\z)/m) do |tokens| tokens.each do |token| next if token.empty? yield(token) end end end end Scanner.regist_scanner(SimpleScanner, nil, false) begin require 'strscan' class SimpleScanner2 < Scanner # :nodoc: def scan stag_reg = /(.*?)(<%%|<%=|<%#|<%|\z)/m etag_reg = /(.*?)(%%>|%>|\z)/m scanner = StringScanner.new(@src) while ! scanner.eos? scanner.scan(@stag ? etag_reg : stag_reg) yield(scanner[1]) yield(scanner[2]) end end end Scanner.regist_scanner(SimpleScanner2, nil, false) class ExplicitScanner < Scanner # :nodoc: def scan stag_reg = /(.*?)(^[ \t]*<%-|<%%|<%=|<%#|<%-|<%|\z)/m etag_reg = /(.*?)(%%>|-%>|%>|\z)/m scanner = StringScanner.new(@src) while ! scanner.eos? scanner.scan(@stag ? etag_reg : stag_reg) yield(scanner[1]) elem = scanner[2] if /[ \t]*<%-/ =~ elem yield('<%') elsif elem == '-%>' yield('%>') yield(:cr) if scanner.scan(/(\n|\z)/) else yield(elem) end end end end Scanner.regist_scanner(ExplicitScanner, '-', false) rescue LoadError end class Buffer # :nodoc: def initialize(compiler) @compiler = compiler @line = [] @script = "" @compiler.pre_cmd.each do |x| push(x) end end attr_reader :script def push(cmd) @line << cmd end def cr @script << (@line.join('; ')) @line = [] @script << "\n" end def close return unless @line @compiler.post_cmd.each do |x| push(x) end @script << (@line.join('; ')) @line = nil end end def content_dump(s) n = s.count("\n") if n > 0 s.dump + "\n" * n else s.dump end end def compile(s) out = Buffer.new(self) content = '' scanner = make_scanner(s) scanner.scan do |token| next if token.nil? next if token == '' if scanner.stag.nil? case token when PercentLine out.push("#{@put_cmd} #{content_dump(content)}") if content.size > 0 content = '' out.push(token.to_s) out.cr when :cr out.cr when '<%', '<%=', '<%#' scanner.stag = token out.push("#{@put_cmd} #{content_dump(content)}") if content.size > 0 content = '' when "\n" content << "\n" out.push("#{@put_cmd} #{content_dump(content)}") content = '' when '<%%' content << '<%' else content << token end else case token when '%>' case scanner.stag when '<%' if content[-1] == ?\n content.chop! out.push(content) out.cr else out.push(content) end when '<%=' out.push("#{@insert_cmd}((#{content}).to_s)") when '<%#' # out.push("# #{content_dump(content)}") end scanner.stag = nil content = '' when '%%>' content << '%>' else content << token end end end out.push("#{@put_cmd} #{content_dump(content)}") if content.size > 0 out.close out.script end def prepare_trim_mode(mode) case mode when 1 return [false, '>'] when 2 return [false, '<>'] when 0 return [false, nil] when String perc = mode.include?('%') if mode.include?('-') return [perc, '-'] elsif mode.include?('<>') return [perc, '<>'] elsif mode.include?('>') return [perc, '>'] else [perc, nil] end else return [false, nil] end end def make_scanner(src) Scanner.make_scanner(src, @trim_mode, @percent) end def initialize(trim_mode) @percent, @trim_mode = prepare_trim_mode(trim_mode) @put_cmd = 'print' @insert_cmd = @put_cmd @pre_cmd = [] @post_cmd = [] end attr_reader :percent, :trim_mode attr_accessor :put_cmd, :insert_cmd, :pre_cmd, :post_cmd end end #-- # ERB class ERB # # Constructs a new ERB object with the template specified in _str_. # # An ERB object works by building a chunk of Ruby code that will output # the completed template when run. If _safe_level_ is set to a non-nil value, # ERB code will be run in a separate thread with <b>$SAFE</b> set to the # provided level. # # If _trim_mode_ is passed a String containing one or more of the following # modifiers, ERB will adjust its code generation as listed: # # % enables Ruby code processing for lines beginning with % # <> omit newline for lines starting with <% and ending in %> # > omit newline for lines ending in %> # # _eoutvar_ can be used to set the name of the variable ERB will build up # its output in. This is useful when you need to run multiple ERB # templates through the same binding and/or when you want to control where # output ends up. Pass the name of the variable to be used inside a String. # # === Example # # require "erb" # # # build data class # class Listings # PRODUCT = { :name => "Chicken Fried Steak", # :desc => "A well messages pattie, breaded and fried.", # :cost => 9.95 } # # attr_reader :product, :price # # def initialize( product = "", price = "" ) # @product = product # @price = price # end # # def build # b = binding # # create and run templates, filling member data variables # ERB.new(<<-'END_PRODUCT'.gsub(/^\s+/, ""), 0, "", "@product").result b # <%= PRODUCT[:name] %> # <%= PRODUCT[:desc] %> # END_PRODUCT # ERB.new(<<-'END_PRICE'.gsub(/^\s+/, ""), 0, "", "@price").result b # <%= PRODUCT[:name] %> -- <%= PRODUCT[:cost] %> # <%= PRODUCT[:desc] %> # END_PRICE # end # end # # # setup template data # listings = Listings.new # listings.build # # puts listings.product + "\n" + listings.price # # _Generates_ # # Chicken Fried Steak # A well messages pattie, breaded and fried. # # Chicken Fried Steak -- 9.95 # A well messages pattie, breaded and fried. # def initialize(str, safe_level=nil, trim_mode=nil, eoutvar='_erbout') @safe_level = safe_level compiler = ERB::Compiler.new(trim_mode) set_eoutvar(compiler, eoutvar) @src = compiler.compile(str) @filename = nil end # The Ruby code generated by ERB attr_reader :src # The optional _filename_ argument passed to Kernel#eval when the ERB code # is run attr_accessor :filename # # Can be used to set _eoutvar_ as described in ERB#new. It's probably easier # to just use the constructor though, since calling this method requires the # setup of an ERB _compiler_ object. # def set_eoutvar(compiler, eoutvar = '_erbout') compiler.put_cmd = "#{eoutvar}.concat" compiler.insert_cmd = "#{eoutvar}.concat" cmd = [] cmd.push "#{eoutvar} = ''" compiler.pre_cmd = cmd cmd = [] cmd.push(eoutvar) compiler.post_cmd = cmd end # Generate results and print them. (see ERB#result) def run(b=TOPLEVEL_BINDING) print self.result(b) end # # Executes the generated ERB code to produce a completed template, returning # the results of that code. (See ERB#new for details on how this process can # be affected by _safe_level_.) # # _b_ accepts a Binding or Proc object which is used to set the context of # code evaluation. # def result(b=TOPLEVEL_BINDING) if @safe_level proc { $SAFE = @safe_level eval(@src, b, (@filename || '(erb)'), 1) }.call else eval(@src, b, (@filename || '(erb)'), 1) end end # Define _methodname_ as instance method of _mod_ from compiled ruby source. # # example: # filename = 'example.rhtml' # 'arg1' and 'arg2' are used in example.rhtml # erb = ERB.new(File.read(filename)) # erb.def_method(MyClass, 'render(arg1, arg2)', filename) # print MyClass.new.render('foo', 123) def def_method(mod, methodname, fname='(ERB)') mod.module_eval("def #{methodname}\n" + self.src + "\nend\n", fname, 0) end # Create unnamed module, define _methodname_ as instance method of it, and return it. # # example: # filename = 'example.rhtml' # 'arg1' and 'arg2' are used in example.rhtml # erb = ERB.new(File.read(filename)) # erb.filename = filename # MyModule = erb.def_module('render(arg1, arg2)') # class MyClass # include MyModule # end def def_module(methodname='erb') mod = Module.new def_method(mod, methodname, @filename || '(ERB)') mod end # Define unnamed class which has _methodname_ as instance method, and return it. # # example: # class MyClass_ # def initialize(arg1, arg2) # @arg1 = arg1; @arg2 = arg2 # end # end # filename = 'example.rhtml' # @arg1 and @arg2 are used in example.rhtml # erb = ERB.new(File.read(filename)) # erb.filename = filename # MyClass = erb.def_class(MyClass_, 'render()') # print MyClass.new('foo', 123).render() def def_class(superklass=Object, methodname='result') cls = Class.new(superklass) def_method(cls, methodname, @filename || '(ERB)') cls end end #-- # ERB::Util class ERB # A utility module for conversion routines, often handy in HTML generation. module Util public # # A utility method for escaping HTML tag characters in _s_. # # require "erb" # include ERB::Util # # puts html_escape("is a > 0 & a < 10?") # # _Generates_ # # is a &gt; 0 &amp; a &lt; 10? # def html_escape(s) s.to_s.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;") end alias h html_escape module_function :h module_function :html_escape # # A utility method for encoding the String _s_ as a URL. # # require "erb" # include ERB::Util # # puts url_encode("Programming Ruby: The Pragmatic Programmer's Guide") # # _Generates_ # # Programming%20Ruby%3A%20%20The%20Pragmatic%20Programmer%27s%20Guide # def url_encode(s) s.to_s.gsub(/[^a-zA-Z0-9_\-.]/n){ sprintf("%%%02X", $&.unpack("C")[0]) } end alias u url_encode module_function :u module_function :url_encode end end #-- # ERB::DefMethod class ERB # Utility module to define eRuby script as instance method. # # === Example # # example.rhtml: # <% for item in @items %> # <b><%= item %></b> # <% end %> # # example.rb: # require 'erb' # class MyClass # extend ERB::DefMethod # def_erb_method('render()', 'example.rhtml') # def initialize(items) # @items = items # end # end # print MyClass.new([10,20,30]).render() # # result: # # <b>10</b> # # <b>20</b> # # <b>30</b> # module DefMethod public # define _methodname_ as instance method of current module, using ERB object or eRuby file def def_erb_method(methodname, erb_or_fname) if erb_or_fname.kind_of? String fname = erb_or_fname erb = ERB.new(File.read(fname)) erb.def_method(self, methodname, fname) else erb = erb_or_fname erb.def_method(self, methodname, erb.filename || '(ERB)') end end module_function :def_erb_method end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/parsedate.rb
tools/jruby-1.5.1/lib/ruby/1.8/parsedate.rb
# # = parsedate.rb: Parses dates # # Author:: Tadayoshi Funaba # Documentation:: Konrad Meyer # # ParseDate munches on a date and turns it into an array of values. # # # ParseDate converts a date into an array of values. # For example: # # require 'parsedate' # # ParseDate.parsedate "Tuesday, July 6th, 2007, 18:35:20 UTC" # # => [2007, 7, 6, 18, 35, 20, "UTC", 2] # # The order is of the form [year, month, day of month, hour, minute, second, # timezone, day of the week]. require 'date/format' module ParseDate # # Parse a string representation of a date into values. # For example: # # require 'parsedate' # # ParseDate.parsedate "Tuesday, July 5th, 2007, 18:35:20 UTC" # # => [2007, 7, 5, 18, 35, 20, "UTC", 2] # # The order is of the form [year, month, day of month, hour, minute, # second, timezone, day of week]. # # ParseDate.parsedate can also take a second argument, +comp+, which # is a boolean telling the method to compensate for dates with years # expressed as two digits. Example: # # require 'parsedate' # # ParseDate.parsedate "Mon Dec 25 00 06:53:24 UTC", true # # => [2000, 12, 25, 6, 53, 24, "UTC", 1] # def parsedate(str, comp=false) Date._parse(str, comp). values_at(:year, :mon, :mday, :hour, :min, :sec, :zone, :wday) end module_function :parsedate end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/scanf.rb
tools/jruby-1.5.1/lib/ruby/1.8/scanf.rb
# scanf for Ruby # # $Revision: 21682 $ # $Id: scanf.rb 21682 2009-01-20 03:23:46Z shyouhei $ # $Author: shyouhei $ # $Date: 2009-01-20 12:23:46 +0900 (Tue, 20 Jan 2009) $ # # A product of the Austin Ruby Codefest (Austin, Texas, August 2002) =begin =scanf for Ruby ==Description scanf for Ruby is an implementation of the C function scanf(3), modified as necessary for Ruby compatibility. The methods provided are String#scanf, IO#scanf, and Kernel#scanf. Kernel#scanf is a wrapper around STDIN.scanf. IO#scanf can be used on any IO stream, including file handles and sockets. scanf can be called either with or without a block. scanf for Ruby scans an input string or stream according to a <b>format</b>, as described below ("Conversions"), and returns an array of matches between the format and the input. The format is defined in a string, and is similar (though not identical) to the formats used in Kernel#printf and Kernel#sprintf. The format may contain <b>conversion specifiers</b>, which tell scanf what form (type) each particular matched substring should be converted to (e.g., decimal integer, floating point number, literal string, etc.) The matches and conversions take place from left to right, and the conversions themselves are returned as an array. The format string may also contain characters other than those in the conversion specifiers. White space (blanks, tabs, or newlines) in the format string matches any amount of white space, including none, in the input. Everything else matches only itself. Scanning stops, and scanf returns, when any input character fails to match the specifications in the format string, or when input is exhausted, or when everything in the format string has been matched. All matches found up to the stopping point are returned in the return array (or yielded to the block, if a block was given). ==Basic usage require 'scanf.rb' # String#scanf and IO#scanf take a single argument (a format string) array = aString.scanf("%d%s") array = anIO.scanf("%d%s") # Kernel#scanf reads from STDIN array = scanf("%d%s") ==Block usage When called with a block, scanf keeps scanning the input, cycling back to the beginning of the format string, and yields a new array of conversions to the block every time the format string is matched (including partial matches, but not including complete failures). The actual return value of scanf when called with a block is an array containing the results of all the executions of the block. str = "123 abc 456 def 789 ghi" str.scanf("%d%s") { |num,str| [ num * 2, str.upcase ] } # => [[246, "ABC"], [912, "DEF"], [1578, "GHI"]] ==Conversions The single argument to scanf is a format string, which generally includes one or more conversion specifiers. Conversion specifiers begin with the percent character ('%') and include information about what scanf should next scan for (string, decimal number, single character, etc.). There may be an optional maximum field width, expressed as a decimal integer, between the % and the conversion. If no width is given, a default of `infinity' is used (with the exception of the %c specifier; see below). Otherwise, given a field width of <em>n</em> for a given conversion, at most <em>n</em> characters are scanned in processing that conversion. Before conversion begins, most conversions skip white space in the input string; this white space is not counted against the field width. The following conversions are available. (See the files EXAMPLES and <tt>tests/scanftests.rb</tt> for examples.) [%] Matches a literal `%'. That is, `%%' in the format string matches a single input `%' character. No conversion is done, and the resulting '%' is not included in the return array. [d] Matches an optionally signed decimal integer. [u] Same as d. [i] Matches an optionally signed integer. The integer is read in base 16 if it begins with `0x' or `0X', in base 8 if it begins with `0', and in base 10 other- wise. Only characters that correspond to the base are recognized. [o] Matches an optionally signed octal integer. [x,X] Matches an optionally signed hexadecimal integer, [f,g,e,E] Matches an optionally signed floating-point number. [s] Matches a sequence of non-white-space character. The input string stops at white space or at the maximum field width, whichever occurs first. [c] Matches a single character, or a sequence of <em>n</em> characters if a field width of <em>n</em> is specified. The usual skip of leading white space is suppressed. To skip white space first, use an explicit space in the format. [<tt>[</tt>] Matches a nonempty sequence of characters from the specified set of accepted characters. The usual skip of leading white space is suppressed. This bracketed sub-expression is interpreted exactly like a character class in a Ruby regular expression. (In fact, it is placed as-is in a regular expression.) The matching against the input string ends with the appearance of a character not in (or, with a circumflex, in) the set, or when the field width runs out, whichever comes first. ===Assignment suppression To require that a particular match occur, but without including the result in the return array, place the <b>assignment suppression flag</b>, which is the star character ('*'), immediately after the leading '%' of a format specifier (just before the field width, if any). ==Examples See the files <tt>EXAMPLES</tt> and <tt>tests/scanftests.rb</tt>. ==scanf for Ruby compared with scanf in C scanf for Ruby is based on the C function scanf(3), but with modifications, dictated mainly by the underlying differences between the languages. ===Unimplemented flags and specifiers * The only flag implemented in scanf for Ruby is '<tt>*</tt>' (ignore upcoming conversion). Many of the flags available in C versions of scanf(4) have to do with the type of upcoming pointer arguments, and are literally meaningless in Ruby. * The <tt>n</tt> specifier (store number of characters consumed so far in next pointer) is not implemented. * The <tt>p</tt> specifier (match a pointer value) is not implemented. ===Altered specifiers [o,u,x,X] In scanf for Ruby, all of these specifiers scan for an optionally signed integer, rather than for an unsigned integer like their C counterparts. ===Return values scanf for Ruby returns an array of successful conversions, whereas scanf(3) returns the number of conversions successfully completed. (See below for more details on scanf for Ruby's return values.) ==Return values Without a block, scanf returns an array containing all the conversions it has found. If none are found, scanf will return an empty array. An unsuccesful match is never ignored, but rather always signals the end of the scanning operation. If the first unsuccessful match takes place after one or more successful matches have already taken place, the returned array will contain the results of those successful matches. With a block scanf returns a 'map'-like array of transformations from the block -- that is, an array reflecting what the block did with each yielded result from the iterative scanf operation. (See "Block usage", above.) ==Test suite scanf for Ruby includes a suite of unit tests (requiring the <tt>TestUnit</tt> package), which can be run with the command <tt>ruby tests/scanftests.rb</tt> or the command <tt>make test</tt>. ==Current limitations and bugs When using IO#scanf under Windows, make sure you open your files in binary mode: File.open("filename", "rb") so that scanf can keep track of characters correctly. Support for character classes is reasonably complete (since it essentially piggy-backs on Ruby's regular expression handling of character classes), but users are advised that character class testing has not been exhaustive, and that they should exercise some caution in using any of the more complex and/or arcane character class idioms. ==Technical notes ===Rationale behind scanf for Ruby The impetus for a scanf implementation in Ruby comes chiefly from the fact that existing pattern matching operations, such as Regexp#match and String#scan, return all results as strings, which have to be converted to integers or floats explicitly in cases where what's ultimately wanted are integer or float values. ===Design of scanf for Ruby scanf for Ruby is essentially a <format string>-to-<regular expression> converter. When scanf is called, a FormatString object is generated from the format string ("%d%s...") argument. The FormatString object breaks the format string down into atoms ("%d", "%5f", "blah", etc.), and from each atom it creates a FormatSpecifier object, which it saves. Each FormatSpecifier has a regular expression fragment and a "handler" associated with it. For example, the regular expression fragment associated with the format "%d" is "([-+]?\d+)", and the handler associated with it is a wrapper around String#to_i. scanf itself calls FormatString#match, passing in the input string. FormatString#match iterates through its FormatSpecifiers; for each one, it matches the corresponding regular expression fragment against the string. If there's a match, it sends the matched string to the handler associated with the FormatSpecifier. Thus, to follow up the "%d" example: if "123" occurs in the input string when a FormatSpecifier consisting of "%d" is reached, the "123" will be matched against "([-+]?\d+)", and the matched string will be rendered into an integer by a call to to_i. The rendered match is then saved to an accumulator array, and the input string is reduced to the post-match substring. Thus the string is "eaten" from the left as the FormatSpecifiers are applied in sequence. (This is done to a duplicate string; the original string is not altered.) As soon as a regular expression fragment fails to match the string, or when the FormatString object runs out of FormatSpecifiers, scanning stops and results accumulated so far are returned in an array. ==License and copyright Copyright:: (c) 2002-2003 David Alan Black License:: Distributed on the same licensing terms as Ruby itself ==Warranty disclaimer This software is provided "as is" and without any express or implied warranties, including, without limitation, the implied warranties of merchantibility and fitness for a particular purpose. ==Credits and acknowledgements scanf for Ruby was developed as the major activity of the Austin Ruby Codefest (Austin, Texas, August 2002). Principal author:: David Alan Black (mailto:dblack@superlink.net) Co-author:: Hal Fulton (mailto:hal9000@hypermetrics.com) Project contributors:: Nolan Darilek, Jason Johnston Thanks to Hal Fulton for hosting the Codefest. Thanks to Matz for suggestions about the class design. Thanks to Gavin Sinclair for some feedback on the documentation. The text for parts of this document, especially the Description and Conversions sections, above, were adapted from the Linux Programmer's Manual manpage for scanf(3), dated 1995-11-01. ==Bugs and bug reports scanf for Ruby is based on something of an amalgam of C scanf implementations and documentation, rather than on a single canonical description. Suggestions for features and behaviors which appear in other scanfs, and would be meaningful in Ruby, are welcome, as are reports of suspicious behaviors and/or bugs. (Please see "Credits and acknowledgements", above, for email addresses.) =end module Scanf class FormatSpecifier attr_reader :re_string, :matched_string, :conversion, :matched private def skip; /^\s*%\*/.match(@spec_string); end def extract_float(s); s.to_f if s &&! skip; end def extract_decimal(s); s.to_i if s &&! skip; end def extract_hex(s); s.hex if s &&! skip; end def extract_octal(s); s.oct if s &&! skip; end def extract_integer(s); Integer(s) if s &&! skip; end def extract_plain(s); s unless skip; end def nil_proc(s); nil; end public def to_s @spec_string end def count_space? /(?:\A|\S)%\*?\d*c|\[/.match(@spec_string) end def initialize(str) @spec_string = str h = '[A-Fa-f0-9]' @re_string, @handler = case @spec_string # %[[:...:]] when /%\*?(\[\[:[a-z]+:\]\])/ [ "(#{$1}+)", :extract_plain ] # %5[[:...:]] when /%\*?(\d+)(\[\[:[a-z]+:\]\])/ [ "(#{$2}{1,#{$1}})", :extract_plain ] # %[...] when /%\*?\[([^\]]*)\]/ yes = $1 if /^\^/.match(yes) then no = yes[1..-1] else no = '^' + yes end [ "([#{yes}]+)(?=[#{no}]|\\z)", :extract_plain ] # %5[...] when /%\*?(\d+)\[([^\]]*)\]/ yes = $2 w = $1 [ "([#{yes}]{1,#{w}})", :extract_plain ] # %i when /%\*?i/ [ "([-+]?(?:(?:0[0-7]+)|(?:0[Xx]#{h}+)|(?:[1-9]\\d*)))", :extract_integer ] # %5i when /%\*?(\d+)i/ n = $1.to_i s = "(" if n > 1 then s += "[1-9]\\d{1,#{n-1}}|" end if n > 1 then s += "0[0-7]{1,#{n-1}}|" end if n > 2 then s += "[-+]0[0-7]{1,#{n-2}}|" end if n > 2 then s += "[-+][1-9]\\d{1,#{n-2}}|" end if n > 2 then s += "0[Xx]#{h}{1,#{n-2}}|" end if n > 3 then s += "[-+]0[Xx]#{h}{1,#{n-3}}|" end s += "\\d" s += ")" [ s, :extract_integer ] # %d, %u when /%\*?[du]/ [ '([-+]?\d+)', :extract_decimal ] # %5d, %5u when /%\*?(\d+)[du]/ n = $1.to_i s = "(" if n > 1 then s += "[-+]\\d{1,#{n-1}}|" end s += "\\d{1,#{$1}})" [ s, :extract_decimal ] # %x when /%\*?[Xx]/ [ "([-+]?(?:0[Xx])?#{h}+)", :extract_hex ] # %5x when /%\*?(\d+)[Xx]/ n = $1.to_i s = "(" if n > 3 then s += "[-+]0[Xx]#{h}{1,#{n-3}}|" end if n > 2 then s += "0[Xx]#{h}{1,#{n-2}}|" end if n > 1 then s += "[-+]#{h}{1,#{n-1}}|" end s += "#{h}{1,#{n}}" s += ")" [ s, :extract_hex ] # %o when /%\*?o/ [ '([-+]?[0-7]+)', :extract_octal ] # %5o when /%\*?(\d+)o/ [ "([-+][0-7]{1,#{$1.to_i-1}}|[0-7]{1,#{$1}})", :extract_octal ] # %f when /%\*?f/ [ '([-+]?((\d+(?>(?=[^\d.]|$)))|(\d*(\.(\d*([eE][-+]?\d+)?)))))', :extract_float ] # %5f when /%\*?(\d+)f/ [ "(\\S{1,#{$1}})", :extract_float ] # %5s when /%\*?(\d+)s/ [ "(\\S{1,#{$1}})", :extract_plain ] # %s when /%\*?s/ [ '(\S+)', :extract_plain ] # %c when /\s%\*?c/ [ "\\s*(.)", :extract_plain ] # %c when /%\*?c/ [ "(.)", :extract_plain ] # %5c (whitespace issues are handled by the count_*_space? methods) when /%\*?(\d+)c/ [ "(.{1,#{$1}})", :extract_plain ] # %% when /%%/ [ '(\s*%)', :nil_proc ] # literal characters else [ "(#{Regexp.escape(@spec_string)})", :nil_proc ] end @re_string = '\A' + @re_string end def to_re Regexp.new(@re_string,Regexp::MULTILINE) end def match(str) @matched = false s = str.dup s.sub!(/\A\s+/,'') unless count_space? res = to_re.match(s) if res @conversion = send(@handler, res[1]) @matched_string = @conversion.to_s @matched = true end res end def letter /%\*?\d*([a-z\[])/.match(@spec_string).to_a[1] end def width w = /%\*?(\d+)/.match(@spec_string).to_a[1] w && w.to_i end def mid_match? return false unless @matched cc_no_width = letter == '[' &&! width c_or_cc_width = (letter == 'c' || letter == '[') && width width_left = c_or_cc_width && (matched_string.size < width) return width_left || cc_no_width end end class FormatString attr_reader :string_left, :last_spec_tried, :last_match_tried, :matched_count, :space SPECIFIERS = 'diuXxofeEgsc' REGEX = / # possible space, followed by... (?:\s* # percent sign, followed by... % # another percent sign, or... (?:%| # optional assignment suppression flag \*? # optional maximum field width \d* # named character class, ... (?:\[\[:\w+:\]\]| # traditional character class, or... \[[^\]]*\]| # specifier letter. [#{SPECIFIERS}])))| # or miscellaneous characters [^%\s]+/ix def initialize(str) @specs = [] @i = 1 s = str.to_s return unless /\S/.match(s) @space = true if /\s\z/.match(s) @specs.replace s.scan(REGEX).map {|spec| FormatSpecifier.new(spec) } end def to_s @specs.join('') end def prune(n=matched_count) n.times { @specs.shift } end def spec_count @specs.size end def last_spec @i == spec_count - 1 end def match(str) accum = [] @string_left = str @matched_count = 0 @specs.each_with_index do |spec,@i| @last_spec_tried = spec @last_match_tried = spec.match(@string_left) break unless @last_match_tried @matched_count += 1 accum << spec.conversion @string_left = @last_match_tried.post_match break if @string_left.empty? end return accum.compact end end end class IO # The trick here is doing a match where you grab one *line* # of input at a time. The linebreak may or may not occur # at the boundary where the string matches a format specifier. # And if it does, some rule about whitespace may or may not # be in effect... # # That's why this is much more elaborate than the string # version. # # For each line: # Match succeeds (non-emptily) # and the last attempted spec/string sub-match succeeded: # # could the last spec keep matching? # yes: save interim results and continue (next line) # # The last attempted spec/string did not match: # # are we on the next-to-last spec in the string? # yes: # is fmt_string.string_left all spaces? # yes: does current spec care about input space? # yes: fatal failure # no: save interim results and continue # no: continue [this state could be analyzed further] # # def scanf(str,&b) return block_scanf(str,&b) if b return [] unless str.size > 0 start_position = pos rescue 0 matched_so_far = 0 source_buffer = "" result_buffer = [] final_result = [] fstr = Scanf::FormatString.new(str) loop do if eof || (tty? &&! fstr.match(source_buffer)) final_result.concat(result_buffer) break end source_buffer << gets current_match = fstr.match(source_buffer) spec = fstr.last_spec_tried if spec.matched if spec.mid_match? result_buffer.replace(current_match) next end elsif (fstr.matched_count == fstr.spec_count - 1) if /\A\s*\z/.match(fstr.string_left) break if spec.count_space? result_buffer.replace(current_match) next end end final_result.concat(current_match) matched_so_far += source_buffer.size source_buffer.replace(fstr.string_left) matched_so_far -= source_buffer.size break if fstr.last_spec fstr.prune end seek(start_position + matched_so_far, IO::SEEK_SET) rescue Errno::ESPIPE soak_up_spaces if fstr.last_spec && fstr.space return final_result end private def soak_up_spaces c = getc ungetc(c) if c until eof ||! c || /\S/.match(c.chr) c = getc end ungetc(c) if (c && /\S/.match(c.chr)) end def block_scanf(str) final = [] # Sub-ideal, since another FS gets created in scanf. # But used here to determine the number of specifiers. fstr = Scanf::FormatString.new(str) last_spec = fstr.last_spec begin current = scanf(str) break if current.empty? final.push(yield(current)) end until eof || fstr.last_spec_tried == last_spec return final end end class String def scanf(fstr,&b) if b block_scanf(fstr,&b) else fs = if fstr.is_a? Scanf::FormatString fstr else Scanf::FormatString.new(fstr) end fs.match(self) end end def block_scanf(fstr,&b) fs = Scanf::FormatString.new(fstr) str = self.dup final = [] begin current = str.scanf(fs) final.push(yield(current)) unless current.empty? str = fs.string_left end until current.empty? || str.empty? return final end end module Kernel private def scanf(fs,&b) STDIN.scanf(fs,&b) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/mutex_m.rb
tools/jruby-1.5.1/lib/ruby/1.8/mutex_m.rb
#-- # mutex_m.rb - # $Release Version: 3.0$ # $Revision: 1.7 $ # $Date: 1998/02/27 04:28:57 $ # Original from mutex.rb # by Keiju ISHITSUKA(keiju@ishitsuka.com) # modified by matz # patched by akira yamada #++ # # == Usage # # Extend an object and use it like a Mutex object: # # require "mutex_m.rb" # obj = Object.new # obj.extend Mutex_m # # ... # # Or, include Mutex_m in a class to have its instances behave like a Mutex # object: # # class Foo # include Mutex_m # # ... # end # # obj = Foo.new module Mutex_m def Mutex_m.define_aliases(cl) cl.module_eval %q{ alias locked? mu_locked? alias lock mu_lock alias unlock mu_unlock alias try_lock mu_try_lock alias synchronize mu_synchronize } end def Mutex_m.append_features(cl) super define_aliases(cl) unless cl.instance_of?(Module) end def Mutex_m.extend_object(obj) super obj.mu_extended end def mu_extended unless (defined? locked? and defined? lock and defined? unlock and defined? try_lock and defined? synchronize) Mutex_m.define_aliases(class<<self;self;end) end mu_initialize end # locking def mu_synchronize begin mu_lock yield ensure mu_unlock end end def mu_locked? @mu_locked end def mu_try_lock result = false Thread.critical = true unless @mu_locked @mu_locked = true result = true end Thread.critical = false result end def mu_lock while (Thread.critical = true; @mu_locked) @mu_waiting.push Thread.current Thread.stop end @mu_locked = true Thread.critical = false self end def mu_unlock return unless @mu_locked Thread.critical = true wait = @mu_waiting @mu_waiting = [] @mu_locked = false Thread.critical = false for w in wait w.run end self end private def mu_initialize @mu_waiting = [] @mu_locked = false; end def initialize(*args) mu_initialize super end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/cgi.rb
tools/jruby-1.5.1/lib/ruby/1.8/cgi.rb
# # cgi.rb - cgi support library # # Copyright (C) 2000 Network Applied Communication Laboratory, Inc. # # Copyright (C) 2000 Information-technology Promotion Agency, Japan # # Author: Wakou Aoyama <wakou@ruby-lang.org> # # Documentation: Wakou Aoyama (RDoc'd and embellished by William Webber) # # == Overview # # The Common Gateway Interface (CGI) is a simple protocol # for passing an HTTP request from a web server to a # standalone program, and returning the output to the web # browser. Basically, a CGI program is called with the # parameters of the request passed in either in the # environment (GET) or via $stdin (POST), and everything # it prints to $stdout is returned to the client. # # This file holds the +CGI+ class. This class provides # functionality for retrieving HTTP request parameters, # managing cookies, and generating HTML output. See the # class documentation for more details and examples of use. # # The file cgi/session.rb provides session management # functionality; see that file for more details. # # See http://www.w3.org/CGI/ for more information on the CGI # protocol. raise "Please, use ruby 1.5.4 or later." if RUBY_VERSION < "1.5.4" require 'English' # CGI class. See documentation for the file cgi.rb for an overview # of the CGI protocol. # # == Introduction # # CGI is a large class, providing several categories of methods, many of which # are mixed in from other modules. Some of the documentation is in this class, # some in the modules CGI::QueryExtension and CGI::HtmlExtension. See # CGI::Cookie for specific information on handling cookies, and cgi/session.rb # (CGI::Session) for information on sessions. # # For queries, CGI provides methods to get at environmental variables, # parameters, cookies, and multipart request data. For responses, CGI provides # methods for writing output and generating HTML. # # Read on for more details. Examples are provided at the bottom. # # == Queries # # The CGI class dynamically mixes in parameter and cookie-parsing # functionality, environmental variable access, and support for # parsing multipart requests (including uploaded files) from the # CGI::QueryExtension module. # # === Environmental Variables # # The standard CGI environmental variables are available as read-only # attributes of a CGI object. The following is a list of these variables: # # # AUTH_TYPE HTTP_HOST REMOTE_IDENT # CONTENT_LENGTH HTTP_NEGOTIATE REMOTE_USER # CONTENT_TYPE HTTP_PRAGMA REQUEST_METHOD # GATEWAY_INTERFACE HTTP_REFERER SCRIPT_NAME # HTTP_ACCEPT HTTP_USER_AGENT SERVER_NAME # HTTP_ACCEPT_CHARSET PATH_INFO SERVER_PORT # HTTP_ACCEPT_ENCODING PATH_TRANSLATED SERVER_PROTOCOL # HTTP_ACCEPT_LANGUAGE QUERY_STRING SERVER_SOFTWARE # HTTP_CACHE_CONTROL REMOTE_ADDR # HTTP_FROM REMOTE_HOST # # # For each of these variables, there is a corresponding attribute with the # same name, except all lower case and without a preceding HTTP_. # +content_length+ and +server_port+ are integers; the rest are strings. # # === Parameters # # The method #params() returns a hash of all parameters in the request as # name/value-list pairs, where the value-list is an Array of one or more # values. The CGI object itself also behaves as a hash of parameter names # to values, but only returns a single value (as a String) for each # parameter name. # # For instance, suppose the request contains the parameter # "favourite_colours" with the multiple values "blue" and "green". The # following behaviour would occur: # # cgi.params["favourite_colours"] # => ["blue", "green"] # cgi["favourite_colours"] # => "blue" # # If a parameter does not exist, the former method will return an empty # array, the latter an empty string. The simplest way to test for existence # of a parameter is by the #has_key? method. # # === Cookies # # HTTP Cookies are automatically parsed from the request. They are available # from the #cookies() accessor, which returns a hash from cookie name to # CGI::Cookie object. # # === Multipart requests # # If a request's method is POST and its content type is multipart/form-data, # then it may contain uploaded files. These are stored by the QueryExtension # module in the parameters of the request. The parameter name is the name # attribute of the file input field, as usual. However, the value is not # a string, but an IO object, either an IOString for small files, or a # Tempfile for larger ones. This object also has the additional singleton # methods: # # #local_path():: the path of the uploaded file on the local filesystem # #original_filename():: the name of the file on the client computer # #content_type():: the content type of the file # # == Responses # # The CGI class provides methods for sending header and content output to # the HTTP client, and mixes in methods for programmatic HTML generation # from CGI::HtmlExtension and CGI::TagMaker modules. The precise version of HTML # to use for HTML generation is specified at object creation time. # # === Writing output # # The simplest way to send output to the HTTP client is using the #out() method. # This takes the HTTP headers as a hash parameter, and the body content # via a block. The headers can be generated as a string using the #header() # method. The output stream can be written directly to using the #print() # method. # # === Generating HTML # # Each HTML element has a corresponding method for generating that # element as a String. The name of this method is the same as that # of the element, all lowercase. The attributes of the element are # passed in as a hash, and the body as a no-argument block that evaluates # to a String. The HTML generation module knows which elements are # always empty, and silently drops any passed-in body. It also knows # which elements require matching closing tags and which don't. However, # it does not know what attributes are legal for which elements. # # There are also some additional HTML generation methods mixed in from # the CGI::HtmlExtension module. These include individual methods for the # different types of form inputs, and methods for elements that commonly # take particular attributes where the attributes can be directly specified # as arguments, rather than via a hash. # # == Examples of use # # === Get form values # # require "cgi" # cgi = CGI.new # value = cgi['field_name'] # <== value string for 'field_name' # # if not 'field_name' included, then return "". # fields = cgi.keys # <== array of field names # # # returns true if form has 'field_name' # cgi.has_key?('field_name') # cgi.has_key?('field_name') # cgi.include?('field_name') # # CAUTION! cgi['field_name'] returned an Array with the old # cgi.rb(included in ruby 1.6) # # === Get form values as hash # # require "cgi" # cgi = CGI.new # params = cgi.params # # cgi.params is a hash. # # cgi.params['new_field_name'] = ["value"] # add new param # cgi.params['field_name'] = ["new_value"] # change value # cgi.params.delete('field_name') # delete param # cgi.params.clear # delete all params # # # === Save form values to file # # require "pstore" # db = PStore.new("query.db") # db.transaction do # db["params"] = cgi.params # end # # # === Restore form values from file # # require "pstore" # db = PStore.new("query.db") # db.transaction do # cgi.params = db["params"] # end # # # === Get multipart form values # # require "cgi" # cgi = CGI.new # value = cgi['field_name'] # <== value string for 'field_name' # value.read # <== body of value # value.local_path # <== path to local file of value # value.original_filename # <== original filename of value # value.content_type # <== content_type of value # # and value has StringIO or Tempfile class methods. # # === Get cookie values # # require "cgi" # cgi = CGI.new # values = cgi.cookies['name'] # <== array of 'name' # # if not 'name' included, then return []. # names = cgi.cookies.keys # <== array of cookie names # # and cgi.cookies is a hash. # # === Get cookie objects # # require "cgi" # cgi = CGI.new # for name, cookie in cgi.cookies # cookie.expires = Time.now + 30 # end # cgi.out("cookie" => cgi.cookies) {"string"} # # cgi.cookies # { "name1" => cookie1, "name2" => cookie2, ... } # # require "cgi" # cgi = CGI.new # cgi.cookies['name'].expires = Time.now + 30 # cgi.out("cookie" => cgi.cookies['name']) {"string"} # # === Print http header and html string to $DEFAULT_OUTPUT ($>) # # require "cgi" # cgi = CGI.new("html3") # add HTML generation methods # cgi.out() do # cgi.html() do # cgi.head{ cgi.title{"TITLE"} } + # cgi.body() do # cgi.form() do # cgi.textarea("get_text") + # cgi.br + # cgi.submit # end + # cgi.pre() do # CGI::escapeHTML( # "params: " + cgi.params.inspect + "\n" + # "cookies: " + cgi.cookies.inspect + "\n" + # ENV.collect() do |key, value| # key + " --> " + value + "\n" # end.join("") # ) # end # end # end # end # # # add HTML generation methods # CGI.new("html3") # html3.2 # CGI.new("html4") # html4.01 (Strict) # CGI.new("html4Tr") # html4.01 Transitional # CGI.new("html4Fr") # html4.01 Frameset # class CGI # :stopdoc: # String for carriage return CR = "\015" # String for linefeed LF = "\012" # Standard internet newline sequence EOL = CR + LF REVISION = '$Id: cgi.rb 26086 2009-12-14 02:40:07Z shyouhei $' #:nodoc: NEEDS_BINMODE = true if /WIN/ni.match(RUBY_PLATFORM) # Path separators in different environments. PATH_SEPARATOR = {'UNIX'=>'/', 'WINDOWS'=>'\\', 'MACINTOSH'=>':'} # HTTP status codes. HTTP_STATUS = { "OK" => "200 OK", "PARTIAL_CONTENT" => "206 Partial Content", "MULTIPLE_CHOICES" => "300 Multiple Choices", "MOVED" => "301 Moved Permanently", "REDIRECT" => "302 Found", "NOT_MODIFIED" => "304 Not Modified", "BAD_REQUEST" => "400 Bad Request", "AUTH_REQUIRED" => "401 Authorization Required", "FORBIDDEN" => "403 Forbidden", "NOT_FOUND" => "404 Not Found", "METHOD_NOT_ALLOWED" => "405 Method Not Allowed", "NOT_ACCEPTABLE" => "406 Not Acceptable", "LENGTH_REQUIRED" => "411 Length Required", "PRECONDITION_FAILED" => "412 Precondition Failed", "SERVER_ERROR" => "500 Internal Server Error", "NOT_IMPLEMENTED" => "501 Method Not Implemented", "BAD_GATEWAY" => "502 Bad Gateway", "VARIANT_ALSO_VARIES" => "506 Variant Also Negotiates" } # Abbreviated day-of-week names specified by RFC 822 RFC822_DAYS = %w[ Sun Mon Tue Wed Thu Fri Sat ] # Abbreviated month names specified by RFC 822 RFC822_MONTHS = %w[ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ] # :startdoc: def env_table ENV end def stdinput $stdin end def stdoutput $DEFAULT_OUTPUT end private :env_table, :stdinput, :stdoutput # URL-encode a string. # url_encoded_string = CGI::escape("'Stop!' said Fred") # # => "%27Stop%21%27+said+Fred" def CGI::escape(string) string.gsub(/([^ a-zA-Z0-9_.-]+)/n) do '%' + $1.unpack('H2' * $1.size).join('%').upcase end.tr(' ', '+') end # URL-decode a string. # string = CGI::unescape("%27Stop%21%27+said+Fred") # # => "'Stop!' said Fred" def CGI::unescape(string) string.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n) do [$1.delete('%')].pack('H*') end end # Escape special characters in HTML, namely &\"<> # CGI::escapeHTML('Usage: foo "bar" <baz>') # # => "Usage: foo &quot;bar&quot; &lt;baz&gt;" def CGI::escapeHTML(string) string.gsub(/&/n, '&amp;').gsub(/\"/n, '&quot;').gsub(/>/n, '&gt;').gsub(/</n, '&lt;') end # Unescape a string that has been HTML-escaped # CGI::unescapeHTML("Usage: foo &quot;bar&quot; &lt;baz&gt;") # # => "Usage: foo \"bar\" <baz>" def CGI::unescapeHTML(string) string.gsub(/&(amp|quot|gt|lt|\#[0-9]+|\#x[0-9A-Fa-f]+);/n) do match = $1.dup case match when 'amp' then '&' when 'quot' then '"' when 'gt' then '>' when 'lt' then '<' when /\A#0*(\d+)\z/n then if Integer($1) < 256 Integer($1).chr else if Integer($1) < 65536 and ($KCODE[0] == ?u or $KCODE[0] == ?U) [Integer($1)].pack("U") else "&##{$1};" end end when /\A#x([0-9a-f]+)\z/ni then if $1.hex < 128 $1.hex.chr else if $1.hex < 65536 and ($KCODE[0] == ?u or $KCODE[0] == ?U) [$1.hex].pack("U") else "&#x#{$1};" end end else "&#{match};" end end end # Escape only the tags of certain HTML elements in +string+. # # Takes an element or elements or array of elements. Each element # is specified by the name of the element, without angle brackets. # This matches both the start and the end tag of that element. # The attribute list of the open tag will also be escaped (for # instance, the double-quotes surrounding attribute values). # # print CGI::escapeElement('<BR><A HREF="url"></A>', "A", "IMG") # # "<BR>&lt;A HREF=&quot;url&quot;&gt;&lt;/A&gt" # # print CGI::escapeElement('<BR><A HREF="url"></A>', ["A", "IMG"]) # # "<BR>&lt;A HREF=&quot;url&quot;&gt;&lt;/A&gt" def CGI::escapeElement(string, *elements) elements = elements[0] if elements[0].kind_of?(Array) unless elements.empty? string.gsub(/<\/?(?:#{elements.join("|")})(?!\w)(?:.|\n)*?>/ni) do CGI::escapeHTML($&) end else string end end # Undo escaping such as that done by CGI::escapeElement() # # print CGI::unescapeElement( # CGI::escapeHTML('<BR><A HREF="url"></A>'), "A", "IMG") # # "&lt;BR&gt;<A HREF="url"></A>" # # print CGI::unescapeElement( # CGI::escapeHTML('<BR><A HREF="url"></A>'), ["A", "IMG"]) # # "&lt;BR&gt;<A HREF="url"></A>" def CGI::unescapeElement(string, *elements) elements = elements[0] if elements[0].kind_of?(Array) unless elements.empty? string.gsub(/&lt;\/?(?:#{elements.join("|")})(?!\w)(?:.|\n)*?&gt;/ni) do CGI::unescapeHTML($&) end else string end end # Format a +Time+ object as a String using the format specified by RFC 1123. # # CGI::rfc1123_date(Time.now) # # Sat, 01 Jan 2000 00:00:00 GMT def CGI::rfc1123_date(time) t = time.clone.gmtime return format("%s, %.2d %s %.4d %.2d:%.2d:%.2d GMT", RFC822_DAYS[t.wday], t.day, RFC822_MONTHS[t.month-1], t.year, t.hour, t.min, t.sec) end # Create an HTTP header block as a string. # # Includes the empty line that ends the header block. # # +options+ can be a string specifying the Content-Type (defaults # to text/html), or a hash of header key/value pairs. The following # header keys are recognized: # # type:: the Content-Type header. Defaults to "text/html" # charset:: the charset of the body, appended to the Content-Type header. # nph:: a boolean value. If true, prepend protocol string and status code, and # date; and sets default values for "server" and "connection" if not # explicitly set. # status:: the HTTP status code, returned as the Status header. See the # list of available status codes below. # server:: the server software, returned as the Server header. # connection:: the connection type, returned as the Connection header (for # instance, "close". # length:: the length of the content that will be sent, returned as the # Content-Length header. # language:: the language of the content, returned as the Content-Language # header. # expires:: the time on which the current content expires, as a +Time+ # object, returned as the Expires header. # cookie:: a cookie or cookies, returned as one or more Set-Cookie headers. # The value can be the literal string of the cookie; a CGI::Cookie # object; an Array of literal cookie strings or Cookie objects; or a # hash all of whose values are literal cookie strings or Cookie objects. # These cookies are in addition to the cookies held in the # @output_cookies field. # # Other header lines can also be set; they are appended as key: value. # # header # # Content-Type: text/html # # header("text/plain") # # Content-Type: text/plain # # header("nph" => true, # "status" => "OK", # == "200 OK" # # "status" => "200 GOOD", # "server" => ENV['SERVER_SOFTWARE'], # "connection" => "close", # "type" => "text/html", # "charset" => "iso-2022-jp", # # Content-Type: text/html; charset=iso-2022-jp # "length" => 103, # "language" => "ja", # "expires" => Time.now + 30, # "cookie" => [cookie1, cookie2], # "my_header1" => "my_value" # "my_header2" => "my_value") # # The status codes are: # # "OK" --> "200 OK" # "PARTIAL_CONTENT" --> "206 Partial Content" # "MULTIPLE_CHOICES" --> "300 Multiple Choices" # "MOVED" --> "301 Moved Permanently" # "REDIRECT" --> "302 Found" # "NOT_MODIFIED" --> "304 Not Modified" # "BAD_REQUEST" --> "400 Bad Request" # "AUTH_REQUIRED" --> "401 Authorization Required" # "FORBIDDEN" --> "403 Forbidden" # "NOT_FOUND" --> "404 Not Found" # "METHOD_NOT_ALLOWED" --> "405 Method Not Allowed" # "NOT_ACCEPTABLE" --> "406 Not Acceptable" # "LENGTH_REQUIRED" --> "411 Length Required" # "PRECONDITION_FAILED" --> "412 Precondition Failed" # "SERVER_ERROR" --> "500 Internal Server Error" # "NOT_IMPLEMENTED" --> "501 Method Not Implemented" # "BAD_GATEWAY" --> "502 Bad Gateway" # "VARIANT_ALSO_VARIES" --> "506 Variant Also Negotiates" # # This method does not perform charset conversion. # def header(options = "text/html") buf = "" case options when String options = { "type" => options } when Hash options = options.dup end unless options.has_key?("type") options["type"] = "text/html" end if options.has_key?("charset") options["type"] += "; charset=" + options.delete("charset") end options.delete("nph") if defined?(MOD_RUBY) if options.delete("nph") or (/IIS\/(\d+)/n.match(env_table['SERVER_SOFTWARE']) and $1.to_i < 5) buf += (env_table["SERVER_PROTOCOL"] or "HTTP/1.0") + " " + (HTTP_STATUS[options["status"]] or options["status"] or "200 OK") + EOL + "Date: " + CGI::rfc1123_date(Time.now) + EOL unless options.has_key?("server") options["server"] = (env_table['SERVER_SOFTWARE'] or "") end unless options.has_key?("connection") options["connection"] = "close" end options.delete("status") end if options.has_key?("status") buf += "Status: " + (HTTP_STATUS[options["status"]] or options["status"]) + EOL options.delete("status") end if options.has_key?("server") buf += "Server: " + options.delete("server") + EOL end if options.has_key?("connection") buf += "Connection: " + options.delete("connection") + EOL end buf += "Content-Type: " + options.delete("type") + EOL if options.has_key?("length") buf += "Content-Length: " + options.delete("length").to_s + EOL end if options.has_key?("language") buf += "Content-Language: " + options.delete("language") + EOL end if options.has_key?("expires") buf += "Expires: " + CGI::rfc1123_date( options.delete("expires") ) + EOL end if options.has_key?("cookie") if options["cookie"].kind_of?(String) or options["cookie"].kind_of?(Cookie) buf += "Set-Cookie: " + options.delete("cookie").to_s + EOL elsif options["cookie"].kind_of?(Array) options.delete("cookie").each{|cookie| buf += "Set-Cookie: " + cookie.to_s + EOL } elsif options["cookie"].kind_of?(Hash) options.delete("cookie").each_value{|cookie| buf += "Set-Cookie: " + cookie.to_s + EOL } end end if @output_cookies for cookie in @output_cookies buf += "Set-Cookie: " + cookie.to_s + EOL end end options.each{|key, value| buf += key + ": " + value.to_s + EOL } if defined?(MOD_RUBY) table = Apache::request.headers_out buf.scan(/([^:]+): (.+)#{EOL}/n){ |name, value| warn sprintf("name:%s value:%s\n", name, value) if $DEBUG case name when 'Set-Cookie' table.add(name, value) when /^status$/ni Apache::request.status_line = value Apache::request.status = value.to_i when /^content-type$/ni Apache::request.content_type = value when /^content-encoding$/ni Apache::request.content_encoding = value when /^location$/ni if Apache::request.status == 200 Apache::request.status = 302 end Apache::request.headers_out[name] = value else Apache::request.headers_out[name] = value end } Apache::request.send_http_header '' else buf + EOL end end # header() # Print an HTTP header and body to $DEFAULT_OUTPUT ($>) # # The header is provided by +options+, as for #header(). # The body of the document is that returned by the passed- # in block. This block takes no arguments. It is required. # # cgi = CGI.new # cgi.out{ "string" } # # Content-Type: text/html # # Content-Length: 6 # # # # string # # cgi.out("text/plain") { "string" } # # Content-Type: text/plain # # Content-Length: 6 # # # # string # # cgi.out("nph" => true, # "status" => "OK", # == "200 OK" # "server" => ENV['SERVER_SOFTWARE'], # "connection" => "close", # "type" => "text/html", # "charset" => "iso-2022-jp", # # Content-Type: text/html; charset=iso-2022-jp # "language" => "ja", # "expires" => Time.now + (3600 * 24 * 30), # "cookie" => [cookie1, cookie2], # "my_header1" => "my_value", # "my_header2" => "my_value") { "string" } # # Content-Length is automatically calculated from the size of # the String returned by the content block. # # If ENV['REQUEST_METHOD'] == "HEAD", then only the header # is outputted (the content block is still required, but it # is ignored). # # If the charset is "iso-2022-jp" or "euc-jp" or "shift_jis" then # the content is converted to this charset, and the language is set # to "ja". def out(options = "text/html") # :yield: options = { "type" => options } if options.kind_of?(String) content = yield if options.has_key?("charset") require "nkf" case options["charset"] when /iso-2022-jp/ni content = NKF::nkf('-m0 -x -j', content) options["language"] = "ja" unless options.has_key?("language") when /euc-jp/ni content = NKF::nkf('-m0 -x -e', content) options["language"] = "ja" unless options.has_key?("language") when /shift_jis/ni content = NKF::nkf('-m0 -x -s', content) options["language"] = "ja" unless options.has_key?("language") end end options["length"] = content.length.to_s output = stdoutput output.binmode if defined? output.binmode output.print header(options) output.print content unless "HEAD" == env_table['REQUEST_METHOD'] end # Print an argument or list of arguments to the default output stream # # cgi = CGI.new # cgi.print # default: cgi.print == $DEFAULT_OUTPUT.print def print(*options) stdoutput.print(*options) end require "delegate" # Class representing an HTTP cookie. # # In addition to its specific fields and methods, a Cookie instance # is a delegator to the array of its values. # # See RFC 2965. # # == Examples of use # cookie1 = CGI::Cookie::new("name", "value1", "value2", ...) # cookie1 = CGI::Cookie::new("name" => "name", "value" => "value") # cookie1 = CGI::Cookie::new('name' => 'name', # 'value' => ['value1', 'value2', ...], # 'path' => 'path', # optional # 'domain' => 'domain', # optional # 'expires' => Time.now, # optional # 'secure' => true # optional # ) # # cgi.out("cookie" => [cookie1, cookie2]) { "string" } # # name = cookie1.name # values = cookie1.value # path = cookie1.path # domain = cookie1.domain # expires = cookie1.expires # secure = cookie1.secure # # cookie1.name = 'name' # cookie1.value = ['value1', 'value2', ...] # cookie1.path = 'path' # cookie1.domain = 'domain' # cookie1.expires = Time.now + 30 # cookie1.secure = true class Cookie < DelegateClass(Array) # Create a new CGI::Cookie object. # # The contents of the cookie can be specified as a +name+ and one # or more +value+ arguments. Alternatively, the contents can # be specified as a single hash argument. The possible keywords of # this hash are as follows: # # name:: the name of the cookie. Required. # value:: the cookie's value or list of values. # path:: the path for which this cookie applies. Defaults to the # base directory of the CGI script. # domain:: the domain for which this cookie applies. # expires:: the time at which this cookie expires, as a +Time+ object. # secure:: whether this cookie is a secure cookie or not (default to # false). Secure cookies are only transmitted to HTTPS # servers. # # These keywords correspond to attributes of the cookie object. def initialize(name = "", *value) if name.kind_of?(String) @name = name @value = value %r|^(.*/)|.match(ENV["SCRIPT_NAME"]) @path = ($1 or "") @secure = false return super(@value) end options = name unless options.has_key?("name") raise ArgumentError, "`name' required" end @name = options["name"] @value = Array(options["value"]) # simple support for IE if options["path"] @path = options["path"] else %r|^(.*/)|.match(ENV["SCRIPT_NAME"]) @path = ($1 or "") end @domain = options["domain"] @expires = options["expires"] @secure = options["secure"] == true ? true : false super(@value) end attr_accessor("name", "path", "domain", "expires") attr_reader("secure", "value") # Set whether the Cookie is a secure cookie or not. # # +val+ must be a boolean. def secure=(val) @secure = val if val == true or val == false @secure end def value=(val) @value.replace(Array(val)) end # Convert the Cookie to its string representation. def to_s buf = "" buf += @name + '=' buf += @value.map { |v| CGI::escape(v) }.join("&") if @domain buf += '; domain=' + @domain end if @path buf += '; path=' + @path end if @expires buf += '; expires=' + CGI::rfc1123_date(@expires) end if @secure == true buf += '; secure' end buf end end # class Cookie # Parse a raw cookie string into a hash of cookie-name=>Cookie # pairs. # # cookies = CGI::Cookie::parse("raw_cookie_string") # # { "name1" => cookie1, "name2" => cookie2, ... } # def Cookie::parse(raw_cookie) cookies = Hash.new([]) return cookies unless raw_cookie raw_cookie.split(/[;,]\s?/).each do |pairs| name, values = pairs.split('=',2) next unless name and values name = CGI::unescape(name) values ||= "" values = values.split('&').collect{|v| CGI::unescape(v) } if cookies.has_key?(name) values = cookies[name].value + values end cookies[name] = Cookie::new(name, *values) end cookies end # Parse an HTTP query string into a hash of key=>value pairs. # # params = CGI::parse("query_string") # # {"name1" => ["value1", "value2", ...], # # "name2" => ["value1", "value2", ...], ... } # def CGI::parse(query) params = Hash.new([].freeze) query.split(/[&;]/n).each do |pairs| key, value = pairs.split('=',2).collect{|v| CGI::unescape(v) } if params.has_key?(key) params[key].push(value) else params[key] = [value] end end params end # Mixin module. It provides the follow functionality groups: # # 1. Access to CGI environment variables as methods. See # documentation to the CGI class for a list of these variables. # # 2. Access to cookies, including the cookies attribute. # # 3. Access to parameters, including the params attribute, and overloading # [] to perform parameter value lookup by key. # # 4. The initialize_query method, for initialising the above # mechanisms, handling multipart forms, and allowing the # class to be used in "offline" mode. # module QueryExtension %w[ CONTENT_LENGTH SERVER_PORT ].each do |env| define_method(env.sub(/^HTTP_/n, '').downcase) do (val = env_table[env]) && Integer(val) end end %w[ AUTH_TYPE CONTENT_TYPE GATEWAY_INTERFACE PATH_INFO PATH_TRANSLATED QUERY_STRING REMOTE_ADDR REMOTE_HOST REMOTE_IDENT REMOTE_USER REQUEST_METHOD SCRIPT_NAME SERVER_NAME SERVER_PROTOCOL SERVER_SOFTWARE HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING HTTP_ACCEPT_LANGUAGE HTTP_CACHE_CONTROL HTTP_FROM HTTP_HOST HTTP_NEGOTIATE HTTP_PRAGMA HTTP_REFERER HTTP_USER_AGENT ].each do |env| define_method(env.sub(/^HTTP_/n, '').downcase) do env_table[env] end end # Get the raw cookies as a string. def raw_cookie env_table["HTTP_COOKIE"] end # Get the raw RFC2965 cookies as a string. def raw_cookie2 env_table["HTTP_COOKIE2"] end # Get the cookies as a hash of cookie-name=>Cookie pairs. attr_accessor("cookies") # Get the parameters as a hash of name=>values pairs, where # values is an Array. attr("params") # Set all the parameters. def params=(hash) @params.clear @params.update(hash) end def read_multipart(boundary, content_length) params = Hash.new([]) boundary = "--" + boundary quoted_boundary = Regexp.quote(boundary, "n") buf = "" bufsize = 10 * 1024 boundary_end="" # start multipart/form-data stdinput.binmode if defined? stdinput.binmode boundary_size = boundary.size + EOL.size content_length -= boundary_size status = stdinput.read(boundary_size) if nil == status raise EOFError, "no content body" elsif boundary + EOL != status raise EOFError, "bad content body" end loop do head = nil if 10240 < content_length require "tempfile" body = Tempfile.new("CGI") else begin require "stringio" body = StringIO.new rescue LoadError require "tempfile" body = Tempfile.new("CGI") end end body.binmode if defined? body.binmode until head and /#{quoted_boundary}(?:#{EOL}|--)/n.match(buf)
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
true
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/tmpdir.rb
tools/jruby-1.5.1/lib/ruby/1.8/tmpdir.rb
# # tmpdir - retrieve temporary directory path # # $Id: tmpdir.rb 21776 2009-01-26 02:12:10Z shyouhei $ # require 'fileutils' class Dir @@systmpdir = '/tmp' begin require 'Win32API' CSIDL_LOCAL_APPDATA = 0x001c max_pathlen = 260 windir = "\0"*(max_pathlen+1) begin getdir = Win32API.new('shell32', 'SHGetFolderPath', 'LLLLP', 'L') raise RuntimeError if getdir.call(0, CSIDL_LOCAL_APPDATA, 0, 0, windir) != 0 windir = File.expand_path(windir.rstrip) rescue RuntimeError begin getdir = Win32API.new('kernel32', 'GetSystemWindowsDirectory', 'PL', 'L') rescue RuntimeError getdir = Win32API.new('kernel32', 'GetWindowsDirectory', 'PL', 'L') end len = getdir.call(windir, windir.size) windir = File.expand_path(windir[0, len]) end temp = File.join(windir.untaint, 'temp') @@systmpdir = temp if File.directory?(temp) and File.writable?(temp) rescue LoadError end ## # Returns the operating system's temporary file path. def Dir::tmpdir tmp = '.' if $SAFE > 0 tmp = @@systmpdir else for dir in [ENV['TMPDIR'], ENV['TMP'], ENV['TEMP'], ENV['USERPROFILE'], @@systmpdir, '/tmp'] if dir and File.directory?(dir) and File.writable?(dir) tmp = dir break end end File.expand_path(tmp) end end # Dir.mktmpdir creates a temporary directory. # # The directory is created with 0700 permission. # # The prefix and suffix of the name of the directory is specified by # the optional first argument, <i>prefix_suffix</i>. # - If it is not specified or nil, "d" is used as the prefix and no suffix is used. # - If it is a string, it is used as the prefix and no suffix is used. # - If it is an array, first element is used as the prefix and second element is used as a suffix. # # Dir.mktmpdir {|dir| dir is ".../d..." } # Dir.mktmpdir("foo") {|dir| dir is ".../foo..." } # Dir.mktmpdir(["foo", "bar"]) {|dir| dir is ".../foo...bar" } # # The directory is created under Dir.tmpdir or # the optional second argument <i>tmpdir</i> if non-nil value is given. # # Dir.mktmpdir {|dir| dir is "#{Dir.tmpdir}/d..." } # Dir.mktmpdir(nil, "/var/tmp") {|dir| dir is "/var/tmp/d..." } # # If a block is given, # it is yielded with the path of the directory. # The directory and its contents are removed # using FileUtils.remove_entry_secure before Dir.mktmpdir returns. # The value of the block is returned. # # Dir.mktmpdir {|dir| # # use the directory... # open("#{dir}/foo", "w") { ... } # } # # If a block is not given, # The path of the directory is returned. # In this case, Dir.mktmpdir doesn't remove the directory. # # dir = Dir.mktmpdir # begin # # use the directory... # open("#{dir}/foo", "w") { ... } # ensure # # remove the directory. # FileUtils.remove_entry_secure dir # end # def Dir.mktmpdir(prefix_suffix=nil, tmpdir=nil) case prefix_suffix when nil prefix = "d" suffix = "" when String prefix = prefix_suffix suffix = "" when Array prefix = prefix_suffix[0] suffix = prefix_suffix[1] else raise ArgumentError, "unexpected prefix_suffix: #{prefix_suffix.inspect}" end tmpdir ||= Dir.tmpdir t = Time.now.strftime("%Y%m%d") n = nil begin path = "#{tmpdir}/#{prefix}#{t}-#{$$}-#{rand(0x100000000).to_s(36)}" path << "-#{n}" if n path << suffix Dir.mkdir(path, 0700) rescue Errno::EEXIST n ||= 0 n += 1 retry end if block_given? begin yield path ensure FileUtils.remove_entry_secure path end else path end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rational.rb
tools/jruby-1.5.1/lib/ruby/1.8/rational.rb
# # rational.rb - # $Release Version: 0.5 $ # $Revision: 1.7 $ # $Date: 1999/08/24 12:49:28 $ # by Keiju ISHITSUKA(SHL Japan Inc.) # # Documentation by Kevin Jackson and Gavin Sinclair. # # When you <tt>require 'rational'</tt>, all interactions between numbers # potentially return a rational result. For example: # # 1.quo(2) # -> 0.5 # require 'rational' # 1.quo(2) # -> Rational(1,2) # # See Rational for full documentation. # # # Creates a Rational number (i.e. a fraction). +a+ and +b+ should be Integers: # # Rational(1,3) # -> 1/3 # # Note: trying to construct a Rational with floating point or real values # produces errors: # # Rational(1.1, 2.3) # -> NoMethodError # def Rational(a, b = 1) if a.kind_of?(Rational) && b == 1 a else Rational.reduce(a, b) end end # # Rational implements a rational class for numbers. # # <em>A rational number is a number that can be expressed as a fraction p/q # where p and q are integers and q != 0. A rational number p/q is said to have # numerator p and denominator q. Numbers that are not rational are called # irrational numbers.</em> (http://mathworld.wolfram.com/RationalNumber.html) # # To create a Rational Number: # Rational(a,b) # -> a/b # Rational.new!(a,b) # -> a/b # # Examples: # Rational(5,6) # -> 5/6 # Rational(5) # -> 5/1 # # Rational numbers are reduced to their lowest terms: # Rational(6,10) # -> 3/5 # # But not if you use the unusual method "new!": # Rational.new!(6,10) # -> 6/10 # # Division by zero is obviously not allowed: # Rational(3,0) # -> ZeroDivisionError # class Rational < Numeric @RCS_ID='-$Id: rational.rb,v 1.7 1999/08/24 12:49:28 keiju Exp keiju $-' # # Reduces the given numerator and denominator to their lowest terms. Use # Rational() instead. # def Rational.reduce(num, den = 1) raise ZeroDivisionError, "denominator is zero" if den == 0 if den < 0 num = -num den = -den end gcd = num.gcd(den) num = num.div(gcd) den = den.div(gcd) if den == 1 && defined?(Unify) num else new!(num, den) end end # # Implements the constructor. This method does not reduce to lowest terms or # check for division by zero. Therefore #Rational() should be preferred in # normal use. # def Rational.new!(num, den = 1) new(num, den) end private_class_method :new # # This method is actually private. # def initialize(num, den) if den < 0 num = -num den = -den end if num.kind_of?(Integer) and den.kind_of?(Integer) @numerator = num @denominator = den else @numerator = num.to_i @denominator = den.to_i end end # # Returns the addition of this value and +a+. # # Examples: # r = Rational(3,4) # -> Rational(3,4) # r + 1 # -> Rational(7,4) # r + 0.5 # -> 1.25 # def + (a) if a.kind_of?(Rational) num = @numerator * a.denominator num_a = a.numerator * @denominator Rational(num + num_a, @denominator * a.denominator) elsif a.kind_of?(Integer) self + Rational.new!(a, 1) elsif a.kind_of?(Float) Float(self) + a else x, y = a.coerce(self) x + y end end # # Returns the difference of this value and +a+. # subtracted. # # Examples: # r = Rational(3,4) # -> Rational(3,4) # r - 1 # -> Rational(-1,4) # r - 0.5 # -> 0.25 # def - (a) if a.kind_of?(Rational) num = @numerator * a.denominator num_a = a.numerator * @denominator Rational(num - num_a, @denominator*a.denominator) elsif a.kind_of?(Integer) self - Rational.new!(a, 1) elsif a.kind_of?(Float) Float(self) - a else x, y = a.coerce(self) x - y end end # # Returns the product of this value and +a+. # # Examples: # r = Rational(3,4) # -> Rational(3,4) # r * 2 # -> Rational(3,2) # r * 4 # -> Rational(3,1) # r * 0.5 # -> 0.375 # r * Rational(1,2) # -> Rational(3,8) # def * (a) if a.kind_of?(Rational) num = @numerator * a.numerator den = @denominator * a.denominator Rational(num, den) elsif a.kind_of?(Integer) self * Rational.new!(a, 1) elsif a.kind_of?(Float) Float(self) * a else x, y = a.coerce(self) x * y end end # # Returns the quotient of this value and +a+. # r = Rational(3,4) # -> Rational(3,4) # r / 2 # -> Rational(3,8) # r / 2.0 # -> 0.375 # r / Rational(1,2) # -> Rational(3,2) # def / (a) if a.kind_of?(Rational) num = @numerator * a.denominator den = @denominator * a.numerator Rational(num, den) elsif a.kind_of?(Integer) raise ZeroDivisionError, "division by zero" if a == 0 self / Rational.new!(a, 1) elsif a.kind_of?(Float) Float(self) / a else x, y = a.coerce(self) x / y end end # # Returns this value raised to the given power. # # Examples: # r = Rational(3,4) # -> Rational(3,4) # r ** 2 # -> Rational(9,16) # r ** 2.0 # -> 0.5625 # r ** Rational(1,2) # -> 0.866025403784439 # def ** (other) if other.kind_of?(Rational) Float(self) ** other elsif other.kind_of?(Integer) if other > 0 num = @numerator ** other den = @denominator ** other elsif other < 0 num = @denominator ** -other den = @numerator ** -other elsif other == 0 num = 1 den = 1 end Rational.new!(num, den) elsif other.kind_of?(Float) Float(self) ** other else x, y = other.coerce(self) x ** y end end def div(other) (self / other).floor end # # Returns the remainder when this value is divided by +other+. # # Examples: # r = Rational(7,4) # -> Rational(7,4) # r % Rational(1,2) # -> Rational(1,4) # r % 1 # -> Rational(3,4) # r % Rational(1,7) # -> Rational(1,28) # r % 0.26 # -> 0.19 # def % (other) value = (self / other).floor return self - other * value end # # Returns the quotient _and_ remainder. # # Examples: # r = Rational(7,4) # -> Rational(7,4) # r.divmod Rational(1,2) # -> [3, Rational(1,4)] # def divmod(other) value = (self / other).floor return value, self - other * value end # # Returns the absolute value. # def abs if @numerator > 0 self else Rational.new!(-@numerator, @denominator) end end # # Returns +true+ iff this value is numerically equal to +other+. # # But beware: # Rational(1,2) == Rational(4,8) # -> true # Rational(1,2) == Rational.new!(4,8) # -> false # # Don't use Rational.new! # def == (other) if other.kind_of?(Rational) @numerator == other.numerator and @denominator == other.denominator elsif other.kind_of?(Integer) self == Rational.new!(other, 1) elsif other.kind_of?(Float) Float(self) == other else other == self end end # # Standard comparison operator. # def <=> (other) if other.kind_of?(Rational) num = @numerator * other.denominator num_a = other.numerator * @denominator v = num - num_a if v > 0 return 1 elsif v < 0 return -1 else return 0 end elsif other.kind_of?(Integer) return self <=> Rational.new!(other, 1) elsif other.kind_of?(Float) return Float(self) <=> other elsif defined? other.coerce x, y = other.coerce(self) return x <=> y else return nil end end def coerce(other) if other.kind_of?(Float) return other, self.to_f elsif other.kind_of?(Integer) return Rational.new!(other, 1), self else super end end # # Converts the rational to an Integer. Not the _nearest_ integer, the # truncated integer. Study the following example carefully: # Rational(+7,4).to_i # -> 1 # Rational(-7,4).to_i # -> -1 # (-1.75).to_i # -> -1 # # In other words: # Rational(-7,4) == -1.75 # -> true # Rational(-7,4).to_i == (-1.75).to_i # -> true # def floor() @numerator.div(@denominator) end def ceil() -((-@numerator).div(@denominator)) end def truncate() if @numerator < 0 return -((-@numerator).div(@denominator)) end @numerator.div(@denominator) end alias_method :to_i, :truncate def round() if @numerator < 0 num = -@numerator num = num * 2 + @denominator den = @denominator * 2 -(num.div(den)) else num = @numerator * 2 + @denominator den = @denominator * 2 num.div(den) end end # # Converts the rational to a Float. # def to_f @numerator.to_f/@denominator.to_f end # # Returns a string representation of the rational number. # # Example: # Rational(3,4).to_s # "3/4" # Rational(8).to_s # "8" # def to_s if @denominator == 1 @numerator.to_s else @numerator.to_s+"/"+@denominator.to_s end end # # Returns +self+. # def to_r self end # # Returns a reconstructable string representation: # # Rational(5,8).inspect # -> "Rational(5, 8)" # def inspect sprintf("Rational(%s, %s)", @numerator.inspect, @denominator.inspect) end # # Returns a hash code for the object. # def hash @numerator.hash ^ @denominator.hash end attr :numerator attr :denominator private :initialize end class Integer # # In an integer, the value _is_ the numerator of its rational equivalent. # Therefore, this method returns +self+. # def numerator self end # # In an integer, the denominator is 1. Therefore, this method returns 1. # def denominator 1 end # # Returns a Rational representation of this integer. # def to_r Rational(self, 1) end # # Returns the <em>greatest common denominator</em> of the two numbers (+self+ # and +n+). # # Examples: # 72.gcd 168 # -> 24 # 19.gcd 36 # -> 1 # # The result is positive, no matter the sign of the arguments. # def gcd(other) min = self.abs max = other.abs while min > 0 tmp = min min = max % min max = tmp end max end # # Returns the <em>lowest common multiple</em> (LCM) of the two arguments # (+self+ and +other+). # # Examples: # 6.lcm 7 # -> 42 # 6.lcm 9 # -> 18 # def lcm(other) if self.zero? or other.zero? 0 else (self.div(self.gcd(other)) * other).abs end end # # Returns the GCD _and_ the LCM (see #gcd and #lcm) of the two arguments # (+self+ and +other+). This is more efficient than calculating them # separately. # # Example: # 6.gcdlcm 9 # -> [3, 18] # def gcdlcm(other) gcd = self.gcd(other) if self.zero? or other.zero? [gcd, 0] else [gcd, (self.div(gcd) * other).abs] end end end class Fixnum remove_method :quo # If Rational is defined, returns a Rational number instead of a Float. def quo(other) Rational.new!(self, 1) / other end alias rdiv quo # Returns a Rational number if the result is in fact rational (i.e. +other+ < 0). def rpower (other) if other >= 0 self.power!(other) else Rational.new!(self, 1)**other end end end class Bignum remove_method :quo # If Rational is defined, returns a Rational number instead of a Float. def quo(other) Rational.new!(self, 1) / other end alias rdiv quo # Returns a Rational number if the result is in fact rational (i.e. +other+ < 0). def rpower (other) if other >= 0 self.power!(other) else Rational.new!(self, 1)**other end end end unless defined? 1.power! class Fixnum alias power! ** alias ** rpower end class Bignum alias power! ** alias ** rpower end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/ipaddr.rb
tools/jruby-1.5.1/lib/ruby/1.8/ipaddr.rb
# # ipaddr.rb - A class to manipulate an IP address # # Copyright (c) 2002 Hajimu UMEMOTO <ume@mahoroba.org>. # Copyright (c) 2007 Akinori MUSHA <knu@iDaemons.org>. # All rights reserved. # # You can redistribute and/or modify it under the same terms as Ruby. # # $Id: ipaddr.rb 18049 2008-07-12 15:08:29Z shyouhei $ # # Contact: # - Akinori MUSHA <knu@iDaemons.org> (current maintainer) # # TODO: # - scope_id support # require 'socket' unless Socket.const_defined? "AF_INET6" class Socket AF_INET6 = Object.new end class << IPSocket def valid_v4?(addr) if /\A(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\Z/ =~ addr return $~.captures.all? {|i| i.to_i < 256} end return false end def valid_v6?(addr) # IPv6 (normal) return true if /\A[\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*\Z/ =~ addr return true if /\A[\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*::([\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*)?\Z/ =~ addr return true if /\A::([\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*)?\Z/ =~ addr # IPv6 (IPv4 compat) return true if /\A[\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*:/ =~ addr && valid_v4?($') return true if /\A[\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*::([\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*:)?/ =~ addr && valid_v4?($') return true if /\A::([\dA-Fa-f]{1,4}(:[\dA-Fa-f]{1,4})*:)?/ =~ addr && valid_v4?($') false end def valid?(addr) valid_v4?(addr) || valid_v6?(addr) end alias getaddress_orig getaddress def getaddress(s) if valid?(s) s elsif /\A[-A-Za-z\d.]+\Z/ =~ s getaddress_orig(s) else raise ArgumentError, "invalid address" end end end end # IPAddr provides a set of methods to manipulate an IP address. Both IPv4 and # IPv6 are supported. # # == Example # # require 'ipaddr' # # ipaddr1 = IPAddr.new "3ffe:505:2::1" # # p ipaddr1 #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0001/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff> # # p ipaddr1.to_s #=> "3ffe:505:2::1" # # ipaddr2 = ipaddr1.mask(48) #=> #<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0000/ffff:ffff:ffff:0000:0000:0000:0000:0000> # # p ipaddr2.to_s #=> "3ffe:505:2::" # # ipaddr3 = IPAddr.new "192.168.2.0/24" # # p ipaddr3 #=> #<IPAddr: IPv4:192.168.2.0/255.255.255.0> class IPAddr IN4MASK = 0xffffffff IN6MASK = 0xffffffffffffffffffffffffffffffff IN6FORMAT = (["%.4x"] * 8).join(':') # Returns the address family of this IP address. attr :family # Creates a new ipaddr containing the given network byte ordered # string form of an IP address. def IPAddr::new_ntoh(addr) return IPAddr.new(IPAddr::ntop(addr)) end # Convert a network byte ordered string form of an IP address into # human readable form. def IPAddr::ntop(addr) case addr.size when 4 s = addr.unpack('C4').join('.') when 16 s = IN6FORMAT % addr.unpack('n8') else raise ArgumentError, "unsupported address family" end return s end # Returns a new ipaddr built by bitwise AND. def &(other) return self.clone.set(@addr & coerce_other(other).to_i) end # Returns a new ipaddr built by bitwise OR. def |(other) return self.clone.set(@addr | coerce_other(other).to_i) end # Returns a new ipaddr built by bitwise right-shift. def >>(num) return self.clone.set(@addr >> num) end # Returns a new ipaddr built by bitwise left shift. def <<(num) return self.clone.set(addr_mask(@addr << num)) end # Returns a new ipaddr built by bitwise negation. def ~ return self.clone.set(addr_mask(~@addr)) end # Returns true if two ipaddrs are equal. def ==(other) other = coerce_other(other) return @family == other.family && @addr == other.to_i end # Returns a new ipaddr built by masking IP address with the given # prefixlen/netmask. (e.g. 8, 64, "255.255.255.0", etc.) def mask(prefixlen) return self.clone.mask!(prefixlen) end # Returns true if the given ipaddr is in the range. # # e.g.: # require 'ipaddr' # net1 = IPAddr.new("192.168.2.0/24") # net2 = IPAddr.new("192.168.2.100") # net3 = IPAddr.new("192.168.3.0") # p net1.include?(net2) #=> true # p net1.include?(net3) #=> false def include?(other) other = coerce_other(other) if ipv4_mapped? if (@mask_addr >> 32) != 0xffffffffffffffffffffffff return false end mask_addr = (@mask_addr & IN4MASK) addr = (@addr & IN4MASK) family = Socket::AF_INET else mask_addr = @mask_addr addr = @addr family = @family end if other.ipv4_mapped? other_addr = (other.to_i & IN4MASK) other_family = Socket::AF_INET else other_addr = other.to_i other_family = other.family end if family != other_family return false end return ((addr & mask_addr) == (other_addr & mask_addr)) end alias === include? # Returns the integer representation of the ipaddr. def to_i return @addr end # Returns a string containing the IP address representation. def to_s str = to_string return str if ipv4? str.gsub!(/\b0{1,3}([\da-f]+)\b/i, '\1') loop do break if str.sub!(/\A0:0:0:0:0:0:0:0\Z/, '::') break if str.sub!(/\b0:0:0:0:0:0:0\b/, ':') break if str.sub!(/\b0:0:0:0:0:0\b/, ':') break if str.sub!(/\b0:0:0:0:0\b/, ':') break if str.sub!(/\b0:0:0:0\b/, ':') break if str.sub!(/\b0:0:0\b/, ':') break if str.sub!(/\b0:0\b/, ':') break end str.sub!(/:{3,}/, '::') if /\A::(ffff:)?([\da-f]{1,4}):([\da-f]{1,4})\Z/i =~ str str = sprintf('::%s%d.%d.%d.%d', $1, $2.hex / 256, $2.hex % 256, $3.hex / 256, $3.hex % 256) end str end # Returns a string containing the IP address representation in # canonical form. def to_string return _to_string(@addr) end # Returns a network byte ordered string form of the IP address. def hton case @family when Socket::AF_INET return [@addr].pack('N') when Socket::AF_INET6 return (0..7).map { |i| (@addr >> (112 - 16 * i)) & 0xffff }.pack('n8') else raise "unsupported address family" end end # Returns true if the ipaddr is an IPv4 address. def ipv4? return @family == Socket::AF_INET end # Returns true if the ipaddr is an IPv6 address. def ipv6? return @family == Socket::AF_INET6 end # Returns true if the ipaddr is an IPv4-mapped IPv6 address. def ipv4_mapped? return ipv6? && (@addr >> 32) == 0xffff end # Returns true if the ipaddr is an IPv4-compatible IPv6 address. def ipv4_compat? if !ipv6? || (@addr >> 32) != 0 return false end a = (@addr & IN4MASK) return a != 0 && a != 1 end # Returns a new ipaddr built by converting the native IPv4 address # into an IPv4-mapped IPv6 address. def ipv4_mapped if !ipv4? raise ArgumentError, "not an IPv4 address" end return self.clone.set(@addr | 0xffff00000000, Socket::AF_INET6) end # Returns a new ipaddr built by converting the native IPv4 address # into an IPv4-compatible IPv6 address. def ipv4_compat if !ipv4? raise ArgumentError, "not an IPv4 address" end return self.clone.set(@addr, Socket::AF_INET6) end # Returns a new ipaddr built by converting the IPv6 address into a # native IPv4 address. If the IP address is not an IPv4-mapped or # IPv4-compatible IPv6 address, returns self. def native if !ipv4_mapped? && !ipv4_compat? return self end return self.clone.set(@addr & IN4MASK, Socket::AF_INET) end # Returns a string for DNS reverse lookup. It returns a string in # RFC3172 form for an IPv6 address. def reverse case @family when Socket::AF_INET return _reverse + ".in-addr.arpa" when Socket::AF_INET6 return ip6_arpa else raise "unsupported address family" end end # Returns a string for DNS reverse lookup compatible with RFC3172. def ip6_arpa if !ipv6? raise ArgumentError, "not an IPv6 address" end return _reverse + ".ip6.arpa" end # Returns a string for DNS reverse lookup compatible with RFC1886. def ip6_int if !ipv6? raise ArgumentError, "not an IPv6 address" end return _reverse + ".ip6.int" end # Returns the successor to the ipaddr. def succ return self.clone.set(@addr + 1, @family) end # Compares the ipaddr with another. def <=>(other) other = coerce_other(other) return nil if other.family != @family return @addr <=> other.to_i end include Comparable # Creates a Range object for the network address. def to_range begin_addr = (@addr & @mask_addr) case @family when Socket::AF_INET end_addr = (@addr | (IN4MASK ^ @mask_addr)) when Socket::AF_INET6 end_addr = (@addr | (IN6MASK ^ @mask_addr)) else raise "unsupported address family" end return clone.set(begin_addr, @family)..clone.set(end_addr, @family) end # Returns a string containing a human-readable representation of the # ipaddr. ("#<IPAddr: family:address/mask>") def inspect case @family when Socket::AF_INET af = "IPv4" when Socket::AF_INET6 af = "IPv6" else raise "unsupported address family" end return sprintf("#<%s: %s:%s/%s>", self.class.name, af, _to_string(@addr), _to_string(@mask_addr)) end protected def set(addr, *family) case family[0] ? family[0] : @family when Socket::AF_INET if addr < 0 || addr > IN4MASK raise ArgumentError, "invalid address" end when Socket::AF_INET6 if addr < 0 || addr > IN6MASK raise ArgumentError, "invalid address" end else raise ArgumentError, "unsupported address family" end @addr = addr if family[0] @family = family[0] end return self end def mask!(mask) if mask.kind_of?(String) if mask =~ /^\d+$/ prefixlen = mask.to_i else m = IPAddr.new(mask) if m.family != @family raise ArgumentError, "address family is not same" end @mask_addr = m.to_i @addr &= @mask_addr return self end else prefixlen = mask end case @family when Socket::AF_INET if prefixlen < 0 || prefixlen > 32 raise ArgumentError, "invalid length" end masklen = 32 - prefixlen @mask_addr = ((IN4MASK >> masklen) << masklen) when Socket::AF_INET6 if prefixlen < 0 || prefixlen > 128 raise ArgumentError, "invalid length" end masklen = 128 - prefixlen @mask_addr = ((IN6MASK >> masklen) << masklen) else raise "unsupported address family" end @addr = ((@addr >> masklen) << masklen) return self end private # Creates a new ipaddr object either from a human readable IP # address representation in string, or from a packed in_addr value # followed by an address family. # # In the former case, the following are the valid formats that will # be recognized: "address", "address/prefixlen" and "address/mask", # where IPv6 address may be enclosed in square brackets (`[' and # `]'). If a prefixlen or a mask is specified, it returns a masked # IP address. Although the address family is determined # automatically from a specified string, you can specify one # explicitly by the optional second argument. # # Otherwise an IP addess is generated from a packed in_addr value # and an address family. # # The IPAddr class defines many methods and operators, and some of # those, such as &, |, include? and ==, accept a string, or a packed # in_addr value instead of an IPAddr object. def initialize(addr = '::', family = Socket::AF_UNSPEC) if !addr.kind_of?(String) case family when Socket::AF_INET, Socket::AF_INET6 set(addr.to_i, family) @mask_addr = (family == Socket::AF_INET) ? IN4MASK : IN6MASK return when Socket::AF_UNSPEC raise ArgumentError, "address family must be specified" else raise ArgumentError, "unsupported address family: #{family}" end end prefix, prefixlen = addr.split('/') if prefix =~ /^\[(.*)\]$/i prefix = $1 family = Socket::AF_INET6 end # It seems AI_NUMERICHOST doesn't do the job. #Socket.getaddrinfo(left, nil, Socket::AF_INET6, Socket::SOCK_STREAM, nil, # Socket::AI_NUMERICHOST) begin IPSocket.getaddress(prefix) # test if address is vaild rescue raise ArgumentError, "invalid address" end @addr = @family = nil if family == Socket::AF_UNSPEC || family == Socket::AF_INET @addr = in_addr(prefix) if @addr @family = Socket::AF_INET end end if !@addr && (family == Socket::AF_UNSPEC || family == Socket::AF_INET6) @addr = in6_addr(prefix) @family = Socket::AF_INET6 end if family != Socket::AF_UNSPEC && @family != family raise ArgumentError, "address family mismatch" end if prefixlen mask!(prefixlen) else @mask_addr = (@family == Socket::AF_INET) ? IN4MASK : IN6MASK end end def coerce_other(other) case other when IPAddr other when String self.class.new(other) else self.class.new(other, @family) end end def in_addr(addr) if addr =~ /^\d+\.\d+\.\d+\.\d+$/ return addr.split('.').inject(0) { |i, s| i << 8 | s.to_i } end return nil end def in6_addr(left) case left when /^::ffff:(\d+\.\d+\.\d+\.\d+)$/i return in_addr($1) + 0xffff00000000 when /^::(\d+\.\d+\.\d+\.\d+)$/i return in_addr($1) when /[^0-9a-f:]/i raise ArgumentError, "invalid address" when /^(.*)::(.*)$/ left, right = $1, $2 else right = '' end l = left.split(':') r = right.split(':') rest = 8 - l.size - r.size if rest < 0 return nil end return (l + Array.new(rest, '0') + r).inject(0) { |i, s| i << 16 | s.hex } end def addr_mask(addr) case @family when Socket::AF_INET return addr & IN4MASK when Socket::AF_INET6 return addr & IN6MASK else raise "unsupported address family" end end def _reverse case @family when Socket::AF_INET return (0..3).map { |i| (@addr >> (8 * i)) & 0xff }.join('.') when Socket::AF_INET6 return ("%.32x" % @addr).reverse!.gsub!(/.(?!$)/, '\&.') else raise "unsupported address family" end end def _to_string(addr) case @family when Socket::AF_INET return (0..3).map { |i| (addr >> (24 - 8 * i)) & 0xff }.join('.') when Socket::AF_INET6 return (("%.32x" % addr).gsub!(/.{4}(?!$)/, '\&:')) else raise "unsupported address family" end end end if $0 == __FILE__ eval DATA.read, nil, $0, __LINE__+4 end __END__ require 'test/unit' require 'test/unit/ui/console/testrunner' class TC_IPAddr < Test::Unit::TestCase def test_s_new assert_nothing_raised { IPAddr.new("3FFE:505:ffff::/48") IPAddr.new("0:0:0:1::") IPAddr.new("2001:200:300::/48") } a = IPAddr.new assert_equal("::", a.to_s) assert_equal("0000:0000:0000:0000:0000:0000:0000:0000", a.to_string) assert_equal(Socket::AF_INET6, a.family) a = IPAddr.new("0123:4567:89ab:cdef:0ABC:DEF0:1234:5678") assert_equal("123:4567:89ab:cdef:abc:def0:1234:5678", a.to_s) assert_equal("0123:4567:89ab:cdef:0abc:def0:1234:5678", a.to_string) assert_equal(Socket::AF_INET6, a.family) a = IPAddr.new("3ffe:505:2::/48") assert_equal("3ffe:505:2::", a.to_s) assert_equal("3ffe:0505:0002:0000:0000:0000:0000:0000", a.to_string) assert_equal(Socket::AF_INET6, a.family) assert_equal(false, a.ipv4?) assert_equal(true, a.ipv6?) assert_equal("#<IPAddr: IPv6:3ffe:0505:0002:0000:0000:0000:0000:0000/ffff:ffff:ffff:0000:0000:0000:0000:0000>", a.inspect) a = IPAddr.new("3ffe:505:2::/ffff:ffff:ffff::") assert_equal("3ffe:505:2::", a.to_s) assert_equal("3ffe:0505:0002:0000:0000:0000:0000:0000", a.to_string) assert_equal(Socket::AF_INET6, a.family) a = IPAddr.new("0.0.0.0") assert_equal("0.0.0.0", a.to_s) assert_equal("0.0.0.0", a.to_string) assert_equal(Socket::AF_INET, a.family) a = IPAddr.new("192.168.1.2") assert_equal("192.168.1.2", a.to_s) assert_equal("192.168.1.2", a.to_string) assert_equal(Socket::AF_INET, a.family) assert_equal(true, a.ipv4?) assert_equal(false, a.ipv6?) a = IPAddr.new("192.168.1.2/24") assert_equal("192.168.1.0", a.to_s) assert_equal("192.168.1.0", a.to_string) assert_equal(Socket::AF_INET, a.family) assert_equal("#<IPAddr: IPv4:192.168.1.0/255.255.255.0>", a.inspect) a = IPAddr.new("192.168.1.2/255.255.255.0") assert_equal("192.168.1.0", a.to_s) assert_equal("192.168.1.0", a.to_string) assert_equal(Socket::AF_INET, a.family) assert_equal("0:0:0:1::", IPAddr.new("0:0:0:1::").to_s) assert_equal("2001:200:300::", IPAddr.new("2001:200:300::/48").to_s) assert_equal("2001:200:300::", IPAddr.new("[2001:200:300::]/48").to_s) [ ["fe80::1%fxp0"], ["::1/255.255.255.0"], ["::1:192.168.1.2/120"], [IPAddr.new("::1").to_i], ["::ffff:192.168.1.2/120", Socket::AF_INET], ["[192.168.1.2]/120"], ].each { |args| assert_raises(ArgumentError) { IPAddr.new(*args) } } end def test_s_new_ntoh addr = '' IPAddr.new("1234:5678:9abc:def0:1234:5678:9abc:def0").hton.each_byte { |c| addr += sprintf("%02x", c) } assert_equal("123456789abcdef0123456789abcdef0", addr) addr = '' IPAddr.new("123.45.67.89").hton.each_byte { |c| addr += sprintf("%02x", c) } assert_equal(sprintf("%02x%02x%02x%02x", 123, 45, 67, 89), addr) a = IPAddr.new("3ffe:505:2::") assert_equal("3ffe:505:2::", IPAddr.new_ntoh(a.hton).to_s) a = IPAddr.new("192.168.2.1") assert_equal("192.168.2.1", IPAddr.new_ntoh(a.hton).to_s) end def test_ipv4_compat a = IPAddr.new("::192.168.1.2") assert_equal("::192.168.1.2", a.to_s) assert_equal("0000:0000:0000:0000:0000:0000:c0a8:0102", a.to_string) assert_equal(Socket::AF_INET6, a.family) assert_equal(true, a.ipv4_compat?) b = a.native assert_equal("192.168.1.2", b.to_s) assert_equal(Socket::AF_INET, b.family) assert_equal(false, b.ipv4_compat?) a = IPAddr.new("192.168.1.2") b = a.ipv4_compat assert_equal("::192.168.1.2", b.to_s) assert_equal(Socket::AF_INET6, b.family) end def test_ipv4_mapped a = IPAddr.new("::ffff:192.168.1.2") assert_equal("::ffff:192.168.1.2", a.to_s) assert_equal("0000:0000:0000:0000:0000:ffff:c0a8:0102", a.to_string) assert_equal(Socket::AF_INET6, a.family) assert_equal(true, a.ipv4_mapped?) b = a.native assert_equal("192.168.1.2", b.to_s) assert_equal(Socket::AF_INET, b.family) assert_equal(false, b.ipv4_mapped?) a = IPAddr.new("192.168.1.2") b = a.ipv4_mapped assert_equal("::ffff:192.168.1.2", b.to_s) assert_equal(Socket::AF_INET6, b.family) end def test_reverse assert_equal("f.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.2.0.0.0.5.0.5.0.e.f.f.3.ip6.arpa", IPAddr.new("3ffe:505:2::f").reverse) assert_equal("1.2.168.192.in-addr.arpa", IPAddr.new("192.168.2.1").reverse) end def test_ip6_arpa assert_equal("f.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.2.0.0.0.5.0.5.0.e.f.f.3.ip6.arpa", IPAddr.new("3ffe:505:2::f").ip6_arpa) assert_raises(ArgumentError) { IPAddr.new("192.168.2.1").ip6_arpa } end def test_ip6_int assert_equal("f.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.2.0.0.0.5.0.5.0.e.f.f.3.ip6.int", IPAddr.new("3ffe:505:2::f").ip6_int) assert_raises(ArgumentError) { IPAddr.new("192.168.2.1").ip6_int } end def test_to_s assert_equal("3ffe:0505:0002:0000:0000:0000:0000:0001", IPAddr.new("3ffe:505:2::1").to_string) assert_equal("3ffe:505:2::1", IPAddr.new("3ffe:505:2::1").to_s) end end class TC_Operator < Test::Unit::TestCase IN6MASK32 = "ffff:ffff::" IN6MASK128 = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff" def setup @in6_addr_any = IPAddr.new() @a = IPAddr.new("3ffe:505:2::/48") @b = IPAddr.new("0:0:0:1::") @c = IPAddr.new(IN6MASK32) end alias set_up setup def test_or assert_equal("3ffe:505:2:1::", (@a | @b).to_s) a = @a a |= @b assert_equal("3ffe:505:2:1::", a.to_s) assert_equal("3ffe:505:2::", @a.to_s) assert_equal("3ffe:505:2:1::", (@a | 0x00000000000000010000000000000000).to_s) end def test_and assert_equal("3ffe:505::", (@a & @c).to_s) a = @a a &= @c assert_equal("3ffe:505::", a.to_s) assert_equal("3ffe:505:2::", @a.to_s) assert_equal("3ffe:505::", (@a & 0xffffffff000000000000000000000000).to_s) end def test_shift_right assert_equal("0:3ffe:505:2::", (@a >> 16).to_s) a = @a a >>= 16 assert_equal("0:3ffe:505:2::", a.to_s) assert_equal("3ffe:505:2::", @a.to_s) end def test_shift_left assert_equal("505:2::", (@a << 16).to_s) a = @a a <<= 16 assert_equal("505:2::", a.to_s) assert_equal("3ffe:505:2::", @a.to_s) end def test_carrot a = ~@in6_addr_any assert_equal(IN6MASK128, a.to_s) assert_equal("::", @in6_addr_any.to_s) end def test_equal assert_equal(true, @a == IPAddr.new("3ffe:505:2::")) assert_equal(false, @a == IPAddr.new("3ffe:505:3::")) assert_equal(true, @a != IPAddr.new("3ffe:505:3::")) assert_equal(false, @a != IPAddr.new("3ffe:505:2::")) end def test_mask a = @a.mask(32) assert_equal("3ffe:505::", a.to_s) assert_equal("3ffe:505:2::", @a.to_s) end def test_include? assert_equal(true, @a.include?(IPAddr.new("3ffe:505:2::"))) assert_equal(true, @a.include?(IPAddr.new("3ffe:505:2::1"))) assert_equal(false, @a.include?(IPAddr.new("3ffe:505:3::"))) net1 = IPAddr.new("192.168.2.0/24") assert_equal(true, net1.include?(IPAddr.new("192.168.2.0"))) assert_equal(true, net1.include?(IPAddr.new("192.168.2.255"))) assert_equal(false, net1.include?(IPAddr.new("192.168.3.0"))) # test with integer parameter int = (192 << 24) + (168 << 16) + (2 << 8) + 13 assert_equal(true, net1.include?(int)) assert_equal(false, net1.include?(int+255)) end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/delegate.rb
tools/jruby-1.5.1/lib/ruby/1.8/delegate.rb
# = delegate -- Support for the Delegation Pattern # # Documentation by James Edward Gray II and Gavin Sinclair # # == Introduction # # This library provides three different ways to delegate method calls to an # object. The easiest to use is SimpleDelegator. Pass an object to the # constructor and all methods supported by the object will be delegated. This # object can be changed later. # # Going a step further, the top level DelegateClass method allows you to easily # setup delegation through class inheritance. This is considerably more # flexible and thus probably the most common use for this library. # # Finally, if you need full control over the delegation scheme, you can inherit # from the abstract class Delegator and customize as needed. (If you find # yourself needing this control, have a look at _forwardable_, also in the # standard library. It may suit your needs better.) # # == Notes # # Be advised, RDoc will not detect delegated methods. # # <b>delegate.rb provides full-class delegation via the # DelegateClass() method. For single-method delegation via # def_delegator(), see forwardable.rb.</b> # # == Examples # # === SimpleDelegator # # Here's a simple example that takes advantage of the fact that # SimpleDelegator's delegation object can be changed at any time. # # class Stats # def initialize # @source = SimpleDelegator.new([]) # end # # def stats( records ) # @source.__setobj__(records) # # "Elements: #{@source.size}\n" + # " Non-Nil: #{@source.compact.size}\n" + # " Unique: #{@source.uniq.size}\n" # end # end # # s = Stats.new # puts s.stats(%w{James Edward Gray II}) # puts # puts s.stats([1, 2, 3, nil, 4, 5, 1, 2]) # # <i>Prints:</i> # # Elements: 4 # Non-Nil: 4 # Unique: 4 # # Elements: 8 # Non-Nil: 7 # Unique: 6 # # === DelegateClass() # # Here's a sample of use from <i>tempfile.rb</i>. # # A _Tempfile_ object is really just a _File_ object with a few special rules # about storage location and/or when the File should be deleted. That makes for # an almost textbook perfect example of how to use delegation. # # class Tempfile < DelegateClass(File) # # constant and class member data initialization... # # def initialize(basename, tmpdir=Dir::tmpdir) # # build up file path/name in var tmpname... # # @tmpfile = File.open(tmpname, File::RDWR|File::CREAT|File::EXCL, 0600) # # # ... # # super(@tmpfile) # # # below this point, all methods of File are supported... # end # # # ... # end # # === Delegator # # SimpleDelegator's implementation serves as a nice example here. # # class SimpleDelegator < Delegator # def initialize(obj) # super # pass obj to Delegator constructor, required # @_sd_obj = obj # store obj for future use # end # # def __getobj__ # @_sd_obj # return object we are delegating to, required # end # # def __setobj__(obj) # @_sd_obj = obj # change delegation object, a feature we're providing # end # # # ... # end # # Delegator is an abstract class used to build delegator pattern objects from # subclasses. Subclasses should redefine \_\_getobj\_\_. For a concrete # implementation, see SimpleDelegator. # if defined?(ENV_JAVA) && ENV_JAVA['jruby.delegate.native'] =~ /true/i # use a pure-Java Delegator require 'delegate_internal' else # original, but slightly improved pure-Ruby Delegator require 'thread' class Delegator IgnoreBacktracePat = %r"\A#{Regexp.quote(__FILE__)}:\d+:in `" LOCK = Mutex.new DelegatorModules = Hash.new do |hash, classes| objclass, deleclass = *classes LOCK.synchronize do hash[classes] = Module.new do preserved = ::Kernel.public_instance_methods(false) preserved -= ["to_s","to_a","inspect","==","=~","==="] for t in deleclass.ancestors preserved |= t.public_instance_methods(false) preserved |= t.private_instance_methods(false) preserved |= t.protected_instance_methods(false) break if t == Delegator end preserved << "singleton_method_added" for method in objclass.instance_methods next if preserved.include? method begin eval <<-EOS, nil, __FILE__, __LINE__+1 def #{method}(*args, &block) begin __getobj__.__send__(:#{method}, *args, &block) ensure $@.delete_if{|s|IgnoreBacktracePat=~s} if $@ end end EOS rescue SyntaxError raise NameError, "invalid identifier %s" % method, caller(4) end end end end end # # Pass in the _obj_ to delegate method calls to. All methods supported by # _obj_ will be delegated to. # def initialize(obj) # This modification caches the generated set of methods for a given pair # of object class + delegate subclass and extends it onto future objects. # This avoids all the overhead of that class generation on each object # construction, but introduces the overhead of .extend and does not # properly define singleton methods (though they'll still dispatch ok # through method_missing) extend DelegatorModules[[obj.class, self.class]] end alias initialize_methods initialize # Handles the magic of delegation through \_\_getobj\_\_. def method_missing(m, *args) target = self.__getobj__ unless target.respond_to?(m) super(m, *args) end target.__send__(m, *args) end # # Checks for a method provided by this the delegate object by fowarding the # call through \_\_getobj\_\_. # def respond_to?(m, include_private = false) return true if super return self.__getobj__.respond_to?(m, include_private) end # # This method must be overridden by subclasses and should return the object # method calls are being delegated to. # def __getobj__ raise NotImplementedError, "need to define `__getobj__'" end # Serialization support for the object returned by \_\_getobj\_\_. def marshal_dump __getobj__ end # Reinitializes delegation from a serialized object. def marshal_load(obj) initialize_methods(obj) __setobj__(obj) end end end # # A concrete implementation of Delegator, this class provides the means to # delegate all supported method calls to the object passed into the constructor # and even to change the object being delegated to at a later time with # \_\_setobj\_\_ . # class SimpleDelegator<Delegator # Pass in the _obj_ you would like to delegate method calls to. def initialize(obj) super @_sd_obj = obj end # Returns the current object method calls are being delegated to. def __getobj__ @_sd_obj end # # Changes the delegate object to _obj_. # # It's important to note that this does *not* cause SimpleDelegator's methods # to change. Because of this, you probably only want to change delegation # to objects of the same type as the original delegate. # # Here's an example of changing the delegation object. # # names = SimpleDelegator.new(%w{James Edward Gray II}) # puts names[1] # => Edward # names.__setobj__(%w{Gavin Sinclair}) # puts names[1] # => Sinclair # def __setobj__(obj) raise ArgumentError, "cannot delegate to self" if self.equal?(obj) @_sd_obj = obj end # Clone support for the object returned by \_\_getobj\_\_. def clone new = super new.__setobj__(__getobj__.clone) new end # Duplication support for the object returned by \_\_getobj\_\_. def dup new = super new.__setobj__(__getobj__.clone) new end end # :stopdoc: # backward compatibility ^_^;;; Delegater = Delegator SimpleDelegater = SimpleDelegator # :startdoc: # # The primary interface to this library. Use to setup delegation when defining # your class. # # class MyClass < DelegateClass( ClassToDelegateTo ) # Step 1 # def initialize # super(obj_of_ClassToDelegateTo) # Step 2 # end # end # def DelegateClass(superclass) klass = Class.new methods = superclass.public_instance_methods(true) methods -= ::Kernel.public_instance_methods(false) methods |= ["to_s","to_a","inspect","==","=~","==="] klass.module_eval { def initialize(obj) # :nodoc: @_dc_obj = obj end def method_missing(m, *args) # :nodoc: unless @_dc_obj.respond_to?(m) super(m, *args) end @_dc_obj.__send__(m, *args) end def respond_to?(m, include_private = false) # :nodoc: return true if super return @_dc_obj.respond_to?(m, include_private) end def __getobj__ # :nodoc: @_dc_obj end def __setobj__(obj) # :nodoc: raise ArgumentError, "cannot delegate to self" if self.equal?(obj) @_dc_obj = obj end def clone # :nodoc: new = super new.__setobj__(__getobj__.clone) new end def dup # :nodoc: new = super new.__setobj__(__getobj__.clone) new end } for method in methods begin klass.module_eval <<-EOS, __FILE__, __LINE__+1 def #{method}(*args, &block) begin @_dc_obj.__send__(:#{method}, *args, &block) ensure $@.delete_if{|s| ::Delegator::IgnoreBacktracePat =~ s} if $@ end end EOS rescue SyntaxError raise NameError, "invalid identifier %s" % method, caller(3) end end return klass end # :enddoc: if __FILE__ == $0 class ExtArray<DelegateClass(Array) def initialize() super([]) end end ary = ExtArray.new p ary.class ary.push 25 p ary foo = Object.new def foo.test 25 end def foo.error raise 'this is OK' end foo2 = SimpleDelegator.new(foo) p foo.test == foo2.test # => true foo2.error # raise error! end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/monitor.rb
tools/jruby-1.5.1/lib/ruby/1.8/monitor.rb
=begin = monitor.rb Copyright (C) 2001 Shugo Maeda <shugo@ruby-lang.org> Copyright (C) 2008 MenTaLguY <mental@rydia.net> This library is distributed under the terms of the Ruby license. You can freely distribute/modify this library. == example This is a simple example. require 'monitor.rb' buf = [] buf.extend(MonitorMixin) empty_cond = buf.new_cond # consumer Thread.start do loop do buf.synchronize do empty_cond.wait_while { buf.empty? } print buf.shift end end end # producer while line = ARGF.gets buf.synchronize do buf.push(line) empty_cond.signal end end The consumer thread waits for the producer thread to push a line to buf while buf.empty?, and the producer thread (main thread) reads a line from ARGF and push it to buf, then call empty_cond.signal. =end require 'thread' # # Adds monitor functionality to an arbitrary object by mixing the module with # +include+. For example: # # require 'monitor.rb' # # buf = [] # buf.extend(MonitorMixin) # empty_cond = buf.new_cond # # # consumer # Thread.start do # loop do # buf.synchronize do # empty_cond.wait_while { buf.empty? } # print buf.shift # end # end # end # # # producer # while line = ARGF.gets # buf.synchronize do # buf.push(line) # empty_cond.signal # end # end # # The consumer thread waits for the producer thread to push a line # to buf while buf.empty?, and the producer thread (main thread) # reads a line from ARGF and push it to buf, then call # empty_cond.signal. # module MonitorMixin # # FIXME: This isn't documented in Nutshell. # # Since MonitorMixin.new_cond returns a ConditionVariable, and the example # above calls while_wait and signal, this class should be documented. # class ConditionVariable # Create a new timer with the argument timeout, and add the # current thread to the list of waiters. Then the thread is # stopped. It will be resumed when a corresponding #signal # occurs. def wait(timeout = nil) condition = @condition @monitor.instance_eval { mon_wait_for_cond(condition, timeout) } end # call #wait while the supplied block returns +true+. def wait_while while yield wait end end # call #wait until the supplied block returns +true+. def wait_until until yield wait end end # Wake up and run the next waiter def signal condition = @condition @monitor.instance_eval { mon_signal_cond(condition) } nil end # Wake up all the waiters. def broadcast condition = @condition @monitor.instance_eval { mon_broadcast_cond(condition) } nil end def count_waiters condition = @condition @monitor.instance_eval { mon_count_cond_waiters(condition) } end private def initialize(monitor, condition) @monitor = monitor @condition = condition end end def self.extend_object(obj) super(obj) obj.instance_eval {mon_initialize()} end # # Attempts to enter exclusive section. Returns +false+ if lock fails. # def mon_try_enter @mon_mutex.synchronize do @mon_owner = Thread.current unless @mon_owner if @mon_owner == Thread.current @mon_count += 1 true else false end end end # For backward compatibility alias try_mon_enter mon_try_enter # # Enters exclusive section. # def mon_enter @mon_mutex.synchronize do mon_acquire(@mon_entering_cond) @mon_count += 1 end end # # Leaves exclusive section. # def mon_exit @mon_mutex.synchronize do mon_check_owner @mon_count -= 1 mon_release if @mon_count.zero? nil end end # # Enters exclusive section and executes the block. Leaves the exclusive # section automatically when the block exits. See example under # +MonitorMixin+. # def mon_synchronize mon_enter begin yield ensure mon_exit end end alias synchronize mon_synchronize # # FIXME: This isn't documented in Nutshell. # # Create a new condition variable for this monitor. # This facilitates control of the monitor with #signal and #wait. # def new_cond condition = ::ConditionVariable.new condition.instance_eval { @mon_n_waiters = 0 } return ConditionVariable.new(self, condition) end private def initialize(*args) super mon_initialize end # called by initialize method to set defaults for instance variables. def mon_initialize @mon_mutex = Mutex.new @mon_owner = nil @mon_count = 0 @mon_total_waiting = 0 @mon_entering_cond = ::ConditionVariable.new @mon_waiting_cond = ::ConditionVariable.new self end # Throw a ThreadError exception if the current thread # does't own the monitor def mon_check_owner # called with @mon_mutex held if @mon_owner != Thread.current raise ThreadError, "current thread not owner" end end def mon_acquire(condition) # called with @mon_mutex held while @mon_owner && @mon_owner != Thread.current condition.wait @mon_mutex end @mon_owner = Thread.current end def mon_release # called with @mon_mutex held @mon_owner = nil if @mon_total_waiting.nonzero? @mon_waiting_cond.signal else @mon_entering_cond.signal end end def mon_wait_for_cond(condition, timeout) @mon_mutex.synchronize do mon_check_owner count = @mon_count @mon_count = 0 condition.instance_eval { @mon_n_waiters += 1 } begin mon_release if timeout condition.wait(@mon_mutex, timeout) else condition.wait(@mon_mutex) true end ensure @mon_total_waiting += 1 # TODO: not interrupt-safe mon_acquire(@mon_waiting_cond) @mon_total_waiting -= 1 @mon_count = count condition.instance_eval { @mon_n_waiters -= 1 } end end end def mon_signal_cond(condition) @mon_mutex.synchronize do mon_check_owner condition.signal end end def mon_broadcast_cond(condition) @mon_mutex.synchronize do mon_check_owner condition.broadcast end end def mon_count_cond_waiters(condition) @mon_mutex.synchronize do condition.instance_eval { @mon_n_waiters } end end end # Monitors provide means of mutual exclusion for Thread programming. # A critical region is created by means of the synchronize method, # which takes a block. # The condition variables (created with #new_cond) may be used # to control the execution of a monitor with #signal and #wait. # # the Monitor class wraps MonitorMixin, and provides aliases # alias try_enter try_mon_enter # alias enter mon_enter # alias exit mon_exit # to access its methods more concisely. class Monitor include MonitorMixin alias try_enter try_mon_enter alias enter mon_enter alias exit mon_exit end # Documentation comments: # - All documentation comes from Nutshell. # - MonitorMixin.new_cond appears in the example, but is not documented in # Nutshell. # - All the internals (internal modules Accessible and Initializable, class # ConditionVariable) appear in RDoc. It might be good to hide them, by # making them private, or marking them :nodoc:, etc. # - The entire example from the RD section at the top is replicated in the RDoc # comment for MonitorMixin. Does the RD section need to remain? # - RDoc doesn't recognise aliases, so we have mon_synchronize documented, but # not synchronize. # - mon_owner is in Nutshell, but appears as an accessor in a separate module # here, so is hard/impossible to RDoc. Some other useful accessors # (mon_count and some queue stuff) are also in this module, and don't appear # directly in the RDoc output. # - in short, it may be worth changing the code layout in this file to make the # documentation easier # Local variables: # mode: Ruby # tab-width: 8 # End:
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/singleton.rb
tools/jruby-1.5.1/lib/ruby/1.8/singleton.rb
# The Singleton module implements the Singleton pattern. # # Usage: # class Klass # include Singleton # # ... # end # # * this ensures that only one instance of Klass lets call it # ``the instance'' can be created. # # a,b = Klass.instance, Klass.instance # a == b # => true # a.new # NoMethodError - new is private ... # # * ``The instance'' is created at instantiation time, in other # words the first call of Klass.instance(), thus # # class OtherKlass # include Singleton # # ... # end # ObjectSpace.each_object(OtherKlass){} # => 0. # # * This behavior is preserved under inheritance and cloning. # # # # This is achieved by marking # * Klass.new and Klass.allocate - as private # # Providing (or modifying) the class methods # * Klass.inherited(sub_klass) and Klass.clone() - # to ensure that the Singleton pattern is properly # inherited and cloned. # # * Klass.instance() - returning ``the instance''. After a # successful self modifying (normally the first) call the # method body is a simple: # # def Klass.instance() # return @__instance__ # end # # * Klass._load(str) - calling Klass.instance() # # * Klass._instantiate?() - returning ``the instance'' or # nil. This hook method puts a second (or nth) thread calling # Klass.instance() on a waiting loop. The return value # signifies the successful completion or premature termination # of the first, or more generally, current "instantiation thread". # # # The instance method of Singleton are # * clone and dup - raising TypeErrors to prevent cloning or duping # # * _dump(depth) - returning the empty string. Marshalling strips # by default all state information, e.g. instance variables and # taint state, from ``the instance''. Providing custom _load(str) # and _dump(depth) hooks allows the (partially) resurrections of # a previous state of ``the instance''. module Singleton # disable build-in copying methods def clone raise TypeError, "can't clone instance of singleton #{self.class}" end def dup raise TypeError, "can't dup instance of singleton #{self.class}" end # default marshalling strategy def _dump(depth=-1) '' end end class << Singleton # Method body of first instance call. FirstInstanceCall = proc do # @__instance__ takes on one of the following values # * nil - before and after a failed creation # * false - during creation # * sub_class instance - after a successful creation # the form makes up for the lack of returns in progs Thread.critical = true if @__instance__.nil? @__instance__ = false Thread.critical = false begin @__instance__ = new ensure if @__instance__ class <<self remove_method :instance def instance; @__instance__ end end else @__instance__ = nil # failed instance creation end end elsif _instantiate?() Thread.critical = false else @__instance__ = false Thread.critical = false begin @__instance__ = new ensure if @__instance__ class <<self remove_method :instance def instance; @__instance__ end end else @__instance__ = nil end end end @__instance__ end module SingletonClassMethods # properly clone the Singleton pattern - did you know # that duping doesn't copy class methods? def clone Singleton.__init__(super) end def _load(str) instance end private # ensure that the Singleton pattern is properly inherited def inherited(sub_klass) super Singleton.__init__(sub_klass) end # waiting-loop hook def _instantiate?() while false.equal?(@__instance__) Thread.critical = false sleep(0.08) # timeout Thread.critical = true end @__instance__ end end def __init__(klass) klass.instance_eval { @__instance__ = nil } class << klass define_method(:instance,FirstInstanceCall) end klass end private # extending an object with Singleton is a bad idea undef_method :extend_object def append_features(mod) # help out people counting on transitive mixins unless mod.instance_of?(Class) raise TypeError, "Inclusion of the OO-Singleton module in module #{mod}" end super end def included(klass) super klass.private_class_method :new, :allocate klass.extend SingletonClassMethods Singleton.__init__(klass) end end if __FILE__ == $0 def num_of_instances(klass) "#{ObjectSpace.each_object(klass){}} #{klass} instance(s)" end # The basic and most important example. class SomeSingletonClass include Singleton end puts "There are #{num_of_instances(SomeSingletonClass)}" a = SomeSingletonClass.instance b = SomeSingletonClass.instance # a and b are same object puts "basic test is #{a == b}" begin SomeSingletonClass.new rescue NoMethodError => mes puts mes end puts "\nThreaded example with exception and customized #_instantiate?() hook"; p Thread.abort_on_exception = false class Ups < SomeSingletonClass def initialize self.class.__sleep puts "initialize called by thread ##{Thread.current[:i]}" end end class << Ups def _instantiate? @enter.push Thread.current[:i] while false.equal?(@__instance__) Thread.critical = false sleep 0.08 Thread.critical = true end @leave.push Thread.current[:i] @__instance__ end def __sleep sleep(rand(0.08)) end def new begin __sleep raise "boom - thread ##{Thread.current[:i]} failed to create instance" ensure # simple flip-flop class << self remove_method :new end end end def instantiate_all @enter = [] @leave = [] 1.upto(9) {|i| Thread.new { begin Thread.current[:i] = i __sleep instance rescue RuntimeError => mes puts mes end } } puts "Before there were #{num_of_instances(self)}" sleep 3 puts "Now there is #{num_of_instances(self)}" puts "#{@enter.join '; '} was the order of threads entering the waiting loop" puts "#{@leave.join '; '} was the order of threads leaving the waiting loop" end end Ups.instantiate_all # results in message like # Before there were 0 Ups instance(s) # boom - thread #6 failed to create instance # initialize called by thread #3 # Now there is 1 Ups instance(s) # 3; 2; 1; 8; 4; 7; 5 was the order of threads entering the waiting loop # 3; 2; 1; 7; 4; 8; 5 was the order of threads leaving the waiting loop puts "\nLets see if class level cloning really works" Yup = Ups.clone def Yup.new begin __sleep raise "boom - thread ##{Thread.current[:i]} failed to create instance" ensure # simple flip-flop class << self remove_method :new end end end Yup.instantiate_all puts "\n\n","Customized marshalling" class A include Singleton attr_accessor :persist, :die def _dump(depth) # this strips the @die information from the instance Marshal.dump(@persist,depth) end end def A._load(str) instance.persist = Marshal.load(str) instance end a = A.instance a.persist = ["persist"] a.die = "die" a.taint stored_state = Marshal.dump(a) # change state a.persist = nil a.die = nil b = Marshal.load(stored_state) p a == b # => true p a.persist # => ["persist"] p a.die # => nil puts "\n\nSingleton with overridden default #inherited() hook" class Up end def Up.inherited(sub_klass) puts "#{sub_klass} subclasses #{self}" end class Middle < Up include Singleton end class Down < Middle; end puts "and basic \"Down test\" is #{Down.instance == Down.instance}\n Various exceptions" begin module AModule include Singleton end rescue TypeError => mes puts mes #=> Inclusion of the OO-Singleton module in module AModule end begin 'aString'.extend Singleton rescue NoMethodError => mes puts mes #=> undefined method `extend_object' for Singleton:Module end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/date.rb
tools/jruby-1.5.1/lib/ruby/1.8/date.rb
# # date.rb - date and time library # # Author: Tadayoshi Funaba 1998-2008 # # Documentation: William Webber <william@williamwebber.com> # #-- # $Id: date.rb,v 2.37 2008-01-17 20:16:31+09 tadf Exp $ #++ # # == Overview # # This file provides two classes for working with # dates and times. # # The first class, Date, represents dates. # It works with years, months, weeks, and days. # See the Date class documentation for more details. # # The second, DateTime, extends Date to include hours, # minutes, seconds, and fractions of a second. It # provides basic support for time zones. See the # DateTime class documentation for more details. # # === Ways of calculating the date. # # In common usage, the date is reckoned in years since or # before the Common Era (CE/BCE, also known as AD/BC), then # as a month and day-of-the-month within the current year. # This is known as the *Civil* *Date*, and abbreviated # as +civil+ in the Date class. # # Instead of year, month-of-the-year, and day-of-the-month, # the date can also be reckoned in terms of year and # day-of-the-year. This is known as the *Ordinal* *Date*, # and is abbreviated as +ordinal+ in the Date class. (Note # that referring to this as the Julian date is incorrect.) # # The date can also be reckoned in terms of year, week-of-the-year, # and day-of-the-week. This is known as the *Commercial* # *Date*, and is abbreviated as +commercial+ in the # Date class. The commercial week runs Monday (day-of-the-week # 1) to Sunday (day-of-the-week 7), in contrast to the civil # week which runs Sunday (day-of-the-week 0) to Saturday # (day-of-the-week 6). The first week of the commercial year # starts on the Monday on or before January 1, and the commercial # year itself starts on this Monday, not January 1. # # For scientific purposes, it is convenient to refer to a date # simply as a day count, counting from an arbitrary initial # day. The date first chosen for this was January 1, 4713 BCE. # A count of days from this date is the *Julian* *Day* *Number* # or *Julian* *Date*, which is abbreviated as +jd+ in the # Date class. This is in local time, and counts from midnight # on the initial day. The stricter usage is in UTC, and counts # from midday on the initial day. This is referred to in the # Date class as the *Astronomical* *Julian* *Day* *Number*, and # abbreviated as +ajd+. In the Date class, the Astronomical # Julian Day Number includes fractional days. # # Another absolute day count is the *Modified* *Julian* *Day* # *Number*, which takes November 17, 1858 as its initial day. # This is abbreviated as +mjd+ in the Date class. There # is also an *Astronomical* *Modified* *Julian* *Day* *Number*, # which is in UTC and includes fractional days. This is # abbreviated as +amjd+ in the Date class. Like the Modified # Julian Day Number (and unlike the Astronomical Julian # Day Number), it counts from midnight. # # Alternative calendars such as the Chinese Lunar Calendar, # the Islamic Calendar, or the French Revolutionary Calendar # are not supported by the Date class; nor are calendars that # are based on an Era different from the Common Era, such as # the Japanese Imperial Calendar or the Republic of China # Calendar. # # === Calendar Reform # # The standard civil year is 365 days long. However, the # solar year is fractionally longer than this. To account # for this, a *leap* *year* is occasionally inserted. This # is a year with 366 days, the extra day falling on February 29. # In the early days of the civil calendar, every fourth # year without exception was a leap year. This way of # reckoning leap years is the *Julian* *Calendar*. # # However, the solar year is marginally shorter than 365 1/4 # days, and so the *Julian* *Calendar* gradually ran slow # over the centuries. To correct this, every 100th year # (but not every 400th year) was excluded as a leap year. # This way of reckoning leap years, which we use today, is # the *Gregorian* *Calendar*. # # The Gregorian Calendar was introduced at different times # in different regions. The day on which it was introduced # for a particular region is the *Day* *of* *Calendar* # *Reform* for that region. This is abbreviated as +sg+ # (for Start of Gregorian calendar) in the Date class. # # Two such days are of particular # significance. The first is October 15, 1582, which was # the Day of Calendar Reform for Italy and most Catholic # countries. The second is September 14, 1752, which was # the Day of Calendar Reform for England and its colonies # (including what is now the United States). These two # dates are available as the constants Date::ITALY and # Date::ENGLAND, respectively. (By comparison, Germany and # Holland, less Catholic than Italy but less stubborn than # England, changed over in 1698; Sweden in 1753; Russia not # till 1918, after the Revolution; and Greece in 1923. Many # Orthodox churches still use the Julian Calendar. A complete # list of Days of Calendar Reform can be found at # http://www.polysyllabic.com/GregConv.html.) # # Switching from the Julian to the Gregorian calendar # involved skipping a number of days to make up for the # accumulated lag, and the later the switch was (or is) # done, the more days need to be skipped. So in 1582 in Italy, # 4th October was followed by 15th October, skipping 10 days; in 1752 # in England, 2nd September was followed by 14th September, skipping # 11 days; and if I decided to switch from Julian to Gregorian # Calendar this midnight, I would go from 27th July 2003 (Julian) # today to 10th August 2003 (Gregorian) tomorrow, skipping # 13 days. The Date class is aware of this gap, and a supposed # date that would fall in the middle of it is regarded as invalid. # # The Day of Calendar Reform is relevant to all date representations # involving years. It is not relevant to the Julian Day Numbers, # except for converting between them and year-based representations. # # In the Date and DateTime classes, the Day of Calendar Reform or # +sg+ can be specified a number of ways. First, it can be as # the Julian Day Number of the Day of Calendar Reform. Second, # it can be using the constants Date::ITALY or Date::ENGLAND; these # are in fact the Julian Day Numbers of the Day of Calendar Reform # of the respective regions. Third, it can be as the constant # Date::JULIAN, which means to always use the Julian Calendar. # Finally, it can be as the constant Date::GREGORIAN, which means # to always use the Gregorian Calendar. # # Note: in the Julian Calendar, New Years Day was March 25. The # Date class does not follow this convention. # # === Time Zones # # DateTime objects support a simple representation # of time zones. Time zones are represented as an offset # from UTC, as a fraction of a day. This offset is the # how much local time is later (or earlier) than UTC. # UTC offset 0 is centred on England (also known as GMT). # As you travel east, the offset increases until you # reach the dateline in the middle of the Pacific Ocean; # as you travel west, the offset decreases. This offset # is abbreviated as +of+ in the Date class. # # This simple representation of time zones does not take # into account the common practice of Daylight Savings # Time or Summer Time. # # Most DateTime methods return the date and the # time in local time. The two exceptions are # #ajd() and #amjd(), which return the date and time # in UTC time, including fractional days. # # The Date class does not support time zone offsets, in that # there is no way to create a Date object with a time zone. # However, methods of the Date class when used by a # DateTime instance will use the time zone offset of this # instance. # # == Examples of use # # === Print out the date of every Sunday between two dates. # # def print_sundays(d1, d2) # d1 +=1 while (d1.wday != 0) # d1.step(d2, 7) do |date| # puts "#{Date::MONTHNAMES[date.mon]} #{date.day}" # end # end # # print_sundays(Date::civil(2003, 4, 8), Date::civil(2003, 5, 23)) # # === Calculate how many seconds to go till midnight on New Year's Day. # # def secs_to_new_year(now = DateTime::now()) # new_year = DateTime.new(now.year + 1, 1, 1) # dif = new_year - now # hours, mins, secs, ignore_fractions = Date::day_fraction_to_time(dif) # return hours * 60 * 60 + mins * 60 + secs # end # # puts secs_to_new_year() require 'rational' require 'date/format' # Class representing a date. # # See the documentation to the file date.rb for an overview. # # Internally, the date is represented as an Astronomical # Julian Day Number, +ajd+. The Day of Calendar Reform, +sg+, is # also stored, for conversions to other date formats. (There # is also an +of+ field for a time zone offset, but this # is only for the use of the DateTime subclass.) # # A new Date object is created using one of the object creation # class methods named after the corresponding date format, and the # arguments appropriate to that date format; for instance, # Date::civil() (aliased to Date::new()) with year, month, # and day-of-month, or Date::ordinal() with year and day-of-year. # All of these object creation class methods also take the # Day of Calendar Reform as an optional argument. # # Date objects are immutable once created. # # Once a Date has been created, date values # can be retrieved for the different date formats supported # using instance methods. For instance, #mon() gives the # Civil month, #cwday() gives the Commercial day of the week, # and #yday() gives the Ordinal day of the year. Date values # can be retrieved in any format, regardless of what format # was used to create the Date instance. # # The Date class includes the Comparable module, allowing # date objects to be compared and sorted, ranges of dates # to be created, and so forth. class Date include Comparable # Full month names, in English. Months count from 1 to 12; a # month's numerical representation indexed into this array # gives the name of that month (hence the first element is nil). MONTHNAMES = [nil] + %w(January February March April May June July August September October November December) # Full names of days of the week, in English. Days of the week # count from 0 to 6 (except in the commercial week); a day's numerical # representation indexed into this array gives the name of that day. DAYNAMES = %w(Sunday Monday Tuesday Wednesday Thursday Friday Saturday) # Abbreviated month names, in English. ABBR_MONTHNAMES = [nil] + %w(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec) # Abbreviated day names, in English. ABBR_DAYNAMES = %w(Sun Mon Tue Wed Thu Fri Sat) [MONTHNAMES, DAYNAMES, ABBR_MONTHNAMES, ABBR_DAYNAMES].each do |xs| xs.each{|x| x.freeze unless x.nil?}.freeze end class Infinity < Numeric # :nodoc: include Comparable def initialize(d=1) @d = d <=> 0 end def d() @d end protected :d def zero? () false end def finite? () false end def infinite? () d.nonzero? end def nan? () d.zero? end def abs() self.class.new end def -@ () self.class.new(-d) end def +@ () self.class.new(+d) end def <=> (other) case other when Infinity; return d <=> other.d when Numeric; return d else begin l, r = other.coerce(self) return l <=> r rescue NoMethodError end end nil end def coerce(other) case other when Numeric; return -d, d else super end end end # The Julian Day Number of the Day of Calendar Reform for Italy # and the Catholic countries. ITALY = 2299161 # 1582-10-15 # The Julian Day Number of the Day of Calendar Reform for England # and her Colonies. ENGLAND = 2361222 # 1752-09-14 # A constant used to indicate that a Date should always use the # Julian calendar. JULIAN = Infinity.new # A constant used to indicate that a Date should always use the # Gregorian calendar. GREGORIAN = -Infinity.new HALF_DAYS_IN_DAY = Rational(1, 2) # :nodoc: HOURS_IN_DAY = Rational(1, 24) # :nodoc: MINUTES_IN_DAY = Rational(1, 1440) # :nodoc: SECONDS_IN_DAY = Rational(1, 86400) # :nodoc: MILLISECONDS_IN_DAY = Rational(1, 86400*10**3) # :nodoc: NANOSECONDS_IN_DAY = Rational(1, 86400*10**9) # :nodoc: MILLISECONDS_IN_SECOND = Rational(1, 10**3) # :nodoc: NANOSECONDS_IN_SECOND = Rational(1, 10**9) # :nodoc: MJD_EPOCH_IN_AJD = Rational(4800001, 2) # 1858-11-17 # :nodoc: UNIX_EPOCH_IN_AJD = Rational(4881175, 2) # 1970-01-01 # :nodoc: MJD_EPOCH_IN_CJD = 2400001 # :nodoc: UNIX_EPOCH_IN_CJD = 2440588 # :nodoc: LD_EPOCH_IN_CJD = 2299160 # :nodoc: # Does a given Julian Day Number fall inside the old-style (Julian) # calendar? # # +jd+ is the Julian Day Number in question. +sg+ may be Date::GREGORIAN, # in which case the answer is false; it may be Date::JULIAN, in which case # the answer is true; or it may a number representing the Day of # Calendar Reform. Date::ENGLAND and Date::ITALY are two possible such # days. def self.julian? (jd, sg) case sg when Numeric jd < sg else if $VERBOSE warn("#{caller.shift.sub(/:in .*/, '')}: " \ "warning: do not use non-numerical object as julian day number anymore") end not sg end end # Does a given Julian Day Number fall inside the new-style (Gregorian) # calendar? # # The reverse of self.os? See the documentation for that method for # more details. def self.gregorian? (jd, sg) !julian?(jd, sg) end def self.fix_style(jd, sg) # :nodoc: if julian?(jd, sg) then JULIAN else GREGORIAN end end private_class_method :fix_style # Convert an Ordinal Date to a Julian Day Number. # # +y+ and +d+ are the year and day-of-year to convert. # +sg+ specifies the Day of Calendar Reform. # # Returns the corresponding Julian Day Number. def self.ordinal_to_jd(y, d, sg=GREGORIAN) civil_to_jd(y, 1, d, sg) end # Convert a Julian Day Number to an Ordinal Date. # # +jd+ is the Julian Day Number to convert. # +sg+ specifies the Day of Calendar Reform. # # Returns the corresponding Ordinal Date as # [year, day_of_year] def self.jd_to_ordinal(jd, sg=GREGORIAN) y = jd_to_civil(jd, sg)[0] doy = jd - civil_to_jd(y - 1, 12, 31, fix_style(jd, sg)) return y, doy end # Convert a Civil Date to a Julian Day Number. # +y+, +m+, and +d+ are the year, month, and day of the # month. +sg+ specifies the Day of Calendar Reform. # # Returns the corresponding Julian Day Number. def self.civil_to_jd(y, m, d, sg=GREGORIAN) if m <= 2 y -= 1 m += 12 end a = (y / 100.0).floor b = 2 - a + (a / 4.0).floor jd = (365.25 * (y + 4716)).floor + (30.6001 * (m + 1)).floor + d + b - 1524 if julian?(jd, sg) jd -= b end jd end # Convert a Julian Day Number to a Civil Date. +jd+ is # the Julian Day Number. +sg+ specifies the Day of # Calendar Reform. # # Returns the corresponding [year, month, day_of_month] # as a three-element array. def self.jd_to_civil(jd, sg=GREGORIAN) if julian?(jd, sg) a = jd else x = ((jd - 1867216.25) / 36524.25).floor a = jd + 1 + x - (x / 4.0).floor end b = a + 1524 c = ((b - 122.1) / 365.25).floor d = (365.25 * c).floor e = ((b - d) / 30.6001).floor dom = b - d - (30.6001 * e).floor if e <= 13 m = e - 1 y = c - 4716 else m = e - 13 y = c - 4715 end return y, m, dom end # Convert a Commercial Date to a Julian Day Number. # # +y+, +w+, and +d+ are the (commercial) year, week of the year, # and day of the week of the Commercial Date to convert. # +sg+ specifies the Day of Calendar Reform. def self.commercial_to_jd(y, w, d, ns=GREGORIAN) jd = civil_to_jd(y, 1, 4, ns) (jd - (((jd - 1) + 1) % 7)) + 7 * (w - 1) + (d - 1) end # Convert a Julian Day Number to a Commercial Date # # +jd+ is the Julian Day Number to convert. # +sg+ specifies the Day of Calendar Reform. # # Returns the corresponding Commercial Date as # [commercial_year, week_of_year, day_of_week] def self.jd_to_commercial(jd, sg=GREGORIAN) ns = fix_style(jd, sg) a = jd_to_civil(jd - 3, ns)[0] y = if jd >= commercial_to_jd(a + 1, 1, 1, ns) then a + 1 else a end w = 1 + ((jd - commercial_to_jd(y, 1, 1, ns)) / 7).floor d = (jd + 1) % 7 d = 7 if d == 0 return y, w, d end def self.weeknum_to_jd(y, w, d, f=0, ns=GREGORIAN) # :nodoc: a = civil_to_jd(y, 1, 1, ns) + 6 (a - ((a - f) + 1) % 7 - 7) + 7 * w + d end def self.jd_to_weeknum(jd, f=0, sg=GREGORIAN) # :nodoc: ns = fix_style(jd, sg) y, m, d = jd_to_civil(jd, ns) a = civil_to_jd(y, 1, 1, ns) + 6 w, d = (jd - (a - ((a - f) + 1) % 7) + 7).divmod(7) return y, w, d end private_class_method :weeknum_to_jd, :jd_to_weeknum # Convert an Astronomical Julian Day Number to a (civil) Julian # Day Number. # # +ajd+ is the Astronomical Julian Day Number to convert. # +of+ is the offset from UTC as a fraction of a day (defaults to 0). # # Returns the (civil) Julian Day Number as [day_number, # fraction] where +fraction+ is always 1/2. def self.ajd_to_jd(ajd, of=0) (ajd + of + HALF_DAYS_IN_DAY).divmod(1) end # Convert a (civil) Julian Day Number to an Astronomical Julian # Day Number. # # +jd+ is the Julian Day Number to convert, and +fr+ is a # fractional day. # +of+ is the offset from UTC as a fraction of a day (defaults to 0). # # Returns the Astronomical Julian Day Number as a single # numeric value. def self.jd_to_ajd(jd, fr, of=0) jd + fr - of - HALF_DAYS_IN_DAY end # Convert a fractional day +fr+ to [hours, minutes, seconds, # fraction_of_a_second] def self.day_fraction_to_time(fr) ss, fr = fr.divmod(SECONDS_IN_DAY) # 4p h, ss = ss.divmod(3600) min, s = ss.divmod(60) return h, min, s, fr end # Convert an +h+ hour, +min+ minutes, +s+ seconds period # to a fractional day. begin Rational(Rational(1, 2), 2) # a challenge def self.time_to_day_fraction(h, min, s) Rational(h * 3600 + min * 60 + s, 86400) # 4p end rescue def self.time_to_day_fraction(h, min, s) if Integer === h && Integer === min && Integer === s Rational(h * 3600 + min * 60 + s, 86400) # 4p else (h * 3600 + min * 60 + s).to_r/86400 # 4p end end end # Convert an Astronomical Modified Julian Day Number to an # Astronomical Julian Day Number. def self.amjd_to_ajd(amjd) amjd + MJD_EPOCH_IN_AJD end # Convert an Astronomical Julian Day Number to an # Astronomical Modified Julian Day Number. def self.ajd_to_amjd(ajd) ajd - MJD_EPOCH_IN_AJD end # Convert a Modified Julian Day Number to a Julian # Day Number. def self.mjd_to_jd(mjd) mjd + MJD_EPOCH_IN_CJD end # Convert a Julian Day Number to a Modified Julian Day # Number. def self.jd_to_mjd(jd) jd - MJD_EPOCH_IN_CJD end # Convert a count of the number of days since the adoption # of the Gregorian Calendar (in Italy) to a Julian Day Number. def self.ld_to_jd(ld) ld + LD_EPOCH_IN_CJD end # Convert a Julian Day Number to the number of days since # the adoption of the Gregorian Calendar (in Italy). def self.jd_to_ld(jd) jd - LD_EPOCH_IN_CJD end # Convert a Julian Day Number to the day of the week. # # Sunday is day-of-week 0; Saturday is day-of-week 6. def self.jd_to_wday(jd) (jd + 1) % 7 end # Is a year a leap year in the Julian calendar? # # All years divisible by 4 are leap years in the Julian calendar. def self.julian_leap? (y) y % 4 == 0 end # Is a year a leap year in the Gregorian calendar? # # All years divisible by 4 are leap years in the Gregorian calendar, # except for years divisible by 100 and not by 400. def self.gregorian_leap? (y) y % 4 == 0 && y % 100 != 0 || y % 400 == 0 end class << self; alias_method :leap?, :gregorian_leap? end class << self; alias_method :new!, :new end # Is +jd+ a valid Julian Day Number? # # If it is, returns it. In fact, any value is treated as a valid # Julian Day Number. def self.valid_jd? (jd, sg=ITALY) jd end # Do the year +y+ and day-of-year +d+ make a valid Ordinal Date? # Returns the corresponding Julian Day Number if they do, or # nil if they don't. # # +d+ can be a negative number, in which case it counts backwards # from the end of the year (-1 being the last day of the year). # No year wraparound is performed, however, so valid values of # +d+ are -365 .. -1, 1 .. 365 on a non-leap-year, # -366 .. -1, 1 .. 366 on a leap year. # A date falling in the period skipped in the Day of Calendar Reform # adjustment is not valid. # # +sg+ specifies the Day of Calendar Reform. def self.valid_ordinal? (y, d, sg=ITALY) if d < 0 ny, = (y + 1).divmod(1) jd = ordinal_to_jd(ny, d + 1, sg) ns = fix_style(jd, sg) return unless [y] == jd_to_ordinal(jd, sg)[0..0] return unless [ny, 1] == jd_to_ordinal(jd - d, ns) else jd = ordinal_to_jd(y, d, sg) return unless [y, d] == jd_to_ordinal(jd, sg) end jd end # Do year +y+, month +m+, and day-of-month +d+ make a # valid Civil Date? Returns the corresponding Julian # Day Number if they do, nil if they don't. # # +m+ and +d+ can be negative, in which case they count # backwards from the end of the year and the end of the # month respectively. No wraparound is performed, however, # and invalid values cause an ArgumentError to be raised. # A date falling in the period skipped in the Day of Calendar # Reform adjustment is not valid. # # +sg+ specifies the Day of Calendar Reform. def self.valid_civil? (y, m, d, sg=ITALY) if m < 0 m += 13 end if d < 0 ny, nm = (y * 12 + m).divmod(12) nm, = (nm + 1).divmod(1) jd = civil_to_jd(ny, nm, d + 1, sg) ns = fix_style(jd, sg) return unless [y, m] == jd_to_civil(jd, sg)[0..1] return unless [ny, nm, 1] == jd_to_civil(jd - d, ns) else jd = civil_to_jd(y, m, d, sg) return unless [y, m, d] == jd_to_civil(jd, sg) end jd end class << self; alias_method :valid_date?, :valid_civil? end # Do year +y+, week-of-year +w+, and day-of-week +d+ make a # valid Commercial Date? Returns the corresponding Julian # Day Number if they do, nil if they don't. # # Monday is day-of-week 1; Sunday is day-of-week 7. # # +w+ and +d+ can be negative, in which case they count # backwards from the end of the year and the end of the # week respectively. No wraparound is performed, however, # and invalid values cause an ArgumentError to be raised. # A date falling in the period skipped in the Day of Calendar # Reform adjustment is not valid. # # +sg+ specifies the Day of Calendar Reform. def self.valid_commercial? (y, w, d, sg=ITALY) if d < 0 d += 8 end if w < 0 ny, nw, nd = jd_to_commercial(commercial_to_jd(y + 1, 1, 1) + w * 7) return unless ny == y w = nw end jd = commercial_to_jd(y, w, d) return unless gregorian?(jd, sg) return unless [y, w, d] == jd_to_commercial(jd) jd end def self.valid_weeknum? (y, w, d, f, sg=ITALY) # :nodoc: if d < 0 d += 7 end if w < 0 ny, nw, nd, nf = jd_to_weeknum(weeknum_to_jd(y + 1, 1, f, f) + w * 7, f) return unless ny == y w = nw end jd = weeknum_to_jd(y, w, d, f) return unless gregorian?(jd, sg) return unless [y, w, d] == jd_to_weeknum(jd, f) jd end private_class_method :valid_weeknum? # Do hour +h+, minute +min+, and second +s+ constitute a valid time? # # If they do, returns their value as a fraction of a day. If not, # returns nil. # # The 24-hour clock is used. Negative values of +h+, +min+, and # +sec+ are treating as counting backwards from the end of the # next larger unit (e.g. a +min+ of -2 is treated as 58). No # wraparound is performed. def self.valid_time? (h, min, s) h += 24 if h < 0 min += 60 if min < 0 s += 60 if s < 0 return unless ((0...24) === h && (0...60) === min && (0...60) === s) || (24 == h && 0 == min && 0 == s) time_to_day_fraction(h, min, s) end # Create a new Date object from a Julian Day Number. # # +jd+ is the Julian Day Number; if not specified, it defaults to # 0. # +sg+ specifies the Day of Calendar Reform. def self.jd(jd=0, sg=ITALY) jd = valid_jd?(jd, sg) new!(jd_to_ajd(jd, 0, 0), 0, sg) end # Create a new Date object from an Ordinal Date, specified # by year +y+ and day-of-year +d+. +d+ can be negative, # in which it counts backwards from the end of the year. # No year wraparound is performed, however. An invalid # value for +d+ results in an ArgumentError being raised. # # +y+ defaults to -4712, and +d+ to 1; this is Julian Day # Number day 0. # # +sg+ specifies the Day of Calendar Reform. def self.ordinal(y=-4712, d=1, sg=ITALY) unless jd = valid_ordinal?(y, d, sg) raise ArgumentError, 'invalid date' end new!(jd_to_ajd(jd, 0, 0), 0, sg) end # Create a new Date object for the Civil Date specified by # year +y+, month +m+, and day-of-month +d+. # # +m+ and +d+ can be negative, in which case they count # backwards from the end of the year and the end of the # month respectively. No wraparound is performed, however, # and invalid values cause an ArgumentError to be raised. # can be negative # # +y+ defaults to -4712, +m+ to 1, and +d+ to 1; this is # Julian Day Number day 0. # # +sg+ specifies the Day of Calendar Reform. def self.civil(y=-4712, m=1, d=1, sg=ITALY) unless jd = valid_civil?(y, m, d, sg) raise ArgumentError, 'invalid date' end new!(jd_to_ajd(jd, 0, 0), 0, sg) end class << self; alias_method :new, :civil end # Create a new Date object for the Commercial Date specified by # year +y+, week-of-year +w+, and day-of-week +d+. # # Monday is day-of-week 1; Sunday is day-of-week 7. # # +w+ and +d+ can be negative, in which case they count # backwards from the end of the year and the end of the # week respectively. No wraparound is performed, however, # and invalid values cause an ArgumentError to be raised. # # +y+ defaults to 1582, +w+ to 41, and +d+ to 5, the Day of # Calendar Reform for Italy and the Catholic countries. # # +sg+ specifies the Day of Calendar Reform. def self.commercial(y=1582, w=41, d=5, sg=ITALY) unless jd = valid_commercial?(y, w, d, sg) raise ArgumentError, 'invalid date' end new!(jd_to_ajd(jd, 0, 0), 0, sg) end def self.weeknum(y=1582, w=41, d=5, f=0, sg=ITALY) # :nodoc: unless jd = valid_weeknum?(y, w, d, f, sg) raise ArgumentError, 'invalid date' end new!(jd_to_ajd(jd, 0, 0), 0, sg) end private_class_method :weeknum def self.rewrite_frags(elem) # :nodoc: elem ||= {} if seconds = elem[:seconds] d, fr = seconds.divmod(86400) h, fr = fr.divmod(3600) min, fr = fr.divmod(60) s, fr = fr.divmod(1) elem[:jd] = UNIX_EPOCH_IN_CJD + d elem[:hour] = h elem[:min] = min elem[:sec] = s elem[:sec_fraction] = fr elem.delete(:seconds) elem.delete(:offset) end elem end private_class_method :rewrite_frags def self.complete_frags(elem) # :nodoc: i = 0 g = [[:time, [:hour, :min, :sec]], [nil, [:jd]], [:ordinal, [:year, :yday, :hour, :min, :sec]], [:civil, [:year, :mon, :mday, :hour, :min, :sec]], [:commercial, [:cwyear, :cweek, :cwday, :hour, :min, :sec]], [:wday, [:wday, :hour, :min, :sec]], [:wnum0, [:year, :wnum0, :wday, :hour, :min, :sec]], [:wnum1, [:year, :wnum1, :wday, :hour, :min, :sec]], [nil, [:cwyear, :cweek, :wday, :hour, :min, :sec]], [nil, [:year, :wnum0, :cwday, :hour, :min, :sec]], [nil, [:year, :wnum1, :cwday, :hour, :min, :sec]]]. collect{|k, a| e = elem.values_at(*a).compact; [k, a, e]}. select{|k, a, e| e.size > 0}. sort_by{|k, a, e| [e.size, i -= 1]}.last d = nil if g && g[0] && (g[1].size - g[2].size) != 0 d ||= Date.today case g[0] when :ordinal elem[:year] ||= d.year elem[:yday] ||= 1 when :civil g[1].each do |e| break if elem[e] elem[e] = d.__send__(e) end elem[:mon] ||= 1 elem[:mday] ||= 1 when :commercial g[1].each do |e| break if elem[e] elem[e] = d.__send__(e) end elem[:cweek] ||= 1 elem[:cwday] ||= 1 when :wday elem[:jd] ||= (d - d.wday + elem[:wday]).jd when :wnum0 g[1].each do |e| break if elem[e] elem[e] = d.__send__(e) end elem[:wnum0] ||= 0 elem[:wday] ||= 0 when :wnum1 g[1].each do |e| break if elem[e] elem[e] = d.__send__(e) end elem[:wnum1] ||= 0 elem[:wday] ||= 0 end end if g && g[0] == :time if self <= DateTime d ||= Date.today elem[:jd] ||= d.jd end end elem[:hour] ||= 0 elem[:min] ||= 0 elem[:sec] ||= 0 elem[:sec] = [elem[:sec], 59].min elem end private_class_method :complete_frags def self.valid_date_frags?(elem, sg) # :nodoc: catch :jd do a = elem.values_at(:jd) if a.all? if jd = valid_jd?(*(a << sg)) throw :jd, jd end end a = elem.values_at(:year, :yday) if a.all? if jd = valid_ordinal?(*(a << sg)) throw :jd, jd end end a = elem.values_at(:year, :mon, :mday) if a.all? if jd = valid_civil?(*(a << sg)) throw :jd, jd end end a = elem.values_at(:cwyear, :cweek, :cwday) if a[2].nil? && elem[:wday] a[2] = elem[:wday].nonzero? || 7 end if a.all? if jd = valid_commercial?(*(a << sg)) throw :jd, jd end end a = elem.values_at(:year, :wnum0, :wday) if a[2].nil? && elem[:cwday] a[2] = elem[:cwday] % 7 end if a.all? if jd = valid_weeknum?(*(a << 0 << sg)) throw :jd, jd end end a = elem.values_at(:year, :wnum1, :wday) if a[2] a[2] = (a[2] - 1) % 7 end if a[2].nil? && elem[:cwday] a[2] = (elem[:cwday] - 1) % 7 end if a.all? if jd = valid_weeknum?(*(a << 1 << sg)) throw :jd, jd end end end end private_class_method :valid_date_frags? def self.valid_time_frags? (elem) # :nodoc: h, min, s = elem.values_at(:hour, :min, :sec) valid_time?(h, min, s) end private_class_method :valid_time_frags? def self.new_by_frags(elem, sg) # :nodoc: elem = rewrite_frags(elem) elem = complete_frags(elem) unless jd = valid_date_frags?(elem, sg) raise ArgumentError, 'invalid date' end new!(jd_to_ajd(jd, 0, 0), 0, sg) end private_class_method :new_by_frags # Create a new Date object by parsing from a String # according to a specified format. # # +str+ is a String holding a date representation. # +fmt+ is the format that the date is in. See # date/format.rb for details on supported formats. # # The default +str+ is '-4712-01-01', and the default # +fmt+ is '%F', which means Year-Month-Day_of_Month. # This gives Julian Day Number day 0. # # +sg+ specifies the Day of Calendar Reform. # # An ArgumentError will be raised if +str+ cannot be # parsed. def self.strptime(str='-4712-01-01', fmt='%F', sg=ITALY) elem = _strptime(str, fmt) new_by_frags(elem, sg) end # Create a new Date object by parsing from a String, # without specifying the format. # # +str+ is a String holding a date representation. # +comp+ specifies whether to interpret 2-digit years # as 19XX (>= 69) or 20XX (< 69); the default is not to. # The method will attempt to parse a date from the String # using various heuristics; see #_parse in date/format.rb # for more details. If parsing fails, an ArgumentError # will be raised. # # The default +str+ is '-4712-01-01'; this is Julian # Day Number day 0. # # +sg+ specifies the Day of Calendar Reform. def self.parse(str='-4712-01-01', comp=false, sg=ITALY) elem = _parse(str, comp) new_by_frags(elem, sg) end class << self def once(*ids) # :nodoc: for id in ids module_eval <<-"end;" alias_method :__#{id.to_i}__, :#{id.to_s} private :__#{id.to_i}__ def #{id.to_s}(*args, &block) (@__#{id.to_i}__ ||= [__#{id.to_i}__(*args, &block)])[0] end end; end end private :once end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
true
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/pp.rb
tools/jruby-1.5.1/lib/ruby/1.8/pp.rb
# == Pretty-printer for Ruby objects. # # = Which seems better? # # non-pretty-printed output by #p is: # #<PP:0x81fedf0 @genspace=#<Proc:0x81feda0>, @group_queue=#<PrettyPrint::GroupQueue:0x81fed3c @queue=[[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], []]>, @buffer=[], @newline="\n", @group_stack=[#<PrettyPrint::Group:0x81fed78 @breakables=[], @depth=0, @break=false>], @buffer_width=0, @indent=0, @maxwidth=79, @output_width=2, @output=#<IO:0x8114ee4>> # # pretty-printed output by #pp is: # #<PP:0x81fedf0 # @buffer=[], # @buffer_width=0, # @genspace=#<Proc:0x81feda0>, # @group_queue= # #<PrettyPrint::GroupQueue:0x81fed3c # @queue= # [[#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>], # []]>, # @group_stack= # [#<PrettyPrint::Group:0x81fed78 @break=false, @breakables=[], @depth=0>], # @indent=0, # @maxwidth=79, # @newline="\n", # @output=#<IO:0x8114ee4>, # @output_width=2> # # I like the latter. If you do too, this library is for you. # # = Usage # # pp(obj) # # output +obj+ to +$>+ in pretty printed format. # # It returns +nil+. # # = Output Customization # To define your customized pretty printing function for your classes, # redefine a method #pretty_print(+pp+) in the class. # It takes an argument +pp+ which is an instance of the class PP. # The method should use PP#text, PP#breakable, PP#nest, PP#group and # PP#pp to print the object. # # = Author # Tanaka Akira <akr@m17n.org> require 'prettyprint' module Kernel # returns a pretty printed object as a string. def pretty_inspect PP.pp(self, '') end private # prints arguments in pretty form. # # pp returns nil. def pp(*objs) # :doc: objs.each {|obj| PP.pp(obj) } nil end module_function :pp end class PP < PrettyPrint # Outputs +obj+ to +out+ in pretty printed format of # +width+ columns in width. # # If +out+ is omitted, +$>+ is assumed. # If +width+ is omitted, 79 is assumed. # # PP.pp returns +out+. def PP.pp(obj, out=$>, width=79) q = PP.new(out, width) q.guard_inspect_key {q.pp obj} q.flush #$pp = q out << "\n" end # Outputs +obj+ to +out+ like PP.pp but with no indent and # newline. # # PP.singleline_pp returns +out+. def PP.singleline_pp(obj, out=$>) q = SingleLine.new(out) q.guard_inspect_key {q.pp obj} q.flush out end # :stopdoc: def PP.mcall(obj, mod, meth, *args, &block) mod.instance_method(meth).bind(obj).call(*args, &block) end # :startdoc: @sharing_detection = false class << self # Returns the sharing detection flag as a boolean value. # It is false by default. attr_accessor :sharing_detection end module PPMethods InspectKey = :__inspect_key__ def guard_inspect_key if Thread.current[InspectKey] == nil Thread.current[InspectKey] = [] end save = Thread.current[InspectKey] begin Thread.current[InspectKey] = [] yield ensure Thread.current[InspectKey] = save end end # Adds +obj+ to the pretty printing buffer # using Object#pretty_print or Object#pretty_print_cycle. # # Object#pretty_print_cycle is used when +obj+ is already # printed, a.k.a the object reference chain has a cycle. def pp(obj) id = obj.__id__ if Thread.current[InspectKey].include? id group {obj.pretty_print_cycle self} return end begin Thread.current[InspectKey] << id group {obj.pretty_print self} ensure Thread.current[InspectKey].pop unless PP.sharing_detection end end # A convenience method which is same as follows: # # group(1, '#<' + obj.class.name, '>') { ... } def object_group(obj, &block) # :yield: group(1, '#<' + obj.class.name, '>', &block) end def object_address_group(obj, &block) id = "%x" % (obj.__id__ * 2) id.sub!(/\Af(?=[[:xdigit:]]{2}+\z)/, '') if id.sub!(/\A\.\./, '') group(1, "\#<#{obj.class}:0x#{id}", '>', &block) end # A convenience method which is same as follows: # # text ',' # breakable def comma_breakable text ',' breakable end # Adds a separated list. # The list is separated by comma with breakable space, by default. # # #seplist iterates the +list+ using +iter_method+. # It yields each object to the block given for #seplist. # The procedure +separator_proc+ is called between each yields. # # If the iteration is zero times, +separator_proc+ is not called at all. # # If +separator_proc+ is nil or not given, # +lambda { comma_breakable }+ is used. # If +iter_method+ is not given, :each is used. # # For example, following 3 code fragments has similar effect. # # q.seplist([1,2,3]) {|v| xxx v } # # q.seplist([1,2,3], lambda { comma_breakable }, :each) {|v| xxx v } # # xxx 1 # q.comma_breakable # xxx 2 # q.comma_breakable # xxx 3 def seplist(list, sep=nil, iter_method=:each) # :yield: element sep ||= lambda { comma_breakable } first = true list.__send__(iter_method) {|*v| if first first = false else sep.call end yield(*v) } end def pp_object(obj) object_address_group(obj) { seplist(obj.pretty_print_instance_variables, lambda { text ',' }) {|v| breakable v = v.to_s if Symbol === v text v text '=' group(1) { breakable '' pp(obj.instance_eval(v)) } } } end def pp_hash(obj) group(1, '{', '}') { seplist(obj, nil, :each_pair) {|k, v| group { pp k text '=>' group(1) { breakable '' pp v } } } } end end include PPMethods class SingleLine < PrettyPrint::SingleLine include PPMethods end module ObjectMixin # 1. specific pretty_print # 2. specific inspect # 3. specific to_s if instance variable is empty # 4. generic pretty_print # A default pretty printing method for general objects. # It calls #pretty_print_instance_variables to list instance variables. # # If +self+ has a customized (redefined) #inspect method, # the result of self.inspect is used but it obviously has no # line break hints. # # This module provides predefined #pretty_print methods for some of # the most commonly used built-in classes for convenience. def pretty_print(q) if /\(Kernel\)#/ !~ Object.instance_method(:method).bind(self).call(:inspect).inspect q.text self.inspect elsif /\(Kernel\)#/ !~ Object.instance_method(:method).bind(self).call(:to_s).inspect && instance_variables.empty? q.text self.to_s else q.pp_object(self) end end # A default pretty printing method for general objects that are # detected as part of a cycle. def pretty_print_cycle(q) q.object_address_group(self) { q.breakable q.text '...' } end # Returns a sorted array of instance variable names. # # This method should return an array of names of instance variables as symbols or strings as: # +[:@a, :@b]+. def pretty_print_instance_variables instance_variables.sort end # Is #inspect implementation using #pretty_print. # If you implement #pretty_print, it can be used as follows. # # alias inspect pretty_print_inspect # # However, doing this requires that every class that #inspect is called on # implement #pretty_print, or a RuntimeError will be raised. def pretty_print_inspect if /\(PP::ObjectMixin\)#/ =~ Object.instance_method(:method).bind(self).call(:pretty_print).inspect raise "pretty_print is not overridden for #{self.class}" end PP.singleline_pp(self, '') end end end class Array def pretty_print(q) q.group(1, '[', ']') { q.seplist(self) {|v| q.pp v } } end def pretty_print_cycle(q) q.text(empty? ? '[]' : '[...]') end end class Hash def pretty_print(q) q.pp_hash self end def pretty_print_cycle(q) q.text(empty? ? '{}' : '{...}') end end class << ENV def pretty_print(q) q.pp_hash self end end class Struct def pretty_print(q) q.group(1, '#<struct ' + PP.mcall(self, Kernel, :class).name, '>') { q.seplist(PP.mcall(self, Struct, :members), lambda { q.text "," }) {|member| q.breakable q.text member.to_s q.text '=' q.group(1) { q.breakable '' q.pp self[member] } } } end def pretty_print_cycle(q) q.text sprintf("#<struct %s:...>", PP.mcall(self, Kernel, :class).name) end end class Range def pretty_print(q) q.pp self.begin q.breakable '' q.text(self.exclude_end? ? '...' : '..') q.breakable '' q.pp self.end end end class File class Stat def pretty_print(q) require 'etc.so' q.object_group(self) { q.breakable q.text sprintf("dev=0x%x", self.dev); q.comma_breakable q.text "ino="; q.pp self.ino; q.comma_breakable q.group { m = self.mode q.text sprintf("mode=0%o", m) q.breakable q.text sprintf("(%s %c%c%c%c%c%c%c%c%c)", self.ftype, (m & 0400 == 0 ? ?- : ?r), (m & 0200 == 0 ? ?- : ?w), (m & 0100 == 0 ? (m & 04000 == 0 ? ?- : ?S) : (m & 04000 == 0 ? ?x : ?s)), (m & 0040 == 0 ? ?- : ?r), (m & 0020 == 0 ? ?- : ?w), (m & 0010 == 0 ? (m & 02000 == 0 ? ?- : ?S) : (m & 02000 == 0 ? ?x : ?s)), (m & 0004 == 0 ? ?- : ?r), (m & 0002 == 0 ? ?- : ?w), (m & 0001 == 0 ? (m & 01000 == 0 ? ?- : ?T) : (m & 01000 == 0 ? ?x : ?t))) } q.comma_breakable q.text "nlink="; q.pp self.nlink; q.comma_breakable q.group { q.text "uid="; q.pp self.uid begin pw = Etc.getpwuid(self.uid) rescue ArgumentError end if pw q.breakable; q.text "(#{pw.name})" end } q.comma_breakable q.group { q.text "gid="; q.pp self.gid begin gr = Etc.getgrgid(self.gid) rescue ArgumentError end if gr q.breakable; q.text "(#{gr.name})" end } q.comma_breakable q.group { q.text sprintf("rdev=0x%x", self.rdev) q.breakable q.text sprintf('(%d, %d)', self.rdev_major, self.rdev_minor) } q.comma_breakable q.text "size="; q.pp self.size; q.comma_breakable q.text "blksize="; q.pp self.blksize; q.comma_breakable q.text "blocks="; q.pp self.blocks; q.comma_breakable q.group { t = self.atime q.text "atime="; q.pp t q.breakable; q.text "(#{t.tv_sec})" } q.comma_breakable q.group { t = self.mtime q.text "mtime="; q.pp t q.breakable; q.text "(#{t.tv_sec})" } q.comma_breakable q.group { t = self.ctime q.text "ctime="; q.pp t q.breakable; q.text "(#{t.tv_sec})" } } end end end class MatchData def pretty_print(q) q.object_group(self) { q.breakable q.seplist(1..self.size, lambda { q.breakable }) {|i| q.pp self[i-1] } } end end class Object include PP::ObjectMixin end [Numeric, Symbol, FalseClass, TrueClass, NilClass, Module].each {|c| c.class_eval { def pretty_print_cycle(q) q.text inspect end } } [Numeric, FalseClass, TrueClass, Module].each {|c| c.class_eval { def pretty_print(q) q.text inspect end } } # :enddoc: if __FILE__ == $0 require 'test/unit' class PPTest < Test::Unit::TestCase def test_list0123_12 assert_equal("[0, 1, 2, 3]\n", PP.pp([0,1,2,3], '', 12)) end def test_list0123_11 assert_equal("[0,\n 1,\n 2,\n 3]\n", PP.pp([0,1,2,3], '', 11)) end OverriddenStruct = Struct.new("OverriddenStruct", :members, :class) def test_struct_override_members # [ruby-core:7865] a = OverriddenStruct.new(1,2) assert_equal("#<struct Struct::OverriddenStruct members=1, class=2>\n", PP.pp(a, '')) end def test_redefined_method o = "" def o.method end assert_equal(%(""\n), PP.pp(o, "")) end end class HasInspect def initialize(a) @a = a end def inspect return "<inspect:#{@a.inspect}>" end end class HasPrettyPrint def initialize(a) @a = a end def pretty_print(q) q.text "<pretty_print:" q.pp @a q.text ">" end end class HasBoth def initialize(a) @a = a end def inspect return "<inspect:#{@a.inspect}>" end def pretty_print(q) q.text "<pretty_print:" q.pp @a q.text ">" end end class PrettyPrintInspect < HasPrettyPrint alias inspect pretty_print_inspect end class PrettyPrintInspectWithoutPrettyPrint alias inspect pretty_print_inspect end class PPInspectTest < Test::Unit::TestCase def test_hasinspect a = HasInspect.new(1) assert_equal("<inspect:1>\n", PP.pp(a, '')) end def test_hasprettyprint a = HasPrettyPrint.new(1) assert_equal("<pretty_print:1>\n", PP.pp(a, '')) end def test_hasboth a = HasBoth.new(1) assert_equal("<pretty_print:1>\n", PP.pp(a, '')) end def test_pretty_print_inspect a = PrettyPrintInspect.new(1) assert_equal("<pretty_print:1>", a.inspect) a = PrettyPrintInspectWithoutPrettyPrint.new assert_raise(RuntimeError) { a.inspect } end def test_proc a = proc {1} assert_equal("#{a.inspect}\n", PP.pp(a, '')) end def test_to_s_with_iv a = Object.new def a.to_s() "aaa" end a.instance_eval { @a = nil } result = PP.pp(a, '') assert_equal("#{a.inspect}\n", result) assert_match(/\A#<Object.*>\n\z/m, result) a = 1.0 a.instance_eval { @a = nil } result = PP.pp(a, '') assert_equal("#{a.inspect}\n", result) end def test_to_s_without_iv a = Object.new def a.to_s() "aaa" end result = PP.pp(a, '') assert_equal("#{a.inspect}\n", result) assert_equal("aaa\n", result) end end class PPCycleTest < Test::Unit::TestCase def test_array a = [] a << a assert_equal("[[...]]\n", PP.pp(a, '')) assert_equal("#{a.inspect}\n", PP.pp(a, '')) end def test_hash a = {} a[0] = a assert_equal("{0=>{...}}\n", PP.pp(a, '')) assert_equal("#{a.inspect}\n", PP.pp(a, '')) end S = Struct.new("S", :a, :b) def test_struct a = S.new(1,2) a.b = a assert_equal("#<struct Struct::S a=1, b=#<struct Struct::S:...>>\n", PP.pp(a, '')) assert_equal("#{a.inspect}\n", PP.pp(a, '')) end def test_object a = Object.new a.instance_eval {@a = a} assert_equal(a.inspect + "\n", PP.pp(a, '')) end def test_anonymous a = Class.new.new assert_equal(a.inspect + "\n", PP.pp(a, '')) end def test_withinspect a = [] a << HasInspect.new(a) assert_equal("[<inspect:[...]>]\n", PP.pp(a, '')) assert_equal("#{a.inspect}\n", PP.pp(a, '')) end def test_share_nil begin PP.sharing_detection = true a = [nil, nil] assert_equal("[nil, nil]\n", PP.pp(a, '')) ensure PP.sharing_detection = false end end end class PPSingleLineTest < Test::Unit::TestCase def test_hash assert_equal("{1=>1}", PP.singleline_pp({ 1 => 1}, '')) # [ruby-core:02699] assert_equal("[1#{', 1'*99}]", PP.singleline_pp([1]*100, '')) end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/date2.rb
tools/jruby-1.5.1/lib/ruby/1.8/date2.rb
# date2 was overridden by date. # To be precise, date was overridden by date2, # and date2 was renamed to date. require 'date'
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/resolv-replace.rb
tools/jruby-1.5.1/lib/ruby/1.8/resolv-replace.rb
require 'socket' require 'resolv' class << IPSocket alias original_resolv_getaddress getaddress def getaddress(host) begin return Resolv.getaddress(host).to_s rescue Resolv::ResolvError raise SocketError, "Hostname not known: #{host}" end end end class TCPSocket alias original_resolv_initialize initialize def initialize(host, serv, *rest) rest[0] = IPSocket.getaddress(rest[0]) unless rest.empty? original_resolv_initialize(IPSocket.getaddress(host), serv, *rest) end end class UDPSocket alias original_resolv_bind bind def bind(host, port) host = IPSocket.getaddress(host) if host != "" original_resolv_bind(host, port) end alias original_resolv_connect connect def connect(host, port) original_resolv_connect(IPSocket.getaddress(host), port) end alias original_resolv_send send def send(mesg, flags, *rest) if rest.length == 2 host, port = rest begin addrs = Resolv.getaddresses(host) rescue Resolv::ResolvError raise SocketError, "Hostname not known: #{host}" end err = nil addrs[0...-1].each {|addr| begin return original_resolv_send(mesg, flags, addr, port) rescue SystemCallError end } original_resolv_send(mesg, flags, addrs[-1], port) else original_resolv_send(mesg, flags, *rest) end end end class SOCKSSocket alias original_resolv_initialize initialize def initialize(host, serv) original_resolv_initialize(IPSocket.getaddress(host), port) end end if defined? SOCKSSocket
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/e2mmap.rb
tools/jruby-1.5.1/lib/ruby/1.8/e2mmap.rb
# # e2mmap.rb - for ruby 1.1 # $Release Version: 2.0$ # $Revision: 1.10 $ # $Date: 1999/02/17 12:33:17 $ # by Keiju ISHITSUKA # # -- # Usage: # # U1) # class Foo # extend Exception2MessageMapper # def_e2message ExistingExceptionClass, "message..." # def_exception :NewExceptionClass, "message..."[, superclass] # ... # end # # U2) # module Error # extend Exception2MessageMapper # def_e2meggage ExistingExceptionClass, "message..." # def_exception :NewExceptionClass, "message..."[, superclass] # ... # end # class Foo # include Error # ... # end # # foo = Foo.new # foo.Fail .... # # U3) # module Error # extend Exception2MessageMapper # def_e2message ExistingExceptionClass, "message..." # def_exception :NewExceptionClass, "message..."[, superclass] # ... # end # class Foo # extend Exception2MessageMapper # include Error # ... # end # # Foo.Fail NewExceptionClass, arg... # Foo.Fail ExistingExceptionClass, arg... # # fail "Use Ruby 1.1" if VERSION < "1.1" module Exception2MessageMapper @RCS_ID='-$Id: e2mmap.rb,v 1.10 1999/02/17 12:33:17 keiju Exp keiju $-' E2MM = Exception2MessageMapper def E2MM.extend_object(cl) super cl.bind(self) unless cl == E2MM end # backward compatibility def E2MM.extend_to(b) c = eval("self", b) c.extend(self) end def bind(cl) self.module_eval %[ def Raise(err = nil, *rest) Exception2MessageMapper.Raise(self.class, err, *rest) end alias Fail Raise def self.included(mod) mod.extend Exception2MessageMapper end ] end # Fail(err, *rest) # err: exception # rest: message arguments # def Raise(err = nil, *rest) E2MM.Raise(self, err, *rest) end alias Fail Raise # backward compatibility alias fail! fail def fail(err = nil, *rest) begin E2MM.Fail(self, err, *rest) rescue E2MM::ErrNotRegisteredException super end end class << self public :fail end # def_e2message(c, m) # c: exception # m: message_form # define exception c with message m. # def def_e2message(c, m) E2MM.def_e2message(self, c, m) end # def_exception(n, m, s) # n: exception_name # m: message_form # s: superclass(default: StandardError) # define exception named ``c'' with message m. # def def_exception(n, m, s = StandardError) E2MM.def_exception(self, n, m, s) end # # Private definitions. # # {[class, exp] => message, ...} @MessageMap = {} # E2MM.def_exception(k, e, m) # k: class to define exception under. # e: exception # m: message_form # define exception c with message m. # def E2MM.def_e2message(k, c, m) E2MM.instance_eval{@MessageMap[[k, c]] = m} c end # E2MM.def_exception(k, n, m, s) # k: class to define exception under. # n: exception_name # m: message_form # s: superclass(default: StandardError) # define exception named ``c'' with message m. # def E2MM.def_exception(k, n, m, s = StandardError) n = n.id2name if n.kind_of?(Fixnum) e = Class.new(s) E2MM.instance_eval{@MessageMap[[k, e]] = m} k.const_set(n, e) end # Fail(klass, err, *rest) # klass: class to define exception under. # err: exception # rest: message arguments # def E2MM.Raise(klass = E2MM, err = nil, *rest) if form = e2mm_message(klass, err) $! = err.new(sprintf(form, *rest)) $@ = caller(1) if $@.nil? #p $@ #p __FILE__ $@.shift if $@[0] =~ /^#{Regexp.quote(__FILE__)}:/ raise else E2MM.Fail E2MM, ErrNotRegisteredException, err.inspect end end class <<E2MM alias Fail Raise end def E2MM.e2mm_message(klass, exp) for c in klass.ancestors if mes = @MessageMap[[c,exp]] #p mes m = klass.instance_eval('"' + mes + '"') return m end end nil end class <<self alias message e2mm_message end E2MM.def_exception(E2MM, :ErrNotRegisteredException, "not registerd exception(%s)") end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/cgi/session.rb
tools/jruby-1.5.1/lib/ruby/1.8/cgi/session.rb
# # cgi/session.rb - session support for cgi scripts # # Copyright (C) 2001 Yukihiro "Matz" Matsumoto # Copyright (C) 2000 Network Applied Communication Laboratory, Inc. # Copyright (C) 2000 Information-technology Promotion Agency, Japan # # Author: Yukihiro "Matz" Matsumoto # # Documentation: William Webber (william@williamwebber.com) # # == Overview # # This file provides the +CGI::Session+ class, which provides session # support for CGI scripts. A session is a sequence of HTTP requests # and responses linked together and associated with a single client. # Information associated with the session is stored # on the server between requests. A session id is passed between client # and server with every request and response, transparently # to the user. This adds state information to the otherwise stateless # HTTP request/response protocol. # # See the documentation to the +CGI::Session+ class for more details # and examples of usage. See cgi.rb for the +CGI+ class itself. require 'cgi' require 'tmpdir' class CGI # Class representing an HTTP session. See documentation for the file # cgi/session.rb for an introduction to HTTP sessions. # # == Lifecycle # # A CGI::Session instance is created from a CGI object. By default, # this CGI::Session instance will start a new session if none currently # exists, or continue the current session for this client if one does # exist. The +new_session+ option can be used to either always or # never create a new session. See #new() for more details. # # #delete() deletes a session from session storage. It # does not however remove the session id from the client. If the client # makes another request with the same id, the effect will be to start # a new session with the old session's id. # # == Setting and retrieving session data. # # The Session class associates data with a session as key-value pairs. # This data can be set and retrieved by indexing the Session instance # using '[]', much the same as hashes (although other hash methods # are not supported). # # When session processing has been completed for a request, the # session should be closed using the close() method. This will # store the session's state to persistent storage. If you want # to store the session's state to persistent storage without # finishing session processing for this request, call the update() # method. # # == Storing session state # # The caller can specify what form of storage to use for the session's # data with the +database_manager+ option to CGI::Session::new. The # following storage classes are provided as part of the standard library: # # CGI::Session::FileStore:: stores data as plain text in a flat file. Only # works with String data. This is the default # storage type. # CGI::Session::MemoryStore:: stores data in an in-memory hash. The data # only persists for as long as the current ruby # interpreter instance does. # CGI::Session::PStore:: stores data in Marshalled format. Provided by # cgi/session/pstore.rb. Supports data of any type, # and provides file-locking and transaction support. # # Custom storage types can also be created by defining a class with # the following methods: # # new(session, options) # restore # returns hash of session data. # update # close # delete # # Changing storage type mid-session does not work. Note in particular # that by default the FileStore and PStore session data files have the # same name. If your application switches from one to the other without # making sure that filenames will be different # and clients still have old sessions lying around in cookies, then # things will break nastily! # # == Maintaining the session id. # # Most session state is maintained on the server. However, a session # id must be passed backwards and forwards between client and server # to maintain a reference to this session state. # # The simplest way to do this is via cookies. The CGI::Session class # provides transparent support for session id communication via cookies # if the client has cookies enabled. # # If the client has cookies disabled, the session id must be included # as a parameter of all requests sent by the client to the server. The # CGI::Session class in conjunction with the CGI class will transparently # add the session id as a hidden input field to all forms generated # using the CGI#form() HTML generation method. No built-in support is # provided for other mechanisms, such as URL re-writing. The caller is # responsible for extracting the session id from the session_id # attribute and manually encoding it in URLs and adding it as a hidden # input to HTML forms created by other mechanisms. Also, session expiry # is not automatically handled. # # == Examples of use # # === Setting the user's name # # require 'cgi' # require 'cgi/session' # require 'cgi/session/pstore' # provides CGI::Session::PStore # # cgi = CGI.new("html4") # # session = CGI::Session.new(cgi, # 'database_manager' => CGI::Session::PStore, # use PStore # 'session_key' => '_rb_sess_id', # custom session key # 'session_expires' => Time.now + 30 * 60, # 30 minute timeout # 'prefix' => 'pstore_sid_') # PStore option # if cgi.has_key?('user_name') and cgi['user_name'] != '' # # coerce to String: cgi[] returns the # # string-like CGI::QueryExtension::Value # session['user_name'] = cgi['user_name'].to_s # elsif !session['user_name'] # session['user_name'] = "guest" # end # session.close # # === Creating a new session safely # # require 'cgi' # require 'cgi/session' # # cgi = CGI.new("html4") # # # We make sure to delete an old session if one exists, # # not just to free resources, but to prevent the session # # from being maliciously hijacked later on. # begin # session = CGI::Session.new(cgi, 'new_session' => false) # session.delete # rescue ArgumentError # if no old session # end # session = CGI::Session.new(cgi, 'new_session' => true) # session.close # class Session class NoSession < RuntimeError #:nodoc: end # The id of this session. attr_reader :session_id, :new_session def Session::callback(dbman) #:nodoc: Proc.new{ dbman[0].close unless dbman.empty? } end # Create a new session id. # # The session id is an MD5 hash based upon the time, # a random number, and a constant string. This routine # is used internally for automatically generated # session ids. def create_new_id require 'securerandom' begin session_id = SecureRandom.hex(16) rescue NotImplementedError require 'digest/md5' md5 = Digest::MD5::new now = Time::now md5.update(now.to_s) md5.update(String(now.usec)) md5.update(String(rand(0))) md5.update(String($$)) md5.update('foobar') session_id = md5.hexdigest end session_id end private :create_new_id # Create a new CGI::Session object for +request+. # # +request+ is an instance of the +CGI+ class (see cgi.rb). # +option+ is a hash of options for initialising this # CGI::Session instance. The following options are # recognised: # # session_key:: the parameter name used for the session id. # Defaults to '_session_id'. # session_id:: the session id to use. If not provided, then # it is retrieved from the +session_key+ parameter # of the request, or automatically generated for # a new session. # new_session:: if true, force creation of a new session. If not set, # a new session is only created if none currently # exists. If false, a new session is never created, # and if none currently exists and the +session_id+ # option is not set, an ArgumentError is raised. # database_manager:: the name of the class providing storage facilities # for session state persistence. Built-in support # is provided for +FileStore+ (the default), # +MemoryStore+, and +PStore+ (from # cgi/session/pstore.rb). See the documentation for # these classes for more details. # # The following options are also recognised, but only apply if the # session id is stored in a cookie. # # session_expires:: the time the current session expires, as a # +Time+ object. If not set, the session will terminate # when the user's browser is closed. # session_domain:: the hostname domain for which this session is valid. # If not set, defaults to the hostname of the server. # session_secure:: if +true+, this session will only work over HTTPS. # session_path:: the path for which this session applies. Defaults # to the directory of the CGI script. # # +option+ is also passed on to the session storage class initializer; see # the documentation for each session storage class for the options # they support. # # The retrieved or created session is automatically added to +request+ # as a cookie, and also to its +output_hidden+ table, which is used # to add hidden input elements to forms. # # *WARNING* the +output_hidden+ # fields are surrounded by a <fieldset> tag in HTML 4 generation, which # is _not_ invisible on many browsers; you may wish to disable the # use of fieldsets with code similar to the following # (see http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-list/37805) # # cgi = CGI.new("html4") # class << cgi # undef_method :fieldset # end # def initialize(request, option={}) @new_session = false session_key = option['session_key'] || '_session_id' session_id = option['session_id'] unless session_id if option['new_session'] session_id = create_new_id @new_session = true end end unless session_id if request.key?(session_key) session_id = request[session_key] session_id = session_id.read if session_id.respond_to?(:read) end unless session_id session_id, = request.cookies[session_key] end unless session_id unless option.fetch('new_session', true) raise ArgumentError, "session_key `%s' should be supplied"%session_key end session_id = create_new_id @new_session = true end end @session_id = session_id dbman = option['database_manager'] || FileStore begin @dbman = dbman::new(self, option) rescue NoSession unless option.fetch('new_session', true) raise ArgumentError, "invalid session_id `%s'"%session_id end session_id = @session_id = create_new_id unless session_id @new_session = true retry end request.instance_eval do @output_hidden = {session_key => session_id} unless option['no_hidden'] @output_cookies = [ Cookie::new("name" => session_key, "value" => session_id, "expires" => option['session_expires'], "domain" => option['session_domain'], "secure" => option['session_secure'], "path" => if option['session_path'] then option['session_path'] elsif ENV["SCRIPT_NAME"] then File::dirname(ENV["SCRIPT_NAME"]) else "" end) ] unless option['no_cookies'] end @dbprot = [@dbman] ObjectSpace::define_finalizer(self, Session::callback(@dbprot)) end # Retrieve the session data for key +key+. def [](key) @data ||= @dbman.restore @data[key] end # Set the session date for key +key+. def []=(key, val) @write_lock ||= true @data ||= @dbman.restore @data[key] = val end # Store session data on the server. For some session storage types, # this is a no-op. def update @dbman.update end # Store session data on the server and close the session storage. # For some session storage types, this is a no-op. def close @dbman.close @dbprot.clear end # Delete the session from storage. Also closes the storage. # # Note that the session's data is _not_ automatically deleted # upon the session expiring. def delete @dbman.delete @dbprot.clear end # File-based session storage class. # # Implements session storage as a flat file of 'key=value' values. # This storage type only works directly with String values; the # user is responsible for converting other types to Strings when # storing and from Strings when retrieving. class FileStore # Create a new FileStore instance. # # This constructor is used internally by CGI::Session. The # user does not generally need to call it directly. # # +session+ is the session for which this instance is being # created. The session id must only contain alphanumeric # characters; automatically generated session ids observe # this requirement. # # +option+ is a hash of options for the initializer. The # following options are recognised: # # tmpdir:: the directory to use for storing the FileStore # file. Defaults to Dir::tmpdir (generally "/tmp" # on Unix systems). # prefix:: the prefix to add to the session id when generating # the filename for this session's FileStore file. # Defaults to the empty string. # suffix:: the prefix to add to the session id when generating # the filename for this session's FileStore file. # Defaults to the empty string. # # This session's FileStore file will be created if it does # not exist, or opened if it does. def initialize(session, option={}) dir = option['tmpdir'] || Dir::tmpdir prefix = option['prefix'] || '' suffix = option['suffix'] || '' id = session.session_id require 'digest/md5' md5 = Digest::MD5.hexdigest(id)[0,16] @path = dir+"/"+prefix+md5+suffix if File::exist? @path @hash = nil else unless session.new_session raise CGI::Session::NoSession, "uninitialized session" end @hash = {} end end # Restore session state from the session's FileStore file. # # Returns the session state as a hash. def restore unless @hash @hash = {} begin lockf = File.open(@path+".lock", "r") lockf.flock File::LOCK_SH f = File.open(@path, 'r') for line in f line.chomp! k, v = line.split('=',2) @hash[CGI::unescape(k)] = CGI::unescape(v) end ensure f.close unless f.nil? lockf.close if lockf end end @hash end # Save session state to the session's FileStore file. def update return unless @hash begin lockf = File.open(@path+".lock", File::CREAT|File::RDWR, 0600) lockf.flock File::LOCK_EX f = File.open(@path+".new", File::CREAT|File::TRUNC|File::WRONLY, 0600) for k,v in @hash f.printf "%s=%s\n", CGI::escape(k), CGI::escape(String(v)) end f.close File.rename @path+".new", @path ensure f.close if f and !f.closed? lockf.close if lockf end end # Update and close the session's FileStore file. def close update end # Close and delete the session's FileStore file. def delete File::unlink @path+".lock" rescue nil File::unlink @path+".new" rescue nil File::unlink @path rescue Errno::ENOENT end end # In-memory session storage class. # # Implements session storage as a global in-memory hash. Session # data will only persist for as long as the ruby interpreter # instance does. class MemoryStore GLOBAL_HASH_TABLE = {} #:nodoc: # Create a new MemoryStore instance. # # +session+ is the session this instance is associated with. # +option+ is a list of initialisation options. None are # currently recognised. def initialize(session, option=nil) @session_id = session.session_id unless GLOBAL_HASH_TABLE.key?(@session_id) unless session.new_session raise CGI::Session::NoSession, "uninitialized session" end GLOBAL_HASH_TABLE[@session_id] = {} end end # Restore session state. # # Returns session data as a hash. def restore GLOBAL_HASH_TABLE[@session_id] end # Update session state. # # A no-op. def update # don't need to update; hash is shared end # Close session storage. # # A no-op. def close # don't need to close end # Delete the session state. def delete GLOBAL_HASH_TABLE.delete(@session_id) end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/cgi/session/pstore.rb
tools/jruby-1.5.1/lib/ruby/1.8/cgi/session/pstore.rb
# # cgi/session/pstore.rb - persistent storage of marshalled session data # # Documentation: William Webber (william@williamwebber.com) # # == Overview # # This file provides the CGI::Session::PStore class, which builds # persistent of session data on top of the pstore library. See # cgi/session.rb for more details on session storage managers. require 'cgi/session' require 'pstore' class CGI class Session # PStore-based session storage class. # # This builds upon the top-level PStore class provided by the # library file pstore.rb. Session data is marshalled and stored # in a file. File locking and transaction services are provided. class PStore # Create a new CGI::Session::PStore instance # # This constructor is used internally by CGI::Session. The # user does not generally need to call it directly. # # +session+ is the session for which this instance is being # created. The session id must only contain alphanumeric # characters; automatically generated session ids observe # this requirement. # # +option+ is a hash of options for the initializer. The # following options are recognised: # # tmpdir:: the directory to use for storing the PStore # file. Defaults to Dir::tmpdir (generally "/tmp" # on Unix systems). # prefix:: the prefix to add to the session id when generating # the filename for this session's PStore file. # Defaults to the empty string. # # This session's PStore file will be created if it does # not exist, or opened if it does. def initialize(session, option={}) dir = option['tmpdir'] || Dir::tmpdir prefix = option['prefix'] || '' id = session.session_id require 'digest/md5' md5 = Digest::MD5.hexdigest(id)[0,16] path = dir+"/"+prefix+md5 path.untaint if File::exist?(path) @hash = nil else unless session.new_session raise CGI::Session::NoSession, "uninitialized session" end @hash = {} end @p = ::PStore.new(path) @p.transaction do |p| File.chmod(0600, p.path) end end # Restore session state from the session's PStore file. # # Returns the session state as a hash. def restore unless @hash @p.transaction do @hash = @p['hash'] || {} end end @hash end # Save session state to the session's PStore file. def update @p.transaction do @p['hash'] = @hash end end # Update and close the session's PStore file. def close update end # Close and delete the session's PStore file. def delete path = @p.path File::unlink path end end end end if $0 == __FILE__ # :enddoc: STDIN.reopen("/dev/null") cgi = CGI.new session = CGI::Session.new(cgi, 'database_manager' => CGI::Session::PStore) session['key'] = {'k' => 'v'} puts session['key'].class fail unless Hash === session['key'] puts session['key'].inspect fail unless session['key'].inspect == '{"k"=>"v"}' end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/data.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/data.rb
# WSDL4R - WSDL data definitions. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/qname' require 'wsdl/documentation' require 'wsdl/definitions' require 'wsdl/types' require 'wsdl/message' require 'wsdl/part' require 'wsdl/portType' require 'wsdl/operation' require 'wsdl/param' require 'wsdl/binding' require 'wsdl/operationBinding' require 'wsdl/service' require 'wsdl/port' require 'wsdl/import' module WSDL ArrayTypeAttrName = XSD::QName.new(Namespace, 'arrayType') BindingName = XSD::QName.new(Namespace, 'binding') DefinitionsName = XSD::QName.new(Namespace, 'definitions') DocumentationName = XSD::QName.new(Namespace, 'documentation') FaultName = XSD::QName.new(Namespace, 'fault') ImportName = XSD::QName.new(Namespace, 'import') InputName = XSD::QName.new(Namespace, 'input') MessageName = XSD::QName.new(Namespace, 'message') OperationName = XSD::QName.new(Namespace, 'operation') OutputName = XSD::QName.new(Namespace, 'output') PartName = XSD::QName.new(Namespace, 'part') PortName = XSD::QName.new(Namespace, 'port') PortTypeName = XSD::QName.new(Namespace, 'portType') ServiceName = XSD::QName.new(Namespace, 'service') TypesName = XSD::QName.new(Namespace, 'types') SchemaName = XSD::QName.new(XSD::Namespace, 'schema') SOAPAddressName = XSD::QName.new(SOAPBindingNamespace, 'address') SOAPBindingName = XSD::QName.new(SOAPBindingNamespace, 'binding') SOAPHeaderName = XSD::QName.new(SOAPBindingNamespace, 'header') SOAPBodyName = XSD::QName.new(SOAPBindingNamespace, 'body') SOAPFaultName = XSD::QName.new(SOAPBindingNamespace, 'fault') SOAPOperationName = XSD::QName.new(SOAPBindingNamespace, 'operation') BindingAttrName = XSD::QName.new(nil, 'binding') ElementAttrName = XSD::QName.new(nil, 'element') LocationAttrName = XSD::QName.new(nil, 'location') MessageAttrName = XSD::QName.new(nil, 'message') NameAttrName = XSD::QName.new(nil, 'name') NamespaceAttrName = XSD::QName.new(nil, 'namespace') ParameterOrderAttrName = XSD::QName.new(nil, 'parameterOrder') TargetNamespaceAttrName = XSD::QName.new(nil, 'targetNamespace') TypeAttrName = XSD::QName.new(nil, 'type') end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/port.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/port.rb
# WSDL4R - WSDL port definition. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL class Port < Info attr_reader :name # required attr_reader :binding # required attr_reader :soap_address def initialize super @name = nil @binding = nil @soap_address = nil end def targetnamespace parent.targetnamespace end def porttype root.porttype(find_binding.type) end def find_binding root.binding(@binding) or raise RuntimeError.new("#{@binding} not found") end def inputoperation_map result = {} find_binding.operations.each do |op_bind| op_info = op_bind.soapoperation.input_info result[op_info.op_name] = op_info end result end def outputoperation_map result = {} find_binding.operations.each do |op_bind| op_info = op_bind.soapoperation.output_info result[op_info.op_name] = op_info end result end def parse_element(element) case element when SOAPAddressName o = WSDL::SOAP::Address.new @soap_address = o o when DocumentationName o = Documentation.new o else nil end end def parse_attr(attr, value) case attr when NameAttrName @name = XSD::QName.new(targetnamespace, value.source) when BindingAttrName @binding = value else nil end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/documentation.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/documentation.rb
# WSDL4R - WSDL SOAP documentation element. # Copyright (C) 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL class Documentation < Info def initialize super end def parse_element(element) # Accepts any element. self end def parse_attr(attr, value) # Accepts any attribute. true end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/param.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/param.rb
# WSDL4R - WSDL param definition. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL class Param < Info attr_reader :message # required attr_reader :name # optional but required for fault. attr_reader :soapbody attr_reader :soapheader attr_reader :soapfault def initialize super @message = nil @name = nil @soapbody = nil @soapheader = [] @soapfault = nil end def targetnamespace parent.targetnamespace end def find_message root.message(@message) or raise RuntimeError.new("#{@message} not found") end def soapbody_use if @soapbody @soapbody.use || :literal else raise RuntimeError.new("soap:body not found") end end def parse_element(element) case element when SOAPBodyName o = WSDL::SOAP::Body.new @soapbody = o o when SOAPHeaderName o = WSDL::SOAP::Header.new @soapheader << o o when SOAPFaultName o = WSDL::SOAP::Fault.new @soap_fault = o o when DocumentationName o = Documentation.new o else nil end end def parse_attr(attr, value) case attr when MessageAttrName if value.namespace.nil? value = XSD::QName.new(targetnamespace, value.source) end @message = value when NameAttrName @name = XSD::QName.new(targetnamespace, value.source) else nil end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/parser.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/parser.rb
# WSDL4R - WSDL XML Instance parser library. # Copyright (C) 2002, 2003, 2005 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/qname' require 'xsd/ns' require 'xsd/charset' require 'xsd/datatypes' require 'xsd/xmlparser' require 'wsdl/wsdl' require 'wsdl/data' require 'wsdl/xmlSchema/data' require 'wsdl/soap/data' module WSDL class Parser include WSDL class ParseError < Error; end class FormatDecodeError < ParseError; end class UnknownElementError < FormatDecodeError; end class UnknownAttributeError < FormatDecodeError; end class UnexpectedElementError < FormatDecodeError; end class ElementConstraintError < FormatDecodeError; end class AttributeConstraintError < FormatDecodeError; end private class ParseFrame attr_reader :ns attr_reader :name attr_accessor :node private def initialize(ns, name, node) @ns = ns @name = name @node = node end end public def initialize(opt = {}) @parser = XSD::XMLParser.create_parser(self, opt) @parsestack = nil @lastnode = nil @ignored = {} @location = opt[:location] @originalroot = opt[:originalroot] end def parse(string_or_readable) @parsestack = [] @lastnode = nil @textbuf = '' @parser.do_parse(string_or_readable) @lastnode end def charset @parser.charset end def start_element(name, attrs) lastframe = @parsestack.last ns = parent = nil if lastframe ns = lastframe.ns.clone_ns parent = lastframe.node else ns = XSD::NS.new parent = nil end attrs = XSD::XMLParser.filter_ns(ns, attrs) node = decode_tag(ns, name, attrs, parent) @parsestack << ParseFrame.new(ns, name, node) end def characters(text) lastframe = @parsestack.last if lastframe # Need not to be cloned because character does not have attr. ns = lastframe.ns decode_text(ns, text) else p text if $DEBUG end end def end_element(name) lastframe = @parsestack.pop unless name == lastframe.name raise UnexpectedElementError.new("closing element name '#{name}' does not match with opening element '#{lastframe.name}'") end decode_tag_end(lastframe.ns, lastframe.node) @lastnode = lastframe.node end private def decode_tag(ns, name, attrs, parent) o = nil elename = ns.parse(name) if !parent if elename == DefinitionsName o = Definitions.parse_element(elename) o.location = @location else raise UnknownElementError.new("unknown element: #{elename}") end o.root = @originalroot if @originalroot # o.root = o otherwise else if elename == XMLSchema::AnnotationName # only the first annotation element is allowed for each xsd element. o = XMLSchema::Annotation.new else o = parent.parse_element(elename) end unless o unless @ignored.key?(elename) warn("ignored element: #{elename}") @ignored[elename] = elename end o = Documentation.new # which accepts any element. end # node could be a pseudo element. pseudo element has its own parent. o.root = parent.root o.parent = parent if o.parent.nil? end attrs.each do |key, value| attr_ele = ns.parse(key, true) value_ele = ns.parse(value, true) value_ele.source = value # for recovery; value may not be a QName unless o.parse_attr(attr_ele, value_ele) unless @ignored.key?(attr_ele) warn("ignored attr: #{attr_ele}") @ignored[attr_ele] = attr_ele end end end o end def decode_tag_end(ns, node) node.parse_epilogue end def decode_text(ns, text) @textbuf << text end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/wsdl.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/wsdl.rb
# WSDL4R - Base definitions. # Copyright (C) 2000, 2001, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'xsd/qname' module WSDL Version = '0.0.2' Namespace = 'http://schemas.xmlsoap.org/wsdl/' SOAPBindingNamespace ='http://schemas.xmlsoap.org/wsdl/soap/' class Error < StandardError; end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/binding.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/binding.rb
# WSDL4R - WSDL binding definition. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'xsd/namedelements' module WSDL class Binding < Info attr_reader :name # required attr_reader :type # required attr_reader :operations attr_reader :soapbinding def initialize super @name = nil @type = nil @operations = XSD::NamedElements.new @soapbinding = nil end def targetnamespace parent.targetnamespace end def parse_element(element) case element when OperationName o = OperationBinding.new @operations << o o when SOAPBindingName o = WSDL::SOAP::Binding.new @soapbinding = o o when DocumentationName o = Documentation.new o else nil end end def parse_attr(attr, value) case attr when NameAttrName @name = XSD::QName.new(targetnamespace, value.source) when TypeAttrName @type = value else nil end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/definitions.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/definitions.rb
# WSDL4R - WSDL definitions. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' require 'xsd/namedelements' module WSDL class Definitions < Info attr_reader :name attr_reader :targetnamespace attr_reader :imports attr_accessor :location attr_reader :importedschema def initialize super @name = nil @targetnamespace = nil @location = nil @importedschema = {} @types = nil @imports = [] @messages = XSD::NamedElements.new @porttypes = XSD::NamedElements.new @bindings = XSD::NamedElements.new @services = XSD::NamedElements.new @anontypes = XSD::NamedElements.new @root = self end def inspect sprintf("#<%s:0x%x %s>", self.class.name, __id__, @name || '(unnamed)') end def targetnamespace=(targetnamespace) @targetnamespace = targetnamespace if @name @name = XSD::QName.new(@targetnamespace, @name.name) end end def collect_attributes result = XSD::NamedElements.new if @types @types.schemas.each do |schema| result.concat(schema.collect_attributes) end end @imports.each do |import| result.concat(import.content.collect_attributes) end result end def collect_elements result = XSD::NamedElements.new if @types @types.schemas.each do |schema| result.concat(schema.collect_elements) end end @imports.each do |import| result.concat(import.content.collect_elements) end result end def collect_complextypes result = @anontypes.dup if @types @types.schemas.each do |schema| result.concat(schema.collect_complextypes) end end @imports.each do |import| result.concat(import.content.collect_complextypes) end result end def collect_simpletypes result = XSD::NamedElements.new if @types @types.schemas.each do |schema| result.concat(schema.collect_simpletypes) end end @imports.each do |import| result.concat(import.content.collect_simpletypes) end result end # ToDo: simpletype must be accepted... def add_type(complextype) @anontypes << complextype end def messages result = @messages.dup @imports.each do |import| result.concat(import.content.messages) if self.class === import.content end result end def porttypes result = @porttypes.dup @imports.each do |import| result.concat(import.content.porttypes) if self.class === import.content end result end def bindings result = @bindings.dup @imports.each do |import| result.concat(import.content.bindings) if self.class === import.content end result end def services result = @services.dup @imports.each do |import| result.concat(import.content.services) if self.class === import.content end result end def message(name) message = @messages[name] return message if message @imports.each do |import| message = import.content.message(name) if self.class === import.content return message if message end nil end def porttype(name) porttype = @porttypes[name] return porttype if porttype @imports.each do |import| porttype = import.content.porttype(name) if self.class === import.content return porttype if porttype end nil end def binding(name) binding = @bindings[name] return binding if binding @imports.each do |import| binding = import.content.binding(name) if self.class === import.content return binding if binding end nil end def service(name) service = @services[name] return service if service @imports.each do |import| service = import.content.service(name) if self.class === import.content return service if service end nil end def porttype_binding(name) binding = @bindings.find { |item| item.type == name } return binding if binding @imports.each do |import| binding = import.content.porttype_binding(name) if self.class === import.content return binding if binding end nil end def parse_element(element) case element when ImportName o = Import.new @imports << o o when TypesName o = Types.new @types = o o when MessageName o = Message.new @messages << o o when PortTypeName o = PortType.new @porttypes << o o when BindingName o = Binding.new @bindings << o o when ServiceName o = Service.new @services << o o when DocumentationName o = Documentation.new o else nil end end def parse_attr(attr, value) case attr when NameAttrName @name = XSD::QName.new(targetnamespace, value.source) when TargetNamespaceAttrName self.targetnamespace = value.source else nil end end def self.parse_element(element) if element == DefinitionsName Definitions.new else nil end end private end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/info.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/info.rb
# WSDL4R - WSDL information base. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. module WSDL class Info attr_accessor :root attr_accessor :parent attr_accessor :id def initialize @root = nil @parent = nil @id = nil end def inspect if self.respond_to?(:name) sprintf("#<%s:0x%x %s>", self.class.name, __id__, self.name) else sprintf("#<%s:0x%x>", self.class.name, __id__) end end def parse_element(element); end # abstract def parse_attr(attr, value); end # abstract def parse_epilogue; end # abstract end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/message.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/message.rb
# WSDL4R - WSDL message definition. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL class Message < Info attr_reader :name # required attr_reader :parts def initialize super @name = nil @parts = [] end def targetnamespace parent.targetnamespace end def parse_element(element) case element when PartName o = Part.new @parts << o o when DocumentationName o = Documentation.new o else nil end end def parse_attr(attr, value) case attr when NameAttrName @name = XSD::QName.new(parent.targetnamespace, value.source) else nil end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/wsdl/operationBinding.rb
tools/jruby-1.5.1/lib/ruby/1.8/wsdl/operationBinding.rb
# WSDL4R - WSDL bound operation definition. # Copyright (C) 2002, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>. # This program is copyrighted free software by NAKAMURA, Hiroshi. You can # redistribute it and/or modify it under the same terms of Ruby's license; # either the dual license version in 2003, or any later version. require 'wsdl/info' module WSDL class OperationBinding < Info attr_reader :name # required attr_reader :input attr_reader :output attr_reader :fault attr_reader :soapoperation def initialize super @name = nil @input = nil @output = nil @fault = [] @soapoperation = nil end def targetnamespace parent.targetnamespace end def porttype root.porttype(parent.type) end def find_operation porttype.operations[@name] or raise RuntimeError.new("#{@name} not found") end def soapoperation_name if @soapoperation @soapoperation.input_info.op_name else find_operation.name end end def soapoperation_style style = nil if @soapoperation style = @soapoperation.operation_style elsif parent.soapbinding style = parent.soapbinding.style else raise TypeError.new("operation style definition not found") end style || :document end def soapaction if @soapoperation @soapoperation.soapaction else nil end end def parse_element(element) case element when InputName o = Param.new @input = o o when OutputName o = Param.new @output = o o when FaultName o = Param.new @fault << o o when SOAPOperationName o = WSDL::SOAP::Operation.new @soapoperation = o o when DocumentationName o = Documentation.new o else nil end end def parse_attr(attr, value) case attr when NameAttrName @name = XSD::QName.new(targetnamespace, value.source) else nil end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false