id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
24,200
snltd/wavefront-sdk
lib/wavefront-sdk/core/api_caller.rb
Wavefront.ApiCaller.post
def post(path, body = nil, ctype = 'text/plain') body = body.to_json unless body.is_a?(String) make_call(mk_conn(path, 'Content-Type': ctype, 'Accept': 'application/json'), :post, nil, body) end
ruby
def post(path, body = nil, ctype = 'text/plain') body = body.to_json unless body.is_a?(String) make_call(mk_conn(path, 'Content-Type': ctype, 'Accept': 'application/json'), :post, nil, body) end
[ "def", "post", "(", "path", ",", "body", "=", "nil", ",", "ctype", "=", "'text/plain'", ")", "body", "=", "body", ".", "to_json", "unless", "body", ".", "is_a?", "(", "String", ")", "make_call", "(", "mk_conn", "(", "path", ",", "'Content-Type'", ":", "ctype", ",", "'Accept'", ":", "'application/json'", ")", ",", ":post", ",", "nil", ",", "body", ")", "end" ]
Make a POST call to the Wavefront API and return the result as a Ruby hash. @param path [String] path to be appended to the #net[:api_base] path. @param body [String,Object] optional body text to post. Objects will be converted to JSON @param ctype [String] the content type to use when posting @return [Hash] API response
[ "Make", "a", "POST", "call", "to", "the", "Wavefront", "API", "and", "return", "the", "result", "as", "a", "Ruby", "hash", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/core/api_caller.rb#L97-L102
24,201
snltd/wavefront-sdk
lib/wavefront-sdk/core/api_caller.rb
Wavefront.ApiCaller.put
def put(path, body = nil, ctype = 'application/json') make_call(mk_conn(path, 'Content-Type': ctype, 'Accept': 'application/json'), :put, nil, body.to_json) end
ruby
def put(path, body = nil, ctype = 'application/json') make_call(mk_conn(path, 'Content-Type': ctype, 'Accept': 'application/json'), :put, nil, body.to_json) end
[ "def", "put", "(", "path", ",", "body", "=", "nil", ",", "ctype", "=", "'application/json'", ")", "make_call", "(", "mk_conn", "(", "path", ",", "'Content-Type'", ":", "ctype", ",", "'Accept'", ":", "'application/json'", ")", ",", ":put", ",", "nil", ",", "body", ".", "to_json", ")", "end" ]
Make a PUT call to the Wavefront API and return the result as a Ruby hash. @param path [String] path to be appended to the #net[:api_base] path. @param body [String] optional body text to post @param ctype [String] the content type to use when putting @return [Hash] API response
[ "Make", "a", "PUT", "call", "to", "the", "Wavefront", "API", "and", "return", "the", "result", "as", "a", "Ruby", "hash", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/core/api_caller.rb#L113-L117
24,202
snltd/wavefront-sdk
lib/wavefront-sdk/core/api_caller.rb
Wavefront.ApiCaller.verbosity
def verbosity(conn, method, *args) return unless noop || verbose log format('uri: %s %s', method.upcase, conn.url_prefix) return unless args.last && !args.last.empty? log method == :get ? "params: #{args.last}" : "body: #{args.last}" end
ruby
def verbosity(conn, method, *args) return unless noop || verbose log format('uri: %s %s', method.upcase, conn.url_prefix) return unless args.last && !args.last.empty? log method == :get ? "params: #{args.last}" : "body: #{args.last}" end
[ "def", "verbosity", "(", "conn", ",", "method", ",", "*", "args", ")", "return", "unless", "noop", "||", "verbose", "log", "format", "(", "'uri: %s %s'", ",", "method", ".", "upcase", ",", "conn", ".", "url_prefix", ")", "return", "unless", "args", ".", "last", "&&", "!", "args", ".", "last", ".", "empty?", "log", "method", "==", ":get", "?", "\"params: #{args.last}\"", ":", "\"body: #{args.last}\"", "end" ]
Try to describe the actual HTTP calls we make. There's a bit of clumsy guesswork here
[ "Try", "to", "describe", "the", "actual", "HTTP", "calls", "we", "make", ".", "There", "s", "a", "bit", "of", "clumsy", "guesswork", "here" ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/core/api_caller.rb#L147-L154
24,203
enkessler/cucumber_analytics
lib/cucumber_analytics/outline.rb
CucumberAnalytics.Outline.to_s
def to_s text = '' text << tag_output_string + "\n" unless tags.empty? text << "Scenario Outline:#{name_output_string}" text << "\n" + description_output_string unless description_text.empty? text << "\n" unless steps.empty? || description_text.empty? text << "\n" + steps_output_string unless steps.empty? text << "\n\n" + examples_output_string unless examples.empty? text end
ruby
def to_s text = '' text << tag_output_string + "\n" unless tags.empty? text << "Scenario Outline:#{name_output_string}" text << "\n" + description_output_string unless description_text.empty? text << "\n" unless steps.empty? || description_text.empty? text << "\n" + steps_output_string unless steps.empty? text << "\n\n" + examples_output_string unless examples.empty? text end
[ "def", "to_s", "text", "=", "''", "text", "<<", "tag_output_string", "+", "\"\\n\"", "unless", "tags", ".", "empty?", "text", "<<", "\"Scenario Outline:#{name_output_string}\"", "text", "<<", "\"\\n\"", "+", "description_output_string", "unless", "description_text", ".", "empty?", "text", "<<", "\"\\n\"", "unless", "steps", ".", "empty?", "||", "description_text", ".", "empty?", "text", "<<", "\"\\n\"", "+", "steps_output_string", "unless", "steps", ".", "empty?", "text", "<<", "\"\\n\\n\"", "+", "examples_output_string", "unless", "examples", ".", "empty?", "text", "end" ]
Returns a gherkin representation of the outline.
[ "Returns", "a", "gherkin", "representation", "of", "the", "outline", "." ]
a74642d30b3566fc11fb43c920518fea4587c6bd
https://github.com/enkessler/cucumber_analytics/blob/a74642d30b3566fc11fb43c920518fea4587c6bd/lib/cucumber_analytics/outline.rb#L35-L46
24,204
snltd/wavefront-sdk
lib/wavefront-sdk/metric_helper.rb
Wavefront.MetricHelper.dist
def dist(path, interval, value, tags = nil) key = [path, interval, tags] @buf[:dists][key] += [value].flatten end
ruby
def dist(path, interval, value, tags = nil) key = [path, interval, tags] @buf[:dists][key] += [value].flatten end
[ "def", "dist", "(", "path", ",", "interval", ",", "value", ",", "tags", "=", "nil", ")", "key", "=", "[", "path", ",", "interval", ",", "tags", "]", "@buf", "[", ":dists", "]", "[", "key", "]", "+=", "[", "value", "]", ".", "flatten", "end" ]
These distributions are stored in memory, and sent to Wavefront as native distibutions when the buffer is flushed. @param path [String] metric path @param value [Array, Numeric] value(s) to add to distribution @param interval [Symbol, String] distribution interval, :m, :h, or :d @param tags [Hash] point tags
[ "These", "distributions", "are", "stored", "in", "memory", "and", "sent", "to", "Wavefront", "as", "native", "distibutions", "when", "the", "buffer", "is", "flushed", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/metric_helper.rb#L62-L65
24,205
snltd/wavefront-sdk
lib/wavefront-sdk/metric_helper.rb
Wavefront.MetricHelper.flush_gauges
def flush_gauges(gauges) return if gauges.empty? to_flush = gauges.dup @buf[:gauges] = empty_gauges writer.write(gauges_to_wf(gauges)).tap do |resp| @buf[:gauges] += to_flush unless resp.ok? end end
ruby
def flush_gauges(gauges) return if gauges.empty? to_flush = gauges.dup @buf[:gauges] = empty_gauges writer.write(gauges_to_wf(gauges)).tap do |resp| @buf[:gauges] += to_flush unless resp.ok? end end
[ "def", "flush_gauges", "(", "gauges", ")", "return", "if", "gauges", ".", "empty?", "to_flush", "=", "gauges", ".", "dup", "@buf", "[", ":gauges", "]", "=", "empty_gauges", "writer", ".", "write", "(", "gauges_to_wf", "(", "gauges", ")", ")", ".", "tap", "do", "|", "resp", "|", "@buf", "[", ":gauges", "]", "+=", "to_flush", "unless", "resp", ".", "ok?", "end", "end" ]
When we are asked to flush the buffers, duplicate the current one, hand it off to the writer class, and clear. If writer tells us there was an error, dump the old buffer into the the new one for the next flush.
[ "When", "we", "are", "asked", "to", "flush", "the", "buffers", "duplicate", "the", "current", "one", "hand", "it", "off", "to", "the", "writer", "class", "and", "clear", ".", "If", "writer", "tells", "us", "there", "was", "an", "error", "dump", "the", "old", "buffer", "into", "the", "the", "new", "one", "for", "the", "next", "flush", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/metric_helper.rb#L81-L90
24,206
snltd/wavefront-sdk
lib/wavefront-sdk/metric_helper.rb
Wavefront.MetricHelper.replay_counters
def replay_counters(buffer) buffer.each { |k, v| counter(k[0], v, k[1]) } end
ruby
def replay_counters(buffer) buffer.each { |k, v| counter(k[0], v, k[1]) } end
[ "def", "replay_counters", "(", "buffer", ")", "buffer", ".", "each", "{", "|", "k", ",", "v", "|", "counter", "(", "k", "[", "0", "]", ",", "v", ",", "k", "[", "1", "]", ")", "}", "end" ]
Play a failed flush full of counters back into the system
[ "Play", "a", "failed", "flush", "full", "of", "counters", "back", "into", "the", "system" ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/metric_helper.rb#L116-L118
24,207
wedesoft/malloc
lib/malloc_ext.rb
Hornetseye.Malloc.+
def +( offset ) if offset > @size raise "Offset must not be more than #{@size} (but was #{offset})" end mark, size = self, @size - offset retval = orig_plus offset retval.instance_eval { @mark, @size = mark, size } retval end
ruby
def +( offset ) if offset > @size raise "Offset must not be more than #{@size} (but was #{offset})" end mark, size = self, @size - offset retval = orig_plus offset retval.instance_eval { @mark, @size = mark, size } retval end
[ "def", "+", "(", "offset", ")", "if", "offset", ">", "@size", "raise", "\"Offset must not be more than #{@size} (but was #{offset})\"", "end", "mark", ",", "size", "=", "self", ",", "@size", "-", "offset", "retval", "=", "orig_plus", "offset", "retval", ".", "instance_eval", "{", "@mark", ",", "@size", "=", "mark", ",", "size", "}", "retval", "end" ]
Operator for doing pointer arithmetic @example Pointer arithmetic m = Malloc.new 4 # Malloc(4) m.write 'abcd' n = m + 2 # Malloc(2) n.read 2 # "cd" @param [Integer] offset Non-negative offset for pointer. @return [Malloc] A new Malloc object.
[ "Operator", "for", "doing", "pointer", "arithmetic" ]
8d2e5f51c277b78b8f116939b4b0be5b6f99328f
https://github.com/wedesoft/malloc/blob/8d2e5f51c277b78b8f116939b4b0be5b6f99328f/lib/malloc_ext.rb#L160-L168
24,208
wedesoft/malloc
lib/malloc_ext.rb
Hornetseye.Malloc.write
def write( data ) if data.is_a? Malloc if data.size > @size raise "Must not write more than #{@size} bytes of memory " + "(illegal attempt to write #{data.size} bytes)" end orig_write data, data.size else if data.bytesize > @size raise "Must not write more than #{@size} bytes of memory " + "(illegal attempt to write #{data.bytesize} bytes)" end orig_write data end end
ruby
def write( data ) if data.is_a? Malloc if data.size > @size raise "Must not write more than #{@size} bytes of memory " + "(illegal attempt to write #{data.size} bytes)" end orig_write data, data.size else if data.bytesize > @size raise "Must not write more than #{@size} bytes of memory " + "(illegal attempt to write #{data.bytesize} bytes)" end orig_write data end end
[ "def", "write", "(", "data", ")", "if", "data", ".", "is_a?", "Malloc", "if", "data", ".", "size", ">", "@size", "raise", "\"Must not write more than #{@size} bytes of memory \"", "+", "\"(illegal attempt to write #{data.size} bytes)\"", "end", "orig_write", "data", ",", "data", ".", "size", "else", "if", "data", ".", "bytesize", ">", "@size", "raise", "\"Must not write more than #{@size} bytes of memory \"", "+", "\"(illegal attempt to write #{data.bytesize} bytes)\"", "end", "orig_write", "data", "end", "end" ]
Write data to memory @example Reading and writing data m = Malloc.new 4 # Malloc(4) m.write 'abcd' m.read 2 # "ab" @param [String,Malloc] data A string or malloc object with the data. @return [String] Returns the parameter +string+. @see #read
[ "Write", "data", "to", "memory" ]
8d2e5f51c277b78b8f116939b4b0be5b6f99328f
https://github.com/wedesoft/malloc/blob/8d2e5f51c277b78b8f116939b4b0be5b6f99328f/lib/malloc_ext.rb#L207-L221
24,209
enkessler/cucumber_analytics
lib/cucumber_analytics/example.rb
CucumberAnalytics.Example.to_s
def to_s text = '' text << tag_output_string + "\n" unless tags.empty? text << "Examples:#{name_output_string}" text << "\n" + description_output_string unless description_text.empty? text << "\n" unless description_text.empty? text << "\n" + parameters_output_string text << "\n" + rows_output_string unless rows.empty? text end
ruby
def to_s text = '' text << tag_output_string + "\n" unless tags.empty? text << "Examples:#{name_output_string}" text << "\n" + description_output_string unless description_text.empty? text << "\n" unless description_text.empty? text << "\n" + parameters_output_string text << "\n" + rows_output_string unless rows.empty? text end
[ "def", "to_s", "text", "=", "''", "text", "<<", "tag_output_string", "+", "\"\\n\"", "unless", "tags", ".", "empty?", "text", "<<", "\"Examples:#{name_output_string}\"", "text", "<<", "\"\\n\"", "+", "description_output_string", "unless", "description_text", ".", "empty?", "text", "<<", "\"\\n\"", "unless", "description_text", ".", "empty?", "text", "<<", "\"\\n\"", "+", "parameters_output_string", "text", "<<", "\"\\n\"", "+", "rows_output_string", "unless", "rows", ".", "empty?", "text", "end" ]
Returns a gherkin representation of the example.
[ "Returns", "a", "gherkin", "representation", "of", "the", "example", "." ]
a74642d30b3566fc11fb43c920518fea4587c6bd
https://github.com/enkessler/cucumber_analytics/blob/a74642d30b3566fc11fb43c920518fea4587c6bd/lib/cucumber_analytics/example.rb#L83-L94
24,210
snltd/wavefront-sdk
lib/wavefront-sdk/core/api.rb
Wavefront.CoreApi.time_to_ms
def time_to_ms(time) return false unless time.is_a?(Integer) return time if time.to_s.size == 13 (time.to_f * 1000).round end
ruby
def time_to_ms(time) return false unless time.is_a?(Integer) return time if time.to_s.size == 13 (time.to_f * 1000).round end
[ "def", "time_to_ms", "(", "time", ")", "return", "false", "unless", "time", ".", "is_a?", "(", "Integer", ")", "return", "time", "if", "time", ".", "to_s", ".", "size", "==", "13", "(", "time", ".", "to_f", "*", "1000", ")", ".", "round", "end" ]
Convert an epoch timestamp into epoch milliseconds. If the timestamp looks like it's already epoch milliseconds, return it as-is. @param t [Integer] epoch timestamp @return [Ingeter] epoch millisecond timestamp
[ "Convert", "an", "epoch", "timestamp", "into", "epoch", "milliseconds", ".", "If", "the", "timestamp", "looks", "like", "it", "s", "already", "epoch", "milliseconds", "return", "it", "as", "-", "is", "." ]
93659d2dab64611fd56aee05cf1de1dd732b46f7
https://github.com/snltd/wavefront-sdk/blob/93659d2dab64611fd56aee05cf1de1dd732b46f7/lib/wavefront-sdk/core/api.rb#L75-L79
24,211
boxgrinder/boxgrinder-build
lib/boxgrinder-build/util/permissions/fs-monitor.rb
BoxGrinder.FSMonitor.capture
def capture(*observers, &block) @lock_a.synchronize do add_observers(observers) _capture(&block) if block_given? yield _stop end end end
ruby
def capture(*observers, &block) @lock_a.synchronize do add_observers(observers) _capture(&block) if block_given? yield _stop end end end
[ "def", "capture", "(", "*", "observers", ",", "&", "block", ")", "@lock_a", ".", "synchronize", "do", "add_observers", "(", "observers", ")", "_capture", "(", "block", ")", "if", "block_given?", "yield", "_stop", "end", "end", "end" ]
Start capturing paths. Providing a block automatically stops the capture process upon termination of the scope. @param Array<#update> Observers to be notified of capture events. Each observer should expect a hash{} containing a +:command+, and potentially +:data+. @yield Block that automatically calls #stop at the end of scope to cease capture.
[ "Start", "capturing", "paths", ".", "Providing", "a", "block", "automatically", "stops", "the", "capture", "process", "upon", "termination", "of", "the", "scope", "." ]
fa21c27451d23f281b41a3e32339d5d791d5f420
https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/util/permissions/fs-monitor.rb#L47-L57
24,212
boxgrinder/boxgrinder-build
lib/boxgrinder-build/util/permissions/fs-monitor.rb
BoxGrinder.FSMonitor.alias_and_capture
def alias_and_capture(klazz, m_sym, flag, &blk) alias_m_sym = "__alias_#{m_sym}" klazz.class_eval do alias_method alias_m_sym, m_sym define_method(m_sym) do |*args, &blx| response = send(alias_m_sym, *args, &blx) blk.call(self, *args) if flag.get_set response end end end
ruby
def alias_and_capture(klazz, m_sym, flag, &blk) alias_m_sym = "__alias_#{m_sym}" klazz.class_eval do alias_method alias_m_sym, m_sym define_method(m_sym) do |*args, &blx| response = send(alias_m_sym, *args, &blx) blk.call(self, *args) if flag.get_set response end end end
[ "def", "alias_and_capture", "(", "klazz", ",", "m_sym", ",", "flag", ",", "&", "blk", ")", "alias_m_sym", "=", "\"__alias_#{m_sym}\"", "klazz", ".", "class_eval", "do", "alias_method", "alias_m_sym", ",", "m_sym", "define_method", "(", "m_sym", ")", "do", "|", "*", "args", ",", "&", "blx", "|", "response", "=", "send", "(", "alias_m_sym", ",", "args", ",", "blx", ")", "blk", ".", "call", "(", "self", ",", "args", ")", "if", "flag", ".", "get_set", "response", "end", "end", "end" ]
Cracks open the target class, and injects a wrapper to enable monitoring. By aliasing the original method the wrapper intercepts the call, which it forwards onto the 'real' method before executing the hook. The hook's functionality is provided via a &block, which is passed the caller's +self+ in addition to the wrapped method's parameters. Locking the +flag+ signals the hook to begin capturing.
[ "Cracks", "open", "the", "target", "class", "and", "injects", "a", "wrapper", "to", "enable", "monitoring", ".", "By", "aliasing", "the", "original", "method", "the", "wrapper", "intercepts", "the", "call", "which", "it", "forwards", "onto", "the", "real", "method", "before", "executing", "the", "hook", "." ]
fa21c27451d23f281b41a3e32339d5d791d5f420
https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/util/permissions/fs-monitor.rb#L151-L163
24,213
boxgrinder/boxgrinder-build
lib/boxgrinder-build/helpers/linux-helper.rb
BoxGrinder.RPMVersion.newest
def newest(versions) versions.sort { |x,y| compare(x,y) }.last end
ruby
def newest(versions) versions.sort { |x,y| compare(x,y) }.last end
[ "def", "newest", "(", "versions", ")", "versions", ".", "sort", "{", "|", "x", ",", "y", "|", "compare", "(", "x", ",", "y", ")", "}", ".", "last", "end" ]
Returns newest version from the array
[ "Returns", "newest", "version", "from", "the", "array" ]
fa21c27451d23f281b41a3e32339d5d791d5f420
https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/helpers/linux-helper.rb#L50-L52
24,214
boxgrinder/boxgrinder-build
lib/boxgrinder-build/helpers/linux-helper.rb
BoxGrinder.LinuxHelper.partition_mount_points
def partition_mount_points(partitions) partitions.keys.sort do |a, b| a_count = a.count('/') b_count = b.count('/') if a_count > b_count v = 1 else if a_count < b_count v = -1 else if a.length == b.length v = a <=> b else v = a.length <=> b.length end end end # This forces having swap partition at the end of the disk v = 1 if a_count == 0 v = -1 if b_count == 0 v end end
ruby
def partition_mount_points(partitions) partitions.keys.sort do |a, b| a_count = a.count('/') b_count = b.count('/') if a_count > b_count v = 1 else if a_count < b_count v = -1 else if a.length == b.length v = a <=> b else v = a.length <=> b.length end end end # This forces having swap partition at the end of the disk v = 1 if a_count == 0 v = -1 if b_count == 0 v end end
[ "def", "partition_mount_points", "(", "partitions", ")", "partitions", ".", "keys", ".", "sort", "do", "|", "a", ",", "b", "|", "a_count", "=", "a", ".", "count", "(", "'/'", ")", "b_count", "=", "b", ".", "count", "(", "'/'", ")", "if", "a_count", ">", "b_count", "v", "=", "1", "else", "if", "a_count", "<", "b_count", "v", "=", "-", "1", "else", "if", "a", ".", "length", "==", "b", ".", "length", "v", "=", "a", "<=>", "b", "else", "v", "=", "a", ".", "length", "<=>", "b", ".", "length", "end", "end", "end", "# This forces having swap partition at the end of the disk", "v", "=", "1", "if", "a_count", "==", "0", "v", "=", "-", "1", "if", "b_count", "==", "0", "v", "end", "end" ]
Returns valid array of sorted mount points ['/', '/home'] => ['/', '/home'] ['swap', '/', '/home'] => ['/', '/home', 'swap'] ['swap', '/', '/home', '/boot'] => ['/', '/boot', '/home', 'swap'] ['/tmp-eventlog', '/', '/ubrc', '/tmp-config'] => ['/', '/ubrc', '/tmp-config', '/tmp-eventlog']
[ "Returns", "valid", "array", "of", "sorted", "mount", "points" ]
fa21c27451d23f281b41a3e32339d5d791d5f420
https://github.com/boxgrinder/boxgrinder-build/blob/fa21c27451d23f281b41a3e32339d5d791d5f420/lib/boxgrinder-build/helpers/linux-helper.rb#L67-L92
24,215
ilkka/consular-terminator
lib/consular/terminator.rb
Consular.Terminator.process!
def process! windows = @termfile[:windows] default = windows.delete('default') execute_window(default, :default => true) unless default[:tabs].empty? windows.each_pair { |_, cont| execute_window(cont) } end
ruby
def process! windows = @termfile[:windows] default = windows.delete('default') execute_window(default, :default => true) unless default[:tabs].empty? windows.each_pair { |_, cont| execute_window(cont) } end
[ "def", "process!", "windows", "=", "@termfile", "[", ":windows", "]", "default", "=", "windows", ".", "delete", "(", "'default'", ")", "execute_window", "(", "default", ",", ":default", "=>", "true", ")", "unless", "default", "[", ":tabs", "]", ".", "empty?", "windows", ".", "each_pair", "{", "|", "_", ",", "cont", "|", "execute_window", "(", "cont", ")", "}", "end" ]
Method called by runner to execute Termfile. @api public
[ "Method", "called", "by", "runner", "to", "execute", "Termfile", "." ]
a7734c7b1f8390ec5a93bc6719d272cd8c1e1a78
https://github.com/ilkka/consular-terminator/blob/a7734c7b1f8390ec5a93bc6719d272cd8c1e1a78/lib/consular/terminator.rb#L55-L60
24,216
kete/kete_gets_trollied
lib/kete_gets_trollied/has_trolley_controller_helpers_overrides.rb
HasTrolleyControllerHelpersOverrides.UrlFor.url_for_trolley
def url_for_trolley(options = { }) return url_for_dc_identifier(@purchasable_item) if @purchasable_item && params[:action] == 'create' user = options.delete(:user) trolley = options[:trolley] || @trolley || user.trolley if trolley.blank? user = @user else user = trolley.user end options[:user_id] = user.id options[:controller] = 'trolleys' options[:action] = 'show' options[:urlified_name] = Basket.site_basket.urlified_name url = url_for(options) # .split(".%23%")[0] end
ruby
def url_for_trolley(options = { }) return url_for_dc_identifier(@purchasable_item) if @purchasable_item && params[:action] == 'create' user = options.delete(:user) trolley = options[:trolley] || @trolley || user.trolley if trolley.blank? user = @user else user = trolley.user end options[:user_id] = user.id options[:controller] = 'trolleys' options[:action] = 'show' options[:urlified_name] = Basket.site_basket.urlified_name url = url_for(options) # .split(".%23%")[0] end
[ "def", "url_for_trolley", "(", "options", "=", "{", "}", ")", "return", "url_for_dc_identifier", "(", "@purchasable_item", ")", "if", "@purchasable_item", "&&", "params", "[", ":action", "]", "==", "'create'", "user", "=", "options", ".", "delete", "(", ":user", ")", "trolley", "=", "options", "[", ":trolley", "]", "||", "@trolley", "||", "user", ".", "trolley", "if", "trolley", ".", "blank?", "user", "=", "@user", "else", "user", "=", "trolley", ".", "user", "end", "options", "[", ":user_id", "]", "=", "user", ".", "id", "options", "[", ":controller", "]", "=", "'trolleys'", "options", "[", ":action", "]", "=", "'show'", "options", "[", ":urlified_name", "]", "=", "Basket", ".", "site_basket", ".", "urlified_name", "url", "=", "url_for", "(", "options", ")", "# .split(\".%23%\")[0]", "end" ]
expects user in options or @user or trolley being set unless @purchasable_item is present WARNING: in the case of @purchasable_item this method name breaks the principle of least surprise maybe alter trollied gem in future to come right
[ "expects", "user", "in", "options", "or" ]
a00e2170e08fec7cbc68b09da8a00eb5645e0ef4
https://github.com/kete/kete_gets_trollied/blob/a00e2170e08fec7cbc68b09da8a00eb5645e0ef4/lib/kete_gets_trollied/has_trolley_controller_helpers_overrides.rb#L14-L32
24,217
kete/kete_gets_trollied
lib/kete_gets_trollied/has_trolley_controller_helpers_overrides.rb
HasTrolleyControllerHelpersOverrides.UrlFor.url_for_order
def url_for_order(options = { }) trolley = options.delete(:trolley) || @trolley trolley = @order.trolley if @order order = options.delete(:order) || @order || trolley.selected_order options[:id] = order options[:controller] = 'orders' options[:action] = 'show' options[:urlified_name] = Basket.site_basket.urlified_name url_for options end
ruby
def url_for_order(options = { }) trolley = options.delete(:trolley) || @trolley trolley = @order.trolley if @order order = options.delete(:order) || @order || trolley.selected_order options[:id] = order options[:controller] = 'orders' options[:action] = 'show' options[:urlified_name] = Basket.site_basket.urlified_name url_for options end
[ "def", "url_for_order", "(", "options", "=", "{", "}", ")", "trolley", "=", "options", ".", "delete", "(", ":trolley", ")", "||", "@trolley", "trolley", "=", "@order", ".", "trolley", "if", "@order", "order", "=", "options", ".", "delete", "(", ":order", ")", "||", "@order", "||", "trolley", ".", "selected_order", "options", "[", ":id", "]", "=", "order", "options", "[", ":controller", "]", "=", "'orders'", "options", "[", ":action", "]", "=", "'show'", "options", "[", ":urlified_name", "]", "=", "Basket", ".", "site_basket", ".", "urlified_name", "url_for", "options", "end" ]
expects order either as instance variables or in options
[ "expects", "order", "either", "as", "instance", "variables", "or", "in", "options" ]
a00e2170e08fec7cbc68b09da8a00eb5645e0ef4
https://github.com/kete/kete_gets_trollied/blob/a00e2170e08fec7cbc68b09da8a00eb5645e0ef4/lib/kete_gets_trollied/has_trolley_controller_helpers_overrides.rb#L36-L48
24,218
altabyte/ebay_trader
lib/ebay_trader/session_id.rb
EbayTrader.SessionID.sign_in_url
def sign_in_url(ruparams = {}) url = [] url << EbayTrader.configuration.production? ? 'https://signin.ebay.com' : 'https://signin.sandbox.ebay.com' url << '/ws/eBayISAPI.dll?SignIn' url << "&runame=#{url_encode ru_name}" url << "&SessID=#{url_encode id}" if ruparams && ruparams.is_a?(Hash) && !ruparams.empty? params = [] ruparams.each_pair { |key, value| params << "#{key}=#{value}" } url << "&ruparams=#{url_encode(params.join('&'))}" end url.join end
ruby
def sign_in_url(ruparams = {}) url = [] url << EbayTrader.configuration.production? ? 'https://signin.ebay.com' : 'https://signin.sandbox.ebay.com' url << '/ws/eBayISAPI.dll?SignIn' url << "&runame=#{url_encode ru_name}" url << "&SessID=#{url_encode id}" if ruparams && ruparams.is_a?(Hash) && !ruparams.empty? params = [] ruparams.each_pair { |key, value| params << "#{key}=#{value}" } url << "&ruparams=#{url_encode(params.join('&'))}" end url.join end
[ "def", "sign_in_url", "(", "ruparams", "=", "{", "}", ")", "url", "=", "[", "]", "url", "<<", "EbayTrader", ".", "configuration", ".", "production?", "?", "'https://signin.ebay.com'", ":", "'https://signin.sandbox.ebay.com'", "url", "<<", "'/ws/eBayISAPI.dll?SignIn'", "url", "<<", "\"&runame=#{url_encode ru_name}\"", "url", "<<", "\"&SessID=#{url_encode id}\"", "if", "ruparams", "&&", "ruparams", ".", "is_a?", "(", "Hash", ")", "&&", "!", "ruparams", ".", "empty?", "params", "=", "[", "]", "ruparams", ".", "each_pair", "{", "|", "key", ",", "value", "|", "params", "<<", "\"#{key}=#{value}\"", "}", "url", "<<", "\"&ruparams=#{url_encode(params.join('&'))}\"", "end", "url", ".", "join", "end" ]
Get the URL through which a user must sign in using this session ID. @param [Hash] ruparams eBay appends this data to the AcceptURL and RejectURL. In a typical rails app this might include the user's model primary key. @return [String] the sign-in URL.
[ "Get", "the", "URL", "through", "which", "a", "user", "must", "sign", "in", "using", "this", "session", "ID", "." ]
4442b683ea27f02fa0ef73f3f6357396fbe29b56
https://github.com/altabyte/ebay_trader/blob/4442b683ea27f02fa0ef73f3f6357396fbe29b56/lib/ebay_trader/session_id.rb#L49-L61
24,219
jmesnil/jmx4r
lib/jmx4r.rb
JMX.MBean.method_missing
def method_missing(method, *args, &block) #:nodoc: method_in_snake_case = method.to_s.snake_case # this way Java/JRuby styles are compatible if @operations.keys.include?(method_in_snake_case) op_name, param_types = @operations[method_in_snake_case] @connection.invoke @object_name, op_name, args.to_java(:Object), param_types.to_java(:String) else super end end
ruby
def method_missing(method, *args, &block) #:nodoc: method_in_snake_case = method.to_s.snake_case # this way Java/JRuby styles are compatible if @operations.keys.include?(method_in_snake_case) op_name, param_types = @operations[method_in_snake_case] @connection.invoke @object_name, op_name, args.to_java(:Object), param_types.to_java(:String) else super end end
[ "def", "method_missing", "(", "method", ",", "*", "args", ",", "&", "block", ")", "#:nodoc:", "method_in_snake_case", "=", "method", ".", "to_s", ".", "snake_case", "# this way Java/JRuby styles are compatible", "if", "@operations", ".", "keys", ".", "include?", "(", "method_in_snake_case", ")", "op_name", ",", "param_types", "=", "@operations", "[", "method_in_snake_case", "]", "@connection", ".", "invoke", "@object_name", ",", "op_name", ",", "args", ".", "to_java", "(", ":Object", ")", ",", "param_types", ".", "to_java", "(", ":String", ")", "else", "super", "end", "end" ]
Creates a new MBean. object_name:: a string corresponding to a valid ObjectName connection:: a connection to a MBean server. If none is passed, use the global connection created by MBean.establish_connection
[ "Creates", "a", "new", "MBean", "." ]
8140fe451d3f9c008e9efa1b56e4e1d710187352
https://github.com/jmesnil/jmx4r/blob/8140fe451d3f9c008e9efa1b56e4e1d710187352/lib/jmx4r.rb#L97-L109
24,220
jdigger/git-process
lib/git-process/github_pull_request.rb
GitHub.PullRequest.create
def create(base, head, title, body) logger.info { "Creating a pull request asking for '#{head}' to be merged into '#{base}' on #{repo}." } begin return sym_hash_JSON(client.create_pull_request(repo, base, head, title, body)) rescue Octokit::UnprocessableEntity => exp pull = pull_requests.find { |p| p[:head][:ref] == head and p[:base][:ref] == base } if pull logger.warn { "Pull request already exists. See #{pull[:html_url]}" } else logger.warn { "UnprocessableEntity: #{exp}" } end return pull end end
ruby
def create(base, head, title, body) logger.info { "Creating a pull request asking for '#{head}' to be merged into '#{base}' on #{repo}." } begin return sym_hash_JSON(client.create_pull_request(repo, base, head, title, body)) rescue Octokit::UnprocessableEntity => exp pull = pull_requests.find { |p| p[:head][:ref] == head and p[:base][:ref] == base } if pull logger.warn { "Pull request already exists. See #{pull[:html_url]}" } else logger.warn { "UnprocessableEntity: #{exp}" } end return pull end end
[ "def", "create", "(", "base", ",", "head", ",", "title", ",", "body", ")", "logger", ".", "info", "{", "\"Creating a pull request asking for '#{head}' to be merged into '#{base}' on #{repo}.\"", "}", "begin", "return", "sym_hash_JSON", "(", "client", ".", "create_pull_request", "(", "repo", ",", "base", ",", "head", ",", "title", ",", "body", ")", ")", "rescue", "Octokit", "::", "UnprocessableEntity", "=>", "exp", "pull", "=", "pull_requests", ".", "find", "{", "|", "p", "|", "p", "[", ":head", "]", "[", ":ref", "]", "==", "head", "and", "p", "[", ":base", "]", "[", ":ref", "]", "==", "base", "}", "if", "pull", "logger", ".", "warn", "{", "\"Pull request already exists. See #{pull[:html_url]}\"", "}", "else", "logger", ".", "warn", "{", "\"UnprocessableEntity: #{exp}\"", "}", "end", "return", "pull", "end", "end" ]
Create a pull request @see https://developer.github.com/v3/pulls/#create-a-pull-request @param base [String] The branch (or git ref) you want your changes pulled into. This should be an existing branch on the current repository. You cannot submit a pull request to one repo that requests a merge to a base of another repo. @param head [String] The branch (or git ref) where your changes are implemented. @param title [String] Title for the pull request @param body [String] The body for the pull request (optional). Supports GFM. @return [Hash] The newly created pull request @example @client.create_pull_request("master", "feature-branch", "Pull Request title", "Pull Request body")
[ "Create", "a", "pull", "request" ]
5853aa94258e724ce0dbc2f1e7407775e1630964
https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/github_pull_request.rb#L62-L75
24,221
brianstorti/vagalume
lib/vagalume/song.rb
Vagalume.Song.remove_title
def remove_title(lyric) lines = lyric.lines lines.shift lines = remove_empty_lines_from_beginning(lines) lines.join end
ruby
def remove_title(lyric) lines = lyric.lines lines.shift lines = remove_empty_lines_from_beginning(lines) lines.join end
[ "def", "remove_title", "(", "lyric", ")", "lines", "=", "lyric", ".", "lines", "lines", ".", "shift", "lines", "=", "remove_empty_lines_from_beginning", "(", "lines", ")", "lines", ".", "join", "end" ]
This is necessary because, for translations, the song title comes with the lyric text. Also, the format is not always the same, sometimes it's just one line for the title, sometimes it's the title followed by some empty lines. Here we remove the first line and any following empty lines, so we have a consident API.
[ "This", "is", "necessary", "because", "for", "translations", "the", "song", "title", "comes", "with", "the", "lyric", "text", ".", "Also", "the", "format", "is", "not", "always", "the", "same", "sometimes", "it", "s", "just", "one", "line", "for", "the", "title", "sometimes", "it", "s", "the", "title", "followed", "by", "some", "empty", "lines", ".", "Here", "we", "remove", "the", "first", "line", "and", "any", "following", "empty", "lines", "so", "we", "have", "a", "consident", "API", "." ]
0001441a65a9fb9393bb8f4e057eaff5d74b29c8
https://github.com/brianstorti/vagalume/blob/0001441a65a9fb9393bb8f4e057eaff5d74b29c8/lib/vagalume/song.rb#L34-L39
24,222
acesuares/inline_forms
lib/generators/inline_forms_generator.rb
InlineForms.InlineFormsGenerator.set_some_flags
def set_some_flags @flag_not_accessible_through_html = true @flag_create_migration = true @flag_create_model = true @create_id = true for attribute in attributes @flag_not_accessible_through_html = false if attribute.name == '_enabled' @flag_create_migration = false if attribute.name == '_no_migration' @flag_create_model = false if attribute.name == '_no_model' @create_id = false if attribute.name == "_id" && attribute.type == :false end @flag_create_controller = @flag_create_model @flag_create_resource_route = @flag_create_model end
ruby
def set_some_flags @flag_not_accessible_through_html = true @flag_create_migration = true @flag_create_model = true @create_id = true for attribute in attributes @flag_not_accessible_through_html = false if attribute.name == '_enabled' @flag_create_migration = false if attribute.name == '_no_migration' @flag_create_model = false if attribute.name == '_no_model' @create_id = false if attribute.name == "_id" && attribute.type == :false end @flag_create_controller = @flag_create_model @flag_create_resource_route = @flag_create_model end
[ "def", "set_some_flags", "@flag_not_accessible_through_html", "=", "true", "@flag_create_migration", "=", "true", "@flag_create_model", "=", "true", "@create_id", "=", "true", "for", "attribute", "in", "attributes", "@flag_not_accessible_through_html", "=", "false", "if", "attribute", ".", "name", "==", "'_enabled'", "@flag_create_migration", "=", "false", "if", "attribute", ".", "name", "==", "'_no_migration'", "@flag_create_model", "=", "false", "if", "attribute", ".", "name", "==", "'_no_model'", "@create_id", "=", "false", "if", "attribute", ".", "name", "==", "\"_id\"", "&&", "attribute", ".", "type", "==", ":false", "end", "@flag_create_controller", "=", "@flag_create_model", "@flag_create_resource_route", "=", "@flag_create_model", "end" ]
using flags.
[ "using", "flags", "." ]
c2fb3c992d7c1e1371f5a20d559855c6bdba21b4
https://github.com/acesuares/inline_forms/blob/c2fb3c992d7c1e1371f5a20d559855c6bdba21b4/lib/generators/inline_forms_generator.rb#L78-L91
24,223
bitaxis/rack-cas-rails
lib/rack-cas-rails/action_controller_base_additions.rb
RackCASRails.ActionControllerBaseAdditions.login_url
def login_url(service_url=request.url) url = URI(Rails.application.cas_server_url) url.path = "/login" url.query = "service=#{service_url || request.url}" url.to_s end
ruby
def login_url(service_url=request.url) url = URI(Rails.application.cas_server_url) url.path = "/login" url.query = "service=#{service_url || request.url}" url.to_s end
[ "def", "login_url", "(", "service_url", "=", "request", ".", "url", ")", "url", "=", "URI", "(", "Rails", ".", "application", ".", "cas_server_url", ")", "url", ".", "path", "=", "\"/login\"", "url", ".", "query", "=", "\"service=#{service_url || request.url}\"", "url", ".", "to_s", "end" ]
Renders the CAS login URL with re-direct back to some URL. @param service_url [String] Optional url to redirect to after authentication. @return [String] The CAS login URL.
[ "Renders", "the", "CAS", "login", "URL", "with", "re", "-", "direct", "back", "to", "some", "URL", "." ]
a2ebc5ce2803868235c6a8ec6b1f018d3caac832
https://github.com/bitaxis/rack-cas-rails/blob/a2ebc5ce2803868235c6a8ec6b1f018d3caac832/lib/rack-cas-rails/action_controller_base_additions.rb#L31-L36
24,224
altabyte/ebay_trader
lib/ebay_trader/sax_handler.rb
EbayTrader.SaxHandler.format_key
def format_key(key) key = key.to_s key = key.gsub('PayPal', 'Paypal') key = key.gsub('eBay', 'Ebay') key = key.gsub('EBay', 'Ebay') key.underscore.to_sym end
ruby
def format_key(key) key = key.to_s key = key.gsub('PayPal', 'Paypal') key = key.gsub('eBay', 'Ebay') key = key.gsub('EBay', 'Ebay') key.underscore.to_sym end
[ "def", "format_key", "(", "key", ")", "key", "=", "key", ".", "to_s", "key", "=", "key", ".", "gsub", "(", "'PayPal'", ",", "'Paypal'", ")", "key", "=", "key", ".", "gsub", "(", "'eBay'", ",", "'Ebay'", ")", "key", "=", "key", ".", "gsub", "(", "'EBay'", ",", "'Ebay'", ")", "key", ".", "underscore", ".", "to_sym", "end" ]
Ensure the key is an underscored Symbol. Examples: 'ApplyBuyerProtection' -> :apply_buyer_protection 'PayPalEmailAddress' -> :paypal_email_address 'SoldOffeBay' -> :sold_off_ebay @return [Symbol] the reformatted key.
[ "Ensure", "the", "key", "is", "an", "underscored", "Symbol", "." ]
4442b683ea27f02fa0ef73f3f6357396fbe29b56
https://github.com/altabyte/ebay_trader/blob/4442b683ea27f02fa0ef73f3f6357396fbe29b56/lib/ebay_trader/sax_handler.rb#L145-L151
24,225
jdigger/git-process
lib/git-process/git_lib.rb
GitProc.GitLib.push_to_server
def push_to_server(local_branch, remote_branch, opts = {}) if opts[:local] logger.debug('Not pushing to the server because the user selected local-only.') elsif not has_a_remote? logger.debug('Not pushing to the server because there is no remote.') elsif local_branch == config.master_branch logger.warn('Not pushing to the server because the current branch is the mainline branch.') else opts[:prepush].call if opts[:prepush] push(remote.name, local_branch, remote_branch, :force => opts[:force]) opts[:postpush].call if opts[:postpush] end end
ruby
def push_to_server(local_branch, remote_branch, opts = {}) if opts[:local] logger.debug('Not pushing to the server because the user selected local-only.') elsif not has_a_remote? logger.debug('Not pushing to the server because there is no remote.') elsif local_branch == config.master_branch logger.warn('Not pushing to the server because the current branch is the mainline branch.') else opts[:prepush].call if opts[:prepush] push(remote.name, local_branch, remote_branch, :force => opts[:force]) opts[:postpush].call if opts[:postpush] end end
[ "def", "push_to_server", "(", "local_branch", ",", "remote_branch", ",", "opts", "=", "{", "}", ")", "if", "opts", "[", ":local", "]", "logger", ".", "debug", "(", "'Not pushing to the server because the user selected local-only.'", ")", "elsif", "not", "has_a_remote?", "logger", ".", "debug", "(", "'Not pushing to the server because there is no remote.'", ")", "elsif", "local_branch", "==", "config", ".", "master_branch", "logger", ".", "warn", "(", "'Not pushing to the server because the current branch is the mainline branch.'", ")", "else", "opts", "[", ":prepush", "]", ".", "call", "if", "opts", "[", ":prepush", "]", "push", "(", "remote", ".", "name", ",", "local_branch", ",", "remote_branch", ",", ":force", "=>", "opts", "[", ":force", "]", ")", "opts", "[", ":postpush", "]", ".", "call", "if", "opts", "[", ":postpush", "]", "end", "end" ]
Push the repository to the server. @param local_branch [String] the name of the local branch to push from @param remote_branch [String] the name of the remote branch to push to @option opts [Boolean] :local should this do nothing because it is in local-only mode? @option opts [Boolean] :force should it force the push even if it can not fast-forward? @option opts [Proc] :prepush a block to call before doing the push @option opts [Proc] :postpush a block to call after doing the push @return [void]
[ "Push", "the", "repository", "to", "the", "server", "." ]
5853aa94258e724ce0dbc2f1e7407775e1630964
https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_lib.rb#L206-L220
24,226
jdigger/git-process
lib/git-process/git_lib.rb
GitProc.GitLib.branch
def branch(branch_name, opts = {}) if branch_name if opts[:delete] return delete_branch(branch_name, opts[:force]) elsif opts[:rename] return rename_branch(branch_name, opts[:rename]) elsif opts[:upstream] return set_upstream_branch(branch_name, opts[:upstream]) else base_branch = opts[:base_branch] || 'master' if opts[:force] return change_branch(branch_name, base_branch) else return create_branch(branch_name, base_branch) end end else #list_branches(opts) return list_branches(opts[:all], opts[:remote], opts[:no_color]) end end
ruby
def branch(branch_name, opts = {}) if branch_name if opts[:delete] return delete_branch(branch_name, opts[:force]) elsif opts[:rename] return rename_branch(branch_name, opts[:rename]) elsif opts[:upstream] return set_upstream_branch(branch_name, opts[:upstream]) else base_branch = opts[:base_branch] || 'master' if opts[:force] return change_branch(branch_name, base_branch) else return create_branch(branch_name, base_branch) end end else #list_branches(opts) return list_branches(opts[:all], opts[:remote], opts[:no_color]) end end
[ "def", "branch", "(", "branch_name", ",", "opts", "=", "{", "}", ")", "if", "branch_name", "if", "opts", "[", ":delete", "]", "return", "delete_branch", "(", "branch_name", ",", "opts", "[", ":force", "]", ")", "elsif", "opts", "[", ":rename", "]", "return", "rename_branch", "(", "branch_name", ",", "opts", "[", ":rename", "]", ")", "elsif", "opts", "[", ":upstream", "]", "return", "set_upstream_branch", "(", "branch_name", ",", "opts", "[", ":upstream", "]", ")", "else", "base_branch", "=", "opts", "[", ":base_branch", "]", "||", "'master'", "if", "opts", "[", ":force", "]", "return", "change_branch", "(", "branch_name", ",", "base_branch", ")", "else", "return", "create_branch", "(", "branch_name", ",", "base_branch", ")", "end", "end", "else", "#list_branches(opts)", "return", "list_branches", "(", "opts", "[", ":all", "]", ",", "opts", "[", ":remote", "]", ",", "opts", "[", ":no_color", "]", ")", "end", "end" ]
Does branch manipulation. @param [String] branch_name the name of the branch @option opts [Boolean] :delete delete the remote branch @option opts [Boolean] :force force the update @option opts [Boolean] :all list all branches, local and remote @option opts [Boolean] :no_color force not using any ANSI color codes @option opts [String] :rename the new name for the branch @option opts [String] :upstream the new branch to track @option opts [String] :base_branch ('master') the branch to base the new branch off of @return [String] the output of running the git command
[ "Does", "branch", "manipulation", "." ]
5853aa94258e724ce0dbc2f1e7407775e1630964
https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_lib.rb#L382-L402
24,227
jdigger/git-process
lib/git-process/git_lib.rb
GitProc.GitLib.remove
def remove(files, opts = {}) args = [] args << '-f' if opts[:force] args << [*files] command(:rm, args) end
ruby
def remove(files, opts = {}) args = [] args << '-f' if opts[:force] args << [*files] command(:rm, args) end
[ "def", "remove", "(", "files", ",", "opts", "=", "{", "}", ")", "args", "=", "[", "]", "args", "<<", "'-f'", "if", "opts", "[", ":force", "]", "args", "<<", "[", "files", "]", "command", "(", ":rm", ",", "args", ")", "end" ]
Remove the files from the Index @param [Array<String>] files the file names to remove from the Index @option opts :force if exists and not false, will force the removal of the files @return [String] the output of the git command
[ "Remove", "the", "files", "from", "the", "Index" ]
5853aa94258e724ce0dbc2f1e7407775e1630964
https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_lib.rb#L571-L576
24,228
jdigger/git-process
lib/git-process/git_lib.rb
GitProc.GitLib.write_sync_control_file
def write_sync_control_file(branch_name) latest_sha = rev_parse(branch_name) filename = sync_control_filename(branch_name) logger.debug { "Writing sync control file, #{filename}, with #{latest_sha}" } File.open(filename, 'w') { |f| f.puts latest_sha } end
ruby
def write_sync_control_file(branch_name) latest_sha = rev_parse(branch_name) filename = sync_control_filename(branch_name) logger.debug { "Writing sync control file, #{filename}, with #{latest_sha}" } File.open(filename, 'w') { |f| f.puts latest_sha } end
[ "def", "write_sync_control_file", "(", "branch_name", ")", "latest_sha", "=", "rev_parse", "(", "branch_name", ")", "filename", "=", "sync_control_filename", "(", "branch_name", ")", "logger", ".", "debug", "{", "\"Writing sync control file, #{filename}, with #{latest_sha}\"", "}", "File", ".", "open", "(", "filename", ",", "'w'", ")", "{", "|", "f", "|", "f", ".", "puts", "latest_sha", "}", "end" ]
Writes the current SHA-1 for the tip of the branch to the "sync control file" @return [void] @see GitLib#read_sync_control_file
[ "Writes", "the", "current", "SHA", "-", "1", "for", "the", "tip", "of", "the", "branch", "to", "the", "sync", "control", "file" ]
5853aa94258e724ce0dbc2f1e7407775e1630964
https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_lib.rb#L670-L675
24,229
jdigger/git-process
lib/git-process/git_lib.rb
GitProc.GitLib.delete_sync_control_file!
def delete_sync_control_file!(branch_name) filename = sync_control_filename(branch_name) logger.debug { "Deleting sync control file, #{filename}" } # on some systems, especially Windows, the file may be locked. wait for it to unlock counter = 10 while counter > 0 begin File.delete(filename) counter = 0 rescue counter = counter - 1 sleep(0.25) end end end
ruby
def delete_sync_control_file!(branch_name) filename = sync_control_filename(branch_name) logger.debug { "Deleting sync control file, #{filename}" } # on some systems, especially Windows, the file may be locked. wait for it to unlock counter = 10 while counter > 0 begin File.delete(filename) counter = 0 rescue counter = counter - 1 sleep(0.25) end end end
[ "def", "delete_sync_control_file!", "(", "branch_name", ")", "filename", "=", "sync_control_filename", "(", "branch_name", ")", "logger", ".", "debug", "{", "\"Deleting sync control file, #{filename}\"", "}", "# on some systems, especially Windows, the file may be locked. wait for it to unlock", "counter", "=", "10", "while", "counter", ">", "0", "begin", "File", ".", "delete", "(", "filename", ")", "counter", "=", "0", "rescue", "counter", "=", "counter", "-", "1", "sleep", "(", "0.25", ")", "end", "end", "end" ]
Delete the sync control file for the branch @return [void] @see GitLib#write_sync_control_file
[ "Delete", "the", "sync", "control", "file", "for", "the", "branch" ]
5853aa94258e724ce0dbc2f1e7407775e1630964
https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_lib.rb#L700-L715
24,230
jdigger/git-process
lib/git-process/git_lib.rb
GitProc.GitLib.create_git_command
def create_git_command(cmd, opts, redirect) opts = [opts].flatten.map { |s| escape(s) }.join(' ') return "git #{cmd} #{opts} #{redirect} 2>&1" end
ruby
def create_git_command(cmd, opts, redirect) opts = [opts].flatten.map { |s| escape(s) }.join(' ') return "git #{cmd} #{opts} #{redirect} 2>&1" end
[ "def", "create_git_command", "(", "cmd", ",", "opts", ",", "redirect", ")", "opts", "=", "[", "opts", "]", ".", "flatten", ".", "map", "{", "|", "s", "|", "escape", "(", "s", ")", "}", ".", "join", "(", "' '", ")", "return", "\"git #{cmd} #{opts} #{redirect} 2>&1\"", "end" ]
Create the CLI for the git command @param [Symbol, String] cmd the command to run (e.g., :commit) @param [Array<String, Symbol>] opts the arguments to pass to the command @param [String] redirect ??????? @return [String] the command line to run
[ "Create", "the", "CLI", "for", "the", "git", "command" ]
5853aa94258e724ce0dbc2f1e7407775e1630964
https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_lib.rb#L761-L764
24,231
rapid7/metasploit-model
lib/metasploit/model/search/with.rb
Metasploit::Model::Search::With.ClassMethods.search_with
def search_with(operator_class, options={}) merged_operations = options.merge( :klass => self ) operator = operator_class.new(merged_operations) operator.valid! search_with_operator_by_name[operator.name] = operator end
ruby
def search_with(operator_class, options={}) merged_operations = options.merge( :klass => self ) operator = operator_class.new(merged_operations) operator.valid! search_with_operator_by_name[operator.name] = operator end
[ "def", "search_with", "(", "operator_class", ",", "options", "=", "{", "}", ")", "merged_operations", "=", "options", ".", "merge", "(", ":klass", "=>", "self", ")", "operator", "=", "operator_class", ".", "new", "(", "merged_operations", ")", "operator", ".", "valid!", "search_with_operator_by_name", "[", "operator", ".", "name", "]", "=", "operator", "end" ]
Declares that this class should be search with an instance of the given `operator_class`. @param operator_class [Class<Metasploit::Model::Search::Operator::Base>] a class to initialize. @param options [Hash] Options passed to `operator_class.new` along with `{:klass => self}`, so that the `operator_class` instance knows it was registered as search this class. @return [Metasploit::Model::Search::Operator::Base] @raise (see Metasploit::Model::Base#invalid!)
[ "Declares", "that", "this", "class", "should", "be", "search", "with", "an", "instance", "of", "the", "given", "operator_class", "." ]
cb6606bf24218798e853ba44470df31a47d9b627
https://github.com/rapid7/metasploit-model/blob/cb6606bf24218798e853ba44470df31a47d9b627/lib/metasploit/model/search/with.rb#L58-L66
24,232
djellemah/philtre
lib/philtre/place_holder.rb
Philtre.PlaceHolder.to_s_append
def to_s_append( ds, s ) s << '$' << name.to_s s << ':' << sql_field.to_s if sql_field s << '/*' << small_source << '*/' end
ruby
def to_s_append( ds, s ) s << '$' << name.to_s s << ':' << sql_field.to_s if sql_field s << '/*' << small_source << '*/' end
[ "def", "to_s_append", "(", "ds", ",", "s", ")", "s", "<<", "'$'", "<<", "name", ".", "to_s", "s", "<<", "':'", "<<", "sql_field", ".", "to_s", "if", "sql_field", "s", "<<", "'/*'", "<<", "small_source", "<<", "'*/'", "end" ]
this is inserted into the generated SQL from a dataset that contains PlaceHolder instances.
[ "this", "is", "inserted", "into", "the", "generated", "SQL", "from", "a", "dataset", "that", "contains", "PlaceHolder", "instances", "." ]
d0407b9eccaee8918a86ea25feabf500a3b2ac1a
https://github.com/djellemah/philtre/blob/d0407b9eccaee8918a86ea25feabf500a3b2ac1a/lib/philtre/place_holder.rb#L19-L23
24,233
djellemah/philtre
lib/philtre/filter.rb
Philtre.Filter.call
def call( dataset ) # mainly for Sequel::Model dataset = dataset.dataset if dataset.respond_to? :dataset # clone here so later order! calls don't mess with a Model's default dataset dataset = expressions.inject(dataset.clone) do |dataset, filter_expr| dataset.filter( filter_expr ) end # preserve existing order if we don't have one. if order_clause.empty? dataset else # There might be multiple orderings in the order_clause dataset.order *order_clause end end
ruby
def call( dataset ) # mainly for Sequel::Model dataset = dataset.dataset if dataset.respond_to? :dataset # clone here so later order! calls don't mess with a Model's default dataset dataset = expressions.inject(dataset.clone) do |dataset, filter_expr| dataset.filter( filter_expr ) end # preserve existing order if we don't have one. if order_clause.empty? dataset else # There might be multiple orderings in the order_clause dataset.order *order_clause end end
[ "def", "call", "(", "dataset", ")", "# mainly for Sequel::Model", "dataset", "=", "dataset", ".", "dataset", "if", "dataset", ".", "respond_to?", ":dataset", "# clone here so later order! calls don't mess with a Model's default dataset", "dataset", "=", "expressions", ".", "inject", "(", "dataset", ".", "clone", ")", "do", "|", "dataset", ",", "filter_expr", "|", "dataset", ".", "filter", "(", "filter_expr", ")", "end", "# preserve existing order if we don't have one.", "if", "order_clause", ".", "empty?", "dataset", "else", "# There might be multiple orderings in the order_clause", "dataset", ".", "order", "order_clause", "end", "end" ]
return a modified dataset containing all the predicates
[ "return", "a", "modified", "dataset", "containing", "all", "the", "predicates" ]
d0407b9eccaee8918a86ea25feabf500a3b2ac1a
https://github.com/djellemah/philtre/blob/d0407b9eccaee8918a86ea25feabf500a3b2ac1a/lib/philtre/filter.rb#L51-L67
24,234
djellemah/philtre
lib/philtre/filter.rb
Philtre.Filter.valued_parameters
def valued_parameters @valued_parameters ||= filter_parameters.select do |key,value| # :order is special, it must always be excluded key.to_sym != :order && valued_parameter?(key,value) end end
ruby
def valued_parameters @valued_parameters ||= filter_parameters.select do |key,value| # :order is special, it must always be excluded key.to_sym != :order && valued_parameter?(key,value) end end
[ "def", "valued_parameters", "@valued_parameters", "||=", "filter_parameters", ".", "select", "do", "|", "key", ",", "value", "|", "# :order is special, it must always be excluded", "key", ".", "to_sym", "!=", ":order", "&&", "valued_parameter?", "(", "key", ",", "value", ")", "end", "end" ]
Values in the parameter list which are not blank, and not an ordering. That is, parameters which will be used to generate the filter expression.
[ "Values", "in", "the", "parameter", "list", "which", "are", "not", "blank", "and", "not", "an", "ordering", ".", "That", "is", "parameters", "which", "will", "be", "used", "to", "generate", "the", "filter", "expression", "." ]
d0407b9eccaee8918a86ea25feabf500a3b2ac1a
https://github.com/djellemah/philtre/blob/d0407b9eccaee8918a86ea25feabf500a3b2ac1a/lib/philtre/filter.rb#L83-L88
24,235
djellemah/philtre
lib/philtre/filter.rb
Philtre.Filter.to_h
def to_h(all=false) filter_parameters.select{|k,v| all || !v.blank?} end
ruby
def to_h(all=false) filter_parameters.select{|k,v| all || !v.blank?} end
[ "def", "to_h", "(", "all", "=", "false", ")", "filter_parameters", ".", "select", "{", "|", "k", ",", "v", "|", "all", "||", "!", "v", ".", "blank?", "}", "end" ]
for use in forms
[ "for", "use", "in", "forms" ]
d0407b9eccaee8918a86ea25feabf500a3b2ac1a
https://github.com/djellemah/philtre/blob/d0407b9eccaee8918a86ea25feabf500a3b2ac1a/lib/philtre/filter.rb#L165-L167
24,236
djellemah/philtre
lib/philtre/filter.rb
Philtre.Filter.expr_hash
def expr_hash vary = valued_parameters.map do |key, value| [ key, to_expr(key, value) ] end Hash[ vary ] end
ruby
def expr_hash vary = valued_parameters.map do |key, value| [ key, to_expr(key, value) ] end Hash[ vary ] end
[ "def", "expr_hash", "vary", "=", "valued_parameters", ".", "map", "do", "|", "key", ",", "value", "|", "[", "key", ",", "to_expr", "(", "key", ",", "value", ")", "]", "end", "Hash", "[", "vary", "]", "end" ]
hash of keys to expressions, but only where there are values.
[ "hash", "of", "keys", "to", "expressions", "but", "only", "where", "there", "are", "values", "." ]
d0407b9eccaee8918a86ea25feabf500a3b2ac1a
https://github.com/djellemah/philtre/blob/d0407b9eccaee8918a86ea25feabf500a3b2ac1a/lib/philtre/filter.rb#L224-L230
24,237
distil/jserializer
lib/jserializer/base.rb
Jserializer.Base.serializable_hash
def serializable_hash return serializable_collection if collection? self.class._attributes.each_with_object({}) do |(name, option), hash| if _include_from_options?(name) && public_send(option[:include_method]) hash[option[:key] || name] = _set_value(name, option) end end end
ruby
def serializable_hash return serializable_collection if collection? self.class._attributes.each_with_object({}) do |(name, option), hash| if _include_from_options?(name) && public_send(option[:include_method]) hash[option[:key] || name] = _set_value(name, option) end end end
[ "def", "serializable_hash", "return", "serializable_collection", "if", "collection?", "self", ".", "class", ".", "_attributes", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "name", ",", "option", ")", ",", "hash", "|", "if", "_include_from_options?", "(", "name", ")", "&&", "public_send", "(", "option", "[", ":include_method", "]", ")", "hash", "[", "option", "[", ":key", "]", "||", "name", "]", "=", "_set_value", "(", "name", ",", "option", ")", "end", "end", "end" ]
Returns a hash representation without the root
[ "Returns", "a", "hash", "representation", "without", "the", "root" ]
7125abb379d7d2b7b7001ecefc8378202542d46c
https://github.com/distil/jserializer/blob/7125abb379d7d2b7b7001ecefc8378202542d46c/lib/jserializer/base.rb#L120-L127
24,238
jdigger/git-process
lib/git-process/git_branch.rb
GitProc.GitBranch.delete!
def delete!(force = false) if local? @lib.branch(@name, :force => force, :delete => true) else @lib.push(Process.server_name, nil, nil, :delete => @name) end end
ruby
def delete!(force = false) if local? @lib.branch(@name, :force => force, :delete => true) else @lib.push(Process.server_name, nil, nil, :delete => @name) end end
[ "def", "delete!", "(", "force", "=", "false", ")", "if", "local?", "@lib", ".", "branch", "(", "@name", ",", ":force", "=>", "force", ",", ":delete", "=>", "true", ")", "else", "@lib", ".", "push", "(", "Process", ".", "server_name", ",", "nil", ",", "nil", ",", ":delete", "=>", "@name", ")", "end", "end" ]
Delete this branch @param [Boolean] force should this force removal even if the branch has not been fully merged? @return [String] the output of running the git command
[ "Delete", "this", "branch" ]
5853aa94258e724ce0dbc2f1e7407775e1630964
https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_branch.rb#L114-L120
24,239
rapid7/metasploit-model
lib/metasploit/model/search.rb
Metasploit::Model::Search.ClassMethods.search_operator_by_name
def search_operator_by_name unless instance_variable_defined? :@search_operator_by_name @search_operator_by_name = {} search_with_operator_by_name.each_value do |operator| @search_operator_by_name[operator.name] = operator end search_association_operators.each do |operator| @search_operator_by_name[operator.name] = operator end end @search_operator_by_name end
ruby
def search_operator_by_name unless instance_variable_defined? :@search_operator_by_name @search_operator_by_name = {} search_with_operator_by_name.each_value do |operator| @search_operator_by_name[operator.name] = operator end search_association_operators.each do |operator| @search_operator_by_name[operator.name] = operator end end @search_operator_by_name end
[ "def", "search_operator_by_name", "unless", "instance_variable_defined?", ":@search_operator_by_name", "@search_operator_by_name", "=", "{", "}", "search_with_operator_by_name", ".", "each_value", "do", "|", "operator", "|", "@search_operator_by_name", "[", "operator", ".", "name", "]", "=", "operator", "end", "search_association_operators", ".", "each", "do", "|", "operator", "|", "@search_operator_by_name", "[", "operator", ".", "name", "]", "=", "operator", "end", "end", "@search_operator_by_name", "end" ]
Collects all search attributes from search associations and all attributes from this class to show the valid search operators to search. @return [Hash{Symbol => Metasploit::Model::Search::Operator}] Maps {Metasploit::Model::Search::Operator::Base#name} to {Metasploit::Model::Search::Operator::Base#name}.
[ "Collects", "all", "search", "attributes", "from", "search", "associations", "and", "all", "attributes", "from", "this", "class", "to", "show", "the", "valid", "search", "operators", "to", "search", "." ]
cb6606bf24218798e853ba44470df31a47d9b627
https://github.com/rapid7/metasploit-model/blob/cb6606bf24218798e853ba44470df31a47d9b627/lib/metasploit/model/search.rb#L87-L101
24,240
altabyte/ebay_trader
lib/ebay_trader/xml_builder.rb
EbayTrader.XMLBuilder.root
def root(name, *args, &block) set_context(&block) node(name, args, &block) end
ruby
def root(name, *args, &block) set_context(&block) node(name, args, &block) end
[ "def", "root", "(", "name", ",", "*", "args", ",", "&", "block", ")", "set_context", "(", "block", ")", "node", "(", "name", ",", "args", ",", "block", ")", "end" ]
Begin creating an XML string by specifying the root node. This also sets the context scope, allowing methods and variables outside the block to be accessed. @param [String] name the name of the root node element. @param [Array] args the data for this element. @param [Block] block an optional block of sub-elements to be nested within the root node.
[ "Begin", "creating", "an", "XML", "string", "by", "specifying", "the", "root", "node", ".", "This", "also", "sets", "the", "context", "scope", "allowing", "methods", "and", "variables", "outside", "the", "block", "to", "be", "accessed", "." ]
4442b683ea27f02fa0ef73f3f6357396fbe29b56
https://github.com/altabyte/ebay_trader/blob/4442b683ea27f02fa0ef73f3f6357396fbe29b56/lib/ebay_trader/xml_builder.rb#L36-L39
24,241
altabyte/ebay_trader
lib/ebay_trader/xml_builder.rb
EbayTrader.XMLBuilder.node
def node(name, args, &block) content = get_node_content(args) options = format_node_attributes(get_node_attributes(args)) @_segments ||= [] @_segments << "#{indent_new_line}<#{name}#{options}>#{content}" if block_given? @depth += 1 instance_eval(&block) @depth -= 1 @_segments << indent_new_line end @_segments << "</#{name}>" @xml = @_segments.join('').strip end
ruby
def node(name, args, &block) content = get_node_content(args) options = format_node_attributes(get_node_attributes(args)) @_segments ||= [] @_segments << "#{indent_new_line}<#{name}#{options}>#{content}" if block_given? @depth += 1 instance_eval(&block) @depth -= 1 @_segments << indent_new_line end @_segments << "</#{name}>" @xml = @_segments.join('').strip end
[ "def", "node", "(", "name", ",", "args", ",", "&", "block", ")", "content", "=", "get_node_content", "(", "args", ")", "options", "=", "format_node_attributes", "(", "get_node_attributes", "(", "args", ")", ")", "@_segments", "||=", "[", "]", "@_segments", "<<", "\"#{indent_new_line}<#{name}#{options}>#{content}\"", "if", "block_given?", "@depth", "+=", "1", "instance_eval", "(", "block", ")", "@depth", "-=", "1", "@_segments", "<<", "indent_new_line", "end", "@_segments", "<<", "\"</#{name}>\"", "@xml", "=", "@_segments", ".", "join", "(", "''", ")", ".", "strip", "end" ]
Create an XML node @param [String|Symbol] name the name of the XML element (ul, li, strong, etc...) @param [Array] args Can contain a String of text or a Hash of attributes @param [Block] block An optional block which will further nest XML
[ "Create", "an", "XML", "node" ]
4442b683ea27f02fa0ef73f3f6357396fbe29b56
https://github.com/altabyte/ebay_trader/blob/4442b683ea27f02fa0ef73f3f6357396fbe29b56/lib/ebay_trader/xml_builder.rb#L54-L68
24,242
altabyte/ebay_trader
lib/ebay_trader/xml_builder.rb
EbayTrader.XMLBuilder.get_node_content
def get_node_content(args) return nil if block_given? content = nil args.each do |arg| case arg when Hash next when Time # eBay official TimeStamp format YYYY-MM-DDTHH:MM:SS.SSSZ content = arg.strftime('%Y-%m-%dT%H:%M:%S.%Z') when DateTime content = arg.strftime('%Y-%m-%dT%H:%M:%S.%Z') break else content = arg.to_s break end end content end
ruby
def get_node_content(args) return nil if block_given? content = nil args.each do |arg| case arg when Hash next when Time # eBay official TimeStamp format YYYY-MM-DDTHH:MM:SS.SSSZ content = arg.strftime('%Y-%m-%dT%H:%M:%S.%Z') when DateTime content = arg.strftime('%Y-%m-%dT%H:%M:%S.%Z') break else content = arg.to_s break end end content end
[ "def", "get_node_content", "(", "args", ")", "return", "nil", "if", "block_given?", "content", "=", "nil", "args", ".", "each", "do", "|", "arg", "|", "case", "arg", "when", "Hash", "next", "when", "Time", "# eBay official TimeStamp format YYYY-MM-DDTHH:MM:SS.SSSZ", "content", "=", "arg", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%S.%Z'", ")", "when", "DateTime", "content", "=", "arg", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%S.%Z'", ")", "break", "else", "content", "=", "arg", ".", "to_s", "break", "end", "end", "content", "end" ]
Return the node content as a String, unless a block is given. @return [String] the node data.
[ "Return", "the", "node", "content", "as", "a", "String", "unless", "a", "block", "is", "given", "." ]
4442b683ea27f02fa0ef73f3f6357396fbe29b56
https://github.com/altabyte/ebay_trader/blob/4442b683ea27f02fa0ef73f3f6357396fbe29b56/lib/ebay_trader/xml_builder.rb#L81-L100
24,243
altabyte/ebay_trader
lib/ebay_trader/xml_builder.rb
EbayTrader.XMLBuilder.format_node_attributes
def format_node_attributes(options) options.collect { |key, value| value = value.to_s.gsub('"', '\"') " #{key}=\"#{value}\"" }.join('') end
ruby
def format_node_attributes(options) options.collect { |key, value| value = value.to_s.gsub('"', '\"') " #{key}=\"#{value}\"" }.join('') end
[ "def", "format_node_attributes", "(", "options", ")", "options", ".", "collect", "{", "|", "key", ",", "value", "|", "value", "=", "value", ".", "to_s", ".", "gsub", "(", "'\"'", ",", "'\\\"'", ")", "\" #{key}=\\\"#{value}\\\"\"", "}", ".", "join", "(", "''", ")", "end" ]
Convert the given Hash of options into a string of XML element attributes.
[ "Convert", "the", "given", "Hash", "of", "options", "into", "a", "string", "of", "XML", "element", "attributes", "." ]
4442b683ea27f02fa0ef73f3f6357396fbe29b56
https://github.com/altabyte/ebay_trader/blob/4442b683ea27f02fa0ef73f3f6357396fbe29b56/lib/ebay_trader/xml_builder.rb#L104-L109
24,244
artursbraucs/mailigen
lib/mailigen/api.rb
Mailigen.Api.call
def call method, params = {} url = "#{api_url}&method=#{method}" params = {apikey: self.api_key}.merge params resp = post_api(url, params) begin return JSON.parse(resp) rescue return resp.tr('"','') end end
ruby
def call method, params = {} url = "#{api_url}&method=#{method}" params = {apikey: self.api_key}.merge params resp = post_api(url, params) begin return JSON.parse(resp) rescue return resp.tr('"','') end end
[ "def", "call", "method", ",", "params", "=", "{", "}", "url", "=", "\"#{api_url}&method=#{method}\"", "params", "=", "{", "apikey", ":", "self", ".", "api_key", "}", ".", "merge", "params", "resp", "=", "post_api", "(", "url", ",", "params", ")", "begin", "return", "JSON", ".", "parse", "(", "resp", ")", "rescue", "return", "resp", ".", "tr", "(", "'\"'", ",", "''", ")", "end", "end" ]
Initialize API wrapper. @param api_key - from mailigen.com . Required. @param secure - use SSL. By default FALSE Call Mailigen api method (Documented in http://dev.mailigen.com/display/AD/Mailigen+API ) @param method - method name @param params - params if required for API @return JSON, String data if all goes well. Exception if somethnigs goes wrong.
[ "Initialize", "API", "wrapper", "." ]
fb87e72242cfabc2bc4aad0844993d71ed2ff53d
https://github.com/artursbraucs/mailigen/blob/fb87e72242cfabc2bc4aad0844993d71ed2ff53d/lib/mailigen/api.rb#L32-L43
24,245
artursbraucs/mailigen
lib/mailigen/api.rb
Mailigen.Api.post_api
def post_api url, params uri = URI.parse(url) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = self.secure form_params = params.to_query res = http.post(uri.request_uri, form_params) res.body end
ruby
def post_api url, params uri = URI.parse(url) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = self.secure form_params = params.to_query res = http.post(uri.request_uri, form_params) res.body end
[ "def", "post_api", "url", ",", "params", "uri", "=", "URI", ".", "parse", "(", "url", ")", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "http", ".", "use_ssl", "=", "self", ".", "secure", "form_params", "=", "params", ".", "to_query", "res", "=", "http", ".", "post", "(", "uri", ".", "request_uri", ",", "form_params", ")", "res", ".", "body", "end" ]
All api calls throught POST method. @param url - url to post @param params - params in hash @return response body
[ "All", "api", "calls", "throught", "POST", "method", "." ]
fb87e72242cfabc2bc4aad0844993d71ed2ff53d
https://github.com/artursbraucs/mailigen/blob/fb87e72242cfabc2bc4aad0844993d71ed2ff53d/lib/mailigen/api.rb#L62-L69
24,246
toptierlabs/api_explorer
app/controllers/api_explorer/api_controller.rb
ApiExplorer.ApiController.read_file
def read_file json_string = '' if ApiExplorer::use_file json_path = ApiExplorer::json_path json_string = File.read(json_path) else json_string = ApiExplorer::json_string end @methods = JSON.parse(json_string)["methods"] end
ruby
def read_file json_string = '' if ApiExplorer::use_file json_path = ApiExplorer::json_path json_string = File.read(json_path) else json_string = ApiExplorer::json_string end @methods = JSON.parse(json_string)["methods"] end
[ "def", "read_file", "json_string", "=", "''", "if", "ApiExplorer", "::", "use_file", "json_path", "=", "ApiExplorer", "::", "json_path", "json_string", "=", "File", ".", "read", "(", "json_path", ")", "else", "json_string", "=", "ApiExplorer", "::", "json_string", "end", "@methods", "=", "JSON", ".", "parse", "(", "json_string", ")", "[", "\"methods\"", "]", "end" ]
Read file with methods
[ "Read", "file", "with", "methods" ]
14b9ad9c687b8c85f178ac7b60887ebe070f182f
https://github.com/toptierlabs/api_explorer/blob/14b9ad9c687b8c85f178ac7b60887ebe070f182f/app/controllers/api_explorer/api_controller.rb#L138-L148
24,247
haberbyte/phoney
lib/phoney/formatter.rb
Phoney.Formatter.format
def format(input, pattern, options={}) fill = options[:fill] intl_prefix = options[:intl_prefix]||'' trunk_prefix = options[:trunk_prefix]||'' slots = pattern.count(PLACEHOLDER_CHAR) # Return original input if it is too long return input if (fill.nil? && input.length > slots) # Pad and clone the string if necessary. source = (fill.nil? || fill.empty?) ? input : input.ljust(slots, fill) result = '' slot = 0 has_open = had_c = had_n = false pattern.split('').each_with_index do |chr, index| case chr when 'c' had_c = true result << intl_prefix when 'n' had_n = true result << trunk_prefix when '#' if slot < source.length result << source[slot] slot += 1 else result << ' ' if has_open end when '(' if slot < source.length has_open = true result << chr end when ')' if (slot < source.length || has_open) has_open = false result << chr end else # Don't show space after n if no trunk prefix or after c if no intl prefix next if (chr == ' ' && pattern[index-1] == 'n' && trunk_prefix.empty?) next if (chr == ' ' && pattern[index-1] == 'c' && intl_prefix.empty?) result << chr if (slot < source.length) end end # Not all format strings have a 'c' or 'n' in them. # If we have an international prefix or a trunk prefix but the format string # doesn't explictly say where to put it then simply add it to the beginning. result.prepend trunk_prefix if (!had_n && !trunk_prefix.empty?) result.prepend "#{intl_prefix} " if (!had_c && !intl_prefix.empty?) result.strip end
ruby
def format(input, pattern, options={}) fill = options[:fill] intl_prefix = options[:intl_prefix]||'' trunk_prefix = options[:trunk_prefix]||'' slots = pattern.count(PLACEHOLDER_CHAR) # Return original input if it is too long return input if (fill.nil? && input.length > slots) # Pad and clone the string if necessary. source = (fill.nil? || fill.empty?) ? input : input.ljust(slots, fill) result = '' slot = 0 has_open = had_c = had_n = false pattern.split('').each_with_index do |chr, index| case chr when 'c' had_c = true result << intl_prefix when 'n' had_n = true result << trunk_prefix when '#' if slot < source.length result << source[slot] slot += 1 else result << ' ' if has_open end when '(' if slot < source.length has_open = true result << chr end when ')' if (slot < source.length || has_open) has_open = false result << chr end else # Don't show space after n if no trunk prefix or after c if no intl prefix next if (chr == ' ' && pattern[index-1] == 'n' && trunk_prefix.empty?) next if (chr == ' ' && pattern[index-1] == 'c' && intl_prefix.empty?) result << chr if (slot < source.length) end end # Not all format strings have a 'c' or 'n' in them. # If we have an international prefix or a trunk prefix but the format string # doesn't explictly say where to put it then simply add it to the beginning. result.prepend trunk_prefix if (!had_n && !trunk_prefix.empty?) result.prepend "#{intl_prefix} " if (!had_c && !intl_prefix.empty?) result.strip end
[ "def", "format", "(", "input", ",", "pattern", ",", "options", "=", "{", "}", ")", "fill", "=", "options", "[", ":fill", "]", "intl_prefix", "=", "options", "[", ":intl_prefix", "]", "||", "''", "trunk_prefix", "=", "options", "[", ":trunk_prefix", "]", "||", "''", "slots", "=", "pattern", ".", "count", "(", "PLACEHOLDER_CHAR", ")", "# Return original input if it is too long", "return", "input", "if", "(", "fill", ".", "nil?", "&&", "input", ".", "length", ">", "slots", ")", "# Pad and clone the string if necessary.", "source", "=", "(", "fill", ".", "nil?", "||", "fill", ".", "empty?", ")", "?", "input", ":", "input", ".", "ljust", "(", "slots", ",", "fill", ")", "result", "=", "''", "slot", "=", "0", "has_open", "=", "had_c", "=", "had_n", "=", "false", "pattern", ".", "split", "(", "''", ")", ".", "each_with_index", "do", "|", "chr", ",", "index", "|", "case", "chr", "when", "'c'", "had_c", "=", "true", "result", "<<", "intl_prefix", "when", "'n'", "had_n", "=", "true", "result", "<<", "trunk_prefix", "when", "'#'", "if", "slot", "<", "source", ".", "length", "result", "<<", "source", "[", "slot", "]", "slot", "+=", "1", "else", "result", "<<", "' '", "if", "has_open", "end", "when", "'('", "if", "slot", "<", "source", ".", "length", "has_open", "=", "true", "result", "<<", "chr", "end", "when", "')'", "if", "(", "slot", "<", "source", ".", "length", "||", "has_open", ")", "has_open", "=", "false", "result", "<<", "chr", "end", "else", "# Don't show space after n if no trunk prefix or after c if no intl prefix", "next", "if", "(", "chr", "==", "' '", "&&", "pattern", "[", "index", "-", "1", "]", "==", "'n'", "&&", "trunk_prefix", ".", "empty?", ")", "next", "if", "(", "chr", "==", "' '", "&&", "pattern", "[", "index", "-", "1", "]", "==", "'c'", "&&", "intl_prefix", ".", "empty?", ")", "result", "<<", "chr", "if", "(", "slot", "<", "source", ".", "length", ")", "end", "end", "# Not all format strings have a 'c' or 'n' in them.", "# If we have an international prefix or a trunk prefix but the format string", "# doesn't explictly say where to put it then simply add it to the beginning.", "result", ".", "prepend", "trunk_prefix", "if", "(", "!", "had_n", "&&", "!", "trunk_prefix", ".", "empty?", ")", "result", ".", "prepend", "\"#{intl_prefix} \"", "if", "(", "!", "had_c", "&&", "!", "intl_prefix", ".", "empty?", ")", "result", ".", "strip", "end" ]
Returns the string formatted according to a pattern. Examples: format('123456789', 'XXX-XX-XXXX') => "123-45-6789" format('12345', 'XXX-XX-XXXX') => "123-45" Parameters: string -- The string to be formatted. pattern -- The format string, see above examples. fill -- A string for padding. If the empty string, then the pattern is filled as much as possible, and the rest of the pattern is truncated. If nil, and the string is too long for the pattern, the string is returned unchanged. Otherwise, the string is padded to fill the pattern, which is not truncated.
[ "Returns", "the", "string", "formatted", "according", "to", "a", "pattern", "." ]
b50708d483dd7c19ff42c0a1c542def9feecb90f
https://github.com/haberbyte/phoney/blob/b50708d483dd7c19ff42c0a1c542def9feecb90f/lib/phoney/formatter.rb#L19-L76
24,248
jdigger/git-process
lib/git-process/github_configuration.rb
GitHubService.Configuration.configure_octokit
def configure_octokit(opts = {}) base_url = opts[:base_url] || base_github_api_url_for_remote Octokit.configure do |c| c.api_endpoint = api_endpoint(base_url) c.web_endpoint = web_endpoint(base_url) end if logger.level < ::GitProc::GitLogger::INFO Octokit.middleware = Faraday::RackBuilder.new do |builder| builder.response :logger, logger builder.use Octokit::Response::RaiseError builder.adapter Faraday.default_adapter end end end
ruby
def configure_octokit(opts = {}) base_url = opts[:base_url] || base_github_api_url_for_remote Octokit.configure do |c| c.api_endpoint = api_endpoint(base_url) c.web_endpoint = web_endpoint(base_url) end if logger.level < ::GitProc::GitLogger::INFO Octokit.middleware = Faraday::RackBuilder.new do |builder| builder.response :logger, logger builder.use Octokit::Response::RaiseError builder.adapter Faraday.default_adapter end end end
[ "def", "configure_octokit", "(", "opts", "=", "{", "}", ")", "base_url", "=", "opts", "[", ":base_url", "]", "||", "base_github_api_url_for_remote", "Octokit", ".", "configure", "do", "|", "c", "|", "c", ".", "api_endpoint", "=", "api_endpoint", "(", "base_url", ")", "c", ".", "web_endpoint", "=", "web_endpoint", "(", "base_url", ")", "end", "if", "logger", ".", "level", "<", "::", "GitProc", "::", "GitLogger", "::", "INFO", "Octokit", ".", "middleware", "=", "Faraday", "::", "RackBuilder", ".", "new", "do", "|", "builder", "|", "builder", ".", "response", ":logger", ",", "logger", "builder", ".", "use", "Octokit", "::", "Response", "::", "RaiseError", "builder", ".", "adapter", "Faraday", ".", "default_adapter", "end", "end", "end" ]
Configures Octokit to use the appropriate URLs for GitHub server. @option opts [String] :base_url The base URL to use for the GitHub server; defaults to {#base_github_api_url_for_remote} @return [void] @todo remove opts and pass in base_url directly
[ "Configures", "Octokit", "to", "use", "the", "appropriate", "URLs", "for", "GitHub", "server", "." ]
5853aa94258e724ce0dbc2f1e7407775e1630964
https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/github_configuration.rb#L100-L113
24,249
jdigger/git-process
lib/git-process/github_configuration.rb
GitHubService.Configuration.create_pw_client
def create_pw_client(opts = {}) usr = opts[:user] || user() pw = opts[:password] || password() remote = opts[:remote_name] || self.remote_name logger.info("Authorizing #{usr} to work with #{remote}.") configure_octokit(opts) Octokit::Client.new(:login => usr, :password => pw) end
ruby
def create_pw_client(opts = {}) usr = opts[:user] || user() pw = opts[:password] || password() remote = opts[:remote_name] || self.remote_name logger.info("Authorizing #{usr} to work with #{remote}.") configure_octokit(opts) Octokit::Client.new(:login => usr, :password => pw) end
[ "def", "create_pw_client", "(", "opts", "=", "{", "}", ")", "usr", "=", "opts", "[", ":user", "]", "||", "user", "(", ")", "pw", "=", "opts", "[", ":password", "]", "||", "password", "(", ")", "remote", "=", "opts", "[", ":remote_name", "]", "||", "self", ".", "remote_name", "logger", ".", "info", "(", "\"Authorizing #{usr} to work with #{remote}.\"", ")", "configure_octokit", "(", "opts", ")", "Octokit", "::", "Client", ".", "new", "(", ":login", "=>", "usr", ",", ":password", "=>", "pw", ")", "end" ]
Create a GitHub client using username and password specifically. Meant to be used to get an OAuth token for "regular" client calls. @param [Hash] opts the options to create a message with @option opts [String] :base_url The base URL to use for the GitHub server @option opts [String] :remote_name (#remote_name) The "remote" name to use (e.g., 'origin') @option opts [String] :user the username to authenticate with @option opts [String] :password (#password) the password to authenticate with @return [Octokit::Client] the Octokit client for communicating with GitHub
[ "Create", "a", "GitHub", "client", "using", "username", "and", "password", "specifically", ".", "Meant", "to", "be", "used", "to", "get", "an", "OAuth", "token", "for", "regular", "client", "calls", "." ]
5853aa94258e724ce0dbc2f1e7407775e1630964
https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/github_configuration.rb#L208-L218
24,250
jdigger/git-process
lib/git-process/github_configuration.rb
GitHubService.Configuration.unprocessable_authorization
def unprocessable_authorization(exp) errors = exp.errors if not (errors.nil? or errors.empty?) error_hash = errors[0] if error_hash[:resource] == 'OauthAccess' # error_hash[:code] return ask_about_resetting_authorization else raise exp end else raise exp end end
ruby
def unprocessable_authorization(exp) errors = exp.errors if not (errors.nil? or errors.empty?) error_hash = errors[0] if error_hash[:resource] == 'OauthAccess' # error_hash[:code] return ask_about_resetting_authorization else raise exp end else raise exp end end
[ "def", "unprocessable_authorization", "(", "exp", ")", "errors", "=", "exp", ".", "errors", "if", "not", "(", "errors", ".", "nil?", "or", "errors", ".", "empty?", ")", "error_hash", "=", "errors", "[", "0", "]", "if", "error_hash", "[", ":resource", "]", "==", "'OauthAccess'", "# error_hash[:code]", "return", "ask_about_resetting_authorization", "else", "raise", "exp", "end", "else", "raise", "exp", "end", "end" ]
Tries to more gracefully handle the token already existing. See @return [String] the OAuth token @raise [TokenAlreadyExists] the token already exists @raise [Octokit::UnprocessableEntity] there was another problem
[ "Tries", "to", "more", "gracefully", "handle", "the", "token", "already", "existing", ".", "See" ]
5853aa94258e724ce0dbc2f1e7407775e1630964
https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/github_configuration.rb#L379-L392
24,251
rapid7/metasploit-model
lib/metasploit/model/association.rb
Metasploit::Model::Association.ClassMethods.association
def association(name, options={}) association = Metasploit::Model::Association::Reflection.new( :model => self, :name => name.to_sym, :class_name => options[:class_name] ) association.valid! association_by_name[association.name] = association end
ruby
def association(name, options={}) association = Metasploit::Model::Association::Reflection.new( :model => self, :name => name.to_sym, :class_name => options[:class_name] ) association.valid! association_by_name[association.name] = association end
[ "def", "association", "(", "name", ",", "options", "=", "{", "}", ")", "association", "=", "Metasploit", "::", "Model", "::", "Association", "::", "Reflection", ".", "new", "(", ":model", "=>", "self", ",", ":name", "=>", "name", ".", "to_sym", ",", ":class_name", "=>", "options", "[", ":class_name", "]", ")", "association", ".", "valid!", "association_by_name", "[", "association", ".", "name", "]", "=", "association", "end" ]
Registers an association. @param name [to_sym] Name of the association @param options [Hash{Symbol => String}] @option options [String] :class_name Name of association's class. @return [Metasploit::Model::Association::Reflection] the reflection of the registered association. @raise [Metasploit::Model::Invalid] if name is blank. @raise [Metasploit::Model::Invalid] if :class_name is blank.
[ "Registers", "an", "association", "." ]
cb6606bf24218798e853ba44470df31a47d9b627
https://github.com/rapid7/metasploit-model/blob/cb6606bf24218798e853ba44470df31a47d9b627/lib/metasploit/model/association.rb#L22-L31
24,252
thinkclay/Rails-Annex-Gem
lib/annex/view_helpers.rb
Annex.ViewHelpers.annex_block
def annex_block(identifier, opts = {}) opts[:route] ||= current_route case Annex::config[:adapter] when :activerecord doc = Annex::Block.where(route: "#{opts[:route]}_#{identifier}").first_or_create content = doc.content when :mongoid doc = Annex::Block.where(route: opts[:route]).first_or_create content = doc.content.try(:[], identifier.to_s) end render partial: 'annex/block', locals: { content: content || opts[:default], identifier: identifier, opts: opts } end
ruby
def annex_block(identifier, opts = {}) opts[:route] ||= current_route case Annex::config[:adapter] when :activerecord doc = Annex::Block.where(route: "#{opts[:route]}_#{identifier}").first_or_create content = doc.content when :mongoid doc = Annex::Block.where(route: opts[:route]).first_or_create content = doc.content.try(:[], identifier.to_s) end render partial: 'annex/block', locals: { content: content || opts[:default], identifier: identifier, opts: opts } end
[ "def", "annex_block", "(", "identifier", ",", "opts", "=", "{", "}", ")", "opts", "[", ":route", "]", "||=", "current_route", "case", "Annex", "::", "config", "[", ":adapter", "]", "when", ":activerecord", "doc", "=", "Annex", "::", "Block", ".", "where", "(", "route", ":", "\"#{opts[:route]}_#{identifier}\"", ")", ".", "first_or_create", "content", "=", "doc", ".", "content", "when", ":mongoid", "doc", "=", "Annex", "::", "Block", ".", "where", "(", "route", ":", "opts", "[", ":route", "]", ")", ".", "first_or_create", "content", "=", "doc", ".", "content", ".", "try", "(", ":[]", ",", "identifier", ".", "to_s", ")", "end", "render", "partial", ":", "'annex/block'", ",", "locals", ":", "{", "content", ":", "content", "||", "opts", "[", ":default", "]", ",", "identifier", ":", "identifier", ",", "opts", ":", "opts", "}", "end" ]
annex_block is a universal helper to render content from the database and display it on the page
[ "annex_block", "is", "a", "universal", "helper", "to", "render", "content", "from", "the", "database", "and", "display", "it", "on", "the", "page" ]
aff8c0a3025910d906ea46331053d3b5117a03c9
https://github.com/thinkclay/Rails-Annex-Gem/blob/aff8c0a3025910d906ea46331053d3b5117a03c9/lib/annex/view_helpers.rb#L10-L26
24,253
jdigger/git-process
lib/git-process/git_remote.rb
GitProc.GitRemote.repo_name
def repo_name unless @repo_name url = config["remote.#{name}.url"] raise GitProcessError.new("There is no #{name} url set up.") if url.nil? or url.empty? uri = Addressable::URI.parse(url) @repo_name = uri.path.sub(/\.git/, '').sub(/^\//, '') end @repo_name end
ruby
def repo_name unless @repo_name url = config["remote.#{name}.url"] raise GitProcessError.new("There is no #{name} url set up.") if url.nil? or url.empty? uri = Addressable::URI.parse(url) @repo_name = uri.path.sub(/\.git/, '').sub(/^\//, '') end @repo_name end
[ "def", "repo_name", "unless", "@repo_name", "url", "=", "config", "[", "\"remote.#{name}.url\"", "]", "raise", "GitProcessError", ".", "new", "(", "\"There is no #{name} url set up.\"", ")", "if", "url", ".", "nil?", "or", "url", ".", "empty?", "uri", "=", "Addressable", "::", "URI", ".", "parse", "(", "url", ")", "@repo_name", "=", "uri", ".", "path", ".", "sub", "(", "/", "\\.", "/", ",", "''", ")", ".", "sub", "(", "/", "\\/", "/", ",", "''", ")", "end", "@repo_name", "end" ]
The name of the repository @example repo_name #=> "jdigger/git-process" @return [String] the name of the repository
[ "The", "name", "of", "the", "repository" ]
5853aa94258e724ce0dbc2f1e7407775e1630964
https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_remote.rb#L84-L92
24,254
jdigger/git-process
lib/git-process/git_remote.rb
GitProc.GitRemote.remote_name
def remote_name unless @remote_name @remote_name = config['gitProcess.remoteName'] if @remote_name.nil? or @remote_name.empty? remotes = self.remote_names if remotes.empty? @remote_name = nil else @remote_name = remotes[0] raise "remote name is not a String: #{@remote_name.inspect}" unless @remote_name.is_a? String end end logger.debug { "Using remote name of '#{@remote_name}'" } end @remote_name end
ruby
def remote_name unless @remote_name @remote_name = config['gitProcess.remoteName'] if @remote_name.nil? or @remote_name.empty? remotes = self.remote_names if remotes.empty? @remote_name = nil else @remote_name = remotes[0] raise "remote name is not a String: #{@remote_name.inspect}" unless @remote_name.is_a? String end end logger.debug { "Using remote name of '#{@remote_name}'" } end @remote_name end
[ "def", "remote_name", "unless", "@remote_name", "@remote_name", "=", "config", "[", "'gitProcess.remoteName'", "]", "if", "@remote_name", ".", "nil?", "or", "@remote_name", ".", "empty?", "remotes", "=", "self", ".", "remote_names", "if", "remotes", ".", "empty?", "@remote_name", "=", "nil", "else", "@remote_name", "=", "remotes", "[", "0", "]", "raise", "\"remote name is not a String: #{@remote_name.inspect}\"", "unless", "@remote_name", ".", "is_a?", "String", "end", "end", "logger", ".", "debug", "{", "\"Using remote name of '#{@remote_name}'\"", "}", "end", "@remote_name", "end" ]
Returns the "remote name" to use. By convention the most common name is "origin". If the Git configuration "gitProcess.remoteName" is set, that will always be used. Otherwise this simple returns the first name it finds in the list of remotes. @return [String, nil] the remote name, or nil if there are none defined
[ "Returns", "the", "remote", "name", "to", "use", ".", "By", "convention", "the", "most", "common", "name", "is", "origin", "." ]
5853aa94258e724ce0dbc2f1e7407775e1630964
https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_remote.rb#L102-L117
24,255
jdigger/git-process
lib/git-process/git_remote.rb
GitProc.GitRemote.expanded_url
def expanded_url(server_name = 'origin', raw_url = nil, opts = {}) if raw_url.nil? raise ArgumentError.new('Need server_name') unless server_name conf_key = "remote.#{server_name}.url" url = config[conf_key] raise GitHubService::NoRemoteRepository.new("There is no value set for '#{conf_key}'") if url.nil? or url.empty? else raise GitHubService::NoRemoteRepository.new("There is no value set for '#{raw_url}'") if raw_url.nil? or raw_url.empty? url = raw_url end if /^\S+@/ =~ url url.sub(/^(\S+@\S+?):(.*)$/, "ssh://\\1/\\2") else uri = URI.parse(url) host = uri.host scheme = uri.scheme raise URI::InvalidURIError.new("Need a scheme in URI: '#{url}'") unless scheme if scheme == 'file' url elsif host.nil? # assume that the 'scheme' is the named configuration in ~/.ssh/config rv = GitRemote.hostname_and_user_from_ssh_config(scheme, opts[:ssh_config_file] ||= "#{ENV['HOME']}/.ssh/config") raise GitHubService::NoRemoteRepository.new("Could not determine a host from #{url}") if rv.nil? host = rv[0] user = rv[1] url.sub(/^\S+:(\S+)$/, "ssh://#{user}@#{host}/\\1") else url end end end
ruby
def expanded_url(server_name = 'origin', raw_url = nil, opts = {}) if raw_url.nil? raise ArgumentError.new('Need server_name') unless server_name conf_key = "remote.#{server_name}.url" url = config[conf_key] raise GitHubService::NoRemoteRepository.new("There is no value set for '#{conf_key}'") if url.nil? or url.empty? else raise GitHubService::NoRemoteRepository.new("There is no value set for '#{raw_url}'") if raw_url.nil? or raw_url.empty? url = raw_url end if /^\S+@/ =~ url url.sub(/^(\S+@\S+?):(.*)$/, "ssh://\\1/\\2") else uri = URI.parse(url) host = uri.host scheme = uri.scheme raise URI::InvalidURIError.new("Need a scheme in URI: '#{url}'") unless scheme if scheme == 'file' url elsif host.nil? # assume that the 'scheme' is the named configuration in ~/.ssh/config rv = GitRemote.hostname_and_user_from_ssh_config(scheme, opts[:ssh_config_file] ||= "#{ENV['HOME']}/.ssh/config") raise GitHubService::NoRemoteRepository.new("Could not determine a host from #{url}") if rv.nil? host = rv[0] user = rv[1] url.sub(/^\S+:(\S+)$/, "ssh://#{user}@#{host}/\\1") else url end end end
[ "def", "expanded_url", "(", "server_name", "=", "'origin'", ",", "raw_url", "=", "nil", ",", "opts", "=", "{", "}", ")", "if", "raw_url", ".", "nil?", "raise", "ArgumentError", ".", "new", "(", "'Need server_name'", ")", "unless", "server_name", "conf_key", "=", "\"remote.#{server_name}.url\"", "url", "=", "config", "[", "conf_key", "]", "raise", "GitHubService", "::", "NoRemoteRepository", ".", "new", "(", "\"There is no value set for '#{conf_key}'\"", ")", "if", "url", ".", "nil?", "or", "url", ".", "empty?", "else", "raise", "GitHubService", "::", "NoRemoteRepository", ".", "new", "(", "\"There is no value set for '#{raw_url}'\"", ")", "if", "raw_url", ".", "nil?", "or", "raw_url", ".", "empty?", "url", "=", "raw_url", "end", "if", "/", "\\S", "/", "=~", "url", "url", ".", "sub", "(", "/", "\\S", "\\S", "/", ",", "\"ssh://\\\\1/\\\\2\"", ")", "else", "uri", "=", "URI", ".", "parse", "(", "url", ")", "host", "=", "uri", ".", "host", "scheme", "=", "uri", ".", "scheme", "raise", "URI", "::", "InvalidURIError", ".", "new", "(", "\"Need a scheme in URI: '#{url}'\"", ")", "unless", "scheme", "if", "scheme", "==", "'file'", "url", "elsif", "host", ".", "nil?", "# assume that the 'scheme' is the named configuration in ~/.ssh/config", "rv", "=", "GitRemote", ".", "hostname_and_user_from_ssh_config", "(", "scheme", ",", "opts", "[", ":ssh_config_file", "]", "||=", "\"#{ENV['HOME']}/.ssh/config\"", ")", "raise", "GitHubService", "::", "NoRemoteRepository", ".", "new", "(", "\"Could not determine a host from #{url}\"", ")", "if", "rv", ".", "nil?", "host", "=", "rv", "[", "0", "]", "user", "=", "rv", "[", "1", "]", "url", ".", "sub", "(", "/", "\\S", "\\S", "/", ",", "\"ssh://#{user}@#{host}/\\\\1\"", ")", "else", "url", "end", "end", "end" ]
Expands the git configuration server name to a url. Takes into account further expanding an SSH uri that uses SSH aliasing in .ssh/config @param [String] server_name the git configuration server name; defaults to 'origin' @option opts [String] :ssh_config_file the SSH config file to use; defaults to ~/.ssh/config @return the fully expanded URL; never nil @raise [GitHubService::NoRemoteRepository] there is not a URL set for the server name @raise [URI::InvalidURIError] the retrieved URL does not have a schema @raise [GitHubService::NoRemoteRepository] if could not figure out a host for the retrieved URL @raise [::ArgumentError] if a server name is not provided @todo use the netrc gem
[ "Expands", "the", "git", "configuration", "server", "name", "to", "a", "url", "." ]
5853aa94258e724ce0dbc2f1e7407775e1630964
https://github.com/jdigger/git-process/blob/5853aa94258e724ce0dbc2f1e7407775e1630964/lib/git-process/git_remote.rb#L166-L203
24,256
altabyte/ebay_trader
lib/ebay_trader/request.rb
EbayTrader.Request.to_s
def to_s(indent = xml_tab_width) xml = '' if defined? Ox ox_doc = Ox.parse(xml_response) xml = Ox.dump(ox_doc, indent: indent) else rexml_doc = REXML::Document.new(xml_response) rexml_doc.write(xml, indent) end xml end
ruby
def to_s(indent = xml_tab_width) xml = '' if defined? Ox ox_doc = Ox.parse(xml_response) xml = Ox.dump(ox_doc, indent: indent) else rexml_doc = REXML::Document.new(xml_response) rexml_doc.write(xml, indent) end xml end
[ "def", "to_s", "(", "indent", "=", "xml_tab_width", ")", "xml", "=", "''", "if", "defined?", "Ox", "ox_doc", "=", "Ox", ".", "parse", "(", "xml_response", ")", "xml", "=", "Ox", ".", "dump", "(", "ox_doc", ",", "indent", ":", "indent", ")", "else", "rexml_doc", "=", "REXML", "::", "Document", ".", "new", "(", "xml_response", ")", "rexml_doc", ".", "write", "(", "xml", ",", "indent", ")", "end", "xml", "end" ]
Get a String representation of the response XML with indentation. @return [String] the response XML.
[ "Get", "a", "String", "representation", "of", "the", "response", "XML", "with", "indentation", "." ]
4442b683ea27f02fa0ef73f3f6357396fbe29b56
https://github.com/altabyte/ebay_trader/blob/4442b683ea27f02fa0ef73f3f6357396fbe29b56/lib/ebay_trader/request.rb#L239-L249
24,257
altabyte/ebay_trader
lib/ebay_trader/request.rb
EbayTrader.Request.submit
def submit raise EbayTraderError, 'Cannot post an eBay API request before application keys have been set' unless EbayTrader.configuration.has_keys_set? uri = EbayTrader.configuration.uri http = Net::HTTP.new(uri.host, uri.port) http.read_timeout = http_timeout if uri.port == 443 # http://www.rubyinside.com/nethttp-cheat-sheet-2940.html http.use_ssl = true verify = EbayTrader.configuration.ssl_verify if verify if verify.is_a?(String) pem = File.read(verify) http.cert = OpenSSL::X509::Certificate.new(pem) http.key = OpenSSL::PKey::RSA.new(pem) end http.verify_mode = OpenSSL::SSL::VERIFY_PEER else http.verify_mode = OpenSSL::SSL::VERIFY_NONE end end post = Net::HTTP::Post.new(uri.path, headers) post.body = xml_request begin response = http.start { |http| http.request(post) } rescue OpenSSL::SSL::SSLError => e # SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed raise EbayTraderError, e rescue Net::ReadTimeout raise EbayTraderTimeoutError, "Failed to complete #{call_name} in #{http_timeout} seconds" rescue Exception => e raise EbayTraderError, e ensure EbayTrader.configuration.counter_callback.call if EbayTrader.configuration.has_counter? end @http_response_code = response.code.to_i.freeze # If the call was successful it should have a response code starting with '2' # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html raise EbayTraderError, "HTTP Response Code: #{http_response_code}" unless http_response_code.between?(200, 299) if response['Content-Encoding'] == 'gzip' @xml_response = ActiveSupport::Gzip.decompress(response.body) else @xml_response = response.body end end
ruby
def submit raise EbayTraderError, 'Cannot post an eBay API request before application keys have been set' unless EbayTrader.configuration.has_keys_set? uri = EbayTrader.configuration.uri http = Net::HTTP.new(uri.host, uri.port) http.read_timeout = http_timeout if uri.port == 443 # http://www.rubyinside.com/nethttp-cheat-sheet-2940.html http.use_ssl = true verify = EbayTrader.configuration.ssl_verify if verify if verify.is_a?(String) pem = File.read(verify) http.cert = OpenSSL::X509::Certificate.new(pem) http.key = OpenSSL::PKey::RSA.new(pem) end http.verify_mode = OpenSSL::SSL::VERIFY_PEER else http.verify_mode = OpenSSL::SSL::VERIFY_NONE end end post = Net::HTTP::Post.new(uri.path, headers) post.body = xml_request begin response = http.start { |http| http.request(post) } rescue OpenSSL::SSL::SSLError => e # SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed raise EbayTraderError, e rescue Net::ReadTimeout raise EbayTraderTimeoutError, "Failed to complete #{call_name} in #{http_timeout} seconds" rescue Exception => e raise EbayTraderError, e ensure EbayTrader.configuration.counter_callback.call if EbayTrader.configuration.has_counter? end @http_response_code = response.code.to_i.freeze # If the call was successful it should have a response code starting with '2' # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html raise EbayTraderError, "HTTP Response Code: #{http_response_code}" unless http_response_code.between?(200, 299) if response['Content-Encoding'] == 'gzip' @xml_response = ActiveSupport::Gzip.decompress(response.body) else @xml_response = response.body end end
[ "def", "submit", "raise", "EbayTraderError", ",", "'Cannot post an eBay API request before application keys have been set'", "unless", "EbayTrader", ".", "configuration", ".", "has_keys_set?", "uri", "=", "EbayTrader", ".", "configuration", ".", "uri", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "http", ".", "read_timeout", "=", "http_timeout", "if", "uri", ".", "port", "==", "443", "# http://www.rubyinside.com/nethttp-cheat-sheet-2940.html", "http", ".", "use_ssl", "=", "true", "verify", "=", "EbayTrader", ".", "configuration", ".", "ssl_verify", "if", "verify", "if", "verify", ".", "is_a?", "(", "String", ")", "pem", "=", "File", ".", "read", "(", "verify", ")", "http", ".", "cert", "=", "OpenSSL", "::", "X509", "::", "Certificate", ".", "new", "(", "pem", ")", "http", ".", "key", "=", "OpenSSL", "::", "PKey", "::", "RSA", ".", "new", "(", "pem", ")", "end", "http", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_PEER", "else", "http", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "end", "end", "post", "=", "Net", "::", "HTTP", "::", "Post", ".", "new", "(", "uri", ".", "path", ",", "headers", ")", "post", ".", "body", "=", "xml_request", "begin", "response", "=", "http", ".", "start", "{", "|", "http", "|", "http", ".", "request", "(", "post", ")", "}", "rescue", "OpenSSL", "::", "SSL", "::", "SSLError", "=>", "e", "# SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed", "raise", "EbayTraderError", ",", "e", "rescue", "Net", "::", "ReadTimeout", "raise", "EbayTraderTimeoutError", ",", "\"Failed to complete #{call_name} in #{http_timeout} seconds\"", "rescue", "Exception", "=>", "e", "raise", "EbayTraderError", ",", "e", "ensure", "EbayTrader", ".", "configuration", ".", "counter_callback", ".", "call", "if", "EbayTrader", ".", "configuration", ".", "has_counter?", "end", "@http_response_code", "=", "response", ".", "code", ".", "to_i", ".", "freeze", "# If the call was successful it should have a response code starting with '2'", "# http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html", "raise", "EbayTraderError", ",", "\"HTTP Response Code: #{http_response_code}\"", "unless", "http_response_code", ".", "between?", "(", "200", ",", "299", ")", "if", "response", "[", "'Content-Encoding'", "]", "==", "'gzip'", "@xml_response", "=", "ActiveSupport", "::", "Gzip", ".", "decompress", "(", "response", ".", "body", ")", "else", "@xml_response", "=", "response", ".", "body", "end", "end" ]
Post the xml_request to eBay and record the xml_response.
[ "Post", "the", "xml_request", "to", "eBay", "and", "record", "the", "xml_response", "." ]
4442b683ea27f02fa0ef73f3f6357396fbe29b56
https://github.com/altabyte/ebay_trader/blob/4442b683ea27f02fa0ef73f3f6357396fbe29b56/lib/ebay_trader/request.rb#L262-L314
24,258
mileszim/webpurify-gem
lib/web_purify/methods/blacklist.rb
WebPurify.Blacklist.add_to_blacklist
def add_to_blacklist(word, deep_search=0) params = { :method => WebPurify::Constants.methods[:add_to_blacklist], :word => word, :ds => deep_search } parsed = WebPurify::Request.query(text_request_base, @query_base, params) return parsed[:success]=='1' end
ruby
def add_to_blacklist(word, deep_search=0) params = { :method => WebPurify::Constants.methods[:add_to_blacklist], :word => word, :ds => deep_search } parsed = WebPurify::Request.query(text_request_base, @query_base, params) return parsed[:success]=='1' end
[ "def", "add_to_blacklist", "(", "word", ",", "deep_search", "=", "0", ")", "params", "=", "{", ":method", "=>", "WebPurify", "::", "Constants", ".", "methods", "[", ":add_to_blacklist", "]", ",", ":word", "=>", "word", ",", ":ds", "=>", "deep_search", "}", "parsed", "=", "WebPurify", "::", "Request", ".", "query", "(", "text_request_base", ",", "@query_base", ",", "params", ")", "return", "parsed", "[", ":success", "]", "==", "'1'", "end" ]
Add a word to the blacklist @param word [String] The word to add to the blacklist @param deep_search [Integer] 1 if deep search on word, otherwise 0 for not (default 0) @return [Boolean] True if successful, false if not
[ "Add", "a", "word", "to", "the", "blacklist" ]
d594a0b483f1fe86ec711e37fd9187302f246faa
https://github.com/mileszim/webpurify-gem/blob/d594a0b483f1fe86ec711e37fd9187302f246faa/lib/web_purify/methods/blacklist.rb#L13-L21
24,259
mileszim/webpurify-gem
lib/web_purify/methods/blacklist.rb
WebPurify.Blacklist.remove_from_blacklist
def remove_from_blacklist(word) params = { :method => WebPurify::Constants.methods[:remove_from_blacklist], :word => word } parsed = WebPurify::Request.query(text_request_base, @query_base, params) return parsed[:success]=='1' end
ruby
def remove_from_blacklist(word) params = { :method => WebPurify::Constants.methods[:remove_from_blacklist], :word => word } parsed = WebPurify::Request.query(text_request_base, @query_base, params) return parsed[:success]=='1' end
[ "def", "remove_from_blacklist", "(", "word", ")", "params", "=", "{", ":method", "=>", "WebPurify", "::", "Constants", ".", "methods", "[", ":remove_from_blacklist", "]", ",", ":word", "=>", "word", "}", "parsed", "=", "WebPurify", "::", "Request", ".", "query", "(", "text_request_base", ",", "@query_base", ",", "params", ")", "return", "parsed", "[", ":success", "]", "==", "'1'", "end" ]
Remove a word from the blacklist @param word [String] The word to remove from the blacklist @return [Boolean] True if successful, false if not
[ "Remove", "a", "word", "from", "the", "blacklist" ]
d594a0b483f1fe86ec711e37fd9187302f246faa
https://github.com/mileszim/webpurify-gem/blob/d594a0b483f1fe86ec711e37fd9187302f246faa/lib/web_purify/methods/blacklist.rb#L28-L35
24,260
mileszim/webpurify-gem
lib/web_purify/methods/blacklist.rb
WebPurify.Blacklist.get_blacklist
def get_blacklist params = { :method => WebPurify::Constants.methods[:get_blacklist] } parsed = WebPurify::Request.query(text_request_base, @query_base, params) if parsed[:word] return [] << parsed[:word] else return [] end end
ruby
def get_blacklist params = { :method => WebPurify::Constants.methods[:get_blacklist] } parsed = WebPurify::Request.query(text_request_base, @query_base, params) if parsed[:word] return [] << parsed[:word] else return [] end end
[ "def", "get_blacklist", "params", "=", "{", ":method", "=>", "WebPurify", "::", "Constants", ".", "methods", "[", ":get_blacklist", "]", "}", "parsed", "=", "WebPurify", "::", "Request", ".", "query", "(", "text_request_base", ",", "@query_base", ",", "params", ")", "if", "parsed", "[", ":word", "]", "return", "[", "]", "<<", "parsed", "[", ":word", "]", "else", "return", "[", "]", "end", "end" ]
Get the blacklist @return [Array] An array of words in the blacklist
[ "Get", "the", "blacklist" ]
d594a0b483f1fe86ec711e37fd9187302f246faa
https://github.com/mileszim/webpurify-gem/blob/d594a0b483f1fe86ec711e37fd9187302f246faa/lib/web_purify/methods/blacklist.rb#L41-L51
24,261
stereocat/expectacle
lib/expectacle/thrower_base_io.rb
Expectacle.ThrowerBase.write_and_logging
def write_and_logging(message, command, secret = false) logging_message = secret ? message : message + command @logger.info logging_message if @writer.closed? @logger.error "Try to write #{command}, but writer closed" @commands.clear else @writer.puts command end end
ruby
def write_and_logging(message, command, secret = false) logging_message = secret ? message : message + command @logger.info logging_message if @writer.closed? @logger.error "Try to write #{command}, but writer closed" @commands.clear else @writer.puts command end end
[ "def", "write_and_logging", "(", "message", ",", "command", ",", "secret", "=", "false", ")", "logging_message", "=", "secret", "?", "message", ":", "message", "+", "command", "@logger", ".", "info", "logging_message", "if", "@writer", ".", "closed?", "@logger", ".", "error", "\"Try to write #{command}, but writer closed\"", "@commands", ".", "clear", "else", "@writer", ".", "puts", "command", "end", "end" ]
Send string to process and logging the string @param message [String] Message to logging @param command [String] Command to send @param secret [Boolearn] Choise to logging command
[ "Send", "string", "to", "process", "and", "logging", "the", "string" ]
a67faca42ba5f90068c69047bb6cf01c2bca1b74
https://github.com/stereocat/expectacle/blob/a67faca42ba5f90068c69047bb6cf01c2bca1b74/lib/expectacle/thrower_base_io.rb#L19-L28
24,262
stereocat/expectacle
lib/expectacle/thrower_base_io.rb
Expectacle.ThrowerBase.default_io_logger
def default_io_logger(logger_io, progname) logger = Logger.new(logger_io) logger.progname = progname logger.datetime_format = '%Y-%m-%d %H:%M:%D %Z' logger end
ruby
def default_io_logger(logger_io, progname) logger = Logger.new(logger_io) logger.progname = progname logger.datetime_format = '%Y-%m-%d %H:%M:%D %Z' logger end
[ "def", "default_io_logger", "(", "logger_io", ",", "progname", ")", "logger", "=", "Logger", ".", "new", "(", "logger_io", ")", "logger", ".", "progname", "=", "progname", "logger", ".", "datetime_format", "=", "'%Y-%m-%d %H:%M:%D %Z'", "logger", "end" ]
Setup default IO logger @return [Logger] logger
[ "Setup", "default", "IO", "logger" ]
a67faca42ba5f90068c69047bb6cf01c2bca1b74
https://github.com/stereocat/expectacle/blob/a67faca42ba5f90068c69047bb6cf01c2bca1b74/lib/expectacle/thrower_base_io.rb#L32-L37
24,263
stereocat/expectacle
lib/expectacle/thrower_base_io.rb
Expectacle.ThrowerBase.load_yaml_file
def load_yaml_file(file_type, file_name) YAML.load_file file_name rescue StandardError => error @logger.error "Cannot load #{file_type}: #{file_name}" raise error end
ruby
def load_yaml_file(file_type, file_name) YAML.load_file file_name rescue StandardError => error @logger.error "Cannot load #{file_type}: #{file_name}" raise error end
[ "def", "load_yaml_file", "(", "file_type", ",", "file_name", ")", "YAML", ".", "load_file", "file_name", "rescue", "StandardError", "=>", "error", "@logger", ".", "error", "\"Cannot load #{file_type}: #{file_name}\"", "raise", "error", "end" ]
YAML file loader @param file_type [String] File description @param file_name [String] File name to load @raise [Error] File load error
[ "YAML", "file", "loader" ]
a67faca42ba5f90068c69047bb6cf01c2bca1b74
https://github.com/stereocat/expectacle/blob/a67faca42ba5f90068c69047bb6cf01c2bca1b74/lib/expectacle/thrower_base_io.rb#L58-L63
24,264
keithrbennett/trick_bag
lib/trick_bag/validations/object_validations.rb
TrickBag.Validations.nil_instance_vars
def nil_instance_vars(object, vars) vars = Array(vars) vars.select { |var| object.instance_variable_get(var).nil? } end
ruby
def nil_instance_vars(object, vars) vars = Array(vars) vars.select { |var| object.instance_variable_get(var).nil? } end
[ "def", "nil_instance_vars", "(", "object", ",", "vars", ")", "vars", "=", "Array", "(", "vars", ")", "vars", ".", "select", "{", "|", "var", "|", "object", ".", "instance_variable_get", "(", "var", ")", ".", "nil?", "}", "end" ]
Returns an array containing each symbol in vars for which the corresponding instance variable in the specified object is nil.
[ "Returns", "an", "array", "containing", "each", "symbol", "in", "vars", "for", "which", "the", "corresponding", "instance", "variable", "in", "the", "specified", "object", "is", "nil", "." ]
a3886a45f32588aba751d13aeba42ae680bcd203
https://github.com/keithrbennett/trick_bag/blob/a3886a45f32588aba751d13aeba42ae680bcd203/lib/trick_bag/validations/object_validations.rb#L11-L14
24,265
keithrbennett/trick_bag
lib/trick_bag/validations/object_validations.rb
TrickBag.Validations.raise_on_nil_instance_vars
def raise_on_nil_instance_vars(object, vars) nil_vars = nil_instance_vars(object, vars) unless nil_vars.empty? raise ObjectValidationError.new("The following instance variables were nil: #{nil_vars.join(', ')}.") end end
ruby
def raise_on_nil_instance_vars(object, vars) nil_vars = nil_instance_vars(object, vars) unless nil_vars.empty? raise ObjectValidationError.new("The following instance variables were nil: #{nil_vars.join(', ')}.") end end
[ "def", "raise_on_nil_instance_vars", "(", "object", ",", "vars", ")", "nil_vars", "=", "nil_instance_vars", "(", "object", ",", "vars", ")", "unless", "nil_vars", ".", "empty?", "raise", "ObjectValidationError", ".", "new", "(", "\"The following instance variables were nil: #{nil_vars.join(', ')}.\"", ")", "end", "end" ]
For each symbol in vars, checks to see that the corresponding instance variable in the specified object is not nil. If any are nil, raises an error listing the nils.
[ "For", "each", "symbol", "in", "vars", "checks", "to", "see", "that", "the", "corresponding", "instance", "variable", "in", "the", "specified", "object", "is", "not", "nil", ".", "If", "any", "are", "nil", "raises", "an", "error", "listing", "the", "nils", "." ]
a3886a45f32588aba751d13aeba42ae680bcd203
https://github.com/keithrbennett/trick_bag/blob/a3886a45f32588aba751d13aeba42ae680bcd203/lib/trick_bag/validations/object_validations.rb#L19-L24
24,266
solutious/rudy
lib/rudy/cli/base.rb
Rudy::CLI.CommandBase.print_header
def print_header # Send The Huxtables the global values again because they could be # updated after initialization but before the command was executed Rudy::Huxtable.update_global @global li Rudy::CLI.generate_header(@@global, @@config) if @@global.print_header unless @@global.quiet if @@global.environment == "prod" msg = "YOU ARE PLAYING WITH PRODUCTION" li Rudy::Utils.banner(msg, :normal), $/ end end end
ruby
def print_header # Send The Huxtables the global values again because they could be # updated after initialization but before the command was executed Rudy::Huxtable.update_global @global li Rudy::CLI.generate_header(@@global, @@config) if @@global.print_header unless @@global.quiet if @@global.environment == "prod" msg = "YOU ARE PLAYING WITH PRODUCTION" li Rudy::Utils.banner(msg, :normal), $/ end end end
[ "def", "print_header", "# Send The Huxtables the global values again because they could be", "# updated after initialization but before the command was executed", "Rudy", "::", "Huxtable", ".", "update_global", "@global", "li", "Rudy", "::", "CLI", ".", "generate_header", "(", "@@global", ",", "@@config", ")", "if", "@@global", ".", "print_header", "unless", "@@global", ".", "quiet", "if", "@@global", ".", "environment", "==", "\"prod\"", "msg", "=", "\"YOU ARE PLAYING WITH PRODUCTION\"", "li", "Rudy", "::", "Utils", ".", "banner", "(", "msg", ",", ":normal", ")", ",", "$/", "end", "end", "end" ]
Print a default header to the screen for every command.
[ "Print", "a", "default", "header", "to", "the", "screen", "for", "every", "command", "." ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/cli/base.rb#L83-L97
24,267
solutious/rudy
lib/rudy/utils.rb
Rudy.Utils.bell
def bell(chimes=1, logger=nil) chimes ||= 0 return unless logger chimed = chimes.to_i logger.print "\a"*chimes if chimes > 0 && logger true # be like Rudy.bug() end
ruby
def bell(chimes=1, logger=nil) chimes ||= 0 return unless logger chimed = chimes.to_i logger.print "\a"*chimes if chimes > 0 && logger true # be like Rudy.bug() end
[ "def", "bell", "(", "chimes", "=", "1", ",", "logger", "=", "nil", ")", "chimes", "||=", "0", "return", "unless", "logger", "chimed", "=", "chimes", ".", "to_i", "logger", ".", "print", "\"\\a\"", "*", "chimes", "if", "chimes", ">", "0", "&&", "logger", "true", "# be like Rudy.bug()", "end" ]
Make a terminal bell chime
[ "Make", "a", "terminal", "bell", "chime" ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/utils.rb#L98-L104
24,268
solutious/rudy
lib/rudy/utils.rb
Rudy.Utils.bug
def bug(bugid, logger=STDERR) logger.puts "You have found a bug! If you want, you can email".color(:red) logger.puts '[email protected]'.color(:red).bright << " about it. It's bug ##{bugid}.".color(:red) logger.puts "Continuing...".color(:red) true # so we can string it together like: bug('1') && next if ... end
ruby
def bug(bugid, logger=STDERR) logger.puts "You have found a bug! If you want, you can email".color(:red) logger.puts '[email protected]'.color(:red).bright << " about it. It's bug ##{bugid}.".color(:red) logger.puts "Continuing...".color(:red) true # so we can string it together like: bug('1') && next if ... end
[ "def", "bug", "(", "bugid", ",", "logger", "=", "STDERR", ")", "logger", ".", "puts", "\"You have found a bug! If you want, you can email\"", ".", "color", "(", ":red", ")", "logger", ".", "puts", "'[email protected]'", ".", "color", "(", ":red", ")", ".", "bright", "<<", "\" about it. It's bug ##{bugid}.\"", ".", "color", "(", ":red", ")", "logger", ".", "puts", "\"Continuing...\"", ".", "color", "(", ":red", ")", "true", "# so we can string it together like: bug('1') && next if ...", "end" ]
Have you seen that episode of The Cosby Show where Dizzy Gillespie... ah nevermind.
[ "Have", "you", "seen", "that", "episode", "of", "The", "Cosby", "Show", "where", "Dizzy", "Gillespie", "...", "ah", "nevermind", "." ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/utils.rb#L107-L112
24,269
solutious/rudy
lib/rudy/utils.rb
Rudy.Utils.known_type?
def known_type?(key) return false unless key key &&= key.to_s.to_sym Rudy::ID_MAP.has_key?(key) end
ruby
def known_type?(key) return false unless key key &&= key.to_s.to_sym Rudy::ID_MAP.has_key?(key) end
[ "def", "known_type?", "(", "key", ")", "return", "false", "unless", "key", "key", "&&=", "key", ".", "to_s", ".", "to_sym", "Rudy", "::", "ID_MAP", ".", "has_key?", "(", "key", ")", "end" ]
Is the given +key+ a known type of object?
[ "Is", "the", "given", "+", "key", "+", "a", "known", "type", "of", "object?" ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/utils.rb#L133-L137
24,270
solutious/rudy
lib/rudy/utils.rb
Rudy.Utils.identifier
def identifier(key) key &&= key.to_sym return unless Rudy::ID_MAP.has_key?(key) Rudy::ID_MAP[key] end
ruby
def identifier(key) key &&= key.to_sym return unless Rudy::ID_MAP.has_key?(key) Rudy::ID_MAP[key] end
[ "def", "identifier", "(", "key", ")", "key", "&&=", "key", ".", "to_sym", "return", "unless", "Rudy", "::", "ID_MAP", ".", "has_key?", "(", "key", ")", "Rudy", "::", "ID_MAP", "[", "key", "]", "end" ]
Returns the string identifier associated to this +key+
[ "Returns", "the", "string", "identifier", "associated", "to", "this", "+", "key", "+" ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/utils.rb#L140-L144
24,271
solutious/rudy
lib/rudy/utils.rb
Rudy.Utils.capture
def capture(stream) #raise "We can only capture STDOUT or STDERR" unless stream == :stdout || stream == :stderr begin stream = stream.to_s eval "$#{stream} = StringIO.new" yield result = eval("$#{stream}").read ensure eval("$#{stream} = #{stream.upcase}") end result end
ruby
def capture(stream) #raise "We can only capture STDOUT or STDERR" unless stream == :stdout || stream == :stderr begin stream = stream.to_s eval "$#{stream} = StringIO.new" yield result = eval("$#{stream}").read ensure eval("$#{stream} = #{stream.upcase}") end result end
[ "def", "capture", "(", "stream", ")", "#raise \"We can only capture STDOUT or STDERR\" unless stream == :stdout || stream == :stderr", "begin", "stream", "=", "stream", ".", "to_s", "eval", "\"$#{stream} = StringIO.new\"", "yield", "result", "=", "eval", "(", "\"$#{stream}\"", ")", ".", "read", "ensure", "eval", "(", "\"$#{stream} = #{stream.upcase}\"", ")", "end", "result", "end" ]
Capture STDOUT or STDERR to prevent it from being printed. capture(:stdout) do ... end
[ "Capture", "STDOUT", "or", "STDERR", "to", "prevent", "it", "from", "being", "printed", "." ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/utils.rb#L236-L248
24,272
solutious/rudy
lib/rudy/utils.rb
Rudy.Utils.write_to_file
def write_to_file(filename, content, mode, chmod=600) mode = (mode == :append) ? 'a' : 'w' f = File.open(filename,mode) f.puts content f.close return unless Rudy.sysinfo.os == :unix raise "Provided chmod is not a Fixnum (#{chmod})" unless chmod.is_a?(Fixnum) File.chmod(chmod, filename) end
ruby
def write_to_file(filename, content, mode, chmod=600) mode = (mode == :append) ? 'a' : 'w' f = File.open(filename,mode) f.puts content f.close return unless Rudy.sysinfo.os == :unix raise "Provided chmod is not a Fixnum (#{chmod})" unless chmod.is_a?(Fixnum) File.chmod(chmod, filename) end
[ "def", "write_to_file", "(", "filename", ",", "content", ",", "mode", ",", "chmod", "=", "600", ")", "mode", "=", "(", "mode", "==", ":append", ")", "?", "'a'", ":", "'w'", "f", "=", "File", ".", "open", "(", "filename", ",", "mode", ")", "f", ".", "puts", "content", "f", ".", "close", "return", "unless", "Rudy", ".", "sysinfo", ".", "os", "==", ":unix", "raise", "\"Provided chmod is not a Fixnum (#{chmod})\"", "unless", "chmod", ".", "is_a?", "(", "Fixnum", ")", "File", ".", "chmod", "(", "chmod", ",", "filename", ")", "end" ]
A basic file writer
[ "A", "basic", "file", "writer" ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/utils.rb#L251-L259
24,273
solutious/rudy
lib/rudy/metadata.rb
Rudy.Metadata.refresh!
def refresh! raise UnknownObject, self.name unless self.exists? h = Rudy::Metadata.get self.name return false if h.nil? || h.empty? obj = self.from_hash(h) obj.postprocess obj end
ruby
def refresh! raise UnknownObject, self.name unless self.exists? h = Rudy::Metadata.get self.name return false if h.nil? || h.empty? obj = self.from_hash(h) obj.postprocess obj end
[ "def", "refresh!", "raise", "UnknownObject", ",", "self", ".", "name", "unless", "self", ".", "exists?", "h", "=", "Rudy", "::", "Metadata", ".", "get", "self", ".", "name", "return", "false", "if", "h", ".", "nil?", "||", "h", ".", "empty?", "obj", "=", "self", ".", "from_hash", "(", "h", ")", "obj", ".", "postprocess", "obj", "end" ]
Refresh the metadata object from SimpleDB. If the record doesn't exist it will raise an UnknownObject error
[ "Refresh", "the", "metadata", "object", "from", "SimpleDB", ".", "If", "the", "record", "doesn", "t", "exist", "it", "will", "raise", "an", "UnknownObject", "error" ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/metadata.rb#L220-L227
24,274
keithrbennett/trick_bag
lib/trick_bag/operators/operators.rb
TrickBag.Operators.multi_eq
def multi_eq(*values) # If there is only 1 arg, it must be an array of at least 2 elements. values = values.first if values.first.is_a?(Array) && values.size == 1 raise ArgumentError.new("Must be called with at least 2 parameters; was: #{values.inspect}") if values.size < 2 values[1..-1].all? { |value| value == values.first } end
ruby
def multi_eq(*values) # If there is only 1 arg, it must be an array of at least 2 elements. values = values.first if values.first.is_a?(Array) && values.size == 1 raise ArgumentError.new("Must be called with at least 2 parameters; was: #{values.inspect}") if values.size < 2 values[1..-1].all? { |value| value == values.first } end
[ "def", "multi_eq", "(", "*", "values", ")", "# If there is only 1 arg, it must be an array of at least 2 elements.", "values", "=", "values", ".", "first", "if", "values", ".", "first", ".", "is_a?", "(", "Array", ")", "&&", "values", ".", "size", "==", "1", "raise", "ArgumentError", ".", "new", "(", "\"Must be called with at least 2 parameters; was: #{values.inspect}\"", ")", "if", "values", ".", "size", "<", "2", "values", "[", "1", "..", "-", "1", "]", ".", "all?", "{", "|", "value", "|", "value", "==", "values", ".", "first", "}", "end" ]
Returns whether or not all passed values are equal Ex: multi_eq(1, 1, 1, 2) => false; multi_eq(1, 1, 1, 1) => true
[ "Returns", "whether", "or", "not", "all", "passed", "values", "are", "equal" ]
a3886a45f32588aba751d13aeba42ae680bcd203
https://github.com/keithrbennett/trick_bag/blob/a3886a45f32588aba751d13aeba42ae680bcd203/lib/trick_bag/operators/operators.rb#L9-L14
24,275
solutious/rudy
lib/rudy/machines.rb
Rudy.Machines.exists?
def exists?(pos=nil) machines = pos.nil? ? list : get(pos) !machines.nil? end
ruby
def exists?(pos=nil) machines = pos.nil? ? list : get(pos) !machines.nil? end
[ "def", "exists?", "(", "pos", "=", "nil", ")", "machines", "=", "pos", ".", "nil?", "?", "list", ":", "get", "(", "pos", ")", "!", "machines", ".", "nil?", "end" ]
Returns true if any machine metadata exists for this group
[ "Returns", "true", "if", "any", "machine", "metadata", "exists", "for", "this", "group" ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/machines.rb#L34-L37
24,276
solutious/rudy
lib/rudy/machines.rb
Rudy.Machines.running?
def running?(pos=nil) group = pos.nil? ? list : [get(pos)].compact return false if group.nil? || group.empty? group.collect! { |m| m.instance_running? } !group.member?(false) end
ruby
def running?(pos=nil) group = pos.nil? ? list : [get(pos)].compact return false if group.nil? || group.empty? group.collect! { |m| m.instance_running? } !group.member?(false) end
[ "def", "running?", "(", "pos", "=", "nil", ")", "group", "=", "pos", ".", "nil?", "?", "list", ":", "[", "get", "(", "pos", ")", "]", ".", "compact", "return", "false", "if", "group", ".", "nil?", "||", "group", ".", "empty?", "group", ".", "collect!", "{", "|", "m", "|", "m", ".", "instance_running?", "}", "!", "group", ".", "member?", "(", "false", ")", "end" ]
Returns true if all machines in the group are running instances
[ "Returns", "true", "if", "all", "machines", "in", "the", "group", "are", "running", "instances" ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/machines.rb#L40-L45
24,277
cryptape/ruby-devp2p
lib/devp2p/rlpx_session.rb
DEVp2p.RLPxSession.create_auth_message
def create_auth_message(remote_pubkey, ephemeral_privkey=nil, nonce=nil) raise RLPxSessionError, 'must be initiator' unless initiator? raise InvalidKeyError, 'invalid remote pubkey' unless Crypto::ECCx.valid_key?(remote_pubkey) @remote_pubkey = remote_pubkey token = @ecc.get_ecdh_key remote_pubkey flag = 0x0 @initiator_nonce = nonce || Crypto.keccak256(Utils.int_to_big_endian(SecureRandom.random_number(TT256))) raise RLPxSessionError, 'invalid nonce length' unless @initiator_nonce.size == 32 token_xor_nonce = Utils.sxor token, @initiator_nonce raise RLPxSessionError, 'invalid token xor nonce length' unless token_xor_nonce.size == 32 ephemeral_pubkey = @ephemeral_ecc.raw_pubkey raise InvalidKeyError, 'invalid ephemeral pubkey' unless ephemeral_pubkey.size == 512 / 8 && Crypto::ECCx.valid_key?(ephemeral_pubkey) sig = @ephemeral_ecc.sign token_xor_nonce raise RLPxSessionError, 'invalid signature' unless sig.size == 65 auth_message = "#{sig}#{Crypto.keccak256(ephemeral_pubkey)}#{@ecc.raw_pubkey}#{@initiator_nonce}#{flag.chr}" raise RLPxSessionError, 'invalid auth message length' unless auth_message.size == 194 auth_message end
ruby
def create_auth_message(remote_pubkey, ephemeral_privkey=nil, nonce=nil) raise RLPxSessionError, 'must be initiator' unless initiator? raise InvalidKeyError, 'invalid remote pubkey' unless Crypto::ECCx.valid_key?(remote_pubkey) @remote_pubkey = remote_pubkey token = @ecc.get_ecdh_key remote_pubkey flag = 0x0 @initiator_nonce = nonce || Crypto.keccak256(Utils.int_to_big_endian(SecureRandom.random_number(TT256))) raise RLPxSessionError, 'invalid nonce length' unless @initiator_nonce.size == 32 token_xor_nonce = Utils.sxor token, @initiator_nonce raise RLPxSessionError, 'invalid token xor nonce length' unless token_xor_nonce.size == 32 ephemeral_pubkey = @ephemeral_ecc.raw_pubkey raise InvalidKeyError, 'invalid ephemeral pubkey' unless ephemeral_pubkey.size == 512 / 8 && Crypto::ECCx.valid_key?(ephemeral_pubkey) sig = @ephemeral_ecc.sign token_xor_nonce raise RLPxSessionError, 'invalid signature' unless sig.size == 65 auth_message = "#{sig}#{Crypto.keccak256(ephemeral_pubkey)}#{@ecc.raw_pubkey}#{@initiator_nonce}#{flag.chr}" raise RLPxSessionError, 'invalid auth message length' unless auth_message.size == 194 auth_message end
[ "def", "create_auth_message", "(", "remote_pubkey", ",", "ephemeral_privkey", "=", "nil", ",", "nonce", "=", "nil", ")", "raise", "RLPxSessionError", ",", "'must be initiator'", "unless", "initiator?", "raise", "InvalidKeyError", ",", "'invalid remote pubkey'", "unless", "Crypto", "::", "ECCx", ".", "valid_key?", "(", "remote_pubkey", ")", "@remote_pubkey", "=", "remote_pubkey", "token", "=", "@ecc", ".", "get_ecdh_key", "remote_pubkey", "flag", "=", "0x0", "@initiator_nonce", "=", "nonce", "||", "Crypto", ".", "keccak256", "(", "Utils", ".", "int_to_big_endian", "(", "SecureRandom", ".", "random_number", "(", "TT256", ")", ")", ")", "raise", "RLPxSessionError", ",", "'invalid nonce length'", "unless", "@initiator_nonce", ".", "size", "==", "32", "token_xor_nonce", "=", "Utils", ".", "sxor", "token", ",", "@initiator_nonce", "raise", "RLPxSessionError", ",", "'invalid token xor nonce length'", "unless", "token_xor_nonce", ".", "size", "==", "32", "ephemeral_pubkey", "=", "@ephemeral_ecc", ".", "raw_pubkey", "raise", "InvalidKeyError", ",", "'invalid ephemeral pubkey'", "unless", "ephemeral_pubkey", ".", "size", "==", "512", "/", "8", "&&", "Crypto", "::", "ECCx", ".", "valid_key?", "(", "ephemeral_pubkey", ")", "sig", "=", "@ephemeral_ecc", ".", "sign", "token_xor_nonce", "raise", "RLPxSessionError", ",", "'invalid signature'", "unless", "sig", ".", "size", "==", "65", "auth_message", "=", "\"#{sig}#{Crypto.keccak256(ephemeral_pubkey)}#{@ecc.raw_pubkey}#{@initiator_nonce}#{flag.chr}\"", "raise", "RLPxSessionError", ",", "'invalid auth message length'", "unless", "auth_message", ".", "size", "==", "194", "auth_message", "end" ]
Handshake Auth Message Handling 1. initiator generates ecdhe-random and nonce and creates auth 2. initiator connects to remote and sends auth New: E(remote-pubk, S(ephemeral-privk, ecdh-shared-secret ^ nonce) || H(ephemeral-pubk) || pubk || nonce || 0x0 ) Known: E(remote-pubk, S(ephemeral-privk, token ^ nonce) || H(ephemeral-pubk) || pubk || nonce || 0x1 )
[ "Handshake", "Auth", "Message", "Handling" ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/rlpx_session.rb#L128-L153
24,278
cryptape/ruby-devp2p
lib/devp2p/rlpx_session.rb
DEVp2p.RLPxSession.create_auth_ack_message
def create_auth_ack_message(ephemeral_pubkey=nil, nonce=nil, version=SUPPORTED_RLPX_VERSION, eip8=false) raise RLPxSessionError, 'must not be initiator' if initiator? ephemeral_pubkey = ephemeral_pubkey || @ephemeral_ecc.raw_pubkey @responder_nonce = nonce || Crypto.keccak256(Utils.int_to_big_endian(SecureRandom.random_number(TT256))) if eip8 || @got_eip8_auth msg = create_eip8_auth_ack_message ephemeral_pubkey, @responder_nonce, version raise RLPxSessionError, 'invalid msg size' unless msg.size > 97 else msg = "#{ephemeral_pubkey}#{@responder_nonce}\x00" raise RLPxSessionError, 'invalid msg size' unless msg.size == 97 end msg end
ruby
def create_auth_ack_message(ephemeral_pubkey=nil, nonce=nil, version=SUPPORTED_RLPX_VERSION, eip8=false) raise RLPxSessionError, 'must not be initiator' if initiator? ephemeral_pubkey = ephemeral_pubkey || @ephemeral_ecc.raw_pubkey @responder_nonce = nonce || Crypto.keccak256(Utils.int_to_big_endian(SecureRandom.random_number(TT256))) if eip8 || @got_eip8_auth msg = create_eip8_auth_ack_message ephemeral_pubkey, @responder_nonce, version raise RLPxSessionError, 'invalid msg size' unless msg.size > 97 else msg = "#{ephemeral_pubkey}#{@responder_nonce}\x00" raise RLPxSessionError, 'invalid msg size' unless msg.size == 97 end msg end
[ "def", "create_auth_ack_message", "(", "ephemeral_pubkey", "=", "nil", ",", "nonce", "=", "nil", ",", "version", "=", "SUPPORTED_RLPX_VERSION", ",", "eip8", "=", "false", ")", "raise", "RLPxSessionError", ",", "'must not be initiator'", "if", "initiator?", "ephemeral_pubkey", "=", "ephemeral_pubkey", "||", "@ephemeral_ecc", ".", "raw_pubkey", "@responder_nonce", "=", "nonce", "||", "Crypto", ".", "keccak256", "(", "Utils", ".", "int_to_big_endian", "(", "SecureRandom", ".", "random_number", "(", "TT256", ")", ")", ")", "if", "eip8", "||", "@got_eip8_auth", "msg", "=", "create_eip8_auth_ack_message", "ephemeral_pubkey", ",", "@responder_nonce", ",", "version", "raise", "RLPxSessionError", ",", "'invalid msg size'", "unless", "msg", ".", "size", ">", "97", "else", "msg", "=", "\"#{ephemeral_pubkey}#{@responder_nonce}\\x00\"", "raise", "RLPxSessionError", ",", "'invalid msg size'", "unless", "msg", ".", "size", "==", "97", "end", "msg", "end" ]
Handshake ack message handling authRecipient = E(remote-pubk, remote-ephemeral-pubk || nonce || 0x1) // token found authRecipient = E(remote-pubk, remote-ephemeral-pubk || nonce || 0x0) // token not found nonce, ephemeral_pubkey, version are local
[ "Handshake", "ack", "message", "handling" ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/rlpx_session.rb#L208-L223
24,279
cryptape/ruby-devp2p
lib/devp2p/rlpx_session.rb
DEVp2p.RLPxSession.setup_cipher
def setup_cipher raise RLPxSessionError, 'missing responder nonce' unless @responder_nonce raise RLPxSessionError, 'missing initiator_nonce' unless @initiator_nonce raise RLPxSessionError, 'missing auth_init' unless @auth_init raise RLPxSessionError, 'missing auth_ack' unless @auth_ack raise RLPxSessionError, 'missing remote ephemeral pubkey' unless @remote_ephemeral_pubkey raise InvalidKeyError, 'invalid remote ephemeral pubkey' unless Crypto::ECCx.valid_key?(@remote_ephemeral_pubkey) # derive base secrets from ephemeral key agreement # ecdhe-shared-secret = ecdh.agree(ephemeral-privkey, remote-ephemeral-pubk) @ecdhe_shared_secret = @ephemeral_ecc.get_ecdh_key(@remote_ephemeral_pubkey) @shared_secret = Crypto.keccak256("#{@ecdhe_shared_secret}#{Crypto.keccak256(@responder_nonce + @initiator_nonce)}") @token = Crypto.keccak256 @shared_secret @aes_secret = Crypto.keccak256 "#{@ecdhe_shared_secret}#{@shared_secret}" @mac_secret = Crypto.keccak256 "#{@ecdhe_shared_secret}#{@aes_secret}" mac1 = keccak256 "#{Utils.sxor(@mac_secret, @responder_nonce)}#{@auth_init}" mac2 = keccak256 "#{Utils.sxor(@mac_secret, @initiator_nonce)}#{@auth_ack}" if initiator? @egress_mac, @ingress_mac = mac1, mac2 else @egress_mac, @ingress_mac = mac2, mac1 end iv = "\x00" * 16 @aes_enc = OpenSSL::Cipher.new(ENC_CIPHER).tap do |c| c.encrypt c.iv = iv c.key = @aes_secret end @aes_dec = OpenSSL::Cipher.new(ENC_CIPHER).tap do |c| c.decrypt c.iv = iv c.key = @aes_secret end @mac_enc = OpenSSL::Cipher.new(MAC_CIPHER).tap do |c| c.encrypt c.key = @mac_secret end @ready = true end
ruby
def setup_cipher raise RLPxSessionError, 'missing responder nonce' unless @responder_nonce raise RLPxSessionError, 'missing initiator_nonce' unless @initiator_nonce raise RLPxSessionError, 'missing auth_init' unless @auth_init raise RLPxSessionError, 'missing auth_ack' unless @auth_ack raise RLPxSessionError, 'missing remote ephemeral pubkey' unless @remote_ephemeral_pubkey raise InvalidKeyError, 'invalid remote ephemeral pubkey' unless Crypto::ECCx.valid_key?(@remote_ephemeral_pubkey) # derive base secrets from ephemeral key agreement # ecdhe-shared-secret = ecdh.agree(ephemeral-privkey, remote-ephemeral-pubk) @ecdhe_shared_secret = @ephemeral_ecc.get_ecdh_key(@remote_ephemeral_pubkey) @shared_secret = Crypto.keccak256("#{@ecdhe_shared_secret}#{Crypto.keccak256(@responder_nonce + @initiator_nonce)}") @token = Crypto.keccak256 @shared_secret @aes_secret = Crypto.keccak256 "#{@ecdhe_shared_secret}#{@shared_secret}" @mac_secret = Crypto.keccak256 "#{@ecdhe_shared_secret}#{@aes_secret}" mac1 = keccak256 "#{Utils.sxor(@mac_secret, @responder_nonce)}#{@auth_init}" mac2 = keccak256 "#{Utils.sxor(@mac_secret, @initiator_nonce)}#{@auth_ack}" if initiator? @egress_mac, @ingress_mac = mac1, mac2 else @egress_mac, @ingress_mac = mac2, mac1 end iv = "\x00" * 16 @aes_enc = OpenSSL::Cipher.new(ENC_CIPHER).tap do |c| c.encrypt c.iv = iv c.key = @aes_secret end @aes_dec = OpenSSL::Cipher.new(ENC_CIPHER).tap do |c| c.decrypt c.iv = iv c.key = @aes_secret end @mac_enc = OpenSSL::Cipher.new(MAC_CIPHER).tap do |c| c.encrypt c.key = @mac_secret end @ready = true end
[ "def", "setup_cipher", "raise", "RLPxSessionError", ",", "'missing responder nonce'", "unless", "@responder_nonce", "raise", "RLPxSessionError", ",", "'missing initiator_nonce'", "unless", "@initiator_nonce", "raise", "RLPxSessionError", ",", "'missing auth_init'", "unless", "@auth_init", "raise", "RLPxSessionError", ",", "'missing auth_ack'", "unless", "@auth_ack", "raise", "RLPxSessionError", ",", "'missing remote ephemeral pubkey'", "unless", "@remote_ephemeral_pubkey", "raise", "InvalidKeyError", ",", "'invalid remote ephemeral pubkey'", "unless", "Crypto", "::", "ECCx", ".", "valid_key?", "(", "@remote_ephemeral_pubkey", ")", "# derive base secrets from ephemeral key agreement", "# ecdhe-shared-secret = ecdh.agree(ephemeral-privkey, remote-ephemeral-pubk)", "@ecdhe_shared_secret", "=", "@ephemeral_ecc", ".", "get_ecdh_key", "(", "@remote_ephemeral_pubkey", ")", "@shared_secret", "=", "Crypto", ".", "keccak256", "(", "\"#{@ecdhe_shared_secret}#{Crypto.keccak256(@responder_nonce + @initiator_nonce)}\"", ")", "@token", "=", "Crypto", ".", "keccak256", "@shared_secret", "@aes_secret", "=", "Crypto", ".", "keccak256", "\"#{@ecdhe_shared_secret}#{@shared_secret}\"", "@mac_secret", "=", "Crypto", ".", "keccak256", "\"#{@ecdhe_shared_secret}#{@aes_secret}\"", "mac1", "=", "keccak256", "\"#{Utils.sxor(@mac_secret, @responder_nonce)}#{@auth_init}\"", "mac2", "=", "keccak256", "\"#{Utils.sxor(@mac_secret, @initiator_nonce)}#{@auth_ack}\"", "if", "initiator?", "@egress_mac", ",", "@ingress_mac", "=", "mac1", ",", "mac2", "else", "@egress_mac", ",", "@ingress_mac", "=", "mac2", ",", "mac1", "end", "iv", "=", "\"\\x00\"", "*", "16", "@aes_enc", "=", "OpenSSL", "::", "Cipher", ".", "new", "(", "ENC_CIPHER", ")", ".", "tap", "do", "|", "c", "|", "c", ".", "encrypt", "c", ".", "iv", "=", "iv", "c", ".", "key", "=", "@aes_secret", "end", "@aes_dec", "=", "OpenSSL", "::", "Cipher", ".", "new", "(", "ENC_CIPHER", ")", ".", "tap", "do", "|", "c", "|", "c", ".", "decrypt", "c", ".", "iv", "=", "iv", "c", ".", "key", "=", "@aes_secret", "end", "@mac_enc", "=", "OpenSSL", "::", "Cipher", ".", "new", "(", "MAC_CIPHER", ")", ".", "tap", "do", "|", "c", "|", "c", ".", "encrypt", "c", ".", "key", "=", "@mac_secret", "end", "@ready", "=", "true", "end" ]
Handshake Key Derivation
[ "Handshake", "Key", "Derivation" ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/rlpx_session.rb#L273-L315
24,280
cryptape/ruby-devp2p
lib/devp2p/rlpx_session.rb
DEVp2p.RLPxSession.decode_auth_plain
def decode_auth_plain(ciphertext) message = begin @ecc.ecies_decrypt ciphertext[0,307] rescue raise AuthenticationError, $! end raise RLPxSessionError, 'invalid message length' unless message.size == 194 sig = message[0,65] pubkey = message[65+32,64] raise InvalidKeyError, 'invalid initiator pubkey' unless Crypto::ECCx.valid_key?(pubkey) nonce = message[65+32+64,32] flag = message[(65+32+64+32)..-1].ord raise RLPxSessionError, 'invalid flag' unless flag == 0 [307, sig, pubkey, nonce, 4] end
ruby
def decode_auth_plain(ciphertext) message = begin @ecc.ecies_decrypt ciphertext[0,307] rescue raise AuthenticationError, $! end raise RLPxSessionError, 'invalid message length' unless message.size == 194 sig = message[0,65] pubkey = message[65+32,64] raise InvalidKeyError, 'invalid initiator pubkey' unless Crypto::ECCx.valid_key?(pubkey) nonce = message[65+32+64,32] flag = message[(65+32+64+32)..-1].ord raise RLPxSessionError, 'invalid flag' unless flag == 0 [307, sig, pubkey, nonce, 4] end
[ "def", "decode_auth_plain", "(", "ciphertext", ")", "message", "=", "begin", "@ecc", ".", "ecies_decrypt", "ciphertext", "[", "0", ",", "307", "]", "rescue", "raise", "AuthenticationError", ",", "$!", "end", "raise", "RLPxSessionError", ",", "'invalid message length'", "unless", "message", ".", "size", "==", "194", "sig", "=", "message", "[", "0", ",", "65", "]", "pubkey", "=", "message", "[", "65", "+", "32", ",", "64", "]", "raise", "InvalidKeyError", ",", "'invalid initiator pubkey'", "unless", "Crypto", "::", "ECCx", ".", "valid_key?", "(", "pubkey", ")", "nonce", "=", "message", "[", "65", "+", "32", "+", "64", ",", "32", "]", "flag", "=", "message", "[", "(", "65", "+", "32", "+", "64", "+", "32", ")", "..", "-", "1", "]", ".", "ord", "raise", "RLPxSessionError", ",", "'invalid flag'", "unless", "flag", "==", "0", "[", "307", ",", "sig", ",", "pubkey", ",", "nonce", ",", "4", "]", "end" ]
decode legacy pre-EIP-8 auth message format
[ "decode", "legacy", "pre", "-", "EIP", "-", "8", "auth", "message", "format" ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/rlpx_session.rb#L358-L375
24,281
cryptape/ruby-devp2p
lib/devp2p/rlpx_session.rb
DEVp2p.RLPxSession.decode_auth_eip8
def decode_auth_eip8(ciphertext) size = ciphertext[0,2].unpack('S>').first + 2 raise RLPxSessionError, 'invalid ciphertext size' unless ciphertext.size >= size message = begin @ecc.ecies_decrypt ciphertext[2...size], ciphertext[0,2] rescue raise AuthenticationError, $! end values = RLP.decode message, sedes: eip8_auth_sedes, strict: false raise RLPxSessionError, 'invalid values size' unless values.size >= 4 [size] + values[0,4] end
ruby
def decode_auth_eip8(ciphertext) size = ciphertext[0,2].unpack('S>').first + 2 raise RLPxSessionError, 'invalid ciphertext size' unless ciphertext.size >= size message = begin @ecc.ecies_decrypt ciphertext[2...size], ciphertext[0,2] rescue raise AuthenticationError, $! end values = RLP.decode message, sedes: eip8_auth_sedes, strict: false raise RLPxSessionError, 'invalid values size' unless values.size >= 4 [size] + values[0,4] end
[ "def", "decode_auth_eip8", "(", "ciphertext", ")", "size", "=", "ciphertext", "[", "0", ",", "2", "]", ".", "unpack", "(", "'S>'", ")", ".", "first", "+", "2", "raise", "RLPxSessionError", ",", "'invalid ciphertext size'", "unless", "ciphertext", ".", "size", ">=", "size", "message", "=", "begin", "@ecc", ".", "ecies_decrypt", "ciphertext", "[", "2", "...", "size", "]", ",", "ciphertext", "[", "0", ",", "2", "]", "rescue", "raise", "AuthenticationError", ",", "$!", "end", "values", "=", "RLP", ".", "decode", "message", ",", "sedes", ":", "eip8_auth_sedes", ",", "strict", ":", "false", "raise", "RLPxSessionError", ",", "'invalid values size'", "unless", "values", ".", "size", ">=", "4", "[", "size", "]", "+", "values", "[", "0", ",", "4", "]", "end" ]
decode EIP-8 auth message format
[ "decode", "EIP", "-", "8", "auth", "message", "format" ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/rlpx_session.rb#L380-L394
24,282
cryptape/ruby-devp2p
lib/devp2p/rlpx_session.rb
DEVp2p.RLPxSession.decode_ack_plain
def decode_ack_plain(ciphertext) message = begin @ecc.ecies_decrypt ciphertext[0,210] rescue raise AuthenticationError, $! end raise RLPxSessionError, 'invalid message length' unless message.size == 64+32+1 ephemeral_pubkey = message[0,64] nonce = message[64,32] known = message[-1].ord raise RLPxSessionError, 'invalid known byte' unless known == 0 [210, ephemeral_pubkey, nonce, 4] end
ruby
def decode_ack_plain(ciphertext) message = begin @ecc.ecies_decrypt ciphertext[0,210] rescue raise AuthenticationError, $! end raise RLPxSessionError, 'invalid message length' unless message.size == 64+32+1 ephemeral_pubkey = message[0,64] nonce = message[64,32] known = message[-1].ord raise RLPxSessionError, 'invalid known byte' unless known == 0 [210, ephemeral_pubkey, nonce, 4] end
[ "def", "decode_ack_plain", "(", "ciphertext", ")", "message", "=", "begin", "@ecc", ".", "ecies_decrypt", "ciphertext", "[", "0", ",", "210", "]", "rescue", "raise", "AuthenticationError", ",", "$!", "end", "raise", "RLPxSessionError", ",", "'invalid message length'", "unless", "message", ".", "size", "==", "64", "+", "32", "+", "1", "ephemeral_pubkey", "=", "message", "[", "0", ",", "64", "]", "nonce", "=", "message", "[", "64", ",", "32", "]", "known", "=", "message", "[", "-", "1", "]", ".", "ord", "raise", "RLPxSessionError", ",", "'invalid known byte'", "unless", "known", "==", "0", "[", "210", ",", "ephemeral_pubkey", ",", "nonce", ",", "4", "]", "end" ]
decode legacy pre-EIP-8 ack message format
[ "decode", "legacy", "pre", "-", "EIP", "-", "8", "ack", "message", "format" ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/rlpx_session.rb#L399-L413
24,283
cryptape/ruby-devp2p
lib/devp2p/rlpx_session.rb
DEVp2p.RLPxSession.decode_ack_eip8
def decode_ack_eip8(ciphertext) size = ciphertext[0,2].unpack('S>').first + 2 raise RLPxSessionError, 'invalid ciphertext length' unless ciphertext.size == size message = begin @ecc.ecies_decrypt(ciphertext[2...size], ciphertext[0,2]) rescue raise AuthenticationError, $! end values = RLP.decode message, sedes: eip8_ack_sedes, strict: false raise RLPxSessionError, 'invalid values length' unless values.size >= 3 [size] + values[0,3] end
ruby
def decode_ack_eip8(ciphertext) size = ciphertext[0,2].unpack('S>').first + 2 raise RLPxSessionError, 'invalid ciphertext length' unless ciphertext.size == size message = begin @ecc.ecies_decrypt(ciphertext[2...size], ciphertext[0,2]) rescue raise AuthenticationError, $! end values = RLP.decode message, sedes: eip8_ack_sedes, strict: false raise RLPxSessionError, 'invalid values length' unless values.size >= 3 [size] + values[0,3] end
[ "def", "decode_ack_eip8", "(", "ciphertext", ")", "size", "=", "ciphertext", "[", "0", ",", "2", "]", ".", "unpack", "(", "'S>'", ")", ".", "first", "+", "2", "raise", "RLPxSessionError", ",", "'invalid ciphertext length'", "unless", "ciphertext", ".", "size", "==", "size", "message", "=", "begin", "@ecc", ".", "ecies_decrypt", "(", "ciphertext", "[", "2", "...", "size", "]", ",", "ciphertext", "[", "0", ",", "2", "]", ")", "rescue", "raise", "AuthenticationError", ",", "$!", "end", "values", "=", "RLP", ".", "decode", "message", ",", "sedes", ":", "eip8_ack_sedes", ",", "strict", ":", "false", "raise", "RLPxSessionError", ",", "'invalid values length'", "unless", "values", ".", "size", ">=", "3", "[", "size", "]", "+", "values", "[", "0", ",", "3", "]", "end" ]
decode EIP-8 ack message format
[ "decode", "EIP", "-", "8", "ack", "message", "format" ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/rlpx_session.rb#L418-L431
24,284
solutious/rudy
lib/rudy/global.rb
Rudy.Global.apply_system_defaults
def apply_system_defaults if @region.nil? && @zone.nil? @region, @zone = Rudy::DEFAULT_REGION, Rudy::DEFAULT_ZONE elsif @region.nil? @region = @zone.to_s.gsub(/[a-z]$/, '').to_sym elsif @zone.nil? @zone = "#{@region}b".to_sym end @environment ||= Rudy::DEFAULT_ENVIRONMENT @role ||= Rudy::DEFAULT_ROLE @localhost ||= Rudy.sysinfo.hostname || 'localhost' @auto = false if @auto.nil? end
ruby
def apply_system_defaults if @region.nil? && @zone.nil? @region, @zone = Rudy::DEFAULT_REGION, Rudy::DEFAULT_ZONE elsif @region.nil? @region = @zone.to_s.gsub(/[a-z]$/, '').to_sym elsif @zone.nil? @zone = "#{@region}b".to_sym end @environment ||= Rudy::DEFAULT_ENVIRONMENT @role ||= Rudy::DEFAULT_ROLE @localhost ||= Rudy.sysinfo.hostname || 'localhost' @auto = false if @auto.nil? end
[ "def", "apply_system_defaults", "if", "@region", ".", "nil?", "&&", "@zone", ".", "nil?", "@region", ",", "@zone", "=", "Rudy", "::", "DEFAULT_REGION", ",", "Rudy", "::", "DEFAULT_ZONE", "elsif", "@region", ".", "nil?", "@region", "=", "@zone", ".", "to_s", ".", "gsub", "(", "/", "/", ",", "''", ")", ".", "to_sym", "elsif", "@zone", ".", "nil?", "@zone", "=", "\"#{@region}b\"", ".", "to_sym", "end", "@environment", "||=", "Rudy", "::", "DEFAULT_ENVIRONMENT", "@role", "||=", "Rudy", "::", "DEFAULT_ROLE", "@localhost", "||=", "Rudy", ".", "sysinfo", ".", "hostname", "||", "'localhost'", "@auto", "=", "false", "if", "@auto", ".", "nil?", "end" ]
Apply defaults for parameters that must have values
[ "Apply", "defaults", "for", "parameters", "that", "must", "have", "values" ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/global.rb#L141-L154
24,285
solutious/rudy
lib/rudy/global.rb
Rudy.Global.clear_system_defaults
def clear_system_defaults @region = nil if @region == Rudy::DEFAULT_REGION @zone = nil if @zone == Rudy::DEFAULT_ZONE @environment = nil if @environment == Rudy::DEFAULT_ENVIRONMENT @role = nil if @role == Rudy::DEFAULT_ROLE @localhost = nil if @localhost == (Rudy.sysinfo.hostname || 'localhost') @auto = nil if @auto == false end
ruby
def clear_system_defaults @region = nil if @region == Rudy::DEFAULT_REGION @zone = nil if @zone == Rudy::DEFAULT_ZONE @environment = nil if @environment == Rudy::DEFAULT_ENVIRONMENT @role = nil if @role == Rudy::DEFAULT_ROLE @localhost = nil if @localhost == (Rudy.sysinfo.hostname || 'localhost') @auto = nil if @auto == false end
[ "def", "clear_system_defaults", "@region", "=", "nil", "if", "@region", "==", "Rudy", "::", "DEFAULT_REGION", "@zone", "=", "nil", "if", "@zone", "==", "Rudy", "::", "DEFAULT_ZONE", "@environment", "=", "nil", "if", "@environment", "==", "Rudy", "::", "DEFAULT_ENVIRONMENT", "@role", "=", "nil", "if", "@role", "==", "Rudy", "::", "DEFAULT_ROLE", "@localhost", "=", "nil", "if", "@localhost", "==", "(", "Rudy", ".", "sysinfo", ".", "hostname", "||", "'localhost'", ")", "@auto", "=", "nil", "if", "@auto", "==", "false", "end" ]
Unapply defaults for parameters that must have values. This is important when reloading configuration since we don't overwrite existing values. If the default ones remained the configuration would not be applied.
[ "Unapply", "defaults", "for", "parameters", "that", "must", "have", "values", ".", "This", "is", "important", "when", "reloading", "configuration", "since", "we", "don", "t", "overwrite", "existing", "values", ".", "If", "the", "default", "ones", "remained", "the", "configuration", "would", "not", "be", "applied", "." ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/global.rb#L160-L167
24,286
solutious/rudy
lib/rudy/routines/handlers/rye.rb
Rudy::Routines::Handlers.RyeTools.print_command
def print_command(user, host, cmd) #return if @@global.parallel cmd ||= "" cmd, user = cmd.to_s, user.to_s prompt = user == "root" ? "#" : "$" li ("%s@%s%s %s" % [user, host, prompt, cmd.bright]) end
ruby
def print_command(user, host, cmd) #return if @@global.parallel cmd ||= "" cmd, user = cmd.to_s, user.to_s prompt = user == "root" ? "#" : "$" li ("%s@%s%s %s" % [user, host, prompt, cmd.bright]) end
[ "def", "print_command", "(", "user", ",", "host", ",", "cmd", ")", "#return if @@global.parallel", "cmd", "||=", "\"\"", "cmd", ",", "user", "=", "cmd", ".", "to_s", ",", "user", ".", "to_s", "prompt", "=", "user", "==", "\"root\"", "?", "\"#\"", ":", "\"$\"", "li", "(", "\"%s@%s%s %s\"", "%", "[", "user", ",", "host", ",", "prompt", ",", "cmd", ".", "bright", "]", ")", "end" ]
Returns a formatted string for printing command info
[ "Returns", "a", "formatted", "string", "for", "printing", "command", "info" ]
52627b6228a29243b22ffeb188546f33aec95343
https://github.com/solutious/rudy/blob/52627b6228a29243b22ffeb188546f33aec95343/lib/rudy/routines/handlers/rye.rb#L117-L123
24,287
Rightpoint/circleci_artifact
lib/circleci_artifact.rb
CircleciArtifact.Fetcher.parse
def parse(artifacts:, queries:) raise ArgumentError, 'Error: Must have artifacts' if artifacts.nil? raise ArgumentError, 'Error: Must have queries' unless queries.is_a?(Array) # Example # [ # { # node_index: 0, # path: "/tmp/circle-artifacts.NHQxLku/cherry-pie.png", # pretty_path: "$CIRCLE_ARTIFACTS/cherry-pie.png", # url: "https://circleci.com/gh/circleci/mongofinil/22/artifacts/0/tmp/circle-artifacts.NHQxLku/cherry-pie.png" # }, # { # node_index: 0, # path: "/tmp/circle-artifacts.NHQxLku/rhubarb-pie.png", # pretty_path: "$CIRCLE_ARTIFACTS/rhubarb-pie.png", # url: "https://circleci.com/gh/circleci/mongofinil/22/artifacts/0/tmp/circle-artifacts.NHQxLku/rhubarb-pie.png" # } # ] results = ResultSet.new artifacts.body.each do |artifact| url = artifact['url'] if url.nil? STDERR.puts "Warning: No URL found on #{artifact}" next end query = queries.find { |q| url.include?(q.url_substring) } next if query.nil? result = Result.new(query: query, url: url) results.add_result(result) end results end
ruby
def parse(artifacts:, queries:) raise ArgumentError, 'Error: Must have artifacts' if artifacts.nil? raise ArgumentError, 'Error: Must have queries' unless queries.is_a?(Array) # Example # [ # { # node_index: 0, # path: "/tmp/circle-artifacts.NHQxLku/cherry-pie.png", # pretty_path: "$CIRCLE_ARTIFACTS/cherry-pie.png", # url: "https://circleci.com/gh/circleci/mongofinil/22/artifacts/0/tmp/circle-artifacts.NHQxLku/cherry-pie.png" # }, # { # node_index: 0, # path: "/tmp/circle-artifacts.NHQxLku/rhubarb-pie.png", # pretty_path: "$CIRCLE_ARTIFACTS/rhubarb-pie.png", # url: "https://circleci.com/gh/circleci/mongofinil/22/artifacts/0/tmp/circle-artifacts.NHQxLku/rhubarb-pie.png" # } # ] results = ResultSet.new artifacts.body.each do |artifact| url = artifact['url'] if url.nil? STDERR.puts "Warning: No URL found on #{artifact}" next end query = queries.find { |q| url.include?(q.url_substring) } next if query.nil? result = Result.new(query: query, url: url) results.add_result(result) end results end
[ "def", "parse", "(", "artifacts", ":", ",", "queries", ":", ")", "raise", "ArgumentError", ",", "'Error: Must have artifacts'", "if", "artifacts", ".", "nil?", "raise", "ArgumentError", ",", "'Error: Must have queries'", "unless", "queries", ".", "is_a?", "(", "Array", ")", "# Example", "# [", "# {", "# node_index: 0,", "# path: \"/tmp/circle-artifacts.NHQxLku/cherry-pie.png\",", "# pretty_path: \"$CIRCLE_ARTIFACTS/cherry-pie.png\",", "# url: \"https://circleci.com/gh/circleci/mongofinil/22/artifacts/0/tmp/circle-artifacts.NHQxLku/cherry-pie.png\"", "# },", "# {", "# node_index: 0,", "# path: \"/tmp/circle-artifacts.NHQxLku/rhubarb-pie.png\",", "# pretty_path: \"$CIRCLE_ARTIFACTS/rhubarb-pie.png\",", "# url: \"https://circleci.com/gh/circleci/mongofinil/22/artifacts/0/tmp/circle-artifacts.NHQxLku/rhubarb-pie.png\"", "# }", "# ]", "results", "=", "ResultSet", ".", "new", "artifacts", ".", "body", ".", "each", "do", "|", "artifact", "|", "url", "=", "artifact", "[", "'url'", "]", "if", "url", ".", "nil?", "STDERR", ".", "puts", "\"Warning: No URL found on #{artifact}\"", "next", "end", "query", "=", "queries", ".", "find", "{", "|", "q", "|", "url", ".", "include?", "(", "q", ".", "url_substring", ")", "}", "next", "if", "query", ".", "nil?", "result", "=", "Result", ".", "new", "(", "query", ":", "query", ",", "url", ":", "url", ")", "results", ".", "add_result", "(", "result", ")", "end", "results", "end" ]
Internal method for extracting results @param artifacts [CircleCi::Artifacts] @param queries [Array<Query>] @return [ResultSet]
[ "Internal", "method", "for", "extracting", "results" ]
ea9c453c7c7ec6d9b6cf6f486b97f2ada161d5d3
https://github.com/Rightpoint/circleci_artifact/blob/ea9c453c7c7ec6d9b6cf6f486b97f2ada161d5d3/lib/circleci_artifact.rb#L126-L162
24,288
encoreshao/crunchbase-ruby-library
lib/crunchbase/client.rb
Crunchbase.Client.get
def get(permalink, kclass_name, relationship_name = nil) case kclass_name when 'Person' person(permalink, relationship_name) when 'Organization' organization(permalink, relationship_name) end end
ruby
def get(permalink, kclass_name, relationship_name = nil) case kclass_name when 'Person' person(permalink, relationship_name) when 'Organization' organization(permalink, relationship_name) end end
[ "def", "get", "(", "permalink", ",", "kclass_name", ",", "relationship_name", "=", "nil", ")", "case", "kclass_name", "when", "'Person'", "person", "(", "permalink", ",", "relationship_name", ")", "when", "'Organization'", "organization", "(", "permalink", ",", "relationship_name", ")", "end", "end" ]
Get information by permalink with optional one relationship
[ "Get", "information", "by", "permalink", "with", "optional", "one", "relationship" ]
9844f8538ef0e4b33000948d9342d2d7119f3f0c
https://github.com/encoreshao/crunchbase-ruby-library/blob/9844f8538ef0e4b33000948d9342d2d7119f3f0c/lib/crunchbase/client.rb#L6-L13
24,289
tiagopog/scrapifier
lib/scrapifier/methods.rb
Scrapifier.Methods.scrapify
def scrapify(options = {}) uri, meta = find_uri(options[:which]), {} return meta if uri.nil? if !(uri =~ sf_regex(:image)) meta = sf_eval_uri(uri, options[:images]) elsif !sf_check_img_ext(uri, options[:images]).empty? [:title, :description, :uri, :images].each { |k| meta[k] = uri } end meta end
ruby
def scrapify(options = {}) uri, meta = find_uri(options[:which]), {} return meta if uri.nil? if !(uri =~ sf_regex(:image)) meta = sf_eval_uri(uri, options[:images]) elsif !sf_check_img_ext(uri, options[:images]).empty? [:title, :description, :uri, :images].each { |k| meta[k] = uri } end meta end
[ "def", "scrapify", "(", "options", "=", "{", "}", ")", "uri", ",", "meta", "=", "find_uri", "(", "options", "[", ":which", "]", ")", ",", "{", "}", "return", "meta", "if", "uri", ".", "nil?", "if", "!", "(", "uri", "=~", "sf_regex", "(", ":image", ")", ")", "meta", "=", "sf_eval_uri", "(", "uri", ",", "options", "[", ":images", "]", ")", "elsif", "!", "sf_check_img_ext", "(", "uri", ",", "options", "[", ":images", "]", ")", ".", "empty?", "[", ":title", ",", ":description", ",", ":uri", ",", ":images", "]", ".", "each", "{", "|", "k", "|", "meta", "[", "k", "]", "=", "uri", "}", "end", "meta", "end" ]
Get metadata from an URI using the screen scraping technique. Example: >> 'Wow! What an awesome site: http://adtangerine.com!'.scrapify => { :title => "AdTangerine | Advertising Platform for Social Media", :description => "AdTangerine is an advertising platform that...", :images => [ "http://adtangerine.com/assets/logo_adt_og.png", "http://adtangerine.com/assets/logo_adt_og.png ], :uri => "http://adtangerine.com" } Arguments: options: (Hash) - which: (Integer) Which URI in the String will be used. It starts from 0 to N. - images: (Symbol or Array) Image extensions which are allowed to be returned as result.
[ "Get", "metadata", "from", "an", "URI", "using", "the", "screen", "scraping", "technique", "." ]
2eda1b0fac6ba58b38b8716816bd71712c7a6994
https://github.com/tiagopog/scrapifier/blob/2eda1b0fac6ba58b38b8716816bd71712c7a6994/lib/scrapifier/methods.rb#L30-L41
24,290
tiagopog/scrapifier
lib/scrapifier/methods.rb
Scrapifier.Methods.find_uri
def find_uri(which = 0) which = scan(sf_regex(:uri))[which.to_i][0] which =~ sf_regex(:protocol) ? which : "http://#{which}" rescue NoMethodError nil end
ruby
def find_uri(which = 0) which = scan(sf_regex(:uri))[which.to_i][0] which =~ sf_regex(:protocol) ? which : "http://#{which}" rescue NoMethodError nil end
[ "def", "find_uri", "(", "which", "=", "0", ")", "which", "=", "scan", "(", "sf_regex", "(", ":uri", ")", ")", "[", "which", ".", "to_i", "]", "[", "0", "]", "which", "=~", "sf_regex", "(", ":protocol", ")", "?", "which", ":", "\"http://#{which}\"", "rescue", "NoMethodError", "nil", "end" ]
Find URIs in the String. Example: >> 'Wow! What an awesome site: http://adtangerine.com!'.find_uri => 'http://adtangerine.com' >> 'Very cool: http://adtangerine.com and www.twitflink.com'.find_uri 1 => 'www.twitflink.com' Arguments: which: (Integer) - Which URI in the String: first (0), second (1) and so on.
[ "Find", "URIs", "in", "the", "String", "." ]
2eda1b0fac6ba58b38b8716816bd71712c7a6994
https://github.com/tiagopog/scrapifier/blob/2eda1b0fac6ba58b38b8716816bd71712c7a6994/lib/scrapifier/methods.rb#L53-L58
24,291
stereocat/expectacle
lib/expectacle/thrower_preview.rb
Expectacle.Thrower.previewed_host_param
def previewed_host_param host_param = @host_param.dup enable_mode = @enable_mode @enable_mode = false host_param[:username] = embed_user_name host_param[:password] = embed_password host_param[:ipaddr] = embed_ipaddr @enable_mode = true host_param[:enable] = embed_password @enable_mode = enable_mode host_param end
ruby
def previewed_host_param host_param = @host_param.dup enable_mode = @enable_mode @enable_mode = false host_param[:username] = embed_user_name host_param[:password] = embed_password host_param[:ipaddr] = embed_ipaddr @enable_mode = true host_param[:enable] = embed_password @enable_mode = enable_mode host_param end
[ "def", "previewed_host_param", "host_param", "=", "@host_param", ".", "dup", "enable_mode", "=", "@enable_mode", "@enable_mode", "=", "false", "host_param", "[", ":username", "]", "=", "embed_user_name", "host_param", "[", ":password", "]", "=", "embed_password", "host_param", "[", ":ipaddr", "]", "=", "embed_ipaddr", "@enable_mode", "=", "true", "host_param", "[", ":enable", "]", "=", "embed_password", "@enable_mode", "=", "enable_mode", "host_param", "end" ]
Setup parameters for a host to preview
[ "Setup", "parameters", "for", "a", "host", "to", "preview" ]
a67faca42ba5f90068c69047bb6cf01c2bca1b74
https://github.com/stereocat/expectacle/blob/a67faca42ba5f90068c69047bb6cf01c2bca1b74/lib/expectacle/thrower_preview.rb#L49-L60
24,292
dankimio/acts_as_learnable
lib/acts_as_learnable/base.rb
ActsAsLearnable.InstanceMethods.reset
def reset self.repetitions = 0 self.interval = 0 self.due = Date.today self.studied_at = Date.today save end
ruby
def reset self.repetitions = 0 self.interval = 0 self.due = Date.today self.studied_at = Date.today save end
[ "def", "reset", "self", ".", "repetitions", "=", "0", "self", ".", "interval", "=", "0", "self", ".", "due", "=", "Date", ".", "today", "self", ".", "studied_at", "=", "Date", ".", "today", "save", "end" ]
Bad recall quality, start over
[ "Bad", "recall", "quality", "start", "over" ]
2bffb223691da31ae8d6519e0cc24dd21f402fee
https://github.com/dankimio/acts_as_learnable/blob/2bffb223691da31ae8d6519e0cc24dd21f402fee/lib/acts_as_learnable/base.rb#L46-L52
24,293
rsutphin/handbrake.rb
lib/handbrake/cli.rb
HandBrake.CLI.output
def output(filename, options={}) options = options.dup overwrite = options.delete :overwrite case overwrite when true, nil # no special behavior when false raise FileExistsError, filename if File.exist?(filename) when :ignore if File.exist?(filename) trace "Ignoring transcode to #{filename.inspect} because it already exists" return end else raise "Unsupported value for :overwrite: #{overwrite.inspect}" end atomic = options.delete :atomic interim_filename = case atomic when true partial_filename(filename) when String partial_filename(File.join(atomic, File.basename(filename))) when false, nil filename else fail "Unsupported value for :atomic: #{atomic.inspect}" end unless options.empty? raise "Unknown options for output: #{options.keys.inspect}" end FileUtils.mkdir_p(File.dirname(interim_filename), fileutils_options) run('--output', interim_filename) if filename != interim_filename replace = if File.exist?(filename) trace "#{filename.inspect} showed up during transcode" case overwrite when false raise FileExistsError, filename when :ignore trace "- will leave #{filename.inspect} as is; copy #{interim_filename.inspect} manually if you want to replace it" false else trace '- will replace with new transcode' true end else true end FileUtils.mkdir_p(File.dirname(filename), fileutils_options) FileUtils.mv(interim_filename, filename, fileutils_options) if replace end end
ruby
def output(filename, options={}) options = options.dup overwrite = options.delete :overwrite case overwrite when true, nil # no special behavior when false raise FileExistsError, filename if File.exist?(filename) when :ignore if File.exist?(filename) trace "Ignoring transcode to #{filename.inspect} because it already exists" return end else raise "Unsupported value for :overwrite: #{overwrite.inspect}" end atomic = options.delete :atomic interim_filename = case atomic when true partial_filename(filename) when String partial_filename(File.join(atomic, File.basename(filename))) when false, nil filename else fail "Unsupported value for :atomic: #{atomic.inspect}" end unless options.empty? raise "Unknown options for output: #{options.keys.inspect}" end FileUtils.mkdir_p(File.dirname(interim_filename), fileutils_options) run('--output', interim_filename) if filename != interim_filename replace = if File.exist?(filename) trace "#{filename.inspect} showed up during transcode" case overwrite when false raise FileExistsError, filename when :ignore trace "- will leave #{filename.inspect} as is; copy #{interim_filename.inspect} manually if you want to replace it" false else trace '- will replace with new transcode' true end else true end FileUtils.mkdir_p(File.dirname(filename), fileutils_options) FileUtils.mv(interim_filename, filename, fileutils_options) if replace end end
[ "def", "output", "(", "filename", ",", "options", "=", "{", "}", ")", "options", "=", "options", ".", "dup", "overwrite", "=", "options", ".", "delete", ":overwrite", "case", "overwrite", "when", "true", ",", "nil", "# no special behavior", "when", "false", "raise", "FileExistsError", ",", "filename", "if", "File", ".", "exist?", "(", "filename", ")", "when", ":ignore", "if", "File", ".", "exist?", "(", "filename", ")", "trace", "\"Ignoring transcode to #{filename.inspect} because it already exists\"", "return", "end", "else", "raise", "\"Unsupported value for :overwrite: #{overwrite.inspect}\"", "end", "atomic", "=", "options", ".", "delete", ":atomic", "interim_filename", "=", "case", "atomic", "when", "true", "partial_filename", "(", "filename", ")", "when", "String", "partial_filename", "(", "File", ".", "join", "(", "atomic", ",", "File", ".", "basename", "(", "filename", ")", ")", ")", "when", "false", ",", "nil", "filename", "else", "fail", "\"Unsupported value for :atomic: #{atomic.inspect}\"", "end", "unless", "options", ".", "empty?", "raise", "\"Unknown options for output: #{options.keys.inspect}\"", "end", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "interim_filename", ")", ",", "fileutils_options", ")", "run", "(", "'--output'", ",", "interim_filename", ")", "if", "filename", "!=", "interim_filename", "replace", "=", "if", "File", ".", "exist?", "(", "filename", ")", "trace", "\"#{filename.inspect} showed up during transcode\"", "case", "overwrite", "when", "false", "raise", "FileExistsError", ",", "filename", "when", ":ignore", "trace", "\"- will leave #{filename.inspect} as is; copy #{interim_filename.inspect} manually if you want to replace it\"", "false", "else", "trace", "'- will replace with new transcode'", "true", "end", "else", "true", "end", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "filename", ")", ",", "fileutils_options", ")", "FileUtils", ".", "mv", "(", "interim_filename", ",", "filename", ",", "fileutils_options", ")", "if", "replace", "end", "end" ]
Performs a conversion. This method immediately begins the transcoding process; set all other options first. @param [String] filename the desired name for the final output file. @param [Hash] options additional options to control the behavior of the output process. The provided hash will not be modified. @option options [Boolean,:ignore] :overwrite (true) determines the behavior if the desired output file already exists. If `true`, the file is replaced. If `false`, an exception is thrown. If `:ignore`, the file is skipped; i.e., HandBrakeCLI is not invoked. @option options [Boolean, String] :atomic (false) provides a pseudo-atomic mode for transcoded output. If true, the transcode will go into a temporary file and only be copied to the specified filename if it completes. If the value is literally `true`, the temporary filename is the target filename with `.handbraking` inserted before the extension. If the value is a string, it is interpreted as a path; the temporary file is written to this path instead of in the ultimate target directory. Any `:overwrite` checking will be applied to the target filename both before and after the transcode happens (the temporary file will always be overwritten). This option is intended to aid in writing automatically resumable batch scripts. @return [void]
[ "Performs", "a", "conversion", ".", "This", "method", "immediately", "begins", "the", "transcoding", "process", ";", "set", "all", "other", "options", "first", "." ]
86c0f6beb6dadd28c8de6ca82fd1515a1d9736ec
https://github.com/rsutphin/handbrake.rb/blob/86c0f6beb6dadd28c8de6ca82fd1515a1d9736ec/lib/handbrake/cli.rb#L140-L197
24,294
rsutphin/handbrake.rb
lib/handbrake/cli.rb
HandBrake.CLI.preset_list
def preset_list result = run('--preset-list') result.output.scan(%r{\< (.*?)\n(.*?)\>}m).inject({}) { |h1, (cat, block)| h1[cat.strip] = block.scan(/\+(.*?):(.*?)\n/).inject({}) { |h2, (name, args)| h2[name.strip] = args.strip h2 } h1 } end
ruby
def preset_list result = run('--preset-list') result.output.scan(%r{\< (.*?)\n(.*?)\>}m).inject({}) { |h1, (cat, block)| h1[cat.strip] = block.scan(/\+(.*?):(.*?)\n/).inject({}) { |h2, (name, args)| h2[name.strip] = args.strip h2 } h1 } end
[ "def", "preset_list", "result", "=", "run", "(", "'--preset-list'", ")", "result", ".", "output", ".", "scan", "(", "%r{", "\\<", "\\n", "\\>", "}m", ")", ".", "inject", "(", "{", "}", ")", "{", "|", "h1", ",", "(", "cat", ",", "block", ")", "|", "h1", "[", "cat", ".", "strip", "]", "=", "block", ".", "scan", "(", "/", "\\+", "\\n", "/", ")", ".", "inject", "(", "{", "}", ")", "{", "|", "h2", ",", "(", "name", ",", "args", ")", "|", "h2", "[", "name", ".", "strip", "]", "=", "args", ".", "strip", "h2", "}", "h1", "}", "end" ]
Returns a structure describing the presets that the current HandBrake install knows about. The structure is a two-level hash. The keys in the first level are the preset categories. The keys in the second level are the preset names and the values are string representations of the arguments for that preset. (This method is included for completeness only. This library does not provide a mechanism to translate the argument lists returned here into the configuration for a {HandBrake::CLI} instance.) @return [Hash]
[ "Returns", "a", "structure", "describing", "the", "presets", "that", "the", "current", "HandBrake", "install", "knows", "about", ".", "The", "structure", "is", "a", "two", "-", "level", "hash", ".", "The", "keys", "in", "the", "first", "level", "are", "the", "preset", "categories", ".", "The", "keys", "in", "the", "second", "level", "are", "the", "preset", "names", "and", "the", "values", "are", "string", "representations", "of", "the", "arguments", "for", "that", "preset", "." ]
86c0f6beb6dadd28c8de6ca82fd1515a1d9736ec
https://github.com/rsutphin/handbrake.rb/blob/86c0f6beb6dadd28c8de6ca82fd1515a1d9736ec/lib/handbrake/cli.rb#L260-L269
24,295
rsutphin/handbrake.rb
lib/handbrake/cli.rb
HandBrake.CLI.method_missing
def method_missing(name, *args) copy = self.dup copy.instance_eval { @args << [name, *(args.collect { |a| a.to_s })] } copy end
ruby
def method_missing(name, *args) copy = self.dup copy.instance_eval { @args << [name, *(args.collect { |a| a.to_s })] } copy end
[ "def", "method_missing", "(", "name", ",", "*", "args", ")", "copy", "=", "self", ".", "dup", "copy", ".", "instance_eval", "{", "@args", "<<", "[", "name", ",", "(", "args", ".", "collect", "{", "|", "a", "|", "a", ".", "to_s", "}", ")", "]", "}", "copy", "end" ]
Copies this CLI instance and appends another command line switch plus optional arguments. This method does not do any validation of the switch name; if you use an invalid one, HandBrakeCLI will fail when it is ultimately invoked. @return [CLI]
[ "Copies", "this", "CLI", "instance", "and", "appends", "another", "command", "line", "switch", "plus", "optional", "arguments", "." ]
86c0f6beb6dadd28c8de6ca82fd1515a1d9736ec
https://github.com/rsutphin/handbrake.rb/blob/86c0f6beb6dadd28c8de6ca82fd1515a1d9736ec/lib/handbrake/cli.rb#L303-L307
24,296
keithrbennett/trick_bag
lib/trick_bag/timing/timing.rb
TrickBag.Timing.retry_until_true_or_timeout
def retry_until_true_or_timeout( sleep_interval, timeout_secs, output_stream = $stdout, predicate = nil) test_preconditions = -> do # Method signature has changed from: # (predicate, sleep_interval, timeout_secs, output_stream = $stdout) # to: # (sleep_interval, timeout_secs, output_stream = $stdout, predicate = nil) # # Test to see that when old signature is used, a descriptive error is raised. # # This test should be removed when we go to version 1.0. if sleep_interval.respond_to?(:call) raise ArgumentError.new('Sorry, method signature has changed to: ' \ '(sleep_interval, timeout_secs, output_stream = $stdout, predicate = nil).' \ ' Also a code block can now be provided instead of a lambda.') end if block_given? && predicate raise ArgumentError.new('Both a predicate lambda and a code block were specified.' \ ' Please specify one or the other but not both.') end end test_preconditions.() success = false start_time = Time.now end_time = start_time + timeout_secs text_generator = ->() do now = Time.now elapsed = now - start_time to_go = end_time - now '%9.3f %9.3f' % [elapsed, to_go] end status_updater = ::TrickBag::Io::TextModeStatusUpdater.new(text_generator, output_stream) loop do break if Time.now >= end_time success = !! (block_given? ? yield : predicate.()) break if success status_updater.print sleep(sleep_interval) end output_stream.print "\n" success end
ruby
def retry_until_true_or_timeout( sleep_interval, timeout_secs, output_stream = $stdout, predicate = nil) test_preconditions = -> do # Method signature has changed from: # (predicate, sleep_interval, timeout_secs, output_stream = $stdout) # to: # (sleep_interval, timeout_secs, output_stream = $stdout, predicate = nil) # # Test to see that when old signature is used, a descriptive error is raised. # # This test should be removed when we go to version 1.0. if sleep_interval.respond_to?(:call) raise ArgumentError.new('Sorry, method signature has changed to: ' \ '(sleep_interval, timeout_secs, output_stream = $stdout, predicate = nil).' \ ' Also a code block can now be provided instead of a lambda.') end if block_given? && predicate raise ArgumentError.new('Both a predicate lambda and a code block were specified.' \ ' Please specify one or the other but not both.') end end test_preconditions.() success = false start_time = Time.now end_time = start_time + timeout_secs text_generator = ->() do now = Time.now elapsed = now - start_time to_go = end_time - now '%9.3f %9.3f' % [elapsed, to_go] end status_updater = ::TrickBag::Io::TextModeStatusUpdater.new(text_generator, output_stream) loop do break if Time.now >= end_time success = !! (block_given? ? yield : predicate.()) break if success status_updater.print sleep(sleep_interval) end output_stream.print "\n" success end
[ "def", "retry_until_true_or_timeout", "(", "sleep_interval", ",", "timeout_secs", ",", "output_stream", "=", "$stdout", ",", "predicate", "=", "nil", ")", "test_preconditions", "=", "->", "do", "# Method signature has changed from:", "# (predicate, sleep_interval, timeout_secs, output_stream = $stdout)", "# to:", "# (sleep_interval, timeout_secs, output_stream = $stdout, predicate = nil)", "#", "# Test to see that when old signature is used, a descriptive error is raised.", "#", "# This test should be removed when we go to version 1.0.", "if", "sleep_interval", ".", "respond_to?", "(", ":call", ")", "raise", "ArgumentError", ".", "new", "(", "'Sorry, method signature has changed to: '", "'(sleep_interval, timeout_secs, output_stream = $stdout, predicate = nil).'", "' Also a code block can now be provided instead of a lambda.'", ")", "end", "if", "block_given?", "&&", "predicate", "raise", "ArgumentError", ".", "new", "(", "'Both a predicate lambda and a code block were specified.'", "' Please specify one or the other but not both.'", ")", "end", "end", "test_preconditions", ".", "(", ")", "success", "=", "false", "start_time", "=", "Time", ".", "now", "end_time", "=", "start_time", "+", "timeout_secs", "text_generator", "=", "->", "(", ")", "do", "now", "=", "Time", ".", "now", "elapsed", "=", "now", "-", "start_time", "to_go", "=", "end_time", "-", "now", "'%9.3f %9.3f'", "%", "[", "elapsed", ",", "to_go", "]", "end", "status_updater", "=", "::", "TrickBag", "::", "Io", "::", "TextModeStatusUpdater", ".", "new", "(", "text_generator", ",", "output_stream", ")", "loop", "do", "break", "if", "Time", ".", "now", ">=", "end_time", "success", "=", "!", "!", "(", "block_given?", "?", "yield", ":", "predicate", ".", "(", ")", ")", "break", "if", "success", "status_updater", ".", "print", "sleep", "(", "sleep_interval", ")", "end", "output_stream", ".", "print", "\"\\n\"", "success", "end" ]
Calls a predicate proc repeatedly, sleeping the specified interval between calls, returning if the predicate returns true, and giving up after the specified number of seconds. Displays elapsed and remaining times on the terminal. Outputs the time elapsed and the time to go. @param predicate something that can be called with .() or .call that returns a truthy value that indicates no further retries are necessary @param sleep_interval number of seconds (fractions ok) to wait between tries @param timeout_secs maximum number of seconds (fractions ok) during which to retry @return true if/when the predicate returns true, false if it times out Ex: TrickBag::Timing.retry_until_true_or_timeout(->{false}, 1.0, 5) Example Code: require 'trick_bag' predicate = -> { false } print "Waiting 10 seconds for true to be returned (but it won't):\n" TrickBag::Timing.retry_until_true_or_timeout(predicate, 1, 10)
[ "Calls", "a", "predicate", "proc", "repeatedly", "sleeping", "the", "specified", "interval", "between", "calls", "returning", "if", "the", "predicate", "returns", "true", "and", "giving", "up", "after", "the", "specified", "number", "of", "seconds", ".", "Displays", "elapsed", "and", "remaining", "times", "on", "the", "terminal", ".", "Outputs", "the", "time", "elapsed", "and", "the", "time", "to", "go", "." ]
a3886a45f32588aba751d13aeba42ae680bcd203
https://github.com/keithrbennett/trick_bag/blob/a3886a45f32588aba751d13aeba42ae680bcd203/lib/trick_bag/timing/timing.rb#L31-L82
24,297
keithrbennett/trick_bag
lib/trick_bag/timing/timing.rb
TrickBag.Timing.benchmark
def benchmark(caption, out_stream = $stdout, &block) return_value = nil bm = Benchmark.measure { return_value = block.call } out_stream << bm.to_s.chomp << ": #{caption}\n" return_value end
ruby
def benchmark(caption, out_stream = $stdout, &block) return_value = nil bm = Benchmark.measure { return_value = block.call } out_stream << bm.to_s.chomp << ": #{caption}\n" return_value end
[ "def", "benchmark", "(", "caption", ",", "out_stream", "=", "$stdout", ",", "&", "block", ")", "return_value", "=", "nil", "bm", "=", "Benchmark", ".", "measure", "{", "return_value", "=", "block", ".", "call", "}", "out_stream", "<<", "bm", ".", "to_s", ".", "chomp", "<<", "\": #{caption}\\n\"", "return_value", "end" ]
Executes the passed block with the Ruby Benchmark standard library. Prints the benchmark string to the specified output stream. Returns the passed block's return value. e.g. benchmark('time to loop 1,000,000 times') { 1_000_000.times { 42 }; 'hi' } outputs the following string: 0.050000 0.000000 0.050000 ( 0.042376): time to loop 1,000,000 times and returns: 'hi' @param caption the text fragment to print after the timing data @param out_stream object responding to << that will get the output string defaults to $stdout @block the block to execute and benchmark
[ "Executes", "the", "passed", "block", "with", "the", "Ruby", "Benchmark", "standard", "library", ".", "Prints", "the", "benchmark", "string", "to", "the", "specified", "output", "stream", ".", "Returns", "the", "passed", "block", "s", "return", "value", "." ]
a3886a45f32588aba751d13aeba42ae680bcd203
https://github.com/keithrbennett/trick_bag/blob/a3886a45f32588aba751d13aeba42ae680bcd203/lib/trick_bag/timing/timing.rb#L98-L103
24,298
keithrbennett/trick_bag
lib/trick_bag/timing/timing.rb
TrickBag.Timing.try_with_timeout
def try_with_timeout(max_seconds, check_interval_in_secs, &block) raise "Must pass block to this method" unless block_given? end_time = Time.now + max_seconds block_return_value = nil thread = Thread.new { block_return_value = block.call } while Time.now < end_time unless thread.alive? return [true, block_return_value] end sleep(check_interval_in_secs) end thread.kill [false, nil] end
ruby
def try_with_timeout(max_seconds, check_interval_in_secs, &block) raise "Must pass block to this method" unless block_given? end_time = Time.now + max_seconds block_return_value = nil thread = Thread.new { block_return_value = block.call } while Time.now < end_time unless thread.alive? return [true, block_return_value] end sleep(check_interval_in_secs) end thread.kill [false, nil] end
[ "def", "try_with_timeout", "(", "max_seconds", ",", "check_interval_in_secs", ",", "&", "block", ")", "raise", "\"Must pass block to this method\"", "unless", "block_given?", "end_time", "=", "Time", ".", "now", "+", "max_seconds", "block_return_value", "=", "nil", "thread", "=", "Thread", ".", "new", "{", "block_return_value", "=", "block", ".", "call", "}", "while", "Time", ".", "now", "<", "end_time", "unless", "thread", ".", "alive?", "return", "[", "true", ",", "block_return_value", "]", "end", "sleep", "(", "check_interval_in_secs", ")", "end", "thread", ".", "kill", "[", "false", ",", "nil", "]", "end" ]
Runs the passed block in a new thread, ensuring that its execution time does not exceed the specified duration. @param max_seconds maximum number of seconds to wait for completion @param check_interval_in_secs interval in seconds at which to check for completion @block block of code to execute in the secondary thread @return [true, block return value] if the block completes before timeout or [false, nil] if the block is still active (i.e. the thread is still alive) when max_seconds is reached
[ "Runs", "the", "passed", "block", "in", "a", "new", "thread", "ensuring", "that", "its", "execution", "time", "does", "not", "exceed", "the", "specified", "duration", "." ]
a3886a45f32588aba751d13aeba42ae680bcd203
https://github.com/keithrbennett/trick_bag/blob/a3886a45f32588aba751d13aeba42ae680bcd203/lib/trick_bag/timing/timing.rb#L116-L129
24,299
cryptape/ruby-devp2p
lib/devp2p/command.rb
DEVp2p.Command.create
def create(proto, *args) options = args.last.is_a?(Hash) ? args.pop : {} raise ArgumentError, "proto #{proto} must be protocol" unless proto.is_a?(Protocol) raise ArgumentError, "command structure mismatch" if !options.empty? && structure.instance_of?(RLP::Sedes::CountableList) options.empty? ? args : options end
ruby
def create(proto, *args) options = args.last.is_a?(Hash) ? args.pop : {} raise ArgumentError, "proto #{proto} must be protocol" unless proto.is_a?(Protocol) raise ArgumentError, "command structure mismatch" if !options.empty? && structure.instance_of?(RLP::Sedes::CountableList) options.empty? ? args : options end
[ "def", "create", "(", "proto", ",", "*", "args", ")", "options", "=", "args", ".", "last", ".", "is_a?", "(", "Hash", ")", "?", "args", ".", "pop", ":", "{", "}", "raise", "ArgumentError", ",", "\"proto #{proto} must be protocol\"", "unless", "proto", ".", "is_a?", "(", "Protocol", ")", "raise", "ArgumentError", ",", "\"command structure mismatch\"", "if", "!", "options", ".", "empty?", "&&", "structure", ".", "instance_of?", "(", "RLP", "::", "Sedes", "::", "CountableList", ")", "options", ".", "empty?", "?", "args", ":", "options", "end" ]
optionally implement create
[ "optionally", "implement", "create" ]
75a085971316507040fcfede3546ae95204dadad
https://github.com/cryptape/ruby-devp2p/blob/75a085971316507040fcfede3546ae95204dadad/lib/devp2p/command.rb#L65-L70