repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
datamapper/dm-core
lib/dm-core/resource.rb
DataMapper.Resource.execute_hooks_for
def execute_hooks_for(type, name) model.hooks[name][type].each { |hook| hook.call(self) } end
ruby
def execute_hooks_for(type, name) model.hooks[name][type].each { |hook| hook.call(self) } end
[ "def", "execute_hooks_for", "(", "type", ",", "name", ")", "model", ".", "hooks", "[", "name", "]", "[", "type", "]", ".", "each", "{", "|", "hook", "|", "hook", ".", "call", "(", "self", ")", "}", "end" ]
Execute all the queued up hooks for a given type and name @param [Symbol] type the type of hook to execute (before or after) @param [Symbol] name the name of the hook to execute @return [undefined] @api private
[ "Execute", "all", "the", "queued", "up", "hooks", "for", "a", "given", "type", "and", "name" ]
226c5af8609a2e1da3bf3ee0b29a874401a49c0b
https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/resource.rb#L1136-L1138
train
datamapper/dm-core
lib/dm-core/resource.rb
DataMapper.Resource.run_once
def run_once(default) caller_method = Kernel.caller(1).first[/`([^'?!]+)[?!]?'/, 1] sentinel = "@_#{caller_method}_sentinel" return instance_variable_get(sentinel) if instance_variable_defined?(sentinel) begin instance_variable_set(sentinel, default) yield ensure remove_instance_variable(sentinel) end end
ruby
def run_once(default) caller_method = Kernel.caller(1).first[/`([^'?!]+)[?!]?'/, 1] sentinel = "@_#{caller_method}_sentinel" return instance_variable_get(sentinel) if instance_variable_defined?(sentinel) begin instance_variable_set(sentinel, default) yield ensure remove_instance_variable(sentinel) end end
[ "def", "run_once", "(", "default", ")", "caller_method", "=", "Kernel", ".", "caller", "(", "1", ")", ".", "first", "[", "/", "/", ",", "1", "]", "sentinel", "=", "\"@_#{caller_method}_sentinel\"", "return", "instance_variable_get", "(", "sentinel", ")", "if", "instance_variable_defined?", "(", "sentinel", ")", "begin", "instance_variable_set", "(", "sentinel", ",", "default", ")", "yield", "ensure", "remove_instance_variable", "(", "sentinel", ")", "end", "end" ]
Prevent a method from being in the stack more than once The purpose of this method is to prevent SystemStackError from being thrown from methods from encountering infinite recursion when called on resources having circular dependencies. @param [Object] default default return value @yield The block of code to run once @return [Object] block return value @api private
[ "Prevent", "a", "method", "from", "being", "in", "the", "stack", "more", "than", "once" ]
226c5af8609a2e1da3bf3ee0b29a874401a49c0b
https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/resource.rb#L1208-L1219
train
datamapper/dm-core
lib/dm-core/support/inflector/inflections.rb
DataMapper.Inflector.pluralize
def pluralize(word) result = word.to_s.dup if word.empty? || inflections.uncountables.include?(result.downcase) result else inflections.plurals.each { |(rule, replacement)| break if result.gsub!(rule, replacement) } result end end
ruby
def pluralize(word) result = word.to_s.dup if word.empty? || inflections.uncountables.include?(result.downcase) result else inflections.plurals.each { |(rule, replacement)| break if result.gsub!(rule, replacement) } result end end
[ "def", "pluralize", "(", "word", ")", "result", "=", "word", ".", "to_s", ".", "dup", "if", "word", ".", "empty?", "||", "inflections", ".", "uncountables", ".", "include?", "(", "result", ".", "downcase", ")", "result", "else", "inflections", ".", "plurals", ".", "each", "{", "|", "(", "rule", ",", "replacement", ")", "|", "break", "if", "result", ".", "gsub!", "(", "rule", ",", "replacement", ")", "}", "result", "end", "end" ]
Returns the plural form of the word in the string. Examples: "post".pluralize # => "posts" "octopus".pluralize # => "octopi" "sheep".pluralize # => "sheep" "words".pluralize # => "words" "CamelOctopus".pluralize # => "CamelOctopi"
[ "Returns", "the", "plural", "form", "of", "the", "word", "in", "the", "string", "." ]
226c5af8609a2e1da3bf3ee0b29a874401a49c0b
https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/support/inflector/inflections.rb#L129-L138
train
nesquena/backburner
lib/backburner/helpers.rb
Backburner.Helpers.exception_message
def exception_message(e) msg = [ "Exception #{e.class} -> #{e.message}" ] base = File.expand_path(Dir.pwd) + '/' e.backtrace.each do |t| msg << " #{File.expand_path(t).gsub(/#{base}/, '')}" end if e.backtrace msg.join("\n") end
ruby
def exception_message(e) msg = [ "Exception #{e.class} -> #{e.message}" ] base = File.expand_path(Dir.pwd) + '/' e.backtrace.each do |t| msg << " #{File.expand_path(t).gsub(/#{base}/, '')}" end if e.backtrace msg.join("\n") end
[ "def", "exception_message", "(", "e", ")", "msg", "=", "[", "\"Exception #{e.class} -> #{e.message}\"", "]", "base", "=", "File", ".", "expand_path", "(", "Dir", ".", "pwd", ")", "+", "'/'", "e", ".", "backtrace", ".", "each", "do", "|", "t", "|", "msg", "<<", "\" #{File.expand_path(t).gsub(/#{base}/, '')}\"", "end", "if", "e", ".", "backtrace", "msg", ".", "join", "(", "\"\\n\"", ")", "end" ]
Prints out exception_message based on specified e
[ "Prints", "out", "exception_message", "based", "on", "specified", "e" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/helpers.rb#L9-L18
train
nesquena/backburner
lib/backburner/helpers.rb
Backburner.Helpers.classify
def classify(dashed_word) dashed_word.to_s.split('-').each { |part| part[0] = part[0].chr.upcase }.join end
ruby
def classify(dashed_word) dashed_word.to_s.split('-').each { |part| part[0] = part[0].chr.upcase }.join end
[ "def", "classify", "(", "dashed_word", ")", "dashed_word", ".", "to_s", ".", "split", "(", "'-'", ")", ".", "each", "{", "|", "part", "|", "part", "[", "0", "]", "=", "part", "[", "0", "]", ".", "chr", ".", "upcase", "}", ".", "join", "end" ]
Given a word with dashes, returns a camel cased version of it. @example classify('job-name') # => 'JobName'
[ "Given", "a", "word", "with", "dashes", "returns", "a", "camel", "cased", "version", "of", "it", "." ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/helpers.rb#L25-L27
train
nesquena/backburner
lib/backburner/helpers.rb
Backburner.Helpers.dasherize
def dasherize(word) classify(word).to_s.gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("_", "-").downcase end
ruby
def dasherize(word) classify(word).to_s.gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("_", "-").downcase end
[ "def", "dasherize", "(", "word", ")", "classify", "(", "word", ")", ".", "to_s", ".", "gsub", "(", "/", "/", ",", "'/'", ")", ".", "gsub", "(", "/", "/", ",", "'\\1_\\2'", ")", ".", "gsub", "(", "/", "\\d", "/", ",", "'\\1_\\2'", ")", ".", "tr", "(", "\"_\"", ",", "\"-\"", ")", ".", "downcase", "end" ]
Given a class, dasherizes the name, used for getting tube names @example dasherize('JobName') # => "job-name"
[ "Given", "a", "class", "dasherizes", "the", "name", "used", "for", "getting", "tube", "names" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/helpers.rb#L34-L39
train
nesquena/backburner
lib/backburner/helpers.rb
Backburner.Helpers.resolve_priority
def resolve_priority(pri) if pri.respond_to?(:queue_priority) resolve_priority(pri.queue_priority) elsif pri.is_a?(String) || pri.is_a?(Symbol) # named priority resolve_priority(Backburner.configuration.priority_labels[pri.to_sym]) elsif pri.is_a?(Integer) # numerical pri else # default Backburner.configuration.default_priority end end
ruby
def resolve_priority(pri) if pri.respond_to?(:queue_priority) resolve_priority(pri.queue_priority) elsif pri.is_a?(String) || pri.is_a?(Symbol) # named priority resolve_priority(Backburner.configuration.priority_labels[pri.to_sym]) elsif pri.is_a?(Integer) # numerical pri else # default Backburner.configuration.default_priority end end
[ "def", "resolve_priority", "(", "pri", ")", "if", "pri", ".", "respond_to?", "(", ":queue_priority", ")", "resolve_priority", "(", "pri", ".", "queue_priority", ")", "elsif", "pri", ".", "is_a?", "(", "String", ")", "||", "pri", ".", "is_a?", "(", "Symbol", ")", "resolve_priority", "(", "Backburner", ".", "configuration", ".", "priority_labels", "[", "pri", ".", "to_sym", "]", ")", "elsif", "pri", ".", "is_a?", "(", "Integer", ")", "pri", "else", "Backburner", ".", "configuration", ".", "default_priority", "end", "end" ]
Resolves job priority based on the value given. Can be integer, a class or nothing @example resolve_priority(1000) => 1000 resolve_priority(FooBar) => <queue priority> resolve_priority(nil) => <default priority>
[ "Resolves", "job", "priority", "based", "on", "the", "value", "given", ".", "Can", "be", "integer", "a", "class", "or", "nothing" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/helpers.rb#L112-L122
train
nesquena/backburner
lib/backburner/helpers.rb
Backburner.Helpers.resolve_respond_timeout
def resolve_respond_timeout(ttr) if ttr.respond_to?(:queue_respond_timeout) resolve_respond_timeout(ttr.queue_respond_timeout) elsif ttr.is_a?(Integer) # numerical ttr else # default Backburner.configuration.respond_timeout end end
ruby
def resolve_respond_timeout(ttr) if ttr.respond_to?(:queue_respond_timeout) resolve_respond_timeout(ttr.queue_respond_timeout) elsif ttr.is_a?(Integer) # numerical ttr else # default Backburner.configuration.respond_timeout end end
[ "def", "resolve_respond_timeout", "(", "ttr", ")", "if", "ttr", ".", "respond_to?", "(", ":queue_respond_timeout", ")", "resolve_respond_timeout", "(", "ttr", ".", "queue_respond_timeout", ")", "elsif", "ttr", ".", "is_a?", "(", "Integer", ")", "ttr", "else", "Backburner", ".", "configuration", ".", "respond_timeout", "end", "end" ]
Resolves job respond timeout based on the value given. Can be integer, a class or nothing @example resolve_respond_timeout(1000) => 1000 resolve_respond_timeout(FooBar) => <queue respond_timeout> resolve_respond_timeout(nil) => <default respond_timeout>
[ "Resolves", "job", "respond", "timeout", "based", "on", "the", "value", "given", ".", "Can", "be", "integer", "a", "class", "or", "nothing" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/helpers.rb#L131-L139
train
nesquena/backburner
lib/backburner/worker.rb
Backburner.Worker.work_one_job
def work_one_job(conn = connection) begin job = reserve_job(conn) rescue Beaneater::TimedOutError => e return end self.log_job_begin(job.name, job.args) job.process self.log_job_end(job.name) rescue Backburner::Job::JobFormatInvalid => e self.log_error self.exception_message(e) rescue => e # Error occurred processing job self.log_error self.exception_message(e) unless e.is_a?(Backburner::Job::RetryJob) unless job self.log_error "Error occurred before we were able to assign a job. Giving up without retrying!" return end # NB: There's a slight chance here that the connection to beanstalkd has # gone down between the time we reserved / processed the job and here. num_retries = job.stats.releases retry_status = "failed: attempt #{num_retries+1} of #{queue_config.max_job_retries+1}" if num_retries < queue_config.max_job_retries # retry again delay = queue_config.retry_delay_proc.call(queue_config.retry_delay, num_retries) rescue queue_config.retry_delay job.retry(num_retries + 1, delay) self.log_job_end(job.name, "#{retry_status}, retrying in #{delay}s") if job_started_at else # retries failed, bury job.bury self.log_job_end(job.name, "#{retry_status}, burying") if job_started_at end handle_error(e, job.name, job.args, job) end
ruby
def work_one_job(conn = connection) begin job = reserve_job(conn) rescue Beaneater::TimedOutError => e return end self.log_job_begin(job.name, job.args) job.process self.log_job_end(job.name) rescue Backburner::Job::JobFormatInvalid => e self.log_error self.exception_message(e) rescue => e # Error occurred processing job self.log_error self.exception_message(e) unless e.is_a?(Backburner::Job::RetryJob) unless job self.log_error "Error occurred before we were able to assign a job. Giving up without retrying!" return end # NB: There's a slight chance here that the connection to beanstalkd has # gone down between the time we reserved / processed the job and here. num_retries = job.stats.releases retry_status = "failed: attempt #{num_retries+1} of #{queue_config.max_job_retries+1}" if num_retries < queue_config.max_job_retries # retry again delay = queue_config.retry_delay_proc.call(queue_config.retry_delay, num_retries) rescue queue_config.retry_delay job.retry(num_retries + 1, delay) self.log_job_end(job.name, "#{retry_status}, retrying in #{delay}s") if job_started_at else # retries failed, bury job.bury self.log_job_end(job.name, "#{retry_status}, burying") if job_started_at end handle_error(e, job.name, job.args, job) end
[ "def", "work_one_job", "(", "conn", "=", "connection", ")", "begin", "job", "=", "reserve_job", "(", "conn", ")", "rescue", "Beaneater", "::", "TimedOutError", "=>", "e", "return", "end", "self", ".", "log_job_begin", "(", "job", ".", "name", ",", "job", ".", "args", ")", "job", ".", "process", "self", ".", "log_job_end", "(", "job", ".", "name", ")", "rescue", "Backburner", "::", "Job", "::", "JobFormatInvalid", "=>", "e", "self", ".", "log_error", "self", ".", "exception_message", "(", "e", ")", "rescue", "=>", "e", "self", ".", "log_error", "self", ".", "exception_message", "(", "e", ")", "unless", "e", ".", "is_a?", "(", "Backburner", "::", "Job", "::", "RetryJob", ")", "unless", "job", "self", ".", "log_error", "\"Error occurred before we were able to assign a job. Giving up without retrying!\"", "return", "end", "num_retries", "=", "job", ".", "stats", ".", "releases", "retry_status", "=", "\"failed: attempt #{num_retries+1} of #{queue_config.max_job_retries+1}\"", "if", "num_retries", "<", "queue_config", ".", "max_job_retries", "delay", "=", "queue_config", ".", "retry_delay_proc", ".", "call", "(", "queue_config", ".", "retry_delay", ",", "num_retries", ")", "rescue", "queue_config", ".", "retry_delay", "job", ".", "retry", "(", "num_retries", "+", "1", ",", "delay", ")", "self", ".", "log_job_end", "(", "job", ".", "name", ",", "\"#{retry_status}, retrying in #{delay}s\"", ")", "if", "job_started_at", "else", "job", ".", "bury", "self", ".", "log_job_end", "(", "job", ".", "name", ",", "\"#{retry_status}, burying\"", ")", "if", "job_started_at", "end", "handle_error", "(", "e", ",", "job", ".", "name", ",", "job", ".", "args", ",", "job", ")", "end" ]
Performs a job by reserving a job from beanstalk and processing it @example @worker.work_one_job @raise [Beaneater::NotConnected] If beanstalk fails to connect multiple times.
[ "Performs", "a", "job", "by", "reserving", "a", "job", "from", "beanstalk", "and", "processing", "it" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/worker.rb#L129-L164
train
nesquena/backburner
lib/backburner/worker.rb
Backburner.Worker.new_connection
def new_connection Connection.new(Backburner.configuration.beanstalk_url) { |conn| Backburner::Hooks.invoke_hook_events(self, :on_reconnect, conn) } end
ruby
def new_connection Connection.new(Backburner.configuration.beanstalk_url) { |conn| Backburner::Hooks.invoke_hook_events(self, :on_reconnect, conn) } end
[ "def", "new_connection", "Connection", ".", "new", "(", "Backburner", ".", "configuration", ".", "beanstalk_url", ")", "{", "|", "conn", "|", "Backburner", "::", "Hooks", ".", "invoke_hook_events", "(", "self", ",", ":on_reconnect", ",", "conn", ")", "}", "end" ]
Return a new connection instance
[ "Return", "a", "new", "connection", "instance" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/worker.rb#L170-L172
train
nesquena/backburner
lib/backburner/worker.rb
Backburner.Worker.reserve_job
def reserve_job(conn, reserve_timeout = Backburner.configuration.reserve_timeout) Backburner::Job.new(conn.tubes.reserve(reserve_timeout)) end
ruby
def reserve_job(conn, reserve_timeout = Backburner.configuration.reserve_timeout) Backburner::Job.new(conn.tubes.reserve(reserve_timeout)) end
[ "def", "reserve_job", "(", "conn", ",", "reserve_timeout", "=", "Backburner", ".", "configuration", ".", "reserve_timeout", ")", "Backburner", "::", "Job", ".", "new", "(", "conn", ".", "tubes", ".", "reserve", "(", "reserve_timeout", ")", ")", "end" ]
Reserve a job from the watched queues
[ "Reserve", "a", "job", "from", "the", "watched", "queues" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/worker.rb#L175-L177
train
nesquena/backburner
lib/backburner/worker.rb
Backburner.Worker.handle_error
def handle_error(e, name, args, job) if error_handler = Backburner.configuration.on_error if error_handler.arity == 1 error_handler.call(e) elsif error_handler.arity == 3 error_handler.call(e, name, args) else error_handler.call(e, name, args, job) end end end
ruby
def handle_error(e, name, args, job) if error_handler = Backburner.configuration.on_error if error_handler.arity == 1 error_handler.call(e) elsif error_handler.arity == 3 error_handler.call(e, name, args) else error_handler.call(e, name, args, job) end end end
[ "def", "handle_error", "(", "e", ",", "name", ",", "args", ",", "job", ")", "if", "error_handler", "=", "Backburner", ".", "configuration", ".", "on_error", "if", "error_handler", ".", "arity", "==", "1", "error_handler", ".", "call", "(", "e", ")", "elsif", "error_handler", ".", "arity", "==", "3", "error_handler", ".", "call", "(", "e", ",", "name", ",", "args", ")", "else", "error_handler", ".", "call", "(", "e", ",", "name", ",", "args", ",", "job", ")", "end", "end", "end" ]
Handles an error according to custom definition Used when processing a job that errors out
[ "Handles", "an", "error", "according", "to", "custom", "definition", "Used", "when", "processing", "a", "job", "that", "errors", "out" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/worker.rb#L190-L200
train
nesquena/backburner
lib/backburner/worker.rb
Backburner.Worker.compact_tube_names
def compact_tube_names(tube_names) tube_names = tube_names.first if tube_names && tube_names.size == 1 && tube_names.first.is_a?(Array) tube_names = Array(tube_names).compact if tube_names && Array(tube_names).compact.size > 0 tube_names = nil if tube_names && tube_names.compact.empty? tube_names ||= Backburner.default_queues.any? ? Backburner.default_queues : all_existing_queues Array(tube_names).uniq end
ruby
def compact_tube_names(tube_names) tube_names = tube_names.first if tube_names && tube_names.size == 1 && tube_names.first.is_a?(Array) tube_names = Array(tube_names).compact if tube_names && Array(tube_names).compact.size > 0 tube_names = nil if tube_names && tube_names.compact.empty? tube_names ||= Backburner.default_queues.any? ? Backburner.default_queues : all_existing_queues Array(tube_names).uniq end
[ "def", "compact_tube_names", "(", "tube_names", ")", "tube_names", "=", "tube_names", ".", "first", "if", "tube_names", "&&", "tube_names", ".", "size", "==", "1", "&&", "tube_names", ".", "first", ".", "is_a?", "(", "Array", ")", "tube_names", "=", "Array", "(", "tube_names", ")", ".", "compact", "if", "tube_names", "&&", "Array", "(", "tube_names", ")", ".", "compact", ".", "size", ">", "0", "tube_names", "=", "nil", "if", "tube_names", "&&", "tube_names", ".", "compact", ".", "empty?", "tube_names", "||=", "Backburner", ".", "default_queues", ".", "any?", "?", "Backburner", ".", "default_queues", ":", "all_existing_queues", "Array", "(", "tube_names", ")", ".", "uniq", "end" ]
Normalizes tube names given array of tube_names Compacts nil items, flattens arrays, sets tubes to nil if no valid names Loads default tubes when no tubes given.
[ "Normalizes", "tube", "names", "given", "array", "of", "tube_names", "Compacts", "nil", "items", "flattens", "arrays", "sets", "tubes", "to", "nil", "if", "no", "valid", "names", "Loads", "default", "tubes", "when", "no", "tubes", "given", "." ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/worker.rb#L205-L211
train
nesquena/backburner
lib/backburner/logger.rb
Backburner.Logger.log_job_end
def log_job_end(name, message = nil) ellapsed = Time.now - job_started_at ms = (ellapsed.to_f * 1000).to_i action_word = message ? 'Finished' : 'Completed' log_info("#{action_word} #{name} in #{ms}ms #{message}") end
ruby
def log_job_end(name, message = nil) ellapsed = Time.now - job_started_at ms = (ellapsed.to_f * 1000).to_i action_word = message ? 'Finished' : 'Completed' log_info("#{action_word} #{name} in #{ms}ms #{message}") end
[ "def", "log_job_end", "(", "name", ",", "message", "=", "nil", ")", "ellapsed", "=", "Time", ".", "now", "-", "job_started_at", "ms", "=", "(", "ellapsed", ".", "to_f", "*", "1000", ")", ".", "to_i", "action_word", "=", "message", "?", "'Finished'", ":", "'Completed'", "log_info", "(", "\"#{action_word} #{name} in #{ms}ms #{message}\"", ")", "end" ]
Print out when a job completed If message is nil, job is considered complete
[ "Print", "out", "when", "a", "job", "completed", "If", "message", "is", "nil", "job", "is", "considered", "complete" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/logger.rb#L18-L23
train
nesquena/backburner
lib/backburner/job.rb
Backburner.Job.process
def process # Invoke before hook and stop if false res = @hooks.invoke_hook_events(job_name, :before_perform, *args) return false unless res # Execute the job @hooks.around_hook_events(job_name, :around_perform, *args) do # We subtract one to ensure we timeout before beanstalkd does, except if: # a) ttr == 0, to support never timing out # b) ttr == 1, so that we don't accidentally set it to never time out # NB: A ttr of 1 will likely result in race conditions between # Backburner and beanstalkd and should probably be avoided timeout_job_after(task.ttr > 1 ? task.ttr - 1 : task.ttr) { job_class.perform(*args) } end task.delete # Invoke after perform hook @hooks.invoke_hook_events(job_name, :after_perform, *args) rescue => e @hooks.invoke_hook_events(job_name, :on_failure, e, *args) raise e end
ruby
def process # Invoke before hook and stop if false res = @hooks.invoke_hook_events(job_name, :before_perform, *args) return false unless res # Execute the job @hooks.around_hook_events(job_name, :around_perform, *args) do # We subtract one to ensure we timeout before beanstalkd does, except if: # a) ttr == 0, to support never timing out # b) ttr == 1, so that we don't accidentally set it to never time out # NB: A ttr of 1 will likely result in race conditions between # Backburner and beanstalkd and should probably be avoided timeout_job_after(task.ttr > 1 ? task.ttr - 1 : task.ttr) { job_class.perform(*args) } end task.delete # Invoke after perform hook @hooks.invoke_hook_events(job_name, :after_perform, *args) rescue => e @hooks.invoke_hook_events(job_name, :on_failure, e, *args) raise e end
[ "def", "process", "res", "=", "@hooks", ".", "invoke_hook_events", "(", "job_name", ",", ":before_perform", ",", "*", "args", ")", "return", "false", "unless", "res", "@hooks", ".", "around_hook_events", "(", "job_name", ",", ":around_perform", ",", "*", "args", ")", "do", "timeout_job_after", "(", "task", ".", "ttr", ">", "1", "?", "task", ".", "ttr", "-", "1", ":", "task", ".", "ttr", ")", "{", "job_class", ".", "perform", "(", "*", "args", ")", "}", "end", "task", ".", "delete", "@hooks", ".", "invoke_hook_events", "(", "job_name", ",", ":after_perform", ",", "*", "args", ")", "rescue", "=>", "e", "@hooks", ".", "invoke_hook_events", "(", "job_name", ",", ":on_failure", ",", "e", ",", "*", "args", ")", "raise", "e", "end" ]
Processes a job and handles any failure, deleting the job once complete @example @task.process
[ "Processes", "a", "job", "and", "handles", "any", "failure", "deleting", "the", "job", "once", "complete" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/job.rb#L45-L64
train
nesquena/backburner
lib/backburner/job.rb
Backburner.Job.timeout_job_after
def timeout_job_after(secs, &block) begin Timeout::timeout(secs) { yield } rescue Timeout::Error => e raise JobTimeout, "#{name}(#{(@args||[]).join(', ')}) hit #{secs}s timeout.\nbacktrace: #{e.backtrace}" end end
ruby
def timeout_job_after(secs, &block) begin Timeout::timeout(secs) { yield } rescue Timeout::Error => e raise JobTimeout, "#{name}(#{(@args||[]).join(', ')}) hit #{secs}s timeout.\nbacktrace: #{e.backtrace}" end end
[ "def", "timeout_job_after", "(", "secs", ",", "&", "block", ")", "begin", "Timeout", "::", "timeout", "(", "secs", ")", "{", "yield", "}", "rescue", "Timeout", "::", "Error", "=>", "e", "raise", "JobTimeout", ",", "\"#{name}(#{(@args||[]).join(', ')}) hit #{secs}s timeout.\\nbacktrace: #{e.backtrace}\"", "end", "end" ]
Timeout job within specified block after given time. @example timeout_job_after(3) { do_something! }
[ "Timeout", "job", "within", "specified", "block", "after", "given", "time", "." ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/job.rb#L109-L115
train
nesquena/backburner
lib/backburner/connection.rb
Backburner.Connection.retryable
def retryable(options = {}, &block) options = {:max_retries => 4, :on_retry => nil, :retry_delay => 1.0}.merge!(options) retry_count = options[:max_retries] begin yield rescue Beaneater::NotConnected if retry_count > 0 reconnect! retry_count -= 1 sleep options[:retry_delay] options[:on_retry].call if options[:on_retry].respond_to?(:call) retry else # stop retrying raise e end end end
ruby
def retryable(options = {}, &block) options = {:max_retries => 4, :on_retry => nil, :retry_delay => 1.0}.merge!(options) retry_count = options[:max_retries] begin yield rescue Beaneater::NotConnected if retry_count > 0 reconnect! retry_count -= 1 sleep options[:retry_delay] options[:on_retry].call if options[:on_retry].respond_to?(:call) retry else # stop retrying raise e end end end
[ "def", "retryable", "(", "options", "=", "{", "}", ",", "&", "block", ")", "options", "=", "{", ":max_retries", "=>", "4", ",", ":on_retry", "=>", "nil", ",", ":retry_delay", "=>", "1.0", "}", ".", "merge!", "(", "options", ")", "retry_count", "=", "options", "[", ":max_retries", "]", "begin", "yield", "rescue", "Beaneater", "::", "NotConnected", "if", "retry_count", ">", "0", "reconnect!", "retry_count", "-=", "1", "sleep", "options", "[", ":retry_delay", "]", "options", "[", ":on_retry", "]", ".", "call", "if", "options", "[", ":on_retry", "]", ".", "respond_to?", "(", ":call", ")", "retry", "else", "raise", "e", "end", "end", "end" ]
Yield to a block that will be retried several times if the connection to beanstalk goes down and is able to be re-established. @param options Hash Options. Valid options are: :max_retries Integer The maximum number of times the block will be yielded to. Defaults to 4 :on_retry Proc An optional proc that will be called for each retry. Will be called after the connection is re-established and :retry_delay has passed but before the block is yielded to again :retry_delay Float The amount to sleep before retrying. Defaults to 1.0 @raise Beaneater::NotConnected If a connection is unable to be re-established
[ "Yield", "to", "a", "block", "that", "will", "be", "retried", "several", "times", "if", "the", "connection", "to", "beanstalk", "goes", "down", "and", "is", "able", "to", "be", "re", "-", "established", "." ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/connection.rb#L63-L81
train
nesquena/backburner
lib/backburner/connection.rb
Backburner.Connection.ensure_connected!
def ensure_connected!(max_retries = 4, retry_delay = 1.0) return self if connected? begin reconnect! return self rescue Beaneater::NotConnected => e if max_retries > 0 max_retries -= 1 sleep retry_delay retry else # stop retrying raise e end end end
ruby
def ensure_connected!(max_retries = 4, retry_delay = 1.0) return self if connected? begin reconnect! return self rescue Beaneater::NotConnected => e if max_retries > 0 max_retries -= 1 sleep retry_delay retry else # stop retrying raise e end end end
[ "def", "ensure_connected!", "(", "max_retries", "=", "4", ",", "retry_delay", "=", "1.0", ")", "return", "self", "if", "connected?", "begin", "reconnect!", "return", "self", "rescue", "Beaneater", "::", "NotConnected", "=>", "e", "if", "max_retries", ">", "0", "max_retries", "-=", "1", "sleep", "retry_delay", "retry", "else", "raise", "e", "end", "end", "end" ]
Attempts to ensure a connection to beanstalk is established but only if we're not connected already @param max_retries Integer The maximum number of times to attempt connecting. Defaults to 4 @param retry_delay Float The time to wait between retrying to connect. Defaults to 1.0 @raise [Beaneater::NotConnected] If beanstalk fails to connect after multiple attempts. @return Connection This Connection is returned if the connection to beanstalk is open or was able to be reconnected
[ "Attempts", "to", "ensure", "a", "connection", "to", "beanstalk", "is", "established", "but", "only", "if", "we", "re", "not", "connected", "already" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/connection.rb#L107-L123
train
nesquena/backburner
lib/backburner/connection.rb
Backburner.Connection.beanstalk_addresses
def beanstalk_addresses uri = self.url.is_a?(Array) ? self.url.first : self.url beanstalk_host_and_port(uri) end
ruby
def beanstalk_addresses uri = self.url.is_a?(Array) ? self.url.first : self.url beanstalk_host_and_port(uri) end
[ "def", "beanstalk_addresses", "uri", "=", "self", ".", "url", ".", "is_a?", "(", "Array", ")", "?", "self", ".", "url", ".", "first", ":", "self", ".", "url", "beanstalk_host_and_port", "(", "uri", ")", "end" ]
Returns the beanstalk queue addresses @example beanstalk_addresses => ["127.0.0.1:11300"]
[ "Returns", "the", "beanstalk", "queue", "addresses" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/connection.rb#L130-L133
train
nesquena/backburner
lib/backburner/connection.rb
Backburner.Connection.beanstalk_host_and_port
def beanstalk_host_and_port(uri_string) uri = URI.parse(uri_string) raise(BadURL, uri_string) if uri.scheme != 'beanstalk'.freeze "#{uri.host}:#{uri.port || 11300}" end
ruby
def beanstalk_host_and_port(uri_string) uri = URI.parse(uri_string) raise(BadURL, uri_string) if uri.scheme != 'beanstalk'.freeze "#{uri.host}:#{uri.port || 11300}" end
[ "def", "beanstalk_host_and_port", "(", "uri_string", ")", "uri", "=", "URI", ".", "parse", "(", "uri_string", ")", "raise", "(", "BadURL", ",", "uri_string", ")", "if", "uri", ".", "scheme", "!=", "'beanstalk'", ".", "freeze", "\"#{uri.host}:#{uri.port || 11300}\"", "end" ]
Returns a host and port based on the uri_string given @example beanstalk_host_and_port("beanstalk://127.0.0.1") => "127.0.0.1:11300"
[ "Returns", "a", "host", "and", "port", "based", "on", "the", "uri_string", "given" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/connection.rb#L140-L144
train
arvindvyas/Country-State-Select
app/controllers/country_state_select/cscs_controller.rb
CountryStateSelect.CscsController.find_cities
def find_cities cities = CS.cities(params[:state_id].to_sym, params[:country_id].to_sym) respond_to do |format| format.json { render :json => cities.to_a} end end
ruby
def find_cities cities = CS.cities(params[:state_id].to_sym, params[:country_id].to_sym) respond_to do |format| format.json { render :json => cities.to_a} end end
[ "def", "find_cities", "cities", "=", "CS", ".", "cities", "(", "params", "[", ":state_id", "]", ".", "to_sym", ",", "params", "[", ":country_id", "]", ".", "to_sym", ")", "respond_to", "do", "|", "format", "|", "format", ".", "json", "{", "render", ":json", "=>", "cities", ".", "to_a", "}", "end", "end" ]
Sent it to state_id and country id it will return cities of that states
[ "Sent", "it", "to", "state_id", "and", "country", "id", "it", "will", "return", "cities", "of", "that", "states" ]
2c91757ccebe3d1a335a87cf5da1c8241ac38437
https://github.com/arvindvyas/Country-State-Select/blob/2c91757ccebe3d1a335a87cf5da1c8241ac38437/app/controllers/country_state_select/cscs_controller.rb#L13-L19
train
comfy/comfy-bootstrap-form
lib/comfy_bootstrap_form/form_builder.rb
ComfyBootstrapForm.FormBuilder.file_field
def file_field(method, options = {}) bootstrap = form_bootstrap.scoped(options.delete(:bootstrap)) return super if bootstrap.disabled draw_form_group(bootstrap, method, options) do if bootstrap.custom_control content_tag(:div, class: "custom-file") do add_css_class!(options, "custom-file-input") remove_css_class!(options, "form-control") label_text = options.delete(:placeholder) concat super(method, options) label_options = { class: "custom-file-label" } label_options[:for] = options[:id] if options[:id].present? concat label(method, label_text, label_options) end else super(method, options) end end end
ruby
def file_field(method, options = {}) bootstrap = form_bootstrap.scoped(options.delete(:bootstrap)) return super if bootstrap.disabled draw_form_group(bootstrap, method, options) do if bootstrap.custom_control content_tag(:div, class: "custom-file") do add_css_class!(options, "custom-file-input") remove_css_class!(options, "form-control") label_text = options.delete(:placeholder) concat super(method, options) label_options = { class: "custom-file-label" } label_options[:for] = options[:id] if options[:id].present? concat label(method, label_text, label_options) end else super(method, options) end end end
[ "def", "file_field", "(", "method", ",", "options", "=", "{", "}", ")", "bootstrap", "=", "form_bootstrap", ".", "scoped", "(", "options", ".", "delete", "(", ":bootstrap", ")", ")", "return", "super", "if", "bootstrap", ".", "disabled", "draw_form_group", "(", "bootstrap", ",", "method", ",", "options", ")", "do", "if", "bootstrap", ".", "custom_control", "content_tag", "(", ":div", ",", "class", ":", "\"custom-file\"", ")", "do", "add_css_class!", "(", "options", ",", "\"custom-file-input\"", ")", "remove_css_class!", "(", "options", ",", "\"form-control\"", ")", "label_text", "=", "options", ".", "delete", "(", ":placeholder", ")", "concat", "super", "(", "method", ",", "options", ")", "label_options", "=", "{", "class", ":", "\"custom-file-label\"", "}", "label_options", "[", ":for", "]", "=", "options", "[", ":id", "]", "if", "options", "[", ":id", "]", ".", "present?", "concat", "label", "(", "method", ",", "label_text", ",", "label_options", ")", "end", "else", "super", "(", "method", ",", "options", ")", "end", "end", "end" ]
Wrapper for file_field helper. It can accept `custom_control` option. file_field :photo, bootstrap: {custom_control: true}
[ "Wrapper", "for", "file_field", "helper", ".", "It", "can", "accept", "custom_control", "option", "." ]
461d5cbd552469eb95e35fbcbed03d13ec702ef7
https://github.com/comfy/comfy-bootstrap-form/blob/461d5cbd552469eb95e35fbcbed03d13ec702ef7/lib/comfy_bootstrap_form/form_builder.rb#L89-L109
train
comfy/comfy-bootstrap-form
lib/comfy_bootstrap_form/form_builder.rb
ComfyBootstrapForm.FormBuilder.plaintext
def plaintext(method, options = {}) bootstrap = form_bootstrap.scoped(options.delete(:bootstrap)) draw_form_group(bootstrap, method, options) do remove_css_class!(options, "form-control") add_css_class!(options, "form-control-plaintext") options[:readonly] = true ActionView::Helpers::FormBuilder.instance_method(:text_field).bind(self).call(method, options) end end
ruby
def plaintext(method, options = {}) bootstrap = form_bootstrap.scoped(options.delete(:bootstrap)) draw_form_group(bootstrap, method, options) do remove_css_class!(options, "form-control") add_css_class!(options, "form-control-plaintext") options[:readonly] = true ActionView::Helpers::FormBuilder.instance_method(:text_field).bind(self).call(method, options) end end
[ "def", "plaintext", "(", "method", ",", "options", "=", "{", "}", ")", "bootstrap", "=", "form_bootstrap", ".", "scoped", "(", "options", ".", "delete", "(", ":bootstrap", ")", ")", "draw_form_group", "(", "bootstrap", ",", "method", ",", "options", ")", "do", "remove_css_class!", "(", "options", ",", "\"form-control\"", ")", "add_css_class!", "(", "options", ",", "\"form-control-plaintext\"", ")", "options", "[", ":readonly", "]", "=", "true", "ActionView", "::", "Helpers", "::", "FormBuilder", ".", "instance_method", "(", ":text_field", ")", ".", "bind", "(", "self", ")", ".", "call", "(", "method", ",", "options", ")", "end", "end" ]
Bootstrap wrapper for readonly text field that is shown as plain text. plaintext(:value)
[ "Bootstrap", "wrapper", "for", "readonly", "text", "field", "that", "is", "shown", "as", "plain", "text", "." ]
461d5cbd552469eb95e35fbcbed03d13ec702ef7
https://github.com/comfy/comfy-bootstrap-form/blob/461d5cbd552469eb95e35fbcbed03d13ec702ef7/lib/comfy_bootstrap_form/form_builder.rb#L204-L212
train
comfy/comfy-bootstrap-form
lib/comfy_bootstrap_form/form_builder.rb
ComfyBootstrapForm.FormBuilder.primary
def primary(value = nil, options = {}, &block) add_css_class!(options, "btn-primary") submit(value, options, &block) end
ruby
def primary(value = nil, options = {}, &block) add_css_class!(options, "btn-primary") submit(value, options, &block) end
[ "def", "primary", "(", "value", "=", "nil", ",", "options", "=", "{", "}", ",", "&", "block", ")", "add_css_class!", "(", "options", ",", "\"btn-primary\"", ")", "submit", "(", "value", ",", "options", ",", "&", "block", ")", "end" ]
Same as submit button, only with btn-primary class added
[ "Same", "as", "submit", "button", "only", "with", "btn", "-", "primary", "class", "added" ]
461d5cbd552469eb95e35fbcbed03d13ec702ef7
https://github.com/comfy/comfy-bootstrap-form/blob/461d5cbd552469eb95e35fbcbed03d13ec702ef7/lib/comfy_bootstrap_form/form_builder.rb#L250-L253
train
comfy/comfy-bootstrap-form
lib/comfy_bootstrap_form/form_builder.rb
ComfyBootstrapForm.FormBuilder.draw_form_group
def draw_form_group(bootstrap, method, options) label = draw_label(bootstrap, method, for_attr: options[:id]) errors = draw_errors(method) control = draw_control(bootstrap, errors, method, options) do yield end form_group_class = "form-group" form_group_class += " row" if bootstrap.horizontal? form_group_class += " mr-sm-2" if bootstrap.inline? content_tag(:div, class: form_group_class) do concat label concat control end end
ruby
def draw_form_group(bootstrap, method, options) label = draw_label(bootstrap, method, for_attr: options[:id]) errors = draw_errors(method) control = draw_control(bootstrap, errors, method, options) do yield end form_group_class = "form-group" form_group_class += " row" if bootstrap.horizontal? form_group_class += " mr-sm-2" if bootstrap.inline? content_tag(:div, class: form_group_class) do concat label concat control end end
[ "def", "draw_form_group", "(", "bootstrap", ",", "method", ",", "options", ")", "label", "=", "draw_label", "(", "bootstrap", ",", "method", ",", "for_attr", ":", "options", "[", ":id", "]", ")", "errors", "=", "draw_errors", "(", "method", ")", "control", "=", "draw_control", "(", "bootstrap", ",", "errors", ",", "method", ",", "options", ")", "do", "yield", "end", "form_group_class", "=", "\"form-group\"", "form_group_class", "+=", "\" row\"", "if", "bootstrap", ".", "horizontal?", "form_group_class", "+=", "\" mr-sm-2\"", "if", "bootstrap", ".", "inline?", "content_tag", "(", ":div", ",", "class", ":", "form_group_class", ")", "do", "concat", "label", "concat", "control", "end", "end" ]
form group wrapper for input fields
[ "form", "group", "wrapper", "for", "input", "fields" ]
461d5cbd552469eb95e35fbcbed03d13ec702ef7
https://github.com/comfy/comfy-bootstrap-form/blob/461d5cbd552469eb95e35fbcbed03d13ec702ef7/lib/comfy_bootstrap_form/form_builder.rb#L297-L313
train
comfy/comfy-bootstrap-form
lib/comfy_bootstrap_form/form_builder.rb
ComfyBootstrapForm.FormBuilder.draw_control
def draw_control(bootstrap, errors, _method, options) add_css_class!(options, "form-control") add_css_class!(options, "is-invalid") if errors.present? draw_control_column(bootstrap, offset: bootstrap.label[:hide]) do draw_input_group(bootstrap, errors) do yield end end end
ruby
def draw_control(bootstrap, errors, _method, options) add_css_class!(options, "form-control") add_css_class!(options, "is-invalid") if errors.present? draw_control_column(bootstrap, offset: bootstrap.label[:hide]) do draw_input_group(bootstrap, errors) do yield end end end
[ "def", "draw_control", "(", "bootstrap", ",", "errors", ",", "_method", ",", "options", ")", "add_css_class!", "(", "options", ",", "\"form-control\"", ")", "add_css_class!", "(", "options", ",", "\"is-invalid\"", ")", "if", "errors", ".", "present?", "draw_control_column", "(", "bootstrap", ",", "offset", ":", "bootstrap", ".", "label", "[", ":hide", "]", ")", "do", "draw_input_group", "(", "bootstrap", ",", "errors", ")", "do", "yield", "end", "end", "end" ]
Renders control for a given field
[ "Renders", "control", "for", "a", "given", "field" ]
461d5cbd552469eb95e35fbcbed03d13ec702ef7
https://github.com/comfy/comfy-bootstrap-form/blob/461d5cbd552469eb95e35fbcbed03d13ec702ef7/lib/comfy_bootstrap_form/form_builder.rb#L357-L366
train
comfy/comfy-bootstrap-form
lib/comfy_bootstrap_form/form_builder.rb
ComfyBootstrapForm.FormBuilder.draw_control_column
def draw_control_column(bootstrap, offset:) return yield unless bootstrap.horizontal? css_class = bootstrap.control_col_class.to_s css_class += " #{bootstrap.offset_col_class}" if offset content_tag(:div, class: css_class) do yield end end
ruby
def draw_control_column(bootstrap, offset:) return yield unless bootstrap.horizontal? css_class = bootstrap.control_col_class.to_s css_class += " #{bootstrap.offset_col_class}" if offset content_tag(:div, class: css_class) do yield end end
[ "def", "draw_control_column", "(", "bootstrap", ",", "offset", ":", ")", "return", "yield", "unless", "bootstrap", ".", "horizontal?", "css_class", "=", "bootstrap", ".", "control_col_class", ".", "to_s", "css_class", "+=", "\" #{bootstrap.offset_col_class}\"", "if", "offset", "content_tag", "(", ":div", ",", "class", ":", "css_class", ")", "do", "yield", "end", "end" ]
Wrapping in control in column wrapper
[ "Wrapping", "in", "control", "in", "column", "wrapper" ]
461d5cbd552469eb95e35fbcbed03d13ec702ef7
https://github.com/comfy/comfy-bootstrap-form/blob/461d5cbd552469eb95e35fbcbed03d13ec702ef7/lib/comfy_bootstrap_form/form_builder.rb#L370-L377
train
comfy/comfy-bootstrap-form
lib/comfy_bootstrap_form/form_builder.rb
ComfyBootstrapForm.FormBuilder.draw_form_group_fieldset
def draw_form_group_fieldset(bootstrap, method) options = {} unless bootstrap.label[:hide] label_text = bootstrap.label[:text] label_text ||= ActionView::Helpers::Tags::Label::LabelBuilder .new(@template, @object_name.to_s, method, @object, nil).translation add_css_class!(options, "col-form-label pt-0") add_css_class!(options, bootstrap.label[:class]) if bootstrap.horizontal? add_css_class!(options, bootstrap.label_col_class) add_css_class!(options, bootstrap.label_align_class) end label = content_tag(:legend, options) do label_text end end content_tag(:fieldset, class: "form-group") do content = "".html_safe content << label if label.present? content << draw_control_column(bootstrap, offset: bootstrap.label[:hide]) do yield end if bootstrap.horizontal? content_tag(:div, content, class: "row") else content end end end
ruby
def draw_form_group_fieldset(bootstrap, method) options = {} unless bootstrap.label[:hide] label_text = bootstrap.label[:text] label_text ||= ActionView::Helpers::Tags::Label::LabelBuilder .new(@template, @object_name.to_s, method, @object, nil).translation add_css_class!(options, "col-form-label pt-0") add_css_class!(options, bootstrap.label[:class]) if bootstrap.horizontal? add_css_class!(options, bootstrap.label_col_class) add_css_class!(options, bootstrap.label_align_class) end label = content_tag(:legend, options) do label_text end end content_tag(:fieldset, class: "form-group") do content = "".html_safe content << label if label.present? content << draw_control_column(bootstrap, offset: bootstrap.label[:hide]) do yield end if bootstrap.horizontal? content_tag(:div, content, class: "row") else content end end end
[ "def", "draw_form_group_fieldset", "(", "bootstrap", ",", "method", ")", "options", "=", "{", "}", "unless", "bootstrap", ".", "label", "[", ":hide", "]", "label_text", "=", "bootstrap", ".", "label", "[", ":text", "]", "label_text", "||=", "ActionView", "::", "Helpers", "::", "Tags", "::", "Label", "::", "LabelBuilder", ".", "new", "(", "@template", ",", "@object_name", ".", "to_s", ",", "method", ",", "@object", ",", "nil", ")", ".", "translation", "add_css_class!", "(", "options", ",", "\"col-form-label pt-0\"", ")", "add_css_class!", "(", "options", ",", "bootstrap", ".", "label", "[", ":class", "]", ")", "if", "bootstrap", ".", "horizontal?", "add_css_class!", "(", "options", ",", "bootstrap", ".", "label_col_class", ")", "add_css_class!", "(", "options", ",", "bootstrap", ".", "label_align_class", ")", "end", "label", "=", "content_tag", "(", ":legend", ",", "options", ")", "do", "label_text", "end", "end", "content_tag", "(", ":fieldset", ",", "class", ":", "\"form-group\"", ")", "do", "content", "=", "\"\"", ".", "html_safe", "content", "<<", "label", "if", "label", ".", "present?", "content", "<<", "draw_control_column", "(", "bootstrap", ",", "offset", ":", "bootstrap", ".", "label", "[", ":hide", "]", ")", "do", "yield", "end", "if", "bootstrap", ".", "horizontal?", "content_tag", "(", ":div", ",", "content", ",", "class", ":", "\"row\"", ")", "else", "content", "end", "end", "end" ]
Wrapper for collections of radio buttons and checkboxes
[ "Wrapper", "for", "collections", "of", "radio", "buttons", "and", "checkboxes" ]
461d5cbd552469eb95e35fbcbed03d13ec702ef7
https://github.com/comfy/comfy-bootstrap-form/blob/461d5cbd552469eb95e35fbcbed03d13ec702ef7/lib/comfy_bootstrap_form/form_builder.rb#L488-L522
train
comfy/comfy-bootstrap-form
lib/comfy_bootstrap_form/view_helper.rb
ComfyBootstrapForm.ViewHelper.bootstrap_form_with
def bootstrap_form_with(**options, &block) bootstrap_options = options[:bootstrap] || {} css_classes = options.delete(:class) if bootstrap_options[:layout].to_s == "inline" css_classes = [css_classes, "form-inline"].compact.join(" ") end form_options = options.reverse_merge(builder: ComfyBootstrapForm::FormBuilder) form_options.merge!(class: css_classes) unless css_classes.blank? supress_form_field_errors do form_with(**form_options, &block) end end
ruby
def bootstrap_form_with(**options, &block) bootstrap_options = options[:bootstrap] || {} css_classes = options.delete(:class) if bootstrap_options[:layout].to_s == "inline" css_classes = [css_classes, "form-inline"].compact.join(" ") end form_options = options.reverse_merge(builder: ComfyBootstrapForm::FormBuilder) form_options.merge!(class: css_classes) unless css_classes.blank? supress_form_field_errors do form_with(**form_options, &block) end end
[ "def", "bootstrap_form_with", "(", "**", "options", ",", "&", "block", ")", "bootstrap_options", "=", "options", "[", ":bootstrap", "]", "||", "{", "}", "css_classes", "=", "options", ".", "delete", "(", ":class", ")", "if", "bootstrap_options", "[", ":layout", "]", ".", "to_s", "==", "\"inline\"", "css_classes", "=", "[", "css_classes", ",", "\"form-inline\"", "]", ".", "compact", ".", "join", "(", "\" \"", ")", "end", "form_options", "=", "options", ".", "reverse_merge", "(", "builder", ":", "ComfyBootstrapForm", "::", "FormBuilder", ")", "form_options", ".", "merge!", "(", "class", ":", "css_classes", ")", "unless", "css_classes", ".", "blank?", "supress_form_field_errors", "do", "form_with", "(", "**", "form_options", ",", "&", "block", ")", "end", "end" ]
Wrapper for `form_with`. Passing in Bootstrap form builder.
[ "Wrapper", "for", "form_with", ".", "Passing", "in", "Bootstrap", "form", "builder", "." ]
461d5cbd552469eb95e35fbcbed03d13ec702ef7
https://github.com/comfy/comfy-bootstrap-form/blob/461d5cbd552469eb95e35fbcbed03d13ec702ef7/lib/comfy_bootstrap_form/view_helper.rb#L7-L22
train
comfy/comfy-bootstrap-form
lib/comfy_bootstrap_form/view_helper.rb
ComfyBootstrapForm.ViewHelper.supress_form_field_errors
def supress_form_field_errors original_proc = ActionView::Base.field_error_proc ActionView::Base.field_error_proc = proc { |input, _instance| input } yield ensure ActionView::Base.field_error_proc = original_proc end
ruby
def supress_form_field_errors original_proc = ActionView::Base.field_error_proc ActionView::Base.field_error_proc = proc { |input, _instance| input } yield ensure ActionView::Base.field_error_proc = original_proc end
[ "def", "supress_form_field_errors", "original_proc", "=", "ActionView", "::", "Base", ".", "field_error_proc", "ActionView", "::", "Base", ".", "field_error_proc", "=", "proc", "{", "|", "input", ",", "_instance", "|", "input", "}", "yield", "ensure", "ActionView", "::", "Base", ".", "field_error_proc", "=", "original_proc", "end" ]
By default, Rails will wrap form fields with extra html to indicate inputs with errors. We need to handle this in the builder to render Bootstrap specific markup. So we need to bypass this.
[ "By", "default", "Rails", "will", "wrap", "form", "fields", "with", "extra", "html", "to", "indicate", "inputs", "with", "errors", ".", "We", "need", "to", "handle", "this", "in", "the", "builder", "to", "render", "Bootstrap", "specific", "markup", ".", "So", "we", "need", "to", "bypass", "this", "." ]
461d5cbd552469eb95e35fbcbed03d13ec702ef7
https://github.com/comfy/comfy-bootstrap-form/blob/461d5cbd552469eb95e35fbcbed03d13ec702ef7/lib/comfy_bootstrap_form/view_helper.rb#L48-L54
train
adelevie/parse-ruby-client
lib/parse/client.rb
Parse.Client.request
def request(uri, method = :get, body = nil, query = nil, content_type = nil) headers = {} { 'Content-Type' => content_type || 'application/json', 'User-Agent' => "Parse for Ruby, #{VERSION}", Protocol::HEADER_MASTER_KEY => @master_key, Protocol::HEADER_APP_ID => @application_id, Protocol::HEADER_API_KEY => @api_key, Protocol::HEADER_SESSION_TOKEN => @session_token }.each do |key, value| headers[key] = value if value end uri = ::File.join(path, uri) response = @session.send(method, uri, query || body || {}, headers) response.body # NOTE: Don't leak our internal libraries to our clients. # Extend this list of exceptions as needed. rescue Faraday::Error::ClientError => e raise Parse::ConnectionError, e.message end
ruby
def request(uri, method = :get, body = nil, query = nil, content_type = nil) headers = {} { 'Content-Type' => content_type || 'application/json', 'User-Agent' => "Parse for Ruby, #{VERSION}", Protocol::HEADER_MASTER_KEY => @master_key, Protocol::HEADER_APP_ID => @application_id, Protocol::HEADER_API_KEY => @api_key, Protocol::HEADER_SESSION_TOKEN => @session_token }.each do |key, value| headers[key] = value if value end uri = ::File.join(path, uri) response = @session.send(method, uri, query || body || {}, headers) response.body # NOTE: Don't leak our internal libraries to our clients. # Extend this list of exceptions as needed. rescue Faraday::Error::ClientError => e raise Parse::ConnectionError, e.message end
[ "def", "request", "(", "uri", ",", "method", "=", ":get", ",", "body", "=", "nil", ",", "query", "=", "nil", ",", "content_type", "=", "nil", ")", "headers", "=", "{", "}", "{", "'Content-Type'", "=>", "content_type", "||", "'application/json'", ",", "'User-Agent'", "=>", "\"Parse for Ruby, #{VERSION}\"", ",", "Protocol", "::", "HEADER_MASTER_KEY", "=>", "@master_key", ",", "Protocol", "::", "HEADER_APP_ID", "=>", "@application_id", ",", "Protocol", "::", "HEADER_API_KEY", "=>", "@api_key", ",", "Protocol", "::", "HEADER_SESSION_TOKEN", "=>", "@session_token", "}", ".", "each", "do", "|", "key", ",", "value", "|", "headers", "[", "key", "]", "=", "value", "if", "value", "end", "uri", "=", "::", "File", ".", "join", "(", "path", ",", "uri", ")", "response", "=", "@session", ".", "send", "(", "method", ",", "uri", ",", "query", "||", "body", "||", "{", "}", ",", "headers", ")", "response", ".", "body", "rescue", "Faraday", "::", "Error", "::", "ClientError", "=>", "e", "raise", "Parse", "::", "ConnectionError", ",", "e", ".", "message", "end" ]
Perform an HTTP request for the given uri and method with common basic response handling. Will raise a ParseProtocolError if the response has an error status code, and will return the parsed JSON body on success, if there is one.
[ "Perform", "an", "HTTP", "request", "for", "the", "given", "uri", "and", "method", "with", "common", "basic", "response", "handling", ".", "Will", "raise", "a", "ParseProtocolError", "if", "the", "response", "has", "an", "error", "status", "code", "and", "will", "return", "the", "parsed", "JSON", "body", "on", "success", "if", "there", "is", "one", "." ]
323e931594681e89bc3547dd998312b15040f982
https://github.com/adelevie/parse-ruby-client/blob/323e931594681e89bc3547dd998312b15040f982/lib/parse/client.rb#L87-L109
train
adelevie/parse-ruby-client
lib/parse/object.rb
Parse.Object.save
def save if @parse_object_id method = :put merge!(@op_fields) # use ops instead of our own view of the columns else method = :post end body = safe_hash.to_json data = @client.request(uri, method, body) if data # array ops can return mutated view of array which needs to be parsed object = Parse.parse_json(class_name, data) object = Parse.copy_client(@client, object) parse object end if @class_name == Parse::Protocol::CLASS_USER delete('password') delete(:username) delete(:password) end self end
ruby
def save if @parse_object_id method = :put merge!(@op_fields) # use ops instead of our own view of the columns else method = :post end body = safe_hash.to_json data = @client.request(uri, method, body) if data # array ops can return mutated view of array which needs to be parsed object = Parse.parse_json(class_name, data) object = Parse.copy_client(@client, object) parse object end if @class_name == Parse::Protocol::CLASS_USER delete('password') delete(:username) delete(:password) end self end
[ "def", "save", "if", "@parse_object_id", "method", "=", ":put", "merge!", "(", "@op_fields", ")", "else", "method", "=", ":post", "end", "body", "=", "safe_hash", ".", "to_json", "data", "=", "@client", ".", "request", "(", "uri", ",", "method", ",", "body", ")", "if", "data", "object", "=", "Parse", ".", "parse_json", "(", "class_name", ",", "data", ")", "object", "=", "Parse", ".", "copy_client", "(", "@client", ",", "object", ")", "parse", "object", "end", "if", "@class_name", "==", "Parse", "::", "Protocol", "::", "CLASS_USER", "delete", "(", "'password'", ")", "delete", "(", ":username", ")", "delete", "(", ":password", ")", "end", "self", "end" ]
Write the current state of the local object to the API. If the object has never been saved before, this will create a new object, otherwise it will update the existing stored object.
[ "Write", "the", "current", "state", "of", "the", "local", "object", "to", "the", "API", ".", "If", "the", "object", "has", "never", "been", "saved", "before", "this", "will", "create", "a", "new", "object", "otherwise", "it", "will", "update", "the", "existing", "stored", "object", "." ]
323e931594681e89bc3547dd998312b15040f982
https://github.com/adelevie/parse-ruby-client/blob/323e931594681e89bc3547dd998312b15040f982/lib/parse/object.rb#L59-L84
train
adelevie/parse-ruby-client
lib/parse/object.rb
Parse.Object.safe_hash
def safe_hash Hash[map do |key, value| if Protocol::RESERVED_KEYS.include?(key) nil elsif value.is_a?(Hash) && value[Protocol::KEY_TYPE] == Protocol::TYPE_RELATION nil elsif value.nil? [key, Protocol::DELETE_OP] else [key, Parse.pointerize_value(value)] end end.compact] end
ruby
def safe_hash Hash[map do |key, value| if Protocol::RESERVED_KEYS.include?(key) nil elsif value.is_a?(Hash) && value[Protocol::KEY_TYPE] == Protocol::TYPE_RELATION nil elsif value.nil? [key, Protocol::DELETE_OP] else [key, Parse.pointerize_value(value)] end end.compact] end
[ "def", "safe_hash", "Hash", "[", "map", "do", "|", "key", ",", "value", "|", "if", "Protocol", "::", "RESERVED_KEYS", ".", "include?", "(", "key", ")", "nil", "elsif", "value", ".", "is_a?", "(", "Hash", ")", "&&", "value", "[", "Protocol", "::", "KEY_TYPE", "]", "==", "Protocol", "::", "TYPE_RELATION", "nil", "elsif", "value", ".", "nil?", "[", "key", ",", "Protocol", "::", "DELETE_OP", "]", "else", "[", "key", ",", "Parse", ".", "pointerize_value", "(", "value", ")", "]", "end", "end", ".", "compact", "]", "end" ]
representation of object to send on saves
[ "representation", "of", "object", "to", "send", "on", "saves" ]
323e931594681e89bc3547dd998312b15040f982
https://github.com/adelevie/parse-ruby-client/blob/323e931594681e89bc3547dd998312b15040f982/lib/parse/object.rb#L87-L100
train
adelevie/parse-ruby-client
lib/parse/object.rb
Parse.Object.increment
def increment(field, amount = 1) # value = (self[field] || 0) + amount # self[field] = value # if !@parse_object_id # # TODO - warn that the object must be stored first # return nil # end body = { field => Parse::Increment.new(amount) }.to_json data = @client.request(uri, :put, body) parse data self end
ruby
def increment(field, amount = 1) # value = (self[field] || 0) + amount # self[field] = value # if !@parse_object_id # # TODO - warn that the object must be stored first # return nil # end body = { field => Parse::Increment.new(amount) }.to_json data = @client.request(uri, :put, body) parse data self end
[ "def", "increment", "(", "field", ",", "amount", "=", "1", ")", "body", "=", "{", "field", "=>", "Parse", "::", "Increment", ".", "new", "(", "amount", ")", "}", ".", "to_json", "data", "=", "@client", ".", "request", "(", "uri", ",", ":put", ",", "body", ")", "parse", "data", "self", "end" ]
Increment the given field by an amount, which defaults to 1. Saves immediately to reflect incremented
[ "Increment", "the", "given", "field", "by", "an", "amount", "which", "defaults", "to", "1", ".", "Saves", "immediately", "to", "reflect", "incremented" ]
323e931594681e89bc3547dd998312b15040f982
https://github.com/adelevie/parse-ruby-client/blob/323e931594681e89bc3547dd998312b15040f982/lib/parse/object.rb#L175-L187
train
adelevie/parse-ruby-client
lib/parse/object.rb
Parse.Object.parse
def parse(data) return unless data @parse_object_id ||= data[Protocol::KEY_OBJECT_ID] if data.key? Protocol::KEY_CREATED_AT @created_at = DateTime.parse data[Protocol::KEY_CREATED_AT] end if data.key? Protocol::KEY_UPDATED_AT @updated_at = DateTime.parse data[Protocol::KEY_UPDATED_AT] end data.each do |k, v| k = k.to_s if k.is_a? Symbol self[k] = v if k != Parse::Protocol::KEY_TYPE end self end
ruby
def parse(data) return unless data @parse_object_id ||= data[Protocol::KEY_OBJECT_ID] if data.key? Protocol::KEY_CREATED_AT @created_at = DateTime.parse data[Protocol::KEY_CREATED_AT] end if data.key? Protocol::KEY_UPDATED_AT @updated_at = DateTime.parse data[Protocol::KEY_UPDATED_AT] end data.each do |k, v| k = k.to_s if k.is_a? Symbol self[k] = v if k != Parse::Protocol::KEY_TYPE end self end
[ "def", "parse", "(", "data", ")", "return", "unless", "data", "@parse_object_id", "||=", "data", "[", "Protocol", "::", "KEY_OBJECT_ID", "]", "if", "data", ".", "key?", "Protocol", "::", "KEY_CREATED_AT", "@created_at", "=", "DateTime", ".", "parse", "data", "[", "Protocol", "::", "KEY_CREATED_AT", "]", "end", "if", "data", ".", "key?", "Protocol", "::", "KEY_UPDATED_AT", "@updated_at", "=", "DateTime", ".", "parse", "data", "[", "Protocol", "::", "KEY_UPDATED_AT", "]", "end", "data", ".", "each", "do", "|", "k", ",", "v", "|", "k", "=", "k", ".", "to_s", "if", "k", ".", "is_a?", "Symbol", "self", "[", "k", "]", "=", "v", "if", "k", "!=", "Parse", "::", "Protocol", "::", "KEY_TYPE", "end", "self", "end" ]
Merge a hash parsed from the JSON representation into this instance. This will extract the reserved fields, merge the hash keys, and then ensure that the reserved fields do not occur in the underlying hash storage.
[ "Merge", "a", "hash", "parsed", "from", "the", "JSON", "representation", "into", "this", "instance", ".", "This", "will", "extract", "the", "reserved", "fields", "merge", "the", "hash", "keys", "and", "then", "ensure", "that", "the", "reserved", "fields", "do", "not", "occur", "in", "the", "underlying", "hash", "storage", "." ]
323e931594681e89bc3547dd998312b15040f982
https://github.com/adelevie/parse-ruby-client/blob/323e931594681e89bc3547dd998312b15040f982/lib/parse/object.rb#L202-L222
train
acquia/moonshot
lib/moonshot/unicode_table.rb
Moonshot.UnicodeTable.draw_children
def draw_children first = true @children.each do |child| child.draw(1, first) first = false end puts '└──' end
ruby
def draw_children first = true @children.each do |child| child.draw(1, first) first = false end puts '└──' end
[ "def", "draw_children", "first", "=", "true", "@children", ".", "each", "do", "|", "child", "|", "child", ".", "draw", "(", "1", ",", "first", ")", "first", "=", "false", "end", "puts", "'└──'", "end" ]
Draw all children at the same level, for having multiple top-level peer leaves.
[ "Draw", "all", "children", "at", "the", "same", "level", "for", "having", "multiple", "top", "-", "level", "peer", "leaves", "." ]
d2f3a81f0674c8fabf07742038f806777d15c819
https://github.com/acquia/moonshot/blob/d2f3a81f0674c8fabf07742038f806777d15c819/lib/moonshot/unicode_table.rb#L54-L61
train
acquia/moonshot
lib/moonshot/artifact_repository/s3_bucket_via_github_releases.rb
Moonshot::ArtifactRepository.S3BucketViaGithubReleases.upload_to_s3
def upload_to_s3(file, key) attempts = 0 begin super unless (checksum = checksum_file(file)).nil? verify_s3_checksum(key, checksum, attempt: attempts) end rescue RuntimeError => e unless (attempts += 1) > 3 # Wait 10 seconds before trying again. sleep 10 retry end raise e end end
ruby
def upload_to_s3(file, key) attempts = 0 begin super unless (checksum = checksum_file(file)).nil? verify_s3_checksum(key, checksum, attempt: attempts) end rescue RuntimeError => e unless (attempts += 1) > 3 # Wait 10 seconds before trying again. sleep 10 retry end raise e end end
[ "def", "upload_to_s3", "(", "file", ",", "key", ")", "attempts", "=", "0", "begin", "super", "unless", "(", "checksum", "=", "checksum_file", "(", "file", ")", ")", ".", "nil?", "verify_s3_checksum", "(", "key", ",", "checksum", ",", "attempt", ":", "attempts", ")", "end", "rescue", "RuntimeError", "=>", "e", "unless", "(", "attempts", "+=", "1", ")", ">", "3", "sleep", "10", "retry", "end", "raise", "e", "end", "end" ]
Uploads the file to s3 and verifies the checksum. @param file [String] File to be uploaded to s3. @param key [String] Name of the object to be created on s3. @raise [RuntimeError] If the file fails to upload correctly after 3 attempts.
[ "Uploads", "the", "file", "to", "s3", "and", "verifies", "the", "checksum", "." ]
d2f3a81f0674c8fabf07742038f806777d15c819
https://github.com/acquia/moonshot/blob/d2f3a81f0674c8fabf07742038f806777d15c819/lib/moonshot/artifact_repository/s3_bucket_via_github_releases.rb#L93-L110
train
acquia/moonshot
lib/moonshot/artifact_repository/s3_bucket_via_github_releases.rb
Moonshot::ArtifactRepository.S3BucketViaGithubReleases.download_from_github
def download_from_github(version) file_pattern = "*#{version}*.tar.gz" attempts = 0 Retriable.retriable on: RuntimeError do # Make sure the directory is empty before downloading the release. FileUtils.rm(Dir.glob('*')) # Download the release and find the actual build file. sh_out("hub release download #{version}") raise "File '#{file_pattern}' not found." if Dir.glob(file_pattern).empty? file = Dir.glob(file_pattern).fetch(0) unless (checksum = checksum_file(file)).nil? verify_download_checksum(file, checksum, attempt: attempts) end attempts += 1 file end end
ruby
def download_from_github(version) file_pattern = "*#{version}*.tar.gz" attempts = 0 Retriable.retriable on: RuntimeError do # Make sure the directory is empty before downloading the release. FileUtils.rm(Dir.glob('*')) # Download the release and find the actual build file. sh_out("hub release download #{version}") raise "File '#{file_pattern}' not found." if Dir.glob(file_pattern).empty? file = Dir.glob(file_pattern).fetch(0) unless (checksum = checksum_file(file)).nil? verify_download_checksum(file, checksum, attempt: attempts) end attempts += 1 file end end
[ "def", "download_from_github", "(", "version", ")", "file_pattern", "=", "\"*#{version}*.tar.gz\"", "attempts", "=", "0", "Retriable", ".", "retriable", "on", ":", "RuntimeError", "do", "FileUtils", ".", "rm", "(", "Dir", ".", "glob", "(", "'*'", ")", ")", "sh_out", "(", "\"hub release download #{version}\"", ")", "raise", "\"File '#{file_pattern}' not found.\"", "if", "Dir", ".", "glob", "(", "file_pattern", ")", ".", "empty?", "file", "=", "Dir", ".", "glob", "(", "file_pattern", ")", ".", "fetch", "(", "0", ")", "unless", "(", "checksum", "=", "checksum_file", "(", "file", ")", ")", ".", "nil?", "verify_download_checksum", "(", "file", ",", "checksum", ",", "attempt", ":", "attempts", ")", "end", "attempts", "+=", "1", "file", "end", "end" ]
Downloads the release build from github and verifies the checksum. @param version [String] Version to be downloaded @param [String] Build file downloaded. @raise [RuntimeError] If the file fails to download correctly after 3 attempts.
[ "Downloads", "the", "release", "build", "from", "github", "and", "verifies", "the", "checksum", "." ]
d2f3a81f0674c8fabf07742038f806777d15c819
https://github.com/acquia/moonshot/blob/d2f3a81f0674c8fabf07742038f806777d15c819/lib/moonshot/artifact_repository/s3_bucket_via_github_releases.rb#L118-L139
train
acquia/moonshot
lib/moonshot/artifact_repository/s3_bucket_via_github_releases.rb
Moonshot::ArtifactRepository.S3BucketViaGithubReleases.verify_download_checksum
def verify_download_checksum(build_file, checksum_file, attempt: 0) expected = File.read(checksum_file) actual = Digest::MD5.file(build_file).hexdigest if actual != expected log.error("GitHub fie #{build_file} checksum should be #{expected} " \ "but was #{actual}.") backup_failed_github_file(build_file, attempt) raise "Checksum for #{build_file} could not be verified." end log.info('Verified downloaded file checksum.') end
ruby
def verify_download_checksum(build_file, checksum_file, attempt: 0) expected = File.read(checksum_file) actual = Digest::MD5.file(build_file).hexdigest if actual != expected log.error("GitHub fie #{build_file} checksum should be #{expected} " \ "but was #{actual}.") backup_failed_github_file(build_file, attempt) raise "Checksum for #{build_file} could not be verified." end log.info('Verified downloaded file checksum.') end
[ "def", "verify_download_checksum", "(", "build_file", ",", "checksum_file", ",", "attempt", ":", "0", ")", "expected", "=", "File", ".", "read", "(", "checksum_file", ")", "actual", "=", "Digest", "::", "MD5", ".", "file", "(", "build_file", ")", ".", "hexdigest", "if", "actual", "!=", "expected", "log", ".", "error", "(", "\"GitHub fie #{build_file} checksum should be #{expected} \"", "\"but was #{actual}.\"", ")", "backup_failed_github_file", "(", "build_file", ",", "attempt", ")", "raise", "\"Checksum for #{build_file} could not be verified.\"", "end", "log", ".", "info", "(", "'Verified downloaded file checksum.'", ")", "end" ]
Verifies the checksum for a file downloaded from github. @param build_file [String] Build file to verify. @param checksum_file [String] Checksum file to verify the build. @param attempt [Integer] The attempt for this verification.
[ "Verifies", "the", "checksum", "for", "a", "file", "downloaded", "from", "github", "." ]
d2f3a81f0674c8fabf07742038f806777d15c819
https://github.com/acquia/moonshot/blob/d2f3a81f0674c8fabf07742038f806777d15c819/lib/moonshot/artifact_repository/s3_bucket_via_github_releases.rb#L155-L166
train
acquia/moonshot
lib/moonshot/artifact_repository/s3_bucket_via_github_releases.rb
Moonshot::ArtifactRepository.S3BucketViaGithubReleases.backup_failed_github_file
def backup_failed_github_file(build_file, attempt) basename = File.basename(build_file, '.tar.gz') destination = File.join(Dir.tmpdir, basename, ".gh.failure.#{attempt}.tar.gz") FileUtils.cp(build_file, destination) log.info("Copied #{build_file} to #{destination}") end
ruby
def backup_failed_github_file(build_file, attempt) basename = File.basename(build_file, '.tar.gz') destination = File.join(Dir.tmpdir, basename, ".gh.failure.#{attempt}.tar.gz") FileUtils.cp(build_file, destination) log.info("Copied #{build_file} to #{destination}") end
[ "def", "backup_failed_github_file", "(", "build_file", ",", "attempt", ")", "basename", "=", "File", ".", "basename", "(", "build_file", ",", "'.tar.gz'", ")", "destination", "=", "File", ".", "join", "(", "Dir", ".", "tmpdir", ",", "basename", ",", "\".gh.failure.#{attempt}.tar.gz\"", ")", "FileUtils", ".", "cp", "(", "build_file", ",", "destination", ")", "log", ".", "info", "(", "\"Copied #{build_file} to #{destination}\"", ")", "end" ]
Backs up the failed file from a github verification. @param build_file [String] The build file to backup. @param attempt [Integer] Which attempt to verify the file failed.
[ "Backs", "up", "the", "failed", "file", "from", "a", "github", "verification", "." ]
d2f3a81f0674c8fabf07742038f806777d15c819
https://github.com/acquia/moonshot/blob/d2f3a81f0674c8fabf07742038f806777d15c819/lib/moonshot/artifact_repository/s3_bucket_via_github_releases.rb#L172-L178
train
acquia/moonshot
lib/moonshot/artifact_repository/s3_bucket_via_github_releases.rb
Moonshot::ArtifactRepository.S3BucketViaGithubReleases.verify_s3_checksum
def verify_s3_checksum(s3_name, checksum_file, attempt: 0) headers = s3_client.head_object( key: s3_name, bucket: @bucket_name ) expected = File.read(checksum_file) actual = headers.etag.tr('"', '') if actual != expected log.error("S3 file #{s3_name} checksum should be #{expected} but " \ "was #{actual}.") backup_failed_s3_file(s3_name, attempt) raise "Checksum for #{s3_name} could not be verified." end log.info('Verified uploaded file checksum.') end
ruby
def verify_s3_checksum(s3_name, checksum_file, attempt: 0) headers = s3_client.head_object( key: s3_name, bucket: @bucket_name ) expected = File.read(checksum_file) actual = headers.etag.tr('"', '') if actual != expected log.error("S3 file #{s3_name} checksum should be #{expected} but " \ "was #{actual}.") backup_failed_s3_file(s3_name, attempt) raise "Checksum for #{s3_name} could not be verified." end log.info('Verified uploaded file checksum.') end
[ "def", "verify_s3_checksum", "(", "s3_name", ",", "checksum_file", ",", "attempt", ":", "0", ")", "headers", "=", "s3_client", ".", "head_object", "(", "key", ":", "s3_name", ",", "bucket", ":", "@bucket_name", ")", "expected", "=", "File", ".", "read", "(", "checksum_file", ")", "actual", "=", "headers", ".", "etag", ".", "tr", "(", "'\"'", ",", "''", ")", "if", "actual", "!=", "expected", "log", ".", "error", "(", "\"S3 file #{s3_name} checksum should be #{expected} but \"", "\"was #{actual}.\"", ")", "backup_failed_s3_file", "(", "s3_name", ",", "attempt", ")", "raise", "\"Checksum for #{s3_name} could not be verified.\"", "end", "log", ".", "info", "(", "'Verified uploaded file checksum.'", ")", "end" ]
Verifies the checksum for a file uploaded to s3. Uses a HEAD request and uses the etag, which is an MD5 hash. @param s3_name [String] The object's name on s3. @param checksum_file [String] Checksum file to verify the build. @param attempt [Integer] The attempt for this verification.
[ "Verifies", "the", "checksum", "for", "a", "file", "uploaded", "to", "s3", "." ]
d2f3a81f0674c8fabf07742038f806777d15c819
https://github.com/acquia/moonshot/blob/d2f3a81f0674c8fabf07742038f806777d15c819/lib/moonshot/artifact_repository/s3_bucket_via_github_releases.rb#L187-L202
train
acquia/moonshot
lib/moonshot/artifact_repository/s3_bucket_via_github_releases.rb
Moonshot::ArtifactRepository.S3BucketViaGithubReleases.backup_failed_s3_file
def backup_failed_s3_file(s3_name, attempt) basename = File.basename(s3_name, '.tar.gz') destination = "#{Dir.tmpdir}/#{basename}.s3.failure.#{attempt}.tar.gz" s3_client.get_object( response_target: destination, key: s3_name, bucket: @bucket_name ) log.info("Copied #{s3_name} to #{destination}") end
ruby
def backup_failed_s3_file(s3_name, attempt) basename = File.basename(s3_name, '.tar.gz') destination = "#{Dir.tmpdir}/#{basename}.s3.failure.#{attempt}.tar.gz" s3_client.get_object( response_target: destination, key: s3_name, bucket: @bucket_name ) log.info("Copied #{s3_name} to #{destination}") end
[ "def", "backup_failed_s3_file", "(", "s3_name", ",", "attempt", ")", "basename", "=", "File", ".", "basename", "(", "s3_name", ",", "'.tar.gz'", ")", "destination", "=", "\"#{Dir.tmpdir}/#{basename}.s3.failure.#{attempt}.tar.gz\"", "s3_client", ".", "get_object", "(", "response_target", ":", "destination", ",", "key", ":", "s3_name", ",", "bucket", ":", "@bucket_name", ")", "log", ".", "info", "(", "\"Copied #{s3_name} to #{destination}\"", ")", "end" ]
Backs up the failed file from an s3 verification. @param s3_name [String] The object's name on s3. @param attempt [Integer] Which attempt to verify the file failed.
[ "Backs", "up", "the", "failed", "file", "from", "an", "s3", "verification", "." ]
d2f3a81f0674c8fabf07742038f806777d15c819
https://github.com/acquia/moonshot/blob/d2f3a81f0674c8fabf07742038f806777d15c819/lib/moonshot/artifact_repository/s3_bucket_via_github_releases.rb#L208-L217
train
acquia/moonshot
lib/moonshot/stack_asg_printer.rb
Moonshot.StackASGPrinter.get_addl_info
def get_addl_info(instance_ids) resp = ec2_client.describe_instances(instance_ids: instance_ids) data = {} resp.reservations.map(&:instances).flatten.each do |instance| data[instance.instance_id] = instance end data end
ruby
def get_addl_info(instance_ids) resp = ec2_client.describe_instances(instance_ids: instance_ids) data = {} resp.reservations.map(&:instances).flatten.each do |instance| data[instance.instance_id] = instance end data end
[ "def", "get_addl_info", "(", "instance_ids", ")", "resp", "=", "ec2_client", ".", "describe_instances", "(", "instance_ids", ":", "instance_ids", ")", "data", "=", "{", "}", "resp", ".", "reservations", ".", "map", "(", "&", ":instances", ")", ".", "flatten", ".", "each", "do", "|", "instance", "|", "data", "[", "instance", ".", "instance_id", "]", "=", "instance", "end", "data", "end" ]
Get additional information about instances not returned by the ASG API.
[ "Get", "additional", "information", "about", "instances", "not", "returned", "by", "the", "ASG", "API", "." ]
d2f3a81f0674c8fabf07742038f806777d15c819
https://github.com/acquia/moonshot/blob/d2f3a81f0674c8fabf07742038f806777d15c819/lib/moonshot/stack_asg_printer.rb#L73-L81
train
acquia/moonshot
lib/moonshot/build_mechanism/travis_deploy.rb
Moonshot::BuildMechanism.TravisDeploy.wait_for_build
def wait_for_build(version) # Attempt to find the build. Re-attempt if the build can not # be found on travis yet. retry_opts = { tries: MAX_BUILD_FIND_ATTEMPTS, base_interval: 10 } job_number = nil sh_retry("bundle exec travis show #{@cli_args} #{version}", opts: retry_opts) do |build_out| raise CommandError, "Build for #{version} not found.\n#{build_out}" \ unless (job_number = build_out.match(/^#(\d+\.\d+) .+BUILD=1.+/)[1]) end job_number end
ruby
def wait_for_build(version) # Attempt to find the build. Re-attempt if the build can not # be found on travis yet. retry_opts = { tries: MAX_BUILD_FIND_ATTEMPTS, base_interval: 10 } job_number = nil sh_retry("bundle exec travis show #{@cli_args} #{version}", opts: retry_opts) do |build_out| raise CommandError, "Build for #{version} not found.\n#{build_out}" \ unless (job_number = build_out.match(/^#(\d+\.\d+) .+BUILD=1.+/)[1]) end job_number end
[ "def", "wait_for_build", "(", "version", ")", "retry_opts", "=", "{", "tries", ":", "MAX_BUILD_FIND_ATTEMPTS", ",", "base_interval", ":", "10", "}", "job_number", "=", "nil", "sh_retry", "(", "\"bundle exec travis show #{@cli_args} #{version}\"", ",", "opts", ":", "retry_opts", ")", "do", "|", "build_out", "|", "raise", "CommandError", ",", "\"Build for #{version} not found.\\n#{build_out}\"", "unless", "(", "job_number", "=", "build_out", ".", "match", "(", "/", "\\d", "\\.", "\\d", "/", ")", "[", "1", "]", ")", "end", "job_number", "end" ]
Looks for the travis build and attempts to retry if the build does not exist yet. @param verison [String] Build version to look for. @return [String] Job number for the travis build.
[ "Looks", "for", "the", "travis", "build", "and", "attempts", "to", "retry", "if", "the", "build", "does", "not", "exist", "yet", "." ]
d2f3a81f0674c8fabf07742038f806777d15c819
https://github.com/acquia/moonshot/blob/d2f3a81f0674c8fabf07742038f806777d15c819/lib/moonshot/build_mechanism/travis_deploy.rb#L68-L82
train
acquia/moonshot
lib/moonshot/build_mechanism/travis_deploy.rb
Moonshot::BuildMechanism.TravisDeploy.wait_for_job
def wait_for_job(job_number) authenticate # Wait for the job to complete or hit the timeout. start = Time.new job = repo.job(job_number) ilog.start_threaded("Waiting for job #{job_number} to complete.") do |s| while !job.finished? && Time.new - start < @timeout s.continue("Job status: #{job.state}") sleep 10 job.reload end if job.finished? s.success else s.failure("Job #{job_number} did not complete within time limit of " \ "#{@timeout} seconds") end end end
ruby
def wait_for_job(job_number) authenticate # Wait for the job to complete or hit the timeout. start = Time.new job = repo.job(job_number) ilog.start_threaded("Waiting for job #{job_number} to complete.") do |s| while !job.finished? && Time.new - start < @timeout s.continue("Job status: #{job.state}") sleep 10 job.reload end if job.finished? s.success else s.failure("Job #{job_number} did not complete within time limit of " \ "#{@timeout} seconds") end end end
[ "def", "wait_for_job", "(", "job_number", ")", "authenticate", "start", "=", "Time", ".", "new", "job", "=", "repo", ".", "job", "(", "job_number", ")", "ilog", ".", "start_threaded", "(", "\"Waiting for job #{job_number} to complete.\"", ")", "do", "|", "s", "|", "while", "!", "job", ".", "finished?", "&&", "Time", ".", "new", "-", "start", "<", "@timeout", "s", ".", "continue", "(", "\"Job status: #{job.state}\"", ")", "sleep", "10", "job", ".", "reload", "end", "if", "job", ".", "finished?", "s", ".", "success", "else", "s", ".", "failure", "(", "\"Job #{job_number} did not complete within time limit of \"", "\"#{@timeout} seconds\"", ")", "end", "end", "end" ]
Waits for a job to complete, within the defined timeout. @param job_number [String] The job number to wait for.
[ "Waits", "for", "a", "job", "to", "complete", "within", "the", "defined", "timeout", "." ]
d2f3a81f0674c8fabf07742038f806777d15c819
https://github.com/acquia/moonshot/blob/d2f3a81f0674c8fabf07742038f806777d15c819/lib/moonshot/build_mechanism/travis_deploy.rb#L87-L107
train
acquia/moonshot
lib/moonshot/stack.rb
Moonshot.Stack.default_values
def default_values h = {} template.parameters.each do |p| h[p.name] = h.default end h end
ruby
def default_values h = {} template.parameters.each do |p| h[p.name] = h.default end h end
[ "def", "default_values", "h", "=", "{", "}", "template", ".", "parameters", ".", "each", "do", "|", "p", "|", "h", "[", "p", ".", "name", "]", "=", "h", ".", "default", "end", "h", "end" ]
Return a Hash of the default values defined in the stack template.
[ "Return", "a", "Hash", "of", "the", "default", "values", "defined", "in", "the", "stack", "template", "." ]
d2f3a81f0674c8fabf07742038f806777d15c819
https://github.com/acquia/moonshot/blob/d2f3a81f0674c8fabf07742038f806777d15c819/lib/moonshot/stack.rb#L125-L131
train
acquia/moonshot
lib/moonshot/build_mechanism/github_release.rb
Moonshot::BuildMechanism.GithubRelease.git_tag_exists
def git_tag_exists(tag, sha) exists = false sh_step("git tag -l #{tag}") do |_, output| exists = (output.strip == tag) end # If the tag does exist, make sure the existing SHA matches the SHA we're # trying to build from. if exists sh_step("git rev-list -n 1 #{tag}") do |_, output| raise "#{tag} already exists at a different SHA" \ if output.strip != sha end log.info("tag #{tag} already exists") end exists end
ruby
def git_tag_exists(tag, sha) exists = false sh_step("git tag -l #{tag}") do |_, output| exists = (output.strip == tag) end # If the tag does exist, make sure the existing SHA matches the SHA we're # trying to build from. if exists sh_step("git rev-list -n 1 #{tag}") do |_, output| raise "#{tag} already exists at a different SHA" \ if output.strip != sha end log.info("tag #{tag} already exists") end exists end
[ "def", "git_tag_exists", "(", "tag", ",", "sha", ")", "exists", "=", "false", "sh_step", "(", "\"git tag -l #{tag}\"", ")", "do", "|", "_", ",", "output", "|", "exists", "=", "(", "output", ".", "strip", "==", "tag", ")", "end", "if", "exists", "sh_step", "(", "\"git rev-list -n 1 #{tag}\"", ")", "do", "|", "_", ",", "output", "|", "raise", "\"#{tag} already exists at a different SHA\"", "if", "output", ".", "strip", "!=", "sha", "end", "log", ".", "info", "(", "\"tag #{tag} already exists\"", ")", "end", "exists", "end" ]
Determines if a valid git tag already exists. @param tag [String] Tag to check existence for. @param sha [String] SHA to verify the tag against. @return [Boolean] Whether or not the tag exists. @raise [RuntimeError] if the SHAs do not match.
[ "Determines", "if", "a", "valid", "git", "tag", "already", "exists", "." ]
d2f3a81f0674c8fabf07742038f806777d15c819
https://github.com/acquia/moonshot/blob/d2f3a81f0674c8fabf07742038f806777d15c819/lib/moonshot/build_mechanism/github_release.rb#L107-L125
train
acquia/moonshot
lib/moonshot/build_mechanism/github_release.rb
Moonshot::BuildMechanism.GithubRelease.hub_release_exists
def hub_release_exists(semver) exists = false sh_step("hub release show #{semver}", fail: false) do |_, output| first_line = output.split("\n").first exists = !first_line.nil? && first_line.strip == semver.to_s end log.info("release #{semver} already exists") if exists exists end
ruby
def hub_release_exists(semver) exists = false sh_step("hub release show #{semver}", fail: false) do |_, output| first_line = output.split("\n").first exists = !first_line.nil? && first_line.strip == semver.to_s end log.info("release #{semver} already exists") if exists exists end
[ "def", "hub_release_exists", "(", "semver", ")", "exists", "=", "false", "sh_step", "(", "\"hub release show #{semver}\"", ",", "fail", ":", "false", ")", "do", "|", "_", ",", "output", "|", "first_line", "=", "output", ".", "split", "(", "\"\\n\"", ")", ".", "first", "exists", "=", "!", "first_line", ".", "nil?", "&&", "first_line", ".", "strip", "==", "semver", ".", "to_s", "end", "log", ".", "info", "(", "\"release #{semver} already exists\"", ")", "if", "exists", "exists", "end" ]
Determines if a github release already exists. @param semver [String] Semantic version string for the release. @return [Boolean]
[ "Determines", "if", "a", "github", "release", "already", "exists", "." ]
d2f3a81f0674c8fabf07742038f806777d15c819
https://github.com/acquia/moonshot/blob/d2f3a81f0674c8fabf07742038f806777d15c819/lib/moonshot/build_mechanism/github_release.rb#L148-L156
train
acquia/moonshot
lib/moonshot/build_mechanism/github_release.rb
Moonshot::BuildMechanism.GithubRelease.check_ci_status
def check_ci_status(sha) out = nil retry_opts = { max_elapsed_time: @ci_status_timeout, base_interval: 10 } ilog.start_threaded("Check CI status for #{sha}.") do |step| out = sh_retry("hub ci-status --verbose #{sha}", opts: retry_opts) step.success end out end
ruby
def check_ci_status(sha) out = nil retry_opts = { max_elapsed_time: @ci_status_timeout, base_interval: 10 } ilog.start_threaded("Check CI status for #{sha}.") do |step| out = sh_retry("hub ci-status --verbose #{sha}", opts: retry_opts) step.success end out end
[ "def", "check_ci_status", "(", "sha", ")", "out", "=", "nil", "retry_opts", "=", "{", "max_elapsed_time", ":", "@ci_status_timeout", ",", "base_interval", ":", "10", "}", "ilog", ".", "start_threaded", "(", "\"Check CI status for #{sha}.\"", ")", "do", "|", "step", "|", "out", "=", "sh_retry", "(", "\"hub ci-status --verbose #{sha}\"", ",", "opts", ":", "retry_opts", ")", "step", ".", "success", "end", "out", "end" ]
Checks for the commit's CI job status. If its not finished yet, wait till timeout. @param sha [String] Commit sha. @return [String] Status and links to the CI jobs
[ "Checks", "for", "the", "commit", "s", "CI", "job", "status", ".", "If", "its", "not", "finished", "yet", "wait", "till", "timeout", "." ]
d2f3a81f0674c8fabf07742038f806777d15c819
https://github.com/acquia/moonshot/blob/d2f3a81f0674c8fabf07742038f806777d15c819/lib/moonshot/build_mechanism/github_release.rb#L202-L213
train
neilslater/games_dice
lib/games_dice/prob_helpers.rb
GamesDice::ProbabilityValidations.ClassMethods.prob_h_to_ao
def prob_h_to_ao h rmin,rmax = h.keys.minmax o = rmin s = 1 + rmax - rmin raise ArgumentError, "Range of possible results too large" if s > 1000000 a = Array.new( s, 0.0 ) h.each { |k,v| a[k-rmin] = Float(v) } [a,o] end
ruby
def prob_h_to_ao h rmin,rmax = h.keys.minmax o = rmin s = 1 + rmax - rmin raise ArgumentError, "Range of possible results too large" if s > 1000000 a = Array.new( s, 0.0 ) h.each { |k,v| a[k-rmin] = Float(v) } [a,o] end
[ "def", "prob_h_to_ao", "h", "rmin", ",", "rmax", "=", "h", ".", "keys", ".", "minmax", "o", "=", "rmin", "s", "=", "1", "+", "rmax", "-", "rmin", "raise", "ArgumentError", ",", "\"Range of possible results too large\"", "if", "s", ">", "1000000", "a", "=", "Array", ".", "new", "(", "s", ",", "0.0", ")", "h", ".", "each", "{", "|", "k", ",", "v", "|", "a", "[", "k", "-", "rmin", "]", "=", "Float", "(", "v", ")", "}", "[", "a", ",", "o", "]", "end" ]
Convert hash to array,offset notation
[ "Convert", "hash", "to", "array", "offset", "notation" ]
3e1c918974103da803c6cefb009c92de85b5ea7a
https://github.com/neilslater/games_dice/blob/3e1c918974103da803c6cefb009c92de85b5ea7a/lib/games_dice/prob_helpers.rb#L37-L45
train
neilslater/games_dice
lib/games_dice/prob_helpers.rb
GamesDice::ProbabilityValidations.ClassMethods.prob_ao_to_h
def prob_ao_to_h a, o h = Hash.new a.each_with_index { |v,i| h[i+o] = v if v > 0.0 } h end
ruby
def prob_ao_to_h a, o h = Hash.new a.each_with_index { |v,i| h[i+o] = v if v > 0.0 } h end
[ "def", "prob_ao_to_h", "a", ",", "o", "h", "=", "Hash", ".", "new", "a", ".", "each_with_index", "{", "|", "v", ",", "i", "|", "h", "[", "i", "+", "o", "]", "=", "v", "if", "v", ">", "0.0", "}", "h", "end" ]
Convert array,offset notation to hash
[ "Convert", "array", "offset", "notation", "to", "hash" ]
3e1c918974103da803c6cefb009c92de85b5ea7a
https://github.com/neilslater/games_dice/blob/3e1c918974103da803c6cefb009c92de85b5ea7a/lib/games_dice/prob_helpers.rb#L48-L52
train
tpitale/legato
lib/legato/query.rb
Legato.Query.basic_options
def basic_options Hash[BASIC_OPTION_KEYS.map { |k| [k, send(k)] }].reject {|_,v| v.nil?} end
ruby
def basic_options Hash[BASIC_OPTION_KEYS.map { |k| [k, send(k)] }].reject {|_,v| v.nil?} end
[ "def", "basic_options", "Hash", "[", "BASIC_OPTION_KEYS", ".", "map", "{", "|", "k", "|", "[", "k", ",", "send", "(", "k", ")", "]", "}", "]", ".", "reject", "{", "|", "_", ",", "v", "|", "v", ".", "nil?", "}", "end" ]
return a hash of basic options to merge
[ "return", "a", "hash", "of", "basic", "options", "to", "merge" ]
e92a3e585a9c6a50a6cac1e053f1a6bf30f8e249
https://github.com/tpitale/legato/blob/e92a3e585a9c6a50a6cac1e053f1a6bf30f8e249/lib/legato/query.rb#L122-L124
train
tpitale/legato
lib/legato/query.rb
Legato.Query.results
def results(profile=nil, options={}) query = loaded? ? Query.from_query(self) : self options, profile = profile, self.profile if profile.is_a?(Hash) query.profile = profile query.apply_options(self.basic_options.merge(options)) query end
ruby
def results(profile=nil, options={}) query = loaded? ? Query.from_query(self) : self options, profile = profile, self.profile if profile.is_a?(Hash) query.profile = profile query.apply_options(self.basic_options.merge(options)) query end
[ "def", "results", "(", "profile", "=", "nil", ",", "options", "=", "{", "}", ")", "query", "=", "loaded?", "?", "Query", ".", "from_query", "(", "self", ")", ":", "self", "options", ",", "profile", "=", "profile", ",", "self", ".", "profile", "if", "profile", ".", "is_a?", "(", "Hash", ")", "query", ".", "profile", "=", "profile", "query", ".", "apply_options", "(", "self", ".", "basic_options", ".", "merge", "(", "options", ")", ")", "query", "end" ]
if no filters, we use results to add profile
[ "if", "no", "filters", "we", "use", "results", "to", "add", "profile" ]
e92a3e585a9c6a50a6cac1e053f1a6bf30f8e249
https://github.com/tpitale/legato/blob/e92a3e585a9c6a50a6cac1e053f1a6bf30f8e249/lib/legato/query.rb#L193-L201
train
seomoz/qless
lib/qless/job.rb
Qless.Job.requeue
def requeue(queue, opts = {}) queue_name = case queue when String, Symbol then queue else queue.name end note_state_change :requeue do @client.call('requeue', @client.worker_name, queue_name, @jid, @klass_name, JSON.dump(opts.fetch(:data, @data)), opts.fetch(:delay, 0), 'priority', opts.fetch(:priority, @priority), 'tags', JSON.dump(opts.fetch(:tags, @tags)), 'retries', opts.fetch(:retries, @original_retries), 'depends', JSON.dump(opts.fetch(:depends, @dependencies)) ) end end
ruby
def requeue(queue, opts = {}) queue_name = case queue when String, Symbol then queue else queue.name end note_state_change :requeue do @client.call('requeue', @client.worker_name, queue_name, @jid, @klass_name, JSON.dump(opts.fetch(:data, @data)), opts.fetch(:delay, 0), 'priority', opts.fetch(:priority, @priority), 'tags', JSON.dump(opts.fetch(:tags, @tags)), 'retries', opts.fetch(:retries, @original_retries), 'depends', JSON.dump(opts.fetch(:depends, @dependencies)) ) end end
[ "def", "requeue", "(", "queue", ",", "opts", "=", "{", "}", ")", "queue_name", "=", "case", "queue", "when", "String", ",", "Symbol", "then", "queue", "else", "queue", ".", "name", "end", "note_state_change", ":requeue", "do", "@client", ".", "call", "(", "'requeue'", ",", "@client", ".", "worker_name", ",", "queue_name", ",", "@jid", ",", "@klass_name", ",", "JSON", ".", "dump", "(", "opts", ".", "fetch", "(", ":data", ",", "@data", ")", ")", ",", "opts", ".", "fetch", "(", ":delay", ",", "0", ")", ",", "'priority'", ",", "opts", ".", "fetch", "(", ":priority", ",", "@priority", ")", ",", "'tags'", ",", "JSON", ".", "dump", "(", "opts", ".", "fetch", "(", ":tags", ",", "@tags", ")", ")", ",", "'retries'", ",", "opts", ".", "fetch", "(", ":retries", ",", "@original_retries", ")", ",", "'depends'", ",", "JSON", ".", "dump", "(", "opts", ".", "fetch", "(", ":depends", ",", "@dependencies", ")", ")", ")", "end", "end" ]
Move this from it's current queue into another
[ "Move", "this", "from", "it", "s", "current", "queue", "into", "another" ]
08e16c2292c5cf0fe9322cce72d1ac6c80d372ce
https://github.com/seomoz/qless/blob/08e16c2292c5cf0fe9322cce72d1ac6c80d372ce/lib/qless/job.rb#L229-L245
train
seomoz/qless
lib/qless/job.rb
Qless.Job.fail
def fail(group, message) note_state_change :fail do @client.call( 'fail', @jid, @worker_name, group, message, JSON.dump(@data)) || false end rescue Qless::LuaScriptError => err raise CantFailError.new(err.message) end
ruby
def fail(group, message) note_state_change :fail do @client.call( 'fail', @jid, @worker_name, group, message, JSON.dump(@data)) || false end rescue Qless::LuaScriptError => err raise CantFailError.new(err.message) end
[ "def", "fail", "(", "group", ",", "message", ")", "note_state_change", ":fail", "do", "@client", ".", "call", "(", "'fail'", ",", "@jid", ",", "@worker_name", ",", "group", ",", "message", ",", "JSON", ".", "dump", "(", "@data", ")", ")", "||", "false", "end", "rescue", "Qless", "::", "LuaScriptError", "=>", "err", "raise", "CantFailError", ".", "new", "(", "err", ".", "message", ")", "end" ]
Fail a job
[ "Fail", "a", "job" ]
08e16c2292c5cf0fe9322cce72d1ac6c80d372ce
https://github.com/seomoz/qless/blob/08e16c2292c5cf0fe9322cce72d1ac6c80d372ce/lib/qless/job.rb#L251-L262
train
seomoz/qless
lib/qless/subscriber.rb
Qless.Subscriber.start
def start queue = ::Queue.new @thread = Thread.start do @listener_redis.subscribe(@channel, @my_channel) do |on| on.subscribe do |channel| queue.push(:subscribed) if channel == @channel end on.message do |channel, message| handle_message(channel, message) end end end queue.pop end
ruby
def start queue = ::Queue.new @thread = Thread.start do @listener_redis.subscribe(@channel, @my_channel) do |on| on.subscribe do |channel| queue.push(:subscribed) if channel == @channel end on.message do |channel, message| handle_message(channel, message) end end end queue.pop end
[ "def", "start", "queue", "=", "::", "Queue", ".", "new", "@thread", "=", "Thread", ".", "start", "do", "@listener_redis", ".", "subscribe", "(", "@channel", ",", "@my_channel", ")", "do", "|", "on", "|", "on", ".", "subscribe", "do", "|", "channel", "|", "queue", ".", "push", "(", ":subscribed", ")", "if", "channel", "==", "@channel", "end", "on", ".", "message", "do", "|", "channel", ",", "message", "|", "handle_message", "(", "channel", ",", "message", ")", "end", "end", "end", "queue", ".", "pop", "end" ]
Start a thread listening
[ "Start", "a", "thread", "listening" ]
08e16c2292c5cf0fe9322cce72d1ac6c80d372ce
https://github.com/seomoz/qless/blob/08e16c2292c5cf0fe9322cce72d1ac6c80d372ce/lib/qless/subscriber.rb#L28-L44
train
seomoz/qless
lib/qless/queue.rb
Qless.Queue.pop
def pop(count = nil) jids = JSON.parse(@client.call('pop', @name, worker_name, (count || 1))) jobs = jids.map { |j| Job.new(@client, j) } count.nil? ? jobs[0] : jobs end
ruby
def pop(count = nil) jids = JSON.parse(@client.call('pop', @name, worker_name, (count || 1))) jobs = jids.map { |j| Job.new(@client, j) } count.nil? ? jobs[0] : jobs end
[ "def", "pop", "(", "count", "=", "nil", ")", "jids", "=", "JSON", ".", "parse", "(", "@client", ".", "call", "(", "'pop'", ",", "@name", ",", "worker_name", ",", "(", "count", "||", "1", ")", ")", ")", "jobs", "=", "jids", ".", "map", "{", "|", "j", "|", "Job", ".", "new", "(", "@client", ",", "j", ")", "}", "count", ".", "nil?", "?", "jobs", "[", "0", "]", ":", "jobs", "end" ]
Pop a work item off the queue
[ "Pop", "a", "work", "item", "off", "the", "queue" ]
08e16c2292c5cf0fe9322cce72d1ac6c80d372ce
https://github.com/seomoz/qless/blob/08e16c2292c5cf0fe9322cce72d1ac6c80d372ce/lib/qless/queue.rb#L143-L147
train
seomoz/qless
lib/qless/queue.rb
Qless.Queue.peek
def peek(count = nil) jids = JSON.parse(@client.call('peek', @name, (count || 1))) jobs = jids.map { |j| Job.new(@client, j) } count.nil? ? jobs[0] : jobs end
ruby
def peek(count = nil) jids = JSON.parse(@client.call('peek', @name, (count || 1))) jobs = jids.map { |j| Job.new(@client, j) } count.nil? ? jobs[0] : jobs end
[ "def", "peek", "(", "count", "=", "nil", ")", "jids", "=", "JSON", ".", "parse", "(", "@client", ".", "call", "(", "'peek'", ",", "@name", ",", "(", "count", "||", "1", ")", ")", ")", "jobs", "=", "jids", ".", "map", "{", "|", "j", "|", "Job", ".", "new", "(", "@client", ",", "j", ")", "}", "count", ".", "nil?", "?", "jobs", "[", "0", "]", ":", "jobs", "end" ]
Peek at a work item
[ "Peek", "at", "a", "work", "item" ]
08e16c2292c5cf0fe9322cce72d1ac6c80d372ce
https://github.com/seomoz/qless/blob/08e16c2292c5cf0fe9322cce72d1ac6c80d372ce/lib/qless/queue.rb#L150-L154
train
seomoz/qless
lib/qless/queue.rb
Qless.Queue.length
def length (@client.redis.multi do %w[ locks work scheduled depends ].each do |suffix| @client.redis.zcard("ql:q:#{@name}-#{suffix}") end end).inject(0, :+) end
ruby
def length (@client.redis.multi do %w[ locks work scheduled depends ].each do |suffix| @client.redis.zcard("ql:q:#{@name}-#{suffix}") end end).inject(0, :+) end
[ "def", "length", "(", "@client", ".", "redis", ".", "multi", "do", "%w[", "locks", "work", "scheduled", "depends", "]", ".", "each", "do", "|", "suffix", "|", "@client", ".", "redis", ".", "zcard", "(", "\"ql:q:#{@name}-#{suffix}\"", ")", "end", "end", ")", ".", "inject", "(", "0", ",", ":+", ")", "end" ]
How many items in the queue?
[ "How", "many", "items", "in", "the", "queue?" ]
08e16c2292c5cf0fe9322cce72d1ac6c80d372ce
https://github.com/seomoz/qless/blob/08e16c2292c5cf0fe9322cce72d1ac6c80d372ce/lib/qless/queue.rb#L161-L167
train
norman/friendly_id-globalize
lib/friendly_id/history.rb
FriendlyId.History.scope_for_slug_generator
def scope_for_slug_generator relation = super return relation if new_record? relation = relation.merge(Slug.where('sluggable_id <> ?', id)) if friendly_id_config.uses?(:scoped) relation = relation.where(Slug.arel_table[:scope].eq(serialized_scope)) end relation end
ruby
def scope_for_slug_generator relation = super return relation if new_record? relation = relation.merge(Slug.where('sluggable_id <> ?', id)) if friendly_id_config.uses?(:scoped) relation = relation.where(Slug.arel_table[:scope].eq(serialized_scope)) end relation end
[ "def", "scope_for_slug_generator", "relation", "=", "super", "return", "relation", "if", "new_record?", "relation", "=", "relation", ".", "merge", "(", "Slug", ".", "where", "(", "'sluggable_id <> ?'", ",", "id", ")", ")", "if", "friendly_id_config", ".", "uses?", "(", ":scoped", ")", "relation", "=", "relation", ".", "where", "(", "Slug", ".", "arel_table", "[", ":scope", "]", ".", "eq", "(", "serialized_scope", ")", ")", "end", "relation", "end" ]
If we're updating, don't consider historic slugs for the same record to be conflicts. This will allow a record to revert to a previously used slug.
[ "If", "we", "re", "updating", "don", "t", "consider", "historic", "slugs", "for", "the", "same", "record", "to", "be", "conflicts", ".", "This", "will", "allow", "a", "record", "to", "revert", "to", "a", "previously", "used", "slug", "." ]
b5c1b8b442f62d174759000facf5fb8b0eed280e
https://github.com/norman/friendly_id-globalize/blob/b5c1b8b442f62d174759000facf5fb8b0eed280e/lib/friendly_id/history.rb#L110-L118
train
chef/chef-apply
lib/chef_apply/target_host.rb
ChefApply.TargetHost.connect!
def connect! # Keep existing connections return unless @backend.nil? @backend = train_connection.connection @backend.wait_until_ready # When the testing function `mock_instance` is used, it will set # this instance variable to false and handle this function call # after the platform data is mocked; this will allow binding # of mixin functions based on the mocked platform. mix_in_target_platform! unless @mocked_connection rescue Train::UserError => e raise ConnectionFailure.new(e, config) rescue Train::Error => e # These are typically wrapper errors for other problems, # so we'll prefer to use e.cause over e if available. raise ConnectionFailure.new(e.cause || e, config) end
ruby
def connect! # Keep existing connections return unless @backend.nil? @backend = train_connection.connection @backend.wait_until_ready # When the testing function `mock_instance` is used, it will set # this instance variable to false and handle this function call # after the platform data is mocked; this will allow binding # of mixin functions based on the mocked platform. mix_in_target_platform! unless @mocked_connection rescue Train::UserError => e raise ConnectionFailure.new(e, config) rescue Train::Error => e # These are typically wrapper errors for other problems, # so we'll prefer to use e.cause over e if available. raise ConnectionFailure.new(e.cause || e, config) end
[ "def", "connect!", "return", "unless", "@backend", ".", "nil?", "@backend", "=", "train_connection", ".", "connection", "@backend", ".", "wait_until_ready", "mix_in_target_platform!", "unless", "@mocked_connection", "rescue", "Train", "::", "UserError", "=>", "e", "raise", "ConnectionFailure", ".", "new", "(", "e", ",", "config", ")", "rescue", "Train", "::", "Error", "=>", "e", "raise", "ConnectionFailure", ".", "new", "(", "e", ".", "cause", "||", "e", ",", "config", ")", "end" ]
Establish connection to configured target.
[ "Establish", "connection", "to", "configured", "target", "." ]
f3619c5af73714cfec942cbd1dae05c510c467e3
https://github.com/chef/chef-apply/blob/f3619c5af73714cfec942cbd1dae05c510c467e3/lib/chef_apply/target_host.rb#L114-L131
train
chef/chef-apply
lib/chef_apply/target_host.rb
ChefApply.TargetHost.fetch_file_contents
def fetch_file_contents(remote_path) result = backend.file(remote_path) if result.exist? && result.file? result.content else nil end end
ruby
def fetch_file_contents(remote_path) result = backend.file(remote_path) if result.exist? && result.file? result.content else nil end end
[ "def", "fetch_file_contents", "(", "remote_path", ")", "result", "=", "backend", ".", "file", "(", "remote_path", ")", "if", "result", ".", "exist?", "&&", "result", ".", "file?", "result", ".", "content", "else", "nil", "end", "end" ]
Retrieve the contents of a remote file. Returns nil if the file didn't exist or couldn't be read.
[ "Retrieve", "the", "contents", "of", "a", "remote", "file", ".", "Returns", "nil", "if", "the", "file", "didn", "t", "exist", "or", "couldn", "t", "be", "read", "." ]
f3619c5af73714cfec942cbd1dae05c510c467e3
https://github.com/chef/chef-apply/blob/f3619c5af73714cfec942cbd1dae05c510c467e3/lib/chef_apply/target_host.rb#L198-L205
train
chef/chef-apply
lib/chef_apply/target_resolver.rb
ChefApply.TargetResolver.targets
def targets return @targets unless @targets.nil? expanded_urls = [] @split_targets.each do |target| expanded_urls = (expanded_urls | expand_targets(target)) end @targets = expanded_urls.map do |url| config = @conn_options.merge(config_for_target(url)) TargetHost.new(config.delete(:url), config) end end
ruby
def targets return @targets unless @targets.nil? expanded_urls = [] @split_targets.each do |target| expanded_urls = (expanded_urls | expand_targets(target)) end @targets = expanded_urls.map do |url| config = @conn_options.merge(config_for_target(url)) TargetHost.new(config.delete(:url), config) end end
[ "def", "targets", "return", "@targets", "unless", "@targets", ".", "nil?", "expanded_urls", "=", "[", "]", "@split_targets", ".", "each", "do", "|", "target", "|", "expanded_urls", "=", "(", "expanded_urls", "|", "expand_targets", "(", "target", ")", ")", "end", "@targets", "=", "expanded_urls", ".", "map", "do", "|", "url", "|", "config", "=", "@conn_options", ".", "merge", "(", "config_for_target", "(", "url", ")", ")", "TargetHost", ".", "new", "(", "config", ".", "delete", "(", ":url", ")", ",", "config", ")", "end", "end" ]
Returns the list of targets as an array of TargetHost instances, them to account for ranges embedded in the target name.
[ "Returns", "the", "list", "of", "targets", "as", "an", "array", "of", "TargetHost", "instances", "them", "to", "account", "for", "ranges", "embedded", "in", "the", "target", "name", "." ]
f3619c5af73714cfec942cbd1dae05c510c467e3
https://github.com/chef/chef-apply/blob/f3619c5af73714cfec942cbd1dae05c510c467e3/lib/chef_apply/target_resolver.rb#L36-L46
train
chef/chef-apply
lib/chef_apply/recipe_lookup.rb
ChefApply.RecipeLookup.load_cookbook
def load_cookbook(path_or_name) require "chef/exceptions" if File.directory?(path_or_name) cookbook_path = path_or_name # First, is there a cookbook in the specified dir that matches? require "chef/cookbook/cookbook_version_loader" begin v = Chef::Cookbook::CookbookVersionLoader.new(cookbook_path) v.load! cookbook = v.cookbook_version rescue Chef::Exceptions::CookbookNotFoundInRepo raise InvalidCookbook.new(cookbook_path) end else cookbook_name = path_or_name # Second, is there a cookbook in their local repository that matches? require "chef/cookbook_loader" cb_loader = Chef::CookbookLoader.new(cookbook_repo_paths) cb_loader.load_cookbooks_without_shadow_warning begin cookbook = cb_loader[cookbook_name] rescue Chef::Exceptions::CookbookNotFoundInRepo cookbook_repo_paths.each do |repo_path| cookbook_path = File.join(repo_path, cookbook_name) if File.directory?(cookbook_path) raise InvalidCookbook.new(cookbook_path) end end raise CookbookNotFound.new(cookbook_name, cookbook_repo_paths) end end cookbook end
ruby
def load_cookbook(path_or_name) require "chef/exceptions" if File.directory?(path_or_name) cookbook_path = path_or_name # First, is there a cookbook in the specified dir that matches? require "chef/cookbook/cookbook_version_loader" begin v = Chef::Cookbook::CookbookVersionLoader.new(cookbook_path) v.load! cookbook = v.cookbook_version rescue Chef::Exceptions::CookbookNotFoundInRepo raise InvalidCookbook.new(cookbook_path) end else cookbook_name = path_or_name # Second, is there a cookbook in their local repository that matches? require "chef/cookbook_loader" cb_loader = Chef::CookbookLoader.new(cookbook_repo_paths) cb_loader.load_cookbooks_without_shadow_warning begin cookbook = cb_loader[cookbook_name] rescue Chef::Exceptions::CookbookNotFoundInRepo cookbook_repo_paths.each do |repo_path| cookbook_path = File.join(repo_path, cookbook_name) if File.directory?(cookbook_path) raise InvalidCookbook.new(cookbook_path) end end raise CookbookNotFound.new(cookbook_name, cookbook_repo_paths) end end cookbook end
[ "def", "load_cookbook", "(", "path_or_name", ")", "require", "\"chef/exceptions\"", "if", "File", ".", "directory?", "(", "path_or_name", ")", "cookbook_path", "=", "path_or_name", "require", "\"chef/cookbook/cookbook_version_loader\"", "begin", "v", "=", "Chef", "::", "Cookbook", "::", "CookbookVersionLoader", ".", "new", "(", "cookbook_path", ")", "v", ".", "load!", "cookbook", "=", "v", ".", "cookbook_version", "rescue", "Chef", "::", "Exceptions", "::", "CookbookNotFoundInRepo", "raise", "InvalidCookbook", ".", "new", "(", "cookbook_path", ")", "end", "else", "cookbook_name", "=", "path_or_name", "require", "\"chef/cookbook_loader\"", "cb_loader", "=", "Chef", "::", "CookbookLoader", ".", "new", "(", "cookbook_repo_paths", ")", "cb_loader", ".", "load_cookbooks_without_shadow_warning", "begin", "cookbook", "=", "cb_loader", "[", "cookbook_name", "]", "rescue", "Chef", "::", "Exceptions", "::", "CookbookNotFoundInRepo", "cookbook_repo_paths", ".", "each", "do", "|", "repo_path", "|", "cookbook_path", "=", "File", ".", "join", "(", "repo_path", ",", "cookbook_name", ")", "if", "File", ".", "directory?", "(", "cookbook_path", ")", "raise", "InvalidCookbook", ".", "new", "(", "cookbook_path", ")", "end", "end", "raise", "CookbookNotFound", ".", "new", "(", "cookbook_name", ",", "cookbook_repo_paths", ")", "end", "end", "cookbook", "end" ]
Given a cookbook path or name, try to load that cookbook. Either return a cookbook object or raise an error.
[ "Given", "a", "cookbook", "path", "or", "name", "try", "to", "load", "that", "cookbook", ".", "Either", "return", "a", "cookbook", "object", "or", "raise", "an", "error", "." ]
f3619c5af73714cfec942cbd1dae05c510c467e3
https://github.com/chef/chef-apply/blob/f3619c5af73714cfec942cbd1dae05c510c467e3/lib/chef_apply/recipe_lookup.rb#L43-L76
train
chef/chef-apply
lib/chef_apply/recipe_lookup.rb
ChefApply.RecipeLookup.find_recipe
def find_recipe(cookbook, recipe_name = nil) recipes = cookbook.recipe_filenames_by_name if recipe_name.nil? default_recipe = recipes["default"] raise NoDefaultRecipe.new(cookbook.root_dir, cookbook.name) if default_recipe.nil? default_recipe else recipe = recipes[recipe_name] raise RecipeNotFound.new(cookbook.root_dir, recipe_name, recipes.keys, cookbook.name) if recipe.nil? recipe end end
ruby
def find_recipe(cookbook, recipe_name = nil) recipes = cookbook.recipe_filenames_by_name if recipe_name.nil? default_recipe = recipes["default"] raise NoDefaultRecipe.new(cookbook.root_dir, cookbook.name) if default_recipe.nil? default_recipe else recipe = recipes[recipe_name] raise RecipeNotFound.new(cookbook.root_dir, recipe_name, recipes.keys, cookbook.name) if recipe.nil? recipe end end
[ "def", "find_recipe", "(", "cookbook", ",", "recipe_name", "=", "nil", ")", "recipes", "=", "cookbook", ".", "recipe_filenames_by_name", "if", "recipe_name", ".", "nil?", "default_recipe", "=", "recipes", "[", "\"default\"", "]", "raise", "NoDefaultRecipe", ".", "new", "(", "cookbook", ".", "root_dir", ",", "cookbook", ".", "name", ")", "if", "default_recipe", ".", "nil?", "default_recipe", "else", "recipe", "=", "recipes", "[", "recipe_name", "]", "raise", "RecipeNotFound", ".", "new", "(", "cookbook", ".", "root_dir", ",", "recipe_name", ",", "recipes", ".", "keys", ",", "cookbook", ".", "name", ")", "if", "recipe", ".", "nil?", "recipe", "end", "end" ]
Find the specified recipe or default recipe if none is specified. Raise an error if recipe cannot be found.
[ "Find", "the", "specified", "recipe", "or", "default", "recipe", "if", "none", "is", "specified", ".", "Raise", "an", "error", "if", "recipe", "cannot", "be", "found", "." ]
f3619c5af73714cfec942cbd1dae05c510c467e3
https://github.com/chef/chef-apply/blob/f3619c5af73714cfec942cbd1dae05c510c467e3/lib/chef_apply/recipe_lookup.rb#L80-L91
train
chef/chef-apply
lib/chef_apply/cli.rb
ChefApply.CLI.connect_target
def connect_target(target_host, reporter) connect_message = T.status.connecting(target_host.user) reporter.update(connect_message) do_connect(target_host, reporter) end
ruby
def connect_target(target_host, reporter) connect_message = T.status.connecting(target_host.user) reporter.update(connect_message) do_connect(target_host, reporter) end
[ "def", "connect_target", "(", "target_host", ",", "reporter", ")", "connect_message", "=", "T", ".", "status", ".", "connecting", "(", "target_host", ".", "user", ")", "reporter", ".", "update", "(", "connect_message", ")", "do_connect", "(", "target_host", ",", "reporter", ")", "end" ]
Accepts a target_host and establishes the connection to that host while providing visual feedback via the Terminal API.
[ "Accepts", "a", "target_host", "and", "establishes", "the", "connection", "to", "that", "host", "while", "providing", "visual", "feedback", "via", "the", "Terminal", "API", "." ]
f3619c5af73714cfec942cbd1dae05c510c467e3
https://github.com/chef/chef-apply/blob/f3619c5af73714cfec942cbd1dae05c510c467e3/lib/chef_apply/cli.rb#L164-L168
train
chef/chef-apply
lib/chef_apply/cli.rb
ChefApply.CLI.generate_local_policy
def generate_local_policy(reporter) action = Action::GenerateLocalPolicy.new(cookbook: temp_cookbook) action.run do |event, data| case event when :generating reporter.update(TS.generate_local_policy.generating) when :exporting reporter.update(TS.generate_local_policy.exporting) when :success reporter.success(TS.generate_local_policy.success) else handle_message(event, data, reporter) end end action.archive_file_location end
ruby
def generate_local_policy(reporter) action = Action::GenerateLocalPolicy.new(cookbook: temp_cookbook) action.run do |event, data| case event when :generating reporter.update(TS.generate_local_policy.generating) when :exporting reporter.update(TS.generate_local_policy.exporting) when :success reporter.success(TS.generate_local_policy.success) else handle_message(event, data, reporter) end end action.archive_file_location end
[ "def", "generate_local_policy", "(", "reporter", ")", "action", "=", "Action", "::", "GenerateLocalPolicy", ".", "new", "(", "cookbook", ":", "temp_cookbook", ")", "action", ".", "run", "do", "|", "event", ",", "data", "|", "case", "event", "when", ":generating", "reporter", ".", "update", "(", "TS", ".", "generate_local_policy", ".", "generating", ")", "when", ":exporting", "reporter", ".", "update", "(", "TS", ".", "generate_local_policy", ".", "exporting", ")", "when", ":success", "reporter", ".", "success", "(", "TS", ".", "generate_local_policy", ".", "success", ")", "else", "handle_message", "(", "event", ",", "data", ",", "reporter", ")", "end", "end", "action", ".", "archive_file_location", "end" ]
Runs the GenerateLocalPolicy action and renders UI updates as the action reports back
[ "Runs", "the", "GenerateLocalPolicy", "action", "and", "renders", "UI", "updates", "as", "the", "action", "reports", "back" ]
f3619c5af73714cfec942cbd1dae05c510c467e3
https://github.com/chef/chef-apply/blob/f3619c5af73714cfec942cbd1dae05c510c467e3/lib/chef_apply/cli.rb#L229-L244
train
chef/chef-apply
lib/chef_apply/cli.rb
ChefApply.CLI.converge
def converge(reporter, local_policy_path, target_host) reporter.update(TS.converge.converging(temp_cookbook.descriptor)) converge_args = { local_policy_path: local_policy_path, target_host: target_host } converger = Action::ConvergeTarget.new(converge_args) converger.run do |event, data| case event when :success reporter.success(TS.converge.success(temp_cookbook.descriptor)) when :converge_error reporter.error(TS.converge.failure(temp_cookbook.descriptor)) when :creating_remote_policy reporter.update(TS.converge.creating_remote_policy) when :uploading_trusted_certs reporter.update(TS.converge.uploading_trusted_certs) when :running_chef reporter.update(TS.converge.converging(temp_cookbook.descriptor)) when :reboot reporter.success(TS.converge.reboot) else handle_message(event, data, reporter) end end end
ruby
def converge(reporter, local_policy_path, target_host) reporter.update(TS.converge.converging(temp_cookbook.descriptor)) converge_args = { local_policy_path: local_policy_path, target_host: target_host } converger = Action::ConvergeTarget.new(converge_args) converger.run do |event, data| case event when :success reporter.success(TS.converge.success(temp_cookbook.descriptor)) when :converge_error reporter.error(TS.converge.failure(temp_cookbook.descriptor)) when :creating_remote_policy reporter.update(TS.converge.creating_remote_policy) when :uploading_trusted_certs reporter.update(TS.converge.uploading_trusted_certs) when :running_chef reporter.update(TS.converge.converging(temp_cookbook.descriptor)) when :reboot reporter.success(TS.converge.reboot) else handle_message(event, data, reporter) end end end
[ "def", "converge", "(", "reporter", ",", "local_policy_path", ",", "target_host", ")", "reporter", ".", "update", "(", "TS", ".", "converge", ".", "converging", "(", "temp_cookbook", ".", "descriptor", ")", ")", "converge_args", "=", "{", "local_policy_path", ":", "local_policy_path", ",", "target_host", ":", "target_host", "}", "converger", "=", "Action", "::", "ConvergeTarget", ".", "new", "(", "converge_args", ")", "converger", ".", "run", "do", "|", "event", ",", "data", "|", "case", "event", "when", ":success", "reporter", ".", "success", "(", "TS", ".", "converge", ".", "success", "(", "temp_cookbook", ".", "descriptor", ")", ")", "when", ":converge_error", "reporter", ".", "error", "(", "TS", ".", "converge", ".", "failure", "(", "temp_cookbook", ".", "descriptor", ")", ")", "when", ":creating_remote_policy", "reporter", ".", "update", "(", "TS", ".", "converge", ".", "creating_remote_policy", ")", "when", ":uploading_trusted_certs", "reporter", ".", "update", "(", "TS", ".", "converge", ".", "uploading_trusted_certs", ")", "when", ":running_chef", "reporter", ".", "update", "(", "TS", ".", "converge", ".", "converging", "(", "temp_cookbook", ".", "descriptor", ")", ")", "when", ":reboot", "reporter", ".", "success", "(", "TS", ".", "converge", ".", "reboot", ")", "else", "handle_message", "(", "event", ",", "data", ",", "reporter", ")", "end", "end", "end" ]
Runs the Converge action and renders UI updates as the action reports back
[ "Runs", "the", "Converge", "action", "and", "renders", "UI", "updates", "as", "the", "action", "reports", "back" ]
f3619c5af73714cfec942cbd1dae05c510c467e3
https://github.com/chef/chef-apply/blob/f3619c5af73714cfec942cbd1dae05c510c467e3/lib/chef_apply/cli.rb#L248-L270
train
chef/chef-apply
lib/chef_apply/cli.rb
ChefApply.CLI.handle_message
def handle_message(message, data, reporter) if message == :error # data[0] = exception # Mark the current task as failed with whatever data is available to us reporter.error(ChefApply::UI::ErrorPrinter.error_summary(data[0])) end end
ruby
def handle_message(message, data, reporter) if message == :error # data[0] = exception # Mark the current task as failed with whatever data is available to us reporter.error(ChefApply::UI::ErrorPrinter.error_summary(data[0])) end end
[ "def", "handle_message", "(", "message", ",", "data", ",", "reporter", ")", "if", "message", "==", ":error", "reporter", ".", "error", "(", "ChefApply", "::", "UI", "::", "ErrorPrinter", ".", "error_summary", "(", "data", "[", "0", "]", ")", ")", "end", "end" ]
A handler for common action messages
[ "A", "handler", "for", "common", "action", "messages" ]
f3619c5af73714cfec942cbd1dae05c510c467e3
https://github.com/chef/chef-apply/blob/f3619c5af73714cfec942cbd1dae05c510c467e3/lib/chef_apply/cli.rb#L307-L312
train
jamesotron/faye-rails
lib/faye-rails/rack_adapter.rb
FayeRails.RackAdapter.map
def map(opts) if opts.is_a? Hash opts.each do |channel, controller| if channel.is_a? String if FayeRails::Matcher.match? '/**', channel routing_extension.map(channel, controller) else raise ArgumentError, "Invalid channel: #{channel}" end elsif channel == :default if controller == :block routing_extension.block_unknown_channels! elsif controller == :drop routing_extension.drop_unknown_channels! elsif controller == :allow routing_extension.allow_unknown_channels! end end end end end
ruby
def map(opts) if opts.is_a? Hash opts.each do |channel, controller| if channel.is_a? String if FayeRails::Matcher.match? '/**', channel routing_extension.map(channel, controller) else raise ArgumentError, "Invalid channel: #{channel}" end elsif channel == :default if controller == :block routing_extension.block_unknown_channels! elsif controller == :drop routing_extension.drop_unknown_channels! elsif controller == :allow routing_extension.allow_unknown_channels! end end end end end
[ "def", "map", "(", "opts", ")", "if", "opts", ".", "is_a?", "Hash", "opts", ".", "each", "do", "|", "channel", ",", "controller", "|", "if", "channel", ".", "is_a?", "String", "if", "FayeRails", "::", "Matcher", ".", "match?", "'/**'", ",", "channel", "routing_extension", ".", "map", "(", "channel", ",", "controller", ")", "else", "raise", "ArgumentError", ",", "\"Invalid channel: #{channel}\"", "end", "elsif", "channel", "==", ":default", "if", "controller", "==", ":block", "routing_extension", ".", "block_unknown_channels!", "elsif", "controller", "==", ":drop", "routing_extension", ".", "drop_unknown_channels!", "elsif", "controller", "==", ":allow", "routing_extension", ".", "allow_unknown_channels!", "end", "end", "end", "end", "end" ]
Rudimentary routing support for channels to controllers. @param opts a Hash of mappings either string keys (channel globs) mapping to controller constants eg: '/widgets/**' => WidgetsController or you can set the behaviour for unknown channels: :default => :block :default can be set to :allow, :drop or :block. if :drop is chosen then messages to unknown channels will be silently dropped, whereas if you choose :block then the message will be returned with the error "Permission denied."
[ "Rudimentary", "routing", "support", "for", "channels", "to", "controllers", "." ]
82943a0337546117f8ec9d1a40f8f6b251aac4b5
https://github.com/jamesotron/faye-rails/blob/82943a0337546117f8ec9d1a40f8f6b251aac4b5/lib/faye-rails/rack_adapter.rb#L30-L50
train
contentful/contentful_rails
lib/contentful_rails/markdown_renderer.rb
ContentfulRails.MarkdownRenderer.image
def image(link, title, alt_text) # add the querystring to the image if @image_parameters.present? prefix = link.include?('?') ? '&' : '?' link += "#{prefix}#{@image_parameters.to_query}" end # return a content tag content_tag(:img, nil, src: link.to_s, alt: alt_text, title: title) end
ruby
def image(link, title, alt_text) # add the querystring to the image if @image_parameters.present? prefix = link.include?('?') ? '&' : '?' link += "#{prefix}#{@image_parameters.to_query}" end # return a content tag content_tag(:img, nil, src: link.to_s, alt: alt_text, title: title) end
[ "def", "image", "(", "link", ",", "title", ",", "alt_text", ")", "if", "@image_parameters", ".", "present?", "prefix", "=", "link", ".", "include?", "(", "'?'", ")", "?", "'&'", ":", "'?'", "link", "+=", "\"#{prefix}#{@image_parameters.to_query}\"", "end", "content_tag", "(", ":img", ",", "nil", ",", "src", ":", "link", ".", "to_s", ",", "alt", ":", "alt_text", ",", "title", ":", "title", ")", "end" ]
Image tag wrapper for forwarding Image API options
[ "Image", "tag", "wrapper", "for", "forwarding", "Image", "API", "options" ]
6c9b50631c8f9a1ade89dea6736285371d3f7969
https://github.com/contentful/contentful_rails/blob/6c9b50631c8f9a1ade89dea6736285371d3f7969/lib/contentful_rails/markdown_renderer.rb#L28-L36
train
contentful/contentful_rails
lib/contentful_rails/nested_resource.rb
ContentfulRails.NestedResource.get_child_entity_from_path_by
def get_child_entity_from_path_by(field, children) # the next child in the path child_value = children.shift # get the child entity child = send(:children).find { |c| c.send(field) == child_value } # we have some recursion to do - we're not at the end of the array # so call this method again with a smaller set of children return child.get_child_entity_from_path_by(field, children) if child && !children.empty? child # this is the final thing in the array - return it end
ruby
def get_child_entity_from_path_by(field, children) # the next child in the path child_value = children.shift # get the child entity child = send(:children).find { |c| c.send(field) == child_value } # we have some recursion to do - we're not at the end of the array # so call this method again with a smaller set of children return child.get_child_entity_from_path_by(field, children) if child && !children.empty? child # this is the final thing in the array - return it end
[ "def", "get_child_entity_from_path_by", "(", "field", ",", "children", ")", "child_value", "=", "children", ".", "shift", "child", "=", "send", "(", ":children", ")", ".", "find", "{", "|", "c", "|", "c", ".", "send", "(", "field", ")", "==", "child_value", "}", "return", "child", ".", "get_child_entity_from_path_by", "(", "field", ",", "children", ")", "if", "child", "&&", "!", "children", ".", "empty?", "child", "end" ]
Given a field and an array of child fields, we need to recurse through them to get the last one @param field [Symbol] the field we need to search for @param children [Array] an array of field values to match against @return an entity matching this class, which is the last in the tree
[ "Given", "a", "field", "and", "an", "array", "of", "child", "fields", "we", "need", "to", "recurse", "through", "them", "to", "get", "the", "last", "one" ]
6c9b50631c8f9a1ade89dea6736285371d3f7969
https://github.com/contentful/contentful_rails/blob/6c9b50631c8f9a1ade89dea6736285371d3f7969/lib/contentful_rails/nested_resource.rb#L51-L63
train
contentful/contentful_rails
app/helpers/contentful_rails/markdown_helper.rb
ContentfulRails.MarkdownHelper.parse_markdown
def parse_markdown(markdown_string, renderer_options: {}, markdown_options: {}, image_options: {}) markdown_string ||= '' markdown_opts = { no_intr_emphasis: true, tables: true, fenced_code_blocks: true, autolink: true, disable_indented_code_blocks: true, strikethrough: true, lax_spacing: true, space_after_headers: false, superscript: true, underline: true, highlight: true, footnotes: true }.merge(markdown_options) renderer_opts = { filter_html: false, # we want to allow HTML in the markdown blocks no_images: false, no_links: false, no_styles: false, escape_html: false, safe_links_only: false, with_toc_data: true, hard_wrap: true, xhtml: false, prettify: false, link_attributes: {}, image_options: image_options }.merge(renderer_options) renderer = ContentfulRails::MarkdownRenderer.new(renderer_opts) markdown = Redcarpet::Markdown.new(renderer, markdown_opts) markdown.render(markdown_string).html_safe end
ruby
def parse_markdown(markdown_string, renderer_options: {}, markdown_options: {}, image_options: {}) markdown_string ||= '' markdown_opts = { no_intr_emphasis: true, tables: true, fenced_code_blocks: true, autolink: true, disable_indented_code_blocks: true, strikethrough: true, lax_spacing: true, space_after_headers: false, superscript: true, underline: true, highlight: true, footnotes: true }.merge(markdown_options) renderer_opts = { filter_html: false, # we want to allow HTML in the markdown blocks no_images: false, no_links: false, no_styles: false, escape_html: false, safe_links_only: false, with_toc_data: true, hard_wrap: true, xhtml: false, prettify: false, link_attributes: {}, image_options: image_options }.merge(renderer_options) renderer = ContentfulRails::MarkdownRenderer.new(renderer_opts) markdown = Redcarpet::Markdown.new(renderer, markdown_opts) markdown.render(markdown_string).html_safe end
[ "def", "parse_markdown", "(", "markdown_string", ",", "renderer_options", ":", "{", "}", ",", "markdown_options", ":", "{", "}", ",", "image_options", ":", "{", "}", ")", "markdown_string", "||=", "''", "markdown_opts", "=", "{", "no_intr_emphasis", ":", "true", ",", "tables", ":", "true", ",", "fenced_code_blocks", ":", "true", ",", "autolink", ":", "true", ",", "disable_indented_code_blocks", ":", "true", ",", "strikethrough", ":", "true", ",", "lax_spacing", ":", "true", ",", "space_after_headers", ":", "false", ",", "superscript", ":", "true", ",", "underline", ":", "true", ",", "highlight", ":", "true", ",", "footnotes", ":", "true", "}", ".", "merge", "(", "markdown_options", ")", "renderer_opts", "=", "{", "filter_html", ":", "false", ",", "no_images", ":", "false", ",", "no_links", ":", "false", ",", "no_styles", ":", "false", ",", "escape_html", ":", "false", ",", "safe_links_only", ":", "false", ",", "with_toc_data", ":", "true", ",", "hard_wrap", ":", "true", ",", "xhtml", ":", "false", ",", "prettify", ":", "false", ",", "link_attributes", ":", "{", "}", ",", "image_options", ":", "image_options", "}", ".", "merge", "(", "renderer_options", ")", "renderer", "=", "ContentfulRails", "::", "MarkdownRenderer", ".", "new", "(", "renderer_opts", ")", "markdown", "=", "Redcarpet", "::", "Markdown", ".", "new", "(", "renderer", ",", "markdown_opts", ")", "markdown", ".", "render", "(", "markdown_string", ")", ".", "html_safe", "end" ]
Return HTML which is passed through the Redcarpet markdown processor, using a custom renderer so that we can manipulate images using contentful's URL-based API. NOTE that this is super-permissive out of the box. Set options to suit when you call the method. @param renderer_options [Hash] of options from https://github.com/vmg/redcarpet#darling-i-packed-you-a-couple-renderers-for-lunch @param markdown_options [Hash] of options from https://github.com/vmg/redcarpet#and-its-like-really-simple-to-use @param image_options [Hash] of options to pass to the Image API. https://github.com/contentful/contentful_rails#manipulating-images
[ "Return", "HTML", "which", "is", "passed", "through", "the", "Redcarpet", "markdown", "processor", "using", "a", "custom", "renderer", "so", "that", "we", "can", "manipulate", "images", "using", "contentful", "s", "URL", "-", "based", "API", ".", "NOTE", "that", "this", "is", "super", "-", "permissive", "out", "of", "the", "box", ".", "Set", "options", "to", "suit", "when", "you", "call", "the", "method", "." ]
6c9b50631c8f9a1ade89dea6736285371d3f7969
https://github.com/contentful/contentful_rails/blob/6c9b50631c8f9a1ade89dea6736285371d3f7969/app/helpers/contentful_rails/markdown_helper.rb#L11-L47
train
contentful/contentful_rails
app/controllers/contentful_rails/webhooks_controller.rb
ContentfulRails.WebhooksController.create
def create # The only things we need to handle in here (for now at least) are entries. # If there's been an update or a deletion, we just remove the cached timestamp. # The updated_at method which is included in ContentfulModel::Base in this gem # will check the cache first before making the call to the API. # We can then just use normal Rails russian doll caching without expensive API calls. request.format = :json update_type = request.headers['HTTP_X_CONTENTFUL_TOPIC'] # All we do here is publish an ActiveSupport::Notification, which is subscribed to # elsewhere. In this gem are subscription options for timestamp or object caching, # implement your own and subscribe in an initializer. ActiveSupport::Notifications.instrument("Contentful.#{update_type}", params) # must return an empty response render body: nil end
ruby
def create # The only things we need to handle in here (for now at least) are entries. # If there's been an update or a deletion, we just remove the cached timestamp. # The updated_at method which is included in ContentfulModel::Base in this gem # will check the cache first before making the call to the API. # We can then just use normal Rails russian doll caching without expensive API calls. request.format = :json update_type = request.headers['HTTP_X_CONTENTFUL_TOPIC'] # All we do here is publish an ActiveSupport::Notification, which is subscribed to # elsewhere. In this gem are subscription options for timestamp or object caching, # implement your own and subscribe in an initializer. ActiveSupport::Notifications.instrument("Contentful.#{update_type}", params) # must return an empty response render body: nil end
[ "def", "create", "request", ".", "format", "=", ":json", "update_type", "=", "request", ".", "headers", "[", "'HTTP_X_CONTENTFUL_TOPIC'", "]", "ActiveSupport", "::", "Notifications", ".", "instrument", "(", "\"Contentful.#{update_type}\"", ",", "params", ")", "render", "body", ":", "nil", "end" ]
this is where we receive a webhook, via a POST
[ "this", "is", "where", "we", "receive", "a", "webhook", "via", "a", "POST" ]
6c9b50631c8f9a1ade89dea6736285371d3f7969
https://github.com/contentful/contentful_rails/blob/6c9b50631c8f9a1ade89dea6736285371d3f7969/app/controllers/contentful_rails/webhooks_controller.rb#L20-L37
train
alphagov/govspeak
lib/govspeak/presenters/attachment_presenter.rb
Govspeak.AttachmentPresenter.references_for_title
def references_for_title references = [] references << "ISBN: #{attachment[:isbn]}" if attachment[:isbn].present? references << "Unique reference: #{attachment[:unique_reference]}" if attachment[:unique_reference].present? references << "Command paper number: #{attachment[:command_paper_number]}" if attachment[:command_paper_number].present? references << "HC: #{attachment[:hoc_paper_number]} #{attachment[:parliamentary_session]}" if attachment[:hoc_paper_number].present? prefix = references.size == 1 ? "and its reference" : "and its references" references.any? ? ", #{prefix} (" + references.join(", ") + ")" : "" end
ruby
def references_for_title references = [] references << "ISBN: #{attachment[:isbn]}" if attachment[:isbn].present? references << "Unique reference: #{attachment[:unique_reference]}" if attachment[:unique_reference].present? references << "Command paper number: #{attachment[:command_paper_number]}" if attachment[:command_paper_number].present? references << "HC: #{attachment[:hoc_paper_number]} #{attachment[:parliamentary_session]}" if attachment[:hoc_paper_number].present? prefix = references.size == 1 ? "and its reference" : "and its references" references.any? ? ", #{prefix} (" + references.join(", ") + ")" : "" end
[ "def", "references_for_title", "references", "=", "[", "]", "references", "<<", "\"ISBN: #{attachment[:isbn]}\"", "if", "attachment", "[", ":isbn", "]", ".", "present?", "references", "<<", "\"Unique reference: #{attachment[:unique_reference]}\"", "if", "attachment", "[", ":unique_reference", "]", ".", "present?", "references", "<<", "\"Command paper number: #{attachment[:command_paper_number]}\"", "if", "attachment", "[", ":command_paper_number", "]", ".", "present?", "references", "<<", "\"HC: #{attachment[:hoc_paper_number]} #{attachment[:parliamentary_session]}\"", "if", "attachment", "[", ":hoc_paper_number", "]", ".", "present?", "prefix", "=", "references", ".", "size", "==", "1", "?", "\"and its reference\"", ":", "\"and its references\"", "references", ".", "any?", "?", "\", #{prefix} (\"", "+", "references", ".", "join", "(", "\", \"", ")", "+", "\")\"", ":", "\"\"", "end" ]
FIXME this has english in it so will cause problems if the locale is not en
[ "FIXME", "this", "has", "english", "in", "it", "so", "will", "cause", "problems", "if", "the", "locale", "is", "not", "en" ]
f626b20e9e0a742cc4c9f4a946a80c87aa63a8da
https://github.com/alphagov/govspeak/blob/f626b20e9e0a742cc4c9f4a946a80c87aa63a8da/lib/govspeak/presenters/attachment_presenter.rb#L145-L153
train
rmodbus/rmodbus
lib/rmodbus/tcp.rb
ModBus.TCP.open_tcp_connection
def open_tcp_connection(ipaddr, port, opts = {}) @ipaddr, @port = ipaddr, port timeout = opts[:connect_timeout] ||= 1 io = nil begin io = Socket.tcp(@ipaddr, @port, nil, nil, connect_timeout: timeout) rescue Errno::ECONNREFUSED, Errno::ETIMEDOUT raise ModBusTimeout.new, 'Timed out attempting to create connection' end io end
ruby
def open_tcp_connection(ipaddr, port, opts = {}) @ipaddr, @port = ipaddr, port timeout = opts[:connect_timeout] ||= 1 io = nil begin io = Socket.tcp(@ipaddr, @port, nil, nil, connect_timeout: timeout) rescue Errno::ECONNREFUSED, Errno::ETIMEDOUT raise ModBusTimeout.new, 'Timed out attempting to create connection' end io end
[ "def", "open_tcp_connection", "(", "ipaddr", ",", "port", ",", "opts", "=", "{", "}", ")", "@ipaddr", ",", "@port", "=", "ipaddr", ",", "port", "timeout", "=", "opts", "[", ":connect_timeout", "]", "||=", "1", "io", "=", "nil", "begin", "io", "=", "Socket", ".", "tcp", "(", "@ipaddr", ",", "@port", ",", "nil", ",", "nil", ",", "connect_timeout", ":", "timeout", ")", "rescue", "Errno", "::", "ECONNREFUSED", ",", "Errno", "::", "ETIMEDOUT", "raise", "ModBusTimeout", ".", "new", ",", "'Timed out attempting to create connection'", "end", "io", "end" ]
Open TCP socket @param [String] ipaddr IP address of remote server @param [Integer] port connection port @param [Hash] opts options of connection @option opts [Float, Integer] :connect_timeout seconds timeout for open socket @return [Socket] socket @raise [ModBusTimeout] timed out attempting to create connection
[ "Open", "TCP", "socket" ]
a411958521cb300c9d69edb9ca6cba075303b0dc
https://github.com/rmodbus/rmodbus/blob/a411958521cb300c9d69edb9ca6cba075303b0dc/lib/rmodbus/tcp.rb#L16-L29
train
rmodbus/rmodbus
lib/rmodbus/debug.rb
ModBus.Debug.logging_bytes
def logging_bytes(msg) result = "" msg.each_byte do |c| byte = if c < 16 '0' + c.to_s(16) else c.to_s(16) end result << "[#{byte}]" end result end
ruby
def logging_bytes(msg) result = "" msg.each_byte do |c| byte = if c < 16 '0' + c.to_s(16) else c.to_s(16) end result << "[#{byte}]" end result end
[ "def", "logging_bytes", "(", "msg", ")", "result", "=", "\"\"", "msg", ".", "each_byte", "do", "|", "c", "|", "byte", "=", "if", "c", "<", "16", "'0'", "+", "c", ".", "to_s", "(", "16", ")", "else", "c", ".", "to_s", "(", "16", ")", "end", "result", "<<", "\"[#{byte}]\"", "end", "result", "end" ]
Convert string of byte to string for log @example logging_bytes("\x1\xa\x8") => "[01][0a][08]" @param [String] msg input string @return [String] readable string of bytes
[ "Convert", "string", "of", "byte", "to", "string", "for", "log" ]
a411958521cb300c9d69edb9ca6cba075303b0dc
https://github.com/rmodbus/rmodbus/blob/a411958521cb300c9d69edb9ca6cba075303b0dc/lib/rmodbus/debug.rb#L19-L30
train
rmodbus/rmodbus
lib/rmodbus/slave.rb
ModBus.Slave.write_single_coil
def write_single_coil(addr, val) if val == 0 query("\x5" + addr.to_word + 0.to_word) else query("\x5" + addr.to_word + 0xff00.to_word) end self end
ruby
def write_single_coil(addr, val) if val == 0 query("\x5" + addr.to_word + 0.to_word) else query("\x5" + addr.to_word + 0xff00.to_word) end self end
[ "def", "write_single_coil", "(", "addr", ",", "val", ")", "if", "val", "==", "0", "query", "(", "\"\\x5\"", "+", "addr", ".", "to_word", "+", "0", ".", "to_word", ")", "else", "query", "(", "\"\\x5\"", "+", "addr", ".", "to_word", "+", "0xff00", ".", "to_word", ")", "end", "self", "end" ]
Write a single coil @example write_single_coil(1, 0) => self @param [Integer] addr address coil @param [Integer] val value coil (0 or other) @return self
[ "Write", "a", "single", "coil" ]
a411958521cb300c9d69edb9ca6cba075303b0dc
https://github.com/rmodbus/rmodbus/blob/a411958521cb300c9d69edb9ca6cba075303b0dc/lib/rmodbus/slave.rb#L58-L65
train
rmodbus/rmodbus
lib/rmodbus/slave.rb
ModBus.Slave.write_multiple_coils
def write_multiple_coils(addr, vals) nbyte = ((vals.size-1) >> 3) + 1 sum = 0 (vals.size - 1).downto(0) do |i| sum = sum << 1 sum |= 1 if vals[i] > 0 end s_val = "" nbyte.times do s_val << (sum & 0xff).chr sum >>= 8 end query("\xf" + addr.to_word + vals.size.to_word + nbyte.chr + s_val) self end
ruby
def write_multiple_coils(addr, vals) nbyte = ((vals.size-1) >> 3) + 1 sum = 0 (vals.size - 1).downto(0) do |i| sum = sum << 1 sum |= 1 if vals[i] > 0 end s_val = "" nbyte.times do s_val << (sum & 0xff).chr sum >>= 8 end query("\xf" + addr.to_word + vals.size.to_word + nbyte.chr + s_val) self end
[ "def", "write_multiple_coils", "(", "addr", ",", "vals", ")", "nbyte", "=", "(", "(", "vals", ".", "size", "-", "1", ")", ">>", "3", ")", "+", "1", "sum", "=", "0", "(", "vals", ".", "size", "-", "1", ")", ".", "downto", "(", "0", ")", "do", "|", "i", "|", "sum", "=", "sum", "<<", "1", "sum", "|=", "1", "if", "vals", "[", "i", "]", ">", "0", "end", "s_val", "=", "\"\"", "nbyte", ".", "times", "do", "s_val", "<<", "(", "sum", "&", "0xff", ")", ".", "chr", "sum", ">>=", "8", "end", "query", "(", "\"\\xf\"", "+", "addr", ".", "to_word", "+", "vals", ".", "size", ".", "to_word", "+", "nbyte", ".", "chr", "+", "s_val", ")", "self", "end" ]
Write multiple coils @example write_multiple_coils(1, [0,1,0,1]) => self @param [Integer] addr address first coil @param [Array] vals written coils
[ "Write", "multiple", "coils" ]
a411958521cb300c9d69edb9ca6cba075303b0dc
https://github.com/rmodbus/rmodbus/blob/a411958521cb300c9d69edb9ca6cba075303b0dc/lib/rmodbus/slave.rb#L75-L91
train
rmodbus/rmodbus
lib/rmodbus/slave.rb
ModBus.Slave.read_discrete_inputs
def read_discrete_inputs(addr, ninputs) query("\x2" + addr.to_word + ninputs.to_word).unpack_bits[0..ninputs-1] end
ruby
def read_discrete_inputs(addr, ninputs) query("\x2" + addr.to_word + ninputs.to_word).unpack_bits[0..ninputs-1] end
[ "def", "read_discrete_inputs", "(", "addr", ",", "ninputs", ")", "query", "(", "\"\\x2\"", "+", "addr", ".", "to_word", "+", "ninputs", ".", "to_word", ")", ".", "unpack_bits", "[", "0", "..", "ninputs", "-", "1", "]", "end" ]
Read discrete inputs @example read_discrete_inputs(addr, ninputs) => [1, 0, ..] @param [Integer] addr address first input @param[Integer] ninputs number inputs @return [Array] inputs
[ "Read", "discrete", "inputs" ]
a411958521cb300c9d69edb9ca6cba075303b0dc
https://github.com/rmodbus/rmodbus/blob/a411958521cb300c9d69edb9ca6cba075303b0dc/lib/rmodbus/slave.rb#L113-L115
train
rmodbus/rmodbus
lib/rmodbus/slave.rb
ModBus.Slave.write_multiple_registers
def write_multiple_registers(addr, vals) s_val = "" vals.each do |reg| s_val << reg.to_word end query("\x10" + addr.to_word + vals.size.to_word + (vals.size * 2).chr + s_val) self end
ruby
def write_multiple_registers(addr, vals) s_val = "" vals.each do |reg| s_val << reg.to_word end query("\x10" + addr.to_word + vals.size.to_word + (vals.size * 2).chr + s_val) self end
[ "def", "write_multiple_registers", "(", "addr", ",", "vals", ")", "s_val", "=", "\"\"", "vals", ".", "each", "do", "|", "reg", "|", "s_val", "<<", "reg", ".", "to_word", "end", "query", "(", "\"\\x10\"", "+", "addr", ".", "to_word", "+", "vals", ".", "size", ".", "to_word", "+", "(", "vals", ".", "size", "*", "2", ")", ".", "chr", "+", "s_val", ")", "self", "end" ]
Write multiple holding registers @example write_multiple_registers(1, [0xaa, 0]) => self @param [Integer] addr address first registers @param [Array] val written registers @return self
[ "Write", "multiple", "holding", "registers" ]
a411958521cb300c9d69edb9ca6cba075303b0dc
https://github.com/rmodbus/rmodbus/blob/a411958521cb300c9d69edb9ca6cba075303b0dc/lib/rmodbus/slave.rb#L191-L199
train
rmodbus/rmodbus
lib/rmodbus/slave.rb
ModBus.Slave.mask_write_register
def mask_write_register(addr, and_mask, or_mask) query("\x16" + addr.to_word + and_mask.to_word + or_mask.to_word) self end
ruby
def mask_write_register(addr, and_mask, or_mask) query("\x16" + addr.to_word + and_mask.to_word + or_mask.to_word) self end
[ "def", "mask_write_register", "(", "addr", ",", "and_mask", ",", "or_mask", ")", "query", "(", "\"\\x16\"", "+", "addr", ".", "to_word", "+", "and_mask", ".", "to_word", "+", "or_mask", ".", "to_word", ")", "self", "end" ]
Mask a holding register @example mask_write_register(1, 0xAAAA, 0x00FF) => self @param [Integer] addr address registers @param [Integer] and_mask mask for AND operation @param [Integer] or_mask mask for OR operation
[ "Mask", "a", "holding", "register" ]
a411958521cb300c9d69edb9ca6cba075303b0dc
https://github.com/rmodbus/rmodbus/blob/a411958521cb300c9d69edb9ca6cba075303b0dc/lib/rmodbus/slave.rb#L209-L212
train
rmodbus/rmodbus
lib/rmodbus/slave.rb
ModBus.Slave.query
def query(request) tried = 0 response = "" begin ::Timeout.timeout(@read_retry_timeout, ModBusTimeout) do send_pdu(request) response = read_pdu end rescue ModBusTimeout => err log "Timeout of read operation: (#{@read_retries - tried})" tried += 1 retry unless tried >= @read_retries raise ModBusTimeout.new, "Timed out during read attempt" end return nil if response.size == 0 read_func = response.getbyte(0) if read_func >= 0x80 exc_id = response.getbyte(1) raise Exceptions[exc_id] unless Exceptions[exc_id].nil? raise ModBusException.new, "Unknown error" end check_response_mismatch(request, response) if raise_exception_on_mismatch response[2..-1] end
ruby
def query(request) tried = 0 response = "" begin ::Timeout.timeout(@read_retry_timeout, ModBusTimeout) do send_pdu(request) response = read_pdu end rescue ModBusTimeout => err log "Timeout of read operation: (#{@read_retries - tried})" tried += 1 retry unless tried >= @read_retries raise ModBusTimeout.new, "Timed out during read attempt" end return nil if response.size == 0 read_func = response.getbyte(0) if read_func >= 0x80 exc_id = response.getbyte(1) raise Exceptions[exc_id] unless Exceptions[exc_id].nil? raise ModBusException.new, "Unknown error" end check_response_mismatch(request, response) if raise_exception_on_mismatch response[2..-1] end
[ "def", "query", "(", "request", ")", "tried", "=", "0", "response", "=", "\"\"", "begin", "::", "Timeout", ".", "timeout", "(", "@read_retry_timeout", ",", "ModBusTimeout", ")", "do", "send_pdu", "(", "request", ")", "response", "=", "read_pdu", "end", "rescue", "ModBusTimeout", "=>", "err", "log", "\"Timeout of read operation: (#{@read_retries - tried})\"", "tried", "+=", "1", "retry", "unless", "tried", ">=", "@read_retries", "raise", "ModBusTimeout", ".", "new", ",", "\"Timed out during read attempt\"", "end", "return", "nil", "if", "response", ".", "size", "==", "0", "read_func", "=", "response", ".", "getbyte", "(", "0", ")", "if", "read_func", ">=", "0x80", "exc_id", "=", "response", ".", "getbyte", "(", "1", ")", "raise", "Exceptions", "[", "exc_id", "]", "unless", "Exceptions", "[", "exc_id", "]", ".", "nil?", "raise", "ModBusException", ".", "new", ",", "\"Unknown error\"", "end", "check_response_mismatch", "(", "request", ",", "response", ")", "if", "raise_exception_on_mismatch", "response", "[", "2", "..", "-", "1", "]", "end" ]
Request pdu to slave device @param [String] pdu request to slave @return [String] received data @raise [ResponseMismatch] the received echo response differs from the request @raise [ModBusTimeout] timed out during read attempt @raise [ModBusException] unknown error @raise [IllegalFunction] function code received in the query is not an allowable action for the server @raise [IllegalDataAddress] data address received in the query is not an allowable address for the server @raise [IllegalDataValue] value contained in the query data field is not an allowable value for server @raise [SlaveDeviceFailure] unrecoverable error occurred while the server was attempting to perform the requested action @raise [Acknowledge] server has accepted the request and is processing it, but a long duration of time will be required to do so @raise [SlaveDeviceBus] server is engaged in processing a long duration program command @raise [MemoryParityError] extended file area failed to pass a consistency check
[ "Request", "pdu", "to", "slave", "device" ]
a411958521cb300c9d69edb9ca6cba075303b0dc
https://github.com/rmodbus/rmodbus/blob/a411958521cb300c9d69edb9ca6cba075303b0dc/lib/rmodbus/slave.rb#L229-L256
train
rmodbus/rmodbus
lib/rmodbus/proxy.rb
ModBus.ReadOnlyProxy.[]
def [](key) if key.instance_of?(0.class) @slave.send("read_#{@type}", key, 1) elsif key.instance_of?(Range) @slave.send("read_#{@type}s", key.first, key.count) else raise ModBus::Errors::ProxyException, "Invalid argument, must be integer or range. Was #{key.class}" end end
ruby
def [](key) if key.instance_of?(0.class) @slave.send("read_#{@type}", key, 1) elsif key.instance_of?(Range) @slave.send("read_#{@type}s", key.first, key.count) else raise ModBus::Errors::ProxyException, "Invalid argument, must be integer or range. Was #{key.class}" end end
[ "def", "[]", "(", "key", ")", "if", "key", ".", "instance_of?", "(", "0", ".", "class", ")", "@slave", ".", "send", "(", "\"read_#{@type}\"", ",", "key", ",", "1", ")", "elsif", "key", ".", "instance_of?", "(", "Range", ")", "@slave", ".", "send", "(", "\"read_#{@type}s\"", ",", "key", ".", "first", ",", "key", ".", "count", ")", "else", "raise", "ModBus", "::", "Errors", "::", "ProxyException", ",", "\"Invalid argument, must be integer or range. Was #{key.class}\"", "end", "end" ]
Initialize a proxy for a slave and a type of operation Read single or multiple values from a modbus slave depending on whether a Fixnum or a Range was given. Note that in the case of multiples, a pluralized version of the method is sent to the slave
[ "Initialize", "a", "proxy", "for", "a", "slave", "and", "a", "type", "of", "operation", "Read", "single", "or", "multiple", "values", "from", "a", "modbus", "slave", "depending", "on", "whether", "a", "Fixnum", "or", "a", "Range", "was", "given", ".", "Note", "that", "in", "the", "case", "of", "multiples", "a", "pluralized", "version", "of", "the", "method", "is", "sent", "to", "the", "slave" ]
a411958521cb300c9d69edb9ca6cba075303b0dc
https://github.com/rmodbus/rmodbus/blob/a411958521cb300c9d69edb9ca6cba075303b0dc/lib/rmodbus/proxy.rb#L11-L19
train
rmodbus/rmodbus
lib/rmodbus/proxy.rb
ModBus.ReadWriteProxy.[]=
def []=(key, val) if key.instance_of?(0.class) @slave.send("write_#{@type}", key, val) elsif key.instance_of?(Range) if key.count != val.size raise ModBus::Errors::ProxyException, "The size of the range must match the size of the values (#{key.count} != #{val.size})" end @slave.send("write_#{@type}s", key.first, val) else raise ModBus::Errors::ProxyException, "Invalid argument, must be integer or range. Was #{key.class}" end end
ruby
def []=(key, val) if key.instance_of?(0.class) @slave.send("write_#{@type}", key, val) elsif key.instance_of?(Range) if key.count != val.size raise ModBus::Errors::ProxyException, "The size of the range must match the size of the values (#{key.count} != #{val.size})" end @slave.send("write_#{@type}s", key.first, val) else raise ModBus::Errors::ProxyException, "Invalid argument, must be integer or range. Was #{key.class}" end end
[ "def", "[]=", "(", "key", ",", "val", ")", "if", "key", ".", "instance_of?", "(", "0", ".", "class", ")", "@slave", ".", "send", "(", "\"write_#{@type}\"", ",", "key", ",", "val", ")", "elsif", "key", ".", "instance_of?", "(", "Range", ")", "if", "key", ".", "count", "!=", "val", ".", "size", "raise", "ModBus", "::", "Errors", "::", "ProxyException", ",", "\"The size of the range must match the size of the values (#{key.count} != #{val.size})\"", "end", "@slave", ".", "send", "(", "\"write_#{@type}s\"", ",", "key", ".", "first", ",", "val", ")", "else", "raise", "ModBus", "::", "Errors", "::", "ProxyException", ",", "\"Invalid argument, must be integer or range. Was #{key.class}\"", "end", "end" ]
Write single or multiple values to a modbus slave depending on whether a Fixnum or a Range was given. Note that in the case of multiples, a pluralized version of the method is sent to the slave. Also when writing multiple values, the number of elements must match the number of registers in the range or an exception is raised
[ "Write", "single", "or", "multiple", "values", "to", "a", "modbus", "slave", "depending", "on", "whether", "a", "Fixnum", "or", "a", "Range", "was", "given", ".", "Note", "that", "in", "the", "case", "of", "multiples", "a", "pluralized", "version", "of", "the", "method", "is", "sent", "to", "the", "slave", ".", "Also", "when", "writing", "multiple", "values", "the", "number", "of", "elements", "must", "match", "the", "number", "of", "registers", "in", "the", "range", "or", "an", "exception", "is", "raised" ]
a411958521cb300c9d69edb9ca6cba075303b0dc
https://github.com/rmodbus/rmodbus/blob/a411958521cb300c9d69edb9ca6cba075303b0dc/lib/rmodbus/proxy.rb#L26-L38
train
rmodbus/rmodbus
lib/rmodbus/rtu.rb
ModBus.RTU.read_rtu_response
def read_rtu_response(io) # Read the slave_id and function code msg = nil while msg.nil? msg = io.read(2) end function_code = msg.getbyte(1) case function_code when 1,2,3,4 then # read the third byte to find out how much more # we need to read + CRC msg += io.read(1) msg += io.read(msg.getbyte(2)+2) when 5,6,15,16 then # We just read in an additional 6 bytes msg += io.read(6) when 22 then msg += io.read(8) when 0x80..0xff then msg += io.read(3) else raise ModBus::Errors::IllegalFunction, "Illegal function: #{function_code}" end end
ruby
def read_rtu_response(io) # Read the slave_id and function code msg = nil while msg.nil? msg = io.read(2) end function_code = msg.getbyte(1) case function_code when 1,2,3,4 then # read the third byte to find out how much more # we need to read + CRC msg += io.read(1) msg += io.read(msg.getbyte(2)+2) when 5,6,15,16 then # We just read in an additional 6 bytes msg += io.read(6) when 22 then msg += io.read(8) when 0x80..0xff then msg += io.read(3) else raise ModBus::Errors::IllegalFunction, "Illegal function: #{function_code}" end end
[ "def", "read_rtu_response", "(", "io", ")", "msg", "=", "nil", "while", "msg", ".", "nil?", "msg", "=", "io", ".", "read", "(", "2", ")", "end", "function_code", "=", "msg", ".", "getbyte", "(", "1", ")", "case", "function_code", "when", "1", ",", "2", ",", "3", ",", "4", "then", "msg", "+=", "io", ".", "read", "(", "1", ")", "msg", "+=", "io", ".", "read", "(", "msg", ".", "getbyte", "(", "2", ")", "+", "2", ")", "when", "5", ",", "6", ",", "15", ",", "16", "then", "msg", "+=", "io", ".", "read", "(", "6", ")", "when", "22", "then", "msg", "+=", "io", ".", "read", "(", "8", ")", "when", "0x80", "..", "0xff", "then", "msg", "+=", "io", ".", "read", "(", "3", ")", "else", "raise", "ModBus", "::", "Errors", "::", "IllegalFunction", ",", "\"Illegal function: #{function_code}\"", "end", "end" ]
We have to read specific amounts of numbers of bytes from the network depending on the function code and content
[ "We", "have", "to", "read", "specific", "amounts", "of", "numbers", "of", "bytes", "from", "the", "network", "depending", "on", "the", "function", "code", "and", "content" ]
a411958521cb300c9d69edb9ca6cba075303b0dc
https://github.com/rmodbus/rmodbus/blob/a411958521cb300c9d69edb9ca6cba075303b0dc/lib/rmodbus/rtu.rb#L6-L30
train
rmodbus/rmodbus
lib/rmodbus/rtu.rb
ModBus.RTU.crc16
def crc16(msg) crc_lo = 0xff crc_hi = 0xff msg.unpack('c*').each do |byte| i = crc_hi ^ byte crc_hi = crc_lo ^ CrcHiTable[i] crc_lo = CrcLoTable[i] end return ((crc_hi << 8) + crc_lo) end
ruby
def crc16(msg) crc_lo = 0xff crc_hi = 0xff msg.unpack('c*').each do |byte| i = crc_hi ^ byte crc_hi = crc_lo ^ CrcHiTable[i] crc_lo = CrcLoTable[i] end return ((crc_hi << 8) + crc_lo) end
[ "def", "crc16", "(", "msg", ")", "crc_lo", "=", "0xff", "crc_hi", "=", "0xff", "msg", ".", "unpack", "(", "'c*'", ")", ".", "each", "do", "|", "byte", "|", "i", "=", "crc_hi", "^", "byte", "crc_hi", "=", "crc_lo", "^", "CrcHiTable", "[", "i", "]", "crc_lo", "=", "CrcLoTable", "[", "i", "]", "end", "return", "(", "(", "crc_hi", "<<", "8", ")", "+", "crc_lo", ")", "end" ]
Calc CRC16 for massage
[ "Calc", "CRC16", "for", "massage" ]
a411958521cb300c9d69edb9ca6cba075303b0dc
https://github.com/rmodbus/rmodbus/blob/a411958521cb300c9d69edb9ca6cba075303b0dc/lib/rmodbus/rtu.rb#L111-L122
train
ammar/regexp_parser
lib/regexp_parser/expression/methods/traverse.rb
Regexp::Expression.Subexpression.each_expression
def each_expression(include_self = false, &block) traverse(include_self) do |event, exp, index| yield(exp, index) unless event == :exit end end
ruby
def each_expression(include_self = false, &block) traverse(include_self) do |event, exp, index| yield(exp, index) unless event == :exit end end
[ "def", "each_expression", "(", "include_self", "=", "false", ",", "&", "block", ")", "traverse", "(", "include_self", ")", "do", "|", "event", ",", "exp", ",", "index", "|", "yield", "(", "exp", ",", "index", ")", "unless", "event", "==", ":exit", "end", "end" ]
Iterates over the expressions of this expression as an array, passing the expression and its index within its parent to the given block.
[ "Iterates", "over", "the", "expressions", "of", "this", "expression", "as", "an", "array", "passing", "the", "expression", "and", "its", "index", "within", "its", "parent", "to", "the", "given", "block", "." ]
24cb67d5f6e7ddaab2ff9806e5f60bb6fcb7d5ba
https://github.com/ammar/regexp_parser/blob/24cb67d5f6e7ddaab2ff9806e5f60bb6fcb7d5ba/lib/regexp_parser/expression/methods/traverse.rb#L39-L43
train
ammar/regexp_parser
lib/regexp_parser/expression/methods/traverse.rb
Regexp::Expression.Subexpression.flat_map
def flat_map(include_self = false, &block) result = [] each_expression(include_self) do |exp, index| if block_given? result << yield(exp, index) else result << [exp, index] end end result end
ruby
def flat_map(include_self = false, &block) result = [] each_expression(include_self) do |exp, index| if block_given? result << yield(exp, index) else result << [exp, index] end end result end
[ "def", "flat_map", "(", "include_self", "=", "false", ",", "&", "block", ")", "result", "=", "[", "]", "each_expression", "(", "include_self", ")", "do", "|", "exp", ",", "index", "|", "if", "block_given?", "result", "<<", "yield", "(", "exp", ",", "index", ")", "else", "result", "<<", "[", "exp", ",", "index", "]", "end", "end", "result", "end" ]
Returns a new array with the results of calling the given block once for every expression. If a block is not given, returns an array with each expression and its level index as an array.
[ "Returns", "a", "new", "array", "with", "the", "results", "of", "calling", "the", "given", "block", "once", "for", "every", "expression", ".", "If", "a", "block", "is", "not", "given", "returns", "an", "array", "with", "each", "expression", "and", "its", "level", "index", "as", "an", "array", "." ]
24cb67d5f6e7ddaab2ff9806e5f60bb6fcb7d5ba
https://github.com/ammar/regexp_parser/blob/24cb67d5f6e7ddaab2ff9806e5f60bb6fcb7d5ba/lib/regexp_parser/expression/methods/traverse.rb#L48-L60
train
kobaltz/clamby
lib/clamby/command.rb
Clamby.Command.run
def run(executable, *args) executable_full = executable_path(executable) self.command = args | default_args self.command = command.sort.unshift(executable_full) system(*self.command, system_options) end
ruby
def run(executable, *args) executable_full = executable_path(executable) self.command = args | default_args self.command = command.sort.unshift(executable_full) system(*self.command, system_options) end
[ "def", "run", "(", "executable", ",", "*", "args", ")", "executable_full", "=", "executable_path", "(", "executable", ")", "self", ".", "command", "=", "args", "|", "default_args", "self", ".", "command", "=", "command", ".", "sort", ".", "unshift", "(", "executable_full", ")", "system", "(", "*", "self", ".", "command", ",", "system_options", ")", "end" ]
Run the given commands via a system call. The executable must be one of the permitted ClamAV executables. The arguments will be combined with default arguments if needed. The arguments are sorted alphabetically before being passed to the system. Examples: run('clamscan', file, '--verbose') run('clamscan', '-V')
[ "Run", "the", "given", "commands", "via", "a", "system", "call", ".", "The", "executable", "must", "be", "one", "of", "the", "permitted", "ClamAV", "executables", ".", "The", "arguments", "will", "be", "combined", "with", "default", "arguments", "if", "needed", ".", "The", "arguments", "are", "sorted", "alphabetically", "before", "being", "passed", "to", "the", "system", "." ]
8e04f7c2a467721b9ac2f8b266a228e32f4ccfbe
https://github.com/kobaltz/clamby/blob/8e04f7c2a467721b9ac2f8b266a228e32f4ccfbe/lib/clamby/command.rb#L66-L72
train
couchrest/couchrest
lib/couchrest/design.rb
CouchRest.Design.view_on
def view_on db, view_name, query = {}, &block raise ArgumentError, "View query options must be set as symbols!" if query.keys.find{|k| k.is_a?(String)} view_name = view_name.to_s view_slug = "#{name}/#{view_name}" # Set the default query options query = view_defaults(view_name).merge(query) # Ensure reduce is set if dealing with a reduceable view # This is a requirement of CouchDB. query[:reduce] ||= false if can_reduce_view?(view_name) db.view(view_slug, query, &block) end
ruby
def view_on db, view_name, query = {}, &block raise ArgumentError, "View query options must be set as symbols!" if query.keys.find{|k| k.is_a?(String)} view_name = view_name.to_s view_slug = "#{name}/#{view_name}" # Set the default query options query = view_defaults(view_name).merge(query) # Ensure reduce is set if dealing with a reduceable view # This is a requirement of CouchDB. query[:reduce] ||= false if can_reduce_view?(view_name) db.view(view_slug, query, &block) end
[ "def", "view_on", "db", ",", "view_name", ",", "query", "=", "{", "}", ",", "&", "block", "raise", "ArgumentError", ",", "\"View query options must be set as symbols!\"", "if", "query", ".", "keys", ".", "find", "{", "|", "k", "|", "k", ".", "is_a?", "(", "String", ")", "}", "view_name", "=", "view_name", ".", "to_s", "view_slug", "=", "\"#{name}/#{view_name}\"", "query", "=", "view_defaults", "(", "view_name", ")", ".", "merge", "(", "query", ")", "query", "[", ":reduce", "]", "||=", "false", "if", "can_reduce_view?", "(", "view_name", ")", "db", ".", "view", "(", "view_slug", ",", "query", ",", "&", "block", ")", "end" ]
Dispatches to any named view in a specific database
[ "Dispatches", "to", "any", "named", "view", "in", "a", "specific", "database" ]
cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9
https://github.com/couchrest/couchrest/blob/cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9/lib/couchrest/design.rb#L43-L53
train
couchrest/couchrest
lib/couchrest/helper/attachments.rb
CouchRest.Attachments.put_attachment
def put_attachment(name, file, options={}) raise ArgumentError, "doc must be saved" unless self.rev raise ArgumentError, "doc.database required to put_attachment" unless database result = database.put_attachment(self, name, file, options) self['_rev'] = result['rev'] result['ok'] end
ruby
def put_attachment(name, file, options={}) raise ArgumentError, "doc must be saved" unless self.rev raise ArgumentError, "doc.database required to put_attachment" unless database result = database.put_attachment(self, name, file, options) self['_rev'] = result['rev'] result['ok'] end
[ "def", "put_attachment", "(", "name", ",", "file", ",", "options", "=", "{", "}", ")", "raise", "ArgumentError", ",", "\"doc must be saved\"", "unless", "self", ".", "rev", "raise", "ArgumentError", ",", "\"doc.database required to put_attachment\"", "unless", "database", "result", "=", "database", ".", "put_attachment", "(", "self", ",", "name", ",", "file", ",", "options", ")", "self", "[", "'_rev'", "]", "=", "result", "[", "'rev'", "]", "result", "[", "'ok'", "]", "end" ]
saves an attachment directly to couchdb
[ "saves", "an", "attachment", "directly", "to", "couchdb" ]
cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9
https://github.com/couchrest/couchrest/blob/cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9/lib/couchrest/helper/attachments.rb#L5-L11
train
couchrest/couchrest
lib/couchrest/helper/attachments.rb
CouchRest.Attachments.fetch_attachment
def fetch_attachment(name) raise ArgumentError, "doc must be saved" unless self.rev raise ArgumentError, "doc.database required to put_attachment" unless database database.fetch_attachment(self, name) end
ruby
def fetch_attachment(name) raise ArgumentError, "doc must be saved" unless self.rev raise ArgumentError, "doc.database required to put_attachment" unless database database.fetch_attachment(self, name) end
[ "def", "fetch_attachment", "(", "name", ")", "raise", "ArgumentError", ",", "\"doc must be saved\"", "unless", "self", ".", "rev", "raise", "ArgumentError", ",", "\"doc.database required to put_attachment\"", "unless", "database", "database", ".", "fetch_attachment", "(", "self", ",", "name", ")", "end" ]
returns an attachment's data
[ "returns", "an", "attachment", "s", "data" ]
cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9
https://github.com/couchrest/couchrest/blob/cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9/lib/couchrest/helper/attachments.rb#L14-L18
train
couchrest/couchrest
lib/couchrest/helper/attachments.rb
CouchRest.Attachments.delete_attachment
def delete_attachment(name, force=false) raise ArgumentError, "doc.database required to delete_attachment" unless database result = database.delete_attachment(self, name, force) self['_rev'] = result['rev'] result['ok'] end
ruby
def delete_attachment(name, force=false) raise ArgumentError, "doc.database required to delete_attachment" unless database result = database.delete_attachment(self, name, force) self['_rev'] = result['rev'] result['ok'] end
[ "def", "delete_attachment", "(", "name", ",", "force", "=", "false", ")", "raise", "ArgumentError", ",", "\"doc.database required to delete_attachment\"", "unless", "database", "result", "=", "database", ".", "delete_attachment", "(", "self", ",", "name", ",", "force", ")", "self", "[", "'_rev'", "]", "=", "result", "[", "'rev'", "]", "result", "[", "'ok'", "]", "end" ]
deletes an attachment directly from couchdb
[ "deletes", "an", "attachment", "directly", "from", "couchdb" ]
cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9
https://github.com/couchrest/couchrest/blob/cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9/lib/couchrest/helper/attachments.rb#L21-L26
train
couchrest/couchrest
lib/couchrest/document.rb
CouchRest.Document.uri
def uri(append_rev = false) return nil if new? couch_uri = "#{database.root}/#{CGI.escape(id)}" if append_rev == true couch_uri << "?rev=#{rev}" elsif append_rev.kind_of?(Integer) couch_uri << "?rev=#{append_rev}" end couch_uri end
ruby
def uri(append_rev = false) return nil if new? couch_uri = "#{database.root}/#{CGI.escape(id)}" if append_rev == true couch_uri << "?rev=#{rev}" elsif append_rev.kind_of?(Integer) couch_uri << "?rev=#{append_rev}" end couch_uri end
[ "def", "uri", "(", "append_rev", "=", "false", ")", "return", "nil", "if", "new?", "couch_uri", "=", "\"#{database.root}/#{CGI.escape(id)}\"", "if", "append_rev", "==", "true", "couch_uri", "<<", "\"?rev=#{rev}\"", "elsif", "append_rev", ".", "kind_of?", "(", "Integer", ")", "couch_uri", "<<", "\"?rev=#{append_rev}\"", "end", "couch_uri", "end" ]
Returns the CouchDB uri for the document
[ "Returns", "the", "CouchDB", "uri", "for", "the", "document" ]
cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9
https://github.com/couchrest/couchrest/blob/cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9/lib/couchrest/document.rb#L78-L87
train
couchrest/couchrest
lib/couchrest/connection.rb
CouchRest.Connection.clean_uri
def clean_uri(uri) uri = uri.dup uri.path = "" uri.query = nil uri.fragment = nil uri end
ruby
def clean_uri(uri) uri = uri.dup uri.path = "" uri.query = nil uri.fragment = nil uri end
[ "def", "clean_uri", "(", "uri", ")", "uri", "=", "uri", ".", "dup", "uri", ".", "path", "=", "\"\"", "uri", ".", "query", "=", "nil", "uri", ".", "fragment", "=", "nil", "uri", "end" ]
Duplicate and remove excess baggage from the provided URI
[ "Duplicate", "and", "remove", "excess", "baggage", "from", "the", "provided", "URI" ]
cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9
https://github.com/couchrest/couchrest/blob/cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9/lib/couchrest/connection.rb#L102-L108
train
couchrest/couchrest
lib/couchrest/connection.rb
CouchRest.Connection.prepare_http_connection
def prepare_http_connection conn = HTTPClient.new(options[:proxy] || self.class.proxy) set_http_connection_options(conn, options) conn end
ruby
def prepare_http_connection conn = HTTPClient.new(options[:proxy] || self.class.proxy) set_http_connection_options(conn, options) conn end
[ "def", "prepare_http_connection", "conn", "=", "HTTPClient", ".", "new", "(", "options", "[", ":proxy", "]", "||", "self", ".", "class", ".", "proxy", ")", "set_http_connection_options", "(", "conn", ",", "options", ")", "conn", "end" ]
Take a look at the options povided and try to apply them to the HTTP conneciton.
[ "Take", "a", "look", "at", "the", "options", "povided", "and", "try", "to", "apply", "them", "to", "the", "HTTP", "conneciton", "." ]
cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9
https://github.com/couchrest/couchrest/blob/cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9/lib/couchrest/connection.rb#L111-L115
train
couchrest/couchrest
lib/couchrest/connection.rb
CouchRest.Connection.set_http_connection_options
def set_http_connection_options(conn, opts) # Authentication unless uri.user.to_s.empty? conn.force_basic_auth = true conn.set_auth(uri.to_s, uri.user, uri.password) end # SSL Certificate option mapping if opts.include?(:verify_ssl) conn.ssl_config.verify_mode = opts[:verify_ssl] ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE end conn.ssl_config.client_cert = opts[:ssl_client_cert] if opts.include?(:ssl_client_cert) conn.ssl_config.client_key = opts[:ssl_client_key] if opts.include?(:ssl_client_key) conn.ssl_config.set_trust_ca(opts[:ssl_ca_file]) if opts.include?(:ssl_ca_file) # Timeout options conn.receive_timeout = opts[:timeout] if opts.include?(:timeout) conn.connect_timeout = opts[:open_timeout] if opts.include?(:open_timeout) conn.send_timeout = opts[:read_timeout] if opts.include?(:read_timeout) end
ruby
def set_http_connection_options(conn, opts) # Authentication unless uri.user.to_s.empty? conn.force_basic_auth = true conn.set_auth(uri.to_s, uri.user, uri.password) end # SSL Certificate option mapping if opts.include?(:verify_ssl) conn.ssl_config.verify_mode = opts[:verify_ssl] ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE end conn.ssl_config.client_cert = opts[:ssl_client_cert] if opts.include?(:ssl_client_cert) conn.ssl_config.client_key = opts[:ssl_client_key] if opts.include?(:ssl_client_key) conn.ssl_config.set_trust_ca(opts[:ssl_ca_file]) if opts.include?(:ssl_ca_file) # Timeout options conn.receive_timeout = opts[:timeout] if opts.include?(:timeout) conn.connect_timeout = opts[:open_timeout] if opts.include?(:open_timeout) conn.send_timeout = opts[:read_timeout] if opts.include?(:read_timeout) end
[ "def", "set_http_connection_options", "(", "conn", ",", "opts", ")", "unless", "uri", ".", "user", ".", "to_s", ".", "empty?", "conn", ".", "force_basic_auth", "=", "true", "conn", ".", "set_auth", "(", "uri", ".", "to_s", ",", "uri", ".", "user", ",", "uri", ".", "password", ")", "end", "if", "opts", ".", "include?", "(", ":verify_ssl", ")", "conn", ".", "ssl_config", ".", "verify_mode", "=", "opts", "[", ":verify_ssl", "]", "?", "OpenSSL", "::", "SSL", "::", "VERIFY_PEER", ":", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "end", "conn", ".", "ssl_config", ".", "client_cert", "=", "opts", "[", ":ssl_client_cert", "]", "if", "opts", ".", "include?", "(", ":ssl_client_cert", ")", "conn", ".", "ssl_config", ".", "client_key", "=", "opts", "[", ":ssl_client_key", "]", "if", "opts", ".", "include?", "(", ":ssl_client_key", ")", "conn", ".", "ssl_config", ".", "set_trust_ca", "(", "opts", "[", ":ssl_ca_file", "]", ")", "if", "opts", ".", "include?", "(", ":ssl_ca_file", ")", "conn", ".", "receive_timeout", "=", "opts", "[", ":timeout", "]", "if", "opts", ".", "include?", "(", ":timeout", ")", "conn", ".", "connect_timeout", "=", "opts", "[", ":open_timeout", "]", "if", "opts", ".", "include?", "(", ":open_timeout", ")", "conn", ".", "send_timeout", "=", "opts", "[", ":read_timeout", "]", "if", "opts", ".", "include?", "(", ":read_timeout", ")", "end" ]
Prepare the http connection options for HTTPClient. We try to maintain RestClient compatability in option names as this is what we used before.
[ "Prepare", "the", "http", "connection", "options", "for", "HTTPClient", ".", "We", "try", "to", "maintain", "RestClient", "compatability", "in", "option", "names", "as", "this", "is", "what", "we", "used", "before", "." ]
cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9
https://github.com/couchrest/couchrest/blob/cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9/lib/couchrest/connection.rb#L119-L138
train
couchrest/couchrest
lib/couchrest/connection.rb
CouchRest.Connection.send_request
def send_request(req, &block) @last_response = @http.request(req.delete(:method), req.delete(:uri), req, &block) end
ruby
def send_request(req, &block) @last_response = @http.request(req.delete(:method), req.delete(:uri), req, &block) end
[ "def", "send_request", "(", "req", ",", "&", "block", ")", "@last_response", "=", "@http", ".", "request", "(", "req", ".", "delete", "(", ":method", ")", ",", "req", ".", "delete", "(", ":uri", ")", ",", "req", ",", "&", "block", ")", "end" ]
Send request, and leave a reference to the response for debugging purposes
[ "Send", "request", "and", "leave", "a", "reference", "to", "the", "response", "for", "debugging", "purposes" ]
cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9
https://github.com/couchrest/couchrest/blob/cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9/lib/couchrest/connection.rb#L178-L180
train
couchrest/couchrest
lib/couchrest/connection.rb
CouchRest.Connection.payload_from_doc
def payload_from_doc(req, doc, opts = {}) if doc.is_a?(IO) || doc.is_a?(StringIO) || doc.is_a?(Tempfile) # attachments req[:header]['Content-Type'] = mime_for(req[:uri].path) doc elsif opts[:raw] || doc.nil? doc else MultiJson.encode(doc.respond_to?(:as_couch_json) ? doc.as_couch_json : doc) end end
ruby
def payload_from_doc(req, doc, opts = {}) if doc.is_a?(IO) || doc.is_a?(StringIO) || doc.is_a?(Tempfile) # attachments req[:header]['Content-Type'] = mime_for(req[:uri].path) doc elsif opts[:raw] || doc.nil? doc else MultiJson.encode(doc.respond_to?(:as_couch_json) ? doc.as_couch_json : doc) end end
[ "def", "payload_from_doc", "(", "req", ",", "doc", ",", "opts", "=", "{", "}", ")", "if", "doc", ".", "is_a?", "(", "IO", ")", "||", "doc", ".", "is_a?", "(", "StringIO", ")", "||", "doc", ".", "is_a?", "(", "Tempfile", ")", "req", "[", ":header", "]", "[", "'Content-Type'", "]", "=", "mime_for", "(", "req", "[", ":uri", "]", ".", "path", ")", "doc", "elsif", "opts", "[", ":raw", "]", "||", "doc", ".", "nil?", "doc", "else", "MultiJson", ".", "encode", "(", "doc", ".", "respond_to?", "(", ":as_couch_json", ")", "?", "doc", ".", "as_couch_json", ":", "doc", ")", "end", "end" ]
Check if the provided doc is nil or special IO device or temp file. If not, encode it into a string. The options supported are: * :raw TrueClass, if true the payload will not be altered.
[ "Check", "if", "the", "provided", "doc", "is", "nil", "or", "special", "IO", "device", "or", "temp", "file", ".", "If", "not", "encode", "it", "into", "a", "string", "." ]
cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9
https://github.com/couchrest/couchrest/blob/cdd3ad30b9fa9aad5464cb4647c18c198b2c48d9/lib/couchrest/connection.rb#L209-L218
train