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
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
6,600
akerl/basiccache
lib/basiccache/caches/timecache.rb
BasicCache.TimeCache.prune
def prune @store.keys.reject { |k| include? k }.map { |k| clear!(k) && k } end
ruby
def prune @store.keys.reject { |k| include? k }.map { |k| clear!(k) && k } end
[ "def", "prune", "@store", ".", "keys", ".", "reject", "{", "|", "k", "|", "include?", "k", "}", ".", "map", "{", "|", "k", "|", "clear!", "(", "k", ")", "&&", "k", "}", "end" ]
Prune expired keys
[ "Prune", "expired", "keys" ]
ac9c60218f2479aedf7f398f1dc2bae70b6d7fa3
https://github.com/akerl/basiccache/blob/ac9c60218f2479aedf7f398f1dc2bae70b6d7fa3/lib/basiccache/caches/timecache.rb#L73-L75
6,601
Raynes/rubyheap
lib/rubyheap/rubyheap.rb
Refheap.Paste.create
def create(contents, params = {:language => "Plain Text", :private => false}) params = params.merge({:contents => contents}.merge(@base_params)) self.class.post("/paste", :body => params).parsed_response end
ruby
def create(contents, params = {:language => "Plain Text", :private => false}) params = params.merge({:contents => contents}.merge(@base_params)) self.class.post("/paste", :body => params).parsed_response end
[ "def", "create", "(", "contents", ",", "params", "=", "{", ":language", "=>", "\"Plain Text\"", ",", ":private", "=>", "false", "}", ")", "params", "=", "params", ".", "merge", "(", "{", ":contents", "=>", "contents", "}", ".", "merge", "(", "@base_params", ")", ")", "self", ".", "class", ".", "post", "(", "\"/paste\"", ",", ":body", "=>", "params", ")", ".", "parsed_response", "end" ]
Create a new paste. If language isn't provided, it defaults to "Plain Text". If private isn't provided, it defaults to false.
[ "Create", "a", "new", "paste", ".", "If", "language", "isn", "t", "provided", "it", "defaults", "to", "Plain", "Text", ".", "If", "private", "isn", "t", "provided", "it", "defaults", "to", "false", "." ]
0f1c258b7643563b2d3e5dbccb3372a82e66c077
https://github.com/Raynes/rubyheap/blob/0f1c258b7643563b2d3e5dbccb3372a82e66c077/lib/rubyheap/rubyheap.rb#L29-L32
6,602
miguelzf/zomato2
lib/zomato2/restaurant.rb
Zomato2.Restaurant.details
def details(start: nil, count: nil) # warn "\tRestaurant#details: This method is currently useless, since, " + # "as of January 2017, Zomato's API doesn't give any additional info here." q = {res_id: @id } q[:start] = start if start q[:count] = count if count results = get('restaurant', q) @location ||= Location.new zom_conn, attributes["location"] @city_id ||= @location.city_id results.each do |k,v| if k == 'apikey' next elsif k == 'R' @id = v['res_id'] # Zomato never returns this?? bad API doc! elsif k == 'location' next elsif k == 'all_reviews' @reviews ||= v.map{ |r| Review.new(zom_conn, r) } elsif k == 'establishment_types' @establishments ||= v.map{ |e,ev| Establishment.new(zom_conn, @city_id, ev) } # elsif k == 'cuisines' the returned cuisines here are just a string.. else #puts "ATTR @#{k} val #{v}" self.instance_variable_set("@#{k}", v) end end self end
ruby
def details(start: nil, count: nil) # warn "\tRestaurant#details: This method is currently useless, since, " + # "as of January 2017, Zomato's API doesn't give any additional info here." q = {res_id: @id } q[:start] = start if start q[:count] = count if count results = get('restaurant', q) @location ||= Location.new zom_conn, attributes["location"] @city_id ||= @location.city_id results.each do |k,v| if k == 'apikey' next elsif k == 'R' @id = v['res_id'] # Zomato never returns this?? bad API doc! elsif k == 'location' next elsif k == 'all_reviews' @reviews ||= v.map{ |r| Review.new(zom_conn, r) } elsif k == 'establishment_types' @establishments ||= v.map{ |e,ev| Establishment.new(zom_conn, @city_id, ev) } # elsif k == 'cuisines' the returned cuisines here are just a string.. else #puts "ATTR @#{k} val #{v}" self.instance_variable_set("@#{k}", v) end end self end
[ "def", "details", "(", "start", ":", "nil", ",", "count", ":", "nil", ")", "# warn \"\\tRestaurant#details: This method is currently useless, since, \" +", "# \"as of January 2017, Zomato's API doesn't give any additional info here.\"", "q", "=", "{", "res_id", ":", "@id", "}", "q", "[", ":start", "]", "=", "start", "if", "start", "q", "[", ":count", "]", "=", "count", "if", "count", "results", "=", "get", "(", "'restaurant'", ",", "q", ")", "@location", "||=", "Location", ".", "new", "zom_conn", ",", "attributes", "[", "\"location\"", "]", "@city_id", "||=", "@location", ".", "city_id", "results", ".", "each", "do", "|", "k", ",", "v", "|", "if", "k", "==", "'apikey'", "next", "elsif", "k", "==", "'R'", "@id", "=", "v", "[", "'res_id'", "]", "# Zomato never returns this?? bad API doc!", "elsif", "k", "==", "'location'", "next", "elsif", "k", "==", "'all_reviews'", "@reviews", "||=", "v", ".", "map", "{", "|", "r", "|", "Review", ".", "new", "(", "zom_conn", ",", "r", ")", "}", "elsif", "k", "==", "'establishment_types'", "@establishments", "||=", "v", ".", "map", "{", "|", "e", ",", "ev", "|", "Establishment", ".", "new", "(", "zom_conn", ",", "@city_id", ",", "ev", ")", "}", "# elsif k == 'cuisines' the returned cuisines here are just a string..", "else", "#puts \"ATTR @#{k} val #{v}\"", "self", ".", "instance_variable_set", "(", "\"@#{k}\"", ",", "v", ")", "end", "end", "self", "end" ]
this doesn't actually give any more detailed info..
[ "this", "doesn", "t", "actually", "give", "any", "more", "detailed", "info", ".." ]
487d64af68a8b0f2735fe13edda3c4e9259504e6
https://github.com/miguelzf/zomato2/blob/487d64af68a8b0f2735fe13edda3c4e9259504e6/lib/zomato2/restaurant.rb#L55-L86
6,603
barkerest/barkest_core
app/helpers/barkest_core/form_helper.rb
BarkestCore.FormHelper.label_with_small
def label_with_small(f, method, text=nil, options = {}, &block) if text.is_a?(Hash) options = text text = nil end small_text = options.delete(:small_text) text = text || options.delete(:text) || method.to_s.humanize.capitalize lbl = f.label(method, text, options, &block) #do # contents = text # contents += "<small>#{h small_text}</small>" if small_text # contents += yield if block_given? # contents.html_safe #end lbl += "&nbsp;<small>(#{h small_text})</small>".html_safe if small_text lbl.html_safe end
ruby
def label_with_small(f, method, text=nil, options = {}, &block) if text.is_a?(Hash) options = text text = nil end small_text = options.delete(:small_text) text = text || options.delete(:text) || method.to_s.humanize.capitalize lbl = f.label(method, text, options, &block) #do # contents = text # contents += "<small>#{h small_text}</small>" if small_text # contents += yield if block_given? # contents.html_safe #end lbl += "&nbsp;<small>(#{h small_text})</small>".html_safe if small_text lbl.html_safe end
[ "def", "label_with_small", "(", "f", ",", "method", ",", "text", "=", "nil", ",", "options", "=", "{", "}", ",", "&", "block", ")", "if", "text", ".", "is_a?", "(", "Hash", ")", "options", "=", "text", "text", "=", "nil", "end", "small_text", "=", "options", ".", "delete", "(", ":small_text", ")", "text", "=", "text", "||", "options", ".", "delete", "(", ":text", ")", "||", "method", ".", "to_s", ".", "humanize", ".", "capitalize", "lbl", "=", "f", ".", "label", "(", "method", ",", "text", ",", "options", ",", "block", ")", "#do", "# contents = text", "# contents += \"<small>#{h small_text}</small>\" if small_text", "# contents += yield if block_given?", "# contents.html_safe", "#end", "lbl", "+=", "\"&nbsp;<small>(#{h small_text})</small>\"", ".", "html_safe", "if", "small_text", "lbl", ".", "html_safe", "end" ]
Creates a label followed by small text. Set the :small_text option to include small text.
[ "Creates", "a", "label", "followed", "by", "small", "text", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/helpers/barkest_core/form_helper.rb#L215-L230
6,604
barkerest/barkest_core
app/helpers/barkest_core/form_helper.rb
BarkestCore.FormHelper.text_form_group
def text_form_group(f, method, options = {}) gopt, lopt, fopt = split_form_group_options(options) lbl = f.label_with_small method, lopt.delete(:text), lopt fld = gopt[:wrap].call(f.text_field(method, fopt)) form_group lbl, fld, gopt end
ruby
def text_form_group(f, method, options = {}) gopt, lopt, fopt = split_form_group_options(options) lbl = f.label_with_small method, lopt.delete(:text), lopt fld = gopt[:wrap].call(f.text_field(method, fopt)) form_group lbl, fld, gopt end
[ "def", "text_form_group", "(", "f", ",", "method", ",", "options", "=", "{", "}", ")", "gopt", ",", "lopt", ",", "fopt", "=", "split_form_group_options", "(", "options", ")", "lbl", "=", "f", ".", "label_with_small", "method", ",", "lopt", ".", "delete", "(", ":text", ")", ",", "lopt", "fld", "=", "gopt", "[", ":wrap", "]", ".", "call", "(", "f", ".", "text_field", "(", "method", ",", "fopt", ")", ")", "form_group", "lbl", ",", "fld", ",", "gopt", "end" ]
Creates a form group including a label and a text field. To specify a label, set the +label_text+ option, otherwise the method name will be used. Prefix field options with +field_+ and label options with +label_+. Any additional options are passed to the form group.
[ "Creates", "a", "form", "group", "including", "a", "label", "and", "a", "text", "field", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/helpers/barkest_core/form_helper.rb#L238-L243
6,605
barkerest/barkest_core
app/helpers/barkest_core/form_helper.rb
BarkestCore.FormHelper.multi_input_form_group
def multi_input_form_group(f, methods, options = {}) gopt, lopt, fopt = split_form_group_options(options) lopt[:text] ||= gopt[:label] if lopt[:text].blank? lopt[:text] = methods.map {|k,_| k.to_s.humanize }.join(', ') end lbl = f.label_with_small methods.map{|k,_| k}.first, lopt[:text], lopt fld = gopt[:wrap].call(multi_input_field(f, methods, fopt)) form_group lbl, fld, gopt end
ruby
def multi_input_form_group(f, methods, options = {}) gopt, lopt, fopt = split_form_group_options(options) lopt[:text] ||= gopt[:label] if lopt[:text].blank? lopt[:text] = methods.map {|k,_| k.to_s.humanize }.join(', ') end lbl = f.label_with_small methods.map{|k,_| k}.first, lopt[:text], lopt fld = gopt[:wrap].call(multi_input_field(f, methods, fopt)) form_group lbl, fld, gopt end
[ "def", "multi_input_form_group", "(", "f", ",", "methods", ",", "options", "=", "{", "}", ")", "gopt", ",", "lopt", ",", "fopt", "=", "split_form_group_options", "(", "options", ")", "lopt", "[", ":text", "]", "||=", "gopt", "[", ":label", "]", "if", "lopt", "[", ":text", "]", ".", "blank?", "lopt", "[", ":text", "]", "=", "methods", ".", "map", "{", "|", "k", ",", "_", "|", "k", ".", "to_s", ".", "humanize", "}", ".", "join", "(", "', '", ")", "end", "lbl", "=", "f", ".", "label_with_small", "methods", ".", "map", "{", "|", "k", ",", "_", "|", "k", "}", ".", "first", ",", "lopt", "[", ":text", "]", ",", "lopt", "fld", "=", "gopt", "[", ":wrap", "]", ".", "call", "(", "multi_input_field", "(", "f", ",", "methods", ",", "fopt", ")", ")", "form_group", "lbl", ",", "fld", ",", "gopt", "end" ]
Creates a form group including a label and a multiple input field. To specify a label, set the +label_text+ option, otherwise the method name will be used. Prefix field options with +field_+ and label options with +label_+. Any additional options are passed to the form group.
[ "Creates", "a", "form", "group", "including", "a", "label", "and", "a", "multiple", "input", "field", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/helpers/barkest_core/form_helper.rb#L304-L313
6,606
barkerest/barkest_core
app/helpers/barkest_core/form_helper.rb
BarkestCore.FormHelper.checkbox_form_group
def checkbox_form_group(f, method, options = {}) gopt, lopt, fopt = split_form_group_options({ class: 'checkbox', field_class: ''}.merge(options)) if gopt[:h_align] gopt[:class] = gopt[:class].blank? ? "col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}" : "#{gopt[:class]} col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}" end lbl = f.label method do f.check_box(method, fopt) + h(lopt[:text] || method.to_s.humanize) + if lopt[:small_text] "<small>#{h lopt[:small_text]}</small>" else '' end.html_safe end "<div class=\"#{gopt[:h_align] ? 'row' : 'form-group'}\"><div class=\"#{gopt[:class]}\">#{lbl}</div></div>".html_safe end
ruby
def checkbox_form_group(f, method, options = {}) gopt, lopt, fopt = split_form_group_options({ class: 'checkbox', field_class: ''}.merge(options)) if gopt[:h_align] gopt[:class] = gopt[:class].blank? ? "col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}" : "#{gopt[:class]} col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}" end lbl = f.label method do f.check_box(method, fopt) + h(lopt[:text] || method.to_s.humanize) + if lopt[:small_text] "<small>#{h lopt[:small_text]}</small>" else '' end.html_safe end "<div class=\"#{gopt[:h_align] ? 'row' : 'form-group'}\"><div class=\"#{gopt[:class]}\">#{lbl}</div></div>".html_safe end
[ "def", "checkbox_form_group", "(", "f", ",", "method", ",", "options", "=", "{", "}", ")", "gopt", ",", "lopt", ",", "fopt", "=", "split_form_group_options", "(", "{", "class", ":", "'checkbox'", ",", "field_class", ":", "''", "}", ".", "merge", "(", "options", ")", ")", "if", "gopt", "[", ":h_align", "]", "gopt", "[", ":class", "]", "=", "gopt", "[", ":class", "]", ".", "blank?", "?", "\"col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}\"", ":", "\"#{gopt[:class]} col-sm-#{12-gopt[:h_align]} col-sm-offset-#{gopt[:h_align]}\"", "end", "lbl", "=", "f", ".", "label", "method", "do", "f", ".", "check_box", "(", "method", ",", "fopt", ")", "+", "h", "(", "lopt", "[", ":text", "]", "||", "method", ".", "to_s", ".", "humanize", ")", "+", "if", "lopt", "[", ":small_text", "]", "\"<small>#{h lopt[:small_text]}</small>\"", "else", "''", "end", ".", "html_safe", "end", "\"<div class=\\\"#{gopt[:h_align] ? 'row' : 'form-group'}\\\"><div class=\\\"#{gopt[:class]}\\\">#{lbl}</div></div>\"", ".", "html_safe", "end" ]
Creates a form group including a label and a checkbox. To specify a label, set the +label_text+ option, otherwise the method name will be used. Prefix field options with +field_+ and label options with +label_+. Any additional options are passed to the form group.
[ "Creates", "a", "form", "group", "including", "a", "label", "and", "a", "checkbox", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/helpers/barkest_core/form_helper.rb#L321-L341
6,607
barkerest/barkest_core
app/helpers/barkest_core/form_helper.rb
BarkestCore.FormHelper.select_form_group
def select_form_group(f, method, collection, value_method = nil, text_method = nil, options = {}) gopt, lopt, fopt = split_form_group_options({ field_include_blank: true }.merge(options)) lbl = f.label_with_small method, lopt.delete(:text), lopt value_method ||= :to_s text_method ||= :to_s opt = {} [:include_blank, :prompt, :include_hidden].each do |attr| if fopt[attr] != nil opt[attr] = fopt[attr] fopt.except! attr end end fld = gopt[:wrap].call(f.collection_select(method, collection, value_method, text_method, opt, fopt)) form_group lbl, fld, gopt end
ruby
def select_form_group(f, method, collection, value_method = nil, text_method = nil, options = {}) gopt, lopt, fopt = split_form_group_options({ field_include_blank: true }.merge(options)) lbl = f.label_with_small method, lopt.delete(:text), lopt value_method ||= :to_s text_method ||= :to_s opt = {} [:include_blank, :prompt, :include_hidden].each do |attr| if fopt[attr] != nil opt[attr] = fopt[attr] fopt.except! attr end end fld = gopt[:wrap].call(f.collection_select(method, collection, value_method, text_method, opt, fopt)) form_group lbl, fld, gopt end
[ "def", "select_form_group", "(", "f", ",", "method", ",", "collection", ",", "value_method", "=", "nil", ",", "text_method", "=", "nil", ",", "options", "=", "{", "}", ")", "gopt", ",", "lopt", ",", "fopt", "=", "split_form_group_options", "(", "{", "field_include_blank", ":", "true", "}", ".", "merge", "(", "options", ")", ")", "lbl", "=", "f", ".", "label_with_small", "method", ",", "lopt", ".", "delete", "(", ":text", ")", ",", "lopt", "value_method", "||=", ":to_s", "text_method", "||=", ":to_s", "opt", "=", "{", "}", "[", ":include_blank", ",", ":prompt", ",", ":include_hidden", "]", ".", "each", "do", "|", "attr", "|", "if", "fopt", "[", "attr", "]", "!=", "nil", "opt", "[", "attr", "]", "=", "fopt", "[", "attr", "]", "fopt", ".", "except!", "attr", "end", "end", "fld", "=", "gopt", "[", ":wrap", "]", ".", "call", "(", "f", ".", "collection_select", "(", "method", ",", "collection", ",", "value_method", ",", "text_method", ",", "opt", ",", "fopt", ")", ")", "form_group", "lbl", ",", "fld", ",", "gopt", "end" ]
Creates a form group including a label and a collection select field. To specify a label, set the +label_text+ option, otherwise the method name will be used. Prefix field options with +field_+ and label options with +label_+. Any additional options are passed to the form group.
[ "Creates", "a", "form", "group", "including", "a", "label", "and", "a", "collection", "select", "field", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/helpers/barkest_core/form_helper.rb#L349-L363
6,608
codescrum/bebox
lib/bebox/commands/node_commands.rb
Bebox.NodeCommands.generate_node_command
def generate_node_command(node_command, command, send_command, description) node_command.desc description node_command.command command do |generated_command| generated_command.action do |global_options,options,args| environment = get_environment(options) info _('cli.current_environment')%{environment: environment} Bebox::NodeWizard.new.send(send_command, project_root, environment) end end end
ruby
def generate_node_command(node_command, command, send_command, description) node_command.desc description node_command.command command do |generated_command| generated_command.action do |global_options,options,args| environment = get_environment(options) info _('cli.current_environment')%{environment: environment} Bebox::NodeWizard.new.send(send_command, project_root, environment) end end end
[ "def", "generate_node_command", "(", "node_command", ",", "command", ",", "send_command", ",", "description", ")", "node_command", ".", "desc", "description", "node_command", ".", "command", "command", "do", "|", "generated_command", "|", "generated_command", ".", "action", "do", "|", "global_options", ",", "options", ",", "args", "|", "environment", "=", "get_environment", "(", "options", ")", "info", "_", "(", "'cli.current_environment'", ")", "%", "{", "environment", ":", "environment", "}", "Bebox", "::", "NodeWizard", ".", "new", ".", "send", "(", "send_command", ",", "project_root", ",", "environment", ")", "end", "end", "end" ]
For new and set_role commands
[ "For", "new", "and", "set_role", "commands" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/commands/node_commands.rb#L37-L46
6,609
delano/familia
lib/familia/object.rb
Familia.ClassMethods.install_redis_object
def install_redis_object name, klass, opts raise ArgumentError, "Name is blank" if name.to_s.empty? name = name.to_s.to_sym opts ||= {} redis_objects_order << name redis_objects[name] = OpenStruct.new redis_objects[name].name = name redis_objects[name].klass = klass redis_objects[name].opts = opts self.send :attr_reader, name define_method "#{name}=" do |v| self.send(name).replace v end define_method "#{name}?" do !self.send(name).empty? end redis_objects[name] end
ruby
def install_redis_object name, klass, opts raise ArgumentError, "Name is blank" if name.to_s.empty? name = name.to_s.to_sym opts ||= {} redis_objects_order << name redis_objects[name] = OpenStruct.new redis_objects[name].name = name redis_objects[name].klass = klass redis_objects[name].opts = opts self.send :attr_reader, name define_method "#{name}=" do |v| self.send(name).replace v end define_method "#{name}?" do !self.send(name).empty? end redis_objects[name] end
[ "def", "install_redis_object", "name", ",", "klass", ",", "opts", "raise", "ArgumentError", ",", "\"Name is blank\"", "if", "name", ".", "to_s", ".", "empty?", "name", "=", "name", ".", "to_s", ".", "to_sym", "opts", "||=", "{", "}", "redis_objects_order", "<<", "name", "redis_objects", "[", "name", "]", "=", "OpenStruct", ".", "new", "redis_objects", "[", "name", "]", ".", "name", "=", "name", "redis_objects", "[", "name", "]", ".", "klass", "=", "klass", "redis_objects", "[", "name", "]", ".", "opts", "=", "opts", "self", ".", "send", ":attr_reader", ",", "name", "define_method", "\"#{name}=\"", "do", "|", "v", "|", "self", ".", "send", "(", "name", ")", ".", "replace", "v", "end", "define_method", "\"#{name}?\"", "do", "!", "self", ".", "send", "(", "name", ")", ".", "empty?", "end", "redis_objects", "[", "name", "]", "end" ]
Creates an instance method called +name+ that returns an instance of the RedisObject +klass+
[ "Creates", "an", "instance", "method", "called", "+", "name", "+", "that", "returns", "an", "instance", "of", "the", "RedisObject", "+", "klass", "+" ]
4ecb29e796c86611c5d37e1924729fb562eeb529
https://github.com/delano/familia/blob/4ecb29e796c86611c5d37e1924729fb562eeb529/lib/familia/object.rb#L75-L92
6,610
delano/familia
lib/familia/object.rb
Familia.ClassMethods.install_class_redis_object
def install_class_redis_object name, klass, opts raise ArgumentError, "Name is blank" if name.to_s.empty? name = name.to_s.to_sym opts = opts.nil? ? {} : opts.clone opts[:parent] = self unless opts.has_key?(:parent) # TODO: investigate using metaclass.redis_objects class_redis_objects_order << name class_redis_objects[name] = OpenStruct.new class_redis_objects[name].name = name class_redis_objects[name].klass = klass class_redis_objects[name].opts = opts # An accessor method created in the metclass will # access the instance variables for this class. metaclass.send :attr_reader, name metaclass.send :define_method, "#{name}=" do |v| send(name).replace v end metaclass.send :define_method, "#{name}?" do !send(name).empty? end redis_object = klass.new name, opts redis_object.freeze self.instance_variable_set("@#{name}", redis_object) class_redis_objects[name] end
ruby
def install_class_redis_object name, klass, opts raise ArgumentError, "Name is blank" if name.to_s.empty? name = name.to_s.to_sym opts = opts.nil? ? {} : opts.clone opts[:parent] = self unless opts.has_key?(:parent) # TODO: investigate using metaclass.redis_objects class_redis_objects_order << name class_redis_objects[name] = OpenStruct.new class_redis_objects[name].name = name class_redis_objects[name].klass = klass class_redis_objects[name].opts = opts # An accessor method created in the metclass will # access the instance variables for this class. metaclass.send :attr_reader, name metaclass.send :define_method, "#{name}=" do |v| send(name).replace v end metaclass.send :define_method, "#{name}?" do !send(name).empty? end redis_object = klass.new name, opts redis_object.freeze self.instance_variable_set("@#{name}", redis_object) class_redis_objects[name] end
[ "def", "install_class_redis_object", "name", ",", "klass", ",", "opts", "raise", "ArgumentError", ",", "\"Name is blank\"", "if", "name", ".", "to_s", ".", "empty?", "name", "=", "name", ".", "to_s", ".", "to_sym", "opts", "=", "opts", ".", "nil?", "?", "{", "}", ":", "opts", ".", "clone", "opts", "[", ":parent", "]", "=", "self", "unless", "opts", ".", "has_key?", "(", ":parent", ")", "# TODO: investigate using metaclass.redis_objects", "class_redis_objects_order", "<<", "name", "class_redis_objects", "[", "name", "]", "=", "OpenStruct", ".", "new", "class_redis_objects", "[", "name", "]", ".", "name", "=", "name", "class_redis_objects", "[", "name", "]", ".", "klass", "=", "klass", "class_redis_objects", "[", "name", "]", ".", "opts", "=", "opts", "# An accessor method created in the metclass will", "# access the instance variables for this class. ", "metaclass", ".", "send", ":attr_reader", ",", "name", "metaclass", ".", "send", ":define_method", ",", "\"#{name}=\"", "do", "|", "v", "|", "send", "(", "name", ")", ".", "replace", "v", "end", "metaclass", ".", "send", ":define_method", ",", "\"#{name}?\"", "do", "!", "send", "(", "name", ")", ".", "empty?", "end", "redis_object", "=", "klass", ".", "new", "name", ",", "opts", "redis_object", ".", "freeze", "self", ".", "instance_variable_set", "(", "\"@#{name}\"", ",", "redis_object", ")", "class_redis_objects", "[", "name", "]", "end" ]
Creates a class method called +name+ that returns an instance of the RedisObject +klass+
[ "Creates", "a", "class", "method", "called", "+", "name", "+", "that", "returns", "an", "instance", "of", "the", "RedisObject", "+", "klass", "+" ]
4ecb29e796c86611c5d37e1924729fb562eeb529
https://github.com/delano/familia/blob/4ecb29e796c86611c5d37e1924729fb562eeb529/lib/familia/object.rb#L103-L127
6,611
delano/familia
lib/familia/object.rb
Familia.ClassMethods.load_or_create
def load_or_create idx return from_redis(idx) if exists?(idx) obj = from_index idx obj.save obj end
ruby
def load_or_create idx return from_redis(idx) if exists?(idx) obj = from_index idx obj.save obj end
[ "def", "load_or_create", "idx", "return", "from_redis", "(", "idx", ")", "if", "exists?", "(", "idx", ")", "obj", "=", "from_index", "idx", "obj", ".", "save", "obj", "end" ]
Returns an instance based on +idx+ otherwise it creates and saves a new instance base on +idx+. See from_index
[ "Returns", "an", "instance", "based", "on", "+", "idx", "+", "otherwise", "it", "creates", "and", "saves", "a", "new", "instance", "base", "on", "+", "idx", "+", ".", "See", "from_index" ]
4ecb29e796c86611c5d37e1924729fb562eeb529
https://github.com/delano/familia/blob/4ecb29e796c86611c5d37e1924729fb562eeb529/lib/familia/object.rb#L237-L242
6,612
delano/familia
lib/familia/object.rb
Familia.ClassMethods.rediskey
def rediskey idx, suffix=self.suffix raise RuntimeError, "No index for #{self}" if idx.to_s.empty? idx = Familia.join *idx if Array === idx idx &&= idx.to_s Familia.rediskey(prefix, idx, suffix) end
ruby
def rediskey idx, suffix=self.suffix raise RuntimeError, "No index for #{self}" if idx.to_s.empty? idx = Familia.join *idx if Array === idx idx &&= idx.to_s Familia.rediskey(prefix, idx, suffix) end
[ "def", "rediskey", "idx", ",", "suffix", "=", "self", ".", "suffix", "raise", "RuntimeError", ",", "\"No index for #{self}\"", "if", "idx", ".", "to_s", ".", "empty?", "idx", "=", "Familia", ".", "join", "idx", "if", "Array", "===", "idx", "idx", "&&=", "idx", ".", "to_s", "Familia", ".", "rediskey", "(", "prefix", ",", "idx", ",", "suffix", ")", "end" ]
idx can be a value or an Array of values used to create the index. We don't enforce a default suffix; that's left up to the instance. A nil +suffix+ will not be included in the key.
[ "idx", "can", "be", "a", "value", "or", "an", "Array", "of", "values", "used", "to", "create", "the", "index", ".", "We", "don", "t", "enforce", "a", "default", "suffix", ";", "that", "s", "left", "up", "to", "the", "instance", ".", "A", "nil", "+", "suffix", "+", "will", "not", "be", "included", "in", "the", "key", "." ]
4ecb29e796c86611c5d37e1924729fb562eeb529
https://github.com/delano/familia/blob/4ecb29e796c86611c5d37e1924729fb562eeb529/lib/familia/object.rb#L283-L288
6,613
delano/familia
lib/familia/object.rb
Familia.InstanceMethods.initialize_redis_objects
def initialize_redis_objects # Generate instances of each RedisObject. These need to be # unique for each instance of this class so they can refer # to the index of this specific instance. # # i.e. # familia_object.rediskey == v1:bone:INDEXVALUE:object # familia_object.redis_object.rediskey == v1:bone:INDEXVALUE:name # # See RedisObject.install_redis_object self.class.redis_objects.each_pair do |name, redis_object_definition| klass, opts = redis_object_definition.klass, redis_object_definition.opts opts = opts.nil? ? {} : opts.clone opts[:parent] = self unless opts.has_key?(:parent) redis_object = klass.new name, opts redis_object.freeze self.instance_variable_set "@#{name}", redis_object end end
ruby
def initialize_redis_objects # Generate instances of each RedisObject. These need to be # unique for each instance of this class so they can refer # to the index of this specific instance. # # i.e. # familia_object.rediskey == v1:bone:INDEXVALUE:object # familia_object.redis_object.rediskey == v1:bone:INDEXVALUE:name # # See RedisObject.install_redis_object self.class.redis_objects.each_pair do |name, redis_object_definition| klass, opts = redis_object_definition.klass, redis_object_definition.opts opts = opts.nil? ? {} : opts.clone opts[:parent] = self unless opts.has_key?(:parent) redis_object = klass.new name, opts redis_object.freeze self.instance_variable_set "@#{name}", redis_object end end
[ "def", "initialize_redis_objects", "# Generate instances of each RedisObject. These need to be", "# unique for each instance of this class so they can refer", "# to the index of this specific instance.", "#", "# i.e. ", "# familia_object.rediskey == v1:bone:INDEXVALUE:object", "# familia_object.redis_object.rediskey == v1:bone:INDEXVALUE:name", "#", "# See RedisObject.install_redis_object", "self", ".", "class", ".", "redis_objects", ".", "each_pair", "do", "|", "name", ",", "redis_object_definition", "|", "klass", ",", "opts", "=", "redis_object_definition", ".", "klass", ",", "redis_object_definition", ".", "opts", "opts", "=", "opts", ".", "nil?", "?", "{", "}", ":", "opts", ".", "clone", "opts", "[", ":parent", "]", "=", "self", "unless", "opts", ".", "has_key?", "(", ":parent", ")", "redis_object", "=", "klass", ".", "new", "name", ",", "opts", "redis_object", ".", "freeze", "self", ".", "instance_variable_set", "\"@#{name}\"", ",", "redis_object", "end", "end" ]
A default initialize method. This will be replaced if a class defines its own initialize method after including Familia. In that case, the replacement must call initialize_redis_objects. This needs to be called in the initialize method of any class that includes Familia.
[ "A", "default", "initialize", "method", ".", "This", "will", "be", "replaced", "if", "a", "class", "defines", "its", "own", "initialize", "method", "after", "including", "Familia", ".", "In", "that", "case", "the", "replacement", "must", "call", "initialize_redis_objects", ".", "This", "needs", "to", "be", "called", "in", "the", "initialize", "method", "of", "any", "class", "that", "includes", "Familia", "." ]
4ecb29e796c86611c5d37e1924729fb562eeb529
https://github.com/delano/familia/blob/4ecb29e796c86611c5d37e1924729fb562eeb529/lib/familia/object.rb#L319-L337
6,614
timstephenson/rHAPI
lib/r_hapi/lead.rb
RHapi.Lead.method_missing
def method_missing(method, *args, &block) attribute = ActiveSupport::Inflector.camelize(method.to_s, false) if attribute =~ /=$/ attribute = attribute.chop return super unless self.attributes.include?(attribute) self.changed_attributes[attribute] = args[0] self.attributes[attribute] = args[0] else return super unless self.attributes.include?(attribute) self.attributes[attribute] end end
ruby
def method_missing(method, *args, &block) attribute = ActiveSupport::Inflector.camelize(method.to_s, false) if attribute =~ /=$/ attribute = attribute.chop return super unless self.attributes.include?(attribute) self.changed_attributes[attribute] = args[0] self.attributes[attribute] = args[0] else return super unless self.attributes.include?(attribute) self.attributes[attribute] end end
[ "def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "attribute", "=", "ActiveSupport", "::", "Inflector", ".", "camelize", "(", "method", ".", "to_s", ",", "false", ")", "if", "attribute", "=~", "/", "/", "attribute", "=", "attribute", ".", "chop", "return", "super", "unless", "self", ".", "attributes", ".", "include?", "(", "attribute", ")", "self", ".", "changed_attributes", "[", "attribute", "]", "=", "args", "[", "0", "]", "self", ".", "attributes", "[", "attribute", "]", "=", "args", "[", "0", "]", "else", "return", "super", "unless", "self", ".", "attributes", ".", "include?", "(", "attribute", ")", "self", ".", "attributes", "[", "attribute", "]", "end", "end" ]
Work with data in the data hash
[ "Work", "with", "data", "in", "the", "data", "hash" ]
1490574e619b7564c9458ac8d967d40fe76fe7a5
https://github.com/timstephenson/rHAPI/blob/1490574e619b7564c9458ac8d967d40fe76fe7a5/lib/r_hapi/lead.rb#L65-L79
6,615
albertosaurus/us_bank_holidays
lib/us_bank_holidays/holiday_year.rb
UsBankHolidays.HolidayYear.bank_holidays
def bank_holidays @bank_holidays ||= begin holidays = [ new_years_day, mlk_day, washingtons_birthday, memorial_day, independence_day, labor_day, columbus_day, veterans_day, thanksgiving, christmas ] if Date.new(year + 1, 1, 1).saturday? holidays << Date.new(year, 12, 31) end holidays.freeze end end
ruby
def bank_holidays @bank_holidays ||= begin holidays = [ new_years_day, mlk_day, washingtons_birthday, memorial_day, independence_day, labor_day, columbus_day, veterans_day, thanksgiving, christmas ] if Date.new(year + 1, 1, 1).saturday? holidays << Date.new(year, 12, 31) end holidays.freeze end end
[ "def", "bank_holidays", "@bank_holidays", "||=", "begin", "holidays", "=", "[", "new_years_day", ",", "mlk_day", ",", "washingtons_birthday", ",", "memorial_day", ",", "independence_day", ",", "labor_day", ",", "columbus_day", ",", "veterans_day", ",", "thanksgiving", ",", "christmas", "]", "if", "Date", ".", "new", "(", "year", "+", "1", ",", "1", ",", "1", ")", ".", "saturday?", "holidays", "<<", "Date", ".", "new", "(", "year", ",", "12", ",", "31", ")", "end", "holidays", ".", "freeze", "end", "end" ]
Initializes instance from a given year Returns the federal holidays for the given year on the dates they will actually be observed.
[ "Initializes", "instance", "from", "a", "given", "year", "Returns", "the", "federal", "holidays", "for", "the", "given", "year", "on", "the", "dates", "they", "will", "actually", "be", "observed", "." ]
506269159bfaf0737955b2cca2d43c627ac9704e
https://github.com/albertosaurus/us_bank_holidays/blob/506269159bfaf0737955b2cca2d43c627ac9704e/lib/us_bank_holidays/holiday_year.rb#L30-L48
6,616
albertosaurus/us_bank_holidays
lib/us_bank_holidays/holiday_year.rb
UsBankHolidays.HolidayYear.init_fixed_holidays
def init_fixed_holidays # Third Monday of January @mlk_day = january.mondays[2] # Third Monday of February @washingtons_birthday = february.mondays[2] # Last Monday of May @memorial_day = may.mondays.last # First Monday of September @labor_day = september.mondays.first # Second Monday of October @columbus_day = october.mondays[1] # Fourth Thursday of November @thanksgiving = november.thursdays[3] end
ruby
def init_fixed_holidays # Third Monday of January @mlk_day = january.mondays[2] # Third Monday of February @washingtons_birthday = february.mondays[2] # Last Monday of May @memorial_day = may.mondays.last # First Monday of September @labor_day = september.mondays.first # Second Monday of October @columbus_day = october.mondays[1] # Fourth Thursday of November @thanksgiving = november.thursdays[3] end
[ "def", "init_fixed_holidays", "# Third Monday of January", "@mlk_day", "=", "january", ".", "mondays", "[", "2", "]", "# Third Monday of February", "@washingtons_birthday", "=", "february", ".", "mondays", "[", "2", "]", "# Last Monday of May", "@memorial_day", "=", "may", ".", "mondays", ".", "last", "# First Monday of September", "@labor_day", "=", "september", ".", "mondays", ".", "first", "# Second Monday of October", "@columbus_day", "=", "october", ".", "mondays", "[", "1", "]", "# Fourth Thursday of November", "@thanksgiving", "=", "november", ".", "thursdays", "[", "3", "]", "end" ]
These holidays are always fixed
[ "These", "holidays", "are", "always", "fixed" ]
506269159bfaf0737955b2cca2d43c627ac9704e
https://github.com/albertosaurus/us_bank_holidays/blob/506269159bfaf0737955b2cca2d43c627ac9704e/lib/us_bank_holidays/holiday_year.rb#L74-L92
6,617
albertosaurus/us_bank_holidays
lib/us_bank_holidays/holiday_year.rb
UsBankHolidays.HolidayYear.init_rolled_holidays
def init_rolled_holidays # First of the year, rolls either forward or back. @new_years_day = roll_nominal(Date.new(year, 1, 1)) # 4'th of July @independence_day = roll_nominal(Date.new(year, 7, 4)) # November 11 @veterans_day = roll_nominal(Date.new(year, 11, 11)) # December 25 @christmas = roll_nominal(Date.new(year, 12, 25)) end
ruby
def init_rolled_holidays # First of the year, rolls either forward or back. @new_years_day = roll_nominal(Date.new(year, 1, 1)) # 4'th of July @independence_day = roll_nominal(Date.new(year, 7, 4)) # November 11 @veterans_day = roll_nominal(Date.new(year, 11, 11)) # December 25 @christmas = roll_nominal(Date.new(year, 12, 25)) end
[ "def", "init_rolled_holidays", "# First of the year, rolls either forward or back.", "@new_years_day", "=", "roll_nominal", "(", "Date", ".", "new", "(", "year", ",", "1", ",", "1", ")", ")", "# 4'th of July", "@independence_day", "=", "roll_nominal", "(", "Date", ".", "new", "(", "year", ",", "7", ",", "4", ")", ")", "# November 11", "@veterans_day", "=", "roll_nominal", "(", "Date", ".", "new", "(", "year", ",", "11", ",", "11", ")", ")", "# December 25", "@christmas", "=", "roll_nominal", "(", "Date", ".", "new", "(", "year", ",", "12", ",", "25", ")", ")", "end" ]
These holidays are potentially rolled if they come on a weekend.
[ "These", "holidays", "are", "potentially", "rolled", "if", "they", "come", "on", "a", "weekend", "." ]
506269159bfaf0737955b2cca2d43c627ac9704e
https://github.com/albertosaurus/us_bank_holidays/blob/506269159bfaf0737955b2cca2d43c627ac9704e/lib/us_bank_holidays/holiday_year.rb#L95-L107
6,618
thejonanshow/guard-shopify
lib/guard/shopify.rb
Guard.Shopify.upgrade_config_file
def upgrade_config_file puts "Old config file found, upgrading..." credentials = File.read(config_file_path).split("\n") config = {} config['api_key'] = credentials[0] config['password'] = credentials[1] config['url'] = credentials[2] config['secret'] = prompt "Please enter your API Shared Secret" write_config config puts 'Upgraded old config file to new format' config end
ruby
def upgrade_config_file puts "Old config file found, upgrading..." credentials = File.read(config_file_path).split("\n") config = {} config['api_key'] = credentials[0] config['password'] = credentials[1] config['url'] = credentials[2] config['secret'] = prompt "Please enter your API Shared Secret" write_config config puts 'Upgraded old config file to new format' config end
[ "def", "upgrade_config_file", "puts", "\"Old config file found, upgrading...\"", "credentials", "=", "File", ".", "read", "(", "config_file_path", ")", ".", "split", "(", "\"\\n\"", ")", "config", "=", "{", "}", "config", "[", "'api_key'", "]", "=", "credentials", "[", "0", "]", "config", "[", "'password'", "]", "=", "credentials", "[", "1", "]", "config", "[", "'url'", "]", "=", "credentials", "[", "2", "]", "config", "[", "'secret'", "]", "=", "prompt", "\"Please enter your API Shared Secret\"", "write_config", "config", "puts", "'Upgraded old config file to new format'", "config", "end" ]
Old line-based config file format
[ "Old", "line", "-", "based", "config", "file", "format" ]
c2f4d468286284a6ec720fd1604c529a26f03c5d
https://github.com/thejonanshow/guard-shopify/blob/c2f4d468286284a6ec720fd1604c529a26f03c5d/lib/guard/shopify.rb#L32-L48
6,619
cmeiklejohn/seedable
lib/seedable/object_tracker.rb
Seedable.ObjectTracker.contains?
def contains?(object) key, id = to_key_and_id(object) @graph[key].is_a?(Enumerable) ? @graph[key].include?(id) : @graph[key] end
ruby
def contains?(object) key, id = to_key_and_id(object) @graph[key].is_a?(Enumerable) ? @graph[key].include?(id) : @graph[key] end
[ "def", "contains?", "(", "object", ")", "key", ",", "id", "=", "to_key_and_id", "(", "object", ")", "@graph", "[", "key", "]", ".", "is_a?", "(", "Enumerable", ")", "?", "@graph", "[", "key", "]", ".", "include?", "(", "id", ")", ":", "@graph", "[", "key", "]", "end" ]
Create a new instance of the object tracker. Determine if the object tracker has already picked this object up.
[ "Create", "a", "new", "instance", "of", "the", "object", "tracker", "." ]
b3383e460e1afc22715c92d920c0fc7910706903
https://github.com/cmeiklejohn/seedable/blob/b3383e460e1afc22715c92d920c0fc7910706903/lib/seedable/object_tracker.rb#L16-L20
6,620
cmeiklejohn/seedable
lib/seedable/object_tracker.rb
Seedable.ObjectTracker.add
def add(object) key, id = to_key_and_id(object) @graph[key] ? @graph[key] << id : @graph[key] = [id] end
ruby
def add(object) key, id = to_key_and_id(object) @graph[key] ? @graph[key] << id : @graph[key] = [id] end
[ "def", "add", "(", "object", ")", "key", ",", "id", "=", "to_key_and_id", "(", "object", ")", "@graph", "[", "key", "]", "?", "@graph", "[", "key", "]", "<<", "id", ":", "@graph", "[", "key", "]", "=", "[", "id", "]", "end" ]
Add this object to the object tracker.
[ "Add", "this", "object", "to", "the", "object", "tracker", "." ]
b3383e460e1afc22715c92d920c0fc7910706903
https://github.com/cmeiklejohn/seedable/blob/b3383e460e1afc22715c92d920c0fc7910706903/lib/seedable/object_tracker.rb#L24-L28
6,621
notCalle/ruby-tangle
lib/tangle/base_graph.rb
Tangle.BaseGraph.subgraph
def subgraph(included = nil, &selector) result = clone result.select_vertices!(included) unless included.nil? result.select_vertices!(&selector) if block_given? result end
ruby
def subgraph(included = nil, &selector) result = clone result.select_vertices!(included) unless included.nil? result.select_vertices!(&selector) if block_given? result end
[ "def", "subgraph", "(", "included", "=", "nil", ",", "&", "selector", ")", "result", "=", "clone", "result", ".", "select_vertices!", "(", "included", ")", "unless", "included", ".", "nil?", "result", ".", "select_vertices!", "(", "selector", ")", "if", "block_given?", "result", "end" ]
Initialize a new graph, optionally preloading it with vertices and edges Graph.new() => Graph Graph.new(mixins: [MixinModule, ...], ...) => Graph +mixins+ is an array of modules that can be mixed into the various classes that makes up a graph. Initialization of a Graph, Vertex or Edge looks for submodules in each mixin, with the same name and extends any created object. Defaults to [Tangle::Mixin::Connectedness]. Any subclass of Graph should also subclass Edge to manage its unique constraints. Return a subgraph, optionally filtered by a vertex selector block subgraph => Graph subgraph { |vertex| ... } => Graph Unless a selector is provided, the subgraph contains the entire graph.
[ "Initialize", "a", "new", "graph", "optionally", "preloading", "it", "with", "vertices", "and", "edges" ]
ccafab96835a0644b05ae749066d7ec7ecada260
https://github.com/notCalle/ruby-tangle/blob/ccafab96835a0644b05ae749066d7ec7ecada260/lib/tangle/base_graph.rb#L66-L71
6,622
notCalle/ruby-tangle
lib/tangle/base_graph.rb
Tangle.BaseGraph.add_vertex
def add_vertex(vertex, name: nil) name ||= callback(vertex, :name) insert_vertex(vertex, name) define_currified_methods(vertex, :vertex) if @currify callback(vertex, :added_to_graph, self) self end
ruby
def add_vertex(vertex, name: nil) name ||= callback(vertex, :name) insert_vertex(vertex, name) define_currified_methods(vertex, :vertex) if @currify callback(vertex, :added_to_graph, self) self end
[ "def", "add_vertex", "(", "vertex", ",", "name", ":", "nil", ")", "name", "||=", "callback", "(", "vertex", ",", ":name", ")", "insert_vertex", "(", "vertex", ",", "name", ")", "define_currified_methods", "(", "vertex", ",", ":vertex", ")", "if", "@currify", "callback", "(", "vertex", ",", ":added_to_graph", ",", "self", ")", "self", "end" ]
Add a vertex into the graph If a name: is given, or the vertex responds to :name, it will be registered by name in the graph
[ "Add", "a", "vertex", "into", "the", "graph" ]
ccafab96835a0644b05ae749066d7ec7ecada260
https://github.com/notCalle/ruby-tangle/blob/ccafab96835a0644b05ae749066d7ec7ecada260/lib/tangle/base_graph.rb#L102-L108
6,623
notCalle/ruby-tangle
lib/tangle/base_graph.rb
Tangle.BaseGraph.remove_vertex
def remove_vertex(vertex) @vertices[vertex].each do |edge| remove_edge(edge) if edge.include?(vertex) end delete_vertex(vertex) callback(vertex, :removed_from_graph, self) end
ruby
def remove_vertex(vertex) @vertices[vertex].each do |edge| remove_edge(edge) if edge.include?(vertex) end delete_vertex(vertex) callback(vertex, :removed_from_graph, self) end
[ "def", "remove_vertex", "(", "vertex", ")", "@vertices", "[", "vertex", "]", ".", "each", "do", "|", "edge", "|", "remove_edge", "(", "edge", ")", "if", "edge", ".", "include?", "(", "vertex", ")", "end", "delete_vertex", "(", "vertex", ")", "callback", "(", "vertex", ",", ":removed_from_graph", ",", "self", ")", "end" ]
Remove a vertex from the graph
[ "Remove", "a", "vertex", "from", "the", "graph" ]
ccafab96835a0644b05ae749066d7ec7ecada260
https://github.com/notCalle/ruby-tangle/blob/ccafab96835a0644b05ae749066d7ec7ecada260/lib/tangle/base_graph.rb#L112-L118
6,624
notCalle/ruby-tangle
lib/tangle/base_graph.rb
Tangle.BaseGraph.add_edge
def add_edge(*vertices, **kvargs) edge = new_edge(*vertices, mixins: @mixins, **kvargs) insert_edge(edge) vertices.each { |vertex| callback(vertex, :edge_added, edge) } edge end
ruby
def add_edge(*vertices, **kvargs) edge = new_edge(*vertices, mixins: @mixins, **kvargs) insert_edge(edge) vertices.each { |vertex| callback(vertex, :edge_added, edge) } edge end
[ "def", "add_edge", "(", "*", "vertices", ",", "**", "kvargs", ")", "edge", "=", "new_edge", "(", "vertices", ",", "mixins", ":", "@mixins", ",", "**", "kvargs", ")", "insert_edge", "(", "edge", ")", "vertices", ".", "each", "{", "|", "vertex", "|", "callback", "(", "vertex", ",", ":edge_added", ",", "edge", ")", "}", "edge", "end" ]
Add a new edge to the graph add_edge(vtx1, vtx2, ...) => Edge
[ "Add", "a", "new", "edge", "to", "the", "graph" ]
ccafab96835a0644b05ae749066d7ec7ecada260
https://github.com/notCalle/ruby-tangle/blob/ccafab96835a0644b05ae749066d7ec7ecada260/lib/tangle/base_graph.rb#L135-L140
6,625
notCalle/ruby-tangle
lib/tangle/base_graph.rb
Tangle.BaseGraph.remove_edge
def remove_edge(edge) delete_edge(edge) edge.each_vertex { |vertex| callback(vertex, :edge_removed, edge) } end
ruby
def remove_edge(edge) delete_edge(edge) edge.each_vertex { |vertex| callback(vertex, :edge_removed, edge) } end
[ "def", "remove_edge", "(", "edge", ")", "delete_edge", "(", "edge", ")", "edge", ".", "each_vertex", "{", "|", "vertex", "|", "callback", "(", "vertex", ",", ":edge_removed", ",", "edge", ")", "}", "end" ]
Remove an edge from the graph
[ "Remove", "an", "edge", "from", "the", "graph" ]
ccafab96835a0644b05ae749066d7ec7ecada260
https://github.com/notCalle/ruby-tangle/blob/ccafab96835a0644b05ae749066d7ec7ecada260/lib/tangle/base_graph.rb#L143-L146
6,626
richard-viney/lightstreamer
lib/lightstreamer/session.rb
Lightstreamer.Session.disconnect
def disconnect control_request LS_op: :destroy if @stream_connection @processing_thread.join 5 if @processing_thread ensure @stream_connection.disconnect if @stream_connection @processing_thread.exit if @processing_thread @subscriptions.each { |subscription| subscription.after_control_request :stop } @subscriptions = [] @processing_thread = @stream_connection = nil end
ruby
def disconnect control_request LS_op: :destroy if @stream_connection @processing_thread.join 5 if @processing_thread ensure @stream_connection.disconnect if @stream_connection @processing_thread.exit if @processing_thread @subscriptions.each { |subscription| subscription.after_control_request :stop } @subscriptions = [] @processing_thread = @stream_connection = nil end
[ "def", "disconnect", "control_request", "LS_op", ":", ":destroy", "if", "@stream_connection", "@processing_thread", ".", "join", "5", "if", "@processing_thread", "ensure", "@stream_connection", ".", "disconnect", "if", "@stream_connection", "@processing_thread", ".", "exit", "if", "@processing_thread", "@subscriptions", ".", "each", "{", "|", "subscription", "|", "subscription", ".", "after_control_request", ":stop", "}", "@subscriptions", "=", "[", "]", "@processing_thread", "=", "@stream_connection", "=", "nil", "end" ]
Disconnects this Lightstreamer session and terminates the session on the server. All worker threads are exited, and all subscriptions created during the connected session can no longer be used.
[ "Disconnects", "this", "Lightstreamer", "session", "and", "terminates", "the", "session", "on", "the", "server", ".", "All", "worker", "threads", "are", "exited", "and", "all", "subscriptions", "created", "during", "the", "connected", "session", "can", "no", "longer", "be", "used", "." ]
7be6350bd861495a52ca35a8640a1e6df34cf9d1
https://github.com/richard-viney/lightstreamer/blob/7be6350bd861495a52ca35a8640a1e6df34cf9d1/lib/lightstreamer/session.rb#L97-L109
6,627
richard-viney/lightstreamer
lib/lightstreamer/session.rb
Lightstreamer.Session.create_processing_thread
def create_processing_thread @processing_thread = Thread.new do Thread.current.abort_on_exception = true loop { break unless processing_thread_tick @stream_connection.read_line } @processing_thread = @stream_connection = nil end end
ruby
def create_processing_thread @processing_thread = Thread.new do Thread.current.abort_on_exception = true loop { break unless processing_thread_tick @stream_connection.read_line } @processing_thread = @stream_connection = nil end end
[ "def", "create_processing_thread", "@processing_thread", "=", "Thread", ".", "new", "do", "Thread", ".", "current", ".", "abort_on_exception", "=", "true", "loop", "{", "break", "unless", "processing_thread_tick", "@stream_connection", ".", "read_line", "}", "@processing_thread", "=", "@stream_connection", "=", "nil", "end", "end" ]
Starts the processing thread that reads and processes incoming data from the stream connection.
[ "Starts", "the", "processing", "thread", "that", "reads", "and", "processes", "incoming", "data", "from", "the", "stream", "connection", "." ]
7be6350bd861495a52ca35a8640a1e6df34cf9d1
https://github.com/richard-viney/lightstreamer/blob/7be6350bd861495a52ca35a8640a1e6df34cf9d1/lib/lightstreamer/session.rb#L308-L316
6,628
richard-viney/lightstreamer
lib/lightstreamer/session.rb
Lightstreamer.Session.process_stream_line
def process_stream_line(line) return if @mutex.synchronize { @subscriptions.any? { |subscription| subscription.process_stream_data line } } return if process_send_message_outcome line warn "Lightstreamer: unprocessed stream data '#{line}'" end
ruby
def process_stream_line(line) return if @mutex.synchronize { @subscriptions.any? { |subscription| subscription.process_stream_data line } } return if process_send_message_outcome line warn "Lightstreamer: unprocessed stream data '#{line}'" end
[ "def", "process_stream_line", "(", "line", ")", "return", "if", "@mutex", ".", "synchronize", "{", "@subscriptions", ".", "any?", "{", "|", "subscription", "|", "subscription", ".", "process_stream_data", "line", "}", "}", "return", "if", "process_send_message_outcome", "line", "warn", "\"Lightstreamer: unprocessed stream data '#{line}'\"", "end" ]
Processes a single line of incoming stream data. This method is always run on the processing thread.
[ "Processes", "a", "single", "line", "of", "incoming", "stream", "data", ".", "This", "method", "is", "always", "run", "on", "the", "processing", "thread", "." ]
7be6350bd861495a52ca35a8640a1e6df34cf9d1
https://github.com/richard-viney/lightstreamer/blob/7be6350bd861495a52ca35a8640a1e6df34cf9d1/lib/lightstreamer/session.rb#L329-L334
6,629
richard-viney/lightstreamer
lib/lightstreamer/session.rb
Lightstreamer.Session.process_send_message_outcome
def process_send_message_outcome(line) outcome = SendMessageOutcomeMessage.parse line return unless outcome @mutex.synchronize do @callbacks[:on_message_result].each do |callback| callback.call outcome.sequence, outcome.numbers, outcome.error end end true end
ruby
def process_send_message_outcome(line) outcome = SendMessageOutcomeMessage.parse line return unless outcome @mutex.synchronize do @callbacks[:on_message_result].each do |callback| callback.call outcome.sequence, outcome.numbers, outcome.error end end true end
[ "def", "process_send_message_outcome", "(", "line", ")", "outcome", "=", "SendMessageOutcomeMessage", ".", "parse", "line", "return", "unless", "outcome", "@mutex", ".", "synchronize", "do", "@callbacks", "[", ":on_message_result", "]", ".", "each", "do", "|", "callback", "|", "callback", ".", "call", "outcome", ".", "sequence", ",", "outcome", ".", "numbers", ",", "outcome", ".", "error", "end", "end", "true", "end" ]
Attempts to process the passed line as a send message outcome message.
[ "Attempts", "to", "process", "the", "passed", "line", "as", "a", "send", "message", "outcome", "message", "." ]
7be6350bd861495a52ca35a8640a1e6df34cf9d1
https://github.com/richard-viney/lightstreamer/blob/7be6350bd861495a52ca35a8640a1e6df34cf9d1/lib/lightstreamer/session.rb#L337-L348
6,630
hck/mongoid_atomic_votes
lib/mongoid_atomic_votes/atomic_votes.rb
Mongoid.AtomicVotes.vote
def vote(value, voted_by) mark = Vote.new(value: value, voted_by_id: voted_by.id, voter_type: voted_by.class.name) add_vote_mark(mark) end
ruby
def vote(value, voted_by) mark = Vote.new(value: value, voted_by_id: voted_by.id, voter_type: voted_by.class.name) add_vote_mark(mark) end
[ "def", "vote", "(", "value", ",", "voted_by", ")", "mark", "=", "Vote", ".", "new", "(", "value", ":", "value", ",", "voted_by_id", ":", "voted_by", ".", "id", ",", "voter_type", ":", "voted_by", ".", "class", ".", "name", ")", "add_vote_mark", "(", "mark", ")", "end" ]
Creates an embedded vote record and updates number of votes and vote value. @param [Int,Float] value vote value @param [Mongoid::Document] voted_by object from which the vote is done @return [Boolean] success flag
[ "Creates", "an", "embedded", "vote", "record", "and", "updates", "number", "of", "votes", "and", "vote", "value", "." ]
5c005fd48927c433091dce068350a6f8b44715b5
https://github.com/hck/mongoid_atomic_votes/blob/5c005fd48927c433091dce068350a6f8b44715b5/lib/mongoid_atomic_votes/atomic_votes.rb#L54-L57
6,631
hck/mongoid_atomic_votes
lib/mongoid_atomic_votes/atomic_votes.rb
Mongoid.AtomicVotes.retract
def retract(voted_by) mark = votes.find_by(voted_by_id: voted_by.id) mark && remove_vote_mark(mark) end
ruby
def retract(voted_by) mark = votes.find_by(voted_by_id: voted_by.id) mark && remove_vote_mark(mark) end
[ "def", "retract", "(", "voted_by", ")", "mark", "=", "votes", ".", "find_by", "(", "voted_by_id", ":", "voted_by", ".", "id", ")", "mark", "&&", "remove_vote_mark", "(", "mark", ")", "end" ]
Removes previously added vote. @param [Mongoid::Document] voted_by object from which the vote was done @return [Boolean] success flag
[ "Removes", "previously", "added", "vote", "." ]
5c005fd48927c433091dce068350a6f8b44715b5
https://github.com/hck/mongoid_atomic_votes/blob/5c005fd48927c433091dce068350a6f8b44715b5/lib/mongoid_atomic_votes/atomic_votes.rb#L63-L66
6,632
hck/mongoid_atomic_votes
lib/mongoid_atomic_votes/atomic_votes.rb
Mongoid.AtomicVotes.voted_by?
def voted_by?(voted_by) !!votes.find_by(voted_by_id: voted_by.id) rescue NoMethodError, Mongoid::Errors::DocumentNotFound false end
ruby
def voted_by?(voted_by) !!votes.find_by(voted_by_id: voted_by.id) rescue NoMethodError, Mongoid::Errors::DocumentNotFound false end
[ "def", "voted_by?", "(", "voted_by", ")", "!", "!", "votes", ".", "find_by", "(", "voted_by_id", ":", "voted_by", ".", "id", ")", "rescue", "NoMethodError", ",", "Mongoid", "::", "Errors", "::", "DocumentNotFound", "false", "end" ]
Indicates whether the document has a vote from particular voter object. @param [Mongoid::Document] voted_by object from which the vote was done @return [Boolean]
[ "Indicates", "whether", "the", "document", "has", "a", "vote", "from", "particular", "voter", "object", "." ]
5c005fd48927c433091dce068350a6f8b44715b5
https://github.com/hck/mongoid_atomic_votes/blob/5c005fd48927c433091dce068350a6f8b44715b5/lib/mongoid_atomic_votes/atomic_votes.rb#L79-L83
6,633
barkerest/shells
lib/shells/shell_base/run.rb
Shells.ShellBase.run
def run(&block) sync do raise Shells::AlreadyRunning if running? self.run_flag = true end begin run_hook :on_before_run debug 'Connecting...' connect debug 'Starting output buffering...' buffer_output debug 'Starting session thread...' self.session_thread = Thread.start(self) do |sh| begin begin debug 'Executing setup...' sh.instance_eval { setup } debug 'Executing block...' block.call sh ensure debug 'Executing teardown...' sh.instance_eval { teardown } end rescue Shells::QuitNow # just exit the session. rescue =>e # if the exception is handled by the hook no further processing is required, otherwise we store the exception # to propagate it in the main thread. unless sh.run_hook(:on_exception, e) == :break sh.sync { sh.instance_eval { self.session_exception = e } } end end end # process the input buffer while the thread is alive and the shell is active. debug 'Entering IO loop...' io_loop do if active? begin if session_thread.status # not dead # process input from the session. unless wait_for_output inp = next_input if inp send_data inp self.wait_for_output = (options[:unbuffered_input] == :echo) end end # continue running the IO loop true elsif session_exception # propagate the exception. raise session_exception.class, session_exception.message, session_exception.backtrace else # the thread has exited, but no exception exists. # regardless, the IO loop should now exit. false end rescue IOError if ignore_io_error # we were (sort of) expecting the IO error, so just tell the IO loop to exit. false else raise end end else # the shell session is no longer active, tell the IO loop to exit. false end end rescue # when an error occurs, try to disconnect, but ignore any further errors. begin debug 'Disconnecting...' disconnect rescue # ignore end raise else # when no error occurs, try to disconnect and propagate any errors (unless we are ignoring IO errors). begin debug 'Disconnecting...' disconnect rescue IOError raise unless ignore_io_error end ensure # cleanup run_hook :on_after_run self.run_flag = false end self end
ruby
def run(&block) sync do raise Shells::AlreadyRunning if running? self.run_flag = true end begin run_hook :on_before_run debug 'Connecting...' connect debug 'Starting output buffering...' buffer_output debug 'Starting session thread...' self.session_thread = Thread.start(self) do |sh| begin begin debug 'Executing setup...' sh.instance_eval { setup } debug 'Executing block...' block.call sh ensure debug 'Executing teardown...' sh.instance_eval { teardown } end rescue Shells::QuitNow # just exit the session. rescue =>e # if the exception is handled by the hook no further processing is required, otherwise we store the exception # to propagate it in the main thread. unless sh.run_hook(:on_exception, e) == :break sh.sync { sh.instance_eval { self.session_exception = e } } end end end # process the input buffer while the thread is alive and the shell is active. debug 'Entering IO loop...' io_loop do if active? begin if session_thread.status # not dead # process input from the session. unless wait_for_output inp = next_input if inp send_data inp self.wait_for_output = (options[:unbuffered_input] == :echo) end end # continue running the IO loop true elsif session_exception # propagate the exception. raise session_exception.class, session_exception.message, session_exception.backtrace else # the thread has exited, but no exception exists. # regardless, the IO loop should now exit. false end rescue IOError if ignore_io_error # we were (sort of) expecting the IO error, so just tell the IO loop to exit. false else raise end end else # the shell session is no longer active, tell the IO loop to exit. false end end rescue # when an error occurs, try to disconnect, but ignore any further errors. begin debug 'Disconnecting...' disconnect rescue # ignore end raise else # when no error occurs, try to disconnect and propagate any errors (unless we are ignoring IO errors). begin debug 'Disconnecting...' disconnect rescue IOError raise unless ignore_io_error end ensure # cleanup run_hook :on_after_run self.run_flag = false end self end
[ "def", "run", "(", "&", "block", ")", "sync", "do", "raise", "Shells", "::", "AlreadyRunning", "if", "running?", "self", ".", "run_flag", "=", "true", "end", "begin", "run_hook", ":on_before_run", "debug", "'Connecting...'", "connect", "debug", "'Starting output buffering...'", "buffer_output", "debug", "'Starting session thread...'", "self", ".", "session_thread", "=", "Thread", ".", "start", "(", "self", ")", "do", "|", "sh", "|", "begin", "begin", "debug", "'Executing setup...'", "sh", ".", "instance_eval", "{", "setup", "}", "debug", "'Executing block...'", "block", ".", "call", "sh", "ensure", "debug", "'Executing teardown...'", "sh", ".", "instance_eval", "{", "teardown", "}", "end", "rescue", "Shells", "::", "QuitNow", "# just exit the session.\r", "rescue", "=>", "e", "# if the exception is handled by the hook no further processing is required, otherwise we store the exception\r", "# to propagate it in the main thread.\r", "unless", "sh", ".", "run_hook", "(", ":on_exception", ",", "e", ")", "==", ":break", "sh", ".", "sync", "{", "sh", ".", "instance_eval", "{", "self", ".", "session_exception", "=", "e", "}", "}", "end", "end", "end", "# process the input buffer while the thread is alive and the shell is active.\r", "debug", "'Entering IO loop...'", "io_loop", "do", "if", "active?", "begin", "if", "session_thread", ".", "status", "# not dead\r", "# process input from the session.\r", "unless", "wait_for_output", "inp", "=", "next_input", "if", "inp", "send_data", "inp", "self", ".", "wait_for_output", "=", "(", "options", "[", ":unbuffered_input", "]", "==", ":echo", ")", "end", "end", "# continue running the IO loop\r", "true", "elsif", "session_exception", "# propagate the exception.\r", "raise", "session_exception", ".", "class", ",", "session_exception", ".", "message", ",", "session_exception", ".", "backtrace", "else", "# the thread has exited, but no exception exists.\r", "# regardless, the IO loop should now exit.\r", "false", "end", "rescue", "IOError", "if", "ignore_io_error", "# we were (sort of) expecting the IO error, so just tell the IO loop to exit.\r", "false", "else", "raise", "end", "end", "else", "# the shell session is no longer active, tell the IO loop to exit.\r", "false", "end", "end", "rescue", "# when an error occurs, try to disconnect, but ignore any further errors.\r", "begin", "debug", "'Disconnecting...'", "disconnect", "rescue", "# ignore\r", "end", "raise", "else", "# when no error occurs, try to disconnect and propagate any errors (unless we are ignoring IO errors).\r", "begin", "debug", "'Disconnecting...'", "disconnect", "rescue", "IOError", "raise", "unless", "ignore_io_error", "end", "ensure", "# cleanup\r", "run_hook", ":on_after_run", "self", ".", "run_flag", "=", "false", "end", "self", "end" ]
Runs a shell session. The block provided will be run asynchronously with the shell. Returns the shell instance.
[ "Runs", "a", "shell", "session", "." ]
674a0254f48cea01b0ae8979933f13892e398506
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/run.rb#L55-L155
6,634
alltom/ruck
lib/ruck/clock.rb
Ruck.Clock.fast_forward
def fast_forward(dt) adjusted_dt = dt * @relative_rate @now += adjusted_dt @children.each { |sub_clock| sub_clock.fast_forward(adjusted_dt) } end
ruby
def fast_forward(dt) adjusted_dt = dt * @relative_rate @now += adjusted_dt @children.each { |sub_clock| sub_clock.fast_forward(adjusted_dt) } end
[ "def", "fast_forward", "(", "dt", ")", "adjusted_dt", "=", "dt", "*", "@relative_rate", "@now", "+=", "adjusted_dt", "@children", ".", "each", "{", "|", "sub_clock", "|", "sub_clock", ".", "fast_forward", "(", "adjusted_dt", ")", "}", "end" ]
fast-forward this clock and all children clocks by the given time delta
[ "fast", "-", "forward", "this", "clock", "and", "all", "children", "clocks", "by", "the", "given", "time", "delta" ]
a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d
https://github.com/alltom/ruck/blob/a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d/lib/ruck/clock.rb#L51-L55
6,635
alltom/ruck
lib/ruck/clock.rb
Ruck.Clock.schedule
def schedule(obj, time = nil) time ||= now @occurrences[obj] = time parent.schedule([:clock, self], unscale_time(time)) if parent && @occurrences.min_key == obj end
ruby
def schedule(obj, time = nil) time ||= now @occurrences[obj] = time parent.schedule([:clock, self], unscale_time(time)) if parent && @occurrences.min_key == obj end
[ "def", "schedule", "(", "obj", ",", "time", "=", "nil", ")", "time", "||=", "now", "@occurrences", "[", "obj", "]", "=", "time", "parent", ".", "schedule", "(", "[", ":clock", ",", "self", "]", ",", "unscale_time", "(", "time", ")", ")", "if", "parent", "&&", "@occurrences", ".", "min_key", "==", "obj", "end" ]
schedules an occurrence at the given time with the given object, defaulting to the current time
[ "schedules", "an", "occurrence", "at", "the", "given", "time", "with", "the", "given", "object", "defaulting", "to", "the", "current", "time" ]
a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d
https://github.com/alltom/ruck/blob/a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d/lib/ruck/clock.rb#L67-L71
6,636
alltom/ruck
lib/ruck/clock.rb
Ruck.Clock.unschedule
def unschedule(obj) if @occurrences.has_key? obj last_priority = @occurrences.min_priority obj, time = @occurrences.delete obj if parent && @occurrences.min_priority != last_priority if @occurrences.min_priority parent.schedule([:clock, self], unscale_time(@occurrences.min_priority)) else parent.unschedule([:clock, self]) end end unscale_time(time) else relative_time = @children.first_non_nil { |clock| clock.unschedule(obj) } unscale_relative_time(relative_time) if relative_time end end
ruby
def unschedule(obj) if @occurrences.has_key? obj last_priority = @occurrences.min_priority obj, time = @occurrences.delete obj if parent && @occurrences.min_priority != last_priority if @occurrences.min_priority parent.schedule([:clock, self], unscale_time(@occurrences.min_priority)) else parent.unschedule([:clock, self]) end end unscale_time(time) else relative_time = @children.first_non_nil { |clock| clock.unschedule(obj) } unscale_relative_time(relative_time) if relative_time end end
[ "def", "unschedule", "(", "obj", ")", "if", "@occurrences", ".", "has_key?", "obj", "last_priority", "=", "@occurrences", ".", "min_priority", "obj", ",", "time", "=", "@occurrences", ".", "delete", "obj", "if", "parent", "&&", "@occurrences", ".", "min_priority", "!=", "last_priority", "if", "@occurrences", ".", "min_priority", "parent", ".", "schedule", "(", "[", ":clock", ",", "self", "]", ",", "unscale_time", "(", "@occurrences", ".", "min_priority", ")", ")", "else", "parent", ".", "unschedule", "(", "[", ":clock", ",", "self", "]", ")", "end", "end", "unscale_time", "(", "time", ")", "else", "relative_time", "=", "@children", ".", "first_non_nil", "{", "|", "clock", "|", "clock", ".", "unschedule", "(", "obj", ")", "}", "unscale_relative_time", "(", "relative_time", ")", "if", "relative_time", "end", "end" ]
dequeues the earliest occurrence from this clock or any child clocks. returns nil if it wasn't there, or its relative_time otherwise
[ "dequeues", "the", "earliest", "occurrence", "from", "this", "clock", "or", "any", "child", "clocks", ".", "returns", "nil", "if", "it", "wasn", "t", "there", "or", "its", "relative_time", "otherwise" ]
a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d
https://github.com/alltom/ruck/blob/a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d/lib/ruck/clock.rb#L75-L91
6,637
jphager2/search_me
lib/search_me/search.rb
SearchMe.Search.attr_search
def attr_search(*attributes) options = attributes.last.is_a?(Hash) ? attributes.pop : {} type = (options.fetch(:type) { :simple }).to_sym accepted_keys = [:simple] + self.reflections.keys.map(&:to_sym) unless accepted_keys.include?(type.to_sym) raise ArgumentError, 'incorect type given' end search_attributes_hash!(attributes, type, search_attributes) end
ruby
def attr_search(*attributes) options = attributes.last.is_a?(Hash) ? attributes.pop : {} type = (options.fetch(:type) { :simple }).to_sym accepted_keys = [:simple] + self.reflections.keys.map(&:to_sym) unless accepted_keys.include?(type.to_sym) raise ArgumentError, 'incorect type given' end search_attributes_hash!(attributes, type, search_attributes) end
[ "def", "attr_search", "(", "*", "attributes", ")", "options", "=", "attributes", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "attributes", ".", "pop", ":", "{", "}", "type", "=", "(", "options", ".", "fetch", "(", ":type", ")", "{", ":simple", "}", ")", ".", "to_sym", "accepted_keys", "=", "[", ":simple", "]", "+", "self", ".", "reflections", ".", "keys", ".", "map", "(", ":to_sym", ")", "unless", "accepted_keys", ".", "include?", "(", "type", ".", "to_sym", ")", "raise", "ArgumentError", ",", "'incorect type given'", "end", "search_attributes_hash!", "(", "attributes", ",", "type", ",", "search_attributes", ")", "end" ]
assuming the last attribute could be a hash
[ "assuming", "the", "last", "attribute", "could", "be", "a", "hash" ]
22057dd6008a7022247bca5ad30450a3abbee9df
https://github.com/jphager2/search_me/blob/22057dd6008a7022247bca5ad30450a3abbee9df/lib/search_me/search.rb#L18-L28
6,638
JuanGongora/mtg-card-finder
lib/mtg_card_finder/concerns/persistable.rb
Persistable.ClassMethods.reify_from_row
def reify_from_row(row) #the tap method allows preconfigured methods and values to #be associated with the instance during instantiation while also automatically returning #the object after its creation is concluded. self.new.tap do |card| self.attributes.keys.each.with_index do |key, index| #sending the new instance the key name as a setter with the value located at the 'row' index card.send("#{key}=", row[index]) #string interpolation is used as the method doesn't know the key name yet #but an = sign is implemented into the string in order to asssociate it as a setter end end end
ruby
def reify_from_row(row) #the tap method allows preconfigured methods and values to #be associated with the instance during instantiation while also automatically returning #the object after its creation is concluded. self.new.tap do |card| self.attributes.keys.each.with_index do |key, index| #sending the new instance the key name as a setter with the value located at the 'row' index card.send("#{key}=", row[index]) #string interpolation is used as the method doesn't know the key name yet #but an = sign is implemented into the string in order to asssociate it as a setter end end end
[ "def", "reify_from_row", "(", "row", ")", "#the tap method allows preconfigured methods and values to", "#be associated with the instance during instantiation while also automatically returning", "#the object after its creation is concluded.", "self", ".", "new", ".", "tap", "do", "|", "card", "|", "self", ".", "attributes", ".", "keys", ".", "each", ".", "with_index", "do", "|", "key", ",", "index", "|", "#sending the new instance the key name as a setter with the value located at the 'row' index", "card", ".", "send", "(", "\"#{key}=\"", ",", "row", "[", "index", "]", ")", "#string interpolation is used as the method doesn't know the key name yet", "#but an = sign is implemented into the string in order to asssociate it as a setter", "end", "end", "end" ]
opposite of abstraction is reification i.e. I'm getting the raw data of these variables
[ "opposite", "of", "abstraction", "is", "reification", "i", ".", "e", ".", "I", "m", "getting", "the", "raw", "data", "of", "these", "variables" ]
a4d2ed1368f4cff8c6f51a1b96ce3a4c3dabfbef
https://github.com/JuanGongora/mtg-card-finder/blob/a4d2ed1368f4cff8c6f51a1b96ce3a4c3dabfbef/lib/mtg_card_finder/concerns/persistable.rb#L130-L142
6,639
barkerest/shells
lib/shells/shell_base/exec.rb
Shells.ShellBase.exec
def exec(command, options = {}, &block) raise Shells::NotRunning unless running? options ||= {} options = { timeout_error: true, get_output: true }.merge(options) options = self.options.merge(options.inject({}) { |m,(k,v)| m[k.to_sym] = v; m }) options[:retrieve_exit_code] = self.options[:retrieve_exit_code] if options[:retrieve_exit_code] == :default options[:on_non_zero_exit_code] = self.options[:on_non_zero_exit_code] unless [:raise, :ignore].include?(options[:on_non_zero_exit_code]) options[:silence_timeout] = self.options[:silence_timeout] if options[:silence_timeout] == :default options[:command_timeout] = self.options[:command_timeout] if options[:command_timeout] == :default options[:command_is_echoed] = true if options[:command_is_echoed].nil? ret = '' merge_local_buffer do begin # buffer while also passing data to the supplied block. if block_given? buffer_output(&block) end command = command.to_s # send the command and wait for the prompt to return. debug 'Queueing command: ' + command queue_input command + line_ending if wait_for_prompt(options[:silence_timeout], options[:command_timeout], options[:timeout_error]) # get the output of the command, minus the trailing prompt. ret = if options[:get_output] debug 'Reading output of command...' command_output command, options[:command_is_echoed] else '' end if options[:retrieve_exit_code] self.last_exit_code = get_exit_code if options[:on_non_zero_exit_code] == :raise raise NonZeroExitCode.new(last_exit_code) unless last_exit_code == 0 || last_exit_code == :undefined end else self.last_exit_code = nil end else # A timeout occurred and timeout_error was set to false. self.last_exit_code = :timeout ret = output end ensure # return buffering to normal. if block_given? buffer_output end end end ret end
ruby
def exec(command, options = {}, &block) raise Shells::NotRunning unless running? options ||= {} options = { timeout_error: true, get_output: true }.merge(options) options = self.options.merge(options.inject({}) { |m,(k,v)| m[k.to_sym] = v; m }) options[:retrieve_exit_code] = self.options[:retrieve_exit_code] if options[:retrieve_exit_code] == :default options[:on_non_zero_exit_code] = self.options[:on_non_zero_exit_code] unless [:raise, :ignore].include?(options[:on_non_zero_exit_code]) options[:silence_timeout] = self.options[:silence_timeout] if options[:silence_timeout] == :default options[:command_timeout] = self.options[:command_timeout] if options[:command_timeout] == :default options[:command_is_echoed] = true if options[:command_is_echoed].nil? ret = '' merge_local_buffer do begin # buffer while also passing data to the supplied block. if block_given? buffer_output(&block) end command = command.to_s # send the command and wait for the prompt to return. debug 'Queueing command: ' + command queue_input command + line_ending if wait_for_prompt(options[:silence_timeout], options[:command_timeout], options[:timeout_error]) # get the output of the command, minus the trailing prompt. ret = if options[:get_output] debug 'Reading output of command...' command_output command, options[:command_is_echoed] else '' end if options[:retrieve_exit_code] self.last_exit_code = get_exit_code if options[:on_non_zero_exit_code] == :raise raise NonZeroExitCode.new(last_exit_code) unless last_exit_code == 0 || last_exit_code == :undefined end else self.last_exit_code = nil end else # A timeout occurred and timeout_error was set to false. self.last_exit_code = :timeout ret = output end ensure # return buffering to normal. if block_given? buffer_output end end end ret end
[ "def", "exec", "(", "command", ",", "options", "=", "{", "}", ",", "&", "block", ")", "raise", "Shells", "::", "NotRunning", "unless", "running?", "options", "||=", "{", "}", "options", "=", "{", "timeout_error", ":", "true", ",", "get_output", ":", "true", "}", ".", "merge", "(", "options", ")", "options", "=", "self", ".", "options", ".", "merge", "(", "options", ".", "inject", "(", "{", "}", ")", "{", "|", "m", ",", "(", "k", ",", "v", ")", "|", "m", "[", "k", ".", "to_sym", "]", "=", "v", ";", "m", "}", ")", "options", "[", ":retrieve_exit_code", "]", "=", "self", ".", "options", "[", ":retrieve_exit_code", "]", "if", "options", "[", ":retrieve_exit_code", "]", "==", ":default", "options", "[", ":on_non_zero_exit_code", "]", "=", "self", ".", "options", "[", ":on_non_zero_exit_code", "]", "unless", "[", ":raise", ",", ":ignore", "]", ".", "include?", "(", "options", "[", ":on_non_zero_exit_code", "]", ")", "options", "[", ":silence_timeout", "]", "=", "self", ".", "options", "[", ":silence_timeout", "]", "if", "options", "[", ":silence_timeout", "]", "==", ":default", "options", "[", ":command_timeout", "]", "=", "self", ".", "options", "[", ":command_timeout", "]", "if", "options", "[", ":command_timeout", "]", "==", ":default", "options", "[", ":command_is_echoed", "]", "=", "true", "if", "options", "[", ":command_is_echoed", "]", ".", "nil?", "ret", "=", "''", "merge_local_buffer", "do", "begin", "# buffer while also passing data to the supplied block.\r", "if", "block_given?", "buffer_output", "(", "block", ")", "end", "command", "=", "command", ".", "to_s", "# send the command and wait for the prompt to return.\r", "debug", "'Queueing command: '", "+", "command", "queue_input", "command", "+", "line_ending", "if", "wait_for_prompt", "(", "options", "[", ":silence_timeout", "]", ",", "options", "[", ":command_timeout", "]", ",", "options", "[", ":timeout_error", "]", ")", "# get the output of the command, minus the trailing prompt.\r", "ret", "=", "if", "options", "[", ":get_output", "]", "debug", "'Reading output of command...'", "command_output", "command", ",", "options", "[", ":command_is_echoed", "]", "else", "''", "end", "if", "options", "[", ":retrieve_exit_code", "]", "self", ".", "last_exit_code", "=", "get_exit_code", "if", "options", "[", ":on_non_zero_exit_code", "]", "==", ":raise", "raise", "NonZeroExitCode", ".", "new", "(", "last_exit_code", ")", "unless", "last_exit_code", "==", "0", "||", "last_exit_code", "==", ":undefined", "end", "else", "self", ".", "last_exit_code", "=", "nil", "end", "else", "# A timeout occurred and timeout_error was set to false.\r", "self", ".", "last_exit_code", "=", ":timeout", "ret", "=", "output", "end", "ensure", "# return buffering to normal.\r", "if", "block_given?", "buffer_output", "end", "end", "end", "ret", "end" ]
Executes a command during the shell session. If called outside of the +new+ block, this will raise an error. The +command+ is the command to execute in the shell. The +options+ can be used to override the exit code behavior. In all cases, the :default option is the same as not providing the option and will cause +exec+ to inherit the option from the shell's options. +retrieve_exit_code+:: This can be one of :default, true, or false. +on_non_zero_exit_code+:: This can be on ot :default, :ignore, or :raise. +silence_timeout+:: This can be :default or the number of seconds to wait in silence before timing out. +command_timeout+:: This can be :default or the maximum number of seconds to wait for a command to finish before timing out. If provided, the +block+ is a chunk of code that will be processed every time the shell receives output from the program. If the block returns a string, the string will be sent to the shell. This can be used to monitor processes or monitor and interact with processes. The +block+ is optional. shell.exec('sudo -p "password:" nginx restart') do |data,type| return 'super-secret' if /password:$/.match(data) nil end
[ "Executes", "a", "command", "during", "the", "shell", "session", "." ]
674a0254f48cea01b0ae8979933f13892e398506
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/exec.rb#L51-L110
6,640
barkerest/shells
lib/shells/shell_base/exec.rb
Shells.ShellBase.command_output
def command_output(command, expect_command = true) #:doc: # get everything except for the ending prompt. ret = if (prompt_pos = (output =~ prompt_match)) output[0...prompt_pos] else output end if expect_command command_regex = command_match(command) # Go until we run out of data or we find one of the possible command starts. # Note that we EXPECT the command to the first line of the output from the command because we expect the # shell to echo it back to us. result_cmd,_,result_data = ret.partition("\n") until result_data.to_s.strip == '' || result_cmd.strip =~ command_regex result_cmd,_,result_data = result_data.partition("\n") end if result_cmd.nil? || !(result_cmd =~ command_regex) STDERR.puts "SHELL WARNING: Failed to match #{command_regex.inspect}." end result_data else ret end end
ruby
def command_output(command, expect_command = true) #:doc: # get everything except for the ending prompt. ret = if (prompt_pos = (output =~ prompt_match)) output[0...prompt_pos] else output end if expect_command command_regex = command_match(command) # Go until we run out of data or we find one of the possible command starts. # Note that we EXPECT the command to the first line of the output from the command because we expect the # shell to echo it back to us. result_cmd,_,result_data = ret.partition("\n") until result_data.to_s.strip == '' || result_cmd.strip =~ command_regex result_cmd,_,result_data = result_data.partition("\n") end if result_cmd.nil? || !(result_cmd =~ command_regex) STDERR.puts "SHELL WARNING: Failed to match #{command_regex.inspect}." end result_data else ret end end
[ "def", "command_output", "(", "command", ",", "expect_command", "=", "true", ")", "#:doc:\r", "# get everything except for the ending prompt.\r", "ret", "=", "if", "(", "prompt_pos", "=", "(", "output", "=~", "prompt_match", ")", ")", "output", "[", "0", "...", "prompt_pos", "]", "else", "output", "end", "if", "expect_command", "command_regex", "=", "command_match", "(", "command", ")", "# Go until we run out of data or we find one of the possible command starts.\r", "# Note that we EXPECT the command to the first line of the output from the command because we expect the\r", "# shell to echo it back to us.\r", "result_cmd", ",", "_", ",", "result_data", "=", "ret", ".", "partition", "(", "\"\\n\"", ")", "until", "result_data", ".", "to_s", ".", "strip", "==", "''", "||", "result_cmd", ".", "strip", "=~", "command_regex", "result_cmd", ",", "_", ",", "result_data", "=", "result_data", ".", "partition", "(", "\"\\n\"", ")", "end", "if", "result_cmd", ".", "nil?", "||", "!", "(", "result_cmd", "=~", "command_regex", ")", "STDERR", ".", "puts", "\"SHELL WARNING: Failed to match #{command_regex.inspect}.\"", "end", "result_data", "else", "ret", "end", "end" ]
Gets the output from a command.
[ "Gets", "the", "output", "from", "a", "command", "." ]
674a0254f48cea01b0ae8979933f13892e398506
https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/exec.rb#L135-L163
6,641
riddopic/garcun
lib/garcon/utility/crypto.rb
Garcon.Crypto.decrypt
def decrypt(encrypted_text, password = nil, salt = nil) password = password.nil? ? Garcon.crypto.password : password salt = salt.nil? ? Garcon.crypto.salt : salt iv_ciphertext = Base64.decode64(encrypted_text) cipher = new_cipher(:decrypt, password, salt) cipher.iv, ciphertext = separate_iv_ciphertext(cipher, iv_ciphertext) plain_text = cipher.update(ciphertext) plain_text << cipher.final plain_text end
ruby
def decrypt(encrypted_text, password = nil, salt = nil) password = password.nil? ? Garcon.crypto.password : password salt = salt.nil? ? Garcon.crypto.salt : salt iv_ciphertext = Base64.decode64(encrypted_text) cipher = new_cipher(:decrypt, password, salt) cipher.iv, ciphertext = separate_iv_ciphertext(cipher, iv_ciphertext) plain_text = cipher.update(ciphertext) plain_text << cipher.final plain_text end
[ "def", "decrypt", "(", "encrypted_text", ",", "password", "=", "nil", ",", "salt", "=", "nil", ")", "password", "=", "password", ".", "nil?", "?", "Garcon", ".", "crypto", ".", "password", ":", "password", "salt", "=", "salt", ".", "nil?", "?", "Garcon", ".", "crypto", ".", "salt", ":", "salt", "iv_ciphertext", "=", "Base64", ".", "decode64", "(", "encrypted_text", ")", "cipher", "=", "new_cipher", "(", ":decrypt", ",", "password", ",", "salt", ")", "cipher", ".", "iv", ",", "ciphertext", "=", "separate_iv_ciphertext", "(", "cipher", ",", "iv_ciphertext", ")", "plain_text", "=", "cipher", ".", "update", "(", "ciphertext", ")", "plain_text", "<<", "cipher", ".", "final", "plain_text", "end" ]
Decrypt the given string, using the salt and password supplied. @param [String] encrypted_text The text to decrypt, probably produced with #decrypt. @param [String] password Secret passphrase to decrypt with. @param [String] salt The cryptographically secure pseudo-random string used to spice up the encryption of your strings. @return [String] The decrypted plain_text. @api public
[ "Decrypt", "the", "given", "string", "using", "the", "salt", "and", "password", "supplied", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/crypto.rb#L180-L190
6,642
riddopic/garcun
lib/garcon/utility/crypto.rb
Garcon.Crypto.salted_hash
def salted_hash(password) salt = SecureRandom.random_bytes(SALT_BYTE_SIZE) pbkdf2 = OpenSSL::PKCS5::pbkdf2_hmac_sha1( password, salt, CRYPTERATIONS, HASH_BYTE_SIZE ) { salt: salt, pbkdf2: Base64.encode64(pbkdf2) } end
ruby
def salted_hash(password) salt = SecureRandom.random_bytes(SALT_BYTE_SIZE) pbkdf2 = OpenSSL::PKCS5::pbkdf2_hmac_sha1( password, salt, CRYPTERATIONS, HASH_BYTE_SIZE ) { salt: salt, pbkdf2: Base64.encode64(pbkdf2) } end
[ "def", "salted_hash", "(", "password", ")", "salt", "=", "SecureRandom", ".", "random_bytes", "(", "SALT_BYTE_SIZE", ")", "pbkdf2", "=", "OpenSSL", "::", "PKCS5", "::", "pbkdf2_hmac_sha1", "(", "password", ",", "salt", ",", "CRYPTERATIONS", ",", "HASH_BYTE_SIZE", ")", "{", "salt", ":", "salt", ",", "pbkdf2", ":", "Base64", ".", "encode64", "(", "pbkdf2", ")", "}", "end" ]
Generates a special hash known as a SPASH, a PBKDF2-HMAC-SHA1 Salted Password Hash for safekeeping. @param [String] password A password to generating the SPASH, salted password hash. @return [Hash] `:salt` contains the unique salt used, `:pbkdf2` contains the password hash. Save both the salt and the hash together. @see Garcon::Crypto#validate_salt @api public
[ "Generates", "a", "special", "hash", "known", "as", "a", "SPASH", "a", "PBKDF2", "-", "HMAC", "-", "SHA1", "Salted", "Password", "Hash", "for", "safekeeping", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/crypto.rb#L205-L212
6,643
riddopic/garcun
lib/garcon/utility/crypto.rb
Garcon.Crypto.new_cipher
def new_cipher(direction, password, salt) cipher = OpenSSL::Cipher::Cipher.new(CIPHER_TYPE) direction == :encrypt ? cipher.encrypt : cipher.decrypt cipher.key = encrypt_key(password, salt) cipher end
ruby
def new_cipher(direction, password, salt) cipher = OpenSSL::Cipher::Cipher.new(CIPHER_TYPE) direction == :encrypt ? cipher.encrypt : cipher.decrypt cipher.key = encrypt_key(password, salt) cipher end
[ "def", "new_cipher", "(", "direction", ",", "password", ",", "salt", ")", "cipher", "=", "OpenSSL", "::", "Cipher", "::", "Cipher", ".", "new", "(", "CIPHER_TYPE", ")", "direction", "==", ":encrypt", "?", "cipher", ".", "encrypt", ":", "cipher", ".", "decrypt", "cipher", ".", "key", "=", "encrypt_key", "(", "password", ",", "salt", ")", "cipher", "end" ]
A T T E N Z I O N E A R E A P R O T E T T A Create a new cipher machine, with its dials set in the given direction. @param [Symbol] direction Whether to `:encrypt` or `:decrypt`. @param [String] pass Secret passphrase to decrypt with. @api private
[ "A", "T", "T", "E", "N", "Z", "I", "O", "N", "E", "A", "R", "E", "A", "P", "R", "O", "T", "E", "T", "T", "A", "Create", "a", "new", "cipher", "machine", "with", "its", "dials", "set", "in", "the", "given", "direction", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/crypto.rb#L256-L261
6,644
riddopic/garcun
lib/garcon/utility/crypto.rb
Garcon.Crypto.combine_iv_ciphertext
def combine_iv_ciphertext(iv, message) message.force_encoding('BINARY') if message.respond_to?(:force_encoding) iv.force_encoding('BINARY') if iv.respond_to?(:force_encoding) iv + message end
ruby
def combine_iv_ciphertext(iv, message) message.force_encoding('BINARY') if message.respond_to?(:force_encoding) iv.force_encoding('BINARY') if iv.respond_to?(:force_encoding) iv + message end
[ "def", "combine_iv_ciphertext", "(", "iv", ",", "message", ")", "message", ".", "force_encoding", "(", "'BINARY'", ")", "if", "message", ".", "respond_to?", "(", ":force_encoding", ")", "iv", ".", "force_encoding", "(", "'BINARY'", ")", "if", "iv", ".", "respond_to?", "(", ":force_encoding", ")", "iv", "+", "message", "end" ]
Prepend the initialization vector to the encoded message. @api private
[ "Prepend", "the", "initialization", "vector", "to", "the", "encoded", "message", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/crypto.rb#L266-L270
6,645
riddopic/garcun
lib/garcon/utility/crypto.rb
Garcon.Crypto.separate_iv_ciphertext
def separate_iv_ciphertext(cipher, iv_ciphertext) idx = cipher.iv_len [iv_ciphertext[0..(idx - 1)], iv_ciphertext[idx..-1]] end
ruby
def separate_iv_ciphertext(cipher, iv_ciphertext) idx = cipher.iv_len [iv_ciphertext[0..(idx - 1)], iv_ciphertext[idx..-1]] end
[ "def", "separate_iv_ciphertext", "(", "cipher", ",", "iv_ciphertext", ")", "idx", "=", "cipher", ".", "iv_len", "[", "iv_ciphertext", "[", "0", "..", "(", "idx", "-", "1", ")", "]", ",", "iv_ciphertext", "[", "idx", "..", "-", "1", "]", "]", "end" ]
Pull the initialization vector from the front of the encoded message. @api private
[ "Pull", "the", "initialization", "vector", "from", "the", "front", "of", "the", "encoded", "message", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/crypto.rb#L275-L278
6,646
riddopic/garcun
lib/garcon/utility/crypto.rb
Garcon.Crypto.encrypt_key
def encrypt_key(password, salt) iterations, length = CRYPTERATIONS, HASH_BYTE_SIZE OpenSSL::PKCS5::pbkdf2_hmac_sha1(password, salt, iterations, length) end
ruby
def encrypt_key(password, salt) iterations, length = CRYPTERATIONS, HASH_BYTE_SIZE OpenSSL::PKCS5::pbkdf2_hmac_sha1(password, salt, iterations, length) end
[ "def", "encrypt_key", "(", "password", ",", "salt", ")", "iterations", ",", "length", "=", "CRYPTERATIONS", ",", "HASH_BYTE_SIZE", "OpenSSL", "::", "PKCS5", "::", "pbkdf2_hmac_sha1", "(", "password", ",", "salt", ",", "iterations", ",", "length", ")", "end" ]
Convert the password into a PBKDF2-HMAC-SHA1 salted key used for safely encrypting and decrypting all your ciphers strings. @api private
[ "Convert", "the", "password", "into", "a", "PBKDF2", "-", "HMAC", "-", "SHA1", "salted", "key", "used", "for", "safely", "encrypting", "and", "decrypting", "all", "your", "ciphers", "strings", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/utility/crypto.rb#L284-L287
6,647
codescrum/bebox
lib/bebox/commands/environment_commands.rb
Bebox.EnvironmentCommands.environment_list_command
def environment_list_command(environment_command) environment_command.desc 'List the remote environments in the project' environment_command.command :list do |environment_list_command| environment_list_command.action do |global_options,options,args| environments = Bebox::Environment.list(project_root) title _('cli.environment.list.current_envs') environments.map{|environment| msg(environment)} warn(_('cli.environment.list.no_envs')) if environments.empty? end end end
ruby
def environment_list_command(environment_command) environment_command.desc 'List the remote environments in the project' environment_command.command :list do |environment_list_command| environment_list_command.action do |global_options,options,args| environments = Bebox::Environment.list(project_root) title _('cli.environment.list.current_envs') environments.map{|environment| msg(environment)} warn(_('cli.environment.list.no_envs')) if environments.empty? end end end
[ "def", "environment_list_command", "(", "environment_command", ")", "environment_command", ".", "desc", "'List the remote environments in the project'", "environment_command", ".", "command", ":list", "do", "|", "environment_list_command", "|", "environment_list_command", ".", "action", "do", "|", "global_options", ",", "options", ",", "args", "|", "environments", "=", "Bebox", "::", "Environment", ".", "list", "(", "project_root", ")", "title", "_", "(", "'cli.environment.list.current_envs'", ")", "environments", ".", "map", "{", "|", "environment", "|", "msg", "(", "environment", ")", "}", "warn", "(", "_", "(", "'cli.environment.list.no_envs'", ")", ")", "if", "environments", ".", "empty?", "end", "end", "end" ]
Environment list command
[ "Environment", "list", "command" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/commands/environment_commands.rb#L31-L41
6,648
Nowaker/ruby-ansi-sys-revived
lib/ansisys.rb
AnsiSys.CSSFormatter.hash_to_styles
def hash_to_styles(hash, separator = '; ') unless hash.empty? return hash.map{|e| "#{e[0]}: #{e[1].join(' ')}"}.join(separator) else return nil end end
ruby
def hash_to_styles(hash, separator = '; ') unless hash.empty? return hash.map{|e| "#{e[0]}: #{e[1].join(' ')}"}.join(separator) else return nil end end
[ "def", "hash_to_styles", "(", "hash", ",", "separator", "=", "'; '", ")", "unless", "hash", ".", "empty?", "return", "hash", ".", "map", "{", "|", "e", "|", "\"#{e[0]}: #{e[1].join(' ')}\"", "}", ".", "join", "(", "separator", ")", "else", "return", "nil", "end", "end" ]
make a CSS style-let from a Hash of CSS settings
[ "make", "a", "CSS", "style", "-", "let", "from", "a", "Hash", "of", "CSS", "settings" ]
6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688
https://github.com/Nowaker/ruby-ansi-sys-revived/blob/6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688/lib/ansisys.rb#L16-L22
6,649
Nowaker/ruby-ansi-sys-revived
lib/ansisys.rb
AnsiSys.Lexer.lex!
def lex! r = Array.new @buffer.gsub!(/(?:\r\n|\n\r)/, "\n") while @code_start_re =~ @buffer r << [:string, $`] unless $`.empty? if CODE_EQUIVALENT.has_key?($&) CODE_EQUIVALENT[$&].each do |c| r << [:code, c] end @buffer = $' else csi = $& residual = $' if PARAMETER_AND_LETTER =~ residual r << [:code, $&] @buffer = $' else @buffer = csi + residual return r end end end r << [:string, @buffer] unless @buffer.empty? @buffer = '' return r end
ruby
def lex! r = Array.new @buffer.gsub!(/(?:\r\n|\n\r)/, "\n") while @code_start_re =~ @buffer r << [:string, $`] unless $`.empty? if CODE_EQUIVALENT.has_key?($&) CODE_EQUIVALENT[$&].each do |c| r << [:code, c] end @buffer = $' else csi = $& residual = $' if PARAMETER_AND_LETTER =~ residual r << [:code, $&] @buffer = $' else @buffer = csi + residual return r end end end r << [:string, @buffer] unless @buffer.empty? @buffer = '' return r end
[ "def", "lex!", "r", "=", "Array", ".", "new", "@buffer", ".", "gsub!", "(", "/", "\\r", "\\n", "\\n", "\\r", "/", ",", "\"\\n\"", ")", "while", "@code_start_re", "=~", "@buffer", "r", "<<", "[", ":string", ",", "$`", "]", "unless", "$`", ".", "empty?", "if", "CODE_EQUIVALENT", ".", "has_key?", "(", "$&", ")", "CODE_EQUIVALENT", "[", "$&", "]", ".", "each", "do", "|", "c", "|", "r", "<<", "[", ":code", ",", "c", "]", "end", "@buffer", "=", "$'", "else", "csi", "=", "$&", "residual", "=", "$'", "if", "PARAMETER_AND_LETTER", "=~", "residual", "r", "<<", "[", ":code", ",", "$&", "]", "@buffer", "=", "$'", "else", "@buffer", "=", "csi", "+", "residual", "return", "r", "end", "end", "end", "r", "<<", "[", ":string", ",", "@buffer", "]", "unless", "@buffer", ".", "empty?", "@buffer", "=", "''", "return", "r", "end" ]
returns array of tokens while deleting the tokenized part from buffer
[ "returns", "array", "of", "tokens", "while", "deleting", "the", "tokenized", "part", "from", "buffer" ]
6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688
https://github.com/Nowaker/ruby-ansi-sys-revived/blob/6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688/lib/ansisys.rb#L68-L93
6,650
Nowaker/ruby-ansi-sys-revived
lib/ansisys.rb
AnsiSys.Characters.echo_on
def echo_on(screen, cursor) each_char do |c| w = width(c) cursor.fit!(w) screen.write(c, w, cursor.cur_col, cursor.cur_row, @sgr.dup) cursor.advance!(w) end return self end
ruby
def echo_on(screen, cursor) each_char do |c| w = width(c) cursor.fit!(w) screen.write(c, w, cursor.cur_col, cursor.cur_row, @sgr.dup) cursor.advance!(w) end return self end
[ "def", "echo_on", "(", "screen", ",", "cursor", ")", "each_char", "do", "|", "c", "|", "w", "=", "width", "(", "c", ")", "cursor", ".", "fit!", "(", "w", ")", "screen", ".", "write", "(", "c", ",", "w", ",", "cursor", ".", "cur_col", ",", "cursor", ".", "cur_row", ",", "@sgr", ".", "dup", ")", "cursor", ".", "advance!", "(", "w", ")", "end", "return", "self", "end" ]
Select Graphic Rendition associated with the text echo the string onto the _screen_ with initial cursor as _cursor_ _cursor_ position will be changed as the string is echoed
[ "Select", "Graphic", "Rendition", "associated", "with", "the", "text", "echo", "the", "string", "onto", "the", "_screen_", "with", "initial", "cursor", "as", "_cursor_", "_cursor_", "position", "will", "be", "changed", "as", "the", "string", "is", "echoed" ]
6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688
https://github.com/Nowaker/ruby-ansi-sys-revived/blob/6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688/lib/ansisys.rb#L112-L120
6,651
Nowaker/ruby-ansi-sys-revived
lib/ansisys.rb
AnsiSys.Cursor.apply_code!
def apply_code!(letter, *pars) case letter when 'A' @cur_row -= pars[0] ? pars[0] : 1 @cur_row = @max_row if @max_row and @cur_row > @max_row when 'B' @cur_row += pars[0] ? pars[0] : 1 @cur_row = @max_row if @max_row and @cur_row > @max_row when 'C' @cur_col += pars[0] ? pars[0] : 1 when 'D' @cur_col -= pars[0] ? pars[0] : 1 when 'E' @cur_row += pars[0] ? pars[0] : 1 @cur_col = 1 @max_row = @cur_row if @max_row and @cur_row > @max_row when 'F' @cur_row -= pars[0] ? pars[0] : 1 @cur_col = 1 @max_row = @cur_row if @max_row and @cur_row > @max_row when 'G' @cur_col = pars[0] ? pars[0] : 1 when 'H' @cur_row = pars[0] ? pars[0] : 1 @cur_col = pars[1] ? pars[1] : 1 @max_row = @cur_row if @max_row and @cur_row > @max_row when 'f' @cur_row = pars[0] ? pars[0] : 1 @cur_col = pars[1] ? pars[1] : 1 @max_row = @cur_row if @max_row and @cur_row > @max_row end if @cur_row < 1 @cur_row = 1 end if @cur_col < 1 @cur_col = 1 elsif @cur_col > @max_col @cur_col = @max_col end return self end
ruby
def apply_code!(letter, *pars) case letter when 'A' @cur_row -= pars[0] ? pars[0] : 1 @cur_row = @max_row if @max_row and @cur_row > @max_row when 'B' @cur_row += pars[0] ? pars[0] : 1 @cur_row = @max_row if @max_row and @cur_row > @max_row when 'C' @cur_col += pars[0] ? pars[0] : 1 when 'D' @cur_col -= pars[0] ? pars[0] : 1 when 'E' @cur_row += pars[0] ? pars[0] : 1 @cur_col = 1 @max_row = @cur_row if @max_row and @cur_row > @max_row when 'F' @cur_row -= pars[0] ? pars[0] : 1 @cur_col = 1 @max_row = @cur_row if @max_row and @cur_row > @max_row when 'G' @cur_col = pars[0] ? pars[0] : 1 when 'H' @cur_row = pars[0] ? pars[0] : 1 @cur_col = pars[1] ? pars[1] : 1 @max_row = @cur_row if @max_row and @cur_row > @max_row when 'f' @cur_row = pars[0] ? pars[0] : 1 @cur_col = pars[1] ? pars[1] : 1 @max_row = @cur_row if @max_row and @cur_row > @max_row end if @cur_row < 1 @cur_row = 1 end if @cur_col < 1 @cur_col = 1 elsif @cur_col > @max_col @cur_col = @max_col end return self end
[ "def", "apply_code!", "(", "letter", ",", "*", "pars", ")", "case", "letter", "when", "'A'", "@cur_row", "-=", "pars", "[", "0", "]", "?", "pars", "[", "0", "]", ":", "1", "@cur_row", "=", "@max_row", "if", "@max_row", "and", "@cur_row", ">", "@max_row", "when", "'B'", "@cur_row", "+=", "pars", "[", "0", "]", "?", "pars", "[", "0", "]", ":", "1", "@cur_row", "=", "@max_row", "if", "@max_row", "and", "@cur_row", ">", "@max_row", "when", "'C'", "@cur_col", "+=", "pars", "[", "0", "]", "?", "pars", "[", "0", "]", ":", "1", "when", "'D'", "@cur_col", "-=", "pars", "[", "0", "]", "?", "pars", "[", "0", "]", ":", "1", "when", "'E'", "@cur_row", "+=", "pars", "[", "0", "]", "?", "pars", "[", "0", "]", ":", "1", "@cur_col", "=", "1", "@max_row", "=", "@cur_row", "if", "@max_row", "and", "@cur_row", ">", "@max_row", "when", "'F'", "@cur_row", "-=", "pars", "[", "0", "]", "?", "pars", "[", "0", "]", ":", "1", "@cur_col", "=", "1", "@max_row", "=", "@cur_row", "if", "@max_row", "and", "@cur_row", ">", "@max_row", "when", "'G'", "@cur_col", "=", "pars", "[", "0", "]", "?", "pars", "[", "0", "]", ":", "1", "when", "'H'", "@cur_row", "=", "pars", "[", "0", "]", "?", "pars", "[", "0", "]", ":", "1", "@cur_col", "=", "pars", "[", "1", "]", "?", "pars", "[", "1", "]", ":", "1", "@max_row", "=", "@cur_row", "if", "@max_row", "and", "@cur_row", ">", "@max_row", "when", "'f'", "@cur_row", "=", "pars", "[", "0", "]", "?", "pars", "[", "0", "]", ":", "1", "@cur_col", "=", "pars", "[", "1", "]", "?", "pars", "[", "1", "]", ":", "1", "@max_row", "=", "@cur_row", "if", "@max_row", "and", "@cur_row", ">", "@max_row", "end", "if", "@cur_row", "<", "1", "@cur_row", "=", "1", "end", "if", "@cur_col", "<", "1", "@cur_col", "=", "1", "elsif", "@cur_col", ">", "@max_col", "@cur_col", "=", "@max_col", "end", "return", "self", "end" ]
maximum row number applies self an escape sequence code that ends with _letter_ as String and with some _pars_ as Integers
[ "maximum", "row", "number", "applies", "self", "an", "escape", "sequence", "code", "that", "ends", "with", "_letter_", "as", "String", "and", "with", "some", "_pars_", "as", "Integers" ]
6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688
https://github.com/Nowaker/ruby-ansi-sys-revived/blob/6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688/lib/ansisys.rb#L167-L207
6,652
Nowaker/ruby-ansi-sys-revived
lib/ansisys.rb
AnsiSys.SGR.css_styles
def css_styles(colors = Screen.default_css_colors) r = Hash.new{|h, k| h[k] = Array.new} # intensity is not (yet) implemented r['font-style'] << 'italic' if @italic == :on r['text-decoration'] << 'underline' unless @underline == :none r['text-decoration'] << 'blink' unless @blink == :off case @image when :positive fg = @foreground bg = @background when :negative fg = @background bg = @foreground end fg = bg if @conceal == :on r['color'] << colors[@intensity][fg] unless fg == :white r['background-color'] << colors[@intensity][bg] unless bg == :black return r end
ruby
def css_styles(colors = Screen.default_css_colors) r = Hash.new{|h, k| h[k] = Array.new} # intensity is not (yet) implemented r['font-style'] << 'italic' if @italic == :on r['text-decoration'] << 'underline' unless @underline == :none r['text-decoration'] << 'blink' unless @blink == :off case @image when :positive fg = @foreground bg = @background when :negative fg = @background bg = @foreground end fg = bg if @conceal == :on r['color'] << colors[@intensity][fg] unless fg == :white r['background-color'] << colors[@intensity][bg] unless bg == :black return r end
[ "def", "css_styles", "(", "colors", "=", "Screen", ".", "default_css_colors", ")", "r", "=", "Hash", ".", "new", "{", "|", "h", ",", "k", "|", "h", "[", "k", "]", "=", "Array", ".", "new", "}", "# intensity is not (yet) implemented", "r", "[", "'font-style'", "]", "<<", "'italic'", "if", "@italic", "==", ":on", "r", "[", "'text-decoration'", "]", "<<", "'underline'", "unless", "@underline", "==", ":none", "r", "[", "'text-decoration'", "]", "<<", "'blink'", "unless", "@blink", "==", ":off", "case", "@image", "when", ":positive", "fg", "=", "@foreground", "bg", "=", "@background", "when", ":negative", "fg", "=", "@background", "bg", "=", "@foreground", "end", "fg", "=", "bg", "if", "@conceal", "==", ":on", "r", "[", "'color'", "]", "<<", "colors", "[", "@intensity", "]", "[", "fg", "]", "unless", "fg", "==", ":white", "r", "[", "'background-color'", "]", "<<", "colors", "[", "@intensity", "]", "[", "bg", "]", "unless", "bg", "==", ":black", "return", "r", "end" ]
a Hash of CSS stylelet
[ "a", "Hash", "of", "CSS", "stylelet" ]
6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688
https://github.com/Nowaker/ruby-ansi-sys-revived/blob/6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688/lib/ansisys.rb#L364-L382
6,653
Nowaker/ruby-ansi-sys-revived
lib/ansisys.rb
AnsiSys.Screen.write
def write(char, char_width, col, row, sgr) @lines[Integer(row)][Integer(col)] = [char, char_width, sgr.dup] end
ruby
def write(char, char_width, col, row, sgr) @lines[Integer(row)][Integer(col)] = [char, char_width, sgr.dup] end
[ "def", "write", "(", "char", ",", "char_width", ",", "col", ",", "row", ",", "sgr", ")", "@lines", "[", "Integer", "(", "row", ")", "]", "[", "Integer", "(", "col", ")", "]", "=", "[", "char", ",", "char_width", ",", "sgr", ".", "dup", "]", "end" ]
register the _char_ at a specific location on Screen
[ "register", "the", "_char_", "at", "a", "specific", "location", "on", "Screen" ]
6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688
https://github.com/Nowaker/ruby-ansi-sys-revived/blob/6ad4b8fa96af4a3ef4c3aafbcf3ebe1684665688/lib/ansisys.rb#L517-L519
6,654
nico-hn/PseudoHikiParser
lib/pseudohiki/htmlplugin.rb
PseudoHiki.HtmlPlugin.anchor
def anchor name, anchor_mark = @data.split(/,\s*/o, 2) anchor_mark = "_" if (anchor_mark.nil? or anchor_mark.empty?) HtmlElement.create("a", anchor_mark, "name" => name, "href" => "#" + name) end
ruby
def anchor name, anchor_mark = @data.split(/,\s*/o, 2) anchor_mark = "_" if (anchor_mark.nil? or anchor_mark.empty?) HtmlElement.create("a", anchor_mark, "name" => name, "href" => "#" + name) end
[ "def", "anchor", "name", ",", "anchor_mark", "=", "@data", ".", "split", "(", "/", "\\s", "/o", ",", "2", ")", "anchor_mark", "=", "\"_\"", "if", "(", "anchor_mark", ".", "nil?", "or", "anchor_mark", ".", "empty?", ")", "HtmlElement", ".", "create", "(", "\"a\"", ",", "anchor_mark", ",", "\"name\"", "=>", "name", ",", "\"href\"", "=>", "\"#\"", "+", "name", ")", "end" ]
def inline lines = HtmlElement.decode(@data).split(/\r*\n/o) lines.shift if lines.first == "" HikiBlockParser.new.parse_lines(lines).join end
[ "def", "inline", "lines", "=", "HtmlElement", ".", "decode", "(" ]
d8c3d13be30409f094317ef81bd37c660dbc242d
https://github.com/nico-hn/PseudoHikiParser/blob/d8c3d13be30409f094317ef81bd37c660dbc242d/lib/pseudohiki/htmlplugin.rb#L67-L73
6,655
wedesoft/multiarray
lib/multiarray/gccfunction.rb
Hornetseye.GCCFunction.params
def params idx = 0 @param_types.collect do |param_type| args = GCCType.new( param_type ).identifiers.collect do arg = GCCValue.new self, "param#{idx}" idx += 1 arg end param_type.construct *args end end
ruby
def params idx = 0 @param_types.collect do |param_type| args = GCCType.new( param_type ).identifiers.collect do arg = GCCValue.new self, "param#{idx}" idx += 1 arg end param_type.construct *args end end
[ "def", "params", "idx", "=", "0", "@param_types", ".", "collect", "do", "|", "param_type", "|", "args", "=", "GCCType", ".", "new", "(", "param_type", ")", ".", "identifiers", ".", "collect", "do", "arg", "=", "GCCValue", ".", "new", "self", ",", "\"param#{idx}\"", "idx", "+=", "1", "arg", "end", "param_type", ".", "construct", "args", "end", "end" ]
Retrieve all parameters @return [Array<Node>] Objects for handling the parameters. @private
[ "Retrieve", "all", "parameters" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/gccfunction.rb#L146-L156
6,656
burlesona/nform
lib/nform/html.rb
NForm.HTML.tag
def tag(name, attributes={}, &block) open = sjoin name, attrs(attributes) body = block.call if block_given? if VOID_ELEMENTS.include?(name.to_sym) raise BuilderError, "Void elements cannot have content" if body "<#{open}>" else "<#{open}>#{body}</#{name}>" end end
ruby
def tag(name, attributes={}, &block) open = sjoin name, attrs(attributes) body = block.call if block_given? if VOID_ELEMENTS.include?(name.to_sym) raise BuilderError, "Void elements cannot have content" if body "<#{open}>" else "<#{open}>#{body}</#{name}>" end end
[ "def", "tag", "(", "name", ",", "attributes", "=", "{", "}", ",", "&", "block", ")", "open", "=", "sjoin", "name", ",", "attrs", "(", "attributes", ")", "body", "=", "block", ".", "call", "if", "block_given?", "if", "VOID_ELEMENTS", ".", "include?", "(", "name", ".", "to_sym", ")", "raise", "BuilderError", ",", "\"Void elements cannot have content\"", "if", "body", "\"<#{open}>\"", "else", "\"<#{open}>#{body}</#{name}>\"", "end", "end" ]
Generate an HTML Tag
[ "Generate", "an", "HTML", "Tag" ]
3ba467b55e9fbb480856d069c1792c2ad41da921
https://github.com/burlesona/nform/blob/3ba467b55e9fbb480856d069c1792c2ad41da921/lib/nform/html.rb#L8-L17
6,657
robfors/ruby-sumac
lib/sumac/objects.rb
Sumac.Objects.process_forget
def process_forget(object, quiet: ) reference = convert_object_to_reference(object, build: false) raise UnexposedObjectError unless reference reference.local_forget_request(quiet: quiet) end
ruby
def process_forget(object, quiet: ) reference = convert_object_to_reference(object, build: false) raise UnexposedObjectError unless reference reference.local_forget_request(quiet: quiet) end
[ "def", "process_forget", "(", "object", ",", "quiet", ":", ")", "reference", "=", "convert_object_to_reference", "(", "object", ",", "build", ":", "false", ")", "raise", "UnexposedObjectError", "unless", "reference", "reference", ".", "local_forget_request", "(", "quiet", ":", "quiet", ")", "end" ]
Process a request from the local application to forget an exposed object. @param object [LocalObject,RemoteObject] @param quiet [Boolean] suppress any message to the remote endpoint @raise [UnexposedObjectError] if object is not exposed or has never been sent on this {Connection} @return [void]
[ "Process", "a", "request", "from", "the", "local", "application", "to", "forget", "an", "exposed", "object", "." ]
524fa68b7d1bb10a74baa69cd594ab2b8cae20a3
https://github.com/robfors/ruby-sumac/blob/524fa68b7d1bb10a74baa69cd594ab2b8cae20a3/lib/sumac/objects.rb#L202-L206
6,658
robfors/ruby-sumac
lib/sumac/objects.rb
Sumac.Objects.process_forget_message
def process_forget_message(message, quiet: ) reference = convert_properties_to_reference(message.object, build: false) reference.remote_forget_request(quiet: quiet) end
ruby
def process_forget_message(message, quiet: ) reference = convert_properties_to_reference(message.object, build: false) reference.remote_forget_request(quiet: quiet) end
[ "def", "process_forget_message", "(", "message", ",", "quiet", ":", ")", "reference", "=", "convert_properties_to_reference", "(", "message", ".", "object", ",", "build", ":", "false", ")", "reference", ".", "remote_forget_request", "(", "quiet", ":", "quiet", ")", "end" ]
Processes a request from the remote endpoint to forget an exposed object. Called when a forget message has been received by the messenger. @param message [Message::Forget] @param quiet [Boolean] suppress any message to the remote endpoint @raise [ProtocolError] if reference does not exist with id received @return [void]
[ "Processes", "a", "request", "from", "the", "remote", "endpoint", "to", "forget", "an", "exposed", "object", ".", "Called", "when", "a", "forget", "message", "has", "been", "received", "by", "the", "messenger", "." ]
524fa68b7d1bb10a74baa69cd594ab2b8cae20a3
https://github.com/robfors/ruby-sumac/blob/524fa68b7d1bb10a74baa69cd594ab2b8cae20a3/lib/sumac/objects.rb#L214-L217
6,659
wedesoft/multiarray
lib/multiarray/node.rb
Hornetseye.Node.memorise
def memorise if memory contiguous_strides = (0 ... dimension).collect do |i| shape[0 ... i].inject 1, :* end if strides == contiguous_strides self else dup end else dup end end
ruby
def memorise if memory contiguous_strides = (0 ... dimension).collect do |i| shape[0 ... i].inject 1, :* end if strides == contiguous_strides self else dup end else dup end end
[ "def", "memorise", "if", "memory", "contiguous_strides", "=", "(", "0", "...", "dimension", ")", ".", "collect", "do", "|", "i", "|", "shape", "[", "0", "...", "i", "]", ".", "inject", "1", ",", ":*", "end", "if", "strides", "==", "contiguous_strides", "self", "else", "dup", "end", "else", "dup", "end", "end" ]
Duplicate array expression if it is not in row-major format @return [Node] Duplicate of array or +self+.
[ "Duplicate", "array", "expression", "if", "it", "is", "not", "in", "row", "-", "major", "format" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/node.rb#L329-L342
6,660
wedesoft/multiarray
lib/multiarray/node.rb
Hornetseye.Node.to_a
def to_a if dimension == 0 force else n = shape.last ( 0 ... n ).collect { |i| element( i ).to_a } end end
ruby
def to_a if dimension == 0 force else n = shape.last ( 0 ... n ).collect { |i| element( i ).to_a } end end
[ "def", "to_a", "if", "dimension", "==", "0", "force", "else", "n", "=", "shape", ".", "last", "(", "0", "...", "n", ")", ".", "collect", "{", "|", "i", "|", "element", "(", "i", ")", ".", "to_a", "}", "end", "end" ]
Convert to Ruby array of objects Perform pending computations and convert native array to Ruby array of objects. @return [Array<Object>] Array of objects.
[ "Convert", "to", "Ruby", "array", "of", "objects" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/node.rb#L412-L419
6,661
wedesoft/multiarray
lib/multiarray/node.rb
Hornetseye.Node.inspect
def inspect( indent = nil, lines = nil ) if variables.empty? if dimension == 0 and not indent "#{typecode.inspect}(#{force.inspect})" else if indent prepend = '' else prepend = "#{Hornetseye::MultiArray(typecode, dimension).inspect}:\n" indent = 0 lines = 0 end if empty? retval = '[]' else retval = '[ ' for i in 0 ... shape.last x = element i if x.dimension > 0 if i > 0 retval += ",\n " lines += 1 if lines >= 10 retval += '...' if indent == 0 break end retval += ' ' * indent end str = x.inspect indent + 1, lines lines += str.count "\n" retval += str if lines >= 10 retval += '...' if indent == 0 break end else retval += ', ' if i > 0 str = x.force.inspect if retval.size + str.size >= 74 - '...'.size - '[ ]'.size * indent.succ retval += '...' break else retval += str end end end retval += ' ]' unless lines >= 10 end prepend + retval end else to_s end end
ruby
def inspect( indent = nil, lines = nil ) if variables.empty? if dimension == 0 and not indent "#{typecode.inspect}(#{force.inspect})" else if indent prepend = '' else prepend = "#{Hornetseye::MultiArray(typecode, dimension).inspect}:\n" indent = 0 lines = 0 end if empty? retval = '[]' else retval = '[ ' for i in 0 ... shape.last x = element i if x.dimension > 0 if i > 0 retval += ",\n " lines += 1 if lines >= 10 retval += '...' if indent == 0 break end retval += ' ' * indent end str = x.inspect indent + 1, lines lines += str.count "\n" retval += str if lines >= 10 retval += '...' if indent == 0 break end else retval += ', ' if i > 0 str = x.force.inspect if retval.size + str.size >= 74 - '...'.size - '[ ]'.size * indent.succ retval += '...' break else retval += str end end end retval += ' ]' unless lines >= 10 end prepend + retval end else to_s end end
[ "def", "inspect", "(", "indent", "=", "nil", ",", "lines", "=", "nil", ")", "if", "variables", ".", "empty?", "if", "dimension", "==", "0", "and", "not", "indent", "\"#{typecode.inspect}(#{force.inspect})\"", "else", "if", "indent", "prepend", "=", "''", "else", "prepend", "=", "\"#{Hornetseye::MultiArray(typecode, dimension).inspect}:\\n\"", "indent", "=", "0", "lines", "=", "0", "end", "if", "empty?", "retval", "=", "'[]'", "else", "retval", "=", "'[ '", "for", "i", "in", "0", "...", "shape", ".", "last", "x", "=", "element", "i", "if", "x", ".", "dimension", ">", "0", "if", "i", ">", "0", "retval", "+=", "\",\\n \"", "lines", "+=", "1", "if", "lines", ">=", "10", "retval", "+=", "'...'", "if", "indent", "==", "0", "break", "end", "retval", "+=", "' '", "*", "indent", "end", "str", "=", "x", ".", "inspect", "indent", "+", "1", ",", "lines", "lines", "+=", "str", ".", "count", "\"\\n\"", "retval", "+=", "str", "if", "lines", ">=", "10", "retval", "+=", "'...'", "if", "indent", "==", "0", "break", "end", "else", "retval", "+=", "', '", "if", "i", ">", "0", "str", "=", "x", ".", "force", ".", "inspect", "if", "retval", ".", "size", "+", "str", ".", "size", ">=", "74", "-", "'...'", ".", "size", "-", "'[ ]'", ".", "size", "*", "indent", ".", "succ", "retval", "+=", "'...'", "break", "else", "retval", "+=", "str", "end", "end", "end", "retval", "+=", "' ]'", "unless", "lines", ">=", "10", "end", "prepend", "+", "retval", "end", "else", "to_s", "end", "end" ]
Display information about this object @return [String] String with information about this object.
[ "Display", "information", "about", "this", "object" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/node.rb#L424-L478
6,662
wedesoft/multiarray
lib/multiarray/node.rb
Hornetseye.Node.check_shape
def check_shape(*args) _shape = shape args.each do |arg| _arg_shape = arg.shape if _shape.size < _arg_shape.size raise "#{arg.inspect} has #{arg.dimension} dimension(s) " + "but should not have more than #{dimension}" end if ( _shape + _arg_shape ).all? { |s| s.is_a? Integer } if _shape.last( _arg_shape.size ) != _arg_shape raise "#{arg.inspect} has shape #{arg.shape.inspect} " + "(does not match last value(s) of #{shape.inspect})" end end end end
ruby
def check_shape(*args) _shape = shape args.each do |arg| _arg_shape = arg.shape if _shape.size < _arg_shape.size raise "#{arg.inspect} has #{arg.dimension} dimension(s) " + "but should not have more than #{dimension}" end if ( _shape + _arg_shape ).all? { |s| s.is_a? Integer } if _shape.last( _arg_shape.size ) != _arg_shape raise "#{arg.inspect} has shape #{arg.shape.inspect} " + "(does not match last value(s) of #{shape.inspect})" end end end end
[ "def", "check_shape", "(", "*", "args", ")", "_shape", "=", "shape", "args", ".", "each", "do", "|", "arg", "|", "_arg_shape", "=", "arg", ".", "shape", "if", "_shape", ".", "size", "<", "_arg_shape", ".", "size", "raise", "\"#{arg.inspect} has #{arg.dimension} dimension(s) \"", "+", "\"but should not have more than #{dimension}\"", "end", "if", "(", "_shape", "+", "_arg_shape", ")", ".", "all?", "{", "|", "s", "|", "s", ".", "is_a?", "Integer", "}", "if", "_shape", ".", "last", "(", "_arg_shape", ".", "size", ")", "!=", "_arg_shape", "raise", "\"#{arg.inspect} has shape #{arg.shape.inspect} \"", "+", "\"(does not match last value(s) of #{shape.inspect})\"", "end", "end", "end", "end" ]
Check arguments for compatible shape The method will throw an exception if one of the arguments has an incompatible shape. @param [Array<Class>] args Arguments to check for compatibility. @return [Object] The return value should be ignored.
[ "Check", "arguments", "for", "compatible", "shape" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/node.rb#L570-L585
6,663
wedesoft/multiarray
lib/multiarray/node.rb
Hornetseye.Node.force
def force if finalised? get elsif (dimension > 0 and Thread.current[:lazy]) or not variables.empty? self elsif compilable? retval = allocate GCCFunction.run Store.new(retval, self) retval.demand.get else retval = allocate Store.new(retval, self).demand retval.demand.get end end
ruby
def force if finalised? get elsif (dimension > 0 and Thread.current[:lazy]) or not variables.empty? self elsif compilable? retval = allocate GCCFunction.run Store.new(retval, self) retval.demand.get else retval = allocate Store.new(retval, self).demand retval.demand.get end end
[ "def", "force", "if", "finalised?", "get", "elsif", "(", "dimension", ">", "0", "and", "Thread", ".", "current", "[", ":lazy", "]", ")", "or", "not", "variables", ".", "empty?", "self", "elsif", "compilable?", "retval", "=", "allocate", "GCCFunction", ".", "run", "Store", ".", "new", "(", "retval", ",", "self", ")", "retval", ".", "demand", ".", "get", "else", "retval", "=", "allocate", "Store", ".", "new", "(", "retval", ",", "self", ")", ".", "demand", "retval", ".", "demand", ".", "get", "end", "end" ]
Force delayed computation unless in lazy mode @return [Node,Object] Result of computation @see #demand @private
[ "Force", "delayed", "computation", "unless", "in", "lazy", "mode" ]
1ae1d98bacb4b941d6f406e44ccb184de12f83d9
https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/node.rb#L656-L670
6,664
alltom/ruck
lib/ruck/shreduler.rb
Ruck.ShredConvenienceMethods.yield
def yield(dt, clock = nil) clock ||= $shreduler.clock $shreduler.shredule(Shred.current, clock.now + dt, clock) Shred.current.pause end
ruby
def yield(dt, clock = nil) clock ||= $shreduler.clock $shreduler.shredule(Shred.current, clock.now + dt, clock) Shred.current.pause end
[ "def", "yield", "(", "dt", ",", "clock", "=", "nil", ")", "clock", "||=", "$shreduler", ".", "clock", "$shreduler", ".", "shredule", "(", "Shred", ".", "current", ",", "clock", ".", "now", "+", "dt", ",", "clock", ")", "Shred", ".", "current", ".", "pause", "end" ]
yields the given amount of time on the global Shreduler, using the provided Clock if given
[ "yields", "the", "given", "amount", "of", "time", "on", "the", "global", "Shreduler", "using", "the", "provided", "Clock", "if", "given" ]
a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d
https://github.com/alltom/ruck/blob/a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d/lib/ruck/shreduler.rb#L109-L113
6,665
alltom/ruck
lib/ruck/shreduler.rb
Ruck.ShredConvenienceMethods.wait_on
def wait_on(event) $shreduler.shredule(Shred.current, event, $shreduler.event_clock) Shred.current.pause end
ruby
def wait_on(event) $shreduler.shredule(Shred.current, event, $shreduler.event_clock) Shred.current.pause end
[ "def", "wait_on", "(", "event", ")", "$shreduler", ".", "shredule", "(", "Shred", ".", "current", ",", "event", ",", "$shreduler", ".", "event_clock", ")", "Shred", ".", "current", ".", "pause", "end" ]
sleeps, waiting on the given event on the default EventClock of the global Shreduler
[ "sleeps", "waiting", "on", "the", "given", "event", "on", "the", "default", "EventClock", "of", "the", "global", "Shreduler" ]
a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d
https://github.com/alltom/ruck/blob/a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d/lib/ruck/shreduler.rb#L117-L120
6,666
alltom/ruck
lib/ruck/shreduler.rb
Ruck.Shreduler.run_one
def run_one shred, relative_time = @clock.unschedule_next return nil unless shred fast_forward(relative_time) if relative_time > 0 invoke_shred(shred) end
ruby
def run_one shred, relative_time = @clock.unschedule_next return nil unless shred fast_forward(relative_time) if relative_time > 0 invoke_shred(shred) end
[ "def", "run_one", "shred", ",", "relative_time", "=", "@clock", ".", "unschedule_next", "return", "nil", "unless", "shred", "fast_forward", "(", "relative_time", ")", "if", "relative_time", ">", "0", "invoke_shred", "(", "shred", ")", "end" ]
runs the next scheduled Shred, if one exists, returning that Shred
[ "runs", "the", "next", "scheduled", "Shred", "if", "one", "exists", "returning", "that", "Shred" ]
a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d
https://github.com/alltom/ruck/blob/a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d/lib/ruck/shreduler.rb#L42-L48
6,667
alltom/ruck
lib/ruck/shreduler.rb
Ruck.Shreduler.run_until
def run_until(target_time) return if target_time < now loop do shred, relative_time = next_shred break unless shred break unless now + relative_time <= target_time run_one end # I hope rounding errors are okay fast_forward(target_time - now) end
ruby
def run_until(target_time) return if target_time < now loop do shred, relative_time = next_shred break unless shred break unless now + relative_time <= target_time run_one end # I hope rounding errors are okay fast_forward(target_time - now) end
[ "def", "run_until", "(", "target_time", ")", "return", "if", "target_time", "<", "now", "loop", "do", "shred", ",", "relative_time", "=", "next_shred", "break", "unless", "shred", "break", "unless", "now", "+", "relative_time", "<=", "target_time", "run_one", "end", "# I hope rounding errors are okay", "fast_forward", "(", "target_time", "-", "now", ")", "end" ]
runs shreds until the given target time, then fast-forwards to that time
[ "runs", "shreds", "until", "the", "given", "target", "time", "then", "fast", "-", "forwards", "to", "that", "time" ]
a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d
https://github.com/alltom/ruck/blob/a4556b1c9ef97cbc64cb7d580dc2ca4738e6c75d/lib/ruck/shreduler.rb#L57-L69
6,668
GemHQ/coin-op
lib/coin-op/bit/transaction.rb
CoinOp::Bit.Transaction.validate_syntax
def validate_syntax update_native validator = Bitcoin::Validation::Tx.new(@native, nil) valid = validator.validate :rules => [:syntax] {:valid => valid, :error => validator.error} end
ruby
def validate_syntax update_native validator = Bitcoin::Validation::Tx.new(@native, nil) valid = validator.validate :rules => [:syntax] {:valid => valid, :error => validator.error} end
[ "def", "validate_syntax", "update_native", "validator", "=", "Bitcoin", "::", "Validation", "::", "Tx", ".", "new", "(", "@native", ",", "nil", ")", "valid", "=", "validator", ".", "validate", ":rules", "=>", "[", ":syntax", "]", "{", ":valid", "=>", "valid", ",", ":error", "=>", "validator", ".", "error", "}", "end" ]
Validate that the transaction is plausibly signable.
[ "Validate", "that", "the", "transaction", "is", "plausibly", "signable", "." ]
0b704b52d9826405cffb1606e914bf21b8dcc681
https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/transaction.rb#L131-L136
6,669
GemHQ/coin-op
lib/coin-op/bit/transaction.rb
CoinOp::Bit.Transaction.validate_script_sigs
def validate_script_sigs bad_inputs = [] valid = true @inputs.each_with_index do |input, index| # TODO: confirm whether we need to mess with the block_timestamp arg unless self.native.verify_input_signature(index, input.output.transaction.native) valid = false bad_inputs << index end end {:valid => valid, :inputs => bad_inputs} end
ruby
def validate_script_sigs bad_inputs = [] valid = true @inputs.each_with_index do |input, index| # TODO: confirm whether we need to mess with the block_timestamp arg unless self.native.verify_input_signature(index, input.output.transaction.native) valid = false bad_inputs << index end end {:valid => valid, :inputs => bad_inputs} end
[ "def", "validate_script_sigs", "bad_inputs", "=", "[", "]", "valid", "=", "true", "@inputs", ".", "each_with_index", "do", "|", "input", ",", "index", "|", "# TODO: confirm whether we need to mess with the block_timestamp arg", "unless", "self", ".", "native", ".", "verify_input_signature", "(", "index", ",", "input", ".", "output", ".", "transaction", ".", "native", ")", "valid", "=", "false", "bad_inputs", "<<", "index", "end", "end", "{", ":valid", "=>", "valid", ",", ":inputs", "=>", "bad_inputs", "}", "end" ]
Verify that the script_sigs for all inputs are valid.
[ "Verify", "that", "the", "script_sigs", "for", "all", "inputs", "are", "valid", "." ]
0b704b52d9826405cffb1606e914bf21b8dcc681
https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/transaction.rb#L139-L151
6,670
GemHQ/coin-op
lib/coin-op/bit/transaction.rb
CoinOp::Bit.Transaction.add_input
def add_input(input, network: @network) # TODO: allow specifying prev_tx and index with a Hash. # Possibly stop using SparseInput. input = Input.new(input.merge(transaction: self, index: @inputs.size, network: network) ) unless input.is_a?(Input) @inputs << input self.update_native do |native| native.add_in input.native end input end
ruby
def add_input(input, network: @network) # TODO: allow specifying prev_tx and index with a Hash. # Possibly stop using SparseInput. input = Input.new(input.merge(transaction: self, index: @inputs.size, network: network) ) unless input.is_a?(Input) @inputs << input self.update_native do |native| native.add_in input.native end input end
[ "def", "add_input", "(", "input", ",", "network", ":", "@network", ")", "# TODO: allow specifying prev_tx and index with a Hash.", "# Possibly stop using SparseInput.", "input", "=", "Input", ".", "new", "(", "input", ".", "merge", "(", "transaction", ":", "self", ",", "index", ":", "@inputs", ".", "size", ",", "network", ":", "network", ")", ")", "unless", "input", ".", "is_a?", "(", "Input", ")", "@inputs", "<<", "input", "self", ".", "update_native", "do", "|", "native", "|", "native", ".", "add_in", "input", ".", "native", "end", "input", "end" ]
Takes one of * an instance of Input * an instance of Output * a Hash describing an Output
[ "Takes", "one", "of" ]
0b704b52d9826405cffb1606e914bf21b8dcc681
https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/transaction.rb#L159-L173
6,671
GemHQ/coin-op
lib/coin-op/bit/transaction.rb
CoinOp::Bit.Transaction.add_output
def add_output(output, network: @network) if output.is_a?(Output) output.set_transaction(self, @outputs.size) else output = Output.new(output.merge(transaction: self, index: @outputs.size), network: network) end @outputs << output self.update_native do |native| native.add_out(output.native) end end
ruby
def add_output(output, network: @network) if output.is_a?(Output) output.set_transaction(self, @outputs.size) else output = Output.new(output.merge(transaction: self, index: @outputs.size), network: network) end @outputs << output self.update_native do |native| native.add_out(output.native) end end
[ "def", "add_output", "(", "output", ",", "network", ":", "@network", ")", "if", "output", ".", "is_a?", "(", "Output", ")", "output", ".", "set_transaction", "(", "self", ",", "@outputs", ".", "size", ")", "else", "output", "=", "Output", ".", "new", "(", "output", ".", "merge", "(", "transaction", ":", "self", ",", "index", ":", "@outputs", ".", "size", ")", ",", "network", ":", "network", ")", "end", "@outputs", "<<", "output", "self", ".", "update_native", "do", "|", "native", "|", "native", ".", "add_out", "(", "output", ".", "native", ")", "end", "end" ]
Takes either an Output or a Hash describing an output.
[ "Takes", "either", "an", "Output", "or", "a", "Hash", "describing", "an", "output", "." ]
0b704b52d9826405cffb1606e914bf21b8dcc681
https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/transaction.rb#L176-L189
6,672
GemHQ/coin-op
lib/coin-op/bit/transaction.rb
CoinOp::Bit.Transaction.set_script_sigs
def set_script_sigs(*input_args, &block) # No sense trying to authorize when the transaction isn't usable. report = validate_syntax unless report[:valid] == true raise "Invalid syntax: #{report[:errors].to_json}" end # Array#zip here allows us to iterate over the inputs in lockstep with any # number of sets of values. self.inputs.zip(*input_args) do |input, *input_arg| input.script_sig = yield input, *input_arg end end
ruby
def set_script_sigs(*input_args, &block) # No sense trying to authorize when the transaction isn't usable. report = validate_syntax unless report[:valid] == true raise "Invalid syntax: #{report[:errors].to_json}" end # Array#zip here allows us to iterate over the inputs in lockstep with any # number of sets of values. self.inputs.zip(*input_args) do |input, *input_arg| input.script_sig = yield input, *input_arg end end
[ "def", "set_script_sigs", "(", "*", "input_args", ",", "&", "block", ")", "# No sense trying to authorize when the transaction isn't usable.", "report", "=", "validate_syntax", "unless", "report", "[", ":valid", "]", "==", "true", "raise", "\"Invalid syntax: #{report[:errors].to_json}\"", "end", "# Array#zip here allows us to iterate over the inputs in lockstep with any", "# number of sets of values.", "self", ".", "inputs", ".", "zip", "(", "input_args", ")", "do", "|", "input", ",", "*", "input_arg", "|", "input", ".", "script_sig", "=", "yield", "input", ",", "input_arg", "end", "end" ]
A convenience method for authorizing inputs in a generic manner. Rather than iterating over the inputs manually, the user can provide this method with an array of values and a block that knows what to do with the values. For example, if you happen to have the script sigs precomputed for some strange reason, you could do this: tx.set_script_sigs sig_array do |input, sig| sig end More realistically, if you have an array of the keypairs corresponding to the inputs: tx.set_script_sigs keys do |input, key| sig_hash = tx.sig_hash(input) key.sign(sig_hash) end Each element of the array may be an array, which allows for easy handling of multisig situations.
[ "A", "convenience", "method", "for", "authorizing", "inputs", "in", "a", "generic", "manner", ".", "Rather", "than", "iterating", "over", "the", "inputs", "manually", "the", "user", "can", "provide", "this", "method", "with", "an", "array", "of", "values", "and", "a", "block", "that", "knows", "what", "to", "do", "with", "the", "values", "." ]
0b704b52d9826405cffb1606e914bf21b8dcc681
https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/transaction.rb#L276-L288
6,673
GemHQ/coin-op
lib/coin-op/bit/transaction.rb
CoinOp::Bit.Transaction.input_value_for
def input_value_for(addresses) own = inputs.select { |input| addresses.include?(input.output.address) } own.inject(0) { |sum, input| input.output.value } end
ruby
def input_value_for(addresses) own = inputs.select { |input| addresses.include?(input.output.address) } own.inject(0) { |sum, input| input.output.value } end
[ "def", "input_value_for", "(", "addresses", ")", "own", "=", "inputs", ".", "select", "{", "|", "input", "|", "addresses", ".", "include?", "(", "input", ".", "output", ".", "address", ")", "}", "own", ".", "inject", "(", "0", ")", "{", "|", "sum", ",", "input", "|", "input", ".", "output", ".", "value", "}", "end" ]
Takes a set of Bitcoin addresses and returns the value expressed in the inputs for this transaction.
[ "Takes", "a", "set", "of", "Bitcoin", "addresses", "and", "returns", "the", "value", "expressed", "in", "the", "inputs", "for", "this", "transaction", "." ]
0b704b52d9826405cffb1606e914bf21b8dcc681
https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/transaction.rb#L339-L342
6,674
GemHQ/coin-op
lib/coin-op/bit/transaction.rb
CoinOp::Bit.Transaction.output_value_for
def output_value_for(addresses) own = outputs.select { |output| addresses.include?(output.address) } own.inject(0) { |sum, output| output.value } end
ruby
def output_value_for(addresses) own = outputs.select { |output| addresses.include?(output.address) } own.inject(0) { |sum, output| output.value } end
[ "def", "output_value_for", "(", "addresses", ")", "own", "=", "outputs", ".", "select", "{", "|", "output", "|", "addresses", ".", "include?", "(", "output", ".", "address", ")", "}", "own", ".", "inject", "(", "0", ")", "{", "|", "sum", ",", "output", "|", "output", ".", "value", "}", "end" ]
Takes a set of Bitcoin addresses and returns the value expressed in the outputs for this transaction.
[ "Takes", "a", "set", "of", "Bitcoin", "addresses", "and", "returns", "the", "value", "expressed", "in", "the", "outputs", "for", "this", "transaction", "." ]
0b704b52d9826405cffb1606e914bf21b8dcc681
https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/transaction.rb#L346-L349
6,675
GemHQ/coin-op
lib/coin-op/bit/transaction.rb
CoinOp::Bit.Transaction.add_change
def add_change(address, metadata={}) add_output( value: change_value, address: address, metadata: {memo: "change"}.merge(metadata) ) end
ruby
def add_change(address, metadata={}) add_output( value: change_value, address: address, metadata: {memo: "change"}.merge(metadata) ) end
[ "def", "add_change", "(", "address", ",", "metadata", "=", "{", "}", ")", "add_output", "(", "value", ":", "change_value", ",", "address", ":", "address", ",", "metadata", ":", "{", "memo", ":", "\"change\"", "}", ".", "merge", "(", "metadata", ")", ")", "end" ]
Add an output to receive change for this transaction. Takes a bitcoin address and optional metadata Hash.
[ "Add", "an", "output", "to", "receive", "change", "for", "this", "transaction", ".", "Takes", "a", "bitcoin", "address", "and", "optional", "metadata", "Hash", "." ]
0b704b52d9826405cffb1606e914bf21b8dcc681
https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/transaction.rb#L358-L364
6,676
Dev-Crea/swagger-docs-generator
lib/swagger_docs_generator/extractor.rb
SwaggerDocsGenerator.Extractor.path
def path temporary = [] actual_route = nil router do |route| actual_route = extract_and_format_route(route) temporary.push(actual_route) unless temporary.include?(actual_route) actual_route end temporary end
ruby
def path temporary = [] actual_route = nil router do |route| actual_route = extract_and_format_route(route) temporary.push(actual_route) unless temporary.include?(actual_route) actual_route end temporary end
[ "def", "path", "temporary", "=", "[", "]", "actual_route", "=", "nil", "router", "do", "|", "route", "|", "actual_route", "=", "extract_and_format_route", "(", "route", ")", "temporary", ".", "push", "(", "actual_route", ")", "unless", "temporary", ".", "include?", "(", "actual_route", ")", "actual_route", "end", "temporary", "end" ]
Extract path to routes and change format to parameter path
[ "Extract", "path", "to", "routes", "and", "change", "format", "to", "parameter", "path" ]
5d3de176aa1119cb38100b451bee028d66c0809d
https://github.com/Dev-Crea/swagger-docs-generator/blob/5d3de176aa1119cb38100b451bee028d66c0809d/lib/swagger_docs_generator/extractor.rb#L26-L35
6,677
satchmorun/tst
lib/tst.rb
Tst.Assertions.assert_raises
def assert_raises(expected=StandardError) begin yield rescue => actual return actual if actual.kind_of?(expected) raise Failure.new("Failure: Unexpected Exception", expected, actual) end raise Failure.new("Failure: No Exception", expected, "Nothing raised.") end
ruby
def assert_raises(expected=StandardError) begin yield rescue => actual return actual if actual.kind_of?(expected) raise Failure.new("Failure: Unexpected Exception", expected, actual) end raise Failure.new("Failure: No Exception", expected, "Nothing raised.") end
[ "def", "assert_raises", "(", "expected", "=", "StandardError", ")", "begin", "yield", "rescue", "=>", "actual", "return", "actual", "if", "actual", ".", "kind_of?", "(", "expected", ")", "raise", "Failure", ".", "new", "(", "\"Failure: Unexpected Exception\"", ",", "expected", ",", "actual", ")", "end", "raise", "Failure", ".", "new", "(", "\"Failure: No Exception\"", ",", "expected", ",", "\"Nothing raised.\"", ")", "end" ]
Succeeds if it catches an error AND that error is a `kind_of?` the `expected` error. Fails otherwise.
[ "Succeeds", "if", "it", "catches", "an", "error", "AND", "that", "error", "is", "a", "kind_of?", "the", "expected", "error", ".", "Fails", "otherwise", "." ]
78bb3c034278eefb0db41e62e1e93b67735216a7
https://github.com/satchmorun/tst/blob/78bb3c034278eefb0db41e62e1e93b67735216a7/lib/tst.rb#L35-L43
6,678
satchmorun/tst
lib/tst.rb
Tst.Runner.tst
def tst(name, &block) start = Time.now block.call status = SUCCEEDED rescue Failure => exception status = FAILED rescue StandardError => exception status = RAISED ensure elapsed = Time.now - start __record(name, status, elapsed, exception) end
ruby
def tst(name, &block) start = Time.now block.call status = SUCCEEDED rescue Failure => exception status = FAILED rescue StandardError => exception status = RAISED ensure elapsed = Time.now - start __record(name, status, elapsed, exception) end
[ "def", "tst", "(", "name", ",", "&", "block", ")", "start", "=", "Time", ".", "now", "block", ".", "call", "status", "=", "SUCCEEDED", "rescue", "Failure", "=>", "exception", "status", "=", "FAILED", "rescue", "StandardError", "=>", "exception", "status", "=", "RAISED", "ensure", "elapsed", "=", "Time", ".", "now", "-", "start", "__record", "(", "name", ",", "status", ",", "elapsed", ",", "exception", ")", "end" ]
The `tst` methods itself. Takes a `name` and a block. Runs the block. Records the result.
[ "The", "tst", "methods", "itself", ".", "Takes", "a", "name", "and", "a", "block", ".", "Runs", "the", "block", ".", "Records", "the", "result", "." ]
78bb3c034278eefb0db41e62e1e93b67735216a7
https://github.com/satchmorun/tst/blob/78bb3c034278eefb0db41e62e1e93b67735216a7/lib/tst.rb#L99-L110
6,679
jinx/core
lib/jinx/metadata/propertied.rb
Jinx.Propertied.add_attribute
def add_attribute(attribute, type, *flags) prop = create_nonjava_property(attribute, type, *flags) add_property(prop) prop end
ruby
def add_attribute(attribute, type, *flags) prop = create_nonjava_property(attribute, type, *flags) add_property(prop) prop end
[ "def", "add_attribute", "(", "attribute", ",", "type", ",", "*", "flags", ")", "prop", "=", "create_nonjava_property", "(", "attribute", ",", "type", ",", "flags", ")", "add_property", "(", "prop", ")", "prop", "end" ]
Adds the given attribute to this Class. @param [Symbol] attribute the attribute to add @param [Class] type (see Property#initialize) @param flags (see Property#initialize) @return [Property] the attribute meta-data
[ "Adds", "the", "given", "attribute", "to", "this", "Class", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/propertied.rb#L30-L34
6,680
jinx/core
lib/jinx/metadata/propertied.rb
Jinx.Propertied.init_property_classifiers
def init_property_classifiers @local_std_prop_hash = {} @alias_std_prop_map = append_ancestor_enum(@local_std_prop_hash) { |par| par.alias_standard_attribute_hash } @local_prop_hash = {} @prop_hash = append_ancestor_enum(@local_prop_hash) { |par| par.property_hash } @attributes = Enumerable::Enumerator.new(@prop_hash, :each_key) @local_mndty_attrs = Set.new @local_defaults = {} @defaults = append_ancestor_enum(@local_defaults) { |par| par.defaults } end
ruby
def init_property_classifiers @local_std_prop_hash = {} @alias_std_prop_map = append_ancestor_enum(@local_std_prop_hash) { |par| par.alias_standard_attribute_hash } @local_prop_hash = {} @prop_hash = append_ancestor_enum(@local_prop_hash) { |par| par.property_hash } @attributes = Enumerable::Enumerator.new(@prop_hash, :each_key) @local_mndty_attrs = Set.new @local_defaults = {} @defaults = append_ancestor_enum(@local_defaults) { |par| par.defaults } end
[ "def", "init_property_classifiers", "@local_std_prop_hash", "=", "{", "}", "@alias_std_prop_map", "=", "append_ancestor_enum", "(", "@local_std_prop_hash", ")", "{", "|", "par", "|", "par", ".", "alias_standard_attribute_hash", "}", "@local_prop_hash", "=", "{", "}", "@prop_hash", "=", "append_ancestor_enum", "(", "@local_prop_hash", ")", "{", "|", "par", "|", "par", ".", "property_hash", "}", "@attributes", "=", "Enumerable", "::", "Enumerator", ".", "new", "(", "@prop_hash", ",", ":each_key", ")", "@local_mndty_attrs", "=", "Set", ".", "new", "@local_defaults", "=", "{", "}", "@defaults", "=", "append_ancestor_enum", "(", "@local_defaults", ")", "{", "|", "par", "|", "par", ".", "defaults", "}", "end" ]
Initializes the property meta-data structures.
[ "Initializes", "the", "property", "meta", "-", "data", "structures", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/propertied.rb#L259-L268
6,681
jinx/core
lib/jinx/metadata/propertied.rb
Jinx.Propertied.compose_property
def compose_property(property, other) if other.inverse.nil? then raise ArgumentError.new("Can't compose #{qp}.#{property} with inverseless #{other.declarer.qp}.#{other}") end # the source -> intermediary access methods sir, siw = property.accessors # the intermediary -> target access methods itr, itw = other.accessors # the target -> intermediary reader method tir = other.inverse # The reader composes the source -> intermediary -> target readers. define_method(itr) do ref = send(sir) ref.send(itr) if ref end # The writer sets the source intermediary to the target intermediary. define_method(itw) do |tgt| if tgt then ref = block_given? ? yield(tgt) : tgt.send(tir) raise ArgumentError.new("#{tgt} does not reference a #{other.inverse}") if ref.nil? end send(siw, ref) end prop = add_attribute(itr, other.type) logger.debug { "Created #{qp}.#{prop} which composes #{qp}.#{property} and #{other.declarer.qp}.#{other}." } prop.qualify(:collection) if other.collection? prop end
ruby
def compose_property(property, other) if other.inverse.nil? then raise ArgumentError.new("Can't compose #{qp}.#{property} with inverseless #{other.declarer.qp}.#{other}") end # the source -> intermediary access methods sir, siw = property.accessors # the intermediary -> target access methods itr, itw = other.accessors # the target -> intermediary reader method tir = other.inverse # The reader composes the source -> intermediary -> target readers. define_method(itr) do ref = send(sir) ref.send(itr) if ref end # The writer sets the source intermediary to the target intermediary. define_method(itw) do |tgt| if tgt then ref = block_given? ? yield(tgt) : tgt.send(tir) raise ArgumentError.new("#{tgt} does not reference a #{other.inverse}") if ref.nil? end send(siw, ref) end prop = add_attribute(itr, other.type) logger.debug { "Created #{qp}.#{prop} which composes #{qp}.#{property} and #{other.declarer.qp}.#{other}." } prop.qualify(:collection) if other.collection? prop end
[ "def", "compose_property", "(", "property", ",", "other", ")", "if", "other", ".", "inverse", ".", "nil?", "then", "raise", "ArgumentError", ".", "new", "(", "\"Can't compose #{qp}.#{property} with inverseless #{other.declarer.qp}.#{other}\"", ")", "end", "# the source -> intermediary access methods", "sir", ",", "siw", "=", "property", ".", "accessors", "# the intermediary -> target access methods", "itr", ",", "itw", "=", "other", ".", "accessors", "# the target -> intermediary reader method", "tir", "=", "other", ".", "inverse", "# The reader composes the source -> intermediary -> target readers.", "define_method", "(", "itr", ")", "do", "ref", "=", "send", "(", "sir", ")", "ref", ".", "send", "(", "itr", ")", "if", "ref", "end", "# The writer sets the source intermediary to the target intermediary.", "define_method", "(", "itw", ")", "do", "|", "tgt", "|", "if", "tgt", "then", "ref", "=", "block_given?", "?", "yield", "(", "tgt", ")", ":", "tgt", ".", "send", "(", "tir", ")", "raise", "ArgumentError", ".", "new", "(", "\"#{tgt} does not reference a #{other.inverse}\"", ")", "if", "ref", ".", "nil?", "end", "send", "(", "siw", ",", "ref", ")", "end", "prop", "=", "add_attribute", "(", "itr", ",", "other", ".", "type", ")", "logger", ".", "debug", "{", "\"Created #{qp}.#{prop} which composes #{qp}.#{property} and #{other.declarer.qp}.#{other}.\"", "}", "prop", ".", "qualify", "(", ":collection", ")", "if", "other", ".", "collection?", "prop", "end" ]
Creates a new convenience property in this source class which composes the given property and the other property. The new property symbol is the same as the other property symbol. The new property reader and writer methods delegate to the respective composed property reader and writer methods. @param [Property] property the reference from the source to the intermediary @param [Property] other the reference from the intermediary to the target @yield [target] obtain the intermediary object from the target @yieldparam [Resource] target the target object @return [Property] the new property @raise [ArgumentError] if the other property does not have an inverse
[ "Creates", "a", "new", "convenience", "property", "in", "this", "source", "class", "which", "composes", "the", "given", "property", "and", "the", "other", "property", ".", "The", "new", "property", "symbol", "is", "the", "same", "as", "the", "other", "property", "symbol", ".", "The", "new", "property", "reader", "and", "writer", "methods", "delegate", "to", "the", "respective", "composed", "property", "reader", "and", "writer", "methods", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/propertied.rb#L282-L309
6,682
jinx/core
lib/jinx/metadata/propertied.rb
Jinx.Propertied.most_specific_domain_attribute
def most_specific_domain_attribute(klass, attributes=nil) attributes ||= domain_attributes candidates = attributes.properties best = candidates.inject(nil) do |better, prop| # If the attribute can return the klass then the return type is a candidate. # In that case, the klass replaces the best candidate if it is more specific than # the best candidate so far. klass <= prop.type ? (better && better.type <= prop.type ? better : prop) : better end if best then logger.debug { "Most specific #{qp} -> #{klass.qp} reference from among #{candidates.qp} is #{best.declarer.qp}.#{best}." } best.to_sym end end
ruby
def most_specific_domain_attribute(klass, attributes=nil) attributes ||= domain_attributes candidates = attributes.properties best = candidates.inject(nil) do |better, prop| # If the attribute can return the klass then the return type is a candidate. # In that case, the klass replaces the best candidate if it is more specific than # the best candidate so far. klass <= prop.type ? (better && better.type <= prop.type ? better : prop) : better end if best then logger.debug { "Most specific #{qp} -> #{klass.qp} reference from among #{candidates.qp} is #{best.declarer.qp}.#{best}." } best.to_sym end end
[ "def", "most_specific_domain_attribute", "(", "klass", ",", "attributes", "=", "nil", ")", "attributes", "||=", "domain_attributes", "candidates", "=", "attributes", ".", "properties", "best", "=", "candidates", ".", "inject", "(", "nil", ")", "do", "|", "better", ",", "prop", "|", "# If the attribute can return the klass then the return type is a candidate.", "# In that case, the klass replaces the best candidate if it is more specific than", "# the best candidate so far.", "klass", "<=", "prop", ".", "type", "?", "(", "better", "&&", "better", ".", "type", "<=", "prop", ".", "type", "?", "better", ":", "prop", ")", ":", "better", "end", "if", "best", "then", "logger", ".", "debug", "{", "\"Most specific #{qp} -> #{klass.qp} reference from among #{candidates.qp} is #{best.declarer.qp}.#{best}.\"", "}", "best", ".", "to_sym", "end", "end" ]
Returns the most specific attribute which references the given target type, or nil if none. If the given class can be returned by more than on of the attributes, then the attribute is chosen whose return type most closely matches the given class. @param [Class] klass the target type @param [AttributeEnumerator, nil] attributes the attributes to check (default all domain attributes) @return [Symbol, nil] the most specific reference attribute, or nil if none
[ "Returns", "the", "most", "specific", "attribute", "which", "references", "the", "given", "target", "type", "or", "nil", "if", "none", ".", "If", "the", "given", "class", "can", "be", "returned", "by", "more", "than", "on", "of", "the", "attributes", "then", "the", "attribute", "is", "chosen", "whose", "return", "type", "most", "closely", "matches", "the", "given", "class", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/propertied.rb#L324-L337
6,683
jinx/core
lib/jinx/metadata/propertied.rb
Jinx.Propertied.set_attribute_type
def set_attribute_type(attribute, klass) prop = property(attribute) # degenerate no-op case return if klass == prop.type # If this class is the declarer, then simply set the attribute type. # Otherwise, if the attribute type is unspecified or is a superclass of the given class, # then make a new attribute metadata for this class. if prop.declarer == self then prop.type = klass logger.debug { "Set #{qp}.#{attribute} type to #{klass.qp}." } elsif prop.type.nil? or klass < prop.type then prop.restrict(self, :type => klass) logger.debug { "Restricted #{prop.declarer.qp}.#{attribute}(#{prop.type.qp}) to #{qp} with return type #{klass.qp}." } else raise ArgumentError.new("Cannot reset #{qp}.#{attribute} type #{prop.type.qp} to incompatible #{klass.qp}") end end
ruby
def set_attribute_type(attribute, klass) prop = property(attribute) # degenerate no-op case return if klass == prop.type # If this class is the declarer, then simply set the attribute type. # Otherwise, if the attribute type is unspecified or is a superclass of the given class, # then make a new attribute metadata for this class. if prop.declarer == self then prop.type = klass logger.debug { "Set #{qp}.#{attribute} type to #{klass.qp}." } elsif prop.type.nil? or klass < prop.type then prop.restrict(self, :type => klass) logger.debug { "Restricted #{prop.declarer.qp}.#{attribute}(#{prop.type.qp}) to #{qp} with return type #{klass.qp}." } else raise ArgumentError.new("Cannot reset #{qp}.#{attribute} type #{prop.type.qp} to incompatible #{klass.qp}") end end
[ "def", "set_attribute_type", "(", "attribute", ",", "klass", ")", "prop", "=", "property", "(", "attribute", ")", "# degenerate no-op case", "return", "if", "klass", "==", "prop", ".", "type", "# If this class is the declarer, then simply set the attribute type.", "# Otherwise, if the attribute type is unspecified or is a superclass of the given class,", "# then make a new attribute metadata for this class.", "if", "prop", ".", "declarer", "==", "self", "then", "prop", ".", "type", "=", "klass", "logger", ".", "debug", "{", "\"Set #{qp}.#{attribute} type to #{klass.qp}.\"", "}", "elsif", "prop", ".", "type", ".", "nil?", "or", "klass", "<", "prop", ".", "type", "then", "prop", ".", "restrict", "(", "self", ",", ":type", "=>", "klass", ")", "logger", ".", "debug", "{", "\"Restricted #{prop.declarer.qp}.#{attribute}(#{prop.type.qp}) to #{qp} with return type #{klass.qp}.\"", "}", "else", "raise", "ArgumentError", ".", "new", "(", "\"Cannot reset #{qp}.#{attribute} type #{prop.type.qp} to incompatible #{klass.qp}\"", ")", "end", "end" ]
Sets the given attribute type to klass. If attribute is defined in a superclass, then klass must be a subclass of the superclass attribute type. @param [Symbol] attribute the attribute to modify @param [Class] klass the attribute type @raise [ArgumentError] if the new type is incompatible with the current attribute type
[ "Sets", "the", "given", "attribute", "type", "to", "klass", ".", "If", "attribute", "is", "defined", "in", "a", "superclass", "then", "klass", "must", "be", "a", "subclass", "of", "the", "superclass", "attribute", "type", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/propertied.rb#L409-L425
6,684
jinx/core
lib/jinx/metadata/propertied.rb
Jinx.Propertied.remove_attribute
def remove_attribute(attribute) sa = standard_attribute(attribute) # if the attribute is local, then delete it, otherwise filter out the superclass attribute sp = @local_prop_hash.delete(sa) if sp then # clear the inverse, if any clear_inverse(sp) # remove from the mandatory attributes, if necessary @local_mndty_attrs.delete(sa) # remove from the attribute => metadata hash @local_std_prop_hash.delete_if { |aliaz, pa| pa == sa } else # Filter the superclass hashes. anc_prop_hash = @prop_hash.components[1] @prop_hash.components[1] = anc_prop_hash.filter_on_key { |pa| pa != attribute } anc_alias_hash = @alias_std_prop_map.components[1] @alias_std_prop_map.components[1] = anc_alias_hash.filter_on_key { |pa| pa != attribute } end logger.debug { "Removed the #{qp} #{attribute} property." } end
ruby
def remove_attribute(attribute) sa = standard_attribute(attribute) # if the attribute is local, then delete it, otherwise filter out the superclass attribute sp = @local_prop_hash.delete(sa) if sp then # clear the inverse, if any clear_inverse(sp) # remove from the mandatory attributes, if necessary @local_mndty_attrs.delete(sa) # remove from the attribute => metadata hash @local_std_prop_hash.delete_if { |aliaz, pa| pa == sa } else # Filter the superclass hashes. anc_prop_hash = @prop_hash.components[1] @prop_hash.components[1] = anc_prop_hash.filter_on_key { |pa| pa != attribute } anc_alias_hash = @alias_std_prop_map.components[1] @alias_std_prop_map.components[1] = anc_alias_hash.filter_on_key { |pa| pa != attribute } end logger.debug { "Removed the #{qp} #{attribute} property." } end
[ "def", "remove_attribute", "(", "attribute", ")", "sa", "=", "standard_attribute", "(", "attribute", ")", "# if the attribute is local, then delete it, otherwise filter out the superclass attribute", "sp", "=", "@local_prop_hash", ".", "delete", "(", "sa", ")", "if", "sp", "then", "# clear the inverse, if any", "clear_inverse", "(", "sp", ")", "# remove from the mandatory attributes, if necessary", "@local_mndty_attrs", ".", "delete", "(", "sa", ")", "# remove from the attribute => metadata hash", "@local_std_prop_hash", ".", "delete_if", "{", "|", "aliaz", ",", "pa", "|", "pa", "==", "sa", "}", "else", "# Filter the superclass hashes.", "anc_prop_hash", "=", "@prop_hash", ".", "components", "[", "1", "]", "@prop_hash", ".", "components", "[", "1", "]", "=", "anc_prop_hash", ".", "filter_on_key", "{", "|", "pa", "|", "pa", "!=", "attribute", "}", "anc_alias_hash", "=", "@alias_std_prop_map", ".", "components", "[", "1", "]", "@alias_std_prop_map", ".", "components", "[", "1", "]", "=", "anc_alias_hash", ".", "filter_on_key", "{", "|", "pa", "|", "pa", "!=", "attribute", "}", "end", "logger", ".", "debug", "{", "\"Removed the #{qp} #{attribute} property.\"", "}", "end" ]
Removes the given attribute from this Resource. An attribute declared in a superclass Resource is hidden from this Resource but retained in the declaring Resource.
[ "Removes", "the", "given", "attribute", "from", "this", "Resource", ".", "An", "attribute", "declared", "in", "a", "superclass", "Resource", "is", "hidden", "from", "this", "Resource", "but", "retained", "in", "the", "declaring", "Resource", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/propertied.rb#L472-L491
6,685
jinx/core
lib/jinx/metadata/propertied.rb
Jinx.Propertied.register_property_alias
def register_property_alias(aliaz, attribute) std = standard_attribute(attribute) raise ArgumentError.new("#{self} attribute not found: #{attribute}") if std.nil? @local_std_prop_hash[aliaz.to_sym] = std end
ruby
def register_property_alias(aliaz, attribute) std = standard_attribute(attribute) raise ArgumentError.new("#{self} attribute not found: #{attribute}") if std.nil? @local_std_prop_hash[aliaz.to_sym] = std end
[ "def", "register_property_alias", "(", "aliaz", ",", "attribute", ")", "std", "=", "standard_attribute", "(", "attribute", ")", "raise", "ArgumentError", ".", "new", "(", "\"#{self} attribute not found: #{attribute}\"", ")", "if", "std", ".", "nil?", "@local_std_prop_hash", "[", "aliaz", ".", "to_sym", "]", "=", "std", "end" ]
Registers an alias to an attribute. @param (see #alias_attribute)
[ "Registers", "an", "alias", "to", "an", "attribute", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/propertied.rb#L508-L512
6,686
hinrik/ircsupport
lib/ircsupport/formatting.rb
IRCSupport.Formatting.strip_color!
def strip_color!(string) [@@mirc_color, @@rgb_color, @@ecma48_color].each do |pattern| string.gsub!(pattern, '') end # strip cancellation codes too if there are no formatting codes string.gsub!(@@normal) if !has_color?(string) return string end
ruby
def strip_color!(string) [@@mirc_color, @@rgb_color, @@ecma48_color].each do |pattern| string.gsub!(pattern, '') end # strip cancellation codes too if there are no formatting codes string.gsub!(@@normal) if !has_color?(string) return string end
[ "def", "strip_color!", "(", "string", ")", "[", "@@mirc_color", ",", "@@rgb_color", ",", "@@ecma48_color", "]", ".", "each", "do", "|", "pattern", "|", "string", ".", "gsub!", "(", "pattern", ",", "''", ")", "end", "# strip cancellation codes too if there are no formatting codes", "string", ".", "gsub!", "(", "@@normal", ")", "if", "!", "has_color?", "(", "string", ")", "return", "string", "end" ]
Strip IRC color codes from a string, modifying it in place. @param [String] string The string you want to strip. @return [String] A string stripped of all IRC color codes.
[ "Strip", "IRC", "color", "codes", "from", "a", "string", "modifying", "it", "in", "place", "." ]
d028b7d5ccc604a6af175ee2264c18d25b1f7dff
https://github.com/hinrik/ircsupport/blob/d028b7d5ccc604a6af175ee2264c18d25b1f7dff/lib/ircsupport/formatting.rb#L71-L78
6,687
michaeljklein/nil-passer
lib/gen/code.rb
Gen.Gen::Code.generate_binding
def generate_binding(a_binding=binding) a_binding.local_variables do |local_var| a_binding.local_variable_set local_var, nil end @bound_procs.each_with_index do |bound_proc, index| a_binding.local_variable_set "proc_#{index}", bound_proc end @bound_constants.each_with_index do |bound_const, index| a_binding.local_variable_set "const_#{index}", bound_const end a_binding end
ruby
def generate_binding(a_binding=binding) a_binding.local_variables do |local_var| a_binding.local_variable_set local_var, nil end @bound_procs.each_with_index do |bound_proc, index| a_binding.local_variable_set "proc_#{index}", bound_proc end @bound_constants.each_with_index do |bound_const, index| a_binding.local_variable_set "const_#{index}", bound_const end a_binding end
[ "def", "generate_binding", "(", "a_binding", "=", "binding", ")", "a_binding", ".", "local_variables", "do", "|", "local_var", "|", "a_binding", ".", "local_variable_set", "local_var", ",", "nil", "end", "@bound_procs", ".", "each_with_index", "do", "|", "bound_proc", ",", "index", "|", "a_binding", ".", "local_variable_set", "\"proc_#{index}\"", ",", "bound_proc", "end", "@bound_constants", ".", "each_with_index", "do", "|", "bound_const", ",", "index", "|", "a_binding", ".", "local_variable_set", "\"const_#{index}\"", ",", "bound_const", "end", "a_binding", "end" ]
Generate a binding containing the locally bound procs and constants
[ "Generate", "a", "binding", "containing", "the", "locally", "bound", "procs", "and", "constants" ]
ec7b9beface13054d9fa82374d860e03dcb17635
https://github.com/michaeljklein/nil-passer/blob/ec7b9beface13054d9fa82374d860e03dcb17635/lib/gen/code.rb#L30-L41
6,688
KatanaCode/evvnt
lib/evvnt/persistence.rb
Evvnt.Persistence.save_as_new_record
def save_as_new_record new_attributes = attributes.reject { |k, _v| k.to_s =~ /^(id|uuid)$/ } self.class.create(new_attributes) end
ruby
def save_as_new_record new_attributes = attributes.reject { |k, _v| k.to_s =~ /^(id|uuid)$/ } self.class.create(new_attributes) end
[ "def", "save_as_new_record", "new_attributes", "=", "attributes", ".", "reject", "{", "|", "k", ",", "_v", "|", "k", ".", "to_s", "=~", "/", "/", "}", "self", ".", "class", ".", "create", "(", "new_attributes", ")", "end" ]
Save this record to the EVVNT API as a new record using the +create+ action.
[ "Save", "this", "record", "to", "the", "EVVNT", "API", "as", "a", "new", "record", "using", "the", "+", "create", "+", "action", "." ]
e13f6d84af09a71819356620fb25685a6cd159c9
https://github.com/KatanaCode/evvnt/blob/e13f6d84af09a71819356620fb25685a6cd159c9/lib/evvnt/persistence.rb#L29-L32
6,689
KatanaCode/evvnt
lib/evvnt/persistence.rb
Evvnt.Persistence.save_as_persisted_record
def save_as_persisted_record new_attributes = attributes.reject { |k, _v| k.to_s =~ /^(id|uuid)$/ } self.class.update(id, new_attributes) end
ruby
def save_as_persisted_record new_attributes = attributes.reject { |k, _v| k.to_s =~ /^(id|uuid)$/ } self.class.update(id, new_attributes) end
[ "def", "save_as_persisted_record", "new_attributes", "=", "attributes", ".", "reject", "{", "|", "k", ",", "_v", "|", "k", ".", "to_s", "=~", "/", "/", "}", "self", ".", "class", ".", "update", "(", "id", ",", "new_attributes", ")", "end" ]
Save this record to the EVVNT API as an existing record using the +update+ action.
[ "Save", "this", "record", "to", "the", "EVVNT", "API", "as", "an", "existing", "record", "using", "the", "+", "update", "+", "action", "." ]
e13f6d84af09a71819356620fb25685a6cd159c9
https://github.com/KatanaCode/evvnt/blob/e13f6d84af09a71819356620fb25685a6cd159c9/lib/evvnt/persistence.rb#L36-L39
6,690
kevinjalbert/godville_kit
lib/godville_kit/api_requester.rb
GodvilleKit.APIRequester.request_raw_hero_data
def request_raw_hero_data return unless authenticated? response = RestClient.get( "https://godvillegame.com/fbh/feed?a=#{@hero_guid}", cookies: @cookies, content_type: :json, accept: :json ) JSON.parse(response) end
ruby
def request_raw_hero_data return unless authenticated? response = RestClient.get( "https://godvillegame.com/fbh/feed?a=#{@hero_guid}", cookies: @cookies, content_type: :json, accept: :json ) JSON.parse(response) end
[ "def", "request_raw_hero_data", "return", "unless", "authenticated?", "response", "=", "RestClient", ".", "get", "(", "\"https://godvillegame.com/fbh/feed?a=#{@hero_guid}\"", ",", "cookies", ":", "@cookies", ",", "content_type", ":", ":json", ",", "accept", ":", ":json", ")", "JSON", ".", "parse", "(", "response", ")", "end" ]
Request the raw hero data from godville
[ "Request", "the", "raw", "hero", "data", "from", "godville" ]
975eb16682f10a278d3c3fff4c7e9c435085b8d1
https://github.com/kevinjalbert/godville_kit/blob/975eb16682f10a278d3c3fff4c7e9c435085b8d1/lib/godville_kit/api_requester.rb#L56-L64
6,691
riddopic/garcun
lib/garcon/task/obligation.rb
Garcon.Obligation.compare_and_set_state
def compare_and_set_state(next_state, expected_current) # :nodoc: mutex.lock if @state == expected_current @state = next_state true else false end ensure mutex.unlock end
ruby
def compare_and_set_state(next_state, expected_current) # :nodoc: mutex.lock if @state == expected_current @state = next_state true else false end ensure mutex.unlock end
[ "def", "compare_and_set_state", "(", "next_state", ",", "expected_current", ")", "# :nodoc:", "mutex", ".", "lock", "if", "@state", "==", "expected_current", "@state", "=", "next_state", "true", "else", "false", "end", "ensure", "mutex", ".", "unlock", "end" ]
Atomic compare and set operation. State is set to `next_state` only if `current state == expected_current`. @param [Symbol] next_state @param [Symbol] expected_current @return [Boolean] TRrue is state is changed, false otherwise @!visibility private
[ "Atomic", "compare", "and", "set", "operation", ".", "State", "is", "set", "to", "next_state", "only", "if", "current", "state", "==", "expected_current", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/obligation.rb#L225-L235
6,692
riddopic/garcun
lib/garcon/task/obligation.rb
Garcon.Obligation.if_state
def if_state(*expected_states) mutex.lock raise ArgumentError, 'no block given' unless block_given? if expected_states.include? @state yield else false end ensure mutex.unlock end
ruby
def if_state(*expected_states) mutex.lock raise ArgumentError, 'no block given' unless block_given? if expected_states.include? @state yield else false end ensure mutex.unlock end
[ "def", "if_state", "(", "*", "expected_states", ")", "mutex", ".", "lock", "raise", "ArgumentError", ",", "'no block given'", "unless", "block_given?", "if", "expected_states", ".", "include?", "@state", "yield", "else", "false", "end", "ensure", "mutex", ".", "unlock", "end" ]
executes the block within mutex if current state is included in expected_states @return block value if executed, false otherwise @!visibility private
[ "executes", "the", "block", "within", "mutex", "if", "current", "state", "is", "included", "in", "expected_states" ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/obligation.rb#L243-L254
6,693
rideliner/poly_delegate
lib/poly_delegate/delegator.rb
PolyDelegate.Delegator.method_missing
def method_missing(name, *args, &block) super unless respond_to_missing?(name) # Send self as the delegator @__delegated_object__.__send__(name, self, *args, &block) end
ruby
def method_missing(name, *args, &block) super unless respond_to_missing?(name) # Send self as the delegator @__delegated_object__.__send__(name, self, *args, &block) end
[ "def", "method_missing", "(", "name", ",", "*", "args", ",", "&", "block", ")", "super", "unless", "respond_to_missing?", "(", "name", ")", "# Send self as the delegator", "@__delegated_object__", ".", "__send__", "(", "name", ",", "self", ",", "args", ",", "block", ")", "end" ]
Create a wrapper around a delegated object @api public @param obj [Delegated] delegated object Relay methods to `@__delegated_object__` if they exist @api private @raise [NoMethodError] if the delegated object does not respond to the method being called @param name [Symbol] method name @param args [Array<Object>] arguments to method @yield to method call @return result of method call
[ "Create", "a", "wrapper", "around", "a", "delegated", "object" ]
fc704dd8f0f68b3b7c67cc67249ea2161fdb2761
https://github.com/rideliner/poly_delegate/blob/fc704dd8f0f68b3b7c67cc67249ea2161fdb2761/lib/poly_delegate/delegator.rb#L33-L37
6,694
avdgaag/observatory
lib/observatory/stack.rb
Observatory.Stack.delete
def delete(observer) old_size = @stack.size @stack.delete_if do |o| o[:observer] == observer end old_size == @stack.size ? nil : observer end
ruby
def delete(observer) old_size = @stack.size @stack.delete_if do |o| o[:observer] == observer end old_size == @stack.size ? nil : observer end
[ "def", "delete", "(", "observer", ")", "old_size", "=", "@stack", ".", "size", "@stack", ".", "delete_if", "do", "|", "o", "|", "o", "[", ":observer", "]", "==", "observer", "end", "old_size", "==", "@stack", ".", "size", "?", "nil", ":", "observer", "end" ]
Remove an observer from the stack. @param [#call] observer the callable object that should be removed. @return [#call, nil] the original object or `nil`
[ "Remove", "an", "observer", "from", "the", "stack", "." ]
af8fdb445c42f425067ac97c39fcdbef5ebac73e
https://github.com/avdgaag/observatory/blob/af8fdb445c42f425067ac97c39fcdbef5ebac73e/lib/observatory/stack.rb#L54-L60
6,695
avdgaag/observatory
lib/observatory/stack.rb
Observatory.Stack.push
def push(observer, priority = nil) raise ArgumentError, 'Observer is not callable' unless observer.respond_to?(:call) raise ArgumentError, 'Priority must be Fixnum' unless priority.nil? || priority.is_a?(Fixnum) @stack.push({ :observer => observer, :priority => (priority || default_priority) }) sort_by_priority observer end
ruby
def push(observer, priority = nil) raise ArgumentError, 'Observer is not callable' unless observer.respond_to?(:call) raise ArgumentError, 'Priority must be Fixnum' unless priority.nil? || priority.is_a?(Fixnum) @stack.push({ :observer => observer, :priority => (priority || default_priority) }) sort_by_priority observer end
[ "def", "push", "(", "observer", ",", "priority", "=", "nil", ")", "raise", "ArgumentError", ",", "'Observer is not callable'", "unless", "observer", ".", "respond_to?", "(", ":call", ")", "raise", "ArgumentError", ",", "'Priority must be Fixnum'", "unless", "priority", ".", "nil?", "||", "priority", ".", "is_a?", "(", "Fixnum", ")", "@stack", ".", "push", "(", "{", ":observer", "=>", "observer", ",", ":priority", "=>", "(", "priority", "||", "default_priority", ")", "}", ")", "sort_by_priority", "observer", "end" ]
Add an element to the stack with an optional priority. @param [#call] observer is the callable object that acts as observer. @param [Fixnum] priority is a number indicating return order. A higher number means lower priority. @return [#call] the original `observer` passed in. @raise `ArgumentError` when not using a `Fixnum` for `priority` @raise `ArgumentError` when not using callable object for `observer`
[ "Add", "an", "element", "to", "the", "stack", "with", "an", "optional", "priority", "." ]
af8fdb445c42f425067ac97c39fcdbef5ebac73e
https://github.com/avdgaag/observatory/blob/af8fdb445c42f425067ac97c39fcdbef5ebac73e/lib/observatory/stack.rb#L70-L77
6,696
barkerest/incline
lib/incline/validators/safe_name_validator.rb
Incline.SafeNameValidator.validate_each
def validate_each(record, attribute, value) unless value.blank? unless value =~ VALID_MASK if value =~ /\A[^a-z]/i record.errors[attribute] << (options[:message] || 'must start with a letter') elsif value =~ /_\z/ record.errors[attribute] << (options[:message] || 'must not end with an underscore') else record.errors[attribute] << (options[:message] || 'must contain only letters, numbers, and underscore') end end end end
ruby
def validate_each(record, attribute, value) unless value.blank? unless value =~ VALID_MASK if value =~ /\A[^a-z]/i record.errors[attribute] << (options[:message] || 'must start with a letter') elsif value =~ /_\z/ record.errors[attribute] << (options[:message] || 'must not end with an underscore') else record.errors[attribute] << (options[:message] || 'must contain only letters, numbers, and underscore') end end end end
[ "def", "validate_each", "(", "record", ",", "attribute", ",", "value", ")", "unless", "value", ".", "blank?", "unless", "value", "=~", "VALID_MASK", "if", "value", "=~", "/", "\\A", "/i", "record", ".", "errors", "[", "attribute", "]", "<<", "(", "options", "[", ":message", "]", "||", "'must start with a letter'", ")", "elsif", "value", "=~", "/", "\\z", "/", "record", ".", "errors", "[", "attribute", "]", "<<", "(", "options", "[", ":message", "]", "||", "'must not end with an underscore'", ")", "else", "record", ".", "errors", "[", "attribute", "]", "<<", "(", "options", "[", ":message", "]", "||", "'must contain only letters, numbers, and underscore'", ")", "end", "end", "end", "end" ]
Validates attributes to determine if the values match the requirements of a safe name.
[ "Validates", "attributes", "to", "determine", "if", "the", "values", "match", "the", "requirements", "of", "a", "safe", "name", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/validators/safe_name_validator.rb#L16-L28
6,697
kenjij/kajiki
lib/kajiki/runner.rb
Kajiki.Runner.validate_command
def validate_command(cmd = ARGV) fail 'Specify one action.' unless cmd.count == 1 cmd = cmd.shift fail 'Invalid action.' unless SUB_COMMANDS.include?(cmd) cmd end
ruby
def validate_command(cmd = ARGV) fail 'Specify one action.' unless cmd.count == 1 cmd = cmd.shift fail 'Invalid action.' unless SUB_COMMANDS.include?(cmd) cmd end
[ "def", "validate_command", "(", "cmd", "=", "ARGV", ")", "fail", "'Specify one action.'", "unless", "cmd", ".", "count", "==", "1", "cmd", "=", "cmd", ".", "shift", "fail", "'Invalid action.'", "unless", "SUB_COMMANDS", ".", "include?", "(", "cmd", ")", "cmd", "end" ]
Validate the given command. @param cmd [Array] only one command should be given. @return [String] extracts out of Array
[ "Validate", "the", "given", "command", "." ]
9b036f2741d515e9bfd158571a813987516d89ed
https://github.com/kenjij/kajiki/blob/9b036f2741d515e9bfd158571a813987516d89ed/lib/kajiki/runner.rb#L33-L38
6,698
kenjij/kajiki
lib/kajiki/runner.rb
Kajiki.Runner.validate_options
def validate_options if @opts[:daemonize] fail 'Must specify PID file.' unless @opts[:pid_given] end @opts[:pid] = File.expand_path(@opts[:pid]) if @opts[:pid_given] @opts[:log] = File.expand_path(@opts[:log]) if @opts[:log_given] @opts[:error] = File.expand_path(@opts[:error]) if @opts[:error_given] @opts[:config] = File.expand_path(@opts[:config]) if @opts[:config_given] end
ruby
def validate_options if @opts[:daemonize] fail 'Must specify PID file.' unless @opts[:pid_given] end @opts[:pid] = File.expand_path(@opts[:pid]) if @opts[:pid_given] @opts[:log] = File.expand_path(@opts[:log]) if @opts[:log_given] @opts[:error] = File.expand_path(@opts[:error]) if @opts[:error_given] @opts[:config] = File.expand_path(@opts[:config]) if @opts[:config_given] end
[ "def", "validate_options", "if", "@opts", "[", ":daemonize", "]", "fail", "'Must specify PID file.'", "unless", "@opts", "[", ":pid_given", "]", "end", "@opts", "[", ":pid", "]", "=", "File", ".", "expand_path", "(", "@opts", "[", ":pid", "]", ")", "if", "@opts", "[", ":pid_given", "]", "@opts", "[", ":log", "]", "=", "File", ".", "expand_path", "(", "@opts", "[", ":log", "]", ")", "if", "@opts", "[", ":log_given", "]", "@opts", "[", ":error", "]", "=", "File", ".", "expand_path", "(", "@opts", "[", ":error", "]", ")", "if", "@opts", "[", ":error_given", "]", "@opts", "[", ":config", "]", "=", "File", ".", "expand_path", "(", "@opts", "[", ":config", "]", ")", "if", "@opts", "[", ":config_given", "]", "end" ]
Validate the options; otherwise fails.
[ "Validate", "the", "options", ";", "otherwise", "fails", "." ]
9b036f2741d515e9bfd158571a813987516d89ed
https://github.com/kenjij/kajiki/blob/9b036f2741d515e9bfd158571a813987516d89ed/lib/kajiki/runner.rb#L41-L49
6,699
kenjij/kajiki
lib/kajiki/runner.rb
Kajiki.Runner.start
def start(&block) fail 'No start block given.' if block.nil? check_existing_pid puts "Starting process..." Process.daemon if @opts[:daemonize] change_privileges if @opts[:auto_default_actions] redirect_outputs if @opts[:auto_default_actions] write_pid trap_default_signals if @opts[:auto_default_actions] block.call('start') end
ruby
def start(&block) fail 'No start block given.' if block.nil? check_existing_pid puts "Starting process..." Process.daemon if @opts[:daemonize] change_privileges if @opts[:auto_default_actions] redirect_outputs if @opts[:auto_default_actions] write_pid trap_default_signals if @opts[:auto_default_actions] block.call('start') end
[ "def", "start", "(", "&", "block", ")", "fail", "'No start block given.'", "if", "block", ".", "nil?", "check_existing_pid", "puts", "\"Starting process...\"", "Process", ".", "daemon", "if", "@opts", "[", ":daemonize", "]", "change_privileges", "if", "@opts", "[", ":auto_default_actions", "]", "redirect_outputs", "if", "@opts", "[", ":auto_default_actions", "]", "write_pid", "trap_default_signals", "if", "@opts", "[", ":auto_default_actions", "]", "block", ".", "call", "(", "'start'", ")", "end" ]
Start the process with the given block. @param [Block]
[ "Start", "the", "process", "with", "the", "given", "block", "." ]
9b036f2741d515e9bfd158571a813987516d89ed
https://github.com/kenjij/kajiki/blob/9b036f2741d515e9bfd158571a813987516d89ed/lib/kajiki/runner.rb#L53-L63