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,800
ThoughtWorksStudios/oauth2_provider
tools/jruby-1.5.1/lib/ruby/1.8/rinda/tuplespace.rb
Rinda.TupleBag.delete
def delete(tuple) key = bin_key(tuple) bin = @hash[key] return nil unless bin bin.delete(tuple) @hash.delete(key) if bin.empty? tuple end
ruby
def delete(tuple) key = bin_key(tuple) bin = @hash[key] return nil unless bin bin.delete(tuple) @hash.delete(key) if bin.empty? tuple end
[ "def", "delete", "(", "tuple", ")", "key", "=", "bin_key", "(", "tuple", ")", "bin", "=", "@hash", "[", "key", "]", "return", "nil", "unless", "bin", "bin", ".", "delete", "(", "tuple", ")", "@hash", ".", "delete", "(", "key", ")", "if", "bin", ".", "empty?", "tuple", "end" ]
Removes +tuple+ from the TupleBag.
[ "Removes", "+", "tuple", "+", "from", "the", "TupleBag", "." ]
d54702f194edd05389968cf8947465860abccc5d
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rinda/tuplespace.rb#L342-L349
1,801
ThoughtWorksStudios/oauth2_provider
tools/jruby-1.5.1/lib/ruby/1.8/rinda/tuplespace.rb
Rinda.TupleBag.find_all
def find_all(template) bin_for_find(template).find_all do |tuple| tuple.alive? && template.match(tuple) end end
ruby
def find_all(template) bin_for_find(template).find_all do |tuple| tuple.alive? && template.match(tuple) end end
[ "def", "find_all", "(", "template", ")", "bin_for_find", "(", "template", ")", ".", "find_all", "do", "|", "tuple", "|", "tuple", ".", "alive?", "&&", "template", ".", "match", "(", "tuple", ")", "end", "end" ]
Finds all live tuples that match +template+.
[ "Finds", "all", "live", "tuples", "that", "match", "+", "template", "+", "." ]
d54702f194edd05389968cf8947465860abccc5d
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rinda/tuplespace.rb#L353-L357
1,802
ThoughtWorksStudios/oauth2_provider
tools/jruby-1.5.1/lib/ruby/1.8/rinda/tuplespace.rb
Rinda.TupleBag.find
def find(template) bin_for_find(template).find do |tuple| tuple.alive? && template.match(tuple) end end
ruby
def find(template) bin_for_find(template).find do |tuple| tuple.alive? && template.match(tuple) end end
[ "def", "find", "(", "template", ")", "bin_for_find", "(", "template", ")", ".", "find", "do", "|", "tuple", "|", "tuple", ".", "alive?", "&&", "template", ".", "match", "(", "tuple", ")", "end", "end" ]
Finds a live tuple that matches +template+.
[ "Finds", "a", "live", "tuple", "that", "matches", "+", "template", "+", "." ]
d54702f194edd05389968cf8947465860abccc5d
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rinda/tuplespace.rb#L362-L366
1,803
ThoughtWorksStudios/oauth2_provider
tools/jruby-1.5.1/lib/ruby/1.8/rinda/tuplespace.rb
Rinda.TupleBag.delete_unless_alive
def delete_unless_alive deleted = [] @hash.each do |key, bin| bin.delete_if do |tuple| if tuple.alive? false else deleted.push(tuple) true end end end deleted end
ruby
def delete_unless_alive deleted = [] @hash.each do |key, bin| bin.delete_if do |tuple| if tuple.alive? false else deleted.push(tuple) true end end end deleted end
[ "def", "delete_unless_alive", "deleted", "=", "[", "]", "@hash", ".", "each", "do", "|", "key", ",", "bin", "|", "bin", ".", "delete_if", "do", "|", "tuple", "|", "if", "tuple", ".", "alive?", "false", "else", "deleted", ".", "push", "(", "tuple", ")", "true", "end", "end", "end", "deleted", "end" ]
Delete tuples which dead tuples from the TupleBag, returning the deleted tuples.
[ "Delete", "tuples", "which", "dead", "tuples", "from", "the", "TupleBag", "returning", "the", "deleted", "tuples", "." ]
d54702f194edd05389968cf8947465860abccc5d
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rinda/tuplespace.rb#L382-L395
1,804
ThoughtWorksStudios/oauth2_provider
tools/jruby-1.5.1/lib/ruby/1.8/rinda/tuplespace.rb
Rinda.TupleSpace.write
def write(tuple, sec=nil) entry = create_entry(tuple, sec) synchronize do if entry.expired? @read_waiter.find_all_template(entry).each do |template| template.read(tuple) end notify_event('write', entry.value) notify_event('delete', entry.value) else @bag.push(entry) start_keeper if entry.expires @read_waiter.find_all_template(entry).each do |template| template.read(tuple) end @take_waiter.find_all_template(entry).each do |template| template.signal end notify_event('write', entry.value) end end entry end
ruby
def write(tuple, sec=nil) entry = create_entry(tuple, sec) synchronize do if entry.expired? @read_waiter.find_all_template(entry).each do |template| template.read(tuple) end notify_event('write', entry.value) notify_event('delete', entry.value) else @bag.push(entry) start_keeper if entry.expires @read_waiter.find_all_template(entry).each do |template| template.read(tuple) end @take_waiter.find_all_template(entry).each do |template| template.signal end notify_event('write', entry.value) end end entry end
[ "def", "write", "(", "tuple", ",", "sec", "=", "nil", ")", "entry", "=", "create_entry", "(", "tuple", ",", "sec", ")", "synchronize", "do", "if", "entry", ".", "expired?", "@read_waiter", ".", "find_all_template", "(", "entry", ")", ".", "each", "do", "|", "template", "|", "template", ".", "read", "(", "tuple", ")", "end", "notify_event", "(", "'write'", ",", "entry", ".", "value", ")", "notify_event", "(", "'delete'", ",", "entry", ".", "value", ")", "else", "@bag", ".", "push", "(", "entry", ")", "start_keeper", "if", "entry", ".", "expires", "@read_waiter", ".", "find_all_template", "(", "entry", ")", ".", "each", "do", "|", "template", "|", "template", ".", "read", "(", "tuple", ")", "end", "@take_waiter", ".", "find_all_template", "(", "entry", ")", ".", "each", "do", "|", "template", "|", "template", ".", "signal", "end", "notify_event", "(", "'write'", ",", "entry", ".", "value", ")", "end", "end", "entry", "end" ]
Creates a new TupleSpace. +period+ is used to control how often to look for dead tuples after modifications to the TupleSpace. If no dead tuples are found +period+ seconds after the last modification, the TupleSpace will stop looking for dead tuples. Adds +tuple+
[ "Creates", "a", "new", "TupleSpace", ".", "+", "period", "+", "is", "used", "to", "control", "how", "often", "to", "look", "for", "dead", "tuples", "after", "modifications", "to", "the", "TupleSpace", "." ]
d54702f194edd05389968cf8947465860abccc5d
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rinda/tuplespace.rb#L451-L473
1,805
ThoughtWorksStudios/oauth2_provider
tools/jruby-1.5.1/lib/ruby/1.8/rinda/tuplespace.rb
Rinda.TupleSpace.move
def move(port, tuple, sec=nil) template = WaitTemplateEntry.new(self, tuple, sec) yield(template) if block_given? synchronize do entry = @bag.find(template) if entry port.push(entry.value) if port @bag.delete(entry) notify_event('take', entry.value) return entry.value end raise RequestExpiredError if template.expired? begin @take_waiter.push(template) start_keeper if template.expires while true raise RequestCanceledError if template.canceled? raise RequestExpiredError if template.expired? entry = @bag.find(template) if entry port.push(entry.value) if port @bag.delete(entry) notify_event('take', entry.value) return entry.value end template.wait end ensure @take_waiter.delete(template) end end end
ruby
def move(port, tuple, sec=nil) template = WaitTemplateEntry.new(self, tuple, sec) yield(template) if block_given? synchronize do entry = @bag.find(template) if entry port.push(entry.value) if port @bag.delete(entry) notify_event('take', entry.value) return entry.value end raise RequestExpiredError if template.expired? begin @take_waiter.push(template) start_keeper if template.expires while true raise RequestCanceledError if template.canceled? raise RequestExpiredError if template.expired? entry = @bag.find(template) if entry port.push(entry.value) if port @bag.delete(entry) notify_event('take', entry.value) return entry.value end template.wait end ensure @take_waiter.delete(template) end end end
[ "def", "move", "(", "port", ",", "tuple", ",", "sec", "=", "nil", ")", "template", "=", "WaitTemplateEntry", ".", "new", "(", "self", ",", "tuple", ",", "sec", ")", "yield", "(", "template", ")", "if", "block_given?", "synchronize", "do", "entry", "=", "@bag", ".", "find", "(", "template", ")", "if", "entry", "port", ".", "push", "(", "entry", ".", "value", ")", "if", "port", "@bag", ".", "delete", "(", "entry", ")", "notify_event", "(", "'take'", ",", "entry", ".", "value", ")", "return", "entry", ".", "value", "end", "raise", "RequestExpiredError", "if", "template", ".", "expired?", "begin", "@take_waiter", ".", "push", "(", "template", ")", "start_keeper", "if", "template", ".", "expires", "while", "true", "raise", "RequestCanceledError", "if", "template", ".", "canceled?", "raise", "RequestExpiredError", "if", "template", ".", "expired?", "entry", "=", "@bag", ".", "find", "(", "template", ")", "if", "entry", "port", ".", "push", "(", "entry", ".", "value", ")", "if", "port", "@bag", ".", "delete", "(", "entry", ")", "notify_event", "(", "'take'", ",", "entry", ".", "value", ")", "return", "entry", ".", "value", "end", "template", ".", "wait", "end", "ensure", "@take_waiter", ".", "delete", "(", "template", ")", "end", "end", "end" ]
Moves +tuple+ to +port+.
[ "Moves", "+", "tuple", "+", "to", "+", "port", "+", "." ]
d54702f194edd05389968cf8947465860abccc5d
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rinda/tuplespace.rb#L485-L517
1,806
ThoughtWorksStudios/oauth2_provider
tools/jruby-1.5.1/lib/ruby/1.8/rinda/tuplespace.rb
Rinda.TupleSpace.read
def read(tuple, sec=nil) template = WaitTemplateEntry.new(self, tuple, sec) yield(template) if block_given? synchronize do entry = @bag.find(template) return entry.value if entry raise RequestExpiredError if template.expired? begin @read_waiter.push(template) start_keeper if template.expires template.wait raise RequestCanceledError if template.canceled? raise RequestExpiredError if template.expired? return template.found ensure @read_waiter.delete(template) end end end
ruby
def read(tuple, sec=nil) template = WaitTemplateEntry.new(self, tuple, sec) yield(template) if block_given? synchronize do entry = @bag.find(template) return entry.value if entry raise RequestExpiredError if template.expired? begin @read_waiter.push(template) start_keeper if template.expires template.wait raise RequestCanceledError if template.canceled? raise RequestExpiredError if template.expired? return template.found ensure @read_waiter.delete(template) end end end
[ "def", "read", "(", "tuple", ",", "sec", "=", "nil", ")", "template", "=", "WaitTemplateEntry", ".", "new", "(", "self", ",", "tuple", ",", "sec", ")", "yield", "(", "template", ")", "if", "block_given?", "synchronize", "do", "entry", "=", "@bag", ".", "find", "(", "template", ")", "return", "entry", ".", "value", "if", "entry", "raise", "RequestExpiredError", "if", "template", ".", "expired?", "begin", "@read_waiter", ".", "push", "(", "template", ")", "start_keeper", "if", "template", ".", "expires", "template", ".", "wait", "raise", "RequestCanceledError", "if", "template", ".", "canceled?", "raise", "RequestExpiredError", "if", "template", ".", "expired?", "return", "template", ".", "found", "ensure", "@read_waiter", ".", "delete", "(", "template", ")", "end", "end", "end" ]
Reads +tuple+, but does not remove it.
[ "Reads", "+", "tuple", "+", "but", "does", "not", "remove", "it", "." ]
d54702f194edd05389968cf8947465860abccc5d
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rinda/tuplespace.rb#L522-L541
1,807
ThoughtWorksStudios/oauth2_provider
tools/jruby-1.5.1/lib/ruby/1.8/rinda/tuplespace.rb
Rinda.TupleSpace.read_all
def read_all(tuple) template = WaitTemplateEntry.new(self, tuple, nil) synchronize do entry = @bag.find_all(template) entry.collect do |e| e.value end end end
ruby
def read_all(tuple) template = WaitTemplateEntry.new(self, tuple, nil) synchronize do entry = @bag.find_all(template) entry.collect do |e| e.value end end end
[ "def", "read_all", "(", "tuple", ")", "template", "=", "WaitTemplateEntry", ".", "new", "(", "self", ",", "tuple", ",", "nil", ")", "synchronize", "do", "entry", "=", "@bag", ".", "find_all", "(", "template", ")", "entry", ".", "collect", "do", "|", "e", "|", "e", ".", "value", "end", "end", "end" ]
Returns all tuples matching +tuple+. Does not remove the found tuples.
[ "Returns", "all", "tuples", "matching", "+", "tuple", "+", ".", "Does", "not", "remove", "the", "found", "tuples", "." ]
d54702f194edd05389968cf8947465860abccc5d
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rinda/tuplespace.rb#L546-L554
1,808
ThoughtWorksStudios/oauth2_provider
tools/jruby-1.5.1/lib/ruby/1.8/rinda/tuplespace.rb
Rinda.TupleSpace.notify
def notify(event, tuple, sec=nil) template = NotifyTemplateEntry.new(self, event, tuple, sec) synchronize do @notify_waiter.push(template) end template end
ruby
def notify(event, tuple, sec=nil) template = NotifyTemplateEntry.new(self, event, tuple, sec) synchronize do @notify_waiter.push(template) end template end
[ "def", "notify", "(", "event", ",", "tuple", ",", "sec", "=", "nil", ")", "template", "=", "NotifyTemplateEntry", ".", "new", "(", "self", ",", "event", ",", "tuple", ",", "sec", ")", "synchronize", "do", "@notify_waiter", ".", "push", "(", "template", ")", "end", "template", "end" ]
Registers for notifications of +event+. Returns a NotifyTemplateEntry. See NotifyTemplateEntry for examples of how to listen for notifications. +event+ can be: 'write':: A tuple was added 'take':: A tuple was taken or moved 'delete':: A tuple was lost after being overwritten or expiring The TupleSpace will also notify you of the 'close' event when the NotifyTemplateEntry has expired.
[ "Registers", "for", "notifications", "of", "+", "event", "+", ".", "Returns", "a", "NotifyTemplateEntry", ".", "See", "NotifyTemplateEntry", "for", "examples", "of", "how", "to", "listen", "for", "notifications", "." ]
d54702f194edd05389968cf8947465860abccc5d
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rinda/tuplespace.rb#L568-L574
1,809
ThoughtWorksStudios/oauth2_provider
tools/jruby-1.5.1/lib/ruby/1.8/rinda/tuplespace.rb
Rinda.TupleSpace.keep_clean
def keep_clean synchronize do @read_waiter.delete_unless_alive.each do |e| e.signal end @take_waiter.delete_unless_alive.each do |e| e.signal end @notify_waiter.delete_unless_alive.each do |e| e.notify(['close']) end @bag.delete_unless_alive.each do |e| notify_event('delete', e.value) end end end
ruby
def keep_clean synchronize do @read_waiter.delete_unless_alive.each do |e| e.signal end @take_waiter.delete_unless_alive.each do |e| e.signal end @notify_waiter.delete_unless_alive.each do |e| e.notify(['close']) end @bag.delete_unless_alive.each do |e| notify_event('delete', e.value) end end end
[ "def", "keep_clean", "synchronize", "do", "@read_waiter", ".", "delete_unless_alive", ".", "each", "do", "|", "e", "|", "e", ".", "signal", "end", "@take_waiter", ".", "delete_unless_alive", ".", "each", "do", "|", "e", "|", "e", ".", "signal", "end", "@notify_waiter", ".", "delete_unless_alive", ".", "each", "do", "|", "e", "|", "e", ".", "notify", "(", "[", "'close'", "]", ")", "end", "@bag", ".", "delete_unless_alive", ".", "each", "do", "|", "e", "|", "notify_event", "(", "'delete'", ",", "e", ".", "value", ")", "end", "end", "end" ]
Removes dead tuples.
[ "Removes", "dead", "tuples", "." ]
d54702f194edd05389968cf8947465860abccc5d
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rinda/tuplespace.rb#L585-L600
1,810
ThoughtWorksStudios/oauth2_provider
tools/jruby-1.5.1/lib/ruby/1.8/rinda/tuplespace.rb
Rinda.TupleSpace.notify_event
def notify_event(event, tuple) ev = [event, tuple] @notify_waiter.find_all_template(ev).each do |template| template.notify(ev) end end
ruby
def notify_event(event, tuple) ev = [event, tuple] @notify_waiter.find_all_template(ev).each do |template| template.notify(ev) end end
[ "def", "notify_event", "(", "event", ",", "tuple", ")", "ev", "=", "[", "event", ",", "tuple", "]", "@notify_waiter", ".", "find_all_template", "(", "ev", ")", ".", "each", "do", "|", "template", "|", "template", ".", "notify", "(", "ev", ")", "end", "end" ]
Notifies all registered listeners for +event+ of a status change of +tuple+.
[ "Notifies", "all", "registered", "listeners", "for", "+", "event", "+", "of", "a", "status", "change", "of", "+", "tuple", "+", "." ]
d54702f194edd05389968cf8947465860abccc5d
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rinda/tuplespace.rb#L606-L611
1,811
bjoernalbers/aruba-doubles
lib/aruba-doubles/history.rb
ArubaDoubles.History.to_pretty
def to_pretty to_a.each_with_index.map { |e,i| "%5d %s" % [i+1, e.shelljoin] }.join("\n") end
ruby
def to_pretty to_a.each_with_index.map { |e,i| "%5d %s" % [i+1, e.shelljoin] }.join("\n") end
[ "def", "to_pretty", "to_a", ".", "each_with_index", ".", "map", "{", "|", "e", ",", "i", "|", "\"%5d %s\"", "%", "[", "i", "+", "1", ",", "e", ".", "shelljoin", "]", "}", ".", "join", "(", "\"\\n\"", ")", "end" ]
Return entries just like running `history` in your shell. @return [String] pretty representation of the entries
[ "Return", "entries", "just", "like", "running", "history", "in", "your", "shell", "." ]
5e835bf60fef4bdf903c225a7c29968d17899516
https://github.com/bjoernalbers/aruba-doubles/blob/5e835bf60fef4bdf903c225a7c29968d17899516/lib/aruba-doubles/history.rb#L34-L36
1,812
benton/fog_tracker
lib/fog_tracker/collection_tracker.rb
FogTracker.CollectionTracker.update
def update new_collection = Array.new fog_collection = @account_tracker.connection.send(@type) || Array.new @log.info "Fetching #{fog_collection.count} #{@type} on #{@account_name}." # Here's where most of the network overhead is actually incurred fog_collection.each do |resource| @log.debug "Fetching resource: #{resource.class} #{resource.identity}" resource._fog_collection_tracker = self new_collection << resource #@log.debug "Got resource: #{resource.inspect}" end @log.info "Fetched #{new_collection.count} #{@type} on #{@account_name}." @collection = new_collection end
ruby
def update new_collection = Array.new fog_collection = @account_tracker.connection.send(@type) || Array.new @log.info "Fetching #{fog_collection.count} #{@type} on #{@account_name}." # Here's where most of the network overhead is actually incurred fog_collection.each do |resource| @log.debug "Fetching resource: #{resource.class} #{resource.identity}" resource._fog_collection_tracker = self new_collection << resource #@log.debug "Got resource: #{resource.inspect}" end @log.info "Fetched #{new_collection.count} #{@type} on #{@account_name}." @collection = new_collection end
[ "def", "update", "new_collection", "=", "Array", ".", "new", "fog_collection", "=", "@account_tracker", ".", "connection", ".", "send", "(", "@type", ")", "||", "Array", ".", "new", "@log", ".", "info", "\"Fetching #{fog_collection.count} #{@type} on #{@account_name}.\"", "# Here's where most of the network overhead is actually incurred", "fog_collection", ".", "each", "do", "|", "resource", "|", "@log", ".", "debug", "\"Fetching resource: #{resource.class} #{resource.identity}\"", "resource", ".", "_fog_collection_tracker", "=", "self", "new_collection", "<<", "resource", "#@log.debug \"Got resource: #{resource.inspect}\"", "end", "@log", ".", "info", "\"Fetched #{new_collection.count} #{@type} on #{@account_name}.\"", "@collection", "=", "new_collection", "end" ]
Creates an object for tracking a single Fog collection in a single account @param [String] resource_type the Fog collection name for this resource type @param [AccountTracker] account_tracker the AccountTracker for this tracker's account. Usually the AccountTracker that created this object Polls the {AccountTracker}'s connection for updated info on all existing instances of this tracker's resource_type
[ "Creates", "an", "object", "for", "tracking", "a", "single", "Fog", "collection", "in", "a", "single", "account" ]
73fdf35dd76ff1b1fc448698f2761ebfbea52e0e
https://github.com/benton/fog_tracker/blob/73fdf35dd76ff1b1fc448698f2761ebfbea52e0e/lib/fog_tracker/collection_tracker.rb#L26-L39
1,813
benton/fog_tracker
lib/fog_tracker/account_tracker.rb
FogTracker.AccountTracker.start
def start if not running? @log.debug "Starting tracking for account #{@name}..." @timer = Thread.new do begin while true update ; sleep @delay end rescue Exception => e sleep @delay ; retry end end else @log.info "Already tracking account #{@name}" end end
ruby
def start if not running? @log.debug "Starting tracking for account #{@name}..." @timer = Thread.new do begin while true update ; sleep @delay end rescue Exception => e sleep @delay ; retry end end else @log.info "Already tracking account #{@name}" end end
[ "def", "start", "if", "not", "running?", "@log", ".", "debug", "\"Starting tracking for account #{@name}...\"", "@timer", "=", "Thread", ".", "new", "do", "begin", "while", "true", "update", ";", "sleep", "@delay", "end", "rescue", "Exception", "=>", "e", "sleep", "@delay", ";", "retry", "end", "end", "else", "@log", ".", "info", "\"Already tracking account #{@name}\"", "end", "end" ]
Creates an object for tracking all collections in a single Fog account @param [String] account_name a human-readable name for the account @param [Hash] account a Hash of account configuration data @param [Hash] options optional additional parameters: - :delay (Integer) - Default time between polling of accounts - :callback (Proc) - A Method or Proc to call each time an account is polled. (should take an Array of resources as its only required parameter) - :error_callback (Proc) - A Method or Proc to call if polling errors occur. (should take a single Exception as its only required parameter) - :logger - a Ruby Logger-compatible object Starts a background thread, which periodically polls for all the resource collections for this tracker's account
[ "Creates", "an", "object", "for", "tracking", "all", "collections", "in", "a", "single", "Fog", "account" ]
73fdf35dd76ff1b1fc448698f2761ebfbea52e0e
https://github.com/benton/fog_tracker/blob/73fdf35dd76ff1b1fc448698f2761ebfbea52e0e/lib/fog_tracker/account_tracker.rb#L43-L58
1,814
benton/fog_tracker
lib/fog_tracker/account_tracker.rb
FogTracker.AccountTracker.update
def update begin @log.info "Polling account #{@name}..." @collection_trackers.each {|tracker| tracker.update} @preceeding_update_time = @most_recent_update @most_recent_update = Time.now @log.info "Polled account #{@name}" @callback.call(all_resources) if @callback rescue Exception => e @log.error "Exception polling account #{name}: #{e.message}" e.backtrace.each {|line| @log.debug line} @error_proc.call(e) if @error_proc raise e end end
ruby
def update begin @log.info "Polling account #{@name}..." @collection_trackers.each {|tracker| tracker.update} @preceeding_update_time = @most_recent_update @most_recent_update = Time.now @log.info "Polled account #{@name}" @callback.call(all_resources) if @callback rescue Exception => e @log.error "Exception polling account #{name}: #{e.message}" e.backtrace.each {|line| @log.debug line} @error_proc.call(e) if @error_proc raise e end end
[ "def", "update", "begin", "@log", ".", "info", "\"Polling account #{@name}...\"", "@collection_trackers", ".", "each", "{", "|", "tracker", "|", "tracker", ".", "update", "}", "@preceeding_update_time", "=", "@most_recent_update", "@most_recent_update", "=", "Time", ".", "now", "@log", ".", "info", "\"Polled account #{@name}\"", "@callback", ".", "call", "(", "all_resources", ")", "if", "@callback", "rescue", "Exception", "=>", "e", "@log", ".", "error", "\"Exception polling account #{name}: #{e.message}\"", "e", ".", "backtrace", ".", "each", "{", "|", "line", "|", "@log", ".", "debug", "line", "}", "@error_proc", ".", "call", "(", "e", ")", "if", "@error_proc", "raise", "e", "end", "end" ]
Polls once for all the resource collections for this tracker's account
[ "Polls", "once", "for", "all", "the", "resource", "collections", "for", "this", "tracker", "s", "account" ]
73fdf35dd76ff1b1fc448698f2761ebfbea52e0e
https://github.com/benton/fog_tracker/blob/73fdf35dd76ff1b1fc448698f2761ebfbea52e0e/lib/fog_tracker/account_tracker.rb#L72-L86
1,815
CORE4/fulmar-shell
lib/fulmar/shell.rb
Fulmar.Shell.execute_quiet
def execute_quiet(command, error_message) # Ladies and gentleman: More debug, please! puts command if @debug return_value = -1 Open3.popen3(environment, command) do |_stdin, stdout, stderr, wait_thread| Thread.new do stdout.each do |line| @last_output << line.strip puts line unless @quiet end end Thread.new do stderr.each do |line| @last_error << line puts line unless @quiet end end _stdin.close return_value = wait_thread.value if @strict and return_value.exitstatus != 0 dump_error_message(command) fail error_message end end puts "Program exited with status #{return_value.exitstatus}." if @debug return_value.exitstatus == 0 end
ruby
def execute_quiet(command, error_message) # Ladies and gentleman: More debug, please! puts command if @debug return_value = -1 Open3.popen3(environment, command) do |_stdin, stdout, stderr, wait_thread| Thread.new do stdout.each do |line| @last_output << line.strip puts line unless @quiet end end Thread.new do stderr.each do |line| @last_error << line puts line unless @quiet end end _stdin.close return_value = wait_thread.value if @strict and return_value.exitstatus != 0 dump_error_message(command) fail error_message end end puts "Program exited with status #{return_value.exitstatus}." if @debug return_value.exitstatus == 0 end
[ "def", "execute_quiet", "(", "command", ",", "error_message", ")", "# Ladies and gentleman: More debug, please!", "puts", "command", "if", "@debug", "return_value", "=", "-", "1", "Open3", ".", "popen3", "(", "environment", ",", "command", ")", "do", "|", "_stdin", ",", "stdout", ",", "stderr", ",", "wait_thread", "|", "Thread", ".", "new", "do", "stdout", ".", "each", "do", "|", "line", "|", "@last_output", "<<", "line", ".", "strip", "puts", "line", "unless", "@quiet", "end", "end", "Thread", ".", "new", "do", "stderr", ".", "each", "do", "|", "line", "|", "@last_error", "<<", "line", "puts", "line", "unless", "@quiet", "end", "end", "_stdin", ".", "close", "return_value", "=", "wait_thread", ".", "value", "if", "@strict", "and", "return_value", ".", "exitstatus", "!=", "0", "dump_error_message", "(", "command", ")", "fail", "error_message", "end", "end", "puts", "\"Program exited with status #{return_value.exitstatus}.\"", "if", "@debug", "return_value", ".", "exitstatus", "==", "0", "end" ]
Run the command and capture the output
[ "Run", "the", "command", "and", "capture", "the", "output" ]
0c26bf98f86e99eeaa022410d4ab3a75b2283078
https://github.com/CORE4/fulmar-shell/blob/0c26bf98f86e99eeaa022410d4ab3a75b2283078/lib/fulmar/shell.rb#L124-L157
1,816
jphager2/mangdown
lib/mangdown/client.rb
Mangdown.Client.cbz
def cbz(dir) Mangdown::CBZ.all(dir) rescue StandardError => error raise Mangdown::Error, "Failed to package #{dir}: #{error.message}" end
ruby
def cbz(dir) Mangdown::CBZ.all(dir) rescue StandardError => error raise Mangdown::Error, "Failed to package #{dir}: #{error.message}" end
[ "def", "cbz", "(", "dir", ")", "Mangdown", "::", "CBZ", ".", "all", "(", "dir", ")", "rescue", "StandardError", "=>", "error", "raise", "Mangdown", "::", "Error", ",", "\"Failed to package #{dir}: #{error.message}\"", "end" ]
cbz all subdirectories in a directory
[ "cbz", "all", "subdirectories", "in", "a", "directory" ]
d57050f486b92873ca96a15cd20cbc1f468f2a61
https://github.com/jphager2/mangdown/blob/d57050f486b92873ca96a15cd20cbc1f468f2a61/lib/mangdown/client.rb#L26-L30
1,817
akhoury6/rbcli
lib/rbcli/util/trollop.rb
Trollop.Parser.each_arg
def each_arg(args) remains = [] i = 0 until i >= args.length return remains += args[i..-1] if @stop_words.member? args[i] case args[i] when /^--$/ # arg terminator return remains += args[(i + 1)..-1] when /^--(\S+?)=(.*)$/ # long argument with equals num_params_taken = yield "--#{$1}", [$2] if num_params_taken.nil? remains << args[i] if @stop_on_unknown return remains += args[i + 1..-1] end end i += 1 when /^--(\S+)$/ # long argument params = collect_argument_parameters(args, i + 1) num_params_taken = yield args[i], params if num_params_taken.nil? remains << args[i] if @stop_on_unknown return remains += args[i + 1..-1] end else i += num_params_taken end i += 1 when /^-(\S+)$/ # one or more short arguments short_remaining = "" shortargs = $1.split(//) shortargs.each_with_index do |a, j| if j == (shortargs.length - 1) params = collect_argument_parameters(args, i + 1) num_params_taken = yield "-#{a}", params unless num_params_taken short_remaining << a if @stop_on_unknown remains << "-#{short_remaining}" return remains += args[i + 1..-1] end else i += num_params_taken end else unless yield "-#{a}", [] short_remaining << a if @stop_on_unknown short_remaining += shortargs[j + 1..-1].join remains << "-#{short_remaining}" return remains += args[i + 1..-1] end end end end unless short_remaining.empty? remains << "-#{short_remaining}" end i += 1 else if @stop_on_unknown return remains += args[i..-1] else remains << args[i] i += 1 end end end remains end
ruby
def each_arg(args) remains = [] i = 0 until i >= args.length return remains += args[i..-1] if @stop_words.member? args[i] case args[i] when /^--$/ # arg terminator return remains += args[(i + 1)..-1] when /^--(\S+?)=(.*)$/ # long argument with equals num_params_taken = yield "--#{$1}", [$2] if num_params_taken.nil? remains << args[i] if @stop_on_unknown return remains += args[i + 1..-1] end end i += 1 when /^--(\S+)$/ # long argument params = collect_argument_parameters(args, i + 1) num_params_taken = yield args[i], params if num_params_taken.nil? remains << args[i] if @stop_on_unknown return remains += args[i + 1..-1] end else i += num_params_taken end i += 1 when /^-(\S+)$/ # one or more short arguments short_remaining = "" shortargs = $1.split(//) shortargs.each_with_index do |a, j| if j == (shortargs.length - 1) params = collect_argument_parameters(args, i + 1) num_params_taken = yield "-#{a}", params unless num_params_taken short_remaining << a if @stop_on_unknown remains << "-#{short_remaining}" return remains += args[i + 1..-1] end else i += num_params_taken end else unless yield "-#{a}", [] short_remaining << a if @stop_on_unknown short_remaining += shortargs[j + 1..-1].join remains << "-#{short_remaining}" return remains += args[i + 1..-1] end end end end unless short_remaining.empty? remains << "-#{short_remaining}" end i += 1 else if @stop_on_unknown return remains += args[i..-1] else remains << args[i] i += 1 end end end remains end
[ "def", "each_arg", "(", "args", ")", "remains", "=", "[", "]", "i", "=", "0", "until", "i", ">=", "args", ".", "length", "return", "remains", "+=", "args", "[", "i", "..", "-", "1", "]", "if", "@stop_words", ".", "member?", "args", "[", "i", "]", "case", "args", "[", "i", "]", "when", "/", "/", "# arg terminator", "return", "remains", "+=", "args", "[", "(", "i", "+", "1", ")", "..", "-", "1", "]", "when", "/", "\\S", "/", "# long argument with equals", "num_params_taken", "=", "yield", "\"--#{$1}\"", ",", "[", "$2", "]", "if", "num_params_taken", ".", "nil?", "remains", "<<", "args", "[", "i", "]", "if", "@stop_on_unknown", "return", "remains", "+=", "args", "[", "i", "+", "1", "..", "-", "1", "]", "end", "end", "i", "+=", "1", "when", "/", "\\S", "/", "# long argument", "params", "=", "collect_argument_parameters", "(", "args", ",", "i", "+", "1", ")", "num_params_taken", "=", "yield", "args", "[", "i", "]", ",", "params", "if", "num_params_taken", ".", "nil?", "remains", "<<", "args", "[", "i", "]", "if", "@stop_on_unknown", "return", "remains", "+=", "args", "[", "i", "+", "1", "..", "-", "1", "]", "end", "else", "i", "+=", "num_params_taken", "end", "i", "+=", "1", "when", "/", "\\S", "/", "# one or more short arguments", "short_remaining", "=", "\"\"", "shortargs", "=", "$1", ".", "split", "(", "/", "/", ")", "shortargs", ".", "each_with_index", "do", "|", "a", ",", "j", "|", "if", "j", "==", "(", "shortargs", ".", "length", "-", "1", ")", "params", "=", "collect_argument_parameters", "(", "args", ",", "i", "+", "1", ")", "num_params_taken", "=", "yield", "\"-#{a}\"", ",", "params", "unless", "num_params_taken", "short_remaining", "<<", "a", "if", "@stop_on_unknown", "remains", "<<", "\"-#{short_remaining}\"", "return", "remains", "+=", "args", "[", "i", "+", "1", "..", "-", "1", "]", "end", "else", "i", "+=", "num_params_taken", "end", "else", "unless", "yield", "\"-#{a}\"", ",", "[", "]", "short_remaining", "<<", "a", "if", "@stop_on_unknown", "short_remaining", "+=", "shortargs", "[", "j", "+", "1", "..", "-", "1", "]", ".", "join", "remains", "<<", "\"-#{short_remaining}\"", "return", "remains", "+=", "args", "[", "i", "+", "1", "..", "-", "1", "]", "end", "end", "end", "end", "unless", "short_remaining", ".", "empty?", "remains", "<<", "\"-#{short_remaining}\"", "end", "i", "+=", "1", "else", "if", "@stop_on_unknown", "return", "remains", "+=", "args", "[", "i", "..", "-", "1", "]", "else", "remains", "<<", "args", "[", "i", "]", "i", "+=", "1", "end", "end", "end", "remains", "end" ]
yield successive arg, parameter pairs
[ "yield", "successive", "arg", "parameter", "pairs" ]
eb8c71af7003059bb1686f89b9204139a537c10d
https://github.com/akhoury6/rbcli/blob/eb8c71af7003059bb1686f89b9204139a537c10d/lib/rbcli/util/trollop.rb#L454-L529
1,818
awexome/doesfacebook
lib/doesfacebook/controller_extensions.rb
DoesFacebook.ControllerExtensions.parse_signed_request
def parse_signed_request Rails.logger.info " Facebook application \"#{fb_app.namespace}\" configuration in use for this request." if request_parameter = request.params["signed_request"] encoded_signature, encoded_data = request_parameter.split(".") decoded_signature = base64_url_decode(encoded_signature) decoded_data = base64_url_decode(encoded_data) @fbparams = HashWithIndifferentAccess.new(JSON.parse(decoded_data)) Rails.logger.info " Facebook Parameters: #{fbparams.inspect}" end end
ruby
def parse_signed_request Rails.logger.info " Facebook application \"#{fb_app.namespace}\" configuration in use for this request." if request_parameter = request.params["signed_request"] encoded_signature, encoded_data = request_parameter.split(".") decoded_signature = base64_url_decode(encoded_signature) decoded_data = base64_url_decode(encoded_data) @fbparams = HashWithIndifferentAccess.new(JSON.parse(decoded_data)) Rails.logger.info " Facebook Parameters: #{fbparams.inspect}" end end
[ "def", "parse_signed_request", "Rails", ".", "logger", ".", "info", "\" Facebook application \\\"#{fb_app.namespace}\\\" configuration in use for this request.\"", "if", "request_parameter", "=", "request", ".", "params", "[", "\"signed_request\"", "]", "encoded_signature", ",", "encoded_data", "=", "request_parameter", ".", "split", "(", "\".\"", ")", "decoded_signature", "=", "base64_url_decode", "(", "encoded_signature", ")", "decoded_data", "=", "base64_url_decode", "(", "encoded_data", ")", "@fbparams", "=", "HashWithIndifferentAccess", ".", "new", "(", "JSON", ".", "parse", "(", "decoded_data", ")", ")", "Rails", ".", "logger", ".", "info", "\" Facebook Parameters: #{fbparams.inspect}\"", "end", "end" ]
If present, parses data from the signed request and inserts it into the fbparams object for use during requests
[ "If", "present", "parses", "data", "from", "the", "signed", "request", "and", "inserts", "it", "into", "the", "fbparams", "object", "for", "use", "during", "requests" ]
fcd4c5daaf7362920c103c825c24ca64c4adf13a
https://github.com/awexome/doesfacebook/blob/fcd4c5daaf7362920c103c825c24ca64c4adf13a/lib/doesfacebook/controller_extensions.rb#L79-L88
1,819
elektronaut/dis
lib/dis/layer.rb
Dis.Layer.store
def store(type, hash, file) raise Dis::Errors::ReadOnlyError if readonly? store!(type, hash, file) end
ruby
def store(type, hash, file) raise Dis::Errors::ReadOnlyError if readonly? store!(type, hash, file) end
[ "def", "store", "(", "type", ",", "hash", ",", "file", ")", "raise", "Dis", "::", "Errors", "::", "ReadOnlyError", "if", "readonly?", "store!", "(", "type", ",", "hash", ",", "file", ")", "end" ]
Stores a file. hash = Digest::SHA1.file(file.path).hexdigest layer.store("documents", hash, path) Hash must be a hex digest of the file content. If an object with the supplied hash already exists, no action will be performed. In other words, no data will be overwritten if a hash collision occurs. Returns an instance of Fog::Model, or raises an error if the layer is readonly.
[ "Stores", "a", "file", "." ]
f5f57f6ac9a5ccba87fd02331210de736cd4ec1c
https://github.com/elektronaut/dis/blob/f5f57f6ac9a5ccba87fd02331210de736cd4ec1c/lib/dis/layer.rb#L95-L98
1,820
elektronaut/dis
lib/dis/layer.rb
Dis.Layer.exists?
def exists?(type, hash) if directory(type, hash) && directory(type, hash).files.head(key_component(type, hash)) true else false end end
ruby
def exists?(type, hash) if directory(type, hash) && directory(type, hash).files.head(key_component(type, hash)) true else false end end
[ "def", "exists?", "(", "type", ",", "hash", ")", "if", "directory", "(", "type", ",", "hash", ")", "&&", "directory", "(", "type", ",", "hash", ")", ".", "files", ".", "head", "(", "key_component", "(", "type", ",", "hash", ")", ")", "true", "else", "false", "end", "end" ]
Returns true if a object with the given hash exists. layer.exists?("documents", hash)
[ "Returns", "true", "if", "a", "object", "with", "the", "given", "hash", "exists", "." ]
f5f57f6ac9a5ccba87fd02331210de736cd4ec1c
https://github.com/elektronaut/dis/blob/f5f57f6ac9a5ccba87fd02331210de736cd4ec1c/lib/dis/layer.rb#L103-L110
1,821
elektronaut/dis
lib/dis/layer.rb
Dis.Layer.get
def get(type, hash) dir = directory(type, hash) return unless dir dir.files.get(key_component(type, hash)) end
ruby
def get(type, hash) dir = directory(type, hash) return unless dir dir.files.get(key_component(type, hash)) end
[ "def", "get", "(", "type", ",", "hash", ")", "dir", "=", "directory", "(", "type", ",", "hash", ")", "return", "unless", "dir", "dir", ".", "files", ".", "get", "(", "key_component", "(", "type", ",", "hash", ")", ")", "end" ]
Retrieves a file from the store. layer.get("documents", hash)
[ "Retrieves", "a", "file", "from", "the", "store", "." ]
f5f57f6ac9a5ccba87fd02331210de736cd4ec1c
https://github.com/elektronaut/dis/blob/f5f57f6ac9a5ccba87fd02331210de736cd4ec1c/lib/dis/layer.rb#L115-L119
1,822
elektronaut/dis
lib/dis/layer.rb
Dis.Layer.delete
def delete(type, hash) raise Dis::Errors::ReadOnlyError if readonly? delete!(type, hash) end
ruby
def delete(type, hash) raise Dis::Errors::ReadOnlyError if readonly? delete!(type, hash) end
[ "def", "delete", "(", "type", ",", "hash", ")", "raise", "Dis", "::", "Errors", "::", "ReadOnlyError", "if", "readonly?", "delete!", "(", "type", ",", "hash", ")", "end" ]
Deletes a file from the store. layer.delete("documents", hash) Returns true if the file was deleted, or false if it could not be found. Raises an error if the layer is readonly.
[ "Deletes", "a", "file", "from", "the", "store", "." ]
f5f57f6ac9a5ccba87fd02331210de736cd4ec1c
https://github.com/elektronaut/dis/blob/f5f57f6ac9a5ccba87fd02331210de736cd4ec1c/lib/dis/layer.rb#L127-L130
1,823
rapid7/daemon_runner
lib/daemon_runner/session.rb
DaemonRunner.Session.renew!
def renew! return if renew? @renew = Thread.new do ## Wakeup every TTL/2 seconds and renew the session loop do sleep ttl / 2 begin logger.debug(" - Renewing Consul session #{id}") Diplomat::Session.renew(id) rescue Faraday::ResourceNotFound logger.warn("Consul session #{id} has expired!") init rescue StandardError => e ## Keep the thread from exiting logger.error(e) end end end self end
ruby
def renew! return if renew? @renew = Thread.new do ## Wakeup every TTL/2 seconds and renew the session loop do sleep ttl / 2 begin logger.debug(" - Renewing Consul session #{id}") Diplomat::Session.renew(id) rescue Faraday::ResourceNotFound logger.warn("Consul session #{id} has expired!") init rescue StandardError => e ## Keep the thread from exiting logger.error(e) end end end self end
[ "def", "renew!", "return", "if", "renew?", "@renew", "=", "Thread", ".", "new", "do", "## Wakeup every TTL/2 seconds and renew the session", "loop", "do", "sleep", "ttl", "/", "2", "begin", "logger", ".", "debug", "(", "\" - Renewing Consul session #{id}\"", ")", "Diplomat", "::", "Session", ".", "renew", "(", "id", ")", "rescue", "Faraday", "::", "ResourceNotFound", "logger", ".", "warn", "(", "\"Consul session #{id} has expired!\"", ")", "init", "rescue", "StandardError", "=>", "e", "## Keep the thread from exiting", "logger", ".", "error", "(", "e", ")", "end", "end", "end", "self", "end" ]
Create a thread to periodically renew the lock session
[ "Create", "a", "thread", "to", "periodically", "renew", "the", "lock", "session" ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/session.rb#L82-L106
1,824
rapid7/daemon_runner
lib/daemon_runner/session.rb
DaemonRunner.Session.verify_session
def verify_session(wait_time = 2) logger.info(" - Wait until Consul session #{id} exists") wait_time.times do exists = session_exist? raise CreateSessionError, 'Error creating session' unless exists sleep 1 end logger.info(" - Found Consul session #{id}") rescue CreateSessionError init end
ruby
def verify_session(wait_time = 2) logger.info(" - Wait until Consul session #{id} exists") wait_time.times do exists = session_exist? raise CreateSessionError, 'Error creating session' unless exists sleep 1 end logger.info(" - Found Consul session #{id}") rescue CreateSessionError init end
[ "def", "verify_session", "(", "wait_time", "=", "2", ")", "logger", ".", "info", "(", "\" - Wait until Consul session #{id} exists\"", ")", "wait_time", ".", "times", "do", "exists", "=", "session_exist?", "raise", "CreateSessionError", ",", "'Error creating session'", "unless", "exists", "sleep", "1", "end", "logger", ".", "info", "(", "\" - Found Consul session #{id}\"", ")", "rescue", "CreateSessionError", "init", "end" ]
Verify wheather the session exists after a period of time
[ "Verify", "wheather", "the", "session", "exists", "after", "a", "period", "of", "time" ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/session.rb#L116-L126
1,825
rapid7/daemon_runner
lib/daemon_runner/session.rb
DaemonRunner.Session.session_exist?
def session_exist? sessions = Diplomat::Session.list sessions.any? { |s| s['ID'] == id } end
ruby
def session_exist? sessions = Diplomat::Session.list sessions.any? { |s| s['ID'] == id } end
[ "def", "session_exist?", "sessions", "=", "Diplomat", "::", "Session", ".", "list", "sessions", ".", "any?", "{", "|", "s", "|", "s", "[", "'ID'", "]", "==", "id", "}", "end" ]
Does the session exist
[ "Does", "the", "session", "exist" ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/session.rb#L143-L146
1,826
ruby-x/rx-file
lib/rx-file/array_node.rb
RxFile.ArrayNode.long_out
def long_out io , level indent = " " * level @children.each_with_index do |child , i| io.write "\n#{indent}" unless i == 0 io.write "- " child.out(io , level + 1) end end
ruby
def long_out io , level indent = " " * level @children.each_with_index do |child , i| io.write "\n#{indent}" unless i == 0 io.write "- " child.out(io , level + 1) end end
[ "def", "long_out", "io", ",", "level", "indent", "=", "\" \"", "*", "level", "@children", ".", "each_with_index", "do", "|", "child", ",", "i", "|", "io", ".", "write", "\"\\n#{indent}\"", "unless", "i", "==", "0", "io", ".", "write", "\"- \"", "child", ".", "out", "(", "io", ",", "level", "+", "1", ")", "end", "end" ]
Arrays start with the minus on each line "-" and each line has the value
[ "Arrays", "start", "with", "the", "minus", "on", "each", "line", "-", "and", "each", "line", "has", "the", "value" ]
7c4a5546136d1bad065803da91778b209c18cb4d
https://github.com/ruby-x/rx-file/blob/7c4a5546136d1bad065803da91778b209c18cb4d/lib/rx-file/array_node.rb#L42-L49
1,827
KentaaNL/buckaruby
lib/buckaruby/gateway.rb
Buckaruby.Gateway.issuers
def issuers(payment_method) if payment_method != PaymentMethod::IDEAL && payment_method != PaymentMethod::IDEAL_PROCESSING raise ArgumentError, "Invalid payment method, only iDEAL is supported." end Ideal::ISSUERS end
ruby
def issuers(payment_method) if payment_method != PaymentMethod::IDEAL && payment_method != PaymentMethod::IDEAL_PROCESSING raise ArgumentError, "Invalid payment method, only iDEAL is supported." end Ideal::ISSUERS end
[ "def", "issuers", "(", "payment_method", ")", "if", "payment_method", "!=", "PaymentMethod", "::", "IDEAL", "&&", "payment_method", "!=", "PaymentMethod", "::", "IDEAL_PROCESSING", "raise", "ArgumentError", ",", "\"Invalid payment method, only iDEAL is supported.\"", "end", "Ideal", "::", "ISSUERS", "end" ]
Get a list with payment issuers.
[ "Get", "a", "list", "with", "payment", "issuers", "." ]
0aeff3712430745e7c25f4352ab8241df5f4658f
https://github.com/KentaaNL/buckaruby/blob/0aeff3712430745e7c25f4352ab8241df5f4658f/lib/buckaruby/gateway.rb#L21-L27
1,828
KentaaNL/buckaruby
lib/buckaruby/gateway.rb
Buckaruby.Gateway.setup_transaction
def setup_transaction(options = {}) @logger.debug("[setup_transaction] options=#{options.inspect}") validate_setup_transaction_params!(options) normalize_account_iban!(options) if options[:payment_method] == PaymentMethod::SEPA_DIRECT_DEBIT execute_request(:setup_transaction, options) end
ruby
def setup_transaction(options = {}) @logger.debug("[setup_transaction] options=#{options.inspect}") validate_setup_transaction_params!(options) normalize_account_iban!(options) if options[:payment_method] == PaymentMethod::SEPA_DIRECT_DEBIT execute_request(:setup_transaction, options) end
[ "def", "setup_transaction", "(", "options", "=", "{", "}", ")", "@logger", ".", "debug", "(", "\"[setup_transaction] options=#{options.inspect}\"", ")", "validate_setup_transaction_params!", "(", "options", ")", "normalize_account_iban!", "(", "options", ")", "if", "options", "[", ":payment_method", "]", "==", "PaymentMethod", "::", "SEPA_DIRECT_DEBIT", "execute_request", "(", ":setup_transaction", ",", "options", ")", "end" ]
Setup a new transaction.
[ "Setup", "a", "new", "transaction", "." ]
0aeff3712430745e7c25f4352ab8241df5f4658f
https://github.com/KentaaNL/buckaruby/blob/0aeff3712430745e7c25f4352ab8241df5f4658f/lib/buckaruby/gateway.rb#L30-L38
1,829
KentaaNL/buckaruby
lib/buckaruby/gateway.rb
Buckaruby.Gateway.refundable?
def refundable?(options = {}) @logger.debug("[refundable?] options=#{options.inspect}") validate_required_params!(options, :transaction_id) response = execute_request(:refund_info, options) response.refundable? end
ruby
def refundable?(options = {}) @logger.debug("[refundable?] options=#{options.inspect}") validate_required_params!(options, :transaction_id) response = execute_request(:refund_info, options) response.refundable? end
[ "def", "refundable?", "(", "options", "=", "{", "}", ")", "@logger", ".", "debug", "(", "\"[refundable?] options=#{options.inspect}\"", ")", "validate_required_params!", "(", "options", ",", ":transaction_id", ")", "response", "=", "execute_request", "(", ":refund_info", ",", "options", ")", "response", ".", "refundable?", "end" ]
Checks if a transaction is refundable.
[ "Checks", "if", "a", "transaction", "is", "refundable", "." ]
0aeff3712430745e7c25f4352ab8241df5f4658f
https://github.com/KentaaNL/buckaruby/blob/0aeff3712430745e7c25f4352ab8241df5f4658f/lib/buckaruby/gateway.rb#L50-L57
1,830
KentaaNL/buckaruby
lib/buckaruby/gateway.rb
Buckaruby.Gateway.refund_transaction
def refund_transaction(options = {}) @logger.debug("[refund_transaction] options=#{options.inspect}") validate_refund_transaction_params!(options) response = execute_request(:refund_info, options) unless response.refundable? raise NonRefundableTransactionException, options[:transaction_id] end # Pick maximum refundable amount if amount is not supplied. options[:amount] = response.maximum_amount unless options[:amount] # Fill required parameters with data from refund info request. options.merge!( payment_method: response.payment_method, invoicenumber: response.invoicenumber, currency: response.currency ) execute_request(:refund_transaction, options) end
ruby
def refund_transaction(options = {}) @logger.debug("[refund_transaction] options=#{options.inspect}") validate_refund_transaction_params!(options) response = execute_request(:refund_info, options) unless response.refundable? raise NonRefundableTransactionException, options[:transaction_id] end # Pick maximum refundable amount if amount is not supplied. options[:amount] = response.maximum_amount unless options[:amount] # Fill required parameters with data from refund info request. options.merge!( payment_method: response.payment_method, invoicenumber: response.invoicenumber, currency: response.currency ) execute_request(:refund_transaction, options) end
[ "def", "refund_transaction", "(", "options", "=", "{", "}", ")", "@logger", ".", "debug", "(", "\"[refund_transaction] options=#{options.inspect}\"", ")", "validate_refund_transaction_params!", "(", "options", ")", "response", "=", "execute_request", "(", ":refund_info", ",", "options", ")", "unless", "response", ".", "refundable?", "raise", "NonRefundableTransactionException", ",", "options", "[", ":transaction_id", "]", "end", "# Pick maximum refundable amount if amount is not supplied.", "options", "[", ":amount", "]", "=", "response", ".", "maximum_amount", "unless", "options", "[", ":amount", "]", "# Fill required parameters with data from refund info request.", "options", ".", "merge!", "(", "payment_method", ":", "response", ".", "payment_method", ",", "invoicenumber", ":", "response", ".", "invoicenumber", ",", "currency", ":", "response", ".", "currency", ")", "execute_request", "(", ":refund_transaction", ",", "options", ")", "end" ]
Refund a transaction.
[ "Refund", "a", "transaction", "." ]
0aeff3712430745e7c25f4352ab8241df5f4658f
https://github.com/KentaaNL/buckaruby/blob/0aeff3712430745e7c25f4352ab8241df5f4658f/lib/buckaruby/gateway.rb#L60-L81
1,831
KentaaNL/buckaruby
lib/buckaruby/gateway.rb
Buckaruby.Gateway.cancellable?
def cancellable?(options = {}) @logger.debug("[cancellable?] options=#{options.inspect}") validate_required_params!(options, :transaction_id) response = execute_request(:status, options) response.cancellable? end
ruby
def cancellable?(options = {}) @logger.debug("[cancellable?] options=#{options.inspect}") validate_required_params!(options, :transaction_id) response = execute_request(:status, options) response.cancellable? end
[ "def", "cancellable?", "(", "options", "=", "{", "}", ")", "@logger", ".", "debug", "(", "\"[cancellable?] options=#{options.inspect}\"", ")", "validate_required_params!", "(", "options", ",", ":transaction_id", ")", "response", "=", "execute_request", "(", ":status", ",", "options", ")", "response", ".", "cancellable?", "end" ]
Checks if a transaction is cancellable.
[ "Checks", "if", "a", "transaction", "is", "cancellable", "." ]
0aeff3712430745e7c25f4352ab8241df5f4658f
https://github.com/KentaaNL/buckaruby/blob/0aeff3712430745e7c25f4352ab8241df5f4658f/lib/buckaruby/gateway.rb#L93-L100
1,832
KentaaNL/buckaruby
lib/buckaruby/gateway.rb
Buckaruby.Gateway.cancel_transaction
def cancel_transaction(options = {}) @logger.debug("[cancel_transaction] options=#{options.inspect}") validate_required_params!(options, :transaction_id) response = execute_request(:status, options) unless response.cancellable? raise NonCancellableTransactionException, options[:transaction_id] end execute_request(:cancel, options) end
ruby
def cancel_transaction(options = {}) @logger.debug("[cancel_transaction] options=#{options.inspect}") validate_required_params!(options, :transaction_id) response = execute_request(:status, options) unless response.cancellable? raise NonCancellableTransactionException, options[:transaction_id] end execute_request(:cancel, options) end
[ "def", "cancel_transaction", "(", "options", "=", "{", "}", ")", "@logger", ".", "debug", "(", "\"[cancel_transaction] options=#{options.inspect}\"", ")", "validate_required_params!", "(", "options", ",", ":transaction_id", ")", "response", "=", "execute_request", "(", ":status", ",", "options", ")", "unless", "response", ".", "cancellable?", "raise", "NonCancellableTransactionException", ",", "options", "[", ":transaction_id", "]", "end", "execute_request", "(", ":cancel", ",", "options", ")", "end" ]
Cancel a transaction.
[ "Cancel", "a", "transaction", "." ]
0aeff3712430745e7c25f4352ab8241df5f4658f
https://github.com/KentaaNL/buckaruby/blob/0aeff3712430745e7c25f4352ab8241df5f4658f/lib/buckaruby/gateway.rb#L103-L114
1,833
KentaaNL/buckaruby
lib/buckaruby/gateway.rb
Buckaruby.Gateway.validate_required_params!
def validate_required_params!(params, *required) required.flatten.each do |param| if !params.key?(param) || params[param].to_s.empty? raise ArgumentError, "Missing required parameter: #{param}." end end end
ruby
def validate_required_params!(params, *required) required.flatten.each do |param| if !params.key?(param) || params[param].to_s.empty? raise ArgumentError, "Missing required parameter: #{param}." end end end
[ "def", "validate_required_params!", "(", "params", ",", "*", "required", ")", "required", ".", "flatten", ".", "each", "do", "|", "param", "|", "if", "!", "params", ".", "key?", "(", "param", ")", "||", "params", "[", "param", "]", ".", "to_s", ".", "empty?", "raise", "ArgumentError", ",", "\"Missing required parameter: #{param}.\"", "end", "end", "end" ]
Validate required parameters.
[ "Validate", "required", "parameters", "." ]
0aeff3712430745e7c25f4352ab8241df5f4658f
https://github.com/KentaaNL/buckaruby/blob/0aeff3712430745e7c25f4352ab8241df5f4658f/lib/buckaruby/gateway.rb#L128-L134
1,834
KentaaNL/buckaruby
lib/buckaruby/gateway.rb
Buckaruby.Gateway.validate_setup_transaction_params!
def validate_setup_transaction_params!(options) required_params = [:amount, :payment_method, :invoicenumber] required_params << :return_url if options[:payment_method] != PaymentMethod::SEPA_DIRECT_DEBIT case options[:payment_method] when PaymentMethod::IDEAL, PaymentMethod::IDEAL_PROCESSING required_params << :payment_issuer when PaymentMethod::SEPA_DIRECT_DEBIT required_params << [:account_iban, :account_name] end validate_required_params!(options, required_params) validate_amount!(options) valid_payment_methods = [ PaymentMethod::IDEAL, PaymentMethod::IDEAL_PROCESSING, PaymentMethod::VISA, PaymentMethod::MASTER_CARD, PaymentMethod::MAESTRO, PaymentMethod::SEPA_DIRECT_DEBIT, PaymentMethod::PAYPAL, PaymentMethod::BANCONTACT_MISTER_CASH ] validate_payment_method!(options, valid_payment_methods) validate_payment_issuer!(options) end
ruby
def validate_setup_transaction_params!(options) required_params = [:amount, :payment_method, :invoicenumber] required_params << :return_url if options[:payment_method] != PaymentMethod::SEPA_DIRECT_DEBIT case options[:payment_method] when PaymentMethod::IDEAL, PaymentMethod::IDEAL_PROCESSING required_params << :payment_issuer when PaymentMethod::SEPA_DIRECT_DEBIT required_params << [:account_iban, :account_name] end validate_required_params!(options, required_params) validate_amount!(options) valid_payment_methods = [ PaymentMethod::IDEAL, PaymentMethod::IDEAL_PROCESSING, PaymentMethod::VISA, PaymentMethod::MASTER_CARD, PaymentMethod::MAESTRO, PaymentMethod::SEPA_DIRECT_DEBIT, PaymentMethod::PAYPAL, PaymentMethod::BANCONTACT_MISTER_CASH ] validate_payment_method!(options, valid_payment_methods) validate_payment_issuer!(options) end
[ "def", "validate_setup_transaction_params!", "(", "options", ")", "required_params", "=", "[", ":amount", ",", ":payment_method", ",", ":invoicenumber", "]", "required_params", "<<", ":return_url", "if", "options", "[", ":payment_method", "]", "!=", "PaymentMethod", "::", "SEPA_DIRECT_DEBIT", "case", "options", "[", ":payment_method", "]", "when", "PaymentMethod", "::", "IDEAL", ",", "PaymentMethod", "::", "IDEAL_PROCESSING", "required_params", "<<", ":payment_issuer", "when", "PaymentMethod", "::", "SEPA_DIRECT_DEBIT", "required_params", "<<", "[", ":account_iban", ",", ":account_name", "]", "end", "validate_required_params!", "(", "options", ",", "required_params", ")", "validate_amount!", "(", "options", ")", "valid_payment_methods", "=", "[", "PaymentMethod", "::", "IDEAL", ",", "PaymentMethod", "::", "IDEAL_PROCESSING", ",", "PaymentMethod", "::", "VISA", ",", "PaymentMethod", "::", "MASTER_CARD", ",", "PaymentMethod", "::", "MAESTRO", ",", "PaymentMethod", "::", "SEPA_DIRECT_DEBIT", ",", "PaymentMethod", "::", "PAYPAL", ",", "PaymentMethod", "::", "BANCONTACT_MISTER_CASH", "]", "validate_payment_method!", "(", "options", ",", "valid_payment_methods", ")", "validate_payment_issuer!", "(", "options", ")", "end" ]
Validate params for setup transaction.
[ "Validate", "params", "for", "setup", "transaction", "." ]
0aeff3712430745e7c25f4352ab8241df5f4658f
https://github.com/KentaaNL/buckaruby/blob/0aeff3712430745e7c25f4352ab8241df5f4658f/lib/buckaruby/gateway.rb#L137-L159
1,835
KentaaNL/buckaruby
lib/buckaruby/gateway.rb
Buckaruby.Gateway.validate_payment_issuer!
def validate_payment_issuer!(options) if options[:payment_method] == PaymentMethod::IDEAL || options[:payment_method] == PaymentMethod::IDEAL_PROCESSING unless Ideal::ISSUERS.include?(options[:payment_issuer]) raise ArgumentError, "Invalid payment issuer: #{options[:payment_issuer]}" end end end
ruby
def validate_payment_issuer!(options) if options[:payment_method] == PaymentMethod::IDEAL || options[:payment_method] == PaymentMethod::IDEAL_PROCESSING unless Ideal::ISSUERS.include?(options[:payment_issuer]) raise ArgumentError, "Invalid payment issuer: #{options[:payment_issuer]}" end end end
[ "def", "validate_payment_issuer!", "(", "options", ")", "if", "options", "[", ":payment_method", "]", "==", "PaymentMethod", "::", "IDEAL", "||", "options", "[", ":payment_method", "]", "==", "PaymentMethod", "::", "IDEAL_PROCESSING", "unless", "Ideal", "::", "ISSUERS", ".", "include?", "(", "options", "[", ":payment_issuer", "]", ")", "raise", "ArgumentError", ",", "\"Invalid payment issuer: #{options[:payment_issuer]}\"", "end", "end", "end" ]
Validate the payment issuer when iDEAL is selected as payment method.
[ "Validate", "the", "payment", "issuer", "when", "iDEAL", "is", "selected", "as", "payment", "method", "." ]
0aeff3712430745e7c25f4352ab8241df5f4658f
https://github.com/KentaaNL/buckaruby/blob/0aeff3712430745e7c25f4352ab8241df5f4658f/lib/buckaruby/gateway.rb#L177-L183
1,836
KentaaNL/buckaruby
lib/buckaruby/gateway.rb
Buckaruby.Gateway.validate_recurrent_transaction_params!
def validate_recurrent_transaction_params!(options) required_params = [:amount, :payment_method, :invoicenumber, :transaction_id] validate_required_params!(options, required_params) validate_amount!(options) valid_payment_methods = [ PaymentMethod::VISA, PaymentMethod::MASTER_CARD, PaymentMethod::MAESTRO, PaymentMethod::SEPA_DIRECT_DEBIT, PaymentMethod::PAYPAL ] validate_payment_method!(options, valid_payment_methods) end
ruby
def validate_recurrent_transaction_params!(options) required_params = [:amount, :payment_method, :invoicenumber, :transaction_id] validate_required_params!(options, required_params) validate_amount!(options) valid_payment_methods = [ PaymentMethod::VISA, PaymentMethod::MASTER_CARD, PaymentMethod::MAESTRO, PaymentMethod::SEPA_DIRECT_DEBIT, PaymentMethod::PAYPAL ] validate_payment_method!(options, valid_payment_methods) end
[ "def", "validate_recurrent_transaction_params!", "(", "options", ")", "required_params", "=", "[", ":amount", ",", ":payment_method", ",", ":invoicenumber", ",", ":transaction_id", "]", "validate_required_params!", "(", "options", ",", "required_params", ")", "validate_amount!", "(", "options", ")", "valid_payment_methods", "=", "[", "PaymentMethod", "::", "VISA", ",", "PaymentMethod", "::", "MASTER_CARD", ",", "PaymentMethod", "::", "MAESTRO", ",", "PaymentMethod", "::", "SEPA_DIRECT_DEBIT", ",", "PaymentMethod", "::", "PAYPAL", "]", "validate_payment_method!", "(", "options", ",", "valid_payment_methods", ")", "end" ]
Validate params for recurrent transaction.
[ "Validate", "params", "for", "recurrent", "transaction", "." ]
0aeff3712430745e7c25f4352ab8241df5f4658f
https://github.com/KentaaNL/buckaruby/blob/0aeff3712430745e7c25f4352ab8241df5f4658f/lib/buckaruby/gateway.rb#L186-L198
1,837
KentaaNL/buckaruby
lib/buckaruby/gateway.rb
Buckaruby.Gateway.execute_request
def execute_request(request_type, options) request = build_request(request_type) response = request.execute(options) case request_type when :setup_transaction SetupTransactionResponse.new(response, config) when :recurrent_transaction RecurrentTransactionResponse.new(response, config) when :refund_transaction RefundTransactionResponse.new(response, config) when :refund_info RefundInfoResponse.new(response, config) when :status StatusResponse.new(response, config) when :cancel CancelResponse.new(response, config) end end
ruby
def execute_request(request_type, options) request = build_request(request_type) response = request.execute(options) case request_type when :setup_transaction SetupTransactionResponse.new(response, config) when :recurrent_transaction RecurrentTransactionResponse.new(response, config) when :refund_transaction RefundTransactionResponse.new(response, config) when :refund_info RefundInfoResponse.new(response, config) when :status StatusResponse.new(response, config) when :cancel CancelResponse.new(response, config) end end
[ "def", "execute_request", "(", "request_type", ",", "options", ")", "request", "=", "build_request", "(", "request_type", ")", "response", "=", "request", ".", "execute", "(", "options", ")", "case", "request_type", "when", ":setup_transaction", "SetupTransactionResponse", ".", "new", "(", "response", ",", "config", ")", "when", ":recurrent_transaction", "RecurrentTransactionResponse", ".", "new", "(", "response", ",", "config", ")", "when", ":refund_transaction", "RefundTransactionResponse", ".", "new", "(", "response", ",", "config", ")", "when", ":refund_info", "RefundInfoResponse", ".", "new", "(", "response", ",", "config", ")", "when", ":status", "StatusResponse", ".", "new", "(", "response", ",", "config", ")", "when", ":cancel", "CancelResponse", ".", "new", "(", "response", ",", "config", ")", "end", "end" ]
Build and execute a request.
[ "Build", "and", "execute", "a", "request", "." ]
0aeff3712430745e7c25f4352ab8241df5f4658f
https://github.com/KentaaNL/buckaruby/blob/0aeff3712430745e7c25f4352ab8241df5f4658f/lib/buckaruby/gateway.rb#L226-L244
1,838
KentaaNL/buckaruby
lib/buckaruby/gateway.rb
Buckaruby.Gateway.build_request
def build_request(request_type) case request_type when :setup_transaction SetupTransactionRequest.new(config) when :recurrent_transaction RecurrentTransactionRequest.new(config) when :refund_transaction RefundTransactionRequest.new(config) when :refund_info RefundInfoRequest.new(config) when :status StatusRequest.new(config) when :cancel CancelRequest.new(config) end end
ruby
def build_request(request_type) case request_type when :setup_transaction SetupTransactionRequest.new(config) when :recurrent_transaction RecurrentTransactionRequest.new(config) when :refund_transaction RefundTransactionRequest.new(config) when :refund_info RefundInfoRequest.new(config) when :status StatusRequest.new(config) when :cancel CancelRequest.new(config) end end
[ "def", "build_request", "(", "request_type", ")", "case", "request_type", "when", ":setup_transaction", "SetupTransactionRequest", ".", "new", "(", "config", ")", "when", ":recurrent_transaction", "RecurrentTransactionRequest", ".", "new", "(", "config", ")", "when", ":refund_transaction", "RefundTransactionRequest", ".", "new", "(", "config", ")", "when", ":refund_info", "RefundInfoRequest", ".", "new", "(", "config", ")", "when", ":status", "StatusRequest", ".", "new", "(", "config", ")", "when", ":cancel", "CancelRequest", ".", "new", "(", "config", ")", "end", "end" ]
Factory method for constructing a request.
[ "Factory", "method", "for", "constructing", "a", "request", "." ]
0aeff3712430745e7c25f4352ab8241df5f4658f
https://github.com/KentaaNL/buckaruby/blob/0aeff3712430745e7c25f4352ab8241df5f4658f/lib/buckaruby/gateway.rb#L247-L262
1,839
ruby-x/rx-file
lib/rx-file/node.rb
RxFile.Node.as_string
def as_string(level) io = StringIO.new out(io,level) io.string end
ruby
def as_string(level) io = StringIO.new out(io,level) io.string end
[ "def", "as_string", "(", "level", ")", "io", "=", "StringIO", ".", "new", "out", "(", "io", ",", "level", ")", "io", ".", "string", "end" ]
helper function to return the output as a string ie creates stringio, calls out and returns the string
[ "helper", "function", "to", "return", "the", "output", "as", "a", "string", "ie", "creates", "stringio", "calls", "out", "and", "returns", "the", "string" ]
7c4a5546136d1bad065803da91778b209c18cb4d
https://github.com/ruby-x/rx-file/blob/7c4a5546136d1bad065803da91778b209c18cb4d/lib/rx-file/node.rb#L50-L54
1,840
ruby-x/rx-file
lib/rx-file/object_node.rb
RxFile.ObjectNode.add
def add k , v raise "Key should be symbol not #{k}" unless k.is_a? Symbol if( v.is_simple?) @simple[k] = v else @complex[k] = v end end
ruby
def add k , v raise "Key should be symbol not #{k}" unless k.is_a? Symbol if( v.is_simple?) @simple[k] = v else @complex[k] = v end end
[ "def", "add", "k", ",", "v", "raise", "\"Key should be symbol not #{k}\"", "unless", "k", ".", "is_a?", "Symbol", "if", "(", "v", ".", "is_simple?", ")", "@simple", "[", "k", "]", "=", "v", "else", "@complex", "[", "k", "]", "=", "v", "end", "end" ]
attributes hold key value pairs
[ "attributes", "hold", "key", "value", "pairs" ]
7c4a5546136d1bad065803da91778b209c18cb4d
https://github.com/ruby-x/rx-file/blob/7c4a5546136d1bad065803da91778b209c18cb4d/lib/rx-file/object_node.rb#L24-L31
1,841
mkroman/blur
library/blur/script_cache.rb
Blur.ScriptCache.save
def save directory = File.dirname @path unless File.directory? directory Dir.mkdir directory end File.open @path, ?w do |file| YAML.dump @hash, file end end
ruby
def save directory = File.dirname @path unless File.directory? directory Dir.mkdir directory end File.open @path, ?w do |file| YAML.dump @hash, file end end
[ "def", "save", "directory", "=", "File", ".", "dirname", "@path", "unless", "File", ".", "directory?", "directory", "Dir", ".", "mkdir", "directory", "end", "File", ".", "open", "@path", ",", "?w", "do", "|", "file", "|", "YAML", ".", "dump", "@hash", ",", "file", "end", "end" ]
Saves the cache as a YAML file.
[ "Saves", "the", "cache", "as", "a", "YAML", "file", "." ]
05408fbbaecb33a506c7e7c72da01d2e68848ea9
https://github.com/mkroman/blur/blob/05408fbbaecb33a506c7e7c72da01d2e68848ea9/library/blur/script_cache.rb#L18-L28
1,842
roqua/authmac
lib/authmac/hmac_checker.rb
Authmac.HmacChecker.params_sorted_by_key
def params_sorted_by_key(params) case params when Hash params.map { |k, v| [k.to_s, params_sorted_by_key(v)] } .sort_by { |k, v| k } .to_h when Array params.map { |val| params_sorted_by_key(val) } else params.to_s end end
ruby
def params_sorted_by_key(params) case params when Hash params.map { |k, v| [k.to_s, params_sorted_by_key(v)] } .sort_by { |k, v| k } .to_h when Array params.map { |val| params_sorted_by_key(val) } else params.to_s end end
[ "def", "params_sorted_by_key", "(", "params", ")", "case", "params", "when", "Hash", "params", ".", "map", "{", "|", "k", ",", "v", "|", "[", "k", ".", "to_s", ",", "params_sorted_by_key", "(", "v", ")", "]", "}", ".", "sort_by", "{", "|", "k", ",", "v", "|", "k", "}", ".", "to_h", "when", "Array", "params", ".", "map", "{", "|", "val", "|", "params_sorted_by_key", "(", "val", ")", "}", "else", "params", ".", "to_s", "end", "end" ]
stringifies and sorts hashes by key at all levels.
[ "stringifies", "and", "sorts", "hashes", "by", "key", "at", "all", "levels", "." ]
c0e064b80f90c10f93c4f5d8e5e3e590829feba4
https://github.com/roqua/authmac/blob/c0e064b80f90c10f93c4f5d8e5e3e590829feba4/lib/authmac/hmac_checker.rb#L55-L66
1,843
richo/juici
lib/juici/controllers/trigger.rb
Juici::Controllers.Trigger.rebuild!
def rebuild! unless project = ::Juici::Project.where(name: params[:project]).first not_found end unless build = ::Juici::Build.where(parent: project.name, _id: params[:id]).first not_found end ::Juici::Build.new_from(build).tap do |new_build| new_build.save! $build_queue << new_build $build_queue.bump! end end
ruby
def rebuild! unless project = ::Juici::Project.where(name: params[:project]).first not_found end unless build = ::Juici::Build.where(parent: project.name, _id: params[:id]).first not_found end ::Juici::Build.new_from(build).tap do |new_build| new_build.save! $build_queue << new_build $build_queue.bump! end end
[ "def", "rebuild!", "unless", "project", "=", "::", "Juici", "::", "Project", ".", "where", "(", "name", ":", "params", "[", ":project", "]", ")", ".", "first", "not_found", "end", "unless", "build", "=", "::", "Juici", "::", "Build", ".", "where", "(", "parent", ":", "project", ".", "name", ",", "_id", ":", "params", "[", ":id", "]", ")", ".", "first", "not_found", "end", "::", "Juici", "::", "Build", ".", "new_from", "(", "build", ")", ".", "tap", "do", "|", "new_build", "|", "new_build", ".", "save!", "$build_queue", "<<", "new_build", "$build_queue", ".", "bump!", "end", "end" ]
Find an existing build, duplicate the sane parts of it.
[ "Find", "an", "existing", "build", "duplicate", "the", "sane", "parts", "of", "it", "." ]
5649b251a9c8f8c29623fba2fd9fd0b1fc2dbffa
https://github.com/richo/juici/blob/5649b251a9c8f8c29623fba2fd9fd0b1fc2dbffa/lib/juici/controllers/trigger.rb#L11-L24
1,844
bjoernalbers/aruba-doubles
lib/aruba-doubles/double.rb
ArubaDoubles.Double.run
def run(argv = ARGV) history << [filename] + argv output = @outputs[argv] || @default_output puts output[:puts] if output[:puts] warn output[:warn] if output[:warn] exit output[:exit] if output[:exit] end
ruby
def run(argv = ARGV) history << [filename] + argv output = @outputs[argv] || @default_output puts output[:puts] if output[:puts] warn output[:warn] if output[:warn] exit output[:exit] if output[:exit] end
[ "def", "run", "(", "argv", "=", "ARGV", ")", "history", "<<", "[", "filename", "]", "+", "argv", "output", "=", "@outputs", "[", "argv", "]", "||", "@default_output", "puts", "output", "[", ":puts", "]", "if", "output", "[", ":puts", "]", "warn", "output", "[", ":warn", "]", "if", "output", "[", ":warn", "]", "exit", "output", "[", ":exit", "]", "if", "output", "[", ":exit", "]", "end" ]
Run the double. This will append the call to the doubles history, display any outputs if defined and exit.
[ "Run", "the", "double", "." ]
5e835bf60fef4bdf903c225a7c29968d17899516
https://github.com/bjoernalbers/aruba-doubles/blob/5e835bf60fef4bdf903c225a7c29968d17899516/lib/aruba-doubles/double.rb#L113-L119
1,845
bjoernalbers/aruba-doubles
lib/aruba-doubles/double.rb
ArubaDoubles.Double.create
def create(&block) register self.instance_eval(&block) if block_given? content = self.to_ruby fullpath = File.join(self.class.bindir, filename) #puts "creating double: #{fullpath} with content:\n#{content}" # debug f = File.open(fullpath, 'w') f.puts content f.close FileUtils.chmod(0755, File.join(self.class.bindir, filename)) self end
ruby
def create(&block) register self.instance_eval(&block) if block_given? content = self.to_ruby fullpath = File.join(self.class.bindir, filename) #puts "creating double: #{fullpath} with content:\n#{content}" # debug f = File.open(fullpath, 'w') f.puts content f.close FileUtils.chmod(0755, File.join(self.class.bindir, filename)) self end
[ "def", "create", "(", "&", "block", ")", "register", "self", ".", "instance_eval", "(", "block", ")", "if", "block_given?", "content", "=", "self", ".", "to_ruby", "fullpath", "=", "File", ".", "join", "(", "self", ".", "class", ".", "bindir", ",", "filename", ")", "#puts \"creating double: #{fullpath} with content:\\n#{content}\" # debug", "f", "=", "File", ".", "open", "(", "fullpath", ",", "'w'", ")", "f", ".", "puts", "content", "f", ".", "close", "FileUtils", ".", "chmod", "(", "0755", ",", "File", ".", "join", "(", "self", ".", "class", ".", "bindir", ",", "filename", ")", ")", "self", "end" ]
Create the executable double. @return [String] full path to the double.
[ "Create", "the", "executable", "double", "." ]
5e835bf60fef4bdf903c225a7c29968d17899516
https://github.com/bjoernalbers/aruba-doubles/blob/5e835bf60fef4bdf903c225a7c29968d17899516/lib/aruba-doubles/double.rb#L124-L135
1,846
bjoernalbers/aruba-doubles
lib/aruba-doubles/double.rb
ArubaDoubles.Double.to_ruby
def to_ruby ruby = ['#!/usr/bin/env ruby'] ruby << "$: << '#{File.expand_path('..', File.dirname(__FILE__))}'" ruby << 'require "aruba-doubles"' ruby << 'ArubaDoubles::Double.run do' @outputs.each_pair { |argv,output| ruby << " on #{argv.inspect}, #{output.inspect}" } ruby << 'end' ruby.join("\n") end
ruby
def to_ruby ruby = ['#!/usr/bin/env ruby'] ruby << "$: << '#{File.expand_path('..', File.dirname(__FILE__))}'" ruby << 'require "aruba-doubles"' ruby << 'ArubaDoubles::Double.run do' @outputs.each_pair { |argv,output| ruby << " on #{argv.inspect}, #{output.inspect}" } ruby << 'end' ruby.join("\n") end
[ "def", "to_ruby", "ruby", "=", "[", "'#!/usr/bin/env ruby'", "]", "ruby", "<<", "\"$: << '#{File.expand_path('..', File.dirname(__FILE__))}'\"", "ruby", "<<", "'require \"aruba-doubles\"'", "ruby", "<<", "'ArubaDoubles::Double.run do'", "@outputs", ".", "each_pair", "{", "|", "argv", ",", "output", "|", "ruby", "<<", "\" on #{argv.inspect}, #{output.inspect}\"", "}", "ruby", "<<", "'end'", "ruby", ".", "join", "(", "\"\\n\"", ")", "end" ]
Export the double to executable Ruby code. @return [String] serialized double
[ "Export", "the", "double", "to", "executable", "Ruby", "code", "." ]
5e835bf60fef4bdf903c225a7c29968d17899516
https://github.com/bjoernalbers/aruba-doubles/blob/5e835bf60fef4bdf903c225a7c29968d17899516/lib/aruba-doubles/double.rb#L140-L148
1,847
bjoernalbers/aruba-doubles
lib/aruba-doubles/double.rb
ArubaDoubles.Double.delete
def delete deregister fullpath = File.join(self.class.bindir, filename) FileUtils.rm(fullpath) if File.exists?(fullpath) end
ruby
def delete deregister fullpath = File.join(self.class.bindir, filename) FileUtils.rm(fullpath) if File.exists?(fullpath) end
[ "def", "delete", "deregister", "fullpath", "=", "File", ".", "join", "(", "self", ".", "class", ".", "bindir", ",", "filename", ")", "FileUtils", ".", "rm", "(", "fullpath", ")", "if", "File", ".", "exists?", "(", "fullpath", ")", "end" ]
Delete the executable double.
[ "Delete", "the", "executable", "double", "." ]
5e835bf60fef4bdf903c225a7c29968d17899516
https://github.com/bjoernalbers/aruba-doubles/blob/5e835bf60fef4bdf903c225a7c29968d17899516/lib/aruba-doubles/double.rb#L151-L155
1,848
meineerde/rackstash
lib/rackstash/filter_chain.rb
Rackstash.FilterChain.[]=
def []=(index, filter) raise TypeError, 'must provide a filter' unless filter.respond_to?(:call) synchronize do id = index_at(index) unless id && ([email protected]).cover?(id) raise ArgumentError, "Cannot insert at index #{index.inspect}" end @filters[id] = filter end end
ruby
def []=(index, filter) raise TypeError, 'must provide a filter' unless filter.respond_to?(:call) synchronize do id = index_at(index) unless id && ([email protected]).cover?(id) raise ArgumentError, "Cannot insert at index #{index.inspect}" end @filters[id] = filter end end
[ "def", "[]=", "(", "index", ",", "filter", ")", "raise", "TypeError", ",", "'must provide a filter'", "unless", "filter", ".", "respond_to?", "(", ":call", ")", "synchronize", "do", "id", "=", "index_at", "(", "index", ")", "unless", "id", "&&", "(", "0", "..", "@filters", ".", "size", ")", ".", "cover?", "(", "id", ")", "raise", "ArgumentError", ",", "\"Cannot insert at index #{index.inspect}\"", "end", "@filters", "[", "id", "]", "=", "filter", "end", "end" ]
Set the new filter at the given `index`. You can specify any existing filter or an index one above the highest index. @param index [Integer, Class, String, Object] The existing filter which should be overwritten with `filter`. It can be described in different ways: When given an `Integer`, we expect it to be the index number; when given a `Class`, we try to find the first filter being of that type; when given a `String`, we try to find the first filter being of a type named like that; when given any other object, we assume it is a filter and search for that. @param filter [#call, nil] the filter to set at `index` @raise [ArgumentError] if no existing filter could be found at `index` @raise [TypeError] if the given filter is not callable @return [#call] the given `filter`
[ "Set", "the", "new", "filter", "at", "the", "given", "index", ".", "You", "can", "specify", "any", "existing", "filter", "or", "an", "index", "one", "above", "the", "highest", "index", "." ]
b610a2157187dd05ef8d500320aa846234487b01
https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/filter_chain.rb#L67-L78
1,849
meineerde/rackstash
lib/rackstash/filter_chain.rb
Rackstash.FilterChain.call
def call(event) each do |filter| result = filter.call(event) return false if result == false end event end
ruby
def call(event) each do |filter| result = filter.call(event) return false if result == false end event end
[ "def", "call", "(", "event", ")", "each", "do", "|", "filter", "|", "result", "=", "filter", ".", "call", "(", "event", ")", "return", "false", "if", "result", "==", "false", "end", "event", "end" ]
Filter the given event by calling each defined filter with it. Each filter will be called with the current event and can manipulate it in any way. If any of the filters returns `false`, no further filter will be applied and we also return `false`. This behavior can be used by filters to cancel the writing of an individual event. Any other return value of filters is ignored. @param event [Hash] an event hash, see {Buffer#event} for details @return [Hash, false] the filtered event or `false` if any of the filters returned `false`
[ "Filter", "the", "given", "event", "by", "calling", "each", "defined", "filter", "with", "it", ".", "Each", "filter", "will", "be", "called", "with", "the", "current", "event", "and", "can", "manipulate", "it", "in", "any", "way", "." ]
b610a2157187dd05ef8d500320aa846234487b01
https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/filter_chain.rb#L110-L116
1,850
meineerde/rackstash
lib/rackstash/filter_chain.rb
Rackstash.FilterChain.insert_before
def insert_before(index, *filter_spec, &block) filter = build_filter(filter_spec, &block) synchronize do id = index_at(index) unless id && ([email protected]).cover?(id) raise ArgumentError, "No such filter to insert before: #{index.inspect}" end @filters.insert(id, filter) end self end
ruby
def insert_before(index, *filter_spec, &block) filter = build_filter(filter_spec, &block) synchronize do id = index_at(index) unless id && ([email protected]).cover?(id) raise ArgumentError, "No such filter to insert before: #{index.inspect}" end @filters.insert(id, filter) end self end
[ "def", "insert_before", "(", "index", ",", "*", "filter_spec", ",", "&", "block", ")", "filter", "=", "build_filter", "(", "filter_spec", ",", "block", ")", "synchronize", "do", "id", "=", "index_at", "(", "index", ")", "unless", "id", "&&", "(", "0", "...", "@filters", ".", "size", ")", ".", "cover?", "(", "id", ")", "raise", "ArgumentError", ",", "\"No such filter to insert before: #{index.inspect}\"", "end", "@filters", ".", "insert", "(", "id", ",", "filter", ")", "end", "self", "end" ]
Insert a new filter before an existing filter in the filter chain. @param index [Integer, Class, String, Object] The existing filter before which the new one should be inserted. It can be described in different ways: When given an `Integer`, we expect it to be the index number; when given a `Class`, we try to find the first filter being of that type; when given a `String`, we try to find the first filter being of a type named like that; when given any other object, we assume it is a filter and search for that. @param filter_spec (see #build_filter) @raise [ArgumentError] if no existing filter could be found at `index` @raise [TypeError] if we could not build a filter from the given `filter_spec` @return [self]
[ "Insert", "a", "new", "filter", "before", "an", "existing", "filter", "in", "the", "filter", "chain", "." ]
b610a2157187dd05ef8d500320aa846234487b01
https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/filter_chain.rb#L209-L221
1,851
meineerde/rackstash
lib/rackstash/filter_chain.rb
Rackstash.FilterChain.build_filter
def build_filter(filter_spec, &block) if filter_spec.empty? return Rackstash::Filter.build(block) if block_given? raise ArgumentError, 'Need to specify a filter' else Rackstash::Filter.build(*filter_spec, &block) end end
ruby
def build_filter(filter_spec, &block) if filter_spec.empty? return Rackstash::Filter.build(block) if block_given? raise ArgumentError, 'Need to specify a filter' else Rackstash::Filter.build(*filter_spec, &block) end end
[ "def", "build_filter", "(", "filter_spec", ",", "&", "block", ")", "if", "filter_spec", ".", "empty?", "return", "Rackstash", "::", "Filter", ".", "build", "(", "block", ")", "if", "block_given?", "raise", "ArgumentError", ",", "'Need to specify a filter'", "else", "Rackstash", "::", "Filter", ".", "build", "(", "filter_spec", ",", "block", ")", "end", "end" ]
Build a new filter instance from the given specification. @param filter_spec [Array] the description of a filter to create. If you give a single `Proc` (or any other object which responds to `#call`) or simply a proc, we will directly return it. If you give a `Class` plus any optional initializer arguments, we will return a new instance of that class. When giving a `String` or `Symbol`, we first use the {Filter.registry} to find the matching filter class. With that class, we then create a filter object as before using the additional arguments given to `initialize`. @return [#call] a filter instance
[ "Build", "a", "new", "filter", "instance", "from", "the", "given", "specification", "." ]
b610a2157187dd05ef8d500320aa846234487b01
https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/filter_chain.rb#L306-L313
1,852
rapid7/daemon_runner
lib/daemon_runner/client.rb
DaemonRunner.Client.start!
def start! wait logger.warn 'Tasks list is empty' if tasks.empty? tasks.each do |task| run_task(task) sleep post_task_sleep_time end scheduler.join rescue SystemExit, Interrupt logger.info 'Shutting down' scheduler.shutdown end
ruby
def start! wait logger.warn 'Tasks list is empty' if tasks.empty? tasks.each do |task| run_task(task) sleep post_task_sleep_time end scheduler.join rescue SystemExit, Interrupt logger.info 'Shutting down' scheduler.shutdown end
[ "def", "start!", "wait", "logger", ".", "warn", "'Tasks list is empty'", "if", "tasks", ".", "empty?", "tasks", ".", "each", "do", "|", "task", "|", "run_task", "(", "task", ")", "sleep", "post_task_sleep_time", "end", "scheduler", ".", "join", "rescue", "SystemExit", ",", "Interrupt", "logger", ".", "info", "'Shutting down'", "scheduler", ".", "shutdown", "end" ]
Start the service @return [nil]
[ "Start", "the", "service" ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/client.rb#L110-L123
1,853
meineerde/rackstash
lib/rackstash/class_registry.rb
Rackstash.ClassRegistry.fetch
def fetch(spec, default = UNDEFINED) case spec when Class spec when String, Symbol, ->(s) { s.respond_to?(:to_sym) } @registry.fetch(spec.to_sym) do |key| next yield(key) if block_given? next default unless UNDEFINED.equal? default raise KeyError, "No #{@object_type} was registered for #{spec.inspect}" end else raise TypeError, "#{spec.inspect} can not be used to describe " \ "#{@object_type} classes" end end
ruby
def fetch(spec, default = UNDEFINED) case spec when Class spec when String, Symbol, ->(s) { s.respond_to?(:to_sym) } @registry.fetch(spec.to_sym) do |key| next yield(key) if block_given? next default unless UNDEFINED.equal? default raise KeyError, "No #{@object_type} was registered for #{spec.inspect}" end else raise TypeError, "#{spec.inspect} can not be used to describe " \ "#{@object_type} classes" end end
[ "def", "fetch", "(", "spec", ",", "default", "=", "UNDEFINED", ")", "case", "spec", "when", "Class", "spec", "when", "String", ",", "Symbol", ",", "->", "(", "s", ")", "{", "s", ".", "respond_to?", "(", ":to_sym", ")", "}", "@registry", ".", "fetch", "(", "spec", ".", "to_sym", ")", "do", "|", "key", "|", "next", "yield", "(", "key", ")", "if", "block_given?", "next", "default", "unless", "UNDEFINED", ".", "equal?", "default", "raise", "KeyError", ",", "\"No #{@object_type} was registered for #{spec.inspect}\"", "end", "else", "raise", "TypeError", ",", "\"#{spec.inspect} can not be used to describe \"", "\"#{@object_type} classes\"", "end", "end" ]
Retrieve the registered class for a given name. If the argument is already a class, we return it unchanged. @param spec [Class,String,Symbol] either a class (in which case it is returned directly) or the name of a registered class @param default [Object] the default value that is returned if no registered class could be found for the given `spec` and no block was given. @yield if no registered class could be found for the given `spec`, we will run the optional block and return its result @yieldparam spec [Symbol] the requested class specification as a `Symbol` @raise [KeyError] when giving a `String` or `Symbol` but no registered class was found for it and no default was specified @raise [TypeError] when giving an invalid `spec` object @return [Class] the registered class (when giving a `String` or `Symbol`) or the given class (when giving a `Class`)
[ "Retrieve", "the", "registered", "class", "for", "a", "given", "name", ".", "If", "the", "argument", "is", "already", "a", "class", "we", "return", "it", "unchanged", "." ]
b610a2157187dd05ef8d500320aa846234487b01
https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/class_registry.rb#L53-L68
1,854
meineerde/rackstash
lib/rackstash/class_registry.rb
Rackstash.ClassRegistry.[]=
def []=(name, registered_class) unless registered_class.is_a?(Class) raise TypeError, 'Can only register class objects' end case name when String, Symbol @registry[name.to_sym] = registered_class else raise TypeError, "Can not use #{name.inspect} to register a #{@object_type} class" end registered_class end
ruby
def []=(name, registered_class) unless registered_class.is_a?(Class) raise TypeError, 'Can only register class objects' end case name when String, Symbol @registry[name.to_sym] = registered_class else raise TypeError, "Can not use #{name.inspect} to register a #{@object_type} class" end registered_class end
[ "def", "[]=", "(", "name", ",", "registered_class", ")", "unless", "registered_class", ".", "is_a?", "(", "Class", ")", "raise", "TypeError", ",", "'Can only register class objects'", "end", "case", "name", "when", "String", ",", "Symbol", "@registry", "[", "name", ".", "to_sym", "]", "=", "registered_class", "else", "raise", "TypeError", ",", "\"Can not use #{name.inspect} to register a #{@object_type} class\"", "end", "registered_class", "end" ]
Register a class for the given name. @param name [String, Symbol] the name at which the class should be registered @param registered_class [Class] the class to register at `name` @raise [TypeError] if `name` is not a `String` or `Symbol`, or if `registered_class` is not a `Class` @return [Class] the `registered_class`
[ "Register", "a", "class", "for", "the", "given", "name", "." ]
b610a2157187dd05ef8d500320aa846234487b01
https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/class_registry.rb#L78-L90
1,855
mkroman/blur
library/blur/callbacks.rb
Blur.Callbacks.emit
def emit name, *args # Trigger callbacks in scripts before triggering events in the client. EM.defer { notify_scripts name, *args } matching_callbacks = callbacks[name] return false unless matching_callbacks&.any? EM.defer do matching_callbacks.each { |callback| callback.call *args } end end
ruby
def emit name, *args # Trigger callbacks in scripts before triggering events in the client. EM.defer { notify_scripts name, *args } matching_callbacks = callbacks[name] return false unless matching_callbacks&.any? EM.defer do matching_callbacks.each { |callback| callback.call *args } end end
[ "def", "emit", "name", ",", "*", "args", "# Trigger callbacks in scripts before triggering events in the client.", "EM", ".", "defer", "{", "notify_scripts", "name", ",", "args", "}", "matching_callbacks", "=", "callbacks", "[", "name", "]", "return", "false", "unless", "matching_callbacks", "&.", "any?", "EM", ".", "defer", "do", "matching_callbacks", ".", "each", "{", "|", "callback", "|", "callback", ".", "call", "args", "}", "end", "end" ]
Emit a new event with given arguments. @param name [Symbol] The event name. @param args [optional, Array] The list of arguments to pass. @return [true, false] True if any callbacks were invoked, nil otherwise
[ "Emit", "a", "new", "event", "with", "given", "arguments", "." ]
05408fbbaecb33a506c7e7c72da01d2e68848ea9
https://github.com/mkroman/blur/blob/05408fbbaecb33a506c7e7c72da01d2e68848ea9/library/blur/callbacks.rb#L17-L27
1,856
derek-schaefer/virtus_model
lib/virtus_model/base.rb
VirtusModel.Base.export
def export(options = nil) self.class.attributes.reduce({}) do |result, name| value = attributes[name] if self.class.association?(name, :many) result[name] = export_values(value, options) elsif self.class.association?(name, :one) result[name] = export_value(value, options) else result[name] = value end result end end
ruby
def export(options = nil) self.class.attributes.reduce({}) do |result, name| value = attributes[name] if self.class.association?(name, :many) result[name] = export_values(value, options) elsif self.class.association?(name, :one) result[name] = export_value(value, options) else result[name] = value end result end end
[ "def", "export", "(", "options", "=", "nil", ")", "self", ".", "class", ".", "attributes", ".", "reduce", "(", "{", "}", ")", "do", "|", "result", ",", "name", "|", "value", "=", "attributes", "[", "name", "]", "if", "self", ".", "class", ".", "association?", "(", "name", ",", ":many", ")", "result", "[", "name", "]", "=", "export_values", "(", "value", ",", "options", ")", "elsif", "self", ".", "class", ".", "association?", "(", "name", ",", ":one", ")", "result", "[", "name", "]", "=", "export_value", "(", "value", ",", "options", ")", "else", "result", "[", "name", "]", "=", "value", "end", "result", "end", "end" ]
Two models are equal if their attributes are equal. Recursively convert all attributes to hash pairs.
[ "Two", "models", "are", "equal", "if", "their", "attributes", "are", "equal", ".", "Recursively", "convert", "all", "attributes", "to", "hash", "pairs", "." ]
97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb
https://github.com/derek-schaefer/virtus_model/blob/97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb/lib/virtus_model/base.rb#L70-L82
1,857
derek-schaefer/virtus_model
lib/virtus_model/base.rb
VirtusModel.Base.extract_attributes
def extract_attributes(model) self.class.attributes.reduce({}) do |result, name| if model.respond_to?(name) result[name] = model.public_send(name) elsif model.respond_to?(:[]) && model.respond_to?(:key?) && model.key?(name) result[name] = model[name] end result end end
ruby
def extract_attributes(model) self.class.attributes.reduce({}) do |result, name| if model.respond_to?(name) result[name] = model.public_send(name) elsif model.respond_to?(:[]) && model.respond_to?(:key?) && model.key?(name) result[name] = model[name] end result end end
[ "def", "extract_attributes", "(", "model", ")", "self", ".", "class", ".", "attributes", ".", "reduce", "(", "{", "}", ")", "do", "|", "result", ",", "name", "|", "if", "model", ".", "respond_to?", "(", "name", ")", "result", "[", "name", "]", "=", "model", ".", "public_send", "(", "name", ")", "elsif", "model", ".", "respond_to?", "(", ":[]", ")", "&&", "model", ".", "respond_to?", "(", ":key?", ")", "&&", "model", ".", "key?", "(", "name", ")", "result", "[", "name", "]", "=", "model", "[", "name", "]", "end", "result", "end", "end" ]
Extract model attributes into a hash.
[ "Extract", "model", "attributes", "into", "a", "hash", "." ]
97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb
https://github.com/derek-schaefer/virtus_model/blob/97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb/lib/virtus_model/base.rb#L107-L116
1,858
derek-schaefer/virtus_model
lib/virtus_model/base.rb
VirtusModel.Base.validate_associations_many
def validate_associations_many self.class.associations(:many).each do |name| values = attributes[name] || [] values.each.with_index do |value, index| import_errors("#{name}[#{index}]", value) end end end
ruby
def validate_associations_many self.class.associations(:many).each do |name| values = attributes[name] || [] values.each.with_index do |value, index| import_errors("#{name}[#{index}]", value) end end end
[ "def", "validate_associations_many", "self", ".", "class", ".", "associations", "(", ":many", ")", ".", "each", "do", "|", "name", "|", "values", "=", "attributes", "[", "name", "]", "||", "[", "]", "values", ".", "each", ".", "with_index", "do", "|", "value", ",", "index", "|", "import_errors", "(", "\"#{name}[#{index}]\"", ",", "value", ")", "end", "end", "end" ]
Validate "many" associations and import errors.
[ "Validate", "many", "associations", "and", "import", "errors", "." ]
97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb
https://github.com/derek-schaefer/virtus_model/blob/97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb/lib/virtus_model/base.rb#L132-L139
1,859
derek-schaefer/virtus_model
lib/virtus_model/base.rb
VirtusModel.Base.import_errors
def import_errors(name, model) return unless model.respond_to?(:validate) return if model.validate(validation_context) model.errors.each do |field, error| errors.add("#{name}[#{field}]", error) end end
ruby
def import_errors(name, model) return unless model.respond_to?(:validate) return if model.validate(validation_context) model.errors.each do |field, error| errors.add("#{name}[#{field}]", error) end end
[ "def", "import_errors", "(", "name", ",", "model", ")", "return", "unless", "model", ".", "respond_to?", "(", ":validate", ")", "return", "if", "model", ".", "validate", "(", "validation_context", ")", "model", ".", "errors", ".", "each", "do", "|", "field", ",", "error", "|", "errors", ".", "add", "(", "\"#{name}[#{field}]\"", ",", "error", ")", "end", "end" ]
Merge associated errors using the current validation context.
[ "Merge", "associated", "errors", "using", "the", "current", "validation", "context", "." ]
97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb
https://github.com/derek-schaefer/virtus_model/blob/97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb/lib/virtus_model/base.rb#L142-L148
1,860
derek-schaefer/virtus_model
lib/virtus_model/base.rb
VirtusModel.Base.export_values
def export_values(values, options = nil) return if values.nil? values.map { |v| export_value(v, options) } end
ruby
def export_values(values, options = nil) return if values.nil? values.map { |v| export_value(v, options) } end
[ "def", "export_values", "(", "values", ",", "options", "=", "nil", ")", "return", "if", "values", ".", "nil?", "values", ".", "map", "{", "|", "v", "|", "export_value", "(", "v", ",", "options", ")", "}", "end" ]
Export each value with the provided options.
[ "Export", "each", "value", "with", "the", "provided", "options", "." ]
97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb
https://github.com/derek-schaefer/virtus_model/blob/97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb/lib/virtus_model/base.rb#L151-L154
1,861
derek-schaefer/virtus_model
lib/virtus_model/base.rb
VirtusModel.Base.export_value
def export_value(value, options = nil) return if value.nil? value.respond_to?(:export) ? value.export(options) : value end
ruby
def export_value(value, options = nil) return if value.nil? value.respond_to?(:export) ? value.export(options) : value end
[ "def", "export_value", "(", "value", ",", "options", "=", "nil", ")", "return", "if", "value", ".", "nil?", "value", ".", "respond_to?", "(", ":export", ")", "?", "value", ".", "export", "(", "options", ")", ":", "value", "end" ]
Export the value with the provided options.
[ "Export", "the", "value", "with", "the", "provided", "options", "." ]
97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb
https://github.com/derek-schaefer/virtus_model/blob/97f0e9efd58aed76d03cd2eb249a6a2f4eb887cb/lib/virtus_model/base.rb#L157-L160
1,862
rapid7/daemon_runner
lib/daemon_runner/semaphore.rb
DaemonRunner.Semaphore.contender_key
def contender_key(value = 'none') if value.nil? || value.empty? raise ArgumentError, 'Value cannot be empty or nil' end key = "#{prefix}/#{session.id}" ::DaemonRunner::RetryErrors.retry do @contender_key = Diplomat::Lock.acquire(key, session.id, value) end @contender_key end
ruby
def contender_key(value = 'none') if value.nil? || value.empty? raise ArgumentError, 'Value cannot be empty or nil' end key = "#{prefix}/#{session.id}" ::DaemonRunner::RetryErrors.retry do @contender_key = Diplomat::Lock.acquire(key, session.id, value) end @contender_key end
[ "def", "contender_key", "(", "value", "=", "'none'", ")", "if", "value", ".", "nil?", "||", "value", ".", "empty?", "raise", "ArgumentError", ",", "'Value cannot be empty or nil'", "end", "key", "=", "\"#{prefix}/#{session.id}\"", "::", "DaemonRunner", "::", "RetryErrors", ".", "retry", "do", "@contender_key", "=", "Diplomat", "::", "Lock", ".", "acquire", "(", "key", ",", "session", ".", "id", ",", "value", ")", "end", "@contender_key", "end" ]
Create a contender key
[ "Create", "a", "contender", "key" ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/semaphore.rb#L139-L148
1,863
rapid7/daemon_runner
lib/daemon_runner/semaphore.rb
DaemonRunner.Semaphore.semaphore_state
def semaphore_state options = { decode_values: true, recurse: true } @state = Diplomat::Kv.get(prefix, options, :return) decode_semaphore_state unless state.empty? state end
ruby
def semaphore_state options = { decode_values: true, recurse: true } @state = Diplomat::Kv.get(prefix, options, :return) decode_semaphore_state unless state.empty? state end
[ "def", "semaphore_state", "options", "=", "{", "decode_values", ":", "true", ",", "recurse", ":", "true", "}", "@state", "=", "Diplomat", "::", "Kv", ".", "get", "(", "prefix", ",", "options", ",", ":return", ")", "decode_semaphore_state", "unless", "state", ".", "empty?", "state", "end" ]
Get the current semaphore state by fetching all conterder keys and the lock key
[ "Get", "the", "current", "semaphore", "state", "by", "fetching", "all", "conterder", "keys", "and", "the", "lock", "key" ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/semaphore.rb#L152-L157
1,864
rapid7/daemon_runner
lib/daemon_runner/semaphore.rb
DaemonRunner.Semaphore.write_lock
def write_lock index = lock_modify_index.nil? ? 0 : lock_modify_index value = generate_lockfile return true if value == true Diplomat::Kv.put(@lock, value, cas: index) end
ruby
def write_lock index = lock_modify_index.nil? ? 0 : lock_modify_index value = generate_lockfile return true if value == true Diplomat::Kv.put(@lock, value, cas: index) end
[ "def", "write_lock", "index", "=", "lock_modify_index", ".", "nil?", "?", "0", ":", "lock_modify_index", "value", "=", "generate_lockfile", "return", "true", "if", "value", "==", "true", "Diplomat", "::", "Kv", ".", "put", "(", "@lock", ",", "value", ",", "cas", ":", "index", ")", "end" ]
Write a new lock file if the number of contenders is less than `limit` @return [Boolean] `true` if the lock was written succesfully
[ "Write", "a", "new", "lock", "file", "if", "the", "number", "of", "contenders", "is", "less", "than", "limit" ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/semaphore.rb#L183-L188
1,865
rapid7/daemon_runner
lib/daemon_runner/semaphore.rb
DaemonRunner.Semaphore.renew?
def renew? logger.debug("Watching Consul #{prefix} for changes") options = { recurse: true } changes = Diplomat::Kv.get(prefix, options, :wait, :wait) logger.info("Changes on #{prefix} detected") if changes changes rescue StandardError => e logger.error(e) end
ruby
def renew? logger.debug("Watching Consul #{prefix} for changes") options = { recurse: true } changes = Diplomat::Kv.get(prefix, options, :wait, :wait) logger.info("Changes on #{prefix} detected") if changes changes rescue StandardError => e logger.error(e) end
[ "def", "renew?", "logger", ".", "debug", "(", "\"Watching Consul #{prefix} for changes\"", ")", "options", "=", "{", "recurse", ":", "true", "}", "changes", "=", "Diplomat", "::", "Kv", ".", "get", "(", "prefix", ",", "options", ",", ":wait", ",", ":wait", ")", "logger", ".", "info", "(", "\"Changes on #{prefix} detected\"", ")", "if", "changes", "changes", "rescue", "StandardError", "=>", "e", "logger", ".", "error", "(", "e", ")", "end" ]
Start a blocking query on the prefix, if there are changes we need to try to obtain the lock again. @return [Boolean] `true` if there are changes, `false` if the request has timed out
[ "Start", "a", "blocking", "query", "on", "the", "prefix", "if", "there", "are", "changes", "we", "need", "to", "try", "to", "obtain", "the", "lock", "again", "." ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/semaphore.rb#L195-L203
1,866
rapid7/daemon_runner
lib/daemon_runner/semaphore.rb
DaemonRunner.Semaphore.decode_semaphore_state
def decode_semaphore_state lock_key = state.find { |k| k['Key'] == @lock } member_keys = state.delete_if { |k| k['Key'] == @lock } member_keys.map! { |k| k['Key'] } unless lock_key.nil? @lock_modify_index = lock_key['ModifyIndex'] @lock_content = JSON.parse(lock_key['Value']) end @members = member_keys.map { |k| k.split('/')[-1] } end
ruby
def decode_semaphore_state lock_key = state.find { |k| k['Key'] == @lock } member_keys = state.delete_if { |k| k['Key'] == @lock } member_keys.map! { |k| k['Key'] } unless lock_key.nil? @lock_modify_index = lock_key['ModifyIndex'] @lock_content = JSON.parse(lock_key['Value']) end @members = member_keys.map { |k| k.split('/')[-1] } end
[ "def", "decode_semaphore_state", "lock_key", "=", "state", ".", "find", "{", "|", "k", "|", "k", "[", "'Key'", "]", "==", "@lock", "}", "member_keys", "=", "state", ".", "delete_if", "{", "|", "k", "|", "k", "[", "'Key'", "]", "==", "@lock", "}", "member_keys", ".", "map!", "{", "|", "k", "|", "k", "[", "'Key'", "]", "}", "unless", "lock_key", ".", "nil?", "@lock_modify_index", "=", "lock_key", "[", "'ModifyIndex'", "]", "@lock_content", "=", "JSON", ".", "parse", "(", "lock_key", "[", "'Value'", "]", ")", "end", "@members", "=", "member_keys", ".", "map", "{", "|", "k", "|", "k", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "}", "end" ]
Decode raw response from Consul Set `@lock_modify_index`, `@lock_content`, and `@members` @returns [Array] List of members
[ "Decode", "raw", "response", "from", "Consul", "Set" ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/semaphore.rb#L210-L220
1,867
rapid7/daemon_runner
lib/daemon_runner/semaphore.rb
DaemonRunner.Semaphore.prune_members
def prune_members @holders = if lock_exists? holders = lock_content['Holders'] return @holders = [] if holders.nil? holders = holders.keys holders & members else [] end end
ruby
def prune_members @holders = if lock_exists? holders = lock_content['Holders'] return @holders = [] if holders.nil? holders = holders.keys holders & members else [] end end
[ "def", "prune_members", "@holders", "=", "if", "lock_exists?", "holders", "=", "lock_content", "[", "'Holders'", "]", "return", "@holders", "=", "[", "]", "if", "holders", ".", "nil?", "holders", "=", "holders", ".", "keys", "holders", "&", "members", "else", "[", "]", "end", "end" ]
Get the active members from the lock file, removing any _dead_ members. This is accomplished by using the contenders keys(`@members`) to get the list of all alive members. So we can easily remove any nodes that don't appear in that list.
[ "Get", "the", "active", "members", "from", "the", "lock", "file", "removing", "any", "_dead_", "members", ".", "This", "is", "accomplished", "by", "using", "the", "contenders", "keys", "(" ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/semaphore.rb#L231-L240
1,868
rapid7/daemon_runner
lib/daemon_runner/semaphore.rb
DaemonRunner.Semaphore.add_self_to_holders
def add_self_to_holders @holders.uniq! @reset = true if @holders.length == 0 return true if @holders.include? session.id if @holders.length < limit @holders << session.id end end
ruby
def add_self_to_holders @holders.uniq! @reset = true if @holders.length == 0 return true if @holders.include? session.id if @holders.length < limit @holders << session.id end end
[ "def", "add_self_to_holders", "@holders", ".", "uniq!", "@reset", "=", "true", "if", "@holders", ".", "length", "==", "0", "return", "true", "if", "@holders", ".", "include?", "session", ".", "id", "if", "@holders", ".", "length", "<", "limit", "@holders", "<<", "session", ".", "id", "end", "end" ]
Add our session.id to the holders list if holders is less than limit
[ "Add", "our", "session", ".", "id", "to", "the", "holders", "list", "if", "holders", "is", "less", "than", "limit" ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/semaphore.rb#L243-L250
1,869
rapid7/daemon_runner
lib/daemon_runner/semaphore.rb
DaemonRunner.Semaphore.format_holders
def format_holders @holders.uniq! @holders.sort! holders = {} logger.debug "Holders are: #{@holders.join(',')}" @holders.map { |m| holders[m] = true } @holders = holders end
ruby
def format_holders @holders.uniq! @holders.sort! holders = {} logger.debug "Holders are: #{@holders.join(',')}" @holders.map { |m| holders[m] = true } @holders = holders end
[ "def", "format_holders", "@holders", ".", "uniq!", "@holders", ".", "sort!", "holders", "=", "{", "}", "logger", ".", "debug", "\"Holders are: #{@holders.join(',')}\"", "@holders", ".", "map", "{", "|", "m", "|", "holders", "[", "m", "]", "=", "true", "}", "@holders", "=", "holders", "end" ]
Format the list of holders for the lock file
[ "Format", "the", "list", "of", "holders", "for", "the", "lock", "file" ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/semaphore.rb#L262-L269
1,870
rapid7/daemon_runner
lib/daemon_runner/semaphore.rb
DaemonRunner.Semaphore.generate_lockfile
def generate_lockfile if lock_exists? && lock_content['Holders'] == @holders logger.info 'Holders are unchanged, not updating' return true end lockfile_format = { 'Limit' => limit, 'Holders' => @holders } JSON.generate(lockfile_format) end
ruby
def generate_lockfile if lock_exists? && lock_content['Holders'] == @holders logger.info 'Holders are unchanged, not updating' return true end lockfile_format = { 'Limit' => limit, 'Holders' => @holders } JSON.generate(lockfile_format) end
[ "def", "generate_lockfile", "if", "lock_exists?", "&&", "lock_content", "[", "'Holders'", "]", "==", "@holders", "logger", ".", "info", "'Holders are unchanged, not updating'", "return", "true", "end", "lockfile_format", "=", "{", "'Limit'", "=>", "limit", ",", "'Holders'", "=>", "@holders", "}", "JSON", ".", "generate", "(", "lockfile_format", ")", "end" ]
Generate JSON formatted lockfile content, only if the content has changed
[ "Generate", "JSON", "formatted", "lockfile", "content", "only", "if", "the", "content", "has", "changed" ]
dc840aeade0c802739e615718c58d7b243a9f13a
https://github.com/rapid7/daemon_runner/blob/dc840aeade0c802739e615718c58d7b243a9f13a/lib/daemon_runner/semaphore.rb#L272-L282
1,871
richo/juici
lib/juici/build_queue.rb
Juici.BuildQueue.bump!
def bump! return unless @started update_children candidate_children.each do |child| next if @child_pids.any? do |pid| get_build_by_pid(pid).parent == child.parent end # We're good to launch this build Juici.dbgp "Starting another child process" return child.tap do |cld| if pid = cld.build! Juici.dbgp "Started child: #{pid}" @child_pids << pid @builds_by_pid[pid] = cld else Juici.dbgp "Child #{cld} failed to start" bump! # Ruby's recursion isn't great, but re{try,do} may as well be # undefined behaviour here. end end end Juici.dbgp "I have quite enough to do" end
ruby
def bump! return unless @started update_children candidate_children.each do |child| next if @child_pids.any? do |pid| get_build_by_pid(pid).parent == child.parent end # We're good to launch this build Juici.dbgp "Starting another child process" return child.tap do |cld| if pid = cld.build! Juici.dbgp "Started child: #{pid}" @child_pids << pid @builds_by_pid[pid] = cld else Juici.dbgp "Child #{cld} failed to start" bump! # Ruby's recursion isn't great, but re{try,do} may as well be # undefined behaviour here. end end end Juici.dbgp "I have quite enough to do" end
[ "def", "bump!", "return", "unless", "@started", "update_children", "candidate_children", ".", "each", "do", "|", "child", "|", "next", "if", "@child_pids", ".", "any?", "do", "|", "pid", "|", "get_build_by_pid", "(", "pid", ")", ".", "parent", "==", "child", ".", "parent", "end", "# We're good to launch this build", "Juici", ".", "dbgp", "\"Starting another child process\"", "return", "child", ".", "tap", "do", "|", "cld", "|", "if", "pid", "=", "cld", ".", "build!", "Juici", ".", "dbgp", "\"Started child: #{pid}\"", "@child_pids", "<<", "pid", "@builds_by_pid", "[", "pid", "]", "=", "cld", "else", "Juici", ".", "dbgp", "\"Child #{cld} failed to start\"", "bump!", "# Ruby's recursion isn't great, but re{try,do} may as well be", "# undefined behaviour here.", "end", "end", "end", "Juici", ".", "dbgp", "\"I have quite enough to do\"", "end" ]
Magic hook that starts a process if there's a good reason to. Stopgap measure that means you can knock on this if there's a chance we should start a process
[ "Magic", "hook", "that", "starts", "a", "process", "if", "there", "s", "a", "good", "reason", "to", ".", "Stopgap", "measure", "that", "means", "you", "can", "knock", "on", "this", "if", "there", "s", "a", "chance", "we", "should", "start", "a", "process" ]
5649b251a9c8f8c29623fba2fd9fd0b1fc2dbffa
https://github.com/richo/juici/blob/5649b251a9c8f8c29623fba2fd9fd0b1fc2dbffa/lib/juici/build_queue.rb#L56-L80
1,872
mkroman/blur
library/blur/network.rb
Blur.Network.got_message
def got_message message @client.got_message self, message rescue StandardError => exception puts "#{exception.class}: #{exception.message}" puts puts '---' puts exception.backtrace end
ruby
def got_message message @client.got_message self, message rescue StandardError => exception puts "#{exception.class}: #{exception.message}" puts puts '---' puts exception.backtrace end
[ "def", "got_message", "message", "@client", ".", "got_message", "self", ",", "message", "rescue", "StandardError", "=>", "exception", "puts", "\"#{exception.class}: #{exception.message}\"", "puts", "puts", "'---'", "puts", "exception", ".", "backtrace", "end" ]
Forwards the received message to the client instance. Called when the network connection has enough data to form a command.
[ "Forwards", "the", "received", "message", "to", "the", "client", "instance", "." ]
05408fbbaecb33a506c7e7c72da01d2e68848ea9
https://github.com/mkroman/blur/blob/05408fbbaecb33a506c7e7c72da01d2e68848ea9/library/blur/network.rb#L114-L121
1,873
mkroman/blur
library/blur/network.rb
Blur.Network.disconnected!
def disconnected! @channels.each { |_name, channel| channel.users.clear } @channels.clear @users.clear @client.network_connection_closed self end
ruby
def disconnected! @channels.each { |_name, channel| channel.users.clear } @channels.clear @users.clear @client.network_connection_closed self end
[ "def", "disconnected!", "@channels", ".", "each", "{", "|", "_name", ",", "channel", "|", "channel", ".", "users", ".", "clear", "}", "@channels", ".", "clear", "@users", ".", "clear", "@client", ".", "network_connection_closed", "self", "end" ]
Called when the connection was closed.
[ "Called", "when", "the", "connection", "was", "closed", "." ]
05408fbbaecb33a506c7e7c72da01d2e68848ea9
https://github.com/mkroman/blur/blob/05408fbbaecb33a506c7e7c72da01d2e68848ea9/library/blur/network.rb#L176-L182
1,874
mkroman/blur
library/blur/network.rb
Blur.Network.transmit
def transmit name, *arguments message = IRCParser::Message.new command: name.to_s, parameters: arguments if @client.verbose formatted_command = message.command.to_s.ljust 8, ' ' formatted_params = message.parameters.map(&:inspect).join ' ' log "#{'→' ^ :red} #{formatted_command} #{formatted_params}" end @connection.send_data "#{message}\r\n" end
ruby
def transmit name, *arguments message = IRCParser::Message.new command: name.to_s, parameters: arguments if @client.verbose formatted_command = message.command.to_s.ljust 8, ' ' formatted_params = message.parameters.map(&:inspect).join ' ' log "#{'→' ^ :red} #{formatted_command} #{formatted_params}" end @connection.send_data "#{message}\r\n" end
[ "def", "transmit", "name", ",", "*", "arguments", "message", "=", "IRCParser", "::", "Message", ".", "new", "command", ":", "name", ".", "to_s", ",", "parameters", ":", "arguments", "if", "@client", ".", "verbose", "formatted_command", "=", "message", ".", "command", ".", "to_s", ".", "ljust", "8", ",", "' '", "formatted_params", "=", "message", ".", "parameters", ".", "map", "(", ":inspect", ")", ".", "join", "' '", "log", "\"#{'→' ^ :red} #{formatted_command} #{formatted_params}\"", "end", "@connection", ".", "send_data", "\"#{message}\\r\\n\"", "end" ]
Transmit a command to the server. @param [Symbol, String] name the command name. @param [...] arguments all the prepended parameters.
[ "Transmit", "a", "command", "to", "the", "server", "." ]
05408fbbaecb33a506c7e7c72da01d2e68848ea9
https://github.com/mkroman/blur/blob/05408fbbaecb33a506c7e7c72da01d2e68848ea9/library/blur/network.rb#L193-L203
1,875
fiverr/switch_board
lib/switch_board/datasets/redis_dataset.rb
SwitchBoard.RedisDataset.lock_id
def lock_id(locker_uid, id_to_lock, expire_in_sec = 5) now = redis_time @con.multi do @con.zadd("#{LOCK_MAP_KEY}_z", (now + expire_in_sec), id_to_lock) @con.hset("#{LOCK_MAP_KEY}_h", id_to_lock, locker_uid) end end
ruby
def lock_id(locker_uid, id_to_lock, expire_in_sec = 5) now = redis_time @con.multi do @con.zadd("#{LOCK_MAP_KEY}_z", (now + expire_in_sec), id_to_lock) @con.hset("#{LOCK_MAP_KEY}_h", id_to_lock, locker_uid) end end
[ "def", "lock_id", "(", "locker_uid", ",", "id_to_lock", ",", "expire_in_sec", "=", "5", ")", "now", "=", "redis_time", "@con", ".", "multi", "do", "@con", ".", "zadd", "(", "\"#{LOCK_MAP_KEY}_z\"", ",", "(", "now", "+", "expire_in_sec", ")", ",", "id_to_lock", ")", "@con", ".", "hset", "(", "\"#{LOCK_MAP_KEY}_h\"", ",", "id_to_lock", ",", "locker_uid", ")", "end", "end" ]
Locking mechanisem is based on sorted set, sorted set is used to allow a simulation of expiration time on the keys in the map
[ "Locking", "mechanisem", "is", "based", "on", "sorted", "set", "sorted", "set", "is", "used", "to", "allow", "a", "simulation", "of", "expiration", "time", "on", "the", "keys", "in", "the", "map" ]
429a095a39e28257f99ea7125b26b509dd80037c
https://github.com/fiverr/switch_board/blob/429a095a39e28257f99ea7125b26b509dd80037c/lib/switch_board/datasets/redis_dataset.rb#L50-L56
1,876
mkroman/blur
library/blur/client.rb
Blur.Client.connect
def connect networks = @networks.reject &:connected? EventMachine.run do load_scripts! networks.each &:connect EventMachine.error_handler do |exception| log.error "#{exception.message ^ :bold} on line #{exception.line.to_s ^ :bold}" puts exception.backtrace.join "\n" end end end
ruby
def connect networks = @networks.reject &:connected? EventMachine.run do load_scripts! networks.each &:connect EventMachine.error_handler do |exception| log.error "#{exception.message ^ :bold} on line #{exception.line.to_s ^ :bold}" puts exception.backtrace.join "\n" end end end
[ "def", "connect", "networks", "=", "@networks", ".", "reject", ":connected?", "EventMachine", ".", "run", "do", "load_scripts!", "networks", ".", "each", ":connect", "EventMachine", ".", "error_handler", "do", "|", "exception", "|", "log", ".", "error", "\"#{exception.message ^ :bold} on line #{exception.line.to_s ^ :bold}\"", "puts", "exception", ".", "backtrace", ".", "join", "\"\\n\"", "end", "end", "end" ]
Instantiates the client, stores the options, instantiates the networks and then loads available scripts. @param [Hash] options the options for the client. @option options [String] :config_path path to a configuration file. @option options [String] :environment the client environment. Connect to each network available that is not already connected, then proceed to start the run-loop.
[ "Instantiates", "the", "client", "stores", "the", "options", "instantiates", "the", "networks", "and", "then", "loads", "available", "scripts", "." ]
05408fbbaecb33a506c7e7c72da01d2e68848ea9
https://github.com/mkroman/blur/blob/05408fbbaecb33a506c7e7c72da01d2e68848ea9/library/blur/client.rb#L74-L86
1,877
mkroman/blur
library/blur/client.rb
Blur.Client.quit
def quit signal = :SIGINT @networks.each do |network| network.transmit :QUIT, 'Got SIGINT?' network.disconnect end EventMachine.stop end
ruby
def quit signal = :SIGINT @networks.each do |network| network.transmit :QUIT, 'Got SIGINT?' network.disconnect end EventMachine.stop end
[ "def", "quit", "signal", "=", ":SIGINT", "@networks", ".", "each", "do", "|", "network", "|", "network", ".", "transmit", ":QUIT", ",", "'Got SIGINT?'", "network", ".", "disconnect", "end", "EventMachine", ".", "stop", "end" ]
Try to gracefully disconnect from each network, unload all scripts and exit properly. @param [optional, Symbol] signal The signal received by the system, if any.
[ "Try", "to", "gracefully", "disconnect", "from", "each", "network", "unload", "all", "scripts", "and", "exit", "properly", "." ]
05408fbbaecb33a506c7e7c72da01d2e68848ea9
https://github.com/mkroman/blur/blob/05408fbbaecb33a506c7e7c72da01d2e68848ea9/library/blur/client.rb#L114-L121
1,878
mkroman/blur
library/blur/client.rb
Blur.Client.load_scripts!
def load_scripts! scripts_dir = File.expand_path @config['blur']['scripts_dir'] script_file_paths = Dir.glob File.join scripts_dir, '*.rb' # Sort the script file paths by file name so they load by alphabetical # order. # # This will make it possible to create a script called '10_database.rb' # which will be loaded before '20_settings.rb' and non-numeric prefixes # will be loaded after that. script_file_paths = script_file_paths.sort do |a, b| File.basename(a) <=> File.basename(b) end script_file_paths.each { |script_path| load_script_file script_path } initialize_superscripts emit :scripts_loaded end
ruby
def load_scripts! scripts_dir = File.expand_path @config['blur']['scripts_dir'] script_file_paths = Dir.glob File.join scripts_dir, '*.rb' # Sort the script file paths by file name so they load by alphabetical # order. # # This will make it possible to create a script called '10_database.rb' # which will be loaded before '20_settings.rb' and non-numeric prefixes # will be loaded after that. script_file_paths = script_file_paths.sort do |a, b| File.basename(a) <=> File.basename(b) end script_file_paths.each { |script_path| load_script_file script_path } initialize_superscripts emit :scripts_loaded end
[ "def", "load_scripts!", "scripts_dir", "=", "File", ".", "expand_path", "@config", "[", "'blur'", "]", "[", "'scripts_dir'", "]", "script_file_paths", "=", "Dir", ".", "glob", "File", ".", "join", "scripts_dir", ",", "'*.rb'", "# Sort the script file paths by file name so they load by alphabetical", "# order.", "#", "# This will make it possible to create a script called '10_database.rb'", "# which will be loaded before '20_settings.rb' and non-numeric prefixes", "# will be loaded after that.", "script_file_paths", "=", "script_file_paths", ".", "sort", "do", "|", "a", ",", "b", "|", "File", ".", "basename", "(", "a", ")", "<=>", "File", ".", "basename", "(", "b", ")", "end", "script_file_paths", ".", "each", "{", "|", "script_path", "|", "load_script_file", "script_path", "}", "initialize_superscripts", "emit", ":scripts_loaded", "end" ]
Loads all scripts in the script directory.
[ "Loads", "all", "scripts", "in", "the", "script", "directory", "." ]
05408fbbaecb33a506c7e7c72da01d2e68848ea9
https://github.com/mkroman/blur/blob/05408fbbaecb33a506c7e7c72da01d2e68848ea9/library/blur/client.rb#L135-L154
1,879
mkroman/blur
library/blur/client.rb
Blur.Client.load_script_file
def load_script_file file_path load file_path, true rescue Exception => exception warn "The script `#{file_path}' failed to load" warn "#{exception.class}: #{exception.message}" warn '' warn 'Backtrace:', '---', exception.backtrace end
ruby
def load_script_file file_path load file_path, true rescue Exception => exception warn "The script `#{file_path}' failed to load" warn "#{exception.class}: #{exception.message}" warn '' warn 'Backtrace:', '---', exception.backtrace end
[ "def", "load_script_file", "file_path", "load", "file_path", ",", "true", "rescue", "Exception", "=>", "exception", "warn", "\"The script `#{file_path}' failed to load\"", "warn", "\"#{exception.class}: #{exception.message}\"", "warn", "''", "warn", "'Backtrace:'", ",", "'---'", ",", "exception", ".", "backtrace", "end" ]
Loads the given +file_path+ as a Ruby script, wrapping it in an anonymous module to protect our global namespace. @param [String] file_path the path to the ruby script. @raise [Exception] if there was any problems loading the file
[ "Loads", "the", "given", "+", "file_path", "+", "as", "a", "Ruby", "script", "wrapping", "it", "in", "an", "anonymous", "module", "to", "protect", "our", "global", "namespace", "." ]
05408fbbaecb33a506c7e7c72da01d2e68848ea9
https://github.com/mkroman/blur/blob/05408fbbaecb33a506c7e7c72da01d2e68848ea9/library/blur/client.rb#L162-L169
1,880
mkroman/blur
library/blur/client.rb
Blur.Client.unload_scripts!
def unload_scripts! @scripts.each do |name, script| script.__send__ :unloaded if script.respond_to? :unloaded end.clear Blur.reset_scripts! end
ruby
def unload_scripts! @scripts.each do |name, script| script.__send__ :unloaded if script.respond_to? :unloaded end.clear Blur.reset_scripts! end
[ "def", "unload_scripts!", "@scripts", ".", "each", "do", "|", "name", ",", "script", "|", "script", ".", "__send__", ":unloaded", "if", "script", ".", "respond_to?", ":unloaded", "end", ".", "clear", "Blur", ".", "reset_scripts!", "end" ]
Unloads initialized scripts and superscripts. This method will call #unloaded on the instance of each loaded script to give it a chance to clean up any resources.
[ "Unloads", "initialized", "scripts", "and", "superscripts", "." ]
05408fbbaecb33a506c7e7c72da01d2e68848ea9
https://github.com/mkroman/blur/blob/05408fbbaecb33a506c7e7c72da01d2e68848ea9/library/blur/client.rb#L196-L202
1,881
mkroman/blur
library/blur/client.rb
Blur.Client.load_config!
def load_config! config = YAML.load_file @config_path if config.key? @environment @config = config[@environment] @config.deeper_merge! DEFAULT_CONFIG emit :config_load else raise Error, "No configuration found for specified environment `#{@environment}'" end end
ruby
def load_config! config = YAML.load_file @config_path if config.key? @environment @config = config[@environment] @config.deeper_merge! DEFAULT_CONFIG emit :config_load else raise Error, "No configuration found for specified environment `#{@environment}'" end end
[ "def", "load_config!", "config", "=", "YAML", ".", "load_file", "@config_path", "if", "config", ".", "key?", "@environment", "@config", "=", "config", "[", "@environment", "]", "@config", ".", "deeper_merge!", "DEFAULT_CONFIG", "emit", ":config_load", "else", "raise", "Error", ",", "\"No configuration found for specified environment `#{@environment}'\"", "end", "end" ]
Load the user-specified configuration file. @returns true on success, false otherwise.
[ "Load", "the", "user", "-", "specified", "configuration", "file", "." ]
05408fbbaecb33a506c7e7c72da01d2e68848ea9
https://github.com/mkroman/blur/blob/05408fbbaecb33a506c7e7c72da01d2e68848ea9/library/blur/client.rb#L209-L220
1,882
jphager2/mangdown
lib/mangdown/page.rb
Mangdown.Page.setup_path
def setup_path(dir = nil) dir ||= chapter.path dir = Tools.valid_path_name(dir) name = self.name.tr('/', '') file = Dir.entries(dir).find { |f| f[name] } if Dir.exist?(dir) path = Tools.file_join(dir, file || name) @path = Tools.relative_or_absolute_path(path) end
ruby
def setup_path(dir = nil) dir ||= chapter.path dir = Tools.valid_path_name(dir) name = self.name.tr('/', '') file = Dir.entries(dir).find { |f| f[name] } if Dir.exist?(dir) path = Tools.file_join(dir, file || name) @path = Tools.relative_or_absolute_path(path) end
[ "def", "setup_path", "(", "dir", "=", "nil", ")", "dir", "||=", "chapter", ".", "path", "dir", "=", "Tools", ".", "valid_path_name", "(", "dir", ")", "name", "=", "self", ".", "name", ".", "tr", "(", "'/'", ",", "''", ")", "file", "=", "Dir", ".", "entries", "(", "dir", ")", ".", "find", "{", "|", "f", "|", "f", "[", "name", "]", "}", "if", "Dir", ".", "exist?", "(", "dir", ")", "path", "=", "Tools", ".", "file_join", "(", "dir", ",", "file", "||", "name", ")", "@path", "=", "Tools", ".", "relative_or_absolute_path", "(", "path", ")", "end" ]
Set path of page to file path if a file exists or to path without file extension if file is not found. File extensions are appended only after the file has been downloaded.
[ "Set", "path", "of", "page", "to", "file", "path", "if", "a", "file", "exists", "or", "to", "path", "without", "file", "extension", "if", "file", "is", "not", "found", ".", "File", "extensions", "are", "appended", "only", "after", "the", "file", "has", "been", "downloaded", "." ]
d57050f486b92873ca96a15cd20cbc1f468f2a61
https://github.com/jphager2/mangdown/blob/d57050f486b92873ca96a15cd20cbc1f468f2a61/lib/mangdown/page.rb#L33-L40
1,883
DocsWebApps/page_right
lib/page_right/text_helper.rb
PageRight.TextHelper.is_text_in_page?
def is_text_in_page?(content, flag=true) if flag assert page.has_content?("#{content}"), "Error: #{content} not found page !" else assert !page.has_content?("#{content}"), "Error: #{content} found in page !" end end
ruby
def is_text_in_page?(content, flag=true) if flag assert page.has_content?("#{content}"), "Error: #{content} not found page !" else assert !page.has_content?("#{content}"), "Error: #{content} found in page !" end end
[ "def", "is_text_in_page?", "(", "content", ",", "flag", "=", "true", ")", "if", "flag", "assert", "page", ".", "has_content?", "(", "\"#{content}\"", ")", ",", "\"Error: #{content} not found page !\"", "else", "assert", "!", "page", ".", "has_content?", "(", "\"#{content}\"", ")", ",", "\"Error: #{content} found in page !\"", "end", "end" ]
Check that the text 'content' is on the page, set flag to check that it isn't
[ "Check", "that", "the", "text", "content", "is", "on", "the", "page", "set", "flag", "to", "check", "that", "it", "isn", "t" ]
54dacbb7197c0d4371c64ef18f7588843dcc0940
https://github.com/DocsWebApps/page_right/blob/54dacbb7197c0d4371c64ef18f7588843dcc0940/lib/page_right/text_helper.rb#L4-L10
1,884
DocsWebApps/page_right
lib/page_right/text_helper.rb
PageRight.TextHelper.is_text_in_section?
def is_text_in_section?(section, content, flag=true) within("#{section}") do if flag assert page.has_content?("#{content}"), "Error: #{content} not found in #{section} !" else assert !page.has_content?("#{content}"), "Error: #{content} found in #{section} !" end end end
ruby
def is_text_in_section?(section, content, flag=true) within("#{section}") do if flag assert page.has_content?("#{content}"), "Error: #{content} not found in #{section} !" else assert !page.has_content?("#{content}"), "Error: #{content} found in #{section} !" end end end
[ "def", "is_text_in_section?", "(", "section", ",", "content", ",", "flag", "=", "true", ")", "within", "(", "\"#{section}\"", ")", "do", "if", "flag", "assert", "page", ".", "has_content?", "(", "\"#{content}\"", ")", ",", "\"Error: #{content} not found in #{section} !\"", "else", "assert", "!", "page", ".", "has_content?", "(", "\"#{content}\"", ")", ",", "\"Error: #{content} found in #{section} !\"", "end", "end", "end" ]
Check that the text 'content' is within a particular css section, set flag to check that it isn't
[ "Check", "that", "the", "text", "content", "is", "within", "a", "particular", "css", "section", "set", "flag", "to", "check", "that", "it", "isn", "t" ]
54dacbb7197c0d4371c64ef18f7588843dcc0940
https://github.com/DocsWebApps/page_right/blob/54dacbb7197c0d4371c64ef18f7588843dcc0940/lib/page_right/text_helper.rb#L13-L21
1,885
richo/juici
lib/juici/build_environment.rb
Juici.BuildEnvironment.load_json!
def load_json!(json) return true if json == "" loaded_json = JSON.load(json) if loaded_json.is_a? Hash env.merge!(loaded_json) return true end false rescue JSON::ParserError return false end
ruby
def load_json!(json) return true if json == "" loaded_json = JSON.load(json) if loaded_json.is_a? Hash env.merge!(loaded_json) return true end false rescue JSON::ParserError return false end
[ "def", "load_json!", "(", "json", ")", "return", "true", "if", "json", "==", "\"\"", "loaded_json", "=", "JSON", ".", "load", "(", "json", ")", "if", "loaded_json", ".", "is_a?", "Hash", "env", ".", "merge!", "(", "loaded_json", ")", "return", "true", "end", "false", "rescue", "JSON", "::", "ParserError", "return", "false", "end" ]
XXX This is spectacular. Not in the good way
[ "XXX", "This", "is", "spectacular", ".", "Not", "in", "the", "good", "way" ]
5649b251a9c8f8c29623fba2fd9fd0b1fc2dbffa
https://github.com/richo/juici/blob/5649b251a9c8f8c29623fba2fd9fd0b1fc2dbffa/lib/juici/build_environment.rb#L21-L31
1,886
meineerde/rackstash
lib/rackstash/buffer.rb
Rackstash.Buffer.timestamp
def timestamp(time = nil) @timestamp ||= begin time ||= Time.now.utc.freeze time = time.getutc.freeze unless time.utc? && time.frozen? time end end
ruby
def timestamp(time = nil) @timestamp ||= begin time ||= Time.now.utc.freeze time = time.getutc.freeze unless time.utc? && time.frozen? time end end
[ "def", "timestamp", "(", "time", "=", "nil", ")", "@timestamp", "||=", "begin", "time", "||=", "Time", ".", "now", ".", "utc", ".", "freeze", "time", "=", "time", ".", "getutc", ".", "freeze", "unless", "time", ".", "utc?", "&&", "time", ".", "frozen?", "time", "end", "end" ]
Returns the time of the current buffer as an ISO 8601 formatted string. If the timestamp was not yet set on the buffer, it is is set to the the passed `time` or the current time. @example buffer.timestamp # => "2016-10-17T13:37:00.234Z" @param time [Time] an optional time object. If no timestamp was set yet, this time is used @return [String] an ISO 8601 formatted UTC timestamp.
[ "Returns", "the", "time", "of", "the", "current", "buffer", "as", "an", "ISO", "8601", "formatted", "string", ".", "If", "the", "timestamp", "was", "not", "yet", "set", "on", "the", "buffer", "it", "is", "is", "set", "to", "the", "the", "passed", "time", "or", "the", "current", "time", "." ]
b610a2157187dd05ef8d500320aa846234487b01
https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/buffer.rb#L293-L299
1,887
meineerde/rackstash
lib/rackstash/buffer.rb
Rackstash.Buffer.event
def event event = fields.to_h event[FIELD_TAGS] = tags.to_a event[FIELD_MESSAGE] = messages event[FIELD_TIMESTAMP] = timestamp event end
ruby
def event event = fields.to_h event[FIELD_TAGS] = tags.to_a event[FIELD_MESSAGE] = messages event[FIELD_TIMESTAMP] = timestamp event end
[ "def", "event", "event", "=", "fields", ".", "to_h", "event", "[", "FIELD_TAGS", "]", "=", "tags", ".", "to_a", "event", "[", "FIELD_MESSAGE", "]", "=", "messages", "event", "[", "FIELD_TIMESTAMP", "]", "=", "timestamp", "event", "end" ]
Create an event hash from `self`. * It contains the all of the current buffer's logged fields * We add the buffer's tags and add them as an array of strings to the `event['tags']` field. * We add the buffer's list of messages to `event['message']`. This field thus contains an array of {Message} objects. * We add the buffer's timestamp to the `event['@timestamp]` as a `Time` object in UTC. The typical event emitted here looks like this: { "beep" => "boop", "foo" => ["bar", "baz"], "tags" => ["request", "controller#action"], "message" => [ #<Rackstash::Message:0x007f908b4414c0 ...>, #<Rackstash::Message:0x007f908d14aee0 ...> ], "@timestamp" => 2016-10-17 13:37:42 UTC } Note that the resulting hash still contains an Array of {Message}s in the `"message"` field and a `Time` object in the '@timestamp' field. This allows the {Flow}'s components (usually a {Filter} or the {Flow#encoder}) to reject or adapt some messages based on their original attributes, e.g., their severity or timestamp. It is the responsibility of the {Flow#encoder} to correctly format the `"@timestamp"` field. All other fields in the event Hash besides `"message"` and `@timestamp"` are either `Hash`, `Array`, frozen `String`, `Integer` or `Float` objects. All hashes (including nested hashes) use `String` keys. @return [Hash] the event expected by the event {Filter}s.
[ "Create", "an", "event", "hash", "from", "self", "." ]
b610a2157187dd05ef8d500320aa846234487b01
https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/buffer.rb#L336-L343
1,888
williambarry007/caboose-rets
lib/rets/http.rb
RETS.HTTP.url_encode
def url_encode(str) encoded_string = "" str.each_char do |char| case char when "+" encoded_string << "%2b" when "=" encoded_string << "%3d" when "?" encoded_string << "%3f" when "&" encoded_string << "%26" when "%" encoded_string << "%25" when "," encoded_string << "%2C" else encoded_string << char end end encoded_string end
ruby
def url_encode(str) encoded_string = "" str.each_char do |char| case char when "+" encoded_string << "%2b" when "=" encoded_string << "%3d" when "?" encoded_string << "%3f" when "&" encoded_string << "%26" when "%" encoded_string << "%25" when "," encoded_string << "%2C" else encoded_string << char end end encoded_string end
[ "def", "url_encode", "(", "str", ")", "encoded_string", "=", "\"\"", "str", ".", "each_char", "do", "|", "char", "|", "case", "char", "when", "\"+\"", "encoded_string", "<<", "\"%2b\"", "when", "\"=\"", "encoded_string", "<<", "\"%3d\"", "when", "\"?\"", "encoded_string", "<<", "\"%3f\"", "when", "\"&\"", "encoded_string", "<<", "\"%26\"", "when", "\"%\"", "encoded_string", "<<", "\"%25\"", "when", "\",\"", "encoded_string", "<<", "\"%2C\"", "else", "encoded_string", "<<", "char", "end", "end", "encoded_string", "end" ]
Creates a new HTTP instance which will automatically handle authenting to the RETS server.
[ "Creates", "a", "new", "HTTP", "instance", "which", "will", "automatically", "handle", "authenting", "to", "the", "RETS", "server", "." ]
1e7a5a3a1d51558229aeb2aa2c2f573e18727d27
https://github.com/williambarry007/caboose-rets/blob/1e7a5a3a1d51558229aeb2aa2c2f573e18727d27/lib/rets/http.rb#L30-L51
1,889
williambarry007/caboose-rets
lib/rets/http.rb
RETS.HTTP.save_digest
def save_digest(header) @request_count = 0 @digest = {} header.split(",").each do |line| k, v = line.strip.split("=", 2) @digest[k] = (k != "algorithm" and k != "stale") && v[1..-2] || v end @digest_type = @digest["qop"] ? @digest["qop"].split(",") : [] end
ruby
def save_digest(header) @request_count = 0 @digest = {} header.split(",").each do |line| k, v = line.strip.split("=", 2) @digest[k] = (k != "algorithm" and k != "stale") && v[1..-2] || v end @digest_type = @digest["qop"] ? @digest["qop"].split(",") : [] end
[ "def", "save_digest", "(", "header", ")", "@request_count", "=", "0", "@digest", "=", "{", "}", "header", ".", "split", "(", "\",\"", ")", ".", "each", "do", "|", "line", "|", "k", ",", "v", "=", "line", ".", "strip", ".", "split", "(", "\"=\"", ",", "2", ")", "@digest", "[", "k", "]", "=", "(", "k", "!=", "\"algorithm\"", "and", "k", "!=", "\"stale\"", ")", "&&", "v", "[", "1", "..", "-", "2", "]", "||", "v", "end", "@digest_type", "=", "@digest", "[", "\"qop\"", "]", "?", "@digest", "[", "\"qop\"", "]", ".", "split", "(", "\",\"", ")", ":", "[", "]", "end" ]
Creates and manages the HTTP digest auth if the WWW-Authorization header is passed, then it will overwrite what it knows about the auth data.
[ "Creates", "and", "manages", "the", "HTTP", "digest", "auth", "if", "the", "WWW", "-", "Authorization", "header", "is", "passed", "then", "it", "will", "overwrite", "what", "it", "knows", "about", "the", "auth", "data", "." ]
1e7a5a3a1d51558229aeb2aa2c2f573e18727d27
https://github.com/williambarry007/caboose-rets/blob/1e7a5a3a1d51558229aeb2aa2c2f573e18727d27/lib/rets/http.rb#L67-L77
1,890
williambarry007/caboose-rets
lib/rets/http.rb
RETS.HTTP.create_digest
def create_digest(method, request_uri) # http://en.wikipedia.org/wiki/Digest_access_authentication first = Digest::MD5.hexdigest("#{@config[:username]}:#{@digest["realm"]}:#{@config[:password]}") second = Digest::MD5.hexdigest("#{method}:#{request_uri}") # Using the "newer" authentication QOP if @digest_type.include?("auth") cnonce = Digest::MD5.hexdigest("#{@headers["User-Agent"]}:#{@config[:password]}:#{@request_count}:#{@digest["nonce"]}") hash = Digest::MD5.hexdigest("#{first}:#{@digest["nonce"]}:#{"%08X" % @request_count}:#{cnonce}:#{@digest["qop"]}:#{second}") # Nothing specified, so default to the old one elsif @digest_type.empty? hash = Digest::MD5.hexdigest("#{first}:#{@digest["nonce"]}:#{second}") else raise RETS::HTTPError, "Cannot determine auth type for server (#{@digest_type.join(",")})" end http_digest = "Digest username=\"#{@config[:username]}\", " http_digest << "realm=\"#{@digest["realm"]}\", " http_digest << "nonce=\"#{@digest["nonce"]}\", " http_digest << "uri=\"#{request_uri}\", " http_digest << "algorithm=MD5, " unless @digest_type.empty? http_digest << "response=\"#{hash}\", " http_digest << "opaque=\"#{@digest["opaque"]}\"" unless @digest_type.empty? http_digest << ", " http_digest << "qop=\"#{@digest["qop"]}\", " http_digest << "nc=#{"%08X" % @request_count}, " http_digest << "cnonce=\"#{cnonce}\"" end http_digest end
ruby
def create_digest(method, request_uri) # http://en.wikipedia.org/wiki/Digest_access_authentication first = Digest::MD5.hexdigest("#{@config[:username]}:#{@digest["realm"]}:#{@config[:password]}") second = Digest::MD5.hexdigest("#{method}:#{request_uri}") # Using the "newer" authentication QOP if @digest_type.include?("auth") cnonce = Digest::MD5.hexdigest("#{@headers["User-Agent"]}:#{@config[:password]}:#{@request_count}:#{@digest["nonce"]}") hash = Digest::MD5.hexdigest("#{first}:#{@digest["nonce"]}:#{"%08X" % @request_count}:#{cnonce}:#{@digest["qop"]}:#{second}") # Nothing specified, so default to the old one elsif @digest_type.empty? hash = Digest::MD5.hexdigest("#{first}:#{@digest["nonce"]}:#{second}") else raise RETS::HTTPError, "Cannot determine auth type for server (#{@digest_type.join(",")})" end http_digest = "Digest username=\"#{@config[:username]}\", " http_digest << "realm=\"#{@digest["realm"]}\", " http_digest << "nonce=\"#{@digest["nonce"]}\", " http_digest << "uri=\"#{request_uri}\", " http_digest << "algorithm=MD5, " unless @digest_type.empty? http_digest << "response=\"#{hash}\", " http_digest << "opaque=\"#{@digest["opaque"]}\"" unless @digest_type.empty? http_digest << ", " http_digest << "qop=\"#{@digest["qop"]}\", " http_digest << "nc=#{"%08X" % @request_count}, " http_digest << "cnonce=\"#{cnonce}\"" end http_digest end
[ "def", "create_digest", "(", "method", ",", "request_uri", ")", "# http://en.wikipedia.org/wiki/Digest_access_authentication", "first", "=", "Digest", "::", "MD5", ".", "hexdigest", "(", "\"#{@config[:username]}:#{@digest[\"realm\"]}:#{@config[:password]}\"", ")", "second", "=", "Digest", "::", "MD5", ".", "hexdigest", "(", "\"#{method}:#{request_uri}\"", ")", "# Using the \"newer\" authentication QOP", "if", "@digest_type", ".", "include?", "(", "\"auth\"", ")", "cnonce", "=", "Digest", "::", "MD5", ".", "hexdigest", "(", "\"#{@headers[\"User-Agent\"]}:#{@config[:password]}:#{@request_count}:#{@digest[\"nonce\"]}\"", ")", "hash", "=", "Digest", "::", "MD5", ".", "hexdigest", "(", "\"#{first}:#{@digest[\"nonce\"]}:#{\"%08X\" % @request_count}:#{cnonce}:#{@digest[\"qop\"]}:#{second}\"", ")", "# Nothing specified, so default to the old one", "elsif", "@digest_type", ".", "empty?", "hash", "=", "Digest", "::", "MD5", ".", "hexdigest", "(", "\"#{first}:#{@digest[\"nonce\"]}:#{second}\"", ")", "else", "raise", "RETS", "::", "HTTPError", ",", "\"Cannot determine auth type for server (#{@digest_type.join(\",\")})\"", "end", "http_digest", "=", "\"Digest username=\\\"#{@config[:username]}\\\", \"", "http_digest", "<<", "\"realm=\\\"#{@digest[\"realm\"]}\\\", \"", "http_digest", "<<", "\"nonce=\\\"#{@digest[\"nonce\"]}\\\", \"", "http_digest", "<<", "\"uri=\\\"#{request_uri}\\\", \"", "http_digest", "<<", "\"algorithm=MD5, \"", "unless", "@digest_type", ".", "empty?", "http_digest", "<<", "\"response=\\\"#{hash}\\\", \"", "http_digest", "<<", "\"opaque=\\\"#{@digest[\"opaque\"]}\\\"\"", "unless", "@digest_type", ".", "empty?", "http_digest", "<<", "\", \"", "http_digest", "<<", "\"qop=\\\"#{@digest[\"qop\"]}\\\", \"", "http_digest", "<<", "\"nc=#{\"%08X\" % @request_count}, \"", "http_digest", "<<", "\"cnonce=\\\"#{cnonce}\\\"\"", "end", "http_digest", "end" ]
Creates a HTTP digest header.
[ "Creates", "a", "HTTP", "digest", "header", "." ]
1e7a5a3a1d51558229aeb2aa2c2f573e18727d27
https://github.com/williambarry007/caboose-rets/blob/1e7a5a3a1d51558229aeb2aa2c2f573e18727d27/lib/rets/http.rb#L81-L113
1,891
williambarry007/caboose-rets
lib/rets/http.rb
RETS.HTTP.get_rets_response
def get_rets_response(rets) code, text = nil, nil rets.attributes.each do |attr| key = attr.first.downcase if key == "replycode" code = attr.last.value elsif key == "replytext" text = attr.last.value end end # puts "replycode: #{code}" return code, text end
ruby
def get_rets_response(rets) code, text = nil, nil rets.attributes.each do |attr| key = attr.first.downcase if key == "replycode" code = attr.last.value elsif key == "replytext" text = attr.last.value end end # puts "replycode: #{code}" return code, text end
[ "def", "get_rets_response", "(", "rets", ")", "code", ",", "text", "=", "nil", ",", "nil", "rets", ".", "attributes", ".", "each", "do", "|", "attr", "|", "key", "=", "attr", ".", "first", ".", "downcase", "if", "key", "==", "\"replycode\"", "code", "=", "attr", ".", "last", ".", "value", "elsif", "key", "==", "\"replytext\"", "text", "=", "attr", ".", "last", ".", "value", "end", "end", "# puts \"replycode: #{code}\"", "return", "code", ",", "text", "end" ]
Finds the ReplyText and ReplyCode attributes in the response @param [Nokogiri::XML::NodeSet] rets <RETS> attributes found @return [String] RETS ReplyCode @return [String] RETS ReplyText
[ "Finds", "the", "ReplyText", "and", "ReplyCode", "attributes", "in", "the", "response" ]
1e7a5a3a1d51558229aeb2aa2c2f573e18727d27
https://github.com/williambarry007/caboose-rets/blob/1e7a5a3a1d51558229aeb2aa2c2f573e18727d27/lib/rets/http.rb#L128-L140
1,892
igor-starostenko/tune_spec
lib/tune_spec/instances.rb
TuneSpec.Instances.groups
def groups(name, opts = {}, *args, &block) instance_handler(name, Groups, opts, *args, block) end
ruby
def groups(name, opts = {}, *args, &block) instance_handler(name, Groups, opts, *args, block) end
[ "def", "groups", "(", "name", ",", "opts", "=", "{", "}", ",", "*", "args", ",", "&", "block", ")", "instance_handler", "(", "name", ",", "Groups", ",", "opts", ",", "args", ",", "block", ")", "end" ]
Creates an instance of Group or calls an existing @param name [Symbol, String] the prefix of the Groups object class @param opts [Hash] optional arguments @param args [Any] extra arguments @param block [Block] that yields to self @return [GroupObject] @example groups(:login, {}, 'Main').complete
[ "Creates", "an", "instance", "of", "Group", "or", "calls", "an", "existing" ]
385e078bf618b9409d823ecbbf90334f5173e3a1
https://github.com/igor-starostenko/tune_spec/blob/385e078bf618b9409d823ecbbf90334f5173e3a1/lib/tune_spec/instances.rb#L20-L22
1,893
igor-starostenko/tune_spec
lib/tune_spec/instances.rb
TuneSpec.Instances.steps
def steps(name, opts = {}, *args, &block) opts[:page] && opts[:page] = pages(opts.fetch(:page)) instance_handler(name, Steps, opts, *args, block) end
ruby
def steps(name, opts = {}, *args, &block) opts[:page] && opts[:page] = pages(opts.fetch(:page)) instance_handler(name, Steps, opts, *args, block) end
[ "def", "steps", "(", "name", ",", "opts", "=", "{", "}", ",", "*", "args", ",", "&", "block", ")", "opts", "[", ":page", "]", "&&", "opts", "[", ":page", "]", "=", "pages", "(", "opts", ".", "fetch", "(", ":page", ")", ")", "instance_handler", "(", "name", ",", "Steps", ",", "opts", ",", "args", ",", "block", ")", "end" ]
Creates an instance of Step or calls an existing @param name [Symbol, String] the prefix of the Step object class @param opts [Hash] optional arguments @param args [Any] extra arguments @param block [Block] that yields to self @return [StepObject] @example steps(:calculator, page: :demo).verify_result
[ "Creates", "an", "instance", "of", "Step", "or", "calls", "an", "existing" ]
385e078bf618b9409d823ecbbf90334f5173e3a1
https://github.com/igor-starostenko/tune_spec/blob/385e078bf618b9409d823ecbbf90334f5173e3a1/lib/tune_spec/instances.rb#L33-L36
1,894
igor-starostenko/tune_spec
lib/tune_spec/instances.rb
TuneSpec.Instances.pages
def pages(name, opts = {}, *args, &block) instance_handler(name, Page, opts, *args, block) end
ruby
def pages(name, opts = {}, *args, &block) instance_handler(name, Page, opts, *args, block) end
[ "def", "pages", "(", "name", ",", "opts", "=", "{", "}", ",", "*", "args", ",", "&", "block", ")", "instance_handler", "(", "name", ",", "Page", ",", "opts", ",", "args", ",", "block", ")", "end" ]
Creates an instance of Page or calls an existing @param name [Symbol, String] the prefix of the Page object class @param opts [Hash] optional arguments @param args [Any] extra arguments @param block [Block] that yields to self @return [PageObject] @example pages(:home).click_element
[ "Creates", "an", "instance", "of", "Page", "or", "calls", "an", "existing" ]
385e078bf618b9409d823ecbbf90334f5173e3a1
https://github.com/igor-starostenko/tune_spec/blob/385e078bf618b9409d823ecbbf90334f5173e3a1/lib/tune_spec/instances.rb#L47-L49
1,895
fixrb/matchi
lib/matchi/matchers_base.rb
Matchi.MatchersBase.to_s
def to_s s = matcher_name .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') .gsub(/([a-z\d])([A-Z])/, '\1_\2') .downcase defined?(@expected) ? [s, @expected.inspect].join(' ') : s end
ruby
def to_s s = matcher_name .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') .gsub(/([a-z\d])([A-Z])/, '\1_\2') .downcase defined?(@expected) ? [s, @expected.inspect].join(' ') : s end
[ "def", "to_s", "s", "=", "matcher_name", ".", "gsub", "(", "/", "/", ",", "'\\1_\\2'", ")", ".", "gsub", "(", "/", "\\d", "/", ",", "'\\1_\\2'", ")", ".", "downcase", "defined?", "(", "@expected", ")", "?", "[", "s", ",", "@expected", ".", "inspect", "]", ".", "join", "(", "' '", ")", ":", "s", "end" ]
Returns a string representing the matcher. @example The readable definition of a FooBar matcher. matcher = Matchi::Matchers::FooBar::Matcher.new(42) matcher.to_s # => "foo_bar 42" @return [String] A string representing the matcher.
[ "Returns", "a", "string", "representing", "the", "matcher", "." ]
4ea2eaf339cbc048fffd104ac392c1d2d98c9c16
https://github.com/fixrb/matchi/blob/4ea2eaf339cbc048fffd104ac392c1d2d98c9c16/lib/matchi/matchers_base.rb#L20-L27
1,896
benton/fog_tracker
lib/fog_tracker/tracker.rb
FogTracker.Tracker.query
def query(query_string) results = FogTracker::Query::QueryProcessor.new( @trackers, :logger => @log ).execute(query_string) (results.each {|r| yield r}) if block_given? results end
ruby
def query(query_string) results = FogTracker::Query::QueryProcessor.new( @trackers, :logger => @log ).execute(query_string) (results.each {|r| yield r}) if block_given? results end
[ "def", "query", "(", "query_string", ")", "results", "=", "FogTracker", "::", "Query", "::", "QueryProcessor", ".", "new", "(", "@trackers", ",", ":logger", "=>", "@log", ")", ".", "execute", "(", "query_string", ")", "(", "results", ".", "each", "{", "|", "r", "|", "yield", "r", "}", ")", "if", "block_given?", "results", "end" ]
Returns an array of Resources matching the query_string. Calls any block passed for each resulting resource. @param [String] query_string a string used to filter for matching resources it might look like: "Account Name::Compute::AWS::servers" @return [Array <Fog::Model>] an Array of Resources, filtered by query
[ "Returns", "an", "array", "of", "Resources", "matching", "the", "query_string", ".", "Calls", "any", "block", "passed", "for", "each", "resulting", "resource", "." ]
73fdf35dd76ff1b1fc448698f2761ebfbea52e0e
https://github.com/benton/fog_tracker/blob/73fdf35dd76ff1b1fc448698f2761ebfbea52e0e/lib/fog_tracker/tracker.rb#L78-L84
1,897
benton/fog_tracker
lib/fog_tracker/tracker.rb
FogTracker.Tracker.accounts=
def accounts=(new_accounts) old_accounts = @accounts @accounts = FogTracker.validate_accounts(new_accounts) if (@accounts != old_accounts) stop if (was_running = running?) create_trackers start if was_running end @accounts end
ruby
def accounts=(new_accounts) old_accounts = @accounts @accounts = FogTracker.validate_accounts(new_accounts) if (@accounts != old_accounts) stop if (was_running = running?) create_trackers start if was_running end @accounts end
[ "def", "accounts", "=", "(", "new_accounts", ")", "old_accounts", "=", "@accounts", "@accounts", "=", "FogTracker", ".", "validate_accounts", "(", "new_accounts", ")", "if", "(", "@accounts", "!=", "old_accounts", ")", "stop", "if", "(", "was_running", "=", "running?", ")", "create_trackers", "start", "if", "was_running", "end", "@accounts", "end" ]
Sets the account information. If any account info has changed, all trackers are restarted. @param [Hash] accounts a Hash of account information (see accounts.example.yml)
[ "Sets", "the", "account", "information", ".", "If", "any", "account", "info", "has", "changed", "all", "trackers", "are", "restarted", "." ]
73fdf35dd76ff1b1fc448698f2761ebfbea52e0e
https://github.com/benton/fog_tracker/blob/73fdf35dd76ff1b1fc448698f2761ebfbea52e0e/lib/fog_tracker/tracker.rb#L109-L118
1,898
benton/fog_tracker
lib/fog_tracker/tracker.rb
FogTracker.Tracker.create_trackers
def create_trackers @trackers = Hash.new @accounts.each do |name, account| @log.debug "Setting up tracker for account #{name}" @trackers[name] = AccountTracker.new(name, account, { :delay => @delay, :error_callback => @error_proc, :logger => @log, :callback => Proc.new do |resources| # attach a QueryProcessor to all returned resources qp = FogTracker::Query::QueryProcessor.new(@trackers, :logger => @log) resources.each {|resource| resource._query_processor = qp} # now relay the resources back to the client software @callback.call(resources) if @callback end } ) end end
ruby
def create_trackers @trackers = Hash.new @accounts.each do |name, account| @log.debug "Setting up tracker for account #{name}" @trackers[name] = AccountTracker.new(name, account, { :delay => @delay, :error_callback => @error_proc, :logger => @log, :callback => Proc.new do |resources| # attach a QueryProcessor to all returned resources qp = FogTracker::Query::QueryProcessor.new(@trackers, :logger => @log) resources.each {|resource| resource._query_processor = qp} # now relay the resources back to the client software @callback.call(resources) if @callback end } ) end end
[ "def", "create_trackers", "@trackers", "=", "Hash", ".", "new", "@accounts", ".", "each", "do", "|", "name", ",", "account", "|", "@log", ".", "debug", "\"Setting up tracker for account #{name}\"", "@trackers", "[", "name", "]", "=", "AccountTracker", ".", "new", "(", "name", ",", "account", ",", "{", ":delay", "=>", "@delay", ",", ":error_callback", "=>", "@error_proc", ",", ":logger", "=>", "@log", ",", ":callback", "=>", "Proc", ".", "new", "do", "|", "resources", "|", "# attach a QueryProcessor to all returned resources", "qp", "=", "FogTracker", "::", "Query", "::", "QueryProcessor", ".", "new", "(", "@trackers", ",", ":logger", "=>", "@log", ")", "resources", ".", "each", "{", "|", "resource", "|", "resource", ".", "_query_processor", "=", "qp", "}", "# now relay the resources back to the client software", "@callback", ".", "call", "(", "resources", ")", "if", "@callback", "end", "}", ")", "end", "end" ]
Creates a Hash of AccountTracker objects, indexed by account name
[ "Creates", "a", "Hash", "of", "AccountTracker", "objects", "indexed", "by", "account", "name" ]
73fdf35dd76ff1b1fc448698f2761ebfbea52e0e
https://github.com/benton/fog_tracker/blob/73fdf35dd76ff1b1fc448698f2761ebfbea52e0e/lib/fog_tracker/tracker.rb#L123-L139
1,899
meineerde/rackstash
lib/rackstash/logger.rb
Rackstash.Logger.<<
def <<(msg) buffer.add_message Message.new( msg, time: Time.now.utc.freeze, progname: @progname, severity: UNKNOWN ) msg end
ruby
def <<(msg) buffer.add_message Message.new( msg, time: Time.now.utc.freeze, progname: @progname, severity: UNKNOWN ) msg end
[ "def", "<<", "(", "msg", ")", "buffer", ".", "add_message", "Message", ".", "new", "(", "msg", ",", "time", ":", "Time", ".", "now", ".", "utc", ".", "freeze", ",", "progname", ":", "@progname", ",", "severity", ":", "UNKNOWN", ")", "msg", "end" ]
Create a new Logger instance. We mostly follow the common interface of Ruby's core Logger class with the exception that you can give one or more flows to write logs to. Each {Flow} is responsible to write a log event (e.g. to a file, STDOUT, a TCP socket, ...). Each log event is written to all defined {#flows}. When giving the flows here, you can given them in one of varous representations, all of which we will transform into an actual {Flow}: * A {Rackstash::Flow} object. For the most control over the flow, you can create the {Flow} object on your own and pass it here * A {Rackstash::Adapter::Adapter}. When passing an adapter, we will create a new {Flow} from this adapter, using its default encoder and without any defined filters. * An log device from which we can create an adapter. In this case, we first attempt to build an adapter from it using {Rackstash::Adapter.[]}. After that, we use it to create a {Flow} as above. When passing a block to this initializer, we will yield the last created flow object to it. If you pass multiple log devices / adapters / flows, only the last one will be yielded. If the block doesn't expect an argument, we run the block in the instance scope of the flow. The following three example to create a custom Logger are thus equivalent: logger = Rackstash::Logger.new(STDOUT) do encoder Rackstash::Encoder::Message.new end logger = Rackstash::Logger.new(Rackstash::Adapter::IO.new(STDOUT)) do encoder Rackstash::Encoder::Message.new end adapter = Rackstash::Adapter::IO.new(STDOUT) flow = Rackstash::Flows.new(adapter) do encoder Rackstash::Encoder::Message.new end logger = Rackstash::Logger.new(flow) To create a simple Logger which logs to `STDOUT` using the default JSON format, you can just use logger = Rackstash::Logger.new(STDOUT) @param flows [Array<Flow, Object>, Flow, Adapter::Adapter, Object] an array of {Flow}s or a single {Flow}, respectivly object which can be used as a {Flow}'s adapter. See {Flow#initialize}. @param level [Integer] a numeric log level. Normally you'd use one of the {SEVERITIES} constants, i.e., an integer between 0 and 5. We will only log messages with a severity above the configured level. @param progname [String] the logger's progname, used as the default for log messages if none is passed to {#add} and passed to the {#formatter}. By default we use {PROGNAME}. @param formatter [#call] the log formatter for each individual buffered line. See {#formatter} for details. @yieldparam flow [Rackstash::Flow] if the given block accepts an argument, we yield the last {Flow} as a parameter. Without an expected argument, the block is directly executed in the context of the last {Flow}. Add a message to the current {Buffer} without any further formatting. If the current buffer is bufering, the message will just be added. Else, it will be flushed to the configured {#flows} directly. @param msg [Object] @return [String] the passed `msg`
[ "Create", "a", "new", "Logger", "instance", "." ]
b610a2157187dd05ef8d500320aa846234487b01
https://github.com/meineerde/rackstash/blob/b610a2157187dd05ef8d500320aa846234487b01/lib/rackstash/logger.rb#L132-L140