id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
1,300
nledez/proxmox
lib/proxmox.rb
Proxmox.Proxmox.extract_ticket
def extract_ticket(response) data = JSON.parse(response.body) ticket = data['data']['ticket'] csrf_prevention_token = data['data']['CSRFPreventionToken'] unless ticket.nil? token = 'PVEAuthCookie=' + ticket.gsub!(/:/, '%3A').gsub!(/=/, '%3D') end @connection_status = 'connected' { CSRFPreventionToken: csrf_prevention_token, cookie: token } end
ruby
def extract_ticket(response) data = JSON.parse(response.body) ticket = data['data']['ticket'] csrf_prevention_token = data['data']['CSRFPreventionToken'] unless ticket.nil? token = 'PVEAuthCookie=' + ticket.gsub!(/:/, '%3A').gsub!(/=/, '%3D') end @connection_status = 'connected' { CSRFPreventionToken: csrf_prevention_token, cookie: token } end
[ "def", "extract_ticket", "(", "response", ")", "data", "=", "JSON", ".", "parse", "(", "response", ".", "body", ")", "ticket", "=", "data", "[", "'data'", "]", "[", "'ticket'", "]", "csrf_prevention_token", "=", "data", "[", "'data'", "]", "[", "'CSRFPreventionToken'", "]", "unless", "ticket", ".", "nil?", "token", "=", "'PVEAuthCookie='", "+", "ticket", ".", "gsub!", "(", "/", "/", ",", "'%3A'", ")", ".", "gsub!", "(", "/", "/", ",", "'%3D'", ")", "end", "@connection_status", "=", "'connected'", "{", "CSRFPreventionToken", ":", "csrf_prevention_token", ",", "cookie", ":", "token", "}", "end" ]
Method create ticket
[ "Method", "create", "ticket" ]
cc679cc69deb78b20f88074b235e172869070a0d
https://github.com/nledez/proxmox/blob/cc679cc69deb78b20f88074b235e172869070a0d/lib/proxmox.rb#L352-L364
1,301
nledez/proxmox
lib/proxmox.rb
Proxmox.Proxmox.check_response
def check_response(response) if response.code == 200 JSON.parse(response.body)['data'] else 'NOK: error code = ' + response.code.to_s end end
ruby
def check_response(response) if response.code == 200 JSON.parse(response.body)['data'] else 'NOK: error code = ' + response.code.to_s end end
[ "def", "check_response", "(", "response", ")", "if", "response", ".", "code", "==", "200", "JSON", ".", "parse", "(", "response", ".", "body", ")", "[", "'data'", "]", "else", "'NOK: error code = '", "+", "response", ".", "code", ".", "to_s", "end", "end" ]
Extract data or return error
[ "Extract", "data", "or", "return", "error" ]
cc679cc69deb78b20f88074b235e172869070a0d
https://github.com/nledez/proxmox/blob/cc679cc69deb78b20f88074b235e172869070a0d/lib/proxmox.rb#L367-L373
1,302
nledez/proxmox
lib/proxmox.rb
Proxmox.Proxmox.http_action_post
def http_action_post(url, data = {}) @site[url].post data, @auth_params do |response, _request, _result, &_block| check_response response end end
ruby
def http_action_post(url, data = {}) @site[url].post data, @auth_params do |response, _request, _result, &_block| check_response response end end
[ "def", "http_action_post", "(", "url", ",", "data", "=", "{", "}", ")", "@site", "[", "url", "]", ".", "post", "data", ",", "@auth_params", "do", "|", "response", ",", "_request", ",", "_result", ",", "&", "_block", "|", "check_response", "response", "end", "end" ]
Methods manage http dialogs
[ "Methods", "manage", "http", "dialogs" ]
cc679cc69deb78b20f88074b235e172869070a0d
https://github.com/nledez/proxmox/blob/cc679cc69deb78b20f88074b235e172869070a0d/lib/proxmox.rb#L376-L380
1,303
farcaller/rly
lib/rly/lex.rb
Rly.Lex.next
def next while @pos < @input.length if self.class.ignores_list[@input[@pos]] ignore_symbol next end m = self.class.token_regexps.match(@input[@pos..-1]) if m && ! m[0].empty? val = nil type = nil resolved_type = nil m.names.each do |n| if m[n] type = n.to_sym resolved_type = (n.start_with?('__anonymous_') ? nil : type) val = m[n] break end end if type tok = build_token(resolved_type, val) @pos += m.end(0) tok = self.class.callables[type].call(tok) if self.class.callables[type] if tok && tok.type return tok else next end end end if self.class.literals_list[@input[@pos]] tok = build_token(@input[@pos], @input[@pos]) matched = true @pos += 1 return tok end if self.class.error_hander pos = @pos tok = build_token(:error, @input[@pos]) tok = self.class.error_hander.call(tok) if pos == @pos raise LexError.new("Illegal character '#{@input[@pos]}' at index #{@pos}") else return tok if tok && tok.type end else raise LexError.new("Illegal character '#{@input[@pos]}' at index #{@pos}") end end return nil end
ruby
def next while @pos < @input.length if self.class.ignores_list[@input[@pos]] ignore_symbol next end m = self.class.token_regexps.match(@input[@pos..-1]) if m && ! m[0].empty? val = nil type = nil resolved_type = nil m.names.each do |n| if m[n] type = n.to_sym resolved_type = (n.start_with?('__anonymous_') ? nil : type) val = m[n] break end end if type tok = build_token(resolved_type, val) @pos += m.end(0) tok = self.class.callables[type].call(tok) if self.class.callables[type] if tok && tok.type return tok else next end end end if self.class.literals_list[@input[@pos]] tok = build_token(@input[@pos], @input[@pos]) matched = true @pos += 1 return tok end if self.class.error_hander pos = @pos tok = build_token(:error, @input[@pos]) tok = self.class.error_hander.call(tok) if pos == @pos raise LexError.new("Illegal character '#{@input[@pos]}' at index #{@pos}") else return tok if tok && tok.type end else raise LexError.new("Illegal character '#{@input[@pos]}' at index #{@pos}") end end return nil end
[ "def", "next", "while", "@pos", "<", "@input", ".", "length", "if", "self", ".", "class", ".", "ignores_list", "[", "@input", "[", "@pos", "]", "]", "ignore_symbol", "next", "end", "m", "=", "self", ".", "class", ".", "token_regexps", ".", "match", "(", "@input", "[", "@pos", "..", "-", "1", "]", ")", "if", "m", "&&", "!", "m", "[", "0", "]", ".", "empty?", "val", "=", "nil", "type", "=", "nil", "resolved_type", "=", "nil", "m", ".", "names", ".", "each", "do", "|", "n", "|", "if", "m", "[", "n", "]", "type", "=", "n", ".", "to_sym", "resolved_type", "=", "(", "n", ".", "start_with?", "(", "'__anonymous_'", ")", "?", "nil", ":", "type", ")", "val", "=", "m", "[", "n", "]", "break", "end", "end", "if", "type", "tok", "=", "build_token", "(", "resolved_type", ",", "val", ")", "@pos", "+=", "m", ".", "end", "(", "0", ")", "tok", "=", "self", ".", "class", ".", "callables", "[", "type", "]", ".", "call", "(", "tok", ")", "if", "self", ".", "class", ".", "callables", "[", "type", "]", "if", "tok", "&&", "tok", ".", "type", "return", "tok", "else", "next", "end", "end", "end", "if", "self", ".", "class", ".", "literals_list", "[", "@input", "[", "@pos", "]", "]", "tok", "=", "build_token", "(", "@input", "[", "@pos", "]", ",", "@input", "[", "@pos", "]", ")", "matched", "=", "true", "@pos", "+=", "1", "return", "tok", "end", "if", "self", ".", "class", ".", "error_hander", "pos", "=", "@pos", "tok", "=", "build_token", "(", ":error", ",", "@input", "[", "@pos", "]", ")", "tok", "=", "self", ".", "class", ".", "error_hander", ".", "call", "(", "tok", ")", "if", "pos", "==", "@pos", "raise", "LexError", ".", "new", "(", "\"Illegal character '#{@input[@pos]}' at index #{@pos}\"", ")", "else", "return", "tok", "if", "tok", "&&", "tok", ".", "type", "end", "else", "raise", "LexError", ".", "new", "(", "\"Illegal character '#{@input[@pos]}' at index #{@pos}\"", ")", "end", "end", "return", "nil", "end" ]
Processes the next token in input This is the main interface to lexer. It returns next available token or **nil** if there are no more tokens available in the input string. {#each} Raises {LexError} if the input cannot be processed. This happens if there were no matches by 'token' rules and no matches by 'literals' rule. If the {.on_error} handler is not set, the exception will be raised immediately, however, if the handler is set, the eception will be raised only if the {#pos} after returning from error handler is still unchanged. @api public @raise [LexError] if the input cannot be processed @return [LexToken] if the next chunk of input was processed successfully @return [nil] if there are no more tokens available in input @example lex = MyLexer.new("hello WORLD") t = lex.next puts "#{tok.type} -> #{tok.value}" #=> "LOWERS -> hello" t = lex.next puts "#{tok.type} -> #{tok.value}" #=> "UPPERS -> WORLD" t = lex.next # => nil
[ "Processes", "the", "next", "token", "in", "input" ]
d5a58194f73a15adb4d7c9940557838641bb2a31
https://github.com/farcaller/rly/blob/d5a58194f73a15adb4d7c9940557838641bb2a31/lib/rly/lex.rb#L119-L176
1,304
eltiare/carrierwave-vips
lib/carrierwave/vips.rb
CarrierWave.Vips.auto_orient
def auto_orient manipulate! do |image| o = image.get('exif-Orientation').to_i rescue nil o ||= image.get('exif-ifd0-Orientation').to_i rescue 1 case o when 1 # Do nothing, everything is peachy when 6 image.rot270 when 8 image.rot180 when 3 image.rot90 else raise('Invalid value for Orientation: ' + o.to_s) end image.set_type GObject::GSTR_TYPE, 'exif-Orientation', '' image.set_type GObject::GSTR_TYPE, 'exif-ifd0-Orientation', '' end end
ruby
def auto_orient manipulate! do |image| o = image.get('exif-Orientation').to_i rescue nil o ||= image.get('exif-ifd0-Orientation').to_i rescue 1 case o when 1 # Do nothing, everything is peachy when 6 image.rot270 when 8 image.rot180 when 3 image.rot90 else raise('Invalid value for Orientation: ' + o.to_s) end image.set_type GObject::GSTR_TYPE, 'exif-Orientation', '' image.set_type GObject::GSTR_TYPE, 'exif-ifd0-Orientation', '' end end
[ "def", "auto_orient", "manipulate!", "do", "|", "image", "|", "o", "=", "image", ".", "get", "(", "'exif-Orientation'", ")", ".", "to_i", "rescue", "nil", "o", "||=", "image", ".", "get", "(", "'exif-ifd0-Orientation'", ")", ".", "to_i", "rescue", "1", "case", "o", "when", "1", "# Do nothing, everything is peachy", "when", "6", "image", ".", "rot270", "when", "8", "image", ".", "rot180", "when", "3", "image", ".", "rot90", "else", "raise", "(", "'Invalid value for Orientation: '", "+", "o", ".", "to_s", ")", "end", "image", ".", "set_type", "GObject", "::", "GSTR_TYPE", ",", "'exif-Orientation'", ",", "''", "image", ".", "set_type", "GObject", "::", "GSTR_TYPE", ",", "'exif-ifd0-Orientation'", ",", "''", "end", "end" ]
Read the camera EXIF data to determine orientation and adjust accordingly
[ "Read", "the", "camera", "EXIF", "data", "to", "determine", "orientation", "and", "adjust", "accordingly" ]
d09a95513e0b54dca18264b63944ae31b2368bda
https://github.com/eltiare/carrierwave-vips/blob/d09a95513e0b54dca18264b63944ae31b2368bda/lib/carrierwave/vips.rb#L55-L74
1,305
eltiare/carrierwave-vips
lib/carrierwave/vips.rb
CarrierWave.Vips.convert
def convert(f, opts = {}) opts = opts.dup f = f.to_s.downcase allowed = %w(jpeg jpg png) raise ArgumentError, "Format must be one of: #{allowed.join(',')}" unless allowed.include?(f) self.format_override = f == 'jpeg' ? 'jpg' : f opts[:Q] = opts.delete(:quality) if opts.has_key?(:quality) write_opts.merge!(opts) get_image end
ruby
def convert(f, opts = {}) opts = opts.dup f = f.to_s.downcase allowed = %w(jpeg jpg png) raise ArgumentError, "Format must be one of: #{allowed.join(',')}" unless allowed.include?(f) self.format_override = f == 'jpeg' ? 'jpg' : f opts[:Q] = opts.delete(:quality) if opts.has_key?(:quality) write_opts.merge!(opts) get_image end
[ "def", "convert", "(", "f", ",", "opts", "=", "{", "}", ")", "opts", "=", "opts", ".", "dup", "f", "=", "f", ".", "to_s", ".", "downcase", "allowed", "=", "%w(", "jpeg", "jpg", "png", ")", "raise", "ArgumentError", ",", "\"Format must be one of: #{allowed.join(',')}\"", "unless", "allowed", ".", "include?", "(", "f", ")", "self", ".", "format_override", "=", "f", "==", "'jpeg'", "?", "'jpg'", ":", "f", "opts", "[", ":Q", "]", "=", "opts", ".", "delete", "(", ":quality", ")", "if", "opts", ".", "has_key?", "(", ":quality", ")", "write_opts", ".", "merge!", "(", "opts", ")", "get_image", "end" ]
Convert the file to a different format === Parameters [f (String)] the format for the file format (jpeg, png) [opts (Hash)] options to be passed to converting function (ie, :interlace => true for png)
[ "Convert", "the", "file", "to", "a", "different", "format" ]
d09a95513e0b54dca18264b63944ae31b2368bda
https://github.com/eltiare/carrierwave-vips/blob/d09a95513e0b54dca18264b63944ae31b2368bda/lib/carrierwave/vips.rb#L106-L115
1,306
eltiare/carrierwave-vips
lib/carrierwave/vips.rb
CarrierWave.Vips.resize_to_fill
def resize_to_fill(new_width, new_height) manipulate! do |image| image = resize_image image, new_width, new_height, :max if image.width > new_width top = 0 left = (image.width - new_width) / 2 elsif image.height > new_height left = 0 top = (image.height - new_height) / 2 else left = 0 top = 0 end # Floating point errors can sometimes chop off an extra pixel # TODO: fix all the universe so that floating point errors never happen again new_height = image.height if image.height < new_height new_width = image.width if image.width < new_width image.extract_area(left, top, new_width, new_height) end end
ruby
def resize_to_fill(new_width, new_height) manipulate! do |image| image = resize_image image, new_width, new_height, :max if image.width > new_width top = 0 left = (image.width - new_width) / 2 elsif image.height > new_height left = 0 top = (image.height - new_height) / 2 else left = 0 top = 0 end # Floating point errors can sometimes chop off an extra pixel # TODO: fix all the universe so that floating point errors never happen again new_height = image.height if image.height < new_height new_width = image.width if image.width < new_width image.extract_area(left, top, new_width, new_height) end end
[ "def", "resize_to_fill", "(", "new_width", ",", "new_height", ")", "manipulate!", "do", "|", "image", "|", "image", "=", "resize_image", "image", ",", "new_width", ",", "new_height", ",", ":max", "if", "image", ".", "width", ">", "new_width", "top", "=", "0", "left", "=", "(", "image", ".", "width", "-", "new_width", ")", "/", "2", "elsif", "image", ".", "height", ">", "new_height", "left", "=", "0", "top", "=", "(", "image", ".", "height", "-", "new_height", ")", "/", "2", "else", "left", "=", "0", "top", "=", "0", "end", "# Floating point errors can sometimes chop off an extra pixel", "# TODO: fix all the universe so that floating point errors never happen again", "new_height", "=", "image", ".", "height", "if", "image", ".", "height", "<", "new_height", "new_width", "=", "image", ".", "width", "if", "image", ".", "width", "<", "new_width", "image", ".", "extract_area", "(", "left", ",", "top", ",", "new_width", ",", "new_height", ")", "end", "end" ]
Resize the image to fit within the specified dimensions while retaining the aspect ratio of the original image. If necessary, crop the image in the larger dimension. === Parameters [width (Integer)] the width to scale the image to [height (Integer)] the height to scale the image to
[ "Resize", "the", "image", "to", "fit", "within", "the", "specified", "dimensions", "while", "retaining", "the", "aspect", "ratio", "of", "the", "original", "image", ".", "If", "necessary", "crop", "the", "image", "in", "the", "larger", "dimension", "." ]
d09a95513e0b54dca18264b63944ae31b2368bda
https://github.com/eltiare/carrierwave-vips/blob/d09a95513e0b54dca18264b63944ae31b2368bda/lib/carrierwave/vips.rb#L146-L170
1,307
eltiare/carrierwave-vips
lib/carrierwave/vips.rb
CarrierWave.Vips.resize_to_limit
def resize_to_limit(new_width, new_height) manipulate! do |image| image = resize_image(image,new_width,new_height) if new_width < image.width || new_height < image.height image end end
ruby
def resize_to_limit(new_width, new_height) manipulate! do |image| image = resize_image(image,new_width,new_height) if new_width < image.width || new_height < image.height image end end
[ "def", "resize_to_limit", "(", "new_width", ",", "new_height", ")", "manipulate!", "do", "|", "image", "|", "image", "=", "resize_image", "(", "image", ",", "new_width", ",", "new_height", ")", "if", "new_width", "<", "image", ".", "width", "||", "new_height", "<", "image", ".", "height", "image", "end", "end" ]
Resize the image to fit within the specified dimensions while retaining the original aspect ratio. Will only resize the image if it is larger than the specified dimensions. The resulting image may be shorter or narrower than specified in the smaller dimension but will not be larger than the specified values. === Parameters [width (Integer)] the width to scale the image to [height (Integer)] the height to scale the image to
[ "Resize", "the", "image", "to", "fit", "within", "the", "specified", "dimensions", "while", "retaining", "the", "original", "aspect", "ratio", ".", "Will", "only", "resize", "the", "image", "if", "it", "is", "larger", "than", "the", "specified", "dimensions", ".", "The", "resulting", "image", "may", "be", "shorter", "or", "narrower", "than", "specified", "in", "the", "smaller", "dimension", "but", "will", "not", "be", "larger", "than", "the", "specified", "values", "." ]
d09a95513e0b54dca18264b63944ae31b2368bda
https://github.com/eltiare/carrierwave-vips/blob/d09a95513e0b54dca18264b63944ae31b2368bda/lib/carrierwave/vips.rb#L183-L188
1,308
prometheus-ev/jekyll-localization
lib/jekyll/localization.rb
Jekyll.Convertible.read_yaml
def read_yaml(base, name, alt = true) _localization_original_read_yaml(base, name) read_alternate_language_content(base, name) if alt && content.empty? end
ruby
def read_yaml(base, name, alt = true) _localization_original_read_yaml(base, name) read_alternate_language_content(base, name) if alt && content.empty? end
[ "def", "read_yaml", "(", "base", ",", "name", ",", "alt", "=", "true", ")", "_localization_original_read_yaml", "(", "base", ",", "name", ")", "read_alternate_language_content", "(", "base", ",", "name", ")", "if", "alt", "&&", "content", ".", "empty?", "end" ]
Overwrites the original method to optionally set the content of a file with no content in it to the content of a file with another language which does have content in it.
[ "Overwrites", "the", "original", "method", "to", "optionally", "set", "the", "content", "of", "a", "file", "with", "no", "content", "in", "it", "to", "the", "content", "of", "a", "file", "with", "another", "language", "which", "does", "have", "content", "in", "it", "." ]
753a293f0efbb252a6a0e1161994ac65d0c50e60
https://github.com/prometheus-ev/jekyll-localization/blob/753a293f0efbb252a6a0e1161994ac65d0c50e60/lib/jekyll/localization.rb#L187-L190
1,309
prometheus-ev/jekyll-localization
lib/jekyll/localization.rb
Jekyll.Page.destination
def destination(dest) # The url needs to be unescaped in order to preserve the correct filename path = File.join(dest, @dir, CGI.unescape(url)) if ext == '.html' && _localization_original_url !~ /\.html\z/ path.sub!(Localization::LANG_END_RE, '') File.join(path, "index#{ext}#{@lang_ext}") else path end end
ruby
def destination(dest) # The url needs to be unescaped in order to preserve the correct filename path = File.join(dest, @dir, CGI.unescape(url)) if ext == '.html' && _localization_original_url !~ /\.html\z/ path.sub!(Localization::LANG_END_RE, '') File.join(path, "index#{ext}#{@lang_ext}") else path end end
[ "def", "destination", "(", "dest", ")", "# The url needs to be unescaped in order to preserve the correct filename", "path", "=", "File", ".", "join", "(", "dest", ",", "@dir", ",", "CGI", ".", "unescape", "(", "url", ")", ")", "if", "ext", "==", "'.html'", "&&", "_localization_original_url", "!~", "/", "\\.", "\\z", "/", "path", ".", "sub!", "(", "Localization", "::", "LANG_END_RE", ",", "''", ")", "File", ".", "join", "(", "path", ",", "\"index#{ext}#{@lang_ext}\"", ")", "else", "path", "end", "end" ]
Overwrites the original method to cater for language extension in output file name.
[ "Overwrites", "the", "original", "method", "to", "cater", "for", "language", "extension", "in", "output", "file", "name", "." ]
753a293f0efbb252a6a0e1161994ac65d0c50e60
https://github.com/prometheus-ev/jekyll-localization/blob/753a293f0efbb252a6a0e1161994ac65d0c50e60/lib/jekyll/localization.rb#L207-L217
1,310
prometheus-ev/jekyll-localization
lib/jekyll/localization.rb
Jekyll.Page.process
def process(name) self.ext = File.extname(name) self.basename = name[0 .. -self.ext.length-1]. sub(Localization::LANG_END_RE, '') end
ruby
def process(name) self.ext = File.extname(name) self.basename = name[0 .. -self.ext.length-1]. sub(Localization::LANG_END_RE, '') end
[ "def", "process", "(", "name", ")", "self", ".", "ext", "=", "File", ".", "extname", "(", "name", ")", "self", ".", "basename", "=", "name", "[", "0", "..", "-", "self", ".", "ext", ".", "length", "-", "1", "]", ".", "sub", "(", "Localization", "::", "LANG_END_RE", ",", "''", ")", "end" ]
Overwrites the original method to filter the language extension from basename
[ "Overwrites", "the", "original", "method", "to", "filter", "the", "language", "extension", "from", "basename" ]
753a293f0efbb252a6a0e1161994ac65d0c50e60
https://github.com/prometheus-ev/jekyll-localization/blob/753a293f0efbb252a6a0e1161994ac65d0c50e60/lib/jekyll/localization.rb#L223-L227
1,311
4commerce-technologies-AG/midi-smtp-server
lib/midi-smtp-server.rb
MidiSmtpServer.Smtpd.stop
def stop(wait_seconds_before_close = 2, gracefully = true) # always signal shutdown shutdown if gracefully # wait if some connection(s) need(s) more time to handle shutdown sleep wait_seconds_before_close if connections? # drop tcp_servers while raising SmtpdStopServiceException @connections_mutex.synchronize do @tcp_server_threads.each do |tcp_server_thread| tcp_server_thread.raise SmtpdStopServiceException if tcp_server_thread end end # wait if some connection(s) still need(s) more time to come down sleep wait_seconds_before_close if connections? || !stopped? end
ruby
def stop(wait_seconds_before_close = 2, gracefully = true) # always signal shutdown shutdown if gracefully # wait if some connection(s) need(s) more time to handle shutdown sleep wait_seconds_before_close if connections? # drop tcp_servers while raising SmtpdStopServiceException @connections_mutex.synchronize do @tcp_server_threads.each do |tcp_server_thread| tcp_server_thread.raise SmtpdStopServiceException if tcp_server_thread end end # wait if some connection(s) still need(s) more time to come down sleep wait_seconds_before_close if connections? || !stopped? end
[ "def", "stop", "(", "wait_seconds_before_close", "=", "2", ",", "gracefully", "=", "true", ")", "# always signal shutdown", "shutdown", "if", "gracefully", "# wait if some connection(s) need(s) more time to handle shutdown", "sleep", "wait_seconds_before_close", "if", "connections?", "# drop tcp_servers while raising SmtpdStopServiceException", "@connections_mutex", ".", "synchronize", "do", "@tcp_server_threads", ".", "each", "do", "|", "tcp_server_thread", "|", "tcp_server_thread", ".", "raise", "SmtpdStopServiceException", "if", "tcp_server_thread", "end", "end", "# wait if some connection(s) still need(s) more time to come down", "sleep", "wait_seconds_before_close", "if", "connections?", "||", "!", "stopped?", "end" ]
Stop the server
[ "Stop", "the", "server" ]
b86a3268ebd32b46854659a2edc1eddaf86adb7b
https://github.com/4commerce-technologies-AG/midi-smtp-server/blob/b86a3268ebd32b46854659a2edc1eddaf86adb7b/lib/midi-smtp-server.rb#L48-L61
1,312
4commerce-technologies-AG/midi-smtp-server
lib/midi-smtp-server.rb
MidiSmtpServer.Smtpd.on_auth_event
def on_auth_event(ctx, authorization_id, authentication_id, authentication) # if authentification is used, override this event # and implement your own user management. # otherwise all authentifications are blocked per default logger.debug("Deny access from #{ctx[:server][:remote_ip]}:#{ctx[:server][:remote_port]} for #{authentication_id}" + (authorization_id == '' ? '' : "/#{authorization_id}") + " with #{authentication}") raise Smtpd535Exception end
ruby
def on_auth_event(ctx, authorization_id, authentication_id, authentication) # if authentification is used, override this event # and implement your own user management. # otherwise all authentifications are blocked per default logger.debug("Deny access from #{ctx[:server][:remote_ip]}:#{ctx[:server][:remote_port]} for #{authentication_id}" + (authorization_id == '' ? '' : "/#{authorization_id}") + " with #{authentication}") raise Smtpd535Exception end
[ "def", "on_auth_event", "(", "ctx", ",", "authorization_id", ",", "authentication_id", ",", "authentication", ")", "# if authentification is used, override this event", "# and implement your own user management.", "# otherwise all authentifications are blocked per default", "logger", ".", "debug", "(", "\"Deny access from #{ctx[:server][:remote_ip]}:#{ctx[:server][:remote_port]} for #{authentication_id}\"", "+", "(", "authorization_id", "==", "''", "?", "''", ":", "\"/#{authorization_id}\"", ")", "+", "\" with #{authentication}\"", ")", "raise", "Smtpd535Exception", "end" ]
check the authentification on AUTH if any value returned, that will be used for ongoing processing otherwise the original value will be used for authorization_id
[ "check", "the", "authentification", "on", "AUTH", "if", "any", "value", "returned", "that", "will", "be", "used", "for", "ongoing", "processing", "otherwise", "the", "original", "value", "will", "be", "used", "for", "authorization_id" ]
b86a3268ebd32b46854659a2edc1eddaf86adb7b
https://github.com/4commerce-technologies-AG/midi-smtp-server/blob/b86a3268ebd32b46854659a2edc1eddaf86adb7b/lib/midi-smtp-server.rb#L296-L302
1,313
4commerce-technologies-AG/midi-smtp-server
lib/midi-smtp-server.rb
MidiSmtpServer.Smtpd.serve_service
def serve_service raise 'Service was already started' unless stopped? # set flag to signal shutdown by stop / shutdown command @shutdown = false # instantiate the service for alls @hosts and @ports @hosts.each_with_index do |host, index| # instantiate the service for each host and port # if host is empty "" wildcard (all) interfaces are used # otherwise it will be bind to single host ip only # if ports at index is not specified, use last item # of ports array. if multiple ports specified by # item like 2525:3535:4545, then all are instantiated ports_for_host = (index < @ports.length ? @ports[index] : @ports.last).to_s.split(':') # loop all ports for that host ports_for_host.each do |port| serve_service_on_host_and_port(host, port) end end end
ruby
def serve_service raise 'Service was already started' unless stopped? # set flag to signal shutdown by stop / shutdown command @shutdown = false # instantiate the service for alls @hosts and @ports @hosts.each_with_index do |host, index| # instantiate the service for each host and port # if host is empty "" wildcard (all) interfaces are used # otherwise it will be bind to single host ip only # if ports at index is not specified, use last item # of ports array. if multiple ports specified by # item like 2525:3535:4545, then all are instantiated ports_for_host = (index < @ports.length ? @ports[index] : @ports.last).to_s.split(':') # loop all ports for that host ports_for_host.each do |port| serve_service_on_host_and_port(host, port) end end end
[ "def", "serve_service", "raise", "'Service was already started'", "unless", "stopped?", "# set flag to signal shutdown by stop / shutdown command", "@shutdown", "=", "false", "# instantiate the service for alls @hosts and @ports", "@hosts", ".", "each_with_index", "do", "|", "host", ",", "index", "|", "# instantiate the service for each host and port", "# if host is empty \"\" wildcard (all) interfaces are used", "# otherwise it will be bind to single host ip only", "# if ports at index is not specified, use last item", "# of ports array. if multiple ports specified by", "# item like 2525:3535:4545, then all are instantiated", "ports_for_host", "=", "(", "index", "<", "@ports", ".", "length", "?", "@ports", "[", "index", "]", ":", "@ports", ".", "last", ")", ".", "to_s", ".", "split", "(", "':'", ")", "# loop all ports for that host", "ports_for_host", ".", "each", "do", "|", "port", "|", "serve_service_on_host_and_port", "(", "host", ",", "port", ")", "end", "end", "end" ]
Start the listeners for all hosts
[ "Start", "the", "listeners", "for", "all", "hosts" ]
b86a3268ebd32b46854659a2edc1eddaf86adb7b
https://github.com/4commerce-technologies-AG/midi-smtp-server/blob/b86a3268ebd32b46854659a2edc1eddaf86adb7b/lib/midi-smtp-server.rb#L347-L367
1,314
4commerce-technologies-AG/midi-smtp-server
lib/midi-smtp-server.rb
MidiSmtpServer.Smtpd.serve_service_on_host_and_port
def serve_service_on_host_and_port(host, port) # log information logger.info('Running service on ' + (host == '' ? '<any>' : host) + ':' + port.to_s) # instantiate the service for host and port # if host is empty "" wildcard (all) interfaces are used # otherwise it will be bind to single host ip only tcp_server = TCPServer.new(host, port) # append this server to the list of TCPServers @tcp_servers << tcp_server # run thread until shutdown @tcp_server_threads << Thread.new do begin # always check for shutdown request until shutdown? # get new client and start additional thread # to handle client process client = tcp_server.accept Thread.new(client) do |io| # add to list of connections @connections << Thread.current # handle connection begin # initialize a session storage hash Thread.current[:session] = {} # process smtp service on io socket io = serve_client(Thread.current[:session], io) # save returned io value due to maybe # established ssl io socket rescue SmtpdStopConnectionException # ignore this exception due to service shutdown rescue StandardError => e # log fatal error while handling connection logger.fatal(e.backtrace.join("\n")) ensure begin # always gracefully shutdown connection. # if the io object was overriden by the # result from serve_client() due to ssl # io, the ssl + io socket will be closed io.close rescue StandardError # ignore any exception from here end # remove closed session from connections @connections_mutex.synchronize do # drop this thread from connections @connections.delete(Thread.current) # drop this thread from processings @processings.delete(Thread.current) # signal mutex for next waiting thread @connections_cv.signal end end end end rescue SmtpdStopServiceException # ignore this exception due to service shutdown rescue StandardError => e # log fatal error while starting new thread logger.fatal(e.backtrace.join("\n")) ensure begin # drop the service tcp_server.close # remove from list @tcp_servers.delete(tcp_server) # reset local var tcp_server = nil rescue StandardError # ignor any error from here end if shutdown? # wait for finishing opened connections @connections_mutex.synchronize do @connections_cv.wait(@connections_mutex) until @connections.empty? end else # drop any open session immediately @connections.each { |c| c.raise SmtpdStopConnectionException } end # remove this thread from list @tcp_server_threads.delete(Thread.current) end end end
ruby
def serve_service_on_host_and_port(host, port) # log information logger.info('Running service on ' + (host == '' ? '<any>' : host) + ':' + port.to_s) # instantiate the service for host and port # if host is empty "" wildcard (all) interfaces are used # otherwise it will be bind to single host ip only tcp_server = TCPServer.new(host, port) # append this server to the list of TCPServers @tcp_servers << tcp_server # run thread until shutdown @tcp_server_threads << Thread.new do begin # always check for shutdown request until shutdown? # get new client and start additional thread # to handle client process client = tcp_server.accept Thread.new(client) do |io| # add to list of connections @connections << Thread.current # handle connection begin # initialize a session storage hash Thread.current[:session] = {} # process smtp service on io socket io = serve_client(Thread.current[:session], io) # save returned io value due to maybe # established ssl io socket rescue SmtpdStopConnectionException # ignore this exception due to service shutdown rescue StandardError => e # log fatal error while handling connection logger.fatal(e.backtrace.join("\n")) ensure begin # always gracefully shutdown connection. # if the io object was overriden by the # result from serve_client() due to ssl # io, the ssl + io socket will be closed io.close rescue StandardError # ignore any exception from here end # remove closed session from connections @connections_mutex.synchronize do # drop this thread from connections @connections.delete(Thread.current) # drop this thread from processings @processings.delete(Thread.current) # signal mutex for next waiting thread @connections_cv.signal end end end end rescue SmtpdStopServiceException # ignore this exception due to service shutdown rescue StandardError => e # log fatal error while starting new thread logger.fatal(e.backtrace.join("\n")) ensure begin # drop the service tcp_server.close # remove from list @tcp_servers.delete(tcp_server) # reset local var tcp_server = nil rescue StandardError # ignor any error from here end if shutdown? # wait for finishing opened connections @connections_mutex.synchronize do @connections_cv.wait(@connections_mutex) until @connections.empty? end else # drop any open session immediately @connections.each { |c| c.raise SmtpdStopConnectionException } end # remove this thread from list @tcp_server_threads.delete(Thread.current) end end end
[ "def", "serve_service_on_host_and_port", "(", "host", ",", "port", ")", "# log information", "logger", ".", "info", "(", "'Running service on '", "+", "(", "host", "==", "''", "?", "'<any>'", ":", "host", ")", "+", "':'", "+", "port", ".", "to_s", ")", "# instantiate the service for host and port", "# if host is empty \"\" wildcard (all) interfaces are used", "# otherwise it will be bind to single host ip only", "tcp_server", "=", "TCPServer", ".", "new", "(", "host", ",", "port", ")", "# append this server to the list of TCPServers", "@tcp_servers", "<<", "tcp_server", "# run thread until shutdown", "@tcp_server_threads", "<<", "Thread", ".", "new", "do", "begin", "# always check for shutdown request", "until", "shutdown?", "# get new client and start additional thread", "# to handle client process", "client", "=", "tcp_server", ".", "accept", "Thread", ".", "new", "(", "client", ")", "do", "|", "io", "|", "# add to list of connections", "@connections", "<<", "Thread", ".", "current", "# handle connection", "begin", "# initialize a session storage hash", "Thread", ".", "current", "[", ":session", "]", "=", "{", "}", "# process smtp service on io socket", "io", "=", "serve_client", "(", "Thread", ".", "current", "[", ":session", "]", ",", "io", ")", "# save returned io value due to maybe", "# established ssl io socket", "rescue", "SmtpdStopConnectionException", "# ignore this exception due to service shutdown", "rescue", "StandardError", "=>", "e", "# log fatal error while handling connection", "logger", ".", "fatal", "(", "e", ".", "backtrace", ".", "join", "(", "\"\\n\"", ")", ")", "ensure", "begin", "# always gracefully shutdown connection.", "# if the io object was overriden by the", "# result from serve_client() due to ssl", "# io, the ssl + io socket will be closed", "io", ".", "close", "rescue", "StandardError", "# ignore any exception from here", "end", "# remove closed session from connections", "@connections_mutex", ".", "synchronize", "do", "# drop this thread from connections", "@connections", ".", "delete", "(", "Thread", ".", "current", ")", "# drop this thread from processings", "@processings", ".", "delete", "(", "Thread", ".", "current", ")", "# signal mutex for next waiting thread", "@connections_cv", ".", "signal", "end", "end", "end", "end", "rescue", "SmtpdStopServiceException", "# ignore this exception due to service shutdown", "rescue", "StandardError", "=>", "e", "# log fatal error while starting new thread", "logger", ".", "fatal", "(", "e", ".", "backtrace", ".", "join", "(", "\"\\n\"", ")", ")", "ensure", "begin", "# drop the service", "tcp_server", ".", "close", "# remove from list", "@tcp_servers", ".", "delete", "(", "tcp_server", ")", "# reset local var", "tcp_server", "=", "nil", "rescue", "StandardError", "# ignor any error from here", "end", "if", "shutdown?", "# wait for finishing opened connections", "@connections_mutex", ".", "synchronize", "do", "@connections_cv", ".", "wait", "(", "@connections_mutex", ")", "until", "@connections", ".", "empty?", "end", "else", "# drop any open session immediately", "@connections", ".", "each", "{", "|", "c", "|", "c", ".", "raise", "SmtpdStopConnectionException", "}", "end", "# remove this thread from list", "@tcp_server_threads", ".", "delete", "(", "Thread", ".", "current", ")", "end", "end", "end" ]
Start the listener thread on single host and port
[ "Start", "the", "listener", "thread", "on", "single", "host", "and", "port" ]
b86a3268ebd32b46854659a2edc1eddaf86adb7b
https://github.com/4commerce-technologies-AG/midi-smtp-server/blob/b86a3268ebd32b46854659a2edc1eddaf86adb7b/lib/midi-smtp-server.rb#L370-L455
1,315
4commerce-technologies-AG/midi-smtp-server
lib/midi-smtp-server.rb
MidiSmtpServer.Smtpd.process_reset_session
def process_reset_session(session, connection_initialize = false) # set active command sequence info session[:cmd_sequence] = connection_initialize ? :CMD_HELO : :CMD_RSET # drop any auth challenge session[:auth_challenge] = {} # test existing of :ctx hash session[:ctx] || session[:ctx] = {} # reset server values (only on connection start) if connection_initialize # create or rebuild :ctx hash session[:ctx].merge!( server: { local_host: '', local_ip: '', local_port: '', local_response: '', remote_host: '', remote_ip: '', remote_port: '', helo: '', helo_response: '', connected: '', exceptions: 0, authorization_id: '', authentication_id: '', authenticated: '', encrypted: '' } ) end # reset envelope values session[:ctx].merge!( envelope: { from: '', to: [], encoding_body: '', encoding_utf8: '' } ) # reset message data session[:ctx].merge!( message: { received: -1, delivered: -1, bytesize: -1, headers: '', crlf: "\r\n", data: '' } ) end
ruby
def process_reset_session(session, connection_initialize = false) # set active command sequence info session[:cmd_sequence] = connection_initialize ? :CMD_HELO : :CMD_RSET # drop any auth challenge session[:auth_challenge] = {} # test existing of :ctx hash session[:ctx] || session[:ctx] = {} # reset server values (only on connection start) if connection_initialize # create or rebuild :ctx hash session[:ctx].merge!( server: { local_host: '', local_ip: '', local_port: '', local_response: '', remote_host: '', remote_ip: '', remote_port: '', helo: '', helo_response: '', connected: '', exceptions: 0, authorization_id: '', authentication_id: '', authenticated: '', encrypted: '' } ) end # reset envelope values session[:ctx].merge!( envelope: { from: '', to: [], encoding_body: '', encoding_utf8: '' } ) # reset message data session[:ctx].merge!( message: { received: -1, delivered: -1, bytesize: -1, headers: '', crlf: "\r\n", data: '' } ) end
[ "def", "process_reset_session", "(", "session", ",", "connection_initialize", "=", "false", ")", "# set active command sequence info", "session", "[", ":cmd_sequence", "]", "=", "connection_initialize", "?", ":CMD_HELO", ":", ":CMD_RSET", "# drop any auth challenge", "session", "[", ":auth_challenge", "]", "=", "{", "}", "# test existing of :ctx hash", "session", "[", ":ctx", "]", "||", "session", "[", ":ctx", "]", "=", "{", "}", "# reset server values (only on connection start)", "if", "connection_initialize", "# create or rebuild :ctx hash", "session", "[", ":ctx", "]", ".", "merge!", "(", "server", ":", "{", "local_host", ":", "''", ",", "local_ip", ":", "''", ",", "local_port", ":", "''", ",", "local_response", ":", "''", ",", "remote_host", ":", "''", ",", "remote_ip", ":", "''", ",", "remote_port", ":", "''", ",", "helo", ":", "''", ",", "helo_response", ":", "''", ",", "connected", ":", "''", ",", "exceptions", ":", "0", ",", "authorization_id", ":", "''", ",", "authentication_id", ":", "''", ",", "authenticated", ":", "''", ",", "encrypted", ":", "''", "}", ")", "end", "# reset envelope values", "session", "[", ":ctx", "]", ".", "merge!", "(", "envelope", ":", "{", "from", ":", "''", ",", "to", ":", "[", "]", ",", "encoding_body", ":", "''", ",", "encoding_utf8", ":", "''", "}", ")", "# reset message data", "session", "[", ":ctx", "]", ".", "merge!", "(", "message", ":", "{", "received", ":", "-", "1", ",", "delivered", ":", "-", "1", ",", "bytesize", ":", "-", "1", ",", "headers", ":", "''", ",", "crlf", ":", "\"\\r\\n\"", ",", "data", ":", "''", "}", ")", "end" ]
reset the context of current smtpd dialog
[ "reset", "the", "context", "of", "current", "smtpd", "dialog" ]
b86a3268ebd32b46854659a2edc1eddaf86adb7b
https://github.com/4commerce-technologies-AG/midi-smtp-server/blob/b86a3268ebd32b46854659a2edc1eddaf86adb7b/lib/midi-smtp-server.rb#L1048-L1098
1,316
4commerce-technologies-AG/midi-smtp-server
lib/midi-smtp-server.rb
MidiSmtpServer.Smtpd.process_auth_plain
def process_auth_plain(session, encoded_auth_response) begin # extract auth id (and password) @auth_values = Base64.decode64(encoded_auth_response).split("\x00") # check for valid credentials parameters raise Smtpd500Exception unless @auth_values.length == 3 # call event function to test credentials return_value = on_auth_event(session[:ctx], @auth_values[0], @auth_values[1], @auth_values[2]) if return_value # overwrite data with returned value as authorization id @auth_values[0] = return_value end # save authentication information to ctx session[:ctx][:server][:authorization_id] = @auth_values[0].to_s.empty? ? @auth_values[1] : @auth_values[0] session[:ctx][:server][:authentication_id] = @auth_values[1] session[:ctx][:server][:authenticated] = Time.now.utc # response code return '235 OK' ensure # whatever happens in this check, reset next sequence session[:cmd_sequence] = :CMD_RSET end end
ruby
def process_auth_plain(session, encoded_auth_response) begin # extract auth id (and password) @auth_values = Base64.decode64(encoded_auth_response).split("\x00") # check for valid credentials parameters raise Smtpd500Exception unless @auth_values.length == 3 # call event function to test credentials return_value = on_auth_event(session[:ctx], @auth_values[0], @auth_values[1], @auth_values[2]) if return_value # overwrite data with returned value as authorization id @auth_values[0] = return_value end # save authentication information to ctx session[:ctx][:server][:authorization_id] = @auth_values[0].to_s.empty? ? @auth_values[1] : @auth_values[0] session[:ctx][:server][:authentication_id] = @auth_values[1] session[:ctx][:server][:authenticated] = Time.now.utc # response code return '235 OK' ensure # whatever happens in this check, reset next sequence session[:cmd_sequence] = :CMD_RSET end end
[ "def", "process_auth_plain", "(", "session", ",", "encoded_auth_response", ")", "begin", "# extract auth id (and password)", "@auth_values", "=", "Base64", ".", "decode64", "(", "encoded_auth_response", ")", ".", "split", "(", "\"\\x00\"", ")", "# check for valid credentials parameters", "raise", "Smtpd500Exception", "unless", "@auth_values", ".", "length", "==", "3", "# call event function to test credentials", "return_value", "=", "on_auth_event", "(", "session", "[", ":ctx", "]", ",", "@auth_values", "[", "0", "]", ",", "@auth_values", "[", "1", "]", ",", "@auth_values", "[", "2", "]", ")", "if", "return_value", "# overwrite data with returned value as authorization id", "@auth_values", "[", "0", "]", "=", "return_value", "end", "# save authentication information to ctx", "session", "[", ":ctx", "]", "[", ":server", "]", "[", ":authorization_id", "]", "=", "@auth_values", "[", "0", "]", ".", "to_s", ".", "empty?", "?", "@auth_values", "[", "1", "]", ":", "@auth_values", "[", "0", "]", "session", "[", ":ctx", "]", "[", ":server", "]", "[", ":authentication_id", "]", "=", "@auth_values", "[", "1", "]", "session", "[", ":ctx", "]", "[", ":server", "]", "[", ":authenticated", "]", "=", "Time", ".", "now", ".", "utc", "# response code", "return", "'235 OK'", "ensure", "# whatever happens in this check, reset next sequence", "session", "[", ":cmd_sequence", "]", "=", ":CMD_RSET", "end", "end" ]
handle plain authentification
[ "handle", "plain", "authentification" ]
b86a3268ebd32b46854659a2edc1eddaf86adb7b
https://github.com/4commerce-technologies-AG/midi-smtp-server/blob/b86a3268ebd32b46854659a2edc1eddaf86adb7b/lib/midi-smtp-server.rb#L1101-L1124
1,317
amoniacou/danthes
lib/danthes/view_helpers.rb
Danthes.ViewHelpers.subscribe_to
def subscribe_to(channel, opts = {}) js_tag = opts.delete(:include_js_tag){ true } subscription = Danthes.subscription(channel: channel) content = raw("if (typeof Danthes != 'undefined') { Danthes.sign(#{subscription.to_json}) }") js_tag ? content_tag('script', content, type: 'text/javascript') : content end
ruby
def subscribe_to(channel, opts = {}) js_tag = opts.delete(:include_js_tag){ true } subscription = Danthes.subscription(channel: channel) content = raw("if (typeof Danthes != 'undefined') { Danthes.sign(#{subscription.to_json}) }") js_tag ? content_tag('script', content, type: 'text/javascript') : content end
[ "def", "subscribe_to", "(", "channel", ",", "opts", "=", "{", "}", ")", "js_tag", "=", "opts", ".", "delete", "(", ":include_js_tag", ")", "{", "true", "}", "subscription", "=", "Danthes", ".", "subscription", "(", "channel", ":", "channel", ")", "content", "=", "raw", "(", "\"if (typeof Danthes != 'undefined') { Danthes.sign(#{subscription.to_json}) }\"", ")", "js_tag", "?", "content_tag", "(", "'script'", ",", "content", ",", "type", ":", "'text/javascript'", ")", ":", "content", "end" ]
Subscribe the client to the given channel. This generates some JavaScript calling Danthes.sign with the subscription options.
[ "Subscribe", "the", "client", "to", "the", "given", "channel", ".", "This", "generates", "some", "JavaScript", "calling", "Danthes", ".", "sign", "with", "the", "subscription", "options", "." ]
bac689d465aaf22c09b6e51fbca8a735bd8fb468
https://github.com/amoniacou/danthes/blob/bac689d465aaf22c09b6e51fbca8a735bd8fb468/lib/danthes/view_helpers.rb#L15-L20
1,318
russ/lacquer
lib/lacquer/cache_utils.rb
Lacquer.CacheUtils.clear_cache_for
def clear_cache_for(*paths) return unless Lacquer.configuration.enable_cache case Lacquer.configuration.job_backend when :delayed_job require 'lacquer/delayed_job_job' Delayed::Job.enqueue(Lacquer::DelayedJobJob.new(paths)) when :resque require 'lacquer/resque_job' Resque.enqueue(Lacquer::ResqueJob, paths) when :sidekiq require 'lacquer/sidekiq_worker' Lacquer::SidekiqWorker.perform_async(paths) when :none Varnish.new.purge(*paths) end end
ruby
def clear_cache_for(*paths) return unless Lacquer.configuration.enable_cache case Lacquer.configuration.job_backend when :delayed_job require 'lacquer/delayed_job_job' Delayed::Job.enqueue(Lacquer::DelayedJobJob.new(paths)) when :resque require 'lacquer/resque_job' Resque.enqueue(Lacquer::ResqueJob, paths) when :sidekiq require 'lacquer/sidekiq_worker' Lacquer::SidekiqWorker.perform_async(paths) when :none Varnish.new.purge(*paths) end end
[ "def", "clear_cache_for", "(", "*", "paths", ")", "return", "unless", "Lacquer", ".", "configuration", ".", "enable_cache", "case", "Lacquer", ".", "configuration", ".", "job_backend", "when", ":delayed_job", "require", "'lacquer/delayed_job_job'", "Delayed", "::", "Job", ".", "enqueue", "(", "Lacquer", "::", "DelayedJobJob", ".", "new", "(", "paths", ")", ")", "when", ":resque", "require", "'lacquer/resque_job'", "Resque", ".", "enqueue", "(", "Lacquer", "::", "ResqueJob", ",", "paths", ")", "when", ":sidekiq", "require", "'lacquer/sidekiq_worker'", "Lacquer", "::", "SidekiqWorker", ".", "perform_async", "(", "paths", ")", "when", ":none", "Varnish", ".", "new", ".", "purge", "(", "paths", ")", "end", "end" ]
Sends url.purge command to varnish to clear cache. clear_cache_for(root_path, blog_posts_path, '/other/content/*')
[ "Sends", "url", ".", "purge", "command", "to", "varnish", "to", "clear", "cache", "." ]
690fef73ee6f9229f0191a7d75bf6172499ffaf4
https://github.com/russ/lacquer/blob/690fef73ee6f9229f0191a7d75bf6172499ffaf4/lib/lacquer/cache_utils.rb#L28-L43
1,319
amoniacou/danthes
lib/danthes/faye_extension.rb
Danthes.FayeExtension.incoming
def incoming(message, callback) if message['channel'] == '/meta/subscribe' authenticate_subscribe(message) elsif message['channel'] !~ %r{^/meta/} authenticate_publish(message) end callback.call(message) end
ruby
def incoming(message, callback) if message['channel'] == '/meta/subscribe' authenticate_subscribe(message) elsif message['channel'] !~ %r{^/meta/} authenticate_publish(message) end callback.call(message) end
[ "def", "incoming", "(", "message", ",", "callback", ")", "if", "message", "[", "'channel'", "]", "==", "'/meta/subscribe'", "authenticate_subscribe", "(", "message", ")", "elsif", "message", "[", "'channel'", "]", "!~", "%r{", "}", "authenticate_publish", "(", "message", ")", "end", "callback", ".", "call", "(", "message", ")", "end" ]
Callback to handle incoming Faye messages. This authenticates both subscribe and publish calls.
[ "Callback", "to", "handle", "incoming", "Faye", "messages", ".", "This", "authenticates", "both", "subscribe", "and", "publish", "calls", "." ]
bac689d465aaf22c09b6e51fbca8a735bd8fb468
https://github.com/amoniacou/danthes/blob/bac689d465aaf22c09b6e51fbca8a735bd8fb468/lib/danthes/faye_extension.rb#L7-L14
1,320
russ/lacquer
lib/lacquer/varnish.rb
Lacquer.Varnish.send_command
def send_command(command) Lacquer.configuration.varnish_servers.collect do |server| retries = 0 response = nil begin retries += 1 connection = Net::Telnet.new( 'Host' => server[:host], 'Port' => server[:port], 'Timeout' => server[:timeout] || 5) if(server[:secret]) connection.waitfor("Match" => /^107/) do |authentication_request| matchdata = /^107 \d{2}\s*(.{32}).*$/m.match(authentication_request) # Might be a bit ugly regex, but it works great! salt = matchdata[1] if(salt.empty?) raise VarnishError, "Bad authentication request" end digest = OpenSSL::Digest.new('sha256') digest << salt digest << "\n" digest << server[:secret] digest << salt digest << "\n" connection.cmd("String" => "auth #{digest.to_s}", "Match" => /\d{3}/) do |auth_response| if(!(/^200/ =~ auth_response)) raise AuthenticationError, "Could not authenticate" end end end end connection.cmd('String' => command, 'Match' => /\n\n/) {|r| response = r.split("\n").first.strip} connection.close if connection.respond_to?(:close) rescue Exception => e if retries < Lacquer.configuration.retries retry else if Lacquer.configuration.command_error_handler Lacquer.configuration.command_error_handler.call({ :error_class => "Varnish Error, retried #{Lacquer.configuration.retries} times", :error_message => "Error while trying to connect to #{server[:host]}:#{server[:port]}: #{e}", :parameters => server, :response => response }) elsif e.kind_of?(Lacquer::AuthenticationError) raise e else raise VarnishError.new("Error while trying to connect to #{server[:host]}:#{server[:port]} #{e}") end end end response end end
ruby
def send_command(command) Lacquer.configuration.varnish_servers.collect do |server| retries = 0 response = nil begin retries += 1 connection = Net::Telnet.new( 'Host' => server[:host], 'Port' => server[:port], 'Timeout' => server[:timeout] || 5) if(server[:secret]) connection.waitfor("Match" => /^107/) do |authentication_request| matchdata = /^107 \d{2}\s*(.{32}).*$/m.match(authentication_request) # Might be a bit ugly regex, but it works great! salt = matchdata[1] if(salt.empty?) raise VarnishError, "Bad authentication request" end digest = OpenSSL::Digest.new('sha256') digest << salt digest << "\n" digest << server[:secret] digest << salt digest << "\n" connection.cmd("String" => "auth #{digest.to_s}", "Match" => /\d{3}/) do |auth_response| if(!(/^200/ =~ auth_response)) raise AuthenticationError, "Could not authenticate" end end end end connection.cmd('String' => command, 'Match' => /\n\n/) {|r| response = r.split("\n").first.strip} connection.close if connection.respond_to?(:close) rescue Exception => e if retries < Lacquer.configuration.retries retry else if Lacquer.configuration.command_error_handler Lacquer.configuration.command_error_handler.call({ :error_class => "Varnish Error, retried #{Lacquer.configuration.retries} times", :error_message => "Error while trying to connect to #{server[:host]}:#{server[:port]}: #{e}", :parameters => server, :response => response }) elsif e.kind_of?(Lacquer::AuthenticationError) raise e else raise VarnishError.new("Error while trying to connect to #{server[:host]}:#{server[:port]} #{e}") end end end response end end
[ "def", "send_command", "(", "command", ")", "Lacquer", ".", "configuration", ".", "varnish_servers", ".", "collect", "do", "|", "server", "|", "retries", "=", "0", "response", "=", "nil", "begin", "retries", "+=", "1", "connection", "=", "Net", "::", "Telnet", ".", "new", "(", "'Host'", "=>", "server", "[", ":host", "]", ",", "'Port'", "=>", "server", "[", ":port", "]", ",", "'Timeout'", "=>", "server", "[", ":timeout", "]", "||", "5", ")", "if", "(", "server", "[", ":secret", "]", ")", "connection", ".", "waitfor", "(", "\"Match\"", "=>", "/", "/", ")", "do", "|", "authentication_request", "|", "matchdata", "=", "/", "\\d", "\\s", "/m", ".", "match", "(", "authentication_request", ")", "# Might be a bit ugly regex, but it works great!", "salt", "=", "matchdata", "[", "1", "]", "if", "(", "salt", ".", "empty?", ")", "raise", "VarnishError", ",", "\"Bad authentication request\"", "end", "digest", "=", "OpenSSL", "::", "Digest", ".", "new", "(", "'sha256'", ")", "digest", "<<", "salt", "digest", "<<", "\"\\n\"", "digest", "<<", "server", "[", ":secret", "]", "digest", "<<", "salt", "digest", "<<", "\"\\n\"", "connection", ".", "cmd", "(", "\"String\"", "=>", "\"auth #{digest.to_s}\"", ",", "\"Match\"", "=>", "/", "\\d", "/", ")", "do", "|", "auth_response", "|", "if", "(", "!", "(", "/", "/", "=~", "auth_response", ")", ")", "raise", "AuthenticationError", ",", "\"Could not authenticate\"", "end", "end", "end", "end", "connection", ".", "cmd", "(", "'String'", "=>", "command", ",", "'Match'", "=>", "/", "\\n", "\\n", "/", ")", "{", "|", "r", "|", "response", "=", "r", ".", "split", "(", "\"\\n\"", ")", ".", "first", ".", "strip", "}", "connection", ".", "close", "if", "connection", ".", "respond_to?", "(", ":close", ")", "rescue", "Exception", "=>", "e", "if", "retries", "<", "Lacquer", ".", "configuration", ".", "retries", "retry", "else", "if", "Lacquer", ".", "configuration", ".", "command_error_handler", "Lacquer", ".", "configuration", ".", "command_error_handler", ".", "call", "(", "{", ":error_class", "=>", "\"Varnish Error, retried #{Lacquer.configuration.retries} times\"", ",", ":error_message", "=>", "\"Error while trying to connect to #{server[:host]}:#{server[:port]}: #{e}\"", ",", ":parameters", "=>", "server", ",", ":response", "=>", "response", "}", ")", "elsif", "e", ".", "kind_of?", "(", "Lacquer", "::", "AuthenticationError", ")", "raise", "e", "else", "raise", "VarnishError", ".", "new", "(", "\"Error while trying to connect to #{server[:host]}:#{server[:port]} #{e}\"", ")", "end", "end", "end", "response", "end", "end" ]
Sends commands over telnet to varnish servers listed in the config.
[ "Sends", "commands", "over", "telnet", "to", "varnish", "servers", "listed", "in", "the", "config", "." ]
690fef73ee6f9229f0191a7d75bf6172499ffaf4
https://github.com/russ/lacquer/blob/690fef73ee6f9229f0191a7d75bf6172499ffaf4/lib/lacquer/varnish.rb#L27-L82
1,321
4commerce-technologies-AG/midi-smtp-server
lib/midi-smtp-server/tls-transport.rb
MidiSmtpServer.TlsTransport.start
def start(io) # start SSL negotiation ssl = OpenSSL::SSL::SSLSocket.new(io, @ctx) # connect to server socket ssl.accept # make sure to close also the underlying io ssl.sync_close = true # return as new io socket return ssl end
ruby
def start(io) # start SSL negotiation ssl = OpenSSL::SSL::SSLSocket.new(io, @ctx) # connect to server socket ssl.accept # make sure to close also the underlying io ssl.sync_close = true # return as new io socket return ssl end
[ "def", "start", "(", "io", ")", "# start SSL negotiation", "ssl", "=", "OpenSSL", "::", "SSL", "::", "SSLSocket", ".", "new", "(", "io", ",", "@ctx", ")", "# connect to server socket", "ssl", ".", "accept", "# make sure to close also the underlying io", "ssl", ".", "sync_close", "=", "true", "# return as new io socket", "return", "ssl", "end" ]
start ssl connection over existing tcpserver socket
[ "start", "ssl", "connection", "over", "existing", "tcpserver", "socket" ]
b86a3268ebd32b46854659a2edc1eddaf86adb7b
https://github.com/4commerce-technologies-AG/midi-smtp-server/blob/b86a3268ebd32b46854659a2edc1eddaf86adb7b/lib/midi-smtp-server/tls-transport.rb#L54-L63
1,322
johnkoht/responsive-images
lib/responsive_images/view_helpers.rb
ResponsiveImages.ViewHelpers.responsive_image_tag
def responsive_image_tag image, options={} # Merge any options passed with the configured options sizes = ResponsiveImages.options.deep_merge(options) # Let's create a hash of the alternative options for our data attributes data_sizes = alternative_sizes(image, sizes) # Get the image source image_src = src_path(image, sizes) # Return the image tag with our responsive data attributes return image_tag image_src, data_sizes.merge(options) end
ruby
def responsive_image_tag image, options={} # Merge any options passed with the configured options sizes = ResponsiveImages.options.deep_merge(options) # Let's create a hash of the alternative options for our data attributes data_sizes = alternative_sizes(image, sizes) # Get the image source image_src = src_path(image, sizes) # Return the image tag with our responsive data attributes return image_tag image_src, data_sizes.merge(options) end
[ "def", "responsive_image_tag", "image", ",", "options", "=", "{", "}", "# Merge any options passed with the configured options", "sizes", "=", "ResponsiveImages", ".", "options", ".", "deep_merge", "(", "options", ")", "# Let's create a hash of the alternative options for our data attributes ", "data_sizes", "=", "alternative_sizes", "(", "image", ",", "sizes", ")", "# Get the image source", "image_src", "=", "src_path", "(", "image", ",", "sizes", ")", "# Return the image tag with our responsive data attributes", "return", "image_tag", "image_src", ",", "data_sizes", ".", "merge", "(", "options", ")", "end" ]
Create a image tag with our responsive image data attributes
[ "Create", "a", "image", "tag", "with", "our", "responsive", "image", "data", "attributes" ]
b5449b2dcb6f96cc8d5a335e9b032858285b156a
https://github.com/johnkoht/responsive-images/blob/b5449b2dcb6f96cc8d5a335e9b032858285b156a/lib/responsive_images/view_helpers.rb#L12-L21
1,323
johnkoht/responsive-images
lib/responsive_images/view_helpers.rb
ResponsiveImages.ViewHelpers.alternative_sizes
def alternative_sizes image, sizes data_sizes = {} sizes[:sizes].each do |size, value| if value.present? data_sizes["data-#{size}-src"] = (value == :default ? image.url : image.send(value)) else false end end data_sizes end
ruby
def alternative_sizes image, sizes data_sizes = {} sizes[:sizes].each do |size, value| if value.present? data_sizes["data-#{size}-src"] = (value == :default ? image.url : image.send(value)) else false end end data_sizes end
[ "def", "alternative_sizes", "image", ",", "sizes", "data_sizes", "=", "{", "}", "sizes", "[", ":sizes", "]", ".", "each", "do", "|", "size", ",", "value", "|", "if", "value", ".", "present?", "data_sizes", "[", "\"data-#{size}-src\"", "]", "=", "(", "value", "==", ":default", "?", "image", ".", "url", ":", "image", ".", "send", "(", "value", ")", ")", "else", "false", "end", "end", "data_sizes", "end" ]
Loop over the images sizes and create our data attributes hash
[ "Loop", "over", "the", "images", "sizes", "and", "create", "our", "data", "attributes", "hash" ]
b5449b2dcb6f96cc8d5a335e9b032858285b156a
https://github.com/johnkoht/responsive-images/blob/b5449b2dcb6f96cc8d5a335e9b032858285b156a/lib/responsive_images/view_helpers.rb#L47-L57
1,324
worlddb/world.db
worlddb-models/lib/worlddb/reader.rb
WorldDb.ReaderBase.load_continent_defs
def load_continent_defs( name, more_attribs={} ) reader = create_values_reader( name, more_attribs ) reader.each_line do |attribs, values| ## check optional values values.each_with_index do |value, index| logger.warn "unknown type for value >#{value}<" end rec = Continent.find_by_key( attribs[ :key ] ) if rec.present? logger.debug "update Continent #{rec.id}-#{rec.key}:" else logger.debug "create Continent:" rec = Continent.new end logger.debug attribs.to_json rec.update_attributes!( attribs ) end # each lines end
ruby
def load_continent_defs( name, more_attribs={} ) reader = create_values_reader( name, more_attribs ) reader.each_line do |attribs, values| ## check optional values values.each_with_index do |value, index| logger.warn "unknown type for value >#{value}<" end rec = Continent.find_by_key( attribs[ :key ] ) if rec.present? logger.debug "update Continent #{rec.id}-#{rec.key}:" else logger.debug "create Continent:" rec = Continent.new end logger.debug attribs.to_json rec.update_attributes!( attribs ) end # each lines end
[ "def", "load_continent_defs", "(", "name", ",", "more_attribs", "=", "{", "}", ")", "reader", "=", "create_values_reader", "(", "name", ",", "more_attribs", ")", "reader", ".", "each_line", "do", "|", "attribs", ",", "values", "|", "## check optional values", "values", ".", "each_with_index", "do", "|", "value", ",", "index", "|", "logger", ".", "warn", "\"unknown type for value >#{value}<\"", "end", "rec", "=", "Continent", ".", "find_by_key", "(", "attribs", "[", ":key", "]", ")", "if", "rec", ".", "present?", "logger", ".", "debug", "\"update Continent #{rec.id}-#{rec.key}:\"", "else", "logger", ".", "debug", "\"create Continent:\"", "rec", "=", "Continent", ".", "new", "end", "logger", ".", "debug", "attribs", ".", "to_json", "rec", ".", "update_attributes!", "(", "attribs", ")", "end", "# each lines", "end" ]
use ContinentDef Reader
[ "use", "ContinentDef", "Reader" ]
8fd44fa8d8dc47290c63b881c713634494aae291
https://github.com/worlddb/world.db/blob/8fd44fa8d8dc47290c63b881c713634494aae291/worlddb-models/lib/worlddb/reader.rb#L198-L221
1,325
agoragames/bracket_tree
lib/bracket_tree/positional_relation.rb
BracketTree.PositionalRelation.all
def all if @side if @round seats = by_round @round, @side else side_root = @bracket.root.send(@side) seats = [] @bracket.top_down(side_root) do |node| seats << node end end else if @round seats = by_round(@round, :left) + by_round(@round, :right) else seats = [] @bracket.top_down(@bracket.root) do |node| seats << node end end end seats end
ruby
def all if @side if @round seats = by_round @round, @side else side_root = @bracket.root.send(@side) seats = [] @bracket.top_down(side_root) do |node| seats << node end end else if @round seats = by_round(@round, :left) + by_round(@round, :right) else seats = [] @bracket.top_down(@bracket.root) do |node| seats << node end end end seats end
[ "def", "all", "if", "@side", "if", "@round", "seats", "=", "by_round", "@round", ",", "@side", "else", "side_root", "=", "@bracket", ".", "root", ".", "send", "(", "@side", ")", "seats", "=", "[", "]", "@bracket", ".", "top_down", "(", "side_root", ")", "do", "|", "node", "|", "seats", "<<", "node", "end", "end", "else", "if", "@round", "seats", "=", "by_round", "(", "@round", ",", ":left", ")", "+", "by_round", "(", "@round", ",", ":right", ")", "else", "seats", "=", "[", "]", "@bracket", ".", "top_down", "(", "@bracket", ".", "root", ")", "do", "|", "node", "|", "seats", "<<", "node", "end", "end", "end", "seats", "end" ]
Retrieves all seats based on the stored relation conditions @return [Array<BracketTree::Node>]
[ "Retrieves", "all", "seats", "based", "on", "the", "stored", "relation", "conditions" ]
68d90aa5c605ef2996fc7a360d4f90dcfde755ca
https://github.com/agoragames/bracket_tree/blob/68d90aa5c605ef2996fc7a360d4f90dcfde755ca/lib/bracket_tree/positional_relation.rb#L67-L91
1,326
agoragames/bracket_tree
lib/bracket_tree/positional_relation.rb
BracketTree.PositionalRelation.by_round
def by_round round, side depth = @bracket.depth[side] - (round - 1) seats = [] side_root = @bracket.root.send(side) @bracket.top_down(side_root) do |node| if node.depth == depth seats << node end end seats end
ruby
def by_round round, side depth = @bracket.depth[side] - (round - 1) seats = [] side_root = @bracket.root.send(side) @bracket.top_down(side_root) do |node| if node.depth == depth seats << node end end seats end
[ "def", "by_round", "round", ",", "side", "depth", "=", "@bracket", ".", "depth", "[", "side", "]", "-", "(", "round", "-", "1", ")", "seats", "=", "[", "]", "side_root", "=", "@bracket", ".", "root", ".", "send", "(", "side", ")", "@bracket", ".", "top_down", "(", "side_root", ")", "do", "|", "node", "|", "if", "node", ".", "depth", "==", "depth", "seats", "<<", "node", "end", "end", "seats", "end" ]
Retrieves an Array of Nodes for a given round on a given side @param [Fixnum] round to pull @param [Fixnum] side of the tree to pull from @return [Array] array of Nodes from the round
[ "Retrieves", "an", "Array", "of", "Nodes", "for", "a", "given", "round", "on", "a", "given", "side" ]
68d90aa5c605ef2996fc7a360d4f90dcfde755ca
https://github.com/agoragames/bracket_tree/blob/68d90aa5c605ef2996fc7a360d4f90dcfde755ca/lib/bracket_tree/positional_relation.rb#L108-L120
1,327
BrunoMazzo/Danger-Slather
lib/slather/plugin.rb
Danger.DangerSlather.configure
def configure(xcodeproj_path, scheme, options: {}) require 'slather' @project = Slather::Project.open(xcodeproj_path) @project.scheme = scheme @project.workspace = options[:workspace] @project.build_directory = options[:build_directory] @project.ignore_list = options[:ignore_list] @project.ci_service = options[:ci_service] @project.coverage_access_token = options[:coverage_access_token] @project.coverage_service = options[:coverage_service] || :terminal @project.source_directory = options[:source_directory] @project.output_directory = options[:output_directory] @project.input_format = options[:input_format] @project.binary_file = options[:binary_file] @project.decimals = options[:decimals] @project.configure @project.post if options[:post] end
ruby
def configure(xcodeproj_path, scheme, options: {}) require 'slather' @project = Slather::Project.open(xcodeproj_path) @project.scheme = scheme @project.workspace = options[:workspace] @project.build_directory = options[:build_directory] @project.ignore_list = options[:ignore_list] @project.ci_service = options[:ci_service] @project.coverage_access_token = options[:coverage_access_token] @project.coverage_service = options[:coverage_service] || :terminal @project.source_directory = options[:source_directory] @project.output_directory = options[:output_directory] @project.input_format = options[:input_format] @project.binary_file = options[:binary_file] @project.decimals = options[:decimals] @project.configure @project.post if options[:post] end
[ "def", "configure", "(", "xcodeproj_path", ",", "scheme", ",", "options", ":", "{", "}", ")", "require", "'slather'", "@project", "=", "Slather", "::", "Project", ".", "open", "(", "xcodeproj_path", ")", "@project", ".", "scheme", "=", "scheme", "@project", ".", "workspace", "=", "options", "[", ":workspace", "]", "@project", ".", "build_directory", "=", "options", "[", ":build_directory", "]", "@project", ".", "ignore_list", "=", "options", "[", ":ignore_list", "]", "@project", ".", "ci_service", "=", "options", "[", ":ci_service", "]", "@project", ".", "coverage_access_token", "=", "options", "[", ":coverage_access_token", "]", "@project", ".", "coverage_service", "=", "options", "[", ":coverage_service", "]", "||", ":terminal", "@project", ".", "source_directory", "=", "options", "[", ":source_directory", "]", "@project", ".", "output_directory", "=", "options", "[", ":output_directory", "]", "@project", ".", "input_format", "=", "options", "[", ":input_format", "]", "@project", ".", "binary_file", "=", "options", "[", ":binary_file", "]", "@project", ".", "decimals", "=", "options", "[", ":decimals", "]", "@project", ".", "configure", "@project", ".", "post", "if", "options", "[", ":post", "]", "end" ]
Required method to configure slather. It's required at least the path to the project and the scheme used with code coverage enabled @return [void]
[ "Required", "method", "to", "configure", "slather", ".", "It", "s", "required", "at", "least", "the", "path", "to", "the", "project", "and", "the", "scheme", "used", "with", "code", "coverage", "enabled" ]
98be417dd89b922a20404810550a5d280d349b0e
https://github.com/BrunoMazzo/Danger-Slather/blob/98be417dd89b922a20404810550a5d280d349b0e/lib/slather/plugin.rb#L19-L36
1,328
BrunoMazzo/Danger-Slather
lib/slather/plugin.rb
Danger.DangerSlather.total_coverage
def total_coverage unless @project.nil? @total_coverage ||= begin total_project_lines = 0 total_project_lines_tested = 0 @project.coverage_files.each do |coverage_file| total_project_lines_tested += coverage_file.num_lines_tested total_project_lines += coverage_file.num_lines_testable end @total_coverage = (total_project_lines_tested / total_project_lines.to_f) * 100.0 end end end
ruby
def total_coverage unless @project.nil? @total_coverage ||= begin total_project_lines = 0 total_project_lines_tested = 0 @project.coverage_files.each do |coverage_file| total_project_lines_tested += coverage_file.num_lines_tested total_project_lines += coverage_file.num_lines_testable end @total_coverage = (total_project_lines_tested / total_project_lines.to_f) * 100.0 end end end
[ "def", "total_coverage", "unless", "@project", ".", "nil?", "@total_coverage", "||=", "begin", "total_project_lines", "=", "0", "total_project_lines_tested", "=", "0", "@project", ".", "coverage_files", ".", "each", "do", "|", "coverage_file", "|", "total_project_lines_tested", "+=", "coverage_file", ".", "num_lines_tested", "total_project_lines", "+=", "coverage_file", ".", "num_lines_testable", "end", "@total_coverage", "=", "(", "total_project_lines_tested", "/", "total_project_lines", ".", "to_f", ")", "*", "100.0", "end", "end", "end" ]
Total coverage of the project @return [Float]
[ "Total", "coverage", "of", "the", "project" ]
98be417dd89b922a20404810550a5d280d349b0e
https://github.com/BrunoMazzo/Danger-Slather/blob/98be417dd89b922a20404810550a5d280d349b0e/lib/slather/plugin.rb#L40-L52
1,329
BrunoMazzo/Danger-Slather
lib/slather/plugin.rb
Danger.DangerSlather.notify_if_coverage_is_less_than
def notify_if_coverage_is_less_than(options) minimum_coverage = options[:minimum_coverage] notify_level = options[:notify_level] || :fail if total_coverage < minimum_coverage notify_message = "Total coverage less than #{minimum_coverage}%" if notify_level == :fail fail notify_message else warn notify_message end end end
ruby
def notify_if_coverage_is_less_than(options) minimum_coverage = options[:minimum_coverage] notify_level = options[:notify_level] || :fail if total_coverage < minimum_coverage notify_message = "Total coverage less than #{minimum_coverage}%" if notify_level == :fail fail notify_message else warn notify_message end end end
[ "def", "notify_if_coverage_is_less_than", "(", "options", ")", "minimum_coverage", "=", "options", "[", ":minimum_coverage", "]", "notify_level", "=", "options", "[", ":notify_level", "]", "||", ":fail", "if", "total_coverage", "<", "minimum_coverage", "notify_message", "=", "\"Total coverage less than #{minimum_coverage}%\"", "if", "notify_level", "==", ":fail", "fail", "notify_message", "else", "warn", "notify_message", "end", "end", "end" ]
Method to check if the coverage of the project is at least a minumum @param options [Hash] a hash with the options @option options [Float] :minimum_coverage the minimum code coverage required @option options [Symbol] :notify_level the level of notification @return [Array<String>]
[ "Method", "to", "check", "if", "the", "coverage", "of", "the", "project", "is", "at", "least", "a", "minumum" ]
98be417dd89b922a20404810550a5d280d349b0e
https://github.com/BrunoMazzo/Danger-Slather/blob/98be417dd89b922a20404810550a5d280d349b0e/lib/slather/plugin.rb#L59-L70
1,330
BrunoMazzo/Danger-Slather
lib/slather/plugin.rb
Danger.DangerSlather.notify_if_modified_file_is_less_than
def notify_if_modified_file_is_less_than(options) minimum_coverage = options[:minimum_coverage] notify_level = options[:notify_level] || :fail if all_modified_files_coverage.count > 0 files_to_notify = all_modified_files_coverage.select do |file| file.percentage_lines_tested < minimum_coverage end notify_messages = files_to_notify.map do |file| "#{file.source_file_pathname_relative_to_repo_root} has less than #{minimum_coverage}% code coverage" end notify_messages.each do |message| if notify_level == :fail fail message else warn message end end end end
ruby
def notify_if_modified_file_is_less_than(options) minimum_coverage = options[:minimum_coverage] notify_level = options[:notify_level] || :fail if all_modified_files_coverage.count > 0 files_to_notify = all_modified_files_coverage.select do |file| file.percentage_lines_tested < minimum_coverage end notify_messages = files_to_notify.map do |file| "#{file.source_file_pathname_relative_to_repo_root} has less than #{minimum_coverage}% code coverage" end notify_messages.each do |message| if notify_level == :fail fail message else warn message end end end end
[ "def", "notify_if_modified_file_is_less_than", "(", "options", ")", "minimum_coverage", "=", "options", "[", ":minimum_coverage", "]", "notify_level", "=", "options", "[", ":notify_level", "]", "||", ":fail", "if", "all_modified_files_coverage", ".", "count", ">", "0", "files_to_notify", "=", "all_modified_files_coverage", ".", "select", "do", "|", "file", "|", "file", ".", "percentage_lines_tested", "<", "minimum_coverage", "end", "notify_messages", "=", "files_to_notify", ".", "map", "do", "|", "file", "|", "\"#{file.source_file_pathname_relative_to_repo_root} has less than #{minimum_coverage}% code coverage\"", "end", "notify_messages", ".", "each", "do", "|", "message", "|", "if", "notify_level", "==", ":fail", "fail", "message", "else", "warn", "message", "end", "end", "end", "end" ]
Method to check if the coverage of modified files is at least a minumum @param options [Hash] a hash with the options @option options [Float] :minimum_coverage the minimum code coverage required for a file @option options [Symbol] :notify_level the level of notification @return [Array<String>]
[ "Method", "to", "check", "if", "the", "coverage", "of", "modified", "files", "is", "at", "least", "a", "minumum" ]
98be417dd89b922a20404810550a5d280d349b0e
https://github.com/BrunoMazzo/Danger-Slather/blob/98be417dd89b922a20404810550a5d280d349b0e/lib/slather/plugin.rb#L77-L97
1,331
BrunoMazzo/Danger-Slather
lib/slather/plugin.rb
Danger.DangerSlather.modified_files_coverage_table
def modified_files_coverage_table unless @project.nil? line = '' if all_modified_files_coverage.count > 0 line << "File | Coverage\n" line << "-----|-----\n" all_modified_files_coverage.each do |coverage_file| file_name = coverage_file.source_file_pathname_relative_to_repo_root.to_s percentage = @project.decimal_f([coverage_file.percentage_lines_tested]) line << "#{file_name} | **`#{percentage}%`**\n" end end return line end end
ruby
def modified_files_coverage_table unless @project.nil? line = '' if all_modified_files_coverage.count > 0 line << "File | Coverage\n" line << "-----|-----\n" all_modified_files_coverage.each do |coverage_file| file_name = coverage_file.source_file_pathname_relative_to_repo_root.to_s percentage = @project.decimal_f([coverage_file.percentage_lines_tested]) line << "#{file_name} | **`#{percentage}%`**\n" end end return line end end
[ "def", "modified_files_coverage_table", "unless", "@project", ".", "nil?", "line", "=", "''", "if", "all_modified_files_coverage", ".", "count", ">", "0", "line", "<<", "\"File | Coverage\\n\"", "line", "<<", "\"-----|-----\\n\"", "all_modified_files_coverage", ".", "each", "do", "|", "coverage_file", "|", "file_name", "=", "coverage_file", ".", "source_file_pathname_relative_to_repo_root", ".", "to_s", "percentage", "=", "@project", ".", "decimal_f", "(", "[", "coverage_file", ".", "percentage_lines_tested", "]", ")", "line", "<<", "\"#{file_name} | **`#{percentage}%`**\\n\"", "end", "end", "return", "line", "end", "end" ]
Build a coverage markdown table of the modified files coverage @return [String]
[ "Build", "a", "coverage", "markdown", "table", "of", "the", "modified", "files", "coverage" ]
98be417dd89b922a20404810550a5d280d349b0e
https://github.com/BrunoMazzo/Danger-Slather/blob/98be417dd89b922a20404810550a5d280d349b0e/lib/slather/plugin.rb#L117-L131
1,332
BrunoMazzo/Danger-Slather
lib/slather/plugin.rb
Danger.DangerSlather.show_coverage
def show_coverage unless @project.nil? line = "## Code coverage\n" line << total_coverage_markdown line << modified_files_coverage_table line << '> Powered by [Slather](https://github.com/SlatherOrg/slather)' markdown line end end
ruby
def show_coverage unless @project.nil? line = "## Code coverage\n" line << total_coverage_markdown line << modified_files_coverage_table line << '> Powered by [Slather](https://github.com/SlatherOrg/slather)' markdown line end end
[ "def", "show_coverage", "unless", "@project", ".", "nil?", "line", "=", "\"## Code coverage\\n\"", "line", "<<", "total_coverage_markdown", "line", "<<", "modified_files_coverage_table", "line", "<<", "'> Powered by [Slather](https://github.com/SlatherOrg/slather)'", "markdown", "line", "end", "end" ]
Show a header with the total coverage and coverage table @return [Array<String>]
[ "Show", "a", "header", "with", "the", "total", "coverage", "and", "coverage", "table" ]
98be417dd89b922a20404810550a5d280d349b0e
https://github.com/BrunoMazzo/Danger-Slather/blob/98be417dd89b922a20404810550a5d280d349b0e/lib/slather/plugin.rb#L143-L151
1,333
BrunoMazzo/Danger-Slather
lib/slather/plugin.rb
Danger.DangerSlather.all_modified_files_coverage
def all_modified_files_coverage unless @project.nil? all_modified_files_coverage ||= begin modified_files = git.modified_files.nil? ? [] : git.modified_files added_files = git.added_files.nil? ? [] : git.added_files all_changed_files = modified_files | added_files @project.coverage_files.select do |file| all_changed_files.include? file.source_file_pathname_relative_to_repo_root.to_s end end all_modified_files_coverage end end
ruby
def all_modified_files_coverage unless @project.nil? all_modified_files_coverage ||= begin modified_files = git.modified_files.nil? ? [] : git.modified_files added_files = git.added_files.nil? ? [] : git.added_files all_changed_files = modified_files | added_files @project.coverage_files.select do |file| all_changed_files.include? file.source_file_pathname_relative_to_repo_root.to_s end end all_modified_files_coverage end end
[ "def", "all_modified_files_coverage", "unless", "@project", ".", "nil?", "all_modified_files_coverage", "||=", "begin", "modified_files", "=", "git", ".", "modified_files", ".", "nil?", "?", "[", "]", ":", "git", ".", "modified_files", "added_files", "=", "git", ".", "added_files", ".", "nil?", "?", "[", "]", ":", "git", ".", "added_files", "all_changed_files", "=", "modified_files", "|", "added_files", "@project", ".", "coverage_files", ".", "select", "do", "|", "file", "|", "all_changed_files", ".", "include?", "file", ".", "source_file_pathname_relative_to_repo_root", ".", "to_s", "end", "end", "all_modified_files_coverage", "end", "end" ]
Array of files that we have coverage information and was modified @return [Array<File>]
[ "Array", "of", "files", "that", "we", "have", "coverage", "information", "and", "was", "modified" ]
98be417dd89b922a20404810550a5d280d349b0e
https://github.com/BrunoMazzo/Danger-Slather/blob/98be417dd89b922a20404810550a5d280d349b0e/lib/slather/plugin.rb#L155-L168
1,334
mobomo/green_onion
lib/green_onion/compare.rb
GreenOnion.Compare.diff_iterator
def diff_iterator @images.first.height.times do |y| @images.first.row(y).each_with_index do |pixel, x| unless pixel == @images.last[x,y] @diff_index << [x,y] pixel_difference_filter(pixel, x, y) end end end end
ruby
def diff_iterator @images.first.height.times do |y| @images.first.row(y).each_with_index do |pixel, x| unless pixel == @images.last[x,y] @diff_index << [x,y] pixel_difference_filter(pixel, x, y) end end end end
[ "def", "diff_iterator", "@images", ".", "first", ".", "height", ".", "times", "do", "|", "y", "|", "@images", ".", "first", ".", "row", "(", "y", ")", ".", "each_with_index", "do", "|", "pixel", ",", "x", "|", "unless", "pixel", "==", "@images", ".", "last", "[", "x", ",", "y", "]", "@diff_index", "<<", "[", "x", ",", "y", "]", "pixel_difference_filter", "(", "pixel", ",", "x", ",", "y", ")", "end", "end", "end", "end" ]
Run through all of the pixels on both org image, and fresh image. Change the pixel color accordingly.
[ "Run", "through", "all", "of", "the", "pixels", "on", "both", "org", "image", "and", "fresh", "image", ".", "Change", "the", "pixel", "color", "accordingly", "." ]
6e4bab440e22dab00fa3e543888c6d924e97777b
https://github.com/mobomo/green_onion/blob/6e4bab440e22dab00fa3e543888c6d924e97777b/lib/green_onion/compare.rb#L27-L36
1,335
mobomo/green_onion
lib/green_onion/compare.rb
GreenOnion.Compare.pixel_difference_filter
def pixel_difference_filter(pixel, x, y) chans = [] [:r, :b, :g].each do |chan| chans << channel_difference(chan, pixel, x, y) end @images.last[x,y] = ChunkyPNG::Color.rgb(chans[0], chans[1], chans[2]) end
ruby
def pixel_difference_filter(pixel, x, y) chans = [] [:r, :b, :g].each do |chan| chans << channel_difference(chan, pixel, x, y) end @images.last[x,y] = ChunkyPNG::Color.rgb(chans[0], chans[1], chans[2]) end
[ "def", "pixel_difference_filter", "(", "pixel", ",", "x", ",", "y", ")", "chans", "=", "[", "]", "[", ":r", ",", ":b", ",", ":g", "]", ".", "each", "do", "|", "chan", "|", "chans", "<<", "channel_difference", "(", "chan", ",", "pixel", ",", "x", ",", "y", ")", "end", "@images", ".", "last", "[", "x", ",", "y", "]", "=", "ChunkyPNG", "::", "Color", ".", "rgb", "(", "chans", "[", "0", "]", ",", "chans", "[", "1", "]", ",", "chans", "[", "2", "]", ")", "end" ]
Changes the pixel color to be the opposite RGB value
[ "Changes", "the", "pixel", "color", "to", "be", "the", "opposite", "RGB", "value" ]
6e4bab440e22dab00fa3e543888c6d924e97777b
https://github.com/mobomo/green_onion/blob/6e4bab440e22dab00fa3e543888c6d924e97777b/lib/green_onion/compare.rb#L39-L45
1,336
mobomo/green_onion
lib/green_onion/compare.rb
GreenOnion.Compare.channel_difference
def channel_difference(chan, pixel, x, y) ChunkyPNG::Color.send(chan, pixel) + ChunkyPNG::Color.send(chan, @images.last[x,y]) - 2 * [ChunkyPNG::Color.send(chan, pixel), ChunkyPNG::Color.send(chan, @images.last[x,y])].min end
ruby
def channel_difference(chan, pixel, x, y) ChunkyPNG::Color.send(chan, pixel) + ChunkyPNG::Color.send(chan, @images.last[x,y]) - 2 * [ChunkyPNG::Color.send(chan, pixel), ChunkyPNG::Color.send(chan, @images.last[x,y])].min end
[ "def", "channel_difference", "(", "chan", ",", "pixel", ",", "x", ",", "y", ")", "ChunkyPNG", "::", "Color", ".", "send", "(", "chan", ",", "pixel", ")", "+", "ChunkyPNG", "::", "Color", ".", "send", "(", "chan", ",", "@images", ".", "last", "[", "x", ",", "y", "]", ")", "-", "2", "*", "[", "ChunkyPNG", "::", "Color", ".", "send", "(", "chan", ",", "pixel", ")", ",", "ChunkyPNG", "::", "Color", ".", "send", "(", "chan", ",", "@images", ".", "last", "[", "x", ",", "y", "]", ")", "]", ".", "min", "end" ]
Interface to run the R, G, B methods on ChunkyPNG
[ "Interface", "to", "run", "the", "R", "G", "B", "methods", "on", "ChunkyPNG" ]
6e4bab440e22dab00fa3e543888c6d924e97777b
https://github.com/mobomo/green_onion/blob/6e4bab440e22dab00fa3e543888c6d924e97777b/lib/green_onion/compare.rb#L48-L50
1,337
mobomo/green_onion
lib/green_onion/compare.rb
GreenOnion.Compare.percentage_diff
def percentage_diff(org, fresh) diff_images(org, fresh) @total_px = @images.first.pixels.length @changed_px = @diff_index.length @percentage_changed = ( (@diff_index.length.to_f / @images.first.pixels.length) * 100 ).round(2) end
ruby
def percentage_diff(org, fresh) diff_images(org, fresh) @total_px = @images.first.pixels.length @changed_px = @diff_index.length @percentage_changed = ( (@diff_index.length.to_f / @images.first.pixels.length) * 100 ).round(2) end
[ "def", "percentage_diff", "(", "org", ",", "fresh", ")", "diff_images", "(", "org", ",", "fresh", ")", "@total_px", "=", "@images", ".", "first", ".", "pixels", ".", "length", "@changed_px", "=", "@diff_index", ".", "length", "@percentage_changed", "=", "(", "(", "@diff_index", ".", "length", ".", "to_f", "/", "@images", ".", "first", ".", "pixels", ".", "length", ")", "*", "100", ")", ".", "round", "(", "2", ")", "end" ]
Returns the numeric results of the diff of 2 images
[ "Returns", "the", "numeric", "results", "of", "the", "diff", "of", "2", "images" ]
6e4bab440e22dab00fa3e543888c6d924e97777b
https://github.com/mobomo/green_onion/blob/6e4bab440e22dab00fa3e543888c6d924e97777b/lib/green_onion/compare.rb#L53-L58
1,338
mobomo/green_onion
lib/green_onion/compare.rb
GreenOnion.Compare.save_visual_diff
def save_visual_diff(org, fresh) x, y = @diff_index.map{ |xy| xy[0] }, @diff_index.map{ |xy| xy[1] } @diffed_image = org.insert(-5, '_diff') begin @images.last.rect(x.min, y.min, x.max, y.max, ChunkyPNG::Color.rgb(0,255,0)) rescue NoMethodError puts "Both skins are the same.".color(:yellow) end @images.last.save(@diffed_image) end
ruby
def save_visual_diff(org, fresh) x, y = @diff_index.map{ |xy| xy[0] }, @diff_index.map{ |xy| xy[1] } @diffed_image = org.insert(-5, '_diff') begin @images.last.rect(x.min, y.min, x.max, y.max, ChunkyPNG::Color.rgb(0,255,0)) rescue NoMethodError puts "Both skins are the same.".color(:yellow) end @images.last.save(@diffed_image) end
[ "def", "save_visual_diff", "(", "org", ",", "fresh", ")", "x", ",", "y", "=", "@diff_index", ".", "map", "{", "|", "xy", "|", "xy", "[", "0", "]", "}", ",", "@diff_index", ".", "map", "{", "|", "xy", "|", "xy", "[", "1", "]", "}", "@diffed_image", "=", "org", ".", "insert", "(", "-", "5", ",", "'_diff'", ")", "begin", "@images", ".", "last", ".", "rect", "(", "x", ".", "min", ",", "y", ".", "min", ",", "x", ".", "max", ",", "y", ".", "max", ",", "ChunkyPNG", "::", "Color", ".", "rgb", "(", "0", ",", "255", ",", "0", ")", ")", "rescue", "NoMethodError", "puts", "\"Both skins are the same.\"", ".", "color", "(", ":yellow", ")", "end", "@images", ".", "last", ".", "save", "(", "@diffed_image", ")", "end" ]
Saves the visual diff as a separate file
[ "Saves", "the", "visual", "diff", "as", "a", "separate", "file" ]
6e4bab440e22dab00fa3e543888c6d924e97777b
https://github.com/mobomo/green_onion/blob/6e4bab440e22dab00fa3e543888c6d924e97777b/lib/green_onion/compare.rb#L67-L78
1,339
ranjib/etcd-ruby
lib/etcd/keys.rb
Etcd.Keys.get
def get(key, opts = {}) response = api_execute(key_endpoint + key, :get, params: opts) Response.from_http_response(response) end
ruby
def get(key, opts = {}) response = api_execute(key_endpoint + key, :get, params: opts) Response.from_http_response(response) end
[ "def", "get", "(", "key", ",", "opts", "=", "{", "}", ")", "response", "=", "api_execute", "(", "key_endpoint", "+", "key", ",", ":get", ",", "params", ":", "opts", ")", "Response", ".", "from_http_response", "(", "response", ")", "end" ]
Retrives a key with its associated data, if key is not present it will return with message "Key Not Found" This method takes the following parameters as arguments * key - whose data is to be retrieved
[ "Retrives", "a", "key", "with", "its", "associated", "data", "if", "key", "is", "not", "present", "it", "will", "return", "with", "message", "Key", "Not", "Found" ]
f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917
https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/lib/etcd/keys.rb#L21-L24
1,340
ranjib/etcd-ruby
lib/etcd/keys.rb
Etcd.Keys.set
def set(key, opts = nil) fail ArgumentError, 'Second argument must be a hash' unless opts.is_a?(Hash) path = key_endpoint + key payload = {} [:ttl, :value, :dir, :prevExist, :prevValue, :prevIndex].each do |k| payload[k] = opts[k] if opts.key?(k) end response = api_execute(path, :put, params: payload) Response.from_http_response(response) end
ruby
def set(key, opts = nil) fail ArgumentError, 'Second argument must be a hash' unless opts.is_a?(Hash) path = key_endpoint + key payload = {} [:ttl, :value, :dir, :prevExist, :prevValue, :prevIndex].each do |k| payload[k] = opts[k] if opts.key?(k) end response = api_execute(path, :put, params: payload) Response.from_http_response(response) end
[ "def", "set", "(", "key", ",", "opts", "=", "nil", ")", "fail", "ArgumentError", ",", "'Second argument must be a hash'", "unless", "opts", ".", "is_a?", "(", "Hash", ")", "path", "=", "key_endpoint", "+", "key", "payload", "=", "{", "}", "[", ":ttl", ",", ":value", ",", ":dir", ",", ":prevExist", ",", ":prevValue", ",", ":prevIndex", "]", ".", "each", "do", "|", "k", "|", "payload", "[", "k", "]", "=", "opts", "[", "k", "]", "if", "opts", ".", "key?", "(", "k", ")", "end", "response", "=", "api_execute", "(", "path", ",", ":put", ",", "params", ":", "payload", ")", "Response", ".", "from_http_response", "(", "response", ")", "end" ]
Create or update a new key This method takes the following parameters as arguments * key - whose value to be set * value - value to be set for specified key * ttl - shelf life of a key (in seconds) (optional)
[ "Create", "or", "update", "a", "new", "key" ]
f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917
https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/lib/etcd/keys.rb#L32-L41
1,341
ranjib/etcd-ruby
lib/etcd/keys.rb
Etcd.Keys.compare_and_swap
def compare_and_swap(key, opts = {}) fail ArgumentError, 'Second argument must be a hash' unless opts.is_a?(Hash) fail ArgumentError, 'You must pass prevValue' unless opts.key?(:prevValue) set(key, opts) end
ruby
def compare_and_swap(key, opts = {}) fail ArgumentError, 'Second argument must be a hash' unless opts.is_a?(Hash) fail ArgumentError, 'You must pass prevValue' unless opts.key?(:prevValue) set(key, opts) end
[ "def", "compare_and_swap", "(", "key", ",", "opts", "=", "{", "}", ")", "fail", "ArgumentError", ",", "'Second argument must be a hash'", "unless", "opts", ".", "is_a?", "(", "Hash", ")", "fail", "ArgumentError", ",", "'You must pass prevValue'", "unless", "opts", ".", "key?", "(", ":prevValue", ")", "set", "(", "key", ",", "opts", ")", "end" ]
Set a new value for key if previous value of key is matched This method takes the following parameters as arguments * key - whose value is going to change if previous value is matched * value - new value to be set for specified key * prevValue - value of a key to compare with existing value of key * ttl - shelf life of a key (in secsonds) (optional)
[ "Set", "a", "new", "value", "for", "key", "if", "previous", "value", "of", "key", "is", "matched" ]
f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917
https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/lib/etcd/keys.rb#L59-L63
1,342
ranjib/etcd-ruby
lib/etcd/keys.rb
Etcd.Keys.watch
def watch(key, opts = {}) params = { wait: true } fail ArgumentError, 'Second argument must be a hash' unless opts.is_a?(Hash) timeout = opts[:timeout] || @read_timeout index = opts[:waitIndex] || opts[:index] params[:waitIndex] = index unless index.nil? params[:consistent] = opts[:consistent] if opts.key?(:consistent) params[:recursive] = opts[:recursive] if opts.key?(:recursive) response = api_execute( key_endpoint + key, :get, timeout: timeout, params: params ) Response.from_http_response(response) end
ruby
def watch(key, opts = {}) params = { wait: true } fail ArgumentError, 'Second argument must be a hash' unless opts.is_a?(Hash) timeout = opts[:timeout] || @read_timeout index = opts[:waitIndex] || opts[:index] params[:waitIndex] = index unless index.nil? params[:consistent] = opts[:consistent] if opts.key?(:consistent) params[:recursive] = opts[:recursive] if opts.key?(:recursive) response = api_execute( key_endpoint + key, :get, timeout: timeout, params: params ) Response.from_http_response(response) end
[ "def", "watch", "(", "key", ",", "opts", "=", "{", "}", ")", "params", "=", "{", "wait", ":", "true", "}", "fail", "ArgumentError", ",", "'Second argument must be a hash'", "unless", "opts", ".", "is_a?", "(", "Hash", ")", "timeout", "=", "opts", "[", ":timeout", "]", "||", "@read_timeout", "index", "=", "opts", "[", ":waitIndex", "]", "||", "opts", "[", ":index", "]", "params", "[", ":waitIndex", "]", "=", "index", "unless", "index", ".", "nil?", "params", "[", ":consistent", "]", "=", "opts", "[", ":consistent", "]", "if", "opts", ".", "key?", "(", ":consistent", ")", "params", "[", ":recursive", "]", "=", "opts", "[", ":recursive", "]", "if", "opts", ".", "key?", "(", ":recursive", ")", "response", "=", "api_execute", "(", "key_endpoint", "+", "key", ",", ":get", ",", "timeout", ":", "timeout", ",", "params", ":", "params", ")", "Response", ".", "from_http_response", "(", "response", ")", "end" ]
Gives a notification when specified key changes This method takes the following parameters as arguments @ key - key to be watched @options [Hash] additional options for watching a key @options [Fixnum] :index watch the specified key from given index @options [Fixnum] :timeout specify http timeout
[ "Gives", "a", "notification", "when", "specified", "key", "changes" ]
f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917
https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/lib/etcd/keys.rb#L72-L88
1,343
marcelocf/gremlin_client
lib/gremlin_client/connection.rb
GremlinClient.Connection.receive_message
def receive_message(msg) response = Oj.load(msg.data) # this check is important in case a request timeout and we make new ones after if response['requestId'] == @request_id if @response.nil? @response = response else @response['result']['data'].concat response['result']['data'] @response['result']['meta'].merge! response['result']['meta'] @response['status'] = response['status'] end end end
ruby
def receive_message(msg) response = Oj.load(msg.data) # this check is important in case a request timeout and we make new ones after if response['requestId'] == @request_id if @response.nil? @response = response else @response['result']['data'].concat response['result']['data'] @response['result']['meta'].merge! response['result']['meta'] @response['status'] = response['status'] end end end
[ "def", "receive_message", "(", "msg", ")", "response", "=", "Oj", ".", "load", "(", "msg", ".", "data", ")", "# this check is important in case a request timeout and we make new ones after", "if", "response", "[", "'requestId'", "]", "==", "@request_id", "if", "@response", ".", "nil?", "@response", "=", "response", "else", "@response", "[", "'result'", "]", "[", "'data'", "]", ".", "concat", "response", "[", "'result'", "]", "[", "'data'", "]", "@response", "[", "'result'", "]", "[", "'meta'", "]", ".", "merge!", "response", "[", "'result'", "]", "[", "'meta'", "]", "@response", "[", "'status'", "]", "=", "response", "[", "'status'", "]", "end", "end", "end" ]
this has to be public so the websocket client thread sees it
[ "this", "has", "to", "be", "public", "so", "the", "websocket", "client", "thread", "sees", "it" ]
91645fd6a5e47e3faf2d925c9aebec86bb457fb1
https://github.com/marcelocf/gremlin_client/blob/91645fd6a5e47e3faf2d925c9aebec86bb457fb1/lib/gremlin_client/connection.rb#L99-L111
1,344
marcelocf/gremlin_client
lib/gremlin_client/connection.rb
GremlinClient.Connection.treat_response
def treat_response # note that the partial_content status should be processed differently. # look at http://tinkerpop.apache.org/docs/3.0.1-incubating/ for more info ok_status = [:success, :no_content, :partial_content].map { |st| STATUS[st] } unless ok_status.include?(@response['status']['code']) fail ::GremlinClient::ServerError.new(@response['status']['code'], @response['status']['message']) end @response['result'] end
ruby
def treat_response # note that the partial_content status should be processed differently. # look at http://tinkerpop.apache.org/docs/3.0.1-incubating/ for more info ok_status = [:success, :no_content, :partial_content].map { |st| STATUS[st] } unless ok_status.include?(@response['status']['code']) fail ::GremlinClient::ServerError.new(@response['status']['code'], @response['status']['message']) end @response['result'] end
[ "def", "treat_response", "# note that the partial_content status should be processed differently.", "# look at http://tinkerpop.apache.org/docs/3.0.1-incubating/ for more info", "ok_status", "=", "[", ":success", ",", ":no_content", ",", ":partial_content", "]", ".", "map", "{", "|", "st", "|", "STATUS", "[", "st", "]", "}", "unless", "ok_status", ".", "include?", "(", "@response", "[", "'status'", "]", "[", "'code'", "]", ")", "fail", "::", "GremlinClient", "::", "ServerError", ".", "new", "(", "@response", "[", "'status'", "]", "[", "'code'", "]", ",", "@response", "[", "'status'", "]", "[", "'message'", "]", ")", "end", "@response", "[", "'result'", "]", "end" ]
we validate our response here to make sure it is going to be raising exceptions in the right thread
[ "we", "validate", "our", "response", "here", "to", "make", "sure", "it", "is", "going", "to", "be", "raising", "exceptions", "in", "the", "right", "thread" ]
91645fd6a5e47e3faf2d925c9aebec86bb457fb1
https://github.com/marcelocf/gremlin_client/blob/91645fd6a5e47e3faf2d925c9aebec86bb457fb1/lib/gremlin_client/connection.rb#L159-L167
1,345
yandex-money/yandex-money-sdk-ruby
lib/yandex_money/external_payment.rb
YandexMoney.ExternalPayment.request_external_payment
def request_external_payment(payment_options) payment_options[:instance_id] = @instance_id request = self.class.send_external_payment_request("/api/request-external-payment", payment_options) RecursiveOpenStruct.new request.parsed_response end
ruby
def request_external_payment(payment_options) payment_options[:instance_id] = @instance_id request = self.class.send_external_payment_request("/api/request-external-payment", payment_options) RecursiveOpenStruct.new request.parsed_response end
[ "def", "request_external_payment", "(", "payment_options", ")", "payment_options", "[", ":instance_id", "]", "=", "@instance_id", "request", "=", "self", ".", "class", ".", "send_external_payment_request", "(", "\"/api/request-external-payment\"", ",", "payment_options", ")", "RecursiveOpenStruct", ".", "new", "request", ".", "parsed_response", "end" ]
Requests a external payment @see http://api.yandex.com/money/doc/dg/reference/request-external-payment.xml @see https://tech.yandex.ru/money/doc/dg/reference/request-external-payment-docpage/ @param payment_options [Hash] Method's parameters. Check out docs for more information. @raise [YandexMoney::InvalidRequestError] HTTP request does not conform to protocol format. Unable to parse HTTP request, or the Authorization header is missing or has an invalid value. @raise [YandexMoney::ServerError] A technical error occurs (the server responds with the HTTP code 500 Internal Server Error). The application should repeat the request with the same parameters later. @return [RecursiveOpenStruct] A struct, containing `payment_id` and additional information about a recipient and payer
[ "Requests", "a", "external", "payment" ]
5634ebc09aaad3c8f96e2cde20cc60edf6b47899
https://github.com/yandex-money/yandex-money-sdk-ruby/blob/5634ebc09aaad3c8f96e2cde20cc60edf6b47899/lib/yandex_money/external_payment.rb#L38-L42
1,346
yandex-money/yandex-money-sdk-ruby
lib/yandex_money/external_payment.rb
YandexMoney.ExternalPayment.process_external_payment
def process_external_payment(payment_options) payment_options[:instance_id] = @instance_id request = self.class.send_external_payment_request("/api/process-external-payment", payment_options) RecursiveOpenStruct.new request.parsed_response end
ruby
def process_external_payment(payment_options) payment_options[:instance_id] = @instance_id request = self.class.send_external_payment_request("/api/process-external-payment", payment_options) RecursiveOpenStruct.new request.parsed_response end
[ "def", "process_external_payment", "(", "payment_options", ")", "payment_options", "[", ":instance_id", "]", "=", "@instance_id", "request", "=", "self", ".", "class", ".", "send_external_payment_request", "(", "\"/api/process-external-payment\"", ",", "payment_options", ")", "RecursiveOpenStruct", ".", "new", "request", ".", "parsed_response", "end" ]
Confirms a payment that was created using the request-extenral-payment method @see http://api.yandex.com/money/doc/dg/reference/process-external-payment.xml @see https://tech.yandex.ru/money/doc/dg/reference/process-external-payment-docpage/ @param payment_options [Hash] Method's parameters. Check out docs for more information. @raise [YandexMoney::InvalidRequestError] HTTP request does not conform to protocol format. Unable to parse HTTP request, or the Authorization header is missing or has an invalid value. @raise [YandexMoney::ServerError] A technical error occurs (the server responds with the HTTP code 500 Internal Server Error). The application should repeat the request with the same parameters later. @return [RecursiveOpenStruct] A status of payment and additional steps for authorization (if needed)
[ "Confirms", "a", "payment", "that", "was", "created", "using", "the", "request", "-", "extenral", "-", "payment", "method" ]
5634ebc09aaad3c8f96e2cde20cc60edf6b47899
https://github.com/yandex-money/yandex-money-sdk-ruby/blob/5634ebc09aaad3c8f96e2cde20cc60edf6b47899/lib/yandex_money/external_payment.rb#L55-L59
1,347
hsgubert/cassandra_migrations
lib/cassandra_migrations/migration.rb
CassandraMigrations.Migration.migrate
def migrate(direction) return unless respond_to?(direction) case direction when :up then announce_migration "migrating" when :down then announce_migration "reverting" end time = Benchmark.measure { send(direction) } case direction when :up then announce_migration "migrated (%.4fs)" % time.real; puts when :down then announce_migration "reverted (%.4fs)" % time.real; puts end end
ruby
def migrate(direction) return unless respond_to?(direction) case direction when :up then announce_migration "migrating" when :down then announce_migration "reverting" end time = Benchmark.measure { send(direction) } case direction when :up then announce_migration "migrated (%.4fs)" % time.real; puts when :down then announce_migration "reverted (%.4fs)" % time.real; puts end end
[ "def", "migrate", "(", "direction", ")", "return", "unless", "respond_to?", "(", "direction", ")", "case", "direction", "when", ":up", "then", "announce_migration", "\"migrating\"", "when", ":down", "then", "announce_migration", "\"reverting\"", "end", "time", "=", "Benchmark", ".", "measure", "{", "send", "(", "direction", ")", "}", "case", "direction", "when", ":up", "then", "announce_migration", "\"migrated (%.4fs)\"", "%", "time", ".", "real", ";", "puts", "when", ":down", "then", "announce_migration", "\"reverted (%.4fs)\"", "%", "time", ".", "real", ";", "puts", "end", "end" ]
Execute this migration in the named direction. The advantage of using this instead of directly calling up or down is that this method gives informative output and benchmarks the time taken.
[ "Execute", "this", "migration", "in", "the", "named", "direction", "." ]
24dae6a4bb39356fa3b596ba120eadf66bca4925
https://github.com/hsgubert/cassandra_migrations/blob/24dae6a4bb39356fa3b596ba120eadf66bca4925/lib/cassandra_migrations/migration.rb#L51-L65
1,348
hsgubert/cassandra_migrations
lib/cassandra_migrations/migration.rb
CassandraMigrations.Migration.announce_migration
def announce_migration(message) text = "#{name}: #{message}" length = [0, 75 - text.length].max puts "== %s %s" % [text, "=" * length] end
ruby
def announce_migration(message) text = "#{name}: #{message}" length = [0, 75 - text.length].max puts "== %s %s" % [text, "=" * length] end
[ "def", "announce_migration", "(", "message", ")", "text", "=", "\"#{name}: #{message}\"", "length", "=", "[", "0", ",", "75", "-", "text", ".", "length", "]", ".", "max", "puts", "\"== %s %s\"", "%", "[", "text", ",", "\"=\"", "*", "length", "]", "end" ]
Generates output labeled with name of migration and a line that goes up to 75 characters long in the terminal
[ "Generates", "output", "labeled", "with", "name", "of", "migration", "and", "a", "line", "that", "goes", "up", "to", "75", "characters", "long", "in", "the", "terminal" ]
24dae6a4bb39356fa3b596ba120eadf66bca4925
https://github.com/hsgubert/cassandra_migrations/blob/24dae6a4bb39356fa3b596ba120eadf66bca4925/lib/cassandra_migrations/migration.rb#L71-L75
1,349
yandex-money/yandex-money-sdk-ruby
lib/yandex_money/wallet.rb
YandexMoney.Wallet.operation_history
def operation_history(options=nil) history = RecursiveOpenStruct.new( send_request("/api/operation-history", options).parsed_response ) history.operations = history.operations.map do |operation| RecursiveOpenStruct.new operation end history end
ruby
def operation_history(options=nil) history = RecursiveOpenStruct.new( send_request("/api/operation-history", options).parsed_response ) history.operations = history.operations.map do |operation| RecursiveOpenStruct.new operation end history end
[ "def", "operation_history", "(", "options", "=", "nil", ")", "history", "=", "RecursiveOpenStruct", ".", "new", "(", "send_request", "(", "\"/api/operation-history\"", ",", "options", ")", ".", "parsed_response", ")", "history", ".", "operations", "=", "history", ".", "operations", ".", "map", "do", "|", "operation", "|", "RecursiveOpenStruct", ".", "new", "operation", "end", "history", "end" ]
Returns operation history of a user's wallet @see http://api.yandex.com/money/doc/dg/reference/operation-history.xml @see https://tech.yandex.ru/money/doc/dg/reference/operation-history-docpage/ @param options [Hash] A hash with filter parameters according to documetation @return [Array<RecursiveOpenStruct>] An array containing user's wallet operations. @raise [YandexMoney::InvalidRequestError] HTTP request does not conform to protocol format. Unable to parse HTTP request, or the Authorization header is missing or has an invalid value. @raise [YandexMoney::UnauthorizedError] Nonexistent, expired, or revoked token specified. @raise [YandexMoney::InsufficientScopeError] The token does not have permissions for the requested operation. @raise [YandexMoney::ServerError] A technical error occurs (the server responds with the HTTP code 500 Internal Server Error). The application should repeat the request with the same parameters later.
[ "Returns", "operation", "history", "of", "a", "user", "s", "wallet" ]
5634ebc09aaad3c8f96e2cde20cc60edf6b47899
https://github.com/yandex-money/yandex-money-sdk-ruby/blob/5634ebc09aaad3c8f96e2cde20cc60edf6b47899/lib/yandex_money/wallet.rb#L45-L53
1,350
yandex-money/yandex-money-sdk-ruby
lib/yandex_money/wallet.rb
YandexMoney.Wallet.operation_details
def operation_details(operation_id) request = send_request("/api/operation-details", operation_id: operation_id) RecursiveOpenStruct.new request.parsed_response end
ruby
def operation_details(operation_id) request = send_request("/api/operation-details", operation_id: operation_id) RecursiveOpenStruct.new request.parsed_response end
[ "def", "operation_details", "(", "operation_id", ")", "request", "=", "send_request", "(", "\"/api/operation-details\"", ",", "operation_id", ":", "operation_id", ")", "RecursiveOpenStruct", ".", "new", "request", ".", "parsed_response", "end" ]
Returns details of operation specified by operation_id @see http://api.yandex.com/money/doc/dg/reference/operation-details.xml @see https://tech.yandex.ru/money/doc/dg/reference/operation-details-docpage/ @param operation_id [String] A operation identifier @return [RecursiveOpenStruct] All details of requested operation. @raise [YandexMoney::InvalidRequestError] HTTP request does not conform to protocol format. Unable to parse HTTP request, or the Authorization header is missing or has an invalid value. @raise [YandexMoney::UnauthorizedError] Nonexistent, expired, or revoked token specified. @raise [YandexMoney::InsufficientScopeError] The token does not have permissions for the requested operation. @raise [YandexMoney::ServerError] A technical error occurs (the server responds with the HTTP code 500 Internal Server Error). The application should repeat the request with the same parameters later.
[ "Returns", "details", "of", "operation", "specified", "by", "operation_id" ]
5634ebc09aaad3c8f96e2cde20cc60edf6b47899
https://github.com/yandex-money/yandex-money-sdk-ruby/blob/5634ebc09aaad3c8f96e2cde20cc60edf6b47899/lib/yandex_money/wallet.rb#L67-L70
1,351
yandex-money/yandex-money-sdk-ruby
lib/yandex_money/wallet.rb
YandexMoney.Wallet.incoming_transfer_accept
def incoming_transfer_accept(operation_id, protection_code = nil) uri = "/api/incoming-transfer-accept" if protection_code request_body = { operation_id: operation_id, protection_code: protection_code } else request_body = { operation_id: operation_id } end RecursiveOpenStruct.new send_request("/api/incoming-transfer-accept", request_body) end
ruby
def incoming_transfer_accept(operation_id, protection_code = nil) uri = "/api/incoming-transfer-accept" if protection_code request_body = { operation_id: operation_id, protection_code: protection_code } else request_body = { operation_id: operation_id } end RecursiveOpenStruct.new send_request("/api/incoming-transfer-accept", request_body) end
[ "def", "incoming_transfer_accept", "(", "operation_id", ",", "protection_code", "=", "nil", ")", "uri", "=", "\"/api/incoming-transfer-accept\"", "if", "protection_code", "request_body", "=", "{", "operation_id", ":", "operation_id", ",", "protection_code", ":", "protection_code", "}", "else", "request_body", "=", "{", "operation_id", ":", "operation_id", "}", "end", "RecursiveOpenStruct", ".", "new", "send_request", "(", "\"/api/incoming-transfer-accept\"", ",", "request_body", ")", "end" ]
Accepts incoming transfer with a protection code or deferred transfer @see http://api.yandex.com/money/doc/dg/reference/incoming-transfer-accept.xml @see https://tech.yandex.ru/money/doc/dg/reference/incoming-transfer-accept-docpage/ @param operation_id [String] A operation identifier @param protection_code [String] Secret code of four decimal digits. Specified for an incoming transfer proteced by a secret code. Omitted for deferred transfers @return [RecursiveOpenStruct] An information about operation result. @raise [YandexMoney::InvalidRequestError] HTTP request does not conform to protocol format. Unable to parse HTTP request, or the Authorization header is missing or has an invalid value. @raise [YandexMoney::UnauthorizedError] Nonexistent, expired, or revoked token specified. @raise [YandexMoney::InsufficientScopeError] The token does not have permissions for the requested operation. @raise [YandexMoney::ServerError] A technical error occurs (the server responds with the HTTP code 500 Internal Server Error). The application should repeat the request with the same parameters later.
[ "Accepts", "incoming", "transfer", "with", "a", "protection", "code", "or", "deferred", "transfer" ]
5634ebc09aaad3c8f96e2cde20cc60edf6b47899
https://github.com/yandex-money/yandex-money-sdk-ruby/blob/5634ebc09aaad3c8f96e2cde20cc60edf6b47899/lib/yandex_money/wallet.rb#L117-L128
1,352
ranjib/etcd-ruby
lib/etcd/client.rb
Etcd.Client.api_execute
def api_execute(path, method, options = {}) params = options[:params] case method when :get req = build_http_request(Net::HTTP::Get, path, params) when :post req = build_http_request(Net::HTTP::Post, path, nil, params) when :put req = build_http_request(Net::HTTP::Put, path, nil, params) when :delete req = build_http_request(Net::HTTP::Delete, path, params) else fail "Unknown http action: #{method}" end http = Net::HTTP.new(host, port) http.read_timeout = options[:timeout] || read_timeout setup_https(http) req.basic_auth(user_name, password) if [user_name, password].all? Log.debug("Invoking: '#{req.class}' against '#{path}") res = http.request(req) Log.debug("Response code: #{res.code}") Log.debug("Response body: #{res.body}") process_http_request(res) end
ruby
def api_execute(path, method, options = {}) params = options[:params] case method when :get req = build_http_request(Net::HTTP::Get, path, params) when :post req = build_http_request(Net::HTTP::Post, path, nil, params) when :put req = build_http_request(Net::HTTP::Put, path, nil, params) when :delete req = build_http_request(Net::HTTP::Delete, path, params) else fail "Unknown http action: #{method}" end http = Net::HTTP.new(host, port) http.read_timeout = options[:timeout] || read_timeout setup_https(http) req.basic_auth(user_name, password) if [user_name, password].all? Log.debug("Invoking: '#{req.class}' against '#{path}") res = http.request(req) Log.debug("Response code: #{res.code}") Log.debug("Response body: #{res.body}") process_http_request(res) end
[ "def", "api_execute", "(", "path", ",", "method", ",", "options", "=", "{", "}", ")", "params", "=", "options", "[", ":params", "]", "case", "method", "when", ":get", "req", "=", "build_http_request", "(", "Net", "::", "HTTP", "::", "Get", ",", "path", ",", "params", ")", "when", ":post", "req", "=", "build_http_request", "(", "Net", "::", "HTTP", "::", "Post", ",", "path", ",", "nil", ",", "params", ")", "when", ":put", "req", "=", "build_http_request", "(", "Net", "::", "HTTP", "::", "Put", ",", "path", ",", "nil", ",", "params", ")", "when", ":delete", "req", "=", "build_http_request", "(", "Net", "::", "HTTP", "::", "Delete", ",", "path", ",", "params", ")", "else", "fail", "\"Unknown http action: #{method}\"", "end", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "host", ",", "port", ")", "http", ".", "read_timeout", "=", "options", "[", ":timeout", "]", "||", "read_timeout", "setup_https", "(", "http", ")", "req", ".", "basic_auth", "(", "user_name", ",", "password", ")", "if", "[", "user_name", ",", "password", "]", ".", "all?", "Log", ".", "debug", "(", "\"Invoking: '#{req.class}' against '#{path}\"", ")", "res", "=", "http", ".", "request", "(", "req", ")", "Log", ".", "debug", "(", "\"Response code: #{res.code}\"", ")", "Log", ".", "debug", "(", "\"Response body: #{res.body}\"", ")", "process_http_request", "(", "res", ")", "end" ]
This method sends api request to etcd server. This method has following parameters as argument * path - etcd server path (etcd server end point) * method - the request method used * options - any additional parameters used by request method (optional) rubocop:disable MethodLength, CyclomaticComplexity
[ "This", "method", "sends", "api", "request", "to", "etcd", "server", "." ]
f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917
https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/lib/etcd/client.rb#L92-L115
1,353
ranjib/etcd-ruby
lib/etcd/client.rb
Etcd.Client.process_http_request
def process_http_request(res) case res when HTTP_SUCCESS Log.debug('Http success') res when HTTP_CLIENT_ERROR fail Error.from_http_response(res) else Log.debug('Http error') Log.debug(res.body) res.error! end end
ruby
def process_http_request(res) case res when HTTP_SUCCESS Log.debug('Http success') res when HTTP_CLIENT_ERROR fail Error.from_http_response(res) else Log.debug('Http error') Log.debug(res.body) res.error! end end
[ "def", "process_http_request", "(", "res", ")", "case", "res", "when", "HTTP_SUCCESS", "Log", ".", "debug", "(", "'Http success'", ")", "res", "when", "HTTP_CLIENT_ERROR", "fail", "Error", ".", "from_http_response", "(", "res", ")", "else", "Log", ".", "debug", "(", "'Http error'", ")", "Log", ".", "debug", "(", "res", ".", "body", ")", "res", ".", "error!", "end", "end" ]
need to have original request to process the response when it redirects
[ "need", "to", "have", "original", "request", "to", "process", "the", "response", "when", "it", "redirects" ]
f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917
https://github.com/ranjib/etcd-ruby/blob/f7153c6a7829b1cd5e5a4470d7ca6f5217c4c917/lib/etcd/client.rb#L135-L147
1,354
b4mboo/git-review
lib/git-review/commands.rb
GitReview.Commands.list
def list(reverse = false) requests = server.current_requests_full.reject do |request| # Find only pending (= unmerged) requests and output summary. # Explicitly look for local changes git does not yet know about. # TODO: Isn't this a bit confusing? Maybe display pending pushes? local.merged? request.head.sha end source = local.source if requests.empty? puts "No pending requests for '#{source}'." else puts "Pending requests for '#{source}':" puts "ID Updated Comments Title".pink print_requests(requests, reverse) end end
ruby
def list(reverse = false) requests = server.current_requests_full.reject do |request| # Find only pending (= unmerged) requests and output summary. # Explicitly look for local changes git does not yet know about. # TODO: Isn't this a bit confusing? Maybe display pending pushes? local.merged? request.head.sha end source = local.source if requests.empty? puts "No pending requests for '#{source}'." else puts "Pending requests for '#{source}':" puts "ID Updated Comments Title".pink print_requests(requests, reverse) end end
[ "def", "list", "(", "reverse", "=", "false", ")", "requests", "=", "server", ".", "current_requests_full", ".", "reject", "do", "|", "request", "|", "# Find only pending (= unmerged) requests and output summary.", "# Explicitly look for local changes git does not yet know about.", "# TODO: Isn't this a bit confusing? Maybe display pending pushes?", "local", ".", "merged?", "request", ".", "head", ".", "sha", "end", "source", "=", "local", ".", "source", "if", "requests", ".", "empty?", "puts", "\"No pending requests for '#{source}'.\"", "else", "puts", "\"Pending requests for '#{source}':\"", "puts", "\"ID Updated Comments Title\"", ".", "pink", "print_requests", "(", "requests", ",", "reverse", ")", "end", "end" ]
List all pending requests.
[ "List", "all", "pending", "requests", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/commands.rb#L9-L24
1,355
b4mboo/git-review
lib/git-review/commands.rb
GitReview.Commands.show
def show(number, full = false) request = server.get_request_by_number(number) # Determine whether to show full diff or stats only. option = full ? '' : '--stat ' diff = "diff --color=always #{option}HEAD...#{request.head.sha}" # TODO: Refactor into using Request model. print_request_details request puts git_call(diff) print_request_discussions request end
ruby
def show(number, full = false) request = server.get_request_by_number(number) # Determine whether to show full diff or stats only. option = full ? '' : '--stat ' diff = "diff --color=always #{option}HEAD...#{request.head.sha}" # TODO: Refactor into using Request model. print_request_details request puts git_call(diff) print_request_discussions request end
[ "def", "show", "(", "number", ",", "full", "=", "false", ")", "request", "=", "server", ".", "get_request_by_number", "(", "number", ")", "# Determine whether to show full diff or stats only.", "option", "=", "full", "?", "''", ":", "'--stat '", "diff", "=", "\"diff --color=always #{option}HEAD...#{request.head.sha}\"", "# TODO: Refactor into using Request model.", "print_request_details", "request", "puts", "git_call", "(", "diff", ")", "print_request_discussions", "request", "end" ]
Show details for a single request.
[ "Show", "details", "for", "a", "single", "request", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/commands.rb#L27-L36
1,356
b4mboo/git-review
lib/git-review/commands.rb
GitReview.Commands.browse
def browse(number) request = server.get_request_by_number(number) # FIXME: Use request.html_url as soon as we are using our Request model. Launchy.open request._links.html.href end
ruby
def browse(number) request = server.get_request_by_number(number) # FIXME: Use request.html_url as soon as we are using our Request model. Launchy.open request._links.html.href end
[ "def", "browse", "(", "number", ")", "request", "=", "server", ".", "get_request_by_number", "(", "number", ")", "# FIXME: Use request.html_url as soon as we are using our Request model.", "Launchy", ".", "open", "request", ".", "_links", ".", "html", ".", "href", "end" ]
Open a browser window and review a specified request.
[ "Open", "a", "browser", "window", "and", "review", "a", "specified", "request", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/commands.rb#L39-L43
1,357
b4mboo/git-review
lib/git-review/commands.rb
GitReview.Commands.checkout
def checkout(number, branch = true) request = server.get_request_by_number(number) puts 'Checking out changes to your local repository.' puts 'To get back to your original state, just run:' puts puts ' git checkout master'.pink puts # Ensure we are looking at the right remote. remote = local.remote_for_request(request) git_call "fetch #{remote}" # Checkout the right branch. branch_name = request.head.ref if branch if local.branch_exists?(:local, branch_name) if local.source_branch == branch_name puts "On branch #{branch_name}." else git_call "checkout #{branch_name}" end else git_call "checkout --track -b #{branch_name} #{remote}/#{branch_name}" end else git_call "checkout #{remote}/#{branch_name}" end end
ruby
def checkout(number, branch = true) request = server.get_request_by_number(number) puts 'Checking out changes to your local repository.' puts 'To get back to your original state, just run:' puts puts ' git checkout master'.pink puts # Ensure we are looking at the right remote. remote = local.remote_for_request(request) git_call "fetch #{remote}" # Checkout the right branch. branch_name = request.head.ref if branch if local.branch_exists?(:local, branch_name) if local.source_branch == branch_name puts "On branch #{branch_name}." else git_call "checkout #{branch_name}" end else git_call "checkout --track -b #{branch_name} #{remote}/#{branch_name}" end else git_call "checkout #{remote}/#{branch_name}" end end
[ "def", "checkout", "(", "number", ",", "branch", "=", "true", ")", "request", "=", "server", ".", "get_request_by_number", "(", "number", ")", "puts", "'Checking out changes to your local repository.'", "puts", "'To get back to your original state, just run:'", "puts", "puts", "' git checkout master'", ".", "pink", "puts", "# Ensure we are looking at the right remote.", "remote", "=", "local", ".", "remote_for_request", "(", "request", ")", "git_call", "\"fetch #{remote}\"", "# Checkout the right branch.", "branch_name", "=", "request", ".", "head", ".", "ref", "if", "branch", "if", "local", ".", "branch_exists?", "(", ":local", ",", "branch_name", ")", "if", "local", ".", "source_branch", "==", "branch_name", "puts", "\"On branch #{branch_name}.\"", "else", "git_call", "\"checkout #{branch_name}\"", "end", "else", "git_call", "\"checkout --track -b #{branch_name} #{remote}/#{branch_name}\"", "end", "else", "git_call", "\"checkout #{remote}/#{branch_name}\"", "end", "end" ]
Checkout a specified request's changes to your local repository.
[ "Checkout", "a", "specified", "request", "s", "changes", "to", "your", "local", "repository", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/commands.rb#L46-L71
1,358
b4mboo/git-review
lib/git-review/commands.rb
GitReview.Commands.approve
def approve(number) request = server.get_request_by_number(number) repo = server.source_repo # TODO: Make this configurable. comment = 'Reviewed and approved.' response = server.add_comment(repo, request.number, comment) if response[:body] == comment puts 'Successfully approved request.' else puts response[:message] end end
ruby
def approve(number) request = server.get_request_by_number(number) repo = server.source_repo # TODO: Make this configurable. comment = 'Reviewed and approved.' response = server.add_comment(repo, request.number, comment) if response[:body] == comment puts 'Successfully approved request.' else puts response[:message] end end
[ "def", "approve", "(", "number", ")", "request", "=", "server", ".", "get_request_by_number", "(", "number", ")", "repo", "=", "server", ".", "source_repo", "# TODO: Make this configurable.", "comment", "=", "'Reviewed and approved.'", "response", "=", "server", ".", "add_comment", "(", "repo", ",", "request", ".", "number", ",", "comment", ")", "if", "response", "[", ":body", "]", "==", "comment", "puts", "'Successfully approved request.'", "else", "puts", "response", "[", ":message", "]", "end", "end" ]
Add an approving comment to the request.
[ "Add", "an", "approving", "comment", "to", "the", "request", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/commands.rb#L74-L85
1,359
b4mboo/git-review
lib/git-review/commands.rb
GitReview.Commands.merge
def merge(number) request = server.get_request_by_number(number) if request.head.repo message = "Accept request ##{request.number} " + "and merge changes into \"#{local.target}\"" command = "merge -m '#{message}' #{request.head.sha}" puts puts "Request title:" puts " #{request.title}" puts puts "Merge command:" puts " git #{command}" puts puts git_call(command) else print_repo_deleted request end end
ruby
def merge(number) request = server.get_request_by_number(number) if request.head.repo message = "Accept request ##{request.number} " + "and merge changes into \"#{local.target}\"" command = "merge -m '#{message}' #{request.head.sha}" puts puts "Request title:" puts " #{request.title}" puts puts "Merge command:" puts " git #{command}" puts puts git_call(command) else print_repo_deleted request end end
[ "def", "merge", "(", "number", ")", "request", "=", "server", ".", "get_request_by_number", "(", "number", ")", "if", "request", ".", "head", ".", "repo", "message", "=", "\"Accept request ##{request.number} \"", "+", "\"and merge changes into \\\"#{local.target}\\\"\"", "command", "=", "\"merge -m '#{message}' #{request.head.sha}\"", "puts", "puts", "\"Request title:\"", "puts", "\" #{request.title}\"", "puts", "puts", "\"Merge command:\"", "puts", "\" git #{command}\"", "puts", "puts", "git_call", "(", "command", ")", "else", "print_repo_deleted", "request", "end", "end" ]
Accept a specified request by merging it into master.
[ "Accept", "a", "specified", "request", "by", "merging", "it", "into", "master", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/commands.rb#L88-L105
1,360
b4mboo/git-review
lib/git-review/commands.rb
GitReview.Commands.close
def close(number) request = server.get_request_by_number(number) repo = server.source_repo server.close_issue(repo, request.number) unless server.request_exists?('open', request.number) puts 'Successfully closed request.' end end
ruby
def close(number) request = server.get_request_by_number(number) repo = server.source_repo server.close_issue(repo, request.number) unless server.request_exists?('open', request.number) puts 'Successfully closed request.' end end
[ "def", "close", "(", "number", ")", "request", "=", "server", ".", "get_request_by_number", "(", "number", ")", "repo", "=", "server", ".", "source_repo", "server", ".", "close_issue", "(", "repo", ",", "request", ".", "number", ")", "unless", "server", ".", "request_exists?", "(", "'open'", ",", "request", ".", "number", ")", "puts", "'Successfully closed request.'", "end", "end" ]
Close a specified request.
[ "Close", "a", "specified", "request", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/commands.rb#L108-L115
1,361
b4mboo/git-review
lib/git-review/commands.rb
GitReview.Commands.create
def create(upstream = false) # Prepare original_branch and local_branch. # TODO: Allow to use the same switches and parameters that prepare takes. original_branch, local_branch = prepare # Don't create request with uncommitted changes in current branch. if local.uncommitted_changes? puts 'You have uncommitted changes.' puts 'Please stash or commit before creating the request.' return end if local.new_commits?(upstream) # Feature branch differs from local or upstream master. if server.request_exists_for_branch?(upstream) puts 'A pull request already exists for this branch.' puts 'Please update the request directly using `git push`.' return end # Push latest commits to the remote branch (create if necessary). remote = local.remote_for_branch(local_branch) || 'origin' git_call( "push --set-upstream #{remote} #{local_branch}", debug_mode, true ) server.send_pull_request upstream # Return to the user's original branch. git_call "checkout #{original_branch}" else puts 'Nothing to push to remote yet. Commit something first.' end end
ruby
def create(upstream = false) # Prepare original_branch and local_branch. # TODO: Allow to use the same switches and parameters that prepare takes. original_branch, local_branch = prepare # Don't create request with uncommitted changes in current branch. if local.uncommitted_changes? puts 'You have uncommitted changes.' puts 'Please stash or commit before creating the request.' return end if local.new_commits?(upstream) # Feature branch differs from local or upstream master. if server.request_exists_for_branch?(upstream) puts 'A pull request already exists for this branch.' puts 'Please update the request directly using `git push`.' return end # Push latest commits to the remote branch (create if necessary). remote = local.remote_for_branch(local_branch) || 'origin' git_call( "push --set-upstream #{remote} #{local_branch}", debug_mode, true ) server.send_pull_request upstream # Return to the user's original branch. git_call "checkout #{original_branch}" else puts 'Nothing to push to remote yet. Commit something first.' end end
[ "def", "create", "(", "upstream", "=", "false", ")", "# Prepare original_branch and local_branch.", "# TODO: Allow to use the same switches and parameters that prepare takes.", "original_branch", ",", "local_branch", "=", "prepare", "# Don't create request with uncommitted changes in current branch.", "if", "local", ".", "uncommitted_changes?", "puts", "'You have uncommitted changes.'", "puts", "'Please stash or commit before creating the request.'", "return", "end", "if", "local", ".", "new_commits?", "(", "upstream", ")", "# Feature branch differs from local or upstream master.", "if", "server", ".", "request_exists_for_branch?", "(", "upstream", ")", "puts", "'A pull request already exists for this branch.'", "puts", "'Please update the request directly using `git push`.'", "return", "end", "# Push latest commits to the remote branch (create if necessary).", "remote", "=", "local", ".", "remote_for_branch", "(", "local_branch", ")", "||", "'origin'", "git_call", "(", "\"push --set-upstream #{remote} #{local_branch}\"", ",", "debug_mode", ",", "true", ")", "server", ".", "send_pull_request", "upstream", "# Return to the user's original branch.", "git_call", "\"checkout #{original_branch}\"", "else", "puts", "'Nothing to push to remote yet. Commit something first.'", "end", "end" ]
Create a new request.
[ "Create", "a", "new", "request", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/commands.rb#L138-L166
1,362
b4mboo/git-review
lib/git-review/commands.rb
GitReview.Commands.print_repo_deleted
def print_repo_deleted(request) user = request.head.user.login url = request.patch_url puts "Sorry, #{user} deleted the source repository." puts "git-review doesn't support this." puts "Tell the contributor not to do this." puts puts "You can still manually patch your repo by running:" puts puts " curl #{url} | git am" puts end
ruby
def print_repo_deleted(request) user = request.head.user.login url = request.patch_url puts "Sorry, #{user} deleted the source repository." puts "git-review doesn't support this." puts "Tell the contributor not to do this." puts puts "You can still manually patch your repo by running:" puts puts " curl #{url} | git am" puts end
[ "def", "print_repo_deleted", "(", "request", ")", "user", "=", "request", ".", "head", ".", "user", ".", "login", "url", "=", "request", ".", "patch_url", "puts", "\"Sorry, #{user} deleted the source repository.\"", "puts", "\"git-review doesn't support this.\"", "puts", "\"Tell the contributor not to do this.\"", "puts", "puts", "\"You can still manually patch your repo by running:\"", "puts", "puts", "\" curl #{url} | git am\"", "puts", "end" ]
someone deleted the source repo
[ "someone", "deleted", "the", "source", "repo" ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/commands.rb#L258-L269
1,363
b4mboo/git-review
lib/git-review/commands.rb
GitReview.Commands.move_local_changes
def move_local_changes(original_branch, feature_name) feature_branch = create_feature_name(feature_name) # By checking out the feature branch, the commits on the original branch # are copied over. That way we only need to remove pending (local) commits # from the original branch. git_call "checkout -b #{feature_branch}" if local.source_branch == feature_branch # Save any uncommitted changes, to be able to reapply them later. save_uncommitted_changes = local.uncommitted_changes? git_call('stash') if save_uncommitted_changes # Go back to original branch and get rid of pending (local) commits. git_call("checkout #{original_branch}") remote = local.remote_for_branch(original_branch) remote += '/' if remote git_call("reset --hard #{remote}#{original_branch}") git_call("checkout #{feature_branch}") git_call('stash pop') if save_uncommitted_changes feature_branch end end
ruby
def move_local_changes(original_branch, feature_name) feature_branch = create_feature_name(feature_name) # By checking out the feature branch, the commits on the original branch # are copied over. That way we only need to remove pending (local) commits # from the original branch. git_call "checkout -b #{feature_branch}" if local.source_branch == feature_branch # Save any uncommitted changes, to be able to reapply them later. save_uncommitted_changes = local.uncommitted_changes? git_call('stash') if save_uncommitted_changes # Go back to original branch and get rid of pending (local) commits. git_call("checkout #{original_branch}") remote = local.remote_for_branch(original_branch) remote += '/' if remote git_call("reset --hard #{remote}#{original_branch}") git_call("checkout #{feature_branch}") git_call('stash pop') if save_uncommitted_changes feature_branch end end
[ "def", "move_local_changes", "(", "original_branch", ",", "feature_name", ")", "feature_branch", "=", "create_feature_name", "(", "feature_name", ")", "# By checking out the feature branch, the commits on the original branch", "# are copied over. That way we only need to remove pending (local) commits", "# from the original branch.", "git_call", "\"checkout -b #{feature_branch}\"", "if", "local", ".", "source_branch", "==", "feature_branch", "# Save any uncommitted changes, to be able to reapply them later.", "save_uncommitted_changes", "=", "local", ".", "uncommitted_changes?", "git_call", "(", "'stash'", ")", "if", "save_uncommitted_changes", "# Go back to original branch and get rid of pending (local) commits.", "git_call", "(", "\"checkout #{original_branch}\"", ")", "remote", "=", "local", ".", "remote_for_branch", "(", "original_branch", ")", "remote", "+=", "'/'", "if", "remote", "git_call", "(", "\"reset --hard #{remote}#{original_branch}\"", ")", "git_call", "(", "\"checkout #{feature_branch}\"", ")", "git_call", "(", "'stash pop'", ")", "if", "save_uncommitted_changes", "feature_branch", "end", "end" ]
Move uncommitted changes from original_branch to a feature_branch. @return [String] the new local branch uncommitted changes are moved to
[ "Move", "uncommitted", "changes", "from", "original_branch", "to", "a", "feature_branch", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/commands.rb#L285-L304
1,364
dwaite/cookiejar
lib/cookiejar/cookie.rb
CookieJar.Cookie.to_s
def to_s(ver = 0, prefix = true) return "#{name}=#{value}" if ver == 0 # we do not need to encode path; the only characters required to be # quoted must be escaped in URI str = prefix ? "$Version=#{version};" : '' str << "#{name}=#{value};$Path=\"#{path}\"" str << ";$Domain=#{domain}" if domain.start_with? '.' str << ";$Port=\"#{ports.join ','}\"" if ports str end
ruby
def to_s(ver = 0, prefix = true) return "#{name}=#{value}" if ver == 0 # we do not need to encode path; the only characters required to be # quoted must be escaped in URI str = prefix ? "$Version=#{version};" : '' str << "#{name}=#{value};$Path=\"#{path}\"" str << ";$Domain=#{domain}" if domain.start_with? '.' str << ";$Port=\"#{ports.join ','}\"" if ports str end
[ "def", "to_s", "(", "ver", "=", "0", ",", "prefix", "=", "true", ")", "return", "\"#{name}=#{value}\"", "if", "ver", "==", "0", "# we do not need to encode path; the only characters required to be", "# quoted must be escaped in URI", "str", "=", "prefix", "?", "\"$Version=#{version};\"", ":", "''", "str", "<<", "\"#{name}=#{value};$Path=\\\"#{path}\\\"\"", "str", "<<", "\";$Domain=#{domain}\"", "if", "domain", ".", "start_with?", "'.'", "str", "<<", "\";$Port=\\\"#{ports.join ','}\\\"\"", "if", "ports", "str", "end" ]
Returns cookie in a format appropriate to send to a server. @param [FixNum] 0 version, 0 for Netscape-style cookies, 1 for RFC2965-style. @param [Boolean] true prefix, for RFC2965, whether to prefix with "$Version=<version>;". Ignored for Netscape-style cookies
[ "Returns", "cookie", "in", "a", "format", "appropriate", "to", "send", "to", "a", "server", "." ]
c02007c13c93f6a71ae71c2534248a728b2965dd
https://github.com/dwaite/cookiejar/blob/c02007c13c93f6a71ae71c2534248a728b2965dd/lib/cookiejar/cookie.rb#L126-L136
1,365
dwaite/cookiejar
lib/cookiejar/cookie.rb
CookieJar.Cookie.to_hash
def to_hash result = { name: @name, value: @value, domain: @domain, path: @path, created_at: @created_at } { expiry: @expiry, secure: (true if @secure), http_only: (true if @http_only), version: (@version if version != 0), comment: @comment, comment_url: @comment_url, discard: (true if @discard), ports: @ports }.each do |name, value| result[name] = value if value end result end
ruby
def to_hash result = { name: @name, value: @value, domain: @domain, path: @path, created_at: @created_at } { expiry: @expiry, secure: (true if @secure), http_only: (true if @http_only), version: (@version if version != 0), comment: @comment, comment_url: @comment_url, discard: (true if @discard), ports: @ports }.each do |name, value| result[name] = value if value end result end
[ "def", "to_hash", "result", "=", "{", "name", ":", "@name", ",", "value", ":", "@value", ",", "domain", ":", "@domain", ",", "path", ":", "@path", ",", "created_at", ":", "@created_at", "}", "{", "expiry", ":", "@expiry", ",", "secure", ":", "(", "true", "if", "@secure", ")", ",", "http_only", ":", "(", "true", "if", "@http_only", ")", ",", "version", ":", "(", "@version", "if", "version", "!=", "0", ")", ",", "comment", ":", "@comment", ",", "comment_url", ":", "@comment_url", ",", "discard", ":", "(", "true", "if", "@discard", ")", ",", "ports", ":", "@ports", "}", ".", "each", "do", "|", "name", ",", "value", "|", "result", "[", "name", "]", "=", "value", "if", "value", "end", "result", "end" ]
Return a hash representation of the cookie.
[ "Return", "a", "hash", "representation", "of", "the", "cookie", "." ]
c02007c13c93f6a71ae71c2534248a728b2965dd
https://github.com/dwaite/cookiejar/blob/c02007c13c93f6a71ae71c2534248a728b2965dd/lib/cookiejar/cookie.rb#L140-L162
1,366
dwaite/cookiejar
lib/cookiejar/cookie.rb
CookieJar.Cookie.should_send?
def should_send?(request_uri, script) uri = CookieJar::CookieValidation.to_uri request_uri # cookie path must start with the uri, it must not be a secure cookie # being sent over http, and it must not be a http_only cookie sent to # a script path = if uri.path == '' '/' else uri.path end path_match = path.start_with? @path secure_match = !(@secure && uri.scheme == 'http') script_match = !(script && @http_only) expiry_match = !expired? ports_match = ports.nil? || (ports.include? uri.port) path_match && secure_match && script_match && expiry_match && ports_match end
ruby
def should_send?(request_uri, script) uri = CookieJar::CookieValidation.to_uri request_uri # cookie path must start with the uri, it must not be a secure cookie # being sent over http, and it must not be a http_only cookie sent to # a script path = if uri.path == '' '/' else uri.path end path_match = path.start_with? @path secure_match = !(@secure && uri.scheme == 'http') script_match = !(script && @http_only) expiry_match = !expired? ports_match = ports.nil? || (ports.include? uri.port) path_match && secure_match && script_match && expiry_match && ports_match end
[ "def", "should_send?", "(", "request_uri", ",", "script", ")", "uri", "=", "CookieJar", "::", "CookieValidation", ".", "to_uri", "request_uri", "# cookie path must start with the uri, it must not be a secure cookie", "# being sent over http, and it must not be a http_only cookie sent to", "# a script", "path", "=", "if", "uri", ".", "path", "==", "''", "'/'", "else", "uri", ".", "path", "end", "path_match", "=", "path", ".", "start_with?", "@path", "secure_match", "=", "!", "(", "@secure", "&&", "uri", ".", "scheme", "==", "'http'", ")", "script_match", "=", "!", "(", "script", "&&", "@http_only", ")", "expiry_match", "=", "!", "expired?", "ports_match", "=", "ports", ".", "nil?", "||", "(", "ports", ".", "include?", "uri", ".", "port", ")", "path_match", "&&", "secure_match", "&&", "script_match", "&&", "expiry_match", "&&", "ports_match", "end" ]
Determine if a cookie should be sent given a request URI along with other options. This currently ignores domain. @param uri [String, URI] the requested page which may need to receive this cookie @param script [Boolean] indicates that cookies with the 'httponly' extension should be ignored @return [Boolean] whether this cookie should be sent to the server
[ "Determine", "if", "a", "cookie", "should", "be", "sent", "given", "a", "request", "URI", "along", "with", "other", "options", "." ]
c02007c13c93f6a71ae71c2534248a728b2965dd
https://github.com/dwaite/cookiejar/blob/c02007c13c93f6a71ae71c2534248a728b2965dd/lib/cookiejar/cookie.rb#L174-L190
1,367
b4mboo/git-review
lib/git-review/local.rb
GitReview.Local.remotes_with_urls
def remotes_with_urls result = {} git_call('remote -vv').split("\n").each do |line| entries = line.split("\t") remote = entries.first target_entry = entries.last.split(' ') direction = target_entry.last[1..-2].to_sym target_url = target_entry.first result[remote] ||= {} result[remote][direction] = target_url end result end
ruby
def remotes_with_urls result = {} git_call('remote -vv').split("\n").each do |line| entries = line.split("\t") remote = entries.first target_entry = entries.last.split(' ') direction = target_entry.last[1..-2].to_sym target_url = target_entry.first result[remote] ||= {} result[remote][direction] = target_url end result end
[ "def", "remotes_with_urls", "result", "=", "{", "}", "git_call", "(", "'remote -vv'", ")", ".", "split", "(", "\"\\n\"", ")", ".", "each", "do", "|", "line", "|", "entries", "=", "line", ".", "split", "(", "\"\\t\"", ")", "remote", "=", "entries", ".", "first", "target_entry", "=", "entries", ".", "last", ".", "split", "(", "' '", ")", "direction", "=", "target_entry", ".", "last", "[", "1", "..", "-", "2", "]", ".", "to_sym", "target_url", "=", "target_entry", ".", "first", "result", "[", "remote", "]", "||=", "{", "}", "result", "[", "remote", "]", "[", "direction", "]", "=", "target_url", "end", "result", "end" ]
Create a Hash with all remotes as keys and their urls as values.
[ "Create", "a", "Hash", "with", "all", "remotes", "as", "keys", "and", "their", "urls", "as", "values", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/local.rb#L38-L50
1,368
b4mboo/git-review
lib/git-review/local.rb
GitReview.Local.remotes_for_url
def remotes_for_url(remote_url) result = remotes_with_urls.collect do |remote, urls| remote if urls.values.all? { |url| url == remote_url } end result.compact end
ruby
def remotes_for_url(remote_url) result = remotes_with_urls.collect do |remote, urls| remote if urls.values.all? { |url| url == remote_url } end result.compact end
[ "def", "remotes_for_url", "(", "remote_url", ")", "result", "=", "remotes_with_urls", ".", "collect", "do", "|", "remote", ",", "urls", "|", "remote", "if", "urls", ".", "values", ".", "all?", "{", "|", "url", "|", "url", "==", "remote_url", "}", "end", "result", ".", "compact", "end" ]
Collect all remotes for a given url.
[ "Collect", "all", "remotes", "for", "a", "given", "url", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/local.rb#L53-L58
1,369
b4mboo/git-review
lib/git-review/local.rb
GitReview.Local.remote_for_request
def remote_for_request(request) repo_owner = request.head.repo.owner.login remote_url = server.remote_url_for(repo_owner) remotes = remotes_for_url(remote_url) if remotes.empty? remote = "review_#{repo_owner}" git_call("remote add #{remote} #{remote_url}", debug_mode, true) else remote = remotes.first end remote end
ruby
def remote_for_request(request) repo_owner = request.head.repo.owner.login remote_url = server.remote_url_for(repo_owner) remotes = remotes_for_url(remote_url) if remotes.empty? remote = "review_#{repo_owner}" git_call("remote add #{remote} #{remote_url}", debug_mode, true) else remote = remotes.first end remote end
[ "def", "remote_for_request", "(", "request", ")", "repo_owner", "=", "request", ".", "head", ".", "repo", ".", "owner", ".", "login", "remote_url", "=", "server", ".", "remote_url_for", "(", "repo_owner", ")", "remotes", "=", "remotes_for_url", "(", "remote_url", ")", "if", "remotes", ".", "empty?", "remote", "=", "\"review_#{repo_owner}\"", "git_call", "(", "\"remote add #{remote} #{remote_url}\"", ",", "debug_mode", ",", "true", ")", "else", "remote", "=", "remotes", ".", "first", "end", "remote", "end" ]
Find or create the correct remote for a fork with a given owner name.
[ "Find", "or", "create", "the", "correct", "remote", "for", "a", "fork", "with", "a", "given", "owner", "name", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/local.rb#L61-L72
1,370
b4mboo/git-review
lib/git-review/local.rb
GitReview.Local.clean_remotes
def clean_remotes protected_remotes = remotes_for_branches remotes.each do |remote| # Only remove review remotes that aren't referenced by current branches. if remote.index('review_') == 0 && !protected_remotes.include?(remote) git_call "remote remove #{remote}" end end end
ruby
def clean_remotes protected_remotes = remotes_for_branches remotes.each do |remote| # Only remove review remotes that aren't referenced by current branches. if remote.index('review_') == 0 && !protected_remotes.include?(remote) git_call "remote remove #{remote}" end end end
[ "def", "clean_remotes", "protected_remotes", "=", "remotes_for_branches", "remotes", ".", "each", "do", "|", "remote", "|", "# Only remove review remotes that aren't referenced by current branches.", "if", "remote", ".", "index", "(", "'review_'", ")", "==", "0", "&&", "!", "protected_remotes", ".", "include?", "(", "remote", ")", "git_call", "\"remote remove #{remote}\"", "end", "end", "end" ]
Remove obsolete remotes with review prefix.
[ "Remove", "obsolete", "remotes", "with", "review", "prefix", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/local.rb#L75-L83
1,371
b4mboo/git-review
lib/git-review/local.rb
GitReview.Local.remotes_for_branches
def remotes_for_branches remotes = git_call('branch -lvv').gsub('* ', '').split("\n").map do |line| line.split(' ')[2][1..-2].split('/').first end remotes.uniq end
ruby
def remotes_for_branches remotes = git_call('branch -lvv').gsub('* ', '').split("\n").map do |line| line.split(' ')[2][1..-2].split('/').first end remotes.uniq end
[ "def", "remotes_for_branches", "remotes", "=", "git_call", "(", "'branch -lvv'", ")", ".", "gsub", "(", "'* '", ",", "''", ")", ".", "split", "(", "\"\\n\"", ")", ".", "map", "do", "|", "line", "|", "line", ".", "split", "(", "' '", ")", "[", "2", "]", "[", "1", "..", "-", "2", "]", ".", "split", "(", "'/'", ")", ".", "first", "end", "remotes", ".", "uniq", "end" ]
Find all remotes which are currently referenced by local branches.
[ "Find", "all", "remotes", "which", "are", "currently", "referenced", "by", "local", "branches", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/local.rb#L91-L96
1,372
b4mboo/git-review
lib/git-review/local.rb
GitReview.Local.remote_for_branch
def remote_for_branch(branch_name) git_call('branch -lvv').gsub('* ', '').split("\n").each do |line| entries = line.split(' ') next unless entries.first == branch_name # Return the remote name or nil for local branches. match = entries[2].match(%r(\[(.*)(\]|:))) return match[1].split('/').first if match end nil end
ruby
def remote_for_branch(branch_name) git_call('branch -lvv').gsub('* ', '').split("\n").each do |line| entries = line.split(' ') next unless entries.first == branch_name # Return the remote name or nil for local branches. match = entries[2].match(%r(\[(.*)(\]|:))) return match[1].split('/').first if match end nil end
[ "def", "remote_for_branch", "(", "branch_name", ")", "git_call", "(", "'branch -lvv'", ")", ".", "gsub", "(", "'* '", ",", "''", ")", ".", "split", "(", "\"\\n\"", ")", ".", "each", "do", "|", "line", "|", "entries", "=", "line", ".", "split", "(", "' '", ")", "next", "unless", "entries", ".", "first", "==", "branch_name", "# Return the remote name or nil for local branches.", "match", "=", "entries", "[", "2", "]", ".", "match", "(", "%r(", "\\[", "\\]", ")", ")", "return", "match", "[", "1", "]", ".", "split", "(", "'/'", ")", ".", "first", "if", "match", "end", "nil", "end" ]
Finds the correct remote for a given branch name.
[ "Finds", "the", "correct", "remote", "for", "a", "given", "branch", "name", "." ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/local.rb#L99-L108
1,373
b4mboo/git-review
lib/git-review/local.rb
GitReview.Local.clean_single
def clean_single(number, force = false) request = server.pull_request(source_repo, number) if request && request.state == 'closed' # ensure there are no unmerged commits or '--force' flag has been set branch_name = request.head.ref if unmerged_commits?(branch_name) && !force puts "Won't delete branches that contain unmerged commits." puts "Use '--force' to override." else delete_branch(branch_name) end end rescue Octokit::NotFound false end
ruby
def clean_single(number, force = false) request = server.pull_request(source_repo, number) if request && request.state == 'closed' # ensure there are no unmerged commits or '--force' flag has been set branch_name = request.head.ref if unmerged_commits?(branch_name) && !force puts "Won't delete branches that contain unmerged commits." puts "Use '--force' to override." else delete_branch(branch_name) end end rescue Octokit::NotFound false end
[ "def", "clean_single", "(", "number", ",", "force", "=", "false", ")", "request", "=", "server", ".", "pull_request", "(", "source_repo", ",", "number", ")", "if", "request", "&&", "request", ".", "state", "==", "'closed'", "# ensure there are no unmerged commits or '--force' flag has been set", "branch_name", "=", "request", ".", "head", ".", "ref", "if", "unmerged_commits?", "(", "branch_name", ")", "&&", "!", "force", "puts", "\"Won't delete branches that contain unmerged commits.\"", "puts", "\"Use '--force' to override.\"", "else", "delete_branch", "(", "branch_name", ")", "end", "end", "rescue", "Octokit", "::", "NotFound", "false", "end" ]
clean a single request's obsolete branch
[ "clean", "a", "single", "request", "s", "obsolete", "branch" ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/local.rb#L130-L144
1,374
b4mboo/git-review
lib/git-review/local.rb
GitReview.Local.clean_all
def clean_all (review_branches - protected_branches).each do |branch_name| # only clean up obsolete branches. delete_branch(branch_name) unless unmerged_commits?(branch_name, false) end end
ruby
def clean_all (review_branches - protected_branches).each do |branch_name| # only clean up obsolete branches. delete_branch(branch_name) unless unmerged_commits?(branch_name, false) end end
[ "def", "clean_all", "(", "review_branches", "-", "protected_branches", ")", ".", "each", "do", "|", "branch_name", "|", "# only clean up obsolete branches.", "delete_branch", "(", "branch_name", ")", "unless", "unmerged_commits?", "(", "branch_name", ",", "false", ")", "end", "end" ]
clean all obsolete branches
[ "clean", "all", "obsolete", "branches" ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/local.rb#L147-L152
1,375
b4mboo/git-review
lib/git-review/local.rb
GitReview.Local.target_repo
def target_repo(upstream=false) # TODO: Manually override this and set arbitrary repositories if upstream server.repository(source_repo).parent.full_name else source_repo end end
ruby
def target_repo(upstream=false) # TODO: Manually override this and set arbitrary repositories if upstream server.repository(source_repo).parent.full_name else source_repo end end
[ "def", "target_repo", "(", "upstream", "=", "false", ")", "# TODO: Manually override this and set arbitrary repositories", "if", "upstream", "server", ".", "repository", "(", "source_repo", ")", ".", "parent", ".", "full_name", "else", "source_repo", "end", "end" ]
if to send a pull request to upstream repo, get the parent as target @return [String] the name of the target repo
[ "if", "to", "send", "a", "pull", "request", "to", "upstream", "repo", "get", "the", "parent", "as", "target" ]
e9de412ba0bf2a67741f59da98edb64fa923dcd1
https://github.com/b4mboo/git-review/blob/e9de412ba0bf2a67741f59da98edb64fa923dcd1/lib/git-review/local.rb#L267-L274
1,376
dwaite/cookiejar
lib/cookiejar/jar.rb
CookieJar.Jar.set_cookie2
def set_cookie2(request_uri, cookie_header_value) cookie = Cookie.from_set_cookie2 request_uri, cookie_header_value add_cookie cookie end
ruby
def set_cookie2(request_uri, cookie_header_value) cookie = Cookie.from_set_cookie2 request_uri, cookie_header_value add_cookie cookie end
[ "def", "set_cookie2", "(", "request_uri", ",", "cookie_header_value", ")", "cookie", "=", "Cookie", ".", "from_set_cookie2", "request_uri", ",", "cookie_header_value", "add_cookie", "cookie", "end" ]
Given a request URI and a literal Set-Cookie2 header value, attempt to add the cookie to the cookie store. @param [String, URI] request_uri the resource returning the header @param [String] cookie_header_value the contents of the Set-Cookie2 @return [Cookie] which was created and stored @raise [InvalidCookieError] if the cookie header did not validate
[ "Given", "a", "request", "URI", "and", "a", "literal", "Set", "-", "Cookie2", "header", "value", "attempt", "to", "add", "the", "cookie", "to", "the", "cookie", "store", "." ]
c02007c13c93f6a71ae71c2534248a728b2965dd
https://github.com/dwaite/cookiejar/blob/c02007c13c93f6a71ae71c2534248a728b2965dd/lib/cookiejar/jar.rb#L73-L76
1,377
dwaite/cookiejar
lib/cookiejar/jar.rb
CookieJar.Jar.to_a
def to_a result = [] @domains.values.each do |paths| paths.values.each do |cookies| cookies.values.inject result, :<< end end result end
ruby
def to_a result = [] @domains.values.each do |paths| paths.values.each do |cookies| cookies.values.inject result, :<< end end result end
[ "def", "to_a", "result", "=", "[", "]", "@domains", ".", "values", ".", "each", "do", "|", "paths", "|", "paths", ".", "values", ".", "each", "do", "|", "cookies", "|", "cookies", ".", "values", ".", "inject", "result", ",", ":<<", "end", "end", "result", "end" ]
Return an array of all cookie objects in the jar @return [Array<Cookie>] all cookies. Includes any expired cookies which have not yet been removed with expire_cookies
[ "Return", "an", "array", "of", "all", "cookie", "objects", "in", "the", "jar" ]
c02007c13c93f6a71ae71c2534248a728b2965dd
https://github.com/dwaite/cookiejar/blob/c02007c13c93f6a71ae71c2534248a728b2965dd/lib/cookiejar/jar.rb#L136-L144
1,378
dwaite/cookiejar
lib/cookiejar/jar.rb
CookieJar.Jar.expire_cookies
def expire_cookies(session = false) @domains.delete_if do |_domain, paths| paths.delete_if do |_path, cookies| cookies.delete_if do |_cookie_name, cookie| cookie.expired? || (session && cookie.session?) end cookies.empty? end paths.empty? end end
ruby
def expire_cookies(session = false) @domains.delete_if do |_domain, paths| paths.delete_if do |_path, cookies| cookies.delete_if do |_cookie_name, cookie| cookie.expired? || (session && cookie.session?) end cookies.empty? end paths.empty? end end
[ "def", "expire_cookies", "(", "session", "=", "false", ")", "@domains", ".", "delete_if", "do", "|", "_domain", ",", "paths", "|", "paths", ".", "delete_if", "do", "|", "_path", ",", "cookies", "|", "cookies", ".", "delete_if", "do", "|", "_cookie_name", ",", "cookie", "|", "cookie", ".", "expired?", "||", "(", "session", "&&", "cookie", ".", "session?", ")", "end", "cookies", ".", "empty?", "end", "paths", ".", "empty?", "end", "end" ]
Look through the jar for any cookies which have passed their expiration date, or session cookies from a previous session @param session [Boolean] whether session cookies should be expired, or just cookies past their expiration date.
[ "Look", "through", "the", "jar", "for", "any", "cookies", "which", "have", "passed", "their", "expiration", "date", "or", "session", "cookies", "from", "a", "previous", "session" ]
c02007c13c93f6a71ae71c2534248a728b2965dd
https://github.com/dwaite/cookiejar/blob/c02007c13c93f6a71ae71c2534248a728b2965dd/lib/cookiejar/jar.rb#L191-L201
1,379
dwaite/cookiejar
lib/cookiejar/jar.rb
CookieJar.Jar.get_cookies
def get_cookies(request_uri, opts = {}) uri = to_uri request_uri hosts = Cookie.compute_search_domains uri return [] if hosts.nil? path = if uri.path == '' '/' else uri.path end results = [] hosts.each do |host| domain = find_domain host domain.each do |apath, cookies| next unless path.start_with? apath results += cookies.values.select do |cookie| cookie.should_send? uri, opts[:script] end end end # Sort by path length, longest first results.sort do |lhs, rhs| rhs.path.length <=> lhs.path.length end end
ruby
def get_cookies(request_uri, opts = {}) uri = to_uri request_uri hosts = Cookie.compute_search_domains uri return [] if hosts.nil? path = if uri.path == '' '/' else uri.path end results = [] hosts.each do |host| domain = find_domain host domain.each do |apath, cookies| next unless path.start_with? apath results += cookies.values.select do |cookie| cookie.should_send? uri, opts[:script] end end end # Sort by path length, longest first results.sort do |lhs, rhs| rhs.path.length <=> lhs.path.length end end
[ "def", "get_cookies", "(", "request_uri", ",", "opts", "=", "{", "}", ")", "uri", "=", "to_uri", "request_uri", "hosts", "=", "Cookie", ".", "compute_search_domains", "uri", "return", "[", "]", "if", "hosts", ".", "nil?", "path", "=", "if", "uri", ".", "path", "==", "''", "'/'", "else", "uri", ".", "path", "end", "results", "=", "[", "]", "hosts", ".", "each", "do", "|", "host", "|", "domain", "=", "find_domain", "host", "domain", ".", "each", "do", "|", "apath", ",", "cookies", "|", "next", "unless", "path", ".", "start_with?", "apath", "results", "+=", "cookies", ".", "values", ".", "select", "do", "|", "cookie", "|", "cookie", ".", "should_send?", "uri", ",", "opts", "[", ":script", "]", "end", "end", "end", "# Sort by path length, longest first", "results", ".", "sort", "do", "|", "lhs", ",", "rhs", "|", "rhs", ".", "path", ".", "length", "<=>", "lhs", ".", "path", ".", "length", "end", "end" ]
Given a request URI, return a sorted list of Cookie objects. Cookies will be in order per RFC 2965 - sorted by longest path length, but otherwise unordered. @param [String, URI] request_uri the address the HTTP request will be sent to. This must be a full URI, i.e. must include the protocol, if you pass digi.ninja it will fail to find the domain, you must pass http://digi.ninja @param [Hash] opts options controlling returned cookies @option opts [Boolean] :script (false) Cookies marked HTTP-only will be ignored if true @return [Array<Cookie>] cookies which should be sent in the HTTP request
[ "Given", "a", "request", "URI", "return", "a", "sorted", "list", "of", "Cookie", "objects", ".", "Cookies", "will", "be", "in", "order", "per", "RFC", "2965", "-", "sorted", "by", "longest", "path", "length", "but", "otherwise", "unordered", "." ]
c02007c13c93f6a71ae71c2534248a728b2965dd
https://github.com/dwaite/cookiejar/blob/c02007c13c93f6a71ae71c2534248a728b2965dd/lib/cookiejar/jar.rb#L215-L241
1,380
dwaite/cookiejar
lib/cookiejar/jar.rb
CookieJar.Jar.get_cookie_header
def get_cookie_header(request_uri, opts = {}) cookies = get_cookies request_uri, opts ver = [[], []] cookies.each do |cookie| ver[cookie.version] << cookie end if ver[1].empty? # can do a netscape-style cookie header, relish the opportunity cookies.map(&:to_s).join ';' else # build a RFC 2965-style cookie header. Split the cookies into # version 0 and 1 groups so that we can reuse the '$Version' header result = '' unless ver[0].empty? result << '$Version=0;' result << ver[0].map do |cookie| (cookie.to_s 1, false) end.join(';') # separate version 0 and 1 with a comma result << ',' end result << '$Version=1;' ver[1].map do |cookie| result << (cookie.to_s 1, false) end result end end
ruby
def get_cookie_header(request_uri, opts = {}) cookies = get_cookies request_uri, opts ver = [[], []] cookies.each do |cookie| ver[cookie.version] << cookie end if ver[1].empty? # can do a netscape-style cookie header, relish the opportunity cookies.map(&:to_s).join ';' else # build a RFC 2965-style cookie header. Split the cookies into # version 0 and 1 groups so that we can reuse the '$Version' header result = '' unless ver[0].empty? result << '$Version=0;' result << ver[0].map do |cookie| (cookie.to_s 1, false) end.join(';') # separate version 0 and 1 with a comma result << ',' end result << '$Version=1;' ver[1].map do |cookie| result << (cookie.to_s 1, false) end result end end
[ "def", "get_cookie_header", "(", "request_uri", ",", "opts", "=", "{", "}", ")", "cookies", "=", "get_cookies", "request_uri", ",", "opts", "ver", "=", "[", "[", "]", ",", "[", "]", "]", "cookies", ".", "each", "do", "|", "cookie", "|", "ver", "[", "cookie", ".", "version", "]", "<<", "cookie", "end", "if", "ver", "[", "1", "]", ".", "empty?", "# can do a netscape-style cookie header, relish the opportunity", "cookies", ".", "map", "(", ":to_s", ")", ".", "join", "';'", "else", "# build a RFC 2965-style cookie header. Split the cookies into", "# version 0 and 1 groups so that we can reuse the '$Version' header", "result", "=", "''", "unless", "ver", "[", "0", "]", ".", "empty?", "result", "<<", "'$Version=0;'", "result", "<<", "ver", "[", "0", "]", ".", "map", "do", "|", "cookie", "|", "(", "cookie", ".", "to_s", "1", ",", "false", ")", "end", ".", "join", "(", "';'", ")", "# separate version 0 and 1 with a comma", "result", "<<", "','", "end", "result", "<<", "'$Version=1;'", "ver", "[", "1", "]", ".", "map", "do", "|", "cookie", "|", "result", "<<", "(", "cookie", ".", "to_s", "1", ",", "false", ")", "end", "result", "end", "end" ]
Given a request URI, return a string Cookie header.Cookies will be in order per RFC 2965 - sorted by longest path length, but otherwise unordered. @param [String, URI] request_uri the address the HTTP request will be sent to @param [Hash] opts options controlling returned cookies @option opts [Boolean] :script (false) Cookies marked HTTP-only will be ignored if true @return String value of the Cookie header which should be sent on the HTTP request
[ "Given", "a", "request", "URI", "return", "a", "string", "Cookie", "header", ".", "Cookies", "will", "be", "in", "order", "per", "RFC", "2965", "-", "sorted", "by", "longest", "path", "length", "but", "otherwise", "unordered", "." ]
c02007c13c93f6a71ae71c2534248a728b2965dd
https://github.com/dwaite/cookiejar/blob/c02007c13c93f6a71ae71c2534248a728b2965dd/lib/cookiejar/jar.rb#L254-L281
1,381
dkubb/memoizable
lib/memoizable/memory.rb
Memoizable.Memory.[]=
def []=(name, value) memoized = true @memory.compute_if_absent(name) do memoized = false value end fail ArgumentError, "The method #{name} is already memoized" if memoized end
ruby
def []=(name, value) memoized = true @memory.compute_if_absent(name) do memoized = false value end fail ArgumentError, "The method #{name} is already memoized" if memoized end
[ "def", "[]=", "(", "name", ",", "value", ")", "memoized", "=", "true", "@memory", ".", "compute_if_absent", "(", "name", ")", "do", "memoized", "=", "false", "value", "end", "fail", "ArgumentError", ",", "\"The method #{name} is already memoized\"", "if", "memoized", "end" ]
Store the value in memory @param [Symbol] name @param [Object] value @return [undefined] @api public
[ "Store", "the", "value", "in", "memory" ]
fd3a0812bee27b64ecbc80d525e1edc838bd1529
https://github.com/dkubb/memoizable/blob/fd3a0812bee27b64ecbc80d525e1edc838bd1529/lib/memoizable/memory.rb#L42-L49
1,382
bsiggelkow/jsonify
lib/jsonify/builder.rb
Jsonify.Builder.attributes!
def attributes!(object, *attrs) attrs.each do |attr| method_missing attr, object.send(attr) end end
ruby
def attributes!(object, *attrs) attrs.each do |attr| method_missing attr, object.send(attr) end end
[ "def", "attributes!", "(", "object", ",", "*", "attrs", ")", "attrs", ".", "each", "do", "|", "attr", "|", "method_missing", "attr", ",", "object", ".", "send", "(", "attr", ")", "end", "end" ]
Adds a new JsonPair for each attribute in attrs by taking attr as key and value of that attribute in object. @param object [Object] Object to take values from @param *attrs [Array<Symbol>] Array of attributes for JsonPair keys
[ "Adds", "a", "new", "JsonPair", "for", "each", "attribute", "in", "attrs", "by", "taking", "attr", "as", "key", "and", "value", "of", "that", "attribute", "in", "object", "." ]
94b1a371cd730470d2829c144957a5206e3fae74
https://github.com/bsiggelkow/jsonify/blob/94b1a371cd730470d2829c144957a5206e3fae74/lib/jsonify/builder.rb#L63-L67
1,383
bsiggelkow/jsonify
lib/jsonify/builder.rb
Jsonify.Builder.array!
def array!(args) __array args.each do |arg| @level += 1 yield arg @level -= 1 value = @stack.pop # If the object created was an array with a single value # assume that just the value should be added if (JsonArray === value && value.values.length <= 1) value = value.values.first end @stack[@level].add value end end
ruby
def array!(args) __array args.each do |arg| @level += 1 yield arg @level -= 1 value = @stack.pop # If the object created was an array with a single value # assume that just the value should be added if (JsonArray === value && value.values.length <= 1) value = value.values.first end @stack[@level].add value end end
[ "def", "array!", "(", "args", ")", "__array", "args", ".", "each", "do", "|", "arg", "|", "@level", "+=", "1", "yield", "arg", "@level", "-=", "1", "value", "=", "@stack", ".", "pop", "# If the object created was an array with a single value", "# assume that just the value should be added", "if", "(", "JsonArray", "===", "value", "&&", "value", ".", "values", ".", "length", "<=", "1", ")", "value", "=", "value", ".", "values", ".", "first", "end", "@stack", "[", "@level", "]", ".", "add", "value", "end", "end" ]
Creates array of json objects in current element from array passed to this method. Accepts block which yields each array element. @example Create array in root JSON element json.array!(@links) do |link| json.rel link.first json.href link.last end @example compiles to something like ... [ { "rel": "self", "href": "http://example.com/people/123" }, { "rel": "school", "href": "http://gatech.edu" } ]
[ "Creates", "array", "of", "json", "objects", "in", "current", "element", "from", "array", "passed", "to", "this", "method", ".", "Accepts", "block", "which", "yields", "each", "array", "element", "." ]
94b1a371cd730470d2829c144957a5206e3fae74
https://github.com/bsiggelkow/jsonify/blob/94b1a371cd730470d2829c144957a5206e3fae74/lib/jsonify/builder.rb#L131-L148
1,384
arambert/semrush
lib/semrush/report.rb
Semrush.Report.error
def error(text = "") e = /ERROR\s(\d+)\s::\s(.*)/.match(text) || {} name = (e[2] || "UnknownError").titleize code = e[1] || -1 error_class = name.gsub(/\s/, "") if error_class == "NothingFound" [] else begin raise Semrush::Exception.const_get(error_class).new(self, "#{name} (#{code})") rescue raise Semrush::Exception::Base.new(self, "#{name} (#{code}) *** error_class=#{error_class} not implemented ***") end end end
ruby
def error(text = "") e = /ERROR\s(\d+)\s::\s(.*)/.match(text) || {} name = (e[2] || "UnknownError").titleize code = e[1] || -1 error_class = name.gsub(/\s/, "") if error_class == "NothingFound" [] else begin raise Semrush::Exception.const_get(error_class).new(self, "#{name} (#{code})") rescue raise Semrush::Exception::Base.new(self, "#{name} (#{code}) *** error_class=#{error_class} not implemented ***") end end end
[ "def", "error", "(", "text", "=", "\"\"", ")", "e", "=", "/", "\\s", "\\d", "\\s", "\\s", "/", ".", "match", "(", "text", ")", "||", "{", "}", "name", "=", "(", "e", "[", "2", "]", "||", "\"UnknownError\"", ")", ".", "titleize", "code", "=", "e", "[", "1", "]", "||", "-", "1", "error_class", "=", "name", ".", "gsub", "(", "/", "\\s", "/", ",", "\"\"", ")", "if", "error_class", "==", "\"NothingFound\"", "[", "]", "else", "begin", "raise", "Semrush", "::", "Exception", ".", "const_get", "(", "error_class", ")", ".", "new", "(", "self", ",", "\"#{name} (#{code})\"", ")", "rescue", "raise", "Semrush", "::", "Exception", "::", "Base", ".", "new", "(", "self", ",", "\"#{name} (#{code}) *** error_class=#{error_class} not implemented ***\"", ")", "end", "end", "end" ]
Format and raise an error
[ "Format", "and", "raise", "an", "error" ]
2b22a14d430ec0e04c37ce6df5d6852973cc0271
https://github.com/arambert/semrush/blob/2b22a14d430ec0e04c37ce6df5d6852973cc0271/lib/semrush/report.rb#L328-L343
1,385
yujinakayama/astrolabe
lib/astrolabe/node.rb
Astrolabe.Node.each_ancestor
def each_ancestor(*types, &block) return to_enum(__method__, *types) unless block_given? types.flatten! if types.empty? visit_ancestors(&block) else visit_ancestors_with_types(types, &block) end self end
ruby
def each_ancestor(*types, &block) return to_enum(__method__, *types) unless block_given? types.flatten! if types.empty? visit_ancestors(&block) else visit_ancestors_with_types(types, &block) end self end
[ "def", "each_ancestor", "(", "*", "types", ",", "&", "block", ")", "return", "to_enum", "(", "__method__", ",", "types", ")", "unless", "block_given?", "types", ".", "flatten!", "if", "types", ".", "empty?", "visit_ancestors", "(", "block", ")", "else", "visit_ancestors_with_types", "(", "types", ",", "block", ")", "end", "self", "end" ]
Calls the given block for each ancestor node in the order from parent to root. If no block is given, an `Enumerator` is returned. @overload each_ancestor Yield all nodes. @overload each_ancestor(type) Yield only nodes matching the type. @param [Symbol] type a node type @overload each_ancestor(type_a, type_b, ...) Yield only nodes matching any of the types. @param [Symbol] type_a a node type @param [Symbol] type_b a node type @overload each_ancestor(types) Yield only nodes matching any of types in the array. @param [Array<Symbol>] types an array containing node types @yieldparam [Node] node each ancestor node @return [self] if a block is given @return [Enumerator] if no block is given
[ "Calls", "the", "given", "block", "for", "each", "ancestor", "node", "in", "the", "order", "from", "parent", "to", "root", ".", "If", "no", "block", "is", "given", "an", "Enumerator", "is", "returned", "." ]
d7279b21e9fef9f56a48f87ef1403eb5264a9600
https://github.com/yujinakayama/astrolabe/blob/d7279b21e9fef9f56a48f87ef1403eb5264a9600/lib/astrolabe/node.rb#L89-L101
1,386
yujinakayama/astrolabe
lib/astrolabe/node.rb
Astrolabe.Node.each_child_node
def each_child_node(*types) return to_enum(__method__, *types) unless block_given? types.flatten! children.each do |child| next unless child.is_a?(Node) yield child if types.empty? || types.include?(child.type) end self end
ruby
def each_child_node(*types) return to_enum(__method__, *types) unless block_given? types.flatten! children.each do |child| next unless child.is_a?(Node) yield child if types.empty? || types.include?(child.type) end self end
[ "def", "each_child_node", "(", "*", "types", ")", "return", "to_enum", "(", "__method__", ",", "types", ")", "unless", "block_given?", "types", ".", "flatten!", "children", ".", "each", "do", "|", "child", "|", "next", "unless", "child", ".", "is_a?", "(", "Node", ")", "yield", "child", "if", "types", ".", "empty?", "||", "types", ".", "include?", "(", "child", ".", "type", ")", "end", "self", "end" ]
Calls the given block for each child node. If no block is given, an `Enumerator` is returned. Note that this is different from `node.children.each { |child| ... }` which yields all children including non-node element. @overload each_child_node Yield all nodes. @overload each_child_node(type) Yield only nodes matching the type. @param [Symbol] type a node type @overload each_child_node(type_a, type_b, ...) Yield only nodes matching any of the types. @param [Symbol] type_a a node type @param [Symbol] type_b a node type @overload each_child_node(types) Yield only nodes matching any of types in the array. @param [Array<Symbol>] types an array containing node types @yieldparam [Node] node each child node @return [self] if a block is given @return [Enumerator] if no block is given
[ "Calls", "the", "given", "block", "for", "each", "child", "node", ".", "If", "no", "block", "is", "given", "an", "Enumerator", "is", "returned", "." ]
d7279b21e9fef9f56a48f87ef1403eb5264a9600
https://github.com/yujinakayama/astrolabe/blob/d7279b21e9fef9f56a48f87ef1403eb5264a9600/lib/astrolabe/node.rb#L132-L143
1,387
yujinakayama/astrolabe
lib/astrolabe/node.rb
Astrolabe.Node.each_descendant
def each_descendant(*types, &block) return to_enum(__method__, *types) unless block_given? types.flatten! if types.empty? visit_descendants(&block) else visit_descendants_with_types(types, &block) end self end
ruby
def each_descendant(*types, &block) return to_enum(__method__, *types) unless block_given? types.flatten! if types.empty? visit_descendants(&block) else visit_descendants_with_types(types, &block) end self end
[ "def", "each_descendant", "(", "*", "types", ",", "&", "block", ")", "return", "to_enum", "(", "__method__", ",", "types", ")", "unless", "block_given?", "types", ".", "flatten!", "if", "types", ".", "empty?", "visit_descendants", "(", "block", ")", "else", "visit_descendants_with_types", "(", "types", ",", "block", ")", "end", "self", "end" ]
Calls the given block for each descendant node with depth first order. If no block is given, an `Enumerator` is returned. @overload each_descendant Yield all nodes. @overload each_descendant(type) Yield only nodes matching the type. @param [Symbol] type a node type @overload each_descendant(type_a, type_b, ...) Yield only nodes matching any of the types. @param [Symbol] type_a a node type @param [Symbol] type_b a node type @overload each_descendant(types) Yield only nodes matching any of types in the array. @param [Array<Symbol>] types an array containing node types @yieldparam [Node] node each descendant node @return [self] if a block is given @return [Enumerator] if no block is given
[ "Calls", "the", "given", "block", "for", "each", "descendant", "node", "with", "depth", "first", "order", ".", "If", "no", "block", "is", "given", "an", "Enumerator", "is", "returned", "." ]
d7279b21e9fef9f56a48f87ef1403eb5264a9600
https://github.com/yujinakayama/astrolabe/blob/d7279b21e9fef9f56a48f87ef1403eb5264a9600/lib/astrolabe/node.rb#L171-L183
1,388
yujinakayama/astrolabe
lib/astrolabe/node.rb
Astrolabe.Node.each_node
def each_node(*types, &block) return to_enum(__method__, *types) unless block_given? types.flatten! yield self if types.empty? || types.include?(type) if types.empty? visit_descendants(&block) else visit_descendants_with_types(types, &block) end self end
ruby
def each_node(*types, &block) return to_enum(__method__, *types) unless block_given? types.flatten! yield self if types.empty? || types.include?(type) if types.empty? visit_descendants(&block) else visit_descendants_with_types(types, &block) end self end
[ "def", "each_node", "(", "*", "types", ",", "&", "block", ")", "return", "to_enum", "(", "__method__", ",", "types", ")", "unless", "block_given?", "types", ".", "flatten!", "yield", "self", "if", "types", ".", "empty?", "||", "types", ".", "include?", "(", "type", ")", "if", "types", ".", "empty?", "visit_descendants", "(", "block", ")", "else", "visit_descendants_with_types", "(", "types", ",", "block", ")", "end", "self", "end" ]
Calls the given block for the receiver and each descendant node with depth first order. If no block is given, an `Enumerator` is returned. This method would be useful when you treat the receiver node as a root of tree and want to iterate all nodes in the tree. @overload each_node Yield all nodes. @overload each_node(type) Yield only nodes matching the type. @param [Symbol] type a node type @overload each_node(type_a, type_b, ...) Yield only nodes matching any of the types. @param [Symbol] type_a a node type @param [Symbol] type_b a node type @overload each_node(types) Yield only nodes matching any of types in the array. @param [Array<Symbol>] types an array containing node types @yieldparam [Node] node each node @return [self] if a block is given @return [Enumerator] if no block is given
[ "Calls", "the", "given", "block", "for", "the", "receiver", "and", "each", "descendant", "node", "with", "depth", "first", "order", ".", "If", "no", "block", "is", "given", "an", "Enumerator", "is", "returned", "." ]
d7279b21e9fef9f56a48f87ef1403eb5264a9600
https://github.com/yujinakayama/astrolabe/blob/d7279b21e9fef9f56a48f87ef1403eb5264a9600/lib/astrolabe/node.rb#L214-L228
1,389
ging/avatars_for_rails
lib/avatars_for_rails/active_record.rb
AvatarsForRails.ActiveRecord.acts_as_avatarable
def acts_as_avatarable(options = {}) options[:styles] ||= AvatarsForRails.avatarable_styles cattr_accessor :avatarable_options self.avatarable_options = options include AvatarsForRails::Avatarable end
ruby
def acts_as_avatarable(options = {}) options[:styles] ||= AvatarsForRails.avatarable_styles cattr_accessor :avatarable_options self.avatarable_options = options include AvatarsForRails::Avatarable end
[ "def", "acts_as_avatarable", "(", "options", "=", "{", "}", ")", "options", "[", ":styles", "]", "||=", "AvatarsForRails", ".", "avatarable_styles", "cattr_accessor", ":avatarable_options", "self", ".", "avatarable_options", "=", "options", "include", "AvatarsForRails", "::", "Avatarable", "end" ]
Adds an ActiveRecord model with support for avatars
[ "Adds", "an", "ActiveRecord", "model", "with", "support", "for", "avatars" ]
b3621788966a1fa89b855e2ca0425282c80bb7aa
https://github.com/ging/avatars_for_rails/blob/b3621788966a1fa89b855e2ca0425282c80bb7aa/lib/avatars_for_rails/active_record.rb#L4-L11
1,390
dkubb/memoizable
lib/memoizable/method_builder.rb
Memoizable.MethodBuilder.create_memoized_method
def create_memoized_method name, method, freezer = @method_name, @original_method, @freezer @descendant.module_eval do define_method(name) do |&block| fail BlockNotAllowedError.new(self.class, name) if block memoized_method_cache.fetch(name) do freezer.call(method.bind(self).call) end end end end
ruby
def create_memoized_method name, method, freezer = @method_name, @original_method, @freezer @descendant.module_eval do define_method(name) do |&block| fail BlockNotAllowedError.new(self.class, name) if block memoized_method_cache.fetch(name) do freezer.call(method.bind(self).call) end end end end
[ "def", "create_memoized_method", "name", ",", "method", ",", "freezer", "=", "@method_name", ",", "@original_method", ",", "@freezer", "@descendant", ".", "module_eval", "do", "define_method", "(", "name", ")", "do", "|", "&", "block", "|", "fail", "BlockNotAllowedError", ".", "new", "(", "self", ".", "class", ",", "name", ")", "if", "block", "memoized_method_cache", ".", "fetch", "(", "name", ")", "do", "freezer", ".", "call", "(", "method", ".", "bind", "(", "self", ")", ".", "call", ")", "end", "end", "end", "end" ]
Create a new memoized method @return [undefined] @api private
[ "Create", "a", "new", "memoized", "method" ]
fd3a0812bee27b64ecbc80d525e1edc838bd1529
https://github.com/dkubb/memoizable/blob/fd3a0812bee27b64ecbc80d525e1edc838bd1529/lib/memoizable/method_builder.rb#L111-L121
1,391
mikamai/ruby-lol
lib/lol/champion_mastery_request.rb
Lol.ChampionMasteryRequest.all
def all summoner_id: result = perform_request api_url "champion-masteries/by-summoner/#{summoner_id}" result.map { |c| DynamicModel.new c } end
ruby
def all summoner_id: result = perform_request api_url "champion-masteries/by-summoner/#{summoner_id}" result.map { |c| DynamicModel.new c } end
[ "def", "all", "summoner_id", ":", "result", "=", "perform_request", "api_url", "\"champion-masteries/by-summoner/#{summoner_id}\"", "result", ".", "map", "{", "|", "c", "|", "DynamicModel", ".", "new", "c", "}", "end" ]
Get all champion mastery entries sorted by number of champion points descending See: https://developer.riotgames.com/api-methods/#champion-mastery-v3/GET_getAllChampionMasteries @param [Integer] summoner_id Summoner ID associated with the player @return [Array<Lol::DynamicModel>] Champion Masteries
[ "Get", "all", "champion", "mastery", "entries", "sorted", "by", "number", "of", "champion", "points", "descending" ]
0833669a96e803ab34aa1576be5b3c274396dc9b
https://github.com/mikamai/ruby-lol/blob/0833669a96e803ab34aa1576be5b3c274396dc9b/lib/lol/champion_mastery_request.rb#L25-L28
1,392
mikamai/ruby-lol
lib/lol/champion_request.rb
Lol.ChampionRequest.all
def all free_to_play: false result = perform_request api_url("champions", "freeToPlay" => free_to_play) result["champions"].map { |c| DynamicModel.new c } end
ruby
def all free_to_play: false result = perform_request api_url("champions", "freeToPlay" => free_to_play) result["champions"].map { |c| DynamicModel.new c } end
[ "def", "all", "free_to_play", ":", "false", "result", "=", "perform_request", "api_url", "(", "\"champions\"", ",", "\"freeToPlay\"", "=>", "free_to_play", ")", "result", "[", "\"champions\"", "]", ".", "map", "{", "|", "c", "|", "DynamicModel", ".", "new", "c", "}", "end" ]
Retrieve all champions See: https://developer.riotgames.com/api-methods/#champion-v3/GET_getChampions @param free_to_play [Boolean] filter param to retrieve only free to play champions @return [Array<Lol::DynamicModel>] an array of champions
[ "Retrieve", "all", "champions" ]
0833669a96e803ab34aa1576be5b3c274396dc9b
https://github.com/mikamai/ruby-lol/blob/0833669a96e803ab34aa1576be5b3c274396dc9b/lib/lol/champion_request.rb#L11-L14
1,393
contactually/zuora-ruby
lib/zuora/response.rb
Zuora.Response.symbolize_key
def symbolize_key(key) return key unless key.respond_to?(:split) key.split(':').last.underscore.to_sym end
ruby
def symbolize_key(key) return key unless key.respond_to?(:split) key.split(':').last.underscore.to_sym end
[ "def", "symbolize_key", "(", "key", ")", "return", "key", "unless", "key", ".", "respond_to?", "(", ":split", ")", "key", ".", "split", "(", "':'", ")", ".", "last", ".", "underscore", ".", "to_sym", "end" ]
Given a key, convert to symbol, removing XML namespace, if any. @param [String] key - a key, either "abc" or "abc:def" @return [Symbol]
[ "Given", "a", "key", "convert", "to", "symbol", "removing", "XML", "namespace", "if", "any", "." ]
1d64da91babbbe37715591610987ef5d3ac9e3ca
https://github.com/contactually/zuora-ruby/blob/1d64da91babbbe37715591610987ef5d3ac9e3ca/lib/zuora/response.rb#L53-L56
1,394
contactually/zuora-ruby
lib/zuora/response.rb
Zuora.Response.symbolize_keys_deep
def symbolize_keys_deep(hash) return hash unless hash.is_a?(Hash) Hash[hash.map do |key, value| # if value is array, loop each element and recursively symbolize keys if value.is_a? Array value = value.map { |element| symbolize_keys_deep(element) } # if value is hash, recursively symbolize keys elsif value.is_a? Hash value = symbolize_keys_deep(value) end [symbolize_key(key), value] end] end
ruby
def symbolize_keys_deep(hash) return hash unless hash.is_a?(Hash) Hash[hash.map do |key, value| # if value is array, loop each element and recursively symbolize keys if value.is_a? Array value = value.map { |element| symbolize_keys_deep(element) } # if value is hash, recursively symbolize keys elsif value.is_a? Hash value = symbolize_keys_deep(value) end [symbolize_key(key), value] end] end
[ "def", "symbolize_keys_deep", "(", "hash", ")", "return", "hash", "unless", "hash", ".", "is_a?", "(", "Hash", ")", "Hash", "[", "hash", ".", "map", "do", "|", "key", ",", "value", "|", "# if value is array, loop each element and recursively symbolize keys", "if", "value", ".", "is_a?", "Array", "value", "=", "value", ".", "map", "{", "|", "element", "|", "symbolize_keys_deep", "(", "element", ")", "}", "# if value is hash, recursively symbolize keys", "elsif", "value", ".", "is_a?", "Hash", "value", "=", "symbolize_keys_deep", "(", "value", ")", "end", "[", "symbolize_key", "(", "key", ")", ",", "value", "]", "end", "]", "end" ]
Recursively transforms a hash @param [Hash] hash @return [Hash]
[ "Recursively", "transforms", "a", "hash" ]
1d64da91babbbe37715591610987ef5d3ac9e3ca
https://github.com/contactually/zuora-ruby/blob/1d64da91babbbe37715591610987ef5d3ac9e3ca/lib/zuora/response.rb#L61-L75
1,395
contactually/zuora-ruby
lib/zuora/client.rb
Zuora.Client.to_s
def to_s public_vars = instance_variables.reject do |var| INSTANCE_VARIABLE_LOG_BLACKLIST.include? var end public_vars.map! do |var| "#{var}=\"#{instance_variable_get(var)}\"" end public_vars = public_vars.join(' ') "<##{self.class}:#{object_id.to_s(8)} #{public_vars}>" end
ruby
def to_s public_vars = instance_variables.reject do |var| INSTANCE_VARIABLE_LOG_BLACKLIST.include? var end public_vars.map! do |var| "#{var}=\"#{instance_variable_get(var)}\"" end public_vars = public_vars.join(' ') "<##{self.class}:#{object_id.to_s(8)} #{public_vars}>" end
[ "def", "to_s", "public_vars", "=", "instance_variables", ".", "reject", "do", "|", "var", "|", "INSTANCE_VARIABLE_LOG_BLACKLIST", ".", "include?", "var", "end", "public_vars", ".", "map!", "do", "|", "var", "|", "\"#{var}=\\\"#{instance_variable_get(var)}\\\"\"", "end", "public_vars", "=", "public_vars", ".", "join", "(", "' '", ")", "\"<##{self.class}:#{object_id.to_s(8)} #{public_vars}>\"", "end" ]
Like Object.to_s, except excludes BLACKLISTed instance vars
[ "Like", "Object", ".", "to_s", "except", "excludes", "BLACKLISTed", "instance", "vars" ]
1d64da91babbbe37715591610987ef5d3ac9e3ca
https://github.com/contactually/zuora-ruby/blob/1d64da91babbbe37715591610987ef5d3ac9e3ca/lib/zuora/client.rb#L32-L44
1,396
mikamai/ruby-lol
lib/lol/tournament_request.rb
Lol.TournamentRequest.create_tournament
def create_tournament provider_id:, name: nil body = { "providerId" => provider_id, "name" => name }.delete_if do |k, v| v.nil? end perform_request api_url("tournaments"), :post, body end
ruby
def create_tournament provider_id:, name: nil body = { "providerId" => provider_id, "name" => name }.delete_if do |k, v| v.nil? end perform_request api_url("tournaments"), :post, body end
[ "def", "create_tournament", "provider_id", ":", ",", "name", ":", "nil", "body", "=", "{", "\"providerId\"", "=>", "provider_id", ",", "\"name\"", "=>", "name", "}", ".", "delete_if", "do", "|", "k", ",", "v", "|", "v", ".", "nil?", "end", "perform_request", "api_url", "(", "\"tournaments\"", ")", ",", ":post", ",", "body", "end" ]
Creates a tournament and returns its ID. @param [Integer] provider_id The provider ID to specify the regional registered provider data to associate this tournament. @param [String] name Name of the tournament @return [Integer] Tournament ID
[ "Creates", "a", "tournament", "and", "returns", "its", "ID", "." ]
0833669a96e803ab34aa1576be5b3c274396dc9b
https://github.com/mikamai/ruby-lol/blob/0833669a96e803ab34aa1576be5b3c274396dc9b/lib/lol/tournament_request.rb#L28-L33
1,397
mikamai/ruby-lol
lib/lol/tournament_request.rb
Lol.TournamentRequest.create_codes
def create_codes tournament_id:, count: nil, allowed_participants: nil, map_type: "SUMMONERS_RIFT", metadata: nil, team_size: 5, pick_type: "TOURNAMENT_DRAFT", spectator_type: "ALL" body = { "allowedSummonerIds" => allowed_participants, "mapType" => map_type, "metadata" => metadata, "pickType" => pick_type, "spectatorType" => spectator_type, "teamSize" => team_size }.compact uri_params = { "tournamentId" => tournament_id, "count" => count }.compact perform_request api_url("codes", uri_params), :post, body end
ruby
def create_codes tournament_id:, count: nil, allowed_participants: nil, map_type: "SUMMONERS_RIFT", metadata: nil, team_size: 5, pick_type: "TOURNAMENT_DRAFT", spectator_type: "ALL" body = { "allowedSummonerIds" => allowed_participants, "mapType" => map_type, "metadata" => metadata, "pickType" => pick_type, "spectatorType" => spectator_type, "teamSize" => team_size }.compact uri_params = { "tournamentId" => tournament_id, "count" => count }.compact perform_request api_url("codes", uri_params), :post, body end
[ "def", "create_codes", "tournament_id", ":", ",", "count", ":", "nil", ",", "allowed_participants", ":", "nil", ",", "map_type", ":", "\"SUMMONERS_RIFT\"", ",", "metadata", ":", "nil", ",", "team_size", ":", "5", ",", "pick_type", ":", "\"TOURNAMENT_DRAFT\"", ",", "spectator_type", ":", "\"ALL\"", "body", "=", "{", "\"allowedSummonerIds\"", "=>", "allowed_participants", ",", "\"mapType\"", "=>", "map_type", ",", "\"metadata\"", "=>", "metadata", ",", "\"pickType\"", "=>", "pick_type", ",", "\"spectatorType\"", "=>", "spectator_type", ",", "\"teamSize\"", "=>", "team_size", "}", ".", "compact", "uri_params", "=", "{", "\"tournamentId\"", "=>", "tournament_id", ",", "\"count\"", "=>", "count", "}", ".", "compact", "perform_request", "api_url", "(", "\"codes\"", ",", "uri_params", ")", ",", ":post", ",", "body", "end" ]
Create a tournament code for the given tournament. @param [Integer] count The number of codes to create (max 1000) @param [Integer] tournament_id The tournament ID @param [String] spectator_type The spectator type of the game. Valid values are NONE, LOBBYONLY, ALL. @param [Integer] team_size The team size of the game. Valid values are 1-5. @param [String] pick_type The pick type of the game. Valid values are BLIND_PICK, DRAFT_MODE, ALL_RANDOM, TOURNAMENT_DRAFT. @param [String] map_type The map type of the game. Valid values are SUMMONERS_RIFT, TWISTED_TREELINE, CRYSTAL_SCAR, and HOWLING_ABYSS. @param [Array<Integer>] allowed_participants List of participants in order to validate the players eligible to join the lobby. @param [String] metadata Optional string that may contain any data in any format, if specified at all. Used to denote any custom information about the game. @return [Array<String>] generated tournament codes
[ "Create", "a", "tournament", "code", "for", "the", "given", "tournament", "." ]
0833669a96e803ab34aa1576be5b3c274396dc9b
https://github.com/mikamai/ruby-lol/blob/0833669a96e803ab34aa1576be5b3c274396dc9b/lib/lol/tournament_request.rb#L45-L61
1,398
mikamai/ruby-lol
lib/lol/tournament_request.rb
Lol.TournamentRequest.update_code
def update_code tournament_code, allowed_participants: nil, map_type: nil, pick_type: nil, spectator_type: nil body = { "allowedSummonerIds" => allowed_participants, "mapType" => map_type, "pickType" => pick_type, "spectatorType" => spectator_type }.compact perform_request api_url("codes/#{tournament_code}"), :put, body end
ruby
def update_code tournament_code, allowed_participants: nil, map_type: nil, pick_type: nil, spectator_type: nil body = { "allowedSummonerIds" => allowed_participants, "mapType" => map_type, "pickType" => pick_type, "spectatorType" => spectator_type }.compact perform_request api_url("codes/#{tournament_code}"), :put, body end
[ "def", "update_code", "tournament_code", ",", "allowed_participants", ":", "nil", ",", "map_type", ":", "nil", ",", "pick_type", ":", "nil", ",", "spectator_type", ":", "nil", "body", "=", "{", "\"allowedSummonerIds\"", "=>", "allowed_participants", ",", "\"mapType\"", "=>", "map_type", ",", "\"pickType\"", "=>", "pick_type", ",", "\"spectatorType\"", "=>", "spectator_type", "}", ".", "compact", "perform_request", "api_url", "(", "\"codes/#{tournament_code}\"", ")", ",", ":put", ",", "body", "end" ]
Update the pick type, map, spectator type, or allowed summoners for a code. @param [String] tournament_code The tournament code to update @param [Array<Integer>] allowed_participants List of participants in order to validate the players eligible to join the lobby. @param [String] map_type The map type of the game. Valid values are SUMMONERS_RIFT, TWISTED_TREELINE, CRYSTAL_SCAR, and HOWLING_ABYSS. @param [String] pick_type The pick type of the game. Valid values are BLIND_PICK, DRAFT_MODE, ALL_RANDOM, TOURNAMENT_DRAFT. @param [String] spectator_type The spectator type of the game. Valid values are NONE, LOBBYONLY, ALL.
[ "Update", "the", "pick", "type", "map", "spectator", "type", "or", "allowed", "summoners", "for", "a", "code", "." ]
0833669a96e803ab34aa1576be5b3c274396dc9b
https://github.com/mikamai/ruby-lol/blob/0833669a96e803ab34aa1576be5b3c274396dc9b/lib/lol/tournament_request.rb#L69-L77
1,399
mikamai/ruby-lol
lib/lol/tournament_request.rb
Lol.TournamentRequest.all_lobby_events
def all_lobby_events tournament_code: result = perform_request api_url "lobby-events/by-code/#{tournament_code}" result["eventList"].map { |e| DynamicModel.new e } end
ruby
def all_lobby_events tournament_code: result = perform_request api_url "lobby-events/by-code/#{tournament_code}" result["eventList"].map { |e| DynamicModel.new e } end
[ "def", "all_lobby_events", "tournament_code", ":", "result", "=", "perform_request", "api_url", "\"lobby-events/by-code/#{tournament_code}\"", "result", "[", "\"eventList\"", "]", ".", "map", "{", "|", "e", "|", "DynamicModel", ".", "new", "e", "}", "end" ]
Gets a list of lobby events by tournament code @param [String] tournament_code the tournament code string @return [Array<DynamicModel>] List of lobby events
[ "Gets", "a", "list", "of", "lobby", "events", "by", "tournament", "code" ]
0833669a96e803ab34aa1576be5b3c274396dc9b
https://github.com/mikamai/ruby-lol/blob/0833669a96e803ab34aa1576be5b3c274396dc9b/lib/lol/tournament_request.rb#L89-L92