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
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
sandipransing/rails_tiny_mce
plugins/paperclip/shoulda_macros/paperclip.rb
Paperclip.Shoulda.stub_paperclip_s3
def stub_paperclip_s3(model, attachment, extension) definition = model.gsub(" ", "_").classify.constantize. attachment_definitions[attachment.to_sym] path = "http://s3.amazonaws.com/:id/#{definition[:path]}" path.gsub!(/:([^\/\.]+)/) do |match| "([^\/\.]+)" end begin FakeWeb.register_uri(:put, Regexp.new(path), :body => "OK") rescue NameError raise NameError, "the stub_paperclip_s3 shoulda macro requires the fakeweb gem." end end
ruby
def stub_paperclip_s3(model, attachment, extension) definition = model.gsub(" ", "_").classify.constantize. attachment_definitions[attachment.to_sym] path = "http://s3.amazonaws.com/:id/#{definition[:path]}" path.gsub!(/:([^\/\.]+)/) do |match| "([^\/\.]+)" end begin FakeWeb.register_uri(:put, Regexp.new(path), :body => "OK") rescue NameError raise NameError, "the stub_paperclip_s3 shoulda macro requires the fakeweb gem." end end
[ "def", "stub_paperclip_s3", "(", "model", ",", "attachment", ",", "extension", ")", "definition", "=", "model", ".", "gsub", "(", "\" \"", ",", "\"_\"", ")", ".", "classify", ".", "constantize", ".", "attachment_definitions", "[", "attachment", ".", "to_sym", "]", "path", "=", "\"http://s3.amazonaws.com/:id/#{definition[:path]}\"", "path", ".", "gsub!", "(", "/", "\\/", "\\.", "/", ")", "do", "|", "match", "|", "\"([^\\/\\.]+)\"", "end", "begin", "FakeWeb", ".", "register_uri", "(", ":put", ",", "Regexp", ".", "new", "(", "path", ")", ",", ":body", "=>", "\"OK\"", ")", "rescue", "NameError", "raise", "NameError", ",", "\"the stub_paperclip_s3 shoulda macro requires the fakeweb gem.\"", "end", "end" ]
Stubs the HTTP PUT for an attachment using S3 storage. @example stub_paperclip_s3('user', 'avatar', 'png')
[ "Stubs", "the", "HTTP", "PUT", "for", "an", "attachment", "using", "S3", "storage", "." ]
4e91040e62784061aa7cca37fd8a95a87df379ce
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/shoulda_macros/paperclip.rb#L68-L82
train
RestlessThinker/danger-jira
lib/jira/plugin.rb
Danger.DangerJira.check
def check(key: nil, url: nil, emoji: ":link:", search_title: true, search_commits: false, fail_on_warning: false, report_missing: true, skippable: true) throw Error("'key' missing - must supply JIRA issue key") if key.nil? throw Error("'url' missing - must supply JIRA installation URL") if url.nil? return if skippable && should_skip_jira?(search_title: search_title) jira_issues = find_jira_issues( key: key, search_title: search_title, search_commits: search_commits ) if !jira_issues.empty? jira_urls = jira_issues.map { |issue| link(href: ensure_url_ends_with_slash(url), issue: issue) }.join(", ") message("#{emoji} #{jira_urls}") elsif report_missing msg = "This PR does not contain any JIRA issue keys in the PR title or commit messages (e.g. KEY-123)" if fail_on_warning fail(msg) else warn(msg) end end end
ruby
def check(key: nil, url: nil, emoji: ":link:", search_title: true, search_commits: false, fail_on_warning: false, report_missing: true, skippable: true) throw Error("'key' missing - must supply JIRA issue key") if key.nil? throw Error("'url' missing - must supply JIRA installation URL") if url.nil? return if skippable && should_skip_jira?(search_title: search_title) jira_issues = find_jira_issues( key: key, search_title: search_title, search_commits: search_commits ) if !jira_issues.empty? jira_urls = jira_issues.map { |issue| link(href: ensure_url_ends_with_slash(url), issue: issue) }.join(", ") message("#{emoji} #{jira_urls}") elsif report_missing msg = "This PR does not contain any JIRA issue keys in the PR title or commit messages (e.g. KEY-123)" if fail_on_warning fail(msg) else warn(msg) end end end
[ "def", "check", "(", "key", ":", "nil", ",", "url", ":", "nil", ",", "emoji", ":", "\":link:\"", ",", "search_title", ":", "true", ",", "search_commits", ":", "false", ",", "fail_on_warning", ":", "false", ",", "report_missing", ":", "true", ",", "skippable", ":", "true", ")", "throw", "Error", "(", "\"'key' missing - must supply JIRA issue key\"", ")", "if", "key", ".", "nil?", "throw", "Error", "(", "\"'url' missing - must supply JIRA installation URL\"", ")", "if", "url", ".", "nil?", "return", "if", "skippable", "&&", "should_skip_jira?", "(", "search_title", ":", "search_title", ")", "jira_issues", "=", "find_jira_issues", "(", "key", ":", "key", ",", "search_title", ":", "search_title", ",", "search_commits", ":", "search_commits", ")", "if", "!", "jira_issues", ".", "empty?", "jira_urls", "=", "jira_issues", ".", "map", "{", "|", "issue", "|", "link", "(", "href", ":", "ensure_url_ends_with_slash", "(", "url", ")", ",", "issue", ":", "issue", ")", "}", ".", "join", "(", "\", \"", ")", "message", "(", "\"#{emoji} #{jira_urls}\"", ")", "elsif", "report_missing", "msg", "=", "\"This PR does not contain any JIRA issue keys in the PR title or commit messages (e.g. KEY-123)\"", "if", "fail_on_warning", "fail", "(", "msg", ")", "else", "warn", "(", "msg", ")", "end", "end", "end" ]
Checks PR for JIRA keys and links them @param [Array] key An array of JIRA project keys KEY-123, JIRA-125 etc. @param [String] url The JIRA url hosted instance. @param [String] emoji The emoji you want to display in the message. @param [Boolean] search_title Option to search JIRA issues from PR title @param [Boolean] search_commits Option to search JIRA issues from commit messages @param [Boolean] fail_on_warning Option to fail danger if no JIRA issue found @param [Boolean] report_missing Option to report if no JIRA issue was found @param [Boolean] skippable Option to skip the report if 'no-jira' is provided on the PR title, description or commits @return [void]
[ "Checks", "PR", "for", "JIRA", "keys", "and", "links", "them" ]
47413c0c46e44cba024e9ff5999620f621eb8c49
https://github.com/RestlessThinker/danger-jira/blob/47413c0c46e44cba024e9ff5999620f621eb8c49/lib/jira/plugin.rb#L40-L63
train
sandipransing/rails_tiny_mce
plugins/paperclip/lib/paperclip/thumbnail.rb
Paperclip.Thumbnail.make
def make src = @file dst = Tempfile.new([@basename, @format ? ".#{@format}" : '']) dst.binmode begin parameters = [] parameters << source_file_options parameters << ":source" parameters << transformation_command parameters << convert_options parameters << ":dest" parameters = parameters.flatten.compact.join(" ").strip.squeeze(" ") success = Paperclip.run("convert", parameters, :source => "#{File.expand_path(src.path)}[0]", :dest => File.expand_path(dst.path)) rescue PaperclipCommandLineError => e raise PaperclipError, "There was an error processing the thumbnail for #{@basename}" if @whiny end dst end
ruby
def make src = @file dst = Tempfile.new([@basename, @format ? ".#{@format}" : '']) dst.binmode begin parameters = [] parameters << source_file_options parameters << ":source" parameters << transformation_command parameters << convert_options parameters << ":dest" parameters = parameters.flatten.compact.join(" ").strip.squeeze(" ") success = Paperclip.run("convert", parameters, :source => "#{File.expand_path(src.path)}[0]", :dest => File.expand_path(dst.path)) rescue PaperclipCommandLineError => e raise PaperclipError, "There was an error processing the thumbnail for #{@basename}" if @whiny end dst end
[ "def", "make", "src", "=", "@file", "dst", "=", "Tempfile", ".", "new", "(", "[", "@basename", ",", "@format", "?", "\".#{@format}\"", ":", "''", "]", ")", "dst", ".", "binmode", "begin", "parameters", "=", "[", "]", "parameters", "<<", "source_file_options", "parameters", "<<", "\":source\"", "parameters", "<<", "transformation_command", "parameters", "<<", "convert_options", "parameters", "<<", "\":dest\"", "parameters", "=", "parameters", ".", "flatten", ".", "compact", ".", "join", "(", "\" \"", ")", ".", "strip", ".", "squeeze", "(", "\" \"", ")", "success", "=", "Paperclip", ".", "run", "(", "\"convert\"", ",", "parameters", ",", ":source", "=>", "\"#{File.expand_path(src.path)}[0]\"", ",", ":dest", "=>", "File", ".", "expand_path", "(", "dst", ".", "path", ")", ")", "rescue", "PaperclipCommandLineError", "=>", "e", "raise", "PaperclipError", ",", "\"There was an error processing the thumbnail for #{@basename}\"", "if", "@whiny", "end", "dst", "end" ]
Performs the conversion of the +file+ into a thumbnail. Returns the Tempfile that contains the new image.
[ "Performs", "the", "conversion", "of", "the", "+", "file", "+", "into", "a", "thumbnail", ".", "Returns", "the", "Tempfile", "that", "contains", "the", "new", "image", "." ]
4e91040e62784061aa7cca37fd8a95a87df379ce
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/lib/paperclip/thumbnail.rb#L46-L67
train
sandipransing/rails_tiny_mce
plugins/paperclip/lib/paperclip/thumbnail.rb
Paperclip.Thumbnail.transformation_command
def transformation_command scale, crop = @current_geometry.transformation_to(@target_geometry, crop?) trans = [] trans << "-resize" << %["#{scale}"] unless scale.nil? || scale.empty? trans << "-crop" << %["#{crop}"] << "+repage" if crop trans end
ruby
def transformation_command scale, crop = @current_geometry.transformation_to(@target_geometry, crop?) trans = [] trans << "-resize" << %["#{scale}"] unless scale.nil? || scale.empty? trans << "-crop" << %["#{crop}"] << "+repage" if crop trans end
[ "def", "transformation_command", "scale", ",", "crop", "=", "@current_geometry", ".", "transformation_to", "(", "@target_geometry", ",", "crop?", ")", "trans", "=", "[", "]", "trans", "<<", "\"-resize\"", "<<", "%[\"#{scale}\"]", "unless", "scale", ".", "nil?", "||", "scale", ".", "empty?", "trans", "<<", "\"-crop\"", "<<", "%[\"#{crop}\"]", "<<", "\"+repage\"", "if", "crop", "trans", "end" ]
Returns the command ImageMagick's +convert+ needs to transform the image into the thumbnail.
[ "Returns", "the", "command", "ImageMagick", "s", "+", "convert", "+", "needs", "to", "transform", "the", "image", "into", "the", "thumbnail", "." ]
4e91040e62784061aa7cca37fd8a95a87df379ce
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/lib/paperclip/thumbnail.rb#L71-L77
train
kete/tiny_mce
lib/tiny_mce/configuration.rb
TinyMCE.Configuration.add_options
def add_options(options = {}, raw_options = nil) @options.merge!(options.stringify_keys) unless options.blank? @raw_options << raw_options unless raw_options.blank? end
ruby
def add_options(options = {}, raw_options = nil) @options.merge!(options.stringify_keys) unless options.blank? @raw_options << raw_options unless raw_options.blank? end
[ "def", "add_options", "(", "options", "=", "{", "}", ",", "raw_options", "=", "nil", ")", "@options", ".", "merge!", "(", "options", ".", "stringify_keys", ")", "unless", "options", ".", "blank?", "@raw_options", "<<", "raw_options", "unless", "raw_options", ".", "blank?", "end" ]
Merge additional options and raw_options
[ "Merge", "additional", "options", "and", "raw_options" ]
49aa365c4256fc0702e3b1a02e1ddecfdbccd7b4
https://github.com/kete/tiny_mce/blob/49aa365c4256fc0702e3b1a02e1ddecfdbccd7b4/lib/tiny_mce/configuration.rb#L58-L61
train
kete/tiny_mce
lib/tiny_mce/configuration.rb
TinyMCE.Configuration.reverse_add_options
def reverse_add_options(options = {}, raw_options = nil) @options.reverse_merge!(options.stringify_keys) unless options.blank? @raw_options << raw_options unless raw_options.blank? end
ruby
def reverse_add_options(options = {}, raw_options = nil) @options.reverse_merge!(options.stringify_keys) unless options.blank? @raw_options << raw_options unless raw_options.blank? end
[ "def", "reverse_add_options", "(", "options", "=", "{", "}", ",", "raw_options", "=", "nil", ")", "@options", ".", "reverse_merge!", "(", "options", ".", "stringify_keys", ")", "unless", "options", ".", "blank?", "@raw_options", "<<", "raw_options", "unless", "raw_options", ".", "blank?", "end" ]
Merge additional options and raw_options, but don't overwrite existing
[ "Merge", "additional", "options", "and", "raw_options", "but", "don", "t", "overwrite", "existing" ]
49aa365c4256fc0702e3b1a02e1ddecfdbccd7b4
https://github.com/kete/tiny_mce/blob/49aa365c4256fc0702e3b1a02e1ddecfdbccd7b4/lib/tiny_mce/configuration.rb#L64-L67
train
sandipransing/rails_tiny_mce
plugins/paperclip/lib/paperclip/upfile.rb
Paperclip.Upfile.content_type
def content_type type = (self.path.match(/\.(\w+)$/)[1] rescue "octet-stream").downcase case type when %r"jp(e|g|eg)" then "image/jpeg" when %r"tiff?" then "image/tiff" when %r"png", "gif", "bmp" then "image/#{type}" when "txt" then "text/plain" when %r"html?" then "text/html" when "js" then "application/js" when "csv", "xml", "css" then "text/#{type}" else # On BSDs, `file` doesn't give a result code of 1 if the file doesn't exist. content_type = (Paperclip.run("file", "-b --mime-type :file", :file => self.path).split(':').last.strip rescue "application/x-#{type}") content_type = "application/x-#{type}" if content_type.match(/\(.*?\)/) content_type end end
ruby
def content_type type = (self.path.match(/\.(\w+)$/)[1] rescue "octet-stream").downcase case type when %r"jp(e|g|eg)" then "image/jpeg" when %r"tiff?" then "image/tiff" when %r"png", "gif", "bmp" then "image/#{type}" when "txt" then "text/plain" when %r"html?" then "text/html" when "js" then "application/js" when "csv", "xml", "css" then "text/#{type}" else # On BSDs, `file` doesn't give a result code of 1 if the file doesn't exist. content_type = (Paperclip.run("file", "-b --mime-type :file", :file => self.path).split(':').last.strip rescue "application/x-#{type}") content_type = "application/x-#{type}" if content_type.match(/\(.*?\)/) content_type end end
[ "def", "content_type", "type", "=", "(", "self", ".", "path", ".", "match", "(", "/", "\\.", "\\w", "/", ")", "[", "1", "]", "rescue", "\"octet-stream\"", ")", ".", "downcase", "case", "type", "when", "%r\"", "\"", "then", "\"image/jpeg\"", "when", "%r\"", "\"", "then", "\"image/tiff\"", "when", "%r\"", "\"", ",", "\"gif\"", ",", "\"bmp\"", "then", "\"image/#{type}\"", "when", "\"txt\"", "then", "\"text/plain\"", "when", "%r\"", "\"", "then", "\"text/html\"", "when", "\"js\"", "then", "\"application/js\"", "when", "\"csv\"", ",", "\"xml\"", ",", "\"css\"", "then", "\"text/#{type}\"", "else", "content_type", "=", "(", "Paperclip", ".", "run", "(", "\"file\"", ",", "\"-b --mime-type :file\"", ",", ":file", "=>", "self", ".", "path", ")", ".", "split", "(", "':'", ")", ".", "last", ".", "strip", "rescue", "\"application/x-#{type}\"", ")", "content_type", "=", "\"application/x-#{type}\"", "if", "content_type", ".", "match", "(", "/", "\\(", "\\)", "/", ")", "content_type", "end", "end" ]
Infer the MIME-type of the file from the extension.
[ "Infer", "the", "MIME", "-", "type", "of", "the", "file", "from", "the", "extension", "." ]
4e91040e62784061aa7cca37fd8a95a87df379ce
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/lib/paperclip/upfile.rb#L8-L24
train
tario/shikashi
lib/shikashi/sandbox.rb
Shikashi.Sandbox.packet
def packet(*args) code = args.pick(String,:code) base_namespace = args.pick(:base_namespace) do nil end no_base_namespace = args.pick(:no_base_namespace) do @no_base_namespace end privileges_ = args.pick(Privileges,:privileges) do Privileges.new end encoding = get_source_encoding(code) || args.pick(:encoding) do nil end hook_handler = nil if base_namespace hook_handler = instantiate_evalhook_handler hook_handler.base_namespace = base_namespace hook_handler.sandbox = self else hook_handler = @hook_handler base_namespace = hook_handler.base_namespace end source = args.pick(:source) do generate_id end self.privileges[source] = privileges_ code = "nil;\n " + code unless no_base_namespace if (eval(base_namespace.to_s).instance_of? Module) code = "module #{base_namespace}\n #{code}\n end\n" else code = "class #{base_namespace}\n #{code}\n end\n" end end if encoding code = "# encoding: #{encoding}\n" + code end evalhook_packet = @hook_handler.packet(code) Shikashi::Sandbox::Packet.new(evalhook_packet, privileges_, source) end
ruby
def packet(*args) code = args.pick(String,:code) base_namespace = args.pick(:base_namespace) do nil end no_base_namespace = args.pick(:no_base_namespace) do @no_base_namespace end privileges_ = args.pick(Privileges,:privileges) do Privileges.new end encoding = get_source_encoding(code) || args.pick(:encoding) do nil end hook_handler = nil if base_namespace hook_handler = instantiate_evalhook_handler hook_handler.base_namespace = base_namespace hook_handler.sandbox = self else hook_handler = @hook_handler base_namespace = hook_handler.base_namespace end source = args.pick(:source) do generate_id end self.privileges[source] = privileges_ code = "nil;\n " + code unless no_base_namespace if (eval(base_namespace.to_s).instance_of? Module) code = "module #{base_namespace}\n #{code}\n end\n" else code = "class #{base_namespace}\n #{code}\n end\n" end end if encoding code = "# encoding: #{encoding}\n" + code end evalhook_packet = @hook_handler.packet(code) Shikashi::Sandbox::Packet.new(evalhook_packet, privileges_, source) end
[ "def", "packet", "(", "*", "args", ")", "code", "=", "args", ".", "pick", "(", "String", ",", ":code", ")", "base_namespace", "=", "args", ".", "pick", "(", ":base_namespace", ")", "do", "nil", "end", "no_base_namespace", "=", "args", ".", "pick", "(", ":no_base_namespace", ")", "do", "@no_base_namespace", "end", "privileges_", "=", "args", ".", "pick", "(", "Privileges", ",", ":privileges", ")", "do", "Privileges", ".", "new", "end", "encoding", "=", "get_source_encoding", "(", "code", ")", "||", "args", ".", "pick", "(", ":encoding", ")", "do", "nil", "end", "hook_handler", "=", "nil", "if", "base_namespace", "hook_handler", "=", "instantiate_evalhook_handler", "hook_handler", ".", "base_namespace", "=", "base_namespace", "hook_handler", ".", "sandbox", "=", "self", "else", "hook_handler", "=", "@hook_handler", "base_namespace", "=", "hook_handler", ".", "base_namespace", "end", "source", "=", "args", ".", "pick", "(", ":source", ")", "do", "generate_id", "end", "self", ".", "privileges", "[", "source", "]", "=", "privileges_", "code", "=", "\"nil;\\n \"", "+", "code", "unless", "no_base_namespace", "if", "(", "eval", "(", "base_namespace", ".", "to_s", ")", ".", "instance_of?", "Module", ")", "code", "=", "\"module #{base_namespace}\\n #{code}\\n end\\n\"", "else", "code", "=", "\"class #{base_namespace}\\n #{code}\\n end\\n\"", "end", "end", "if", "encoding", "code", "=", "\"# encoding: #{encoding}\\n\"", "+", "code", "end", "evalhook_packet", "=", "@hook_handler", ".", "packet", "(", "code", ")", "Shikashi", "::", "Sandbox", "::", "Packet", ".", "new", "(", "evalhook_packet", ",", "privileges_", ",", "source", ")", "end" ]
Creates a packet of code with the given privileges to execute later as many times as neccessary (see examples) Arguments :code Mandatory argument of class String with the code to execute restricted in the sandbox :privileges Optional argument of class Shikashi::Sandbox::Privileges to indicate the restrictions of the code executed in the sandbox. The default is an empty Privileges (absolutly no permission) Must be of class Privileges or passed as hash_key (:privileges => privileges) :source Optional argument to indicate the "source name", (visible in the backtraces). Only can be specified as hash parameter :base_namespace Alternate module to contain all classes and constants defined by the unprivileged code if not specified, by default, the base_namespace is created with the sandbox itself :no_base_namespace Specify to do not use a base_namespace (default false, not recommended to change) :encoding Specify the encoding of source (example: "utf-8"), the encoding also can be specified on header like a ruby normal source file NOTE: arguments are the same as for Sandbox#run method, except for timeout and binding which can be used when calling Shikashi::Sandbox::Packet#run Example: require "rubygems" require "shikashi" include Shikashi sandbox = Sandbox.new privileges = Privileges.allow_method(:print) # this is equivallent to sandbox.run('print "hello world\n"') packet = sandbox.packet('print "hello world\n"', privileges) packet.run
[ "Creates", "a", "packet", "of", "code", "with", "the", "given", "privileges", "to", "execute", "later", "as", "many", "times", "as", "neccessary" ]
171e0687a42327fa702225e8ad0d321e578f0cb0
https://github.com/tario/shikashi/blob/171e0687a42327fa702225e8ad0d321e578f0cb0/lib/shikashi/sandbox.rb#L380-L417
train
drewtempelmeyer/tax_cloud
lib/tax_cloud/address.rb
TaxCloud.Address.verify
def verify params = to_hash.downcase_keys if TaxCloud.configuration.usps_username params = params.merge( 'uspsUserID' => TaxCloud.configuration.usps_username ) end response = TaxCloud.client.request(:verify_address, params) TaxCloud::Responses::VerifyAddress.parse(response) end
ruby
def verify params = to_hash.downcase_keys if TaxCloud.configuration.usps_username params = params.merge( 'uspsUserID' => TaxCloud.configuration.usps_username ) end response = TaxCloud.client.request(:verify_address, params) TaxCloud::Responses::VerifyAddress.parse(response) end
[ "def", "verify", "params", "=", "to_hash", ".", "downcase_keys", "if", "TaxCloud", ".", "configuration", ".", "usps_username", "params", "=", "params", ".", "merge", "(", "'uspsUserID'", "=>", "TaxCloud", ".", "configuration", ".", "usps_username", ")", "end", "response", "=", "TaxCloud", ".", "client", ".", "request", "(", ":verify_address", ",", "params", ")", "TaxCloud", "::", "Responses", "::", "VerifyAddress", ".", "parse", "(", "response", ")", "end" ]
Verify this address. Returns a verified TaxCloud::Address.
[ "Verify", "this", "address", "." ]
ace4fae5586bc993e10a39989efbd048849ecad0
https://github.com/drewtempelmeyer/tax_cloud/blob/ace4fae5586bc993e10a39989efbd048849ecad0/lib/tax_cloud/address.rb#L20-L29
train
drewtempelmeyer/tax_cloud
lib/tax_cloud/address.rb
TaxCloud.Address.zip
def zip return nil unless zip5 && !zip5.empty? [zip5, zip4].select { |z| z && !z.empty? }.join('-') end
ruby
def zip return nil unless zip5 && !zip5.empty? [zip5, zip4].select { |z| z && !z.empty? }.join('-') end
[ "def", "zip", "return", "nil", "unless", "zip5", "&&", "!", "zip5", ".", "empty?", "[", "zip5", ",", "zip4", "]", ".", "select", "{", "|", "z", "|", "z", "&&", "!", "z", ".", "empty?", "}", ".", "join", "(", "'-'", ")", "end" ]
Complete zip code. Returns a 9-digit Zip Code, when available.
[ "Complete", "zip", "code", ".", "Returns", "a", "9", "-", "digit", "Zip", "Code", "when", "available", "." ]
ace4fae5586bc993e10a39989efbd048849ecad0
https://github.com/drewtempelmeyer/tax_cloud/blob/ace4fae5586bc993e10a39989efbd048849ecad0/lib/tax_cloud/address.rb#L33-L36
train
sandipransing/rails_tiny_mce
plugins/paperclip/lib/paperclip/style.rb
Paperclip.Style.processor_options
def processor_options args = {} @other_args.each do |k,v| args[k] = v.respond_to?(:call) ? v.call(attachment) : v end [:processors, :geometry, :format, :whiny, :convert_options].each do |k| (arg = send(k)) && args[k] = arg end args end
ruby
def processor_options args = {} @other_args.each do |k,v| args[k] = v.respond_to?(:call) ? v.call(attachment) : v end [:processors, :geometry, :format, :whiny, :convert_options].each do |k| (arg = send(k)) && args[k] = arg end args end
[ "def", "processor_options", "args", "=", "{", "}", "@other_args", ".", "each", "do", "|", "k", ",", "v", "|", "args", "[", "k", "]", "=", "v", ".", "respond_to?", "(", ":call", ")", "?", "v", ".", "call", "(", "attachment", ")", ":", "v", "end", "[", ":processors", ",", ":geometry", ",", ":format", ",", ":whiny", ",", ":convert_options", "]", ".", "each", "do", "|", "k", "|", "(", "arg", "=", "send", "(", "k", ")", ")", "&&", "args", "[", "k", "]", "=", "arg", "end", "args", "end" ]
Supplies the hash of options that processors expect to receive as their second argument Arguments other than the standard geometry, format etc are just passed through from initialization and any procs are called here, just before post-processing.
[ "Supplies", "the", "hash", "of", "options", "that", "processors", "expect", "to", "receive", "as", "their", "second", "argument", "Arguments", "other", "than", "the", "standard", "geometry", "format", "etc", "are", "just", "passed", "through", "from", "initialization", "and", "any", "procs", "are", "called", "here", "just", "before", "post", "-", "processing", "." ]
4e91040e62784061aa7cca37fd8a95a87df379ce
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/lib/paperclip/style.rb#L60-L69
train
sandipransing/rails_tiny_mce
plugins/paperclip/lib/paperclip/attachment.rb
Paperclip.Attachment.styles
def styles unless @normalized_styles @normalized_styles = {} (@styles.respond_to?(:call) ? @styles.call(self) : @styles).each do |name, args| @normalized_styles[name] = Paperclip::Style.new(name, args.dup, self) end end @normalized_styles end
ruby
def styles unless @normalized_styles @normalized_styles = {} (@styles.respond_to?(:call) ? @styles.call(self) : @styles).each do |name, args| @normalized_styles[name] = Paperclip::Style.new(name, args.dup, self) end end @normalized_styles end
[ "def", "styles", "unless", "@normalized_styles", "@normalized_styles", "=", "{", "}", "(", "@styles", ".", "respond_to?", "(", ":call", ")", "?", "@styles", ".", "call", "(", "self", ")", ":", "@styles", ")", ".", "each", "do", "|", "name", ",", "args", "|", "@normalized_styles", "[", "name", "]", "=", "Paperclip", "::", "Style", ".", "new", "(", "name", ",", "args", ".", "dup", ",", "self", ")", "end", "end", "@normalized_styles", "end" ]
Creates an Attachment object. +name+ is the name of the attachment, +instance+ is the ActiveRecord object instance it's attached to, and +options+ is the same as the hash passed to +has_attached_file+.
[ "Creates", "an", "Attachment", "object", ".", "+", "name", "+", "is", "the", "name", "of", "the", "attachment", "+", "instance", "+", "is", "the", "ActiveRecord", "object", "instance", "it", "s", "attached", "to", "and", "+", "options", "+", "is", "the", "same", "as", "the", "hash", "passed", "to", "+", "has_attached_file", "+", "." ]
4e91040e62784061aa7cca37fd8a95a87df379ce
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/lib/paperclip/attachment.rb#L57-L65
train
sandipransing/rails_tiny_mce
plugins/paperclip/lib/paperclip/attachment.rb
Paperclip.Attachment.url
def url(style_name = default_style, use_timestamp = @use_timestamp) url = original_filename.nil? ? interpolate(@default_url, style_name) : interpolate(@url, style_name) use_timestamp && updated_at ? [url, updated_at].compact.join(url.include?("?") ? "&" : "?") : url end
ruby
def url(style_name = default_style, use_timestamp = @use_timestamp) url = original_filename.nil? ? interpolate(@default_url, style_name) : interpolate(@url, style_name) use_timestamp && updated_at ? [url, updated_at].compact.join(url.include?("?") ? "&" : "?") : url end
[ "def", "url", "(", "style_name", "=", "default_style", ",", "use_timestamp", "=", "@use_timestamp", ")", "url", "=", "original_filename", ".", "nil?", "?", "interpolate", "(", "@default_url", ",", "style_name", ")", ":", "interpolate", "(", "@url", ",", "style_name", ")", "use_timestamp", "&&", "updated_at", "?", "[", "url", ",", "updated_at", "]", ".", "compact", ".", "join", "(", "url", ".", "include?", "(", "\"?\"", ")", "?", "\"&\"", ":", "\"?\"", ")", ":", "url", "end" ]
Returns the public URL of the attachment, with a given style. Note that this does not necessarily need to point to a file that your web server can access and can point to an action in your app, if you need fine grained security. This is not recommended if you don't need the security, however, for performance reasons. Set use_timestamp to false if you want to stop the attachment update time appended to the url
[ "Returns", "the", "public", "URL", "of", "the", "attachment", "with", "a", "given", "style", ".", "Note", "that", "this", "does", "not", "necessarily", "need", "to", "point", "to", "a", "file", "that", "your", "web", "server", "can", "access", "and", "can", "point", "to", "an", "action", "in", "your", "app", "if", "you", "need", "fine", "grained", "security", ".", "This", "is", "not", "recommended", "if", "you", "don", "t", "need", "the", "security", "however", "for", "performance", "reasons", ".", "Set", "use_timestamp", "to", "false", "if", "you", "want", "to", "stop", "the", "attachment", "update", "time", "appended", "to", "the", "url" ]
4e91040e62784061aa7cca37fd8a95a87df379ce
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/lib/paperclip/attachment.rb#L116-L119
train
rslifka/elasticity
lib/elasticity/emr.rb
Elasticity.EMR.add_tags
def add_tags(jobflow_id, tags) params = { :operation => 'AddTags', :resource_id => jobflow_id, :tags => tags } aws_result = @aws_request.submit(params) yield aws_result if block_given? end
ruby
def add_tags(jobflow_id, tags) params = { :operation => 'AddTags', :resource_id => jobflow_id, :tags => tags } aws_result = @aws_request.submit(params) yield aws_result if block_given? end
[ "def", "add_tags", "(", "jobflow_id", ",", "tags", ")", "params", "=", "{", ":operation", "=>", "'AddTags'", ",", ":resource_id", "=>", "jobflow_id", ",", ":tags", "=>", "tags", "}", "aws_result", "=", "@aws_request", ".", "submit", "(", "params", ")", "yield", "aws_result", "if", "block_given?", "end" ]
Sets the specified tags on all instances in the specified jobflow emr.add_tags('j-123', [{:key => 'key1', :value => 'value1'}, {:key => 'key_only2'}]) See http://docs.aws.amazon.com/ElasticMapReduce/latest/API/API_AddTags.html
[ "Sets", "the", "specified", "tags", "on", "all", "instances", "in", "the", "specified", "jobflow" ]
ee0a534b2c63ae0113aee5c85681ae4954703efb
https://github.com/rslifka/elasticity/blob/ee0a534b2c63ae0113aee5c85681ae4954703efb/lib/elasticity/emr.rb#L73-L81
train
rslifka/elasticity
lib/elasticity/emr.rb
Elasticity.EMR.describe_cluster
def describe_cluster(jobflow_id) params = { :operation => 'DescribeCluster', :cluster_id => jobflow_id, } aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
ruby
def describe_cluster(jobflow_id) params = { :operation => 'DescribeCluster', :cluster_id => jobflow_id, } aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
[ "def", "describe_cluster", "(", "jobflow_id", ")", "params", "=", "{", ":operation", "=>", "'DescribeCluster'", ",", ":cluster_id", "=>", "jobflow_id", ",", "}", "aws_result", "=", "@aws_request", ".", "submit", "(", "params", ")", "yield", "aws_result", "if", "block_given?", "JSON", ".", "parse", "(", "aws_result", ")", "end" ]
Provides details about the specified jobflow emr.describe_cluster('j-123') http://docs.aws.amazon.com/ElasticMapReduce/latest/API/API_DescribeCluster.html
[ "Provides", "details", "about", "the", "specified", "jobflow" ]
ee0a534b2c63ae0113aee5c85681ae4954703efb
https://github.com/rslifka/elasticity/blob/ee0a534b2c63ae0113aee5c85681ae4954703efb/lib/elasticity/emr.rb#L88-L96
train
rslifka/elasticity
lib/elasticity/emr.rb
Elasticity.EMR.describe_step
def describe_step(jobflow_id, step_id) params = { :operation => 'DescribeStep', :cluster_id => jobflow_id, :step_id => step_id } aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
ruby
def describe_step(jobflow_id, step_id) params = { :operation => 'DescribeStep', :cluster_id => jobflow_id, :step_id => step_id } aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
[ "def", "describe_step", "(", "jobflow_id", ",", "step_id", ")", "params", "=", "{", ":operation", "=>", "'DescribeStep'", ",", ":cluster_id", "=>", "jobflow_id", ",", ":step_id", "=>", "step_id", "}", "aws_result", "=", "@aws_request", ".", "submit", "(", "params", ")", "yield", "aws_result", "if", "block_given?", "JSON", ".", "parse", "(", "aws_result", ")", "end" ]
Provides details about the specified step within an existing jobflow emr.describe_step('j-123', 'step-456') http://docs.aws.amazon.com/ElasticMapReduce/latest/API/API_DescribeStep.html
[ "Provides", "details", "about", "the", "specified", "step", "within", "an", "existing", "jobflow" ]
ee0a534b2c63ae0113aee5c85681ae4954703efb
https://github.com/rslifka/elasticity/blob/ee0a534b2c63ae0113aee5c85681ae4954703efb/lib/elasticity/emr.rb#L103-L112
train
rslifka/elasticity
lib/elasticity/emr.rb
Elasticity.EMR.list_clusters
def list_clusters(options={}) params = { :operation => 'ListClusters' } params.merge!(:cluster_states => options[:states]) if options[:states] params.merge!(:created_before => options[:created_before].to_i) if options[:created_before] params.merge!(:created_after => options[:created_after].to_i) if options[:created_after] params.merge!(:marker => options[:marker]) if options[:marker] aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
ruby
def list_clusters(options={}) params = { :operation => 'ListClusters' } params.merge!(:cluster_states => options[:states]) if options[:states] params.merge!(:created_before => options[:created_before].to_i) if options[:created_before] params.merge!(:created_after => options[:created_after].to_i) if options[:created_after] params.merge!(:marker => options[:marker]) if options[:marker] aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
[ "def", "list_clusters", "(", "options", "=", "{", "}", ")", "params", "=", "{", ":operation", "=>", "'ListClusters'", "}", "params", ".", "merge!", "(", ":cluster_states", "=>", "options", "[", ":states", "]", ")", "if", "options", "[", ":states", "]", "params", ".", "merge!", "(", ":created_before", "=>", "options", "[", ":created_before", "]", ".", "to_i", ")", "if", "options", "[", ":created_before", "]", "params", ".", "merge!", "(", ":created_after", "=>", "options", "[", ":created_after", "]", ".", "to_i", ")", "if", "options", "[", ":created_after", "]", "params", ".", "merge!", "(", ":marker", "=>", "options", "[", ":marker", "]", ")", "if", "options", "[", ":marker", "]", "aws_result", "=", "@aws_request", ".", "submit", "(", "params", ")", "yield", "aws_result", "if", "block_given?", "JSON", ".", "parse", "(", "aws_result", ")", "end" ]
List the clusters given specified filtering emr.list_clusters({ :states => ['status1', 'status2', ...], :created_before => Time, # Amazon times are in UTC :created_after => Time, # Amazon times are in UTC :marker => 'marker' # Retrieve from a prior call to list_clusters }) http://docs.aws.amazon.com/ElasticMapReduce/latest/API/API_ListClusters.html
[ "List", "the", "clusters", "given", "specified", "filtering" ]
ee0a534b2c63ae0113aee5c85681ae4954703efb
https://github.com/rslifka/elasticity/blob/ee0a534b2c63ae0113aee5c85681ae4954703efb/lib/elasticity/emr.rb#L124-L135
train
rslifka/elasticity
lib/elasticity/emr.rb
Elasticity.EMR.list_instance_groups
def list_instance_groups(jobflow_id) params = { :operation => 'ListInstanceGroups', :cluster_id => jobflow_id, } aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
ruby
def list_instance_groups(jobflow_id) params = { :operation => 'ListInstanceGroups', :cluster_id => jobflow_id, } aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
[ "def", "list_instance_groups", "(", "jobflow_id", ")", "params", "=", "{", ":operation", "=>", "'ListInstanceGroups'", ",", ":cluster_id", "=>", "jobflow_id", ",", "}", "aws_result", "=", "@aws_request", ".", "submit", "(", "params", ")", "yield", "aws_result", "if", "block_given?", "JSON", ".", "parse", "(", "aws_result", ")", "end" ]
List the instance groups in the specified jobflow emr.list_instance_groups('j-123') http://docs.aws.amazon.com/ElasticMapReduce/latest/API/API_ListInstanceGroups.html
[ "List", "the", "instance", "groups", "in", "the", "specified", "jobflow" ]
ee0a534b2c63ae0113aee5c85681ae4954703efb
https://github.com/rslifka/elasticity/blob/ee0a534b2c63ae0113aee5c85681ae4954703efb/lib/elasticity/emr.rb#L163-L171
train
rslifka/elasticity
lib/elasticity/emr.rb
Elasticity.EMR.list_bootstrap_actions
def list_bootstrap_actions(jobflow_id) params = { :operation => 'ListBootstrapActions', :cluster_id => jobflow_id, } aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
ruby
def list_bootstrap_actions(jobflow_id) params = { :operation => 'ListBootstrapActions', :cluster_id => jobflow_id, } aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
[ "def", "list_bootstrap_actions", "(", "jobflow_id", ")", "params", "=", "{", ":operation", "=>", "'ListBootstrapActions'", ",", ":cluster_id", "=>", "jobflow_id", ",", "}", "aws_result", "=", "@aws_request", ".", "submit", "(", "params", ")", "yield", "aws_result", "if", "block_given?", "JSON", ".", "parse", "(", "aws_result", ")", "end" ]
List the bootstrap actions in the specified jobflow emr.list_bootstrap_actions('j-123') http://docs.aws.amazon.com/ElasticMapReduce/latest/API/API_ListBootstrapActions.html
[ "List", "the", "bootstrap", "actions", "in", "the", "specified", "jobflow" ]
ee0a534b2c63ae0113aee5c85681ae4954703efb
https://github.com/rslifka/elasticity/blob/ee0a534b2c63ae0113aee5c85681ae4954703efb/lib/elasticity/emr.rb#L178-L186
train
rslifka/elasticity
lib/elasticity/emr.rb
Elasticity.EMR.list_steps
def list_steps(jobflow_id, options={}) params = { :operation => 'ListSteps', :cluster_id => jobflow_id, } params.merge!(:step_ids => options[:step_ids]) if options[:step_ids] params.merge!(:step_states => options[:step_states]) if options[:step_states] params.merge!(:marker => options[:marker]) if options[:marker] aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
ruby
def list_steps(jobflow_id, options={}) params = { :operation => 'ListSteps', :cluster_id => jobflow_id, } params.merge!(:step_ids => options[:step_ids]) if options[:step_ids] params.merge!(:step_states => options[:step_states]) if options[:step_states] params.merge!(:marker => options[:marker]) if options[:marker] aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
[ "def", "list_steps", "(", "jobflow_id", ",", "options", "=", "{", "}", ")", "params", "=", "{", ":operation", "=>", "'ListSteps'", ",", ":cluster_id", "=>", "jobflow_id", ",", "}", "params", ".", "merge!", "(", ":step_ids", "=>", "options", "[", ":step_ids", "]", ")", "if", "options", "[", ":step_ids", "]", "params", ".", "merge!", "(", ":step_states", "=>", "options", "[", ":step_states", "]", ")", "if", "options", "[", ":step_states", "]", "params", ".", "merge!", "(", ":marker", "=>", "options", "[", ":marker", "]", ")", "if", "options", "[", ":marker", "]", "aws_result", "=", "@aws_request", ".", "submit", "(", "params", ")", "yield", "aws_result", "if", "block_given?", "JSON", ".", "parse", "(", "aws_result", ")", "end" ]
List the steps in a job flow given specified filtering emr.list_steps('j-123', { :types => ['MASTER', 'CORE', 'TASK'], :step_ids => ['ID-1', 'ID-2'] :step_states => ['PENDING', 'RUNNING', ...] :marker => 'marker' # Retrieve from a prior call to list_steps }) http://docs.aws.amazon.com/ElasticMapReduce/latest/API/API_ListSteps.html
[ "List", "the", "steps", "in", "a", "job", "flow", "given", "specified", "filtering" ]
ee0a534b2c63ae0113aee5c85681ae4954703efb
https://github.com/rslifka/elasticity/blob/ee0a534b2c63ae0113aee5c85681ae4954703efb/lib/elasticity/emr.rb#L198-L209
train
rslifka/elasticity
lib/elasticity/emr.rb
Elasticity.EMR.remove_tags
def remove_tags(jobflow_id, keys) params = { :operation => 'RemoveTags', :resource_id => jobflow_id, :tag_keys => keys } aws_result = @aws_request.submit(params) yield aws_result if block_given? end
ruby
def remove_tags(jobflow_id, keys) params = { :operation => 'RemoveTags', :resource_id => jobflow_id, :tag_keys => keys } aws_result = @aws_request.submit(params) yield aws_result if block_given? end
[ "def", "remove_tags", "(", "jobflow_id", ",", "keys", ")", "params", "=", "{", ":operation", "=>", "'RemoveTags'", ",", ":resource_id", "=>", "jobflow_id", ",", ":tag_keys", "=>", "keys", "}", "aws_result", "=", "@aws_request", ".", "submit", "(", "params", ")", "yield", "aws_result", "if", "block_given?", "end" ]
Remove the specified tags on all instances in the specified jobflow emr.remove_tags('j-123', ['key1','key_only2']) See http://docs.aws.amazon.com/ElasticMapReduce/latest/API/API_RemoveTags.html
[ "Remove", "the", "specified", "tags", "on", "all", "instances", "in", "the", "specified", "jobflow" ]
ee0a534b2c63ae0113aee5c85681ae4954703efb
https://github.com/rslifka/elasticity/blob/ee0a534b2c63ae0113aee5c85681ae4954703efb/lib/elasticity/emr.rb#L233-L241
train
rslifka/elasticity
lib/elasticity/emr.rb
Elasticity.EMR.set_termination_protection
def set_termination_protection(jobflow_ids, protection_enabled=true) params = { :operation => 'SetTerminationProtection', :termination_protected => protection_enabled, :job_flow_ids => jobflow_ids } aws_result = @aws_request.submit(params) yield aws_result if block_given? end
ruby
def set_termination_protection(jobflow_ids, protection_enabled=true) params = { :operation => 'SetTerminationProtection', :termination_protected => protection_enabled, :job_flow_ids => jobflow_ids } aws_result = @aws_request.submit(params) yield aws_result if block_given? end
[ "def", "set_termination_protection", "(", "jobflow_ids", ",", "protection_enabled", "=", "true", ")", "params", "=", "{", ":operation", "=>", "'SetTerminationProtection'", ",", ":termination_protected", "=>", "protection_enabled", ",", ":job_flow_ids", "=>", "jobflow_ids", "}", "aws_result", "=", "@aws_request", ".", "submit", "(", "params", ")", "yield", "aws_result", "if", "block_given?", "end" ]
Enabled or disable "termination protection" on the specified job flows. Termination protection prevents a job flow from being terminated by a user initiated action, although the job flow will still terminate naturally. Takes an [] of job flow IDs. ["j-1B4D1XP0C0A35", "j-1YG2MYL0HVYS5", ...]
[ "Enabled", "or", "disable", "termination", "protection", "on", "the", "specified", "job", "flows", ".", "Termination", "protection", "prevents", "a", "job", "flow", "from", "being", "terminated", "by", "a", "user", "initiated", "action", "although", "the", "job", "flow", "will", "still", "terminate", "naturally", "." ]
ee0a534b2c63ae0113aee5c85681ae4954703efb
https://github.com/rslifka/elasticity/blob/ee0a534b2c63ae0113aee5c85681ae4954703efb/lib/elasticity/emr.rb#L315-L323
train
rslifka/elasticity
lib/elasticity/emr.rb
Elasticity.EMR.set_visible_to_all_users
def set_visible_to_all_users(jobflow_ids, visible=true) params = { :operation => 'SetVisibleToAllUsers', :visible_to_all_users => visible, :job_flow_ids => jobflow_ids } aws_result = @aws_request.submit(params) yield aws_result if block_given? end
ruby
def set_visible_to_all_users(jobflow_ids, visible=true) params = { :operation => 'SetVisibleToAllUsers', :visible_to_all_users => visible, :job_flow_ids => jobflow_ids } aws_result = @aws_request.submit(params) yield aws_result if block_given? end
[ "def", "set_visible_to_all_users", "(", "jobflow_ids", ",", "visible", "=", "true", ")", "params", "=", "{", ":operation", "=>", "'SetVisibleToAllUsers'", ",", ":visible_to_all_users", "=>", "visible", ",", ":job_flow_ids", "=>", "jobflow_ids", "}", "aws_result", "=", "@aws_request", ".", "submit", "(", "params", ")", "yield", "aws_result", "if", "block_given?", "end" ]
Whether or not all IAM users in this account can access the job flows. Takes an [] of job flow IDs. ["j-1B4D1XP0C0A35", "j-1YG2MYL0HVYS5", ...] http://docs.aws.amazon.com/ElasticMapReduce/latest/API/API_SetVisibleToAllUsers.html
[ "Whether", "or", "not", "all", "IAM", "users", "in", "this", "account", "can", "access", "the", "job", "flows", "." ]
ee0a534b2c63ae0113aee5c85681ae4954703efb
https://github.com/rslifka/elasticity/blob/ee0a534b2c63ae0113aee5c85681ae4954703efb/lib/elasticity/emr.rb#L332-L340
train
benschwarz/bonsai
lib/bonsai/page.rb
Bonsai.Page.assets
def assets Dir["#{directory}/**/*"].sort.select{|path| !File.directory?(path) && !File.basename(path).include?("yml") }.map do |file| file_to_hash(file) end end
ruby
def assets Dir["#{directory}/**/*"].sort.select{|path| !File.directory?(path) && !File.basename(path).include?("yml") }.map do |file| file_to_hash(file) end end
[ "def", "assets", "Dir", "[", "\"#{directory}/**/*\"", "]", ".", "sort", ".", "select", "{", "|", "path", "|", "!", "File", ".", "directory?", "(", "path", ")", "&&", "!", "File", ".", "basename", "(", "path", ")", ".", "include?", "(", "\"yml\"", ")", "}", ".", "map", "do", "|", "file", "|", "file_to_hash", "(", "file", ")", "end", "end" ]
This method is used for the exporter to copy assets
[ "This", "method", "is", "used", "for", "the", "exporter", "to", "copy", "assets" ]
33d6a84e21f0ee33e4fb1d029fe30a6d21444aaf
https://github.com/benschwarz/bonsai/blob/33d6a84e21f0ee33e4fb1d029fe30a6d21444aaf/lib/bonsai/page.rb#L76-L80
train
benschwarz/bonsai
lib/bonsai/page.rb
Bonsai.Page.to_hash
def to_hash hash = { :slug => slug, :permalink => permalink, :name => name, :children => children, :siblings => siblings, :parent => parent, :ancestors => ancestors, :navigation => Bonsai::Navigation.tree, :updated_at => mtime, :created_at => ctime }.merge(formatted_content).merge(disk_assets).merge(Bonsai.site) hash.stringify_keys end
ruby
def to_hash hash = { :slug => slug, :permalink => permalink, :name => name, :children => children, :siblings => siblings, :parent => parent, :ancestors => ancestors, :navigation => Bonsai::Navigation.tree, :updated_at => mtime, :created_at => ctime }.merge(formatted_content).merge(disk_assets).merge(Bonsai.site) hash.stringify_keys end
[ "def", "to_hash", "hash", "=", "{", ":slug", "=>", "slug", ",", ":permalink", "=>", "permalink", ",", ":name", "=>", "name", ",", ":children", "=>", "children", ",", ":siblings", "=>", "siblings", ",", ":parent", "=>", "parent", ",", ":ancestors", "=>", "ancestors", ",", ":navigation", "=>", "Bonsai", "::", "Navigation", ".", "tree", ",", ":updated_at", "=>", "mtime", ",", ":created_at", "=>", "ctime", "}", ".", "merge", "(", "formatted_content", ")", ".", "merge", "(", "disk_assets", ")", ".", "merge", "(", "Bonsai", ".", "site", ")", "hash", ".", "stringify_keys", "end" ]
This hash is available to all templates, it will map common properties, content file results, as well as any "magic" hashes for file system contents
[ "This", "hash", "is", "available", "to", "all", "templates", "it", "will", "map", "common", "properties", "content", "file", "results", "as", "well", "as", "any", "magic", "hashes", "for", "file", "system", "contents" ]
33d6a84e21f0ee33e4fb1d029fe30a6d21444aaf
https://github.com/benschwarz/bonsai/blob/33d6a84e21f0ee33e4fb1d029fe30a6d21444aaf/lib/bonsai/page.rb#L139-L154
train
benschwarz/bonsai
lib/bonsai/page.rb
Bonsai.Page.formatted_content
def formatted_content formatted_content = content formatted_content.each do |k,v| if v.is_a?(String) and v =~ /\n/ formatted_content[k] = to_markdown(v) end end formatted_content end
ruby
def formatted_content formatted_content = content formatted_content.each do |k,v| if v.is_a?(String) and v =~ /\n/ formatted_content[k] = to_markdown(v) end end formatted_content end
[ "def", "formatted_content", "formatted_content", "=", "content", "formatted_content", ".", "each", "do", "|", "k", ",", "v", "|", "if", "v", ".", "is_a?", "(", "String", ")", "and", "v", "=~", "/", "\\n", "/", "formatted_content", "[", "k", "]", "=", "to_markdown", "(", "v", ")", "end", "end", "formatted_content", "end" ]
This method ensures that multiline strings are run through markdown and smartypants
[ "This", "method", "ensures", "that", "multiline", "strings", "are", "run", "through", "markdown", "and", "smartypants" ]
33d6a84e21f0ee33e4fb1d029fe30a6d21444aaf
https://github.com/benschwarz/bonsai/blob/33d6a84e21f0ee33e4fb1d029fe30a6d21444aaf/lib/bonsai/page.rb#L160-L169
train
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
train
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
train
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
train
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", ")", "}", "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
train
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", "|", "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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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", ")", "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
train
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
train
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
train
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
train
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
train
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", "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
train
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?", "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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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", "=", "[", "]", "begin", "account_provider", "=", "RecoveryToken", ".", "account_provider_issuer", "(", "token", ")", "rescue", "RecoveryTokenSerializationError", ",", "UnknownProviderError", ",", "TokenFormatError", "=>", "e", "raise", "RecoveryTokenError", ",", "\"Could not determine provider: #{e.message}\"", "end", "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", "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
train
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
train
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
train
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", "=", "{", "}", ")", "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", "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", "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", "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", "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
train
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
train
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
train
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
train
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
train
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
train
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", ")", "store", "=", "record_store", "(", "options", ".", "delete", "(", ":store", ")", ")", "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", "]", "@strategy_by_attribute", "[", "strategy", ".", "attribute", "]", "=", "strategy", "end", "@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
train
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", ")", "@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
train
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
train
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", ")", "end", "end", "threads", ".", "each", "do", "|", "t", "|", "Kernel", ".", "sleep", "0.03", "begin", "t", ".", "join", "rescue", "Exception", "=>", "ex", "raps", "<<", "Rap", ".", "new", "(", "self", ",", "[", "ex", "]", ")", "next", "end", "raps", "<<", "t", "[", ":rap", "]", "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
train
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
train
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
train
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", "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
train
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", "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
train
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
train
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
train
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
train
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
train
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", ")", "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", ")", "cmd_internal", "=", "prepend_env", "(", "cmd_clean", ")", "if", "@rye_current_working_directory", "cwd", "=", "Rye", ".", "escape", "(", "@rye_safe", ",", "'cd'", ",", "@rye_current_working_directory", ")", "cmd_internal", "=", "'(%s; %s)'", "%", "[", "cwd", ",", "cmd_internal", "]", "end", "if", "@rye_current_umask", "cwd", "=", "Rye", ".", "escape", "(", "@rye_safe", ",", "'umask'", ",", "@rye_current_umask", ")", "cmd_internal", "=", "[", "cwd", ",", "cmd_internal", "]", ".", "join", "(", "' && '", ")", "end", "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", "]", "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", "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
train
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
train
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
train
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
train
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
train
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
train
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", "!", "(", "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
train
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", "@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
train
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", "retried", "=", "0", "@rye_opts", "[", ":keys", "]", ".", "compact!", "begin", "if", "@rye_via", "@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", "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", "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", "@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
train
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
train
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
train
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", "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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train