id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
6,300
cloudhead/mutter
lib/mutter/mutterer.rb
Mutter.Mutterer.unstyle
def unstyle msg styles.map do |_,v| v[:match] end.flatten.inject(msg) do |m, tag| m.gsub(tag, '') end end
ruby
def unstyle msg styles.map do |_,v| v[:match] end.flatten.inject(msg) do |m, tag| m.gsub(tag, '') end end
[ "def", "unstyle", "msg", "styles", ".", "map", "do", "|", "_", ",", "v", "|", "v", "[", ":match", "]", "end", ".", "flatten", ".", "inject", "(", "msg", ")", "do", "|", "m", ",", "tag", "|", "m", ".", "gsub", "(", "tag", ",", "''", ")", "end", "end" ]
Remove all tags from string
[ "Remove", "all", "tags", "from", "string" ]
08a422552027d5a7b30b60206384c11698cf903d
https://github.com/cloudhead/mutter/blob/08a422552027d5a7b30b60206384c11698cf903d/lib/mutter/mutterer.rb#L88-L94
6,301
cloudhead/mutter
lib/mutter/mutterer.rb
Mutter.Mutterer.write
def write str self.class.stream.tap do |stream| stream.write str stream.flush end ; nil end
ruby
def write str self.class.stream.tap do |stream| stream.write str stream.flush end ; nil end
[ "def", "write", "str", "self", ".", "class", ".", "stream", ".", "tap", "do", "|", "stream", "|", "stream", ".", "write", "str", "stream", ".", "flush", "end", ";", "nil", "end" ]
Write to the out stream, and flush it
[ "Write", "to", "the", "out", "stream", "and", "flush", "it" ]
08a422552027d5a7b30b60206384c11698cf903d
https://github.com/cloudhead/mutter/blob/08a422552027d5a7b30b60206384c11698cf903d/lib/mutter/mutterer.rb#L107-L112
6,302
cloudhead/mutter
lib/mutter/mutterer.rb
Mutter.Mutterer.stylize
def stylize string, styles = [] [styles].flatten.inject(string) do |str, style| style = style.to_sym if ANSI[:transforms].include? style esc str, *ANSI[:transforms][style] elsif ANSI[:colors].include? style esc str, ANSI[:colors][style], ANSI[:colors][:reset] else stylize(str, @styles[style][:style]) end end end
ruby
def stylize string, styles = [] [styles].flatten.inject(string) do |str, style| style = style.to_sym if ANSI[:transforms].include? style esc str, *ANSI[:transforms][style] elsif ANSI[:colors].include? style esc str, ANSI[:colors][style], ANSI[:colors][:reset] else stylize(str, @styles[style][:style]) end end end
[ "def", "stylize", "string", ",", "styles", "=", "[", "]", "[", "styles", "]", ".", "flatten", ".", "inject", "(", "string", ")", "do", "|", "str", ",", "style", "|", "style", "=", "style", ".", "to_sym", "if", "ANSI", "[", ":transforms", "]", ".", "include?", "style", "esc", "str", ",", "ANSI", "[", ":transforms", "]", "[", "style", "]", "elsif", "ANSI", "[", ":colors", "]", ".", "include?", "style", "esc", "str", ",", "ANSI", "[", ":colors", "]", "[", "style", "]", ",", "ANSI", "[", ":colors", "]", "[", ":reset", "]", "else", "stylize", "(", "str", ",", "@styles", "[", "style", "]", "[", ":style", "]", ")", "end", "end", "end" ]
Apply styles to a string if the style is a default ANSI style, we add the start and end sequence to the string. if the style is a custom style, we recurse, sending the list of ANSI styles contained in the custom style. TODO: use ';' delimited codes instead of multiple \e sequences
[ "Apply", "styles", "to", "a", "string" ]
08a422552027d5a7b30b60206384c11698cf903d
https://github.com/cloudhead/mutter/blob/08a422552027d5a7b30b60206384c11698cf903d/lib/mutter/mutterer.rb#L170-L181
6,303
danielpuglisi/seiten
lib/seiten/page.rb
Seiten.Page.parent_of?
def parent_of?(child) page = self if child if page.id == child.parent_id true else child.parent.nil? ? false : page.parent_of?(child.parent) end end end
ruby
def parent_of?(child) page = self if child if page.id == child.parent_id true else child.parent.nil? ? false : page.parent_of?(child.parent) end end end
[ "def", "parent_of?", "(", "child", ")", "page", "=", "self", "if", "child", "if", "page", ".", "id", "==", "child", ".", "parent_id", "true", "else", "child", ".", "parent", ".", "nil?", "?", "false", ":", "page", ".", "parent_of?", "(", "child", ".", "parent", ")", "end", "end", "end" ]
true if child is children of page
[ "true", "if", "child", "is", "children", "of", "page" ]
fa23d9ec616a23c615b0bf4b358bb979ab849104
https://github.com/danielpuglisi/seiten/blob/fa23d9ec616a23c615b0bf4b358bb979ab849104/lib/seiten/page.rb#L83-L92
6,304
danielpuglisi/seiten
lib/seiten/page.rb
Seiten.Page.active?
def active?(current_page) if current_page if id == current_page.id true elsif parent_of?(current_page) true else false end end end
ruby
def active?(current_page) if current_page if id == current_page.id true elsif parent_of?(current_page) true else false end end end
[ "def", "active?", "(", "current_page", ")", "if", "current_page", "if", "id", "==", "current_page", ".", "id", "true", "elsif", "parent_of?", "(", "current_page", ")", "true", "else", "false", "end", "end", "end" ]
true if page is equal current_page or parent of current_page
[ "true", "if", "page", "is", "equal", "current_page", "or", "parent", "of", "current_page" ]
fa23d9ec616a23c615b0bf4b358bb979ab849104
https://github.com/danielpuglisi/seiten/blob/fa23d9ec616a23c615b0bf4b358bb979ab849104/lib/seiten/page.rb#L95-L105
6,305
knaveofdiamonds/sequel_load_data_infile
lib/sequel/load_data_infile.rb
Sequel.LoadDataInfile.load_infile_sql
def load_infile_sql(path, columns, options={}) replacement = opts[:insert_ignore] ? :ignore : :replace options = {:update => replacement}.merge(options) LoadDataInfileExpression.new(path, opts[:from].first, columns, options). to_sql(db) end
ruby
def load_infile_sql(path, columns, options={}) replacement = opts[:insert_ignore] ? :ignore : :replace options = {:update => replacement}.merge(options) LoadDataInfileExpression.new(path, opts[:from].first, columns, options). to_sql(db) end
[ "def", "load_infile_sql", "(", "path", ",", "columns", ",", "options", "=", "{", "}", ")", "replacement", "=", "opts", "[", ":insert_ignore", "]", "?", ":ignore", ":", ":replace", "options", "=", "{", ":update", "=>", "replacement", "}", ".", "merge", "(", "options", ")", "LoadDataInfileExpression", ".", "new", "(", "path", ",", "opts", "[", ":from", "]", ".", "first", ",", "columns", ",", "options", ")", ".", "to_sql", "(", "db", ")", "end" ]
Returns the SQL for a LOAD DATA INFILE statement.
[ "Returns", "the", "SQL", "for", "a", "LOAD", "DATA", "INFILE", "statement", "." ]
a9198d727b44289ae99d2eaaf4bd7ec032ef737a
https://github.com/knaveofdiamonds/sequel_load_data_infile/blob/a9198d727b44289ae99d2eaaf4bd7ec032ef737a/lib/sequel/load_data_infile.rb#L136-L144
6,306
dabassett/shibbolite
spec/support/features/session_helpers.rb
Features.SessionHelpers.sign_in_as
def sign_in_as(group) FactoryGirl.create(:user, umbcusername: 'test_user', group: group) page.driver.browser.process_and_follow_redirects(:get, '/shibbolite/login', {}, {'umbcusername' => 'test_user'}) end
ruby
def sign_in_as(group) FactoryGirl.create(:user, umbcusername: 'test_user', group: group) page.driver.browser.process_and_follow_redirects(:get, '/shibbolite/login', {}, {'umbcusername' => 'test_user'}) end
[ "def", "sign_in_as", "(", "group", ")", "FactoryGirl", ".", "create", "(", ":user", ",", "umbcusername", ":", "'test_user'", ",", "group", ":", "group", ")", "page", ".", "driver", ".", "browser", ".", "process_and_follow_redirects", "(", ":get", ",", "'/shibbolite/login'", ",", "{", "}", ",", "{", "'umbcusername'", "=>", "'test_user'", "}", ")", "end" ]
hacked login, but the alternative is not having integration tests when using a Shibboleth based auth
[ "hacked", "login", "but", "the", "alternative", "is", "not", "having", "integration", "tests", "when", "using", "a", "Shibboleth", "based", "auth" ]
cbd679c88de4ab238c40029447715f6ff22f3f50
https://github.com/dabassett/shibbolite/blob/cbd679c88de4ab238c40029447715f6ff22f3f50/spec/support/features/session_helpers.rb#L7-L10
6,307
arvicco/poster
lib/poster/site.rb
Poster.Site.connect
def connect uri Faraday.new(:url => "#{uri.scheme}://#{uri.host}") do |faraday| faraday.request :multipart faraday.request :url_encoded # faraday.use FaradayMiddleware::FollowRedirects, limit: 3 faraday.use :cookie_jar faraday.response :logger # log requests to STDOUT faraday.adapter Faraday.default_adapter # make requests with Net::HTTP end end
ruby
def connect uri Faraday.new(:url => "#{uri.scheme}://#{uri.host}") do |faraday| faraday.request :multipart faraday.request :url_encoded # faraday.use FaradayMiddleware::FollowRedirects, limit: 3 faraday.use :cookie_jar faraday.response :logger # log requests to STDOUT faraday.adapter Faraday.default_adapter # make requests with Net::HTTP end end
[ "def", "connect", "uri", "Faraday", ".", "new", "(", ":url", "=>", "\"#{uri.scheme}://#{uri.host}\"", ")", "do", "|", "faraday", "|", "faraday", ".", "request", ":multipart", "faraday", ".", "request", ":url_encoded", "# faraday.use FaradayMiddleware::FollowRedirects, limit: 3", "faraday", ".", "use", ":cookie_jar", "faraday", ".", "response", ":logger", "# log requests to STDOUT", "faraday", ".", "adapter", "Faraday", ".", "default_adapter", "# make requests with Net::HTTP", "end", "end" ]
Establish Faraday connection
[ "Establish", "Faraday", "connection" ]
a5f22f7cb02116ab4dc5b7f2bdb672306b3dac63
https://github.com/arvicco/poster/blob/a5f22f7cb02116ab4dc5b7f2bdb672306b3dac63/lib/poster/site.rb#L20-L29
6,308
tnorthb/coinstack
lib/coinstack/printer.rb
Coinstack.Printer.pretty_print_user_list
def pretty_print_user_list(list) total = 0 data = [] # Header row data.push('Asset', 'Total Value', 'Change % (Week)') list.user_pairs.each do |user_pair| data.push(user_pair.symbol) data.push(user_pair.valuation.format) data.push(user_pair.perchant_change_week.to_s) total += user_pair.valuation end data.push('', '', '') data.push('TOTAL:', total.format, '') data.push('', '', '') print_arrays(data, 3) end
ruby
def pretty_print_user_list(list) total = 0 data = [] # Header row data.push('Asset', 'Total Value', 'Change % (Week)') list.user_pairs.each do |user_pair| data.push(user_pair.symbol) data.push(user_pair.valuation.format) data.push(user_pair.perchant_change_week.to_s) total += user_pair.valuation end data.push('', '', '') data.push('TOTAL:', total.format, '') data.push('', '', '') print_arrays(data, 3) end
[ "def", "pretty_print_user_list", "(", "list", ")", "total", "=", "0", "data", "=", "[", "]", "# Header row", "data", ".", "push", "(", "'Asset'", ",", "'Total Value'", ",", "'Change % (Week)'", ")", "list", ".", "user_pairs", ".", "each", "do", "|", "user_pair", "|", "data", ".", "push", "(", "user_pair", ".", "symbol", ")", "data", ".", "push", "(", "user_pair", ".", "valuation", ".", "format", ")", "data", ".", "push", "(", "user_pair", ".", "perchant_change_week", ".", "to_s", ")", "total", "+=", "user_pair", ".", "valuation", "end", "data", ".", "push", "(", "''", ",", "''", ",", "''", ")", "data", ".", "push", "(", "'TOTAL:'", ",", "total", ".", "format", ",", "''", ")", "data", ".", "push", "(", "''", ",", "''", ",", "''", ")", "print_arrays", "(", "data", ",", "3", ")", "end" ]
Prints out a summary of the user's hodlings formatted nicely
[ "Prints", "out", "a", "summary", "of", "the", "user", "s", "hodlings", "formatted", "nicely" ]
1316fd069f502fa04fe15bc6ab7e63302aa29fd8
https://github.com/tnorthb/coinstack/blob/1316fd069f502fa04fe15bc6ab7e63302aa29fd8/lib/coinstack/printer.rb#L13-L29
6,309
tnorthb/coinstack
lib/coinstack/printer.rb
Coinstack.Printer.print_arrays
def print_arrays(data, cols) formatted_list = cli.list(data, :uneven_columns_across, cols) cli.say(formatted_list) end
ruby
def print_arrays(data, cols) formatted_list = cli.list(data, :uneven_columns_across, cols) cli.say(formatted_list) end
[ "def", "print_arrays", "(", "data", ",", "cols", ")", "formatted_list", "=", "cli", ".", "list", "(", "data", ",", ":uneven_columns_across", ",", "cols", ")", "cli", ".", "say", "(", "formatted_list", ")", "end" ]
Data should be an array of arays, cols is the number of columns it has Prints the data to screen with equal spacing between them
[ "Data", "should", "be", "an", "array", "of", "arays", "cols", "is", "the", "number", "of", "columns", "it", "has", "Prints", "the", "data", "to", "screen", "with", "equal", "spacing", "between", "them" ]
1316fd069f502fa04fe15bc6ab7e63302aa29fd8
https://github.com/tnorthb/coinstack/blob/1316fd069f502fa04fe15bc6ab7e63302aa29fd8/lib/coinstack/printer.rb#L33-L36
6,310
tnorthb/coinstack
lib/coinstack/printer.rb
Coinstack.Printer.array_char_length
def array_char_length(input_array) length = 0 input_array.each do |a| length += a.to_s.length end length end
ruby
def array_char_length(input_array) length = 0 input_array.each do |a| length += a.to_s.length end length end
[ "def", "array_char_length", "(", "input_array", ")", "length", "=", "0", "input_array", ".", "each", "do", "|", "a", "|", "length", "+=", "a", ".", "to_s", ".", "length", "end", "length", "end" ]
Returns the combined length of charaters in an array
[ "Returns", "the", "combined", "length", "of", "charaters", "in", "an", "array" ]
1316fd069f502fa04fe15bc6ab7e63302aa29fd8
https://github.com/tnorthb/coinstack/blob/1316fd069f502fa04fe15bc6ab7e63302aa29fd8/lib/coinstack/printer.rb#L43-L49
6,311
remote-exec/context-filters
lib/context-filters/filters/filters.rb
ContextFilters::Filters.Filters.select_filters
def select_filters(target, options) found = filters_store.fetch(options, []) if Hash === options || options.nil? then options ||={} options.merge!(:target => target) found += # can not @filters.fetch(options, []) to allow filters provide custom ==() filters_store.select do |filter_options, filters| options == filter_options end.map(&:last).flatten end found end
ruby
def select_filters(target, options) found = filters_store.fetch(options, []) if Hash === options || options.nil? then options ||={} options.merge!(:target => target) found += # can not @filters.fetch(options, []) to allow filters provide custom ==() filters_store.select do |filter_options, filters| options == filter_options end.map(&:last).flatten end found end
[ "def", "select_filters", "(", "target", ",", "options", ")", "found", "=", "filters_store", ".", "fetch", "(", "options", ",", "[", "]", ")", "if", "Hash", "===", "options", "||", "options", ".", "nil?", "then", "options", "||=", "{", "}", "options", ".", "merge!", "(", ":target", "=>", "target", ")", "found", "+=", "# can not @filters.fetch(options, []) to allow filters provide custom ==()", "filters_store", ".", "select", "do", "|", "filter_options", ",", "filters", "|", "options", "==", "filter_options", "end", ".", "map", "(", ":last", ")", ".", "flatten", "end", "found", "end" ]
Select matching filters and filters including targets when options is a +Hash+ @param target [Object] an object to run the method on @param options [Object] a filter for selecting matching blocks
[ "Select", "matching", "filters", "and", "filters", "including", "targets", "when", "options", "is", "a", "+", "Hash", "+" ]
66b54fc6c46b224321713b608d70bba3afde9902
https://github.com/remote-exec/context-filters/blob/66b54fc6c46b224321713b608d70bba3afde9902/lib/context-filters/filters/filters.rb#L54-L68
6,312
modernistik/parse-stack-async
lib/parse/stack/async.rb
Parse.Object.save_eventually
def save_eventually block = block_given? ? Proc.new : nil _self = self Parse::Stack::Async.run do begin result = true _self.save! rescue => e result = false puts "[SaveEventually] Failed for object #{_self.parse_class}##{_self.id}: #{e}" ensure block.call(result) if block block = nil _self = nil end # begin end # do end
ruby
def save_eventually block = block_given? ? Proc.new : nil _self = self Parse::Stack::Async.run do begin result = true _self.save! rescue => e result = false puts "[SaveEventually] Failed for object #{_self.parse_class}##{_self.id}: #{e}" ensure block.call(result) if block block = nil _self = nil end # begin end # do end
[ "def", "save_eventually", "block", "=", "block_given?", "?", "Proc", ".", "new", ":", "nil", "_self", "=", "self", "Parse", "::", "Stack", "::", "Async", ".", "run", "do", "begin", "result", "=", "true", "_self", ".", "save!", "rescue", "=>", "e", "result", "=", "false", "puts", "\"[SaveEventually] Failed for object #{_self.parse_class}##{_self.id}: #{e}\"", "ensure", "block", ".", "call", "(", "result", ")", "if", "block", "block", "=", "nil", "_self", "=", "nil", "end", "# begin", "end", "# do", "end" ]
Adds support for saving a Parse object in the background. @example object.save_eventually do |success| puts "Saved successfully" if success end @yield A block to call after the save has completed. @yieldparam [Boolean] success whether the save was successful. @return [Boolean] whether the job was enqueued.
[ "Adds", "support", "for", "saving", "a", "Parse", "object", "in", "the", "background", "." ]
24f79f0d79c1f2d3f8c561242c4528ac878143a8
https://github.com/modernistik/parse-stack-async/blob/24f79f0d79c1f2d3f8c561242c4528ac878143a8/lib/parse/stack/async.rb#L66-L82
6,313
modernistik/parse-stack-async
lib/parse/stack/async.rb
Parse.Object.destroy_eventually
def destroy_eventually block = block_given? ? Proc.new : nil _self = self Parse::Stack::Async.run do begin result = true _self.destroy rescue => e result = false puts "[DestroyEventually] Failed for object #{_self.parse_class}##{_self.id}: #{e}" ensure block.call(result) if block block = nil _self = nil end # begin end # do end
ruby
def destroy_eventually block = block_given? ? Proc.new : nil _self = self Parse::Stack::Async.run do begin result = true _self.destroy rescue => e result = false puts "[DestroyEventually] Failed for object #{_self.parse_class}##{_self.id}: #{e}" ensure block.call(result) if block block = nil _self = nil end # begin end # do end
[ "def", "destroy_eventually", "block", "=", "block_given?", "?", "Proc", ".", "new", ":", "nil", "_self", "=", "self", "Parse", "::", "Stack", "::", "Async", ".", "run", "do", "begin", "result", "=", "true", "_self", ".", "destroy", "rescue", "=>", "e", "result", "=", "false", "puts", "\"[DestroyEventually] Failed for object #{_self.parse_class}##{_self.id}: #{e}\"", "ensure", "block", ".", "call", "(", "result", ")", "if", "block", "block", "=", "nil", "_self", "=", "nil", "end", "# begin", "end", "# do", "end" ]
save_eventually Adds support for deleting a Parse object in the background. @example object.destroy_eventually do |success| puts 'Deleted successfully' if success end @yield A block to call after the deletion has completed. @yieldparam [Boolean] success whether the save was successful.' @return [Boolean] whether the job was enqueued.
[ "save_eventually", "Adds", "support", "for", "deleting", "a", "Parse", "object", "in", "the", "background", "." ]
24f79f0d79c1f2d3f8c561242c4528ac878143a8
https://github.com/modernistik/parse-stack-async/blob/24f79f0d79c1f2d3f8c561242c4528ac878143a8/lib/parse/stack/async.rb#L92-L108
6,314
Raybeam/myreplicator
lib/exporter/mysql_exporter.rb
Myreplicator.MysqlExporter.export_table
def export_table export_obj @export_obj = export_obj ExportMetadata.record(:table => @export_obj.table_name, :database => @export_obj.source_schema, :export_to => load_to, :export_id => @export_obj.id, :filepath => filepath, :store_in => @export_obj.s3_path, :incremental_col => @export_obj.incremental_column) do |metadata| prepare metadata if (@export_obj.export_type? == :new && load_to == "mysql") || load_to == "mysql" on_failure_state_trans(metadata, "new") # If failed, go back to new on_export_success(metadata) initial_export metadata elsif @export_obj.export_type? == :incremental || load_to == "vertica" on_failure_state_trans(metadata, "failed") # Set state trans on failure on_export_success(metadata) incremental_export_into_outfile metadata end end # metadata end
ruby
def export_table export_obj @export_obj = export_obj ExportMetadata.record(:table => @export_obj.table_name, :database => @export_obj.source_schema, :export_to => load_to, :export_id => @export_obj.id, :filepath => filepath, :store_in => @export_obj.s3_path, :incremental_col => @export_obj.incremental_column) do |metadata| prepare metadata if (@export_obj.export_type? == :new && load_to == "mysql") || load_to == "mysql" on_failure_state_trans(metadata, "new") # If failed, go back to new on_export_success(metadata) initial_export metadata elsif @export_obj.export_type? == :incremental || load_to == "vertica" on_failure_state_trans(metadata, "failed") # Set state trans on failure on_export_success(metadata) incremental_export_into_outfile metadata end end # metadata end
[ "def", "export_table", "export_obj", "@export_obj", "=", "export_obj", "ExportMetadata", ".", "record", "(", ":table", "=>", "@export_obj", ".", "table_name", ",", ":database", "=>", "@export_obj", ".", "source_schema", ",", ":export_to", "=>", "load_to", ",", ":export_id", "=>", "@export_obj", ".", "id", ",", ":filepath", "=>", "filepath", ",", ":store_in", "=>", "@export_obj", ".", "s3_path", ",", ":incremental_col", "=>", "@export_obj", ".", "incremental_column", ")", "do", "|", "metadata", "|", "prepare", "metadata", "if", "(", "@export_obj", ".", "export_type?", "==", ":new", "&&", "load_to", "==", "\"mysql\"", ")", "||", "load_to", "==", "\"mysql\"", "on_failure_state_trans", "(", "metadata", ",", "\"new\"", ")", "# If failed, go back to new", "on_export_success", "(", "metadata", ")", "initial_export", "metadata", "elsif", "@export_obj", ".", "export_type?", "==", ":incremental", "||", "load_to", "==", "\"vertica\"", "on_failure_state_trans", "(", "metadata", ",", "\"failed\"", ")", "# Set state trans on failure", "on_export_success", "(", "metadata", ")", "incremental_export_into_outfile", "metadata", "end", "end", "# metadata", "end" ]
Gets an Export object and dumps the data Initially using mysqldump Incrementally using mysql -e afterwards
[ "Gets", "an", "Export", "object", "and", "dumps", "the", "data", "Initially", "using", "mysqldump", "Incrementally", "using", "mysql", "-", "e", "afterwards" ]
470938e70f46886b525c65a4a464b4cf8383d00d
https://github.com/Raybeam/myreplicator/blob/470938e70f46886b525c65a4a464b4cf8383d00d/lib/exporter/mysql_exporter.rb#L13-L37
6,315
Raybeam/myreplicator
lib/exporter/mysql_exporter.rb
Myreplicator.MysqlExporter.initial_export
def initial_export metadata metadata.export_type = "initial" max_value = @export_obj.max_value if @export_obj.incremental_export? cmd = initial_mysqldump_cmd exporting_state_trans # mark exporting puts "Exporting..." result = execute_export(cmd, metadata) check_result(result, 0) @export_obj.update_max_val(max_value) if @export_obj.incremental_export? end
ruby
def initial_export metadata metadata.export_type = "initial" max_value = @export_obj.max_value if @export_obj.incremental_export? cmd = initial_mysqldump_cmd exporting_state_trans # mark exporting puts "Exporting..." result = execute_export(cmd, metadata) check_result(result, 0) @export_obj.update_max_val(max_value) if @export_obj.incremental_export? end
[ "def", "initial_export", "metadata", "metadata", ".", "export_type", "=", "\"initial\"", "max_value", "=", "@export_obj", ".", "max_value", "if", "@export_obj", ".", "incremental_export?", "cmd", "=", "initial_mysqldump_cmd", "exporting_state_trans", "# mark exporting", "puts", "\"Exporting...\"", "result", "=", "execute_export", "(", "cmd", ",", "metadata", ")", "check_result", "(", "result", ",", "0", ")", "@export_obj", ".", "update_max_val", "(", "max_value", ")", "if", "@export_obj", ".", "incremental_export?", "end" ]
Exports Table using mysqldump. This method is invoked only once. Dumps with create options, no need to create table manaully
[ "Exports", "Table", "using", "mysqldump", ".", "This", "method", "is", "invoked", "only", "once", ".", "Dumps", "with", "create", "options", "no", "need", "to", "create", "table", "manaully" ]
470938e70f46886b525c65a4a464b4cf8383d00d
https://github.com/Raybeam/myreplicator/blob/470938e70f46886b525c65a4a464b4cf8383d00d/lib/exporter/mysql_exporter.rb#L72-L83
6,316
Raybeam/myreplicator
lib/exporter/mysql_exporter.rb
Myreplicator.MysqlExporter.incremental_export_into_outfile
def incremental_export_into_outfile metadata unless @export_obj.is_running? if @export_obj.export_type == "incremental" max_value = @export_obj.max_value metadata.export_type = "incremental" @export_obj.update_max_val if @export_obj.max_incremental_value.blank? end if (@export_obj.export_type == "all" && @export_obj.export_to == "vertica") metadata.export_type = "incremental" end options = { :db => @export_obj.source_schema, :source_schema => @export_obj.source_schema, :table => @export_obj.table_name, :filepath => filepath, :destination_schema => @export_obj.destination_schema, :enclosed_by => Myreplicator.configs[@export_obj.source_schema]["enclosed_by"], :export_id => @export_obj.id } schema_status = Myreplicator::MysqlExporter.schema_changed?(options) Kernel.p "===== schema_status =====" Kernel.p schema_status if schema_status[:changed] # && new? metadata.export_type = "initial" else options[:incremental_col] = @export_obj.incremental_column options[:incremental_col_type] = @export_obj.incremental_column_type options[:export_type] = @export_obj.export_type options[:incremental_val] = [@export_obj.destination_max_incremental_value, @export_obj.max_incremental_value].min #options[:incremental_val] = @export_obj.max_incremental_value end #Kernel.p "===== incremental_export_into_outfile OPTIONS =====" #Kernel.p options cmd = SqlCommands.mysql_export_outfile(options) #Kernel.p "===== incremental_export_into_outfile CMD =====" #puts cmd exporting_state_trans puts "Exporting..." result = execute_export(cmd, metadata) check_result(result, 0) if @export_obj.export_type == "incremental" metadata.incremental_val = max_value # store max val in metadata @export_obj.update_max_val(max_value) # update max value if export was successful end end return false end
ruby
def incremental_export_into_outfile metadata unless @export_obj.is_running? if @export_obj.export_type == "incremental" max_value = @export_obj.max_value metadata.export_type = "incremental" @export_obj.update_max_val if @export_obj.max_incremental_value.blank? end if (@export_obj.export_type == "all" && @export_obj.export_to == "vertica") metadata.export_type = "incremental" end options = { :db => @export_obj.source_schema, :source_schema => @export_obj.source_schema, :table => @export_obj.table_name, :filepath => filepath, :destination_schema => @export_obj.destination_schema, :enclosed_by => Myreplicator.configs[@export_obj.source_schema]["enclosed_by"], :export_id => @export_obj.id } schema_status = Myreplicator::MysqlExporter.schema_changed?(options) Kernel.p "===== schema_status =====" Kernel.p schema_status if schema_status[:changed] # && new? metadata.export_type = "initial" else options[:incremental_col] = @export_obj.incremental_column options[:incremental_col_type] = @export_obj.incremental_column_type options[:export_type] = @export_obj.export_type options[:incremental_val] = [@export_obj.destination_max_incremental_value, @export_obj.max_incremental_value].min #options[:incremental_val] = @export_obj.max_incremental_value end #Kernel.p "===== incremental_export_into_outfile OPTIONS =====" #Kernel.p options cmd = SqlCommands.mysql_export_outfile(options) #Kernel.p "===== incremental_export_into_outfile CMD =====" #puts cmd exporting_state_trans puts "Exporting..." result = execute_export(cmd, metadata) check_result(result, 0) if @export_obj.export_type == "incremental" metadata.incremental_val = max_value # store max val in metadata @export_obj.update_max_val(max_value) # update max value if export was successful end end return false end
[ "def", "incremental_export_into_outfile", "metadata", "unless", "@export_obj", ".", "is_running?", "if", "@export_obj", ".", "export_type", "==", "\"incremental\"", "max_value", "=", "@export_obj", ".", "max_value", "metadata", ".", "export_type", "=", "\"incremental\"", "@export_obj", ".", "update_max_val", "if", "@export_obj", ".", "max_incremental_value", ".", "blank?", "end", "if", "(", "@export_obj", ".", "export_type", "==", "\"all\"", "&&", "@export_obj", ".", "export_to", "==", "\"vertica\"", ")", "metadata", ".", "export_type", "=", "\"incremental\"", "end", "options", "=", "{", ":db", "=>", "@export_obj", ".", "source_schema", ",", ":source_schema", "=>", "@export_obj", ".", "source_schema", ",", ":table", "=>", "@export_obj", ".", "table_name", ",", ":filepath", "=>", "filepath", ",", ":destination_schema", "=>", "@export_obj", ".", "destination_schema", ",", ":enclosed_by", "=>", "Myreplicator", ".", "configs", "[", "@export_obj", ".", "source_schema", "]", "[", "\"enclosed_by\"", "]", ",", ":export_id", "=>", "@export_obj", ".", "id", "}", "schema_status", "=", "Myreplicator", "::", "MysqlExporter", ".", "schema_changed?", "(", "options", ")", "Kernel", ".", "p", "\"===== schema_status =====\"", "Kernel", ".", "p", "schema_status", "if", "schema_status", "[", ":changed", "]", "# && new?", "metadata", ".", "export_type", "=", "\"initial\"", "else", "options", "[", ":incremental_col", "]", "=", "@export_obj", ".", "incremental_column", "options", "[", ":incremental_col_type", "]", "=", "@export_obj", ".", "incremental_column_type", "options", "[", ":export_type", "]", "=", "@export_obj", ".", "export_type", "options", "[", ":incremental_val", "]", "=", "[", "@export_obj", ".", "destination_max_incremental_value", ",", "@export_obj", ".", "max_incremental_value", "]", ".", "min", "#options[:incremental_val] = @export_obj.max_incremental_value", "end", "#Kernel.p \"===== incremental_export_into_outfile OPTIONS =====\"", "#Kernel.p options", "cmd", "=", "SqlCommands", ".", "mysql_export_outfile", "(", "options", ")", "#Kernel.p \"===== incremental_export_into_outfile CMD =====\"", "#puts cmd ", "exporting_state_trans", "puts", "\"Exporting...\"", "result", "=", "execute_export", "(", "cmd", ",", "metadata", ")", "check_result", "(", "result", ",", "0", ")", "if", "@export_obj", ".", "export_type", "==", "\"incremental\"", "metadata", ".", "incremental_val", "=", "max_value", "# store max val in metadata", "@export_obj", ".", "update_max_val", "(", "max_value", ")", "# update max value if export was successful", "end", "end", "return", "false", "end" ]
Exports table incrementally, similar to incremental_export method Dumps file in tmp directory specified in myreplicator.yml Note that directory needs 777 permissions for mysql to be able to export the file Uses \\0 as the delimiter and new line for lines
[ "Exports", "table", "incrementally", "similar", "to", "incremental_export", "method", "Dumps", "file", "in", "tmp", "directory", "specified", "in", "myreplicator", ".", "yml", "Note", "that", "directory", "needs", "777", "permissions", "for", "mysql", "to", "be", "able", "to", "export", "the", "file", "Uses", "\\\\", "0", "as", "the", "delimiter", "and", "new", "line", "for", "lines" ]
470938e70f46886b525c65a4a464b4cf8383d00d
https://github.com/Raybeam/myreplicator/blob/470938e70f46886b525c65a4a464b4cf8383d00d/lib/exporter/mysql_exporter.rb#L110-L162
6,317
Raybeam/myreplicator
lib/exporter/mysql_exporter.rb
Myreplicator.MysqlExporter.check_result
def check_result result, size unless result.nil? raise Exceptions::ExportError.new("Export Error\n#{result}") if result.length > 0 end end
ruby
def check_result result, size unless result.nil? raise Exceptions::ExportError.new("Export Error\n#{result}") if result.length > 0 end end
[ "def", "check_result", "result", ",", "size", "unless", "result", ".", "nil?", "raise", "Exceptions", "::", "ExportError", ".", "new", "(", "\"Export Error\\n#{result}\"", ")", "if", "result", ".", "length", ">", "0", "end", "end" ]
Checks the returned resut from SSH CMD Size specifies if there should be any returned results or not
[ "Checks", "the", "returned", "resut", "from", "SSH", "CMD", "Size", "specifies", "if", "there", "should", "be", "any", "returned", "results", "or", "not" ]
470938e70f46886b525c65a4a464b4cf8383d00d
https://github.com/Raybeam/myreplicator/blob/470938e70f46886b525c65a4a464b4cf8383d00d/lib/exporter/mysql_exporter.rb#L239-L243
6,318
Raybeam/myreplicator
lib/exporter/mysql_exporter.rb
Myreplicator.MysqlExporter.zipfile
def zipfile metadata cmd = "cd #{Myreplicator.configs[@export_obj.source_schema]["ssh_tmp_dir"]}; gzip #{@export_obj.filename}" puts cmd zip_result = metadata.ssh.exec!(cmd) unless zip_result.nil? raise Exceptions::ExportError.new("Export Error\n#{zip_result}") if zip_result.length > 0 end metadata.zipped = true return zip_result end
ruby
def zipfile metadata cmd = "cd #{Myreplicator.configs[@export_obj.source_schema]["ssh_tmp_dir"]}; gzip #{@export_obj.filename}" puts cmd zip_result = metadata.ssh.exec!(cmd) unless zip_result.nil? raise Exceptions::ExportError.new("Export Error\n#{zip_result}") if zip_result.length > 0 end metadata.zipped = true return zip_result end
[ "def", "zipfile", "metadata", "cmd", "=", "\"cd #{Myreplicator.configs[@export_obj.source_schema][\"ssh_tmp_dir\"]}; gzip #{@export_obj.filename}\"", "puts", "cmd", "zip_result", "=", "metadata", ".", "ssh", ".", "exec!", "(", "cmd", ")", "unless", "zip_result", ".", "nil?", "raise", "Exceptions", "::", "ExportError", ".", "new", "(", "\"Export Error\\n#{zip_result}\"", ")", "if", "zip_result", ".", "length", ">", "0", "end", "metadata", ".", "zipped", "=", "true", "return", "zip_result", "end" ]
zips the file on the source DB server
[ "zips", "the", "file", "on", "the", "source", "DB", "server" ]
470938e70f46886b525c65a4a464b4cf8383d00d
https://github.com/Raybeam/myreplicator/blob/470938e70f46886b525c65a4a464b4cf8383d00d/lib/exporter/mysql_exporter.rb#L262-L276
6,319
blotto/thermometer
lib/thermometer/configuration.rb
Thermometer.Configuration.load_time_ranges
def load_time_ranges @time_ranges = ActiveSupport::HashWithIndifferentAccess.new time_ranges = @config['time'] time_ranges.each do |t,r| time_range = ActiveSupport::HashWithIndifferentAccess.new src_ranges ||= r src_ranges.map { |k,v| time_range[k.to_sym] = rangify_time_boundaries(v) } @time_ranges[t.to_sym] = time_range end end
ruby
def load_time_ranges @time_ranges = ActiveSupport::HashWithIndifferentAccess.new time_ranges = @config['time'] time_ranges.each do |t,r| time_range = ActiveSupport::HashWithIndifferentAccess.new src_ranges ||= r src_ranges.map { |k,v| time_range[k.to_sym] = rangify_time_boundaries(v) } @time_ranges[t.to_sym] = time_range end end
[ "def", "load_time_ranges", "@time_ranges", "=", "ActiveSupport", "::", "HashWithIndifferentAccess", ".", "new", "time_ranges", "=", "@config", "[", "'time'", "]", "time_ranges", ".", "each", "do", "|", "t", ",", "r", "|", "time_range", "=", "ActiveSupport", "::", "HashWithIndifferentAccess", ".", "new", "src_ranges", "||=", "r", "src_ranges", ".", "map", "{", "|", "k", ",", "v", "|", "time_range", "[", "k", ".", "to_sym", "]", "=", "rangify_time_boundaries", "(", "v", ")", "}", "@time_ranges", "[", "t", ".", "to_sym", "]", "=", "time_range", "end", "end" ]
Load ranges from config file
[ "Load", "ranges", "from", "config", "file" ]
bb436c4f3b2ebce23aa1ed51d551ab7a165aedfa
https://github.com/blotto/thermometer/blob/bb436c4f3b2ebce23aa1ed51d551ab7a165aedfa/lib/thermometer/configuration.rb#L95-L105
6,320
blotto/thermometer
lib/thermometer/configuration.rb
Thermometer.Configuration.rangify_time_boundaries
def rangify_time_boundaries(src) src.split("..").inject{ |s,e| s.split(".").inject{|n,m| n.to_i.send(m)}..e.split(".").inject{|n,m| n.to_i.send(m) }} end
ruby
def rangify_time_boundaries(src) src.split("..").inject{ |s,e| s.split(".").inject{|n,m| n.to_i.send(m)}..e.split(".").inject{|n,m| n.to_i.send(m) }} end
[ "def", "rangify_time_boundaries", "(", "src", ")", "src", ".", "split", "(", "\"..\"", ")", ".", "inject", "{", "|", "s", ",", "e", "|", "s", ".", "split", "(", "\".\"", ")", ".", "inject", "{", "|", "n", ",", "m", "|", "n", ".", "to_i", ".", "send", "(", "m", ")", "}", "..", "e", ".", "split", "(", "\".\"", ")", ".", "inject", "{", "|", "n", ",", "m", "|", "n", ".", "to_i", ".", "send", "(", "m", ")", "}", "}", "end" ]
Takes a string like "2.days..3.weeks" and converts to Range object -> 2.days..3.weeks
[ "Takes", "a", "string", "like", "2", ".", "days", "..", "3", ".", "weeks", "and", "converts", "to", "Range", "object", "-", ">", "2", ".", "days", "..", "3", ".", "weeks" ]
bb436c4f3b2ebce23aa1ed51d551ab7a165aedfa
https://github.com/blotto/thermometer/blob/bb436c4f3b2ebce23aa1ed51d551ab7a165aedfa/lib/thermometer/configuration.rb#L111-L113
6,321
sanctuarycomputer/appi
app/controllers/concerns/appi/handles_resources.rb
APPI.HandlesResources.klass_for_type
def klass_for_type(type, singular=false) type = type.singularize unless singular type.classify.constantize end
ruby
def klass_for_type(type, singular=false) type = type.singularize unless singular type.classify.constantize end
[ "def", "klass_for_type", "(", "type", ",", "singular", "=", "false", ")", "type", "=", "type", ".", "singularize", "unless", "singular", "type", ".", "classify", ".", "constantize", "end" ]
Resolves the Class for a type. Params: +type+:: +String+ A stringified type. +singular+:: +Boolean+ Pass true if you don't want to singularize the type.
[ "Resolves", "the", "Class", "for", "a", "type", "." ]
5a06f7c090e4fcaaba9060685fa6a6c7434e8436
https://github.com/sanctuarycomputer/appi/blob/5a06f7c090e4fcaaba9060685fa6a6c7434e8436/app/controllers/concerns/appi/handles_resources.rb#L31-L34
6,322
sanctuarycomputer/appi
app/controllers/concerns/appi/handles_resources.rb
APPI.HandlesResources.resource_params
def resource_params attributes = find_in_params(:attributes).try(:permit, permitted_attributes) || {} relationships = {} # Build Relationships Data relationships_in_payload = find_in_params(:relationships) if relationships_in_payload raw_relationships = relationships_in_payload.clone raw_relationships.each_key do |key| data = raw_relationships.delete(key)[:data] if permitted_relationships.include?(key.to_sym) && data if data.kind_of?(Array) relationships["#{key.singularize}_ids"] = extract_ids data else relationships["#{key}_id"] = extract_id data end end end end attributes.merge relationships end
ruby
def resource_params attributes = find_in_params(:attributes).try(:permit, permitted_attributes) || {} relationships = {} # Build Relationships Data relationships_in_payload = find_in_params(:relationships) if relationships_in_payload raw_relationships = relationships_in_payload.clone raw_relationships.each_key do |key| data = raw_relationships.delete(key)[:data] if permitted_relationships.include?(key.to_sym) && data if data.kind_of?(Array) relationships["#{key.singularize}_ids"] = extract_ids data else relationships["#{key}_id"] = extract_id data end end end end attributes.merge relationships end
[ "def", "resource_params", "attributes", "=", "find_in_params", "(", ":attributes", ")", ".", "try", "(", ":permit", ",", "permitted_attributes", ")", "||", "{", "}", "relationships", "=", "{", "}", "# Build Relationships Data", "relationships_in_payload", "=", "find_in_params", "(", ":relationships", ")", "if", "relationships_in_payload", "raw_relationships", "=", "relationships_in_payload", ".", "clone", "raw_relationships", ".", "each_key", "do", "|", "key", "|", "data", "=", "raw_relationships", ".", "delete", "(", "key", ")", "[", ":data", "]", "if", "permitted_relationships", ".", "include?", "(", "key", ".", "to_sym", ")", "&&", "data", "if", "data", ".", "kind_of?", "(", "Array", ")", "relationships", "[", "\"#{key.singularize}_ids\"", "]", "=", "extract_ids", "data", "else", "relationships", "[", "\"#{key}_id\"", "]", "=", "extract_id", "data", "end", "end", "end", "end", "attributes", ".", "merge", "relationships", "end" ]
Builds a whitelisted resource_params hash from the permitted_attributes & permitted_relationships arrays. Will automatically attempt to resolve string IDs to numerical IDs, in the case the model's slug was passed to the controller as ID.
[ "Builds", "a", "whitelisted", "resource_params", "hash", "from", "the", "permitted_attributes", "&", "permitted_relationships", "arrays", ".", "Will", "automatically", "attempt", "to", "resolve", "string", "IDs", "to", "numerical", "IDs", "in", "the", "case", "the", "model", "s", "slug", "was", "passed", "to", "the", "controller", "as", "ID", "." ]
5a06f7c090e4fcaaba9060685fa6a6c7434e8436
https://github.com/sanctuarycomputer/appi/blob/5a06f7c090e4fcaaba9060685fa6a6c7434e8436/app/controllers/concerns/appi/handles_resources.rb#L108-L131
6,323
richard-viney/lightstreamer
lib/lightstreamer/stream_connection_header.rb
Lightstreamer.StreamConnectionHeader.process_line
def process_line(line) @lines << line return process_success if @lines.first == 'OK' return process_error if @lines.first == 'ERROR' return process_end if @lines.first == 'END' return process_sync_error if @lines.first == 'SYNC ERROR' process_unrecognized end
ruby
def process_line(line) @lines << line return process_success if @lines.first == 'OK' return process_error if @lines.first == 'ERROR' return process_end if @lines.first == 'END' return process_sync_error if @lines.first == 'SYNC ERROR' process_unrecognized end
[ "def", "process_line", "(", "line", ")", "@lines", "<<", "line", "return", "process_success", "if", "@lines", ".", "first", "==", "'OK'", "return", "process_error", "if", "@lines", ".", "first", "==", "'ERROR'", "return", "process_end", "if", "@lines", ".", "first", "==", "'END'", "return", "process_sync_error", "if", "@lines", ".", "first", "==", "'SYNC ERROR'", "process_unrecognized", "end" ]
Processes a single line of header information. The return value indicates whether further data is required in order to complete the header. @param [String] line The line of header data to process. @return [Boolean] Whether the header is still incomplete and requires further data.
[ "Processes", "a", "single", "line", "of", "header", "information", ".", "The", "return", "value", "indicates", "whether", "further", "data", "is", "required", "in", "order", "to", "complete", "the", "header", "." ]
7be6350bd861495a52ca35a8640a1e6df34cf9d1
https://github.com/richard-viney/lightstreamer/blob/7be6350bd861495a52ca35a8640a1e6df34cf9d1/lib/lightstreamer/stream_connection_header.rb#L24-L33
6,324
vpacher/xpay
lib/xpay/transaction_query.rb
Xpay.TransactionQuery.create_request
def create_request raise AttributeMissing.new "(2500) TransactionReference or OrderReference need to be present." if (transaction_reference.nil? && order_reference.nil?) raise AttributeMissing.new "(2500) SiteReference must be present." if (site_reference.nil? && (REXML::XPath.first(@request_xml, "//SiteReference").text.blank? rescue true)) REXML::XPath.first(@request_xml, "//Request").attributes["Type"] = "TRANSACTIONQUERY" ops = REXML::XPath.first(@request_xml, "//Operation") ["TermUrl", "MerchantName", "Currency", "SettlementDay"].each { |e| ops.delete_element e } (ops.elements["SiteReference"] || ops.add_element("SiteReference")).text = self.site_reference if self.site_reference (ops.elements["TransactionReference"] || ops.add_element("TransactionReference")).text = self.transaction_reference if self.transaction_reference order = REXML::XPath.first(@request_xml, "//Operation") (order.elements["OrderReference"] || order.add_element("OrderReference")).text = self.order_reference if self.order_reference root = @request_xml.root (root.elements["Certificate"] || root.add_element("Certificate")).text = self.site_alias if self.site_alias end
ruby
def create_request raise AttributeMissing.new "(2500) TransactionReference or OrderReference need to be present." if (transaction_reference.nil? && order_reference.nil?) raise AttributeMissing.new "(2500) SiteReference must be present." if (site_reference.nil? && (REXML::XPath.first(@request_xml, "//SiteReference").text.blank? rescue true)) REXML::XPath.first(@request_xml, "//Request").attributes["Type"] = "TRANSACTIONQUERY" ops = REXML::XPath.first(@request_xml, "//Operation") ["TermUrl", "MerchantName", "Currency", "SettlementDay"].each { |e| ops.delete_element e } (ops.elements["SiteReference"] || ops.add_element("SiteReference")).text = self.site_reference if self.site_reference (ops.elements["TransactionReference"] || ops.add_element("TransactionReference")).text = self.transaction_reference if self.transaction_reference order = REXML::XPath.first(@request_xml, "//Operation") (order.elements["OrderReference"] || order.add_element("OrderReference")).text = self.order_reference if self.order_reference root = @request_xml.root (root.elements["Certificate"] || root.add_element("Certificate")).text = self.site_alias if self.site_alias end
[ "def", "create_request", "raise", "AttributeMissing", ".", "new", "\"(2500) TransactionReference or OrderReference need to be present.\"", "if", "(", "transaction_reference", ".", "nil?", "&&", "order_reference", ".", "nil?", ")", "raise", "AttributeMissing", ".", "new", "\"(2500) SiteReference must be present.\"", "if", "(", "site_reference", ".", "nil?", "&&", "(", "REXML", "::", "XPath", ".", "first", "(", "@request_xml", ",", "\"//SiteReference\"", ")", ".", "text", ".", "blank?", "rescue", "true", ")", ")", "REXML", "::", "XPath", ".", "first", "(", "@request_xml", ",", "\"//Request\"", ")", ".", "attributes", "[", "\"Type\"", "]", "=", "\"TRANSACTIONQUERY\"", "ops", "=", "REXML", "::", "XPath", ".", "first", "(", "@request_xml", ",", "\"//Operation\"", ")", "[", "\"TermUrl\"", ",", "\"MerchantName\"", ",", "\"Currency\"", ",", "\"SettlementDay\"", "]", ".", "each", "{", "|", "e", "|", "ops", ".", "delete_element", "e", "}", "(", "ops", ".", "elements", "[", "\"SiteReference\"", "]", "||", "ops", ".", "add_element", "(", "\"SiteReference\"", ")", ")", ".", "text", "=", "self", ".", "site_reference", "if", "self", ".", "site_reference", "(", "ops", ".", "elements", "[", "\"TransactionReference\"", "]", "||", "ops", ".", "add_element", "(", "\"TransactionReference\"", ")", ")", ".", "text", "=", "self", ".", "transaction_reference", "if", "self", ".", "transaction_reference", "order", "=", "REXML", "::", "XPath", ".", "first", "(", "@request_xml", ",", "\"//Operation\"", ")", "(", "order", ".", "elements", "[", "\"OrderReference\"", "]", "||", "order", ".", "add_element", "(", "\"OrderReference\"", ")", ")", ".", "text", "=", "self", ".", "order_reference", "if", "self", ".", "order_reference", "root", "=", "@request_xml", ".", "root", "(", "root", ".", "elements", "[", "\"Certificate\"", "]", "||", "root", ".", "add_element", "(", "\"Certificate\"", ")", ")", ".", "text", "=", "self", ".", "site_alias", "if", "self", ".", "site_alias", "end" ]
Write the xml document needed for processing, fill in elements need and delete unused ones from the root_xml raises an error if any necessary elements are missing
[ "Write", "the", "xml", "document", "needed", "for", "processing", "fill", "in", "elements", "need", "and", "delete", "unused", "ones", "from", "the", "root_xml", "raises", "an", "error", "if", "any", "necessary", "elements", "are", "missing" ]
58c0b0f2600ed30ff44b84f97b96c74590474f3f
https://github.com/vpacher/xpay/blob/58c0b0f2600ed30ff44b84f97b96c74590474f3f/lib/xpay/transaction_query.rb#L43-L55
6,325
subimage/cashboard-rb
lib/cashboard/time_entry.rb
Cashboard.TimeEntry.toggle_timer
def toggle_timer options = self.class.merge_options() options.merge!({:body => self.to_xml}) response = self.class.put(self.links[:toggle_timer], options) # Raise special errors if not a success self.class.check_status_code(response) # Re-initialize ourselves with information from response initialize(response.parsed_response) if self.stopped_timer stopped_timer = Cashboard::Struct.new(self.stopped_timer) end stopped_timer || nil end
ruby
def toggle_timer options = self.class.merge_options() options.merge!({:body => self.to_xml}) response = self.class.put(self.links[:toggle_timer], options) # Raise special errors if not a success self.class.check_status_code(response) # Re-initialize ourselves with information from response initialize(response.parsed_response) if self.stopped_timer stopped_timer = Cashboard::Struct.new(self.stopped_timer) end stopped_timer || nil end
[ "def", "toggle_timer", "options", "=", "self", ".", "class", ".", "merge_options", "(", ")", "options", ".", "merge!", "(", "{", ":body", "=>", "self", ".", "to_xml", "}", ")", "response", "=", "self", ".", "class", ".", "put", "(", "self", ".", "links", "[", ":toggle_timer", "]", ",", "options", ")", "# Raise special errors if not a success", "self", ".", "class", ".", "check_status_code", "(", "response", ")", "# Re-initialize ourselves with information from response", "initialize", "(", "response", ".", "parsed_response", ")", "if", "self", ".", "stopped_timer", "stopped_timer", "=", "Cashboard", "::", "Struct", ".", "new", "(", "self", ".", "stopped_timer", ")", "end", "stopped_timer", "||", "nil", "end" ]
readonly Starts or stops timer depending on its current state. Will return an object of Cashboard::Struct if another timer was stopped during this toggle operation. Will return nil if no timer was stopped.
[ "readonly", "Starts", "or", "stops", "timer", "depending", "on", "its", "current", "state", "." ]
320e311ea1549cdd0dada0f8a0a4f9942213b28f
https://github.com/subimage/cashboard-rb/blob/320e311ea1549cdd0dada0f8a0a4f9942213b28f/lib/cashboard/time_entry.rb#L20-L36
6,326
mbj/ducktrap
lib/ducktrap/error.rb
Ducktrap.Error.dump
def dump(output) output.name(self) output.attribute(:input, input) output.nest(:context, context) end
ruby
def dump(output) output.name(self) output.attribute(:input, input) output.nest(:context, context) end
[ "def", "dump", "(", "output", ")", "output", ".", "name", "(", "self", ")", "output", ".", "attribute", "(", ":input", ",", "input", ")", "output", ".", "nest", "(", ":context", ",", "context", ")", "end" ]
Dump state to output @param [Formatter] formatter @return [undefined] @api private
[ "Dump", "state", "to", "output" ]
482d874d3eb43b2dbb518b8537851d742d785903
https://github.com/mbj/ducktrap/blob/482d874d3eb43b2dbb518b8537851d742d785903/lib/ducktrap/error.rb#L17-L21
6,327
raid5/agilezen
lib/agilezen/stories.rb
AgileZen.Stories.project_story
def project_story(project_id, story_id, options={}) response_body = nil begin response = connection.get do |req| req.url "/api/v1/projects/#{project_id}/story/#{story_id}", options end response_body = response.body rescue MultiJson::DecodeError => e #p 'Unable to parse JSON.' end response_body end
ruby
def project_story(project_id, story_id, options={}) response_body = nil begin response = connection.get do |req| req.url "/api/v1/projects/#{project_id}/story/#{story_id}", options end response_body = response.body rescue MultiJson::DecodeError => e #p 'Unable to parse JSON.' end response_body end
[ "def", "project_story", "(", "project_id", ",", "story_id", ",", "options", "=", "{", "}", ")", "response_body", "=", "nil", "begin", "response", "=", "connection", ".", "get", "do", "|", "req", "|", "req", ".", "url", "\"/api/v1/projects/#{project_id}/story/#{story_id}\"", ",", "options", "end", "response_body", "=", "response", ".", "body", "rescue", "MultiJson", "::", "DecodeError", "=>", "e", "#p 'Unable to parse JSON.'", "end", "response_body", "end" ]
Retrieve information for an individual story of a given project.
[ "Retrieve", "information", "for", "an", "individual", "story", "of", "a", "given", "project", "." ]
36fcef642c82b35c8c8664ee6a2ff22ce52054c0
https://github.com/raid5/agilezen/blob/36fcef642c82b35c8c8664ee6a2ff22ce52054c0/lib/agilezen/stories.rb#L21-L33
6,328
twohlix/database_cached_attribute
lib/database_cached_attribute.rb
DatabaseCachedAttribute.ClassMethods.database_cached_attribute
def database_cached_attribute(*attrs) attrs.each do |attr| define_method("invalidate_#{attr}") do |arg=nil| # default arg to allow before_blah callbacks invalidate_cache attr.to_sym end define_method("only_#{attr}_changed?") do only_change? attr.to_sym end define_method("cache_#{attr}") do update_cache attr.to_sym end end end
ruby
def database_cached_attribute(*attrs) attrs.each do |attr| define_method("invalidate_#{attr}") do |arg=nil| # default arg to allow before_blah callbacks invalidate_cache attr.to_sym end define_method("only_#{attr}_changed?") do only_change? attr.to_sym end define_method("cache_#{attr}") do update_cache attr.to_sym end end end
[ "def", "database_cached_attribute", "(", "*", "attrs", ")", "attrs", ".", "each", "do", "|", "attr", "|", "define_method", "(", "\"invalidate_#{attr}\"", ")", "do", "|", "arg", "=", "nil", "|", "# default arg to allow before_blah callbacks", "invalidate_cache", "attr", ".", "to_sym", "end", "define_method", "(", "\"only_#{attr}_changed?\"", ")", "do", "only_change?", "attr", ".", "to_sym", "end", "define_method", "(", "\"cache_#{attr}\"", ")", "do", "update_cache", "attr", ".", "to_sym", "end", "end", "end" ]
Sets up cache invalidation callbacks for the provided attributes
[ "Sets", "up", "cache", "invalidation", "callbacks", "for", "the", "provided", "attributes" ]
9aee710f10062eb0ffa918310183aaabaeaffa04
https://github.com/twohlix/database_cached_attribute/blob/9aee710f10062eb0ffa918310183aaabaeaffa04/lib/database_cached_attribute.rb#L62-L76
6,329
midas/nameable_record
lib/nameable_record/name.rb
NameableRecord.Name.to_s
def to_s( pattern='%l, %f' ) if pattern.is_a?( Symbol ) return conversational if pattern == :conversational return sortable if pattern == :sortable pattern = PREDEFINED_PATTERNS[pattern] end PATTERN_MAP.inject( pattern ) do |name, mapping| name = name.gsub( mapping.first, (send( mapping.last ) || '') ) end end
ruby
def to_s( pattern='%l, %f' ) if pattern.is_a?( Symbol ) return conversational if pattern == :conversational return sortable if pattern == :sortable pattern = PREDEFINED_PATTERNS[pattern] end PATTERN_MAP.inject( pattern ) do |name, mapping| name = name.gsub( mapping.first, (send( mapping.last ) || '') ) end end
[ "def", "to_s", "(", "pattern", "=", "'%l, %f'", ")", "if", "pattern", ".", "is_a?", "(", "Symbol", ")", "return", "conversational", "if", "pattern", "==", ":conversational", "return", "sortable", "if", "pattern", "==", ":sortable", "pattern", "=", "PREDEFINED_PATTERNS", "[", "pattern", "]", "end", "PATTERN_MAP", ".", "inject", "(", "pattern", ")", "do", "|", "name", ",", "mapping", "|", "name", "=", "name", ".", "gsub", "(", "mapping", ".", "first", ",", "(", "send", "(", "mapping", ".", "last", ")", "||", "''", ")", ")", "end", "end" ]
Creates a name based on pattern provided. Defaults to last, first. Symbols: %l - last name %f - first name %m - middle name %p - prefix %s - suffix
[ "Creates", "a", "name", "based", "on", "pattern", "provided", ".", "Defaults", "to", "last", "first", "." ]
a8a6689151bff1e7448baeffbd9ee603989a708e
https://github.com/midas/nameable_record/blob/a8a6689151bff1e7448baeffbd9ee603989a708e/lib/nameable_record/name.rb#L38-L49
6,330
midas/nameable_record
lib/nameable_record/name.rb
NameableRecord.Name.sortable
def sortable [ last, [ prefix, first, middle, suffix ].reject( &:blank? ). join( ' ' ) ].reject( &:blank? ). join( ', ' ) end
ruby
def sortable [ last, [ prefix, first, middle, suffix ].reject( &:blank? ). join( ' ' ) ].reject( &:blank? ). join( ', ' ) end
[ "def", "sortable", "[", "last", ",", "[", "prefix", ",", "first", ",", "middle", ",", "suffix", "]", ".", "reject", "(", ":blank?", ")", ".", "join", "(", "' '", ")", "]", ".", "reject", "(", ":blank?", ")", ".", "join", "(", "', '", ")", "end" ]
Returns the name in a sortable format.
[ "Returns", "the", "name", "in", "a", "sortable", "format", "." ]
a8a6689151bff1e7448baeffbd9ee603989a708e
https://github.com/midas/nameable_record/blob/a8a6689151bff1e7448baeffbd9ee603989a708e/lib/nameable_record/name.rb#L66-L78
6,331
schoefmann/klarlack
lib/varnish/client.rb
Varnish.Client.vcl
def vcl(op, *params) response = cmd("vcl.#{op}", *params) case op when :list response.split("\n").map do |line| a = line.split(/\s+/, 3) [a[0], a[1].to_i, a[2]] end else response end end
ruby
def vcl(op, *params) response = cmd("vcl.#{op}", *params) case op when :list response.split("\n").map do |line| a = line.split(/\s+/, 3) [a[0], a[1].to_i, a[2]] end else response end end
[ "def", "vcl", "(", "op", ",", "*", "params", ")", "response", "=", "cmd", "(", "\"vcl.#{op}\"", ",", "params", ")", "case", "op", "when", ":list", "response", ".", "split", "(", "\"\\n\"", ")", ".", "map", "do", "|", "line", "|", "a", "=", "line", ".", "split", "(", "/", "\\s", "/", ",", "3", ")", "[", "a", "[", "0", "]", ",", "a", "[", "1", "]", ".", "to_i", ",", "a", "[", "2", "]", "]", "end", "else", "response", "end", "end" ]
Manipulate the VCL configuration .vcl :load, <configname>, <filename> .vcl :inline, <configname>, <quoted_VCLstring> .vcl :use, <configname> .vcl :discard, <configname> .vcl :list .vcl :show, <configname> Returns an array of VCL configurations for :list, and the servers response as string otherwise Ex.: v = Varnish::Client.new v.vcl :list #=> [["active", 0, "boot"]] v.vcl :load, "newconf", "/etc/varnish/myconf.vcl"
[ "Manipulate", "the", "VCL", "configuration" ]
7c1b2668da27d663d904c9646ef0d492830fe3de
https://github.com/schoefmann/klarlack/blob/7c1b2668da27d663d904c9646ef0d492830fe3de/lib/varnish/client.rb#L105-L116
6,332
schoefmann/klarlack
lib/varnish/client.rb
Varnish.Client.purge
def purge(*args) c = 'purge' c << ".#{args.shift}" if [:url, :hash, :list].include?(args.first) response = cmd(c, *args) case c when 'purge.list' response.split("\n").map do |line| a = line.split("\t") [a[0].to_i, a[1]] end else bool response end end
ruby
def purge(*args) c = 'purge' c << ".#{args.shift}" if [:url, :hash, :list].include?(args.first) response = cmd(c, *args) case c when 'purge.list' response.split("\n").map do |line| a = line.split("\t") [a[0].to_i, a[1]] end else bool response end end
[ "def", "purge", "(", "*", "args", ")", "c", "=", "'purge'", "c", "<<", "\".#{args.shift}\"", "if", "[", ":url", ",", ":hash", ",", ":list", "]", ".", "include?", "(", "args", ".", "first", ")", "response", "=", "cmd", "(", "c", ",", "args", ")", "case", "c", "when", "'purge.list'", "response", ".", "split", "(", "\"\\n\"", ")", ".", "map", "do", "|", "line", "|", "a", "=", "line", ".", "split", "(", "\"\\t\"", ")", "[", "a", "[", "0", "]", ".", "to_i", ",", "a", "[", "1", "]", "]", "end", "else", "bool", "response", "end", "end" ]
Purge objects from the cache or show the purge queue. Takes one or two arguments: 1. .purge :url, <regexp> .purge :hash, <regexp> <regexp> is a string containing a varnish compatible regexp 2. .purge <costum-purge-conditions> .purge :list Returns true for purging, returns an array containing the purge queue for :list Ex.: v = Varnish::Client.new v.purge :url, '.*' v.purge "req.http.host ~ www.foo.com && req.http.url ~ images" v.purge :list #=> [[1, "req.url ~ .*"]]
[ "Purge", "objects", "from", "the", "cache", "or", "show", "the", "purge", "queue", "." ]
7c1b2668da27d663d904c9646ef0d492830fe3de
https://github.com/schoefmann/klarlack/blob/7c1b2668da27d663d904c9646ef0d492830fe3de/lib/varnish/client.rb#L144-L157
6,333
schoefmann/klarlack
lib/varnish/client.rb
Varnish.Client.stats
def stats result = cmd("stats") Hash[*result.split("\n").map { |line| stat = line.strip!.split(/\s+/, 2) [stat[1], stat[0].to_i] }.flatten ] end
ruby
def stats result = cmd("stats") Hash[*result.split("\n").map { |line| stat = line.strip!.split(/\s+/, 2) [stat[1], stat[0].to_i] }.flatten ] end
[ "def", "stats", "result", "=", "cmd", "(", "\"stats\"", ")", "Hash", "[", "result", ".", "split", "(", "\"\\n\"", ")", ".", "map", "{", "|", "line", "|", "stat", "=", "line", ".", "strip!", ".", "split", "(", "/", "\\s", "/", ",", "2", ")", "[", "stat", "[", "1", "]", ",", "stat", "[", "0", "]", ".", "to_i", "]", "}", ".", "flatten", "]", "end" ]
Returns a hash of status information Ex.: v = Varnish::Client.new v.stats => {"Total header bytes"=>0, "Cache misses"=>0 ...}
[ "Returns", "a", "hash", "of", "status", "information" ]
7c1b2668da27d663d904c9646ef0d492830fe3de
https://github.com/schoefmann/klarlack/blob/7c1b2668da27d663d904c9646ef0d492830fe3de/lib/varnish/client.rb#L170-L177
6,334
barkerest/barkest_core
app/models/barkest_core/pdf_table_builder.rb
BarkestCore.PdfTableBuilder.last_column
def last_column max = 0 @data.each do |row| max = row.length if max < row.length end max - 1 end
ruby
def last_column max = 0 @data.each do |row| max = row.length if max < row.length end max - 1 end
[ "def", "last_column", "max", "=", "0", "@data", ".", "each", "do", "|", "row", "|", "max", "=", "row", ".", "length", "if", "max", "<", "row", ".", "length", "end", "max", "-", "1", "end" ]
Gets the last column in the table.
[ "Gets", "the", "last", "column", "in", "the", "table", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/pdf_table_builder.rb#L75-L81
6,335
barkerest/barkest_core
app/models/barkest_core/pdf_table_builder.rb
BarkestCore.PdfTableBuilder.build_column
def build_column(start_column = nil) if block_given? raise StandardError.new('build_column block called within row block') if @in_row raise StandardError.new('build_column called without valid argument') unless start_column.is_a?(Numeric) backup_col_start = @col_start backup_col_offset = @col_offset backup_row_offset = @row_offset @col_start = start_column.to_i @col_offset = @col_start @row_offset = 0 yield @col_start = backup_col_start @col_offset = backup_col_offset @row_offset = backup_row_offset end @col_start end
ruby
def build_column(start_column = nil) if block_given? raise StandardError.new('build_column block called within row block') if @in_row raise StandardError.new('build_column called without valid argument') unless start_column.is_a?(Numeric) backup_col_start = @col_start backup_col_offset = @col_offset backup_row_offset = @row_offset @col_start = start_column.to_i @col_offset = @col_start @row_offset = 0 yield @col_start = backup_col_start @col_offset = backup_col_offset @row_offset = backup_row_offset end @col_start end
[ "def", "build_column", "(", "start_column", "=", "nil", ")", "if", "block_given?", "raise", "StandardError", ".", "new", "(", "'build_column block called within row block'", ")", "if", "@in_row", "raise", "StandardError", ".", "new", "(", "'build_column called without valid argument'", ")", "unless", "start_column", ".", "is_a?", "(", "Numeric", ")", "backup_col_start", "=", "@col_start", "backup_col_offset", "=", "@col_offset", "backup_row_offset", "=", "@row_offset", "@col_start", "=", "start_column", ".", "to_i", "@col_offset", "=", "@col_start", "@row_offset", "=", "0", "yield", "@col_start", "=", "backup_col_start", "@col_offset", "=", "backup_col_offset", "@row_offset", "=", "backup_row_offset", "end", "@col_start", "end" ]
Builds data starting at the specified column. The +start_column+ is the first column you want to be building. When you start a new row inside of a build_column block, the new row starts at this same column.
[ "Builds", "data", "starting", "at", "the", "specified", "column", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/pdf_table_builder.rb#L89-L108
6,336
barkerest/barkest_core
app/models/barkest_core/pdf_table_builder.rb
BarkestCore.PdfTableBuilder.row
def row(options = {}, &block) raise StandardError.new('row called within row block') if @in_row @in_row = true @col_offset = @col_start options = change_row(options || {}) @row_cell_options = @base_cell_options.merge(options) fill_cells(@row_offset, @col_offset) # skip placeholders when starting a new row. if @data[@row_offset] while @data[@row_offset][@col_offset] == :span_placeholder @col_offset += 1 end end yield if block_given? @in_row = false @row_offset += 1 @row_cell_options = nil end
ruby
def row(options = {}, &block) raise StandardError.new('row called within row block') if @in_row @in_row = true @col_offset = @col_start options = change_row(options || {}) @row_cell_options = @base_cell_options.merge(options) fill_cells(@row_offset, @col_offset) # skip placeholders when starting a new row. if @data[@row_offset] while @data[@row_offset][@col_offset] == :span_placeholder @col_offset += 1 end end yield if block_given? @in_row = false @row_offset += 1 @row_cell_options = nil end
[ "def", "row", "(", "options", "=", "{", "}", ",", "&", "block", ")", "raise", "StandardError", ".", "new", "(", "'row called within row block'", ")", "if", "@in_row", "@in_row", "=", "true", "@col_offset", "=", "@col_start", "options", "=", "change_row", "(", "options", "||", "{", "}", ")", "@row_cell_options", "=", "@base_cell_options", ".", "merge", "(", "options", ")", "fill_cells", "(", "@row_offset", ",", "@col_offset", ")", "# skip placeholders when starting a new row.", "if", "@data", "[", "@row_offset", "]", "while", "@data", "[", "@row_offset", "]", "[", "@col_offset", "]", "==", ":span_placeholder", "@col_offset", "+=", "1", "end", "end", "yield", "if", "block_given?", "@in_row", "=", "false", "@row_offset", "+=", "1", "@row_cell_options", "=", "nil", "end" ]
Builds a row in the table. Valid options: row:: Defines the row you want to start on. If not set, then it uses #current_row. Additional options are merged with the base cell options for this row. When it completes, the #current_row is set to 1 more than the row we started on.
[ "Builds", "a", "row", "in", "the", "table", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/pdf_table_builder.rb#L122-L145
6,337
barkerest/barkest_core
app/models/barkest_core/pdf_table_builder.rb
BarkestCore.PdfTableBuilder.subtable
def subtable(cell_options = {}, options = {}, &block) raise StandardError.new('subtable called outside of row block') unless @in_row cell cell_options || {} do PdfTableBuilder.new(@doc, options || {}, &block).to_table end end
ruby
def subtable(cell_options = {}, options = {}, &block) raise StandardError.new('subtable called outside of row block') unless @in_row cell cell_options || {} do PdfTableBuilder.new(@doc, options || {}, &block).to_table end end
[ "def", "subtable", "(", "cell_options", "=", "{", "}", ",", "options", "=", "{", "}", ",", "&", "block", ")", "raise", "StandardError", ".", "new", "(", "'subtable called outside of row block'", ")", "unless", "@in_row", "cell", "cell_options", "||", "{", "}", "do", "PdfTableBuilder", ".", "new", "(", "@doc", ",", "options", "||", "{", "}", ",", "block", ")", ".", "to_table", "end", "end" ]
Builds a subtable within the current row. The +cell_options+ are passed to the current cell. The +options+ are passed to the new TableBuilder.
[ "Builds", "a", "subtable", "within", "the", "current", "row", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/pdf_table_builder.rb#L153-L158
6,338
barkerest/barkest_core
app/models/barkest_core/pdf_table_builder.rb
BarkestCore.PdfTableBuilder.cells
def cells(options = {}, &block) cell_regex = /^cell_([0-9]+)_/ options ||= { } result = block_given? ? yield : (options[:values] || ['']) cell_options = result.map { {} } common_options = {} options.each do |k,v| # if the option starts with 'cell_#_' then apply it accordingly. if (m = cell_regex.match(k.to_s)) k = k.to_s[m[0].length..-1].to_sym cell_options[m[1].to_i - 1][k] = v # the 'column' option applies only to the first cell. elsif k == :column cell_options[0][k] = v # everything else applies to all cells, unless overridden explicitly. elsif k != :values common_options[k] = v end end cell_options.each_with_index do |opt,idx| cell common_options.merge(opt).merge( { value: result[idx] } ) end end
ruby
def cells(options = {}, &block) cell_regex = /^cell_([0-9]+)_/ options ||= { } result = block_given? ? yield : (options[:values] || ['']) cell_options = result.map { {} } common_options = {} options.each do |k,v| # if the option starts with 'cell_#_' then apply it accordingly. if (m = cell_regex.match(k.to_s)) k = k.to_s[m[0].length..-1].to_sym cell_options[m[1].to_i - 1][k] = v # the 'column' option applies only to the first cell. elsif k == :column cell_options[0][k] = v # everything else applies to all cells, unless overridden explicitly. elsif k != :values common_options[k] = v end end cell_options.each_with_index do |opt,idx| cell common_options.merge(opt).merge( { value: result[idx] } ) end end
[ "def", "cells", "(", "options", "=", "{", "}", ",", "&", "block", ")", "cell_regex", "=", "/", "/", "options", "||=", "{", "}", "result", "=", "block_given?", "?", "yield", ":", "(", "options", "[", ":values", "]", "||", "[", "''", "]", ")", "cell_options", "=", "result", ".", "map", "{", "{", "}", "}", "common_options", "=", "{", "}", "options", ".", "each", "do", "|", "k", ",", "v", "|", "# if the option starts with 'cell_#_' then apply it accordingly.", "if", "(", "m", "=", "cell_regex", ".", "match", "(", "k", ".", "to_s", ")", ")", "k", "=", "k", ".", "to_s", "[", "m", "[", "0", "]", ".", "length", "..", "-", "1", "]", ".", "to_sym", "cell_options", "[", "m", "[", "1", "]", ".", "to_i", "-", "1", "]", "[", "k", "]", "=", "v", "# the 'column' option applies only to the first cell.", "elsif", "k", "==", ":column", "cell_options", "[", "0", "]", "[", "k", "]", "=", "v", "# everything else applies to all cells, unless overridden explicitly.", "elsif", "k", "!=", ":values", "common_options", "[", "k", "]", "=", "v", "end", "end", "cell_options", ".", "each_with_index", "do", "|", "opt", ",", "idx", "|", "cell", "common_options", ".", "merge", "(", "opt", ")", ".", "merge", "(", "{", "value", ":", "result", "[", "idx", "]", "}", ")", "end", "end" ]
Creates multiple cells. Individual cells can be given options by prefixing the keys with 'cell_#' where # is the cell number (starting at 1). See #cell for valid options.
[ "Creates", "multiple", "cells", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/pdf_table_builder.rb#L203-L232
6,339
barkerest/barkest_core
app/models/barkest_core/pdf_table_builder.rb
BarkestCore.PdfTableBuilder.cell
def cell(options = {}, &block) raise StandardError.new('cell called outside of row block') unless @in_row options = @row_cell_options.merge(options || {}) options = change_col(options) result = block_given? ? yield : (options[:value] || '') options.except!(:value) set_cell(result, nil, nil, options) end
ruby
def cell(options = {}, &block) raise StandardError.new('cell called outside of row block') unless @in_row options = @row_cell_options.merge(options || {}) options = change_col(options) result = block_given? ? yield : (options[:value] || '') options.except!(:value) set_cell(result, nil, nil, options) end
[ "def", "cell", "(", "options", "=", "{", "}", ",", "&", "block", ")", "raise", "StandardError", ".", "new", "(", "'cell called outside of row block'", ")", "unless", "@in_row", "options", "=", "@row_cell_options", ".", "merge", "(", "options", "||", "{", "}", ")", "options", "=", "change_col", "(", "options", ")", "result", "=", "block_given?", "?", "yield", ":", "(", "options", "[", ":value", "]", "||", "''", ")", "options", ".", "except!", "(", ":value", ")", "set_cell", "(", "result", ",", "nil", ",", "nil", ",", "options", ")", "end" ]
Generates a cell in the current row. Valid options: value:: The value to put in the cell, unless a code block is provided, in which case the result of the code block is used. rowspan:: The number of rows for this cell to cover. colspan:: The number of columns for this cell to cover. Additional options are embedded and passed on to Prawn::Table, see {Prawn PDF Table Manual}[http://prawnpdf.org/prawn-table-manual.pdf] for more information.
[ "Generates", "a", "cell", "in", "the", "current", "row", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/pdf_table_builder.rb#L275-L287
6,340
barkerest/barkest_core
app/models/barkest_core/pdf_table_builder.rb
BarkestCore.PdfTableBuilder.fix_row_widths
def fix_row_widths fill_cells(@row_offset - 1, 0) max = 0 @data.each_with_index do |row| max = row.length unless max >= row.length end @data.each_with_index do |row,idx| if row.length < max row = row + [ @base_cell_options.merge({content: ''}) ] * (max - row.length) @data[idx] = row end end end
ruby
def fix_row_widths fill_cells(@row_offset - 1, 0) max = 0 @data.each_with_index do |row| max = row.length unless max >= row.length end @data.each_with_index do |row,idx| if row.length < max row = row + [ @base_cell_options.merge({content: ''}) ] * (max - row.length) @data[idx] = row end end end
[ "def", "fix_row_widths", "fill_cells", "(", "@row_offset", "-", "1", ",", "0", ")", "max", "=", "0", "@data", ".", "each_with_index", "do", "|", "row", "|", "max", "=", "row", ".", "length", "unless", "max", ">=", "row", ".", "length", "end", "@data", ".", "each_with_index", "do", "|", "row", ",", "idx", "|", "if", "row", ".", "length", "<", "max", "row", "=", "row", "+", "[", "@base_cell_options", ".", "merge", "(", "{", "content", ":", "''", "}", ")", "]", "*", "(", "max", "-", "row", ".", "length", ")", "@data", "[", "idx", "]", "=", "row", "end", "end", "end" ]
ensure that all 2nd level arrays are the same size.
[ "ensure", "that", "all", "2nd", "level", "arrays", "are", "the", "same", "size", "." ]
3eeb025ec870888cacbc9bae252a39ebf9295f61
https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/models/barkest_core/pdf_table_builder.rb#L387-L404
6,341
ekosz/Erics-Tic-Tac-Toe
lib/tic_tac_toe/board.rb
TicTacToe.Board.empty_positions
def empty_positions(&block) positions = [] each_position do |row, column| next if get_cell(row, column) yield(row, column) if block_given? positions << [row, column] end positions end
ruby
def empty_positions(&block) positions = [] each_position do |row, column| next if get_cell(row, column) yield(row, column) if block_given? positions << [row, column] end positions end
[ "def", "empty_positions", "(", "&", "block", ")", "positions", "=", "[", "]", "each_position", "do", "|", "row", ",", "column", "|", "next", "if", "get_cell", "(", "row", ",", "column", ")", "yield", "(", "row", ",", "column", ")", "if", "block_given?", "positions", "<<", "[", "row", ",", "column", "]", "end", "positions", "end" ]
Returns the corners of the empty cells
[ "Returns", "the", "corners", "of", "the", "empty", "cells" ]
d0c2580974c12187ec9cf11030b72eda6cae3d97
https://github.com/ekosz/Erics-Tic-Tac-Toe/blob/d0c2580974c12187ec9cf11030b72eda6cae3d97/lib/tic_tac_toe/board.rb#L21-L29
6,342
ekosz/Erics-Tic-Tac-Toe
lib/tic_tac_toe/board.rb
TicTacToe.Board.solved?
def solved? letter = won_across? return letter if letter letter = won_up_and_down? return letter if letter letter = won_diagonally? return letter if letter false end
ruby
def solved? letter = won_across? return letter if letter letter = won_up_and_down? return letter if letter letter = won_diagonally? return letter if letter false end
[ "def", "solved?", "letter", "=", "won_across?", "return", "letter", "if", "letter", "letter", "=", "won_up_and_down?", "return", "letter", "if", "letter", "letter", "=", "won_diagonally?", "return", "letter", "if", "letter", "false", "end" ]
Returns true if the board has a wining pattern
[ "Returns", "true", "if", "the", "board", "has", "a", "wining", "pattern" ]
d0c2580974c12187ec9cf11030b72eda6cae3d97
https://github.com/ekosz/Erics-Tic-Tac-Toe/blob/d0c2580974c12187ec9cf11030b72eda6cae3d97/lib/tic_tac_toe/board.rb#L64-L72
6,343
buzzware/buzztools
lib/buzztools/config.rb
Buzztools.Config.read
def read(aSource,&aBlock) default_values.each do |k,v| done = false if block_given? && ((newv = yield(k,v,aSource && aSource[k])) != nil) self[k] = newv done = true end copy_item(aSource,k) if !done && aSource && !aSource[k].nil? end self end
ruby
def read(aSource,&aBlock) default_values.each do |k,v| done = false if block_given? && ((newv = yield(k,v,aSource && aSource[k])) != nil) self[k] = newv done = true end copy_item(aSource,k) if !done && aSource && !aSource[k].nil? end self end
[ "def", "read", "(", "aSource", ",", "&", "aBlock", ")", "default_values", ".", "each", "do", "|", "k", ",", "v", "|", "done", "=", "false", "if", "block_given?", "&&", "(", "(", "newv", "=", "yield", "(", "k", ",", "v", ",", "aSource", "&&", "aSource", "[", "k", "]", ")", ")", "!=", "nil", ")", "self", "[", "k", "]", "=", "newv", "done", "=", "true", "end", "copy_item", "(", "aSource", ",", "k", ")", "if", "!", "done", "&&", "aSource", "&&", "!", "aSource", "[", "k", "]", ".", "nil?", "end", "self", "end" ]
aBlock allows values to be filtered based on key,default and new values
[ "aBlock", "allows", "values", "to", "be", "filtered", "based", "on", "key", "default", "and", "new", "values" ]
0823721974d521330ceffe099368ed8cac6209c3
https://github.com/buzzware/buzztools/blob/0823721974d521330ceffe099368ed8cac6209c3/lib/buzztools/config.rb#L15-L25
6,344
buzzware/buzztools
lib/buzztools/config.rb
Buzztools.Config.reset
def reset self.clear me = self @default_values.each {|n,v| me[n] = v.is_a?(Class) ? nil : v} end
ruby
def reset self.clear me = self @default_values.each {|n,v| me[n] = v.is_a?(Class) ? nil : v} end
[ "def", "reset", "self", ".", "clear", "me", "=", "self", "@default_values", ".", "each", "{", "|", "n", ",", "v", "|", "me", "[", "n", "]", "=", "v", ".", "is_a?", "(", "Class", ")", "?", "nil", ":", "v", "}", "end" ]
reset values back to defaults
[ "reset", "values", "back", "to", "defaults" ]
0823721974d521330ceffe099368ed8cac6209c3
https://github.com/buzzware/buzztools/blob/0823721974d521330ceffe099368ed8cac6209c3/lib/buzztools/config.rb#L28-L32
6,345
cbetta/snapshotify
lib/snapshotify/writer.rb
Snapshotify.Writer.ensure_directory
def ensure_directory dir = File.dirname(full_filename) unless File.directory?(dir) FileUtils.mkdir_p(dir) end end
ruby
def ensure_directory dir = File.dirname(full_filename) unless File.directory?(dir) FileUtils.mkdir_p(dir) end end
[ "def", "ensure_directory", "dir", "=", "File", ".", "dirname", "(", "full_filename", ")", "unless", "File", ".", "directory?", "(", "dir", ")", "FileUtils", ".", "mkdir_p", "(", "dir", ")", "end", "end" ]
Ensure the directory for the file exists
[ "Ensure", "the", "directory", "for", "the", "file", "exists" ]
7f5553f4281ffc5bf0e54da1141574bd15af45b6
https://github.com/cbetta/snapshotify/blob/7f5553f4281ffc5bf0e54da1141574bd15af45b6/lib/snapshotify/writer.rb#L29-L34
6,346
cbetta/snapshotify
lib/snapshotify/writer.rb
Snapshotify.Writer.filename
def filename # Based on the path of the file path = resource.url.uri.path # It's either an index.html file # if the path ends with a slash if path.end_with?('/') return path + 'index.html' # Or it's also an index.html if it ends # without a slah yet is not a file with an # extension elsif !path.split('/').last.include?(".") return path + '/index.html' end # Alternative, the filename is the path as described path end
ruby
def filename # Based on the path of the file path = resource.url.uri.path # It's either an index.html file # if the path ends with a slash if path.end_with?('/') return path + 'index.html' # Or it's also an index.html if it ends # without a slah yet is not a file with an # extension elsif !path.split('/').last.include?(".") return path + '/index.html' end # Alternative, the filename is the path as described path end
[ "def", "filename", "# Based on the path of the file", "path", "=", "resource", ".", "url", ".", "uri", ".", "path", "# It's either an index.html file", "# if the path ends with a slash", "if", "path", ".", "end_with?", "(", "'/'", ")", "return", "path", "+", "'index.html'", "# Or it's also an index.html if it ends", "# without a slah yet is not a file with an", "# extension", "elsif", "!", "path", ".", "split", "(", "'/'", ")", ".", "last", ".", "include?", "(", "\".\"", ")", "return", "path", "+", "'/index.html'", "end", "# Alternative, the filename is the path as described", "path", "end" ]
The actual name of the file
[ "The", "actual", "name", "of", "the", "file" ]
7f5553f4281ffc5bf0e54da1141574bd15af45b6
https://github.com/cbetta/snapshotify/blob/7f5553f4281ffc5bf0e54da1141574bd15af45b6/lib/snapshotify/writer.rb#L57-L72
6,347
jinx/core
lib/jinx/helpers/hasher.rb
Jinx.Hasher.assoc_values
def assoc_values(*others) all_keys = keys others.each { |hash| all_keys.concat(hash.keys) } all_keys.to_compact_hash do |k| others.map { |other| other[k] }.unshift(self[k]) end end
ruby
def assoc_values(*others) all_keys = keys others.each { |hash| all_keys.concat(hash.keys) } all_keys.to_compact_hash do |k| others.map { |other| other[k] }.unshift(self[k]) end end
[ "def", "assoc_values", "(", "*", "others", ")", "all_keys", "=", "keys", "others", ".", "each", "{", "|", "hash", "|", "all_keys", ".", "concat", "(", "hash", ".", "keys", ")", "}", "all_keys", ".", "to_compact_hash", "do", "|", "k", "|", "others", ".", "map", "{", "|", "other", "|", "other", "[", "k", "]", "}", ".", "unshift", "(", "self", "[", "k", "]", ")", "end", "end" ]
Returns a hash which associates each key in this hash with the value mapped by the others. @example {:a => 1, :b => 2}.assoc_values({:a => 3, :c => 4}) #=> {:a => [1, 3], :b => [2, nil], :c => [nil, 4]} {:a => 1, :b => 2}.assoc_values({:a => 3}, {:a => 4, :b => 5}) #=> {:a => [1, 3, 4], :b => [2, nil, 5]} @param [<Hasher>] others the other Hashers to associate with this Hasher @return [Hash] the association hash
[ "Returns", "a", "hash", "which", "associates", "each", "key", "in", "this", "hash", "with", "the", "value", "mapped", "by", "the", "others", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/helpers/hasher.rb#L225-L231
6,348
jinx/core
lib/jinx/helpers/hasher.rb
Jinx.Hasher.enum_keys_with_value
def enum_keys_with_value(target_value=nil, &filter) # :yields: value return enum_keys_with_value { |v| v == target_value } if target_value filter_on_value(&filter).keys end
ruby
def enum_keys_with_value(target_value=nil, &filter) # :yields: value return enum_keys_with_value { |v| v == target_value } if target_value filter_on_value(&filter).keys end
[ "def", "enum_keys_with_value", "(", "target_value", "=", "nil", ",", "&", "filter", ")", "# :yields: value", "return", "enum_keys_with_value", "{", "|", "v", "|", "v", "==", "target_value", "}", "if", "target_value", "filter_on_value", "(", "filter", ")", ".", "keys", "end" ]
Returns an Enumerable whose each block is called on each key which maps to a value which either equals the given target_value or satisfies the filter block. @param target_value the filter value @yield [value] the filter block @return [Enumerable] the filtered keys
[ "Returns", "an", "Enumerable", "whose", "each", "block", "is", "called", "on", "each", "key", "which", "maps", "to", "a", "value", "which", "either", "equals", "the", "given", "target_value", "or", "satisfies", "the", "filter", "block", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/helpers/hasher.rb#L239-L242
6,349
jinx/core
lib/jinx/helpers/hasher.rb
Jinx.Hasher.copy_recursive
def copy_recursive copy = Hash.new keys.each do |k| value = self[k] copy[k] = Hash === value ? value.copy_recursive : value end copy end
ruby
def copy_recursive copy = Hash.new keys.each do |k| value = self[k] copy[k] = Hash === value ? value.copy_recursive : value end copy end
[ "def", "copy_recursive", "copy", "=", "Hash", ".", "new", "keys", ".", "each", "do", "|", "k", "|", "value", "=", "self", "[", "k", "]", "copy", "[", "k", "]", "=", "Hash", "===", "value", "?", "value", ".", "copy_recursive", ":", "value", "end", "copy", "end" ]
Returns a new Hash that recursively copies this hash's values. Values of type hash are copied using copy_recursive. Other values are unchanged. This method is useful for preserving and restoring hash associations. @return [Hash] a deep copy of this Hasher
[ "Returns", "a", "new", "Hash", "that", "recursively", "copies", "this", "hash", "s", "values", ".", "Values", "of", "type", "hash", "are", "copied", "using", "copy_recursive", ".", "Other", "values", "are", "unchanged", "." ]
964a274cc9d7ab74613910e8375e12ed210a434d
https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/helpers/hasher.rb#L316-L323
6,350
benton/rds_backup_service
lib/rds_backup_service/model/email.rb
RDSBackup.Email.body
def body msg = "Hello.\n\n" if job.status == 200 msg += "Your backup of database #{job.rds_id} is complete.\n"+ (job.files.empty? ? "" : "Output is at #{job.files.first[:url]}\n") else msg += "Your backup is incomplete. (job ID #{job.backup_id})\n" end msg += "Job status: #{job.message}" end
ruby
def body msg = "Hello.\n\n" if job.status == 200 msg += "Your backup of database #{job.rds_id} is complete.\n"+ (job.files.empty? ? "" : "Output is at #{job.files.first[:url]}\n") else msg += "Your backup is incomplete. (job ID #{job.backup_id})\n" end msg += "Job status: #{job.message}" end
[ "def", "body", "msg", "=", "\"Hello.\\n\\n\"", "if", "job", ".", "status", "==", "200", "msg", "+=", "\"Your backup of database #{job.rds_id} is complete.\\n\"", "+", "(", "job", ".", "files", ".", "empty?", "?", "\"\"", ":", "\"Output is at #{job.files.first[:url]}\\n\"", ")", "else", "msg", "+=", "\"Your backup is incomplete. (job ID #{job.backup_id})\\n\"", "end", "msg", "+=", "\"Job status: #{job.message}\"", "end" ]
defines the body of a Job's status email
[ "defines", "the", "body", "of", "a", "Job", "s", "status", "email" ]
4930dd47e78a510f0a8abe21a5f9e1a483dda96f
https://github.com/benton/rds_backup_service/blob/4930dd47e78a510f0a8abe21a5f9e1a483dda96f/lib/rds_backup_service/model/email.rb#L36-L45
6,351
robacarp/bootstraps_bootstraps
lib/bootstraps_bootstraps/bootstrap_form_helper.rb
BootstrapsBootstraps.BootstrapFormHelper.bootstrapped_form
def bootstrapped_form object, options={}, &block options[:builder] = BootstrapFormBuilder form_for object, options, &block end
ruby
def bootstrapped_form object, options={}, &block options[:builder] = BootstrapFormBuilder form_for object, options, &block end
[ "def", "bootstrapped_form", "object", ",", "options", "=", "{", "}", ",", "&", "block", "options", "[", ":builder", "]", "=", "BootstrapFormBuilder", "form_for", "object", ",", "options", ",", "block", "end" ]
merely setup the form_for to use our new form builder
[ "merely", "setup", "the", "form_for", "to", "use", "our", "new", "form", "builder" ]
34ccd3cae58e7c4926c0f98f3ac40e6cecb42296
https://github.com/robacarp/bootstraps_bootstraps/blob/34ccd3cae58e7c4926c0f98f3ac40e6cecb42296/lib/bootstraps_bootstraps/bootstrap_form_helper.rb#L4-L7
6,352
xtoddx/maturate
lib/maturate.rb
Maturate.InstanceMethods.api_version
def api_version version = params[:api_version] return current_api_version if version == 'current' api_versions.include?(version) ? version : current_api_version end
ruby
def api_version version = params[:api_version] return current_api_version if version == 'current' api_versions.include?(version) ? version : current_api_version end
[ "def", "api_version", "version", "=", "params", "[", ":api_version", "]", "return", "current_api_version", "if", "version", "==", "'current'", "api_versions", ".", "include?", "(", "version", ")", "?", "version", ":", "current_api_version", "end" ]
The api version of the current request
[ "The", "api", "version", "of", "the", "current", "request" ]
6acb72efe720e8b61dd777a4b190c4a6869bc30c
https://github.com/xtoddx/maturate/blob/6acb72efe720e8b61dd777a4b190c4a6869bc30c/lib/maturate.rb#L186-L190
6,353
jeremiahishere/trackable_tasks
lib/trackable_tasks/base.rb
TrackableTasks.Base.allowable_log_level
def allowable_log_level(log_level) log_level = "" if log_level.nil? log_level = log_level.to_sym unless log_level.is_a?(Symbol) if !@log_levels.include?(log_level) log_level = :notice end return log_level end
ruby
def allowable_log_level(log_level) log_level = "" if log_level.nil? log_level = log_level.to_sym unless log_level.is_a?(Symbol) if !@log_levels.include?(log_level) log_level = :notice end return log_level end
[ "def", "allowable_log_level", "(", "log_level", ")", "log_level", "=", "\"\"", "if", "log_level", ".", "nil?", "log_level", "=", "log_level", ".", "to_sym", "unless", "log_level", ".", "is_a?", "(", "Symbol", ")", "if", "!", "@log_levels", ".", "include?", "(", "log_level", ")", "log_level", "=", ":notice", "end", "return", "log_level", "end" ]
Initializes the task run and sets the start time @param [Symbol] log_level The log level for the task, defaults to notice Checks if the log level is an allowable level, then returns it or notice if it is not allowable @param [Sybmol] log_level Log level to check @return [Symbol] The given log level or notice if it is not allowable
[ "Initializes", "the", "task", "run", "and", "sets", "the", "start", "time" ]
8702672a7b38efa936fd285a0025e04e4b025908
https://github.com/jeremiahishere/trackable_tasks/blob/8702672a7b38efa936fd285a0025e04e4b025908/lib/trackable_tasks/base.rb#L38-L45
6,354
jeremiahishere/trackable_tasks
lib/trackable_tasks/base.rb
TrackableTasks.Base.run_task
def run_task begin run rescue Exception => e @task_run.add_error_text(e.class.name + ": " + e.message) @task_run.add_error_text(e.backtrace.inspect) @task_run.success = false end finally @task_run.end_time = Time.now @task_run.save end
ruby
def run_task begin run rescue Exception => e @task_run.add_error_text(e.class.name + ": " + e.message) @task_run.add_error_text(e.backtrace.inspect) @task_run.success = false end finally @task_run.end_time = Time.now @task_run.save end
[ "def", "run_task", "begin", "run", "rescue", "Exception", "=>", "e", "@task_run", ".", "add_error_text", "(", "e", ".", "class", ".", "name", "+", "\": \"", "+", "e", ".", "message", ")", "@task_run", ".", "add_error_text", "(", "e", ".", "backtrace", ".", "inspect", ")", "@task_run", ".", "success", "=", "false", "end", "finally", "@task_run", ".", "end_time", "=", "Time", ".", "now", "@task_run", ".", "save", "end" ]
this calls task with error catching if an error is caught, sets success to false and records the error either way, sets an end time and saves the task run information After the run completes, whether or not the run succeeds, run finally If finally has an error, don't catch it
[ "this", "calls", "task", "with", "error", "catching", "if", "an", "error", "is", "caught", "sets", "success", "to", "false", "and", "records", "the", "error", "either", "way", "sets", "an", "end", "time", "and", "saves", "the", "task", "run", "information" ]
8702672a7b38efa936fd285a0025e04e4b025908
https://github.com/jeremiahishere/trackable_tasks/blob/8702672a7b38efa936fd285a0025e04e4b025908/lib/trackable_tasks/base.rb#L53-L66
6,355
DeNA/mobilize-base
lib/mobilize-base/models/runner.rb
Mobilize.Runner.force_due
def force_due r = self r.update_attributes(:started_at=>(Time.now.utc - Jobtracker.runner_read_freq - 1.second)) end
ruby
def force_due r = self r.update_attributes(:started_at=>(Time.now.utc - Jobtracker.runner_read_freq - 1.second)) end
[ "def", "force_due", "r", "=", "self", "r", ".", "update_attributes", "(", ":started_at", "=>", "(", "Time", ".", "now", ".", "utc", "-", "Jobtracker", ".", "runner_read_freq", "-", "1", ".", "second", ")", ")", "end" ]
update runner started_at to be whatever the notification is - 1.second which will force runner to be due
[ "update", "runner", "started_at", "to", "be", "whatever", "the", "notification", "is", "-", "1", ".", "second", "which", "will", "force", "runner", "to", "be", "due" ]
0c9d3ba7f1648629f6fc9218a00a1366f1e43a75
https://github.com/DeNA/mobilize-base/blob/0c9d3ba7f1648629f6fc9218a00a1366f1e43a75/lib/mobilize-base/models/runner.rb#L131-L134
6,356
triglav-dataflow/triglav-client-ruby
lib/triglav_client/api/users_api.rb
TriglavClient.UsersApi.create_user
def create_user(user, opts = {}) data, _status_code, _headers = create_user_with_http_info(user, opts) return data end
ruby
def create_user(user, opts = {}) data, _status_code, _headers = create_user_with_http_info(user, opts) return data end
[ "def", "create_user", "(", "user", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "create_user_with_http_info", "(", "user", ",", "opts", ")", "return", "data", "end" ]
Creates a new user in the store @param user User to add to the store @param [Hash] opts the optional parameters @return [UserResponse]
[ "Creates", "a", "new", "user", "in", "the", "store" ]
b2f3781d65ee032ba96eb703fbd789c713a5e0bd
https://github.com/triglav-dataflow/triglav-client-ruby/blob/b2f3781d65ee032ba96eb703fbd789c713a5e0bd/lib/triglav_client/api/users_api.rb#L39-L42
6,357
triglav-dataflow/triglav-client-ruby
lib/triglav_client/api/users_api.rb
TriglavClient.UsersApi.get_user
def get_user(id, opts = {}) data, _status_code, _headers = get_user_with_http_info(id, opts) return data end
ruby
def get_user(id, opts = {}) data, _status_code, _headers = get_user_with_http_info(id, opts) return data end
[ "def", "get_user", "(", "id", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "get_user_with_http_info", "(", "id", ",", "opts", ")", "return", "data", "end" ]
Returns a single user @param id ID of user to fetch @param [Hash] opts the optional parameters @return [UserResponse]
[ "Returns", "a", "single", "user" ]
b2f3781d65ee032ba96eb703fbd789c713a5e0bd
https://github.com/triglav-dataflow/triglav-client-ruby/blob/b2f3781d65ee032ba96eb703fbd789c713a5e0bd/lib/triglav_client/api/users_api.rb#L152-L155
6,358
triglav-dataflow/triglav-client-ruby
lib/triglav_client/api/users_api.rb
TriglavClient.UsersApi.update_user
def update_user(id, user, opts = {}) data, _status_code, _headers = update_user_with_http_info(id, user, opts) return data end
ruby
def update_user(id, user, opts = {}) data, _status_code, _headers = update_user_with_http_info(id, user, opts) return data end
[ "def", "update_user", "(", "id", ",", "user", ",", "opts", "=", "{", "}", ")", "data", ",", "_status_code", ",", "_headers", "=", "update_user_with_http_info", "(", "id", ",", "user", ",", "opts", ")", "return", "data", "end" ]
Updates a single user @param id ID of user to fetch @param user User parameters to update @param [Hash] opts the optional parameters @return [UserResponse]
[ "Updates", "a", "single", "user" ]
b2f3781d65ee032ba96eb703fbd789c713a5e0bd
https://github.com/triglav-dataflow/triglav-client-ruby/blob/b2f3781d65ee032ba96eb703fbd789c713a5e0bd/lib/triglav_client/api/users_api.rb#L263-L266
6,359
romgrod/dater
lib/dater.rb
Dater.Resolver.time_for_period
def time_for_period(string=nil) @last_date = case string when /today/,/now/ now when /tomorrow/ tomorrow_time when /yesterday/ yesterday_time when /sunday/, /monday/, /tuesday/, /wednesday/, /thursday/, /friday/, /saturday/ time_for_weekday(string) when /next/ now + period_of_time_from_string(string.gsub("next","1")) when /last/ now - period_of_time_from_string(string.gsub("last","1")) when /\d[\sa-zA-Z]+\sbefore/ @last_date ||= now @last_date -= period_of_time_from_string(string) when /\d[\sa-zA-Z]+\sago/ @last_date ||= now now - period_of_time_from_string(string) when /\d[\sa-zA-Z]+\slater/ @last_date ||= now @last_date += period_of_time_from_string(string) when /in/,/\d\sminutes?/,/\d\shours?/,/\d\sdays?/, /\d\smonths?/, /\d\sweeks?/, /\d\syears?/ now + period_of_time_from_string(string) when /\d+.\d+.\d+/ time_from_date(string) when /rand/,/future/ now + rand(100_000_000) when /past/ now - rand(100_000_000) end return @last_date end
ruby
def time_for_period(string=nil) @last_date = case string when /today/,/now/ now when /tomorrow/ tomorrow_time when /yesterday/ yesterday_time when /sunday/, /monday/, /tuesday/, /wednesday/, /thursday/, /friday/, /saturday/ time_for_weekday(string) when /next/ now + period_of_time_from_string(string.gsub("next","1")) when /last/ now - period_of_time_from_string(string.gsub("last","1")) when /\d[\sa-zA-Z]+\sbefore/ @last_date ||= now @last_date -= period_of_time_from_string(string) when /\d[\sa-zA-Z]+\sago/ @last_date ||= now now - period_of_time_from_string(string) when /\d[\sa-zA-Z]+\slater/ @last_date ||= now @last_date += period_of_time_from_string(string) when /in/,/\d\sminutes?/,/\d\shours?/,/\d\sdays?/, /\d\smonths?/, /\d\sweeks?/, /\d\syears?/ now + period_of_time_from_string(string) when /\d+.\d+.\d+/ time_from_date(string) when /rand/,/future/ now + rand(100_000_000) when /past/ now - rand(100_000_000) end return @last_date end
[ "def", "time_for_period", "(", "string", "=", "nil", ")", "@last_date", "=", "case", "string", "when", "/", "/", ",", "/", "/", "now", "when", "/", "/", "tomorrow_time", "when", "/", "/", "yesterday_time", "when", "/", "/", ",", "/", "/", ",", "/", "/", ",", "/", "/", ",", "/", "/", ",", "/", "/", ",", "/", "/", "time_for_weekday", "(", "string", ")", "when", "/", "/", "now", "+", "period_of_time_from_string", "(", "string", ".", "gsub", "(", "\"next\"", ",", "\"1\"", ")", ")", "when", "/", "/", "now", "-", "period_of_time_from_string", "(", "string", ".", "gsub", "(", "\"last\"", ",", "\"1\"", ")", ")", "when", "/", "\\d", "\\s", "\\s", "/", "@last_date", "||=", "now", "@last_date", "-=", "period_of_time_from_string", "(", "string", ")", "when", "/", "\\d", "\\s", "\\s", "/", "@last_date", "||=", "now", "now", "-", "period_of_time_from_string", "(", "string", ")", "when", "/", "\\d", "\\s", "\\s", "/", "@last_date", "||=", "now", "@last_date", "+=", "period_of_time_from_string", "(", "string", ")", "when", "/", "/", ",", "/", "\\d", "\\s", "/", ",", "/", "\\d", "\\s", "/", ",", "/", "\\d", "\\s", "/", ",", "/", "\\d", "\\s", "/", ",", "/", "\\d", "\\s", "/", ",", "/", "\\d", "\\s", "/", "now", "+", "period_of_time_from_string", "(", "string", ")", "when", "/", "\\d", "\\d", "\\d", "/", "time_from_date", "(", "string", ")", "when", "/", "/", ",", "/", "/", "now", "+", "rand", "(", "100_000_000", ")", "when", "/", "/", "now", "-", "rand", "(", "100_000_000", ")", "end", "return", "@last_date", "end" ]
Returns the formatted date according to the given period of time expresed in a literal way @param [String] period = time expressed literally (e.g: in 2 days) @return [String] formatted time
[ "Returns", "the", "formatted", "date", "according", "to", "the", "given", "period", "of", "time", "expresed", "in", "a", "literal", "way" ]
b3c1d597e81ed21e62c2874725349502e6f606f8
https://github.com/romgrod/dater/blob/b3c1d597e81ed21e62c2874725349502e6f606f8/lib/dater.rb#L70-L119
6,360
romgrod/dater
lib/dater.rb
Dater.Resolver.is_required_day?
def is_required_day?(time, day) day_to_ask = "#{day}?" result = eval("time.#{day_to_ask}") if time.respond_to? day_to_ask.to_sym return result end
ruby
def is_required_day?(time, day) day_to_ask = "#{day}?" result = eval("time.#{day_to_ask}") if time.respond_to? day_to_ask.to_sym return result end
[ "def", "is_required_day?", "(", "time", ",", "day", ")", "day_to_ask", "=", "\"#{day}?\"", "result", "=", "eval", "(", "\"time.#{day_to_ask}\"", ")", "if", "time", ".", "respond_to?", "day_to_ask", ".", "to_sym", "return", "result", "end" ]
Method to know if the day is the required day @param [Time] time @param [String] day = to match in case statement @return [Boolean] = true if day is the required day
[ "Method", "to", "know", "if", "the", "day", "is", "the", "required", "day" ]
b3c1d597e81ed21e62c2874725349502e6f606f8
https://github.com/romgrod/dater/blob/b3c1d597e81ed21e62c2874725349502e6f606f8/lib/dater.rb#L176-L180
6,361
romgrod/dater
lib/dater.rb
Dater.Resolver.multiply_by
def multiply_by(string) return minute_mult(string) || hour_mult(string) || day_mult(string) || week_mult(string) || month_mult(string) || year_mult(string) || 1 end
ruby
def multiply_by(string) return minute_mult(string) || hour_mult(string) || day_mult(string) || week_mult(string) || month_mult(string) || year_mult(string) || 1 end
[ "def", "multiply_by", "(", "string", ")", "return", "minute_mult", "(", "string", ")", "||", "hour_mult", "(", "string", ")", "||", "day_mult", "(", "string", ")", "||", "week_mult", "(", "string", ")", "||", "month_mult", "(", "string", ")", "||", "year_mult", "(", "string", ")", "||", "1", "end" ]
Returns seconds to multiply by for the given string @param [String] period = the period of time expressed in a literal way @return [Fixnum] number to multiply by
[ "Returns", "seconds", "to", "multiply", "by", "for", "the", "given", "string" ]
b3c1d597e81ed21e62c2874725349502e6f606f8
https://github.com/romgrod/dater/blob/b3c1d597e81ed21e62c2874725349502e6f606f8/lib/dater.rb#L299-L301
6,362
romgrod/dater
lib/dater.rb
Dater.Resolver.time_from_date
def time_from_date(date) numbers=date.scan(/\d+/).map!{|i| i.to_i} day=numbers[2-numbers.index(numbers.max)] Date.new(numbers.max,numbers[1],day).to_time end
ruby
def time_from_date(date) numbers=date.scan(/\d+/).map!{|i| i.to_i} day=numbers[2-numbers.index(numbers.max)] Date.new(numbers.max,numbers[1],day).to_time end
[ "def", "time_from_date", "(", "date", ")", "numbers", "=", "date", ".", "scan", "(", "/", "\\d", "/", ")", ".", "map!", "{", "|", "i", "|", "i", ".", "to_i", "}", "day", "=", "numbers", "[", "2", "-", "numbers", ".", "index", "(", "numbers", ".", "max", ")", "]", "Date", ".", "new", "(", "numbers", ".", "max", ",", "numbers", "[", "1", "]", ",", "day", ")", ".", "to_time", "end" ]
Return the Time object according to the splitted date in the given array @param [String] date @return [Time]
[ "Return", "the", "Time", "object", "according", "to", "the", "splitted", "date", "in", "the", "given", "array" ]
b3c1d597e81ed21e62c2874725349502e6f606f8
https://github.com/romgrod/dater/blob/b3c1d597e81ed21e62c2874725349502e6f606f8/lib/dater.rb#L309-L313
6,363
romgrod/dater
lib/dater.rb
Dater.Resolver.method_missing
def method_missing(meth) self.class.send :define_method, meth do string = meth.to_s.gsub("_"," ") self.for("for('#{string}')") end begin self.send(meth.to_s) rescue raise "Method does not exists (#{meth})." end end
ruby
def method_missing(meth) self.class.send :define_method, meth do string = meth.to_s.gsub("_"," ") self.for("for('#{string}')") end begin self.send(meth.to_s) rescue raise "Method does not exists (#{meth})." end end
[ "def", "method_missing", "(", "meth", ")", "self", ".", "class", ".", "send", ":define_method", ",", "meth", "do", "string", "=", "meth", ".", "to_s", ".", "gsub", "(", "\"_\"", ",", "\" \"", ")", "self", ".", "for", "(", "\"for('#{string}')\"", ")", "end", "begin", "self", ".", "send", "(", "meth", ".", "to_s", ")", "rescue", "raise", "\"Method does not exists (#{meth}).\"", "end", "end" ]
Try to convert Missing methods to string and call to for method with converted string
[ "Try", "to", "convert", "Missing", "methods", "to", "string", "and", "call", "to", "for", "method", "with", "converted", "string" ]
b3c1d597e81ed21e62c2874725349502e6f606f8
https://github.com/romgrod/dater/blob/b3c1d597e81ed21e62c2874725349502e6f606f8/lib/dater.rb#L327-L337
6,364
barkerest/incline
app/models/incline/action_security.rb
Incline.ActionSecurity.update_flags
def update_flags self.allow_anon = self.require_anon = self.require_admin = self.unknown_controller = self.non_standard = false self.unknown_controller = true klass = ::Incline.get_controller_class(controller_name) if klass self.unknown_controller = false if klass.require_admin_for?(action_name) self.require_admin = true elsif klass.require_anon_for?(action_name) self.require_anon = true elsif klass.allow_anon_for?(action_name) self.allow_anon = true end # if the authentication methods are overridden, set a flag to alert the user that standard security may not be honored. unless klass.instance_method(:valid_user?).owner == Incline::Extensions::ActionControllerBase && klass.instance_method(:authorize!).owner == Incline::Extensions::ActionControllerBase self.non_standard = true end end end
ruby
def update_flags self.allow_anon = self.require_anon = self.require_admin = self.unknown_controller = self.non_standard = false self.unknown_controller = true klass = ::Incline.get_controller_class(controller_name) if klass self.unknown_controller = false if klass.require_admin_for?(action_name) self.require_admin = true elsif klass.require_anon_for?(action_name) self.require_anon = true elsif klass.allow_anon_for?(action_name) self.allow_anon = true end # if the authentication methods are overridden, set a flag to alert the user that standard security may not be honored. unless klass.instance_method(:valid_user?).owner == Incline::Extensions::ActionControllerBase && klass.instance_method(:authorize!).owner == Incline::Extensions::ActionControllerBase self.non_standard = true end end end
[ "def", "update_flags", "self", ".", "allow_anon", "=", "self", ".", "require_anon", "=", "self", ".", "require_admin", "=", "self", ".", "unknown_controller", "=", "self", ".", "non_standard", "=", "false", "self", ".", "unknown_controller", "=", "true", "klass", "=", "::", "Incline", ".", "get_controller_class", "(", "controller_name", ")", "if", "klass", "self", ".", "unknown_controller", "=", "false", "if", "klass", ".", "require_admin_for?", "(", "action_name", ")", "self", ".", "require_admin", "=", "true", "elsif", "klass", ".", "require_anon_for?", "(", "action_name", ")", "self", ".", "require_anon", "=", "true", "elsif", "klass", ".", "allow_anon_for?", "(", "action_name", ")", "self", ".", "allow_anon", "=", "true", "end", "# if the authentication methods are overridden, set a flag to alert the user that standard security may not be honored.", "unless", "klass", ".", "instance_method", "(", ":valid_user?", ")", ".", "owner", "==", "Incline", "::", "Extensions", "::", "ActionControllerBase", "&&", "klass", ".", "instance_method", "(", ":authorize!", ")", ".", "owner", "==", "Incline", "::", "Extensions", "::", "ActionControllerBase", "self", ".", "non_standard", "=", "true", "end", "end", "end" ]
Updates the flags based on the controller configuration.
[ "Updates", "the", "flags", "based", "on", "the", "controller", "configuration", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/models/incline/action_security.rb#L30-L54
6,365
barkerest/incline
app/models/incline/action_security.rb
Incline.ActionSecurity.permitted
def permitted(refresh = false) @permitted = nil if refresh @permitted ||= if require_admin? 'Administrators Only' elsif require_anon? 'Anonymous Only' elsif allow_anon? 'Everyone' elsif groups.any? names = groups.pluck(:name).map{|v| "\"#{v}\""} 'Members of ' + if names.count == 1 names.first elsif names.count == 2 names.join(' or ') else names[0...-1].join(', ') + ', or ' + names.last end else 'All Users' end + if non_standard ' (Non-Standard)' else '' end end
ruby
def permitted(refresh = false) @permitted = nil if refresh @permitted ||= if require_admin? 'Administrators Only' elsif require_anon? 'Anonymous Only' elsif allow_anon? 'Everyone' elsif groups.any? names = groups.pluck(:name).map{|v| "\"#{v}\""} 'Members of ' + if names.count == 1 names.first elsif names.count == 2 names.join(' or ') else names[0...-1].join(', ') + ', or ' + names.last end else 'All Users' end + if non_standard ' (Non-Standard)' else '' end end
[ "def", "permitted", "(", "refresh", "=", "false", ")", "@permitted", "=", "nil", "if", "refresh", "@permitted", "||=", "if", "require_admin?", "'Administrators Only'", "elsif", "require_anon?", "'Anonymous Only'", "elsif", "allow_anon?", "'Everyone'", "elsif", "groups", ".", "any?", "names", "=", "groups", ".", "pluck", "(", ":name", ")", ".", "map", "{", "|", "v", "|", "\"\\\"#{v}\\\"\"", "}", "'Members of '", "+", "if", "names", ".", "count", "==", "1", "names", ".", "first", "elsif", "names", ".", "count", "==", "2", "names", ".", "join", "(", "' or '", ")", "else", "names", "[", "0", "...", "-", "1", "]", ".", "join", "(", "', '", ")", "+", "', or '", "+", "names", ".", "last", "end", "else", "'All Users'", "end", "+", "if", "non_standard", "' (Non-Standard)'", "else", "''", "end", "end" ]
Gets a string describing who is permitted to execute the action.
[ "Gets", "a", "string", "describing", "who", "is", "permitted", "to", "execute", "the", "action", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/models/incline/action_security.rb#L129-L156
6,366
barkerest/incline
app/models/incline/action_security.rb
Incline.ActionSecurity.group_ids=
def group_ids=(values) values ||= [] values = [ values ] unless values.is_a?(::Array) values = values.reject{|v| v.blank?}.map{|v| v.to_i} self.groups = Incline::AccessGroup.where(id: values).to_a end
ruby
def group_ids=(values) values ||= [] values = [ values ] unless values.is_a?(::Array) values = values.reject{|v| v.blank?}.map{|v| v.to_i} self.groups = Incline::AccessGroup.where(id: values).to_a end
[ "def", "group_ids", "=", "(", "values", ")", "values", "||=", "[", "]", "values", "=", "[", "values", "]", "unless", "values", ".", "is_a?", "(", "::", "Array", ")", "values", "=", "values", ".", "reject", "{", "|", "v", "|", "v", ".", "blank?", "}", ".", "map", "{", "|", "v", "|", "v", ".", "to_i", "}", "self", ".", "groups", "=", "Incline", "::", "AccessGroup", ".", "where", "(", "id", ":", "values", ")", ".", "to_a", "end" ]
Sets the group IDs accepted by this action.
[ "Sets", "the", "group", "IDs", "accepted", "by", "this", "action", "." ]
1ff08db7aa8ab7f86b223268b700bc67d15bb8aa
https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/models/incline/action_security.rb#L193-L198
6,367
TheComments/the_viking
lib/the_viking/akismet.rb
TheViking.Akismet.check_comment
def check_comment(options = {}) return false if invalid_options? message = call_akismet('comment-check', options) { :spam => !self.class.valid_responses.include?(message), :message => message } end
ruby
def check_comment(options = {}) return false if invalid_options? message = call_akismet('comment-check', options) { :spam => !self.class.valid_responses.include?(message), :message => message } end
[ "def", "check_comment", "(", "options", "=", "{", "}", ")", "return", "false", "if", "invalid_options?", "message", "=", "call_akismet", "(", "'comment-check'", ",", "options", ")", "{", ":spam", "=>", "!", "self", ".", "class", ".", "valid_responses", ".", "include?", "(", "message", ")", ",", ":message", "=>", "message", "}", "end" ]
This is basically the core of everything. This call takes a number of arguments and characteristics about the submitted content and then returns a thumbs up or thumbs down. Almost everything is optional, but performance can drop dramatically if you exclude certain elements. ==== Arguments +options+ <Hash>:: describes the comment being verified The following keys are available for the +options+ hash: +user_ip+ (*required*):: IP address of the comment submitter. +user_agent+ (*required*):: user agent information. +referrer+ (<i>note spelling</i>):: the content of the HTTP_REFERER header should be sent here. +permalink+:: permanent location of the entry the comment was submitted to +comment_type+:: may be blank, comment, trackback, pingback, or a made up value like "registration". +comment_author+:: submitted name with the comment +comment_author_email+:: submitted email address +comment_author_url+:: commenter URL +comment_content+:: the content that was submitted Other server enviroment variables:: In PHP there is an array of enviroment variables called <tt>_SERVER</tt> which contains information about the web server itself as well as a key/value for every HTTP header sent with the request. This data is highly useful to Akismet as how the submited content interacts with the server can be very telling, so please include as much information as possible.
[ "This", "is", "basically", "the", "core", "of", "everything", ".", "This", "call", "takes", "a", "number", "of", "arguments", "and", "characteristics", "about", "the", "submitted", "content", "and", "then", "returns", "a", "thumbs", "up", "or", "thumbs", "down", ".", "Almost", "everything", "is", "optional", "but", "performance", "can", "drop", "dramatically", "if", "you", "exclude", "certain", "elements", "." ]
66ab061d5c07789377b07d875f99267e3846665f
https://github.com/TheComments/the_viking/blob/66ab061d5c07789377b07d875f99267e3846665f/lib/the_viking/akismet.rb#L95-L99
6,368
TheComments/the_viking
lib/the_viking/akismet.rb
TheViking.Akismet.call_akismet
def call_akismet(akismet_function, options = {}) http_post( Net::HTTP.new([self.options[:api_key], self.class.host].join('.'), options[:proxy_host], options[:proxy_port]), akismet_function, options.update(:blog => self.options[:blog]).to_query ) end
ruby
def call_akismet(akismet_function, options = {}) http_post( Net::HTTP.new([self.options[:api_key], self.class.host].join('.'), options[:proxy_host], options[:proxy_port]), akismet_function, options.update(:blog => self.options[:blog]).to_query ) end
[ "def", "call_akismet", "(", "akismet_function", ",", "options", "=", "{", "}", ")", "http_post", "(", "Net", "::", "HTTP", ".", "new", "(", "[", "self", ".", "options", "[", ":api_key", "]", ",", "self", ".", "class", ".", "host", "]", ".", "join", "(", "'.'", ")", ",", "options", "[", ":proxy_host", "]", ",", "options", "[", ":proxy_port", "]", ")", ",", "akismet_function", ",", "options", ".", "update", "(", ":blog", "=>", "self", ".", "options", "[", ":blog", "]", ")", ".", "to_query", ")", "end" ]
Internal call to Akismet. Prepares the data for posting to the Akismet service. ==== Arguments +akismet_function+ <String>:: the Akismet function that should be called The following keys are available to configure a given call to Akismet: +user_ip+ (*required*):: IP address of the comment submitter. +user_agent+ (*required*):: user agent information. +referrer+ (<i>note spelling</i>):: the content of the HTTP_REFERER header should be sent here. +permalink+:: the permanent location of the entry the comment was submitted to. +comment_type+:: may be blank, comment, trackback, pingback, or a made up value like "registration". +comment_author+:: submitted name with the comment +comment_author_email+:: submitted email address +comment_author_url+:: commenter URL +comment_content+:: the content that was submitted Other server enviroment variables:: In PHP there is an array of enviroment variables called <tt>_SERVER</tt> which contains information about the web server itself as well as a key/value for every HTTP header sent with the request. This data is highly useful to Akismet as how the submited content interacts with the server can be very telling, so please include as much information as possible.
[ "Internal", "call", "to", "Akismet", ".", "Prepares", "the", "data", "for", "posting", "to", "the", "Akismet", "service", "." ]
66ab061d5c07789377b07d875f99267e3846665f
https://github.com/TheComments/the_viking/blob/66ab061d5c07789377b07d875f99267e3846665f/lib/the_viking/akismet.rb#L165-L171
6,369
KatanaCode/evvnt
lib/evvnt/actions.rb
Evvnt.Actions.define_action
def define_action(action, &block) action = action.to_sym defined_actions << action unless defined_actions.include?(action) if action.in?(Evvnt::ClassTemplateMethods.instance_methods) define_class_action(action, &block) end if action.in?(Evvnt::InstanceTemplateMethods.instance_methods) define_instance_action(action, &block) end action end
ruby
def define_action(action, &block) action = action.to_sym defined_actions << action unless defined_actions.include?(action) if action.in?(Evvnt::ClassTemplateMethods.instance_methods) define_class_action(action, &block) end if action.in?(Evvnt::InstanceTemplateMethods.instance_methods) define_instance_action(action, &block) end action end
[ "def", "define_action", "(", "action", ",", "&", "block", ")", "action", "=", "action", ".", "to_sym", "defined_actions", "<<", "action", "unless", "defined_actions", ".", "include?", "(", "action", ")", "if", "action", ".", "in?", "(", "Evvnt", "::", "ClassTemplateMethods", ".", "instance_methods", ")", "define_class_action", "(", "action", ",", "block", ")", "end", "if", "action", ".", "in?", "(", "Evvnt", "::", "InstanceTemplateMethods", ".", "instance_methods", ")", "define_instance_action", "(", "action", ",", "block", ")", "end", "action", "end" ]
Define an action for this class to map on to the Evvnt API for this class's resource. action - A Symbol or String representing the action name. Should be one of the template actions if block is not provided. block - A Proc to be used as the action method definition when custom behaviour is required. Examples class Package < Evvnt::Base # Define using the template `all` method define_action :all define_action :mine do # define the custom behaviour here end end Returns Symbol
[ "Define", "an", "action", "for", "this", "class", "to", "map", "on", "to", "the", "Evvnt", "API", "for", "this", "class", "s", "resource", "." ]
e13f6d84af09a71819356620fb25685a6cd159c9
https://github.com/KatanaCode/evvnt/blob/e13f6d84af09a71819356620fb25685a6cd159c9/lib/evvnt/actions.rb#L51-L61
6,370
TonFw/br_open_data
lib/br_open_data/parent_service.rb
BROpenData.ParentService.get_request
def get_request(hash=true) resp = RestClient.get get_url hash ? Hash.from_xml(resp).it_keys_to_sym : resp end
ruby
def get_request(hash=true) resp = RestClient.get get_url hash ? Hash.from_xml(resp).it_keys_to_sym : resp end
[ "def", "get_request", "(", "hash", "=", "true", ")", "resp", "=", "RestClient", ".", "get", "get_url", "hash", "?", "Hash", ".", "from_xml", "(", "resp", ")", ".", "it_keys_to_sym", ":", "resp", "end" ]
send GET HTTP request
[ "send", "GET", "HTTP", "request" ]
c0ddfbf0b38137aa4246d634468520a755248dae
https://github.com/TonFw/br_open_data/blob/c0ddfbf0b38137aa4246d634468520a755248dae/lib/br_open_data/parent_service.rb#L30-L33
6,371
EcomDev/ecomdev-chefspec
lib/ecomdev/chefspec/helpers/platform.rb
EcomDev::ChefSpec::Helpers.Platform.filter
def filter(*conditions) latest = !conditions.select {|item| item === true }.empty? filters = translate_conditions(conditions) items = list(latest) unless filters.empty? items = items.select do |item| !filters.select {|filter| match_filter(filter, item) }.empty? end end items end
ruby
def filter(*conditions) latest = !conditions.select {|item| item === true }.empty? filters = translate_conditions(conditions) items = list(latest) unless filters.empty? items = items.select do |item| !filters.select {|filter| match_filter(filter, item) }.empty? end end items end
[ "def", "filter", "(", "*", "conditions", ")", "latest", "=", "!", "conditions", ".", "select", "{", "|", "item", "|", "item", "===", "true", "}", ".", "empty?", "filters", "=", "translate_conditions", "(", "conditions", ")", "items", "=", "list", "(", "latest", ")", "unless", "filters", ".", "empty?", "items", "=", "items", ".", "select", "do", "|", "item", "|", "!", "filters", ".", "select", "{", "|", "filter", "|", "match_filter", "(", "filter", ",", "item", ")", "}", ".", "empty?", "end", "end", "items", "end" ]
Returns list of available os versions filtered by conditions Each condition is treated as OR operation If no condition is specified all items are listed If TrueClass is supplied as one of the arguments it filters only last versions
[ "Returns", "list", "of", "available", "os", "versions", "filtered", "by", "conditions" ]
67abb6d882aef11a8726b296e4db4bf715ec5869
https://github.com/EcomDev/ecomdev-chefspec/blob/67abb6d882aef11a8726b296e4db4bf715ec5869/lib/ecomdev/chefspec/helpers/platform.rb#L53-L64
6,372
EcomDev/ecomdev-chefspec
lib/ecomdev/chefspec/helpers/platform.rb
EcomDev::ChefSpec::Helpers.Platform.is_version
def is_version(string) return false if string === false || string === true || string.nil? string.to_s.match(/^\d+[\d\.a-zA-Z\-_~]*/) end
ruby
def is_version(string) return false if string === false || string === true || string.nil? string.to_s.match(/^\d+[\d\.a-zA-Z\-_~]*/) end
[ "def", "is_version", "(", "string", ")", "return", "false", "if", "string", "===", "false", "||", "string", "===", "true", "||", "string", ".", "nil?", "string", ".", "to_s", ".", "match", "(", "/", "\\d", "\\d", "\\.", "\\-", "/", ")", "end" ]
Returns `true` if provided value is a version string @param string [String, Symbol] value to check @return [TrueClass, FalseClass]
[ "Returns", "true", "if", "provided", "value", "is", "a", "version", "string" ]
67abb6d882aef11a8726b296e4db4bf715ec5869
https://github.com/EcomDev/ecomdev-chefspec/blob/67abb6d882aef11a8726b296e4db4bf715ec5869/lib/ecomdev/chefspec/helpers/platform.rb#L106-L109
6,373
EcomDev/ecomdev-chefspec
lib/ecomdev/chefspec/helpers/platform.rb
EcomDev::ChefSpec::Helpers.Platform.is_os
def is_os(string) return false if string === false || string === true || string.nil? @os.key?(string.to_sym) end
ruby
def is_os(string) return false if string === false || string === true || string.nil? @os.key?(string.to_sym) end
[ "def", "is_os", "(", "string", ")", "return", "false", "if", "string", "===", "false", "||", "string", "===", "true", "||", "string", ".", "nil?", "@os", ".", "key?", "(", "string", ".", "to_sym", ")", "end" ]
Returns `true` if provided value is a registered OS @param string [String, Symbol] value to check @return [TrueClass, FalseClass]
[ "Returns", "true", "if", "provided", "value", "is", "a", "registered", "OS" ]
67abb6d882aef11a8726b296e4db4bf715ec5869
https://github.com/EcomDev/ecomdev-chefspec/blob/67abb6d882aef11a8726b296e4db4bf715ec5869/lib/ecomdev/chefspec/helpers/platform.rb#L114-L117
6,374
EcomDev/ecomdev-chefspec
lib/ecomdev/chefspec/helpers/platform.rb
EcomDev::ChefSpec::Helpers.Platform.match_filter
def match_filter(filter, item) filter.each_pair do |key, value| unless item.key?(key) return false end unless value.is_a?(Array) return false if value != item[key] else return true if value.empty? return false unless value.include?(item[key]) end end true end
ruby
def match_filter(filter, item) filter.each_pair do |key, value| unless item.key?(key) return false end unless value.is_a?(Array) return false if value != item[key] else return true if value.empty? return false unless value.include?(item[key]) end end true end
[ "def", "match_filter", "(", "filter", ",", "item", ")", "filter", ".", "each_pair", "do", "|", "key", ",", "value", "|", "unless", "item", ".", "key?", "(", "key", ")", "return", "false", "end", "unless", "value", ".", "is_a?", "(", "Array", ")", "return", "false", "if", "value", "!=", "item", "[", "key", "]", "else", "return", "true", "if", "value", ".", "empty?", "return", "false", "unless", "value", ".", "include?", "(", "item", "[", "key", "]", ")", "end", "end", "true", "end" ]
Returns true if item matches filter conditions @param filter [Hash{Symbol => String, Symbol}] @param item [Hash{Symbol => String, Symbol}] @return [true, false]
[ "Returns", "true", "if", "item", "matches", "filter", "conditions" ]
67abb6d882aef11a8726b296e4db4bf715ec5869
https://github.com/EcomDev/ecomdev-chefspec/blob/67abb6d882aef11a8726b296e4db4bf715ec5869/lib/ecomdev/chefspec/helpers/platform.rb#L123-L136
6,375
EcomDev/ecomdev-chefspec
lib/ecomdev/chefspec/helpers/platform.rb
EcomDev::ChefSpec::Helpers.Platform.list
def list(latest = false) result = [] @os.map do |os, versions| unless latest versions.each { |version| result << {os: os, version: version}} else result << {os: os, version: versions.last} if versions.length > 0 end end result end
ruby
def list(latest = false) result = [] @os.map do |os, versions| unless latest versions.each { |version| result << {os: os, version: version}} else result << {os: os, version: versions.last} if versions.length > 0 end end result end
[ "def", "list", "(", "latest", "=", "false", ")", "result", "=", "[", "]", "@os", ".", "map", "do", "|", "os", ",", "versions", "|", "unless", "latest", "versions", ".", "each", "{", "|", "version", "|", "result", "<<", "{", "os", ":", "os", ",", "version", ":", "version", "}", "}", "else", "result", "<<", "{", "os", ":", "os", ",", "version", ":", "versions", ".", "last", "}", "if", "versions", ".", "length", ">", "0", "end", "end", "result", "end" ]
Returns list of available os versions @param [TrueClass, FalseClass] latest specify if would like to receive only latest @return [Array<Hash{Symbol => String, Symbol}>] list of os versions in view of hash
[ "Returns", "list", "of", "available", "os", "versions" ]
67abb6d882aef11a8726b296e4db4bf715ec5869
https://github.com/EcomDev/ecomdev-chefspec/blob/67abb6d882aef11a8726b296e4db4bf715ec5869/lib/ecomdev/chefspec/helpers/platform.rb#L144-L154
6,376
gemeraldbeanstalk/stalk_climber
lib/stalk_climber/connection.rb
StalkClimber.Connection.fetch_and_cache_job
def fetch_and_cache_job(job_id) job = fetch_job(job_id) self.cached_jobs[job_id] = job unless job.nil? @min_climbed_job_id = job_id if job_id < @min_climbed_job_id @max_climbed_job_id = job_id if job_id > @max_climbed_job_id return job end
ruby
def fetch_and_cache_job(job_id) job = fetch_job(job_id) self.cached_jobs[job_id] = job unless job.nil? @min_climbed_job_id = job_id if job_id < @min_climbed_job_id @max_climbed_job_id = job_id if job_id > @max_climbed_job_id return job end
[ "def", "fetch_and_cache_job", "(", "job_id", ")", "job", "=", "fetch_job", "(", "job_id", ")", "self", ".", "cached_jobs", "[", "job_id", "]", "=", "job", "unless", "job", ".", "nil?", "@min_climbed_job_id", "=", "job_id", "if", "job_id", "<", "@min_climbed_job_id", "@max_climbed_job_id", "=", "job_id", "if", "job_id", ">", "@max_climbed_job_id", "return", "job", "end" ]
Helper method, similar to fetch_job, that retrieves the job identified by +job_id+, caches it, and updates counters before returning the job. If the job does not exist, nothing is cached, however counters will be updated, and nil is returned
[ "Helper", "method", "similar", "to", "fetch_job", "that", "retrieves", "the", "job", "identified", "by", "+", "job_id", "+", "caches", "it", "and", "updates", "counters", "before", "returning", "the", "job", ".", "If", "the", "job", "does", "not", "exist", "nothing", "is", "cached", "however", "counters", "will", "be", "updated", "and", "nil", "is", "returned" ]
d22f74bbae864ca2771d15621ccbf29d8e86521a
https://github.com/gemeraldbeanstalk/stalk_climber/blob/d22f74bbae864ca2771d15621ccbf29d8e86521a/lib/stalk_climber/connection.rb#L144-L150
6,377
rit-sse-mycroft/template-ruby
lib/mycroft/messages.rb
Mycroft.Messages.connect_to_mycroft
def connect_to_mycroft if ARGV.include?("--no-tls") @client = TCPSocket.open(@host, @port) else socket = TCPSocket.new(@host, @port) ssl_context = OpenSSL::SSL::SSLContext.new ssl_context.cert = OpenSSL::X509::Certificate.new(File.open(@cert)) ssl_context.key = OpenSSL::PKey::RSA.new(File.open(@key)) @client = OpenSSL::SSL::SSLSocket.new(socket, ssl_context) begin @client.connect rescue end end end
ruby
def connect_to_mycroft if ARGV.include?("--no-tls") @client = TCPSocket.open(@host, @port) else socket = TCPSocket.new(@host, @port) ssl_context = OpenSSL::SSL::SSLContext.new ssl_context.cert = OpenSSL::X509::Certificate.new(File.open(@cert)) ssl_context.key = OpenSSL::PKey::RSA.new(File.open(@key)) @client = OpenSSL::SSL::SSLSocket.new(socket, ssl_context) begin @client.connect rescue end end end
[ "def", "connect_to_mycroft", "if", "ARGV", ".", "include?", "(", "\"--no-tls\"", ")", "@client", "=", "TCPSocket", ".", "open", "(", "@host", ",", "@port", ")", "else", "socket", "=", "TCPSocket", ".", "new", "(", "@host", ",", "@port", ")", "ssl_context", "=", "OpenSSL", "::", "SSL", "::", "SSLContext", ".", "new", "ssl_context", ".", "cert", "=", "OpenSSL", "::", "X509", "::", "Certificate", ".", "new", "(", "File", ".", "open", "(", "@cert", ")", ")", "ssl_context", ".", "key", "=", "OpenSSL", "::", "PKey", "::", "RSA", ".", "new", "(", "File", ".", "open", "(", "@key", ")", ")", "@client", "=", "OpenSSL", "::", "SSL", "::", "SSLSocket", ".", "new", "(", "socket", ",", "ssl_context", ")", "begin", "@client", ".", "connect", "rescue", "end", "end", "end" ]
connects to mycroft aka starts tls if necessary
[ "connects", "to", "mycroft", "aka", "starts", "tls", "if", "necessary" ]
60ede42375b4647b9770bc9a03e614f8d90233ac
https://github.com/rit-sse-mycroft/template-ruby/blob/60ede42375b4647b9770bc9a03e614f8d90233ac/lib/mycroft/messages.rb#L10-L24
6,378
rit-sse-mycroft/template-ruby
lib/mycroft/messages.rb
Mycroft.Messages.send_manifest
def send_manifest begin manifest = JSON.parse(File.read(@manifest)) manifest['instanceId'] = "#{Socket.gethostname}_#{SecureRandom.uuid}" if @generate_instance_ids @instance_id = manifest['instanceId'] rescue end send_message('APP_MANIFEST', manifest) end
ruby
def send_manifest begin manifest = JSON.parse(File.read(@manifest)) manifest['instanceId'] = "#{Socket.gethostname}_#{SecureRandom.uuid}" if @generate_instance_ids @instance_id = manifest['instanceId'] rescue end send_message('APP_MANIFEST', manifest) end
[ "def", "send_manifest", "begin", "manifest", "=", "JSON", ".", "parse", "(", "File", ".", "read", "(", "@manifest", ")", ")", "manifest", "[", "'instanceId'", "]", "=", "\"#{Socket.gethostname}_#{SecureRandom.uuid}\"", "if", "@generate_instance_ids", "@instance_id", "=", "manifest", "[", "'instanceId'", "]", "rescue", "end", "send_message", "(", "'APP_MANIFEST'", ",", "manifest", ")", "end" ]
Sends the app manifest to mycroft
[ "Sends", "the", "app", "manifest", "to", "mycroft" ]
60ede42375b4647b9770bc9a03e614f8d90233ac
https://github.com/rit-sse-mycroft/template-ruby/blob/60ede42375b4647b9770bc9a03e614f8d90233ac/lib/mycroft/messages.rb#L27-L35
6,379
rit-sse-mycroft/template-ruby
lib/mycroft/messages.rb
Mycroft.Messages.query
def query(capability, action, data, priority = 30, instance_id = nil) query_message = { id: SecureRandom.uuid, capability: capability, action: action, data: data, priority: priority, instanceId: [] } query_message[:instanceId] = instance_id unless instance_id.nil? send_message('MSG_QUERY', query_message) end
ruby
def query(capability, action, data, priority = 30, instance_id = nil) query_message = { id: SecureRandom.uuid, capability: capability, action: action, data: data, priority: priority, instanceId: [] } query_message[:instanceId] = instance_id unless instance_id.nil? send_message('MSG_QUERY', query_message) end
[ "def", "query", "(", "capability", ",", "action", ",", "data", ",", "priority", "=", "30", ",", "instance_id", "=", "nil", ")", "query_message", "=", "{", "id", ":", "SecureRandom", ".", "uuid", ",", "capability", ":", "capability", ",", "action", ":", "action", ",", "data", ":", "data", ",", "priority", ":", "priority", ",", "instanceId", ":", "[", "]", "}", "query_message", "[", ":instanceId", "]", "=", "instance_id", "unless", "instance_id", ".", "nil?", "send_message", "(", "'MSG_QUERY'", ",", "query_message", ")", "end" ]
Sends a query to mycroft
[ "Sends", "a", "query", "to", "mycroft" ]
60ede42375b4647b9770bc9a03e614f8d90233ac
https://github.com/rit-sse-mycroft/template-ruby/blob/60ede42375b4647b9770bc9a03e614f8d90233ac/lib/mycroft/messages.rb#L52-L64
6,380
rit-sse-mycroft/template-ruby
lib/mycroft/messages.rb
Mycroft.Messages.broadcast
def broadcast(content) message = { id: SecureRandom.uuid, content: content } send_message('MSG_BROADCAST', message) end
ruby
def broadcast(content) message = { id: SecureRandom.uuid, content: content } send_message('MSG_BROADCAST', message) end
[ "def", "broadcast", "(", "content", ")", "message", "=", "{", "id", ":", "SecureRandom", ".", "uuid", ",", "content", ":", "content", "}", "send_message", "(", "'MSG_BROADCAST'", ",", "message", ")", "end" ]
Sends a broadcast to the mycroft message board
[ "Sends", "a", "broadcast", "to", "the", "mycroft", "message", "board" ]
60ede42375b4647b9770bc9a03e614f8d90233ac
https://github.com/rit-sse-mycroft/template-ruby/blob/60ede42375b4647b9770bc9a03e614f8d90233ac/lib/mycroft/messages.rb#L83-L90
6,381
saclark/lite_page
lib/lite_page/page_initializers.rb
LitePage.PageInitializers.visit
def visit(page_class, query_params = {}, browser = @browser) page = page_class.new(browser) url = query_params.empty? ? page.page_url : page.page_url(query_params) browser.goto(url) yield page if block_given? page end
ruby
def visit(page_class, query_params = {}, browser = @browser) page = page_class.new(browser) url = query_params.empty? ? page.page_url : page.page_url(query_params) browser.goto(url) yield page if block_given? page end
[ "def", "visit", "(", "page_class", ",", "query_params", "=", "{", "}", ",", "browser", "=", "@browser", ")", "page", "=", "page_class", ".", "new", "(", "browser", ")", "url", "=", "query_params", ".", "empty?", "?", "page", ".", "page_url", ":", "page", ".", "page_url", "(", "query_params", ")", "browser", ".", "goto", "(", "url", ")", "yield", "page", "if", "block_given?", "page", "end" ]
Initializes an instance of the given page class, drives the given browser instance to the page's url with any given query parameters appended, yields the page instance to a block if given, and returns the page instance. @param page_class [Class] the page class @param query_params [Hash, Array] the query parameters to append to the page url to viist @param browser [Object] the browser instance @yield [page] yields page instance to a block
[ "Initializes", "an", "instance", "of", "the", "given", "page", "class", "drives", "the", "given", "browser", "instance", "to", "the", "page", "s", "url", "with", "any", "given", "query", "parameters", "appended", "yields", "the", "page", "instance", "to", "a", "block", "if", "given", "and", "returns", "the", "page", "instance", "." ]
efa3ae28a49428ee60c6ee95b51c5d79f603acec
https://github.com/saclark/lite_page/blob/efa3ae28a49428ee60c6ee95b51c5d79f603acec/lib/lite_page/page_initializers.rb#L11-L19
6,382
saclark/lite_page
lib/lite_page/page_initializers.rb
LitePage.PageInitializers.on
def on(page_class, browser = @browser) page = page_class.new(browser) yield page if block_given? page end
ruby
def on(page_class, browser = @browser) page = page_class.new(browser) yield page if block_given? page end
[ "def", "on", "(", "page_class", ",", "browser", "=", "@browser", ")", "page", "=", "page_class", ".", "new", "(", "browser", ")", "yield", "page", "if", "block_given?", "page", "end" ]
Initializes and returns an instance of the given page class. Yields the page instance to a block if given. @param page_class [Class] the page class @param browser [Object] the browser instance @yield [page] yields page instance to a block
[ "Initializes", "and", "returns", "an", "instance", "of", "the", "given", "page", "class", ".", "Yields", "the", "page", "instance", "to", "a", "block", "if", "given", "." ]
efa3ae28a49428ee60c6ee95b51c5d79f603acec
https://github.com/saclark/lite_page/blob/efa3ae28a49428ee60c6ee95b51c5d79f603acec/lib/lite_page/page_initializers.rb#L27-L31
6,383
starrhorne/konfig
lib/konfig/store.rb
Konfig.Store.load_directory
def load_directory(path) unless File.directory?(path) raise "Konfig couldn't load because it was unable to access #{ path }. Please make sure the directory exists and has the correct permissions." end Dir[File.join(path, "*.yml")].each { |f| load_file(f) } end
ruby
def load_directory(path) unless File.directory?(path) raise "Konfig couldn't load because it was unable to access #{ path }. Please make sure the directory exists and has the correct permissions." end Dir[File.join(path, "*.yml")].each { |f| load_file(f) } end
[ "def", "load_directory", "(", "path", ")", "unless", "File", ".", "directory?", "(", "path", ")", "raise", "\"Konfig couldn't load because it was unable to access #{ path }. Please make sure the directory exists and has the correct permissions.\"", "end", "Dir", "[", "File", ".", "join", "(", "path", ",", "\"*.yml\"", ")", "]", ".", "each", "{", "|", "f", "|", "load_file", "(", "f", ")", "}", "end" ]
Loads all yml files in a directory into this store Will not recurse into subdirectories. @param [String] path to directory
[ "Loads", "all", "yml", "files", "in", "a", "directory", "into", "this", "store", "Will", "not", "recurse", "into", "subdirectories", "." ]
5d655945586a489868bb868243d9c0da18c90228
https://github.com/starrhorne/konfig/blob/5d655945586a489868bb868243d9c0da18c90228/lib/konfig/store.rb#L16-L23
6,384
starrhorne/konfig
lib/konfig/store.rb
Konfig.Store.load_file
def load_file(path) d = YAML.load_file(path) if d.is_a?(Hash) d = HashWithIndifferentAccess.new(d) e = Evaluator.new(d) d = process(d, e) end @data[File.basename(path, ".yml").downcase] = d end
ruby
def load_file(path) d = YAML.load_file(path) if d.is_a?(Hash) d = HashWithIndifferentAccess.new(d) e = Evaluator.new(d) d = process(d, e) end @data[File.basename(path, ".yml").downcase] = d end
[ "def", "load_file", "(", "path", ")", "d", "=", "YAML", ".", "load_file", "(", "path", ")", "if", "d", ".", "is_a?", "(", "Hash", ")", "d", "=", "HashWithIndifferentAccess", ".", "new", "(", "d", ")", "e", "=", "Evaluator", ".", "new", "(", "d", ")", "d", "=", "process", "(", "d", ",", "e", ")", "end", "@data", "[", "File", ".", "basename", "(", "path", ",", "\".yml\"", ")", ".", "downcase", "]", "=", "d", "end" ]
Loads a single yml file into the store @param [String] path to file
[ "Loads", "a", "single", "yml", "file", "into", "the", "store" ]
5d655945586a489868bb868243d9c0da18c90228
https://github.com/starrhorne/konfig/blob/5d655945586a489868bb868243d9c0da18c90228/lib/konfig/store.rb#L27-L37
6,385
codescrum/bebox
lib/bebox/commands/profile_commands.rb
Bebox.ProfileCommands.profile_new_command
def profile_new_command(profile_command) profile_command.desc _('cli.profile.new.desc') profile_command.arg_name "[name]" profile_command.command :new do |profile_new_command| profile_new_command.flag :p, :arg_name => 'path', :desc => _('cli.profile.new.path_flag_desc') profile_new_command.action do |global_options,options,args| path = options[:p] || '' help_now!(error(_('cli.profile.new.name_arg_missing'))) if args.count == 0 Bebox::ProfileWizard.new.create_new_profile(project_root, args.first, path) end end end
ruby
def profile_new_command(profile_command) profile_command.desc _('cli.profile.new.desc') profile_command.arg_name "[name]" profile_command.command :new do |profile_new_command| profile_new_command.flag :p, :arg_name => 'path', :desc => _('cli.profile.new.path_flag_desc') profile_new_command.action do |global_options,options,args| path = options[:p] || '' help_now!(error(_('cli.profile.new.name_arg_missing'))) if args.count == 0 Bebox::ProfileWizard.new.create_new_profile(project_root, args.first, path) end end end
[ "def", "profile_new_command", "(", "profile_command", ")", "profile_command", ".", "desc", "_", "(", "'cli.profile.new.desc'", ")", "profile_command", ".", "arg_name", "\"[name]\"", "profile_command", ".", "command", ":new", "do", "|", "profile_new_command", "|", "profile_new_command", ".", "flag", ":p", ",", ":arg_name", "=>", "'path'", ",", ":desc", "=>", "_", "(", "'cli.profile.new.path_flag_desc'", ")", "profile_new_command", ".", "action", "do", "|", "global_options", ",", "options", ",", "args", "|", "path", "=", "options", "[", ":p", "]", "||", "''", "help_now!", "(", "error", "(", "_", "(", "'cli.profile.new.name_arg_missing'", ")", ")", ")", "if", "args", ".", "count", "==", "0", "Bebox", "::", "ProfileWizard", ".", "new", ".", "create_new_profile", "(", "project_root", ",", "args", ".", "first", ",", "path", ")", "end", "end", "end" ]
Profile new command
[ "Profile", "new", "command" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/commands/profile_commands.rb#L19-L30
6,386
codescrum/bebox
lib/bebox/commands/profile_commands.rb
Bebox.ProfileCommands.profile_remove_command
def profile_remove_command(profile_command) profile_command.desc _('cli.profile.remove.desc') profile_command.command :remove do |profile_remove_command| profile_remove_command.action do |global_options,options,args| Bebox::ProfileWizard.new.remove_profile(project_root) end end end
ruby
def profile_remove_command(profile_command) profile_command.desc _('cli.profile.remove.desc') profile_command.command :remove do |profile_remove_command| profile_remove_command.action do |global_options,options,args| Bebox::ProfileWizard.new.remove_profile(project_root) end end end
[ "def", "profile_remove_command", "(", "profile_command", ")", "profile_command", ".", "desc", "_", "(", "'cli.profile.remove.desc'", ")", "profile_command", ".", "command", ":remove", "do", "|", "profile_remove_command", "|", "profile_remove_command", ".", "action", "do", "|", "global_options", ",", "options", ",", "args", "|", "Bebox", "::", "ProfileWizard", ".", "new", ".", "remove_profile", "(", "project_root", ")", "end", "end", "end" ]
Profile remove command
[ "Profile", "remove", "command" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/commands/profile_commands.rb#L33-L40
6,387
codescrum/bebox
lib/bebox/commands/profile_commands.rb
Bebox.ProfileCommands.profile_list_command
def profile_list_command(profile_command) profile_command.desc _('cli.profile.list.desc') profile_command.command :list do |profile_list_command| profile_list_command.action do |global_options,options,args| profiles = Bebox::ProfileWizard.new.list_profiles(project_root) title _('cli.profile.list.current_profiles') profiles.map{|profile| msg(profile)} warn(_('cli.profile.list.no_profiles')) if profiles.empty? linebreak end end end
ruby
def profile_list_command(profile_command) profile_command.desc _('cli.profile.list.desc') profile_command.command :list do |profile_list_command| profile_list_command.action do |global_options,options,args| profiles = Bebox::ProfileWizard.new.list_profiles(project_root) title _('cli.profile.list.current_profiles') profiles.map{|profile| msg(profile)} warn(_('cli.profile.list.no_profiles')) if profiles.empty? linebreak end end end
[ "def", "profile_list_command", "(", "profile_command", ")", "profile_command", ".", "desc", "_", "(", "'cli.profile.list.desc'", ")", "profile_command", ".", "command", ":list", "do", "|", "profile_list_command", "|", "profile_list_command", ".", "action", "do", "|", "global_options", ",", "options", ",", "args", "|", "profiles", "=", "Bebox", "::", "ProfileWizard", ".", "new", ".", "list_profiles", "(", "project_root", ")", "title", "_", "(", "'cli.profile.list.current_profiles'", ")", "profiles", ".", "map", "{", "|", "profile", "|", "msg", "(", "profile", ")", "}", "warn", "(", "_", "(", "'cli.profile.list.no_profiles'", ")", ")", "if", "profiles", ".", "empty?", "linebreak", "end", "end", "end" ]
Profile list command
[ "Profile", "list", "command" ]
0d19315847103341e599d32837ab0bd75524e5be
https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/commands/profile_commands.rb#L43-L54
6,388
aetherised/ark-util
lib/ark/text.rb
ARK.TextBuilder.wrap
def wrap(width: 78, indent: 0, indent_after: false, segments: false) if segments text = Text.wrap_segments(@lines[@line], width: width, indent: indent, indent_after: indent_after) else text = Text.wrap(@lines[@line], width: width, indent: indent, indent_after: indent_after) end @lines.delete_at(@line) @line -= 1 text.split("\n").each {|line| self.next(line) } return self end
ruby
def wrap(width: 78, indent: 0, indent_after: false, segments: false) if segments text = Text.wrap_segments(@lines[@line], width: width, indent: indent, indent_after: indent_after) else text = Text.wrap(@lines[@line], width: width, indent: indent, indent_after: indent_after) end @lines.delete_at(@line) @line -= 1 text.split("\n").each {|line| self.next(line) } return self end
[ "def", "wrap", "(", "width", ":", "78", ",", "indent", ":", "0", ",", "indent_after", ":", "false", ",", "segments", ":", "false", ")", "if", "segments", "text", "=", "Text", ".", "wrap_segments", "(", "@lines", "[", "@line", "]", ",", "width", ":", "width", ",", "indent", ":", "indent", ",", "indent_after", ":", "indent_after", ")", "else", "text", "=", "Text", ".", "wrap", "(", "@lines", "[", "@line", "]", ",", "width", ":", "width", ",", "indent", ":", "indent", ",", "indent_after", ":", "indent_after", ")", "end", "@lines", ".", "delete_at", "(", "@line", ")", "@line", "-=", "1", "text", ".", "split", "(", "\"\\n\"", ")", ".", "each", "{", "|", "line", "|", "self", ".", "next", "(", "line", ")", "}", "return", "self", "end" ]
Wrap the current line to +width+, with an optional +indent+. After wrapping, the current line will be the last line wrapped.
[ "Wrap", "the", "current", "line", "to", "+", "width", "+", "with", "an", "optional", "+", "indent", "+", ".", "After", "wrapping", "the", "current", "line", "will", "be", "the", "last", "line", "wrapped", "." ]
d7573ad0e44568a394808dfa895b9375de1bc3fd
https://github.com/aetherised/ark-util/blob/d7573ad0e44568a394808dfa895b9375de1bc3fd/lib/ark/text.rb#L67-L77
6,389
RudyComputing/shopsense-ruby
lib/shopsense/api.rb
Shopsense.API.search
def search( search_string = nil, index = 0, num_results = 10) raise "no search string provieded!" if( search_string === nil) fts = "fts=" + search_string.split().join( '+').to_s min = "min=" + index.to_s count = "count=" + num_results.to_s args = [fts, min, count].join( '&') return call_api( __method__, args) end
ruby
def search( search_string = nil, index = 0, num_results = 10) raise "no search string provieded!" if( search_string === nil) fts = "fts=" + search_string.split().join( '+').to_s min = "min=" + index.to_s count = "count=" + num_results.to_s args = [fts, min, count].join( '&') return call_api( __method__, args) end
[ "def", "search", "(", "search_string", "=", "nil", ",", "index", "=", "0", ",", "num_results", "=", "10", ")", "raise", "\"no search string provieded!\"", "if", "(", "search_string", "===", "nil", ")", "fts", "=", "\"fts=\"", "+", "search_string", ".", "split", "(", ")", ".", "join", "(", "'+'", ")", ".", "to_s", "min", "=", "\"min=\"", "+", "index", ".", "to_s", "count", "=", "\"count=\"", "+", "num_results", ".", "to_s", "args", "=", "[", "fts", ",", "min", ",", "count", "]", ".", "join", "(", "'&'", ")", "return", "call_api", "(", "__method__", ",", "args", ")", "end" ]
Searches the shopsense API @param [String] search_string The string to be in the query. @param [Integer] index The start index of results returned. @param [Integer] num_results The number of results to be returned. @return A list of Product objects. Each Product has an id, name, description, price, retailer, brand name, categories, images in small/medium/large, and a URL that forwards to the retailer's site.
[ "Searches", "the", "shopsense", "API" ]
956c92567c6cbc140b12e48239ae7812fa65782f
https://github.com/RudyComputing/shopsense-ruby/blob/956c92567c6cbc140b12e48239ae7812fa65782f/lib/shopsense/api.rb#L15-L24
6,390
RudyComputing/shopsense-ruby
lib/shopsense/api.rb
Shopsense.API.get_look
def get_look( look_id = nil) raise "no look_id provieded!" if( look_id === nil) look = "look=" + look_id.to_s return call_api( __method__, look) end
ruby
def get_look( look_id = nil) raise "no look_id provieded!" if( look_id === nil) look = "look=" + look_id.to_s return call_api( __method__, look) end
[ "def", "get_look", "(", "look_id", "=", "nil", ")", "raise", "\"no look_id provieded!\"", "if", "(", "look_id", "===", "nil", ")", "look", "=", "\"look=\"", "+", "look_id", ".", "to_s", "return", "call_api", "(", "__method__", ",", "look", ")", "end" ]
This method returns information about a particular look and its products. @param [Integer] look_id The ID number of the look. An easy way to get a look's ID is to go to the Stylebook page that contains the look at the ShopStyle website and right-click on the button that you use to edit the look. From the popup menu, select "Copy Link" and paste that into any text editor. The "lookId" query parameter of that URL is the value to use for this API method. @return [String] single look, with title, description, a set of tags, and a list of products. The products have the fields listed (see #search)
[ "This", "method", "returns", "information", "about", "a", "particular", "look", "and", "its", "products", "." ]
956c92567c6cbc140b12e48239ae7812fa65782f
https://github.com/RudyComputing/shopsense-ruby/blob/956c92567c6cbc140b12e48239ae7812fa65782f/lib/shopsense/api.rb#L75-L81
6,391
RudyComputing/shopsense-ruby
lib/shopsense/api.rb
Shopsense.API.get_stylebook
def get_stylebook( user_name = nil, index = 0, num_results = 10) raise "no user_name provieded!" if( user_name === nil) handle = "handle=" + user_name.to_s min = "min=" + index.to_s count = "count=" + num_results.to_s args = [handle, min, count].join( '&') return call_api( __method__, args) end
ruby
def get_stylebook( user_name = nil, index = 0, num_results = 10) raise "no user_name provieded!" if( user_name === nil) handle = "handle=" + user_name.to_s min = "min=" + index.to_s count = "count=" + num_results.to_s args = [handle, min, count].join( '&') return call_api( __method__, args) end
[ "def", "get_stylebook", "(", "user_name", "=", "nil", ",", "index", "=", "0", ",", "num_results", "=", "10", ")", "raise", "\"no user_name provieded!\"", "if", "(", "user_name", "===", "nil", ")", "handle", "=", "\"handle=\"", "+", "user_name", ".", "to_s", "min", "=", "\"min=\"", "+", "index", ".", "to_s", "count", "=", "\"count=\"", "+", "num_results", ".", "to_s", "args", "=", "[", "handle", ",", "min", ",", "count", "]", ".", "join", "(", "'&'", ")", "return", "call_api", "(", "__method__", ",", "args", ")", "end" ]
This method returns information about a particular user's Stylebook, the looks within that Stylebook, and the title and description associated with each look. @param [String] username The username of the Stylebook owner. @param [Integer] index The start index of results returned. @param [Integer] num_results The number of results to be returned. @return [String] A look id of the user's Stylebook, the look id of each individual look within that Stylebook, and the title and description associated with each look.
[ "This", "method", "returns", "information", "about", "a", "particular", "user", "s", "Stylebook", "the", "looks", "within", "that", "Stylebook", "and", "the", "title", "and", "description", "associated", "with", "each", "look", "." ]
956c92567c6cbc140b12e48239ae7812fa65782f
https://github.com/RudyComputing/shopsense-ruby/blob/956c92567c6cbc140b12e48239ae7812fa65782f/lib/shopsense/api.rb#L100-L109
6,392
RudyComputing/shopsense-ruby
lib/shopsense/api.rb
Shopsense.API.get_looks
def get_looks( look_type = nil, index = 0, num_results = 10) raise "invalid filter type must be one of the following: #{self.look_types}" if( !self.look_types.include?( look_type)) type = "type=" + look_type.to_s min = "min=" + index.to_s count = "count=" + num_results.to_s args = [type, min, count].join( '&') return call_api( __method__, args) end
ruby
def get_looks( look_type = nil, index = 0, num_results = 10) raise "invalid filter type must be one of the following: #{self.look_types}" if( !self.look_types.include?( look_type)) type = "type=" + look_type.to_s min = "min=" + index.to_s count = "count=" + num_results.to_s args = [type, min, count].join( '&') return call_api( __method__, args) end
[ "def", "get_looks", "(", "look_type", "=", "nil", ",", "index", "=", "0", ",", "num_results", "=", "10", ")", "raise", "\"invalid filter type must be one of the following: #{self.look_types}\"", "if", "(", "!", "self", ".", "look_types", ".", "include?", "(", "look_type", ")", ")", "type", "=", "\"type=\"", "+", "look_type", ".", "to_s", "min", "=", "\"min=\"", "+", "index", ".", "to_s", "count", "=", "\"count=\"", "+", "num_results", ".", "to_s", "args", "=", "[", "type", ",", "min", ",", "count", "]", ".", "join", "(", "'&'", ")", "return", "call_api", "(", "__method__", ",", "args", ")", "end" ]
This method returns information about looks that match different kinds of searches. @param [Integer] look_type The type of search to perform. Supported values are: New - Recently created looks. TopRated - Recently created looks that are highly rated. Celebrities - Looks owned by celebrity users. Featured - Looks from featured stylebooks. @param [String] username The username of the Stylebook owner. @param [Integer] index The start index of results returned. @param [Integer] num_results The number of results to be returned. @return [String] A list of looks of the given type.
[ "This", "method", "returns", "information", "about", "looks", "that", "match", "different", "kinds", "of", "searches", "." ]
956c92567c6cbc140b12e48239ae7812fa65782f
https://github.com/RudyComputing/shopsense-ruby/blob/956c92567c6cbc140b12e48239ae7812fa65782f/lib/shopsense/api.rb#L126-L135
6,393
RudyComputing/shopsense-ruby
lib/shopsense/api.rb
Shopsense.API.get_trends
def get_trends( category = "", products = 0) cat = "cat=" + category.to_s products = "products=" + products.to_s args = [cat, products].join( '&') return call_api( __method__, args) end
ruby
def get_trends( category = "", products = 0) cat = "cat=" + category.to_s products = "products=" + products.to_s args = [cat, products].join( '&') return call_api( __method__, args) end
[ "def", "get_trends", "(", "category", "=", "\"\"", ",", "products", "=", "0", ")", "cat", "=", "\"cat=\"", "+", "category", ".", "to_s", "products", "=", "\"products=\"", "+", "products", ".", "to_s", "args", "=", "[", "cat", ",", "products", "]", ".", "join", "(", "'&'", ")", "return", "call_api", "(", "__method__", ",", "args", ")", "end" ]
This method returns the popular brands for a given category along with a sample product for the brand-category combination. @param [String] category Category you want to restrict the popularity search for. This is an optional parameter. If category is not supplied, all the popular brands regardless of category will be returned. @return [String] A list of trends in the given category. Each trend has a brand, category, url, and optionally the top-ranked product for each brand/category.
[ "This", "method", "returns", "the", "popular", "brands", "for", "a", "given", "category", "along", "with", "a", "sample", "product", "for", "the", "brand", "-", "category", "combination", "." ]
956c92567c6cbc140b12e48239ae7812fa65782f
https://github.com/RudyComputing/shopsense-ruby/blob/956c92567c6cbc140b12e48239ae7812fa65782f/lib/shopsense/api.rb#L160-L166
6,394
RudyComputing/shopsense-ruby
lib/shopsense/api.rb
Shopsense.API.call_api
def call_api( method, args = nil) method_url = self.api_url + self.send( "#{method}_path") pid = "pid=" + self.partner_id format = "format=" + self.format site = "site=" + self.site if( args === nil) then uri = URI.parse( method_url.to_s + [pid, format, site].join('&').to_s) else uri = URI.parse( method_url.to_s + [pid, format, site, args].join('&').to_s) end return Net::HTTP.get( uri) end
ruby
def call_api( method, args = nil) method_url = self.api_url + self.send( "#{method}_path") pid = "pid=" + self.partner_id format = "format=" + self.format site = "site=" + self.site if( args === nil) then uri = URI.parse( method_url.to_s + [pid, format, site].join('&').to_s) else uri = URI.parse( method_url.to_s + [pid, format, site, args].join('&').to_s) end return Net::HTTP.get( uri) end
[ "def", "call_api", "(", "method", ",", "args", "=", "nil", ")", "method_url", "=", "self", ".", "api_url", "+", "self", ".", "send", "(", "\"#{method}_path\"", ")", "pid", "=", "\"pid=\"", "+", "self", ".", "partner_id", "format", "=", "\"format=\"", "+", "self", ".", "format", "site", "=", "\"site=\"", "+", "self", ".", "site", "if", "(", "args", "===", "nil", ")", "then", "uri", "=", "URI", ".", "parse", "(", "method_url", ".", "to_s", "+", "[", "pid", ",", "format", ",", "site", "]", ".", "join", "(", "'&'", ")", ".", "to_s", ")", "else", "uri", "=", "URI", ".", "parse", "(", "method_url", ".", "to_s", "+", "[", "pid", ",", "format", ",", "site", ",", "args", "]", ".", "join", "(", "'&'", ")", ".", "to_s", ")", "end", "return", "Net", "::", "HTTP", ".", "get", "(", "uri", ")", "end" ]
This method is used for making the http calls building off the DSL of this module. @param [String] method The method which is to be used in the call to Shopsense @param [String] args A concatenated group of arguments seperated by a an & symbol and spces substitued with a + symbol. @return [String] A list of the data returned
[ "This", "method", "is", "used", "for", "making", "the", "http", "calls", "building", "off", "the", "DSL", "of", "this", "module", "." ]
956c92567c6cbc140b12e48239ae7812fa65782f
https://github.com/RudyComputing/shopsense-ruby/blob/956c92567c6cbc140b12e48239ae7812fa65782f/lib/shopsense/api.rb#L175-L188
6,395
jgoizueta/numerals
lib/numerals/format/symbols/digits.rb
Numerals.Format::Symbols::Digits.digits_text
def digits_text(digit_values, options={}) insignificant_digits = options[:insignificant_digits] || 0 num_digits = digit_values.reduce(0) { |num, digit| digit.nil? ? num : num + 1 } num_digits -= insignificant_digits digit_values.map { |d| if d.nil? options[:separator] else num_digits -= 1 if num_digits >= 0 digit_symbol(d, options) else options[:insignificant_symbol] end end }.join end
ruby
def digits_text(digit_values, options={}) insignificant_digits = options[:insignificant_digits] || 0 num_digits = digit_values.reduce(0) { |num, digit| digit.nil? ? num : num + 1 } num_digits -= insignificant_digits digit_values.map { |d| if d.nil? options[:separator] else num_digits -= 1 if num_digits >= 0 digit_symbol(d, options) else options[:insignificant_symbol] end end }.join end
[ "def", "digits_text", "(", "digit_values", ",", "options", "=", "{", "}", ")", "insignificant_digits", "=", "options", "[", ":insignificant_digits", "]", "||", "0", "num_digits", "=", "digit_values", ".", "reduce", "(", "0", ")", "{", "|", "num", ",", "digit", "|", "digit", ".", "nil?", "?", "num", ":", "num", "+", "1", "}", "num_digits", "-=", "insignificant_digits", "digit_values", ".", "map", "{", "|", "d", "|", "if", "d", ".", "nil?", "options", "[", ":separator", "]", "else", "num_digits", "-=", "1", "if", "num_digits", ">=", "0", "digit_symbol", "(", "d", ",", "options", ")", "else", "options", "[", ":insignificant_symbol", "]", "end", "end", "}", ".", "join", "end" ]
Convert sequence of digits to its text representation. The nil value can be used in the digits sequence to represent the group separator.
[ "Convert", "sequence", "of", "digits", "to", "its", "text", "representation", ".", "The", "nil", "value", "can", "be", "used", "in", "the", "digits", "sequence", "to", "represent", "the", "group", "separator", "." ]
a195e75f689af926537f791441bf8d11590c99c0
https://github.com/jgoizueta/numerals/blob/a195e75f689af926537f791441bf8d11590c99c0/lib/numerals/format/symbols/digits.rb#L91-L109
6,396
Dahie/woro
lib/woro/task_list.rb
Woro.TaskList.width
def width @width ||= list.map { |t| t.name_with_args ? t.name_with_args.length : 0 }.max || 10 end
ruby
def width @width ||= list.map { |t| t.name_with_args ? t.name_with_args.length : 0 }.max || 10 end
[ "def", "width", "@width", "||=", "list", ".", "map", "{", "|", "t", "|", "t", ".", "name_with_args", "?", "t", ".", "name_with_args", ".", "length", ":", "0", "}", ".", "max", "||", "10", "end" ]
Determine the max count of characters for all task names. @return [integer] count of characters
[ "Determine", "the", "max", "count", "of", "characters", "for", "all", "task", "names", "." ]
796873cca145c61cd72c7363551e10d402f867c6
https://github.com/Dahie/woro/blob/796873cca145c61cd72c7363551e10d402f867c6/lib/woro/task_list.rb#L17-L19
6,397
Dahie/woro
lib/woro/task_list.rb
Woro.TaskList.print
def print list.each do |entry| entry.headline ? print_headline(entry) : print_task_description(entry) end end
ruby
def print list.each do |entry| entry.headline ? print_headline(entry) : print_task_description(entry) end end
[ "def", "print", "list", ".", "each", "do", "|", "entry", "|", "entry", ".", "headline", "?", "print_headline", "(", "entry", ")", ":", "print_task_description", "(", "entry", ")", "end", "end" ]
Print the current task list to console.
[ "Print", "the", "current", "task", "list", "to", "console", "." ]
796873cca145c61cd72c7363551e10d402f867c6
https://github.com/Dahie/woro/blob/796873cca145c61cd72c7363551e10d402f867c6/lib/woro/task_list.rb#L30-L34
6,398
riddopic/garcun
lib/garcon/task/event.rb
Garcon.Event.wait
def wait(timeout = nil) @mutex.lock unless @set remaining = Condition::Result.new(timeout) while !@set && remaining.can_wait? remaining = @condition.wait(@mutex, remaining.remaining_time) end end @set ensure @mutex.unlock end
ruby
def wait(timeout = nil) @mutex.lock unless @set remaining = Condition::Result.new(timeout) while !@set && remaining.can_wait? remaining = @condition.wait(@mutex, remaining.remaining_time) end end @set ensure @mutex.unlock end
[ "def", "wait", "(", "timeout", "=", "nil", ")", "@mutex", ".", "lock", "unless", "@set", "remaining", "=", "Condition", "::", "Result", ".", "new", "(", "timeout", ")", "while", "!", "@set", "&&", "remaining", ".", "can_wait?", "remaining", "=", "@condition", ".", "wait", "(", "@mutex", ",", "remaining", ".", "remaining_time", ")", "end", "end", "@set", "ensure", "@mutex", ".", "unlock", "end" ]
Wait a given number of seconds for the `Event` to be set by another thread. Will wait forever when no `timeout` value is given. Returns immediately if the `Event` has already been set. @return [Boolean] true if the `Event` was set before timeout else false
[ "Wait", "a", "given", "number", "of", "seconds", "for", "the", "Event", "to", "be", "set", "by", "another", "thread", ".", "Will", "wait", "forever", "when", "no", "timeout", "value", "is", "given", ".", "Returns", "immediately", "if", "the", "Event", "has", "already", "been", "set", "." ]
c2409bd8cf9c14b967a719810dab5269d69b42de
https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/event.rb#L104-L117
6,399
robfors/ruby-sumac
lib/sumac/remote_object.rb
Sumac.RemoteObject.method_missing
def method_missing(method_name, *arguments, &block) # TODO: blocks not working yet arguments << block.to_lambda if block_given? reqeust = {object: self, method: method_name.to_s, arguments: arguments} begin return_value = @object_request_broker.call(reqeust) rescue ClosedObjectRequestBrokerError raise StaleObjectError end end
ruby
def method_missing(method_name, *arguments, &block) # TODO: blocks not working yet arguments << block.to_lambda if block_given? reqeust = {object: self, method: method_name.to_s, arguments: arguments} begin return_value = @object_request_broker.call(reqeust) rescue ClosedObjectRequestBrokerError raise StaleObjectError end end
[ "def", "method_missing", "(", "method_name", ",", "*", "arguments", ",", "&", "block", ")", "# TODO: blocks not working yet", "arguments", "<<", "block", ".", "to_lambda", "if", "block_given?", "reqeust", "=", "{", "object", ":", "self", ",", "method", ":", "method_name", ".", "to_s", ",", "arguments", ":", "arguments", "}", "begin", "return_value", "=", "@object_request_broker", ".", "call", "(", "reqeust", ")", "rescue", "ClosedObjectRequestBrokerError", "raise", "StaleObjectError", "end", "end" ]
Makes a calls to the object on the remote endpoint. @note will block until the call has completed @param method_name [String] method to call @param arguments [Array<Array,Boolean,Exception,ExposedObject,Float,Hash,Integer,nil,String>] arguments being passed @raise [ClosedObjectRequestBrokerError] if broker is closed before the request is sent or respose is received @raise [UnexposedObjectError] if an object being sent is an invalid type @raise [StaleObjectError] if an object being sent has been forgoten by this endpoint (may not be forgoten by the remote endpoint yet) @raise [RemoteError] if an error was raised during call @raise [ArgumentError,StaleObjectError,UnexposedMethodError,UnexposedObjectError] if one is raised by the remote endpoint when trying to call the method or return a value (but not during the call) @return [Array,Boolean,Exception,ExposedObject,Float,Hash,Integer,nil,String] value returned from the call on remote endpoint
[ "Makes", "a", "calls", "to", "the", "object", "on", "the", "remote", "endpoint", "." ]
524fa68b7d1bb10a74baa69cd594ab2b8cae20a3
https://github.com/robfors/ruby-sumac/blob/524fa68b7d1bb10a74baa69cd594ab2b8cae20a3/lib/sumac/remote_object.rb#L64-L72