repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
quirkey/jim
lib/jim/bundler.rb
Jim.Bundler.resolve!
def resolve! self.bundles.each do |bundle_name, requirements| self.paths[bundle_name] = [] requirements.each do |name, version| path = self.index.find(name, version) if !path raise(MissingFile, "Could not find #{name} #{version} in any of these paths #{index.directories.join(':')}") end self.paths[bundle_name] << [path, name, version] end end paths end
ruby
def resolve! self.bundles.each do |bundle_name, requirements| self.paths[bundle_name] = [] requirements.each do |name, version| path = self.index.find(name, version) if !path raise(MissingFile, "Could not find #{name} #{version} in any of these paths #{index.directories.join(':')}") end self.paths[bundle_name] << [path, name, version] end end paths end
[ "def", "resolve!", "self", ".", "bundles", ".", "each", "do", "|", "bundle_name", ",", "requirements", "|", "self", ".", "paths", "[", "bundle_name", "]", "=", "[", "]", "requirements", ".", "each", "do", "|", "name", ",", "version", "|", "path", "=", "self", ".", "index", ".", "find", "(", "name", ",", "version", ")", "if", "!", "path", "raise", "(", "MissingFile", ",", "\"Could not find #{name} #{version} in any of these paths #{index.directories.join(':')}\"", ")", "end", "self", ".", "paths", "[", "bundle_name", "]", "<<", "[", "path", ",", "name", ",", "version", "]", "end", "end", "paths", "end" ]
Resolve the requirements specified in the Jimfile for each bundle to `paths` Raises MissingFile error
[ "Resolve", "the", "requirements", "specified", "in", "the", "Jimfile", "for", "each", "bundle", "to", "paths", "Raises", "MissingFile", "error" ]
ad5dbf06527a1d0376055a02b58bb11b5a0ebc35
https://github.com/quirkey/jim/blob/ad5dbf06527a1d0376055a02b58bb11b5a0ebc35/lib/jim/bundler.rb#L100-L113
train
samvera-labs/geo_works
app/models/concerns/geo_works/vector_file_behavior.rb
GeoWorks.VectorFileBehavior.vector_work
def vector_work parents.select do |parent| parent.class.included_modules.include?(::GeoWorks::VectorWorkBehavior) end.to_a end
ruby
def vector_work parents.select do |parent| parent.class.included_modules.include?(::GeoWorks::VectorWorkBehavior) end.to_a end
[ "def", "vector_work", "parents", ".", "select", "do", "|", "parent", "|", "parent", ".", "class", ".", "included_modules", ".", "include?", "(", "::", "GeoWorks", "::", "VectorWorkBehavior", ")", "end", ".", "to_a", "end" ]
Retrieve the Vector Work of which this Object is a member @return [GeoWorks::VectorWork]
[ "Retrieve", "the", "Vector", "Work", "of", "which", "this", "Object", "is", "a", "member" ]
df1eff35fd01469a623fafeb9d71b44fd6160ca8
https://github.com/samvera-labs/geo_works/blob/df1eff35fd01469a623fafeb9d71b44fd6160ca8/app/models/concerns/geo_works/vector_file_behavior.rb#L8-L12
train
usmu/usmu
lib/usmu/plugin.rb
Usmu.Plugin.invoke
def invoke(method, *args) @log.debug("Invoking plugin API #{method}") plugins.map do |p| if p.respond_to? method @log.debug("Sending message to #{p.class.name}") p.public_send method, *args else nil end end.select {|i| i} end
ruby
def invoke(method, *args) @log.debug("Invoking plugin API #{method}") plugins.map do |p| if p.respond_to? method @log.debug("Sending message to #{p.class.name}") p.public_send method, *args else nil end end.select {|i| i} end
[ "def", "invoke", "(", "method", ",", "*", "args", ")", "@log", ".", "debug", "(", "\"Invoking plugin API #{method}\"", ")", "plugins", ".", "map", "do", "|", "p", "|", "if", "p", ".", "respond_to?", "method", "@log", ".", "debug", "(", "\"Sending message to #{p.class.name}\"", ")", "p", ".", "public_send", "method", ",", "*", "args", "else", "nil", "end", "end", ".", "select", "{", "|", "i", "|", "i", "}", "end" ]
Call all plugins and collate any data returned. nil can be returned explicitly to say this plugin has nothing to return. @param [Symbol] method The name of the method to call. This should be namespaced somehow. For example, a plugin called `usmu-s3` could use the method namespace `s3` and have a hook called `:s3_upload` @param [Array] args The arguments to pass through to plugins. Can be empty. @return [Array] An array of non-nil values returned from plugins
[ "Call", "all", "plugins", "and", "collate", "any", "data", "returned", "." ]
037bfe0daa995477c29662931236d7a60ca29730
https://github.com/usmu/usmu/blob/037bfe0daa995477c29662931236d7a60ca29730/lib/usmu/plugin.rb#L42-L52
train
usmu/usmu
lib/usmu/plugin.rb
Usmu.Plugin.alter
def alter(method, value, *context) @log.debug("Invoking plugin alter API #{method}") plugins.each do |p| if p.respond_to? "#{method}_alter" @log.debug("Sending message to #{p.class.name}") value = p.public_send "#{method}_alter", value, *context end end value end
ruby
def alter(method, value, *context) @log.debug("Invoking plugin alter API #{method}") plugins.each do |p| if p.respond_to? "#{method}_alter" @log.debug("Sending message to #{p.class.name}") value = p.public_send "#{method}_alter", value, *context end end value end
[ "def", "alter", "(", "method", ",", "value", ",", "*", "context", ")", "@log", ".", "debug", "(", "\"Invoking plugin alter API #{method}\"", ")", "plugins", ".", "each", "do", "|", "p", "|", "if", "p", ".", "respond_to?", "\"#{method}_alter\"", "@log", ".", "debug", "(", "\"Sending message to #{p.class.name}\"", ")", "value", "=", "p", ".", "public_send", "\"#{method}_alter\"", ",", "value", ",", "*", "context", "end", "end", "value", "end" ]
Call all plugins and allow for altering a value. The return value of each hook is passed into the next alter function, hence all implementations must always return a value. If the hook doesn't wish to modify data this call then it should return the original value. @param [Symbol] method The name of the method to call. This should be namespaced somehow. For example, a plugin called `usmu-s3` could use the method namespace `s3` and have a hook called `:s3_upload` @param [Object] value The value to modify. @param [Array] context Optional extra parameters to provide. @return [Object] The modified value.
[ "Call", "all", "plugins", "and", "allow", "for", "altering", "a", "value", "." ]
037bfe0daa995477c29662931236d7a60ca29730
https://github.com/usmu/usmu/blob/037bfe0daa995477c29662931236d7a60ca29730/lib/usmu/plugin.rb#L64-L73
train
usmu/usmu
lib/usmu/plugin.rb
Usmu.Plugin.load_gem
def load_gem(spec) load_path = spec.name.gsub('-', '/') require load_path unless @loaded.include? load_path @loaded << load_path klass = path_to_class(load_path) @log.debug("Loading plugin #{klass} from '#{load_path}'") plugins.push plugin_get(klass) end nil end
ruby
def load_gem(spec) load_path = spec.name.gsub('-', '/') require load_path unless @loaded.include? load_path @loaded << load_path klass = path_to_class(load_path) @log.debug("Loading plugin #{klass} from '#{load_path}'") plugins.push plugin_get(klass) end nil end
[ "def", "load_gem", "(", "spec", ")", "load_path", "=", "spec", ".", "name", ".", "gsub", "(", "'-'", ",", "'/'", ")", "require", "load_path", "unless", "@loaded", ".", "include?", "load_path", "@loaded", "<<", "load_path", "klass", "=", "path_to_class", "(", "load_path", ")", "@log", ".", "debug", "(", "\"Loading plugin #{klass} from '#{load_path}'\"", ")", "plugins", ".", "push", "plugin_get", "(", "klass", ")", "end", "nil", "end" ]
Helper function to load a plugin from a gem specification @param [Gem::Specification] spec
[ "Helper", "function", "to", "load", "a", "plugin", "from", "a", "gem", "specification" ]
037bfe0daa995477c29662931236d7a60ca29730
https://github.com/usmu/usmu/blob/037bfe0daa995477c29662931236d7a60ca29730/lib/usmu/plugin.rb#L88-L99
train
buren/honey_format
lib/honey_format/cli/benchmark_cli.rb
HoneyFormat.BenchmarkCLI.expected_runtime_seconds
def expected_runtime_seconds(report_count:) runs = report_count * options[:lines_multipliers].length warmup_time_seconds = runs * options[:benchmark_warmup] bench_time_seconds = runs * options[:benchmark_time] warmup_time_seconds + bench_time_seconds end
ruby
def expected_runtime_seconds(report_count:) runs = report_count * options[:lines_multipliers].length warmup_time_seconds = runs * options[:benchmark_warmup] bench_time_seconds = runs * options[:benchmark_time] warmup_time_seconds + bench_time_seconds end
[ "def", "expected_runtime_seconds", "(", "report_count", ":", ")", "runs", "=", "report_count", "*", "options", "[", ":lines_multipliers", "]", ".", "length", "warmup_time_seconds", "=", "runs", "*", "options", "[", ":benchmark_warmup", "]", "bench_time_seconds", "=", "runs", "*", "options", "[", ":benchmark_time", "]", "warmup_time_seconds", "+", "bench_time_seconds", "end" ]
Instantiate the CLI @param writer [CLIResultWriter] the result writer to use Returns the expected runtime in seconds @param report_count [Integer] number of reports in benchmark @return [Integer] expected runtime in seconds
[ "Instantiate", "the", "CLI" ]
5c54fba5f5ba044721afeef460a069af2018452c
https://github.com/buren/honey_format/blob/5c54fba5f5ba044721afeef460a069af2018452c/lib/honey_format/cli/benchmark_cli.rb#L30-L36
train
buren/honey_format
lib/honey_format/cli/benchmark_cli.rb
HoneyFormat.BenchmarkCLI.fetch_default_benchmark_csv
def fetch_default_benchmark_csv cache_path = CSV_TEST_DATA_CACHE_PATH if File.exist?(cache_path) writer.puts "Cache file found at #{cache_path}.", verbose: true @used_input_path = cache_path return File.read(cache_path) end writer.print 'Downloading test data file from GitHub..', verbose: true require 'open-uri' open(CSV_TEST_DATA_URL).read.tap do |csv| # rubocop:disable Security/Open @used_input_path = CSV_TEST_DATA_URL writer.puts 'done!', verbose: true File.write(cache_path, csv) writer.puts "Wrote cache file to #{cache_path}..", verbose: true end end
ruby
def fetch_default_benchmark_csv cache_path = CSV_TEST_DATA_CACHE_PATH if File.exist?(cache_path) writer.puts "Cache file found at #{cache_path}.", verbose: true @used_input_path = cache_path return File.read(cache_path) end writer.print 'Downloading test data file from GitHub..', verbose: true require 'open-uri' open(CSV_TEST_DATA_URL).read.tap do |csv| # rubocop:disable Security/Open @used_input_path = CSV_TEST_DATA_URL writer.puts 'done!', verbose: true File.write(cache_path, csv) writer.puts "Wrote cache file to #{cache_path}..", verbose: true end end
[ "def", "fetch_default_benchmark_csv", "cache_path", "=", "CSV_TEST_DATA_CACHE_PATH", "if", "File", ".", "exist?", "(", "cache_path", ")", "writer", ".", "puts", "\"Cache file found at #{cache_path}.\"", ",", "verbose", ":", "true", "@used_input_path", "=", "cache_path", "return", "File", ".", "read", "(", "cache_path", ")", "end", "writer", ".", "print", "'Downloading test data file from GitHub..'", ",", "verbose", ":", "true", "require", "'open-uri'", "open", "(", "CSV_TEST_DATA_URL", ")", ".", "read", ".", "tap", "do", "|", "csv", "|", "@used_input_path", "=", "CSV_TEST_DATA_URL", "writer", ".", "puts", "'done!'", ",", "verbose", ":", "true", "File", ".", "write", "(", "cache_path", ",", "csv", ")", "writer", ".", "puts", "\"Wrote cache file to #{cache_path}..\"", ",", "verbose", ":", "true", "end", "end" ]
Download or fetch the default benchmark file from cache @return [String] CSV file as a string
[ "Download", "or", "fetch", "the", "default", "benchmark", "file", "from", "cache" ]
5c54fba5f5ba044721afeef460a069af2018452c
https://github.com/buren/honey_format/blob/5c54fba5f5ba044721afeef460a069af2018452c/lib/honey_format/cli/benchmark_cli.rb#L46-L63
train
culturecode/stagehand
lib/stagehand/auditor.rb
Stagehand.Auditor.incomplete_end_operations
def incomplete_end_operations last_entry_per_session = Staging::CommitEntry.group(:session).select('MAX(id) AS id') return Staging::CommitEntry.uncontained.end_operations.where.not(:id => last_entry_per_session) end
ruby
def incomplete_end_operations last_entry_per_session = Staging::CommitEntry.group(:session).select('MAX(id) AS id') return Staging::CommitEntry.uncontained.end_operations.where.not(:id => last_entry_per_session) end
[ "def", "incomplete_end_operations", "last_entry_per_session", "=", "Staging", "::", "CommitEntry", ".", "group", "(", ":session", ")", ".", "select", "(", "'MAX(id) AS id'", ")", "return", "Staging", "::", "CommitEntry", ".", "uncontained", ".", "end_operations", ".", "where", ".", "not", "(", ":id", "=>", "last_entry_per_session", ")", "end" ]
Incomplete End Operation that are not the last entry in their session
[ "Incomplete", "End", "Operation", "that", "are", "not", "the", "last", "entry", "in", "their", "session" ]
af627f1948b9dfc39ec13aefe77a47c21b4456a5
https://github.com/culturecode/stagehand/blob/af627f1948b9dfc39ec13aefe77a47c21b4456a5/lib/stagehand/auditor.rb#L92-L95
train
culturecode/stagehand
lib/stagehand/auditor.rb
Stagehand.Auditor.incomplete_start_operations
def incomplete_start_operations last_start_entry_per_session = Staging::CommitEntry.start_operations.group(:session).select('MAX(id) AS id') return Staging::CommitEntry.uncontained.start_operations.where.not(:id => last_start_entry_per_session) end
ruby
def incomplete_start_operations last_start_entry_per_session = Staging::CommitEntry.start_operations.group(:session).select('MAX(id) AS id') return Staging::CommitEntry.uncontained.start_operations.where.not(:id => last_start_entry_per_session) end
[ "def", "incomplete_start_operations", "last_start_entry_per_session", "=", "Staging", "::", "CommitEntry", ".", "start_operations", ".", "group", "(", ":session", ")", ".", "select", "(", "'MAX(id) AS id'", ")", "return", "Staging", "::", "CommitEntry", ".", "uncontained", ".", "start_operations", ".", "where", ".", "not", "(", ":id", "=>", "last_start_entry_per_session", ")", "end" ]
Incomplete Start on the same session as a subsequent start operation
[ "Incomplete", "Start", "on", "the", "same", "session", "as", "a", "subsequent", "start", "operation" ]
af627f1948b9dfc39ec13aefe77a47c21b4456a5
https://github.com/culturecode/stagehand/blob/af627f1948b9dfc39ec13aefe77a47c21b4456a5/lib/stagehand/auditor.rb#L98-L101
train
samvera-labs/geo_works
app/models/concerns/geo_works/metadata_extraction_helper.rb
GeoWorks.MetadataExtractionHelper.populate_metadata
def populate_metadata(id) extract_metadata(id).each do |k, v| send("#{k}=".to_sym, v) # set each property end end
ruby
def populate_metadata(id) extract_metadata(id).each do |k, v| send("#{k}=".to_sym, v) # set each property end end
[ "def", "populate_metadata", "(", "id", ")", "extract_metadata", "(", "id", ")", ".", "each", "do", "|", "k", ",", "v", "|", "send", "(", "\"#{k}=\"", ".", "to_sym", ",", "v", ")", "end", "end" ]
Sets properties from the constitutent external metadata file
[ "Sets", "properties", "from", "the", "constitutent", "external", "metadata", "file" ]
df1eff35fd01469a623fafeb9d71b44fd6160ca8
https://github.com/samvera-labs/geo_works/blob/df1eff35fd01469a623fafeb9d71b44fd6160ca8/app/models/concerns/geo_works/metadata_extraction_helper.rb#L12-L16
train
usmu/usmu
lib/usmu/site_generator.rb
Usmu.SiteGenerator.generate_page
def generate_page(page) output_filename = page.output_filename @log.success("creating #{output_filename}...") @log.debug("Rendering #{output_filename} from #{page.name}") file = File.join(@configuration.destination_path, output_filename) directory = File.dirname(file) unless File.directory?(directory) FileUtils.mkdir_p(directory) end File.write file, page.render FileUtils.touch file, mtime: page.mtime nil end
ruby
def generate_page(page) output_filename = page.output_filename @log.success("creating #{output_filename}...") @log.debug("Rendering #{output_filename} from #{page.name}") file = File.join(@configuration.destination_path, output_filename) directory = File.dirname(file) unless File.directory?(directory) FileUtils.mkdir_p(directory) end File.write file, page.render FileUtils.touch file, mtime: page.mtime nil end
[ "def", "generate_page", "(", "page", ")", "output_filename", "=", "page", ".", "output_filename", "@log", ".", "success", "(", "\"creating #{output_filename}...\"", ")", "@log", ".", "debug", "(", "\"Rendering #{output_filename} from #{page.name}\"", ")", "file", "=", "File", ".", "join", "(", "@configuration", ".", "destination_path", ",", "output_filename", ")", "directory", "=", "File", ".", "dirname", "(", "file", ")", "unless", "File", ".", "directory?", "(", "directory", ")", "FileUtils", ".", "mkdir_p", "(", "directory", ")", "end", "File", ".", "write", "file", ",", "page", ".", "render", "FileUtils", ".", "touch", "file", ",", "mtime", ":", "page", ".", "mtime", "nil", "end" ]
Helper function to generate a page @param [Usmu::Template::Page] page
[ "Helper", "function", "to", "generate", "a", "page" ]
037bfe0daa995477c29662931236d7a60ca29730
https://github.com/usmu/usmu/blob/037bfe0daa995477c29662931236d7a60ca29730/lib/usmu/site_generator.rb#L76-L91
train
printercu/gemfile_locker
lib/gemfile_locker/gem_entry.rb
GemfileLocker.GemEntry.replace_string_node
def replace_string_node(target, value) quote = target.loc.begin.source rewriter.replace(target.loc.expression, "#{quote}#{value}#{quote}") end
ruby
def replace_string_node(target, value) quote = target.loc.begin.source rewriter.replace(target.loc.expression, "#{quote}#{value}#{quote}") end
[ "def", "replace_string_node", "(", "target", ",", "value", ")", "quote", "=", "target", ".", "loc", ".", "begin", ".", "source", "rewriter", ".", "replace", "(", "target", ".", "loc", ".", "expression", ",", "\"#{quote}#{value}#{quote}\"", ")", "end" ]
Change content of string, keeping quoting style.
[ "Change", "content", "of", "string", "keeping", "quoting", "style", "." ]
886852a3d000eade8511efee91cac6a8cc927cdf
https://github.com/printercu/gemfile_locker/blob/886852a3d000eade8511efee91cac6a8cc927cdf/lib/gemfile_locker/gem_entry.rb#L37-L40
train
printercu/gemfile_locker
lib/gemfile_locker/gem_entry.rb
GemfileLocker.GemEntry.remove_node_with_comma
def remove_node_with_comma(target) expression = target.loc.expression comma_pos = expression.source_buffer.source.rindex(',', expression.begin_pos) rewriter.remove(expression.with(begin_pos: comma_pos)) end
ruby
def remove_node_with_comma(target) expression = target.loc.expression comma_pos = expression.source_buffer.source.rindex(',', expression.begin_pos) rewriter.remove(expression.with(begin_pos: comma_pos)) end
[ "def", "remove_node_with_comma", "(", "target", ")", "expression", "=", "target", ".", "loc", ".", "expression", "comma_pos", "=", "expression", ".", "source_buffer", ".", "source", ".", "rindex", "(", "','", ",", "expression", ".", "begin_pos", ")", "rewriter", ".", "remove", "(", "expression", ".", "with", "(", "begin_pos", ":", "comma_pos", ")", ")", "end" ]
Remove node with preceding comma.
[ "Remove", "node", "with", "preceding", "comma", "." ]
886852a3d000eade8511efee91cac6a8cc927cdf
https://github.com/printercu/gemfile_locker/blob/886852a3d000eade8511efee91cac6a8cc927cdf/lib/gemfile_locker/gem_entry.rb#L43-L47
train
phatworx/rails_paginate
lib/rails_paginate/helpers/action_view.rb
RailsPaginate::Helpers.ActionView.paginate
def paginate(*args) options = args.extract_options! raise ArgumentError, "first argument must be a RailsPaginate::Collection" unless args.first.is_a? RailsPaginate::Collection collection = args.first # p @controller # p url_for(:action => :index, :controller => :dummy) # renderer renderer = options[:renderer] || RailsPaginate.default_renderer pager = options[:pager] || RailsPaginate.default_pager attributes = {} attributes[:class] = "pagination #{options[:class]}".strip attributes[:id] = options[:id] unless options[:id].blank? # load classes renderer = RailsPaginate.renderer(renderer) pager = RailsPaginate.pager(pager) content_tag :div, attributes do renderer.new(self, collection, pager.new(collection), options).render end end
ruby
def paginate(*args) options = args.extract_options! raise ArgumentError, "first argument must be a RailsPaginate::Collection" unless args.first.is_a? RailsPaginate::Collection collection = args.first # p @controller # p url_for(:action => :index, :controller => :dummy) # renderer renderer = options[:renderer] || RailsPaginate.default_renderer pager = options[:pager] || RailsPaginate.default_pager attributes = {} attributes[:class] = "pagination #{options[:class]}".strip attributes[:id] = options[:id] unless options[:id].blank? # load classes renderer = RailsPaginate.renderer(renderer) pager = RailsPaginate.pager(pager) content_tag :div, attributes do renderer.new(self, collection, pager.new(collection), options).render end end
[ "def", "paginate", "(", "*", "args", ")", "options", "=", "args", ".", "extract_options!", "raise", "ArgumentError", ",", "\"first argument must be a RailsPaginate::Collection\"", "unless", "args", ".", "first", ".", "is_a?", "RailsPaginate", "::", "Collection", "collection", "=", "args", ".", "first", "renderer", "=", "options", "[", ":renderer", "]", "||", "RailsPaginate", ".", "default_renderer", "pager", "=", "options", "[", ":pager", "]", "||", "RailsPaginate", ".", "default_pager", "attributes", "=", "{", "}", "attributes", "[", ":class", "]", "=", "\"pagination #{options[:class]}\"", ".", "strip", "attributes", "[", ":id", "]", "=", "options", "[", ":id", "]", "unless", "options", "[", ":id", "]", ".", "blank?", "renderer", "=", "RailsPaginate", ".", "renderer", "(", "renderer", ")", "pager", "=", "RailsPaginate", ".", "pager", "(", "pager", ")", "content_tag", ":div", ",", "attributes", "do", "renderer", ".", "new", "(", "self", ",", "collection", ",", "pager", ".", "new", "(", "collection", ")", ",", "options", ")", ".", "render", "end", "end" ]
view_helper for paginate == Options :id :class
[ "view_helper", "for", "paginate" ]
ae8cbc12030853b236dc2cbf6ede8700fb835771
https://github.com/phatworx/rails_paginate/blob/ae8cbc12030853b236dc2cbf6ede8700fb835771/lib/rails_paginate/helpers/action_view.rb#L9-L33
train
topfunky/google-checkout
lib/google-checkout/notification.rb
GoogleCheckout.Notification.acknowledgment_xml
def acknowledgment_xml xml = Builder::XmlMarkup.new xml.instruct! @xml = xml.tag!('notification-acknowledgment', { :xmlns => "http://checkout.google.com/schema/2", 'serial-number' => serial_number }) @xml end
ruby
def acknowledgment_xml xml = Builder::XmlMarkup.new xml.instruct! @xml = xml.tag!('notification-acknowledgment', { :xmlns => "http://checkout.google.com/schema/2", 'serial-number' => serial_number }) @xml end
[ "def", "acknowledgment_xml", "xml", "=", "Builder", "::", "XmlMarkup", ".", "new", "xml", ".", "instruct!", "@xml", "=", "xml", ".", "tag!", "(", "'notification-acknowledgment'", ",", "{", ":xmlns", "=>", "\"http://checkout.google.com/schema/2\"", ",", "'serial-number'", "=>", "serial_number", "}", ")", "@xml", "end" ]
Returns an XML string that can be sent back to Google to communicate successful receipt of the notification.
[ "Returns", "an", "XML", "string", "that", "can", "be", "sent", "back", "to", "Google", "to", "communicate", "successful", "receipt", "of", "the", "notification", "." ]
66089cef799bd40f3ba4370f01f1b8dc10f92115
https://github.com/topfunky/google-checkout/blob/66089cef799bd40f3ba4370f01f1b8dc10f92115/lib/google-checkout/notification.rb#L103-L111
train
topfunky/google-checkout
lib/google-checkout/notification.rb
GoogleCheckout.Notification.method_missing
def method_missing(method_name, *args) element_name = method_name.to_s.gsub(/_/, '-') if element = (@doc.at element_name) if element.respond_to?(:inner_html) return element.inner_html end end super end
ruby
def method_missing(method_name, *args) element_name = method_name.to_s.gsub(/_/, '-') if element = (@doc.at element_name) if element.respond_to?(:inner_html) return element.inner_html end end super end
[ "def", "method_missing", "(", "method_name", ",", "*", "args", ")", "element_name", "=", "method_name", ".", "to_s", ".", "gsub", "(", "/", "/", ",", "'-'", ")", "if", "element", "=", "(", "@doc", ".", "at", "element_name", ")", "if", "element", ".", "respond_to?", "(", ":inner_html", ")", "return", "element", ".", "inner_html", "end", "end", "super", "end" ]
Take requests for an XML element and returns its value. notification.google_order_number => Returns value of '<google-order-number>' Because of how Nokogiri#at works, it will even dig into subtags and return the value of the first matching tag. For example, there is an +email+ field in +buyer-shipping-address+ and also in +buyer-billing-address+, but only the first will be returned. If you want to get at a value explicitly, use +notification.doc+ and search the Nokogiri document manually.
[ "Take", "requests", "for", "an", "XML", "element", "and", "returns", "its", "value", "." ]
66089cef799bd40f3ba4370f01f1b8dc10f92115
https://github.com/topfunky/google-checkout/blob/66089cef799bd40f3ba4370f01f1b8dc10f92115/lib/google-checkout/notification.rb#L134-L142
train
buren/honey_format
lib/honey_format/matrix/matrix.rb
HoneyFormat.Matrix.to_csv
def to_csv(columns: nil, &block) columns = columns&.map(&:to_sym) @header.to_csv(columns: columns) + @rows.to_csv(columns: columns, &block) end
ruby
def to_csv(columns: nil, &block) columns = columns&.map(&:to_sym) @header.to_csv(columns: columns) + @rows.to_csv(columns: columns, &block) end
[ "def", "to_csv", "(", "columns", ":", "nil", ",", "&", "block", ")", "columns", "=", "columns", "&.", "map", "(", "&", ":to_sym", ")", "@header", ".", "to_csv", "(", "columns", ":", "columns", ")", "+", "@rows", ".", "to_csv", "(", "columns", ":", "columns", ",", "&", "block", ")", "end" ]
Convert matrix to CSV-string. @param columns [Array<Symbol>, Set<Symbol>, NilClass] the columns to output, nil means all columns (default: nil) @yield [row] The given block will be passed for every row - return truthy if you want the row to be included in the output @yieldparam [Row] row @return [String] CSV-string representation. @example with selected columns matrix.to_csv(columns: [:id, :country]) @example with selected rows matrix.to_csv { |row| row.country == 'Sweden' } @example with both selected columns and rows matrix.to_csv(columns: [:id, :country]) { |row| row.country == 'Sweden' }
[ "Convert", "matrix", "to", "CSV", "-", "string", "." ]
5c54fba5f5ba044721afeef460a069af2018452c
https://github.com/buren/honey_format/blob/5c54fba5f5ba044721afeef460a069af2018452c/lib/honey_format/matrix/matrix.rb#L99-L102
train
dropofwill/rtasklib
lib/rtasklib/controller.rb
Rtasklib.Controller.some
def some ids: nil, tags: nil, dom: nil, active: true some = [] f = Helpers.filter(ids: ids, tags: tags, dom: dom) a = Helpers.pending_or_waiting(active) Execute.task_popen3(*@override_a, f, a, "export") do |i, o, e, t| some = MultiJson.load(o.read).map do |x| Rtasklib::Models::TaskModel.new(x) end end return some end
ruby
def some ids: nil, tags: nil, dom: nil, active: true some = [] f = Helpers.filter(ids: ids, tags: tags, dom: dom) a = Helpers.pending_or_waiting(active) Execute.task_popen3(*@override_a, f, a, "export") do |i, o, e, t| some = MultiJson.load(o.read).map do |x| Rtasklib::Models::TaskModel.new(x) end end return some end
[ "def", "some", "ids", ":", "nil", ",", "tags", ":", "nil", ",", "dom", ":", "nil", ",", "active", ":", "true", "some", "=", "[", "]", "f", "=", "Helpers", ".", "filter", "(", "ids", ":", "ids", ",", "tags", ":", "tags", ",", "dom", ":", "dom", ")", "a", "=", "Helpers", ".", "pending_or_waiting", "(", "active", ")", "Execute", ".", "task_popen3", "(", "*", "@override_a", ",", "f", ",", "a", ",", "\"export\"", ")", "do", "|", "i", ",", "o", ",", "e", ",", "t", "|", "some", "=", "MultiJson", ".", "load", "(", "o", ".", "read", ")", ".", "map", "do", "|", "x", "|", "Rtasklib", "::", "Models", "::", "TaskModel", ".", "new", "(", "x", ")", "end", "end", "return", "some", "end" ]
Retrieves the current task list filtered by id, tag, or a dom query @example filter by an array of ids tw.some(ids: [1..2, 5]) @example filter by tags tw.some(tags: ["+school", "or", "-work"] # You can also pass in a TW style string if you prefer tw.some(tags: "+school or -work"] @example filter by a dom query require "date" today = DateTime.now # note that queries with dots need to be Strings, as they would be # invalid Symbols tw.some(dom: {project: "Work", "due.before" => today}) # You can also pass in a TW style string if you prefer tw.some(dom: "project:Work due.before:#{today}") @param ids [Array<Range, Fixnum, String>, String, Range, Fixnum] @param tags [Array<String>, String] @param dom [Array<String>, String] @param active [Boolean] return only pending & waiting tasks @return [Array<Models::TaskModel>] @api public
[ "Retrieves", "the", "current", "task", "list", "filtered", "by", "id", "tag", "or", "a", "dom", "query" ]
c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c
https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/controller.rb#L104-L114
train
dropofwill/rtasklib
lib/rtasklib/controller.rb
Rtasklib.Controller.get_rc
def get_rc res = [] Execute.task_popen3(*@override_a, "_show") do |i, o, e, t| res = o.read.each_line.map { |l| l.chomp } end Taskrc.new(res, :array) end
ruby
def get_rc res = [] Execute.task_popen3(*@override_a, "_show") do |i, o, e, t| res = o.read.each_line.map { |l| l.chomp } end Taskrc.new(res, :array) end
[ "def", "get_rc", "res", "=", "[", "]", "Execute", ".", "task_popen3", "(", "*", "@override_a", ",", "\"_show\"", ")", "do", "|", "i", ",", "o", ",", "e", ",", "t", "|", "res", "=", "o", ".", "read", ".", "each_line", ".", "map", "{", "|", "l", "|", "l", ".", "chomp", "}", "end", "Taskrc", ".", "new", "(", "res", ",", ":array", ")", "end" ]
Calls `task _show` with initial overrides returns a Taskrc object of the result @return [Rtasklib::Taskrc] @api public
[ "Calls", "task", "_show", "with", "initial", "overrides", "returns", "a", "Taskrc", "object", "of", "the", "result" ]
c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c
https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/controller.rb#L139-L145
train
dropofwill/rtasklib
lib/rtasklib/controller.rb
Rtasklib.Controller.get_version
def get_version version = nil Execute.task_popen3("_version") do |i, o, e, t| version = Helpers.to_gem_version(o.read.chomp) end version end
ruby
def get_version version = nil Execute.task_popen3("_version") do |i, o, e, t| version = Helpers.to_gem_version(o.read.chomp) end version end
[ "def", "get_version", "version", "=", "nil", "Execute", ".", "task_popen3", "(", "\"_version\"", ")", "do", "|", "i", ",", "o", ",", "e", ",", "t", "|", "version", "=", "Helpers", ".", "to_gem_version", "(", "o", ".", "read", ".", "chomp", ")", "end", "version", "end" ]
Calls `task _version` and returns the result @return [String] @api public
[ "Calls", "task", "_version", "and", "returns", "the", "result" ]
c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c
https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/controller.rb#L151-L157
train
dropofwill/rtasklib
lib/rtasklib/controller.rb
Rtasklib.Controller.get_udas
def get_udas udas = {} taskrc.config.attributes .select { |attr, val| Helpers.uda_attr? attr } .sort .chunk { |attr, val| Helpers.arbitrary_attr attr } .each do |attr, arr| uda = arr.map do |pair| [Helpers.deep_attr(pair[0]), pair[1]] end udas[attr.to_sym] = Hash[uda] end return udas end
ruby
def get_udas udas = {} taskrc.config.attributes .select { |attr, val| Helpers.uda_attr? attr } .sort .chunk { |attr, val| Helpers.arbitrary_attr attr } .each do |attr, arr| uda = arr.map do |pair| [Helpers.deep_attr(pair[0]), pair[1]] end udas[attr.to_sym] = Hash[uda] end return udas end
[ "def", "get_udas", "udas", "=", "{", "}", "taskrc", ".", "config", ".", "attributes", ".", "select", "{", "|", "attr", ",", "val", "|", "Helpers", ".", "uda_attr?", "attr", "}", ".", "sort", ".", "chunk", "{", "|", "attr", ",", "val", "|", "Helpers", ".", "arbitrary_attr", "attr", "}", ".", "each", "do", "|", "attr", ",", "arr", "|", "uda", "=", "arr", ".", "map", "do", "|", "pair", "|", "[", "Helpers", ".", "deep_attr", "(", "pair", "[", "0", "]", ")", ",", "pair", "[", "1", "]", "]", "end", "udas", "[", "attr", ".", "to_sym", "]", "=", "Hash", "[", "uda", "]", "end", "return", "udas", "end" ]
Retrieves a hash of hashes with info about the UDAs currently available @return [Hash{Symbol=>Hash}] @api public
[ "Retrieves", "a", "hash", "of", "hashes", "with", "info", "about", "the", "UDAs", "currently", "available" ]
c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c
https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/controller.rb#L292-L305
train
dropofwill/rtasklib
lib/rtasklib/controller.rb
Rtasklib.Controller.update_config!
def update_config! attr, val Execute.task_popen3(*override_a, "config #{attr} #{val}") do |i, o, e, t| return t.value end end
ruby
def update_config! attr, val Execute.task_popen3(*override_a, "config #{attr} #{val}") do |i, o, e, t| return t.value end end
[ "def", "update_config!", "attr", ",", "val", "Execute", ".", "task_popen3", "(", "*", "override_a", ",", "\"config #{attr} #{val}\"", ")", "do", "|", "i", ",", "o", ",", "e", ",", "t", "|", "return", "t", ".", "value", "end", "end" ]
Update a configuration variable in the .taskrc @param attr [String] @param val [String] @return [Process::Status] the exit status of the thread @api public
[ "Update", "a", "configuration", "variable", "in", "the", ".", "taskrc" ]
c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c
https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/controller.rb#L313-L317
train
dropofwill/rtasklib
lib/rtasklib/controller.rb
Rtasklib.Controller.add_udas_to_model!
def add_udas_to_model! uda_hash, type=nil, model=Models::TaskModel uda_hash.each do |attr, val| val.each do |k, v| type = Helpers.determine_type(v) if type.nil? model.attribute attr, type end end end
ruby
def add_udas_to_model! uda_hash, type=nil, model=Models::TaskModel uda_hash.each do |attr, val| val.each do |k, v| type = Helpers.determine_type(v) if type.nil? model.attribute attr, type end end end
[ "def", "add_udas_to_model!", "uda_hash", ",", "type", "=", "nil", ",", "model", "=", "Models", "::", "TaskModel", "uda_hash", ".", "each", "do", "|", "attr", ",", "val", "|", "val", ".", "each", "do", "|", "k", ",", "v", "|", "type", "=", "Helpers", ".", "determine_type", "(", "v", ")", "if", "type", ".", "nil?", "model", ".", "attribute", "attr", ",", "type", "end", "end", "end" ]
Add new found udas to our internal TaskModel @param uda_hash [Hash{Symbol=>Hash}] @param type [Class, nil] @param model [Models::TaskModel, Class] @api protected
[ "Add", "new", "found", "udas", "to", "our", "internal", "TaskModel" ]
c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c
https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/controller.rb#L325-L332
train
dropofwill/rtasklib
lib/rtasklib/controller.rb
Rtasklib.Controller.get_uda_names
def get_uda_names Execute.task_popen3(*@override_a, "_udas") do |i, o, e, t| return o.read.each_line.map { |l| l.chomp } end end
ruby
def get_uda_names Execute.task_popen3(*@override_a, "_udas") do |i, o, e, t| return o.read.each_line.map { |l| l.chomp } end end
[ "def", "get_uda_names", "Execute", ".", "task_popen3", "(", "*", "@override_a", ",", "\"_udas\"", ")", "do", "|", "i", ",", "o", ",", "e", ",", "t", "|", "return", "o", ".", "read", ".", "each_line", ".", "map", "{", "|", "l", "|", "l", ".", "chomp", "}", "end", "end" ]
Retrieve an array of the uda names @return [Array<String>] @api public
[ "Retrieve", "an", "array", "of", "the", "uda", "names" ]
c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c
https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/controller.rb#L339-L343
train
dropofwill/rtasklib
lib/rtasklib/controller.rb
Rtasklib.Controller.sync!
def sync! Execute.task_popen3(*override_a, "sync") do |i, o, e, t| return t.value end end
ruby
def sync! Execute.task_popen3(*override_a, "sync") do |i, o, e, t| return t.value end end
[ "def", "sync!", "Execute", ".", "task_popen3", "(", "*", "override_a", ",", "\"sync\"", ")", "do", "|", "i", ",", "o", ",", "e", ",", "t", "|", "return", "t", ".", "value", "end", "end" ]
Sync the local TaskWarrior database changes to the remote databases. Remotes need to be configured in the .taskrc. @example # make some local changes with add!, modify!, or the like tw.sync! @return [Process::Status] the exit status of the thread @api public
[ "Sync", "the", "local", "TaskWarrior", "database", "changes", "to", "the", "remote", "databases", ".", "Remotes", "need", "to", "be", "configured", "in", "the", ".", "taskrc", "." ]
c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c
https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/controller.rb#L388-L392
train
isabanin/mercurial-ruby
lib/mercurial-ruby/manifest.rb
Mercurial.Manifest.contents
def contents(revision=nil, cmd_options={}) revision ||= 'tip' hg(manifest_cmd(revision), cmd_options).tap do |res| if RUBY_VERSION >= '1.9.1' res.force_encoding('utf-8') end end end
ruby
def contents(revision=nil, cmd_options={}) revision ||= 'tip' hg(manifest_cmd(revision), cmd_options).tap do |res| if RUBY_VERSION >= '1.9.1' res.force_encoding('utf-8') end end end
[ "def", "contents", "(", "revision", "=", "nil", ",", "cmd_options", "=", "{", "}", ")", "revision", "||=", "'tip'", "hg", "(", "manifest_cmd", "(", "revision", ")", ",", "cmd_options", ")", ".", "tap", "do", "|", "res", "|", "if", "RUBY_VERSION", ">=", "'1.9.1'", "res", ".", "force_encoding", "(", "'utf-8'", ")", "end", "end", "end" ]
Returns contents of the manifest as a String at a specified revision. Latest version of the manifest is used if +revision+ is ommitted. === Example: repository.manifest.contents
[ "Returns", "contents", "of", "the", "manifest", "as", "a", "String", "at", "a", "specified", "revision", ".", "Latest", "version", "of", "the", "manifest", "is", "used", "if", "+", "revision", "+", "is", "ommitted", "." ]
d7cc2d3bfeaa7564f6ea8d622fbddd92ca5a3d0a
https://github.com/isabanin/mercurial-ruby/blob/d7cc2d3bfeaa7564f6ea8d622fbddd92ca5a3d0a/lib/mercurial-ruby/manifest.rb#L27-L34
train
imanel/odt2html
lib/odt2html/analyze_styles.rb
ODT2HTML.AnalyzeStyles.process_normal_style_attr
def process_normal_style_attr( selector, property, value ) if (@style_info[selector] == nil) then @style_info[selector] = DeclarationBlock.new( ) @style_info[selector].push Declaration.new(property, value) else found = @style_info[selector].find { |obj| obj.property == property } if (found != nil) then found.value = value else @style_info[selector].push Declaration.new(property, value) end end end
ruby
def process_normal_style_attr( selector, property, value ) if (@style_info[selector] == nil) then @style_info[selector] = DeclarationBlock.new( ) @style_info[selector].push Declaration.new(property, value) else found = @style_info[selector].find { |obj| obj.property == property } if (found != nil) then found.value = value else @style_info[selector].push Declaration.new(property, value) end end end
[ "def", "process_normal_style_attr", "(", "selector", ",", "property", ",", "value", ")", "if", "(", "@style_info", "[", "selector", "]", "==", "nil", ")", "then", "@style_info", "[", "selector", "]", "=", "DeclarationBlock", ".", "new", "(", ")", "@style_info", "[", "selector", "]", ".", "push", "Declaration", ".", "new", "(", "property", ",", "value", ")", "else", "found", "=", "@style_info", "[", "selector", "]", ".", "find", "{", "|", "obj", "|", "obj", ".", "property", "==", "property", "}", "if", "(", "found", "!=", "nil", ")", "then", "found", ".", "value", "=", "value", "else", "@style_info", "[", "selector", "]", ".", "push", "Declaration", ".", "new", "(", "property", ",", "value", ")", "end", "end", "end" ]
If the style hasn't been registered yet, create a new array with the style property and value. If the style has been registered, and the property name is a duplicate, supplant the old property value with the new one. If the style has been registered, and the property is a new one, push the property and value onto the array.
[ "If", "the", "style", "hasn", "t", "been", "registered", "yet", "create", "a", "new", "array", "with", "the", "style", "property", "and", "value", "." ]
ae155289a9290adef55a5eddfa7c9bfe8eeb7a34
https://github.com/imanel/odt2html/blob/ae155289a9290adef55a5eddfa7c9bfe8eeb7a34/lib/odt2html/analyze_styles.rb#L142-L155
train
joelanders/r6502
lib/r6502/assembler.rb
R6502.Assembler.asm_instr
def asm_instr(instr) command = extract_command(instr) param = extract_param(instr) # Branch instructions always in relative # mode. No other instructions use this mode. # Relative mode and zero-page mode look the # same to addr_mode(), so we need to handle # this here. if [:bpl, :bmi, :bvc, :bvs, :bcc, :bcs, :bne, :beq]. include?(command) mode = :rel else mode = addr_mode(param) end bytes = [] bytes << opcode(command, mode) # If implied mode, it's a 1-byte instruction. if [:imp].include?(mode) return bytes end # Handle label or address / immediate value if param =~ /\$/ # non-labels always have a $ # Extract hex number from param string. number = /[0-9a-f]{1,4}/.match(param)[0].to_i(16) else # Store a dummy value and record this location # to be updated in 2nd pass. defer_value(@pc + 1, param) number = mode == :rel ? 0xff : 0xffff end # These instructions take 1 byte. if [:imm, :zp, :zpx, :zpy, :indx, :indy, :rel].include?(mode) (number <= 0xff) || (raise "#{command}'s number too big") return bytes << number # These instructions take 2 bytes. elsif [:abs, :absx, :absy, :ind].include?(mode) (number <= 0xffff) || (raise 'number too big') bytes << (number & 0xff) # least-sig. byte bytes << (number >> 8) # most-sig. byte end end
ruby
def asm_instr(instr) command = extract_command(instr) param = extract_param(instr) # Branch instructions always in relative # mode. No other instructions use this mode. # Relative mode and zero-page mode look the # same to addr_mode(), so we need to handle # this here. if [:bpl, :bmi, :bvc, :bvs, :bcc, :bcs, :bne, :beq]. include?(command) mode = :rel else mode = addr_mode(param) end bytes = [] bytes << opcode(command, mode) # If implied mode, it's a 1-byte instruction. if [:imp].include?(mode) return bytes end # Handle label or address / immediate value if param =~ /\$/ # non-labels always have a $ # Extract hex number from param string. number = /[0-9a-f]{1,4}/.match(param)[0].to_i(16) else # Store a dummy value and record this location # to be updated in 2nd pass. defer_value(@pc + 1, param) number = mode == :rel ? 0xff : 0xffff end # These instructions take 1 byte. if [:imm, :zp, :zpx, :zpy, :indx, :indy, :rel].include?(mode) (number <= 0xff) || (raise "#{command}'s number too big") return bytes << number # These instructions take 2 bytes. elsif [:abs, :absx, :absy, :ind].include?(mode) (number <= 0xffff) || (raise 'number too big') bytes << (number & 0xff) # least-sig. byte bytes << (number >> 8) # most-sig. byte end end
[ "def", "asm_instr", "(", "instr", ")", "command", "=", "extract_command", "(", "instr", ")", "param", "=", "extract_param", "(", "instr", ")", "if", "[", ":bpl", ",", ":bmi", ",", ":bvc", ",", ":bvs", ",", ":bcc", ",", ":bcs", ",", ":bne", ",", ":beq", "]", ".", "include?", "(", "command", ")", "mode", "=", ":rel", "else", "mode", "=", "addr_mode", "(", "param", ")", "end", "bytes", "=", "[", "]", "bytes", "<<", "opcode", "(", "command", ",", "mode", ")", "if", "[", ":imp", "]", ".", "include?", "(", "mode", ")", "return", "bytes", "end", "if", "param", "=~", "/", "\\$", "/", "number", "=", "/", "/", ".", "match", "(", "param", ")", "[", "0", "]", ".", "to_i", "(", "16", ")", "else", "defer_value", "(", "@pc", "+", "1", ",", "param", ")", "number", "=", "mode", "==", ":rel", "?", "0xff", ":", "0xffff", "end", "if", "[", ":imm", ",", ":zp", ",", ":zpx", ",", ":zpy", ",", ":indx", ",", ":indy", ",", ":rel", "]", ".", "include?", "(", "mode", ")", "(", "number", "<=", "0xff", ")", "||", "(", "raise", "\"#{command}'s number too big\"", ")", "return", "bytes", "<<", "number", "elsif", "[", ":abs", ",", ":absx", ",", ":absy", ",", ":ind", "]", ".", "include?", "(", "mode", ")", "(", "number", "<=", "0xffff", ")", "||", "(", "raise", "'number too big'", ")", "bytes", "<<", "(", "number", "&", "0xff", ")", "bytes", "<<", "(", "number", ">>", "8", ")", "end", "end" ]
This method got nasty.
[ "This", "method", "got", "nasty", "." ]
1b3a73b439edc3a0742976ada7d987c041e126b5
https://github.com/joelanders/r6502/blob/1b3a73b439edc3a0742976ada7d987c041e126b5/lib/r6502/assembler.rb#L75-L122
train
cotag/em-promise
lib/em-promise/q.rb
EventMachine.Q.all
def all(*promises) deferred = Q.defer counter = promises.length results = [] if counter > 0 promises.each_index do |index| ref(promises[index]).then(proc {|result| if results[index].nil? results[index] = result counter -= 1 deferred.resolve(results) if counter <= 0 end result }, proc {|reason| if results[index].nil? deferred.reject(reason) end reason }) end else deferred.resolve(results) end return deferred.promise end
ruby
def all(*promises) deferred = Q.defer counter = promises.length results = [] if counter > 0 promises.each_index do |index| ref(promises[index]).then(proc {|result| if results[index].nil? results[index] = result counter -= 1 deferred.resolve(results) if counter <= 0 end result }, proc {|reason| if results[index].nil? deferred.reject(reason) end reason }) end else deferred.resolve(results) end return deferred.promise end
[ "def", "all", "(", "*", "promises", ")", "deferred", "=", "Q", ".", "defer", "counter", "=", "promises", ".", "length", "results", "=", "[", "]", "if", "counter", ">", "0", "promises", ".", "each_index", "do", "|", "index", "|", "ref", "(", "promises", "[", "index", "]", ")", ".", "then", "(", "proc", "{", "|", "result", "|", "if", "results", "[", "index", "]", ".", "nil?", "results", "[", "index", "]", "=", "result", "counter", "-=", "1", "deferred", ".", "resolve", "(", "results", ")", "if", "counter", "<=", "0", "end", "result", "}", ",", "proc", "{", "|", "reason", "|", "if", "results", "[", "index", "]", ".", "nil?", "deferred", ".", "reject", "(", "reason", ")", "end", "reason", "}", ")", "end", "else", "deferred", ".", "resolve", "(", "results", ")", "end", "return", "deferred", ".", "promise", "end" ]
Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. @param [*Promise] Promises a number of promises that will be combined into a single promise @return [Promise] Returns a single promise that will be resolved with an array of values, each value corresponding to the promise at the same index in the `promises` array. If any of the promises is resolved with a rejection, this resulting promise will be resolved with the same rejection.
[ "Combines", "multiple", "promises", "into", "a", "single", "promise", "that", "is", "resolved", "when", "all", "of", "the", "input", "promises", "are", "resolved", "." ]
b2a7bcb97f085a4271b2b79ade02f8f3442bbdf9
https://github.com/cotag/em-promise/blob/b2a7bcb97f085a4271b2b79ade02f8f3442bbdf9/lib/em-promise/q.rb#L230-L256
train
topfunky/google-checkout
lib/google-checkout/cart.rb
GoogleCheckout.Cart.shipping_cost_xml
def shipping_cost_xml xml = Builder::XmlMarkup.new if @flat_rate_shipping xml.price(:currency => currency) { xml.text! @flat_rate_shipping[:price].to_s } else xml.price(:currency => @currency) { xml.text! shipping_cost.to_s } end end
ruby
def shipping_cost_xml xml = Builder::XmlMarkup.new if @flat_rate_shipping xml.price(:currency => currency) { xml.text! @flat_rate_shipping[:price].to_s } else xml.price(:currency => @currency) { xml.text! shipping_cost.to_s } end end
[ "def", "shipping_cost_xml", "xml", "=", "Builder", "::", "XmlMarkup", ".", "new", "if", "@flat_rate_shipping", "xml", ".", "price", "(", ":currency", "=>", "currency", ")", "{", "xml", ".", "text!", "@flat_rate_shipping", "[", ":price", "]", ".", "to_s", "}", "else", "xml", ".", "price", "(", ":currency", "=>", "@currency", ")", "{", "xml", ".", "text!", "shipping_cost", ".", "to_s", "}", "end", "end" ]
Generates the XML for the shipping cost, conditional on @flat_rate_shipping being set.
[ "Generates", "the", "XML", "for", "the", "shipping", "cost", "conditional", "on" ]
66089cef799bd40f3ba4370f01f1b8dc10f92115
https://github.com/topfunky/google-checkout/blob/66089cef799bd40f3ba4370f01f1b8dc10f92115/lib/google-checkout/cart.rb#L267-L278
train
topfunky/google-checkout
lib/google-checkout/cart.rb
GoogleCheckout.Cart.shipping_cost
def shipping_cost currency = 'USD' shipping = @contents.inject(0) { |total,item| total + item[:regular_shipping].to_i }.to_s end
ruby
def shipping_cost currency = 'USD' shipping = @contents.inject(0) { |total,item| total + item[:regular_shipping].to_i }.to_s end
[ "def", "shipping_cost", "currency", "=", "'USD'", "shipping", "=", "@contents", ".", "inject", "(", "0", ")", "{", "|", "total", ",", "item", "|", "total", "+", "item", "[", ":regular_shipping", "]", ".", "to_i", "}", ".", "to_s", "end" ]
Returns the shipping cost for the contents of the cart.
[ "Returns", "the", "shipping", "cost", "for", "the", "contents", "of", "the", "cart", "." ]
66089cef799bd40f3ba4370f01f1b8dc10f92115
https://github.com/topfunky/google-checkout/blob/66089cef799bd40f3ba4370f01f1b8dc10f92115/lib/google-checkout/cart.rb#L281-L286
train
topfunky/google-checkout
lib/google-checkout/cart.rb
GoogleCheckout.Cart.currency
def currency # Mixing currency not allowed; this # library can't convert between # currencies. currencies = @contents.map { |item| item[:currency] }.uniq || "USD" case currencies.count when 0 "USD" when 1 currencies.first else raise RuntimeError.new("Mixing currency not allowed") end end
ruby
def currency # Mixing currency not allowed; this # library can't convert between # currencies. currencies = @contents.map { |item| item[:currency] }.uniq || "USD" case currencies.count when 0 "USD" when 1 currencies.first else raise RuntimeError.new("Mixing currency not allowed") end end
[ "def", "currency", "currencies", "=", "@contents", ".", "map", "{", "|", "item", "|", "item", "[", ":currency", "]", "}", ".", "uniq", "||", "\"USD\"", "case", "currencies", ".", "count", "when", "0", "\"USD\"", "when", "1", "currencies", ".", "first", "else", "raise", "RuntimeError", ".", "new", "(", "\"Mixing currency not allowed\"", ")", "end", "end" ]
Returns the currency for the cart. Mixing currency not allowed; this library can't convert between currencies.
[ "Returns", "the", "currency", "for", "the", "cart", ".", "Mixing", "currency", "not", "allowed", ";", "this", "library", "can", "t", "convert", "between", "currencies", "." ]
66089cef799bd40f3ba4370f01f1b8dc10f92115
https://github.com/topfunky/google-checkout/blob/66089cef799bd40f3ba4370f01f1b8dc10f92115/lib/google-checkout/cart.rb#L290-L305
train
topfunky/google-checkout
lib/google-checkout/cart.rb
GoogleCheckout.Cart.signature
def signature @xml or to_xml digest = OpenSSL::Digest::Digest.new('sha1') OpenSSL::HMAC.digest(digest, @merchant_key, @xml) end
ruby
def signature @xml or to_xml digest = OpenSSL::Digest::Digest.new('sha1') OpenSSL::HMAC.digest(digest, @merchant_key, @xml) end
[ "def", "signature", "@xml", "or", "to_xml", "digest", "=", "OpenSSL", "::", "Digest", "::", "Digest", ".", "new", "(", "'sha1'", ")", "OpenSSL", "::", "HMAC", ".", "digest", "(", "digest", ",", "@merchant_key", ",", "@xml", ")", "end" ]
Returns the signature for the cart XML.
[ "Returns", "the", "signature", "for", "the", "cart", "XML", "." ]
66089cef799bd40f3ba4370f01f1b8dc10f92115
https://github.com/topfunky/google-checkout/blob/66089cef799bd40f3ba4370f01f1b8dc10f92115/lib/google-checkout/cart.rb#L308-L313
train
topfunky/google-checkout
lib/google-checkout/cart.rb
GoogleCheckout.Cart.checkout_button
def checkout_button(button_opts = {}) @xml or to_xml burl = button_url(button_opts) html = Builder::XmlMarkup.new(:indent => 2) html.form({ :action => submit_url, :style => 'border: 0;', :id => 'BB_BuyButtonForm', :method => 'post', :name => 'BB_BuyButtonForm' }) do html.input({ :name => 'cart', :type => 'hidden', :value => Base64.encode64(@xml).gsub("\n", '') }) html.input({ :name => 'signature', :type => 'hidden', :value => Base64.encode64(signature).gsub("\n", '') }) html.input({ :alt => 'Google Checkout', :style => "width: auto;", :src => button_url(button_opts), :type => 'image' }) end end
ruby
def checkout_button(button_opts = {}) @xml or to_xml burl = button_url(button_opts) html = Builder::XmlMarkup.new(:indent => 2) html.form({ :action => submit_url, :style => 'border: 0;', :id => 'BB_BuyButtonForm', :method => 'post', :name => 'BB_BuyButtonForm' }) do html.input({ :name => 'cart', :type => 'hidden', :value => Base64.encode64(@xml).gsub("\n", '') }) html.input({ :name => 'signature', :type => 'hidden', :value => Base64.encode64(signature).gsub("\n", '') }) html.input({ :alt => 'Google Checkout', :style => "width: auto;", :src => button_url(button_opts), :type => 'image' }) end end
[ "def", "checkout_button", "(", "button_opts", "=", "{", "}", ")", "@xml", "or", "to_xml", "burl", "=", "button_url", "(", "button_opts", ")", "html", "=", "Builder", "::", "XmlMarkup", ".", "new", "(", ":indent", "=>", "2", ")", "html", ".", "form", "(", "{", ":action", "=>", "submit_url", ",", ":style", "=>", "'border: 0;'", ",", ":id", "=>", "'BB_BuyButtonForm'", ",", ":method", "=>", "'post'", ",", ":name", "=>", "'BB_BuyButtonForm'", "}", ")", "do", "html", ".", "input", "(", "{", ":name", "=>", "'cart'", ",", ":type", "=>", "'hidden'", ",", ":value", "=>", "Base64", ".", "encode64", "(", "@xml", ")", ".", "gsub", "(", "\"\\n\"", ",", "''", ")", "}", ")", "html", ".", "input", "(", "{", ":name", "=>", "'signature'", ",", ":type", "=>", "'hidden'", ",", ":value", "=>", "Base64", ".", "encode64", "(", "signature", ")", ".", "gsub", "(", "\"\\n\"", ",", "''", ")", "}", ")", "html", ".", "input", "(", "{", ":alt", "=>", "'Google Checkout'", ",", ":style", "=>", "\"width: auto;\"", ",", ":src", "=>", "button_url", "(", "button_opts", ")", ",", ":type", "=>", "'image'", "}", ")", "end", "end" ]
Returns HTML for a checkout form for buying all the items in the cart.
[ "Returns", "HTML", "for", "a", "checkout", "form", "for", "buying", "all", "the", "items", "in", "the", "cart", "." ]
66089cef799bd40f3ba4370f01f1b8dc10f92115
https://github.com/topfunky/google-checkout/blob/66089cef799bd40f3ba4370f01f1b8dc10f92115/lib/google-checkout/cart.rb#L317-L345
train
drKreso/cube
lib/cube/cube.rb
XMLA.Cube.table
def table if (header.size == 1 && y_size == 0) cell_data[0] else (0...y_axe.size).reduce(header) do |result, j| result << ( y_axe[j] + (0...x_size).map { |i| "#{cell_data[i + j]}" }) end end end
ruby
def table if (header.size == 1 && y_size == 0) cell_data[0] else (0...y_axe.size).reduce(header) do |result, j| result << ( y_axe[j] + (0...x_size).map { |i| "#{cell_data[i + j]}" }) end end end
[ "def", "table", "if", "(", "header", ".", "size", "==", "1", "&&", "y_size", "==", "0", ")", "cell_data", "[", "0", "]", "else", "(", "0", "...", "y_axe", ".", "size", ")", ".", "reduce", "(", "header", ")", "do", "|", "result", ",", "j", "|", "result", "<<", "(", "y_axe", "[", "j", "]", "+", "(", "0", "...", "x_size", ")", ".", "map", "{", "|", "i", "|", "\"#{cell_data[i + j]}\"", "}", ")", "end", "end", "end" ]
header and rows
[ "header", "and", "rows" ]
9955eac4fd21a69771bc74525ba17acf81b996e8
https://github.com/drKreso/cube/blob/9955eac4fd21a69771bc74525ba17acf81b996e8/lib/cube/cube.rb#L33-L41
train
phatworx/rails_paginate
lib/rails_paginate/collection.rb
RailsPaginate.Collection.load_result
def load_result if array_or_relation.is_a? Array result = array_or_relation[offset..(offset + per_page - 1)] else result = array_or_relation.limit(per_page).offset(offset).all end self.replace result.nil? ? [] : result end
ruby
def load_result if array_or_relation.is_a? Array result = array_or_relation[offset..(offset + per_page - 1)] else result = array_or_relation.limit(per_page).offset(offset).all end self.replace result.nil? ? [] : result end
[ "def", "load_result", "if", "array_or_relation", ".", "is_a?", "Array", "result", "=", "array_or_relation", "[", "offset", "..", "(", "offset", "+", "per_page", "-", "1", ")", "]", "else", "result", "=", "array_or_relation", ".", "limit", "(", "per_page", ")", ".", "offset", "(", "offset", ")", ".", "all", "end", "self", ".", "replace", "result", ".", "nil?", "?", "[", "]", ":", "result", "end" ]
load result from input array_or_relation to internal array
[ "load", "result", "from", "input", "array_or_relation", "to", "internal", "array" ]
ae8cbc12030853b236dc2cbf6ede8700fb835771
https://github.com/phatworx/rails_paginate/blob/ae8cbc12030853b236dc2cbf6ede8700fb835771/lib/rails_paginate/collection.rb#L43-L51
train
sosedoff/munin-ruby
lib/munin-ruby/connection.rb
Munin.Connection.open
def open begin begin with_timeout do @socket = TCPSocket.new(@host, @port) @socket.sync = true welcome = @socket.gets unless welcome =~ /^# munin node at/ raise Munin::AccessDenied end @connected = true end rescue Timeout::Error raise Munin::ConnectionError, "Timed out talking to #{@host}" end rescue Errno::ETIMEDOUT, Errno::ECONNREFUSED, Errno::ECONNRESET => ex raise Munin::ConnectionError, ex.message rescue EOFError raise Munin::AccessDenied rescue Exception => ex raise Munin::ConnectionError, ex.message end end
ruby
def open begin begin with_timeout do @socket = TCPSocket.new(@host, @port) @socket.sync = true welcome = @socket.gets unless welcome =~ /^# munin node at/ raise Munin::AccessDenied end @connected = true end rescue Timeout::Error raise Munin::ConnectionError, "Timed out talking to #{@host}" end rescue Errno::ETIMEDOUT, Errno::ECONNREFUSED, Errno::ECONNRESET => ex raise Munin::ConnectionError, ex.message rescue EOFError raise Munin::AccessDenied rescue Exception => ex raise Munin::ConnectionError, ex.message end end
[ "def", "open", "begin", "begin", "with_timeout", "do", "@socket", "=", "TCPSocket", ".", "new", "(", "@host", ",", "@port", ")", "@socket", ".", "sync", "=", "true", "welcome", "=", "@socket", ".", "gets", "unless", "welcome", "=~", "/", "/", "raise", "Munin", "::", "AccessDenied", "end", "@connected", "=", "true", "end", "rescue", "Timeout", "::", "Error", "raise", "Munin", "::", "ConnectionError", ",", "\"Timed out talking to #{@host}\"", "end", "rescue", "Errno", "::", "ETIMEDOUT", ",", "Errno", "::", "ECONNREFUSED", ",", "Errno", "::", "ECONNRESET", "=>", "ex", "raise", "Munin", "::", "ConnectionError", ",", "ex", ".", "message", "rescue", "EOFError", "raise", "Munin", "::", "AccessDenied", "rescue", "Exception", "=>", "ex", "raise", "Munin", "::", "ConnectionError", ",", "ex", ".", "message", "end", "end" ]
Establish connection to the server
[ "Establish", "connection", "to", "the", "server" ]
28f65b0abb88fc40e234b6af327094992504be6a
https://github.com/sosedoff/munin-ruby/blob/28f65b0abb88fc40e234b6af327094992504be6a/lib/munin-ruby/connection.rb#L33-L55
train
sosedoff/munin-ruby
lib/munin-ruby/connection.rb
Munin.Connection.send_data
def send_data(str) if !connected? if [email protected]? && @reconnect == false raise Munin::ConnectionError, "Not connected." else open end end begin with_timeout { @socket.puts("#{str.strip}\n") } rescue Timeout::Error raise Munin::ConnectionError, "Timed out on #{@host} trying to send." end end
ruby
def send_data(str) if !connected? if [email protected]? && @reconnect == false raise Munin::ConnectionError, "Not connected." else open end end begin with_timeout { @socket.puts("#{str.strip}\n") } rescue Timeout::Error raise Munin::ConnectionError, "Timed out on #{@host} trying to send." end end
[ "def", "send_data", "(", "str", ")", "if", "!", "connected?", "if", "!", "@socket", ".", "nil?", "&&", "@reconnect", "==", "false", "raise", "Munin", "::", "ConnectionError", ",", "\"Not connected.\"", "else", "open", "end", "end", "begin", "with_timeout", "{", "@socket", ".", "puts", "(", "\"#{str.strip}\\n\"", ")", "}", "rescue", "Timeout", "::", "Error", "raise", "Munin", "::", "ConnectionError", ",", "\"Timed out on #{@host} trying to send.\"", "end", "end" ]
Send a string of data followed by a newline symbol
[ "Send", "a", "string", "of", "data", "followed", "by", "a", "newline", "symbol" ]
28f65b0abb88fc40e234b6af327094992504be6a
https://github.com/sosedoff/munin-ruby/blob/28f65b0abb88fc40e234b6af327094992504be6a/lib/munin-ruby/connection.rb#L70-L84
train
sosedoff/munin-ruby
lib/munin-ruby/connection.rb
Munin.Connection.read_line
def read_line begin with_timeout { @socket.gets.to_s.strip } rescue Errno::ETIMEDOUT, Errno::ECONNREFUSED, Errno::ECONNRESET, EOFError => ex raise Munin::ConnectionError, ex.message rescue Timeout::Error raise Munin::ConnectionError, "Timed out reading from #{@host}." end end
ruby
def read_line begin with_timeout { @socket.gets.to_s.strip } rescue Errno::ETIMEDOUT, Errno::ECONNREFUSED, Errno::ECONNRESET, EOFError => ex raise Munin::ConnectionError, ex.message rescue Timeout::Error raise Munin::ConnectionError, "Timed out reading from #{@host}." end end
[ "def", "read_line", "begin", "with_timeout", "{", "@socket", ".", "gets", ".", "to_s", ".", "strip", "}", "rescue", "Errno", "::", "ETIMEDOUT", ",", "Errno", "::", "ECONNREFUSED", ",", "Errno", "::", "ECONNRESET", ",", "EOFError", "=>", "ex", "raise", "Munin", "::", "ConnectionError", ",", "ex", ".", "message", "rescue", "Timeout", "::", "Error", "raise", "Munin", "::", "ConnectionError", ",", "\"Timed out reading from #{@host}.\"", "end", "end" ]
Reads a single line from socket
[ "Reads", "a", "single", "line", "from", "socket" ]
28f65b0abb88fc40e234b6af327094992504be6a
https://github.com/sosedoff/munin-ruby/blob/28f65b0abb88fc40e234b6af327094992504be6a/lib/munin-ruby/connection.rb#L88-L96
train
sosedoff/munin-ruby
lib/munin-ruby/connection.rb
Munin.Connection.read_packet
def read_packet begin with_timeout do lines = [] while(str = @socket.readline.to_s) do break if str.strip == '.' lines << str.strip end parse_error(lines) lines end rescue Errno::ETIMEDOUT, Errno::ECONNREFUSED, Errno::ECONNRESET, EOFError => ex raise Munin::ConnectionError, ex.message rescue Timeout::Error raise Munin::ConnectionError, "Timed out reading from #{@host}." end end
ruby
def read_packet begin with_timeout do lines = [] while(str = @socket.readline.to_s) do break if str.strip == '.' lines << str.strip end parse_error(lines) lines end rescue Errno::ETIMEDOUT, Errno::ECONNREFUSED, Errno::ECONNRESET, EOFError => ex raise Munin::ConnectionError, ex.message rescue Timeout::Error raise Munin::ConnectionError, "Timed out reading from #{@host}." end end
[ "def", "read_packet", "begin", "with_timeout", "do", "lines", "=", "[", "]", "while", "(", "str", "=", "@socket", ".", "readline", ".", "to_s", ")", "do", "break", "if", "str", ".", "strip", "==", "'.'", "lines", "<<", "str", ".", "strip", "end", "parse_error", "(", "lines", ")", "lines", "end", "rescue", "Errno", "::", "ETIMEDOUT", ",", "Errno", "::", "ECONNREFUSED", ",", "Errno", "::", "ECONNRESET", ",", "EOFError", "=>", "ex", "raise", "Munin", "::", "ConnectionError", ",", "ex", ".", "message", "rescue", "Timeout", "::", "Error", "raise", "Munin", "::", "ConnectionError", ",", "\"Timed out reading from #{@host}.\"", "end", "end" ]
Reads a packet of data until '.' reached
[ "Reads", "a", "packet", "of", "data", "until", ".", "reached" ]
28f65b0abb88fc40e234b6af327094992504be6a
https://github.com/sosedoff/munin-ruby/blob/28f65b0abb88fc40e234b6af327094992504be6a/lib/munin-ruby/connection.rb#L100-L116
train
sosedoff/munin-ruby
lib/munin-ruby/connection.rb
Munin.Connection.with_timeout
def with_timeout(time=@options[:timeout]) raise ArgumentError, "Block required" if !block_given? if Munin::TIMEOUT_CLASS.respond_to?(:timeout_after) Munin::TIMEOUT_CLASS.timeout_after(time) { yield } else Munin::TIMEOUT_CLASS.timeout(time) { yield } end end
ruby
def with_timeout(time=@options[:timeout]) raise ArgumentError, "Block required" if !block_given? if Munin::TIMEOUT_CLASS.respond_to?(:timeout_after) Munin::TIMEOUT_CLASS.timeout_after(time) { yield } else Munin::TIMEOUT_CLASS.timeout(time) { yield } end end
[ "def", "with_timeout", "(", "time", "=", "@options", "[", ":timeout", "]", ")", "raise", "ArgumentError", ",", "\"Block required\"", "if", "!", "block_given?", "if", "Munin", "::", "TIMEOUT_CLASS", ".", "respond_to?", "(", ":timeout_after", ")", "Munin", "::", "TIMEOUT_CLASS", ".", "timeout_after", "(", "time", ")", "{", "yield", "}", "else", "Munin", "::", "TIMEOUT_CLASS", ".", "timeout", "(", "time", ")", "{", "yield", "}", "end", "end" ]
Execute operation with timeout @param [Block] block Block to execute
[ "Execute", "operation", "with", "timeout" ]
28f65b0abb88fc40e234b6af327094992504be6a
https://github.com/sosedoff/munin-ruby/blob/28f65b0abb88fc40e234b6af327094992504be6a/lib/munin-ruby/connection.rb#L122-L129
train
davesloan/restful_api_authentication
lib/restful_api_authentication/checker.rb
RestfulApiAuthentication.Checker.authorized?
def authorized?(options = {}) raise "Configuration values not found. Please run rails g restful_api_authentication:install to generate a config file." if @@header_timestamp.nil? || @@header_signature.nil? || @@header_api_key.nil? || @@time_window.nil? || @@disabled_message.nil? return_val = false if headers_have_values? if in_time_window? if test_hash.downcase == @http_headers[@@header_signature].downcase if is_disabled? @errors << @@disabled_message return false end if options[:require_master] == true if is_master? return_val = true else @errors << "client does not have the required permissions" end else return_val = true end else @errors << "signature is invalid" end else @errors << "request is outside the required time window of #{@@time_window.to_s} minutes" end else @errors << "one or more required headers is missing" end if return_val == false && @errors.count == 0 @errors << "authentication failed" end return_val end
ruby
def authorized?(options = {}) raise "Configuration values not found. Please run rails g restful_api_authentication:install to generate a config file." if @@header_timestamp.nil? || @@header_signature.nil? || @@header_api_key.nil? || @@time_window.nil? || @@disabled_message.nil? return_val = false if headers_have_values? if in_time_window? if test_hash.downcase == @http_headers[@@header_signature].downcase if is_disabled? @errors << @@disabled_message return false end if options[:require_master] == true if is_master? return_val = true else @errors << "client does not have the required permissions" end else return_val = true end else @errors << "signature is invalid" end else @errors << "request is outside the required time window of #{@@time_window.to_s} minutes" end else @errors << "one or more required headers is missing" end if return_val == false && @errors.count == 0 @errors << "authentication failed" end return_val end
[ "def", "authorized?", "(", "options", "=", "{", "}", ")", "raise", "\"Configuration values not found. Please run rails g restful_api_authentication:install to generate a config file.\"", "if", "@@header_timestamp", ".", "nil?", "||", "@@header_signature", ".", "nil?", "||", "@@header_api_key", ".", "nil?", "||", "@@time_window", ".", "nil?", "||", "@@disabled_message", ".", "nil?", "return_val", "=", "false", "if", "headers_have_values?", "if", "in_time_window?", "if", "test_hash", ".", "downcase", "==", "@http_headers", "[", "@@header_signature", "]", ".", "downcase", "if", "is_disabled?", "@errors", "<<", "@@disabled_message", "return", "false", "end", "if", "options", "[", ":require_master", "]", "==", "true", "if", "is_master?", "return_val", "=", "true", "else", "@errors", "<<", "\"client does not have the required permissions\"", "end", "else", "return_val", "=", "true", "end", "else", "@errors", "<<", "\"signature is invalid\"", "end", "else", "@errors", "<<", "\"request is outside the required time window of #{@@time_window.to_s} minutes\"", "end", "else", "@errors", "<<", "\"one or more required headers is missing\"", "end", "if", "return_val", "==", "false", "&&", "@errors", ".", "count", "==", "0", "@errors", "<<", "\"authentication failed\"", "end", "return_val", "end" ]
Checks if the current request passes authorization
[ "Checks", "if", "the", "current", "request", "passes", "authorization" ]
1612e3adf815fd54502f2b08c2f222c11dbbf432
https://github.com/davesloan/restful_api_authentication/blob/1612e3adf815fd54502f2b08c2f222c11dbbf432/lib/restful_api_authentication/checker.rb#L37-L69
train
davesloan/restful_api_authentication
lib/restful_api_authentication/checker.rb
RestfulApiAuthentication.Checker.is_disabled?
def is_disabled? client = RestClient.where(:api_key => @http_headers[@@header_api_key]).first return true if client.nil? return false if client.is_disabled.nil? client.is_disabled end
ruby
def is_disabled? client = RestClient.where(:api_key => @http_headers[@@header_api_key]).first return true if client.nil? return false if client.is_disabled.nil? client.is_disabled end
[ "def", "is_disabled?", "client", "=", "RestClient", ".", "where", "(", ":api_key", "=>", "@http_headers", "[", "@@header_api_key", "]", ")", ".", "first", "return", "true", "if", "client", ".", "nil?", "return", "false", "if", "client", ".", "is_disabled", ".", "nil?", "client", ".", "is_disabled", "end" ]
determines if a RestClient is disabled or not
[ "determines", "if", "a", "RestClient", "is", "disabled", "or", "not" ]
1612e3adf815fd54502f2b08c2f222c11dbbf432
https://github.com/davesloan/restful_api_authentication/blob/1612e3adf815fd54502f2b08c2f222c11dbbf432/lib/restful_api_authentication/checker.rb#L74-L79
train
davesloan/restful_api_authentication
lib/restful_api_authentication/checker.rb
RestfulApiAuthentication.Checker.in_time_window?
def in_time_window? @@time_window = 4 if @@time_window < 4 minutes = (@@time_window / 2).floor ts = Chronic.parse @http_headers[@@header_timestamp] before = Time.now.utc - 60*minutes after = Time.now.utc + 60*minutes if ts.nil? @errors << "timestamp was in an invalid format; should be YYYY-MM-DD HH:MM:SS UTC" return false end ts > before && ts < after end
ruby
def in_time_window? @@time_window = 4 if @@time_window < 4 minutes = (@@time_window / 2).floor ts = Chronic.parse @http_headers[@@header_timestamp] before = Time.now.utc - 60*minutes after = Time.now.utc + 60*minutes if ts.nil? @errors << "timestamp was in an invalid format; should be YYYY-MM-DD HH:MM:SS UTC" return false end ts > before && ts < after end
[ "def", "in_time_window?", "@@time_window", "=", "4", "if", "@@time_window", "<", "4", "minutes", "=", "(", "@@time_window", "/", "2", ")", ".", "floor", "ts", "=", "Chronic", ".", "parse", "@http_headers", "[", "@@header_timestamp", "]", "before", "=", "Time", ".", "now", ".", "utc", "-", "60", "*", "minutes", "after", "=", "Time", ".", "now", ".", "utc", "+", "60", "*", "minutes", "if", "ts", ".", "nil?", "@errors", "<<", "\"timestamp was in an invalid format; should be YYYY-MM-DD HH:MM:SS UTC\"", "return", "false", "end", "ts", ">", "before", "&&", "ts", "<", "after", "end" ]
determines if given timestamp is within a specific window of minutes
[ "determines", "if", "given", "timestamp", "is", "within", "a", "specific", "window", "of", "minutes" ]
1612e3adf815fd54502f2b08c2f222c11dbbf432
https://github.com/davesloan/restful_api_authentication/blob/1612e3adf815fd54502f2b08c2f222c11dbbf432/lib/restful_api_authentication/checker.rb#L88-L99
train
davesloan/restful_api_authentication
lib/restful_api_authentication/checker.rb
RestfulApiAuthentication.Checker.str_to_hash
def str_to_hash client = RestClient.where(:api_key => @http_headers[@@header_api_key]).first if client.nil? @errors << "client is not registered" end client.nil? ? "" : client.secret + @request_uri.gsub( /\?.*/, "" ) + @http_headers[@@header_timestamp] end
ruby
def str_to_hash client = RestClient.where(:api_key => @http_headers[@@header_api_key]).first if client.nil? @errors << "client is not registered" end client.nil? ? "" : client.secret + @request_uri.gsub( /\?.*/, "" ) + @http_headers[@@header_timestamp] end
[ "def", "str_to_hash", "client", "=", "RestClient", ".", "where", "(", ":api_key", "=>", "@http_headers", "[", "@@header_api_key", "]", ")", ".", "first", "if", "client", ".", "nil?", "@errors", "<<", "\"client is not registered\"", "end", "client", ".", "nil?", "?", "\"\"", ":", "client", ".", "secret", "+", "@request_uri", ".", "gsub", "(", "/", "\\?", "/", ",", "\"\"", ")", "+", "@http_headers", "[", "@@header_timestamp", "]", "end" ]
generates the string that is hashed to produce the signature
[ "generates", "the", "string", "that", "is", "hashed", "to", "produce", "the", "signature" ]
1612e3adf815fd54502f2b08c2f222c11dbbf432
https://github.com/davesloan/restful_api_authentication/blob/1612e3adf815fd54502f2b08c2f222c11dbbf432/lib/restful_api_authentication/checker.rb#L107-L113
train
unipept/unipept-cli
lib/formatters.rb
Unipept.Formatter.format
def format(data, fasta_mapper, first) data = integrate_fasta_headers(data, fasta_mapper) if fasta_mapper convert(data, first) end
ruby
def format(data, fasta_mapper, first) data = integrate_fasta_headers(data, fasta_mapper) if fasta_mapper convert(data, first) end
[ "def", "format", "(", "data", ",", "fasta_mapper", ",", "first", ")", "data", "=", "integrate_fasta_headers", "(", "data", ",", "fasta_mapper", ")", "if", "fasta_mapper", "convert", "(", "data", ",", "first", ")", "end" ]
Converts the given input data and corresponding fasta headers to another format. @param [Array] data The data we wish to convert @param [Array<Array<String>>] fasta_mapper Optional mapping between input data and corresponding fasta header. The data is represented as a list containing tuples where the first element is the fasta header and second element is the input data @param [Boolean] Is this the first output batch? @return [String] The converted input data
[ "Converts", "the", "given", "input", "data", "and", "corresponding", "fasta", "headers", "to", "another", "format", "." ]
183779bd1dffcd01ed623685c789160153b78681
https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/formatters.rb#L89-L92
train
unipept/unipept-cli
lib/formatters.rb
Unipept.Formatter.integrate_fasta_headers
def integrate_fasta_headers(data, fasta_mapper) data_dict = group_by_first_key(data) data = fasta_mapper.map do |header, key| result = data_dict[key] unless result.nil? result = result.map do |row| copy = { fasta_header: header } copy.merge(row) end end result end data.compact.flatten(1) end
ruby
def integrate_fasta_headers(data, fasta_mapper) data_dict = group_by_first_key(data) data = fasta_mapper.map do |header, key| result = data_dict[key] unless result.nil? result = result.map do |row| copy = { fasta_header: header } copy.merge(row) end end result end data.compact.flatten(1) end
[ "def", "integrate_fasta_headers", "(", "data", ",", "fasta_mapper", ")", "data_dict", "=", "group_by_first_key", "(", "data", ")", "data", "=", "fasta_mapper", ".", "map", "do", "|", "header", ",", "key", "|", "result", "=", "data_dict", "[", "key", "]", "unless", "result", ".", "nil?", "result", "=", "result", ".", "map", "do", "|", "row", "|", "copy", "=", "{", "fasta_header", ":", "header", "}", "copy", ".", "merge", "(", "row", ")", "end", "end", "result", "end", "data", ".", "compact", ".", "flatten", "(", "1", ")", "end" ]
Integrates the fasta headers into the data object
[ "Integrates", "the", "fasta", "headers", "into", "the", "data", "object" ]
183779bd1dffcd01ed623685c789160153b78681
https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/formatters.rb#L106-L119
train
unipept/unipept-cli
lib/formatters.rb
Unipept.JSONFormatter.convert
def convert(data, first) output = data.map(&:to_json).join(',') first ? output : ',' + output end
ruby
def convert(data, first) output = data.map(&:to_json).join(',') first ? output : ',' + output end
[ "def", "convert", "(", "data", ",", "first", ")", "output", "=", "data", ".", "map", "(", "&", ":to_json", ")", ".", "join", "(", "','", ")", "first", "?", "output", ":", "','", "+", "output", "end" ]
Converts the given input data to the JSON format. @param [Array] data The data we wish to convert @param [Boolean] Is this the first output batch? @return [String] The converted input data in the JSON format
[ "Converts", "the", "given", "input", "data", "to", "the", "JSON", "format", "." ]
183779bd1dffcd01ed623685c789160153b78681
https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/formatters.rb#L157-L160
train
unipept/unipept-cli
lib/formatters.rb
Unipept.CSVFormatter.header
def header(data, fasta_mapper = nil) CSV.generate do |csv| first = data.first keys = fasta_mapper ? ['fasta_header'] : [] csv << (keys + first.keys).map(&:to_s) if first end end
ruby
def header(data, fasta_mapper = nil) CSV.generate do |csv| first = data.first keys = fasta_mapper ? ['fasta_header'] : [] csv << (keys + first.keys).map(&:to_s) if first end end
[ "def", "header", "(", "data", ",", "fasta_mapper", "=", "nil", ")", "CSV", ".", "generate", "do", "|", "csv", "|", "first", "=", "data", ".", "first", "keys", "=", "fasta_mapper", "?", "[", "'fasta_header'", "]", ":", "[", "]", "csv", "<<", "(", "keys", "+", "first", ".", "keys", ")", ".", "map", "(", "&", ":to_s", ")", "if", "first", "end", "end" ]
Returns the header row for the given data and fasta_mapper. This row contains all the keys of the first element of the data, preceded by 'fasta_header' if a fasta_mapper is given. @param [Array] data The data that we will use to extract the keys from. @param [Array<Array<String>>] fasta_mapper Optional mapping between input data and corresponding fasta header. The data is represented as a list containing tuples where the first element is the fasta header and second element is the input data If a fasta_mapper is given, the output will be preceded with 'fasta_header'. @return [String] The header row
[ "Returns", "the", "header", "row", "for", "the", "given", "data", "and", "fasta_mapper", ".", "This", "row", "contains", "all", "the", "keys", "of", "the", "first", "element", "of", "the", "data", "preceded", "by", "fasta_header", "if", "a", "fasta_mapper", "is", "given", "." ]
183779bd1dffcd01ed623685c789160153b78681
https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/formatters.rb#L185-L191
train
unipept/unipept-cli
lib/formatters.rb
Unipept.CSVFormatter.convert
def convert(data, _first) CSV.generate do |csv| data.each do |o| csv << o.values.map { |v| v == '' ? nil : v } end end end
ruby
def convert(data, _first) CSV.generate do |csv| data.each do |o| csv << o.values.map { |v| v == '' ? nil : v } end end end
[ "def", "convert", "(", "data", ",", "_first", ")", "CSV", ".", "generate", "do", "|", "csv", "|", "data", ".", "each", "do", "|", "o", "|", "csv", "<<", "o", ".", "values", ".", "map", "{", "|", "v", "|", "v", "==", "''", "?", "nil", ":", "v", "}", "end", "end", "end" ]
Converts the given input data to the CSV format. @param [Array] data The data we wish to convert @param [Boolean] Is this the first output batch? @return [String] The converted input data in the CSV format
[ "Converts", "the", "given", "input", "data", "to", "the", "CSV", "format", "." ]
183779bd1dffcd01ed623685c789160153b78681
https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/formatters.rb#L204-L210
train
unipept/unipept-cli
lib/formatters.rb
Unipept.BlastFormatter.convert
def convert(data, _first) data .reject { |o| o['refseq_protein_ids'].empty? } .map do |o| "#{o['peptide']}\tref|#{o['refseq_protein_ids']}|\t100\t10\t0\t0\t0\t10\t0\t10\t1e-100\t100\n" end .join end
ruby
def convert(data, _first) data .reject { |o| o['refseq_protein_ids'].empty? } .map do |o| "#{o['peptide']}\tref|#{o['refseq_protein_ids']}|\t100\t10\t0\t0\t0\t10\t0\t10\t1e-100\t100\n" end .join end
[ "def", "convert", "(", "data", ",", "_first", ")", "data", ".", "reject", "{", "|", "o", "|", "o", "[", "'refseq_protein_ids'", "]", ".", "empty?", "}", ".", "map", "do", "|", "o", "|", "\"#{o['peptide']}\\tref|#{o['refseq_protein_ids']}|\\t100\\t10\\t0\\t0\\t0\\t10\\t0\\t10\\t1e-100\\t100\\n\"", "end", ".", "join", "end" ]
Converts the given input data to the Blast format. @param [Array] data The data we wish to convert @param [Boolean] Is this the first output batch? @return [String] The converted input data in the Blast format
[ "Converts", "the", "given", "input", "data", "to", "the", "Blast", "format", "." ]
183779bd1dffcd01ed623685c789160153b78681
https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/formatters.rb#L289-L296
train
code-and-effect/effective_roles
app/models/concerns/acts_as_role_restricted.rb
ActsAsRoleRestricted.ClassMethods.for_role
def for_role(*roles) sql = with_role_sql(roles) || '' sql += ' OR ' if sql.present? sql += "(#{self.table_name}.roles_mask = 0) OR (#{self.table_name}.roles_mask IS NULL)" where(sql) end
ruby
def for_role(*roles) sql = with_role_sql(roles) || '' sql += ' OR ' if sql.present? sql += "(#{self.table_name}.roles_mask = 0) OR (#{self.table_name}.roles_mask IS NULL)" where(sql) end
[ "def", "for_role", "(", "*", "roles", ")", "sql", "=", "with_role_sql", "(", "roles", ")", "||", "''", "sql", "+=", "' OR '", "if", "sql", ".", "present?", "sql", "+=", "\"(#{self.table_name}.roles_mask = 0) OR (#{self.table_name}.roles_mask IS NULL)\"", "where", "(", "sql", ")", "end" ]
Returns all records which have been assigned any of the given roles, as well as any record with no role assigned
[ "Returns", "all", "records", "which", "have", "been", "assigned", "any", "of", "the", "given", "roles", "as", "well", "as", "any", "record", "with", "no", "role", "assigned" ]
334605ae4573f742bedc3e29b0eb4d4245a4cff9
https://github.com/code-and-effect/effective_roles/blob/334605ae4573f742bedc3e29b0eb4d4245a4cff9/app/models/concerns/acts_as_role_restricted.rb#L39-L44
train
zertico/softlayer
lib/softlayer/client.rb
Softlayer.Client.auth_params
def auth_params return {} unless Softlayer.configuration auth_hash = { authenticate: { 'username' => Softlayer.configuration.username, 'apiKey' => Softlayer.configuration.api_key } } auth_hash.merge!({ "clientLegacySession" => { "userId" => Softlayer.configuration.impersonate_user, "authToken" => Softlayer.configuration.impersonate_token } }) if Softlayer.impersonating? auth_hash end
ruby
def auth_params return {} unless Softlayer.configuration auth_hash = { authenticate: { 'username' => Softlayer.configuration.username, 'apiKey' => Softlayer.configuration.api_key } } auth_hash.merge!({ "clientLegacySession" => { "userId" => Softlayer.configuration.impersonate_user, "authToken" => Softlayer.configuration.impersonate_token } }) if Softlayer.impersonating? auth_hash end
[ "def", "auth_params", "return", "{", "}", "unless", "Softlayer", ".", "configuration", "auth_hash", "=", "{", "authenticate", ":", "{", "'username'", "=>", "Softlayer", ".", "configuration", ".", "username", ",", "'apiKey'", "=>", "Softlayer", ".", "configuration", ".", "api_key", "}", "}", "auth_hash", ".", "merge!", "(", "{", "\"clientLegacySession\"", "=>", "{", "\"userId\"", "=>", "Softlayer", ".", "configuration", ".", "impersonate_user", ",", "\"authToken\"", "=>", "Softlayer", ".", "configuration", ".", "impersonate_token", "}", "}", ")", "if", "Softlayer", ".", "impersonating?", "auth_hash", "end" ]
Authorization hash to use with all SOAP requests
[ "Authorization", "hash", "to", "use", "with", "all", "SOAP", "requests" ]
77c2e73f22cebd73359ff108342ed1927a063428
https://github.com/zertico/softlayer/blob/77c2e73f22cebd73359ff108342ed1927a063428/lib/softlayer/client.rb#L23-L39
train
samvera-labs/geo_works
app/models/concerns/geo_works/image_file_behavior.rb
GeoWorks.ImageFileBehavior.image_work
def image_work parents.select do |parent| parent.class.included_modules.include?(::GeoWorks::ImageWorkBehavior) end.to_a end
ruby
def image_work parents.select do |parent| parent.class.included_modules.include?(::GeoWorks::ImageWorkBehavior) end.to_a end
[ "def", "image_work", "parents", ".", "select", "do", "|", "parent", "|", "parent", ".", "class", ".", "included_modules", ".", "include?", "(", "::", "GeoWorks", "::", "ImageWorkBehavior", ")", "end", ".", "to_a", "end" ]
Retrieve the Image Work of which this Object is a member @return [GeoWorks::ImageWork]
[ "Retrieve", "the", "Image", "Work", "of", "which", "this", "Object", "is", "a", "member" ]
df1eff35fd01469a623fafeb9d71b44fd6160ca8
https://github.com/samvera-labs/geo_works/blob/df1eff35fd01469a623fafeb9d71b44fd6160ca8/app/models/concerns/geo_works/image_file_behavior.rb#L8-L12
train
phatworx/rails_paginate
lib/rails_paginate/pagers/slider.rb
RailsPaginate::Pagers.Slider.visible_pages
def visible_pages visible = [] last_inserted = 0 splited = false (1..pages).each do |page| # insert if visible? page visible << page last_inserted = page splited = false else # need splitter if not splited and outer > 0 and last_inserted < page visible << nil splited = true end end end visible end
ruby
def visible_pages visible = [] last_inserted = 0 splited = false (1..pages).each do |page| # insert if visible? page visible << page last_inserted = page splited = false else # need splitter if not splited and outer > 0 and last_inserted < page visible << nil splited = true end end end visible end
[ "def", "visible_pages", "visible", "=", "[", "]", "last_inserted", "=", "0", "splited", "=", "false", "(", "1", "..", "pages", ")", ".", "each", "do", "|", "page", "|", "if", "visible?", "page", "visible", "<<", "page", "last_inserted", "=", "page", "splited", "=", "false", "else", "if", "not", "splited", "and", "outer", ">", "0", "and", "last_inserted", "<", "page", "visible", "<<", "nil", "splited", "=", "true", "end", "end", "end", "visible", "end" ]
build array with all visible pages
[ "build", "array", "with", "all", "visible", "pages" ]
ae8cbc12030853b236dc2cbf6ede8700fb835771
https://github.com/phatworx/rails_paginate/blob/ae8cbc12030853b236dc2cbf6ede8700fb835771/lib/rails_paginate/pagers/slider.rb#L14-L33
train
phatworx/rails_paginate
lib/rails_paginate/pagers/slider.rb
RailsPaginate::Pagers.Slider.visible?
def visible?(page) # outer if outer > 0 return true if outer >= page return true if (pages - outer) < page end # current page return true if current_page == page # inner return true if inner_range.include? page false end
ruby
def visible?(page) # outer if outer > 0 return true if outer >= page return true if (pages - outer) < page end # current page return true if current_page == page # inner return true if inner_range.include? page false end
[ "def", "visible?", "(", "page", ")", "if", "outer", ">", "0", "return", "true", "if", "outer", ">=", "page", "return", "true", "if", "(", "pages", "-", "outer", ")", "<", "page", "end", "return", "true", "if", "current_page", "==", "page", "return", "true", "if", "inner_range", ".", "include?", "page", "false", "end" ]
looks should this page visible
[ "looks", "should", "this", "page", "visible" ]
ae8cbc12030853b236dc2cbf6ede8700fb835771
https://github.com/phatworx/rails_paginate/blob/ae8cbc12030853b236dc2cbf6ede8700fb835771/lib/rails_paginate/pagers/slider.rb#L41-L55
train
Mik-die/mongoid_globalize
lib/mongoid_globalize/class_methods.rb
Mongoid::Globalize.ClassMethods.required_attributes
def required_attributes validators.map{ |v| v.attributes if v.is_a?(Mongoid::Validations::PresenceValidator) }.flatten.compact end
ruby
def required_attributes validators.map{ |v| v.attributes if v.is_a?(Mongoid::Validations::PresenceValidator) }.flatten.compact end
[ "def", "required_attributes", "validators", ".", "map", "{", "|", "v", "|", "v", ".", "attributes", "if", "v", ".", "is_a?", "(", "Mongoid", "::", "Validations", "::", "PresenceValidator", ")", "}", ".", "flatten", ".", "compact", "end" ]
Return Array of attribute names with presence validations
[ "Return", "Array", "of", "attribute", "names", "with", "presence", "validations" ]
458105154574950aed98119fd54ffaae4e1a55ee
https://github.com/Mik-die/mongoid_globalize/blob/458105154574950aed98119fd54ffaae4e1a55ee/lib/mongoid_globalize/class_methods.rb#L47-L49
train
Mik-die/mongoid_globalize
lib/mongoid_globalize/methods.rb
Mongoid::Globalize.Methods.translated_attributes
def translated_attributes @translated_attributes ||= translated_attribute_names.inject({}) do |attrs, name| attrs.merge(name.to_s => translation.send(name)) end end
ruby
def translated_attributes @translated_attributes ||= translated_attribute_names.inject({}) do |attrs, name| attrs.merge(name.to_s => translation.send(name)) end end
[ "def", "translated_attributes", "@translated_attributes", "||=", "translated_attribute_names", ".", "inject", "(", "{", "}", ")", "do", "|", "attrs", ",", "name", "|", "attrs", ".", "merge", "(", "name", ".", "to_s", "=>", "translation", ".", "send", "(", "name", ")", ")", "end", "end" ]
Returns translations for current locale. Is used for initial mixing into @attributes hash. Actual translations are in @translated_attributes hash. Return Hash
[ "Returns", "translations", "for", "current", "locale", ".", "Is", "used", "for", "initial", "mixing", "into" ]
458105154574950aed98119fd54ffaae4e1a55ee
https://github.com/Mik-die/mongoid_globalize/blob/458105154574950aed98119fd54ffaae4e1a55ee/lib/mongoid_globalize/methods.rb#L90-L94
train
Mik-die/mongoid_globalize
lib/mongoid_globalize/methods.rb
Mongoid::Globalize.Methods.translation_for
def translation_for(locale) @translation_caches ||= {} # Need to temporary switch of merging, because #translations uses # #attributes method too, to avoid stack level too deep error. @stop_merging_translated_attributes = true unless @translation_caches[locale] _translation = translations.find_by_locale(locale) _translation ||= translations.build(:locale => locale) @translation_caches[locale] = _translation end @stop_merging_translated_attributes = false @translation_caches[locale] end
ruby
def translation_for(locale) @translation_caches ||= {} # Need to temporary switch of merging, because #translations uses # #attributes method too, to avoid stack level too deep error. @stop_merging_translated_attributes = true unless @translation_caches[locale] _translation = translations.find_by_locale(locale) _translation ||= translations.build(:locale => locale) @translation_caches[locale] = _translation end @stop_merging_translated_attributes = false @translation_caches[locale] end
[ "def", "translation_for", "(", "locale", ")", "@translation_caches", "||=", "{", "}", "@stop_merging_translated_attributes", "=", "true", "unless", "@translation_caches", "[", "locale", "]", "_translation", "=", "translations", ".", "find_by_locale", "(", "locale", ")", "_translation", "||=", "translations", ".", "build", "(", ":locale", "=>", "locale", ")", "@translation_caches", "[", "locale", "]", "=", "_translation", "end", "@stop_merging_translated_attributes", "=", "false", "@translation_caches", "[", "locale", "]", "end" ]
Returns instance of Translation for given locale. Param String or Symbol
[ "Returns", "instance", "of", "Translation", "for", "given", "locale", ".", "Param", "String", "or", "Symbol" ]
458105154574950aed98119fd54ffaae4e1a55ee
https://github.com/Mik-die/mongoid_globalize/blob/458105154574950aed98119fd54ffaae4e1a55ee/lib/mongoid_globalize/methods.rb#L146-L158
train
Mik-die/mongoid_globalize
lib/mongoid_globalize/methods.rb
Mongoid::Globalize.Methods.used_locales
def used_locales locales = globalize.stash.keys.concat(globalize.stash.keys).concat(translations.translated_locales) locales.uniq! locales end
ruby
def used_locales locales = globalize.stash.keys.concat(globalize.stash.keys).concat(translations.translated_locales) locales.uniq! locales end
[ "def", "used_locales", "locales", "=", "globalize", ".", "stash", ".", "keys", ".", "concat", "(", "globalize", ".", "stash", ".", "keys", ")", ".", "concat", "(", "translations", ".", "translated_locales", ")", "locales", ".", "uniq!", "locales", "end" ]
Return Array with locales, used for translation of this document
[ "Return", "Array", "with", "locales", "used", "for", "translation", "of", "this", "document" ]
458105154574950aed98119fd54ffaae4e1a55ee
https://github.com/Mik-die/mongoid_globalize/blob/458105154574950aed98119fd54ffaae4e1a55ee/lib/mongoid_globalize/methods.rb#L172-L176
train
Mik-die/mongoid_globalize
lib/mongoid_globalize/methods.rb
Mongoid::Globalize.Methods.prepare_translations!
def prepare_translations! @stop_merging_translated_attributes = true translated_attribute_names.each do |name| @attributes.delete name.to_s @changed_attributes.delete name.to_s if @changed_attributes end globalize.prepare_translations! end
ruby
def prepare_translations! @stop_merging_translated_attributes = true translated_attribute_names.each do |name| @attributes.delete name.to_s @changed_attributes.delete name.to_s if @changed_attributes end globalize.prepare_translations! end
[ "def", "prepare_translations!", "@stop_merging_translated_attributes", "=", "true", "translated_attribute_names", ".", "each", "do", "|", "name", "|", "@attributes", ".", "delete", "name", ".", "to_s", "@changed_attributes", ".", "delete", "name", ".", "to_s", "if", "@changed_attributes", "end", "globalize", ".", "prepare_translations!", "end" ]
Before save callback. Cleans @attributes hash from translated attributes and prepares them for persisting.
[ "Before", "save", "callback", ".", "Cleans" ]
458105154574950aed98119fd54ffaae4e1a55ee
https://github.com/Mik-die/mongoid_globalize/blob/458105154574950aed98119fd54ffaae4e1a55ee/lib/mongoid_globalize/methods.rb#L180-L187
train
sportngin/ical_importer
lib/ical_importer/single_event_builder.rb
IcalImporter.SingleEventBuilder.build
def build # handle recuring events @local_event.tap do |le| if @event.rrule.present? @rrule = @event.rrule.first # only support recurrence on one schedule # set out new event's basic rucurring properties le.attributes = recurrence_attributes set_date_exclusion frequency_set else # make sure we remove this if it changed le.attributes = non_recurrence_attributes end end end
ruby
def build # handle recuring events @local_event.tap do |le| if @event.rrule.present? @rrule = @event.rrule.first # only support recurrence on one schedule # set out new event's basic rucurring properties le.attributes = recurrence_attributes set_date_exclusion frequency_set else # make sure we remove this if it changed le.attributes = non_recurrence_attributes end end end
[ "def", "build", "@local_event", ".", "tap", "do", "|", "le", "|", "if", "@event", ".", "rrule", ".", "present?", "@rrule", "=", "@event", ".", "rrule", ".", "first", "le", ".", "attributes", "=", "recurrence_attributes", "set_date_exclusion", "frequency_set", "else", "le", ".", "attributes", "=", "non_recurrence_attributes", "end", "end", "end" ]
Get single-occurrence events built and get a lits of recurrence events, these must be build last
[ "Get", "single", "-", "occurrence", "events", "built", "and", "get", "a", "lits", "of", "recurrence", "events", "these", "must", "be", "build", "last" ]
4a78590e973c3f1695797fd7d5f5b0cd93a86c52
https://github.com/sportngin/ical_importer/blob/4a78590e973c3f1695797fd7d5f5b0cd93a86c52/lib/ical_importer/single_event_builder.rb#L12-L26
train
r7kamura/jsonism
lib/jsonism/definer.rb
Jsonism.Definer.define_methods_into
def define_methods_into(client) links.each do |link| @client.define_singleton_method(link.method_signature) do |params = {}, headers = {}| Request.call(client: client, headers: headers, link: link, params: params) end end end
ruby
def define_methods_into(client) links.each do |link| @client.define_singleton_method(link.method_signature) do |params = {}, headers = {}| Request.call(client: client, headers: headers, link: link, params: params) end end end
[ "def", "define_methods_into", "(", "client", ")", "links", ".", "each", "do", "|", "link", "|", "@client", ".", "define_singleton_method", "(", "link", ".", "method_signature", ")", "do", "|", "params", "=", "{", "}", ",", "headers", "=", "{", "}", "|", "Request", ".", "call", "(", "client", ":", "client", ",", "headers", ":", "headers", ",", "link", ":", "link", ",", "params", ":", "params", ")", "end", "end", "end" ]
Defines methods into client @example client.list_app client.info_app(id: 1)
[ "Defines", "methods", "into", "client" ]
4e3bcc5413aed3cfadb5f9b23e6e5dc2eb4d8790
https://github.com/r7kamura/jsonism/blob/4e3bcc5413aed3cfadb5f9b23e6e5dc2eb4d8790/lib/jsonism/definer.rb#L79-L85
train
samvera-labs/geo_works
app/helpers/geo_works/bounding_box_helper.rb
GeoWorks.BoundingBoxHelper.bbox
def bbox(property) markup = '' markup << %(<div id='bbox'></div>) markup << bbox_display_inputs markup << bbox_script_tag(property) markup.html_safe end
ruby
def bbox(property) markup = '' markup << %(<div id='bbox'></div>) markup << bbox_display_inputs markup << bbox_script_tag(property) markup.html_safe end
[ "def", "bbox", "(", "property", ")", "markup", "=", "''", "markup", "<<", "%(<div id='bbox'></div>)", "markup", "<<", "bbox_display_inputs", "markup", "<<", "bbox_script_tag", "(", "property", ")", "markup", ".", "html_safe", "end" ]
Builds HTML string for bounding box selector tool. Calls boundingBoxSelector javascript function and passes the id of the location input element that it binds to. @param [Symbol] name of property that holds bounding box string @return[String]
[ "Builds", "HTML", "string", "for", "bounding", "box", "selector", "tool", ".", "Calls", "boundingBoxSelector", "javascript", "function", "and", "passes", "the", "id", "of", "the", "location", "input", "element", "that", "it", "binds", "to", "." ]
df1eff35fd01469a623fafeb9d71b44fd6160ca8
https://github.com/samvera-labs/geo_works/blob/df1eff35fd01469a623fafeb9d71b44fd6160ca8/app/helpers/geo_works/bounding_box_helper.rb#L9-L15
train
blinkist/grantinee
lib/grantinee/cli.rb
Grantinee.CLI.process_database_param
def process_database_param unless @options[:config] || Grantinee.configuration.configured? Grantinee::Engine.detect_active_record_connection! unless Grantinee.configuration.configured? raise "No configuration file found. Please use the -c option"\ " to pass a configuration file." end end require options[:config] rescue StandardError, LoadError => error puts error exit end
ruby
def process_database_param unless @options[:config] || Grantinee.configuration.configured? Grantinee::Engine.detect_active_record_connection! unless Grantinee.configuration.configured? raise "No configuration file found. Please use the -c option"\ " to pass a configuration file." end end require options[:config] rescue StandardError, LoadError => error puts error exit end
[ "def", "process_database_param", "unless", "@options", "[", ":config", "]", "||", "Grantinee", ".", "configuration", ".", "configured?", "Grantinee", "::", "Engine", ".", "detect_active_record_connection!", "unless", "Grantinee", ".", "configuration", ".", "configured?", "raise", "\"No configuration file found. Please use the -c option\"", "\" to pass a configuration file.\"", "end", "end", "require", "options", "[", ":config", "]", "rescue", "StandardError", ",", "LoadError", "=>", "error", "puts", "error", "exit", "end" ]
Database configuration file
[ "Database", "configuration", "file" ]
ba0c9a8ccaf377c2484c814d39359f01f7e56ded
https://github.com/blinkist/grantinee/blob/ba0c9a8ccaf377c2484c814d39359f01f7e56ded/lib/grantinee/cli.rb#L110-L124
train
blinkist/grantinee
lib/grantinee/cli.rb
Grantinee.CLI.process_verbosity_param
def process_verbosity_param return unless @options[:verbose] log_levels = %w[debug info warn error fatal unknown] @logger.level = log_levels.index(@options[:verbose]) end
ruby
def process_verbosity_param return unless @options[:verbose] log_levels = %w[debug info warn error fatal unknown] @logger.level = log_levels.index(@options[:verbose]) end
[ "def", "process_verbosity_param", "return", "unless", "@options", "[", ":verbose", "]", "log_levels", "=", "%w[", "debug", "info", "warn", "error", "fatal", "unknown", "]", "@logger", ".", "level", "=", "log_levels", ".", "index", "(", "@options", "[", ":verbose", "]", ")", "end" ]
Explicit verbose mode, overrides configuration value
[ "Explicit", "verbose", "mode", "overrides", "configuration", "value" ]
ba0c9a8ccaf377c2484c814d39359f01f7e56ded
https://github.com/blinkist/grantinee/blob/ba0c9a8ccaf377c2484c814d39359f01f7e56ded/lib/grantinee/cli.rb#L132-L136
train
IntrepidPursuits/danger-shellcheck
lib/shellcheck/plugin.rb
Danger.DangerShellcheck.report
def report(file_path) raise 'ShellCheck summary file not found' unless File.file?(file_path) shellcheck_summary = JSON.parse(File.read(file_path), symbolize_names: true) run_summary(shellcheck_summary) end
ruby
def report(file_path) raise 'ShellCheck summary file not found' unless File.file?(file_path) shellcheck_summary = JSON.parse(File.read(file_path), symbolize_names: true) run_summary(shellcheck_summary) end
[ "def", "report", "(", "file_path", ")", "raise", "'ShellCheck summary file not found'", "unless", "File", ".", "file?", "(", "file_path", ")", "shellcheck_summary", "=", "JSON", ".", "parse", "(", "File", ".", "read", "(", "file_path", ")", ",", "symbolize_names", ":", "true", ")", "run_summary", "(", "shellcheck_summary", ")", "end" ]
Reads a file with JSON ShellCheck summary and reports it. @param [String] file_path Path for ShellCheck summary in JSON format. @return [void]
[ "Reads", "a", "file", "with", "JSON", "ShellCheck", "summary", "and", "reports", "it", "." ]
b6e02ed40cde8036721c8692c2e27d858b85fb1b
https://github.com/IntrepidPursuits/danger-shellcheck/blob/b6e02ed40cde8036721c8692c2e27d858b85fb1b/lib/shellcheck/plugin.rb#L41-L45
train
IntrepidPursuits/danger-shellcheck
lib/shellcheck/plugin.rb
Danger.DangerShellcheck.parse_files
def parse_files(shellcheck_summary) shellcheck_summary.each do |element| file = element[:file] @files.add(file) level = element[:level] message = format_violation(file, element) if level == 'error' @error_count += 1 fail(message, sticky: false) else if level == 'warning' @warning_count += 1 elsif level == 'info' @info_count += 1 else @style_count += 1 end warn(message, sticky: false) end end end
ruby
def parse_files(shellcheck_summary) shellcheck_summary.each do |element| file = element[:file] @files.add(file) level = element[:level] message = format_violation(file, element) if level == 'error' @error_count += 1 fail(message, sticky: false) else if level == 'warning' @warning_count += 1 elsif level == 'info' @info_count += 1 else @style_count += 1 end warn(message, sticky: false) end end end
[ "def", "parse_files", "(", "shellcheck_summary", ")", "shellcheck_summary", ".", "each", "do", "|", "element", "|", "file", "=", "element", "[", ":file", "]", "@files", ".", "add", "(", "file", ")", "level", "=", "element", "[", ":level", "]", "message", "=", "format_violation", "(", "file", ",", "element", ")", "if", "level", "==", "'error'", "@error_count", "+=", "1", "fail", "(", "message", ",", "sticky", ":", "false", ")", "else", "if", "level", "==", "'warning'", "@warning_count", "+=", "1", "elsif", "level", "==", "'info'", "@info_count", "+=", "1", "else", "@style_count", "+=", "1", "end", "warn", "(", "message", ",", "sticky", ":", "false", ")", "end", "end", "end" ]
A method that takes the ShellCheck summary and parses any violations found
[ "A", "method", "that", "takes", "the", "ShellCheck", "summary", "and", "parses", "any", "violations", "found" ]
b6e02ed40cde8036721c8692c2e27d858b85fb1b
https://github.com/IntrepidPursuits/danger-shellcheck/blob/b6e02ed40cde8036721c8692c2e27d858b85fb1b/lib/shellcheck/plugin.rb#L68-L90
train
samvera-labs/geo_works
spec/support/features/session_helpers.rb
Features.SessionHelpers.sign_up_with
def sign_up_with(email, password) Capybara.exact = true visit new_user_registration_path fill_in 'Email', with: email fill_in 'Password', with: password fill_in 'Password confirmation', with: password click_button 'Sign up' end
ruby
def sign_up_with(email, password) Capybara.exact = true visit new_user_registration_path fill_in 'Email', with: email fill_in 'Password', with: password fill_in 'Password confirmation', with: password click_button 'Sign up' end
[ "def", "sign_up_with", "(", "email", ",", "password", ")", "Capybara", ".", "exact", "=", "true", "visit", "new_user_registration_path", "fill_in", "'Email'", ",", "with", ":", "email", "fill_in", "'Password'", ",", "with", ":", "password", "fill_in", "'Password confirmation'", ",", "with", ":", "password", "click_button", "'Sign up'", "end" ]
Poltergeist-friendly sign-up Use this in feature tests
[ "Poltergeist", "-", "friendly", "sign", "-", "up", "Use", "this", "in", "feature", "tests" ]
df1eff35fd01469a623fafeb9d71b44fd6160ca8
https://github.com/samvera-labs/geo_works/blob/df1eff35fd01469a623fafeb9d71b44fd6160ca8/spec/support/features/session_helpers.rb#L16-L23
train
samvera-labs/geo_works
spec/support/features/session_helpers.rb
Features.SessionHelpers.sign_in
def sign_in(who = :user) user = if who.instance_of?(User) who else FactoryGirl.build(:user).tap(&:save!) end visit new_user_session_path fill_in 'Email', with: user.email fill_in 'Password', with: user.password click_button 'Log in' expect(page).not_to have_text 'Invalid email or password.' end
ruby
def sign_in(who = :user) user = if who.instance_of?(User) who else FactoryGirl.build(:user).tap(&:save!) end visit new_user_session_path fill_in 'Email', with: user.email fill_in 'Password', with: user.password click_button 'Log in' expect(page).not_to have_text 'Invalid email or password.' end
[ "def", "sign_in", "(", "who", "=", ":user", ")", "user", "=", "if", "who", ".", "instance_of?", "(", "User", ")", "who", "else", "FactoryGirl", ".", "build", "(", ":user", ")", ".", "tap", "(", "&", ":save!", ")", "end", "visit", "new_user_session_path", "fill_in", "'Email'", ",", "with", ":", "user", ".", "email", "fill_in", "'Password'", ",", "with", ":", "user", ".", "password", "click_button", "'Log in'", "expect", "(", "page", ")", ".", "not_to", "have_text", "'Invalid email or password.'", "end" ]
Poltergeist-friendly sign-in Use this in feature tests
[ "Poltergeist", "-", "friendly", "sign", "-", "in", "Use", "this", "in", "feature", "tests" ]
df1eff35fd01469a623fafeb9d71b44fd6160ca8
https://github.com/samvera-labs/geo_works/blob/df1eff35fd01469a623fafeb9d71b44fd6160ca8/spec/support/features/session_helpers.rb#L27-L38
train
couchrest/couchrest_extended_document
lib/couchrest/support/couchrest.rb
CouchRest.Database.clear_extended_doc_fresh_cache
def clear_extended_doc_fresh_cache ::CouchRest::ExtendedDocument.subclasses.each{|klass| klass.req_design_doc_refresh if klass.respond_to?(:req_design_doc_refresh)} end
ruby
def clear_extended_doc_fresh_cache ::CouchRest::ExtendedDocument.subclasses.each{|klass| klass.req_design_doc_refresh if klass.respond_to?(:req_design_doc_refresh)} end
[ "def", "clear_extended_doc_fresh_cache", "::", "CouchRest", "::", "ExtendedDocument", ".", "subclasses", ".", "each", "{", "|", "klass", "|", "klass", ".", "req_design_doc_refresh", "if", "klass", ".", "respond_to?", "(", ":req_design_doc_refresh", ")", "}", "end" ]
If the database is deleted, ensure that the design docs will be refreshed.
[ "If", "the", "database", "is", "deleted", "ensure", "that", "the", "design", "docs", "will", "be", "refreshed", "." ]
71511202ae10d3010dcf7b98fcba017cb37c76da
https://github.com/couchrest/couchrest_extended_document/blob/71511202ae10d3010dcf7b98fcba017cb37c76da/lib/couchrest/support/couchrest.rb#L13-L15
train
imanel/odt2html
lib/odt2html/analyze_content.rb
ODT2HTML.AnalyzeContent.register_style
def register_style( element ) # get namespace prefix for this element style_name = element.attribute("#{element.prefix}:style-name"); if (style_name != nil) then style_name = style_name.value.tr_s('.','_') if (@style_info[style_name] != nil) then @style_info[style_name].block_used = true end end return style_name end
ruby
def register_style( element ) # get namespace prefix for this element style_name = element.attribute("#{element.prefix}:style-name"); if (style_name != nil) then style_name = style_name.value.tr_s('.','_') if (@style_info[style_name] != nil) then @style_info[style_name].block_used = true end end return style_name end
[ "def", "register_style", "(", "element", ")", "style_name", "=", "element", ".", "attribute", "(", "\"#{element.prefix}:style-name\"", ")", ";", "if", "(", "style_name", "!=", "nil", ")", "then", "style_name", "=", "style_name", ".", "value", ".", "tr_s", "(", "'.'", ",", "'_'", ")", "if", "(", "@style_info", "[", "style_name", "]", "!=", "nil", ")", "then", "@style_info", "[", "style_name", "]", ".", "block_used", "=", "true", "end", "end", "return", "style_name", "end" ]
Return the style name for this element, with periods changed to underscores to make it valid CSS. Side effect: registers this style as "having been used" in the document
[ "Return", "the", "style", "name", "for", "this", "element", "with", "periods", "changed", "to", "underscores", "to", "make", "it", "valid", "CSS", "." ]
ae155289a9290adef55a5eddfa7c9bfe8eeb7a34
https://github.com/imanel/odt2html/blob/ae155289a9290adef55a5eddfa7c9bfe8eeb7a34/lib/odt2html/analyze_content.rb#L254-L264
train
tachyons/luis
lib/luis/result.rb
Luis.Result.entities_of_type
def entities_of_type(type) @entities.select { |entity| entity['type'] == type }.map { |entity| Entity.new entity } end
ruby
def entities_of_type(type) @entities.select { |entity| entity['type'] == type }.map { |entity| Entity.new entity } end
[ "def", "entities_of_type", "(", "type", ")", "@entities", ".", "select", "{", "|", "entity", "|", "entity", "[", "'type'", "]", "==", "type", "}", ".", "map", "{", "|", "entity", "|", "Entity", ".", "new", "entity", "}", "end" ]
Entitities with specific type
[ "Entitities", "with", "specific", "type" ]
ef22bd70a84b4a532b57c9cb57e5acdabb5baded
https://github.com/tachyons/luis/blob/ef22bd70a84b4a532b57c9cb57e5acdabb5baded/lib/luis/result.rb#L31-L33
train
yoyo0906/ruby-adb-sdklib
lib/adb_sdklib/common.rb
AdbSdkLib.Common.convert_map_to_hash
def convert_map_to_hash(object, &block) hash = Hash.new i = object.entrySet.iterator if block_given? while i.hasNext entry = i.next yield hash, entry.getKey, entry.getValue end else while i.hasNext entry = i.next hash[entry.getKey] = entry.getValue end end hash end
ruby
def convert_map_to_hash(object, &block) hash = Hash.new i = object.entrySet.iterator if block_given? while i.hasNext entry = i.next yield hash, entry.getKey, entry.getValue end else while i.hasNext entry = i.next hash[entry.getKey] = entry.getValue end end hash end
[ "def", "convert_map_to_hash", "(", "object", ",", "&", "block", ")", "hash", "=", "Hash", ".", "new", "i", "=", "object", ".", "entrySet", ".", "iterator", "if", "block_given?", "while", "i", ".", "hasNext", "entry", "=", "i", ".", "next", "yield", "hash", ",", "entry", ".", "getKey", ",", "entry", ".", "getValue", "end", "else", "while", "i", ".", "hasNext", "entry", "=", "i", ".", "next", "hash", "[", "entry", ".", "getKey", "]", "=", "entry", ".", "getValue", "end", "end", "hash", "end" ]
Converts Java Map object to Ruby Hash object.
[ "Converts", "Java", "Map", "object", "to", "Ruby", "Hash", "object", "." ]
9f8a5c88ee8e7b572600ca7919b506bfc0e8d105
https://github.com/yoyo0906/ruby-adb-sdklib/blob/9f8a5c88ee8e7b572600ca7919b506bfc0e8d105/lib/adb_sdklib/common.rb#L78-L93
train
ftomassetti/codemodels
lib/codemodels/parser.rb
CodeModels.Parser.parse_file
def parse_file(path,file_encoding=nil) file_encoding = @internal_encoding unless file_encoding code = IO.read(path,{ :encoding => file_encoding, :mode => 'rb'}) code = code.encode(@internal_encoding) artifact = FileArtifact.new(path,code) parse_artifact(artifact) end
ruby
def parse_file(path,file_encoding=nil) file_encoding = @internal_encoding unless file_encoding code = IO.read(path,{ :encoding => file_encoding, :mode => 'rb'}) code = code.encode(@internal_encoding) artifact = FileArtifact.new(path,code) parse_artifact(artifact) end
[ "def", "parse_file", "(", "path", ",", "file_encoding", "=", "nil", ")", "file_encoding", "=", "@internal_encoding", "unless", "file_encoding", "code", "=", "IO", ".", "read", "(", "path", ",", "{", ":encoding", "=>", "file_encoding", ",", ":mode", "=>", "'rb'", "}", ")", "code", "=", "code", ".", "encode", "(", "@internal_encoding", ")", "artifact", "=", "FileArtifact", ".", "new", "(", "path", ",", "code", ")", "parse_artifact", "(", "artifact", ")", "end" ]
Parse the file by producing an artifact corresponding to the file
[ "Parse", "the", "file", "by", "producing", "an", "artifact", "corresponding", "to", "the", "file" ]
fb08f1fe13dad5a20c32b59d88bc5e9f3faa60f2
https://github.com/ftomassetti/codemodels/blob/fb08f1fe13dad5a20c32b59d88bc5e9f3faa60f2/lib/codemodels/parser.rb#L29-L35
train
ftomassetti/codemodels
lib/codemodels/parser.rb
CodeModels.Parser.parse_string
def parse_string(code) code = code.encode(@internal_encoding) artifact = StringArtifact.new(code) parse_artifact(artifact) end
ruby
def parse_string(code) code = code.encode(@internal_encoding) artifact = StringArtifact.new(code) parse_artifact(artifact) end
[ "def", "parse_string", "(", "code", ")", "code", "=", "code", ".", "encode", "(", "@internal_encoding", ")", "artifact", "=", "StringArtifact", ".", "new", "(", "code", ")", "parse_artifact", "(", "artifact", ")", "end" ]
Parse the file by producing an artifact corresponding to the string
[ "Parse", "the", "file", "by", "producing", "an", "artifact", "corresponding", "to", "the", "string" ]
fb08f1fe13dad5a20c32b59d88bc5e9f3faa60f2
https://github.com/ftomassetti/codemodels/blob/fb08f1fe13dad5a20c32b59d88bc5e9f3faa60f2/lib/codemodels/parser.rb#L38-L42
train
yoyo0906/ruby-adb-sdklib
lib/adb-sdklib.rb
AdbSdkLib.Adb.devices
def devices devices = @adb.devices.map { |d| serial = d.serial_number (@devices.has_key?(serial) && same_jobject?(@devices[serial].jobject, d)) \ ? @devices[serial] : Device.new(d) } @devices = DeviceList.new(devices) return @devices end
ruby
def devices devices = @adb.devices.map { |d| serial = d.serial_number (@devices.has_key?(serial) && same_jobject?(@devices[serial].jobject, d)) \ ? @devices[serial] : Device.new(d) } @devices = DeviceList.new(devices) return @devices end
[ "def", "devices", "devices", "=", "@adb", ".", "devices", ".", "map", "{", "|", "d", "|", "serial", "=", "d", ".", "serial_number", "(", "@devices", ".", "has_key?", "(", "serial", ")", "&&", "same_jobject?", "(", "@devices", "[", "serial", "]", ".", "jobject", ",", "d", ")", ")", "?", "@devices", "[", "serial", "]", ":", "Device", ".", "new", "(", "d", ")", "}", "@devices", "=", "DeviceList", ".", "new", "(", "devices", ")", "return", "@devices", "end" ]
Get devices attached with ADB. @return [DeviceList] List of devices
[ "Get", "devices", "attached", "with", "ADB", "." ]
9f8a5c88ee8e7b572600ca7919b506bfc0e8d105
https://github.com/yoyo0906/ruby-adb-sdklib/blob/9f8a5c88ee8e7b572600ca7919b506bfc0e8d105/lib/adb-sdklib.rb#L89-L97
train
envylabs/vaulted_billing
lib/vaulted_billing/credit_card.rb
VaultedBilling.CreditCard.attributes
def attributes { :vault_id => vault_id, :currency => currency, :card_number => card_number, :cvv_number => cvv_number, :expires_on => expires_on, :first_name => first_name, :last_name => last_name, :street_address => street_address, :locality => locality, :region => region, :postal_code => postal_code, :country => country, :phone => phone } end
ruby
def attributes { :vault_id => vault_id, :currency => currency, :card_number => card_number, :cvv_number => cvv_number, :expires_on => expires_on, :first_name => first_name, :last_name => last_name, :street_address => street_address, :locality => locality, :region => region, :postal_code => postal_code, :country => country, :phone => phone } end
[ "def", "attributes", "{", ":vault_id", "=>", "vault_id", ",", ":currency", "=>", "currency", ",", ":card_number", "=>", "card_number", ",", ":cvv_number", "=>", "cvv_number", ",", ":expires_on", "=>", "expires_on", ",", ":first_name", "=>", "first_name", ",", ":last_name", "=>", "last_name", ",", ":street_address", "=>", "street_address", ",", ":locality", "=>", "locality", ",", ":region", "=>", "region", ",", ":postal_code", "=>", "postal_code", ",", ":country", "=>", "country", ",", ":phone", "=>", "phone", "}", "end" ]
The unique, gateway-generated identifier for this credit card. You may define any of the CreditCard attributes by passing a hash with the attribute name as the key: CreditCard.new(:card_number => '4111....')
[ "The", "unique", "gateway", "-", "generated", "identifier", "for", "this", "credit", "card", "." ]
a2d9689a6c500a3983100e657abe1606daa09d3a
https://github.com/envylabs/vaulted_billing/blob/a2d9689a6c500a3983100e657abe1606daa09d3a/lib/vaulted_billing/credit_card.rb#L67-L83
train
phatworx/rails_paginate
lib/rails_paginate/helpers/array.rb
RailsPaginate::Helpers.Array.paginate
def paginate(*args) options = args.extract_options! per_page = options.delete(:per_page) page = options.delete(:page) || 1 ::RailsPaginate::Collection.new(self, args.first || page, per_page) end
ruby
def paginate(*args) options = args.extract_options! per_page = options.delete(:per_page) page = options.delete(:page) || 1 ::RailsPaginate::Collection.new(self, args.first || page, per_page) end
[ "def", "paginate", "(", "*", "args", ")", "options", "=", "args", ".", "extract_options!", "per_page", "=", "options", ".", "delete", "(", ":per_page", ")", "page", "=", "options", ".", "delete", "(", ":page", ")", "||", "1", "::", "RailsPaginate", "::", "Collection", ".", "new", "(", "self", ",", "args", ".", "first", "||", "page", ",", "per_page", ")", "end" ]
paginate with options page = active page per_page = how much entries per page
[ "paginate", "with", "options" ]
ae8cbc12030853b236dc2cbf6ede8700fb835771
https://github.com/phatworx/rails_paginate/blob/ae8cbc12030853b236dc2cbf6ede8700fb835771/lib/rails_paginate/helpers/array.rb#L8-L13
train
topfunky/google-checkout
lib/google-checkout/command.rb
GoogleCheckout.Command.post
def post # Create HTTP(S) POST command and set up Basic Authentication. uri = URI.parse(url) request = Net::HTTP::Post.new(uri.path) request.basic_auth(@merchant_id, @merchant_key) # Set up the HTTP connection object and the SSL layer. https = Net::HTTP.new(uri.host, uri.port) https.use_ssl = true https.cert_store = self.class.x509_store https.verify_mode = OpenSSL::SSL::VERIFY_PEER https.verify_depth = 5 # Send the request to Google. response = https.request(request, self.to_xml) # NOTE Because Notification.parse() is used, the content of objects # will be correctly parsed no matter what the HTTP response code # is from the server. case response when Net::HTTPSuccess, Net::HTTPClientError notification = Notification.parse(response.body) if notification.error? raise APIError, "#{notification.message} [in #{GoogleCheckout.production? ? 'production' : 'sandbox' }]" end return notification when Net::HTTPRedirection, Net::HTTPServerError, Net::HTTPInformation raise "Unexpected response code (#{response.class}): #{response.code} - #{response.message}" else raise "Unknown response code: #{response.code} - #{response.message}" end end
ruby
def post # Create HTTP(S) POST command and set up Basic Authentication. uri = URI.parse(url) request = Net::HTTP::Post.new(uri.path) request.basic_auth(@merchant_id, @merchant_key) # Set up the HTTP connection object and the SSL layer. https = Net::HTTP.new(uri.host, uri.port) https.use_ssl = true https.cert_store = self.class.x509_store https.verify_mode = OpenSSL::SSL::VERIFY_PEER https.verify_depth = 5 # Send the request to Google. response = https.request(request, self.to_xml) # NOTE Because Notification.parse() is used, the content of objects # will be correctly parsed no matter what the HTTP response code # is from the server. case response when Net::HTTPSuccess, Net::HTTPClientError notification = Notification.parse(response.body) if notification.error? raise APIError, "#{notification.message} [in #{GoogleCheckout.production? ? 'production' : 'sandbox' }]" end return notification when Net::HTTPRedirection, Net::HTTPServerError, Net::HTTPInformation raise "Unexpected response code (#{response.class}): #{response.code} - #{response.message}" else raise "Unknown response code: #{response.code} - #{response.message}" end end
[ "def", "post", "uri", "=", "URI", ".", "parse", "(", "url", ")", "request", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "uri", ".", "path", ")", "request", ".", "basic_auth", "(", "@merchant_id", ",", "@merchant_key", ")", "https", "=", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "https", ".", "use_ssl", "=", "true", "https", ".", "cert_store", "=", "self", ".", "class", ".", "x509_store", "https", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_PEER", "https", ".", "verify_depth", "=", "5", "response", "=", "https", ".", "request", "(", "request", ",", "self", ".", "to_xml", ")", "case", "response", "when", "Net", "::", "HTTPSuccess", ",", "Net", "::", "HTTPClientError", "notification", "=", "Notification", ".", "parse", "(", "response", ".", "body", ")", "if", "notification", ".", "error?", "raise", "APIError", ",", "\"#{notification.message} [in #{GoogleCheckout.production? ? 'production' : 'sandbox' }]\"", "end", "return", "notification", "when", "Net", "::", "HTTPRedirection", ",", "Net", "::", "HTTPServerError", ",", "Net", "::", "HTTPInformation", "raise", "\"Unexpected response code (#{response.class}): #{response.code} - #{response.message}\"", "else", "raise", "\"Unknown response code: #{response.code} - #{response.message}\"", "end", "end" ]
Sends the Command's XML to GoogleCheckout via HTTPS with Basic Auth. Returns a GoogleCheckout::RequestReceived or a GoogleCheckout::Error object.
[ "Sends", "the", "Command", "s", "XML", "to", "GoogleCheckout", "via", "HTTPS", "with", "Basic", "Auth", "." ]
66089cef799bd40f3ba4370f01f1b8dc10f92115
https://github.com/topfunky/google-checkout/blob/66089cef799bd40f3ba4370f01f1b8dc10f92115/lib/google-checkout/command.rb#L40-L72
train
topfunky/google-checkout
lib/google-checkout/command.rb
GoogleCheckout.SendBuyerMessage.to_xml
def to_xml # :nodoc: xml = Builder::XmlMarkup.new xml.instruct! @xml = xml.tag!('send-buyer-message', { :xmlns => "http://checkout.google.com/schema/2", "google-order-number" => @google_order_number }) do xml.tag!("message", @message) xml.tag!("send-email", true) end @xml end
ruby
def to_xml # :nodoc: xml = Builder::XmlMarkup.new xml.instruct! @xml = xml.tag!('send-buyer-message', { :xmlns => "http://checkout.google.com/schema/2", "google-order-number" => @google_order_number }) do xml.tag!("message", @message) xml.tag!("send-email", true) end @xml end
[ "def", "to_xml", "xml", "=", "Builder", "::", "XmlMarkup", ".", "new", "xml", ".", "instruct!", "@xml", "=", "xml", ".", "tag!", "(", "'send-buyer-message'", ",", "{", ":xmlns", "=>", "\"http://checkout.google.com/schema/2\"", ",", "\"google-order-number\"", "=>", "@google_order_number", "}", ")", "do", "xml", ".", "tag!", "(", "\"message\"", ",", "@message", ")", "xml", ".", "tag!", "(", "\"send-email\"", ",", "true", ")", "end", "@xml", "end" ]
Make a new message to send. The last argument is the actual message. Call +post+ on the resulting object to submit it to Google for sending.
[ "Make", "a", "new", "message", "to", "send", "." ]
66089cef799bd40f3ba4370f01f1b8dc10f92115
https://github.com/topfunky/google-checkout/blob/66089cef799bd40f3ba4370f01f1b8dc10f92115/lib/google-checkout/command.rb#L176-L187
train
dropofwill/rtasklib
lib/rtasklib/taskrc.rb
Rtasklib.Taskrc.hash_to_model
def hash_to_model taskrc_hash taskrc_hash.each do |attr, value| add_model_attr(attr, value) set_model_attr_value(attr, value) end config end
ruby
def hash_to_model taskrc_hash taskrc_hash.each do |attr, value| add_model_attr(attr, value) set_model_attr_value(attr, value) end config end
[ "def", "hash_to_model", "taskrc_hash", "taskrc_hash", ".", "each", "do", "|", "attr", ",", "value", "|", "add_model_attr", "(", "attr", ",", "value", ")", "set_model_attr_value", "(", "attr", ",", "value", ")", "end", "config", "end" ]
Generate a dynamic Virtus model, with the attributes defined by the input @param rc [Hash, Pathname] either a hash of attribute value pairs or a Pathname to the raw taskrc file. @raise [TypeError] if rc is not of type Hash, String, or Pathname @raise [RuntimeError] if rc is a path and does not exist on the fs Turn a hash of attribute => value pairs into a TaskrcModel object. There can be only one TaskrcModel object per Taskrc, it's saved to the instance variable `config` @param taskrc_hash [Hash{Symbol=>String}] @return [Models::TaskrcModel] the instance variable config @api private
[ "Generate", "a", "dynamic", "Virtus", "model", "with", "the", "attributes", "defined", "by", "the", "input" ]
c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c
https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/taskrc.rb#L54-L60
train
dropofwill/rtasklib
lib/rtasklib/taskrc.rb
Rtasklib.Taskrc.mappable_to_model
def mappable_to_model rc_file rc_file.map! { |l| line_to_tuple(l) }.compact! taskrc = Hash[rc_file] hash_to_model(taskrc) end
ruby
def mappable_to_model rc_file rc_file.map! { |l| line_to_tuple(l) }.compact! taskrc = Hash[rc_file] hash_to_model(taskrc) end
[ "def", "mappable_to_model", "rc_file", "rc_file", ".", "map!", "{", "|", "l", "|", "line_to_tuple", "(", "l", ")", "}", ".", "compact!", "taskrc", "=", "Hash", "[", "rc_file", "]", "hash_to_model", "(", "taskrc", ")", "end" ]
Converts a .taskrc file path into a Hash that can be converted into a TaskrcModel object @param rc_file [String,Pathname] a valid pathname to a .taskrc file @return [Models::TaskrcModel] the instance variable config @api private
[ "Converts", "a", ".", "taskrc", "file", "path", "into", "a", "Hash", "that", "can", "be", "converted", "into", "a", "TaskrcModel", "object" ]
c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c
https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/taskrc.rb#L69-L73
train
dropofwill/rtasklib
lib/rtasklib/taskrc.rb
Rtasklib.Taskrc.part_of_model_to_rc
def part_of_model_to_rc *attrs attrs.map do |attr| value = get_model_attr_value attr hash_attr = get_rc_attr_from_hash attr.to_s attr = "rc.#{hash_attr}=#{value}" end end
ruby
def part_of_model_to_rc *attrs attrs.map do |attr| value = get_model_attr_value attr hash_attr = get_rc_attr_from_hash attr.to_s attr = "rc.#{hash_attr}=#{value}" end end
[ "def", "part_of_model_to_rc", "*", "attrs", "attrs", ".", "map", "do", "|", "attr", "|", "value", "=", "get_model_attr_value", "attr", "hash_attr", "=", "get_rc_attr_from_hash", "attr", ".", "to_s", "attr", "=", "\"rc.#{hash_attr}=#{value}\"", "end", "end" ]
Serialize the given attrs model back to the taskrc format @param attrs [Array] a splat of attributes @return [Array<String>] an array of CLI formatted strings @api public
[ "Serialize", "the", "given", "attrs", "model", "back", "to", "the", "taskrc", "format" ]
c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c
https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/taskrc.rb#L99-L105
train
dropofwill/rtasklib
lib/rtasklib/taskrc.rb
Rtasklib.Taskrc.path_exist?
def path_exist? path if path.is_a? Pathname return path.exist? elsif path.is_a? String return Pathname.new(path).exist? else return false end end
ruby
def path_exist? path if path.is_a? Pathname return path.exist? elsif path.is_a? String return Pathname.new(path).exist? else return false end end
[ "def", "path_exist?", "path", "if", "path", ".", "is_a?", "Pathname", "return", "path", ".", "exist?", "elsif", "path", ".", "is_a?", "String", "return", "Pathname", ".", "new", "(", "path", ")", ".", "exist?", "else", "return", "false", "end", "end" ]
Check whether a given object is a path and it exists on the file system @param path [Object] @return [Boolean] @api private
[ "Check", "whether", "a", "given", "object", "is", "a", "path", "and", "it", "exists", "on", "the", "file", "system" ]
c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c
https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/taskrc.rb#L192-L200
train
quirkey/jim
lib/jim/index.rb
Jim.Index.find_all
def find_all(name, version = nil) matched = [] find(name, version) {|p| matched << p } matched end
ruby
def find_all(name, version = nil) matched = [] find(name, version) {|p| matched << p } matched end
[ "def", "find_all", "(", "name", ",", "version", "=", "nil", ")", "matched", "=", "[", "]", "find", "(", "name", ",", "version", ")", "{", "|", "p", "|", "matched", "<<", "p", "}", "matched", "end" ]
Find _all_ paths matching `name` and `version`. Returning an array.
[ "Find", "_all_", "paths", "matching", "name", "and", "version", ".", "Returning", "an", "array", "." ]
ad5dbf06527a1d0376055a02b58bb11b5a0ebc35
https://github.com/quirkey/jim/blob/ad5dbf06527a1d0376055a02b58bb11b5a0ebc35/lib/jim/index.rb#L73-L77
train
buren/honey_format
lib/honey_format/matrix/header.rb
HoneyFormat.Header.to_csv
def to_csv(columns: nil) attributes = if columns self.columns & columns.map(&:to_sym) else self.columns end ::CSV.generate_line(attributes) end
ruby
def to_csv(columns: nil) attributes = if columns self.columns & columns.map(&:to_sym) else self.columns end ::CSV.generate_line(attributes) end
[ "def", "to_csv", "(", "columns", ":", "nil", ")", "attributes", "=", "if", "columns", "self", ".", "columns", "&", "columns", ".", "map", "(", "&", ":to_sym", ")", "else", "self", ".", "columns", "end", "::", "CSV", ".", "generate_line", "(", "attributes", ")", "end" ]
Header as CSV-string @return [String] CSV-string representation.
[ "Header", "as", "CSV", "-", "string" ]
5c54fba5f5ba044721afeef460a069af2018452c
https://github.com/buren/honey_format/blob/5c54fba5f5ba044721afeef460a069af2018452c/lib/honey_format/matrix/header.rb#L83-L91
train
buren/honey_format
lib/honey_format/matrix/header.rb
HoneyFormat.Header.build_columns
def build_columns(header) columns = header.each_with_index.map do |header_column, index| convert_column(header_column, index).tap do |column| maybe_raise_missing_column!(column) end end @deduplicator.call(columns) end
ruby
def build_columns(header) columns = header.each_with_index.map do |header_column, index| convert_column(header_column, index).tap do |column| maybe_raise_missing_column!(column) end end @deduplicator.call(columns) end
[ "def", "build_columns", "(", "header", ")", "columns", "=", "header", ".", "each_with_index", ".", "map", "do", "|", "header_column", ",", "index", "|", "convert_column", "(", "header_column", ",", "index", ")", ".", "tap", "do", "|", "column", "|", "maybe_raise_missing_column!", "(", "column", ")", "end", "end", "@deduplicator", ".", "call", "(", "columns", ")", "end" ]
Convert original header @param [Array<String>] header the original header @return [Array<String>] converted columns
[ "Convert", "original", "header" ]
5c54fba5f5ba044721afeef460a069af2018452c
https://github.com/buren/honey_format/blob/5c54fba5f5ba044721afeef460a069af2018452c/lib/honey_format/matrix/header.rb#L122-L130
train
buren/honey_format
lib/honey_format/matrix/header.rb
HoneyFormat.Header.convert_column
def convert_column(column, index) value = if converter_arity == 1 @converter.call(column) else @converter.call(column, index) end value.to_sym end
ruby
def convert_column(column, index) value = if converter_arity == 1 @converter.call(column) else @converter.call(column, index) end value.to_sym end
[ "def", "convert_column", "(", "column", ",", "index", ")", "value", "=", "if", "converter_arity", "==", "1", "@converter", ".", "call", "(", "column", ")", "else", "@converter", ".", "call", "(", "column", ",", "index", ")", "end", "value", ".", "to_sym", "end" ]
Convert the column value @param [String, Symbol] column the CSV header column value @param [Integer] index the CSV header column index @return [Symbol] the converted column
[ "Convert", "the", "column", "value" ]
5c54fba5f5ba044721afeef460a069af2018452c
https://github.com/buren/honey_format/blob/5c54fba5f5ba044721afeef460a069af2018452c/lib/honey_format/matrix/header.rb#L136-L143
train
delagoya/mascot-dat
lib/mascot/dat.rb
Mascot.DAT.goto
def goto(key) if @idx.has_key?(key.to_sym) @dat_file.pos = @idx[key.to_sym] else raise Exception.new "Invalid DAT section \"#{key}\"" end end
ruby
def goto(key) if @idx.has_key?(key.to_sym) @dat_file.pos = @idx[key.to_sym] else raise Exception.new "Invalid DAT section \"#{key}\"" end end
[ "def", "goto", "(", "key", ")", "if", "@idx", ".", "has_key?", "(", "key", ".", "to_sym", ")", "@dat_file", ".", "pos", "=", "@idx", "[", "key", ".", "to_sym", "]", "else", "raise", "Exception", ".", "new", "\"Invalid DAT section \\\"#{key}\\\"\"", "end", "end" ]
Go to a section of the Mascot DAT file
[ "Go", "to", "a", "section", "of", "the", "Mascot", "DAT", "file" ]
c7c239e545687008b195047e72c77d09331d6a0e
https://github.com/delagoya/mascot-dat/blob/c7c239e545687008b195047e72c77d09331d6a0e/lib/mascot/dat.rb#L62-L68
train
delagoya/mascot-dat
lib/mascot/dat.rb
Mascot.DAT.read_section
def read_section(key) self.goto(key.to_sym) # read past the initial boundary marker tmp = @dat_file.readline @dat_file.each do |l| break if l =~ @boundary tmp << l end tmp end
ruby
def read_section(key) self.goto(key.to_sym) # read past the initial boundary marker tmp = @dat_file.readline @dat_file.each do |l| break if l =~ @boundary tmp << l end tmp end
[ "def", "read_section", "(", "key", ")", "self", ".", "goto", "(", "key", ".", "to_sym", ")", "tmp", "=", "@dat_file", ".", "readline", "@dat_file", ".", "each", "do", "|", "l", "|", "break", "if", "l", "=~", "@boundary", "tmp", "<<", "l", "end", "tmp", "end" ]
Read a section of the DAT file into memory. THIS IS NOT RECOMMENDED UNLESS YOU KNOW WHAT YOU ARE DOING. @param key [String or Symbol] The section name @return [String] The section of the DAT file as a String. The section includes the MIME boundary and content type definition lines.
[ "Read", "a", "section", "of", "the", "DAT", "file", "into", "memory", ".", "THIS", "IS", "NOT", "RECOMMENDED", "UNLESS", "YOU", "KNOW", "WHAT", "YOU", "ARE", "DOING", "." ]
c7c239e545687008b195047e72c77d09331d6a0e
https://github.com/delagoya/mascot-dat/blob/c7c239e545687008b195047e72c77d09331d6a0e/lib/mascot/dat.rb#L77-L86
train
usmu/usmu
lib/usmu/configuration.rb
Usmu.Configuration.excluded?
def excluded?(filename) exclude.each do |f| f += '**/*' if f.end_with? '/' return true if File.fnmatch(f, filename, File::FNM_EXTGLOB | File::FNM_PATHNAME) end false end
ruby
def excluded?(filename) exclude.each do |f| f += '**/*' if f.end_with? '/' return true if File.fnmatch(f, filename, File::FNM_EXTGLOB | File::FNM_PATHNAME) end false end
[ "def", "excluded?", "(", "filename", ")", "exclude", ".", "each", "do", "|", "f", "|", "f", "+=", "'**/*'", "if", "f", ".", "end_with?", "'/'", "return", "true", "if", "File", ".", "fnmatch", "(", "f", ",", "filename", ",", "File", "::", "FNM_EXTGLOB", "|", "File", "::", "FNM_PATHNAME", ")", "end", "false", "end" ]
Helper to determine if a filename is excluded according to the exclude configuration parameter. @return [Boolean]
[ "Helper", "to", "determine", "if", "a", "filename", "is", "excluded", "according", "to", "the", "exclude", "configuration", "parameter", "." ]
037bfe0daa995477c29662931236d7a60ca29730
https://github.com/usmu/usmu/blob/037bfe0daa995477c29662931236d7a60ca29730/lib/usmu/configuration.rb#L141-L147
train
sinefunc/pagination
lib/pagination/template.rb
Pagination.Template.render
def render if engine.respond_to?(:render) engine.render(Object.new, :items => items) else engine.result(binding) end end
ruby
def render if engine.respond_to?(:render) engine.render(Object.new, :items => items) else engine.result(binding) end end
[ "def", "render", "if", "engine", ".", "respond_to?", "(", ":render", ")", "engine", ".", "render", "(", "Object", ".", "new", ",", ":items", "=>", "items", ")", "else", "engine", ".", "result", "(", "binding", ")", "end", "end" ]
Initialize with your paginated collection. == Paramaters: items:: a `Pagination::Collection` object return by `Pagination.paginate`. Displayed the standard pagination markup as provided by the `Pagination` library. This uses Haml if Haml is required already. Else it uses ERB. == Returns: The actual HTML for the pagination.
[ "Initialize", "with", "your", "paginated", "collection", "." ]
e4d8684676dab2d4d9755af334fd35958bbfc3c8
https://github.com/sinefunc/pagination/blob/e4d8684676dab2d4d9755af334fd35958bbfc3c8/lib/pagination/template.rb#L31-L37
train
nilium/ruby-snowmath
lib/snow-math/to_a.rb
Snow.ArraySupport.map!
def map!(&block) return to_enum(:map!) unless block_given? (0 ... self.length).each { |index| store(index, yield(fetch(index))) } self end
ruby
def map!(&block) return to_enum(:map!) unless block_given? (0 ... self.length).each { |index| store(index, yield(fetch(index))) } self end
[ "def", "map!", "(", "&", "block", ")", "return", "to_enum", "(", ":map!", ")", "unless", "block_given?", "(", "0", "...", "self", ".", "length", ")", ".", "each", "{", "|", "index", "|", "store", "(", "index", ",", "yield", "(", "fetch", "(", "index", ")", ")", ")", "}", "self", "end" ]
In the first form, iterates over all elements of the object, yields them to the block given, and overwrites the element's value with the value returned by the block. In the second form, returns an Enumerator. The return value of the block must be the same kind of object as was yielded to the block. So, if yielded a Vec3, the block must return a Vec3. If yielded a Numeric, it must return a Numeric. call-seq: map! { |elem| block } -> self map! -> Enumerator
[ "In", "the", "first", "form", "iterates", "over", "all", "elements", "of", "the", "object", "yields", "them", "to", "the", "block", "given", "and", "overwrites", "the", "element", "s", "value", "with", "the", "value", "returned", "by", "the", "block", "." ]
ebac4e56494ff440004a07e7e2b97a2893e48b3a
https://github.com/nilium/ruby-snowmath/blob/ebac4e56494ff440004a07e7e2b97a2893e48b3a/lib/snow-math/to_a.rb#L80-L87
train
payneteasy/ruby-library-payneteasy-api
lib/paynet_easy/paynet_easy_api/query/query_factory.rb
PaynetEasy::PaynetEasyApi::Query.QueryFactory.query
def query(api_query_name) query_class = "#{api_query_name.camelize}Query" query_file = "query/#{api_query_name.gsub('-', '_')}_query" require query_file PaynetEasy::PaynetEasyApi::Query.const_get(query_class).new(api_query_name) end
ruby
def query(api_query_name) query_class = "#{api_query_name.camelize}Query" query_file = "query/#{api_query_name.gsub('-', '_')}_query" require query_file PaynetEasy::PaynetEasyApi::Query.const_get(query_class).new(api_query_name) end
[ "def", "query", "(", "api_query_name", ")", "query_class", "=", "\"#{api_query_name.camelize}Query\"", "query_file", "=", "\"query/#{api_query_name.gsub('-', '_')}_query\"", "require", "query_file", "PaynetEasy", "::", "PaynetEasyApi", "::", "Query", ".", "const_get", "(", "query_class", ")", ".", "new", "(", "api_query_name", ")", "end" ]
Create API query object by API query method @param api_query_name [String] API query method name @return [Prototype::Query] API query object
[ "Create", "API", "query", "object", "by", "API", "query", "method" ]
3200a447829b62e241fdc329f80fddb5f8d68cc0
https://github.com/payneteasy/ruby-library-payneteasy-api/blob/3200a447829b62e241fdc329f80fddb5f8d68cc0/lib/paynet_easy/paynet_easy_api/query/query_factory.rb#L11-L17
train
i0n/jumpstart
lib/jumpstart/base.rb
JumpStart.Base.start
def start puts "\n******************************************************************************************************************************************\n\n" puts " JumpStarting....\n".purple check_setup execute_install_command run_scripts_from_yaml(:run_after_install_command) parse_template_dir create_dirs populate_files_from_whole_templates populate_files_from_append_templates populate_files_from_line_templates remove_unwanted_files run_scripts_from_yaml(:run_after_jumpstart) check_for_strings_to_replace run_scripts_from_yaml(:run_after_string_replace) check_local_nginx_configuration exit_with_success end
ruby
def start puts "\n******************************************************************************************************************************************\n\n" puts " JumpStarting....\n".purple check_setup execute_install_command run_scripts_from_yaml(:run_after_install_command) parse_template_dir create_dirs populate_files_from_whole_templates populate_files_from_append_templates populate_files_from_line_templates remove_unwanted_files run_scripts_from_yaml(:run_after_jumpstart) check_for_strings_to_replace run_scripts_from_yaml(:run_after_string_replace) check_local_nginx_configuration exit_with_success end
[ "def", "start", "puts", "\"\\n******************************************************************************************************************************************\\n\\n\"", "puts", "\" JumpStarting....\\n\"", ".", "purple", "check_setup", "execute_install_command", "run_scripts_from_yaml", "(", ":run_after_install_command", ")", "parse_template_dir", "create_dirs", "populate_files_from_whole_templates", "populate_files_from_append_templates", "populate_files_from_line_templates", "remove_unwanted_files", "run_scripts_from_yaml", "(", ":run_after_jumpstart", ")", "check_for_strings_to_replace", "run_scripts_from_yaml", "(", ":run_after_string_replace", ")", "check_local_nginx_configuration", "exit_with_success", "end" ]
Runs the configuration, generating the new project from the chosen template.
[ "Runs", "the", "configuration", "generating", "the", "new", "project", "from", "the", "chosen", "template", "." ]
e61beee175ba5a69796e00c2fb88097227c5ce9b
https://github.com/i0n/jumpstart/blob/e61beee175ba5a69796e00c2fb88097227c5ce9b/lib/jumpstart/base.rb#L62-L79
train
i0n/jumpstart
lib/jumpstart/base.rb
JumpStart.Base.check_install_path
def check_install_path @install_path = JumpStart::LAUNCH_PATH if @install_path.nil? || @install_path.empty? if File.directory?(FileUtils.join_paths(@install_path, @project_name)) puts "\nThe directory #{FileUtils.join_paths(@install_path, @project_name).red} already exists.\nAs this is the location you have specified for creating your new project jumpstart will now exit to avoid overwriting anything." exit_normal end return true end
ruby
def check_install_path @install_path = JumpStart::LAUNCH_PATH if @install_path.nil? || @install_path.empty? if File.directory?(FileUtils.join_paths(@install_path, @project_name)) puts "\nThe directory #{FileUtils.join_paths(@install_path, @project_name).red} already exists.\nAs this is the location you have specified for creating your new project jumpstart will now exit to avoid overwriting anything." exit_normal end return true end
[ "def", "check_install_path", "@install_path", "=", "JumpStart", "::", "LAUNCH_PATH", "if", "@install_path", ".", "nil?", "||", "@install_path", ".", "empty?", "if", "File", ".", "directory?", "(", "FileUtils", ".", "join_paths", "(", "@install_path", ",", "@project_name", ")", ")", "puts", "\"\\nThe directory #{FileUtils.join_paths(@install_path, @project_name).red} already exists.\\nAs this is the location you have specified for creating your new project jumpstart will now exit to avoid overwriting anything.\"", "exit_normal", "end", "return", "true", "end" ]
Sets the install path to executing directory if @install_path varibale is nil or empty. This should result in projects being created in directory from which the jumpstart command was called, if the template specified does not set this option. Checks the install path set in @install_path. Checks that a directory with the same name as the project does not already exist in the install path.
[ "Sets", "the", "install", "path", "to", "executing", "directory", "if" ]
e61beee175ba5a69796e00c2fb88097227c5ce9b
https://github.com/i0n/jumpstart/blob/e61beee175ba5a69796e00c2fb88097227c5ce9b/lib/jumpstart/base.rb#L141-L148
train
i0n/jumpstart
lib/jumpstart/base.rb
JumpStart.Base.create_template
def create_template if File.directory?(FileUtils.join_paths(JumpStart.templates_path, @template_name)) puts "\nThe directory #{FileUtils.join_paths(JumpStart.templates_path, @template_name).red} already exists. The template will not be created." exit_normal else FileUtils.mkdir_p(FileUtils.join_paths(JumpStart.templates_path, @template_name, "/jumpstart_config")) yaml = IO.read(FileUtils.join_paths(ROOT_PATH, "/source_templates/template_config.yml")) File.open(FileUtils.join_paths(JumpStart.templates_path, @template_name, "/jumpstart_config", "#{@template_name}.yml"), 'w') do |file| file.puts yaml end puts "The template #{@template_name.green} has been generated.\n" end end
ruby
def create_template if File.directory?(FileUtils.join_paths(JumpStart.templates_path, @template_name)) puts "\nThe directory #{FileUtils.join_paths(JumpStart.templates_path, @template_name).red} already exists. The template will not be created." exit_normal else FileUtils.mkdir_p(FileUtils.join_paths(JumpStart.templates_path, @template_name, "/jumpstart_config")) yaml = IO.read(FileUtils.join_paths(ROOT_PATH, "/source_templates/template_config.yml")) File.open(FileUtils.join_paths(JumpStart.templates_path, @template_name, "/jumpstart_config", "#{@template_name}.yml"), 'w') do |file| file.puts yaml end puts "The template #{@template_name.green} has been generated.\n" end end
[ "def", "create_template", "if", "File", ".", "directory?", "(", "FileUtils", ".", "join_paths", "(", "JumpStart", ".", "templates_path", ",", "@template_name", ")", ")", "puts", "\"\\nThe directory #{FileUtils.join_paths(JumpStart.templates_path, @template_name).red} already exists. The template will not be created.\"", "exit_normal", "else", "FileUtils", ".", "mkdir_p", "(", "FileUtils", ".", "join_paths", "(", "JumpStart", ".", "templates_path", ",", "@template_name", ",", "\"/jumpstart_config\"", ")", ")", "yaml", "=", "IO", ".", "read", "(", "FileUtils", ".", "join_paths", "(", "ROOT_PATH", ",", "\"/source_templates/template_config.yml\"", ")", ")", "File", ".", "open", "(", "FileUtils", ".", "join_paths", "(", "JumpStart", ".", "templates_path", ",", "@template_name", ",", "\"/jumpstart_config\"", ",", "\"#{@template_name}.yml\"", ")", ",", "'w'", ")", "do", "|", "file", "|", "file", ".", "puts", "yaml", "end", "puts", "\"The template #{@template_name.green} has been generated.\\n\"", "end", "end" ]
Creates a new blank template in whichever directory the default templates directory has been set to.
[ "Creates", "a", "new", "blank", "template", "in", "whichever", "directory", "the", "default", "templates", "directory", "has", "been", "set", "to", "." ]
e61beee175ba5a69796e00c2fb88097227c5ce9b
https://github.com/i0n/jumpstart/blob/e61beee175ba5a69796e00c2fb88097227c5ce9b/lib/jumpstart/base.rb#L151-L163
train
i0n/jumpstart
lib/jumpstart/base.rb
JumpStart.Base.jumpstart_menu
def jumpstart_menu puts "\n\n******************************************************************************************************************************************\n\n" puts " JUMPSTART MENU\n".purple puts " Here are your options:\n\n" puts " 1".yellow + " Create a new project from an existing template.\n" puts " 2".yellow + " Create a new template.\n" puts " 3".yellow + " Set the default template.\n" puts " 4".yellow + " Set the templates directory.\n\n" puts " x".yellow + " Exit jumpstart.\n\n" puts "******************************************************************************************************************************************\n\n" jumpstart_menu_options end
ruby
def jumpstart_menu puts "\n\n******************************************************************************************************************************************\n\n" puts " JUMPSTART MENU\n".purple puts " Here are your options:\n\n" puts " 1".yellow + " Create a new project from an existing template.\n" puts " 2".yellow + " Create a new template.\n" puts " 3".yellow + " Set the default template.\n" puts " 4".yellow + " Set the templates directory.\n\n" puts " x".yellow + " Exit jumpstart.\n\n" puts "******************************************************************************************************************************************\n\n" jumpstart_menu_options end
[ "def", "jumpstart_menu", "puts", "\"\\n\\n******************************************************************************************************************************************\\n\\n\"", "puts", "\" JUMPSTART MENU\\n\"", ".", "purple", "puts", "\" Here are your options:\\n\\n\"", "puts", "\" 1\"", ".", "yellow", "+", "\" Create a new project from an existing template.\\n\"", "puts", "\" 2\"", ".", "yellow", "+", "\" Create a new template.\\n\"", "puts", "\" 3\"", ".", "yellow", "+", "\" Set the default template.\\n\"", "puts", "\" 4\"", ".", "yellow", "+", "\" Set the templates directory.\\n\\n\"", "puts", "\" x\"", ".", "yellow", "+", "\" Exit jumpstart.\\n\\n\"", "puts", "\"******************************************************************************************************************************************\\n\\n\"", "jumpstart_menu_options", "end" ]
Displays options for the main jumpstart menu.
[ "Displays", "options", "for", "the", "main", "jumpstart", "menu", "." ]
e61beee175ba5a69796e00c2fb88097227c5ce9b
https://github.com/i0n/jumpstart/blob/e61beee175ba5a69796e00c2fb88097227c5ce9b/lib/jumpstart/base.rb#L166-L177
train
i0n/jumpstart
lib/jumpstart/base.rb
JumpStart.Base.jumpstart_menu_options
def jumpstart_menu_options input = gets.chomp.strip.downcase case when input == "1" new_project_from_template_menu when input == "2" new_template_menu when input == "3" set_default_template_menu when input == "4" templates_dir_menu when input == "x" exit_normal else puts "That command hasn't been understood. Try again!".red jumpstart_menu_options end end
ruby
def jumpstart_menu_options input = gets.chomp.strip.downcase case when input == "1" new_project_from_template_menu when input == "2" new_template_menu when input == "3" set_default_template_menu when input == "4" templates_dir_menu when input == "x" exit_normal else puts "That command hasn't been understood. Try again!".red jumpstart_menu_options end end
[ "def", "jumpstart_menu_options", "input", "=", "gets", ".", "chomp", ".", "strip", ".", "downcase", "case", "when", "input", "==", "\"1\"", "new_project_from_template_menu", "when", "input", "==", "\"2\"", "new_template_menu", "when", "input", "==", "\"3\"", "set_default_template_menu", "when", "input", "==", "\"4\"", "templates_dir_menu", "when", "input", "==", "\"x\"", "exit_normal", "else", "puts", "\"That command hasn't been understood. Try again!\"", ".", "red", "jumpstart_menu_options", "end", "end" ]
Captures user input for the main jumpstart menu and calls the appropriate method
[ "Captures", "user", "input", "for", "the", "main", "jumpstart", "menu", "and", "calls", "the", "appropriate", "method" ]
e61beee175ba5a69796e00c2fb88097227c5ce9b
https://github.com/i0n/jumpstart/blob/e61beee175ba5a69796e00c2fb88097227c5ce9b/lib/jumpstart/base.rb#L180-L197
train