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
jeremyd/virtualmonkey
lib/virtualmonkey/frontend.rb
VirtualMonkey.Frontend.get_lb_hostname_input
def get_lb_hostname_input lb_hostname_input = "text:" fe_servers.each do |fe| timeout = 30 loopcounter = 0 begin if fe.settings['private-dns-name'] == nil raise "FATAL: private DNS name is empty" if loopcounter > 10 sleep(timeout) loopcounter += 1 next end lb_hostname_input << fe.settings['private-dns-name'] + " " done = true end while !done end lb_hostname_input end
ruby
def get_lb_hostname_input lb_hostname_input = "text:" fe_servers.each do |fe| timeout = 30 loopcounter = 0 begin if fe.settings['private-dns-name'] == nil raise "FATAL: private DNS name is empty" if loopcounter > 10 sleep(timeout) loopcounter += 1 next end lb_hostname_input << fe.settings['private-dns-name'] + " " done = true end while !done end lb_hostname_input end
[ "def", "get_lb_hostname_input", "lb_hostname_input", "=", "\"text:\"", "fe_servers", ".", "each", "do", "|", "fe", "|", "timeout", "=", "30", "loopcounter", "=", "0", "begin", "if", "fe", ".", "settings", "[", "'private-dns-name'", "]", "==", "nil", "raise", "\"FATAL: private DNS name is empty\"", "if", "loopcounter", ">", "10", "sleep", "(", "timeout", ")", "loopcounter", "+=", "1", "next", "end", "lb_hostname_input", "<<", "fe", ".", "settings", "[", "'private-dns-name'", "]", "+", "\" \"", "done", "=", "true", "end", "while", "!", "done", "end", "lb_hostname_input", "end" ]
returns String with all the private dns of the Front End servers used for setting the LB_HOSTNAME input.
[ "returns", "String", "with", "all", "the", "private", "dns", "of", "the", "Front", "End", "servers", "used", "for", "setting", "the", "LB_HOSTNAME", "input", "." ]
b2c7255f20ac5ec881eb90afbb5e712160db0dcb
https://github.com/jeremyd/virtualmonkey/blob/b2c7255f20ac5ec881eb90afbb5e712160db0dcb/lib/virtualmonkey/frontend.rb#L15-L32
train
dmitrizagidulin/riagent
lib/riagent/configuration.rb
Riagent.Configuration.config_for
def config_for(environment=:development) if self.config.present? env_config = self.config[environment.to_s] else env_config = { 'host' => ENV['RIAK_HOST'], 'http_port' => ENV['RIAK_HTTP_PORT'], 'pb_port' => ENV['RIAK_PB_PORT'] } end env_config end
ruby
def config_for(environment=:development) if self.config.present? env_config = self.config[environment.to_s] else env_config = { 'host' => ENV['RIAK_HOST'], 'http_port' => ENV['RIAK_HTTP_PORT'], 'pb_port' => ENV['RIAK_PB_PORT'] } end env_config end
[ "def", "config_for", "(", "environment", "=", ":development", ")", "if", "self", ".", "config", ".", "present?", "env_config", "=", "self", ".", "config", "[", "environment", ".", "to_s", "]", "else", "env_config", "=", "{", "'host'", "=>", "ENV", "[", "'RIAK_HOST'", "]", ",", "'http_port'", "=>", "ENV", "[", "'RIAK_HTTP_PORT'", "]", ",", "'pb_port'", "=>", "ENV", "[", "'RIAK_PB_PORT'", "]", "}", "end", "env_config", "end" ]
Return a configuration hash for a given environment @param [Symbol] environment Environment for which to load the client configs @return [Hash]
[ "Return", "a", "configuration", "hash", "for", "a", "given", "environment" ]
074bbb9c354abc1ba2037d704b0706caa3f34f37
https://github.com/dmitrizagidulin/riagent/blob/074bbb9c354abc1ba2037d704b0706caa3f34f37/lib/riagent/configuration.rb#L38-L49
train
gr4y/streambot
lib/streambot/handler.rb
StreamBot.Handler.parse_response
def parse_response(object) LOG.debug("response is #{object}") case object when ::Net::HTTPUnauthorized ::File.delete(ACCESS_TOKEN) raise 'user revoked oauth connection' when ::Net::HTTPOK then object.body end end
ruby
def parse_response(object) LOG.debug("response is #{object}") case object when ::Net::HTTPUnauthorized ::File.delete(ACCESS_TOKEN) raise 'user revoked oauth connection' when ::Net::HTTPOK then object.body end end
[ "def", "parse_response", "(", "object", ")", "LOG", ".", "debug", "(", "\"response is #{object}\"", ")", "case", "object", "when", "::", "Net", "::", "HTTPUnauthorized", "::", "File", ".", "delete", "(", "ACCESS_TOKEN", ")", "raise", "'user revoked oauth connection'", "when", "::", "Net", "::", "HTTPOK", "then", "object", ".", "body", "end", "end" ]
parse an response
[ "parse", "an", "response" ]
3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375
https://github.com/gr4y/streambot/blob/3f454b62ea0c1e9eb29a3c7bf0d17f3caf14b375/lib/streambot/handler.rb#L5-L14
train
esmarkowski/schemata
lib/schemata/schema/addressable.rb
Schemata.Schema.addressable
def addressable apply_schema :street_address_1, String apply_schema :street_address_2, String apply_schema :city, String apply_schema :state, String apply_schema :zip_code, String apply_schema :country, String end
ruby
def addressable apply_schema :street_address_1, String apply_schema :street_address_2, String apply_schema :city, String apply_schema :state, String apply_schema :zip_code, String apply_schema :country, String end
[ "def", "addressable", "apply_schema", ":street_address_1", ",", "String", "apply_schema", ":street_address_2", ",", "String", "apply_schema", ":city", ",", "String", "apply_schema", ":state", ",", "String", "apply_schema", ":zip_code", ",", "String", "apply_schema", ":country", ",", "String", "end" ]
Provides a common set of address fields such as, street_address_1, street_address_2, city, state, zip_code and country as String fields.
[ "Provides", "a", "common", "set", "of", "address", "fields", "such", "as", "street_address_1", "street_address_2", "city", "state", "zip_code", "and", "country", "as", "String", "fields", "." ]
59689b60eefcf6d15babebea37ee58325e0f6042
https://github.com/esmarkowski/schemata/blob/59689b60eefcf6d15babebea37ee58325e0f6042/lib/schemata/schema/addressable.rb#L6-L13
train
caruby/core
lib/caruby/database/persistable.rb
CaRuby.Persistable.merge_into_snapshot
def merge_into_snapshot(other) if @snapshot.nil? then raise ValidationError.new("Cannot merge #{other.qp} content into #{qp} snapshot, since #{qp} does not have a snapshot.") end # the non-domain attribute => [target value, other value] difference hash delta = diff(other) # the difference attribute => other value hash, excluding nil other values dvh = delta.transform_value { |d| d.last } return if dvh.empty? logger.debug { "#{qp} differs from database content #{other.qp} as follows: #{delta.filter_on_key { |pa| dvh.has_key?(pa) }.qp}" } logger.debug { "Setting #{qp} snapshot values from other #{other.qp} values to reflect the database state: #{dvh.qp}..." } # update the snapshot from the other value to reflect the database state @snapshot.merge!(dvh) end
ruby
def merge_into_snapshot(other) if @snapshot.nil? then raise ValidationError.new("Cannot merge #{other.qp} content into #{qp} snapshot, since #{qp} does not have a snapshot.") end # the non-domain attribute => [target value, other value] difference hash delta = diff(other) # the difference attribute => other value hash, excluding nil other values dvh = delta.transform_value { |d| d.last } return if dvh.empty? logger.debug { "#{qp} differs from database content #{other.qp} as follows: #{delta.filter_on_key { |pa| dvh.has_key?(pa) }.qp}" } logger.debug { "Setting #{qp} snapshot values from other #{other.qp} values to reflect the database state: #{dvh.qp}..." } # update the snapshot from the other value to reflect the database state @snapshot.merge!(dvh) end
[ "def", "merge_into_snapshot", "(", "other", ")", "if", "@snapshot", ".", "nil?", "then", "raise", "ValidationError", ".", "new", "(", "\"Cannot merge #{other.qp} content into #{qp} snapshot, since #{qp} does not have a snapshot.\"", ")", "end", "delta", "=", "diff", "(", "other", ")", "dvh", "=", "delta", ".", "transform_value", "{", "|", "d", "|", "d", ".", "last", "}", "return", "if", "dvh", ".", "empty?", "logger", ".", "debug", "{", "\"#{qp} differs from database content #{other.qp} as follows: #{delta.filter_on_key { |pa| dvh.has_key?(pa) }.qp}\"", "}", "logger", ".", "debug", "{", "\"Setting #{qp} snapshot values from other #{other.qp} values to reflect the database state: #{dvh.qp}...\"", "}", "@snapshot", ".", "merge!", "(", "dvh", ")", "end" ]
Merges the other domain object non-domain attribute values into this domain object's snapshot, An existing snapshot value is replaced by the corresponding other attribute value. @param [Jinx::Resource] other the source domain object @raise [ValidationError] if this domain object does not have a snapshot
[ "Merges", "the", "other", "domain", "object", "non", "-", "domain", "attribute", "values", "into", "this", "domain", "object", "s", "snapshot", "An", "existing", "snapshot", "value", "is", "replaced", "by", "the", "corresponding", "other", "attribute", "value", "." ]
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/persistable.rb#L145-L158
train
caruby/core
lib/caruby/database/persistable.rb
CaRuby.Persistable.add_lazy_loader
def add_lazy_loader(loader, attributes=nil) # guard against invalid call if identifier.nil? then raise ValidationError.new("Cannot add lazy loader to an unfetched domain object: #{self}") end # the attributes to lazy-load attributes ||= loadable_attributes return if attributes.empty? # define the reader and writer method overrides for the missing attributes pas = attributes.select { |pa| inject_lazy_loader(pa) } logger.debug { "Lazy loader added to #{qp} attributes #{pas.to_series}." } unless pas.empty? end
ruby
def add_lazy_loader(loader, attributes=nil) # guard against invalid call if identifier.nil? then raise ValidationError.new("Cannot add lazy loader to an unfetched domain object: #{self}") end # the attributes to lazy-load attributes ||= loadable_attributes return if attributes.empty? # define the reader and writer method overrides for the missing attributes pas = attributes.select { |pa| inject_lazy_loader(pa) } logger.debug { "Lazy loader added to #{qp} attributes #{pas.to_series}." } unless pas.empty? end
[ "def", "add_lazy_loader", "(", "loader", ",", "attributes", "=", "nil", ")", "if", "identifier", ".", "nil?", "then", "raise", "ValidationError", ".", "new", "(", "\"Cannot add lazy loader to an unfetched domain object: #{self}\"", ")", "end", "attributes", "||=", "loadable_attributes", "return", "if", "attributes", ".", "empty?", "pas", "=", "attributes", ".", "select", "{", "|", "pa", "|", "inject_lazy_loader", "(", "pa", ")", "}", "logger", ".", "debug", "{", "\"Lazy loader added to #{qp} attributes #{pas.to_series}.\"", "}", "unless", "pas", ".", "empty?", "end" ]
Lazy loads the attributes. If a block is given to this method, then the attributes are determined by calling the block with this Persistable as a parameter. Otherwise, the default attributes are the unfetched domain attributes. Each of the attributes which does not already hold a non-nil or non-empty value will be loaded from the database on demand. This method injects attribute value initialization into each loadable attribute reader. The initializer is given by either the loader Proc argument. The loader takes two arguments, the target object and the attribute to load. If this Persistable already has a lazy loader, then this method is a no-op. Lazy loading is disabled on an attribute after it is invoked on that attribute or when the attribute setter method is called. @param loader [LazyLoader] the lazy loader to add
[ "Lazy", "loads", "the", "attributes", ".", "If", "a", "block", "is", "given", "to", "this", "method", "then", "the", "attributes", "are", "determined", "by", "calling", "the", "block", "with", "this", "Persistable", "as", "a", "parameter", ".", "Otherwise", "the", "default", "attributes", "are", "the", "unfetched", "domain", "attributes", "." ]
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/persistable.rb#L197-L206
train
caruby/core
lib/caruby/database/persistable.rb
CaRuby.Persistable.remove_lazy_loader
def remove_lazy_loader(attribute=nil) if attribute.nil? then return self.class.domain_attributes.each { |pa| remove_lazy_loader(pa) } end # the modified accessor method reader, writer = self.class.property(attribute).accessors # remove the reader override disable_singleton_method(reader) # remove the writer override disable_singleton_method(writer) end
ruby
def remove_lazy_loader(attribute=nil) if attribute.nil? then return self.class.domain_attributes.each { |pa| remove_lazy_loader(pa) } end # the modified accessor method reader, writer = self.class.property(attribute).accessors # remove the reader override disable_singleton_method(reader) # remove the writer override disable_singleton_method(writer) end
[ "def", "remove_lazy_loader", "(", "attribute", "=", "nil", ")", "if", "attribute", ".", "nil?", "then", "return", "self", ".", "class", ".", "domain_attributes", ".", "each", "{", "|", "pa", "|", "remove_lazy_loader", "(", "pa", ")", "}", "end", "reader", ",", "writer", "=", "self", ".", "class", ".", "property", "(", "attribute", ")", ".", "accessors", "disable_singleton_method", "(", "reader", ")", "disable_singleton_method", "(", "writer", ")", "end" ]
Disables lazy loading of the specified attribute. Lazy loaded is disabled for all attributes if no attribute is specified. This method is a no-op if this Persistable does not have a lazy loader. @param [Symbol] the attribute to remove from the load list, or nil if to remove all attributes
[ "Disables", "lazy", "loading", "of", "the", "specified", "attribute", ".", "Lazy", "loaded", "is", "disabled", "for", "all", "attributes", "if", "no", "attribute", "is", "specified", ".", "This", "method", "is", "a", "no", "-", "op", "if", "this", "Persistable", "does", "not", "have", "a", "lazy", "loader", "." ]
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/persistable.rb#L231-L241
train
caruby/core
lib/caruby/database/persistable.rb
CaRuby.Persistable.fetch_saved?
def fetch_saved? # only fetch a create, not an update (note that subclasses can override this condition) return false if identifier # Check for an attribute with a value that might need to be changed in order to # reflect the auto-generated database content. ag_attrs = self.class.autogenerated_attributes return false if ag_attrs.empty? ag_attrs.any? { |pa| not send(pa).nil_or_empty? } end
ruby
def fetch_saved? # only fetch a create, not an update (note that subclasses can override this condition) return false if identifier # Check for an attribute with a value that might need to be changed in order to # reflect the auto-generated database content. ag_attrs = self.class.autogenerated_attributes return false if ag_attrs.empty? ag_attrs.any? { |pa| not send(pa).nil_or_empty? } end
[ "def", "fetch_saved?", "return", "false", "if", "identifier", "ag_attrs", "=", "self", ".", "class", ".", "autogenerated_attributes", "return", "false", "if", "ag_attrs", ".", "empty?", "ag_attrs", ".", "any?", "{", "|", "pa", "|", "not", "send", "(", "pa", ")", ".", "nil_or_empty?", "}", "end" ]
Returns whether this domain object must be fetched to reflect the database state. This default implementation returns whether this domain object was created and there are any autogenerated attributes. Subclasses can override to relax or restrict the condition. @quirk caCORE The auto-generated criterion is a necessary but not sufficient condition to determine whether a save caCORE result reflects the database state. Example: * caTissue SCG event parameters are not auto-generated on SCG create if the SCG collection status is Pending, but are auto-generated on SCG update if the SCG status is changed to Complete. By contrast, the SCG specimens are auto-generated on SCG create, even if the status is +Pending+. The caBIG application can override this method in a Database subclass to fine-tune the fetch criteria. Adding a more restrictive {#fetch_saved?} condition will will improve performance but not change functionality. @quirk caCORE A saved attribute which is cascaded but not fetched must be fetched in order to reflect the database identifier in the saved object. TODO - this method is no longeer used. Should it be? If not, remove here and in catissue subclasses. @return [Boolean] whether this domain object must be fetched to reflect the database state
[ "Returns", "whether", "this", "domain", "object", "must", "be", "fetched", "to", "reflect", "the", "database", "state", ".", "This", "default", "implementation", "returns", "whether", "this", "domain", "object", "was", "created", "and", "there", "are", "any", "autogenerated", "attributes", ".", "Subclasses", "can", "override", "to", "relax", "or", "restrict", "the", "condition", "." ]
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/persistable.rb#L378-L386
train
caruby/core
lib/caruby/database/persistable.rb
CaRuby.Persistable.inject_lazy_loader
def inject_lazy_loader(attribute) # bail if there is already a value return false if attribute_loaded?(attribute) # the accessor methods to modify reader, writer = self.class.property(attribute).accessors # The singleton attribute reader method loads the reference once and thenceforth calls the # standard reader. instance_eval "def #{reader}; load_reference(:#{attribute}); end" # The singleton attribute writer method removes the lazy loader once and thenceforth calls # the standard writer. instance_eval "def #{writer}(value); remove_lazy_loader(:#{attribute}); super; end" true end
ruby
def inject_lazy_loader(attribute) # bail if there is already a value return false if attribute_loaded?(attribute) # the accessor methods to modify reader, writer = self.class.property(attribute).accessors # The singleton attribute reader method loads the reference once and thenceforth calls the # standard reader. instance_eval "def #{reader}; load_reference(:#{attribute}); end" # The singleton attribute writer method removes the lazy loader once and thenceforth calls # the standard writer. instance_eval "def #{writer}(value); remove_lazy_loader(:#{attribute}); super; end" true end
[ "def", "inject_lazy_loader", "(", "attribute", ")", "return", "false", "if", "attribute_loaded?", "(", "attribute", ")", "reader", ",", "writer", "=", "self", ".", "class", ".", "property", "(", "attribute", ")", ".", "accessors", "instance_eval", "\"def #{reader}; load_reference(:#{attribute}); end\"", "instance_eval", "\"def #{writer}(value); remove_lazy_loader(:#{attribute}); super; end\"", "true", "end" ]
Adds this Persistable lazy loader to the given attribute unless the attribute already holds a fetched reference. @param [Symbol] attribute the attribute to mod @return [Boolean] whether a loader was added to the attribute
[ "Adds", "this", "Persistable", "lazy", "loader", "to", "the", "given", "attribute", "unless", "the", "attribute", "already", "holds", "a", "fetched", "reference", "." ]
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/persistable.rb#L471-L483
train
caruby/core
lib/caruby/database/persistable.rb
CaRuby.Persistable.load_reference
def load_reference(attribute) ldr = database.lazy_loader # bypass the singleton method and call the class instance method if the lazy loader is disabled return transient_value(attribute) unless ldr.enabled? # First disable lazy loading for the attribute, since the reader method is called by the loader. remove_lazy_loader(attribute) # load the fetched value merged = ldr.load(self, attribute) # update dependent snapshots if necessary pa = self.class.property(attribute) if pa.dependent? then # the owner attribute oattr = pa.inverse if oattr then # update dependent snapshot with the owner, since the owner snapshot is taken when fetched but the # owner might be set when the fetched dependent is merged into the owner dependent attribute. merged.enumerate do |dep| if dep.fetched? then dep.snapshot[oattr] = self logger.debug { "Updated the #{qp} fetched #{attribute} dependent #{dep.qp} snapshot with #{oattr} value #{qp}." } end end end end merged end
ruby
def load_reference(attribute) ldr = database.lazy_loader # bypass the singleton method and call the class instance method if the lazy loader is disabled return transient_value(attribute) unless ldr.enabled? # First disable lazy loading for the attribute, since the reader method is called by the loader. remove_lazy_loader(attribute) # load the fetched value merged = ldr.load(self, attribute) # update dependent snapshots if necessary pa = self.class.property(attribute) if pa.dependent? then # the owner attribute oattr = pa.inverse if oattr then # update dependent snapshot with the owner, since the owner snapshot is taken when fetched but the # owner might be set when the fetched dependent is merged into the owner dependent attribute. merged.enumerate do |dep| if dep.fetched? then dep.snapshot[oattr] = self logger.debug { "Updated the #{qp} fetched #{attribute} dependent #{dep.qp} snapshot with #{oattr} value #{qp}." } end end end end merged end
[ "def", "load_reference", "(", "attribute", ")", "ldr", "=", "database", ".", "lazy_loader", "return", "transient_value", "(", "attribute", ")", "unless", "ldr", ".", "enabled?", "remove_lazy_loader", "(", "attribute", ")", "merged", "=", "ldr", ".", "load", "(", "self", ",", "attribute", ")", "pa", "=", "self", ".", "class", ".", "property", "(", "attribute", ")", "if", "pa", ".", "dependent?", "then", "oattr", "=", "pa", ".", "inverse", "if", "oattr", "then", "merged", ".", "enumerate", "do", "|", "dep", "|", "if", "dep", ".", "fetched?", "then", "dep", ".", "snapshot", "[", "oattr", "]", "=", "self", "logger", ".", "debug", "{", "\"Updated the #{qp} fetched #{attribute} dependent #{dep.qp} snapshot with #{oattr} value #{qp}.\"", "}", "end", "end", "end", "end", "merged", "end" ]
Loads the reference attribute database value into this Persistable. @param [Symbol] attribute the attribute to load @return the attribute value merged from the database value
[ "Loads", "the", "reference", "attribute", "database", "value", "into", "this", "Persistable", "." ]
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/persistable.rb#L498-L526
train
caruby/core
lib/caruby/database/persistable.rb
CaRuby.Persistable.disable_singleton_method
def disable_singleton_method(name_or_sym) return unless singleton_methods.include?(name_or_sym.to_s) # dissociate the method from this instance method = self.method(name_or_sym.to_sym) method.unbind # JRuby unbind doesn't work in JRuby 1.1.6. In that case, redefine the singleton method to delegate # to the class instance method. if singleton_methods.include?(name_or_sym.to_s) then args = (1..method.arity).map { |argnum| "arg#{argnum}" }.join(', ') instance_eval "def #{name_or_sym}(#{args}); super; end" end end
ruby
def disable_singleton_method(name_or_sym) return unless singleton_methods.include?(name_or_sym.to_s) # dissociate the method from this instance method = self.method(name_or_sym.to_sym) method.unbind # JRuby unbind doesn't work in JRuby 1.1.6. In that case, redefine the singleton method to delegate # to the class instance method. if singleton_methods.include?(name_or_sym.to_s) then args = (1..method.arity).map { |argnum| "arg#{argnum}" }.join(', ') instance_eval "def #{name_or_sym}(#{args}); super; end" end end
[ "def", "disable_singleton_method", "(", "name_or_sym", ")", "return", "unless", "singleton_methods", ".", "include?", "(", "name_or_sym", ".", "to_s", ")", "method", "=", "self", ".", "method", "(", "name_or_sym", ".", "to_sym", ")", "method", ".", "unbind", "if", "singleton_methods", ".", "include?", "(", "name_or_sym", ".", "to_s", ")", "then", "args", "=", "(", "1", "..", "method", ".", "arity", ")", ".", "map", "{", "|", "argnum", "|", "\"arg#{argnum}\"", "}", ".", "join", "(", "', '", ")", "instance_eval", "\"def #{name_or_sym}(#{args}); super; end\"", "end", "end" ]
Disables the given singleton attribute accessor method. @param [String, Symbol] name_or_sym the accessor method to disable
[ "Disables", "the", "given", "singleton", "attribute", "accessor", "method", "." ]
a682dc57c6fa31aef765cdd206ed3d4b4c289c60
https://github.com/caruby/core/blob/a682dc57c6fa31aef765cdd206ed3d4b4c289c60/lib/caruby/database/persistable.rb#L537-L548
train
jackhq/mercury
lib/mercury/helpers.rb
Sinatra.MercuryHelpers.sass
def sass(sassfile, mediatype="all") render_style Sass::Engine.new(open_file(find_file(sassfile, SASS))).render, mediatype end
ruby
def sass(sassfile, mediatype="all") render_style Sass::Engine.new(open_file(find_file(sassfile, SASS))).render, mediatype end
[ "def", "sass", "(", "sassfile", ",", "mediatype", "=", "\"all\"", ")", "render_style", "Sass", "::", "Engine", ".", "new", "(", "open_file", "(", "find_file", "(", "sassfile", ",", "SASS", ")", ")", ")", ".", "render", ",", "mediatype", "end" ]
renders sass files
[ "renders", "sass", "files" ]
1ebbade5597a94a3d24b9ac7c7e2d3c214cfca5c
https://github.com/jackhq/mercury/blob/1ebbade5597a94a3d24b9ac7c7e2d3c214cfca5c/lib/mercury/helpers.rb#L27-L29
train
jackhq/mercury
lib/mercury/helpers.rb
Sinatra.MercuryHelpers.scss
def scss(scssfile, mediatype="all") render_style Sass::Engine.new(open_file(find_file(scssfile, SCSS)), :syntax => :scss).render, mediatype end
ruby
def scss(scssfile, mediatype="all") render_style Sass::Engine.new(open_file(find_file(scssfile, SCSS)), :syntax => :scss).render, mediatype end
[ "def", "scss", "(", "scssfile", ",", "mediatype", "=", "\"all\"", ")", "render_style", "Sass", "::", "Engine", ".", "new", "(", "open_file", "(", "find_file", "(", "scssfile", ",", "SCSS", ")", ")", ",", ":syntax", "=>", ":scss", ")", ".", "render", ",", "mediatype", "end" ]
renders scss files
[ "renders", "scss", "files" ]
1ebbade5597a94a3d24b9ac7c7e2d3c214cfca5c
https://github.com/jackhq/mercury/blob/1ebbade5597a94a3d24b9ac7c7e2d3c214cfca5c/lib/mercury/helpers.rb#L32-L34
train
medcat/brandish
lib/brandish/application.rb
Brandish.Application.call
def call program_information configure_global_option directory_global_option command(:initialize) { |c| InitializeCommand.define(self, c) } command(:bench) { |c| BenchCommand.define(self, c) } command(:build) { |c| BuildCommand.define(self, c) } command(:serve) { |c| ServeCommand.define(self, c) } alias_command(:init, :initialize) default_command(:build) run! end
ruby
def call program_information configure_global_option directory_global_option command(:initialize) { |c| InitializeCommand.define(self, c) } command(:bench) { |c| BenchCommand.define(self, c) } command(:build) { |c| BuildCommand.define(self, c) } command(:serve) { |c| ServeCommand.define(self, c) } alias_command(:init, :initialize) default_command(:build) run! end
[ "def", "call", "program_information", "configure_global_option", "directory_global_option", "command", "(", ":initialize", ")", "{", "|", "c", "|", "InitializeCommand", ".", "define", "(", "self", ",", "c", ")", "}", "command", "(", ":bench", ")", "{", "|", "c", "|", "BenchCommand", ".", "define", "(", "self", ",", "c", ")", "}", "command", "(", ":build", ")", "{", "|", "c", "|", "BuildCommand", ".", "define", "(", "self", ",", "c", ")", "}", "command", "(", ":serve", ")", "{", "|", "c", "|", "ServeCommand", ".", "define", "(", "self", ",", "c", ")", "}", "alias_command", "(", ":init", ",", ":initialize", ")", "default_command", "(", ":build", ")", "run!", "end" ]
Defines and runs the command line interface. @see #program_information @see #configure_global_option @see #directory_global_option @see InitializeCommand.define @see BenchCommand.define @see BuildCommand.define @see ServeCommand.define @return [void]
[ "Defines", "and", "runs", "the", "command", "line", "interface", "." ]
c63f91dbb356aa0958351ad9bcbdab0c57e7f649
https://github.com/medcat/brandish/blob/c63f91dbb356aa0958351ad9bcbdab0c57e7f649/lib/brandish/application.rb#L51-L62
train
medcat/brandish
lib/brandish/application.rb
Brandish.Application.program_information
def program_information program :name, "Brandish" program :version, Brandish::VERSION program :help_formatter, :compact program :help_paging, false program :description, "A multi-format document generator." program :help, "Author", "Jeremy Rodi <[email protected]>" program :help, "License", "MIT License Copyright (c) 2017 Jeremy Rodi" end
ruby
def program_information program :name, "Brandish" program :version, Brandish::VERSION program :help_formatter, :compact program :help_paging, false program :description, "A multi-format document generator." program :help, "Author", "Jeremy Rodi <[email protected]>" program :help, "License", "MIT License Copyright (c) 2017 Jeremy Rodi" end
[ "def", "program_information", "program", ":name", ",", "\"Brandish\"", "program", ":version", ",", "Brandish", "::", "VERSION", "program", ":help_formatter", ",", ":compact", "program", ":help_paging", ",", "false", "program", ":description", ",", "\"A multi-format document generator.\"", "program", ":help", ",", "\"Author\"", ",", "\"Jeremy Rodi <[email protected]>\"", "program", ":help", ",", "\"License\"", ",", "\"MIT License Copyright (c) 2017 Jeremy Rodi\"", "end" ]
The program information. This is for use with Commander. @return [void]
[ "The", "program", "information", ".", "This", "is", "for", "use", "with", "Commander", "." ]
c63f91dbb356aa0958351ad9bcbdab0c57e7f649
https://github.com/medcat/brandish/blob/c63f91dbb356aa0958351ad9bcbdab0c57e7f649/lib/brandish/application.rb#L67-L75
train
medcat/brandish
lib/brandish/application.rb
Brandish.Application.progress
def progress(array, &block) # rubocop:disable Style/GlobalVars width = $terminal.terminal_size[0] - PROGRESS_WIDTH # rubocop:enable Style/GlobalVars options = PROGRESS_OPTIONS.merge(width: width) super(array, options, &block) end
ruby
def progress(array, &block) # rubocop:disable Style/GlobalVars width = $terminal.terminal_size[0] - PROGRESS_WIDTH # rubocop:enable Style/GlobalVars options = PROGRESS_OPTIONS.merge(width: width) super(array, options, &block) end
[ "def", "progress", "(", "array", ",", "&", "block", ")", "width", "=", "$terminal", ".", "terminal_size", "[", "0", "]", "-", "PROGRESS_WIDTH", "options", "=", "PROGRESS_OPTIONS", ".", "merge", "(", "width", ":", "width", ")", "super", "(", "array", ",", "options", ",", "&", "block", ")", "end" ]
Creates a progress bar on the terminal based off of the given array. This mostly passes everything on to the `progress` method provided by Commander, but with a few options added. @param array [::Array] The array of items that are being processed. @yield [item] Once for every item in the array. Once the block ends, the progress bar increments. @yieldparam item [::Object] One of the items in the array. @return [void]
[ "Creates", "a", "progress", "bar", "on", "the", "terminal", "based", "off", "of", "the", "given", "array", ".", "This", "mostly", "passes", "everything", "on", "to", "the", "progress", "method", "provided", "by", "Commander", "but", "with", "a", "few", "options", "added", "." ]
c63f91dbb356aa0958351ad9bcbdab0c57e7f649
https://github.com/medcat/brandish/blob/c63f91dbb356aa0958351ad9bcbdab0c57e7f649/lib/brandish/application.rb#L122-L128
train
justfalter/align
lib/align/needleman_wunsch.rb
Align.NeedlemanWunsch.fill
def fill @matrix[0][0] = 0 # Set up the first column on each row. 1.upto(@rows-1) {|i| @matrix[i][0] = @matrix[i-1][0] + @scoring.score_delete(@seq1[i])} # Set up the first row 1.upto(@cols-1) {|j| @matrix[0][j] = @matrix[0][j-1] + @scoring.score_insert(@seq2[j])} 1.upto(@rows-1) do |i| prv_row = @matrix[i-1] cur_row = @matrix[i] 1.upto(@cols-1) do |j| seq1_obj = @seq1[i-1] seq2_obj = @seq2[j-1] # Calculate the score. score_align = prv_row[j-1] + @scoring.score_align(seq1_obj, seq2_obj) score_delete = prv_row[j] + @scoring.score_delete(seq1_obj) score_insert = cur_row[j-1] + @scoring.score_insert(seq2_obj) max = max3(score_align, score_delete, score_insert) @matrix[i][j] = max end end end
ruby
def fill @matrix[0][0] = 0 # Set up the first column on each row. 1.upto(@rows-1) {|i| @matrix[i][0] = @matrix[i-1][0] + @scoring.score_delete(@seq1[i])} # Set up the first row 1.upto(@cols-1) {|j| @matrix[0][j] = @matrix[0][j-1] + @scoring.score_insert(@seq2[j])} 1.upto(@rows-1) do |i| prv_row = @matrix[i-1] cur_row = @matrix[i] 1.upto(@cols-1) do |j| seq1_obj = @seq1[i-1] seq2_obj = @seq2[j-1] # Calculate the score. score_align = prv_row[j-1] + @scoring.score_align(seq1_obj, seq2_obj) score_delete = prv_row[j] + @scoring.score_delete(seq1_obj) score_insert = cur_row[j-1] + @scoring.score_insert(seq2_obj) max = max3(score_align, score_delete, score_insert) @matrix[i][j] = max end end end
[ "def", "fill", "@matrix", "[", "0", "]", "[", "0", "]", "=", "0", "1", ".", "upto", "(", "@rows", "-", "1", ")", "{", "|", "i", "|", "@matrix", "[", "i", "]", "[", "0", "]", "=", "@matrix", "[", "i", "-", "1", "]", "[", "0", "]", "+", "@scoring", ".", "score_delete", "(", "@seq1", "[", "i", "]", ")", "}", "1", ".", "upto", "(", "@cols", "-", "1", ")", "{", "|", "j", "|", "@matrix", "[", "0", "]", "[", "j", "]", "=", "@matrix", "[", "0", "]", "[", "j", "-", "1", "]", "+", "@scoring", ".", "score_insert", "(", "@seq2", "[", "j", "]", ")", "}", "1", ".", "upto", "(", "@rows", "-", "1", ")", "do", "|", "i", "|", "prv_row", "=", "@matrix", "[", "i", "-", "1", "]", "cur_row", "=", "@matrix", "[", "i", "]", "1", ".", "upto", "(", "@cols", "-", "1", ")", "do", "|", "j", "|", "seq1_obj", "=", "@seq1", "[", "i", "-", "1", "]", "seq2_obj", "=", "@seq2", "[", "j", "-", "1", "]", "score_align", "=", "prv_row", "[", "j", "-", "1", "]", "+", "@scoring", ".", "score_align", "(", "seq1_obj", ",", "seq2_obj", ")", "score_delete", "=", "prv_row", "[", "j", "]", "+", "@scoring", ".", "score_delete", "(", "seq1_obj", ")", "score_insert", "=", "cur_row", "[", "j", "-", "1", "]", "+", "@scoring", ".", "score_insert", "(", "seq2_obj", ")", "max", "=", "max3", "(", "score_align", ",", "score_delete", ",", "score_insert", ")", "@matrix", "[", "i", "]", "[", "j", "]", "=", "max", "end", "end", "end" ]
Fills the matrix with the alignment map.
[ "Fills", "the", "matrix", "with", "the", "alignment", "map", "." ]
e95ac63253e99ee18d66c1e7d9695f5eb80036cf
https://github.com/justfalter/align/blob/e95ac63253e99ee18d66c1e7d9695f5eb80036cf/lib/align/needleman_wunsch.rb#L41-L66
train
justfalter/align
lib/align/needleman_wunsch.rb
Align.NeedlemanWunsch.traceback
def traceback i = @rows - 1 j = @cols - 1 while (i > 0 && j > 0) score = @matrix[i][j] seq1_obj = @seq1[i-1] seq2_obj = @seq2[j-1] score_align = @matrix[i-1][j-1] + @scoring.score_align(seq1_obj, seq2_obj) score_delete = @matrix[i-1][j] + @scoring.score_delete(seq1_obj) score_insert = @matrix[i][j-1] + @scoring.score_insert(seq2_obj) flags = 0 need_select = false if score == score_align flags = :align i-=1 j-=1 elsif score == score_delete flags = :delete i-=1 else flags = :insert j-=1 end yield(i,j,flags) end # while while i > 0 i-=1 yield(i,j,:delete) end while j > 0 j-=1 yield(i,j,:insert) end end
ruby
def traceback i = @rows - 1 j = @cols - 1 while (i > 0 && j > 0) score = @matrix[i][j] seq1_obj = @seq1[i-1] seq2_obj = @seq2[j-1] score_align = @matrix[i-1][j-1] + @scoring.score_align(seq1_obj, seq2_obj) score_delete = @matrix[i-1][j] + @scoring.score_delete(seq1_obj) score_insert = @matrix[i][j-1] + @scoring.score_insert(seq2_obj) flags = 0 need_select = false if score == score_align flags = :align i-=1 j-=1 elsif score == score_delete flags = :delete i-=1 else flags = :insert j-=1 end yield(i,j,flags) end # while while i > 0 i-=1 yield(i,j,:delete) end while j > 0 j-=1 yield(i,j,:insert) end end
[ "def", "traceback", "i", "=", "@rows", "-", "1", "j", "=", "@cols", "-", "1", "while", "(", "i", ">", "0", "&&", "j", ">", "0", ")", "score", "=", "@matrix", "[", "i", "]", "[", "j", "]", "seq1_obj", "=", "@seq1", "[", "i", "-", "1", "]", "seq2_obj", "=", "@seq2", "[", "j", "-", "1", "]", "score_align", "=", "@matrix", "[", "i", "-", "1", "]", "[", "j", "-", "1", "]", "+", "@scoring", ".", "score_align", "(", "seq1_obj", ",", "seq2_obj", ")", "score_delete", "=", "@matrix", "[", "i", "-", "1", "]", "[", "j", "]", "+", "@scoring", ".", "score_delete", "(", "seq1_obj", ")", "score_insert", "=", "@matrix", "[", "i", "]", "[", "j", "-", "1", "]", "+", "@scoring", ".", "score_insert", "(", "seq2_obj", ")", "flags", "=", "0", "need_select", "=", "false", "if", "score", "==", "score_align", "flags", "=", ":align", "i", "-=", "1", "j", "-=", "1", "elsif", "score", "==", "score_delete", "flags", "=", ":delete", "i", "-=", "1", "else", "flags", "=", ":insert", "j", "-=", "1", "end", "yield", "(", "i", ",", "j", ",", "flags", ")", "end", "while", "i", ">", "0", "i", "-=", "1", "yield", "(", "i", ",", "j", ",", ":delete", ")", "end", "while", "j", ">", "0", "j", "-=", "1", "yield", "(", "i", ",", "j", ",", ":insert", ")", "end", "end" ]
fill Traces backward, finding the alignment. @yield [i,j,step] @yieldparam i [Integer] The location in sequence one @yieldparam j [Integer] The location in sequence two @yieldparam step [Integer] The direction we took
[ "fill", "Traces", "backward", "finding", "the", "alignment", "." ]
e95ac63253e99ee18d66c1e7d9695f5eb80036cf
https://github.com/justfalter/align/blob/e95ac63253e99ee18d66c1e7d9695f5eb80036cf/lib/align/needleman_wunsch.rb#L73-L114
train
ithouse/lolita-first-data
app/controllers/lolita_first_data/transactions_controller.rb
LolitaFirstData.TransactionsController.checkout
def checkout response = gateway.purchase(payment.price, currency: payment.currency.to_s, client_ip_addr: request.remote_ip, description: payment.description, language: payment.first_data_language) if response[:transaction_id] trx = LolitaFirstData::Transaction.add(payment, request, response) redirect_to gateway.redirect_url(trx.transaction_id) else if request.xhr? || !request.referer render text: I18n.t('fd.purchase_failed'), status: 400 else flash[:error] = I18n.t('fd.purchase_failed') redirect_to :back end end ensure LolitaFirstData.logger.info("[#{session_id}][#{payment.id}][checkout] #{response}") end
ruby
def checkout response = gateway.purchase(payment.price, currency: payment.currency.to_s, client_ip_addr: request.remote_ip, description: payment.description, language: payment.first_data_language) if response[:transaction_id] trx = LolitaFirstData::Transaction.add(payment, request, response) redirect_to gateway.redirect_url(trx.transaction_id) else if request.xhr? || !request.referer render text: I18n.t('fd.purchase_failed'), status: 400 else flash[:error] = I18n.t('fd.purchase_failed') redirect_to :back end end ensure LolitaFirstData.logger.info("[#{session_id}][#{payment.id}][checkout] #{response}") end
[ "def", "checkout", "response", "=", "gateway", ".", "purchase", "(", "payment", ".", "price", ",", "currency", ":", "payment", ".", "currency", ".", "to_s", ",", "client_ip_addr", ":", "request", ".", "remote_ip", ",", "description", ":", "payment", ".", "description", ",", "language", ":", "payment", ".", "first_data_language", ")", "if", "response", "[", ":transaction_id", "]", "trx", "=", "LolitaFirstData", "::", "Transaction", ".", "add", "(", "payment", ",", "request", ",", "response", ")", "redirect_to", "gateway", ".", "redirect_url", "(", "trx", ".", "transaction_id", ")", "else", "if", "request", ".", "xhr?", "||", "!", "request", ".", "referer", "render", "text", ":", "I18n", ".", "t", "(", "'fd.purchase_failed'", ")", ",", "status", ":", "400", "else", "flash", "[", ":error", "]", "=", "I18n", ".", "t", "(", "'fd.purchase_failed'", ")", "redirect_to", ":back", "end", "end", "ensure", "LolitaFirstData", ".", "logger", ".", "info", "(", "\"[#{session_id}][#{payment.id}][checkout] #{response}\"", ")", "end" ]
We get transaction_id from FirstData and if ok, then we redirect to web interface
[ "We", "get", "transaction_id", "from", "FirstData", "and", "if", "ok", "then", "we", "redirect", "to", "web", "interface" ]
f148588b06a50bfe274b92816700b20c2e899247
https://github.com/ithouse/lolita-first-data/blob/f148588b06a50bfe274b92816700b20c2e899247/app/controllers/lolita_first_data/transactions_controller.rb#L8-L27
train
ithouse/lolita-first-data
app/controllers/lolita_first_data/transactions_controller.rb
LolitaFirstData.TransactionsController.answer
def answer if trx = LolitaFirstData::Transaction.where(transaction_id: params[:trans_id]).first response = gateway.result(params[:trans_id], client_ip_addr: request.remote_ip) trx.process_result(response) redirect_to trx.return_path else render text: I18n.t('fd.wrong_request'), status: 400 end ensure if trx LolitaFirstData.logger.info("[#{session_id}][#{trx.paymentable_id}][answer] #{response}") end end
ruby
def answer if trx = LolitaFirstData::Transaction.where(transaction_id: params[:trans_id]).first response = gateway.result(params[:trans_id], client_ip_addr: request.remote_ip) trx.process_result(response) redirect_to trx.return_path else render text: I18n.t('fd.wrong_request'), status: 400 end ensure if trx LolitaFirstData.logger.info("[#{session_id}][#{trx.paymentable_id}][answer] #{response}") end end
[ "def", "answer", "if", "trx", "=", "LolitaFirstData", "::", "Transaction", ".", "where", "(", "transaction_id", ":", "params", "[", ":trans_id", "]", ")", ".", "first", "response", "=", "gateway", ".", "result", "(", "params", "[", ":trans_id", "]", ",", "client_ip_addr", ":", "request", ".", "remote_ip", ")", "trx", ".", "process_result", "(", "response", ")", "redirect_to", "trx", ".", "return_path", "else", "render", "text", ":", "I18n", ".", "t", "(", "'fd.wrong_request'", ")", ",", "status", ":", "400", "end", "ensure", "if", "trx", "LolitaFirstData", ".", "logger", ".", "info", "(", "\"[#{session_id}][#{trx.paymentable_id}][answer] #{response}\"", ")", "end", "end" ]
there we land after returning from FirstData server then we get transactions result and redirect to your given "finish" path
[ "there", "we", "land", "after", "returning", "from", "FirstData", "server", "then", "we", "get", "transactions", "result", "and", "redirect", "to", "your", "given", "finish", "path" ]
f148588b06a50bfe274b92816700b20c2e899247
https://github.com/ithouse/lolita-first-data/blob/f148588b06a50bfe274b92816700b20c2e899247/app/controllers/lolita_first_data/transactions_controller.rb#L31-L43
train
cwabbott/heart
app/helpers/heart/dashboards_helper.rb
Heart.DashboardsHelper.flot_array
def flot_array(metrics) replace = false hash = Hash.new if metrics.nil? || metrics.first.nil? || metrics.first.movingaverage.nil? replace = true metrics = Metric.aggregate_daily_moving_averages(0, "WHERE fulldate > SUBDATE((SELECT fulldate FROM heart_metrics WHERE movingaverage = 0 ORDER BY fulldate desc LIMIT 1), 3)") end if metrics.first.nil? return '' end movingaverage = metrics.first.movingaverage #TODO need to move all these options into the HEART js object, set these at runtime, make them easily customizable in the UI extraMeasurements = '' label_suffix = '' if replace == true extraMeasurements = "lines : { show : false, fill : false }," label_suffix = '' else if movingaverage.to_i > 0 extraMeasurements = 'points : { show : false, symbol : "circle" }, lines : { show : true, fill : false },' label_suffix = " [MA:#{movingaverage}] " end end#if replace = true #loop through for all the standard measurements metrics.first.attributes.sort.each do |att, value| next unless value.respond_to? :to_f next if value.is_a? Time extraSettings = extraMeasurements label = t(att) + label_suffix hash[att] = "#{att} : {#{extraSettings} label : '#{label}', data : [" end # # Now start creating the data arrays for flot. [date_converted_to_integer, value_of_metric_for_date] # metrics.each do |metric| metric.attributes.sort.each do |att, value| next unless value.respond_to? :to_f next if value.is_a? Time hash[att] = "#{hash[att]} [#{to_flot_time(metric.fulldate)}, #{value}]," end end # # Finished creating data arrays # metrics.first.attributes.sort.each do |att, value| next unless value.respond_to? :to_f next if value.is_a? Time hash[att] = "#{hash[att]} ], att_name : \"#{att}\",}," end flotdata = "flotData_#{movingaverage} : {" hash.each { |key, value| flotdata += value + "\n" } flotdata += "}," flotdata end
ruby
def flot_array(metrics) replace = false hash = Hash.new if metrics.nil? || metrics.first.nil? || metrics.first.movingaverage.nil? replace = true metrics = Metric.aggregate_daily_moving_averages(0, "WHERE fulldate > SUBDATE((SELECT fulldate FROM heart_metrics WHERE movingaverage = 0 ORDER BY fulldate desc LIMIT 1), 3)") end if metrics.first.nil? return '' end movingaverage = metrics.first.movingaverage #TODO need to move all these options into the HEART js object, set these at runtime, make them easily customizable in the UI extraMeasurements = '' label_suffix = '' if replace == true extraMeasurements = "lines : { show : false, fill : false }," label_suffix = '' else if movingaverage.to_i > 0 extraMeasurements = 'points : { show : false, symbol : "circle" }, lines : { show : true, fill : false },' label_suffix = " [MA:#{movingaverage}] " end end#if replace = true #loop through for all the standard measurements metrics.first.attributes.sort.each do |att, value| next unless value.respond_to? :to_f next if value.is_a? Time extraSettings = extraMeasurements label = t(att) + label_suffix hash[att] = "#{att} : {#{extraSettings} label : '#{label}', data : [" end # # Now start creating the data arrays for flot. [date_converted_to_integer, value_of_metric_for_date] # metrics.each do |metric| metric.attributes.sort.each do |att, value| next unless value.respond_to? :to_f next if value.is_a? Time hash[att] = "#{hash[att]} [#{to_flot_time(metric.fulldate)}, #{value}]," end end # # Finished creating data arrays # metrics.first.attributes.sort.each do |att, value| next unless value.respond_to? :to_f next if value.is_a? Time hash[att] = "#{hash[att]} ], att_name : \"#{att}\",}," end flotdata = "flotData_#{movingaverage} : {" hash.each { |key, value| flotdata += value + "\n" } flotdata += "}," flotdata end
[ "def", "flot_array", "(", "metrics", ")", "replace", "=", "false", "hash", "=", "Hash", ".", "new", "if", "metrics", ".", "nil?", "||", "metrics", ".", "first", ".", "nil?", "||", "metrics", ".", "first", ".", "movingaverage", ".", "nil?", "replace", "=", "true", "metrics", "=", "Metric", ".", "aggregate_daily_moving_averages", "(", "0", ",", "\"WHERE fulldate > SUBDATE((SELECT fulldate FROM heart_metrics WHERE movingaverage = 0 ORDER BY fulldate desc LIMIT 1), 3)\"", ")", "end", "if", "metrics", ".", "first", ".", "nil?", "return", "''", "end", "movingaverage", "=", "metrics", ".", "first", ".", "movingaverage", "extraMeasurements", "=", "''", "label_suffix", "=", "''", "if", "replace", "==", "true", "extraMeasurements", "=", "\"lines : { show : false, fill : false },\"", "label_suffix", "=", "''", "else", "if", "movingaverage", ".", "to_i", ">", "0", "extraMeasurements", "=", "'points : { show : false, symbol : \"circle\" }, lines : { show : true, fill : false },'", "label_suffix", "=", "\" [MA:#{movingaverage}] \"", "end", "end", "metrics", ".", "first", ".", "attributes", ".", "sort", ".", "each", "do", "|", "att", ",", "value", "|", "next", "unless", "value", ".", "respond_to?", ":to_f", "next", "if", "value", ".", "is_a?", "Time", "extraSettings", "=", "extraMeasurements", "label", "=", "t", "(", "att", ")", "+", "label_suffix", "hash", "[", "att", "]", "=", "\"#{att} : {#{extraSettings} label : '#{label}', data : [\"", "end", "metrics", ".", "each", "do", "|", "metric", "|", "metric", ".", "attributes", ".", "sort", ".", "each", "do", "|", "att", ",", "value", "|", "next", "unless", "value", ".", "respond_to?", ":to_f", "next", "if", "value", ".", "is_a?", "Time", "hash", "[", "att", "]", "=", "\"#{hash[att]} [#{to_flot_time(metric.fulldate)}, #{value}],\"", "end", "end", "metrics", ".", "first", ".", "attributes", ".", "sort", ".", "each", "do", "|", "att", ",", "value", "|", "next", "unless", "value", ".", "respond_to?", ":to_f", "next", "if", "value", ".", "is_a?", "Time", "hash", "[", "att", "]", "=", "\"#{hash[att]} ], att_name : \\\"#{att}\\\",},\"", "end", "flotdata", "=", "\"flotData_#{movingaverage} : {\"", "hash", ".", "each", "{", "|", "key", ",", "value", "|", "flotdata", "+=", "value", "+", "\"\\n\"", "}", "flotdata", "+=", "\"},\"", "flotdata", "end" ]
Creates javascript objects to use as hashes for flot graph data series + labels
[ "Creates", "javascript", "objects", "to", "use", "as", "hashes", "for", "flot", "graph", "data", "series", "+", "labels" ]
593740a96152fe896848155888ba866f5bbb3dc3
https://github.com/cwabbott/heart/blob/593740a96152fe896848155888ba866f5bbb3dc3/app/helpers/heart/dashboards_helper.rb#L31-L86
train
jtzero/vigilem-core
lib/vigilem/core/hooks/callback.rb
Vigilem::Core::Hooks.Callback.evaluate
def evaluate(context, *args, &block) self.result = if block context.define_singleton_method(:__callback__, &self) ret = context.send :__callback__, *args, &block context.class_eval { send :remove_method, :__callback__ } ret else context.instance_exec(*args, &self) end end
ruby
def evaluate(context, *args, &block) self.result = if block context.define_singleton_method(:__callback__, &self) ret = context.send :__callback__, *args, &block context.class_eval { send :remove_method, :__callback__ } ret else context.instance_exec(*args, &self) end end
[ "def", "evaluate", "(", "context", ",", "*", "args", ",", "&", "block", ")", "self", ".", "result", "=", "if", "block", "context", ".", "define_singleton_method", "(", ":__callback__", ",", "&", "self", ")", "ret", "=", "context", ".", "send", ":__callback__", ",", "*", "args", ",", "&", "block", "context", ".", "class_eval", "{", "send", ":remove_method", ",", ":__callback__", "}", "ret", "else", "context", ".", "instance_exec", "(", "*", "args", ",", "&", "self", ")", "end", "end" ]
evaluates the Callback in the specified context @param context @param [Array] args @param [Proc] block @return [Array]
[ "evaluates", "the", "Callback", "in", "the", "specified", "context" ]
a35864229ee76800f5197e3c3c6fb2bf34a68495
https://github.com/jtzero/vigilem-core/blob/a35864229ee76800f5197e3c3c6fb2bf34a68495/lib/vigilem/core/hooks/callback.rb#L22-L31
train
pione/ruby-xes
lib/xes/attribute-accessor.rb
XES.AttributeAccessor.define_attribute
def define_attribute(name, type) _name = name.gsub(":", "_") define_method(_name) do var = instance_variables.include?(:@meta) ? :@meta : :@attributes instance_variable_get(var).find do |attribute| attribute.key == name end.tap{|x| return x.value if x} end define_method("%s=" % _name) do |value| var = instance_variables.include?(:@meta) ? :@meta : :@attributes instance_variable_get(var).tap do |attributes| if elt = __send__(_name) attributes.delete(elt) end attributes << XES.send(type, name, value) end end end
ruby
def define_attribute(name, type) _name = name.gsub(":", "_") define_method(_name) do var = instance_variables.include?(:@meta) ? :@meta : :@attributes instance_variable_get(var).find do |attribute| attribute.key == name end.tap{|x| return x.value if x} end define_method("%s=" % _name) do |value| var = instance_variables.include?(:@meta) ? :@meta : :@attributes instance_variable_get(var).tap do |attributes| if elt = __send__(_name) attributes.delete(elt) end attributes << XES.send(type, name, value) end end end
[ "def", "define_attribute", "(", "name", ",", "type", ")", "_name", "=", "name", ".", "gsub", "(", "\":\"", ",", "\"_\"", ")", "define_method", "(", "_name", ")", "do", "var", "=", "instance_variables", ".", "include?", "(", ":@meta", ")", "?", ":@meta", ":", ":@attributes", "instance_variable_get", "(", "var", ")", ".", "find", "do", "|", "attribute", "|", "attribute", ".", "key", "==", "name", "end", ".", "tap", "{", "|", "x", "|", "return", "x", ".", "value", "if", "x", "}", "end", "define_method", "(", "\"%s=\"", "%", "_name", ")", "do", "|", "value", "|", "var", "=", "instance_variables", ".", "include?", "(", ":@meta", ")", "?", ":@meta", ":", ":@attributes", "instance_variable_get", "(", "var", ")", ".", "tap", "do", "|", "attributes", "|", "if", "elt", "=", "__send__", "(", "_name", ")", "attributes", ".", "delete", "(", "elt", ")", "end", "attributes", "<<", "XES", ".", "send", "(", "type", ",", "name", ",", "value", ")", "end", "end", "end" ]
Define an attribute accessor. @param name [String] attribute name @param type [String] attribute type @return [void]
[ "Define", "an", "attribute", "accessor", "." ]
61501a8fd8027708f670264a150b1ce74fdccd74
https://github.com/pione/ruby-xes/blob/61501a8fd8027708f670264a150b1ce74fdccd74/lib/xes/attribute-accessor.rb#L11-L30
train
MrJoy/orderly_garden
lib/orderly_garden/dsl.rb
OrderlyGarden.DSL.with_tempfile
def with_tempfile(fname = nil, &_block) Tempfile.open("tmp") do |f| yield f.path, f.path.shellescape FileUtils.cp(f.path, fname) unless fname.nil? end end
ruby
def with_tempfile(fname = nil, &_block) Tempfile.open("tmp") do |f| yield f.path, f.path.shellescape FileUtils.cp(f.path, fname) unless fname.nil? end end
[ "def", "with_tempfile", "(", "fname", "=", "nil", ",", "&", "_block", ")", "Tempfile", ".", "open", "(", "\"tmp\"", ")", "do", "|", "f", "|", "yield", "f", ".", "path", ",", "f", ".", "path", ".", "shellescape", "FileUtils", ".", "cp", "(", "f", ".", "path", ",", "fname", ")", "unless", "fname", ".", "nil?", "end", "end" ]
Create and manage a temp file, replacing `fname` with the temp file, if `fname` is provided.
[ "Create", "and", "manage", "a", "temp", "file", "replacing", "fname", "with", "the", "temp", "file", "if", "fname", "is", "provided", "." ]
413bcf013de7b7c10650685f713d5131e19494a9
https://github.com/MrJoy/orderly_garden/blob/413bcf013de7b7c10650685f713d5131e19494a9/lib/orderly_garden/dsl.rb#L7-L12
train
MrJoy/orderly_garden
lib/orderly_garden/dsl.rb
OrderlyGarden.DSL.write_file
def write_file(file_name, file_contents) contents = file_contents .flatten .select { |line| line } .join("\n") File.open(file_name, "w") do |fh| fh.write(contents) fh.write("\n") end end
ruby
def write_file(file_name, file_contents) contents = file_contents .flatten .select { |line| line } .join("\n") File.open(file_name, "w") do |fh| fh.write(contents) fh.write("\n") end end
[ "def", "write_file", "(", "file_name", ",", "file_contents", ")", "contents", "=", "file_contents", ".", "flatten", ".", "select", "{", "|", "line", "|", "line", "}", ".", "join", "(", "\"\\n\"", ")", "File", ".", "open", "(", "file_name", ",", "\"w\"", ")", "do", "|", "fh", "|", "fh", ".", "write", "(", "contents", ")", "fh", ".", "write", "(", "\"\\n\"", ")", "end", "end" ]
Write an array of strings to a file, adding newline separators, and ensuring a trailing newline at the end of a file.
[ "Write", "an", "array", "of", "strings", "to", "a", "file", "adding", "newline", "separators", "and", "ensuring", "a", "trailing", "newline", "at", "the", "end", "of", "a", "file", "." ]
413bcf013de7b7c10650685f713d5131e19494a9
https://github.com/MrJoy/orderly_garden/blob/413bcf013de7b7c10650685f713d5131e19494a9/lib/orderly_garden/dsl.rb#L16-L25
train
rixth/guard-tay
lib/guard/tay.rb
Guard.Tay.munge_options
def munge_options(options) keys_to_munge = [:build_directory, :tayfile] munged = {} options.keys.each do |key| if keys_to_munge.include?(key) new_key = key.to_s.gsub(/_/, '-') end munged[new_key || key] = options[key] end munged end
ruby
def munge_options(options) keys_to_munge = [:build_directory, :tayfile] munged = {} options.keys.each do |key| if keys_to_munge.include?(key) new_key = key.to_s.gsub(/_/, '-') end munged[new_key || key] = options[key] end munged end
[ "def", "munge_options", "(", "options", ")", "keys_to_munge", "=", "[", ":build_directory", ",", ":tayfile", "]", "munged", "=", "{", "}", "options", ".", "keys", ".", "each", "do", "|", "key", "|", "if", "keys_to_munge", ".", "include?", "(", "key", ")", "new_key", "=", "key", ".", "to_s", ".", "gsub", "(", "/", "/", ",", "'-'", ")", "end", "munged", "[", "new_key", "||", "key", "]", "=", "options", "[", "key", "]", "end", "munged", "end" ]
We're using Tay's CLI helpers and they expect string optiopns with dashes, rather than symbols and underscores. So munge!
[ "We", "re", "using", "Tay", "s", "CLI", "helpers", "and", "they", "expect", "string", "optiopns", "with", "dashes", "rather", "than", "symbols", "and", "underscores", ".", "So", "munge!" ]
7441325415571c8012a537ac68bf43e5ca61501d
https://github.com/rixth/guard-tay/blob/7441325415571c8012a537ac68bf43e5ca61501d/lib/guard/tay.rb#L52-L62
train
appdrones/page_record
lib/page_record/attributes.rb
PageRecord.Attributes.read_attribute
def read_attribute(attribute) if block_given? element = yield else element = send("#{attribute}?") end tag = element.tag_name input_field?(tag) ? element.value : element.text end
ruby
def read_attribute(attribute) if block_given? element = yield else element = send("#{attribute}?") end tag = element.tag_name input_field?(tag) ? element.value : element.text end
[ "def", "read_attribute", "(", "attribute", ")", "if", "block_given?", "element", "=", "yield", "else", "element", "=", "send", "(", "\"#{attribute}?\"", ")", "end", "tag", "=", "element", ".", "tag_name", "input_field?", "(", "tag", ")", "?", "element", ".", "value", ":", "element", ".", "text", "end" ]
Searches the record for the specified attribute and returns the text content. This method is called when you access an attribute of a record @return [String] the text content of the specified attribute @raise [AttributeNotFound] when the attribute is not found in the record
[ "Searches", "the", "record", "for", "the", "specified", "attribute", "and", "returns", "the", "text", "content", ".", "This", "method", "is", "called", "when", "you", "access", "an", "attribute", "of", "a", "record" ]
2a6d285cbfab906dad6f13f66fea1c09d354b762
https://github.com/appdrones/page_record/blob/2a6d285cbfab906dad6f13f66fea1c09d354b762/lib/page_record/attributes.rb#L27-L35
train
appdrones/page_record
lib/page_record/attributes.rb
PageRecord.Attributes.write_attribute
def write_attribute(attribute, value) element = send("#{attribute}?") tag = element.tag_name case tag when 'textarea', 'input' then element.set(value) when 'select'then element.select(value) else raise NotInputField end element end
ruby
def write_attribute(attribute, value) element = send("#{attribute}?") tag = element.tag_name case tag when 'textarea', 'input' then element.set(value) when 'select'then element.select(value) else raise NotInputField end element end
[ "def", "write_attribute", "(", "attribute", ",", "value", ")", "element", "=", "send", "(", "\"#{attribute}?\"", ")", "tag", "=", "element", ".", "tag_name", "case", "tag", "when", "'textarea'", ",", "'input'", "then", "element", ".", "set", "(", "value", ")", "when", "'select'", "then", "element", ".", "select", "(", "value", ")", "else", "raise", "NotInputField", "end", "element", "end" ]
Searches the record for the specified attribute and sets the value of the attribute This method is called when you set an attribute of a record @return [Capybara::Result] the text content of the specified attribute @raise [AttributeNotFound] when the attribute is not found in the record @raise [NotInputField] when the attribute is not a `TEXTAREA` or `INPUT` tag
[ "Searches", "the", "record", "for", "the", "specified", "attribute", "and", "sets", "the", "value", "of", "the", "attribute", "This", "method", "is", "called", "when", "you", "set", "an", "attribute", "of", "a", "record" ]
2a6d285cbfab906dad6f13f66fea1c09d354b762
https://github.com/appdrones/page_record/blob/2a6d285cbfab906dad6f13f66fea1c09d354b762/lib/page_record/attributes.rb#L46-L55
train
bottiger/Blog_Basic
app/models/blog_basic/blog_comment.rb
BlogBasic.BlogComment.request=
def request=(request) self.user_ip = request.remote_ip self.user_agent = request.env['HTTP_USER_AGENT'] self.referrer = request.env['HTTP_REFERER'] end
ruby
def request=(request) self.user_ip = request.remote_ip self.user_agent = request.env['HTTP_USER_AGENT'] self.referrer = request.env['HTTP_REFERER'] end
[ "def", "request", "=", "(", "request", ")", "self", ".", "user_ip", "=", "request", ".", "remote_ip", "self", ".", "user_agent", "=", "request", ".", "env", "[", "'HTTP_USER_AGENT'", "]", "self", ".", "referrer", "=", "request", ".", "env", "[", "'HTTP_REFERER'", "]", "end" ]
Used to set more tracking for akismet
[ "Used", "to", "set", "more", "tracking", "for", "akismet" ]
9eb8fc2e7100b93bf4193ed86671c6dd1c8fc440
https://github.com/bottiger/Blog_Basic/blob/9eb8fc2e7100b93bf4193ed86671c6dd1c8fc440/app/models/blog_basic/blog_comment.rb#L72-L76
train
jarrett/ichiban
lib/ichiban/loader.rb
Ichiban.Loader.delete_all
def delete_all @loaded_constants.each do |const_name| if Object.const_defined?(const_name) Object.send(:remove_const, const_name) end end Ichiban::HTMLCompiler::Context.clear_user_defined_helpers end
ruby
def delete_all @loaded_constants.each do |const_name| if Object.const_defined?(const_name) Object.send(:remove_const, const_name) end end Ichiban::HTMLCompiler::Context.clear_user_defined_helpers end
[ "def", "delete_all", "@loaded_constants", ".", "each", "do", "|", "const_name", "|", "if", "Object", ".", "const_defined?", "(", "const_name", ")", "Object", ".", "send", "(", ":remove_const", ",", "const_name", ")", "end", "end", "Ichiban", "::", "HTMLCompiler", "::", "Context", ".", "clear_user_defined_helpers", "end" ]
Calls Object.remove_const on all tracked modules. Also clears the compiler's list of user-defined helpers.
[ "Calls", "Object", ".", "remove_const", "on", "all", "tracked", "modules", ".", "Also", "clears", "the", "compiler", "s", "list", "of", "user", "-", "defined", "helpers", "." ]
310f96b0981ea19bf01246995f3732c986915d5b
https://github.com/jarrett/ichiban/blob/310f96b0981ea19bf01246995f3732c986915d5b/lib/ichiban/loader.rb#L21-L28
train
ktonon/code_node
spec/fixtures/activerecord/src/active_record/dynamic_matchers.rb
ActiveRecord.DynamicMatchers.expand_attribute_names_for_aggregates
def expand_attribute_names_for_aggregates(attribute_names) attribute_names.map { |attribute_name| unless (aggregation = reflect_on_aggregation(attribute_name.to_sym)).nil? aggregate_mapping(aggregation).map do |field_attr, _| field_attr.to_sym end else attribute_name.to_sym end }.flatten end
ruby
def expand_attribute_names_for_aggregates(attribute_names) attribute_names.map { |attribute_name| unless (aggregation = reflect_on_aggregation(attribute_name.to_sym)).nil? aggregate_mapping(aggregation).map do |field_attr, _| field_attr.to_sym end else attribute_name.to_sym end }.flatten end
[ "def", "expand_attribute_names_for_aggregates", "(", "attribute_names", ")", "attribute_names", ".", "map", "{", "|", "attribute_name", "|", "unless", "(", "aggregation", "=", "reflect_on_aggregation", "(", "attribute_name", ".", "to_sym", ")", ")", ".", "nil?", "aggregate_mapping", "(", "aggregation", ")", ".", "map", "do", "|", "field_attr", ",", "_", "|", "field_attr", ".", "to_sym", "end", "else", "attribute_name", ".", "to_sym", "end", "}", ".", "flatten", "end" ]
Similar in purpose to +expand_hash_conditions_for_aggregates+.
[ "Similar", "in", "purpose", "to", "+", "expand_hash_conditions_for_aggregates", "+", "." ]
48d5d1a7442d9cade602be4fb782a1b56c7677f5
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/dynamic_matchers.rb#L55-L65
train
redding/sanford
bench/report.rb
Bench.Runner.build_report
def build_report output "Running benchmark report..." REQUESTS.each do |name, params, times| self.benchmark_service(name, params, times, false) end output "Done running benchmark report" end
ruby
def build_report output "Running benchmark report..." REQUESTS.each do |name, params, times| self.benchmark_service(name, params, times, false) end output "Done running benchmark report" end
[ "def", "build_report", "output", "\"Running benchmark report...\"", "REQUESTS", ".", "each", "do", "|", "name", ",", "params", ",", "times", "|", "self", ".", "benchmark_service", "(", "name", ",", "params", ",", "times", ",", "false", ")", "end", "output", "\"Done running benchmark report\"", "end" ]
4 decimal places
[ "4", "decimal", "places" ]
8153d13ac0b87e5e56eaee3fadb165a5cc6576e9
https://github.com/redding/sanford/blob/8153d13ac0b87e5e56eaee3fadb165a5cc6576e9/bench/report.rb#L24-L32
train
RobertAudi/TaskList
lib/task-list/parser.rb
TaskList.Parser.parse!
def parse! unless @type.nil? || VALID_TASKS.include?(@type) raise TaskList::Exceptions::InvalidTaskTypeError.new type: @type end @files.each { |f| parsef! file: f } end
ruby
def parse! unless @type.nil? || VALID_TASKS.include?(@type) raise TaskList::Exceptions::InvalidTaskTypeError.new type: @type end @files.each { |f| parsef! file: f } end
[ "def", "parse!", "unless", "@type", ".", "nil?", "||", "VALID_TASKS", ".", "include?", "(", "@type", ")", "raise", "TaskList", "::", "Exceptions", "::", "InvalidTaskTypeError", ".", "new", "type", ":", "@type", "end", "@files", ".", "each", "{", "|", "f", "|", "parsef!", "file", ":", "f", "}", "end" ]
Parse all the collected files to find tasks and populate the tasks hash
[ "Parse", "all", "the", "collected", "files", "to", "find", "tasks", "and", "populate", "the", "tasks", "hash" ]
98ac82f449eec7a6958f88c19c9637845eae68f2
https://github.com/RobertAudi/TaskList/blob/98ac82f449eec7a6958f88c19c9637845eae68f2/lib/task-list/parser.rb#L28-L34
train
neiljohari/scram
lib/scram/dsl/model_conditions.rb
Scram::DSL.ModelConditions.method_missing
def method_missing(method, *args) if method.to_s.starts_with? "*" condition_name = method.to_s.split("*")[1].to_sym conditions = self.class.scram_conditions if conditions && !conditions[condition_name].nil? return conditions[condition_name].call(self) end end super end
ruby
def method_missing(method, *args) if method.to_s.starts_with? "*" condition_name = method.to_s.split("*")[1].to_sym conditions = self.class.scram_conditions if conditions && !conditions[condition_name].nil? return conditions[condition_name].call(self) end end super end
[ "def", "method_missing", "(", "method", ",", "*", "args", ")", "if", "method", ".", "to_s", ".", "starts_with?", "\"*\"", "condition_name", "=", "method", ".", "to_s", ".", "split", "(", "\"*\"", ")", "[", "1", "]", ".", "to_sym", "conditions", "=", "self", ".", "class", ".", "scram_conditions", "if", "conditions", "&&", "!", "conditions", "[", "condition_name", "]", ".", "nil?", "return", "conditions", "[", "condition_name", "]", ".", "call", "(", "self", ")", "end", "end", "super", "end" ]
Methods starting with an asterisk are tested for DSL defined conditions
[ "Methods", "starting", "with", "an", "asterisk", "are", "tested", "for", "DSL", "defined", "conditions" ]
df3e48e9e9cab4b363b1370df5991319d21c256d
https://github.com/neiljohari/scram/blob/df3e48e9e9cab4b363b1370df5991319d21c256d/lib/scram/dsl/model_conditions.rb#L27-L36
train
jamesmacaulay/sprockets_rails3_backport
lib/action_view/asset_paths.rb
ActionView.AssetPaths.compute_source_path
def compute_source_path(source, dir, ext) source = rewrite_extension(source, dir, ext) if ext File.join(config.assets_dir, dir, source) end
ruby
def compute_source_path(source, dir, ext) source = rewrite_extension(source, dir, ext) if ext File.join(config.assets_dir, dir, source) end
[ "def", "compute_source_path", "(", "source", ",", "dir", ",", "ext", ")", "source", "=", "rewrite_extension", "(", "source", ",", "dir", ",", "ext", ")", "if", "ext", "File", ".", "join", "(", "config", ".", "assets_dir", ",", "dir", ",", "source", ")", "end" ]
Return the filesystem path for the source
[ "Return", "the", "filesystem", "path", "for", "the", "source" ]
243de154606be141221b5ebd4cfe75857328e08a
https://github.com/jamesmacaulay/sprockets_rails3_backport/blob/243de154606be141221b5ebd4cfe75857328e08a/lib/action_view/asset_paths.rb#L34-L37
train
imathis/jekyll-stitch-plus
lib/jekyll-stitch-plus.rb
Jekyll.StitchPlus.cleanup
def cleanup(site, stitch) files = stitch.all_files.map{ |f| File.absolute_path(f)} files.concat stitch.deleted if files.size > 0 site.static_files.clone.each do |sf| if sf.kind_of?(Jekyll::StaticFile) and files.include? sf.path site.static_files.delete(sf) end end end end
ruby
def cleanup(site, stitch) files = stitch.all_files.map{ |f| File.absolute_path(f)} files.concat stitch.deleted if files.size > 0 site.static_files.clone.each do |sf| if sf.kind_of?(Jekyll::StaticFile) and files.include? sf.path site.static_files.delete(sf) end end end end
[ "def", "cleanup", "(", "site", ",", "stitch", ")", "files", "=", "stitch", ".", "all_files", ".", "map", "{", "|", "f", "|", "File", ".", "absolute_path", "(", "f", ")", "}", "files", ".", "concat", "stitch", ".", "deleted", "if", "files", ".", "size", ">", "0", "site", ".", "static_files", ".", "clone", ".", "each", "do", "|", "sf", "|", "if", "sf", ".", "kind_of?", "(", "Jekyll", "::", "StaticFile", ")", "and", "files", ".", "include?", "sf", ".", "path", "site", ".", "static_files", ".", "delete", "(", "sf", ")", "end", "end", "end", "end" ]
Remove files from Jekyll's static_files array
[ "Remove", "files", "from", "Jekyll", "s", "static_files", "array" ]
0ffd1f7061c2b36f37bb0b175b35f15e1561eeeb
https://github.com/imathis/jekyll-stitch-plus/blob/0ffd1f7061c2b36f37bb0b175b35f15e1561eeeb/lib/jekyll-stitch-plus.rb#L54-L66
train
betaworks/slack-bot-manager
lib/slack-bot-manager/manager/tokens.rb
SlackBotManager.Tokens.get_id_from_token
def get_id_from_token(token) storage.get_all(tokens_key).each { |id, t| return id if t == token } false end
ruby
def get_id_from_token(token) storage.get_all(tokens_key).each { |id, t| return id if t == token } false end
[ "def", "get_id_from_token", "(", "token", ")", "storage", ".", "get_all", "(", "tokens_key", ")", ".", "each", "{", "|", "id", ",", "t", "|", "return", "id", "if", "t", "==", "token", "}", "false", "end" ]
Given a token, get id from tokens list
[ "Given", "a", "token", "get", "id", "from", "tokens", "list" ]
cb59bd1c80abd3ede0520017708891486f733e40
https://github.com/betaworks/slack-bot-manager/blob/cb59bd1c80abd3ede0520017708891486f733e40/lib/slack-bot-manager/manager/tokens.rb#L88-L91
train
mswart/cany
lib/cany/recipe.rb
Cany.Recipe.exec
def exec(*args) args.flatten! Cany.logger.info args.join(' ') unless system(*args) raise CommandExecutionFailed.new args end end
ruby
def exec(*args) args.flatten! Cany.logger.info args.join(' ') unless system(*args) raise CommandExecutionFailed.new args end end
[ "def", "exec", "(", "*", "args", ")", "args", ".", "flatten!", "Cany", ".", "logger", ".", "info", "args", ".", "join", "(", "' '", ")", "unless", "system", "(", "*", "args", ")", "raise", "CommandExecutionFailed", ".", "new", "args", "end", "end" ]
API to use inside the recipe @api public Run a command inside the build directory. In most cases it is not needed to call this method directly. Look at the other helper methods. The method expects as arguments the program name and additional parameters for the program. The arguments can be group with arguments, but must not: @example exec 'echo', %w(a b) exec ['echo', 'a', 'b'] exec 'echo', 'a', 'b' @raise [CommandExecutionFailed] if the executed program exists with a non-zero exit code.
[ "API", "to", "use", "inside", "the", "recipe" ]
0d2bf4d3704d4e9a222b11f6d764b57234ddf36d
https://github.com/mswart/cany/blob/0d2bf4d3704d4e9a222b11f6d764b57234ddf36d/lib/cany/recipe.rb#L69-L75
train
chocolateboy/wireless
lib/wireless/registry.rb
Wireless.Registry.factory
def factory(name, klass = nil, &block) @registry[name.to_sym] = Resolver::Factory.new(block || klass) end
ruby
def factory(name, klass = nil, &block) @registry[name.to_sym] = Resolver::Factory.new(block || klass) end
[ "def", "factory", "(", "name", ",", "klass", "=", "nil", ",", "&", "block", ")", "@registry", "[", "name", ".", "to_sym", "]", "=", "Resolver", "::", "Factory", ".", "new", "(", "block", "||", "klass", ")", "end" ]
Registers a dependency which is resolved every time its value is fetched.
[ "Registers", "a", "dependency", "which", "is", "resolved", "every", "time", "its", "value", "is", "fetched", "." ]
d764691d39d64557693ac500e2b763ed4c5bf24d
https://github.com/chocolateboy/wireless/blob/d764691d39d64557693ac500e2b763ed4c5bf24d/lib/wireless/registry.rb#L38-L40
train
chocolateboy/wireless
lib/wireless/registry.rb
Wireless.Registry.singleton
def singleton(name, klass = nil, &block) @registry[name.to_sym] = Resolver::Singleton.new(block || klass) end
ruby
def singleton(name, klass = nil, &block) @registry[name.to_sym] = Resolver::Singleton.new(block || klass) end
[ "def", "singleton", "(", "name", ",", "klass", "=", "nil", ",", "&", "block", ")", "@registry", "[", "name", ".", "to_sym", "]", "=", "Resolver", "::", "Singleton", ".", "new", "(", "block", "||", "klass", ")", "end" ]
Registers a dependency which is only resolved the first time its value is fetched. On subsequent fetches, the cached value is returned.
[ "Registers", "a", "dependency", "which", "is", "only", "resolved", "the", "first", "time", "its", "value", "is", "fetched", ".", "On", "subsequent", "fetches", "the", "cached", "value", "is", "returned", "." ]
d764691d39d64557693ac500e2b763ed4c5bf24d
https://github.com/chocolateboy/wireless/blob/d764691d39d64557693ac500e2b763ed4c5bf24d/lib/wireless/registry.rb#L50-L52
train
chocolateboy/wireless
lib/wireless/registry.rb
Wireless.Registry.mixin
def mixin(args) # normalize the supplied argument (array or hash) into a hash of # { visibility => exports } pairs, where `visibility` is a symbol and # `exports` is a hash of { dependency_name => method_name } pairs if args.is_a?(Array) args = { @default_visibility => args } elsif !args.is_a?(Hash) raise ArgumentError, "invalid mixin argument: expected array or hash, got: #{args.class}" end # slurp each array of name (symbol) or name => alias (hash) imports into # a normalized hash of { dependency_name => method_name } pairs e.g.: # # before: # # [:foo, { :bar => :baz }, :quux] # # after: # # { :foo => :foo, :bar => :baz, :quux => :quux } # XXX transform_values isn't available in ruby 2.3 and we don't want to # pull in ActiveSupport just for one method (on this occasion) # # args = DEFAULT_EXPORTS.merge(args).transform_values do |exports| # exports = [exports] unless exports.is_a?(Array) # exports.reduce({}) do |a, b| # a.merge(b.is_a?(Hash) ? b : { b => b }) # end # end args = DEFAULT_EXPORTS.merge(args).each_with_object({}) do |(key, exports), merged| exports = [exports] unless exports.is_a?(Array) merged[key] = exports.reduce({}) do |a, b| a.merge(b.is_a?(Hash) ? b : { b => b }) end end @module_cache.get!(args) { module_for(args) } end
ruby
def mixin(args) # normalize the supplied argument (array or hash) into a hash of # { visibility => exports } pairs, where `visibility` is a symbol and # `exports` is a hash of { dependency_name => method_name } pairs if args.is_a?(Array) args = { @default_visibility => args } elsif !args.is_a?(Hash) raise ArgumentError, "invalid mixin argument: expected array or hash, got: #{args.class}" end # slurp each array of name (symbol) or name => alias (hash) imports into # a normalized hash of { dependency_name => method_name } pairs e.g.: # # before: # # [:foo, { :bar => :baz }, :quux] # # after: # # { :foo => :foo, :bar => :baz, :quux => :quux } # XXX transform_values isn't available in ruby 2.3 and we don't want to # pull in ActiveSupport just for one method (on this occasion) # # args = DEFAULT_EXPORTS.merge(args).transform_values do |exports| # exports = [exports] unless exports.is_a?(Array) # exports.reduce({}) do |a, b| # a.merge(b.is_a?(Hash) ? b : { b => b }) # end # end args = DEFAULT_EXPORTS.merge(args).each_with_object({}) do |(key, exports), merged| exports = [exports] unless exports.is_a?(Array) merged[key] = exports.reduce({}) do |a, b| a.merge(b.is_a?(Hash) ? b : { b => b }) end end @module_cache.get!(args) { module_for(args) } end
[ "def", "mixin", "(", "args", ")", "if", "args", ".", "is_a?", "(", "Array", ")", "args", "=", "{", "@default_visibility", "=>", "args", "}", "elsif", "!", "args", ".", "is_a?", "(", "Hash", ")", "raise", "ArgumentError", ",", "\"invalid mixin argument: expected array or hash, got: #{args.class}\"", "end", "args", "=", "DEFAULT_EXPORTS", ".", "merge", "(", "args", ")", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "key", ",", "exports", ")", ",", "merged", "|", "exports", "=", "[", "exports", "]", "unless", "exports", ".", "is_a?", "(", "Array", ")", "merged", "[", "key", "]", "=", "exports", ".", "reduce", "(", "{", "}", ")", "do", "|", "a", ",", "b", "|", "a", ".", "merge", "(", "b", ".", "is_a?", "(", "Hash", ")", "?", "b", ":", "{", "b", "=>", "b", "}", ")", "end", "end", "@module_cache", ".", "get!", "(", "args", ")", "{", "module_for", "(", "args", ")", "}", "end" ]
Takes an array or hash specifying the dependencies to export, and returns a module which defines getters for those dependencies. class Test # hash (specify visibilities) include Services.mixin private: :foo, protected: %i[bar baz], public: :quux # or an array of imports using the default visibility (:private by default) include Services.mixin %i[foo bar baz quux] def test foo + bar + baz + quux # access the dependencies end end The visibility of the generated getters can be controlled by passing a hash with { visibility => imports } pairs, where imports is an array of import specifiers. An import specifier is a symbol (method name == dependency name) or a hash with { dependency_name => method_name } pairs (aliases). If there's only one import specifier, its enclosing array can be omitted e.g.: include Services.mixin(private: :foo, protected: { :baz => :quux }) is equivalent to: include Services.mixin(private: [:foo], protected: [{ :baz => :quux }])
[ "Takes", "an", "array", "or", "hash", "specifying", "the", "dependencies", "to", "export", "and", "returns", "a", "module", "which", "defines", "getters", "for", "those", "dependencies", "." ]
d764691d39d64557693ac500e2b763ed4c5bf24d
https://github.com/chocolateboy/wireless/blob/d764691d39d64557693ac500e2b763ed4c5bf24d/lib/wireless/registry.rb#L81-L120
train
chocolateboy/wireless
lib/wireless/registry.rb
Wireless.Registry.module_for
def module_for(args) registry = self mod = Module.new args.each do |visibility, exports| exports.each do |dependency_name, method_name| # equivalent to (e.g.): # # def foo # registry.fetch(:foo) # end mod.send(:define_method, method_name) do registry.fetch(dependency_name) end # equivalent to (e.g.): # # private :foo mod.send(visibility, method_name) end end mod end
ruby
def module_for(args) registry = self mod = Module.new args.each do |visibility, exports| exports.each do |dependency_name, method_name| # equivalent to (e.g.): # # def foo # registry.fetch(:foo) # end mod.send(:define_method, method_name) do registry.fetch(dependency_name) end # equivalent to (e.g.): # # private :foo mod.send(visibility, method_name) end end mod end
[ "def", "module_for", "(", "args", ")", "registry", "=", "self", "mod", "=", "Module", ".", "new", "args", ".", "each", "do", "|", "visibility", ",", "exports", "|", "exports", ".", "each", "do", "|", "dependency_name", ",", "method_name", "|", "mod", ".", "send", "(", ":define_method", ",", "method_name", ")", "do", "registry", ".", "fetch", "(", "dependency_name", ")", "end", "mod", ".", "send", "(", "visibility", ",", "method_name", ")", "end", "end", "mod", "end" ]
Create a module with the specified exports
[ "Create", "a", "module", "with", "the", "specified", "exports" ]
d764691d39d64557693ac500e2b763ed4c5bf24d
https://github.com/chocolateboy/wireless/blob/d764691d39d64557693ac500e2b763ed4c5bf24d/lib/wireless/registry.rb#L128-L151
train
dgjnpr/Sloe
lib/sloe/junos.rb
Sloe.Junos.cli
def cli(cmd_str, attrs = { format: 'text' }) reply = rpc.command(cmd_str, attrs) reply.respond_to?(:text) ? reply.text : reply end
ruby
def cli(cmd_str, attrs = { format: 'text' }) reply = rpc.command(cmd_str, attrs) reply.respond_to?(:text) ? reply.text : reply end
[ "def", "cli", "(", "cmd_str", ",", "attrs", "=", "{", "format", ":", "'text'", "}", ")", "reply", "=", "rpc", ".", "command", "(", "cmd_str", ",", "attrs", ")", "reply", ".", "respond_to?", "(", ":text", ")", "?", "reply", ".", "text", ":", "reply", "end" ]
execute CLI commands over NETCONF transport returns plain text, rather than XML, by default @param cmd_str [String] A valid Junos CLI command. @param attrs [Hash] Supports same attributes as {http://rubydoc.info/gems/netconf/Netconf/RPC/Junos:command Junos#command} @return nil if command returns no text. Otherwise returns text in format requested (default is plain text)
[ "execute", "CLI", "commands", "over", "NETCONF", "transport", "returns", "plain", "text", "rather", "than", "XML", "by", "default" ]
7d1b462fbd8c91e6feafa6fa64adf1ce7a78e355
https://github.com/dgjnpr/Sloe/blob/7d1b462fbd8c91e6feafa6fa64adf1ce7a78e355/lib/sloe/junos.rb#L15-L18
train
dgjnpr/Sloe
lib/sloe/junos.rb
Sloe.Junos.apply_configuration
def apply_configuration(config, attrs = { format: 'text' }) rpc.lock_configuration rpc.load_configuration(config, attrs) rpc.commit_configuration rpc.unlock_configuration end
ruby
def apply_configuration(config, attrs = { format: 'text' }) rpc.lock_configuration rpc.load_configuration(config, attrs) rpc.commit_configuration rpc.unlock_configuration end
[ "def", "apply_configuration", "(", "config", ",", "attrs", "=", "{", "format", ":", "'text'", "}", ")", "rpc", ".", "lock_configuration", "rpc", ".", "load_configuration", "(", "config", ",", "attrs", ")", "rpc", ".", "commit_configuration", "rpc", ".", "unlock_configuration", "end" ]
Simplifies applying configuration to a Junos device. Uses Junos NETCONF extensions to apply the configuration. Returns to the previous committed config if any arror occurs @param config [String] Configuration to be applied the device @param attrs [Hash] Takes same attributes as {http://rubydoc.info/gems/netconf/Netconf/RPC/Junos:load_configuration Junos#load_configuration}
[ "Simplifies", "applying", "configuration", "to", "a", "Junos", "device", ".", "Uses", "Junos", "NETCONF", "extensions", "to", "apply", "the", "configuration", ".", "Returns", "to", "the", "previous", "committed", "config", "if", "any", "arror", "occurs" ]
7d1b462fbd8c91e6feafa6fa64adf1ce7a78e355
https://github.com/dgjnpr/Sloe/blob/7d1b462fbd8c91e6feafa6fa64adf1ce7a78e355/lib/sloe/junos.rb#L27-L32
train
geekyfox/tdp
lib/tdp.rb
TDP.PatchSet.<<
def <<(patch) known_patch = @patches[patch.name] if known_patch.nil? @patches[patch.name] = patch elsif patch.content != known_patch.content raise ContradictionError, [known_patch, patch] end end
ruby
def <<(patch) known_patch = @patches[patch.name] if known_patch.nil? @patches[patch.name] = patch elsif patch.content != known_patch.content raise ContradictionError, [known_patch, patch] end end
[ "def", "<<", "(", "patch", ")", "known_patch", "=", "@patches", "[", "patch", ".", "name", "]", "if", "known_patch", ".", "nil?", "@patches", "[", "patch", ".", "name", "]", "=", "patch", "elsif", "patch", ".", "content", "!=", "known_patch", ".", "content", "raise", "ContradictionError", ",", "[", "known_patch", ",", "patch", "]", "end", "end" ]
Adds a patch to the set. Raises ContradictionError in case if patch set already contains a patch with the same name and different content. patch :: Patch object to add
[ "Adds", "a", "patch", "to", "the", "set", ".", "Raises", "ContradictionError", "in", "case", "if", "patch", "set", "already", "contains", "a", "patch", "with", "the", "same", "name", "and", "different", "content", "." ]
13718e35a4539945c0b62313194cbf458a4e9ed5
https://github.com/geekyfox/tdp/blob/13718e35a4539945c0b62313194cbf458a4e9ed5/lib/tdp.rb#L162-L169
train
geekyfox/tdp
lib/tdp.rb
TDP.DAO.patch_signature
def patch_signature(name) row = @db[:tdp_patch].select(:signature).where(name: name).first row.nil? ? nil : row[:signature] end
ruby
def patch_signature(name) row = @db[:tdp_patch].select(:signature).where(name: name).first row.nil? ? nil : row[:signature] end
[ "def", "patch_signature", "(", "name", ")", "row", "=", "@db", "[", ":tdp_patch", "]", ".", "select", "(", ":signature", ")", ".", "where", "(", "name", ":", "name", ")", ".", "first", "row", ".", "nil?", "?", "nil", ":", "row", "[", ":signature", "]", "end" ]
Looks up a signature of a patch by its name.
[ "Looks", "up", "a", "signature", "of", "a", "patch", "by", "its", "name", "." ]
13718e35a4539945c0b62313194cbf458a4e9ed5
https://github.com/geekyfox/tdp/blob/13718e35a4539945c0b62313194cbf458a4e9ed5/lib/tdp.rb#L269-L272
train
geekyfox/tdp
lib/tdp.rb
TDP.Engine.<<
def <<(filename) if File.directory?(filename) Dir.foreach(filename) do |x| self << File.join(filename, x) unless x.start_with?('.') end elsif TDP.patch_file?(filename) @patches << Patch.new(filename) end end
ruby
def <<(filename) if File.directory?(filename) Dir.foreach(filename) do |x| self << File.join(filename, x) unless x.start_with?('.') end elsif TDP.patch_file?(filename) @patches << Patch.new(filename) end end
[ "def", "<<", "(", "filename", ")", "if", "File", ".", "directory?", "(", "filename", ")", "Dir", ".", "foreach", "(", "filename", ")", "do", "|", "x", "|", "self", "<<", "File", ".", "join", "(", "filename", ",", "x", ")", "unless", "x", ".", "start_with?", "(", "'.'", ")", "end", "elsif", "TDP", ".", "patch_file?", "(", "filename", ")", "@patches", "<<", "Patch", ".", "new", "(", "filename", ")", "end", "end" ]
Creates a new Engine object. db :: must be one of: * instance of Sequel::Database class * database URL that can be passed to Sequel.connect() Registers patch files in the engine. filename :: may be either a name of .sql file or a name of directory (which would be recursively scanned for .sql files)
[ "Creates", "a", "new", "Engine", "object", "." ]
13718e35a4539945c0b62313194cbf458a4e9ed5
https://github.com/geekyfox/tdp/blob/13718e35a4539945c0b62313194cbf458a4e9ed5/lib/tdp.rb#L338-L346
train
geekyfox/tdp
lib/tdp.rb
TDP.Engine.plan
def plan ref = @dao.applied_patches @patches.select do |patch| signature = ref[patch.name] next false if signature == patch.signature next true if signature.nil? || patch.volatile? raise MismatchError, patch end end
ruby
def plan ref = @dao.applied_patches @patches.select do |patch| signature = ref[patch.name] next false if signature == patch.signature next true if signature.nil? || patch.volatile? raise MismatchError, patch end end
[ "def", "plan", "ref", "=", "@dao", ".", "applied_patches", "@patches", ".", "select", "do", "|", "patch", "|", "signature", "=", "ref", "[", "patch", ".", "name", "]", "next", "false", "if", "signature", "==", "patch", ".", "signature", "next", "true", "if", "signature", ".", "nil?", "||", "patch", ".", "volatile?", "raise", "MismatchError", ",", "patch", "end", "end" ]
Produces an ordered list of patches that need to be applied. May raise MismatchError in case if signatures of any permanent patches that are present in the definition don't match ones of the patches applied to the database.
[ "Produces", "an", "ordered", "list", "of", "patches", "that", "need", "to", "be", "applied", "." ]
13718e35a4539945c0b62313194cbf458a4e9ed5
https://github.com/geekyfox/tdp/blob/13718e35a4539945c0b62313194cbf458a4e9ed5/lib/tdp.rb#L363-L371
train
geekyfox/tdp
lib/tdp.rb
TDP.Engine.validate_compatible
def validate_compatible validate_upgradable @patches.each do |patch| signature = @dao.patch_signature(patch.name) next if signature == patch.signature raise NotAppliedError, patch if signature.nil? raise MismatchError, patch end end
ruby
def validate_compatible validate_upgradable @patches.each do |patch| signature = @dao.patch_signature(patch.name) next if signature == patch.signature raise NotAppliedError, patch if signature.nil? raise MismatchError, patch end end
[ "def", "validate_compatible", "validate_upgradable", "@patches", ".", "each", "do", "|", "patch", "|", "signature", "=", "@dao", ".", "patch_signature", "(", "patch", ".", "name", ")", "next", "if", "signature", "==", "patch", ".", "signature", "raise", "NotAppliedError", ",", "patch", "if", "signature", ".", "nil?", "raise", "MismatchError", ",", "patch", "end", "end" ]
Validates that all patches are applied to the database. May raise MismatchError, NotConfiguredError or NotAppliedError in case if there are any problems.
[ "Validates", "that", "all", "patches", "are", "applied", "to", "the", "database", "." ]
13718e35a4539945c0b62313194cbf458a4e9ed5
https://github.com/geekyfox/tdp/blob/13718e35a4539945c0b62313194cbf458a4e9ed5/lib/tdp.rb#L420-L429
train
jeremyd/virtualmonkey
lib/virtualmonkey/unified_application.rb
VirtualMonkey.UnifiedApplication.run_unified_application_check
def run_unified_application_check(dns_name, port=8000) url_base = "#{dns_name}:#{port}" behavior(:test_http_response, "html serving succeeded", "#{url_base}/index.html", port) behavior(:test_http_response, "configuration=succeeded", "#{url_base}/appserver/", port) behavior(:test_http_response, "I am in the db", "#{url_base}/dbread/", port) behavior(:test_http_response, "hostname=", "#{url_base}/serverid/", port) end
ruby
def run_unified_application_check(dns_name, port=8000) url_base = "#{dns_name}:#{port}" behavior(:test_http_response, "html serving succeeded", "#{url_base}/index.html", port) behavior(:test_http_response, "configuration=succeeded", "#{url_base}/appserver/", port) behavior(:test_http_response, "I am in the db", "#{url_base}/dbread/", port) behavior(:test_http_response, "hostname=", "#{url_base}/serverid/", port) end
[ "def", "run_unified_application_check", "(", "dns_name", ",", "port", "=", "8000", ")", "url_base", "=", "\"#{dns_name}:#{port}\"", "behavior", "(", ":test_http_response", ",", "\"html serving succeeded\"", ",", "\"#{url_base}/index.html\"", ",", "port", ")", "behavior", "(", ":test_http_response", ",", "\"configuration=succeeded\"", ",", "\"#{url_base}/appserver/\"", ",", "port", ")", "behavior", "(", ":test_http_response", ",", "\"I am in the db\"", ",", "\"#{url_base}/dbread/\"", ",", "port", ")", "behavior", "(", ":test_http_response", ",", "\"hostname=\"", ",", "\"#{url_base}/serverid/\"", ",", "port", ")", "end" ]
this is where ALL the generic application server checks live, this could get rather long but for now it's a single method with a sequence of checks
[ "this", "is", "where", "ALL", "the", "generic", "application", "server", "checks", "live", "this", "could", "get", "rather", "long", "but", "for", "now", "it", "s", "a", "single", "method", "with", "a", "sequence", "of", "checks" ]
b2c7255f20ac5ec881eb90afbb5e712160db0dcb
https://github.com/jeremyd/virtualmonkey/blob/b2c7255f20ac5ec881eb90afbb5e712160db0dcb/lib/virtualmonkey/unified_application.rb#L31-L37
train
seblindberg/ruby-adam6050
lib/adam6050/session.rb
ADAM6050.Session.validate!
def validate!(sender, time: monotonic_timestamp) key = session_key sender last_observed = @session.fetch(key) { raise UnknownSender, sender } raise InvalidSender, sender if expired? last_observed, time, @timeout @session[key] = time nil end
ruby
def validate!(sender, time: monotonic_timestamp) key = session_key sender last_observed = @session.fetch(key) { raise UnknownSender, sender } raise InvalidSender, sender if expired? last_observed, time, @timeout @session[key] = time nil end
[ "def", "validate!", "(", "sender", ",", "time", ":", "monotonic_timestamp", ")", "key", "=", "session_key", "sender", "last_observed", "=", "@session", ".", "fetch", "(", "key", ")", "{", "raise", "UnknownSender", ",", "sender", "}", "raise", "InvalidSender", ",", "sender", "if", "expired?", "last_observed", ",", "time", ",", "@timeout", "@session", "[", "key", "]", "=", "time", "nil", "end" ]
Renews the given sender if it is still valid within the session and raises an exception otherwise. @raise [UnknownSender] if the given sender is not registered. @raise [InvalidSender] if the given sender is not valid. @param sender [Socket::UDPSource] the udp client. @param time [Numeric] the current time. The current time will be used if not specified. @return [nil]
[ "Renews", "the", "given", "sender", "if", "it", "is", "still", "valid", "within", "the", "session", "and", "raises", "an", "exception", "otherwise", "." ]
7a8e8c344cc770b25d18ddf43f105d0f19e14d50
https://github.com/seblindberg/ruby-adam6050/blob/7a8e8c344cc770b25d18ddf43f105d0f19e14d50/lib/adam6050/session.rb#L98-L105
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/tags_controller.rb
LatoBlog.Back::TagsController.new
def new core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:tags_new]) @tag = LatoBlog::Tag.new if params[:language] set_current_language params[:language] end if params[:parent] @tag_parent = LatoBlog::TagParent.find_by(id: params[:parent]) end end
ruby
def new core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:tags_new]) @tag = LatoBlog::Tag.new if params[:language] set_current_language params[:language] end if params[:parent] @tag_parent = LatoBlog::TagParent.find_by(id: params[:parent]) end end
[ "def", "new", "core__set_header_active_page_title", "(", "LANGUAGES", "[", ":lato_blog", "]", "[", ":pages", "]", "[", ":tags_new", "]", ")", "@tag", "=", "LatoBlog", "::", "Tag", ".", "new", "if", "params", "[", ":language", "]", "set_current_language", "params", "[", ":language", "]", "end", "if", "params", "[", ":parent", "]", "@tag_parent", "=", "LatoBlog", "::", "TagParent", ".", "find_by", "(", "id", ":", "params", "[", ":parent", "]", ")", "end", "end" ]
This function shows the view to create a new tag.
[ "This", "function", "shows", "the", "view", "to", "create", "a", "new", "tag", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/tags_controller.rb#L27-L38
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/tags_controller.rb
LatoBlog.Back::TagsController.create
def create @tag = LatoBlog::Tag.new(new_tag_params) if [email protected] flash[:danger] = @tag.errors.full_messages.to_sentence redirect_to lato_blog.new_tag_path return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:tag_create_success] redirect_to lato_blog.tag_path(@tag.id) end
ruby
def create @tag = LatoBlog::Tag.new(new_tag_params) if [email protected] flash[:danger] = @tag.errors.full_messages.to_sentence redirect_to lato_blog.new_tag_path return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:tag_create_success] redirect_to lato_blog.tag_path(@tag.id) end
[ "def", "create", "@tag", "=", "LatoBlog", "::", "Tag", ".", "new", "(", "new_tag_params", ")", "if", "!", "@tag", ".", "save", "flash", "[", ":danger", "]", "=", "@tag", ".", "errors", ".", "full_messages", ".", "to_sentence", "redirect_to", "lato_blog", ".", "new_tag_path", "return", "end", "flash", "[", ":success", "]", "=", "LANGUAGES", "[", ":lato_blog", "]", "[", ":flashes", "]", "[", ":tag_create_success", "]", "redirect_to", "lato_blog", ".", "tag_path", "(", "@tag", ".", "id", ")", "end" ]
This function creates a new tag.
[ "This", "function", "creates", "a", "new", "tag", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/tags_controller.rb#L41-L52
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/tags_controller.rb
LatoBlog.Back::TagsController.edit
def edit core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:tags_edit]) @tag = LatoBlog::Tag.find_by(id: params[:id]) return unless check_tag_presence if @tag.meta_language != cookies[:lato_blog__current_language] set_current_language @tag.meta_language end end
ruby
def edit core__set_header_active_page_title(LANGUAGES[:lato_blog][:pages][:tags_edit]) @tag = LatoBlog::Tag.find_by(id: params[:id]) return unless check_tag_presence if @tag.meta_language != cookies[:lato_blog__current_language] set_current_language @tag.meta_language end end
[ "def", "edit", "core__set_header_active_page_title", "(", "LANGUAGES", "[", ":lato_blog", "]", "[", ":pages", "]", "[", ":tags_edit", "]", ")", "@tag", "=", "LatoBlog", "::", "Tag", ".", "find_by", "(", "id", ":", "params", "[", ":id", "]", ")", "return", "unless", "check_tag_presence", "if", "@tag", ".", "meta_language", "!=", "cookies", "[", ":lato_blog__current_language", "]", "set_current_language", "@tag", ".", "meta_language", "end", "end" ]
This function show the view to edit a tag.
[ "This", "function", "show", "the", "view", "to", "edit", "a", "tag", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/tags_controller.rb#L55-L63
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/tags_controller.rb
LatoBlog.Back::TagsController.update
def update @tag = LatoBlog::Tag.find_by(id: params[:id]) return unless check_tag_presence if [email protected](edit_tag_params) flash[:danger] = @tag.errors.full_messages.to_sentence redirect_to lato_blog.edit_tag_path(@tag.id) return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:tag_update_success] redirect_to lato_blog.tag_path(@tag.id) end
ruby
def update @tag = LatoBlog::Tag.find_by(id: params[:id]) return unless check_tag_presence if [email protected](edit_tag_params) flash[:danger] = @tag.errors.full_messages.to_sentence redirect_to lato_blog.edit_tag_path(@tag.id) return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:tag_update_success] redirect_to lato_blog.tag_path(@tag.id) end
[ "def", "update", "@tag", "=", "LatoBlog", "::", "Tag", ".", "find_by", "(", "id", ":", "params", "[", ":id", "]", ")", "return", "unless", "check_tag_presence", "if", "!", "@tag", ".", "update", "(", "edit_tag_params", ")", "flash", "[", ":danger", "]", "=", "@tag", ".", "errors", ".", "full_messages", ".", "to_sentence", "redirect_to", "lato_blog", ".", "edit_tag_path", "(", "@tag", ".", "id", ")", "return", "end", "flash", "[", ":success", "]", "=", "LANGUAGES", "[", ":lato_blog", "]", "[", ":flashes", "]", "[", ":tag_update_success", "]", "redirect_to", "lato_blog", ".", "tag_path", "(", "@tag", ".", "id", ")", "end" ]
This function updates a tag.
[ "This", "function", "updates", "a", "tag", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/tags_controller.rb#L66-L78
train
ideonetwork/lato-blog
app/controllers/lato_blog/back/tags_controller.rb
LatoBlog.Back::TagsController.destroy
def destroy @tag = LatoBlog::Tag.find_by(id: params[:id]) return unless check_tag_presence if [email protected] flash[:danger] = @tag.tag_parent.errors.full_messages.to_sentence redirect_to lato_blog.edit_tag_path(@tag.id) return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:tag_destroy_success] redirect_to lato_blog.categories_path(status: 'deleted') end
ruby
def destroy @tag = LatoBlog::Tag.find_by(id: params[:id]) return unless check_tag_presence if [email protected] flash[:danger] = @tag.tag_parent.errors.full_messages.to_sentence redirect_to lato_blog.edit_tag_path(@tag.id) return end flash[:success] = LANGUAGES[:lato_blog][:flashes][:tag_destroy_success] redirect_to lato_blog.categories_path(status: 'deleted') end
[ "def", "destroy", "@tag", "=", "LatoBlog", "::", "Tag", ".", "find_by", "(", "id", ":", "params", "[", ":id", "]", ")", "return", "unless", "check_tag_presence", "if", "!", "@tag", ".", "destroy", "flash", "[", ":danger", "]", "=", "@tag", ".", "tag_parent", ".", "errors", ".", "full_messages", ".", "to_sentence", "redirect_to", "lato_blog", ".", "edit_tag_path", "(", "@tag", ".", "id", ")", "return", "end", "flash", "[", ":success", "]", "=", "LANGUAGES", "[", ":lato_blog", "]", "[", ":flashes", "]", "[", ":tag_destroy_success", "]", "redirect_to", "lato_blog", ".", "categories_path", "(", "status", ":", "'deleted'", ")", "end" ]
This function destroyes a tag.
[ "This", "function", "destroyes", "a", "tag", "." ]
a0d92de299a0e285851743b9d4a902f611187cba
https://github.com/ideonetwork/lato-blog/blob/a0d92de299a0e285851743b9d4a902f611187cba/app/controllers/lato_blog/back/tags_controller.rb#L81-L93
train
mixflame/Hokkaido
lib/gem_modifier.rb
Hokkaido.GemModifier.parse_gem
def parse_gem(init_lib) # puts "Processing: #{init_lib}" # don't ask init_path = init_lib init_file = File.read(init_lib) current_file = "" init_file.each_line do |line| if line.strip =~ /^require/ parser = RubyParser.new sexp = parser.parse(line) call = sexp[2] unless call == :require # WEIRD SHIT IS HAPPENING current_file += line next end require_type = sexp[3][1][0] library = sexp[3][1][1] #p library if require_type == :str && library.match(@gem_name) # fold in full_rb_path = File.join([@lib_folder, "#{library}.rb"]) unless @require_libs.include?(full_rb_path) file_index = @require_libs.index(init_lib) insert_index = file_index @require_libs.insert insert_index, full_rb_path parse_gem(full_rb_path) end else current_file += "# FIXME: #require is not supported in RubyMotion\n" current_file += "# #{line}" next end # comment it out current_file += "# #{line}" next elsif line.strip =~ /^autoload/ # same as require parser = RubyParser.new sexp = parser.parse(line) call = sexp[2] unless call == :autoload # WEIRD SHIT IS HAPPENING current_file += line next end require_type = sexp[3][2][0] library = sexp[3][2][1] full_rb_path = File.join([@lib_folder, "#{library}.rb"]) unless @require_libs.include?(full_rb_path) file_index = @require_libs.index(init_lib) insert_index = file_index @require_libs.insert insert_index, full_rb_path parse_gem(full_rb_path) end # comment it out current_file += "# #{line}" next elsif line.strip =~ /^eval/ # reprint as a block # parser = RubyParser.new # sexp = parser.parse(line) # code_str = sexp[3][1][1] # new_eval = "eval do\n #{code_str}\nend\n" # current_file += "#{new_eval}" # next # produce a fixme current_file += "# FIXME: Cannot eval strings in RubyMotion. \n" current_file += "# Rewrite to use a block.. inbuilt hack will run \n" current_file += "# Change this: \n" current_file += "# eval %Q{ \n" current_file += '# def #{c}(string = nil) ' + "\n" current_file += "# To this \n" current_file += "# eval do \n" current_file += "# define_method(c) do |string| \n" current_file += "#{line}" next elsif line.strip =~ /^binding/ current_file += "# FIXME: binding is not supported in RubyMotion.\n" current_file += "#{line}" next end # dont intefere current_file += line end # replace file File.open(init_lib, 'w') {|f| f.write(current_file) } #unless TEST_MODE end
ruby
def parse_gem(init_lib) # puts "Processing: #{init_lib}" # don't ask init_path = init_lib init_file = File.read(init_lib) current_file = "" init_file.each_line do |line| if line.strip =~ /^require/ parser = RubyParser.new sexp = parser.parse(line) call = sexp[2] unless call == :require # WEIRD SHIT IS HAPPENING current_file += line next end require_type = sexp[3][1][0] library = sexp[3][1][1] #p library if require_type == :str && library.match(@gem_name) # fold in full_rb_path = File.join([@lib_folder, "#{library}.rb"]) unless @require_libs.include?(full_rb_path) file_index = @require_libs.index(init_lib) insert_index = file_index @require_libs.insert insert_index, full_rb_path parse_gem(full_rb_path) end else current_file += "# FIXME: #require is not supported in RubyMotion\n" current_file += "# #{line}" next end # comment it out current_file += "# #{line}" next elsif line.strip =~ /^autoload/ # same as require parser = RubyParser.new sexp = parser.parse(line) call = sexp[2] unless call == :autoload # WEIRD SHIT IS HAPPENING current_file += line next end require_type = sexp[3][2][0] library = sexp[3][2][1] full_rb_path = File.join([@lib_folder, "#{library}.rb"]) unless @require_libs.include?(full_rb_path) file_index = @require_libs.index(init_lib) insert_index = file_index @require_libs.insert insert_index, full_rb_path parse_gem(full_rb_path) end # comment it out current_file += "# #{line}" next elsif line.strip =~ /^eval/ # reprint as a block # parser = RubyParser.new # sexp = parser.parse(line) # code_str = sexp[3][1][1] # new_eval = "eval do\n #{code_str}\nend\n" # current_file += "#{new_eval}" # next # produce a fixme current_file += "# FIXME: Cannot eval strings in RubyMotion. \n" current_file += "# Rewrite to use a block.. inbuilt hack will run \n" current_file += "# Change this: \n" current_file += "# eval %Q{ \n" current_file += '# def #{c}(string = nil) ' + "\n" current_file += "# To this \n" current_file += "# eval do \n" current_file += "# define_method(c) do |string| \n" current_file += "#{line}" next elsif line.strip =~ /^binding/ current_file += "# FIXME: binding is not supported in RubyMotion.\n" current_file += "#{line}" next end # dont intefere current_file += line end # replace file File.open(init_lib, 'w') {|f| f.write(current_file) } #unless TEST_MODE end
[ "def", "parse_gem", "(", "init_lib", ")", "init_path", "=", "init_lib", "init_file", "=", "File", ".", "read", "(", "init_lib", ")", "current_file", "=", "\"\"", "init_file", ".", "each_line", "do", "|", "line", "|", "if", "line", ".", "strip", "=~", "/", "/", "parser", "=", "RubyParser", ".", "new", "sexp", "=", "parser", ".", "parse", "(", "line", ")", "call", "=", "sexp", "[", "2", "]", "unless", "call", "==", ":require", "current_file", "+=", "line", "next", "end", "require_type", "=", "sexp", "[", "3", "]", "[", "1", "]", "[", "0", "]", "library", "=", "sexp", "[", "3", "]", "[", "1", "]", "[", "1", "]", "if", "require_type", "==", ":str", "&&", "library", ".", "match", "(", "@gem_name", ")", "full_rb_path", "=", "File", ".", "join", "(", "[", "@lib_folder", ",", "\"#{library}.rb\"", "]", ")", "unless", "@require_libs", ".", "include?", "(", "full_rb_path", ")", "file_index", "=", "@require_libs", ".", "index", "(", "init_lib", ")", "insert_index", "=", "file_index", "@require_libs", ".", "insert", "insert_index", ",", "full_rb_path", "parse_gem", "(", "full_rb_path", ")", "end", "else", "current_file", "+=", "\"# FIXME: #require is not supported in RubyMotion\\n\"", "current_file", "+=", "\"# #{line}\"", "next", "end", "current_file", "+=", "\"# #{line}\"", "next", "elsif", "line", ".", "strip", "=~", "/", "/", "parser", "=", "RubyParser", ".", "new", "sexp", "=", "parser", ".", "parse", "(", "line", ")", "call", "=", "sexp", "[", "2", "]", "unless", "call", "==", ":autoload", "current_file", "+=", "line", "next", "end", "require_type", "=", "sexp", "[", "3", "]", "[", "2", "]", "[", "0", "]", "library", "=", "sexp", "[", "3", "]", "[", "2", "]", "[", "1", "]", "full_rb_path", "=", "File", ".", "join", "(", "[", "@lib_folder", ",", "\"#{library}.rb\"", "]", ")", "unless", "@require_libs", ".", "include?", "(", "full_rb_path", ")", "file_index", "=", "@require_libs", ".", "index", "(", "init_lib", ")", "insert_index", "=", "file_index", "@require_libs", ".", "insert", "insert_index", ",", "full_rb_path", "parse_gem", "(", "full_rb_path", ")", "end", "current_file", "+=", "\"# #{line}\"", "next", "elsif", "line", ".", "strip", "=~", "/", "/", "current_file", "+=", "\"# FIXME: Cannot eval strings in RubyMotion. \\n\"", "current_file", "+=", "\"# Rewrite to use a block.. inbuilt hack will run \\n\"", "current_file", "+=", "\"# Change this: \\n\"", "current_file", "+=", "\"# eval %Q{ \\n\"", "current_file", "+=", "'# def #{c}(string = nil) '", "+", "\"\\n\"", "current_file", "+=", "\"# To this \\n\"", "current_file", "+=", "\"# eval do \\n\"", "current_file", "+=", "\"# define_method(c) do |string| \\n\"", "current_file", "+=", "\"#{line}\"", "next", "elsif", "line", ".", "strip", "=~", "/", "/", "current_file", "+=", "\"# FIXME: binding is not supported in RubyMotion.\\n\"", "current_file", "+=", "\"#{line}\"", "next", "end", "current_file", "+=", "line", "end", "File", ".", "open", "(", "init_lib", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "write", "(", "current_file", ")", "}", "end" ]
def simulate! puts "simulator not implemented..." end
[ "def", "simulate!", "puts", "simulator", "not", "implemented", "...", "end" ]
bf21e7915044576ef74495ccd70d7ff5ee1bcd4b
https://github.com/mixflame/Hokkaido/blob/bf21e7915044576ef74495ccd70d7ff5ee1bcd4b/lib/gem_modifier.rb#L54-L156
train
ashiksp/smart_que
lib/smart_que/consumers/base.rb
Consumers.Base.start
def start channel.prefetch(10) queue.subscribe(manual_ack: true, exclusive: false) do |delivery_info, metadata, payload| begin body = JSON.parse(payload).with_indifferent_access status = run(body) rescue => e status = :error end if status == :ok channel.ack(delivery_info.delivery_tag) elsif status == :retry channel.reject(delivery_info.delivery_tag, true) else # :error, nil etc channel.reject(delivery_info.delivery_tag, false) end end wait_for_threads end
ruby
def start channel.prefetch(10) queue.subscribe(manual_ack: true, exclusive: false) do |delivery_info, metadata, payload| begin body = JSON.parse(payload).with_indifferent_access status = run(body) rescue => e status = :error end if status == :ok channel.ack(delivery_info.delivery_tag) elsif status == :retry channel.reject(delivery_info.delivery_tag, true) else # :error, nil etc channel.reject(delivery_info.delivery_tag, false) end end wait_for_threads end
[ "def", "start", "channel", ".", "prefetch", "(", "10", ")", "queue", ".", "subscribe", "(", "manual_ack", ":", "true", ",", "exclusive", ":", "false", ")", "do", "|", "delivery_info", ",", "metadata", ",", "payload", "|", "begin", "body", "=", "JSON", ".", "parse", "(", "payload", ")", ".", "with_indifferent_access", "status", "=", "run", "(", "body", ")", "rescue", "=>", "e", "status", "=", ":error", "end", "if", "status", "==", ":ok", "channel", ".", "ack", "(", "delivery_info", ".", "delivery_tag", ")", "elsif", "status", "==", ":retry", "channel", ".", "reject", "(", "delivery_info", ".", "delivery_tag", ",", "true", ")", "else", "channel", ".", "reject", "(", "delivery_info", ".", "delivery_tag", ",", "false", ")", "end", "end", "wait_for_threads", "end" ]
Method which kick start the consumer process thread
[ "Method", "which", "kick", "start", "the", "consumer", "process", "thread" ]
3b16451e38c430f05c0ac5fb111cfc96e4dc34b8
https://github.com/ashiksp/smart_que/blob/3b16451e38c430f05c0ac5fb111cfc96e4dc34b8/lib/smart_que/consumers/base.rb#L40-L60
train
tmcarthur/DAF
lib/daf/configurable.rb
DAF.Configurable.process_options
def process_options(options) options.each do |key, value| key = key.to_s fail OptionException, "No Option #{key}" unless self.class.options[key] opt = send("#{key}") opt.value = value fail OptionException, "Bad value for option #{key}" unless opt.valid? end validate_required_options end
ruby
def process_options(options) options.each do |key, value| key = key.to_s fail OptionException, "No Option #{key}" unless self.class.options[key] opt = send("#{key}") opt.value = value fail OptionException, "Bad value for option #{key}" unless opt.valid? end validate_required_options end
[ "def", "process_options", "(", "options", ")", "options", ".", "each", "do", "|", "key", ",", "value", "|", "key", "=", "key", ".", "to_s", "fail", "OptionException", ",", "\"No Option #{key}\"", "unless", "self", ".", "class", ".", "options", "[", "key", "]", "opt", "=", "send", "(", "\"#{key}\"", ")", "opt", ".", "value", "=", "value", "fail", "OptionException", ",", "\"Bad value for option #{key}\"", "unless", "opt", ".", "valid?", "end", "validate_required_options", "end" ]
Processes given parameter into the defined options previously declared includes validation for types and any custom validators delcared @param [Hash<String,Object>] Hash of option name/value pairs, values must conform to validation rules for options or exception will be raised
[ "Processes", "given", "parameter", "into", "the", "defined", "options", "previously", "declared", "includes", "validation", "for", "types", "and", "any", "custom", "validators", "delcared" ]
e88d67ec123cc911131dbc74d33735378224703b
https://github.com/tmcarthur/DAF/blob/e88d67ec123cc911131dbc74d33735378224703b/lib/daf/configurable.rb#L13-L22
train
PeterCamilleri/pause_output
lib/pause_output/output_pager.rb
PauseOutput.OutputPager.write
def write(str) while !str.empty? pre,mid,str = str.partition("\n") write_str(pre) unless pre.empty? writeln unless mid.empty? end end
ruby
def write(str) while !str.empty? pre,mid,str = str.partition("\n") write_str(pre) unless pre.empty? writeln unless mid.empty? end end
[ "def", "write", "(", "str", ")", "while", "!", "str", ".", "empty?", "pre", ",", "mid", ",", "str", "=", "str", ".", "partition", "(", "\"\\n\"", ")", "write_str", "(", "pre", ")", "unless", "pre", ".", "empty?", "writeln", "unless", "mid", ".", "empty?", "end", "end" ]
Set up the initial values. Write out a general string with page pauses.
[ "Set", "up", "the", "initial", "values", ".", "Write", "out", "a", "general", "string", "with", "page", "pauses", "." ]
60bcf8e0f386543aba7f3274714d877168f7cf28
https://github.com/PeterCamilleri/pause_output/blob/60bcf8e0f386543aba7f3274714d877168f7cf28/lib/pause_output/output_pager.rb#L18-L24
train
PeterCamilleri/pause_output
lib/pause_output/output_pager.rb
PauseOutput.OutputPager.write_str
def write_str(str) loop do len = str.length if @chars + len < chars_per_line $pause_output_out.write(str) @chars += len return else tipping_point = chars_per_line - @chars $pause_output_out.write(str[0, tipping_point]) count_lines str = (str[tipping_point..-1]) end end end
ruby
def write_str(str) loop do len = str.length if @chars + len < chars_per_line $pause_output_out.write(str) @chars += len return else tipping_point = chars_per_line - @chars $pause_output_out.write(str[0, tipping_point]) count_lines str = (str[tipping_point..-1]) end end end
[ "def", "write_str", "(", "str", ")", "loop", "do", "len", "=", "str", ".", "length", "if", "@chars", "+", "len", "<", "chars_per_line", "$pause_output_out", ".", "write", "(", "str", ")", "@chars", "+=", "len", "return", "else", "tipping_point", "=", "chars_per_line", "-", "@chars", "$pause_output_out", ".", "write", "(", "str", "[", "0", ",", "tipping_point", "]", ")", "count_lines", "str", "=", "(", "str", "[", "tipping_point", "..", "-", "1", "]", ")", "end", "end", "end" ]
Write out a simple string with no embedded new-lines.
[ "Write", "out", "a", "simple", "string", "with", "no", "embedded", "new", "-", "lines", "." ]
60bcf8e0f386543aba7f3274714d877168f7cf28
https://github.com/PeterCamilleri/pause_output/blob/60bcf8e0f386543aba7f3274714d877168f7cf28/lib/pause_output/output_pager.rb#L34-L50
train
PeterCamilleri/pause_output
lib/pause_output/output_pager.rb
PauseOutput.OutputPager.pause
def pause msg = pause_message $pause_output_out.write(msg) MiniTerm.raw do |term| result = term.get_raw_char term.flush result end ensure $pause_output_out.write("\r" + " " * msg.length + "\r") end
ruby
def pause msg = pause_message $pause_output_out.write(msg) MiniTerm.raw do |term| result = term.get_raw_char term.flush result end ensure $pause_output_out.write("\r" + " " * msg.length + "\r") end
[ "def", "pause", "msg", "=", "pause_message", "$pause_output_out", ".", "write", "(", "msg", ")", "MiniTerm", ".", "raw", "do", "|", "term", "|", "result", "=", "term", ".", "get_raw_char", "term", ".", "flush", "result", "end", "ensure", "$pause_output_out", ".", "write", "(", "\"\\r\"", "+", "\" \"", "*", "msg", ".", "length", "+", "\"\\r\"", ")", "end" ]
Pause waiting for the user.
[ "Pause", "waiting", "for", "the", "user", "." ]
60bcf8e0f386543aba7f3274714d877168f7cf28
https://github.com/PeterCamilleri/pause_output/blob/60bcf8e0f386543aba7f3274714d877168f7cf28/lib/pause_output/output_pager.rb#L77-L89
train
evilmarty/internode.rb
lib/internode/account.rb
Internode.Account.concurrent_map
def concurrent_map threads = services.map{|s| Thread.new{ yield s } } threads.each(&:join) threads.map(&:value) end
ruby
def concurrent_map threads = services.map{|s| Thread.new{ yield s } } threads.each(&:join) threads.map(&:value) end
[ "def", "concurrent_map", "threads", "=", "services", ".", "map", "{", "|", "s", "|", "Thread", ".", "new", "{", "yield", "s", "}", "}", "threads", ".", "each", "(", "&", ":join", ")", "threads", ".", "map", "(", "&", ":value", ")", "end" ]
Used to allow performing API requests in parallal instead of series
[ "Used", "to", "allow", "performing", "API", "requests", "in", "parallal", "instead", "of", "series" ]
6107c4a3b5f7f05edf2fdfe5daa987113b2050a7
https://github.com/evilmarty/internode.rb/blob/6107c4a3b5f7f05edf2fdfe5daa987113b2050a7/lib/internode/account.rb#L28-L32
train
dlindahl/network_executive
lib/network_executive/program_schedule.rb
NetworkExecutive.ProgramSchedule.occurrence_at
def occurrence_at( time ) real_duration = duration - 1 range = [ time - real_duration, time ] start_time = proxy.occurrences_between( range[0], range[1] ).first end_time = start_time + real_duration Occurrence.new start_time, real_duration, end_time end
ruby
def occurrence_at( time ) real_duration = duration - 1 range = [ time - real_duration, time ] start_time = proxy.occurrences_between( range[0], range[1] ).first end_time = start_time + real_duration Occurrence.new start_time, real_duration, end_time end
[ "def", "occurrence_at", "(", "time", ")", "real_duration", "=", "duration", "-", "1", "range", "=", "[", "time", "-", "real_duration", ",", "time", "]", "start_time", "=", "proxy", ".", "occurrences_between", "(", "range", "[", "0", "]", ",", "range", "[", "1", "]", ")", ".", "first", "end_time", "=", "start_time", "+", "real_duration", "Occurrence", ".", "new", "start_time", ",", "real_duration", ",", "end_time", "end" ]
Returns the scheduled occurrence that matches the specified time
[ "Returns", "the", "scheduled", "occurrence", "that", "matches", "the", "specified", "time" ]
4802e8b20225d7058c82f5ded05bfa6c84918e3d
https://github.com/dlindahl/network_executive/blob/4802e8b20225d7058c82f5ded05bfa6c84918e3d/lib/network_executive/program_schedule.rb#L56-L65
train
Nauktis/nauktis_utils
lib/nauktis_utils/duplicate.rb
NauktisUtils.Duplicate.files_in
def files_in(directories) files = [] Find.find(*directories) do |path| unless File.directory?(path) or File.symlink?(path) files << File.expand_path(path) end end files.uniq end
ruby
def files_in(directories) files = [] Find.find(*directories) do |path| unless File.directory?(path) or File.symlink?(path) files << File.expand_path(path) end end files.uniq end
[ "def", "files_in", "(", "directories", ")", "files", "=", "[", "]", "Find", ".", "find", "(", "*", "directories", ")", "do", "|", "path", "|", "unless", "File", ".", "directory?", "(", "path", ")", "or", "File", ".", "symlink?", "(", "path", ")", "files", "<<", "File", ".", "expand_path", "(", "path", ")", "end", "end", "files", ".", "uniq", "end" ]
Returns the list of files in the directories provided
[ "Returns", "the", "list", "of", "files", "in", "the", "directories", "provided" ]
10e2a8ae558484a95ab61b8ee0a15f3e68b94b1c
https://github.com/Nauktis/nauktis_utils/blob/10e2a8ae558484a95ab61b8ee0a15f3e68b94b1c/lib/nauktis_utils/duplicate.rb#L176-L184
train
Nauktis/nauktis_utils
lib/nauktis_utils/duplicate.rb
NauktisUtils.Duplicate.size_of
def size_of(directories) size = 0 files_in(directories).each do |f| size += File.size(f) end size end
ruby
def size_of(directories) size = 0 files_in(directories).each do |f| size += File.size(f) end size end
[ "def", "size_of", "(", "directories", ")", "size", "=", "0", "files_in", "(", "directories", ")", ".", "each", "do", "|", "f", "|", "size", "+=", "File", ".", "size", "(", "f", ")", "end", "size", "end" ]
Returns the total size of the directories provided
[ "Returns", "the", "total", "size", "of", "the", "directories", "provided" ]
10e2a8ae558484a95ab61b8ee0a15f3e68b94b1c
https://github.com/Nauktis/nauktis_utils/blob/10e2a8ae558484a95ab61b8ee0a15f3e68b94b1c/lib/nauktis_utils/duplicate.rb#L187-L193
train
jeremyd/virtualmonkey
lib/virtualmonkey/mysql.rb
VirtualMonkey.Mysql.setup_dns
def setup_dns(domain) # TODO should we just use the ID instead of the full href? [email protected] @dns = SharedDns.new(domain) raise "Unable to reserve DNS" unless @dns.reserve_dns(owner) @dns.set_dns_inputs(@deployment) end
ruby
def setup_dns(domain) # TODO should we just use the ID instead of the full href? [email protected] @dns = SharedDns.new(domain) raise "Unable to reserve DNS" unless @dns.reserve_dns(owner) @dns.set_dns_inputs(@deployment) end
[ "def", "setup_dns", "(", "domain", ")", "owner", "=", "@deployment", ".", "href", "@dns", "=", "SharedDns", ".", "new", "(", "domain", ")", "raise", "\"Unable to reserve DNS\"", "unless", "@dns", ".", "reserve_dns", "(", "owner", ")", "@dns", ".", "set_dns_inputs", "(", "@deployment", ")", "end" ]
uses SharedDns to find an available set of DNS records and sets them on the deployment
[ "uses", "SharedDns", "to", "find", "an", "available", "set", "of", "DNS", "records", "and", "sets", "them", "on", "the", "deployment" ]
b2c7255f20ac5ec881eb90afbb5e712160db0dcb
https://github.com/jeremyd/virtualmonkey/blob/b2c7255f20ac5ec881eb90afbb5e712160db0dcb/lib/virtualmonkey/mysql.rb#L113-L119
train
talyric/pvcglue
lib/pvcglue/cloud.rb
Pvcglue.Cloud.find_minion_by_name
def find_minion_by_name(minion_name, raise_error = true) # raise(Thor::Error, "Node not specified.") if node_name.nil? || node_name.empty? raise('Minion not specified.') if minion_name.nil? || minion_name.empty? return {minion_name => minions_filtered[minion_name]} if minions[minion_name] minions.each do |key, value| return {key => value} if key.start_with?(minion_name) end raise("Not found: #{minion_name} in #{stage_name}.") if raise_error # raise(Thor::Error, "Not found: #{node_name} in #{stage_name}.") nil end
ruby
def find_minion_by_name(minion_name, raise_error = true) # raise(Thor::Error, "Node not specified.") if node_name.nil? || node_name.empty? raise('Minion not specified.') if minion_name.nil? || minion_name.empty? return {minion_name => minions_filtered[minion_name]} if minions[minion_name] minions.each do |key, value| return {key => value} if key.start_with?(minion_name) end raise("Not found: #{minion_name} in #{stage_name}.") if raise_error # raise(Thor::Error, "Not found: #{node_name} in #{stage_name}.") nil end
[ "def", "find_minion_by_name", "(", "minion_name", ",", "raise_error", "=", "true", ")", "raise", "(", "'Minion not specified.'", ")", "if", "minion_name", ".", "nil?", "||", "minion_name", ".", "empty?", "return", "{", "minion_name", "=>", "minions_filtered", "[", "minion_name", "]", "}", "if", "minions", "[", "minion_name", "]", "minions", ".", "each", "do", "|", "key", ",", "value", "|", "return", "{", "key", "=>", "value", "}", "if", "key", ".", "start_with?", "(", "minion_name", ")", "end", "raise", "(", "\"Not found: #{minion_name} in #{stage_name}.\"", ")", "if", "raise_error", "nil", "end" ]
find node by full node_name or by matching prefix of node_name
[ "find", "node", "by", "full", "node_name", "or", "by", "matching", "prefix", "of", "node_name" ]
c0f8c70d75fb34dd9ba0e186c355f25a9e165452
https://github.com/talyric/pvcglue/blob/c0f8c70d75fb34dd9ba0e186c355f25a9e165452/lib/pvcglue/cloud.rb#L91-L101
train
babausse/kharon
lib/kharon/validator.rb
Kharon.Validator.method_missing
def method_missing(name, *arguments, &block) if respond_to? name if arguments.count == 1 processors[name].process(arguments[0]) elsif arguments.count == 2 processors[name].process(arguments[0], arguments[1]) end else super end end
ruby
def method_missing(name, *arguments, &block) if respond_to? name if arguments.count == 1 processors[name].process(arguments[0]) elsif arguments.count == 2 processors[name].process(arguments[0], arguments[1]) end else super end end
[ "def", "method_missing", "(", "name", ",", "*", "arguments", ",", "&", "block", ")", "if", "respond_to?", "name", "if", "arguments", ".", "count", "==", "1", "processors", "[", "name", "]", ".", "process", "(", "arguments", "[", "0", "]", ")", "elsif", "arguments", ".", "count", "==", "2", "processors", "[", "name", "]", ".", "process", "(", "arguments", "[", "0", "]", ",", "arguments", "[", "1", "]", ")", "end", "else", "super", "end", "end" ]
Constructor of the classe, receiving the datas to validate and filter. @param [Hash] datas the datas to validate in the validator. @example create a new instance of validator. @validator = Kharon::Validator.new({key: "value"}) Method used to not directly define the different type validation methods, but instead to look for it in the processors list. @param [String] name the name of the not found method. @param [Array] arguments the arguments passed to the not found method when it's called. @param [Proc] block the block that might have been passed to the not found method when it's called.
[ "Constructor", "of", "the", "classe", "receiving", "the", "datas", "to", "validate", "and", "filter", "." ]
bfd3d90cbc229db70f2ed1762f5f1743259154cd
https://github.com/babausse/kharon/blob/bfd3d90cbc229db70f2ed1762f5f1743259154cd/lib/kharon/validator.rb#L38-L48
train
conversation/raca
lib/raca/http_client.rb
Raca.HttpClient.cloud_request
def cloud_request(request, &block) Net::HTTP.start(@hostname, 443, use_ssl: true, read_timeout: 120) do |http| request['X-Auth-Token'] = @account.auth_token request['User-Agent'] = "raca 0.4.4 (http://rubygems.org/gems/raca)" response = http.request(request, &block) if response.is_a?(Net::HTTPSuccess) response else raise_on_error(request, response) end end end
ruby
def cloud_request(request, &block) Net::HTTP.start(@hostname, 443, use_ssl: true, read_timeout: 120) do |http| request['X-Auth-Token'] = @account.auth_token request['User-Agent'] = "raca 0.4.4 (http://rubygems.org/gems/raca)" response = http.request(request, &block) if response.is_a?(Net::HTTPSuccess) response else raise_on_error(request, response) end end end
[ "def", "cloud_request", "(", "request", ",", "&", "block", ")", "Net", "::", "HTTP", ".", "start", "(", "@hostname", ",", "443", ",", "use_ssl", ":", "true", ",", "read_timeout", ":", "120", ")", "do", "|", "http", "|", "request", "[", "'X-Auth-Token'", "]", "=", "@account", ".", "auth_token", "request", "[", "'User-Agent'", "]", "=", "\"raca 0.4.4 (http://rubygems.org/gems/raca)\"", "response", "=", "http", ".", "request", "(", "request", ",", "&", "block", ")", "if", "response", ".", "is_a?", "(", "Net", "::", "HTTPSuccess", ")", "response", "else", "raise_on_error", "(", "request", ",", "response", ")", "end", "end", "end" ]
perform an HTTP request to rackpsace. request is a Net::HTTP request object. This can be called with and without a block. Without a block, the response is returned as you'd expect response = http_client.cloud_request(request) With the block form, the response is yielded to the block: http_client.cloud_request(request) do |response| puts response end
[ "perform", "an", "HTTP", "request", "to", "rackpsace", "." ]
fa69dfde22359cc0e06f655055be4eadcc7019c0
https://github.com/conversation/raca/blob/fa69dfde22359cc0e06f655055be4eadcc7019c0/lib/raca/http_client.rb#L95-L106
train
ukparliament/gromnative
lib/grom_native/request.rb
GromNative.UrlRequest.method_missing
def method_missing(method, *params, &block) @endpoint_parts << method.to_s @endpoint_parts << params @endpoint_parts = @endpoint_parts.flatten! block&.call self || super end
ruby
def method_missing(method, *params, &block) @endpoint_parts << method.to_s @endpoint_parts << params @endpoint_parts = @endpoint_parts.flatten! block&.call self || super end
[ "def", "method_missing", "(", "method", ",", "*", "params", ",", "&", "block", ")", "@endpoint_parts", "<<", "method", ".", "to_s", "@endpoint_parts", "<<", "params", "@endpoint_parts", "=", "@endpoint_parts", ".", "flatten!", "block", "&.", "call", "self", "||", "super", "end" ]
Overrides ruby's method_missing to allow creation of URLs through method calls. @example Adding a simple URL part request = Parliament::Request::UrlRequest.new(base_url: 'http://example.com') # url: http://example.com/people request.people @example Adding a simple URL part with parameters request = Parliament::Request::UrlRequest.new(base_url: 'http://example.com') # url: http://example.com/people/123456 request.people('123456') @example Chaining URL parts and using hyphens request = Parliament::Request::UrlRequest.new(base_url: 'http://example.com') # url: http://example.com/people/123456/foo/bar/hello-world/7890 request.people('123456').foo.bar('hello-world', '7890') @param [Symbol] method the 'method' (url part) we are processing. @param [Array<Object>] params parameters passed to the specified method (url part). @param [Block] block additional block (kept for compatibility with method_missing API). @return [Parliament::Request::UrlRequest] self (this is to allow method chaining).
[ "Overrides", "ruby", "s", "method_missing", "to", "allow", "creation", "of", "URLs", "through", "method", "calls", "." ]
4b291e9e910699f7881316279ca787be6f1d5038
https://github.com/ukparliament/gromnative/blob/4b291e9e910699f7881316279ca787be6f1d5038/lib/grom_native/request.rb#L97-L106
train
traject/traject_sequel_writer
lib/traject/sequel_writer.rb
Traject.SequelWriter.output_value_to_column_value
def output_value_to_column_value(v) if v.kind_of?(Array) if v.length == 0 nil elsif v.length == 1 v.first elsif v.first.kind_of?(String) v.join(@internal_delimiter) else # Not a string? Um, raise for now? raise ArgumentError.new("Traject::SequelWriter, multiple non-String values provided: #{v}") end else v end end
ruby
def output_value_to_column_value(v) if v.kind_of?(Array) if v.length == 0 nil elsif v.length == 1 v.first elsif v.first.kind_of?(String) v.join(@internal_delimiter) else # Not a string? Um, raise for now? raise ArgumentError.new("Traject::SequelWriter, multiple non-String values provided: #{v}") end else v end end
[ "def", "output_value_to_column_value", "(", "v", ")", "if", "v", ".", "kind_of?", "(", "Array", ")", "if", "v", ".", "length", "==", "0", "nil", "elsif", "v", ".", "length", "==", "1", "v", ".", "first", "elsif", "v", ".", "first", ".", "kind_of?", "(", "String", ")", "v", ".", "join", "(", "@internal_delimiter", ")", "else", "raise", "ArgumentError", ".", "new", "(", "\"Traject::SequelWriter, multiple non-String values provided: #{v}\"", ")", "end", "else", "v", "end", "end" ]
Traject context.output_hash values are arrays. turn them into good column values, joining strings if needed. Single values also accepted, even though not traject standard, they will be passed through unchanged.
[ "Traject", "context", ".", "output_hash", "values", "are", "arrays", ".", "turn", "them", "into", "good", "column", "values", "joining", "strings", "if", "needed", "." ]
72c8b9c3d5cfc09fbcae4652826d7b9e0731b842
https://github.com/traject/traject_sequel_writer/blob/72c8b9c3d5cfc09fbcae4652826d7b9e0731b842/lib/traject/sequel_writer.rb#L152-L167
train
GoConflux/conify
lib/conify/command.rb
Conify.Command.run
def run(klass, method) # Get the command info for this method on this klass command_info_module = klass::CommandInfo.const_get(camelize(method)) # If seeking help for this command with --help or -h if seeking_command_help?(@current_args) puts "\nPurpose: #{command_description(command_info_module)}\n" # respond with command-specific help respond_with_command_help(command_info_module) return end # get the valid arguments defined for this comand valid_args = command_valid_args(command_info_module) if !valid_args?(valid_args) handle_invalid_args(command_info_module) return end klass.new(@current_args.dup).send(method) end
ruby
def run(klass, method) # Get the command info for this method on this klass command_info_module = klass::CommandInfo.const_get(camelize(method)) # If seeking help for this command with --help or -h if seeking_command_help?(@current_args) puts "\nPurpose: #{command_description(command_info_module)}\n" # respond with command-specific help respond_with_command_help(command_info_module) return end # get the valid arguments defined for this comand valid_args = command_valid_args(command_info_module) if !valid_args?(valid_args) handle_invalid_args(command_info_module) return end klass.new(@current_args.dup).send(method) end
[ "def", "run", "(", "klass", ",", "method", ")", "command_info_module", "=", "klass", "::", "CommandInfo", ".", "const_get", "(", "camelize", "(", "method", ")", ")", "if", "seeking_command_help?", "(", "@current_args", ")", "puts", "\"\\nPurpose: #{command_description(command_info_module)}\\n\"", "respond_with_command_help", "(", "command_info_module", ")", "return", "end", "valid_args", "=", "command_valid_args", "(", "command_info_module", ")", "if", "!", "valid_args?", "(", "valid_args", ")", "handle_invalid_args", "(", "command_info_module", ")", "return", "end", "klass", ".", "new", "(", "@current_args", ".", "dup", ")", ".", "send", "(", "method", ")", "end" ]
Call a method on a klass with certain arguments. Will validate arguments first before calling method.
[ "Call", "a", "method", "on", "a", "klass", "with", "certain", "arguments", ".", "Will", "validate", "arguments", "first", "before", "calling", "method", "." ]
2232fa8a3b144566f4558ab888988559d4dff6bd
https://github.com/GoConflux/conify/blob/2232fa8a3b144566f4558ab888988559d4dff6bd/lib/conify/command.rb#L73-L95
train
GoConflux/conify
lib/conify/command.rb
Conify.Command.valid_args?
def valid_args?(accepted_arg_formats) valid_args = false accepted_arg_formats.each { |format| # if no arguments exist, and no arguments is an accepted format, args are valid. if format.empty? && @current_args.empty? valid_args = true else passed_in_args = @current_args.clone format.each_with_index { |arg, i| passed_in_args[i] = arg if CMD_BLACKLIST.include?(arg) } @invalid_args = passed_in_args - format - [nil] valid_args = true if passed_in_args == format end } valid_args end
ruby
def valid_args?(accepted_arg_formats) valid_args = false accepted_arg_formats.each { |format| # if no arguments exist, and no arguments is an accepted format, args are valid. if format.empty? && @current_args.empty? valid_args = true else passed_in_args = @current_args.clone format.each_with_index { |arg, i| passed_in_args[i] = arg if CMD_BLACKLIST.include?(arg) } @invalid_args = passed_in_args - format - [nil] valid_args = true if passed_in_args == format end } valid_args end
[ "def", "valid_args?", "(", "accepted_arg_formats", ")", "valid_args", "=", "false", "accepted_arg_formats", ".", "each", "{", "|", "format", "|", "if", "format", ".", "empty?", "&&", "@current_args", ".", "empty?", "valid_args", "=", "true", "else", "passed_in_args", "=", "@current_args", ".", "clone", "format", ".", "each_with_index", "{", "|", "arg", ",", "i", "|", "passed_in_args", "[", "i", "]", "=", "arg", "if", "CMD_BLACKLIST", ".", "include?", "(", "arg", ")", "}", "@invalid_args", "=", "passed_in_args", "-", "format", "-", "[", "nil", "]", "valid_args", "=", "true", "if", "passed_in_args", "==", "format", "end", "}", "valid_args", "end" ]
Check if passed-in arguments are valid for a specific format
[ "Check", "if", "passed", "-", "in", "arguments", "are", "valid", "for", "a", "specific", "format" ]
2232fa8a3b144566f4558ab888988559d4dff6bd
https://github.com/GoConflux/conify/blob/2232fa8a3b144566f4558ab888988559d4dff6bd/lib/conify/command.rb#L128-L149
train
GoConflux/conify
lib/conify/command.rb
Conify.Command.handle_invalid_args
def handle_invalid_args(command_info_module) if !@invalid_args.empty? message = 'Invalid argument' message += 's' if @invalid_args.length > 1 args = @invalid_args.map { |arg| "\"#{arg}\"" }.join(', ') puts " ! #{message}: #{args}" else puts " ! Invalid command usage" end respond_with_command_help(command_info_module) end
ruby
def handle_invalid_args(command_info_module) if !@invalid_args.empty? message = 'Invalid argument' message += 's' if @invalid_args.length > 1 args = @invalid_args.map { |arg| "\"#{arg}\"" }.join(', ') puts " ! #{message}: #{args}" else puts " ! Invalid command usage" end respond_with_command_help(command_info_module) end
[ "def", "handle_invalid_args", "(", "command_info_module", ")", "if", "!", "@invalid_args", ".", "empty?", "message", "=", "'Invalid argument'", "message", "+=", "'s'", "if", "@invalid_args", ".", "length", ">", "1", "args", "=", "@invalid_args", ".", "map", "{", "|", "arg", "|", "\"\\\"#{arg}\\\"\"", "}", ".", "join", "(", "', '", ")", "puts", "\" ! #{message}: #{args}\"", "else", "puts", "\" ! Invalid command usage\"", "end", "respond_with_command_help", "(", "command_info_module", ")", "end" ]
Respond to the user in the instance of invalid arguments.
[ "Respond", "to", "the", "user", "in", "the", "instance", "of", "invalid", "arguments", "." ]
2232fa8a3b144566f4558ab888988559d4dff6bd
https://github.com/GoConflux/conify/blob/2232fa8a3b144566f4558ab888988559d4dff6bd/lib/conify/command.rb#L152-L164
train
GoConflux/conify
lib/conify/command.rb
Conify.Command.create_commands_map
def create_commands_map # Require all the ruby command files command_file_paths.each do |file| require file # Get basename for the file without the extension basename = get_basename_from_file(file) # Camelcase the basename to be the klass name klass_name = camelize(basename) # return the command klass for this klass_name command_klass = Conify::Command.const_get(klass_name) # For each of the user-defined methods inside this class, create a command for it manually_added_methods(command_klass).each { |method| register_command(basename, method.to_s, command_klass, global: basename == 'global') } end end
ruby
def create_commands_map # Require all the ruby command files command_file_paths.each do |file| require file # Get basename for the file without the extension basename = get_basename_from_file(file) # Camelcase the basename to be the klass name klass_name = camelize(basename) # return the command klass for this klass_name command_klass = Conify::Command.const_get(klass_name) # For each of the user-defined methods inside this class, create a command for it manually_added_methods(command_klass).each { |method| register_command(basename, method.to_s, command_klass, global: basename == 'global') } end end
[ "def", "create_commands_map", "command_file_paths", ".", "each", "do", "|", "file", "|", "require", "file", "basename", "=", "get_basename_from_file", "(", "file", ")", "klass_name", "=", "camelize", "(", "basename", ")", "command_klass", "=", "Conify", "::", "Command", ".", "const_get", "(", "klass_name", ")", "manually_added_methods", "(", "command_klass", ")", ".", "each", "{", "|", "method", "|", "register_command", "(", "basename", ",", "method", ".", "to_s", ",", "command_klass", ",", "global", ":", "basename", "==", "'global'", ")", "}", "end", "end" ]
Create a commands map to respond to `conify help` with.
[ "Create", "a", "commands", "map", "to", "respond", "to", "conify", "help", "with", "." ]
2232fa8a3b144566f4558ab888988559d4dff6bd
https://github.com/GoConflux/conify/blob/2232fa8a3b144566f4558ab888988559d4dff6bd/lib/conify/command.rb#L196-L215
train
GoConflux/conify
lib/conify/command.rb
Conify.Command.usage_info
def usage_info(map) keys = map.keys commands_column_width = keys.max_by(&:length).length + 1 commands_column_width += 2 if commands_column_width < 12 # iterate through each of the commands, create an array # of strings in a `<command> # <description>` format. Sort # them alphabetically, and then join them with new lines. keys.map { |key| command = " #{key}" command += (' ' * (commands_column_width - key.length + 1)) command += "# #{map[key][:description]}" command }.sort_by{ |k| k.downcase }.join("\n") end
ruby
def usage_info(map) keys = map.keys commands_column_width = keys.max_by(&:length).length + 1 commands_column_width += 2 if commands_column_width < 12 # iterate through each of the commands, create an array # of strings in a `<command> # <description>` format. Sort # them alphabetically, and then join them with new lines. keys.map { |key| command = " #{key}" command += (' ' * (commands_column_width - key.length + 1)) command += "# #{map[key][:description]}" command }.sort_by{ |k| k.downcase }.join("\n") end
[ "def", "usage_info", "(", "map", ")", "keys", "=", "map", ".", "keys", "commands_column_width", "=", "keys", ".", "max_by", "(", "&", ":length", ")", ".", "length", "+", "1", "commands_column_width", "+=", "2", "if", "commands_column_width", "<", "12", "keys", ".", "map", "{", "|", "key", "|", "command", "=", "\" #{key}\"", "command", "+=", "(", "' '", "*", "(", "commands_column_width", "-", "key", ".", "length", "+", "1", ")", ")", "command", "+=", "\"# #{map[key][:description]}\"", "command", "}", ".", "sort_by", "{", "|", "k", "|", "k", ".", "downcase", "}", ".", "join", "(", "\"\\n\"", ")", "end" ]
Format a map of commands into help output format
[ "Format", "a", "map", "of", "commands", "into", "help", "output", "format" ]
2232fa8a3b144566f4558ab888988559d4dff6bd
https://github.com/GoConflux/conify/blob/2232fa8a3b144566f4558ab888988559d4dff6bd/lib/conify/command.rb#L218-L232
train
GoConflux/conify
lib/conify/command.rb
Conify.Command.get_basename_from_file
def get_basename_from_file(file) basename = Pathname.new(file).basename.to_s basename[0..(basename.rindex('.') - 1)] end
ruby
def get_basename_from_file(file) basename = Pathname.new(file).basename.to_s basename[0..(basename.rindex('.') - 1)] end
[ "def", "get_basename_from_file", "(", "file", ")", "basename", "=", "Pathname", ".", "new", "(", "file", ")", ".", "basename", ".", "to_s", "basename", "[", "0", "..", "(", "basename", ".", "rindex", "(", "'.'", ")", "-", "1", ")", "]", "end" ]
Return just the basename for a file, no extensions.
[ "Return", "just", "the", "basename", "for", "a", "file", "no", "extensions", "." ]
2232fa8a3b144566f4558ab888988559d4dff6bd
https://github.com/GoConflux/conify/blob/2232fa8a3b144566f4558ab888988559d4dff6bd/lib/conify/command.rb#L261-L264
train
GoConflux/conify
lib/conify/command.rb
Conify.Command.command_file_paths
def command_file_paths abstract_file = File.join(File.dirname(__FILE__), 'command', 'abstract_command.rb') Dir[File.join(File.dirname(__FILE__), 'command', '*.rb')] - [abstract_file] end
ruby
def command_file_paths abstract_file = File.join(File.dirname(__FILE__), 'command', 'abstract_command.rb') Dir[File.join(File.dirname(__FILE__), 'command', '*.rb')] - [abstract_file] end
[ "def", "command_file_paths", "abstract_file", "=", "File", ".", "join", "(", "File", ".", "dirname", "(", "__FILE__", ")", ",", "'command'", ",", "'abstract_command.rb'", ")", "Dir", "[", "File", ".", "join", "(", "File", ".", "dirname", "(", "__FILE__", ")", ",", "'command'", ",", "'*.rb'", ")", "]", "-", "[", "abstract_file", "]", "end" ]
Feturn an array of all command file paths, with the exception of abstract_command.rb
[ "Feturn", "an", "array", "of", "all", "command", "file", "paths", "with", "the", "exception", "of", "abstract_command", ".", "rb" ]
2232fa8a3b144566f4558ab888988559d4dff6bd
https://github.com/GoConflux/conify/blob/2232fa8a3b144566f4558ab888988559d4dff6bd/lib/conify/command.rb#L267-L270
train
GoConflux/conify
lib/conify/command.rb
Conify.Command.register_command
def register_command(basename, action, command_class, global: false) command = global ? action : (action == 'index' ? basename : "#{basename}:#{action}") command_info_module = command_class::CommandInfo.const_get(camelize(action)) commands[command] = { description: command_description(command_info_module) } end
ruby
def register_command(basename, action, command_class, global: false) command = global ? action : (action == 'index' ? basename : "#{basename}:#{action}") command_info_module = command_class::CommandInfo.const_get(camelize(action)) commands[command] = { description: command_description(command_info_module) } end
[ "def", "register_command", "(", "basename", ",", "action", ",", "command_class", ",", "global", ":", "false", ")", "command", "=", "global", "?", "action", ":", "(", "action", "==", "'index'", "?", "basename", ":", "\"#{basename}:#{action}\"", ")", "command_info_module", "=", "command_class", "::", "CommandInfo", ".", "const_get", "(", "camelize", "(", "action", ")", ")", "commands", "[", "command", "]", "=", "{", "description", ":", "command_description", "(", "command_info_module", ")", "}", "end" ]
register a command's info to the @@commands map - utilized when calling `conify help`
[ "register", "a", "command", "s", "info", "to", "the" ]
2232fa8a3b144566f4558ab888988559d4dff6bd
https://github.com/GoConflux/conify/blob/2232fa8a3b144566f4558ab888988559d4dff6bd/lib/conify/command.rb#L277-L283
train
psyho/prezio
lib/prezio/syntax_highlighter.rb
Prezio.SyntaxHighlighter.tableize_code
def tableize_code (str, lang = '') table = '<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers">' code = '' str.lines.each_with_index do |line,index| table += "<span class='line-number'>#{index+1}</span>\n" code += "<span class='line'>#{line}</span>" end table += "</pre></td><td class='code'><pre><code class='#{lang}'>#{code}</code></pre></td></tr></table></div>" end
ruby
def tableize_code (str, lang = '') table = '<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers">' code = '' str.lines.each_with_index do |line,index| table += "<span class='line-number'>#{index+1}</span>\n" code += "<span class='line'>#{line}</span>" end table += "</pre></td><td class='code'><pre><code class='#{lang}'>#{code}</code></pre></td></tr></table></div>" end
[ "def", "tableize_code", "(", "str", ",", "lang", "=", "''", ")", "table", "=", "'<div class=\"highlight\"><table><tr><td class=\"gutter\"><pre class=\"line-numbers\">'", "code", "=", "''", "str", ".", "lines", ".", "each_with_index", "do", "|", "line", ",", "index", "|", "table", "+=", "\"<span class='line-number'>#{index+1}</span>\\n\"", "code", "+=", "\"<span class='line'>#{line}</span>\"", "end", "table", "+=", "\"</pre></td><td class='code'><pre><code class='#{lang}'>#{code}</code></pre></td></tr></table></div>\"", "end" ]
taken from octopress
[ "taken", "from", "octopress" ]
201730e61665c985fda3acf35f3389dd1776de67
https://github.com/psyho/prezio/blob/201730e61665c985fda3acf35f3389dd1776de67/lib/prezio/syntax_highlighter.rb#L45-L53
train
nickcharlton/atlas-ruby
lib/atlas/box.rb
Atlas.Box.save
def save validate! body = { box: to_hash } # versions are saved seperately body[:box].delete(:versions) # update or create the box begin response = Atlas.client.put(url_builder.box_url, body: body) rescue Atlas::Errors::NotFoundError body[:box].replace_key!(:private, :is_private) response = Atlas.client.post("/boxes", body: body) end # trigger the same on versions versions.each(&:save) if versions update_with_response(response, [:versions]) end
ruby
def save validate! body = { box: to_hash } # versions are saved seperately body[:box].delete(:versions) # update or create the box begin response = Atlas.client.put(url_builder.box_url, body: body) rescue Atlas::Errors::NotFoundError body[:box].replace_key!(:private, :is_private) response = Atlas.client.post("/boxes", body: body) end # trigger the same on versions versions.each(&:save) if versions update_with_response(response, [:versions]) end
[ "def", "save", "validate!", "body", "=", "{", "box", ":", "to_hash", "}", "body", "[", ":box", "]", ".", "delete", "(", ":versions", ")", "begin", "response", "=", "Atlas", ".", "client", ".", "put", "(", "url_builder", ".", "box_url", ",", "body", ":", "body", ")", "rescue", "Atlas", "::", "Errors", "::", "NotFoundError", "body", "[", ":box", "]", ".", "replace_key!", "(", ":private", ",", ":is_private", ")", "response", "=", "Atlas", ".", "client", ".", "post", "(", "\"/boxes\"", ",", "body", ":", "body", ")", "end", "versions", ".", "each", "(", "&", ":save", ")", "if", "versions", "update_with_response", "(", "response", ",", "[", ":versions", "]", ")", "end" ]
Save the box. @return [Hash] Atlas response object.
[ "Save", "the", "box", "." ]
2170c04496682e0d8e7c959bd9f267f62fa84c1d
https://github.com/nickcharlton/atlas-ruby/blob/2170c04496682e0d8e7c959bd9f267f62fa84c1d/lib/atlas/box.rb#L110-L131
train
rikas/bitwise_attribute
lib/bitwise_attribute.rb
BitwiseAttribute.ClassMethods.build_mapping
def build_mapping(values) {}.tap do |hash| values.each_with_index { |key, index| hash[key] = (0b1 << index) } end end
ruby
def build_mapping(values) {}.tap do |hash| values.each_with_index { |key, index| hash[key] = (0b1 << index) } end end
[ "def", "build_mapping", "(", "values", ")", "{", "}", ".", "tap", "do", "|", "hash", "|", "values", ".", "each_with_index", "{", "|", "key", ",", "index", "|", "hash", "[", "key", "]", "=", "(", "0b1", "<<", "index", ")", "}", "end", "end" ]
Builds internal bitwise key-value mapping it add a zero value, needed for bits operations. Each sym get a power of 2 value
[ "Builds", "internal", "bitwise", "key", "-", "value", "mapping", "it", "add", "a", "zero", "value", "needed", "for", "bits", "operations", ".", "Each", "sym", "get", "a", "power", "of", "2", "value" ]
b5a24fa843b6738ac7d83a01c73818bc75048021
https://github.com/rikas/bitwise_attribute/blob/b5a24fa843b6738ac7d83a01c73818bc75048021/lib/bitwise_attribute.rb#L60-L64
train
ariejan/firefly-client
lib/firefly/client.rb
Firefly.Client.shorten
def shorten(input) if input.is_a?(String) return create_url(input) elsif input.is_a?(Array) result = {} input.each do |inp| result[inp] = create_url(inp) end return result else raise ArgumentError.new('Shorten requires either a url or an array of urls') end end
ruby
def shorten(input) if input.is_a?(String) return create_url(input) elsif input.is_a?(Array) result = {} input.each do |inp| result[inp] = create_url(inp) end return result else raise ArgumentError.new('Shorten requires either a url or an array of urls') end end
[ "def", "shorten", "(", "input", ")", "if", "input", ".", "is_a?", "(", "String", ")", "return", "create_url", "(", "input", ")", "elsif", "input", ".", "is_a?", "(", "Array", ")", "result", "=", "{", "}", "input", ".", "each", "do", "|", "inp", "|", "result", "[", "inp", "]", "=", "create_url", "(", "inp", ")", "end", "return", "result", "else", "raise", "ArgumentError", ".", "new", "(", "'Shorten requires either a url or an array of urls'", ")", "end", "end" ]
Creates a new instance to shorten Firefly URLs +url+ is the URL to your Firefly server. E.g. "http://aj.gs". Note: do not include a trailing slash +api_key+ is your Firefly API Key. Shortens the given URL or array of URLs. shorten("http://google.com") => "http://aj.gs/7dZ" shorten(["http://google.com", "http://yahoo.com"]) => { "http://google.com/" => "http://aj.gs/7dZ", "http://yahoo.com/" => "http://aj.gs/8Yt" }
[ "Creates", "a", "new", "instance", "to", "shorten", "Firefly", "URLs" ]
217a37418e7eb1288626d4a4070e0ad2bc0effcc
https://github.com/ariejan/firefly-client/blob/217a37418e7eb1288626d4a4070e0ad2bc0effcc/lib/firefly/client.rb#L29-L41
train
ariejan/firefly-client
lib/firefly/client.rb
Firefly.Client.create_url
def create_url(long_url) begin options = { :query => { :url => long_url, :api_key => @api_key } } result = HTTParty.post(@firefly_url + '/api/add', options) if result =~ /Permission denied/i raise "Permission denied. Is your API Key set correctly?" if result.status = 401 else return result end end end
ruby
def create_url(long_url) begin options = { :query => { :url => long_url, :api_key => @api_key } } result = HTTParty.post(@firefly_url + '/api/add', options) if result =~ /Permission denied/i raise "Permission denied. Is your API Key set correctly?" if result.status = 401 else return result end end end
[ "def", "create_url", "(", "long_url", ")", "begin", "options", "=", "{", ":query", "=>", "{", ":url", "=>", "long_url", ",", ":api_key", "=>", "@api_key", "}", "}", "result", "=", "HTTParty", ".", "post", "(", "@firefly_url", "+", "'/api/add'", ",", "options", ")", "if", "result", "=~", "/", "/i", "raise", "\"Permission denied. Is your API Key set correctly?\"", "if", "result", ".", "status", "=", "401", "else", "return", "result", "end", "end", "end" ]
Shortend +long_url+ and returns the short_url on success
[ "Shortend", "+", "long_url", "+", "and", "returns", "the", "short_url", "on", "success" ]
217a37418e7eb1288626d4a4070e0ad2bc0effcc
https://github.com/ariejan/firefly-client/blob/217a37418e7eb1288626d4a4070e0ad2bc0effcc/lib/firefly/client.rb#L46-L57
train
buren/jsonapi_helpers
lib/jsonapi_helpers/support/key_transform.rb
JSONAPIHelpers.KeyTransform.camel
def camel(value) case value when Hash then value.deep_transform_keys! { |key| camel(key) } when Symbol then camel(value.to_s).to_sym when String then StringSupport.camel(value) else value end end
ruby
def camel(value) case value when Hash then value.deep_transform_keys! { |key| camel(key) } when Symbol then camel(value.to_s).to_sym when String then StringSupport.camel(value) else value end end
[ "def", "camel", "(", "value", ")", "case", "value", "when", "Hash", "then", "value", ".", "deep_transform_keys!", "{", "|", "key", "|", "camel", "(", "key", ")", "}", "when", "Symbol", "then", "camel", "(", "value", ".", "to_s", ")", ".", "to_sym", "when", "String", "then", "StringSupport", ".", "camel", "(", "value", ")", "else", "value", "end", "end" ]
Transforms values to UpperCamelCase or PascalCase. @example: "some_key" => "SomeKey",
[ "Transforms", "values", "to", "UpperCamelCase", "or", "PascalCase", "." ]
4a025a5f6ba3d6f01cd96e1776134d3aeb21e2a6
https://github.com/buren/jsonapi_helpers/blob/4a025a5f6ba3d6f01cd96e1776134d3aeb21e2a6/lib/jsonapi_helpers/support/key_transform.rb#L20-L27
train
buren/jsonapi_helpers
lib/jsonapi_helpers/support/key_transform.rb
JSONAPIHelpers.KeyTransform.camel_lower
def camel_lower(value) case value when Hash then value.deep_transform_keys! { |key| camel_lower(key) } when Symbol then camel_lower(value.to_s).to_sym when String then StringSupport.camel_lower(value) else value end end
ruby
def camel_lower(value) case value when Hash then value.deep_transform_keys! { |key| camel_lower(key) } when Symbol then camel_lower(value.to_s).to_sym when String then StringSupport.camel_lower(value) else value end end
[ "def", "camel_lower", "(", "value", ")", "case", "value", "when", "Hash", "then", "value", ".", "deep_transform_keys!", "{", "|", "key", "|", "camel_lower", "(", "key", ")", "}", "when", "Symbol", "then", "camel_lower", "(", "value", ".", "to_s", ")", ".", "to_sym", "when", "String", "then", "StringSupport", ".", "camel_lower", "(", "value", ")", "else", "value", "end", "end" ]
Transforms values to camelCase. @example: "some_key" => "someKey",
[ "Transforms", "values", "to", "camelCase", "." ]
4a025a5f6ba3d6f01cd96e1776134d3aeb21e2a6
https://github.com/buren/jsonapi_helpers/blob/4a025a5f6ba3d6f01cd96e1776134d3aeb21e2a6/lib/jsonapi_helpers/support/key_transform.rb#L33-L40
train
buren/jsonapi_helpers
lib/jsonapi_helpers/support/key_transform.rb
JSONAPIHelpers.KeyTransform.dash
def dash(value) case value when Hash then value.deep_transform_keys! { |key| dash(key) } when Symbol then dash(value.to_s).to_sym when String then StringSupport.dash(value) else value end end
ruby
def dash(value) case value when Hash then value.deep_transform_keys! { |key| dash(key) } when Symbol then dash(value.to_s).to_sym when String then StringSupport.dash(value) else value end end
[ "def", "dash", "(", "value", ")", "case", "value", "when", "Hash", "then", "value", ".", "deep_transform_keys!", "{", "|", "key", "|", "dash", "(", "key", ")", "}", "when", "Symbol", "then", "dash", "(", "value", ".", "to_s", ")", ".", "to_sym", "when", "String", "then", "StringSupport", ".", "dash", "(", "value", ")", "else", "value", "end", "end" ]
Transforms values to dashed-case. This is the default case for the JsonApi adapter. @example: "some_key" => "some-key",
[ "Transforms", "values", "to", "dashed", "-", "case", ".", "This", "is", "the", "default", "case", "for", "the", "JsonApi", "adapter", "." ]
4a025a5f6ba3d6f01cd96e1776134d3aeb21e2a6
https://github.com/buren/jsonapi_helpers/blob/4a025a5f6ba3d6f01cd96e1776134d3aeb21e2a6/lib/jsonapi_helpers/support/key_transform.rb#L47-L54
train
buren/jsonapi_helpers
lib/jsonapi_helpers/support/key_transform.rb
JSONAPIHelpers.KeyTransform.underscore
def underscore(value) case value when Hash then value.deep_transform_keys! { |key| underscore(key) } when Symbol then underscore(value.to_s).to_sym when String then StringSupport.underscore(value) else value end end
ruby
def underscore(value) case value when Hash then value.deep_transform_keys! { |key| underscore(key) } when Symbol then underscore(value.to_s).to_sym when String then StringSupport.underscore(value) else value end end
[ "def", "underscore", "(", "value", ")", "case", "value", "when", "Hash", "then", "value", ".", "deep_transform_keys!", "{", "|", "key", "|", "underscore", "(", "key", ")", "}", "when", "Symbol", "then", "underscore", "(", "value", ".", "to_s", ")", ".", "to_sym", "when", "String", "then", "StringSupport", ".", "underscore", "(", "value", ")", "else", "value", "end", "end" ]
Transforms values to underscore_case. This is the default case for deserialization in the JsonApi adapter. @example: "some-key" => "some_key",
[ "Transforms", "values", "to", "underscore_case", ".", "This", "is", "the", "default", "case", "for", "deserialization", "in", "the", "JsonApi", "adapter", "." ]
4a025a5f6ba3d6f01cd96e1776134d3aeb21e2a6
https://github.com/buren/jsonapi_helpers/blob/4a025a5f6ba3d6f01cd96e1776134d3aeb21e2a6/lib/jsonapi_helpers/support/key_transform.rb#L61-L68
train
ghn/swissforecast
lib/swissforecast.rb
Swissforecast.Client.find_by
def find_by(param) if param.key?(:city) perform(param[:city].sub(' ', '-')) elsif param.key?(:lat) && param.key?(:lng) perform("lat=#{param[:lat]}lng=#{param[:lng]}") end end
ruby
def find_by(param) if param.key?(:city) perform(param[:city].sub(' ', '-')) elsif param.key?(:lat) && param.key?(:lng) perform("lat=#{param[:lat]}lng=#{param[:lng]}") end end
[ "def", "find_by", "(", "param", ")", "if", "param", ".", "key?", "(", ":city", ")", "perform", "(", "param", "[", ":city", "]", ".", "sub", "(", "' '", ",", "'-'", ")", ")", "elsif", "param", ".", "key?", "(", ":lat", ")", "&&", "param", ".", "key?", "(", ":lng", ")", "perform", "(", "\"lat=#{param[:lat]}lng=#{param[:lng]}\"", ")", "end", "end" ]
=> find weather by city or by gps position
[ "=", ">", "find", "weather", "by", "city", "or", "by", "gps", "position" ]
aea52c3451002689a53a2cac63338a5409c445ec
https://github.com/ghn/swissforecast/blob/aea52c3451002689a53a2cac63338a5409c445ec/lib/swissforecast.rb#L13-L19
train
antonversal/fake_service
lib/fake_service/server.rb
FakeService.Server.right_header?
def right_header?(expected, actual) expected.inject(true) do |memo, (k, v)| memo && v == actual[k] end end
ruby
def right_header?(expected, actual) expected.inject(true) do |memo, (k, v)| memo && v == actual[k] end end
[ "def", "right_header?", "(", "expected", ",", "actual", ")", "expected", ".", "inject", "(", "true", ")", "do", "|", "memo", ",", "(", "k", ",", "v", ")", "|", "memo", "&&", "v", "==", "actual", "[", "k", "]", "end", "end" ]
Checks for request comes with right header.
[ "Checks", "for", "request", "comes", "with", "right", "header", "." ]
93a59f859447004bdea27b3b4226c4d73d197008
https://github.com/antonversal/fake_service/blob/93a59f859447004bdea27b3b4226c4d73d197008/lib/fake_service/server.rb#L19-L23
train
maxjacobson/todo_lint
lib/todo_lint/options.rb
TodoLint.Options.parse
def parse(args) @options = { :report => false } OptionParser.new do |parser| parser.banner = "Usage: todo_lint [options] [files]" add_config_options parser exclude_file_options parser include_extension_options parser report_version parser report_report_options parser end.parse!(args) # Any remaining arguments are assumed to be files options[:files] = args options end
ruby
def parse(args) @options = { :report => false } OptionParser.new do |parser| parser.banner = "Usage: todo_lint [options] [files]" add_config_options parser exclude_file_options parser include_extension_options parser report_version parser report_report_options parser end.parse!(args) # Any remaining arguments are assumed to be files options[:files] = args options end
[ "def", "parse", "(", "args", ")", "@options", "=", "{", ":report", "=>", "false", "}", "OptionParser", ".", "new", "do", "|", "parser", "|", "parser", ".", "banner", "=", "\"Usage: todo_lint [options] [files]\"", "add_config_options", "parser", "exclude_file_options", "parser", "include_extension_options", "parser", "report_version", "parser", "report_report_options", "parser", "end", ".", "parse!", "(", "args", ")", "options", "[", ":files", "]", "=", "args", "options", "end" ]
Parses command line options into an options hash @api public @example Options.new.parse("todo_lint -c app.rb") @param args [Array<String>] arguments passed via the command line @return [Hash] parsed options
[ "Parses", "command", "line", "options", "into", "an", "options", "hash" ]
0d1061383ea205ef4c74edc64568e308ac1af990
https://github.com/maxjacobson/todo_lint/blob/0d1061383ea205ef4c74edc64568e308ac1af990/lib/todo_lint/options.rb#L11-L27
train
maxjacobson/todo_lint
lib/todo_lint/options.rb
TodoLint.Options.exclude_file_options
def exclude_file_options(parser) parser.on("-e", "--exclude file1,...", Array, "List of file names to exclude") do |files_list| options[:excluded_files] = [] files_list.each do |short_file| options[:excluded_files] << File.expand_path(short_file) end end end
ruby
def exclude_file_options(parser) parser.on("-e", "--exclude file1,...", Array, "List of file names to exclude") do |files_list| options[:excluded_files] = [] files_list.each do |short_file| options[:excluded_files] << File.expand_path(short_file) end end end
[ "def", "exclude_file_options", "(", "parser", ")", "parser", ".", "on", "(", "\"-e\"", ",", "\"--exclude file1,...\"", ",", "Array", ",", "\"List of file names to exclude\"", ")", "do", "|", "files_list", "|", "options", "[", ":excluded_files", "]", "=", "[", "]", "files_list", ".", "each", "do", "|", "short_file", "|", "options", "[", ":excluded_files", "]", "<<", "File", ".", "expand_path", "(", "short_file", ")", "end", "end", "end" ]
Adds the excluded file options to the options hash @api private @return [Hash]
[ "Adds", "the", "excluded", "file", "options", "to", "the", "options", "hash" ]
0d1061383ea205ef4c74edc64568e308ac1af990
https://github.com/maxjacobson/todo_lint/blob/0d1061383ea205ef4c74edc64568e308ac1af990/lib/todo_lint/options.rb#L45-L53
train
kristianmandrup/cantango-config
lib/cantango/category.rb
CanTango.Category.has_any?
def has_any? subject, &block found = subjects.include? subject yield if found && block found end
ruby
def has_any? subject, &block found = subjects.include? subject yield if found && block found end
[ "def", "has_any?", "subject", ",", "&", "block", "found", "=", "subjects", ".", "include?", "subject", "yield", "if", "found", "&&", "block", "found", "end" ]
test if a particular category has a certain subject
[ "test", "if", "a", "particular", "category", "has", "a", "certain", "subject" ]
b3131f92c594cb5f085979c01699fe81fb3e724d
https://github.com/kristianmandrup/cantango-config/blob/b3131f92c594cb5f085979c01699fe81fb3e724d/lib/cantango/category.rb#L12-L16
train
caruby/scat
lib/scat/field.rb
Scat.Field.input_attributes
def input_attributes(value) params = {:id => input_id, :type => type, :name => name, :value => value } if type == 'checkbox' then params[:value] ||= self.value params[:checked] = true if default end params end
ruby
def input_attributes(value) params = {:id => input_id, :type => type, :name => name, :value => value } if type == 'checkbox' then params[:value] ||= self.value params[:checked] = true if default end params end
[ "def", "input_attributes", "(", "value", ")", "params", "=", "{", ":id", "=>", "input_id", ",", ":type", "=>", "type", ",", ":name", "=>", "name", ",", ":value", "=>", "value", "}", "if", "type", "==", "'checkbox'", "then", "params", "[", ":value", "]", "||=", "self", ".", "value", "params", "[", ":checked", "]", "=", "true", "if", "default", "end", "params", "end" ]
Parses the given field specification. @param [String] label the configuration field specification key @param [{String => String}] spec the configuration field specification value Returns this field's HTML input element attributes and target caTissue properties. The attributes are determined by the field configuration as follows: * +id+: this field's HTML input element id * +type+: this field's type * +checked+: +true+ if the field type is +checkbox+ and the field default is set * +name+: if the field type is not +checkbox+, then this field's name @param [String, nil] value the request parameter value @return [{Symbol => String}] the form input element attributes
[ "Parses", "the", "given", "field", "specification", "." ]
90291b317eb6b8ef8b0a4497622eadc15d3d9028
https://github.com/caruby/scat/blob/90291b317eb6b8ef8b0a4497622eadc15d3d9028/lib/scat/field.rb#L79-L86
train
26fe/sem4r
lib/sem4r/geo_location/geo_location_account_extension.rb
Sem4r.GeoLocationAccountExtension.geo_location
def geo_location(c1, c2 = nil , c3 = nil) if c1.class != GeoLocationSelector # TODO: raise wrong number of arguments if c2 or c3 are nil selector = GeoLocationSelector.new selector.address do address c1 city c2 country c3 end else selector = c1 end soap_message = service.geo_location.get(credentials, selector.to_xml) add_counters(soap_message.counters) end
ruby
def geo_location(c1, c2 = nil , c3 = nil) if c1.class != GeoLocationSelector # TODO: raise wrong number of arguments if c2 or c3 are nil selector = GeoLocationSelector.new selector.address do address c1 city c2 country c3 end else selector = c1 end soap_message = service.geo_location.get(credentials, selector.to_xml) add_counters(soap_message.counters) end
[ "def", "geo_location", "(", "c1", ",", "c2", "=", "nil", ",", "c3", "=", "nil", ")", "if", "c1", ".", "class", "!=", "GeoLocationSelector", "selector", "=", "GeoLocationSelector", ".", "new", "selector", ".", "address", "do", "address", "c1", "city", "c2", "country", "c3", "end", "else", "selector", "=", "c1", "end", "soap_message", "=", "service", ".", "geo_location", ".", "get", "(", "credentials", ",", "selector", ".", "to_xml", ")", "add_counters", "(", "soap_message", ".", "counters", ")", "end" ]
Call geo location adwords service @example account.geo_location("Via Conca del Naviglio", "Milano", "IT") account.geo_location( geoLocationSelector )
[ "Call", "geo", "location", "adwords", "service" ]
2326404f98b9c2833549fcfda078d39c9954a0fa
https://github.com/26fe/sem4r/blob/2326404f98b9c2833549fcfda078d39c9954a0fa/lib/sem4r/geo_location/geo_location_account_extension.rb#L35-L50
train
ktonon/code_node
spec/fixtures/activerecord/src/active_record/relation.rb
ActiveRecord.Relation.update_all
def update_all(updates, conditions = nil, options = {}) IdentityMap.repository[symbolized_base_class].clear if IdentityMap.enabled? if conditions || options.present? where(conditions).apply_finder_options(options.slice(:limit, :order)).update_all(updates) else stmt = Arel::UpdateManager.new(arel.engine) stmt.set Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates)) stmt.table(table) stmt.key = table[primary_key] if joins_values.any? @klass.connection.join_to_update(stmt, arel) else stmt.take(arel.limit) stmt.order(*arel.orders) stmt.wheres = arel.constraints end @klass.connection.update stmt, 'SQL', bind_values end end
ruby
def update_all(updates, conditions = nil, options = {}) IdentityMap.repository[symbolized_base_class].clear if IdentityMap.enabled? if conditions || options.present? where(conditions).apply_finder_options(options.slice(:limit, :order)).update_all(updates) else stmt = Arel::UpdateManager.new(arel.engine) stmt.set Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates)) stmt.table(table) stmt.key = table[primary_key] if joins_values.any? @klass.connection.join_to_update(stmt, arel) else stmt.take(arel.limit) stmt.order(*arel.orders) stmt.wheres = arel.constraints end @klass.connection.update stmt, 'SQL', bind_values end end
[ "def", "update_all", "(", "updates", ",", "conditions", "=", "nil", ",", "options", "=", "{", "}", ")", "IdentityMap", ".", "repository", "[", "symbolized_base_class", "]", ".", "clear", "if", "IdentityMap", ".", "enabled?", "if", "conditions", "||", "options", ".", "present?", "where", "(", "conditions", ")", ".", "apply_finder_options", "(", "options", ".", "slice", "(", ":limit", ",", ":order", ")", ")", ".", "update_all", "(", "updates", ")", "else", "stmt", "=", "Arel", "::", "UpdateManager", ".", "new", "(", "arel", ".", "engine", ")", "stmt", ".", "set", "Arel", ".", "sql", "(", "@klass", ".", "send", "(", ":sanitize_sql_for_assignment", ",", "updates", ")", ")", "stmt", ".", "table", "(", "table", ")", "stmt", ".", "key", "=", "table", "[", "primary_key", "]", "if", "joins_values", ".", "any?", "@klass", ".", "connection", ".", "join_to_update", "(", "stmt", ",", "arel", ")", "else", "stmt", ".", "take", "(", "arel", ".", "limit", ")", "stmt", ".", "order", "(", "*", "arel", ".", "orders", ")", "stmt", ".", "wheres", "=", "arel", ".", "constraints", "end", "@klass", ".", "connection", ".", "update", "stmt", ",", "'SQL'", ",", "bind_values", "end", "end" ]
Updates all records with details given if they match a set of conditions supplied, limits and order can also be supplied. This method constructs a single SQL UPDATE statement and sends it straight to the database. It does not instantiate the involved models and it does not trigger Active Record callbacks or validations. ==== Parameters * +updates+ - A string, array, or hash representing the SET part of an SQL statement. * +conditions+ - A string, array, or hash representing the WHERE part of an SQL statement. See conditions in the intro. * +options+ - Additional options are <tt>:limit</tt> and <tt>:order</tt>, see the examples for usage. ==== Examples # Update all customers with the given attributes Customer.update_all :wants_email => true # Update all books with 'Rails' in their title Book.update_all "author = 'David'", "title LIKE '%Rails%'" # Update all avatars migrated more than a week ago Avatar.update_all ['migrated_at = ?', Time.now.utc], ['migrated_at > ?', 1.week.ago] # Update all books that match conditions, but limit it to 5 ordered by date Book.update_all "author = 'David'", "title LIKE '%Rails%'", :order => 'created_at', :limit => 5 # Conditions from the current relation also works Book.where('title LIKE ?', '%Rails%').update_all(:author => 'David') # The same idea applies to limit and order Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(:author => 'David')
[ "Updates", "all", "records", "with", "details", "given", "if", "they", "match", "a", "set", "of", "conditions", "supplied", "limits", "and", "order", "can", "also", "be", "supplied", ".", "This", "method", "constructs", "a", "single", "SQL", "UPDATE", "statement", "and", "sends", "it", "straight", "to", "the", "database", ".", "It", "does", "not", "instantiate", "the", "involved", "models", "and", "it", "does", "not", "trigger", "Active", "Record", "callbacks", "or", "validations", "." ]
48d5d1a7442d9cade602be4fb782a1b56c7677f5
https://github.com/ktonon/code_node/blob/48d5d1a7442d9cade602be4fb782a1b56c7677f5/spec/fixtures/activerecord/src/active_record/relation.rb#L275-L296
train
wwidea/rexport
lib/rexport/data_fields.rb
Rexport.DataFields.export
def export(*methods) methods.flatten.map do |method| case value = (eval("self.#{method}", binding) rescue nil) when Date, Time value.strftime("%m/%d/%y") when TrueClass 'Y' when FalseClass 'N' else value.to_s end end end
ruby
def export(*methods) methods.flatten.map do |method| case value = (eval("self.#{method}", binding) rescue nil) when Date, Time value.strftime("%m/%d/%y") when TrueClass 'Y' when FalseClass 'N' else value.to_s end end end
[ "def", "export", "(", "*", "methods", ")", "methods", ".", "flatten", ".", "map", "do", "|", "method", "|", "case", "value", "=", "(", "eval", "(", "\"self.#{method}\"", ",", "binding", ")", "rescue", "nil", ")", "when", "Date", ",", "Time", "value", ".", "strftime", "(", "\"%m/%d/%y\"", ")", "when", "TrueClass", "'Y'", "when", "FalseClass", "'N'", "else", "value", ".", "to_s", "end", "end", "end" ]
Return an array of formatted export values for the passed methods
[ "Return", "an", "array", "of", "formatted", "export", "values", "for", "the", "passed", "methods" ]
f4f978dd0327ddba3a4318dd24090fbc6d4e4e59
https://github.com/wwidea/rexport/blob/f4f978dd0327ddba3a4318dd24090fbc6d4e4e59/lib/rexport/data_fields.rb#L100-L112
train
petebrowne/machined
lib/machined/environment.rb
Machined.Environment.reload
def reload # Make sure we have a fresh cache after we reload config.cache.clear if config.cache.respond_to?(:clear) # Reload dependencies as well, if necessary ActiveSupport::Dependencies.clear if defined?(ActiveSupport::Dependencies) # Use current configuration, but skip bundle and autoloading initializers current_config = config.marshal_dump.dup current_config.merge! :skip_bundle => true#, :skip_autoloading => true) initialize current_config end
ruby
def reload # Make sure we have a fresh cache after we reload config.cache.clear if config.cache.respond_to?(:clear) # Reload dependencies as well, if necessary ActiveSupport::Dependencies.clear if defined?(ActiveSupport::Dependencies) # Use current configuration, but skip bundle and autoloading initializers current_config = config.marshal_dump.dup current_config.merge! :skip_bundle => true#, :skip_autoloading => true) initialize current_config end
[ "def", "reload", "config", ".", "cache", ".", "clear", "if", "config", ".", "cache", ".", "respond_to?", "(", ":clear", ")", "ActiveSupport", "::", "Dependencies", ".", "clear", "if", "defined?", "(", "ActiveSupport", "::", "Dependencies", ")", "current_config", "=", "config", ".", "marshal_dump", ".", "dup", "current_config", ".", "merge!", ":skip_bundle", "=>", "true", "initialize", "current_config", "end" ]
Reloads the environment. This will re-evaluate the config file & clear the current cache.
[ "Reloads", "the", "environment", ".", "This", "will", "re", "-", "evaluate", "the", "config", "file", "&", "clear", "the", "current", "cache", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/lib/machined/environment.rb#L310-L322
train
petebrowne/machined
lib/machined/environment.rb
Machined.Environment.remove_sprocket
def remove_sprocket(name) if sprocket = get_sprocket(name) sprockets.delete sprocket set_sprocket(name, nil) end end
ruby
def remove_sprocket(name) if sprocket = get_sprocket(name) sprockets.delete sprocket set_sprocket(name, nil) end end
[ "def", "remove_sprocket", "(", "name", ")", "if", "sprocket", "=", "get_sprocket", "(", "name", ")", "sprockets", ".", "delete", "sprocket", "set_sprocket", "(", "name", ",", "nil", ")", "end", "end" ]
Removes the sprocket with the given name. This is useful if you don't need one of the default Sprockets.
[ "Removes", "the", "sprocket", "with", "the", "given", "name", ".", "This", "is", "useful", "if", "you", "don", "t", "need", "one", "of", "the", "default", "Sprockets", "." ]
4f3921bc5098104096474300e933f009f1b4f7dd
https://github.com/petebrowne/machined/blob/4f3921bc5098104096474300e933f009f1b4f7dd/lib/machined/environment.rb#L352-L357
train