id
int32
0
24.9k
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
23,200
SecureBrain/ruby_apk
lib/android/apk.rb
Android.Apk.digest
def digest(type = :sha1) case type when :sha1 Digest::SHA1.hexdigest(@bindata) when :sha256 Digest::SHA256.hexdigest(@bindata) when :md5 Digest::MD5.hexdigest(@bindata) else raise ArgumentError end end
ruby
def digest(type = :sha1) case type when :sha1 Digest::SHA1.hexdigest(@bindata) when :sha256 Digest::SHA256.hexdigest(@bindata) when :md5 Digest::MD5.hexdigest(@bindata) else raise ArgumentError end end
[ "def", "digest", "(", "type", "=", ":sha1", ")", "case", "type", "when", ":sha1", "Digest", "::", "SHA1", ".", "hexdigest", "(", "@bindata", ")", "when", ":sha256", "Digest", "::", "SHA256", ".", "hexdigest", "(", "@bindata", ")", "when", ":md5", "Digest", "::", "MD5", ".", "hexdigest", "(", "@bindata", ")", "else", "raise", "ArgumentError", "end", "end" ]
return hex digest string of apk file @param [Symbol] type hash digest type(:sha1, sha256, :md5) @return [String] hex digest string @raise [ArgumentError] type is knknown type
[ "return", "hex", "digest", "string", "of", "apk", "file" ]
405b6af165722c6b547ad914dfbb78fdc40e6ef7
https://github.com/SecureBrain/ruby_apk/blob/405b6af165722c6b547ad914dfbb78fdc40e6ef7/lib/android/apk.rb#L81-L92
23,201
SecureBrain/ruby_apk
lib/android/apk.rb
Android.Apk.entry
def entry(name) entry = @zip.find_entry(name) raise NotFoundError, "'#{name}'" if entry.nil? return entry end
ruby
def entry(name) entry = @zip.find_entry(name) raise NotFoundError, "'#{name}'" if entry.nil? return entry end
[ "def", "entry", "(", "name", ")", "entry", "=", "@zip", ".", "find_entry", "(", "name", ")", "raise", "NotFoundError", ",", "\"'#{name}'\"", "if", "entry", ".", "nil?", "return", "entry", "end" ]
find and return zip entry with name @param [String] name file name in apk(fullpath) @return [Zip::ZipEntry] zip entry object @raise [NotFoundError] when 'name' doesn't exist in the apk
[ "find", "and", "return", "zip", "entry", "with", "name" ]
405b6af165722c6b547ad914dfbb78fdc40e6ef7
https://github.com/SecureBrain/ruby_apk/blob/405b6af165722c6b547ad914dfbb78fdc40e6ef7/lib/android/apk.rb#L131-L135
23,202
SecureBrain/ruby_apk
lib/android/apk.rb
Android.Apk.find
def find(&block) found = [] self.each_file do |name, data| ret = block.call(name, data) found << name if ret end found end
ruby
def find(&block) found = [] self.each_file do |name, data| ret = block.call(name, data) found << name if ret end found end
[ "def", "find", "(", "&", "block", ")", "found", "=", "[", "]", "self", ".", "each_file", "do", "|", "name", ",", "data", "|", "ret", "=", "block", ".", "call", "(", "name", ",", "data", ")", "found", "<<", "name", "if", "ret", "end", "found", "end" ]
find files which is matched with block condition @yield [name, data] find condition @yieldparam [String] name file name in apk @yieldparam [String] data file data in apk @yieldreturn [Array] Array of matched entry name @return [Array] Array of matched entry name @example apk = Apk.new(path) elf_files = apk.find { |name, data| data[0..3] == [0x7f, 0x45, 0x4c, 0x46] } # ELF magic number
[ "find", "files", "which", "is", "matched", "with", "block", "condition" ]
405b6af165722c6b547ad914dfbb78fdc40e6ef7
https://github.com/SecureBrain/ruby_apk/blob/405b6af165722c6b547ad914dfbb78fdc40e6ef7/lib/android/apk.rb#L146-L153
23,203
SecureBrain/ruby_apk
lib/android/apk.rb
Android.Apk.icon
def icon icon_id = @manifest.doc.elements['/manifest/application'].attributes['icon'] if /^@(\w+\/\w+)|(0x[0-9a-fA-F]{8})$/ =~ icon_id drawables = @resource.find(icon_id) Hash[drawables.map {|name| [name, file(name)] }] else { icon_id => file(icon_id) } # ugh!: not tested!! end end
ruby
def icon icon_id = @manifest.doc.elements['/manifest/application'].attributes['icon'] if /^@(\w+\/\w+)|(0x[0-9a-fA-F]{8})$/ =~ icon_id drawables = @resource.find(icon_id) Hash[drawables.map {|name| [name, file(name)] }] else { icon_id => file(icon_id) } # ugh!: not tested!! end end
[ "def", "icon", "icon_id", "=", "@manifest", ".", "doc", ".", "elements", "[", "'/manifest/application'", "]", ".", "attributes", "[", "'icon'", "]", "if", "/", "\\w", "\\/", "\\w", "/", "=~", "icon_id", "drawables", "=", "@resource", ".", "find", "(", "icon_id", ")", "Hash", "[", "drawables", ".", "map", "{", "|", "name", "|", "[", "name", ",", "file", "(", "name", ")", "]", "}", "]", "else", "{", "icon_id", "=>", "file", "(", "icon_id", ")", "}", "# ugh!: not tested!!", "end", "end" ]
extract icon data from AndroidManifest and resource. @return [Hash{ String => String }] hash key is icon filename. value is image data @raise [NotFoundError] @since 0.6.0
[ "extract", "icon", "data", "from", "AndroidManifest", "and", "resource", "." ]
405b6af165722c6b547ad914dfbb78fdc40e6ef7
https://github.com/SecureBrain/ruby_apk/blob/405b6af165722c6b547ad914dfbb78fdc40e6ef7/lib/android/apk.rb#L159-L167
23,204
SecureBrain/ruby_apk
lib/android/apk.rb
Android.Apk.signs
def signs signs = {} self.each_file do |path, data| # find META-INF/xxx.{RSA|DSA} next unless path =~ /^META-INF\// && data.unpack("CC") == [0x30, 0x82] signs[path] = OpenSSL::PKCS7.new(data) end signs end
ruby
def signs signs = {} self.each_file do |path, data| # find META-INF/xxx.{RSA|DSA} next unless path =~ /^META-INF\// && data.unpack("CC") == [0x30, 0x82] signs[path] = OpenSSL::PKCS7.new(data) end signs end
[ "def", "signs", "signs", "=", "{", "}", "self", ".", "each_file", "do", "|", "path", ",", "data", "|", "# find META-INF/xxx.{RSA|DSA}", "next", "unless", "path", "=~", "/", "\\/", "/", "&&", "data", ".", "unpack", "(", "\"CC\"", ")", "==", "[", "0x30", ",", "0x82", "]", "signs", "[", "path", "]", "=", "OpenSSL", "::", "PKCS7", ".", "new", "(", "data", ")", "end", "signs", "end" ]
apk's signature information @return [Hash{ String => OpenSSL::PKCS7 } ] key: sign file path, value: signature @since 0.7.0
[ "apk", "s", "signature", "information" ]
405b6af165722c6b547ad914dfbb78fdc40e6ef7
https://github.com/SecureBrain/ruby_apk/blob/405b6af165722c6b547ad914dfbb78fdc40e6ef7/lib/android/apk.rb#L189-L197
23,205
SecureBrain/ruby_apk
lib/android/apk.rb
Android.Apk.certificates
def certificates return Hash[self.signs.map{|path, sign| [path, sign.certificates.first] }] end
ruby
def certificates return Hash[self.signs.map{|path, sign| [path, sign.certificates.first] }] end
[ "def", "certificates", "return", "Hash", "[", "self", ".", "signs", ".", "map", "{", "|", "path", ",", "sign", "|", "[", "path", ",", "sign", ".", "certificates", ".", "first", "]", "}", "]", "end" ]
certificate info which is used for signing @return [Hash{String => OpenSSL::X509::Certificate }] key: sign file path, value: first certficate in the sign file @since 0.7.0
[ "certificate", "info", "which", "is", "used", "for", "signing" ]
405b6af165722c6b547ad914dfbb78fdc40e6ef7
https://github.com/SecureBrain/ruby_apk/blob/405b6af165722c6b547ad914dfbb78fdc40e6ef7/lib/android/apk.rb#L202-L204
23,206
SecureBrain/ruby_apk
lib/android/manifest.rb
Android.Manifest.version_name
def version_name(lang=nil) vername = @doc.root.attributes['versionName'] unless @rsc.nil? if /^@(\w+\/\w+)|(0x[0-9a-fA-F]{8})$/ =~ vername opts = {} opts[:lang] = lang unless lang.nil? vername = @rsc.find(vername, opts) end end vername end
ruby
def version_name(lang=nil) vername = @doc.root.attributes['versionName'] unless @rsc.nil? if /^@(\w+\/\w+)|(0x[0-9a-fA-F]{8})$/ =~ vername opts = {} opts[:lang] = lang unless lang.nil? vername = @rsc.find(vername, opts) end end vername end
[ "def", "version_name", "(", "lang", "=", "nil", ")", "vername", "=", "@doc", ".", "root", ".", "attributes", "[", "'versionName'", "]", "unless", "@rsc", ".", "nil?", "if", "/", "\\w", "\\/", "\\w", "/", "=~", "vername", "opts", "=", "{", "}", "opts", "[", ":lang", "]", "=", "lang", "unless", "lang", ".", "nil?", "vername", "=", "@rsc", ".", "find", "(", "vername", ",", "opts", ")", "end", "end", "vername", "end" ]
application version name @return [String]
[ "application", "version", "name" ]
405b6af165722c6b547ad914dfbb78fdc40e6ef7
https://github.com/SecureBrain/ruby_apk/blob/405b6af165722c6b547ad914dfbb78fdc40e6ef7/lib/android/manifest.rb#L199-L209
23,207
SecureBrain/ruby_apk
lib/android/manifest.rb
Android.Manifest.to_xml
def to_xml(indent=4) xml ='' formatter = REXML::Formatters::Pretty.new(indent) formatter.write(@doc.root, xml) xml end
ruby
def to_xml(indent=4) xml ='' formatter = REXML::Formatters::Pretty.new(indent) formatter.write(@doc.root, xml) xml end
[ "def", "to_xml", "(", "indent", "=", "4", ")", "xml", "=", "''", "formatter", "=", "REXML", "::", "Formatters", "::", "Pretty", ".", "new", "(", "indent", ")", "formatter", ".", "write", "(", "@doc", ".", "root", ",", "xml", ")", "xml", "end" ]
return xml as string format @param [Integer] indent size(bytes) @return [String] raw xml string
[ "return", "xml", "as", "string", "format" ]
405b6af165722c6b547ad914dfbb78fdc40e6ef7
https://github.com/SecureBrain/ruby_apk/blob/405b6af165722c6b547ad914dfbb78fdc40e6ef7/lib/android/manifest.rb#L242-L247
23,208
SecureBrain/ruby_apk
lib/android/axml_parser.rb
Android.AXMLParser.parse_attribute
def parse_attribute ns_id, name_id, val_str_id, flags, val = @io.read(4*5).unpack("V*") key = @strings[name_id] unless ns_id == 0xFFFFFFFF ns = @strings[ns_id] prefix = ns.sub(/.*\//,'') unless @ns.include? ns @ns << ns @doc.root.add_namespace(prefix, ns) end key = "#{prefix}:#{key}" end value = convert_value(val_str_id, flags, val) return key, value end
ruby
def parse_attribute ns_id, name_id, val_str_id, flags, val = @io.read(4*5).unpack("V*") key = @strings[name_id] unless ns_id == 0xFFFFFFFF ns = @strings[ns_id] prefix = ns.sub(/.*\//,'') unless @ns.include? ns @ns << ns @doc.root.add_namespace(prefix, ns) end key = "#{prefix}:#{key}" end value = convert_value(val_str_id, flags, val) return key, value end
[ "def", "parse_attribute", "ns_id", ",", "name_id", ",", "val_str_id", ",", "flags", ",", "val", "=", "@io", ".", "read", "(", "4", "*", "5", ")", ".", "unpack", "(", "\"V*\"", ")", "key", "=", "@strings", "[", "name_id", "]", "unless", "ns_id", "==", "0xFFFFFFFF", "ns", "=", "@strings", "[", "ns_id", "]", "prefix", "=", "ns", ".", "sub", "(", "/", "\\/", "/", ",", "''", ")", "unless", "@ns", ".", "include?", "ns", "@ns", "<<", "ns", "@doc", ".", "root", ".", "add_namespace", "(", "prefix", ",", "ns", ")", "end", "key", "=", "\"#{prefix}:#{key}\"", "end", "value", "=", "convert_value", "(", "val_str_id", ",", "flags", ",", "val", ")", "return", "key", ",", "value", "end" ]
parse attribute of a element
[ "parse", "attribute", "of", "a", "element" ]
405b6af165722c6b547ad914dfbb78fdc40e6ef7
https://github.com/SecureBrain/ruby_apk/blob/405b6af165722c6b547ad914dfbb78fdc40e6ef7/lib/android/axml_parser.rb#L133-L147
23,209
ericbeland/html_validation
lib/html_validation/page_validations.rb
PageValidations.HTMLValidation.each_exception
def each_exception Dir.chdir(@data_folder) Dir.glob("*.exceptions.txt").each do |file| if File.open(File.join(@data_folder, file), 'r').read != '' yield HTMLValidationResult.load_from_files(file.gsub('.exceptions.txt','')) end end end
ruby
def each_exception Dir.chdir(@data_folder) Dir.glob("*.exceptions.txt").each do |file| if File.open(File.join(@data_folder, file), 'r').read != '' yield HTMLValidationResult.load_from_files(file.gsub('.exceptions.txt','')) end end end
[ "def", "each_exception", "Dir", ".", "chdir", "(", "@data_folder", ")", "Dir", ".", "glob", "(", "\"*.exceptions.txt\"", ")", ".", "each", "do", "|", "file", "|", "if", "File", ".", "open", "(", "File", ".", "join", "(", "@data_folder", ",", "file", ")", ",", "'r'", ")", ".", "read", "!=", "''", "yield", "HTMLValidationResult", ".", "load_from_files", "(", "file", ".", "gsub", "(", "'.exceptions.txt'", ",", "''", ")", ")", "end", "end", "end" ]
For each stored exception, yield an HTMLValidationResult object to allow the user to call .accept! on the exception if it is OK.
[ "For", "each", "stored", "exception", "yield", "an", "HTMLValidationResult", "object", "to", "allow", "the", "user", "to", "call", ".", "accept!", "on", "the", "exception", "if", "it", "is", "OK", "." ]
1a806a447dc46e3f28595d53dd10ee6cd9b97be7
https://github.com/ericbeland/html_validation/blob/1a806a447dc46e3f28595d53dd10ee6cd9b97be7/lib/html_validation/page_validations.rb#L103-L110
23,210
ms-ati/rumonade
lib/rumonade/monad.rb
Rumonade.Monad.map_with_monad
def map_with_monad(lam = nil, &blk) bind { |v| self.class.unit((lam || blk).call(v)) } end
ruby
def map_with_monad(lam = nil, &blk) bind { |v| self.class.unit((lam || blk).call(v)) } end
[ "def", "map_with_monad", "(", "lam", "=", "nil", ",", "&", "blk", ")", "bind", "{", "|", "v", "|", "self", ".", "class", ".", "unit", "(", "(", "lam", "||", "blk", ")", ".", "call", "(", "v", ")", ")", "}", "end" ]
Returns a monad whose elements are the results of applying the given function to each element in this monad NOTE: normally aliased as +map+ when +Monad+ is mixed into a class
[ "Returns", "a", "monad", "whose", "elements", "are", "the", "results", "of", "applying", "the", "given", "function", "to", "each", "element", "in", "this", "monad" ]
e439a37ccc1c96a28332ef31b53d1ba830640b9f
https://github.com/ms-ati/rumonade/blob/e439a37ccc1c96a28332ef31b53d1ba830640b9f/lib/rumonade/monad.rb#L39-L41
23,211
ms-ati/rumonade
lib/rumonade/monad.rb
Rumonade.Monad.select
def select(lam = nil, &blk) bind { |x| (lam || blk).call(x) ? self.class.unit(x) : self.class.empty } end
ruby
def select(lam = nil, &blk) bind { |x| (lam || blk).call(x) ? self.class.unit(x) : self.class.empty } end
[ "def", "select", "(", "lam", "=", "nil", ",", "&", "blk", ")", "bind", "{", "|", "x", "|", "(", "lam", "||", "blk", ")", ".", "call", "(", "x", ")", "?", "self", ".", "class", ".", "unit", "(", "x", ")", ":", "self", ".", "class", ".", "empty", "}", "end" ]
Returns a monad whose elements are all those elements of this monad for which the given predicate returned true
[ "Returns", "a", "monad", "whose", "elements", "are", "all", "those", "elements", "of", "this", "monad", "for", "which", "the", "given", "predicate", "returned", "true" ]
e439a37ccc1c96a28332ef31b53d1ba830640b9f
https://github.com/ms-ati/rumonade/blob/e439a37ccc1c96a28332ef31b53d1ba830640b9f/lib/rumonade/monad.rb#L73-L75
23,212
Asquera/warden-hmac-authentication
lib/hmac/signer.rb
HMAC.Signer.generate_signature
def generate_signature(params) secret = params.delete(:secret) # jruby stumbles over empty secrets, we regard them as invalid anyways, so we return an empty digest if no scret was given if '' == secret.to_s nil else OpenSSL::HMAC.hexdigest(algorithm, secret, canonical_representation(params)) end end
ruby
def generate_signature(params) secret = params.delete(:secret) # jruby stumbles over empty secrets, we regard them as invalid anyways, so we return an empty digest if no scret was given if '' == secret.to_s nil else OpenSSL::HMAC.hexdigest(algorithm, secret, canonical_representation(params)) end end
[ "def", "generate_signature", "(", "params", ")", "secret", "=", "params", ".", "delete", "(", ":secret", ")", "# jruby stumbles over empty secrets, we regard them as invalid anyways, so we return an empty digest if no scret was given", "if", "''", "==", "secret", ".", "to_s", "nil", "else", "OpenSSL", "::", "HMAC", ".", "hexdigest", "(", "algorithm", ",", "secret", ",", "canonical_representation", "(", "params", ")", ")", "end", "end" ]
create a new HMAC instance @param [String] algorithm The hashing-algorithm to use. See the openssl documentation for valid values. @param [Hash] default_opts The default options for all calls that take opts @option default_opts [String] :auth_scheme ('HMAC') The name of the authorization scheme used in the Authorization header and to construct various header-names @option default_opts [String] :auth_param ('auth') The name of the authentication param to use for query based authentication @option default_opts [String] :auth_header ('Authorization') The name of the authorization header to use @option default_opts [String] :auth_header_format ('%{auth_scheme} %{signature}') The format of the authorization header. Will be interpolated with the given options and the signature. @option default_opts [String] :nonce_header ('X-#{auth_scheme}-Nonce') The header name for the request nonce @option default_opts [String] :alternate_date_header ('X-#{auth_scheme}-Date') The header name for the alternate date header @option default_opts [Bool] :query_based (false) Whether to use query based authentication @option default_opts [Bool] :use_alternate_date_header (false) Use the alternate date header instead of `Date` @option default_opts [Hash] :extra_auth_params ({}) Additional parameters to inject in the auth parameter @option default_opts [Array<Symbol>] :ignore_params ([]) Params to ignore for signing Generate the signature from a hash representation returns nil if no secret or an empty secret was given @param [Hash] params the parameters to create the representation with @option params [String] :secret The secret to generate the signature with @option params [String] :method The HTTP Verb of the request @option params [String] :date The date of the request as it was formatted in the request @option params [String] :nonce ('') The nonce given in the request @option params [String] :path The path portion of the request @option params [Hash] :query ({}) The query parameters given in the request. Must not contain the auth param. @option params [Hash] :headers ({}) All headers given in the request (optional and required) @option params [String] :auth_scheme ('HMAC') The name of the authorization scheme used in the Authorization header and to construct various header-names @option params [String] :auth_param ('auth') The name of the authentication param to use for query based authentication @option params [Hash] :extra_auth_params ({}) Additional parameters to inject in the auth parameter @option params [Array<Symbol>] :ignore_params ([]) Params to ignore for signing @option params [String] :auth_header ('Authorization') The name of the authorization header to use @option params [String] :auth_header_format ('%{auth_scheme} %{signature}') The format of the authorization header. Will be interpolated with the given options and the signature. @option params [String] :nonce_header ('X-#{auth_scheme}-Nonce') The header name for the request nonce @option params [String] :alternate_date_header ('X-#{auth_scheme}-Date') The header name for the alternate date header @option params [Bool] :query_based (false) Whether to use query based authentication @option params [Bool] :use_alternate_date_header (false) Use the alternate date header instead of `Date` @return [String] the signature
[ "create", "a", "new", "HMAC", "instance" ]
10005a8d205411405e7f5f5d5711c3c2228b5b71
https://github.com/Asquera/warden-hmac-authentication/blob/10005a8d205411405e7f5f5d5711c3c2228b5b71/lib/hmac/signer.rb#L72-L81
23,213
Asquera/warden-hmac-authentication
lib/hmac/signer.rb
HMAC.Signer.validate_url_signature
def validate_url_signature(url, secret, opts = {}) opts = default_opts.merge(opts) opts[:query_based] = true uri = parse_url(url) query_values = Rack::Utils.parse_nested_query(uri.query) return false unless query_values auth_params = query_values.delete(opts[:auth_param]) return false unless auth_params date = auth_params["date"] nonce = auth_params["nonce"] validate_signature(auth_params["signature"], :secret => secret, :method => "GET", :path => uri.path, :date => date, :nonce => nonce, :query => query_values, :headers => {}) end
ruby
def validate_url_signature(url, secret, opts = {}) opts = default_opts.merge(opts) opts[:query_based] = true uri = parse_url(url) query_values = Rack::Utils.parse_nested_query(uri.query) return false unless query_values auth_params = query_values.delete(opts[:auth_param]) return false unless auth_params date = auth_params["date"] nonce = auth_params["nonce"] validate_signature(auth_params["signature"], :secret => secret, :method => "GET", :path => uri.path, :date => date, :nonce => nonce, :query => query_values, :headers => {}) end
[ "def", "validate_url_signature", "(", "url", ",", "secret", ",", "opts", "=", "{", "}", ")", "opts", "=", "default_opts", ".", "merge", "(", "opts", ")", "opts", "[", ":query_based", "]", "=", "true", "uri", "=", "parse_url", "(", "url", ")", "query_values", "=", "Rack", "::", "Utils", ".", "parse_nested_query", "(", "uri", ".", "query", ")", "return", "false", "unless", "query_values", "auth_params", "=", "query_values", ".", "delete", "(", "opts", "[", ":auth_param", "]", ")", "return", "false", "unless", "auth_params", "date", "=", "auth_params", "[", "\"date\"", "]", "nonce", "=", "auth_params", "[", "\"nonce\"", "]", "validate_signature", "(", "auth_params", "[", "\"signature\"", "]", ",", ":secret", "=>", "secret", ",", ":method", "=>", "\"GET\"", ",", ":path", "=>", "uri", ".", "path", ",", ":date", "=>", "date", ",", ":nonce", "=>", "nonce", ",", ":query", "=>", "query_values", ",", ":headers", "=>", "{", "}", ")", "end" ]
convienience method to check the signature of a url with query-based authentication @param [String] url the url to test @param [String] secret the secret used to sign the url @param [Hash] opts Options controlling the singature generation @option opts [String] :auth_param ('auth') The name of the authentication param to use for query based authentication @return [Bool] true if the signature is valid
[ "convienience", "method", "to", "check", "the", "signature", "of", "a", "url", "with", "query", "-", "based", "authentication" ]
10005a8d205411405e7f5f5d5711c3c2228b5b71
https://github.com/Asquera/warden-hmac-authentication/blob/10005a8d205411405e7f5f5d5711c3c2228b5b71/lib/hmac/signer.rb#L119-L133
23,214
Asquera/warden-hmac-authentication
lib/hmac/signer.rb
HMAC.Signer.canonical_representation
def canonical_representation(params) rep = "" rep << "#{params[:method].upcase}\n" rep << "date:#{params[:date]}\n" rep << "nonce:#{params[:nonce]}\n" (params[:headers] || {}).sort.each do |pair| name,value = *pair rep << "#{name.downcase}:#{value}\n" end rep << params[:path] p = (params[:query] || {}).dup if !p.empty? query = p.sort.map do |key, value| "%{key}=%{value}" % { :key => Rack::Utils.unescape(key.to_s), :value => Rack::Utils.unescape(value.to_s) } end.join("&") rep << "?#{query}" end rep end
ruby
def canonical_representation(params) rep = "" rep << "#{params[:method].upcase}\n" rep << "date:#{params[:date]}\n" rep << "nonce:#{params[:nonce]}\n" (params[:headers] || {}).sort.each do |pair| name,value = *pair rep << "#{name.downcase}:#{value}\n" end rep << params[:path] p = (params[:query] || {}).dup if !p.empty? query = p.sort.map do |key, value| "%{key}=%{value}" % { :key => Rack::Utils.unescape(key.to_s), :value => Rack::Utils.unescape(value.to_s) } end.join("&") rep << "?#{query}" end rep end
[ "def", "canonical_representation", "(", "params", ")", "rep", "=", "\"\"", "rep", "<<", "\"#{params[:method].upcase}\\n\"", "rep", "<<", "\"date:#{params[:date]}\\n\"", "rep", "<<", "\"nonce:#{params[:nonce]}\\n\"", "(", "params", "[", ":headers", "]", "||", "{", "}", ")", ".", "sort", ".", "each", "do", "|", "pair", "|", "name", ",", "value", "=", "pair", "rep", "<<", "\"#{name.downcase}:#{value}\\n\"", "end", "rep", "<<", "params", "[", ":path", "]", "p", "=", "(", "params", "[", ":query", "]", "||", "{", "}", ")", ".", "dup", "if", "!", "p", ".", "empty?", "query", "=", "p", ".", "sort", ".", "map", "do", "|", "key", ",", "value", "|", "\"%{key}=%{value}\"", "%", "{", ":key", "=>", "Rack", "::", "Utils", ".", "unescape", "(", "key", ".", "to_s", ")", ",", ":value", "=>", "Rack", "::", "Utils", ".", "unescape", "(", "value", ".", "to_s", ")", "}", "end", ".", "join", "(", "\"&\"", ")", "rep", "<<", "\"?#{query}\"", "end", "rep", "end" ]
generates the canonical representation for a given request @param [Hash] params the parameters to create the representation with @option params [String] :method The HTTP Verb of the request @option params [String] :date The date of the request as it was formatted in the request @option params [String] :nonce ('') The nonce given in the request @option params [String] :path The path portion of the request @option params [Hash] :query ({}) The query parameters given in the request. Must not contain the auth param. @option params [Hash] :headers ({}) All headers given in the request (optional and required) @option params [String] :auth_scheme ('HMAC') The name of the authorization scheme used in the Authorization header and to construct various header-names @option params [String] :auth_param ('auth') The name of the authentication param to use for query based authentication @option params [Hash] :extra_auth_params ({}) Additional parameters to inject in the auth parameter @option params [Array<Symbol>] :ignore_params ([]) Params to ignore for signing @option params [String] :auth_header ('Authorization') The name of the authorization header to use @option params [String] :auth_header_format ('%{auth_scheme} %{signature}') The format of the authorization header. Will be interpolated with the given options and the signature. @option params [String] :nonce_header ('X-#{auth_scheme}-Nonce') The header name for the request nonce @option params [String] :alternate_date_header ('X-#{auth_scheme}-Date') The header name for the alternate date header @option params [Bool] :query_based (false) Whether to use query based authentication @option params [Bool] :use_alternate_date_header (false) Use the alternate date header instead of `Date` @return [String] the canonical representation
[ "generates", "the", "canonical", "representation", "for", "a", "given", "request" ]
10005a8d205411405e7f5f5d5711c3c2228b5b71
https://github.com/Asquera/warden-hmac-authentication/blob/10005a8d205411405e7f5f5d5711c3c2228b5b71/lib/hmac/signer.rb#L156-L183
23,215
Asquera/warden-hmac-authentication
lib/hmac/signer.rb
HMAC.Signer.sign_request
def sign_request(url, secret, opts = {}) opts = default_opts.merge(opts) uri = parse_url(url) headers = opts[:headers] || {} date = opts[:date] || Time.now.gmtime date = date.gmtime.strftime('%a, %d %b %Y %T GMT') if date.respond_to? :strftime method = opts[:method] ? opts[:method].to_s.upcase : "GET" query_values = Rack::Utils.parse_nested_query(uri.query) if query_values query_values.delete_if do |k,v| opts[:ignore_params].one? { |param| (k == param) || (k == param.to_s) } end end signature = generate_signature(:secret => secret, :method => method, :path => uri.path, :date => date, :nonce => opts[:nonce], :query => query_values, :headers => opts[:headers], :ignore_params => opts[:ignore_params]) if opts[:query_based] auth_params = opts[:extra_auth_params].merge({ "date" => date, "signature" => signature }) auth_params[:nonce] = opts[:nonce] unless opts[:nonce].nil? query_values ||= {} query_values[opts[:auth_param]] = auth_params uri.query = Rack::Utils.build_nested_query(query_values) else headers[opts[:auth_header]] = opts[:auth_header_format] % opts.merge({:signature => signature}) headers[opts[:nonce_header]] = opts[:nonce] unless opts[:nonce].nil? if opts[:use_alternate_date_header] headers[opts[:alternate_date_header]] = date else headers["Date"] = date end end [headers, uri.to_s] end
ruby
def sign_request(url, secret, opts = {}) opts = default_opts.merge(opts) uri = parse_url(url) headers = opts[:headers] || {} date = opts[:date] || Time.now.gmtime date = date.gmtime.strftime('%a, %d %b %Y %T GMT') if date.respond_to? :strftime method = opts[:method] ? opts[:method].to_s.upcase : "GET" query_values = Rack::Utils.parse_nested_query(uri.query) if query_values query_values.delete_if do |k,v| opts[:ignore_params].one? { |param| (k == param) || (k == param.to_s) } end end signature = generate_signature(:secret => secret, :method => method, :path => uri.path, :date => date, :nonce => opts[:nonce], :query => query_values, :headers => opts[:headers], :ignore_params => opts[:ignore_params]) if opts[:query_based] auth_params = opts[:extra_auth_params].merge({ "date" => date, "signature" => signature }) auth_params[:nonce] = opts[:nonce] unless opts[:nonce].nil? query_values ||= {} query_values[opts[:auth_param]] = auth_params uri.query = Rack::Utils.build_nested_query(query_values) else headers[opts[:auth_header]] = opts[:auth_header_format] % opts.merge({:signature => signature}) headers[opts[:nonce_header]] = opts[:nonce] unless opts[:nonce].nil? if opts[:use_alternate_date_header] headers[opts[:alternate_date_header]] = date else headers["Date"] = date end end [headers, uri.to_s] end
[ "def", "sign_request", "(", "url", ",", "secret", ",", "opts", "=", "{", "}", ")", "opts", "=", "default_opts", ".", "merge", "(", "opts", ")", "uri", "=", "parse_url", "(", "url", ")", "headers", "=", "opts", "[", ":headers", "]", "||", "{", "}", "date", "=", "opts", "[", ":date", "]", "||", "Time", ".", "now", ".", "gmtime", "date", "=", "date", ".", "gmtime", ".", "strftime", "(", "'%a, %d %b %Y %T GMT'", ")", "if", "date", ".", "respond_to?", ":strftime", "method", "=", "opts", "[", ":method", "]", "?", "opts", "[", ":method", "]", ".", "to_s", ".", "upcase", ":", "\"GET\"", "query_values", "=", "Rack", "::", "Utils", ".", "parse_nested_query", "(", "uri", ".", "query", ")", "if", "query_values", "query_values", ".", "delete_if", "do", "|", "k", ",", "v", "|", "opts", "[", ":ignore_params", "]", ".", "one?", "{", "|", "param", "|", "(", "k", "==", "param", ")", "||", "(", "k", "==", "param", ".", "to_s", ")", "}", "end", "end", "signature", "=", "generate_signature", "(", ":secret", "=>", "secret", ",", ":method", "=>", "method", ",", ":path", "=>", "uri", ".", "path", ",", ":date", "=>", "date", ",", ":nonce", "=>", "opts", "[", ":nonce", "]", ",", ":query", "=>", "query_values", ",", ":headers", "=>", "opts", "[", ":headers", "]", ",", ":ignore_params", "=>", "opts", "[", ":ignore_params", "]", ")", "if", "opts", "[", ":query_based", "]", "auth_params", "=", "opts", "[", ":extra_auth_params", "]", ".", "merge", "(", "{", "\"date\"", "=>", "date", ",", "\"signature\"", "=>", "signature", "}", ")", "auth_params", "[", ":nonce", "]", "=", "opts", "[", ":nonce", "]", "unless", "opts", "[", ":nonce", "]", ".", "nil?", "query_values", "||=", "{", "}", "query_values", "[", "opts", "[", ":auth_param", "]", "]", "=", "auth_params", "uri", ".", "query", "=", "Rack", "::", "Utils", ".", "build_nested_query", "(", "query_values", ")", "else", "headers", "[", "opts", "[", ":auth_header", "]", "]", "=", "opts", "[", ":auth_header_format", "]", "%", "opts", ".", "merge", "(", "{", ":signature", "=>", "signature", "}", ")", "headers", "[", "opts", "[", ":nonce_header", "]", "]", "=", "opts", "[", ":nonce", "]", "unless", "opts", "[", ":nonce", "]", ".", "nil?", "if", "opts", "[", ":use_alternate_date_header", "]", "headers", "[", "opts", "[", ":alternate_date_header", "]", "]", "=", "date", "else", "headers", "[", "\"Date\"", "]", "=", "date", "end", "end", "[", "headers", ",", "uri", ".", "to_s", "]", "end" ]
sign the given request @param [String] url The url of the request @param [String] secret The shared secret for the signature @param [Hash] opts Options for the signature generation @option opts [String] :nonce ('') The nonce to use in the signature @option opts [String, #strftime] :date (Time.now) The date to use in the signature @option opts [Hash] :headers ({}) A list of optional headers to include in the signature @option opts [String,Symbol] :method ('GET') The HTTP method to use in the signature @option opts [String] :auth_scheme ('HMAC') The name of the authorization scheme used in the Authorization header and to construct various header-names @option opts [String] :auth_param ('auth') The name of the authentication param to use for query based authentication @option opts [Hash] :extra_auth_params ({}) Additional parameters to inject in the auth parameter @option opts [Array<Symbol>] :ignore_params ([]) Params to ignore for signing @option opts [String] :auth_header ('Authorization') The name of the authorization header to use @option opts [String] :auth_header_format ('%{auth_scheme} %{signature}') The format of the authorization header. Will be interpolated with the given options and the signature. @option opts [String] :nonce_header ('X-#{auth_scheme}-Nonce') The header name for the request nonce @option opts [String] :alternate_date_header ('X-#{auth_scheme}-Date') The header name for the alternate date header @option opts [Bool] :query_based (false) Whether to use query based authentication @option opts [Bool] :use_alternate_date_header (false) Use the alternate date header instead of `Date`
[ "sign", "the", "given", "request" ]
10005a8d205411405e7f5f5d5711c3c2228b5b71
https://github.com/Asquera/warden-hmac-authentication/blob/10005a8d205411405e7f5f5d5711c3c2228b5b71/lib/hmac/signer.rb#L207-L250
23,216
Asquera/warden-hmac-authentication
lib/hmac/signer.rb
HMAC.Signer.sign_url
def sign_url(url, secret, opts = {}) opts = default_opts.merge(opts) opts[:query_based] = true headers, url = *sign_request(url, secret, opts) url end
ruby
def sign_url(url, secret, opts = {}) opts = default_opts.merge(opts) opts[:query_based] = true headers, url = *sign_request(url, secret, opts) url end
[ "def", "sign_url", "(", "url", ",", "secret", ",", "opts", "=", "{", "}", ")", "opts", "=", "default_opts", ".", "merge", "(", "opts", ")", "opts", "[", ":query_based", "]", "=", "true", "headers", ",", "url", "=", "sign_request", "(", "url", ",", "secret", ",", "opts", ")", "url", "end" ]
convienience method to sign a url for use with query-based authentication @param [String] url the url to sign @param [String] secret the secret used to sign the url @param [Hash] opts Options controlling the singature generation @option opts [String] :auth_param ('auth') The name of the authentication param to use for query based authentication @option opts [Hash] :extra_auth_params ({}) Additional parameters to inject in the auth parameter @return [String] The signed url
[ "convienience", "method", "to", "sign", "a", "url", "for", "use", "with", "query", "-", "based", "authentication" ]
10005a8d205411405e7f5f5d5711c3c2228b5b71
https://github.com/Asquera/warden-hmac-authentication/blob/10005a8d205411405e7f5f5d5711c3c2228b5b71/lib/hmac/signer.rb#L262-L268
23,217
turboladen/playful
lib/playful/device.rb
Playful.Device.start
def start EM.synchrony do web_server = Thin::Server.start('0.0.0.0', 3000) do use Rack::CommonLogger use Rack::ShowExceptions map '/presentation' do use Rack::Lint run Rack::Lobster.new end end # Do advertisement # Listen for subscribers end end
ruby
def start EM.synchrony do web_server = Thin::Server.start('0.0.0.0', 3000) do use Rack::CommonLogger use Rack::ShowExceptions map '/presentation' do use Rack::Lint run Rack::Lobster.new end end # Do advertisement # Listen for subscribers end end
[ "def", "start", "EM", ".", "synchrony", "do", "web_server", "=", "Thin", "::", "Server", ".", "start", "(", "'0.0.0.0'", ",", "3000", ")", "do", "use", "Rack", "::", "CommonLogger", "use", "Rack", "::", "ShowExceptions", "map", "'/presentation'", "do", "use", "Rack", "::", "Lint", "run", "Rack", "::", "Lobster", ".", "new", "end", "end", "# Do advertisement", "# Listen for subscribers", "end", "end" ]
Multicasts discovery messages to advertise its root device, any embedded devices, and any services.
[ "Multicasts", "discovery", "messages", "to", "advertise", "its", "root", "device", "any", "embedded", "devices", "and", "any", "services", "." ]
86f9dcab0ef98818f0317ebe6efe8e3e611ae050
https://github.com/turboladen/playful/blob/86f9dcab0ef98818f0317ebe6efe8e3e611ae050/lib/playful/device.rb#L11-L26
23,218
abrt/satyr
ruby/lib/satyr.rb
Satyr.Report.stacktrace
def stacktrace stacktrace = @struct[:stacktrace] return nil if stacktrace.null? # There's no sr_stacktrace_dup in libsatyr.so.3, we've got to find out # the type ourselves. dup = case @struct[:type] when :core Satyr::FFI.sr_core_stacktrace_dup(stacktrace) when :python Satyr::FFI.sr_python_stacktrace_dup(stacktrace) when :kerneloops Satyr::FFI.sr_koops_stacktrace_dup(stacktrace) when :java Satyr::FFI.sr_java_stacktrace_dup(stacktrace) when :gdb Satyr::FFI.sr_gdb_stacktrace_dup(stacktrace) else raise SatyrError, "Invalid report type" end raise SatyrError, "Failed to obtain stacktrace" if dup.null? Stacktrace.send(:new, dup) end
ruby
def stacktrace stacktrace = @struct[:stacktrace] return nil if stacktrace.null? # There's no sr_stacktrace_dup in libsatyr.so.3, we've got to find out # the type ourselves. dup = case @struct[:type] when :core Satyr::FFI.sr_core_stacktrace_dup(stacktrace) when :python Satyr::FFI.sr_python_stacktrace_dup(stacktrace) when :kerneloops Satyr::FFI.sr_koops_stacktrace_dup(stacktrace) when :java Satyr::FFI.sr_java_stacktrace_dup(stacktrace) when :gdb Satyr::FFI.sr_gdb_stacktrace_dup(stacktrace) else raise SatyrError, "Invalid report type" end raise SatyrError, "Failed to obtain stacktrace" if dup.null? Stacktrace.send(:new, dup) end
[ "def", "stacktrace", "stacktrace", "=", "@struct", "[", ":stacktrace", "]", "return", "nil", "if", "stacktrace", ".", "null?", "# There's no sr_stacktrace_dup in libsatyr.so.3, we've got to find out", "# the type ourselves.", "dup", "=", "case", "@struct", "[", ":type", "]", "when", ":core", "Satyr", "::", "FFI", ".", "sr_core_stacktrace_dup", "(", "stacktrace", ")", "when", ":python", "Satyr", "::", "FFI", ".", "sr_python_stacktrace_dup", "(", "stacktrace", ")", "when", ":kerneloops", "Satyr", "::", "FFI", ".", "sr_koops_stacktrace_dup", "(", "stacktrace", ")", "when", ":java", "Satyr", "::", "FFI", ".", "sr_java_stacktrace_dup", "(", "stacktrace", ")", "when", ":gdb", "Satyr", "::", "FFI", ".", "sr_gdb_stacktrace_dup", "(", "stacktrace", ")", "else", "raise", "SatyrError", ",", "\"Invalid report type\"", "end", "raise", "SatyrError", ",", "\"Failed to obtain stacktrace\"", "if", "dup", ".", "null?", "Stacktrace", ".", "send", "(", ":new", ",", "dup", ")", "end" ]
Parses given JSON string to create new Report Returns Stacktrace of the report
[ "Parses", "given", "JSON", "string", "to", "create", "new", "Report", "Returns", "Stacktrace", "of", "the", "report" ]
dff1b877d42bf2153f8f090905d9cc8fb333bf1e
https://github.com/abrt/satyr/blob/dff1b877d42bf2153f8f090905d9cc8fb333bf1e/ruby/lib/satyr.rb#L108-L132
23,219
abrt/satyr
ruby/lib/satyr.rb
Satyr.Stacktrace.find_crash_thread
def find_crash_thread pointer = Satyr::FFI.sr_stacktrace_find_crash_thread @struct.to_ptr raise SatyrError, "Could not find crash thread" if pointer.null? dup = Satyr::FFI.sr_thread_dup(pointer) raise SatyrError, "Failed to duplicate thread" if dup.null? Thread.send(:new, dup) end
ruby
def find_crash_thread pointer = Satyr::FFI.sr_stacktrace_find_crash_thread @struct.to_ptr raise SatyrError, "Could not find crash thread" if pointer.null? dup = Satyr::FFI.sr_thread_dup(pointer) raise SatyrError, "Failed to duplicate thread" if dup.null? Thread.send(:new, dup) end
[ "def", "find_crash_thread", "pointer", "=", "Satyr", "::", "FFI", ".", "sr_stacktrace_find_crash_thread", "@struct", ".", "to_ptr", "raise", "SatyrError", ",", "\"Could not find crash thread\"", "if", "pointer", ".", "null?", "dup", "=", "Satyr", "::", "FFI", ".", "sr_thread_dup", "(", "pointer", ")", "raise", "SatyrError", ",", "\"Failed to duplicate thread\"", "if", "dup", ".", "null?", "Thread", ".", "send", "(", ":new", ",", "dup", ")", "end" ]
Returns Thread that likely caused the crash that produced this stack trace
[ "Returns", "Thread", "that", "likely", "caused", "the", "crash", "that", "produced", "this", "stack", "trace" ]
dff1b877d42bf2153f8f090905d9cc8fb333bf1e
https://github.com/abrt/satyr/blob/dff1b877d42bf2153f8f090905d9cc8fb333bf1e/ruby/lib/satyr.rb#L147-L154
23,220
ms-ati/rumonade
lib/rumonade/option.rb
Rumonade.Option.get_or_else
def get_or_else(val_or_lam = nil, &blk) v_or_f = val_or_lam || blk if !empty? then value else (v_or_f.respond_to?(:call) ? v_or_f.call : v_or_f) end end
ruby
def get_or_else(val_or_lam = nil, &blk) v_or_f = val_or_lam || blk if !empty? then value else (v_or_f.respond_to?(:call) ? v_or_f.call : v_or_f) end end
[ "def", "get_or_else", "(", "val_or_lam", "=", "nil", ",", "&", "blk", ")", "v_or_f", "=", "val_or_lam", "||", "blk", "if", "!", "empty?", "then", "value", "else", "(", "v_or_f", ".", "respond_to?", "(", ":call", ")", "?", "v_or_f", ".", "call", ":", "v_or_f", ")", "end", "end" ]
Returns contents if Some, or given value or result of given block or lambda if None
[ "Returns", "contents", "if", "Some", "or", "given", "value", "or", "result", "of", "given", "block", "or", "lambda", "if", "None" ]
e439a37ccc1c96a28332ef31b53d1ba830640b9f
https://github.com/ms-ati/rumonade/blob/e439a37ccc1c96a28332ef31b53d1ba830640b9f/lib/rumonade/option.rb#L75-L78
23,221
guideline-tech/subroutine
lib/subroutine/op.rb
Subroutine.Op.inherit_errors
def inherit_errors(error_object) error_object = error_object.errors if error_object.respond_to?(:errors) error_object.each do |k, v| next if _error_ignores[k.to_sym] if respond_to?(k) errors.add(k, v) elsif _error_map[k.to_sym] errors.add(_error_map[k.to_sym], v) else errors.add(:base, error_object.full_message(k, v)) end end false end
ruby
def inherit_errors(error_object) error_object = error_object.errors if error_object.respond_to?(:errors) error_object.each do |k, v| next if _error_ignores[k.to_sym] if respond_to?(k) errors.add(k, v) elsif _error_map[k.to_sym] errors.add(_error_map[k.to_sym], v) else errors.add(:base, error_object.full_message(k, v)) end end false end
[ "def", "inherit_errors", "(", "error_object", ")", "error_object", "=", "error_object", ".", "errors", "if", "error_object", ".", "respond_to?", "(", ":errors", ")", "error_object", ".", "each", "do", "|", "k", ",", "v", "|", "next", "if", "_error_ignores", "[", "k", ".", "to_sym", "]", "if", "respond_to?", "(", "k", ")", "errors", ".", "add", "(", "k", ",", "v", ")", "elsif", "_error_map", "[", "k", ".", "to_sym", "]", "errors", ".", "add", "(", "_error_map", "[", "k", ".", "to_sym", "]", ",", "v", ")", "else", "errors", ".", "add", "(", ":base", ",", "error_object", ".", "full_message", "(", "k", ",", "v", ")", ")", "end", "end", "false", "end" ]
applies the errors in error_object to self returns false so failure cases can end with this invocation
[ "applies", "the", "errors", "in", "error_object", "to", "self", "returns", "false", "so", "failure", "cases", "can", "end", "with", "this", "invocation" ]
76e501bb82e444ed7e7a1379d57f2b76effb1cf8
https://github.com/guideline-tech/subroutine/blob/76e501bb82e444ed7e7a1379d57f2b76effb1cf8/lib/subroutine/op.rb#L258-L274
23,222
guideline-tech/subroutine
lib/subroutine/op.rb
Subroutine.Op.sanitize_params
def sanitize_params(inputs) out = {}.with_indifferent_access _fields.each_pair do |field, config| next unless inputs.key?(field) out[field] = ::Subroutine::TypeCaster.cast(inputs[field], config) end out end
ruby
def sanitize_params(inputs) out = {}.with_indifferent_access _fields.each_pair do |field, config| next unless inputs.key?(field) out[field] = ::Subroutine::TypeCaster.cast(inputs[field], config) end out end
[ "def", "sanitize_params", "(", "inputs", ")", "out", "=", "{", "}", ".", "with_indifferent_access", "_fields", ".", "each_pair", "do", "|", "field", ",", "config", "|", "next", "unless", "inputs", ".", "key?", "(", "field", ")", "out", "[", "field", "]", "=", "::", "Subroutine", "::", "TypeCaster", ".", "cast", "(", "inputs", "[", "field", "]", ",", "config", ")", "end", "out", "end" ]
if you want to use strong parameters or something in your form object you can do so here. by default we just slice the inputs to the defined fields
[ "if", "you", "want", "to", "use", "strong", "parameters", "or", "something", "in", "your", "form", "object", "you", "can", "do", "so", "here", ".", "by", "default", "we", "just", "slice", "the", "inputs", "to", "the", "defined", "fields" ]
76e501bb82e444ed7e7a1379d57f2b76effb1cf8
https://github.com/guideline-tech/subroutine/blob/76e501bb82e444ed7e7a1379d57f2b76effb1cf8/lib/subroutine/op.rb#L278-L287
23,223
ms-ati/rumonade
lib/rumonade/error_handling.rb
Rumonade.PartialFunction.or_else
def or_else(other) PartialFunction.new(lambda { |x| self.defined_at?(x) || other.defined_at?(x) }, lambda { |x| if self.defined_at?(x) then self.call(x) else other.call(x) end }) end
ruby
def or_else(other) PartialFunction.new(lambda { |x| self.defined_at?(x) || other.defined_at?(x) }, lambda { |x| if self.defined_at?(x) then self.call(x) else other.call(x) end }) end
[ "def", "or_else", "(", "other", ")", "PartialFunction", ".", "new", "(", "lambda", "{", "|", "x", "|", "self", ".", "defined_at?", "(", "x", ")", "||", "other", ".", "defined_at?", "(", "x", ")", "}", ",", "lambda", "{", "|", "x", "|", "if", "self", ".", "defined_at?", "(", "x", ")", "then", "self", ".", "call", "(", "x", ")", "else", "other", ".", "call", "(", "x", ")", "end", "}", ")", "end" ]
Composes this partial function with a fallback partial function which gets applied where this partial function is not defined. @param [PartialFunction] other the fallback function @return [PartialFunction] a partial function which has as domain the union of the domains of this partial function and +other+. The resulting partial function takes +x+ to +self.call(x)+ where +self+ is defined, and to +other.call(x)+ where it is not.
[ "Composes", "this", "partial", "function", "with", "a", "fallback", "partial", "function", "which", "gets", "applied", "where", "this", "partial", "function", "is", "not", "defined", "." ]
e439a37ccc1c96a28332ef31b53d1ba830640b9f
https://github.com/ms-ati/rumonade/blob/e439a37ccc1c96a28332ef31b53d1ba830640b9f/lib/rumonade/error_handling.rb#L30-L33
23,224
ms-ati/rumonade
lib/rumonade/error_handling.rb
Rumonade.PartialFunction.and_then
def and_then(func) PartialFunction.new(@defined_at_proc, lambda { |x| func.call(self.call(x)) }) end
ruby
def and_then(func) PartialFunction.new(@defined_at_proc, lambda { |x| func.call(self.call(x)) }) end
[ "def", "and_then", "(", "func", ")", "PartialFunction", ".", "new", "(", "@defined_at_proc", ",", "lambda", "{", "|", "x", "|", "func", ".", "call", "(", "self", ".", "call", "(", "x", ")", ")", "}", ")", "end" ]
Composes this partial function with a transformation function that gets applied to results of this partial function. @param [Proc] func the transformation function @return [PartialFunction] a partial function with the same domain as this partial function, which maps arguments +x+ to +func.call(self.call(x))+.
[ "Composes", "this", "partial", "function", "with", "a", "transformation", "function", "that", "gets", "applied", "to", "results", "of", "this", "partial", "function", "." ]
e439a37ccc1c96a28332ef31b53d1ba830640b9f
https://github.com/ms-ati/rumonade/blob/e439a37ccc1c96a28332ef31b53d1ba830640b9f/lib/rumonade/error_handling.rb#L40-L42
23,225
uploadcare/uploadcare-ruby
lib/uploadcare/api/raw_api.rb
Uploadcare.RawApi.request
def request(method = :get, path = '/files/', params = {}) response = @api_connection.send method, path, params response.body end
ruby
def request(method = :get, path = '/files/', params = {}) response = @api_connection.send method, path, params response.body end
[ "def", "request", "(", "method", "=", ":get", ",", "path", "=", "'/files/'", ",", "params", "=", "{", "}", ")", "response", "=", "@api_connection", ".", "send", "method", ",", "path", ",", "params", "response", ".", "body", "end" ]
basic request method
[ "basic", "request", "method" ]
f78e510af0b2ec0e4135e12d444b7793b0a1e75c
https://github.com/uploadcare/uploadcare-ruby/blob/f78e510af0b2ec0e4135e12d444b7793b0a1e75c/lib/uploadcare/api/raw_api.rb#L12-L15
23,226
uploadcare/uploadcare-ruby
lib/uploadcare/api/uploading_api.rb
Uploadcare.UploadingApi.upload
def upload(object, options = {}) if file?(object) then upload_file(object, options) elsif object.is_a?(Array) then upload_files(object, options) elsif object.is_a?(String) then upload_url(object, options) else raise ArgumentError, "Expected input to be a file/Array/URL, given: `#{object}`" end end
ruby
def upload(object, options = {}) if file?(object) then upload_file(object, options) elsif object.is_a?(Array) then upload_files(object, options) elsif object.is_a?(String) then upload_url(object, options) else raise ArgumentError, "Expected input to be a file/Array/URL, given: `#{object}`" end end
[ "def", "upload", "(", "object", ",", "options", "=", "{", "}", ")", "if", "file?", "(", "object", ")", "then", "upload_file", "(", "object", ",", "options", ")", "elsif", "object", ".", "is_a?", "(", "Array", ")", "then", "upload_files", "(", "object", ",", "options", ")", "elsif", "object", ".", "is_a?", "(", "String", ")", "then", "upload_url", "(", "object", ",", "options", ")", "else", "raise", "ArgumentError", ",", "\"Expected input to be a file/Array/URL, given: `#{object}`\"", "end", "end" ]
intelegent guess for file or URL uploading
[ "intelegent", "guess", "for", "file", "or", "URL", "uploading" ]
f78e510af0b2ec0e4135e12d444b7793b0a1e75c
https://github.com/uploadcare/uploadcare-ruby/blob/f78e510af0b2ec0e4135e12d444b7793b0a1e75c/lib/uploadcare/api/uploading_api.rb#L6-L13
23,227
uploadcare/uploadcare-ruby
lib/uploadcare/api/uploading_api.rb
Uploadcare.UploadingApi.upload_files
def upload_files(files, options = {}) data = upload_params(options).for_file_upload(files) response = @upload_connection.post('/base/', data) response.body.values.map! { |f| Uploadcare::Api::File.new(self, f) } end
ruby
def upload_files(files, options = {}) data = upload_params(options).for_file_upload(files) response = @upload_connection.post('/base/', data) response.body.values.map! { |f| Uploadcare::Api::File.new(self, f) } end
[ "def", "upload_files", "(", "files", ",", "options", "=", "{", "}", ")", "data", "=", "upload_params", "(", "options", ")", ".", "for_file_upload", "(", "files", ")", "response", "=", "@upload_connection", ".", "post", "(", "'/base/'", ",", "data", ")", "response", ".", "body", ".", "values", ".", "map!", "{", "|", "f", "|", "Uploadcare", "::", "Api", "::", "File", ".", "new", "(", "self", ",", "f", ")", "}", "end" ]
Upload multiple files
[ "Upload", "multiple", "files" ]
f78e510af0b2ec0e4135e12d444b7793b0a1e75c
https://github.com/uploadcare/uploadcare-ruby/blob/f78e510af0b2ec0e4135e12d444b7793b0a1e75c/lib/uploadcare/api/uploading_api.rb#L16-L22
23,228
uploadcare/uploadcare-ruby
lib/uploadcare/api/uploading_api.rb
Uploadcare.UploadingApi.upload_url
def upload_url(url, options = {}) params = upload_params(options).for_url_upload(url) token = request_file_upload(params) upload_status = poll_upload_result(token) if upload_status['status'] == 'error' raise ArgumentError.new(upload_status['error']) end Uploadcare::Api::File.new(self, upload_status['file_id']) end
ruby
def upload_url(url, options = {}) params = upload_params(options).for_url_upload(url) token = request_file_upload(params) upload_status = poll_upload_result(token) if upload_status['status'] == 'error' raise ArgumentError.new(upload_status['error']) end Uploadcare::Api::File.new(self, upload_status['file_id']) end
[ "def", "upload_url", "(", "url", ",", "options", "=", "{", "}", ")", "params", "=", "upload_params", "(", "options", ")", ".", "for_url_upload", "(", "url", ")", "token", "=", "request_file_upload", "(", "params", ")", "upload_status", "=", "poll_upload_result", "(", "token", ")", "if", "upload_status", "[", "'status'", "]", "==", "'error'", "raise", "ArgumentError", ".", "new", "(", "upload_status", "[", "'error'", "]", ")", "end", "Uploadcare", "::", "Api", "::", "File", ".", "new", "(", "self", ",", "upload_status", "[", "'file_id'", "]", ")", "end" ]
Upload from an URL
[ "Upload", "from", "an", "URL" ]
f78e510af0b2ec0e4135e12d444b7793b0a1e75c
https://github.com/uploadcare/uploadcare-ruby/blob/f78e510af0b2ec0e4135e12d444b7793b0a1e75c/lib/uploadcare/api/uploading_api.rb#L31-L41
23,229
nukeproof/oanda_api
lib/oanda_api/throttling/throttling.rb
OandaAPI.Throttling.restore_original_new_method
def restore_original_new_method(klass) klass.define_singleton_method :new do |*args, &block| Throttling.original_new_method(klass).bind(klass).call *args, &block end end
ruby
def restore_original_new_method(klass) klass.define_singleton_method :new do |*args, &block| Throttling.original_new_method(klass).bind(klass).call *args, &block end end
[ "def", "restore_original_new_method", "(", "klass", ")", "klass", ".", "define_singleton_method", ":new", "do", "|", "*", "args", ",", "&", "block", "|", "Throttling", ".", "original_new_method", "(", "klass", ")", ".", "bind", "(", "klass", ")", ".", "call", "args", ",", "block", "end", "end" ]
Restores the original '.new' method of the including class @param klass [Class] the class that has included this module @return [void]
[ "Restores", "the", "original", ".", "new", "method", "of", "the", "including", "class" ]
8003a5ef9b2a3506faafa3e82c0666c5192d6771
https://github.com/nukeproof/oanda_api/blob/8003a5ef9b2a3506faafa3e82c0666c5192d6771/lib/oanda_api/throttling/throttling.rb#L44-L48
23,230
nukeproof/oanda_api
lib/oanda_api/throttling/throttling.rb
OandaAPI.Throttling.throttle_connection_rate
def throttle_connection_rate now = Time.now delta = now - (last_new_connection_at || now) _throttle(delta, now) if delta < OandaAPI.configuration.min_new_connection_interval && OandaAPI.configuration.use_request_throttling? self.last_new_connection_at = Time.now end
ruby
def throttle_connection_rate now = Time.now delta = now - (last_new_connection_at || now) _throttle(delta, now) if delta < OandaAPI.configuration.min_new_connection_interval && OandaAPI.configuration.use_request_throttling? self.last_new_connection_at = Time.now end
[ "def", "throttle_connection_rate", "now", "=", "Time", ".", "now", "delta", "=", "now", "-", "(", "last_new_connection_at", "||", "now", ")", "_throttle", "(", "delta", ",", "now", ")", "if", "delta", "<", "OandaAPI", ".", "configuration", ".", "min_new_connection_interval", "&&", "OandaAPI", ".", "configuration", ".", "use_request_throttling?", "self", ".", "last_new_connection_at", "=", "Time", ".", "now", "end" ]
Throttles the connection rate by sleeping for a duration if the interval bewteen consecutive connections is less than the allowed minimum. Only throttles when the API is configured to use_request_throttling. @return [void]
[ "Throttles", "the", "connection", "rate", "by", "sleeping", "for", "a", "duration", "if", "the", "interval", "bewteen", "consecutive", "connections", "is", "less", "than", "the", "allowed", "minimum", ".", "Only", "throttles", "when", "the", "API", "is", "configured", "to", "use_request_throttling", "." ]
8003a5ef9b2a3506faafa3e82c0666c5192d6771
https://github.com/nukeproof/oanda_api/blob/8003a5ef9b2a3506faafa3e82c0666c5192d6771/lib/oanda_api/throttling/throttling.rb#L55-L61
23,231
Tretti/rails-bootstrap-helpers
lib/rails-bootstrap-helpers/renderers/abstract_link_renderer.rb
RailsBootstrapHelpers::Renderers.AbstractLinkRenderer.append_class
def append_class (cls) return unless cls if c = html_options["class"] html_options["class"] << " " + cls.to_s else if c = has_option?("class") c << " " + cls.to_s cls = c end html_options["class"] = cls.to_s end end
ruby
def append_class (cls) return unless cls if c = html_options["class"] html_options["class"] << " " + cls.to_s else if c = has_option?("class") c << " " + cls.to_s cls = c end html_options["class"] = cls.to_s end end
[ "def", "append_class", "(", "cls", ")", "return", "unless", "cls", "if", "c", "=", "html_options", "[", "\"class\"", "]", "html_options", "[", "\"class\"", "]", "<<", "\" \"", "+", "cls", ".", "to_s", "else", "if", "c", "=", "has_option?", "(", "\"class\"", ")", "c", "<<", "\" \"", "+", "cls", ".", "to_s", "cls", "=", "c", "end", "html_options", "[", "\"class\"", "]", "=", "cls", ".", "to_s", "end", "end" ]
Appends the given class to the "class" HTMl attribute. @param cls [String, Symbol] the class to append
[ "Appends", "the", "given", "class", "to", "the", "class", "HTMl", "attribute", "." ]
98bc0458f864be3f21f1a53f1a265b15f9e0e883
https://github.com/Tretti/rails-bootstrap-helpers/blob/98bc0458f864be3f21f1a53f1a265b15f9e0e883/lib/rails-bootstrap-helpers/renderers/abstract_link_renderer.rb#L58-L71
23,232
github/darrrr
lib/darrrr/recovery_provider.rb
Darrrr.RecoveryProvider.countersign_token
def countersign_token(token:, context: nil, options: 0x00) begin account_provider = RecoveryToken.account_provider_issuer(token) rescue RecoveryTokenSerializationError, UnknownProviderError raise TokenFormatError, "Could not determine provider" end counter_recovery_token = RecoveryToken.build( issuer: self, audience: account_provider, type: COUNTERSIGNED_RECOVERY_TOKEN_TYPE, options: options, ) counter_recovery_token.data = token seal(counter_recovery_token, context) end
ruby
def countersign_token(token:, context: nil, options: 0x00) begin account_provider = RecoveryToken.account_provider_issuer(token) rescue RecoveryTokenSerializationError, UnknownProviderError raise TokenFormatError, "Could not determine provider" end counter_recovery_token = RecoveryToken.build( issuer: self, audience: account_provider, type: COUNTERSIGNED_RECOVERY_TOKEN_TYPE, options: options, ) counter_recovery_token.data = token seal(counter_recovery_token, context) end
[ "def", "countersign_token", "(", "token", ":", ",", "context", ":", "nil", ",", "options", ":", "0x00", ")", "begin", "account_provider", "=", "RecoveryToken", ".", "account_provider_issuer", "(", "token", ")", "rescue", "RecoveryTokenSerializationError", ",", "UnknownProviderError", "raise", "TokenFormatError", ",", "\"Could not determine provider\"", "end", "counter_recovery_token", "=", "RecoveryToken", ".", "build", "(", "issuer", ":", "self", ",", "audience", ":", "account_provider", ",", "type", ":", "COUNTERSIGNED_RECOVERY_TOKEN_TYPE", ",", "options", ":", "options", ",", ")", "counter_recovery_token", ".", "data", "=", "token", "seal", "(", "counter_recovery_token", ",", "context", ")", "end" ]
Takes a binary representation of a token and signs if for a given account provider. Do not pass in a RecoveryToken object. The wrapping data structure is identical to the structure it's wrapping in format. token: the to_binary_s or binary representation of the recovery token context: an arbitrary object that is passed to lower level crypto operations options: the value to set in the options byte field of the recovery token (defaults to 0x00) returns a Base64 encoded representation of the countersigned token and the signature over the token.
[ "Takes", "a", "binary", "representation", "of", "a", "token", "and", "signs", "if", "for", "a", "given", "account", "provider", ".", "Do", "not", "pass", "in", "a", "RecoveryToken", "object", ".", "The", "wrapping", "data", "structure", "is", "identical", "to", "the", "structure", "it", "s", "wrapping", "in", "format", "." ]
5519cc0cc208316c8cc891d797cc15570c919a5b
https://github.com/github/darrrr/blob/5519cc0cc208316c8cc891d797cc15570c919a5b/lib/darrrr/recovery_provider.rb#L75-L91
23,233
github/darrrr
lib/darrrr/recovery_provider.rb
Darrrr.RecoveryProvider.validate_recovery_token!
def validate_recovery_token!(token, context = {}) errors = [] # 1. Authenticate the User. The exact nature of how the Recovery Provider authenticates the User is beyond the scope of this specification. # handled in before_filter # 4. Retrieve the Account Provider configuration as described in Section 2 using the issuer field of the token as the subject. begin account_provider = RecoveryToken.account_provider_issuer(token) rescue RecoveryTokenSerializationError, UnknownProviderError, TokenFormatError => e raise RecoveryTokenError, "Could not determine provider: #{e.message}" end # 2. Parse the token. # 3. Validate that the version value is 0. # 5. Validate the signature over the token according to processing rules for the algorithm implied by the version. begin recovery_token = account_provider.unseal(token, context) rescue CryptoError => e raise RecoveryTokenError.new("Unable to verify signature of token") rescue TokenFormatError => e raise RecoveryTokenError.new(e.message) end # 6. Validate that the audience field of the token identifies an origin which the provider considers itself authoritative for. (Often the audience will be same-origin with the Recovery Provider, but other values may be acceptable, e.g. "https://mail.example.com" and "https://social.example.com" may be acceptable audiences for "https://recovery.example.com".) unless self.origin == recovery_token.audience raise RecoveryTokenError.new("Unnacceptable audience") end if DateTime.parse(recovery_token.issued_time).utc < (Time.now - CLOCK_SKEW).utc raise RecoveryTokenError.new("Issued at time is too far in the past") end recovery_token end
ruby
def validate_recovery_token!(token, context = {}) errors = [] # 1. Authenticate the User. The exact nature of how the Recovery Provider authenticates the User is beyond the scope of this specification. # handled in before_filter # 4. Retrieve the Account Provider configuration as described in Section 2 using the issuer field of the token as the subject. begin account_provider = RecoveryToken.account_provider_issuer(token) rescue RecoveryTokenSerializationError, UnknownProviderError, TokenFormatError => e raise RecoveryTokenError, "Could not determine provider: #{e.message}" end # 2. Parse the token. # 3. Validate that the version value is 0. # 5. Validate the signature over the token according to processing rules for the algorithm implied by the version. begin recovery_token = account_provider.unseal(token, context) rescue CryptoError => e raise RecoveryTokenError.new("Unable to verify signature of token") rescue TokenFormatError => e raise RecoveryTokenError.new(e.message) end # 6. Validate that the audience field of the token identifies an origin which the provider considers itself authoritative for. (Often the audience will be same-origin with the Recovery Provider, but other values may be acceptable, e.g. "https://mail.example.com" and "https://social.example.com" may be acceptable audiences for "https://recovery.example.com".) unless self.origin == recovery_token.audience raise RecoveryTokenError.new("Unnacceptable audience") end if DateTime.parse(recovery_token.issued_time).utc < (Time.now - CLOCK_SKEW).utc raise RecoveryTokenError.new("Issued at time is too far in the past") end recovery_token end
[ "def", "validate_recovery_token!", "(", "token", ",", "context", "=", "{", "}", ")", "errors", "=", "[", "]", "# 1. Authenticate the User. The exact nature of how the Recovery Provider authenticates the User is beyond the scope of this specification.", "# handled in before_filter", "# 4. Retrieve the Account Provider configuration as described in Section 2 using the issuer field of the token as the subject.", "begin", "account_provider", "=", "RecoveryToken", ".", "account_provider_issuer", "(", "token", ")", "rescue", "RecoveryTokenSerializationError", ",", "UnknownProviderError", ",", "TokenFormatError", "=>", "e", "raise", "RecoveryTokenError", ",", "\"Could not determine provider: #{e.message}\"", "end", "# 2. Parse the token.", "# 3. Validate that the version value is 0.", "# 5. Validate the signature over the token according to processing rules for the algorithm implied by the version.", "begin", "recovery_token", "=", "account_provider", ".", "unseal", "(", "token", ",", "context", ")", "rescue", "CryptoError", "=>", "e", "raise", "RecoveryTokenError", ".", "new", "(", "\"Unable to verify signature of token\"", ")", "rescue", "TokenFormatError", "=>", "e", "raise", "RecoveryTokenError", ".", "new", "(", "e", ".", "message", ")", "end", "# 6. Validate that the audience field of the token identifies an origin which the provider considers itself authoritative for. (Often the audience will be same-origin with the Recovery Provider, but other values may be acceptable, e.g. \"https://mail.example.com\" and \"https://social.example.com\" may be acceptable audiences for \"https://recovery.example.com\".)", "unless", "self", ".", "origin", "==", "recovery_token", ".", "audience", "raise", "RecoveryTokenError", ".", "new", "(", "\"Unnacceptable audience\"", ")", "end", "if", "DateTime", ".", "parse", "(", "recovery_token", ".", "issued_time", ")", ".", "utc", "<", "(", "Time", ".", "now", "-", "CLOCK_SKEW", ")", ".", "utc", "raise", "RecoveryTokenError", ".", "new", "(", "\"Issued at time is too far in the past\"", ")", "end", "recovery_token", "end" ]
Validate the token according to the processing instructions for the save-token endpoint. Returns a validated token
[ "Validate", "the", "token", "according", "to", "the", "processing", "instructions", "for", "the", "save", "-", "token", "endpoint", "." ]
5519cc0cc208316c8cc891d797cc15570c919a5b
https://github.com/github/darrrr/blob/5519cc0cc208316c8cc891d797cc15570c919a5b/lib/darrrr/recovery_provider.rb#L97-L131
23,234
github/darrrr
lib/darrrr/account_provider.rb
Darrrr.AccountProvider.generate_recovery_token
def generate_recovery_token(data:, audience:, context: nil, options: 0x00) token = RecoveryToken.build(issuer: self, audience: audience, type: RECOVERY_TOKEN_TYPE, options: options) token.data = self.encryptor.encrypt(data, self, context) [token, seal(token, context)] end
ruby
def generate_recovery_token(data:, audience:, context: nil, options: 0x00) token = RecoveryToken.build(issuer: self, audience: audience, type: RECOVERY_TOKEN_TYPE, options: options) token.data = self.encryptor.encrypt(data, self, context) [token, seal(token, context)] end
[ "def", "generate_recovery_token", "(", "data", ":", ",", "audience", ":", ",", "context", ":", "nil", ",", "options", ":", "0x00", ")", "token", "=", "RecoveryToken", ".", "build", "(", "issuer", ":", "self", ",", "audience", ":", "audience", ",", "type", ":", "RECOVERY_TOKEN_TYPE", ",", "options", ":", "options", ")", "token", ".", "data", "=", "self", ".", "encryptor", ".", "encrypt", "(", "data", ",", "self", ",", "context", ")", "[", "token", ",", "seal", "(", "token", ",", "context", ")", "]", "end" ]
Generates a binary token with an encrypted arbitrary data payload. data: value to encrypt in the token provider: the recovery provider/audience of the token context: arbitrary data passed on to underlying crypto operations options: the value to set for the options byte returns a [RecoveryToken, b64 encoded sealed_token] tuple
[ "Generates", "a", "binary", "token", "with", "an", "encrypted", "arbitrary", "data", "payload", "." ]
5519cc0cc208316c8cc891d797cc15570c919a5b
https://github.com/github/darrrr/blob/5519cc0cc208316c8cc891d797cc15570c919a5b/lib/darrrr/account_provider.rb#L59-L64
23,235
github/darrrr
lib/darrrr/account_provider.rb
Darrrr.AccountProvider.dangerous_unverified_recovery_token
def dangerous_unverified_recovery_token(countersigned_token) parsed_countersigned_token = RecoveryToken.parse(Base64.strict_decode64(countersigned_token)) RecoveryToken.parse(parsed_countersigned_token.data) end
ruby
def dangerous_unverified_recovery_token(countersigned_token) parsed_countersigned_token = RecoveryToken.parse(Base64.strict_decode64(countersigned_token)) RecoveryToken.parse(parsed_countersigned_token.data) end
[ "def", "dangerous_unverified_recovery_token", "(", "countersigned_token", ")", "parsed_countersigned_token", "=", "RecoveryToken", ".", "parse", "(", "Base64", ".", "strict_decode64", "(", "countersigned_token", ")", ")", "RecoveryToken", ".", "parse", "(", "parsed_countersigned_token", ".", "data", ")", "end" ]
Parses a countersigned_token and returns the nested recovery token WITHOUT verifying any signatures. This should only be used if no user context can be identified or if we're extracting issuer information.
[ "Parses", "a", "countersigned_token", "and", "returns", "the", "nested", "recovery", "token", "WITHOUT", "verifying", "any", "signatures", ".", "This", "should", "only", "be", "used", "if", "no", "user", "context", "can", "be", "identified", "or", "if", "we", "re", "extracting", "issuer", "information", "." ]
5519cc0cc208316c8cc891d797cc15570c919a5b
https://github.com/github/darrrr/blob/5519cc0cc208316c8cc891d797cc15570c919a5b/lib/darrrr/account_provider.rb#L69-L72
23,236
github/darrrr
lib/darrrr/account_provider.rb
Darrrr.AccountProvider.validate_countersigned_recovery_token!
def validate_countersigned_recovery_token!(countersigned_token, context = {}) # 5. Validate the the issuer field is present in the token, # and that it matches the audience field in the original countersigned token. begin recovery_provider = RecoveryToken.recovery_provider_issuer(Base64.strict_decode64(countersigned_token)) rescue RecoveryTokenSerializationError => e raise CountersignedTokenError.new("Countersigned token is invalid: " + e.message, :countersigned_token_parse_error) rescue UnknownProviderError => e raise CountersignedTokenError.new(e.message, :recovery_token_invalid_issuer) end # 1. Parse the countersigned-token. # 2. Validate that the version field is 0. # 7. Retrieve the current Recovery Provider configuration as described in Section 2. # 8. Validate that the counter-signed token signature validates with a current element of the countersign-pubkeys-secp256r1 array. begin parsed_countersigned_token = recovery_provider.unseal(Base64.strict_decode64(countersigned_token), context) rescue TokenFormatError => e raise CountersignedTokenError.new(e.message, :countersigned_invalid_token_version) rescue CryptoError raise CountersignedTokenError.new("Countersigned token has an invalid signature", :countersigned_invalid_signature) end # 3. De-serialize the original recovery token from the data field. # 4. Validate the signature on the original recovery token. begin recovery_token = self.unseal(parsed_countersigned_token.data, context) rescue RecoveryTokenSerializationError => e raise CountersignedTokenError.new("Nested recovery token is invalid: " + e.message, :recovery_token_token_parse_error) rescue TokenFormatError => e raise CountersignedTokenError.new("Nested recovery token format error: #{e.message}", :recovery_token_invalid_token_type) rescue CryptoError raise CountersignedTokenError.new("Nested recovery token has an invalid signature", :recovery_token_invalid_signature) end # 5. Validate the the issuer field is present in the countersigned-token, # and that it matches the audience field in the original token. countersigned_token_issuer = parsed_countersigned_token.issuer if countersigned_token_issuer.blank? || countersigned_token_issuer != recovery_token.audience || recovery_provider.origin != countersigned_token_issuer raise CountersignedTokenError.new("Validate the the issuer field is present in the countersigned-token, and that it matches the audience field in the original token", :recovery_token_invalid_issuer) end # 6. Validate the token binding for the countersigned token, if present. # (the token binding for the inner token is not relevant) # TODO not required, to be implemented later # 9. Decrypt the data field from the original recovery token and parse its information, if present. # no decryption here is attempted. Attempts to call `decode` will just fail. # 10. Apply any additional processing which provider-specific data in the opaque data portion may indicate is necessary. begin if DateTime.parse(parsed_countersigned_token.issued_time).utc < (Time.now - CLOCK_SKEW).utc raise CountersignedTokenError.new("Countersigned recovery token issued at time is too far in the past", :stale_token) end rescue ArgumentError raise CountersignedTokenError.new("Invalid countersigned token issued time", :invalid_issued_time) end recovery_token end
ruby
def validate_countersigned_recovery_token!(countersigned_token, context = {}) # 5. Validate the the issuer field is present in the token, # and that it matches the audience field in the original countersigned token. begin recovery_provider = RecoveryToken.recovery_provider_issuer(Base64.strict_decode64(countersigned_token)) rescue RecoveryTokenSerializationError => e raise CountersignedTokenError.new("Countersigned token is invalid: " + e.message, :countersigned_token_parse_error) rescue UnknownProviderError => e raise CountersignedTokenError.new(e.message, :recovery_token_invalid_issuer) end # 1. Parse the countersigned-token. # 2. Validate that the version field is 0. # 7. Retrieve the current Recovery Provider configuration as described in Section 2. # 8. Validate that the counter-signed token signature validates with a current element of the countersign-pubkeys-secp256r1 array. begin parsed_countersigned_token = recovery_provider.unseal(Base64.strict_decode64(countersigned_token), context) rescue TokenFormatError => e raise CountersignedTokenError.new(e.message, :countersigned_invalid_token_version) rescue CryptoError raise CountersignedTokenError.new("Countersigned token has an invalid signature", :countersigned_invalid_signature) end # 3. De-serialize the original recovery token from the data field. # 4. Validate the signature on the original recovery token. begin recovery_token = self.unseal(parsed_countersigned_token.data, context) rescue RecoveryTokenSerializationError => e raise CountersignedTokenError.new("Nested recovery token is invalid: " + e.message, :recovery_token_token_parse_error) rescue TokenFormatError => e raise CountersignedTokenError.new("Nested recovery token format error: #{e.message}", :recovery_token_invalid_token_type) rescue CryptoError raise CountersignedTokenError.new("Nested recovery token has an invalid signature", :recovery_token_invalid_signature) end # 5. Validate the the issuer field is present in the countersigned-token, # and that it matches the audience field in the original token. countersigned_token_issuer = parsed_countersigned_token.issuer if countersigned_token_issuer.blank? || countersigned_token_issuer != recovery_token.audience || recovery_provider.origin != countersigned_token_issuer raise CountersignedTokenError.new("Validate the the issuer field is present in the countersigned-token, and that it matches the audience field in the original token", :recovery_token_invalid_issuer) end # 6. Validate the token binding for the countersigned token, if present. # (the token binding for the inner token is not relevant) # TODO not required, to be implemented later # 9. Decrypt the data field from the original recovery token and parse its information, if present. # no decryption here is attempted. Attempts to call `decode` will just fail. # 10. Apply any additional processing which provider-specific data in the opaque data portion may indicate is necessary. begin if DateTime.parse(parsed_countersigned_token.issued_time).utc < (Time.now - CLOCK_SKEW).utc raise CountersignedTokenError.new("Countersigned recovery token issued at time is too far in the past", :stale_token) end rescue ArgumentError raise CountersignedTokenError.new("Invalid countersigned token issued time", :invalid_issued_time) end recovery_token end
[ "def", "validate_countersigned_recovery_token!", "(", "countersigned_token", ",", "context", "=", "{", "}", ")", "# 5. Validate the the issuer field is present in the token,", "# and that it matches the audience field in the original countersigned token.", "begin", "recovery_provider", "=", "RecoveryToken", ".", "recovery_provider_issuer", "(", "Base64", ".", "strict_decode64", "(", "countersigned_token", ")", ")", "rescue", "RecoveryTokenSerializationError", "=>", "e", "raise", "CountersignedTokenError", ".", "new", "(", "\"Countersigned token is invalid: \"", "+", "e", ".", "message", ",", ":countersigned_token_parse_error", ")", "rescue", "UnknownProviderError", "=>", "e", "raise", "CountersignedTokenError", ".", "new", "(", "e", ".", "message", ",", ":recovery_token_invalid_issuer", ")", "end", "# 1. Parse the countersigned-token.", "# 2. Validate that the version field is 0.", "# 7. Retrieve the current Recovery Provider configuration as described in Section 2.", "# 8. Validate that the counter-signed token signature validates with a current element of the countersign-pubkeys-secp256r1 array.", "begin", "parsed_countersigned_token", "=", "recovery_provider", ".", "unseal", "(", "Base64", ".", "strict_decode64", "(", "countersigned_token", ")", ",", "context", ")", "rescue", "TokenFormatError", "=>", "e", "raise", "CountersignedTokenError", ".", "new", "(", "e", ".", "message", ",", ":countersigned_invalid_token_version", ")", "rescue", "CryptoError", "raise", "CountersignedTokenError", ".", "new", "(", "\"Countersigned token has an invalid signature\"", ",", ":countersigned_invalid_signature", ")", "end", "# 3. De-serialize the original recovery token from the data field.", "# 4. Validate the signature on the original recovery token.", "begin", "recovery_token", "=", "self", ".", "unseal", "(", "parsed_countersigned_token", ".", "data", ",", "context", ")", "rescue", "RecoveryTokenSerializationError", "=>", "e", "raise", "CountersignedTokenError", ".", "new", "(", "\"Nested recovery token is invalid: \"", "+", "e", ".", "message", ",", ":recovery_token_token_parse_error", ")", "rescue", "TokenFormatError", "=>", "e", "raise", "CountersignedTokenError", ".", "new", "(", "\"Nested recovery token format error: #{e.message}\"", ",", ":recovery_token_invalid_token_type", ")", "rescue", "CryptoError", "raise", "CountersignedTokenError", ".", "new", "(", "\"Nested recovery token has an invalid signature\"", ",", ":recovery_token_invalid_signature", ")", "end", "# 5. Validate the the issuer field is present in the countersigned-token,", "# and that it matches the audience field in the original token.", "countersigned_token_issuer", "=", "parsed_countersigned_token", ".", "issuer", "if", "countersigned_token_issuer", ".", "blank?", "||", "countersigned_token_issuer", "!=", "recovery_token", ".", "audience", "||", "recovery_provider", ".", "origin", "!=", "countersigned_token_issuer", "raise", "CountersignedTokenError", ".", "new", "(", "\"Validate the the issuer field is present in the countersigned-token, and that it matches the audience field in the original token\"", ",", ":recovery_token_invalid_issuer", ")", "end", "# 6. Validate the token binding for the countersigned token, if present.", "# (the token binding for the inner token is not relevant)", "# TODO not required, to be implemented later", "# 9. Decrypt the data field from the original recovery token and parse its information, if present.", "# no decryption here is attempted. Attempts to call `decode` will just fail.", "# 10. Apply any additional processing which provider-specific data in the opaque data portion may indicate is necessary.", "begin", "if", "DateTime", ".", "parse", "(", "parsed_countersigned_token", ".", "issued_time", ")", ".", "utc", "<", "(", "Time", ".", "now", "-", "CLOCK_SKEW", ")", ".", "utc", "raise", "CountersignedTokenError", ".", "new", "(", "\"Countersigned recovery token issued at time is too far in the past\"", ",", ":stale_token", ")", "end", "rescue", "ArgumentError", "raise", "CountersignedTokenError", ".", "new", "(", "\"Invalid countersigned token issued time\"", ",", ":invalid_issued_time", ")", "end", "recovery_token", "end" ]
Validates the countersigned recovery token by verifying the signature of the countersigned token, parsing out the origin recovery token, verifying the signature on the recovery token, and finally decrypting the data in the origin recovery token. countersigned_token: our original recovery token wrapped in recovery token instance that is signed by the recovery provider. context: arbitrary data to be passed to Provider#unseal. returns a verified recovery token or raises an error if the token fails validation.
[ "Validates", "the", "countersigned", "recovery", "token", "by", "verifying", "the", "signature", "of", "the", "countersigned", "token", "parsing", "out", "the", "origin", "recovery", "token", "verifying", "the", "signature", "on", "the", "recovery", "token", "and", "finally", "decrypting", "the", "data", "in", "the", "origin", "recovery", "token", "." ]
5519cc0cc208316c8cc891d797cc15570c919a5b
https://github.com/github/darrrr/blob/5519cc0cc208316c8cc891d797cc15570c919a5b/lib/darrrr/account_provider.rb#L89-L149
23,237
github/darrrr
lib/darrrr/crypto_helper.rb
Darrrr.CryptoHelper.seal
def seal(token, context = nil) raise RuntimeError, "signing private key must be set" unless self.instance_variable_get(:@signing_private_key) binary_token = token.to_binary_s signature = self.encryptor.sign(binary_token, self.instance_variable_get(:@signing_private_key), self, context) Base64.strict_encode64([binary_token, signature].join) end
ruby
def seal(token, context = nil) raise RuntimeError, "signing private key must be set" unless self.instance_variable_get(:@signing_private_key) binary_token = token.to_binary_s signature = self.encryptor.sign(binary_token, self.instance_variable_get(:@signing_private_key), self, context) Base64.strict_encode64([binary_token, signature].join) end
[ "def", "seal", "(", "token", ",", "context", "=", "nil", ")", "raise", "RuntimeError", ",", "\"signing private key must be set\"", "unless", "self", ".", "instance_variable_get", "(", ":@signing_private_key", ")", "binary_token", "=", "token", ".", "to_binary_s", "signature", "=", "self", ".", "encryptor", ".", "sign", "(", "binary_token", ",", "self", ".", "instance_variable_get", "(", ":@signing_private_key", ")", ",", "self", ",", "context", ")", "Base64", ".", "strict_encode64", "(", "[", "binary_token", ",", "signature", "]", ".", "join", ")", "end" ]
Signs the provided token and joins the data with the signature. token: a RecoveryToken instance returns a base64 value for the binary token string and the signature of the token.
[ "Signs", "the", "provided", "token", "and", "joins", "the", "data", "with", "the", "signature", "." ]
5519cc0cc208316c8cc891d797cc15570c919a5b
https://github.com/github/darrrr/blob/5519cc0cc208316c8cc891d797cc15570c919a5b/lib/darrrr/crypto_helper.rb#L12-L17
23,238
github/darrrr
lib/darrrr/crypto_helper.rb
Darrrr.CryptoHelper.unseal
def unseal(token_and_signature, context = nil) token = RecoveryToken.parse(token_and_signature) unless token.version.to_i == PROTOCOL_VERSION raise TokenFormatError, "Version field must be #{PROTOCOL_VERSION}" end token_data, signature = partition_signed_token(token_and_signature, token) self.unseal_keys(context).each do |key| return token if self.encryptor.verify(token_data, signature, key, self, context) end raise CryptoError, "Recovery token signature was invalid" end
ruby
def unseal(token_and_signature, context = nil) token = RecoveryToken.parse(token_and_signature) unless token.version.to_i == PROTOCOL_VERSION raise TokenFormatError, "Version field must be #{PROTOCOL_VERSION}" end token_data, signature = partition_signed_token(token_and_signature, token) self.unseal_keys(context).each do |key| return token if self.encryptor.verify(token_data, signature, key, self, context) end raise CryptoError, "Recovery token signature was invalid" end
[ "def", "unseal", "(", "token_and_signature", ",", "context", "=", "nil", ")", "token", "=", "RecoveryToken", ".", "parse", "(", "token_and_signature", ")", "unless", "token", ".", "version", ".", "to_i", "==", "PROTOCOL_VERSION", "raise", "TokenFormatError", ",", "\"Version field must be #{PROTOCOL_VERSION}\"", "end", "token_data", ",", "signature", "=", "partition_signed_token", "(", "token_and_signature", ",", "token", ")", "self", ".", "unseal_keys", "(", "context", ")", ".", "each", "do", "|", "key", "|", "return", "token", "if", "self", ".", "encryptor", ".", "verify", "(", "token_data", ",", "signature", ",", "key", ",", "self", ",", "context", ")", "end", "raise", "CryptoError", ",", "\"Recovery token signature was invalid\"", "end" ]
Splits the payload by the token size, treats the remaining portion as the signature of the payload, and verifies the signature is valid for the given payload. token_and_signature: binary string consisting of [token_binary_str, signature].join keys - An array of public keys to use for signature verification. returns a RecoveryToken if the payload has been verified and deserializes correctly. Raises exceptions if any crypto fails. Raises an error if the token's version field is not valid.
[ "Splits", "the", "payload", "by", "the", "token", "size", "treats", "the", "remaining", "portion", "as", "the", "signature", "of", "the", "payload", "and", "verifies", "the", "signature", "is", "valid", "for", "the", "given", "payload", "." ]
5519cc0cc208316c8cc891d797cc15570c919a5b
https://github.com/github/darrrr/blob/5519cc0cc208316c8cc891d797cc15570c919a5b/lib/darrrr/crypto_helper.rb#L29-L41
23,239
rstacruz/rspec-repeat
lib/rspec/repeat.rb
RSpec.Repeat.repeat
def repeat(ex, count, options = {}) Repeater.new(count, options).run(ex, self) end
ruby
def repeat(ex, count, options = {}) Repeater.new(count, options).run(ex, self) end
[ "def", "repeat", "(", "ex", ",", "count", ",", "options", "=", "{", "}", ")", "Repeater", ".", "new", "(", "count", ",", "options", ")", ".", "run", "(", "ex", ",", "self", ")", "end" ]
Retries an example. include Rspec::Repeat around do |example| repeat example, 3 end Available options: - `wait` - seconds to wait between each retry - `verbose` - print messages if true - `exceptions` - if given, only retry exceptions from this list - `clear_let` - when false, don't clear `let`'s
[ "Retries", "an", "example", "." ]
14d51c837982d21c98ffedfabb365d9d0aea6fc3
https://github.com/rstacruz/rspec-repeat/blob/14d51c837982d21c98ffedfabb365d9d0aea6fc3/lib/rspec/repeat.rb#L21-L23
23,240
dvandersluis/amcharts.rb
lib/amcharts/chart.rb
AmCharts.Chart.method_missing
def method_missing(name, *args, &block) return type.send(name) if type if name.to_s.end_with?('?') @settings.send(name, *args, &block) end
ruby
def method_missing(name, *args, &block) return type.send(name) if type if name.to_s.end_with?('?') @settings.send(name, *args, &block) end
[ "def", "method_missing", "(", "name", ",", "*", "args", ",", "&", "block", ")", "return", "type", ".", "send", "(", "name", ")", "if", "type", "if", "name", ".", "to_s", ".", "end_with?", "(", "'?'", ")", "@settings", ".", "send", "(", "name", ",", "args", ",", "block", ")", "end" ]
Delegate unknown messages to the settings object
[ "Delegate", "unknown", "messages", "to", "the", "settings", "object" ]
c3203b78011fbd84b295ade01d2dd4a5c3bb48f6
https://github.com/dvandersluis/amcharts.rb/blob/c3203b78011fbd84b295ade01d2dd4a5c3bb48f6/lib/amcharts/chart.rb#L165-L168
23,241
delano/rye
lib/rye/rap.rb
Rye.Rap.add_stderr
def add_stderr(*args) args = args.flatten.compact args = args.first.split($/) if args.size == 1 @stderr ||= [] @stderr << args @stderr.flatten! self end
ruby
def add_stderr(*args) args = args.flatten.compact args = args.first.split($/) if args.size == 1 @stderr ||= [] @stderr << args @stderr.flatten! self end
[ "def", "add_stderr", "(", "*", "args", ")", "args", "=", "args", ".", "flatten", ".", "compact", "args", "=", "args", ".", "first", ".", "split", "(", "$/", ")", "if", "args", ".", "size", "==", "1", "@stderr", "||=", "[", "]", "@stderr", "<<", "args", "@stderr", ".", "flatten!", "self", "end" ]
Add STDERR output from the command executed via SSH.
[ "Add", "STDERR", "output", "from", "the", "command", "executed", "via", "SSH", "." ]
9b3893b2bcd9d578b81353a9186f2bd671aa1253
https://github.com/delano/rye/blob/9b3893b2bcd9d578b81353a9186f2bd671aa1253/lib/rye/rap.rb#L56-L63
23,242
orslumen/record-cache
lib/record_cache/dispatcher.rb
RecordCache.Dispatcher.parse
def parse(options) # find the record store, possibly based on the :store option store = record_store(options.delete(:store)) # dispatch the parse call to all known strategies Dispatcher.strategy_classes.map{ |klass| klass.parse(@base, store, options) }.flatten.compact.each do |strategy| raise "Multiple record cache definitions found for '#{strategy.attribute}' on #{@base.name}" if @strategy_by_attribute[strategy.attribute] # and keep track of all strategies @strategy_by_attribute[strategy.attribute] = strategy end # make sure the strategies are ordered again on next call to +ordered_strategies+ @ordered_strategies = nil end
ruby
def parse(options) # find the record store, possibly based on the :store option store = record_store(options.delete(:store)) # dispatch the parse call to all known strategies Dispatcher.strategy_classes.map{ |klass| klass.parse(@base, store, options) }.flatten.compact.each do |strategy| raise "Multiple record cache definitions found for '#{strategy.attribute}' on #{@base.name}" if @strategy_by_attribute[strategy.attribute] # and keep track of all strategies @strategy_by_attribute[strategy.attribute] = strategy end # make sure the strategies are ordered again on next call to +ordered_strategies+ @ordered_strategies = nil end
[ "def", "parse", "(", "options", ")", "# find the record store, possibly based on the :store option", "store", "=", "record_store", "(", "options", ".", "delete", "(", ":store", ")", ")", "# dispatch the parse call to all known strategies", "Dispatcher", ".", "strategy_classes", ".", "map", "{", "|", "klass", "|", "klass", ".", "parse", "(", "@base", ",", "store", ",", "options", ")", "}", ".", "flatten", ".", "compact", ".", "each", "do", "|", "strategy", "|", "raise", "\"Multiple record cache definitions found for '#{strategy.attribute}' on #{@base.name}\"", "if", "@strategy_by_attribute", "[", "strategy", ".", "attribute", "]", "# and keep track of all strategies", "@strategy_by_attribute", "[", "strategy", ".", "attribute", "]", "=", "strategy", "end", "# make sure the strategies are ordered again on next call to +ordered_strategies+", "@ordered_strategies", "=", "nil", "end" ]
Parse the options provided to the cache_records method and create the appropriate cache strategies.
[ "Parse", "the", "options", "provided", "to", "the", "cache_records", "method", "and", "create", "the", "appropriate", "cache", "strategies", "." ]
9bf4285c0a086f831b4b6e1d3fc292fbe44a14d6
https://github.com/orslumen/record-cache/blob/9bf4285c0a086f831b4b6e1d3fc292fbe44a14d6/lib/record_cache/dispatcher.rb#L24-L35
23,243
orslumen/record-cache
lib/record_cache/dispatcher.rb
RecordCache.Dispatcher.invalidate
def invalidate(strategy, value = nil) (value = strategy; strategy = :id) unless strategy.is_a?(Symbol) # call the invalidate method of the chosen strategy @strategy_by_attribute[strategy].invalidate(value) if @strategy_by_attribute[strategy] end
ruby
def invalidate(strategy, value = nil) (value = strategy; strategy = :id) unless strategy.is_a?(Symbol) # call the invalidate method of the chosen strategy @strategy_by_attribute[strategy].invalidate(value) if @strategy_by_attribute[strategy] end
[ "def", "invalidate", "(", "strategy", ",", "value", "=", "nil", ")", "(", "value", "=", "strategy", ";", "strategy", "=", ":id", ")", "unless", "strategy", ".", "is_a?", "(", "Symbol", ")", "# call the invalidate method of the chosen strategy", "@strategy_by_attribute", "[", "strategy", "]", ".", "invalidate", "(", "value", ")", "if", "@strategy_by_attribute", "[", "strategy", "]", "end" ]
Explicitly invalidate one or more records @param: strategy: the id of the strategy to invalidate (defaults to +:id+) @param: value: the value to send to the invalidate method of the chosen strategy
[ "Explicitly", "invalidate", "one", "or", "more", "records" ]
9bf4285c0a086f831b4b6e1d3fc292fbe44a14d6
https://github.com/orslumen/record-cache/blob/9bf4285c0a086f831b4b6e1d3fc292fbe44a14d6/lib/record_cache/dispatcher.rb#L61-L65
23,244
delano/rye
lib/rye/set.rb
Rye.Set.run_command
def run_command(meth, *args, &block) runner = @parallel ? :run_command_parallel : :run_command_serial self.send(runner, meth, *args, &block) end
ruby
def run_command(meth, *args, &block) runner = @parallel ? :run_command_parallel : :run_command_serial self.send(runner, meth, *args, &block) end
[ "def", "run_command", "(", "meth", ",", "*", "args", ",", "&", "block", ")", "runner", "=", "@parallel", "?", ":run_command_parallel", ":", ":run_command_serial", "self", ".", "send", "(", "runner", ",", "meth", ",", "args", ",", "block", ")", "end" ]
Determines whether to call the serial or parallel method, then calls it.
[ "Determines", "whether", "to", "call", "the", "serial", "or", "parallel", "method", "then", "calls", "it", "." ]
9b3893b2bcd9d578b81353a9186f2bd671aa1253
https://github.com/delano/rye/blob/9b3893b2bcd9d578b81353a9186f2bd671aa1253/lib/rye/set.rb#L155-L158
23,245
delano/rye
lib/rye/set.rb
Rye.Set.run_command_parallel
def run_command_parallel(meth, *args, &block) debug "P: #{meth} on #{@boxes.size} boxes (#{@boxes.collect {|b| b.host }.join(', ')})" threads = [] raps = Rye::Rap.new(self) (@boxes || []).each do |box| threads << Thread.new do Thread.current[:rap] = box.send(meth, *args, &block) # Store the result in the thread end end threads.each do |t| Kernel.sleep 0.03 # Give the thread some breathing room begin t.join # Wait for the thread to finish rescue Exception => ex # Store the exception in the result raps << Rap.new(self, [ex]) next end raps << t[:rap] # Grab the result end raps end
ruby
def run_command_parallel(meth, *args, &block) debug "P: #{meth} on #{@boxes.size} boxes (#{@boxes.collect {|b| b.host }.join(', ')})" threads = [] raps = Rye::Rap.new(self) (@boxes || []).each do |box| threads << Thread.new do Thread.current[:rap] = box.send(meth, *args, &block) # Store the result in the thread end end threads.each do |t| Kernel.sleep 0.03 # Give the thread some breathing room begin t.join # Wait for the thread to finish rescue Exception => ex # Store the exception in the result raps << Rap.new(self, [ex]) next end raps << t[:rap] # Grab the result end raps end
[ "def", "run_command_parallel", "(", "meth", ",", "*", "args", ",", "&", "block", ")", "debug", "\"P: #{meth} on #{@boxes.size} boxes (#{@boxes.collect {|b| b.host }.join(', ')})\"", "threads", "=", "[", "]", "raps", "=", "Rye", "::", "Rap", ".", "new", "(", "self", ")", "(", "@boxes", "||", "[", "]", ")", ".", "each", "do", "|", "box", "|", "threads", "<<", "Thread", ".", "new", "do", "Thread", ".", "current", "[", ":rap", "]", "=", "box", ".", "send", "(", "meth", ",", "args", ",", "block", ")", "# Store the result in the thread", "end", "end", "threads", ".", "each", "do", "|", "t", "|", "Kernel", ".", "sleep", "0.03", "# Give the thread some breathing room", "begin", "t", ".", "join", "# Wait for the thread to finish", "rescue", "Exception", "=>", "ex", "# Store the exception in the result", "raps", "<<", "Rap", ".", "new", "(", "self", ",", "[", "ex", "]", ")", "next", "end", "raps", "<<", "t", "[", ":rap", "]", "# Grab the result", "end", "raps", "end" ]
Run the command on all boxes in parallel
[ "Run", "the", "command", "on", "all", "boxes", "in", "parallel" ]
9b3893b2bcd9d578b81353a9186f2bd671aa1253
https://github.com/delano/rye/blob/9b3893b2bcd9d578b81353a9186f2bd671aa1253/lib/rye/set.rb#L162-L188
23,246
delano/rye
lib/rye/set.rb
Rye.Set.run_command_serial
def run_command_serial(meth, *args, &block) debug "S: #{meth} on #{@boxes.size} boxes (#{@boxes.collect {|b| b.host }.join(', ')})" raps = Rye::Rap.new(self) (@boxes || []).each do |box| raps << box.send(meth, *args, &block) end raps end
ruby
def run_command_serial(meth, *args, &block) debug "S: #{meth} on #{@boxes.size} boxes (#{@boxes.collect {|b| b.host }.join(', ')})" raps = Rye::Rap.new(self) (@boxes || []).each do |box| raps << box.send(meth, *args, &block) end raps end
[ "def", "run_command_serial", "(", "meth", ",", "*", "args", ",", "&", "block", ")", "debug", "\"S: #{meth} on #{@boxes.size} boxes (#{@boxes.collect {|b| b.host }.join(', ')})\"", "raps", "=", "Rye", "::", "Rap", ".", "new", "(", "self", ")", "(", "@boxes", "||", "[", "]", ")", ".", "each", "do", "|", "box", "|", "raps", "<<", "box", ".", "send", "(", "meth", ",", "args", ",", "block", ")", "end", "raps", "end" ]
Run the command on all boxes in serial
[ "Run", "the", "command", "on", "all", "boxes", "in", "serial" ]
9b3893b2bcd9d578b81353a9186f2bd671aa1253
https://github.com/delano/rye/blob/9b3893b2bcd9d578b81353a9186f2bd671aa1253/lib/rye/set.rb#L192-L199
23,247
pdeffendol/spatial_adapter
lib/spatial_adapter/postgresql.rb
ActiveRecord::ConnectionAdapters.PostgreSQLAdapter.quote
def quote(value, column = nil) if value.kind_of?(GeoRuby::SimpleFeatures::Geometry) "'#{value.as_hex_ewkb}'" else original_quote(value,column) end end
ruby
def quote(value, column = nil) if value.kind_of?(GeoRuby::SimpleFeatures::Geometry) "'#{value.as_hex_ewkb}'" else original_quote(value,column) end end
[ "def", "quote", "(", "value", ",", "column", "=", "nil", ")", "if", "value", ".", "kind_of?", "(", "GeoRuby", "::", "SimpleFeatures", "::", "Geometry", ")", "\"'#{value.as_hex_ewkb}'\"", "else", "original_quote", "(", "value", ",", "column", ")", "end", "end" ]
Redefines the quote method to add behaviour for when a Geometry is encountered
[ "Redefines", "the", "quote", "method", "to", "add", "behaviour", "for", "when", "a", "Geometry", "is", "encountered" ]
798d12381f4172043e8b36c7362eb5bc8f88f5d7
https://github.com/pdeffendol/spatial_adapter/blob/798d12381f4172043e8b36c7362eb5bc8f88f5d7/lib/spatial_adapter/postgresql.rb#L39-L45
23,248
pdeffendol/spatial_adapter
lib/spatial_adapter/postgresql.rb
ActiveRecord::ConnectionAdapters.PostgreSQLAdapter.add_index
def add_index(table_name, column_name, options = {}) column_names = Array(column_name) index_name = index_name(table_name, :column => column_names) if Hash === options # legacy support, since this param was a string index_type = options[:unique] ? "UNIQUE" : "" index_name = options[:name] || index_name index_method = options[:spatial] ? 'USING GIST' : "" else index_type = options end quoted_column_names = column_names.map { |e| quote_column_name(e) }.join(", ") execute "CREATE #{index_type} INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} #{index_method} (#{quoted_column_names})" end
ruby
def add_index(table_name, column_name, options = {}) column_names = Array(column_name) index_name = index_name(table_name, :column => column_names) if Hash === options # legacy support, since this param was a string index_type = options[:unique] ? "UNIQUE" : "" index_name = options[:name] || index_name index_method = options[:spatial] ? 'USING GIST' : "" else index_type = options end quoted_column_names = column_names.map { |e| quote_column_name(e) }.join(", ") execute "CREATE #{index_type} INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} #{index_method} (#{quoted_column_names})" end
[ "def", "add_index", "(", "table_name", ",", "column_name", ",", "options", "=", "{", "}", ")", "column_names", "=", "Array", "(", "column_name", ")", "index_name", "=", "index_name", "(", "table_name", ",", ":column", "=>", "column_names", ")", "if", "Hash", "===", "options", "# legacy support, since this param was a string", "index_type", "=", "options", "[", ":unique", "]", "?", "\"UNIQUE\"", ":", "\"\"", "index_name", "=", "options", "[", ":name", "]", "||", "index_name", "index_method", "=", "options", "[", ":spatial", "]", "?", "'USING GIST'", ":", "\"\"", "else", "index_type", "=", "options", "end", "quoted_column_names", "=", "column_names", ".", "map", "{", "|", "e", "|", "quote_column_name", "(", "e", ")", "}", ".", "join", "(", "\", \"", ")", "execute", "\"CREATE #{index_type} INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} #{index_method} (#{quoted_column_names})\"", "end" ]
Adds an index to a column.
[ "Adds", "an", "index", "to", "a", "column", "." ]
798d12381f4172043e8b36c7362eb5bc8f88f5d7
https://github.com/pdeffendol/spatial_adapter/blob/798d12381f4172043e8b36c7362eb5bc8f88f5d7/lib/spatial_adapter/postgresql.rb#L132-L145
23,249
delano/rye
lib/rye/box.rb
Rye.Box.ostype
def ostype return @rye_ostype if @rye_ostype # simple cache os = self.quietly { uname.first } rescue nil os ||= 'unknown' os &&= os.downcase @rye_ostype = os end
ruby
def ostype return @rye_ostype if @rye_ostype # simple cache os = self.quietly { uname.first } rescue nil os ||= 'unknown' os &&= os.downcase @rye_ostype = os end
[ "def", "ostype", "return", "@rye_ostype", "if", "@rye_ostype", "# simple cache", "os", "=", "self", ".", "quietly", "{", "uname", ".", "first", "}", "rescue", "nil", "os", "||=", "'unknown'", "os", "&&=", "os", ".", "downcase", "@rye_ostype", "=", "os", "end" ]
Return the value of uname in lowercase This is a temporary fix. We can use SysInfo for this, upload it, execute it directly, parse the output.
[ "Return", "the", "value", "of", "uname", "in", "lowercase", "This", "is", "a", "temporary", "fix", ".", "We", "can", "use", "SysInfo", "for", "this", "upload", "it", "execute", "it", "directly", "parse", "the", "output", "." ]
9b3893b2bcd9d578b81353a9186f2bd671aa1253
https://github.com/delano/rye/blob/9b3893b2bcd9d578b81353a9186f2bd671aa1253/lib/rye/box.rb#L344-L350
23,250
delano/rye
lib/rye/box.rb
Rye.Box.unsafely
def unsafely(*args, &block) previous_state = @rye_safe disable_safe_mode ret = self.instance_exec *args, &block @rye_safe = previous_state ret end
ruby
def unsafely(*args, &block) previous_state = @rye_safe disable_safe_mode ret = self.instance_exec *args, &block @rye_safe = previous_state ret end
[ "def", "unsafely", "(", "*", "args", ",", "&", "block", ")", "previous_state", "=", "@rye_safe", "disable_safe_mode", "ret", "=", "self", ".", "instance_exec", "args", ",", "block", "@rye_safe", "=", "previous_state", "ret", "end" ]
Like batch, except it disables safe mode before executing the block. After executing the block, safe mode is returned back to whichever state it was previously in. In other words, this method won't enable safe mode if it was already disabled.
[ "Like", "batch", "except", "it", "disables", "safe", "mode", "before", "executing", "the", "block", ".", "After", "executing", "the", "block", "safe", "mode", "is", "returned", "back", "to", "whichever", "state", "it", "was", "previously", "in", ".", "In", "other", "words", "this", "method", "won", "t", "enable", "safe", "mode", "if", "it", "was", "already", "disabled", "." ]
9b3893b2bcd9d578b81353a9186f2bd671aa1253
https://github.com/delano/rye/blob/9b3893b2bcd9d578b81353a9186f2bd671aa1253/lib/rye/box.rb#L558-L564
23,251
delano/rye
lib/rye/box.rb
Rye.Box.quietly
def quietly(*args, &block) previous_state = @rye_quiet enable_quiet_mode ret = self.instance_exec *args, &block @rye_quiet = previous_state ret end
ruby
def quietly(*args, &block) previous_state = @rye_quiet enable_quiet_mode ret = self.instance_exec *args, &block @rye_quiet = previous_state ret end
[ "def", "quietly", "(", "*", "args", ",", "&", "block", ")", "previous_state", "=", "@rye_quiet", "enable_quiet_mode", "ret", "=", "self", ".", "instance_exec", "args", ",", "block", "@rye_quiet", "=", "previous_state", "ret", "end" ]
Like batch, except it enables quiet mode before executing the block. After executing the block, quiet mode is returned back to whichever state it was previously in. In other words, this method won't enable quiet mode if it was already disabled. In quiet mode, the pre and post command hooks are not called. This is used internally when calling commands like +ls+ to check whether a file path exists (to prevent polluting the logs).
[ "Like", "batch", "except", "it", "enables", "quiet", "mode", "before", "executing", "the", "block", ".", "After", "executing", "the", "block", "quiet", "mode", "is", "returned", "back", "to", "whichever", "state", "it", "was", "previously", "in", ".", "In", "other", "words", "this", "method", "won", "t", "enable", "quiet", "mode", "if", "it", "was", "already", "disabled", "." ]
9b3893b2bcd9d578b81353a9186f2bd671aa1253
https://github.com/delano/rye/blob/9b3893b2bcd9d578b81353a9186f2bd671aa1253/lib/rye/box.rb#L584-L590
23,252
delano/rye
lib/rye/box.rb
Rye.Box.sudo
def sudo(*args, &block) if block.nil? run_command('sudo', args); else previous_state = @rye_sudo enable_sudo ret = self.instance_exec *args, &block @rye_sudo = previous_state ret end end
ruby
def sudo(*args, &block) if block.nil? run_command('sudo', args); else previous_state = @rye_sudo enable_sudo ret = self.instance_exec *args, &block @rye_sudo = previous_state ret end end
[ "def", "sudo", "(", "*", "args", ",", "&", "block", ")", "if", "block", ".", "nil?", "run_command", "(", "'sudo'", ",", "args", ")", ";", "else", "previous_state", "=", "@rye_sudo", "enable_sudo", "ret", "=", "self", ".", "instance_exec", "args", ",", "block", "@rye_sudo", "=", "previous_state", "ret", "end", "end" ]
Like batch, except it enables sudo mode before executing the block. If the user is already root, this has no effect. Otherwise all commands executed in the block will run via sudo. If no block is specified then sudo is called just like a regular command.
[ "Like", "batch", "except", "it", "enables", "sudo", "mode", "before", "executing", "the", "block", ".", "If", "the", "user", "is", "already", "root", "this", "has", "no", "effect", ".", "Otherwise", "all", "commands", "executed", "in", "the", "block", "will", "run", "via", "sudo", "." ]
9b3893b2bcd9d578b81353a9186f2bd671aa1253
https://github.com/delano/rye/blob/9b3893b2bcd9d578b81353a9186f2bd671aa1253/lib/rye/box.rb#L598-L608
23,253
delano/rye
lib/rye/box.rb
Rye.Box.prepend_env
def prepend_env(cmd) return cmd unless @rye_current_environment_variables.is_a?(Hash) env = '' @rye_current_environment_variables.each_pair do |n,v| env << "export #{n}=#{Escape.shell_single_word(v)}; " end [env, cmd].join(' ') end
ruby
def prepend_env(cmd) return cmd unless @rye_current_environment_variables.is_a?(Hash) env = '' @rye_current_environment_variables.each_pair do |n,v| env << "export #{n}=#{Escape.shell_single_word(v)}; " end [env, cmd].join(' ') end
[ "def", "prepend_env", "(", "cmd", ")", "return", "cmd", "unless", "@rye_current_environment_variables", ".", "is_a?", "(", "Hash", ")", "env", "=", "''", "@rye_current_environment_variables", ".", "each_pair", "do", "|", "n", ",", "v", "|", "env", "<<", "\"export #{n}=#{Escape.shell_single_word(v)}; \"", "end", "[", "env", ",", "cmd", "]", ".", "join", "(", "' '", ")", "end" ]
Add the current environment variables to the beginning of +cmd+
[ "Add", "the", "current", "environment", "variables", "to", "the", "beginning", "of", "+", "cmd", "+" ]
9b3893b2bcd9d578b81353a9186f2bd671aa1253
https://github.com/delano/rye/blob/9b3893b2bcd9d578b81353a9186f2bd671aa1253/lib/rye/box.rb#L738-L745
23,254
delano/rye
lib/rye/box.rb
Rye.Box.run_command
def run_command(*args, &blk) debug "run_command" cmd, args = prep_args(*args) #p [:run_command, cmd, blk.nil?] connect if !@rye_ssh || @rye_ssh.closed? raise Rye::NotConnected, @rye_host unless @rye_ssh && !@rye_ssh.closed? cmd_clean = Rye.escape(@rye_safe, cmd, args) # This following is the command we'll actually execute. cmd_clean # can be used for logging, otherwise the output is confusing. cmd_internal = prepend_env(cmd_clean) # Add the current working directory before the command if supplied. # The command will otherwise run in the user's home directory. if @rye_current_working_directory cwd = Rye.escape(@rye_safe, 'cd', @rye_current_working_directory) cmd_internal = '(%s; %s)' % [cwd, cmd_internal] end # ditto (same explanation as cwd) if @rye_current_umask cwd = Rye.escape(@rye_safe, 'umask', @rye_current_umask) cmd_internal = [cwd, cmd_internal].join(' && ') end ## NOTE: Do not raise a CommandNotFound exception in this method. # We want it to be possible to define methods to a single instance # of Rye::Box. i.e. def rbox.rm()... # can? returns the methods in Rye::Cmd so it would incorrectly # return false. We could use self.respond_to? but it's possible # to get a name collision. I could write a work around but I think # this is good enough for now. ## raise Rye::CommandNotFound unless self.can?(cmd) begin debug "COMMAND: #{cmd_internal}" if !@rye_quiet && @rye_pre_command_hook.is_a?(Proc) @rye_pre_command_hook.call(cmd_clean, user, host, nickname) end rap = Rye::Rap.new(self) rap.cmd = cmd_clean channel = net_ssh_exec!(cmd_internal, &blk) channel[:stderr].position = 0 channel[:stdout].position = 0 if channel[:exception] rap = channel[:exception].rap else rap.add_stdout(channel[:stdout].read || '') rap.add_stderr(channel[:stderr].read || '') rap.add_exit_status(channel[:exit_status]) rap.exit_signal = channel[:exit_signal] end debug "RESULT: %s " % [rap.inspect] # It seems a convention for various commands to return -1 # when something only mildly concerning happens. (ls even # returns -1 for apparently no reason sometimes). Anyway, # the real errors are the ones that are greater than zero. raise Rye::Err.new(rap) if rap.exit_status != 0 rescue Exception => ex return rap if @rye_quiet choice = nil @rye_exception_hook.each_pair do |klass,act| next unless ex.kind_of? klass choice = act.call(ex, cmd_clean, user, host, nickname) break end if choice == :retry retry elsif choice == :skip # do nothing elsif choice == :interactive && !@rye_shell @rye_shell = true previous_state = @rye_sudo disable_sudo bash @rye_sudo = previous_state @rye_shell = false elsif !ex.is_a?(Interrupt) raise ex, ex.message end end if !@rye_quiet && @rye_post_command_hook.is_a?(Proc) @rye_post_command_hook.call(rap) end rap end
ruby
def run_command(*args, &blk) debug "run_command" cmd, args = prep_args(*args) #p [:run_command, cmd, blk.nil?] connect if !@rye_ssh || @rye_ssh.closed? raise Rye::NotConnected, @rye_host unless @rye_ssh && !@rye_ssh.closed? cmd_clean = Rye.escape(@rye_safe, cmd, args) # This following is the command we'll actually execute. cmd_clean # can be used for logging, otherwise the output is confusing. cmd_internal = prepend_env(cmd_clean) # Add the current working directory before the command if supplied. # The command will otherwise run in the user's home directory. if @rye_current_working_directory cwd = Rye.escape(@rye_safe, 'cd', @rye_current_working_directory) cmd_internal = '(%s; %s)' % [cwd, cmd_internal] end # ditto (same explanation as cwd) if @rye_current_umask cwd = Rye.escape(@rye_safe, 'umask', @rye_current_umask) cmd_internal = [cwd, cmd_internal].join(' && ') end ## NOTE: Do not raise a CommandNotFound exception in this method. # We want it to be possible to define methods to a single instance # of Rye::Box. i.e. def rbox.rm()... # can? returns the methods in Rye::Cmd so it would incorrectly # return false. We could use self.respond_to? but it's possible # to get a name collision. I could write a work around but I think # this is good enough for now. ## raise Rye::CommandNotFound unless self.can?(cmd) begin debug "COMMAND: #{cmd_internal}" if !@rye_quiet && @rye_pre_command_hook.is_a?(Proc) @rye_pre_command_hook.call(cmd_clean, user, host, nickname) end rap = Rye::Rap.new(self) rap.cmd = cmd_clean channel = net_ssh_exec!(cmd_internal, &blk) channel[:stderr].position = 0 channel[:stdout].position = 0 if channel[:exception] rap = channel[:exception].rap else rap.add_stdout(channel[:stdout].read || '') rap.add_stderr(channel[:stderr].read || '') rap.add_exit_status(channel[:exit_status]) rap.exit_signal = channel[:exit_signal] end debug "RESULT: %s " % [rap.inspect] # It seems a convention for various commands to return -1 # when something only mildly concerning happens. (ls even # returns -1 for apparently no reason sometimes). Anyway, # the real errors are the ones that are greater than zero. raise Rye::Err.new(rap) if rap.exit_status != 0 rescue Exception => ex return rap if @rye_quiet choice = nil @rye_exception_hook.each_pair do |klass,act| next unless ex.kind_of? klass choice = act.call(ex, cmd_clean, user, host, nickname) break end if choice == :retry retry elsif choice == :skip # do nothing elsif choice == :interactive && !@rye_shell @rye_shell = true previous_state = @rye_sudo disable_sudo bash @rye_sudo = previous_state @rye_shell = false elsif !ex.is_a?(Interrupt) raise ex, ex.message end end if !@rye_quiet && @rye_post_command_hook.is_a?(Proc) @rye_post_command_hook.call(rap) end rap end
[ "def", "run_command", "(", "*", "args", ",", "&", "blk", ")", "debug", "\"run_command\"", "cmd", ",", "args", "=", "prep_args", "(", "args", ")", "#p [:run_command, cmd, blk.nil?]", "connect", "if", "!", "@rye_ssh", "||", "@rye_ssh", ".", "closed?", "raise", "Rye", "::", "NotConnected", ",", "@rye_host", "unless", "@rye_ssh", "&&", "!", "@rye_ssh", ".", "closed?", "cmd_clean", "=", "Rye", ".", "escape", "(", "@rye_safe", ",", "cmd", ",", "args", ")", "# This following is the command we'll actually execute. cmd_clean", "# can be used for logging, otherwise the output is confusing.", "cmd_internal", "=", "prepend_env", "(", "cmd_clean", ")", "# Add the current working directory before the command if supplied. ", "# The command will otherwise run in the user's home directory.", "if", "@rye_current_working_directory", "cwd", "=", "Rye", ".", "escape", "(", "@rye_safe", ",", "'cd'", ",", "@rye_current_working_directory", ")", "cmd_internal", "=", "'(%s; %s)'", "%", "[", "cwd", ",", "cmd_internal", "]", "end", "# ditto (same explanation as cwd)", "if", "@rye_current_umask", "cwd", "=", "Rye", ".", "escape", "(", "@rye_safe", ",", "'umask'", ",", "@rye_current_umask", ")", "cmd_internal", "=", "[", "cwd", ",", "cmd_internal", "]", ".", "join", "(", "' && '", ")", "end", "## NOTE: Do not raise a CommandNotFound exception in this method.", "# We want it to be possible to define methods to a single instance", "# of Rye::Box. i.e. def rbox.rm()...", "# can? returns the methods in Rye::Cmd so it would incorrectly", "# return false. We could use self.respond_to? but it's possible", "# to get a name collision. I could write a work around but I think", "# this is good enough for now. ", "## raise Rye::CommandNotFound unless self.can?(cmd)", "begin", "debug", "\"COMMAND: #{cmd_internal}\"", "if", "!", "@rye_quiet", "&&", "@rye_pre_command_hook", ".", "is_a?", "(", "Proc", ")", "@rye_pre_command_hook", ".", "call", "(", "cmd_clean", ",", "user", ",", "host", ",", "nickname", ")", "end", "rap", "=", "Rye", "::", "Rap", ".", "new", "(", "self", ")", "rap", ".", "cmd", "=", "cmd_clean", "channel", "=", "net_ssh_exec!", "(", "cmd_internal", ",", "blk", ")", "channel", "[", ":stderr", "]", ".", "position", "=", "0", "channel", "[", ":stdout", "]", ".", "position", "=", "0", "if", "channel", "[", ":exception", "]", "rap", "=", "channel", "[", ":exception", "]", ".", "rap", "else", "rap", ".", "add_stdout", "(", "channel", "[", ":stdout", "]", ".", "read", "||", "''", ")", "rap", ".", "add_stderr", "(", "channel", "[", ":stderr", "]", ".", "read", "||", "''", ")", "rap", ".", "add_exit_status", "(", "channel", "[", ":exit_status", "]", ")", "rap", ".", "exit_signal", "=", "channel", "[", ":exit_signal", "]", "end", "debug", "\"RESULT: %s \"", "%", "[", "rap", ".", "inspect", "]", "# It seems a convention for various commands to return -1", "# when something only mildly concerning happens. (ls even ", "# returns -1 for apparently no reason sometimes). Anyway,", "# the real errors are the ones that are greater than zero.", "raise", "Rye", "::", "Err", ".", "new", "(", "rap", ")", "if", "rap", ".", "exit_status", "!=", "0", "rescue", "Exception", "=>", "ex", "return", "rap", "if", "@rye_quiet", "choice", "=", "nil", "@rye_exception_hook", ".", "each_pair", "do", "|", "klass", ",", "act", "|", "next", "unless", "ex", ".", "kind_of?", "klass", "choice", "=", "act", ".", "call", "(", "ex", ",", "cmd_clean", ",", "user", ",", "host", ",", "nickname", ")", "break", "end", "if", "choice", "==", ":retry", "retry", "elsif", "choice", "==", ":skip", "# do nothing", "elsif", "choice", "==", ":interactive", "&&", "!", "@rye_shell", "@rye_shell", "=", "true", "previous_state", "=", "@rye_sudo", "disable_sudo", "bash", "@rye_sudo", "=", "previous_state", "@rye_shell", "=", "false", "elsif", "!", "ex", ".", "is_a?", "(", "Interrupt", ")", "raise", "ex", ",", "ex", ".", "message", "end", "end", "if", "!", "@rye_quiet", "&&", "@rye_post_command_hook", ".", "is_a?", "(", "Proc", ")", "@rye_post_command_hook", ".", "call", "(", "rap", ")", "end", "rap", "end" ]
Execute a command over SSH * +args+ is a command name and list of arguments. The command name is the literal name of the command that will be executed in the remote shell. The arguments will be thoroughly escaped and passed to the command. rbox = Rye::Box.new rbox.ls :l, 'arg1', 'arg2' is equivalent to $ ls -l 'arg1' 'arg2' This method will try to connect to the host automatically but if it fails it will raise a Rye::NotConnected exception.
[ "Execute", "a", "command", "over", "SSH" ]
9b3893b2bcd9d578b81353a9186f2bd671aa1253
https://github.com/delano/rye/blob/9b3893b2bcd9d578b81353a9186f2bd671aa1253/lib/rye/box.rb#L766-L864
23,255
orslumen/record-cache
lib/record_cache/query.rb
RecordCache.Query.where_values
def where_values(attribute, type = :integer) return @where_values[attribute] if @where_values.key?(attribute) @where_values[attribute] ||= array_of_values(@wheres[attribute], type) end
ruby
def where_values(attribute, type = :integer) return @where_values[attribute] if @where_values.key?(attribute) @where_values[attribute] ||= array_of_values(@wheres[attribute], type) end
[ "def", "where_values", "(", "attribute", ",", "type", "=", ":integer", ")", "return", "@where_values", "[", "attribute", "]", "if", "@where_values", ".", "key?", "(", "attribute", ")", "@where_values", "[", "attribute", "]", "||=", "array_of_values", "(", "@wheres", "[", "attribute", "]", ",", "type", ")", "end" ]
Retrieve the values for the given attribute from the where statements Returns nil if no the attribute is not present @param attribute: the attribute name @param type: the type to be retrieved, :integer or :string (defaults to :integer)
[ "Retrieve", "the", "values", "for", "the", "given", "attribute", "from", "the", "where", "statements", "Returns", "nil", "if", "no", "the", "attribute", "is", "not", "present" ]
9bf4285c0a086f831b4b6e1d3fc292fbe44a14d6
https://github.com/orslumen/record-cache/blob/9bf4285c0a086f831b4b6e1d3fc292fbe44a14d6/lib/record_cache/query.rb#L23-L26
23,256
orslumen/record-cache
lib/record_cache/query.rb
RecordCache.Query.where_value
def where_value(attribute, type = :integer) values = where_values(attribute, type) return nil unless values && values.size == 1 values.first end
ruby
def where_value(attribute, type = :integer) values = where_values(attribute, type) return nil unless values && values.size == 1 values.first end
[ "def", "where_value", "(", "attribute", ",", "type", "=", ":integer", ")", "values", "=", "where_values", "(", "attribute", ",", "type", ")", "return", "nil", "unless", "values", "&&", "values", ".", "size", "==", "1", "values", ".", "first", "end" ]
Retrieve the single value for the given attribute from the where statements Returns nil if the attribute is not present, or if it contains multiple values @param attribute: the attribute name @param type: the type to be retrieved, :integer or :string (defaults to :integer)
[ "Retrieve", "the", "single", "value", "for", "the", "given", "attribute", "from", "the", "where", "statements", "Returns", "nil", "if", "the", "attribute", "is", "not", "present", "or", "if", "it", "contains", "multiple", "values" ]
9bf4285c0a086f831b4b6e1d3fc292fbe44a14d6
https://github.com/orslumen/record-cache/blob/9bf4285c0a086f831b4b6e1d3fc292fbe44a14d6/lib/record_cache/query.rb#L32-L36
23,257
delano/rye
lib/rye/cmd.rb
Rye.Cmd.file_append
def file_append(filepath, newcontent, backup=false) content = StringIO.new if self.file_exists?(filepath) self.cp filepath, "#{filepath}-previous" if backup content = self.file_download filepath end if newcontent.is_a?(StringIO) newcontent.rewind content.puts newcontent.read else content.puts newcontent end self.file_upload content, filepath end
ruby
def file_append(filepath, newcontent, backup=false) content = StringIO.new if self.file_exists?(filepath) self.cp filepath, "#{filepath}-previous" if backup content = self.file_download filepath end if newcontent.is_a?(StringIO) newcontent.rewind content.puts newcontent.read else content.puts newcontent end self.file_upload content, filepath end
[ "def", "file_append", "(", "filepath", ",", "newcontent", ",", "backup", "=", "false", ")", "content", "=", "StringIO", ".", "new", "if", "self", ".", "file_exists?", "(", "filepath", ")", "self", ".", "cp", "filepath", ",", "\"#{filepath}-previous\"", "if", "backup", "content", "=", "self", ".", "file_download", "filepath", "end", "if", "newcontent", ".", "is_a?", "(", "StringIO", ")", "newcontent", ".", "rewind", "content", ".", "puts", "newcontent", ".", "read", "else", "content", ".", "puts", "newcontent", "end", "self", ".", "file_upload", "content", ",", "filepath", "end" ]
Append +newcontent+ to remote +filepath+. If the file doesn't exist it will be created. If +backup+ is specified, +filepath+ will be copied to +filepath-previous+ before appending. NOTE: Not recommended for large files. It downloads the contents.
[ "Append", "+", "newcontent", "+", "to", "remote", "+", "filepath", "+", ".", "If", "the", "file", "doesn", "t", "exist", "it", "will", "be", "created", ".", "If", "+", "backup", "+", "is", "specified", "+", "filepath", "+", "will", "be", "copied", "to", "+", "filepath", "-", "previous", "+", "before", "appending", "." ]
9b3893b2bcd9d578b81353a9186f2bd671aa1253
https://github.com/delano/rye/blob/9b3893b2bcd9d578b81353a9186f2bd671aa1253/lib/rye/cmd.rb#L204-L220
23,258
delano/rye
lib/rye/cmd.rb
Rye.Cmd.file_write
def file_write(filepath, newcontent, backup=false) if self.file_exists?(filepath) self.cp filepath, "#{filepath}-previous" if backup end content = StringIO.new content.puts newcontent self.file_upload content, filepath end
ruby
def file_write(filepath, newcontent, backup=false) if self.file_exists?(filepath) self.cp filepath, "#{filepath}-previous" if backup end content = StringIO.new content.puts newcontent self.file_upload content, filepath end
[ "def", "file_write", "(", "filepath", ",", "newcontent", ",", "backup", "=", "false", ")", "if", "self", ".", "file_exists?", "(", "filepath", ")", "self", ".", "cp", "filepath", ",", "\"#{filepath}-previous\"", "if", "backup", "end", "content", "=", "StringIO", ".", "new", "content", ".", "puts", "newcontent", "self", ".", "file_upload", "content", ",", "filepath", "end" ]
Write +newcontent+ to remote +filepath+. If the file exists it will be overwritten. If +backup+ is specified, +filepath+ will be copied to +filepath-previous+ before appending.
[ "Write", "+", "newcontent", "+", "to", "remote", "+", "filepath", "+", ".", "If", "the", "file", "exists", "it", "will", "be", "overwritten", ".", "If", "+", "backup", "+", "is", "specified", "+", "filepath", "+", "will", "be", "copied", "to", "+", "filepath", "-", "previous", "+", "before", "appending", "." ]
9b3893b2bcd9d578b81353a9186f2bd671aa1253
https://github.com/delano/rye/blob/9b3893b2bcd9d578b81353a9186f2bd671aa1253/lib/rye/cmd.rb#L225-L233
23,259
delano/rye
lib/rye/cmd.rb
Rye.Cmd.template_upload
def template_upload(*paths) remote_path = paths.pop templates = [] paths.collect! do |path| if StringIO === path path.rewind template = Rye::Tpl.new(path.read, "inline-template") elsif String === path raise "No such file: #{Dir.pwd}/#{path}" unless File.exists?(path) template = Rye::Tpl.new(File.read(path), File.basename(path)) end template.result!(binding) templates << template template.path end paths << remote_path ret = self.file_upload *paths templates.each { |template| tmp_path = File.join(remote_path, File.basename(template.path)) if file_exists?(tmp_path) mv tmp_path, File.join(remote_path, template.basename) end template.delete } ret end
ruby
def template_upload(*paths) remote_path = paths.pop templates = [] paths.collect! do |path| if StringIO === path path.rewind template = Rye::Tpl.new(path.read, "inline-template") elsif String === path raise "No such file: #{Dir.pwd}/#{path}" unless File.exists?(path) template = Rye::Tpl.new(File.read(path), File.basename(path)) end template.result!(binding) templates << template template.path end paths << remote_path ret = self.file_upload *paths templates.each { |template| tmp_path = File.join(remote_path, File.basename(template.path)) if file_exists?(tmp_path) mv tmp_path, File.join(remote_path, template.basename) end template.delete } ret end
[ "def", "template_upload", "(", "*", "paths", ")", "remote_path", "=", "paths", ".", "pop", "templates", "=", "[", "]", "paths", ".", "collect!", "do", "|", "path", "|", "if", "StringIO", "===", "path", "path", ".", "rewind", "template", "=", "Rye", "::", "Tpl", ".", "new", "(", "path", ".", "read", ",", "\"inline-template\"", ")", "elsif", "String", "===", "path", "raise", "\"No such file: #{Dir.pwd}/#{path}\"", "unless", "File", ".", "exists?", "(", "path", ")", "template", "=", "Rye", "::", "Tpl", ".", "new", "(", "File", ".", "read", "(", "path", ")", ",", "File", ".", "basename", "(", "path", ")", ")", "end", "template", ".", "result!", "(", "binding", ")", "templates", "<<", "template", "template", ".", "path", "end", "paths", "<<", "remote_path", "ret", "=", "self", ".", "file_upload", "paths", "templates", ".", "each", "{", "|", "template", "|", "tmp_path", "=", "File", ".", "join", "(", "remote_path", ",", "File", ".", "basename", "(", "template", ".", "path", ")", ")", "if", "file_exists?", "(", "tmp_path", ")", "mv", "tmp_path", ",", "File", ".", "join", "(", "remote_path", ",", "template", ".", "basename", ")", "end", "template", ".", "delete", "}", "ret", "end" ]
Parse a template and upload that as a file to remote_path.
[ "Parse", "a", "template", "and", "upload", "that", "as", "a", "file", "to", "remote_path", "." ]
9b3893b2bcd9d578b81353a9186f2bd671aa1253
https://github.com/delano/rye/blob/9b3893b2bcd9d578b81353a9186f2bd671aa1253/lib/rye/cmd.rb#L241-L266
23,260
delano/rye
lib/rye/cmd.rb
Rye.Cmd.file_exists?
def file_exists?(path) begin ret = self.quietly { ls(path) } rescue Rye::Err => ex ret = ex.rap end # "ls" returns a 0 exit code regardless of success in Linux # But on OSX exit code is 1. This is why we look at STDERR. !(ret.exit_status > 0) || ret.stderr.empty? end
ruby
def file_exists?(path) begin ret = self.quietly { ls(path) } rescue Rye::Err => ex ret = ex.rap end # "ls" returns a 0 exit code regardless of success in Linux # But on OSX exit code is 1. This is why we look at STDERR. !(ret.exit_status > 0) || ret.stderr.empty? end
[ "def", "file_exists?", "(", "path", ")", "begin", "ret", "=", "self", ".", "quietly", "{", "ls", "(", "path", ")", "}", "rescue", "Rye", "::", "Err", "=>", "ex", "ret", "=", "ex", ".", "rap", "end", "# \"ls\" returns a 0 exit code regardless of success in Linux", "# But on OSX exit code is 1. This is why we look at STDERR. ", "!", "(", "ret", ".", "exit_status", ">", "0", ")", "||", "ret", ".", "stderr", ".", "empty?", "end" ]
Does +path+ from the current working directory?
[ "Does", "+", "path", "+", "from", "the", "current", "working", "directory?" ]
9b3893b2bcd9d578b81353a9186f2bd671aa1253
https://github.com/delano/rye/blob/9b3893b2bcd9d578b81353a9186f2bd671aa1253/lib/rye/cmd.rb#L274-L283
23,261
delano/rye
lib/rye/hop.rb
Rye.Hop.fetch_port
def fetch_port(host, port = 22, localport = nil) connect unless @rye_ssh if localport.nil? port_used = next_port else port_used = localport end # i would like to check if the port and host # are already an active_locals forward, but that # info does not get returned, and trusting the localport # is not enough information, so lets just set up a new one @rye_ssh.forward.local(port_used, host, port) return port_used end
ruby
def fetch_port(host, port = 22, localport = nil) connect unless @rye_ssh if localport.nil? port_used = next_port else port_used = localport end # i would like to check if the port and host # are already an active_locals forward, but that # info does not get returned, and trusting the localport # is not enough information, so lets just set up a new one @rye_ssh.forward.local(port_used, host, port) return port_used end
[ "def", "fetch_port", "(", "host", ",", "port", "=", "22", ",", "localport", "=", "nil", ")", "connect", "unless", "@rye_ssh", "if", "localport", ".", "nil?", "port_used", "=", "next_port", "else", "port_used", "=", "localport", "end", "# i would like to check if the port and host ", "# are already an active_locals forward, but that ", "# info does not get returned, and trusting the localport", "# is not enough information, so lets just set up a new one", "@rye_ssh", ".", "forward", ".", "local", "(", "port_used", ",", "host", ",", "port", ")", "return", "port_used", "end" ]
instance method, that will setup a forward, and return the port used
[ "instance", "method", "that", "will", "setup", "a", "forward", "and", "return", "the", "port", "used" ]
9b3893b2bcd9d578b81353a9186f2bd671aa1253
https://github.com/delano/rye/blob/9b3893b2bcd9d578b81353a9186f2bd671aa1253/lib/rye/hop.rb#L181-L194
23,262
delano/rye
lib/rye/hop.rb
Rye.Hop.connect
def connect(reconnect=true) raise Rye::NoHost unless @rye_host return if @rye_ssh && !reconnect disconnect if @rye_ssh if @rye_via debug "Opening connection to #{@rye_host} as #{@rye_user}, via #{@rye_via.host}" else debug "Opening connection to #{@rye_host} as #{@rye_user}" end highline = HighLine.new # Used for password prompt retried = 0 @rye_opts[:keys].compact! # A quick fix in Windows. TODO: Why is there a nil? begin if @rye_via # tell the +Rye::Hop+ what and where to setup, # it returns the local port used @rye_localport = @rye_via.fetch_port(@rye_host, @rye_opts[:port].nil? ? 22 : @rye_opts[:port] ) @rye_ssh = Net::SSH.start("localhost", @rye_user, @rye_opts.merge(:port => @rye_localport) || {}) else @rye_ssh = Net::SSH.start(@rye_host, @rye_user, @rye_opts || {}) end debug "starting the port forward thread" port_loop rescue Net::SSH::HostKeyMismatch => ex STDERR.puts ex.message print "\a" if @rye_info # Ring the bell if highline.ask("Continue? ").strip.match(/\Ay|yes|sure|ya\z/i) @rye_opts[:paranoid] = false retry else raise ex end rescue Net::SSH::AuthenticationFailed => ex print "\a" if retried == 0 && @rye_info # Ring the bell once retried += 1 if STDIN.tty? && retried <= 3 STDERR.puts "Passwordless login failed for #{@rye_user}" @rye_opts[:password] = highline.ask("Password: ") { |q| q.echo = '' }.strip @rye_opts[:auth_methods] ||= [] @rye_opts[:auth_methods].push *['keyboard-interactive', 'password'] retry else raise ex end end # We add :auth_methods (a Net::SSH joint) to force asking for a # password if the initial (key-based) authentication fails. We # need to delete the key from @rye_opts otherwise it lingers until # the next connection (if we switch_user is called for example). @rye_opts.delete :auth_methods if @rye_opts.has_key?(:auth_methods) self end
ruby
def connect(reconnect=true) raise Rye::NoHost unless @rye_host return if @rye_ssh && !reconnect disconnect if @rye_ssh if @rye_via debug "Opening connection to #{@rye_host} as #{@rye_user}, via #{@rye_via.host}" else debug "Opening connection to #{@rye_host} as #{@rye_user}" end highline = HighLine.new # Used for password prompt retried = 0 @rye_opts[:keys].compact! # A quick fix in Windows. TODO: Why is there a nil? begin if @rye_via # tell the +Rye::Hop+ what and where to setup, # it returns the local port used @rye_localport = @rye_via.fetch_port(@rye_host, @rye_opts[:port].nil? ? 22 : @rye_opts[:port] ) @rye_ssh = Net::SSH.start("localhost", @rye_user, @rye_opts.merge(:port => @rye_localport) || {}) else @rye_ssh = Net::SSH.start(@rye_host, @rye_user, @rye_opts || {}) end debug "starting the port forward thread" port_loop rescue Net::SSH::HostKeyMismatch => ex STDERR.puts ex.message print "\a" if @rye_info # Ring the bell if highline.ask("Continue? ").strip.match(/\Ay|yes|sure|ya\z/i) @rye_opts[:paranoid] = false retry else raise ex end rescue Net::SSH::AuthenticationFailed => ex print "\a" if retried == 0 && @rye_info # Ring the bell once retried += 1 if STDIN.tty? && retried <= 3 STDERR.puts "Passwordless login failed for #{@rye_user}" @rye_opts[:password] = highline.ask("Password: ") { |q| q.echo = '' }.strip @rye_opts[:auth_methods] ||= [] @rye_opts[:auth_methods].push *['keyboard-interactive', 'password'] retry else raise ex end end # We add :auth_methods (a Net::SSH joint) to force asking for a # password if the initial (key-based) authentication fails. We # need to delete the key from @rye_opts otherwise it lingers until # the next connection (if we switch_user is called for example). @rye_opts.delete :auth_methods if @rye_opts.has_key?(:auth_methods) self end
[ "def", "connect", "(", "reconnect", "=", "true", ")", "raise", "Rye", "::", "NoHost", "unless", "@rye_host", "return", "if", "@rye_ssh", "&&", "!", "reconnect", "disconnect", "if", "@rye_ssh", "if", "@rye_via", "debug", "\"Opening connection to #{@rye_host} as #{@rye_user}, via #{@rye_via.host}\"", "else", "debug", "\"Opening connection to #{@rye_host} as #{@rye_user}\"", "end", "highline", "=", "HighLine", ".", "new", "# Used for password prompt", "retried", "=", "0", "@rye_opts", "[", ":keys", "]", ".", "compact!", "# A quick fix in Windows. TODO: Why is there a nil?", "begin", "if", "@rye_via", "# tell the +Rye::Hop+ what and where to setup,", "# it returns the local port used", "@rye_localport", "=", "@rye_via", ".", "fetch_port", "(", "@rye_host", ",", "@rye_opts", "[", ":port", "]", ".", "nil?", "?", "22", ":", "@rye_opts", "[", ":port", "]", ")", "@rye_ssh", "=", "Net", "::", "SSH", ".", "start", "(", "\"localhost\"", ",", "@rye_user", ",", "@rye_opts", ".", "merge", "(", ":port", "=>", "@rye_localport", ")", "||", "{", "}", ")", "else", "@rye_ssh", "=", "Net", "::", "SSH", ".", "start", "(", "@rye_host", ",", "@rye_user", ",", "@rye_opts", "||", "{", "}", ")", "end", "debug", "\"starting the port forward thread\"", "port_loop", "rescue", "Net", "::", "SSH", "::", "HostKeyMismatch", "=>", "ex", "STDERR", ".", "puts", "ex", ".", "message", "print", "\"\\a\"", "if", "@rye_info", "# Ring the bell", "if", "highline", ".", "ask", "(", "\"Continue? \"", ")", ".", "strip", ".", "match", "(", "/", "\\A", "\\z", "/i", ")", "@rye_opts", "[", ":paranoid", "]", "=", "false", "retry", "else", "raise", "ex", "end", "rescue", "Net", "::", "SSH", "::", "AuthenticationFailed", "=>", "ex", "print", "\"\\a\"", "if", "retried", "==", "0", "&&", "@rye_info", "# Ring the bell once", "retried", "+=", "1", "if", "STDIN", ".", "tty?", "&&", "retried", "<=", "3", "STDERR", ".", "puts", "\"Passwordless login failed for #{@rye_user}\"", "@rye_opts", "[", ":password", "]", "=", "highline", ".", "ask", "(", "\"Password: \"", ")", "{", "|", "q", "|", "q", ".", "echo", "=", "''", "}", ".", "strip", "@rye_opts", "[", ":auth_methods", "]", "||=", "[", "]", "@rye_opts", "[", ":auth_methods", "]", ".", "push", "[", "'keyboard-interactive'", ",", "'password'", "]", "retry", "else", "raise", "ex", "end", "end", "# We add :auth_methods (a Net::SSH joint) to force asking for a", "# password if the initial (key-based) authentication fails. We", "# need to delete the key from @rye_opts otherwise it lingers until", "# the next connection (if we switch_user is called for example).", "@rye_opts", ".", "delete", ":auth_methods", "if", "@rye_opts", ".", "has_key?", "(", ":auth_methods", ")", "self", "end" ]
Open an SSH session with +@rye_host+. This called automatically when you the first comamnd is run if it's not already connected. Raises a Rye::NoHost exception if +@rye_host+ is not specified. Will attempt a password login up to 3 times if the initial authentication fails. * +reconnect+ Disconnect first if already connected. The default is true. When set to false, connect will do nothing if already connected.
[ "Open", "an", "SSH", "session", "with", "+" ]
9b3893b2bcd9d578b81353a9186f2bd671aa1253
https://github.com/delano/rye/blob/9b3893b2bcd9d578b81353a9186f2bd671aa1253/lib/rye/hop.rb#L246-L299
23,263
delano/rye
lib/rye/hop.rb
Rye.Hop.remove_hops!
def remove_hops! return unless @rye_ssh && @rye_ssh.forward.active_locals.count > 0 @rye_ssh.forward.active_locals.each {|fport, fhost| @rye_ssh.forward.cancel_local(fport, fhost) } if !@rye_ssh.channels.empty? @rye_ssh.channels.each {|channel| channel[-1].close } end return @rye_ssh.forward.active_locals.count end
ruby
def remove_hops! return unless @rye_ssh && @rye_ssh.forward.active_locals.count > 0 @rye_ssh.forward.active_locals.each {|fport, fhost| @rye_ssh.forward.cancel_local(fport, fhost) } if !@rye_ssh.channels.empty? @rye_ssh.channels.each {|channel| channel[-1].close } end return @rye_ssh.forward.active_locals.count end
[ "def", "remove_hops!", "return", "unless", "@rye_ssh", "&&", "@rye_ssh", ".", "forward", ".", "active_locals", ".", "count", ">", "0", "@rye_ssh", ".", "forward", ".", "active_locals", ".", "each", "{", "|", "fport", ",", "fhost", "|", "@rye_ssh", ".", "forward", ".", "cancel_local", "(", "fport", ",", "fhost", ")", "}", "if", "!", "@rye_ssh", ".", "channels", ".", "empty?", "@rye_ssh", ".", "channels", ".", "each", "{", "|", "channel", "|", "channel", "[", "-", "1", "]", ".", "close", "}", "end", "return", "@rye_ssh", ".", "forward", ".", "active_locals", ".", "count", "end" ]
Cancel the port forward on all active local forwards
[ "Cancel", "the", "port", "forward", "on", "all", "active", "local", "forwards" ]
9b3893b2bcd9d578b81353a9186f2bd671aa1253
https://github.com/delano/rye/blob/9b3893b2bcd9d578b81353a9186f2bd671aa1253/lib/rye/hop.rb#L302-L313
23,264
delano/rye
lib/rye/hop.rb
Rye.Hop.disconnect
def disconnect return unless @rye_ssh && !@rye_ssh.closed? begin debug "removing active forwards" remove_hops! debug "killing port_loop @rye_port_thread" @rye_port_thread.kill if @rye_ssh.busy?; info "Is something still running? (ctrl-C to exit)" Timeout::timeout(10) do @rye_ssh.loop(0.3) { @rye_ssh.busy?; } end end debug "Closing connection to #{@rye_ssh.host}" @rye_ssh.close if @rye_via debug "disconnecting Hop #{@rye_via.host}" @rye_via.disconnect end rescue SystemCallError, Timeout::Error => ex error "Rye::Hop: Disconnect timeout (#{ex.message})" debug ex.backtrace rescue Interrupt debug "Exiting..." end end
ruby
def disconnect return unless @rye_ssh && !@rye_ssh.closed? begin debug "removing active forwards" remove_hops! debug "killing port_loop @rye_port_thread" @rye_port_thread.kill if @rye_ssh.busy?; info "Is something still running? (ctrl-C to exit)" Timeout::timeout(10) do @rye_ssh.loop(0.3) { @rye_ssh.busy?; } end end debug "Closing connection to #{@rye_ssh.host}" @rye_ssh.close if @rye_via debug "disconnecting Hop #{@rye_via.host}" @rye_via.disconnect end rescue SystemCallError, Timeout::Error => ex error "Rye::Hop: Disconnect timeout (#{ex.message})" debug ex.backtrace rescue Interrupt debug "Exiting..." end end
[ "def", "disconnect", "return", "unless", "@rye_ssh", "&&", "!", "@rye_ssh", ".", "closed?", "begin", "debug", "\"removing active forwards\"", "remove_hops!", "debug", "\"killing port_loop @rye_port_thread\"", "@rye_port_thread", ".", "kill", "if", "@rye_ssh", ".", "busy?", ";", "info", "\"Is something still running? (ctrl-C to exit)\"", "Timeout", "::", "timeout", "(", "10", ")", "do", "@rye_ssh", ".", "loop", "(", "0.3", ")", "{", "@rye_ssh", ".", "busy?", ";", "}", "end", "end", "debug", "\"Closing connection to #{@rye_ssh.host}\"", "@rye_ssh", ".", "close", "if", "@rye_via", "debug", "\"disconnecting Hop #{@rye_via.host}\"", "@rye_via", ".", "disconnect", "end", "rescue", "SystemCallError", ",", "Timeout", "::", "Error", "=>", "ex", "error", "\"Rye::Hop: Disconnect timeout (#{ex.message})\"", "debug", "ex", ".", "backtrace", "rescue", "Interrupt", "debug", "\"Exiting...\"", "end", "end" ]
Close the SSH session with +@rye_host+. This is called automatically at exit if the connection is open.
[ "Close", "the", "SSH", "session", "with", "+" ]
9b3893b2bcd9d578b81353a9186f2bd671aa1253
https://github.com/delano/rye/blob/9b3893b2bcd9d578b81353a9186f2bd671aa1253/lib/rye/hop.rb#L317-L342
23,265
delano/rye
lib/rye/hop.rb
Rye.Hop.next_port
def next_port port = @next_port @next_port -= 1 @next_port = MAX_PORT if @next_port < MIN_PORT # check if the port is in use, if so get the next_port begin TCPSocket.new '127.0.0.1', port rescue Errno::EADDRINUSE next_port() rescue Errno::ECONNREFUSED port else next_port() end end
ruby
def next_port port = @next_port @next_port -= 1 @next_port = MAX_PORT if @next_port < MIN_PORT # check if the port is in use, if so get the next_port begin TCPSocket.new '127.0.0.1', port rescue Errno::EADDRINUSE next_port() rescue Errno::ECONNREFUSED port else next_port() end end
[ "def", "next_port", "port", "=", "@next_port", "@next_port", "-=", "1", "@next_port", "=", "MAX_PORT", "if", "@next_port", "<", "MIN_PORT", "# check if the port is in use, if so get the next_port", "begin", "TCPSocket", ".", "new", "'127.0.0.1'", ",", "port", "rescue", "Errno", "::", "EADDRINUSE", "next_port", "(", ")", "rescue", "Errno", "::", "ECONNREFUSED", "port", "else", "next_port", "(", ")", "end", "end" ]
Grabs the next available port number and returns it.
[ "Grabs", "the", "next", "available", "port", "number", "and", "returns", "it", "." ]
9b3893b2bcd9d578b81353a9186f2bd671aa1253
https://github.com/delano/rye/blob/9b3893b2bcd9d578b81353a9186f2bd671aa1253/lib/rye/hop.rb#L386-L400
23,266
orslumen/record-cache
lib/record_cache/version_store.rb
RecordCache.VersionStore.current_multi
def current_multi(id_key_map) current_versions = @store.read_multi(*(id_key_map.values)) Hash[id_key_map.map{ |id, key| [id, current_versions[key]] }] end
ruby
def current_multi(id_key_map) current_versions = @store.read_multi(*(id_key_map.values)) Hash[id_key_map.map{ |id, key| [id, current_versions[key]] }] end
[ "def", "current_multi", "(", "id_key_map", ")", "current_versions", "=", "@store", ".", "read_multi", "(", "(", "id_key_map", ".", "values", ")", ")", "Hash", "[", "id_key_map", ".", "map", "{", "|", "id", ",", "key", "|", "[", "id", ",", "current_versions", "[", "key", "]", "]", "}", "]", "end" ]
Retrieve the current versions for the given keys @param id_key_map is a map with {id => cache_key} @return a map with {id => current_version} version nil for all keys unknown to the version store
[ "Retrieve", "the", "current", "versions", "for", "the", "given", "keys" ]
9bf4285c0a086f831b4b6e1d3fc292fbe44a14d6
https://github.com/orslumen/record-cache/blob/9bf4285c0a086f831b4b6e1d3fc292fbe44a14d6/lib/record_cache/version_store.rb#L26-L29
23,267
xinminlabs/synvert
lib/synvert/cli.rb
Synvert.CLI.run
def run(args) run_option_parser(args) case @options[:command] when 'list' load_rewriters list_available_rewriters when 'open' open_rewriter when 'query' load_rewriters query_available_rewriters when 'show' load_rewriters show_rewriter when 'sync' sync_snippets else load_rewriters @options[:snippet_names].each do |snippet_name| puts "===== #{snippet_name} started =====" group, name = snippet_name.split('/') rewriter = Core::Rewriter.call group, name rewriter.warnings.each do |warning| puts '[Warn] ' + warning.message end puts rewriter.todo if rewriter.todo puts "===== #{snippet_name} done =====" end end true rescue SystemExit true rescue Parser::SyntaxError => e puts "Syntax error: #{e.message}" puts "file #{e.diagnostic.location.source_buffer.name}" puts "line #{e.diagnostic.location.line}" false rescue Synvert::Core::RewriterNotFound => e puts e.message false end
ruby
def run(args) run_option_parser(args) case @options[:command] when 'list' load_rewriters list_available_rewriters when 'open' open_rewriter when 'query' load_rewriters query_available_rewriters when 'show' load_rewriters show_rewriter when 'sync' sync_snippets else load_rewriters @options[:snippet_names].each do |snippet_name| puts "===== #{snippet_name} started =====" group, name = snippet_name.split('/') rewriter = Core::Rewriter.call group, name rewriter.warnings.each do |warning| puts '[Warn] ' + warning.message end puts rewriter.todo if rewriter.todo puts "===== #{snippet_name} done =====" end end true rescue SystemExit true rescue Parser::SyntaxError => e puts "Syntax error: #{e.message}" puts "file #{e.diagnostic.location.source_buffer.name}" puts "line #{e.diagnostic.location.line}" false rescue Synvert::Core::RewriterNotFound => e puts e.message false end
[ "def", "run", "(", "args", ")", "run_option_parser", "(", "args", ")", "case", "@options", "[", ":command", "]", "when", "'list'", "load_rewriters", "list_available_rewriters", "when", "'open'", "open_rewriter", "when", "'query'", "load_rewriters", "query_available_rewriters", "when", "'show'", "load_rewriters", "show_rewriter", "when", "'sync'", "sync_snippets", "else", "load_rewriters", "@options", "[", ":snippet_names", "]", ".", "each", "do", "|", "snippet_name", "|", "puts", "\"===== #{snippet_name} started =====\"", "group", ",", "name", "=", "snippet_name", ".", "split", "(", "'/'", ")", "rewriter", "=", "Core", "::", "Rewriter", ".", "call", "group", ",", "name", "rewriter", ".", "warnings", ".", "each", "do", "|", "warning", "|", "puts", "'[Warn] '", "+", "warning", ".", "message", "end", "puts", "rewriter", ".", "todo", "if", "rewriter", ".", "todo", "puts", "\"===== #{snippet_name} done =====\"", "end", "end", "true", "rescue", "SystemExit", "true", "rescue", "Parser", "::", "SyntaxError", "=>", "e", "puts", "\"Syntax error: #{e.message}\"", "puts", "\"file #{e.diagnostic.location.source_buffer.name}\"", "puts", "\"line #{e.diagnostic.location.line}\"", "false", "rescue", "Synvert", "::", "Core", "::", "RewriterNotFound", "=>", "e", "puts", "e", ".", "message", "false", "end" ]
Initialize a CLI. Run the CLI. @param args [Array] arguments. @return [Boolean] true if command runs successfully.
[ "Initialize", "a", "CLI", ".", "Run", "the", "CLI", "." ]
85191908318125a4429a8fb5051ab4d2d133b316
https://github.com/xinminlabs/synvert/blob/85191908318125a4429a8fb5051ab4d2d133b316/lib/synvert/cli.rb#L25-L66
23,268
xinminlabs/synvert
lib/synvert/cli.rb
Synvert.CLI.run_option_parser
def run_option_parser(args) optparse = OptionParser.new do |opts| opts.banner = 'Usage: synvert [project_path]' opts.on '-d', '--load SNIPPET_PATHS', 'load custom snippets, snippet paths can be local file path or remote http url' do |snippet_paths| @options[:custom_snippet_paths] = snippet_paths.split(',').map(&:strip) end opts.on '-l', '--list', 'list all available snippets' do @options[:command] = 'list' end opts.on '-o', '--open SNIPPET_NAME', 'Open a snippet' do |snippet_name| @options[:command] = 'open' @options[:snippet_name] = snippet_name end opts.on '-q', '--query QUERY', 'query specified snippets' do |query| @options[:command] = 'query' @options[:query] = query end opts.on '--skip FILE_PATTERNS', 'skip specified files or directories, separated by comma, e.g. app/models/post.rb,vendor/plugins/**/*.rb' do |file_patterns| @options[:skip_file_patterns] = file_patterns.split(',') end opts.on '-s', '--show SNIPPET_NAME', 'show specified snippet description, SNIPPET_NAME is combined by group and name, e.g. ruby/new_hash_syntax' do |snippet_name| @options[:command] = 'show' @options[:snippet_name] = snippet_name end opts.on '--sync', 'sync snippets' do @options[:command] = 'sync' end opts.on '-r', '--run SNIPPET_NAMES', 'run specified snippets, each SNIPPET_NAME is combined by group and name, e.g. ruby/new_hash_syntax,ruby/new_lambda_syntax' do |snippet_names| @options[:snippet_names] = snippet_names.split(',').map(&:strip) end opts.on '-v', '--version', 'show this version' do puts Core::VERSION exit end end paths = optparse.parse(args) Core::Configuration.instance.set :path, paths.first || Dir.pwd if @options[:skip_file_patterns] && !@options[:skip_file_patterns].empty? skip_files = @options[:skip_file_patterns].map do |file_pattern| full_file_pattern = File.join(Core::Configuration.instance.get(:path), file_pattern) Dir.glob(full_file_pattern) end.flatten Core::Configuration.instance.set :skip_files, skip_files end end
ruby
def run_option_parser(args) optparse = OptionParser.new do |opts| opts.banner = 'Usage: synvert [project_path]' opts.on '-d', '--load SNIPPET_PATHS', 'load custom snippets, snippet paths can be local file path or remote http url' do |snippet_paths| @options[:custom_snippet_paths] = snippet_paths.split(',').map(&:strip) end opts.on '-l', '--list', 'list all available snippets' do @options[:command] = 'list' end opts.on '-o', '--open SNIPPET_NAME', 'Open a snippet' do |snippet_name| @options[:command] = 'open' @options[:snippet_name] = snippet_name end opts.on '-q', '--query QUERY', 'query specified snippets' do |query| @options[:command] = 'query' @options[:query] = query end opts.on '--skip FILE_PATTERNS', 'skip specified files or directories, separated by comma, e.g. app/models/post.rb,vendor/plugins/**/*.rb' do |file_patterns| @options[:skip_file_patterns] = file_patterns.split(',') end opts.on '-s', '--show SNIPPET_NAME', 'show specified snippet description, SNIPPET_NAME is combined by group and name, e.g. ruby/new_hash_syntax' do |snippet_name| @options[:command] = 'show' @options[:snippet_name] = snippet_name end opts.on '--sync', 'sync snippets' do @options[:command] = 'sync' end opts.on '-r', '--run SNIPPET_NAMES', 'run specified snippets, each SNIPPET_NAME is combined by group and name, e.g. ruby/new_hash_syntax,ruby/new_lambda_syntax' do |snippet_names| @options[:snippet_names] = snippet_names.split(',').map(&:strip) end opts.on '-v', '--version', 'show this version' do puts Core::VERSION exit end end paths = optparse.parse(args) Core::Configuration.instance.set :path, paths.first || Dir.pwd if @options[:skip_file_patterns] && !@options[:skip_file_patterns].empty? skip_files = @options[:skip_file_patterns].map do |file_pattern| full_file_pattern = File.join(Core::Configuration.instance.get(:path), file_pattern) Dir.glob(full_file_pattern) end.flatten Core::Configuration.instance.set :skip_files, skip_files end end
[ "def", "run_option_parser", "(", "args", ")", "optparse", "=", "OptionParser", ".", "new", "do", "|", "opts", "|", "opts", ".", "banner", "=", "'Usage: synvert [project_path]'", "opts", ".", "on", "'-d'", ",", "'--load SNIPPET_PATHS'", ",", "'load custom snippets, snippet paths can be local file path or remote http url'", "do", "|", "snippet_paths", "|", "@options", "[", ":custom_snippet_paths", "]", "=", "snippet_paths", ".", "split", "(", "','", ")", ".", "map", "(", ":strip", ")", "end", "opts", ".", "on", "'-l'", ",", "'--list'", ",", "'list all available snippets'", "do", "@options", "[", ":command", "]", "=", "'list'", "end", "opts", ".", "on", "'-o'", ",", "'--open SNIPPET_NAME'", ",", "'Open a snippet'", "do", "|", "snippet_name", "|", "@options", "[", ":command", "]", "=", "'open'", "@options", "[", ":snippet_name", "]", "=", "snippet_name", "end", "opts", ".", "on", "'-q'", ",", "'--query QUERY'", ",", "'query specified snippets'", "do", "|", "query", "|", "@options", "[", ":command", "]", "=", "'query'", "@options", "[", ":query", "]", "=", "query", "end", "opts", ".", "on", "'--skip FILE_PATTERNS'", ",", "'skip specified files or directories, separated by comma, e.g. app/models/post.rb,vendor/plugins/**/*.rb'", "do", "|", "file_patterns", "|", "@options", "[", ":skip_file_patterns", "]", "=", "file_patterns", ".", "split", "(", "','", ")", "end", "opts", ".", "on", "'-s'", ",", "'--show SNIPPET_NAME'", ",", "'show specified snippet description, SNIPPET_NAME is combined by group and name, e.g. ruby/new_hash_syntax'", "do", "|", "snippet_name", "|", "@options", "[", ":command", "]", "=", "'show'", "@options", "[", ":snippet_name", "]", "=", "snippet_name", "end", "opts", ".", "on", "'--sync'", ",", "'sync snippets'", "do", "@options", "[", ":command", "]", "=", "'sync'", "end", "opts", ".", "on", "'-r'", ",", "'--run SNIPPET_NAMES'", ",", "'run specified snippets, each SNIPPET_NAME is combined by group and name, e.g. ruby/new_hash_syntax,ruby/new_lambda_syntax'", "do", "|", "snippet_names", "|", "@options", "[", ":snippet_names", "]", "=", "snippet_names", ".", "split", "(", "','", ")", ".", "map", "(", ":strip", ")", "end", "opts", ".", "on", "'-v'", ",", "'--version'", ",", "'show this version'", "do", "puts", "Core", "::", "VERSION", "exit", "end", "end", "paths", "=", "optparse", ".", "parse", "(", "args", ")", "Core", "::", "Configuration", ".", "instance", ".", "set", ":path", ",", "paths", ".", "first", "||", "Dir", ".", "pwd", "if", "@options", "[", ":skip_file_patterns", "]", "&&", "!", "@options", "[", ":skip_file_patterns", "]", ".", "empty?", "skip_files", "=", "@options", "[", ":skip_file_patterns", "]", ".", "map", "do", "|", "file_pattern", "|", "full_file_pattern", "=", "File", ".", "join", "(", "Core", "::", "Configuration", ".", "instance", ".", "get", "(", ":path", ")", ",", "file_pattern", ")", "Dir", ".", "glob", "(", "full_file_pattern", ")", "end", ".", "flatten", "Core", "::", "Configuration", ".", "instance", ".", "set", ":skip_files", ",", "skip_files", "end", "end" ]
Run OptionParser to parse arguments.
[ "Run", "OptionParser", "to", "parse", "arguments", "." ]
85191908318125a4429a8fb5051ab4d2d133b316
https://github.com/xinminlabs/synvert/blob/85191908318125a4429a8fb5051ab4d2d133b316/lib/synvert/cli.rb#L71-L115
23,269
xinminlabs/synvert
lib/synvert/cli.rb
Synvert.CLI.load_rewriters
def load_rewriters Dir.glob(File.join(default_snippets_path, 'lib/**/*.rb')).each { |file| require file } @options[:custom_snippet_paths].each do |snippet_path| if snippet_path =~ /^http/ uri = URI.parse snippet_path eval(uri.read) else require snippet_path end end rescue FileUtils.rm_rf default_snippets_path retry end
ruby
def load_rewriters Dir.glob(File.join(default_snippets_path, 'lib/**/*.rb')).each { |file| require file } @options[:custom_snippet_paths].each do |snippet_path| if snippet_path =~ /^http/ uri = URI.parse snippet_path eval(uri.read) else require snippet_path end end rescue FileUtils.rm_rf default_snippets_path retry end
[ "def", "load_rewriters", "Dir", ".", "glob", "(", "File", ".", "join", "(", "default_snippets_path", ",", "'lib/**/*.rb'", ")", ")", ".", "each", "{", "|", "file", "|", "require", "file", "}", "@options", "[", ":custom_snippet_paths", "]", ".", "each", "do", "|", "snippet_path", "|", "if", "snippet_path", "=~", "/", "/", "uri", "=", "URI", ".", "parse", "snippet_path", "eval", "(", "uri", ".", "read", ")", "else", "require", "snippet_path", "end", "end", "rescue", "FileUtils", ".", "rm_rf", "default_snippets_path", "retry", "end" ]
Load all rewriters.
[ "Load", "all", "rewriters", "." ]
85191908318125a4429a8fb5051ab4d2d133b316
https://github.com/xinminlabs/synvert/blob/85191908318125a4429a8fb5051ab4d2d133b316/lib/synvert/cli.rb#L118-L132
23,270
xinminlabs/synvert
lib/synvert/cli.rb
Synvert.CLI.list_available_rewriters
def list_available_rewriters if Core::Rewriter.availables.empty? puts 'There is no snippet under ~/.synvert, please run `synvert --sync` to fetch snippets.' else Core::Rewriter.availables.each do |group, rewriters| puts group rewriters.each do |name, rewriter| puts ' ' + name end end puts end end
ruby
def list_available_rewriters if Core::Rewriter.availables.empty? puts 'There is no snippet under ~/.synvert, please run `synvert --sync` to fetch snippets.' else Core::Rewriter.availables.each do |group, rewriters| puts group rewriters.each do |name, rewriter| puts ' ' + name end end puts end end
[ "def", "list_available_rewriters", "if", "Core", "::", "Rewriter", ".", "availables", ".", "empty?", "puts", "'There is no snippet under ~/.synvert, please run `synvert --sync` to fetch snippets.'", "else", "Core", "::", "Rewriter", ".", "availables", ".", "each", "do", "|", "group", ",", "rewriters", "|", "puts", "group", "rewriters", ".", "each", "do", "|", "name", ",", "rewriter", "|", "puts", "' '", "+", "name", "end", "end", "puts", "end", "end" ]
List and print all available rewriters.
[ "List", "and", "print", "all", "available", "rewriters", "." ]
85191908318125a4429a8fb5051ab4d2d133b316
https://github.com/xinminlabs/synvert/blob/85191908318125a4429a8fb5051ab4d2d133b316/lib/synvert/cli.rb#L135-L147
23,271
xinminlabs/synvert
lib/synvert/cli.rb
Synvert.CLI.open_rewriter
def open_rewriter editor = [ENV['SYNVERT_EDITOR'], ENV['EDITOR']].find { |e| !e.nil? && !e.empty? } return puts 'To open a synvert snippet, set $EDITOR or $SYNVERT_EDITOR' unless editor path = File.expand_path(File.join(default_snippets_path, "lib/#{@options[:snippet_name]}.rb")) if File.exist? path system editor, path else puts "Can't run #{editor} #{path}" end end
ruby
def open_rewriter editor = [ENV['SYNVERT_EDITOR'], ENV['EDITOR']].find { |e| !e.nil? && !e.empty? } return puts 'To open a synvert snippet, set $EDITOR or $SYNVERT_EDITOR' unless editor path = File.expand_path(File.join(default_snippets_path, "lib/#{@options[:snippet_name]}.rb")) if File.exist? path system editor, path else puts "Can't run #{editor} #{path}" end end
[ "def", "open_rewriter", "editor", "=", "[", "ENV", "[", "'SYNVERT_EDITOR'", "]", ",", "ENV", "[", "'EDITOR'", "]", "]", ".", "find", "{", "|", "e", "|", "!", "e", ".", "nil?", "&&", "!", "e", ".", "empty?", "}", "return", "puts", "'To open a synvert snippet, set $EDITOR or $SYNVERT_EDITOR'", "unless", "editor", "path", "=", "File", ".", "expand_path", "(", "File", ".", "join", "(", "default_snippets_path", ",", "\"lib/#{@options[:snippet_name]}.rb\"", ")", ")", "if", "File", ".", "exist?", "path", "system", "editor", ",", "path", "else", "puts", "\"Can't run #{editor} #{path}\"", "end", "end" ]
Open one rewriter.
[ "Open", "one", "rewriter", "." ]
85191908318125a4429a8fb5051ab4d2d133b316
https://github.com/xinminlabs/synvert/blob/85191908318125a4429a8fb5051ab4d2d133b316/lib/synvert/cli.rb#L150-L160
23,272
xinminlabs/synvert
lib/synvert/cli.rb
Synvert.CLI.query_available_rewriters
def query_available_rewriters Core::Rewriter.availables.each do |group, rewriters| if group.include? @options[:query] puts group rewriters.each do |name, rewriter| puts ' ' + name end elsif rewriters.keys.any? { |name| name.include? @options[:query] } puts group rewriters.each do |name, rewriter| puts ' ' + name if name.include?(@options[:query]) end end end puts end
ruby
def query_available_rewriters Core::Rewriter.availables.each do |group, rewriters| if group.include? @options[:query] puts group rewriters.each do |name, rewriter| puts ' ' + name end elsif rewriters.keys.any? { |name| name.include? @options[:query] } puts group rewriters.each do |name, rewriter| puts ' ' + name if name.include?(@options[:query]) end end end puts end
[ "def", "query_available_rewriters", "Core", "::", "Rewriter", ".", "availables", ".", "each", "do", "|", "group", ",", "rewriters", "|", "if", "group", ".", "include?", "@options", "[", ":query", "]", "puts", "group", "rewriters", ".", "each", "do", "|", "name", ",", "rewriter", "|", "puts", "' '", "+", "name", "end", "elsif", "rewriters", ".", "keys", ".", "any?", "{", "|", "name", "|", "name", ".", "include?", "@options", "[", ":query", "]", "}", "puts", "group", "rewriters", ".", "each", "do", "|", "name", ",", "rewriter", "|", "puts", "' '", "+", "name", "if", "name", ".", "include?", "(", "@options", "[", ":query", "]", ")", "end", "end", "end", "puts", "end" ]
Query and print available rewriters.
[ "Query", "and", "print", "available", "rewriters", "." ]
85191908318125a4429a8fb5051ab4d2d133b316
https://github.com/xinminlabs/synvert/blob/85191908318125a4429a8fb5051ab4d2d133b316/lib/synvert/cli.rb#L163-L178
23,273
xinminlabs/synvert
lib/synvert/cli.rb
Synvert.CLI.show_rewriter
def show_rewriter group, name = @options[:snippet_name].split('/') rewriter = Core::Rewriter.fetch(group, name) if rewriter rewriter.process_with_sandbox puts rewriter.description rewriter.sub_snippets.each do |sub_rewriter| puts puts '=' * 80 puts "snippet: #{sub_rewriter.name}" puts '=' * 80 puts sub_rewriter.description end else puts "snippet #{@options[:snippet_name]} not found" end end
ruby
def show_rewriter group, name = @options[:snippet_name].split('/') rewriter = Core::Rewriter.fetch(group, name) if rewriter rewriter.process_with_sandbox puts rewriter.description rewriter.sub_snippets.each do |sub_rewriter| puts puts '=' * 80 puts "snippet: #{sub_rewriter.name}" puts '=' * 80 puts sub_rewriter.description end else puts "snippet #{@options[:snippet_name]} not found" end end
[ "def", "show_rewriter", "group", ",", "name", "=", "@options", "[", ":snippet_name", "]", ".", "split", "(", "'/'", ")", "rewriter", "=", "Core", "::", "Rewriter", ".", "fetch", "(", "group", ",", "name", ")", "if", "rewriter", "rewriter", ".", "process_with_sandbox", "puts", "rewriter", ".", "description", "rewriter", ".", "sub_snippets", ".", "each", "do", "|", "sub_rewriter", "|", "puts", "puts", "'='", "*", "80", "puts", "\"snippet: #{sub_rewriter.name}\"", "puts", "'='", "*", "80", "puts", "sub_rewriter", ".", "description", "end", "else", "puts", "\"snippet #{@options[:snippet_name]} not found\"", "end", "end" ]
Show and print one rewriter.
[ "Show", "and", "print", "one", "rewriter", "." ]
85191908318125a4429a8fb5051ab4d2d133b316
https://github.com/xinminlabs/synvert/blob/85191908318125a4429a8fb5051ab4d2d133b316/lib/synvert/cli.rb#L181-L197
23,274
dorack/jiralicious
lib/jiralicious/session.rb
Jiralicious.Session.request
def request(method, *options) response_handler = if options.last.is_a?(Hash) && options.last[:handler] options.last.delete(:handler) else handler end self.class.base_uri Jiralicious.uri before_request if respond_to?(:before_request) response = self.class.send(method, *options) after_request(response) if respond_to?(:after_request) response_handler.call(response) end
ruby
def request(method, *options) response_handler = if options.last.is_a?(Hash) && options.last[:handler] options.last.delete(:handler) else handler end self.class.base_uri Jiralicious.uri before_request if respond_to?(:before_request) response = self.class.send(method, *options) after_request(response) if respond_to?(:after_request) response_handler.call(response) end
[ "def", "request", "(", "method", ",", "*", "options", ")", "response_handler", "=", "if", "options", ".", "last", ".", "is_a?", "(", "Hash", ")", "&&", "options", ".", "last", "[", ":handler", "]", "options", ".", "last", ".", "delete", "(", ":handler", ")", "else", "handler", "end", "self", ".", "class", ".", "base_uri", "Jiralicious", ".", "uri", "before_request", "if", "respond_to?", "(", ":before_request", ")", "response", "=", "self", ".", "class", ".", "send", "(", "method", ",", "options", ")", "after_request", "(", "response", ")", "if", "respond_to?", "(", ":after_request", ")", "response_handler", ".", "call", "(", "response", ")", "end" ]
Main access method to request data from the Jira API [Arguments] :method (required) http method type :options (required) request specific options
[ "Main", "access", "method", "to", "request", "data", "from", "the", "Jira", "API" ]
e907cba8618fb15893b62666e195a5288a9899d8
https://github.com/dorack/jiralicious/blob/e907cba8618fb15893b62666e195a5288a9899d8/lib/jiralicious/session.rb#L25-L38
23,275
theforeman/staypuft
app/models/staypuft/deployment.rb
Staypuft.Deployment.update_hostgroup_list
def update_hostgroup_list old_deployment_role_hostgroups = deployment_role_hostgroups.to_a new_deployment_role_hostgroups = layout.layout_roles.map do |layout_role| deployment_role_hostgroup = deployment_role_hostgroups.where(:role_id => layout_role.role).first_or_initialize do |drh| drh.hostgroup = Hostgroup.new(name: layout_role.role.name, parent: hostgroup) end deployment_role_hostgroup.hostgroup.add_puppetclasses_from_resource(layout_role.role) layout_role.role.services.each do |service| deployment_role_hostgroup.hostgroup.add_puppetclasses_from_resource(service) end # deployment_role_hostgroup.hostgroup.save! deployment_role_hostgroup.deploy_order = layout_role.deploy_order deployment_role_hostgroup.save! deployment_role_hostgroup end # delete any prior mappings that remain (old_deployment_role_hostgroups - new_deployment_role_hostgroups).each &:destroy end
ruby
def update_hostgroup_list old_deployment_role_hostgroups = deployment_role_hostgroups.to_a new_deployment_role_hostgroups = layout.layout_roles.map do |layout_role| deployment_role_hostgroup = deployment_role_hostgroups.where(:role_id => layout_role.role).first_or_initialize do |drh| drh.hostgroup = Hostgroup.new(name: layout_role.role.name, parent: hostgroup) end deployment_role_hostgroup.hostgroup.add_puppetclasses_from_resource(layout_role.role) layout_role.role.services.each do |service| deployment_role_hostgroup.hostgroup.add_puppetclasses_from_resource(service) end # deployment_role_hostgroup.hostgroup.save! deployment_role_hostgroup.deploy_order = layout_role.deploy_order deployment_role_hostgroup.save! deployment_role_hostgroup end # delete any prior mappings that remain (old_deployment_role_hostgroups - new_deployment_role_hostgroups).each &:destroy end
[ "def", "update_hostgroup_list", "old_deployment_role_hostgroups", "=", "deployment_role_hostgroups", ".", "to_a", "new_deployment_role_hostgroups", "=", "layout", ".", "layout_roles", ".", "map", "do", "|", "layout_role", "|", "deployment_role_hostgroup", "=", "deployment_role_hostgroups", ".", "where", "(", ":role_id", "=>", "layout_role", ".", "role", ")", ".", "first_or_initialize", "do", "|", "drh", "|", "drh", ".", "hostgroup", "=", "Hostgroup", ".", "new", "(", "name", ":", "layout_role", ".", "role", ".", "name", ",", "parent", ":", "hostgroup", ")", "end", "deployment_role_hostgroup", ".", "hostgroup", ".", "add_puppetclasses_from_resource", "(", "layout_role", ".", "role", ")", "layout_role", ".", "role", ".", "services", ".", "each", "do", "|", "service", "|", "deployment_role_hostgroup", ".", "hostgroup", ".", "add_puppetclasses_from_resource", "(", "service", ")", "end", "# deployment_role_hostgroup.hostgroup.save!", "deployment_role_hostgroup", ".", "deploy_order", "=", "layout_role", ".", "deploy_order", "deployment_role_hostgroup", ".", "save!", "deployment_role_hostgroup", "end", "# delete any prior mappings that remain", "(", "old_deployment_role_hostgroups", "-", "new_deployment_role_hostgroups", ")", ".", "each", ":destroy", "end" ]
After setting or changing layout, update the set of child hostgroups, adding groups for any roles not already represented, and removing others no longer needed.
[ "After", "setting", "or", "changing", "layout", "update", "the", "set", "of", "child", "hostgroups", "adding", "groups", "for", "any", "roles", "not", "already", "represented", "and", "removing", "others", "no", "longer", "needed", "." ]
58b0dec6a027bb6fb10c5db4dc5e4430faba8e6f
https://github.com/theforeman/staypuft/blob/58b0dec6a027bb6fb10c5db4dc5e4430faba8e6f/app/models/staypuft/deployment.rb#L353-L374
23,276
dorack/jiralicious
lib/jiralicious/versions.rb
Jiralicious.Version.update
def update(details) details.each do |k, v| send("#{k}=", v) end self.class.update(version_key, details) end
ruby
def update(details) details.each do |k, v| send("#{k}=", v) end self.class.update(version_key, details) end
[ "def", "update", "(", "details", ")", "details", ".", "each", "do", "|", "k", ",", "v", "|", "send", "(", "\"#{k}=\"", ",", "v", ")", "end", "self", ".", "class", ".", "update", "(", "version_key", ",", "details", ")", "end" ]
Updates a version [Arguments] :details (required) Details of the version to be updated
[ "Updates", "a", "version" ]
e907cba8618fb15893b62666e195a5288a9899d8
https://github.com/dorack/jiralicious/blob/e907cba8618fb15893b62666e195a5288a9899d8/lib/jiralicious/versions.rb#L136-L141
23,277
dorack/jiralicious
lib/jiralicious/oauth_session.rb
Jiralicious.OauthSession.get_secret
def get_secret if Jiralicious.oauth_secret.nil? IO.read(Jiralicious.config_path + Jiralicious.oauth_secret_filename) else Jiralicious.oauth_secret end end
ruby
def get_secret if Jiralicious.oauth_secret.nil? IO.read(Jiralicious.config_path + Jiralicious.oauth_secret_filename) else Jiralicious.oauth_secret end end
[ "def", "get_secret", "if", "Jiralicious", ".", "oauth_secret", ".", "nil?", "IO", ".", "read", "(", "Jiralicious", ".", "config_path", "+", "Jiralicious", ".", "oauth_secret_filename", ")", "else", "Jiralicious", ".", "oauth_secret", "end", "end" ]
returns the oauth_secret parameter or the file
[ "returns", "the", "oauth_secret", "parameter", "or", "the", "file" ]
e907cba8618fb15893b62666e195a5288a9899d8
https://github.com/dorack/jiralicious/blob/e907cba8618fb15893b62666e195a5288a9899d8/lib/jiralicious/oauth_session.rb#L102-L108
23,278
dorack/jiralicious
lib/jiralicious/oauth_session.rb
Jiralicious.OauthSession.handler
def handler proc do |response| case response.code when 200..204 response else message = response.body message = message["errorMessages"].join('\n') if message.is_a?(Hash) Jiralicious::JiraError.new(message) end end end
ruby
def handler proc do |response| case response.code when 200..204 response else message = response.body message = message["errorMessages"].join('\n') if message.is_a?(Hash) Jiralicious::JiraError.new(message) end end end
[ "def", "handler", "proc", "do", "|", "response", "|", "case", "response", ".", "code", "when", "200", "..", "204", "response", "else", "message", "=", "response", ".", "body", "message", "=", "message", "[", "\"errorMessages\"", "]", ".", "join", "(", "'\\n'", ")", "if", "message", ".", "is_a?", "(", "Hash", ")", "Jiralicious", "::", "JiraError", ".", "new", "(", "message", ")", "end", "end", "end" ]
Configures the default handler. This can be overridden in the child class to provide additional error handling.
[ "Configures", "the", "default", "handler", ".", "This", "can", "be", "overridden", "in", "the", "child", "class", "to", "provide", "additional", "error", "handling", "." ]
e907cba8618fb15893b62666e195a5288a9899d8
https://github.com/dorack/jiralicious/blob/e907cba8618fb15893b62666e195a5288a9899d8/lib/jiralicious/oauth_session.rb#L114-L125
23,279
dorack/jiralicious
lib/jiralicious/cookie_session.rb
Jiralicious.CookieSession.after_request
def after_request(response) unless @authenticating if captcha_required(response) # rubocop:disable Style/GuardClause raise Jiralicious::CaptchaRequired, "Captacha is required. Try logging into Jira via the web interface" elsif cookie_invalid(response) # Can usually be fixed by logging in again clear_session raise Jiralicious::CookieExpired end end @authenticating = false end
ruby
def after_request(response) unless @authenticating if captcha_required(response) # rubocop:disable Style/GuardClause raise Jiralicious::CaptchaRequired, "Captacha is required. Try logging into Jira via the web interface" elsif cookie_invalid(response) # Can usually be fixed by logging in again clear_session raise Jiralicious::CookieExpired end end @authenticating = false end
[ "def", "after_request", "(", "response", ")", "unless", "@authenticating", "if", "captcha_required", "(", "response", ")", "# rubocop:disable Style/GuardClause", "raise", "Jiralicious", "::", "CaptchaRequired", ",", "\"Captacha is required. Try logging into Jira via the web interface\"", "elsif", "cookie_invalid", "(", "response", ")", "# Can usually be fixed by logging in again", "clear_session", "raise", "Jiralicious", "::", "CookieExpired", "end", "end", "@authenticating", "=", "false", "end" ]
Handles the response from the request
[ "Handles", "the", "response", "from", "the", "request" ]
e907cba8618fb15893b62666e195a5288a9899d8
https://github.com/dorack/jiralicious/blob/e907cba8618fb15893b62666e195a5288a9899d8/lib/jiralicious/cookie_session.rb#L24-L35
23,280
dorack/jiralicious
lib/jiralicious/cookie_session.rb
Jiralicious.CookieSession.login
def login @authenticating = true handler = proc do |response| if response.code == 200 @session = response["session"] @login_info = response["loginInfo"] self.class.cookies(session["name"] => session["value"]) else clear_session case response.code when 401 then raise Jiralicious::InvalidLogin, "Invalid login" when 403 raise Jiralicious::CaptchaRequired, "Captacha is required. Try logging into Jira via the web interface" else # Give Net::HTTP reason raise Jiralicious::JiraError, response end end end request( :post, "/rest/auth/latest/session", body: { username: Jiralicious.username, password: Jiralicious.password }.to_json, handler: handler ) end
ruby
def login @authenticating = true handler = proc do |response| if response.code == 200 @session = response["session"] @login_info = response["loginInfo"] self.class.cookies(session["name"] => session["value"]) else clear_session case response.code when 401 then raise Jiralicious::InvalidLogin, "Invalid login" when 403 raise Jiralicious::CaptchaRequired, "Captacha is required. Try logging into Jira via the web interface" else # Give Net::HTTP reason raise Jiralicious::JiraError, response end end end request( :post, "/rest/auth/latest/session", body: { username: Jiralicious.username, password: Jiralicious.password }.to_json, handler: handler ) end
[ "def", "login", "@authenticating", "=", "true", "handler", "=", "proc", "do", "|", "response", "|", "if", "response", ".", "code", "==", "200", "@session", "=", "response", "[", "\"session\"", "]", "@login_info", "=", "response", "[", "\"loginInfo\"", "]", "self", ".", "class", ".", "cookies", "(", "session", "[", "\"name\"", "]", "=>", "session", "[", "\"value\"", "]", ")", "else", "clear_session", "case", "response", ".", "code", "when", "401", "then", "raise", "Jiralicious", "::", "InvalidLogin", ",", "\"Invalid login\"", "when", "403", "raise", "Jiralicious", "::", "CaptchaRequired", ",", "\"Captacha is required. Try logging into Jira via the web interface\"", "else", "# Give Net::HTTP reason", "raise", "Jiralicious", "::", "JiraError", ",", "response", "end", "end", "end", "request", "(", ":post", ",", "\"/rest/auth/latest/session\"", ",", "body", ":", "{", "username", ":", "Jiralicious", ".", "username", ",", "password", ":", "Jiralicious", ".", "password", "}", ".", "to_json", ",", "handler", ":", "handler", ")", "end" ]
Authenticates the login
[ "Authenticates", "the", "login" ]
e907cba8618fb15893b62666e195a5288a9899d8
https://github.com/dorack/jiralicious/blob/e907cba8618fb15893b62666e195a5288a9899d8/lib/jiralicious/cookie_session.rb#L38-L67
23,281
dorack/jiralicious
lib/jiralicious/cookie_session.rb
Jiralicious.CookieSession.logout
def logout handler = proc do if response.code == 204 clear_session else case response.code when 401 then raise Jiralicious::NotLoggedIn, "Not logged in" else # Give Net::HTTP reason raise Jiralicious::JiraError, response end end end request(:delete, "/rest/auth/latest/session", handler: handler) end
ruby
def logout handler = proc do if response.code == 204 clear_session else case response.code when 401 then raise Jiralicious::NotLoggedIn, "Not logged in" else # Give Net::HTTP reason raise Jiralicious::JiraError, response end end end request(:delete, "/rest/auth/latest/session", handler: handler) end
[ "def", "logout", "handler", "=", "proc", "do", "if", "response", ".", "code", "==", "204", "clear_session", "else", "case", "response", ".", "code", "when", "401", "then", "raise", "Jiralicious", "::", "NotLoggedIn", ",", "\"Not logged in\"", "else", "# Give Net::HTTP reason", "raise", "Jiralicious", "::", "JiraError", ",", "response", "end", "end", "end", "request", "(", ":delete", ",", "\"/rest/auth/latest/session\"", ",", "handler", ":", "handler", ")", "end" ]
Logs out of the API
[ "Logs", "out", "of", "the", "API" ]
e907cba8618fb15893b62666e195a5288a9899d8
https://github.com/dorack/jiralicious/blob/e907cba8618fb15893b62666e195a5288a9899d8/lib/jiralicious/cookie_session.rb#L70-L86
23,282
dorack/jiralicious
lib/jiralicious/issue.rb
Jiralicious.Issue.save
def save if loaded? self.class.update(@fields.format_for_update, jira_key) else response = self.class.create(@fields.format_for_create) self.jira_key = response.parsed_response["key"] end jira_key end
ruby
def save if loaded? self.class.update(@fields.format_for_update, jira_key) else response = self.class.create(@fields.format_for_create) self.jira_key = response.parsed_response["key"] end jira_key end
[ "def", "save", "if", "loaded?", "self", ".", "class", ".", "update", "(", "@fields", ".", "format_for_update", ",", "jira_key", ")", "else", "response", "=", "self", ".", "class", ".", "create", "(", "@fields", ".", "format_for_create", ")", "self", ".", "jira_key", "=", "response", ".", "parsed_response", "[", "\"key\"", "]", "end", "jira_key", "end" ]
Saves the current Issue but does not update itself.
[ "Saves", "the", "current", "Issue", "but", "does", "not", "update", "itself", "." ]
e907cba8618fb15893b62666e195a5288a9899d8
https://github.com/dorack/jiralicious/blob/e907cba8618fb15893b62666e195a5288a9899d8/lib/jiralicious/issue.rb#L253-L261
23,283
leonhartX/danger-eslint
lib/eslint/plugin.rb
Danger.DangerEslint.lint_results
def lint_results bin = eslint_path raise 'eslint is not installed' unless bin return run_lint(bin, '.') unless filtering ((git.modified_files - git.deleted_files) + git.added_files) .select { |f| f.end_with? '.js' } .map { |f| f.gsub("#{Dir.pwd}/", '') } .map { |f| run_lint(bin, f).first } end
ruby
def lint_results bin = eslint_path raise 'eslint is not installed' unless bin return run_lint(bin, '.') unless filtering ((git.modified_files - git.deleted_files) + git.added_files) .select { |f| f.end_with? '.js' } .map { |f| f.gsub("#{Dir.pwd}/", '') } .map { |f| run_lint(bin, f).first } end
[ "def", "lint_results", "bin", "=", "eslint_path", "raise", "'eslint is not installed'", "unless", "bin", "return", "run_lint", "(", "bin", ",", "'.'", ")", "unless", "filtering", "(", "(", "git", ".", "modified_files", "-", "git", ".", "deleted_files", ")", "+", "git", ".", "added_files", ")", ".", "select", "{", "|", "f", "|", "f", ".", "end_with?", "'.js'", "}", ".", "map", "{", "|", "f", "|", "f", ".", "gsub", "(", "\"#{Dir.pwd}/\"", ",", "''", ")", "}", ".", "map", "{", "|", "f", "|", "run_lint", "(", "bin", ",", "f", ")", ".", "first", "}", "end" ]
Get lint result regards the filtering option return [Hash]
[ "Get", "lint", "result", "regards", "the", "filtering", "option" ]
f51dca105e8c87326b35a27e9a349cd486e7a5e2
https://github.com/leonhartX/danger-eslint/blob/f51dca105e8c87326b35a27e9a349cd486e7a5e2/lib/eslint/plugin.rb#L55-L63
23,284
leonhartX/danger-eslint
lib/eslint/plugin.rb
Danger.DangerEslint.send_comment
def send_comment(results) dir = "#{Dir.pwd}/" results['messages'].each do |r| filename = results['filePath'].gsub(dir, '') method = r['severity'] > 1 ? 'fail' : 'warn' send(method, r['message'], file: filename, line: r['line']) end end
ruby
def send_comment(results) dir = "#{Dir.pwd}/" results['messages'].each do |r| filename = results['filePath'].gsub(dir, '') method = r['severity'] > 1 ? 'fail' : 'warn' send(method, r['message'], file: filename, line: r['line']) end end
[ "def", "send_comment", "(", "results", ")", "dir", "=", "\"#{Dir.pwd}/\"", "results", "[", "'messages'", "]", ".", "each", "do", "|", "r", "|", "filename", "=", "results", "[", "'filePath'", "]", ".", "gsub", "(", "dir", ",", "''", ")", "method", "=", "r", "[", "'severity'", "]", ">", "1", "?", "'fail'", ":", "'warn'", "send", "(", "method", ",", "r", "[", "'message'", "]", ",", "file", ":", "filename", ",", "line", ":", "r", "[", "'line'", "]", ")", "end", "end" ]
Send comment with danger's warn or fail method. @return [void]
[ "Send", "comment", "with", "danger", "s", "warn", "or", "fail", "method", "." ]
f51dca105e8c87326b35a27e9a349cd486e7a5e2
https://github.com/leonhartX/danger-eslint/blob/f51dca105e8c87326b35a27e9a349cd486e7a5e2/lib/eslint/plugin.rb#L85-L92
23,285
dorack/jiralicious
lib/jiralicious/component.rb
Jiralicious.Component.update
def update(details) details.each do |k, v| send("#{k}=", v) end self.class.update(component_key, details) end
ruby
def update(details) details.each do |k, v| send("#{k}=", v) end self.class.update(component_key, details) end
[ "def", "update", "(", "details", ")", "details", ".", "each", "do", "|", "k", ",", "v", "|", "send", "(", "\"#{k}=\"", ",", "v", ")", "end", "self", ".", "class", ".", "update", "(", "component_key", ",", "details", ")", "end" ]
Updates a component [Arguments] :details (required) Details of the component to be updated
[ "Updates", "a", "component" ]
e907cba8618fb15893b62666e195a5288a9899d8
https://github.com/dorack/jiralicious/blob/e907cba8618fb15893b62666e195a5288a9899d8/lib/jiralicious/component.rb#L94-L99
23,286
dorack/jiralicious
lib/jiralicious/base.rb
Jiralicious.Base.method_missing
def method_missing(meth, *args, &block) if !loaded? self.loaded = true reload send(meth, *args, &block) else super end end
ruby
def method_missing(meth, *args, &block) if !loaded? self.loaded = true reload send(meth, *args, &block) else super end end
[ "def", "method_missing", "(", "meth", ",", "*", "args", ",", "&", "block", ")", "if", "!", "loaded?", "self", ".", "loaded", "=", "true", "reload", "send", "(", "meth", ",", "args", ",", "block", ")", "else", "super", "end", "end" ]
Overrides the default method_missing check. This override is used in lazy loading to ensure that the requested field or method is truly unavailable. [Arguments] :meth (system) :args (system) :block (system)
[ "Overrides", "the", "default", "method_missing", "check", ".", "This", "override", "is", "used", "in", "lazy", "loading", "to", "ensure", "that", "the", "requested", "field", "or", "method", "is", "truly", "unavailable", "." ]
e907cba8618fb15893b62666e195a5288a9899d8
https://github.com/dorack/jiralicious/blob/e907cba8618fb15893b62666e195a5288a9899d8/lib/jiralicious/base.rb#L212-L220
23,287
dorack/jiralicious
lib/jiralicious/configuration.rb
Jiralicious.Configuration.options
def options VALID_OPTIONS.inject({}) do |option, key| option.merge!(key => send(key)) end end
ruby
def options VALID_OPTIONS.inject({}) do |option, key| option.merge!(key => send(key)) end end
[ "def", "options", "VALID_OPTIONS", ".", "inject", "(", "{", "}", ")", "do", "|", "option", ",", "key", "|", "option", ".", "merge!", "(", "key", "=>", "send", "(", "key", ")", ")", "end", "end" ]
Pass options to set the values
[ "Pass", "options", "to", "set", "the", "values" ]
e907cba8618fb15893b62666e195a5288a9899d8
https://github.com/dorack/jiralicious/blob/e907cba8618fb15893b62666e195a5288a9899d8/lib/jiralicious/configuration.rb#L44-L48
23,288
dorack/jiralicious
lib/jiralicious/configuration.rb
Jiralicious.Configuration.reset
def reset self.username = DEFAULT_USERNAME self.password = DEFAULT_PASSWORD self.uri = DEFAULT_URI self.api_version = DEFAULT_API_VERSION self.auth_type = DEFAULT_AUTH_TYPE self.project = nil self.oauth_secret = nil self.oauth_secret_filename = nil self.oauth_pass_phrase = nil self.oauth_consumer_key = nil self.config_path = nil end
ruby
def reset self.username = DEFAULT_USERNAME self.password = DEFAULT_PASSWORD self.uri = DEFAULT_URI self.api_version = DEFAULT_API_VERSION self.auth_type = DEFAULT_AUTH_TYPE self.project = nil self.oauth_secret = nil self.oauth_secret_filename = nil self.oauth_pass_phrase = nil self.oauth_consumer_key = nil self.config_path = nil end
[ "def", "reset", "self", ".", "username", "=", "DEFAULT_USERNAME", "self", ".", "password", "=", "DEFAULT_PASSWORD", "self", ".", "uri", "=", "DEFAULT_URI", "self", ".", "api_version", "=", "DEFAULT_API_VERSION", "self", ".", "auth_type", "=", "DEFAULT_AUTH_TYPE", "self", ".", "project", "=", "nil", "self", ".", "oauth_secret", "=", "nil", "self", ".", "oauth_secret_filename", "=", "nil", "self", ".", "oauth_pass_phrase", "=", "nil", "self", ".", "oauth_consumer_key", "=", "nil", "self", ".", "config_path", "=", "nil", "end" ]
Resets all attributes to default values
[ "Resets", "all", "attributes", "to", "default", "values" ]
e907cba8618fb15893b62666e195a5288a9899d8
https://github.com/dorack/jiralicious/blob/e907cba8618fb15893b62666e195a5288a9899d8/lib/jiralicious/configuration.rb#L53-L65
23,289
dorack/jiralicious
lib/jiralicious/configuration.rb
Jiralicious.Configuration.load_yml
def load_yml(yml_file, mode = nil) if File.exist?(yml_file) yml_cfg = OpenStruct.new(YAML.load_file(yml_file)) if mode.nil? || mode =~ /production/i yml_cfg.jira.each do |k, v| instance_variable_set("@#{k}", v) end else yml_cfg.send(mode).each do |k, v| instance_variable_set("@#{k}", v) end end else reset end end
ruby
def load_yml(yml_file, mode = nil) if File.exist?(yml_file) yml_cfg = OpenStruct.new(YAML.load_file(yml_file)) if mode.nil? || mode =~ /production/i yml_cfg.jira.each do |k, v| instance_variable_set("@#{k}", v) end else yml_cfg.send(mode).each do |k, v| instance_variable_set("@#{k}", v) end end else reset end end
[ "def", "load_yml", "(", "yml_file", ",", "mode", "=", "nil", ")", "if", "File", ".", "exist?", "(", "yml_file", ")", "yml_cfg", "=", "OpenStruct", ".", "new", "(", "YAML", ".", "load_file", "(", "yml_file", ")", ")", "if", "mode", ".", "nil?", "||", "mode", "=~", "/", "/i", "yml_cfg", ".", "jira", ".", "each", "do", "|", "k", ",", "v", "|", "instance_variable_set", "(", "\"@#{k}\"", ",", "v", ")", "end", "else", "yml_cfg", ".", "send", "(", "mode", ")", ".", "each", "do", "|", "k", ",", "v", "|", "instance_variable_set", "(", "\"@#{k}\"", ",", "v", ")", "end", "end", "else", "reset", "end", "end" ]
Loads the provided YML file. Can provide either direct or relational path to the file. It is recommended to send a direct path due to dynamic loading and/or different file locations due to different deployment methods. [Direct Path] /usr/project/somepath_to_file/jira.yml [Relational Path] Rails.root.to_s + "/config/jira.yml" "./config/jira.yml" [Arguments] :yml_file (required) path to file to load :mode (optional) used to define environment type
[ "Loads", "the", "provided", "YML", "file", "." ]
e907cba8618fb15893b62666e195a5288a9899d8
https://github.com/dorack/jiralicious/blob/e907cba8618fb15893b62666e195a5288a9899d8/lib/jiralicious/configuration.rb#L85-L100
23,290
theforeman/staypuft
app/models/staypuft/interface_assigner.rb
Staypuft.InterfaceAssigner.unassign_physical
def unassign_physical(interface) interface.ip = nil if interface.subnet.ipam? interface.subnet_id = nil unless interface.save @errors.push(interface.errors.full_messages) end end
ruby
def unassign_physical(interface) interface.ip = nil if interface.subnet.ipam? interface.subnet_id = nil unless interface.save @errors.push(interface.errors.full_messages) end end
[ "def", "unassign_physical", "(", "interface", ")", "interface", ".", "ip", "=", "nil", "if", "interface", ".", "subnet", ".", "ipam?", "interface", ".", "subnet_id", "=", "nil", "unless", "interface", ".", "save", "@errors", ".", "push", "(", "interface", ".", "errors", ".", "full_messages", ")", "end", "end" ]
if subnet has IP suggesting enabled we also clear the IP that was suggested this IP will be used for another interface
[ "if", "subnet", "has", "IP", "suggesting", "enabled", "we", "also", "clear", "the", "IP", "that", "was", "suggested", "this", "IP", "will", "be", "used", "for", "another", "interface" ]
58b0dec6a027bb6fb10c5db4dc5e4430faba8e6f
https://github.com/theforeman/staypuft/blob/58b0dec6a027bb6fb10c5db4dc5e4430faba8e6f/app/models/staypuft/interface_assigner.rb#L120-L126
23,291
localytics/humidifier
lib/humidifier/loader.rb
Humidifier.Loader.load
def load parsed = JSON.parse(File.read(SPECPATH)) structs = StructureContainer.new(parsed['PropertyTypes']) parsed['ResourceTypes'].each do |key, spec| match = key.match(/\A(\w+)::(\w+)::(\w+)\z/) register(match[1], match[2], match[3], spec, structs.search(key)) end end
ruby
def load parsed = JSON.parse(File.read(SPECPATH)) structs = StructureContainer.new(parsed['PropertyTypes']) parsed['ResourceTypes'].each do |key, spec| match = key.match(/\A(\w+)::(\w+)::(\w+)\z/) register(match[1], match[2], match[3], spec, structs.search(key)) end end
[ "def", "load", "parsed", "=", "JSON", ".", "parse", "(", "File", ".", "read", "(", "SPECPATH", ")", ")", "structs", "=", "StructureContainer", ".", "new", "(", "parsed", "[", "'PropertyTypes'", "]", ")", "parsed", "[", "'ResourceTypes'", "]", ".", "each", "do", "|", "key", ",", "spec", "|", "match", "=", "key", ".", "match", "(", "/", "\\A", "\\w", "\\w", "\\w", "\\z", "/", ")", "register", "(", "match", "[", "1", "]", ",", "match", "[", "2", "]", ",", "match", "[", "3", "]", ",", "spec", ",", "structs", ".", "search", "(", "key", ")", ")", "end", "end" ]
loop through the specs and register each class
[ "loop", "through", "the", "specs", "and", "register", "each", "class" ]
143c2fd9a411278988e8b40bd7598ac80f419c20
https://github.com/localytics/humidifier/blob/143c2fd9a411278988e8b40bd7598ac80f419c20/lib/humidifier/loader.rb#L44-L53
23,292
toy/progress
lib/progress/active_record.rb
ActiveRecord.Base.find_each_with_progress
def find_each_with_progress(options = {}) Progress.start(name.tableize, count(options)) do find_each do |model| Progress.step do yield model end end end end
ruby
def find_each_with_progress(options = {}) Progress.start(name.tableize, count(options)) do find_each do |model| Progress.step do yield model end end end end
[ "def", "find_each_with_progress", "(", "options", "=", "{", "}", ")", "Progress", ".", "start", "(", "name", ".", "tableize", ",", "count", "(", "options", ")", ")", "do", "find_each", "do", "|", "model", "|", "Progress", ".", "step", "do", "yield", "model", "end", "end", "end", "end" ]
run `find_each` with progress
[ "run", "find_each", "with", "progress" ]
1a3db7805fc95ef1412b3c21a19b87504933ac3d
https://github.com/toy/progress/blob/1a3db7805fc95ef1412b3c21a19b87504933ac3d/lib/progress/active_record.rb#L8-L16
23,293
toy/progress
lib/progress/active_record.rb
ActiveRecord.Base.find_in_batches_with_progress
def find_in_batches_with_progress(options = {}) Progress.start(name.tableize, count(options)) do find_in_batches do |batch| Progress.step batch.length do yield batch end end end end
ruby
def find_in_batches_with_progress(options = {}) Progress.start(name.tableize, count(options)) do find_in_batches do |batch| Progress.step batch.length do yield batch end end end end
[ "def", "find_in_batches_with_progress", "(", "options", "=", "{", "}", ")", "Progress", ".", "start", "(", "name", ".", "tableize", ",", "count", "(", "options", ")", ")", "do", "find_in_batches", "do", "|", "batch", "|", "Progress", ".", "step", "batch", ".", "length", "do", "yield", "batch", "end", "end", "end", "end" ]
run `find_in_batches` with progress
[ "run", "find_in_batches", "with", "progress" ]
1a3db7805fc95ef1412b3c21a19b87504933ac3d
https://github.com/toy/progress/blob/1a3db7805fc95ef1412b3c21a19b87504933ac3d/lib/progress/active_record.rb#L19-L27
23,294
localytics/humidifier
lib/humidifier/resource.rb
Humidifier.Resource.method_missing
def method_missing(name, *args) if !valid_accessor?(name) super elsif self.class.prop?(name.to_s) self.class.build_property_reader(name) send(name) else self.class.build_property_writer(name) send(name, args.first) end end
ruby
def method_missing(name, *args) if !valid_accessor?(name) super elsif self.class.prop?(name.to_s) self.class.build_property_reader(name) send(name) else self.class.build_property_writer(name) send(name, args.first) end end
[ "def", "method_missing", "(", "name", ",", "*", "args", ")", "if", "!", "valid_accessor?", "(", "name", ")", "super", "elsif", "self", ".", "class", ".", "prop?", "(", "name", ".", "to_s", ")", "self", ".", "class", ".", "build_property_reader", "(", "name", ")", "send", "(", "name", ")", "else", "self", ".", "class", ".", "build_property_writer", "(", "name", ")", "send", "(", "name", ",", "args", ".", "first", ")", "end", "end" ]
Patches method_missing to include property accessors After the first method call, builds the accessor methods to get a speed boost
[ "Patches", "method_missing", "to", "include", "property", "accessors", "After", "the", "first", "method", "call", "builds", "the", "accessor", "methods", "to", "get", "a", "speed", "boost" ]
143c2fd9a411278988e8b40bd7598ac80f419c20
https://github.com/localytics/humidifier/blob/143c2fd9a411278988e8b40bd7598ac80f419c20/lib/humidifier/resource.rb#L21-L31
23,295
localytics/humidifier
lib/humidifier/resource.rb
Humidifier.Resource.update
def update(properties, raw = false) properties.each do |property, value| update_property(property, value, raw) end end
ruby
def update(properties, raw = false) properties.each do |property, value| update_property(property, value, raw) end end
[ "def", "update", "(", "properties", ",", "raw", "=", "false", ")", "properties", ".", "each", "do", "|", "property", ",", "value", "|", "update_property", "(", "property", ",", "value", ",", "raw", ")", "end", "end" ]
Update a set of properties defined by the given properties hash
[ "Update", "a", "set", "of", "properties", "defined", "by", "the", "given", "properties", "hash" ]
143c2fd9a411278988e8b40bd7598ac80f419c20
https://github.com/localytics/humidifier/blob/143c2fd9a411278988e8b40bd7598ac80f419c20/lib/humidifier/resource.rb#L52-L56
23,296
localytics/humidifier
lib/humidifier/resource.rb
Humidifier.Resource.update_property
def update_property(property, value, raw = false) property = property.to_s property = validate_property(property, raw) value = validate_value(property, value, raw) properties[property] = value end
ruby
def update_property(property, value, raw = false) property = property.to_s property = validate_property(property, raw) value = validate_value(property, value, raw) properties[property] = value end
[ "def", "update_property", "(", "property", ",", "value", ",", "raw", "=", "false", ")", "property", "=", "property", ".", "to_s", "property", "=", "validate_property", "(", "property", ",", "raw", ")", "value", "=", "validate_value", "(", "property", ",", "value", ",", "raw", ")", "properties", "[", "property", "]", "=", "value", "end" ]
Update an individual property on this resource
[ "Update", "an", "individual", "property", "on", "this", "resource" ]
143c2fd9a411278988e8b40bd7598ac80f419c20
https://github.com/localytics/humidifier/blob/143c2fd9a411278988e8b40bd7598ac80f419c20/lib/humidifier/resource.rb#L70-L75
23,297
pandastream/panda_gem
lib/panda/proxies/scope.rb
Panda.Scope.find_by_path
def find_by_path(url, map={}) object = find_object_by_path(url, map) if object.is_a?(Array) object.map{|o| klass.new(o.merge('cloud_id' => cloud.id))} elsif object['id'] klass.new(object.merge('cloud_id' => cloud.id)) else raise APIError.new(object) end end
ruby
def find_by_path(url, map={}) object = find_object_by_path(url, map) if object.is_a?(Array) object.map{|o| klass.new(o.merge('cloud_id' => cloud.id))} elsif object['id'] klass.new(object.merge('cloud_id' => cloud.id)) else raise APIError.new(object) end end
[ "def", "find_by_path", "(", "url", ",", "map", "=", "{", "}", ")", "object", "=", "find_object_by_path", "(", "url", ",", "map", ")", "if", "object", ".", "is_a?", "(", "Array", ")", "object", ".", "map", "{", "|", "o", "|", "klass", ".", "new", "(", "o", ".", "merge", "(", "'cloud_id'", "=>", "cloud", ".", "id", ")", ")", "}", "elsif", "object", "[", "'id'", "]", "klass", ".", "new", "(", "object", ".", "merge", "(", "'cloud_id'", "=>", "cloud", ".", "id", ")", ")", "else", "raise", "APIError", ".", "new", "(", "object", ")", "end", "end" ]
Overide the function to set the cloud_id as the same as the scope
[ "Overide", "the", "function", "to", "set", "the", "cloud_id", "as", "the", "same", "as", "the", "scope" ]
5c242b5b7b32d1d11e5cc9d031eeea4dbae60476
https://github.com/pandastream/panda_gem/blob/5c242b5b7b32d1d11e5cc9d031eeea4dbae60476/lib/panda/proxies/scope.rb#L24-L34
23,298
colinmarc/impala-ruby
lib/impala/connection.rb
Impala.Connection.open
def open return if @connected socket = Thrift::Socket.new(@host, @port, @options[:timeout]) if @options[:kerberos] @transport = SASLTransport.new(socket, :GSSAPI, @options[:kerberos]) elsif @options[:sasl] @transport = SASLTransport.new(socket, :PLAIN, @options[:sasl]) else @transport = Thrift::BufferedTransport.new(socket) end @transport.open proto = Thrift::BinaryProtocol.new(@transport) @service = Protocol::ImpalaService::Client.new(proto) @connected = true end
ruby
def open return if @connected socket = Thrift::Socket.new(@host, @port, @options[:timeout]) if @options[:kerberos] @transport = SASLTransport.new(socket, :GSSAPI, @options[:kerberos]) elsif @options[:sasl] @transport = SASLTransport.new(socket, :PLAIN, @options[:sasl]) else @transport = Thrift::BufferedTransport.new(socket) end @transport.open proto = Thrift::BinaryProtocol.new(@transport) @service = Protocol::ImpalaService::Client.new(proto) @connected = true end
[ "def", "open", "return", "if", "@connected", "socket", "=", "Thrift", "::", "Socket", ".", "new", "(", "@host", ",", "@port", ",", "@options", "[", ":timeout", "]", ")", "if", "@options", "[", ":kerberos", "]", "@transport", "=", "SASLTransport", ".", "new", "(", "socket", ",", ":GSSAPI", ",", "@options", "[", ":kerberos", "]", ")", "elsif", "@options", "[", ":sasl", "]", "@transport", "=", "SASLTransport", ".", "new", "(", "socket", ",", ":PLAIN", ",", "@options", "[", ":sasl", "]", ")", "else", "@transport", "=", "Thrift", "::", "BufferedTransport", ".", "new", "(", "socket", ")", "end", "@transport", ".", "open", "proto", "=", "Thrift", "::", "BinaryProtocol", ".", "new", "(", "@transport", ")", "@service", "=", "Protocol", "::", "ImpalaService", "::", "Client", ".", "new", "(", "proto", ")", "@connected", "=", "true", "end" ]
Open the connection if it's currently closed.
[ "Open", "the", "connection", "if", "it", "s", "currently", "closed", "." ]
1b5b2c228a4feac43c1b1cb889b27838a253e2ea
https://github.com/colinmarc/impala-ruby/blob/1b5b2c228a4feac43c1b1cb889b27838a253e2ea/lib/impala/connection.rb#L21-L39
23,299
colinmarc/impala-ruby
lib/impala/connection.rb
Impala.Connection.execute
def execute(query, query_options = {}) raise ConnectionError.new("Connection closed") unless open? handle = send_query(query, query_options) check_result(handle) Cursor.new(handle, @service) end
ruby
def execute(query, query_options = {}) raise ConnectionError.new("Connection closed") unless open? handle = send_query(query, query_options) check_result(handle) Cursor.new(handle, @service) end
[ "def", "execute", "(", "query", ",", "query_options", "=", "{", "}", ")", "raise", "ConnectionError", ".", "new", "(", "\"Connection closed\"", ")", "unless", "open?", "handle", "=", "send_query", "(", "query", ",", "query_options", ")", "check_result", "(", "handle", ")", "Cursor", ".", "new", "(", "handle", ",", "@service", ")", "end" ]
Perform a query and return a cursor for iterating over the results. @param [String] query the query you want to run @param [Hash] query_options the options to set user and configuration except for :user, see TImpalaQueryOptions in ImpalaService.thrift @option query_options [String] :user the user runs the query @return [Cursor] a cursor for the result rows
[ "Perform", "a", "query", "and", "return", "a", "cursor", "for", "iterating", "over", "the", "results", "." ]
1b5b2c228a4feac43c1b1cb889b27838a253e2ea
https://github.com/colinmarc/impala-ruby/blob/1b5b2c228a4feac43c1b1cb889b27838a253e2ea/lib/impala/connection.rb#L78-L84