repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
reinteractive/wallaby
lib/renderers/wallaby/custom_partial_renderer.rb
Wallaby.CustomPartialRenderer.render
def render(context, options, block) super rescue CellHandling => e CellUtils.render context, e.message, options[:locals], &block end
ruby
def render(context, options, block) super rescue CellHandling => e CellUtils.render context, e.message, options[:locals], &block end
[ "def", "render", "(", "context", ",", "options", ",", "block", ")", "super", "rescue", "CellHandling", "=>", "e", "CellUtils", ".", "render", "context", ",", "e", ".", "message", ",", "options", "[", ":locals", "]", ",", "block", "end" ]
When a type partial is found, it works as usual. But when a cell is found, there is an exception {Wallaby::CellHandling} raised. This error will be captured, and the cell will be rendered. @param context [ActionView::Context] @param options [Hash] @param block [Proc] @return [String] HTML output
[ "When", "a", "type", "partial", "is", "found", "it", "works", "as", "usual", "." ]
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/renderers/wallaby/custom_partial_renderer.rb#L12-L16
train
reinteractive/wallaby
lib/renderers/wallaby/custom_partial_renderer.rb
Wallaby.CustomPartialRenderer.find_partial
def find_partial(*) super.tap do |partial| raise CellHandling, partial.inspect if CellUtils.cell? partial.inspect end end
ruby
def find_partial(*) super.tap do |partial| raise CellHandling, partial.inspect if CellUtils.cell? partial.inspect end end
[ "def", "find_partial", "(", "*", ")", "super", ".", "tap", "do", "|", "partial", "|", "raise", "CellHandling", ",", "partial", ".", "inspect", "if", "CellUtils", ".", "cell?", "partial", ".", "inspect", "end", "end" ]
Override origin method to stop rendering when a cell is found. @return [ActionView::Template] partial template @raise [Wallaby:::CellHandling] when a cell is found
[ "Override", "origin", "method", "to", "stop", "rendering", "when", "a", "cell", "is", "found", "." ]
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/renderers/wallaby/custom_partial_renderer.rb#L21-L25
train
ucnv/pnglitch
lib/pnglitch/base.rb
PNGlitch.Base.filter_types
def filter_types types = [] wrap_with_rewind(@filtered_data) do scanline_positions.each do |pos| @filtered_data.pos = pos byte = @filtered_data.read 1 types << byte.unpack('C').first end end types end
ruby
def filter_types types = [] wrap_with_rewind(@filtered_data) do scanline_positions.each do |pos| @filtered_data.pos = pos byte = @filtered_data.read 1 types << byte.unpack('C').first end end types end
[ "def", "filter_types", "types", "=", "[", "]", "wrap_with_rewind", "(", "@filtered_data", ")", "do", "scanline_positions", ".", "each", "do", "|", "pos", "|", "@filtered_data", ".", "pos", "=", "pos", "byte", "=", "@filtered_data", ".", "read", "1", "types", "<<", "byte", ".", "unpack", "(", "'C'", ")", ".", "first", "end", "end", "types", "end" ]
Returns an array of each scanline's filter type value.
[ "Returns", "an", "array", "of", "each", "scanline", "s", "filter", "type", "value", "." ]
ea4d0801b81343fae9b3e711c022e24b667d5a2a
https://github.com/ucnv/pnglitch/blob/ea4d0801b81343fae9b3e711c022e24b667d5a2a/lib/pnglitch/base.rb#L104-L114
train
ucnv/pnglitch
lib/pnglitch/base.rb
PNGlitch.Base.compress
def compress( level = Zlib::DEFAULT_COMPRESSION, window_bits = Zlib::MAX_WBITS, mem_level = Zlib::DEF_MEM_LEVEL, strategy = Zlib::DEFAULT_STRATEGY ) wrap_with_rewind(@compressed_data, @filtered_data) do z = Zlib::Deflate.new level, window_bits, mem_level, strategy until @filtered_data.eof? do buffer_size = 2 ** 16 flush = Zlib::NO_FLUSH flush = Zlib::FINISH if @filtered_data.size - @filtered_data.pos < buffer_size @compressed_data << z.deflate(@filtered_data.read(buffer_size), flush) end z.finish z.close truncate_io @compressed_data end @is_compressed_data_modified = false self end
ruby
def compress( level = Zlib::DEFAULT_COMPRESSION, window_bits = Zlib::MAX_WBITS, mem_level = Zlib::DEF_MEM_LEVEL, strategy = Zlib::DEFAULT_STRATEGY ) wrap_with_rewind(@compressed_data, @filtered_data) do z = Zlib::Deflate.new level, window_bits, mem_level, strategy until @filtered_data.eof? do buffer_size = 2 ** 16 flush = Zlib::NO_FLUSH flush = Zlib::FINISH if @filtered_data.size - @filtered_data.pos < buffer_size @compressed_data << z.deflate(@filtered_data.read(buffer_size), flush) end z.finish z.close truncate_io @compressed_data end @is_compressed_data_modified = false self end
[ "def", "compress", "(", "level", "=", "Zlib", "::", "DEFAULT_COMPRESSION", ",", "window_bits", "=", "Zlib", "::", "MAX_WBITS", ",", "mem_level", "=", "Zlib", "::", "DEF_MEM_LEVEL", ",", "strategy", "=", "Zlib", "::", "DEFAULT_STRATEGY", ")", "wrap_with_rewind", "(", "@compressed_data", ",", "@filtered_data", ")", "do", "z", "=", "Zlib", "::", "Deflate", ".", "new", "level", ",", "window_bits", ",", "mem_level", ",", "strategy", "until", "@filtered_data", ".", "eof?", "do", "buffer_size", "=", "2", "**", "16", "flush", "=", "Zlib", "::", "NO_FLUSH", "flush", "=", "Zlib", "::", "FINISH", "if", "@filtered_data", ".", "size", "-", "@filtered_data", ".", "pos", "<", "buffer_size", "@compressed_data", "<<", "z", ".", "deflate", "(", "@filtered_data", ".", "read", "(", "buffer_size", ")", ",", "flush", ")", "end", "z", ".", "finish", "z", ".", "close", "truncate_io", "@compressed_data", "end", "@is_compressed_data_modified", "=", "false", "self", "end" ]
Re-compress the filtered data. All arguments are for Zlib. See the document of Zlib::Deflate.new for more detail.
[ "Re", "-", "compress", "the", "filtered", "data", "." ]
ea4d0801b81343fae9b3e711c022e24b667d5a2a
https://github.com/ucnv/pnglitch/blob/ea4d0801b81343fae9b3e711c022e24b667d5a2a/lib/pnglitch/base.rb#L264-L284
train
ucnv/pnglitch
lib/pnglitch/base.rb
PNGlitch.Base.each_scanline
def each_scanline # :yield: scanline return enum_for :each_scanline unless block_given? prev_filters = self.filter_types is_refilter_needed = false filter_codecs = [] wrap_with_rewind(@filtered_data) do at = 0 scanline_positions.push(@filtered_data.size).inject do |pos, delimit| scanline = Scanline.new @filtered_data, pos, (delimit - pos - 1), at yield scanline if fabricate_scanline(scanline, prev_filters, filter_codecs) is_refilter_needed = true end at += 1 delimit end end apply_filters(prev_filters, filter_codecs) if is_refilter_needed compress self end
ruby
def each_scanline # :yield: scanline return enum_for :each_scanline unless block_given? prev_filters = self.filter_types is_refilter_needed = false filter_codecs = [] wrap_with_rewind(@filtered_data) do at = 0 scanline_positions.push(@filtered_data.size).inject do |pos, delimit| scanline = Scanline.new @filtered_data, pos, (delimit - pos - 1), at yield scanline if fabricate_scanline(scanline, prev_filters, filter_codecs) is_refilter_needed = true end at += 1 delimit end end apply_filters(prev_filters, filter_codecs) if is_refilter_needed compress self end
[ "def", "each_scanline", "# :yield: scanline", "return", "enum_for", ":each_scanline", "unless", "block_given?", "prev_filters", "=", "self", ".", "filter_types", "is_refilter_needed", "=", "false", "filter_codecs", "=", "[", "]", "wrap_with_rewind", "(", "@filtered_data", ")", "do", "at", "=", "0", "scanline_positions", ".", "push", "(", "@filtered_data", ".", "size", ")", ".", "inject", "do", "|", "pos", ",", "delimit", "|", "scanline", "=", "Scanline", ".", "new", "@filtered_data", ",", "pos", ",", "(", "delimit", "-", "pos", "-", "1", ")", ",", "at", "yield", "scanline", "if", "fabricate_scanline", "(", "scanline", ",", "prev_filters", ",", "filter_codecs", ")", "is_refilter_needed", "=", "true", "end", "at", "+=", "1", "delimit", "end", "end", "apply_filters", "(", "prev_filters", ",", "filter_codecs", ")", "if", "is_refilter_needed", "compress", "self", "end" ]
Process each scanline. It takes a block with a parameter. The parameter must be an instance of PNGlitch::Scanline and it provides ways to edit the filter type and the data of the scanlines. Normally it iterates the number of the PNG image height. Here is some examples: pnglitch.each_scanline do |line| line.gsub!(/\w/, '0') # replace all alphabetical chars in data end pnglicth.each_scanline do |line| line.change_filter 3 # change all filter to 3, data will get re-filtering (it won't be a glitch) end pnglicth.each_scanline do |line| line.graft 3 # change all filter to 3 and data remains (it will be a glitch) end See PNGlitch::Scanline for more details. This method is safer than +glitch+ but will be a little bit slow. ----- Please note that +each_scanline+ will apply the filters *after* the loop. It means a following example doesn't work as expected. pnglicth.each_scanline do |line| line.change_filter 3 line.gsub! /\d/, 'x' # wants to glitch after changing filters. end To glitch after applying the new filter types, it should be called separately like: pnglicth.each_scanline do |line| line.change_filter 3 end pnglicth.each_scanline do |line| line.gsub! /\d/, 'x' end
[ "Process", "each", "scanline", "." ]
ea4d0801b81343fae9b3e711c022e24b667d5a2a
https://github.com/ucnv/pnglitch/blob/ea4d0801b81343fae9b3e711c022e24b667d5a2a/lib/pnglitch/base.rb#L330-L350
train
ucnv/pnglitch
lib/pnglitch/base.rb
PNGlitch.Base.width=
def width= w @head_data.pos = 8 while bytes = @head_data.read(8) length, type = bytes.unpack 'Na*' if type == 'IHDR' @head_data << [w].pack('N') @head_data.pos -= 4 data = @head_data.read length @head_data << [Zlib.crc32(data, Zlib.crc32(type))].pack('N') break end end @head_data.rewind w end
ruby
def width= w @head_data.pos = 8 while bytes = @head_data.read(8) length, type = bytes.unpack 'Na*' if type == 'IHDR' @head_data << [w].pack('N') @head_data.pos -= 4 data = @head_data.read length @head_data << [Zlib.crc32(data, Zlib.crc32(type))].pack('N') break end end @head_data.rewind w end
[ "def", "width", "=", "w", "@head_data", ".", "pos", "=", "8", "while", "bytes", "=", "@head_data", ".", "read", "(", "8", ")", "length", ",", "type", "=", "bytes", ".", "unpack", "'Na*'", "if", "type", "==", "'IHDR'", "@head_data", "<<", "[", "w", "]", ".", "pack", "(", "'N'", ")", "@head_data", ".", "pos", "-=", "4", "data", "=", "@head_data", ".", "read", "length", "@head_data", "<<", "[", "Zlib", ".", "crc32", "(", "data", ",", "Zlib", ".", "crc32", "(", "type", ")", ")", "]", ".", "pack", "(", "'N'", ")", "break", "end", "end", "@head_data", ".", "rewind", "w", "end" ]
Rewrites the width value.
[ "Rewrites", "the", "width", "value", "." ]
ea4d0801b81343fae9b3e711c022e24b667d5a2a
https://github.com/ucnv/pnglitch/blob/ea4d0801b81343fae9b3e711c022e24b667d5a2a/lib/pnglitch/base.rb#L418-L432
train
ucnv/pnglitch
lib/pnglitch/base.rb
PNGlitch.Base.height=
def height= h @head_data.pos = 8 while bytes = @head_data.read(8) length, type = bytes.unpack 'Na*' if type == 'IHDR' @head_data.pos += 4 @head_data << [h].pack('N') @head_data.pos -= 8 data = @head_data.read length @head_data << [Zlib.crc32(data, Zlib.crc32(type))].pack('N') @head_data.rewind break end end @head_data.rewind h end
ruby
def height= h @head_data.pos = 8 while bytes = @head_data.read(8) length, type = bytes.unpack 'Na*' if type == 'IHDR' @head_data.pos += 4 @head_data << [h].pack('N') @head_data.pos -= 8 data = @head_data.read length @head_data << [Zlib.crc32(data, Zlib.crc32(type))].pack('N') @head_data.rewind break end end @head_data.rewind h end
[ "def", "height", "=", "h", "@head_data", ".", "pos", "=", "8", "while", "bytes", "=", "@head_data", ".", "read", "(", "8", ")", "length", ",", "type", "=", "bytes", ".", "unpack", "'Na*'", "if", "type", "==", "'IHDR'", "@head_data", ".", "pos", "+=", "4", "@head_data", "<<", "[", "h", "]", ".", "pack", "(", "'N'", ")", "@head_data", ".", "pos", "-=", "8", "data", "=", "@head_data", ".", "read", "length", "@head_data", "<<", "[", "Zlib", ".", "crc32", "(", "data", ",", "Zlib", ".", "crc32", "(", "type", ")", ")", "]", ".", "pack", "(", "'N'", ")", "@head_data", ".", "rewind", "break", "end", "end", "@head_data", ".", "rewind", "h", "end" ]
Rewrites the height value.
[ "Rewrites", "the", "height", "value", "." ]
ea4d0801b81343fae9b3e711c022e24b667d5a2a
https://github.com/ucnv/pnglitch/blob/ea4d0801b81343fae9b3e711c022e24b667d5a2a/lib/pnglitch/base.rb#L437-L453
train
ucnv/pnglitch
lib/pnglitch/base.rb
PNGlitch.Base.save
def save file wrap_with_rewind(@head_data, @tail_data, @compressed_data) do open(file, 'wb') do |io| io << @head_data.read chunk_size = @idat_chunk_size || @compressed_data.size type = 'IDAT' until @compressed_data.eof? do data = @compressed_data.read(chunk_size) io << [data.size].pack('N') io << type io << data io << [Zlib.crc32(data, Zlib.crc32(type))].pack('N') end io << @tail_data.read end end self end
ruby
def save file wrap_with_rewind(@head_data, @tail_data, @compressed_data) do open(file, 'wb') do |io| io << @head_data.read chunk_size = @idat_chunk_size || @compressed_data.size type = 'IDAT' until @compressed_data.eof? do data = @compressed_data.read(chunk_size) io << [data.size].pack('N') io << type io << data io << [Zlib.crc32(data, Zlib.crc32(type))].pack('N') end io << @tail_data.read end end self end
[ "def", "save", "file", "wrap_with_rewind", "(", "@head_data", ",", "@tail_data", ",", "@compressed_data", ")", "do", "open", "(", "file", ",", "'wb'", ")", "do", "|", "io", "|", "io", "<<", "@head_data", ".", "read", "chunk_size", "=", "@idat_chunk_size", "||", "@compressed_data", ".", "size", "type", "=", "'IDAT'", "until", "@compressed_data", ".", "eof?", "do", "data", "=", "@compressed_data", ".", "read", "(", "chunk_size", ")", "io", "<<", "[", "data", ".", "size", "]", ".", "pack", "(", "'N'", ")", "io", "<<", "type", "io", "<<", "data", "io", "<<", "[", "Zlib", ".", "crc32", "(", "data", ",", "Zlib", ".", "crc32", "(", "type", ")", ")", "]", ".", "pack", "(", "'N'", ")", "end", "io", "<<", "@tail_data", ".", "read", "end", "end", "self", "end" ]
Save to the +file+.
[ "Save", "to", "the", "+", "file", "+", "." ]
ea4d0801b81343fae9b3e711c022e24b667d5a2a
https://github.com/ucnv/pnglitch/blob/ea4d0801b81343fae9b3e711c022e24b667d5a2a/lib/pnglitch/base.rb#L458-L475
train
ucnv/pnglitch
lib/pnglitch/base.rb
PNGlitch.Base.wrap_with_rewind
def wrap_with_rewind *io, &block io.each do |i| i.rewind end yield io.each do |i| i.rewind end end
ruby
def wrap_with_rewind *io, &block io.each do |i| i.rewind end yield io.each do |i| i.rewind end end
[ "def", "wrap_with_rewind", "*", "io", ",", "&", "block", "io", ".", "each", "do", "|", "i", "|", "i", ".", "rewind", "end", "yield", "io", ".", "each", "do", "|", "i", "|", "i", ".", "rewind", "end", "end" ]
Rewinds given IOs before and after the block.
[ "Rewinds", "given", "IOs", "before", "and", "after", "the", "block", "." ]
ea4d0801b81343fae9b3e711c022e24b667d5a2a
https://github.com/ucnv/pnglitch/blob/ea4d0801b81343fae9b3e711c022e24b667d5a2a/lib/pnglitch/base.rb#L488-L496
train
ucnv/pnglitch
lib/pnglitch/base.rb
PNGlitch.Base.scanline_positions
def scanline_positions scanline_pos = [0] amount = @filtered_data.size @interlace_pass_count = [] if self.interlaced? # Adam7 # Pass 1 v = 1 + (@width / 8.0).ceil * @sample_size (@height / 8.0).ceil.times do scanline_pos << scanline_pos.last + v end @interlace_pass_count << scanline_pos.size # Pass 2 v = 1 + ((@width - 4) / 8.0).ceil * @sample_size (@height / 8.0).ceil.times do scanline_pos << scanline_pos.last + v end @interlace_pass_count << scanline_pos.size # Pass 3 v = 1 + (@width / 4.0).ceil * @sample_size ((@height - 4) / 8.0).ceil.times do scanline_pos << scanline_pos.last + v end @interlace_pass_count << scanline_pos.size # Pass 4 v = 1 + ((@width - 2) / 4.0).ceil * @sample_size (@height / 4.0).ceil.times do scanline_pos << scanline_pos.last + v end @interlace_pass_count << scanline_pos.size # Pass 5 v = 1 + (@width / 2.0).ceil * @sample_size ((@height - 2) / 4.0).ceil.times do scanline_pos << scanline_pos.last + v end @interlace_pass_count << scanline_pos.size # Pass 6 v = 1 + ((@width - 1) / 2.0).ceil * @sample_size (@height / 2.0).ceil.times do scanline_pos << scanline_pos.last + v end @interlace_pass_count << scanline_pos.size # Pass 7 v = 1 + @width * @sample_size ((@height - 1) / 2.0).ceil.times do scanline_pos << scanline_pos.last + v end scanline_pos.pop # no need to keep last position end loop do v = scanline_pos.last + (1 + @width * @sample_size) break if v >= amount scanline_pos << v end scanline_pos end
ruby
def scanline_positions scanline_pos = [0] amount = @filtered_data.size @interlace_pass_count = [] if self.interlaced? # Adam7 # Pass 1 v = 1 + (@width / 8.0).ceil * @sample_size (@height / 8.0).ceil.times do scanline_pos << scanline_pos.last + v end @interlace_pass_count << scanline_pos.size # Pass 2 v = 1 + ((@width - 4) / 8.0).ceil * @sample_size (@height / 8.0).ceil.times do scanline_pos << scanline_pos.last + v end @interlace_pass_count << scanline_pos.size # Pass 3 v = 1 + (@width / 4.0).ceil * @sample_size ((@height - 4) / 8.0).ceil.times do scanline_pos << scanline_pos.last + v end @interlace_pass_count << scanline_pos.size # Pass 4 v = 1 + ((@width - 2) / 4.0).ceil * @sample_size (@height / 4.0).ceil.times do scanline_pos << scanline_pos.last + v end @interlace_pass_count << scanline_pos.size # Pass 5 v = 1 + (@width / 2.0).ceil * @sample_size ((@height - 2) / 4.0).ceil.times do scanline_pos << scanline_pos.last + v end @interlace_pass_count << scanline_pos.size # Pass 6 v = 1 + ((@width - 1) / 2.0).ceil * @sample_size (@height / 2.0).ceil.times do scanline_pos << scanline_pos.last + v end @interlace_pass_count << scanline_pos.size # Pass 7 v = 1 + @width * @sample_size ((@height - 1) / 2.0).ceil.times do scanline_pos << scanline_pos.last + v end scanline_pos.pop # no need to keep last position end loop do v = scanline_pos.last + (1 + @width * @sample_size) break if v >= amount scanline_pos << v end scanline_pos end
[ "def", "scanline_positions", "scanline_pos", "=", "[", "0", "]", "amount", "=", "@filtered_data", ".", "size", "@interlace_pass_count", "=", "[", "]", "if", "self", ".", "interlaced?", "# Adam7", "# Pass 1", "v", "=", "1", "+", "(", "@width", "/", "8.0", ")", ".", "ceil", "*", "@sample_size", "(", "@height", "/", "8.0", ")", ".", "ceil", ".", "times", "do", "scanline_pos", "<<", "scanline_pos", ".", "last", "+", "v", "end", "@interlace_pass_count", "<<", "scanline_pos", ".", "size", "# Pass 2", "v", "=", "1", "+", "(", "(", "@width", "-", "4", ")", "/", "8.0", ")", ".", "ceil", "*", "@sample_size", "(", "@height", "/", "8.0", ")", ".", "ceil", ".", "times", "do", "scanline_pos", "<<", "scanline_pos", ".", "last", "+", "v", "end", "@interlace_pass_count", "<<", "scanline_pos", ".", "size", "# Pass 3", "v", "=", "1", "+", "(", "@width", "/", "4.0", ")", ".", "ceil", "*", "@sample_size", "(", "(", "@height", "-", "4", ")", "/", "8.0", ")", ".", "ceil", ".", "times", "do", "scanline_pos", "<<", "scanline_pos", ".", "last", "+", "v", "end", "@interlace_pass_count", "<<", "scanline_pos", ".", "size", "# Pass 4", "v", "=", "1", "+", "(", "(", "@width", "-", "2", ")", "/", "4.0", ")", ".", "ceil", "*", "@sample_size", "(", "@height", "/", "4.0", ")", ".", "ceil", ".", "times", "do", "scanline_pos", "<<", "scanline_pos", ".", "last", "+", "v", "end", "@interlace_pass_count", "<<", "scanline_pos", ".", "size", "# Pass 5", "v", "=", "1", "+", "(", "@width", "/", "2.0", ")", ".", "ceil", "*", "@sample_size", "(", "(", "@height", "-", "2", ")", "/", "4.0", ")", ".", "ceil", ".", "times", "do", "scanline_pos", "<<", "scanline_pos", ".", "last", "+", "v", "end", "@interlace_pass_count", "<<", "scanline_pos", ".", "size", "# Pass 6", "v", "=", "1", "+", "(", "(", "@width", "-", "1", ")", "/", "2.0", ")", ".", "ceil", "*", "@sample_size", "(", "@height", "/", "2.0", ")", ".", "ceil", ".", "times", "do", "scanline_pos", "<<", "scanline_pos", ".", "last", "+", "v", "end", "@interlace_pass_count", "<<", "scanline_pos", ".", "size", "# Pass 7", "v", "=", "1", "+", "@width", "*", "@sample_size", "(", "(", "@height", "-", "1", ")", "/", "2.0", ")", ".", "ceil", ".", "times", "do", "scanline_pos", "<<", "scanline_pos", ".", "last", "+", "v", "end", "scanline_pos", ".", "pop", "# no need to keep last position", "end", "loop", "do", "v", "=", "scanline_pos", ".", "last", "+", "(", "1", "+", "@width", "*", "@sample_size", ")", "break", "if", "v", ">=", "amount", "scanline_pos", "<<", "v", "end", "scanline_pos", "end" ]
Calculate positions of scanlines
[ "Calculate", "positions", "of", "scanlines" ]
ea4d0801b81343fae9b3e711c022e24b667d5a2a
https://github.com/ucnv/pnglitch/blob/ea4d0801b81343fae9b3e711c022e24b667d5a2a/lib/pnglitch/base.rb#L499-L554
train
ucnv/pnglitch
lib/pnglitch/scanline.rb
PNGlitch.Scanline.register_filter_encoder
def register_filter_encoder encoder = nil, &block if !encoder.nil? && encoder.is_a?(Proc) @filter_codec[:encoder] = encoder elsif block_given? @filter_codec[:encoder] = block end save end
ruby
def register_filter_encoder encoder = nil, &block if !encoder.nil? && encoder.is_a?(Proc) @filter_codec[:encoder] = encoder elsif block_given? @filter_codec[:encoder] = block end save end
[ "def", "register_filter_encoder", "encoder", "=", "nil", ",", "&", "block", "if", "!", "encoder", ".", "nil?", "&&", "encoder", ".", "is_a?", "(", "Proc", ")", "@filter_codec", "[", ":encoder", "]", "=", "encoder", "elsif", "block_given?", "@filter_codec", "[", ":encoder", "]", "=", "block", "end", "save", "end" ]
Registers a custom filter function to encode data. With this operation, it will be able to change filter encoding behavior despite the specified filter type value. It takes a Proc object or a block.
[ "Registers", "a", "custom", "filter", "function", "to", "encode", "data", "." ]
ea4d0801b81343fae9b3e711c022e24b667d5a2a
https://github.com/ucnv/pnglitch/blob/ea4d0801b81343fae9b3e711c022e24b667d5a2a/lib/pnglitch/scanline.rb#L97-L104
train
ucnv/pnglitch
lib/pnglitch/scanline.rb
PNGlitch.Scanline.register_filter_decoder
def register_filter_decoder decoder = nil, &block if !decoder.nil? && decoder.is_a?(Proc) @filter_codec[:decoder] = decoder elsif block_given? @filter_codec[:decoder] = block end save end
ruby
def register_filter_decoder decoder = nil, &block if !decoder.nil? && decoder.is_a?(Proc) @filter_codec[:decoder] = decoder elsif block_given? @filter_codec[:decoder] = block end save end
[ "def", "register_filter_decoder", "decoder", "=", "nil", ",", "&", "block", "if", "!", "decoder", ".", "nil?", "&&", "decoder", ".", "is_a?", "(", "Proc", ")", "@filter_codec", "[", ":decoder", "]", "=", "decoder", "elsif", "block_given?", "@filter_codec", "[", ":decoder", "]", "=", "block", "end", "save", "end" ]
Registers a custom filter function to decode data. With this operation, it will be able to change filter decoding behavior despite the specified filter type value. It takes a Proc object or a block.
[ "Registers", "a", "custom", "filter", "function", "to", "decode", "data", "." ]
ea4d0801b81343fae9b3e711c022e24b667d5a2a
https://github.com/ucnv/pnglitch/blob/ea4d0801b81343fae9b3e711c022e24b667d5a2a/lib/pnglitch/scanline.rb#L112-L119
train
ucnv/pnglitch
lib/pnglitch/scanline.rb
PNGlitch.Scanline.save
def save pos = @io.pos @io.pos = @start_at @io << [Filter.guess(@filter_type)].pack('C') @io << self.data.slice(0, @data_size).ljust(@data_size, "\0") @io.pos = pos @callback.call(self) unless @callback.nil? self end
ruby
def save pos = @io.pos @io.pos = @start_at @io << [Filter.guess(@filter_type)].pack('C') @io << self.data.slice(0, @data_size).ljust(@data_size, "\0") @io.pos = pos @callback.call(self) unless @callback.nil? self end
[ "def", "save", "pos", "=", "@io", ".", "pos", "@io", ".", "pos", "=", "@start_at", "@io", "<<", "[", "Filter", ".", "guess", "(", "@filter_type", ")", "]", ".", "pack", "(", "'C'", ")", "@io", "<<", "self", ".", "data", ".", "slice", "(", "0", ",", "@data_size", ")", ".", "ljust", "(", "@data_size", ",", "\"\\0\"", ")", "@io", ".", "pos", "=", "pos", "@callback", ".", "call", "(", "self", ")", "unless", "@callback", ".", "nil?", "self", "end" ]
Save the changes.
[ "Save", "the", "changes", "." ]
ea4d0801b81343fae9b3e711c022e24b667d5a2a
https://github.com/ucnv/pnglitch/blob/ea4d0801b81343fae9b3e711c022e24b667d5a2a/lib/pnglitch/scanline.rb#L124-L132
train
piotrmurach/benchmark-perf
lib/benchmark/perf.rb
Benchmark.Perf.variance
def variance(measurements) return 0 if measurements.empty? avg = average(measurements) total = measurements.reduce(0) do |sum, x| sum + (x - avg)**2 end total.to_f / measurements.size end
ruby
def variance(measurements) return 0 if measurements.empty? avg = average(measurements) total = measurements.reduce(0) do |sum, x| sum + (x - avg)**2 end total.to_f / measurements.size end
[ "def", "variance", "(", "measurements", ")", "return", "0", "if", "measurements", ".", "empty?", "avg", "=", "average", "(", "measurements", ")", "total", "=", "measurements", ".", "reduce", "(", "0", ")", "do", "|", "sum", ",", "x", "|", "sum", "+", "(", "x", "-", "avg", ")", "**", "2", "end", "total", ".", "to_f", "/", "measurements", ".", "size", "end" ]
Calculate variance of measurements @param [Array[Float]] measurements @return [Float] @api public
[ "Calculate", "variance", "of", "measurements" ]
ed17c0a5f10d4fc25e443cc2b4151c54c8c4480e
https://github.com/piotrmurach/benchmark-perf/blob/ed17c0a5f10d4fc25e443cc2b4151c54c8c4480e/lib/benchmark/perf.rb#L33-L41
train
piotrmurach/benchmark-perf
lib/benchmark/perf.rb
Benchmark.Perf.assert_perform_under
def assert_perform_under(threshold, options = {}, &work) actual, _ = ExecutionTime.run(options, &work) actual <= threshold end
ruby
def assert_perform_under(threshold, options = {}, &work) actual, _ = ExecutionTime.run(options, &work) actual <= threshold end
[ "def", "assert_perform_under", "(", "threshold", ",", "options", "=", "{", "}", ",", "&", "work", ")", "actual", ",", "_", "=", "ExecutionTime", ".", "run", "(", "options", ",", "work", ")", "actual", "<=", "threshold", "end" ]
Run given work and gather time statistics @param [Float] threshold @return [Boolean] @api public
[ "Run", "given", "work", "and", "gather", "time", "statistics" ]
ed17c0a5f10d4fc25e443cc2b4151c54c8c4480e
https://github.com/piotrmurach/benchmark-perf/blob/ed17c0a5f10d4fc25e443cc2b4151c54c8c4480e/lib/benchmark/perf.rb#L63-L66
train
piotrmurach/benchmark-perf
lib/benchmark/perf.rb
Benchmark.Perf.assert_perform_ips
def assert_perform_ips(iterations, options = {}, &work) mean, stddev, _ = Iteration.run(options, &work) iterations <= (mean + 3 * stddev) end
ruby
def assert_perform_ips(iterations, options = {}, &work) mean, stddev, _ = Iteration.run(options, &work) iterations <= (mean + 3 * stddev) end
[ "def", "assert_perform_ips", "(", "iterations", ",", "options", "=", "{", "}", ",", "&", "work", ")", "mean", ",", "stddev", ",", "_", "=", "Iteration", ".", "run", "(", "options", ",", "work", ")", "iterations", "<=", "(", "mean", "+", "3", "*", "stddev", ")", "end" ]
Assert work is performed within expected iterations per second @param [Integer] iterations @return [Boolean] @api public
[ "Assert", "work", "is", "performed", "within", "expected", "iterations", "per", "second" ]
ed17c0a5f10d4fc25e443cc2b4151c54c8c4480e
https://github.com/piotrmurach/benchmark-perf/blob/ed17c0a5f10d4fc25e443cc2b4151c54c8c4480e/lib/benchmark/perf.rb#L76-L79
train
zenhob/hcl
lib/hcl/app.rb
HCl.App.run
def run request_config if @options[:reauth] if @options[:changelog] system %[ more "#{File.join(File.dirname(__FILE__), '../../CHANGELOG.markdown')}" ] exit end begin if @command if command? @command result = send @command, *@args if not result.nil? if result.respond_to? :join, include_all=false puts result.join(', ') elsif result.respond_to? :to_s, include_all=false puts result end end else puts start(@command, *@args) end else puts show end rescue CommandError => e $stderr.puts e exit 1 rescue RuntimeError => e $stderr.puts "Error: #{e}" exit 1 rescue Faraday::Error => e $stderr.puts "Connection failed. (#{e.message})" exit 1 rescue HarvestMiddleware::ThrottleFailure => e $stderr.puts "Too many requests, retrying in #{e.retry_after+5} seconds..." sleep e.retry_after+5 run rescue HarvestMiddleware::AuthFailure => e $stderr.puts "Unable to authenticate: #{e}" request_config run rescue HarvestMiddleware::Failure => e $stderr.puts "API failure: #{e}" exit 1 end end
ruby
def run request_config if @options[:reauth] if @options[:changelog] system %[ more "#{File.join(File.dirname(__FILE__), '../../CHANGELOG.markdown')}" ] exit end begin if @command if command? @command result = send @command, *@args if not result.nil? if result.respond_to? :join, include_all=false puts result.join(', ') elsif result.respond_to? :to_s, include_all=false puts result end end else puts start(@command, *@args) end else puts show end rescue CommandError => e $stderr.puts e exit 1 rescue RuntimeError => e $stderr.puts "Error: #{e}" exit 1 rescue Faraday::Error => e $stderr.puts "Connection failed. (#{e.message})" exit 1 rescue HarvestMiddleware::ThrottleFailure => e $stderr.puts "Too many requests, retrying in #{e.retry_after+5} seconds..." sleep e.retry_after+5 run rescue HarvestMiddleware::AuthFailure => e $stderr.puts "Unable to authenticate: #{e}" request_config run rescue HarvestMiddleware::Failure => e $stderr.puts "API failure: #{e}" exit 1 end end
[ "def", "run", "request_config", "if", "@options", "[", ":reauth", "]", "if", "@options", "[", ":changelog", "]", "system", "%[ more \"#{File.join(File.dirname(__FILE__), '../../CHANGELOG.markdown')}\" ]", "exit", "end", "begin", "if", "@command", "if", "command?", "@command", "result", "=", "send", "@command", ",", "@args", "if", "not", "result", ".", "nil?", "if", "result", ".", "respond_to?", ":join", ",", "include_all", "=", "false", "puts", "result", ".", "join", "(", "', '", ")", "elsif", "result", ".", "respond_to?", ":to_s", ",", "include_all", "=", "false", "puts", "result", "end", "end", "else", "puts", "start", "(", "@command", ",", "@args", ")", "end", "else", "puts", "show", "end", "rescue", "CommandError", "=>", "e", "$stderr", ".", "puts", "e", "exit", "1", "rescue", "RuntimeError", "=>", "e", "$stderr", ".", "puts", "\"Error: #{e}\"", "exit", "1", "rescue", "Faraday", "::", "Error", "=>", "e", "$stderr", ".", "puts", "\"Connection failed. (#{e.message})\"", "exit", "1", "rescue", "HarvestMiddleware", "::", "ThrottleFailure", "=>", "e", "$stderr", ".", "puts", "\"Too many requests, retrying in #{e.retry_after+5} seconds...\"", "sleep", "e", ".", "retry_after", "+", "5", "run", "rescue", "HarvestMiddleware", "::", "AuthFailure", "=>", "e", "$stderr", ".", "puts", "\"Unable to authenticate: #{e}\"", "request_config", "run", "rescue", "HarvestMiddleware", "::", "Failure", "=>", "e", "$stderr", ".", "puts", "\"API failure: #{e}\"", "exit", "1", "end", "end" ]
Start the application.
[ "Start", "the", "application", "." ]
31a014960b100b2ced9316547a01054fc768d7a9
https://github.com/zenhob/hcl/blob/31a014960b100b2ced9316547a01054fc768d7a9/lib/hcl/app.rb#L40-L84
train
zenhob/hcl
lib/hcl/utility.rb
HCl.Utility.time2float
def time2float time_string if time_string =~ /:/ hours, minutes = time_string.split(':') hours.to_f + (minutes.to_f / 60.0) else time_string.to_f end end
ruby
def time2float time_string if time_string =~ /:/ hours, minutes = time_string.split(':') hours.to_f + (minutes.to_f / 60.0) else time_string.to_f end end
[ "def", "time2float", "time_string", "if", "time_string", "=~", "/", "/", "hours", ",", "minutes", "=", "time_string", ".", "split", "(", "':'", ")", "hours", ".", "to_f", "+", "(", "minutes", ".", "to_f", "/", "60.0", ")", "else", "time_string", ".", "to_f", "end", "end" ]
Convert from a time span in hour or decimal format to a float. @param [String] time_string either "M:MM" or decimal @return [#to_f] converted to a floating-point number
[ "Convert", "from", "a", "time", "span", "in", "hour", "or", "decimal", "format", "to", "a", "float", "." ]
31a014960b100b2ced9316547a01054fc768d7a9
https://github.com/zenhob/hcl/blob/31a014960b100b2ced9316547a01054fc768d7a9/lib/hcl/utility.rb#L55-L62
train
zenhob/hcl
lib/hcl/day_entry.rb
HCl.DayEntry.append_note
def append_note http, new_notes # If I don't include hours it gets reset. # This doens't appear to be the case for task and project. (self.notes << "\n#{new_notes}").lstrip! http.post "daily/update/#{id}", notes:notes, hours:hours end
ruby
def append_note http, new_notes # If I don't include hours it gets reset. # This doens't appear to be the case for task and project. (self.notes << "\n#{new_notes}").lstrip! http.post "daily/update/#{id}", notes:notes, hours:hours end
[ "def", "append_note", "http", ",", "new_notes", "# If I don't include hours it gets reset.", "# This doens't appear to be the case for task and project.", "(", "self", ".", "notes", "<<", "\"\\n#{new_notes}\"", ")", ".", "lstrip!", "http", ".", "post", "\"daily/update/#{id}\"", ",", "notes", ":", "notes", ",", "hours", ":", "hours", "end" ]
Append a string to the notes for this task.
[ "Append", "a", "string", "to", "the", "notes", "for", "this", "task", "." ]
31a014960b100b2ced9316547a01054fc768d7a9
https://github.com/zenhob/hcl/blob/31a014960b100b2ced9316547a01054fc768d7a9/lib/hcl/day_entry.rb#L32-L37
train
zenhob/hcl
lib/hcl/commands.rb
HCl.Commands.status
def status result = Faraday.new("http://kccljmymlslr.statuspage.io/api/v2") do |f| f.adapter Faraday.default_adapter end.get('status.json').body json = Yajl::Parser.parse result, symbolize_keys: true status = json[:status][:description] updated_at = DateTime.parse(json[:page][:updated_at]).strftime "%F %T %:z" "#{status} [#{updated_at}]" end
ruby
def status result = Faraday.new("http://kccljmymlslr.statuspage.io/api/v2") do |f| f.adapter Faraday.default_adapter end.get('status.json').body json = Yajl::Parser.parse result, symbolize_keys: true status = json[:status][:description] updated_at = DateTime.parse(json[:page][:updated_at]).strftime "%F %T %:z" "#{status} [#{updated_at}]" end
[ "def", "status", "result", "=", "Faraday", ".", "new", "(", "\"http://kccljmymlslr.statuspage.io/api/v2\"", ")", "do", "|", "f", "|", "f", ".", "adapter", "Faraday", ".", "default_adapter", "end", ".", "get", "(", "'status.json'", ")", ".", "body", "json", "=", "Yajl", "::", "Parser", ".", "parse", "result", ",", "symbolize_keys", ":", "true", "status", "=", "json", "[", ":status", "]", "[", ":description", "]", "updated_at", "=", "DateTime", ".", "parse", "(", "json", "[", ":page", "]", "[", ":updated_at", "]", ")", ".", "strftime", "\"%F %T %:z\"", "\"#{status} [#{updated_at}]\"", "end" ]
Show the network status of the Harvest service.
[ "Show", "the", "network", "status", "of", "the", "Harvest", "service", "." ]
31a014960b100b2ced9316547a01054fc768d7a9
https://github.com/zenhob/hcl/blob/31a014960b100b2ced9316547a01054fc768d7a9/lib/hcl/commands.rb#L14-L24
train
sosedoff/goodreads
lib/goodreads/client/shelves.rb
Goodreads.Shelves.shelves
def shelves(user_id, options = {}) options = options.merge(user_id: user_id, v: 2) data = request("/shelf/list.xml", options) shelves = data["shelves"] shelves = data["shelves"]["user_shelf"].map do |s| Hashie::Mash.new({ id: s["id"], name: s["name"], book_count: s["book_count"], exclusive: s["exclusive_flag"], description: s["description"], sort: s["sort"], order: s["order"], per_page: s["per_page"], display_fields: s["display_fields"], featured: s["featured"], recommend_for: s["recommend_for"], sticky: s["sticky"], }) end Hashie::Mash.new( start: data["shelves"]["start"].to_i, end: data["shelves"]["end"].to_i, total: data["shelves"]["total"].to_i, shelves: shelves ) end
ruby
def shelves(user_id, options = {}) options = options.merge(user_id: user_id, v: 2) data = request("/shelf/list.xml", options) shelves = data["shelves"] shelves = data["shelves"]["user_shelf"].map do |s| Hashie::Mash.new({ id: s["id"], name: s["name"], book_count: s["book_count"], exclusive: s["exclusive_flag"], description: s["description"], sort: s["sort"], order: s["order"], per_page: s["per_page"], display_fields: s["display_fields"], featured: s["featured"], recommend_for: s["recommend_for"], sticky: s["sticky"], }) end Hashie::Mash.new( start: data["shelves"]["start"].to_i, end: data["shelves"]["end"].to_i, total: data["shelves"]["total"].to_i, shelves: shelves ) end
[ "def", "shelves", "(", "user_id", ",", "options", "=", "{", "}", ")", "options", "=", "options", ".", "merge", "(", "user_id", ":", "user_id", ",", "v", ":", "2", ")", "data", "=", "request", "(", "\"/shelf/list.xml\"", ",", "options", ")", "shelves", "=", "data", "[", "\"shelves\"", "]", "shelves", "=", "data", "[", "\"shelves\"", "]", "[", "\"user_shelf\"", "]", ".", "map", "do", "|", "s", "|", "Hashie", "::", "Mash", ".", "new", "(", "{", "id", ":", "s", "[", "\"id\"", "]", ",", "name", ":", "s", "[", "\"name\"", "]", ",", "book_count", ":", "s", "[", "\"book_count\"", "]", ",", "exclusive", ":", "s", "[", "\"exclusive_flag\"", "]", ",", "description", ":", "s", "[", "\"description\"", "]", ",", "sort", ":", "s", "[", "\"sort\"", "]", ",", "order", ":", "s", "[", "\"order\"", "]", ",", "per_page", ":", "s", "[", "\"per_page\"", "]", ",", "display_fields", ":", "s", "[", "\"display_fields\"", "]", ",", "featured", ":", "s", "[", "\"featured\"", "]", ",", "recommend_for", ":", "s", "[", "\"recommend_for\"", "]", ",", "sticky", ":", "s", "[", "\"sticky\"", "]", ",", "}", ")", "end", "Hashie", "::", "Mash", ".", "new", "(", "start", ":", "data", "[", "\"shelves\"", "]", "[", "\"start\"", "]", ".", "to_i", ",", "end", ":", "data", "[", "\"shelves\"", "]", "[", "\"end\"", "]", ".", "to_i", ",", "total", ":", "data", "[", "\"shelves\"", "]", "[", "\"total\"", "]", ".", "to_i", ",", "shelves", ":", "shelves", ")", "end" ]
Lists shelves for a user
[ "Lists", "shelves", "for", "a", "user" ]
aa571069ab07190c93b8a8aff77e1da2c79ab694
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/client/shelves.rb#L4-L32
train
sosedoff/goodreads
lib/goodreads/client/shelves.rb
Goodreads.Shelves.shelf
def shelf(user_id, shelf_name, options = {}) options = options.merge(shelf: shelf_name, v: 2) data = request("/review/list/#{user_id}.xml", options) reviews = data["reviews"]["review"] books = [] unless reviews.nil? # one-book results come back as a single hash reviews = [reviews] unless reviews.instance_of?(Array) books = reviews.map { |e| Hashie::Mash.new(e) } end Hashie::Mash.new( start: data["reviews"]["start"].to_i, end: data["reviews"]["end"].to_i, total: data["reviews"]["total"].to_i, books: books ) end
ruby
def shelf(user_id, shelf_name, options = {}) options = options.merge(shelf: shelf_name, v: 2) data = request("/review/list/#{user_id}.xml", options) reviews = data["reviews"]["review"] books = [] unless reviews.nil? # one-book results come back as a single hash reviews = [reviews] unless reviews.instance_of?(Array) books = reviews.map { |e| Hashie::Mash.new(e) } end Hashie::Mash.new( start: data["reviews"]["start"].to_i, end: data["reviews"]["end"].to_i, total: data["reviews"]["total"].to_i, books: books ) end
[ "def", "shelf", "(", "user_id", ",", "shelf_name", ",", "options", "=", "{", "}", ")", "options", "=", "options", ".", "merge", "(", "shelf", ":", "shelf_name", ",", "v", ":", "2", ")", "data", "=", "request", "(", "\"/review/list/#{user_id}.xml\"", ",", "options", ")", "reviews", "=", "data", "[", "\"reviews\"", "]", "[", "\"review\"", "]", "books", "=", "[", "]", "unless", "reviews", ".", "nil?", "# one-book results come back as a single hash", "reviews", "=", "[", "reviews", "]", "unless", "reviews", ".", "instance_of?", "(", "Array", ")", "books", "=", "reviews", ".", "map", "{", "|", "e", "|", "Hashie", "::", "Mash", ".", "new", "(", "e", ")", "}", "end", "Hashie", "::", "Mash", ".", "new", "(", "start", ":", "data", "[", "\"reviews\"", "]", "[", "\"start\"", "]", ".", "to_i", ",", "end", ":", "data", "[", "\"reviews\"", "]", "[", "\"end\"", "]", ".", "to_i", ",", "total", ":", "data", "[", "\"reviews\"", "]", "[", "\"total\"", "]", ".", "to_i", ",", "books", ":", "books", ")", "end" ]
Get books from a user's shelf
[ "Get", "books", "from", "a", "user", "s", "shelf" ]
aa571069ab07190c93b8a8aff77e1da2c79ab694
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/client/shelves.rb#L35-L53
train
sosedoff/goodreads
lib/goodreads/client/shelves.rb
Goodreads.Shelves.add_to_shelf
def add_to_shelf(book_id, shelf_name, options = {}) options = options.merge(book_id: book_id, name: shelf_name, v: 2) data = oauth_request_method(:post, "/shelf/add_to_shelf.xml", options) # when a book is on a single shelf it is a single hash shelves = data["my_review"]["shelves"]["shelf"] shelves = [shelves] unless shelves.instance_of?(Array) shelves = shelves.map do |s| Hashie::Mash.new({ id: s["id"].to_i, name: s["name"], exclusive: s["exclusive"] == "true", sortable: s["sortable"] == "true", }) end Hashie::Mash.new( id: data["my_review"]["id"].to_i, book_id: data["my_review"]["book_id"].to_i, rating: data["my_review"]["rating"].to_i, body: data["my_review"]["body"], body_raw: data["my_review"]["body_raw"], spoiler: data["my_review"]["spoiler_flag"] == "true", shelves: shelves, read_at: data["my_review"]["read_at"], started_at: data["my_review"]["started_at"], date_added: data["my_review"]["date_added"], updated_at: data["my_review"]["updated_at"], ) end
ruby
def add_to_shelf(book_id, shelf_name, options = {}) options = options.merge(book_id: book_id, name: shelf_name, v: 2) data = oauth_request_method(:post, "/shelf/add_to_shelf.xml", options) # when a book is on a single shelf it is a single hash shelves = data["my_review"]["shelves"]["shelf"] shelves = [shelves] unless shelves.instance_of?(Array) shelves = shelves.map do |s| Hashie::Mash.new({ id: s["id"].to_i, name: s["name"], exclusive: s["exclusive"] == "true", sortable: s["sortable"] == "true", }) end Hashie::Mash.new( id: data["my_review"]["id"].to_i, book_id: data["my_review"]["book_id"].to_i, rating: data["my_review"]["rating"].to_i, body: data["my_review"]["body"], body_raw: data["my_review"]["body_raw"], spoiler: data["my_review"]["spoiler_flag"] == "true", shelves: shelves, read_at: data["my_review"]["read_at"], started_at: data["my_review"]["started_at"], date_added: data["my_review"]["date_added"], updated_at: data["my_review"]["updated_at"], ) end
[ "def", "add_to_shelf", "(", "book_id", ",", "shelf_name", ",", "options", "=", "{", "}", ")", "options", "=", "options", ".", "merge", "(", "book_id", ":", "book_id", ",", "name", ":", "shelf_name", ",", "v", ":", "2", ")", "data", "=", "oauth_request_method", "(", ":post", ",", "\"/shelf/add_to_shelf.xml\"", ",", "options", ")", "# when a book is on a single shelf it is a single hash", "shelves", "=", "data", "[", "\"my_review\"", "]", "[", "\"shelves\"", "]", "[", "\"shelf\"", "]", "shelves", "=", "[", "shelves", "]", "unless", "shelves", ".", "instance_of?", "(", "Array", ")", "shelves", "=", "shelves", ".", "map", "do", "|", "s", "|", "Hashie", "::", "Mash", ".", "new", "(", "{", "id", ":", "s", "[", "\"id\"", "]", ".", "to_i", ",", "name", ":", "s", "[", "\"name\"", "]", ",", "exclusive", ":", "s", "[", "\"exclusive\"", "]", "==", "\"true\"", ",", "sortable", ":", "s", "[", "\"sortable\"", "]", "==", "\"true\"", ",", "}", ")", "end", "Hashie", "::", "Mash", ".", "new", "(", "id", ":", "data", "[", "\"my_review\"", "]", "[", "\"id\"", "]", ".", "to_i", ",", "book_id", ":", "data", "[", "\"my_review\"", "]", "[", "\"book_id\"", "]", ".", "to_i", ",", "rating", ":", "data", "[", "\"my_review\"", "]", "[", "\"rating\"", "]", ".", "to_i", ",", "body", ":", "data", "[", "\"my_review\"", "]", "[", "\"body\"", "]", ",", "body_raw", ":", "data", "[", "\"my_review\"", "]", "[", "\"body_raw\"", "]", ",", "spoiler", ":", "data", "[", "\"my_review\"", "]", "[", "\"spoiler_flag\"", "]", "==", "\"true\"", ",", "shelves", ":", "shelves", ",", "read_at", ":", "data", "[", "\"my_review\"", "]", "[", "\"read_at\"", "]", ",", "started_at", ":", "data", "[", "\"my_review\"", "]", "[", "\"started_at\"", "]", ",", "date_added", ":", "data", "[", "\"my_review\"", "]", "[", "\"date_added\"", "]", ",", "updated_at", ":", "data", "[", "\"my_review\"", "]", "[", "\"updated_at\"", "]", ",", ")", "end" ]
Add book to a user's shelf Returns the user's review for the book, which includes all its current shelves
[ "Add", "book", "to", "a", "user", "s", "shelf" ]
aa571069ab07190c93b8a8aff77e1da2c79ab694
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/client/shelves.rb#L58-L90
train
sosedoff/goodreads
lib/goodreads/request.rb
Goodreads.Request.request
def request(path, params = {}) if oauth_configured? oauth_request(path, params) else http_request(path, params) end end
ruby
def request(path, params = {}) if oauth_configured? oauth_request(path, params) else http_request(path, params) end end
[ "def", "request", "(", "path", ",", "params", "=", "{", "}", ")", "if", "oauth_configured?", "oauth_request", "(", "path", ",", "params", ")", "else", "http_request", "(", "path", ",", "params", ")", "end", "end" ]
Perform an API request using API key or OAuth token path - Request path params - Parameters hash Will make a request with the configured API key (application authentication) or OAuth token (user authentication) if available.
[ "Perform", "an", "API", "request", "using", "API", "key", "or", "OAuth", "token" ]
aa571069ab07190c93b8a8aff77e1da2c79ab694
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/request.rb#L19-L25
train
sosedoff/goodreads
lib/goodreads/request.rb
Goodreads.Request.http_request
def http_request(path, params) token = api_key || Goodreads.configuration[:api_key] fail(Goodreads::ConfigurationError, "API key required.") if token.nil? params.merge!(format: API_FORMAT, key: token) url = "#{API_URL}#{path}" resp = RestClient.get(url, params: params) do |response, request, result, &block| case response.code when 200 response.return!(&block) when 401 fail(Goodreads::Unauthorized) when 403 fail(Goodreads::Forbidden) when 404 fail(Goodreads::NotFound) end end parse(resp) end
ruby
def http_request(path, params) token = api_key || Goodreads.configuration[:api_key] fail(Goodreads::ConfigurationError, "API key required.") if token.nil? params.merge!(format: API_FORMAT, key: token) url = "#{API_URL}#{path}" resp = RestClient.get(url, params: params) do |response, request, result, &block| case response.code when 200 response.return!(&block) when 401 fail(Goodreads::Unauthorized) when 403 fail(Goodreads::Forbidden) when 404 fail(Goodreads::NotFound) end end parse(resp) end
[ "def", "http_request", "(", "path", ",", "params", ")", "token", "=", "api_key", "||", "Goodreads", ".", "configuration", "[", ":api_key", "]", "fail", "(", "Goodreads", "::", "ConfigurationError", ",", "\"API key required.\"", ")", "if", "token", ".", "nil?", "params", ".", "merge!", "(", "format", ":", "API_FORMAT", ",", "key", ":", "token", ")", "url", "=", "\"#{API_URL}#{path}\"", "resp", "=", "RestClient", ".", "get", "(", "url", ",", "params", ":", "params", ")", "do", "|", "response", ",", "request", ",", "result", ",", "&", "block", "|", "case", "response", ".", "code", "when", "200", "response", ".", "return!", "(", "block", ")", "when", "401", "fail", "(", "Goodreads", "::", "Unauthorized", ")", "when", "403", "fail", "(", "Goodreads", "::", "Forbidden", ")", "when", "404", "fail", "(", "Goodreads", "::", "NotFound", ")", "end", "end", "parse", "(", "resp", ")", "end" ]
Perform an API request using API key path - Request path params - Parameters hash
[ "Perform", "an", "API", "request", "using", "API", "key" ]
aa571069ab07190c93b8a8aff77e1da2c79ab694
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/request.rb#L31-L53
train
sosedoff/goodreads
lib/goodreads/request.rb
Goodreads.Request.oauth_request_method
def oauth_request_method(http_method, path, params = {}) fail "OAuth access token required!" unless @oauth_token headers = { "Accept" => "application/xml" } resp = if http_method == :get || http_method == :delete if params url_params = params.map { |k, v| "#{k}=#{v}" }.join("&") path = "#{path}?#{url_params}" end @oauth_token.request(http_method, path, headers) else @oauth_token.request(http_method, path, params || {}, headers) end case resp when Net::HTTPUnauthorized fail Goodreads::Unauthorized when Net::HTTPNotFound fail Goodreads::NotFound end parse(resp) end
ruby
def oauth_request_method(http_method, path, params = {}) fail "OAuth access token required!" unless @oauth_token headers = { "Accept" => "application/xml" } resp = if http_method == :get || http_method == :delete if params url_params = params.map { |k, v| "#{k}=#{v}" }.join("&") path = "#{path}?#{url_params}" end @oauth_token.request(http_method, path, headers) else @oauth_token.request(http_method, path, params || {}, headers) end case resp when Net::HTTPUnauthorized fail Goodreads::Unauthorized when Net::HTTPNotFound fail Goodreads::NotFound end parse(resp) end
[ "def", "oauth_request_method", "(", "http_method", ",", "path", ",", "params", "=", "{", "}", ")", "fail", "\"OAuth access token required!\"", "unless", "@oauth_token", "headers", "=", "{", "\"Accept\"", "=>", "\"application/xml\"", "}", "resp", "=", "if", "http_method", "==", ":get", "||", "http_method", "==", ":delete", "if", "params", "url_params", "=", "params", ".", "map", "{", "|", "k", ",", "v", "|", "\"#{k}=#{v}\"", "}", ".", "join", "(", "\"&\"", ")", "path", "=", "\"#{path}?#{url_params}\"", "end", "@oauth_token", ".", "request", "(", "http_method", ",", "path", ",", "headers", ")", "else", "@oauth_token", ".", "request", "(", "http_method", ",", "path", ",", "params", "||", "{", "}", ",", "headers", ")", "end", "case", "resp", "when", "Net", "::", "HTTPUnauthorized", "fail", "Goodreads", "::", "Unauthorized", "when", "Net", "::", "HTTPNotFound", "fail", "Goodreads", "::", "NotFound", "end", "parse", "(", "resp", ")", "end" ]
Perform an OAuth API request. Goodreads must have been initialized with a valid OAuth access token. http_method - HTTP verb supported by OAuth gem (one of :get, :post, :delete, etc.) path - Request path params - Parameters hash
[ "Perform", "an", "OAuth", "API", "request", ".", "Goodreads", "must", "have", "been", "initialized", "with", "a", "valid", "OAuth", "access", "token", "." ]
aa571069ab07190c93b8a8aff77e1da2c79ab694
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/request.rb#L70-L93
train
sosedoff/goodreads
lib/goodreads/client/groups.rb
Goodreads.Groups.group
def group(group_id) data = request("/group/show", id: group_id) Hashie::Mash.new(data["group"]) end
ruby
def group(group_id) data = request("/group/show", id: group_id) Hashie::Mash.new(data["group"]) end
[ "def", "group", "(", "group_id", ")", "data", "=", "request", "(", "\"/group/show\"", ",", "id", ":", "group_id", ")", "Hashie", "::", "Mash", ".", "new", "(", "data", "[", "\"group\"", "]", ")", "end" ]
Get group details
[ "Get", "group", "details" ]
aa571069ab07190c93b8a8aff77e1da2c79ab694
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/client/groups.rb#L4-L7
train
sosedoff/goodreads
lib/goodreads/client/groups.rb
Goodreads.Groups.group_list
def group_list(user_id, sort = "my_activity") data = request("/group/list", id: user_id, sort: sort) Hashie::Mash.new(data["groups"]["list"]) end
ruby
def group_list(user_id, sort = "my_activity") data = request("/group/list", id: user_id, sort: sort) Hashie::Mash.new(data["groups"]["list"]) end
[ "def", "group_list", "(", "user_id", ",", "sort", "=", "\"my_activity\"", ")", "data", "=", "request", "(", "\"/group/list\"", ",", "id", ":", "user_id", ",", "sort", ":", "sort", ")", "Hashie", "::", "Mash", ".", "new", "(", "data", "[", "\"groups\"", "]", "[", "\"list\"", "]", ")", "end" ]
Get list of groups a given user is a member of
[ "Get", "list", "of", "groups", "a", "given", "user", "is", "a", "member", "of" ]
aa571069ab07190c93b8a8aff77e1da2c79ab694
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/client/groups.rb#L10-L13
train
sosedoff/goodreads
lib/goodreads/client/users.rb
Goodreads.Users.user
def user(id) data = request("/user/show", id: id) Hashie::Mash.new(data["user"]) end
ruby
def user(id) data = request("/user/show", id: id) Hashie::Mash.new(data["user"]) end
[ "def", "user", "(", "id", ")", "data", "=", "request", "(", "\"/user/show\"", ",", "id", ":", "id", ")", "Hashie", "::", "Mash", ".", "new", "(", "data", "[", "\"user\"", "]", ")", "end" ]
Get user details
[ "Get", "user", "details" ]
aa571069ab07190c93b8a8aff77e1da2c79ab694
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/client/users.rb#L5-L8
train
sosedoff/goodreads
lib/goodreads/client/friends.rb
Goodreads.Friends.friends
def friends(user_id, options={}) data = oauth_request("/friend/user/#{user_id}", options) Hashie::Mash.new(data["friends"]) end
ruby
def friends(user_id, options={}) data = oauth_request("/friend/user/#{user_id}", options) Hashie::Mash.new(data["friends"]) end
[ "def", "friends", "(", "user_id", ",", "options", "=", "{", "}", ")", "data", "=", "oauth_request", "(", "\"/friend/user/#{user_id}\"", ",", "options", ")", "Hashie", "::", "Mash", ".", "new", "(", "data", "[", "\"friends\"", "]", ")", "end" ]
Get the specified user's friends user_id - integer or string
[ "Get", "the", "specified", "user", "s", "friends" ]
aa571069ab07190c93b8a8aff77e1da2c79ab694
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/client/friends.rb#L7-L10
train
sosedoff/goodreads
lib/goodreads/client/reviews.rb
Goodreads.Reviews.recent_reviews
def recent_reviews(params = {}) skip_cropped = params.delete(:skip_cropped) || false data = request("/review/recent_reviews", params) return unless data["reviews"] && data["reviews"].key?("review") reviews = data["reviews"]["review"].map { |r| Hashie::Mash.new(r) } reviews = reviews.select { |r| !r.body.include?(r.url) } if skip_cropped reviews end
ruby
def recent_reviews(params = {}) skip_cropped = params.delete(:skip_cropped) || false data = request("/review/recent_reviews", params) return unless data["reviews"] && data["reviews"].key?("review") reviews = data["reviews"]["review"].map { |r| Hashie::Mash.new(r) } reviews = reviews.select { |r| !r.body.include?(r.url) } if skip_cropped reviews end
[ "def", "recent_reviews", "(", "params", "=", "{", "}", ")", "skip_cropped", "=", "params", ".", "delete", "(", ":skip_cropped", ")", "||", "false", "data", "=", "request", "(", "\"/review/recent_reviews\"", ",", "params", ")", "return", "unless", "data", "[", "\"reviews\"", "]", "&&", "data", "[", "\"reviews\"", "]", ".", "key?", "(", "\"review\"", ")", "reviews", "=", "data", "[", "\"reviews\"", "]", "[", "\"review\"", "]", ".", "map", "{", "|", "r", "|", "Hashie", "::", "Mash", ".", "new", "(", "r", ")", "}", "reviews", "=", "reviews", ".", "select", "{", "|", "r", "|", "!", "r", ".", "body", ".", "include?", "(", "r", ".", "url", ")", "}", "if", "skip_cropped", "reviews", "end" ]
Recent reviews from all members. params[:skip_cropped] - Select only non-cropped reviews
[ "Recent", "reviews", "from", "all", "members", "." ]
aa571069ab07190c93b8a8aff77e1da2c79ab694
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/client/reviews.rb#L7-L14
train
sosedoff/goodreads
lib/goodreads/client/reviews.rb
Goodreads.Reviews.review
def review(id) data = request("/review/show", id: id) Hashie::Mash.new(data["review"]) end
ruby
def review(id) data = request("/review/show", id: id) Hashie::Mash.new(data["review"]) end
[ "def", "review", "(", "id", ")", "data", "=", "request", "(", "\"/review/show\"", ",", "id", ":", "id", ")", "Hashie", "::", "Mash", ".", "new", "(", "data", "[", "\"review\"", "]", ")", "end" ]
Get review details
[ "Get", "review", "details" ]
aa571069ab07190c93b8a8aff77e1da2c79ab694
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/client/reviews.rb#L18-L21
train
sosedoff/goodreads
lib/goodreads/client/reviews.rb
Goodreads.Reviews.reviews
def reviews(params = {}) data = request("/review/list", params.merge(v: "2")) reviews = data["reviews"]["review"] if reviews.present? reviews.map { |review| Hashie::Mash.new(review) } else [] end end
ruby
def reviews(params = {}) data = request("/review/list", params.merge(v: "2")) reviews = data["reviews"]["review"] if reviews.present? reviews.map { |review| Hashie::Mash.new(review) } else [] end end
[ "def", "reviews", "(", "params", "=", "{", "}", ")", "data", "=", "request", "(", "\"/review/list\"", ",", "params", ".", "merge", "(", "v", ":", "\"2\"", ")", ")", "reviews", "=", "data", "[", "\"reviews\"", "]", "[", "\"review\"", "]", "if", "reviews", ".", "present?", "reviews", ".", "map", "{", "|", "review", "|", "Hashie", "::", "Mash", ".", "new", "(", "review", ")", "}", "else", "[", "]", "end", "end" ]
Get list of reviews
[ "Get", "list", "of", "reviews" ]
aa571069ab07190c93b8a8aff77e1da2c79ab694
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/client/reviews.rb#L25-L33
train
sosedoff/goodreads
lib/goodreads/client/reviews.rb
Goodreads.Reviews.user_review
def user_review(user_id, book_id, params = {}) data = request('/review/show_by_user_and_book.xml', params.merge(v: "2", user_id: user_id, book_id: book_id)) Hashie::Mash.new(data["review"]) end
ruby
def user_review(user_id, book_id, params = {}) data = request('/review/show_by_user_and_book.xml', params.merge(v: "2", user_id: user_id, book_id: book_id)) Hashie::Mash.new(data["review"]) end
[ "def", "user_review", "(", "user_id", ",", "book_id", ",", "params", "=", "{", "}", ")", "data", "=", "request", "(", "'/review/show_by_user_and_book.xml'", ",", "params", ".", "merge", "(", "v", ":", "\"2\"", ",", "user_id", ":", "user_id", ",", "book_id", ":", "book_id", ")", ")", "Hashie", "::", "Mash", ".", "new", "(", "data", "[", "\"review\"", "]", ")", "end" ]
Get a user's review for a given book
[ "Get", "a", "user", "s", "review", "for", "a", "given", "book" ]
aa571069ab07190c93b8a8aff77e1da2c79ab694
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/client/reviews.rb#L36-L39
train
sosedoff/goodreads
lib/goodreads/client/reviews.rb
Goodreads.Reviews.create_review
def create_review(book_id, params = {}) params = params.merge(book_id: book_id, v: "2") params[:read_at] = params[:read_at].strftime('%Y-%m-%d') if params[:read_at].is_a?(Time) params[:'review[review]'] = params.delete(:review) if params[:review] params[:'review[rating]'] = params.delete(:rating) if params[:rating] params[:'review[read_at]'] = params.delete(:read_at) if params[:read_at] data = oauth_request_method(:post, '/review.xml', params) Hashie::Mash.new(data["review"]) end
ruby
def create_review(book_id, params = {}) params = params.merge(book_id: book_id, v: "2") params[:read_at] = params[:read_at].strftime('%Y-%m-%d') if params[:read_at].is_a?(Time) params[:'review[review]'] = params.delete(:review) if params[:review] params[:'review[rating]'] = params.delete(:rating) if params[:rating] params[:'review[read_at]'] = params.delete(:read_at) if params[:read_at] data = oauth_request_method(:post, '/review.xml', params) Hashie::Mash.new(data["review"]) end
[ "def", "create_review", "(", "book_id", ",", "params", "=", "{", "}", ")", "params", "=", "params", ".", "merge", "(", "book_id", ":", "book_id", ",", "v", ":", "\"2\"", ")", "params", "[", ":read_at", "]", "=", "params", "[", ":read_at", "]", ".", "strftime", "(", "'%Y-%m-%d'", ")", "if", "params", "[", ":read_at", "]", ".", "is_a?", "(", "Time", ")", "params", "[", ":'", "'", "]", "=", "params", ".", "delete", "(", ":review", ")", "if", "params", "[", ":review", "]", "params", "[", ":'", "'", "]", "=", "params", ".", "delete", "(", ":rating", ")", "if", "params", "[", ":rating", "]", "params", "[", ":'", "'", "]", "=", "params", ".", "delete", "(", ":read_at", ")", "if", "params", "[", ":read_at", "]", "data", "=", "oauth_request_method", "(", ":post", ",", "'/review.xml'", ",", "params", ")", "Hashie", "::", "Mash", ".", "new", "(", "data", "[", "\"review\"", "]", ")", "end" ]
Add review for a book Params can include :review, :rating, and :shelf review: text of the review (optional) rating: rating (0-5) (optional, default is 0 (no rating)) shelf: Name of shelf to add book to (optional, must exist, see: shelves.list) Note that Goodreads API documentation says that this endpoint accepts the read_at parameter but it does not appear to work as of 2018-06.
[ "Add", "review", "for", "a", "book" ]
aa571069ab07190c93b8a8aff77e1da2c79ab694
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/client/reviews.rb#L51-L63
train
sosedoff/goodreads
lib/goodreads/client/reviews.rb
Goodreads.Reviews.edit_review
def edit_review(review_id, params = {}) params = params.merge(v: "2") params[:read_at] = params[:read_at].strftime('%Y-%m-%d') if params[:read_at].is_a?(Time) params[:'review[review]'] = params.delete(:review) if params[:review] params[:'review[rating]'] = params.delete(:rating) if params[:rating] params[:'review[read_at]'] = params.delete(:read_at) if params[:read_at] # Documentation says that you should use HTTP PUT, but API returns # 401 Unauthorized when PUT is used instead of POST data = oauth_request_method(:post, "/review/#{review_id}.xml", params) Hashie::Mash.new(data["review"]) end
ruby
def edit_review(review_id, params = {}) params = params.merge(v: "2") params[:read_at] = params[:read_at].strftime('%Y-%m-%d') if params[:read_at].is_a?(Time) params[:'review[review]'] = params.delete(:review) if params[:review] params[:'review[rating]'] = params.delete(:rating) if params[:rating] params[:'review[read_at]'] = params.delete(:read_at) if params[:read_at] # Documentation says that you should use HTTP PUT, but API returns # 401 Unauthorized when PUT is used instead of POST data = oauth_request_method(:post, "/review/#{review_id}.xml", params) Hashie::Mash.new(data["review"]) end
[ "def", "edit_review", "(", "review_id", ",", "params", "=", "{", "}", ")", "params", "=", "params", ".", "merge", "(", "v", ":", "\"2\"", ")", "params", "[", ":read_at", "]", "=", "params", "[", ":read_at", "]", ".", "strftime", "(", "'%Y-%m-%d'", ")", "if", "params", "[", ":read_at", "]", ".", "is_a?", "(", "Time", ")", "params", "[", ":'", "'", "]", "=", "params", ".", "delete", "(", ":review", ")", "if", "params", "[", ":review", "]", "params", "[", ":'", "'", "]", "=", "params", ".", "delete", "(", ":rating", ")", "if", "params", "[", ":rating", "]", "params", "[", ":'", "'", "]", "=", "params", ".", "delete", "(", ":read_at", ")", "if", "params", "[", ":read_at", "]", "# Documentation says that you should use HTTP PUT, but API returns", "# 401 Unauthorized when PUT is used instead of POST", "data", "=", "oauth_request_method", "(", ":post", ",", "\"/review/#{review_id}.xml\"", ",", "params", ")", "Hashie", "::", "Mash", ".", "new", "(", "data", "[", "\"review\"", "]", ")", "end" ]
Edit review for a book Params can include :review, :rating, :read_at and :shelf, and :finished review: text of the review (optional) rating: rating (0-5) (optional, default is 0 (no rating)) shelf: Name of shelf to add book to (optional, must exist, see: shelves.list) read_at: Time object or String in YYYY-MM-DD format (optional) finished: true to mark finished reading (optional) shelf: Name of shelf to add book to (optional, must exist, see: shelves.list)
[ "Edit", "review", "for", "a", "book" ]
aa571069ab07190c93b8a8aff77e1da2c79ab694
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/client/reviews.rb#L75-L89
train
sosedoff/goodreads
lib/goodreads/client/books.rb
Goodreads.Books.search_books
def search_books(query, params = {}) params[:q] = query.to_s.strip data = request("/search/index", params) Hashie::Mash.new(data["search"]) end
ruby
def search_books(query, params = {}) params[:q] = query.to_s.strip data = request("/search/index", params) Hashie::Mash.new(data["search"]) end
[ "def", "search_books", "(", "query", ",", "params", "=", "{", "}", ")", "params", "[", ":q", "]", "=", "query", ".", "to_s", ".", "strip", "data", "=", "request", "(", "\"/search/index\"", ",", "params", ")", "Hashie", "::", "Mash", ".", "new", "(", "data", "[", "\"search\"", "]", ")", "end" ]
Search for books query - Text to match against book title, author, and ISBN fields. options - Optional search parameters options[:page] - Which page to returns (default: 1) options[:field] - Search field. One of: title, author, or genre (default is all)
[ "Search", "for", "books" ]
aa571069ab07190c93b8a8aff77e1da2c79ab694
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/client/books.rb#L11-L15
train
sosedoff/goodreads
lib/goodreads/client/authors.rb
Goodreads.Authors.author
def author(id, params = {}) params[:id] = id data = request("/author/show", params) Hashie::Mash.new(data["author"]) end
ruby
def author(id, params = {}) params[:id] = id data = request("/author/show", params) Hashie::Mash.new(data["author"]) end
[ "def", "author", "(", "id", ",", "params", "=", "{", "}", ")", "params", "[", ":id", "]", "=", "id", "data", "=", "request", "(", "\"/author/show\"", ",", "params", ")", "Hashie", "::", "Mash", ".", "new", "(", "data", "[", "\"author\"", "]", ")", "end" ]
Get author details
[ "Get", "author", "details" ]
aa571069ab07190c93b8a8aff77e1da2c79ab694
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/client/authors.rb#L5-L9
train
sosedoff/goodreads
lib/goodreads/client/authors.rb
Goodreads.Authors.author_by_name
def author_by_name(name, params = {}) params[:id] = name name_encoded = URI.encode(name) data = request("/api/author_url/#{name_encoded}", params) Hashie::Mash.new(data["author"]) end
ruby
def author_by_name(name, params = {}) params[:id] = name name_encoded = URI.encode(name) data = request("/api/author_url/#{name_encoded}", params) Hashie::Mash.new(data["author"]) end
[ "def", "author_by_name", "(", "name", ",", "params", "=", "{", "}", ")", "params", "[", ":id", "]", "=", "name", "name_encoded", "=", "URI", ".", "encode", "(", "name", ")", "data", "=", "request", "(", "\"/api/author_url/#{name_encoded}\"", ",", "params", ")", "Hashie", "::", "Mash", ".", "new", "(", "data", "[", "\"author\"", "]", ")", "end" ]
Search for an author by name
[ "Search", "for", "an", "author", "by", "name" ]
aa571069ab07190c93b8a8aff77e1da2c79ab694
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/client/authors.rb#L13-L18
train
sdaubert/packetgen
lib/packetgen/packet.rb
PacketGen.Packet.insert
def insert(prev, protocol, options={}) klass = check_protocol(protocol) nxt = prev.body header = klass.new(options.merge!(packet: self)) add_header header, previous_header: prev idx = headers.index(prev) + 1 headers[idx, 0] = header header[:body] = nxt self end
ruby
def insert(prev, protocol, options={}) klass = check_protocol(protocol) nxt = prev.body header = klass.new(options.merge!(packet: self)) add_header header, previous_header: prev idx = headers.index(prev) + 1 headers[idx, 0] = header header[:body] = nxt self end
[ "def", "insert", "(", "prev", ",", "protocol", ",", "options", "=", "{", "}", ")", "klass", "=", "check_protocol", "(", "protocol", ")", "nxt", "=", "prev", ".", "body", "header", "=", "klass", ".", "new", "(", "options", ".", "merge!", "(", "packet", ":", "self", ")", ")", "add_header", "header", ",", "previous_header", ":", "prev", "idx", "=", "headers", ".", "index", "(", "prev", ")", "+", "1", "headers", "[", "idx", ",", "0", "]", "=", "header", "header", "[", ":body", "]", "=", "nxt", "self", "end" ]
Insert a header in packet @param [Header] prev header after which insert new one @param [String] protocol protocol to insert @param [Hash] options protocol specific options @return [self] @raise [ArgumentError] unknown protocol
[ "Insert", "a", "header", "in", "packet" ]
fd093a638d5b5dfe0440fa90fc75b5647f560be3
https://github.com/sdaubert/packetgen/blob/fd093a638d5b5dfe0440fa90fc75b5647f560be3/lib/packetgen/packet.rb#L150-L160
train
sdaubert/packetgen
lib/packetgen/packet.rb
PacketGen.Packet.encapsulate
def encapsulate(other, parsing: false) other.headers.each_with_index do |h, i| add_header h, parsing: (i > 0) || parsing end end
ruby
def encapsulate(other, parsing: false) other.headers.each_with_index do |h, i| add_header h, parsing: (i > 0) || parsing end end
[ "def", "encapsulate", "(", "other", ",", "parsing", ":", "false", ")", "other", ".", "headers", ".", "each_with_index", "do", "|", "h", ",", "i", "|", "add_header", "h", ",", "parsing", ":", "(", "i", ">", "0", ")", "||", "parsing", "end", "end" ]
Encapulate another packet in +self+ @param [Packet] other @param [Boolean] parsing set to +true+ to not update last current header field from binding with first other's one. Use only when current header field has its value set accordingly. @return [self] +self+ with new headers from +other+ @since 1.1.0
[ "Encapulate", "another", "packet", "in", "+", "self", "+" ]
fd093a638d5b5dfe0440fa90fc75b5647f560be3
https://github.com/sdaubert/packetgen/blob/fd093a638d5b5dfe0440fa90fc75b5647f560be3/lib/packetgen/packet.rb#L255-L259
train
sdaubert/packetgen
lib/packetgen/packet.rb
PacketGen.Packet.decapsulate
def decapsulate(*hdrs) hdrs.each do |hdr| idx = headers.index(hdr) raise FormatError, 'header not in packet!' if idx.nil? prev_hdr = idx > 0 ? headers[idx - 1] : nil next_hdr = (idx + 1) < headers.size ? headers[idx + 1] : nil headers.delete_at(idx) add_header(next_hdr, previous_header: prev_hdr) if prev_hdr && next_hdr end rescue ArgumentError => ex raise FormatError, ex.message end
ruby
def decapsulate(*hdrs) hdrs.each do |hdr| idx = headers.index(hdr) raise FormatError, 'header not in packet!' if idx.nil? prev_hdr = idx > 0 ? headers[idx - 1] : nil next_hdr = (idx + 1) < headers.size ? headers[idx + 1] : nil headers.delete_at(idx) add_header(next_hdr, previous_header: prev_hdr) if prev_hdr && next_hdr end rescue ArgumentError => ex raise FormatError, ex.message end
[ "def", "decapsulate", "(", "*", "hdrs", ")", "hdrs", ".", "each", "do", "|", "hdr", "|", "idx", "=", "headers", ".", "index", "(", "hdr", ")", "raise", "FormatError", ",", "'header not in packet!'", "if", "idx", ".", "nil?", "prev_hdr", "=", "idx", ">", "0", "?", "headers", "[", "idx", "-", "1", "]", ":", "nil", "next_hdr", "=", "(", "idx", "+", "1", ")", "<", "headers", ".", "size", "?", "headers", "[", "idx", "+", "1", "]", ":", "nil", "headers", ".", "delete_at", "(", "idx", ")", "add_header", "(", "next_hdr", ",", "previous_header", ":", "prev_hdr", ")", "if", "prev_hdr", "&&", "next_hdr", "end", "rescue", "ArgumentError", "=>", "ex", "raise", "FormatError", ",", "ex", ".", "message", "end" ]
Remove headers from +self+ @param [Array<Header>] hdrs @return [self] +self+ with some headers removed @raise [FormatError] any headers not in +self+ @raise [FormatError] removed headers result in an unknown binding @since 1.1.0
[ "Remove", "headers", "from", "+", "self", "+" ]
fd093a638d5b5dfe0440fa90fc75b5647f560be3
https://github.com/sdaubert/packetgen/blob/fd093a638d5b5dfe0440fa90fc75b5647f560be3/lib/packetgen/packet.rb#L267-L279
train
sdaubert/packetgen
lib/packetgen/packet.rb
PacketGen.Packet.parse
def parse(binary_str, first_header: nil) headers.clear if first_header.nil? # No decoding forced for first header. Have to guess it! first_header = guess_first_header(binary_str) if first_header.nil? raise ParseError, 'cannot identify first header in string' end end add first_header headers[-1, 1] = last_header.read(binary_str) # Decode upper headers recursively decode_bottom_up self end
ruby
def parse(binary_str, first_header: nil) headers.clear if first_header.nil? # No decoding forced for first header. Have to guess it! first_header = guess_first_header(binary_str) if first_header.nil? raise ParseError, 'cannot identify first header in string' end end add first_header headers[-1, 1] = last_header.read(binary_str) # Decode upper headers recursively decode_bottom_up self end
[ "def", "parse", "(", "binary_str", ",", "first_header", ":", "nil", ")", "headers", ".", "clear", "if", "first_header", ".", "nil?", "# No decoding forced for first header. Have to guess it!", "first_header", "=", "guess_first_header", "(", "binary_str", ")", "if", "first_header", ".", "nil?", "raise", "ParseError", ",", "'cannot identify first header in string'", "end", "end", "add", "first_header", "headers", "[", "-", "1", ",", "1", "]", "=", "last_header", ".", "read", "(", "binary_str", ")", "# Decode upper headers recursively", "decode_bottom_up", "self", "end" ]
Parse a binary string and populate Packet from it. @param [String] binary_str @param [String,nil] first_header First protocol header. +nil+ means discover it! @return [Packet] self @raise [ArgumentError] +first_header+ is an unknown header
[ "Parse", "a", "binary", "string", "and", "populate", "Packet", "from", "it", "." ]
fd093a638d5b5dfe0440fa90fc75b5647f560be3
https://github.com/sdaubert/packetgen/blob/fd093a638d5b5dfe0440fa90fc75b5647f560be3/lib/packetgen/packet.rb#L286-L303
train
sdaubert/packetgen
lib/packetgen/packet.rb
PacketGen.Packet.inspect
def inspect str = Inspect.dashed_line(self.class) headers.each do |header| str << header.inspect end str << Inspect.inspect_body(body) end
ruby
def inspect str = Inspect.dashed_line(self.class) headers.each do |header| str << header.inspect end str << Inspect.inspect_body(body) end
[ "def", "inspect", "str", "=", "Inspect", ".", "dashed_line", "(", "self", ".", "class", ")", "headers", ".", "each", "do", "|", "header", "|", "str", "<<", "header", ".", "inspect", "end", "str", "<<", "Inspect", ".", "inspect_body", "(", "body", ")", "end" ]
Get packet as a pretty formatted string. @return [String]
[ "Get", "packet", "as", "a", "pretty", "formatted", "string", "." ]
fd093a638d5b5dfe0440fa90fc75b5647f560be3
https://github.com/sdaubert/packetgen/blob/fd093a638d5b5dfe0440fa90fc75b5647f560be3/lib/packetgen/packet.rb#L307-L313
train
sdaubert/packetgen
lib/packetgen/packet.rb
PacketGen.Packet.check_protocol
def check_protocol(protocol) klass = Header.get_header_class_by_name(protocol) raise ArgumentError, "unknown #{protocol} protocol" if klass.nil? klass end
ruby
def check_protocol(protocol) klass = Header.get_header_class_by_name(protocol) raise ArgumentError, "unknown #{protocol} protocol" if klass.nil? klass end
[ "def", "check_protocol", "(", "protocol", ")", "klass", "=", "Header", ".", "get_header_class_by_name", "(", "protocol", ")", "raise", "ArgumentError", ",", "\"unknown #{protocol} protocol\"", "if", "klass", ".", "nil?", "klass", "end" ]
check if protocol is known @param [String] protocol @raise [ArgumentError] unknown protocol
[ "check", "if", "protocol", "is", "known" ]
fd093a638d5b5dfe0440fa90fc75b5647f560be3
https://github.com/sdaubert/packetgen/blob/fd093a638d5b5dfe0440fa90fc75b5647f560be3/lib/packetgen/packet.rb#L403-L408
train
sdaubert/packetgen
lib/packetgen/packet.rb
PacketGen.Packet.add_header
def add_header(header, previous_header: nil, parsing: false) prev_header = previous_header || last_header if prev_header bindings = prev_header.class.known_headers[header.class] bindings = prev_header.class.known_headers[header.class.superclass] if bindings.nil? if bindings.nil? msg = "#{prev_header.class} knowns no layer association with #{header.protocol_name}. ".dup msg << "Try #{prev_header.class}.bind_layer(#{header.class}, " msg << "#{prev_header.method_name}_proto_field: " msg << "value_for_#{header.method_name})" raise ArgumentError, msg end bindings.set(prev_header) if !bindings.empty? && !parsing prev_header[:body] = header end header.packet = self headers << header unless previous_header return if respond_to? header.method_name add_magic_header_method header end
ruby
def add_header(header, previous_header: nil, parsing: false) prev_header = previous_header || last_header if prev_header bindings = prev_header.class.known_headers[header.class] bindings = prev_header.class.known_headers[header.class.superclass] if bindings.nil? if bindings.nil? msg = "#{prev_header.class} knowns no layer association with #{header.protocol_name}. ".dup msg << "Try #{prev_header.class}.bind_layer(#{header.class}, " msg << "#{prev_header.method_name}_proto_field: " msg << "value_for_#{header.method_name})" raise ArgumentError, msg end bindings.set(prev_header) if !bindings.empty? && !parsing prev_header[:body] = header end header.packet = self headers << header unless previous_header return if respond_to? header.method_name add_magic_header_method header end
[ "def", "add_header", "(", "header", ",", "previous_header", ":", "nil", ",", "parsing", ":", "false", ")", "prev_header", "=", "previous_header", "||", "last_header", "if", "prev_header", "bindings", "=", "prev_header", ".", "class", ".", "known_headers", "[", "header", ".", "class", "]", "bindings", "=", "prev_header", ".", "class", ".", "known_headers", "[", "header", ".", "class", ".", "superclass", "]", "if", "bindings", ".", "nil?", "if", "bindings", ".", "nil?", "msg", "=", "\"#{prev_header.class} knowns no layer association with #{header.protocol_name}. \"", ".", "dup", "msg", "<<", "\"Try #{prev_header.class}.bind_layer(#{header.class}, \"", "msg", "<<", "\"#{prev_header.method_name}_proto_field: \"", "msg", "<<", "\"value_for_#{header.method_name})\"", "raise", "ArgumentError", ",", "msg", "end", "bindings", ".", "set", "(", "prev_header", ")", "if", "!", "bindings", ".", "empty?", "&&", "!", "parsing", "prev_header", "[", ":body", "]", "=", "header", "end", "header", ".", "packet", "=", "self", "headers", "<<", "header", "unless", "previous_header", "return", "if", "respond_to?", "header", ".", "method_name", "add_magic_header_method", "header", "end" ]
Add a header to packet @param [Header::Base] header @param [Header::Base] previous_header @param [Boolean] parsing @return [void]
[ "Add", "a", "header", "to", "packet" ]
fd093a638d5b5dfe0440fa90fc75b5647f560be3
https://github.com/sdaubert/packetgen/blob/fd093a638d5b5dfe0440fa90fc75b5647f560be3/lib/packetgen/packet.rb#L415-L437
train
sdaubert/packetgen
lib/packetgen/packet.rb
PacketGen.Packet.guess_first_header
def guess_first_header(binary_str) first_header = nil Header.all.each do |hklass| hdr = hklass.new(packet: self) # #read may return another object (more specific class) hdr = hdr.read(binary_str) # First header is found when, for one known header, # * +#parse?+ is true # * it exists a known binding with a upper header next unless hdr.parse? first_header = hklass.to_s.gsub(/.*::/, '') if search_upper_header(hdr) break unless first_header.nil? end first_header end
ruby
def guess_first_header(binary_str) first_header = nil Header.all.each do |hklass| hdr = hklass.new(packet: self) # #read may return another object (more specific class) hdr = hdr.read(binary_str) # First header is found when, for one known header, # * +#parse?+ is true # * it exists a known binding with a upper header next unless hdr.parse? first_header = hklass.to_s.gsub(/.*::/, '') if search_upper_header(hdr) break unless first_header.nil? end first_header end
[ "def", "guess_first_header", "(", "binary_str", ")", "first_header", "=", "nil", "Header", ".", "all", ".", "each", "do", "|", "hklass", "|", "hdr", "=", "hklass", ".", "new", "(", "packet", ":", "self", ")", "# #read may return another object (more specific class)", "hdr", "=", "hdr", ".", "read", "(", "binary_str", ")", "# First header is found when, for one known header,", "# * +#parse?+ is true", "# * it exists a known binding with a upper header", "next", "unless", "hdr", ".", "parse?", "first_header", "=", "hklass", ".", "to_s", ".", "gsub", "(", "/", "/", ",", "''", ")", "if", "search_upper_header", "(", "hdr", ")", "break", "unless", "first_header", ".", "nil?", "end", "first_header", "end" ]
Try to guess header from +binary_str+ @param [String] binary_str @return [String] header/protocol name
[ "Try", "to", "guess", "header", "from", "+", "binary_str", "+" ]
fd093a638d5b5dfe0440fa90fc75b5647f560be3
https://github.com/sdaubert/packetgen/blob/fd093a638d5b5dfe0440fa90fc75b5647f560be3/lib/packetgen/packet.rb#L450-L465
train
sdaubert/packetgen
lib/packetgen/packet.rb
PacketGen.Packet.decode_bottom_up
def decode_bottom_up loop do last_known_hdr = last_header break if !last_known_hdr.respond_to?(:body) || last_known_hdr.body.empty? nh = search_upper_header(last_known_hdr) break if nh.nil? nheader = nh.new(packet: self) nheader = nheader.read(last_known_hdr.body) next unless nheader.parse? add_header nheader, parsing: true break if last_header == last_known_hdr end end
ruby
def decode_bottom_up loop do last_known_hdr = last_header break if !last_known_hdr.respond_to?(:body) || last_known_hdr.body.empty? nh = search_upper_header(last_known_hdr) break if nh.nil? nheader = nh.new(packet: self) nheader = nheader.read(last_known_hdr.body) next unless nheader.parse? add_header nheader, parsing: true break if last_header == last_known_hdr end end
[ "def", "decode_bottom_up", "loop", "do", "last_known_hdr", "=", "last_header", "break", "if", "!", "last_known_hdr", ".", "respond_to?", "(", ":body", ")", "||", "last_known_hdr", ".", "body", ".", "empty?", "nh", "=", "search_upper_header", "(", "last_known_hdr", ")", "break", "if", "nh", ".", "nil?", "nheader", "=", "nh", ".", "new", "(", "packet", ":", "self", ")", "nheader", "=", "nheader", ".", "read", "(", "last_known_hdr", ".", "body", ")", "next", "unless", "nheader", ".", "parse?", "add_header", "nheader", ",", "parsing", ":", "true", "break", "if", "last_header", "==", "last_known_hdr", "end", "end" ]
Decode packet bottom up @return [void]
[ "Decode", "packet", "bottom", "up" ]
fd093a638d5b5dfe0440fa90fc75b5647f560be3
https://github.com/sdaubert/packetgen/blob/fd093a638d5b5dfe0440fa90fc75b5647f560be3/lib/packetgen/packet.rb#L469-L484
train
sdaubert/packetgen
lib/packetgen/packet.rb
PacketGen.Packet.search_upper_header
def search_upper_header(hdr) hdr.class.known_headers.each do |nh, bindings| return nh if bindings.check?(hdr) end nil end
ruby
def search_upper_header(hdr) hdr.class.known_headers.each do |nh, bindings| return nh if bindings.check?(hdr) end nil end
[ "def", "search_upper_header", "(", "hdr", ")", "hdr", ".", "class", ".", "known_headers", ".", "each", "do", "|", "nh", ",", "bindings", "|", "return", "nh", "if", "bindings", ".", "check?", "(", "hdr", ")", "end", "nil", "end" ]
Search a upper header for +hdr+ @param [Header::Base] hdr @return [void] @yieldparam [Header::Base] found upper header
[ "Search", "a", "upper", "header", "for", "+", "hdr", "+" ]
fd093a638d5b5dfe0440fa90fc75b5647f560be3
https://github.com/sdaubert/packetgen/blob/fd093a638d5b5dfe0440fa90fc75b5647f560be3/lib/packetgen/packet.rb#L490-L496
train
madzhuga/rails_workflow
app/models/rails_workflow/process_template.rb
RailsWorkflow.ProcessTemplate.dependent_operations
def dependent_operations(operation) operations.select do |top| top.dependencies.select do |dp| dp['id'] == operation.template.id && dp['statuses'].include?(operation.status) end.present? end end
ruby
def dependent_operations(operation) operations.select do |top| top.dependencies.select do |dp| dp['id'] == operation.template.id && dp['statuses'].include?(operation.status) end.present? end end
[ "def", "dependent_operations", "(", "operation", ")", "operations", ".", "select", "do", "|", "top", "|", "top", ".", "dependencies", ".", "select", "do", "|", "dp", "|", "dp", "[", "'id'", "]", "==", "operation", ".", "template", ".", "id", "&&", "dp", "[", "'statuses'", "]", ".", "include?", "(", "operation", ".", "status", ")", "end", ".", "present?", "end", "end" ]
here we calculate template operations that depends on given process operation status and template id
[ "here", "we", "calculate", "template", "operations", "that", "depends", "on", "given", "process", "operation", "status", "and", "template", "id" ]
881ccbc4efd58b48a5125f3850ecccfc84490f94
https://github.com/madzhuga/rails_workflow/blob/881ccbc4efd58b48a5125f3850ecccfc84490f94/app/models/rails_workflow/process_template.rb#L32-L39
train
madzhuga/rails_workflow
lib/rails_workflow/error_builder.rb
RailsWorkflow.ErrorBuilder.target
def target @target ||= begin parent = context[:parent] if parent.is_a? RailsWorkflow::Operation parent.becomes(RailsWorkflow::Operation) elsif parent.is_a? RailsWorkflow::Process parent.becomes(RailsWorkflow::Process) end end end
ruby
def target @target ||= begin parent = context[:parent] if parent.is_a? RailsWorkflow::Operation parent.becomes(RailsWorkflow::Operation) elsif parent.is_a? RailsWorkflow::Process parent.becomes(RailsWorkflow::Process) end end end
[ "def", "target", "@target", "||=", "begin", "parent", "=", "context", "[", ":parent", "]", "if", "parent", ".", "is_a?", "RailsWorkflow", "::", "Operation", "parent", ".", "becomes", "(", "RailsWorkflow", "::", "Operation", ")", "elsif", "parent", ".", "is_a?", "RailsWorkflow", "::", "Process", "parent", ".", "becomes", "(", "RailsWorkflow", "::", "Process", ")", "end", "end", "end" ]
Changing custom process or operation classes to default classes. If we store error with a custom class and somebody will delete or rename this class - we will not be able to load error.
[ "Changing", "custom", "process", "or", "operation", "classes", "to", "default", "classes", ".", "If", "we", "store", "error", "with", "a", "custom", "class", "and", "somebody", "will", "delete", "or", "rename", "this", "class", "-", "we", "will", "not", "be", "able", "to", "load", "error", "." ]
881ccbc4efd58b48a5125f3850ecccfc84490f94
https://github.com/madzhuga/rails_workflow/blob/881ccbc4efd58b48a5125f3850ecccfc84490f94/lib/rails_workflow/error_builder.rb#L38-L47
train
buruzaemon/natto
lib/natto/struct.rb
Natto.MeCabStruct.method_missing
def method_missing(attr_name) member_sym = attr_name.id2name.to_sym self[member_sym] rescue ArgumentError # `member_sym` field doesn't exist. raise(NoMethodError.new("undefined method '#{attr_name}' for #{self}")) end
ruby
def method_missing(attr_name) member_sym = attr_name.id2name.to_sym self[member_sym] rescue ArgumentError # `member_sym` field doesn't exist. raise(NoMethodError.new("undefined method '#{attr_name}' for #{self}")) end
[ "def", "method_missing", "(", "attr_name", ")", "member_sym", "=", "attr_name", ".", "id2name", ".", "to_sym", "self", "[", "member_sym", "]", "rescue", "ArgumentError", "# `member_sym` field doesn't exist.", "raise", "(", "NoMethodError", ".", "new", "(", "\"undefined method '#{attr_name}' for #{self}\"", ")", ")", "end" ]
Provides accessor methods for the members of the MeCab struct. @param attr_name [String] attribute name @return member values for the MeCab struct @raise [NoMethodError] if `attr_name` is not a member of this MeCab struct
[ "Provides", "accessor", "methods", "for", "the", "members", "of", "the", "MeCab", "struct", "." ]
7801f1294dcda534b707024182a1b5743d0e41e8
https://github.com/buruzaemon/natto/blob/7801f1294dcda534b707024182a1b5743d0e41e8/lib/natto/struct.rb#L16-L21
train
buruzaemon/natto
lib/natto/natto.rb
Natto.MeCab.parse
def parse(text, constraints={}) if text.nil? raise ArgumentError.new 'Text to parse cannot be nil' elsif constraints[:boundary_constraints] if !(constraints[:boundary_constraints].is_a?(Regexp) || constraints[:boundary_constraints].is_a?(String)) raise ArgumentError.new 'boundary constraints must be a Regexp or String' end elsif constraints[:feature_constraints] && !constraints[:feature_constraints].is_a?(Hash) raise ArgumentError.new 'feature constraints must be a Hash' elsif @options[:partial] && !text.end_with?("\n") raise ArgumentError.new 'partial parsing requires new-line char at end of text' end if block_given? @parse_tonodes.call(text, constraints).each {|n| yield n } else @parse_tostr.call(text, constraints) end end
ruby
def parse(text, constraints={}) if text.nil? raise ArgumentError.new 'Text to parse cannot be nil' elsif constraints[:boundary_constraints] if !(constraints[:boundary_constraints].is_a?(Regexp) || constraints[:boundary_constraints].is_a?(String)) raise ArgumentError.new 'boundary constraints must be a Regexp or String' end elsif constraints[:feature_constraints] && !constraints[:feature_constraints].is_a?(Hash) raise ArgumentError.new 'feature constraints must be a Hash' elsif @options[:partial] && !text.end_with?("\n") raise ArgumentError.new 'partial parsing requires new-line char at end of text' end if block_given? @parse_tonodes.call(text, constraints).each {|n| yield n } else @parse_tostr.call(text, constraints) end end
[ "def", "parse", "(", "text", ",", "constraints", "=", "{", "}", ")", "if", "text", ".", "nil?", "raise", "ArgumentError", ".", "new", "'Text to parse cannot be nil'", "elsif", "constraints", "[", ":boundary_constraints", "]", "if", "!", "(", "constraints", "[", ":boundary_constraints", "]", ".", "is_a?", "(", "Regexp", ")", "||", "constraints", "[", ":boundary_constraints", "]", ".", "is_a?", "(", "String", ")", ")", "raise", "ArgumentError", ".", "new", "'boundary constraints must be a Regexp or String'", "end", "elsif", "constraints", "[", ":feature_constraints", "]", "&&", "!", "constraints", "[", ":feature_constraints", "]", ".", "is_a?", "(", "Hash", ")", "raise", "ArgumentError", ".", "new", "'feature constraints must be a Hash'", "elsif", "@options", "[", ":partial", "]", "&&", "!", "text", ".", "end_with?", "(", "\"\\n\"", ")", "raise", "ArgumentError", ".", "new", "'partial parsing requires new-line char at end of text'", "end", "if", "block_given?", "@parse_tonodes", ".", "call", "(", "text", ",", "constraints", ")", ".", "each", "{", "|", "n", "|", "yield", "n", "}", "else", "@parse_tostr", ".", "call", "(", "text", ",", "constraints", ")", "end", "end" ]
Initializes the wrapped Tagger instance with the given `options`. Options supported are: - :rcfile -- resource file - :dicdir -- system dicdir - :userdic -- user dictionary - :lattice_level -- lattice information level (DEPRECATED) - :output_format_type -- output format type (wakati, chasen, yomi, etc.) - :all_morphs -- output all morphs (default false) - :nbest -- output N best results (integer, default 1), requires lattice level >= 1 - :partial -- partial parsing mode - :marginal -- output marginal probability - :max_grouping_size -- maximum grouping size for unknown words (default 24) - :node_format -- user-defined node format - :unk_format -- user-defined unknown node format - :bos_format -- user-defined beginning-of-sentence format - :eos_format -- user-defined end-of-sentence format - :eon_format -- user-defined end-of-NBest format - :unk_feature -- feature for unknown word - :input_buffer_size -- set input buffer size (default 8192) - :allocate_sentence -- allocate new memory for input sentence - :theta -- temperature parameter theta (float, default 0.75) - :cost_factor -- cost factor (integer, default 700) <p>MeCab command-line arguments (-F) or long (--node-format) may be used in addition to Ruby-style hashs</p> <i>Use single-quotes to preserve format options that contain escape chars.</i><br/> e.g.<br/> nm = Natto::MeCab.new(node_format: '%m¥t%f[7]¥n') => #<Natto::MeCab:0x00000803503ee8 \ @model=#<FFI::Pointer address=0x00000802b6d9c0>, \ @tagger=#<FFI::Pointer address=0x00000802ad3ec0>, \ @lattice=#<FFI::Pointer address=0x000008035f3980>, \ @libpath="/usr/local/lib/libmecab.so", \ @options={:node_format=>"%m¥t%f[7]¥n"}, \ @dicts=[#<Natto::DictionaryInfo:0x000008035038f8 \ @filepath="/usr/local/lib/mecab/dic/ipadic/sys.dic" \ charset=utf8, \ type=0>] \ @version=0.996> puts nm.parse('才能とは求める人間に与えられるものではない。') 才能 サイノウ と ト は ハ 求 モトメル 人間 ニンゲン に ニ 与え アタエ られる ラレル もの モノ で デ は ハ ない ナイ 。 。 EOS @param options [Hash, String] the MeCab options @raise [MeCabError] if MeCab cannot be initialized with the given `options` Parses the given `text`, returning the MeCab output as a single string. If a block is passed to this method, then node parsing will be used and each node yielded to the given block. Boundary constraint parsing is available via passing in the `boundary_constraints` key in the `options` hash. Boundary constraints parsing provides hints to MeCab on where the morpheme boundaries in the given `text` are located. `boundary_constraints` value may be either a `Regexp` or `String`; please see [String#scan](http://ruby-doc.org/core-2.2.1/String.html#method-i-scan) The boundary constraint parsed output will be returned as a single string, unless a block is passed to this method for node parsing. Feature constraint parsing is available by passing in the `feature_constraints` key in the `options` hash. Feature constraints parsing provides instructions to MeCab to use the feature indicated for any morpheme that is an exact match for the given key. `feature_constraints` is a hash mapping a specific morpheme (String) to a corresponding feature value (String). @param text [String] the Japanese text to parse @param constraints [Hash] `boundary_constraints` or `feature_constraints` @return [String] parsing result from MeCab @raise [MeCabError] if the MeCab Tagger cannot parse the given `text` @raise [ArgumentError] if the given string `text` argument is `nil` @see MeCabNode
[ "Initializes", "the", "wrapped", "Tagger", "instance", "with", "the", "given", "options", "." ]
7801f1294dcda534b707024182a1b5743d0e41e8
https://github.com/buruzaemon/natto/blob/7801f1294dcda534b707024182a1b5743d0e41e8/lib/natto/natto.rb#L466-L485
train
flapjack/flapjack
lib/flapjack/utility.rb
Flapjack.Utility.truncate
def truncate(str, length, options = {}) text = str.dup options[:omission] ||= "..." length_with_room_for_omission = length - options[:omission].length stop = options[:separator] ? (text.rindex(options[:separator], length_with_room_for_omission) || length_with_room_for_omission) : length_with_room_for_omission (text.length > length ? text[0...stop] + options[:omission] : text).to_s end
ruby
def truncate(str, length, options = {}) text = str.dup options[:omission] ||= "..." length_with_room_for_omission = length - options[:omission].length stop = options[:separator] ? (text.rindex(options[:separator], length_with_room_for_omission) || length_with_room_for_omission) : length_with_room_for_omission (text.length > length ? text[0...stop] + options[:omission] : text).to_s end
[ "def", "truncate", "(", "str", ",", "length", ",", "options", "=", "{", "}", ")", "text", "=", "str", ".", "dup", "options", "[", ":omission", "]", "||=", "\"...\"", "length_with_room_for_omission", "=", "length", "-", "options", "[", ":omission", "]", ".", "length", "stop", "=", "options", "[", ":separator", "]", "?", "(", "text", ".", "rindex", "(", "options", "[", ":separator", "]", ",", "length_with_room_for_omission", ")", "||", "length_with_room_for_omission", ")", ":", "length_with_room_for_omission", "(", "text", ".", "length", ">", "length", "?", "text", "[", "0", "...", "stop", "]", "+", "options", "[", ":omission", "]", ":", "text", ")", ".", "to_s", "end" ]
copied from ActiveSupport
[ "copied", "from", "ActiveSupport" ]
1f27caebf5a632510effb82cc72d62ddce4b9275
https://github.com/flapjack/flapjack/blob/1f27caebf5a632510effb82cc72d62ddce4b9275/lib/flapjack/utility.rb#L79-L88
train
flapjack/flapjack
lib/flapjack/notifier.rb
Flapjack.Notifier.process_notification
def process_notification(notification) Flapjack.logger.debug { "Processing notification: #{notification.inspect}" } check = notification.check check_name = check.name # TODO check whether time should come from something stored in the notification alerts = alerts_for(notification, check, :time => Time.now) if alerts.nil? || alerts.empty? Flapjack.logger.info { "No alerts" } else Flapjack.logger.info { "Alerts: #{alerts.size}" } alerts.each do |alert| medium = alert.medium Flapjack.logger.info { "#{check_name} | #{medium.contact.id} | " \ "#{medium.transport} | #{medium.address}\n" \ "Enqueueing #{medium.transport} alert for " \ "#{check_name} to #{medium.address} " \ " rollup: #{alert.rollup || '-'}" } @queues[medium.transport].push(alert) end end notification.destroy end
ruby
def process_notification(notification) Flapjack.logger.debug { "Processing notification: #{notification.inspect}" } check = notification.check check_name = check.name # TODO check whether time should come from something stored in the notification alerts = alerts_for(notification, check, :time => Time.now) if alerts.nil? || alerts.empty? Flapjack.logger.info { "No alerts" } else Flapjack.logger.info { "Alerts: #{alerts.size}" } alerts.each do |alert| medium = alert.medium Flapjack.logger.info { "#{check_name} | #{medium.contact.id} | " \ "#{medium.transport} | #{medium.address}\n" \ "Enqueueing #{medium.transport} alert for " \ "#{check_name} to #{medium.address} " \ " rollup: #{alert.rollup || '-'}" } @queues[medium.transport].push(alert) end end notification.destroy end
[ "def", "process_notification", "(", "notification", ")", "Flapjack", ".", "logger", ".", "debug", "{", "\"Processing notification: #{notification.inspect}\"", "}", "check", "=", "notification", ".", "check", "check_name", "=", "check", ".", "name", "# TODO check whether time should come from something stored in the notification", "alerts", "=", "alerts_for", "(", "notification", ",", "check", ",", ":time", "=>", "Time", ".", "now", ")", "if", "alerts", ".", "nil?", "||", "alerts", ".", "empty?", "Flapjack", ".", "logger", ".", "info", "{", "\"No alerts\"", "}", "else", "Flapjack", ".", "logger", ".", "info", "{", "\"Alerts: #{alerts.size}\"", "}", "alerts", ".", "each", "do", "|", "alert", "|", "medium", "=", "alert", ".", "medium", "Flapjack", ".", "logger", ".", "info", "{", "\"#{check_name} | #{medium.contact.id} | \"", "\"#{medium.transport} | #{medium.address}\\n\"", "\"Enqueueing #{medium.transport} alert for \"", "\"#{check_name} to #{medium.address} \"", "\" rollup: #{alert.rollup || '-'}\"", "}", "@queues", "[", "medium", ".", "transport", "]", ".", "push", "(", "alert", ")", "end", "end", "notification", ".", "destroy", "end" ]
takes an event for which messages should be generated, works out the type of notification, updates the notification history in redis, generates the notifications
[ "takes", "an", "event", "for", "which", "messages", "should", "be", "generated", "works", "out", "the", "type", "of", "notification", "updates", "the", "notification", "history", "in", "redis", "generates", "the", "notifications" ]
1f27caebf5a632510effb82cc72d62ddce4b9275
https://github.com/flapjack/flapjack/blob/1f27caebf5a632510effb82cc72d62ddce4b9275/lib/flapjack/notifier.rb#L69-L99
train
flapjack/flapjack
lib/flapjack/coordinator.rb
Flapjack.Coordinator.setup_signals
def setup_signals Kernel.trap('INT') { Thread.new { @shutdown.call(Signal.list['INT']) }.join } Kernel.trap('TERM') { Thread.new { @shutdown.call(Signal.list['TERM']) }.join } unless RbConfig::CONFIG['host_os'] =~ /mswin|windows|cygwin/i Kernel.trap('HUP') { Thread.new { @reload.call }.join } end end
ruby
def setup_signals Kernel.trap('INT') { Thread.new { @shutdown.call(Signal.list['INT']) }.join } Kernel.trap('TERM') { Thread.new { @shutdown.call(Signal.list['TERM']) }.join } unless RbConfig::CONFIG['host_os'] =~ /mswin|windows|cygwin/i Kernel.trap('HUP') { Thread.new { @reload.call }.join } end end
[ "def", "setup_signals", "Kernel", ".", "trap", "(", "'INT'", ")", "{", "Thread", ".", "new", "{", "@shutdown", ".", "call", "(", "Signal", ".", "list", "[", "'INT'", "]", ")", "}", ".", "join", "}", "Kernel", ".", "trap", "(", "'TERM'", ")", "{", "Thread", ".", "new", "{", "@shutdown", ".", "call", "(", "Signal", ".", "list", "[", "'TERM'", "]", ")", "}", ".", "join", "}", "unless", "RbConfig", "::", "CONFIG", "[", "'host_os'", "]", "=~", "/", "/i", "Kernel", ".", "trap", "(", "'HUP'", ")", "{", "Thread", ".", "new", "{", "@reload", ".", "call", "}", ".", "join", "}", "end", "end" ]
the global nature of this seems at odds with it calling stop within a single coordinator instance. Coordinator is essentially a singleton anyway...
[ "the", "global", "nature", "of", "this", "seems", "at", "odds", "with", "it", "calling", "stop", "within", "a", "single", "coordinator", "instance", ".", "Coordinator", "is", "essentially", "a", "singleton", "anyway", "..." ]
1f27caebf5a632510effb82cc72d62ddce4b9275
https://github.com/flapjack/flapjack/blob/1f27caebf5a632510effb82cc72d62ddce4b9275/lib/flapjack/coordinator.rb#L114-L120
train
khipu/khipu-api-ruby-client
lib/khipu-api-client/models/base_object.rb
Khipu.BaseObject.build_from_hash
def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /^Array<(.*)>/i if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) else #TODO show warning in debug mode end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) else # data not found in attributes(hash), not an issue as the data can be optional end end self end
ruby
def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /^Array<(.*)>/i if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) else #TODO show warning in debug mode end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) else # data not found in attributes(hash), not an issue as the data can be optional end end self end
[ "def", "build_from_hash", "(", "attributes", ")", "return", "nil", "unless", "attributes", ".", "is_a?", "(", "Hash", ")", "self", ".", "class", ".", "swagger_types", ".", "each_pair", "do", "|", "key", ",", "type", "|", "if", "type", "=~", "/", "/i", "if", "attributes", "[", "self", ".", "class", ".", "attribute_map", "[", "key", "]", "]", ".", "is_a?", "(", "Array", ")", "self", ".", "send", "(", "\"#{key}=\"", ",", "attributes", "[", "self", ".", "class", ".", "attribute_map", "[", "key", "]", "]", ".", "map", "{", "|", "v", "|", "_deserialize", "(", "$1", ",", "v", ")", "}", ")", "else", "#TODO show warning in debug mode", "end", "elsif", "!", "attributes", "[", "self", ".", "class", ".", "attribute_map", "[", "key", "]", "]", ".", "nil?", "self", ".", "send", "(", "\"#{key}=\"", ",", "_deserialize", "(", "type", ",", "attributes", "[", "self", ".", "class", ".", "attribute_map", "[", "key", "]", "]", ")", ")", "else", "# data not found in attributes(hash), not an issue as the data can be optional", "end", "end", "self", "end" ]
build the object from hash
[ "build", "the", "object", "from", "hash" ]
865af9e81c3b6e3b69205bbe7161806981a015e8
https://github.com/khipu/khipu-api-ruby-client/blob/865af9e81c3b6e3b69205bbe7161806981a015e8/lib/khipu-api-client/models/base_object.rb#L8-L25
train
khipu/khipu-api-ruby-client
lib/khipu-api-client/models/base_object.rb
Khipu.BaseObject.to_hash
def to_hash hash = {} attributes = self.class.attribute_map.sort_by {|key,value| key} attributes.each { |attr, param| value = self.send(attr) next if value.nil? if value.is_a?(Array) hash[param] = value.compact.map{ |v| _to_hash(v) } else hash[param] = _to_hash(value) end } hash end
ruby
def to_hash hash = {} attributes = self.class.attribute_map.sort_by {|key,value| key} attributes.each { |attr, param| value = self.send(attr) next if value.nil? if value.is_a?(Array) hash[param] = value.compact.map{ |v| _to_hash(v) } else hash[param] = _to_hash(value) end } hash end
[ "def", "to_hash", "hash", "=", "{", "}", "attributes", "=", "self", ".", "class", ".", "attribute_map", ".", "sort_by", "{", "|", "key", ",", "value", "|", "key", "}", "attributes", ".", "each", "{", "|", "attr", ",", "param", "|", "value", "=", "self", ".", "send", "(", "attr", ")", "next", "if", "value", ".", "nil?", "if", "value", ".", "is_a?", "(", "Array", ")", "hash", "[", "param", "]", "=", "value", ".", "compact", ".", "map", "{", "|", "v", "|", "_to_hash", "(", "v", ")", "}", "else", "hash", "[", "param", "]", "=", "_to_hash", "(", "value", ")", "end", "}", "hash", "end" ]
return the object in the form of hash
[ "return", "the", "object", "in", "the", "form", "of", "hash" ]
865af9e81c3b6e3b69205bbe7161806981a015e8
https://github.com/khipu/khipu-api-ruby-client/blob/865af9e81c3b6e3b69205bbe7161806981a015e8/lib/khipu-api-client/models/base_object.rb#L61-L74
train
interagent/heroics
lib/heroics/cli.rb
Heroics.CLI.run
def run(*parameters) name = parameters.shift if name.nil? || name == 'help' if command_name = parameters.first command = @commands[command_name] command.usage else usage end else command = @commands[name] if command.nil? @output.write("There is no command called '#{name}'.\n") else command.run(*parameters) end end end
ruby
def run(*parameters) name = parameters.shift if name.nil? || name == 'help' if command_name = parameters.first command = @commands[command_name] command.usage else usage end else command = @commands[name] if command.nil? @output.write("There is no command called '#{name}'.\n") else command.run(*parameters) end end end
[ "def", "run", "(", "*", "parameters", ")", "name", "=", "parameters", ".", "shift", "if", "name", ".", "nil?", "||", "name", "==", "'help'", "if", "command_name", "=", "parameters", ".", "first", "command", "=", "@commands", "[", "command_name", "]", "command", ".", "usage", "else", "usage", "end", "else", "command", "=", "@commands", "[", "name", "]", "if", "command", ".", "nil?", "@output", ".", "write", "(", "\"There is no command called '#{name}'.\\n\"", ")", "else", "command", ".", "run", "(", "parameters", ")", "end", "end", "end" ]
Instantiate a CLI for an API described by a JSON schema. @param name [String] The name of the CLI. @param schema [Schema] The JSON schema describing the API. @param client [Client] A client generated from the JSON schema. @param output [IO] The stream to write to. Run a command. @param parameters [Array] The parameters to use when running the command. The first parameters is the name of the command and the remaining parameters are passed to it.
[ "Instantiate", "a", "CLI", "for", "an", "API", "described", "by", "a", "JSON", "schema", "." ]
373f6defeade22fd9d09b89ec3f8a39ba9f29df1
https://github.com/interagent/heroics/blob/373f6defeade22fd9d09b89ec3f8a39ba9f29df1/lib/heroics/cli.rb#L21-L38
train
interagent/heroics
lib/heroics/command.rb
Heroics.Command.run
def run(*parameters) resource_name = @link_schema.resource_name name = @link_schema.name result = @client.send(resource_name).send(name, *parameters) result = result.to_a if result.instance_of?(Enumerator) if result && !result.instance_of?(String) result = MultiJson.dump(result, pretty: true) end @output.puts(result) unless result.nil? end
ruby
def run(*parameters) resource_name = @link_schema.resource_name name = @link_schema.name result = @client.send(resource_name).send(name, *parameters) result = result.to_a if result.instance_of?(Enumerator) if result && !result.instance_of?(String) result = MultiJson.dump(result, pretty: true) end @output.puts(result) unless result.nil? end
[ "def", "run", "(", "*", "parameters", ")", "resource_name", "=", "@link_schema", ".", "resource_name", "name", "=", "@link_schema", ".", "name", "result", "=", "@client", ".", "send", "(", "resource_name", ")", ".", "send", "(", "name", ",", "parameters", ")", "result", "=", "result", ".", "to_a", "if", "result", ".", "instance_of?", "(", "Enumerator", ")", "if", "result", "&&", "!", "result", ".", "instance_of?", "(", "String", ")", "result", "=", "MultiJson", ".", "dump", "(", "result", ",", "pretty", ":", "true", ")", "end", "@output", ".", "puts", "(", "result", ")", "unless", "result", ".", "nil?", "end" ]
Run the command and write the results to the output stream. @param parameters [Array] The parameters to pass when making a request to run the command.
[ "Run", "the", "command", "and", "write", "the", "results", "to", "the", "output", "stream", "." ]
373f6defeade22fd9d09b89ec3f8a39ba9f29df1
https://github.com/interagent/heroics/blob/373f6defeade22fd9d09b89ec3f8a39ba9f29df1/lib/heroics/command.rb#L57-L66
train
interagent/heroics
lib/heroics/link.rb
Heroics.Link.run
def run(*parameters) path, body = @link_schema.format_path(parameters) path = "#{@path_prefix}#{path}" unless @path_prefix == '/' headers = @default_headers if body case @link_schema.method when :put, :post, :patch headers = headers.merge({'Content-Type' => @link_schema.content_type}) body = @link_schema.encode(body) when :get, :delete if body.is_a?(Hash) query = body else query = MultiJson.load(body) end body = nil end end connection = Excon.new(@root_url, thread_safe_sockets: true) response = request_with_cache(connection, method: @link_schema.method, path: path, headers: headers, body: body, query: query, expects: [200, 201, 202, 204, 206]) content_type = response.headers['Content-Type'] if content_type && content_type =~ /application\/.*json/ body = MultiJson.load(response.body) if response.status == 206 next_range = response.headers['Next-Range'] Enumerator.new do |yielder| while true do # Yield the results we got in the body. body.each do |item| yielder << item end # Only make a request to get the next page if we have a valid # next range. break unless next_range headers = headers.merge({'Range' => next_range}) response = request_with_cache(connection, method: @link_schema.method, path: path, headers: headers, expects: [200, 201, 206]) body = MultiJson.load(response.body) next_range = response.headers['Next-Range'] end end else body end elsif !response.body.empty? response.body end end
ruby
def run(*parameters) path, body = @link_schema.format_path(parameters) path = "#{@path_prefix}#{path}" unless @path_prefix == '/' headers = @default_headers if body case @link_schema.method when :put, :post, :patch headers = headers.merge({'Content-Type' => @link_schema.content_type}) body = @link_schema.encode(body) when :get, :delete if body.is_a?(Hash) query = body else query = MultiJson.load(body) end body = nil end end connection = Excon.new(@root_url, thread_safe_sockets: true) response = request_with_cache(connection, method: @link_schema.method, path: path, headers: headers, body: body, query: query, expects: [200, 201, 202, 204, 206]) content_type = response.headers['Content-Type'] if content_type && content_type =~ /application\/.*json/ body = MultiJson.load(response.body) if response.status == 206 next_range = response.headers['Next-Range'] Enumerator.new do |yielder| while true do # Yield the results we got in the body. body.each do |item| yielder << item end # Only make a request to get the next page if we have a valid # next range. break unless next_range headers = headers.merge({'Range' => next_range}) response = request_with_cache(connection, method: @link_schema.method, path: path, headers: headers, expects: [200, 201, 206]) body = MultiJson.load(response.body) next_range = response.headers['Next-Range'] end end else body end elsif !response.body.empty? response.body end end
[ "def", "run", "(", "*", "parameters", ")", "path", ",", "body", "=", "@link_schema", ".", "format_path", "(", "parameters", ")", "path", "=", "\"#{@path_prefix}#{path}\"", "unless", "@path_prefix", "==", "'/'", "headers", "=", "@default_headers", "if", "body", "case", "@link_schema", ".", "method", "when", ":put", ",", ":post", ",", ":patch", "headers", "=", "headers", ".", "merge", "(", "{", "'Content-Type'", "=>", "@link_schema", ".", "content_type", "}", ")", "body", "=", "@link_schema", ".", "encode", "(", "body", ")", "when", ":get", ",", ":delete", "if", "body", ".", "is_a?", "(", "Hash", ")", "query", "=", "body", "else", "query", "=", "MultiJson", ".", "load", "(", "body", ")", "end", "body", "=", "nil", "end", "end", "connection", "=", "Excon", ".", "new", "(", "@root_url", ",", "thread_safe_sockets", ":", "true", ")", "response", "=", "request_with_cache", "(", "connection", ",", "method", ":", "@link_schema", ".", "method", ",", "path", ":", "path", ",", "headers", ":", "headers", ",", "body", ":", "body", ",", "query", ":", "query", ",", "expects", ":", "[", "200", ",", "201", ",", "202", ",", "204", ",", "206", "]", ")", "content_type", "=", "response", ".", "headers", "[", "'Content-Type'", "]", "if", "content_type", "&&", "content_type", "=~", "/", "\\/", "/", "body", "=", "MultiJson", ".", "load", "(", "response", ".", "body", ")", "if", "response", ".", "status", "==", "206", "next_range", "=", "response", ".", "headers", "[", "'Next-Range'", "]", "Enumerator", ".", "new", "do", "|", "yielder", "|", "while", "true", "do", "# Yield the results we got in the body.", "body", ".", "each", "do", "|", "item", "|", "yielder", "<<", "item", "end", "# Only make a request to get the next page if we have a valid", "# next range.", "break", "unless", "next_range", "headers", "=", "headers", ".", "merge", "(", "{", "'Range'", "=>", "next_range", "}", ")", "response", "=", "request_with_cache", "(", "connection", ",", "method", ":", "@link_schema", ".", "method", ",", "path", ":", "path", ",", "headers", ":", "headers", ",", "expects", ":", "[", "200", ",", "201", ",", "206", "]", ")", "body", "=", "MultiJson", ".", "load", "(", "response", ".", "body", ")", "next_range", "=", "response", ".", "headers", "[", "'Next-Range'", "]", "end", "end", "else", "body", "end", "elsif", "!", "response", ".", "body", ".", "empty?", "response", ".", "body", "end", "end" ]
Instantiate a link. @param url [String] The URL to use when making requests. Include the username and password to use with HTTP basic auth. @param link_schema [LinkSchema] The schema for this link. @param options [Hash] Configuration for the link. Possible keys include: - default_headers: Optionally, a set of headers to include in every request made by the client. Default is no custom headers. - cache: Optionally, a Moneta-compatible cache to store ETags. Default is no caching. Make a request to the server. JSON content received with an ETag is cached. When the server returns a *304 Not Modified* status code content is loaded and returned from the cache. The cache considers headers, in addition to the URL path, when creating keys so that requests to the same path, such as for paginated results, don't cause cache collisions. When the server returns a *206 Partial Content* status code the result is assumed to be an array and an enumerator is returned. The enumerator yields results from the response until they've been consumed at which point, if additional content is available from the server, it blocks and makes a request to fetch the subsequent page of data. This behaviour continues until the client stops iterating the enumerator or the dataset from the server has been entirely consumed. @param parameters [Array] The list of parameters to inject into the path. A request body can be passed as the final parameter and will always be converted to JSON before being transmitted. @raise [ArgumentError] Raised if either too many or too few parameters were provided. @return [String,Object,Enumerator] A string for text responses, an object for JSON responses, or an enumerator for list responses.
[ "Instantiate", "a", "link", "." ]
373f6defeade22fd9d09b89ec3f8a39ba9f29df1
https://github.com/interagent/heroics/blob/373f6defeade22fd9d09b89ec3f8a39ba9f29df1/lib/heroics/link.rb#L46-L100
train
interagent/heroics
lib/heroics/link.rb
Heroics.Link.unpack_url
def unpack_url(url) root_url = [] path_prefix = '' parts = URI.split(url) root_url << "#{parts[0]}://" root_url << "#{parts[1]}@" unless parts[1].nil? root_url << "#{parts[2]}" root_url << ":#{parts[3]}" unless parts[3].nil? path_prefix = parts[5] return root_url.join(''), path_prefix end
ruby
def unpack_url(url) root_url = [] path_prefix = '' parts = URI.split(url) root_url << "#{parts[0]}://" root_url << "#{parts[1]}@" unless parts[1].nil? root_url << "#{parts[2]}" root_url << ":#{parts[3]}" unless parts[3].nil? path_prefix = parts[5] return root_url.join(''), path_prefix end
[ "def", "unpack_url", "(", "url", ")", "root_url", "=", "[", "]", "path_prefix", "=", "''", "parts", "=", "URI", ".", "split", "(", "url", ")", "root_url", "<<", "\"#{parts[0]}://\"", "root_url", "<<", "\"#{parts[1]}@\"", "unless", "parts", "[", "1", "]", ".", "nil?", "root_url", "<<", "\"#{parts[2]}\"", "root_url", "<<", "\":#{parts[3]}\"", "unless", "parts", "[", "3", "]", ".", "nil?", "path_prefix", "=", "parts", "[", "5", "]", "return", "root_url", ".", "join", "(", "''", ")", ",", "path_prefix", "end" ]
Unpack the URL and split it into a root URL and a path prefix, if one exists. @param url [String] The complete base URL to use when making requests. @return [String,String] A (root URL, path) prefix pair.
[ "Unpack", "the", "URL", "and", "split", "it", "into", "a", "root", "URL", "and", "a", "path", "prefix", "if", "one", "exists", "." ]
373f6defeade22fd9d09b89ec3f8a39ba9f29df1
https://github.com/interagent/heroics/blob/373f6defeade22fd9d09b89ec3f8a39ba9f29df1/lib/heroics/link.rb#L134-L144
train
interagent/heroics
lib/heroics/client.rb
Heroics.Client.method_missing
def method_missing(name) name = name.to_s resource = @resources[name] if resource.nil? # Find the name using the same ruby_name replacement semantics as when # we set up the @resources hash name = Heroics.ruby_name(name) resource = @resources[name] if resource.nil? raise NoMethodError.new("undefined method `#{name}' for #{to_s}") end end resource end
ruby
def method_missing(name) name = name.to_s resource = @resources[name] if resource.nil? # Find the name using the same ruby_name replacement semantics as when # we set up the @resources hash name = Heroics.ruby_name(name) resource = @resources[name] if resource.nil? raise NoMethodError.new("undefined method `#{name}' for #{to_s}") end end resource end
[ "def", "method_missing", "(", "name", ")", "name", "=", "name", ".", "to_s", "resource", "=", "@resources", "[", "name", "]", "if", "resource", ".", "nil?", "# Find the name using the same ruby_name replacement semantics as when", "# we set up the @resources hash", "name", "=", "Heroics", ".", "ruby_name", "(", "name", ")", "resource", "=", "@resources", "[", "name", "]", "if", "resource", ".", "nil?", "raise", "NoMethodError", ".", "new", "(", "\"undefined method `#{name}' for #{to_s}\"", ")", "end", "end", "resource", "end" ]
Instantiate an HTTP client. @param resources [Hash<String,Resource>] A hash that maps method names to resources. @param url [String] The URL used by this client. Find a resource. @param name [String] The name of the resource to find. @raise [NoMethodError] Raised if the name doesn't match a known resource. @return [Resource] The resource matching the name.
[ "Instantiate", "an", "HTTP", "client", "." ]
373f6defeade22fd9d09b89ec3f8a39ba9f29df1
https://github.com/interagent/heroics/blob/373f6defeade22fd9d09b89ec3f8a39ba9f29df1/lib/heroics/client.rb#L21-L34
train
interagent/heroics
lib/heroics/resource.rb
Heroics.Resource.method_missing
def method_missing(name, *parameters) link = @links[name.to_s] if link.nil? address = "<#{self.class.name}:0x00#{(self.object_id << 1).to_s(16)}>" raise NoMethodError.new("undefined method `#{name}' for ##{address}") end link.run(*parameters) end
ruby
def method_missing(name, *parameters) link = @links[name.to_s] if link.nil? address = "<#{self.class.name}:0x00#{(self.object_id << 1).to_s(16)}>" raise NoMethodError.new("undefined method `#{name}' for ##{address}") end link.run(*parameters) end
[ "def", "method_missing", "(", "name", ",", "*", "parameters", ")", "link", "=", "@links", "[", "name", ".", "to_s", "]", "if", "link", ".", "nil?", "address", "=", "\"<#{self.class.name}:0x00#{(self.object_id << 1).to_s(16)}>\"", "raise", "NoMethodError", ".", "new", "(", "\"undefined method `#{name}' for ##{address}\"", ")", "end", "link", ".", "run", "(", "parameters", ")", "end" ]
Find a link and invoke it. @param name [String] The name of the method to invoke. @param parameters [Array] The arguments to pass to the method. This should always be a `Hash` mapping parameter names to values. @raise [NoMethodError] Raised if the name doesn't match a known link. @return [String,Array,Hash] The response received from the server. JSON responses are automatically decoded into Ruby objects.
[ "Find", "a", "link", "and", "invoke", "it", "." ]
373f6defeade22fd9d09b89ec3f8a39ba9f29df1
https://github.com/interagent/heroics/blob/373f6defeade22fd9d09b89ec3f8a39ba9f29df1/lib/heroics/resource.rb#L22-L29
train
interagent/heroics
lib/heroics/schema.rb
Heroics.Schema.resource
def resource(name) if @schema['definitions'].has_key?(name) ResourceSchema.new(@schema, name) else raise SchemaError.new("Unknown resource '#{name}'.") end end
ruby
def resource(name) if @schema['definitions'].has_key?(name) ResourceSchema.new(@schema, name) else raise SchemaError.new("Unknown resource '#{name}'.") end end
[ "def", "resource", "(", "name", ")", "if", "@schema", "[", "'definitions'", "]", ".", "has_key?", "(", "name", ")", "ResourceSchema", ".", "new", "(", "@schema", ",", "name", ")", "else", "raise", "SchemaError", ".", "new", "(", "\"Unknown resource '#{name}'.\"", ")", "end", "end" ]
Get a schema for a named resource. @param name [String] The name of the resource. @raise [SchemaError] Raised if an unknown resource name is provided.
[ "Get", "a", "schema", "for", "a", "named", "resource", "." ]
373f6defeade22fd9d09b89ec3f8a39ba9f29df1
https://github.com/interagent/heroics/blob/373f6defeade22fd9d09b89ec3f8a39ba9f29df1/lib/heroics/schema.rb#L27-L33
train
interagent/heroics
lib/heroics/schema.rb
Heroics.LinkSchema.example_body
def example_body if body_schema = link_schema['schema'] definitions = @schema['definitions'][@resource_name]['definitions'] Hash[body_schema['properties'].keys.map do |property| # FIXME This is wrong! -jkakar if definitions.has_key?(property) example = definitions[property]['example'] else example = '' end [property, example] end] end end
ruby
def example_body if body_schema = link_schema['schema'] definitions = @schema['definitions'][@resource_name]['definitions'] Hash[body_schema['properties'].keys.map do |property| # FIXME This is wrong! -jkakar if definitions.has_key?(property) example = definitions[property]['example'] else example = '' end [property, example] end] end end
[ "def", "example_body", "if", "body_schema", "=", "link_schema", "[", "'schema'", "]", "definitions", "=", "@schema", "[", "'definitions'", "]", "[", "@resource_name", "]", "[", "'definitions'", "]", "Hash", "[", "body_schema", "[", "'properties'", "]", ".", "keys", ".", "map", "do", "|", "property", "|", "# FIXME This is wrong! -jkakar", "if", "definitions", ".", "has_key?", "(", "property", ")", "example", "=", "definitions", "[", "property", "]", "[", "'example'", "]", "else", "example", "=", "''", "end", "[", "property", ",", "example", "]", "end", "]", "end", "end" ]
Get an example request body. @return [Hash] A sample request body.
[ "Get", "an", "example", "request", "body", "." ]
373f6defeade22fd9d09b89ec3f8a39ba9f29df1
https://github.com/interagent/heroics/blob/373f6defeade22fd9d09b89ec3f8a39ba9f29df1/lib/heroics/schema.rb#L181-L194
train
interagent/heroics
lib/heroics/schema.rb
Heroics.LinkSchema.format_path
def format_path(parameters) path = link_schema['href'] parameter_size = path.scan(PARAMETER_REGEX).size too_few_parameters = parameter_size > parameters.size # FIXME We should use the schema to detect when a request body is # permitted and do the calculation correctly here. -jkakar too_many_parameters = parameter_size < (parameters.size - 1) if too_few_parameters || too_many_parameters raise ArgumentError.new("wrong number of arguments " + "(#{parameters.size} for #{parameter_size})") end (0...parameter_size).each do |i| path = path.sub(PARAMETER_REGEX, format_parameter(parameters[i])) end body = parameters.slice(parameter_size) return path, body end
ruby
def format_path(parameters) path = link_schema['href'] parameter_size = path.scan(PARAMETER_REGEX).size too_few_parameters = parameter_size > parameters.size # FIXME We should use the schema to detect when a request body is # permitted and do the calculation correctly here. -jkakar too_many_parameters = parameter_size < (parameters.size - 1) if too_few_parameters || too_many_parameters raise ArgumentError.new("wrong number of arguments " + "(#{parameters.size} for #{parameter_size})") end (0...parameter_size).each do |i| path = path.sub(PARAMETER_REGEX, format_parameter(parameters[i])) end body = parameters.slice(parameter_size) return path, body end
[ "def", "format_path", "(", "parameters", ")", "path", "=", "link_schema", "[", "'href'", "]", "parameter_size", "=", "path", ".", "scan", "(", "PARAMETER_REGEX", ")", ".", "size", "too_few_parameters", "=", "parameter_size", ">", "parameters", ".", "size", "# FIXME We should use the schema to detect when a request body is", "# permitted and do the calculation correctly here. -jkakar", "too_many_parameters", "=", "parameter_size", "<", "(", "parameters", ".", "size", "-", "1", ")", "if", "too_few_parameters", "||", "too_many_parameters", "raise", "ArgumentError", ".", "new", "(", "\"wrong number of arguments \"", "+", "\"(#{parameters.size} for #{parameter_size})\"", ")", "end", "(", "0", "...", "parameter_size", ")", ".", "each", "do", "|", "i", "|", "path", "=", "path", ".", "sub", "(", "PARAMETER_REGEX", ",", "format_parameter", "(", "parameters", "[", "i", "]", ")", ")", "end", "body", "=", "parameters", ".", "slice", "(", "parameter_size", ")", "return", "path", ",", "body", "end" ]
Inject parameters into the link href and return the body, if it exists. @param parameters [Array] The list of parameters to inject into the path. @raise [ArgumentError] Raised if either too many or too few parameters were provided. @return [String,Object] A path and request body pair. The body value is nil if a payload wasn't included in the list of parameters.
[ "Inject", "parameters", "into", "the", "link", "href", "and", "return", "the", "body", "if", "it", "exists", "." ]
373f6defeade22fd9d09b89ec3f8a39ba9f29df1
https://github.com/interagent/heroics/blob/373f6defeade22fd9d09b89ec3f8a39ba9f29df1/lib/heroics/schema.rb#L204-L221
train
interagent/heroics
lib/heroics/schema.rb
Heroics.LinkSchema.resolve_parameters
def resolve_parameters(parameters) properties = @schema['definitions'][@resource_name]['properties'] return [''] if properties.nil? definitions = Hash[properties.each_pair.map do |key, value| [value['$ref'], key] end] parameters.map do |parameter| definition_name = URI.unescape(parameter[2..-3]) if definitions.has_key?(definition_name) definitions[definition_name] else definition_name = definition_name.split('/')[-1] resource_definitions = @schema[ 'definitions'][@resource_name]['definitions'][definition_name] if resource_definitions.has_key?('anyOf') resource_definitions['anyOf'].map do |property| definitions[property['$ref']] end.join('|') else resource_definitions['oneOf'].map do |property| definitions[property['$ref']] end.join('|') end end end end
ruby
def resolve_parameters(parameters) properties = @schema['definitions'][@resource_name]['properties'] return [''] if properties.nil? definitions = Hash[properties.each_pair.map do |key, value| [value['$ref'], key] end] parameters.map do |parameter| definition_name = URI.unescape(parameter[2..-3]) if definitions.has_key?(definition_name) definitions[definition_name] else definition_name = definition_name.split('/')[-1] resource_definitions = @schema[ 'definitions'][@resource_name]['definitions'][definition_name] if resource_definitions.has_key?('anyOf') resource_definitions['anyOf'].map do |property| definitions[property['$ref']] end.join('|') else resource_definitions['oneOf'].map do |property| definitions[property['$ref']] end.join('|') end end end end
[ "def", "resolve_parameters", "(", "parameters", ")", "properties", "=", "@schema", "[", "'definitions'", "]", "[", "@resource_name", "]", "[", "'properties'", "]", "return", "[", "''", "]", "if", "properties", ".", "nil?", "definitions", "=", "Hash", "[", "properties", ".", "each_pair", ".", "map", "do", "|", "key", ",", "value", "|", "[", "value", "[", "'$ref'", "]", ",", "key", "]", "end", "]", "parameters", ".", "map", "do", "|", "parameter", "|", "definition_name", "=", "URI", ".", "unescape", "(", "parameter", "[", "2", "..", "-", "3", "]", ")", "if", "definitions", ".", "has_key?", "(", "definition_name", ")", "definitions", "[", "definition_name", "]", "else", "definition_name", "=", "definition_name", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "resource_definitions", "=", "@schema", "[", "'definitions'", "]", "[", "@resource_name", "]", "[", "'definitions'", "]", "[", "definition_name", "]", "if", "resource_definitions", ".", "has_key?", "(", "'anyOf'", ")", "resource_definitions", "[", "'anyOf'", "]", ".", "map", "do", "|", "property", "|", "definitions", "[", "property", "[", "'$ref'", "]", "]", "end", ".", "join", "(", "'|'", ")", "else", "resource_definitions", "[", "'oneOf'", "]", ".", "map", "do", "|", "property", "|", "definitions", "[", "property", "[", "'$ref'", "]", "]", "end", ".", "join", "(", "'|'", ")", "end", "end", "end", "end" ]
Get the names of the parameters this link expects. @param parameters [Array] The names of the parameter definitions to convert to parameter names. @return [Array<String>] The parameters.
[ "Get", "the", "names", "of", "the", "parameters", "this", "link", "expects", "." ]
373f6defeade22fd9d09b89ec3f8a39ba9f29df1
https://github.com/interagent/heroics/blob/373f6defeade22fd9d09b89ec3f8a39ba9f29df1/lib/heroics/schema.rb#L240-L265
train
interagent/heroics
lib/heroics/schema.rb
Heroics.LinkSchema.resolve_parameter_details
def resolve_parameter_details(parameters) parameters.map do |parameter| # URI decode parameters and strip the leading '{(' and trailing ')}'. parameter = URI.unescape(parameter[2..-3]) # Split the path into components and discard the leading '#' that # represents the root of the schema. path = parameter.split('/')[1..-1] info = lookup_parameter(path, @schema) # The reference can be one of several values. resource_name = path[1].gsub('-', '_') if info.has_key?('anyOf') ParameterChoice.new(resource_name, unpack_multiple_parameters(info['anyOf'])) elsif info.has_key?('oneOf') ParameterChoice.new(resource_name, unpack_multiple_parameters(info['oneOf'])) else name = path[-1] Parameter.new(resource_name, name, info['description']) end end end
ruby
def resolve_parameter_details(parameters) parameters.map do |parameter| # URI decode parameters and strip the leading '{(' and trailing ')}'. parameter = URI.unescape(parameter[2..-3]) # Split the path into components and discard the leading '#' that # represents the root of the schema. path = parameter.split('/')[1..-1] info = lookup_parameter(path, @schema) # The reference can be one of several values. resource_name = path[1].gsub('-', '_') if info.has_key?('anyOf') ParameterChoice.new(resource_name, unpack_multiple_parameters(info['anyOf'])) elsif info.has_key?('oneOf') ParameterChoice.new(resource_name, unpack_multiple_parameters(info['oneOf'])) else name = path[-1] Parameter.new(resource_name, name, info['description']) end end end
[ "def", "resolve_parameter_details", "(", "parameters", ")", "parameters", ".", "map", "do", "|", "parameter", "|", "# URI decode parameters and strip the leading '{(' and trailing ')}'.", "parameter", "=", "URI", ".", "unescape", "(", "parameter", "[", "2", "..", "-", "3", "]", ")", "# Split the path into components and discard the leading '#' that", "# represents the root of the schema.", "path", "=", "parameter", ".", "split", "(", "'/'", ")", "[", "1", "..", "-", "1", "]", "info", "=", "lookup_parameter", "(", "path", ",", "@schema", ")", "# The reference can be one of several values.", "resource_name", "=", "path", "[", "1", "]", ".", "gsub", "(", "'-'", ",", "'_'", ")", "if", "info", ".", "has_key?", "(", "'anyOf'", ")", "ParameterChoice", ".", "new", "(", "resource_name", ",", "unpack_multiple_parameters", "(", "info", "[", "'anyOf'", "]", ")", ")", "elsif", "info", ".", "has_key?", "(", "'oneOf'", ")", "ParameterChoice", ".", "new", "(", "resource_name", ",", "unpack_multiple_parameters", "(", "info", "[", "'oneOf'", "]", ")", ")", "else", "name", "=", "path", "[", "-", "1", "]", "Parameter", ".", "new", "(", "resource_name", ",", "name", ",", "info", "[", "'description'", "]", ")", "end", "end", "end" ]
Get the parameters this link expects. @param parameters [Array] The names of the parameter definitions to convert to parameter names. @return [Array<Parameter|ParameterChoice>] A list of parameter instances that represent parameters to be injected into the link URL.
[ "Get", "the", "parameters", "this", "link", "expects", "." ]
373f6defeade22fd9d09b89ec3f8a39ba9f29df1
https://github.com/interagent/heroics/blob/373f6defeade22fd9d09b89ec3f8a39ba9f29df1/lib/heroics/schema.rb#L273-L295
train
interagent/heroics
lib/heroics/schema.rb
Heroics.LinkSchema.unpack_multiple_parameters
def unpack_multiple_parameters(parameters) parameters.map do |info| parameter = info['$ref'] path = parameter.split('/')[1..-1] info = lookup_parameter(path, @schema) resource_name = path.size > 2 ? path[1].gsub('-', '_') : nil name = path[-1] Parameter.new(resource_name, name, info['description']) end end
ruby
def unpack_multiple_parameters(parameters) parameters.map do |info| parameter = info['$ref'] path = parameter.split('/')[1..-1] info = lookup_parameter(path, @schema) resource_name = path.size > 2 ? path[1].gsub('-', '_') : nil name = path[-1] Parameter.new(resource_name, name, info['description']) end end
[ "def", "unpack_multiple_parameters", "(", "parameters", ")", "parameters", ".", "map", "do", "|", "info", "|", "parameter", "=", "info", "[", "'$ref'", "]", "path", "=", "parameter", ".", "split", "(", "'/'", ")", "[", "1", "..", "-", "1", "]", "info", "=", "lookup_parameter", "(", "path", ",", "@schema", ")", "resource_name", "=", "path", ".", "size", ">", "2", "?", "path", "[", "1", "]", ".", "gsub", "(", "'-'", ",", "'_'", ")", ":", "nil", "name", "=", "path", "[", "-", "1", "]", "Parameter", ".", "new", "(", "resource_name", ",", "name", ",", "info", "[", "'description'", "]", ")", "end", "end" ]
Unpack an 'anyOf' or 'oneOf' multi-parameter blob. @param parameters [Array<Hash>] An array of hashes containing '$ref' keys and definition values. @return [Array<Parameter>] An array of parameters extracted from the blob.
[ "Unpack", "an", "anyOf", "or", "oneOf", "multi", "-", "parameter", "blob", "." ]
373f6defeade22fd9d09b89ec3f8a39ba9f29df1
https://github.com/interagent/heroics/blob/373f6defeade22fd9d09b89ec3f8a39ba9f29df1/lib/heroics/schema.rb#L303-L312
train
interagent/heroics
lib/heroics/schema.rb
Heroics.LinkSchema.lookup_parameter
def lookup_parameter(path, schema) key = path[0] remaining = path[1..-1] if remaining.empty? return schema[key] else lookup_parameter(remaining, schema[key]) end end
ruby
def lookup_parameter(path, schema) key = path[0] remaining = path[1..-1] if remaining.empty? return schema[key] else lookup_parameter(remaining, schema[key]) end end
[ "def", "lookup_parameter", "(", "path", ",", "schema", ")", "key", "=", "path", "[", "0", "]", "remaining", "=", "path", "[", "1", "..", "-", "1", "]", "if", "remaining", ".", "empty?", "return", "schema", "[", "key", "]", "else", "lookup_parameter", "(", "remaining", ",", "schema", "[", "key", "]", ")", "end", "end" ]
Recursively walk the object hierarchy in the schema to resolve a given path. This is used to find property information related to definitions in link hrefs. @param path [Array<String>] An array of paths to walk, such as ['definitions', 'resource', 'definitions', 'property']. @param schema [Hash] The schema to walk.
[ "Recursively", "walk", "the", "object", "hierarchy", "in", "the", "schema", "to", "resolve", "a", "given", "path", ".", "This", "is", "used", "to", "find", "property", "information", "related", "to", "definitions", "in", "link", "hrefs", "." ]
373f6defeade22fd9d09b89ec3f8a39ba9f29df1
https://github.com/interagent/heroics/blob/373f6defeade22fd9d09b89ec3f8a39ba9f29df1/lib/heroics/schema.rb#L321-L329
train
interagent/heroics
lib/heroics/schema.rb
Heroics.LinkSchema.format_parameter
def format_parameter(parameter) formatted_parameter = parameter.instance_of?(Time) ? iso_format(parameter) : parameter.to_s WEBrick::HTTPUtils.escape formatted_parameter end
ruby
def format_parameter(parameter) formatted_parameter = parameter.instance_of?(Time) ? iso_format(parameter) : parameter.to_s WEBrick::HTTPUtils.escape formatted_parameter end
[ "def", "format_parameter", "(", "parameter", ")", "formatted_parameter", "=", "parameter", ".", "instance_of?", "(", "Time", ")", "?", "iso_format", "(", "parameter", ")", ":", "parameter", ".", "to_s", "WEBrick", "::", "HTTPUtils", ".", "escape", "formatted_parameter", "end" ]
Convert a path parameter to a format suitable for use in a path. @param [Fixnum,String,TrueClass,FalseClass,Time] The parameter to format. @return [String] The formatted parameter.
[ "Convert", "a", "path", "parameter", "to", "a", "format", "suitable", "for", "use", "in", "a", "path", "." ]
373f6defeade22fd9d09b89ec3f8a39ba9f29df1
https://github.com/interagent/heroics/blob/373f6defeade22fd9d09b89ec3f8a39ba9f29df1/lib/heroics/schema.rb#L335-L338
train
interagent/heroics
lib/heroics/client_generator.rb
Heroics.GeneratorLink.method_signature
def method_signature @parameters.map { |info| info.name == 'body' ? "body = {}" : Heroics.ruby_name(info.name) }.join(', ') end
ruby
def method_signature @parameters.map { |info| info.name == 'body' ? "body = {}" : Heroics.ruby_name(info.name) }.join(', ') end
[ "def", "method_signature", "@parameters", ".", "map", "{", "|", "info", "|", "info", ".", "name", "==", "'body'", "?", "\"body = {}\"", ":", "Heroics", ".", "ruby_name", "(", "info", ".", "name", ")", "}", ".", "join", "(", "', '", ")", "end" ]
list of parameters for method signature, body is optional
[ "list", "of", "parameters", "for", "method", "signature", "body", "is", "optional" ]
373f6defeade22fd9d09b89ec3f8a39ba9f29df1
https://github.com/interagent/heroics/blob/373f6defeade22fd9d09b89ec3f8a39ba9f29df1/lib/heroics/client_generator.rb#L77-L79
train
ddfreyne/cri
lib/cri/command_dsl.rb
Cri.CommandDSL.option
def option(short, long, desc, argument: :forbidden, multiple: false, hidden: false, default: nil, transform: nil, &block) @command.option_definitions << Cri::OptionDefinition.new( short: short&.to_s, long: long&.to_s, desc: desc, argument: argument, multiple: multiple, hidden: hidden, default: default, transform: transform, block: block, ) end
ruby
def option(short, long, desc, argument: :forbidden, multiple: false, hidden: false, default: nil, transform: nil, &block) @command.option_definitions << Cri::OptionDefinition.new( short: short&.to_s, long: long&.to_s, desc: desc, argument: argument, multiple: multiple, hidden: hidden, default: default, transform: transform, block: block, ) end
[ "def", "option", "(", "short", ",", "long", ",", "desc", ",", "argument", ":", ":forbidden", ",", "multiple", ":", "false", ",", "hidden", ":", "false", ",", "default", ":", "nil", ",", "transform", ":", "nil", ",", "&", "block", ")", "@command", ".", "option_definitions", "<<", "Cri", "::", "OptionDefinition", ".", "new", "(", "short", ":", "short", "&.", "to_s", ",", "long", ":", "long", "&.", "to_s", ",", "desc", ":", "desc", ",", "argument", ":", "argument", ",", "multiple", ":", "multiple", ",", "hidden", ":", "hidden", ",", "default", ":", "default", ",", "transform", ":", "transform", ",", "block", ":", "block", ",", ")", "end" ]
Adds a new option to the command. If a block is given, it will be executed when the option is successfully parsed. @param [String, Symbol, nil] short The short option name @param [String, Symbol, nil] long The long option name @param [String] desc The option description @option params [:forbidden, :required, :optional] :argument Whether the argument is forbidden, required or optional @option params [Boolean] :multiple Whether or not the option should be multi-valued @option params [Boolean] :hidden Whether or not the option should be printed in the help output @return [void]
[ "Adds", "a", "new", "option", "to", "the", "command", ".", "If", "a", "block", "is", "given", "it", "will", "be", "executed", "when", "the", "option", "is", "successfully", "parsed", "." ]
4e4abafb352be093b63e0773e1d1d8869fc2ace9
https://github.com/ddfreyne/cri/blob/4e4abafb352be093b63e0773e1d1d8869fc2ace9/lib/cri/command_dsl.rb#L155-L173
train
ddfreyne/cri
lib/cri/command_dsl.rb
Cri.CommandDSL.param
def param(name, transform: nil) if @command.explicitly_no_params? raise AlreadySpecifiedAsNoParams.new(name, @command) end @command.parameter_definitions << Cri::ParamDefinition.new( name: name, transform: transform, ) end
ruby
def param(name, transform: nil) if @command.explicitly_no_params? raise AlreadySpecifiedAsNoParams.new(name, @command) end @command.parameter_definitions << Cri::ParamDefinition.new( name: name, transform: transform, ) end
[ "def", "param", "(", "name", ",", "transform", ":", "nil", ")", "if", "@command", ".", "explicitly_no_params?", "raise", "AlreadySpecifiedAsNoParams", ".", "new", "(", "name", ",", "@command", ")", "end", "@command", ".", "parameter_definitions", "<<", "Cri", "::", "ParamDefinition", ".", "new", "(", "name", ":", "name", ",", "transform", ":", "transform", ",", ")", "end" ]
Defines a new parameter for the command. @param [Symbol] name The name of the parameter
[ "Defines", "a", "new", "parameter", "for", "the", "command", "." ]
4e4abafb352be093b63e0773e1d1d8869fc2ace9
https://github.com/ddfreyne/cri/blob/4e4abafb352be093b63e0773e1d1d8869fc2ace9/lib/cri/command_dsl.rb#L179-L188
train
ddfreyne/cri
lib/cri/command_dsl.rb
Cri.CommandDSL.required
def required(short, long, desc, params = {}, &block) params = params.merge(argument: :required) option(short, long, desc, params, &block) end
ruby
def required(short, long, desc, params = {}, &block) params = params.merge(argument: :required) option(short, long, desc, params, &block) end
[ "def", "required", "(", "short", ",", "long", ",", "desc", ",", "params", "=", "{", "}", ",", "&", "block", ")", "params", "=", "params", ".", "merge", "(", "argument", ":", ":required", ")", "option", "(", "short", ",", "long", ",", "desc", ",", "params", ",", "block", ")", "end" ]
Adds a new option with a required argument to the command. If a block is given, it will be executed when the option is successfully parsed. @param [String, Symbol, nil] short The short option name @param [String, Symbol, nil] long The long option name @param [String] desc The option description @option params [Boolean] :multiple Whether or not the option should be multi-valued @option params [Boolean] :hidden Whether or not the option should be printed in the help output @return [void] @deprecated @see #option
[ "Adds", "a", "new", "option", "with", "a", "required", "argument", "to", "the", "command", ".", "If", "a", "block", "is", "given", "it", "will", "be", "executed", "when", "the", "option", "is", "successfully", "parsed", "." ]
4e4abafb352be093b63e0773e1d1d8869fc2ace9
https://github.com/ddfreyne/cri/blob/4e4abafb352be093b63e0773e1d1d8869fc2ace9/lib/cri/command_dsl.rb#L218-L221
train
ddfreyne/cri
lib/cri/parser.rb
Cri.Parser.run
def run @running = true while running? # Get next item e = @unprocessed_arguments_and_options.shift break if e.nil? if e == '--' handle_dashdash(e) elsif e =~ /^--./ && !@no_more_options handle_dashdash_option(e) elsif e =~ /^-./ && !@no_more_options handle_dash_option(e) else add_argument(e) end end add_defaults self ensure @running = false end
ruby
def run @running = true while running? # Get next item e = @unprocessed_arguments_and_options.shift break if e.nil? if e == '--' handle_dashdash(e) elsif e =~ /^--./ && !@no_more_options handle_dashdash_option(e) elsif e =~ /^-./ && !@no_more_options handle_dash_option(e) else add_argument(e) end end add_defaults self ensure @running = false end
[ "def", "run", "@running", "=", "true", "while", "running?", "# Get next item", "e", "=", "@unprocessed_arguments_and_options", ".", "shift", "break", "if", "e", ".", "nil?", "if", "e", "==", "'--'", "handle_dashdash", "(", "e", ")", "elsif", "e", "=~", "/", "/", "&&", "!", "@no_more_options", "handle_dashdash_option", "(", "e", ")", "elsif", "e", "=~", "/", "/", "&&", "!", "@no_more_options", "handle_dash_option", "(", "e", ")", "else", "add_argument", "(", "e", ")", "end", "end", "add_defaults", "self", "ensure", "@running", "=", "false", "end" ]
Parses the command-line arguments into options and arguments. During parsing, two errors can be raised: @raise IllegalOptionError if an unrecognised option was encountered, i.e. an option that is not present in the list of option definitions @raise OptionRequiresAnArgumentError if an option was found that did not have a value, even though this value was required. @return [Cri::Parser] The option parser self
[ "Parses", "the", "command", "-", "line", "arguments", "into", "options", "and", "arguments", "." ]
4e4abafb352be093b63e0773e1d1d8869fc2ace9
https://github.com/ddfreyne/cri/blob/4e4abafb352be093b63e0773e1d1d8869fc2ace9/lib/cri/parser.rb#L102-L126
train
ddfreyne/cri
lib/cri/string_formatter.rb
Cri.StringFormatter.wrap_and_indent
def wrap_and_indent(str, width, indentation, first_line_already_indented = false) indented_width = width - indentation indent = ' ' * indentation # Split into paragraphs paragraphs = to_paragraphs(str) # Wrap and indent each paragraph text = paragraphs.map do |paragraph| # Initialize lines = [] line = '' # Split into words paragraph.split(/\s/).each do |word| # Begin new line if it's too long if (line + ' ' + word).length >= indented_width lines << line line = '' end # Add word to line line += (line == '' ? '' : ' ') + word end lines << line # Join lines lines.map { |l| indent + l }.join("\n") end.join("\n\n") if first_line_already_indented text[indentation..-1] else text end end
ruby
def wrap_and_indent(str, width, indentation, first_line_already_indented = false) indented_width = width - indentation indent = ' ' * indentation # Split into paragraphs paragraphs = to_paragraphs(str) # Wrap and indent each paragraph text = paragraphs.map do |paragraph| # Initialize lines = [] line = '' # Split into words paragraph.split(/\s/).each do |word| # Begin new line if it's too long if (line + ' ' + word).length >= indented_width lines << line line = '' end # Add word to line line += (line == '' ? '' : ' ') + word end lines << line # Join lines lines.map { |l| indent + l }.join("\n") end.join("\n\n") if first_line_already_indented text[indentation..-1] else text end end
[ "def", "wrap_and_indent", "(", "str", ",", "width", ",", "indentation", ",", "first_line_already_indented", "=", "false", ")", "indented_width", "=", "width", "-", "indentation", "indent", "=", "' '", "*", "indentation", "# Split into paragraphs", "paragraphs", "=", "to_paragraphs", "(", "str", ")", "# Wrap and indent each paragraph", "text", "=", "paragraphs", ".", "map", "do", "|", "paragraph", "|", "# Initialize", "lines", "=", "[", "]", "line", "=", "''", "# Split into words", "paragraph", ".", "split", "(", "/", "\\s", "/", ")", ".", "each", "do", "|", "word", "|", "# Begin new line if it's too long", "if", "(", "line", "+", "' '", "+", "word", ")", ".", "length", ">=", "indented_width", "lines", "<<", "line", "line", "=", "''", "end", "# Add word to line", "line", "+=", "(", "line", "==", "''", "?", "''", ":", "' '", ")", "+", "word", "end", "lines", "<<", "line", "# Join lines", "lines", ".", "map", "{", "|", "l", "|", "indent", "+", "l", "}", ".", "join", "(", "\"\\n\"", ")", "end", ".", "join", "(", "\"\\n\\n\"", ")", "if", "first_line_already_indented", "text", "[", "indentation", "..", "-", "1", "]", "else", "text", "end", "end" ]
Word-wraps and indents the string. @param [String] str The string to format @param [Number] width The maximal width of each line. This also includes indentation, i.e. the actual maximal width of the text is `width`-`indentation`. @param [Number] indentation The number of spaces to indent each line. @param [Boolean] first_line_already_indented Whether or not the first line is already indented @return [String] The word-wrapped and indented string
[ "Word", "-", "wraps", "and", "indents", "the", "string", "." ]
4e4abafb352be093b63e0773e1d1d8869fc2ace9
https://github.com/ddfreyne/cri/blob/4e4abafb352be093b63e0773e1d1d8869fc2ace9/lib/cri/string_formatter.rb#L43-L77
train
ddfreyne/cri
lib/cri/help_renderer.rb
Cri.HelpRenderer.render
def render text = +'' append_summary(text) append_usage(text) append_description(text) append_subcommands(text) append_options(text) text end
ruby
def render text = +'' append_summary(text) append_usage(text) append_description(text) append_subcommands(text) append_options(text) text end
[ "def", "render", "text", "=", "+", "''", "append_summary", "(", "text", ")", "append_usage", "(", "text", ")", "append_description", "(", "text", ")", "append_subcommands", "(", "text", ")", "append_options", "(", "text", ")", "text", "end" ]
Creates a new help renderer for the given command. @param [Cri::Command] cmd The command to generate the help for @option params [Boolean] :verbose true if the help output should be verbose, false otherwise. @return [String] The help text for this command
[ "Creates", "a", "new", "help", "renderer", "for", "the", "given", "command", "." ]
4e4abafb352be093b63e0773e1d1d8869fc2ace9
https://github.com/ddfreyne/cri/blob/4e4abafb352be093b63e0773e1d1d8869fc2ace9/lib/cri/help_renderer.rb#L29-L39
train
ddfreyne/cri
lib/cri/command.rb
Cri.Command.modify
def modify(&block) dsl = Cri::CommandDSL.new(self) if [-1, 0].include? block.arity dsl.instance_eval(&block) else yield(dsl) end self end
ruby
def modify(&block) dsl = Cri::CommandDSL.new(self) if [-1, 0].include? block.arity dsl.instance_eval(&block) else yield(dsl) end self end
[ "def", "modify", "(", "&", "block", ")", "dsl", "=", "Cri", "::", "CommandDSL", ".", "new", "(", "self", ")", "if", "[", "-", "1", ",", "0", "]", ".", "include?", "block", ".", "arity", "dsl", ".", "instance_eval", "(", "block", ")", "else", "yield", "(", "dsl", ")", "end", "self", "end" ]
Modifies the command using the DSL. If the block has one parameter, the block will be executed in the same context with the command DSL as its parameter. If the block has no parameters, the block will be executed in the context of the DSL. @return [Cri::Command] The command itself
[ "Modifies", "the", "command", "using", "the", "DSL", "." ]
4e4abafb352be093b63e0773e1d1d8869fc2ace9
https://github.com/ddfreyne/cri/blob/4e4abafb352be093b63e0773e1d1d8869fc2ace9/lib/cri/command.rb#L185-L193
train
ddfreyne/cri
lib/cri/command.rb
Cri.Command.define_command
def define_command(name = nil, &block) # Execute DSL dsl = Cri::CommandDSL.new dsl.name name unless name.nil? if [-1, 0].include? block.arity dsl.instance_eval(&block) else yield(dsl) end # Create command cmd = dsl.command add_command(cmd) cmd end
ruby
def define_command(name = nil, &block) # Execute DSL dsl = Cri::CommandDSL.new dsl.name name unless name.nil? if [-1, 0].include? block.arity dsl.instance_eval(&block) else yield(dsl) end # Create command cmd = dsl.command add_command(cmd) cmd end
[ "def", "define_command", "(", "name", "=", "nil", ",", "&", "block", ")", "# Execute DSL", "dsl", "=", "Cri", "::", "CommandDSL", ".", "new", "dsl", ".", "name", "name", "unless", "name", ".", "nil?", "if", "[", "-", "1", ",", "0", "]", ".", "include?", "block", ".", "arity", "dsl", ".", "instance_eval", "(", "block", ")", "else", "yield", "(", "dsl", ")", "end", "# Create command", "cmd", "=", "dsl", ".", "command", "add_command", "(", "cmd", ")", "cmd", "end" ]
Defines a new subcommand for the current command using the DSL. @param [String, nil] name The name of the subcommand, or nil if no name should be set (yet) @return [Cri::Command] The subcommand
[ "Defines", "a", "new", "subcommand", "for", "the", "current", "command", "using", "the", "DSL", "." ]
4e4abafb352be093b63e0773e1d1d8869fc2ace9
https://github.com/ddfreyne/cri/blob/4e4abafb352be093b63e0773e1d1d8869fc2ace9/lib/cri/command.rb#L220-L234
train
ddfreyne/cri
lib/cri/command.rb
Cri.Command.commands_named
def commands_named(name) # Find by exact name or alias @commands.each do |cmd| found = cmd.name == name || cmd.aliases.include?(name) return [cmd] if found end # Find by approximation @commands.select do |cmd| cmd.name[0, name.length] == name end end
ruby
def commands_named(name) # Find by exact name or alias @commands.each do |cmd| found = cmd.name == name || cmd.aliases.include?(name) return [cmd] if found end # Find by approximation @commands.select do |cmd| cmd.name[0, name.length] == name end end
[ "def", "commands_named", "(", "name", ")", "# Find by exact name or alias", "@commands", ".", "each", "do", "|", "cmd", "|", "found", "=", "cmd", ".", "name", "==", "name", "||", "cmd", ".", "aliases", ".", "include?", "(", "name", ")", "return", "[", "cmd", "]", "if", "found", "end", "# Find by approximation", "@commands", ".", "select", "do", "|", "cmd", "|", "cmd", ".", "name", "[", "0", ",", "name", ".", "length", "]", "==", "name", "end", "end" ]
Returns the commands that could be referred to with the given name. If the result contains more than one command, the name is ambiguous. @param [String] name The full, partial or aliases name of the command @return [Array<Cri::Command>] A list of commands matching the given name
[ "Returns", "the", "commands", "that", "could", "be", "referred", "to", "with", "the", "given", "name", ".", "If", "the", "result", "contains", "more", "than", "one", "command", "the", "name", "is", "ambiguous", "." ]
4e4abafb352be093b63e0773e1d1d8869fc2ace9
https://github.com/ddfreyne/cri/blob/4e4abafb352be093b63e0773e1d1d8869fc2ace9/lib/cri/command.rb#L242-L253
train
ddfreyne/cri
lib/cri/command.rb
Cri.Command.run
def run(opts_and_args, parent_opts = {}, hard_exit: true) # Parse up to command name stuff = partition(opts_and_args) opts_before_subcmd, subcmd_name, opts_and_args_after_subcmd = *stuff if subcommands.empty? || (subcmd_name.nil? && !block.nil?) run_this(opts_and_args, parent_opts) else # Handle options handle_options(opts_before_subcmd) # Get command if subcmd_name.nil? if default_subcommand_name subcmd_name = default_subcommand_name else warn "#{name}: no command given" raise CriExitException.new(is_error: true) end end subcommand = command_named(subcmd_name, hard_exit: hard_exit) return if subcommand.nil? # Run subcommand.run(opts_and_args_after_subcmd, parent_opts.merge(opts_before_subcmd), hard_exit: hard_exit) end rescue CriExitException => e exit(e.error? ? 1 : 0) if hard_exit end
ruby
def run(opts_and_args, parent_opts = {}, hard_exit: true) # Parse up to command name stuff = partition(opts_and_args) opts_before_subcmd, subcmd_name, opts_and_args_after_subcmd = *stuff if subcommands.empty? || (subcmd_name.nil? && !block.nil?) run_this(opts_and_args, parent_opts) else # Handle options handle_options(opts_before_subcmd) # Get command if subcmd_name.nil? if default_subcommand_name subcmd_name = default_subcommand_name else warn "#{name}: no command given" raise CriExitException.new(is_error: true) end end subcommand = command_named(subcmd_name, hard_exit: hard_exit) return if subcommand.nil? # Run subcommand.run(opts_and_args_after_subcmd, parent_opts.merge(opts_before_subcmd), hard_exit: hard_exit) end rescue CriExitException => e exit(e.error? ? 1 : 0) if hard_exit end
[ "def", "run", "(", "opts_and_args", ",", "parent_opts", "=", "{", "}", ",", "hard_exit", ":", "true", ")", "# Parse up to command name", "stuff", "=", "partition", "(", "opts_and_args", ")", "opts_before_subcmd", ",", "subcmd_name", ",", "opts_and_args_after_subcmd", "=", "stuff", "if", "subcommands", ".", "empty?", "||", "(", "subcmd_name", ".", "nil?", "&&", "!", "block", ".", "nil?", ")", "run_this", "(", "opts_and_args", ",", "parent_opts", ")", "else", "# Handle options", "handle_options", "(", "opts_before_subcmd", ")", "# Get command", "if", "subcmd_name", ".", "nil?", "if", "default_subcommand_name", "subcmd_name", "=", "default_subcommand_name", "else", "warn", "\"#{name}: no command given\"", "raise", "CriExitException", ".", "new", "(", "is_error", ":", "true", ")", "end", "end", "subcommand", "=", "command_named", "(", "subcmd_name", ",", "hard_exit", ":", "hard_exit", ")", "return", "if", "subcommand", ".", "nil?", "# Run", "subcommand", ".", "run", "(", "opts_and_args_after_subcmd", ",", "parent_opts", ".", "merge", "(", "opts_before_subcmd", ")", ",", "hard_exit", ":", "hard_exit", ")", "end", "rescue", "CriExitException", "=>", "e", "exit", "(", "e", ".", "error?", "?", "1", ":", "0", ")", "if", "hard_exit", "end" ]
Runs the command with the given command-line arguments, possibly invoking subcommands and passing on the options and arguments. @param [Array<String>] opts_and_args A list of unparsed arguments @param [Hash] parent_opts A hash of options already handled by the supercommand @return [void]
[ "Runs", "the", "command", "with", "the", "given", "command", "-", "line", "arguments", "possibly", "invoking", "subcommands", "and", "passing", "on", "the", "options", "and", "arguments", "." ]
4e4abafb352be093b63e0773e1d1d8869fc2ace9
https://github.com/ddfreyne/cri/blob/4e4abafb352be093b63e0773e1d1d8869fc2ace9/lib/cri/command.rb#L290-L318
train
ddfreyne/cri
lib/cri/command.rb
Cri.Command.run_this
def run_this(opts_and_args, parent_opts = {}) if all_opts_as_args? args = opts_and_args global_opts = parent_opts else # Parse parser = Cri::Parser.new( opts_and_args, global_option_definitions, parameter_definitions, explicitly_no_params?, ) handle_errors_while { parser.run } local_opts = parser.options global_opts = parent_opts.merge(parser.options) # Handle options handle_options(local_opts) args = handle_errors_while { parser.gen_argument_list } end # Execute if block.nil? raise NotImplementedError, "No implementation available for '#{name}'" end block.call(global_opts, args, self) end
ruby
def run_this(opts_and_args, parent_opts = {}) if all_opts_as_args? args = opts_and_args global_opts = parent_opts else # Parse parser = Cri::Parser.new( opts_and_args, global_option_definitions, parameter_definitions, explicitly_no_params?, ) handle_errors_while { parser.run } local_opts = parser.options global_opts = parent_opts.merge(parser.options) # Handle options handle_options(local_opts) args = handle_errors_while { parser.gen_argument_list } end # Execute if block.nil? raise NotImplementedError, "No implementation available for '#{name}'" end block.call(global_opts, args, self) end
[ "def", "run_this", "(", "opts_and_args", ",", "parent_opts", "=", "{", "}", ")", "if", "all_opts_as_args?", "args", "=", "opts_and_args", "global_opts", "=", "parent_opts", "else", "# Parse", "parser", "=", "Cri", "::", "Parser", ".", "new", "(", "opts_and_args", ",", "global_option_definitions", ",", "parameter_definitions", ",", "explicitly_no_params?", ",", ")", "handle_errors_while", "{", "parser", ".", "run", "}", "local_opts", "=", "parser", ".", "options", "global_opts", "=", "parent_opts", ".", "merge", "(", "parser", ".", "options", ")", "# Handle options", "handle_options", "(", "local_opts", ")", "args", "=", "handle_errors_while", "{", "parser", ".", "gen_argument_list", "}", "end", "# Execute", "if", "block", ".", "nil?", "raise", "NotImplementedError", ",", "\"No implementation available for '#{name}'\"", "end", "block", ".", "call", "(", "global_opts", ",", "args", ",", "self", ")", "end" ]
Runs the actual command with the given command-line arguments, not invoking any subcommands. If the command does not have an execution block, an error ir raised. @param [Array<String>] opts_and_args A list of unparsed arguments @param [Hash] parent_opts A hash of options already handled by the supercommand @raise [NotImplementedError] if the command does not have an execution block @return [void]
[ "Runs", "the", "actual", "command", "with", "the", "given", "command", "-", "line", "arguments", "not", "invoking", "any", "subcommands", ".", "If", "the", "command", "does", "not", "have", "an", "execution", "block", "an", "error", "ir", "raised", "." ]
4e4abafb352be093b63e0773e1d1d8869fc2ace9
https://github.com/ddfreyne/cri/blob/4e4abafb352be093b63e0773e1d1d8869fc2ace9/lib/cri/command.rb#L333-L360
train
nwops/puppet-debugger
lib/puppet-debugger/support.rb
PuppetDebugger.Support.parse_error
def parse_error(error) case error when SocketError PuppetDebugger::Exception::ConnectError.new(message: "Unknown host: #{Puppet[:server]}") when Net::HTTPError PuppetDebugger::Exception::AuthError.new(message: error.message) when Errno::ECONNREFUSED PuppetDebugger::Exception::ConnectError.new(message: error.message) when Puppet::Error if error.message =~ /could\ not\ find\ class/i PuppetDebugger::Exception::NoClassError.new(default_modules_paths: default_modules_paths, message: error.message) elsif error.message =~ /default\ node/i PuppetDebugger::Exception::NodeDefinitionError.new(default_site_manifest: default_site_manifest, message: error.message) else error end else error end end
ruby
def parse_error(error) case error when SocketError PuppetDebugger::Exception::ConnectError.new(message: "Unknown host: #{Puppet[:server]}") when Net::HTTPError PuppetDebugger::Exception::AuthError.new(message: error.message) when Errno::ECONNREFUSED PuppetDebugger::Exception::ConnectError.new(message: error.message) when Puppet::Error if error.message =~ /could\ not\ find\ class/i PuppetDebugger::Exception::NoClassError.new(default_modules_paths: default_modules_paths, message: error.message) elsif error.message =~ /default\ node/i PuppetDebugger::Exception::NodeDefinitionError.new(default_site_manifest: default_site_manifest, message: error.message) else error end else error end end
[ "def", "parse_error", "(", "error", ")", "case", "error", "when", "SocketError", "PuppetDebugger", "::", "Exception", "::", "ConnectError", ".", "new", "(", "message", ":", "\"Unknown host: #{Puppet[:server]}\"", ")", "when", "Net", "::", "HTTPError", "PuppetDebugger", "::", "Exception", "::", "AuthError", ".", "new", "(", "message", ":", "error", ".", "message", ")", "when", "Errno", "::", "ECONNREFUSED", "PuppetDebugger", "::", "Exception", "::", "ConnectError", ".", "new", "(", "message", ":", "error", ".", "message", ")", "when", "Puppet", "::", "Error", "if", "error", ".", "message", "=~", "/", "\\ ", "\\ ", "\\ ", "/i", "PuppetDebugger", "::", "Exception", "::", "NoClassError", ".", "new", "(", "default_modules_paths", ":", "default_modules_paths", ",", "message", ":", "error", ".", "message", ")", "elsif", "error", ".", "message", "=~", "/", "\\ ", "/i", "PuppetDebugger", "::", "Exception", "::", "NodeDefinitionError", ".", "new", "(", "default_site_manifest", ":", "default_site_manifest", ",", "message", ":", "error", ".", "message", ")", "else", "error", "end", "else", "error", "end", "end" ]
parses the error type into a more useful error message defined in errors.rb returns new error object or the original if error cannot be parsed
[ "parses", "the", "error", "type", "into", "a", "more", "useful", "error", "message", "defined", "in", "errors", ".", "rb", "returns", "new", "error", "object", "or", "the", "original", "if", "error", "cannot", "be", "parsed" ]
ee9705ceec08dd1330c8bff6fb6bb55982496305
https://github.com/nwops/puppet-debugger/blob/ee9705ceec08dd1330c8bff6fb6bb55982496305/lib/puppet-debugger/support.rb#L24-L45
train
nwops/puppet-debugger
lib/puppet-debugger/support.rb
PuppetDebugger.Support.puppet_repl_lib_dir
def puppet_repl_lib_dir File.expand_path(File.join(File.dirname(File.dirname(File.dirname(__FILE__))), 'lib')) end
ruby
def puppet_repl_lib_dir File.expand_path(File.join(File.dirname(File.dirname(File.dirname(__FILE__))), 'lib')) end
[ "def", "puppet_repl_lib_dir", "File", ".", "expand_path", "(", "File", ".", "join", "(", "File", ".", "dirname", "(", "File", ".", "dirname", "(", "File", ".", "dirname", "(", "__FILE__", ")", ")", ")", ",", "'lib'", ")", ")", "end" ]
this is the lib directory of this gem in order to load any puppet functions from this gem we need to add the lib path of this gem
[ "this", "is", "the", "lib", "directory", "of", "this", "gem", "in", "order", "to", "load", "any", "puppet", "functions", "from", "this", "gem", "we", "need", "to", "add", "the", "lib", "path", "of", "this", "gem" ]
ee9705ceec08dd1330c8bff6fb6bb55982496305
https://github.com/nwops/puppet-debugger/blob/ee9705ceec08dd1330c8bff6fb6bb55982496305/lib/puppet-debugger/support.rb#L54-L56
train
nwops/puppet-debugger
lib/puppet-debugger/support.rb
PuppetDebugger.Support.do_initialize
def do_initialize Puppet.initialize_settings Puppet[:parser] = 'future' # this is required in order to work with puppet 3.8 Puppet[:trusted_node_data] = true rescue ArgumentError => e rescue Puppet::DevError => e # do nothing otherwise calling init twice raises an error end
ruby
def do_initialize Puppet.initialize_settings Puppet[:parser] = 'future' # this is required in order to work with puppet 3.8 Puppet[:trusted_node_data] = true rescue ArgumentError => e rescue Puppet::DevError => e # do nothing otherwise calling init twice raises an error end
[ "def", "do_initialize", "Puppet", ".", "initialize_settings", "Puppet", "[", ":parser", "]", "=", "'future'", "# this is required in order to work with puppet 3.8", "Puppet", "[", ":trusted_node_data", "]", "=", "true", "rescue", "ArgumentError", "=>", "e", "rescue", "Puppet", "::", "DevError", "=>", "e", "# do nothing otherwise calling init twice raises an error", "end" ]
this is required in order to load things only when we need them
[ "this", "is", "required", "in", "order", "to", "load", "things", "only", "when", "we", "need", "them" ]
ee9705ceec08dd1330c8bff6fb6bb55982496305
https://github.com/nwops/puppet-debugger/blob/ee9705ceec08dd1330c8bff6fb6bb55982496305/lib/puppet-debugger/support.rb#L87-L94
train
nwops/puppet-debugger
lib/puppet-debugger/cli.rb
PuppetDebugger.Cli.key_words
def key_words # because dollar signs don't work we can't display a $ sign in the keyword # list so its not explicitly clear what the keyword variables = scope.to_hash.keys # prepend a :: to topscope variables scoped_vars = variables.map { |k, _v| scope.compiler.topscope.exist?(k) ? "$::#{k}" : "$#{k}" } # append a () to functions so we know they are functions funcs = function_map.keys.map { |k| "#{k.split('::').last}()" } PuppetDebugger::InputResponders::Datatypes.instance.debugger = self (scoped_vars + funcs + static_responder_list + PuppetDebugger::InputResponders::Datatypes.instance.all_data_types).uniq.sort end
ruby
def key_words # because dollar signs don't work we can't display a $ sign in the keyword # list so its not explicitly clear what the keyword variables = scope.to_hash.keys # prepend a :: to topscope variables scoped_vars = variables.map { |k, _v| scope.compiler.topscope.exist?(k) ? "$::#{k}" : "$#{k}" } # append a () to functions so we know they are functions funcs = function_map.keys.map { |k| "#{k.split('::').last}()" } PuppetDebugger::InputResponders::Datatypes.instance.debugger = self (scoped_vars + funcs + static_responder_list + PuppetDebugger::InputResponders::Datatypes.instance.all_data_types).uniq.sort end
[ "def", "key_words", "# because dollar signs don't work we can't display a $ sign in the keyword", "# list so its not explicitly clear what the keyword", "variables", "=", "scope", ".", "to_hash", ".", "keys", "# prepend a :: to topscope variables", "scoped_vars", "=", "variables", ".", "map", "{", "|", "k", ",", "_v", "|", "scope", ".", "compiler", ".", "topscope", ".", "exist?", "(", "k", ")", "?", "\"$::#{k}\"", ":", "\"$#{k}\"", "}", "# append a () to functions so we know they are functions", "funcs", "=", "function_map", ".", "keys", ".", "map", "{", "|", "k", "|", "\"#{k.split('::').last}()\"", "}", "PuppetDebugger", "::", "InputResponders", "::", "Datatypes", ".", "instance", ".", "debugger", "=", "self", "(", "scoped_vars", "+", "funcs", "+", "static_responder_list", "+", "PuppetDebugger", "::", "InputResponders", "::", "Datatypes", ".", "instance", ".", "all_data_types", ")", ".", "uniq", ".", "sort", "end" ]
returns a cached list of key words
[ "returns", "a", "cached", "list", "of", "key", "words" ]
ee9705ceec08dd1330c8bff6fb6bb55982496305
https://github.com/nwops/puppet-debugger/blob/ee9705ceec08dd1330c8bff6fb6bb55982496305/lib/puppet-debugger/cli.rb#L66-L76
train
nwops/puppet-debugger
lib/puppet-debugger/cli.rb
PuppetDebugger.Cli.to_resource_declaration
def to_resource_declaration(type) if type.respond_to?(:type_name) && type.respond_to?(:title) title = type.title type_name = type.type_name elsif type_result = /(\w+)\['?(\w+)'?\]/.match(type.to_s) # not all types have a type_name and title so we # output to a string and parse the results title = type_result[2] type_name = type_result[1] else return type end res = scope.catalog.resource(type_name, title) return res.to_ral if res # don't return anything or returns nil if item is not in the catalog end
ruby
def to_resource_declaration(type) if type.respond_to?(:type_name) && type.respond_to?(:title) title = type.title type_name = type.type_name elsif type_result = /(\w+)\['?(\w+)'?\]/.match(type.to_s) # not all types have a type_name and title so we # output to a string and parse the results title = type_result[2] type_name = type_result[1] else return type end res = scope.catalog.resource(type_name, title) return res.to_ral if res # don't return anything or returns nil if item is not in the catalog end
[ "def", "to_resource_declaration", "(", "type", ")", "if", "type", ".", "respond_to?", "(", ":type_name", ")", "&&", "type", ".", "respond_to?", "(", ":title", ")", "title", "=", "type", ".", "title", "type_name", "=", "type", ".", "type_name", "elsif", "type_result", "=", "/", "\\w", "\\[", "\\w", "\\]", "/", ".", "match", "(", "type", ".", "to_s", ")", "# not all types have a type_name and title so we", "# output to a string and parse the results", "title", "=", "type_result", "[", "2", "]", "type_name", "=", "type_result", "[", "1", "]", "else", "return", "type", "end", "res", "=", "scope", ".", "catalog", ".", "resource", "(", "type_name", ",", "title", ")", "return", "res", ".", "to_ral", "if", "res", "# don't return anything or returns nil if item is not in the catalog", "end" ]
looks up the type in the catalog by using the type and title and returns the resource in ral format
[ "looks", "up", "the", "type", "in", "the", "catalog", "by", "using", "the", "type", "and", "title", "and", "returns", "the", "resource", "in", "ral", "format" ]
ee9705ceec08dd1330c8bff6fb6bb55982496305
https://github.com/nwops/puppet-debugger/blob/ee9705ceec08dd1330c8bff6fb6bb55982496305/lib/puppet-debugger/cli.rb#L80-L95
train
nwops/puppet-debugger
lib/puppet-debugger/cli.rb
PuppetDebugger.Cli.expand_resource_type
def expand_resource_type(types) output = [types].flatten.map do |t| if t.class.to_s =~ /Puppet::Pops::Types/ to_resource_declaration(t) else t end end output end
ruby
def expand_resource_type(types) output = [types].flatten.map do |t| if t.class.to_s =~ /Puppet::Pops::Types/ to_resource_declaration(t) else t end end output end
[ "def", "expand_resource_type", "(", "types", ")", "output", "=", "[", "types", "]", ".", "flatten", ".", "map", "do", "|", "t", "|", "if", "t", ".", "class", ".", "to_s", "=~", "/", "/", "to_resource_declaration", "(", "t", ")", "else", "t", "end", "end", "output", "end" ]
returns a formatted array
[ "returns", "a", "formatted", "array" ]
ee9705ceec08dd1330c8bff6fb6bb55982496305
https://github.com/nwops/puppet-debugger/blob/ee9705ceec08dd1330c8bff6fb6bb55982496305/lib/puppet-debugger/cli.rb#L98-L107
train
nwops/puppet-debugger
lib/puppet-debugger/cli.rb
PuppetDebugger.Cli.handle_input
def handle_input(input) raise ArgumentError unless input.instance_of?(String) begin output = '' case input.strip when PuppetDebugger::InputResponders::Commands.command_list_regex args = input.split(' ') command = args.shift plugin = PuppetDebugger::InputResponders::Commands.plugin_from_command(command) output = plugin.execute(args, self) return out_buffer.puts output when '_' output = " => #{@last_item}" else result = puppet_eval(input) @last_item = result output = normalize_output(result) output = output.nil? ? '' : output.ai end rescue PuppetDebugger::Exception::InvalidCommand => e output = e.message.fatal rescue LoadError => e output = e.message.fatal rescue Errno::ETIMEDOUT => e output = e.message.fatal rescue ArgumentError => e output = e.message.fatal rescue Puppet::ResourceError => e output = e.message.fatal rescue Puppet::Error => e output = e.message.fatal rescue Puppet::ParseErrorWithIssue => e output = e.message.fatal rescue PuppetDebugger::Exception::FatalError => e output = e.message.fatal out_buffer.puts output exit 1 # this can sometimes causes tests to fail rescue PuppetDebugger::Exception::Error => e output = e.message.fatal end unless output.empty? out_buffer.print ' => ' out_buffer.puts output unless output.empty? exec_hook :after_output, out_buffer, self, self end end
ruby
def handle_input(input) raise ArgumentError unless input.instance_of?(String) begin output = '' case input.strip when PuppetDebugger::InputResponders::Commands.command_list_regex args = input.split(' ') command = args.shift plugin = PuppetDebugger::InputResponders::Commands.plugin_from_command(command) output = plugin.execute(args, self) return out_buffer.puts output when '_' output = " => #{@last_item}" else result = puppet_eval(input) @last_item = result output = normalize_output(result) output = output.nil? ? '' : output.ai end rescue PuppetDebugger::Exception::InvalidCommand => e output = e.message.fatal rescue LoadError => e output = e.message.fatal rescue Errno::ETIMEDOUT => e output = e.message.fatal rescue ArgumentError => e output = e.message.fatal rescue Puppet::ResourceError => e output = e.message.fatal rescue Puppet::Error => e output = e.message.fatal rescue Puppet::ParseErrorWithIssue => e output = e.message.fatal rescue PuppetDebugger::Exception::FatalError => e output = e.message.fatal out_buffer.puts output exit 1 # this can sometimes causes tests to fail rescue PuppetDebugger::Exception::Error => e output = e.message.fatal end unless output.empty? out_buffer.print ' => ' out_buffer.puts output unless output.empty? exec_hook :after_output, out_buffer, self, self end end
[ "def", "handle_input", "(", "input", ")", "raise", "ArgumentError", "unless", "input", ".", "instance_of?", "(", "String", ")", "begin", "output", "=", "''", "case", "input", ".", "strip", "when", "PuppetDebugger", "::", "InputResponders", "::", "Commands", ".", "command_list_regex", "args", "=", "input", ".", "split", "(", "' '", ")", "command", "=", "args", ".", "shift", "plugin", "=", "PuppetDebugger", "::", "InputResponders", "::", "Commands", ".", "plugin_from_command", "(", "command", ")", "output", "=", "plugin", ".", "execute", "(", "args", ",", "self", ")", "return", "out_buffer", ".", "puts", "output", "when", "'_'", "output", "=", "\" => #{@last_item}\"", "else", "result", "=", "puppet_eval", "(", "input", ")", "@last_item", "=", "result", "output", "=", "normalize_output", "(", "result", ")", "output", "=", "output", ".", "nil?", "?", "''", ":", "output", ".", "ai", "end", "rescue", "PuppetDebugger", "::", "Exception", "::", "InvalidCommand", "=>", "e", "output", "=", "e", ".", "message", ".", "fatal", "rescue", "LoadError", "=>", "e", "output", "=", "e", ".", "message", ".", "fatal", "rescue", "Errno", "::", "ETIMEDOUT", "=>", "e", "output", "=", "e", ".", "message", ".", "fatal", "rescue", "ArgumentError", "=>", "e", "output", "=", "e", ".", "message", ".", "fatal", "rescue", "Puppet", "::", "ResourceError", "=>", "e", "output", "=", "e", ".", "message", ".", "fatal", "rescue", "Puppet", "::", "Error", "=>", "e", "output", "=", "e", ".", "message", ".", "fatal", "rescue", "Puppet", "::", "ParseErrorWithIssue", "=>", "e", "output", "=", "e", ".", "message", ".", "fatal", "rescue", "PuppetDebugger", "::", "Exception", "::", "FatalError", "=>", "e", "output", "=", "e", ".", "message", ".", "fatal", "out_buffer", ".", "puts", "output", "exit", "1", "# this can sometimes causes tests to fail", "rescue", "PuppetDebugger", "::", "Exception", "::", "Error", "=>", "e", "output", "=", "e", ".", "message", ".", "fatal", "end", "unless", "output", ".", "empty?", "out_buffer", ".", "print", "' => '", "out_buffer", ".", "puts", "output", "unless", "output", ".", "empty?", "exec_hook", ":after_output", ",", "out_buffer", ",", "self", ",", "self", "end", "end" ]
this method handles all input and expects a string of text.
[ "this", "method", "handles", "all", "input", "and", "expects", "a", "string", "of", "text", "." ]
ee9705ceec08dd1330c8bff6fb6bb55982496305
https://github.com/nwops/puppet-debugger/blob/ee9705ceec08dd1330c8bff6fb6bb55982496305/lib/puppet-debugger/cli.rb#L126-L171
train
nwops/puppet-debugger
lib/puppet-debugger/cli.rb
PuppetDebugger.Cli.read_loop
def read_loop line_number = 1 full_buffer = '' while buf = Readline.readline("#{line_number}:#{extra_prompt}>> ", true) begin full_buffer += buf # unless this is puppet code, otherwise skip repl keywords unless PuppetDebugger::InputResponders::Commands.command_list_regex.match(buf) line_number = line_number.next begin parser.parse_string(full_buffer) rescue Puppet::ParseErrorWithIssue => e if multiline_input?(e) out_buffer.print ' ' full_buffer += "\n" next end end end handle_input(full_buffer) full_buffer = '' end end end
ruby
def read_loop line_number = 1 full_buffer = '' while buf = Readline.readline("#{line_number}:#{extra_prompt}>> ", true) begin full_buffer += buf # unless this is puppet code, otherwise skip repl keywords unless PuppetDebugger::InputResponders::Commands.command_list_regex.match(buf) line_number = line_number.next begin parser.parse_string(full_buffer) rescue Puppet::ParseErrorWithIssue => e if multiline_input?(e) out_buffer.print ' ' full_buffer += "\n" next end end end handle_input(full_buffer) full_buffer = '' end end end
[ "def", "read_loop", "line_number", "=", "1", "full_buffer", "=", "''", "while", "buf", "=", "Readline", ".", "readline", "(", "\"#{line_number}:#{extra_prompt}>> \"", ",", "true", ")", "begin", "full_buffer", "+=", "buf", "# unless this is puppet code, otherwise skip repl keywords", "unless", "PuppetDebugger", "::", "InputResponders", "::", "Commands", ".", "command_list_regex", ".", "match", "(", "buf", ")", "line_number", "=", "line_number", ".", "next", "begin", "parser", ".", "parse_string", "(", "full_buffer", ")", "rescue", "Puppet", "::", "ParseErrorWithIssue", "=>", "e", "if", "multiline_input?", "(", "e", ")", "out_buffer", ".", "print", "' '", "full_buffer", "+=", "\"\\n\"", "next", "end", "end", "end", "handle_input", "(", "full_buffer", ")", "full_buffer", "=", "''", "end", "end", "end" ]
reads input from stdin, since readline requires a tty we cannot read from other sources as readline requires a file object we parse the string after each input to determine if the input is a multiline_input entry. If it is multiline we run through the loop again and concatenate the input
[ "reads", "input", "from", "stdin", "since", "readline", "requires", "a", "tty", "we", "cannot", "read", "from", "other", "sources", "as", "readline", "requires", "a", "file", "object", "we", "parse", "the", "string", "after", "each", "input", "to", "determine", "if", "the", "input", "is", "a", "multiline_input", "entry", ".", "If", "it", "is", "multiline", "we", "run", "through", "the", "loop", "again", "and", "concatenate", "the", "input" ]
ee9705ceec08dd1330c8bff6fb6bb55982496305
https://github.com/nwops/puppet-debugger/blob/ee9705ceec08dd1330c8bff6fb6bb55982496305/lib/puppet-debugger/cli.rb#L204-L227
train
ruby-oembed/ruby-oembed
lib/oembed/http_helper.rb
OEmbed.HttpHelper.http_get
def http_get(uri, options = {}) found = false remaining_redirects = options[:max_redirects] ? options[:max_redirects].to_i : 4 until found http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = uri.scheme == 'https' http.verify_mode = OpenSSL::SSL::VERIFY_PEER http.read_timeout = http.open_timeout = options[:timeout] if options[:timeout] methods = if RUBY_VERSION < "2.2" %w{scheme userinfo host port registry} else %w{scheme userinfo host port} end methods.each { |method| uri.send("#{method}=", nil) } req = Net::HTTP::Get.new(uri.to_s) req['User-Agent'] = "Mozilla/5.0 (compatible; ruby-oembed/#{OEmbed::VERSION})" res = http.request(req) if remaining_redirects == 0 found = true elsif res.is_a?(Net::HTTPRedirection) && res.header['location'] uri = URI.parse(res.header['location']) remaining_redirects -= 1 else found = true end end case res when Net::HTTPNotImplemented raise OEmbed::UnknownFormat when Net::HTTPNotFound raise OEmbed::NotFound, uri when Net::HTTPSuccess res.body else raise OEmbed::UnknownResponse, res && res.respond_to?(:code) ? res.code : 'Error' end rescue StandardError # Convert known errors into OEmbed::UnknownResponse for easy catching # up the line. This is important if given a URL that doesn't support # OEmbed. The following are known errors: # * Net::* errors like Net::HTTPBadResponse # * JSON::JSONError errors like JSON::ParserError if defined?(::JSON) && $!.is_a?(::JSON::JSONError) || $!.class.to_s =~ /\ANet::/ raise OEmbed::UnknownResponse, res && res.respond_to?(:code) ? res.code : 'Error' else raise $! end end
ruby
def http_get(uri, options = {}) found = false remaining_redirects = options[:max_redirects] ? options[:max_redirects].to_i : 4 until found http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = uri.scheme == 'https' http.verify_mode = OpenSSL::SSL::VERIFY_PEER http.read_timeout = http.open_timeout = options[:timeout] if options[:timeout] methods = if RUBY_VERSION < "2.2" %w{scheme userinfo host port registry} else %w{scheme userinfo host port} end methods.each { |method| uri.send("#{method}=", nil) } req = Net::HTTP::Get.new(uri.to_s) req['User-Agent'] = "Mozilla/5.0 (compatible; ruby-oembed/#{OEmbed::VERSION})" res = http.request(req) if remaining_redirects == 0 found = true elsif res.is_a?(Net::HTTPRedirection) && res.header['location'] uri = URI.parse(res.header['location']) remaining_redirects -= 1 else found = true end end case res when Net::HTTPNotImplemented raise OEmbed::UnknownFormat when Net::HTTPNotFound raise OEmbed::NotFound, uri when Net::HTTPSuccess res.body else raise OEmbed::UnknownResponse, res && res.respond_to?(:code) ? res.code : 'Error' end rescue StandardError # Convert known errors into OEmbed::UnknownResponse for easy catching # up the line. This is important if given a URL that doesn't support # OEmbed. The following are known errors: # * Net::* errors like Net::HTTPBadResponse # * JSON::JSONError errors like JSON::ParserError if defined?(::JSON) && $!.is_a?(::JSON::JSONError) || $!.class.to_s =~ /\ANet::/ raise OEmbed::UnknownResponse, res && res.respond_to?(:code) ? res.code : 'Error' else raise $! end end
[ "def", "http_get", "(", "uri", ",", "options", "=", "{", "}", ")", "found", "=", "false", "remaining_redirects", "=", "options", "[", ":max_redirects", "]", "?", "options", "[", ":max_redirects", "]", ".", "to_i", ":", "4", "until", "found", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "http", ".", "use_ssl", "=", "uri", ".", "scheme", "==", "'https'", "http", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_PEER", "http", ".", "read_timeout", "=", "http", ".", "open_timeout", "=", "options", "[", ":timeout", "]", "if", "options", "[", ":timeout", "]", "methods", "=", "if", "RUBY_VERSION", "<", "\"2.2\"", "%w{", "scheme", "userinfo", "host", "port", "registry", "}", "else", "%w{", "scheme", "userinfo", "host", "port", "}", "end", "methods", ".", "each", "{", "|", "method", "|", "uri", ".", "send", "(", "\"#{method}=\"", ",", "nil", ")", "}", "req", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "uri", ".", "to_s", ")", "req", "[", "'User-Agent'", "]", "=", "\"Mozilla/5.0 (compatible; ruby-oembed/#{OEmbed::VERSION})\"", "res", "=", "http", ".", "request", "(", "req", ")", "if", "remaining_redirects", "==", "0", "found", "=", "true", "elsif", "res", ".", "is_a?", "(", "Net", "::", "HTTPRedirection", ")", "&&", "res", ".", "header", "[", "'location'", "]", "uri", "=", "URI", ".", "parse", "(", "res", ".", "header", "[", "'location'", "]", ")", "remaining_redirects", "-=", "1", "else", "found", "=", "true", "end", "end", "case", "res", "when", "Net", "::", "HTTPNotImplemented", "raise", "OEmbed", "::", "UnknownFormat", "when", "Net", "::", "HTTPNotFound", "raise", "OEmbed", "::", "NotFound", ",", "uri", "when", "Net", "::", "HTTPSuccess", "res", ".", "body", "else", "raise", "OEmbed", "::", "UnknownResponse", ",", "res", "&&", "res", ".", "respond_to?", "(", ":code", ")", "?", "res", ".", "code", ":", "'Error'", "end", "rescue", "StandardError", "# Convert known errors into OEmbed::UnknownResponse for easy catching", "# up the line. This is important if given a URL that doesn't support", "# OEmbed. The following are known errors:", "# * Net::* errors like Net::HTTPBadResponse", "# * JSON::JSONError errors like JSON::ParserError", "if", "defined?", "(", "::", "JSON", ")", "&&", "$!", ".", "is_a?", "(", "::", "JSON", "::", "JSONError", ")", "||", "$!", ".", "class", ".", "to_s", "=~", "/", "\\A", "/", "raise", "OEmbed", "::", "UnknownResponse", ",", "res", "&&", "res", ".", "respond_to?", "(", ":code", ")", "?", "res", ".", "code", ":", "'Error'", "else", "raise", "$!", "end", "end" ]
Given a URI, make an HTTP request The options Hash recognizes the following keys: :timeout:: specifies the timeout (in seconds) for the http request. :max_redirects:: the number of times this request will follow 3XX redirects before throwing an error. Default: 4
[ "Given", "a", "URI", "make", "an", "HTTP", "request" ]
cd3f3531e3b0d1d0dec833af6f2b5142fc35be0f
https://github.com/ruby-oembed/ruby-oembed/blob/cd3f3531e3b0d1d0dec833af6f2b5142fc35be0f/lib/oembed/http_helper.rb#L13-L63
train
nwops/puppet-debugger
lib/awesome_print/ext/awesome_puppet.rb
AwesomePrint.Puppet.cast_with_puppet_resource
def cast_with_puppet_resource(object, type) cast = cast_without_puppet_resource(object, type) # check the object to see if it has an acestor (< ) of the specified type if defined?(::Puppet::Type) && (object.class < ::Puppet::Type) cast = :puppet_type elsif defined?(::Puppet::Pops::Types) && (object.class < ::Puppet::Pops::Types) cast = :puppet_type elsif defined?(::Puppet::Parser::Resource) && (object.class < ::Puppet::Parser::Resource) cast = :puppet_resource elsif /Puppet::Pops::Types/.match(object.class.to_s) cast = :puppet_type end cast end
ruby
def cast_with_puppet_resource(object, type) cast = cast_without_puppet_resource(object, type) # check the object to see if it has an acestor (< ) of the specified type if defined?(::Puppet::Type) && (object.class < ::Puppet::Type) cast = :puppet_type elsif defined?(::Puppet::Pops::Types) && (object.class < ::Puppet::Pops::Types) cast = :puppet_type elsif defined?(::Puppet::Parser::Resource) && (object.class < ::Puppet::Parser::Resource) cast = :puppet_resource elsif /Puppet::Pops::Types/.match(object.class.to_s) cast = :puppet_type end cast end
[ "def", "cast_with_puppet_resource", "(", "object", ",", "type", ")", "cast", "=", "cast_without_puppet_resource", "(", "object", ",", "type", ")", "# check the object to see if it has an acestor (< ) of the specified type", "if", "defined?", "(", "::", "Puppet", "::", "Type", ")", "&&", "(", "object", ".", "class", "<", "::", "Puppet", "::", "Type", ")", "cast", "=", ":puppet_type", "elsif", "defined?", "(", "::", "Puppet", "::", "Pops", "::", "Types", ")", "&&", "(", "object", ".", "class", "<", "::", "Puppet", "::", "Pops", "::", "Types", ")", "cast", "=", ":puppet_type", "elsif", "defined?", "(", "::", "Puppet", "::", "Parser", "::", "Resource", ")", "&&", "(", "object", ".", "class", "<", "::", "Puppet", "::", "Parser", "::", "Resource", ")", "cast", "=", ":puppet_resource", "elsif", "/", "/", ".", "match", "(", "object", ".", "class", ".", "to_s", ")", "cast", "=", ":puppet_type", "end", "cast", "end" ]
this tells ap how to cast our object so we can be specific about printing different puppet objects
[ "this", "tells", "ap", "how", "to", "cast", "our", "object", "so", "we", "can", "be", "specific", "about", "printing", "different", "puppet", "objects" ]
ee9705ceec08dd1330c8bff6fb6bb55982496305
https://github.com/nwops/puppet-debugger/blob/ee9705ceec08dd1330c8bff6fb6bb55982496305/lib/awesome_print/ext/awesome_puppet.rb#L26-L39
train
nwops/puppet-debugger
lib/puppet-debugger/hooks.rb
PuppetDebugger.Hooks.initialize_copy
def initialize_copy(orig) hooks_dup = @hooks.dup @hooks.each do |k, v| hooks_dup[k] = v.dup end @hooks = hooks_dup end
ruby
def initialize_copy(orig) hooks_dup = @hooks.dup @hooks.each do |k, v| hooks_dup[k] = v.dup end @hooks = hooks_dup end
[ "def", "initialize_copy", "(", "orig", ")", "hooks_dup", "=", "@hooks", ".", "dup", "@hooks", ".", "each", "do", "|", "k", ",", "v", "|", "hooks_dup", "[", "k", "]", "=", "v", ".", "dup", "end", "@hooks", "=", "hooks_dup", "end" ]
Ensure that duplicates have their @hooks object.
[ "Ensure", "that", "duplicates", "have", "their" ]
ee9705ceec08dd1330c8bff6fb6bb55982496305
https://github.com/nwops/puppet-debugger/blob/ee9705ceec08dd1330c8bff6fb6bb55982496305/lib/puppet-debugger/hooks.rb#L21-L28
train
nwops/puppet-debugger
lib/puppet-debugger/hooks.rb
PuppetDebugger.Hooks.add_hook
def add_hook(event_name, hook_name, callable=nil, &block) event_name = event_name.to_s # do not allow duplicates, but allow multiple `nil` hooks # (anonymous hooks) if hook_exists?(event_name, hook_name) && !hook_name.nil? raise ArgumentError, "Hook with name '#{hook_name}' already defined!" end if !block && !callable raise ArgumentError, "Must provide a block or callable." end # ensure we only have one anonymous hook @hooks[event_name].delete_if { |h, k| h.nil? } if hook_name.nil? if block @hooks[event_name] << [hook_name, block] elsif callable @hooks[event_name] << [hook_name, callable] end self end
ruby
def add_hook(event_name, hook_name, callable=nil, &block) event_name = event_name.to_s # do not allow duplicates, but allow multiple `nil` hooks # (anonymous hooks) if hook_exists?(event_name, hook_name) && !hook_name.nil? raise ArgumentError, "Hook with name '#{hook_name}' already defined!" end if !block && !callable raise ArgumentError, "Must provide a block or callable." end # ensure we only have one anonymous hook @hooks[event_name].delete_if { |h, k| h.nil? } if hook_name.nil? if block @hooks[event_name] << [hook_name, block] elsif callable @hooks[event_name] << [hook_name, callable] end self end
[ "def", "add_hook", "(", "event_name", ",", "hook_name", ",", "callable", "=", "nil", ",", "&", "block", ")", "event_name", "=", "event_name", ".", "to_s", "# do not allow duplicates, but allow multiple `nil` hooks", "# (anonymous hooks)", "if", "hook_exists?", "(", "event_name", ",", "hook_name", ")", "&&", "!", "hook_name", ".", "nil?", "raise", "ArgumentError", ",", "\"Hook with name '#{hook_name}' already defined!\"", "end", "if", "!", "block", "&&", "!", "callable", "raise", "ArgumentError", ",", "\"Must provide a block or callable.\"", "end", "# ensure we only have one anonymous hook", "@hooks", "[", "event_name", "]", ".", "delete_if", "{", "|", "h", ",", "k", "|", "h", ".", "nil?", "}", "if", "hook_name", ".", "nil?", "if", "block", "@hooks", "[", "event_name", "]", "<<", "[", "hook_name", ",", "block", "]", "elsif", "callable", "@hooks", "[", "event_name", "]", "<<", "[", "hook_name", ",", "callable", "]", "end", "self", "end" ]
Add a new hook to be executed for the `event_name` event. @param [Symbol] event_name The name of the event. @param [Symbol] hook_name The name of the hook. @param [#call] callable The callable. @yield The block to use as the callable (if no `callable` provided). @return [PuppetDebugger::Hooks] The receiver.
[ "Add", "a", "new", "hook", "to", "be", "executed", "for", "the", "event_name", "event", "." ]
ee9705ceec08dd1330c8bff6fb6bb55982496305
https://github.com/nwops/puppet-debugger/blob/ee9705ceec08dd1330c8bff6fb6bb55982496305/lib/puppet-debugger/hooks.rb#L71-L94
train
nwops/puppet-debugger
lib/puppet-debugger/hooks.rb
PuppetDebugger.Hooks.exec_hook
def exec_hook(event_name, *args, &block) @hooks[event_name.to_s].map do |hook_name, callable| begin callable.call(*args, &block) rescue PuppetDebugger::Exception::Error, ::RuntimeError => e errors << e e end end.last end
ruby
def exec_hook(event_name, *args, &block) @hooks[event_name.to_s].map do |hook_name, callable| begin callable.call(*args, &block) rescue PuppetDebugger::Exception::Error, ::RuntimeError => e errors << e e end end.last end
[ "def", "exec_hook", "(", "event_name", ",", "*", "args", ",", "&", "block", ")", "@hooks", "[", "event_name", ".", "to_s", "]", ".", "map", "do", "|", "hook_name", ",", "callable", "|", "begin", "callable", ".", "call", "(", "args", ",", "block", ")", "rescue", "PuppetDebugger", "::", "Exception", "::", "Error", ",", "::", "RuntimeError", "=>", "e", "errors", "<<", "e", "e", "end", "end", ".", "last", "end" ]
Execute the list of hooks for the `event_name` event. @param [Symbol] event_name The name of the event. @param [Array] args The arguments to pass to each hook function. @return [Object] The return value of the last executed hook.
[ "Execute", "the", "list", "of", "hooks", "for", "the", "event_name", "event", "." ]
ee9705ceec08dd1330c8bff6fb6bb55982496305
https://github.com/nwops/puppet-debugger/blob/ee9705ceec08dd1330c8bff6fb6bb55982496305/lib/puppet-debugger/hooks.rb#L100-L109
train
acquia/sf-sdk-ruby
lib/sfrest/task.rb
SFRest.Task.task_status
def task_status(task_id) current_path = "/api/v1/wip/task/#{task_id}/status" res = @conn.get(current_path) raise InvalidDataError, "No wip task returned for task id #{task_id}" if res['wip_task'].nil? raise InvalidDataError, "No task status returned for task id #{task_id}" if res['wip_task']['status'].nil? res['wip_task']['status'] end
ruby
def task_status(task_id) current_path = "/api/v1/wip/task/#{task_id}/status" res = @conn.get(current_path) raise InvalidDataError, "No wip task returned for task id #{task_id}" if res['wip_task'].nil? raise InvalidDataError, "No task status returned for task id #{task_id}" if res['wip_task']['status'].nil? res['wip_task']['status'] end
[ "def", "task_status", "(", "task_id", ")", "current_path", "=", "\"/api/v1/wip/task/#{task_id}/status\"", "res", "=", "@conn", ".", "get", "(", "current_path", ")", "raise", "InvalidDataError", ",", "\"No wip task returned for task id #{task_id}\"", "if", "res", "[", "'wip_task'", "]", ".", "nil?", "raise", "InvalidDataError", ",", "\"No task status returned for task id #{task_id}\"", "if", "res", "[", "'wip_task'", "]", "[", "'status'", "]", ".", "nil?", "res", "[", "'wip_task'", "]", "[", "'status'", "]", "end" ]
Get the status of a wip task by id. @param [Integer] task_id @return [Hash{"wip_task" => {"id" => Integer, "status" => Integer}, "time" => timestamp}]
[ "Get", "the", "status", "of", "a", "wip", "task", "by", "id", "." ]
c0e9f2a72cd111b1d3213d012bfe7868d88eb1f8
https://github.com/acquia/sf-sdk-ruby/blob/c0e9f2a72cd111b1d3213d012bfe7868d88eb1f8/lib/sfrest/task.rb#L81-L88
train
acquia/sf-sdk-ruby
lib/sfrest/task.rb
SFRest.Task.find_task_ids
def find_task_ids(limit = nil, page = nil, group = nil, klass = nil, status = nil) res = find_tasks limit: limit, page: page, group: group, klass: klass, status: status task_ids = [] i = 0 res.each do |task| task_ids[i] = task['id'] i += 1 end task_ids end
ruby
def find_task_ids(limit = nil, page = nil, group = nil, klass = nil, status = nil) res = find_tasks limit: limit, page: page, group: group, klass: klass, status: status task_ids = [] i = 0 res.each do |task| task_ids[i] = task['id'] i += 1 end task_ids end
[ "def", "find_task_ids", "(", "limit", "=", "nil", ",", "page", "=", "nil", ",", "group", "=", "nil", ",", "klass", "=", "nil", ",", "status", "=", "nil", ")", "res", "=", "find_tasks", "limit", ":", "limit", ",", "page", ":", "page", ",", "group", ":", "group", ",", "klass", ":", "klass", ",", "status", ":", "status", "task_ids", "=", "[", "]", "i", "=", "0", "res", ".", "each", "do", "|", "task", "|", "task_ids", "[", "i", "]", "=", "task", "[", "'id'", "]", "i", "+=", "1", "end", "task_ids", "end" ]
Find a set of task ids. @param [Integer] limit max amount of results to return per request @param [Integer] page page of request @param [String] group task group @param [String] klass task class @param [Integer] status Integerish the status of the task see SFRest::Task::STATUS_* @return [Array[Integer]]
[ "Find", "a", "set", "of", "task", "ids", "." ]
c0e9f2a72cd111b1d3213d012bfe7868d88eb1f8
https://github.com/acquia/sf-sdk-ruby/blob/c0e9f2a72cd111b1d3213d012bfe7868d88eb1f8/lib/sfrest/task.rb#L148-L157
train
acquia/sf-sdk-ruby
lib/sfrest/task.rb
SFRest.Task.find_tasks
def find_tasks(datum = nil) current_path = '/api/v1/tasks' pb = SFRest::Pathbuilder.new @conn.get URI.parse(pb.build_url_query(current_path, datum)).to_s end
ruby
def find_tasks(datum = nil) current_path = '/api/v1/tasks' pb = SFRest::Pathbuilder.new @conn.get URI.parse(pb.build_url_query(current_path, datum)).to_s end
[ "def", "find_tasks", "(", "datum", "=", "nil", ")", "current_path", "=", "'/api/v1/tasks'", "pb", "=", "SFRest", "::", "Pathbuilder", ".", "new", "@conn", ".", "get", "URI", ".", "parse", "(", "pb", ".", "build_url_query", "(", "current_path", ",", "datum", ")", ")", ".", "to_s", "end" ]
Find a set of tasks. @param [Hash] datum Hash of filters @option datum [Integer] :limit max amount of results to return per request @option datum [Integer] :page page of request @option datum [String] :group task group @option datum [String] :class task class @option datum [Integer] :status Integerish the status of the task see SFRest::Task::STATUS_*
[ "Find", "a", "set", "of", "tasks", "." ]
c0e9f2a72cd111b1d3213d012bfe7868d88eb1f8
https://github.com/acquia/sf-sdk-ruby/blob/c0e9f2a72cd111b1d3213d012bfe7868d88eb1f8/lib/sfrest/task.rb#L167-L171
train