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,400
fotonauts/activr
lib/activr/registry.rb
Activr.Registry.classes_from_path
def classes_from_path(dir_path) Dir["#{dir_path}/*.rb"].sort.inject({ }) do |memo, file_path| klass = File.basename(file_path, '.rb').camelize.constantize if !memo[klass.kind].nil? raise "Kind #{klass.kind} already used by class #{memo[klass.kind]} so can't use it for class #{klass}" end memo[klass.kind] = klass memo end end
ruby
def classes_from_path(dir_path) Dir["#{dir_path}/*.rb"].sort.inject({ }) do |memo, file_path| klass = File.basename(file_path, '.rb').camelize.constantize if !memo[klass.kind].nil? raise "Kind #{klass.kind} already used by class #{memo[klass.kind]} so can't use it for class #{klass}" end memo[klass.kind] = klass memo end end
[ "def", "classes_from_path", "(", "dir_path", ")", "Dir", "[", "\"#{dir_path}/*.rb\"", "]", ".", "sort", ".", "inject", "(", "{", "}", ")", "do", "|", "memo", ",", "file_path", "|", "klass", "=", "File", ".", "basename", "(", "file_path", ",", "'.rb'", ")", ".", "camelize", ".", "constantize", "if", "!", "memo", "[", "klass", ".", "kind", "]", ".", "nil?", "raise", "\"Kind #{klass.kind} already used by class #{memo[klass.kind]} so can't use it for class #{klass}\"", "end", "memo", "[", "klass", ".", "kind", "]", "=", "klass", "memo", "end", "end" ]
Find all classes in given directory @api private @param dir_path [String] Directory path @return [Hash{String=>Class}] Hash of `<kind> => <Class>`
[ "Find", "all", "classes", "in", "given", "directory" ]
92c071ad18a76d4130661da3ce47c1f0fb8ae913
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/registry.rb#L252-L264
9,401
sugaryourcoffee/syclink
lib/syclink/internet_explorer.rb
SycLink.InternetExplorer.read
def read files = Dir.glob(File.join(path, "**/*")) regex = Regexp.new("(?<=#{path}).*") files.map do |file| unless ((File.directory? file) || (File.extname(file).upcase != ".URL")) url = File.read(file).scan(/(?<=\nURL=)(.*)$/).flatten.first.chomp name = url_name(File.basename(file, ".*")) description = "" tag = extract_tags(File.dirname(file).scan(regex)) [url, name, description, tag] end end.compact end
ruby
def read files = Dir.glob(File.join(path, "**/*")) regex = Regexp.new("(?<=#{path}).*") files.map do |file| unless ((File.directory? file) || (File.extname(file).upcase != ".URL")) url = File.read(file).scan(/(?<=\nURL=)(.*)$/).flatten.first.chomp name = url_name(File.basename(file, ".*")) description = "" tag = extract_tags(File.dirname(file).scan(regex)) [url, name, description, tag] end end.compact end
[ "def", "read", "files", "=", "Dir", ".", "glob", "(", "File", ".", "join", "(", "path", ",", "\"**/*\"", ")", ")", "regex", "=", "Regexp", ".", "new", "(", "\"(?<=#{path}).*\"", ")", "files", ".", "map", "do", "|", "file", "|", "unless", "(", "(", "File", ".", "directory?", "file", ")", "||", "(", "File", ".", "extname", "(", "file", ")", ".", "upcase", "!=", "\".URL\"", ")", ")", "url", "=", "File", ".", "read", "(", "file", ")", ".", "scan", "(", "/", "\\n", "/", ")", ".", "flatten", ".", "first", ".", "chomp", "name", "=", "url_name", "(", "File", ".", "basename", "(", "file", ",", "\".*\"", ")", ")", "description", "=", "\"\"", "tag", "=", "extract_tags", "(", "File", ".", "dirname", "(", "file", ")", ".", "scan", "(", "regex", ")", ")", "[", "url", ",", "name", ",", "description", ",", "tag", "]", "end", "end", ".", "compact", "end" ]
Reads the links from the Internet Explorer's bookmarks directory
[ "Reads", "the", "links", "from", "the", "Internet", "Explorer", "s", "bookmarks", "directory" ]
941ee2045c946daa1e0db394eb643aa82c1254cc
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/internet_explorer.rb#L10-L24
9,402
toshi0328/gmath3D
lib/ext.rb
GMath3D.::Matrix.multi_new
def multi_new(rhs) if(rhs.kind_of?(Vector3)) ans = self.multi_inner(rhs.to_column_vector) return Vector3.new(ans[0,0], ans[1,0], ans[2,0]) end multi_inner(rhs) end
ruby
def multi_new(rhs) if(rhs.kind_of?(Vector3)) ans = self.multi_inner(rhs.to_column_vector) return Vector3.new(ans[0,0], ans[1,0], ans[2,0]) end multi_inner(rhs) end
[ "def", "multi_new", "(", "rhs", ")", "if", "(", "rhs", ".", "kind_of?", "(", "Vector3", ")", ")", "ans", "=", "self", ".", "multi_inner", "(", "rhs", ".", "to_column_vector", ")", "return", "Vector3", ".", "new", "(", "ans", "[", "0", ",", "0", "]", ",", "ans", "[", "1", ",", "0", "]", ",", "ans", "[", "2", ",", "0", "]", ")", "end", "multi_inner", "(", "rhs", ")", "end" ]
hold original multiply processing
[ "hold", "original", "multiply", "processing" ]
a90fc3bfbc447af0585632e8d6a68aeae6f5bcc4
https://github.com/toshi0328/gmath3D/blob/a90fc3bfbc447af0585632e8d6a68aeae6f5bcc4/lib/ext.rb#L46-L52
9,403
ideonetwork/lato-blog
app/models/lato_blog/tag.rb
LatoBlog.Tag.check_meta_permalink
def check_meta_permalink candidate = (self.meta_permalink ? self.meta_permalink : self.title.parameterize) accepted = nil counter = 0 while accepted.nil? if LatoBlog::Tag.find_by(meta_permalink: candidate) counter += 1 candidate = "#{candidate}-#{counter}" else accepted = candidate end end self.meta_permalink = accepted end
ruby
def check_meta_permalink candidate = (self.meta_permalink ? self.meta_permalink : self.title.parameterize) accepted = nil counter = 0 while accepted.nil? if LatoBlog::Tag.find_by(meta_permalink: candidate) counter += 1 candidate = "#{candidate}-#{counter}" else accepted = candidate end end self.meta_permalink = accepted end
[ "def", "check_meta_permalink", "candidate", "=", "(", "self", ".", "meta_permalink", "?", "self", ".", "meta_permalink", ":", "self", ".", "title", ".", "parameterize", ")", "accepted", "=", "nil", "counter", "=", "0", "while", "accepted", ".", "nil?", "if", "LatoBlog", "::", "Tag", ".", "find_by", "(", "meta_permalink", ":", "candidate", ")", "counter", "+=", "1", "candidate", "=", "\"#{candidate}-#{counter}\"", "else", "accepted", "=", "candidate", "end", "end", "self", ".", "meta_permalink", "=", "accepted", "end" ]
This function check if current permalink is valid. If it is not valid it generate a new from the post title.
[ "This", "function", "check", "if", "current", "permalink", "is", "valid", ".", "If", "it", "is", "not", "valid", "it", "generate", "a", "new", "from", "the", "post", "title", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/models/lato_blog/tag.rb#L48-L63
9,404
ideonetwork/lato-blog
app/models/lato_blog/tag.rb
LatoBlog.Tag.check_lato_blog_tag_parent
def check_lato_blog_tag_parent tag_parent = LatoBlog::TagParent.find_by(id: lato_blog_tag_parent_id) if !tag_parent errors.add('Tag parent', 'not exist for the tag') throw :abort return end same_language_tag = tag_parent.tags.find_by(meta_language: meta_language) if same_language_tag && same_language_tag.id != id errors.add('Tag parent', 'has another tag for the same language') throw :abort return end end
ruby
def check_lato_blog_tag_parent tag_parent = LatoBlog::TagParent.find_by(id: lato_blog_tag_parent_id) if !tag_parent errors.add('Tag parent', 'not exist for the tag') throw :abort return end same_language_tag = tag_parent.tags.find_by(meta_language: meta_language) if same_language_tag && same_language_tag.id != id errors.add('Tag parent', 'has another tag for the same language') throw :abort return end end
[ "def", "check_lato_blog_tag_parent", "tag_parent", "=", "LatoBlog", "::", "TagParent", ".", "find_by", "(", "id", ":", "lato_blog_tag_parent_id", ")", "if", "!", "tag_parent", "errors", ".", "add", "(", "'Tag parent'", ",", "'not exist for the tag'", ")", "throw", ":abort", "return", "end", "same_language_tag", "=", "tag_parent", ".", "tags", ".", "find_by", "(", "meta_language", ":", "meta_language", ")", "if", "same_language_tag", "&&", "same_language_tag", ".", "id", "!=", "id", "errors", ".", "add", "(", "'Tag parent'", ",", "'has another tag for the same language'", ")", "throw", ":abort", "return", "end", "end" ]
This function check that the category parent exist and has not others tags for the same language.
[ "This", "function", "check", "that", "the", "category", "parent", "exist", "and", "has", "not", "others", "tags", "for", "the", "same", "language", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/models/lato_blog/tag.rb#L66-L80
9,405
ideasasylum/tinycert
lib/tinycert/request.rb
Tinycert.Request.prepare_params
def prepare_params p results = {} # Build a new hash with string keys p.each { |k, v| results[k.to_s] = v } # Sort nested structures results.sort.to_h end
ruby
def prepare_params p results = {} # Build a new hash with string keys p.each { |k, v| results[k.to_s] = v } # Sort nested structures results.sort.to_h end
[ "def", "prepare_params", "p", "results", "=", "{", "}", "# Build a new hash with string keys", "p", ".", "each", "{", "|", "k", ",", "v", "|", "results", "[", "k", ".", "to_s", "]", "=", "v", "}", "# Sort nested structures", "results", ".", "sort", ".", "to_h", "end" ]
Sort the params consistently
[ "Sort", "the", "params", "consistently" ]
6176e740e7d14eb3e9468e442d6c3575fb5810dc
https://github.com/ideasasylum/tinycert/blob/6176e740e7d14eb3e9468e442d6c3575fb5810dc/lib/tinycert/request.rb#L22-L28
9,406
topbitdu/progne_tapera
lib/progne_tapera/enum_list.rb
ProgneTapera::EnumList.ClassMethods.enum_constants
def enum_constants constants.select { |constant| value = const_get constant value.is_a? ProgneTapera::EnumItem } end
ruby
def enum_constants constants.select { |constant| value = const_get constant value.is_a? ProgneTapera::EnumItem } end
[ "def", "enum_constants", "constants", ".", "select", "{", "|", "constant", "|", "value", "=", "const_get", "constant", "value", ".", "is_a?", "ProgneTapera", "::", "EnumItem", "}", "end" ]
Destroy or Update the Enum Items def clear_optional_items end Infrastructure for the Enumerable
[ "Destroy", "or", "Update", "the", "Enum", "Items", "def", "clear_optional_items" ]
7815a518e4c23acaeafb9dbf4a7c4eb08bcfdbcc
https://github.com/topbitdu/progne_tapera/blob/7815a518e4c23acaeafb9dbf4a7c4eb08bcfdbcc/lib/progne_tapera/enum_list.rb#L54-L59
9,407
ajeychronus/chronuscop_client
lib/chronuscop_client/configuration.rb
ChronuscopClient.Configuration.load_yaml_configuration
def load_yaml_configuration yaml_config = YAML.load_file("#{@rails_root_dir}/config/chronuscop.yml") @redis_db_number = yaml_config[@rails_environment]['redis_db_number'] @redis_server_port = yaml_config[@rails_environment]['redis_server_port'] @project_number = yaml_config[@rails_environment]['project_number'] @api_token = yaml_config[@rails_environment]['api_token'] @chronuscop_server_address = yaml_config[@rails_environment]['chronuscop_server_address'] @sync_time_interval = yaml_config[@rails_environment]['sync_time_interval'] end
ruby
def load_yaml_configuration yaml_config = YAML.load_file("#{@rails_root_dir}/config/chronuscop.yml") @redis_db_number = yaml_config[@rails_environment]['redis_db_number'] @redis_server_port = yaml_config[@rails_environment]['redis_server_port'] @project_number = yaml_config[@rails_environment]['project_number'] @api_token = yaml_config[@rails_environment]['api_token'] @chronuscop_server_address = yaml_config[@rails_environment]['chronuscop_server_address'] @sync_time_interval = yaml_config[@rails_environment]['sync_time_interval'] end
[ "def", "load_yaml_configuration", "yaml_config", "=", "YAML", ".", "load_file", "(", "\"#{@rails_root_dir}/config/chronuscop.yml\"", ")", "@redis_db_number", "=", "yaml_config", "[", "@rails_environment", "]", "[", "'redis_db_number'", "]", "@redis_server_port", "=", "yaml_config", "[", "@rails_environment", "]", "[", "'redis_server_port'", "]", "@project_number", "=", "yaml_config", "[", "@rails_environment", "]", "[", "'project_number'", "]", "@api_token", "=", "yaml_config", "[", "@rails_environment", "]", "[", "'api_token'", "]", "@chronuscop_server_address", "=", "yaml_config", "[", "@rails_environment", "]", "[", "'chronuscop_server_address'", "]", "@sync_time_interval", "=", "yaml_config", "[", "@rails_environment", "]", "[", "'sync_time_interval'", "]", "end" ]
rails root directory must be set before calling this.
[ "rails", "root", "directory", "must", "be", "set", "before", "calling", "this", "." ]
17834beba5215b122b399f145f8710da03ff7a0a
https://github.com/ajeychronus/chronuscop_client/blob/17834beba5215b122b399f145f8710da03ff7a0a/lib/chronuscop_client/configuration.rb#L41-L49
9,408
tbuehlmann/ponder
lib/ponder/user.rb
Ponder.User.whois
def whois connected do fiber = Fiber.current callbacks = {} # User is online. callbacks[311] = @thaum.on(311) do |event_data| nick = event_data[:params].split(' ')[1] if nick.downcase == @nick.downcase @online = true # TODO: Add properties. end end # User is not online. callbacks[401] = @thaum.on(401) do |event_data| nick = event_data[:params].split(' ')[1] if nick.downcase == @nick.downcase @online = false fiber.resume end end # End of WHOIS. callbacks[318] = @thaum.on(318) do |event_data| nick = event_data[:params].split(' ')[1] if nick.downcase == @nick.downcase fiber.resume end end raw "WHOIS #{@nick}" Fiber.yield callbacks.each do |type, callback| @thaum.callbacks[type].delete(callback) end end self end
ruby
def whois connected do fiber = Fiber.current callbacks = {} # User is online. callbacks[311] = @thaum.on(311) do |event_data| nick = event_data[:params].split(' ')[1] if nick.downcase == @nick.downcase @online = true # TODO: Add properties. end end # User is not online. callbacks[401] = @thaum.on(401) do |event_data| nick = event_data[:params].split(' ')[1] if nick.downcase == @nick.downcase @online = false fiber.resume end end # End of WHOIS. callbacks[318] = @thaum.on(318) do |event_data| nick = event_data[:params].split(' ')[1] if nick.downcase == @nick.downcase fiber.resume end end raw "WHOIS #{@nick}" Fiber.yield callbacks.each do |type, callback| @thaum.callbacks[type].delete(callback) end end self end
[ "def", "whois", "connected", "do", "fiber", "=", "Fiber", ".", "current", "callbacks", "=", "{", "}", "# User is online.", "callbacks", "[", "311", "]", "=", "@thaum", ".", "on", "(", "311", ")", "do", "|", "event_data", "|", "nick", "=", "event_data", "[", ":params", "]", ".", "split", "(", "' '", ")", "[", "1", "]", "if", "nick", ".", "downcase", "==", "@nick", ".", "downcase", "@online", "=", "true", "# TODO: Add properties.", "end", "end", "# User is not online.", "callbacks", "[", "401", "]", "=", "@thaum", ".", "on", "(", "401", ")", "do", "|", "event_data", "|", "nick", "=", "event_data", "[", ":params", "]", ".", "split", "(", "' '", ")", "[", "1", "]", "if", "nick", ".", "downcase", "==", "@nick", ".", "downcase", "@online", "=", "false", "fiber", ".", "resume", "end", "end", "# End of WHOIS.", "callbacks", "[", "318", "]", "=", "@thaum", ".", "on", "(", "318", ")", "do", "|", "event_data", "|", "nick", "=", "event_data", "[", ":params", "]", ".", "split", "(", "' '", ")", "[", "1", "]", "if", "nick", ".", "downcase", "==", "@nick", ".", "downcase", "fiber", ".", "resume", "end", "end", "raw", "\"WHOIS #{@nick}\"", "Fiber", ".", "yield", "callbacks", ".", "each", "do", "|", "type", ",", "callback", "|", "@thaum", ".", "callbacks", "[", "type", "]", ".", "delete", "(", "callback", ")", "end", "end", "self", "end" ]
Updates the properties of an user.
[ "Updates", "the", "properties", "of", "an", "user", "." ]
930912e1b78b41afa1359121aca46197e9edff9c
https://github.com/tbuehlmann/ponder/blob/930912e1b78b41afa1359121aca46197e9edff9c/lib/ponder/user.rb#L11-L51
9,409
spaghetticode/lazymodel
lib/lazymodel/base.rb
Lazymodel.Base.attributes
def attributes _attributes.inject(HashWithIndifferentAccess.new) do |hash, attribute| hash.update attribute => send(attribute) end end
ruby
def attributes _attributes.inject(HashWithIndifferentAccess.new) do |hash, attribute| hash.update attribute => send(attribute) end end
[ "def", "attributes", "_attributes", ".", "inject", "(", "HashWithIndifferentAccess", ".", "new", ")", "do", "|", "hash", ",", "attribute", "|", "hash", ".", "update", "attribute", "=>", "send", "(", "attribute", ")", "end", "end" ]
don't override this method without calling super!
[ "don", "t", "override", "this", "method", "without", "calling", "super!" ]
de0b4567bf5c0731c7417f476d38fd74c5a2a3e2
https://github.com/spaghetticode/lazymodel/blob/de0b4567bf5c0731c7417f476d38fd74c5a2a3e2/lib/lazymodel/base.rb#L55-L59
9,410
rrn/acts_as_joinable
lib/joinable/permissions_attribute_wrapper.rb
Joinable.PermissionsAttributeWrapper.permission_attributes=
def permission_attributes=(permissions) self.permissions = [] # Reset permissions in anticipation for re-population permissions.each do |key, value| key, value = key.dup, value.dup # Component Permissions if key.ends_with? "_permissions" grant_permissions(value) # Singular Permission elsif key.chomp! "_permission" grant_permissions(key) if value.to_i != 0 end end end
ruby
def permission_attributes=(permissions) self.permissions = [] # Reset permissions in anticipation for re-population permissions.each do |key, value| key, value = key.dup, value.dup # Component Permissions if key.ends_with? "_permissions" grant_permissions(value) # Singular Permission elsif key.chomp! "_permission" grant_permissions(key) if value.to_i != 0 end end end
[ "def", "permission_attributes", "=", "(", "permissions", ")", "self", ".", "permissions", "=", "[", "]", "# Reset permissions in anticipation for re-population", "permissions", ".", "each", "do", "|", "key", ",", "value", "|", "key", ",", "value", "=", "key", ".", "dup", ",", "value", ".", "dup", "# Component Permissions", "if", "key", ".", "ends_with?", "\"_permissions\"", "grant_permissions", "(", "value", ")", "# Singular Permission", "elsif", "key", ".", "chomp!", "\"_permission\"", "grant_permissions", "(", "key", ")", "if", "value", ".", "to_i", "!=", "0", "end", "end", "end" ]
Used by advanced permission forms which group permissions by their associated component or using a single check box per permission.
[ "Used", "by", "advanced", "permission", "forms", "which", "group", "permissions", "by", "their", "associated", "component", "or", "using", "a", "single", "check", "box", "per", "permission", "." ]
33bfa5bfed84ec1644fd4ddfb75b661d24a2fb71
https://github.com/rrn/acts_as_joinable/blob/33bfa5bfed84ec1644fd4ddfb75b661d24a2fb71/lib/joinable/permissions_attribute_wrapper.rb#L33-L47
9,411
rrn/acts_as_joinable
lib/joinable/permissions_attribute_wrapper.rb
Joinable.PermissionsAttributeWrapper.has_permission?
def has_permission?(*levels) if levels.all? { |level| permissions.include? level.to_sym } return true else return false end end
ruby
def has_permission?(*levels) if levels.all? { |level| permissions.include? level.to_sym } return true else return false end end
[ "def", "has_permission?", "(", "*", "levels", ")", "if", "levels", ".", "all?", "{", "|", "level", "|", "permissions", ".", "include?", "level", ".", "to_sym", "}", "return", "true", "else", "return", "false", "end", "end" ]
Returns true if the object has all the permissions specified by +levels+
[ "Returns", "true", "if", "the", "object", "has", "all", "the", "permissions", "specified", "by", "+", "levels", "+" ]
33bfa5bfed84ec1644fd4ddfb75b661d24a2fb71
https://github.com/rrn/acts_as_joinable/blob/33bfa5bfed84ec1644fd4ddfb75b661d24a2fb71/lib/joinable/permissions_attribute_wrapper.rb#L59-L65
9,412
rrn/acts_as_joinable
lib/joinable/permissions_attribute_wrapper.rb
Joinable.PermissionsAttributeWrapper.method_missing
def method_missing(method_name, *args, &block) # NOTE: As of Rails 4, respond_to? must be checked inside the case statement otherwise it breaks regular AR attribute accessors case method_name.to_s when /.+_permissions/ return component_permissions_reader(method_name) if respond_to?(:joinable_type) && joinable_type.present? when /.+_permission/ return single_permission_reader(method_name) if respond_to?(:joinable_type) && joinable_type.present? end super end
ruby
def method_missing(method_name, *args, &block) # NOTE: As of Rails 4, respond_to? must be checked inside the case statement otherwise it breaks regular AR attribute accessors case method_name.to_s when /.+_permissions/ return component_permissions_reader(method_name) if respond_to?(:joinable_type) && joinable_type.present? when /.+_permission/ return single_permission_reader(method_name) if respond_to?(:joinable_type) && joinable_type.present? end super end
[ "def", "method_missing", "(", "method_name", ",", "*", "args", ",", "&", "block", ")", "# NOTE: As of Rails 4, respond_to? must be checked inside the case statement otherwise it breaks regular AR attribute accessors", "case", "method_name", ".", "to_s", "when", "/", "/", "return", "component_permissions_reader", "(", "method_name", ")", "if", "respond_to?", "(", ":joinable_type", ")", "&&", "joinable_type", ".", "present?", "when", "/", "/", "return", "single_permission_reader", "(", "method_name", ")", "if", "respond_to?", "(", ":joinable_type", ")", "&&", "joinable_type", ".", "present?", "end", "super", "end" ]
Adds readers for component permission groups and single permissions Used by advanced permission forms to determine how which options to select in the various fields. (eg. which option of f.select :labels_permissions to choose)
[ "Adds", "readers", "for", "component", "permission", "groups", "and", "single", "permissions" ]
33bfa5bfed84ec1644fd4ddfb75b661d24a2fb71
https://github.com/rrn/acts_as_joinable/blob/33bfa5bfed84ec1644fd4ddfb75b661d24a2fb71/lib/joinable/permissions_attribute_wrapper.rb#L105-L115
9,413
rrn/acts_as_joinable
lib/joinable/permissions_attribute_wrapper.rb
Joinable.PermissionsAttributeWrapper.verify_and_sort_permissions
def verify_and_sort_permissions # DefaultPermissionSet is allowed to have blank permissions (private joinable), the other models need at least find and view self.permissions += [:find, :view] unless is_a?(DefaultPermissionSet) raise "Invalid permissions: #{(permissions - allowed_permissions).inspect}. Must be one of #{allowed_permissions.inspect}" unless permissions.all? {|permission| allowed_permissions.include? permission} self.permissions = permissions.uniq.sort_by { |permission| allowed_permissions.index(permission) } end
ruby
def verify_and_sort_permissions # DefaultPermissionSet is allowed to have blank permissions (private joinable), the other models need at least find and view self.permissions += [:find, :view] unless is_a?(DefaultPermissionSet) raise "Invalid permissions: #{(permissions - allowed_permissions).inspect}. Must be one of #{allowed_permissions.inspect}" unless permissions.all? {|permission| allowed_permissions.include? permission} self.permissions = permissions.uniq.sort_by { |permission| allowed_permissions.index(permission) } end
[ "def", "verify_and_sort_permissions", "# DefaultPermissionSet is allowed to have blank permissions (private joinable), the other models need at least find and view", "self", ".", "permissions", "+=", "[", ":find", ",", ":view", "]", "unless", "is_a?", "(", "DefaultPermissionSet", ")", "raise", "\"Invalid permissions: #{(permissions - allowed_permissions).inspect}. Must be one of #{allowed_permissions.inspect}\"", "unless", "permissions", ".", "all?", "{", "|", "permission", "|", "allowed_permissions", ".", "include?", "permission", "}", "self", ".", "permissions", "=", "permissions", ".", "uniq", ".", "sort_by", "{", "|", "permission", "|", "allowed_permissions", ".", "index", "(", "permission", ")", "}", "end" ]
Verifies that all the access levels are valid for the attached permissible Makes sure no permissions are duplicated Enforces the order of access levels in the access attribute using the order of the permissions array
[ "Verifies", "that", "all", "the", "access", "levels", "are", "valid", "for", "the", "attached", "permissible", "Makes", "sure", "no", "permissions", "are", "duplicated", "Enforces", "the", "order", "of", "access", "levels", "in", "the", "access", "attribute", "using", "the", "order", "of", "the", "permissions", "array" ]
33bfa5bfed84ec1644fd4ddfb75b661d24a2fb71
https://github.com/rrn/acts_as_joinable/blob/33bfa5bfed84ec1644fd4ddfb75b661d24a2fb71/lib/joinable/permissions_attribute_wrapper.rb#L131-L138
9,414
jeremyruppel/git-approvals
lib/git/approvals/rspec.rb
RSpec.Approvals.verify
def verify( options={}, &block ) approval = Git::Approvals::Approval.new( approval_path, options ) approval.diff( block.call ) do |err| ::RSpec::Expectations.fail_with err end rescue Errno::ENOENT => e ::RSpec::Expectations.fail_with e.message EOS end
ruby
def verify( options={}, &block ) approval = Git::Approvals::Approval.new( approval_path, options ) approval.diff( block.call ) do |err| ::RSpec::Expectations.fail_with err end rescue Errno::ENOENT => e ::RSpec::Expectations.fail_with e.message EOS end
[ "def", "verify", "(", "options", "=", "{", "}", ",", "&", "block", ")", "approval", "=", "Git", "::", "Approvals", "::", "Approval", ".", "new", "(", "approval_path", ",", "options", ")", "approval", ".", "diff", "(", "block", ".", "call", ")", "do", "|", "err", "|", "::", "RSpec", "::", "Expectations", ".", "fail_with", "err", "end", "rescue", "Errno", "::", "ENOENT", "=>", "e", "::", "RSpec", "::", "Expectations", ".", "fail_with", "e", ".", "message", "EOS", "end" ]
Verifies that the result of the block is the same as the approved version.
[ "Verifies", "that", "the", "result", "of", "the", "block", "is", "the", "same", "as", "the", "approved", "version", "." ]
4d08f5cce9e0aa1d716dd9e14c86bc94d9499f96
https://github.com/jeremyruppel/git-approvals/blob/4d08f5cce9e0aa1d716dd9e14c86bc94d9499f96/lib/git/approvals/rspec.rb#L15-L23
9,415
jeremyruppel/git-approvals
lib/git/approvals/rspec.rb
RSpec.Approvals.approval_filename
def approval_filename parts = [ example, *example.example_group.parent_groups ].map do |ex| Git::Approvals::Utils.filenamify ex.description end File.join parts.to_a.reverse end
ruby
def approval_filename parts = [ example, *example.example_group.parent_groups ].map do |ex| Git::Approvals::Utils.filenamify ex.description end File.join parts.to_a.reverse end
[ "def", "approval_filename", "parts", "=", "[", "example", ",", "example", ".", "example_group", ".", "parent_groups", "]", ".", "map", "do", "|", "ex", "|", "Git", "::", "Approvals", "::", "Utils", ".", "filenamify", "ex", ".", "description", "end", "File", ".", "join", "parts", ".", "to_a", ".", "reverse", "end" ]
The approval filename
[ "The", "approval", "filename" ]
4d08f5cce9e0aa1d716dd9e14c86bc94d9499f96
https://github.com/jeremyruppel/git-approvals/blob/4d08f5cce9e0aa1d716dd9e14c86bc94d9499f96/lib/git/approvals/rspec.rb#L33-L38
9,416
octoai/gem-octocore-cassandra
lib/octocore-cassandra/trends.rb
Octo.Trends.aggregate_and_create
def aggregate_and_create(oftype, ts = Time.now.floor) Octo::Enterprise.each do |enterprise| calculate(enterprise.id, oftype, ts) end end
ruby
def aggregate_and_create(oftype, ts = Time.now.floor) Octo::Enterprise.each do |enterprise| calculate(enterprise.id, oftype, ts) end end
[ "def", "aggregate_and_create", "(", "oftype", ",", "ts", "=", "Time", ".", "now", ".", "floor", ")", "Octo", "::", "Enterprise", ".", "each", "do", "|", "enterprise", "|", "calculate", "(", "enterprise", ".", "id", ",", "oftype", ",", "ts", ")", "end", "end" ]
Aggregates and creates trends for all the enterprises for a specific trend type at a specific timestamp @param [Fixnum] oftype The type of trend to be calculated @param [Time] ts The time at which trend needs to be calculated
[ "Aggregates", "and", "creates", "trends", "for", "all", "the", "enterprises", "for", "a", "specific", "trend", "type", "at", "a", "specific", "timestamp" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/trends.rb#L32-L36
9,417
octoai/gem-octocore-cassandra
lib/octocore-cassandra/trends.rb
Octo.Trends.aggregate!
def aggregate!(ts = Time.now.floor) aggregate_and_create(Octo::Counter::TYPE_MINUTE, ts) end
ruby
def aggregate!(ts = Time.now.floor) aggregate_and_create(Octo::Counter::TYPE_MINUTE, ts) end
[ "def", "aggregate!", "(", "ts", "=", "Time", ".", "now", ".", "floor", ")", "aggregate_and_create", "(", "Octo", "::", "Counter", "::", "TYPE_MINUTE", ",", "ts", ")", "end" ]
Override the aggregate! defined in counter class as the calculations for trending are a little different
[ "Override", "the", "aggregate!", "defined", "in", "counter", "class", "as", "the", "calculations", "for", "trending", "are", "a", "little", "different" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/trends.rb#L40-L42
9,418
octoai/gem-octocore-cassandra
lib/octocore-cassandra/trends.rb
Octo.Trends.calculate
def calculate(enterprise_id, trend_type, ts = Time.now.floor) args = { enterprise_id: enterprise_id, ts: ts, type: trend_type } klass = @trend_for.constantize hitsResult = klass.public_send(:where, args) trends = hitsResult.map { |h| counter2trend(h) } # group trends as per the time of their happening and rank them on their # score grouped_trends = trends.group_by { |x| x.ts } grouped_trends.each do |_ts, trendlist| sorted_trendlist = trendlist.sort_by { |x| x.score } sorted_trendlist.each_with_index do |trend, index| trend.rank = index trend.type = trend_type trend.save! end end end
ruby
def calculate(enterprise_id, trend_type, ts = Time.now.floor) args = { enterprise_id: enterprise_id, ts: ts, type: trend_type } klass = @trend_for.constantize hitsResult = klass.public_send(:where, args) trends = hitsResult.map { |h| counter2trend(h) } # group trends as per the time of their happening and rank them on their # score grouped_trends = trends.group_by { |x| x.ts } grouped_trends.each do |_ts, trendlist| sorted_trendlist = trendlist.sort_by { |x| x.score } sorted_trendlist.each_with_index do |trend, index| trend.rank = index trend.type = trend_type trend.save! end end end
[ "def", "calculate", "(", "enterprise_id", ",", "trend_type", ",", "ts", "=", "Time", ".", "now", ".", "floor", ")", "args", "=", "{", "enterprise_id", ":", "enterprise_id", ",", "ts", ":", "ts", ",", "type", ":", "trend_type", "}", "klass", "=", "@trend_for", ".", "constantize", "hitsResult", "=", "klass", ".", "public_send", "(", ":where", ",", "args", ")", "trends", "=", "hitsResult", ".", "map", "{", "|", "h", "|", "counter2trend", "(", "h", ")", "}", "# group trends as per the time of their happening and rank them on their", "# score", "grouped_trends", "=", "trends", ".", "group_by", "{", "|", "x", "|", "x", ".", "ts", "}", "grouped_trends", ".", "each", "do", "|", "_ts", ",", "trendlist", "|", "sorted_trendlist", "=", "trendlist", ".", "sort_by", "{", "|", "x", "|", "x", ".", "score", "}", "sorted_trendlist", ".", "each_with_index", "do", "|", "trend", ",", "index", "|", "trend", ".", "rank", "=", "index", "trend", ".", "type", "=", "trend_type", "trend", ".", "save!", "end", "end", "end" ]
Performs the actual trend calculation @param [String] enterprise_id The enterprise ID for whom trend needs to be found @param [Fixnum] trend_type The trend type to be calculates @param [Time] ts The Timestamp at which trend needs to be calculated.
[ "Performs", "the", "actual", "trend", "calculation" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/trends.rb#L48-L70
9,419
octoai/gem-octocore-cassandra
lib/octocore-cassandra/trends.rb
Octo.Trends.get_trending
def get_trending(enterprise_id, type, opts={}) ts = opts.fetch(:ts, Time.now.floor) args = { enterprise_id: enterprise_id, ts: opts.fetch(:ts, Time.now.floor), type: type } res = where(args).limit(opts.fetch(:limit, DEFAULT_COUNT)) enterprise = Octo::Enterprise.find_by_id(enterprise_id) if res.count == 0 and enterprise.fakedata? Octo.logger.info 'Beginning to fake data' res = [] if ts.class == Range ts_begin = ts.begin ts_end = ts.end ts_begin.to(ts_end, 1.day).each do |_ts| 3.times do |rank| items = @trend_class.constantize.send(:where, {enterprise_id: enterprise_id}).first(10) if items.count > 0 uid = items.shuffle.pop.unique_id _args = args.merge( ts: _ts, rank: rank, score: rank+1, uid: uid ) res << self.new(_args).save! end end end elsif ts.class == Time 3.times do |rank| uid = 0 items = @trend_class.constantize.send(:where, {enterprise_id: enterprise_id}).first(10) if items.count > 0 uid = items.shuffle.pop.unique_id _args = args.merge( rank: rank, score: rank+1, uid: uid ) res << self.new(_args).save! end end end end res.map do |r| clazz = @trend_class.constantize clazz.public_send(:recreate_from, r) end end
ruby
def get_trending(enterprise_id, type, opts={}) ts = opts.fetch(:ts, Time.now.floor) args = { enterprise_id: enterprise_id, ts: opts.fetch(:ts, Time.now.floor), type: type } res = where(args).limit(opts.fetch(:limit, DEFAULT_COUNT)) enterprise = Octo::Enterprise.find_by_id(enterprise_id) if res.count == 0 and enterprise.fakedata? Octo.logger.info 'Beginning to fake data' res = [] if ts.class == Range ts_begin = ts.begin ts_end = ts.end ts_begin.to(ts_end, 1.day).each do |_ts| 3.times do |rank| items = @trend_class.constantize.send(:where, {enterprise_id: enterprise_id}).first(10) if items.count > 0 uid = items.shuffle.pop.unique_id _args = args.merge( ts: _ts, rank: rank, score: rank+1, uid: uid ) res << self.new(_args).save! end end end elsif ts.class == Time 3.times do |rank| uid = 0 items = @trend_class.constantize.send(:where, {enterprise_id: enterprise_id}).first(10) if items.count > 0 uid = items.shuffle.pop.unique_id _args = args.merge( rank: rank, score: rank+1, uid: uid ) res << self.new(_args).save! end end end end res.map do |r| clazz = @trend_class.constantize clazz.public_send(:recreate_from, r) end end
[ "def", "get_trending", "(", "enterprise_id", ",", "type", ",", "opts", "=", "{", "}", ")", "ts", "=", "opts", ".", "fetch", "(", ":ts", ",", "Time", ".", "now", ".", "floor", ")", "args", "=", "{", "enterprise_id", ":", "enterprise_id", ",", "ts", ":", "opts", ".", "fetch", "(", ":ts", ",", "Time", ".", "now", ".", "floor", ")", ",", "type", ":", "type", "}", "res", "=", "where", "(", "args", ")", ".", "limit", "(", "opts", ".", "fetch", "(", ":limit", ",", "DEFAULT_COUNT", ")", ")", "enterprise", "=", "Octo", "::", "Enterprise", ".", "find_by_id", "(", "enterprise_id", ")", "if", "res", ".", "count", "==", "0", "and", "enterprise", ".", "fakedata?", "Octo", ".", "logger", ".", "info", "'Beginning to fake data'", "res", "=", "[", "]", "if", "ts", ".", "class", "==", "Range", "ts_begin", "=", "ts", ".", "begin", "ts_end", "=", "ts", ".", "end", "ts_begin", ".", "to", "(", "ts_end", ",", "1", ".", "day", ")", ".", "each", "do", "|", "_ts", "|", "3", ".", "times", "do", "|", "rank", "|", "items", "=", "@trend_class", ".", "constantize", ".", "send", "(", ":where", ",", "{", "enterprise_id", ":", "enterprise_id", "}", ")", ".", "first", "(", "10", ")", "if", "items", ".", "count", ">", "0", "uid", "=", "items", ".", "shuffle", ".", "pop", ".", "unique_id", "_args", "=", "args", ".", "merge", "(", "ts", ":", "_ts", ",", "rank", ":", "rank", ",", "score", ":", "rank", "+", "1", ",", "uid", ":", "uid", ")", "res", "<<", "self", ".", "new", "(", "_args", ")", ".", "save!", "end", "end", "end", "elsif", "ts", ".", "class", "==", "Time", "3", ".", "times", "do", "|", "rank", "|", "uid", "=", "0", "items", "=", "@trend_class", ".", "constantize", ".", "send", "(", ":where", ",", "{", "enterprise_id", ":", "enterprise_id", "}", ")", ".", "first", "(", "10", ")", "if", "items", ".", "count", ">", "0", "uid", "=", "items", ".", "shuffle", ".", "pop", ".", "unique_id", "_args", "=", "args", ".", "merge", "(", "rank", ":", "rank", ",", "score", ":", "rank", "+", "1", ",", "uid", ":", "uid", ")", "res", "<<", "self", ".", "new", "(", "_args", ")", ".", "save!", "end", "end", "end", "end", "res", ".", "map", "do", "|", "r", "|", "clazz", "=", "@trend_class", ".", "constantize", "clazz", ".", "public_send", "(", ":recreate_from", ",", "r", ")", "end", "end" ]
Gets the trend of a type at a time @param [String] enterprise_id The ID of enterprise for whom trend to fetch @param [Fixnum] type The type of trend to fetch @param [Hash] opts The options to be provided for finding trends
[ "Gets", "the", "trend", "of", "a", "type", "at", "a", "time" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/trends.rb#L90-L131
9,420
octoai/gem-octocore-cassandra
lib/octocore-cassandra/trends.rb
Octo.Trends.counter2trend
def counter2trend(counter) self.new({ enterprise: counter.enterprise, score: score(counter.divergence), uid: counter.uid, ts: counter.ts }) end
ruby
def counter2trend(counter) self.new({ enterprise: counter.enterprise, score: score(counter.divergence), uid: counter.uid, ts: counter.ts }) end
[ "def", "counter2trend", "(", "counter", ")", "self", ".", "new", "(", "{", "enterprise", ":", "counter", ".", "enterprise", ",", "score", ":", "score", "(", "counter", ".", "divergence", ")", ",", "uid", ":", "counter", ".", "uid", ",", "ts", ":", "counter", ".", "ts", "}", ")", "end" ]
Converts a couunter into a trend @param [Object] counter A counter object. This object must belong to one of the counter types defined in models. @return [Object] Returns a trend instance corresponding to the counter instance
[ "Converts", "a", "couunter", "into", "a", "trend" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/trends.rb#L140-L147
9,421
bernerdschaefer/uninhibited
lib/uninhibited/formatter.rb
Uninhibited.Formatter.example_pending
def example_pending(example) if example_group.metadata[:feature] && example.metadata[:skipped] @skipped_examples << pending_examples.delete(example) @skipped_count += 1 output.puts cyan("#{current_indentation}#{example.description}") else super end end
ruby
def example_pending(example) if example_group.metadata[:feature] && example.metadata[:skipped] @skipped_examples << pending_examples.delete(example) @skipped_count += 1 output.puts cyan("#{current_indentation}#{example.description}") else super end end
[ "def", "example_pending", "(", "example", ")", "if", "example_group", ".", "metadata", "[", ":feature", "]", "&&", "example", ".", "metadata", "[", ":skipped", "]", "@skipped_examples", "<<", "pending_examples", ".", "delete", "(", "example", ")", "@skipped_count", "+=", "1", "output", ".", "puts", "cyan", "(", "\"#{current_indentation}#{example.description}\"", ")", "else", "super", "end", "end" ]
Builds a new formatter for outputting Uninhibited features. @api rspec @param [IO] output the output stream Adds the pending example to skipped examples array if it was skipped, otherwise it delegates to super. @api rspec
[ "Builds", "a", "new", "formatter", "for", "outputting", "Uninhibited", "features", "." ]
a45297e127f529ee10719f0306b1ae6721450a33
https://github.com/bernerdschaefer/uninhibited/blob/a45297e127f529ee10719f0306b1ae6721450a33/lib/uninhibited/formatter.rb#L28-L36
9,422
bernerdschaefer/uninhibited
lib/uninhibited/formatter.rb
Uninhibited.Formatter.summary_line
def summary_line(example_count, failure_count, pending_count) pending_count -= skipped_count summary = pluralize(example_count, "example") summary << " (" summary << red(pluralize(failure_count, "failure")) summary << ", " << yellow("#{pending_count} pending") if pending_count > 0 summary << ", " << cyan("#{skipped_count} skipped") if skipped_count > 0 summary << ")" summary end
ruby
def summary_line(example_count, failure_count, pending_count) pending_count -= skipped_count summary = pluralize(example_count, "example") summary << " (" summary << red(pluralize(failure_count, "failure")) summary << ", " << yellow("#{pending_count} pending") if pending_count > 0 summary << ", " << cyan("#{skipped_count} skipped") if skipped_count > 0 summary << ")" summary end
[ "def", "summary_line", "(", "example_count", ",", "failure_count", ",", "pending_count", ")", "pending_count", "-=", "skipped_count", "summary", "=", "pluralize", "(", "example_count", ",", "\"example\"", ")", "summary", "<<", "\" (\"", "summary", "<<", "red", "(", "pluralize", "(", "failure_count", ",", "\"failure\"", ")", ")", "summary", "<<", "\", \"", "<<", "yellow", "(", "\"#{pending_count} pending\"", ")", "if", "pending_count", ">", "0", "summary", "<<", "\", \"", "<<", "cyan", "(", "\"#{skipped_count} skipped\"", ")", "if", "skipped_count", ">", "0", "summary", "<<", "\")\"", "summary", "end" ]
Generates a colorized summary line based on the supplied arguments. formatter.summary_line(1, 0, 0) # => 1 example (0 failures) formatter.summary_line(2, 1, 1) # => 2 examples (1 failure, 1 pending) formatter.skipped_count += 1 formatter.summary_line(2, 0, 0) # => 2 examples (1 failure, 1 skipped) @param [Integer] example_count the total examples run @param [Integer] failure_count the failed examples @param [Integer] pending_count the pending examples @return [String] the formatted summary line @api rspec
[ "Generates", "a", "colorized", "summary", "line", "based", "on", "the", "supplied", "arguments", "." ]
a45297e127f529ee10719f0306b1ae6721450a33
https://github.com/bernerdschaefer/uninhibited/blob/a45297e127f529ee10719f0306b1ae6721450a33/lib/uninhibited/formatter.rb#L67-L76
9,423
MakarovCode/EasyPayULatam
lib/easy_pay_u_latam/r_api/subscription_interceptor.rb
PayuLatam.SubscriptionInterceptor.run
def run PayuLatam::SubscriptionService.new(context.params, context.current_user).call rescue => exception fail!(exception.message) end
ruby
def run PayuLatam::SubscriptionService.new(context.params, context.current_user).call rescue => exception fail!(exception.message) end
[ "def", "run", "PayuLatam", "::", "SubscriptionService", ".", "new", "(", "context", ".", "params", ",", "context", ".", "current_user", ")", ".", "call", "rescue", "=>", "exception", "fail!", "(", "exception", ".", "message", ")", "end" ]
metodo principal de esta clase al estar en un 'rescue' evitamos que el proyecto saque error 500 cuando algo sale mal INTERCEPTAMOS el error y lo enviamos al controller para que trabaje con el de la variable @context, obtenemos los params y el current_user en los params se encuentran datos del plan , tarjeta de crédito seleccionada o datos de nueva tarjeta se ejecuta el metodo 'call' del SubscriptionService
[ "metodo", "principal", "de", "esta", "clase", "al", "estar", "en", "un", "rescue", "evitamos", "que", "el", "proyecto", "saque", "error", "500", "cuando", "algo", "sale", "mal", "INTERCEPTAMOS", "el", "error", "y", "lo", "enviamos", "al", "controller", "para", "que", "trabaje", "con", "el" ]
c412b36fc316eabc338ce9cd152b8fea7316983d
https://github.com/MakarovCode/EasyPayULatam/blob/c412b36fc316eabc338ce9cd152b8fea7316983d/lib/easy_pay_u_latam/r_api/subscription_interceptor.rb#L34-L38
9,424
redding/logsly
lib/logsly/logging182/stats.rb
Logsly::Logging182::Stats.Sampler.coalesce
def coalesce( other ) @sum += other.sum @sumsq += other.sumsq if other.num > 0 @min = other.min if @min > other.min @max = other.max if @max < other.max @last = other.last end @num += other.num end
ruby
def coalesce( other ) @sum += other.sum @sumsq += other.sumsq if other.num > 0 @min = other.min if @min > other.min @max = other.max if @max < other.max @last = other.last end @num += other.num end
[ "def", "coalesce", "(", "other", ")", "@sum", "+=", "other", ".", "sum", "@sumsq", "+=", "other", ".", "sumsq", "if", "other", ".", "num", ">", "0", "@min", "=", "other", ".", "min", "if", "@min", ">", "other", ".", "min", "@max", "=", "other", ".", "max", "if", "@max", "<", "other", ".", "max", "@last", "=", "other", ".", "last", "end", "@num", "+=", "other", ".", "num", "end" ]
Coalesce the statistics from the _other_ sampler into this one. The _other_ sampler is not modified by this method. Coalescing the same two samplers multiple times should only be done if one of the samplers is reset between calls to this method. Otherwise statistics will be counted multiple times.
[ "Coalesce", "the", "statistics", "from", "the", "_other_", "sampler", "into", "this", "one", ".", "The", "_other_", "sampler", "is", "not", "modified", "by", "this", "method", "." ]
a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf
https://github.com/redding/logsly/blob/a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf/lib/logsly/logging182/stats.rb#L47-L56
9,425
redding/logsly
lib/logsly/logging182/stats.rb
Logsly::Logging182::Stats.Sampler.sample
def sample( s ) @sum += s @sumsq += s * s if @num == 0 @min = @max = s else @min = s if @min > s @max = s if @max < s end @num += 1 @last = s end
ruby
def sample( s ) @sum += s @sumsq += s * s if @num == 0 @min = @max = s else @min = s if @min > s @max = s if @max < s end @num += 1 @last = s end
[ "def", "sample", "(", "s", ")", "@sum", "+=", "s", "@sumsq", "+=", "s", "*", "s", "if", "@num", "==", "0", "@min", "=", "@max", "=", "s", "else", "@min", "=", "s", "if", "@min", ">", "s", "@max", "=", "s", "if", "@max", "<", "s", "end", "@num", "+=", "1", "@last", "=", "s", "end" ]
Adds a sampling to the calculations.
[ "Adds", "a", "sampling", "to", "the", "calculations", "." ]
a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf
https://github.com/redding/logsly/blob/a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf/lib/logsly/logging182/stats.rb#L60-L71
9,426
redding/logsly
lib/logsly/logging182/stats.rb
Logsly::Logging182::Stats.Sampler.sd
def sd return 0.0 if num < 2 # (sqrt( ((s).sumsq - ( (s).sum * (s).sum / (s).num)) / ((s).num-1) )) begin return Math.sqrt( (sumsq - ( sum * sum / num)) / (num-1) ) rescue Errno::EDOM return 0.0 end end
ruby
def sd return 0.0 if num < 2 # (sqrt( ((s).sumsq - ( (s).sum * (s).sum / (s).num)) / ((s).num-1) )) begin return Math.sqrt( (sumsq - ( sum * sum / num)) / (num-1) ) rescue Errno::EDOM return 0.0 end end
[ "def", "sd", "return", "0.0", "if", "num", "<", "2", "# (sqrt( ((s).sumsq - ( (s).sum * (s).sum / (s).num)) / ((s).num-1) ))", "begin", "return", "Math", ".", "sqrt", "(", "(", "sumsq", "-", "(", "sum", "*", "sum", "/", "num", ")", ")", "/", "(", "num", "-", "1", ")", ")", "rescue", "Errno", "::", "EDOM", "return", "0.0", "end", "end" ]
Calculates the standard deviation of the data so far.
[ "Calculates", "the", "standard", "deviation", "of", "the", "data", "so", "far", "." ]
a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf
https://github.com/redding/logsly/blob/a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf/lib/logsly/logging182/stats.rb#L106-L115
9,427
redding/logsly
lib/logsly/logging182/stats.rb
Logsly::Logging182::Stats.Tracker.coalesce
def coalesce( other ) sync { other.stats.each do |name,sampler| stats[name].coalesce(sampler) end } end
ruby
def coalesce( other ) sync { other.stats.each do |name,sampler| stats[name].coalesce(sampler) end } end
[ "def", "coalesce", "(", "other", ")", "sync", "{", "other", ".", "stats", ".", "each", "do", "|", "name", ",", "sampler", "|", "stats", "[", "name", "]", ".", "coalesce", "(", "sampler", ")", "end", "}", "end" ]
Create a new Tracker instance. An optional boolean can be passed in to change the "threadsafe" value of the tracker. By default all trackers are created to be threadsafe. Coalesce the samplers from the _other_ tracker into this one. The _other_ tracker is not modified by this method. Coalescing the same two trackers multiple times should only be done if one of the trackers is reset between calls to this method. Otherwise statistics will be counted multiple times. Only this tracker is locked when the coalescing is happening. It is left to the user to lock the other tracker if that is the desired behavior. This is a deliberate choice in order to prevent deadlock situations where two threads are contending on the same mutex.
[ "Create", "a", "new", "Tracker", "instance", ".", "An", "optional", "boolean", "can", "be", "passed", "in", "to", "change", "the", "threadsafe", "value", "of", "the", "tracker", ".", "By", "default", "all", "trackers", "are", "created", "to", "be", "threadsafe", "." ]
a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf
https://github.com/redding/logsly/blob/a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf/lib/logsly/logging182/stats.rb#L175-L181
9,428
redding/logsly
lib/logsly/logging182/stats.rb
Logsly::Logging182::Stats.Tracker.time
def time( event ) sync {stats[event].mark} yield ensure sync {stats[event].tick} end
ruby
def time( event ) sync {stats[event].mark} yield ensure sync {stats[event].tick} end
[ "def", "time", "(", "event", ")", "sync", "{", "stats", "[", "event", "]", ".", "mark", "}", "yield", "ensure", "sync", "{", "stats", "[", "event", "]", ".", "tick", "}", "end" ]
Time the execution of the given block and store the results in the named _event_ sampler. The sampler will be created if it does not exist.
[ "Time", "the", "execution", "of", "the", "given", "block", "and", "store", "the", "results", "in", "the", "named", "_event_", "sampler", ".", "The", "sampler", "will", "be", "created", "if", "it", "does", "not", "exist", "." ]
a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf
https://github.com/redding/logsly/blob/a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf/lib/logsly/logging182/stats.rb#L208-L213
9,429
redding/logsly
lib/logsly/logging182/stats.rb
Logsly::Logging182::Stats.Tracker.periodically_run
def periodically_run( period, &block ) raise ArgumentError, 'a runner already exists' unless @runner.nil? @runner = Thread.new do start = stop = Time.now.to_f loop do seconds = period - (stop-start) seconds = period if seconds <= 0 sleep seconds start = Time.now.to_f break if Thread.current[:stop] == true if @mutex then @mutex.synchronize(&block) else block.call end stop = Time.now.to_f end end end
ruby
def periodically_run( period, &block ) raise ArgumentError, 'a runner already exists' unless @runner.nil? @runner = Thread.new do start = stop = Time.now.to_f loop do seconds = period - (stop-start) seconds = period if seconds <= 0 sleep seconds start = Time.now.to_f break if Thread.current[:stop] == true if @mutex then @mutex.synchronize(&block) else block.call end stop = Time.now.to_f end end end
[ "def", "periodically_run", "(", "period", ",", "&", "block", ")", "raise", "ArgumentError", ",", "'a runner already exists'", "unless", "@runner", ".", "nil?", "@runner", "=", "Thread", ".", "new", "do", "start", "=", "stop", "=", "Time", ".", "now", ".", "to_f", "loop", "do", "seconds", "=", "period", "-", "(", "stop", "-", "start", ")", "seconds", "=", "period", "if", "seconds", "<=", "0", "sleep", "seconds", "start", "=", "Time", ".", "now", ".", "to_f", "break", "if", "Thread", ".", "current", "[", ":stop", "]", "==", "true", "if", "@mutex", "then", "@mutex", ".", "synchronize", "(", "block", ")", "else", "block", ".", "call", "end", "stop", "=", "Time", ".", "now", ".", "to_f", "end", "end", "end" ]
Periodically execute the given _block_ at the given _period_. The tracker will be locked while the block is executing. This method is useful for logging statistics at given interval. Example periodically_run( 300 ) { logger = Logsly::Logging182::Logger['stats'] tracker.each {|sampler| logger << sampler.to_s} tracker.reset }
[ "Periodically", "execute", "the", "given", "_block_", "at", "the", "given", "_period_", ".", "The", "tracker", "will", "be", "locked", "while", "the", "block", "is", "executing", "." ]
a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf
https://github.com/redding/logsly/blob/a17040f0dc8f73a476616bd0ad036c2ff3e4ccaf/lib/logsly/logging182/stats.rb#L235-L252
9,430
ossuarium/palimpsest
lib/palimpsest/assets.rb
Palimpsest.Assets.write
def write(target, gzip: options[:gzip], hash: options[:hash]) asset = assets[target] return if asset.nil? name = hash ? asset.digest_path : asset.logical_path.to_s name = File.join(options[:output], name) unless options[:output].nil? path = name path = File.join(directory, path) unless directory.nil? write(target, gzip: gzip, hash: false) if hash == :also_unhashed asset.write_to "#{path}.gz", compress: true if gzip asset.write_to path name end
ruby
def write(target, gzip: options[:gzip], hash: options[:hash]) asset = assets[target] return if asset.nil? name = hash ? asset.digest_path : asset.logical_path.to_s name = File.join(options[:output], name) unless options[:output].nil? path = name path = File.join(directory, path) unless directory.nil? write(target, gzip: gzip, hash: false) if hash == :also_unhashed asset.write_to "#{path}.gz", compress: true if gzip asset.write_to path name end
[ "def", "write", "(", "target", ",", "gzip", ":", "options", "[", ":gzip", "]", ",", "hash", ":", "options", "[", ":hash", "]", ")", "asset", "=", "assets", "[", "target", "]", "return", "if", "asset", ".", "nil?", "name", "=", "hash", "?", "asset", ".", "digest_path", ":", "asset", ".", "logical_path", ".", "to_s", "name", "=", "File", ".", "join", "(", "options", "[", ":output", "]", ",", "name", ")", "unless", "options", "[", ":output", "]", ".", "nil?", "path", "=", "name", "path", "=", "File", ".", "join", "(", "directory", ",", "path", ")", "unless", "directory", ".", "nil?", "write", "(", "target", ",", "gzip", ":", "gzip", ",", "hash", ":", "false", ")", "if", "hash", "==", ":also_unhashed", "asset", ".", "write_to", "\"#{path}.gz\"", ",", "compress", ":", "true", "if", "gzip", "asset", ".", "write_to", "path", "name", "end" ]
Write a target asset to file with a hashed name. @param target [String] logical path to asset @param gzip [Boolean] if the asset should be gzipped @param hash [Boolean] if the asset name should include the hash @return [String, nil] the relative path to the written asset or `nil` if no such asset
[ "Write", "a", "target", "asset", "to", "file", "with", "a", "hashed", "name", "." ]
7a1d45d33ec7ed878e2b761150ec163ce2125274
https://github.com/ossuarium/palimpsest/blob/7a1d45d33ec7ed878e2b761150ec163ce2125274/lib/palimpsest/assets.rb#L131-L147
9,431
medcat/breadcrumb_trail
lib/breadcrumb_trail/breadcrumb.rb
BreadcrumbTrail.Breadcrumb.computed_path
def computed_path(context) @_path ||= case @path when String, Hash @path when Symbol context.public_send(@path) # todo when Proc context.instance_exec(&@path) else raise ArgumentError, "Expected one of String, Symbol, or Proc, " \ "got #{@path.class}" end end
ruby
def computed_path(context) @_path ||= case @path when String, Hash @path when Symbol context.public_send(@path) # todo when Proc context.instance_exec(&@path) else raise ArgumentError, "Expected one of String, Symbol, or Proc, " \ "got #{@path.class}" end end
[ "def", "computed_path", "(", "context", ")", "@_path", "||=", "case", "@path", "when", "String", ",", "Hash", "@path", "when", "Symbol", "context", ".", "public_send", "(", "@path", ")", "# todo", "when", "Proc", "context", ".", "instance_exec", "(", "@path", ")", "else", "raise", "ArgumentError", ",", "\"Expected one of String, Symbol, or Proc, \"", "\"got #{@path.class}\"", "end", "end" ]
Computes the path of the breadcrumb under the given context. @return [String, Hash]
[ "Computes", "the", "path", "of", "the", "breadcrumb", "under", "the", "given", "context", "." ]
02803a8a3f2492bf6e23d97873b3b906ee95d0b9
https://github.com/medcat/breadcrumb_trail/blob/02803a8a3f2492bf6e23d97873b3b906ee95d0b9/lib/breadcrumb_trail/breadcrumb.rb#L59-L72
9,432
medcat/breadcrumb_trail
lib/breadcrumb_trail/breadcrumb.rb
BreadcrumbTrail.Breadcrumb.computed_name
def computed_name(context) @_name ||= case @name when String @name when Symbol I18n.translate(@name) when Proc context.instance_exec(&@name) when nil computed_path(context) else raise ArgumentError, "Expected one of String, Symbol, or Proc, " \ "got #{@name.class}" end end
ruby
def computed_name(context) @_name ||= case @name when String @name when Symbol I18n.translate(@name) when Proc context.instance_exec(&@name) when nil computed_path(context) else raise ArgumentError, "Expected one of String, Symbol, or Proc, " \ "got #{@name.class}" end end
[ "def", "computed_name", "(", "context", ")", "@_name", "||=", "case", "@name", "when", "String", "@name", "when", "Symbol", "I18n", ".", "translate", "(", "@name", ")", "when", "Proc", "context", ".", "instance_exec", "(", "@name", ")", "when", "nil", "computed_path", "(", "context", ")", "else", "raise", "ArgumentError", ",", "\"Expected one of String, Symbol, or Proc, \"", "\"got #{@name.class}\"", "end", "end" ]
Computes the name of the breadcrumb under the given context. @return [String]
[ "Computes", "the", "name", "of", "the", "breadcrumb", "under", "the", "given", "context", "." ]
02803a8a3f2492bf6e23d97873b3b906ee95d0b9
https://github.com/medcat/breadcrumb_trail/blob/02803a8a3f2492bf6e23d97873b3b906ee95d0b9/lib/breadcrumb_trail/breadcrumb.rb#L77-L92
9,433
sugaryourcoffee/syclink
lib/syclink/firefox.rb
SycLink.Firefox.read
def read bookmark_file = Dir.glob(File.expand_path(path)).shift raise "Did not find file #{path}" unless bookmark_file db = SQLite3::Database.new(path) import = db.execute(QUERY_STRING) end
ruby
def read bookmark_file = Dir.glob(File.expand_path(path)).shift raise "Did not find file #{path}" unless bookmark_file db = SQLite3::Database.new(path) import = db.execute(QUERY_STRING) end
[ "def", "read", "bookmark_file", "=", "Dir", ".", "glob", "(", "File", ".", "expand_path", "(", "path", ")", ")", ".", "shift", "raise", "\"Did not find file #{path}\"", "unless", "bookmark_file", "db", "=", "SQLite3", "::", "Database", ".", "new", "(", "path", ")", "import", "=", "db", ".", "execute", "(", "QUERY_STRING", ")", "end" ]
Reads the links from the Firefox database places.sqlite
[ "Reads", "the", "links", "from", "the", "Firefox", "database", "places", ".", "sqlite" ]
941ee2045c946daa1e0db394eb643aa82c1254cc
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/firefox.rb#L14-L21
9,434
sugaryourcoffee/syclink
lib/syclink/firefox.rb
SycLink.Firefox.rows
def rows read.map do |row| a = row[0]; b = row[1]; c = row[2]; d = row[3]; e = row[4]; f = row[5] [a, b || c, (d || '').gsub("\n", ' '), [e, f].join(',').gsub(/^,|,$/, '')] end end
ruby
def rows read.map do |row| a = row[0]; b = row[1]; c = row[2]; d = row[3]; e = row[4]; f = row[5] [a, b || c, (d || '').gsub("\n", ' '), [e, f].join(',').gsub(/^,|,$/, '')] end end
[ "def", "rows", "read", ".", "map", "do", "|", "row", "|", "a", "=", "row", "[", "0", "]", ";", "b", "=", "row", "[", "1", "]", ";", "c", "=", "row", "[", "2", "]", ";", "d", "=", "row", "[", "3", "]", ";", "e", "=", "row", "[", "4", "]", ";", "f", "=", "row", "[", "5", "]", "[", "a", ",", "b", "||", "c", ",", "(", "d", "||", "''", ")", ".", "gsub", "(", "\"\\n\"", ",", "' '", ")", ",", "[", "e", ",", "f", "]", ".", "join", "(", "','", ")", ".", "gsub", "(", "/", "/", ",", "''", ")", "]", "end", "end" ]
Returns row values in Arrays
[ "Returns", "row", "values", "in", "Arrays" ]
941ee2045c946daa1e0db394eb643aa82c1254cc
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/firefox.rb#L24-L32
9,435
linrock/favicon_party
lib/favicon_party/image.rb
FaviconParty.Image.to_png
def to_png return @png_data if !@png_data.nil? image = minimagick_image image.resize '16x16!' image.format 'png' image.strip @png_data = image.to_blob raise FaviconParty::InvalidData.new("Empty png") if @png_data.empty? @png_data end
ruby
def to_png return @png_data if !@png_data.nil? image = minimagick_image image.resize '16x16!' image.format 'png' image.strip @png_data = image.to_blob raise FaviconParty::InvalidData.new("Empty png") if @png_data.empty? @png_data end
[ "def", "to_png", "return", "@png_data", "if", "!", "@png_data", ".", "nil?", "image", "=", "minimagick_image", "image", ".", "resize", "'16x16!'", "image", ".", "format", "'png'", "image", ".", "strip", "@png_data", "=", "image", ".", "to_blob", "raise", "FaviconParty", "::", "InvalidData", ".", "new", "(", "\"Empty png\"", ")", "if", "@png_data", ".", "empty?", "@png_data", "end" ]
Export source_data as a 16x16 png
[ "Export", "source_data", "as", "a", "16x16", "png" ]
645d3c6f4a7152bf705ac092976a74f405f83ca1
https://github.com/linrock/favicon_party/blob/645d3c6f4a7152bf705ac092976a74f405f83ca1/lib/favicon_party/image.rb#L106-L115
9,436
ossuarium/palimpsest
lib/palimpsest/repo.rb
Palimpsest.Repo.extract_repo
def extract_repo(path, destination, reference) fail 'Git not installed' unless Utils.command? 'git' Dir.chdir path do system "git archive #{reference} | tar -x -C #{destination}" end end
ruby
def extract_repo(path, destination, reference) fail 'Git not installed' unless Utils.command? 'git' Dir.chdir path do system "git archive #{reference} | tar -x -C #{destination}" end end
[ "def", "extract_repo", "(", "path", ",", "destination", ",", "reference", ")", "fail", "'Git not installed'", "unless", "Utils", ".", "command?", "'git'", "Dir", ".", "chdir", "path", "do", "system", "\"git archive #{reference} | tar -x -C #{destination}\"", "end", "end" ]
Extract repository files at a particular reference to directory.
[ "Extract", "repository", "files", "at", "a", "particular", "reference", "to", "directory", "." ]
7a1d45d33ec7ed878e2b761150ec163ce2125274
https://github.com/ossuarium/palimpsest/blob/7a1d45d33ec7ed878e2b761150ec163ce2125274/lib/palimpsest/repo.rb#L82-L87
9,437
medcat/breadcrumb_trail
lib/breadcrumb_trail/builder.rb
BreadcrumbTrail.BlockBuilder.call
def call buffer = ActiveSupport::SafeBuffer.new @breadcrumbs.each do |breadcrumb| buffer << @block.call(breadcrumb.computed(@context)) end buffer end
ruby
def call buffer = ActiveSupport::SafeBuffer.new @breadcrumbs.each do |breadcrumb| buffer << @block.call(breadcrumb.computed(@context)) end buffer end
[ "def", "call", "buffer", "=", "ActiveSupport", "::", "SafeBuffer", ".", "new", "@breadcrumbs", ".", "each", "do", "|", "breadcrumb", "|", "buffer", "<<", "@block", ".", "call", "(", "breadcrumb", ".", "computed", "(", "@context", ")", ")", "end", "buffer", "end" ]
Creates a buffer, and iterates over every breadcrumb, yielding the breadcrumb to the block given on initialization. @return [String]
[ "Creates", "a", "buffer", "and", "iterates", "over", "every", "breadcrumb", "yielding", "the", "breadcrumb", "to", "the", "block", "given", "on", "initialization", "." ]
02803a8a3f2492bf6e23d97873b3b906ee95d0b9
https://github.com/medcat/breadcrumb_trail/blob/02803a8a3f2492bf6e23d97873b3b906ee95d0b9/lib/breadcrumb_trail/builder.rb#L43-L50
9,438
medcat/breadcrumb_trail
lib/breadcrumb_trail/builder.rb
BreadcrumbTrail.HTMLBuilder.call
def call outer_tag = @options.fetch(:outer, "ol") inner_tag = @options.fetch(:inner, "li") outer = tag(outer_tag, @options.fetch(:outer_options, nil), true) if outer_tag inner = tag(inner_tag, @options.fetch(:inner_options, nil), true) if inner_tag buffer = ActiveSupport::SafeBuffer.new buffer.safe_concat(outer) if outer_tag @breadcrumbs.each do |breadcrumb| buffer.safe_concat(inner) if inner_tag buffer << link_to(breadcrumb.computed_name(@context), breadcrumb.computed_path(@context), breadcrumb.options) buffer.safe_concat("</#{inner_tag}>") if inner_tag end buffer.safe_concat("</#{outer_tag}>") if outer_tag buffer end
ruby
def call outer_tag = @options.fetch(:outer, "ol") inner_tag = @options.fetch(:inner, "li") outer = tag(outer_tag, @options.fetch(:outer_options, nil), true) if outer_tag inner = tag(inner_tag, @options.fetch(:inner_options, nil), true) if inner_tag buffer = ActiveSupport::SafeBuffer.new buffer.safe_concat(outer) if outer_tag @breadcrumbs.each do |breadcrumb| buffer.safe_concat(inner) if inner_tag buffer << link_to(breadcrumb.computed_name(@context), breadcrumb.computed_path(@context), breadcrumb.options) buffer.safe_concat("</#{inner_tag}>") if inner_tag end buffer.safe_concat("</#{outer_tag}>") if outer_tag buffer end
[ "def", "call", "outer_tag", "=", "@options", ".", "fetch", "(", ":outer", ",", "\"ol\"", ")", "inner_tag", "=", "@options", ".", "fetch", "(", ":inner", ",", "\"li\"", ")", "outer", "=", "tag", "(", "outer_tag", ",", "@options", ".", "fetch", "(", ":outer_options", ",", "nil", ")", ",", "true", ")", "if", "outer_tag", "inner", "=", "tag", "(", "inner_tag", ",", "@options", ".", "fetch", "(", ":inner_options", ",", "nil", ")", ",", "true", ")", "if", "inner_tag", "buffer", "=", "ActiveSupport", "::", "SafeBuffer", ".", "new", "buffer", ".", "safe_concat", "(", "outer", ")", "if", "outer_tag", "@breadcrumbs", ".", "each", "do", "|", "breadcrumb", "|", "buffer", ".", "safe_concat", "(", "inner", ")", "if", "inner_tag", "buffer", "<<", "link_to", "(", "breadcrumb", ".", "computed_name", "(", "@context", ")", ",", "breadcrumb", ".", "computed_path", "(", "@context", ")", ",", "breadcrumb", ".", "options", ")", "buffer", ".", "safe_concat", "(", "\"</#{inner_tag}>\"", ")", "if", "inner_tag", "end", "buffer", ".", "safe_concat", "(", "\"</#{outer_tag}>\"", ")", "if", "outer_tag", "buffer", "end" ]
Renders the breadcrumbs in HTML tags. If no options were provided on initialization, it uses defaults. @option @options [String] :outer ("ol") The outer tag element to use. @option @options [String] :inner ("li") The inner tag element to use. @option @options [Hash] :outer_options (nil) The outer tag element attributes to use. Things like `class="some-class"` are best placed here. @option @options [Hash] :inner_options (nil) The inner tag element attributes to use. Things like `class="some-class"` are best placed here. @return [String]
[ "Renders", "the", "breadcrumbs", "in", "HTML", "tags", ".", "If", "no", "options", "were", "provided", "on", "initialization", "it", "uses", "defaults", "." ]
02803a8a3f2492bf6e23d97873b3b906ee95d0b9
https://github.com/medcat/breadcrumb_trail/blob/02803a8a3f2492bf6e23d97873b3b906ee95d0b9/lib/breadcrumb_trail/builder.rb#L72-L95
9,439
shanna/swift
lib/swift/fiber_connection_pool.rb
Swift.FiberConnectionPool.acquire
def acquire id, fiber if conn = @available.pop @reserved[id] = conn else Fiber.yield @pending.push(fiber) acquire(id, fiber) end end
ruby
def acquire id, fiber if conn = @available.pop @reserved[id] = conn else Fiber.yield @pending.push(fiber) acquire(id, fiber) end end
[ "def", "acquire", "id", ",", "fiber", "if", "conn", "=", "@available", ".", "pop", "@reserved", "[", "id", "]", "=", "conn", "else", "Fiber", ".", "yield", "@pending", ".", "push", "(", "fiber", ")", "acquire", "(", "id", ",", "fiber", ")", "end", "end" ]
Acquire a lock on a connection and assign it to executing fiber - if connection is available, pass it back to the calling block - if pool is full, yield the current fiber until connection is available
[ "Acquire", "a", "lock", "on", "a", "connection", "and", "assign", "it", "to", "executing", "fiber", "-", "if", "connection", "is", "available", "pass", "it", "back", "to", "the", "calling", "block", "-", "if", "pool", "is", "full", "yield", "the", "current", "fiber", "until", "connection", "is", "available" ]
c9488d5594da546958ab9cf3602d69d0ca51b021
https://github.com/shanna/swift/blob/c9488d5594da546958ab9cf3602d69d0ca51b021/lib/swift/fiber_connection_pool.rb#L47-L54
9,440
shanna/swift
lib/swift/fiber_connection_pool.rb
Swift.FiberConnectionPool.method_missing
def method_missing method, *args, &blk __reserve__ do |conn| if @trace conn.trace(@trace) {conn.__send__(method, *args, &blk)} else conn.__send__(method, *args, &blk) end end end
ruby
def method_missing method, *args, &blk __reserve__ do |conn| if @trace conn.trace(@trace) {conn.__send__(method, *args, &blk)} else conn.__send__(method, *args, &blk) end end end
[ "def", "method_missing", "method", ",", "*", "args", ",", "&", "blk", "__reserve__", "do", "|", "conn", "|", "if", "@trace", "conn", ".", "trace", "(", "@trace", ")", "{", "conn", ".", "__send__", "(", "method", ",", "args", ",", "blk", ")", "}", "else", "conn", ".", "__send__", "(", "method", ",", "args", ",", "blk", ")", "end", "end", "end" ]
Allow the pool to behave as the underlying connection
[ "Allow", "the", "pool", "to", "behave", "as", "the", "underlying", "connection" ]
c9488d5594da546958ab9cf3602d69d0ca51b021
https://github.com/shanna/swift/blob/c9488d5594da546958ab9cf3602d69d0ca51b021/lib/swift/fiber_connection_pool.rb#L67-L75
9,441
docwhat/lego_nxt
lib/lego_nxt/low_level/usb_connection.rb
LegoNXT::LowLevel.UsbConnection.transmit!
def transmit! bits bytes_sent = @handle.bulk_transfer dataOut: bits, endpoint: USB_ENDPOINT_OUT bytes_sent == bits.length end
ruby
def transmit! bits bytes_sent = @handle.bulk_transfer dataOut: bits, endpoint: USB_ENDPOINT_OUT bytes_sent == bits.length end
[ "def", "transmit!", "bits", "bytes_sent", "=", "@handle", ".", "bulk_transfer", "dataOut", ":", "bits", ",", "endpoint", ":", "USB_ENDPOINT_OUT", "bytes_sent", "==", "bits", ".", "length", "end" ]
Creates a connection to the NXT brick. Sends a packed string of bits. Example: # Causes the brick to beep conn.transmit [0x80, 0x03, 0xf4, 0x01, 0xf4, 0x01].pack('C*')' @see The LEGO MINDSTORMS NXT Communications Protocol (Appendex 1 of the Bluetooth Development Kit) @param {String} bits This must be a binary string. Use `Array#pack('C*')` to generate the string. @return [Boolean] Returns true if all the data was sent and received by the NXT.
[ "Creates", "a", "connection", "to", "the", "NXT", "brick", "." ]
74f6ea3e019bce0be68fa974eaa0a41185b6c4a8
https://github.com/docwhat/lego_nxt/blob/74f6ea3e019bce0be68fa974eaa0a41185b6c4a8/lib/lego_nxt/low_level/usb_connection.rb#L54-L57
9,442
docwhat/lego_nxt
lib/lego_nxt/low_level/usb_connection.rb
LegoNXT::LowLevel.UsbConnection.transceive
def transceive bits raise ::LegoNXT::BadOpCodeError unless bytestring(DirectOps::REQUIRE_RESPONSE, SystemOps::REQUIRE_RESPONSE).include? bits[0] raise ::LegoNXT::TransmitError unless transmit! bits bytes_received = @handle.bulk_transfer dataIn: 64, endpoint: USB_ENDPOINT_IN return bytes_received end
ruby
def transceive bits raise ::LegoNXT::BadOpCodeError unless bytestring(DirectOps::REQUIRE_RESPONSE, SystemOps::REQUIRE_RESPONSE).include? bits[0] raise ::LegoNXT::TransmitError unless transmit! bits bytes_received = @handle.bulk_transfer dataIn: 64, endpoint: USB_ENDPOINT_IN return bytes_received end
[ "def", "transceive", "bits", "raise", "::", "LegoNXT", "::", "BadOpCodeError", "unless", "bytestring", "(", "DirectOps", "::", "REQUIRE_RESPONSE", ",", "SystemOps", "::", "REQUIRE_RESPONSE", ")", ".", "include?", "bits", "[", "0", "]", "raise", "::", "LegoNXT", "::", "TransmitError", "unless", "transmit!", "bits", "bytes_received", "=", "@handle", ".", "bulk_transfer", "dataIn", ":", "64", ",", "endpoint", ":", "USB_ENDPOINT_IN", "return", "bytes_received", "end" ]
Sends a packet string of bits and then receives a result. Example: # Causes the brick to beep conn.transceive [0x80, 0x03, 0xf4, 0x01, 0xf4, 0x01].pack('C*')' @see The LEGO MINDSTORMS NXT Communications Protocol (Appendex 1 of the Bluetooth Development Kit) @param {String} bits This must be a binary string. Use `Array#pack('C*')` to generate the string. @raise {LegoNXT::TransmitError} Raised if the {#transmit} fails. @return [String] A packed string of the response bits. Use `String#unpack('C*')`.
[ "Sends", "a", "packet", "string", "of", "bits", "and", "then", "receives", "a", "result", "." ]
74f6ea3e019bce0be68fa974eaa0a41185b6c4a8
https://github.com/docwhat/lego_nxt/blob/74f6ea3e019bce0be68fa974eaa0a41185b6c4a8/lib/lego_nxt/low_level/usb_connection.rb#L83-L88
9,443
docwhat/lego_nxt
lib/lego_nxt/low_level/usb_connection.rb
LegoNXT::LowLevel.UsbConnection.open
def open context = LIBUSB::Context.new device = context.devices(:idVendor => LEGO_VENDOR_ID, :idProduct => NXT_PRODUCT_ID).first raise ::LegoNXT::NoDeviceError.new("Please make sure the device is plugged in and powered on") if device.nil? @handle = device.open @handle.claim_interface(0) end
ruby
def open context = LIBUSB::Context.new device = context.devices(:idVendor => LEGO_VENDOR_ID, :idProduct => NXT_PRODUCT_ID).first raise ::LegoNXT::NoDeviceError.new("Please make sure the device is plugged in and powered on") if device.nil? @handle = device.open @handle.claim_interface(0) end
[ "def", "open", "context", "=", "LIBUSB", "::", "Context", ".", "new", "device", "=", "context", ".", "devices", "(", ":idVendor", "=>", "LEGO_VENDOR_ID", ",", ":idProduct", "=>", "NXT_PRODUCT_ID", ")", ".", "first", "raise", "::", "LegoNXT", "::", "NoDeviceError", ".", "new", "(", "\"Please make sure the device is plugged in and powered on\"", ")", "if", "device", ".", "nil?", "@handle", "=", "device", ".", "open", "@handle", ".", "claim_interface", "(", "0", ")", "end" ]
Opens the connection This is triggered automatically by intantiating the object. @return [nil]
[ "Opens", "the", "connection" ]
74f6ea3e019bce0be68fa974eaa0a41185b6c4a8
https://github.com/docwhat/lego_nxt/blob/74f6ea3e019bce0be68fa974eaa0a41185b6c4a8/lib/lego_nxt/low_level/usb_connection.rb#L107-L113
9,444
starpeak/gricer
app/controllers/gricer/requests_controller.rb
Gricer.RequestsController.handle_special_fields
def handle_special_fields if ['referer_host', 'referer_path', 'referer_params', 'search_engine', 'search_query'].include?(params[:field]) @items = @items.only_first_in_session end if ['search_engine', 'search_query'].include?(params[:field]) @items = @items.without_nil_in params[:field] end if params[:field] == 'entry_path' params[:field] = 'path' @items = @items.only_first_in_session end super end
ruby
def handle_special_fields if ['referer_host', 'referer_path', 'referer_params', 'search_engine', 'search_query'].include?(params[:field]) @items = @items.only_first_in_session end if ['search_engine', 'search_query'].include?(params[:field]) @items = @items.without_nil_in params[:field] end if params[:field] == 'entry_path' params[:field] = 'path' @items = @items.only_first_in_session end super end
[ "def", "handle_special_fields", "if", "[", "'referer_host'", ",", "'referer_path'", ",", "'referer_params'", ",", "'search_engine'", ",", "'search_query'", "]", ".", "include?", "(", "params", "[", ":field", "]", ")", "@items", "=", "@items", ".", "only_first_in_session", "end", "if", "[", "'search_engine'", ",", "'search_query'", "]", ".", "include?", "(", "params", "[", ":field", "]", ")", "@items", "=", "@items", ".", "without_nil_in", "params", "[", ":field", "]", "end", "if", "params", "[", ":field", "]", "==", "'entry_path'", "params", "[", ":field", "]", "=", "'path'", "@items", "=", "@items", ".", "only_first_in_session", "end", "super", "end" ]
Handle special fields
[ "Handle", "special", "fields" ]
46bb77bd4fc7074ce294d0310ad459fef068f507
https://github.com/starpeak/gricer/blob/46bb77bd4fc7074ce294d0310ad459fef068f507/app/controllers/gricer/requests_controller.rb#L12-L27
9,445
johnwunder/stix_schema_spy
lib/stix_schema_spy/models/node.rb
StixSchemaSpy.Node.referenced_element
def referenced_element ref = @xml.attributes['ref'].value @referenced_element ||= if ref =~ /:/ prefix, element = ref.split(':') schema.find_element(element) || schema.find_attribute("@#{element}") if schema = Schema.find(prefix) else self.schema.find_element(ref) || self.schema.find_attribute("@#{ref}") end end
ruby
def referenced_element ref = @xml.attributes['ref'].value @referenced_element ||= if ref =~ /:/ prefix, element = ref.split(':') schema.find_element(element) || schema.find_attribute("@#{element}") if schema = Schema.find(prefix) else self.schema.find_element(ref) || self.schema.find_attribute("@#{ref}") end end
[ "def", "referenced_element", "ref", "=", "@xml", ".", "attributes", "[", "'ref'", "]", ".", "value", "@referenced_element", "||=", "if", "ref", "=~", "/", "/", "prefix", ",", "element", "=", "ref", ".", "split", "(", "':'", ")", "schema", ".", "find_element", "(", "element", ")", "||", "schema", ".", "find_attribute", "(", "\"@#{element}\"", ")", "if", "schema", "=", "Schema", ".", "find", "(", "prefix", ")", "else", "self", ".", "schema", ".", "find_element", "(", "ref", ")", "||", "self", ".", "schema", ".", "find_attribute", "(", "\"@#{ref}\"", ")", "end", "end" ]
Only valid if this is a reference. Also works for attributes, this was a crappy name
[ "Only", "valid", "if", "this", "is", "a", "reference", ".", "Also", "works", "for", "attributes", "this", "was", "a", "crappy", "name" ]
2d551c6854d749eb330340e69f73baee1c4b52d3
https://github.com/johnwunder/stix_schema_spy/blob/2d551c6854d749eb330340e69f73baee1c4b52d3/lib/stix_schema_spy/models/node.rb#L58-L66
9,446
maxim/has_price
lib/has_price/price_builder.rb
HasPrice.PriceBuilder.item
def item(price, item_name) @current_nesting_level[item_name.to_s] = price.respond_to?(:to_hash) ? price.to_hash : price.to_i end
ruby
def item(price, item_name) @current_nesting_level[item_name.to_s] = price.respond_to?(:to_hash) ? price.to_hash : price.to_i end
[ "def", "item", "(", "price", ",", "item_name", ")", "@current_nesting_level", "[", "item_name", ".", "to_s", "]", "=", "price", ".", "respond_to?", "(", ":to_hash", ")", "?", "price", ".", "to_hash", ":", "price", ".", "to_i", "end" ]
Creates PriceBuilder on a target object. @param [Object] object the target object on which price is being built. Adds price item to the current nesting level of price definition. @param [#to_hash, #to_i] price an integer representing amount for this price item. Alternatively, anything that responds to #to_hash can be used, and will be treated as a group named with item_name. @param [#to_s] item_name name for the provided price item or group. @see #group
[ "Creates", "PriceBuilder", "on", "a", "target", "object", "." ]
671c5c7463b0e6540cbb8ac3114da08b99c697bd
https://github.com/maxim/has_price/blob/671c5c7463b0e6540cbb8ac3114da08b99c697bd/lib/has_price/price_builder.rb#L22-L24
9,447
maxim/has_price
lib/has_price/price_builder.rb
HasPrice.PriceBuilder.group
def group(group_name, &block) group_key = group_name.to_s @current_nesting_level[group_key] ||= {} if block_given? within_group(group_key) do instance_eval &block end end end
ruby
def group(group_name, &block) group_key = group_name.to_s @current_nesting_level[group_key] ||= {} if block_given? within_group(group_key) do instance_eval &block end end end
[ "def", "group", "(", "group_name", ",", "&", "block", ")", "group_key", "=", "group_name", ".", "to_s", "@current_nesting_level", "[", "group_key", "]", "||=", "{", "}", "if", "block_given?", "within_group", "(", "group_key", ")", "do", "instance_eval", "block", "end", "end", "end" ]
Adds price group to the current nesting level of price definition. Groups are useful for price breakdown categorization and easy subtotal values. @example Using group subtotals class Product include HasPrice def base_price; 100 end def federal_tax; 15 end def state_tax; 10 end has_price do item base_price, "base" group "tax" do item federal_tax, "federal" item state_tax, "state" end end end @product = Product.new @product.price.total # => 125 @product.price.tax.total # => 25 @param [#to_s] group_name a name for the price group @yield The yielded block is executed within the group, such that all groups and items declared within the block appear nested under this group. This behavior is recursive. @see #item
[ "Adds", "price", "group", "to", "the", "current", "nesting", "level", "of", "price", "definition", ".", "Groups", "are", "useful", "for", "price", "breakdown", "categorization", "and", "easy", "subtotal", "values", "." ]
671c5c7463b0e6540cbb8ac3114da08b99c697bd
https://github.com/maxim/has_price/blob/671c5c7463b0e6540cbb8ac3114da08b99c697bd/lib/has_price/price_builder.rb#L55-L65
9,448
fissionxuiptz/kat
lib/kat/search.rb
Kat.Search.query=
def query=(search_term) @search_term = case search_term when nil, '' then [] when String, Symbol then [search_term] when Array then search_term.flatten.select { |e| [String, Symbol].include? e.class } else fail ArgumentError, 'search_term must be a String, Symbol or Array. ' \ "#{ search_term.inspect } given." end build_query end
ruby
def query=(search_term) @search_term = case search_term when nil, '' then [] when String, Symbol then [search_term] when Array then search_term.flatten.select { |e| [String, Symbol].include? e.class } else fail ArgumentError, 'search_term must be a String, Symbol or Array. ' \ "#{ search_term.inspect } given." end build_query end
[ "def", "query", "=", "(", "search_term", ")", "@search_term", "=", "case", "search_term", "when", "nil", ",", "''", "then", "[", "]", "when", "String", ",", "Symbol", "then", "[", "search_term", "]", "when", "Array", "then", "search_term", ".", "flatten", ".", "select", "{", "|", "e", "|", "[", "String", ",", "Symbol", "]", ".", "include?", "e", ".", "class", "}", "else", "fail", "ArgumentError", ",", "'search_term must be a String, Symbol or Array. '", "\"#{ search_term.inspect } given.\"", "end", "build_query", "end" ]
Change the search term, triggering a query rebuild and clearing past results. Raises ArgumentError if search_term is not a String, Symbol or Array
[ "Change", "the", "search", "term", "triggering", "a", "query", "rebuild", "and", "clearing", "past", "results", "." ]
8f9e43c5dbeb2462e00fd841c208764380f6983b
https://github.com/fissionxuiptz/kat/blob/8f9e43c5dbeb2462e00fd841c208764380f6983b/lib/kat/search.rb#L97-L108
9,449
fissionxuiptz/kat
lib/kat/search.rb
Kat.Search.options=
def options=(options) fail ArgumentError, 'options must be a Hash. ' \ "#{ options.inspect } given." unless options.is_a?(Hash) @options.merge! options build_query end
ruby
def options=(options) fail ArgumentError, 'options must be a Hash. ' \ "#{ options.inspect } given." unless options.is_a?(Hash) @options.merge! options build_query end
[ "def", "options", "=", "(", "options", ")", "fail", "ArgumentError", ",", "'options must be a Hash. '", "\"#{ options.inspect } given.\"", "unless", "options", ".", "is_a?", "(", "Hash", ")", "@options", ".", "merge!", "options", "build_query", "end" ]
Change search options with a hash, triggering a query string rebuild and clearing past results. Raises ArgumentError if options is not a Hash
[ "Change", "search", "options", "with", "a", "hash", "triggering", "a", "query", "string", "rebuild", "and", "clearing", "past", "results", "." ]
8f9e43c5dbeb2462e00fd841c208764380f6983b
https://github.com/fissionxuiptz/kat/blob/8f9e43c5dbeb2462e00fd841c208764380f6983b/lib/kat/search.rb#L123-L130
9,450
fissionxuiptz/kat
lib/kat/search.rb
Kat.Search.build_query
def build_query @query = @search_term.dup @pages = -1 @results = [] @query << "\"#{ @options[:exact] }\"" if @options[:exact] @query << @options[:or].join(' OR ') unless @options[:or].nil? or @options[:or].empty? @query += @options[:without].map { |s| "-#{ s }" } if @options[:without] @query += inputs.select { |k, v| @options[k] }.map { |k, v| "#{ k }:#{ @options[k] }" } @query += checks.select { |k, v| @options[k] }.map { |k, v| "#{ k }:1" } byzantine = selects.select do |k, v| (v[:id].to_s[/^.*_id$/] && @options[k].to_s.to_i > 0) || (v[:id].to_s[/^[^_]+$/] && @options[k]) end @query += byzantine.map { |k, v| "#{ v[:id] }:#{ @options[k] }" } end
ruby
def build_query @query = @search_term.dup @pages = -1 @results = [] @query << "\"#{ @options[:exact] }\"" if @options[:exact] @query << @options[:or].join(' OR ') unless @options[:or].nil? or @options[:or].empty? @query += @options[:without].map { |s| "-#{ s }" } if @options[:without] @query += inputs.select { |k, v| @options[k] }.map { |k, v| "#{ k }:#{ @options[k] }" } @query += checks.select { |k, v| @options[k] }.map { |k, v| "#{ k }:1" } byzantine = selects.select do |k, v| (v[:id].to_s[/^.*_id$/] && @options[k].to_s.to_i > 0) || (v[:id].to_s[/^[^_]+$/] && @options[k]) end @query += byzantine.map { |k, v| "#{ v[:id] }:#{ @options[k] }" } end
[ "def", "build_query", "@query", "=", "@search_term", ".", "dup", "@pages", "=", "-", "1", "@results", "=", "[", "]", "@query", "<<", "\"\\\"#{ @options[:exact] }\\\"\"", "if", "@options", "[", ":exact", "]", "@query", "<<", "@options", "[", ":or", "]", ".", "join", "(", "' OR '", ")", "unless", "@options", "[", ":or", "]", ".", "nil?", "or", "@options", "[", ":or", "]", ".", "empty?", "@query", "+=", "@options", "[", ":without", "]", ".", "map", "{", "|", "s", "|", "\"-#{ s }\"", "}", "if", "@options", "[", ":without", "]", "@query", "+=", "inputs", ".", "select", "{", "|", "k", ",", "v", "|", "@options", "[", "k", "]", "}", ".", "map", "{", "|", "k", ",", "v", "|", "\"#{ k }:#{ @options[k] }\"", "}", "@query", "+=", "checks", ".", "select", "{", "|", "k", ",", "v", "|", "@options", "[", "k", "]", "}", ".", "map", "{", "|", "k", ",", "v", "|", "\"#{ k }:1\"", "}", "byzantine", "=", "selects", ".", "select", "do", "|", "k", ",", "v", "|", "(", "v", "[", ":id", "]", ".", "to_s", "[", "/", "/", "]", "&&", "@options", "[", "k", "]", ".", "to_s", ".", "to_i", ">", "0", ")", "||", "(", "v", "[", ":id", "]", ".", "to_s", "[", "/", "/", "]", "&&", "@options", "[", "k", "]", ")", "end", "@query", "+=", "byzantine", ".", "map", "{", "|", "k", ",", "v", "|", "\"#{ v[:id] }:#{ @options[k] }\"", "}", "end" ]
Clear out the query and rebuild it from the various stored options. Also clears out the results set and sets pages back to -1
[ "Clear", "out", "the", "query", "and", "rebuild", "it", "from", "the", "various", "stored", "options", ".", "Also", "clears", "out", "the", "results", "set", "and", "sets", "pages", "back", "to", "-", "1" ]
8f9e43c5dbeb2462e00fd841c208764380f6983b
https://github.com/fissionxuiptz/kat/blob/8f9e43c5dbeb2462e00fd841c208764380f6983b/lib/kat/search.rb#L283-L301
9,451
fissionxuiptz/kat
lib/kat/search.rb
Kat.Search.results_column
def results_column(name) @results.compact.map do |rs| rs.map { |r| r[name] || r[name[0...-1].intern] } end.flatten end
ruby
def results_column(name) @results.compact.map do |rs| rs.map { |r| r[name] || r[name[0...-1].intern] } end.flatten end
[ "def", "results_column", "(", "name", ")", "@results", ".", "compact", ".", "map", "do", "|", "rs", "|", "rs", ".", "map", "{", "|", "r", "|", "r", "[", "name", "]", "||", "r", "[", "name", "[", "0", "...", "-", "1", "]", ".", "intern", "]", "}", "end", ".", "flatten", "end" ]
Fetch a list of values from the results set given by name
[ "Fetch", "a", "list", "of", "values", "from", "the", "results", "set", "given", "by", "name" ]
8f9e43c5dbeb2462e00fd841c208764380f6983b
https://github.com/fissionxuiptz/kat/blob/8f9e43c5dbeb2462e00fd841c208764380f6983b/lib/kat/search.rb#L306-L310
9,452
NUBIC/aker
lib/aker/user.rb
Aker.User.full_name
def full_name display_name_parts = [first_name, last_name].compact if display_name_parts.empty? username else display_name_parts.join(' ') end end
ruby
def full_name display_name_parts = [first_name, last_name].compact if display_name_parts.empty? username else display_name_parts.join(' ') end end
[ "def", "full_name", "display_name_parts", "=", "[", "first_name", ",", "last_name", "]", ".", "compact", "if", "display_name_parts", ".", "empty?", "username", "else", "display_name_parts", ".", "join", "(", "' '", ")", "end", "end" ]
A display-friendly name for this user. Uses `first_name` and `last_name` if available, otherwise it just uses the username. @return [String]
[ "A", "display", "-", "friendly", "name", "for", "this", "user", ".", "Uses", "first_name", "and", "last_name", "if", "available", "otherwise", "it", "just", "uses", "the", "username", "." ]
ff43606a8812e38f96bbe71b46e7f631cbeacf1c
https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/user.rb#L109-L116
9,453
on-site/Easy-Partials
lib/easy_partials/helper_additions.rb
EasyPartials.HelperAdditions.concat_partial
def concat_partial(partial, *args, &block) rendered = invoke_partial partial, *args, &block concat rendered end
ruby
def concat_partial(partial, *args, &block) rendered = invoke_partial partial, *args, &block concat rendered end
[ "def", "concat_partial", "(", "partial", ",", "*", "args", ",", "&", "block", ")", "rendered", "=", "invoke_partial", "partial", ",", "args", ",", "block", "concat", "rendered", "end" ]
Used to create nice templated "tags" while keeping the html out of our helpers. Additionally, this can be invoked implicitly by invoking the partial as a method with "_" prepended to the name. Invoking the method: <% concat_partial "my_partial", { :var => "value" } do %> <strong>Contents stored as a "body" local</strong> <% end %> Or invoking implicitly: <% _my_partial :var => "value" do %> <strong>Contents stored as a "body" local</strong> <% end %> Note that with the implicit partials the partial will first be searched for locally within the current view directory, and then additional directories defined by the controller level 'additional_partials' method, and finally within the views/shared directory.
[ "Used", "to", "create", "nice", "templated", "tags", "while", "keeping", "the", "html", "out", "of", "our", "helpers", ".", "Additionally", "this", "can", "be", "invoked", "implicitly", "by", "invoking", "the", "partial", "as", "a", "method", "with", "_", "prepended", "to", "the", "name", "." ]
ce4a1a47175dbf135d2a07e8f15f178b2076bbd8
https://github.com/on-site/Easy-Partials/blob/ce4a1a47175dbf135d2a07e8f15f178b2076bbd8/lib/easy_partials/helper_additions.rb#L101-L104
9,454
NUBIC/aker
lib/aker/authorities/static.rb
Aker::Authorities.Static.valid_credentials?
def valid_credentials?(kind, *credentials) found_username = (all_credentials(kind).detect { |c| c[:credentials] == credentials } || {})[:username] @users[found_username] end
ruby
def valid_credentials?(kind, *credentials) found_username = (all_credentials(kind).detect { |c| c[:credentials] == credentials } || {})[:username] @users[found_username] end
[ "def", "valid_credentials?", "(", "kind", ",", "*", "credentials", ")", "found_username", "=", "(", "all_credentials", "(", "kind", ")", ".", "detect", "{", "|", "c", "|", "c", "[", ":credentials", "]", "==", "credentials", "}", "||", "{", "}", ")", "[", ":username", "]", "@users", "[", "found_username", "]", "end" ]
AUTHORITY API IMPLEMENTATION Verifies the credentials against the set provided by calls to {#valid_credentials!} and {#load!}. Supports all kinds. @return [Aker::User, nil]
[ "AUTHORITY", "API", "IMPLEMENTATION" ]
ff43606a8812e38f96bbe71b46e7f631cbeacf1c
https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/authorities/static.rb#L43-L47
9,455
NUBIC/aker
lib/aker/authorities/static.rb
Aker::Authorities.Static.load!
def load!(io) doc = YAML.load(io) return self unless doc (doc["groups"] || {}).each do |portal, top_level_groups| @groups[portal.to_sym] = top_level_groups.collect { |group_data| build_group(group_data) } end (doc["users"] || {}).each do |username, config| attr_keys = config.keys - ["password", "portals", "identifiers"] valid_credentials!(:user, username, config["password"]) do |u| attr_keys.each do |k| begin u.send("#{k}=", config[k]) rescue NoMethodError raise NoMethodError, "#{k} is not a recognized user attribute" end end portal_data = config["portals"] || [] portals_and_groups_from_yaml(portal_data) do |portal, group, affiliate_ids| u.default_portal = portal unless u.default_portal u.in_portal!(portal) if group if affiliate_ids u.in_group!(portal, group, :affiliate_ids => affiliate_ids) else u.in_group!(portal, group) end end end (config["identifiers"] || {}).each do |ident, value| u.identifiers[ident.to_sym] = value end end end self end
ruby
def load!(io) doc = YAML.load(io) return self unless doc (doc["groups"] || {}).each do |portal, top_level_groups| @groups[portal.to_sym] = top_level_groups.collect { |group_data| build_group(group_data) } end (doc["users"] || {}).each do |username, config| attr_keys = config.keys - ["password", "portals", "identifiers"] valid_credentials!(:user, username, config["password"]) do |u| attr_keys.each do |k| begin u.send("#{k}=", config[k]) rescue NoMethodError raise NoMethodError, "#{k} is not a recognized user attribute" end end portal_data = config["portals"] || [] portals_and_groups_from_yaml(portal_data) do |portal, group, affiliate_ids| u.default_portal = portal unless u.default_portal u.in_portal!(portal) if group if affiliate_ids u.in_group!(portal, group, :affiliate_ids => affiliate_ids) else u.in_group!(portal, group) end end end (config["identifiers"] || {}).each do |ident, value| u.identifiers[ident.to_sym] = value end end end self end
[ "def", "load!", "(", "io", ")", "doc", "=", "YAML", ".", "load", "(", "io", ")", "return", "self", "unless", "doc", "(", "doc", "[", "\"groups\"", "]", "||", "{", "}", ")", ".", "each", "do", "|", "portal", ",", "top_level_groups", "|", "@groups", "[", "portal", ".", "to_sym", "]", "=", "top_level_groups", ".", "collect", "{", "|", "group_data", "|", "build_group", "(", "group_data", ")", "}", "end", "(", "doc", "[", "\"users\"", "]", "||", "{", "}", ")", ".", "each", "do", "|", "username", ",", "config", "|", "attr_keys", "=", "config", ".", "keys", "-", "[", "\"password\"", ",", "\"portals\"", ",", "\"identifiers\"", "]", "valid_credentials!", "(", ":user", ",", "username", ",", "config", "[", "\"password\"", "]", ")", "do", "|", "u", "|", "attr_keys", ".", "each", "do", "|", "k", "|", "begin", "u", ".", "send", "(", "\"#{k}=\"", ",", "config", "[", "k", "]", ")", "rescue", "NoMethodError", "raise", "NoMethodError", ",", "\"#{k} is not a recognized user attribute\"", "end", "end", "portal_data", "=", "config", "[", "\"portals\"", "]", "||", "[", "]", "portals_and_groups_from_yaml", "(", "portal_data", ")", "do", "|", "portal", ",", "group", ",", "affiliate_ids", "|", "u", ".", "default_portal", "=", "portal", "unless", "u", ".", "default_portal", "u", ".", "in_portal!", "(", "portal", ")", "if", "group", "if", "affiliate_ids", "u", ".", "in_group!", "(", "portal", ",", "group", ",", ":affiliate_ids", "=>", "affiliate_ids", ")", "else", "u", ".", "in_group!", "(", "portal", ",", "group", ")", "end", "end", "end", "(", "config", "[", "\"identifiers\"", "]", "||", "{", "}", ")", ".", "each", "do", "|", "ident", ",", "value", "|", "u", ".", "identifiers", "[", "ident", ".", "to_sym", "]", "=", "value", "end", "end", "end", "self", "end" ]
Loads a YAML doc and uses its contents to initialize the authority's authentication and authorization data. Sample doc: users: wakibbe: # username password: ekibder # password for :user auth (optional) first_name: Warren # any attributes from Aker::User may last_name: Kibbe # be set here identifiers: # identifiers will be loaded with employee_id: 4 # symbolized keys portals: # portal & group auth info (optional) - SQLSubmit # A groupless portal - ENU: # A portal with simple groups - User - NOTIS: # A portal with affiliated groups - Manager: [23] - User # you can mix affiliated and simple groups: # groups for hierarchical portals NOTIS: # (these aren't real NOTIS groups) - Admin: - Manager: - User - Auditor @param [#read] io a readable handle (something that can be passed to `YAML.load`) @return [Static] self
[ "Loads", "a", "YAML", "doc", "and", "uses", "its", "contents", "to", "initialize", "the", "authority", "s", "authentication", "and", "authorization", "data", "." ]
ff43606a8812e38f96bbe71b46e7f631cbeacf1c
https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/authorities/static.rb#L204-L245
9,456
jimjh/reaction
lib/reaction/client/client.rb
Reaction.Client.broadcast
def broadcast(name, message, opts={}) # encapsulation encap = { n: name, m: message, t: opts[:to] || /.*/, e: opts[:except] || [] } EM.next_tick { @faye.publish BROADCAST, Base64.urlsafe_encode64(Marshal.dump(encap)) } end
ruby
def broadcast(name, message, opts={}) # encapsulation encap = { n: name, m: message, t: opts[:to] || /.*/, e: opts[:except] || [] } EM.next_tick { @faye.publish BROADCAST, Base64.urlsafe_encode64(Marshal.dump(encap)) } end
[ "def", "broadcast", "(", "name", ",", "message", ",", "opts", "=", "{", "}", ")", "# encapsulation", "encap", "=", "{", "n", ":", "name", ",", "m", ":", "message", ",", "t", ":", "opts", "[", ":to", "]", "||", "/", "/", ",", "e", ":", "opts", "[", ":except", "]", "||", "[", "]", "}", "EM", ".", "next_tick", "{", "@faye", ".", "publish", "BROADCAST", ",", "Base64", ".", "urlsafe_encode64", "(", "Marshal", ".", "dump", "(", "encap", ")", ")", "}", "end" ]
Creates a new reaction client. @param [Faye::Client] client bayeux client @param [String] salt secret salt, used to generate access tokens Publishes message to zero or more channels. @param [String] name controller name @param [String] message message to send @option opts :to can be a regular expression or an array, defaults to all. @option opts :except can be a regular expression or an array, defaults to none.
[ "Creates", "a", "new", "reaction", "client", "." ]
8aff9633dbd177ea536b79f59115a2825b5adf0a
https://github.com/jimjh/reaction/blob/8aff9633dbd177ea536b79f59115a2825b5adf0a/lib/reaction/client/client.rb#L26-L39
9,457
empowerunited/manage
app/helpers/manage/resource_helper.rb
Manage.ResourceHelper.action_link
def action_link(scope, link_data) value = nil case link_data when Proc value = link_data.call(scope) when Hash relation = link_data.keys.first entity = Fields::Reader.field_value(scope, relation) unless entity.present? return '' end if link_data[relation][:label_field].present? value = field_value(scope, link_data[relation][:label_field]) elsif link_data[relation][:label].present? value = link_data[relation][:label] end path = entity.class.name.dasherize.pluralize.downcase return link_to value, [scope.public_send(relation)] when *[Symbol, String] relation = link_data.to_s assocation = scope.class.reflect_on_association(link_data.to_sym) raise "assocation #{link_data} not found on #{scope.class}" unless assocation if assocation.options[:class_name].present? rel_name = scope.class.reflect_on_association(link_data.to_sym).options[:class_name] relation = rel_name.downcase.dasherize.pluralize end if scope.class.reflect_on_association(link_data.to_sym).options[:as].present? key = scope.class.reflect_on_association(link_data.to_sym).options[:as].to_s + '_id' else key = scope.class.name.downcase.dasherize + '_id' end return "<a href=\"#{relation}?f%5B#{key}%5D=#{scope.id}\">#{resource_class.human_attribute_name(link_data.to_s)}</a>".html_safe else raise 'Unsupported link data' end end
ruby
def action_link(scope, link_data) value = nil case link_data when Proc value = link_data.call(scope) when Hash relation = link_data.keys.first entity = Fields::Reader.field_value(scope, relation) unless entity.present? return '' end if link_data[relation][:label_field].present? value = field_value(scope, link_data[relation][:label_field]) elsif link_data[relation][:label].present? value = link_data[relation][:label] end path = entity.class.name.dasherize.pluralize.downcase return link_to value, [scope.public_send(relation)] when *[Symbol, String] relation = link_data.to_s assocation = scope.class.reflect_on_association(link_data.to_sym) raise "assocation #{link_data} not found on #{scope.class}" unless assocation if assocation.options[:class_name].present? rel_name = scope.class.reflect_on_association(link_data.to_sym).options[:class_name] relation = rel_name.downcase.dasherize.pluralize end if scope.class.reflect_on_association(link_data.to_sym).options[:as].present? key = scope.class.reflect_on_association(link_data.to_sym).options[:as].to_s + '_id' else key = scope.class.name.downcase.dasherize + '_id' end return "<a href=\"#{relation}?f%5B#{key}%5D=#{scope.id}\">#{resource_class.human_attribute_name(link_data.to_s)}</a>".html_safe else raise 'Unsupported link data' end end
[ "def", "action_link", "(", "scope", ",", "link_data", ")", "value", "=", "nil", "case", "link_data", "when", "Proc", "value", "=", "link_data", ".", "call", "(", "scope", ")", "when", "Hash", "relation", "=", "link_data", ".", "keys", ".", "first", "entity", "=", "Fields", "::", "Reader", ".", "field_value", "(", "scope", ",", "relation", ")", "unless", "entity", ".", "present?", "return", "''", "end", "if", "link_data", "[", "relation", "]", "[", ":label_field", "]", ".", "present?", "value", "=", "field_value", "(", "scope", ",", "link_data", "[", "relation", "]", "[", ":label_field", "]", ")", "elsif", "link_data", "[", "relation", "]", "[", ":label", "]", ".", "present?", "value", "=", "link_data", "[", "relation", "]", "[", ":label", "]", "end", "path", "=", "entity", ".", "class", ".", "name", ".", "dasherize", ".", "pluralize", ".", "downcase", "return", "link_to", "value", ",", "[", "scope", ".", "public_send", "(", "relation", ")", "]", "when", "[", "Symbol", ",", "String", "]", "relation", "=", "link_data", ".", "to_s", "assocation", "=", "scope", ".", "class", ".", "reflect_on_association", "(", "link_data", ".", "to_sym", ")", "raise", "\"assocation #{link_data} not found on #{scope.class}\"", "unless", "assocation", "if", "assocation", ".", "options", "[", ":class_name", "]", ".", "present?", "rel_name", "=", "scope", ".", "class", ".", "reflect_on_association", "(", "link_data", ".", "to_sym", ")", ".", "options", "[", ":class_name", "]", "relation", "=", "rel_name", ".", "downcase", ".", "dasherize", ".", "pluralize", "end", "if", "scope", ".", "class", ".", "reflect_on_association", "(", "link_data", ".", "to_sym", ")", ".", "options", "[", ":as", "]", ".", "present?", "key", "=", "scope", ".", "class", ".", "reflect_on_association", "(", "link_data", ".", "to_sym", ")", ".", "options", "[", ":as", "]", ".", "to_s", "+", "'_id'", "else", "key", "=", "scope", ".", "class", ".", "name", ".", "downcase", ".", "dasherize", "+", "'_id'", "end", "return", "\"<a href=\\\"#{relation}?f%5B#{key}%5D=#{scope.id}\\\">#{resource_class.human_attribute_name(link_data.to_s)}</a>\"", ".", "html_safe", "else", "raise", "'Unsupported link data'", "end", "end" ]
to customise the actions for a resource define a list of actions example: action_links :posts, :tickets, ->(resource) {link_to "#{resource.name}"} @param scope [type] [description] @param link_data [type] [description] @return [type] [description]
[ "to", "customise", "the", "actions", "for", "a", "resource", "define", "a", "list", "of", "actions" ]
aac8580208513afd180a0fbbc067865deff765fe
https://github.com/empowerunited/manage/blob/aac8580208513afd180a0fbbc067865deff765fe/app/helpers/manage/resource_helper.rb#L34-L74
9,458
binarylogic/addresslogic
lib/addresslogic.rb
Addresslogic.ClassMethods.apply_addresslogic
def apply_addresslogic(options = {}) n = options[:namespace] options[:fields] ||= [ "#{n}street1".to_sym, "#{n}street2".to_sym, ["#{n}city".to_sym, ["#{n}state".to_sym, "#{n}zip".to_sym]], "#{n}country".to_sym ] self.addresslogic_options = options include Addresslogic::InstanceMethods end
ruby
def apply_addresslogic(options = {}) n = options[:namespace] options[:fields] ||= [ "#{n}street1".to_sym, "#{n}street2".to_sym, ["#{n}city".to_sym, ["#{n}state".to_sym, "#{n}zip".to_sym]], "#{n}country".to_sym ] self.addresslogic_options = options include Addresslogic::InstanceMethods end
[ "def", "apply_addresslogic", "(", "options", "=", "{", "}", ")", "n", "=", "options", "[", ":namespace", "]", "options", "[", ":fields", "]", "||=", "[", "\"#{n}street1\"", ".", "to_sym", ",", "\"#{n}street2\"", ".", "to_sym", ",", "[", "\"#{n}city\"", ".", "to_sym", ",", "[", "\"#{n}state\"", ".", "to_sym", ",", "\"#{n}zip\"", ".", "to_sym", "]", "]", ",", "\"#{n}country\"", ".", "to_sym", "]", "self", ".", "addresslogic_options", "=", "options", "include", "Addresslogic", "::", "InstanceMethods", "end" ]
Mixes in useful methods for handling addresses. === Options * <tt>fields:</tt> array of fields (default: [:street1, :street2, [:city, [:state, :zip]], :country]) * <tt>namespace:</tt> prefixes fields names with this, great for use with composed_of in ActiveRecord.
[ "Mixes", "in", "useful", "methods", "for", "handling", "addresses", "." ]
8ba73d6f56ca80d24d4b0c050944d5a06dcc33be
https://github.com/binarylogic/addresslogic/blob/8ba73d6f56ca80d24d4b0c050944d5a06dcc33be/lib/addresslogic.rb#L16-L27
9,459
wwood/yargraph
lib/yargraph.rb
Yargraph.UndirectedGraph.hamiltonian_cycles_dynamic_programming
def hamiltonian_cycles_dynamic_programming(operational_limit=nil) stack = DS::Stack.new return [] if @vertices.empty? origin_vertex = @vertices.to_a[0] hamiltonians = [] num_operations = 0 # This hash keeps track of subproblems that have already been # solved. ie is there a path through vertices that ends in the # endpoint # Hash of [vertex_set,endpoint] => Array of Path objects. # If no path is found, then the key is false # The endpoint is not stored in the vertex set to make the programming # easier. dp_cache = {} # First problem is the whole problem. We get the Hamiltonian paths, # and then after reject those paths that are not cycles. initial_vertex_set = Set.new(@vertices.reject{|v| v==origin_vertex}) initial_problem = [initial_vertex_set, origin_vertex] stack.push initial_problem while next_problem = stack.pop vertices = next_problem[0] destination = next_problem[1] if dp_cache[next_problem] # No need to do anything - problem already solved elsif vertices.empty? # The bottom of the problem. Only return a path # if there is an edge between the destination and the origin # node if edge?(destination, origin_vertex) path = Path.new [destination] dp_cache[next_problem] = [path] else # Reached dead end dp_cache[next_problem] = false end else # This is an unsolved problem and there are at least 2 vertices in the vertex set. # Work out which vertices in the set are neighbours neighs = Set.new neighbours(destination) possibilities = neighs.intersection(vertices) if possibilities.length > 0 # There is still the possibility to go further into this unsolved problem subproblems_unsolved = [] subproblems = [] possibilities.each do |new_destination| new_vertex_set = Set.new(vertices.to_a.reject{|v| v==new_destination}) subproblem = [new_vertex_set, new_destination] subproblems.push subproblem if !dp_cache.key?(subproblem) subproblems_unsolved.push subproblem end end # if solved all the subproblems, then we can make a decision about this problem if subproblems_unsolved.empty? answers = [] subproblems.each do |problem| paths = dp_cache[problem] if paths == false # Nothing to see here else # Add the found sub-paths to the set of answers paths.each do |path| answers.push Path.new(path+[destination]) end end end if answers.empty? # No paths have been found here dp_cache[next_problem] = false else dp_cache[next_problem] = answers end else # More problems to be solved before a decision can be made stack.push next_problem #We have only delayed solving this problem, need to keep going in the future subproblems_unsolved.each do |prob| unless operational_limit.nil? num_operations += 1 raise OperationalLimitReachedException if num_operations > operational_limit end stack.push prob end end else # No neighbours in the set, so reached a dead end, can go no further dp_cache[next_problem] = false end end end if block_given? dp_cache[initial_problem].each do |hpath| yield hpath end return else return dp_cache[initial_problem] end end
ruby
def hamiltonian_cycles_dynamic_programming(operational_limit=nil) stack = DS::Stack.new return [] if @vertices.empty? origin_vertex = @vertices.to_a[0] hamiltonians = [] num_operations = 0 # This hash keeps track of subproblems that have already been # solved. ie is there a path through vertices that ends in the # endpoint # Hash of [vertex_set,endpoint] => Array of Path objects. # If no path is found, then the key is false # The endpoint is not stored in the vertex set to make the programming # easier. dp_cache = {} # First problem is the whole problem. We get the Hamiltonian paths, # and then after reject those paths that are not cycles. initial_vertex_set = Set.new(@vertices.reject{|v| v==origin_vertex}) initial_problem = [initial_vertex_set, origin_vertex] stack.push initial_problem while next_problem = stack.pop vertices = next_problem[0] destination = next_problem[1] if dp_cache[next_problem] # No need to do anything - problem already solved elsif vertices.empty? # The bottom of the problem. Only return a path # if there is an edge between the destination and the origin # node if edge?(destination, origin_vertex) path = Path.new [destination] dp_cache[next_problem] = [path] else # Reached dead end dp_cache[next_problem] = false end else # This is an unsolved problem and there are at least 2 vertices in the vertex set. # Work out which vertices in the set are neighbours neighs = Set.new neighbours(destination) possibilities = neighs.intersection(vertices) if possibilities.length > 0 # There is still the possibility to go further into this unsolved problem subproblems_unsolved = [] subproblems = [] possibilities.each do |new_destination| new_vertex_set = Set.new(vertices.to_a.reject{|v| v==new_destination}) subproblem = [new_vertex_set, new_destination] subproblems.push subproblem if !dp_cache.key?(subproblem) subproblems_unsolved.push subproblem end end # if solved all the subproblems, then we can make a decision about this problem if subproblems_unsolved.empty? answers = [] subproblems.each do |problem| paths = dp_cache[problem] if paths == false # Nothing to see here else # Add the found sub-paths to the set of answers paths.each do |path| answers.push Path.new(path+[destination]) end end end if answers.empty? # No paths have been found here dp_cache[next_problem] = false else dp_cache[next_problem] = answers end else # More problems to be solved before a decision can be made stack.push next_problem #We have only delayed solving this problem, need to keep going in the future subproblems_unsolved.each do |prob| unless operational_limit.nil? num_operations += 1 raise OperationalLimitReachedException if num_operations > operational_limit end stack.push prob end end else # No neighbours in the set, so reached a dead end, can go no further dp_cache[next_problem] = false end end end if block_given? dp_cache[initial_problem].each do |hpath| yield hpath end return else return dp_cache[initial_problem] end end
[ "def", "hamiltonian_cycles_dynamic_programming", "(", "operational_limit", "=", "nil", ")", "stack", "=", "DS", "::", "Stack", ".", "new", "return", "[", "]", "if", "@vertices", ".", "empty?", "origin_vertex", "=", "@vertices", ".", "to_a", "[", "0", "]", "hamiltonians", "=", "[", "]", "num_operations", "=", "0", "# This hash keeps track of subproblems that have already been", "# solved. ie is there a path through vertices that ends in the", "# endpoint", "# Hash of [vertex_set,endpoint] => Array of Path objects.", "# If no path is found, then the key is false", "# The endpoint is not stored in the vertex set to make the programming", "# easier.", "dp_cache", "=", "{", "}", "# First problem is the whole problem. We get the Hamiltonian paths,", "# and then after reject those paths that are not cycles.", "initial_vertex_set", "=", "Set", ".", "new", "(", "@vertices", ".", "reject", "{", "|", "v", "|", "v", "==", "origin_vertex", "}", ")", "initial_problem", "=", "[", "initial_vertex_set", ",", "origin_vertex", "]", "stack", ".", "push", "initial_problem", "while", "next_problem", "=", "stack", ".", "pop", "vertices", "=", "next_problem", "[", "0", "]", "destination", "=", "next_problem", "[", "1", "]", "if", "dp_cache", "[", "next_problem", "]", "# No need to do anything - problem already solved", "elsif", "vertices", ".", "empty?", "# The bottom of the problem. Only return a path", "# if there is an edge between the destination and the origin", "# node", "if", "edge?", "(", "destination", ",", "origin_vertex", ")", "path", "=", "Path", ".", "new", "[", "destination", "]", "dp_cache", "[", "next_problem", "]", "=", "[", "path", "]", "else", "# Reached dead end", "dp_cache", "[", "next_problem", "]", "=", "false", "end", "else", "# This is an unsolved problem and there are at least 2 vertices in the vertex set.", "# Work out which vertices in the set are neighbours", "neighs", "=", "Set", ".", "new", "neighbours", "(", "destination", ")", "possibilities", "=", "neighs", ".", "intersection", "(", "vertices", ")", "if", "possibilities", ".", "length", ">", "0", "# There is still the possibility to go further into this unsolved problem", "subproblems_unsolved", "=", "[", "]", "subproblems", "=", "[", "]", "possibilities", ".", "each", "do", "|", "new_destination", "|", "new_vertex_set", "=", "Set", ".", "new", "(", "vertices", ".", "to_a", ".", "reject", "{", "|", "v", "|", "v", "==", "new_destination", "}", ")", "subproblem", "=", "[", "new_vertex_set", ",", "new_destination", "]", "subproblems", ".", "push", "subproblem", "if", "!", "dp_cache", ".", "key?", "(", "subproblem", ")", "subproblems_unsolved", ".", "push", "subproblem", "end", "end", "# if solved all the subproblems, then we can make a decision about this problem", "if", "subproblems_unsolved", ".", "empty?", "answers", "=", "[", "]", "subproblems", ".", "each", "do", "|", "problem", "|", "paths", "=", "dp_cache", "[", "problem", "]", "if", "paths", "==", "false", "# Nothing to see here", "else", "# Add the found sub-paths to the set of answers", "paths", ".", "each", "do", "|", "path", "|", "answers", ".", "push", "Path", ".", "new", "(", "path", "+", "[", "destination", "]", ")", "end", "end", "end", "if", "answers", ".", "empty?", "# No paths have been found here", "dp_cache", "[", "next_problem", "]", "=", "false", "else", "dp_cache", "[", "next_problem", "]", "=", "answers", "end", "else", "# More problems to be solved before a decision can be made", "stack", ".", "push", "next_problem", "#We have only delayed solving this problem, need to keep going in the future", "subproblems_unsolved", ".", "each", "do", "|", "prob", "|", "unless", "operational_limit", ".", "nil?", "num_operations", "+=", "1", "raise", "OperationalLimitReachedException", "if", "num_operations", ">", "operational_limit", "end", "stack", ".", "push", "prob", "end", "end", "else", "# No neighbours in the set, so reached a dead end, can go no further", "dp_cache", "[", "next_problem", "]", "=", "false", "end", "end", "end", "if", "block_given?", "dp_cache", "[", "initial_problem", "]", ".", "each", "do", "|", "hpath", "|", "yield", "hpath", "end", "return", "else", "return", "dp_cache", "[", "initial_problem", "]", "end", "end" ]
Use dynamic programming to find all the Hamiltonian cycles in this graph
[ "Use", "dynamic", "programming", "to", "find", "all", "the", "Hamiltonian", "cycles", "in", "this", "graph" ]
7991279040f9674cfd3f7b40b056d03fed584a96
https://github.com/wwood/yargraph/blob/7991279040f9674cfd3f7b40b056d03fed584a96/lib/yargraph.rb#L215-L325
9,460
fusor/egon
lib/egon/overcloud/undercloud_handle/node.rb
Overcloud.Node.introspect_node
def introspect_node(node_uuid) workflow = 'tripleo.baremetal.v1.introspect' input = { node_uuids: [node_uuid] } execute_workflow(workflow, input, false) end
ruby
def introspect_node(node_uuid) workflow = 'tripleo.baremetal.v1.introspect' input = { node_uuids: [node_uuid] } execute_workflow(workflow, input, false) end
[ "def", "introspect_node", "(", "node_uuid", ")", "workflow", "=", "'tripleo.baremetal.v1.introspect'", "input", "=", "{", "node_uuids", ":", "[", "node_uuid", "]", "}", "execute_workflow", "(", "workflow", ",", "input", ",", "false", ")", "end" ]
THESE METHODS ARE TEMPORARY UNTIL IRONIC-DISCOVERD IS ADDED TO OPENSTACK AND KEYSTONE
[ "THESE", "METHODS", "ARE", "TEMPORARY", "UNTIL", "IRONIC", "-", "DISCOVERD", "IS", "ADDED", "TO", "OPENSTACK", "AND", "KEYSTONE" ]
e3a57d8748964989b7a0aacd2be4fec4a0a760e4
https://github.com/fusor/egon/blob/e3a57d8748964989b7a0aacd2be4fec4a0a760e4/lib/egon/overcloud/undercloud_handle/node.rb#L152-L156
9,461
Mordorreal/SiteAnalyzer
lib/site_analyzer/site.rb
SiteAnalyzer.Site.add_pages_for_scan!
def add_pages_for_scan! @pages_for_scan = [] @bad_pages = [] @pages.each do |page| @bad_pages << page.page_url unless page.page_a_tags next unless page.page_a_tags page.home_a.each do |link| @pages_for_scan << link end end end
ruby
def add_pages_for_scan! @pages_for_scan = [] @bad_pages = [] @pages.each do |page| @bad_pages << page.page_url unless page.page_a_tags next unless page.page_a_tags page.home_a.each do |link| @pages_for_scan << link end end end
[ "def", "add_pages_for_scan!", "@pages_for_scan", "=", "[", "]", "@bad_pages", "=", "[", "]", "@pages", ".", "each", "do", "|", "page", "|", "@bad_pages", "<<", "page", ".", "page_url", "unless", "page", ".", "page_a_tags", "next", "unless", "page", ".", "page_a_tags", "page", ".", "home_a", ".", "each", "do", "|", "link", "|", "@pages_for_scan", "<<", "link", "end", "end", "end" ]
add pages for scan array, also add bad pages to bad_pages array
[ "add", "pages", "for", "scan", "array", "also", "add", "bad", "pages", "to", "bad_pages", "array" ]
7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb
https://github.com/Mordorreal/SiteAnalyzer/blob/7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb/lib/site_analyzer/site.rb#L41-L51
9,462
Mordorreal/SiteAnalyzer
lib/site_analyzer/site.rb
SiteAnalyzer.Site.add_page
def add_page(url) unless robot_txt_allowed?(url) @scanned_pages << url return nil end page = Page.new(url) @pages << page @scanned_pages << url end
ruby
def add_page(url) unless robot_txt_allowed?(url) @scanned_pages << url return nil end page = Page.new(url) @pages << page @scanned_pages << url end
[ "def", "add_page", "(", "url", ")", "unless", "robot_txt_allowed?", "(", "url", ")", "@scanned_pages", "<<", "url", "return", "nil", "end", "page", "=", "Page", ".", "new", "(", "url", ")", "@pages", "<<", "page", "@scanned_pages", "<<", "url", "end" ]
create Page and add to to site
[ "create", "Page", "and", "add", "to", "to", "site" ]
7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb
https://github.com/Mordorreal/SiteAnalyzer/blob/7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb/lib/site_analyzer/site.rb#L53-L61
9,463
Mordorreal/SiteAnalyzer
lib/site_analyzer/site.rb
SiteAnalyzer.Site.all_titles
def all_titles result = [] @pages.each do |page| result << [page.page_url, page.all_titles] if page.page_a_tags end result end
ruby
def all_titles result = [] @pages.each do |page| result << [page.page_url, page.all_titles] if page.page_a_tags end result end
[ "def", "all_titles", "result", "=", "[", "]", "@pages", ".", "each", "do", "|", "page", "|", "result", "<<", "[", "page", ".", "page_url", ",", "page", ".", "all_titles", "]", "if", "page", ".", "page_a_tags", "end", "result", "end" ]
get all titles on site and return array of them
[ "get", "all", "titles", "on", "site", "and", "return", "array", "of", "them" ]
7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb
https://github.com/Mordorreal/SiteAnalyzer/blob/7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb/lib/site_analyzer/site.rb#L63-L69
9,464
Mordorreal/SiteAnalyzer
lib/site_analyzer/site.rb
SiteAnalyzer.Site.all_descriptions
def all_descriptions result = [] @pages.each do |page| result << [page.page_url, page.meta_desc_content] if page.page_a_tags end result end
ruby
def all_descriptions result = [] @pages.each do |page| result << [page.page_url, page.meta_desc_content] if page.page_a_tags end result end
[ "def", "all_descriptions", "result", "=", "[", "]", "@pages", ".", "each", "do", "|", "page", "|", "result", "<<", "[", "page", ".", "page_url", ",", "page", ".", "meta_desc_content", "]", "if", "page", ".", "page_a_tags", "end", "result", "end" ]
get all meta description tags content and return it as array
[ "get", "all", "meta", "description", "tags", "content", "and", "return", "it", "as", "array" ]
7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb
https://github.com/Mordorreal/SiteAnalyzer/blob/7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb/lib/site_analyzer/site.rb#L71-L77
9,465
Mordorreal/SiteAnalyzer
lib/site_analyzer/site.rb
SiteAnalyzer.Site.all_h2
def all_h2 result = [] @pages.each do |page| result << [page.page_url, page.h2_text] unless page.page_a_tags end result end
ruby
def all_h2 result = [] @pages.each do |page| result << [page.page_url, page.h2_text] unless page.page_a_tags end result end
[ "def", "all_h2", "result", "=", "[", "]", "@pages", ".", "each", "do", "|", "page", "|", "result", "<<", "[", "page", ".", "page_url", ",", "page", ".", "h2_text", "]", "unless", "page", ".", "page_a_tags", "end", "result", "end" ]
get all h2 tags and return array of it
[ "get", "all", "h2", "tags", "and", "return", "array", "of", "it" ]
7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb
https://github.com/Mordorreal/SiteAnalyzer/blob/7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb/lib/site_analyzer/site.rb#L79-L85
9,466
Mordorreal/SiteAnalyzer
lib/site_analyzer/site.rb
SiteAnalyzer.Site.all_a
def all_a result = [] @pages.each do |page| next unless page.page_a_tags page.page_a_tags.compact.each do |tag| tag[0] = '-' unless tag[0] tag[1] = '-' unless tag[1] tag[2] = '-' unless tag[2] result << [page.page_url, tag[0], tag[1], tag[2]] end end result.compact end
ruby
def all_a result = [] @pages.each do |page| next unless page.page_a_tags page.page_a_tags.compact.each do |tag| tag[0] = '-' unless tag[0] tag[1] = '-' unless tag[1] tag[2] = '-' unless tag[2] result << [page.page_url, tag[0], tag[1], tag[2]] end end result.compact end
[ "def", "all_a", "result", "=", "[", "]", "@pages", ".", "each", "do", "|", "page", "|", "next", "unless", "page", ".", "page_a_tags", "page", ".", "page_a_tags", ".", "compact", ".", "each", "do", "|", "tag", "|", "tag", "[", "0", "]", "=", "'-'", "unless", "tag", "[", "0", "]", "tag", "[", "1", "]", "=", "'-'", "unless", "tag", "[", "1", "]", "tag", "[", "2", "]", "=", "'-'", "unless", "tag", "[", "2", "]", "result", "<<", "[", "page", ".", "page_url", ",", "tag", "[", "0", "]", ",", "tag", "[", "1", "]", ",", "tag", "[", "2", "]", "]", "end", "end", "result", ".", "compact", "end" ]
get all a tags and return array of it
[ "get", "all", "a", "tags", "and", "return", "array", "of", "it" ]
7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb
https://github.com/Mordorreal/SiteAnalyzer/blob/7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb/lib/site_analyzer/site.rb#L87-L99
9,467
Mordorreal/SiteAnalyzer
lib/site_analyzer/site.rb
SiteAnalyzer.Site.convert_to_valid
def convert_to_valid(url) return nil if url =~ /.jpg$/i url.insert(0, @main_url.first(5)) if url.start_with? '//' link = URI(url) main_page = URI(@main_url) if link && link.scheme && link.scheme.empty? link.scheme = main_page.scheme elsif link.nil? return nil end if link.scheme =~ /^http/ request = link.to_s else request = nil end request rescue link end
ruby
def convert_to_valid(url) return nil if url =~ /.jpg$/i url.insert(0, @main_url.first(5)) if url.start_with? '//' link = URI(url) main_page = URI(@main_url) if link && link.scheme && link.scheme.empty? link.scheme = main_page.scheme elsif link.nil? return nil end if link.scheme =~ /^http/ request = link.to_s else request = nil end request rescue link end
[ "def", "convert_to_valid", "(", "url", ")", "return", "nil", "if", "url", "=~", "/", "/i", "url", ".", "insert", "(", "0", ",", "@main_url", ".", "first", "(", "5", ")", ")", "if", "url", ".", "start_with?", "'//'", "link", "=", "URI", "(", "url", ")", "main_page", "=", "URI", "(", "@main_url", ")", "if", "link", "&&", "link", ".", "scheme", "&&", "link", ".", "scheme", ".", "empty?", "link", ".", "scheme", "=", "main_page", ".", "scheme", "elsif", "link", ".", "nil?", "return", "nil", "end", "if", "link", ".", "scheme", "=~", "/", "/", "request", "=", "link", ".", "to_s", "else", "request", "=", "nil", "end", "request", "rescue", "link", "end" ]
check url and try to convert it to valid, remove .jpg links, add scheme to url
[ "check", "url", "and", "try", "to", "convert", "it", "to", "valid", "remove", ".", "jpg", "links", "add", "scheme", "to", "url" ]
7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb
https://github.com/Mordorreal/SiteAnalyzer/blob/7b17f7c1651c2fe85dbc2088c28cf1ec94ffdefb/lib/site_analyzer/site.rb#L115-L133
9,468
anshulverma/sawaal
lib/sawaal/selections.rb
Sawaal.Selections.read_char
def read_char input = $stdin.getch return input unless input == "\e" begin Timeout.timeout(0.01) do input += $stdin.getch input += $stdin.getch end rescue Timeout::Error # ignored end input end
ruby
def read_char input = $stdin.getch return input unless input == "\e" begin Timeout.timeout(0.01) do input += $stdin.getch input += $stdin.getch end rescue Timeout::Error # ignored end input end
[ "def", "read_char", "input", "=", "$stdin", ".", "getch", "return", "input", "unless", "input", "==", "\"\\e\"", "begin", "Timeout", ".", "timeout", "(", "0.01", ")", "do", "input", "+=", "$stdin", ".", "getch", "input", "+=", "$stdin", ".", "getch", "end", "rescue", "Timeout", "::", "Error", "# ignored", "end", "input", "end" ]
Reads keypresses from the user including 2 and 3 escape character sequences.
[ "Reads", "keypresses", "from", "the", "user", "including", "2", "and", "3", "escape", "character", "sequences", "." ]
ccbfc7997024ba7e13e565d778dccb9af80dbb5d
https://github.com/anshulverma/sawaal/blob/ccbfc7997024ba7e13e565d778dccb9af80dbb5d/lib/sawaal/selections.rb#L56-L68
9,469
maxjacobson/todo_lint
lib/todo_lint/reporter.rb
TodoLint.Reporter.number_of_spaces
def number_of_spaces todo.character_number - 1 - (todo.line.length - todo.line.lstrip.length) end
ruby
def number_of_spaces todo.character_number - 1 - (todo.line.length - todo.line.lstrip.length) end
[ "def", "number_of_spaces", "todo", ".", "character_number", "-", "1", "-", "(", "todo", ".", "line", ".", "length", "-", "todo", ".", "line", ".", "lstrip", ".", "length", ")", "end" ]
How many spaces before the carets should there be? @return [Fixnum] @api private
[ "How", "many", "spaces", "before", "the", "carets", "should", "there", "be?" ]
0d1061383ea205ef4c74edc64568e308ac1af990
https://github.com/maxjacobson/todo_lint/blob/0d1061383ea205ef4c74edc64568e308ac1af990/lib/todo_lint/reporter.rb#L71-L73
9,470
shanna/swift
lib/swift/adapter.rb
Swift.Adapter.create
def create record, resources result = [resources].flatten.map do |resource| resource = record.new(resource) unless resource.kind_of?(record) result = execute(command_create(record), *resource.tuple.values_at(*record.header.insertable)) resource.tuple[record.header.serial] = result.insert_id if record.header.serial resource end resources.kind_of?(Array) ? result : result.first end
ruby
def create record, resources result = [resources].flatten.map do |resource| resource = record.new(resource) unless resource.kind_of?(record) result = execute(command_create(record), *resource.tuple.values_at(*record.header.insertable)) resource.tuple[record.header.serial] = result.insert_id if record.header.serial resource end resources.kind_of?(Array) ? result : result.first end
[ "def", "create", "record", ",", "resources", "result", "=", "[", "resources", "]", ".", "flatten", ".", "map", "do", "|", "resource", "|", "resource", "=", "record", ".", "new", "(", "resource", ")", "unless", "resource", ".", "kind_of?", "(", "record", ")", "result", "=", "execute", "(", "command_create", "(", "record", ")", ",", "resource", ".", "tuple", ".", "values_at", "(", "record", ".", "header", ".", "insertable", ")", ")", "resource", ".", "tuple", "[", "record", ".", "header", ".", "serial", "]", "=", "result", ".", "insert_id", "if", "record", ".", "header", ".", "serial", "resource", "end", "resources", ".", "kind_of?", "(", "Array", ")", "?", "result", ":", "result", ".", "first", "end" ]
Create one or more. @example Record. user = User.new(name: 'Apply Arthurton', age: 32) Swift.db.create(User, user) #=> Swift::Record @example Coerce hash to record. Swif.db.create(User, name: 'Apple Arthurton', age: 32) #=> Swift::Record @example Multiple resources. apple = User.new(name: 'Apple Arthurton', age: 32) benny = User.new(name: 'Benny Arthurton', age: 30) Swift.db.create(User, [apple, benny]) #=> Array<Swift::Record> @example Coerce multiple resources. Swift.db.create(User, [{name: 'Apple Arthurton', age: 32}, {name: 'Benny Arthurton', age: 30}]) #=> Array<Swift::Record> @param [Swift::Record] record Concrete record subclass to load. @param [Swift::Record, Hash, Array<Swift::Record, Hash>] resources The resources to be saved. @return [Swift::Record, Array<Swift::Record>] @note Hashes will be coerced into a Swift::Record resource via Swift::Record#new @note Passing a scalar will result in a scalar. @see Swift::Record.create
[ "Create", "one", "or", "more", "." ]
c9488d5594da546958ab9cf3602d69d0ca51b021
https://github.com/shanna/swift/blob/c9488d5594da546958ab9cf3602d69d0ca51b021/lib/swift/adapter.rb#L59-L67
9,471
shanna/swift
lib/swift/adapter.rb
Swift.Adapter.update
def update record, resources result = [resources].flatten.map do |resource| resource = record.new(resource) unless resource.kind_of?(record) keys = resource.tuple.values_at(*record.header.keys) # TODO: Name the key field(s) missing. raise ArgumentError, "#{record} resource has incomplete key: #{resource.inspect}" \ unless keys.select(&:nil?).empty? execute(command_update(record), *resource.tuple.values_at(*record.header.updatable), *keys) resource end resources.kind_of?(Array) ? result : result.first end
ruby
def update record, resources result = [resources].flatten.map do |resource| resource = record.new(resource) unless resource.kind_of?(record) keys = resource.tuple.values_at(*record.header.keys) # TODO: Name the key field(s) missing. raise ArgumentError, "#{record} resource has incomplete key: #{resource.inspect}" \ unless keys.select(&:nil?).empty? execute(command_update(record), *resource.tuple.values_at(*record.header.updatable), *keys) resource end resources.kind_of?(Array) ? result : result.first end
[ "def", "update", "record", ",", "resources", "result", "=", "[", "resources", "]", ".", "flatten", ".", "map", "do", "|", "resource", "|", "resource", "=", "record", ".", "new", "(", "resource", ")", "unless", "resource", ".", "kind_of?", "(", "record", ")", "keys", "=", "resource", ".", "tuple", ".", "values_at", "(", "record", ".", "header", ".", "keys", ")", "# TODO: Name the key field(s) missing.", "raise", "ArgumentError", ",", "\"#{record} resource has incomplete key: #{resource.inspect}\"", "unless", "keys", ".", "select", "(", ":nil?", ")", ".", "empty?", "execute", "(", "command_update", "(", "record", ")", ",", "resource", ".", "tuple", ".", "values_at", "(", "record", ".", "header", ".", "updatable", ")", ",", "keys", ")", "resource", "end", "resources", ".", "kind_of?", "(", "Array", ")", "?", "result", ":", "result", ".", "first", "end" ]
Update one or more. @example Record. user = Swift.db.create(User, name: 'Apply Arthurton', age: 32) user.name = 'Arthur Appleton' Swift.db.update(User, user) #=> Swift::Record @example Coerce hash to record. user = Swift.db.create(User, name: 'Apply Arthurton', age: 32) user.name = 'Arthur Appleton' Swif.db.update(User, user.tuple) #=> Swift::Record @example Multiple resources. apple = Swift.db.create(User, name: 'Apple Arthurton', age: 32) benny = Swift.db.create(User, name: 'Benny Arthurton', age: 30) Swift.db.update(User, [apple, benny]) #=> Array<Swift::Record> @example Coerce multiple resources. apple = Swift.db.create(User, name: 'Apple Arthurton', age: 32) benny = Swift.db.create(User, name: 'Benny Arthurton', age: 30) Swift.db.update(User, [apple.tuple, benny.tuple]) #=> Array<Swift::Record> @param [Swift::Record] record Concrete record subclass to load. @param [Swift::Record, Hash, Array<Swift::Record, Hash>] resources The resources to be updated. @return [Swift::Record, Swift::Result] @note Hashes will be coerced into a Swift::Record resource via Swift::Record#new @note Passing a scalar will result in a scalar. @see Swift::Record#update
[ "Update", "one", "or", "more", "." ]
c9488d5594da546958ab9cf3602d69d0ca51b021
https://github.com/shanna/swift/blob/c9488d5594da546958ab9cf3602d69d0ca51b021/lib/swift/adapter.rb#L98-L111
9,472
shanna/swift
lib/swift/adapter.rb
Swift.Adapter.delete
def delete record, resources result = [resources].flatten.map do |resource| resource = record.new(resource) unless resource.kind_of?(record) keys = resource.tuple.values_at(*record.header.keys) # TODO: Name the key field(s) missing. raise ArgumentError, "#{record} resource has incomplete key: #{resource.inspect}" \ unless keys.select(&:nil?).empty? if result = execute(command_delete(record), *keys) resource.freeze end result end resources.kind_of?(Array) ? result : result.first end
ruby
def delete record, resources result = [resources].flatten.map do |resource| resource = record.new(resource) unless resource.kind_of?(record) keys = resource.tuple.values_at(*record.header.keys) # TODO: Name the key field(s) missing. raise ArgumentError, "#{record} resource has incomplete key: #{resource.inspect}" \ unless keys.select(&:nil?).empty? if result = execute(command_delete(record), *keys) resource.freeze end result end resources.kind_of?(Array) ? result : result.first end
[ "def", "delete", "record", ",", "resources", "result", "=", "[", "resources", "]", ".", "flatten", ".", "map", "do", "|", "resource", "|", "resource", "=", "record", ".", "new", "(", "resource", ")", "unless", "resource", ".", "kind_of?", "(", "record", ")", "keys", "=", "resource", ".", "tuple", ".", "values_at", "(", "record", ".", "header", ".", "keys", ")", "# TODO: Name the key field(s) missing.", "raise", "ArgumentError", ",", "\"#{record} resource has incomplete key: #{resource.inspect}\"", "unless", "keys", ".", "select", "(", ":nil?", ")", ".", "empty?", "if", "result", "=", "execute", "(", "command_delete", "(", "record", ")", ",", "keys", ")", "resource", ".", "freeze", "end", "result", "end", "resources", ".", "kind_of?", "(", "Array", ")", "?", "result", ":", "result", ".", "first", "end" ]
Delete one or more. @example Record. user = Swift.db.create(User, name: 'Apply Arthurton', age: 32) user.name = 'Arthur Appleton' Swift.db.delete(User, user) @example Coerce hash to record. user = Swift.db.create(User, name: 'Apply Arthurton', age: 32) user.name = 'Arthur Appleton' Swif.db.delete(User, user.tuple) @example Multiple resources. apple = Swift.db.create(User, name: 'Apple Arthurton', age: 32) benny = Swift.db.create(User, name: 'Benny Arthurton', age: 30) Swift.db.delete(User, [apple, benny]) @example Coerce multiple resources. apple = Swift.db.create(User, name: 'Apple Arthurton', age: 32) benny = Swift.db.create(User, name: 'Benny Arthurton', age: 30) Swift.db.delete(User, [apple.tuple, benny.tuple]) @param [Swift::Record] record Concrete record subclass to load. @param [Swift::Record, Hash, Array<Swift::Record, Hash>] resources The resources to be deleteed. @return [Swift::Record, Array<Swift::Record>] @note Hashes will be coerced into a Swift::Record resource via Swift::Record#new @note Passing a scalar will result in a scalar. @see Swift::Record#delete
[ "Delete", "one", "or", "more", "." ]
c9488d5594da546958ab9cf3602d69d0ca51b021
https://github.com/shanna/swift/blob/c9488d5594da546958ab9cf3602d69d0ca51b021/lib/swift/adapter.rb#L138-L153
9,473
shanna/swift
lib/swift/adapter.rb
Swift.Adapter.prepare
def prepare record = nil, command record ? Statement.new(record, command) : db.prepare(command) end
ruby
def prepare record = nil, command record ? Statement.new(record, command) : db.prepare(command) end
[ "def", "prepare", "record", "=", "nil", ",", "command", "record", "?", "Statement", ".", "new", "(", "record", ",", "command", ")", ":", "db", ".", "prepare", "(", "command", ")", "end" ]
Create a server side prepared statement @example finder = Swift.db.prepare(User, "select * from users where id > ?") user = finder.execute(1).first user.id @overload prepare(record, command) @param [Swift::Record] record Concrete record subclass to load. @param [String] command Command to be prepared by the underlying concrete adapter. @overload prepare(command) @param [String] command Command to be prepared by the underlying concrete adapter. @return [Swift::Statement, Swift::DB::Mysql::Statement, Swift::DB::Sqlite3::Statement, ...]
[ "Create", "a", "server", "side", "prepared", "statement" ]
c9488d5594da546958ab9cf3602d69d0ca51b021
https://github.com/shanna/swift/blob/c9488d5594da546958ab9cf3602d69d0ca51b021/lib/swift/adapter.rb#L169-L171
9,474
shanna/swift
lib/swift/adapter.rb
Swift.Adapter.execute
def execute command, *bind start = Time.now record, command = command, bind.shift if command.kind_of?(Class) && command < Record record ? Result.new(record, db.execute(command, *bind)) : db.execute(command, *bind) ensure log_command(start, command, bind) if @trace end
ruby
def execute command, *bind start = Time.now record, command = command, bind.shift if command.kind_of?(Class) && command < Record record ? Result.new(record, db.execute(command, *bind)) : db.execute(command, *bind) ensure log_command(start, command, bind) if @trace end
[ "def", "execute", "command", ",", "*", "bind", "start", "=", "Time", ".", "now", "record", ",", "command", "=", "command", ",", "bind", ".", "shift", "if", "command", ".", "kind_of?", "(", "Class", ")", "&&", "command", "<", "Record", "record", "?", "Result", ".", "new", "(", "record", ",", "db", ".", "execute", "(", "command", ",", "bind", ")", ")", ":", "db", ".", "execute", "(", "command", ",", "bind", ")", "ensure", "log_command", "(", "start", ",", "command", ",", "bind", ")", "if", "@trace", "end" ]
Execute a command using the underlying concrete adapter. @example Swift.db.execute("select * from users") @example Swift.db.execute(User, "select * from users where id = ?", 1) @overload execute(record, command, *bind) @param [Swift::Record] record Concrete record subclass to load. @param [String] command Command to be executed by the adapter. @param [*Object] bind Bind values. @overload execute(command, *bind) @param [String] command Command to be executed by the adapter. @param [*Object] bind Bind values. @return [Swift::Result, Swift::DB::Mysql::Result, Swift::DB::Sqlite3::Result, ...]
[ "Execute", "a", "command", "using", "the", "underlying", "concrete", "adapter", "." ]
c9488d5594da546958ab9cf3602d69d0ca51b021
https://github.com/shanna/swift/blob/c9488d5594da546958ab9cf3602d69d0ca51b021/lib/swift/adapter.rb#L214-L220
9,475
fnando/troy
lib/troy/page.rb
Troy.Page.method_missing
def method_missing(name, *args, &block) return meta[name.to_s] if meta.key?(name.to_s) super end
ruby
def method_missing(name, *args, &block) return meta[name.to_s] if meta.key?(name.to_s) super end
[ "def", "method_missing", "(", "name", ",", "*", "args", ",", "&", "block", ")", "return", "meta", "[", "name", ".", "to_s", "]", "if", "meta", ".", "key?", "(", "name", ".", "to_s", ")", "super", "end" ]
Initialize a new page, which can be simply rendered or persisted to the filesystem.
[ "Initialize", "a", "new", "page", "which", "can", "be", "simply", "rendered", "or", "persisted", "to", "the", "filesystem", "." ]
6940116610abef3490da168c31a19fc26840cb99
https://github.com/fnando/troy/blob/6940116610abef3490da168c31a19fc26840cb99/lib/troy/page.rb#L32-L35
9,476
fnando/troy
lib/troy/page.rb
Troy.Page.render
def render ExtensionMatcher.new(path) .default { content } .on("html") { compress render_erb } .on("md") { compress render_erb } .on("erb") { compress render_erb } .match end
ruby
def render ExtensionMatcher.new(path) .default { content } .on("html") { compress render_erb } .on("md") { compress render_erb } .on("erb") { compress render_erb } .match end
[ "def", "render", "ExtensionMatcher", ".", "new", "(", "path", ")", ".", "default", "{", "content", "}", ".", "on", "(", "\"html\"", ")", "{", "compress", "render_erb", "}", ".", "on", "(", "\"md\"", ")", "{", "compress", "render_erb", "}", ".", "on", "(", "\"erb\"", ")", "{", "compress", "render_erb", "}", ".", "match", "end" ]
Render the current page.
[ "Render", "the", "current", "page", "." ]
6940116610abef3490da168c31a19fc26840cb99
https://github.com/fnando/troy/blob/6940116610abef3490da168c31a19fc26840cb99/lib/troy/page.rb#L73-L80
9,477
fnando/troy
lib/troy/page.rb
Troy.Page.save_to
def save_to(path) File.open(path, "w") do |file| I18n.with_locale(meta.locale) do file << render end end end
ruby
def save_to(path) File.open(path, "w") do |file| I18n.with_locale(meta.locale) do file << render end end end
[ "def", "save_to", "(", "path", ")", "File", ".", "open", "(", "path", ",", "\"w\"", ")", "do", "|", "file", "|", "I18n", ".", "with_locale", "(", "meta", ".", "locale", ")", "do", "file", "<<", "render", "end", "end", "end" ]
Save current page to the specified path.
[ "Save", "current", "page", "to", "the", "specified", "path", "." ]
6940116610abef3490da168c31a19fc26840cb99
https://github.com/fnando/troy/blob/6940116610abef3490da168c31a19fc26840cb99/lib/troy/page.rb#L120-L126
9,478
zeevex/zeevex_threadsafe
lib/zeevex_threadsafe/thread_locals.rb
ZeevexThreadsafe::ThreadLocals.InstanceMethods._thread_local_clean
def _thread_local_clean ids = Thread.list.map &:object_id (@_thread_local_threads.keys - ids).each { |key| @_thread_local_threads.delete(key) } end
ruby
def _thread_local_clean ids = Thread.list.map &:object_id (@_thread_local_threads.keys - ids).each { |key| @_thread_local_threads.delete(key) } end
[ "def", "_thread_local_clean", "ids", "=", "Thread", ".", "list", ".", "map", ":object_id", "(", "@_thread_local_threads", ".", "keys", "-", "ids", ")", ".", "each", "{", "|", "key", "|", "@_thread_local_threads", ".", "delete", "(", "key", ")", "}", "end" ]
remove the thread local maps for threads that are no longer active. likely to be painful if many threads are running. must be called manually; otherwise this object may accumulate lots of garbage if it is used from many different threads.
[ "remove", "the", "thread", "local", "maps", "for", "threads", "that", "are", "no", "longer", "active", ".", "likely", "to", "be", "painful", "if", "many", "threads", "are", "running", "." ]
a486da9094204c8fb9007bf7a4668a17f97a1f22
https://github.com/zeevex/zeevex_threadsafe/blob/a486da9094204c8fb9007bf7a4668a17f97a1f22/lib/zeevex_threadsafe/thread_locals.rb#L38-L41
9,479
caruby/core
lib/caruby/helpers/properties.rb
CaRuby.Properties.[]=
def []=(key, value) return super if has_key?(key) alt = alternate_key(key) has_key?(alt) ? super(alt, value) : super end
ruby
def []=(key, value) return super if has_key?(key) alt = alternate_key(key) has_key?(alt) ? super(alt, value) : super end
[ "def", "[]=", "(", "key", ",", "value", ")", "return", "super", "if", "has_key?", "(", "key", ")", "alt", "=", "alternate_key", "(", "key", ")", "has_key?", "(", "alt", ")", "?", "super", "(", "alt", ",", "value", ")", ":", "super", "end" ]
Returns the property value for the key. If there is no key entry but there is an alternate key entry, then alternate key entry is set.
[ "Returns", "the", "property", "value", "for", "the", "key", ".", "If", "there", "is", "no", "key", "entry", "but", "there", "is", "an", "alternate", "key", "entry", "then", "alternate", "key", "entry", "is", "set", "." ]
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/helpers/properties.rb#L47-L51
9,480
caruby/core
lib/caruby/helpers/properties.rb
CaRuby.Properties.load_properties
def load_properties(file) raise ConfigurationError.new("Properties file not found: #{File.expand_path(file)}") unless File.exists?(file) properties = {} begin YAML.load_file(file).each { |key, value| properties[key.to_sym] = value } rescue raise ConfigurationError.new("Could not read properties file #{file}: " + $!) end # Uncomment the following line to print detail properties. #logger.debug { "#{file} properties:\n#{properties.pp_s}" } # parse comma-delimited string values of array properties into arrays @array_properties.each do |key| value = properties[key] if String === value then properties[key] = value.split(/,\s*/) end end # if the key is a merge property key, then perform a deep merge. # otherwise, do a shallow merge of the property value into this property hash. deep, shallow = properties.split { |key, value| @merge_properties.include?(key) } merge!(deep, :deep) merge!(shallow) end
ruby
def load_properties(file) raise ConfigurationError.new("Properties file not found: #{File.expand_path(file)}") unless File.exists?(file) properties = {} begin YAML.load_file(file).each { |key, value| properties[key.to_sym] = value } rescue raise ConfigurationError.new("Could not read properties file #{file}: " + $!) end # Uncomment the following line to print detail properties. #logger.debug { "#{file} properties:\n#{properties.pp_s}" } # parse comma-delimited string values of array properties into arrays @array_properties.each do |key| value = properties[key] if String === value then properties[key] = value.split(/,\s*/) end end # if the key is a merge property key, then perform a deep merge. # otherwise, do a shallow merge of the property value into this property hash. deep, shallow = properties.split { |key, value| @merge_properties.include?(key) } merge!(deep, :deep) merge!(shallow) end
[ "def", "load_properties", "(", "file", ")", "raise", "ConfigurationError", ".", "new", "(", "\"Properties file not found: #{File.expand_path(file)}\"", ")", "unless", "File", ".", "exists?", "(", "file", ")", "properties", "=", "{", "}", "begin", "YAML", ".", "load_file", "(", "file", ")", ".", "each", "{", "|", "key", ",", "value", "|", "properties", "[", "key", ".", "to_sym", "]", "=", "value", "}", "rescue", "raise", "ConfigurationError", ".", "new", "(", "\"Could not read properties file #{file}: \"", "+", "$!", ")", "end", "# Uncomment the following line to print detail properties.", "#logger.debug { \"#{file} properties:\\n#{properties.pp_s}\" }", "# parse comma-delimited string values of array properties into arrays", "@array_properties", ".", "each", "do", "|", "key", "|", "value", "=", "properties", "[", "key", "]", "if", "String", "===", "value", "then", "properties", "[", "key", "]", "=", "value", ".", "split", "(", "/", "\\s", "/", ")", "end", "end", "# if the key is a merge property key, then perform a deep merge.", "# otherwise, do a shallow merge of the property value into this property hash.", "deep", ",", "shallow", "=", "properties", ".", "split", "{", "|", "key", ",", "value", "|", "@merge_properties", ".", "include?", "(", "key", ")", "}", "merge!", "(", "deep", ",", ":deep", ")", "merge!", "(", "shallow", ")", "end" ]
Loads the specified properties file, replacing any existing properties. If a key is included in this Properties merge_properties array, then the old value for that key will be merged with the new value for that key rather than replaced. This method reloads a property file that has already been loaded. Raises ConfigurationError if file doesn't exist or couldn't be parsed.
[ "Loads", "the", "specified", "properties", "file", "replacing", "any", "existing", "properties", "." ]
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/helpers/properties.rb#L68-L90
9,481
sugaryourcoffee/syclink
lib/syclink/infrastructure.rb
SycLink.Infrastructure.copy_file_if_missing
def copy_file_if_missing(file, to_directory) unless File.exists? File.join(to_directory, File.basename(file)) FileUtils.cp(file, to_directory) end end
ruby
def copy_file_if_missing(file, to_directory) unless File.exists? File.join(to_directory, File.basename(file)) FileUtils.cp(file, to_directory) end end
[ "def", "copy_file_if_missing", "(", "file", ",", "to_directory", ")", "unless", "File", ".", "exists?", "File", ".", "join", "(", "to_directory", ",", "File", ".", "basename", "(", "file", ")", ")", "FileUtils", ".", "cp", "(", "file", ",", "to_directory", ")", "end", "end" ]
Copies a file to a target directory
[ "Copies", "a", "file", "to", "a", "target", "directory" ]
941ee2045c946daa1e0db394eb643aa82c1254cc
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/infrastructure.rb#L15-L19
9,482
sugaryourcoffee/syclink
lib/syclink/infrastructure.rb
SycLink.Infrastructure.load_config
def load_config(file) unless File.exists? file File.open(file, 'w') do |f| YAML.dump({ default_website: 'default' }, f) end end YAML.load_file(file) end
ruby
def load_config(file) unless File.exists? file File.open(file, 'w') do |f| YAML.dump({ default_website: 'default' }, f) end end YAML.load_file(file) end
[ "def", "load_config", "(", "file", ")", "unless", "File", ".", "exists?", "file", "File", ".", "open", "(", "file", ",", "'w'", ")", "do", "|", "f", "|", "YAML", ".", "dump", "(", "{", "default_website", ":", "'default'", "}", ",", "f", ")", "end", "end", "YAML", ".", "load_file", "(", "file", ")", "end" ]
Loads the configuration from a file
[ "Loads", "the", "configuration", "from", "a", "file" ]
941ee2045c946daa1e0db394eb643aa82c1254cc
https://github.com/sugaryourcoffee/syclink/blob/941ee2045c946daa1e0db394eb643aa82c1254cc/lib/syclink/infrastructure.rb#L22-L29
9,483
stevedowney/rails_view_helpers
app/helpers/rails_view_helpers/datetime_helper.rb
RailsViewHelpers.DatetimeHelper.datetime_to_s
def datetime_to_s(date_or_datetime, format) return '' if date_or_datetime.blank? return date_or_datetime.to_s(format) if date_or_datetime.instance_of?(Date) date_or_datetime.localtime.to_s(format) end
ruby
def datetime_to_s(date_or_datetime, format) return '' if date_or_datetime.blank? return date_or_datetime.to_s(format) if date_or_datetime.instance_of?(Date) date_or_datetime.localtime.to_s(format) end
[ "def", "datetime_to_s", "(", "date_or_datetime", ",", "format", ")", "return", "''", "if", "date_or_datetime", ".", "blank?", "return", "date_or_datetime", ".", "to_s", "(", "format", ")", "if", "date_or_datetime", ".", "instance_of?", "(", "Date", ")", "date_or_datetime", ".", "localtime", ".", "to_s", "(", "format", ")", "end" ]
Return _date_or_datetime_ converted to _format_. Reminder: * you can add formats (e.g. in an initializer) * this gem has monkey-patched +NilClass+ so you can just do this: +datetime.to_s(:short)+ without worrying if +datetime+ is +nil+. @example datetime_to_s(record.created_at, :long) datetime_to_s(Date.today, :short) @param date_or_datetime [Date, Datetime] the date/time to convert to string @param format [Symbol] one of +Date::DATE_FORMATS+ or +Time::DATE_FORMATS+ @return [String]
[ "Return", "_date_or_datetime_", "converted", "to", "_format_", "." ]
715c7daca9434c763b777be25b1069ecc50df287
https://github.com/stevedowney/rails_view_helpers/blob/715c7daca9434c763b777be25b1069ecc50df287/app/helpers/rails_view_helpers/datetime_helper.rb#L19-L23
9,484
pwnall/authpwn_rails
lib/authpwn_rails/http_token.rb
Authpwn.HttpTokenControllerInstanceMethods.authenticate_using_http_token
def authenticate_using_http_token return if current_user authenticate_with_http_token do |token_code, options| auth = Tokens::Api.authenticate token_code # NOTE: Setting the instance variable directly bypasses the session # setup. Tokens are generally used in API contexts, so the session # cookie would get ignored anyway. @current_user = auth unless auth.kind_of? Symbol end end
ruby
def authenticate_using_http_token return if current_user authenticate_with_http_token do |token_code, options| auth = Tokens::Api.authenticate token_code # NOTE: Setting the instance variable directly bypasses the session # setup. Tokens are generally used in API contexts, so the session # cookie would get ignored anyway. @current_user = auth unless auth.kind_of? Symbol end end
[ "def", "authenticate_using_http_token", "return", "if", "current_user", "authenticate_with_http_token", "do", "|", "token_code", ",", "options", "|", "auth", "=", "Tokens", "::", "Api", ".", "authenticate", "token_code", "# NOTE: Setting the instance variable directly bypasses the session", "# setup. Tokens are generally used in API contexts, so the session", "# cookie would get ignored anyway.", "@current_user", "=", "auth", "unless", "auth", ".", "kind_of?", "Symbol", "end", "end" ]
The before_action that implements authenticates_using_http_token. If your ApplicationController contains authenticates_using_http_token, you can opt out in individual controllers using skip_before_action. skip_before_action :authenticate_using_http_token
[ "The", "before_action", "that", "implements", "authenticates_using_http_token", "." ]
de3bd612a00025e8dc8296a73abe3acba948db17
https://github.com/pwnall/authpwn_rails/blob/de3bd612a00025e8dc8296a73abe3acba948db17/lib/authpwn_rails/http_token.rb#L29-L39
9,485
pione/ruby-xes
lib/xes/document.rb
XES.Document.format
def format raise FormatError.new(self) unless formattable? REXML::Document.new.tap do |doc| doc << REXML::XMLDecl.new doc.elements << @log.format end end
ruby
def format raise FormatError.new(self) unless formattable? REXML::Document.new.tap do |doc| doc << REXML::XMLDecl.new doc.elements << @log.format end end
[ "def", "format", "raise", "FormatError", ".", "new", "(", "self", ")", "unless", "formattable?", "REXML", "::", "Document", ".", "new", ".", "tap", "do", "|", "doc", "|", "doc", "<<", "REXML", "::", "XMLDecl", ".", "new", "doc", ".", "elements", "<<", "@log", ".", "format", "end", "end" ]
Format as a XML document. @return [REXML::Document] XML document @raise FormatError format error when the document is not formattable
[ "Format", "as", "a", "XML", "document", "." ]
61501a8fd8027708f670264a150b1ce74fdccd74
https://github.com/pione/ruby-xes/blob/61501a8fd8027708f670264a150b1ce74fdccd74/lib/xes/document.rb#L27-L34
9,486
kgnzt/polyseerio-ruby
lib/request.rb
Polyseerio.Request.execute
def execute(method, *args) new_args = args @pre_request.each do |middleware| new_args = middleware.call(*new_args) end path = new_args.empty? ? '' : new_args.shift req = proc do || @resource[path].send(method, *new_args) end post = proc do |result| @post_request.each do |middleware| result = middleware.call(result) end result end Concurrent::Promise.new(&req).on_success(&post) end
ruby
def execute(method, *args) new_args = args @pre_request.each do |middleware| new_args = middleware.call(*new_args) end path = new_args.empty? ? '' : new_args.shift req = proc do || @resource[path].send(method, *new_args) end post = proc do |result| @post_request.each do |middleware| result = middleware.call(result) end result end Concurrent::Promise.new(&req).on_success(&post) end
[ "def", "execute", "(", "method", ",", "*", "args", ")", "new_args", "=", "args", "@pre_request", ".", "each", "do", "|", "middleware", "|", "new_args", "=", "middleware", ".", "call", "(", "new_args", ")", "end", "path", "=", "new_args", ".", "empty?", "?", "''", ":", "new_args", ".", "shift", "req", "=", "proc", "do", "|", "|", "@resource", "[", "path", "]", ".", "send", "(", "method", ",", "new_args", ")", "end", "post", "=", "proc", "do", "|", "result", "|", "@post_request", ".", "each", "do", "|", "middleware", "|", "result", "=", "middleware", ".", "call", "(", "result", ")", "end", "result", "end", "Concurrent", "::", "Promise", ".", "new", "(", "req", ")", ".", "on_success", "(", "post", ")", "end" ]
Execute a request using pre, post, and reject middleware. method - The HTTP method. ... - Arguments to forward to execute. Returns a promise.
[ "Execute", "a", "request", "using", "pre", "post", "and", "reject", "middleware", "." ]
ec2d87ce0056692b74e26a85ca5a66f21c599152
https://github.com/kgnzt/polyseerio-ruby/blob/ec2d87ce0056692b74e26a85ca5a66f21c599152/lib/request.rb#L58-L80
9,487
gotqn/thumbnail_hover_effect
lib/thumbnail_hover_effect/image.rb
ThumbnailHoverEffect.Image.render
def render(parameters = {}) has_thumbnail = parameters.fetch(:has_thumbnail, true) effect_number = parameters.fetch(:effect_number, false) thumbnail_template = self.get_template(effect_number) if has_thumbnail @attributes.map { |key, value| thumbnail_template["###{key}##"] &&= value } thumbnail_template.gsub!('##url##', @url).html_safe else self.to_s.html_safe end end
ruby
def render(parameters = {}) has_thumbnail = parameters.fetch(:has_thumbnail, true) effect_number = parameters.fetch(:effect_number, false) thumbnail_template = self.get_template(effect_number) if has_thumbnail @attributes.map { |key, value| thumbnail_template["###{key}##"] &&= value } thumbnail_template.gsub!('##url##', @url).html_safe else self.to_s.html_safe end end
[ "def", "render", "(", "parameters", "=", "{", "}", ")", "has_thumbnail", "=", "parameters", ".", "fetch", "(", ":has_thumbnail", ",", "true", ")", "effect_number", "=", "parameters", ".", "fetch", "(", ":effect_number", ",", "false", ")", "thumbnail_template", "=", "self", ".", "get_template", "(", "effect_number", ")", "if", "has_thumbnail", "@attributes", ".", "map", "{", "|", "key", ",", "value", "|", "thumbnail_template", "[", "\"###{key}##\"", "]", "&&=", "value", "}", "thumbnail_template", ".", "gsub!", "(", "'##url##'", ",", "@url", ")", ".", "html_safe", "else", "self", ".", "to_s", ".", "html_safe", "end", "end" ]
rendering image with thumbnail effect applied
[ "rendering", "image", "with", "thumbnail", "effect", "applied" ]
29588d7b31927710a8a79564ea7913bb4b14beb1
https://github.com/gotqn/thumbnail_hover_effect/blob/29588d7b31927710a8a79564ea7913bb4b14beb1/lib/thumbnail_hover_effect/image.rb#L37-L50
9,488
mudasobwa/itudes
lib/itudes.rb
Geo.Itudes.distance
def distance other, units = :km o = Itudes.new other raise ArgumentError.new "operand must be lat-/longitudable" if (o.latitude.nil? || o.longitude.nil?) dlat = Itudes.radians(o.latitude - @latitude) dlon = Itudes.radians(o.longitude - @longitude) lat1 = Itudes.radians(@latitude) lat2 = Itudes.radians(o.latitude); a = Math::sin(dlat/2)**2 + Math::sin(dlon/2)**2 * Math::cos(lat1) * Math::cos(lat2) (RADIUS[units] * 2.0 * Math::atan2(Math.sqrt(a), Math.sqrt(1-a))).abs end
ruby
def distance other, units = :km o = Itudes.new other raise ArgumentError.new "operand must be lat-/longitudable" if (o.latitude.nil? || o.longitude.nil?) dlat = Itudes.radians(o.latitude - @latitude) dlon = Itudes.radians(o.longitude - @longitude) lat1 = Itudes.radians(@latitude) lat2 = Itudes.radians(o.latitude); a = Math::sin(dlat/2)**2 + Math::sin(dlon/2)**2 * Math::cos(lat1) * Math::cos(lat2) (RADIUS[units] * 2.0 * Math::atan2(Math.sqrt(a), Math.sqrt(1-a))).abs end
[ "def", "distance", "other", ",", "units", "=", ":km", "o", "=", "Itudes", ".", "new", "other", "raise", "ArgumentError", ".", "new", "\"operand must be lat-/longitudable\"", "if", "(", "o", ".", "latitude", ".", "nil?", "||", "o", ".", "longitude", ".", "nil?", ")", "dlat", "=", "Itudes", ".", "radians", "(", "o", ".", "latitude", "-", "@latitude", ")", "dlon", "=", "Itudes", ".", "radians", "(", "o", ".", "longitude", "-", "@longitude", ")", "lat1", "=", "Itudes", ".", "radians", "(", "@latitude", ")", "lat2", "=", "Itudes", ".", "radians", "(", "o", ".", "latitude", ")", ";", "a", "=", "Math", "::", "sin", "(", "dlat", "/", "2", ")", "**", "2", "+", "Math", "::", "sin", "(", "dlon", "/", "2", ")", "**", "2", "*", "Math", "::", "cos", "(", "lat1", ")", "*", "Math", "::", "cos", "(", "lat2", ")", "(", "RADIUS", "[", "units", "]", "*", "2.0", "*", "Math", "::", "atan2", "(", "Math", ".", "sqrt", "(", "a", ")", ",", "Math", ".", "sqrt", "(", "1", "-", "a", ")", ")", ")", ".", "abs", "end" ]
Calculates distance between two points on the Earth. @param other the place on the Earth to calculate distance to @return [Float] the distance between two places on the Earth
[ "Calculates", "distance", "between", "two", "points", "on", "the", "Earth", "." ]
047d976e6cae0e01cde41217fab910cd3ad75ac6
https://github.com/mudasobwa/itudes/blob/047d976e6cae0e01cde41217fab910cd3ad75ac6/lib/itudes.rb#L94-L105
9,489
checkdin/checkdin-ruby
lib/checkdin/promotions.rb
Checkdin.Promotions.promotions
def promotions(options={}) response = connection.get do |req| req.url "promotions", options end return_error_or_body(response) end
ruby
def promotions(options={}) response = connection.get do |req| req.url "promotions", options end return_error_or_body(response) end
[ "def", "promotions", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"promotions\"", ",", "options", "end", "return_error_or_body", "(", "response", ")", "end" ]
Get a list of all promotions for the authenticating client. @param [Hash] options @option options Integer :campaign_id - Only return promotions for this campaign. @option options String :active - Return either active or inactive promotions, use true or false value. @option options Integer :limit - The maximum number of records to return.
[ "Get", "a", "list", "of", "all", "promotions", "for", "the", "authenticating", "client", "." ]
c3c4b38b0f8c710e1f805100dcf3a70649215b48
https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/promotions.rb#L20-L25
9,490
checkdin/checkdin-ruby
lib/checkdin/promotions.rb
Checkdin.Promotions.promotion_votes_leaderboard
def promotion_votes_leaderboard(id, options={}) response = connection.get do |req| req.url "promotions/#{id}/votes_leaderboard", options end return_error_or_body(response) end
ruby
def promotion_votes_leaderboard(id, options={}) response = connection.get do |req| req.url "promotions/#{id}/votes_leaderboard", options end return_error_or_body(response) end
[ "def", "promotion_votes_leaderboard", "(", "id", ",", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"promotions/#{id}/votes_leaderboard\"", ",", "options", "end", "return_error_or_body", "(", "response", ")", "end" ]
Get a list of activities for a promotion ordered by the number of votes they have received param [Integer] id The ID of the promotion @param [Hash] options @option options Integer :limit - The maximum number of records to return. @option options Integer :page - The page of results to return.
[ "Get", "a", "list", "of", "activities", "for", "a", "promotion", "ordered", "by", "the", "number", "of", "votes", "they", "have", "received" ]
c3c4b38b0f8c710e1f805100dcf3a70649215b48
https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/promotions.rb#L34-L39
9,491
elifoster/fishbans-rb
lib/player_skins.rb
Fishbans.PlayerSkins.get_player_image
def get_player_image(username, type, size) url = "http://i.fishbans.com/#{type}/#{username}/#{size}" response = get(url, false) ChunkyPNG::Image.from_blob(response.body) end
ruby
def get_player_image(username, type, size) url = "http://i.fishbans.com/#{type}/#{username}/#{size}" response = get(url, false) ChunkyPNG::Image.from_blob(response.body) end
[ "def", "get_player_image", "(", "username", ",", "type", ",", "size", ")", "url", "=", "\"http://i.fishbans.com/#{type}/#{username}/#{size}\"", "response", "=", "get", "(", "url", ",", "false", ")", "ChunkyPNG", "::", "Image", ".", "from_blob", "(", "response", ".", "body", ")", "end" ]
Gets the player image for the type. @param username [String] See #get_player_head. @param type [String] The type of image to get. Can be 'helm', 'player', or 'skin' as defined by the Fishbans Player Skins API. @param size [Integer] See #get_player_head. @return [ChunkyPNG::Image] The ChunkyPNG::Image instance for the params. @raise see #get
[ "Gets", "the", "player", "image", "for", "the", "type", "." ]
652016694176ade8767ac6a3b4dea2dc631be747
https://github.com/elifoster/fishbans-rb/blob/652016694176ade8767ac6a3b4dea2dc631be747/lib/player_skins.rb#L42-L46
9,492
jstumbaugh/copy_csv
lib/copy_csv.rb
CopyCsv.ClassMethods.write_to_csv
def write_to_csv(file_name, mode = "w") File.open(file_name, mode) do |file| all.copy_csv(file) end end
ruby
def write_to_csv(file_name, mode = "w") File.open(file_name, mode) do |file| all.copy_csv(file) end end
[ "def", "write_to_csv", "(", "file_name", ",", "mode", "=", "\"w\"", ")", "File", ".", "open", "(", "file_name", ",", "mode", ")", "do", "|", "file", "|", "all", ".", "copy_csv", "(", "file", ")", "end", "end" ]
Opens the file provided and writes the relation to it as a CSV. Example User.where(unsubscribed: false).write_to_csv("unsubscribed_users.csv") Returns nil
[ "Opens", "the", "file", "provided", "and", "writes", "the", "relation", "to", "it", "as", "a", "CSV", "." ]
3e3ec08715bd00784be3f0b17e88dd7a841de70c
https://github.com/jstumbaugh/copy_csv/blob/3e3ec08715bd00784be3f0b17e88dd7a841de70c/lib/copy_csv.rb#L41-L45
9,493
starpeak/gricer
app/controllers/gricer/base_controller.rb
Gricer.BaseController.process_stats
def process_stats @items = basic_collection handle_special_fields data = { alternatives: [ { type: 'spread', uri: url_for(action: "spread_stats", field: params[:field], filters: params[:filters], only_path: true) }, { type: 'process' } ], from: @stat_from.to_time.utc.to_i * 1000, thru: @stat_thru.to_time.utc.to_i * 1000, step: @stat_step.to_i * 1000, data: @items.stat(params[:field], @stat_from, @stat_thru, @stat_step) } if further_details.keys.include? params[:field] filters = (params[:filters] || {}) filters[params[:field]] = '%{self}' data[:detail_uri] = url_for(action: "process_stats", field: further_details[params[:field]], filters: filters, only_path: true) end render json: data end
ruby
def process_stats @items = basic_collection handle_special_fields data = { alternatives: [ { type: 'spread', uri: url_for(action: "spread_stats", field: params[:field], filters: params[:filters], only_path: true) }, { type: 'process' } ], from: @stat_from.to_time.utc.to_i * 1000, thru: @stat_thru.to_time.utc.to_i * 1000, step: @stat_step.to_i * 1000, data: @items.stat(params[:field], @stat_from, @stat_thru, @stat_step) } if further_details.keys.include? params[:field] filters = (params[:filters] || {}) filters[params[:field]] = '%{self}' data[:detail_uri] = url_for(action: "process_stats", field: further_details[params[:field]], filters: filters, only_path: true) end render json: data end
[ "def", "process_stats", "@items", "=", "basic_collection", "handle_special_fields", "data", "=", "{", "alternatives", ":", "[", "{", "type", ":", "'spread'", ",", "uri", ":", "url_for", "(", "action", ":", "\"spread_stats\"", ",", "field", ":", "params", "[", ":field", "]", ",", "filters", ":", "params", "[", ":filters", "]", ",", "only_path", ":", "true", ")", "}", ",", "{", "type", ":", "'process'", "}", "]", ",", "from", ":", "@stat_from", ".", "to_time", ".", "utc", ".", "to_i", "*", "1000", ",", "thru", ":", "@stat_thru", ".", "to_time", ".", "utc", ".", "to_i", "*", "1000", ",", "step", ":", "@stat_step", ".", "to_i", "*", "1000", ",", "data", ":", "@items", ".", "stat", "(", "params", "[", ":field", "]", ",", "@stat_from", ",", "@stat_thru", ",", "@stat_step", ")", "}", "if", "further_details", ".", "keys", ".", "include?", "params", "[", ":field", "]", "filters", "=", "(", "params", "[", ":filters", "]", "||", "{", "}", ")", "filters", "[", "params", "[", ":field", "]", "]", "=", "'%{self}'", "data", "[", ":detail_uri", "]", "=", "url_for", "(", "action", ":", "\"process_stats\"", ",", "field", ":", "further_details", "[", "params", "[", ":field", "]", "]", ",", "filters", ":", "filters", ",", "only_path", ":", "true", ")", "end", "render", "json", ":", "data", "end" ]
This action generates a JSON for a process statistics.
[ "This", "action", "generates", "a", "JSON", "for", "a", "process", "statistics", "." ]
46bb77bd4fc7074ce294d0310ad459fef068f507
https://github.com/starpeak/gricer/blob/46bb77bd4fc7074ce294d0310ad459fef068f507/app/controllers/gricer/base_controller.rb#L12-L41
9,494
starpeak/gricer
app/controllers/gricer/base_controller.rb
Gricer.BaseController.spread_stats
def spread_stats @items = basic_collection.between_dates(@stat_from, @stat_thru) handle_special_fields data = { alternatives: [ { type: 'spread' }, { type: 'process', uri: url_for(action: "process_stats", field: params[:field], filters: params[:filters], only_path: true) } ], from: @stat_from.to_time.utc.to_i * 1000, thru: @stat_thru.to_time.utc.to_i * 1000, total: @items.count(:id), data: @items.count_by(params[:field]) } if further_details.keys.include? params[:field] filters = (params[:filters] || {}) filters[params[:field]] = '%{self}' data[:detail_uri] = url_for(action: "spread_stats", field: further_details[params[:field]], filters: filters, only_path: true) end render json: data end
ruby
def spread_stats @items = basic_collection.between_dates(@stat_from, @stat_thru) handle_special_fields data = { alternatives: [ { type: 'spread' }, { type: 'process', uri: url_for(action: "process_stats", field: params[:field], filters: params[:filters], only_path: true) } ], from: @stat_from.to_time.utc.to_i * 1000, thru: @stat_thru.to_time.utc.to_i * 1000, total: @items.count(:id), data: @items.count_by(params[:field]) } if further_details.keys.include? params[:field] filters = (params[:filters] || {}) filters[params[:field]] = '%{self}' data[:detail_uri] = url_for(action: "spread_stats", field: further_details[params[:field]], filters: filters, only_path: true) end render json: data end
[ "def", "spread_stats", "@items", "=", "basic_collection", ".", "between_dates", "(", "@stat_from", ",", "@stat_thru", ")", "handle_special_fields", "data", "=", "{", "alternatives", ":", "[", "{", "type", ":", "'spread'", "}", ",", "{", "type", ":", "'process'", ",", "uri", ":", "url_for", "(", "action", ":", "\"process_stats\"", ",", "field", ":", "params", "[", ":field", "]", ",", "filters", ":", "params", "[", ":filters", "]", ",", "only_path", ":", "true", ")", "}", "]", ",", "from", ":", "@stat_from", ".", "to_time", ".", "utc", ".", "to_i", "*", "1000", ",", "thru", ":", "@stat_thru", ".", "to_time", ".", "utc", ".", "to_i", "*", "1000", ",", "total", ":", "@items", ".", "count", "(", ":id", ")", ",", "data", ":", "@items", ".", "count_by", "(", "params", "[", ":field", "]", ")", "}", "if", "further_details", ".", "keys", ".", "include?", "params", "[", ":field", "]", "filters", "=", "(", "params", "[", ":filters", "]", "||", "{", "}", ")", "filters", "[", "params", "[", ":field", "]", "]", "=", "'%{self}'", "data", "[", ":detail_uri", "]", "=", "url_for", "(", "action", ":", "\"spread_stats\"", ",", "field", ":", "further_details", "[", "params", "[", ":field", "]", "]", ",", "filters", ":", "filters", ",", "only_path", ":", "true", ")", "end", "render", "json", ":", "data", "end" ]
This action generates a JSON for a spread statistics.
[ "This", "action", "generates", "a", "JSON", "for", "a", "spread", "statistics", "." ]
46bb77bd4fc7074ce294d0310ad459fef068f507
https://github.com/starpeak/gricer/blob/46bb77bd4fc7074ce294d0310ad459fef068f507/app/controllers/gricer/base_controller.rb#L44-L73
9,495
starpeak/gricer
app/controllers/gricer/base_controller.rb
Gricer.BaseController.guess_from_thru
def guess_from_thru begin @stat_thru = Time.parse(params[:thru]).to_date rescue end begin @stat_from = Time.parse(params[:from]).to_date rescue end if @stat_from.nil? if @stat_thru.nil? @stat_thru = Time.now.localtime.to_date - 1.day end @stat_from = @stat_thru - 1.week + 1.day else if @stat_thru.nil? @stat_thru = @stat_from + 1.week - 1.day end end @stat_step = 1.day duration = @stat_thru - @stat_from if duration < 90 @stat_step = 12.hours end if duration < 30 @stat_step = 6.hour end if duration < 10 @stat_step = 1.hour end #if @stat_thru - @stat_from > 12.month # @stat_step = 4.week #end end
ruby
def guess_from_thru begin @stat_thru = Time.parse(params[:thru]).to_date rescue end begin @stat_from = Time.parse(params[:from]).to_date rescue end if @stat_from.nil? if @stat_thru.nil? @stat_thru = Time.now.localtime.to_date - 1.day end @stat_from = @stat_thru - 1.week + 1.day else if @stat_thru.nil? @stat_thru = @stat_from + 1.week - 1.day end end @stat_step = 1.day duration = @stat_thru - @stat_from if duration < 90 @stat_step = 12.hours end if duration < 30 @stat_step = 6.hour end if duration < 10 @stat_step = 1.hour end #if @stat_thru - @stat_from > 12.month # @stat_step = 4.week #end end
[ "def", "guess_from_thru", "begin", "@stat_thru", "=", "Time", ".", "parse", "(", "params", "[", ":thru", "]", ")", ".", "to_date", "rescue", "end", "begin", "@stat_from", "=", "Time", ".", "parse", "(", "params", "[", ":from", "]", ")", ".", "to_date", "rescue", "end", "if", "@stat_from", ".", "nil?", "if", "@stat_thru", ".", "nil?", "@stat_thru", "=", "Time", ".", "now", ".", "localtime", ".", "to_date", "-", "1", ".", "day", "end", "@stat_from", "=", "@stat_thru", "-", "1", ".", "week", "+", "1", ".", "day", "else", "if", "@stat_thru", ".", "nil?", "@stat_thru", "=", "@stat_from", "+", "1", ".", "week", "-", "1", ".", "day", "end", "end", "@stat_step", "=", "1", ".", "day", "duration", "=", "@stat_thru", "-", "@stat_from", "if", "duration", "<", "90", "@stat_step", "=", "12", ".", "hours", "end", "if", "duration", "<", "30", "@stat_step", "=", "6", ".", "hour", "end", "if", "duration", "<", "10", "@stat_step", "=", "1", ".", "hour", "end", "#if @stat_thru - @stat_from > 12.month", "# @stat_step = 4.week", "#end", "end" ]
Guess for which time range to display statistics
[ "Guess", "for", "which", "time", "range", "to", "display", "statistics" ]
46bb77bd4fc7074ce294d0310ad459fef068f507
https://github.com/starpeak/gricer/blob/46bb77bd4fc7074ce294d0310ad459fef068f507/app/controllers/gricer/base_controller.rb#L98-L139
9,496
mntnorv/puttext
lib/puttext/po_file.rb
PutText.POFile.write_to
def write_to(io) deduplicate io.write(@header_entry.to_s) @entries.each do |entry| io.write("\n") io.write(entry.to_s) end end
ruby
def write_to(io) deduplicate io.write(@header_entry.to_s) @entries.each do |entry| io.write("\n") io.write(entry.to_s) end end
[ "def", "write_to", "(", "io", ")", "deduplicate", "io", ".", "write", "(", "@header_entry", ".", "to_s", ")", "@entries", ".", "each", "do", "|", "entry", "|", "io", ".", "write", "(", "\"\\n\"", ")", "io", ".", "write", "(", "entry", ".", "to_s", ")", "end", "end" ]
Write the contents of this file to the specified IO object. @param [IO] io the IO object to write the contents of the file to.
[ "Write", "the", "contents", "of", "this", "file", "to", "the", "specified", "IO", "object", "." ]
c5c210dff4e11f714418b6b426dc9e2739fe9876
https://github.com/mntnorv/puttext/blob/c5c210dff4e11f714418b6b426dc9e2739fe9876/lib/puttext/po_file.rb#L34-L43
9,497
caruby/core
lib/caruby/database/cache.rb
CaRuby.Cache.clear
def clear if @sticky.empty? then @ckh.clear else @ckh.each { |klass, ch| ch.clear unless @sticky.include?(klass) } end end
ruby
def clear if @sticky.empty? then @ckh.clear else @ckh.each { |klass, ch| ch.clear unless @sticky.include?(klass) } end end
[ "def", "clear", "if", "@sticky", ".", "empty?", "then", "@ckh", ".", "clear", "else", "@ckh", ".", "each", "{", "|", "klass", ",", "ch", "|", "ch", ".", "clear", "unless", "@sticky", ".", "include?", "(", "klass", ")", "}", "end", "end" ]
Clears the non-sticky class caches.
[ "Clears", "the", "non", "-", "sticky", "class", "caches", "." ]
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/cache.rb#L63-L69
9,498
hackersrc/hs-cli
lib/hs/models/chapter.rb
HS.Chapter.find_module
def find_module(slug) modules.find { |m| m.slug.to_s == slug.to_s } end
ruby
def find_module(slug) modules.find { |m| m.slug.to_s == slug.to_s } end
[ "def", "find_module", "(", "slug", ")", "modules", ".", "find", "{", "|", "m", "|", "m", ".", "slug", ".", "to_s", "==", "slug", ".", "to_s", "}", "end" ]
Tries to find module in this chapter by module slug.
[ "Tries", "to", "find", "module", "in", "this", "chapter", "by", "module", "slug", "." ]
018367cab5e8d324f2097e79faaf71819390eccc
https://github.com/hackersrc/hs-cli/blob/018367cab5e8d324f2097e79faaf71819390eccc/lib/hs/models/chapter.rb#L37-L39
9,499
ithouse/lolita-paypal
app/controllers/lolita_paypal/transactions_controller.rb
LolitaPaypal.TransactionsController.answer
def answer if request.post? if ipn_notify.acknowledge LolitaPaypal::Transaction.create_transaction(ipn_notify, payment_from_ipn, request) end render nothing: true else if payment_from_ipn redirect_to payment_from_ipn.paypal_return_path else render text: I18n.t('lolita_paypal.wrong_request'), status: 400 end end ensure LolitaPaypal.logger.info("[#{session_id}][#{payment_from_ipn && payment_from_ipn.id}][answer] #{params}") end
ruby
def answer if request.post? if ipn_notify.acknowledge LolitaPaypal::Transaction.create_transaction(ipn_notify, payment_from_ipn, request) end render nothing: true else if payment_from_ipn redirect_to payment_from_ipn.paypal_return_path else render text: I18n.t('lolita_paypal.wrong_request'), status: 400 end end ensure LolitaPaypal.logger.info("[#{session_id}][#{payment_from_ipn && payment_from_ipn.id}][answer] #{params}") end
[ "def", "answer", "if", "request", ".", "post?", "if", "ipn_notify", ".", "acknowledge", "LolitaPaypal", "::", "Transaction", ".", "create_transaction", "(", "ipn_notify", ",", "payment_from_ipn", ",", "request", ")", "end", "render", "nothing", ":", "true", "else", "if", "payment_from_ipn", "redirect_to", "payment_from_ipn", ".", "paypal_return_path", "else", "render", "text", ":", "I18n", ".", "t", "(", "'lolita_paypal.wrong_request'", ")", ",", "status", ":", "400", "end", "end", "ensure", "LolitaPaypal", ".", "logger", ".", "info", "(", "\"[#{session_id}][#{payment_from_ipn && payment_from_ipn.id}][answer] #{params}\"", ")", "end" ]
process ipn request POST is sent from paypal and will create transaction GET is a redirect from paypal and will redirect back to return_path
[ "process", "ipn", "request", "POST", "is", "sent", "from", "paypal", "and", "will", "create", "transaction", "GET", "is", "a", "redirect", "from", "paypal", "and", "will", "redirect", "back", "to", "return_path" ]
f18d0995aaec58a144e39d073bf32bdd2c1cb4b1
https://github.com/ithouse/lolita-paypal/blob/f18d0995aaec58a144e39d073bf32bdd2c1cb4b1/app/controllers/lolita_paypal/transactions_controller.rb#L20-L35