repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
rhomobile/rhodes
lib/extensions/openssl/openssl/config.rb
OpenSSL.Config.to_s
def to_s ary = [] @data.keys.sort.each do |section| ary << "[ #{section} ]\n" @data[section].keys.each do |key| ary << "#{key}=#{@data[section][key]}\n" end ary << "\n" end ary.join end
ruby
def to_s ary = [] @data.keys.sort.each do |section| ary << "[ #{section} ]\n" @data[section].keys.each do |key| ary << "#{key}=#{@data[section][key]}\n" end ary << "\n" end ary.join end
[ "def", "to_s", "ary", "=", "[", "]", "@data", ".", "keys", ".", "sort", ".", "each", "do", "|", "section", "|", "ary", "<<", "\"[ #{section} ]\\n\"", "@data", "[", "section", "]", ".", "keys", ".", "each", "do", "|", "key", "|", "ary", "<<", "\"#{key}=#{@data[section][key]}\\n\"", "end", "ary", "<<", "\"\\n\"", "end", "ary", ".", "join", "end" ]
Get the parsable form of the current configuration Given the following configuration being created: config = OpenSSL::Config.new #=> #<OpenSSL::Config sections=[]> config['default'] = {"foo"=>"bar","baz"=>"buz"} #=> {"foo"=>"bar", "baz"=>"buz"} puts config.to_s #=> [ default ] # foo=bar # baz=buz You can parse get the serialized configuration using #to_s and then parse it later: serialized_config = config.to_s # much later... new_config = OpenSSL::Config.parse(serialized_config) #=> #<OpenSSL::Config sections=["default"]> puts new_config #=> [ default ] foo=bar baz=buz
[ "Get", "the", "parsable", "form", "of", "the", "current", "configuration" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/extensions/openssl/openssl/config.rb#L417-L427
train
rhomobile/rhodes
lib/extensions/openssl/openssl/config.rb
OpenSSL.Config.each
def each @data.each do |section, hash| hash.each do |key, value| yield [section, key, value] end end end
ruby
def each @data.each do |section, hash| hash.each do |key, value| yield [section, key, value] end end end
[ "def", "each", "@data", ".", "each", "do", "|", "section", ",", "hash", "|", "hash", ".", "each", "do", "|", "key", ",", "value", "|", "yield", "[", "section", ",", "key", ",", "value", "]", "end", "end", "end" ]
For a block. Receive the section and its pairs for the current configuration. config.each do |section, key, value| # ... end
[ "For", "a", "block", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/extensions/openssl/openssl/config.rb#L438-L444
train
rhomobile/rhodes
lib/extensions/rexml/rexml/parent.rb
REXML.Parent.insert_before
def insert_before( child1, child2 ) if child1.kind_of? String child1 = XPath.first( self, child1 ) child1.parent.insert_before child1, child2 else ind = index(child1) child2.parent.delete(child2) if child2.parent @children[ind,0] = child2 child2.parent = self end self end
ruby
def insert_before( child1, child2 ) if child1.kind_of? String child1 = XPath.first( self, child1 ) child1.parent.insert_before child1, child2 else ind = index(child1) child2.parent.delete(child2) if child2.parent @children[ind,0] = child2 child2.parent = self end self end
[ "def", "insert_before", "(", "child1", ",", "child2", ")", "if", "child1", ".", "kind_of?", "String", "child1", "=", "XPath", ".", "first", "(", "self", ",", "child1", ")", "child1", ".", "parent", ".", "insert_before", "child1", ",", "child2", "else", "ind", "=", "index", "(", "child1", ")", "child2", ".", "parent", ".", "delete", "(", "child2", ")", "if", "child2", ".", "parent", "@children", "[", "ind", ",", "0", "]", "=", "child2", "child2", ".", "parent", "=", "self", "end", "self", "end" ]
Inserts an child before another child @param child1 this is either an xpath or an Element. If an Element, child2 will be inserted before child1 in the child list of the parent. If an xpath, child2 will be inserted before the first child to match the xpath. @param child2 the child to insert @return the parent (self)
[ "Inserts", "an", "child", "before", "another", "child" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/extensions/rexml/rexml/parent.rb#L83-L94
train
rhomobile/rhodes
lib/extensions/rexml/rexml/parent.rb
REXML.Parent.index
def index( child ) count = -1 @children.find { |i| count += 1 ; i.hash == child.hash } count end
ruby
def index( child ) count = -1 @children.find { |i| count += 1 ; i.hash == child.hash } count end
[ "def", "index", "(", "child", ")", "count", "=", "-", "1", "@children", ".", "find", "{", "|", "i", "|", "count", "+=", "1", ";", "i", ".", "hash", "==", "child", ".", "hash", "}", "count", "end" ]
Fetches the index of a given child @param child the child to get the index of @return the index of the child, or nil if the object is not a child of this parent.
[ "Fetches", "the", "index", "of", "a", "given", "child" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/extensions/rexml/rexml/parent.rb#L124-L128
train
rhomobile/rhodes
lib/extensions/rexml/rexml/parent.rb
REXML.Parent.replace_child
def replace_child( to_replace, replacement ) @children.map! {|c| c.equal?( to_replace ) ? replacement : c } to_replace.parent = nil replacement.parent = self end
ruby
def replace_child( to_replace, replacement ) @children.map! {|c| c.equal?( to_replace ) ? replacement : c } to_replace.parent = nil replacement.parent = self end
[ "def", "replace_child", "(", "to_replace", ",", "replacement", ")", "@children", ".", "map!", "{", "|", "c", "|", "c", ".", "equal?", "(", "to_replace", ")", "?", "replacement", ":", "c", "}", "to_replace", ".", "parent", "=", "nil", "replacement", ".", "parent", "=", "self", "end" ]
Replaces one child with another, making sure the nodelist is correct @param to_replace the child to replace (must be a Child) @param replacement the child to insert into the nodelist (must be a Child)
[ "Replaces", "one", "child", "with", "another", "making", "sure", "the", "nodelist", "is", "correct" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/extensions/rexml/rexml/parent.rb#L141-L145
train
rhomobile/rhodes
lib/extensions/rexml/rexml/parent.rb
REXML.Parent.deep_clone
def deep_clone cl = clone() each do |child| if child.kind_of? Parent cl << child.deep_clone else cl << child.clone end end cl end
ruby
def deep_clone cl = clone() each do |child| if child.kind_of? Parent cl << child.deep_clone else cl << child.clone end end cl end
[ "def", "deep_clone", "cl", "=", "clone", "(", ")", "each", "do", "|", "child", "|", "if", "child", ".", "kind_of?", "Parent", "cl", "<<", "child", ".", "deep_clone", "else", "cl", "<<", "child", ".", "clone", "end", "end", "cl", "end" ]
Deeply clones this object. This creates a complete duplicate of this Parent, including all descendants.
[ "Deeply", "clones", "this", "object", ".", "This", "creates", "a", "complete", "duplicate", "of", "this", "Parent", "including", "all", "descendants", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/extensions/rexml/rexml/parent.rb#L149-L159
train
rhomobile/rhodes
lib/extensions/rexml/rexml/instruction.rb
REXML.Instruction.write
def write writer, indent=-1, transitive=false, ie_hack=false Kernel.warn( "#{self.class.name}.write is deprecated" ) indent(writer, indent) writer << START.sub(/\\/u, '') writer << @target writer << ' ' writer << @content writer << STOP.sub(/\\/u, '') end
ruby
def write writer, indent=-1, transitive=false, ie_hack=false Kernel.warn( "#{self.class.name}.write is deprecated" ) indent(writer, indent) writer << START.sub(/\\/u, '') writer << @target writer << ' ' writer << @content writer << STOP.sub(/\\/u, '') end
[ "def", "write", "writer", ",", "indent", "=", "-", "1", ",", "transitive", "=", "false", ",", "ie_hack", "=", "false", "Kernel", ".", "warn", "(", "\"#{self.class.name}.write is deprecated\"", ")", "indent", "(", "writer", ",", "indent", ")", "writer", "<<", "START", ".", "sub", "(", "/", "\\\\", "/u", ",", "''", ")", "writer", "<<", "@target", "writer", "<<", "' '", "writer", "<<", "@content", "writer", "<<", "STOP", ".", "sub", "(", "/", "\\\\", "/u", ",", "''", ")", "end" ]
Constructs a new Instruction @param target can be one of a number of things. If String, then the target of this instruction is set to this. If an Instruction, then the Instruction is shallowly cloned (target and content are copied). If a Source, then the source is scanned and parsed for an Instruction declaration. @param content Must be either a String, or a Parent. Can only be a Parent if the target argument is a Source. Otherwise, this String is set as the content of this instruction. == DEPRECATED See the rexml/formatters package
[ "Constructs", "a", "new", "Instruction" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/extensions/rexml/rexml/instruction.rb#L44-L52
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/templater-1.0.0/lib/templater/description.rb
Templater.ArgumentDescription.valid?
def valid?(argument) if argument.nil? and options[:required] raise Templater::TooFewArgumentsError elsif not argument.nil? if options[:as] == :hash and not argument.is_a?(Hash) raise Templater::MalformattedArgumentError, "Expected the argument to be a Hash, but was '#{argument.inspect}'" elsif options[:as] == :array and not argument.is_a?(Array) raise Templater::MalformattedArgumentError, "Expected the argument to be an Array, but was '#{argument.inspect}'" end invalid = catch :invalid do block.call(argument) if block throw :invalid, :not_invalid end raise Templater::ArgumentError, invalid unless invalid == :not_invalid end end
ruby
def valid?(argument) if argument.nil? and options[:required] raise Templater::TooFewArgumentsError elsif not argument.nil? if options[:as] == :hash and not argument.is_a?(Hash) raise Templater::MalformattedArgumentError, "Expected the argument to be a Hash, but was '#{argument.inspect}'" elsif options[:as] == :array and not argument.is_a?(Array) raise Templater::MalformattedArgumentError, "Expected the argument to be an Array, but was '#{argument.inspect}'" end invalid = catch :invalid do block.call(argument) if block throw :invalid, :not_invalid end raise Templater::ArgumentError, invalid unless invalid == :not_invalid end end
[ "def", "valid?", "(", "argument", ")", "if", "argument", ".", "nil?", "and", "options", "[", ":required", "]", "raise", "Templater", "::", "TooFewArgumentsError", "elsif", "not", "argument", ".", "nil?", "if", "options", "[", ":as", "]", "==", ":hash", "and", "not", "argument", ".", "is_a?", "(", "Hash", ")", "raise", "Templater", "::", "MalformattedArgumentError", ",", "\"Expected the argument to be a Hash, but was '#{argument.inspect}'\"", "elsif", "options", "[", ":as", "]", "==", ":array", "and", "not", "argument", ".", "is_a?", "(", "Array", ")", "raise", "Templater", "::", "MalformattedArgumentError", ",", "\"Expected the argument to be an Array, but was '#{argument.inspect}'\"", "end", "invalid", "=", "catch", ":invalid", "do", "block", ".", "call", "(", "argument", ")", "if", "block", "throw", ":invalid", ",", ":not_invalid", "end", "raise", "Templater", "::", "ArgumentError", ",", "invalid", "unless", "invalid", "==", ":not_invalid", "end", "end" ]
Checks if the given argument is valid according to this description === Parameters argument<Object>:: Checks if the given argument is valid. === Returns Boolean:: Validity of the argument
[ "Checks", "if", "the", "given", "argument", "is", "valid", "according", "to", "this", "description" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/templater-1.0.0/lib/templater/description.rb#L29-L45
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/ftp.rb
Net.FTP.open_socket
def open_socket(host, port) # :nodoc: return Timeout.timeout(@open_timeout, Net::OpenTimeout) { if defined? SOCKSSocket and ENV["SOCKS_SERVER"] @passive = true sock = SOCKSSocket.open(host, port) else sock = TCPSocket.open(host, port) end io = BufferedSocket.new(sock) io.read_timeout = @read_timeout io } end
ruby
def open_socket(host, port) # :nodoc: return Timeout.timeout(@open_timeout, Net::OpenTimeout) { if defined? SOCKSSocket and ENV["SOCKS_SERVER"] @passive = true sock = SOCKSSocket.open(host, port) else sock = TCPSocket.open(host, port) end io = BufferedSocket.new(sock) io.read_timeout = @read_timeout io } end
[ "def", "open_socket", "(", "host", ",", "port", ")", "# :nodoc:", "return", "Timeout", ".", "timeout", "(", "@open_timeout", ",", "Net", "::", "OpenTimeout", ")", "{", "if", "defined?", "SOCKSSocket", "and", "ENV", "[", "\"SOCKS_SERVER\"", "]", "@passive", "=", "true", "sock", "=", "SOCKSSocket", ".", "open", "(", "host", ",", "port", ")", "else", "sock", "=", "TCPSocket", ".", "open", "(", "host", ",", "port", ")", "end", "io", "=", "BufferedSocket", ".", "new", "(", "sock", ")", "io", ".", "read_timeout", "=", "@read_timeout", "io", "}", "end" ]
Constructs a socket with +host+ and +port+. If SOCKSSocket is defined and the environment (ENV) defines SOCKS_SERVER, then a SOCKSSocket is returned, else a TCPSocket is returned.
[ "Constructs", "a", "socket", "with", "+", "host", "+", "and", "+", "port", "+", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/ftp.rb#L222-L234
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/ftp.rb
Net.FTP.transfercmd
def transfercmd(cmd, rest_offset = nil) # :nodoc: if @passive host, port = makepasv conn = open_socket(host, port) if @resume and rest_offset resp = sendcmd("REST " + rest_offset.to_s) if resp[0] != ?3 raise FTPReplyError, resp end end resp = sendcmd(cmd) # skip 2XX for some ftp servers resp = getresp if resp[0] == ?2 if resp[0] != ?1 raise FTPReplyError, resp end else sock = makeport if @resume and rest_offset resp = sendcmd("REST " + rest_offset.to_s) if resp[0] != ?3 raise FTPReplyError, resp end end resp = sendcmd(cmd) # skip 2XX for some ftp servers resp = getresp if resp[0] == ?2 if resp[0] != ?1 raise FTPReplyError, resp end conn = BufferedSocket.new(sock.accept) conn.read_timeout = @read_timeout sock.shutdown(Socket::SHUT_WR) rescue nil sock.read rescue nil sock.close end return conn end
ruby
def transfercmd(cmd, rest_offset = nil) # :nodoc: if @passive host, port = makepasv conn = open_socket(host, port) if @resume and rest_offset resp = sendcmd("REST " + rest_offset.to_s) if resp[0] != ?3 raise FTPReplyError, resp end end resp = sendcmd(cmd) # skip 2XX for some ftp servers resp = getresp if resp[0] == ?2 if resp[0] != ?1 raise FTPReplyError, resp end else sock = makeport if @resume and rest_offset resp = sendcmd("REST " + rest_offset.to_s) if resp[0] != ?3 raise FTPReplyError, resp end end resp = sendcmd(cmd) # skip 2XX for some ftp servers resp = getresp if resp[0] == ?2 if resp[0] != ?1 raise FTPReplyError, resp end conn = BufferedSocket.new(sock.accept) conn.read_timeout = @read_timeout sock.shutdown(Socket::SHUT_WR) rescue nil sock.read rescue nil sock.close end return conn end
[ "def", "transfercmd", "(", "cmd", ",", "rest_offset", "=", "nil", ")", "# :nodoc:", "if", "@passive", "host", ",", "port", "=", "makepasv", "conn", "=", "open_socket", "(", "host", ",", "port", ")", "if", "@resume", "and", "rest_offset", "resp", "=", "sendcmd", "(", "\"REST \"", "+", "rest_offset", ".", "to_s", ")", "if", "resp", "[", "0", "]", "!=", "?3", "raise", "FTPReplyError", ",", "resp", "end", "end", "resp", "=", "sendcmd", "(", "cmd", ")", "# skip 2XX for some ftp servers", "resp", "=", "getresp", "if", "resp", "[", "0", "]", "==", "?2", "if", "resp", "[", "0", "]", "!=", "?1", "raise", "FTPReplyError", ",", "resp", "end", "else", "sock", "=", "makeport", "if", "@resume", "and", "rest_offset", "resp", "=", "sendcmd", "(", "\"REST \"", "+", "rest_offset", ".", "to_s", ")", "if", "resp", "[", "0", "]", "!=", "?3", "raise", "FTPReplyError", ",", "resp", "end", "end", "resp", "=", "sendcmd", "(", "cmd", ")", "# skip 2XX for some ftp servers", "resp", "=", "getresp", "if", "resp", "[", "0", "]", "==", "?2", "if", "resp", "[", "0", "]", "!=", "?1", "raise", "FTPReplyError", ",", "resp", "end", "conn", "=", "BufferedSocket", ".", "new", "(", "sock", ".", "accept", ")", "conn", ".", "read_timeout", "=", "@read_timeout", "sock", ".", "shutdown", "(", "Socket", "::", "SHUT_WR", ")", "rescue", "nil", "sock", ".", "read", "rescue", "nil", "sock", ".", "close", "end", "return", "conn", "end" ]
Constructs a connection for transferring data
[ "Constructs", "a", "connection", "for", "transferring", "data" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/ftp.rb#L405-L442
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/ftp.rb
Net.FTP.getbinaryfile
def getbinaryfile(remotefile, localfile = File.basename(remotefile), blocksize = DEFAULT_BLOCKSIZE) # :yield: data result = nil if localfile if @resume rest_offset = File.size?(localfile) f = open(localfile, "a") else rest_offset = nil f = open(localfile, "w") end elsif !block_given? result = "" end begin f.binmode if localfile retrbinary("RETR " + remotefile.to_s, blocksize, rest_offset) do |data| f.write(data) if localfile yield(data) if block_given? result.concat(data) if result end return result ensure f.close if localfile end end
ruby
def getbinaryfile(remotefile, localfile = File.basename(remotefile), blocksize = DEFAULT_BLOCKSIZE) # :yield: data result = nil if localfile if @resume rest_offset = File.size?(localfile) f = open(localfile, "a") else rest_offset = nil f = open(localfile, "w") end elsif !block_given? result = "" end begin f.binmode if localfile retrbinary("RETR " + remotefile.to_s, blocksize, rest_offset) do |data| f.write(data) if localfile yield(data) if block_given? result.concat(data) if result end return result ensure f.close if localfile end end
[ "def", "getbinaryfile", "(", "remotefile", ",", "localfile", "=", "File", ".", "basename", "(", "remotefile", ")", ",", "blocksize", "=", "DEFAULT_BLOCKSIZE", ")", "# :yield: data", "result", "=", "nil", "if", "localfile", "if", "@resume", "rest_offset", "=", "File", ".", "size?", "(", "localfile", ")", "f", "=", "open", "(", "localfile", ",", "\"a\"", ")", "else", "rest_offset", "=", "nil", "f", "=", "open", "(", "localfile", ",", "\"w\"", ")", "end", "elsif", "!", "block_given?", "result", "=", "\"\"", "end", "begin", "f", ".", "binmode", "if", "localfile", "retrbinary", "(", "\"RETR \"", "+", "remotefile", ".", "to_s", ",", "blocksize", ",", "rest_offset", ")", "do", "|", "data", "|", "f", ".", "write", "(", "data", ")", "if", "localfile", "yield", "(", "data", ")", "if", "block_given?", "result", ".", "concat", "(", "data", ")", "if", "result", "end", "return", "result", "ensure", "f", ".", "close", "if", "localfile", "end", "end" ]
Retrieves +remotefile+ in binary mode, storing the result in +localfile+. If +localfile+ is nil, returns retrieved data. If a block is supplied, it is passed the retrieved data in +blocksize+ chunks.
[ "Retrieves", "+", "remotefile", "+", "in", "binary", "mode", "storing", "the", "result", "in", "+", "localfile", "+", ".", "If", "+", "localfile", "+", "is", "nil", "returns", "retrieved", "data", ".", "If", "a", "block", "is", "supplied", "it", "is", "passed", "the", "retrieved", "data", "in", "+", "blocksize", "+", "chunks", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/ftp.rb#L602-L627
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/ftp.rb
Net.FTP.nlst
def nlst(dir = nil) cmd = "NLST" if dir cmd = cmd + " " + dir end files = [] retrlines(cmd) do |line| files.push(line) end return files end
ruby
def nlst(dir = nil) cmd = "NLST" if dir cmd = cmd + " " + dir end files = [] retrlines(cmd) do |line| files.push(line) end return files end
[ "def", "nlst", "(", "dir", "=", "nil", ")", "cmd", "=", "\"NLST\"", "if", "dir", "cmd", "=", "cmd", "+", "\" \"", "+", "dir", "end", "files", "=", "[", "]", "retrlines", "(", "cmd", ")", "do", "|", "line", "|", "files", ".", "push", "(", "line", ")", "end", "return", "files", "end" ]
Returns an array of filenames in the remote directory.
[ "Returns", "an", "array", "of", "filenames", "in", "the", "remote", "directory", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/ftp.rb#L739-L749
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/ftp.rb
Net.FTP.rename
def rename(fromname, toname) resp = sendcmd("RNFR " + fromname) if resp[0] != ?3 raise FTPReplyError, resp end voidcmd("RNTO " + toname) end
ruby
def rename(fromname, toname) resp = sendcmd("RNFR " + fromname) if resp[0] != ?3 raise FTPReplyError, resp end voidcmd("RNTO " + toname) end
[ "def", "rename", "(", "fromname", ",", "toname", ")", "resp", "=", "sendcmd", "(", "\"RNFR \"", "+", "fromname", ")", "if", "resp", "[", "0", "]", "!=", "?3", "raise", "FTPReplyError", ",", "resp", "end", "voidcmd", "(", "\"RNTO \"", "+", "toname", ")", "end" ]
Renames a file on the server.
[ "Renames", "a", "file", "on", "the", "server", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/ftp.rb#L776-L782
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/ftp.rb
Net.FTP.delete
def delete(filename) resp = sendcmd("DELE " + filename) if resp[0, 3] == "250" return elsif resp[0] == ?5 raise FTPPermError, resp else raise FTPReplyError, resp end end
ruby
def delete(filename) resp = sendcmd("DELE " + filename) if resp[0, 3] == "250" return elsif resp[0] == ?5 raise FTPPermError, resp else raise FTPReplyError, resp end end
[ "def", "delete", "(", "filename", ")", "resp", "=", "sendcmd", "(", "\"DELE \"", "+", "filename", ")", "if", "resp", "[", "0", ",", "3", "]", "==", "\"250\"", "return", "elsif", "resp", "[", "0", "]", "==", "?5", "raise", "FTPPermError", ",", "resp", "else", "raise", "FTPReplyError", ",", "resp", "end", "end" ]
Deletes a file on the server.
[ "Deletes", "a", "file", "on", "the", "server", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/ftp.rb#L787-L796
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/cgi.rb
WEBrick.CGI.start
def start(env=ENV, stdin=$stdin, stdout=$stdout) sock = WEBrick::CGI::Socket.new(@config, env, stdin, stdout) req = HTTPRequest.new(@config) res = HTTPResponse.new(@config) unless @config[:NPH] or defined?(MOD_RUBY) def res.setup_header unless @header["status"] phrase = HTTPStatus::reason_phrase(@status) @header["status"] = "#{@status} #{phrase}" end super end def res.status_line "" end end begin req.parse(sock) req.script_name = (env["SCRIPT_NAME"] || File.expand_path($0)).dup req.path_info = (env["PATH_INFO"] || "").dup req.query_string = env["QUERY_STRING"] req.user = env["REMOTE_USER"] res.request_method = req.request_method res.request_uri = req.request_uri res.request_http_version = req.http_version res.keep_alive = req.keep_alive? self.service(req, res) rescue HTTPStatus::Error => ex res.set_error(ex) rescue HTTPStatus::Status => ex res.status = ex.code rescue Exception => ex @logger.error(ex) res.set_error(ex, true) ensure req.fixup if defined?(MOD_RUBY) res.setup_header Apache.request.status_line = "#{res.status} #{res.reason_phrase}" Apache.request.status = res.status table = Apache.request.headers_out res.header.each{|key, val| case key when /^content-encoding$/i Apache::request.content_encoding = val when /^content-type$/i Apache::request.content_type = val else table[key] = val.to_s end } res.cookies.each{|cookie| table.add("Set-Cookie", cookie.to_s) } Apache.request.send_http_header res.send_body(sock) else res.send_response(sock) end end end
ruby
def start(env=ENV, stdin=$stdin, stdout=$stdout) sock = WEBrick::CGI::Socket.new(@config, env, stdin, stdout) req = HTTPRequest.new(@config) res = HTTPResponse.new(@config) unless @config[:NPH] or defined?(MOD_RUBY) def res.setup_header unless @header["status"] phrase = HTTPStatus::reason_phrase(@status) @header["status"] = "#{@status} #{phrase}" end super end def res.status_line "" end end begin req.parse(sock) req.script_name = (env["SCRIPT_NAME"] || File.expand_path($0)).dup req.path_info = (env["PATH_INFO"] || "").dup req.query_string = env["QUERY_STRING"] req.user = env["REMOTE_USER"] res.request_method = req.request_method res.request_uri = req.request_uri res.request_http_version = req.http_version res.keep_alive = req.keep_alive? self.service(req, res) rescue HTTPStatus::Error => ex res.set_error(ex) rescue HTTPStatus::Status => ex res.status = ex.code rescue Exception => ex @logger.error(ex) res.set_error(ex, true) ensure req.fixup if defined?(MOD_RUBY) res.setup_header Apache.request.status_line = "#{res.status} #{res.reason_phrase}" Apache.request.status = res.status table = Apache.request.headers_out res.header.each{|key, val| case key when /^content-encoding$/i Apache::request.content_encoding = val when /^content-type$/i Apache::request.content_type = val else table[key] = val.to_s end } res.cookies.each{|cookie| table.add("Set-Cookie", cookie.to_s) } Apache.request.send_http_header res.send_body(sock) else res.send_response(sock) end end end
[ "def", "start", "(", "env", "=", "ENV", ",", "stdin", "=", "$stdin", ",", "stdout", "=", "$stdout", ")", "sock", "=", "WEBrick", "::", "CGI", "::", "Socket", ".", "new", "(", "@config", ",", "env", ",", "stdin", ",", "stdout", ")", "req", "=", "HTTPRequest", ".", "new", "(", "@config", ")", "res", "=", "HTTPResponse", ".", "new", "(", "@config", ")", "unless", "@config", "[", ":NPH", "]", "or", "defined?", "(", "MOD_RUBY", ")", "def", "res", ".", "setup_header", "unless", "@header", "[", "\"status\"", "]", "phrase", "=", "HTTPStatus", "::", "reason_phrase", "(", "@status", ")", "@header", "[", "\"status\"", "]", "=", "\"#{@status} #{phrase}\"", "end", "super", "end", "def", "res", ".", "status_line", "\"\"", "end", "end", "begin", "req", ".", "parse", "(", "sock", ")", "req", ".", "script_name", "=", "(", "env", "[", "\"SCRIPT_NAME\"", "]", "||", "File", ".", "expand_path", "(", "$0", ")", ")", ".", "dup", "req", ".", "path_info", "=", "(", "env", "[", "\"PATH_INFO\"", "]", "||", "\"\"", ")", ".", "dup", "req", ".", "query_string", "=", "env", "[", "\"QUERY_STRING\"", "]", "req", ".", "user", "=", "env", "[", "\"REMOTE_USER\"", "]", "res", ".", "request_method", "=", "req", ".", "request_method", "res", ".", "request_uri", "=", "req", ".", "request_uri", "res", ".", "request_http_version", "=", "req", ".", "http_version", "res", ".", "keep_alive", "=", "req", ".", "keep_alive?", "self", ".", "service", "(", "req", ",", "res", ")", "rescue", "HTTPStatus", "::", "Error", "=>", "ex", "res", ".", "set_error", "(", "ex", ")", "rescue", "HTTPStatus", "::", "Status", "=>", "ex", "res", ".", "status", "=", "ex", ".", "code", "rescue", "Exception", "=>", "ex", "@logger", ".", "error", "(", "ex", ")", "res", ".", "set_error", "(", "ex", ",", "true", ")", "ensure", "req", ".", "fixup", "if", "defined?", "(", "MOD_RUBY", ")", "res", ".", "setup_header", "Apache", ".", "request", ".", "status_line", "=", "\"#{res.status} #{res.reason_phrase}\"", "Apache", ".", "request", ".", "status", "=", "res", ".", "status", "table", "=", "Apache", ".", "request", ".", "headers_out", "res", ".", "header", ".", "each", "{", "|", "key", ",", "val", "|", "case", "key", "when", "/", "/i", "Apache", "::", "request", ".", "content_encoding", "=", "val", "when", "/", "/i", "Apache", "::", "request", ".", "content_type", "=", "val", "else", "table", "[", "key", "]", "=", "val", ".", "to_s", "end", "}", "res", ".", "cookies", ".", "each", "{", "|", "cookie", "|", "table", ".", "add", "(", "\"Set-Cookie\"", ",", "cookie", ".", "to_s", ")", "}", "Apache", ".", "request", ".", "send_http_header", "res", ".", "send_body", "(", "sock", ")", "else", "res", ".", "send_response", "(", "sock", ")", "end", "end", "end" ]
Starts the CGI process with the given environment +env+ and standard input and output +stdin+ and +stdout+.
[ "Starts", "the", "CGI", "process", "with", "the", "given", "environment", "+", "env", "+", "and", "standard", "input", "and", "output", "+", "stdin", "+", "and", "+", "stdout", "+", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/cgi.rb#L89-L150
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/templater-1.0.0/lib/templater/manifold.rb
Templater.Manifold.remove
def remove(name) public_generators.delete(name.to_sym) private_generators.delete(name.to_sym) end
ruby
def remove(name) public_generators.delete(name.to_sym) private_generators.delete(name.to_sym) end
[ "def", "remove", "(", "name", ")", "public_generators", ".", "delete", "(", "name", ".", "to_sym", ")", "private_generators", ".", "delete", "(", "name", ".", "to_sym", ")", "end" ]
Remove the generator with the given name from the manifold === Parameters name<Symbol>:: The name of the generator to be removed.
[ "Remove", "the", "generator", "with", "the", "given", "name", "from", "the", "manifold" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/templater-1.0.0/lib/templater/manifold.rb#L56-L59
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/templater-1.0.0/lib/templater/manifold.rb
Templater.Manifold.run_cli
def run_cli(destination_root, name, version, args) Templater::CLI::Manifold.run(destination_root, self, name, version, args) end
ruby
def run_cli(destination_root, name, version, args) Templater::CLI::Manifold.run(destination_root, self, name, version, args) end
[ "def", "run_cli", "(", "destination_root", ",", "name", ",", "version", ",", "args", ")", "Templater", "::", "CLI", "::", "Manifold", ".", "run", "(", "destination_root", ",", "self", ",", "name", ",", "version", ",", "args", ")", "end" ]
A Shortcut method for invoking the command line interface provided with Templater. === Parameters destination_root<String>:: Where the generated files should be put, this would usually be Dir.pwd name<String>:: The name of the executable running this generator (such as 'merb-gen') version<String>:: The version number of the executable. args<Array[String]>:: An array of arguments to pass into the generator. This would usually be ARGV
[ "A", "Shortcut", "method", "for", "invoking", "the", "command", "line", "interface", "provided", "with", "Templater", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/templater-1.0.0/lib/templater/manifold.rb#L79-L81
train
rhomobile/rhodes
lib/framework/rhom/rhom_object.rb
Rhom.RhomObject.djb_hash
def djb_hash(str, len) hash = 5381 for i in (0..len) hash = ((hash << 5) + hash) + str[i].to_i end return hash end
ruby
def djb_hash(str, len) hash = 5381 for i in (0..len) hash = ((hash << 5) + hash) + str[i].to_i end return hash end
[ "def", "djb_hash", "(", "str", ",", "len", ")", "hash", "=", "5381", "for", "i", "in", "(", "0", "..", "len", ")", "hash", "=", "(", "(", "hash", "<<", "5", ")", "+", "hash", ")", "+", "str", "[", "i", "]", ".", "to_i", "end", "return", "hash", "end" ]
use djb hash function to generate temp object id
[ "use", "djb", "hash", "function", "to", "generate", "temp", "object", "id" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/framework/rhom/rhom_object.rb#L34-L40
train
rhomobile/rhodes
lib/extensions/rexml/rexml/namespace.rb
REXML.Namespace.has_name?
def has_name?( other, ns=nil ) if ns return (namespace() == ns and name() == other) elsif other.include? ":" return fully_expanded_name == other else return name == other end end
ruby
def has_name?( other, ns=nil ) if ns return (namespace() == ns and name() == other) elsif other.include? ":" return fully_expanded_name == other else return name == other end end
[ "def", "has_name?", "(", "other", ",", "ns", "=", "nil", ")", "if", "ns", "return", "(", "namespace", "(", ")", "==", "ns", "and", "name", "(", ")", "==", "other", ")", "elsif", "other", ".", "include?", "\":\"", "return", "fully_expanded_name", "==", "other", "else", "return", "name", "==", "other", "end", "end" ]
Compares names optionally WITH namespaces
[ "Compares", "names", "optionally", "WITH", "namespaces" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/extensions/rexml/rexml/namespace.rb#L27-L35
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httprequest.rb
WEBrick.HTTPRequest.each
def each if @header @header.each{|k, v| value = @header[k] yield(k, value.empty? ? nil : value.join(", ")) } end end
ruby
def each if @header @header.each{|k, v| value = @header[k] yield(k, value.empty? ? nil : value.join(", ")) } end end
[ "def", "each", "if", "@header", "@header", ".", "each", "{", "|", "k", ",", "v", "|", "value", "=", "@header", "[", "k", "]", "yield", "(", "k", ",", "value", ".", "empty?", "?", "nil", ":", "value", ".", "join", "(", "\", \"", ")", ")", "}", "end", "end" ]
Iterates over the request headers
[ "Iterates", "over", "the", "request", "headers" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httprequest.rb#L296-L303
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httprequest.rb
WEBrick.HTTPRequest.fixup
def fixup() # :nodoc: begin body{|chunk| } # read remaining body rescue HTTPStatus::Error => ex @logger.error("HTTPRequest#fixup: #{ex.class} occurred.") @keep_alive = false rescue => ex @logger.error(ex) @keep_alive = false end end
ruby
def fixup() # :nodoc: begin body{|chunk| } # read remaining body rescue HTTPStatus::Error => ex @logger.error("HTTPRequest#fixup: #{ex.class} occurred.") @keep_alive = false rescue => ex @logger.error(ex) @keep_alive = false end end
[ "def", "fixup", "(", ")", "# :nodoc:", "begin", "body", "{", "|", "chunk", "|", "}", "# read remaining body", "rescue", "HTTPStatus", "::", "Error", "=>", "ex", "@logger", ".", "error", "(", "\"HTTPRequest#fixup: #{ex.class} occurred.\"", ")", "@keep_alive", "=", "false", "rescue", "=>", "ex", "@logger", ".", "error", "(", "ex", ")", "@keep_alive", "=", "false", "end", "end" ]
Consumes any remaining body and updates keep-alive status
[ "Consumes", "any", "remaining", "body", "and", "updates", "keep", "-", "alive", "status" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httprequest.rb#L358-L368
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/accesslog.rb
WEBrick.AccessLog.format
def format(format_string, params) format_string.gsub(/\%(?:\{(.*?)\})?>?([a-zA-Z%])/){ param, spec = $1, $2 case spec[0] when ?e, ?i, ?n, ?o raise AccessLogError, "parameter is required for \"#{spec}\"" unless param (param = params[spec][param]) ? escape(param) : "-" when ?t params[spec].strftime(param || CLF_TIME_FORMAT) when ?p case param when 'remote' escape(params["i"].peeraddr[1].to_s) else escape(params["p"].to_s) end when ?% "%" else escape(params[spec].to_s) end } end
ruby
def format(format_string, params) format_string.gsub(/\%(?:\{(.*?)\})?>?([a-zA-Z%])/){ param, spec = $1, $2 case spec[0] when ?e, ?i, ?n, ?o raise AccessLogError, "parameter is required for \"#{spec}\"" unless param (param = params[spec][param]) ? escape(param) : "-" when ?t params[spec].strftime(param || CLF_TIME_FORMAT) when ?p case param when 'remote' escape(params["i"].peeraddr[1].to_s) else escape(params["p"].to_s) end when ?% "%" else escape(params[spec].to_s) end } end
[ "def", "format", "(", "format_string", ",", "params", ")", "format_string", ".", "gsub", "(", "/", "\\%", "\\{", "\\}", "/", ")", "{", "param", ",", "spec", "=", "$1", ",", "$2", "case", "spec", "[", "0", "]", "when", "?e", ",", "?i", ",", "?n", ",", "?o", "raise", "AccessLogError", ",", "\"parameter is required for \\\"#{spec}\\\"\"", "unless", "param", "(", "param", "=", "params", "[", "spec", "]", "[", "param", "]", ")", "?", "escape", "(", "param", ")", ":", "\"-\"", "when", "?t", "params", "[", "spec", "]", ".", "strftime", "(", "param", "||", "CLF_TIME_FORMAT", ")", "when", "?p", "case", "param", "when", "'remote'", "escape", "(", "params", "[", "\"i\"", "]", ".", "peeraddr", "[", "1", "]", ".", "to_s", ")", "else", "escape", "(", "params", "[", "\"p\"", "]", ".", "to_s", ")", "end", "when", "?%", "\"%\"", "else", "escape", "(", "params", "[", "spec", "]", ".", "to_s", ")", "end", "}", "end" ]
Formats +params+ according to +format_string+ which is described in setup_params.
[ "Formats", "+", "params", "+", "according", "to", "+", "format_string", "+", "which", "is", "described", "in", "setup_params", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/accesslog.rb#L122-L145
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/rake/application.rb
Rake.Application.run_with_threads
def run_with_threads thread_pool.gather_history if options.job_stats == :history yield thread_pool.join if options.job_stats stats = thread_pool.statistics puts "Maximum active threads: #{stats[:max_active_threads]}" puts "Total threads in play: #{stats[:total_threads_in_play]}" end ThreadHistoryDisplay.new(thread_pool.history).show if options.job_stats == :history end
ruby
def run_with_threads thread_pool.gather_history if options.job_stats == :history yield thread_pool.join if options.job_stats stats = thread_pool.statistics puts "Maximum active threads: #{stats[:max_active_threads]}" puts "Total threads in play: #{stats[:total_threads_in_play]}" end ThreadHistoryDisplay.new(thread_pool.history).show if options.job_stats == :history end
[ "def", "run_with_threads", "thread_pool", ".", "gather_history", "if", "options", ".", "job_stats", "==", ":history", "yield", "thread_pool", ".", "join", "if", "options", ".", "job_stats", "stats", "=", "thread_pool", ".", "statistics", "puts", "\"Maximum active threads: #{stats[:max_active_threads]}\"", "puts", "\"Total threads in play: #{stats[:total_threads_in_play]}\"", "end", "ThreadHistoryDisplay", ".", "new", "(", "thread_pool", ".", "history", ")", ".", "show", "if", "options", ".", "job_stats", "==", ":history", "end" ]
Run the given block with the thread startup and shutdown.
[ "Run", "the", "given", "block", "with", "the", "thread", "startup", "and", "shutdown", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/rake/application.rb#L112-L125
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/rake/application.rb
Rake.Application.standard_exception_handling
def standard_exception_handling yield rescue SystemExit # Exit silently with current status raise rescue OptionParser::InvalidOption => ex $stderr.puts ex.message exit(false) rescue Exception => ex # Exit with error message display_error_message(ex) exit_because_of_exception(ex) end
ruby
def standard_exception_handling yield rescue SystemExit # Exit silently with current status raise rescue OptionParser::InvalidOption => ex $stderr.puts ex.message exit(false) rescue Exception => ex # Exit with error message display_error_message(ex) exit_because_of_exception(ex) end
[ "def", "standard_exception_handling", "yield", "rescue", "SystemExit", "# Exit silently with current status", "raise", "rescue", "OptionParser", "::", "InvalidOption", "=>", "ex", "$stderr", ".", "puts", "ex", ".", "message", "exit", "(", "false", ")", "rescue", "Exception", "=>", "ex", "# Exit with error message", "display_error_message", "(", "ex", ")", "exit_because_of_exception", "(", "ex", ")", "end" ]
Provide standard exception handling for the given block.
[ "Provide", "standard", "exception", "handling", "for", "the", "given", "block", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/rake/application.rb#L164-L176
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/rake/application.rb
Rake.Application.display_prerequisites
def display_prerequisites tasks.each do |t| puts "#{name} #{t.name}" t.prerequisites.each { |pre| puts " #{pre}" } end end
ruby
def display_prerequisites tasks.each do |t| puts "#{name} #{t.name}" t.prerequisites.each { |pre| puts " #{pre}" } end end
[ "def", "display_prerequisites", "tasks", ".", "each", "do", "|", "t", "|", "puts", "\"#{name} #{t.name}\"", "t", ".", "prerequisites", ".", "each", "{", "|", "pre", "|", "puts", "\" #{pre}\"", "}", "end", "end" ]
Display the tasks and prerequisites
[ "Display", "the", "tasks", "and", "prerequisites" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/rake/application.rb#L331-L336
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/templater-1.0.0/lib/templater/generator.rb
Templater.Generator.invocations
def invocations return [] unless self.class.manifold self.class.invocations.map do |invocation| invocation.get(self) if match_options?(invocation.options) end.compact end
ruby
def invocations return [] unless self.class.manifold self.class.invocations.map do |invocation| invocation.get(self) if match_options?(invocation.options) end.compact end
[ "def", "invocations", "return", "[", "]", "unless", "self", ".", "class", ".", "manifold", "self", ".", "class", ".", "invocations", ".", "map", "do", "|", "invocation", "|", "invocation", ".", "get", "(", "self", ")", "if", "match_options?", "(", "invocation", ".", "options", ")", "end", ".", "compact", "end" ]
Finds and returns all templates whose options match the generator options. === Returns [Templater::Generator]:: The found templates.
[ "Finds", "and", "returns", "all", "templates", "whose", "options", "match", "the", "generator", "options", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/templater-1.0.0/lib/templater/generator.rb#L534-L540
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/templater-1.0.0/lib/templater/generator.rb
Templater.Generator.actions
def actions(type=nil) actions = type ? self.class.actions[type] : self.class.actions.values.flatten actions.inject([]) do |actions, description| actions << description.compile(self) if match_options?(description.options) actions end end
ruby
def actions(type=nil) actions = type ? self.class.actions[type] : self.class.actions.values.flatten actions.inject([]) do |actions, description| actions << description.compile(self) if match_options?(description.options) actions end end
[ "def", "actions", "(", "type", "=", "nil", ")", "actions", "=", "type", "?", "self", ".", "class", ".", "actions", "[", "type", "]", ":", "self", ".", "class", ".", "actions", ".", "values", ".", "flatten", "actions", ".", "inject", "(", "[", "]", ")", "do", "|", "actions", ",", "description", "|", "actions", "<<", "description", ".", "compile", "(", "self", ")", "if", "match_options?", "(", "description", ".", "options", ")", "actions", "end", "end" ]
Finds and returns all templates and files for this generators whose options match its options. === Parameters type<Symbol>:: The type of actions to look up (optional) === Returns [Templater::Actions::*]:: The found templates and files.
[ "Finds", "and", "returns", "all", "templates", "and", "files", "for", "this", "generators", "whose", "options", "match", "its", "options", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/templater-1.0.0/lib/templater/generator.rb#L548-L554
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/templater-1.0.0/lib/templater/generator.rb
Templater.Generator.all_actions
def all_actions(type=nil) all_actions = actions(type) all_actions += invocations.map { |i| i.all_actions(type) } all_actions.flatten end
ruby
def all_actions(type=nil) all_actions = actions(type) all_actions += invocations.map { |i| i.all_actions(type) } all_actions.flatten end
[ "def", "all_actions", "(", "type", "=", "nil", ")", "all_actions", "=", "actions", "(", "type", ")", "all_actions", "+=", "invocations", ".", "map", "{", "|", "i", "|", "i", ".", "all_actions", "(", "type", ")", "}", "all_actions", ".", "flatten", "end" ]
Finds and returns all templates and files for this generators and any of those generators it invokes, whose options match that generator's options. === Returns [Templater::Actions::File, Templater::Actions::Template]:: The found templates and files.
[ "Finds", "and", "returns", "all", "templates", "and", "files", "for", "this", "generators", "and", "any", "of", "those", "generators", "it", "invokes", "whose", "options", "match", "that", "generator", "s", "options", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/templater-1.0.0/lib/templater/generator.rb#L561-L565
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/ssl.rb
WEBrick.Utils.create_self_signed_cert
def create_self_signed_cert(bits, cn, comment) rsa = OpenSSL::PKey::RSA.new(bits){|p, n| case p when 0; $stderr.putc "." # BN_generate_prime when 1; $stderr.putc "+" # BN_generate_prime when 2; $stderr.putc "*" # searching good prime, # n = #of try, # but also data from BN_generate_prime when 3; $stderr.putc "\n" # found good prime, n==0 - p, n==1 - q, # but also data from BN_generate_prime else; $stderr.putc "*" # BN_generate_prime end } cert = OpenSSL::X509::Certificate.new cert.version = 2 cert.serial = 1 name = OpenSSL::X509::Name.new(cn) cert.subject = name cert.issuer = name cert.not_before = Time.now cert.not_after = Time.now + (365*24*60*60) cert.public_key = rsa.public_key ef = OpenSSL::X509::ExtensionFactory.new(nil,cert) ef.issuer_certificate = cert cert.extensions = [ ef.create_extension("basicConstraints","CA:FALSE"), ef.create_extension("keyUsage", "keyEncipherment"), ef.create_extension("subjectKeyIdentifier", "hash"), ef.create_extension("extendedKeyUsage", "serverAuth"), ef.create_extension("nsComment", comment), ] aki = ef.create_extension("authorityKeyIdentifier", "keyid:always,issuer:always") cert.add_extension(aki) cert.sign(rsa, OpenSSL::Digest::SHA1.new) return [ cert, rsa ] end
ruby
def create_self_signed_cert(bits, cn, comment) rsa = OpenSSL::PKey::RSA.new(bits){|p, n| case p when 0; $stderr.putc "." # BN_generate_prime when 1; $stderr.putc "+" # BN_generate_prime when 2; $stderr.putc "*" # searching good prime, # n = #of try, # but also data from BN_generate_prime when 3; $stderr.putc "\n" # found good prime, n==0 - p, n==1 - q, # but also data from BN_generate_prime else; $stderr.putc "*" # BN_generate_prime end } cert = OpenSSL::X509::Certificate.new cert.version = 2 cert.serial = 1 name = OpenSSL::X509::Name.new(cn) cert.subject = name cert.issuer = name cert.not_before = Time.now cert.not_after = Time.now + (365*24*60*60) cert.public_key = rsa.public_key ef = OpenSSL::X509::ExtensionFactory.new(nil,cert) ef.issuer_certificate = cert cert.extensions = [ ef.create_extension("basicConstraints","CA:FALSE"), ef.create_extension("keyUsage", "keyEncipherment"), ef.create_extension("subjectKeyIdentifier", "hash"), ef.create_extension("extendedKeyUsage", "serverAuth"), ef.create_extension("nsComment", comment), ] aki = ef.create_extension("authorityKeyIdentifier", "keyid:always,issuer:always") cert.add_extension(aki) cert.sign(rsa, OpenSSL::Digest::SHA1.new) return [ cert, rsa ] end
[ "def", "create_self_signed_cert", "(", "bits", ",", "cn", ",", "comment", ")", "rsa", "=", "OpenSSL", "::", "PKey", "::", "RSA", ".", "new", "(", "bits", ")", "{", "|", "p", ",", "n", "|", "case", "p", "when", "0", ";", "$stderr", ".", "putc", "\".\"", "# BN_generate_prime", "when", "1", ";", "$stderr", ".", "putc", "\"+\"", "# BN_generate_prime", "when", "2", ";", "$stderr", ".", "putc", "\"*\"", "# searching good prime,", "# n = #of try,", "# but also data from BN_generate_prime", "when", "3", ";", "$stderr", ".", "putc", "\"\\n\"", "# found good prime, n==0 - p, n==1 - q,", "# but also data from BN_generate_prime", "else", ";", "$stderr", ".", "putc", "\"*\"", "# BN_generate_prime", "end", "}", "cert", "=", "OpenSSL", "::", "X509", "::", "Certificate", ".", "new", "cert", ".", "version", "=", "2", "cert", ".", "serial", "=", "1", "name", "=", "OpenSSL", "::", "X509", "::", "Name", ".", "new", "(", "cn", ")", "cert", ".", "subject", "=", "name", "cert", ".", "issuer", "=", "name", "cert", ".", "not_before", "=", "Time", ".", "now", "cert", ".", "not_after", "=", "Time", ".", "now", "+", "(", "365", "*", "24", "*", "60", "*", "60", ")", "cert", ".", "public_key", "=", "rsa", ".", "public_key", "ef", "=", "OpenSSL", "::", "X509", "::", "ExtensionFactory", ".", "new", "(", "nil", ",", "cert", ")", "ef", ".", "issuer_certificate", "=", "cert", "cert", ".", "extensions", "=", "[", "ef", ".", "create_extension", "(", "\"basicConstraints\"", ",", "\"CA:FALSE\"", ")", ",", "ef", ".", "create_extension", "(", "\"keyUsage\"", ",", "\"keyEncipherment\"", ")", ",", "ef", ".", "create_extension", "(", "\"subjectKeyIdentifier\"", ",", "\"hash\"", ")", ",", "ef", ".", "create_extension", "(", "\"extendedKeyUsage\"", ",", "\"serverAuth\"", ")", ",", "ef", ".", "create_extension", "(", "\"nsComment\"", ",", "comment", ")", ",", "]", "aki", "=", "ef", ".", "create_extension", "(", "\"authorityKeyIdentifier\"", ",", "\"keyid:always,issuer:always\"", ")", "cert", ".", "add_extension", "(", "aki", ")", "cert", ".", "sign", "(", "rsa", ",", "OpenSSL", "::", "Digest", "::", "SHA1", ".", "new", ")", "return", "[", "cert", ",", "rsa", "]", "end" ]
Creates a self-signed certificate with the given number of +bits+, the issuer +cn+ and a +comment+ to be stored in the certificate.
[ "Creates", "a", "self", "-", "signed", "certificate", "with", "the", "given", "number", "of", "+", "bits", "+", "the", "issuer", "+", "cn", "+", "and", "a", "+", "comment", "+", "to", "be", "stored", "in", "the", "certificate", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/ssl.rb#L91-L129
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/ssl.rb
WEBrick.GenericServer.listen
def listen(address, port) # :nodoc: listeners = Utils::create_listeners(address, port, @logger) if @config[:SSLEnable] unless ssl_context @ssl_context = setup_ssl_context(@config) @logger.info("\n" + @config[:SSLCertificate].to_text) end listeners.collect!{|svr| ssvr = ::OpenSSL::SSL::SSLServer.new(svr, ssl_context) ssvr.start_immediately = @config[:SSLStartImmediately] ssvr } end @listeners += listeners end
ruby
def listen(address, port) # :nodoc: listeners = Utils::create_listeners(address, port, @logger) if @config[:SSLEnable] unless ssl_context @ssl_context = setup_ssl_context(@config) @logger.info("\n" + @config[:SSLCertificate].to_text) end listeners.collect!{|svr| ssvr = ::OpenSSL::SSL::SSLServer.new(svr, ssl_context) ssvr.start_immediately = @config[:SSLStartImmediately] ssvr } end @listeners += listeners end
[ "def", "listen", "(", "address", ",", "port", ")", "# :nodoc:", "listeners", "=", "Utils", "::", "create_listeners", "(", "address", ",", "port", ",", "@logger", ")", "if", "@config", "[", ":SSLEnable", "]", "unless", "ssl_context", "@ssl_context", "=", "setup_ssl_context", "(", "@config", ")", "@logger", ".", "info", "(", "\"\\n\"", "+", "@config", "[", ":SSLCertificate", "]", ".", "to_text", ")", "end", "listeners", ".", "collect!", "{", "|", "svr", "|", "ssvr", "=", "::", "OpenSSL", "::", "SSL", "::", "SSLServer", ".", "new", "(", "svr", ",", "ssl_context", ")", "ssvr", ".", "start_immediately", "=", "@config", "[", ":SSLStartImmediately", "]", "ssvr", "}", "end", "@listeners", "+=", "listeners", "end" ]
Updates +listen+ to enable SSL when the SSL configuration is active.
[ "Updates", "+", "listen", "+", "to", "enable", "SSL", "when", "the", "SSL", "configuration", "is", "active", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/ssl.rb#L151-L165
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/extlib-0.9.16/lib/extlib/logger.rb
Extlib.Logger.initialize_log
def initialize_log(log) close if @log # be sure that we don't leave open files laying around. if log.respond_to?(:write) @log = log elsif File.exist?(log) @log = open(log, (File::WRONLY | File::APPEND)) @log.sync = true else FileUtils.mkdir_p(File.dirname(log)) unless File.directory?(File.dirname(log)) @log = open(log, (File::WRONLY | File::APPEND | File::CREAT)) @log.sync = true @log.write("#{Time.now.httpdate} #{delimiter} info #{delimiter} Logfile created\n") end end
ruby
def initialize_log(log) close if @log # be sure that we don't leave open files laying around. if log.respond_to?(:write) @log = log elsif File.exist?(log) @log = open(log, (File::WRONLY | File::APPEND)) @log.sync = true else FileUtils.mkdir_p(File.dirname(log)) unless File.directory?(File.dirname(log)) @log = open(log, (File::WRONLY | File::APPEND | File::CREAT)) @log.sync = true @log.write("#{Time.now.httpdate} #{delimiter} info #{delimiter} Logfile created\n") end end
[ "def", "initialize_log", "(", "log", ")", "close", "if", "@log", "# be sure that we don't leave open files laying around.", "if", "log", ".", "respond_to?", "(", ":write", ")", "@log", "=", "log", "elsif", "File", ".", "exist?", "(", "log", ")", "@log", "=", "open", "(", "log", ",", "(", "File", "::", "WRONLY", "|", "File", "::", "APPEND", ")", ")", "@log", ".", "sync", "=", "true", "else", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "log", ")", ")", "unless", "File", ".", "directory?", "(", "File", ".", "dirname", "(", "log", ")", ")", "@log", "=", "open", "(", "log", ",", "(", "File", "::", "WRONLY", "|", "File", "::", "APPEND", "|", "File", "::", "CREAT", ")", ")", "@log", ".", "sync", "=", "true", "@log", ".", "write", "(", "\"#{Time.now.httpdate} #{delimiter} info #{delimiter} Logfile created\\n\"", ")", "end", "end" ]
Readies a log for writing. ==== Parameters log<IO, String>:: Either an IO object or a name of a logfile.
[ "Readies", "a", "log", "for", "writing", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/extlib-0.9.16/lib/extlib/logger.rb#L71-L85
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/extlib-0.9.16/lib/extlib/logger.rb
Extlib.Logger.<<
def <<(string = nil) message = "" message << delimiter message << string if string message << "\n" unless message[-1] == ?\n @buffer << message flush if @auto_flush message end
ruby
def <<(string = nil) message = "" message << delimiter message << string if string message << "\n" unless message[-1] == ?\n @buffer << message flush if @auto_flush message end
[ "def", "<<", "(", "string", "=", "nil", ")", "message", "=", "\"\"", "message", "<<", "delimiter", "message", "<<", "string", "if", "string", "message", "<<", "\"\\n\"", "unless", "message", "[", "-", "1", "]", "==", "?\\n", "@buffer", "<<", "message", "flush", "if", "@auto_flush", "message", "end" ]
Appends a message to the log. The methods yield to an optional block and the output of this block will be appended to the message. ==== Parameters string<String>:: The message to be logged. Defaults to nil. ==== Returns String:: The resulting message added to the log file.
[ "Appends", "a", "message", "to", "the", "log", ".", "The", "methods", "yield", "to", "an", "optional", "block", "and", "the", "output", "of", "this", "block", "will", "be", "appended", "to", "the", "message", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/extlib-0.9.16/lib/extlib/logger.rb#L144-L153
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/telnet.rb
Net.Telnet.write
def write(string) length = string.length while 0 < length IO::select(nil, [@sock]) @dumplog.log_dump('>', string[-length..-1]) if @options.has_key?("Dump_log") length -= @sock.syswrite(string[-length..-1]) end end
ruby
def write(string) length = string.length while 0 < length IO::select(nil, [@sock]) @dumplog.log_dump('>', string[-length..-1]) if @options.has_key?("Dump_log") length -= @sock.syswrite(string[-length..-1]) end end
[ "def", "write", "(", "string", ")", "length", "=", "string", ".", "length", "while", "0", "<", "length", "IO", "::", "select", "(", "nil", ",", "[", "@sock", "]", ")", "@dumplog", ".", "log_dump", "(", "'>'", ",", "string", "[", "-", "length", "..", "-", "1", "]", ")", "if", "@options", ".", "has_key?", "(", "\"Dump_log\"", ")", "length", "-=", "@sock", ".", "syswrite", "(", "string", "[", "-", "length", "..", "-", "1", "]", ")", "end", "end" ]
Write +string+ to the host. Does not perform any conversions on +string+. Will log +string+ to the dumplog, if the Dump_log option is set.
[ "Write", "+", "string", "+", "to", "the", "host", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/telnet.rb#L610-L617
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/telnet.rb
Net.Telnet.cmd
def cmd(options) # :yield: recvdata match = @options["Prompt"] time_out = @options["Timeout"] fail_eof = @options["FailEOF"] if options.kind_of?(Hash) string = options["String"] match = options["Match"] if options.has_key?("Match") time_out = options["Timeout"] if options.has_key?("Timeout") fail_eof = options["FailEOF"] if options.has_key?("FailEOF") else string = options end self.puts(string) if block_given? waitfor({"Prompt" => match, "Timeout" => time_out, "FailEOF" => fail_eof}){|c| yield c } else waitfor({"Prompt" => match, "Timeout" => time_out, "FailEOF" => fail_eof}) end end
ruby
def cmd(options) # :yield: recvdata match = @options["Prompt"] time_out = @options["Timeout"] fail_eof = @options["FailEOF"] if options.kind_of?(Hash) string = options["String"] match = options["Match"] if options.has_key?("Match") time_out = options["Timeout"] if options.has_key?("Timeout") fail_eof = options["FailEOF"] if options.has_key?("FailEOF") else string = options end self.puts(string) if block_given? waitfor({"Prompt" => match, "Timeout" => time_out, "FailEOF" => fail_eof}){|c| yield c } else waitfor({"Prompt" => match, "Timeout" => time_out, "FailEOF" => fail_eof}) end end
[ "def", "cmd", "(", "options", ")", "# :yield: recvdata", "match", "=", "@options", "[", "\"Prompt\"", "]", "time_out", "=", "@options", "[", "\"Timeout\"", "]", "fail_eof", "=", "@options", "[", "\"FailEOF\"", "]", "if", "options", ".", "kind_of?", "(", "Hash", ")", "string", "=", "options", "[", "\"String\"", "]", "match", "=", "options", "[", "\"Match\"", "]", "if", "options", ".", "has_key?", "(", "\"Match\"", ")", "time_out", "=", "options", "[", "\"Timeout\"", "]", "if", "options", ".", "has_key?", "(", "\"Timeout\"", ")", "fail_eof", "=", "options", "[", "\"FailEOF\"", "]", "if", "options", ".", "has_key?", "(", "\"FailEOF\"", ")", "else", "string", "=", "options", "end", "self", ".", "puts", "(", "string", ")", "if", "block_given?", "waitfor", "(", "{", "\"Prompt\"", "=>", "match", ",", "\"Timeout\"", "=>", "time_out", ",", "\"FailEOF\"", "=>", "fail_eof", "}", ")", "{", "|", "c", "|", "yield", "c", "}", "else", "waitfor", "(", "{", "\"Prompt\"", "=>", "match", ",", "\"Timeout\"", "=>", "time_out", ",", "\"FailEOF\"", "=>", "fail_eof", "}", ")", "end", "end" ]
Send a command to the host. More exactly, sends a string to the host, and reads in all received data until is sees the prompt or other matched sequence. If a block is given, the received data will be yielded to it as it is read in. Whether a block is given or not, the received data will be return as a string. Note that the received data includes the prompt and in most cases the host's echo of our command. +options+ is either a String, specified the string or command to send to the host; or it is a hash of options. If a hash, the following options can be specified: String:: the command or other string to send to the host. Match:: a regular expression, the sequence to look for in the received data before returning. If not specified, the Prompt option value specified when this instance was created will be used, or, failing that, the default prompt of /[$%#>] \z/n. Timeout:: the seconds to wait for data from the host before raising a Timeout error. If not specified, the Timeout option value specified when this instance was created will be used, or, failing that, the default value of 10 seconds. The command or other string will have the newline sequence appended to it.
[ "Send", "a", "command", "to", "the", "host", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/telnet.rb#L678-L698
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/telnet.rb
Net.Telnet.login
def login(options, password = nil) # :yield: recvdata login_prompt = /[Ll]ogin[: ]*\z/n password_prompt = /[Pp]ass(?:word|phrase)[: ]*\z/n if options.kind_of?(Hash) username = options["Name"] password = options["Password"] login_prompt = options["LoginPrompt"] if options["LoginPrompt"] password_prompt = options["PasswordPrompt"] if options["PasswordPrompt"] else username = options end if block_given? line = waitfor(login_prompt){|c| yield c } if password line += cmd({"String" => username, "Match" => password_prompt}){|c| yield c } line += cmd(password){|c| yield c } else line += cmd(username){|c| yield c } end else line = waitfor(login_prompt) if password line += cmd({"String" => username, "Match" => password_prompt}) line += cmd(password) else line += cmd(username) end end line end
ruby
def login(options, password = nil) # :yield: recvdata login_prompt = /[Ll]ogin[: ]*\z/n password_prompt = /[Pp]ass(?:word|phrase)[: ]*\z/n if options.kind_of?(Hash) username = options["Name"] password = options["Password"] login_prompt = options["LoginPrompt"] if options["LoginPrompt"] password_prompt = options["PasswordPrompt"] if options["PasswordPrompt"] else username = options end if block_given? line = waitfor(login_prompt){|c| yield c } if password line += cmd({"String" => username, "Match" => password_prompt}){|c| yield c } line += cmd(password){|c| yield c } else line += cmd(username){|c| yield c } end else line = waitfor(login_prompt) if password line += cmd({"String" => username, "Match" => password_prompt}) line += cmd(password) else line += cmd(username) end end line end
[ "def", "login", "(", "options", ",", "password", "=", "nil", ")", "# :yield: recvdata", "login_prompt", "=", "/", "\\z", "/n", "password_prompt", "=", "/", "\\z", "/n", "if", "options", ".", "kind_of?", "(", "Hash", ")", "username", "=", "options", "[", "\"Name\"", "]", "password", "=", "options", "[", "\"Password\"", "]", "login_prompt", "=", "options", "[", "\"LoginPrompt\"", "]", "if", "options", "[", "\"LoginPrompt\"", "]", "password_prompt", "=", "options", "[", "\"PasswordPrompt\"", "]", "if", "options", "[", "\"PasswordPrompt\"", "]", "else", "username", "=", "options", "end", "if", "block_given?", "line", "=", "waitfor", "(", "login_prompt", ")", "{", "|", "c", "|", "yield", "c", "}", "if", "password", "line", "+=", "cmd", "(", "{", "\"String\"", "=>", "username", ",", "\"Match\"", "=>", "password_prompt", "}", ")", "{", "|", "c", "|", "yield", "c", "}", "line", "+=", "cmd", "(", "password", ")", "{", "|", "c", "|", "yield", "c", "}", "else", "line", "+=", "cmd", "(", "username", ")", "{", "|", "c", "|", "yield", "c", "}", "end", "else", "line", "=", "waitfor", "(", "login_prompt", ")", "if", "password", "line", "+=", "cmd", "(", "{", "\"String\"", "=>", "username", ",", "\"Match\"", "=>", "password_prompt", "}", ")", "line", "+=", "cmd", "(", "password", ")", "else", "line", "+=", "cmd", "(", "username", ")", "end", "end", "line", "end" ]
Login to the host with a given username and password. The username and password can either be provided as two string arguments in that order, or as a hash with keys "Name" and "Password". This method looks for the strings "login" and "Password" from the host to determine when to send the username and password. If the login sequence does not follow this pattern (for instance, you are connecting to a service other than telnet), you will need to handle login yourself. The password can be omitted, either by only provided one String argument, which will be used as the username, or by providing a has that has no "Password" key. In this case, the method will not look for the "Password:" prompt; if it is sent, it will have to be dealt with by later calls. The method returns all data received during the login process from the host, including the echoed username but not the password (which the host should not echo). If a block is passed in, this received data is also yielded to the block as it is received.
[ "Login", "to", "the", "host", "with", "a", "given", "username", "and", "password", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/telnet.rb#L722-L754
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httputils.rb
WEBrick.HTTPUtils.normalize_path
def normalize_path(path) raise "abnormal path `#{path}'" if path[0] != ?/ ret = path.dup ret.gsub!(%r{/+}o, '/') # // => / while ret.sub!(%r'/\.(?:/|\Z)', '/'); end # /. => / while ret.sub!(%r'/(?!\.\./)[^/]+/\.\.(?:/|\Z)', '/'); end # /foo/.. => /foo raise "abnormal path `#{path}'" if %r{/\.\.(/|\Z)} =~ ret ret end
ruby
def normalize_path(path) raise "abnormal path `#{path}'" if path[0] != ?/ ret = path.dup ret.gsub!(%r{/+}o, '/') # // => / while ret.sub!(%r'/\.(?:/|\Z)', '/'); end # /. => / while ret.sub!(%r'/(?!\.\./)[^/]+/\.\.(?:/|\Z)', '/'); end # /foo/.. => /foo raise "abnormal path `#{path}'" if %r{/\.\.(/|\Z)} =~ ret ret end
[ "def", "normalize_path", "(", "path", ")", "raise", "\"abnormal path `#{path}'\"", "if", "path", "[", "0", "]", "!=", "?/", "ret", "=", "path", ".", "dup", "ret", ".", "gsub!", "(", "%r{", "}o", ",", "'/'", ")", "# // => /", "while", "ret", ".", "sub!", "(", "%r'", "\\.", "\\Z", "'", ",", "'/'", ")", ";", "end", "# /. => /", "while", "ret", ".", "sub!", "(", "%r'", "\\.", "\\.", "\\.", "\\.", "\\Z", "'", ",", "'/'", ")", ";", "end", "# /foo/.. => /foo", "raise", "\"abnormal path `#{path}'\"", "if", "%r{", "\\.", "\\.", "\\Z", "}", "=~", "ret", "ret", "end" ]
Normalizes a request path. Raises an exception if the path cannot be normalized.
[ "Normalizes", "a", "request", "path", ".", "Raises", "an", "exception", "if", "the", "path", "cannot", "be", "normalized", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httputils.rb#L30-L40
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httputils.rb
WEBrick.HTTPUtils.load_mime_types
def load_mime_types(file) open(file){ |io| hash = Hash.new io.each{ |line| next if /^#/ =~ line line.chomp! mimetype, ext0 = line.split(/\s+/, 2) next unless ext0 next if ext0.empty? ext0.split(/\s+/).each{ |ext| hash[ext] = mimetype } } hash } end
ruby
def load_mime_types(file) open(file){ |io| hash = Hash.new io.each{ |line| next if /^#/ =~ line line.chomp! mimetype, ext0 = line.split(/\s+/, 2) next unless ext0 next if ext0.empty? ext0.split(/\s+/).each{ |ext| hash[ext] = mimetype } } hash } end
[ "def", "load_mime_types", "(", "file", ")", "open", "(", "file", ")", "{", "|", "io", "|", "hash", "=", "Hash", ".", "new", "io", ".", "each", "{", "|", "line", "|", "next", "if", "/", "/", "=~", "line", "line", ".", "chomp!", "mimetype", ",", "ext0", "=", "line", ".", "split", "(", "/", "\\s", "/", ",", "2", ")", "next", "unless", "ext0", "next", "if", "ext0", ".", "empty?", "ext0", ".", "split", "(", "/", "\\s", "/", ")", ".", "each", "{", "|", "ext", "|", "hash", "[", "ext", "]", "=", "mimetype", "}", "}", "hash", "}", "end" ]
Loads Apache-compatible mime.types in +file+.
[ "Loads", "Apache", "-", "compatible", "mime", ".", "types", "in", "+", "file", "+", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httputils.rb#L108-L121
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httputils.rb
WEBrick.HTTPUtils.parse_range_header
def parse_range_header(ranges_specifier) if /^bytes=(.*)/ =~ ranges_specifier byte_range_set = split_header_value($1) byte_range_set.collect{|range_spec| case range_spec when /^(\d+)-(\d+)/ then $1.to_i .. $2.to_i when /^(\d+)-/ then $1.to_i .. -1 when /^-(\d+)/ then -($1.to_i) .. -1 else return nil end } end end
ruby
def parse_range_header(ranges_specifier) if /^bytes=(.*)/ =~ ranges_specifier byte_range_set = split_header_value($1) byte_range_set.collect{|range_spec| case range_spec when /^(\d+)-(\d+)/ then $1.to_i .. $2.to_i when /^(\d+)-/ then $1.to_i .. -1 when /^-(\d+)/ then -($1.to_i) .. -1 else return nil end } end end
[ "def", "parse_range_header", "(", "ranges_specifier", ")", "if", "/", "/", "=~", "ranges_specifier", "byte_range_set", "=", "split_header_value", "(", "$1", ")", "byte_range_set", ".", "collect", "{", "|", "range_spec", "|", "case", "range_spec", "when", "/", "\\d", "\\d", "/", "then", "$1", ".", "to_i", "..", "$2", ".", "to_i", "when", "/", "\\d", "/", "then", "$1", ".", "to_i", "..", "-", "1", "when", "/", "\\d", "/", "then", "-", "(", "$1", ".", "to_i", ")", "..", "-", "1", "else", "return", "nil", "end", "}", "end", "end" ]
Parses a Range header value +ranges_specifier+
[ "Parses", "a", "Range", "header", "value", "+", "ranges_specifier", "+" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httputils.rb#L181-L193
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httputils.rb
WEBrick.HTTPUtils.parse_qvalues
def parse_qvalues(value) tmp = [] if value parts = value.split(/,\s*/) parts.each {|part| if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part) val = m[1] q = (m[2] or 1).to_f tmp.push([val, q]) end } tmp = tmp.sort_by{|val, q| -q} tmp.collect!{|val, q| val} end return tmp end
ruby
def parse_qvalues(value) tmp = [] if value parts = value.split(/,\s*/) parts.each {|part| if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part) val = m[1] q = (m[2] or 1).to_f tmp.push([val, q]) end } tmp = tmp.sort_by{|val, q| -q} tmp.collect!{|val, q| val} end return tmp end
[ "def", "parse_qvalues", "(", "value", ")", "tmp", "=", "[", "]", "if", "value", "parts", "=", "value", ".", "split", "(", "/", "\\s", "/", ")", "parts", ".", "each", "{", "|", "part", "|", "if", "m", "=", "%r{", "\\s", "\\s", "\\d", "\\.", "\\d", "}", ".", "match", "(", "part", ")", "val", "=", "m", "[", "1", "]", "q", "=", "(", "m", "[", "2", "]", "or", "1", ")", ".", "to_f", "tmp", ".", "push", "(", "[", "val", ",", "q", "]", ")", "end", "}", "tmp", "=", "tmp", ".", "sort_by", "{", "|", "val", ",", "q", "|", "-", "q", "}", "tmp", ".", "collect!", "{", "|", "val", ",", "q", "|", "val", "}", "end", "return", "tmp", "end" ]
Parses q values in +value+ as used in Accept headers.
[ "Parses", "q", "values", "in", "+", "value", "+", "as", "used", "in", "Accept", "headers", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httputils.rb#L199-L214
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httputils.rb
WEBrick.HTTPUtils.parse_query
def parse_query(str) query = Hash.new if str str.split(/[&;]/).each{|x| next if x.empty? key, val = x.split(/=/,2) key = unescape_form(key) val = unescape_form(val.to_s) val = FormData.new(val) val.name = key if query.has_key?(key) query[key].append_data(val) next end query[key] = val } end query end
ruby
def parse_query(str) query = Hash.new if str str.split(/[&;]/).each{|x| next if x.empty? key, val = x.split(/=/,2) key = unescape_form(key) val = unescape_form(val.to_s) val = FormData.new(val) val.name = key if query.has_key?(key) query[key].append_data(val) next end query[key] = val } end query end
[ "def", "parse_query", "(", "str", ")", "query", "=", "Hash", ".", "new", "if", "str", "str", ".", "split", "(", "/", "/", ")", ".", "each", "{", "|", "x", "|", "next", "if", "x", ".", "empty?", "key", ",", "val", "=", "x", ".", "split", "(", "/", "/", ",", "2", ")", "key", "=", "unescape_form", "(", "key", ")", "val", "=", "unescape_form", "(", "val", ".", "to_s", ")", "val", "=", "FormData", ".", "new", "(", "val", ")", "val", ".", "name", "=", "key", "if", "query", ".", "has_key?", "(", "key", ")", "query", "[", "key", "]", ".", "append_data", "(", "val", ")", "next", "end", "query", "[", "key", "]", "=", "val", "}", "end", "query", "end" ]
Parses the query component of a URI in +str+
[ "Parses", "the", "query", "component", "of", "a", "URI", "in", "+", "str", "+" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httputils.rb#L368-L386
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httputils.rb
WEBrick.HTTPUtils.escape_path
def escape_path(str) result = "" str.scan(%r{/([^/]*)}).each{|i| result << "/" << _escape(i[0], UNESCAPED_PCHAR) } return result end
ruby
def escape_path(str) result = "" str.scan(%r{/([^/]*)}).each{|i| result << "/" << _escape(i[0], UNESCAPED_PCHAR) } return result end
[ "def", "escape_path", "(", "str", ")", "result", "=", "\"\"", "str", ".", "scan", "(", "%r{", "}", ")", ".", "each", "{", "|", "i", "|", "result", "<<", "\"/\"", "<<", "_escape", "(", "i", "[", "0", "]", ",", "UNESCAPED_PCHAR", ")", "}", "return", "result", "end" ]
Escapes path +str+
[ "Escapes", "path", "+", "str", "+" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httputils.rb#L494-L500
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/rake/file_list.rb
Rake.FileList.partition
def partition(&block) # :nodoc: resolve result = @items.partition(&block) [ FileList.new.import(result[0]), FileList.new.import(result[1]), ] end
ruby
def partition(&block) # :nodoc: resolve result = @items.partition(&block) [ FileList.new.import(result[0]), FileList.new.import(result[1]), ] end
[ "def", "partition", "(", "&", "block", ")", "# :nodoc:", "resolve", "result", "=", "@items", ".", "partition", "(", "block", ")", "[", "FileList", ".", "new", ".", "import", "(", "result", "[", "0", "]", ")", ",", "FileList", ".", "new", ".", "import", "(", "result", "[", "1", "]", ")", ",", "]", "end" ]
FileList version of partition. Needed because the nested arrays should be FileLists in this version.
[ "FileList", "version", "of", "partition", ".", "Needed", "because", "the", "nested", "arrays", "should", "be", "FileLists", "in", "this", "version", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/rake/file_list.rb#L326-L333
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/rake/file_list.rb
Rake.FileList.add_matching
def add_matching(pattern) FileList.glob(pattern).each do |fn| self << fn unless excluded_from_list?(fn) end end
ruby
def add_matching(pattern) FileList.glob(pattern).each do |fn| self << fn unless excluded_from_list?(fn) end end
[ "def", "add_matching", "(", "pattern", ")", "FileList", ".", "glob", "(", "pattern", ")", ".", "each", "do", "|", "fn", "|", "self", "<<", "fn", "unless", "excluded_from_list?", "(", "fn", ")", "end", "end" ]
Add matching glob patterns.
[ "Add", "matching", "glob", "patterns", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/rake/file_list.rb#L342-L346
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/rake/promise.rb
Rake.Promise.value
def value unless complete? stat :sleeping_on, :item_id => object_id @mutex.synchronize do stat :has_lock_on, :item_id => object_id chore stat :releasing_lock_on, :item_id => object_id end end error? ? raise(@error) : @result end
ruby
def value unless complete? stat :sleeping_on, :item_id => object_id @mutex.synchronize do stat :has_lock_on, :item_id => object_id chore stat :releasing_lock_on, :item_id => object_id end end error? ? raise(@error) : @result end
[ "def", "value", "unless", "complete?", "stat", ":sleeping_on", ",", ":item_id", "=>", "object_id", "@mutex", ".", "synchronize", "do", "stat", ":has_lock_on", ",", ":item_id", "=>", "object_id", "chore", "stat", ":releasing_lock_on", ",", ":item_id", "=>", "object_id", "end", "end", "error?", "?", "raise", "(", "@error", ")", ":", "@result", "end" ]
Create a promise to do the chore specified by the block. Return the value of this promise. If the promised chore is not yet complete, then do the work synchronously. We will wait.
[ "Create", "a", "promise", "to", "do", "the", "chore", "specified", "by", "the", "block", ".", "Return", "the", "value", "of", "this", "promise", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/rake/promise.rb#L28-L38
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/rake/promise.rb
Rake.Promise.chore
def chore if complete? stat :found_completed, :item_id => object_id return end stat :will_execute, :item_id => object_id begin @result = @block.call(*@args) rescue Exception => e @error = e end stat :did_execute, :item_id => object_id discard end
ruby
def chore if complete? stat :found_completed, :item_id => object_id return end stat :will_execute, :item_id => object_id begin @result = @block.call(*@args) rescue Exception => e @error = e end stat :did_execute, :item_id => object_id discard end
[ "def", "chore", "if", "complete?", "stat", ":found_completed", ",", ":item_id", "=>", "object_id", "return", "end", "stat", ":will_execute", ",", ":item_id", "=>", "object_id", "begin", "@result", "=", "@block", ".", "call", "(", "@args", ")", "rescue", "Exception", "=>", "e", "@error", "=", "e", "end", "stat", ":did_execute", ",", ":item_id", "=>", "object_id", "discard", "end" ]
Perform the chore promised
[ "Perform", "the", "chore", "promised" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/rake/promise.rb#L56-L69
train
rhomobile/rhodes
lib/extensions/net-http/net/http.rb
Net.HTTPHeader.[]=
def []=(key, val) unless val @header.delete key.downcase return val end @header[key.downcase] = [val] end
ruby
def []=(key, val) unless val @header.delete key.downcase return val end @header[key.downcase] = [val] end
[ "def", "[]=", "(", "key", ",", "val", ")", "unless", "val", "@header", ".", "delete", "key", ".", "downcase", "return", "val", "end", "@header", "[", "key", ".", "downcase", "]", "=", "[", "val", "]", "end" ]
Sets the header field corresponding to the case-insensitive key.
[ "Sets", "the", "header", "field", "corresponding", "to", "the", "case", "-", "insensitive", "key", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/extensions/net-http/net/http.rb#L1346-L1352
train
rhomobile/rhodes
lib/extensions/net-http/net/http.rb
Net.HTTPHeader.each_header
def each_header #:yield: +key+, +value+ block_given? or return enum_for(__method__) @header.each do |k,va| yield k, va.join(', ') end end
ruby
def each_header #:yield: +key+, +value+ block_given? or return enum_for(__method__) @header.each do |k,va| yield k, va.join(', ') end end
[ "def", "each_header", "#:yield: +key+, +value+", "block_given?", "or", "return", "enum_for", "(", "__method__", ")", "@header", ".", "each", "do", "|", "k", ",", "va", "|", "yield", "k", ",", "va", ".", "join", "(", "', '", ")", "end", "end" ]
Iterates for each header names and values.
[ "Iterates", "for", "each", "header", "names", "and", "values", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/extensions/net-http/net/http.rb#L1403-L1408
train
rhomobile/rhodes
lib/extensions/net-http/net/http.rb
Net.HTTPResponse.read_body
def read_body(dest = nil, &block) if @read raise IOError, "#{self.class}\#read_body called twice" if dest or block return @body end to = procdest(dest, block) stream_check if @body_exist read_body_0 to @body = to else @body = nil end @read = true @body end
ruby
def read_body(dest = nil, &block) if @read raise IOError, "#{self.class}\#read_body called twice" if dest or block return @body end to = procdest(dest, block) stream_check if @body_exist read_body_0 to @body = to else @body = nil end @read = true @body end
[ "def", "read_body", "(", "dest", "=", "nil", ",", "&", "block", ")", "if", "@read", "raise", "IOError", ",", "\"#{self.class}\\#read_body called twice\"", "if", "dest", "or", "block", "return", "@body", "end", "to", "=", "procdest", "(", "dest", ",", "block", ")", "stream_check", "if", "@body_exist", "read_body_0", "to", "@body", "=", "to", "else", "@body", "=", "nil", "end", "@read", "=", "true", "@body", "end" ]
Gets entity body. If the block given, yields it to +block+. The body is provided in fragments, as it is read in from the socket. Calling this method a second or subsequent time will return the already read string. http.request_get('/index.html') {|res| puts res.read_body } http.request_get('/index.html') {|res| p res.read_body.object_id # 538149362 p res.read_body.object_id # 538149362 } # using iterator http.request_get('/index.html') {|res| res.read_body do |segment| print segment end }
[ "Gets", "entity", "body", ".", "If", "the", "block", "given", "yields", "it", "to", "+", "block", "+", ".", "The", "body", "is", "provided", "in", "fragments", "as", "it", "is", "read", "in", "from", "the", "socket", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/extensions/net-http/net/http.rb#L2395-L2411
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/rest-client-1.7.2/lib/restclient/abstract_response.rb
RestClient.AbstractResponse.follow_redirection
def follow_redirection request = nil, result = nil, & block url = headers[:location] if url !~ /^http/ url = URI.parse(args[:url]).merge(url).to_s end args[:url] = url if request if request.max_redirects == 0 raise MaxRedirectsReached end args[:password] = request.password args[:user] = request.user args[:headers] = request.headers args[:max_redirects] = request.max_redirects - 1 # pass any cookie set in the result if result && result['set-cookie'] args[:headers][:cookies] = (args[:headers][:cookies] || {}).merge(parse_cookie(result['set-cookie'])) end end Request.execute args, &block end
ruby
def follow_redirection request = nil, result = nil, & block url = headers[:location] if url !~ /^http/ url = URI.parse(args[:url]).merge(url).to_s end args[:url] = url if request if request.max_redirects == 0 raise MaxRedirectsReached end args[:password] = request.password args[:user] = request.user args[:headers] = request.headers args[:max_redirects] = request.max_redirects - 1 # pass any cookie set in the result if result && result['set-cookie'] args[:headers][:cookies] = (args[:headers][:cookies] || {}).merge(parse_cookie(result['set-cookie'])) end end Request.execute args, &block end
[ "def", "follow_redirection", "request", "=", "nil", ",", "result", "=", "nil", ",", "&", "block", "url", "=", "headers", "[", ":location", "]", "if", "url", "!~", "/", "/", "url", "=", "URI", ".", "parse", "(", "args", "[", ":url", "]", ")", ".", "merge", "(", "url", ")", ".", "to_s", "end", "args", "[", ":url", "]", "=", "url", "if", "request", "if", "request", ".", "max_redirects", "==", "0", "raise", "MaxRedirectsReached", "end", "args", "[", ":password", "]", "=", "request", ".", "password", "args", "[", ":user", "]", "=", "request", ".", "user", "args", "[", ":headers", "]", "=", "request", ".", "headers", "args", "[", ":max_redirects", "]", "=", "request", ".", "max_redirects", "-", "1", "# pass any cookie set in the result", "if", "result", "&&", "result", "[", "'set-cookie'", "]", "args", "[", ":headers", "]", "[", ":cookies", "]", "=", "(", "args", "[", ":headers", "]", "[", ":cookies", "]", "||", "{", "}", ")", ".", "merge", "(", "parse_cookie", "(", "result", "[", "'set-cookie'", "]", ")", ")", "end", "end", "Request", ".", "execute", "args", ",", "block", "end" ]
Follow a redirection
[ "Follow", "a", "redirection" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/rest-client-1.7.2/lib/restclient/abstract_response.rb#L63-L83
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/rest-client-1.7.2/lib/restclient/abstract_response.rb
RestClient.AbstractResponse.parse_cookie
def parse_cookie cookie_content out = {} CGI::Cookie::parse(cookie_content).each do |key, cookie| unless ['expires', 'path'].include? key out[CGI::escape(key)] = cookie.value[0] ? (CGI::escape(cookie.value[0]) || '') : '' end end out end
ruby
def parse_cookie cookie_content out = {} CGI::Cookie::parse(cookie_content).each do |key, cookie| unless ['expires', 'path'].include? key out[CGI::escape(key)] = cookie.value[0] ? (CGI::escape(cookie.value[0]) || '') : '' end end out end
[ "def", "parse_cookie", "cookie_content", "out", "=", "{", "}", "CGI", "::", "Cookie", "::", "parse", "(", "cookie_content", ")", ".", "each", "do", "|", "key", ",", "cookie", "|", "unless", "[", "'expires'", ",", "'path'", "]", ".", "include?", "key", "out", "[", "CGI", "::", "escape", "(", "key", ")", "]", "=", "cookie", ".", "value", "[", "0", "]", "?", "(", "CGI", "::", "escape", "(", "cookie", ".", "value", "[", "0", "]", ")", "||", "''", ")", ":", "''", "end", "end", "out", "end" ]
Parse a cookie value and return its content in an Hash
[ "Parse", "a", "cookie", "value", "and", "return", "its", "content", "in", "an", "Hash" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/rest-client-1.7.2/lib/restclient/abstract_response.rb#L95-L103
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/rake/task_manager.rb
Rake.TaskManager.[]
def [](task_name, scopes=nil) task_name = task_name.to_s self.lookup(task_name, scopes) or enhance_with_matching_rule(task_name) or synthesize_file_task(task_name) or fail "Don't know how to build task '#{task_name}'" end
ruby
def [](task_name, scopes=nil) task_name = task_name.to_s self.lookup(task_name, scopes) or enhance_with_matching_rule(task_name) or synthesize_file_task(task_name) or fail "Don't know how to build task '#{task_name}'" end
[ "def", "[]", "(", "task_name", ",", "scopes", "=", "nil", ")", "task_name", "=", "task_name", ".", "to_s", "self", ".", "lookup", "(", "task_name", ",", "scopes", ")", "or", "enhance_with_matching_rule", "(", "task_name", ")", "or", "synthesize_file_task", "(", "task_name", ")", "or", "fail", "\"Don't know how to build task '#{task_name}'\"", "end" ]
Find a matching task for +task_name+.
[ "Find", "a", "matching", "task", "for", "+", "task_name", "+", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/rake/task_manager.rb#L44-L50
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httpserver.rb
WEBrick.HTTPServer.run
def run(sock) while true res = HTTPResponse.new(@config) req = HTTPRequest.new(@config) server = self begin timeout = @config[:RequestTimeout] while timeout > 0 break if IO.select([sock], nil, nil, 0.5) timeout = 0 if @status != :Running timeout -= 0.5 end raise HTTPStatus::EOFError if timeout <= 0 raise HTTPStatus::EOFError if sock.eof? req.parse(sock) res.request_method = req.request_method res.request_uri = req.request_uri res.request_http_version = req.http_version res.keep_alive = req.keep_alive? server = lookup_server(req) || self if callback = server[:RequestCallback] callback.call(req, res) elsif callback = server[:RequestHandler] msg = ":RequestHandler is deprecated, please use :RequestCallback" @logger.warn(msg) callback.call(req, res) end server.service(req, res) rescue HTTPStatus::EOFError, HTTPStatus::RequestTimeout => ex res.set_error(ex) rescue HTTPStatus::Error => ex @logger.error(ex.message) res.set_error(ex) rescue HTTPStatus::Status => ex res.status = ex.code rescue StandardError => ex @logger.error(ex) res.set_error(ex, true) ensure if req.request_line if req.keep_alive? && res.keep_alive? req.fixup() end res.send_response(sock) server.access_log(@config, req, res) end end break if @http_version < "1.1" break unless req.keep_alive? break unless res.keep_alive? end end
ruby
def run(sock) while true res = HTTPResponse.new(@config) req = HTTPRequest.new(@config) server = self begin timeout = @config[:RequestTimeout] while timeout > 0 break if IO.select([sock], nil, nil, 0.5) timeout = 0 if @status != :Running timeout -= 0.5 end raise HTTPStatus::EOFError if timeout <= 0 raise HTTPStatus::EOFError if sock.eof? req.parse(sock) res.request_method = req.request_method res.request_uri = req.request_uri res.request_http_version = req.http_version res.keep_alive = req.keep_alive? server = lookup_server(req) || self if callback = server[:RequestCallback] callback.call(req, res) elsif callback = server[:RequestHandler] msg = ":RequestHandler is deprecated, please use :RequestCallback" @logger.warn(msg) callback.call(req, res) end server.service(req, res) rescue HTTPStatus::EOFError, HTTPStatus::RequestTimeout => ex res.set_error(ex) rescue HTTPStatus::Error => ex @logger.error(ex.message) res.set_error(ex) rescue HTTPStatus::Status => ex res.status = ex.code rescue StandardError => ex @logger.error(ex) res.set_error(ex, true) ensure if req.request_line if req.keep_alive? && res.keep_alive? req.fixup() end res.send_response(sock) server.access_log(@config, req, res) end end break if @http_version < "1.1" break unless req.keep_alive? break unless res.keep_alive? end end
[ "def", "run", "(", "sock", ")", "while", "true", "res", "=", "HTTPResponse", ".", "new", "(", "@config", ")", "req", "=", "HTTPRequest", ".", "new", "(", "@config", ")", "server", "=", "self", "begin", "timeout", "=", "@config", "[", ":RequestTimeout", "]", "while", "timeout", ">", "0", "break", "if", "IO", ".", "select", "(", "[", "sock", "]", ",", "nil", ",", "nil", ",", "0.5", ")", "timeout", "=", "0", "if", "@status", "!=", ":Running", "timeout", "-=", "0.5", "end", "raise", "HTTPStatus", "::", "EOFError", "if", "timeout", "<=", "0", "raise", "HTTPStatus", "::", "EOFError", "if", "sock", ".", "eof?", "req", ".", "parse", "(", "sock", ")", "res", ".", "request_method", "=", "req", ".", "request_method", "res", ".", "request_uri", "=", "req", ".", "request_uri", "res", ".", "request_http_version", "=", "req", ".", "http_version", "res", ".", "keep_alive", "=", "req", ".", "keep_alive?", "server", "=", "lookup_server", "(", "req", ")", "||", "self", "if", "callback", "=", "server", "[", ":RequestCallback", "]", "callback", ".", "call", "(", "req", ",", "res", ")", "elsif", "callback", "=", "server", "[", ":RequestHandler", "]", "msg", "=", "\":RequestHandler is deprecated, please use :RequestCallback\"", "@logger", ".", "warn", "(", "msg", ")", "callback", ".", "call", "(", "req", ",", "res", ")", "end", "server", ".", "service", "(", "req", ",", "res", ")", "rescue", "HTTPStatus", "::", "EOFError", ",", "HTTPStatus", "::", "RequestTimeout", "=>", "ex", "res", ".", "set_error", "(", "ex", ")", "rescue", "HTTPStatus", "::", "Error", "=>", "ex", "@logger", ".", "error", "(", "ex", ".", "message", ")", "res", ".", "set_error", "(", "ex", ")", "rescue", "HTTPStatus", "::", "Status", "=>", "ex", "res", ".", "status", "=", "ex", ".", "code", "rescue", "StandardError", "=>", "ex", "@logger", ".", "error", "(", "ex", ")", "res", ".", "set_error", "(", "ex", ",", "true", ")", "ensure", "if", "req", ".", "request_line", "if", "req", ".", "keep_alive?", "&&", "res", ".", "keep_alive?", "req", ".", "fixup", "(", ")", "end", "res", ".", "send_response", "(", "sock", ")", "server", ".", "access_log", "(", "@config", ",", "req", ",", "res", ")", "end", "end", "break", "if", "@http_version", "<", "\"1.1\"", "break", "unless", "req", ".", "keep_alive?", "break", "unless", "res", ".", "keep_alive?", "end", "end" ]
Creates a new HTTP server according to +config+ An HTTP server uses the following attributes: :AccessLog:: An array of access logs. See WEBrick::AccessLog :BindAddress:: Local address for the server to bind to :DocumentRoot:: Root path to serve files from :DocumentRootOptions:: Options for the default HTTPServlet::FileHandler :HTTPVersion:: The HTTP version of this server :Port:: Port to listen on :RequestCallback:: Called with a request and response before each request is serviced. :RequestTimeout:: Maximum time to wait between requests :ServerAlias:: Array of alternate names for this server for virtual hosting :ServerName:: Name for this server for virtual hosting Processes requests on +sock+
[ "Creates", "a", "new", "HTTP", "server", "according", "to", "+", "config", "+" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httpserver.rb#L67-L118
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httpserver.rb
WEBrick.HTTPServer.service
def service(req, res) if req.unparsed_uri == "*" if req.request_method == "OPTIONS" do_OPTIONS(req, res) raise HTTPStatus::OK end raise HTTPStatus::NotFound, "`#{req.unparsed_uri}' not found." end servlet, options, script_name, path_info = search_servlet(req.path) raise HTTPStatus::NotFound, "`#{req.path}' not found." unless servlet req.script_name = script_name req.path_info = path_info si = servlet.get_instance(self, *options) @logger.debug(format("%s is invoked.", si.class.name)) si.service(req, res) end
ruby
def service(req, res) if req.unparsed_uri == "*" if req.request_method == "OPTIONS" do_OPTIONS(req, res) raise HTTPStatus::OK end raise HTTPStatus::NotFound, "`#{req.unparsed_uri}' not found." end servlet, options, script_name, path_info = search_servlet(req.path) raise HTTPStatus::NotFound, "`#{req.path}' not found." unless servlet req.script_name = script_name req.path_info = path_info si = servlet.get_instance(self, *options) @logger.debug(format("%s is invoked.", si.class.name)) si.service(req, res) end
[ "def", "service", "(", "req", ",", "res", ")", "if", "req", ".", "unparsed_uri", "==", "\"*\"", "if", "req", ".", "request_method", "==", "\"OPTIONS\"", "do_OPTIONS", "(", "req", ",", "res", ")", "raise", "HTTPStatus", "::", "OK", "end", "raise", "HTTPStatus", "::", "NotFound", ",", "\"`#{req.unparsed_uri}' not found.\"", "end", "servlet", ",", "options", ",", "script_name", ",", "path_info", "=", "search_servlet", "(", "req", ".", "path", ")", "raise", "HTTPStatus", "::", "NotFound", ",", "\"`#{req.path}' not found.\"", "unless", "servlet", "req", ".", "script_name", "=", "script_name", "req", ".", "path_info", "=", "path_info", "si", "=", "servlet", ".", "get_instance", "(", "self", ",", "options", ")", "@logger", ".", "debug", "(", "format", "(", "\"%s is invoked.\"", ",", "si", ".", "class", ".", "name", ")", ")", "si", ".", "service", "(", "req", ",", "res", ")", "end" ]
Services +req+ and fills in +res+
[ "Services", "+", "req", "+", "and", "fills", "in", "+", "res", "+" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httpserver.rb#L123-L139
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httpserver.rb
WEBrick.HTTPServer.mount
def mount(dir, servlet, *options) @logger.debug(sprintf("%s is mounted on %s.", servlet.inspect, dir)) @mount_tab[dir] = [ servlet, options ] end
ruby
def mount(dir, servlet, *options) @logger.debug(sprintf("%s is mounted on %s.", servlet.inspect, dir)) @mount_tab[dir] = [ servlet, options ] end
[ "def", "mount", "(", "dir", ",", "servlet", ",", "*", "options", ")", "@logger", ".", "debug", "(", "sprintf", "(", "\"%s is mounted on %s.\"", ",", "servlet", ".", "inspect", ",", "dir", ")", ")", "@mount_tab", "[", "dir", "]", "=", "[", "servlet", ",", "options", "]", "end" ]
Mounts +servlet+ on +dir+ passing +options+ to the servlet at creation time
[ "Mounts", "+", "servlet", "+", "on", "+", "dir", "+", "passing", "+", "options", "+", "to", "the", "servlet", "at", "creation", "time" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httpserver.rb#L153-L156
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httpserver.rb
WEBrick.HTTPServer.search_servlet
def search_servlet(path) script_name, path_info = @mount_tab.scan(path) servlet, options = @mount_tab[script_name] if servlet [ servlet, options, script_name, path_info ] end end
ruby
def search_servlet(path) script_name, path_info = @mount_tab.scan(path) servlet, options = @mount_tab[script_name] if servlet [ servlet, options, script_name, path_info ] end end
[ "def", "search_servlet", "(", "path", ")", "script_name", ",", "path_info", "=", "@mount_tab", ".", "scan", "(", "path", ")", "servlet", ",", "options", "=", "@mount_tab", "[", "script_name", "]", "if", "servlet", "[", "servlet", ",", "options", ",", "script_name", ",", "path_info", "]", "end", "end" ]
Finds a servlet for +path+
[ "Finds", "a", "servlet", "for", "+", "path", "+" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httpserver.rb#L180-L186
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httpserver.rb
WEBrick.HTTPServer.virtual_host
def virtual_host(server) @virtual_hosts << server @virtual_hosts = @virtual_hosts.sort_by{|s| num = 0 num -= 4 if s[:BindAddress] num -= 2 if s[:Port] num -= 1 if s[:ServerName] num } end
ruby
def virtual_host(server) @virtual_hosts << server @virtual_hosts = @virtual_hosts.sort_by{|s| num = 0 num -= 4 if s[:BindAddress] num -= 2 if s[:Port] num -= 1 if s[:ServerName] num } end
[ "def", "virtual_host", "(", "server", ")", "@virtual_hosts", "<<", "server", "@virtual_hosts", "=", "@virtual_hosts", ".", "sort_by", "{", "|", "s", "|", "num", "=", "0", "num", "-=", "4", "if", "s", "[", ":BindAddress", "]", "num", "-=", "2", "if", "s", "[", ":Port", "]", "num", "-=", "1", "if", "s", "[", ":ServerName", "]", "num", "}", "end" ]
Adds +server+ as a virtual host.
[ "Adds", "+", "server", "+", "as", "a", "virtual", "host", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httpserver.rb#L191-L200
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httpserver.rb
WEBrick.HTTPServer.lookup_server
def lookup_server(req) @virtual_hosts.find{|s| (s[:BindAddress].nil? || req.addr[3] == s[:BindAddress]) && (s[:Port].nil? || req.port == s[:Port]) && ((s[:ServerName].nil? || req.host == s[:ServerName]) || (!s[:ServerAlias].nil? && s[:ServerAlias].find{|h| h === req.host})) } end
ruby
def lookup_server(req) @virtual_hosts.find{|s| (s[:BindAddress].nil? || req.addr[3] == s[:BindAddress]) && (s[:Port].nil? || req.port == s[:Port]) && ((s[:ServerName].nil? || req.host == s[:ServerName]) || (!s[:ServerAlias].nil? && s[:ServerAlias].find{|h| h === req.host})) } end
[ "def", "lookup_server", "(", "req", ")", "@virtual_hosts", ".", "find", "{", "|", "s", "|", "(", "s", "[", ":BindAddress", "]", ".", "nil?", "||", "req", ".", "addr", "[", "3", "]", "==", "s", "[", ":BindAddress", "]", ")", "&&", "(", "s", "[", ":Port", "]", ".", "nil?", "||", "req", ".", "port", "==", "s", "[", ":Port", "]", ")", "&&", "(", "(", "s", "[", ":ServerName", "]", ".", "nil?", "||", "req", ".", "host", "==", "s", "[", ":ServerName", "]", ")", "||", "(", "!", "s", "[", ":ServerAlias", "]", ".", "nil?", "&&", "s", "[", ":ServerAlias", "]", ".", "find", "{", "|", "h", "|", "h", "===", "req", ".", "host", "}", ")", ")", "}", "end" ]
Finds the appropriate virtual host to handle +req+
[ "Finds", "the", "appropriate", "virtual", "host", "to", "handle", "+", "req", "+" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httpserver.rb#L205-L212
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httpserver.rb
WEBrick.HTTPServer.access_log
def access_log(config, req, res) param = AccessLog::setup_params(config, req, res) @config[:AccessLog].each{|logger, fmt| logger << AccessLog::format(fmt+"\n", param) } end
ruby
def access_log(config, req, res) param = AccessLog::setup_params(config, req, res) @config[:AccessLog].each{|logger, fmt| logger << AccessLog::format(fmt+"\n", param) } end
[ "def", "access_log", "(", "config", ",", "req", ",", "res", ")", "param", "=", "AccessLog", "::", "setup_params", "(", "config", ",", "req", ",", "res", ")", "@config", "[", ":AccessLog", "]", ".", "each", "{", "|", "logger", ",", "fmt", "|", "logger", "<<", "AccessLog", "::", "format", "(", "fmt", "+", "\"\\n\"", ",", "param", ")", "}", "end" ]
Logs +req+ and +res+ in the access logs. +config+ is used for the server name.
[ "Logs", "+", "req", "+", "and", "+", "res", "+", "in", "the", "access", "logs", ".", "+", "config", "+", "is", "used", "for", "the", "server", "name", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/httpserver.rb#L218-L223
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/utils.rb
WEBrick.Utils.set_non_blocking
def set_non_blocking(io) flag = File::NONBLOCK if defined?(Fcntl::F_GETFL) flag |= io.fcntl(Fcntl::F_GETFL) end io.fcntl(Fcntl::F_SETFL, flag) end
ruby
def set_non_blocking(io) flag = File::NONBLOCK if defined?(Fcntl::F_GETFL) flag |= io.fcntl(Fcntl::F_GETFL) end io.fcntl(Fcntl::F_SETFL, flag) end
[ "def", "set_non_blocking", "(", "io", ")", "flag", "=", "File", "::", "NONBLOCK", "if", "defined?", "(", "Fcntl", "::", "F_GETFL", ")", "flag", "|=", "io", ".", "fcntl", "(", "Fcntl", "::", "F_GETFL", ")", "end", "io", ".", "fcntl", "(", "Fcntl", "::", "F_SETFL", ",", "flag", ")", "end" ]
Sets IO operations on +io+ to be non-blocking
[ "Sets", "IO", "operations", "on", "+", "io", "+", "to", "be", "non", "-", "blocking" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/utils.rb#L23-L29
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/utils.rb
WEBrick.Utils.set_close_on_exec
def set_close_on_exec(io) if defined?(Fcntl::FD_CLOEXEC) io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) end end
ruby
def set_close_on_exec(io) if defined?(Fcntl::FD_CLOEXEC) io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) end end
[ "def", "set_close_on_exec", "(", "io", ")", "if", "defined?", "(", "Fcntl", "::", "FD_CLOEXEC", ")", "io", ".", "fcntl", "(", "Fcntl", "::", "F_SETFD", ",", "Fcntl", "::", "FD_CLOEXEC", ")", "end", "end" ]
Sets the close on exec flag for +io+
[ "Sets", "the", "close", "on", "exec", "flag", "for", "+", "io", "+" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/utils.rb#L34-L38
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/utils.rb
WEBrick.Utils.su
def su(user) if defined?(Etc) pw = Etc.getpwnam(user) Process::initgroups(user, pw.gid) Process::Sys::setgid(pw.gid) Process::Sys::setuid(pw.uid) else warn("WEBrick::Utils::su doesn't work on this platform") end end
ruby
def su(user) if defined?(Etc) pw = Etc.getpwnam(user) Process::initgroups(user, pw.gid) Process::Sys::setgid(pw.gid) Process::Sys::setuid(pw.uid) else warn("WEBrick::Utils::su doesn't work on this platform") end end
[ "def", "su", "(", "user", ")", "if", "defined?", "(", "Etc", ")", "pw", "=", "Etc", ".", "getpwnam", "(", "user", ")", "Process", "::", "initgroups", "(", "user", ",", "pw", ".", "gid", ")", "Process", "::", "Sys", "::", "setgid", "(", "pw", ".", "gid", ")", "Process", "::", "Sys", "::", "setuid", "(", "pw", ".", "uid", ")", "else", "warn", "(", "\"WEBrick::Utils::su doesn't work on this platform\"", ")", "end", "end" ]
Changes the process's uid and gid to the ones of +user+
[ "Changes", "the", "process", "s", "uid", "and", "gid", "to", "the", "ones", "of", "+", "user", "+" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/utils.rb#L43-L52
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/utils.rb
WEBrick.Utils.random_string
def random_string(len) rand_max = RAND_CHARS.bytesize ret = "" len.times{ ret << RAND_CHARS[rand(rand_max)] } ret end
ruby
def random_string(len) rand_max = RAND_CHARS.bytesize ret = "" len.times{ ret << RAND_CHARS[rand(rand_max)] } ret end
[ "def", "random_string", "(", "len", ")", "rand_max", "=", "RAND_CHARS", ".", "bytesize", "ret", "=", "\"\"", "len", ".", "times", "{", "ret", "<<", "RAND_CHARS", "[", "rand", "(", "rand_max", ")", "]", "}", "ret", "end" ]
Generates a random string of length +len+
[ "Generates", "a", "random", "string", "of", "length", "+", "len", "+" ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/utils.rb#L92-L97
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/utils.rb
WEBrick.Utils.timeout
def timeout(seconds, exception=Timeout::Error) return yield if seconds.nil? or seconds.zero? # raise ThreadError, "timeout within critical session" if Thread.critical id = TimeoutHandler.register(seconds, exception) begin yield(seconds) ensure TimeoutHandler.cancel(id) end end
ruby
def timeout(seconds, exception=Timeout::Error) return yield if seconds.nil? or seconds.zero? # raise ThreadError, "timeout within critical session" if Thread.critical id = TimeoutHandler.register(seconds, exception) begin yield(seconds) ensure TimeoutHandler.cancel(id) end end
[ "def", "timeout", "(", "seconds", ",", "exception", "=", "Timeout", "::", "Error", ")", "return", "yield", "if", "seconds", ".", "nil?", "or", "seconds", ".", "zero?", "# raise ThreadError, \"timeout within critical session\" if Thread.critical", "id", "=", "TimeoutHandler", ".", "register", "(", "seconds", ",", "exception", ")", "begin", "yield", "(", "seconds", ")", "ensure", "TimeoutHandler", ".", "cancel", "(", "id", ")", "end", "end" ]
Executes the passed block and raises +exception+ if execution takes more than +seconds+. If +seconds+ is zero or nil, simply executes the block
[ "Executes", "the", "passed", "block", "and", "raises", "+", "exception", "+", "if", "execution", "takes", "more", "than", "+", "seconds", "+", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/utils.rb#L219-L228
train
rhomobile/rhodes
res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/rake/contrib/ftptools.rb
Rake.FtpUploader.makedirs
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 $stderr.puts "Creating Directory #{current_dir}" if @verbose @ftp.mkdir(current_dir) rescue nil end end end
ruby
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 $stderr.puts "Creating Directory #{current_dir}" if @verbose @ftp.mkdir(current_dir) rescue nil end end end
[ "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", "$stderr", ".", "puts", "\"Creating Directory #{current_dir}\"", "if", "@verbose", "@ftp", ".", "mkdir", "(", "current_dir", ")", "rescue", "nil", "end", "end", "end" ]
Create an FTP uploader targeting the directory +path+ on +host+ using the given account and password. +path+ will be the root path of the uploader. Create the directory +path+ in the uploader root path.
[ "Create", "an", "FTP", "uploader", "targeting", "the", "directory", "+", "path", "+", "on", "+", "host", "+", "using", "the", "given", "account", "and", "password", ".", "+", "path", "+", "will", "be", "the", "root", "path", "of", "the", "uploader", ".", "Create", "the", "directory", "+", "path", "+", "in", "the", "uploader", "root", "path", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/rake/contrib/ftptools.rb#L103-L114
train
rhomobile/rhodes
lib/extensions/digest/digest.rb
Digest.Instance.file
def file(name) File.open(name, "rb") {|f| buf = "" while f.read(16384, buf) update buf end } self end
ruby
def file(name) File.open(name, "rb") {|f| buf = "" while f.read(16384, buf) update buf end } self end
[ "def", "file", "(", "name", ")", "File", ".", "open", "(", "name", ",", "\"rb\"", ")", "{", "|", "f", "|", "buf", "=", "\"\"", "while", "f", ".", "read", "(", "16384", ",", "buf", ")", "update", "buf", "end", "}", "self", "end" ]
updates the digest with the contents of a given file _name_ and returns self.
[ "updates", "the", "digest", "with", "the", "contents", "of", "a", "given", "file", "_name_", "and", "returns", "self", "." ]
3c5f87b1a44f0ba2865ca0e1dd780dd202f64872
https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/extensions/digest/digest.rb#L36-L44
train
oauth-xx/oauth-ruby
lib/oauth/tokens/request_token.rb
OAuth.RequestToken.authorize_url
def authorize_url(params = nil) return nil if self.token.nil? params = (params || {}).merge(:oauth_token => self.token) build_authorize_url(consumer.authorize_url, params) end
ruby
def authorize_url(params = nil) return nil if self.token.nil? params = (params || {}).merge(:oauth_token => self.token) build_authorize_url(consumer.authorize_url, params) end
[ "def", "authorize_url", "(", "params", "=", "nil", ")", "return", "nil", "if", "self", ".", "token", ".", "nil?", "params", "=", "(", "params", "||", "{", "}", ")", ".", "merge", "(", ":oauth_token", "=>", "self", ".", "token", ")", "build_authorize_url", "(", "consumer", ".", "authorize_url", ",", "params", ")", "end" ]
Generate an authorization URL for user authorization
[ "Generate", "an", "authorization", "URL", "for", "user", "authorization" ]
cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14
https://github.com/oauth-xx/oauth-ruby/blob/cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14/lib/oauth/tokens/request_token.rb#L7-L12
train
oauth-xx/oauth-ruby
lib/oauth/tokens/request_token.rb
OAuth.RequestToken.get_access_token
def get_access_token(options = {}, *arguments) response = consumer.token_request(consumer.http_method, (consumer.access_token_url? ? consumer.access_token_url : consumer.access_token_path), self, options, *arguments) OAuth::AccessToken.from_hash(consumer, response) end
ruby
def get_access_token(options = {}, *arguments) response = consumer.token_request(consumer.http_method, (consumer.access_token_url? ? consumer.access_token_url : consumer.access_token_path), self, options, *arguments) OAuth::AccessToken.from_hash(consumer, response) end
[ "def", "get_access_token", "(", "options", "=", "{", "}", ",", "*", "arguments", ")", "response", "=", "consumer", ".", "token_request", "(", "consumer", ".", "http_method", ",", "(", "consumer", ".", "access_token_url?", "?", "consumer", ".", "access_token_url", ":", "consumer", ".", "access_token_path", ")", ",", "self", ",", "options", ",", "arguments", ")", "OAuth", "::", "AccessToken", ".", "from_hash", "(", "consumer", ",", "response", ")", "end" ]
exchange for AccessToken on server
[ "exchange", "for", "AccessToken", "on", "server" ]
cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14
https://github.com/oauth-xx/oauth-ruby/blob/cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14/lib/oauth/tokens/request_token.rb#L19-L22
train
oauth-xx/oauth-ruby
lib/oauth/tokens/request_token.rb
OAuth.RequestToken.build_authorize_url
def build_authorize_url(base_url, params) uri = URI.parse(base_url.to_s) queries = {} queries = Hash[URI.decode_www_form(uri.query)] if uri.query # TODO doesn't handle array values correctly queries.merge!(params) if params uri.query = URI.encode_www_form(queries) if !queries.empty? uri.to_s end
ruby
def build_authorize_url(base_url, params) uri = URI.parse(base_url.to_s) queries = {} queries = Hash[URI.decode_www_form(uri.query)] if uri.query # TODO doesn't handle array values correctly queries.merge!(params) if params uri.query = URI.encode_www_form(queries) if !queries.empty? uri.to_s end
[ "def", "build_authorize_url", "(", "base_url", ",", "params", ")", "uri", "=", "URI", ".", "parse", "(", "base_url", ".", "to_s", ")", "queries", "=", "{", "}", "queries", "=", "Hash", "[", "URI", ".", "decode_www_form", "(", "uri", ".", "query", ")", "]", "if", "uri", ".", "query", "# TODO doesn't handle array values correctly", "queries", ".", "merge!", "(", "params", ")", "if", "params", "uri", ".", "query", "=", "URI", ".", "encode_www_form", "(", "queries", ")", "if", "!", "queries", ".", "empty?", "uri", ".", "to_s", "end" ]
construct an authorization url
[ "construct", "an", "authorization", "url" ]
cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14
https://github.com/oauth-xx/oauth-ruby/blob/cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14/lib/oauth/tokens/request_token.rb#L27-L35
train
oauth-xx/oauth-ruby
lib/oauth/request_proxy/base.rb
OAuth::RequestProxy.Base.signature_base_string
def signature_base_string base = [method, normalized_uri, normalized_parameters] base.map { |v| escape(v) }.join("&") end
ruby
def signature_base_string base = [method, normalized_uri, normalized_parameters] base.map { |v| escape(v) }.join("&") end
[ "def", "signature_base_string", "base", "=", "[", "method", ",", "normalized_uri", ",", "normalized_parameters", "]", "base", ".", "map", "{", "|", "v", "|", "escape", "(", "v", ")", "}", ".", "join", "(", "\"&\"", ")", "end" ]
See 9.1 in specs
[ "See", "9", ".", "1", "in", "specs" ]
cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14
https://github.com/oauth-xx/oauth-ruby/blob/cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14/lib/oauth/request_proxy/base.rb#L116-L119
train
oauth-xx/oauth-ruby
lib/oauth/request_proxy/base.rb
OAuth::RequestProxy.Base.signed_uri
def signed_uri(with_oauth = true) if signed? if with_oauth params = parameters else params = non_oauth_parameters end [uri, normalize(params)] * "?" else STDERR.puts "This request has not yet been signed!" end end
ruby
def signed_uri(with_oauth = true) if signed? if with_oauth params = parameters else params = non_oauth_parameters end [uri, normalize(params)] * "?" else STDERR.puts "This request has not yet been signed!" end end
[ "def", "signed_uri", "(", "with_oauth", "=", "true", ")", "if", "signed?", "if", "with_oauth", "params", "=", "parameters", "else", "params", "=", "non_oauth_parameters", "end", "[", "uri", ",", "normalize", "(", "params", ")", "]", "*", "\"?\"", "else", "STDERR", ".", "puts", "\"This request has not yet been signed!\"", "end", "end" ]
URI, including OAuth parameters
[ "URI", "including", "OAuth", "parameters" ]
cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14
https://github.com/oauth-xx/oauth-ruby/blob/cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14/lib/oauth/request_proxy/base.rb#L127-L139
train
oauth-xx/oauth-ruby
lib/oauth/request_proxy/base.rb
OAuth::RequestProxy.Base.oauth_header
def oauth_header(options = {}) header_params_str = oauth_parameters.map { |k,v| "#{k}=\"#{escape(v)}\"" }.join(', ') realm = "realm=\"#{options[:realm]}\", " if options[:realm] "OAuth #{realm}#{header_params_str}" end
ruby
def oauth_header(options = {}) header_params_str = oauth_parameters.map { |k,v| "#{k}=\"#{escape(v)}\"" }.join(', ') realm = "realm=\"#{options[:realm]}\", " if options[:realm] "OAuth #{realm}#{header_params_str}" end
[ "def", "oauth_header", "(", "options", "=", "{", "}", ")", "header_params_str", "=", "oauth_parameters", ".", "map", "{", "|", "k", ",", "v", "|", "\"#{k}=\\\"#{escape(v)}\\\"\"", "}", ".", "join", "(", "', '", ")", "realm", "=", "\"realm=\\\"#{options[:realm]}\\\", \"", "if", "options", "[", ":realm", "]", "\"OAuth #{realm}#{header_params_str}\"", "end" ]
Authorization header for OAuth
[ "Authorization", "header", "for", "OAuth" ]
cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14
https://github.com/oauth-xx/oauth-ruby/blob/cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14/lib/oauth/request_proxy/base.rb#L142-L147
train
oauth-xx/oauth-ruby
lib/oauth/consumer.rb
OAuth.Consumer.create_signed_request
def create_signed_request(http_method, path, token = nil, request_options = {}, *arguments) request = create_http_request(http_method, path, *arguments) sign!(request, token, request_options) request end
ruby
def create_signed_request(http_method, path, token = nil, request_options = {}, *arguments) request = create_http_request(http_method, path, *arguments) sign!(request, token, request_options) request end
[ "def", "create_signed_request", "(", "http_method", ",", "path", ",", "token", "=", "nil", ",", "request_options", "=", "{", "}", ",", "*", "arguments", ")", "request", "=", "create_http_request", "(", "http_method", ",", "path", ",", "arguments", ")", "sign!", "(", "request", ",", "token", ",", "request_options", ")", "request", "end" ]
Creates and signs an http request. It's recommended to use the Token classes to set this up correctly
[ "Creates", "and", "signs", "an", "http", "request", ".", "It", "s", "recommended", "to", "use", "the", "Token", "classes", "to", "set", "this", "up", "correctly" ]
cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14
https://github.com/oauth-xx/oauth-ruby/blob/cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14/lib/oauth/consumer.rb#L205-L209
train
oauth-xx/oauth-ruby
lib/oauth/consumer.rb
OAuth.Consumer.token_request
def token_request(http_method, path, token = nil, request_options = {}, *arguments) request_options[:token_request] ||= true response = request(http_method, path, token, request_options, *arguments) case response.code.to_i when (200..299) if block_given? yield response.body else # symbolize keys # TODO this could be considered unexpected behavior; symbols or not? # TODO this also drops subsequent values from multi-valued keys CGI.parse(response.body).inject({}) do |h,(k,v)| h[k.strip.to_sym] = v.first h[k.strip] = v.first h end end when (300..399) # this is a redirect uri = URI.parse(response['location']) response.error! if uri.path == path # careful of those infinite redirects self.token_request(http_method, uri.path, token, request_options, arguments) when (400..499) raise OAuth::Unauthorized, response else response.error! end end
ruby
def token_request(http_method, path, token = nil, request_options = {}, *arguments) request_options[:token_request] ||= true response = request(http_method, path, token, request_options, *arguments) case response.code.to_i when (200..299) if block_given? yield response.body else # symbolize keys # TODO this could be considered unexpected behavior; symbols or not? # TODO this also drops subsequent values from multi-valued keys CGI.parse(response.body).inject({}) do |h,(k,v)| h[k.strip.to_sym] = v.first h[k.strip] = v.first h end end when (300..399) # this is a redirect uri = URI.parse(response['location']) response.error! if uri.path == path # careful of those infinite redirects self.token_request(http_method, uri.path, token, request_options, arguments) when (400..499) raise OAuth::Unauthorized, response else response.error! end end
[ "def", "token_request", "(", "http_method", ",", "path", ",", "token", "=", "nil", ",", "request_options", "=", "{", "}", ",", "*", "arguments", ")", "request_options", "[", ":token_request", "]", "||=", "true", "response", "=", "request", "(", "http_method", ",", "path", ",", "token", ",", "request_options", ",", "arguments", ")", "case", "response", ".", "code", ".", "to_i", "when", "(", "200", "..", "299", ")", "if", "block_given?", "yield", "response", ".", "body", "else", "# symbolize keys", "# TODO this could be considered unexpected behavior; symbols or not?", "# TODO this also drops subsequent values from multi-valued keys", "CGI", ".", "parse", "(", "response", ".", "body", ")", ".", "inject", "(", "{", "}", ")", "do", "|", "h", ",", "(", "k", ",", "v", ")", "|", "h", "[", "k", ".", "strip", ".", "to_sym", "]", "=", "v", ".", "first", "h", "[", "k", ".", "strip", "]", "=", "v", ".", "first", "h", "end", "end", "when", "(", "300", "..", "399", ")", "# this is a redirect", "uri", "=", "URI", ".", "parse", "(", "response", "[", "'location'", "]", ")", "response", ".", "error!", "if", "uri", ".", "path", "==", "path", "# careful of those infinite redirects", "self", ".", "token_request", "(", "http_method", ",", "uri", ".", "path", ",", "token", ",", "request_options", ",", "arguments", ")", "when", "(", "400", "..", "499", ")", "raise", "OAuth", "::", "Unauthorized", ",", "response", "else", "response", ".", "error!", "end", "end" ]
Creates a request and parses the result as url_encoded. This is used internally for the RequestToken and AccessToken requests.
[ "Creates", "a", "request", "and", "parses", "the", "result", "as", "url_encoded", ".", "This", "is", "used", "internally", "for", "the", "RequestToken", "and", "AccessToken", "requests", "." ]
cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14
https://github.com/oauth-xx/oauth-ruby/blob/cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14/lib/oauth/consumer.rb#L212-L240
train
oauth-xx/oauth-ruby
lib/oauth/consumer.rb
OAuth.Consumer.sign!
def sign!(request, token = nil, request_options = {}) request.oauth!(http, self, token, options.merge(request_options)) end
ruby
def sign!(request, token = nil, request_options = {}) request.oauth!(http, self, token, options.merge(request_options)) end
[ "def", "sign!", "(", "request", ",", "token", "=", "nil", ",", "request_options", "=", "{", "}", ")", "request", ".", "oauth!", "(", "http", ",", "self", ",", "token", ",", "options", ".", "merge", "(", "request_options", ")", ")", "end" ]
Sign the Request object. Use this if you have an externally generated http request object you want to sign.
[ "Sign", "the", "Request", "object", ".", "Use", "this", "if", "you", "have", "an", "externally", "generated", "http", "request", "object", "you", "want", "to", "sign", "." ]
cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14
https://github.com/oauth-xx/oauth-ruby/blob/cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14/lib/oauth/consumer.rb#L243-L245
train
oauth-xx/oauth-ruby
lib/oauth/consumer.rb
OAuth.Consumer.signature_base_string
def signature_base_string(request, token = nil, request_options = {}) request.signature_base_string(http, self, token, options.merge(request_options)) end
ruby
def signature_base_string(request, token = nil, request_options = {}) request.signature_base_string(http, self, token, options.merge(request_options)) end
[ "def", "signature_base_string", "(", "request", ",", "token", "=", "nil", ",", "request_options", "=", "{", "}", ")", "request", ".", "signature_base_string", "(", "http", ",", "self", ",", "token", ",", "options", ".", "merge", "(", "request_options", ")", ")", "end" ]
Return the signature_base_string
[ "Return", "the", "signature_base_string" ]
cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14
https://github.com/oauth-xx/oauth-ruby/blob/cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14/lib/oauth/consumer.rb#L248-L250
train
oauth-xx/oauth-ruby
lib/oauth/consumer.rb
OAuth.Consumer.create_http_request
def create_http_request(http_method, path, *arguments) http_method = http_method.to_sym if [:post, :put, :patch].include?(http_method) data = arguments.shift end # if the base site contains a path, add it now # only add if the site host matches the current http object's host # (in case we've specified a full url for token requests) uri = URI.parse(site) path = uri.path + path if uri.path && uri.path != '/' && uri.host == http.address headers = arguments.first.is_a?(Hash) ? arguments.shift : {} case http_method when :post request = Net::HTTP::Post.new(path,headers) request["Content-Length"] = '0' # Default to 0 when :put request = Net::HTTP::Put.new(path,headers) request["Content-Length"] = '0' # Default to 0 when :patch request = Net::HTTP::Patch.new(path,headers) request["Content-Length"] = '0' # Default to 0 when :get request = Net::HTTP::Get.new(path,headers) when :delete request = Net::HTTP::Delete.new(path,headers) when :head request = Net::HTTP::Head.new(path,headers) else raise ArgumentError, "Don't know how to handle http_method: :#{http_method.to_s}" end if data.is_a?(Hash) request.body = OAuth::Helper.normalize(data) request.content_type = 'application/x-www-form-urlencoded' elsif data if data.respond_to?(:read) request.body_stream = data if data.respond_to?(:length) request["Content-Length"] = data.length.to_s elsif data.respond_to?(:stat) && data.stat.respond_to?(:size) request["Content-Length"] = data.stat.size.to_s else raise ArgumentError, "Don't know how to send a body_stream that doesn't respond to .length or .stat.size" end else request.body = data.to_s request["Content-Length"] = request.body.length.to_s end end request end
ruby
def create_http_request(http_method, path, *arguments) http_method = http_method.to_sym if [:post, :put, :patch].include?(http_method) data = arguments.shift end # if the base site contains a path, add it now # only add if the site host matches the current http object's host # (in case we've specified a full url for token requests) uri = URI.parse(site) path = uri.path + path if uri.path && uri.path != '/' && uri.host == http.address headers = arguments.first.is_a?(Hash) ? arguments.shift : {} case http_method when :post request = Net::HTTP::Post.new(path,headers) request["Content-Length"] = '0' # Default to 0 when :put request = Net::HTTP::Put.new(path,headers) request["Content-Length"] = '0' # Default to 0 when :patch request = Net::HTTP::Patch.new(path,headers) request["Content-Length"] = '0' # Default to 0 when :get request = Net::HTTP::Get.new(path,headers) when :delete request = Net::HTTP::Delete.new(path,headers) when :head request = Net::HTTP::Head.new(path,headers) else raise ArgumentError, "Don't know how to handle http_method: :#{http_method.to_s}" end if data.is_a?(Hash) request.body = OAuth::Helper.normalize(data) request.content_type = 'application/x-www-form-urlencoded' elsif data if data.respond_to?(:read) request.body_stream = data if data.respond_to?(:length) request["Content-Length"] = data.length.to_s elsif data.respond_to?(:stat) && data.stat.respond_to?(:size) request["Content-Length"] = data.stat.size.to_s else raise ArgumentError, "Don't know how to send a body_stream that doesn't respond to .length or .stat.size" end else request.body = data.to_s request["Content-Length"] = request.body.length.to_s end end request end
[ "def", "create_http_request", "(", "http_method", ",", "path", ",", "*", "arguments", ")", "http_method", "=", "http_method", ".", "to_sym", "if", "[", ":post", ",", ":put", ",", ":patch", "]", ".", "include?", "(", "http_method", ")", "data", "=", "arguments", ".", "shift", "end", "# if the base site contains a path, add it now", "# only add if the site host matches the current http object's host", "# (in case we've specified a full url for token requests)", "uri", "=", "URI", ".", "parse", "(", "site", ")", "path", "=", "uri", ".", "path", "+", "path", "if", "uri", ".", "path", "&&", "uri", ".", "path", "!=", "'/'", "&&", "uri", ".", "host", "==", "http", ".", "address", "headers", "=", "arguments", ".", "first", ".", "is_a?", "(", "Hash", ")", "?", "arguments", ".", "shift", ":", "{", "}", "case", "http_method", "when", ":post", "request", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "path", ",", "headers", ")", "request", "[", "\"Content-Length\"", "]", "=", "'0'", "# Default to 0", "when", ":put", "request", "=", "Net", "::", "HTTP", "::", "Put", ".", "new", "(", "path", ",", "headers", ")", "request", "[", "\"Content-Length\"", "]", "=", "'0'", "# Default to 0", "when", ":patch", "request", "=", "Net", "::", "HTTP", "::", "Patch", ".", "new", "(", "path", ",", "headers", ")", "request", "[", "\"Content-Length\"", "]", "=", "'0'", "# Default to 0", "when", ":get", "request", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "path", ",", "headers", ")", "when", ":delete", "request", "=", "Net", "::", "HTTP", "::", "Delete", ".", "new", "(", "path", ",", "headers", ")", "when", ":head", "request", "=", "Net", "::", "HTTP", "::", "Head", ".", "new", "(", "path", ",", "headers", ")", "else", "raise", "ArgumentError", ",", "\"Don't know how to handle http_method: :#{http_method.to_s}\"", "end", "if", "data", ".", "is_a?", "(", "Hash", ")", "request", ".", "body", "=", "OAuth", "::", "Helper", ".", "normalize", "(", "data", ")", "request", ".", "content_type", "=", "'application/x-www-form-urlencoded'", "elsif", "data", "if", "data", ".", "respond_to?", "(", ":read", ")", "request", ".", "body_stream", "=", "data", "if", "data", ".", "respond_to?", "(", ":length", ")", "request", "[", "\"Content-Length\"", "]", "=", "data", ".", "length", ".", "to_s", "elsif", "data", ".", "respond_to?", "(", ":stat", ")", "&&", "data", ".", "stat", ".", "respond_to?", "(", ":size", ")", "request", "[", "\"Content-Length\"", "]", "=", "data", ".", "stat", ".", "size", ".", "to_s", "else", "raise", "ArgumentError", ",", "\"Don't know how to send a body_stream that doesn't respond to .length or .stat.size\"", "end", "else", "request", ".", "body", "=", "data", ".", "to_s", "request", "[", "\"Content-Length\"", "]", "=", "request", ".", "body", ".", "length", ".", "to_s", "end", "end", "request", "end" ]
create the http request object for a given http_method and path
[ "create", "the", "http", "request", "object", "for", "a", "given", "http_method", "and", "path" ]
cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14
https://github.com/oauth-xx/oauth-ruby/blob/cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14/lib/oauth/consumer.rb#L350-L405
train
oauth-xx/oauth-ruby
lib/oauth/helper.rb
OAuth.Helper.escape
def escape(value) _escape(value.to_s.to_str) rescue ArgumentError _escape(value.to_s.to_str.force_encoding(Encoding::UTF_8)) end
ruby
def escape(value) _escape(value.to_s.to_str) rescue ArgumentError _escape(value.to_s.to_str.force_encoding(Encoding::UTF_8)) end
[ "def", "escape", "(", "value", ")", "_escape", "(", "value", ".", "to_s", ".", "to_str", ")", "rescue", "ArgumentError", "_escape", "(", "value", ".", "to_s", ".", "to_str", ".", "force_encoding", "(", "Encoding", "::", "UTF_8", ")", ")", "end" ]
Escape +value+ by URL encoding all non-reserved character. See Also: {OAuth core spec version 1.0, section 5.1}[http://oauth.net/core/1.0#rfc.section.5.1]
[ "Escape", "+", "value", "+", "by", "URL", "encoding", "all", "non", "-", "reserved", "character", "." ]
cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14
https://github.com/oauth-xx/oauth-ruby/blob/cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14/lib/oauth/helper.rb#L11-L15
train
oauth-xx/oauth-ruby
lib/oauth/helper.rb
OAuth.Helper.normalize
def normalize(params) params.sort.map do |k, values| if values.is_a?(Array) # make sure the array has an element so we don't lose the key values << nil if values.empty? # multiple values were provided for a single key values.sort.collect do |v| [escape(k),escape(v)] * "=" end elsif values.is_a?(Hash) normalize_nested_query(values, k) else [escape(k),escape(values)] * "=" end end * "&" end
ruby
def normalize(params) params.sort.map do |k, values| if values.is_a?(Array) # make sure the array has an element so we don't lose the key values << nil if values.empty? # multiple values were provided for a single key values.sort.collect do |v| [escape(k),escape(v)] * "=" end elsif values.is_a?(Hash) normalize_nested_query(values, k) else [escape(k),escape(values)] * "=" end end * "&" end
[ "def", "normalize", "(", "params", ")", "params", ".", "sort", ".", "map", "do", "|", "k", ",", "values", "|", "if", "values", ".", "is_a?", "(", "Array", ")", "# make sure the array has an element so we don't lose the key", "values", "<<", "nil", "if", "values", ".", "empty?", "# multiple values were provided for a single key", "values", ".", "sort", ".", "collect", "do", "|", "v", "|", "[", "escape", "(", "k", ")", ",", "escape", "(", "v", ")", "]", "*", "\"=\"", "end", "elsif", "values", ".", "is_a?", "(", "Hash", ")", "normalize_nested_query", "(", "values", ",", "k", ")", "else", "[", "escape", "(", "k", ")", ",", "escape", "(", "values", ")", "]", "*", "\"=\"", "end", "end", "*", "\"&\"", "end" ]
Normalize a +Hash+ of parameter values. Parameters are sorted by name, using lexicographical byte value ordering. If two or more parameters share the same name, they are sorted by their value. Parameters are concatenated in their sorted order into a single string. For each parameter, the name is separated from the corresponding value by an "=" character, even if the value is empty. Each name-value pair is separated by an "&" character. See Also: {OAuth core spec version 1.0, section 9.1.1}[http://oauth.net/core/1.0#rfc.section.9.1.1]
[ "Normalize", "a", "+", "Hash", "+", "of", "parameter", "values", ".", "Parameters", "are", "sorted", "by", "name", "using", "lexicographical", "byte", "value", "ordering", ".", "If", "two", "or", "more", "parameters", "share", "the", "same", "name", "they", "are", "sorted", "by", "their", "value", ".", "Parameters", "are", "concatenated", "in", "their", "sorted", "order", "into", "a", "single", "string", ".", "For", "each", "parameter", "the", "name", "is", "separated", "from", "the", "corresponding", "value", "by", "an", "=", "character", "even", "if", "the", "value", "is", "empty", ".", "Each", "name", "-", "value", "pair", "is", "separated", "by", "an", "&", "character", "." ]
cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14
https://github.com/oauth-xx/oauth-ruby/blob/cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14/lib/oauth/helper.rb#L44-L59
train
oauth-xx/oauth-ruby
lib/oauth/server.rb
OAuth.Server.create_consumer
def create_consumer creds = generate_credentials Consumer.new(creds[0], creds[1], { :site => base_url, :request_token_path => request_token_path, :authorize_path => authorize_path, :access_token_path => access_token_path }) end
ruby
def create_consumer creds = generate_credentials Consumer.new(creds[0], creds[1], { :site => base_url, :request_token_path => request_token_path, :authorize_path => authorize_path, :access_token_path => access_token_path }) end
[ "def", "create_consumer", "creds", "=", "generate_credentials", "Consumer", ".", "new", "(", "creds", "[", "0", "]", ",", "creds", "[", "1", "]", ",", "{", ":site", "=>", "base_url", ",", ":request_token_path", "=>", "request_token_path", ",", ":authorize_path", "=>", "authorize_path", ",", ":access_token_path", "=>", "access_token_path", "}", ")", "end" ]
mainly for testing purposes
[ "mainly", "for", "testing", "purposes" ]
cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14
https://github.com/oauth-xx/oauth-ruby/blob/cb9b9db64f520dc0ee87fe6e4fe82a7601cffb14/lib/oauth/server.rb#L31-L40
train
graylog-labs/gelf-rb
lib/gelf/notifier.rb
GELF.Notifier.convert_hoptoad_keys_to_graylog2
def convert_hoptoad_keys_to_graylog2(hash) if hash['short_message'].to_s.empty? if hash.has_key?('error_class') && hash.has_key?('error_message') hash['short_message'] = hash.delete('error_class') + ': ' + hash.delete('error_message') end end end
ruby
def convert_hoptoad_keys_to_graylog2(hash) if hash['short_message'].to_s.empty? if hash.has_key?('error_class') && hash.has_key?('error_message') hash['short_message'] = hash.delete('error_class') + ': ' + hash.delete('error_message') end end end
[ "def", "convert_hoptoad_keys_to_graylog2", "(", "hash", ")", "if", "hash", "[", "'short_message'", "]", ".", "to_s", ".", "empty?", "if", "hash", ".", "has_key?", "(", "'error_class'", ")", "&&", "hash", ".", "has_key?", "(", "'error_message'", ")", "hash", "[", "'short_message'", "]", "=", "hash", ".", "delete", "(", "'error_class'", ")", "+", "': '", "+", "hash", ".", "delete", "(", "'error_message'", ")", "end", "end", "end" ]
Converts Hoptoad-specific keys in +@hash+ to Graylog2-specific.
[ "Converts", "Hoptoad", "-", "specific", "keys", "in", "+" ]
eb2d31cdc4b37c316de880122279bcac52a08ba2
https://github.com/graylog-labs/gelf-rb/blob/eb2d31cdc4b37c316de880122279bcac52a08ba2/lib/gelf/notifier.rb#L201-L207
train
lassebunk/gretel
lib/gretel/crumb.rb
Gretel.Crumb.parent
def parent(*args) return @parent if args.empty? key = args.shift @parent = Gretel::Crumb.new(context, key, *args) end
ruby
def parent(*args) return @parent if args.empty? key = args.shift @parent = Gretel::Crumb.new(context, key, *args) end
[ "def", "parent", "(", "*", "args", ")", "return", "@parent", "if", "args", ".", "empty?", "key", "=", "args", ".", "shift", "@parent", "=", "Gretel", "::", "Crumb", ".", "new", "(", "context", ",", "key", ",", "args", ")", "end" ]
Sets or gets the parent breadcrumb. If you supply a parent key and optional arguments, it will set the parent. If nothing is supplied, it will return the parent, if this has been set. Example: parent :category, category Or short, which will infer the key from the model's `model_name`: parent category
[ "Sets", "or", "gets", "the", "parent", "breadcrumb", ".", "If", "you", "supply", "a", "parent", "key", "and", "optional", "arguments", "it", "will", "set", "the", "parent", ".", "If", "nothing", "is", "supplied", "it", "will", "return", "the", "parent", "if", "this", "has", "been", "set", "." ]
a3b0c99c59571ca091dce15c61a80a71addc091a
https://github.com/lassebunk/gretel/blob/a3b0c99c59571ca091dce15c61a80a71addc091a/lib/gretel/crumb.rb#L50-L55
train
lassebunk/gretel
lib/gretel/link.rb
Gretel.Link.method_missing
def method_missing(method, *args, &block) if method =~ /(.+)\?$/ options[$1.to_sym].present? else options[method] end end
ruby
def method_missing(method, *args, &block) if method =~ /(.+)\?$/ options[$1.to_sym].present? else options[method] end end
[ "def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "if", "method", "=~", "/", "\\?", "/", "options", "[", "$1", ".", "to_sym", "]", ".", "present?", "else", "options", "[", "method", "]", "end", "end" ]
Enables accessors and predicate methods for values in the +options+ hash. This can be used to pass information to links when rendering breadcrumbs manually. link = Link.new(:my_crumb, "My Crumb", my_path, title: "Test Title", other_value: "Other") link.title? # => true link.title # => "Test Title" link.other_value? # => true link.other_value # => "Other" link.some_other? # => false link.some_other # => nil
[ "Enables", "accessors", "and", "predicate", "methods", "for", "values", "in", "the", "+", "options", "+", "hash", ".", "This", "can", "be", "used", "to", "pass", "information", "to", "links", "when", "rendering", "breadcrumbs", "manually", "." ]
a3b0c99c59571ca091dce15c61a80a71addc091a
https://github.com/lassebunk/gretel/blob/a3b0c99c59571ca091dce15c61a80a71addc091a/lib/gretel/link.rb#L31-L37
train
lassebunk/gretel
lib/gretel/view_helpers.rb
Gretel.ViewHelpers.with_breadcrumb
def with_breadcrumb(key, *args, &block) original_renderer = @_gretel_renderer @_gretel_renderer = Gretel::Renderer.new(self, key, *args) yield @_gretel_renderer = original_renderer end
ruby
def with_breadcrumb(key, *args, &block) original_renderer = @_gretel_renderer @_gretel_renderer = Gretel::Renderer.new(self, key, *args) yield @_gretel_renderer = original_renderer end
[ "def", "with_breadcrumb", "(", "key", ",", "*", "args", ",", "&", "block", ")", "original_renderer", "=", "@_gretel_renderer", "@_gretel_renderer", "=", "Gretel", "::", "Renderer", ".", "new", "(", "self", ",", "key", ",", "args", ")", "yield", "@_gretel_renderer", "=", "original_renderer", "end" ]
Yields a block where inside the block you have a different breadcrumb than outside. <% breadcrumb :about %> <%= breadcrumbs # shows the :about breadcrumb %> <% with_breadcrumb :product, Product.first do %> <%= breadcrumbs # shows the :product breadcrumb %> <% end %> <%= breadcrumbs # shows the :about breadcrumb %>
[ "Yields", "a", "block", "where", "inside", "the", "block", "you", "have", "a", "different", "breadcrumb", "than", "outside", "." ]
a3b0c99c59571ca091dce15c61a80a71addc091a
https://github.com/lassebunk/gretel/blob/a3b0c99c59571ca091dce15c61a80a71addc091a/lib/gretel/view_helpers.rb#L28-L33
train
lassebunk/gretel
lib/gretel/renderer.rb
Gretel.Renderer.render
def render(options) options = options_for_render(options) links = links_for_render(options) LinkCollection.new(context, links, options) end
ruby
def render(options) options = options_for_render(options) links = links_for_render(options) LinkCollection.new(context, links, options) end
[ "def", "render", "(", "options", ")", "options", "=", "options_for_render", "(", "options", ")", "links", "=", "links_for_render", "(", "options", ")", "LinkCollection", ".", "new", "(", "context", ",", "links", ",", "options", ")", "end" ]
Renders the breadcrumbs HTML.
[ "Renders", "the", "breadcrumbs", "HTML", "." ]
a3b0c99c59571ca091dce15c61a80a71addc091a
https://github.com/lassebunk/gretel/blob/a3b0c99c59571ca091dce15c61a80a71addc091a/lib/gretel/renderer.rb#L35-L40
train
lassebunk/gretel
lib/gretel/renderer.rb
Gretel.Renderer.options_for_render
def options_for_render(options = {}) style = options_for_style(options[:style] || DEFAULT_OPTIONS[:style]) DEFAULT_OPTIONS.merge(style).merge(options) end
ruby
def options_for_render(options = {}) style = options_for_style(options[:style] || DEFAULT_OPTIONS[:style]) DEFAULT_OPTIONS.merge(style).merge(options) end
[ "def", "options_for_render", "(", "options", "=", "{", "}", ")", "style", "=", "options_for_style", "(", "options", "[", ":style", "]", "||", "DEFAULT_OPTIONS", "[", ":style", "]", ")", "DEFAULT_OPTIONS", ".", "merge", "(", "style", ")", ".", "merge", "(", "options", ")", "end" ]
Returns merged options for rendering breadcrumbs.
[ "Returns", "merged", "options", "for", "rendering", "breadcrumbs", "." ]
a3b0c99c59571ca091dce15c61a80a71addc091a
https://github.com/lassebunk/gretel/blob/a3b0c99c59571ca091dce15c61a80a71addc091a/lib/gretel/renderer.rb#L64-L67
train
lassebunk/gretel
lib/gretel/renderer.rb
Gretel.Renderer.links_for_render
def links_for_render(options = {}) out = links.dup # Handle autoroot if options[:autoroot] && out.map(&:key).exclude?(:root) && Gretel::Crumbs.crumb_defined?(:root) out.unshift *Gretel::Crumb.new(context, :root).links end # Set current link to actual path if options[:link_current_to_request_path] && out.any? && request out.last.url = request.fullpath end # Handle show root alone if out.size == 1 && !options[:display_single_fragment] out.shift end # Set last link to current out.last.try(:current!) out end
ruby
def links_for_render(options = {}) out = links.dup # Handle autoroot if options[:autoroot] && out.map(&:key).exclude?(:root) && Gretel::Crumbs.crumb_defined?(:root) out.unshift *Gretel::Crumb.new(context, :root).links end # Set current link to actual path if options[:link_current_to_request_path] && out.any? && request out.last.url = request.fullpath end # Handle show root alone if out.size == 1 && !options[:display_single_fragment] out.shift end # Set last link to current out.last.try(:current!) out end
[ "def", "links_for_render", "(", "options", "=", "{", "}", ")", "out", "=", "links", ".", "dup", "# Handle autoroot", "if", "options", "[", ":autoroot", "]", "&&", "out", ".", "map", "(", ":key", ")", ".", "exclude?", "(", ":root", ")", "&&", "Gretel", "::", "Crumbs", ".", "crumb_defined?", "(", ":root", ")", "out", ".", "unshift", "Gretel", "::", "Crumb", ".", "new", "(", "context", ",", ":root", ")", ".", "links", "end", "# Set current link to actual path", "if", "options", "[", ":link_current_to_request_path", "]", "&&", "out", ".", "any?", "&&", "request", "out", ".", "last", ".", "url", "=", "request", ".", "fullpath", "end", "# Handle show root alone", "if", "out", ".", "size", "==", "1", "&&", "!", "options", "[", ":display_single_fragment", "]", "out", ".", "shift", "end", "# Set last link to current", "out", ".", "last", ".", "try", "(", ":current!", ")", "out", "end" ]
Array of links with applied options.
[ "Array", "of", "links", "with", "applied", "options", "." ]
a3b0c99c59571ca091dce15c61a80a71addc091a
https://github.com/lassebunk/gretel/blob/a3b0c99c59571ca091dce15c61a80a71addc091a/lib/gretel/renderer.rb#L79-L101
train
lassebunk/gretel
lib/gretel/renderer.rb
Gretel.Renderer.links
def links @links ||= if @breadcrumb_key.present? # Reload breadcrumbs configuration if needed Gretel::Crumbs.reload_if_needed # Get breadcrumb set by the `breadcrumb` method crumb = Gretel::Crumb.new(context, breadcrumb_key, *breadcrumb_args) # Links of first crumb links = crumb.links.dup # Get parent links links.unshift *parent_links_for(crumb) links else [] end end
ruby
def links @links ||= if @breadcrumb_key.present? # Reload breadcrumbs configuration if needed Gretel::Crumbs.reload_if_needed # Get breadcrumb set by the `breadcrumb` method crumb = Gretel::Crumb.new(context, breadcrumb_key, *breadcrumb_args) # Links of first crumb links = crumb.links.dup # Get parent links links.unshift *parent_links_for(crumb) links else [] end end
[ "def", "links", "@links", "||=", "if", "@breadcrumb_key", ".", "present?", "# Reload breadcrumbs configuration if needed", "Gretel", "::", "Crumbs", ".", "reload_if_needed", "# Get breadcrumb set by the `breadcrumb` method", "crumb", "=", "Gretel", "::", "Crumb", ".", "new", "(", "context", ",", "breadcrumb_key", ",", "breadcrumb_args", ")", "# Links of first crumb", "links", "=", "crumb", ".", "links", ".", "dup", "# Get parent links", "links", ".", "unshift", "parent_links_for", "(", "crumb", ")", "links", "else", "[", "]", "end", "end" ]
Array of links for the path of the breadcrumb. Also reloads the breadcrumb configuration if needed.
[ "Array", "of", "links", "for", "the", "path", "of", "the", "breadcrumb", ".", "Also", "reloads", "the", "breadcrumb", "configuration", "if", "needed", "." ]
a3b0c99c59571ca091dce15c61a80a71addc091a
https://github.com/lassebunk/gretel/blob/a3b0c99c59571ca091dce15c61a80a71addc091a/lib/gretel/renderer.rb#L105-L123
train
lassebunk/gretel
lib/gretel/renderer.rb
Gretel.Renderer.parent_links_for
def parent_links_for(crumb) links = [] while crumb = crumb.parent links.unshift *crumb.links end links end
ruby
def parent_links_for(crumb) links = [] while crumb = crumb.parent links.unshift *crumb.links end links end
[ "def", "parent_links_for", "(", "crumb", ")", "links", "=", "[", "]", "while", "crumb", "=", "crumb", ".", "parent", "links", ".", "unshift", "crumb", ".", "links", "end", "links", "end" ]
Returns parent links for the crumb.
[ "Returns", "parent", "links", "for", "the", "crumb", "." ]
a3b0c99c59571ca091dce15c61a80a71addc091a
https://github.com/lassebunk/gretel/blob/a3b0c99c59571ca091dce15c61a80a71addc091a/lib/gretel/renderer.rb#L126-L132
train
lassebunk/gretel
lib/gretel/resettable.rb
Gretel.Resettable.reset!
def reset! instance_variables.each { |var| remove_instance_variable var } constants.each do |c| c = const_get(c) c.reset! if c.respond_to?(:reset!) end end
ruby
def reset! instance_variables.each { |var| remove_instance_variable var } constants.each do |c| c = const_get(c) c.reset! if c.respond_to?(:reset!) end end
[ "def", "reset!", "instance_variables", ".", "each", "{", "|", "var", "|", "remove_instance_variable", "var", "}", "constants", ".", "each", "do", "|", "c", "|", "c", "=", "const_get", "(", "c", ")", "c", ".", "reset!", "if", "c", ".", "respond_to?", "(", ":reset!", ")", "end", "end" ]
Resets all instance variables and calls +reset!+ on all child modules and classes. Used for testing.
[ "Resets", "all", "instance", "variables", "and", "calls", "+", "reset!", "+", "on", "all", "child", "modules", "and", "classes", ".", "Used", "for", "testing", "." ]
a3b0c99c59571ca091dce15c61a80a71addc091a
https://github.com/lassebunk/gretel/blob/a3b0c99c59571ca091dce15c61a80a71addc091a/lib/gretel/resettable.rb#L5-L11
train
crohr/pkgr
lib/pkgr/builder.rb
Pkgr.Builder.extract
def extract FileUtils.mkdir_p source_dir opts = {} if tarball == "-" # FIXME: not really happy with reading everything in memory opts[:input] = $stdin.read end tarball_extract = Mixlib::ShellOut.new("tar xzf #{tarball} -C #{source_dir}", opts) tarball_extract.logger = Pkgr.logger tarball_extract.run_command tarball_extract.error! end
ruby
def extract FileUtils.mkdir_p source_dir opts = {} if tarball == "-" # FIXME: not really happy with reading everything in memory opts[:input] = $stdin.read end tarball_extract = Mixlib::ShellOut.new("tar xzf #{tarball} -C #{source_dir}", opts) tarball_extract.logger = Pkgr.logger tarball_extract.run_command tarball_extract.error! end
[ "def", "extract", "FileUtils", ".", "mkdir_p", "source_dir", "opts", "=", "{", "}", "if", "tarball", "==", "\"-\"", "# FIXME: not really happy with reading everything in memory", "opts", "[", ":input", "]", "=", "$stdin", ".", "read", "end", "tarball_extract", "=", "Mixlib", "::", "ShellOut", ".", "new", "(", "\"tar xzf #{tarball} -C #{source_dir}\"", ",", "opts", ")", "tarball_extract", ".", "logger", "=", "Pkgr", ".", "logger", "tarball_extract", ".", "run_command", "tarball_extract", ".", "error!", "end" ]
Extract the given tarball to the target directory
[ "Extract", "the", "given", "tarball", "to", "the", "target", "directory" ]
d80c1f1055e428f720123c56e1558b9820ec6fca
https://github.com/crohr/pkgr/blob/d80c1f1055e428f720123c56e1558b9820ec6fca/lib/pkgr/builder.rb#L39-L52
train
crohr/pkgr
lib/pkgr/builder.rb
Pkgr.Builder.update_config
def update_config if File.exist?(config_file) Pkgr.debug "Loading #{distribution.slug} from #{config_file}." @config = Config.load_file(config_file, distribution.slug).merge(config) Pkgr.debug "Found .pkgr.yml file. Updated config is now: #{config.inspect}" # update distribution config distribution.config = @config # FIXME: make Config the authoritative source of the runner config (distribution only tells the default runner) if @config.runner type, *version = @config.runner.split("-") distribution.runner = Distributions::Runner.new(type, version.join("-")) end end config.distribution = distribution config.env.variables.push("TARGET=#{distribution.target}") # useful for templates that need to read files config.source_dir = source_dir config.build_dir = build_dir end
ruby
def update_config if File.exist?(config_file) Pkgr.debug "Loading #{distribution.slug} from #{config_file}." @config = Config.load_file(config_file, distribution.slug).merge(config) Pkgr.debug "Found .pkgr.yml file. Updated config is now: #{config.inspect}" # update distribution config distribution.config = @config # FIXME: make Config the authoritative source of the runner config (distribution only tells the default runner) if @config.runner type, *version = @config.runner.split("-") distribution.runner = Distributions::Runner.new(type, version.join("-")) end end config.distribution = distribution config.env.variables.push("TARGET=#{distribution.target}") # useful for templates that need to read files config.source_dir = source_dir config.build_dir = build_dir end
[ "def", "update_config", "if", "File", ".", "exist?", "(", "config_file", ")", "Pkgr", ".", "debug", "\"Loading #{distribution.slug} from #{config_file}.\"", "@config", "=", "Config", ".", "load_file", "(", "config_file", ",", "distribution", ".", "slug", ")", ".", "merge", "(", "config", ")", "Pkgr", ".", "debug", "\"Found .pkgr.yml file. Updated config is now: #{config.inspect}\"", "# update distribution config", "distribution", ".", "config", "=", "@config", "# FIXME: make Config the authoritative source of the runner config (distribution only tells the default runner)", "if", "@config", ".", "runner", "type", ",", "*", "version", "=", "@config", ".", "runner", ".", "split", "(", "\"-\"", ")", "distribution", ".", "runner", "=", "Distributions", "::", "Runner", ".", "new", "(", "type", ",", "version", ".", "join", "(", "\"-\"", ")", ")", "end", "end", "config", ".", "distribution", "=", "distribution", "config", ".", "env", ".", "variables", ".", "push", "(", "\"TARGET=#{distribution.target}\"", ")", "# useful for templates that need to read files", "config", ".", "source_dir", "=", "source_dir", "config", ".", "build_dir", "=", "build_dir", "end" ]
Update existing config with the one from .pkgr.yml file, if any
[ "Update", "existing", "config", "with", "the", "one", "from", ".", "pkgr", ".", "yml", "file", "if", "any" ]
d80c1f1055e428f720123c56e1558b9820ec6fca
https://github.com/crohr/pkgr/blob/d80c1f1055e428f720123c56e1558b9820ec6fca/lib/pkgr/builder.rb#L55-L75
train
crohr/pkgr
lib/pkgr/builder.rb
Pkgr.Builder.check
def check raise Errors::ConfigurationInvalid, config.errors.join("; ") unless config.valid? distribution.check end
ruby
def check raise Errors::ConfigurationInvalid, config.errors.join("; ") unless config.valid? distribution.check end
[ "def", "check", "raise", "Errors", "::", "ConfigurationInvalid", ",", "config", ".", "errors", ".", "join", "(", "\"; \"", ")", "unless", "config", ".", "valid?", "distribution", ".", "check", "end" ]
Check configuration, and verifies that the current distribution's requirements are satisfied
[ "Check", "configuration", "and", "verifies", "that", "the", "current", "distribution", "s", "requirements", "are", "satisfied" ]
d80c1f1055e428f720123c56e1558b9820ec6fca
https://github.com/crohr/pkgr/blob/d80c1f1055e428f720123c56e1558b9820ec6fca/lib/pkgr/builder.rb#L88-L91
train
crohr/pkgr
lib/pkgr/builder.rb
Pkgr.Builder.setup
def setup Dir.chdir(build_dir) do distribution.templates.each do |template| template.install(config.sesame) end end end
ruby
def setup Dir.chdir(build_dir) do distribution.templates.each do |template| template.install(config.sesame) end end end
[ "def", "setup", "Dir", ".", "chdir", "(", "build_dir", ")", "do", "distribution", ".", "templates", ".", "each", "do", "|", "template", "|", "template", ".", "install", "(", "config", ".", "sesame", ")", "end", "end", "end" ]
Setup the build directory structure
[ "Setup", "the", "build", "directory", "structure" ]
d80c1f1055e428f720123c56e1558b9820ec6fca
https://github.com/crohr/pkgr/blob/d80c1f1055e428f720123c56e1558b9820ec6fca/lib/pkgr/builder.rb#L94-L100
train
crohr/pkgr
lib/pkgr/builder.rb
Pkgr.Builder.compile
def compile begin FileUtils.mkdir_p(app_home_dir) rescue Errno::EACCES => e Pkgr.logger.warn "Can't create #{app_home_dir.inspect}, which may be needed by some buildpacks." end FileUtils.mkdir_p(compile_cache_dir) FileUtils.mkdir_p(compile_env_dir) if buildpacks_for_app.size > 0 run_hook config.before_hook buildpacks_for_app.each do |buildpack| puts "-----> #{buildpack.banner} app" buildpack.compile(source_dir, compile_cache_dir, compile_env_dir) buildpack.release(source_dir) end run_hook config.after_hook else raise Errors::UnknownAppType, "Can't find a buildpack for your app" end end
ruby
def compile begin FileUtils.mkdir_p(app_home_dir) rescue Errno::EACCES => e Pkgr.logger.warn "Can't create #{app_home_dir.inspect}, which may be needed by some buildpacks." end FileUtils.mkdir_p(compile_cache_dir) FileUtils.mkdir_p(compile_env_dir) if buildpacks_for_app.size > 0 run_hook config.before_hook buildpacks_for_app.each do |buildpack| puts "-----> #{buildpack.banner} app" buildpack.compile(source_dir, compile_cache_dir, compile_env_dir) buildpack.release(source_dir) end run_hook config.after_hook else raise Errors::UnknownAppType, "Can't find a buildpack for your app" end end
[ "def", "compile", "begin", "FileUtils", ".", "mkdir_p", "(", "app_home_dir", ")", "rescue", "Errno", "::", "EACCES", "=>", "e", "Pkgr", ".", "logger", ".", "warn", "\"Can't create #{app_home_dir.inspect}, which may be needed by some buildpacks.\"", "end", "FileUtils", ".", "mkdir_p", "(", "compile_cache_dir", ")", "FileUtils", ".", "mkdir_p", "(", "compile_env_dir", ")", "if", "buildpacks_for_app", ".", "size", ">", "0", "run_hook", "config", ".", "before_hook", "buildpacks_for_app", ".", "each", "do", "|", "buildpack", "|", "puts", "\"-----> #{buildpack.banner} app\"", "buildpack", ".", "compile", "(", "source_dir", ",", "compile_cache_dir", ",", "compile_env_dir", ")", "buildpack", ".", "release", "(", "source_dir", ")", "end", "run_hook", "config", ".", "after_hook", "else", "raise", "Errors", "::", "UnknownAppType", ",", "\"Can't find a buildpack for your app\"", "end", "end" ]
Pass the app through the buildpack
[ "Pass", "the", "app", "through", "the", "buildpack" ]
d80c1f1055e428f720123c56e1558b9820ec6fca
https://github.com/crohr/pkgr/blob/d80c1f1055e428f720123c56e1558b9820ec6fca/lib/pkgr/builder.rb#L109-L131
train
crohr/pkgr
lib/pkgr/builder.rb
Pkgr.Builder.write_init
def write_init FileUtils.mkdir_p scaling_dir Dir.chdir(scaling_dir) do distribution.initializers_for(config.name, procfile_entries).each do |(process, file)| process_config = config.dup process_config.process_name = process.name process_config.process_command = process.command file.install(process_config.sesame) end end end
ruby
def write_init FileUtils.mkdir_p scaling_dir Dir.chdir(scaling_dir) do distribution.initializers_for(config.name, procfile_entries).each do |(process, file)| process_config = config.dup process_config.process_name = process.name process_config.process_command = process.command file.install(process_config.sesame) end end end
[ "def", "write_init", "FileUtils", ".", "mkdir_p", "scaling_dir", "Dir", ".", "chdir", "(", "scaling_dir", ")", "do", "distribution", ".", "initializers_for", "(", "config", ".", "name", ",", "procfile_entries", ")", ".", "each", "do", "|", "(", "process", ",", "file", ")", "|", "process_config", "=", "config", ".", "dup", "process_config", ".", "process_name", "=", "process", ".", "name", "process_config", ".", "process_command", "=", "process", ".", "command", "file", ".", "install", "(", "process_config", ".", "sesame", ")", "end", "end", "end" ]
Write startup scripts.
[ "Write", "startup", "scripts", "." ]
d80c1f1055e428f720123c56e1558b9820ec6fca
https://github.com/crohr/pkgr/blob/d80c1f1055e428f720123c56e1558b9820ec6fca/lib/pkgr/builder.rb#L154-L164
train
crohr/pkgr
lib/pkgr/builder.rb
Pkgr.Builder.setup_crons
def setup_crons crons_dir = File.join("/", distribution.crons_dir) config.crons.map! do |cron_path| Cron.new(File.expand_path(cron_path, config.home), File.join(crons_dir, File.basename(cron_path))) end config.crons.each do |cron| puts "-----> [cron] #{cron.source} => #{cron.destination}" end end
ruby
def setup_crons crons_dir = File.join("/", distribution.crons_dir) config.crons.map! do |cron_path| Cron.new(File.expand_path(cron_path, config.home), File.join(crons_dir, File.basename(cron_path))) end config.crons.each do |cron| puts "-----> [cron] #{cron.source} => #{cron.destination}" end end
[ "def", "setup_crons", "crons_dir", "=", "File", ".", "join", "(", "\"/\"", ",", "distribution", ".", "crons_dir", ")", "config", ".", "crons", ".", "map!", "do", "|", "cron_path", "|", "Cron", ".", "new", "(", "File", ".", "expand_path", "(", "cron_path", ",", "config", ".", "home", ")", ",", "File", ".", "join", "(", "crons_dir", ",", "File", ".", "basename", "(", "cron_path", ")", ")", ")", "end", "config", ".", "crons", ".", "each", "do", "|", "cron", "|", "puts", "\"-----> [cron] #{cron.source} => #{cron.destination}\"", "end", "end" ]
Write cron files
[ "Write", "cron", "files" ]
d80c1f1055e428f720123c56e1558b9820ec6fca
https://github.com/crohr/pkgr/blob/d80c1f1055e428f720123c56e1558b9820ec6fca/lib/pkgr/builder.rb#L167-L177
train
crohr/pkgr
lib/pkgr/builder.rb
Pkgr.Builder.package
def package(remaining_attempts = 3) app_package = Mixlib::ShellOut.new(fpm_command) app_package.logger = Pkgr.logger app_package.run_command app_package.error! begin verify rescue Mixlib::ShellOut::ShellCommandFailed => e if remaining_attempts > 0 package(remaining_attempts - 1) else raise end end end
ruby
def package(remaining_attempts = 3) app_package = Mixlib::ShellOut.new(fpm_command) app_package.logger = Pkgr.logger app_package.run_command app_package.error! begin verify rescue Mixlib::ShellOut::ShellCommandFailed => e if remaining_attempts > 0 package(remaining_attempts - 1) else raise end end end
[ "def", "package", "(", "remaining_attempts", "=", "3", ")", "app_package", "=", "Mixlib", "::", "ShellOut", ".", "new", "(", "fpm_command", ")", "app_package", ".", "logger", "=", "Pkgr", ".", "logger", "app_package", ".", "run_command", "app_package", ".", "error!", "begin", "verify", "rescue", "Mixlib", "::", "ShellOut", "::", "ShellCommandFailed", "=>", "e", "if", "remaining_attempts", ">", "0", "package", "(", "remaining_attempts", "-", "1", ")", "else", "raise", "end", "end", "end" ]
Launch the FPM command that will generate the package.
[ "Launch", "the", "FPM", "command", "that", "will", "generate", "the", "package", "." ]
d80c1f1055e428f720123c56e1558b9820ec6fca
https://github.com/crohr/pkgr/blob/d80c1f1055e428f720123c56e1558b9820ec6fca/lib/pkgr/builder.rb#L181-L195
train
crohr/pkgr
lib/pkgr/builder.rb
Pkgr.Builder.buildpacks_for_app
def buildpacks_for_app raise "#{source_dir} does not exist" unless File.directory?(source_dir) @buildpacks_for_app ||= begin mode, buildpacks = distribution.buildpacks case mode when :custom buildpacks.find_all do |buildpack| buildpack.setup(config.edge, config.home) buildpack.detect(source_dir) end else [buildpacks.find do |buildpack| buildpack.setup(config.edge, config.home) buildpack.detect(source_dir) end].compact end end end
ruby
def buildpacks_for_app raise "#{source_dir} does not exist" unless File.directory?(source_dir) @buildpacks_for_app ||= begin mode, buildpacks = distribution.buildpacks case mode when :custom buildpacks.find_all do |buildpack| buildpack.setup(config.edge, config.home) buildpack.detect(source_dir) end else [buildpacks.find do |buildpack| buildpack.setup(config.edge, config.home) buildpack.detect(source_dir) end].compact end end end
[ "def", "buildpacks_for_app", "raise", "\"#{source_dir} does not exist\"", "unless", "File", ".", "directory?", "(", "source_dir", ")", "@buildpacks_for_app", "||=", "begin", "mode", ",", "buildpacks", "=", "distribution", ".", "buildpacks", "case", "mode", "when", ":custom", "buildpacks", ".", "find_all", "do", "|", "buildpack", "|", "buildpack", ".", "setup", "(", "config", ".", "edge", ",", "config", ".", "home", ")", "buildpack", ".", "detect", "(", "source_dir", ")", "end", "else", "[", "buildpacks", ".", "find", "do", "|", "buildpack", "|", "buildpack", ".", "setup", "(", "config", ".", "edge", ",", "config", ".", "home", ")", "buildpack", ".", "detect", "(", "source_dir", ")", "end", "]", ".", "compact", "end", "end", "end" ]
Buildpacks detected for the app, if any. If multiple buildpacks are explicitly specified, all are used
[ "Buildpacks", "detected", "for", "the", "app", "if", "any", ".", "If", "multiple", "buildpacks", "are", "explicitly", "specified", "all", "are", "used" ]
d80c1f1055e428f720123c56e1558b9820ec6fca
https://github.com/crohr/pkgr/blob/d80c1f1055e428f720123c56e1558b9820ec6fca/lib/pkgr/builder.rb#L292-L309
train
Jesus/dropbox_api
lib/dropbox_api/options_validator.rb
DropboxApi.OptionsValidator.validate_options
def validate_options(valid_option_keys, options) options.keys.each do |key| unless valid_option_keys.include? key.to_sym raise ArgumentError, "Invalid option `#{key}`" end end end
ruby
def validate_options(valid_option_keys, options) options.keys.each do |key| unless valid_option_keys.include? key.to_sym raise ArgumentError, "Invalid option `#{key}`" end end end
[ "def", "validate_options", "(", "valid_option_keys", ",", "options", ")", "options", ".", "keys", ".", "each", "do", "|", "key", "|", "unless", "valid_option_keys", ".", "include?", "key", ".", "to_sym", "raise", "ArgumentError", ",", "\"Invalid option `#{key}`\"", "end", "end", "end" ]
Takes in a list of valid option keys and a hash of options. If one of the keys in the hash is invalid an ArgumentError will be raised. @param valid_option_keys List of valid keys for the options hash. @param options [Hash] Options hash.
[ "Takes", "in", "a", "list", "of", "valid", "option", "keys", "and", "a", "hash", "of", "options", ".", "If", "one", "of", "the", "keys", "in", "the", "hash", "is", "invalid", "an", "ArgumentError", "will", "be", "raised", "." ]
cc9bc0cbe0ee0035a01cb549822f9edd40797e9d
https://github.com/Jesus/dropbox_api/blob/cc9bc0cbe0ee0035a01cb549822f9edd40797e9d/lib/dropbox_api/options_validator.rb#L8-L14
train
Jesus/dropbox_api
lib/dropbox_api/metadata/base.rb
DropboxApi::Metadata.Base.to_hash
def to_hash Hash[self.class.fields.keys.map do |field_name| [field_name.to_s, serialized_field(field_name)] end.select { |k, v| !v.nil? }] end
ruby
def to_hash Hash[self.class.fields.keys.map do |field_name| [field_name.to_s, serialized_field(field_name)] end.select { |k, v| !v.nil? }] end
[ "def", "to_hash", "Hash", "[", "self", ".", "class", ".", "fields", ".", "keys", ".", "map", "do", "|", "field_name", "|", "[", "field_name", ".", "to_s", ",", "serialized_field", "(", "field_name", ")", "]", "end", ".", "select", "{", "|", "k", ",", "v", "|", "!", "v", ".", "nil?", "}", "]", "end" ]
Takes in a hash containing all the attributes required to initialize the object. Each hash entry should have a key which identifies a field and its value, so a valid call would be something like this: DropboxApi::Metadata::File.new({ "name" => "a.jpg", "path_lower" => "/a.jpg", "path_display" => "/a.jpg", "id" => "id:evvfE6q6cK0AAAAAAAAB2w", "client_modified" => "2016-10-19T17:17:34Z", "server_modified" => "2016-10-19T17:17:34Z", "rev" => "28924061bdd", "size" => 396317 }) @raise [ArgumentError] If a required attribute is missing. @param metadata [Hash]
[ "Takes", "in", "a", "hash", "containing", "all", "the", "attributes", "required", "to", "initialize", "the", "object", "." ]
cc9bc0cbe0ee0035a01cb549822f9edd40797e9d
https://github.com/Jesus/dropbox_api/blob/cc9bc0cbe0ee0035a01cb549822f9edd40797e9d/lib/dropbox_api/metadata/base.rb#L39-L43
train