repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
christoph-buente/retentiongrid
lib/retentiongrid/customer.rb
Retentiongrid.Customer.save!
def save! result = Api.post("#{BASE_PATH}/#{customer_id}", body: attributes.to_json) Customer.new(result.parsed_response["rg_customer"]) end
ruby
def save! result = Api.post("#{BASE_PATH}/#{customer_id}", body: attributes.to_json) Customer.new(result.parsed_response["rg_customer"]) end
[ "def", "save!", "result", "=", "Api", ".", "post", "(", "\"#{BASE_PATH}/#{customer_id}\"", ",", "body", ":", "attributes", ".", "to_json", ")", "Customer", ".", "new", "(", "result", ".", "parsed_response", "[", "\"rg_customer\"", "]", ")", "end" ]
Create or update a customer with given id @return [Customer] if successfully created or updated @raise [Httparty::Error] for all sorts of HTTP statuses.
[ "Create", "or", "update", "a", "customer", "with", "given", "id" ]
601d256786dd2e2c42f7374b999cd4e195e0e848
https://github.com/christoph-buente/retentiongrid/blob/601d256786dd2e2c42f7374b999cd4e195e0e848/lib/retentiongrid/customer.rb#L41-L44
train
delagoya/mzml
lib/mzml/doc.rb
MzML.Doc.parse_index_list
def parse_index_list self.seek(self.stat.size - 200) # parse the index offset tmp = self.read tmp =~ MzML::RGX::INDEX_OFFSET offset = $1 # if I didn't match anything, compute the index and return unless (offset) return compute_index_list end @index = {} @spectrum_list = [] @chromatogram_list = [] self.seek(offset.to_i) tmp = Nokogiri::XML.parse(self.read).root tmp.css("index").each do |idx| index_type = idx[:name].to_sym @index[index_type] = {} idx.css("offset").each do |o| @index[index_type][o[:idRef]] = o.text().to_i if index_type == :spectrum @spectrum_list << o[:idRef] else @chromatogram_list << o[:idRef] end end end self.rewind return @index end
ruby
def parse_index_list self.seek(self.stat.size - 200) # parse the index offset tmp = self.read tmp =~ MzML::RGX::INDEX_OFFSET offset = $1 # if I didn't match anything, compute the index and return unless (offset) return compute_index_list end @index = {} @spectrum_list = [] @chromatogram_list = [] self.seek(offset.to_i) tmp = Nokogiri::XML.parse(self.read).root tmp.css("index").each do |idx| index_type = idx[:name].to_sym @index[index_type] = {} idx.css("offset").each do |o| @index[index_type][o[:idRef]] = o.text().to_i if index_type == :spectrum @spectrum_list << o[:idRef] else @chromatogram_list << o[:idRef] end end end self.rewind return @index end
[ "def", "parse_index_list", "self", ".", "seek", "(", "self", ".", "stat", ".", "size", "-", "200", ")", "tmp", "=", "self", ".", "read", "tmp", "=~", "MzML", "::", "RGX", "::", "INDEX_OFFSET", "offset", "=", "$1", "unless", "(", "offset", ")", "return", "compute_index_list", "end", "@index", "=", "{", "}", "@spectrum_list", "=", "[", "]", "@chromatogram_list", "=", "[", "]", "self", ".", "seek", "(", "offset", ".", "to_i", ")", "tmp", "=", "Nokogiri", "::", "XML", ".", "parse", "(", "self", ".", "read", ")", ".", "root", "tmp", ".", "css", "(", "\"index\"", ")", ".", "each", "do", "|", "idx", "|", "index_type", "=", "idx", "[", ":name", "]", ".", "to_sym", "@index", "[", "index_type", "]", "=", "{", "}", "idx", ".", "css", "(", "\"offset\"", ")", ".", "each", "do", "|", "o", "|", "@index", "[", "index_type", "]", "[", "o", "[", ":idRef", "]", "]", "=", "o", ".", "text", "(", ")", ".", "to_i", "if", "index_type", "==", ":spectrum", "@spectrum_list", "<<", "o", "[", ":idRef", "]", "else", "@chromatogram_list", "<<", "o", "[", ":idRef", "]", "end", "end", "end", "self", ".", "rewind", "return", "@index", "end" ]
Parses the IndexList
[ "Parses", "the", "IndexList" ]
6375cfe54a32ad3f7ebbeb92f0c25c5e456101de
https://github.com/delagoya/mzml/blob/6375cfe54a32ad3f7ebbeb92f0c25c5e456101de/lib/mzml/doc.rb#L140-L169
train
npepinpe/redstruct
lib/redstruct/struct.rb
Redstruct.Struct.expire
def expire(ttl) ttl = (ttl.to_f * 1000).floor return coerce_bool(self.connection.pexpire(@key, ttl)) end
ruby
def expire(ttl) ttl = (ttl.to_f * 1000).floor return coerce_bool(self.connection.pexpire(@key, ttl)) end
[ "def", "expire", "(", "ttl", ")", "ttl", "=", "(", "ttl", ".", "to_f", "*", "1000", ")", ".", "floor", "return", "coerce_bool", "(", "self", ".", "connection", ".", "pexpire", "(", "@key", ",", "ttl", ")", ")", "end" ]
Sets the key to expire after ttl seconds @param [#to_f] ttl the time to live in seconds (where 0.001 = 1ms) @return [Boolean] true if expired, false otherwise
[ "Sets", "the", "key", "to", "expire", "after", "ttl", "seconds" ]
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/struct.rb#L33-L36
train
npepinpe/redstruct
lib/redstruct/struct.rb
Redstruct.Struct.expire_at
def expire_at(time) time = (time.to_f * 1000).floor return coerce_bool(self.connection.pexpireat(@key, time)) end
ruby
def expire_at(time) time = (time.to_f * 1000).floor return coerce_bool(self.connection.pexpireat(@key, time)) end
[ "def", "expire_at", "(", "time", ")", "time", "=", "(", "time", ".", "to_f", "*", "1000", ")", ".", "floor", "return", "coerce_bool", "(", "self", ".", "connection", ".", "pexpireat", "(", "@key", ",", "time", ")", ")", "end" ]
Sets the key to expire at the given timestamp. @param [#to_f] time time or unix timestamp at which the key should expire; once converted to float, assumes 1.0 is one second, 0.001 is 1 ms @return [Boolean] true if expired, false otherwise
[ "Sets", "the", "key", "to", "expire", "at", "the", "given", "timestamp", "." ]
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/struct.rb#L41-L44
train
npepinpe/redstruct
lib/redstruct/struct.rb
Redstruct.Struct.restore
def restore(serialized, ttl: 0) ttl = (ttl.to_f * 1000).floor return self.connection.restore(@key, ttl, serialized) end
ruby
def restore(serialized, ttl: 0) ttl = (ttl.to_f * 1000).floor return self.connection.restore(@key, ttl, serialized) end
[ "def", "restore", "(", "serialized", ",", "ttl", ":", "0", ")", "ttl", "=", "(", "ttl", ".", "to_f", "*", "1000", ")", ".", "floor", "return", "self", ".", "connection", ".", "restore", "(", "@key", ",", "ttl", ",", "serialized", ")", "end" ]
Restores the struct to its serialized value as given @param [String] serialized serialized representation of the value @param [#to_f] ttl the time to live (in seconds) for the struct; defaults to 0 (meaning no expiry) @raise [Redis::CommandError] raised if the serialized value is incompatible or the key already exists @return [Boolean] true if restored, false otherwise
[ "Restores", "the", "struct", "to", "its", "serialized", "value", "as", "given" ]
c97b45e7227f8ed9029f0effff352fc4d82dc3cb
https://github.com/npepinpe/redstruct/blob/c97b45e7227f8ed9029f0effff352fc4d82dc3cb/lib/redstruct/struct.rb#L82-L85
train
colbell/bitsa
lib/bitsa/cli.rb
Bitsa.CLI.parse
def parse(args) @global_opts = create_global_args(args) @cmd = args.shift || '' @search_data = '' if cmd == 'search' @search_data << args.shift unless args.empty? elsif !CLI::SUB_COMMANDS.include?(cmd) Trollop.die "unknown subcommand '#{cmd}'" end end
ruby
def parse(args) @global_opts = create_global_args(args) @cmd = args.shift || '' @search_data = '' if cmd == 'search' @search_data << args.shift unless args.empty? elsif !CLI::SUB_COMMANDS.include?(cmd) Trollop.die "unknown subcommand '#{cmd}'" end end
[ "def", "parse", "(", "args", ")", "@global_opts", "=", "create_global_args", "(", "args", ")", "@cmd", "=", "args", ".", "shift", "||", "''", "@search_data", "=", "''", "if", "cmd", "==", "'search'", "@search_data", "<<", "args", ".", "shift", "unless", "args", ".", "empty?", "elsif", "!", "CLI", "::", "SUB_COMMANDS", ".", "include?", "(", "cmd", ")", "Trollop", ".", "die", "\"unknown subcommand '#{cmd}'\"", "end", "end" ]
Parse arguments and setup attributes. It also handles showing the Help and Version information. @example parse command line arguments cli = Bitsa::CLI.new cli.parse(ARGV) cli.cmd # => # => "reload" @param args [String[]] Cmd line arguments. @return [nil] @raise [TrollopException] If invalid data is passed
[ "Parse", "arguments", "and", "setup", "attributes", "." ]
8b73c4988bde1bf8e64d9cb999164c3e5988dba5
https://github.com/colbell/bitsa/blob/8b73c4988bde1bf8e64d9cb999164c3e5988dba5/lib/bitsa/cli.rb#L79-L90
train
thriventures/storage_room_gem
lib/storage_room/models/collection.rb
StorageRoom.Collection.field
def field(identifier) ensure_loaded do fields.each do |f| return f if f.identifier == identifier end end nil end
ruby
def field(identifier) ensure_loaded do fields.each do |f| return f if f.identifier == identifier end end nil end
[ "def", "field", "(", "identifier", ")", "ensure_loaded", "do", "fields", ".", "each", "do", "|", "f", "|", "return", "f", "if", "f", ".", "identifier", "==", "identifier", "end", "end", "nil", "end" ]
The field with a specific identifier
[ "The", "field", "with", "a", "specific", "identifier" ]
cadf132b865ff82f7b09fadfec1d294a714c6728
https://github.com/thriventures/storage_room_gem/blob/cadf132b865ff82f7b09fadfec1d294a714c6728/lib/storage_room/models/collection.rb#L51-L59
train
thriventures/storage_room_gem
lib/storage_room/models/collection.rb
StorageRoom.Collection.load_associated_collections
def load_associated_collections array = association_fields if array.map{|f| f.collection_loaded?}.include?(false) StorageRoom.log("Fetching associated collections for '#{name}'") array.each{|f| f.collection} end end
ruby
def load_associated_collections array = association_fields if array.map{|f| f.collection_loaded?}.include?(false) StorageRoom.log("Fetching associated collections for '#{name}'") array.each{|f| f.collection} end end
[ "def", "load_associated_collections", "array", "=", "association_fields", "if", "array", ".", "map", "{", "|", "f", "|", "f", ".", "collection_loaded?", "}", ".", "include?", "(", "false", ")", "StorageRoom", ".", "log", "(", "\"Fetching associated collections for '#{name}'\"", ")", "array", ".", "each", "{", "|", "f", "|", "f", ".", "collection", "}", "end", "end" ]
Load all Collections that are related to the current one through AssociationFields
[ "Load", "all", "Collections", "that", "are", "related", "to", "the", "current", "one", "through", "AssociationFields" ]
cadf132b865ff82f7b09fadfec1d294a714c6728
https://github.com/thriventures/storage_room_gem/blob/cadf132b865ff82f7b09fadfec1d294a714c6728/lib/storage_room/models/collection.rb#L67-L74
train
astjohn/cornerstone
app/models/cornerstone/discussion.rb
Cornerstone.Discussion.created_by?
def created_by?(check_user) return false unless check_user.present? return true if check_user.cornerstone_admin? self.user && self.user == check_user end
ruby
def created_by?(check_user) return false unless check_user.present? return true if check_user.cornerstone_admin? self.user && self.user == check_user end
[ "def", "created_by?", "(", "check_user", ")", "return", "false", "unless", "check_user", ".", "present?", "return", "true", "if", "check_user", ".", "cornerstone_admin?", "self", ".", "user", "&&", "self", ".", "user", "==", "check_user", "end" ]
returns true if it was created by given user or if given user is an admin
[ "returns", "true", "if", "it", "was", "created", "by", "given", "user", "or", "if", "given", "user", "is", "an", "admin" ]
d7af7c06288477c961f3e328b8640df4be337301
https://github.com/astjohn/cornerstone/blob/d7af7c06288477c961f3e328b8640df4be337301/app/models/cornerstone/discussion.rb#L49-L53
train
astjohn/cornerstone
app/models/cornerstone/discussion.rb
Cornerstone.Discussion.participants
def participants(exclude_email=nil) ps = [] self.posts.each do |p| if p.author_name && p.author_email ps << [p.author_name, p.author_email] end end ps.delete_if{|p| p[1] == exclude_email}.uniq end
ruby
def participants(exclude_email=nil) ps = [] self.posts.each do |p| if p.author_name && p.author_email ps << [p.author_name, p.author_email] end end ps.delete_if{|p| p[1] == exclude_email}.uniq end
[ "def", "participants", "(", "exclude_email", "=", "nil", ")", "ps", "=", "[", "]", "self", ".", "posts", ".", "each", "do", "|", "p", "|", "if", "p", ".", "author_name", "&&", "p", ".", "author_email", "ps", "<<", "[", "p", ".", "author_name", ",", "p", ".", "author_email", "]", "end", "end", "ps", ".", "delete_if", "{", "|", "p", "|", "p", "[", "1", "]", "==", "exclude_email", "}", ".", "uniq", "end" ]
returns an array of participants for the discussion
[ "returns", "an", "array", "of", "participants", "for", "the", "discussion" ]
d7af7c06288477c961f3e328b8640df4be337301
https://github.com/astjohn/cornerstone/blob/d7af7c06288477c961f3e328b8640df4be337301/app/models/cornerstone/discussion.rb#L56-L64
train
ktonon/code_node
spec/fixtures/activerecord/src/active_record/relation/calculations.rb
ActiveRecord.Calculations.count
def count(column_name = nil, options = {}) column_name, options = nil, column_name if column_name.is_a?(Hash) calculate(:count, column_name, options) end
ruby
def count(column_name = nil, options = {}) column_name, options = nil, column_name if column_name.is_a?(Hash) calculate(:count, column_name, options) end
[ "def", "count", "(", "column_name", "=", "nil", ",", "options", "=", "{", "}", ")", "column_name", ",", "options", "=", "nil", ",", "column_name", "if", "column_name", ".", "is_a?", "(", "Hash", ")", "calculate", "(", ":count", ",", "column_name", ",", "options", ")", "end" ]
Count operates using three different approaches. * Count all: By not passing any parameters to count, it will return a count of all the rows for the model. * Count using column: By passing a column name to count, it will return a count of all the rows for the model with supplied column present. * Count using options will find the row count matched by the options used. The third approach, count using options, accepts an option hash as the only parameter. The options are: * <tt>:conditions</tt>: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro to ActiveRecord::Base. * <tt>:joins</tt>: Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed) or named associations in the same form used for the <tt>:include</tt> option, which will perform an INNER JOIN on the associated table(s). If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table's columns. Pass <tt>:readonly => false</tt> to override. * <tt>:include</tt>: Named associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer to already defined associations. When using named associations, count returns the number of DISTINCT items for the model you're counting. See eager loading under Associations. * <tt>:order</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations). * <tt>:group</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause. * <tt>:select</tt>: By default, this is * as in SELECT * FROM, but can be changed if you, for example, want to do a join but not include the joined columns. * <tt>:distinct</tt>: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ... * <tt>:from</tt> - By default, this is the table name of the class, but can be changed to an alternate table name (or even the name of a database view). Examples for counting all: Person.count # returns the total count of all people Examples for counting by column: Person.count(:age) # returns the total count of all people whose age is present in database Examples for count with options: Person.count(:conditions => "age > 26") # because of the named association, it finds the DISTINCT count using LEFT OUTER JOIN. Person.count(:conditions => "age > 26 AND job.salary > 60000", :include => :job) # finds the number of rows matching the conditions and joins. Person.count(:conditions => "age > 26 AND job.salary > 60000", :joins => "LEFT JOIN jobs on jobs.person_id = person.id") Person.count('id', :conditions => "age > 26") # Performs a COUNT(id) Person.count(:all, :conditions => "age > 26") # Performs a COUNT(*) (:all is an alias for '*') Note: <tt>Person.count(:all)</tt> will not work because it will use <tt>:all</tt> as the condition. Use Person.count instead.
[ "Count", "operates", "using", "three", "different", "approaches", "." ]
48d5d1a7442d9cade602be4fb782a1b56c7677f5
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/relation/calculations.rb#L56-L59
train
ktonon/code_node
spec/fixtures/activerecord/src/active_record/relation/calculations.rb
ActiveRecord.Calculations.sum
def sum(*args) if block_given? self.to_a.sum(*args) {|*block_args| yield(*block_args)} else calculate(:sum, *args) end end
ruby
def sum(*args) if block_given? self.to_a.sum(*args) {|*block_args| yield(*block_args)} else calculate(:sum, *args) end end
[ "def", "sum", "(", "*", "args", ")", "if", "block_given?", "self", ".", "to_a", ".", "sum", "(", "*", "args", ")", "{", "|", "*", "block_args", "|", "yield", "(", "*", "block_args", ")", "}", "else", "calculate", "(", ":sum", ",", "*", "args", ")", "end", "end" ]
Calculates the sum of values on a given column. The value is returned with the same data type of the column, 0 if there's no row. See +calculate+ for examples with options. Person.sum('age') # => 4562
[ "Calculates", "the", "sum", "of", "values", "on", "a", "given", "column", ".", "The", "value", "is", "returned", "with", "the", "same", "data", "type", "of", "the", "column", "0", "if", "there", "s", "no", "row", ".", "See", "+", "calculate", "+", "for", "examples", "with", "options", "." ]
48d5d1a7442d9cade602be4fb782a1b56c7677f5
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/relation/calculations.rb#L92-L98
train
ktonon/code_node
spec/fixtures/activerecord/src/active_record/relation/query_methods.rb
ActiveRecord.QueryMethods.reorder
def reorder(*args) return self if args.blank? relation = clone relation.reordering_value = true relation.order_values = args.flatten relation end
ruby
def reorder(*args) return self if args.blank? relation = clone relation.reordering_value = true relation.order_values = args.flatten relation end
[ "def", "reorder", "(", "*", "args", ")", "return", "self", "if", "args", ".", "blank?", "relation", "=", "clone", "relation", ".", "reordering_value", "=", "true", "relation", ".", "order_values", "=", "args", ".", "flatten", "relation", "end" ]
Replaces any existing order defined on the relation with the specified order. User.order('email DESC').reorder('id ASC') # generated SQL has 'ORDER BY id ASC' Subsequent calls to order on the same relation will be appended. For example: User.order('email DESC').reorder('id ASC').order('name ASC') generates a query with 'ORDER BY id ASC, name ASC'.
[ "Replaces", "any", "existing", "order", "defined", "on", "the", "relation", "with", "the", "specified", "order", "." ]
48d5d1a7442d9cade602be4fb782a1b56c7677f5
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/relation/query_methods.rb#L106-L113
train
dnd/permit
lib/permit/permit_rule.rb
Permit.PermitRule.matches?
def matches?(person, context_binding) matched = if BUILTIN_ROLES.include? @roles[0] has_builtin_authorization? person, context_binding else has_named_authorizations? person, context_binding end passed_conditionals = matched ? passes_conditionals?(person, context_binding) : false passed = matched && passed_conditionals return passed end
ruby
def matches?(person, context_binding) matched = if BUILTIN_ROLES.include? @roles[0] has_builtin_authorization? person, context_binding else has_named_authorizations? person, context_binding end passed_conditionals = matched ? passes_conditionals?(person, context_binding) : false passed = matched && passed_conditionals return passed end
[ "def", "matches?", "(", "person", ",", "context_binding", ")", "matched", "=", "if", "BUILTIN_ROLES", ".", "include?", "@roles", "[", "0", "]", "has_builtin_authorization?", "person", ",", "context_binding", "else", "has_named_authorizations?", "person", ",", "context_binding", "end", "passed_conditionals", "=", "matched", "?", "passes_conditionals?", "(", "person", ",", "context_binding", ")", ":", "false", "passed", "=", "matched", "&&", "passed_conditionals", "return", "passed", "end" ]
Creates a new PermitRule. +:if+ and +:unless+ conditions may be evaluated for static, dynamic, and named authorizations. They are evaluated after the other rule checks are applied, and only if the rule still matches. The conditionals may make a matching rule not match, but will not make an unmatched rule match. If both +:if+ and +:unless+ are given the +:if+ condition is run first, and if the rule still matches the +:unless+ will be run. @param [:person, :guest, :everyone, Symbol, <Symbol>] roles the role(s) to test against. - :person - +current_person.guest? == false+ This person should be authenticated. This indicates a dynamic authorization. - :guest - +current_person.guest? == true+ This is a person that is not authenticated. This is a static authorization. - :everyone - Any user of the system. This is a static authorization. - Symbol/<Symbol> - This is the key or keys of any of the role(s) to match against in the database. This indicates a named authorization. @param [Hash] options the options to use to configure the authorization. @option options [Symbol] :who Indicates that a method should be checked on the target object to authorize. Checks a variety of possibilities, taking the first variation that the target responds to. When the symbol is prefixed with 'is_' then multiple methods will be tried passing the person in. The methods tried for +:is_owner+ would be +is_owner()+, +is_owner?()+, +owner()+, +owner+, +owners.exist?()+. If this option is given +:of+/+:on+ must also be given. @option options [Symbol] :that alias for +:who+ @option options [Symbol, nil, :any, <Symbol, nil>] :of The name of the instance variable(s) to use as the target resource(s). In a dynamic authorization this is the object that will be tested using the value of +:who+/+:that+. In a named authorization this is the resource the person must be authorized on for one or more of the roles. +:any+ may be given to indicate a match if the person has one of the roles for any resource. If not given, or set to +nil+, then the match will apply to a person that has a matching role authorization for a nil resource. @option options [Symbol, nil, :any, <Symbol, nil>] :on alias for +:of+ @option options [Symbol, String, Proc] :if code to evaluate at the end of the match if it is still valid. If it returns false, the rule will not match. If a proc if given, it will be passed the current subject and binding. A method will be called without any arguments. @option options [Symbol, String, Proc] :unless code to evaluate at the end of the match if it is still valid. If it returns true, the rule will not match. If a proc if given, it will be passed the current subject and binding. A method will be called without any arguments. @raise [PermitConfigurationError] if the rule options are invalid. Determine if the passed in person matches this rule. @param [permit_person] person the person to evaluate for authorization @param [Binding] context_binding the binding to use to locate the resource and/or evaluate the if/unless conditions. @return [Boolean] true if the person matches the rule, otherwise false. @raise [PermitEvaluationError] if there is a problem evaluating the rule.
[ "Creates", "a", "new", "PermitRule", "." ]
4bf41d5cc1fe1cbd100405bda773921e605f7a7a
https://github.com/dnd/permit/blob/4bf41d5cc1fe1cbd100405bda773921e605f7a7a/lib/permit/permit_rule.rb#L83-L93
train
jbe/lazy_load
lib/lazy_load.rb
LazyLoad.Mixin.best
def best(*names) names.map do |name| @groups[name] || name end.flatten.each do |name| begin return const_get(name) rescue NameError, LoadError; end end const_get(names.first) end
ruby
def best(*names) names.map do |name| @groups[name] || name end.flatten.each do |name| begin return const_get(name) rescue NameError, LoadError; end end const_get(names.first) end
[ "def", "best", "(", "*", "names", ")", "names", ".", "map", "do", "|", "name", "|", "@groups", "[", "name", "]", "||", "name", "end", ".", "flatten", ".", "each", "do", "|", "name", "|", "begin", "return", "const_get", "(", "name", ")", "rescue", "NameError", ",", "LoadError", ";", "end", "end", "const_get", "(", "names", ".", "first", ")", "end" ]
Return the first available dependency from the list of constant names.
[ "Return", "the", "first", "available", "dependency", "from", "the", "list", "of", "constant", "names", "." ]
41e5e8a08b130c1ba6f032c4d50e317e0140d1f2
https://github.com/jbe/lazy_load/blob/41e5e8a08b130c1ba6f032c4d50e317e0140d1f2/lib/lazy_load.rb#L63-L72
train
jonahoffline/link_shrink
lib/link_shrink/cli.rb
LinkShrink.CLI.set_options
def set_options(opts) opts.version, opts.banner = options.version, options.banner opts.set_program_name 'LinkShrink' options.api.map do |k, v| arg = k.to_s.downcase opts.on_head("-#{arg[0]}", "--#{arg}", argument_text_for(k)) do options.api[k] = true end end opts.on_tail('-v', '--version', 'display the version of LinkShrink and exit') do puts opts.ver exit end opts.on_tail('-h', '--help', 'print this help') do puts opts.help exit end end
ruby
def set_options(opts) opts.version, opts.banner = options.version, options.banner opts.set_program_name 'LinkShrink' options.api.map do |k, v| arg = k.to_s.downcase opts.on_head("-#{arg[0]}", "--#{arg}", argument_text_for(k)) do options.api[k] = true end end opts.on_tail('-v', '--version', 'display the version of LinkShrink and exit') do puts opts.ver exit end opts.on_tail('-h', '--help', 'print this help') do puts opts.help exit end end
[ "def", "set_options", "(", "opts", ")", "opts", ".", "version", ",", "opts", ".", "banner", "=", "options", ".", "version", ",", "options", ".", "banner", "opts", ".", "set_program_name", "'LinkShrink'", "options", ".", "api", ".", "map", "do", "|", "k", ",", "v", "|", "arg", "=", "k", ".", "to_s", ".", "downcase", "opts", ".", "on_head", "(", "\"-#{arg[0]}\"", ",", "\"--#{arg}\"", ",", "argument_text_for", "(", "k", ")", ")", "do", "options", ".", "api", "[", "k", "]", "=", "true", "end", "end", "opts", ".", "on_tail", "(", "'-v'", ",", "'--version'", ",", "'display the version of LinkShrink and exit'", ")", "do", "puts", "opts", ".", "ver", "exit", "end", "opts", ".", "on_tail", "(", "'-h'", ",", "'--help'", ",", "'print this help'", ")", "do", "puts", "opts", ".", "help", "exit", "end", "end" ]
Configures the arguments for the command @param opts [OptionParser]
[ "Configures", "the", "arguments", "for", "the", "command" ]
8ed842b4f004265e4e91693df72a4d8c49de3ea8
https://github.com/jonahoffline/link_shrink/blob/8ed842b4f004265e4e91693df72a4d8c49de3ea8/lib/link_shrink/cli.rb#L43-L65
train
jonahoffline/link_shrink
lib/link_shrink/cli.rb
LinkShrink.CLI.parse
def parse opts = OptionParser.new(&method(:set_options)) opts.parse!(@args) return process_url if url_present? opts.help end
ruby
def parse opts = OptionParser.new(&method(:set_options)) opts.parse!(@args) return process_url if url_present? opts.help end
[ "def", "parse", "opts", "=", "OptionParser", ".", "new", "(", "&", "method", "(", ":set_options", ")", ")", "opts", ".", "parse!", "(", "@args", ")", "return", "process_url", "if", "url_present?", "opts", ".", "help", "end" ]
Parses the command-line arguments and runs the executable @return [String] The short url or argument passed
[ "Parses", "the", "command", "-", "line", "arguments", "and", "runs", "the", "executable" ]
8ed842b4f004265e4e91693df72a4d8c49de3ea8
https://github.com/jonahoffline/link_shrink/blob/8ed842b4f004265e4e91693df72a4d8c49de3ea8/lib/link_shrink/cli.rb#L73-L78
train
zpatten/ztk
lib/ztk/base.rb
ZTK.Base.log_and_raise
def log_and_raise(exception, message, shift=2) Base.log_and_raise(config.ui.logger, exception, message, shift) end
ruby
def log_and_raise(exception, message, shift=2) Base.log_and_raise(config.ui.logger, exception, message, shift) end
[ "def", "log_and_raise", "(", "exception", ",", "message", ",", "shift", "=", "2", ")", "Base", ".", "log_and_raise", "(", "config", ".", "ui", ".", "logger", ",", "exception", ",", "message", ",", "shift", ")", "end" ]
Logs an exception and then raises it. @see Base.log_and_raise @param [Exception] exception The exception class to raise. @param [String] message The message to display with the exception. @param [Integer] shift (2) How many places to shift the caller stack in the log statement.
[ "Logs", "an", "exception", "and", "then", "raises", "it", "." ]
9b0f35bef36f38428e1a57b36f25a806c240b3fb
https://github.com/zpatten/ztk/blob/9b0f35bef36f38428e1a57b36f25a806c240b3fb/lib/ztk/base.rb#L103-L105
train
zpatten/ztk
lib/ztk/base.rb
ZTK.Base.direct_log
def direct_log(log_level, &blocK) @config.ui.logger.nil? and raise BaseError, "You must supply a logger for direct logging support!" if !block_given? log_and_raise(BaseError, "You must supply a block to the log method!") elsif (@config.ui.logger.level <= ::Logger.const_get(log_level.to_s.upcase)) @config.ui.logger << ZTK::ANSI.uncolor(yield) end end
ruby
def direct_log(log_level, &blocK) @config.ui.logger.nil? and raise BaseError, "You must supply a logger for direct logging support!" if !block_given? log_and_raise(BaseError, "You must supply a block to the log method!") elsif (@config.ui.logger.level <= ::Logger.const_get(log_level.to_s.upcase)) @config.ui.logger << ZTK::ANSI.uncolor(yield) end end
[ "def", "direct_log", "(", "log_level", ",", "&", "blocK", ")", "@config", ".", "ui", ".", "logger", ".", "nil?", "and", "raise", "BaseError", ",", "\"You must supply a logger for direct logging support!\"", "if", "!", "block_given?", "log_and_raise", "(", "BaseError", ",", "\"You must supply a block to the log method!\"", ")", "elsif", "(", "@config", ".", "ui", ".", "logger", ".", "level", "<=", "::", "Logger", ".", "const_get", "(", "log_level", ".", "to_s", ".", "upcase", ")", ")", "@config", ".", "ui", ".", "logger", "<<", "ZTK", "::", "ANSI", ".", "uncolor", "(", "yield", ")", "end", "end" ]
Direct logging method. This method provides direct writing of data to the current log device. This is mainly used for pushing STDOUT and STDERR into the log file in ZTK::SSH and ZTK::Command, but could easily be used by other classes. The value returned in the block is passed down to the logger specified in the classes configuration. @param [Symbol] log_level This should be any one of [:debug, :info, :warn, :error, :fatal]. @yield No value is passed to the block. @yieldreturn [String] The message to log.
[ "Direct", "logging", "method", "." ]
9b0f35bef36f38428e1a57b36f25a806c240b3fb
https://github.com/zpatten/ztk/blob/9b0f35bef36f38428e1a57b36f25a806c240b3fb/lib/ztk/base.rb#L119-L127
train
colbell/bitsa
lib/bitsa/settings.rb
Bitsa.Settings.load_config_file_settings
def load_config_file_settings(config_file_hash) @login = config_file_hash.data[:login] @password = config_file_hash.data[:password] @cache_file_path = config_file_hash.data[:cache_file_path] @auto_check = config_file_hash.data[:auto_check] end
ruby
def load_config_file_settings(config_file_hash) @login = config_file_hash.data[:login] @password = config_file_hash.data[:password] @cache_file_path = config_file_hash.data[:cache_file_path] @auto_check = config_file_hash.data[:auto_check] end
[ "def", "load_config_file_settings", "(", "config_file_hash", ")", "@login", "=", "config_file_hash", ".", "data", "[", ":login", "]", "@password", "=", "config_file_hash", ".", "data", "[", ":password", "]", "@cache_file_path", "=", "config_file_hash", ".", "data", "[", ":cache_file_path", "]", "@auto_check", "=", "config_file_hash", ".", "data", "[", ":auto_check", "]", "end" ]
Load settings from the configuration file hash. @param [Hash] config_file_hash <tt>Hash</tt> of settings loaded from configuration file.
[ "Load", "settings", "from", "the", "configuration", "file", "hash", "." ]
8b73c4988bde1bf8e64d9cb999164c3e5988dba5
https://github.com/colbell/bitsa/blob/8b73c4988bde1bf8e64d9cb999164c3e5988dba5/lib/bitsa/settings.rb#L81-L86
train
colbell/bitsa
lib/bitsa/settings.rb
Bitsa.Settings.load_cmd_line_settings
def load_cmd_line_settings(options) @login = options[:login] if options[:login] @password = options[:password] if options[:password] @cache_file_path = options[:cache_file_path] if options[:cache_file_path] @auto_check = options[:auto_check] if options[:auto_check] end
ruby
def load_cmd_line_settings(options) @login = options[:login] if options[:login] @password = options[:password] if options[:password] @cache_file_path = options[:cache_file_path] if options[:cache_file_path] @auto_check = options[:auto_check] if options[:auto_check] end
[ "def", "load_cmd_line_settings", "(", "options", ")", "@login", "=", "options", "[", ":login", "]", "if", "options", "[", ":login", "]", "@password", "=", "options", "[", ":password", "]", "if", "options", "[", ":password", "]", "@cache_file_path", "=", "options", "[", ":cache_file_path", "]", "if", "options", "[", ":cache_file_path", "]", "@auto_check", "=", "options", "[", ":auto_check", "]", "if", "options", "[", ":auto_check", "]", "end" ]
Load settings from the command line hash. Load a setting only if it was passed. @param [Hash] options <tt>Hash</tt> of settings passed on command line.
[ "Load", "settings", "from", "the", "command", "line", "hash", ".", "Load", "a", "setting", "only", "if", "it", "was", "passed", "." ]
8b73c4988bde1bf8e64d9cb999164c3e5988dba5
https://github.com/colbell/bitsa/blob/8b73c4988bde1bf8e64d9cb999164c3e5988dba5/lib/bitsa/settings.rb#L92-L97
train
matharvard/tastes_bitter
app/controllers/tastes_bitter/javascript_errors_controller.rb
TastesBitter.JavascriptErrorsController.create
def create browser = Browser.new(ua: params["user_agent"]) error_info = { message: params["message"], file_or_page: params["file_or_page"], line_number: params["line_number"], column_number: params["column_number"], user_agent: params["user_agent"], current_page: params["current_page"], platform: browser.platform.to_s.humanize, browser_name: browser.name, browser_version: browser.full_version, user_ip: request.remote_ip, referrer: request.env["HTTP_REFERER"], stack_trace: params["stack_trace"] } ::TastesBitter::JavascriptErrorsMailer.javascript_error(error_info).deliver_later respond_to do |format| format.js { render nothing: true, status: :ok } end end
ruby
def create browser = Browser.new(ua: params["user_agent"]) error_info = { message: params["message"], file_or_page: params["file_or_page"], line_number: params["line_number"], column_number: params["column_number"], user_agent: params["user_agent"], current_page: params["current_page"], platform: browser.platform.to_s.humanize, browser_name: browser.name, browser_version: browser.full_version, user_ip: request.remote_ip, referrer: request.env["HTTP_REFERER"], stack_trace: params["stack_trace"] } ::TastesBitter::JavascriptErrorsMailer.javascript_error(error_info).deliver_later respond_to do |format| format.js { render nothing: true, status: :ok } end end
[ "def", "create", "browser", "=", "Browser", ".", "new", "(", "ua", ":", "params", "[", "\"user_agent\"", "]", ")", "error_info", "=", "{", "message", ":", "params", "[", "\"message\"", "]", ",", "file_or_page", ":", "params", "[", "\"file_or_page\"", "]", ",", "line_number", ":", "params", "[", "\"line_number\"", "]", ",", "column_number", ":", "params", "[", "\"column_number\"", "]", ",", "user_agent", ":", "params", "[", "\"user_agent\"", "]", ",", "current_page", ":", "params", "[", "\"current_page\"", "]", ",", "platform", ":", "browser", ".", "platform", ".", "to_s", ".", "humanize", ",", "browser_name", ":", "browser", ".", "name", ",", "browser_version", ":", "browser", ".", "full_version", ",", "user_ip", ":", "request", ".", "remote_ip", ",", "referrer", ":", "request", ".", "env", "[", "\"HTTP_REFERER\"", "]", ",", "stack_trace", ":", "params", "[", "\"stack_trace\"", "]", "}", "::", "TastesBitter", "::", "JavascriptErrorsMailer", ".", "javascript_error", "(", "error_info", ")", ".", "deliver_later", "respond_to", "do", "|", "format", "|", "format", ".", "js", "{", "render", "nothing", ":", "true", ",", "status", ":", ":ok", "}", "end", "end" ]
Responsible for handling errors sent from the browser, parsing the data, and sending the email with the information about the error.
[ "Responsible", "for", "handling", "errors", "sent", "from", "the", "browser", "parsing", "the", "data", "and", "sending", "the", "email", "with", "the", "information", "about", "the", "error", "." ]
20e50883dbe4d99282bbd831d7090d0cf56a0665
https://github.com/matharvard/tastes_bitter/blob/20e50883dbe4d99282bbd831d7090d0cf56a0665/app/controllers/tastes_bitter/javascript_errors_controller.rb#L10-L33
train
26fe/sem4r
lib/sem4r/report_definition/report_definition_account_extension.rb
Sem4r.ReportDefinitionAccountExtension.report_fields
def report_fields(report_type) soap_message = service.report_definition.report_fields(credentials, report_type) add_counters(soap_message.counters) els = soap_message.response.xpath("//getReportFieldsResponse/rval") els.map do |el| ReportField.from_element(el) end end
ruby
def report_fields(report_type) soap_message = service.report_definition.report_fields(credentials, report_type) add_counters(soap_message.counters) els = soap_message.response.xpath("//getReportFieldsResponse/rval") els.map do |el| ReportField.from_element(el) end end
[ "def", "report_fields", "(", "report_type", ")", "soap_message", "=", "service", ".", "report_definition", ".", "report_fields", "(", "credentials", ",", "report_type", ")", "add_counters", "(", "soap_message", ".", "counters", ")", "els", "=", "soap_message", ".", "response", ".", "xpath", "(", "\"//getReportFieldsResponse/rval\"", ")", "els", ".", "map", "do", "|", "el", "|", "ReportField", ".", "from_element", "(", "el", ")", "end", "end" ]
Query the list of field for a report type @param [ReportDefinition::ReportTypes] a value of
[ "Query", "the", "list", "of", "field", "for", "a", "report", "type" ]
2326404f98b9c2833549fcfda078d39c9954a0fa
https://github.com/26fe/sem4r/blob/2326404f98b9c2833549fcfda078d39c9954a0fa/lib/sem4r/report_definition/report_definition_account_extension.rb#L33-L40
train
26fe/sem4r
lib/sem4r/report_definition/report_definition_account_extension.rb
Sem4r.ReportDefinitionAccountExtension.report_definition_delete
def report_definition_delete(repdef_or_id) if repdef_or_id.class == ReportDefinition report_definition = repdef_or_id else report_definition = ReportDefinition.new(self) report_definition.instance_eval { @id = repdef_or_id } end op = ReportDefinitionOperation.remove(report_definition) soap_message = service.report_definition.mutate(credentials, op.to_xml) add_counters(soap_message.counters) unless @report_definitions @report_definition.delete_if { |repdef| repdef == report_definition.id } end report_definition.instance_eval { @id = -1 } # repdef status invalid/deleted self end
ruby
def report_definition_delete(repdef_or_id) if repdef_or_id.class == ReportDefinition report_definition = repdef_or_id else report_definition = ReportDefinition.new(self) report_definition.instance_eval { @id = repdef_or_id } end op = ReportDefinitionOperation.remove(report_definition) soap_message = service.report_definition.mutate(credentials, op.to_xml) add_counters(soap_message.counters) unless @report_definitions @report_definition.delete_if { |repdef| repdef == report_definition.id } end report_definition.instance_eval { @id = -1 } # repdef status invalid/deleted self end
[ "def", "report_definition_delete", "(", "repdef_or_id", ")", "if", "repdef_or_id", ".", "class", "==", "ReportDefinition", "report_definition", "=", "repdef_or_id", "else", "report_definition", "=", "ReportDefinition", ".", "new", "(", "self", ")", "report_definition", ".", "instance_eval", "{", "@id", "=", "repdef_or_id", "}", "end", "op", "=", "ReportDefinitionOperation", ".", "remove", "(", "report_definition", ")", "soap_message", "=", "service", ".", "report_definition", ".", "mutate", "(", "credentials", ",", "op", ".", "to_xml", ")", "add_counters", "(", "soap_message", ".", "counters", ")", "unless", "@report_definitions", "@report_definition", ".", "delete_if", "{", "|", "repdef", "|", "repdef", "==", "report_definition", ".", "id", "}", "end", "report_definition", ".", "instance_eval", "{", "@id", "=", "-", "1", "}", "self", "end" ]
Delete a report definition @param[ReportDefinition, Number]
[ "Delete", "a", "report", "definition" ]
2326404f98b9c2833549fcfda078d39c9954a0fa
https://github.com/26fe/sem4r/blob/2326404f98b9c2833549fcfda078d39c9954a0fa/lib/sem4r/report_definition/report_definition_account_extension.rb#L47-L64
train
26fe/sem4r
lib/sem4r/report_definition/report_definition_account_extension.rb
Sem4r.ReportDefinitionAccountExtension.p_report_definitions
def p_report_definitions(refresh = false) report_definitions(refresh).each do |report_definition| puts report_definition.to_s end self end
ruby
def p_report_definitions(refresh = false) report_definitions(refresh).each do |report_definition| puts report_definition.to_s end self end
[ "def", "p_report_definitions", "(", "refresh", "=", "false", ")", "report_definitions", "(", "refresh", ")", ".", "each", "do", "|", "report_definition", "|", "puts", "report_definition", ".", "to_s", "end", "self", "end" ]
Prints on stdout the list of report definition contained into account @param [bool] true if the list must be refreshed @return self
[ "Prints", "on", "stdout", "the", "list", "of", "report", "definition", "contained", "into", "account" ]
2326404f98b9c2833549fcfda078d39c9954a0fa
https://github.com/26fe/sem4r/blob/2326404f98b9c2833549fcfda078d39c9954a0fa/lib/sem4r/report_definition/report_definition_account_extension.rb#L95-L100
train
rgeyer/rs_user_policy
lib/rs_user_policy/user_collection.rb
RsUserPolicy.UserCollection.add_users
def add_users(users) users.each do |user| unless @users_by_href.has_key?(user.href) @users_by_href[user.href] = RsUserPolicy::User.new(user) end end end
ruby
def add_users(users) users.each do |user| unless @users_by_href.has_key?(user.href) @users_by_href[user.href] = RsUserPolicy::User.new(user) end end end
[ "def", "add_users", "(", "users", ")", "users", ".", "each", "do", "|", "user", "|", "unless", "@users_by_href", ".", "has_key?", "(", "user", ".", "href", ")", "@users_by_href", "[", "user", ".", "href", "]", "=", "RsUserPolicy", "::", "User", ".", "new", "(", "user", ")", "end", "end", "end" ]
Adds users to this collection only if the collection does not already include the specified users. The users RightScale API href is used as the unique identifier for deduplication @param [Array<RightApi::ResourceDetail>] users An array of RightAPI::ResourceDetail for the resource type "user"
[ "Adds", "users", "to", "this", "collection", "only", "if", "the", "collection", "does", "not", "already", "include", "the", "specified", "users", ".", "The", "users", "RightScale", "API", "href", "is", "used", "as", "the", "unique", "identifier", "for", "deduplication" ]
bae3355f1471cc7d28de7992c5d5f4ac39fff68b
https://github.com/rgeyer/rs_user_policy/blob/bae3355f1471cc7d28de7992c5d5f4ac39fff68b/lib/rs_user_policy/user_collection.rb#L41-L47
train
colstrom/ezmq
lib/ezmq/subscribe.rb
EZMQ.Subscriber.receive
def receive(**options) message = '' @socket.recv_string message message = message.match(/^(?<topic>[^\ ]*)\ (?<body>.*)/m) decoded = (options[:decode] || @decode).call message['body'] if block_given? yield decoded, message['topic'] else [decoded, message['topic']] end end
ruby
def receive(**options) message = '' @socket.recv_string message message = message.match(/^(?<topic>[^\ ]*)\ (?<body>.*)/m) decoded = (options[:decode] || @decode).call message['body'] if block_given? yield decoded, message['topic'] else [decoded, message['topic']] end end
[ "def", "receive", "(", "**", "options", ")", "message", "=", "''", "@socket", ".", "recv_string", "message", "message", "=", "message", ".", "match", "(", "/", "\\ ", "\\ ", "/m", ")", "decoded", "=", "(", "options", "[", ":decode", "]", "||", "@decode", ")", ".", "call", "message", "[", "'body'", "]", "if", "block_given?", "yield", "decoded", ",", "message", "[", "'topic'", "]", "else", "[", "decoded", ",", "message", "[", "'topic'", "]", "]", "end", "end" ]
Creates a new Subscriber socket. @note The default behaviour is to output and messages received to STDOUT. @param [:bind, :connect] mode (:connect) a mode for the socket. @param [Hash] options optional parameters. @option options [String] topic a topic to subscribe to. @see EZMQ::Socket EZMQ::Socket for optional parameters. @return [Publisher] a new instance of Publisher. Receive a message from the socket. @note This method blocks until a message arrives. @param [Hash] options optional parameters. @option options [lambda] decode how to decode the message. @yield [message, topic] passes the message body and topic to the block. @yieldparam [Object] message the message received (decoded). @yieldparam [String] topic the topic of the message. @return [Object] the message received (decoded).
[ "Creates", "a", "new", "Subscriber", "socket", "." ]
cd7f9f256d6c3f7a844871a3a77a89d7122d5836
https://github.com/colstrom/ezmq/blob/cd7f9f256d6c3f7a844871a3a77a89d7122d5836/lib/ezmq/subscribe.rb#L36-L48
train
bilus/kawaii
lib/kawaii/render_methods.rb
Kawaii.RenderMethods.render
def render(tmpl) t = Tilt.new(File.join('views', tmpl)) # @todo Caching! t.render(self) end
ruby
def render(tmpl) t = Tilt.new(File.join('views', tmpl)) # @todo Caching! t.render(self) end
[ "def", "render", "(", "tmpl", ")", "t", "=", "Tilt", ".", "new", "(", "File", ".", "join", "(", "'views'", ",", "tmpl", ")", ")", "t", ".", "render", "(", "self", ")", "end" ]
Renders a template. @param tmpl [String] file name or path to template, relative to /views in project dir @example Rendering html erb file render('index.html.erb') @todo Layouts.
[ "Renders", "a", "template", "." ]
a72be28e713b0ed2b2cfc180a38bebe0c968b0b3
https://github.com/bilus/kawaii/blob/a72be28e713b0ed2b2cfc180a38bebe0c968b0b3/lib/kawaii/render_methods.rb#L10-L13
train
sonots/growthforecast-client
lib/growthforecast/client.rb
GrowthForecast.Client.get_json
def get_json(path) @request_uri = "#{@base_uri}#{path}" req = get_request(path) @res = http_connection.start {|http| http.request(req) } handle_error(@res, @request_uri) JSON.parse(@res.body) end
ruby
def get_json(path) @request_uri = "#{@base_uri}#{path}" req = get_request(path) @res = http_connection.start {|http| http.request(req) } handle_error(@res, @request_uri) JSON.parse(@res.body) end
[ "def", "get_json", "(", "path", ")", "@request_uri", "=", "\"#{@base_uri}#{path}\"", "req", "=", "get_request", "(", "path", ")", "@res", "=", "http_connection", ".", "start", "{", "|", "http", "|", "http", ".", "request", "(", "req", ")", "}", "handle_error", "(", "@res", ",", "@request_uri", ")", "JSON", ".", "parse", "(", "@res", ".", "body", ")", "end" ]
GET the JSON API @param [String] path @return [Hash] response body
[ "GET", "the", "JSON", "API" ]
6e0c463fe47627a96bded7e628f9456da4aa69ee
https://github.com/sonots/growthforecast-client/blob/6e0c463fe47627a96bded7e628f9456da4aa69ee/lib/growthforecast/client.rb#L84-L90
train
sonots/growthforecast-client
lib/growthforecast/client.rb
GrowthForecast.Client.post_json
def post_json(path, data = {}) @request_uri = "#{@base_uri}#{path}" body = JSON.generate(data) extheader = { 'Content-Type' => 'application/json' } req = post_request(path, body, extheader) @res = http_connection.start {|http| http.request(req) } handle_error(@res, @request_uri) JSON.parse(@res.body) end
ruby
def post_json(path, data = {}) @request_uri = "#{@base_uri}#{path}" body = JSON.generate(data) extheader = { 'Content-Type' => 'application/json' } req = post_request(path, body, extheader) @res = http_connection.start {|http| http.request(req) } handle_error(@res, @request_uri) JSON.parse(@res.body) end
[ "def", "post_json", "(", "path", ",", "data", "=", "{", "}", ")", "@request_uri", "=", "\"#{@base_uri}#{path}\"", "body", "=", "JSON", ".", "generate", "(", "data", ")", "extheader", "=", "{", "'Content-Type'", "=>", "'application/json'", "}", "req", "=", "post_request", "(", "path", ",", "body", ",", "extheader", ")", "@res", "=", "http_connection", ".", "start", "{", "|", "http", "|", "http", ".", "request", "(", "req", ")", "}", "handle_error", "(", "@res", ",", "@request_uri", ")", "JSON", ".", "parse", "(", "@res", ".", "body", ")", "end" ]
POST the JSON API @param [String] path @param [Hash] data @return [Hash] response body
[ "POST", "the", "JSON", "API" ]
6e0c463fe47627a96bded7e628f9456da4aa69ee
https://github.com/sonots/growthforecast-client/blob/6e0c463fe47627a96bded7e628f9456da4aa69ee/lib/growthforecast/client.rb#L96-L104
train
sonots/growthforecast-client
lib/growthforecast/client.rb
GrowthForecast.Client.post_query
def post_query(path, data = {}) @request_uri = "#{@base_uri}#{path}" body = URI.encode_www_form(data) extheader = { 'Content-Type' => 'application/x-www-form-urlencoded' } req = post_request(path, body, extheader) @res = http_connection.start {|http| http.request(req) } handle_error(@res, @request_uri) JSON.parse(@res.body) end
ruby
def post_query(path, data = {}) @request_uri = "#{@base_uri}#{path}" body = URI.encode_www_form(data) extheader = { 'Content-Type' => 'application/x-www-form-urlencoded' } req = post_request(path, body, extheader) @res = http_connection.start {|http| http.request(req) } handle_error(@res, @request_uri) JSON.parse(@res.body) end
[ "def", "post_query", "(", "path", ",", "data", "=", "{", "}", ")", "@request_uri", "=", "\"#{@base_uri}#{path}\"", "body", "=", "URI", ".", "encode_www_form", "(", "data", ")", "extheader", "=", "{", "'Content-Type'", "=>", "'application/x-www-form-urlencoded'", "}", "req", "=", "post_request", "(", "path", ",", "body", ",", "extheader", ")", "@res", "=", "http_connection", ".", "start", "{", "|", "http", "|", "http", ".", "request", "(", "req", ")", "}", "handle_error", "(", "@res", ",", "@request_uri", ")", "JSON", ".", "parse", "(", "@res", ".", "body", ")", "end" ]
POST the non-JSON API @param [String] path @param [Hash] data @return [String] response body
[ "POST", "the", "non", "-", "JSON", "API" ]
6e0c463fe47627a96bded7e628f9456da4aa69ee
https://github.com/sonots/growthforecast-client/blob/6e0c463fe47627a96bded7e628f9456da4aa69ee/lib/growthforecast/client.rb#L110-L118
train
malev/freeling-client
lib/freeling_client/analyzer.rb
FreelingClient.Analyzer.tokens
def tokens(cmd, text) valide_command!(cmd) Enumerator.new do |yielder| call(cmd, text).each do |freeling_line| yielder << parse_token_line(freeling_line) unless freeling_line.empty? end end end
ruby
def tokens(cmd, text) valide_command!(cmd) Enumerator.new do |yielder| call(cmd, text).each do |freeling_line| yielder << parse_token_line(freeling_line) unless freeling_line.empty? end end end
[ "def", "tokens", "(", "cmd", ",", "text", ")", "valide_command!", "(", "cmd", ")", "Enumerator", ".", "new", "do", "|", "yielder", "|", "call", "(", "cmd", ",", "text", ")", ".", "each", "do", "|", "freeling_line", "|", "yielder", "<<", "parse_token_line", "(", "freeling_line", ")", "unless", "freeling_line", ".", "empty?", "end", "end", "end" ]
Generate tokens for a given text Example: >> analyzer = FreelingClient::Analyzer.new >> analyzer.token(:morfo, "Este texto está en español.") Arguments: cmd: (Symbol) text: (String)
[ "Generate", "tokens", "for", "a", "given", "text" ]
1ca32aa9edf8fbc60a48cf23bf298db38b84fc8c
https://github.com/malev/freeling-client/blob/1ca32aa9edf8fbc60a48cf23bf298db38b84fc8c/lib/freeling_client/analyzer.rb#L29-L36
train
Figure53/qlab-ruby
lib/qlab-ruby/machine.rb
QLab.Machine.find_workspace
def find_workspace params={} workspaces.find do |ws| matches = true # match each key to the given workspace params.keys.each do |key| matches = matches && (ws.send(key.to_sym) == params[key]) end matches end end
ruby
def find_workspace params={} workspaces.find do |ws| matches = true # match each key to the given workspace params.keys.each do |key| matches = matches && (ws.send(key.to_sym) == params[key]) end matches end end
[ "def", "find_workspace", "params", "=", "{", "}", "workspaces", ".", "find", "do", "|", "ws", "|", "matches", "=", "true", "params", ".", "keys", ".", "each", "do", "|", "key", "|", "matches", "=", "matches", "&&", "(", "ws", ".", "send", "(", "key", ".", "to_sym", ")", "==", "params", "[", "key", "]", ")", "end", "matches", "end", "end" ]
Find a workspace according to the given params.
[ "Find", "a", "workspace", "according", "to", "the", "given", "params", "." ]
169494940f478b897066db4c15f130769aa43243
https://github.com/Figure53/qlab-ruby/blob/169494940f478b897066db4c15f130769aa43243/lib/qlab-ruby/machine.rb#L47-L58
train
yipdw/analysand
lib/analysand/errors.rb
Analysand.Errors.ex
def ex(klass, response) klass.new("Expected response to have code 2xx, got #{response.code} instead").tap do |ex| ex.response = response end end
ruby
def ex(klass, response) klass.new("Expected response to have code 2xx, got #{response.code} instead").tap do |ex| ex.response = response end end
[ "def", "ex", "(", "klass", ",", "response", ")", "klass", ".", "new", "(", "\"Expected response to have code 2xx, got #{response.code} instead\"", ")", ".", "tap", "do", "|", "ex", "|", "ex", ".", "response", "=", "response", "end", "end" ]
Instantiates an exception and fills in a response. klass - the exception class response - the response object that caused the error
[ "Instantiates", "an", "exception", "and", "fills", "in", "a", "response", "." ]
bc62e67031bf7e813e49538669f7434f2efd9ee9
https://github.com/yipdw/analysand/blob/bc62e67031bf7e813e49538669f7434f2efd9ee9/lib/analysand/errors.rb#L8-L12
train
wapcaplet/kelp
lib/kelp/checkbox.rb
Kelp.Checkbox.checkbox_should_be_checked
def checkbox_should_be_checked(checkbox, scope={}) in_scope(scope) do field_checked = find_field(checkbox)['checked'] if !field_checked raise Kelp::Unexpected, "Expected '#{checkbox}' to be checked, but it is unchecked." end end end
ruby
def checkbox_should_be_checked(checkbox, scope={}) in_scope(scope) do field_checked = find_field(checkbox)['checked'] if !field_checked raise Kelp::Unexpected, "Expected '#{checkbox}' to be checked, but it is unchecked." end end end
[ "def", "checkbox_should_be_checked", "(", "checkbox", ",", "scope", "=", "{", "}", ")", "in_scope", "(", "scope", ")", "do", "field_checked", "=", "find_field", "(", "checkbox", ")", "[", "'checked'", "]", "if", "!", "field_checked", "raise", "Kelp", "::", "Unexpected", ",", "\"Expected '#{checkbox}' to be checked, but it is unchecked.\"", "end", "end", "end" ]
Verify that the given checkbox is checked. @param [String] checkbox Capybara locator for the checkbox @param [Hash] scope Scoping keywords as understood by {#in_scope} @raise [Kelp::Unexpected] If the given checkbox is not checked @since 0.1.2
[ "Verify", "that", "the", "given", "checkbox", "is", "checked", "." ]
592fe188db5a3d05e6120ed2157ad8d781601b7a
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/checkbox.rb#L22-L30
train
michaeledgar/amp-front
lib/amp-front/third_party/maruku/string_utils.rb
MaRuKu.Strings.parse_email_headers
def parse_email_headers(s) keys={} match = (s =~ /\A((\w[\w\s\_\-]+: .*\n)+)\s*\n/) if match != 0 keys[:data] = s else keys[:data] = $' headers = $1 headers.split("\n").each do |l| # Fails if there are other ':' characters. # k, v = l.split(':') k, v = l.split(':', 2) k, v = normalize_key_and_value(k, v) k = k.to_sym # puts "K = #{k}, V=#{v}" keys[k] = v end end keys end
ruby
def parse_email_headers(s) keys={} match = (s =~ /\A((\w[\w\s\_\-]+: .*\n)+)\s*\n/) if match != 0 keys[:data] = s else keys[:data] = $' headers = $1 headers.split("\n").each do |l| # Fails if there are other ':' characters. # k, v = l.split(':') k, v = l.split(':', 2) k, v = normalize_key_and_value(k, v) k = k.to_sym # puts "K = #{k}, V=#{v}" keys[k] = v end end keys end
[ "def", "parse_email_headers", "(", "s", ")", "keys", "=", "{", "}", "match", "=", "(", "s", "=~", "/", "\\A", "\\w", "\\w", "\\s", "\\_", "\\-", "\\n", "\\s", "\\n", "/", ")", "if", "match", "!=", "0", "keys", "[", ":data", "]", "=", "s", "else", "keys", "[", ":data", "]", "=", "$'", "headers", "=", "$1", "headers", ".", "split", "(", "\"\\n\"", ")", ".", "each", "do", "|", "l", "|", "k", ",", "v", "=", "l", ".", "split", "(", "':'", ",", "2", ")", "k", ",", "v", "=", "normalize_key_and_value", "(", "k", ",", "v", ")", "k", "=", "k", ".", "to_sym", "keys", "[", "k", "]", "=", "v", "end", "end", "keys", "end" ]
This parses email headers. Returns an hash. +hash['data']+ is the message. Keys are downcased, space becomes underscore, converted to symbols. My key: true becomes: {:my_key => true}
[ "This", "parses", "email", "headers", ".", "Returns", "an", "hash", "." ]
d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9
https://github.com/michaeledgar/amp-front/blob/d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9/lib/amp-front/third_party/maruku/string_utils.rb#L47-L66
train
michaeledgar/amp-front
lib/amp-front/third_party/maruku/string_utils.rb
MaRuKu.Strings.normalize_key_and_value
def normalize_key_and_value(k,v) v = v ? v.strip : true # no value defaults to true k = k.strip # check synonyms v = true if ['yes','true'].include?(v.to_s.downcase) v = false if ['no','false'].include?(v.to_s.downcase) k = k.downcase.gsub(' ','_') return k, v end
ruby
def normalize_key_and_value(k,v) v = v ? v.strip : true # no value defaults to true k = k.strip # check synonyms v = true if ['yes','true'].include?(v.to_s.downcase) v = false if ['no','false'].include?(v.to_s.downcase) k = k.downcase.gsub(' ','_') return k, v end
[ "def", "normalize_key_and_value", "(", "k", ",", "v", ")", "v", "=", "v", "?", "v", ".", "strip", ":", "true", "k", "=", "k", ".", "strip", "v", "=", "true", "if", "[", "'yes'", ",", "'true'", "]", ".", "include?", "(", "v", ".", "to_s", ".", "downcase", ")", "v", "=", "false", "if", "[", "'no'", ",", "'false'", "]", ".", "include?", "(", "v", ".", "to_s", ".", "downcase", ")", "k", "=", "k", ".", "downcase", ".", "gsub", "(", "' '", ",", "'_'", ")", "return", "k", ",", "v", "end" ]
Keys are downcased, space becomes underscore, converted to symbols.
[ "Keys", "are", "downcased", "space", "becomes", "underscore", "converted", "to", "symbols", "." ]
d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9
https://github.com/michaeledgar/amp-front/blob/d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9/lib/amp-front/third_party/maruku/string_utils.rb#L69-L79
train
michaeledgar/amp-front
lib/amp-front/third_party/maruku/string_utils.rb
MaRuKu.Strings.number_of_leading_spaces
def number_of_leading_spaces(s) n=0; i=0; while i < s.size c = s[i,1] if c == ' ' i+=1; n+=1; elsif c == "\t" i+=1; n+=TabSize; else break end end n end
ruby
def number_of_leading_spaces(s) n=0; i=0; while i < s.size c = s[i,1] if c == ' ' i+=1; n+=1; elsif c == "\t" i+=1; n+=TabSize; else break end end n end
[ "def", "number_of_leading_spaces", "(", "s", ")", "n", "=", "0", ";", "i", "=", "0", ";", "while", "i", "<", "s", ".", "size", "c", "=", "s", "[", "i", ",", "1", "]", "if", "c", "==", "' '", "i", "+=", "1", ";", "n", "+=", "1", ";", "elsif", "c", "==", "\"\\t\"", "i", "+=", "1", ";", "n", "+=", "TabSize", ";", "else", "break", "end", "end", "n", "end" ]
Returns the number of leading spaces, considering that a tab counts as `TabSize` spaces.
[ "Returns", "the", "number", "of", "leading", "spaces", "considering", "that", "a", "tab", "counts", "as", "TabSize", "spaces", "." ]
d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9
https://github.com/michaeledgar/amp-front/blob/d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9/lib/amp-front/third_party/maruku/string_utils.rb#L83-L96
train
michaeledgar/amp-front
lib/amp-front/third_party/maruku/string_utils.rb
MaRuKu.Strings.spaces_before_first_char
def spaces_before_first_char(s) case s.md_type when :ulist i=0; # skip whitespace if present while s[i,1] =~ /\s/; i+=1 end # skip indicator (+, -, *) i+=1 # skip optional whitespace while s[i,1] =~ /\s/; i+=1 end return i when :olist i=0; # skip whitespace while s[i,1] =~ /\s/; i+=1 end # skip digits while s[i,1] =~ /\d/; i+=1 end # skip dot i+=1 # skip whitespace while s[i,1] =~ /\s/; i+=1 end return i else tell_user "BUG (my bad): '#{s}' is not a list" 0 end end
ruby
def spaces_before_first_char(s) case s.md_type when :ulist i=0; # skip whitespace if present while s[i,1] =~ /\s/; i+=1 end # skip indicator (+, -, *) i+=1 # skip optional whitespace while s[i,1] =~ /\s/; i+=1 end return i when :olist i=0; # skip whitespace while s[i,1] =~ /\s/; i+=1 end # skip digits while s[i,1] =~ /\d/; i+=1 end # skip dot i+=1 # skip whitespace while s[i,1] =~ /\s/; i+=1 end return i else tell_user "BUG (my bad): '#{s}' is not a list" 0 end end
[ "def", "spaces_before_first_char", "(", "s", ")", "case", "s", ".", "md_type", "when", ":ulist", "i", "=", "0", ";", "while", "s", "[", "i", ",", "1", "]", "=~", "/", "\\s", "/", ";", "i", "+=", "1", "end", "i", "+=", "1", "while", "s", "[", "i", ",", "1", "]", "=~", "/", "\\s", "/", ";", "i", "+=", "1", "end", "return", "i", "when", ":olist", "i", "=", "0", ";", "while", "s", "[", "i", ",", "1", "]", "=~", "/", "\\s", "/", ";", "i", "+=", "1", "end", "while", "s", "[", "i", ",", "1", "]", "=~", "/", "\\d", "/", ";", "i", "+=", "1", "end", "i", "+=", "1", "while", "s", "[", "i", ",", "1", "]", "=~", "/", "\\s", "/", ";", "i", "+=", "1", "end", "return", "i", "else", "tell_user", "\"BUG (my bad): '#{s}' is not a list\"", "0", "end", "end" ]
This returns the position of the first real char in a list item For example: '*Hello' # => 1 '* Hello' # => 2 ' * Hello' # => 3 ' * Hello' # => 5 '1.Hello' # => 2 ' 1. Hello' # => 5
[ "This", "returns", "the", "position", "of", "the", "first", "real", "char", "in", "a", "list", "item" ]
d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9
https://github.com/michaeledgar/amp-front/blob/d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9/lib/amp-front/third_party/maruku/string_utils.rb#L108-L134
train
michaeledgar/amp-front
lib/amp-front/third_party/maruku/string_utils.rb
MaRuKu.Strings.strip_hashes
def strip_hashes(s) s = s[num_leading_hashes(s), s.size] i = s.size-1 while i > 0 && (s[i,1] =~ /(#|\s)/); i-=1; end s[0, i+1].strip end
ruby
def strip_hashes(s) s = s[num_leading_hashes(s), s.size] i = s.size-1 while i > 0 && (s[i,1] =~ /(#|\s)/); i-=1; end s[0, i+1].strip end
[ "def", "strip_hashes", "(", "s", ")", "s", "=", "s", "[", "num_leading_hashes", "(", "s", ")", ",", "s", ".", "size", "]", "i", "=", "s", ".", "size", "-", "1", "while", "i", ">", "0", "&&", "(", "s", "[", "i", ",", "1", "]", "=~", "/", "\\s", "/", ")", ";", "i", "-=", "1", ";", "end", "s", "[", "0", ",", "i", "+", "1", "]", ".", "strip", "end" ]
Strips initial and final hashes
[ "Strips", "initial", "and", "final", "hashes" ]
d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9
https://github.com/michaeledgar/amp-front/blob/d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9/lib/amp-front/third_party/maruku/string_utils.rb#L144-L149
train
michaeledgar/amp-front
lib/amp-front/third_party/maruku/string_utils.rb
MaRuKu.Strings.strip_indent
def strip_indent(s, n) i = 0 while i < s.size && n>0 c = s[i,1] if c == ' ' n-=1; elsif c == "\t" n-=TabSize; else break end i+=1 end s[i, s.size] end
ruby
def strip_indent(s, n) i = 0 while i < s.size && n>0 c = s[i,1] if c == ' ' n-=1; elsif c == "\t" n-=TabSize; else break end i+=1 end s[i, s.size] end
[ "def", "strip_indent", "(", "s", ",", "n", ")", "i", "=", "0", "while", "i", "<", "s", ".", "size", "&&", "n", ">", "0", "c", "=", "s", "[", "i", ",", "1", "]", "if", "c", "==", "' '", "n", "-=", "1", ";", "elsif", "c", "==", "\"\\t\"", "n", "-=", "TabSize", ";", "else", "break", "end", "i", "+=", "1", "end", "s", "[", "i", ",", "s", ".", "size", "]", "end" ]
toglie al massimo n caratteri
[ "toglie", "al", "massimo", "n", "caratteri" ]
d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9
https://github.com/michaeledgar/amp-front/blob/d939b7ed9a7b0e5a3d26e536b95149f88b64e3a9/lib/amp-front/third_party/maruku/string_utils.rb#L163-L177
train
fotonauts/activr
lib/activr/timeline.rb
Activr.Timeline.dump
def dump(options = { }) options = options.dup limit = options.delete(:nb) || 100 self.find(limit).map{ |tl_entry| tl_entry.humanize(options) } end
ruby
def dump(options = { }) options = options.dup limit = options.delete(:nb) || 100 self.find(limit).map{ |tl_entry| tl_entry.humanize(options) } end
[ "def", "dump", "(", "options", "=", "{", "}", ")", "options", "=", "options", ".", "dup", "limit", "=", "options", ".", "delete", "(", ":nb", ")", "||", "100", "self", ".", "find", "(", "limit", ")", ".", "map", "{", "|", "tl_entry", "|", "tl_entry", ".", "humanize", "(", "options", ")", "}", "end" ]
Dump humanization of last timeline entries @param options [Hash] Options hash @option options (see Activr::Timeline::Entry#humanize) @option options [Integer] :nb Number of timeline entries to dump (default: 100) @return [Array<String>] Array of humanized sentences
[ "Dump", "humanization", "of", "last", "timeline", "entries" ]
92c071ad18a76d4130661da3ce47c1f0fb8ae913
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/timeline.rb#L368-L374
train
fotonauts/activr
lib/activr/timeline.rb
Activr.Timeline.trim!
def trim! # check if trimming is needed if (self.trim_max_length > 0) && (self.count > self.trim_max_length) last_tle = self.find(1, :skip => self.trim_max_length - 1).first if last_tle self.delete(:before => last_tle.activity.at) end end end
ruby
def trim! # check if trimming is needed if (self.trim_max_length > 0) && (self.count > self.trim_max_length) last_tle = self.find(1, :skip => self.trim_max_length - 1).first if last_tle self.delete(:before => last_tle.activity.at) end end end
[ "def", "trim!", "if", "(", "self", ".", "trim_max_length", ">", "0", ")", "&&", "(", "self", ".", "count", ">", "self", ".", "trim_max_length", ")", "last_tle", "=", "self", ".", "find", "(", "1", ",", ":skip", "=>", "self", ".", "trim_max_length", "-", "1", ")", ".", "first", "if", "last_tle", "self", ".", "delete", "(", ":before", "=>", "last_tle", ".", "activity", ".", "at", ")", "end", "end", "end" ]
Remove old timeline entries
[ "Remove", "old", "timeline", "entries" ]
92c071ad18a76d4130661da3ce47c1f0fb8ae913
https://github.com/fotonauts/activr/blob/92c071ad18a76d4130661da3ce47c1f0fb8ae913/lib/activr/timeline.rb#L385-L393
train
alphagov/govuk_navigation_helpers
lib/govuk_navigation_helpers/rummager_taxonomy_sidebar_links.rb
GovukNavigationHelpers.RummagerTaxonomySidebarLinks.content_related_to
def content_related_to(taxon, used_related_links) statsd.time(:taxonomy_sidebar_search_time) do begin results = Services.rummager.search( similar_to: @content_item.base_path, start: 0, count: 3, filter_taxons: [taxon.content_id], filter_navigation_document_supertype: 'guidance', reject_link: used_related_links.to_a, fields: %w[title link], )['results'] statsd.increment(:taxonomy_sidebar_searches) results .map { |result| { title: result['title'], link: result['link'], } } .sort_by { |result| result[:title] } rescue StandardError => e GovukNavigationHelpers.configuration.error_handler.notify(e) [] end end end
ruby
def content_related_to(taxon, used_related_links) statsd.time(:taxonomy_sidebar_search_time) do begin results = Services.rummager.search( similar_to: @content_item.base_path, start: 0, count: 3, filter_taxons: [taxon.content_id], filter_navigation_document_supertype: 'guidance', reject_link: used_related_links.to_a, fields: %w[title link], )['results'] statsd.increment(:taxonomy_sidebar_searches) results .map { |result| { title: result['title'], link: result['link'], } } .sort_by { |result| result[:title] } rescue StandardError => e GovukNavigationHelpers.configuration.error_handler.notify(e) [] end end end
[ "def", "content_related_to", "(", "taxon", ",", "used_related_links", ")", "statsd", ".", "time", "(", ":taxonomy_sidebar_search_time", ")", "do", "begin", "results", "=", "Services", ".", "rummager", ".", "search", "(", "similar_to", ":", "@content_item", ".", "base_path", ",", "start", ":", "0", ",", "count", ":", "3", ",", "filter_taxons", ":", "[", "taxon", ".", "content_id", "]", ",", "filter_navigation_document_supertype", ":", "'guidance'", ",", "reject_link", ":", "used_related_links", ".", "to_a", ",", "fields", ":", "%w[", "title", "link", "]", ",", ")", "[", "'results'", "]", "statsd", ".", "increment", "(", ":taxonomy_sidebar_searches", ")", "results", ".", "map", "{", "|", "result", "|", "{", "title", ":", "result", "[", "'title'", "]", ",", "link", ":", "result", "[", "'link'", "]", ",", "}", "}", ".", "sort_by", "{", "|", "result", "|", "result", "[", ":title", "]", "}", "rescue", "StandardError", "=>", "e", "GovukNavigationHelpers", ".", "configuration", ".", "error_handler", ".", "notify", "(", "e", ")", "[", "]", "end", "end", "end" ]
This method will fetch content related to content_item, and tagged to taxon. This is a temporary method that uses search to achieve this. This behaviour is to be moved into  the content store
[ "This", "method", "will", "fetch", "content", "related", "to", "content_item", "and", "tagged", "to", "taxon", ".", "This", "is", "a", "temporary", "method", "that", "uses", "search", "to", "achieve", "this", ".", "This", "behaviour", "is", "to", "be", "moved", "into", "the", "content", "store" ]
5eddcaec5412473fa4e22ef8b8d2cbe406825886
https://github.com/alphagov/govuk_navigation_helpers/blob/5eddcaec5412473fa4e22ef8b8d2cbe406825886/lib/govuk_navigation_helpers/rummager_taxonomy_sidebar_links.rb#L32-L55
train
sanichi/icu_tournament
lib/icu_tournament/tournament_sp.rb
ICU.Player.to_sp_text
def to_sp_text(rounds, format) attrs = [num.to_s, name, id.to_s, ('%.1f' % points).sub(/\.0/, '')] (1..rounds).each do |r| result = find_result(r) attrs << (result ? result.to_sp_text : " : ") end format % attrs end
ruby
def to_sp_text(rounds, format) attrs = [num.to_s, name, id.to_s, ('%.1f' % points).sub(/\.0/, '')] (1..rounds).each do |r| result = find_result(r) attrs << (result ? result.to_sp_text : " : ") end format % attrs end
[ "def", "to_sp_text", "(", "rounds", ",", "format", ")", "attrs", "=", "[", "num", ".", "to_s", ",", "name", ",", "id", ".", "to_s", ",", "(", "'%.1f'", "%", "points", ")", ".", "sub", "(", "/", "\\.", "/", ",", "''", ")", "]", "(", "1", "..", "rounds", ")", ".", "each", "do", "|", "r", "|", "result", "=", "find_result", "(", "r", ")", "attrs", "<<", "(", "result", "?", "result", ".", "to_sp_text", ":", "\" : \"", ")", "end", "format", "%", "attrs", "end" ]
Format a player's record as it would appear in an SP text export file.
[ "Format", "a", "player", "s", "record", "as", "it", "would", "appear", "in", "an", "SP", "text", "export", "file", "." ]
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament_sp.rb#L333-L340
train
sanichi/icu_tournament
lib/icu_tournament/tournament_sp.rb
ICU.Result.to_sp_text
def to_sp_text sp = opponent ? opponent.to_s : '0' sp << ':' if rateable sp << score else sp << case score when 'W' then '+' when 'L' then '-' else '=' end end end
ruby
def to_sp_text sp = opponent ? opponent.to_s : '0' sp << ':' if rateable sp << score else sp << case score when 'W' then '+' when 'L' then '-' else '=' end end end
[ "def", "to_sp_text", "sp", "=", "opponent", "?", "opponent", ".", "to_s", ":", "'0'", "sp", "<<", "':'", "if", "rateable", "sp", "<<", "score", "else", "sp", "<<", "case", "score", "when", "'W'", "then", "'+'", "when", "'L'", "then", "'-'", "else", "'='", "end", "end", "end" ]
Format a player's result as it would appear in an SP text export file.
[ "Format", "a", "player", "s", "result", "as", "it", "would", "appear", "in", "an", "SP", "text", "export", "file", "." ]
badd2940189feaeb9f0edb4b4e07ff6b2548bd3d
https://github.com/sanichi/icu_tournament/blob/badd2940189feaeb9f0edb4b4e07ff6b2548bd3d/lib/icu_tournament/tournament_sp.rb#L345-L357
train
octoai/gem-octocore-cassandra
lib/octocore-cassandra/baseline.rb
Octo.Baseline.get_baseline_value
def get_baseline_value(baseline_type, obj, ts = Time.now.ceil) unless Octo::Counter.constants.include?baseline_type raise ArgumentError, 'No such baseline defined' end args = { ts: ts, type: Octo::Counter.const_get(baseline_type), uid: obj.unique_id, enterprise_id: obj.enterprise.id } bl = get_cached(args) if bl bl.val else 0.01 end end
ruby
def get_baseline_value(baseline_type, obj, ts = Time.now.ceil) unless Octo::Counter.constants.include?baseline_type raise ArgumentError, 'No such baseline defined' end args = { ts: ts, type: Octo::Counter.const_get(baseline_type), uid: obj.unique_id, enterprise_id: obj.enterprise.id } bl = get_cached(args) if bl bl.val else 0.01 end end
[ "def", "get_baseline_value", "(", "baseline_type", ",", "obj", ",", "ts", "=", "Time", ".", "now", ".", "ceil", ")", "unless", "Octo", "::", "Counter", ".", "constants", ".", "include?", "baseline_type", "raise", "ArgumentError", ",", "'No such baseline defined'", "end", "args", "=", "{", "ts", ":", "ts", ",", "type", ":", "Octo", "::", "Counter", ".", "const_get", "(", "baseline_type", ")", ",", "uid", ":", "obj", ".", "unique_id", ",", "enterprise_id", ":", "obj", ".", "enterprise", ".", "id", "}", "bl", "=", "get_cached", "(", "args", ")", "if", "bl", "bl", ".", "val", "else", "0.01", "end", "end" ]
Finds baseline value of an object @param [Fixnum] baseline_type One of the valid Baseline Types defined @param [Object] obj The object for whom baseline value is to be found @param [Time] ts The timestamp at which baseline is to be found
[ "Finds", "baseline", "value", "of", "an", "object" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/baseline.rb#L40-L57
train
octoai/gem-octocore-cassandra
lib/octocore-cassandra/baseline.rb
Octo.Baseline.aggregate
def aggregate(type, ts) Octo::Enterprise.each do |enterprise| aggregate_baseline enterprise.id, type, ts end end
ruby
def aggregate(type, ts) Octo::Enterprise.each do |enterprise| aggregate_baseline enterprise.id, type, ts end end
[ "def", "aggregate", "(", "type", ",", "ts", ")", "Octo", "::", "Enterprise", ".", "each", "do", "|", "enterprise", "|", "aggregate_baseline", "enterprise", ".", "id", ",", "type", ",", "ts", "end", "end" ]
Does an aggregation of type for a timestamp @param [Fixnum] type The counter type for which aggregation has to be done @param [Time] ts The time at which aggregation should happen
[ "Does", "an", "aggregation", "of", "type", "for", "a", "timestamp" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/baseline.rb#L63-L67
train
octoai/gem-octocore-cassandra
lib/octocore-cassandra/baseline.rb
Octo.Baseline.aggregate_baseline
def aggregate_baseline(enterprise_id, type, ts = Time.now.floor) clazz = @baseline_for.constantize _ts = ts start_calc_time = (_ts.to_datetime - MAX_DURATION.day).to_time last_n_days_interval = start_calc_time.ceil.to(_ts, 24.hour) last_n_days_interval.each do |hist| args = { ts: hist, type: type, enterprise_id: enterprise_id } counters = @baseline_for.constantize.send(:where, args) baseline = baseline_from_counters(counters) store_baseline enterprise_id, type, hist, baseline end end
ruby
def aggregate_baseline(enterprise_id, type, ts = Time.now.floor) clazz = @baseline_for.constantize _ts = ts start_calc_time = (_ts.to_datetime - MAX_DURATION.day).to_time last_n_days_interval = start_calc_time.ceil.to(_ts, 24.hour) last_n_days_interval.each do |hist| args = { ts: hist, type: type, enterprise_id: enterprise_id } counters = @baseline_for.constantize.send(:where, args) baseline = baseline_from_counters(counters) store_baseline enterprise_id, type, hist, baseline end end
[ "def", "aggregate_baseline", "(", "enterprise_id", ",", "type", ",", "ts", "=", "Time", ".", "now", ".", "floor", ")", "clazz", "=", "@baseline_for", ".", "constantize", "_ts", "=", "ts", "start_calc_time", "=", "(", "_ts", ".", "to_datetime", "-", "MAX_DURATION", ".", "day", ")", ".", "to_time", "last_n_days_interval", "=", "start_calc_time", ".", "ceil", ".", "to", "(", "_ts", ",", "24", ".", "hour", ")", "last_n_days_interval", ".", "each", "do", "|", "hist", "|", "args", "=", "{", "ts", ":", "hist", ",", "type", ":", "type", ",", "enterprise_id", ":", "enterprise_id", "}", "counters", "=", "@baseline_for", ".", "constantize", ".", "send", "(", ":where", ",", "args", ")", "baseline", "=", "baseline_from_counters", "(", "counters", ")", "store_baseline", "enterprise_id", ",", "type", ",", "hist", ",", "baseline", "end", "end" ]
Aggregates the baseline for a minute
[ "Aggregates", "the", "baseline", "for", "a", "minute" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/baseline.rb#L71-L86
train
octoai/gem-octocore-cassandra
lib/octocore-cassandra/baseline.rb
Octo.Baseline.store_baseline
def store_baseline(enterprise_id, type, ts, baseline) return if baseline.nil? or baseline.empty? baseline.each do |uid, val| self.new({ enterprise_id: enterprise_id, type: type, ts: ts, uid: uid, val: val }).save! end end
ruby
def store_baseline(enterprise_id, type, ts, baseline) return if baseline.nil? or baseline.empty? baseline.each do |uid, val| self.new({ enterprise_id: enterprise_id, type: type, ts: ts, uid: uid, val: val }).save! end end
[ "def", "store_baseline", "(", "enterprise_id", ",", "type", ",", "ts", ",", "baseline", ")", "return", "if", "baseline", ".", "nil?", "or", "baseline", ".", "empty?", "baseline", ".", "each", "do", "|", "uid", ",", "val", "|", "self", ".", "new", "(", "{", "enterprise_id", ":", "enterprise_id", ",", "type", ":", "type", ",", "ts", ":", "ts", ",", "uid", ":", "uid", ",", "val", ":", "val", "}", ")", ".", "save!", "end", "end" ]
Stores the baseline for an enterprise, and type @param [String] enterprise_id The enterprise ID of enterprise @param [Fixnum] type The Counter type as baseline type @param [Time] ts The time stamp of storage @param [Hash{String => Float}] baseline A hash representing baseline
[ "Stores", "the", "baseline", "for", "an", "enterprise", "and", "type" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/baseline.rb#L95-L106
train
octoai/gem-octocore-cassandra
lib/octocore-cassandra/baseline.rb
Octo.Baseline.baseline_from_counters
def baseline_from_counters(counters) baseline = {} uid_groups = counters.group_by { |x| x.uid } uid_groups.each do |uid, counts| baseline[uid] = score_counts(counts) end baseline end
ruby
def baseline_from_counters(counters) baseline = {} uid_groups = counters.group_by { |x| x.uid } uid_groups.each do |uid, counts| baseline[uid] = score_counts(counts) end baseline end
[ "def", "baseline_from_counters", "(", "counters", ")", "baseline", "=", "{", "}", "uid_groups", "=", "counters", ".", "group_by", "{", "|", "x", "|", "x", ".", "uid", "}", "uid_groups", ".", "each", "do", "|", "uid", ",", "counts", "|", "baseline", "[", "uid", "]", "=", "score_counts", "(", "counts", ")", "end", "baseline", "end" ]
Calculates the baseline from counters
[ "Calculates", "the", "baseline", "from", "counters" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/baseline.rb#L109-L116
train
octoai/gem-octocore-cassandra
lib/octocore-cassandra/baseline.rb
Octo.Baseline.score_counts
def score_counts(counts) if counts.count > 0 _num = counts.map { |x| x.obp } _num.percentile(90) else 0.01 end end
ruby
def score_counts(counts) if counts.count > 0 _num = counts.map { |x| x.obp } _num.percentile(90) else 0.01 end end
[ "def", "score_counts", "(", "counts", ")", "if", "counts", ".", "count", ">", "0", "_num", "=", "counts", ".", "map", "{", "|", "x", "|", "x", ".", "obp", "}", "_num", ".", "percentile", "(", "90", ")", "else", "0.01", "end", "end" ]
Calculates the baseline score from an array of scores @param [Array<Float>] counts The counts array @return [Float] The baseline score for counters
[ "Calculates", "the", "baseline", "score", "from", "an", "array", "of", "scores" ]
c0977dce5ba0eb174ff810f161aba151069935df
https://github.com/octoai/gem-octocore-cassandra/blob/c0977dce5ba0eb174ff810f161aba151069935df/lib/octocore-cassandra/baseline.rb#L121-L128
train
brainlid/locale_dating
lib/locale_dating.rb
LocaleDating.ClassMethods.locale_dating_naming_checks
def locale_dating_naming_checks(args, options) options.reverse_merge!(:format => :default) options[:ending] ||= "as_#{options[:format]}".to_sym unless options[:format] == :default options[:ending] ||= :as_text # error if multiple args used with :name option raise MethodOverwriteError, "multiple attributes cannot be wrapped with an explicitly named method" if args.length > 1 && options.key?(:name) end
ruby
def locale_dating_naming_checks(args, options) options.reverse_merge!(:format => :default) options[:ending] ||= "as_#{options[:format]}".to_sym unless options[:format] == :default options[:ending] ||= :as_text # error if multiple args used with :name option raise MethodOverwriteError, "multiple attributes cannot be wrapped with an explicitly named method" if args.length > 1 && options.key?(:name) end
[ "def", "locale_dating_naming_checks", "(", "args", ",", "options", ")", "options", ".", "reverse_merge!", "(", ":format", "=>", ":default", ")", "options", "[", ":ending", "]", "||=", "\"as_#{options[:format]}\"", ".", "to_sym", "unless", "options", "[", ":format", "]", "==", ":default", "options", "[", ":ending", "]", "||=", ":as_text", "raise", "MethodOverwriteError", ",", "\"multiple attributes cannot be wrapped with an explicitly named method\"", "if", "args", ".", "length", ">", "1", "&&", "options", ".", "key?", "(", ":name", ")", "end" ]
Given the options for a locale_dating call, set the defaults for the naming convention to use.
[ "Given", "the", "options", "for", "a", "locale_dating", "call", "set", "the", "defaults", "for", "the", "naming", "convention", "to", "use", "." ]
696aa73a648d5c0552a437801b07331c6cc005ee
https://github.com/brainlid/locale_dating/blob/696aa73a648d5c0552a437801b07331c6cc005ee/lib/locale_dating.rb#L176-L182
train
zdavatz/htmlgrid
lib/htmlgrid/component.rb
HtmlGrid.Component.escape_symbols
def escape_symbols(txt) esc = '' txt.to_s.each_byte { |byte| esc << if(entity = @@symbol_entities[byte]) '&' << entity << ';' else byte end } esc end
ruby
def escape_symbols(txt) esc = '' txt.to_s.each_byte { |byte| esc << if(entity = @@symbol_entities[byte]) '&' << entity << ';' else byte end } esc end
[ "def", "escape_symbols", "(", "txt", ")", "esc", "=", "''", "txt", ".", "to_s", ".", "each_byte", "{", "|", "byte", "|", "esc", "<<", "if", "(", "entity", "=", "@@symbol_entities", "[", "byte", "]", ")", "'&'", "<<", "entity", "<<", "';'", "else", "byte", "end", "}", "esc", "end" ]
escape symbol-font strings
[ "escape", "symbol", "-", "font", "strings" ]
88a0440466e422328b4553685d0efe7c9bbb4d72
https://github.com/zdavatz/htmlgrid/blob/88a0440466e422328b4553685d0efe7c9bbb4d72/lib/htmlgrid/component.rb#L173-L183
train
dwa012/nacho
lib/nacho/helper.rb
Nacho.Helper.nacho_select_tag
def nacho_select_tag(name, choices = nil, options = {}, html_options = {}) nacho_options = build_options(name, choices, options, html_options) select_element = select_tag(name, options_for_select(nacho_options[:choices]), nacho_options[:options], nacho_options[:html_options]) select_element += nacho_options[:button] if nacho_options[:html_options][:multiple] select_element end
ruby
def nacho_select_tag(name, choices = nil, options = {}, html_options = {}) nacho_options = build_options(name, choices, options, html_options) select_element = select_tag(name, options_for_select(nacho_options[:choices]), nacho_options[:options], nacho_options[:html_options]) select_element += nacho_options[:button] if nacho_options[:html_options][:multiple] select_element end
[ "def", "nacho_select_tag", "(", "name", ",", "choices", "=", "nil", ",", "options", "=", "{", "}", ",", "html_options", "=", "{", "}", ")", "nacho_options", "=", "build_options", "(", "name", ",", "choices", ",", "options", ",", "html_options", ")", "select_element", "=", "select_tag", "(", "name", ",", "options_for_select", "(", "nacho_options", "[", ":choices", "]", ")", ",", "nacho_options", "[", ":options", "]", ",", "nacho_options", "[", ":html_options", "]", ")", "select_element", "+=", "nacho_options", "[", ":button", "]", "if", "nacho_options", "[", ":html_options", "]", "[", ":multiple", "]", "select_element", "end" ]
A tag helper version for a FormBuilder class. Will create the select and the needed modal that contains the given form for the target model to create. A multiple select will generate a button to trigger the modal. @param [Symbol] method See http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select. @param [Array] choices The list of choices for the select, shoudl be in [[val, display],...] format @param [Hash] options the options to create a message with. @option options [Boolean] :include_blank Include a blank option (Forced to <tt>true</tt> when <tt>choices.count</tt> == 0) @option options [String] :new_option_text Text to display as the <tt>option</tt> that will trigger the new modal (Default "-- Add new --", will be ignored if <tt>html_options[:multiple]</tt> is set to <tt>true</tt>) @option options [Symbol] :value_key The attribute of the model that will be used as the <tt>option</tt> value from the JSON return when a new record is created @option options [Symbol] :text_key The attribute of the model that will be used as the <tt>option</tt> display content from the JSON return when a new record is created @option options [Symbol] :new_key The JSON key that will contain the value of the record that was created with the modal @option options [String] :modal_title The title of the modal (Default to "Add new <model.class.name>") @option options [String] :partial The form partial for the modal body @param [Hash] html_options See http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select.
[ "A", "tag", "helper", "version", "for", "a", "FormBuilder", "class", ".", "Will", "create", "the", "select", "and", "the", "needed", "modal", "that", "contains", "the", "given", "form", "for", "the", "target", "model", "to", "create", "." ]
80b9dce74cdc0f17a59ee130de6d7c2bcdf9e903
https://github.com/dwa012/nacho/blob/80b9dce74cdc0f17a59ee130de6d7c2bcdf9e903/lib/nacho/helper.rb#L23-L29
train
checkdin/checkdin-ruby
lib/checkdin/custom_activities.rb
Checkdin.CustomActivities.create_custom_activity
def create_custom_activity(options={}) response = connection.post do |req| req.url "custom_activities", options end return_error_or_body(response) end
ruby
def create_custom_activity(options={}) response = connection.post do |req| req.url "custom_activities", options end return_error_or_body(response) end
[ "def", "create_custom_activity", "(", "options", "=", "{", "}", ")", "response", "=", "connection", ".", "post", "do", "|", "req", "|", "req", ".", "url", "\"custom_activities\"", ",", "options", "end", "return_error_or_body", "(", "response", ")", "end" ]
Notify checkd.in of a custom activity ocurring @param [Hash] options @option options Integer :custom_activity_node_id - The ID of the custom activity node that has ocurred, available in checkd.in admin. Required. @option options Integer :user_id - The ID of the user that has performed the custom activity - either this or email is required. @option options String :email - The email address of the user that has performed the custom activity - either this or user_id is required.
[ "Notify", "checkd", ".", "in", "of", "a", "custom", "activity", "ocurring" ]
c3c4b38b0f8c710e1f805100dcf3a70649215b48
https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/custom_activities.rb#L11-L16
train
michaelirey/mailgun_api
lib/mailgun/domain.rb
Mailgun.Domain.list
def list(domain=nil) if domain @mailgun.response = Mailgun::Base.fire(:get, @mailgun.api_url + "/domains/#{domain}") else @mailgun.response = Mailgun::Base.fire(:get, @mailgun.api_url + "/domains")["items"] || [] end end
ruby
def list(domain=nil) if domain @mailgun.response = Mailgun::Base.fire(:get, @mailgun.api_url + "/domains/#{domain}") else @mailgun.response = Mailgun::Base.fire(:get, @mailgun.api_url + "/domains")["items"] || [] end end
[ "def", "list", "(", "domain", "=", "nil", ")", "if", "domain", "@mailgun", ".", "response", "=", "Mailgun", "::", "Base", ".", "fire", "(", ":get", ",", "@mailgun", ".", "api_url", "+", "\"/domains/#{domain}\"", ")", "else", "@mailgun", ".", "response", "=", "Mailgun", "::", "Base", ".", "fire", "(", ":get", ",", "@mailgun", ".", "api_url", "+", "\"/domains\"", ")", "[", "\"items\"", "]", "||", "[", "]", "end", "end" ]
Used internally List Domains. If domain name is passed return detailed information, otherwise return a list of all domains.
[ "Used", "internally", "List", "Domains", ".", "If", "domain", "name", "is", "passed", "return", "detailed", "information", "otherwise", "return", "a", "list", "of", "all", "domains", "." ]
1008cb653b7ba346e8e5404d772f0ebc8f99fa7e
https://github.com/michaelirey/mailgun_api/blob/1008cb653b7ba346e8e5404d772f0ebc8f99fa7e/lib/mailgun/domain.rb#L17-L23
train
kamui/kanpachi
lib/kanpachi/response_list.rb
Kanpachi.ResponseList.add
def add(response) if @list.key? response.name raise DuplicateResponse, "A response named #{response.name} already exists" end @list[response.name] = response end
ruby
def add(response) if @list.key? response.name raise DuplicateResponse, "A response named #{response.name} already exists" end @list[response.name] = response end
[ "def", "add", "(", "response", ")", "if", "@list", ".", "key?", "response", ".", "name", "raise", "DuplicateResponse", ",", "\"A response named #{response.name} already exists\"", "end", "@list", "[", "response", ".", "name", "]", "=", "response", "end" ]
Add a response to the list @param [Kanpachi::Response] response The response to add. @return [Hash<Kanpachi::Response>] All the added responses. @raise DuplicateResponse If a response is being duplicated. @api public
[ "Add", "a", "response", "to", "the", "list" ]
dbd09646bd8779ab874e1578b57a13f5747b0da7
https://github.com/kamui/kanpachi/blob/dbd09646bd8779ab874e1578b57a13f5747b0da7/lib/kanpachi/response_list.rb#L34-L39
train
futurechimp/drafter
lib/drafter/apply.rb
Drafter.Apply.restore_attrs
def restore_attrs draftable_columns.each do |key| self.send "#{key}=", self.draft.data[key] if self.respond_to?(key) end self end
ruby
def restore_attrs draftable_columns.each do |key| self.send "#{key}=", self.draft.data[key] if self.respond_to?(key) end self end
[ "def", "restore_attrs", "draftable_columns", ".", "each", "do", "|", "key", "|", "self", ".", "send", "\"#{key}=\"", ",", "self", ".", "draft", ".", "data", "[", "key", "]", "if", "self", ".", "respond_to?", "(", "key", ")", "end", "self", "end" ]
Whack the draft data onto the real object. @return [Draftable] the draftable object populated with the draft attrs.
[ "Whack", "the", "draft", "data", "onto", "the", "real", "object", "." ]
8308b922148a6a44280023b0ef33d48a41f2e83e
https://github.com/futurechimp/drafter/blob/8308b922148a6a44280023b0ef33d48a41f2e83e/lib/drafter/apply.rb#L22-L27
train
futurechimp/drafter
lib/drafter/apply.rb
Drafter.Apply.restore_files
def restore_files draft.draft_uploads.each do |draft_upload| uploader = draft_upload.draftable_mount_column self.send(uploader + "=", draft_upload.file_data) end end
ruby
def restore_files draft.draft_uploads.each do |draft_upload| uploader = draft_upload.draftable_mount_column self.send(uploader + "=", draft_upload.file_data) end end
[ "def", "restore_files", "draft", ".", "draft_uploads", ".", "each", "do", "|", "draft_upload", "|", "uploader", "=", "draft_upload", ".", "draftable_mount_column", "self", ".", "send", "(", "uploader", "+", "\"=\"", ",", "draft_upload", ".", "file_data", ")", "end", "end" ]
Attach draft files to the real object. @return [Draftable] the draftable object where CarrierWave uploads on the object have been replaced with their draft equivalents.
[ "Attach", "draft", "files", "to", "the", "real", "object", "." ]
8308b922148a6a44280023b0ef33d48a41f2e83e
https://github.com/futurechimp/drafter/blob/8308b922148a6a44280023b0ef33d48a41f2e83e/lib/drafter/apply.rb#L33-L38
train
stevedowney/rails_view_helpers
app/helpers/rails_view_helpers/html_helper.rb
RailsViewHelpers.HtmlHelper.body_tag
def body_tag(options={}, &block) options = canonicalize_options(options) options.delete(:class) if options[:class].blank? options[:data] ||= {} options[:data][:controller] = controller.controller_name options[:data][:action] = controller.action_name content_tag(:body, options) do yield end end
ruby
def body_tag(options={}, &block) options = canonicalize_options(options) options.delete(:class) if options[:class].blank? options[:data] ||= {} options[:data][:controller] = controller.controller_name options[:data][:action] = controller.action_name content_tag(:body, options) do yield end end
[ "def", "body_tag", "(", "options", "=", "{", "}", ",", "&", "block", ")", "options", "=", "canonicalize_options", "(", "options", ")", "options", ".", "delete", "(", ":class", ")", "if", "options", "[", ":class", "]", ".", "blank?", "options", "[", ":data", "]", "||=", "{", "}", "options", "[", ":data", "]", "[", ":controller", "]", "=", "controller", ".", "controller_name", "options", "[", ":data", "]", "[", ":action", "]", "=", "controller", ".", "action_name", "content_tag", "(", ":body", ",", "options", ")", "do", "yield", "end", "end" ]
Includes controller and action name as data attributes. @example body_tag() #=> <body data-action='index' data-controller='home'> body_tag(id: 'my-id', class: 'my-class') #=> <body class="my-class" data-action="index" data-controller="home" id="my-id"> @param options [Hash] become attributes of the BODY tag @return [String]
[ "Includes", "controller", "and", "action", "name", "as", "data", "attributes", "." ]
715c7daca9434c763b777be25b1069ecc50df287
https://github.com/stevedowney/rails_view_helpers/blob/715c7daca9434c763b777be25b1069ecc50df287/app/helpers/rails_view_helpers/html_helper.rb#L13-L23
train
appdrones/page_record
lib/page_record/validations.rb
PageRecord.Validations.errors
def errors found_errors = @record.all('[data-error-for]') error_list = ActiveModel::Errors.new(self) found_errors.each do | error | attribute = error['data-error-for'] message = error.text error_list.add(attribute, message) end error_list end
ruby
def errors found_errors = @record.all('[data-error-for]') error_list = ActiveModel::Errors.new(self) found_errors.each do | error | attribute = error['data-error-for'] message = error.text error_list.add(attribute, message) end error_list end
[ "def", "errors", "found_errors", "=", "@record", ".", "all", "(", "'[data-error-for]'", ")", "error_list", "=", "ActiveModel", "::", "Errors", ".", "new", "(", "self", ")", "found_errors", ".", "each", "do", "|", "error", "|", "attribute", "=", "error", "[", "'data-error-for'", "]", "message", "=", "error", ".", "text", "error_list", ".", "add", "(", "attribute", ",", "message", ")", "end", "error_list", "end" ]
Searches the record for any errors and returns them @return [ActiveModel::Errors] the error object for the current record @raise [AttributeNotFound] when the attribute is not found in the record
[ "Searches", "the", "record", "for", "any", "errors", "and", "returns", "them" ]
2a6d285cbfab906dad6f13f66fea1c09d354b762
https://github.com/appdrones/page_record/blob/2a6d285cbfab906dad6f13f66fea1c09d354b762/lib/page_record/validations.rb#L12-L21
train
Velir/kaltura_fu
lib/kaltura_fu/view_helpers.rb
KalturaFu.ViewHelpers.kaltura_player_embed
def kaltura_player_embed(entry_id,options={}) player_conf_parameter = "/ui_conf_id/" options[:div_id] ||= "kplayer" options[:size] ||= [] options[:use_url] ||= false width = PLAYER_WIDTH height = PLAYER_HEIGHT source_type = "entryId" unless options[:size].empty? width = options[:size].first height = options[:size].last end if options[:use_url] == true source_type = "url" end unless options[:player_conf_id].nil? player_conf_parameter += "#{options[:player_conf_id]}" else unless KalturaFu.config.player_conf_id.nil? player_conf_parameter += "#{KalturaFu.config.player_conf_id}" else player_conf_parameter += "#{DEFAULT_KPLAYER}" end end "<div id=\"#{options[:div_id]}\"></div> <script type=\"text/javascript\"> var params= { allowscriptaccess: \"always\", allownetworking: \"all\", allowfullscreen: \"true\", wmode: \"opaque\", bgcolor: \"#000000\" }; var flashVars = {}; flashVars.sourceType = \"#{source_type}\"; flashVars.entryId = \"#{entry_id}\"; flashVars.emptyF = \"onKdpEmpty\"; flashVars.readyF = \"onKdpReady\"; var attributes = { id: \"#{options[:div_id]}\", name: \"#{options[:div_id]}\" }; swfobject.embedSWF(\"#{KalturaFu.config.service_url}/kwidget/wid/_#{KalturaFu.config.partner_id}" + player_conf_parameter + "\",\"#{options[:div_id]}\",\"#{width}\",\"#{height}\",\"10.0.0\",\"http://ttv.mit.edu/swfs/expressinstall.swf\",flashVars,params,attributes); </script>" end
ruby
def kaltura_player_embed(entry_id,options={}) player_conf_parameter = "/ui_conf_id/" options[:div_id] ||= "kplayer" options[:size] ||= [] options[:use_url] ||= false width = PLAYER_WIDTH height = PLAYER_HEIGHT source_type = "entryId" unless options[:size].empty? width = options[:size].first height = options[:size].last end if options[:use_url] == true source_type = "url" end unless options[:player_conf_id].nil? player_conf_parameter += "#{options[:player_conf_id]}" else unless KalturaFu.config.player_conf_id.nil? player_conf_parameter += "#{KalturaFu.config.player_conf_id}" else player_conf_parameter += "#{DEFAULT_KPLAYER}" end end "<div id=\"#{options[:div_id]}\"></div> <script type=\"text/javascript\"> var params= { allowscriptaccess: \"always\", allownetworking: \"all\", allowfullscreen: \"true\", wmode: \"opaque\", bgcolor: \"#000000\" }; var flashVars = {}; flashVars.sourceType = \"#{source_type}\"; flashVars.entryId = \"#{entry_id}\"; flashVars.emptyF = \"onKdpEmpty\"; flashVars.readyF = \"onKdpReady\"; var attributes = { id: \"#{options[:div_id]}\", name: \"#{options[:div_id]}\" }; swfobject.embedSWF(\"#{KalturaFu.config.service_url}/kwidget/wid/_#{KalturaFu.config.partner_id}" + player_conf_parameter + "\",\"#{options[:div_id]}\",\"#{width}\",\"#{height}\",\"10.0.0\",\"http://ttv.mit.edu/swfs/expressinstall.swf\",flashVars,params,attributes); </script>" end
[ "def", "kaltura_player_embed", "(", "entry_id", ",", "options", "=", "{", "}", ")", "player_conf_parameter", "=", "\"/ui_conf_id/\"", "options", "[", ":div_id", "]", "||=", "\"kplayer\"", "options", "[", ":size", "]", "||=", "[", "]", "options", "[", ":use_url", "]", "||=", "false", "width", "=", "PLAYER_WIDTH", "height", "=", "PLAYER_HEIGHT", "source_type", "=", "\"entryId\"", "unless", "options", "[", ":size", "]", ".", "empty?", "width", "=", "options", "[", ":size", "]", ".", "first", "height", "=", "options", "[", ":size", "]", ".", "last", "end", "if", "options", "[", ":use_url", "]", "==", "true", "source_type", "=", "\"url\"", "end", "unless", "options", "[", ":player_conf_id", "]", ".", "nil?", "player_conf_parameter", "+=", "\"#{options[:player_conf_id]}\"", "else", "unless", "KalturaFu", ".", "config", ".", "player_conf_id", ".", "nil?", "player_conf_parameter", "+=", "\"#{KalturaFu.config.player_conf_id}\"", "else", "player_conf_parameter", "+=", "\"#{DEFAULT_KPLAYER}\"", "end", "end", "\"<div id=\\\"#{options[:div_id]}\\\"></div> <script type=\\\"text/javascript\\\"> \tvar params= { \t\tallowscriptaccess: \\\"always\\\", \t\tallownetworking: \\\"all\\\", \t\tallowfullscreen: \\\"true\\\", \t\twmode: \\\"opaque\\\", \t\tbgcolor: \\\"#000000\\\" \t}; \tvar flashVars = {}; \tflashVars.sourceType = \\\"#{source_type}\\\"; \t \tflashVars.entryId = \\\"#{entry_id}\\\"; \tflashVars.emptyF = \\\"onKdpEmpty\\\"; \t\tflashVars.readyF = \\\"onKdpReady\\\"; \t\t \tvar attributes = { id: \\\"#{options[:div_id]}\\\", name: \\\"#{options[:div_id]}\\\" \t}; \tswfobject.embedSWF(\\\"#{KalturaFu.config.service_url}/kwidget/wid/_#{KalturaFu.config.partner_id}\"", "+", "player_conf_parameter", "+", "\"\\\",\\\"#{options[:div_id]}\\\",\\\"#{width}\\\",\\\"#{height}\\\",\\\"10.0.0\\\",\\\"http://ttv.mit.edu/swfs/expressinstall.swf\\\",flashVars,params,attributes); </script>\"", "end" ]
Returns the code needed to embed a KDPv3 player. @param [String] entry_id Kaltura entry_id @param [Hash] options the embed code options. @option options [String] :div_id ('kplayer') The div element that the flash object will be inserted into. @option options [Array] :size ([]) The [width,wight] of the player. @option options [Boolean] :use_url (false) flag to determine whether entry_id is an entry or a URL of a flash file. @option options [String] :player_conf_id (KalturaFu.config(:player_conf_id)) A UI Conf ID to override the player with. @return [String] returns a string representation of the html/javascript necessary to play a Kaltura entry.
[ "Returns", "the", "code", "needed", "to", "embed", "a", "KDPv3", "player", "." ]
539e476786d1fd2257b90dfb1e50c2c75ae75bdd
https://github.com/Velir/kaltura_fu/blob/539e476786d1fd2257b90dfb1e50c2c75ae75bdd/lib/kaltura_fu/view_helpers.rb#L75-L125
train
Velir/kaltura_fu
lib/kaltura_fu/view_helpers.rb
KalturaFu.ViewHelpers.kaltura_seek_link
def kaltura_seek_link(content,seek_time,options={}) options[:div_id] ||= "kplayer" options[:onclick] = "$(#{options[:div_id]}).get(0).sendNotification('doSeek',#{seek_time});window.scrollTo(0,0);return false;" options.delete(:div_id) link_to(content,"#", options) end
ruby
def kaltura_seek_link(content,seek_time,options={}) options[:div_id] ||= "kplayer" options[:onclick] = "$(#{options[:div_id]}).get(0).sendNotification('doSeek',#{seek_time});window.scrollTo(0,0);return false;" options.delete(:div_id) link_to(content,"#", options) end
[ "def", "kaltura_seek_link", "(", "content", ",", "seek_time", ",", "options", "=", "{", "}", ")", "options", "[", ":div_id", "]", "||=", "\"kplayer\"", "options", "[", ":onclick", "]", "=", "\"$(#{options[:div_id]}).get(0).sendNotification('doSeek',#{seek_time});window.scrollTo(0,0);return false;\"", "options", ".", "delete", "(", ":div_id", ")", "link_to", "(", "content", ",", "\"#\"", ",", "options", ")", "end" ]
Creates a link_to tag that seeks to a certain time on a KDPv3 player. @param [String] content The text in the link tag. @param [Integer] seek_time The time in seconds to seek the player to. @param [Hash] options @option options [String] :div_id ('kplayer') The div of the KDP player.
[ "Creates", "a", "link_to", "tag", "that", "seeks", "to", "a", "certain", "time", "on", "a", "KDPv3", "player", "." ]
539e476786d1fd2257b90dfb1e50c2c75ae75bdd
https://github.com/Velir/kaltura_fu/blob/539e476786d1fd2257b90dfb1e50c2c75ae75bdd/lib/kaltura_fu/view_helpers.rb#L173-L179
train
nerab/hms
lib/hms/duration.rb
HMS.Duration.op
def op(sym, o) case o when Duration Duration.new(@seconds.send(sym, o.to_i)) when Numeric Duration.new(@seconds.send(sym, o)) else a, b = o.coerce(self) a.send(sym, b) end end
ruby
def op(sym, o) case o when Duration Duration.new(@seconds.send(sym, o.to_i)) when Numeric Duration.new(@seconds.send(sym, o)) else a, b = o.coerce(self) a.send(sym, b) end end
[ "def", "op", "(", "sym", ",", "o", ")", "case", "o", "when", "Duration", "Duration", ".", "new", "(", "@seconds", ".", "send", "(", "sym", ",", "o", ".", "to_i", ")", ")", "when", "Numeric", "Duration", ".", "new", "(", "@seconds", ".", "send", "(", "sym", ",", "o", ")", ")", "else", "a", ",", "b", "=", "o", ".", "coerce", "(", "self", ")", "a", ".", "send", "(", "sym", ",", "b", ")", "end", "end" ]
generic operator implementation
[ "generic", "operator", "implementation" ]
9f373eb48847e5055110c90c6dde924ba4a2181b
https://github.com/nerab/hms/blob/9f373eb48847e5055110c90c6dde924ba4a2181b/lib/hms/duration.rb#L139-L149
train
wapcaplet/kelp
lib/kelp/navigation.rb
Kelp.Navigation.follow
def follow(link, scope={}) in_scope(scope) do begin click_link(link) rescue Capybara::ElementNotFound raise Kelp::MissingLink, "No link with title, id or text '#{link}' found" end end end
ruby
def follow(link, scope={}) in_scope(scope) do begin click_link(link) rescue Capybara::ElementNotFound raise Kelp::MissingLink, "No link with title, id or text '#{link}' found" end end end
[ "def", "follow", "(", "link", ",", "scope", "=", "{", "}", ")", "in_scope", "(", "scope", ")", "do", "begin", "click_link", "(", "link", ")", "rescue", "Capybara", "::", "ElementNotFound", "raise", "Kelp", "::", "MissingLink", ",", "\"No link with title, id or text '#{link}' found\"", "end", "end", "end" ]
Follow a link on the page. @example follow "Login" follow "Contact Us", :within => "#footer" @param [String] link Capybara locator expression (id, name, or link text) @param [Hash] scope Scoping keywords as understood by {#in_scope}
[ "Follow", "a", "link", "on", "the", "page", "." ]
592fe188db5a3d05e6120ed2157ad8d781601b7a
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/navigation.rb#L27-L36
train
wapcaplet/kelp
lib/kelp/navigation.rb
Kelp.Navigation.press
def press(button, scope={}) in_scope(scope) do begin click_button(button) rescue Capybara::ElementNotFound raise Kelp::MissingButton, "No button with value, id or text '#{button}' found" end end end
ruby
def press(button, scope={}) in_scope(scope) do begin click_button(button) rescue Capybara::ElementNotFound raise Kelp::MissingButton, "No button with value, id or text '#{button}' found" end end end
[ "def", "press", "(", "button", ",", "scope", "=", "{", "}", ")", "in_scope", "(", "scope", ")", "do", "begin", "click_button", "(", "button", ")", "rescue", "Capybara", "::", "ElementNotFound", "raise", "Kelp", "::", "MissingButton", ",", "\"No button with value, id or text '#{button}' found\"", "end", "end", "end" ]
Press a button on the page. @example press "Cancel" press "Submit", :within => "#survey" @param [String] button Capybara locator expression (id, name, or button text) @param [Hash] scope Scoping keywords as understood by {#in_scope}
[ "Press", "a", "button", "on", "the", "page", "." ]
592fe188db5a3d05e6120ed2157ad8d781601b7a
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/navigation.rb#L49-L58
train
wapcaplet/kelp
lib/kelp/navigation.rb
Kelp.Navigation.click_link_in_row
def click_link_in_row(link, text) begin row = find(:xpath, xpath_row_containing([link, text])) rescue Capybara::ElementNotFound raise Kelp::MissingRow, "No table row found containing '#{link}' and '#{text}'" end begin row.click_link(link) rescue Capybara::ElementNotFound raise Kelp::MissingLink, "No link with title, id or text '#{link}' found in the same row as '#{text}'" end end
ruby
def click_link_in_row(link, text) begin row = find(:xpath, xpath_row_containing([link, text])) rescue Capybara::ElementNotFound raise Kelp::MissingRow, "No table row found containing '#{link}' and '#{text}'" end begin row.click_link(link) rescue Capybara::ElementNotFound raise Kelp::MissingLink, "No link with title, id or text '#{link}' found in the same row as '#{text}'" end end
[ "def", "click_link_in_row", "(", "link", ",", "text", ")", "begin", "row", "=", "find", "(", ":xpath", ",", "xpath_row_containing", "(", "[", "link", ",", "text", "]", ")", ")", "rescue", "Capybara", "::", "ElementNotFound", "raise", "Kelp", "::", "MissingRow", ",", "\"No table row found containing '#{link}' and '#{text}'\"", "end", "begin", "row", ".", "click_link", "(", "link", ")", "rescue", "Capybara", "::", "ElementNotFound", "raise", "Kelp", "::", "MissingLink", ",", "\"No link with title, id or text '#{link}' found in the same row as '#{text}'\"", "end", "end" ]
Click a link in a table row containing the given text. @example click_link_in_row "Edit", "Pinky" @param [String] link Content of the link to click @param [String] text Other content that must be in the same row
[ "Click", "a", "link", "in", "a", "table", "row", "containing", "the", "given", "text", "." ]
592fe188db5a3d05e6120ed2157ad8d781601b7a
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/navigation.rb#L71-L84
train
wapcaplet/kelp
lib/kelp/navigation.rb
Kelp.Navigation.should_be_on_page
def should_be_on_page(page_name_or_path) # Use the path_to translator function if it's defined # (normally in features/support/paths.rb) if defined? path_to expect_path = path_to(page_name_or_path) # Otherwise, expect a raw path string else expect_path = page_name_or_path end actual_path = URI.parse(current_url).path if actual_path != expect_path raise Kelp::Unexpected, "Expected to be on page: '#{expect_path}'" + \ "\nActually on page: '#{actual_path}'" end end
ruby
def should_be_on_page(page_name_or_path) # Use the path_to translator function if it's defined # (normally in features/support/paths.rb) if defined? path_to expect_path = path_to(page_name_or_path) # Otherwise, expect a raw path string else expect_path = page_name_or_path end actual_path = URI.parse(current_url).path if actual_path != expect_path raise Kelp::Unexpected, "Expected to be on page: '#{expect_path}'" + \ "\nActually on page: '#{actual_path}'" end end
[ "def", "should_be_on_page", "(", "page_name_or_path", ")", "if", "defined?", "path_to", "expect_path", "=", "path_to", "(", "page_name_or_path", ")", "else", "expect_path", "=", "page_name_or_path", "end", "actual_path", "=", "URI", ".", "parse", "(", "current_url", ")", ".", "path", "if", "actual_path", "!=", "expect_path", "raise", "Kelp", "::", "Unexpected", ",", "\"Expected to be on page: '#{expect_path}'\"", "+", "\"\\nActually on page: '#{actual_path}'\"", "end", "end" ]
Verify that the current page matches the path of `page_name_or_path`. The cucumber-generated `path_to` function will be used, if it's defined, to translate human-readable names into URL paths. Otherwise, assume a raw, absolute path string. @example should_be_on_page 'home page' should_be_on_page '/admin/login' @param [String] page_name_or_path Human-readable page name (mapped to a pathname by your `path_to` function), or an absolute path beginning with `/`. @raise [Kelp::Unexpected] If actual page path doesn't match the expected path @since 0.1.9
[ "Verify", "that", "the", "current", "page", "matches", "the", "path", "of", "page_name_or_path", ".", "The", "cucumber", "-", "generated", "path_to", "function", "will", "be", "used", "if", "it", "s", "defined", "to", "translate", "human", "-", "readable", "names", "into", "URL", "paths", ".", "Otherwise", "assume", "a", "raw", "absolute", "path", "string", "." ]
592fe188db5a3d05e6120ed2157ad8d781601b7a
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/navigation.rb#L114-L129
train
wapcaplet/kelp
lib/kelp/navigation.rb
Kelp.Navigation.should_have_query
def should_have_query(params) query = URI.parse(current_url).query actual_params = query ? CGI.parse(query) : {} expected_params = {} params.each_pair do |k,v| expected_params[k] = v.split(',') end if actual_params != expected_params raise Kelp::Unexpected, "Expected query params: '#{expected_params.inspect}'" + \ "\nActual query params: '#{actual_params.inspect}'" end end
ruby
def should_have_query(params) query = URI.parse(current_url).query actual_params = query ? CGI.parse(query) : {} expected_params = {} params.each_pair do |k,v| expected_params[k] = v.split(',') end if actual_params != expected_params raise Kelp::Unexpected, "Expected query params: '#{expected_params.inspect}'" + \ "\nActual query params: '#{actual_params.inspect}'" end end
[ "def", "should_have_query", "(", "params", ")", "query", "=", "URI", ".", "parse", "(", "current_url", ")", ".", "query", "actual_params", "=", "query", "?", "CGI", ".", "parse", "(", "query", ")", ":", "{", "}", "expected_params", "=", "{", "}", "params", ".", "each_pair", "do", "|", "k", ",", "v", "|", "expected_params", "[", "k", "]", "=", "v", ".", "split", "(", "','", ")", "end", "if", "actual_params", "!=", "expected_params", "raise", "Kelp", "::", "Unexpected", ",", "\"Expected query params: '#{expected_params.inspect}'\"", "+", "\"\\nActual query params: '#{actual_params.inspect}'\"", "end", "end" ]
Verify that the current page has the given query parameters. @param [Hash] params Key => value parameters, as they would appear in the URL @raise [Kelp::Unexpected] If actual query parameters don't match expected parameters @since 0.1.9
[ "Verify", "that", "the", "current", "page", "has", "the", "given", "query", "parameters", "." ]
592fe188db5a3d05e6120ed2157ad8d781601b7a
https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/navigation.rb#L142-L154
train
petebrowne/machined
lib/machined/static_compiler.rb
Machined.StaticCompiler.compile
def compile compiled_assets = {} machined.sprockets.each do |sprocket| next unless sprocket.compile? sprocket.each_logical_path do |logical_path| url = File.join(sprocket.config.url, logical_path) next unless compiled_assets[url].nil? && compile?(url) if asset = sprocket.find_asset(logical_path) compiled_assets[url] = write_asset(sprocket, asset) end end end compiled_assets end
ruby
def compile compiled_assets = {} machined.sprockets.each do |sprocket| next unless sprocket.compile? sprocket.each_logical_path do |logical_path| url = File.join(sprocket.config.url, logical_path) next unless compiled_assets[url].nil? && compile?(url) if asset = sprocket.find_asset(logical_path) compiled_assets[url] = write_asset(sprocket, asset) end end end compiled_assets end
[ "def", "compile", "compiled_assets", "=", "{", "}", "machined", ".", "sprockets", ".", "each", "do", "|", "sprocket", "|", "next", "unless", "sprocket", ".", "compile?", "sprocket", ".", "each_logical_path", "do", "|", "logical_path", "|", "url", "=", "File", ".", "join", "(", "sprocket", ".", "config", ".", "url", ",", "logical_path", ")", "next", "unless", "compiled_assets", "[", "url", "]", ".", "nil?", "&&", "compile?", "(", "url", ")", "if", "asset", "=", "sprocket", ".", "find_asset", "(", "logical_path", ")", "compiled_assets", "[", "url", "]", "=", "write_asset", "(", "sprocket", ",", "asset", ")", "end", "end", "end", "compiled_assets", "end" ]
Creates a new instance, which will compile the assets to the given +output_path+. Loop through and compile each available asset to the appropriate output path.
[ "Creates", "a", "new", "instance", "which", "will", "compile", "the", "assets", "to", "the", "given", "+", "output_path", "+", ".", "Loop", "through", "and", "compile", "each", "available", "asset", "to", "the", "appropriate", "output", "path", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/lib/machined/static_compiler.rb#L17-L31
train
petebrowne/machined
lib/machined/static_compiler.rb
Machined.StaticCompiler.write_asset
def write_asset(environment, asset) filename = path_for(environment, asset) FileUtils.mkdir_p File.dirname(filename) asset.write_to filename asset.write_to "#{filename}.gz" if gzip?(filename) asset.digest end
ruby
def write_asset(environment, asset) filename = path_for(environment, asset) FileUtils.mkdir_p File.dirname(filename) asset.write_to filename asset.write_to "#{filename}.gz" if gzip?(filename) asset.digest end
[ "def", "write_asset", "(", "environment", ",", "asset", ")", "filename", "=", "path_for", "(", "environment", ",", "asset", ")", "FileUtils", ".", "mkdir_p", "File", ".", "dirname", "(", "filename", ")", "asset", ".", "write_to", "filename", "asset", ".", "write_to", "\"#{filename}.gz\"", "if", "gzip?", "(", "filename", ")", "asset", ".", "digest", "end" ]
Writes the asset to its destination, also writing a gzipped version if necessary.
[ "Writes", "the", "asset", "to", "its", "destination", "also", "writing", "a", "gzipped", "version", "if", "necessary", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/lib/machined/static_compiler.rb#L42-L48
train
petebrowne/machined
lib/machined/static_compiler.rb
Machined.StaticCompiler.path_for
def path_for(environment, asset) # :nodoc: path = digest?(environment, asset) ? asset.digest_path : asset.logical_path File.join(machined.output_path, environment.config.url, path) end
ruby
def path_for(environment, asset) # :nodoc: path = digest?(environment, asset) ? asset.digest_path : asset.logical_path File.join(machined.output_path, environment.config.url, path) end
[ "def", "path_for", "(", "environment", ",", "asset", ")", "path", "=", "digest?", "(", "environment", ",", "asset", ")", "?", "asset", ".", "digest_path", ":", "asset", ".", "logical_path", "File", ".", "join", "(", "machined", ".", "output_path", ",", "environment", ".", "config", ".", "url", ",", "path", ")", "end" ]
Gets the full output path for the given asset. If it's supposed to include a digest, it will return the digest_path.
[ "Gets", "the", "full", "output", "path", "for", "the", "given", "asset", ".", "If", "it", "s", "supposed", "to", "include", "a", "digest", "it", "will", "return", "the", "digest_path", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/lib/machined/static_compiler.rb#L55-L58
train
bilus/kawaii
lib/kawaii/route_handler.rb
Kawaii.RouteHandler.call
def call(env) @request = Rack::Request.new(env) @params = @path_params.merge(@request.params.symbolize_keys) process_response(instance_exec(self, params, request, &@block)) end
ruby
def call(env) @request = Rack::Request.new(env) @params = @path_params.merge(@request.params.symbolize_keys) process_response(instance_exec(self, params, request, &@block)) end
[ "def", "call", "(", "env", ")", "@request", "=", "Rack", "::", "Request", ".", "new", "(", "env", ")", "@params", "=", "@path_params", ".", "merge", "(", "@request", ".", "params", ".", "symbolize_keys", ")", "process_response", "(", "instance_exec", "(", "self", ",", "params", ",", "request", ",", "&", "@block", ")", ")", "end" ]
Creates a new RouteHandler wrapping a handler block. @param path_params [Hash] named parameters from paths similar to /users/:id @param block [Proc] the actual route handler Invokes the handler as a normal Rack application. @param env [Hash] Rack environment @return [Array] Rack response array
[ "Creates", "a", "new", "RouteHandler", "wrapping", "a", "handler", "block", "." ]
a72be28e713b0ed2b2cfc180a38bebe0c968b0b3
https://github.com/bilus/kawaii/blob/a72be28e713b0ed2b2cfc180a38bebe0c968b0b3/lib/kawaii/route_handler.rb#L32-L36
train
ktonon/code_node
spec/fixtures/activerecord/src/active_record/associations/builder/has_and_belongs_to_many.rb
ActiveRecord::Associations::Builder.HasAndBelongsToMany.join_table_name
def join_table_name(first_table_name, second_table_name) if first_table_name < second_table_name join_table = "#{first_table_name}_#{second_table_name}" else join_table = "#{second_table_name}_#{first_table_name}" end model.table_name_prefix + join_table + model.table_name_suffix end
ruby
def join_table_name(first_table_name, second_table_name) if first_table_name < second_table_name join_table = "#{first_table_name}_#{second_table_name}" else join_table = "#{second_table_name}_#{first_table_name}" end model.table_name_prefix + join_table + model.table_name_suffix end
[ "def", "join_table_name", "(", "first_table_name", ",", "second_table_name", ")", "if", "first_table_name", "<", "second_table_name", "join_table", "=", "\"#{first_table_name}_#{second_table_name}\"", "else", "join_table", "=", "\"#{second_table_name}_#{first_table_name}\"", "end", "model", ".", "table_name_prefix", "+", "join_table", "+", "model", ".", "table_name_suffix", "end" ]
Generates a join table name from two provided table names. The names in the join table names end up in lexicographic order. join_table_name("members", "clubs") # => "clubs_members" join_table_name("members", "special_clubs") # => "members_special_clubs"
[ "Generates", "a", "join", "table", "name", "from", "two", "provided", "table", "names", ".", "The", "names", "in", "the", "join", "table", "names", "end", "up", "in", "lexicographic", "order", "." ]
48d5d1a7442d9cade602be4fb782a1b56c7677f5
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/associations/builder/has_and_belongs_to_many.rb#L47-L55
train
koppen/in_columns
lib/in_columns/columnizer.rb
InColumns.Columnizer.row_counts
def row_counts(number_of_columns) per_column = (number_of_elements / number_of_columns).floor counts = [per_column] * number_of_columns left_overs = number_of_elements % number_of_columns left_overs.times { |n| counts[n] = counts[n] + 1 } counts end
ruby
def row_counts(number_of_columns) per_column = (number_of_elements / number_of_columns).floor counts = [per_column] * number_of_columns left_overs = number_of_elements % number_of_columns left_overs.times { |n| counts[n] = counts[n] + 1 } counts end
[ "def", "row_counts", "(", "number_of_columns", ")", "per_column", "=", "(", "number_of_elements", "/", "number_of_columns", ")", ".", "floor", "counts", "=", "[", "per_column", "]", "*", "number_of_columns", "left_overs", "=", "number_of_elements", "%", "number_of_columns", "left_overs", ".", "times", "{", "|", "n", "|", "counts", "[", "n", "]", "=", "counts", "[", "n", "]", "+", "1", "}", "counts", "end" ]
Returns an array with an element for each column containing the number of rows for that column
[ "Returns", "an", "array", "with", "an", "element", "for", "each", "column", "containing", "the", "number", "of", "rows", "for", "that", "column" ]
de3abb612dada4d99b3720a8b885196864b5ce5b
https://github.com/koppen/in_columns/blob/de3abb612dada4d99b3720a8b885196864b5ce5b/lib/in_columns/columnizer.rb#L48-L58
train
26fe/dircat
lib/dircat/cat_on_sqlite/cat_on_sqlite.rb
SimpleCataloger.CatOnSqlite.require_models
def require_models model_dir = File.join(File.dirname(__FILE__), %w{ model }) unless Dir.exist? model_dir raise "model directory '#{model_dir}' not exists" end Dir[File.join(model_dir, '*.rb')].each do |f| # puts f require f end end
ruby
def require_models model_dir = File.join(File.dirname(__FILE__), %w{ model }) unless Dir.exist? model_dir raise "model directory '#{model_dir}' not exists" end Dir[File.join(model_dir, '*.rb')].each do |f| # puts f require f end end
[ "def", "require_models", "model_dir", "=", "File", ".", "join", "(", "File", ".", "dirname", "(", "__FILE__", ")", ",", "%w{", "model", "}", ")", "unless", "Dir", ".", "exist?", "model_dir", "raise", "\"model directory '#{model_dir}' not exists\"", "end", "Dir", "[", "File", ".", "join", "(", "model_dir", ",", "'*.rb'", ")", "]", ".", "each", "do", "|", "f", "|", "require", "f", "end", "end" ]
model must be loaded after the connection is established
[ "model", "must", "be", "loaded", "after", "the", "connection", "is", "established" ]
b36bc07562f6be4a7092b33b9153f807033ad670
https://github.com/26fe/dircat/blob/b36bc07562f6be4a7092b33b9153f807033ad670/lib/dircat/cat_on_sqlite/cat_on_sqlite.rb#L164-L173
train
samvera-deprecated/solrizer-fedora
lib/solrizer/fedora/solrizer.rb
Solrizer::Fedora.Solrizer.solrize_objects
def solrize_objects(opts={}) # retrieve a list of all the pids in the fedora repository num_docs = 1000000 # modify this number to guarantee that all the objects are retrieved from the repository puts "WARNING: You have turned off indexing of Full Text content. Be sure to re-run indexer with @@index_full_text set to true in main.rb" if index_full_text == false if @@index_list == false solrize_from_fedora_search(opts) else solrize_from_csv end end
ruby
def solrize_objects(opts={}) # retrieve a list of all the pids in the fedora repository num_docs = 1000000 # modify this number to guarantee that all the objects are retrieved from the repository puts "WARNING: You have turned off indexing of Full Text content. Be sure to re-run indexer with @@index_full_text set to true in main.rb" if index_full_text == false if @@index_list == false solrize_from_fedora_search(opts) else solrize_from_csv end end
[ "def", "solrize_objects", "(", "opts", "=", "{", "}", ")", "num_docs", "=", "1000000", "puts", "\"WARNING: You have turned off indexing of Full Text content. Be sure to re-run indexer with @@index_full_text set to true in main.rb\"", "if", "index_full_text", "==", "false", "if", "@@index_list", "==", "false", "solrize_from_fedora_search", "(", "opts", ")", "else", "solrize_from_csv", "end", "end" ]
Retrieve a comprehensive list of all the unique identifiers in Fedora and solrize each object's full-text and facets into the search index @example Suppress errors using :suppress_errors option solrizer.solrize_objects( :suppress_errors=>true )
[ "Retrieve", "a", "comprehensive", "list", "of", "all", "the", "unique", "identifiers", "in", "Fedora", "and", "solrize", "each", "object", "s", "full", "-", "text", "and", "facets", "into", "the", "search", "index" ]
277fab50a93a761fbccd07e2cfa01b22736d5cff
https://github.com/samvera-deprecated/solrizer-fedora/blob/277fab50a93a761fbccd07e2cfa01b22736d5cff/lib/solrizer/fedora/solrizer.rb#L89-L99
train
mastermindg/farmstead
lib/farmstead/project.rb
Farmstead.Project.generate_files
def generate_files ip = local_ip version = Farmstead::VERSION scaffold_path = "#{File.dirname __FILE__}/scaffold" scaffold = Dir.glob("#{scaffold_path}/**/*.erb", File::FNM_DOTMATCH) scaffold.each do |file| basename = File.basename(file) folderstruct = file.match("#{scaffold_path}/(.*)")[1] if basename != folderstruct foldername = File.dirname(folderstruct) create_recursive("#{@name}/#{foldername}") end projectpath = "#{@name}/#{folderstruct}".chomp(".erb") template = File.read(file) results = ERB.new(template).result(binding) copy_to_directory(results, projectpath) end end
ruby
def generate_files ip = local_ip version = Farmstead::VERSION scaffold_path = "#{File.dirname __FILE__}/scaffold" scaffold = Dir.glob("#{scaffold_path}/**/*.erb", File::FNM_DOTMATCH) scaffold.each do |file| basename = File.basename(file) folderstruct = file.match("#{scaffold_path}/(.*)")[1] if basename != folderstruct foldername = File.dirname(folderstruct) create_recursive("#{@name}/#{foldername}") end projectpath = "#{@name}/#{folderstruct}".chomp(".erb") template = File.read(file) results = ERB.new(template).result(binding) copy_to_directory(results, projectpath) end end
[ "def", "generate_files", "ip", "=", "local_ip", "version", "=", "Farmstead", "::", "VERSION", "scaffold_path", "=", "\"#{File.dirname __FILE__}/scaffold\"", "scaffold", "=", "Dir", ".", "glob", "(", "\"#{scaffold_path}/**/*.erb\"", ",", "File", "::", "FNM_DOTMATCH", ")", "scaffold", ".", "each", "do", "|", "file", "|", "basename", "=", "File", ".", "basename", "(", "file", ")", "folderstruct", "=", "file", ".", "match", "(", "\"#{scaffold_path}/(.*)\"", ")", "[", "1", "]", "if", "basename", "!=", "folderstruct", "foldername", "=", "File", ".", "dirname", "(", "folderstruct", ")", "create_recursive", "(", "\"#{@name}/#{foldername}\"", ")", "end", "projectpath", "=", "\"#{@name}/#{folderstruct}\"", ".", "chomp", "(", "\".erb\"", ")", "template", "=", "File", ".", "read", "(", "file", ")", "results", "=", "ERB", ".", "new", "(", "template", ")", ".", "result", "(", "binding", ")", "copy_to_directory", "(", "results", ",", "projectpath", ")", "end", "end" ]
Generate from templates in scaffold
[ "Generate", "from", "templates", "in", "scaffold" ]
32ef99b902304a69c110b3c7727155c38dc8d278
https://github.com/mastermindg/farmstead/blob/32ef99b902304a69c110b3c7727155c38dc8d278/lib/farmstead/project.rb#L59-L76
train
erpe/acts_as_referred
lib/acts_as_referred/class_methods.rb
ActsAsReferred.ClassMethods.acts_as_referred
def acts_as_referred(options = {}) has_one :referee, as: :referable, dependent: :destroy, class_name: 'Referee' after_create :create_referrer include ActsAsReferred::InstanceMethods end
ruby
def acts_as_referred(options = {}) has_one :referee, as: :referable, dependent: :destroy, class_name: 'Referee' after_create :create_referrer include ActsAsReferred::InstanceMethods end
[ "def", "acts_as_referred", "(", "options", "=", "{", "}", ")", "has_one", ":referee", ",", "as", ":", ":referable", ",", "dependent", ":", ":destroy", ",", "class_name", ":", "'Referee'", "after_create", ":create_referrer", "include", "ActsAsReferred", "::", "InstanceMethods", "end" ]
Hook to serve behavior to ActiveRecord-Descendants
[ "Hook", "to", "serve", "behavior", "to", "ActiveRecord", "-", "Descendants" ]
d1ffb3208e6e358c9888cec71c7bd76d30a0fdd3
https://github.com/erpe/acts_as_referred/blob/d1ffb3208e6e358c9888cec71c7bd76d30a0fdd3/lib/acts_as_referred/class_methods.rb#L5-L11
train
ltello/drsi
lib/drsi/dci/role.rb
DCI.Role.add_role_reader_for!
def add_role_reader_for!(rolekey) return if private_method_defined?(rolekey) define_method(rolekey) {__context.send(rolekey)} private rolekey end
ruby
def add_role_reader_for!(rolekey) return if private_method_defined?(rolekey) define_method(rolekey) {__context.send(rolekey)} private rolekey end
[ "def", "add_role_reader_for!", "(", "rolekey", ")", "return", "if", "private_method_defined?", "(", "rolekey", ")", "define_method", "(", "rolekey", ")", "{", "__context", ".", "send", "(", "rolekey", ")", "}", "private", "rolekey", "end" ]
Defines a new private reader instance method for a context mate role, delegating it to the context object.
[ "Defines", "a", "new", "private", "reader", "instance", "method", "for", "a", "context", "mate", "role", "delegating", "it", "to", "the", "context", "object", "." ]
f584ee2c2f6438e341474b6922b568f43b3e1f25
https://github.com/ltello/drsi/blob/f584ee2c2f6438e341474b6922b568f43b3e1f25/lib/drsi/dci/role.rb#L11-L15
train
gotqn/railslider
lib/railslider/image.rb
Railslider.Image.render
def render @result_html = '' @result_html += "<div class=\"rs-container #{self.class.name}\" id=\"#{@id}\">" @result_html += render_controls.gsub("<option value=\"rs-#{@effect}\">", "<option value=\"rs-#{@effect}\" selected=\"selected\">") @result_html += "<div class=\"rs-wrapper\">" @result_html += "<div class=\"rs-shadow\"></div>" @result_html += '<div class="rs-images">' @images_urls.each do |url| @result_html += "<img src=\"#{url}\"/>" end @result_html += '</div>' @result_html += '<div class="rs-cover">' @result_html += '<a class="rs-animation-command rs-pause" href="javascript:void(0)">Play/Pause</a>' @result_html += "<img src=\"#{@images_urls.first}\"/>" @result_html += '</div>' @result_html += '<div class="rs-transition">' @result_html += render_flips @result_html += render_multi_flips @result_html += render_cubes @result_html += render_unfolds @result_html += '</div>' @result_html += '</div>' @result_html += render_bullets @result_html += '</div>' @result_html.html_safe end
ruby
def render @result_html = '' @result_html += "<div class=\"rs-container #{self.class.name}\" id=\"#{@id}\">" @result_html += render_controls.gsub("<option value=\"rs-#{@effect}\">", "<option value=\"rs-#{@effect}\" selected=\"selected\">") @result_html += "<div class=\"rs-wrapper\">" @result_html += "<div class=\"rs-shadow\"></div>" @result_html += '<div class="rs-images">' @images_urls.each do |url| @result_html += "<img src=\"#{url}\"/>" end @result_html += '</div>' @result_html += '<div class="rs-cover">' @result_html += '<a class="rs-animation-command rs-pause" href="javascript:void(0)">Play/Pause</a>' @result_html += "<img src=\"#{@images_urls.first}\"/>" @result_html += '</div>' @result_html += '<div class="rs-transition">' @result_html += render_flips @result_html += render_multi_flips @result_html += render_cubes @result_html += render_unfolds @result_html += '</div>' @result_html += '</div>' @result_html += render_bullets @result_html += '</div>' @result_html.html_safe end
[ "def", "render", "@result_html", "=", "''", "@result_html", "+=", "\"<div class=\\\"rs-container #{self.class.name}\\\" id=\\\"#{@id}\\\">\"", "@result_html", "+=", "render_controls", ".", "gsub", "(", "\"<option value=\\\"rs-#{@effect}\\\">\"", ",", "\"<option value=\\\"rs-#{@effect}\\\" selected=\\\"selected\\\">\"", ")", "@result_html", "+=", "\"<div class=\\\"rs-wrapper\\\">\"", "@result_html", "+=", "\"<div class=\\\"rs-shadow\\\"></div>\"", "@result_html", "+=", "'<div class=\"rs-images\">'", "@images_urls", ".", "each", "do", "|", "url", "|", "@result_html", "+=", "\"<img src=\\\"#{url}\\\"/>\"", "end", "@result_html", "+=", "'</div>'", "@result_html", "+=", "'<div class=\"rs-cover\">'", "@result_html", "+=", "'<a class=\"rs-animation-command rs-pause\" href=\"javascript:void(0)\">Play/Pause</a>'", "@result_html", "+=", "\"<img src=\\\"#{@images_urls.first}\\\"/>\"", "@result_html", "+=", "'</div>'", "@result_html", "+=", "'<div class=\"rs-transition\">'", "@result_html", "+=", "render_flips", "@result_html", "+=", "render_multi_flips", "@result_html", "+=", "render_cubes", "@result_html", "+=", "render_unfolds", "@result_html", "+=", "'</div>'", "@result_html", "+=", "'</div>'", "@result_html", "+=", "render_bullets", "@result_html", "+=", "'</div>'", "@result_html", ".", "html_safe", "end" ]
rendering images with rails slider effects
[ "rendering", "images", "with", "rails", "slider", "effects" ]
86084f5ce60a217a4ee7371511ee7987fb4af171
https://github.com/gotqn/railslider/blob/86084f5ce60a217a4ee7371511ee7987fb4af171/lib/railslider/image.rb#L44-L71
train
starpeak/gricer
lib/gricer/config.rb
Gricer.Config.admin_menu
def admin_menu @admin_menu ||= [ ['overview', :dashboard, {controller: 'gricer/dashboard', action: 'overview'}], ['visitors', :menu, [ ['entry_pages', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'entry_path'}], ['referers', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'referer_host'}], ['search_engines', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'search_engine'}], ['search_terms', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'search_query'}], ['countries', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'country'}], ['domains', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'domain'}], ['locales', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'requested_locale_major'}] ] ], ['pages', :menu, [ ['views', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'path'}], ['hosts', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'host'}], ['methods', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'method'}], ['protocols', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'protocol'}], ] ], ['browsers', :menu, [ ['browsers', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'agent.name'}], ['operating_systems', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'agent.os'}], ['engines', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'agent.engine_name'}], ['javascript', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'javascript'}], ['java', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'java'}], ['silverlight', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'silverlight_major_version'}], ['flash', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'flash_major_version'}], ['screen_sizes', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'screen_size'}], ['color_depths', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'screen_depth'}] ] ] ] end
ruby
def admin_menu @admin_menu ||= [ ['overview', :dashboard, {controller: 'gricer/dashboard', action: 'overview'}], ['visitors', :menu, [ ['entry_pages', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'entry_path'}], ['referers', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'referer_host'}], ['search_engines', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'search_engine'}], ['search_terms', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'search_query'}], ['countries', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'country'}], ['domains', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'domain'}], ['locales', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'requested_locale_major'}] ] ], ['pages', :menu, [ ['views', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'path'}], ['hosts', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'host'}], ['methods', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'method'}], ['protocols', :spread, {controller: 'gricer/requests', action: 'spread_stats', field: 'protocol'}], ] ], ['browsers', :menu, [ ['browsers', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'agent.name'}], ['operating_systems', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'agent.os'}], ['engines', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'agent.engine_name'}], ['javascript', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'javascript'}], ['java', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'java'}], ['silverlight', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'silverlight_major_version'}], ['flash', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'flash_major_version'}], ['screen_sizes', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'screen_size'}], ['color_depths', :spread, {controller: 'gricer/sessions', action: 'spread_stats', field: 'screen_depth'}] ] ] ] end
[ "def", "admin_menu", "@admin_menu", "||=", "[", "[", "'overview'", ",", ":dashboard", ",", "{", "controller", ":", "'gricer/dashboard'", ",", "action", ":", "'overview'", "}", "]", ",", "[", "'visitors'", ",", ":menu", ",", "[", "[", "'entry_pages'", ",", ":spread", ",", "{", "controller", ":", "'gricer/requests'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'entry_path'", "}", "]", ",", "[", "'referers'", ",", ":spread", ",", "{", "controller", ":", "'gricer/requests'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'referer_host'", "}", "]", ",", "[", "'search_engines'", ",", ":spread", ",", "{", "controller", ":", "'gricer/requests'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'search_engine'", "}", "]", ",", "[", "'search_terms'", ",", ":spread", ",", "{", "controller", ":", "'gricer/requests'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'search_query'", "}", "]", ",", "[", "'countries'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'country'", "}", "]", ",", "[", "'domains'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'domain'", "}", "]", ",", "[", "'locales'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'requested_locale_major'", "}", "]", "]", "]", ",", "[", "'pages'", ",", ":menu", ",", "[", "[", "'views'", ",", ":spread", ",", "{", "controller", ":", "'gricer/requests'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'path'", "}", "]", ",", "[", "'hosts'", ",", ":spread", ",", "{", "controller", ":", "'gricer/requests'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'host'", "}", "]", ",", "[", "'methods'", ",", ":spread", ",", "{", "controller", ":", "'gricer/requests'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'method'", "}", "]", ",", "[", "'protocols'", ",", ":spread", ",", "{", "controller", ":", "'gricer/requests'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'protocol'", "}", "]", ",", "]", "]", ",", "[", "'browsers'", ",", ":menu", ",", "[", "[", "'browsers'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'agent.name'", "}", "]", ",", "[", "'operating_systems'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'agent.os'", "}", "]", ",", "[", "'engines'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'agent.engine_name'", "}", "]", ",", "[", "'javascript'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'javascript'", "}", "]", ",", "[", "'java'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'java'", "}", "]", ",", "[", "'silverlight'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'silverlight_major_version'", "}", "]", ",", "[", "'flash'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'flash_major_version'", "}", "]", ",", "[", "'screen_sizes'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'screen_size'", "}", "]", ",", "[", "'color_depths'", ",", ":spread", ",", "{", "controller", ":", "'gricer/sessions'", ",", "action", ":", "'spread_stats'", ",", "field", ":", "'screen_depth'", "}", "]", "]", "]", "]", "end" ]
Configure the structure of Gricer's admin menu Default value see source @return [Array]
[ "Configure", "the", "structure", "of", "Gricer", "s", "admin", "menu" ]
46bb77bd4fc7074ce294d0310ad459fef068f507
https://github.com/starpeak/gricer/blob/46bb77bd4fc7074ce294d0310ad459fef068f507/lib/gricer/config.rb#L61-L91
train
johnwunder/stix_schema_spy
lib/stix_schema_spy/models/has_children.rb
StixSchemaSpy.HasChildren.process_field
def process_field(child) if ['complexContent', 'simpleContent', 'sequence', 'group', 'choice', 'extension', 'restriction'].include?(child.name) child.elements.each {|grandchild| process_field(grandchild)} elsif child.name == 'element' element = Element.new(child, self.schema, self) @elements[element.name] = element elsif child.name == 'attribute' attribute = Attribute.new(child, self.schema, self) @attributes[attribute.name] = attribute elsif child.name == 'complexType' type = ComplexType.build(child, self.schema) @types[type.name] = type elsif child.name == 'simpleType' type = SimpleType.build(child, self.schema) @types[type.name] = type elsif child.name == 'anyAttribute' @special_fields << SpecialField.new("##anyAttribute") elsif child.name == 'anyElement' @special_fields << SpecialField.new("##anyElement") elsif child.name == 'attributeGroup' # The only special case here...essentially we'll' transparently roll attribute groups into parent nodes, # while at the schema level global attribute groups get created as a type if self.kind_of?(Schema) type = ComplexType.build(child, self.schema) @types[type.name] = type else Type.find(child.attributes['ref'].value, nil, stix_version).attributes.each {|attrib| @attributes[attrib.name] = attrib} end else $logger.debug "Skipping: #{child.name}" if defined?($logger) end end
ruby
def process_field(child) if ['complexContent', 'simpleContent', 'sequence', 'group', 'choice', 'extension', 'restriction'].include?(child.name) child.elements.each {|grandchild| process_field(grandchild)} elsif child.name == 'element' element = Element.new(child, self.schema, self) @elements[element.name] = element elsif child.name == 'attribute' attribute = Attribute.new(child, self.schema, self) @attributes[attribute.name] = attribute elsif child.name == 'complexType' type = ComplexType.build(child, self.schema) @types[type.name] = type elsif child.name == 'simpleType' type = SimpleType.build(child, self.schema) @types[type.name] = type elsif child.name == 'anyAttribute' @special_fields << SpecialField.new("##anyAttribute") elsif child.name == 'anyElement' @special_fields << SpecialField.new("##anyElement") elsif child.name == 'attributeGroup' # The only special case here...essentially we'll' transparently roll attribute groups into parent nodes, # while at the schema level global attribute groups get created as a type if self.kind_of?(Schema) type = ComplexType.build(child, self.schema) @types[type.name] = type else Type.find(child.attributes['ref'].value, nil, stix_version).attributes.each {|attrib| @attributes[attrib.name] = attrib} end else $logger.debug "Skipping: #{child.name}" if defined?($logger) end end
[ "def", "process_field", "(", "child", ")", "if", "[", "'complexContent'", ",", "'simpleContent'", ",", "'sequence'", ",", "'group'", ",", "'choice'", ",", "'extension'", ",", "'restriction'", "]", ".", "include?", "(", "child", ".", "name", ")", "child", ".", "elements", ".", "each", "{", "|", "grandchild", "|", "process_field", "(", "grandchild", ")", "}", "elsif", "child", ".", "name", "==", "'element'", "element", "=", "Element", ".", "new", "(", "child", ",", "self", ".", "schema", ",", "self", ")", "@elements", "[", "element", ".", "name", "]", "=", "element", "elsif", "child", ".", "name", "==", "'attribute'", "attribute", "=", "Attribute", ".", "new", "(", "child", ",", "self", ".", "schema", ",", "self", ")", "@attributes", "[", "attribute", ".", "name", "]", "=", "attribute", "elsif", "child", ".", "name", "==", "'complexType'", "type", "=", "ComplexType", ".", "build", "(", "child", ",", "self", ".", "schema", ")", "@types", "[", "type", ".", "name", "]", "=", "type", "elsif", "child", ".", "name", "==", "'simpleType'", "type", "=", "SimpleType", ".", "build", "(", "child", ",", "self", ".", "schema", ")", "@types", "[", "type", ".", "name", "]", "=", "type", "elsif", "child", ".", "name", "==", "'anyAttribute'", "@special_fields", "<<", "SpecialField", ".", "new", "(", "\"##anyAttribute\"", ")", "elsif", "child", ".", "name", "==", "'anyElement'", "@special_fields", "<<", "SpecialField", ".", "new", "(", "\"##anyElement\"", ")", "elsif", "child", ".", "name", "==", "'attributeGroup'", "if", "self", ".", "kind_of?", "(", "Schema", ")", "type", "=", "ComplexType", ".", "build", "(", "child", ",", "self", ".", "schema", ")", "@types", "[", "type", ".", "name", "]", "=", "type", "else", "Type", ".", "find", "(", "child", ".", "attributes", "[", "'ref'", "]", ".", "value", ",", "nil", ",", "stix_version", ")", ".", "attributes", ".", "each", "{", "|", "attrib", "|", "@attributes", "[", "attrib", ".", "name", "]", "=", "attrib", "}", "end", "else", "$logger", ".", "debug", "\"Skipping: #{child.name}\"", "if", "defined?", "(", "$logger", ")", "end", "end" ]
Runs through the list of fields under this type and creates the appropriate objects
[ "Runs", "through", "the", "list", "of", "fields", "under", "this", "type", "and", "creates", "the", "appropriate", "objects" ]
2d551c6854d749eb330340e69f73baee1c4b52d3
https://github.com/johnwunder/stix_schema_spy/blob/2d551c6854d749eb330340e69f73baee1c4b52d3/lib/stix_schema_spy/models/has_children.rb#L50-L81
train
0000marcell/simple_commander
lib/simple_commander/runner.rb
SimpleCommander.Runner.helper_exist?
def helper_exist?(helper) Object.const_defined?(helper) && Object.const_get(helper).instance_of?(::Module) end
ruby
def helper_exist?(helper) Object.const_defined?(helper) && Object.const_get(helper).instance_of?(::Module) end
[ "def", "helper_exist?", "(", "helper", ")", "Object", ".", "const_defined?", "(", "helper", ")", "&&", "Object", ".", "const_get", "(", "helper", ")", ".", "instance_of?", "(", "::", "Module", ")", "end" ]
check if the helper exist
[ "check", "if", "the", "helper", "exist" ]
337c2e0d9926c643ce131b1a1ebd3740241e4424
https://github.com/0000marcell/simple_commander/blob/337c2e0d9926c643ce131b1a1ebd3740241e4424/lib/simple_commander/runner.rb#L58-L61
train
ktonon/code_node
spec/fixtures/activerecord/src/active_record/explain.rb
ActiveRecord.Explain.logging_query_plan
def logging_query_plan # :nodoc: return yield unless logger threshold = auto_explain_threshold_in_seconds current = Thread.current if threshold && current[:available_queries_for_explain].nil? begin queries = current[:available_queries_for_explain] = [] start = Time.now result = yield logger.warn(exec_explain(queries)) if Time.now - start > threshold result ensure current[:available_queries_for_explain] = nil end else yield end end
ruby
def logging_query_plan # :nodoc: return yield unless logger threshold = auto_explain_threshold_in_seconds current = Thread.current if threshold && current[:available_queries_for_explain].nil? begin queries = current[:available_queries_for_explain] = [] start = Time.now result = yield logger.warn(exec_explain(queries)) if Time.now - start > threshold result ensure current[:available_queries_for_explain] = nil end else yield end end
[ "def", "logging_query_plan", "return", "yield", "unless", "logger", "threshold", "=", "auto_explain_threshold_in_seconds", "current", "=", "Thread", ".", "current", "if", "threshold", "&&", "current", "[", ":available_queries_for_explain", "]", ".", "nil?", "begin", "queries", "=", "current", "[", ":available_queries_for_explain", "]", "=", "[", "]", "start", "=", "Time", ".", "now", "result", "=", "yield", "logger", ".", "warn", "(", "exec_explain", "(", "queries", ")", ")", "if", "Time", ".", "now", "-", "start", ">", "threshold", "result", "ensure", "current", "[", ":available_queries_for_explain", "]", "=", "nil", "end", "else", "yield", "end", "end" ]
If auto explain is enabled, this method triggers EXPLAIN logging for the queries triggered by the block if it takes more than the threshold as a whole. That is, the threshold is not checked against each individual query, but against the duration of the entire block. This approach is convenient for relations. The available_queries_for_explain thread variable collects the queries to be explained. If the value is nil, it means queries are not being currently collected. A false value indicates collecting is turned off. Otherwise it is an array of queries.
[ "If", "auto", "explain", "is", "enabled", "this", "method", "triggers", "EXPLAIN", "logging", "for", "the", "queries", "triggered", "by", "the", "block", "if", "it", "takes", "more", "than", "the", "threshold", "as", "a", "whole", ".", "That", "is", "the", "threshold", "is", "not", "checked", "against", "each", "individual", "query", "but", "against", "the", "duration", "of", "the", "entire", "block", ".", "This", "approach", "is", "convenient", "for", "relations", "." ]
48d5d1a7442d9cade602be4fb782a1b56c7677f5
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/explain.rb#L24-L42
train
ktonon/code_node
spec/fixtures/activerecord/src/active_record/explain.rb
ActiveRecord.Explain.silence_auto_explain
def silence_auto_explain current = Thread.current original, current[:available_queries_for_explain] = current[:available_queries_for_explain], false yield ensure current[:available_queries_for_explain] = original end
ruby
def silence_auto_explain current = Thread.current original, current[:available_queries_for_explain] = current[:available_queries_for_explain], false yield ensure current[:available_queries_for_explain] = original end
[ "def", "silence_auto_explain", "current", "=", "Thread", ".", "current", "original", ",", "current", "[", ":available_queries_for_explain", "]", "=", "current", "[", ":available_queries_for_explain", "]", ",", "false", "yield", "ensure", "current", "[", ":available_queries_for_explain", "]", "=", "original", "end" ]
Silences automatic EXPLAIN logging for the duration of the block. This has high priority, no EXPLAINs will be run even if downwards the threshold is set to 0. As the name of the method suggests this only applies to automatic EXPLAINs, manual calls to +ActiveRecord::Relation#explain+ run.
[ "Silences", "automatic", "EXPLAIN", "logging", "for", "the", "duration", "of", "the", "block", "." ]
48d5d1a7442d9cade602be4fb782a1b56c7677f5
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/explain.rb#L77-L83
train
pwnedkeys/openssl-additions
lib/openssl/x509/spki.rb
OpenSSL::X509.SPKI.validate_spki
def validate_spki unless @spki.is_a?(OpenSSL::ASN1::Sequence) raise SPKIError, "SPKI data is not an ASN1 sequence (got a #{@spki.class})" end if @spki.value.length != 2 raise SPKIError, "SPKI top-level sequence must have two elements (length is #{@spki.value.length})" end alg_id, key_data = @spki.value unless alg_id.is_a?(OpenSSL::ASN1::Sequence) raise SPKIError, "SPKI algorithm_identifier must be a sequence (got a #{alg_id.class})" end unless (1..2) === alg_id.value.length raise SPKIError, "SPKI algorithm sequence must have one or two elements (got #{alg_id.value.length} elements)" end unless alg_id.value.first.is_a?(OpenSSL::ASN1::ObjectId) raise SPKIError, "SPKI algorithm identifier does not contain an object ID (got #{alg_id.value.first.class})" end unless key_data.is_a?(OpenSSL::ASN1::BitString) raise SPKIError, "SPKI publicKeyInfo field must be a BitString (got a #{@spki.value.last.class})" end end
ruby
def validate_spki unless @spki.is_a?(OpenSSL::ASN1::Sequence) raise SPKIError, "SPKI data is not an ASN1 sequence (got a #{@spki.class})" end if @spki.value.length != 2 raise SPKIError, "SPKI top-level sequence must have two elements (length is #{@spki.value.length})" end alg_id, key_data = @spki.value unless alg_id.is_a?(OpenSSL::ASN1::Sequence) raise SPKIError, "SPKI algorithm_identifier must be a sequence (got a #{alg_id.class})" end unless (1..2) === alg_id.value.length raise SPKIError, "SPKI algorithm sequence must have one or two elements (got #{alg_id.value.length} elements)" end unless alg_id.value.first.is_a?(OpenSSL::ASN1::ObjectId) raise SPKIError, "SPKI algorithm identifier does not contain an object ID (got #{alg_id.value.first.class})" end unless key_data.is_a?(OpenSSL::ASN1::BitString) raise SPKIError, "SPKI publicKeyInfo field must be a BitString (got a #{@spki.value.last.class})" end end
[ "def", "validate_spki", "unless", "@spki", ".", "is_a?", "(", "OpenSSL", "::", "ASN1", "::", "Sequence", ")", "raise", "SPKIError", ",", "\"SPKI data is not an ASN1 sequence (got a #{@spki.class})\"", "end", "if", "@spki", ".", "value", ".", "length", "!=", "2", "raise", "SPKIError", ",", "\"SPKI top-level sequence must have two elements (length is #{@spki.value.length})\"", "end", "alg_id", ",", "key_data", "=", "@spki", ".", "value", "unless", "alg_id", ".", "is_a?", "(", "OpenSSL", "::", "ASN1", "::", "Sequence", ")", "raise", "SPKIError", ",", "\"SPKI algorithm_identifier must be a sequence (got a #{alg_id.class})\"", "end", "unless", "(", "1", "..", "2", ")", "===", "alg_id", ".", "value", ".", "length", "raise", "SPKIError", ",", "\"SPKI algorithm sequence must have one or two elements (got #{alg_id.value.length} elements)\"", "end", "unless", "alg_id", ".", "value", ".", "first", ".", "is_a?", "(", "OpenSSL", "::", "ASN1", "::", "ObjectId", ")", "raise", "SPKIError", ",", "\"SPKI algorithm identifier does not contain an object ID (got #{alg_id.value.first.class})\"", "end", "unless", "key_data", ".", "is_a?", "(", "OpenSSL", "::", "ASN1", "::", "BitString", ")", "raise", "SPKIError", ",", "\"SPKI publicKeyInfo field must be a BitString (got a #{@spki.value.last.class})\"", "end", "end" ]
Make sure that the SPKI data we were passed is legit.
[ "Make", "sure", "that", "the", "SPKI", "data", "we", "were", "passed", "is", "legit", "." ]
e6d105cf39ff1ae901967644e7d46cb65f416c87
https://github.com/pwnedkeys/openssl-additions/blob/e6d105cf39ff1ae901967644e7d46cb65f416c87/lib/openssl/x509/spki.rb#L140-L172
train
celldee/ffi-rxs
lib/ffi-rxs/socket.rb
XS.CommonSocketBehavior.setsockopt
def setsockopt name, value, length = nil if 1 == @option_lookup[name] length = 8 pointer = LibC.malloc length pointer.write_long_long value elsif 0 == @option_lookup[name] length = 4 pointer = LibC.malloc length pointer.write_int value elsif 2 == @option_lookup[name] length ||= value.size # note: not checking errno for failed memory allocations :( pointer = LibC.malloc length pointer.write_string value end rc = LibXS.xs_setsockopt @socket, name, pointer, length LibC.free(pointer) unless pointer.nil? || pointer.null? rc end
ruby
def setsockopt name, value, length = nil if 1 == @option_lookup[name] length = 8 pointer = LibC.malloc length pointer.write_long_long value elsif 0 == @option_lookup[name] length = 4 pointer = LibC.malloc length pointer.write_int value elsif 2 == @option_lookup[name] length ||= value.size # note: not checking errno for failed memory allocations :( pointer = LibC.malloc length pointer.write_string value end rc = LibXS.xs_setsockopt @socket, name, pointer, length LibC.free(pointer) unless pointer.nil? || pointer.null? rc end
[ "def", "setsockopt", "name", ",", "value", ",", "length", "=", "nil", "if", "1", "==", "@option_lookup", "[", "name", "]", "length", "=", "8", "pointer", "=", "LibC", ".", "malloc", "length", "pointer", ".", "write_long_long", "value", "elsif", "0", "==", "@option_lookup", "[", "name", "]", "length", "=", "4", "pointer", "=", "LibC", ".", "malloc", "length", "pointer", ".", "write_int", "value", "elsif", "2", "==", "@option_lookup", "[", "name", "]", "length", "||=", "value", ".", "size", "pointer", "=", "LibC", ".", "malloc", "length", "pointer", ".", "write_string", "value", "end", "rc", "=", "LibXS", ".", "xs_setsockopt", "@socket", ",", "name", ",", "pointer", ",", "length", "LibC", ".", "free", "(", "pointer", ")", "unless", "pointer", ".", "nil?", "||", "pointer", ".", "null?", "rc", "end" ]
Allocates a socket of type +type+ for sending and receiving data. To avoid rescuing exceptions, use the factory method #create for all socket creation. By default, this class uses XS::Message for manual memory management. For automatic garbage collection of received messages, it is possible to override the :receiver_class to use XS::ManagedMessage. @example Socket creation sock = Socket.new(Context.new, XS::REQ, :receiver_class => XS::ManagedMessage) Advanced users may want to replace the receiver class with their own custom class. The custom class must conform to the same public API as XS::Message. Creation of a new Socket object can raise an exception. This occurs when the +context_ptr+ is null or when the allocation of the Crossroads socket within the context fails. @example begin socket = Socket.new(context.pointer, XS::REQ) rescue ContextError => e # error handling end @param pointer @param [Constant] type One of @XS::REQ@, @XS::REP@, @XS::PUB@, @XS::SUB@, @XS::PAIR@, @XS::PULL@, @XS::PUSH@, @XS::XREQ@, @XS::REP@, @XS::DEALER@ or @XS::ROUTER@ @param [Hash] options @return [Socket] when successful @return nil when unsuccessful Set the queue options on this socket @param [Constant] name numeric values One of @XS::AFFINITY@, @XS::RATE@, @XS::RECOVERY_IVL@, @XS::LINGER@, @XS::RECONNECT_IVL@, @XS::BACKLOG@, @XS::RECONNECT_IVL_MAX@, @XS::MAXMSGSIZE@, @XS::SNDHWM@, @XS::RCVHWM@, @XS::MULTICAST_HOPS@, @XS::RCVTIMEO@, @XS::SNDTIMEO@, @XS::IPV4ONLY@, @XS::KEEPALIVE@, @XS::SUBSCRIBE@, @XS::UNSUBSCRIBE@, @XS::IDENTITY@, @XS::SNDBUF@, @XS::RCVBUF@ @param [Constant] name string values One of @XS::IDENTITY@, @XS::SUBSCRIBE@ or @XS::UNSUBSCRIBE@ @param value @return 0 when the operation completed successfully @return -1 when this operation fails With a -1 return code, the user must check XS.errno to determine the cause. @example rc = socket.setsockopt(XS::LINGER, 1_000) XS::Util.resultcode_ok?(rc) ? puts("succeeded") : puts("failed")
[ "Allocates", "a", "socket", "of", "type", "+", "type", "+", "for", "sending", "and", "receiving", "data", "." ]
95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e
https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/socket.rb#L128-L150
train
celldee/ffi-rxs
lib/ffi-rxs/socket.rb
XS.CommonSocketBehavior.more_parts?
def more_parts? rc = getsockopt XS::RCVMORE, @more_parts_array Util.resultcode_ok?(rc) ? @more_parts_array.at(0) : false end
ruby
def more_parts? rc = getsockopt XS::RCVMORE, @more_parts_array Util.resultcode_ok?(rc) ? @more_parts_array.at(0) : false end
[ "def", "more_parts?", "rc", "=", "getsockopt", "XS", "::", "RCVMORE", ",", "@more_parts_array", "Util", ".", "resultcode_ok?", "(", "rc", ")", "?", "@more_parts_array", ".", "at", "(", "0", ")", ":", "false", "end" ]
Convenience method for checking on additional message parts. Equivalent to calling Socket#getsockopt with XS::RCVMORE. Warning: if the call to #getsockopt fails, this method will return false and swallow the error. @example message_parts = [] message = Message.new rc = socket.recvmsg(message) if XS::Util.resultcode_ok?(rc) message_parts << message while more_parts? message = Message.new rc = socket.recvmsg(message) message_parts.push(message) if resultcode_ok?(rc) end end @return true if more message parts @return false if not
[ "Convenience", "method", "for", "checking", "on", "additional", "message", "parts", "." ]
95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e
https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/socket.rb#L174-L178
train
celldee/ffi-rxs
lib/ffi-rxs/socket.rb
XS.CommonSocketBehavior.send_strings
def send_strings parts, flag = 0 return -1 if !parts || parts.empty? flag = NonBlocking if dontwait?(flag) parts[0..-2].each do |part| rc = send_string part, (flag | XS::SNDMORE) return rc unless Util.resultcode_ok?(rc) end send_string parts[-1], flag end
ruby
def send_strings parts, flag = 0 return -1 if !parts || parts.empty? flag = NonBlocking if dontwait?(flag) parts[0..-2].each do |part| rc = send_string part, (flag | XS::SNDMORE) return rc unless Util.resultcode_ok?(rc) end send_string parts[-1], flag end
[ "def", "send_strings", "parts", ",", "flag", "=", "0", "return", "-", "1", "if", "!", "parts", "||", "parts", ".", "empty?", "flag", "=", "NonBlocking", "if", "dontwait?", "(", "flag", ")", "parts", "[", "0", "..", "-", "2", "]", ".", "each", "do", "|", "part", "|", "rc", "=", "send_string", "part", ",", "(", "flag", "|", "XS", "::", "SNDMORE", ")", "return", "rc", "unless", "Util", ".", "resultcode_ok?", "(", "rc", ")", "end", "send_string", "parts", "[", "-", "1", "]", ",", "flag", "end" ]
Send a sequence of strings as a multipart message out of the +parts+ passed in for transmission. Every element of +parts+ should be a String. @param [Array] parts @param flag One of @0 (default)@ and @XS::NonBlocking@ @return 0 when the messages were successfully enqueued @return -1 under two conditions 1. A message could not be enqueued 2. When +flag+ is set with XS::NonBlocking and the socket returned EAGAIN. With a -1 return code, the user must check XS.errno to determine the cause.
[ "Send", "a", "sequence", "of", "strings", "as", "a", "multipart", "message", "out", "of", "the", "+", "parts", "+", "passed", "in", "for", "transmission", ".", "Every", "element", "of", "+", "parts", "+", "should", "be", "a", "String", "." ]
95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e
https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/socket.rb#L280-L290
train
celldee/ffi-rxs
lib/ffi-rxs/socket.rb
XS.CommonSocketBehavior.send_and_close
def send_and_close message, flag = 0 rc = sendmsg message, flag message.close rc end
ruby
def send_and_close message, flag = 0 rc = sendmsg message, flag message.close rc end
[ "def", "send_and_close", "message", ",", "flag", "=", "0", "rc", "=", "sendmsg", "message", ",", "flag", "message", ".", "close", "rc", "end" ]
Sends a message. This will automatically close the +message+ for both successful and failed sends. @param message @param flag One of @0 (default)@ and @XS::NonBlocking @return 0 when the message was successfully enqueued @return -1 under two conditions 1. The message could not be enqueued 2. When +flag+ is set with XS::NonBlocking and the socket returned EAGAIN. With a -1 return code, the user must check XS.errno to determine the cause.
[ "Sends", "a", "message", ".", "This", "will", "automatically", "close", "the", "+", "message", "+", "for", "both", "successful", "and", "failed", "sends", "." ]
95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e
https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/socket.rb#L333-L337
train
celldee/ffi-rxs
lib/ffi-rxs/socket.rb
XS.CommonSocketBehavior.recv_strings
def recv_strings list, flag = 0 array = [] rc = recvmsgs array, flag if Util.resultcode_ok?(rc) array.each do |message| list << message.copy_out_string message.close end end rc end
ruby
def recv_strings list, flag = 0 array = [] rc = recvmsgs array, flag if Util.resultcode_ok?(rc) array.each do |message| list << message.copy_out_string message.close end end rc end
[ "def", "recv_strings", "list", ",", "flag", "=", "0", "array", "=", "[", "]", "rc", "=", "recvmsgs", "array", ",", "flag", "if", "Util", ".", "resultcode_ok?", "(", "rc", ")", "array", ".", "each", "do", "|", "message", "|", "list", "<<", "message", ".", "copy_out_string", "message", ".", "close", "end", "end", "rc", "end" ]
Receive a multipart message as a list of strings. @param [Array] list @param flag One of @0 (default)@ and @XS::NonBlocking@. Any other flag will be removed. @return 0 if successful @return -1 if unsuccessful
[ "Receive", "a", "multipart", "message", "as", "a", "list", "of", "strings", "." ]
95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e
https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/socket.rb#L406-L418
train
celldee/ffi-rxs
lib/ffi-rxs/socket.rb
XS.CommonSocketBehavior.recv_multipart
def recv_multipart list, routing_envelope, flag = 0 parts = [] rc = recvmsgs parts, flag if Util.resultcode_ok?(rc) routing = true parts.each do |part| if routing routing_envelope << part routing = part.size > 0 else list << part end end end rc end
ruby
def recv_multipart list, routing_envelope, flag = 0 parts = [] rc = recvmsgs parts, flag if Util.resultcode_ok?(rc) routing = true parts.each do |part| if routing routing_envelope << part routing = part.size > 0 else list << part end end end rc end
[ "def", "recv_multipart", "list", ",", "routing_envelope", ",", "flag", "=", "0", "parts", "=", "[", "]", "rc", "=", "recvmsgs", "parts", ",", "flag", "if", "Util", ".", "resultcode_ok?", "(", "rc", ")", "routing", "=", "true", "parts", ".", "each", "do", "|", "part", "|", "if", "routing", "routing_envelope", "<<", "part", "routing", "=", "part", ".", "size", ">", "0", "else", "list", "<<", "part", "end", "end", "end", "rc", "end" ]
Should only be used for XREQ, XREP, DEALER and ROUTER type sockets. Takes a +list+ for receiving the message body parts and a +routing_envelope+ for receiving the message parts comprising the 0mq routing information. @param [Array] list @param routing_envelope @param flag One of @0 (default)@ and @XS::NonBlocking@ @return 0 if successful @return -1 if unsuccessful
[ "Should", "only", "be", "used", "for", "XREQ", "XREP", "DEALER", "and", "ROUTER", "type", "sockets", ".", "Takes", "a", "+", "list", "+", "for", "receiving", "the", "message", "body", "parts", "and", "a", "+", "routing_envelope", "+", "for", "receiving", "the", "message", "parts", "comprising", "the", "0mq", "routing", "information", "." ]
95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e
https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/socket.rb#L472-L489
train
celldee/ffi-rxs
lib/ffi-rxs/socket.rb
XS.CommonSocketBehavior.sockopt_buffers
def sockopt_buffers option_type if 1 == option_type # int64_t or uint64_t unless @longlong_cache length = FFI::MemoryPointer.new :size_t length.write_int 8 @longlong_cache = [FFI::MemoryPointer.new(:int64), length] end @longlong_cache elsif 0 == option_type # int, Crossroads assumes int is 4-bytes unless @int_cache length = FFI::MemoryPointer.new :size_t length.write_int 4 @int_cache = [FFI::MemoryPointer.new(:int32), length] end @int_cache elsif 2 == option_type length = FFI::MemoryPointer.new :size_t # could be a string of up to 255 bytes length.write_int 255 [FFI::MemoryPointer.new(255), length] else # uh oh, someone passed in an unknown option; use a slop buffer unless @int_cache length = FFI::MemoryPointer.new :size_t length.write_int 4 @int_cache = [FFI::MemoryPointer.new(:int32), length] end @int_cache end end
ruby
def sockopt_buffers option_type if 1 == option_type # int64_t or uint64_t unless @longlong_cache length = FFI::MemoryPointer.new :size_t length.write_int 8 @longlong_cache = [FFI::MemoryPointer.new(:int64), length] end @longlong_cache elsif 0 == option_type # int, Crossroads assumes int is 4-bytes unless @int_cache length = FFI::MemoryPointer.new :size_t length.write_int 4 @int_cache = [FFI::MemoryPointer.new(:int32), length] end @int_cache elsif 2 == option_type length = FFI::MemoryPointer.new :size_t # could be a string of up to 255 bytes length.write_int 255 [FFI::MemoryPointer.new(255), length] else # uh oh, someone passed in an unknown option; use a slop buffer unless @int_cache length = FFI::MemoryPointer.new :size_t length.write_int 4 @int_cache = [FFI::MemoryPointer.new(:int32), length] end @int_cache end end
[ "def", "sockopt_buffers", "option_type", "if", "1", "==", "option_type", "unless", "@longlong_cache", "length", "=", "FFI", "::", "MemoryPointer", ".", "new", ":size_t", "length", ".", "write_int", "8", "@longlong_cache", "=", "[", "FFI", "::", "MemoryPointer", ".", "new", "(", ":int64", ")", ",", "length", "]", "end", "@longlong_cache", "elsif", "0", "==", "option_type", "unless", "@int_cache", "length", "=", "FFI", "::", "MemoryPointer", ".", "new", ":size_t", "length", ".", "write_int", "4", "@int_cache", "=", "[", "FFI", "::", "MemoryPointer", ".", "new", "(", ":int32", ")", ",", "length", "]", "end", "@int_cache", "elsif", "2", "==", "option_type", "length", "=", "FFI", "::", "MemoryPointer", ".", "new", ":size_t", "length", ".", "write_int", "255", "[", "FFI", "::", "MemoryPointer", ".", "new", "(", "255", ")", ",", "length", "]", "else", "unless", "@int_cache", "length", "=", "FFI", "::", "MemoryPointer", ".", "new", ":size_t", "length", ".", "write_int", "4", "@int_cache", "=", "[", "FFI", "::", "MemoryPointer", ".", "new", "(", ":int32", ")", ",", "length", "]", "end", "@int_cache", "end", "end" ]
Calls to xs_getsockopt require us to pass in some pointers. We can cache and save those buffers for subsequent calls. This is a big perf win for calling RCVMORE which happens quite often. Cannot save the buffer for the IDENTITY. @param option_type @return cached number or string
[ "Calls", "to", "xs_getsockopt", "require", "us", "to", "pass", "in", "some", "pointers", ".", "We", "can", "cache", "and", "save", "those", "buffers", "for", "subsequent", "calls", ".", "This", "is", "a", "big", "perf", "win", "for", "calling", "RCVMORE", "which", "happens", "quite", "often", ".", "Cannot", "save", "the", "buffer", "for", "the", "IDENTITY", "." ]
95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e
https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/socket.rb#L528-L565
train
celldee/ffi-rxs
lib/ffi-rxs/socket.rb
XS.Socket.getsockopt
def getsockopt name, array rc = __getsockopt__ name, array if Util.resultcode_ok?(rc) && (RCVMORE == name) # convert to boolean array[0] = 1 == array[0] end rc end
ruby
def getsockopt name, array rc = __getsockopt__ name, array if Util.resultcode_ok?(rc) && (RCVMORE == name) # convert to boolean array[0] = 1 == array[0] end rc end
[ "def", "getsockopt", "name", ",", "array", "rc", "=", "__getsockopt__", "name", ",", "array", "if", "Util", ".", "resultcode_ok?", "(", "rc", ")", "&&", "(", "RCVMORE", "==", "name", ")", "array", "[", "0", "]", "=", "1", "==", "array", "[", "0", "]", "end", "rc", "end" ]
Get the options set on this socket. @param name One of @XS::RCVMORE@, @XS::SNDHWM@, @XS::AFFINITY@, @XS::IDENTITY@, @XS::RATE@, @XS::RECOVERY_IVL@, @XS::SNDBUF@, @XS::RCVBUF@, @XS::FD@, @XS::EVENTS@, @XS::LINGER@, @XS::RECONNECT_IVL@, @XS::BACKLOG@, XS::RECONNECT_IVL_MAX@, @XS::RCVTIMEO@, @XS::SNDTIMEO@, @XS::IPV4ONLY@, @XS::TYPE@, @XS::RCVHWM@, @XS::MAXMSGSIZE@, @XS::MULTICAST_HOPS@, @XS::KEEPALIVE@ @param array should be an empty array; a result of the proper type (numeric, string, boolean) will be inserted into the first position. @return 0 when the operation completed successfully @return -1 when this operation failed With a -1 return code, the user must check XS.errno to determine the cause. @example Retrieve send high water mark array = [] rc = socket.getsockopt(XS::SNDHWM, array) sndhwm = array.first if XS::Util.resultcode_ok?(rc)
[ "Get", "the", "options", "set", "on", "this", "socket", "." ]
95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e
https://github.com/celldee/ffi-rxs/blob/95378f3a5e5b5b3f1f726a9a1620f41ab4ee7f0e/lib/ffi-rxs/socket.rb#L657-L666
train
kristianmandrup/roles_generic
lib/roles_generic/generic/user/implementation.rb
Roles::Generic::User.Implementation.role=
def role= role raise ArgumentError, '#add_role takes a single role String or Symbol as the argument' if !role || role.kind_of?(Array) self.roles = role end
ruby
def role= role raise ArgumentError, '#add_role takes a single role String or Symbol as the argument' if !role || role.kind_of?(Array) self.roles = role end
[ "def", "role", "=", "role", "raise", "ArgumentError", ",", "'#add_role takes a single role String or Symbol as the argument'", "if", "!", "role", "||", "role", ".", "kind_of?", "(", "Array", ")", "self", ".", "roles", "=", "role", "end" ]
set a single role
[ "set", "a", "single", "role" ]
94588ac58bcca1f44ace5695d1984da1bd98fe1a
https://github.com/kristianmandrup/roles_generic/blob/94588ac58bcca1f44ace5695d1984da1bd98fe1a/lib/roles_generic/generic/user/implementation.rb#L10-L13
train
kristianmandrup/roles_generic
lib/roles_generic/generic/user/implementation.rb
Roles::Generic::User.Implementation.add_role
def add_role role raise ArgumentError, '#add_role takes a single role String or Symbol as the argument' if !role || role.kind_of?(Array) add_roles role end
ruby
def add_role role raise ArgumentError, '#add_role takes a single role String or Symbol as the argument' if !role || role.kind_of?(Array) add_roles role end
[ "def", "add_role", "role", "raise", "ArgumentError", ",", "'#add_role takes a single role String or Symbol as the argument'", "if", "!", "role", "||", "role", ".", "kind_of?", "(", "Array", ")", "add_roles", "role", "end" ]
add a single role
[ "add", "a", "single", "role" ]
94588ac58bcca1f44ace5695d1984da1bd98fe1a
https://github.com/kristianmandrup/roles_generic/blob/94588ac58bcca1f44ace5695d1984da1bd98fe1a/lib/roles_generic/generic/user/implementation.rb#L16-L19
train
kristianmandrup/roles_generic
lib/roles_generic/generic/user/implementation.rb
Roles::Generic::User.Implementation.remove_role
def remove_role role raise ArgumentError, '#remove_role takes a single role String or Symbol as the argument' if !role || role.kind_of?(Array) remove_roles role end
ruby
def remove_role role raise ArgumentError, '#remove_role takes a single role String or Symbol as the argument' if !role || role.kind_of?(Array) remove_roles role end
[ "def", "remove_role", "role", "raise", "ArgumentError", ",", "'#remove_role takes a single role String or Symbol as the argument'", "if", "!", "role", "||", "role", ".", "kind_of?", "(", "Array", ")", "remove_roles", "role", "end" ]
remove a single role
[ "remove", "a", "single", "role" ]
94588ac58bcca1f44ace5695d1984da1bd98fe1a
https://github.com/kristianmandrup/roles_generic/blob/94588ac58bcca1f44ace5695d1984da1bd98fe1a/lib/roles_generic/generic/user/implementation.rb#L22-L25
train
zohararad/handlebarer
lib/handlebarer/compiler.rb
Handlebarer.Compiler.v8_context
def v8_context V8::C::Locker() do context = V8::Context.new context.eval(source) yield context end end
ruby
def v8_context V8::C::Locker() do context = V8::Context.new context.eval(source) yield context end end
[ "def", "v8_context", "V8", "::", "C", "::", "Locker", "(", ")", "do", "context", "=", "V8", "::", "Context", ".", "new", "context", ".", "eval", "(", "source", ")", "yield", "context", "end", "end" ]
V8 context with Handlerbars code compiled @yield [context] V8::Context compiled Handlerbars source code in V8 context
[ "V8", "context", "with", "Handlerbars", "code", "compiled" ]
f5b2db17cb72fd2874ebe8268cf6f2ae17e74002
https://github.com/zohararad/handlebarer/blob/f5b2db17cb72fd2874ebe8268cf6f2ae17e74002/lib/handlebarer/compiler.rb#L14-L20
train