id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
23,100
domgetter/dare
lib/dare/window.rb
Dare.Window.add_keyboard_event_listeners
def add_keyboard_event_listeners Element.find("html").on :keydown do |event| @keys[get_key_id(event)] = true end Element.find("html").on :keyup do |event| @keys[get_key_id(event)] = false end ::Window.on :blur do |event| @keys.fill false end end
ruby
def add_keyboard_event_listeners Element.find("html").on :keydown do |event| @keys[get_key_id(event)] = true end Element.find("html").on :keyup do |event| @keys[get_key_id(event)] = false end ::Window.on :blur do |event| @keys.fill false end end
[ "def", "add_keyboard_event_listeners", "Element", ".", "find", "(", "\"html\"", ")", ".", "on", ":keydown", "do", "|", "event", "|", "@keys", "[", "get_key_id", "(", "event", ")", "]", "=", "true", "end", "Element", ".", "find", "(", "\"html\"", ")", ".", "on", ":keyup", "do", "|", "event", "|", "@keys", "[", "get_key_id", "(", "event", ")", "]", "=", "false", "end", "::", "Window", ".", "on", ":blur", "do", "|", "event", "|", "@keys", ".", "fill", "false", "end", "end" ]
adds keyboard event listeners to entire page
[ "adds", "keyboard", "event", "listeners", "to", "entire", "page" ]
a017efd98275992912f016fefe45a17f00117fe5
https://github.com/domgetter/dare/blob/a017efd98275992912f016fefe45a17f00117fe5/lib/dare/window.rb#L77-L87
23,101
kameeoze/jruby-poi
lib/poi/workbook/worksheet.rb
POI.Worksheet.[]
def [](row_index) if Fixnum === row_index rows[row_index] else ref = org.apache.poi.ss.util.CellReference.new(row_index) cell = rows[ref.row][ref.col] cell && cell.value ? cell.value : cell end end
ruby
def [](row_index) if Fixnum === row_index rows[row_index] else ref = org.apache.poi.ss.util.CellReference.new(row_index) cell = rows[ref.row][ref.col] cell && cell.value ? cell.value : cell end end
[ "def", "[]", "(", "row_index", ")", "if", "Fixnum", "===", "row_index", "rows", "[", "row_index", "]", "else", "ref", "=", "org", ".", "apache", ".", "poi", ".", "ss", ".", "util", ".", "CellReference", ".", "new", "(", "row_index", ")", "cell", "=", "rows", "[", "ref", ".", "row", "]", "[", "ref", ".", "col", "]", "cell", "&&", "cell", ".", "value", "?", "cell", ".", "value", ":", "cell", "end", "end" ]
Accepts a Fixnum or a String as the row_index row_index as Fixnum: returns the 0-based row row_index as String: assumes a cell reference within this sheet if the value of the reference is non-nil the value is returned, otherwise the referenced cell is returned
[ "Accepts", "a", "Fixnum", "or", "a", "String", "as", "the", "row_index" ]
c10b7e7ccfd19f132d153834ea0372a67a1d4981
https://github.com/kameeoze/jruby-poi/blob/c10b7e7ccfd19f132d153834ea0372a67a1d4981/lib/poi/workbook/worksheet.rb#L59-L67
23,102
antw/iniparse
lib/iniparse/generator.rb
IniParse.Generator.section
def section(name, opts = {}) if @in_section # Nesting sections is bad, mmmkay? raise LineNotAllowed, "You can't nest sections in INI files." end # Add to a section if it already exists if @document.has_section?(name.to_s()) @context = @document[name.to_s()] else @context = Lines::Section.new(name, line_options(opts)) @document.lines << @context end if block_given? begin @in_section = true with_options(opts) { yield self } @context = @document blank() ensure @in_section = false end end end
ruby
def section(name, opts = {}) if @in_section # Nesting sections is bad, mmmkay? raise LineNotAllowed, "You can't nest sections in INI files." end # Add to a section if it already exists if @document.has_section?(name.to_s()) @context = @document[name.to_s()] else @context = Lines::Section.new(name, line_options(opts)) @document.lines << @context end if block_given? begin @in_section = true with_options(opts) { yield self } @context = @document blank() ensure @in_section = false end end end
[ "def", "section", "(", "name", ",", "opts", "=", "{", "}", ")", "if", "@in_section", "# Nesting sections is bad, mmmkay?", "raise", "LineNotAllowed", ",", "\"You can't nest sections in INI files.\"", "end", "# Add to a section if it already exists", "if", "@document", ".", "has_section?", "(", "name", ".", "to_s", "(", ")", ")", "@context", "=", "@document", "[", "name", ".", "to_s", "(", ")", "]", "else", "@context", "=", "Lines", "::", "Section", ".", "new", "(", "name", ",", "line_options", "(", "opts", ")", ")", "@document", ".", "lines", "<<", "@context", "end", "if", "block_given?", "begin", "@in_section", "=", "true", "with_options", "(", "opts", ")", "{", "yield", "self", "}", "@context", "=", "@document", "blank", "(", ")", "ensure", "@in_section", "=", "false", "end", "end", "end" ]
Creates a new section with the given name and adds it to the document. You can optionally supply a block (as detailed in the documentation for Generator#gen) in order to add options to the section. ==== Parameters name<String>:: A name for the given section.
[ "Creates", "a", "new", "section", "with", "the", "given", "name", "and", "adds", "it", "to", "the", "document", "." ]
72715aa116aa303b05f5415362fb2611e597cb48
https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/generator.rb#L107-L131
23,103
antw/iniparse
lib/iniparse/generator.rb
IniParse.Generator.option
def option(key, value, opts = {}) @context.lines << Lines::Option.new( key, value, line_options(opts) ) rescue LineNotAllowed # Tried to add an Option to a Document. raise NoSectionError, 'Your INI document contains an option before the first section is ' \ 'declared which is not allowed.' end
ruby
def option(key, value, opts = {}) @context.lines << Lines::Option.new( key, value, line_options(opts) ) rescue LineNotAllowed # Tried to add an Option to a Document. raise NoSectionError, 'Your INI document contains an option before the first section is ' \ 'declared which is not allowed.' end
[ "def", "option", "(", "key", ",", "value", ",", "opts", "=", "{", "}", ")", "@context", ".", "lines", "<<", "Lines", "::", "Option", ".", "new", "(", "key", ",", "value", ",", "line_options", "(", "opts", ")", ")", "rescue", "LineNotAllowed", "# Tried to add an Option to a Document.", "raise", "NoSectionError", ",", "'Your INI document contains an option before the first section is '", "'declared which is not allowed.'", "end" ]
Adds a new option to the current section. Can only be called as part of a section block, or after at least one section has been added to the document. ==== Parameters key<String>:: The key (name) for this option. value:: The option's value. opts<Hash>:: Extra options for the line (formatting, etc). ==== Raises IniParse::NoSectionError:: If no section has been added to the document yet.
[ "Adds", "a", "new", "option", "to", "the", "current", "section", "." ]
72715aa116aa303b05f5415362fb2611e597cb48
https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/generator.rb#L147-L156
23,104
antw/iniparse
lib/iniparse/generator.rb
IniParse.Generator.comment
def comment(comment, opts = {}) @context.lines << Lines::Comment.new( line_options(opts.merge(:comment => comment)) ) end
ruby
def comment(comment, opts = {}) @context.lines << Lines::Comment.new( line_options(opts.merge(:comment => comment)) ) end
[ "def", "comment", "(", "comment", ",", "opts", "=", "{", "}", ")", "@context", ".", "lines", "<<", "Lines", "::", "Comment", ".", "new", "(", "line_options", "(", "opts", ".", "merge", "(", ":comment", "=>", "comment", ")", ")", ")", "end" ]
Adds a new comment line to the document. ==== Parameters comment<String>:: The text for the comment line.
[ "Adds", "a", "new", "comment", "line", "to", "the", "document", "." ]
72715aa116aa303b05f5415362fb2611e597cb48
https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/generator.rb#L163-L167
23,105
antw/iniparse
lib/iniparse/generator.rb
IniParse.Generator.with_options
def with_options(opts = {}) # :nodoc: opts = opts.dup opts.delete(:comment) @opt_stack.push( @opt_stack.last.merge(opts)) yield self @opt_stack.pop end
ruby
def with_options(opts = {}) # :nodoc: opts = opts.dup opts.delete(:comment) @opt_stack.push( @opt_stack.last.merge(opts)) yield self @opt_stack.pop end
[ "def", "with_options", "(", "opts", "=", "{", "}", ")", "# :nodoc:", "opts", "=", "opts", ".", "dup", "opts", ".", "delete", "(", ":comment", ")", "@opt_stack", ".", "push", "(", "@opt_stack", ".", "last", ".", "merge", "(", "opts", ")", ")", "yield", "self", "@opt_stack", ".", "pop", "end" ]
Wraps lines, setting default options for each.
[ "Wraps", "lines", "setting", "default", "options", "for", "each", "." ]
72715aa116aa303b05f5415362fb2611e597cb48
https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/generator.rb#L175-L181
23,106
Fullscreen/yt-core
lib/yt/response.rb
Yt.Response.videos_for
def videos_for(items, key, options) items.body['items'].map{|item| item['id'] = item[key]['videoId']} if options[:parts] == %i(id) items else options[:ids] = items.body['items'].map{|item| item['id']} options[:offset] = nil get('/youtube/v3/videos', resource_params(options)).tap do |response| response.body['nextPageToken'] = items.body['nextPageToken'] end end end
ruby
def videos_for(items, key, options) items.body['items'].map{|item| item['id'] = item[key]['videoId']} if options[:parts] == %i(id) items else options[:ids] = items.body['items'].map{|item| item['id']} options[:offset] = nil get('/youtube/v3/videos', resource_params(options)).tap do |response| response.body['nextPageToken'] = items.body['nextPageToken'] end end end
[ "def", "videos_for", "(", "items", ",", "key", ",", "options", ")", "items", ".", "body", "[", "'items'", "]", ".", "map", "{", "|", "item", "|", "item", "[", "'id'", "]", "=", "item", "[", "key", "]", "[", "'videoId'", "]", "}", "if", "options", "[", ":parts", "]", "==", "%i(", "id", ")", "items", "else", "options", "[", ":ids", "]", "=", "items", ".", "body", "[", "'items'", "]", ".", "map", "{", "|", "item", "|", "item", "[", "'id'", "]", "}", "options", "[", ":offset", "]", "=", "nil", "get", "(", "'/youtube/v3/videos'", ",", "resource_params", "(", "options", ")", ")", ".", "tap", "do", "|", "response", "|", "response", ".", "body", "[", "'nextPageToken'", "]", "=", "items", ".", "body", "[", "'nextPageToken'", "]", "end", "end", "end" ]
Expands the resultset into a collection of videos by fetching missing parts, eventually with an additional HTTP request.
[ "Expands", "the", "resultset", "into", "a", "collection", "of", "videos", "by", "fetching", "missing", "parts", "eventually", "with", "an", "additional", "HTTP", "request", "." ]
65b7fd61285c90beb72df241648eeff5b81ae321
https://github.com/Fullscreen/yt-core/blob/65b7fd61285c90beb72df241648eeff5b81ae321/lib/yt/response.rb#L124-L136
23,107
kangguru/rack-google-analytics
lib/google-analytics/instance_methods.rb
GoogleAnalytics.InstanceMethods.ga_track_event
def ga_track_event(category, action, label = nil, value = nil) ga_events.push(GoogleAnalytics::Event.new(category, action, label, value)) end
ruby
def ga_track_event(category, action, label = nil, value = nil) ga_events.push(GoogleAnalytics::Event.new(category, action, label, value)) end
[ "def", "ga_track_event", "(", "category", ",", "action", ",", "label", "=", "nil", ",", "value", "=", "nil", ")", "ga_events", ".", "push", "(", "GoogleAnalytics", "::", "Event", ".", "new", "(", "category", ",", "action", ",", "label", ",", "value", ")", ")", "end" ]
Tracks an event or goal on a page load e.g. writes ga.('send', 'event', 'Videos', 'Play', 'Gone With the Wind');
[ "Tracks", "an", "event", "or", "goal", "on", "a", "page", "load" ]
ac21206f1844abf00bedea7f0caa1b485873b238
https://github.com/kangguru/rack-google-analytics/blob/ac21206f1844abf00bedea7f0caa1b485873b238/lib/google-analytics/instance_methods.rb#L27-L29
23,108
antw/iniparse
lib/iniparse/document.rb
IniParse.Document.to_ini
def to_ini string = @lines.to_a.map { |line| line.to_ini }.join($/) string = "#{ string }\n" unless string[-1] == "\n" string end
ruby
def to_ini string = @lines.to_a.map { |line| line.to_ini }.join($/) string = "#{ string }\n" unless string[-1] == "\n" string end
[ "def", "to_ini", "string", "=", "@lines", ".", "to_a", ".", "map", "{", "|", "line", "|", "line", ".", "to_ini", "}", ".", "join", "(", "$/", ")", "string", "=", "\"#{ string }\\n\"", "unless", "string", "[", "-", "1", "]", "==", "\"\\n\"", "string", "end" ]
Returns this document as a string suitable for saving to a file.
[ "Returns", "this", "document", "as", "a", "string", "suitable", "for", "saving", "to", "a", "file", "." ]
72715aa116aa303b05f5415362fb2611e597cb48
https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/document.rb#L53-L58
23,109
antw/iniparse
lib/iniparse/document.rb
IniParse.Document.to_hash
def to_hash result = {} @lines.entries.each do |section| result[section.key] ||= {} section.entries.each do |option| opts = Array(option) val = opts.map { |o| o.respond_to?(:value) ? o.value : o } val = val.size > 1 ? val : val.first result[section.key][opts.first.key] = val end end result end
ruby
def to_hash result = {} @lines.entries.each do |section| result[section.key] ||= {} section.entries.each do |option| opts = Array(option) val = opts.map { |o| o.respond_to?(:value) ? o.value : o } val = val.size > 1 ? val : val.first result[section.key][opts.first.key] = val end end result end
[ "def", "to_hash", "result", "=", "{", "}", "@lines", ".", "entries", ".", "each", "do", "|", "section", "|", "result", "[", "section", ".", "key", "]", "||=", "{", "}", "section", ".", "entries", ".", "each", "do", "|", "option", "|", "opts", "=", "Array", "(", "option", ")", "val", "=", "opts", ".", "map", "{", "|", "o", "|", "o", ".", "respond_to?", "(", ":value", ")", "?", "o", ".", "value", ":", "o", "}", "val", "=", "val", ".", "size", ">", "1", "?", "val", ":", "val", ".", "first", "result", "[", "section", ".", "key", "]", "[", "opts", ".", "first", ".", "key", "]", "=", "val", "end", "end", "result", "end" ]
Returns a has representation of the INI with multi-line options as an array
[ "Returns", "a", "has", "representation", "of", "the", "INI", "with", "multi", "-", "line", "options", "as", "an", "array" ]
72715aa116aa303b05f5415362fb2611e597cb48
https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/document.rb#L64-L76
23,110
antw/iniparse
lib/iniparse/document.rb
IniParse.Document.save
def save(path = nil) @path = path if path raise IniParseError, 'No path given to Document#save' if @path !~ /\S/ File.open(@path, 'w') { |f| f.write(self.to_ini) } end
ruby
def save(path = nil) @path = path if path raise IniParseError, 'No path given to Document#save' if @path !~ /\S/ File.open(@path, 'w') { |f| f.write(self.to_ini) } end
[ "def", "save", "(", "path", "=", "nil", ")", "@path", "=", "path", "if", "path", "raise", "IniParseError", ",", "'No path given to Document#save'", "if", "@path", "!~", "/", "\\S", "/", "File", ".", "open", "(", "@path", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "(", "self", ".", "to_ini", ")", "}", "end" ]
Saves a copy of this Document to disk. If a path was supplied when the Document was initialized then nothing needs to be given to Document#save. If Document was not given a file path, or you wish to save the document elsewhere, supply a path when calling Document#save. ==== Parameters path<String>:: A path to which this document will be saved. ==== Raises IniParseError:: If your document couldn't be saved.
[ "Saves", "a", "copy", "of", "this", "Document", "to", "disk", "." ]
72715aa116aa303b05f5415362fb2611e597cb48
https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/document.rb#L104-L108
23,111
kameeoze/jruby-poi
lib/poi/workbook/workbook.rb
POI.Workbook.[]
def [](reference) if Fixnum === reference return worksheets[reference] end if sheet = worksheets.detect{|e| e.name == reference} return sheet.poi_worksheet.nil? ? nil : sheet end cell = cell(reference) if Array === cell cell.collect{|e| e.value} elsif Hash === cell values = {} cell.each_pair{|column_name, cells| values[column_name] = cells.collect{|e| e.value}} values else cell.value end end
ruby
def [](reference) if Fixnum === reference return worksheets[reference] end if sheet = worksheets.detect{|e| e.name == reference} return sheet.poi_worksheet.nil? ? nil : sheet end cell = cell(reference) if Array === cell cell.collect{|e| e.value} elsif Hash === cell values = {} cell.each_pair{|column_name, cells| values[column_name] = cells.collect{|e| e.value}} values else cell.value end end
[ "def", "[]", "(", "reference", ")", "if", "Fixnum", "===", "reference", "return", "worksheets", "[", "reference", "]", "end", "if", "sheet", "=", "worksheets", ".", "detect", "{", "|", "e", "|", "e", ".", "name", "==", "reference", "}", "return", "sheet", ".", "poi_worksheet", ".", "nil?", "?", "nil", ":", "sheet", "end", "cell", "=", "cell", "(", "reference", ")", "if", "Array", "===", "cell", "cell", ".", "collect", "{", "|", "e", "|", "e", ".", "value", "}", "elsif", "Hash", "===", "cell", "values", "=", "{", "}", "cell", ".", "each_pair", "{", "|", "column_name", ",", "cells", "|", "values", "[", "column_name", "]", "=", "cells", ".", "collect", "{", "|", "e", "|", "e", ".", "value", "}", "}", "values", "else", "cell", ".", "value", "end", "end" ]
reference can be a Fixnum, referring to the 0-based sheet or a String which is the sheet name or a cell reference. If a cell reference is passed the value of that cell is returned. If the reference refers to a contiguous range of cells an Array of values will be returned. If the reference refers to a multiple columns a Hash of values will be returned by column name.
[ "reference", "can", "be", "a", "Fixnum", "referring", "to", "the", "0", "-", "based", "sheet", "or", "a", "String", "which", "is", "the", "sheet", "name", "or", "a", "cell", "reference", "." ]
c10b7e7ccfd19f132d153834ea0372a67a1d4981
https://github.com/kameeoze/jruby-poi/blob/c10b7e7ccfd19f132d153834ea0372a67a1d4981/lib/poi/workbook/workbook.rb#L147-L166
23,112
antw/iniparse
lib/iniparse/parser.rb
IniParse.Parser.parse
def parse IniParse::Generator.gen do |generator| @source.split("\n", -1).each do |line| generator.send(*Parser.parse_line(line)) end end end
ruby
def parse IniParse::Generator.gen do |generator| @source.split("\n", -1).each do |line| generator.send(*Parser.parse_line(line)) end end end
[ "def", "parse", "IniParse", "::", "Generator", ".", "gen", "do", "|", "generator", "|", "@source", ".", "split", "(", "\"\\n\"", ",", "-", "1", ")", ".", "each", "do", "|", "line", "|", "generator", ".", "send", "(", "Parser", ".", "parse_line", "(", "line", ")", ")", "end", "end", "end" ]
Creates a new Parser instance for parsing string +source+. ==== Parameters source<String>:: The source string. Parses the source string and returns the resulting data structure. ==== Returns IniParse::Document
[ "Creates", "a", "new", "Parser", "instance", "for", "parsing", "string", "+", "source", "+", "." ]
72715aa116aa303b05f5415362fb2611e597cb48
https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/parser.rb#L40-L46
23,113
antw/iniparse
lib/iniparse/line_collection.rb
IniParse.LineCollection.[]=
def []=(key, value) key = key.to_s if has_key?(key) @lines[ @indicies[key] ] = value else @lines << value @indicies[key] = @lines.length - 1 end end
ruby
def []=(key, value) key = key.to_s if has_key?(key) @lines[ @indicies[key] ] = value else @lines << value @indicies[key] = @lines.length - 1 end end
[ "def", "[]=", "(", "key", ",", "value", ")", "key", "=", "key", ".", "to_s", "if", "has_key?", "(", "key", ")", "@lines", "[", "@indicies", "[", "key", "]", "]", "=", "value", "else", "@lines", "<<", "value", "@indicies", "[", "key", "]", "=", "@lines", ".", "length", "-", "1", "end", "end" ]
Set a +value+ identified by +key+. If a value with the given key already exists, the value will be replaced with the new one, with the new value taking the position of the old.
[ "Set", "a", "+", "value", "+", "identified", "by", "+", "key", "+", "." ]
72715aa116aa303b05f5415362fb2611e597cb48
https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/line_collection.rb#L30-L39
23,114
antw/iniparse
lib/iniparse/line_collection.rb
IniParse.LineCollection.each
def each(include_blank = false) @lines.each do |line| if include_blank || ! (line.is_a?(Array) ? line.empty? : line.blank?) yield(line) end end end
ruby
def each(include_blank = false) @lines.each do |line| if include_blank || ! (line.is_a?(Array) ? line.empty? : line.blank?) yield(line) end end end
[ "def", "each", "(", "include_blank", "=", "false", ")", "@lines", ".", "each", "do", "|", "line", "|", "if", "include_blank", "||", "!", "(", "line", ".", "is_a?", "(", "Array", ")", "?", "line", ".", "empty?", ":", "line", ".", "blank?", ")", "yield", "(", "line", ")", "end", "end", "end" ]
Enumerates through the collection. By default #each does not yield blank and comment lines. ==== Parameters include_blank<Boolean>:: Include blank/comment lines?
[ "Enumerates", "through", "the", "collection", "." ]
72715aa116aa303b05f5415362fb2611e597cb48
https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/line_collection.rb#L59-L65
23,115
antw/iniparse
lib/iniparse/line_collection.rb
IniParse.LineCollection.delete
def delete(key) key = key.key if key.respond_to?(:key) unless (idx = @indicies[key]).nil? @indicies.delete(key) @indicies.each { |k,v| @indicies[k] = v -= 1 if v > idx } @lines.delete_at(idx) end end
ruby
def delete(key) key = key.key if key.respond_to?(:key) unless (idx = @indicies[key]).nil? @indicies.delete(key) @indicies.each { |k,v| @indicies[k] = v -= 1 if v > idx } @lines.delete_at(idx) end end
[ "def", "delete", "(", "key", ")", "key", "=", "key", ".", "key", "if", "key", ".", "respond_to?", "(", ":key", ")", "unless", "(", "idx", "=", "@indicies", "[", "key", "]", ")", ".", "nil?", "@indicies", ".", "delete", "(", "key", ")", "@indicies", ".", "each", "{", "|", "k", ",", "v", "|", "@indicies", "[", "k", "]", "=", "v", "-=", "1", "if", "v", ">", "idx", "}", "@lines", ".", "delete_at", "(", "idx", ")", "end", "end" ]
Removes the value identified by +key+.
[ "Removes", "the", "value", "identified", "by", "+", "key", "+", "." ]
72715aa116aa303b05f5415362fb2611e597cb48
https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/line_collection.rb#L68-L76
23,116
antw/iniparse
lib/iniparse/line_collection.rb
IniParse.OptionCollection.<<
def <<(line) if line.kind_of?(IniParse::Lines::Section) raise IniParse::LineNotAllowed, "You can't add a Section to an OptionCollection." end if line.blank? || (! has_key?(line.key)) super # Adding a new option, comment or blank line. else self[line.key] = [self[line.key], line].flatten end self end
ruby
def <<(line) if line.kind_of?(IniParse::Lines::Section) raise IniParse::LineNotAllowed, "You can't add a Section to an OptionCollection." end if line.blank? || (! has_key?(line.key)) super # Adding a new option, comment or blank line. else self[line.key] = [self[line.key], line].flatten end self end
[ "def", "<<", "(", "line", ")", "if", "line", ".", "kind_of?", "(", "IniParse", "::", "Lines", "::", "Section", ")", "raise", "IniParse", "::", "LineNotAllowed", ",", "\"You can't add a Section to an OptionCollection.\"", "end", "if", "line", ".", "blank?", "||", "(", "!", "has_key?", "(", "line", ".", "key", ")", ")", "super", "# Adding a new option, comment or blank line.", "else", "self", "[", "line", ".", "key", "]", "=", "[", "self", "[", "line", ".", "key", "]", ",", "line", "]", ".", "flatten", "end", "self", "end" ]
Appends a line to the collection. If you push an Option with a key already represented in the collection, the previous Option will not be overwritten, but treated as a duplicate. ==== Parameters line<IniParse::LineType::Line>:: The line to be added to this section.
[ "Appends", "a", "line", "to", "the", "collection", "." ]
72715aa116aa303b05f5415362fb2611e597cb48
https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/line_collection.rb#L149-L162
23,117
antw/iniparse
lib/iniparse/line_collection.rb
IniParse.OptionCollection.keys
def keys map { |line| line.kind_of?(Array) ? line.first.key : line.key } end
ruby
def keys map { |line| line.kind_of?(Array) ? line.first.key : line.key } end
[ "def", "keys", "map", "{", "|", "line", "|", "line", ".", "kind_of?", "(", "Array", ")", "?", "line", ".", "first", ".", "key", ":", "line", ".", "key", "}", "end" ]
Return an array containing the keys for the lines added to this collection.
[ "Return", "an", "array", "containing", "the", "keys", "for", "the", "lines", "added", "to", "this", "collection", "." ]
72715aa116aa303b05f5415362fb2611e597cb48
https://github.com/antw/iniparse/blob/72715aa116aa303b05f5415362fb2611e597cb48/lib/iniparse/line_collection.rb#L166-L168
23,118
beatrichartz/exchange
lib/exchange/helper.rb
Exchange.Helper.assure_time
def assure_time arg=nil, opts={} if arg arg.kind_of?(Time) ? arg : Time.gm(*arg.split('-')) elsif opts[:default] Time.send(opts[:default]) end end
ruby
def assure_time arg=nil, opts={} if arg arg.kind_of?(Time) ? arg : Time.gm(*arg.split('-')) elsif opts[:default] Time.send(opts[:default]) end end
[ "def", "assure_time", "arg", "=", "nil", ",", "opts", "=", "{", "}", "if", "arg", "arg", ".", "kind_of?", "(", "Time", ")", "?", "arg", ":", "Time", ".", "gm", "(", "arg", ".", "split", "(", "'-'", ")", ")", "elsif", "opts", "[", ":default", "]", "Time", ".", "send", "(", "opts", "[", ":default", "]", ")", "end", "end" ]
A helper function to assure a value is an instance of time @param [Time, String, NilClass] arg The value to be asserted @param [Hash] opts Options for assertion @option opts [Symbol] :default a method that can be sent to Time if the argument is nil (:now for example)
[ "A", "helper", "function", "to", "assure", "a", "value", "is", "an", "instance", "of", "time" ]
4318b9dad3cce5e933827126160fafe30c68dc2a
https://github.com/beatrichartz/exchange/blob/4318b9dad3cce5e933827126160fafe30c68dc2a/lib/exchange/helper.rb#L21-L27
23,119
BadrIT/translation_center
app/controllers/translation_center/center_controller.rb
TranslationCenter.CenterController.set_language_from
def set_language_from session[:lang_from] = params[:lang].to_sym I18n.locale = session[:lang_from] render nothing: true end
ruby
def set_language_from session[:lang_from] = params[:lang].to_sym I18n.locale = session[:lang_from] render nothing: true end
[ "def", "set_language_from", "session", "[", ":lang_from", "]", "=", "params", "[", ":lang", "]", ".", "to_sym", "I18n", ".", "locale", "=", "session", "[", ":lang_from", "]", "render", "nothing", ":", "true", "end" ]
set language user translating from
[ "set", "language", "user", "translating", "from" ]
439cbf70323e629a630fe939d02b44361afae13e
https://github.com/BadrIT/translation_center/blob/439cbf70323e629a630fe939d02b44361afae13e/app/controllers/translation_center/center_controller.rb#L10-L14
23,120
BadrIT/translation_center
app/controllers/translation_center/center_controller.rb
TranslationCenter.CenterController.set_language_to
def set_language_to session[:lang_to] = params[:lang].to_sym respond_to do |format| format.html { redirect_to root_url } format.js { render nothing: true } end end
ruby
def set_language_to session[:lang_to] = params[:lang].to_sym respond_to do |format| format.html { redirect_to root_url } format.js { render nothing: true } end end
[ "def", "set_language_to", "session", "[", ":lang_to", "]", "=", "params", "[", ":lang", "]", ".", "to_sym", "respond_to", "do", "|", "format", "|", "format", ".", "html", "{", "redirect_to", "root_url", "}", "format", ".", "js", "{", "render", "nothing", ":", "true", "}", "end", "end" ]
set language user translating to
[ "set", "language", "user", "translating", "to" ]
439cbf70323e629a630fe939d02b44361afae13e
https://github.com/BadrIT/translation_center/blob/439cbf70323e629a630fe939d02b44361afae13e/app/controllers/translation_center/center_controller.rb#L17-L24
23,121
BadrIT/translation_center
app/models/translation_center/activity_query.rb
TranslationCenter.ActivityQuery.translation_ids
def translation_ids query = Translation.all query = query.where(lang: lang) unless lang.blank? query = query.joins(:translation_key).where("translation_center_translation_keys.name LIKE ?", "%#{translation_key_name}%") unless translation_key_name.blank? if translator_identifier translator_class = TranslationCenter::CONFIG['translator_type'].camelize.constantize translators_ids = translator_class.where("#{TranslationCenter::CONFIG['identifier_type']} LIKE ? ", "%#{translator_identifier}%").map(&:id) query = query.where(translator_id: translators_ids) end query.map(&:id) end
ruby
def translation_ids query = Translation.all query = query.where(lang: lang) unless lang.blank? query = query.joins(:translation_key).where("translation_center_translation_keys.name LIKE ?", "%#{translation_key_name}%") unless translation_key_name.blank? if translator_identifier translator_class = TranslationCenter::CONFIG['translator_type'].camelize.constantize translators_ids = translator_class.where("#{TranslationCenter::CONFIG['identifier_type']} LIKE ? ", "%#{translator_identifier}%").map(&:id) query = query.where(translator_id: translators_ids) end query.map(&:id) end
[ "def", "translation_ids", "query", "=", "Translation", ".", "all", "query", "=", "query", ".", "where", "(", "lang", ":", "lang", ")", "unless", "lang", ".", "blank?", "query", "=", "query", ".", "joins", "(", ":translation_key", ")", ".", "where", "(", "\"translation_center_translation_keys.name LIKE ?\"", ",", "\"%#{translation_key_name}%\"", ")", "unless", "translation_key_name", ".", "blank?", "if", "translator_identifier", "translator_class", "=", "TranslationCenter", "::", "CONFIG", "[", "'translator_type'", "]", ".", "camelize", ".", "constantize", "translators_ids", "=", "translator_class", ".", "where", "(", "\"#{TranslationCenter::CONFIG['identifier_type']} LIKE ? \"", ",", "\"%#{translator_identifier}%\"", ")", ".", "map", "(", ":id", ")", "query", "=", "query", ".", "where", "(", "translator_id", ":", "translators_ids", ")", "end", "query", ".", "map", "(", ":id", ")", "end" ]
return translation ids that matches this search criteria
[ "return", "translation", "ids", "that", "matches", "this", "search", "criteria" ]
439cbf70323e629a630fe939d02b44361afae13e
https://github.com/BadrIT/translation_center/blob/439cbf70323e629a630fe939d02b44361afae13e/app/models/translation_center/activity_query.rb#L30-L43
23,122
BadrIT/translation_center
app/models/translation_center/translation_key.rb
TranslationCenter.TranslationKey.add_category
def add_category category_name = self.name.to_s.split('.').first # if one word then add to general category category_name = self.name.to_s.split('.').size == 1 ? 'general' : self.name.to_s.split('.').first self.category = TranslationCenter::Category.where(name: category_name).first_or_create self.last_accessed = Time.now end
ruby
def add_category category_name = self.name.to_s.split('.').first # if one word then add to general category category_name = self.name.to_s.split('.').size == 1 ? 'general' : self.name.to_s.split('.').first self.category = TranslationCenter::Category.where(name: category_name).first_or_create self.last_accessed = Time.now end
[ "def", "add_category", "category_name", "=", "self", ".", "name", ".", "to_s", ".", "split", "(", "'.'", ")", ".", "first", "# if one word then add to general category", "category_name", "=", "self", ".", "name", ".", "to_s", ".", "split", "(", "'.'", ")", ".", "size", "==", "1", "?", "'general'", ":", "self", ".", "name", ".", "to_s", ".", "split", "(", "'.'", ")", ".", "first", "self", ".", "category", "=", "TranslationCenter", "::", "Category", ".", "where", "(", "name", ":", "category_name", ")", ".", "first_or_create", "self", ".", "last_accessed", "=", "Time", ".", "now", "end" ]
add a category of this translation key
[ "add", "a", "category", "of", "this", "translation", "key" ]
439cbf70323e629a630fe939d02b44361afae13e
https://github.com/BadrIT/translation_center/blob/439cbf70323e629a630fe939d02b44361afae13e/app/models/translation_center/translation_key.rb#L28-L34
23,123
BadrIT/translation_center
app/models/translation_center/translation_key.rb
TranslationCenter.TranslationKey.update_status
def update_status(lang) if self.translations.in(lang).blank? self.update_attribute("#{lang}_status", UNTRANSLATED) elsif !self.translations.in(lang).accepted.blank? self.update_attribute("#{lang}_status", TRANSLATED) else self.update_attribute("#{lang}_status", PENDING) end end
ruby
def update_status(lang) if self.translations.in(lang).blank? self.update_attribute("#{lang}_status", UNTRANSLATED) elsif !self.translations.in(lang).accepted.blank? self.update_attribute("#{lang}_status", TRANSLATED) else self.update_attribute("#{lang}_status", PENDING) end end
[ "def", "update_status", "(", "lang", ")", "if", "self", ".", "translations", ".", "in", "(", "lang", ")", ".", "blank?", "self", ".", "update_attribute", "(", "\"#{lang}_status\"", ",", "UNTRANSLATED", ")", "elsif", "!", "self", ".", "translations", ".", "in", "(", "lang", ")", ".", "accepted", ".", "blank?", "self", ".", "update_attribute", "(", "\"#{lang}_status\"", ",", "TRANSLATED", ")", "else", "self", ".", "update_attribute", "(", "\"#{lang}_status\"", ",", "PENDING", ")", "end", "end" ]
updates the status of the translation key depending on the translations
[ "updates", "the", "status", "of", "the", "translation", "key", "depending", "on", "the", "translations" ]
439cbf70323e629a630fe939d02b44361afae13e
https://github.com/BadrIT/translation_center/blob/439cbf70323e629a630fe939d02b44361afae13e/app/models/translation_center/translation_key.rb#L37-L45
23,124
BadrIT/translation_center
app/models/translation_center/translation_key.rb
TranslationCenter.TranslationKey.create_default_translation
def create_default_translation translation = self.translations.build(value: self.name.to_s.split('.').last.titleize, lang: :en, status: 'accepted') translation.translator = TranslationCenter.prepare_translator translation.save end
ruby
def create_default_translation translation = self.translations.build(value: self.name.to_s.split('.').last.titleize, lang: :en, status: 'accepted') translation.translator = TranslationCenter.prepare_translator translation.save end
[ "def", "create_default_translation", "translation", "=", "self", ".", "translations", ".", "build", "(", "value", ":", "self", ".", "name", ".", "to_s", ".", "split", "(", "'.'", ")", ".", "last", ".", "titleize", ",", "lang", ":", ":en", ",", "status", ":", "'accepted'", ")", "translation", ".", "translator", "=", "TranslationCenter", ".", "prepare_translator", "translation", ".", "save", "end" ]
create default translation
[ "create", "default", "translation" ]
439cbf70323e629a630fe939d02b44361afae13e
https://github.com/BadrIT/translation_center/blob/439cbf70323e629a630fe939d02b44361afae13e/app/models/translation_center/translation_key.rb#L86-L92
23,125
BadrIT/translation_center
app/models/translation_center/translation_key.rb
TranslationCenter.TranslationKey.add_to_hash
def add_to_hash(all_translations, lang) levels = self.name.split('.') add_to_hash_rec(all_translations, levels, lang.to_s) end
ruby
def add_to_hash(all_translations, lang) levels = self.name.split('.') add_to_hash_rec(all_translations, levels, lang.to_s) end
[ "def", "add_to_hash", "(", "all_translations", ",", "lang", ")", "levels", "=", "self", ".", "name", ".", "split", "(", "'.'", ")", "add_to_hash_rec", "(", "all_translations", ",", "levels", ",", "lang", ".", "to_s", ")", "end" ]
adds a translation key with its translation to a translation yaml hash send the hash and the language as parameters
[ "adds", "a", "translation", "key", "with", "its", "translation", "to", "a", "translation", "yaml", "hash", "send", "the", "hash", "and", "the", "language", "as", "parameters" ]
439cbf70323e629a630fe939d02b44361afae13e
https://github.com/BadrIT/translation_center/blob/439cbf70323e629a630fe939d02b44361afae13e/app/models/translation_center/translation_key.rb#L164-L167
23,126
beatrichartz/exchange
lib/exchange/typecasting.rb
Exchange.Typecasting.money
def money *attributes options = attributes.last.is_a?(Hash) ? attributes.pop : {} attributes.each do |attribute| # Get the attribute typecasted into money # @return [Exchange::Money] an instance of money # install_money_getter attribute, options # Set the attribute either with money or just any data # Implicitly converts values given that are not in the same currency as the currency option evaluates to # @param [Exchange::Money, String, Numberic] data The data to set the attribute to # install_money_setter attribute, options end # Evaluates options given either as symbols or as procs # @param [Symbol, Proc] option The option to evaluate # install_money_option_eval # Evaluates whether an error should be raised because there is no currency present # @param [Symbol] currency The currency, if given # install_currency_error_tester end
ruby
def money *attributes options = attributes.last.is_a?(Hash) ? attributes.pop : {} attributes.each do |attribute| # Get the attribute typecasted into money # @return [Exchange::Money] an instance of money # install_money_getter attribute, options # Set the attribute either with money or just any data # Implicitly converts values given that are not in the same currency as the currency option evaluates to # @param [Exchange::Money, String, Numberic] data The data to set the attribute to # install_money_setter attribute, options end # Evaluates options given either as symbols or as procs # @param [Symbol, Proc] option The option to evaluate # install_money_option_eval # Evaluates whether an error should be raised because there is no currency present # @param [Symbol] currency The currency, if given # install_currency_error_tester end
[ "def", "money", "*", "attributes", "options", "=", "attributes", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "attributes", ".", "pop", ":", "{", "}", "attributes", ".", "each", "do", "|", "attribute", "|", "# Get the attribute typecasted into money ", "# @return [Exchange::Money] an instance of money", "#", "install_money_getter", "attribute", ",", "options", "# Set the attribute either with money or just any data", "# Implicitly converts values given that are not in the same currency as the currency option evaluates to", "# @param [Exchange::Money, String, Numberic] data The data to set the attribute to", "# ", "install_money_setter", "attribute", ",", "options", "end", "# Evaluates options given either as symbols or as procs", "# @param [Symbol, Proc] option The option to evaluate", "#", "install_money_option_eval", "# Evaluates whether an error should be raised because there is no currency present", "# @param [Symbol] currency The currency, if given", "#", "install_currency_error_tester", "end" ]
installs a setter and a getter for the attribute you want to typecast as exchange money @overload def money(*attributes, options={}) @param [Symbol] attributes The attributes you want to typecast as money. @param [Hash] options Pass a hash as last argument as options @option options [Symbol, Proc] :currency The currency to evaluate the money with. Can be a symbol or a proc @option options [Symbol, Proc] :at The time at which the currency should be casted. All conversions of this currency will take place at this time @raise [NoCurrencyError] if no currency option is given or the currency evals to nil @example configure money with symbols, the currency option here will call the method currency in the object context money :price, :currency => :currency, :time => :created_at @example configure money with a proc, the proc will be called with the object as an argument. This is equivalent to the example above money :price, :currency => lambda {|o| o.currency}, :time => lambda{|o| o.created_at}
[ "installs", "a", "setter", "and", "a", "getter", "for", "the", "attribute", "you", "want", "to", "typecast", "as", "exchange", "money" ]
4318b9dad3cce5e933827126160fafe30c68dc2a
https://github.com/beatrichartz/exchange/blob/4318b9dad3cce5e933827126160fafe30c68dc2a/lib/exchange/typecasting.rb#L135-L163
23,127
akarzim/capybara-bootstrap-datepicker
lib/capybara-bootstrap-datepicker.rb
Capybara.BootstrapDatepicker.select_date
def select_date(value, datepicker: :bootstrap, format: nil, from: nil, xpath: nil, **args) fail "Must pass a hash containing 'from' or 'xpath'" if from.nil? && xpath.nil? value = value.respond_to?(:to_date) ? value.to_date : Date.parse(value) date_input = xpath ? find(:xpath, xpath, **args) : find_field(from, **args) case datepicker when :bootstrap select_bootstrap_date date_input, value else select_simple_date date_input, value, format end first(:xpath, '//body').click end
ruby
def select_date(value, datepicker: :bootstrap, format: nil, from: nil, xpath: nil, **args) fail "Must pass a hash containing 'from' or 'xpath'" if from.nil? && xpath.nil? value = value.respond_to?(:to_date) ? value.to_date : Date.parse(value) date_input = xpath ? find(:xpath, xpath, **args) : find_field(from, **args) case datepicker when :bootstrap select_bootstrap_date date_input, value else select_simple_date date_input, value, format end first(:xpath, '//body').click end
[ "def", "select_date", "(", "value", ",", "datepicker", ":", ":bootstrap", ",", "format", ":", "nil", ",", "from", ":", "nil", ",", "xpath", ":", "nil", ",", "**", "args", ")", "fail", "\"Must pass a hash containing 'from' or 'xpath'\"", "if", "from", ".", "nil?", "&&", "xpath", ".", "nil?", "value", "=", "value", ".", "respond_to?", "(", ":to_date", ")", "?", "value", ".", "to_date", ":", "Date", ".", "parse", "(", "value", ")", "date_input", "=", "xpath", "?", "find", "(", ":xpath", ",", "xpath", ",", "**", "args", ")", ":", "find_field", "(", "from", ",", "**", "args", ")", "case", "datepicker", "when", ":bootstrap", "select_bootstrap_date", "date_input", ",", "value", "else", "select_simple_date", "date_input", ",", "value", ",", "format", "end", "first", "(", ":xpath", ",", "'//body'", ")", ".", "click", "end" ]
Selects a date by simulating human interaction with the datepicker or filling the input field @param value [#to_date, String] any object that responds to `#to_date` or a parsable date string @param datepicker [:bootstrap, :simple] the datepicker to use (are supported: bootstrap or input field) @param format [String, nil] a valid date format used to format value @param from [String, nil] the path to input field (required if `xpath` is nil) @param xpath [String, nil] the xpath to input field (required if `from` is nil) @param args [Hash] extra args to find the input field
[ "Selects", "a", "date", "by", "simulating", "human", "interaction", "with", "the", "datepicker", "or", "filling", "the", "input", "field" ]
fb2349436a8ca31337936e8b8f9a89998f9e38b1
https://github.com/akarzim/capybara-bootstrap-datepicker/blob/fb2349436a8ca31337936e8b8f9a89998f9e38b1/lib/capybara-bootstrap-datepicker.rb#L13-L27
23,128
akarzim/capybara-bootstrap-datepicker
lib/capybara-bootstrap-datepicker.rb
Capybara.BootstrapDatepicker.select_simple_date
def select_simple_date(date_input, value, format = nil) value = value.strftime format unless format.nil? date_input.set "#{value}\e" end
ruby
def select_simple_date(date_input, value, format = nil) value = value.strftime format unless format.nil? date_input.set "#{value}\e" end
[ "def", "select_simple_date", "(", "date_input", ",", "value", ",", "format", "=", "nil", ")", "value", "=", "value", ".", "strftime", "format", "unless", "format", ".", "nil?", "date_input", ".", "set", "\"#{value}\\e\"", "end" ]
Selects a date by filling the input field @param date_input the input field @param value [Date] the date to set @param format [String, nil] a valid date format used to format value
[ "Selects", "a", "date", "by", "filling", "the", "input", "field" ]
fb2349436a8ca31337936e8b8f9a89998f9e38b1
https://github.com/akarzim/capybara-bootstrap-datepicker/blob/fb2349436a8ca31337936e8b8f9a89998f9e38b1/lib/capybara-bootstrap-datepicker.rb#L33-L37
23,129
akarzim/capybara-bootstrap-datepicker
lib/capybara-bootstrap-datepicker.rb
Capybara.BootstrapDatepicker.select_bootstrap_date
def select_bootstrap_date(date_input, value) date_input.click picker = Picker.new picker.goto_decade_panel picker.navigate_through_decades value.year picker.find_year(value.year).click picker.find_month(value.month).click picker.find_day(value.day).click fail if Date.parse(date_input.value) != value end
ruby
def select_bootstrap_date(date_input, value) date_input.click picker = Picker.new picker.goto_decade_panel picker.navigate_through_decades value.year picker.find_year(value.year).click picker.find_month(value.month).click picker.find_day(value.day).click fail if Date.parse(date_input.value) != value end
[ "def", "select_bootstrap_date", "(", "date_input", ",", "value", ")", "date_input", ".", "click", "picker", "=", "Picker", ".", "new", "picker", ".", "goto_decade_panel", "picker", ".", "navigate_through_decades", "value", ".", "year", "picker", ".", "find_year", "(", "value", ".", "year", ")", ".", "click", "picker", ".", "find_month", "(", "value", ".", "month", ")", ".", "click", "picker", ".", "find_day", "(", "value", ".", "day", ")", ".", "click", "fail", "if", "Date", ".", "parse", "(", "date_input", ".", "value", ")", "!=", "value", "end" ]
Selects a date by simulating human interaction with the datepicker @param (see #select_simple_date)
[ "Selects", "a", "date", "by", "simulating", "human", "interaction", "with", "the", "datepicker" ]
fb2349436a8ca31337936e8b8f9a89998f9e38b1
https://github.com/akarzim/capybara-bootstrap-datepicker/blob/fb2349436a8ca31337936e8b8f9a89998f9e38b1/lib/capybara-bootstrap-datepicker.rb#L41-L54
23,130
beatrichartz/exchange
lib/exchange/configurable.rb
Exchange.Configurable.subclass_with_constantize
def subclass_with_constantize self.subclass = parent_module.const_get camelize(self.subclass_without_constantize) unless !self.subclass_without_constantize || self.subclass_without_constantize.is_a?(Class) subclass_without_constantize end
ruby
def subclass_with_constantize self.subclass = parent_module.const_get camelize(self.subclass_without_constantize) unless !self.subclass_without_constantize || self.subclass_without_constantize.is_a?(Class) subclass_without_constantize end
[ "def", "subclass_with_constantize", "self", ".", "subclass", "=", "parent_module", ".", "const_get", "camelize", "(", "self", ".", "subclass_without_constantize", ")", "unless", "!", "self", ".", "subclass_without_constantize", "||", "self", ".", "subclass_without_constantize", ".", "is_a?", "(", "Class", ")", "subclass_without_constantize", "end" ]
Alias method chain to instantiate the subclass from a symbol should it not be a class @return [NilClass, Class] The subclass or nil
[ "Alias", "method", "chain", "to", "instantiate", "the", "subclass", "from", "a", "symbol", "should", "it", "not", "be", "a", "class" ]
4318b9dad3cce5e933827126160fafe30c68dc2a
https://github.com/beatrichartz/exchange/blob/4318b9dad3cce5e933827126160fafe30c68dc2a/lib/exchange/configurable.rb#L18-L21
23,131
beatrichartz/exchange
lib/exchange/iso.rb
Exchange.ISO.assert_currency!
def assert_currency! arg defines?(arg) ? (country_map[arg] || arg) : raise(Exchange::NoCurrencyError.new("#{arg} is not a currency nor a country code matchable to a currency")) end
ruby
def assert_currency! arg defines?(arg) ? (country_map[arg] || arg) : raise(Exchange::NoCurrencyError.new("#{arg} is not a currency nor a country code matchable to a currency")) end
[ "def", "assert_currency!", "arg", "defines?", "(", "arg", ")", "?", "(", "country_map", "[", "arg", "]", "||", "arg", ")", ":", "raise", "(", "Exchange", "::", "NoCurrencyError", ".", "new", "(", "\"#{arg} is not a currency nor a country code matchable to a currency\"", ")", ")", "end" ]
Asserts a given argument is a currency. Tries to match with a country code if the argument is not a currency @param [Symbol, String] arg The argument to assert @return [Symbol] The matching currency as a symbol
[ "Asserts", "a", "given", "argument", "is", "a", "currency", ".", "Tries", "to", "match", "with", "a", "country", "code", "if", "the", "argument", "is", "not", "a", "currency" ]
4318b9dad3cce5e933827126160fafe30c68dc2a
https://github.com/beatrichartz/exchange/blob/4318b9dad3cce5e933827126160fafe30c68dc2a/lib/exchange/iso.rb#L77-L79
23,132
beatrichartz/exchange
lib/exchange/iso.rb
Exchange.ISO.instantiate
def instantiate amount, currency if amount.is_a?(BigDecimal) amount else BigDecimal.new(amount.to_s, precision_for(amount, currency)) end end
ruby
def instantiate amount, currency if amount.is_a?(BigDecimal) amount else BigDecimal.new(amount.to_s, precision_for(amount, currency)) end end
[ "def", "instantiate", "amount", ",", "currency", "if", "amount", ".", "is_a?", "(", "BigDecimal", ")", "amount", "else", "BigDecimal", ".", "new", "(", "amount", ".", "to_s", ",", "precision_for", "(", "amount", ",", "currency", ")", ")", "end", "end" ]
Use this to instantiate a currency amount. For one, it is important that we use BigDecimal here so nothing gets lost because of floating point errors. For the other, This allows us to set the precision exactly according to the iso definition @param [BigDecimal, Fixed, Float, String] amount The amount of money you want to instantiate @param [String, Symbol] currency The currency you want to instantiate the money in @return [BigDecimal] The instantiated currency @example instantiate a currency from a string Exchange::ISO.instantiate("4523", "usd") #=> #<Bigdecimal 4523.00> @note Reinstantiation is not needed in case the amount is already a big decimal. In this case, the maximum precision is already given.
[ "Use", "this", "to", "instantiate", "a", "currency", "amount", ".", "For", "one", "it", "is", "important", "that", "we", "use", "BigDecimal", "here", "so", "nothing", "gets", "lost", "because", "of", "floating", "point", "errors", ".", "For", "the", "other", "This", "allows", "us", "to", "set", "the", "precision", "exactly", "according", "to", "the", "iso", "definition" ]
4318b9dad3cce5e933827126160fafe30c68dc2a
https://github.com/beatrichartz/exchange/blob/4318b9dad3cce5e933827126160fafe30c68dc2a/lib/exchange/iso.rb#L90-L96
23,133
beatrichartz/exchange
lib/exchange/iso.rb
Exchange.ISO.stringify
def stringify amount, currency, opts={} definition = definitions[currency] separators = definition[:separators] || {} format = "%.#{definition[:minor_unit]}f" string = format % amount major, minor = string.split('.') major.gsub!(/(\d)(?=(\d\d\d)+(?!\d))/) { $1 + separators[:major] } if separators[:major] && opts[:format] != :plain string = minor ? major + (opts[:format] == :plain || !separators[:minor] ? '.' : separators[:minor]) + minor : major pre = [[:amount, :plain].include?(opts[:format]) && '', opts[:format] == :symbol && definition[:symbol], currency.to_s.upcase + ' '].detect{|a| a.is_a?(String)} "#{pre}#{string}" end
ruby
def stringify amount, currency, opts={} definition = definitions[currency] separators = definition[:separators] || {} format = "%.#{definition[:minor_unit]}f" string = format % amount major, minor = string.split('.') major.gsub!(/(\d)(?=(\d\d\d)+(?!\d))/) { $1 + separators[:major] } if separators[:major] && opts[:format] != :plain string = minor ? major + (opts[:format] == :plain || !separators[:minor] ? '.' : separators[:minor]) + minor : major pre = [[:amount, :plain].include?(opts[:format]) && '', opts[:format] == :symbol && definition[:symbol], currency.to_s.upcase + ' '].detect{|a| a.is_a?(String)} "#{pre}#{string}" end
[ "def", "stringify", "amount", ",", "currency", ",", "opts", "=", "{", "}", "definition", "=", "definitions", "[", "currency", "]", "separators", "=", "definition", "[", ":separators", "]", "||", "{", "}", "format", "=", "\"%.#{definition[:minor_unit]}f\"", "string", "=", "format", "%", "amount", "major", ",", "minor", "=", "string", ".", "split", "(", "'.'", ")", "major", ".", "gsub!", "(", "/", "\\d", "\\d", "\\d", "\\d", "\\d", "/", ")", "{", "$1", "+", "separators", "[", ":major", "]", "}", "if", "separators", "[", ":major", "]", "&&", "opts", "[", ":format", "]", "!=", ":plain", "string", "=", "minor", "?", "major", "+", "(", "opts", "[", ":format", "]", "==", ":plain", "||", "!", "separators", "[", ":minor", "]", "?", "'.'", ":", "separators", "[", ":minor", "]", ")", "+", "minor", ":", "major", "pre", "=", "[", "[", ":amount", ",", ":plain", "]", ".", "include?", "(", "opts", "[", ":format", "]", ")", "&&", "''", ",", "opts", "[", ":format", "]", "==", ":symbol", "&&", "definition", "[", ":symbol", "]", ",", "currency", ".", "to_s", ".", "upcase", "+", "' '", "]", ".", "detect", "{", "|", "a", "|", "a", ".", "is_a?", "(", "String", ")", "}", "\"#{pre}#{string}\"", "end" ]
Converts the currency to a string in ISO 4217 standardized format, either with or without the currency. This leaves you with no worries how to display the currency. @param [BigDecimal, Fixed, Float] amount The amount of currency you want to stringify @param [String, Symbol] currency The currency you want to stringify @param [Hash] opts The options for formatting @option opts [Boolean] :format The format to put the string out in: :amount for only the amount, :symbol for a string with a currency symbol @return [String] The formatted string @example Convert a currency to a string Exchange::ISO.stringify(49.567, :usd) #=> "USD 49.57" @example Convert a currency without minor to a string Exchange::ISO.stringif(45, :jpy) #=> "JPY 45" @example Convert a currency with a three decimal minor to a string Exchange::ISO.stringif(34.34, :omr) #=> "OMR 34.340" @example Convert a currency to a string without the currency Exchange::ISO.stringif(34.34, :omr, :amount_only => true) #=> "34.340"
[ "Converts", "the", "currency", "to", "a", "string", "in", "ISO", "4217", "standardized", "format", "either", "with", "or", "without", "the", "currency", ".", "This", "leaves", "you", "with", "no", "worries", "how", "to", "display", "the", "currency", "." ]
4318b9dad3cce5e933827126160fafe30c68dc2a
https://github.com/beatrichartz/exchange/blob/4318b9dad3cce5e933827126160fafe30c68dc2a/lib/exchange/iso.rb#L114-L127
23,134
beatrichartz/exchange
lib/exchange/iso.rb
Exchange.ISO.symbolize_keys
def symbolize_keys hsh new_hsh = Hash.new hsh.each_pair do |k,v| v = symbolize_keys v if v.is_a?(Hash) new_hsh[k.downcase.to_sym] = v end new_hsh end
ruby
def symbolize_keys hsh new_hsh = Hash.new hsh.each_pair do |k,v| v = symbolize_keys v if v.is_a?(Hash) new_hsh[k.downcase.to_sym] = v end new_hsh end
[ "def", "symbolize_keys", "hsh", "new_hsh", "=", "Hash", ".", "new", "hsh", ".", "each_pair", "do", "|", "k", ",", "v", "|", "v", "=", "symbolize_keys", "v", "if", "v", ".", "is_a?", "(", "Hash", ")", "new_hsh", "[", "k", ".", "downcase", ".", "to_sym", "]", "=", "v", "end", "new_hsh", "end" ]
symbolizes keys and returns a new hash
[ "symbolizes", "keys", "and", "returns", "a", "new", "hash" ]
4318b9dad3cce5e933827126160fafe30c68dc2a
https://github.com/beatrichartz/exchange/blob/4318b9dad3cce5e933827126160fafe30c68dc2a/lib/exchange/iso.rb#L172-L181
23,135
beatrichartz/exchange
lib/exchange/iso.rb
Exchange.ISO.precision_for
def precision_for amount, currency defined_minor_precision = definitions[currency][:minor_unit] match = amount.to_s.match(/^-?(\d*)\.?(\d*)e?(-?\d+)?$/).to_a[1..3] given_major_precision, given_minor_precision = precision_from_match *match given_major_precision + [defined_minor_precision, given_minor_precision].max end
ruby
def precision_for amount, currency defined_minor_precision = definitions[currency][:minor_unit] match = amount.to_s.match(/^-?(\d*)\.?(\d*)e?(-?\d+)?$/).to_a[1..3] given_major_precision, given_minor_precision = precision_from_match *match given_major_precision + [defined_minor_precision, given_minor_precision].max end
[ "def", "precision_for", "amount", ",", "currency", "defined_minor_precision", "=", "definitions", "[", "currency", "]", "[", ":minor_unit", "]", "match", "=", "amount", ".", "to_s", ".", "match", "(", "/", "\\d", "\\.", "\\d", "\\d", "/", ")", ".", "to_a", "[", "1", "..", "3", "]", "given_major_precision", ",", "given_minor_precision", "=", "precision_from_match", "match", "given_major_precision", "+", "[", "defined_minor_precision", ",", "given_minor_precision", "]", ".", "max", "end" ]
get a precision for a specified amount and a specified currency @params [Float, Integer] amount The amount to get the precision for @params [Symbol] currency the currency to get the precision for
[ "get", "a", "precision", "for", "a", "specified", "amount", "and", "a", "specified", "currency" ]
4318b9dad3cce5e933827126160fafe30c68dc2a
https://github.com/beatrichartz/exchange/blob/4318b9dad3cce5e933827126160fafe30c68dc2a/lib/exchange/iso.rb#L188-L194
23,136
BadrIT/translation_center
lib/translation_center/acts_as_translator.rb
ActsAsTranslator.InstanceMethods.translation_for
def translation_for(key, lang) self.translations.find_or_initialize_by(translation_key_id: key.id, lang: lang.to_s, translator_type: self.class.name) end
ruby
def translation_for(key, lang) self.translations.find_or_initialize_by(translation_key_id: key.id, lang: lang.to_s, translator_type: self.class.name) end
[ "def", "translation_for", "(", "key", ",", "lang", ")", "self", ".", "translations", ".", "find_or_initialize_by", "(", "translation_key_id", ":", "key", ".", "id", ",", "lang", ":", "lang", ".", "to_s", ",", "translator_type", ":", "self", ".", "class", ".", "name", ")", "end" ]
returns the translation a user has made for a certain key in a certain language
[ "returns", "the", "translation", "a", "user", "has", "made", "for", "a", "certain", "key", "in", "a", "certain", "language" ]
439cbf70323e629a630fe939d02b44361afae13e
https://github.com/BadrIT/translation_center/blob/439cbf70323e629a630fe939d02b44361afae13e/lib/translation_center/acts_as_translator.rb#L11-L13
23,137
BadrIT/translation_center
app/models/translation_center/category.rb
TranslationCenter.Category.complete_percentage_in
def complete_percentage_in(lang) if self.keys.blank? 100 else accepted_keys = accepted_keys(lang) 100 * accepted_keys.count / self.keys.count end end
ruby
def complete_percentage_in(lang) if self.keys.blank? 100 else accepted_keys = accepted_keys(lang) 100 * accepted_keys.count / self.keys.count end end
[ "def", "complete_percentage_in", "(", "lang", ")", "if", "self", ".", "keys", ".", "blank?", "100", "else", "accepted_keys", "=", "accepted_keys", "(", "lang", ")", "100", "*", "accepted_keys", ".", "count", "/", "self", ".", "keys", ".", "count", "end", "end" ]
gets how much complete translation of category is in a certain language
[ "gets", "how", "much", "complete", "translation", "of", "category", "is", "in", "a", "certain", "language" ]
439cbf70323e629a630fe939d02b44361afae13e
https://github.com/BadrIT/translation_center/blob/439cbf70323e629a630fe939d02b44361afae13e/app/models/translation_center/category.rb#L12-L19
23,138
beatrichartz/exchange
lib/exchange/money.rb
Exchange.Money.to
def to other, options={} other = ISO.assert_currency!(other) if api_supports_currency?(currency) && api_supports_currency?(other) opts = { :at => time, :from => self }.merge(options) Money.new(api.new.convert(value, currency, other, opts), other, opts) elsif fallback! to other, options else raise_no_rate_error(other) end rescue ExternalAPI::APIError if fallback! to other, options else raise end end
ruby
def to other, options={} other = ISO.assert_currency!(other) if api_supports_currency?(currency) && api_supports_currency?(other) opts = { :at => time, :from => self }.merge(options) Money.new(api.new.convert(value, currency, other, opts), other, opts) elsif fallback! to other, options else raise_no_rate_error(other) end rescue ExternalAPI::APIError if fallback! to other, options else raise end end
[ "def", "to", "other", ",", "options", "=", "{", "}", "other", "=", "ISO", ".", "assert_currency!", "(", "other", ")", "if", "api_supports_currency?", "(", "currency", ")", "&&", "api_supports_currency?", "(", "other", ")", "opts", "=", "{", ":at", "=>", "time", ",", ":from", "=>", "self", "}", ".", "merge", "(", "options", ")", "Money", ".", "new", "(", "api", ".", "new", ".", "convert", "(", "value", ",", "currency", ",", "other", ",", "opts", ")", ",", "other", ",", "opts", ")", "elsif", "fallback!", "to", "other", ",", "options", "else", "raise_no_rate_error", "(", "other", ")", "end", "rescue", "ExternalAPI", "::", "APIError", "if", "fallback!", "to", "other", ",", "options", "else", "raise", "end", "end" ]
Converts this instance of currency into another currency @return [Exchange::Money] An instance of Exchange::Money with the converted number and the converted currency @param [Symbol, String] other The currency to convert the number to @param [Hash] options An options hash @option [Time] :at The timestamp of the rate the conversion took place in @example convert to 'chf' Exchange::Money.new(40,:usd).to(:chf) @example convert to 'sek' at a specific rate Exchange::Money.new(40,:nok).to(:sek, :at => Time.gm(2012,2,2))
[ "Converts", "this", "instance", "of", "currency", "into", "another", "currency" ]
4318b9dad3cce5e933827126160fafe30c68dc2a
https://github.com/beatrichartz/exchange/blob/4318b9dad3cce5e933827126160fafe30c68dc2a/lib/exchange/money.rb#L86-L103
23,139
beatrichartz/exchange
lib/exchange/money.rb
Exchange.Money.fallback!
def fallback! fallback = Exchange.configuration.api.fallback new_api = fallback.index(api) ? fallback[fallback.index(api) + 1] : fallback.first if new_api @api = new_api return true end return false end
ruby
def fallback! fallback = Exchange.configuration.api.fallback new_api = fallback.index(api) ? fallback[fallback.index(api) + 1] : fallback.first if new_api @api = new_api return true end return false end
[ "def", "fallback!", "fallback", "=", "Exchange", ".", "configuration", ".", "api", ".", "fallback", "new_api", "=", "fallback", ".", "index", "(", "api", ")", "?", "fallback", "[", "fallback", ".", "index", "(", "api", ")", "+", "1", "]", ":", "fallback", ".", "first", "if", "new_api", "@api", "=", "new_api", "return", "true", "end", "return", "false", "end" ]
Fallback to the next api defined in the api fallbacks. Changes the api for the given instance @return [Boolean] true if the fallback was successful, false if not @since 1.0 @version 1.0
[ "Fallback", "to", "the", "next", "api", "defined", "in", "the", "api", "fallbacks", ".", "Changes", "the", "api", "for", "the", "given", "instance" ]
4318b9dad3cce5e933827126160fafe30c68dc2a
https://github.com/beatrichartz/exchange/blob/4318b9dad3cce5e933827126160fafe30c68dc2a/lib/exchange/money.rb#L334-L344
23,140
BadrIT/translation_center
app/models/translation_center/translation.rb
TranslationCenter.Translation.accept
def accept # If translation is accepted do nothing unless self.accepted? self.translation_key.accepted_translation_in(self.lang) .try(:update_attribute, :status, TranslationKey::PENDING) # reload the translation key as it has changed self.translation_key.reload self.update_attribute(:status, ACCEPTED) end end
ruby
def accept # If translation is accepted do nothing unless self.accepted? self.translation_key.accepted_translation_in(self.lang) .try(:update_attribute, :status, TranslationKey::PENDING) # reload the translation key as it has changed self.translation_key.reload self.update_attribute(:status, ACCEPTED) end end
[ "def", "accept", "# If translation is accepted do nothing", "unless", "self", ".", "accepted?", "self", ".", "translation_key", ".", "accepted_translation_in", "(", "self", ".", "lang", ")", ".", "try", "(", ":update_attribute", ",", ":status", ",", "TranslationKey", "::", "PENDING", ")", "# reload the translation key as it has changed", "self", ".", "translation_key", ".", "reload", "self", ".", "update_attribute", "(", ":status", ",", "ACCEPTED", ")", "end", "end" ]
Accept translation by changing its status and if there is an accepting translation make it pending
[ "Accept", "translation", "by", "changing", "its", "status", "and", "if", "there", "is", "an", "accepting", "translation", "make", "it", "pending" ]
439cbf70323e629a630fe939d02b44361afae13e
https://github.com/BadrIT/translation_center/blob/439cbf70323e629a630fe939d02b44361afae13e/app/models/translation_center/translation.rb#L71-L81
23,141
BadrIT/translation_center
app/models/translation_center/translation.rb
TranslationCenter.Translation.one_translation_per_lang_per_key
def one_translation_per_lang_per_key translation_exists = Translation.exists?( lang: self.lang, translator_id: self.translator.id, translator_type: self.translator.class.name, translation_key_id: self.key.id ) unless translation_exists true else false self.errors.add(:lang, I18n.t('.one_translation_per_lang_per_key')) end end
ruby
def one_translation_per_lang_per_key translation_exists = Translation.exists?( lang: self.lang, translator_id: self.translator.id, translator_type: self.translator.class.name, translation_key_id: self.key.id ) unless translation_exists true else false self.errors.add(:lang, I18n.t('.one_translation_per_lang_per_key')) end end
[ "def", "one_translation_per_lang_per_key", "translation_exists", "=", "Translation", ".", "exists?", "(", "lang", ":", "self", ".", "lang", ",", "translator_id", ":", "self", ".", "translator", ".", "id", ",", "translator_type", ":", "self", ".", "translator", ".", "class", ".", "name", ",", "translation_key_id", ":", "self", ".", "key", ".", "id", ")", "unless", "translation_exists", "true", "else", "false", "self", ".", "errors", ".", "add", "(", ":lang", ",", "I18n", ".", "t", "(", "'.one_translation_per_lang_per_key'", ")", ")", "end", "end" ]
make sure user has one translation per key per lang
[ "make", "sure", "user", "has", "one", "translation", "per", "key", "per", "lang" ]
439cbf70323e629a630fe939d02b44361afae13e
https://github.com/BadrIT/translation_center/blob/439cbf70323e629a630fe939d02b44361afae13e/app/models/translation_center/translation.rb#L89-L103
23,142
vigetlabs/pointless-feedback
app/helpers/pointless_feedback/application_helper.rb
PointlessFeedback.ApplicationHelper.method_missing
def method_missing(method, *args, &block) if main_app_url_helper?(method) main_app.send(method, *args) else super end end
ruby
def method_missing(method, *args, &block) if main_app_url_helper?(method) main_app.send(method, *args) else super end end
[ "def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "if", "main_app_url_helper?", "(", "method", ")", "main_app", ".", "send", "(", "method", ",", "args", ")", "else", "super", "end", "end" ]
Can search for named routes directly in the main app, omitting the "main_app." prefix
[ "Can", "search", "for", "named", "routes", "directly", "in", "the", "main", "app", "omitting", "the", "main_app", ".", "prefix" ]
be7ca04bf51a46ca9a1db6710665857d0e21fcc8
https://github.com/vigetlabs/pointless-feedback/blob/be7ca04bf51a46ca9a1db6710665857d0e21fcc8/app/helpers/pointless_feedback/application_helper.rb#L7-L13
23,143
change/aws-swf
lib/swf/decision_task_handler.rb
SWF.DecisionTaskHandler.tags
def tags runner.tag_lists[decision_task.workflow_execution] ||= begin collision = 0 begin decision_task.workflow_execution.tags rescue => e collision += 1 if collision < 10 max_slot_delay = 2**collision - 1 sleep(slot_time * rand(0 .. max_slot_delay)) retry end end end
ruby
def tags runner.tag_lists[decision_task.workflow_execution] ||= begin collision = 0 begin decision_task.workflow_execution.tags rescue => e collision += 1 if collision < 10 max_slot_delay = 2**collision - 1 sleep(slot_time * rand(0 .. max_slot_delay)) retry end end end
[ "def", "tags", "runner", ".", "tag_lists", "[", "decision_task", ".", "workflow_execution", "]", "||=", "begin", "collision", "=", "0", "begin", "decision_task", ".", "workflow_execution", ".", "tags", "rescue", "=>", "e", "collision", "+=", "1", "if", "collision", "<", "10", "max_slot_delay", "=", "2", "**", "collision", "-", "1", "sleep", "(", "slot_time", "*", "rand", "(", "0", "..", "max_slot_delay", ")", ")", "retry", "end", "end", "end" ]
exponential backoff handles rate limiting exceptions when querying tags on a workflow execution.
[ "exponential", "backoff", "handles", "rate", "limiting", "exceptions", "when", "querying", "tags", "on", "a", "workflow", "execution", "." ]
a025d5b1009371f48c9386b8a717e2e54738094d
https://github.com/change/aws-swf/blob/a025d5b1009371f48c9386b8a717e2e54738094d/lib/swf/decision_task_handler.rb#L70-L82
23,144
damianFC/alexa-rubykit
lib/alexa_rubykit/response.rb
AlexaRubykit.Response.say_response
def say_response(speech, end_session = true, ssml = false) output_speech = add_speech(speech,ssml) { :outputSpeech => output_speech, :shouldEndSession => end_session } end
ruby
def say_response(speech, end_session = true, ssml = false) output_speech = add_speech(speech,ssml) { :outputSpeech => output_speech, :shouldEndSession => end_session } end
[ "def", "say_response", "(", "speech", ",", "end_session", "=", "true", ",", "ssml", "=", "false", ")", "output_speech", "=", "add_speech", "(", "speech", ",", "ssml", ")", "{", ":outputSpeech", "=>", "output_speech", ",", ":shouldEndSession", "=>", "end_session", "}", "end" ]
Adds a speech to the object, also returns a outputspeech object.
[ "Adds", "a", "speech", "to", "the", "object", "also", "returns", "a", "outputspeech", "object", "." ]
06c9506b20adbd6fb0f37d6a1df223e1d8469338
https://github.com/damianFC/alexa-rubykit/blob/06c9506b20adbd6fb0f37d6a1df223e1d8469338/lib/alexa_rubykit/response.rb#L104-L107
23,145
damianFC/alexa-rubykit
lib/alexa_rubykit/response.rb
AlexaRubykit.Response.say_response_with_reprompt
def say_response_with_reprompt(speech, reprompt_speech, end_session = true, speech_ssml = false, reprompt_ssml = false) output_speech = add_speech(speech,speech_ssml) reprompt_speech = add_reprompt(reprompt_speech,reprompt_ssml) { :outputSpeech => output_speech, :reprompt => reprompt_speech, :shouldEndSession => end_session } end
ruby
def say_response_with_reprompt(speech, reprompt_speech, end_session = true, speech_ssml = false, reprompt_ssml = false) output_speech = add_speech(speech,speech_ssml) reprompt_speech = add_reprompt(reprompt_speech,reprompt_ssml) { :outputSpeech => output_speech, :reprompt => reprompt_speech, :shouldEndSession => end_session } end
[ "def", "say_response_with_reprompt", "(", "speech", ",", "reprompt_speech", ",", "end_session", "=", "true", ",", "speech_ssml", "=", "false", ",", "reprompt_ssml", "=", "false", ")", "output_speech", "=", "add_speech", "(", "speech", ",", "speech_ssml", ")", "reprompt_speech", "=", "add_reprompt", "(", "reprompt_speech", ",", "reprompt_ssml", ")", "{", ":outputSpeech", "=>", "output_speech", ",", ":reprompt", "=>", "reprompt_speech", ",", ":shouldEndSession", "=>", "end_session", "}", "end" ]
Incorporates reprompt in the SDK 2015-05
[ "Incorporates", "reprompt", "in", "the", "SDK", "2015", "-", "05" ]
06c9506b20adbd6fb0f37d6a1df223e1d8469338
https://github.com/damianFC/alexa-rubykit/blob/06c9506b20adbd6fb0f37d6a1df223e1d8469338/lib/alexa_rubykit/response.rb#L110-L114
23,146
damianFC/alexa-rubykit
lib/alexa_rubykit/response.rb
AlexaRubykit.Response.build_response
def build_response(session_end = true) response_object = build_response_object(session_end) response = Hash.new response[:version] = @version response[:sessionAttributes] = @session_attributes unless @session_attributes.empty? response[:response] = response_object response.to_json end
ruby
def build_response(session_end = true) response_object = build_response_object(session_end) response = Hash.new response[:version] = @version response[:sessionAttributes] = @session_attributes unless @session_attributes.empty? response[:response] = response_object response.to_json end
[ "def", "build_response", "(", "session_end", "=", "true", ")", "response_object", "=", "build_response_object", "(", "session_end", ")", "response", "=", "Hash", ".", "new", "response", "[", ":version", "]", "=", "@version", "response", "[", ":sessionAttributes", "]", "=", "@session_attributes", "unless", "@session_attributes", ".", "empty?", "response", "[", ":response", "]", "=", "response_object", "response", ".", "to_json", "end" ]
Builds a response. Takes the version, response and should_end_session variables and builds a JSON object.
[ "Builds", "a", "response", ".", "Takes", "the", "version", "response", "and", "should_end_session", "variables", "and", "builds", "a", "JSON", "object", "." ]
06c9506b20adbd6fb0f37d6a1df223e1d8469338
https://github.com/damianFC/alexa-rubykit/blob/06c9506b20adbd6fb0f37d6a1df223e1d8469338/lib/alexa_rubykit/response.rb#L139-L146
23,147
damianFC/alexa-rubykit
lib/alexa_rubykit/intent_request.rb
AlexaRubykit.IntentRequest.add_hash_slots
def add_hash_slots(slots) raise ArgumentError, 'Slots can\'t be empty' slots.each do |slot| @slots[:slot[:name]] = Slot.new(slot[:name], slot[:value]) end @slots end
ruby
def add_hash_slots(slots) raise ArgumentError, 'Slots can\'t be empty' slots.each do |slot| @slots[:slot[:name]] = Slot.new(slot[:name], slot[:value]) end @slots end
[ "def", "add_hash_slots", "(", "slots", ")", "raise", "ArgumentError", ",", "'Slots can\\'t be empty'", "slots", ".", "each", "do", "|", "slot", "|", "@slots", "[", ":slot", "[", ":name", "]", "]", "=", "Slot", ".", "new", "(", "slot", "[", ":name", "]", ",", "slot", "[", ":value", "]", ")", "end", "@slots", "end" ]
We still don't know if all of the parameters in the request are required. Checking for the presence of intent on an IntentRequest. Takes a Hash object.
[ "We", "still", "don", "t", "know", "if", "all", "of", "the", "parameters", "in", "the", "request", "are", "required", ".", "Checking", "for", "the", "presence", "of", "intent", "on", "an", "IntentRequest", ".", "Takes", "a", "Hash", "object", "." ]
06c9506b20adbd6fb0f37d6a1df223e1d8469338
https://github.com/damianFC/alexa-rubykit/blob/06c9506b20adbd6fb0f37d6a1df223e1d8469338/lib/alexa_rubykit/intent_request.rb#L17-L23
23,148
damianFC/alexa-rubykit
lib/alexa_rubykit/intent_request.rb
AlexaRubykit.IntentRequest.add_slot
def add_slot(name, value) slot = Slot.new(name, value) @slots[:name] = slot slot end
ruby
def add_slot(name, value) slot = Slot.new(name, value) @slots[:name] = slot slot end
[ "def", "add_slot", "(", "name", ",", "value", ")", "slot", "=", "Slot", ".", "new", "(", "name", ",", "value", ")", "@slots", "[", ":name", "]", "=", "slot", "slot", "end" ]
Adds a slot from a name and a value.
[ "Adds", "a", "slot", "from", "a", "name", "and", "a", "value", "." ]
06c9506b20adbd6fb0f37d6a1df223e1d8469338
https://github.com/damianFC/alexa-rubykit/blob/06c9506b20adbd6fb0f37d6a1df223e1d8469338/lib/alexa_rubykit/intent_request.rb#L32-L36
23,149
ankane/activejob_backport
lib/active_job/execution.rb
ActiveJob.Execution.perform_now
def perform_now deserialize_arguments_if_needed run_callbacks :perform do perform(*arguments) end rescue => exception rescue_with_handler(exception) || raise(exception) end
ruby
def perform_now deserialize_arguments_if_needed run_callbacks :perform do perform(*arguments) end rescue => exception rescue_with_handler(exception) || raise(exception) end
[ "def", "perform_now", "deserialize_arguments_if_needed", "run_callbacks", ":perform", "do", "perform", "(", "arguments", ")", "end", "rescue", "=>", "exception", "rescue_with_handler", "(", "exception", ")", "||", "raise", "(", "exception", ")", "end" ]
Performs the job immediately. The job is not sent to the queueing adapter and will block the execution until it's finished. MyJob.new(*args).perform_now
[ "Performs", "the", "job", "immediately", ".", "The", "job", "is", "not", "sent", "to", "the", "queueing", "adapter", "and", "will", "block", "the", "execution", "until", "it", "s", "finished", "." ]
daa74738d1a241a01f2c373145ac81ec1e822c7c
https://github.com/ankane/activejob_backport/blob/daa74738d1a241a01f2c373145ac81ec1e822c7c/lib/active_job/execution.rb#L28-L35
23,150
jeremy/rack-ratelimit
lib/rack/ratelimit.rb
Rack.Ratelimit.apply_rate_limit?
def apply_rate_limit?(env) @exceptions.none? { |e| e.call(env) } && @conditions.all? { |c| c.call(env) } end
ruby
def apply_rate_limit?(env) @exceptions.none? { |e| e.call(env) } && @conditions.all? { |c| c.call(env) } end
[ "def", "apply_rate_limit?", "(", "env", ")", "@exceptions", ".", "none?", "{", "|", "e", "|", "e", ".", "call", "(", "env", ")", "}", "&&", "@conditions", ".", "all?", "{", "|", "c", "|", "c", ".", "call", "(", "env", ")", "}", "end" ]
Apply the rate limiter if none of the exceptions apply and all the conditions are met.
[ "Apply", "the", "rate", "limiter", "if", "none", "of", "the", "exceptions", "apply", "and", "all", "the", "conditions", "are", "met", "." ]
f40b928d456b08532a3226270b2bbf4878d1a320
https://github.com/jeremy/rack-ratelimit/blob/f40b928d456b08532a3226270b2bbf4878d1a320/lib/rack/ratelimit.rb#L108-L110
23,151
jeremy/rack-ratelimit
lib/rack/ratelimit.rb
Rack.Ratelimit.seconds_until_epoch
def seconds_until_epoch(epoch) sec = (epoch - Time.now.to_f).ceil sec = 0 if sec < 0 sec end
ruby
def seconds_until_epoch(epoch) sec = (epoch - Time.now.to_f).ceil sec = 0 if sec < 0 sec end
[ "def", "seconds_until_epoch", "(", "epoch", ")", "sec", "=", "(", "epoch", "-", "Time", ".", "now", ".", "to_f", ")", ".", "ceil", "sec", "=", "0", "if", "sec", "<", "0", "sec", "end" ]
Clamp negative durations in case we're in a new rate-limiting window.
[ "Clamp", "negative", "durations", "in", "case", "we", "re", "in", "a", "new", "rate", "-", "limiting", "window", "." ]
f40b928d456b08532a3226270b2bbf4878d1a320
https://github.com/jeremy/rack-ratelimit/blob/f40b928d456b08532a3226270b2bbf4878d1a320/lib/rack/ratelimit.rb#L176-L180
23,152
ankane/activejob_backport
lib/active_job/enqueuing.rb
ActiveJob.Enqueuing.enqueue
def enqueue(options={}) self.scheduled_at = options[:wait].seconds.from_now.to_f if options[:wait] self.scheduled_at = options[:wait_until].to_f if options[:wait_until] self.queue_name = self.class.queue_name_from_part(options[:queue]) if options[:queue] run_callbacks :enqueue do if self.scheduled_at self.class.queue_adapter.enqueue_at self, self.scheduled_at else self.class.queue_adapter.enqueue self end end self end
ruby
def enqueue(options={}) self.scheduled_at = options[:wait].seconds.from_now.to_f if options[:wait] self.scheduled_at = options[:wait_until].to_f if options[:wait_until] self.queue_name = self.class.queue_name_from_part(options[:queue]) if options[:queue] run_callbacks :enqueue do if self.scheduled_at self.class.queue_adapter.enqueue_at self, self.scheduled_at else self.class.queue_adapter.enqueue self end end self end
[ "def", "enqueue", "(", "options", "=", "{", "}", ")", "self", ".", "scheduled_at", "=", "options", "[", ":wait", "]", ".", "seconds", ".", "from_now", ".", "to_f", "if", "options", "[", ":wait", "]", "self", ".", "scheduled_at", "=", "options", "[", ":wait_until", "]", ".", "to_f", "if", "options", "[", ":wait_until", "]", "self", ".", "queue_name", "=", "self", ".", "class", ".", "queue_name_from_part", "(", "options", "[", ":queue", "]", ")", "if", "options", "[", ":queue", "]", "run_callbacks", ":enqueue", "do", "if", "self", ".", "scheduled_at", "self", ".", "class", ".", "queue_adapter", ".", "enqueue_at", "self", ",", "self", ".", "scheduled_at", "else", "self", ".", "class", ".", "queue_adapter", ".", "enqueue", "self", "end", "end", "self", "end" ]
Equeue the job to be performed by the queue adapter. ==== Options * <tt>:wait</tt> - Enqueues the job with the specified delay * <tt>:wait_until</tt> - Enqueues the job at the time specified * <tt>:queue</tt> - Enqueues the job on the specified queue ==== Examples my_job_instance.enqueue my_job_instance.enqueue wait: 5.minutes my_job_instance.enqueue queue: :important my_job_instance.enqueue wait_until: Date.tomorrow.midnight
[ "Equeue", "the", "job", "to", "be", "performed", "by", "the", "queue", "adapter", "." ]
daa74738d1a241a01f2c373145ac81ec1e822c7c
https://github.com/ankane/activejob_backport/blob/daa74738d1a241a01f2c373145ac81ec1e822c7c/lib/active_job/enqueuing.rb#L61-L73
23,153
ozfortress/tournament-system
lib/tournament_system/driver.rb
TournamentSystem.Driver.create_match
def create_match(home_team, away_team) home_team, away_team = away_team, home_team unless home_team raise 'Invalid match' unless home_team build_match(home_team, away_team) end
ruby
def create_match(home_team, away_team) home_team, away_team = away_team, home_team unless home_team raise 'Invalid match' unless home_team build_match(home_team, away_team) end
[ "def", "create_match", "(", "home_team", ",", "away_team", ")", "home_team", ",", "away_team", "=", "away_team", ",", "home_team", "unless", "home_team", "raise", "'Invalid match'", "unless", "home_team", "build_match", "(", "home_team", ",", "away_team", ")", "end" ]
Create a match. Used by tournament systems. Specially handles byes, swapping home/away if required. @param home_team [team, nil] @param away_team [team, nil] @return [nil] @raise when both teams are +nil+
[ "Create", "a", "match", ".", "Used", "by", "tournament", "systems", "." ]
d4c8dc77933ba97d369f287b1c21d7fcda78830b
https://github.com/ozfortress/tournament-system/blob/d4c8dc77933ba97d369f287b1c21d7fcda78830b/lib/tournament_system/driver.rb#L207-L212
23,154
ozfortress/tournament-system
lib/tournament_system/driver.rb
TournamentSystem.Driver.loss_count_hash
def loss_count_hash @loss_count_hash ||= matches.each_with_object(Hash.new(0)) { |match, hash| hash[get_match_loser(match)] += 1 } end
ruby
def loss_count_hash @loss_count_hash ||= matches.each_with_object(Hash.new(0)) { |match, hash| hash[get_match_loser(match)] += 1 } end
[ "def", "loss_count_hash", "@loss_count_hash", "||=", "matches", ".", "each_with_object", "(", "Hash", ".", "new", "(", "0", ")", ")", "{", "|", "match", ",", "hash", "|", "hash", "[", "get_match_loser", "(", "match", ")", "]", "+=", "1", "}", "end" ]
Get a hash of the number of losses of each team. Used by tournament systems. @return [Hash{team => Number}] a mapping from teams to losses
[ "Get", "a", "hash", "of", "the", "number", "of", "losses", "of", "each", "team", ".", "Used", "by", "tournament", "systems", "." ]
d4c8dc77933ba97d369f287b1c21d7fcda78830b
https://github.com/ozfortress/tournament-system/blob/d4c8dc77933ba97d369f287b1c21d7fcda78830b/lib/tournament_system/driver.rb#L235-L237
23,155
jarthod/survey-gizmo-ruby
lib/survey_gizmo/api/answer.rb
SurveyGizmo::API.Answer.to_hash
def to_hash { response_id: response_id, question_id: question_id, option_id: option_id, question_pipe: question_pipe, submitted_at: submitted_at, survey_id: survey_id, other_text: other_text, answer_text: option_id || other_text ? nil : answer_text }.reject { |k, v| v.nil? } end
ruby
def to_hash { response_id: response_id, question_id: question_id, option_id: option_id, question_pipe: question_pipe, submitted_at: submitted_at, survey_id: survey_id, other_text: other_text, answer_text: option_id || other_text ? nil : answer_text }.reject { |k, v| v.nil? } end
[ "def", "to_hash", "{", "response_id", ":", "response_id", ",", "question_id", ":", "question_id", ",", "option_id", ":", "option_id", ",", "question_pipe", ":", "question_pipe", ",", "submitted_at", ":", "submitted_at", ",", "survey_id", ":", "survey_id", ",", "other_text", ":", "other_text", ",", "answer_text", ":", "option_id", "||", "other_text", "?", "nil", ":", "answer_text", "}", ".", "reject", "{", "|", "k", ",", "v", "|", "v", ".", "nil?", "}", "end" ]
Strips out the answer_text when there is a valid option_id
[ "Strips", "out", "the", "answer_text", "when", "there", "is", "a", "valid", "option_id" ]
757b91399b03bd5bf8d3e61b2224da5b77503a88
https://github.com/jarthod/survey-gizmo-ruby/blob/757b91399b03bd5bf8d3e61b2224da5b77503a88/lib/survey_gizmo/api/answer.rb#L51-L62
23,156
smalruby/smalruby
lib/smalruby/color.rb
Smalruby.Color.rgb_to_hsl
def rgb_to_hsl(red, green, blue) red = round_rgb_color(red) green = round_rgb_color(green) blue = round_rgb_color(blue) color_max = [red, green, blue].max color_min = [red, green, blue].min color_range = color_max - color_min if color_range == 0 return [0, 0, (color_max * 100.0 / 255).to_i] end color_range = color_range.to_f hue = (case color_max when red then HUE_PER_6 * ((green - blue) / color_range) when green then HUE_PER_6 * ((blue - red) / color_range) + HUE_PER_6 * 2 else HUE_PER_6 * ((red - green) / color_range) + HUE_PER_6 * 4 end) cnt = color_range / 2.0 if cnt <= 127 saturation = color_range / (color_max + color_min) * 100 else saturation = color_range / (510 - color_max - color_min) * 100 end lightness = (color_max + color_min) / 2.0 / 255.0 * 100 [hue.round, saturation.round, lightness.round] end
ruby
def rgb_to_hsl(red, green, blue) red = round_rgb_color(red) green = round_rgb_color(green) blue = round_rgb_color(blue) color_max = [red, green, blue].max color_min = [red, green, blue].min color_range = color_max - color_min if color_range == 0 return [0, 0, (color_max * 100.0 / 255).to_i] end color_range = color_range.to_f hue = (case color_max when red then HUE_PER_6 * ((green - blue) / color_range) when green then HUE_PER_6 * ((blue - red) / color_range) + HUE_PER_6 * 2 else HUE_PER_6 * ((red - green) / color_range) + HUE_PER_6 * 4 end) cnt = color_range / 2.0 if cnt <= 127 saturation = color_range / (color_max + color_min) * 100 else saturation = color_range / (510 - color_max - color_min) * 100 end lightness = (color_max + color_min) / 2.0 / 255.0 * 100 [hue.round, saturation.round, lightness.round] end
[ "def", "rgb_to_hsl", "(", "red", ",", "green", ",", "blue", ")", "red", "=", "round_rgb_color", "(", "red", ")", "green", "=", "round_rgb_color", "(", "green", ")", "blue", "=", "round_rgb_color", "(", "blue", ")", "color_max", "=", "[", "red", ",", "green", ",", "blue", "]", ".", "max", "color_min", "=", "[", "red", ",", "green", ",", "blue", "]", ".", "min", "color_range", "=", "color_max", "-", "color_min", "if", "color_range", "==", "0", "return", "[", "0", ",", "0", ",", "(", "color_max", "*", "100.0", "/", "255", ")", ".", "to_i", "]", "end", "color_range", "=", "color_range", ".", "to_f", "hue", "=", "(", "case", "color_max", "when", "red", "then", "HUE_PER_6", "*", "(", "(", "green", "-", "blue", ")", "/", "color_range", ")", "when", "green", "then", "HUE_PER_6", "*", "(", "(", "blue", "-", "red", ")", "/", "color_range", ")", "+", "HUE_PER_6", "*", "2", "else", "HUE_PER_6", "*", "(", "(", "red", "-", "green", ")", "/", "color_range", ")", "+", "HUE_PER_6", "*", "4", "end", ")", "cnt", "=", "color_range", "/", "2.0", "if", "cnt", "<=", "127", "saturation", "=", "color_range", "/", "(", "color_max", "+", "color_min", ")", "*", "100", "else", "saturation", "=", "color_range", "/", "(", "510", "-", "color_max", "-", "color_min", ")", "*", "100", "end", "lightness", "=", "(", "color_max", "+", "color_min", ")", "/", "2.0", "/", "255.0", "*", "100", "[", "hue", ".", "round", ",", "saturation", ".", "round", ",", "lightness", ".", "round", "]", "end" ]
Convert RGB Color model to HSL Color model @param [Integer] red @param [Integer] green @param [Integer] blue @return [Array] hue, saturation, lightness hue in the range [0,200], saturation and lightness in the range [0, 100]
[ "Convert", "RGB", "Color", "model", "to", "HSL", "Color", "model" ]
859a5f0b503bc55a790fda38f2bce27414226ada
https://github.com/smalruby/smalruby/blob/859a5f0b503bc55a790fda38f2bce27414226ada/lib/smalruby/color.rb#L183-L213
23,157
smalruby/smalruby
lib/smalruby/color.rb
Smalruby.Color.hsl_to_rgb
def hsl_to_rgb(h, s, l) h %= 201 s %= 101 l %= 101 if l <= 49 color_max = 255.0 * (l + l * (s / 100.0)) / 100.0 color_min = 255.0 * (l - l * (s / 100.0)) / 100.0 else color_max = 255.0 * (l + (100 - l) * (s / 100.0)) / 100.0 color_min = 255.0 * (l - (100 - l) * (s / 100.0)) / 100.0 end if h < HUE_PER_6 base = h elsif h < HUE_PER_6 * 3 base = (h - HUE_PER_6 * 2).abs elsif h < HUE_PER_6 * 5 base = (h - HUE_PER_6 * 4).abs else base = (200 - h) end base = base / HUE_PER_6 * (color_max - color_min) + color_min divide = (h / HUE_PER_6).to_i red, green, blue = (case divide when 0 then [color_max, base, color_min] when 1 then [base, color_max, color_min] when 2 then [color_min, color_max, base] when 3 then [color_min, base, color_max] when 4 then [base, color_min, color_max] else [color_max, color_min, base] end) [red.round, green.round, blue.round] end
ruby
def hsl_to_rgb(h, s, l) h %= 201 s %= 101 l %= 101 if l <= 49 color_max = 255.0 * (l + l * (s / 100.0)) / 100.0 color_min = 255.0 * (l - l * (s / 100.0)) / 100.0 else color_max = 255.0 * (l + (100 - l) * (s / 100.0)) / 100.0 color_min = 255.0 * (l - (100 - l) * (s / 100.0)) / 100.0 end if h < HUE_PER_6 base = h elsif h < HUE_PER_6 * 3 base = (h - HUE_PER_6 * 2).abs elsif h < HUE_PER_6 * 5 base = (h - HUE_PER_6 * 4).abs else base = (200 - h) end base = base / HUE_PER_6 * (color_max - color_min) + color_min divide = (h / HUE_PER_6).to_i red, green, blue = (case divide when 0 then [color_max, base, color_min] when 1 then [base, color_max, color_min] when 2 then [color_min, color_max, base] when 3 then [color_min, base, color_max] when 4 then [base, color_min, color_max] else [color_max, color_min, base] end) [red.round, green.round, blue.round] end
[ "def", "hsl_to_rgb", "(", "h", ",", "s", ",", "l", ")", "h", "%=", "201", "s", "%=", "101", "l", "%=", "101", "if", "l", "<=", "49", "color_max", "=", "255.0", "*", "(", "l", "+", "l", "*", "(", "s", "/", "100.0", ")", ")", "/", "100.0", "color_min", "=", "255.0", "*", "(", "l", "-", "l", "*", "(", "s", "/", "100.0", ")", ")", "/", "100.0", "else", "color_max", "=", "255.0", "*", "(", "l", "+", "(", "100", "-", "l", ")", "*", "(", "s", "/", "100.0", ")", ")", "/", "100.0", "color_min", "=", "255.0", "*", "(", "l", "-", "(", "100", "-", "l", ")", "*", "(", "s", "/", "100.0", ")", ")", "/", "100.0", "end", "if", "h", "<", "HUE_PER_6", "base", "=", "h", "elsif", "h", "<", "HUE_PER_6", "*", "3", "base", "=", "(", "h", "-", "HUE_PER_6", "*", "2", ")", ".", "abs", "elsif", "h", "<", "HUE_PER_6", "*", "5", "base", "=", "(", "h", "-", "HUE_PER_6", "*", "4", ")", ".", "abs", "else", "base", "=", "(", "200", "-", "h", ")", "end", "base", "=", "base", "/", "HUE_PER_6", "*", "(", "color_max", "-", "color_min", ")", "+", "color_min", "divide", "=", "(", "h", "/", "HUE_PER_6", ")", ".", "to_i", "red", ",", "green", ",", "blue", "=", "(", "case", "divide", "when", "0", "then", "[", "color_max", ",", "base", ",", "color_min", "]", "when", "1", "then", "[", "base", ",", "color_max", ",", "color_min", "]", "when", "2", "then", "[", "color_min", ",", "color_max", ",", "base", "]", "when", "3", "then", "[", "color_min", ",", "base", ",", "color_max", "]", "when", "4", "then", "[", "base", ",", "color_min", ",", "color_max", "]", "else", "[", "color_max", ",", "color_min", ",", "base", "]", "end", ")", "[", "red", ".", "round", ",", "green", ".", "round", ",", "blue", ".", "round", "]", "end" ]
Convert HSV Color model to RGB Color model @param [Integer] h @param [Integer] s @param [Integer] l @return [Array] red,green,blue color red,green,blue in the range [0,255]
[ "Convert", "HSV", "Color", "model", "to", "RGB", "Color", "model" ]
859a5f0b503bc55a790fda38f2bce27414226ada
https://github.com/smalruby/smalruby/blob/859a5f0b503bc55a790fda38f2bce27414226ada/lib/smalruby/color.rb#L236-L270
23,158
aspring/racker
lib/racker/template.rb
Racker.Template.to_packer
def to_packer # Create the new smash packer = Smash.new # Variables packer['variables'] = self['variables'].dup unless self['variables'].nil? || self['variables'].empty? # Builders packer['builders'] = [] unless self['builders'].nil? || self['builders'].empty? logger.info("Processing builders...") self['builders'].each do |name,config| logger.info("Processing builder: #{name} with type: #{config['type']}") # Get the builder for this config builder = get_builder(config['type']) # Have the builder convert the config to packer format packer['builders'] << builder.to_packer(name, config.dup) end # Provisioners packer['provisioners'] = [] unless self['provisioners'].nil? || self['provisioners'].empty? logger.info("Processing provisioners...") self['provisioners'].sort.map do |index, provisioners| provisioners.each do |name,config| logger.debug("Processing provisioner: #{name}") packer['provisioners'] << config.dup end end # Post-Processors packer['post-processors'] = [] unless self['postprocessors'].nil? || self['postprocessors'].empty? logger.info("Processing post-processors...") self['postprocessors'].each do |name,config| logger.debug("Processing post-processor: #{name}") packer['post-processors'] << config.dup unless config.nil? end packer end
ruby
def to_packer # Create the new smash packer = Smash.new # Variables packer['variables'] = self['variables'].dup unless self['variables'].nil? || self['variables'].empty? # Builders packer['builders'] = [] unless self['builders'].nil? || self['builders'].empty? logger.info("Processing builders...") self['builders'].each do |name,config| logger.info("Processing builder: #{name} with type: #{config['type']}") # Get the builder for this config builder = get_builder(config['type']) # Have the builder convert the config to packer format packer['builders'] << builder.to_packer(name, config.dup) end # Provisioners packer['provisioners'] = [] unless self['provisioners'].nil? || self['provisioners'].empty? logger.info("Processing provisioners...") self['provisioners'].sort.map do |index, provisioners| provisioners.each do |name,config| logger.debug("Processing provisioner: #{name}") packer['provisioners'] << config.dup end end # Post-Processors packer['post-processors'] = [] unless self['postprocessors'].nil? || self['postprocessors'].empty? logger.info("Processing post-processors...") self['postprocessors'].each do |name,config| logger.debug("Processing post-processor: #{name}") packer['post-processors'] << config.dup unless config.nil? end packer end
[ "def", "to_packer", "# Create the new smash", "packer", "=", "Smash", ".", "new", "# Variables", "packer", "[", "'variables'", "]", "=", "self", "[", "'variables'", "]", ".", "dup", "unless", "self", "[", "'variables'", "]", ".", "nil?", "||", "self", "[", "'variables'", "]", ".", "empty?", "# Builders", "packer", "[", "'builders'", "]", "=", "[", "]", "unless", "self", "[", "'builders'", "]", ".", "nil?", "||", "self", "[", "'builders'", "]", ".", "empty?", "logger", ".", "info", "(", "\"Processing builders...\"", ")", "self", "[", "'builders'", "]", ".", "each", "do", "|", "name", ",", "config", "|", "logger", ".", "info", "(", "\"Processing builder: #{name} with type: #{config['type']}\"", ")", "# Get the builder for this config", "builder", "=", "get_builder", "(", "config", "[", "'type'", "]", ")", "# Have the builder convert the config to packer format", "packer", "[", "'builders'", "]", "<<", "builder", ".", "to_packer", "(", "name", ",", "config", ".", "dup", ")", "end", "# Provisioners", "packer", "[", "'provisioners'", "]", "=", "[", "]", "unless", "self", "[", "'provisioners'", "]", ".", "nil?", "||", "self", "[", "'provisioners'", "]", ".", "empty?", "logger", ".", "info", "(", "\"Processing provisioners...\"", ")", "self", "[", "'provisioners'", "]", ".", "sort", ".", "map", "do", "|", "index", ",", "provisioners", "|", "provisioners", ".", "each", "do", "|", "name", ",", "config", "|", "logger", ".", "debug", "(", "\"Processing provisioner: #{name}\"", ")", "packer", "[", "'provisioners'", "]", "<<", "config", ".", "dup", "end", "end", "# Post-Processors", "packer", "[", "'post-processors'", "]", "=", "[", "]", "unless", "self", "[", "'postprocessors'", "]", ".", "nil?", "||", "self", "[", "'postprocessors'", "]", ".", "empty?", "logger", ".", "info", "(", "\"Processing post-processors...\"", ")", "self", "[", "'postprocessors'", "]", ".", "each", "do", "|", "name", ",", "config", "|", "logger", ".", "debug", "(", "\"Processing post-processor: #{name}\"", ")", "packer", "[", "'post-processors'", "]", "<<", "config", ".", "dup", "unless", "config", ".", "nil?", "end", "packer", "end" ]
This formats the template into packer format hash
[ "This", "formats", "the", "template", "into", "packer", "format", "hash" ]
78453d3d5e204486b1df99015ab1b2be821663f5
https://github.com/aspring/racker/blob/78453d3d5e204486b1df99015ab1b2be821663f5/lib/racker/template.rb#L21-L60
23,159
jarthod/survey-gizmo-ruby
lib/survey_gizmo/resource.rb
SurveyGizmo.Resource.route_params
def route_params params = { id: id } self.class.routes.values.each do |route| route.gsub(/:(\w+)/) do |m| m = m.delete(':').to_sym params[m] = self.send(m) end end params end
ruby
def route_params params = { id: id } self.class.routes.values.each do |route| route.gsub(/:(\w+)/) do |m| m = m.delete(':').to_sym params[m] = self.send(m) end end params end
[ "def", "route_params", "params", "=", "{", "id", ":", "id", "}", "self", ".", "class", ".", "routes", ".", "values", ".", "each", "do", "|", "route", "|", "route", ".", "gsub", "(", "/", "\\w", "/", ")", "do", "|", "m", "|", "m", "=", "m", ".", "delete", "(", "':'", ")", ".", "to_sym", "params", "[", "m", "]", "=", "self", ".", "send", "(", "m", ")", "end", "end", "params", "end" ]
Extract attributes required for API calls about this object
[ "Extract", "attributes", "required", "for", "API", "calls", "about", "this", "object" ]
757b91399b03bd5bf8d3e61b2224da5b77503a88
https://github.com/jarthod/survey-gizmo-ruby/blob/757b91399b03bd5bf8d3e61b2224da5b77503a88/lib/survey_gizmo/resource.rb#L173-L184
23,160
smalruby/smalruby
lib/smalruby/character.rb
Smalruby.Character.pen_color=
def pen_color=(val) if val.is_a?(Numeric) val %= 201 _, s, l = Color.rgb_to_hsl(*pen_color) val = Color.hsl_to_rgb(val, s, l) end @pen_color = val end
ruby
def pen_color=(val) if val.is_a?(Numeric) val %= 201 _, s, l = Color.rgb_to_hsl(*pen_color) val = Color.hsl_to_rgb(val, s, l) end @pen_color = val end
[ "def", "pen_color", "=", "(", "val", ")", "if", "val", ".", "is_a?", "(", "Numeric", ")", "val", "%=", "201", "_", ",", "s", ",", "l", "=", "Color", ".", "rgb_to_hsl", "(", "pen_color", ")", "val", "=", "Color", ".", "hsl_to_rgb", "(", "val", ",", "s", ",", "l", ")", "end", "@pen_color", "=", "val", "end" ]
set pen color @param [Array<Integer>|Symbol|Integer] val color When color is Array<Integer>, it means [R, G, B]. When color is Symbol, it means the color code; like :white, :black, etc... When color is Integer, it means hue.
[ "set", "pen", "color" ]
859a5f0b503bc55a790fda38f2bce27414226ada
https://github.com/smalruby/smalruby/blob/859a5f0b503bc55a790fda38f2bce27414226ada/lib/smalruby/character.rb#L414-L421
23,161
smalruby/smalruby
lib/smalruby/character.rb
Smalruby.Character.change_pen_color_by
def change_pen_color_by(val) h, s, l = Color.rgb_to_hsl(*pen_color) @pen_color = Color.hsl_to_rgb(h + val, s, l) end
ruby
def change_pen_color_by(val) h, s, l = Color.rgb_to_hsl(*pen_color) @pen_color = Color.hsl_to_rgb(h + val, s, l) end
[ "def", "change_pen_color_by", "(", "val", ")", "h", ",", "s", ",", "l", "=", "Color", ".", "rgb_to_hsl", "(", "pen_color", ")", "@pen_color", "=", "Color", ".", "hsl_to_rgb", "(", "h", "+", "val", ",", "s", ",", "l", ")", "end" ]
change pen color @param [Integer] val color
[ "change", "pen", "color" ]
859a5f0b503bc55a790fda38f2bce27414226ada
https://github.com/smalruby/smalruby/blob/859a5f0b503bc55a790fda38f2bce27414226ada/lib/smalruby/character.rb#L426-L429
23,162
smalruby/smalruby
lib/smalruby/character.rb
Smalruby.Character.pen_shade=
def pen_shade=(val) val %= 101 h, s, = *Color.rgb_to_hsl(*pen_color) @pen_color = Color.hsl_to_rgb(h, s, val) end
ruby
def pen_shade=(val) val %= 101 h, s, = *Color.rgb_to_hsl(*pen_color) @pen_color = Color.hsl_to_rgb(h, s, val) end
[ "def", "pen_shade", "=", "(", "val", ")", "val", "%=", "101", "h", ",", "s", ",", "=", "Color", ".", "rgb_to_hsl", "(", "pen_color", ")", "@pen_color", "=", "Color", ".", "hsl_to_rgb", "(", "h", ",", "s", ",", "val", ")", "end" ]
set pen shade @param Integer val shade
[ "set", "pen", "shade" ]
859a5f0b503bc55a790fda38f2bce27414226ada
https://github.com/smalruby/smalruby/blob/859a5f0b503bc55a790fda38f2bce27414226ada/lib/smalruby/character.rb#L434-L438
23,163
sandipransing/rails_tiny_mce
plugins/will_paginate/lib/will_paginate/view_helpers.rb
WillPaginate.ViewHelpers.page_entries_info
def page_entries_info(collection, options = {}) entry_name = options[:entry_name] || (collection.empty?? 'entry' : collection.first.class.name.underscore.sub('_', ' ')) if collection.total_pages < 2 case collection.size when 0; "No #{entry_name.pluralize} found" when 1; "Displaying <b>1</b> #{entry_name}" else; "Displaying <b>all #{collection.size}</b> #{entry_name.pluralize}" end else %{Displaying #{entry_name.pluralize} <b>%d&nbsp;-&nbsp;%d</b> of <b>%d</b> in total} % [ collection.offset + 1, collection.offset + collection.length, collection.total_entries ] end end
ruby
def page_entries_info(collection, options = {}) entry_name = options[:entry_name] || (collection.empty?? 'entry' : collection.first.class.name.underscore.sub('_', ' ')) if collection.total_pages < 2 case collection.size when 0; "No #{entry_name.pluralize} found" when 1; "Displaying <b>1</b> #{entry_name}" else; "Displaying <b>all #{collection.size}</b> #{entry_name.pluralize}" end else %{Displaying #{entry_name.pluralize} <b>%d&nbsp;-&nbsp;%d</b> of <b>%d</b> in total} % [ collection.offset + 1, collection.offset + collection.length, collection.total_entries ] end end
[ "def", "page_entries_info", "(", "collection", ",", "options", "=", "{", "}", ")", "entry_name", "=", "options", "[", ":entry_name", "]", "||", "(", "collection", ".", "empty?", "?", "'entry'", ":", "collection", ".", "first", ".", "class", ".", "name", ".", "underscore", ".", "sub", "(", "'_'", ",", "' '", ")", ")", "if", "collection", ".", "total_pages", "<", "2", "case", "collection", ".", "size", "when", "0", ";", "\"No #{entry_name.pluralize} found\"", "when", "1", ";", "\"Displaying <b>1</b> #{entry_name}\"", "else", ";", "\"Displaying <b>all #{collection.size}</b> #{entry_name.pluralize}\"", "end", "else", "%{Displaying #{entry_name.pluralize} <b>%d&nbsp;-&nbsp;%d</b> of <b>%d</b> in total}", "%", "[", "collection", ".", "offset", "+", "1", ",", "collection", ".", "offset", "+", "collection", ".", "length", ",", "collection", ".", "total_entries", "]", "end", "end" ]
Renders a helpful message with numbers of displayed vs. total entries. You can use this as a blueprint for your own, similar helpers. <%= page_entries_info @posts %> #-> Displaying posts 6 - 10 of 26 in total By default, the message will use the humanized class name of objects in collection: for instance, "project types" for ProjectType models. Override this to your liking with the <tt>:entry_name</tt> parameter: <%= page_entries_info @posts, :entry_name => 'item' %> #-> Displaying items 6 - 10 of 26 in total
[ "Renders", "a", "helpful", "message", "with", "numbers", "of", "displayed", "vs", ".", "total", "entries", ".", "You", "can", "use", "this", "as", "a", "blueprint", "for", "your", "own", "similar", "helpers", "." ]
4e91040e62784061aa7cca37fd8a95a87df379ce
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/will_paginate/lib/will_paginate/view_helpers.rb#L150-L167
23,164
sandipransing/rails_tiny_mce
plugins/will_paginate/lib/will_paginate/view_helpers.rb
WillPaginate.LinkRenderer.to_html
def to_html links = @options[:page_links] ? windowed_links : [] # previous/next buttons links.unshift page_link_or_span(@collection.previous_page, 'disabled prev_page', @options[:prev_label]) links.push page_link_or_span(@collection.next_page, 'disabled next_page', @options[:next_label]) html = links.join(@options[:separator]) @options[:container] ? @template.content_tag(:div, html, html_attributes) : html end
ruby
def to_html links = @options[:page_links] ? windowed_links : [] # previous/next buttons links.unshift page_link_or_span(@collection.previous_page, 'disabled prev_page', @options[:prev_label]) links.push page_link_or_span(@collection.next_page, 'disabled next_page', @options[:next_label]) html = links.join(@options[:separator]) @options[:container] ? @template.content_tag(:div, html, html_attributes) : html end
[ "def", "to_html", "links", "=", "@options", "[", ":page_links", "]", "?", "windowed_links", ":", "[", "]", "# previous/next buttons", "links", ".", "unshift", "page_link_or_span", "(", "@collection", ".", "previous_page", ",", "'disabled prev_page'", ",", "@options", "[", ":prev_label", "]", ")", "links", ".", "push", "page_link_or_span", "(", "@collection", ".", "next_page", ",", "'disabled next_page'", ",", "@options", "[", ":next_label", "]", ")", "html", "=", "links", ".", "join", "(", "@options", "[", ":separator", "]", ")", "@options", "[", ":container", "]", "?", "@template", ".", "content_tag", "(", ":div", ",", "html", ",", "html_attributes", ")", ":", "html", "end" ]
Process it! This method returns the complete HTML string which contains pagination links. Feel free to subclass LinkRenderer and change this method as you see fit.
[ "Process", "it!", "This", "method", "returns", "the", "complete", "HTML", "string", "which", "contains", "pagination", "links", ".", "Feel", "free", "to", "subclass", "LinkRenderer", "and", "change", "this", "method", "as", "you", "see", "fit", "." ]
4e91040e62784061aa7cca37fd8a95a87df379ce
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/will_paginate/lib/will_paginate/view_helpers.rb#L214-L222
23,165
sandipransing/rails_tiny_mce
plugins/will_paginate/lib/will_paginate/view_helpers.rb
WillPaginate.LinkRenderer.html_attributes
def html_attributes return @html_attributes if @html_attributes @html_attributes = @options.except *(WillPaginate::ViewHelpers.pagination_options.keys - [:class]) # pagination of Post models will have the ID of "posts_pagination" if @options[:container] and @options[:id] === true @html_attributes[:id] = @collection.first.class.name.underscore.pluralize + '_pagination' end @html_attributes end
ruby
def html_attributes return @html_attributes if @html_attributes @html_attributes = @options.except *(WillPaginate::ViewHelpers.pagination_options.keys - [:class]) # pagination of Post models will have the ID of "posts_pagination" if @options[:container] and @options[:id] === true @html_attributes[:id] = @collection.first.class.name.underscore.pluralize + '_pagination' end @html_attributes end
[ "def", "html_attributes", "return", "@html_attributes", "if", "@html_attributes", "@html_attributes", "=", "@options", ".", "except", "(", "WillPaginate", "::", "ViewHelpers", ".", "pagination_options", ".", "keys", "-", "[", ":class", "]", ")", "# pagination of Post models will have the ID of \"posts_pagination\"", "if", "@options", "[", ":container", "]", "and", "@options", "[", ":id", "]", "===", "true", "@html_attributes", "[", ":id", "]", "=", "@collection", ".", "first", ".", "class", ".", "name", ".", "underscore", ".", "pluralize", "+", "'_pagination'", "end", "@html_attributes", "end" ]
Returns the subset of +options+ this instance was initialized with that represent HTML attributes for the container element of pagination links.
[ "Returns", "the", "subset", "of", "+", "options", "+", "this", "instance", "was", "initialized", "with", "that", "represent", "HTML", "attributes", "for", "the", "container", "element", "of", "pagination", "links", "." ]
4e91040e62784061aa7cca37fd8a95a87df379ce
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/will_paginate/lib/will_paginate/view_helpers.rb#L226-L234
23,166
sandipransing/rails_tiny_mce
plugins/will_paginate/lib/will_paginate/view_helpers.rb
WillPaginate.LinkRenderer.windowed_links
def windowed_links prev = nil visible_page_numbers.inject [] do |links, n| # detect gaps: links << gap_marker if prev and n > prev + 1 links << page_link_or_span(n, 'current') prev = n links end end
ruby
def windowed_links prev = nil visible_page_numbers.inject [] do |links, n| # detect gaps: links << gap_marker if prev and n > prev + 1 links << page_link_or_span(n, 'current') prev = n links end end
[ "def", "windowed_links", "prev", "=", "nil", "visible_page_numbers", ".", "inject", "[", "]", "do", "|", "links", ",", "n", "|", "# detect gaps:", "links", "<<", "gap_marker", "if", "prev", "and", "n", ">", "prev", "+", "1", "links", "<<", "page_link_or_span", "(", "n", ",", "'current'", ")", "prev", "=", "n", "links", "end", "end" ]
Collects link items for visible page numbers.
[ "Collects", "link", "items", "for", "visible", "page", "numbers", "." ]
4e91040e62784061aa7cca37fd8a95a87df379ce
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/will_paginate/lib/will_paginate/view_helpers.rb#L239-L249
23,167
sandipransing/rails_tiny_mce
plugins/will_paginate/lib/will_paginate/view_helpers.rb
WillPaginate.LinkRenderer.stringified_merge
def stringified_merge(target, other) other.each do |key, value| key = key.to_s # this line is what it's all about! existing = target[key] if value.is_a?(Hash) and (existing.is_a?(Hash) or existing.nil?) stringified_merge(existing || (target[key] = {}), value) else target[key] = value end end end
ruby
def stringified_merge(target, other) other.each do |key, value| key = key.to_s # this line is what it's all about! existing = target[key] if value.is_a?(Hash) and (existing.is_a?(Hash) or existing.nil?) stringified_merge(existing || (target[key] = {}), value) else target[key] = value end end end
[ "def", "stringified_merge", "(", "target", ",", "other", ")", "other", ".", "each", "do", "|", "key", ",", "value", "|", "key", "=", "key", ".", "to_s", "# this line is what it's all about!", "existing", "=", "target", "[", "key", "]", "if", "value", ".", "is_a?", "(", "Hash", ")", "and", "(", "existing", ".", "is_a?", "(", "Hash", ")", "or", "existing", ".", "nil?", ")", "stringified_merge", "(", "existing", "||", "(", "target", "[", "key", "]", "=", "{", "}", ")", ",", "value", ")", "else", "target", "[", "key", "]", "=", "value", "end", "end", "end" ]
Recursively merge into target hash by using stringified keys from the other one
[ "Recursively", "merge", "into", "target", "hash", "by", "using", "stringified", "keys", "from", "the", "other", "one" ]
4e91040e62784061aa7cca37fd8a95a87df379ce
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/will_paginate/lib/will_paginate/view_helpers.rb#L360-L371
23,168
drewtempelmeyer/tax_cloud
lib/tax_cloud/tax_code_group.rb
TaxCloud.TaxCodeGroup.tax_codes
def tax_codes @tax_codes ||= begin response = TaxCloud.client.request :get_ti_cs_by_group, tic_group: group_id tax_codes = TaxCloud::Responses::TaxCodesByGroup.parse response Hash[tax_codes.map { |tic| [tic.ticid, tic] }] end end
ruby
def tax_codes @tax_codes ||= begin response = TaxCloud.client.request :get_ti_cs_by_group, tic_group: group_id tax_codes = TaxCloud::Responses::TaxCodesByGroup.parse response Hash[tax_codes.map { |tic| [tic.ticid, tic] }] end end
[ "def", "tax_codes", "@tax_codes", "||=", "begin", "response", "=", "TaxCloud", ".", "client", ".", "request", ":get_ti_cs_by_group", ",", "tic_group", ":", "group_id", "tax_codes", "=", "TaxCloud", "::", "Responses", "::", "TaxCodesByGroup", ".", "parse", "response", "Hash", "[", "tax_codes", ".", "map", "{", "|", "tic", "|", "[", "tic", ".", "ticid", ",", "tic", "]", "}", "]", "end", "end" ]
All Tax Codes in this group.
[ "All", "Tax", "Codes", "in", "this", "group", "." ]
ace4fae5586bc993e10a39989efbd048849ecad0
https://github.com/drewtempelmeyer/tax_cloud/blob/ace4fae5586bc993e10a39989efbd048849ecad0/lib/tax_cloud/tax_code_group.rb#L12-L18
23,169
drewtempelmeyer/tax_cloud
lib/tax_cloud/transaction.rb
TaxCloud.Transaction.authorized
def authorized(options = {}) options = { date_authorized: Date.today }.merge(options) request_params = { 'customerID' => customer_id, 'cartID' => cart_id, 'orderID' => order_id, 'dateAuthorized' => xml_date(options[:date_authorized]) } response = TaxCloud.client.request :authorized, request_params TaxCloud::Responses::Authorized.parse response end
ruby
def authorized(options = {}) options = { date_authorized: Date.today }.merge(options) request_params = { 'customerID' => customer_id, 'cartID' => cart_id, 'orderID' => order_id, 'dateAuthorized' => xml_date(options[:date_authorized]) } response = TaxCloud.client.request :authorized, request_params TaxCloud::Responses::Authorized.parse response end
[ "def", "authorized", "(", "options", "=", "{", "}", ")", "options", "=", "{", "date_authorized", ":", "Date", ".", "today", "}", ".", "merge", "(", "options", ")", "request_params", "=", "{", "'customerID'", "=>", "customer_id", ",", "'cartID'", "=>", "cart_id", ",", "'orderID'", "=>", "order_id", ",", "'dateAuthorized'", "=>", "xml_date", "(", "options", "[", ":date_authorized", "]", ")", "}", "response", "=", "TaxCloud", ".", "client", ".", "request", ":authorized", ",", "request_params", "TaxCloud", "::", "Responses", "::", "Authorized", ".", "parse", "response", "end" ]
Once a purchase has been made and payment has been authorized, this method must be called. A matching Lookup call must have been made before this is called. === Options * <tt>date_authorized</tt> - The date the transaction was authorized. Default is today.
[ "Once", "a", "purchase", "has", "been", "made", "and", "payment", "has", "been", "authorized", "this", "method", "must", "be", "called", ".", "A", "matching", "Lookup", "call", "must", "have", "been", "made", "before", "this", "is", "called", "." ]
ace4fae5586bc993e10a39989efbd048849ecad0
https://github.com/drewtempelmeyer/tax_cloud/blob/ace4fae5586bc993e10a39989efbd048849ecad0/lib/tax_cloud/transaction.rb#L46-L58
23,170
drewtempelmeyer/tax_cloud
lib/tax_cloud/transaction.rb
TaxCloud.Transaction.returned
def returned(options = {}) options = { returned_date: Date.today }.merge(options) request_params = { 'orderID' => order_id, 'cartItems' => { 'CartItem' => cart_items.map(&:to_hash) }, 'returnedDate' => xml_date(options[:returned_date]) } response = TaxCloud.client.request :returned, request_params TaxCloud::Responses::Returned.parse response end
ruby
def returned(options = {}) options = { returned_date: Date.today }.merge(options) request_params = { 'orderID' => order_id, 'cartItems' => { 'CartItem' => cart_items.map(&:to_hash) }, 'returnedDate' => xml_date(options[:returned_date]) } response = TaxCloud.client.request :returned, request_params TaxCloud::Responses::Returned.parse response end
[ "def", "returned", "(", "options", "=", "{", "}", ")", "options", "=", "{", "returned_date", ":", "Date", ".", "today", "}", ".", "merge", "(", "options", ")", "request_params", "=", "{", "'orderID'", "=>", "order_id", ",", "'cartItems'", "=>", "{", "'CartItem'", "=>", "cart_items", ".", "map", "(", ":to_hash", ")", "}", ",", "'returnedDate'", "=>", "xml_date", "(", "options", "[", ":returned_date", "]", ")", "}", "response", "=", "TaxCloud", ".", "client", ".", "request", ":returned", ",", "request_params", "TaxCloud", "::", "Responses", "::", "Returned", ".", "parse", "response", "end" ]
Marks any included cart items as returned. === Options [returned_date] The date the return occured. Default is today.
[ "Marks", "any", "included", "cart", "items", "as", "returned", "." ]
ace4fae5586bc993e10a39989efbd048849ecad0
https://github.com/drewtempelmeyer/tax_cloud/blob/ace4fae5586bc993e10a39989efbd048849ecad0/lib/tax_cloud/transaction.rb#L100-L110
23,171
sandipransing/rails_tiny_mce
plugins/paperclip/lib/paperclip/geometry.rb
Paperclip.Geometry.to_s
def to_s s = "" s << width.to_i.to_s if width > 0 s << "x#{height.to_i}" if height > 0 s << modifier.to_s s end
ruby
def to_s s = "" s << width.to_i.to_s if width > 0 s << "x#{height.to_i}" if height > 0 s << modifier.to_s s end
[ "def", "to_s", "s", "=", "\"\"", "s", "<<", "width", ".", "to_i", ".", "to_s", "if", "width", ">", "0", "s", "<<", "\"x#{height.to_i}\"", "if", "height", ">", "0", "s", "<<", "modifier", ".", "to_s", "s", "end" ]
Returns the width and height in a format suitable to be passed to Geometry.parse
[ "Returns", "the", "width", "and", "height", "in", "a", "format", "suitable", "to", "be", "passed", "to", "Geometry", ".", "parse" ]
4e91040e62784061aa7cca37fd8a95a87df379ce
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/lib/paperclip/geometry.rb#L65-L71
23,172
sandipransing/rails_tiny_mce
plugins/paperclip/shoulda_macros/paperclip.rb
Paperclip.Shoulda.should_have_attached_file
def should_have_attached_file name klass = self.name.gsub(/Test$/, '').constantize matcher = have_attached_file name should matcher.description do assert_accepts(matcher, klass) end end
ruby
def should_have_attached_file name klass = self.name.gsub(/Test$/, '').constantize matcher = have_attached_file name should matcher.description do assert_accepts(matcher, klass) end end
[ "def", "should_have_attached_file", "name", "klass", "=", "self", ".", "name", ".", "gsub", "(", "/", "/", ",", "''", ")", ".", "constantize", "matcher", "=", "have_attached_file", "name", "should", "matcher", ".", "description", "do", "assert_accepts", "(", "matcher", ",", "klass", ")", "end", "end" ]
This will test whether you have defined your attachment correctly by checking for all the required fields exist after the definition of the attachment.
[ "This", "will", "test", "whether", "you", "have", "defined", "your", "attachment", "correctly", "by", "checking", "for", "all", "the", "required", "fields", "exist", "after", "the", "definition", "of", "the", "attachment", "." ]
4e91040e62784061aa7cca37fd8a95a87df379ce
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/shoulda_macros/paperclip.rb#L16-L22
23,173
sandipransing/rails_tiny_mce
plugins/paperclip/shoulda_macros/paperclip.rb
Paperclip.Shoulda.should_validate_attachment_presence
def should_validate_attachment_presence name klass = self.name.gsub(/Test$/, '').constantize matcher = validate_attachment_presence name should matcher.description do assert_accepts(matcher, klass) end end
ruby
def should_validate_attachment_presence name klass = self.name.gsub(/Test$/, '').constantize matcher = validate_attachment_presence name should matcher.description do assert_accepts(matcher, klass) end end
[ "def", "should_validate_attachment_presence", "name", "klass", "=", "self", ".", "name", ".", "gsub", "(", "/", "/", ",", "''", ")", ".", "constantize", "matcher", "=", "validate_attachment_presence", "name", "should", "matcher", ".", "description", "do", "assert_accepts", "(", "matcher", ",", "klass", ")", "end", "end" ]
Tests for validations on the presence of the attachment.
[ "Tests", "for", "validations", "on", "the", "presence", "of", "the", "attachment", "." ]
4e91040e62784061aa7cca37fd8a95a87df379ce
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/shoulda_macros/paperclip.rb#L25-L31
23,174
sandipransing/rails_tiny_mce
plugins/paperclip/shoulda_macros/paperclip.rb
Paperclip.Shoulda.stub_paperclip_s3
def stub_paperclip_s3(model, attachment, extension) definition = model.gsub(" ", "_").classify.constantize. attachment_definitions[attachment.to_sym] path = "http://s3.amazonaws.com/:id/#{definition[:path]}" path.gsub!(/:([^\/\.]+)/) do |match| "([^\/\.]+)" end begin FakeWeb.register_uri(:put, Regexp.new(path), :body => "OK") rescue NameError raise NameError, "the stub_paperclip_s3 shoulda macro requires the fakeweb gem." end end
ruby
def stub_paperclip_s3(model, attachment, extension) definition = model.gsub(" ", "_").classify.constantize. attachment_definitions[attachment.to_sym] path = "http://s3.amazonaws.com/:id/#{definition[:path]}" path.gsub!(/:([^\/\.]+)/) do |match| "([^\/\.]+)" end begin FakeWeb.register_uri(:put, Regexp.new(path), :body => "OK") rescue NameError raise NameError, "the stub_paperclip_s3 shoulda macro requires the fakeweb gem." end end
[ "def", "stub_paperclip_s3", "(", "model", ",", "attachment", ",", "extension", ")", "definition", "=", "model", ".", "gsub", "(", "\" \"", ",", "\"_\"", ")", ".", "classify", ".", "constantize", ".", "attachment_definitions", "[", "attachment", ".", "to_sym", "]", "path", "=", "\"http://s3.amazonaws.com/:id/#{definition[:path]}\"", "path", ".", "gsub!", "(", "/", "\\/", "\\.", "/", ")", "do", "|", "match", "|", "\"([^\\/\\.]+)\"", "end", "begin", "FakeWeb", ".", "register_uri", "(", ":put", ",", "Regexp", ".", "new", "(", "path", ")", ",", ":body", "=>", "\"OK\"", ")", "rescue", "NameError", "raise", "NameError", ",", "\"the stub_paperclip_s3 shoulda macro requires the fakeweb gem.\"", "end", "end" ]
Stubs the HTTP PUT for an attachment using S3 storage. @example stub_paperclip_s3('user', 'avatar', 'png')
[ "Stubs", "the", "HTTP", "PUT", "for", "an", "attachment", "using", "S3", "storage", "." ]
4e91040e62784061aa7cca37fd8a95a87df379ce
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/shoulda_macros/paperclip.rb#L68-L82
23,175
RestlessThinker/danger-jira
lib/jira/plugin.rb
Danger.DangerJira.check
def check(key: nil, url: nil, emoji: ":link:", search_title: true, search_commits: false, fail_on_warning: false, report_missing: true, skippable: true) throw Error("'key' missing - must supply JIRA issue key") if key.nil? throw Error("'url' missing - must supply JIRA installation URL") if url.nil? return if skippable && should_skip_jira?(search_title: search_title) jira_issues = find_jira_issues( key: key, search_title: search_title, search_commits: search_commits ) if !jira_issues.empty? jira_urls = jira_issues.map { |issue| link(href: ensure_url_ends_with_slash(url), issue: issue) }.join(", ") message("#{emoji} #{jira_urls}") elsif report_missing msg = "This PR does not contain any JIRA issue keys in the PR title or commit messages (e.g. KEY-123)" if fail_on_warning fail(msg) else warn(msg) end end end
ruby
def check(key: nil, url: nil, emoji: ":link:", search_title: true, search_commits: false, fail_on_warning: false, report_missing: true, skippable: true) throw Error("'key' missing - must supply JIRA issue key") if key.nil? throw Error("'url' missing - must supply JIRA installation URL") if url.nil? return if skippable && should_skip_jira?(search_title: search_title) jira_issues = find_jira_issues( key: key, search_title: search_title, search_commits: search_commits ) if !jira_issues.empty? jira_urls = jira_issues.map { |issue| link(href: ensure_url_ends_with_slash(url), issue: issue) }.join(", ") message("#{emoji} #{jira_urls}") elsif report_missing msg = "This PR does not contain any JIRA issue keys in the PR title or commit messages (e.g. KEY-123)" if fail_on_warning fail(msg) else warn(msg) end end end
[ "def", "check", "(", "key", ":", "nil", ",", "url", ":", "nil", ",", "emoji", ":", "\":link:\"", ",", "search_title", ":", "true", ",", "search_commits", ":", "false", ",", "fail_on_warning", ":", "false", ",", "report_missing", ":", "true", ",", "skippable", ":", "true", ")", "throw", "Error", "(", "\"'key' missing - must supply JIRA issue key\"", ")", "if", "key", ".", "nil?", "throw", "Error", "(", "\"'url' missing - must supply JIRA installation URL\"", ")", "if", "url", ".", "nil?", "return", "if", "skippable", "&&", "should_skip_jira?", "(", "search_title", ":", "search_title", ")", "jira_issues", "=", "find_jira_issues", "(", "key", ":", "key", ",", "search_title", ":", "search_title", ",", "search_commits", ":", "search_commits", ")", "if", "!", "jira_issues", ".", "empty?", "jira_urls", "=", "jira_issues", ".", "map", "{", "|", "issue", "|", "link", "(", "href", ":", "ensure_url_ends_with_slash", "(", "url", ")", ",", "issue", ":", "issue", ")", "}", ".", "join", "(", "\", \"", ")", "message", "(", "\"#{emoji} #{jira_urls}\"", ")", "elsif", "report_missing", "msg", "=", "\"This PR does not contain any JIRA issue keys in the PR title or commit messages (e.g. KEY-123)\"", "if", "fail_on_warning", "fail", "(", "msg", ")", "else", "warn", "(", "msg", ")", "end", "end", "end" ]
Checks PR for JIRA keys and links them @param [Array] key An array of JIRA project keys KEY-123, JIRA-125 etc. @param [String] url The JIRA url hosted instance. @param [String] emoji The emoji you want to display in the message. @param [Boolean] search_title Option to search JIRA issues from PR title @param [Boolean] search_commits Option to search JIRA issues from commit messages @param [Boolean] fail_on_warning Option to fail danger if no JIRA issue found @param [Boolean] report_missing Option to report if no JIRA issue was found @param [Boolean] skippable Option to skip the report if 'no-jira' is provided on the PR title, description or commits @return [void]
[ "Checks", "PR", "for", "JIRA", "keys", "and", "links", "them" ]
47413c0c46e44cba024e9ff5999620f621eb8c49
https://github.com/RestlessThinker/danger-jira/blob/47413c0c46e44cba024e9ff5999620f621eb8c49/lib/jira/plugin.rb#L40-L63
23,176
sandipransing/rails_tiny_mce
plugins/paperclip/lib/paperclip/thumbnail.rb
Paperclip.Thumbnail.make
def make src = @file dst = Tempfile.new([@basename, @format ? ".#{@format}" : '']) dst.binmode begin parameters = [] parameters << source_file_options parameters << ":source" parameters << transformation_command parameters << convert_options parameters << ":dest" parameters = parameters.flatten.compact.join(" ").strip.squeeze(" ") success = Paperclip.run("convert", parameters, :source => "#{File.expand_path(src.path)}[0]", :dest => File.expand_path(dst.path)) rescue PaperclipCommandLineError => e raise PaperclipError, "There was an error processing the thumbnail for #{@basename}" if @whiny end dst end
ruby
def make src = @file dst = Tempfile.new([@basename, @format ? ".#{@format}" : '']) dst.binmode begin parameters = [] parameters << source_file_options parameters << ":source" parameters << transformation_command parameters << convert_options parameters << ":dest" parameters = parameters.flatten.compact.join(" ").strip.squeeze(" ") success = Paperclip.run("convert", parameters, :source => "#{File.expand_path(src.path)}[0]", :dest => File.expand_path(dst.path)) rescue PaperclipCommandLineError => e raise PaperclipError, "There was an error processing the thumbnail for #{@basename}" if @whiny end dst end
[ "def", "make", "src", "=", "@file", "dst", "=", "Tempfile", ".", "new", "(", "[", "@basename", ",", "@format", "?", "\".#{@format}\"", ":", "''", "]", ")", "dst", ".", "binmode", "begin", "parameters", "=", "[", "]", "parameters", "<<", "source_file_options", "parameters", "<<", "\":source\"", "parameters", "<<", "transformation_command", "parameters", "<<", "convert_options", "parameters", "<<", "\":dest\"", "parameters", "=", "parameters", ".", "flatten", ".", "compact", ".", "join", "(", "\" \"", ")", ".", "strip", ".", "squeeze", "(", "\" \"", ")", "success", "=", "Paperclip", ".", "run", "(", "\"convert\"", ",", "parameters", ",", ":source", "=>", "\"#{File.expand_path(src.path)}[0]\"", ",", ":dest", "=>", "File", ".", "expand_path", "(", "dst", ".", "path", ")", ")", "rescue", "PaperclipCommandLineError", "=>", "e", "raise", "PaperclipError", ",", "\"There was an error processing the thumbnail for #{@basename}\"", "if", "@whiny", "end", "dst", "end" ]
Performs the conversion of the +file+ into a thumbnail. Returns the Tempfile that contains the new image.
[ "Performs", "the", "conversion", "of", "the", "+", "file", "+", "into", "a", "thumbnail", ".", "Returns", "the", "Tempfile", "that", "contains", "the", "new", "image", "." ]
4e91040e62784061aa7cca37fd8a95a87df379ce
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/lib/paperclip/thumbnail.rb#L46-L67
23,177
sandipransing/rails_tiny_mce
plugins/paperclip/lib/paperclip/thumbnail.rb
Paperclip.Thumbnail.transformation_command
def transformation_command scale, crop = @current_geometry.transformation_to(@target_geometry, crop?) trans = [] trans << "-resize" << %["#{scale}"] unless scale.nil? || scale.empty? trans << "-crop" << %["#{crop}"] << "+repage" if crop trans end
ruby
def transformation_command scale, crop = @current_geometry.transformation_to(@target_geometry, crop?) trans = [] trans << "-resize" << %["#{scale}"] unless scale.nil? || scale.empty? trans << "-crop" << %["#{crop}"] << "+repage" if crop trans end
[ "def", "transformation_command", "scale", ",", "crop", "=", "@current_geometry", ".", "transformation_to", "(", "@target_geometry", ",", "crop?", ")", "trans", "=", "[", "]", "trans", "<<", "\"-resize\"", "<<", "%[\"#{scale}\"]", "unless", "scale", ".", "nil?", "||", "scale", ".", "empty?", "trans", "<<", "\"-crop\"", "<<", "%[\"#{crop}\"]", "<<", "\"+repage\"", "if", "crop", "trans", "end" ]
Returns the command ImageMagick's +convert+ needs to transform the image into the thumbnail.
[ "Returns", "the", "command", "ImageMagick", "s", "+", "convert", "+", "needs", "to", "transform", "the", "image", "into", "the", "thumbnail", "." ]
4e91040e62784061aa7cca37fd8a95a87df379ce
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/lib/paperclip/thumbnail.rb#L71-L77
23,178
kete/tiny_mce
lib/tiny_mce/configuration.rb
TinyMCE.Configuration.add_options
def add_options(options = {}, raw_options = nil) @options.merge!(options.stringify_keys) unless options.blank? @raw_options << raw_options unless raw_options.blank? end
ruby
def add_options(options = {}, raw_options = nil) @options.merge!(options.stringify_keys) unless options.blank? @raw_options << raw_options unless raw_options.blank? end
[ "def", "add_options", "(", "options", "=", "{", "}", ",", "raw_options", "=", "nil", ")", "@options", ".", "merge!", "(", "options", ".", "stringify_keys", ")", "unless", "options", ".", "blank?", "@raw_options", "<<", "raw_options", "unless", "raw_options", ".", "blank?", "end" ]
Merge additional options and raw_options
[ "Merge", "additional", "options", "and", "raw_options" ]
49aa365c4256fc0702e3b1a02e1ddecfdbccd7b4
https://github.com/kete/tiny_mce/blob/49aa365c4256fc0702e3b1a02e1ddecfdbccd7b4/lib/tiny_mce/configuration.rb#L58-L61
23,179
kete/tiny_mce
lib/tiny_mce/configuration.rb
TinyMCE.Configuration.reverse_add_options
def reverse_add_options(options = {}, raw_options = nil) @options.reverse_merge!(options.stringify_keys) unless options.blank? @raw_options << raw_options unless raw_options.blank? end
ruby
def reverse_add_options(options = {}, raw_options = nil) @options.reverse_merge!(options.stringify_keys) unless options.blank? @raw_options << raw_options unless raw_options.blank? end
[ "def", "reverse_add_options", "(", "options", "=", "{", "}", ",", "raw_options", "=", "nil", ")", "@options", ".", "reverse_merge!", "(", "options", ".", "stringify_keys", ")", "unless", "options", ".", "blank?", "@raw_options", "<<", "raw_options", "unless", "raw_options", ".", "blank?", "end" ]
Merge additional options and raw_options, but don't overwrite existing
[ "Merge", "additional", "options", "and", "raw_options", "but", "don", "t", "overwrite", "existing" ]
49aa365c4256fc0702e3b1a02e1ddecfdbccd7b4
https://github.com/kete/tiny_mce/blob/49aa365c4256fc0702e3b1a02e1ddecfdbccd7b4/lib/tiny_mce/configuration.rb#L64-L67
23,180
sandipransing/rails_tiny_mce
plugins/paperclip/lib/paperclip/upfile.rb
Paperclip.Upfile.content_type
def content_type type = (self.path.match(/\.(\w+)$/)[1] rescue "octet-stream").downcase case type when %r"jp(e|g|eg)" then "image/jpeg" when %r"tiff?" then "image/tiff" when %r"png", "gif", "bmp" then "image/#{type}" when "txt" then "text/plain" when %r"html?" then "text/html" when "js" then "application/js" when "csv", "xml", "css" then "text/#{type}" else # On BSDs, `file` doesn't give a result code of 1 if the file doesn't exist. content_type = (Paperclip.run("file", "-b --mime-type :file", :file => self.path).split(':').last.strip rescue "application/x-#{type}") content_type = "application/x-#{type}" if content_type.match(/\(.*?\)/) content_type end end
ruby
def content_type type = (self.path.match(/\.(\w+)$/)[1] rescue "octet-stream").downcase case type when %r"jp(e|g|eg)" then "image/jpeg" when %r"tiff?" then "image/tiff" when %r"png", "gif", "bmp" then "image/#{type}" when "txt" then "text/plain" when %r"html?" then "text/html" when "js" then "application/js" when "csv", "xml", "css" then "text/#{type}" else # On BSDs, `file` doesn't give a result code of 1 if the file doesn't exist. content_type = (Paperclip.run("file", "-b --mime-type :file", :file => self.path).split(':').last.strip rescue "application/x-#{type}") content_type = "application/x-#{type}" if content_type.match(/\(.*?\)/) content_type end end
[ "def", "content_type", "type", "=", "(", "self", ".", "path", ".", "match", "(", "/", "\\.", "\\w", "/", ")", "[", "1", "]", "rescue", "\"octet-stream\"", ")", ".", "downcase", "case", "type", "when", "%r\"", "\"", "then", "\"image/jpeg\"", "when", "%r\"", "\"", "then", "\"image/tiff\"", "when", "%r\"", "\"", ",", "\"gif\"", ",", "\"bmp\"", "then", "\"image/#{type}\"", "when", "\"txt\"", "then", "\"text/plain\"", "when", "%r\"", "\"", "then", "\"text/html\"", "when", "\"js\"", "then", "\"application/js\"", "when", "\"csv\"", ",", "\"xml\"", ",", "\"css\"", "then", "\"text/#{type}\"", "else", "# On BSDs, `file` doesn't give a result code of 1 if the file doesn't exist.", "content_type", "=", "(", "Paperclip", ".", "run", "(", "\"file\"", ",", "\"-b --mime-type :file\"", ",", ":file", "=>", "self", ".", "path", ")", ".", "split", "(", "':'", ")", ".", "last", ".", "strip", "rescue", "\"application/x-#{type}\"", ")", "content_type", "=", "\"application/x-#{type}\"", "if", "content_type", ".", "match", "(", "/", "\\(", "\\)", "/", ")", "content_type", "end", "end" ]
Infer the MIME-type of the file from the extension.
[ "Infer", "the", "MIME", "-", "type", "of", "the", "file", "from", "the", "extension", "." ]
4e91040e62784061aa7cca37fd8a95a87df379ce
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/lib/paperclip/upfile.rb#L8-L24
23,181
tario/shikashi
lib/shikashi/sandbox.rb
Shikashi.Sandbox.packet
def packet(*args) code = args.pick(String,:code) base_namespace = args.pick(:base_namespace) do nil end no_base_namespace = args.pick(:no_base_namespace) do @no_base_namespace end privileges_ = args.pick(Privileges,:privileges) do Privileges.new end encoding = get_source_encoding(code) || args.pick(:encoding) do nil end hook_handler = nil if base_namespace hook_handler = instantiate_evalhook_handler hook_handler.base_namespace = base_namespace hook_handler.sandbox = self else hook_handler = @hook_handler base_namespace = hook_handler.base_namespace end source = args.pick(:source) do generate_id end self.privileges[source] = privileges_ code = "nil;\n " + code unless no_base_namespace if (eval(base_namespace.to_s).instance_of? Module) code = "module #{base_namespace}\n #{code}\n end\n" else code = "class #{base_namespace}\n #{code}\n end\n" end end if encoding code = "# encoding: #{encoding}\n" + code end evalhook_packet = @hook_handler.packet(code) Shikashi::Sandbox::Packet.new(evalhook_packet, privileges_, source) end
ruby
def packet(*args) code = args.pick(String,:code) base_namespace = args.pick(:base_namespace) do nil end no_base_namespace = args.pick(:no_base_namespace) do @no_base_namespace end privileges_ = args.pick(Privileges,:privileges) do Privileges.new end encoding = get_source_encoding(code) || args.pick(:encoding) do nil end hook_handler = nil if base_namespace hook_handler = instantiate_evalhook_handler hook_handler.base_namespace = base_namespace hook_handler.sandbox = self else hook_handler = @hook_handler base_namespace = hook_handler.base_namespace end source = args.pick(:source) do generate_id end self.privileges[source] = privileges_ code = "nil;\n " + code unless no_base_namespace if (eval(base_namespace.to_s).instance_of? Module) code = "module #{base_namespace}\n #{code}\n end\n" else code = "class #{base_namespace}\n #{code}\n end\n" end end if encoding code = "# encoding: #{encoding}\n" + code end evalhook_packet = @hook_handler.packet(code) Shikashi::Sandbox::Packet.new(evalhook_packet, privileges_, source) end
[ "def", "packet", "(", "*", "args", ")", "code", "=", "args", ".", "pick", "(", "String", ",", ":code", ")", "base_namespace", "=", "args", ".", "pick", "(", ":base_namespace", ")", "do", "nil", "end", "no_base_namespace", "=", "args", ".", "pick", "(", ":no_base_namespace", ")", "do", "@no_base_namespace", "end", "privileges_", "=", "args", ".", "pick", "(", "Privileges", ",", ":privileges", ")", "do", "Privileges", ".", "new", "end", "encoding", "=", "get_source_encoding", "(", "code", ")", "||", "args", ".", "pick", "(", ":encoding", ")", "do", "nil", "end", "hook_handler", "=", "nil", "if", "base_namespace", "hook_handler", "=", "instantiate_evalhook_handler", "hook_handler", ".", "base_namespace", "=", "base_namespace", "hook_handler", ".", "sandbox", "=", "self", "else", "hook_handler", "=", "@hook_handler", "base_namespace", "=", "hook_handler", ".", "base_namespace", "end", "source", "=", "args", ".", "pick", "(", ":source", ")", "do", "generate_id", "end", "self", ".", "privileges", "[", "source", "]", "=", "privileges_", "code", "=", "\"nil;\\n \"", "+", "code", "unless", "no_base_namespace", "if", "(", "eval", "(", "base_namespace", ".", "to_s", ")", ".", "instance_of?", "Module", ")", "code", "=", "\"module #{base_namespace}\\n #{code}\\n end\\n\"", "else", "code", "=", "\"class #{base_namespace}\\n #{code}\\n end\\n\"", "end", "end", "if", "encoding", "code", "=", "\"# encoding: #{encoding}\\n\"", "+", "code", "end", "evalhook_packet", "=", "@hook_handler", ".", "packet", "(", "code", ")", "Shikashi", "::", "Sandbox", "::", "Packet", ".", "new", "(", "evalhook_packet", ",", "privileges_", ",", "source", ")", "end" ]
Creates a packet of code with the given privileges to execute later as many times as neccessary (see examples) Arguments :code Mandatory argument of class String with the code to execute restricted in the sandbox :privileges Optional argument of class Shikashi::Sandbox::Privileges to indicate the restrictions of the code executed in the sandbox. The default is an empty Privileges (absolutly no permission) Must be of class Privileges or passed as hash_key (:privileges => privileges) :source Optional argument to indicate the "source name", (visible in the backtraces). Only can be specified as hash parameter :base_namespace Alternate module to contain all classes and constants defined by the unprivileged code if not specified, by default, the base_namespace is created with the sandbox itself :no_base_namespace Specify to do not use a base_namespace (default false, not recommended to change) :encoding Specify the encoding of source (example: "utf-8"), the encoding also can be specified on header like a ruby normal source file NOTE: arguments are the same as for Sandbox#run method, except for timeout and binding which can be used when calling Shikashi::Sandbox::Packet#run Example: require "rubygems" require "shikashi" include Shikashi sandbox = Sandbox.new privileges = Privileges.allow_method(:print) # this is equivallent to sandbox.run('print "hello world\n"') packet = sandbox.packet('print "hello world\n"', privileges) packet.run
[ "Creates", "a", "packet", "of", "code", "with", "the", "given", "privileges", "to", "execute", "later", "as", "many", "times", "as", "neccessary" ]
171e0687a42327fa702225e8ad0d321e578f0cb0
https://github.com/tario/shikashi/blob/171e0687a42327fa702225e8ad0d321e578f0cb0/lib/shikashi/sandbox.rb#L380-L417
23,182
drewtempelmeyer/tax_cloud
lib/tax_cloud/address.rb
TaxCloud.Address.verify
def verify params = to_hash.downcase_keys if TaxCloud.configuration.usps_username params = params.merge( 'uspsUserID' => TaxCloud.configuration.usps_username ) end response = TaxCloud.client.request(:verify_address, params) TaxCloud::Responses::VerifyAddress.parse(response) end
ruby
def verify params = to_hash.downcase_keys if TaxCloud.configuration.usps_username params = params.merge( 'uspsUserID' => TaxCloud.configuration.usps_username ) end response = TaxCloud.client.request(:verify_address, params) TaxCloud::Responses::VerifyAddress.parse(response) end
[ "def", "verify", "params", "=", "to_hash", ".", "downcase_keys", "if", "TaxCloud", ".", "configuration", ".", "usps_username", "params", "=", "params", ".", "merge", "(", "'uspsUserID'", "=>", "TaxCloud", ".", "configuration", ".", "usps_username", ")", "end", "response", "=", "TaxCloud", ".", "client", ".", "request", "(", ":verify_address", ",", "params", ")", "TaxCloud", "::", "Responses", "::", "VerifyAddress", ".", "parse", "(", "response", ")", "end" ]
Verify this address. Returns a verified TaxCloud::Address.
[ "Verify", "this", "address", "." ]
ace4fae5586bc993e10a39989efbd048849ecad0
https://github.com/drewtempelmeyer/tax_cloud/blob/ace4fae5586bc993e10a39989efbd048849ecad0/lib/tax_cloud/address.rb#L20-L29
23,183
drewtempelmeyer/tax_cloud
lib/tax_cloud/address.rb
TaxCloud.Address.zip
def zip return nil unless zip5 && !zip5.empty? [zip5, zip4].select { |z| z && !z.empty? }.join('-') end
ruby
def zip return nil unless zip5 && !zip5.empty? [zip5, zip4].select { |z| z && !z.empty? }.join('-') end
[ "def", "zip", "return", "nil", "unless", "zip5", "&&", "!", "zip5", ".", "empty?", "[", "zip5", ",", "zip4", "]", ".", "select", "{", "|", "z", "|", "z", "&&", "!", "z", ".", "empty?", "}", ".", "join", "(", "'-'", ")", "end" ]
Complete zip code. Returns a 9-digit Zip Code, when available.
[ "Complete", "zip", "code", ".", "Returns", "a", "9", "-", "digit", "Zip", "Code", "when", "available", "." ]
ace4fae5586bc993e10a39989efbd048849ecad0
https://github.com/drewtempelmeyer/tax_cloud/blob/ace4fae5586bc993e10a39989efbd048849ecad0/lib/tax_cloud/address.rb#L33-L36
23,184
sandipransing/rails_tiny_mce
plugins/paperclip/lib/paperclip/style.rb
Paperclip.Style.processor_options
def processor_options args = {} @other_args.each do |k,v| args[k] = v.respond_to?(:call) ? v.call(attachment) : v end [:processors, :geometry, :format, :whiny, :convert_options].each do |k| (arg = send(k)) && args[k] = arg end args end
ruby
def processor_options args = {} @other_args.each do |k,v| args[k] = v.respond_to?(:call) ? v.call(attachment) : v end [:processors, :geometry, :format, :whiny, :convert_options].each do |k| (arg = send(k)) && args[k] = arg end args end
[ "def", "processor_options", "args", "=", "{", "}", "@other_args", ".", "each", "do", "|", "k", ",", "v", "|", "args", "[", "k", "]", "=", "v", ".", "respond_to?", "(", ":call", ")", "?", "v", ".", "call", "(", "attachment", ")", ":", "v", "end", "[", ":processors", ",", ":geometry", ",", ":format", ",", ":whiny", ",", ":convert_options", "]", ".", "each", "do", "|", "k", "|", "(", "arg", "=", "send", "(", "k", ")", ")", "&&", "args", "[", "k", "]", "=", "arg", "end", "args", "end" ]
Supplies the hash of options that processors expect to receive as their second argument Arguments other than the standard geometry, format etc are just passed through from initialization and any procs are called here, just before post-processing.
[ "Supplies", "the", "hash", "of", "options", "that", "processors", "expect", "to", "receive", "as", "their", "second", "argument", "Arguments", "other", "than", "the", "standard", "geometry", "format", "etc", "are", "just", "passed", "through", "from", "initialization", "and", "any", "procs", "are", "called", "here", "just", "before", "post", "-", "processing", "." ]
4e91040e62784061aa7cca37fd8a95a87df379ce
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/lib/paperclip/style.rb#L60-L69
23,185
sandipransing/rails_tiny_mce
plugins/paperclip/lib/paperclip/attachment.rb
Paperclip.Attachment.styles
def styles unless @normalized_styles @normalized_styles = {} (@styles.respond_to?(:call) ? @styles.call(self) : @styles).each do |name, args| @normalized_styles[name] = Paperclip::Style.new(name, args.dup, self) end end @normalized_styles end
ruby
def styles unless @normalized_styles @normalized_styles = {} (@styles.respond_to?(:call) ? @styles.call(self) : @styles).each do |name, args| @normalized_styles[name] = Paperclip::Style.new(name, args.dup, self) end end @normalized_styles end
[ "def", "styles", "unless", "@normalized_styles", "@normalized_styles", "=", "{", "}", "(", "@styles", ".", "respond_to?", "(", ":call", ")", "?", "@styles", ".", "call", "(", "self", ")", ":", "@styles", ")", ".", "each", "do", "|", "name", ",", "args", "|", "@normalized_styles", "[", "name", "]", "=", "Paperclip", "::", "Style", ".", "new", "(", "name", ",", "args", ".", "dup", ",", "self", ")", "end", "end", "@normalized_styles", "end" ]
Creates an Attachment object. +name+ is the name of the attachment, +instance+ is the ActiveRecord object instance it's attached to, and +options+ is the same as the hash passed to +has_attached_file+.
[ "Creates", "an", "Attachment", "object", ".", "+", "name", "+", "is", "the", "name", "of", "the", "attachment", "+", "instance", "+", "is", "the", "ActiveRecord", "object", "instance", "it", "s", "attached", "to", "and", "+", "options", "+", "is", "the", "same", "as", "the", "hash", "passed", "to", "+", "has_attached_file", "+", "." ]
4e91040e62784061aa7cca37fd8a95a87df379ce
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/lib/paperclip/attachment.rb#L57-L65
23,186
sandipransing/rails_tiny_mce
plugins/paperclip/lib/paperclip/attachment.rb
Paperclip.Attachment.url
def url(style_name = default_style, use_timestamp = @use_timestamp) url = original_filename.nil? ? interpolate(@default_url, style_name) : interpolate(@url, style_name) use_timestamp && updated_at ? [url, updated_at].compact.join(url.include?("?") ? "&" : "?") : url end
ruby
def url(style_name = default_style, use_timestamp = @use_timestamp) url = original_filename.nil? ? interpolate(@default_url, style_name) : interpolate(@url, style_name) use_timestamp && updated_at ? [url, updated_at].compact.join(url.include?("?") ? "&" : "?") : url end
[ "def", "url", "(", "style_name", "=", "default_style", ",", "use_timestamp", "=", "@use_timestamp", ")", "url", "=", "original_filename", ".", "nil?", "?", "interpolate", "(", "@default_url", ",", "style_name", ")", ":", "interpolate", "(", "@url", ",", "style_name", ")", "use_timestamp", "&&", "updated_at", "?", "[", "url", ",", "updated_at", "]", ".", "compact", ".", "join", "(", "url", ".", "include?", "(", "\"?\"", ")", "?", "\"&\"", ":", "\"?\"", ")", ":", "url", "end" ]
Returns the public URL of the attachment, with a given style. Note that this does not necessarily need to point to a file that your web server can access and can point to an action in your app, if you need fine grained security. This is not recommended if you don't need the security, however, for performance reasons. Set use_timestamp to false if you want to stop the attachment update time appended to the url
[ "Returns", "the", "public", "URL", "of", "the", "attachment", "with", "a", "given", "style", ".", "Note", "that", "this", "does", "not", "necessarily", "need", "to", "point", "to", "a", "file", "that", "your", "web", "server", "can", "access", "and", "can", "point", "to", "an", "action", "in", "your", "app", "if", "you", "need", "fine", "grained", "security", ".", "This", "is", "not", "recommended", "if", "you", "don", "t", "need", "the", "security", "however", "for", "performance", "reasons", ".", "Set", "use_timestamp", "to", "false", "if", "you", "want", "to", "stop", "the", "attachment", "update", "time", "appended", "to", "the", "url" ]
4e91040e62784061aa7cca37fd8a95a87df379ce
https://github.com/sandipransing/rails_tiny_mce/blob/4e91040e62784061aa7cca37fd8a95a87df379ce/plugins/paperclip/lib/paperclip/attachment.rb#L116-L119
23,187
rslifka/elasticity
lib/elasticity/emr.rb
Elasticity.EMR.add_tags
def add_tags(jobflow_id, tags) params = { :operation => 'AddTags', :resource_id => jobflow_id, :tags => tags } aws_result = @aws_request.submit(params) yield aws_result if block_given? end
ruby
def add_tags(jobflow_id, tags) params = { :operation => 'AddTags', :resource_id => jobflow_id, :tags => tags } aws_result = @aws_request.submit(params) yield aws_result if block_given? end
[ "def", "add_tags", "(", "jobflow_id", ",", "tags", ")", "params", "=", "{", ":operation", "=>", "'AddTags'", ",", ":resource_id", "=>", "jobflow_id", ",", ":tags", "=>", "tags", "}", "aws_result", "=", "@aws_request", ".", "submit", "(", "params", ")", "yield", "aws_result", "if", "block_given?", "end" ]
Sets the specified tags on all instances in the specified jobflow emr.add_tags('j-123', [{:key => 'key1', :value => 'value1'}, {:key => 'key_only2'}]) See http://docs.aws.amazon.com/ElasticMapReduce/latest/API/API_AddTags.html
[ "Sets", "the", "specified", "tags", "on", "all", "instances", "in", "the", "specified", "jobflow" ]
ee0a534b2c63ae0113aee5c85681ae4954703efb
https://github.com/rslifka/elasticity/blob/ee0a534b2c63ae0113aee5c85681ae4954703efb/lib/elasticity/emr.rb#L73-L81
23,188
rslifka/elasticity
lib/elasticity/emr.rb
Elasticity.EMR.describe_cluster
def describe_cluster(jobflow_id) params = { :operation => 'DescribeCluster', :cluster_id => jobflow_id, } aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
ruby
def describe_cluster(jobflow_id) params = { :operation => 'DescribeCluster', :cluster_id => jobflow_id, } aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
[ "def", "describe_cluster", "(", "jobflow_id", ")", "params", "=", "{", ":operation", "=>", "'DescribeCluster'", ",", ":cluster_id", "=>", "jobflow_id", ",", "}", "aws_result", "=", "@aws_request", ".", "submit", "(", "params", ")", "yield", "aws_result", "if", "block_given?", "JSON", ".", "parse", "(", "aws_result", ")", "end" ]
Provides details about the specified jobflow emr.describe_cluster('j-123') http://docs.aws.amazon.com/ElasticMapReduce/latest/API/API_DescribeCluster.html
[ "Provides", "details", "about", "the", "specified", "jobflow" ]
ee0a534b2c63ae0113aee5c85681ae4954703efb
https://github.com/rslifka/elasticity/blob/ee0a534b2c63ae0113aee5c85681ae4954703efb/lib/elasticity/emr.rb#L88-L96
23,189
rslifka/elasticity
lib/elasticity/emr.rb
Elasticity.EMR.describe_step
def describe_step(jobflow_id, step_id) params = { :operation => 'DescribeStep', :cluster_id => jobflow_id, :step_id => step_id } aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
ruby
def describe_step(jobflow_id, step_id) params = { :operation => 'DescribeStep', :cluster_id => jobflow_id, :step_id => step_id } aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
[ "def", "describe_step", "(", "jobflow_id", ",", "step_id", ")", "params", "=", "{", ":operation", "=>", "'DescribeStep'", ",", ":cluster_id", "=>", "jobflow_id", ",", ":step_id", "=>", "step_id", "}", "aws_result", "=", "@aws_request", ".", "submit", "(", "params", ")", "yield", "aws_result", "if", "block_given?", "JSON", ".", "parse", "(", "aws_result", ")", "end" ]
Provides details about the specified step within an existing jobflow emr.describe_step('j-123', 'step-456') http://docs.aws.amazon.com/ElasticMapReduce/latest/API/API_DescribeStep.html
[ "Provides", "details", "about", "the", "specified", "step", "within", "an", "existing", "jobflow" ]
ee0a534b2c63ae0113aee5c85681ae4954703efb
https://github.com/rslifka/elasticity/blob/ee0a534b2c63ae0113aee5c85681ae4954703efb/lib/elasticity/emr.rb#L103-L112
23,190
rslifka/elasticity
lib/elasticity/emr.rb
Elasticity.EMR.list_clusters
def list_clusters(options={}) params = { :operation => 'ListClusters' } params.merge!(:cluster_states => options[:states]) if options[:states] params.merge!(:created_before => options[:created_before].to_i) if options[:created_before] params.merge!(:created_after => options[:created_after].to_i) if options[:created_after] params.merge!(:marker => options[:marker]) if options[:marker] aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
ruby
def list_clusters(options={}) params = { :operation => 'ListClusters' } params.merge!(:cluster_states => options[:states]) if options[:states] params.merge!(:created_before => options[:created_before].to_i) if options[:created_before] params.merge!(:created_after => options[:created_after].to_i) if options[:created_after] params.merge!(:marker => options[:marker]) if options[:marker] aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
[ "def", "list_clusters", "(", "options", "=", "{", "}", ")", "params", "=", "{", ":operation", "=>", "'ListClusters'", "}", "params", ".", "merge!", "(", ":cluster_states", "=>", "options", "[", ":states", "]", ")", "if", "options", "[", ":states", "]", "params", ".", "merge!", "(", ":created_before", "=>", "options", "[", ":created_before", "]", ".", "to_i", ")", "if", "options", "[", ":created_before", "]", "params", ".", "merge!", "(", ":created_after", "=>", "options", "[", ":created_after", "]", ".", "to_i", ")", "if", "options", "[", ":created_after", "]", "params", ".", "merge!", "(", ":marker", "=>", "options", "[", ":marker", "]", ")", "if", "options", "[", ":marker", "]", "aws_result", "=", "@aws_request", ".", "submit", "(", "params", ")", "yield", "aws_result", "if", "block_given?", "JSON", ".", "parse", "(", "aws_result", ")", "end" ]
List the clusters given specified filtering emr.list_clusters({ :states => ['status1', 'status2', ...], :created_before => Time, # Amazon times are in UTC :created_after => Time, # Amazon times are in UTC :marker => 'marker' # Retrieve from a prior call to list_clusters }) http://docs.aws.amazon.com/ElasticMapReduce/latest/API/API_ListClusters.html
[ "List", "the", "clusters", "given", "specified", "filtering" ]
ee0a534b2c63ae0113aee5c85681ae4954703efb
https://github.com/rslifka/elasticity/blob/ee0a534b2c63ae0113aee5c85681ae4954703efb/lib/elasticity/emr.rb#L124-L135
23,191
rslifka/elasticity
lib/elasticity/emr.rb
Elasticity.EMR.list_instance_groups
def list_instance_groups(jobflow_id) params = { :operation => 'ListInstanceGroups', :cluster_id => jobflow_id, } aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
ruby
def list_instance_groups(jobflow_id) params = { :operation => 'ListInstanceGroups', :cluster_id => jobflow_id, } aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
[ "def", "list_instance_groups", "(", "jobflow_id", ")", "params", "=", "{", ":operation", "=>", "'ListInstanceGroups'", ",", ":cluster_id", "=>", "jobflow_id", ",", "}", "aws_result", "=", "@aws_request", ".", "submit", "(", "params", ")", "yield", "aws_result", "if", "block_given?", "JSON", ".", "parse", "(", "aws_result", ")", "end" ]
List the instance groups in the specified jobflow emr.list_instance_groups('j-123') http://docs.aws.amazon.com/ElasticMapReduce/latest/API/API_ListInstanceGroups.html
[ "List", "the", "instance", "groups", "in", "the", "specified", "jobflow" ]
ee0a534b2c63ae0113aee5c85681ae4954703efb
https://github.com/rslifka/elasticity/blob/ee0a534b2c63ae0113aee5c85681ae4954703efb/lib/elasticity/emr.rb#L163-L171
23,192
rslifka/elasticity
lib/elasticity/emr.rb
Elasticity.EMR.list_bootstrap_actions
def list_bootstrap_actions(jobflow_id) params = { :operation => 'ListBootstrapActions', :cluster_id => jobflow_id, } aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
ruby
def list_bootstrap_actions(jobflow_id) params = { :operation => 'ListBootstrapActions', :cluster_id => jobflow_id, } aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
[ "def", "list_bootstrap_actions", "(", "jobflow_id", ")", "params", "=", "{", ":operation", "=>", "'ListBootstrapActions'", ",", ":cluster_id", "=>", "jobflow_id", ",", "}", "aws_result", "=", "@aws_request", ".", "submit", "(", "params", ")", "yield", "aws_result", "if", "block_given?", "JSON", ".", "parse", "(", "aws_result", ")", "end" ]
List the bootstrap actions in the specified jobflow emr.list_bootstrap_actions('j-123') http://docs.aws.amazon.com/ElasticMapReduce/latest/API/API_ListBootstrapActions.html
[ "List", "the", "bootstrap", "actions", "in", "the", "specified", "jobflow" ]
ee0a534b2c63ae0113aee5c85681ae4954703efb
https://github.com/rslifka/elasticity/blob/ee0a534b2c63ae0113aee5c85681ae4954703efb/lib/elasticity/emr.rb#L178-L186
23,193
rslifka/elasticity
lib/elasticity/emr.rb
Elasticity.EMR.list_steps
def list_steps(jobflow_id, options={}) params = { :operation => 'ListSteps', :cluster_id => jobflow_id, } params.merge!(:step_ids => options[:step_ids]) if options[:step_ids] params.merge!(:step_states => options[:step_states]) if options[:step_states] params.merge!(:marker => options[:marker]) if options[:marker] aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
ruby
def list_steps(jobflow_id, options={}) params = { :operation => 'ListSteps', :cluster_id => jobflow_id, } params.merge!(:step_ids => options[:step_ids]) if options[:step_ids] params.merge!(:step_states => options[:step_states]) if options[:step_states] params.merge!(:marker => options[:marker]) if options[:marker] aws_result = @aws_request.submit(params) yield aws_result if block_given? JSON.parse(aws_result) end
[ "def", "list_steps", "(", "jobflow_id", ",", "options", "=", "{", "}", ")", "params", "=", "{", ":operation", "=>", "'ListSteps'", ",", ":cluster_id", "=>", "jobflow_id", ",", "}", "params", ".", "merge!", "(", ":step_ids", "=>", "options", "[", ":step_ids", "]", ")", "if", "options", "[", ":step_ids", "]", "params", ".", "merge!", "(", ":step_states", "=>", "options", "[", ":step_states", "]", ")", "if", "options", "[", ":step_states", "]", "params", ".", "merge!", "(", ":marker", "=>", "options", "[", ":marker", "]", ")", "if", "options", "[", ":marker", "]", "aws_result", "=", "@aws_request", ".", "submit", "(", "params", ")", "yield", "aws_result", "if", "block_given?", "JSON", ".", "parse", "(", "aws_result", ")", "end" ]
List the steps in a job flow given specified filtering emr.list_steps('j-123', { :types => ['MASTER', 'CORE', 'TASK'], :step_ids => ['ID-1', 'ID-2'] :step_states => ['PENDING', 'RUNNING', ...] :marker => 'marker' # Retrieve from a prior call to list_steps }) http://docs.aws.amazon.com/ElasticMapReduce/latest/API/API_ListSteps.html
[ "List", "the", "steps", "in", "a", "job", "flow", "given", "specified", "filtering" ]
ee0a534b2c63ae0113aee5c85681ae4954703efb
https://github.com/rslifka/elasticity/blob/ee0a534b2c63ae0113aee5c85681ae4954703efb/lib/elasticity/emr.rb#L198-L209
23,194
rslifka/elasticity
lib/elasticity/emr.rb
Elasticity.EMR.remove_tags
def remove_tags(jobflow_id, keys) params = { :operation => 'RemoveTags', :resource_id => jobflow_id, :tag_keys => keys } aws_result = @aws_request.submit(params) yield aws_result if block_given? end
ruby
def remove_tags(jobflow_id, keys) params = { :operation => 'RemoveTags', :resource_id => jobflow_id, :tag_keys => keys } aws_result = @aws_request.submit(params) yield aws_result if block_given? end
[ "def", "remove_tags", "(", "jobflow_id", ",", "keys", ")", "params", "=", "{", ":operation", "=>", "'RemoveTags'", ",", ":resource_id", "=>", "jobflow_id", ",", ":tag_keys", "=>", "keys", "}", "aws_result", "=", "@aws_request", ".", "submit", "(", "params", ")", "yield", "aws_result", "if", "block_given?", "end" ]
Remove the specified tags on all instances in the specified jobflow emr.remove_tags('j-123', ['key1','key_only2']) See http://docs.aws.amazon.com/ElasticMapReduce/latest/API/API_RemoveTags.html
[ "Remove", "the", "specified", "tags", "on", "all", "instances", "in", "the", "specified", "jobflow" ]
ee0a534b2c63ae0113aee5c85681ae4954703efb
https://github.com/rslifka/elasticity/blob/ee0a534b2c63ae0113aee5c85681ae4954703efb/lib/elasticity/emr.rb#L233-L241
23,195
rslifka/elasticity
lib/elasticity/emr.rb
Elasticity.EMR.set_termination_protection
def set_termination_protection(jobflow_ids, protection_enabled=true) params = { :operation => 'SetTerminationProtection', :termination_protected => protection_enabled, :job_flow_ids => jobflow_ids } aws_result = @aws_request.submit(params) yield aws_result if block_given? end
ruby
def set_termination_protection(jobflow_ids, protection_enabled=true) params = { :operation => 'SetTerminationProtection', :termination_protected => protection_enabled, :job_flow_ids => jobflow_ids } aws_result = @aws_request.submit(params) yield aws_result if block_given? end
[ "def", "set_termination_protection", "(", "jobflow_ids", ",", "protection_enabled", "=", "true", ")", "params", "=", "{", ":operation", "=>", "'SetTerminationProtection'", ",", ":termination_protected", "=>", "protection_enabled", ",", ":job_flow_ids", "=>", "jobflow_ids", "}", "aws_result", "=", "@aws_request", ".", "submit", "(", "params", ")", "yield", "aws_result", "if", "block_given?", "end" ]
Enabled or disable "termination protection" on the specified job flows. Termination protection prevents a job flow from being terminated by a user initiated action, although the job flow will still terminate naturally. Takes an [] of job flow IDs. ["j-1B4D1XP0C0A35", "j-1YG2MYL0HVYS5", ...]
[ "Enabled", "or", "disable", "termination", "protection", "on", "the", "specified", "job", "flows", ".", "Termination", "protection", "prevents", "a", "job", "flow", "from", "being", "terminated", "by", "a", "user", "initiated", "action", "although", "the", "job", "flow", "will", "still", "terminate", "naturally", "." ]
ee0a534b2c63ae0113aee5c85681ae4954703efb
https://github.com/rslifka/elasticity/blob/ee0a534b2c63ae0113aee5c85681ae4954703efb/lib/elasticity/emr.rb#L315-L323
23,196
rslifka/elasticity
lib/elasticity/emr.rb
Elasticity.EMR.set_visible_to_all_users
def set_visible_to_all_users(jobflow_ids, visible=true) params = { :operation => 'SetVisibleToAllUsers', :visible_to_all_users => visible, :job_flow_ids => jobflow_ids } aws_result = @aws_request.submit(params) yield aws_result if block_given? end
ruby
def set_visible_to_all_users(jobflow_ids, visible=true) params = { :operation => 'SetVisibleToAllUsers', :visible_to_all_users => visible, :job_flow_ids => jobflow_ids } aws_result = @aws_request.submit(params) yield aws_result if block_given? end
[ "def", "set_visible_to_all_users", "(", "jobflow_ids", ",", "visible", "=", "true", ")", "params", "=", "{", ":operation", "=>", "'SetVisibleToAllUsers'", ",", ":visible_to_all_users", "=>", "visible", ",", ":job_flow_ids", "=>", "jobflow_ids", "}", "aws_result", "=", "@aws_request", ".", "submit", "(", "params", ")", "yield", "aws_result", "if", "block_given?", "end" ]
Whether or not all IAM users in this account can access the job flows. Takes an [] of job flow IDs. ["j-1B4D1XP0C0A35", "j-1YG2MYL0HVYS5", ...] http://docs.aws.amazon.com/ElasticMapReduce/latest/API/API_SetVisibleToAllUsers.html
[ "Whether", "or", "not", "all", "IAM", "users", "in", "this", "account", "can", "access", "the", "job", "flows", "." ]
ee0a534b2c63ae0113aee5c85681ae4954703efb
https://github.com/rslifka/elasticity/blob/ee0a534b2c63ae0113aee5c85681ae4954703efb/lib/elasticity/emr.rb#L332-L340
23,197
benschwarz/bonsai
lib/bonsai/page.rb
Bonsai.Page.assets
def assets Dir["#{directory}/**/*"].sort.select{|path| !File.directory?(path) && !File.basename(path).include?("yml") }.map do |file| file_to_hash(file) end end
ruby
def assets Dir["#{directory}/**/*"].sort.select{|path| !File.directory?(path) && !File.basename(path).include?("yml") }.map do |file| file_to_hash(file) end end
[ "def", "assets", "Dir", "[", "\"#{directory}/**/*\"", "]", ".", "sort", ".", "select", "{", "|", "path", "|", "!", "File", ".", "directory?", "(", "path", ")", "&&", "!", "File", ".", "basename", "(", "path", ")", ".", "include?", "(", "\"yml\"", ")", "}", ".", "map", "do", "|", "file", "|", "file_to_hash", "(", "file", ")", "end", "end" ]
This method is used for the exporter to copy assets
[ "This", "method", "is", "used", "for", "the", "exporter", "to", "copy", "assets" ]
33d6a84e21f0ee33e4fb1d029fe30a6d21444aaf
https://github.com/benschwarz/bonsai/blob/33d6a84e21f0ee33e4fb1d029fe30a6d21444aaf/lib/bonsai/page.rb#L76-L80
23,198
benschwarz/bonsai
lib/bonsai/page.rb
Bonsai.Page.to_hash
def to_hash hash = { :slug => slug, :permalink => permalink, :name => name, :children => children, :siblings => siblings, :parent => parent, :ancestors => ancestors, :navigation => Bonsai::Navigation.tree, :updated_at => mtime, :created_at => ctime }.merge(formatted_content).merge(disk_assets).merge(Bonsai.site) hash.stringify_keys end
ruby
def to_hash hash = { :slug => slug, :permalink => permalink, :name => name, :children => children, :siblings => siblings, :parent => parent, :ancestors => ancestors, :navigation => Bonsai::Navigation.tree, :updated_at => mtime, :created_at => ctime }.merge(formatted_content).merge(disk_assets).merge(Bonsai.site) hash.stringify_keys end
[ "def", "to_hash", "hash", "=", "{", ":slug", "=>", "slug", ",", ":permalink", "=>", "permalink", ",", ":name", "=>", "name", ",", ":children", "=>", "children", ",", ":siblings", "=>", "siblings", ",", ":parent", "=>", "parent", ",", ":ancestors", "=>", "ancestors", ",", ":navigation", "=>", "Bonsai", "::", "Navigation", ".", "tree", ",", ":updated_at", "=>", "mtime", ",", ":created_at", "=>", "ctime", "}", ".", "merge", "(", "formatted_content", ")", ".", "merge", "(", "disk_assets", ")", ".", "merge", "(", "Bonsai", ".", "site", ")", "hash", ".", "stringify_keys", "end" ]
This hash is available to all templates, it will map common properties, content file results, as well as any "magic" hashes for file system contents
[ "This", "hash", "is", "available", "to", "all", "templates", "it", "will", "map", "common", "properties", "content", "file", "results", "as", "well", "as", "any", "magic", "hashes", "for", "file", "system", "contents" ]
33d6a84e21f0ee33e4fb1d029fe30a6d21444aaf
https://github.com/benschwarz/bonsai/blob/33d6a84e21f0ee33e4fb1d029fe30a6d21444aaf/lib/bonsai/page.rb#L139-L154
23,199
benschwarz/bonsai
lib/bonsai/page.rb
Bonsai.Page.formatted_content
def formatted_content formatted_content = content formatted_content.each do |k,v| if v.is_a?(String) and v =~ /\n/ formatted_content[k] = to_markdown(v) end end formatted_content end
ruby
def formatted_content formatted_content = content formatted_content.each do |k,v| if v.is_a?(String) and v =~ /\n/ formatted_content[k] = to_markdown(v) end end formatted_content end
[ "def", "formatted_content", "formatted_content", "=", "content", "formatted_content", ".", "each", "do", "|", "k", ",", "v", "|", "if", "v", ".", "is_a?", "(", "String", ")", "and", "v", "=~", "/", "\\n", "/", "formatted_content", "[", "k", "]", "=", "to_markdown", "(", "v", ")", "end", "end", "formatted_content", "end" ]
This method ensures that multiline strings are run through markdown and smartypants
[ "This", "method", "ensures", "that", "multiline", "strings", "are", "run", "through", "markdown", "and", "smartypants" ]
33d6a84e21f0ee33e4fb1d029fe30a6d21444aaf
https://github.com/benschwarz/bonsai/blob/33d6a84e21f0ee33e4fb1d029fe30a6d21444aaf/lib/bonsai/page.rb#L160-L169