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
9,100
babausse/kharon
lib/kharon/processor.rb
Kharon.Processor.contains?
def contains?(key, values, required_values) raise_error(type: "contains.values", required: required_values, key: key) if (values & required_values) != required_values end
ruby
def contains?(key, values, required_values) raise_error(type: "contains.values", required: required_values, key: key) if (values & required_values) != required_values end
[ "def", "contains?", "(", "key", ",", "values", ",", "required_values", ")", "raise_error", "(", "type", ":", "\"contains.values\"", ",", "required", ":", "required_values", ",", "key", ":", "key", ")", "if", "(", "values", "&", "required_values", ")", "!=", "required_values", "end" ]
Checks if the value associated with the given key has the given required values. @param [Object] key the key associated with the value to check. @param [Array] required_values the values that the initial Enumerable typed value should contain. @raise [ArgumentError] if the initial value has not each and every one of the given values.
[ "Checks", "if", "the", "value", "associated", "with", "the", "given", "key", "has", "the", "given", "required", "values", "." ]
bfd3d90cbc229db70f2ed1762f5f1743259154cd
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/processor.rb#L150-L152
9,101
babausse/kharon
lib/kharon/processor.rb
Kharon.Processor.has_keys?
def has_keys?(key, required_keys) raise_error(type: "contains.keys", required: required_keys, key: key) if (validator.datas[key].keys & required_keys) != required_keys end
ruby
def has_keys?(key, required_keys) raise_error(type: "contains.keys", required: required_keys, key: key) if (validator.datas[key].keys & required_keys) != required_keys end
[ "def", "has_keys?", "(", "key", ",", "required_keys", ")", "raise_error", "(", "type", ":", "\"contains.keys\"", ",", "required", ":", "required_keys", ",", "key", ":", "key", ")", "if", "(", "validator", ".", "datas", "[", "key", "]", ".", "keys", "&", "required_keys", ")", "!=", "required_keys", "end" ]
Checks if the value associated with the given key has the given required keys. @param [Object] key the key associated with the value to check. @param [Array] required_keys the keys that the initial Hash typed value should contain. @raise [ArgumentError] if the initial value has not each and every one of the given keys.
[ "Checks", "if", "the", "value", "associated", "with", "the", "given", "key", "has", "the", "given", "required", "keys", "." ]
bfd3d90cbc229db70f2ed1762f5f1743259154cd
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/processor.rb#L158-L160
9,102
ideonetwork/lato-blog
lib/lato_blog/interfaces/tags.rb
LatoBlog.Interface::Tags.blog__clean_tag_parents
def blog__clean_tag_parents tag_parents = LatoBlog::TagParent.all tag_parents.map { |tp| tp.destroy if tp.tags.empty? } end
ruby
def blog__clean_tag_parents tag_parents = LatoBlog::TagParent.all tag_parents.map { |tp| tp.destroy if tp.tags.empty? } end
[ "def", "blog__clean_tag_parents", "tag_parents", "=", "LatoBlog", "::", "TagParent", ".", "all", "tag_parents", ".", "map", "{", "|", "tp", "|", "tp", ".", "destroy", "if", "tp", ".", "tags", ".", "empty?", "}", "end" ]
This function cleans all old tag parents without any child.
[ "This", "function", "cleans", "all", "old", "tag", "parents", "without", "any", "child", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/tags.rb#L7-L10
9,103
ideonetwork/lato-blog
lib/lato_blog/interfaces/tags.rb
LatoBlog.Interface::Tags.blog__get_tags
def blog__get_tags( order: nil, language: nil, search: nil, page: nil, per_page: nil ) tags = LatoBlog::Tag.all # apply filters order = order && order == 'ASC' ? 'ASC' : 'DESC' tags = _tags_filter_by_order(tags, order) tags = _tags_filter_by_language(tags, language) tags = _tags_filter_search(tags, search) # take tags uniqueness tags = tags.uniq(&:id) # save total tags total = tags.length # manage pagination page = page&.to_i || 1 per_page = per_page&.to_i || 20 tags = core__paginate_array(tags, per_page, page) # return result { tags: tags && !tags.empty? ? tags.map(&:serialize) : [], page: page, per_page: per_page, order: order, total: total } end
ruby
def blog__get_tags( order: nil, language: nil, search: nil, page: nil, per_page: nil ) tags = LatoBlog::Tag.all # apply filters order = order && order == 'ASC' ? 'ASC' : 'DESC' tags = _tags_filter_by_order(tags, order) tags = _tags_filter_by_language(tags, language) tags = _tags_filter_search(tags, search) # take tags uniqueness tags = tags.uniq(&:id) # save total tags total = tags.length # manage pagination page = page&.to_i || 1 per_page = per_page&.to_i || 20 tags = core__paginate_array(tags, per_page, page) # return result { tags: tags && !tags.empty? ? tags.map(&:serialize) : [], page: page, per_page: per_page, order: order, total: total } end
[ "def", "blog__get_tags", "(", "order", ":", "nil", ",", "language", ":", "nil", ",", "search", ":", "nil", ",", "page", ":", "nil", ",", "per_page", ":", "nil", ")", "tags", "=", "LatoBlog", "::", "Tag", ".", "all", "# apply filters", "order", "=", "order", "&&", "order", "==", "'ASC'", "?", "'ASC'", ":", "'DESC'", "tags", "=", "_tags_filter_by_order", "(", "tags", ",", "order", ")", "tags", "=", "_tags_filter_by_language", "(", "tags", ",", "language", ")", "tags", "=", "_tags_filter_search", "(", "tags", ",", "search", ")", "# take tags uniqueness", "tags", "=", "tags", ".", "uniq", "(", ":id", ")", "# save total tags", "total", "=", "tags", ".", "length", "# manage pagination", "page", "=", "page", "&.", "to_i", "||", "1", "per_page", "=", "per_page", "&.", "to_i", "||", "20", "tags", "=", "core__paginate_array", "(", "tags", ",", "per_page", ",", "page", ")", "# return result", "{", "tags", ":", "tags", "&&", "!", "tags", ".", "empty?", "?", "tags", ".", "map", "(", ":serialize", ")", ":", "[", "]", ",", "page", ":", "page", ",", "per_page", ":", "per_page", ",", "order", ":", "order", ",", "total", ":", "total", "}", "end" ]
This function returns an object with the list of tags with some filters.
[ "This", "function", "returns", "an", "object", "with", "the", "list", "of", "tags", "with", "some", "filters", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/tags.rb#L13-L47
9,104
ideonetwork/lato-blog
lib/lato_blog/interfaces/tags.rb
LatoBlog.Interface::Tags.blog__get_category
def blog__get_category(id: nil, permalink: nil) return {} unless id || permalink if id category = LatoBlog::Category.find_by(id: id.to_i) else category = LatoBlog::Category.find_by(meta_permalink: permalink) end category.serialize end
ruby
def blog__get_category(id: nil, permalink: nil) return {} unless id || permalink if id category = LatoBlog::Category.find_by(id: id.to_i) else category = LatoBlog::Category.find_by(meta_permalink: permalink) end category.serialize end
[ "def", "blog__get_category", "(", "id", ":", "nil", ",", "permalink", ":", "nil", ")", "return", "{", "}", "unless", "id", "||", "permalink", "if", "id", "category", "=", "LatoBlog", "::", "Category", ".", "find_by", "(", "id", ":", "id", ".", "to_i", ")", "else", "category", "=", "LatoBlog", "::", "Category", ".", "find_by", "(", "meta_permalink", ":", "permalink", ")", "end", "category", ".", "serialize", "end" ]
This function returns a single category searched by id or permalink.
[ "This", "function", "returns", "a", "single", "category", "searched", "by", "id", "or", "permalink", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/lib/lato_blog/interfaces/tags.rb#L50-L60
9,105
npepinpe/redstruct
lib/redstruct/set.rb
Redstruct.Set.random
def random(count: 1) list = self.connection.srandmember(@key, count) return nil if list.nil? return count == 1 ? list[0] : ::Set.new(list) end
ruby
def random(count: 1) list = self.connection.srandmember(@key, count) return nil if list.nil? return count == 1 ? list[0] : ::Set.new(list) end
[ "def", "random", "(", "count", ":", "1", ")", "list", "=", "self", ".", "connection", ".", "srandmember", "(", "@key", ",", "count", ")", "return", "nil", "if", "list", ".", "nil?", "return", "count", "==", "1", "?", "list", "[", "0", "]", ":", "::", "Set", ".", "new", "(", "list", ")", "end" ]
Returns random items from the set @param [Integer] count the number of items to return @return [String, Set] if count is one, then return the item; otherwise returns a set
[ "Returns", "random", "items", "from", "the", "set" ]
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/set.rb#L22-L27
9,106
npepinpe/redstruct
lib/redstruct/set.rb
Redstruct.Set.difference
def difference(other, dest: nil) destination = coerce_destination(dest) results = if destination.nil? ::Set.new(self.connection.sdiff(@key, other.key)) else self.connection.sdiffstore(destination.key, @key, other.key) end return results end
ruby
def difference(other, dest: nil) destination = coerce_destination(dest) results = if destination.nil? ::Set.new(self.connection.sdiff(@key, other.key)) else self.connection.sdiffstore(destination.key, @key, other.key) end return results end
[ "def", "difference", "(", "other", ",", "dest", ":", "nil", ")", "destination", "=", "coerce_destination", "(", "dest", ")", "results", "=", "if", "destination", ".", "nil?", "::", "Set", ".", "new", "(", "self", ".", "connection", ".", "sdiff", "(", "@key", ",", "other", ".", "key", ")", ")", "else", "self", ".", "connection", ".", "sdiffstore", "(", "destination", ".", "key", ",", "@key", ",", "other", ".", "key", ")", "end", "return", "results", "end" ]
Computes the difference of the two sets and stores the result in `dest`. If no destination provided, computes the results in memory. @param [Redstruct::Set] other set the set to subtract @param [Redstruct::Set, String] dest if nil, results are computed in memory. if a string, a new Redstruct::Set is constructed with the string as the key, and results are stored there. if already a Redstruct::Set, results are stored there. @return [::Set, Integer] if dest was provided, returns the number of elements in the destination; otherwise a standard Ruby set containing the difference
[ "Computes", "the", "difference", "of", "the", "two", "sets", "and", "stores", "the", "result", "in", "dest", ".", "If", "no", "destination", "provided", "computes", "the", "results", "in", "memory", "." ]
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/set.rb#L77-L86
9,107
npepinpe/redstruct
lib/redstruct/set.rb
Redstruct.Set.intersection
def intersection(other, dest: nil) destination = coerce_destination(dest) results = if destination.nil? ::Set.new(self.connection.sinter(@key, other.key)) else self.connection.sinterstore(destination.key, @key, other.key) end return results end
ruby
def intersection(other, dest: nil) destination = coerce_destination(dest) results = if destination.nil? ::Set.new(self.connection.sinter(@key, other.key)) else self.connection.sinterstore(destination.key, @key, other.key) end return results end
[ "def", "intersection", "(", "other", ",", "dest", ":", "nil", ")", "destination", "=", "coerce_destination", "(", "dest", ")", "results", "=", "if", "destination", ".", "nil?", "::", "Set", ".", "new", "(", "self", ".", "connection", ".", "sinter", "(", "@key", ",", "other", ".", "key", ")", ")", "else", "self", ".", "connection", ".", "sinterstore", "(", "destination", ".", "key", ",", "@key", ",", "other", ".", "key", ")", "end", "return", "results", "end" ]
Computes the interesection of the two sets and stores the result in `dest`. If no destination provided, computes the results in memory. @param [Redstruct::Set] other set the set to intersect @param [Redstruct::Set, String] dest if nil, results are computed in memory. if a string, a new Redstruct::Set is constructed with the string as the key, and results are stored there. if already a Redstruct::Set, results are stored there. @return [::Set, Integer] if dest was provided, returns the number of elements in the destination; otherwise a standard Ruby set containing the intersection
[ "Computes", "the", "interesection", "of", "the", "two", "sets", "and", "stores", "the", "result", "in", "dest", ".", "If", "no", "destination", "provided", "computes", "the", "results", "in", "memory", "." ]
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/set.rb#L95-L104
9,108
npepinpe/redstruct
lib/redstruct/set.rb
Redstruct.Set.union
def union(other, dest: nil) destination = coerce_destination(dest) results = if destination.nil? ::Set.new(self.connection.sunion(@key, other.key)) else self.connection.sunionstore(destination.key, @key, other.key) end return results end
ruby
def union(other, dest: nil) destination = coerce_destination(dest) results = if destination.nil? ::Set.new(self.connection.sunion(@key, other.key)) else self.connection.sunionstore(destination.key, @key, other.key) end return results end
[ "def", "union", "(", "other", ",", "dest", ":", "nil", ")", "destination", "=", "coerce_destination", "(", "dest", ")", "results", "=", "if", "destination", ".", "nil?", "::", "Set", ".", "new", "(", "self", ".", "connection", ".", "sunion", "(", "@key", ",", "other", ".", "key", ")", ")", "else", "self", ".", "connection", ".", "sunionstore", "(", "destination", ".", "key", ",", "@key", ",", "other", ".", "key", ")", "end", "return", "results", "end" ]
Computes the union of the two sets and stores the result in `dest`. If no destination provided, computes the results in memory. @param [Redstruct::Set] other set the set to add @param [Redstruct::Set, String] dest if nil, results are computed in memory. if a string, a new Redstruct::Set is constructed with the string as the key, and results are stored there. if already a Redstruct::Set, results are stored there. @return [::Set, Integer] if dest was provided, returns the number of elements in the destination; otherwise a standard Ruby set containing the union
[ "Computes", "the", "union", "of", "the", "two", "sets", "and", "stores", "the", "result", "in", "dest", ".", "If", "no", "destination", "provided", "computes", "the", "results", "in", "memory", "." ]
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/set.rb#L113-L122
9,109
cqql/exec_env
lib/exec_env/env.rb
ExecEnv.Env.exec
def exec (*args, &block) if @scope @scope.instance_variables.each do |name| instance_variable_set(name, @scope.instance_variable_get(name)) end end @ivars.each do |name, value| instance_variable_set(name, value) end instance_exec(*args, &block) end
ruby
def exec (*args, &block) if @scope @scope.instance_variables.each do |name| instance_variable_set(name, @scope.instance_variable_get(name)) end end @ivars.each do |name, value| instance_variable_set(name, value) end instance_exec(*args, &block) end
[ "def", "exec", "(", "*", "args", ",", "&", "block", ")", "if", "@scope", "@scope", ".", "instance_variables", ".", "each", "do", "|", "name", "|", "instance_variable_set", "(", "name", ",", "@scope", ".", "instance_variable_get", "(", "name", ")", ")", "end", "end", "@ivars", ".", "each", "do", "|", "name", ",", "value", "|", "instance_variable_set", "(", "name", ",", "value", ")", "end", "instance_exec", "(", "args", ",", "block", ")", "end" ]
Execute a block in the manipulated environment. Additional arguments will be passed to the block. Returns the return value of the block
[ "Execute", "a", "block", "in", "the", "manipulated", "environment", "." ]
288e109c3be390349ddb73dee74897f49479824f
https://github.com/cqql/exec_env/blob/288e109c3be390349ddb73dee74897f49479824f/lib/exec_env/env.rb#L57-L69
9,110
ZirconCode/Scrapah
lib/scrapah/scraper.rb
Scrapah.Scraper.process_appropriate
def process_appropriate(doc,cmd) return process_regex(doc,cmd) if(cmd.is_a? Regexp) return process_proc(doc,cmd) if(cmd.is_a? Proc) if cmd.is_a?(String) return process_xpath(doc,cmd) if cmd.start_with?("x|") return process_css(doc,cmd) if cmd.start_with?("c|") end nil end
ruby
def process_appropriate(doc,cmd) return process_regex(doc,cmd) if(cmd.is_a? Regexp) return process_proc(doc,cmd) if(cmd.is_a? Proc) if cmd.is_a?(String) return process_xpath(doc,cmd) if cmd.start_with?("x|") return process_css(doc,cmd) if cmd.start_with?("c|") end nil end
[ "def", "process_appropriate", "(", "doc", ",", "cmd", ")", "return", "process_regex", "(", "doc", ",", "cmd", ")", "if", "(", "cmd", ".", "is_a?", "Regexp", ")", "return", "process_proc", "(", "doc", ",", "cmd", ")", "if", "(", "cmd", ".", "is_a?", "Proc", ")", "if", "cmd", ".", "is_a?", "(", "String", ")", "return", "process_xpath", "(", "doc", ",", "cmd", ")", "if", "cmd", ".", "start_with?", "(", "\"x|\"", ")", "return", "process_css", "(", "doc", ",", "cmd", ")", "if", "cmd", ".", "start_with?", "(", "\"c|\"", ")", "end", "nil", "end" ]
accepts nokogiri doc's only atm
[ "accepts", "nokogiri", "doc", "s", "only", "atm" ]
5adcc92da1f7d7634f91c717f6f28e0daf0129b7
https://github.com/ZirconCode/Scrapah/blob/5adcc92da1f7d7634f91c717f6f28e0daf0129b7/lib/scrapah/scraper.rb#L103-L115
9,111
bradfeehan/derelict
lib/derelict/connection.rb
Derelict.Connection.validate!
def validate! logger.debug "Starting validation for #{description}" raise NotFound.new path unless File.exists? path logger.info "Successfully validated #{description}" self end
ruby
def validate! logger.debug "Starting validation for #{description}" raise NotFound.new path unless File.exists? path logger.info "Successfully validated #{description}" self end
[ "def", "validate!", "logger", ".", "debug", "\"Starting validation for #{description}\"", "raise", "NotFound", ".", "new", "path", "unless", "File", ".", "exists?", "path", "logger", ".", "info", "\"Successfully validated #{description}\"", "self", "end" ]
Initializes a Connection for use in a particular directory * instance: The Derelict::Instance to use to control Vagrant * path: The project path, which contains the Vagrantfile Validates the data used for this connection Raises exceptions on failure: * +Derelict::Connection::NotFound+ if the path is not found
[ "Initializes", "a", "Connection", "for", "use", "in", "a", "particular", "directory" ]
c9d70f04562280a34083dd060b0e4099e6f32d8d
https://github.com/bradfeehan/derelict/blob/c9d70f04562280a34083dd060b0e4099e6f32d8d/lib/derelict/connection.rb#L28-L33
9,112
adriancuadros/seedsv
lib/seedsv/csv_seed.rb
Seedsv.CsvSeed.seed_model
def seed_model(model_class, options={}) if model_class.count == 0 or options[:force] table_name = options[:file_name] || model_class.table_name puts "Seeding #{model_class.to_s.pluralize}..." csv_file = @@csv_class.open(Rails.root + "db/csv/#{table_name}.csv", :headers => true) seed_from_csv(model_class, csv_file) end end
ruby
def seed_model(model_class, options={}) if model_class.count == 0 or options[:force] table_name = options[:file_name] || model_class.table_name puts "Seeding #{model_class.to_s.pluralize}..." csv_file = @@csv_class.open(Rails.root + "db/csv/#{table_name}.csv", :headers => true) seed_from_csv(model_class, csv_file) end end
[ "def", "seed_model", "(", "model_class", ",", "options", "=", "{", "}", ")", "if", "model_class", ".", "count", "==", "0", "or", "options", "[", ":force", "]", "table_name", "=", "options", "[", ":file_name", "]", "||", "model_class", ".", "table_name", "puts", "\"Seeding #{model_class.to_s.pluralize}...\"", "csv_file", "=", "@@csv_class", ".", "open", "(", "Rails", ".", "root", "+", "\"db/csv/#{table_name}.csv\"", ",", ":headers", "=>", "true", ")", "seed_from_csv", "(", "model_class", ",", "csv_file", ")", "end", "end" ]
Receives the reference to the model class to seed. Seeds only when there are no records in the table or if the +force+ option is set to true. Also optionally it can receive the +file_name+ to use.
[ "Receives", "the", "reference", "to", "the", "model", "class", "to", "seed", ".", "Seeds", "only", "when", "there", "are", "no", "records", "in", "the", "table", "or", "if", "the", "+", "force", "+", "option", "is", "set", "to", "true", ".", "Also", "optionally", "it", "can", "receive", "the", "+", "file_name", "+", "to", "use", "." ]
db01147a5ece722389120230247c5f0ee111ea9e
https://github.com/adriancuadros/seedsv/blob/db01147a5ece722389120230247c5f0ee111ea9e/lib/seedsv/csv_seed.rb#L20-L27
9,113
adriancuadros/seedsv
lib/seedsv/csv_seed.rb
Seedsv.CsvSeed.seed_from_csv
def seed_from_csv(migration_class, csv_file) migration_class.transaction do csv_file.each do |line_values| record = migration_class.new line_values.to_hash.keys.map{|attribute| record.send("#{attribute.strip}=",line_values[attribute].strip) rescue nil} record.save(:validate => false) end end end
ruby
def seed_from_csv(migration_class, csv_file) migration_class.transaction do csv_file.each do |line_values| record = migration_class.new line_values.to_hash.keys.map{|attribute| record.send("#{attribute.strip}=",line_values[attribute].strip) rescue nil} record.save(:validate => false) end end end
[ "def", "seed_from_csv", "(", "migration_class", ",", "csv_file", ")", "migration_class", ".", "transaction", "do", "csv_file", ".", "each", "do", "|", "line_values", "|", "record", "=", "migration_class", ".", "new", "line_values", ".", "to_hash", ".", "keys", ".", "map", "{", "|", "attribute", "|", "record", ".", "send", "(", "\"#{attribute.strip}=\"", ",", "line_values", "[", "attribute", "]", ".", "strip", ")", "rescue", "nil", "}", "record", ".", "save", "(", ":validate", "=>", "false", ")", "end", "end", "end" ]
Receives the class reference and csv file and creates all thre records inside one transaction
[ "Receives", "the", "class", "reference", "and", "csv", "file", "and", "creates", "all", "thre", "records", "inside", "one", "transaction" ]
db01147a5ece722389120230247c5f0ee111ea9e
https://github.com/adriancuadros/seedsv/blob/db01147a5ece722389120230247c5f0ee111ea9e/lib/seedsv/csv_seed.rb#L33-L41
9,114
jeremyz/edoors-ruby
lib/edoors/particle.rb
Edoors.Particle.add_dsts
def add_dsts *dsts dsts.each do |dst| if dst.empty? or dst==Edoors::ACT_SEP or dst[0]==Edoors::PATH_SEP \ or dst=~/\/\?/ or dst=~/\/{2,}/ or dst=~/\s+/ raise Edoors::Exception.new "destination #{dst} is not acceptable" end @dsts << dst end end
ruby
def add_dsts *dsts dsts.each do |dst| if dst.empty? or dst==Edoors::ACT_SEP or dst[0]==Edoors::PATH_SEP \ or dst=~/\/\?/ or dst=~/\/{2,}/ or dst=~/\s+/ raise Edoors::Exception.new "destination #{dst} is not acceptable" end @dsts << dst end end
[ "def", "add_dsts", "*", "dsts", "dsts", ".", "each", "do", "|", "dst", "|", "if", "dst", ".", "empty?", "or", "dst", "==", "Edoors", "::", "ACT_SEP", "or", "dst", "[", "0", "]", "==", "Edoors", "::", "PATH_SEP", "or", "dst", "=~", "/", "\\/", "\\?", "/", "or", "dst", "=~", "/", "\\/", "/", "or", "dst", "=~", "/", "\\s", "/", "raise", "Edoors", "::", "Exception", ".", "new", "\"destination #{dst} is not acceptable\"", "end", "@dsts", "<<", "dst", "end", "end" ]
adds destinations to the destination list @param [Array] dsts destinations to add @raise Edoors::Exception if a destination is not acceptable The parameters are checked before beeing added. they must not be empty or be '?' or start with '/' or contain '/?' or '//' or '\s+'
[ "adds", "destinations", "to", "the", "destination", "list" ]
4f065f63125907b3a4f72fbab8722c58ccab41c1
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/particle.rb#L162-L170
9,115
jeremyz/edoors-ruby
lib/edoors/particle.rb
Edoors.Particle.set_dst!
def set_dst! a, d @action = a if d.is_a? Edoors::Iota @dst = d else @dst = nil _split_path! d end end
ruby
def set_dst! a, d @action = a if d.is_a? Edoors::Iota @dst = d else @dst = nil _split_path! d end end
[ "def", "set_dst!", "a", ",", "d", "@action", "=", "a", "if", "d", ".", "is_a?", "Edoors", "::", "Iota", "@dst", "=", "d", "else", "@dst", "=", "nil", "_split_path!", "d", "end", "end" ]
sets the current destination @param [String] a the action @param [String Iota] d the destination
[ "sets", "the", "current", "destination" ]
4f065f63125907b3a4f72fbab8722c58ccab41c1
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/particle.rb#L186-L194
9,116
jeremyz/edoors-ruby
lib/edoors/particle.rb
Edoors.Particle.apply_link!
def apply_link! lnk init! lnk.door clear_dsts! add_dsts *lnk.dsts set_link_keys *lnk.keys end
ruby
def apply_link! lnk init! lnk.door clear_dsts! add_dsts *lnk.dsts set_link_keys *lnk.keys end
[ "def", "apply_link!", "lnk", "init!", "lnk", ".", "door", "clear_dsts!", "add_dsts", "lnk", ".", "dsts", "set_link_keys", "lnk", ".", "keys", "end" ]
applies the effects of the given Link @param [Link] lnk the link to apply effects updates @src with Link @src, clears the destination list adds the Link destinations to @dsts, sets the @link_keys
[ "applies", "the", "effects", "of", "the", "given", "Link" ]
4f065f63125907b3a4f72fbab8722c58ccab41c1
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/particle.rb#L257-L262
9,117
jeremyz/edoors-ruby
lib/edoors/particle.rb
Edoors.Particle.set_link_keys
def set_link_keys *args @link_keys.clear if not @link_keys.empty? args.compact! args.each do |lf| @link_keys << lf end @link_value = @payload.select { |k,v| @link_keys.include? k } end
ruby
def set_link_keys *args @link_keys.clear if not @link_keys.empty? args.compact! args.each do |lf| @link_keys << lf end @link_value = @payload.select { |k,v| @link_keys.include? k } end
[ "def", "set_link_keys", "*", "args", "@link_keys", ".", "clear", "if", "not", "@link_keys", ".", "empty?", "args", ".", "compact!", "args", ".", "each", "do", "|", "lf", "|", "@link_keys", "<<", "lf", "end", "@link_value", "=", "@payload", ".", "select", "{", "|", "k", ",", "v", "|", "@link_keys", ".", "include?", "k", "}", "end" ]
sets the links keys @param [Array] args list of keys to set \@link_value attribute will be updated
[ "sets", "the", "links", "keys" ]
4f065f63125907b3a4f72fbab8722c58ccab41c1
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/particle.rb#L315-L322
9,118
jeremyz/edoors-ruby
lib/edoors/particle.rb
Edoors.Particle.link_with?
def link_with? link return true if link.value.nil? link.value.keys.inject({}) { |h,k| h[k]=@payload[k] if @payload.has_key?(k); h }.eql? link.value end
ruby
def link_with? link return true if link.value.nil? link.value.keys.inject({}) { |h,k| h[k]=@payload[k] if @payload.has_key?(k); h }.eql? link.value end
[ "def", "link_with?", "link", "return", "true", "if", "link", ".", "value", ".", "nil?", "link", ".", "value", ".", "keys", ".", "inject", "(", "{", "}", ")", "{", "|", "h", ",", "k", "|", "h", "[", "k", "]", "=", "@payload", "[", "k", "]", "if", "@payload", ".", "has_key?", "(", "k", ")", ";", "h", "}", ".", "eql?", "link", ".", "value", "end" ]
tries to link the Particle with the given Link @param [Link] link the link to try to link with returns true if the value of the Link is nil otherwise checks if the extracted key values pairs from the Particle payload using the Link value keys as selectors, equals the Link value @return [Boolean] true if the Link links with the Particle
[ "tries", "to", "link", "the", "Particle", "with", "the", "given", "Link" ]
4f065f63125907b3a4f72fbab8722c58ccab41c1
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/particle.rb#L334-L337
9,119
jeremyz/edoors-ruby
lib/edoors/particle.rb
Edoors.Particle.clear_merged!
def clear_merged! r=false @merged.each do |p| p.clear_merged! r r.release_p p if r end @merged.clear end
ruby
def clear_merged! r=false @merged.each do |p| p.clear_merged! r r.release_p p if r end @merged.clear end
[ "def", "clear_merged!", "r", "=", "false", "@merged", ".", "each", "do", "|", "p", "|", "p", ".", "clear_merged!", "r", "r", ".", "release_p", "p", "if", "r", "end", "@merged", ".", "clear", "end" ]
recursively clears the merged Particle list @param [Boolean] r releases the cleared Particle if true
[ "recursively", "clears", "the", "merged", "Particle", "list" ]
4f065f63125907b3a4f72fbab8722c58ccab41c1
https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/particle.rb#L365-L371
9,120
bottleneckco/playoverwatch-scraper
lib/playoverwatch-scraper/scraper.rb
PlayOverwatch.Scraper.sr
def sr comp_div = @player_page.css('.competitive-rank > .h5') return -1 if comp_div.empty? content = comp_div.first.content content.to_i if Integer(content) rescue -1 end
ruby
def sr comp_div = @player_page.css('.competitive-rank > .h5') return -1 if comp_div.empty? content = comp_div.first.content content.to_i if Integer(content) rescue -1 end
[ "def", "sr", "comp_div", "=", "@player_page", ".", "css", "(", "'.competitive-rank > .h5'", ")", "return", "-", "1", "if", "comp_div", ".", "empty?", "content", "=", "comp_div", ".", "first", ".", "content", "content", ".", "to_i", "if", "Integer", "(", "content", ")", "rescue", "-", "1", "end" ]
Retrieve a player's current competitive season ranking. Returns -1 if player did not complete placements.
[ "Retrieve", "a", "player", "s", "current", "competitive", "season", "ranking", ".", "Returns", "-", "1", "if", "player", "did", "not", "complete", "placements", "." ]
7909bdda3cefe15a5f4718e122943146365a01e1
https://github.com/bottleneckco/playoverwatch-scraper/blob/7909bdda3cefe15a5f4718e122943146365a01e1/lib/playoverwatch-scraper/scraper.rb#L40-L45
9,121
bottleneckco/playoverwatch-scraper
lib/playoverwatch-scraper/scraper.rb
PlayOverwatch.Scraper.main_qp
def main_qp hero_img = hidden_mains_style.content.scan(/\.quickplay {.+?url\((.+?)\);/mis).flatten.first hero_img.scan(/\/hero\/(.+?)\/career/i).flatten.first end
ruby
def main_qp hero_img = hidden_mains_style.content.scan(/\.quickplay {.+?url\((.+?)\);/mis).flatten.first hero_img.scan(/\/hero\/(.+?)\/career/i).flatten.first end
[ "def", "main_qp", "hero_img", "=", "hidden_mains_style", ".", "content", ".", "scan", "(", "/", "\\.", "\\(", "\\)", "/mis", ")", ".", "flatten", ".", "first", "hero_img", ".", "scan", "(", "/", "\\/", "\\/", "\\/", "/i", ")", ".", "flatten", ".", "first", "end" ]
Retrieve player's main Quick Play hero, in lowercase form.
[ "Retrieve", "player", "s", "main", "Quick", "Play", "hero", "in", "lowercase", "form", "." ]
7909bdda3cefe15a5f4718e122943146365a01e1
https://github.com/bottleneckco/playoverwatch-scraper/blob/7909bdda3cefe15a5f4718e122943146365a01e1/lib/playoverwatch-scraper/scraper.rb#L49-L52
9,122
bottleneckco/playoverwatch-scraper
lib/playoverwatch-scraper/scraper.rb
PlayOverwatch.Scraper.main_comp
def main_comp hero_img = hidden_mains_style.content.scan(/\.competitive {.+?url\((.+?)\);/mis).flatten.first hero_img.scan(/\/hero\/(.+?)\/career/i).flatten.first end
ruby
def main_comp hero_img = hidden_mains_style.content.scan(/\.competitive {.+?url\((.+?)\);/mis).flatten.first hero_img.scan(/\/hero\/(.+?)\/career/i).flatten.first end
[ "def", "main_comp", "hero_img", "=", "hidden_mains_style", ".", "content", ".", "scan", "(", "/", "\\.", "\\(", "\\)", "/mis", ")", ".", "flatten", ".", "first", "hero_img", ".", "scan", "(", "/", "\\/", "\\/", "\\/", "/i", ")", ".", "flatten", ".", "first", "end" ]
Retrieve player's main Competitive hero, in lowercase form. You should check if the sr is -1 before attempting to call this.
[ "Retrieve", "player", "s", "main", "Competitive", "hero", "in", "lowercase", "form", ".", "You", "should", "check", "if", "the", "sr", "is", "-", "1", "before", "attempting", "to", "call", "this", "." ]
7909bdda3cefe15a5f4718e122943146365a01e1
https://github.com/bottleneckco/playoverwatch-scraper/blob/7909bdda3cefe15a5f4718e122943146365a01e1/lib/playoverwatch-scraper/scraper.rb#L57-L60
9,123
hilotus/spear-cb-api
lib/spear/request.rb
Spear.Request.to_xml
def to_xml(body) root = @api_options[:root_element].nil? ? 'Request' : @api_options[:root_element] body.to_xml(root: root, skip_instruct: true, skip_types: true) end
ruby
def to_xml(body) root = @api_options[:root_element].nil? ? 'Request' : @api_options[:root_element] body.to_xml(root: root, skip_instruct: true, skip_types: true) end
[ "def", "to_xml", "(", "body", ")", "root", "=", "@api_options", "[", ":root_element", "]", ".", "nil?", "?", "'Request'", ":", "@api_options", "[", ":root_element", "]", "body", ".", "to_xml", "(", "root", ":", "root", ",", "skip_instruct", ":", "true", ",", "skip_types", ":", "true", ")", "end" ]
parse body from hash to xml format
[ "parse", "body", "from", "hash", "to", "xml", "format" ]
a0fd264556b3532ee61961cbb2abf990fe855f47
https://github.com/hilotus/spear-cb-api/blob/a0fd264556b3532ee61961cbb2abf990fe855f47/lib/spear/request.rb#L74-L77
9,124
janlelis/ripl-profiles
lib/ripl/profiles.rb
Ripl::Profiles.Runner.parse_option
def parse_option( option, argv ) if option =~ /(?:-p|--profile)=?(.*)/ Ripl::Profiles.load( ($1.empty? ? argv.shift.to_s : $1).split(':') ) else super end end
ruby
def parse_option( option, argv ) if option =~ /(?:-p|--profile)=?(.*)/ Ripl::Profiles.load( ($1.empty? ? argv.shift.to_s : $1).split(':') ) else super end end
[ "def", "parse_option", "(", "option", ",", "argv", ")", "if", "option", "=~", "/", "/", "Ripl", "::", "Profiles", ".", "load", "(", "(", "$1", ".", "empty?", "?", "argv", ".", "shift", ".", "to_s", ":", "$1", ")", ".", "split", "(", "':'", ")", ")", "else", "super", "end", "end" ]
add command line option
[ "add", "command", "line", "option" ]
0f8d64d9650b2917fdb59b6846263578218f375f
https://github.com/janlelis/ripl-profiles/blob/0f8d64d9650b2917fdb59b6846263578218f375f/lib/ripl/profiles.rb#L59-L65
9,125
mlandauer/new_time
lib/new_time.rb
NewTime.NewTime.convert
def convert(point) today = Date.new(year, month, day) new_seconds = seconds + fractional + (minutes + hours * 60) * 60 # During daylight hours? if hours >= 6 && hours < 18 start = NewTime.sunrise(today, point) finish = NewTime.sunset(today, point) new_start_hour = 6 else # Is it before sunrise or after sunset? if hours < 6 start = NewTime.sunset(today - 1, point) finish = NewTime.sunrise(today, point) new_start_hour = 18 - 24 else start = NewTime.sunset(today, point) finish = NewTime.sunrise(today + 1, point) new_start_hour = 18 end end start + (new_seconds.to_f / (60 * 60) - new_start_hour) * (finish - start) / 12 end
ruby
def convert(point) today = Date.new(year, month, day) new_seconds = seconds + fractional + (minutes + hours * 60) * 60 # During daylight hours? if hours >= 6 && hours < 18 start = NewTime.sunrise(today, point) finish = NewTime.sunset(today, point) new_start_hour = 6 else # Is it before sunrise or after sunset? if hours < 6 start = NewTime.sunset(today - 1, point) finish = NewTime.sunrise(today, point) new_start_hour = 18 - 24 else start = NewTime.sunset(today, point) finish = NewTime.sunrise(today + 1, point) new_start_hour = 18 end end start + (new_seconds.to_f / (60 * 60) - new_start_hour) * (finish - start) / 12 end
[ "def", "convert", "(", "point", ")", "today", "=", "Date", ".", "new", "(", "year", ",", "month", ",", "day", ")", "new_seconds", "=", "seconds", "+", "fractional", "+", "(", "minutes", "+", "hours", "*", "60", ")", "*", "60", "# During daylight hours?", "if", "hours", ">=", "6", "&&", "hours", "<", "18", "start", "=", "NewTime", ".", "sunrise", "(", "today", ",", "point", ")", "finish", "=", "NewTime", ".", "sunset", "(", "today", ",", "point", ")", "new_start_hour", "=", "6", "else", "# Is it before sunrise or after sunset?", "if", "hours", "<", "6", "start", "=", "NewTime", ".", "sunset", "(", "today", "-", "1", ",", "point", ")", "finish", "=", "NewTime", ".", "sunrise", "(", "today", ",", "point", ")", "new_start_hour", "=", "18", "-", "24", "else", "start", "=", "NewTime", ".", "sunset", "(", "today", ",", "point", ")", "finish", "=", "NewTime", ".", "sunrise", "(", "today", "+", "1", ",", "point", ")", "new_start_hour", "=", "18", "end", "end", "start", "+", "(", "new_seconds", ".", "to_f", "/", "(", "60", "*", "60", ")", "-", "new_start_hour", ")", "*", "(", "finish", "-", "start", ")", "/", "12", "end" ]
Convert back to "normal" time
[ "Convert", "back", "to", "normal", "time" ]
0ea74c82cf59a56a03860c7d38f9058cff1f6d8b
https://github.com/mlandauer/new_time/blob/0ea74c82cf59a56a03860c7d38f9058cff1f6d8b/lib/new_time.rb#L33-L55
9,126
smsified/smsified-ruby
lib/smsified/reporting.rb
Smsified.Reporting.delivery_status
def delivery_status(options) raise ArgumentError, 'an options Hash is required' if !options.instance_of?(Hash) raise ArgumentError, ':sender_address is required' if options[:sender_address].nil? && @sender_address.nil? options[:sender_address] = options[:sender_address] || @sender_address Response.new self.class.get("/smsmessaging/outbound/#{options[:sender_address]}/requests/#{options[:request_id]}/deliveryInfos", :basic_auth => @auth, :headers => SMSIFIED_HTTP_HEADERS) end
ruby
def delivery_status(options) raise ArgumentError, 'an options Hash is required' if !options.instance_of?(Hash) raise ArgumentError, ':sender_address is required' if options[:sender_address].nil? && @sender_address.nil? options[:sender_address] = options[:sender_address] || @sender_address Response.new self.class.get("/smsmessaging/outbound/#{options[:sender_address]}/requests/#{options[:request_id]}/deliveryInfos", :basic_auth => @auth, :headers => SMSIFIED_HTTP_HEADERS) end
[ "def", "delivery_status", "(", "options", ")", "raise", "ArgumentError", ",", "'an options Hash is required'", "if", "!", "options", ".", "instance_of?", "(", "Hash", ")", "raise", "ArgumentError", ",", "':sender_address is required'", "if", "options", "[", ":sender_address", "]", ".", "nil?", "&&", "@sender_address", ".", "nil?", "options", "[", ":sender_address", "]", "=", "options", "[", ":sender_address", "]", "||", "@sender_address", "Response", ".", "new", "self", ".", "class", ".", "get", "(", "\"/smsmessaging/outbound/#{options[:sender_address]}/requests/#{options[:request_id]}/deliveryInfos\"", ",", ":basic_auth", "=>", "@auth", ",", ":headers", "=>", "SMSIFIED_HTTP_HEADERS", ")", "end" ]
Intantiate a new class to work with reporting @param [required, Hash] params to create the Reporting object with @option params [required, String] :username username to authenticate with @option params [required, String] :password to authenticate with @option params [optional, String] :base_uri of an alternative location of SMSified @option params [optional, String] :destination_address to use with subscriptions @option params [optional, String] :sender_address to use with subscriptions @option params [optional, Boolean] :debug to turn on the HTTparty debugging to stdout @example subscription = Subscription.new :username => 'user', :password => '123' Get the delivery status of an outstanding SMS request @param [required, Hash] params to get the delivery status @option params [required, String] :request_id to fetch the status for @option params [optional, String] :sender_address used to send the SMS, required if not provided on initialization of OneAPI @return [Object] A Response Object with http and data instance methods @raise [ArgumentError] of :sender_address is not passed here when not passed on instantiating the object @example one_api.delivery_status :request_id => 'f359193765f6a3149ca76a4508e21234', :sender_address => '14155551212'
[ "Intantiate", "a", "new", "class", "to", "work", "with", "reporting" ]
1c7a0f445ffe7fe0fb035a1faf44ac55687a4488
https://github.com/smsified/smsified-ruby/blob/1c7a0f445ffe7fe0fb035a1faf44ac55687a4488/lib/smsified/reporting.rb#L41-L48
9,127
jeremyvdw/disqussion
lib/disqussion/client/threads.rb
Disqussion.Threads.list
def list(*args) options = args.last.is_a?(Hash) ? args.pop : {} response = get('threads/list', options) end
ruby
def list(*args) options = args.last.is_a?(Hash) ? args.pop : {} response = get('threads/list', options) end
[ "def", "list", "(", "*", "args", ")", "options", "=", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "args", ".", "pop", ":", "{", "}", "response", "=", "get", "(", "'threads/list'", ",", "options", ")", "end" ]
Returns a list of threads sorted by the date created. @accessibility: public key, secret key @methods: GET @format: json, jsonp, rss @authenticated: false @limited: false @return [Hashie::Rash] List of threads. @param options [Hash] A customizable set of options. @option options [Integer] :category. Defaults to null @option options [String] :forum. Defaults to null. Looks up a forum by ID (aka short name) @option options [Integer] :thread. Defaults to null. Looks up a thread by ID. You may pass use the 'ident' or 'link' query types instead of an ID by including 'forum'. @option options [Integer, String] :author. Defaults to null. You may look up a user by username using the 'username' query type. @option options [Datetime, Timestamp] :since. Unix timestamp (or ISO datetime standard). Defaults to null @option options [String, Array] :related allows multiple. Defaults to []. You may specify relations to include with your response. Choices: forum, author, category @option options [Integer] :cursor. Defaults to null @option options [Integer] :limit. Defaults to 25. Maximum length of 100 @option options [String, Array] :include allows multiple. Defaults to ["open", "close"]. Choices: open, closed, killed. @option options [String] :order. Defaults to "asc". Choices: asc, desc @example Return extended information for forum 'myforum' Disqussion::Client.threads.list(:forum => "the88") @see: http://disqus.com/api/3.0/threads/list.json
[ "Returns", "a", "list", "of", "threads", "sorted", "by", "the", "date", "created", "." ]
5ad1b0325b7630daf41eb59fc8acbcb785cbc387
https://github.com/jeremyvdw/disqussion/blob/5ad1b0325b7630daf41eb59fc8acbcb785cbc387/lib/disqussion/client/threads.rb#L94-L97
9,128
jeremyvdw/disqussion
lib/disqussion/client/threads.rb
Disqussion.Threads.listPosts
def listPosts(*args) options = args.last.is_a?(Hash) ? args.pop : {} thread = args.first options.merge!(:thread => thread) if ([:ident, :link] & options.keys).empty? response = get('threads/listPosts', options) end
ruby
def listPosts(*args) options = args.last.is_a?(Hash) ? args.pop : {} thread = args.first options.merge!(:thread => thread) if ([:ident, :link] & options.keys).empty? response = get('threads/listPosts', options) end
[ "def", "listPosts", "(", "*", "args", ")", "options", "=", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "args", ".", "pop", ":", "{", "}", "thread", "=", "args", ".", "first", "options", ".", "merge!", "(", ":thread", "=>", "thread", ")", "if", "(", "[", ":ident", ",", ":link", "]", "&", "options", ".", "keys", ")", ".", "empty?", "response", "=", "get", "(", "'threads/listPosts'", ",", "options", ")", "end" ]
Returns a list of posts within a thread. @accessibility: public key, secret key @methods: GET @format: json, jsonp, rss @authenticated: false @limited: false @return [Hashie::Rash] List of threads post. @param thread [Integer] Looks up a thread by ID. You must be a moderator on the selected thread's forum. You may pass use the 'ident' or 'link' query types instead of an ID by including 'forum'. @param options [Hash] A customizable set of options. @option options [String] :forum. Defaults to null. Looks up a forum by ID (aka short name) @option options [Datetime, Timestamp] :since. Unix timestamp (or ISO datetime standard). Defaults to null @option options [String, Array] :related allows multiple. Defaults to []. You may specify relations to include with your response. Choices: forum @option options [Integer] :cursor. Defaults to null @option options [Integer] :limit. Defaults to 25. Maximum length of 100 @option options [Integer] :query. Defaults to null. @option options [String, Array] :include allows multiple. Defaults to ["approved"]. Choices: unapproved, approved, spam, deleted, flagged @option options [String] :order. Defaults to "desc". Choices: asc, desc @example Return extended information for forum 'myforum' Disqussion::Client.threads.list() @see: http://disqus.com/api/3.0/threads/listPosts.json
[ "Returns", "a", "list", "of", "posts", "within", "a", "thread", "." ]
5ad1b0325b7630daf41eb59fc8acbcb785cbc387
https://github.com/jeremyvdw/disqussion/blob/5ad1b0325b7630daf41eb59fc8acbcb785cbc387/lib/disqussion/client/threads.rb#L185-L190
9,129
jeremyvdw/disqussion
lib/disqussion/client/threads.rb
Disqussion.Threads.remove
def remove(*args) options = args.last.is_a?(Hash) ? args.pop : {} thread = args.first options.merge!(:thread => thread) if ([:ident, :link] & options.keys).empty? response = post('threads/remove', options) end
ruby
def remove(*args) options = args.last.is_a?(Hash) ? args.pop : {} thread = args.first options.merge!(:thread => thread) if ([:ident, :link] & options.keys).empty? response = post('threads/remove', options) end
[ "def", "remove", "(", "*", "args", ")", "options", "=", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "args", ".", "pop", ":", "{", "}", "thread", "=", "args", ".", "first", "options", ".", "merge!", "(", ":thread", "=>", "thread", ")", "if", "(", "[", ":ident", ",", ":link", "]", "&", "options", ".", "keys", ")", ".", "empty?", "response", "=", "post", "(", "'threads/remove'", ",", "options", ")", "end" ]
Removes a thread @accessibility: public key, secret key @methods: POST @format: json, jsonp @authenticated: true @limited: false @param thread [Array, Integer] allows multiple. Looks up a thread by ID. You must be a moderator on the selected thread's forum. You may pass use the 'ident' or 'link' query types instead of an ID by including 'forum'. @return [Hashie::Rash] ID of the deleted thread. @option options [String] :forum. Defaults to null. Looks up a forum by ID (aka short name). You must be a moderator on the selected forum. @example Removes thread 12345678 Disqussion::Client.threads.remove(12345678) @see: http://disqus.com/api/3.0/threads/remove.json
[ "Removes", "a", "thread" ]
5ad1b0325b7630daf41eb59fc8acbcb785cbc387
https://github.com/jeremyvdw/disqussion/blob/5ad1b0325b7630daf41eb59fc8acbcb785cbc387/lib/disqussion/client/threads.rb#L223-L228
9,130
PlasticLizard/ruote-mongodb
lib/ruote-mongodb/mongodb_storage.rb
Ruote.MongoDbStorage.dump
def dump(type) get_many(type).map{|d|d.to_s}.sort.join("\n") end
ruby
def dump(type) get_many(type).map{|d|d.to_s}.sort.join("\n") end
[ "def", "dump", "(", "type", ")", "get_many", "(", "type", ")", ".", "map", "{", "|", "d", "|", "d", ".", "to_s", "}", ".", "sort", ".", "join", "(", "\"\\n\"", ")", "end" ]
Returns a String containing a representation of the current content of in this storage.
[ "Returns", "a", "String", "containing", "a", "representation", "of", "the", "current", "content", "of", "in", "this", "storage", "." ]
82d9701c4eea1916c7b27768b0abd43af1bb80f6
https://github.com/PlasticLizard/ruote-mongodb/blob/82d9701c4eea1916c7b27768b0abd43af1bb80f6/lib/ruote-mongodb/mongodb_storage.rb#L174-L176
9,131
wapcaplet/kelp
lib/kelp/field.rb
Kelp.Field.select_or_fill
def select_or_fill(field, value) case field_type(field) when :select begin select(value, :from => field) rescue Capybara::ElementNotFound raise Kelp::OptionNotFound, "Field '#{field}' has no option '#{value}'" end when :fillable_field fill_in(field, :with => value) end end
ruby
def select_or_fill(field, value) case field_type(field) when :select begin select(value, :from => field) rescue Capybara::ElementNotFound raise Kelp::OptionNotFound, "Field '#{field}' has no option '#{value}'" end when :fillable_field fill_in(field, :with => value) end end
[ "def", "select_or_fill", "(", "field", ",", "value", ")", "case", "field_type", "(", "field", ")", "when", ":select", "begin", "select", "(", "value", ",", ":from", "=>", "field", ")", "rescue", "Capybara", "::", "ElementNotFound", "raise", "Kelp", "::", "OptionNotFound", ",", "\"Field '#{field}' has no option '#{value}'\"", "end", "when", ":fillable_field", "fill_in", "(", "field", ",", ":with", "=>", "value", ")", "end", "end" ]
Select a value from a dropdown or listbox, or fill in a text field, depending on what kind of form field is available. If `field` is a dropdown or listbox, select `value` from that; otherwise, assume `field` is a text box. @param [String] field Capybara locator for the field (name, id, or label text) @param [String] value Text to select from a dropdown or enter in a text box @raise [Kelp::AmbiguousField] If more than one field matching `field` is found @raise [Kelp::FieldNotFound] If no field matching `field` is found @raise [Kelp::OptionNotFound] If a dropdown matching `field` is found, but it has no option matching `value` @since 0.1.9
[ "Select", "a", "value", "from", "a", "dropdown", "or", "listbox", "or", "fill", "in", "a", "text", "field", "depending", "on", "what", "kind", "of", "form", "field", "is", "available", ".", "If", "field", "is", "a", "dropdown", "or", "listbox", "select", "value", "from", "that", ";", "otherwise", "assume", "field", "is", "a", "text", "box", "." ]
592fe188db5a3d05e6120ed2157ad8d781601b7a
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/field.rb#L34-L46
9,132
wapcaplet/kelp
lib/kelp/field.rb
Kelp.Field.field_should_be_empty
def field_should_be_empty(field, scope={}) in_scope(scope) do _field = nice_find_field(field) if !(_field.nil? || _field.value.nil? || _field.value.strip == '') raise Kelp::Unexpected, "Expected field '#{field}' to be empty, but value is '#{_field.value}'" end end end
ruby
def field_should_be_empty(field, scope={}) in_scope(scope) do _field = nice_find_field(field) if !(_field.nil? || _field.value.nil? || _field.value.strip == '') raise Kelp::Unexpected, "Expected field '#{field}' to be empty, but value is '#{_field.value}'" end end end
[ "def", "field_should_be_empty", "(", "field", ",", "scope", "=", "{", "}", ")", "in_scope", "(", "scope", ")", "do", "_field", "=", "nice_find_field", "(", "field", ")", "if", "!", "(", "_field", ".", "nil?", "||", "_field", ".", "value", ".", "nil?", "||", "_field", ".", "value", ".", "strip", "==", "''", ")", "raise", "Kelp", "::", "Unexpected", ",", "\"Expected field '#{field}' to be empty, but value is '#{_field.value}'\"", "end", "end", "end" ]
Verify that the given field is empty or nil. @param [String] field Capybara locator for the field (name, id, or label text) @param [Hash] scope Scoping keywords as understood by {#in_scope} @raise [Kelp::Unexpected] If the given field is not empty or nil
[ "Verify", "that", "the", "given", "field", "is", "empty", "or", "nil", "." ]
592fe188db5a3d05e6120ed2157ad8d781601b7a
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/field.rb#L168-L176
9,133
wapcaplet/kelp
lib/kelp/field.rb
Kelp.Field.field_value
def field_value(field) element = find_field(field) value = (element.tag_name == 'textarea') ? element.text : element.value # If field value is an Array, take the first item if value.class == Array value = value.first end return value.to_s end
ruby
def field_value(field) element = find_field(field) value = (element.tag_name == 'textarea') ? element.text : element.value # If field value is an Array, take the first item if value.class == Array value = value.first end return value.to_s end
[ "def", "field_value", "(", "field", ")", "element", "=", "find_field", "(", "field", ")", "value", "=", "(", "element", ".", "tag_name", "==", "'textarea'", ")", "?", "element", ".", "text", ":", "element", ".", "value", "# If field value is an Array, take the first item", "if", "value", ".", "class", "==", "Array", "value", "=", "value", ".", "first", "end", "return", "value", ".", "to_s", "end" ]
Return the string value found in the given field. If the field is `nil`, return the empty string. @param [String] field Capybara locator for the field (name, id, or label text) @return [String] The value found in the given field @since 0.2.1
[ "Return", "the", "string", "value", "found", "in", "the", "given", "field", ".", "If", "the", "field", "is", "nil", "return", "the", "empty", "string", "." ]
592fe188db5a3d05e6120ed2157ad8d781601b7a
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/field.rb#L190-L198
9,134
wapcaplet/kelp
lib/kelp/field.rb
Kelp.Field.fields_should_contain
def fields_should_contain(field_values, scope={}) in_scope(scope) do field_values.each do |field, value| _field = find_field(field) # For nil/empty, check for nil field or nil value if value.nil? or value.strip.empty? field_should_be_empty(field) # If field is a dropdown elsif _field.tag_name == 'select' dropdown_should_equal(field, value) # Otherwise treat as a text field else field_should_contain(field, value) end end end end
ruby
def fields_should_contain(field_values, scope={}) in_scope(scope) do field_values.each do |field, value| _field = find_field(field) # For nil/empty, check for nil field or nil value if value.nil? or value.strip.empty? field_should_be_empty(field) # If field is a dropdown elsif _field.tag_name == 'select' dropdown_should_equal(field, value) # Otherwise treat as a text field else field_should_contain(field, value) end end end end
[ "def", "fields_should_contain", "(", "field_values", ",", "scope", "=", "{", "}", ")", "in_scope", "(", "scope", ")", "do", "field_values", ".", "each", "do", "|", "field", ",", "value", "|", "_field", "=", "find_field", "(", "field", ")", "# For nil/empty, check for nil field or nil value", "if", "value", ".", "nil?", "or", "value", ".", "strip", ".", "empty?", "field_should_be_empty", "(", "field", ")", "# If field is a dropdown", "elsif", "_field", ".", "tag_name", "==", "'select'", "dropdown_should_equal", "(", "field", ",", "value", ")", "# Otherwise treat as a text field", "else", "field_should_contain", "(", "field", ",", "value", ")", "end", "end", "end", "end" ]
Verify the values of multiple fields given as a Hash. @param [Hash] field_values "field" => "value" for each field you want to verify @param [Hash] scope Scoping keywords as understood by {#in_scope} @raise [Kelp::Unexpected] If any field does not contain the expected value
[ "Verify", "the", "values", "of", "multiple", "fields", "given", "as", "a", "Hash", "." ]
592fe188db5a3d05e6120ed2157ad8d781601b7a
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/field.rb#L265-L281
9,135
wapcaplet/kelp
lib/kelp/field.rb
Kelp.Field.field_type
def field_type(field) select = all(:select, field).count fillable = all(:fillable_field, field).count count = select + fillable case count when 0 raise Kelp::FieldNotFound, "No field with id, name, or label '#{field}' found" when 1 return select > 0 ? :select : :fillable_field else raise Kelp::AmbiguousField, "Field '#{field}' is ambiguous" end end
ruby
def field_type(field) select = all(:select, field).count fillable = all(:fillable_field, field).count count = select + fillable case count when 0 raise Kelp::FieldNotFound, "No field with id, name, or label '#{field}' found" when 1 return select > 0 ? :select : :fillable_field else raise Kelp::AmbiguousField, "Field '#{field}' is ambiguous" end end
[ "def", "field_type", "(", "field", ")", "select", "=", "all", "(", ":select", ",", "field", ")", ".", "count", "fillable", "=", "all", "(", ":fillable_field", ",", "field", ")", ".", "count", "count", "=", "select", "+", "fillable", "case", "count", "when", "0", "raise", "Kelp", "::", "FieldNotFound", ",", "\"No field with id, name, or label '#{field}' found\"", "when", "1", "return", "select", ">", "0", "?", ":select", ":", ":fillable_field", "else", "raise", "Kelp", "::", "AmbiguousField", ",", "\"Field '#{field}' is ambiguous\"", "end", "end" ]
Figure out whether the field locator matches a single select or fillable field. @param [String] field Capybara locator for the field (name, id, or label text) @raise [Kelp::AmbiguousField] If more than one field matching `field` is found @raise [Kelp::FieldNotFound] If no field matching `field` is found @return [Symbol] `:select` or `:fillable_field` depending on the type of element
[ "Figure", "out", "whether", "the", "field", "locator", "matches", "a", "single", "select", "or", "fillable", "field", "." ]
592fe188db5a3d05e6120ed2157ad8d781601b7a
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/field.rb#L318-L333
9,136
octoai/gem-octocore-cassandra
lib/octocore-cassandra/kafka_bridge.rb
Octo.KafkaBridge.create_message
def create_message(message) begin @producer.produce(JSON.dump(message), topic: @topic) rescue Kafka::BufferOverflow Octo.logger.error 'Buffer Overflow. Sleeping for 1s' sleep 1 retry end end
ruby
def create_message(message) begin @producer.produce(JSON.dump(message), topic: @topic) rescue Kafka::BufferOverflow Octo.logger.error 'Buffer Overflow. Sleeping for 1s' sleep 1 retry end end
[ "def", "create_message", "(", "message", ")", "begin", "@producer", ".", "produce", "(", "JSON", ".", "dump", "(", "message", ")", ",", "topic", ":", "@topic", ")", "rescue", "Kafka", "::", "BufferOverflow", "Octo", ".", "logger", ".", "error", "'Buffer Overflow. Sleeping for 1s'", "sleep", "1", "retry", "end", "end" ]
Creates a new message. @param [Hash] message The message hash to be produced
[ "Creates", "a", "new", "message", "." ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/kafka_bridge.rb#L49-L57
9,137
erpe/acts_as_referred
lib/acts_as_referred/instance_methods.rb
ActsAsReferred.InstanceMethods.create_referrer
def create_referrer # will not respond to _get_reqref unless # reqref injected in application-controller # if self.respond_to?(:_get_reqref) if struct = _get_reqref self.create_referee( origin: struct.referrer_url, request: struct.request_url, visits: struct.visit_count ) end end end
ruby
def create_referrer # will not respond to _get_reqref unless # reqref injected in application-controller # if self.respond_to?(:_get_reqref) if struct = _get_reqref self.create_referee( origin: struct.referrer_url, request: struct.request_url, visits: struct.visit_count ) end end end
[ "def", "create_referrer", "# will not respond to _get_reqref unless ", "# reqref injected in application-controller", "#", "if", "self", ".", "respond_to?", "(", ":_get_reqref", ")", "if", "struct", "=", "_get_reqref", "self", ".", "create_referee", "(", "origin", ":", "struct", ".", "referrer_url", ",", "request", ":", "struct", ".", "request_url", ",", "visits", ":", "struct", ".", "visit_count", ")", "end", "end", "end" ]
after create hook to create a corresponding +Referee+
[ "after", "create", "hook", "to", "create", "a", "corresponding", "+", "Referee", "+" ]
d1ffb3208e6e358c9888cec71c7bd76d30a0fdd3
https://github.com/erpe/acts_as_referred/blob/d1ffb3208e6e358c9888cec71c7bd76d30a0fdd3/lib/acts_as_referred/instance_methods.rb#L7-L22
9,138
justenwalker/baha
lib/baha/config.rb
Baha.Config.init_docker!
def init_docker! Docker.options = @options set_docker_url LOG.debug { "Docker URL: #{Docker.url}"} LOG.debug { "Docker Options: #{Docker.options.inspect}"} Docker.validate_version! end
ruby
def init_docker! Docker.options = @options set_docker_url LOG.debug { "Docker URL: #{Docker.url}"} LOG.debug { "Docker Options: #{Docker.options.inspect}"} Docker.validate_version! end
[ "def", "init_docker!", "Docker", ".", "options", "=", "@options", "set_docker_url", "LOG", ".", "debug", "{", "\"Docker URL: #{Docker.url}\"", "}", "LOG", ".", "debug", "{", "\"Docker Options: #{Docker.options.inspect}\"", "}", "Docker", ".", "validate_version!", "end" ]
Initialize Docker Client
[ "Initialize", "Docker", "Client" ]
df1b57e222f4f4ebe474794d7f191f912be6d9fc
https://github.com/justenwalker/baha/blob/df1b57e222f4f4ebe474794d7f191f912be6d9fc/lib/baha/config.rb#L112-L118
9,139
redding/logsly
lib/logsly/logging182/appenders/buffering.rb
Logsly::Logging182::Appenders.Buffering.immediate_at=
def immediate_at=( level ) @immediate.clear # get the immediate levels -- no buffering occurs at these levels, and # a log message is written to the logging destination immediately immediate_at = case level when String; level.split(',').map {|x| x.strip} when Array; level else Array(level) end immediate_at.each do |lvl| num = ::Logsly::Logging182.level_num(lvl) next if num.nil? @immediate[num] = true end end
ruby
def immediate_at=( level ) @immediate.clear # get the immediate levels -- no buffering occurs at these levels, and # a log message is written to the logging destination immediately immediate_at = case level when String; level.split(',').map {|x| x.strip} when Array; level else Array(level) end immediate_at.each do |lvl| num = ::Logsly::Logging182.level_num(lvl) next if num.nil? @immediate[num] = true end end
[ "def", "immediate_at", "=", "(", "level", ")", "@immediate", ".", "clear", "# get the immediate levels -- no buffering occurs at these levels, and", "# a log message is written to the logging destination immediately", "immediate_at", "=", "case", "level", "when", "String", ";", "level", ".", "split", "(", "','", ")", ".", "map", "{", "|", "x", "|", "x", ".", "strip", "}", "when", "Array", ";", "level", "else", "Array", "(", "level", ")", "end", "immediate_at", ".", "each", "do", "|", "lvl", "|", "num", "=", "::", "Logsly", "::", "Logging182", ".", "level_num", "(", "lvl", ")", "next", "if", "num", ".", "nil?", "@immediate", "[", "num", "]", "=", "true", "end", "end" ]
Configure the levels that will trigger an immediate flush of the logging buffer. When a log event of the given level is seen, the buffer will be flushed immediately. Only the levels explicitly given in this assignment will flush the buffer; if an "error" message is configured to immediately flush the buffer, a "fatal" message will not even though it is a higher level. Both must be explicitly passed to this assignment. You can pass in a single level name or number, an array of level names or numbers, or a string containing a comma separated list of level names or numbers. immediate_at = :error immediate_at = [:error, :fatal] immediate_at = "warn, error"
[ "Configure", "the", "levels", "that", "will", "trigger", "an", "immediate", "flush", "of", "the", "logging", "buffer", ".", "When", "a", "log", "event", "of", "the", "given", "level", "is", "seen", "the", "buffer", "will", "be", "flushed", "immediately", ".", "Only", "the", "levels", "explicitly", "given", "in", "this", "assignment", "will", "flush", "the", "buffer", ";", "if", "an", "error", "message", "is", "configured", "to", "immediately", "flush", "the", "buffer", "a", "fatal", "message", "will", "not", "even", "though", "it", "is", "a", "higher", "level", ".", "Both", "must", "be", "explicitly", "passed", "to", "this", "assignment", "." ]
a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf
https://github.com/redding/logsly/blob/a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf/lib/logsly/logging182/appenders/buffering.rb#L102-L118
9,140
michaelmior/mipper
lib/mipper/expression.rb
MIPPeR.LinExpr.add
def add(other) case other when LinExpr @terms.merge!(other.terms) { |_, c1, c2| c1 + c2 } when Variable if @terms.key? other @terms[other] += 1.0 else @terms[other] = 1.0 end else fail TypeError end self end
ruby
def add(other) case other when LinExpr @terms.merge!(other.terms) { |_, c1, c2| c1 + c2 } when Variable if @terms.key? other @terms[other] += 1.0 else @terms[other] = 1.0 end else fail TypeError end self end
[ "def", "add", "(", "other", ")", "case", "other", "when", "LinExpr", "@terms", ".", "merge!", "(", "other", ".", "terms", ")", "{", "|", "_", ",", "c1", ",", "c2", "|", "c1", "+", "c2", "}", "when", "Variable", "if", "@terms", ".", "key?", "other", "@terms", "[", "other", "]", "+=", "1.0", "else", "@terms", "[", "other", "]", "=", "1.0", "end", "else", "fail", "TypeError", "end", "self", "end" ]
Add terms from the other expression to this one
[ "Add", "terms", "from", "the", "other", "expression", "to", "this", "one" ]
4ab7f8b32c27f33fc5121756554a0a28d2077e06
https://github.com/michaelmior/mipper/blob/4ab7f8b32c27f33fc5121756554a0a28d2077e06/lib/mipper/expression.rb#L25-L40
9,141
michaelmior/mipper
lib/mipper/expression.rb
MIPPeR.LinExpr.inspect
def inspect @terms.map do |var, coeff| # Skip if the coefficient is zero or the value is zero value = var.value next if coeff == 0 || value == 0 || value == false coeff == 1 ? var.name : "#{var.name} * #{coeff}" end.compact.join(' + ') end
ruby
def inspect @terms.map do |var, coeff| # Skip if the coefficient is zero or the value is zero value = var.value next if coeff == 0 || value == 0 || value == false coeff == 1 ? var.name : "#{var.name} * #{coeff}" end.compact.join(' + ') end
[ "def", "inspect", "@terms", ".", "map", "do", "|", "var", ",", "coeff", "|", "# Skip if the coefficient is zero or the value is zero", "value", "=", "var", ".", "value", "next", "if", "coeff", "==", "0", "||", "value", "==", "0", "||", "value", "==", "false", "coeff", "==", "1", "?", "var", ".", "name", ":", "\"#{var.name} * #{coeff}\"", "end", ".", "compact", ".", "join", "(", "' + '", ")", "end" ]
Produce a string representing the expression
[ "Produce", "a", "string", "representing", "the", "expression" ]
4ab7f8b32c27f33fc5121756554a0a28d2077e06
https://github.com/michaelmior/mipper/blob/4ab7f8b32c27f33fc5121756554a0a28d2077e06/lib/mipper/expression.rb#L43-L51
9,142
redding/ns-options
lib/ns-options/option.rb
NsOptions.Option.value
def value val = self.lazy_proc?(@value) ? self.coerce(@value.call) : @value val.respond_to?(:returned_value) ? val.returned_value : val end
ruby
def value val = self.lazy_proc?(@value) ? self.coerce(@value.call) : @value val.respond_to?(:returned_value) ? val.returned_value : val end
[ "def", "value", "val", "=", "self", ".", "lazy_proc?", "(", "@value", ")", "?", "self", ".", "coerce", "(", "@value", ".", "call", ")", ":", "@value", "val", ".", "respond_to?", "(", ":returned_value", ")", "?", "val", ".", "returned_value", ":", "val", "end" ]
if reading a lazy_proc, call the proc and return its coerced return val otherwise, just return the stored value
[ "if", "reading", "a", "lazy_proc", "call", "the", "proc", "and", "return", "its", "coerced", "return", "val", "otherwise", "just", "return", "the", "stored", "value" ]
63618a18e7a1d270dffc5a3cfea70ef45569e061
https://github.com/redding/ns-options/blob/63618a18e7a1d270dffc5a3cfea70ef45569e061/lib/ns-options/option.rb#L40-L43
9,143
geoffgarside/demolisher
lib/demolisher.rb
Demolisher.Node.method_missing
def method_missing(meth, *args, &block) # :nodoc: xpath = _xpath_for_element(meth.to_s, args.shift) return nil if xpath.empty? if block_given? xpath.each_with_index do |node, idx| @nodes.push(node) case block.arity when 1 yield idx when 2 yield self.class.new(node, @namespaces, false), idx else yield end @nodes.pop end self else node = xpath.first if node.xpath('text()').length == 1 content = node.xpath('text()').first.content case meth.to_s when /\?$/ !! Regexp.new(/(t(rue)?|y(es)?|1)/i).match(content) else content end else self.class.new(node, @namespaces, false) end end end
ruby
def method_missing(meth, *args, &block) # :nodoc: xpath = _xpath_for_element(meth.to_s, args.shift) return nil if xpath.empty? if block_given? xpath.each_with_index do |node, idx| @nodes.push(node) case block.arity when 1 yield idx when 2 yield self.class.new(node, @namespaces, false), idx else yield end @nodes.pop end self else node = xpath.first if node.xpath('text()').length == 1 content = node.xpath('text()').first.content case meth.to_s when /\?$/ !! Regexp.new(/(t(rue)?|y(es)?|1)/i).match(content) else content end else self.class.new(node, @namespaces, false) end end end
[ "def", "method_missing", "(", "meth", ",", "*", "args", ",", "&", "block", ")", "# :nodoc:", "xpath", "=", "_xpath_for_element", "(", "meth", ".", "to_s", ",", "args", ".", "shift", ")", "return", "nil", "if", "xpath", ".", "empty?", "if", "block_given?", "xpath", ".", "each_with_index", "do", "|", "node", ",", "idx", "|", "@nodes", ".", "push", "(", "node", ")", "case", "block", ".", "arity", "when", "1", "yield", "idx", "when", "2", "yield", "self", ".", "class", ".", "new", "(", "node", ",", "@namespaces", ",", "false", ")", ",", "idx", "else", "yield", "end", "@nodes", ".", "pop", "end", "self", "else", "node", "=", "xpath", ".", "first", "if", "node", ".", "xpath", "(", "'text()'", ")", ".", "length", "==", "1", "content", "=", "node", ".", "xpath", "(", "'text()'", ")", ".", "first", ".", "content", "case", "meth", ".", "to_s", "when", "/", "\\?", "/", "!", "!", "Regexp", ".", "new", "(", "/", "/i", ")", ".", "match", "(", "content", ")", "else", "content", "end", "else", "self", ".", "class", ".", "new", "(", "node", ",", "@namespaces", ",", "false", ")", "end", "end", "end" ]
The workhorse, finds the node matching meth. Rough flow guide: If a block is given then yield to it each for each instance of the element found in the current node. If no block given then get the first element found If the node has only one text element check if the method called has a ? suffix then return true if node content looks like a boolean. Otherwise return text content Otherwise return a new Node instance
[ "The", "workhorse", "finds", "the", "node", "matching", "meth", "." ]
36e12417a35aa4e04c8bf76f7be305bb0cb0516d
https://github.com/geoffgarside/demolisher/blob/36e12417a35aa4e04c8bf76f7be305bb0cb0516d/lib/demolisher.rb#L72-L105
9,144
dmolesUC3/xml-mapping_extensions
lib/xml/mapping_extensions.rb
XML.Mapping.write_xml
def write_xml(options = { mapping: :_default }) xml = save_to_xml(options) formatter = REXML::Formatters::Pretty.new formatter.compact = true io = ::StringIO.new formatter.write(xml, io) io.string end
ruby
def write_xml(options = { mapping: :_default }) xml = save_to_xml(options) formatter = REXML::Formatters::Pretty.new formatter.compact = true io = ::StringIO.new formatter.write(xml, io) io.string end
[ "def", "write_xml", "(", "options", "=", "{", "mapping", ":", ":_default", "}", ")", "xml", "=", "save_to_xml", "(", "options", ")", "formatter", "=", "REXML", "::", "Formatters", "::", "Pretty", ".", "new", "formatter", ".", "compact", "=", "true", "io", "=", "::", "StringIO", ".", "new", "formatter", ".", "write", "(", "xml", ",", "io", ")", "io", ".", "string", "end" ]
Writes this mapped object as a pretty-printed XML string. @param options [Hash] the options to be passed to [XML::Mapping#save_to_xml](http://multi-io.github.io/xml-mapping/XML/Mapping.html#method-i-save_to_xml) @return [String] the XML form of the object, as a compact, pretty-printed string.
[ "Writes", "this", "mapped", "object", "as", "a", "pretty", "-", "printed", "XML", "string", "." ]
012a01aaebc920229f6af9df881717fe91b24c8e
https://github.com/dmolesUC3/xml-mapping_extensions/blob/012a01aaebc920229f6af9df881717fe91b24c8e/lib/xml/mapping_extensions.rb#L43-L50
9,145
stevenhaddox/cert_munger
lib/cert_munger/formatter.rb
CertMunger.ClassMethods.to_cert
def to_cert(raw_cert) logger.debug "CertMunger raw_cert:\n#{raw_cert}" new_cert = build_cert(raw_cert) logger.debug "CertMunger reformatted_cert:\n#{new_cert}" logger.debug 'Returning OpenSSL::X509::Certificate.new on new_cert' OpenSSL::X509::Certificate.new new_cert end
ruby
def to_cert(raw_cert) logger.debug "CertMunger raw_cert:\n#{raw_cert}" new_cert = build_cert(raw_cert) logger.debug "CertMunger reformatted_cert:\n#{new_cert}" logger.debug 'Returning OpenSSL::X509::Certificate.new on new_cert' OpenSSL::X509::Certificate.new new_cert end
[ "def", "to_cert", "(", "raw_cert", ")", "logger", ".", "debug", "\"CertMunger raw_cert:\\n#{raw_cert}\"", "new_cert", "=", "build_cert", "(", "raw_cert", ")", "logger", ".", "debug", "\"CertMunger reformatted_cert:\\n#{new_cert}\"", "logger", ".", "debug", "'Returning OpenSSL::X509::Certificate.new on new_cert'", "OpenSSL", "::", "X509", "::", "Certificate", ".", "new", "new_cert", "end" ]
Attempts to munge a string into a valid X509 certificate @param raw_cert [String] The string of text you wish to parse into a cert @return [OpenSSL::X509::Certificate]
[ "Attempts", "to", "munge", "a", "string", "into", "a", "valid", "X509", "certificate" ]
48a42f93f964bb47f4311d9e3f7a3ab03c7a5bee
https://github.com/stevenhaddox/cert_munger/blob/48a42f93f964bb47f4311d9e3f7a3ab03c7a5bee/lib/cert_munger/formatter.rb#L36-L43
9,146
stevenhaddox/cert_munger
lib/cert_munger/formatter.rb
CertMunger.ClassMethods.build_cert
def build_cert(raw_cert) tmp_cert = ['-----BEGIN CERTIFICATE-----'] cert_contents = if raw_cert.lines.count == 1 one_line_contents(raw_cert) else multi_line_contents(raw_cert) end tmp_cert << cert_contents.flatten # put mixed space lines as own elements tmp_cert << '-----END CERTIFICATE-----' tmp_cert.join("\n").rstrip end
ruby
def build_cert(raw_cert) tmp_cert = ['-----BEGIN CERTIFICATE-----'] cert_contents = if raw_cert.lines.count == 1 one_line_contents(raw_cert) else multi_line_contents(raw_cert) end tmp_cert << cert_contents.flatten # put mixed space lines as own elements tmp_cert << '-----END CERTIFICATE-----' tmp_cert.join("\n").rstrip end
[ "def", "build_cert", "(", "raw_cert", ")", "tmp_cert", "=", "[", "'-----BEGIN CERTIFICATE-----'", "]", "cert_contents", "=", "if", "raw_cert", ".", "lines", ".", "count", "==", "1", "one_line_contents", "(", "raw_cert", ")", "else", "multi_line_contents", "(", "raw_cert", ")", "end", "tmp_cert", "<<", "cert_contents", ".", "flatten", "# put mixed space lines as own elements", "tmp_cert", "<<", "'-----END CERTIFICATE-----'", "tmp_cert", ".", "join", "(", "\"\\n\"", ")", ".", "rstrip", "end" ]
Creates a temporary cert and orchestrates certificate body reformatting @param raw_cert [String] The string of text you wish to parse into a cert @return [String] reformatted and (hopefully) parseable certificate string
[ "Creates", "a", "temporary", "cert", "and", "orchestrates", "certificate", "body", "reformatting" ]
48a42f93f964bb47f4311d9e3f7a3ab03c7a5bee
https://github.com/stevenhaddox/cert_munger/blob/48a42f93f964bb47f4311d9e3f7a3ab03c7a5bee/lib/cert_munger/formatter.rb#L49-L59
9,147
stevenhaddox/cert_munger
lib/cert_munger/formatter.rb
CertMunger.ClassMethods.multi_line_contents
def multi_line_contents(raw_cert) cert_contents = raw_cert.split(/[-](.*)[-]/)[2] cert_contents.lines.map do |line| line.lstrip.squeeze(' ').split(' ') end end
ruby
def multi_line_contents(raw_cert) cert_contents = raw_cert.split(/[-](.*)[-]/)[2] cert_contents.lines.map do |line| line.lstrip.squeeze(' ').split(' ') end end
[ "def", "multi_line_contents", "(", "raw_cert", ")", "cert_contents", "=", "raw_cert", ".", "split", "(", "/", "/", ")", "[", "2", "]", "cert_contents", ".", "lines", ".", "map", "do", "|", "line", "|", "line", ".", "lstrip", ".", "squeeze", "(", "' '", ")", ".", "split", "(", "' '", ")", "end", "end" ]
Attempts to reformat multi-line certificate bodies @param raw_cert [String] The string of text you wish to parse into a cert @return [String] reformatted certificate body
[ "Attempts", "to", "reformat", "multi", "-", "line", "certificate", "bodies" ]
48a42f93f964bb47f4311d9e3f7a3ab03c7a5bee
https://github.com/stevenhaddox/cert_munger/blob/48a42f93f964bb47f4311d9e3f7a3ab03c7a5bee/lib/cert_munger/formatter.rb#L96-L101
9,148
wvanbergen/love
lib/love.rb
Love.ResourceURI.append_query
def append_query(base_uri, added_params = {}) base_params = base_uri.query ? CGI.parse(base_uri.query) : {} get_params = base_params.merge(added_params.stringify_keys) base_uri.dup.tap do |uri| assignments = get_params.map do |k, v| case v when Array; v.map { |val| "#{::CGI.escape(k.to_s)}=#{::CGI.escape(val.to_s)}" }.join('&') else "#{::CGI.escape(k.to_s)}=#{::CGI.escape(v.to_s)}" end end uri.query = assignments.join('&') end end
ruby
def append_query(base_uri, added_params = {}) base_params = base_uri.query ? CGI.parse(base_uri.query) : {} get_params = base_params.merge(added_params.stringify_keys) base_uri.dup.tap do |uri| assignments = get_params.map do |k, v| case v when Array; v.map { |val| "#{::CGI.escape(k.to_s)}=#{::CGI.escape(val.to_s)}" }.join('&') else "#{::CGI.escape(k.to_s)}=#{::CGI.escape(v.to_s)}" end end uri.query = assignments.join('&') end end
[ "def", "append_query", "(", "base_uri", ",", "added_params", "=", "{", "}", ")", "base_params", "=", "base_uri", ".", "query", "?", "CGI", ".", "parse", "(", "base_uri", ".", "query", ")", ":", "{", "}", "get_params", "=", "base_params", ".", "merge", "(", "added_params", ".", "stringify_keys", ")", "base_uri", ".", "dup", ".", "tap", "do", "|", "uri", "|", "assignments", "=", "get_params", ".", "map", "do", "|", "k", ",", "v", "|", "case", "v", "when", "Array", ";", "v", ".", "map", "{", "|", "val", "|", "\"#{::CGI.escape(k.to_s)}=#{::CGI.escape(val.to_s)}\"", "}", ".", "join", "(", "'&'", ")", "else", "\"#{::CGI.escape(k.to_s)}=#{::CGI.escape(v.to_s)}\"", "end", "end", "uri", ".", "query", "=", "assignments", ".", "join", "(", "'&'", ")", "end", "end" ]
Appends GET parameters to a URI instance. Duplicate parameters will be replaced with the new value. @param [URI] base_uri The original URI to work with (will not be modified) @param [Hash] added_params To GET params to add. @return [URI] The URI with appended GET parameters
[ "Appends", "GET", "parameters", "to", "a", "URI", "instance", ".", "Duplicate", "parameters", "will", "be", "replaced", "with", "the", "new", "value", "." ]
14ed84c2fcc6b008879dd598328ab56d7dd4a053
https://github.com/wvanbergen/love/blob/14ed84c2fcc6b008879dd598328ab56d7dd4a053/lib/love.rb#L108-L120
9,149
wvanbergen/love
lib/love.rb
Love.Client.connection
def connection @connection ||= Net::HTTP.new(TENDER_API_HOST, Net::HTTP.https_default_port).tap do |http| http.use_ssl = true # http.verify_mode = OpenSSL::SSL::VERIFY_NONE http.start end end
ruby
def connection @connection ||= Net::HTTP.new(TENDER_API_HOST, Net::HTTP.https_default_port).tap do |http| http.use_ssl = true # http.verify_mode = OpenSSL::SSL::VERIFY_NONE http.start end end
[ "def", "connection", "@connection", "||=", "Net", "::", "HTTP", ".", "new", "(", "TENDER_API_HOST", ",", "Net", "::", "HTTP", ".", "https_default_port", ")", ".", "tap", "do", "|", "http", "|", "http", ".", "use_ssl", "=", "true", "# http.verify_mode = OpenSSL::SSL::VERIFY_NONE", "http", ".", "start", "end", "end" ]
Returns a persistent connection to the server, reusing a connection of it was previously established. This method is mainly used for internal use but can be used to do advanced HTTP connectivity with the Tender API server. @return [Net::HTTP] The net/http connection instance.
[ "Returns", "a", "persistent", "connection", "to", "the", "server", "reusing", "a", "connection", "of", "it", "was", "previously", "established", "." ]
14ed84c2fcc6b008879dd598328ab56d7dd4a053
https://github.com/wvanbergen/love/blob/14ed84c2fcc6b008879dd598328ab56d7dd4a053/lib/love.rb#L239-L245
9,150
wvanbergen/love
lib/love.rb
Love.Client.paged_each
def paged_each(uri, list_key, options = {}, &block) query_params = {} query_params[:since] = options[:since].to_date.to_s(:db) if options[:since] query_params[:page] = [options[:start_page].to_i, 1].max rescue 1 results = [] initial_result = get(append_query(uri, query_params)) # Determine the amount of pages that is going to be requested. max_page = (initial_result['total'].to_f / initial_result['per_page'].to_f).ceil end_page = options[:end_page].nil? ? max_page : [options[:end_page].to_i, max_page].min # Print out some initial debugging information Love.logger.debug "Paged requests to #{uri}: #{max_page} total pages, importing #{query_params[:page]} upto #{end_page}." if Love.logger # Handle first page of results if initial_result[list_key].kind_of?(Array) block_given? ? initial_result[list_key].each { |record| yield(record) } : results << initial_result[list_key] sleep(sleep_between_requests) if sleep_between_requests end start_page = query_params[:page].to_i + 1 start_page.upto(end_page) do |page| query_params[:page] = page result = get(append_query(uri, query_params)) if result[list_key].kind_of?(Array) block_given? ? result[list_key].each { |record| yield(record) } : results << result[list_key] sleep(sleep_between_requests) if sleep_between_requests end end results.flatten.map {|r| OpenStruct.new(r)} unless block_given? end
ruby
def paged_each(uri, list_key, options = {}, &block) query_params = {} query_params[:since] = options[:since].to_date.to_s(:db) if options[:since] query_params[:page] = [options[:start_page].to_i, 1].max rescue 1 results = [] initial_result = get(append_query(uri, query_params)) # Determine the amount of pages that is going to be requested. max_page = (initial_result['total'].to_f / initial_result['per_page'].to_f).ceil end_page = options[:end_page].nil? ? max_page : [options[:end_page].to_i, max_page].min # Print out some initial debugging information Love.logger.debug "Paged requests to #{uri}: #{max_page} total pages, importing #{query_params[:page]} upto #{end_page}." if Love.logger # Handle first page of results if initial_result[list_key].kind_of?(Array) block_given? ? initial_result[list_key].each { |record| yield(record) } : results << initial_result[list_key] sleep(sleep_between_requests) if sleep_between_requests end start_page = query_params[:page].to_i + 1 start_page.upto(end_page) do |page| query_params[:page] = page result = get(append_query(uri, query_params)) if result[list_key].kind_of?(Array) block_given? ? result[list_key].each { |record| yield(record) } : results << result[list_key] sleep(sleep_between_requests) if sleep_between_requests end end results.flatten.map {|r| OpenStruct.new(r)} unless block_given? end
[ "def", "paged_each", "(", "uri", ",", "list_key", ",", "options", "=", "{", "}", ",", "&", "block", ")", "query_params", "=", "{", "}", "query_params", "[", ":since", "]", "=", "options", "[", ":since", "]", ".", "to_date", ".", "to_s", "(", ":db", ")", "if", "options", "[", ":since", "]", "query_params", "[", ":page", "]", "=", "[", "options", "[", ":start_page", "]", ".", "to_i", ",", "1", "]", ".", "max", "rescue", "1", "results", "=", "[", "]", "initial_result", "=", "get", "(", "append_query", "(", "uri", ",", "query_params", ")", ")", "# Determine the amount of pages that is going to be requested.", "max_page", "=", "(", "initial_result", "[", "'total'", "]", ".", "to_f", "/", "initial_result", "[", "'per_page'", "]", ".", "to_f", ")", ".", "ceil", "end_page", "=", "options", "[", ":end_page", "]", ".", "nil?", "?", "max_page", ":", "[", "options", "[", ":end_page", "]", ".", "to_i", ",", "max_page", "]", ".", "min", "# Print out some initial debugging information", "Love", ".", "logger", ".", "debug", "\"Paged requests to #{uri}: #{max_page} total pages, importing #{query_params[:page]} upto #{end_page}.\"", "if", "Love", ".", "logger", "# Handle first page of results", "if", "initial_result", "[", "list_key", "]", ".", "kind_of?", "(", "Array", ")", "block_given?", "?", "initial_result", "[", "list_key", "]", ".", "each", "{", "|", "record", "|", "yield", "(", "record", ")", "}", ":", "results", "<<", "initial_result", "[", "list_key", "]", "sleep", "(", "sleep_between_requests", ")", "if", "sleep_between_requests", "end", "start_page", "=", "query_params", "[", ":page", "]", ".", "to_i", "+", "1", "start_page", ".", "upto", "(", "end_page", ")", "do", "|", "page", "|", "query_params", "[", ":page", "]", "=", "page", "result", "=", "get", "(", "append_query", "(", "uri", ",", "query_params", ")", ")", "if", "result", "[", "list_key", "]", ".", "kind_of?", "(", "Array", ")", "block_given?", "?", "result", "[", "list_key", "]", ".", "each", "{", "|", "record", "|", "yield", "(", "record", ")", "}", ":", "results", "<<", "result", "[", "list_key", "]", "sleep", "(", "sleep_between_requests", ")", "if", "sleep_between_requests", "end", "end", "results", ".", "flatten", ".", "map", "{", "|", "r", "|", "OpenStruct", ".", "new", "(", "r", ")", "}", "unless", "block_given?", "end" ]
Iterates over a collection, issuing multiple requests to get all the paged results. @option options [Date] :since Only include records updated since the provided date. Caution: not supported by all resources. @option options [Integer] :start_page The initial page number to request. @option options [Integer] :end_page The final page number to request.
[ "Iterates", "over", "a", "collection", "issuing", "multiple", "requests", "to", "get", "all", "the", "paged", "results", "." ]
14ed84c2fcc6b008879dd598328ab56d7dd4a053
https://github.com/wvanbergen/love/blob/14ed84c2fcc6b008879dd598328ab56d7dd4a053/lib/love.rb#L310-L340
9,151
IntegraCore/quick_dry
app/controllers/quick_dry/quick_dry_controller.rb
QuickDry.QuickDryController.serialize
def serialize stuff if stuff.is_a? Array or stuff.is_a? ActiveRecord::Relation json = render_to_string json:QuickDryArraySerializer.new(stuff, root:get_model.model_name.route_key ) hash = JSON.parse(json) temp = [] if hash[get_model.model_name.route_key].first.has_key? get_model.model_name.route_key hash[get_model.model_name.route_key].each{|x| temp << x[get_model.model_name.route_key]} hash[get_model.model_name.route_key] = temp return hash.to_json end return json elsif stuff.is_a? get_model end end
ruby
def serialize stuff if stuff.is_a? Array or stuff.is_a? ActiveRecord::Relation json = render_to_string json:QuickDryArraySerializer.new(stuff, root:get_model.model_name.route_key ) hash = JSON.parse(json) temp = [] if hash[get_model.model_name.route_key].first.has_key? get_model.model_name.route_key hash[get_model.model_name.route_key].each{|x| temp << x[get_model.model_name.route_key]} hash[get_model.model_name.route_key] = temp return hash.to_json end return json elsif stuff.is_a? get_model end end
[ "def", "serialize", "stuff", "if", "stuff", ".", "is_a?", "Array", "or", "stuff", ".", "is_a?", "ActiveRecord", "::", "Relation", "json", "=", "render_to_string", "json", ":", "QuickDryArraySerializer", ".", "new", "(", "stuff", ",", "root", ":", "get_model", ".", "model_name", ".", "route_key", ")", "hash", "=", "JSON", ".", "parse", "(", "json", ")", "temp", "=", "[", "]", "if", "hash", "[", "get_model", ".", "model_name", ".", "route_key", "]", ".", "first", ".", "has_key?", "get_model", ".", "model_name", ".", "route_key", "hash", "[", "get_model", ".", "model_name", ".", "route_key", "]", ".", "each", "{", "|", "x", "|", "temp", "<<", "x", "[", "get_model", ".", "model_name", ".", "route_key", "]", "}", "hash", "[", "get_model", ".", "model_name", ".", "route_key", "]", "=", "temp", "return", "hash", ".", "to_json", "end", "return", "json", "elsif", "stuff", ".", "is_a?", "get_model", "end", "end" ]
nasty hack until I can get an answer on the official way to remove the instance root keys in a list
[ "nasty", "hack", "until", "I", "can", "get", "an", "answer", "on", "the", "official", "way", "to", "remove", "the", "instance", "root", "keys", "in", "a", "list" ]
5a488499497dd453dbd0d29d3a0511f1b99a2fdf
https://github.com/IntegraCore/quick_dry/blob/5a488499497dd453dbd0d29d3a0511f1b99a2fdf/app/controllers/quick_dry/quick_dry_controller.rb#L10-L24
9,152
IntegraCore/quick_dry
app/controllers/quick_dry/quick_dry_controller.rb
QuickDry.QuickDryController.get_paged_search_results
def get_paged_search_results(params,user:nil,model:nil) params[:per_page] = 10 if params[:per_page].blank? params[:page] = 1 if params[:page].blank? # a ghetto user check, but for some reason a devise user is not a devise user... user = User.new if user.blank? or !user.class.to_s == User.to_s # get the model in question # there has got to be a better way to do this... I just can't find it # model = params[:controller].blank? ? self.class.name.gsub('Controller','').singularize.constantize : params[:controller].classify.constantize if model.blank? model = request.params[:table_name].classify.constantize unless request.params[:table_name].blank? return nil if model.blank? end # initialize un-paged filtered result set result_set = model.none # create where clauses to filter result to just the customers the current user has access to customer_filter = "" user.customers.each do |cust| if model.column_names.include? "cust_id" customer_filter << "(cust_id = '#{cust.cust_id(true)}') OR " unless cust.cust_id.blank? elsif model.attribute_alias? "cust_id" customer_filter << "(#{model.attribute_alias "cust_id"} = '#{cust.cust_id(true)}') OR " unless cust.cust_id.blank? elsif model.column_names.include? "order_number" customer_filter << "(order_number like '#{cust.prefix}%') OR " unless cust.prefix.blank? elsif model.attribute_alias? "order_number" customer_filter << "(#{model.attribute_alias "order_number"} like '#{cust.prefix}%') OR " unless cust.prefix.blank? end end customer_filter << " (1=0)" # create where clauses for each search parameter if params[:columns].blank? result_set = model.where(customer_filter) else where_clause = "" params[:columns].each do |name, value| where_clause << "(#{model.table_name}.#{name} like '%#{value}%') AND " unless value.blank? end where_clause << " (1=1)" result_set = model.where(customer_filter).where(where_clause) end instances = model.paginate(page: params[:page], per_page: params[:per_page]).merge(result_set).order(updated_at: :desc) return {instances:instances,params:params} end
ruby
def get_paged_search_results(params,user:nil,model:nil) params[:per_page] = 10 if params[:per_page].blank? params[:page] = 1 if params[:page].blank? # a ghetto user check, but for some reason a devise user is not a devise user... user = User.new if user.blank? or !user.class.to_s == User.to_s # get the model in question # there has got to be a better way to do this... I just can't find it # model = params[:controller].blank? ? self.class.name.gsub('Controller','').singularize.constantize : params[:controller].classify.constantize if model.blank? model = request.params[:table_name].classify.constantize unless request.params[:table_name].blank? return nil if model.blank? end # initialize un-paged filtered result set result_set = model.none # create where clauses to filter result to just the customers the current user has access to customer_filter = "" user.customers.each do |cust| if model.column_names.include? "cust_id" customer_filter << "(cust_id = '#{cust.cust_id(true)}') OR " unless cust.cust_id.blank? elsif model.attribute_alias? "cust_id" customer_filter << "(#{model.attribute_alias "cust_id"} = '#{cust.cust_id(true)}') OR " unless cust.cust_id.blank? elsif model.column_names.include? "order_number" customer_filter << "(order_number like '#{cust.prefix}%') OR " unless cust.prefix.blank? elsif model.attribute_alias? "order_number" customer_filter << "(#{model.attribute_alias "order_number"} like '#{cust.prefix}%') OR " unless cust.prefix.blank? end end customer_filter << " (1=0)" # create where clauses for each search parameter if params[:columns].blank? result_set = model.where(customer_filter) else where_clause = "" params[:columns].each do |name, value| where_clause << "(#{model.table_name}.#{name} like '%#{value}%') AND " unless value.blank? end where_clause << " (1=1)" result_set = model.where(customer_filter).where(where_clause) end instances = model.paginate(page: params[:page], per_page: params[:per_page]).merge(result_set).order(updated_at: :desc) return {instances:instances,params:params} end
[ "def", "get_paged_search_results", "(", "params", ",", "user", ":", "nil", ",", "model", ":", "nil", ")", "params", "[", ":per_page", "]", "=", "10", "if", "params", "[", ":per_page", "]", ".", "blank?", "params", "[", ":page", "]", "=", "1", "if", "params", "[", ":page", "]", ".", "blank?", "# a ghetto user check, but for some reason a devise user is not a devise user...", "user", "=", "User", ".", "new", "if", "user", ".", "blank?", "or", "!", "user", ".", "class", ".", "to_s", "==", "User", ".", "to_s", "# get the model in question", "# there has got to be a better way to do this... I just can't find it", "# model = params[:controller].blank? ? self.class.name.gsub('Controller','').singularize.constantize : params[:controller].classify.constantize", "if", "model", ".", "blank?", "model", "=", "request", ".", "params", "[", ":table_name", "]", ".", "classify", ".", "constantize", "unless", "request", ".", "params", "[", ":table_name", "]", ".", "blank?", "return", "nil", "if", "model", ".", "blank?", "end", "# initialize un-paged filtered result set", "result_set", "=", "model", ".", "none", "# create where clauses to filter result to just the customers the current user has access to", "customer_filter", "=", "\"\"", "user", ".", "customers", ".", "each", "do", "|", "cust", "|", "if", "model", ".", "column_names", ".", "include?", "\"cust_id\"", "customer_filter", "<<", "\"(cust_id = '#{cust.cust_id(true)}') OR \"", "unless", "cust", ".", "cust_id", ".", "blank?", "elsif", "model", ".", "attribute_alias?", "\"cust_id\"", "customer_filter", "<<", "\"(#{model.attribute_alias \"cust_id\"} = '#{cust.cust_id(true)}') OR \"", "unless", "cust", ".", "cust_id", ".", "blank?", "elsif", "model", ".", "column_names", ".", "include?", "\"order_number\"", "customer_filter", "<<", "\"(order_number like '#{cust.prefix}%') OR \"", "unless", "cust", ".", "prefix", ".", "blank?", "elsif", "model", ".", "attribute_alias?", "\"order_number\"", "customer_filter", "<<", "\"(#{model.attribute_alias \"order_number\"} like '#{cust.prefix}%') OR \"", "unless", "cust", ".", "prefix", ".", "blank?", "end", "end", "customer_filter", "<<", "\" (1=0)\"", "# create where clauses for each search parameter", "if", "params", "[", ":columns", "]", ".", "blank?", "result_set", "=", "model", ".", "where", "(", "customer_filter", ")", "else", "where_clause", "=", "\"\"", "params", "[", ":columns", "]", ".", "each", "do", "|", "name", ",", "value", "|", "where_clause", "<<", "\"(#{model.table_name}.#{name} like '%#{value}%') AND \"", "unless", "value", ".", "blank?", "end", "where_clause", "<<", "\" (1=1)\"", "result_set", "=", "model", ".", "where", "(", "customer_filter", ")", ".", "where", "(", "where_clause", ")", "end", "instances", "=", "model", ".", "paginate", "(", "page", ":", "params", "[", ":page", "]", ",", "per_page", ":", "params", "[", ":per_page", "]", ")", ".", "merge", "(", "result_set", ")", ".", "order", "(", "updated_at", ":", ":desc", ")", "return", "{", "instances", ":", "instances", ",", "params", ":", "params", "}", "end" ]
Assumes the existance of a User model
[ "Assumes", "the", "existance", "of", "a", "User", "model" ]
5a488499497dd453dbd0d29d3a0511f1b99a2fdf
https://github.com/IntegraCore/quick_dry/blob/5a488499497dd453dbd0d29d3a0511f1b99a2fdf/app/controllers/quick_dry/quick_dry_controller.rb#L176-L223
9,153
0000marcell/simple_commander
lib/simple_commander/user_interaction.rb
SimpleCommander.UI.converse
def converse(prompt, responses = {}) i, commands = 0, responses.map { |_key, value| value.inspect }.join(',') statement = responses.inject '' do |inner_statement, (key, value)| inner_statement << ( (i += 1) == 1 ? %(if response is "#{value}" then\n) : %(else if response is "#{value}" then\n) ) << %(do shell script "echo '#{key}'"\n) end applescript( %( tell application "SpeechRecognitionServer" set response to listen for {#{commands}} with prompt "#{prompt}" #{statement} end if end tell ), ).strip.to_sym end
ruby
def converse(prompt, responses = {}) i, commands = 0, responses.map { |_key, value| value.inspect }.join(',') statement = responses.inject '' do |inner_statement, (key, value)| inner_statement << ( (i += 1) == 1 ? %(if response is "#{value}" then\n) : %(else if response is "#{value}" then\n) ) << %(do shell script "echo '#{key}'"\n) end applescript( %( tell application "SpeechRecognitionServer" set response to listen for {#{commands}} with prompt "#{prompt}" #{statement} end if end tell ), ).strip.to_sym end
[ "def", "converse", "(", "prompt", ",", "responses", "=", "{", "}", ")", "i", ",", "commands", "=", "0", ",", "responses", ".", "map", "{", "|", "_key", ",", "value", "|", "value", ".", "inspect", "}", ".", "join", "(", "','", ")", "statement", "=", "responses", ".", "inject", "''", "do", "|", "inner_statement", ",", "(", "key", ",", "value", ")", "|", "inner_statement", "<<", "(", "(", "i", "+=", "1", ")", "==", "1", "?", "%(if response is \"#{value}\" then\\n)", ":", "%(else if response is \"#{value}\" then\\n)", ")", "<<", "%(do shell script \"echo '#{key}'\"\\n)", "end", "applescript", "(", "%(\n tell application \"SpeechRecognitionServer\"\n set response to listen for {#{commands}} with prompt \"#{prompt}\"\n #{statement}\n end if\n end tell\n )", ",", ")", ".", "strip", ".", "to_sym", "end" ]
Converse with speech recognition. Currently a "poorman's" DSL to utilize applescript and the MacOS speech recognition server. === Examples case converse 'What is the best food?', :cookies => 'Cookies', :unknown => 'Nothing' when :cookies speak 'o.m.g. you are awesome!' else case converse 'That is lame, shall I convince you cookies are the best?', :yes => 'Ok', :no => 'No', :maybe => 'Maybe another time' when :yes speak 'Well you see, cookies are just fantastic.' else speak 'Ok then, bye.' end end === Notes * MacOS only
[ "Converse", "with", "speech", "recognition", "." ]
337c2e0d9926c643ce131b1a1ebd3740241e4424
https://github.com/0000marcell/simple_commander/blob/337c2e0d9926c643ce131b1a1ebd3740241e4424/lib/simple_commander/user_interaction.rb#L166-L186
9,154
davidan1981/rails-identity
app/helpers/rails_identity/application_helper.rb
RailsIdentity.ApplicationHelper.authorized_for?
def authorized_for?(obj) logger.debug("Checking to see if authorized to access object") if @auth_user.nil? # :nocov: return false # :nocov: elsif @auth_user.role >= Roles::ADMIN return true elsif obj.is_a? User return obj == @auth_user else return obj.try(:user) == @auth_user end end
ruby
def authorized_for?(obj) logger.debug("Checking to see if authorized to access object") if @auth_user.nil? # :nocov: return false # :nocov: elsif @auth_user.role >= Roles::ADMIN return true elsif obj.is_a? User return obj == @auth_user else return obj.try(:user) == @auth_user end end
[ "def", "authorized_for?", "(", "obj", ")", "logger", ".", "debug", "(", "\"Checking to see if authorized to access object\"", ")", "if", "@auth_user", ".", "nil?", "# :nocov:", "return", "false", "# :nocov:", "elsif", "@auth_user", ".", "role", ">=", "Roles", "::", "ADMIN", "return", "true", "elsif", "obj", ".", "is_a?", "User", "return", "obj", "==", "@auth_user", "else", "return", "obj", ".", "try", "(", ":user", ")", "==", "@auth_user", "end", "end" ]
Determines if the user is authorized for the object. The user must be either the creator of the object or must be an admin or above.
[ "Determines", "if", "the", "user", "is", "authorized", "for", "the", "object", ".", "The", "user", "must", "be", "either", "the", "creator", "of", "the", "object", "or", "must", "be", "an", "admin", "or", "above", "." ]
12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0
https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/helpers/rails_identity/application_helper.rb#L124-L137
9,155
davidan1981/rails-identity
app/helpers/rails_identity/application_helper.rb
RailsIdentity.ApplicationHelper.get_token_payload
def get_token_payload(token) # Attempt to decode without verifying. May raise DecodeError. decoded = JWT.decode token, nil, false payload = decoded[0] # At this point, we know that the token is not expired and # well formatted. Find out if the payload is well defined. if payload.nil? # :nocov: logger.error("Token payload is nil: #{token}") raise UNAUTHORIZED_ERROR, "Invalid token" # :nocov: end return payload rescue JWT::DecodeError => e logger.error("Token decode error: #{e.message}") raise UNAUTHORIZED_ERROR, "Invalid token" end
ruby
def get_token_payload(token) # Attempt to decode without verifying. May raise DecodeError. decoded = JWT.decode token, nil, false payload = decoded[0] # At this point, we know that the token is not expired and # well formatted. Find out if the payload is well defined. if payload.nil? # :nocov: logger.error("Token payload is nil: #{token}") raise UNAUTHORIZED_ERROR, "Invalid token" # :nocov: end return payload rescue JWT::DecodeError => e logger.error("Token decode error: #{e.message}") raise UNAUTHORIZED_ERROR, "Invalid token" end
[ "def", "get_token_payload", "(", "token", ")", "# Attempt to decode without verifying. May raise DecodeError.", "decoded", "=", "JWT", ".", "decode", "token", ",", "nil", ",", "false", "payload", "=", "decoded", "[", "0", "]", "# At this point, we know that the token is not expired and", "# well formatted. Find out if the payload is well defined.", "if", "payload", ".", "nil?", "# :nocov:", "logger", ".", "error", "(", "\"Token payload is nil: #{token}\"", ")", "raise", "UNAUTHORIZED_ERROR", ",", "\"Invalid token\"", "# :nocov:", "end", "return", "payload", "rescue", "JWT", "::", "DecodeError", "=>", "e", "logger", ".", "error", "(", "\"Token decode error: #{e.message}\"", ")", "raise", "UNAUTHORIZED_ERROR", ",", "\"Invalid token\"", "end" ]
Attempts to retrieve the payload encoded in the token. It checks if the token is "valid" according to JWT definition and not expired. A UNAUTHORIZED_ERROR is raised if token cannot be decoded.
[ "Attempts", "to", "retrieve", "the", "payload", "encoded", "in", "the", "token", ".", "It", "checks", "if", "the", "token", "is", "valid", "according", "to", "JWT", "definition", "and", "not", "expired", "." ]
12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0
https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/helpers/rails_identity/application_helper.rb#L169-L189
9,156
davidan1981/rails-identity
app/helpers/rails_identity/application_helper.rb
RailsIdentity.ApplicationHelper.verify_token
def verify_token(token) logger.debug("Verifying token: #{token}") # First get the payload of the token. This will also verify whether # or not the token is welformed. payload = get_token_payload(token) # Next, the payload should define user UUID and session UUID. user_uuid = payload["user_uuid"] session_uuid = payload["session_uuid"] if user_uuid.nil? || session_uuid.nil? logger.error("User or session is not specified") raise UNAUTHORIZED_ERROR, "Invalid token" end logger.debug("Token well defined: #{token}") # But, the user UUID and session UUID better be valid too. That is, # they must be real user and session, and the session must belong to # the user. auth_user = User.find_by_uuid(user_uuid) if auth_user.nil? # :nocov: logger.error("Specified user doesn't exist #{user_uuid}") raise UNAUTHORIZED_ERROR, "Invalid token" # :nocov: end auth_session = Session.find_by_uuid(session_uuid) if auth_session.nil? || auth_session.user != auth_user logger.error("Specified session doesn't exist #{session_uuid}") raise UNAUTHORIZED_ERROR, "Invalid token" end # Finally, decode the token using the secret. Also check expiration # here too. JWT.decode token, auth_session.secret, true logger.debug("Token well formatted and verified. Set cache.") # Return the corresponding session return auth_session rescue JWT::DecodeError => e logger.error(e.message) raise UNAUTHORIZED_ERROR, "Invalid token" end
ruby
def verify_token(token) logger.debug("Verifying token: #{token}") # First get the payload of the token. This will also verify whether # or not the token is welformed. payload = get_token_payload(token) # Next, the payload should define user UUID and session UUID. user_uuid = payload["user_uuid"] session_uuid = payload["session_uuid"] if user_uuid.nil? || session_uuid.nil? logger.error("User or session is not specified") raise UNAUTHORIZED_ERROR, "Invalid token" end logger.debug("Token well defined: #{token}") # But, the user UUID and session UUID better be valid too. That is, # they must be real user and session, and the session must belong to # the user. auth_user = User.find_by_uuid(user_uuid) if auth_user.nil? # :nocov: logger.error("Specified user doesn't exist #{user_uuid}") raise UNAUTHORIZED_ERROR, "Invalid token" # :nocov: end auth_session = Session.find_by_uuid(session_uuid) if auth_session.nil? || auth_session.user != auth_user logger.error("Specified session doesn't exist #{session_uuid}") raise UNAUTHORIZED_ERROR, "Invalid token" end # Finally, decode the token using the secret. Also check expiration # here too. JWT.decode token, auth_session.secret, true logger.debug("Token well formatted and verified. Set cache.") # Return the corresponding session return auth_session rescue JWT::DecodeError => e logger.error(e.message) raise UNAUTHORIZED_ERROR, "Invalid token" end
[ "def", "verify_token", "(", "token", ")", "logger", ".", "debug", "(", "\"Verifying token: #{token}\"", ")", "# First get the payload of the token. This will also verify whether", "# or not the token is welformed.", "payload", "=", "get_token_payload", "(", "token", ")", "# Next, the payload should define user UUID and session UUID.", "user_uuid", "=", "payload", "[", "\"user_uuid\"", "]", "session_uuid", "=", "payload", "[", "\"session_uuid\"", "]", "if", "user_uuid", ".", "nil?", "||", "session_uuid", ".", "nil?", "logger", ".", "error", "(", "\"User or session is not specified\"", ")", "raise", "UNAUTHORIZED_ERROR", ",", "\"Invalid token\"", "end", "logger", ".", "debug", "(", "\"Token well defined: #{token}\"", ")", "# But, the user UUID and session UUID better be valid too. That is,", "# they must be real user and session, and the session must belong to", "# the user.", "auth_user", "=", "User", ".", "find_by_uuid", "(", "user_uuid", ")", "if", "auth_user", ".", "nil?", "# :nocov:", "logger", ".", "error", "(", "\"Specified user doesn't exist #{user_uuid}\"", ")", "raise", "UNAUTHORIZED_ERROR", ",", "\"Invalid token\"", "# :nocov:", "end", "auth_session", "=", "Session", ".", "find_by_uuid", "(", "session_uuid", ")", "if", "auth_session", ".", "nil?", "||", "auth_session", ".", "user", "!=", "auth_user", "logger", ".", "error", "(", "\"Specified session doesn't exist #{session_uuid}\"", ")", "raise", "UNAUTHORIZED_ERROR", ",", "\"Invalid token\"", "end", "# Finally, decode the token using the secret. Also check expiration", "# here too.", "JWT", ".", "decode", "token", ",", "auth_session", ".", "secret", ",", "true", "logger", ".", "debug", "(", "\"Token well formatted and verified. Set cache.\"", ")", "# Return the corresponding session", "return", "auth_session", "rescue", "JWT", "::", "DecodeError", "=>", "e", "logger", ".", "error", "(", "e", ".", "message", ")", "raise", "UNAUTHORIZED_ERROR", ",", "\"Invalid token\"", "end" ]
Truly verifies the token and its payload. It ensures the user and session specified in the token payload are indeed valid. The required role is also checked. A UNAUTHORIZED_ERROR is thrown for all cases where token is invalid.
[ "Truly", "verifies", "the", "token", "and", "its", "payload", ".", "It", "ensures", "the", "user", "and", "session", "specified", "in", "the", "token", "payload", "are", "indeed", "valid", ".", "The", "required", "role", "is", "also", "checked", "." ]
12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0
https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/helpers/rails_identity/application_helper.rb#L199-L242
9,157
davidan1981/rails-identity
app/helpers/rails_identity/application_helper.rb
RailsIdentity.ApplicationHelper.get_token
def get_token(required_role: Roles::PUBLIC) token = params[:token] # Look up the cache. If present, use it and skip the verification. # Use token itself (and not a session UUID) as part of the key so # it can be considered *verified*. @auth_session = Cache.get(kind: :session, token: token) # Cache miss. So proceed to verify the token and get user and # session data from database. Then set the cache for later. if @auth_session.nil? @auth_session = verify_token(token) @auth_session.role # NOTE: no-op Cache.set({kind: :session, token: token}, @auth_session) end # Obtained session may not have enough permission. Check here. if @auth_session.role < required_role logger.error("Not enough permission (role: #{@auth_session.role})") raise UNAUTHORIZED_ERROR, "Invalid token" end @auth_user = @auth_session.user @token = @auth_session.token return true end
ruby
def get_token(required_role: Roles::PUBLIC) token = params[:token] # Look up the cache. If present, use it and skip the verification. # Use token itself (and not a session UUID) as part of the key so # it can be considered *verified*. @auth_session = Cache.get(kind: :session, token: token) # Cache miss. So proceed to verify the token and get user and # session data from database. Then set the cache for later. if @auth_session.nil? @auth_session = verify_token(token) @auth_session.role # NOTE: no-op Cache.set({kind: :session, token: token}, @auth_session) end # Obtained session may not have enough permission. Check here. if @auth_session.role < required_role logger.error("Not enough permission (role: #{@auth_session.role})") raise UNAUTHORIZED_ERROR, "Invalid token" end @auth_user = @auth_session.user @token = @auth_session.token return true end
[ "def", "get_token", "(", "required_role", ":", "Roles", "::", "PUBLIC", ")", "token", "=", "params", "[", ":token", "]", "# Look up the cache. If present, use it and skip the verification.", "# Use token itself (and not a session UUID) as part of the key so", "# it can be considered *verified*.", "@auth_session", "=", "Cache", ".", "get", "(", "kind", ":", ":session", ",", "token", ":", "token", ")", "# Cache miss. So proceed to verify the token and get user and", "# session data from database. Then set the cache for later.", "if", "@auth_session", ".", "nil?", "@auth_session", "=", "verify_token", "(", "token", ")", "@auth_session", ".", "role", "# NOTE: no-op", "Cache", ".", "set", "(", "{", "kind", ":", ":session", ",", "token", ":", "token", "}", ",", "@auth_session", ")", "end", "# Obtained session may not have enough permission. Check here.", "if", "@auth_session", ".", "role", "<", "required_role", "logger", ".", "error", "(", "\"Not enough permission (role: #{@auth_session.role})\"", ")", "raise", "UNAUTHORIZED_ERROR", ",", "\"Invalid token\"", "end", "@auth_user", "=", "@auth_session", ".", "user", "@token", "=", "@auth_session", ".", "token", "return", "true", "end" ]
Attempt to get a token for the session. Token must be specified in query string or part of the JSON object. Raises a UNAUTHORIZED_ERROR if cached session has less role than what's required.
[ "Attempt", "to", "get", "a", "token", "for", "the", "session", ".", "Token", "must", "be", "specified", "in", "query", "string", "or", "part", "of", "the", "JSON", "object", "." ]
12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0
https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/helpers/rails_identity/application_helper.rb#L251-L275
9,158
davidan1981/rails-identity
app/helpers/rails_identity/application_helper.rb
RailsIdentity.ApplicationHelper.get_api_key
def get_api_key(required_role: Roles::PUBLIC) api_key = params[:api_key] if api_key.nil? # This case is not likely, but as a safeguard in case migration # has not gone well. # :nocov: raise UNAUTHORIZED_ERROR, "Invalid api key" # :nocov: end auth_user = User.find_by_api_key(api_key) if auth_user.nil? || auth_user.role < required_role raise UNAUTHORIZED_ERROR, "Invalid api key" end @auth_user = auth_user @auth_session = nil @token = nil return true end
ruby
def get_api_key(required_role: Roles::PUBLIC) api_key = params[:api_key] if api_key.nil? # This case is not likely, but as a safeguard in case migration # has not gone well. # :nocov: raise UNAUTHORIZED_ERROR, "Invalid api key" # :nocov: end auth_user = User.find_by_api_key(api_key) if auth_user.nil? || auth_user.role < required_role raise UNAUTHORIZED_ERROR, "Invalid api key" end @auth_user = auth_user @auth_session = nil @token = nil return true end
[ "def", "get_api_key", "(", "required_role", ":", "Roles", "::", "PUBLIC", ")", "api_key", "=", "params", "[", ":api_key", "]", "if", "api_key", ".", "nil?", "# This case is not likely, but as a safeguard in case migration", "# has not gone well.", "# :nocov:", "raise", "UNAUTHORIZED_ERROR", ",", "\"Invalid api key\"", "# :nocov:", "end", "auth_user", "=", "User", ".", "find_by_api_key", "(", "api_key", ")", "if", "auth_user", ".", "nil?", "||", "auth_user", ".", "role", "<", "required_role", "raise", "UNAUTHORIZED_ERROR", ",", "\"Invalid api key\"", "end", "@auth_user", "=", "auth_user", "@auth_session", "=", "nil", "@token", "=", "nil", "return", "true", "end" ]
Get API key from the request. Raises a UNAUTHORIZED_ERROR if API key is not valid (or not provided).
[ "Get", "API", "key", "from", "the", "request", "." ]
12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0
https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/helpers/rails_identity/application_helper.rb#L283-L300
9,159
davidan1981/rails-identity
app/helpers/rails_identity/application_helper.rb
RailsIdentity.ApplicationHelper.get_auth
def get_auth(required_role: Roles::USER) if params[:token] get_token(required_role: required_role) else get_api_key(required_role: required_role) end end
ruby
def get_auth(required_role: Roles::USER) if params[:token] get_token(required_role: required_role) else get_api_key(required_role: required_role) end end
[ "def", "get_auth", "(", "required_role", ":", "Roles", "::", "USER", ")", "if", "params", "[", ":token", "]", "get_token", "(", "required_role", ":", "required_role", ")", "else", "get_api_key", "(", "required_role", ":", "required_role", ")", "end", "end" ]
Get auth data from the request. The token takes the precedence.
[ "Get", "auth", "data", "from", "the", "request", ".", "The", "token", "takes", "the", "precedence", "." ]
12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0
https://github.com/davidan1981/rails-identity/blob/12b0d6fd85bd9019d3be7f4fd79fbca39f824ca0/app/helpers/rails_identity/application_helper.rb#L305-L311
9,160
jeremyvdw/disqussion
lib/disqussion/client/reactions.rb
Disqussion.Reactions.details
def details(*args) options = args.last.is_a?(Hash) ? args.pop : {} if args.length == 2 options.merge!(:reaction => args[0]) options.merge!(:forum => args[1]) response = get('reactions/details', options) else puts "#{Kernel.caller.first}: Reactions.details expects 2 arguments: reaction and forum" end end
ruby
def details(*args) options = args.last.is_a?(Hash) ? args.pop : {} if args.length == 2 options.merge!(:reaction => args[0]) options.merge!(:forum => args[1]) response = get('reactions/details', options) else puts "#{Kernel.caller.first}: Reactions.details expects 2 arguments: reaction and forum" end end
[ "def", "details", "(", "*", "args", ")", "options", "=", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "args", ".", "pop", ":", "{", "}", "if", "args", ".", "length", "==", "2", "options", ".", "merge!", "(", ":reaction", "=>", "args", "[", "0", "]", ")", "options", ".", "merge!", "(", ":forum", "=>", "args", "[", "1", "]", ")", "response", "=", "get", "(", "'reactions/details'", ",", "options", ")", "else", "puts", "\"#{Kernel.caller.first}: Reactions.details expects 2 arguments: reaction and forum\"", "end", "end" ]
Returns reaction details @accessibility: public key, secret key @methods: GET @format: json, jsonp @authenticated: false @limited: false @param reaction [Integer] Looks up a reaction by ID. @param forum [String] Looks up a forum by ID (aka shortname). @return [Hashie::Rash] Reaction of the forum. @example Message for post ID 12345678 Disqussion::Client.reactions.detail(12345678,"Hello") @see: http://disqus.com/api/3.0/reactions/details.json
[ "Returns", "reaction", "details" ]
5ad1b0325b7630daf41eb59fc8acbcb785cbc387
https://github.com/jeremyvdw/disqussion/blob/5ad1b0325b7630daf41eb59fc8acbcb785cbc387/lib/disqussion/client/reactions.rb#L16-L25
9,161
biola/biola-logs
lib/biola_logs/controller_extensions.rb
BiolaLogs.ControllerExtensions.append_info_to_payload
def append_info_to_payload(payload) super payload[:session_id] = request.session_options[:id] payload[:uuid] = request.uuid payload[:host] = request.host end
ruby
def append_info_to_payload(payload) super payload[:session_id] = request.session_options[:id] payload[:uuid] = request.uuid payload[:host] = request.host end
[ "def", "append_info_to_payload", "(", "payload", ")", "super", "payload", "[", ":session_id", "]", "=", "request", ".", "session_options", "[", ":id", "]", "payload", "[", ":uuid", "]", "=", "request", ".", "uuid", "payload", "[", ":host", "]", "=", "request", ".", "host", "end" ]
Custom attributes for lograge logging
[ "Custom", "attributes", "for", "lograge", "logging" ]
614a0b9181c0c647ccf82d4fcb44d07fc2ab1829
https://github.com/biola/biola-logs/blob/614a0b9181c0c647ccf82d4fcb44d07fc2ab1829/lib/biola_logs/controller_extensions.rb#L14-L19
9,162
irvingwashington/gem_footprint_analyzer
lib/gem_footprint_analyzer/child_context.rb
GemFootprintAnalyzer.ChildContext.start
def start RequireSpy.spy_require(transport) error = try_require(require_string) return transport.done_and_wait_for_ack unless error transport.exit_with_error(error) exit(1) end
ruby
def start RequireSpy.spy_require(transport) error = try_require(require_string) return transport.done_and_wait_for_ack unless error transport.exit_with_error(error) exit(1) end
[ "def", "start", "RequireSpy", ".", "spy_require", "(", "transport", ")", "error", "=", "try_require", "(", "require_string", ")", "return", "transport", ".", "done_and_wait_for_ack", "unless", "error", "transport", ".", "exit_with_error", "(", "error", ")", "exit", "(", "1", ")", "end" ]
Prints the process pid, so it can be grabbed by the supervisor process, inits tranport fifos and requires requested libraries. Installs the require-spying code and starts requiring
[ "Prints", "the", "process", "pid", "so", "it", "can", "be", "grabbed", "by", "the", "supervisor", "process", "inits", "tranport", "fifos", "and", "requires", "requested", "libraries", ".", "Installs", "the", "require", "-", "spying", "code", "and", "starts", "requiring" ]
19a8892f6baaeb16b1b166144c4f73852396220c
https://github.com/irvingwashington/gem_footprint_analyzer/blob/19a8892f6baaeb16b1b166144c4f73852396220c/lib/gem_footprint_analyzer/child_context.rb#L22-L29
9,163
mattmccray/gumdrop
lib/gumdrop/content.rb
Gumdrop.SpecialContentList.find
def find(uri) _try_variations_of(uri) do |path| content= get path return [content] unless content.nil? end unless uri.nil? [] end
ruby
def find(uri) _try_variations_of(uri) do |path| content= get path return [content] unless content.nil? end unless uri.nil? [] end
[ "def", "find", "(", "uri", ")", "_try_variations_of", "(", "uri", ")", "do", "|", "path", "|", "content", "=", "get", "path", "return", "[", "content", "]", "unless", "content", ".", "nil?", "end", "unless", "uri", ".", "nil?", "[", "]", "end" ]
Find isn't fuzzy for Special Content. It looks for full uri or the uri's basename, optionally tacking on @ext
[ "Find", "isn", "t", "fuzzy", "for", "Special", "Content", ".", "It", "looks", "for", "full", "uri", "or", "the", "uri", "s", "basename", "optionally", "tacking", "on" ]
7c0998675dbc65e6c7fa0cd580ea0fc3167394fd
https://github.com/mattmccray/gumdrop/blob/7c0998675dbc65e6c7fa0cd580ea0fc3167394fd/lib/gumdrop/content.rb#L277-L283
9,164
chetan/bixby-common
lib/bixby-common/api/json_request.rb
Bixby.JsonRequest.to_s
def to_s(include_params=true) s = [] s << "JsonRequest:#{self.object_id}" s << " operation: #{self.operation}" s << " params: " + MultiJson.dump(self.params) if include_params s.join("\n") end
ruby
def to_s(include_params=true) s = [] s << "JsonRequest:#{self.object_id}" s << " operation: #{self.operation}" s << " params: " + MultiJson.dump(self.params) if include_params s.join("\n") end
[ "def", "to_s", "(", "include_params", "=", "true", ")", "s", "=", "[", "]", "s", "<<", "\"JsonRequest:#{self.object_id}\"", "s", "<<", "\" operation: #{self.operation}\"", "s", "<<", "\" params: \"", "+", "MultiJson", ".", "dump", "(", "self", ".", "params", ")", "if", "include_params", "s", ".", "join", "(", "\"\\n\"", ")", "end" ]
Create a new JsonRequest @param [String] operation Name of operation @param [Array] params Array of parameters; must ve valid JSON types Stringify, useful for debugging @param [Boolean] include_params whether or not to include params in the output (default: true) @return [String]
[ "Create", "a", "new", "JsonRequest" ]
3fb8829987b115fc53ec820d97a20b4a8c49b4a2
https://github.com/chetan/bixby-common/blob/3fb8829987b115fc53ec820d97a20b4a8c49b4a2/lib/bixby-common/api/json_request.rb#L29-L35
9,165
zacscodingclub/balancing_act
lib/balancing_act/server.rb
BalancingAct.Server.valid_params?
def valid_params?(name, size) return raise TypeError.new("A 'name' should be a string") if name.class != String return raise TypeError.new("A 'size' should be an integer") if size.class != Integer true end
ruby
def valid_params?(name, size) return raise TypeError.new("A 'name' should be a string") if name.class != String return raise TypeError.new("A 'size' should be an integer") if size.class != Integer true end
[ "def", "valid_params?", "(", "name", ",", "size", ")", "return", "raise", "TypeError", ".", "new", "(", "\"A 'name' should be a string\"", ")", "if", "name", ".", "class", "!=", "String", "return", "raise", "TypeError", ".", "new", "(", "\"A 'size' should be an integer\"", ")", "if", "size", ".", "class", "!=", "Integer", "true", "end" ]
Validates the params by type. Could add in additional validations in this method depending on requirements. Raises exception with invalid types with early return or returns true if params are valid
[ "Validates", "the", "params", "by", "type", ".", "Could", "add", "in", "additional", "validations", "in", "this", "method", "depending", "on", "requirements", ".", "Raises", "exception", "with", "invalid", "types", "with", "early", "return", "or", "returns", "true", "if", "params", "are", "valid" ]
5a8b86d03b1218192cef23c14533d1dd9264bdc1
https://github.com/zacscodingclub/balancing_act/blob/5a8b86d03b1218192cef23c14533d1dd9264bdc1/lib/balancing_act/server.rb#L17-L22
9,166
rgeyer/rs_user_policy
lib/rs_user_policy/audit_log.rb
RsUserPolicy.AuditLog.add_entry
def add_entry(email, account, action, changes) @audit_log[email] = [] unless audit_log[email] @audit_log[email] << { :account => account, :action => action, :changes => changes } end
ruby
def add_entry(email, account, action, changes) @audit_log[email] = [] unless audit_log[email] @audit_log[email] << { :account => account, :action => action, :changes => changes } end
[ "def", "add_entry", "(", "email", ",", "account", ",", "action", ",", "changes", ")", "@audit_log", "[", "email", "]", "=", "[", "]", "unless", "audit_log", "[", "email", "]", "@audit_log", "[", "email", "]", "<<", "{", ":account", "=>", "account", ",", ":action", "=>", "action", ",", ":changes", "=>", "changes", "}", "end" ]
Initializes a new AuditLog @param [Hash] options A hash of options that impact the audit log filename. @option options [String] :timestamp The timestamp to append to the filename @option options [Bool] :dry_run A boolean indicating if this is a dry run @option options [String] :audit_dir The directory where the audit log should be created Adds a new entry to the audit log @param [String] email The email address of the user impacted by the change @param [String] account The account name impacted by the change @param [String] action The action performed. Expected options are ['update_permissions', 'created', 'deleted'] @param [String] changes A free form description of the changes
[ "Initializes", "a", "new", "AuditLog" ]
bae3355f1471cc7d28de7992c5d5f4ac39fff68b
https://github.com/rgeyer/rs_user_policy/blob/bae3355f1471cc7d28de7992c5d5f4ac39fff68b/lib/rs_user_policy/audit_log.rb#L57-L64
9,167
mikemackintosh/slackdraft
lib/slackdraft/base.rb
Slackdraft.Base.send!
def send! # Send the request request = HTTParty.post(self.target, :body => { :payload => generate_payload.to_json }) unless request.code.eql? 200 false end true end
ruby
def send! # Send the request request = HTTParty.post(self.target, :body => { :payload => generate_payload.to_json }) unless request.code.eql? 200 false end true end
[ "def", "send!", "# Send the request", "request", "=", "HTTParty", ".", "post", "(", "self", ".", "target", ",", ":body", "=>", "{", ":payload", "=>", "generate_payload", ".", "to_json", "}", ")", "unless", "request", ".", "code", ".", "eql?", "200", "false", "end", "true", "end" ]
Send the message!
[ "Send", "the", "message!" ]
4025fe370f468750fdf5a0dc9741871bca897c0a
https://github.com/mikemackintosh/slackdraft/blob/4025fe370f468750fdf5a0dc9741871bca897c0a/lib/slackdraft/base.rb#L22-L35
9,168
culturecode/templatr
app/models/templatr/template.rb
Templatr.Template.common_fields_attributes=
def common_fields_attributes=(nested_attributes) nested_attributes.values.each do |attributes| common_field = common_fields.find {|field| field.id.to_s == attributes[:id] && attributes[:id].present? } || common_fields.build assign_to_or_mark_for_destruction(common_field, attributes, true, {}) end end
ruby
def common_fields_attributes=(nested_attributes) nested_attributes.values.each do |attributes| common_field = common_fields.find {|field| field.id.to_s == attributes[:id] && attributes[:id].present? } || common_fields.build assign_to_or_mark_for_destruction(common_field, attributes, true, {}) end end
[ "def", "common_fields_attributes", "=", "(", "nested_attributes", ")", "nested_attributes", ".", "values", ".", "each", "do", "|", "attributes", "|", "common_field", "=", "common_fields", ".", "find", "{", "|", "field", "|", "field", ".", "id", ".", "to_s", "==", "attributes", "[", ":id", "]", "&&", "attributes", "[", ":id", "]", ".", "present?", "}", "||", "common_fields", ".", "build", "assign_to_or_mark_for_destruction", "(", "common_field", ",", "attributes", ",", "true", ",", "{", "}", ")", "end", "end" ]
Ensure all nested attributes for common fields get saved as common fields, and not as template fields
[ "Ensure", "all", "nested", "attributes", "for", "common", "fields", "get", "saved", "as", "common", "fields", "and", "not", "as", "template", "fields" ]
0bffb930736b4339fb8a9e8adc080404dc6860d8
https://github.com/culturecode/templatr/blob/0bffb930736b4339fb8a9e8adc080404dc6860d8/app/models/templatr/template.rb#L25-L30
9,169
conversation/chrome_debugger
lib/chrome_debugger/document.rb
ChromeDebugger.Document.start_time
def start_time @start_time ||= @events.select { |event| event.is_a?(RequestWillBeSent) }.select { |event| event.request['url'] == @url }.map { |event| event.timestamp }.first end
ruby
def start_time @start_time ||= @events.select { |event| event.is_a?(RequestWillBeSent) }.select { |event| event.request['url'] == @url }.map { |event| event.timestamp }.first end
[ "def", "start_time", "@start_time", "||=", "@events", ".", "select", "{", "|", "event", "|", "event", ".", "is_a?", "(", "RequestWillBeSent", ")", "}", ".", "select", "{", "|", "event", "|", "event", ".", "request", "[", "'url'", "]", "==", "@url", "}", ".", "map", "{", "|", "event", "|", "event", ".", "timestamp", "}", ".", "first", "end" ]
The seconds since epoch that the request for this document started
[ "The", "seconds", "since", "epoch", "that", "the", "request", "for", "this", "document", "started" ]
b1b0c6a7bff94e8f4967aefc39c7e043582f549e
https://github.com/conversation/chrome_debugger/blob/b1b0c6a7bff94e8f4967aefc39c7e043582f549e/lib/chrome_debugger/document.rb#L20-L28
9,170
conversation/chrome_debugger
lib/chrome_debugger/document.rb
ChromeDebugger.Document.encoded_bytes
def encoded_bytes(resource_type) @events.select {|e| e.is_a?(ResponseReceived) && e.resource_type == resource_type }.map { |e| e.request_id }.map { |request_id| data_received_for_request(request_id) }.flatten.inject(0) { |bytes_sum, n| bytes_sum + n.encoded_data_length } end
ruby
def encoded_bytes(resource_type) @events.select {|e| e.is_a?(ResponseReceived) && e.resource_type == resource_type }.map { |e| e.request_id }.map { |request_id| data_received_for_request(request_id) }.flatten.inject(0) { |bytes_sum, n| bytes_sum + n.encoded_data_length } end
[ "def", "encoded_bytes", "(", "resource_type", ")", "@events", ".", "select", "{", "|", "e", "|", "e", ".", "is_a?", "(", "ResponseReceived", ")", "&&", "e", ".", "resource_type", "==", "resource_type", "}", ".", "map", "{", "|", "e", "|", "e", ".", "request_id", "}", ".", "map", "{", "|", "request_id", "|", "data_received_for_request", "(", "request_id", ")", "}", ".", "flatten", ".", "inject", "(", "0", ")", "{", "|", "bytes_sum", ",", "n", "|", "bytes_sum", "+", "n", ".", "encoded_data_length", "}", "end" ]
The number of bytes downloaded for a particular resource type. If the resource was gzipped during transfer then the gzipped size is reported. The HTTP headers for the response are included in the byte count. Possible resource types: 'Document','Script', 'Image', 'Stylesheet', 'Other'.
[ "The", "number", "of", "bytes", "downloaded", "for", "a", "particular", "resource", "type", ".", "If", "the", "resource", "was", "gzipped", "during", "transfer", "then", "the", "gzipped", "size", "is", "reported", "." ]
b1b0c6a7bff94e8f4967aefc39c7e043582f549e
https://github.com/conversation/chrome_debugger/blob/b1b0c6a7bff94e8f4967aefc39c7e043582f549e/lib/chrome_debugger/document.rb#L60-L68
9,171
conversation/chrome_debugger
lib/chrome_debugger/document.rb
ChromeDebugger.Document.bytes
def bytes(resource_type) @events.select {|e| e.is_a?(ResponseReceived) && e.resource_type == resource_type }.map { |e| e.request_id }.map { |request_id| data_received_for_request(request_id) }.flatten.inject(0) { |bytes_sum, n| bytes_sum + n.data_length } end
ruby
def bytes(resource_type) @events.select {|e| e.is_a?(ResponseReceived) && e.resource_type == resource_type }.map { |e| e.request_id }.map { |request_id| data_received_for_request(request_id) }.flatten.inject(0) { |bytes_sum, n| bytes_sum + n.data_length } end
[ "def", "bytes", "(", "resource_type", ")", "@events", ".", "select", "{", "|", "e", "|", "e", ".", "is_a?", "(", "ResponseReceived", ")", "&&", "e", ".", "resource_type", "==", "resource_type", "}", ".", "map", "{", "|", "e", "|", "e", ".", "request_id", "}", ".", "map", "{", "|", "request_id", "|", "data_received_for_request", "(", "request_id", ")", "}", ".", "flatten", ".", "inject", "(", "0", ")", "{", "|", "bytes_sum", ",", "n", "|", "bytes_sum", "+", "n", ".", "data_length", "}", "end" ]
The number of bytes downloaded for a particular resource type. If the resource was gzipped during transfer then the uncompressed size is reported. The HTTP headers for the response are NOT included in the byte count. Possible resource types: 'Document','Script', 'Image', 'Stylesheet', 'Other'.
[ "The", "number", "of", "bytes", "downloaded", "for", "a", "particular", "resource", "type", ".", "If", "the", "resource", "was", "gzipped", "during", "transfer", "then", "the", "uncompressed", "size", "is", "reported", "." ]
b1b0c6a7bff94e8f4967aefc39c7e043582f549e
https://github.com/conversation/chrome_debugger/blob/b1b0c6a7bff94e8f4967aefc39c7e043582f549e/lib/chrome_debugger/document.rb#L79-L87
9,172
conversation/chrome_debugger
lib/chrome_debugger/document.rb
ChromeDebugger.Document.request_count_by_resource
def request_count_by_resource(resource_type) @events.select {|n| n.is_a?(ResponseReceived) && n.resource_type == resource_type }.size end
ruby
def request_count_by_resource(resource_type) @events.select {|n| n.is_a?(ResponseReceived) && n.resource_type == resource_type }.size end
[ "def", "request_count_by_resource", "(", "resource_type", ")", "@events", ".", "select", "{", "|", "n", "|", "n", ".", "is_a?", "(", "ResponseReceived", ")", "&&", "n", ".", "resource_type", "==", "resource_type", "}", ".", "size", "end" ]
the number of network requests of a particular resource type that were required to load this document Possible resource types: 'Document', 'Script', 'Image', 'Stylesheet', 'Other'.
[ "the", "number", "of", "network", "requests", "of", "a", "particular", "resource", "type", "that", "were", "required", "to", "load", "this", "document" ]
b1b0c6a7bff94e8f4967aefc39c7e043582f549e
https://github.com/conversation/chrome_debugger/blob/b1b0c6a7bff94e8f4967aefc39c7e043582f549e/lib/chrome_debugger/document.rb#L103-L107
9,173
noted/scholar
lib/scholar/search.rb
Scholar.Search.to_hash
def to_hash hash = {} instance_variables.each do |v| hash[v.to_s[1..-1].to_sym] = instance_variable_get(v) end hash[:results].each do |c| hash[:results][hash[:results].index(c)] = c.to_hash end hash end
ruby
def to_hash hash = {} instance_variables.each do |v| hash[v.to_s[1..-1].to_sym] = instance_variable_get(v) end hash[:results].each do |c| hash[:results][hash[:results].index(c)] = c.to_hash end hash end
[ "def", "to_hash", "hash", "=", "{", "}", "instance_variables", ".", "each", "do", "|", "v", "|", "hash", "[", "v", ".", "to_s", "[", "1", "..", "-", "1", "]", ".", "to_sym", "]", "=", "instance_variable_get", "(", "v", ")", "end", "hash", "[", ":results", "]", ".", "each", "do", "|", "c", "|", "hash", "[", ":results", "]", "[", "hash", "[", ":results", "]", ".", "index", "(", "c", ")", "]", "=", "c", ".", "to_hash", "end", "hash", "end" ]
Searches for sources in Google Books. ==== Attributes * +query+ - The search term. Return as hash.
[ "Searches", "for", "sources", "in", "Google", "Books", "." ]
2bfface9d90307d7d3cecfa756f921087407d394
https://github.com/noted/scholar/blob/2bfface9d90307d7d3cecfa756f921087407d394/lib/scholar/search.rb#L39-L51
9,174
betaworks/slack-bot-manager
lib/slack-bot-manager/client/commands.rb
SlackBotManager.Commands.on_close
def on_close(data, *args) options = args.extract_options! options[:code] ||= (data && data.code) || '1000' disconnect fail SlackBotManager::ConnectionRateLimited if %w(1008 429).include?(options[:code].to_s) end
ruby
def on_close(data, *args) options = args.extract_options! options[:code] ||= (data && data.code) || '1000' disconnect fail SlackBotManager::ConnectionRateLimited if %w(1008 429).include?(options[:code].to_s) end
[ "def", "on_close", "(", "data", ",", "*", "args", ")", "options", "=", "args", ".", "extract_options!", "options", "[", ":code", "]", "||=", "(", "data", "&&", "data", ".", "code", ")", "||", "'1000'", "disconnect", "fail", "SlackBotManager", "::", "ConnectionRateLimited", "if", "%w(", "1008", "429", ")", ".", "include?", "(", "options", "[", ":code", "]", ".", "to_s", ")", "end" ]
Handle when connection gets closed
[ "Handle", "when", "connection", "gets", "closed" ]
cb59bd1c80abd3ede0520017708891486f733e40
https://github.com/betaworks/slack-bot-manager/blob/cb59bd1c80abd3ede0520017708891486f733e40/lib/slack-bot-manager/client/commands.rb#L4-L10
9,175
hexorx/oxmlk
lib/oxmlk.rb
OxMlk.ClassMethods.ox_attr
def ox_attr(name,o={},&block) new_attr = Attr.new(name, o.reverse_merge(:tag_proc => @tag_proc),&block) @ox_attrs << new_attr ox_accessor new_attr.accessor end
ruby
def ox_attr(name,o={},&block) new_attr = Attr.new(name, o.reverse_merge(:tag_proc => @tag_proc),&block) @ox_attrs << new_attr ox_accessor new_attr.accessor end
[ "def", "ox_attr", "(", "name", ",", "o", "=", "{", "}", ",", "&", "block", ")", "new_attr", "=", "Attr", ".", "new", "(", "name", ",", "o", ".", "reverse_merge", "(", ":tag_proc", "=>", "@tag_proc", ")", ",", "block", ")", "@ox_attrs", "<<", "new_attr", "ox_accessor", "new_attr", ".", "accessor", "end" ]
Declares a reference to a certain xml attribute. == Sym Option [sym] Symbol representing the name of the accessor === Default naming This is what it will use to lookup the attribute if a name isn't defined in :from. For example: ox_attr :bob ox_attr :pony are equivalent to: ox_attr :bob, :from => 'bob' ox_attr :pony, :from => 'pony' === Boolean attributes If the name ends in a ?, OxMlk will attempt to coerce the value to true or false, with true, yes, t and 1 mapping to true and false, no, f and 0 mapping to false, as shown below: ox_elem :desirable? ox_attr :bizzare?, :from => 'BIZZARE' x = #from_xml(%{ <object BIZZARE="1"> <desirable>False</desirable> </object> }) x.desirable? => false x.bizzare? => true When a block is provided the value will be passed to the block where unexpected values can be handled. If no block is provided the unexpected value will be returned. #from_xml(%{ <object BIZZARE="Dunno"\> }).desirable? => "Dunno" ox_attr :bizzare? do |val| val.upcase end #from_xml(%{ <object BIZZARE="Dunno"\> }).strange? => "DUNNO" == Blocks You may also pass a block which manipulates the associated parsed value. class Muffins include OxMlk ox_attr(:count, :from => 'bakers_dozens') {|val| val.to_i * 13 } end Blocks are always passed the value after being manipulated by the :as option and are the last thing to manipulate the XML. This is different than the ox_elem annotation that is passed an Array. == Options === :as ==== Basic Types Allows you to specify one of several basic types to return the value as. For example ox_elem :count, :as => Integer is equivalent to: ox_elem(:count) {|val| Integer(val) unless val.empty?} Such block shorthands for Integer, Float, String, Symbol and Time are currently available. If an Array is passed each Type in the array will be applied to the value in order. === :from The name by which the xml value will be found in XML. Default is sym.
[ "Declares", "a", "reference", "to", "a", "certain", "xml", "attribute", "." ]
bf4be00ece9b13a3357d8eb324e2a571d2715f79
https://github.com/hexorx/oxmlk/blob/bf4be00ece9b13a3357d8eb324e2a571d2715f79/lib/oxmlk.rb#L123-L127
9,176
hexorx/oxmlk
lib/oxmlk.rb
OxMlk.ClassMethods.ox_elem
def ox_elem(name,o={},&block) new_elem = Elem.new(name, o.reverse_merge(:tag_proc => @tag_proc),&block) @ox_elems << new_elem ox_accessor new_elem.accessor end
ruby
def ox_elem(name,o={},&block) new_elem = Elem.new(name, o.reverse_merge(:tag_proc => @tag_proc),&block) @ox_elems << new_elem ox_accessor new_elem.accessor end
[ "def", "ox_elem", "(", "name", ",", "o", "=", "{", "}", ",", "&", "block", ")", "new_elem", "=", "Elem", ".", "new", "(", "name", ",", "o", ".", "reverse_merge", "(", ":tag_proc", "=>", "@tag_proc", ")", ",", "block", ")", "@ox_elems", "<<", "new_elem", "ox_accessor", "new_elem", ".", "accessor", "end" ]
Declares a reference to a certain xml element or a typed collection of elements. == Sym Option [sym] Symbol representing the name of the accessor. === Default naming This name will be the default node searched for, if no other is declared. For example: ox_elem :bob ox_elem :pony are equivalent to: ox_elem :bob, :from => 'bob' ox_elem :pony, :from => 'pony' === Boolean attributes If the name ends in a ?, OxMlk will attempt to coerce the value to true or false, with true, yes, t and 1 mapping to true and false, no, f and 0 mapping to false, as shown below: ox_elem :desirable? ox_attr :bizzare?, :from => 'BIZZARE' x = #from_xml(%{ <object BIZZARE="1"> <desirable>False</desirable> </object> }) x.desirable? => false x.bizzare? => true When a block is provided the value will be passed to the block where unexpected values can be handled. If no block is provided the unexpected value will be returned. #from_xml(%{ <object> <desirable>Dunno</desirable> </object> }).desirable? => "Dunno" ox_elem :strange? do |val| val.upcase end #from_xml(%{ <object> <strange>Dunno</strange> </object> }).strange? => "DUNNO" == Blocks You may also pass a block which manipulates the associated parsed value. class Muffins include OxMlk ox_elem(:count, :from => 'bakers_dozens') {|val| val.first.to_i * 13 } end Blocks are always passed an Array and are the last thing to manipulate the XML. The array will include all elements already manipulated by anything passed to the :as option. If the :as option is an Array and no block is passed then the Array is returned unmodified. If the :as option is nil or is not an Array then only the first element is == Options === :as ==== Basic Types Allows you to specify one of several basic types to return the value as. For example ox_elem :count, :as => Integer is equivalent to: ox_elem(:count) {|val| Integer(val.first) unless val.first.empty?} Such block shorthands for Integer, Float, String, Symbol and Time are currently available. To reference many elements, put the desired type in a literal array. e.g.: ox_elem :counts, :as => [Integer] Even an array of text nodes can be specified with :as => [] ox_elem :quotes, :as => [] === Other OxMlk Classes Declares an accessor that represents another OxMlk class as child XML element (one-to-one or composition) or array of child elements (one-to-many or aggregation) of this type. Default is one-to-one. For one-to-many, simply pass the class as the only element in an array. You can also put several OxMlk classes in an Array that will act like a polymorphic one-to-many association. Composition example: <book> <publisher> <name>Pragmatic Bookshelf</name> </publisher> </book> Can be mapped using the following code: class Book include OxMlk ox_elem :publisher, :as => Publisher end Aggregation example: <library> <books> <book/> <book/> </books> </library> Can be mapped using the following code: class Library include OxMlk ox_elem :books, :as => [Book], :in => 'books' end If you don't have the <books> tag to wrap around the list of <book> tags: <library> <name>Ruby books</name> <book/> <book/> </library> You can skip the wrapper argument: ox_elem :books, :as => [Book] ==== Hash Unlike ROXML, OxMlk doesn't do anything special for hashes. However OxMlk applies :as to each element and the block once to the Array of elements. This means OxMlk can support setting hashes but it is more of a manual process. I am looking for a easier method but for now here are a few examples: ===== Hash of element contents For xml such as this: <dictionary> <definition> <word/> <meaning/> </definition> <definition> <word/> <meaning/> </definition> </dictionary> This is actually one of the more complex ones. It uses the :raw keyword to pass the block an array of LibXML::XML::Nodes ox_elem(:definitions, :from => 'definition', :as => [:raw]) do |vals| Hash[*vals.map {}|val| [val.search('word').content,val.search('meaning').content]}.flatten] end ===== Hash of :content For xml such as this: <dictionary> <definition word="quaquaversally">adjective: (of a geological formation) sloping downward from the center in all directions.</definition> <definition word="tergiversate">To use evasions or ambiguities; equivocate.</definition> </dictionary> This one can also be accomplished with the :raw keyword and a fancy block. ox_elem(:definitions, :from => 'definition', :as => [:raw]) {|x| Hash[*x.map {|val| [val['word'],val.content] }.flatten]} ===== Hash of :name For xml such as this: <dictionary> <quaquaversally>adjective: (of a geological formation) sloping downward from the center in all directions.</quaquaversally> <tergiversate>To use evasions or ambiguities; equivocate.</tergiversate> </dictionary> This one requires some fancy xpath in :from to grab all the elements ox_elem(:definitions, :from => './*', :as => [:raw]) {|x| Hash[*x.map {|val| [val.name,val.content] }.flatten]} === :from The name by which the xml value will be found in XML. Default is sym. This value may also include XPath notation. ==== :from => :content When :from is set to :content, this refers to the content of the current node, rather than a sub-node. It is equivalent to :from => '.' Example: class Contributor ox_elem :name, :from => :content ox_attr :role end To map: <contributor role="editor">James Wick</contributor> === :in An optional name of a wrapping tag for this XML accessor. This can include other xpath values, which will be joined with :from with a '/'
[ "Declares", "a", "reference", "to", "a", "certain", "xml", "element", "or", "a", "typed", "collection", "of", "elements", "." ]
bf4be00ece9b13a3357d8eb324e2a571d2715f79
https://github.com/hexorx/oxmlk/blob/bf4be00ece9b13a3357d8eb324e2a571d2715f79/lib/oxmlk.rb#L335-L339
9,177
hexorx/oxmlk
lib/oxmlk.rb
OxMlk.ClassMethods.ox_tag
def ox_tag(tag=nil,&block) raise 'you can only set tag or a block, not both.' if tag && block @base_tag ||= self.to_s.split('::').last @ox_tag ||= case tag when String tag when Proc, Symbol, nil @tag_proc = (block || tag || :to_s).to_proc @tag_proc.call(@base_tag) rescue tag.to_s else raise 'you passed something weird' end end
ruby
def ox_tag(tag=nil,&block) raise 'you can only set tag or a block, not both.' if tag && block @base_tag ||= self.to_s.split('::').last @ox_tag ||= case tag when String tag when Proc, Symbol, nil @tag_proc = (block || tag || :to_s).to_proc @tag_proc.call(@base_tag) rescue tag.to_s else raise 'you passed something weird' end end
[ "def", "ox_tag", "(", "tag", "=", "nil", ",", "&", "block", ")", "raise", "'you can only set tag or a block, not both.'", "if", "tag", "&&", "block", "@base_tag", "||=", "self", ".", "to_s", ".", "split", "(", "'::'", ")", ".", "last", "@ox_tag", "||=", "case", "tag", "when", "String", "tag", "when", "Proc", ",", "Symbol", ",", "nil", "@tag_proc", "=", "(", "block", "||", "tag", "||", ":to_s", ")", ".", "to_proc", "@tag_proc", ".", "call", "(", "@base_tag", ")", "rescue", "tag", ".", "to_s", "else", "raise", "'you passed something weird'", "end", "end" ]
Sets the name of the XML element that represents this class. Use this to override the default camelcase class name. Example: class BookWithPublisher ox_tag 'book' end Without the ox_tag annotation, the XML mapped tag would have been 'BookWithPublisher'. Most xml documents have a consistent naming convention, for example, the node and and attribute names might appear in CamelCase. ox_tag enables you to adapt the oxmlk default names for this object to suit this convention. For example, if I had a document like so: <XmlDoc> <MyPreciousData /> <MoreToSee /> </XmlDoc> Then I could access it's contents by defining the following class: class XmlDoc include OxMlk ox_tag :camelcase ox_elem :my_precious_data ox_elem :more_to_see end You may supply a block or any #to_proc-able object as the argument, and it will be called against the default node and attribute names before searching the document. Here are some example declaration: ox_tag :upcase ox_tag &:camelcase ox_tag {|val| val.gsub('_', '').downcase } See ActiveSupport::CoreExtensions::String::Inflections for more prepackaged formats
[ "Sets", "the", "name", "of", "the", "XML", "element", "that", "represents", "this", "class", ".", "Use", "this", "to", "override", "the", "default", "camelcase", "class", "name", "." ]
bf4be00ece9b13a3357d8eb324e2a571d2715f79
https://github.com/hexorx/oxmlk/blob/bf4be00ece9b13a3357d8eb324e2a571d2715f79/lib/oxmlk.rb#L380-L393
9,178
hexorx/oxmlk
lib/oxmlk.rb
OxMlk.ClassMethods.from_xml
def from_xml(data) xml = XML::Node.from(data) raise 'invalid XML' unless xml.name == ox_tag returning new do |ox| (ox_attrs + ox_elems).each {|e| ox.send(e.setter,e.from_xml(xml))} ox.send(:after_parse) if ox.respond_to?(:after_parse) end end
ruby
def from_xml(data) xml = XML::Node.from(data) raise 'invalid XML' unless xml.name == ox_tag returning new do |ox| (ox_attrs + ox_elems).each {|e| ox.send(e.setter,e.from_xml(xml))} ox.send(:after_parse) if ox.respond_to?(:after_parse) end end
[ "def", "from_xml", "(", "data", ")", "xml", "=", "XML", "::", "Node", ".", "from", "(", "data", ")", "raise", "'invalid XML'", "unless", "xml", ".", "name", "==", "ox_tag", "returning", "new", "do", "|", "ox", "|", "(", "ox_attrs", "+", "ox_elems", ")", ".", "each", "{", "|", "e", "|", "ox", ".", "send", "(", "e", ".", "setter", ",", "e", ".", "from_xml", "(", "xml", ")", ")", "}", "ox", ".", "send", "(", ":after_parse", ")", "if", "ox", ".", "respond_to?", "(", ":after_parse", ")", "end", "end" ]
Returns a new instance from XML @param [XML::Document,XML::Node,File,Pathname,URI,String] data The xml data used to create a new instance. @return New instance generated from xml data passed in. Attr and Elem definitions are used to translate the xml to new object.
[ "Returns", "a", "new", "instance", "from", "XML" ]
bf4be00ece9b13a3357d8eb324e2a571d2715f79
https://github.com/hexorx/oxmlk/blob/bf4be00ece9b13a3357d8eb324e2a571d2715f79/lib/oxmlk.rb#L405-L413
9,179
hexorx/oxmlk
lib/oxmlk.rb
OxMlk.ClassMethods.to_xml
def to_xml(data) ox = XML::Node.new(ox_tag) wrappers = {} ox_elems.each do |elem| if elem.in wrappers[elem.in] ||= XML::Node.new elem.in elem.to_xml(data).each {|e| wrappers[elem.in] << e} else elem.to_xml(data).each {|e| ox << e} end end wrappers.each {|k,v| ox << v} ox_attrs.each do |a| val = data.send(a.accessor).to_s ox[a.tag]= val if val.present? end ox end
ruby
def to_xml(data) ox = XML::Node.new(ox_tag) wrappers = {} ox_elems.each do |elem| if elem.in wrappers[elem.in] ||= XML::Node.new elem.in elem.to_xml(data).each {|e| wrappers[elem.in] << e} else elem.to_xml(data).each {|e| ox << e} end end wrappers.each {|k,v| ox << v} ox_attrs.each do |a| val = data.send(a.accessor).to_s ox[a.tag]= val if val.present? end ox end
[ "def", "to_xml", "(", "data", ")", "ox", "=", "XML", "::", "Node", ".", "new", "(", "ox_tag", ")", "wrappers", "=", "{", "}", "ox_elems", ".", "each", "do", "|", "elem", "|", "if", "elem", ".", "in", "wrappers", "[", "elem", ".", "in", "]", "||=", "XML", "::", "Node", ".", "new", "elem", ".", "in", "elem", ".", "to_xml", "(", "data", ")", ".", "each", "{", "|", "e", "|", "wrappers", "[", "elem", ".", "in", "]", "<<", "e", "}", "else", "elem", ".", "to_xml", "(", "data", ")", ".", "each", "{", "|", "e", "|", "ox", "<<", "e", "}", "end", "end", "wrappers", ".", "each", "{", "|", "k", ",", "v", "|", "ox", "<<", "v", "}", "ox_attrs", ".", "each", "do", "|", "a", "|", "val", "=", "data", ".", "send", "(", "a", ".", "accessor", ")", ".", "to_s", "ox", "[", "a", ".", "tag", "]", "=", "val", "if", "val", ".", "present?", "end", "ox", "end" ]
Returns XML generated from an instance based on Attr & Elem definitions. @param [Object] data An instance used to populate XML @return [XML::Node] Generated XML::Node
[ "Returns", "XML", "generated", "from", "an", "instance", "based", "on", "Attr", "&", "Elem", "definitions", "." ]
bf4be00ece9b13a3357d8eb324e2a571d2715f79
https://github.com/hexorx/oxmlk/blob/bf4be00ece9b13a3357d8eb324e2a571d2715f79/lib/oxmlk.rb#L429-L450
9,180
urso/rb_prob
lib/prob.rb
Probably.Distribution.pick
def pick tst = rand sum = 0 @map.each do |value, prob| sum += prob return value,prob if tst < sum end return nil end
ruby
def pick tst = rand sum = 0 @map.each do |value, prob| sum += prob return value,prob if tst < sum end return nil end
[ "def", "pick", "tst", "=", "rand", "sum", "=", "0", "@map", ".", "each", "do", "|", "value", ",", "prob", "|", "sum", "+=", "prob", "return", "value", ",", "prob", "if", "tst", "<", "sum", "end", "return", "nil", "end" ]
randomly pick a key-value with respect to its probability in given distribution
[ "randomly", "pick", "a", "key", "-", "value", "with", "respect", "to", "its", "probability", "in", "given", "distribution" ]
f7c448a15a40c26ce9a4424151a0f4942e544389
https://github.com/urso/rb_prob/blob/f7c448a15a40c26ce9a4424151a0f4942e544389/lib/prob.rb#L115-L123
9,181
urso/rb_prob
lib/prob.rb
Probably.Distribution.variance
def variance expected = self.expectation @map.reduce(0) {|sum, (value,p)| tmp = (value.to_f - expectation) sum + tmp * tmp * p } end
ruby
def variance expected = self.expectation @map.reduce(0) {|sum, (value,p)| tmp = (value.to_f - expectation) sum + tmp * tmp * p } end
[ "def", "variance", "expected", "=", "self", ".", "expectation", "@map", ".", "reduce", "(", "0", ")", "{", "|", "sum", ",", "(", "value", ",", "p", ")", "|", "tmp", "=", "(", "value", ".", "to_f", "-", "expectation", ")", "sum", "+", "tmp", "*", "tmp", "*", "p", "}", "end" ]
computes variance given that keys in distribution are numeric
[ "computes", "variance", "given", "that", "keys", "in", "distribution", "are", "numeric" ]
f7c448a15a40c26ce9a4424151a0f4942e544389
https://github.com/urso/rb_prob/blob/f7c448a15a40c26ce9a4424151a0f4942e544389/lib/prob.rb#L214-L220
9,182
benschwarz/smoke
lib/smoke/origin.rb
Smoke.Origin.transform
def transform(*keys) raise ArgumentError, "requires a block" unless block_given? keys.each do |key| items.each do |item| item[key] = yield(item[key]) || item[key] end end end
ruby
def transform(*keys) raise ArgumentError, "requires a block" unless block_given? keys.each do |key| items.each do |item| item[key] = yield(item[key]) || item[key] end end end
[ "def", "transform", "(", "*", "keys", ")", "raise", "ArgumentError", ",", "\"requires a block\"", "unless", "block_given?", "keys", ".", "each", "do", "|", "key", "|", "items", ".", "each", "do", "|", "item", "|", "item", "[", "key", "]", "=", "yield", "(", "item", "[", "key", "]", ")", "||", "item", "[", "key", "]", "end", "end", "end" ]
Transform must be used inside an `emit` block. It can be used to alter named keys within the item set Usage: emit do transform :name, :description do |name| name.gsub(/\302/, "") end end In quasi-english: The result of the block is returned and set to each of the :name and :description keys in the result set.
[ "Transform", "must", "be", "used", "inside", "an", "emit", "block", ".", "It", "can", "be", "used", "to", "alter", "named", "keys", "within", "the", "item", "set" ]
b229e0cc975d6420a3b7505b42f38b8ba1126d54
https://github.com/benschwarz/smoke/blob/b229e0cc975d6420a3b7505b42f38b8ba1126d54/lib/smoke/origin.rb#L87-L94
9,183
benschwarz/smoke
lib/smoke/origin.rb
Smoke.Origin.method_missing
def method_missing(symbol, *args, &block) ivar = "@#{symbol}" if args.empty? return instance_variable_get(ivar) || super else instance_variable_set(ivar, args.pop) end return self end
ruby
def method_missing(symbol, *args, &block) ivar = "@#{symbol}" if args.empty? return instance_variable_get(ivar) || super else instance_variable_set(ivar, args.pop) end return self end
[ "def", "method_missing", "(", "symbol", ",", "*", "args", ",", "&", "block", ")", "ivar", "=", "\"@#{symbol}\"", "if", "args", ".", "empty?", "return", "instance_variable_get", "(", "ivar", ")", "||", "super", "else", "instance_variable_set", "(", "ivar", ",", "args", ".", "pop", ")", "end", "return", "self", "end" ]
Used to store or retreive variables that are used to query services. Usage: Smoke.twitter.username("benschwarz").output As you can see, the method is chainable, many properties can be set at once, although it may be cleaner to use the method argument method: Demo: Smoke.twitter(:username => "benschwarz").output
[ "Used", "to", "store", "or", "retreive", "variables", "that", "are", "used", "to", "query", "services", "." ]
b229e0cc975d6420a3b7505b42f38b8ba1126d54
https://github.com/benschwarz/smoke/blob/b229e0cc975d6420a3b7505b42f38b8ba1126d54/lib/smoke/origin.rb#L145-L155
9,184
benschwarz/smoke
lib/smoke/origin.rb
Smoke.Origin.sort
def sort(key) @items = @items.sort_by{|i| i[key] } rescue NoMethodError => e Smoke.log.info "You're trying to sort by \"#{key}\" but it does not exist in your item set" end
ruby
def sort(key) @items = @items.sort_by{|i| i[key] } rescue NoMethodError => e Smoke.log.info "You're trying to sort by \"#{key}\" but it does not exist in your item set" end
[ "def", "sort", "(", "key", ")", "@items", "=", "@items", ".", "sort_by", "{", "|", "i", "|", "i", "[", "key", "]", "}", "rescue", "NoMethodError", "=>", "e", "Smoke", ".", "log", ".", "info", "\"You're trying to sort by \\\"#{key}\\\" but it does not exist in your item set\"", "end" ]
Re-sort items by a particular key Sort must be used inside an `emit` block.
[ "Re", "-", "sort", "items", "by", "a", "particular", "key", "Sort", "must", "be", "used", "inside", "an", "emit", "block", "." ]
b229e0cc975d6420a3b7505b42f38b8ba1126d54
https://github.com/benschwarz/smoke/blob/b229e0cc975d6420a3b7505b42f38b8ba1126d54/lib/smoke/origin.rb#L159-L163
9,185
benschwarz/smoke
lib/smoke/origin.rb
Smoke.Origin.keep
def keep(key, matcher) @items.reject! {|i| (i[key] =~ matcher) ? false : true } end
ruby
def keep(key, matcher) @items.reject! {|i| (i[key] =~ matcher) ? false : true } end
[ "def", "keep", "(", "key", ",", "matcher", ")", "@items", ".", "reject!", "{", "|", "i", "|", "(", "i", "[", "key", "]", "=~", "matcher", ")", "?", "false", ":", "true", "}", "end" ]
Keep items that match the regex Usage (block, during initialization): Smoke.yql(:ruby) do ... emit do keep(:title, /tuesday/i) end end Keep must be used inside an `emit` block.
[ "Keep", "items", "that", "match", "the", "regex" ]
b229e0cc975d6420a3b7505b42f38b8ba1126d54
https://github.com/benschwarz/smoke/blob/b229e0cc975d6420a3b7505b42f38b8ba1126d54/lib/smoke/origin.rb#L192-L194
9,186
benschwarz/smoke
lib/smoke/origin.rb
Smoke.Origin.discard
def discard(key, matcher) @items.reject! {|i| (i[key] =~ matcher) ? true : false } end
ruby
def discard(key, matcher) @items.reject! {|i| (i[key] =~ matcher) ? true : false } end
[ "def", "discard", "(", "key", ",", "matcher", ")", "@items", ".", "reject!", "{", "|", "i", "|", "(", "i", "[", "key", "]", "=~", "matcher", ")", "?", "true", ":", "false", "}", "end" ]
Discard items that do not match the regex Usage (block, during initialization): Smoke.yql(:ruby) do ... emit do discard(:title, /tuesday/i) end end Discard must be used inside an `emit` block.
[ "Discard", "items", "that", "do", "not", "match", "the", "regex" ]
b229e0cc975d6420a3b7505b42f38b8ba1126d54
https://github.com/benschwarz/smoke/blob/b229e0cc975d6420a3b7505b42f38b8ba1126d54/lib/smoke/origin.rb#L206-L208
9,187
madx/roy
lib/roy/context.rb
Roy.Context.prepare!
def prepare!(env) @env = env @request = Rack::Request.new(env) @response = Rack::Response.new @headers = @response.header @params = @request.GET.merge(@request.POST) @params.default_proc = proc do |hash, key| hash[key.to_s] if Symbol === key end end
ruby
def prepare!(env) @env = env @request = Rack::Request.new(env) @response = Rack::Response.new @headers = @response.header @params = @request.GET.merge(@request.POST) @params.default_proc = proc do |hash, key| hash[key.to_s] if Symbol === key end end
[ "def", "prepare!", "(", "env", ")", "@env", "=", "env", "@request", "=", "Rack", "::", "Request", ".", "new", "(", "env", ")", "@response", "=", "Rack", "::", "Response", ".", "new", "@headers", "=", "@response", ".", "header", "@params", "=", "@request", ".", "GET", ".", "merge", "(", "@request", ".", "POST", ")", "@params", ".", "default_proc", "=", "proc", "do", "|", "hash", ",", "key", "|", "hash", "[", "key", ".", "to_s", "]", "if", "Symbol", "===", "key", "end", "end" ]
Creates a new Context object. @param app the context's application Initializes the attributes based on an environment. @param env the environment to use
[ "Creates", "a", "new", "Context", "object", "." ]
7f9d96b146c15c7b2d3f4019a8a2078475983186
https://github.com/madx/roy/blob/7f9d96b146c15c7b2d3f4019a8a2078475983186/lib/roy/context.rb#L43-L52
9,188
mikemackintosh/slackdraft
lib/slackdraft/attachment.rb
Slackdraft.Attachment.generate_attachment
def generate_attachment payload = {} payload[:fallback] = self.fallback unless self.fallback.nil? payload[:color] = self.color unless self.color.nil? payload[:pretext] = self.pretext unless self.pretext.nil? payload[:author_name] = self.author_name unless self.author_name.nil? payload[:author_link] = self.author_link unless self.author_link.nil? payload[:author_icon] = self.author_icon unless self.author_icon.nil? payload[:title] = self.title unless self.title.nil? payload[:title_link] = self.title_link unless self.title_link.nil? payload[:text] = self.message unless self.message.nil? unless self.fields.nil? payload[:fields] = self.fields if self.fields.length > 0 end payload[:image_url] = self.image_url unless self.image_url.nil? payload end
ruby
def generate_attachment payload = {} payload[:fallback] = self.fallback unless self.fallback.nil? payload[:color] = self.color unless self.color.nil? payload[:pretext] = self.pretext unless self.pretext.nil? payload[:author_name] = self.author_name unless self.author_name.nil? payload[:author_link] = self.author_link unless self.author_link.nil? payload[:author_icon] = self.author_icon unless self.author_icon.nil? payload[:title] = self.title unless self.title.nil? payload[:title_link] = self.title_link unless self.title_link.nil? payload[:text] = self.message unless self.message.nil? unless self.fields.nil? payload[:fields] = self.fields if self.fields.length > 0 end payload[:image_url] = self.image_url unless self.image_url.nil? payload end
[ "def", "generate_attachment", "payload", "=", "{", "}", "payload", "[", ":fallback", "]", "=", "self", ".", "fallback", "unless", "self", ".", "fallback", ".", "nil?", "payload", "[", ":color", "]", "=", "self", ".", "color", "unless", "self", ".", "color", ".", "nil?", "payload", "[", ":pretext", "]", "=", "self", ".", "pretext", "unless", "self", ".", "pretext", ".", "nil?", "payload", "[", ":author_name", "]", "=", "self", ".", "author_name", "unless", "self", ".", "author_name", ".", "nil?", "payload", "[", ":author_link", "]", "=", "self", ".", "author_link", "unless", "self", ".", "author_link", ".", "nil?", "payload", "[", ":author_icon", "]", "=", "self", ".", "author_icon", "unless", "self", ".", "author_icon", ".", "nil?", "payload", "[", ":title", "]", "=", "self", ".", "title", "unless", "self", ".", "title", ".", "nil?", "payload", "[", ":title_link", "]", "=", "self", ".", "title_link", "unless", "self", ".", "title_link", ".", "nil?", "payload", "[", ":text", "]", "=", "self", ".", "message", "unless", "self", ".", "message", ".", "nil?", "unless", "self", ".", "fields", ".", "nil?", "payload", "[", ":fields", "]", "=", "self", ".", "fields", "if", "self", ".", "fields", ".", "length", ">", "0", "end", "payload", "[", ":image_url", "]", "=", "self", ".", "image_url", "unless", "self", ".", "image_url", ".", "nil?", "payload", "end" ]
Generate the payload for slack attachments
[ "Generate", "the", "payload", "for", "slack", "attachments" ]
4025fe370f468750fdf5a0dc9741871bca897c0a
https://github.com/mikemackintosh/slackdraft/blob/4025fe370f468750fdf5a0dc9741871bca897c0a/lib/slackdraft/attachment.rb#L34-L53
9,189
Deradon/Rdcpu16
lib/dcpu16/screen.rb
DCPU16.Screen.frame
def frame return @frame if @frame chars = [] # 4 corners chars << Char.new(0x23, @x_offset - 1, @y_offset - 1) # TopLeft chars << Char.new(0x23, @x_offset + @width, @y_offset - 1) # TopRight chars << Char.new(0x23, @x_offset - 1, @y_offset + @height) # BottomLeft chars << Char.new(0x23, @x_offset + @width, @y_offset + @height) # BottomRight # horiz @width.times { |x| chars << Char.new(0x2d, x + @x_offset, @y_offset - 1) } @width.times { |x| chars << Char.new(0x2d, x + @x_offset, @y_offset + @height) } # vertical @height.times { |y| chars << Char.new(0x7c, @x_offset - 1, y + @y_offset) } @height.times { |y| chars << Char.new(0x7c, @x_offset + @width, y + @y_offset) } @frame = "" @frame << chars.join end
ruby
def frame return @frame if @frame chars = [] # 4 corners chars << Char.new(0x23, @x_offset - 1, @y_offset - 1) # TopLeft chars << Char.new(0x23, @x_offset + @width, @y_offset - 1) # TopRight chars << Char.new(0x23, @x_offset - 1, @y_offset + @height) # BottomLeft chars << Char.new(0x23, @x_offset + @width, @y_offset + @height) # BottomRight # horiz @width.times { |x| chars << Char.new(0x2d, x + @x_offset, @y_offset - 1) } @width.times { |x| chars << Char.new(0x2d, x + @x_offset, @y_offset + @height) } # vertical @height.times { |y| chars << Char.new(0x7c, @x_offset - 1, y + @y_offset) } @height.times { |y| chars << Char.new(0x7c, @x_offset + @width, y + @y_offset) } @frame = "" @frame << chars.join end
[ "def", "frame", "return", "@frame", "if", "@frame", "chars", "=", "[", "]", "# 4 corners", "chars", "<<", "Char", ".", "new", "(", "0x23", ",", "@x_offset", "-", "1", ",", "@y_offset", "-", "1", ")", "# TopLeft", "chars", "<<", "Char", ".", "new", "(", "0x23", ",", "@x_offset", "+", "@width", ",", "@y_offset", "-", "1", ")", "# TopRight", "chars", "<<", "Char", ".", "new", "(", "0x23", ",", "@x_offset", "-", "1", ",", "@y_offset", "+", "@height", ")", "# BottomLeft", "chars", "<<", "Char", ".", "new", "(", "0x23", ",", "@x_offset", "+", "@width", ",", "@y_offset", "+", "@height", ")", "# BottomRight", "# horiz", "@width", ".", "times", "{", "|", "x", "|", "chars", "<<", "Char", ".", "new", "(", "0x2d", ",", "x", "+", "@x_offset", ",", "@y_offset", "-", "1", ")", "}", "@width", ".", "times", "{", "|", "x", "|", "chars", "<<", "Char", ".", "new", "(", "0x2d", ",", "x", "+", "@x_offset", ",", "@y_offset", "+", "@height", ")", "}", "# vertical", "@height", ".", "times", "{", "|", "y", "|", "chars", "<<", "Char", ".", "new", "(", "0x7c", ",", "@x_offset", "-", "1", ",", "y", "+", "@y_offset", ")", "}", "@height", ".", "times", "{", "|", "y", "|", "chars", "<<", "Char", ".", "new", "(", "0x7c", ",", "@x_offset", "+", "@width", ",", "y", "+", "@y_offset", ")", "}", "@frame", "=", "\"\"", "@frame", "<<", "chars", ".", "join", "end" ]
Use a fancy border around console
[ "Use", "a", "fancy", "border", "around", "console" ]
a4460927aa64c2a514c57993e8ea13f5b48377e9
https://github.com/Deradon/Rdcpu16/blob/a4460927aa64c2a514c57993e8ea13f5b48377e9/lib/dcpu16/screen.rb#L73-L92
9,190
Deradon/Rdcpu16
lib/dcpu16/screen.rb
DCPU16.Screen.update
def update(offset, value) return unless (memory_offset..memory_offset_end).include?(offset) @to_s = nil diff = offset - @memory_offset h = diff / @width w = diff % @width @chars[diff] = Char.new(value, w + @x_offset, h + @y_offset) print @chars[diff] changed notify_observers(self) print @chars[diff] end
ruby
def update(offset, value) return unless (memory_offset..memory_offset_end).include?(offset) @to_s = nil diff = offset - @memory_offset h = diff / @width w = diff % @width @chars[diff] = Char.new(value, w + @x_offset, h + @y_offset) print @chars[diff] changed notify_observers(self) print @chars[diff] end
[ "def", "update", "(", "offset", ",", "value", ")", "return", "unless", "(", "memory_offset", "..", "memory_offset_end", ")", ".", "include?", "(", "offset", ")", "@to_s", "=", "nil", "diff", "=", "offset", "-", "@memory_offset", "h", "=", "diff", "/", "@width", "w", "=", "diff", "%", "@width", "@chars", "[", "diff", "]", "=", "Char", ".", "new", "(", "value", ",", "w", "+", "@x_offset", ",", "h", "+", "@y_offset", ")", "print", "@chars", "[", "diff", "]", "changed", "notify_observers", "(", "self", ")", "print", "@chars", "[", "diff", "]", "end" ]
Callback from observed memory
[ "Callback", "from", "observed", "memory" ]
a4460927aa64c2a514c57993e8ea13f5b48377e9
https://github.com/Deradon/Rdcpu16/blob/a4460927aa64c2a514c57993e8ea13f5b48377e9/lib/dcpu16/screen.rb#L95-L107
9,191
bumbleworks/bumbleworks
lib/bumbleworks/configuration.rb
Bumbleworks.Configuration.add_storage_adapter
def add_storage_adapter(adapter) raise ArgumentError, "#{adapter} is not a Bumbleworks storage adapter" unless [:driver, :use?, :new_storage, :allow_history_storage?, :storage_class, :display_name].all? { |m| adapter.respond_to?(m) } @storage_adapters << adapter @storage_adapters end
ruby
def add_storage_adapter(adapter) raise ArgumentError, "#{adapter} is not a Bumbleworks storage adapter" unless [:driver, :use?, :new_storage, :allow_history_storage?, :storage_class, :display_name].all? { |m| adapter.respond_to?(m) } @storage_adapters << adapter @storage_adapters end
[ "def", "add_storage_adapter", "(", "adapter", ")", "raise", "ArgumentError", ",", "\"#{adapter} is not a Bumbleworks storage adapter\"", "unless", "[", ":driver", ",", ":use?", ",", ":new_storage", ",", ":allow_history_storage?", ",", ":storage_class", ",", ":display_name", "]", ".", "all?", "{", "|", "m", "|", "adapter", ".", "respond_to?", "(", "m", ")", "}", "@storage_adapters", "<<", "adapter", "@storage_adapters", "end" ]
Add a storage adapter to the set of possible adapters. Takes an object that responds to `driver`, `use?`, `storage_class`, and `display_name`.
[ "Add", "a", "storage", "adapter", "to", "the", "set", "of", "possible", "adapters", ".", "Takes", "an", "object", "that", "responds", "to", "driver", "use?", "storage_class", "and", "display_name", "." ]
6f63992e921dcf8371d4453ef9e7b4e3322cc360
https://github.com/bumbleworks/bumbleworks/blob/6f63992e921dcf8371d4453ef9e7b4e3322cc360/lib/bumbleworks/configuration.rb#L263-L269
9,192
bumbleworks/bumbleworks
lib/bumbleworks/configuration.rb
Bumbleworks.Configuration.storage_adapter
def storage_adapter @storage_adapter ||= begin all_adapters = storage_adapters raise UndefinedSetting, "No storage adapters configured" if all_adapters.empty? adapter = all_adapters.detect do |potential_adapter| potential_adapter.use?(storage) end raise UndefinedSetting, "Storage is missing or not supported. Supported: #{all_adapters.map(&:display_name).join(', ')}" unless adapter adapter end end
ruby
def storage_adapter @storage_adapter ||= begin all_adapters = storage_adapters raise UndefinedSetting, "No storage adapters configured" if all_adapters.empty? adapter = all_adapters.detect do |potential_adapter| potential_adapter.use?(storage) end raise UndefinedSetting, "Storage is missing or not supported. Supported: #{all_adapters.map(&:display_name).join(', ')}" unless adapter adapter end end
[ "def", "storage_adapter", "@storage_adapter", "||=", "begin", "all_adapters", "=", "storage_adapters", "raise", "UndefinedSetting", ",", "\"No storage adapters configured\"", "if", "all_adapters", ".", "empty?", "adapter", "=", "all_adapters", ".", "detect", "do", "|", "potential_adapter", "|", "potential_adapter", ".", "use?", "(", "storage", ")", "end", "raise", "UndefinedSetting", ",", "\"Storage is missing or not supported. Supported: #{all_adapters.map(&:display_name).join(', ')}\"", "unless", "adapter", "adapter", "end", "end" ]
If storage_adapter is not explicitly set, find first registered adapter that can use Bumbleworks.storage.
[ "If", "storage_adapter", "is", "not", "explicitly", "set", "find", "first", "registered", "adapter", "that", "can", "use", "Bumbleworks", ".", "storage", "." ]
6f63992e921dcf8371d4453ef9e7b4e3322cc360
https://github.com/bumbleworks/bumbleworks/blob/6f63992e921dcf8371d4453ef9e7b4e3322cc360/lib/bumbleworks/configuration.rb#L274-L284
9,193
bumbleworks/bumbleworks
lib/bumbleworks/configuration.rb
Bumbleworks.Configuration.look_up_configured_path
def look_up_configured_path(path_type, options = {}) return @cached_paths[path_type] if @cached_paths.has_key?(path_type) if user_defined_path = user_configured_path(path_type) if path_resolves?(user_defined_path, :file => options[:file]) return user_defined_path else raise Bumbleworks::InvalidSetting, "#{Bumbleworks::Support.humanize(path_type)} not found (looked for #{user_defined_path || defaults.join(', ')})" end end first_existing_default_path(options[:defaults], :file => options[:file]) end
ruby
def look_up_configured_path(path_type, options = {}) return @cached_paths[path_type] if @cached_paths.has_key?(path_type) if user_defined_path = user_configured_path(path_type) if path_resolves?(user_defined_path, :file => options[:file]) return user_defined_path else raise Bumbleworks::InvalidSetting, "#{Bumbleworks::Support.humanize(path_type)} not found (looked for #{user_defined_path || defaults.join(', ')})" end end first_existing_default_path(options[:defaults], :file => options[:file]) end
[ "def", "look_up_configured_path", "(", "path_type", ",", "options", "=", "{", "}", ")", "return", "@cached_paths", "[", "path_type", "]", "if", "@cached_paths", ".", "has_key?", "(", "path_type", ")", "if", "user_defined_path", "=", "user_configured_path", "(", "path_type", ")", "if", "path_resolves?", "(", "user_defined_path", ",", ":file", "=>", "options", "[", ":file", "]", ")", "return", "user_defined_path", "else", "raise", "Bumbleworks", "::", "InvalidSetting", ",", "\"#{Bumbleworks::Support.humanize(path_type)} not found (looked for #{user_defined_path || defaults.join(', ')})\"", "end", "end", "first_existing_default_path", "(", "options", "[", ":defaults", "]", ",", ":file", "=>", "options", "[", ":file", "]", ")", "end" ]
If the user explicitly declared a path, raises an exception if the path was not found. Missing default paths do not raise an exception since no paths are required.
[ "If", "the", "user", "explicitly", "declared", "a", "path", "raises", "an", "exception", "if", "the", "path", "was", "not", "found", ".", "Missing", "default", "paths", "do", "not", "raise", "an", "exception", "since", "no", "paths", "are", "required", "." ]
6f63992e921dcf8371d4453ef9e7b4e3322cc360
https://github.com/bumbleworks/bumbleworks/blob/6f63992e921dcf8371d4453ef9e7b4e3322cc360/lib/bumbleworks/configuration.rb#L350-L361
9,194
ronen/hash_keyword_args
lib/hash_keyword_args/hash.rb
HashKeywordArgs.Hash.keyword_args
def keyword_args(*args) argshash = args[-1].is_a?(Hash) ? args.pop : {} argshash = args.hashify(:optional).merge(argshash) others_OK = argshash.delete(:OTHERS) ret = {} # defaults, required, and checked required = [] check = {} argshash.each do |key, val| # construct fleshed-out attribute hash for all args attrs = case val when Hash val[:default] ||= [] if val[:enumerable] val when :required { :required => true } when :optional {} when :enumerable { :enumerable => true, :default => [] } when Array { :valid => val } when Class, Module { :valid => val } else { :default => val } end # extract required flag, validity checks, and default vlues from attribute hash required << key if attrs[:required] check[key] = case valid = attrs[:valid] when Enumerable [:one_of, valid] when Class, Module [:is_a, valid] else [:ok] end check[key][2] = [:allow_nil, :enumerable].select{|mod| attrs[mod]} ret[key] = attrs[:default] if attrs.include?(:default) end # check validity of keys unless others_OK or (others = self.keys - argshash.keys).empty? raise ArgumentError, "Invalid keyword arg#{others.length>1 && "s" or ""} #{others.collect{|a| a.inspect}.join(', ')}", caller end # process values, checking validity self.each do |key, val| code, valid, mods = check[key] mods ||= [] val = [ val ] unless mods.include?(:enumerable) and val.is_a?(Enumerable) ok = val.all? { |v| if mods.include?(:allow_nil) and v.nil? true else case code when nil then true # for OTHERS args, there's no code when :ok then true when :one_of then valid.include?(v) when :is_a then v.is_a?(valid) end end } val = val.first unless mods.include?(:enumerable) raise ArgumentError, "Invalid value for keyword arg #{key.inspect} => #{val.inspect}", caller unless ok ret[key] = val required.delete(key) end unless required.empty? raise ArgumentError, "Missing required keyword arg#{required.length>1 && "s" or ""} #{required.collect{|a| a.inspect}.join(', ')}", caller end (class << ret ; self ; end).class_eval do argshash.keys.each do |key| define_method(key) do self[key] end end end ret end
ruby
def keyword_args(*args) argshash = args[-1].is_a?(Hash) ? args.pop : {} argshash = args.hashify(:optional).merge(argshash) others_OK = argshash.delete(:OTHERS) ret = {} # defaults, required, and checked required = [] check = {} argshash.each do |key, val| # construct fleshed-out attribute hash for all args attrs = case val when Hash val[:default] ||= [] if val[:enumerable] val when :required { :required => true } when :optional {} when :enumerable { :enumerable => true, :default => [] } when Array { :valid => val } when Class, Module { :valid => val } else { :default => val } end # extract required flag, validity checks, and default vlues from attribute hash required << key if attrs[:required] check[key] = case valid = attrs[:valid] when Enumerable [:one_of, valid] when Class, Module [:is_a, valid] else [:ok] end check[key][2] = [:allow_nil, :enumerable].select{|mod| attrs[mod]} ret[key] = attrs[:default] if attrs.include?(:default) end # check validity of keys unless others_OK or (others = self.keys - argshash.keys).empty? raise ArgumentError, "Invalid keyword arg#{others.length>1 && "s" or ""} #{others.collect{|a| a.inspect}.join(', ')}", caller end # process values, checking validity self.each do |key, val| code, valid, mods = check[key] mods ||= [] val = [ val ] unless mods.include?(:enumerable) and val.is_a?(Enumerable) ok = val.all? { |v| if mods.include?(:allow_nil) and v.nil? true else case code when nil then true # for OTHERS args, there's no code when :ok then true when :one_of then valid.include?(v) when :is_a then v.is_a?(valid) end end } val = val.first unless mods.include?(:enumerable) raise ArgumentError, "Invalid value for keyword arg #{key.inspect} => #{val.inspect}", caller unless ok ret[key] = val required.delete(key) end unless required.empty? raise ArgumentError, "Missing required keyword arg#{required.length>1 && "s" or ""} #{required.collect{|a| a.inspect}.join(', ')}", caller end (class << ret ; self ; end).class_eval do argshash.keys.each do |key| define_method(key) do self[key] end end end ret end
[ "def", "keyword_args", "(", "*", "args", ")", "argshash", "=", "args", "[", "-", "1", "]", ".", "is_a?", "(", "Hash", ")", "?", "args", ".", "pop", ":", "{", "}", "argshash", "=", "args", ".", "hashify", "(", ":optional", ")", ".", "merge", "(", "argshash", ")", "others_OK", "=", "argshash", ".", "delete", "(", ":OTHERS", ")", "ret", "=", "{", "}", "# defaults, required, and checked", "required", "=", "[", "]", "check", "=", "{", "}", "argshash", ".", "each", "do", "|", "key", ",", "val", "|", "# construct fleshed-out attribute hash for all args", "attrs", "=", "case", "val", "when", "Hash", "val", "[", ":default", "]", "||=", "[", "]", "if", "val", "[", ":enumerable", "]", "val", "when", ":required", "{", ":required", "=>", "true", "}", "when", ":optional", "{", "}", "when", ":enumerable", "{", ":enumerable", "=>", "true", ",", ":default", "=>", "[", "]", "}", "when", "Array", "{", ":valid", "=>", "val", "}", "when", "Class", ",", "Module", "{", ":valid", "=>", "val", "}", "else", "{", ":default", "=>", "val", "}", "end", "# extract required flag, validity checks, and default vlues from attribute hash", "required", "<<", "key", "if", "attrs", "[", ":required", "]", "check", "[", "key", "]", "=", "case", "valid", "=", "attrs", "[", ":valid", "]", "when", "Enumerable", "[", ":one_of", ",", "valid", "]", "when", "Class", ",", "Module", "[", ":is_a", ",", "valid", "]", "else", "[", ":ok", "]", "end", "check", "[", "key", "]", "[", "2", "]", "=", "[", ":allow_nil", ",", ":enumerable", "]", ".", "select", "{", "|", "mod", "|", "attrs", "[", "mod", "]", "}", "ret", "[", "key", "]", "=", "attrs", "[", ":default", "]", "if", "attrs", ".", "include?", "(", ":default", ")", "end", "# check validity of keys", "unless", "others_OK", "or", "(", "others", "=", "self", ".", "keys", "-", "argshash", ".", "keys", ")", ".", "empty?", "raise", "ArgumentError", ",", "\"Invalid keyword arg#{others.length>1 && \"s\" or \"\"} #{others.collect{|a| a.inspect}.join(', ')}\"", ",", "caller", "end", "# process values, checking validity", "self", ".", "each", "do", "|", "key", ",", "val", "|", "code", ",", "valid", ",", "mods", "=", "check", "[", "key", "]", "mods", "||=", "[", "]", "val", "=", "[", "val", "]", "unless", "mods", ".", "include?", "(", ":enumerable", ")", "and", "val", ".", "is_a?", "(", "Enumerable", ")", "ok", "=", "val", ".", "all?", "{", "|", "v", "|", "if", "mods", ".", "include?", "(", ":allow_nil", ")", "and", "v", ".", "nil?", "true", "else", "case", "code", "when", "nil", "then", "true", "# for OTHERS args, there's no code", "when", ":ok", "then", "true", "when", ":one_of", "then", "valid", ".", "include?", "(", "v", ")", "when", ":is_a", "then", "v", ".", "is_a?", "(", "valid", ")", "end", "end", "}", "val", "=", "val", ".", "first", "unless", "mods", ".", "include?", "(", ":enumerable", ")", "raise", "ArgumentError", ",", "\"Invalid value for keyword arg #{key.inspect} => #{val.inspect}\"", ",", "caller", "unless", "ok", "ret", "[", "key", "]", "=", "val", "required", ".", "delete", "(", "key", ")", "end", "unless", "required", ".", "empty?", "raise", "ArgumentError", ",", "\"Missing required keyword arg#{required.length>1 && \"s\" or \"\"} #{required.collect{|a| a.inspect}.join(', ')}\"", ",", "caller", "end", "(", "class", "<<", "ret", ";", "self", ";", "end", ")", ".", "class_eval", "do", "argshash", ".", "keys", ".", "each", "do", "|", "key", "|", "define_method", "(", "key", ")", "do", "self", "[", "key", "]", "end", "end", "end", "ret", "end" ]
given an argument hash and a description of acceptable keyword args and their default values, checks validity of the arguments and raises any errors, otherwise returns a new hash containing all arg values with defaults filled in as needed. args = hash.keyword_args(:a, :b, :c, # these are all optional args :d => :optional, # same as listing it the arg up front :e => :required, # raises an error if arg not provided :f => "hello" # default value :g => [:x,:y,:z] # valid values :h => Integer # valid type :i => :enumerable # expect/coerce an enumerable, check all items, default is [] :j => { :valid => Integer, :allow_nil => true} # Integer or nil :j => { :valid => [:x,:y,:z], :default => :x, :required => true } # combo ) by default this will raise an error if the hash contains any keys not listed. however, if :OTHERS is specified as a keyword arg, that test will be disabled and any other key/value pairs will be passed through. Returns a Struct whose values are the
[ "given", "an", "argument", "hash", "and", "a", "description", "of", "acceptable", "keyword", "args", "and", "their", "default", "values", "checks", "validity", "of", "the", "arguments", "and", "raises", "any", "errors", "otherwise", "returns", "a", "new", "hash", "containing", "all", "arg", "values", "with", "defaults", "filled", "in", "as", "needed", "." ]
10b0b5d46b32afc0cf6129aa84b49b54ec44474a
https://github.com/ronen/hash_keyword_args/blob/10b0b5d46b32afc0cf6129aa84b49b54ec44474a/lib/hash_keyword_args/hash.rb#L27-L111
9,195
ryohashimoto/actionpager
lib/action_pager/pager.rb
ActionPager.Pager.near_pages
def near_pages @near_pages ||= begin if current_page <= near + 1 upper_page = shown_page_count >= last_page ? last_page : shown_page_count 1..upper_page elsif current_page >= last_page - near - 1 bottom_page = last_page - shown_page_count + 1 (bottom_page > 1 ? bottom_page : 1)..last_page else bottom_page = current_page - near upper_page = current_page + near (bottom_page > 1 ? bottom_page : 1)..(upper_page < last_page ? upper_page : last_page) end end end
ruby
def near_pages @near_pages ||= begin if current_page <= near + 1 upper_page = shown_page_count >= last_page ? last_page : shown_page_count 1..upper_page elsif current_page >= last_page - near - 1 bottom_page = last_page - shown_page_count + 1 (bottom_page > 1 ? bottom_page : 1)..last_page else bottom_page = current_page - near upper_page = current_page + near (bottom_page > 1 ? bottom_page : 1)..(upper_page < last_page ? upper_page : last_page) end end end
[ "def", "near_pages", "@near_pages", "||=", "begin", "if", "current_page", "<=", "near", "+", "1", "upper_page", "=", "shown_page_count", ">=", "last_page", "?", "last_page", ":", "shown_page_count", "1", "..", "upper_page", "elsif", "current_page", ">=", "last_page", "-", "near", "-", "1", "bottom_page", "=", "last_page", "-", "shown_page_count", "+", "1", "(", "bottom_page", ">", "1", "?", "bottom_page", ":", "1", ")", "..", "last_page", "else", "bottom_page", "=", "current_page", "-", "near", "upper_page", "=", "current_page", "+", "near", "(", "bottom_page", ">", "1", "?", "bottom_page", ":", "1", ")", "..", "(", "upper_page", "<", "last_page", "?", "upper_page", ":", "last_page", ")", "end", "end", "end" ]
pages that numbers are displayed
[ "pages", "that", "numbers", "are", "displayed" ]
4ef4e3005748fae2d10a23a5ac5a191ca7a3f65f
https://github.com/ryohashimoto/actionpager/blob/4ef4e3005748fae2d10a23a5ac5a191ca7a3f65f/lib/action_pager/pager.rb#L112-L126
9,196
dmmalam/wall-leecher
lib/leecher.rb
WallLeecher.Leecher.prep_file
def prep_file(url, dir) parts = url.split('/') File.join(dir, parts[-1]) end
ruby
def prep_file(url, dir) parts = url.split('/') File.join(dir, parts[-1]) end
[ "def", "prep_file", "(", "url", ",", "dir", ")", "parts", "=", "url", ".", "split", "(", "'/'", ")", "File", ".", "join", "(", "dir", ",", "parts", "[", "-", "1", "]", ")", "end" ]
Pure function to create correct filename
[ "Pure", "function", "to", "create", "correct", "filename" ]
c744ec6886db0dfd5f316ff59f410e10866e2e15
https://github.com/dmmalam/wall-leecher/blob/c744ec6886db0dfd5f316ff59f410e10866e2e15/lib/leecher.rb#L38-L41
9,197
dmmalam/wall-leecher
lib/leecher.rb
WallLeecher.Fetcher.get
def get schedule do inc_io @@log.info("Requesting: #{@url}") http = EM::HttpRequest.new(@url).get :redirects => 5 http.callback do |h| succeed http.response dec_io end http.headers do |headers| unless OK_ERROR_CODES.include?(headers.status) fail("Error (#{headers.status}) with url:#{@url}") dec_io end end http.errback do fail("Error downloading #{@url}") dec_io end end self # Fluent interface end
ruby
def get schedule do inc_io @@log.info("Requesting: #{@url}") http = EM::HttpRequest.new(@url).get :redirects => 5 http.callback do |h| succeed http.response dec_io end http.headers do |headers| unless OK_ERROR_CODES.include?(headers.status) fail("Error (#{headers.status}) with url:#{@url}") dec_io end end http.errback do fail("Error downloading #{@url}") dec_io end end self # Fluent interface end
[ "def", "get", "schedule", "do", "inc_io", "@@log", ".", "info", "(", "\"Requesting: #{@url}\"", ")", "http", "=", "EM", "::", "HttpRequest", ".", "new", "(", "@url", ")", ".", "get", ":redirects", "=>", "5", "http", ".", "callback", "do", "|", "h", "|", "succeed", "http", ".", "response", "dec_io", "end", "http", ".", "headers", "do", "|", "headers", "|", "unless", "OK_ERROR_CODES", ".", "include?", "(", "headers", ".", "status", ")", "fail", "(", "\"Error (#{headers.status}) with url:#{@url}\"", ")", "dec_io", "end", "end", "http", ".", "errback", "do", "fail", "(", "\"Error downloading #{@url}\"", ")", "dec_io", "end", "end", "self", "# Fluent interface", "end" ]
Non blocking get url
[ "Non", "blocking", "get", "url" ]
c744ec6886db0dfd5f316ff59f410e10866e2e15
https://github.com/dmmalam/wall-leecher/blob/c744ec6886db0dfd5f316ff59f410e10866e2e15/lib/leecher.rb#L120-L144
9,198
npolar/npolar-api-client-ruby
lib/npolar/api/client/json_api_client.rb
Npolar::Api::Client.JsonApiClient.valid
def valid(condition=true) all.select {|d| condition == valid?(d) }.map {|d| model.class.new(d)} end
ruby
def valid(condition=true) all.select {|d| condition == valid?(d) }.map {|d| model.class.new(d)} end
[ "def", "valid", "(", "condition", "=", "true", ")", "all", ".", "select", "{", "|", "d", "|", "condition", "==", "valid?", "(", "d", ")", "}", ".", "map", "{", "|", "d", "|", "model", ".", "class", ".", "new", "(", "d", ")", "}", "end" ]
All valid documents
[ "All", "valid", "documents" ]
e28ff77dad15bb1bcfcb750f5d1fd4679aa8b7fb
https://github.com/npolar/npolar-api-client-ruby/blob/e28ff77dad15bb1bcfcb750f5d1fd4679aa8b7fb/lib/npolar/api/client/json_api_client.rb#L286-L288
9,199
npolar/npolar-api-client-ruby
lib/npolar/api/client/json_api_client.rb
Npolar::Api::Client.JsonApiClient.multi_request
def multi_request(method, paths, body=nil, param=nil, header=nil) @multi = true # Response storage, if not already set if @responses.nil? @responses = [] end # Handle one or many paths if paths.is_a? String or paths.is_a? URI paths = [paths] end # Handle (URI) objects paths = paths.map {|p| p.to_s } log.debug "Queueing multi-#{method} requests, concurrency: #{concurrency}, path(s): #{ paths.size == 1 ? paths[0]: paths.size }" paths.each do | path | multi_request = request(path, method.downcase.to_sym, body, param, header) multi_request.on_complete do | response | log.debug "Multi-#{method} [#{paths.size}]: "+log_message(response) @responses << response end hydra.queue(multi_request) end hydra end
ruby
def multi_request(method, paths, body=nil, param=nil, header=nil) @multi = true # Response storage, if not already set if @responses.nil? @responses = [] end # Handle one or many paths if paths.is_a? String or paths.is_a? URI paths = [paths] end # Handle (URI) objects paths = paths.map {|p| p.to_s } log.debug "Queueing multi-#{method} requests, concurrency: #{concurrency}, path(s): #{ paths.size == 1 ? paths[0]: paths.size }" paths.each do | path | multi_request = request(path, method.downcase.to_sym, body, param, header) multi_request.on_complete do | response | log.debug "Multi-#{method} [#{paths.size}]: "+log_message(response) @responses << response end hydra.queue(multi_request) end hydra end
[ "def", "multi_request", "(", "method", ",", "paths", ",", "body", "=", "nil", ",", "param", "=", "nil", ",", "header", "=", "nil", ")", "@multi", "=", "true", "# Response storage, if not already set", "if", "@responses", ".", "nil?", "@responses", "=", "[", "]", "end", "# Handle one or many paths", "if", "paths", ".", "is_a?", "String", "or", "paths", ".", "is_a?", "URI", "paths", "=", "[", "paths", "]", "end", "# Handle (URI) objects", "paths", "=", "paths", ".", "map", "{", "|", "p", "|", "p", ".", "to_s", "}", "log", ".", "debug", "\"Queueing multi-#{method} requests, concurrency: #{concurrency}, path(s): #{ paths.size == 1 ? paths[0]: paths.size }\"", "paths", ".", "each", "do", "|", "path", "|", "multi_request", "=", "request", "(", "path", ",", "method", ".", "downcase", ".", "to_sym", ",", "body", ",", "param", ",", "header", ")", "multi_request", ".", "on_complete", "do", "|", "response", "|", "log", ".", "debug", "\"Multi-#{method} [#{paths.size}]: \"", "+", "log_message", "(", "response", ")", "@responses", "<<", "response", "end", "hydra", ".", "queue", "(", "multi_request", ")", "end", "hydra", "end" ]
Prepare and queue a multi request @return [#run]
[ "Prepare", "and", "queue", "a", "multi", "request" ]
e28ff77dad15bb1bcfcb750f5d1fd4679aa8b7fb
https://github.com/npolar/npolar-api-client-ruby/blob/e28ff77dad15bb1bcfcb750f5d1fd4679aa8b7fb/lib/npolar/api/client/json_api_client.rb#L496-L524