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
johnwunder/stix_schema_spy
lib/stix_schema_spy/models/schema.rb
StixSchemaSpy.Schema.find_prefix
def find_prefix(doc) return config['prefix'] if config && config['prefix'] # Loop through the attributes until we see one with the same value ns_prefix_attribute = doc.namespaces.find do |prefix, ns| ns.to_s == namespace.to_s && prefix != 'xmlns' end # If the attribute was found, return it, otherwise return nil ns_prefix_attribute ? ns_prefix_attribute[0].split(':').last : "Unknown" end
ruby
def find_prefix(doc) return config['prefix'] if config && config['prefix'] # Loop through the attributes until we see one with the same value ns_prefix_attribute = doc.namespaces.find do |prefix, ns| ns.to_s == namespace.to_s && prefix != 'xmlns' end # If the attribute was found, return it, otherwise return nil ns_prefix_attribute ? ns_prefix_attribute[0].split(':').last : "Unknown" end
[ "def", "find_prefix", "(", "doc", ")", "return", "config", "[", "'prefix'", "]", "if", "config", "&&", "config", "[", "'prefix'", "]", "# Loop through the attributes until we see one with the same value", "ns_prefix_attribute", "=", "doc", ".", "namespaces", ".", "find", "do", "|", "prefix", ",", "ns", "|", "ns", ".", "to_s", "==", "namespace", ".", "to_s", "&&", "prefix", "!=", "'xmlns'", "end", "# If the attribute was found, return it, otherwise return nil", "ns_prefix_attribute", "?", "ns_prefix_attribute", "[", "0", "]", ".", "split", "(", "':'", ")", ".", "last", ":", "\"Unknown\"", "end" ]
Find the namespace prefix by searching through the namespaces for the TNS
[ "Find", "the", "namespace", "prefix", "by", "searching", "through", "the", "namespaces", "for", "the", "TNS" ]
2d551c6854d749eb330340e69f73baee1c4b52d3
https://github.com/johnwunder/stix_schema_spy/blob/2d551c6854d749eb330340e69f73baee1c4b52d3/lib/stix_schema_spy/models/schema.rb#L97-L107
train
hannesg/multi_git
lib/multi_git/config.rb
MultiGit.Config.each
def each return to_enum unless block_given? each_explicit_key do |*key| next if default?(*key) yield key, get(*key) end end
ruby
def each return to_enum unless block_given? each_explicit_key do |*key| next if default?(*key) yield key, get(*key) end end
[ "def", "each", "return", "to_enum", "unless", "block_given?", "each_explicit_key", "do", "|", "*", "key", "|", "next", "if", "default?", "(", "key", ")", "yield", "key", ",", "get", "(", "key", ")", "end", "end" ]
Expensive. Use only for debug
[ "Expensive", ".", "Use", "only", "for", "debug" ]
cb82e66be7d27c3b630610ce3f1385b30811f139
https://github.com/hannesg/multi_git/blob/cb82e66be7d27c3b630610ce3f1385b30811f139/lib/multi_git/config.rb#L139-L145
train
maca/eventual
lib/eventual/syntax_nodes.rb
Eventual.Node.include?
def include? date result = false walk { |elements| break result = true if elements.include? date } return result if !result || date.class == Date || times.nil? times.include? date end
ruby
def include? date result = false walk { |elements| break result = true if elements.include? date } return result if !result || date.class == Date || times.nil? times.include? date end
[ "def", "include?", "date", "result", "=", "false", "walk", "{", "|", "elements", "|", "break", "result", "=", "true", "if", "elements", ".", "include?", "date", "}", "return", "result", "if", "!", "result", "||", "date", ".", "class", "==", "Date", "||", "times", ".", "nil?", "times", ".", "include?", "date", "end" ]
Returns true if the Date or DateTime passed is included in the parsed Dates or DateTimes
[ "Returns", "true", "if", "the", "Date", "or", "DateTime", "passed", "is", "included", "in", "the", "parsed", "Dates", "or", "DateTimes" ]
8933def8f4440dae69df47fb90b80796c32ebc9d
https://github.com/maca/eventual/blob/8933def8f4440dae69df47fb90b80796c32ebc9d/lib/eventual/syntax_nodes.rb#L82-L91
train
vast/rokko
lib/rokko/task.rb
Rokko.Task.define
def define desc "Generate rokko documentation" task @name do # Find README file for `index.html` and delete it from `sources` if @options[:generate_index] readme_source = @sources.detect { |f| File.basename(f) =~ /README(\.(md|text|markdown|mdown|mkd|mkdn)$)?/i } readme = readme_source ? File.read(@sources.delete(readme_source)) : '' end # Run each file through Rokko and write output @sources.each do |filename| rokko = Rokko.new(filename, @sources, @options) out_dest = File.join(@dest, filename.sub(Regexp.new("#{File.extname(filename)}$"), ".html")) puts "rokko: #{filename} -> #{out_dest}" FileUtils.mkdir_p File.dirname(out_dest) File.open(out_dest, 'wb') { |fd| fd.write(rokko.to_html) } end # Generate index.html if needed if @options[:generate_index] require 'rokko/index_layout' out_dest = File.join(@dest, 'index.html') puts "rokko: #{out_dest}" File.open(out_dest, 'wb') { |fd| fd.write(IndexLayout.new(@sources, readme, @options).render) } end # Run specified file through rokko and use it as index if @options[:index] && source_index = @sources.find{|s| s == @options[:index]} rokko = Rokko.new(source_index, @sources, @options.merge(preserve_urls: true)) out_dest = File.join(@dest, 'index.html') puts "rokko: #{source_index} -> index.html" File.open(out_dest, 'wb') { |fd| fd.write(rokko.to_html) } end end end
ruby
def define desc "Generate rokko documentation" task @name do # Find README file for `index.html` and delete it from `sources` if @options[:generate_index] readme_source = @sources.detect { |f| File.basename(f) =~ /README(\.(md|text|markdown|mdown|mkd|mkdn)$)?/i } readme = readme_source ? File.read(@sources.delete(readme_source)) : '' end # Run each file through Rokko and write output @sources.each do |filename| rokko = Rokko.new(filename, @sources, @options) out_dest = File.join(@dest, filename.sub(Regexp.new("#{File.extname(filename)}$"), ".html")) puts "rokko: #{filename} -> #{out_dest}" FileUtils.mkdir_p File.dirname(out_dest) File.open(out_dest, 'wb') { |fd| fd.write(rokko.to_html) } end # Generate index.html if needed if @options[:generate_index] require 'rokko/index_layout' out_dest = File.join(@dest, 'index.html') puts "rokko: #{out_dest}" File.open(out_dest, 'wb') { |fd| fd.write(IndexLayout.new(@sources, readme, @options).render) } end # Run specified file through rokko and use it as index if @options[:index] && source_index = @sources.find{|s| s == @options[:index]} rokko = Rokko.new(source_index, @sources, @options.merge(preserve_urls: true)) out_dest = File.join(@dest, 'index.html') puts "rokko: #{source_index} -> index.html" File.open(out_dest, 'wb') { |fd| fd.write(rokko.to_html) } end end end
[ "def", "define", "desc", "\"Generate rokko documentation\"", "task", "@name", "do", "# Find README file for `index.html` and delete it from `sources`", "if", "@options", "[", ":generate_index", "]", "readme_source", "=", "@sources", ".", "detect", "{", "|", "f", "|", "File", ".", "basename", "(", "f", ")", "=~", "/", "\\.", "/i", "}", "readme", "=", "readme_source", "?", "File", ".", "read", "(", "@sources", ".", "delete", "(", "readme_source", ")", ")", ":", "''", "end", "# Run each file through Rokko and write output", "@sources", ".", "each", "do", "|", "filename", "|", "rokko", "=", "Rokko", ".", "new", "(", "filename", ",", "@sources", ",", "@options", ")", "out_dest", "=", "File", ".", "join", "(", "@dest", ",", "filename", ".", "sub", "(", "Regexp", ".", "new", "(", "\"#{File.extname(filename)}$\"", ")", ",", "\".html\"", ")", ")", "puts", "\"rokko: #{filename} -> #{out_dest}\"", "FileUtils", ".", "mkdir_p", "File", ".", "dirname", "(", "out_dest", ")", "File", ".", "open", "(", "out_dest", ",", "'wb'", ")", "{", "|", "fd", "|", "fd", ".", "write", "(", "rokko", ".", "to_html", ")", "}", "end", "# Generate index.html if needed", "if", "@options", "[", ":generate_index", "]", "require", "'rokko/index_layout'", "out_dest", "=", "File", ".", "join", "(", "@dest", ",", "'index.html'", ")", "puts", "\"rokko: #{out_dest}\"", "File", ".", "open", "(", "out_dest", ",", "'wb'", ")", "{", "|", "fd", "|", "fd", ".", "write", "(", "IndexLayout", ".", "new", "(", "@sources", ",", "readme", ",", "@options", ")", ".", "render", ")", "}", "end", "# Run specified file through rokko and use it as index", "if", "@options", "[", ":index", "]", "&&", "source_index", "=", "@sources", ".", "find", "{", "|", "s", "|", "s", "==", "@options", "[", ":index", "]", "}", "rokko", "=", "Rokko", ".", "new", "(", "source_index", ",", "@sources", ",", "@options", ".", "merge", "(", "preserve_urls", ":", "true", ")", ")", "out_dest", "=", "File", ".", "join", "(", "@dest", ",", "'index.html'", ")", "puts", "\"rokko: #{source_index} -> index.html\"", "File", ".", "open", "(", "out_dest", ",", "'wb'", ")", "{", "|", "fd", "|", "fd", ".", "write", "(", "rokko", ".", "to_html", ")", "}", "end", "end", "end" ]
Actually setup the task
[ "Actually", "setup", "the", "task" ]
37f451db3d0bd92151809fcaba5a88bb597bbcc0
https://github.com/vast/rokko/blob/37f451db3d0bd92151809fcaba5a88bb597bbcc0/lib/rokko/task.rb#L42-L77
train
brandonpittman/stocker
lib/stocker.rb
Stocker.Generator.new
def new(item, total) data = read_file data[item] = {'total' => total.to_i, 'min' => options[:minimum].to_i, 'url' => options[:url] || read_config['url'], 'checked' => Time.now} write_file(data) end
ruby
def new(item, total) data = read_file data[item] = {'total' => total.to_i, 'min' => options[:minimum].to_i, 'url' => options[:url] || read_config['url'], 'checked' => Time.now} write_file(data) end
[ "def", "new", "(", "item", ",", "total", ")", "data", "=", "read_file", "data", "[", "item", "]", "=", "{", "'total'", "=>", "total", ".", "to_i", ",", "'min'", "=>", "options", "[", ":minimum", "]", ".", "to_i", ",", "'url'", "=>", "options", "[", ":url", "]", "||", "read_config", "[", "'url'", "]", ",", "'checked'", "=>", "Time", ".", "now", "}", "write_file", "(", "data", ")", "end" ]
Creates a new item in the inventory @param item [String] The item to add to the inventory @param total [String] How many of the new item on hand @return [Hash] Returns a hash of the updated inventory and writes YAML to .stocker.yaml
[ "Creates", "a", "new", "item", "in", "the", "inventory" ]
f2251eb3dc10dda8068a5edc1822f7704e51bade
https://github.com/brandonpittman/stocker/blob/f2251eb3dc10dda8068a5edc1822f7704e51bade/lib/stocker.rb#L23-L27
train
brandonpittman/stocker
lib/stocker.rb
Stocker.Generator.delete
def delete(item) data = read_file match_name(item) data.delete(@@item) write_file(data) end
ruby
def delete(item) data = read_file match_name(item) data.delete(@@item) write_file(data) end
[ "def", "delete", "(", "item", ")", "data", "=", "read_file", "match_name", "(", "item", ")", "data", ".", "delete", "(", "@@item", ")", "write_file", "(", "data", ")", "end" ]
Deletes an item from the inventory. Stocker will attempt a "fuzzy match" of the item name. @param item [String] The item to delete from the inventory @return [Hash] Returns a hash of the updated inventory and writes YAML to .stocker.yaml
[ "Deletes", "an", "item", "from", "the", "inventory", ".", "Stocker", "will", "attempt", "a", "fuzzy", "match", "of", "the", "item", "name", "." ]
f2251eb3dc10dda8068a5edc1822f7704e51bade
https://github.com/brandonpittman/stocker/blob/f2251eb3dc10dda8068a5edc1822f7704e51bade/lib/stocker.rb#L34-L39
train
brandonpittman/stocker
lib/stocker.rb
Stocker.Generator.check
def check links = [] read_file.each do |key, value| value["checked"] = Time.now if value["total"] < value["min"] puts "You're running low on #{key}!" links << key end end links.uniq! links.each { |link| buy(link)} end
ruby
def check links = [] read_file.each do |key, value| value["checked"] = Time.now if value["total"] < value["min"] puts "You're running low on #{key}!" links << key end end links.uniq! links.each { |link| buy(link)} end
[ "def", "check", "links", "=", "[", "]", "read_file", ".", "each", "do", "|", "key", ",", "value", "|", "value", "[", "\"checked\"", "]", "=", "Time", ".", "now", "if", "value", "[", "\"total\"", "]", "<", "value", "[", "\"min\"", "]", "puts", "\"You're running low on #{key}!\"", "links", "<<", "key", "end", "end", "links", ".", "uniq!", "links", ".", "each", "{", "|", "link", "|", "buy", "(", "link", ")", "}", "end" ]
Checks the total number of items on hand against their acceptable minimum values and opens the URLs of any items running low in stock. @return Opens a link in default web browser if URL is set for low stock item
[ "Checks", "the", "total", "number", "of", "items", "on", "hand", "against", "their", "acceptable", "minimum", "values", "and", "opens", "the", "URLs", "of", "any", "items", "running", "low", "in", "stock", "." ]
f2251eb3dc10dda8068a5edc1822f7704e51bade
https://github.com/brandonpittman/stocker/blob/f2251eb3dc10dda8068a5edc1822f7704e51bade/lib/stocker.rb#L44-L55
train
brandonpittman/stocker
lib/stocker.rb
Stocker.Generator.total
def total(item, total) data = read_file match_name(item) data[@@item]["total"] = total.to_i time(item) write_file(data) end
ruby
def total(item, total) data = read_file match_name(item) data[@@item]["total"] = total.to_i time(item) write_file(data) end
[ "def", "total", "(", "item", ",", "total", ")", "data", "=", "read_file", "match_name", "(", "item", ")", "data", "[", "@@item", "]", "[", "\"total\"", "]", "=", "total", ".", "to_i", "time", "(", "item", ")", "write_file", "(", "data", ")", "end" ]
Set total of existing item in Stocker's inventory @param item [String] item to update @param total [String] total on hand
[ "Set", "total", "of", "existing", "item", "in", "Stocker", "s", "inventory" ]
f2251eb3dc10dda8068a5edc1822f7704e51bade
https://github.com/brandonpittman/stocker/blob/f2251eb3dc10dda8068a5edc1822f7704e51bade/lib/stocker.rb#L61-L67
train
brandonpittman/stocker
lib/stocker.rb
Stocker.Generator.url
def url(item, url) data = read_file match_name(item) data[@@item]["url"] = url time(item) write_file(data) end
ruby
def url(item, url) data = read_file match_name(item) data[@@item]["url"] = url time(item) write_file(data) end
[ "def", "url", "(", "item", ",", "url", ")", "data", "=", "read_file", "match_name", "(", "item", ")", "data", "[", "@@item", "]", "[", "\"url\"", "]", "=", "url", "time", "(", "item", ")", "write_file", "(", "data", ")", "end" ]
Set URL of existing item in Stocker's inventory @param item [String] item to update @param url [String] URL of item
[ "Set", "URL", "of", "existing", "item", "in", "Stocker", "s", "inventory" ]
f2251eb3dc10dda8068a5edc1822f7704e51bade
https://github.com/brandonpittman/stocker/blob/f2251eb3dc10dda8068a5edc1822f7704e51bade/lib/stocker.rb#L73-L79
train
brandonpittman/stocker
lib/stocker.rb
Stocker.Generator.min
def min(item, min) data = read_file match_name(item) data[@@item]["min"] = min.to_i write_file(data) end
ruby
def min(item, min) data = read_file match_name(item) data[@@item]["min"] = min.to_i write_file(data) end
[ "def", "min", "(", "item", ",", "min", ")", "data", "=", "read_file", "match_name", "(", "item", ")", "data", "[", "@@item", "]", "[", "\"min\"", "]", "=", "min", ".", "to_i", "write_file", "(", "data", ")", "end" ]
Set minimum acceptable amount of existing inventory item @param item [String] item to update @param min [String] acceptable minimum amount of item to always have on hand
[ "Set", "minimum", "acceptable", "amount", "of", "existing", "inventory", "item" ]
f2251eb3dc10dda8068a5edc1822f7704e51bade
https://github.com/brandonpittman/stocker/blob/f2251eb3dc10dda8068a5edc1822f7704e51bade/lib/stocker.rb#L93-L98
train
brandonpittman/stocker
lib/stocker.rb
Stocker.Generator.list
def list begin @header = [["", ""]] # @header = [[set_color("Item", :white), set_color("Total", :white)], [set_color("=================", :white), set_color("=====", :white)]] @green = [] @yellow = [] @yellow2 = [] @green2 = [] @red = [] @red2 = [] read_file.each do |key, value| if value['total'] > value['min'] @green += [[key.titlecase,value['total'], value['total']-value['min']]] elsif value['total'] == value['min'] @yellow += [[key.titlecase,value['total'], value['total']-value['min']]] else @red += [[key.titlecase,value['total'], value['total']-value['min']]] end end @green.sort_by! { |a,b,c| c } @yellow.sort_by! { |a,b,c| c } @red.sort_by! { |a,b,c| c } @green.reverse! @yellow.reverse! @red.reverse! @green.each { |a,b| @green2 += [[set_color(a, :green), set_color(b, :green)]] } @yellow.each { |a,b| @yellow2 += [[set_color(a, :yellow), set_color(b, :yellow)]] } @red.each { |a,b| @red2 += [[set_color(a, :red), set_color(b, :red)]] } print_table(@header + @green2 + @yellow2 + @red2,{indent: 2}) rescue Exception => e puts "Inventory empty" end end
ruby
def list begin @header = [["", ""]] # @header = [[set_color("Item", :white), set_color("Total", :white)], [set_color("=================", :white), set_color("=====", :white)]] @green = [] @yellow = [] @yellow2 = [] @green2 = [] @red = [] @red2 = [] read_file.each do |key, value| if value['total'] > value['min'] @green += [[key.titlecase,value['total'], value['total']-value['min']]] elsif value['total'] == value['min'] @yellow += [[key.titlecase,value['total'], value['total']-value['min']]] else @red += [[key.titlecase,value['total'], value['total']-value['min']]] end end @green.sort_by! { |a,b,c| c } @yellow.sort_by! { |a,b,c| c } @red.sort_by! { |a,b,c| c } @green.reverse! @yellow.reverse! @red.reverse! @green.each { |a,b| @green2 += [[set_color(a, :green), set_color(b, :green)]] } @yellow.each { |a,b| @yellow2 += [[set_color(a, :yellow), set_color(b, :yellow)]] } @red.each { |a,b| @red2 += [[set_color(a, :red), set_color(b, :red)]] } print_table(@header + @green2 + @yellow2 + @red2,{indent: 2}) rescue Exception => e puts "Inventory empty" end end
[ "def", "list", "begin", "@header", "=", "[", "[", "\"\"", ",", "\"\"", "]", "]", "# @header = [[set_color(\"Item\", :white), set_color(\"Total\", :white)], [set_color(\"=================\", :white), set_color(\"=====\", :white)]]", "@green", "=", "[", "]", "@yellow", "=", "[", "]", "@yellow2", "=", "[", "]", "@green2", "=", "[", "]", "@red", "=", "[", "]", "@red2", "=", "[", "]", "read_file", ".", "each", "do", "|", "key", ",", "value", "|", "if", "value", "[", "'total'", "]", ">", "value", "[", "'min'", "]", "@green", "+=", "[", "[", "key", ".", "titlecase", ",", "value", "[", "'total'", "]", ",", "value", "[", "'total'", "]", "-", "value", "[", "'min'", "]", "]", "]", "elsif", "value", "[", "'total'", "]", "==", "value", "[", "'min'", "]", "@yellow", "+=", "[", "[", "key", ".", "titlecase", ",", "value", "[", "'total'", "]", ",", "value", "[", "'total'", "]", "-", "value", "[", "'min'", "]", "]", "]", "else", "@red", "+=", "[", "[", "key", ".", "titlecase", ",", "value", "[", "'total'", "]", ",", "value", "[", "'total'", "]", "-", "value", "[", "'min'", "]", "]", "]", "end", "end", "@green", ".", "sort_by!", "{", "|", "a", ",", "b", ",", "c", "|", "c", "}", "@yellow", ".", "sort_by!", "{", "|", "a", ",", "b", ",", "c", "|", "c", "}", "@red", ".", "sort_by!", "{", "|", "a", ",", "b", ",", "c", "|", "c", "}", "@green", ".", "reverse!", "@yellow", ".", "reverse!", "@red", ".", "reverse!", "@green", ".", "each", "{", "|", "a", ",", "b", "|", "@green2", "+=", "[", "[", "set_color", "(", "a", ",", ":green", ")", ",", "set_color", "(", "b", ",", ":green", ")", "]", "]", "}", "@yellow", ".", "each", "{", "|", "a", ",", "b", "|", "@yellow2", "+=", "[", "[", "set_color", "(", "a", ",", ":yellow", ")", ",", "set_color", "(", "b", ",", ":yellow", ")", "]", "]", "}", "@red", ".", "each", "{", "|", "a", ",", "b", "|", "@red2", "+=", "[", "[", "set_color", "(", "a", ",", ":red", ")", ",", "set_color", "(", "b", ",", ":red", ")", "]", "]", "}", "print_table", "(", "@header", "+", "@green2", "+", "@yellow2", "+", "@red2", ",", "{", "indent", ":", "2", "}", ")", "rescue", "Exception", "=>", "e", "puts", "\"Inventory empty\"", "end", "end" ]
Print a list of all inventory items. Green items are well stocked. Yellow items are at minimum acceptable total. Red items are below minimum acceptable total.
[ "Print", "a", "list", "of", "all", "inventory", "items", ".", "Green", "items", "are", "well", "stocked", ".", "Yellow", "items", "are", "at", "minimum", "acceptable", "total", ".", "Red", "items", "are", "below", "minimum", "acceptable", "total", "." ]
f2251eb3dc10dda8068a5edc1822f7704e51bade
https://github.com/brandonpittman/stocker/blob/f2251eb3dc10dda8068a5edc1822f7704e51bade/lib/stocker.rb#L132-L164
train
mattmccray/gumdrop
lib/gumdrop/data.rb
Gumdrop.DataManager.parse_file
def parse_file(path, target_ext=nil) return nil if path.nil? return nil if File.directory? path _load_from_file path, target_ext # if File.directory? path # _load_from_directory path # else # _load_from_file path, target_ext # end end
ruby
def parse_file(path, target_ext=nil) return nil if path.nil? return nil if File.directory? path _load_from_file path, target_ext # if File.directory? path # _load_from_directory path # else # _load_from_file path, target_ext # end end
[ "def", "parse_file", "(", "path", ",", "target_ext", "=", "nil", ")", "return", "nil", "if", "path", ".", "nil?", "return", "nil", "if", "File", ".", "directory?", "path", "_load_from_file", "path", ",", "target_ext", "# if File.directory? path", "# _load_from_directory path", "# else", "# _load_from_file path, target_ext", "# end", "end" ]
Not used internally, but useful for external usage
[ "Not", "used", "internally", "but", "useful", "for", "external", "usage" ]
7c0998675dbc65e6c7fa0cd580ea0fc3167394fd
https://github.com/mattmccray/gumdrop/blob/7c0998675dbc65e6c7fa0cd580ea0fc3167394fd/lib/gumdrop/data.rb#L59-L68
train
michaelmior/mipper
lib/mipper/model.rb
MIPPeR.Model.build_pointer_array
def build_pointer_array(array, type) buffer = FFI::MemoryPointer.new type, array.length buffer.send("write_array_of_#{type}".to_sym, array) buffer end
ruby
def build_pointer_array(array, type) buffer = FFI::MemoryPointer.new type, array.length buffer.send("write_array_of_#{type}".to_sym, array) buffer end
[ "def", "build_pointer_array", "(", "array", ",", "type", ")", "buffer", "=", "FFI", "::", "MemoryPointer", ".", "new", "type", ",", "array", ".", "length", "buffer", ".", "send", "(", "\"write_array_of_#{type}\"", ".", "to_sym", ",", "array", ")", "buffer", "end" ]
Shortcut to build a C array from a Ruby array
[ "Shortcut", "to", "build", "a", "C", "array", "from", "a", "Ruby", "array" ]
4ab7f8b32c27f33fc5121756554a0a28d2077e06
https://github.com/michaelmior/mipper/blob/4ab7f8b32c27f33fc5121756554a0a28d2077e06/lib/mipper/model.rb#L82-L87
train
adamsanderson/has_default_association
lib/has_default_association.rb
HasDefaultAssociation.ClassMethods.has_default_association
def has_default_association *names, &default_proc opts = names.extract_options! opts.assert_valid_keys(:eager) names.each do |name| create_default_association(name, default_proc) add_default_association_callback(name) if opts[:eager] end end
ruby
def has_default_association *names, &default_proc opts = names.extract_options! opts.assert_valid_keys(:eager) names.each do |name| create_default_association(name, default_proc) add_default_association_callback(name) if opts[:eager] end end
[ "def", "has_default_association", "*", "names", ",", "&", "default_proc", "opts", "=", "names", ".", "extract_options!", "opts", ".", "assert_valid_keys", "(", ":eager", ")", "names", ".", "each", "do", "|", "name", "|", "create_default_association", "(", "name", ",", "default_proc", ")", "add_default_association_callback", "(", "name", ")", "if", "opts", "[", ":eager", "]", "end", "end" ]
Declare default associations for ActiveRecord models. # Build a new association on demand belongs_to :address has_default_association :address # Build a custom assocation on demand belongs_to :address has_default_association :address do |model| Address.new(:name => model.full_name) end =Options +eager+ will instantiate a default assocation when a model is initialized.
[ "Declare", "default", "associations", "for", "ActiveRecord", "models", "." ]
68d33e9d1fd470d164eb8ec9cdb312cbd32fd7b3
https://github.com/adamsanderson/has_default_association/blob/68d33e9d1fd470d164eb8ec9cdb312cbd32fd7b3/lib/has_default_association.rb#L26-L34
train
georgyangelov/vcs-toolkit
lib/vcs_toolkit/repository.rb
VCSToolkit.Repository.status
def status(commit, ignore: []) tree = get_object(commit.tree) unless commit.nil? Utils::Status.compare_tree_and_store tree, staging_area, object_store, ignore: ignore end
ruby
def status(commit, ignore: []) tree = get_object(commit.tree) unless commit.nil? Utils::Status.compare_tree_and_store tree, staging_area, object_store, ignore: ignore end
[ "def", "status", "(", "commit", ",", "ignore", ":", "[", "]", ")", "tree", "=", "get_object", "(", "commit", ".", "tree", ")", "unless", "commit", ".", "nil?", "Utils", "::", "Status", ".", "compare_tree_and_store", "tree", ",", "staging_area", ",", "object_store", ",", "ignore", ":", "ignore", "end" ]
Return new, changed and deleted files compared to a specific commit and the staging area. The return value is a hash with :created, :changed and :deleted keys.
[ "Return", "new", "changed", "and", "deleted", "files", "compared", "to", "a", "specific", "commit", "and", "the", "staging", "area", "." ]
9d73735da090a5e0f612aee04f423306fa512f38
https://github.com/georgyangelov/vcs-toolkit/blob/9d73735da090a5e0f612aee04f423306fa512f38/lib/vcs_toolkit/repository.rb#L89-L96
train
georgyangelov/vcs-toolkit
lib/vcs_toolkit/repository.rb
VCSToolkit.Repository.commit_status
def commit_status(base_commit, new_commit, ignore: []) base_tree = get_object(base_commit.tree) unless base_commit.nil? new_tree = get_object(new_commit.tree) unless new_commit.nil? Utils::Status.compare_trees base_tree, new_tree, object_store, ignore: ignore end
ruby
def commit_status(base_commit, new_commit, ignore: []) base_tree = get_object(base_commit.tree) unless base_commit.nil? new_tree = get_object(new_commit.tree) unless new_commit.nil? Utils::Status.compare_trees base_tree, new_tree, object_store, ignore: ignore end
[ "def", "commit_status", "(", "base_commit", ",", "new_commit", ",", "ignore", ":", "[", "]", ")", "base_tree", "=", "get_object", "(", "base_commit", ".", "tree", ")", "unless", "base_commit", ".", "nil?", "new_tree", "=", "get_object", "(", "new_commit", ".", "tree", ")", "unless", "new_commit", ".", "nil?", "Utils", "::", "Status", ".", "compare_trees", "base_tree", ",", "new_tree", ",", "object_store", ",", "ignore", ":", "ignore", "end" ]
Return new, changed and deleted files by comparing two commits. The return value is a hash with :created, :changed and :deleted keys.
[ "Return", "new", "changed", "and", "deleted", "files", "by", "comparing", "two", "commits", "." ]
9d73735da090a5e0f612aee04f423306fa512f38
https://github.com/georgyangelov/vcs-toolkit/blob/9d73735da090a5e0f612aee04f423306fa512f38/lib/vcs_toolkit/repository.rb#L104-L112
train
georgyangelov/vcs-toolkit
lib/vcs_toolkit/repository.rb
VCSToolkit.Repository.merge
def merge(commit_one, commit_two) common_ancestor = commit_one.common_ancestor(commit_two, object_store) commit_one_files = Hash[get_object(commit_one.tree).all_files(object_store).to_a] commit_two_files = Hash[get_object(commit_two.tree).all_files(object_store).to_a] if common_ancestor.nil? ancestor_files = {} else ancestor_files = Hash[get_object(common_ancestor.tree).all_files(object_store).to_a] end all_files = commit_one_files.keys | commit_two_files.keys | ancestor_files.keys merged = [] conflicted = [] all_files.each do |file| ancestor = ancestor_files.key?(file) ? get_object(ancestor_files[file]).content.lines : [] file_one = commit_one_files.key?(file) ? get_object(commit_one_files[file]).content.lines : [] file_two = commit_two_files.key?(file) ? get_object(commit_two_files[file]).content.lines : [] diff = VCSToolkit::Merge.three_way ancestor, file_one, file_two if diff.has_conflicts? conflicted << file elsif diff.has_changes? merged << file end content = diff.new_content("<<<<< #{commit_one.id}\n", ">>>>> #{commit_two.id}\n", "=====\n") if content.empty? staging_area.delete_file file if staging_area.file? file else staging_area.store file, content.join('') end end {merged: merged, conflicted: conflicted} end
ruby
def merge(commit_one, commit_two) common_ancestor = commit_one.common_ancestor(commit_two, object_store) commit_one_files = Hash[get_object(commit_one.tree).all_files(object_store).to_a] commit_two_files = Hash[get_object(commit_two.tree).all_files(object_store).to_a] if common_ancestor.nil? ancestor_files = {} else ancestor_files = Hash[get_object(common_ancestor.tree).all_files(object_store).to_a] end all_files = commit_one_files.keys | commit_two_files.keys | ancestor_files.keys merged = [] conflicted = [] all_files.each do |file| ancestor = ancestor_files.key?(file) ? get_object(ancestor_files[file]).content.lines : [] file_one = commit_one_files.key?(file) ? get_object(commit_one_files[file]).content.lines : [] file_two = commit_two_files.key?(file) ? get_object(commit_two_files[file]).content.lines : [] diff = VCSToolkit::Merge.three_way ancestor, file_one, file_two if diff.has_conflicts? conflicted << file elsif diff.has_changes? merged << file end content = diff.new_content("<<<<< #{commit_one.id}\n", ">>>>> #{commit_two.id}\n", "=====\n") if content.empty? staging_area.delete_file file if staging_area.file? file else staging_area.store file, content.join('') end end {merged: merged, conflicted: conflicted} end
[ "def", "merge", "(", "commit_one", ",", "commit_two", ")", "common_ancestor", "=", "commit_one", ".", "common_ancestor", "(", "commit_two", ",", "object_store", ")", "commit_one_files", "=", "Hash", "[", "get_object", "(", "commit_one", ".", "tree", ")", ".", "all_files", "(", "object_store", ")", ".", "to_a", "]", "commit_two_files", "=", "Hash", "[", "get_object", "(", "commit_two", ".", "tree", ")", ".", "all_files", "(", "object_store", ")", ".", "to_a", "]", "if", "common_ancestor", ".", "nil?", "ancestor_files", "=", "{", "}", "else", "ancestor_files", "=", "Hash", "[", "get_object", "(", "common_ancestor", ".", "tree", ")", ".", "all_files", "(", "object_store", ")", ".", "to_a", "]", "end", "all_files", "=", "commit_one_files", ".", "keys", "|", "commit_two_files", ".", "keys", "|", "ancestor_files", ".", "keys", "merged", "=", "[", "]", "conflicted", "=", "[", "]", "all_files", ".", "each", "do", "|", "file", "|", "ancestor", "=", "ancestor_files", ".", "key?", "(", "file", ")", "?", "get_object", "(", "ancestor_files", "[", "file", "]", ")", ".", "content", ".", "lines", ":", "[", "]", "file_one", "=", "commit_one_files", ".", "key?", "(", "file", ")", "?", "get_object", "(", "commit_one_files", "[", "file", "]", ")", ".", "content", ".", "lines", ":", "[", "]", "file_two", "=", "commit_two_files", ".", "key?", "(", "file", ")", "?", "get_object", "(", "commit_two_files", "[", "file", "]", ")", ".", "content", ".", "lines", ":", "[", "]", "diff", "=", "VCSToolkit", "::", "Merge", ".", "three_way", "ancestor", ",", "file_one", ",", "file_two", "if", "diff", ".", "has_conflicts?", "conflicted", "<<", "file", "elsif", "diff", ".", "has_changes?", "merged", "<<", "file", "end", "content", "=", "diff", ".", "new_content", "(", "\"<<<<< #{commit_one.id}\\n\"", ",", "\">>>>> #{commit_two.id}\\n\"", ",", "\"=====\\n\"", ")", "if", "content", ".", "empty?", "staging_area", ".", "delete_file", "file", "if", "staging_area", ".", "file?", "file", "else", "staging_area", ".", "store", "file", ",", "content", ".", "join", "(", "''", ")", "end", "end", "{", "merged", ":", "merged", ",", "conflicted", ":", "conflicted", "}", "end" ]
Merge two commits and save the changes to the staging area.
[ "Merge", "two", "commits", "and", "save", "the", "changes", "to", "the", "staging", "area", "." ]
9d73735da090a5e0f612aee04f423306fa512f38
https://github.com/georgyangelov/vcs-toolkit/blob/9d73735da090a5e0f612aee04f423306fa512f38/lib/vcs_toolkit/repository.rb#L129-L168
train
georgyangelov/vcs-toolkit
lib/vcs_toolkit/repository.rb
VCSToolkit.Repository.file_difference
def file_difference(file_path, commit) if staging_area.file? file_path file_lines = staging_area.fetch(file_path).lines file_lines.last << "\n" unless file_lines.last.nil? or file_lines.last.end_with? "\n" else file_lines = [] end tree = get_object commit.tree blob_name_and_id = tree.all_files(object_store).find { |file, _| file_path == file } if blob_name_and_id.nil? blob_lines = [] else blob = get_object blob_name_and_id.last blob_lines = blob.content.lines blob_lines.last << "\n" unless blob_lines.last.nil? or blob_lines.last.end_with? "\n" end Diff.from_sequences blob_lines, file_lines end
ruby
def file_difference(file_path, commit) if staging_area.file? file_path file_lines = staging_area.fetch(file_path).lines file_lines.last << "\n" unless file_lines.last.nil? or file_lines.last.end_with? "\n" else file_lines = [] end tree = get_object commit.tree blob_name_and_id = tree.all_files(object_store).find { |file, _| file_path == file } if blob_name_and_id.nil? blob_lines = [] else blob = get_object blob_name_and_id.last blob_lines = blob.content.lines blob_lines.last << "\n" unless blob_lines.last.nil? or blob_lines.last.end_with? "\n" end Diff.from_sequences blob_lines, file_lines end
[ "def", "file_difference", "(", "file_path", ",", "commit", ")", "if", "staging_area", ".", "file?", "file_path", "file_lines", "=", "staging_area", ".", "fetch", "(", "file_path", ")", ".", "lines", "file_lines", ".", "last", "<<", "\"\\n\"", "unless", "file_lines", ".", "last", ".", "nil?", "or", "file_lines", ".", "last", ".", "end_with?", "\"\\n\"", "else", "file_lines", "=", "[", "]", "end", "tree", "=", "get_object", "commit", ".", "tree", "blob_name_and_id", "=", "tree", ".", "all_files", "(", "object_store", ")", ".", "find", "{", "|", "file", ",", "_", "|", "file_path", "==", "file", "}", "if", "blob_name_and_id", ".", "nil?", "blob_lines", "=", "[", "]", "else", "blob", "=", "get_object", "blob_name_and_id", ".", "last", "blob_lines", "=", "blob", ".", "content", ".", "lines", "blob_lines", ".", "last", "<<", "\"\\n\"", "unless", "blob_lines", ".", "last", ".", "nil?", "or", "blob_lines", ".", "last", ".", "end_with?", "\"\\n\"", "end", "Diff", ".", "from_sequences", "blob_lines", ",", "file_lines", "end" ]
Return a list of changes between a file in the staging area and a specific commit. This method is just a tiny wrapper around VCSToolkit::Diff.from_sequences which loads the two files and splits them by lines beforehand. It also ensures that both files have \n at the end (otherwise the last two lines of the diff may be merged).
[ "Return", "a", "list", "of", "changes", "between", "a", "file", "in", "the", "staging", "area", "and", "a", "specific", "commit", "." ]
9d73735da090a5e0f612aee04f423306fa512f38
https://github.com/georgyangelov/vcs-toolkit/blob/9d73735da090a5e0f612aee04f423306fa512f38/lib/vcs_toolkit/repository.rb#L179-L200
train
jgrowl/omniauth-oauthio
lib/oauthio/client.rb
Oauthio.Client.me_url
def me_url(provider, params=nil) connection.build_url(options[:me_url].sub(/:provider/, provider), params). to_s end
ruby
def me_url(provider, params=nil) connection.build_url(options[:me_url].sub(/:provider/, provider), params). to_s end
[ "def", "me_url", "(", "provider", ",", "params", "=", "nil", ")", "connection", ".", "build_url", "(", "options", "[", ":me_url", "]", ".", "sub", "(", "/", "/", ",", "provider", ")", ",", "params", ")", ".", "to_s", "end" ]
Instantiate a new OAuth 2.0 client using the Client ID and Client Secret registered to your application. @param [String] client_id the client_id value @param [String] client_secret the client_secret value @param [Hash] opts the options to create the client with @option opts [String] :site the OAuth2 provider site host @option opts [String] :authorize_url ('/oauth/authorize') absolute or relative URL path to the Authorization endpoint @option opts [String] :token_url ('/oauth/token') absolute or relative URL path to the Token endpoint @option opts [Symbol] :token_method (:post) HTTP method to use to request token (:get or :post) @option opts [Hash] :connection_opts ({}) Hash of connection options to pass to initialize Faraday with @option opts [FixNum] :max_redirects (5) maximum number of redirects to follow @option opts [Boolean] :raise_errors (true) whether or not to raise an OAuth2::Error on responses with 400+ status codes @yield [builder] The Faraday connection builder
[ "Instantiate", "a", "new", "OAuth", "2", ".", "0", "client", "using", "the", "Client", "ID", "and", "Client", "Secret", "registered", "to", "your", "application", "." ]
3e6a338dccac764dce8b12673156924233dcc605
https://github.com/jgrowl/omniauth-oauthio/blob/3e6a338dccac764dce8b12673156924233dcc605/lib/oauthio/client.rb#L39-L42
train
redding/much-plugin
lib/much-plugin.rb
MuchPlugin.ClassMethods.included
def included(plugin_receiver) return if plugin_receiver.include?(self.much_plugin_included_detector) plugin_receiver.send(:include, self.much_plugin_included_detector) self.much_plugin_included_hooks.each do |hook| plugin_receiver.class_eval(&hook) end end
ruby
def included(plugin_receiver) return if plugin_receiver.include?(self.much_plugin_included_detector) plugin_receiver.send(:include, self.much_plugin_included_detector) self.much_plugin_included_hooks.each do |hook| plugin_receiver.class_eval(&hook) end end
[ "def", "included", "(", "plugin_receiver", ")", "return", "if", "plugin_receiver", ".", "include?", "(", "self", ".", "much_plugin_included_detector", ")", "plugin_receiver", ".", "send", "(", ":include", ",", "self", ".", "much_plugin_included_detector", ")", "self", ".", "much_plugin_included_hooks", ".", "each", "do", "|", "hook", "|", "plugin_receiver", ".", "class_eval", "(", "hook", ")", "end", "end" ]
install an included hook that first checks if this plugin's receiver mixin has already been included. If it has not been, include the receiver mixin and run all of the `plugin_included` hooks
[ "install", "an", "included", "hook", "that", "first", "checks", "if", "this", "plugin", "s", "receiver", "mixin", "has", "already", "been", "included", ".", "If", "it", "has", "not", "been", "include", "the", "receiver", "mixin", "and", "run", "all", "of", "the", "plugin_included", "hooks" ]
5df6dfbc2c66b53faa899359f4a528eda124bb86
https://github.com/redding/much-plugin/blob/5df6dfbc2c66b53faa899359f4a528eda124bb86/lib/much-plugin.rb#L14-L21
train
amberbit/amberbit-config
lib/amberbit-config/hash_struct.rb
AmberbitConfig.HashStruct.to_hash
def to_hash _copy = {} @table.each { |key, value| _copy[key] = value.is_a?(HashStruct) ? value.to_hash : value } _copy end
ruby
def to_hash _copy = {} @table.each { |key, value| _copy[key] = value.is_a?(HashStruct) ? value.to_hash : value } _copy end
[ "def", "to_hash", "_copy", "=", "{", "}", "@table", ".", "each", "{", "|", "key", ",", "value", "|", "_copy", "[", "key", "]", "=", "value", ".", "is_a?", "(", "HashStruct", ")", "?", "value", ".", "to_hash", ":", "value", "}", "_copy", "end" ]
Generates a nested Hash object which is a copy of existing configuration
[ "Generates", "a", "nested", "Hash", "object", "which", "is", "a", "copy", "of", "existing", "configuration" ]
cc392005c740d987ad44502d0eb6f9269a55bd4a
https://github.com/amberbit/amberbit-config/blob/cc392005c740d987ad44502d0eb6f9269a55bd4a/lib/amberbit-config/hash_struct.rb#L18-L22
train
amberbit/amberbit-config
lib/amberbit-config/hash_struct.rb
AmberbitConfig.HashStruct.check_hash_for_conflicts
def check_hash_for_conflicts(hash) raise HashArgumentError, 'It must be a hash' unless hash.is_a?(Hash) unless (conflicts = self.public_methods & hash.keys.map(&:to_sym)).empty? raise HashArgumentError, "Rename keys in order to avoid conflicts with internal calls: #{conflicts.join(', ')}" end end
ruby
def check_hash_for_conflicts(hash) raise HashArgumentError, 'It must be a hash' unless hash.is_a?(Hash) unless (conflicts = self.public_methods & hash.keys.map(&:to_sym)).empty? raise HashArgumentError, "Rename keys in order to avoid conflicts with internal calls: #{conflicts.join(', ')}" end end
[ "def", "check_hash_for_conflicts", "(", "hash", ")", "raise", "HashArgumentError", ",", "'It must be a hash'", "unless", "hash", ".", "is_a?", "(", "Hash", ")", "unless", "(", "conflicts", "=", "self", ".", "public_methods", "&", "hash", ".", "keys", ".", "map", "(", ":to_sym", ")", ")", ".", "empty?", "raise", "HashArgumentError", ",", "\"Rename keys in order to avoid conflicts with internal calls: #{conflicts.join(', ')}\"", "end", "end" ]
Checks if provided option is a hash and if the keys are not in confict with OpenStruct public methods.
[ "Checks", "if", "provided", "option", "is", "a", "hash", "and", "if", "the", "keys", "are", "not", "in", "confict", "with", "OpenStruct", "public", "methods", "." ]
cc392005c740d987ad44502d0eb6f9269a55bd4a
https://github.com/amberbit/amberbit-config/blob/cc392005c740d987ad44502d0eb6f9269a55bd4a/lib/amberbit-config/hash_struct.rb#L51-L57
train
andrewpthorp/unchained
lib/unchained/request.rb
Unchained.Request.get_resource
def get_resource(url, resource_class, params={}) resource_class.from_hash(get(url, params), client: self) end
ruby
def get_resource(url, resource_class, params={}) resource_class.from_hash(get(url, params), client: self) end
[ "def", "get_resource", "(", "url", ",", "resource_class", ",", "params", "=", "{", "}", ")", "resource_class", ".", "from_hash", "(", "get", "(", "url", ",", "params", ")", ",", "client", ":", "self", ")", "end" ]
If an API endpoint returns a single resource, not an Array of resources, we want to use this. Returns an instance of `resource_class`.
[ "If", "an", "API", "endpoint", "returns", "a", "single", "resource", "not", "an", "Array", "of", "resources", "we", "want", "to", "use", "this", "." ]
54db3bfdb41f141de95df9bb620cbd86de675d07
https://github.com/andrewpthorp/unchained/blob/54db3bfdb41f141de95df9bb620cbd86de675d07/lib/unchained/request.rb#L28-L30
train
andrewpthorp/unchained
lib/unchained/request.rb
Unchained.Request.get_resources
def get_resources(url, resource_class, params={}) get(url, params).map do |result| resource_class.from_hash(result, client: self) end end
ruby
def get_resources(url, resource_class, params={}) get(url, params).map do |result| resource_class.from_hash(result, client: self) end end
[ "def", "get_resources", "(", "url", ",", "resource_class", ",", "params", "=", "{", "}", ")", "get", "(", "url", ",", "params", ")", ".", "map", "do", "|", "result", "|", "resource_class", ".", "from_hash", "(", "result", ",", "client", ":", "self", ")", "end", "end" ]
If an API endpoint returns an Array of resources, we want to use this. Returns an array of `resource_classes`.
[ "If", "an", "API", "endpoint", "returns", "an", "Array", "of", "resources", "we", "want", "to", "use", "this", "." ]
54db3bfdb41f141de95df9bb620cbd86de675d07
https://github.com/andrewpthorp/unchained/blob/54db3bfdb41f141de95df9bb620cbd86de675d07/lib/unchained/request.rb#L35-L39
train
bcantin/auditing
lib/auditing/audit_relationship.rb
Auditing.AuditRelationship.audit_relationship_enabled
def audit_relationship_enabled(opts={}) include InstanceMethods # class_inheritable_accessor :audit_enabled_models # class_inheritable_accessor :field_names class_attribute :audit_enabled_models class_attribute :field_names self.audit_enabled_models = gather_models(opts) self.field_names = gather_assoc_fields_for_auditing(opts[:fields]) after_create :audit_relationship_create before_update :audit_relationship_update before_destroy :audit_relationship_destroy end
ruby
def audit_relationship_enabled(opts={}) include InstanceMethods # class_inheritable_accessor :audit_enabled_models # class_inheritable_accessor :field_names class_attribute :audit_enabled_models class_attribute :field_names self.audit_enabled_models = gather_models(opts) self.field_names = gather_assoc_fields_for_auditing(opts[:fields]) after_create :audit_relationship_create before_update :audit_relationship_update before_destroy :audit_relationship_destroy end
[ "def", "audit_relationship_enabled", "(", "opts", "=", "{", "}", ")", "include", "InstanceMethods", "# class_inheritable_accessor :audit_enabled_models", "# class_inheritable_accessor :field_names", "class_attribute", ":audit_enabled_models", "class_attribute", ":field_names", "self", ".", "audit_enabled_models", "=", "gather_models", "(", "opts", ")", "self", ".", "field_names", "=", "gather_assoc_fields_for_auditing", "(", "opts", "[", ":fields", "]", ")", "after_create", ":audit_relationship_create", "before_update", ":audit_relationship_update", "before_destroy", ":audit_relationship_destroy", "end" ]
AuditRelationship creates audits for a has_many relationship. @examples class Company < ActiveRecord::Base has_many :phone_numbers audit_enabled end class PhoneNumber < ActiveRecord::Base belongs_to :company audit_relationship_enabled end valid options include: :only => [(array of models)] an array of models to only send an audit to :except => [(array of models)] an array of models to not send an audit to :fields => [(array of field names)] an array of field names. Each field name will be one audit item
[ "AuditRelationship", "creates", "audits", "for", "a", "has_many", "relationship", "." ]
495b9e2d465c8263e7709623a003bb933ff540b7
https://github.com/bcantin/auditing/blob/495b9e2d465c8263e7709623a003bb933ff540b7/lib/auditing/audit_relationship.rb#L23-L38
train
blambeau/myrrha
lib/myrrha/coercions.rb
Myrrha.Coercions.delegate
def delegate(method, &convproc) convproc ||= lambda{|v,t| v.send(method) } upon(lambda{|v,t| v.respond_to?(method) }, convproc) end
ruby
def delegate(method, &convproc) convproc ||= lambda{|v,t| v.send(method) } upon(lambda{|v,t| v.respond_to?(method) }, convproc) end
[ "def", "delegate", "(", "method", ",", "&", "convproc", ")", "convproc", "||=", "lambda", "{", "|", "v", ",", "t", "|", "v", ".", "send", "(", "method", ")", "}", "upon", "(", "lambda", "{", "|", "v", ",", "t", "|", "v", ".", "respond_to?", "(", "method", ")", "}", ",", "convproc", ")", "end" ]
Adds an upon rule that works by delegation if the value responds to `method`. Example: Myrrha.coercions do |r| r.delegate(:to_foo) # is a shortcut for r.upon(lambda{|v,_| v.respond_to?(:to_foo)}){|v,_| v.to_foo} end
[ "Adds", "an", "upon", "rule", "that", "works", "by", "delegation", "if", "the", "value", "responds", "to", "method", "." ]
302f90d1bd6039410cbfbf87e90ff3f4e6abe9fe
https://github.com/blambeau/myrrha/blob/302f90d1bd6039410cbfbf87e90ff3f4e6abe9fe/lib/myrrha/coercions.rb#L100-L103
train
blambeau/myrrha
lib/myrrha/coercions.rb
Myrrha.Coercions.coercion
def coercion(source, target = main_target_domain, converter = nil, &convproc) @rules.send(@appender, [source, target, converter || convproc]) self end
ruby
def coercion(source, target = main_target_domain, converter = nil, &convproc) @rules.send(@appender, [source, target, converter || convproc]) self end
[ "def", "coercion", "(", "source", ",", "target", "=", "main_target_domain", ",", "converter", "=", "nil", ",", "&", "convproc", ")", "@rules", ".", "send", "(", "@appender", ",", "[", "source", ",", "target", ",", "converter", "||", "convproc", "]", ")", "self", "end" ]
Adds a coercion rule from a source to a target domain. The conversion can be provided through `converter` or via a block directly. See main documentation about recognized converters. Example: Myrrha.coercions do |r| # With an explicit proc r.coercion String, Integer, lambda{|v,t| Integer(v) } # With an implicit proc r.coercion(String, Float) do |v,t| Float(v) end end @param source [Domain] a source domain (mimicing Domain) @param target [Domain] a target domain (mimicing Domain) @param converter [Converter] an optional converter (mimic Converter) @param convproc [Proc] used when converter is not specified @return self
[ "Adds", "a", "coercion", "rule", "from", "a", "source", "to", "a", "target", "domain", "." ]
302f90d1bd6039410cbfbf87e90ff3f4e6abe9fe
https://github.com/blambeau/myrrha/blob/302f90d1bd6039410cbfbf87e90ff3f4e6abe9fe/lib/myrrha/coercions.rb#L132-L135
train
blambeau/myrrha
lib/myrrha/coercions.rb
Myrrha.Coercions.coerce
def coerce(value, target_domain = main_target_domain) return value if belongs_to?(value, target_domain) error = nil each_rule do |from,to,converter| next unless from.nil? or belongs_to?(value, from, target_domain) begin catch(:nextrule) do if to.nil? or subdomain?(to, target_domain) got = convert(value, target_domain, converter) return got elsif subdomain?(target_domain, to) got = convert(value, target_domain, converter) return got if belongs_to?(got, target_domain) end end rescue => ex error = ex unless error end end error_handler.call(value, target_domain, error) end
ruby
def coerce(value, target_domain = main_target_domain) return value if belongs_to?(value, target_domain) error = nil each_rule do |from,to,converter| next unless from.nil? or belongs_to?(value, from, target_domain) begin catch(:nextrule) do if to.nil? or subdomain?(to, target_domain) got = convert(value, target_domain, converter) return got elsif subdomain?(target_domain, to) got = convert(value, target_domain, converter) return got if belongs_to?(got, target_domain) end end rescue => ex error = ex unless error end end error_handler.call(value, target_domain, error) end
[ "def", "coerce", "(", "value", ",", "target_domain", "=", "main_target_domain", ")", "return", "value", "if", "belongs_to?", "(", "value", ",", "target_domain", ")", "error", "=", "nil", "each_rule", "do", "|", "from", ",", "to", ",", "converter", "|", "next", "unless", "from", ".", "nil?", "or", "belongs_to?", "(", "value", ",", "from", ",", "target_domain", ")", "begin", "catch", "(", ":nextrule", ")", "do", "if", "to", ".", "nil?", "or", "subdomain?", "(", "to", ",", "target_domain", ")", "got", "=", "convert", "(", "value", ",", "target_domain", ",", "converter", ")", "return", "got", "elsif", "subdomain?", "(", "target_domain", ",", "to", ")", "got", "=", "convert", "(", "value", ",", "target_domain", ",", "converter", ")", "return", "got", "if", "belongs_to?", "(", "got", ",", "target_domain", ")", "end", "end", "rescue", "=>", "ex", "error", "=", "ex", "unless", "error", "end", "end", "error_handler", ".", "call", "(", "value", ",", "target_domain", ",", "error", ")", "end" ]
Coerces `value` to an element of `target_domain` This method tries each coercion rule, then each fallback in turn. Rules for which source and target domain match are executed until one succeeds. A Myrrha::Error is raised if no rule matches or executes successfuly. @param [Object] value any ruby value @param [Domain] target_domain a target domain to convert to (mimic Domain) @return self
[ "Coerces", "value", "to", "an", "element", "of", "target_domain" ]
302f90d1bd6039410cbfbf87e90ff3f4e6abe9fe
https://github.com/blambeau/myrrha/blob/302f90d1bd6039410cbfbf87e90ff3f4e6abe9fe/lib/myrrha/coercions.rb#L170-L190
train
blambeau/myrrha
lib/myrrha/coercions.rb
Myrrha.Coercions.belongs_to?
def belongs_to?(value, domain, target_domain = domain) if domain.is_a?(Proc) and domain.arity==2 domain.call(value, target_domain) else domain.respond_to?(:===) && (domain === value) end end
ruby
def belongs_to?(value, domain, target_domain = domain) if domain.is_a?(Proc) and domain.arity==2 domain.call(value, target_domain) else domain.respond_to?(:===) && (domain === value) end end
[ "def", "belongs_to?", "(", "value", ",", "domain", ",", "target_domain", "=", "domain", ")", "if", "domain", ".", "is_a?", "(", "Proc", ")", "and", "domain", ".", "arity", "==", "2", "domain", ".", "call", "(", "value", ",", "target_domain", ")", "else", "domain", ".", "respond_to?", "(", ":===", ")", "&&", "(", "domain", "===", "value", ")", "end", "end" ]
Returns true if `value` can be considered as a valid element of the domain `domain`, false otherwise. @param [Object] value any ruby value @param [Domain] domain a domain (mimic Domain) @return [Boolean] true if `value` belongs to `domain`, false otherwise
[ "Returns", "true", "if", "value", "can", "be", "considered", "as", "a", "valid", "element", "of", "the", "domain", "domain", "false", "otherwise", "." ]
302f90d1bd6039410cbfbf87e90ff3f4e6abe9fe
https://github.com/blambeau/myrrha/blob/302f90d1bd6039410cbfbf87e90ff3f4e6abe9fe/lib/myrrha/coercions.rb#L215-L221
train
kynetx/Kynetx-Application-Manager-API
lib/kynetx_am_api/application.rb
KynetxAmApi.Application.endpoint
def endpoint(type, opts={}) options = { :extname => @name, :extdesc => "", :extauthor => @user.name, :force_build => 'N', :contents => "compiled", :format => 'json', :env => 'prod' } # Set type specific options case type.to_s when 'bookmarklet' options[:runtime] = "init.kobj.net/js/shared/kobj-static.js" when 'info_card' options[:image_url] = image_url('icard') options[:datasets] = "" when 'ie' options[:appguid] = @guid end options.merge!(opts) puts "ENDPOINT PARAMS: (#{type}): #{options.inspect}" if $DEBUG return @api.post_app_generate(@application_id, type.to_s, options) end
ruby
def endpoint(type, opts={}) options = { :extname => @name, :extdesc => "", :extauthor => @user.name, :force_build => 'N', :contents => "compiled", :format => 'json', :env => 'prod' } # Set type specific options case type.to_s when 'bookmarklet' options[:runtime] = "init.kobj.net/js/shared/kobj-static.js" when 'info_card' options[:image_url] = image_url('icard') options[:datasets] = "" when 'ie' options[:appguid] = @guid end options.merge!(opts) puts "ENDPOINT PARAMS: (#{type}): #{options.inspect}" if $DEBUG return @api.post_app_generate(@application_id, type.to_s, options) end
[ "def", "endpoint", "(", "type", ",", "opts", "=", "{", "}", ")", "options", "=", "{", ":extname", "=>", "@name", ",", ":extdesc", "=>", "\"\"", ",", ":extauthor", "=>", "@user", ".", "name", ",", ":force_build", "=>", "'N'", ",", ":contents", "=>", "\"compiled\"", ",", ":format", "=>", "'json'", ",", ":env", "=>", "'prod'", "}", "# Set type specific options", "case", "type", ".", "to_s", "when", "'bookmarklet'", "options", "[", ":runtime", "]", "=", "\"init.kobj.net/js/shared/kobj-static.js\"", "when", "'info_card'", "options", "[", ":image_url", "]", "=", "image_url", "(", "'icard'", ")", "options", "[", ":datasets", "]", "=", "\"\"", "when", "'ie'", "options", "[", ":appguid", "]", "=", "@guid", "end", "options", ".", "merge!", "(", "opts", ")", "puts", "\"ENDPOINT PARAMS: (#{type}): #{options.inspect}\"", "if", "$DEBUG", "return", "@api", ".", "post_app_generate", "(", "@application_id", ",", "type", ".", "to_s", ",", "options", ")", "end" ]
Returns an endpoint type is a String or Symbol of one of the following: :chrome :ie :firefox :info_card :bookmarklet :sitetags opts is a Hash of options that has the following keys: (see Kynetx App Management API documentation on "generate" for more information) - :extname (endpoint name - defaults to app name.) - :extauthor (endpoint author - defaults to user generating the endpoint.) - :extdesc (endpoint description - defaults to empty.) - :force_build ('Y' or 'N' force a regeneration of the endpoint - defaults to 'N'.) - :contents ( 'compiled' or 'src' specifies whether you want the endpoint or the source code of the endpoint - defaults to 'compiled'.) - :format ('url' or 'json' specifies how the endpoint is returned - default is 'json' which returns a Base64 encoded data string.) - :datasets (used for infocards - defaults to empty) - :env ('dev' or 'prod' specifies whether to run the development or production version of the app - defaults to 'prod'.) - :image_url (a fully qualified url to the image that will be used for the infocard. It must be a 240x160 jpg - defaults to a cropped version of the app image in appBuilder.) - :runtime (specific runtime to be used. This only works with bookmarklets - defaults to init.kobj.net/js/shared/kobj-static.js ) Returns a hash formatted as follows: {:data => "endpoint as specified in the :format option", :file_name => "filename.*", :content_type => 'content type', :errors => [] }
[ "Returns", "an", "endpoint" ]
fe96ad8aca56fef99734416cc3a7d29ee6f24d57
https://github.com/kynetx/Kynetx-Application-Manager-API/blob/fe96ad8aca56fef99734416cc3a7d29ee6f24d57/lib/kynetx_am_api/application.rb#L217-L243
train
mark-d-holmberg/handcart
app/models/handcart/concerns/handcarts.rb
Handcart::Concerns::Handcarts.ClassMethods.handcart_show_path
def handcart_show_path(handcart) if Handcart.handcart_show_path.present? # Load it straight from the config "/#{Handcart.handcart_show_path}/#{handcart.to_param}" else if Rails.application.routes.url_helpers.respond_to?("#{Handcart.handcart_class.model_name.singular}_path".to_sym) # Is there one already defined Rails.application.routes.url_helpers.send("#{Handcart.handcart_class.model_name.singular}_path", handcart.to_param) else # Shot in the dark "/#{Handcart.handcart_class.model_name.route_key}/#{handcart.to_param}" end end end
ruby
def handcart_show_path(handcart) if Handcart.handcart_show_path.present? # Load it straight from the config "/#{Handcart.handcart_show_path}/#{handcart.to_param}" else if Rails.application.routes.url_helpers.respond_to?("#{Handcart.handcart_class.model_name.singular}_path".to_sym) # Is there one already defined Rails.application.routes.url_helpers.send("#{Handcart.handcart_class.model_name.singular}_path", handcart.to_param) else # Shot in the dark "/#{Handcart.handcart_class.model_name.route_key}/#{handcart.to_param}" end end end
[ "def", "handcart_show_path", "(", "handcart", ")", "if", "Handcart", ".", "handcart_show_path", ".", "present?", "# Load it straight from the config", "\"/#{Handcart.handcart_show_path}/#{handcart.to_param}\"", "else", "if", "Rails", ".", "application", ".", "routes", ".", "url_helpers", ".", "respond_to?", "(", "\"#{Handcart.handcart_class.model_name.singular}_path\"", ".", "to_sym", ")", "# Is there one already defined", "Rails", ".", "application", ".", "routes", ".", "url_helpers", ".", "send", "(", "\"#{Handcart.handcart_class.model_name.singular}_path\"", ",", "handcart", ".", "to_param", ")", "else", "# Shot in the dark", "\"/#{Handcart.handcart_class.model_name.route_key}/#{handcart.to_param}\"", "end", "end", "end" ]
Try to formulate a path to view the handcart show page
[ "Try", "to", "formulate", "a", "path", "to", "view", "the", "handcart", "show", "page" ]
9f9c7484db007066357c71c9c50f3342aab59c11
https://github.com/mark-d-holmberg/handcart/blob/9f9c7484db007066357c71c9c50f3342aab59c11/app/models/handcart/concerns/handcarts.rb#L14-L27
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/post_fields_controller.rb
LatoBlog.Back::PostFieldsController.destroy_relay_field
def destroy_relay_field # find post field child_field = LatoBlog::PostField.find_by(id: params[:id]) @post_field = child_field.post_field unless @post_field @error = true respond_to { |r| r.js } end # find post field child and destroy it unless child_field.destroy @error = true respond_to { |r| r.js } end # send response to client @error = false respond_to { |r| r.js } end
ruby
def destroy_relay_field # find post field child_field = LatoBlog::PostField.find_by(id: params[:id]) @post_field = child_field.post_field unless @post_field @error = true respond_to { |r| r.js } end # find post field child and destroy it unless child_field.destroy @error = true respond_to { |r| r.js } end # send response to client @error = false respond_to { |r| r.js } end
[ "def", "destroy_relay_field", "# find post field", "child_field", "=", "LatoBlog", "::", "PostField", ".", "find_by", "(", "id", ":", "params", "[", ":id", "]", ")", "@post_field", "=", "child_field", ".", "post_field", "unless", "@post_field", "@error", "=", "true", "respond_to", "{", "|", "r", "|", "r", ".", "js", "}", "end", "# find post field child and destroy it", "unless", "child_field", ".", "destroy", "@error", "=", "true", "respond_to", "{", "|", "r", "|", "r", ".", "js", "}", "end", "# send response to client", "@error", "=", "false", "respond_to", "{", "|", "r", "|", "r", ".", "js", "}", "end" ]
This function destroy a post for the field.
[ "This", "function", "destroy", "a", "post", "for", "the", "field", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/post_fields_controller.rb#L67-L83
train
dannysmith/guard-shopifytheme
lib/guard/shopifytheme.rb
Guard.Shopifytheme.start
def start if File.exist? 'config.yml' Notifier.notify "Watching for changes to Shopify Theme" else data = <<-EOF --- :api_key: YOUR_API_KEY :password: YOUR_PASSWORD :store: YOURSHOP.myshopify.com :theme_id: 'YOUR_THEME_ID' :ignore_files: - README.md - CHANGELOG.md EOF File.open('./config.yml', "w") { |file| file.write data } Notifier.notify "Created config.yml. Remember to add your Shopify details to it." end end
ruby
def start if File.exist? 'config.yml' Notifier.notify "Watching for changes to Shopify Theme" else data = <<-EOF --- :api_key: YOUR_API_KEY :password: YOUR_PASSWORD :store: YOURSHOP.myshopify.com :theme_id: 'YOUR_THEME_ID' :ignore_files: - README.md - CHANGELOG.md EOF File.open('./config.yml', "w") { |file| file.write data } Notifier.notify "Created config.yml. Remember to add your Shopify details to it." end end
[ "def", "start", "if", "File", ".", "exist?", "'config.yml'", "Notifier", ".", "notify", "\"Watching for changes to Shopify Theme\"", "else", "data", "=", "<<-EOF", "EOF", "File", ".", "open", "(", "'./config.yml'", ",", "\"w\"", ")", "{", "|", "file", "|", "file", ".", "write", "data", "}", "Notifier", ".", "notify", "\"Created config.yml. Remember to add your Shopify details to it.\"", "end", "end" ]
VERSION = "0.0.1" Called once when Guard starts. Please override initialize method to init stuff. @raise [:task_has_failed] when start has failed @return [Object] the task result
[ "VERSION", "=", "0", ".", "0", ".", "1", "Called", "once", "when", "Guard", "starts", ".", "Please", "override", "initialize", "method", "to", "init", "stuff", "." ]
bb30fdb228f8f370ab9a6aa5b819a1347c2c1249
https://github.com/dannysmith/guard-shopifytheme/blob/bb30fdb228f8f370ab9a6aa5b819a1347c2c1249/lib/guard/shopifytheme.rb#L20-L37
train
fenton-project/fenton_shell
lib/fenton_shell/project.rb
FentonShell.Project.create
def create(global_options, options) status, body = project_create(global_options, options) if status == 201 save_message(create_success_message(body)) true else parse_message(body) false end end
ruby
def create(global_options, options) status, body = project_create(global_options, options) if status == 201 save_message(create_success_message(body)) true else parse_message(body) false end end
[ "def", "create", "(", "global_options", ",", "options", ")", "status", ",", "body", "=", "project_create", "(", "global_options", ",", "options", ")", "if", "status", "==", "201", "save_message", "(", "create_success_message", "(", "body", ")", ")", "true", "else", "parse_message", "(", "body", ")", "false", "end", "end" ]
Creates a new project on fenton server by sending a post request with json from the command line to create the project @param global_options [Hash] global command line options @param options [Hash] json fields to send to fenton server @return [String] success or failure message
[ "Creates", "a", "new", "project", "on", "fenton", "server", "by", "sending", "a", "post", "request", "with", "json", "from", "the", "command", "line", "to", "create", "the", "project" ]
6e1d76186fa7ee7a3be141afad9361e3a3e0ec91
https://github.com/fenton-project/fenton_shell/blob/6e1d76186fa7ee7a3be141afad9361e3a3e0ec91/lib/fenton_shell/project.rb#L15-L25
train
fenton-project/fenton_shell
lib/fenton_shell/project.rb
FentonShell.Project.project_json
def project_json(options) { project: { name: options[:name], description: options[:description], passphrase: options[:passphrase], key: options[:key], organization: options[:organization] } }.to_json end
ruby
def project_json(options) { project: { name: options[:name], description: options[:description], passphrase: options[:passphrase], key: options[:key], organization: options[:organization] } }.to_json end
[ "def", "project_json", "(", "options", ")", "{", "project", ":", "{", "name", ":", "options", "[", ":name", "]", ",", "description", ":", "options", "[", ":description", "]", ",", "passphrase", ":", "options", "[", ":passphrase", "]", ",", "key", ":", "options", "[", ":key", "]", ",", "organization", ":", "options", "[", ":organization", "]", "}", "}", ".", "to_json", "end" ]
Formulates the project json for the post request @param options [Hash] fields from fenton command line @return [String] json created from the options hash
[ "Formulates", "the", "project", "json", "for", "the", "post", "request" ]
6e1d76186fa7ee7a3be141afad9361e3a3e0ec91
https://github.com/fenton-project/fenton_shell/blob/6e1d76186fa7ee7a3be141afad9361e3a3e0ec91/lib/fenton_shell/project.rb#L62-L72
train
thriventures/storage_room_gem
lib/storage_room/resource.rb
StorageRoom.Resource.reload
def reload(url = nil, parameters = {}) httparty = self.class.get(url || self[:@url], StorageRoom.request_options.merge(parameters)) hash = httparty.parsed_response.first[1] reset! set_from_response_data(hash) true end
ruby
def reload(url = nil, parameters = {}) httparty = self.class.get(url || self[:@url], StorageRoom.request_options.merge(parameters)) hash = httparty.parsed_response.first[1] reset! set_from_response_data(hash) true end
[ "def", "reload", "(", "url", "=", "nil", ",", "parameters", "=", "{", "}", ")", "httparty", "=", "self", ".", "class", ".", "get", "(", "url", "||", "self", "[", ":@url", "]", ",", "StorageRoom", ".", "request_options", ".", "merge", "(", "parameters", ")", ")", "hash", "=", "httparty", ".", "parsed_response", ".", "first", "[", "1", "]", "reset!", "set_from_response_data", "(", "hash", ")", "true", "end" ]
Reload an object from the API. Optionally pass an URL.
[ "Reload", "an", "object", "from", "the", "API", ".", "Optionally", "pass", "an", "URL", "." ]
cadf132b865ff82f7b09fadfec1d294a714c6728
https://github.com/thriventures/storage_room_gem/blob/cadf132b865ff82f7b09fadfec1d294a714c6728/lib/storage_room/resource.rb#L31-L37
train
d11wtq/rdo
lib/rdo/connection.rb
RDO.Connection.debug
def debug raise ArgumentError, "RDO::Connection#debug requires a block" unless block_given? reset, logger.level = logger.level, Logger::DEBUG yield ensure logger.level = reset end
ruby
def debug raise ArgumentError, "RDO::Connection#debug requires a block" unless block_given? reset, logger.level = logger.level, Logger::DEBUG yield ensure logger.level = reset end
[ "def", "debug", "raise", "ArgumentError", ",", "\"RDO::Connection#debug requires a block\"", "unless", "block_given?", "reset", ",", "logger", ".", "level", "=", "logger", ".", "level", ",", "Logger", "::", "DEBUG", "yield", "ensure", "logger", ".", "level", "=", "reset", "end" ]
Use debug log level in the context of a block.
[ "Use", "debug", "log", "level", "in", "the", "context", "of", "a", "block", "." ]
91fe0c70cbce9947b879141c0f1001b8c4eeef19
https://github.com/d11wtq/rdo/blob/91fe0c70cbce9947b879141c0f1001b8c4eeef19/lib/rdo/connection.rb#L131-L139
train
d11wtq/rdo
lib/rdo/connection.rb
RDO.Connection.normalize_options
def normalize_options(options) case options when Hash Hash[options.map{|k,v| [k.respond_to?(:to_sym) ? k.to_sym : k, v]}].tap do |opts| opts[:driver] = opts[:driver].to_s if opts[:driver] end when String, URI parse_connection_uri(options) else raise RDO::Exception, "Unsupported connection argument format: #{options.class.name}" end end
ruby
def normalize_options(options) case options when Hash Hash[options.map{|k,v| [k.respond_to?(:to_sym) ? k.to_sym : k, v]}].tap do |opts| opts[:driver] = opts[:driver].to_s if opts[:driver] end when String, URI parse_connection_uri(options) else raise RDO::Exception, "Unsupported connection argument format: #{options.class.name}" end end
[ "def", "normalize_options", "(", "options", ")", "case", "options", "when", "Hash", "Hash", "[", "options", ".", "map", "{", "|", "k", ",", "v", "|", "[", "k", ".", "respond_to?", "(", ":to_sym", ")", "?", "k", ".", "to_sym", ":", "k", ",", "v", "]", "}", "]", ".", "tap", "do", "|", "opts", "|", "opts", "[", ":driver", "]", "=", "opts", "[", ":driver", "]", ".", "to_s", "if", "opts", "[", ":driver", "]", "end", "when", "String", ",", "URI", "parse_connection_uri", "(", "options", ")", "else", "raise", "RDO", "::", "Exception", ",", "\"Unsupported connection argument format: #{options.class.name}\"", "end", "end" ]
Normalizes the given options String or Hash into a Symbol-keyed Hash. @param [Object] options either a String, a URI or a Hash @return [Hash] a Symbol-keyed Hash
[ "Normalizes", "the", "given", "options", "String", "or", "Hash", "into", "a", "Symbol", "-", "keyed", "Hash", "." ]
91fe0c70cbce9947b879141c0f1001b8c4eeef19
https://github.com/d11wtq/rdo/blob/91fe0c70cbce9947b879141c0f1001b8c4eeef19/lib/rdo/connection.rb#L150-L162
train
vinsol/Unified-Payments
lib/generators/unified_payment/install_generator.rb
UnifiedPayment.InstallGenerator.create_migrations
def create_migrations Dir["#{self.class.source_root}/migrations/*.rb"].sort.each do |filepath| name = File.basename(filepath) template "migrations/#{name}", "db/migrate/#{name}" sleep 1 end end
ruby
def create_migrations Dir["#{self.class.source_root}/migrations/*.rb"].sort.each do |filepath| name = File.basename(filepath) template "migrations/#{name}", "db/migrate/#{name}" sleep 1 end end
[ "def", "create_migrations", "Dir", "[", "\"#{self.class.source_root}/migrations/*.rb\"", "]", ".", "sort", ".", "each", "do", "|", "filepath", "|", "name", "=", "File", ".", "basename", "(", "filepath", ")", "template", "\"migrations/#{name}\"", ",", "\"db/migrate/#{name}\"", "sleep", "1", "end", "end" ]
Generator Code. Remember this is just suped-up Thor so methods are executed in order
[ "Generator", "Code", ".", "Remember", "this", "is", "just", "suped", "-", "up", "Thor", "so", "methods", "are", "executed", "in", "order" ]
2cd3f984ce45a2add0a7754aa48d18a2fbf87205
https://github.com/vinsol/Unified-Payments/blob/2cd3f984ce45a2add0a7754aa48d18a2fbf87205/lib/generators/unified_payment/install_generator.rb#L18-L24
train
Nanosim-LIG/ffi-bitmask
lib/ffi/bitmask.rb
FFI.Bitmask.to_native
def to_native(query, ctx) return 0 if query.nil? flat_query = [query].flatten flat_query.inject(0) do |val, o| case o when Symbol v = @kv_map[o] raise ArgumentError, "invalid bitmask value, #{o.inspect}" unless v val |= v when Integer val |= o when ->(obj) { obj.respond_to?(:to_int) } val |= o.to_int else raise ArgumentError, "invalid bitmask value, #{o.inspect}" end end end
ruby
def to_native(query, ctx) return 0 if query.nil? flat_query = [query].flatten flat_query.inject(0) do |val, o| case o when Symbol v = @kv_map[o] raise ArgumentError, "invalid bitmask value, #{o.inspect}" unless v val |= v when Integer val |= o when ->(obj) { obj.respond_to?(:to_int) } val |= o.to_int else raise ArgumentError, "invalid bitmask value, #{o.inspect}" end end end
[ "def", "to_native", "(", "query", ",", "ctx", ")", "return", "0", "if", "query", ".", "nil?", "flat_query", "=", "[", "query", "]", ".", "flatten", "flat_query", ".", "inject", "(", "0", ")", "do", "|", "val", ",", "o", "|", "case", "o", "when", "Symbol", "v", "=", "@kv_map", "[", "o", "]", "raise", "ArgumentError", ",", "\"invalid bitmask value, #{o.inspect}\"", "unless", "v", "val", "|=", "v", "when", "Integer", "val", "|=", "o", "when", "->", "(", "obj", ")", "{", "obj", ".", "respond_to?", "(", ":to_int", ")", "}", "val", "|=", "o", ".", "to_int", "else", "raise", "ArgumentError", ",", "\"invalid bitmask value, #{o.inspect}\"", "end", "end", "end" ]
Get the native value of a bitmask @overload to_native(query, ctx) @param [Symbol, Integer, #to_int] query @param ctx unused @return [Integer] value of a bitmask @overload to_native(query, ctx) @param [Array<Symbol, Integer, #to_int>] query @param ctx unused @return [Integer] value of a bitmask
[ "Get", "the", "native", "value", "of", "a", "bitmask" ]
ee891f00d28223494e45574c7b6663fc0f67f5ef
https://github.com/Nanosim-LIG/ffi-bitmask/blob/ee891f00d28223494e45574c7b6663fc0f67f5ef/lib/ffi/bitmask.rb#L151-L168
train
PeterCamilleri/format_output
lib/format_output/builders/column_builder.rb
FormatOutput.ColumnBuilder.render
def render results, column_widths = [], get_column_widths rows.times { |row_index| results << render_row(row_index, column_widths)} @page_data.clear results end
ruby
def render results, column_widths = [], get_column_widths rows.times { |row_index| results << render_row(row_index, column_widths)} @page_data.clear results end
[ "def", "render", "results", ",", "column_widths", "=", "[", "]", ",", "get_column_widths", "rows", ".", "times", "{", "|", "row_index", "|", "results", "<<", "render_row", "(", "row_index", ",", "column_widths", ")", "}", "@page_data", ".", "clear", "results", "end" ]
Render the page as an array of strings.
[ "Render", "the", "page", "as", "an", "array", "of", "strings", "." ]
95dac24bd21f618a74bb665a44235491d725e1b7
https://github.com/PeterCamilleri/format_output/blob/95dac24bd21f618a74bb665a44235491d725e1b7/lib/format_output/builders/column_builder.rb#L32-L39
train
PeterCamilleri/format_output
lib/format_output/builders/column_builder.rb
FormatOutput.ColumnBuilder.add_a_row
def add_a_row new_rows = rows + 1 pool, @page_data = @page_data.flatten, [] until pool.empty? @page_data << pool.shift(new_rows) end end
ruby
def add_a_row new_rows = rows + 1 pool, @page_data = @page_data.flatten, [] until pool.empty? @page_data << pool.shift(new_rows) end end
[ "def", "add_a_row", "new_rows", "=", "rows", "+", "1", "pool", ",", "@page_data", "=", "@page_data", ".", "flatten", ",", "[", "]", "until", "pool", ".", "empty?", "@page_data", "<<", "pool", ".", "shift", "(", "new_rows", ")", "end", "end" ]
Add a row to the page, moving items as needed.
[ "Add", "a", "row", "to", "the", "page", "moving", "items", "as", "needed", "." ]
95dac24bd21f618a74bb665a44235491d725e1b7
https://github.com/PeterCamilleri/format_output/blob/95dac24bd21f618a74bb665a44235491d725e1b7/lib/format_output/builders/column_builder.rb#L64-L71
train
NUBIC/aker
lib/aker/cas/rack_proxy_callback.rb
Aker::Cas.RackProxyCallback.call
def call(env) return receive(env) if env["PATH_INFO"] == RECEIVE_PATH return retrieve(env) if env["PATH_INFO"] == RETRIEVE_PATH @app.call(env) end
ruby
def call(env) return receive(env) if env["PATH_INFO"] == RECEIVE_PATH return retrieve(env) if env["PATH_INFO"] == RETRIEVE_PATH @app.call(env) end
[ "def", "call", "(", "env", ")", "return", "receive", "(", "env", ")", "if", "env", "[", "\"PATH_INFO\"", "]", "==", "RECEIVE_PATH", "return", "retrieve", "(", "env", ")", "if", "env", "[", "\"PATH_INFO\"", "]", "==", "RETRIEVE_PATH", "@app", ".", "call", "(", "env", ")", "end" ]
Create a new instance of the middleware. @param [#call] app the next rack application in the chain. @param [Hash] options @option options [String] :store the file where the middleware will store the received PGTs until they are retrieved. Handles a single request in the manner specified in the class overview. @param [Hash] env the rack environment for the request. @return [Array] an appropriate rack response.
[ "Create", "a", "new", "instance", "of", "the", "middleware", "." ]
ff43606a8812e38f96bbe71b46e7f631cbeacf1c
https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/cas/rack_proxy_callback.rb#L66-L70
train
NUBIC/aker
lib/aker/cas/rack_proxy_callback.rb
Aker::Cas.RackProxyCallback.store_iou
def store_iou(pgt_iou, pgt) pstore = open_pstore pstore.transaction do pstore[pgt_iou] = pgt end end
ruby
def store_iou(pgt_iou, pgt) pstore = open_pstore pstore.transaction do pstore[pgt_iou] = pgt end end
[ "def", "store_iou", "(", "pgt_iou", ",", "pgt", ")", "pstore", "=", "open_pstore", "pstore", ".", "transaction", "do", "pstore", "[", "pgt_iou", "]", "=", "pgt", "end", "end" ]
Associates the given PGTIOU and PGT. @param [String] pgt_iou @param [String] pgt @return [void]
[ "Associates", "the", "given", "PGTIOU", "and", "PGT", "." ]
ff43606a8812e38f96bbe71b46e7f631cbeacf1c
https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/cas/rack_proxy_callback.rb#L96-L102
train
NUBIC/aker
lib/aker/cas/rack_proxy_callback.rb
Aker::Cas.RackProxyCallback.resolve_iou
def resolve_iou(pgt_iou) pstore = open_pstore pgt = nil pstore.transaction do pgt = pstore[pgt_iou] pstore.delete(pgt_iou) if pgt end pgt end
ruby
def resolve_iou(pgt_iou) pstore = open_pstore pgt = nil pstore.transaction do pgt = pstore[pgt_iou] pstore.delete(pgt_iou) if pgt end pgt end
[ "def", "resolve_iou", "(", "pgt_iou", ")", "pstore", "=", "open_pstore", "pgt", "=", "nil", "pstore", ".", "transaction", "do", "pgt", "=", "pstore", "[", "pgt_iou", "]", "pstore", ".", "delete", "(", "pgt_iou", ")", "if", "pgt", "end", "pgt", "end" ]
Finds the PGT for the given PGTIOU. If there isn't one, it returns nil. If there is one, it deletes it from the store before returning it. @param [String] pgt_iou @return [String,nil]
[ "Finds", "the", "PGT", "for", "the", "given", "PGTIOU", ".", "If", "there", "isn", "t", "one", "it", "returns", "nil", ".", "If", "there", "is", "one", "it", "deletes", "it", "from", "the", "store", "before", "returning", "it", "." ]
ff43606a8812e38f96bbe71b46e7f631cbeacf1c
https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/cas/rack_proxy_callback.rb#L111-L121
train
mhluska/quadrigacx
lib/quadrigacx/client/private.rb
QuadrigaCX.Private.withdraw
def withdraw(coin, params = {}) raise ConfigurationError.new('No coin type specified') unless coin raise ConfigurationError.new('Invalid coin type specified') unless Coin.valid?(coin) request(:post, "/#{coin}_withdrawal", params) end
ruby
def withdraw(coin, params = {}) raise ConfigurationError.new('No coin type specified') unless coin raise ConfigurationError.new('Invalid coin type specified') unless Coin.valid?(coin) request(:post, "/#{coin}_withdrawal", params) end
[ "def", "withdraw", "(", "coin", ",", "params", "=", "{", "}", ")", "raise", "ConfigurationError", ".", "new", "(", "'No coin type specified'", ")", "unless", "coin", "raise", "ConfigurationError", ".", "new", "(", "'Invalid coin type specified'", ")", "unless", "Coin", ".", "valid?", "(", "coin", ")", "request", "(", ":post", ",", "\"/#{coin}_withdrawal\"", ",", "params", ")", "end" ]
Withdrawal of the specified coin type. coin - The coin type amount - The amount to withdraw. address - The coin type's address we will send the amount to.
[ "Withdrawal", "of", "the", "specified", "coin", "type", "." ]
4d83ce3aa21dbe8a80a24efdb1ae40514f014136
https://github.com/mhluska/quadrigacx/blob/4d83ce3aa21dbe8a80a24efdb1ae40514f014136/lib/quadrigacx/client/private.rb#L71-L75
train
mhluska/quadrigacx
lib/quadrigacx/client/private.rb
QuadrigaCX.Private.user_transactions
def user_transactions(params = {}) request(:post, '/user_transactions', params).each { |t| t.id = t.id.to_s } end
ruby
def user_transactions(params = {}) request(:post, '/user_transactions', params).each { |t| t.id = t.id.to_s } end
[ "def", "user_transactions", "(", "params", "=", "{", "}", ")", "request", "(", ":post", ",", "'/user_transactions'", ",", "params", ")", ".", "each", "{", "|", "t", "|", "t", ".", "id", "=", "t", ".", "id", ".", "to_s", "}", "end" ]
Return a list of user transactions. offset - optional, skip that many transactions before beginning to return results. Default: 0. limit - optional, limit result to that many transactions. Default: 50. sort - optional, sorting by date and time (asc - ascending; desc - descending). Default: desc. book - optional, if not specified, will default to btc_cad.
[ "Return", "a", "list", "of", "user", "transactions", "." ]
4d83ce3aa21dbe8a80a24efdb1ae40514f014136
https://github.com/mhluska/quadrigacx/blob/4d83ce3aa21dbe8a80a24efdb1ae40514f014136/lib/quadrigacx/client/private.rb#L92-L94
train
chetan/bixby-bench
lib/bixby/bench.rb
Bixby.Bench.label_width
def label_width if !@label_width then @label_width = @samples.find_all{ |s| Sample === s }. max{ |a, b| a.label.length <=> b.label.length }. label.length + 1 @label_width = 40 if @label_width < 40 end return @label_width end
ruby
def label_width if !@label_width then @label_width = @samples.find_all{ |s| Sample === s }. max{ |a, b| a.label.length <=> b.label.length }. label.length + 1 @label_width = 40 if @label_width < 40 end return @label_width end
[ "def", "label_width", "if", "!", "@label_width", "then", "@label_width", "=", "@samples", ".", "find_all", "{", "|", "s", "|", "Sample", "===", "s", "}", ".", "max", "{", "|", "a", ",", "b", "|", "a", ".", "label", ".", "length", "<=>", "b", ".", "label", ".", "length", "}", ".", "label", ".", "length", "+", "1", "@label_width", "=", "40", "if", "@label_width", "<", "40", "end", "return", "@label_width", "end" ]
Calculate the label padding, taking all labels into account
[ "Calculate", "the", "label", "padding", "taking", "all", "labels", "into", "account" ]
488754f5ae88b4e3345b45590b63d77159891b57
https://github.com/chetan/bixby-bench/blob/488754f5ae88b4e3345b45590b63d77159891b57/lib/bixby/bench.rb#L71-L81
train
sinisterchipmunk/genspec
lib/genspec/matchers.rb
GenSpec.Matchers.delete
def delete(filename) within_source_root do FileUtils.mkdir_p File.dirname(filename) FileUtils.touch filename end generate { expect(File).not_to exist(filename) } end
ruby
def delete(filename) within_source_root do FileUtils.mkdir_p File.dirname(filename) FileUtils.touch filename end generate { expect(File).not_to exist(filename) } end
[ "def", "delete", "(", "filename", ")", "within_source_root", "do", "FileUtils", ".", "mkdir_p", "File", ".", "dirname", "(", "filename", ")", "FileUtils", ".", "touch", "filename", "end", "generate", "{", "expect", "(", "File", ")", ".", "not_to", "exist", "(", "filename", ")", "}", "end" ]
Makes sure that the generator deletes the named file. This is done by first ensuring that the file exists in the first place, and then ensuring that it does not exist after the generator completes its run. Example: expect(subject).to delete("path/to/file")
[ "Makes", "sure", "that", "the", "generator", "deletes", "the", "named", "file", ".", "This", "is", "done", "by", "first", "ensuring", "that", "the", "file", "exists", "in", "the", "first", "place", "and", "then", "ensuring", "that", "it", "does", "not", "exist", "after", "the", "generator", "completes", "its", "run", "." ]
88dcef6bc09d29fe9a26c2782cb643ed6b888549
https://github.com/sinisterchipmunk/genspec/blob/88dcef6bc09d29fe9a26c2782cb643ed6b888549/lib/genspec/matchers.rb#L32-L39
train
alexanderbez/sounddrop
lib/sounddrop/client.rb
SoundDrop.Client.get_client
def get_client init_opts = { client_id: @CLIENT_ID, client_secret: @CLIENT_SECRET } if username? and password? init_opts[:username] = @USERNAME init_opts[:password] = @PASSWORD end Soundcloud.new(init_opts) end
ruby
def get_client init_opts = { client_id: @CLIENT_ID, client_secret: @CLIENT_SECRET } if username? and password? init_opts[:username] = @USERNAME init_opts[:password] = @PASSWORD end Soundcloud.new(init_opts) end
[ "def", "get_client", "init_opts", "=", "{", "client_id", ":", "@CLIENT_ID", ",", "client_secret", ":", "@CLIENT_SECRET", "}", "if", "username?", "and", "password?", "init_opts", "[", ":username", "]", "=", "@USERNAME", "init_opts", "[", ":password", "]", "=", "@PASSWORD", "end", "Soundcloud", ".", "new", "(", "init_opts", ")", "end" ]
Defines a Soundcloud client object
[ "Defines", "a", "Soundcloud", "client", "object" ]
563903234cb8a86d2fd8c19f2991437a5dc71d7e
https://github.com/alexanderbez/sounddrop/blob/563903234cb8a86d2fd8c19f2991437a5dc71d7e/lib/sounddrop/client.rb#L34-L46
train
alexanderbez/sounddrop
lib/sounddrop/client.rb
SoundDrop.Client.get_drop
def get_drop(url) sc_track = client.get('/resolve', url: url) SoundDrop::Drop.new(client: client, track: sc_track) end
ruby
def get_drop(url) sc_track = client.get('/resolve', url: url) SoundDrop::Drop.new(client: client, track: sc_track) end
[ "def", "get_drop", "(", "url", ")", "sc_track", "=", "client", ".", "get", "(", "'/resolve'", ",", "url", ":", "url", ")", "SoundDrop", "::", "Drop", ".", "new", "(", "client", ":", "client", ",", "track", ":", "sc_track", ")", "end" ]
Returns a Drop object that contains useful track information.
[ "Returns", "a", "Drop", "object", "that", "contains", "useful", "track", "information", "." ]
563903234cb8a86d2fd8c19f2991437a5dc71d7e
https://github.com/alexanderbez/sounddrop/blob/563903234cb8a86d2fd8c19f2991437a5dc71d7e/lib/sounddrop/client.rb#L49-L52
train
marcusbaguley/exception_dog
lib/exception_dog/handler.rb
ExceptionDog.Handler.format_backtrace
def format_backtrace(backtrace) backtrace ||= [] backtrace[0..BACKTRACE_LINES].collect do |line| "#{line.gsub(/\n|\`|\'/, '')}".split(//).last(MAX_LINE_LENGTH).join end end
ruby
def format_backtrace(backtrace) backtrace ||= [] backtrace[0..BACKTRACE_LINES].collect do |line| "#{line.gsub(/\n|\`|\'/, '')}".split(//).last(MAX_LINE_LENGTH).join end end
[ "def", "format_backtrace", "(", "backtrace", ")", "backtrace", "||=", "[", "]", "backtrace", "[", "0", "..", "BACKTRACE_LINES", "]", ".", "collect", "do", "|", "line", "|", "\"#{line.gsub(/\\n|\\`|\\'/, '')}\"", ".", "split", "(", "/", "/", ")", ".", "last", "(", "MAX_LINE_LENGTH", ")", ".", "join", "end", "end" ]
remove backticks, single quotes, \n and ensure each line is reasonably small
[ "remove", "backticks", "single", "quotes", "\\", "n", "and", "ensure", "each", "line", "is", "reasonably", "small" ]
33b3a61e842b8d9d1b9c0ce897bf195b90f78e02
https://github.com/marcusbaguley/exception_dog/blob/33b3a61e842b8d9d1b9c0ce897bf195b90f78e02/lib/exception_dog/handler.rb#L52-L57
train
chetan/bixby-common
lib/bixby-common/command_spec.rb
Bixby.CommandSpec.validate
def validate(expected_digest) if not bundle_exists? then raise BundleNotFound.new("repo = #{@repo}; bundle = #{@bundle}") end if not command_exists? then raise CommandNotFound.new("repo = #{@repo}; bundle = #{@bundle}; command = #{@command}") end if self.digest != expected_digest then raise BundleNotFound, "digest does not match ('#{self.digest}' != '#{expected_digest}')", caller end return true end
ruby
def validate(expected_digest) if not bundle_exists? then raise BundleNotFound.new("repo = #{@repo}; bundle = #{@bundle}") end if not command_exists? then raise CommandNotFound.new("repo = #{@repo}; bundle = #{@bundle}; command = #{@command}") end if self.digest != expected_digest then raise BundleNotFound, "digest does not match ('#{self.digest}' != '#{expected_digest}')", caller end return true end
[ "def", "validate", "(", "expected_digest", ")", "if", "not", "bundle_exists?", "then", "raise", "BundleNotFound", ".", "new", "(", "\"repo = #{@repo}; bundle = #{@bundle}\"", ")", "end", "if", "not", "command_exists?", "then", "raise", "CommandNotFound", ".", "new", "(", "\"repo = #{@repo}; bundle = #{@bundle}; command = #{@command}\"", ")", "end", "if", "self", ".", "digest", "!=", "expected_digest", "then", "raise", "BundleNotFound", ",", "\"digest does not match ('#{self.digest}' != '#{expected_digest}')\"", ",", "caller", "end", "return", "true", "end" ]
Create new CommandSpec @param [Hash] params Hash of attributes to initialize with Validate the existence of this Command on the local system and compare digest to local version @param [String] expected_digest @return [Boolean] returns true if available, else raises error @raise [BundleNotFound] If bundle doesn't exist or digest does not match @raise [CommandNotFound] If command doesn't exist
[ "Create", "new", "CommandSpec" ]
3fb8829987b115fc53ec820d97a20b4a8c49b4a2
https://github.com/chetan/bixby-common/blob/3fb8829987b115fc53ec820d97a20b4a8c49b4a2/lib/bixby-common/command_spec.rb#L34-L46
train
chetan/bixby-common
lib/bixby-common/command_spec.rb
Bixby.CommandSpec.manifest
def manifest if File.exists?(manifest_file) && File.readable?(manifest_file) then MultiJson.load(File.read(manifest_file)) else {} end end
ruby
def manifest if File.exists?(manifest_file) && File.readable?(manifest_file) then MultiJson.load(File.read(manifest_file)) else {} end end
[ "def", "manifest", "if", "File", ".", "exists?", "(", "manifest_file", ")", "&&", "File", ".", "readable?", "(", "manifest_file", ")", "then", "MultiJson", ".", "load", "(", "File", ".", "read", "(", "manifest_file", ")", ")", "else", "{", "}", "end", "end" ]
Retrieve the command's Manifest, loading it from disk if necessary If no Manifest is available, returns an empty hash @return [Hash]
[ "Retrieve", "the", "command", "s", "Manifest", "loading", "it", "from", "disk", "if", "necessary", "If", "no", "Manifest", "is", "available", "returns", "an", "empty", "hash" ]
3fb8829987b115fc53ec820d97a20b4a8c49b4a2
https://github.com/chetan/bixby-common/blob/3fb8829987b115fc53ec820d97a20b4a8c49b4a2/lib/bixby-common/command_spec.rb#L100-L106
train
chetan/bixby-common
lib/bixby-common/command_spec.rb
Bixby.CommandSpec.to_s
def to_s # :nocov: s = [] s << "CommandSpec:#{self.object_id}" s << " digest: #{self.digest}" s << " repo: #{self.repo}" s << " bundle: #{self.bundle}" s << " command: #{self.command}" s << " args: #{self.args}" s << " user: #{self.user}" s << " group: #{self.group}" s << " env: " + (self.env.nil?() ? "" : MultiJson.dump(self.env)) s << " stdin: " + Debug.pretty_str(stdin) s.join("\n") end
ruby
def to_s # :nocov: s = [] s << "CommandSpec:#{self.object_id}" s << " digest: #{self.digest}" s << " repo: #{self.repo}" s << " bundle: #{self.bundle}" s << " command: #{self.command}" s << " args: #{self.args}" s << " user: #{self.user}" s << " group: #{self.group}" s << " env: " + (self.env.nil?() ? "" : MultiJson.dump(self.env)) s << " stdin: " + Debug.pretty_str(stdin) s.join("\n") end
[ "def", "to_s", "# :nocov:", "s", "=", "[", "]", "s", "<<", "\"CommandSpec:#{self.object_id}\"", "s", "<<", "\" digest: #{self.digest}\"", "s", "<<", "\" repo: #{self.repo}\"", "s", "<<", "\" bundle: #{self.bundle}\"", "s", "<<", "\" command: #{self.command}\"", "s", "<<", "\" args: #{self.args}\"", "s", "<<", "\" user: #{self.user}\"", "s", "<<", "\" group: #{self.group}\"", "s", "<<", "\" env: \"", "+", "(", "self", ".", "env", ".", "nil?", "(", ")", "?", "\"\"", ":", "MultiJson", ".", "dump", "(", "self", ".", "env", ")", ")", "s", "<<", "\" stdin: \"", "+", "Debug", ".", "pretty_str", "(", "stdin", ")", "s", ".", "join", "(", "\"\\n\"", ")", "end" ]
Convert object to String, useful for debugging @return [String]
[ "Convert", "object", "to", "String", "useful", "for", "debugging" ]
3fb8829987b115fc53ec820d97a20b4a8c49b4a2
https://github.com/chetan/bixby-common/blob/3fb8829987b115fc53ec820d97a20b4a8c49b4a2/lib/bixby-common/command_spec.rb#L173-L186
train
ideonetwork/lato-blog
app/models/lato_blog/category.rb
LatoBlog.Category.check_category_father_circular_dependency
def check_category_father_circular_dependency return unless self.lato_blog_category_id all_children = self.get_all_category_children same_children = all_children.select { |child| child.id === self.lato_blog_category_id } if same_children.length > 0 errors.add('Category father', 'can not be a children of the category') throw :abort end end
ruby
def check_category_father_circular_dependency return unless self.lato_blog_category_id all_children = self.get_all_category_children same_children = all_children.select { |child| child.id === self.lato_blog_category_id } if same_children.length > 0 errors.add('Category father', 'can not be a children of the category') throw :abort end end
[ "def", "check_category_father_circular_dependency", "return", "unless", "self", ".", "lato_blog_category_id", "all_children", "=", "self", ".", "get_all_category_children", "same_children", "=", "all_children", ".", "select", "{", "|", "child", "|", "child", ".", "id", "===", "self", ".", "lato_blog_category_id", "}", "if", "same_children", ".", "length", ">", "0", "errors", ".", "add", "(", "'Category father'", ",", "'can not be a children of the category'", ")", "throw", ":abort", "end", "end" ]
This function check the category parent of the category do not create a circular dependency.
[ "This", "function", "check", "the", "category", "parent", "of", "the", "category", "do", "not", "create", "a", "circular", "dependency", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/models/lato_blog/category.rb#L80-L90
train
ideonetwork/lato-blog
app/models/lato_blog/category.rb
LatoBlog.Category.check_lato_blog_category_parent
def check_lato_blog_category_parent category_parent = LatoBlog::CategoryParent.find_by(id: lato_blog_category_parent_id) if !category_parent errors.add('Category parent', 'not exist for the category') throw :abort return end same_language_category = category_parent.categories.find_by(meta_language: meta_language) if same_language_category && same_language_category.id != id errors.add('Category parent', 'has another category for the same language') throw :abort return end end
ruby
def check_lato_blog_category_parent category_parent = LatoBlog::CategoryParent.find_by(id: lato_blog_category_parent_id) if !category_parent errors.add('Category parent', 'not exist for the category') throw :abort return end same_language_category = category_parent.categories.find_by(meta_language: meta_language) if same_language_category && same_language_category.id != id errors.add('Category parent', 'has another category for the same language') throw :abort return end end
[ "def", "check_lato_blog_category_parent", "category_parent", "=", "LatoBlog", "::", "CategoryParent", ".", "find_by", "(", "id", ":", "lato_blog_category_parent_id", ")", "if", "!", "category_parent", "errors", ".", "add", "(", "'Category parent'", ",", "'not exist for the category'", ")", "throw", ":abort", "return", "end", "same_language_category", "=", "category_parent", ".", "categories", ".", "find_by", "(", "meta_language", ":", "meta_language", ")", "if", "same_language_category", "&&", "same_language_category", ".", "id", "!=", "id", "errors", ".", "add", "(", "'Category parent'", ",", "'has another category for the same language'", ")", "throw", ":abort", "return", "end", "end" ]
This function check that the category parent exist and has not others categories for the same language.
[ "This", "function", "check", "that", "the", "category", "parent", "exist", "and", "has", "not", "others", "categories", "for", "the", "same", "language", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/models/lato_blog/category.rb#L102-L116
train
nsi-iff/nsivideogranulate-ruby
lib/nsivideogranulate/fake_server.rb
NSIVideoGranulate.FakeServerManager.start_server
def start_server(port=9886) @thread = Thread.new do Server.prepare Server.run! :port => port end sleep(1) self end
ruby
def start_server(port=9886) @thread = Thread.new do Server.prepare Server.run! :port => port end sleep(1) self end
[ "def", "start_server", "(", "port", "=", "9886", ")", "@thread", "=", "Thread", ".", "new", "do", "Server", ".", "prepare", "Server", ".", "run!", ":port", "=>", "port", "end", "sleep", "(", "1", ")", "self", "end" ]
Start the nsi.videogranulate fake server @param [Fixnum] port the port where the fake server will listen * make sure there's not anything else listenning on this port
[ "Start", "the", "nsi", ".", "videogranulate", "fake", "server" ]
794f44630ba6cac019a320288229ccccee00864d
https://github.com/nsi-iff/nsivideogranulate-ruby/blob/794f44630ba6cac019a320288229ccccee00864d/lib/nsivideogranulate/fake_server.rb#L56-L63
train
sugaryourcoffee/syclink
lib/syclink/importer.rb
SycLink.Importer.links
def links rows.map do |row| attributes = Link::ATTRS.dup - [:url] Link.new(row.shift, Hash[row.map { |v| [attributes.shift, v] }]) end end
ruby
def links rows.map do |row| attributes = Link::ATTRS.dup - [:url] Link.new(row.shift, Hash[row.map { |v| [attributes.shift, v] }]) end end
[ "def", "links", "rows", ".", "map", "do", "|", "row", "|", "attributes", "=", "Link", "::", "ATTRS", ".", "dup", "-", "[", ":url", "]", "Link", ".", "new", "(", "row", ".", "shift", ",", "Hash", "[", "row", ".", "map", "{", "|", "v", "|", "[", "attributes", ".", "shift", ",", "v", "]", "}", "]", ")", "end", "end" ]
Links returned as Link objects
[ "Links", "returned", "as", "Link", "objects" ]
941ee2045c946daa1e0db394eb643aa82c1254cc
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/importer.rb#L38-L43
train
petebrowne/machined
lib/machined/server.rb
Machined.Server.to_app
def to_app # :nodoc: Rack::Builder.new.tap do |app| app.use Middleware::Static, machined.output_path app.use Middleware::RootIndex app.run Rack::URLMap.new(sprockets_map) end end
ruby
def to_app # :nodoc: Rack::Builder.new.tap do |app| app.use Middleware::Static, machined.output_path app.use Middleware::RootIndex app.run Rack::URLMap.new(sprockets_map) end end
[ "def", "to_app", "# :nodoc:", "Rack", "::", "Builder", ".", "new", ".", "tap", "do", "|", "app", "|", "app", ".", "use", "Middleware", "::", "Static", ",", "machined", ".", "output_path", "app", ".", "use", "Middleware", "::", "RootIndex", "app", ".", "run", "Rack", "::", "URLMap", ".", "new", "(", "sprockets_map", ")", "end", "end" ]
Creates a Rack app with the current Machined environment configuration.
[ "Creates", "a", "Rack", "app", "with", "the", "current", "Machined", "environment", "configuration", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/lib/machined/server.rb#L52-L58
train
checkdin/checkdin-ruby
lib/checkdin/twitter_hashtag_streams.rb
Checkdin.TwitterHashtagStreams.twitter_hashtag_streams
def twitter_hashtag_streams(campaign_id, options={}) response = connection.get do |req| req.url "campaigns/#{campaign_id}/twitter_hashtag_streams", options end return_error_or_body(response) end
ruby
def twitter_hashtag_streams(campaign_id, options={}) response = connection.get do |req| req.url "campaigns/#{campaign_id}/twitter_hashtag_streams", options end return_error_or_body(response) end
[ "def", "twitter_hashtag_streams", "(", "campaign_id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"campaigns/#{campaign_id}/twitter_hashtag_streams\"", ",", "options", "end", "return_error_or_body", "(", "response", ")", "end" ]
Retrieve Twitter Hashtag Streams for a campaign param [Integer] campaign_id The ID of the campaign to fetch the twitter hashtag stream for. @param [Hash] options
[ "Retrieve", "Twitter", "Hashtag", "Streams", "for", "a", "campaign" ]
c3c4b38b0f8c710e1f805100dcf3a70649215b48
https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/twitter_hashtag_streams.rb#L9-L14
train
checkdin/checkdin-ruby
lib/checkdin/twitter_hashtag_streams.rb
Checkdin.TwitterHashtagStreams.twitter_hashtag_stream
def twitter_hashtag_stream(campaign_id, id, options={}) response = connection.get do |req| req.url "campaigns/#{campaign_id}/twitter_hashtag_streams/#{id}", options end return_error_or_body(response) end
ruby
def twitter_hashtag_stream(campaign_id, id, options={}) response = connection.get do |req| req.url "campaigns/#{campaign_id}/twitter_hashtag_streams/#{id}", options end return_error_or_body(response) end
[ "def", "twitter_hashtag_stream", "(", "campaign_id", ",", "id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"campaigns/#{campaign_id}/twitter_hashtag_streams/#{id}\"", ",", "options", "end", "return_error_or_body", "(", "response", ")", "end" ]
Retrieve Single Twitter Hashtag Stream for a campaign param [Integer] campaign_id The ID of the campaign to fetch the twitter hashtag stream for. param [Integer] id The ID of the twitter_hashtag_stream to fetch. @param [Hash] options
[ "Retrieve", "Single", "Twitter", "Hashtag", "Stream", "for", "a", "campaign" ]
c3c4b38b0f8c710e1f805100dcf3a70649215b48
https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/twitter_hashtag_streams.rb#L22-L27
train
pixeltrix/rails_legacy_mapper
lib/rails_legacy_mapper/mapper.rb
RailsLegacyMapper.Mapper.root
def root(options = {}) if options.is_a?(Symbol) if source_route = @set.named_routes.routes[options] options = source_route.defaults.merge({ :conditions => source_route.conditions }) end end named_route("root", '', options) end
ruby
def root(options = {}) if options.is_a?(Symbol) if source_route = @set.named_routes.routes[options] options = source_route.defaults.merge({ :conditions => source_route.conditions }) end end named_route("root", '', options) end
[ "def", "root", "(", "options", "=", "{", "}", ")", "if", "options", ".", "is_a?", "(", "Symbol", ")", "if", "source_route", "=", "@set", ".", "named_routes", ".", "routes", "[", "options", "]", "options", "=", "source_route", ".", "defaults", ".", "merge", "(", "{", ":conditions", "=>", "source_route", ".", "conditions", "}", ")", "end", "end", "named_route", "(", "\"root\"", ",", "''", ",", "options", ")", "end" ]
Creates a named route called "root" for matching the root level request.
[ "Creates", "a", "named", "route", "called", "root", "for", "matching", "the", "root", "level", "request", "." ]
d841d25b76fed96595f5dff19d4772c7017b3b71
https://github.com/pixeltrix/rails_legacy_mapper/blob/d841d25b76fed96595f5dff19d4772c7017b3b71/lib/rails_legacy_mapper/mapper.rb#L157-L164
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/categories_controller.rb
LatoBlog.Back::CategoriesController.index
def index core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:categories]) # find categories to show @categories = LatoBlog::Category.where(meta_language: cookies[:lato_blog__current_language]).order('title ASC') @widget_index_categories = core__widgets_index(@categories, search: 'title', pagination: 10) end
ruby
def index core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:categories]) # find categories to show @categories = LatoBlog::Category.where(meta_language: cookies[:lato_blog__current_language]).order('title ASC') @widget_index_categories = core__widgets_index(@categories, search: 'title', pagination: 10) end
[ "def", "index", "core__set_header_active_page_title", "(", "LANGUAGES", "[", ":lato_blog", "]", "[", ":pages", "]", "[", ":categories", "]", ")", "# find categories to show", "@categories", "=", "LatoBlog", "::", "Category", ".", "where", "(", "meta_language", ":", "cookies", "[", ":lato_blog__current_language", "]", ")", ".", "order", "(", "'title ASC'", ")", "@widget_index_categories", "=", "core__widgets_index", "(", "@categories", ",", "search", ":", "'title'", ",", "pagination", ":", "10", ")", "end" ]
This function shows the list of possible categories.
[ "This", "function", "shows", "the", "list", "of", "possible", "categories", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/categories_controller.rb#L9-L14
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/categories_controller.rb
LatoBlog.Back::CategoriesController.new
def new core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:categories_new]) @category = LatoBlog::Category.new if params[:language] set_current_language params[:language] end if params[:parent] @category_parent = LatoBlog::CategoryParent.find_by(id: params[:parent]) end fetch_external_objects end
ruby
def new core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:categories_new]) @category = LatoBlog::Category.new if params[:language] set_current_language params[:language] end if params[:parent] @category_parent = LatoBlog::CategoryParent.find_by(id: params[:parent]) end fetch_external_objects end
[ "def", "new", "core__set_header_active_page_title", "(", "LANGUAGES", "[", ":lato_blog", "]", "[", ":pages", "]", "[", ":categories_new", "]", ")", "@category", "=", "LatoBlog", "::", "Category", ".", "new", "if", "params", "[", ":language", "]", "set_current_language", "params", "[", ":language", "]", "end", "if", "params", "[", ":parent", "]", "@category_parent", "=", "LatoBlog", "::", "CategoryParent", ".", "find_by", "(", "id", ":", "params", "[", ":parent", "]", ")", "end", "fetch_external_objects", "end" ]
This function shows the view to create a new category.
[ "This", "function", "shows", "the", "view", "to", "create", "a", "new", "category", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/categories_controller.rb#L23-L36
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/categories_controller.rb
LatoBlog.Back::CategoriesController.create
def create @category = LatoBlog::Category.new(new_category_params) if !@category.save flash[:danger] = @category.errors.full_messages.to_sentence redirect_to lato_blog.new_category_path return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:category_create_success] redirect_to lato_blog.category_path(@category.id) end
ruby
def create @category = LatoBlog::Category.new(new_category_params) if !@category.save flash[:danger] = @category.errors.full_messages.to_sentence redirect_to lato_blog.new_category_path return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:category_create_success] redirect_to lato_blog.category_path(@category.id) end
[ "def", "create", "@category", "=", "LatoBlog", "::", "Category", ".", "new", "(", "new_category_params", ")", "if", "!", "@category", ".", "save", "flash", "[", ":danger", "]", "=", "@category", ".", "errors", ".", "full_messages", ".", "to_sentence", "redirect_to", "lato_blog", ".", "new_category_path", "return", "end", "flash", "[", ":success", "]", "=", "LANGUAGES", "[", ":lato_blog", "]", "[", ":flashes", "]", "[", ":category_create_success", "]", "redirect_to", "lato_blog", ".", "category_path", "(", "@category", ".", "id", ")", "end" ]
This function creates a new category.
[ "This", "function", "creates", "a", "new", "category", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/categories_controller.rb#L39-L50
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/categories_controller.rb
LatoBlog.Back::CategoriesController.edit
def edit core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:categories_edit]) @category = LatoBlog::Category.find_by(id: params[:id]) return unless check_category_presence if @category.meta_language != cookies[:lato_blog__current_language] set_current_language @category.meta_language end fetch_external_objects end
ruby
def edit core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:categories_edit]) @category = LatoBlog::Category.find_by(id: params[:id]) return unless check_category_presence if @category.meta_language != cookies[:lato_blog__current_language] set_current_language @category.meta_language end fetch_external_objects end
[ "def", "edit", "core__set_header_active_page_title", "(", "LANGUAGES", "[", ":lato_blog", "]", "[", ":pages", "]", "[", ":categories_edit", "]", ")", "@category", "=", "LatoBlog", "::", "Category", ".", "find_by", "(", "id", ":", "params", "[", ":id", "]", ")", "return", "unless", "check_category_presence", "if", "@category", ".", "meta_language", "!=", "cookies", "[", ":lato_blog__current_language", "]", "set_current_language", "@category", ".", "meta_language", "end", "fetch_external_objects", "end" ]
This function show the view to edit a category.
[ "This", "function", "show", "the", "view", "to", "edit", "a", "category", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/categories_controller.rb#L53-L63
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/categories_controller.rb
LatoBlog.Back::CategoriesController.update
def update @category = LatoBlog::Category.find_by(id: params[:id]) return unless check_category_presence if !@category.update(edit_category_params) flash[:danger] = @category.errors.full_messages.to_sentence redirect_to lato_blog.edit_category_path(@category.id) return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:category_update_success] redirect_to lato_blog.category_path(@category.id) end
ruby
def update @category = LatoBlog::Category.find_by(id: params[:id]) return unless check_category_presence if !@category.update(edit_category_params) flash[:danger] = @category.errors.full_messages.to_sentence redirect_to lato_blog.edit_category_path(@category.id) return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:category_update_success] redirect_to lato_blog.category_path(@category.id) end
[ "def", "update", "@category", "=", "LatoBlog", "::", "Category", ".", "find_by", "(", "id", ":", "params", "[", ":id", "]", ")", "return", "unless", "check_category_presence", "if", "!", "@category", ".", "update", "(", "edit_category_params", ")", "flash", "[", ":danger", "]", "=", "@category", ".", "errors", ".", "full_messages", ".", "to_sentence", "redirect_to", "lato_blog", ".", "edit_category_path", "(", "@category", ".", "id", ")", "return", "end", "flash", "[", ":success", "]", "=", "LANGUAGES", "[", ":lato_blog", "]", "[", ":flashes", "]", "[", ":category_update_success", "]", "redirect_to", "lato_blog", ".", "category_path", "(", "@category", ".", "id", ")", "end" ]
This function updates a category.
[ "This", "function", "updates", "a", "category", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/categories_controller.rb#L66-L78
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/categories_controller.rb
LatoBlog.Back::CategoriesController.destroy
def destroy @category = LatoBlog::Category.find_by(id: params[:id]) return unless check_category_presence if !@category.destroy flash[:danger] = @category.category_parent.errors.full_messages.to_sentence redirect_to lato_blog.edit_category_path(@category.id) return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:category_destroy_success] redirect_to lato_blog.categories_path(status: 'deleted') end
ruby
def destroy @category = LatoBlog::Category.find_by(id: params[:id]) return unless check_category_presence if !@category.destroy flash[:danger] = @category.category_parent.errors.full_messages.to_sentence redirect_to lato_blog.edit_category_path(@category.id) return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:category_destroy_success] redirect_to lato_blog.categories_path(status: 'deleted') end
[ "def", "destroy", "@category", "=", "LatoBlog", "::", "Category", ".", "find_by", "(", "id", ":", "params", "[", ":id", "]", ")", "return", "unless", "check_category_presence", "if", "!", "@category", ".", "destroy", "flash", "[", ":danger", "]", "=", "@category", ".", "category_parent", ".", "errors", ".", "full_messages", ".", "to_sentence", "redirect_to", "lato_blog", ".", "edit_category_path", "(", "@category", ".", "id", ")", "return", "end", "flash", "[", ":success", "]", "=", "LANGUAGES", "[", ":lato_blog", "]", "[", ":flashes", "]", "[", ":category_destroy_success", "]", "redirect_to", "lato_blog", ".", "categories_path", "(", "status", ":", "'deleted'", ")", "end" ]
This function destroyes a category.
[ "This", "function", "destroyes", "a", "category", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/categories_controller.rb#L81-L93
train
yolk/pump
lib/pump/encoder.rb
Pump.Encoder.encode
def encode(object, options={}) object = object.to_a if defined?(ActiveRecord::Relation) && object.is_a?(ActiveRecord::Relation) fields_to_hash(options) if object.is_a?(Array) if options[:fields] encode_partial_array(object, options) else encode_array(object, options) end elsif options[:fields] encode_partial_single(object, options) else encode_single(object, options) end end
ruby
def encode(object, options={}) object = object.to_a if defined?(ActiveRecord::Relation) && object.is_a?(ActiveRecord::Relation) fields_to_hash(options) if object.is_a?(Array) if options[:fields] encode_partial_array(object, options) else encode_array(object, options) end elsif options[:fields] encode_partial_single(object, options) else encode_single(object, options) end end
[ "def", "encode", "(", "object", ",", "options", "=", "{", "}", ")", "object", "=", "object", ".", "to_a", "if", "defined?", "(", "ActiveRecord", "::", "Relation", ")", "&&", "object", ".", "is_a?", "(", "ActiveRecord", "::", "Relation", ")", "fields_to_hash", "(", "options", ")", "if", "object", ".", "is_a?", "(", "Array", ")", "if", "options", "[", ":fields", "]", "encode_partial_array", "(", "object", ",", "options", ")", "else", "encode_array", "(", "object", ",", "options", ")", "end", "elsif", "options", "[", ":fields", "]", "encode_partial_single", "(", "object", ",", "options", ")", "else", "encode_single", "(", "object", ",", "options", ")", "end", "end" ]
Creates a new XML-encoder with a root tag named after +root_name+. @example Create a simple encoder for a person with a name attribute: Pump::Xml.new :person do tag :name end @example Create the same without usage of the DSL: Pump::Xml.new :person, [{:name => :name}] @example Create the same but without the xml instruct Pump::Xml.new :person, :instruct => false do tag :name end @example The same again without DSL: Pump::Xml.new :person, [{:name => :name}], :instruct => false @param [String, Symbol] root_name the name of the used root tag @param [Array<Hash>] encoder_config optional config for all tags @param [Hash] encoder_options optional encoder_options for the whole encoder @yield an optional block to create the encoder with the Pump::Dsl @return [self] Encode a object or an array of objects to an formatted string. @param [Object, Array<Object>] object object or an array of objects to encode to XML or JSON. The only requirement: The given objects must respond to all methods configured during initalization of the Pump::Xml or Pump::JSON instance. @return [String]
[ "Creates", "a", "new", "XML", "-", "encoder", "with", "a", "root", "tag", "named", "after", "+", "root_name", "+", "." ]
164281df30363302ff43ad2a250d9407b3aa3af4
https://github.com/yolk/pump/blob/164281df30363302ff43ad2a250d9407b3aa3af4/lib/pump/encoder.rb#L55-L69
train
dlindahl/network_executive
lib/network_executive/channel_schedule.rb
NetworkExecutive.ChannelSchedule.extend_off_air
def extend_off_air( programs, program, stop ) prev = programs.pop + program program = prev.program occurrence = prev.occurrence remainder = time_left( occurrence.start_time, occurrence.end_time, stop ) [ program, occurrence, remainder ] end
ruby
def extend_off_air( programs, program, stop ) prev = programs.pop + program program = prev.program occurrence = prev.occurrence remainder = time_left( occurrence.start_time, occurrence.end_time, stop ) [ program, occurrence, remainder ] end
[ "def", "extend_off_air", "(", "programs", ",", "program", ",", "stop", ")", "prev", "=", "programs", ".", "pop", "+", "program", "program", "=", "prev", ".", "program", "occurrence", "=", "prev", ".", "occurrence", "remainder", "=", "time_left", "(", "occurrence", ".", "start_time", ",", "occurrence", ".", "end_time", ",", "stop", ")", "[", "program", ",", "occurrence", ",", "remainder", "]", "end" ]
Extends the previous Off Air schedule
[ "Extends", "the", "previous", "Off", "Air", "schedule" ]
4802e8b20225d7058c82f5ded05bfa6c84918e3d
https://github.com/dlindahl/network_executive/blob/4802e8b20225d7058c82f5ded05bfa6c84918e3d/lib/network_executive/channel_schedule.rb#L55-L62
train
jimjh/reaction
lib/reaction/client/signer.rb
Reaction.Client::Signer.outgoing
def outgoing(message, callback) # Allow non-data messages to pass through. return callback.call(message) if %r{^/meta/} =~ message['channel'] message['ext'] ||= {} signature = OpenSSL::HMAC.digest('sha256', @key, message['data']) message['ext']['signature'] = Base64.encode64(signature) return callback.call(message) end
ruby
def outgoing(message, callback) # Allow non-data messages to pass through. return callback.call(message) if %r{^/meta/} =~ message['channel'] message['ext'] ||= {} signature = OpenSSL::HMAC.digest('sha256', @key, message['data']) message['ext']['signature'] = Base64.encode64(signature) return callback.call(message) end
[ "def", "outgoing", "(", "message", ",", "callback", ")", "# Allow non-data messages to pass through.", "return", "callback", ".", "call", "(", "message", ")", "if", "%r{", "}", "=~", "message", "[", "'channel'", "]", "message", "[", "'ext'", "]", "||=", "{", "}", "signature", "=", "OpenSSL", "::", "HMAC", ".", "digest", "(", "'sha256'", ",", "@key", ",", "message", "[", "'data'", "]", ")", "message", "[", "'ext'", "]", "[", "'signature'", "]", "=", "Base64", ".", "encode64", "(", "signature", ")", "return", "callback", ".", "call", "(", "message", ")", "end" ]
Initializes the signer with a secret key. @param [String] key secret key, used to sign messages Adds a signature to every outgoing publish message.
[ "Initializes", "the", "signer", "with", "a", "secret", "key", "." ]
8aff9633dbd177ea536b79f59115a2825b5adf0a
https://github.com/jimjh/reaction/blob/8aff9633dbd177ea536b79f59115a2825b5adf0a/lib/reaction/client/signer.rb#L14-L25
train
mntnorv/puttext
lib/puttext/extractor.rb
PutText.Extractor.extract
def extract(path) files = files_in_path(path) supported_files = filter_files(files) parse_files(supported_files) end
ruby
def extract(path) files = files_in_path(path) supported_files = filter_files(files) parse_files(supported_files) end
[ "def", "extract", "(", "path", ")", "files", "=", "files_in_path", "(", "path", ")", "supported_files", "=", "filter_files", "(", "files", ")", "parse_files", "(", "supported_files", ")", "end" ]
Extract strings from files in the given path. @param [String] path the path of a directory or file to extract strings from. @return [POFile] a POFile object, representing the strings extracted from the files or file in the specified path.
[ "Extract", "strings", "from", "files", "in", "the", "given", "path", "." ]
c5c210dff4e11f714418b6b426dc9e2739fe9876
https://github.com/mntnorv/puttext/blob/c5c210dff4e11f714418b6b426dc9e2739fe9876/lib/puttext/extractor.rb#L45-L50
train
TuftsUniversity/whowas
lib/whowas/validatable.rb
Whowas.Validatable.validate
def validate(input) (check_exists(required_inputs, input) && check_format(input_formats, input)) || (raise Errors::InvalidInput, "Invalid input for #{self.class.name}") end
ruby
def validate(input) (check_exists(required_inputs, input) && check_format(input_formats, input)) || (raise Errors::InvalidInput, "Invalid input for #{self.class.name}") end
[ "def", "validate", "(", "input", ")", "(", "check_exists", "(", "required_inputs", ",", "input", ")", "&&", "check_format", "(", "input_formats", ",", "input", ")", ")", "||", "(", "raise", "Errors", "::", "InvalidInput", ",", "\"Invalid input for #{self.class.name}\"", ")", "end" ]
Checks for required inputs and input formats that the adapter will need to process the search. It does *not* matter if there are other, non-required parameters in the input hash; they will be ignored later.
[ "Checks", "for", "required", "inputs", "and", "input", "formats", "that", "the", "adapter", "will", "need", "to", "process", "the", "search", "." ]
65197b1dd9ca8170c12eaa239f6bcfb9c2061a9c
https://github.com/TuftsUniversity/whowas/blob/65197b1dd9ca8170c12eaa239f6bcfb9c2061a9c/lib/whowas/validatable.rb#L8-L12
train
TuftsUniversity/whowas
lib/whowas/validatable.rb
Whowas.Validatable.check_exists
def check_exists(required, input) required.inject(true) do |result, key| input[key] && result end end
ruby
def check_exists(required, input) required.inject(true) do |result, key| input[key] && result end end
[ "def", "check_exists", "(", "required", ",", "input", ")", "required", ".", "inject", "(", "true", ")", "do", "|", "result", ",", "key", "|", "input", "[", "key", "]", "&&", "result", "end", "end" ]
Required keys must exist in the input hash and must have a non-nil, non-empty value.
[ "Required", "keys", "must", "exist", "in", "the", "input", "hash", "and", "must", "have", "a", "non", "-", "nil", "non", "-", "empty", "value", "." ]
65197b1dd9ca8170c12eaa239f6bcfb9c2061a9c
https://github.com/TuftsUniversity/whowas/blob/65197b1dd9ca8170c12eaa239f6bcfb9c2061a9c/lib/whowas/validatable.rb#L29-L33
train
Noah2610/MachineConfigure
lib/machine_configure/exporter.rb
MachineConfigure.Exporter.get_files
def get_files return @dir.values.map do |dir| next get_files_recursively_from dir end .reject { |x| !x } .flatten end
ruby
def get_files return @dir.values.map do |dir| next get_files_recursively_from dir end .reject { |x| !x } .flatten end
[ "def", "get_files", "return", "@dir", ".", "values", ".", "map", "do", "|", "dir", "|", "next", "get_files_recursively_from", "dir", "end", ".", "reject", "{", "|", "x", "|", "!", "x", "}", ".", "flatten", "end" ]
Returns all necessary filepaths.
[ "Returns", "all", "necessary", "filepaths", "." ]
8dc94112a1da91a72fa32b84dc53ac41ec0ec00a
https://github.com/Noah2610/MachineConfigure/blob/8dc94112a1da91a72fa32b84dc53ac41ec0ec00a/lib/machine_configure/exporter.rb#L42-L46
train
mufid/kanade
lib/kanade/engine.rb
Kanade.Engine.deserialize_object
def deserialize_object(definition, hash) return nil if hash.nil? result = definition.new result.__fields.each do |field| name = field.key_json || name_to_json(field.sym) if field.options[:as] == :list value = deserialize_list(hash[name], field) elsif field.options[:as] == :dto value = deserialize_object(field.options[:of], hash[name]) else value = hash[name] end next if value.nil? result.send("#{field.key_ruby}=", value) end result end
ruby
def deserialize_object(definition, hash) return nil if hash.nil? result = definition.new result.__fields.each do |field| name = field.key_json || name_to_json(field.sym) if field.options[:as] == :list value = deserialize_list(hash[name], field) elsif field.options[:as] == :dto value = deserialize_object(field.options[:of], hash[name]) else value = hash[name] end next if value.nil? result.send("#{field.key_ruby}=", value) end result end
[ "def", "deserialize_object", "(", "definition", ",", "hash", ")", "return", "nil", "if", "hash", ".", "nil?", "result", "=", "definition", ".", "new", "result", ".", "__fields", ".", "each", "do", "|", "field", "|", "name", "=", "field", ".", "key_json", "||", "name_to_json", "(", "field", ".", "sym", ")", "if", "field", ".", "options", "[", ":as", "]", "==", ":list", "value", "=", "deserialize_list", "(", "hash", "[", "name", "]", ",", "field", ")", "elsif", "field", ".", "options", "[", ":as", "]", "==", ":dto", "value", "=", "deserialize_object", "(", "field", ".", "options", "[", ":of", "]", ",", "hash", "[", "name", "]", ")", "else", "value", "=", "hash", "[", "name", "]", "end", "next", "if", "value", ".", "nil?", "result", ".", "send", "(", "\"#{field.key_ruby}=\"", ",", "value", ")", "end", "result", "end" ]
IF engine contains deserialization logic, we can no more unit test the converters. Seems like, the conversion logic must be outsourced to its respective converter
[ "IF", "engine", "contains", "deserialization", "logic", "we", "can", "no", "more", "unit", "test", "the", "converters", ".", "Seems", "like", "the", "conversion", "logic", "must", "be", "outsourced", "to", "its", "respective", "converter" ]
b0666e306df89d19fed87e956d82ca869a647006
https://github.com/mufid/kanade/blob/b0666e306df89d19fed87e956d82ca869a647006/lib/kanade/engine.rb#L70-L89
train
seamusabshere/cohort_scope
lib/cohort_scope/big_cohort.rb
CohortScope.BigCohort.reduce!
def reduce! @reduced_characteristics = if @reduced_characteristics.keys.length < 2 {} else most_restrictive_characteristic = @reduced_characteristics.keys.max_by do |key| conditions = CohortScope.conditions_for @reduced_characteristics.except(key) @active_record_relation.where(conditions).count end @reduced_characteristics.except most_restrictive_characteristic end end
ruby
def reduce! @reduced_characteristics = if @reduced_characteristics.keys.length < 2 {} else most_restrictive_characteristic = @reduced_characteristics.keys.max_by do |key| conditions = CohortScope.conditions_for @reduced_characteristics.except(key) @active_record_relation.where(conditions).count end @reduced_characteristics.except most_restrictive_characteristic end end
[ "def", "reduce!", "@reduced_characteristics", "=", "if", "@reduced_characteristics", ".", "keys", ".", "length", "<", "2", "{", "}", "else", "most_restrictive_characteristic", "=", "@reduced_characteristics", ".", "keys", ".", "max_by", "do", "|", "key", "|", "conditions", "=", "CohortScope", ".", "conditions_for", "@reduced_characteristics", ".", "except", "(", "key", ")", "@active_record_relation", ".", "where", "(", "conditions", ")", ".", "count", "end", "@reduced_characteristics", ".", "except", "most_restrictive_characteristic", "end", "end" ]
Reduce characteristics by removing them one by one and counting the results. The characteristic whose removal leads to the highest record count is removed from the overall characteristic set.
[ "Reduce", "characteristics", "by", "removing", "them", "one", "by", "one", "and", "counting", "the", "results", "." ]
62e2f67a4bfeaae9c8befce318bf0a9bb40e4350
https://github.com/seamusabshere/cohort_scope/blob/62e2f67a4bfeaae9c8befce318bf0a9bb40e4350/lib/cohort_scope/big_cohort.rb#L6-L16
train
ryanuber/ruby-aptly
lib/aptly/snapshot.rb
Aptly.Snapshot.pull
def pull name, source, dest, kwargs={} packages = kwargs.arg :packages, [] deps = kwargs.arg :deps, true remove = kwargs.arg :remove, true if packages.length == 0 raise AptlyError.new "1 or more package names are required" end cmd = 'aptly snapshot pull' cmd += ' -no-deps' if !deps cmd += ' -no-remove' if !remove cmd += " #{name.quote} #{source.quote} #{dest.quote}" if !packages.empty? packages.each {|p| cmd += " #{p.quote}"} end Aptly::runcmd cmd Aptly::Snapshot.new dest end
ruby
def pull name, source, dest, kwargs={} packages = kwargs.arg :packages, [] deps = kwargs.arg :deps, true remove = kwargs.arg :remove, true if packages.length == 0 raise AptlyError.new "1 or more package names are required" end cmd = 'aptly snapshot pull' cmd += ' -no-deps' if !deps cmd += ' -no-remove' if !remove cmd += " #{name.quote} #{source.quote} #{dest.quote}" if !packages.empty? packages.each {|p| cmd += " #{p.quote}"} end Aptly::runcmd cmd Aptly::Snapshot.new dest end
[ "def", "pull", "name", ",", "source", ",", "dest", ",", "kwargs", "=", "{", "}", "packages", "=", "kwargs", ".", "arg", ":packages", ",", "[", "]", "deps", "=", "kwargs", ".", "arg", ":deps", ",", "true", "remove", "=", "kwargs", ".", "arg", ":remove", ",", "true", "if", "packages", ".", "length", "==", "0", "raise", "AptlyError", ".", "new", "\"1 or more package names are required\"", "end", "cmd", "=", "'aptly snapshot pull'", "cmd", "+=", "' -no-deps'", "if", "!", "deps", "cmd", "+=", "' -no-remove'", "if", "!", "remove", "cmd", "+=", "\" #{name.quote} #{source.quote} #{dest.quote}\"", "if", "!", "packages", ".", "empty?", "packages", ".", "each", "{", "|", "p", "|", "cmd", "+=", "\" #{p.quote}\"", "}", "end", "Aptly", "::", "runcmd", "cmd", "Aptly", "::", "Snapshot", ".", "new", "dest", "end" ]
Pull packages from a snapshot into another, creating a new snapshot. == Parameters: name:: The name of the snapshot to pull to source:: The repository containing the packages to pull in dest:: The name for the new snapshot which will be created packages:: An array of package names to search deps:: When true, process dependencies remove:: When true, removes package versions not found in source
[ "Pull", "packages", "from", "a", "snapshot", "into", "another", "creating", "a", "new", "snapshot", "." ]
9581c38da30119d6a61b7ddac6334ab17fc67164
https://github.com/ryanuber/ruby-aptly/blob/9581c38da30119d6a61b7ddac6334ab17fc67164/lib/aptly/snapshot.rb#L200-L219
train
ryanuber/ruby-aptly
lib/aptly/snapshot.rb
Aptly.Snapshot.pull_from
def pull_from source, dest, kwargs={} packages = kwargs.arg :packages, [] deps = kwargs.arg :deps, true remove = kwargs.arg :remove, true pull @name, source, dest, :packages => packages, :deps => deps, :remove => remove end
ruby
def pull_from source, dest, kwargs={} packages = kwargs.arg :packages, [] deps = kwargs.arg :deps, true remove = kwargs.arg :remove, true pull @name, source, dest, :packages => packages, :deps => deps, :remove => remove end
[ "def", "pull_from", "source", ",", "dest", ",", "kwargs", "=", "{", "}", "packages", "=", "kwargs", ".", "arg", ":packages", ",", "[", "]", "deps", "=", "kwargs", ".", "arg", ":deps", ",", "true", "remove", "=", "kwargs", ".", "arg", ":remove", ",", "true", "pull", "@name", ",", "source", ",", "dest", ",", ":packages", "=>", "packages", ",", ":deps", "=>", "deps", ",", ":remove", "=>", "remove", "end" ]
Shortcut method to pull packages to the current snapshot
[ "Shortcut", "method", "to", "pull", "packages", "to", "the", "current", "snapshot" ]
9581c38da30119d6a61b7ddac6334ab17fc67164
https://github.com/ryanuber/ruby-aptly/blob/9581c38da30119d6a61b7ddac6334ab17fc67164/lib/aptly/snapshot.rb#L223-L229
train
bradfeehan/derelict
lib/derelict/parser/status.rb
Derelict.Parser::Status.exists?
def exists?(vm_name = nil) return (vm_names.count > 0) if vm_name.nil? vm_names.include? vm_name.to_sym end
ruby
def exists?(vm_name = nil) return (vm_names.count > 0) if vm_name.nil? vm_names.include? vm_name.to_sym end
[ "def", "exists?", "(", "vm_name", "=", "nil", ")", "return", "(", "vm_names", ".", "count", ">", "0", ")", "if", "vm_name", ".", "nil?", "vm_names", ".", "include?", "vm_name", ".", "to_sym", "end" ]
Determines if a particular virtual machine exists in the output * vm_name: The name of the virtual machine to look for
[ "Determines", "if", "a", "particular", "virtual", "machine", "exists", "in", "the", "output" ]
c9d70f04562280a34083dd060b0e4099e6f32d8d
https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/parser/status.rb#L32-L35
train
bradfeehan/derelict
lib/derelict/parser/status.rb
Derelict.Parser::Status.state
def state(vm_name) unless states.include? vm_name.to_sym raise Derelict::VirtualMachine::NotFound.new vm_name end states[vm_name.to_sym] end
ruby
def state(vm_name) unless states.include? vm_name.to_sym raise Derelict::VirtualMachine::NotFound.new vm_name end states[vm_name.to_sym] end
[ "def", "state", "(", "vm_name", ")", "unless", "states", ".", "include?", "vm_name", ".", "to_sym", "raise", "Derelict", "::", "VirtualMachine", "::", "NotFound", ".", "new", "vm_name", "end", "states", "[", "vm_name", ".", "to_sym", "]", "end" ]
Determines the state of a particular virtual machine The state is returned as a symbol, e.g. :running. * vm_name: The name of the virtual machine to retrieve state
[ "Determines", "the", "state", "of", "a", "particular", "virtual", "machine" ]
c9d70f04562280a34083dd060b0e4099e6f32d8d
https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/parser/status.rb#L42-L48
train
bradfeehan/derelict
lib/derelict/parser/status.rb
Derelict.Parser::Status.vm_lines
def vm_lines output.match(PARSE_LIST_FROM_OUTPUT).tap {|list| logger.debug "Parsing VM list from output using #{description}" raise InvalidFormat.new "Couldn't find VM list" if list.nil? }.captures[0].lines end
ruby
def vm_lines output.match(PARSE_LIST_FROM_OUTPUT).tap {|list| logger.debug "Parsing VM list from output using #{description}" raise InvalidFormat.new "Couldn't find VM list" if list.nil? }.captures[0].lines end
[ "def", "vm_lines", "output", ".", "match", "(", "PARSE_LIST_FROM_OUTPUT", ")", ".", "tap", "{", "|", "list", "|", "logger", ".", "debug", "\"Parsing VM list from output using #{description}\"", "raise", "InvalidFormat", ".", "new", "\"Couldn't find VM list\"", "if", "list", ".", "nil?", "}", ".", "captures", "[", "0", "]", ".", "lines", "end" ]
Retrieves the virtual machine list section of the output
[ "Retrieves", "the", "virtual", "machine", "list", "section", "of", "the", "output" ]
c9d70f04562280a34083dd060b0e4099e6f32d8d
https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/parser/status.rb#L59-L64
train
marcboeker/mongolicious
lib/mongolicious/db.rb
Mongolicious.DB.get_opts
def get_opts(db_uri) uri = URI.parse(db_uri) { :host => uri.host, :port => uri.port, :user => uri.user, :password => uri.password, :db => uri.path.gsub('/', '') } end
ruby
def get_opts(db_uri) uri = URI.parse(db_uri) { :host => uri.host, :port => uri.port, :user => uri.user, :password => uri.password, :db => uri.path.gsub('/', '') } end
[ "def", "get_opts", "(", "db_uri", ")", "uri", "=", "URI", ".", "parse", "(", "db_uri", ")", "{", ":host", "=>", "uri", ".", "host", ",", ":port", "=>", "uri", ".", "port", ",", ":user", "=>", "uri", ".", "user", ",", ":password", "=>", "uri", ".", "password", ",", ":db", "=>", "uri", ".", "path", ".", "gsub", "(", "'/'", ",", "''", ")", "}", "end" ]
Initialize a ne DB object. @return [DB] Parse the MongoDB URI. @param [String] db_uri the DB URI. @return [Hash]
[ "Initialize", "a", "ne", "DB", "object", "." ]
bc1553188df97d3df825de6d826b34ab7185a431
https://github.com/marcboeker/mongolicious/blob/bc1553188df97d3df825de6d826b34ab7185a431/lib/mongolicious/db.rb#L16-L26
train
marcboeker/mongolicious
lib/mongolicious/db.rb
Mongolicious.DB.dump
def dump(db, path) Mongolicious.logger.info("Dumping database #{db[:db]}") cmd = "mongodump -d #{db[:db]} -h #{db[:host]}:#{db[:port]} -o #{path}" cmd << " -u '#{db[:user]}' -p '#{db[:password]}'" unless (db[:user].nil? || db[:user].empty?) cmd << " > /dev/null" system(cmd) raise "Error while backuing up #{db[:db]}" if $?.to_i != 0 end
ruby
def dump(db, path) Mongolicious.logger.info("Dumping database #{db[:db]}") cmd = "mongodump -d #{db[:db]} -h #{db[:host]}:#{db[:port]} -o #{path}" cmd << " -u '#{db[:user]}' -p '#{db[:password]}'" unless (db[:user].nil? || db[:user].empty?) cmd << " > /dev/null" system(cmd) raise "Error while backuing up #{db[:db]}" if $?.to_i != 0 end
[ "def", "dump", "(", "db", ",", "path", ")", "Mongolicious", ".", "logger", ".", "info", "(", "\"Dumping database #{db[:db]}\"", ")", "cmd", "=", "\"mongodump -d #{db[:db]} -h #{db[:host]}:#{db[:port]} -o #{path}\"", "cmd", "<<", "\" -u '#{db[:user]}' -p '#{db[:password]}'\"", "unless", "(", "db", "[", ":user", "]", ".", "nil?", "||", "db", "[", ":user", "]", ".", "empty?", ")", "cmd", "<<", "\" > /dev/null\"", "system", "(", "cmd", ")", "raise", "\"Error while backuing up #{db[:db]}\"", "if", "$?", ".", "to_i", "!=", "0", "end" ]
Dump database using mongodump. @param [Hash] db the DB connection opts. @param [String] path the path, where the dump should be stored. @return [nil]
[ "Dump", "database", "using", "mongodump", "." ]
bc1553188df97d3df825de6d826b34ab7185a431
https://github.com/marcboeker/mongolicious/blob/bc1553188df97d3df825de6d826b34ab7185a431/lib/mongolicious/db.rb#L34-L43
train
postmodern/wsoc
lib/wsoc/runner.rb
WSOC.Runner.run
def run(*args) optparse(*args) options = { :env => :production, :host => @host, :port => @port } options.merge!(:server => @handler) if @handler App.run!(options) end
ruby
def run(*args) optparse(*args) options = { :env => :production, :host => @host, :port => @port } options.merge!(:server => @handler) if @handler App.run!(options) end
[ "def", "run", "(", "*", "args", ")", "optparse", "(", "args", ")", "options", "=", "{", ":env", "=>", ":production", ",", ":host", "=>", "@host", ",", ":port", "=>", "@port", "}", "options", ".", "merge!", "(", ":server", "=>", "@handler", ")", "if", "@handler", "App", ".", "run!", "(", "options", ")", "end" ]
Runs the runner. @param [Array<String>] args The arguments to run the runner with. @since 0.1.0
[ "Runs", "the", "runner", "." ]
b8b82f0cef0fd8594c48c45d3b213bc65412b455
https://github.com/postmodern/wsoc/blob/b8b82f0cef0fd8594c48c45d3b213bc65412b455/lib/wsoc/runner.rb#L67-L79
train
rodrigopinto/biju
lib/biju/modem.rb
Biju.Modem.messages
def messages(which = "ALL") # read message from all storage in the mobile phone (sim+mem) cmd('AT+CPMS="MT"') # get message list sms = cmd('AT+CMGL="%s"' % which ) # collect messages msgs = sms.scan(/\+CMGL\:\s*?(\d+)\,.*?\,\"(.+?)\"\,.*?\,\"(.+?)\".*?\n(.*)/) return nil unless msgs msgs.collect!{ |msg| Biju::Sms.new(:id => msg[0], :phone_number => msg[1], :datetime => msg[2], :message => msg[3].chomp) } end
ruby
def messages(which = "ALL") # read message from all storage in the mobile phone (sim+mem) cmd('AT+CPMS="MT"') # get message list sms = cmd('AT+CMGL="%s"' % which ) # collect messages msgs = sms.scan(/\+CMGL\:\s*?(\d+)\,.*?\,\"(.+?)\"\,.*?\,\"(.+?)\".*?\n(.*)/) return nil unless msgs msgs.collect!{ |msg| Biju::Sms.new(:id => msg[0], :phone_number => msg[1], :datetime => msg[2], :message => msg[3].chomp) } end
[ "def", "messages", "(", "which", "=", "\"ALL\"", ")", "# read message from all storage in the mobile phone (sim+mem)", "cmd", "(", "'AT+CPMS=\"MT\"'", ")", "# get message list", "sms", "=", "cmd", "(", "'AT+CMGL=\"%s\"'", "%", "which", ")", "# collect messages", "msgs", "=", "sms", ".", "scan", "(", "/", "\\+", "\\:", "\\s", "\\d", "\\,", "\\,", "\\\"", "\\\"", "\\,", "\\,", "\\\"", "\\\"", "\\n", "/", ")", "return", "nil", "unless", "msgs", "msgs", ".", "collect!", "{", "|", "msg", "|", "Biju", "::", "Sms", ".", "new", "(", ":id", "=>", "msg", "[", "0", "]", ",", ":phone_number", "=>", "msg", "[", "1", "]", ",", ":datetime", "=>", "msg", "[", "2", "]", ",", ":message", "=>", "msg", "[", "3", "]", ".", "chomp", ")", "}", "end" ]
Return an Array of Sms if there is messages nad return nil if not.
[ "Return", "an", "Array", "of", "Sms", "if", "there", "is", "messages", "nad", "return", "nil", "if", "not", "." ]
898d8d73a9cac0f6bca68731927c37343b9e0ff6
https://github.com/rodrigopinto/biju/blob/898d8d73a9cac0f6bca68731927c37343b9e0ff6/lib/biju/modem.rb#L34-L43
train
djhworld/gmail-mailer
lib/gmail-mailer.rb
GmailMailer.Mailer.send_smtp
def send_smtp(mail) smtp = Net::SMTP.new(SMTP_SERVER, SMTP_PORT) smtp.enable_starttls_auto secret = { :consumer_key => SMTP_CONSUMER_KEY, :consumer_secret => SMTP_CONSUMER_SECRET, :token => @email_credentials[:smtp_oauth_token], :token_secret => @email_credentials[:smtp_oauth_token_secret] } smtp.start(SMTP_HOST, @email_credentials[:email], secret, :xoauth) do |session| print "Sending message..." session.send_message(mail.encoded, mail.from_addrs.first, mail.destinations) puts ".sent!" end end
ruby
def send_smtp(mail) smtp = Net::SMTP.new(SMTP_SERVER, SMTP_PORT) smtp.enable_starttls_auto secret = { :consumer_key => SMTP_CONSUMER_KEY, :consumer_secret => SMTP_CONSUMER_SECRET, :token => @email_credentials[:smtp_oauth_token], :token_secret => @email_credentials[:smtp_oauth_token_secret] } smtp.start(SMTP_HOST, @email_credentials[:email], secret, :xoauth) do |session| print "Sending message..." session.send_message(mail.encoded, mail.from_addrs.first, mail.destinations) puts ".sent!" end end
[ "def", "send_smtp", "(", "mail", ")", "smtp", "=", "Net", "::", "SMTP", ".", "new", "(", "SMTP_SERVER", ",", "SMTP_PORT", ")", "smtp", ".", "enable_starttls_auto", "secret", "=", "{", ":consumer_key", "=>", "SMTP_CONSUMER_KEY", ",", ":consumer_secret", "=>", "SMTP_CONSUMER_SECRET", ",", ":token", "=>", "@email_credentials", "[", ":smtp_oauth_token", "]", ",", ":token_secret", "=>", "@email_credentials", "[", ":smtp_oauth_token_secret", "]", "}", "smtp", ".", "start", "(", "SMTP_HOST", ",", "@email_credentials", "[", ":email", "]", ",", "secret", ",", ":xoauth", ")", "do", "|", "session", "|", "print", "\"Sending message...\"", "session", ".", "send_message", "(", "mail", ".", "encoded", ",", "mail", ".", "from_addrs", ".", "first", ",", "mail", ".", "destinations", ")", "puts", "\".sent!\"", "end", "end" ]
Use gmail_xoauth to send email
[ "Use", "gmail_xoauth", "to", "send", "email" ]
b63c259d124950b612d20bcad1e82d260984f0e9
https://github.com/djhworld/gmail-mailer/blob/b63c259d124950b612d20bcad1e82d260984f0e9/lib/gmail-mailer.rb#L49-L63
train
ryansobol/mango
lib/mango/application.rb
Mango.Application.render_404_public_file!
def render_404_public_file!(file_name) four_oh_four_path = File.expand_path("#{file_name}.html", settings.public_dir) return unless File.file?(four_oh_four_path) send_file four_oh_four_path, status: 404 end
ruby
def render_404_public_file!(file_name) four_oh_four_path = File.expand_path("#{file_name}.html", settings.public_dir) return unless File.file?(four_oh_four_path) send_file four_oh_four_path, status: 404 end
[ "def", "render_404_public_file!", "(", "file_name", ")", "four_oh_four_path", "=", "File", ".", "expand_path", "(", "\"#{file_name}.html\"", ",", "settings", ".", "public_dir", ")", "return", "unless", "File", ".", "file?", "(", "four_oh_four_path", ")", "send_file", "four_oh_four_path", ",", "status", ":", "404", "end" ]
Given a file name, attempts to send an public 404 file, if it exists, and halt @param [String] file_name
[ "Given", "a", "file", "name", "attempts", "to", "send", "an", "public", "404", "file", "if", "it", "exists", "and", "halt" ]
f28f1fb9ff2820f11e6b9f96cdd92576774da12f
https://github.com/ryansobol/mango/blob/f28f1fb9ff2820f11e6b9f96cdd92576774da12f/lib/mango/application.rb#L275-L279
train
ryansobol/mango
lib/mango/application.rb
Mango.Application.render_404_template!
def render_404_template!(template_name) VIEW_TEMPLATE_ENGINES.each do |engine, extension| @preferred_extension = extension.to_s find_template(settings.views, template_name, engine) do |file| next unless File.file?(file) halt send(extension, template_name.to_sym, layout: false) end end end
ruby
def render_404_template!(template_name) VIEW_TEMPLATE_ENGINES.each do |engine, extension| @preferred_extension = extension.to_s find_template(settings.views, template_name, engine) do |file| next unless File.file?(file) halt send(extension, template_name.to_sym, layout: false) end end end
[ "def", "render_404_template!", "(", "template_name", ")", "VIEW_TEMPLATE_ENGINES", ".", "each", "do", "|", "engine", ",", "extension", "|", "@preferred_extension", "=", "extension", ".", "to_s", "find_template", "(", "settings", ".", "views", ",", "template_name", ",", "engine", ")", "do", "|", "file", "|", "next", "unless", "File", ".", "file?", "(", "file", ")", "halt", "send", "(", "extension", ",", "template_name", ".", "to_sym", ",", "layout", ":", "false", ")", "end", "end", "end" ]
Given a template name, and with a prioritized list of template engines, attempts to render a 404 template, if one exists, and halt. @param [String] template_name @see VIEW_TEMPLATE_ENGINES
[ "Given", "a", "template", "name", "and", "with", "a", "prioritized", "list", "of", "template", "engines", "attempts", "to", "render", "a", "404", "template", "if", "one", "exists", "and", "halt", "." ]
f28f1fb9ff2820f11e6b9f96cdd92576774da12f
https://github.com/ryansobol/mango/blob/f28f1fb9ff2820f11e6b9f96cdd92576774da12f/lib/mango/application.rb#L287-L295
train
ryansobol/mango
lib/mango/application.rb
Mango.Application.render_javascript_template!
def render_javascript_template!(uri_path) javascript_match = File.join(settings.javascripts, "*") javascript_path = File.expand_path(uri_path, settings.javascripts) return unless File.fnmatch(javascript_match, javascript_path) JAVASCRIPT_TEMPLATE_ENGINES.each do |engine, extension| @preferred_extension = extension.to_s find_template(settings.javascripts, uri_path, engine) do |file| next unless File.file?(file) halt send(extension, uri_path.to_sym, views: settings.javascripts) end end end
ruby
def render_javascript_template!(uri_path) javascript_match = File.join(settings.javascripts, "*") javascript_path = File.expand_path(uri_path, settings.javascripts) return unless File.fnmatch(javascript_match, javascript_path) JAVASCRIPT_TEMPLATE_ENGINES.each do |engine, extension| @preferred_extension = extension.to_s find_template(settings.javascripts, uri_path, engine) do |file| next unless File.file?(file) halt send(extension, uri_path.to_sym, views: settings.javascripts) end end end
[ "def", "render_javascript_template!", "(", "uri_path", ")", "javascript_match", "=", "File", ".", "join", "(", "settings", ".", "javascripts", ",", "\"*\"", ")", "javascript_path", "=", "File", ".", "expand_path", "(", "uri_path", ",", "settings", ".", "javascripts", ")", "return", "unless", "File", ".", "fnmatch", "(", "javascript_match", ",", "javascript_path", ")", "JAVASCRIPT_TEMPLATE_ENGINES", ".", "each", "do", "|", "engine", ",", "extension", "|", "@preferred_extension", "=", "extension", ".", "to_s", "find_template", "(", "settings", ".", "javascripts", ",", "uri_path", ",", "engine", ")", "do", "|", "file", "|", "next", "unless", "File", ".", "file?", "(", "file", ")", "halt", "send", "(", "extension", ",", "uri_path", ".", "to_sym", ",", "views", ":", "settings", ".", "javascripts", ")", "end", "end", "end" ]
Given a URI path, attempts to render a JavaScript template, if it exists, and halt @param [String] uri_path @see JAVASCRIPT_TEMPLATE_ENGINES
[ "Given", "a", "URI", "path", "attempts", "to", "render", "a", "JavaScript", "template", "if", "it", "exists", "and", "halt" ]
f28f1fb9ff2820f11e6b9f96cdd92576774da12f
https://github.com/ryansobol/mango/blob/f28f1fb9ff2820f11e6b9f96cdd92576774da12f/lib/mango/application.rb#L355-L368
train
ryansobol/mango
lib/mango/application.rb
Mango.Application.render_stylesheet_template!
def render_stylesheet_template!(uri_path) stylesheet_match = File.join(settings.stylesheets, "*") stylesheet_path = File.expand_path(uri_path, settings.stylesheets) return unless File.fnmatch(stylesheet_match, stylesheet_path) STYLESHEET_TEMPLATE_ENGINES.each do |engine, extension| @preferred_extension = extension.to_s find_template(settings.stylesheets, uri_path, engine) do |file| next unless File.file?(file) halt send(extension, uri_path.to_sym, views: settings.stylesheets) end end end
ruby
def render_stylesheet_template!(uri_path) stylesheet_match = File.join(settings.stylesheets, "*") stylesheet_path = File.expand_path(uri_path, settings.stylesheets) return unless File.fnmatch(stylesheet_match, stylesheet_path) STYLESHEET_TEMPLATE_ENGINES.each do |engine, extension| @preferred_extension = extension.to_s find_template(settings.stylesheets, uri_path, engine) do |file| next unless File.file?(file) halt send(extension, uri_path.to_sym, views: settings.stylesheets) end end end
[ "def", "render_stylesheet_template!", "(", "uri_path", ")", "stylesheet_match", "=", "File", ".", "join", "(", "settings", ".", "stylesheets", ",", "\"*\"", ")", "stylesheet_path", "=", "File", ".", "expand_path", "(", "uri_path", ",", "settings", ".", "stylesheets", ")", "return", "unless", "File", ".", "fnmatch", "(", "stylesheet_match", ",", "stylesheet_path", ")", "STYLESHEET_TEMPLATE_ENGINES", ".", "each", "do", "|", "engine", ",", "extension", "|", "@preferred_extension", "=", "extension", ".", "to_s", "find_template", "(", "settings", ".", "stylesheets", ",", "uri_path", ",", "engine", ")", "do", "|", "file", "|", "next", "unless", "File", ".", "file?", "(", "file", ")", "halt", "send", "(", "extension", ",", "uri_path", ".", "to_sym", ",", "views", ":", "settings", ".", "stylesheets", ")", "end", "end", "end" ]
Given a URI path, attempts to render a stylesheet template, if it exists, and halt @param [String] uri_path @see STYLESHEET_TEMPLATE_ENGINES
[ "Given", "a", "URI", "path", "attempts", "to", "render", "a", "stylesheet", "template", "if", "it", "exists", "and", "halt" ]
f28f1fb9ff2820f11e6b9f96cdd92576774da12f
https://github.com/ryansobol/mango/blob/f28f1fb9ff2820f11e6b9f96cdd92576774da12f/lib/mango/application.rb#L425-L438
train
ryansobol/mango
lib/mango/application.rb
Mango.Application.render_index_file!
def render_index_file!(uri_path) return unless URI.directory?(uri_path) index_match = File.join(settings.public_dir, "*") index_file_path = File.expand_path(uri_path + "index.html", settings.public_dir) return unless File.fnmatch(index_match, index_file_path) return unless File.file?(index_file_path) send_file index_file_path end
ruby
def render_index_file!(uri_path) return unless URI.directory?(uri_path) index_match = File.join(settings.public_dir, "*") index_file_path = File.expand_path(uri_path + "index.html", settings.public_dir) return unless File.fnmatch(index_match, index_file_path) return unless File.file?(index_file_path) send_file index_file_path end
[ "def", "render_index_file!", "(", "uri_path", ")", "return", "unless", "URI", ".", "directory?", "(", "uri_path", ")", "index_match", "=", "File", ".", "join", "(", "settings", ".", "public_dir", ",", "\"*\"", ")", "index_file_path", "=", "File", ".", "expand_path", "(", "uri_path", "+", "\"index.html\"", ",", "settings", ".", "public_dir", ")", "return", "unless", "File", ".", "fnmatch", "(", "index_match", ",", "index_file_path", ")", "return", "unless", "File", ".", "file?", "(", "index_file_path", ")", "send_file", "index_file_path", "end" ]
Given a URI path, attempts to send an index.html file, if it exists, and halt @param [String] uri_path
[ "Given", "a", "URI", "path", "attempts", "to", "send", "an", "index", ".", "html", "file", "if", "it", "exists", "and", "halt" ]
f28f1fb9ff2820f11e6b9f96cdd92576774da12f
https://github.com/ryansobol/mango/blob/f28f1fb9ff2820f11e6b9f96cdd92576774da12f/lib/mango/application.rb#L504-L514
train
ryansobol/mango
lib/mango/application.rb
Mango.Application.render_content_page!
def render_content_page!(uri_path) uri_path += "index" if URI.directory?(uri_path) content_match = File.join(settings.content, "*") content_page_path = File.expand_path(uri_path, settings.content) return unless File.fnmatch(content_match, content_page_path) begin content_page = find_content_page(uri_path) rescue ContentPageNotFound return end view_template_path = File.expand_path(content_page.view, settings.views) begin engine = VIEW_TEMPLATE_ENGINES.fetch(Tilt[content_page.view]) rescue KeyError message = "Cannot find registered engine for view template file -- #{view_template_path}" raise RegisteredEngineNotFound, message end begin halt send(engine, content_page.view.to_s.templatize, locals: { page: content_page }) rescue Errno::ENOENT message = "Cannot find view template file -- #{view_template_path}" raise ViewTemplateNotFound, message end end
ruby
def render_content_page!(uri_path) uri_path += "index" if URI.directory?(uri_path) content_match = File.join(settings.content, "*") content_page_path = File.expand_path(uri_path, settings.content) return unless File.fnmatch(content_match, content_page_path) begin content_page = find_content_page(uri_path) rescue ContentPageNotFound return end view_template_path = File.expand_path(content_page.view, settings.views) begin engine = VIEW_TEMPLATE_ENGINES.fetch(Tilt[content_page.view]) rescue KeyError message = "Cannot find registered engine for view template file -- #{view_template_path}" raise RegisteredEngineNotFound, message end begin halt send(engine, content_page.view.to_s.templatize, locals: { page: content_page }) rescue Errno::ENOENT message = "Cannot find view template file -- #{view_template_path}" raise ViewTemplateNotFound, message end end
[ "def", "render_content_page!", "(", "uri_path", ")", "uri_path", "+=", "\"index\"", "if", "URI", ".", "directory?", "(", "uri_path", ")", "content_match", "=", "File", ".", "join", "(", "settings", ".", "content", ",", "\"*\"", ")", "content_page_path", "=", "File", ".", "expand_path", "(", "uri_path", ",", "settings", ".", "content", ")", "return", "unless", "File", ".", "fnmatch", "(", "content_match", ",", "content_page_path", ")", "begin", "content_page", "=", "find_content_page", "(", "uri_path", ")", "rescue", "ContentPageNotFound", "return", "end", "view_template_path", "=", "File", ".", "expand_path", "(", "content_page", ".", "view", ",", "settings", ".", "views", ")", "begin", "engine", "=", "VIEW_TEMPLATE_ENGINES", ".", "fetch", "(", "Tilt", "[", "content_page", ".", "view", "]", ")", "rescue", "KeyError", "message", "=", "\"Cannot find registered engine for view template file -- #{view_template_path}\"", "raise", "RegisteredEngineNotFound", ",", "message", "end", "begin", "halt", "send", "(", "engine", ",", "content_page", ".", "view", ".", "to_s", ".", "templatize", ",", "locals", ":", "{", "page", ":", "content_page", "}", ")", "rescue", "Errno", "::", "ENOENT", "message", "=", "\"Cannot find view template file -- #{view_template_path}\"", "raise", "ViewTemplateNotFound", ",", "message", "end", "end" ]
Given a URI path, attempts to render a content page, if it exists, and halt @param [String] uri_path @raise [RegisteredEngineNotFound] Raised when a registered engine for the content page's view template cannot be found @raise [ViewTemplateNotFound] Raised when the content page's view template cannot be found
[ "Given", "a", "URI", "path", "attempts", "to", "render", "a", "content", "page", "if", "it", "exists", "and", "halt" ]
f28f1fb9ff2820f11e6b9f96cdd92576774da12f
https://github.com/ryansobol/mango/blob/f28f1fb9ff2820f11e6b9f96cdd92576774da12f/lib/mango/application.rb#L533-L561
train
ryansobol/mango
lib/mango/application.rb
Mango.Application.find_content_page
def find_content_page(uri_path) ContentPage::TEMPLATE_ENGINES.each do |engine, extension| @preferred_extension = extension.to_s find_template(settings.content, uri_path, engine) do |file| next unless File.file?(file) return ContentPage.new(data: File.read(file), engine: engine) end end raise ContentPageNotFound, "Cannot find content page for path -- #{uri_path}" end
ruby
def find_content_page(uri_path) ContentPage::TEMPLATE_ENGINES.each do |engine, extension| @preferred_extension = extension.to_s find_template(settings.content, uri_path, engine) do |file| next unless File.file?(file) return ContentPage.new(data: File.read(file), engine: engine) end end raise ContentPageNotFound, "Cannot find content page for path -- #{uri_path}" end
[ "def", "find_content_page", "(", "uri_path", ")", "ContentPage", "::", "TEMPLATE_ENGINES", ".", "each", "do", "|", "engine", ",", "extension", "|", "@preferred_extension", "=", "extension", ".", "to_s", "find_template", "(", "settings", ".", "content", ",", "uri_path", ",", "engine", ")", "do", "|", "file", "|", "next", "unless", "File", ".", "file?", "(", "file", ")", "return", "ContentPage", ".", "new", "(", "data", ":", "File", ".", "read", "(", "file", ")", ",", "engine", ":", "engine", ")", "end", "end", "raise", "ContentPageNotFound", ",", "\"Cannot find content page for path -- #{uri_path}\"", "end" ]
Given a URI path, creates a new `ContentPage` instance by searching for and reading a content file from disk. Content files are searched consecutively until a page with a supported content page template engine is found. @param [String] uri_path @raise [ContentPageNotFound] Raised when a content page cannot be found for the uri path @return [ContentPage] A new instance is created and returned when found @see ContentPage::TEMPLATE_ENGINES
[ "Given", "a", "URI", "path", "creates", "a", "new", "ContentPage", "instance", "by", "searching", "for", "and", "reading", "a", "content", "file", "from", "disk", ".", "Content", "files", "are", "searched", "consecutively", "until", "a", "page", "with", "a", "supported", "content", "page", "template", "engine", "is", "found", "." ]
f28f1fb9ff2820f11e6b9f96cdd92576774da12f
https://github.com/ryansobol/mango/blob/f28f1fb9ff2820f11e6b9f96cdd92576774da12f/lib/mango/application.rb#L572-L582
train
skift/estore_conventions
lib/estore_conventions.rb
EstoreConventions.ClassMethods.factory_build_for_store
def factory_build_for_store(atts_hash, identifier_conditions = {}, full_data_object={}, &blk) if identifier_conditions.empty? record = self.new else record = self.where(identifier_conditions).first_or_initialize end record.assign_attributes(atts_hash, :without_protection => true) if block_given? yield record, full_data_object end return record end
ruby
def factory_build_for_store(atts_hash, identifier_conditions = {}, full_data_object={}, &blk) if identifier_conditions.empty? record = self.new else record = self.where(identifier_conditions).first_or_initialize end record.assign_attributes(atts_hash, :without_protection => true) if block_given? yield record, full_data_object end return record end
[ "def", "factory_build_for_store", "(", "atts_hash", ",", "identifier_conditions", "=", "{", "}", ",", "full_data_object", "=", "{", "}", ",", "&", "blk", ")", "if", "identifier_conditions", ".", "empty?", "record", "=", "self", ".", "new", "else", "record", "=", "self", ".", "where", "(", "identifier_conditions", ")", ".", "first_or_initialize", "end", "record", ".", "assign_attributes", "(", "atts_hash", ",", ":without_protection", "=>", "true", ")", "if", "block_given?", "yield", "record", ",", "full_data_object", "end", "return", "record", "end" ]
atts_hash are the attributes to assign to the Record identifier_conditions is what the scope for first_or_initialize is called upon so that an existing object is updated full_data_object is passed in to be saved as a blob
[ "atts_hash", "are", "the", "attributes", "to", "assign", "to", "the", "Record", "identifier_conditions", "is", "what", "the", "scope", "for", "first_or_initialize", "is", "called", "upon", "so", "that", "an", "existing", "object", "is", "updated", "full_data_object", "is", "passed", "in", "to", "be", "saved", "as", "a", "blob" ]
b9f1dfa45d476ecbadaa0a50729aeef064961183
https://github.com/skift/estore_conventions/blob/b9f1dfa45d476ecbadaa0a50729aeef064961183/lib/estore_conventions.rb#L40-L53
train
wwidea/rexport
lib/rexport/tree_node.rb
Rexport.TreeNode.add_child
def add_child(*names) names.flatten! return unless name = names.shift node = children.find { |c| c.name == name } node ? node.add_child(names) : (children << TreeNode.new(name, names)) end
ruby
def add_child(*names) names.flatten! return unless name = names.shift node = children.find { |c| c.name == name } node ? node.add_child(names) : (children << TreeNode.new(name, names)) end
[ "def", "add_child", "(", "*", "names", ")", "names", ".", "flatten!", "return", "unless", "name", "=", "names", ".", "shift", "node", "=", "children", ".", "find", "{", "|", "c", "|", "c", ".", "name", "==", "name", "}", "node", "?", "node", ".", "add_child", "(", "names", ")", ":", "(", "children", "<<", "TreeNode", ".", "new", "(", "name", ",", "names", ")", ")", "end" ]
Initialize a tree node setting name and adding a child if one was passed Add one or more children to the tree
[ "Initialize", "a", "tree", "node", "setting", "name", "and", "adding", "a", "child", "if", "one", "was", "passed", "Add", "one", "or", "more", "children", "to", "the", "tree" ]
f4f978dd0327ddba3a4318dd24090fbc6d4e4e59
https://github.com/wwidea/rexport/blob/f4f978dd0327ddba3a4318dd24090fbc6d4e4e59/lib/rexport/tree_node.rb#L14-L19
train
lkdjiin/bookmarks
lib/bookmarks/document.rb
Bookmarks.Document.parse_a_bookmark
def parse_a_bookmark line line = line.strip if line =~ /^<DT><H3/ @h3_tags << h3_tags(line) elsif line =~ /^<\/DL>/ @h3_tags.pop elsif line =~ /<DT><A HREF="http/ @bookmarks << NetscapeBookmark.from_string(line) if (not @h3_tags.empty?) && (not @bookmarks.last.nil?) @bookmarks.last.add_tags @h3_tags end elsif line =~ /^<DD>/ @bookmarks.last.description = line[4..-1].chomp end end
ruby
def parse_a_bookmark line line = line.strip if line =~ /^<DT><H3/ @h3_tags << h3_tags(line) elsif line =~ /^<\/DL>/ @h3_tags.pop elsif line =~ /<DT><A HREF="http/ @bookmarks << NetscapeBookmark.from_string(line) if (not @h3_tags.empty?) && (not @bookmarks.last.nil?) @bookmarks.last.add_tags @h3_tags end elsif line =~ /^<DD>/ @bookmarks.last.description = line[4..-1].chomp end end
[ "def", "parse_a_bookmark", "line", "line", "=", "line", ".", "strip", "if", "line", "=~", "/", "/", "@h3_tags", "<<", "h3_tags", "(", "line", ")", "elsif", "line", "=~", "/", "\\/", "/", "@h3_tags", ".", "pop", "elsif", "line", "=~", "/", "/", "@bookmarks", "<<", "NetscapeBookmark", ".", "from_string", "(", "line", ")", "if", "(", "not", "@h3_tags", ".", "empty?", ")", "&&", "(", "not", "@bookmarks", ".", "last", ".", "nil?", ")", "@bookmarks", ".", "last", ".", "add_tags", "@h3_tags", "end", "elsif", "line", "=~", "/", "/", "@bookmarks", ".", "last", ".", "description", "=", "line", "[", "4", "..", "-", "1", "]", ".", "chomp", "end", "end" ]
Parse a single line from a bookmarks file. line - String. Returns nothing. TODO This should have its own parser class.
[ "Parse", "a", "single", "line", "from", "a", "bookmarks", "file", "." ]
6f6bdf94f2de5347a9db19d01ad0721033cf0123
https://github.com/lkdjiin/bookmarks/blob/6f6bdf94f2de5347a9db19d01ad0721033cf0123/lib/bookmarks/document.rb#L78-L92
train
nickcharlton/atlas-ruby
lib/atlas/box_version.rb
Atlas.BoxVersion.save
def save # rubocop:disable Metrics/AbcSize body = { version: to_hash } # providers are saved seperately body[:version].delete(:providers) begin response = Atlas.client.put(url_builder.box_version_url, body: body) rescue Atlas::Errors::NotFoundError response = Atlas.client.post("#{url_builder.box_url}/versions", body: body) end # trigger the same on the providers providers.each(&:save) if providers update_with_response(response, [:providers]) end
ruby
def save # rubocop:disable Metrics/AbcSize body = { version: to_hash } # providers are saved seperately body[:version].delete(:providers) begin response = Atlas.client.put(url_builder.box_version_url, body: body) rescue Atlas::Errors::NotFoundError response = Atlas.client.post("#{url_builder.box_url}/versions", body: body) end # trigger the same on the providers providers.each(&:save) if providers update_with_response(response, [:providers]) end
[ "def", "save", "# rubocop:disable Metrics/AbcSize", "body", "=", "{", "version", ":", "to_hash", "}", "# providers are saved seperately", "body", "[", ":version", "]", ".", "delete", "(", ":providers", ")", "begin", "response", "=", "Atlas", ".", "client", ".", "put", "(", "url_builder", ".", "box_version_url", ",", "body", ":", "body", ")", "rescue", "Atlas", "::", "Errors", "::", "NotFoundError", "response", "=", "Atlas", ".", "client", ".", "post", "(", "\"#{url_builder.box_url}/versions\"", ",", "body", ":", "body", ")", "end", "# trigger the same on the providers", "providers", ".", "each", "(", ":save", ")", "if", "providers", "update_with_response", "(", "response", ",", "[", ":providers", "]", ")", "end" ]
Save the version. @return [Hash] Atlas response object.
[ "Save", "the", "version", "." ]
2170c04496682e0d8e7c959bd9f267f62fa84c1d
https://github.com/nickcharlton/atlas-ruby/blob/2170c04496682e0d8e7c959bd9f267f62fa84c1d/lib/atlas/box_version.rb#L80-L97
train
sight-labs/enchanted_quill
lib/enchanted_quill/label.rb
EnchantedQuill.Label.textRectForBounds
def textRectForBounds(bounds, limitedToNumberOfLines: num_of_lines) required_rect = rect_fitting_text_for_container_size(bounds.size, for_number_of_line: num_of_lines) text_container.size = required_rect.size required_rect end
ruby
def textRectForBounds(bounds, limitedToNumberOfLines: num_of_lines) required_rect = rect_fitting_text_for_container_size(bounds.size, for_number_of_line: num_of_lines) text_container.size = required_rect.size required_rect end
[ "def", "textRectForBounds", "(", "bounds", ",", "limitedToNumberOfLines", ":", "num_of_lines", ")", "required_rect", "=", "rect_fitting_text_for_container_size", "(", "bounds", ".", "size", ",", "for_number_of_line", ":", "num_of_lines", ")", "text_container", ".", "size", "=", "required_rect", ".", "size", "required_rect", "end" ]
Override UILabel Methods
[ "Override", "UILabel", "Methods" ]
d8c70f50fea320878249fec7ed3ea134a4975f32
https://github.com/sight-labs/enchanted_quill/blob/d8c70f50fea320878249fec7ed3ea134a4975f32/lib/enchanted_quill/label.rb#L66-L70
train