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
16,500
jonatas/fast
lib/fast/experiment.rb
Fast.ExperimentFile.ok_with
def ok_with(combination) @ok_experiments << combination return unless combination.is_a?(Array) combination.each do |element| @ok_experiments.delete(element) end end
ruby
def ok_with(combination) @ok_experiments << combination return unless combination.is_a?(Array) combination.each do |element| @ok_experiments.delete(element) end end
[ "def", "ok_with", "(", "combination", ")", "@ok_experiments", "<<", "combination", "return", "unless", "combination", ".", "is_a?", "(", "Array", ")", "combination", ".", "each", "do", "|", "element", "|", "@ok_experiments", ".", "delete", "(", "element", ")", "end", "end" ]
Keep track of ok experiments depending on the current combination. It keep the combinations unique removing single replacements after the first round. @return void
[ "Keep", "track", "of", "ok", "experiments", "depending", "on", "the", "current", "combination", ".", "It", "keep", "the", "combinations", "unique", "removing", "single", "replacements", "after", "the", "first", "round", "." ]
5d918a5c19327847fbadab6c56035f936458ba70
https://github.com/jonatas/fast/blob/5d918a5c19327847fbadab6c56035f936458ba70/lib/fast/experiment.rb#L273-L280
16,501
jonatas/fast
lib/fast/experiment.rb
Fast.ExperimentFile.run_partial_replacement_with
def run_partial_replacement_with(combination) content = partial_replace(*combination) experimental_file = experimental_filename(combination) File.open(experimental_file, 'w+') { |f| f.puts content } raise 'No changes were made to the file.' if FileUtils.compare_file(@file, experimental_file) result = experiment.ok_if.call(experimental_file) if result ok_with(combination) puts "✅ #{experimental_file} - Combination: #{combination}" else failed_with(combination) puts "🔴 #{experimental_file} - Combination: #{combination}" end end
ruby
def run_partial_replacement_with(combination) content = partial_replace(*combination) experimental_file = experimental_filename(combination) File.open(experimental_file, 'w+') { |f| f.puts content } raise 'No changes were made to the file.' if FileUtils.compare_file(@file, experimental_file) result = experiment.ok_if.call(experimental_file) if result ok_with(combination) puts "✅ #{experimental_file} - Combination: #{combination}" else failed_with(combination) puts "🔴 #{experimental_file} - Combination: #{combination}" end end
[ "def", "run_partial_replacement_with", "(", "combination", ")", "content", "=", "partial_replace", "(", "combination", ")", "experimental_file", "=", "experimental_filename", "(", "combination", ")", "File", ".", "open", "(", "experimental_file", ",", "'w+'", ")", "{", "|", "f", "|", "f", ".", "puts", "content", "}", "raise", "'No changes were made to the file.'", "if", "FileUtils", ".", "compare_file", "(", "@file", ",", "experimental_file", ")", "result", "=", "experiment", ".", "ok_if", ".", "call", "(", "experimental_file", ")", "if", "result", "ok_with", "(", "combination", ")", "puts", "\"✅ #{experimental_file} - Combination: #{combination}\"", "else", "failed_with", "(", "combination", ")", "puts", "\"🔴 #{experimental_file} - Combination: #{combination}\"", "end", "end" ]
Writes a new file with partial replacements based on the current combination. Raise error if no changes was made with the given combination indices. @param [Array<Integer>] combination to be replaced.
[ "Writes", "a", "new", "file", "with", "partial", "replacements", "based", "on", "the", "current", "combination", ".", "Raise", "error", "if", "no", "changes", "was", "made", "with", "the", "given", "combination", "indices", "." ]
5d918a5c19327847fbadab6c56035f936458ba70
https://github.com/jonatas/fast/blob/5d918a5c19327847fbadab6c56035f936458ba70/lib/fast/experiment.rb#L366-L383
16,502
gottfrois/link_thumbnailer
lib/link_thumbnailer/grader.rb
LinkThumbnailer.Grader.call
def call probability = 1.0 graders.each do |lambda| instance = lambda.call(description) probability *= instance.call.to_f ** instance.weight end probability end
ruby
def call probability = 1.0 graders.each do |lambda| instance = lambda.call(description) probability *= instance.call.to_f ** instance.weight end probability end
[ "def", "call", "probability", "=", "1.0", "graders", ".", "each", "do", "|", "lambda", "|", "instance", "=", "lambda", ".", "call", "(", "description", ")", "probability", "*=", "instance", ".", "call", ".", "to_f", "**", "instance", ".", "weight", "end", "probability", "end" ]
For given description, computes probabilities returned by each graders by multipying them together. @return [Float] the probability for the given description to be considered good
[ "For", "given", "description", "computes", "probabilities", "returned", "by", "each", "graders", "by", "multipying", "them", "together", "." ]
299e6cec1b392ca4134e872acfe76fa82b1ba9a9
https://github.com/gottfrois/link_thumbnailer/blob/299e6cec1b392ca4134e872acfe76fa82b1ba9a9/lib/link_thumbnailer/grader.rb#L25-L34
16,503
infinitered/ProMotion
lib/ProMotion/table/table.rb
ProMotion.Table.tableView
def tableView(_, viewForHeaderInSection: index) section = promotion_table_data.section(index) view = section[:title_view] view = section[:title_view].new if section[:title_view].respond_to?(:new) view.on_load if view.respond_to?(:on_load) view.title = section[:title] if view.respond_to?(:title=) view end
ruby
def tableView(_, viewForHeaderInSection: index) section = promotion_table_data.section(index) view = section[:title_view] view = section[:title_view].new if section[:title_view].respond_to?(:new) view.on_load if view.respond_to?(:on_load) view.title = section[:title] if view.respond_to?(:title=) view end
[ "def", "tableView", "(", "_", ",", "viewForHeaderInSection", ":", "index", ")", "section", "=", "promotion_table_data", ".", "section", "(", "index", ")", "view", "=", "section", "[", ":title_view", "]", "view", "=", "section", "[", ":title_view", "]", ".", "new", "if", "section", "[", ":title_view", "]", ".", "respond_to?", "(", ":new", ")", "view", ".", "on_load", "if", "view", ".", "respond_to?", "(", ":on_load", ")", "view", ".", "title", "=", "section", "[", ":title", "]", "if", "view", ".", "respond_to?", "(", ":title=", ")", "view", "end" ]
Section header view methods
[ "Section", "header", "view", "methods" ]
837d4b1dbdf7fac4ce6dee840223db5a917f0116
https://github.com/infinitered/ProMotion/blob/837d4b1dbdf7fac4ce6dee840223db5a917f0116/lib/ProMotion/table/table.rb#L288-L295
16,504
infinitered/ProMotion
lib/ProMotion/web/web_screen_module.rb
ProMotion.WebScreenModule.webView
def webView(in_web, shouldStartLoadWithRequest:in_request, navigationType:in_type) if %w(http https).include?(in_request.URL.scheme) if self.external_links == true && in_type == UIWebViewNavigationTypeLinkClicked if defined?(OpenInChromeController) open_in_chrome in_request else open_in_safari in_request end return false # don't allow the web view to load the link. end end load_request_enable = true #return true on default for local file loading. load_request_enable = !!on_request(in_request, in_type) if self.respond_to?(:on_request) load_request_enable end
ruby
def webView(in_web, shouldStartLoadWithRequest:in_request, navigationType:in_type) if %w(http https).include?(in_request.URL.scheme) if self.external_links == true && in_type == UIWebViewNavigationTypeLinkClicked if defined?(OpenInChromeController) open_in_chrome in_request else open_in_safari in_request end return false # don't allow the web view to load the link. end end load_request_enable = true #return true on default for local file loading. load_request_enable = !!on_request(in_request, in_type) if self.respond_to?(:on_request) load_request_enable end
[ "def", "webView", "(", "in_web", ",", "shouldStartLoadWithRequest", ":", "in_request", ",", "navigationType", ":", "in_type", ")", "if", "%w(", "http", "https", ")", ".", "include?", "(", "in_request", ".", "URL", ".", "scheme", ")", "if", "self", ".", "external_links", "==", "true", "&&", "in_type", "==", "UIWebViewNavigationTypeLinkClicked", "if", "defined?", "(", "OpenInChromeController", ")", "open_in_chrome", "in_request", "else", "open_in_safari", "in_request", "end", "return", "false", "# don't allow the web view to load the link.", "end", "end", "load_request_enable", "=", "true", "#return true on default for local file loading.", "load_request_enable", "=", "!", "!", "on_request", "(", "in_request", ",", "in_type", ")", "if", "self", ".", "respond_to?", "(", ":on_request", ")", "load_request_enable", "end" ]
UIWebViewDelegate Methods - Camelcase
[ "UIWebViewDelegate", "Methods", "-", "Camelcase" ]
837d4b1dbdf7fac4ce6dee840223db5a917f0116
https://github.com/infinitered/ProMotion/blob/837d4b1dbdf7fac4ce6dee840223db5a917f0116/lib/ProMotion/web/web_screen_module.rb#L123-L138
16,505
infinitered/ProMotion
lib/ProMotion/ipad/split_screen.rb
ProMotion.SplitScreen.splitViewController
def splitViewController(svc, willHideViewController: vc, withBarButtonItem: button, forPopoverController: _) button ||= self.displayModeButtonItem if self.respond_to?(:displayModeButtonItem) return unless button button.title = @pm_split_screen_button_title || vc.title svc.detail_screen.navigationItem.leftBarButtonItem = button end
ruby
def splitViewController(svc, willHideViewController: vc, withBarButtonItem: button, forPopoverController: _) button ||= self.displayModeButtonItem if self.respond_to?(:displayModeButtonItem) return unless button button.title = @pm_split_screen_button_title || vc.title svc.detail_screen.navigationItem.leftBarButtonItem = button end
[ "def", "splitViewController", "(", "svc", ",", "willHideViewController", ":", "vc", ",", "withBarButtonItem", ":", "button", ",", "forPopoverController", ":", "_", ")", "button", "||=", "self", ".", "displayModeButtonItem", "if", "self", ".", "respond_to?", "(", ":displayModeButtonItem", ")", "return", "unless", "button", "button", ".", "title", "=", "@pm_split_screen_button_title", "||", "vc", ".", "title", "svc", ".", "detail_screen", ".", "navigationItem", ".", "leftBarButtonItem", "=", "button", "end" ]
UISplitViewControllerDelegate methods iOS 7 and below
[ "UISplitViewControllerDelegate", "methods", "iOS", "7", "and", "below" ]
837d4b1dbdf7fac4ce6dee840223db5a917f0116
https://github.com/infinitered/ProMotion/blob/837d4b1dbdf7fac4ce6dee840223db5a917f0116/lib/ProMotion/ipad/split_screen.rb#L20-L25
16,506
infinitered/ProMotion
lib/ProMotion/ipad/split_screen.rb
ProMotion.SplitScreen.splitViewController
def splitViewController(svc, willChangeToDisplayMode: display_mode) vc = svc.viewControllers.first vc = vc.topViewController if vc.respond_to?(:topViewController) case display_mode # when UISplitViewControllerDisplayModeAutomatic then do_something? when UISplitViewControllerDisplayModePrimaryHidden self.splitViewController(svc, willHideViewController: vc, withBarButtonItem: nil, forPopoverController: nil) # TODO: Add `self.master_screen.try(:will_hide_split_screen)` or similar? when UISplitViewControllerDisplayModeAllVisible self.splitViewController(svc, willShowViewController: vc, invalidatingBarButtonItem: nil) # TODO: Add `self.master_screen.try(:will_show_split_screen)` or similar? # when UISplitViewControllerDisplayModePrimaryOverlay # TODO: Add `self.master_screen.try(:will_show_split_screen_overlay)` or similar? end end
ruby
def splitViewController(svc, willChangeToDisplayMode: display_mode) vc = svc.viewControllers.first vc = vc.topViewController if vc.respond_to?(:topViewController) case display_mode # when UISplitViewControllerDisplayModeAutomatic then do_something? when UISplitViewControllerDisplayModePrimaryHidden self.splitViewController(svc, willHideViewController: vc, withBarButtonItem: nil, forPopoverController: nil) # TODO: Add `self.master_screen.try(:will_hide_split_screen)` or similar? when UISplitViewControllerDisplayModeAllVisible self.splitViewController(svc, willShowViewController: vc, invalidatingBarButtonItem: nil) # TODO: Add `self.master_screen.try(:will_show_split_screen)` or similar? # when UISplitViewControllerDisplayModePrimaryOverlay # TODO: Add `self.master_screen.try(:will_show_split_screen_overlay)` or similar? end end
[ "def", "splitViewController", "(", "svc", ",", "willChangeToDisplayMode", ":", "display_mode", ")", "vc", "=", "svc", ".", "viewControllers", ".", "first", "vc", "=", "vc", ".", "topViewController", "if", "vc", ".", "respond_to?", "(", ":topViewController", ")", "case", "display_mode", "# when UISplitViewControllerDisplayModeAutomatic then do_something?", "when", "UISplitViewControllerDisplayModePrimaryHidden", "self", ".", "splitViewController", "(", "svc", ",", "willHideViewController", ":", "vc", ",", "withBarButtonItem", ":", "nil", ",", "forPopoverController", ":", "nil", ")", "# TODO: Add `self.master_screen.try(:will_hide_split_screen)` or similar?", "when", "UISplitViewControllerDisplayModeAllVisible", "self", ".", "splitViewController", "(", "svc", ",", "willShowViewController", ":", "vc", ",", "invalidatingBarButtonItem", ":", "nil", ")", "# TODO: Add `self.master_screen.try(:will_show_split_screen)` or similar?", "# when UISplitViewControllerDisplayModePrimaryOverlay", "# TODO: Add `self.master_screen.try(:will_show_split_screen_overlay)` or similar?", "end", "end" ]
iOS 8 and above
[ "iOS", "8", "and", "above" ]
837d4b1dbdf7fac4ce6dee840223db5a917f0116
https://github.com/infinitered/ProMotion/blob/837d4b1dbdf7fac4ce6dee840223db5a917f0116/lib/ProMotion/ipad/split_screen.rb#L32-L46
16,507
infinitered/ProMotion
lib/ProMotion/styling/styling.rb
ProMotion.Styling.closest_parent
def closest_parent(type, this_view = nil) this_view ||= view_or_self.superview while this_view != nil do return this_view if this_view.is_a? type this_view = this_view.superview end nil end
ruby
def closest_parent(type, this_view = nil) this_view ||= view_or_self.superview while this_view != nil do return this_view if this_view.is_a? type this_view = this_view.superview end nil end
[ "def", "closest_parent", "(", "type", ",", "this_view", "=", "nil", ")", "this_view", "||=", "view_or_self", ".", "superview", "while", "this_view", "!=", "nil", "do", "return", "this_view", "if", "this_view", ".", "is_a?", "type", "this_view", "=", "this_view", ".", "superview", "end", "nil", "end" ]
iterate up the view hierarchy to find the parent element of "type" containing this view
[ "iterate", "up", "the", "view", "hierarchy", "to", "find", "the", "parent", "element", "of", "type", "containing", "this", "view" ]
837d4b1dbdf7fac4ce6dee840223db5a917f0116
https://github.com/infinitered/ProMotion/blob/837d4b1dbdf7fac4ce6dee840223db5a917f0116/lib/ProMotion/styling/styling.rb#L58-L65
16,508
jackc/tod
lib/tod/shift.rb
Tod.Shift.include?
def include?(tod) second = tod.to_i second += TimeOfDay::NUM_SECONDS_IN_DAY if second < @range.first @range.cover?(second) end
ruby
def include?(tod) second = tod.to_i second += TimeOfDay::NUM_SECONDS_IN_DAY if second < @range.first @range.cover?(second) end
[ "def", "include?", "(", "tod", ")", "second", "=", "tod", ".", "to_i", "second", "+=", "TimeOfDay", "::", "NUM_SECONDS_IN_DAY", "if", "second", "<", "@range", ".", "first", "@range", ".", "cover?", "(", "second", ")", "end" ]
Returns true if the time of day is inside the shift, false otherwise.
[ "Returns", "true", "if", "the", "time", "of", "day", "is", "inside", "the", "shift", "false", "otherwise", "." ]
14c54f00e056264379484d2d8f55568e327a3b74
https://github.com/jackc/tod/blob/14c54f00e056264379484d2d8f55568e327a3b74/lib/tod/shift.rb#L28-L32
16,509
jackc/tod
lib/tod/shift.rb
Tod.Shift.overlaps?
def overlaps?(other) max_seconds = TimeOfDay::NUM_SECONDS_IN_DAY # Standard case, when Shifts are on the same day a, b = [self, other].map(&:range).sort_by(&:first) op = a.exclude_end? ? :> : :>= return true if a.last.send(op, b.first) # Special cases, when Shifts span to the next day return false if (a.last < max_seconds) && (b.last < max_seconds) a = Range.new(a.first, a.last - max_seconds, a.exclude_end?) if a.last > max_seconds b = Range.new(b.first, b.last - max_seconds, b.exclude_end?) if b.last > max_seconds a, b = [a, b].sort_by(&:last) b.last.send(op, a.last) && a.last.send(op, b.first) end
ruby
def overlaps?(other) max_seconds = TimeOfDay::NUM_SECONDS_IN_DAY # Standard case, when Shifts are on the same day a, b = [self, other].map(&:range).sort_by(&:first) op = a.exclude_end? ? :> : :>= return true if a.last.send(op, b.first) # Special cases, when Shifts span to the next day return false if (a.last < max_seconds) && (b.last < max_seconds) a = Range.new(a.first, a.last - max_seconds, a.exclude_end?) if a.last > max_seconds b = Range.new(b.first, b.last - max_seconds, b.exclude_end?) if b.last > max_seconds a, b = [a, b].sort_by(&:last) b.last.send(op, a.last) && a.last.send(op, b.first) end
[ "def", "overlaps?", "(", "other", ")", "max_seconds", "=", "TimeOfDay", "::", "NUM_SECONDS_IN_DAY", "# Standard case, when Shifts are on the same day", "a", ",", "b", "=", "[", "self", ",", "other", "]", ".", "map", "(", ":range", ")", ".", "sort_by", "(", ":first", ")", "op", "=", "a", ".", "exclude_end?", "?", ":>", ":", ":>=", "return", "true", "if", "a", ".", "last", ".", "send", "(", "op", ",", "b", ".", "first", ")", "# Special cases, when Shifts span to the next day", "return", "false", "if", "(", "a", ".", "last", "<", "max_seconds", ")", "&&", "(", "b", ".", "last", "<", "max_seconds", ")", "a", "=", "Range", ".", "new", "(", "a", ".", "first", ",", "a", ".", "last", "-", "max_seconds", ",", "a", ".", "exclude_end?", ")", "if", "a", ".", "last", ">", "max_seconds", "b", "=", "Range", ".", "new", "(", "b", ".", "first", ",", "b", ".", "last", "-", "max_seconds", ",", "b", ".", "exclude_end?", ")", "if", "b", ".", "last", ">", "max_seconds", "a", ",", "b", "=", "[", "a", ",", "b", "]", ".", "sort_by", "(", ":last", ")", "b", ".", "last", ".", "send", "(", "op", ",", "a", ".", "last", ")", "&&", "a", ".", "last", ".", "send", "(", "op", ",", "b", ".", "first", ")", "end" ]
Returns true if ranges overlap, false otherwise.
[ "Returns", "true", "if", "ranges", "overlap", "false", "otherwise", "." ]
14c54f00e056264379484d2d8f55568e327a3b74
https://github.com/jackc/tod/blob/14c54f00e056264379484d2d8f55568e327a3b74/lib/tod/shift.rb#L35-L50
16,510
jackc/tod
lib/tod/time_of_day.rb
Tod.TimeOfDay.round
def round(round_sec = 1) down = self - (self.to_i % round_sec) up = down + round_sec difference_down = self - down difference_up = up - self if (difference_down < difference_up) return down else return up end end
ruby
def round(round_sec = 1) down = self - (self.to_i % round_sec) up = down + round_sec difference_down = self - down difference_up = up - self if (difference_down < difference_up) return down else return up end end
[ "def", "round", "(", "round_sec", "=", "1", ")", "down", "=", "self", "-", "(", "self", ".", "to_i", "%", "round_sec", ")", "up", "=", "down", "+", "round_sec", "difference_down", "=", "self", "-", "down", "difference_up", "=", "up", "-", "self", "if", "(", "difference_down", "<", "difference_up", ")", "return", "down", "else", "return", "up", "end", "end" ]
Rounding to the given nearest number of seconds
[ "Rounding", "to", "the", "given", "nearest", "number", "of", "seconds" ]
14c54f00e056264379484d2d8f55568e327a3b74
https://github.com/jackc/tod/blob/14c54f00e056264379484d2d8f55568e327a3b74/lib/tod/time_of_day.rb#L74-L86
16,511
jackc/tod
lib/tod/time_of_day.rb
Tod.TimeOfDay.-
def -(other) if other.instance_of?(TimeOfDay) TimeOfDay.from_second_of_day @second_of_day - other.second_of_day else TimeOfDay.from_second_of_day @second_of_day - other end end
ruby
def -(other) if other.instance_of?(TimeOfDay) TimeOfDay.from_second_of_day @second_of_day - other.second_of_day else TimeOfDay.from_second_of_day @second_of_day - other end end
[ "def", "-", "(", "other", ")", "if", "other", ".", "instance_of?", "(", "TimeOfDay", ")", "TimeOfDay", ".", "from_second_of_day", "@second_of_day", "-", "other", ".", "second_of_day", "else", "TimeOfDay", ".", "from_second_of_day", "@second_of_day", "-", "other", "end", "end" ]
Return a new TimeOfDay num_seconds less than self. It will wrap around at midnight.
[ "Return", "a", "new", "TimeOfDay", "num_seconds", "less", "than", "self", ".", "It", "will", "wrap", "around", "at", "midnight", "." ]
14c54f00e056264379484d2d8f55568e327a3b74
https://github.com/jackc/tod/blob/14c54f00e056264379484d2d8f55568e327a3b74/lib/tod/time_of_day.rb#L121-L127
16,512
jackc/tod
lib/tod/time_of_day.rb
Tod.TimeOfDay.on
def on(date, time_zone=Tod::TimeOfDay.time_zone) time_zone.local date.year, date.month, date.day, @hour, @minute, @second end
ruby
def on(date, time_zone=Tod::TimeOfDay.time_zone) time_zone.local date.year, date.month, date.day, @hour, @minute, @second end
[ "def", "on", "(", "date", ",", "time_zone", "=", "Tod", "::", "TimeOfDay", ".", "time_zone", ")", "time_zone", ".", "local", "date", ".", "year", ",", "date", ".", "month", ",", "date", ".", "day", ",", "@hour", ",", "@minute", ",", "@second", "end" ]
Returns a Time instance on date using self as the time of day Optional time_zone will build time in that zone
[ "Returns", "a", "Time", "instance", "on", "date", "using", "self", "as", "the", "time", "of", "day", "Optional", "time_zone", "will", "build", "time", "in", "that", "zone" ]
14c54f00e056264379484d2d8f55568e327a3b74
https://github.com/jackc/tod/blob/14c54f00e056264379484d2d8f55568e327a3b74/lib/tod/time_of_day.rb#L131-L133
16,513
opentracing/opentracing-ruby
lib/opentracing/tracer.rb
OpenTracing.Tracer.extract
def extract(format, carrier) case format when OpenTracing::FORMAT_TEXT_MAP, OpenTracing::FORMAT_BINARY, OpenTracing::FORMAT_RACK return SpanContext::NOOP_INSTANCE else warn 'Unknown extract format' nil end end
ruby
def extract(format, carrier) case format when OpenTracing::FORMAT_TEXT_MAP, OpenTracing::FORMAT_BINARY, OpenTracing::FORMAT_RACK return SpanContext::NOOP_INSTANCE else warn 'Unknown extract format' nil end end
[ "def", "extract", "(", "format", ",", "carrier", ")", "case", "format", "when", "OpenTracing", "::", "FORMAT_TEXT_MAP", ",", "OpenTracing", "::", "FORMAT_BINARY", ",", "OpenTracing", "::", "FORMAT_RACK", "return", "SpanContext", "::", "NOOP_INSTANCE", "else", "warn", "'Unknown extract format'", "nil", "end", "end" ]
Extract a SpanContext in the given format from the given carrier. @param format [OpenTracing::FORMAT_TEXT_MAP, OpenTracing::FORMAT_BINARY, OpenTracing::FORMAT_RACK] @param carrier [Carrier] A carrier object of the type dictated by the specified `format` @return [SpanContext, nil] the extracted SpanContext or nil if none could be found
[ "Extract", "a", "SpanContext", "in", "the", "given", "format", "from", "the", "given", "carrier", "." ]
01304d46b6d8322e23bb2962189c0cd14065c886
https://github.com/opentracing/opentracing-ruby/blob/01304d46b6d8322e23bb2962189c0cd14065c886/lib/opentracing/tracer.rb#L116-L124
16,514
mailboxer/mailboxer
lib/mailboxer/recipient_filter.rb
Mailboxer.RecipientFilter.call
def call return recipients unless mailable.respond_to?(:conversation) recipients.each_with_object([]) do |recipient, array| array << recipient if mailable.conversation.has_subscriber?(recipient) end end
ruby
def call return recipients unless mailable.respond_to?(:conversation) recipients.each_with_object([]) do |recipient, array| array << recipient if mailable.conversation.has_subscriber?(recipient) end end
[ "def", "call", "return", "recipients", "unless", "mailable", ".", "respond_to?", "(", ":conversation", ")", "recipients", ".", "each_with_object", "(", "[", "]", ")", "do", "|", "recipient", ",", "array", "|", "array", "<<", "recipient", "if", "mailable", ".", "conversation", ".", "has_subscriber?", "(", "recipient", ")", "end", "end" ]
recipients can be filtered on a conversation basis
[ "recipients", "can", "be", "filtered", "on", "a", "conversation", "basis" ]
3e148858879110c3258b46152b11e5bfc514dc04
https://github.com/mailboxer/mailboxer/blob/3e148858879110c3258b46152b11e5bfc514dc04/lib/mailboxer/recipient_filter.rb#L9-L15
16,515
lassebunk/dynamic_sitemaps
lib/dynamic_sitemaps/index_generator.rb
DynamicSitemaps.IndexGenerator.generate
def generate sitemaps.group_by(&:folder).each do |folder, sitemaps| index_path = "#{DynamicSitemaps.temp_path}/#{folder}/#{DynamicSitemaps.index_file_name}" if !DynamicSitemaps.always_generate_index && sitemaps.count == 1 && sitemaps.first.files.count == 1 file_path = "#{DynamicSitemaps.temp_path}/#{folder}/#{sitemaps.first.files.first}" FileUtils.copy file_path, index_path File.delete file_path else File.open(index_path, "w") do |file| write_beginning(file) write_sitemaps(file, sitemaps) write_end(file) end end end end
ruby
def generate sitemaps.group_by(&:folder).each do |folder, sitemaps| index_path = "#{DynamicSitemaps.temp_path}/#{folder}/#{DynamicSitemaps.index_file_name}" if !DynamicSitemaps.always_generate_index && sitemaps.count == 1 && sitemaps.first.files.count == 1 file_path = "#{DynamicSitemaps.temp_path}/#{folder}/#{sitemaps.first.files.first}" FileUtils.copy file_path, index_path File.delete file_path else File.open(index_path, "w") do |file| write_beginning(file) write_sitemaps(file, sitemaps) write_end(file) end end end end
[ "def", "generate", "sitemaps", ".", "group_by", "(", ":folder", ")", ".", "each", "do", "|", "folder", ",", "sitemaps", "|", "index_path", "=", "\"#{DynamicSitemaps.temp_path}/#{folder}/#{DynamicSitemaps.index_file_name}\"", "if", "!", "DynamicSitemaps", ".", "always_generate_index", "&&", "sitemaps", ".", "count", "==", "1", "&&", "sitemaps", ".", "first", ".", "files", ".", "count", "==", "1", "file_path", "=", "\"#{DynamicSitemaps.temp_path}/#{folder}/#{sitemaps.first.files.first}\"", "FileUtils", ".", "copy", "file_path", ",", "index_path", "File", ".", "delete", "file_path", "else", "File", ".", "open", "(", "index_path", ",", "\"w\"", ")", "do", "|", "file", "|", "write_beginning", "(", "file", ")", "write_sitemaps", "(", "file", ",", "sitemaps", ")", "write_end", "(", "file", ")", "end", "end", "end", "end" ]
Array of sitemap results Initialize the class with an array of SitemapResult
[ "Array", "of", "sitemap", "results", "Initialize", "the", "class", "with", "an", "array", "of", "SitemapResult" ]
37beeba143e8202218ee814056231b0e6974bafb
https://github.com/lassebunk/dynamic_sitemaps/blob/37beeba143e8202218ee814056231b0e6974bafb/lib/dynamic_sitemaps/index_generator.rb#L10-L26
16,516
ianfixes/arduino_ci
lib/arduino_ci/cpp_library.rb
ArduinoCI.CppLibrary.cpp_files_in
def cpp_files_in(some_dir) raise ArgumentError, 'some_dir is not a Pathname' unless some_dir.is_a? Pathname return [] unless some_dir.exist? && some_dir.directory? real = some_dir.realpath files = Find.find(real).map { |p| Pathname.new(p) }.reject(&:directory?) cpp = files.select { |path| CPP_EXTENSIONS.include?(path.extname.downcase) } not_hidden = cpp.reject { |path| path.basename.to_s.start_with?(".") } not_hidden.sort_by(&:to_s) end
ruby
def cpp_files_in(some_dir) raise ArgumentError, 'some_dir is not a Pathname' unless some_dir.is_a? Pathname return [] unless some_dir.exist? && some_dir.directory? real = some_dir.realpath files = Find.find(real).map { |p| Pathname.new(p) }.reject(&:directory?) cpp = files.select { |path| CPP_EXTENSIONS.include?(path.extname.downcase) } not_hidden = cpp.reject { |path| path.basename.to_s.start_with?(".") } not_hidden.sort_by(&:to_s) end
[ "def", "cpp_files_in", "(", "some_dir", ")", "raise", "ArgumentError", ",", "'some_dir is not a Pathname'", "unless", "some_dir", ".", "is_a?", "Pathname", "return", "[", "]", "unless", "some_dir", ".", "exist?", "&&", "some_dir", ".", "directory?", "real", "=", "some_dir", ".", "realpath", "files", "=", "Find", ".", "find", "(", "real", ")", ".", "map", "{", "|", "p", "|", "Pathname", ".", "new", "(", "p", ")", "}", ".", "reject", "(", ":directory?", ")", "cpp", "=", "files", ".", "select", "{", "|", "path", "|", "CPP_EXTENSIONS", ".", "include?", "(", "path", ".", "extname", ".", "downcase", ")", "}", "not_hidden", "=", "cpp", ".", "reject", "{", "|", "path", "|", "path", ".", "basename", ".", "to_s", ".", "start_with?", "(", "\".\"", ")", "}", "not_hidden", ".", "sort_by", "(", ":to_s", ")", "end" ]
Get a list of all CPP source files in a directory and its subdirectories @param some_dir [Pathname] The directory in which to begin the search @return [Array<Pathname>] The paths of the found files
[ "Get", "a", "list", "of", "all", "CPP", "source", "files", "in", "a", "directory", "and", "its", "subdirectories" ]
cb3fe8df14a744b9a3bc5cdc0168f820f78cde57
https://github.com/ianfixes/arduino_ci/blob/cb3fe8df14a744b9a3bc5cdc0168f820f78cde57/lib/arduino_ci/cpp_library.rb#L139-L148
16,517
ianfixes/arduino_ci
lib/arduino_ci/cpp_library.rb
ArduinoCI.CppLibrary.cpp_files_libraries
def cpp_files_libraries(aux_libraries) arduino_library_src_dirs(aux_libraries).map { |d| cpp_files_in(d) }.flatten.uniq end
ruby
def cpp_files_libraries(aux_libraries) arduino_library_src_dirs(aux_libraries).map { |d| cpp_files_in(d) }.flatten.uniq end
[ "def", "cpp_files_libraries", "(", "aux_libraries", ")", "arduino_library_src_dirs", "(", "aux_libraries", ")", ".", "map", "{", "|", "d", "|", "cpp_files_in", "(", "d", ")", "}", ".", "flatten", ".", "uniq", "end" ]
CPP files that are part of the 3rd-party libraries we're including @param [Array<String>] aux_libraries @return [Array<Pathname>]
[ "CPP", "files", "that", "are", "part", "of", "the", "3rd", "-", "party", "libraries", "we", "re", "including" ]
cb3fe8df14a744b9a3bc5cdc0168f820f78cde57
https://github.com/ianfixes/arduino_ci/blob/cb3fe8df14a744b9a3bc5cdc0168f820f78cde57/lib/arduino_ci/cpp_library.rb#L171-L173
16,518
ianfixes/arduino_ci
lib/arduino_ci/cpp_library.rb
ArduinoCI.CppLibrary.header_dirs
def header_dirs real = @base_dir.realpath all_files = Find.find(real).map { |f| Pathname.new(f) }.reject(&:directory?) unbundled = all_files.reject { |path| vendor_bundle?(path) } files = unbundled.select { |path| HPP_EXTENSIONS.include?(path.extname.downcase) } files.map(&:dirname).uniq end
ruby
def header_dirs real = @base_dir.realpath all_files = Find.find(real).map { |f| Pathname.new(f) }.reject(&:directory?) unbundled = all_files.reject { |path| vendor_bundle?(path) } files = unbundled.select { |path| HPP_EXTENSIONS.include?(path.extname.downcase) } files.map(&:dirname).uniq end
[ "def", "header_dirs", "real", "=", "@base_dir", ".", "realpath", "all_files", "=", "Find", ".", "find", "(", "real", ")", ".", "map", "{", "|", "f", "|", "Pathname", ".", "new", "(", "f", ")", "}", ".", "reject", "(", ":directory?", ")", "unbundled", "=", "all_files", ".", "reject", "{", "|", "path", "|", "vendor_bundle?", "(", "path", ")", "}", "files", "=", "unbundled", ".", "select", "{", "|", "path", "|", "HPP_EXTENSIONS", ".", "include?", "(", "path", ".", "extname", ".", "downcase", ")", "}", "files", ".", "map", "(", ":dirname", ")", ".", "uniq", "end" ]
Find all directories in the project library that include C++ header files @return [Array<Pathname>]
[ "Find", "all", "directories", "in", "the", "project", "library", "that", "include", "C", "++", "header", "files" ]
cb3fe8df14a744b9a3bc5cdc0168f820f78cde57
https://github.com/ianfixes/arduino_ci/blob/cb3fe8df14a744b9a3bc5cdc0168f820f78cde57/lib/arduino_ci/cpp_library.rb#L189-L195
16,519
ianfixes/arduino_ci
lib/arduino_ci/cpp_library.rb
ArduinoCI.CppLibrary.run_gcc
def run_gcc(gcc_binary, *args, **kwargs) full_args = [gcc_binary] + args @last_cmd = " $ #{full_args.join(' ')}" ret = Host.run_and_capture(*full_args, **kwargs) @last_err = ret[:err] @last_out = ret[:out] ret[:success] end
ruby
def run_gcc(gcc_binary, *args, **kwargs) full_args = [gcc_binary] + args @last_cmd = " $ #{full_args.join(' ')}" ret = Host.run_and_capture(*full_args, **kwargs) @last_err = ret[:err] @last_out = ret[:out] ret[:success] end
[ "def", "run_gcc", "(", "gcc_binary", ",", "*", "args", ",", "**", "kwargs", ")", "full_args", "=", "[", "gcc_binary", "]", "+", "args", "@last_cmd", "=", "\" $ #{full_args.join(' ')}\"", "ret", "=", "Host", ".", "run_and_capture", "(", "full_args", ",", "**", "kwargs", ")", "@last_err", "=", "ret", "[", ":err", "]", "@last_out", "=", "ret", "[", ":out", "]", "ret", "[", ":success", "]", "end" ]
wrapper for the GCC command
[ "wrapper", "for", "the", "GCC", "command" ]
cb3fe8df14a744b9a3bc5cdc0168f820f78cde57
https://github.com/ianfixes/arduino_ci/blob/cb3fe8df14a744b9a3bc5cdc0168f820f78cde57/lib/arduino_ci/cpp_library.rb#L198-L205
16,520
ianfixes/arduino_ci
lib/arduino_ci/cpp_library.rb
ArduinoCI.CppLibrary.arduino_library_src_dirs
def arduino_library_src_dirs(aux_libraries) # Pull in all possible places that headers could live, according to the spec: # https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification # TODO: be smart and implement library spec (library.properties, etc)? subdirs = ["", "src", "utility"] all_aux_include_dirs_nested = aux_libraries.map do |libdir| subdirs.map { |subdir| Pathname.new(@arduino_lib_dir) + libdir + subdir } end all_aux_include_dirs_nested.flatten.select(&:exist?).select(&:directory?) end
ruby
def arduino_library_src_dirs(aux_libraries) # Pull in all possible places that headers could live, according to the spec: # https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification # TODO: be smart and implement library spec (library.properties, etc)? subdirs = ["", "src", "utility"] all_aux_include_dirs_nested = aux_libraries.map do |libdir| subdirs.map { |subdir| Pathname.new(@arduino_lib_dir) + libdir + subdir } end all_aux_include_dirs_nested.flatten.select(&:exist?).select(&:directory?) end
[ "def", "arduino_library_src_dirs", "(", "aux_libraries", ")", "# Pull in all possible places that headers could live, according to the spec:", "# https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification", "# TODO: be smart and implement library spec (library.properties, etc)?", "subdirs", "=", "[", "\"\"", ",", "\"src\"", ",", "\"utility\"", "]", "all_aux_include_dirs_nested", "=", "aux_libraries", ".", "map", "do", "|", "libdir", "|", "subdirs", ".", "map", "{", "|", "subdir", "|", "Pathname", ".", "new", "(", "@arduino_lib_dir", ")", "+", "libdir", "+", "subdir", "}", "end", "all_aux_include_dirs_nested", ".", "flatten", ".", "select", "(", ":exist?", ")", ".", "select", "(", ":directory?", ")", "end" ]
Arduino library directories containing sources @return [Array<Pathname>]
[ "Arduino", "library", "directories", "containing", "sources" ]
cb3fe8df14a744b9a3bc5cdc0168f820f78cde57
https://github.com/ianfixes/arduino_ci/blob/cb3fe8df14a744b9a3bc5cdc0168f820f78cde57/lib/arduino_ci/cpp_library.rb#L217-L226
16,521
ianfixes/arduino_ci
lib/arduino_ci/cpp_library.rb
ArduinoCI.CppLibrary.include_args
def include_args(aux_libraries) all_aux_include_dirs = arduino_library_src_dirs(aux_libraries) places = [ARDUINO_HEADER_DIR, UNITTEST_HEADER_DIR] + header_dirs + all_aux_include_dirs places.map { |d| "-I#{d}" } end
ruby
def include_args(aux_libraries) all_aux_include_dirs = arduino_library_src_dirs(aux_libraries) places = [ARDUINO_HEADER_DIR, UNITTEST_HEADER_DIR] + header_dirs + all_aux_include_dirs places.map { |d| "-I#{d}" } end
[ "def", "include_args", "(", "aux_libraries", ")", "all_aux_include_dirs", "=", "arduino_library_src_dirs", "(", "aux_libraries", ")", "places", "=", "[", "ARDUINO_HEADER_DIR", ",", "UNITTEST_HEADER_DIR", "]", "+", "header_dirs", "+", "all_aux_include_dirs", "places", ".", "map", "{", "|", "d", "|", "\"-I#{d}\"", "}", "end" ]
GCC command line arguments for including aux libraries @param aux_libraries [Array<Pathname>] The external Arduino libraries required by this project @return [Array<String>] The GCC command-line flags necessary to include those libraries
[ "GCC", "command", "line", "arguments", "for", "including", "aux", "libraries" ]
cb3fe8df14a744b9a3bc5cdc0168f820f78cde57
https://github.com/ianfixes/arduino_ci/blob/cb3fe8df14a744b9a3bc5cdc0168f820f78cde57/lib/arduino_ci/cpp_library.rb#L231-L235
16,522
ianfixes/arduino_ci
lib/arduino_ci/arduino_downloader.rb
ArduinoCI.ArduinoDownloader.execute
def execute error_preparing = prepare unless error_preparing.nil? @output.puts "Arduino force-install failed preparation: #{error_preparing}" return false end attempts = 0 loop do if File.exist? package_file @output.puts "Arduino package seems to have been downloaded already" if attempts.zero? break elsif attempts >= DOWNLOAD_ATTEMPTS break @output.puts "After #{DOWNLOAD_ATTEMPTS} attempts, failed to download #{package_url}" else @output.print "Attempting to download Arduino package with #{downloader}" download @output.puts end attempts += 1 end if File.exist? extracted_file @output.puts "Arduino package seems to have been extracted already" elsif File.exist? package_file @output.print "Extracting archive with #{extracter}" extract @output.puts end if File.exist? self.class.force_install_location @output.puts "Arduino package seems to have been installed already" elsif File.exist? extracted_file install else @output.puts "Could not find extracted archive (tried #{extracted_file})" end File.exist? self.class.force_install_location end
ruby
def execute error_preparing = prepare unless error_preparing.nil? @output.puts "Arduino force-install failed preparation: #{error_preparing}" return false end attempts = 0 loop do if File.exist? package_file @output.puts "Arduino package seems to have been downloaded already" if attempts.zero? break elsif attempts >= DOWNLOAD_ATTEMPTS break @output.puts "After #{DOWNLOAD_ATTEMPTS} attempts, failed to download #{package_url}" else @output.print "Attempting to download Arduino package with #{downloader}" download @output.puts end attempts += 1 end if File.exist? extracted_file @output.puts "Arduino package seems to have been extracted already" elsif File.exist? package_file @output.print "Extracting archive with #{extracter}" extract @output.puts end if File.exist? self.class.force_install_location @output.puts "Arduino package seems to have been installed already" elsif File.exist? extracted_file install else @output.puts "Could not find extracted archive (tried #{extracted_file})" end File.exist? self.class.force_install_location end
[ "def", "execute", "error_preparing", "=", "prepare", "unless", "error_preparing", ".", "nil?", "@output", ".", "puts", "\"Arduino force-install failed preparation: #{error_preparing}\"", "return", "false", "end", "attempts", "=", "0", "loop", "do", "if", "File", ".", "exist?", "package_file", "@output", ".", "puts", "\"Arduino package seems to have been downloaded already\"", "if", "attempts", ".", "zero?", "break", "elsif", "attempts", ">=", "DOWNLOAD_ATTEMPTS", "break", "@output", ".", "puts", "\"After #{DOWNLOAD_ATTEMPTS} attempts, failed to download #{package_url}\"", "else", "@output", ".", "print", "\"Attempting to download Arduino package with #{downloader}\"", "download", "@output", ".", "puts", "end", "attempts", "+=", "1", "end", "if", "File", ".", "exist?", "extracted_file", "@output", ".", "puts", "\"Arduino package seems to have been extracted already\"", "elsif", "File", ".", "exist?", "package_file", "@output", ".", "print", "\"Extracting archive with #{extracter}\"", "extract", "@output", ".", "puts", "end", "if", "File", ".", "exist?", "self", ".", "class", ".", "force_install_location", "@output", ".", "puts", "\"Arduino package seems to have been installed already\"", "elsif", "File", ".", "exist?", "extracted_file", "install", "else", "@output", ".", "puts", "\"Could not find extracted archive (tried #{extracted_file})\"", "end", "File", ".", "exist?", "self", ".", "class", ".", "force_install_location", "end" ]
Forcibly install Arduino on linux from the web @return [bool] Whether the command succeeded
[ "Forcibly", "install", "Arduino", "on", "linux", "from", "the", "web" ]
cb3fe8df14a744b9a3bc5cdc0168f820f78cde57
https://github.com/ianfixes/arduino_ci/blob/cb3fe8df14a744b9a3bc5cdc0168f820f78cde57/lib/arduino_ci/arduino_downloader.rb#L157-L197
16,523
ianfixes/arduino_ci
lib/arduino_ci/arduino_cmd.rb
ArduinoCI.ArduinoCmd.parse_pref_string
def parse_pref_string(arduino_output) lines = arduino_output.split("\n").select { |l| l.include? "=" } ret = lines.each_with_object({}) do |e, acc| parts = e.split("=", 2) acc[parts[0]] = parts[1] acc end ret end
ruby
def parse_pref_string(arduino_output) lines = arduino_output.split("\n").select { |l| l.include? "=" } ret = lines.each_with_object({}) do |e, acc| parts = e.split("=", 2) acc[parts[0]] = parts[1] acc end ret end
[ "def", "parse_pref_string", "(", "arduino_output", ")", "lines", "=", "arduino_output", ".", "split", "(", "\"\\n\"", ")", ".", "select", "{", "|", "l", "|", "l", ".", "include?", "\"=\"", "}", "ret", "=", "lines", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "e", ",", "acc", "|", "parts", "=", "e", ".", "split", "(", "\"=\"", ",", "2", ")", "acc", "[", "parts", "[", "0", "]", "]", "=", "parts", "[", "1", "]", "acc", "end", "ret", "end" ]
Convert a preferences dump into a flat hash @param arduino_output [String] The raw Arduino executable output @return [Hash] preferences as a hash
[ "Convert", "a", "preferences", "dump", "into", "a", "flat", "hash" ]
cb3fe8df14a744b9a3bc5cdc0168f820f78cde57
https://github.com/ianfixes/arduino_ci/blob/cb3fe8df14a744b9a3bc5cdc0168f820f78cde57/lib/arduino_ci/arduino_cmd.rb#L66-L74
16,524
ianfixes/arduino_ci
lib/arduino_ci/arduino_cmd.rb
ArduinoCI.ArduinoCmd.run_and_output
def run_and_output(*args, **kwargs) _wrap_run((proc { |*a, **k| Host.run_and_output(*a, **k) }), *args, **kwargs) end
ruby
def run_and_output(*args, **kwargs) _wrap_run((proc { |*a, **k| Host.run_and_output(*a, **k) }), *args, **kwargs) end
[ "def", "run_and_output", "(", "*", "args", ",", "**", "kwargs", ")", "_wrap_run", "(", "(", "proc", "{", "|", "*", "a", ",", "**", "k", "|", "Host", ".", "run_and_output", "(", "a", ",", "**", "k", ")", "}", ")", ",", "args", ",", "**", "kwargs", ")", "end" ]
build and run the arduino command
[ "build", "and", "run", "the", "arduino", "command" ]
cb3fe8df14a744b9a3bc5cdc0168f820f78cde57
https://github.com/ianfixes/arduino_ci/blob/cb3fe8df14a744b9a3bc5cdc0168f820f78cde57/lib/arduino_ci/arduino_cmd.rb#L142-L144
16,525
ianfixes/arduino_ci
lib/arduino_ci/arduino_cmd.rb
ArduinoCI.ArduinoCmd.run_and_capture
def run_and_capture(*args, **kwargs) ret = _wrap_run((proc { |*a, **k| Host.run_and_capture(*a, **k) }), *args, **kwargs) @last_err = ret[:err] @last_out = ret[:out] ret end
ruby
def run_and_capture(*args, **kwargs) ret = _wrap_run((proc { |*a, **k| Host.run_and_capture(*a, **k) }), *args, **kwargs) @last_err = ret[:err] @last_out = ret[:out] ret end
[ "def", "run_and_capture", "(", "*", "args", ",", "**", "kwargs", ")", "ret", "=", "_wrap_run", "(", "(", "proc", "{", "|", "*", "a", ",", "**", "k", "|", "Host", ".", "run_and_capture", "(", "a", ",", "**", "k", ")", "}", ")", ",", "args", ",", "**", "kwargs", ")", "@last_err", "=", "ret", "[", ":err", "]", "@last_out", "=", "ret", "[", ":out", "]", "ret", "end" ]
run a command and capture its output @return [Hash] {:out => String, :err => String, :success => bool}
[ "run", "a", "command", "and", "capture", "its", "output" ]
cb3fe8df14a744b9a3bc5cdc0168f820f78cde57
https://github.com/ianfixes/arduino_ci/blob/cb3fe8df14a744b9a3bc5cdc0168f820f78cde57/lib/arduino_ci/arduino_cmd.rb#L148-L153
16,526
ianfixes/arduino_ci
lib/arduino_ci/arduino_cmd.rb
ArduinoCI.ArduinoCmd.install_boards
def install_boards(boardfamily) # TODO: find out why IO.pipe fails but File::NULL succeeds :( result = run_and_capture(flag_install_boards, boardfamily) already_installed = result[:err].include?("Platform is already installed!") result[:success] || already_installed end
ruby
def install_boards(boardfamily) # TODO: find out why IO.pipe fails but File::NULL succeeds :( result = run_and_capture(flag_install_boards, boardfamily) already_installed = result[:err].include?("Platform is already installed!") result[:success] || already_installed end
[ "def", "install_boards", "(", "boardfamily", ")", "# TODO: find out why IO.pipe fails but File::NULL succeeds :(", "result", "=", "run_and_capture", "(", "flag_install_boards", ",", "boardfamily", ")", "already_installed", "=", "result", "[", ":err", "]", ".", "include?", "(", "\"Platform is already installed!\"", ")", "result", "[", ":success", "]", "||", "already_installed", "end" ]
install a board by name @param name [String] the board name @return [bool] whether the command succeeded
[ "install", "a", "board", "by", "name" ]
cb3fe8df14a744b9a3bc5cdc0168f820f78cde57
https://github.com/ianfixes/arduino_ci/blob/cb3fe8df14a744b9a3bc5cdc0168f820f78cde57/lib/arduino_ci/arduino_cmd.rb#L182-L187
16,527
ianfixes/arduino_ci
lib/arduino_ci/arduino_cmd.rb
ArduinoCI.ArduinoCmd._install_library
def _install_library(library_name) result = run_and_capture(flag_install_library, library_name) already_installed = result[:err].include?("Library is already installed: #{library_name}") success = result[:success] || already_installed @libraries_indexed = (@libraries_indexed || success) if library_name == WORKAROUND_LIB success end
ruby
def _install_library(library_name) result = run_and_capture(flag_install_library, library_name) already_installed = result[:err].include?("Library is already installed: #{library_name}") success = result[:success] || already_installed @libraries_indexed = (@libraries_indexed || success) if library_name == WORKAROUND_LIB success end
[ "def", "_install_library", "(", "library_name", ")", "result", "=", "run_and_capture", "(", "flag_install_library", ",", "library_name", ")", "already_installed", "=", "result", "[", ":err", "]", ".", "include?", "(", "\"Library is already installed: #{library_name}\"", ")", "success", "=", "result", "[", ":success", "]", "||", "already_installed", "@libraries_indexed", "=", "(", "@libraries_indexed", "||", "success", ")", "if", "library_name", "==", "WORKAROUND_LIB", "success", "end" ]
install a library by name @param name [String] the library name @return [bool] whether the command succeeded
[ "install", "a", "library", "by", "name" ]
cb3fe8df14a744b9a3bc5cdc0168f820f78cde57
https://github.com/ianfixes/arduino_ci/blob/cb3fe8df14a744b9a3bc5cdc0168f820f78cde57/lib/arduino_ci/arduino_cmd.rb#L192-L200
16,528
ianfixes/arduino_ci
lib/arduino_ci/arduino_cmd.rb
ArduinoCI.ArduinoCmd.use_board!
def use_board!(boardname) return true if use_board(boardname) boardfamily = boardname.split(":")[0..1].join(":") puts "Board '#{boardname}' not found; attempting to install '#{boardfamily}'" return false unless install_boards(boardfamily) # guess board family from first 2 :-separated fields use_board(boardname) end
ruby
def use_board!(boardname) return true if use_board(boardname) boardfamily = boardname.split(":")[0..1].join(":") puts "Board '#{boardname}' not found; attempting to install '#{boardfamily}'" return false unless install_boards(boardfamily) # guess board family from first 2 :-separated fields use_board(boardname) end
[ "def", "use_board!", "(", "boardname", ")", "return", "true", "if", "use_board", "(", "boardname", ")", "boardfamily", "=", "boardname", ".", "split", "(", "\":\"", ")", "[", "0", "..", "1", "]", ".", "join", "(", "\":\"", ")", "puts", "\"Board '#{boardname}' not found; attempting to install '#{boardfamily}'\"", "return", "false", "unless", "install_boards", "(", "boardfamily", ")", "# guess board family from first 2 :-separated fields", "use_board", "(", "boardname", ")", "end" ]
use a particular board for compilation, installing it if necessary @param boardname [String] The board to use @return [bool] whether the command succeeded
[ "use", "a", "particular", "board", "for", "compilation", "installing", "it", "if", "necessary" ]
cb3fe8df14a744b9a3bc5cdc0168f820f78cde57
https://github.com/ianfixes/arduino_ci/blob/cb3fe8df14a744b9a3bc5cdc0168f820f78cde57/lib/arduino_ci/arduino_cmd.rb#L256-L264
16,529
ianfixes/arduino_ci
lib/arduino_ci/arduino_cmd.rb
ArduinoCI.ArduinoCmd.install_local_library
def install_local_library(path) src_path = path.realpath library_name = src_path.basename destination_path = library_path(library_name) # things get weird if the sketchbook contains the library. # check that first if destination_path.exist? uhoh = "There is already a library '#{library_name}' in the library directory" return destination_path if destination_path == src_path # maybe it's a symlink? that would be OK if destination_path.symlink? return destination_path if destination_path.readlink == src_path @last_msg = "#{uhoh} and it's not symlinked to #{src_path}" return nil end @last_msg = "#{uhoh}. It may need to be removed manually." return nil end # install the library Host.symlink(src_path, destination_path) destination_path end
ruby
def install_local_library(path) src_path = path.realpath library_name = src_path.basename destination_path = library_path(library_name) # things get weird if the sketchbook contains the library. # check that first if destination_path.exist? uhoh = "There is already a library '#{library_name}' in the library directory" return destination_path if destination_path == src_path # maybe it's a symlink? that would be OK if destination_path.symlink? return destination_path if destination_path.readlink == src_path @last_msg = "#{uhoh} and it's not symlinked to #{src_path}" return nil end @last_msg = "#{uhoh}. It may need to be removed manually." return nil end # install the library Host.symlink(src_path, destination_path) destination_path end
[ "def", "install_local_library", "(", "path", ")", "src_path", "=", "path", ".", "realpath", "library_name", "=", "src_path", ".", "basename", "destination_path", "=", "library_path", "(", "library_name", ")", "# things get weird if the sketchbook contains the library.", "# check that first", "if", "destination_path", ".", "exist?", "uhoh", "=", "\"There is already a library '#{library_name}' in the library directory\"", "return", "destination_path", "if", "destination_path", "==", "src_path", "# maybe it's a symlink? that would be OK", "if", "destination_path", ".", "symlink?", "return", "destination_path", "if", "destination_path", ".", "readlink", "==", "src_path", "@last_msg", "=", "\"#{uhoh} and it's not symlinked to #{src_path}\"", "return", "nil", "end", "@last_msg", "=", "\"#{uhoh}. It may need to be removed manually.\"", "return", "nil", "end", "# install the library", "Host", ".", "symlink", "(", "src_path", ",", "destination_path", ")", "destination_path", "end" ]
ensure that the given library is installed, or symlinked as appropriate return the path of the prepared library, or nil @param path [Pathname] library to use @return [String] the path of the installed library
[ "ensure", "that", "the", "given", "library", "is", "installed", "or", "symlinked", "as", "appropriate", "return", "the", "path", "of", "the", "prepared", "library", "or", "nil" ]
cb3fe8df14a744b9a3bc5cdc0168f820f78cde57
https://github.com/ianfixes/arduino_ci/blob/cb3fe8df14a744b9a3bc5cdc0168f820f78cde57/lib/arduino_ci/arduino_cmd.rb#L286-L312
16,530
ianfixes/arduino_ci
lib/arduino_ci/ci_config.rb
ArduinoCI.CIConfig.validate_data
def validate_data(rootname, source, schema) return nil if source.nil? good_data = {} source.each do |key, value| ksym = key.to_sym expected_type = schema[ksym].class == Class ? schema[ksym] : Hash if !schema.include?(ksym) puts "Warning: unknown field '#{ksym}' under definition for #{rootname}" elsif value.nil? good_data[ksym] = nil elsif value.class != expected_type puts "Warning: expected field '#{ksym}' of #{rootname} to be '#{expected_type}', got '#{value.class}'" else good_data[ksym] = value.class == Hash ? validate_data(key, value, schema[ksym]) : value end end good_data end
ruby
def validate_data(rootname, source, schema) return nil if source.nil? good_data = {} source.each do |key, value| ksym = key.to_sym expected_type = schema[ksym].class == Class ? schema[ksym] : Hash if !schema.include?(ksym) puts "Warning: unknown field '#{ksym}' under definition for #{rootname}" elsif value.nil? good_data[ksym] = nil elsif value.class != expected_type puts "Warning: expected field '#{ksym}' of #{rootname} to be '#{expected_type}', got '#{value.class}'" else good_data[ksym] = value.class == Hash ? validate_data(key, value, schema[ksym]) : value end end good_data end
[ "def", "validate_data", "(", "rootname", ",", "source", ",", "schema", ")", "return", "nil", "if", "source", ".", "nil?", "good_data", "=", "{", "}", "source", ".", "each", "do", "|", "key", ",", "value", "|", "ksym", "=", "key", ".", "to_sym", "expected_type", "=", "schema", "[", "ksym", "]", ".", "class", "==", "Class", "?", "schema", "[", "ksym", "]", ":", "Hash", "if", "!", "schema", ".", "include?", "(", "ksym", ")", "puts", "\"Warning: unknown field '#{ksym}' under definition for #{rootname}\"", "elsif", "value", ".", "nil?", "good_data", "[", "ksym", "]", "=", "nil", "elsif", "value", ".", "class", "!=", "expected_type", "puts", "\"Warning: expected field '#{ksym}' of #{rootname} to be '#{expected_type}', got '#{value.class}'\"", "else", "good_data", "[", "ksym", "]", "=", "value", ".", "class", "==", "Hash", "?", "validate_data", "(", "key", ",", "value", ",", "schema", "[", "ksym", "]", ")", ":", "value", "end", "end", "good_data", "end" ]
validate a data source according to a schema print out warnings for bad fields, and return only the good ones @param rootname [String] the name, for printing @param source [Hash] source data @param schema [Hash] a mapping of field names to their expected type @return [Hash] a copy, containing only expected & valid data
[ "validate", "a", "data", "source", "according", "to", "a", "schema", "print", "out", "warnings", "for", "bad", "fields", "and", "return", "only", "the", "good", "ones" ]
cb3fe8df14a744b9a3bc5cdc0168f820f78cde57
https://github.com/ianfixes/arduino_ci/blob/cb3fe8df14a744b9a3bc5cdc0168f820f78cde57/lib/arduino_ci/ci_config.rb#L103-L121
16,531
ianfixes/arduino_ci
lib/arduino_ci/ci_config.rb
ArduinoCI.CIConfig.load_yaml
def load_yaml(path) yml = YAML.load_file(path) raise ConfigurationError, "The YAML file at #{path} failed to load" unless yml apply_configuration(yml) end
ruby
def load_yaml(path) yml = YAML.load_file(path) raise ConfigurationError, "The YAML file at #{path} failed to load" unless yml apply_configuration(yml) end
[ "def", "load_yaml", "(", "path", ")", "yml", "=", "YAML", ".", "load_file", "(", "path", ")", "raise", "ConfigurationError", ",", "\"The YAML file at #{path} failed to load\"", "unless", "yml", "apply_configuration", "(", "yml", ")", "end" ]
Load configuration yaml from a file @param path [String] the source file @return [ArduinoCI::CIConfig] a reference to self
[ "Load", "configuration", "yaml", "from", "a", "file" ]
cb3fe8df14a744b9a3bc5cdc0168f820f78cde57
https://github.com/ianfixes/arduino_ci/blob/cb3fe8df14a744b9a3bc5cdc0168f820f78cde57/lib/arduino_ci/ci_config.rb#L126-L131
16,532
ianfixes/arduino_ci
lib/arduino_ci/ci_config.rb
ArduinoCI.CIConfig.apply_configuration
def apply_configuration(yml) if yml.include?("packages") yml["packages"].each do |k, v| valid_data = validate_data("packages", v, PACKAGE_SCHEMA) @package_info[k] = valid_data end end if yml.include?("platforms") yml["platforms"].each do |k, v| valid_data = validate_data("platforms", v, PLATFORM_SCHEMA) @platform_info[k] = valid_data end end if yml.include?("compile") valid_data = validate_data("compile", yml["compile"], COMPILE_SCHEMA) valid_data.each { |k, v| @compile_info[k] = v } end if yml.include?("unittest") valid_data = validate_data("unittest", yml["unittest"], UNITTEST_SCHEMA) valid_data.each { |k, v| @unittest_info[k] = v } end self end
ruby
def apply_configuration(yml) if yml.include?("packages") yml["packages"].each do |k, v| valid_data = validate_data("packages", v, PACKAGE_SCHEMA) @package_info[k] = valid_data end end if yml.include?("platforms") yml["platforms"].each do |k, v| valid_data = validate_data("platforms", v, PLATFORM_SCHEMA) @platform_info[k] = valid_data end end if yml.include?("compile") valid_data = validate_data("compile", yml["compile"], COMPILE_SCHEMA) valid_data.each { |k, v| @compile_info[k] = v } end if yml.include?("unittest") valid_data = validate_data("unittest", yml["unittest"], UNITTEST_SCHEMA) valid_data.each { |k, v| @unittest_info[k] = v } end self end
[ "def", "apply_configuration", "(", "yml", ")", "if", "yml", ".", "include?", "(", "\"packages\"", ")", "yml", "[", "\"packages\"", "]", ".", "each", "do", "|", "k", ",", "v", "|", "valid_data", "=", "validate_data", "(", "\"packages\"", ",", "v", ",", "PACKAGE_SCHEMA", ")", "@package_info", "[", "k", "]", "=", "valid_data", "end", "end", "if", "yml", ".", "include?", "(", "\"platforms\"", ")", "yml", "[", "\"platforms\"", "]", ".", "each", "do", "|", "k", ",", "v", "|", "valid_data", "=", "validate_data", "(", "\"platforms\"", ",", "v", ",", "PLATFORM_SCHEMA", ")", "@platform_info", "[", "k", "]", "=", "valid_data", "end", "end", "if", "yml", ".", "include?", "(", "\"compile\"", ")", "valid_data", "=", "validate_data", "(", "\"compile\"", ",", "yml", "[", "\"compile\"", "]", ",", "COMPILE_SCHEMA", ")", "valid_data", ".", "each", "{", "|", "k", ",", "v", "|", "@compile_info", "[", "k", "]", "=", "v", "}", "end", "if", "yml", ".", "include?", "(", "\"unittest\"", ")", "valid_data", "=", "validate_data", "(", "\"unittest\"", ",", "yml", "[", "\"unittest\"", "]", ",", "UNITTEST_SCHEMA", ")", "valid_data", ".", "each", "{", "|", "k", ",", "v", "|", "@unittest_info", "[", "k", "]", "=", "v", "}", "end", "self", "end" ]
Load configuration from a hash @param yml [Hash] the source data @return [ArduinoCI::CIConfig] a reference to self
[ "Load", "configuration", "from", "a", "hash" ]
cb3fe8df14a744b9a3bc5cdc0168f820f78cde57
https://github.com/ianfixes/arduino_ci/blob/cb3fe8df14a744b9a3bc5cdc0168f820f78cde57/lib/arduino_ci/ci_config.rb#L136-L162
16,533
ianfixes/arduino_ci
lib/arduino_ci/ci_config.rb
ArduinoCI.CIConfig.with_config
def with_config(base_dir, val_when_no_match) CONFIG_FILENAMES.each do |f| path = base_dir.nil? ? f : File.join(base_dir, f) return (yield path) if File.exist?(path) end val_when_no_match end
ruby
def with_config(base_dir, val_when_no_match) CONFIG_FILENAMES.each do |f| path = base_dir.nil? ? f : File.join(base_dir, f) return (yield path) if File.exist?(path) end val_when_no_match end
[ "def", "with_config", "(", "base_dir", ",", "val_when_no_match", ")", "CONFIG_FILENAMES", ".", "each", "do", "|", "f", "|", "path", "=", "base_dir", ".", "nil?", "?", "f", ":", "File", ".", "join", "(", "base_dir", ",", "f", ")", "return", "(", "yield", "path", ")", "if", "File", ".", "exist?", "(", "path", ")", "end", "val_when_no_match", "end" ]
Get the config file at a given path, if it exists, and pass that to a block. Many config files may exist, but only the first match is used @param base_dir [String] The directory in which to search for a config file @param val_when_no_match [Object] The value to return if no config files are found @yield [path] Process the configuration file at the given path @yieldparam [String] The path of an existing config file @yieldreturn [ArduinoCI::CIConfig] a settings object @return [ArduinoCI::CIConfig]
[ "Get", "the", "config", "file", "at", "a", "given", "path", "if", "it", "exists", "and", "pass", "that", "to", "a", "block", ".", "Many", "config", "files", "may", "exist", "but", "only", "the", "first", "match", "is", "used" ]
cb3fe8df14a744b9a3bc5cdc0168f820f78cde57
https://github.com/ianfixes/arduino_ci/blob/cb3fe8df14a744b9a3bc5cdc0168f820f78cde57/lib/arduino_ci/ci_config.rb#L201-L207
16,534
ianfixes/arduino_ci
lib/arduino_ci/ci_config.rb
ArduinoCI.CIConfig.from_example
def from_example(example_path) base_dir = File.directory?(example_path) ? example_path : File.dirname(example_path) with_config(base_dir, self) { |path| with_override(path) } end
ruby
def from_example(example_path) base_dir = File.directory?(example_path) ? example_path : File.dirname(example_path) with_config(base_dir, self) { |path| with_override(path) } end
[ "def", "from_example", "(", "example_path", ")", "base_dir", "=", "File", ".", "directory?", "(", "example_path", ")", "?", "example_path", ":", "File", ".", "dirname", "(", "example_path", ")", "with_config", "(", "base_dir", ",", "self", ")", "{", "|", "path", "|", "with_override", "(", "path", ")", "}", "end" ]
Produce a configuration override taken from an Arduino library example path handle either path to example file or example dir @param path [String] the path to the settings yaml file @return [ArduinoCI::CIConfig] the new settings object
[ "Produce", "a", "configuration", "override", "taken", "from", "an", "Arduino", "library", "example", "path", "handle", "either", "path", "to", "example", "file", "or", "example", "dir" ]
cb3fe8df14a744b9a3bc5cdc0168f820f78cde57
https://github.com/ianfixes/arduino_ci/blob/cb3fe8df14a744b9a3bc5cdc0168f820f78cde57/lib/arduino_ci/ci_config.rb#L219-L222
16,535
activemerchant/offsite_payments
lib/offsite_payments/action_view_helper.rb
OffsitePayments.ActionViewHelper.payment_service_for
def payment_service_for(order, account, options = {}, &proc) raise ArgumentError, "Missing block" unless block_given? integration_module = OffsitePayments::integration(options.delete(:service).to_s) service_class = integration_module.const_get('Helper') form_options = options.delete(:html) || {} service = service_class.new(order, account, options) form_options[:method] = service.form_method result = [] service_url = service.respond_to?(:credential_based_url) ? service.credential_based_url : integration_module.service_url result << form_tag(service_url, form_options) result << capture(service, &proc) service.form_fields.each do |field, value| result << hidden_field_tag(field, value) end service.raw_html_fields.each do |field, value| result << "<input id=\"#{field}\" name=\"#{field}\" type=\"hidden\" value=\"#{value}\" />\n" end result << '</form>' result= result.join("\n") concat(result.respond_to?(:html_safe) ? result.html_safe : result) nil end
ruby
def payment_service_for(order, account, options = {}, &proc) raise ArgumentError, "Missing block" unless block_given? integration_module = OffsitePayments::integration(options.delete(:service).to_s) service_class = integration_module.const_get('Helper') form_options = options.delete(:html) || {} service = service_class.new(order, account, options) form_options[:method] = service.form_method result = [] service_url = service.respond_to?(:credential_based_url) ? service.credential_based_url : integration_module.service_url result << form_tag(service_url, form_options) result << capture(service, &proc) service.form_fields.each do |field, value| result << hidden_field_tag(field, value) end service.raw_html_fields.each do |field, value| result << "<input id=\"#{field}\" name=\"#{field}\" type=\"hidden\" value=\"#{value}\" />\n" end result << '</form>' result= result.join("\n") concat(result.respond_to?(:html_safe) ? result.html_safe : result) nil end
[ "def", "payment_service_for", "(", "order", ",", "account", ",", "options", "=", "{", "}", ",", "&", "proc", ")", "raise", "ArgumentError", ",", "\"Missing block\"", "unless", "block_given?", "integration_module", "=", "OffsitePayments", "::", "integration", "(", "options", ".", "delete", "(", ":service", ")", ".", "to_s", ")", "service_class", "=", "integration_module", ".", "const_get", "(", "'Helper'", ")", "form_options", "=", "options", ".", "delete", "(", ":html", ")", "||", "{", "}", "service", "=", "service_class", ".", "new", "(", "order", ",", "account", ",", "options", ")", "form_options", "[", ":method", "]", "=", "service", ".", "form_method", "result", "=", "[", "]", "service_url", "=", "service", ".", "respond_to?", "(", ":credential_based_url", ")", "?", "service", ".", "credential_based_url", ":", "integration_module", ".", "service_url", "result", "<<", "form_tag", "(", "service_url", ",", "form_options", ")", "result", "<<", "capture", "(", "service", ",", "proc", ")", "service", ".", "form_fields", ".", "each", "do", "|", "field", ",", "value", "|", "result", "<<", "hidden_field_tag", "(", "field", ",", "value", ")", "end", "service", ".", "raw_html_fields", ".", "each", "do", "|", "field", ",", "value", "|", "result", "<<", "\"<input id=\\\"#{field}\\\" name=\\\"#{field}\\\" type=\\\"hidden\\\" value=\\\"#{value}\\\" />\\n\"", "end", "result", "<<", "'</form>'", "result", "=", "result", ".", "join", "(", "\"\\n\"", ")", "concat", "(", "result", ".", "respond_to?", "(", ":html_safe", ")", "?", "result", ".", "html_safe", ":", "result", ")", "nil", "end" ]
This helper allows the usage of different payment integrations through a single form helper. Payment integrations are the type of service where the user is redirected to the secure site of the service, like Paypal or Chronopay. The helper creates a scope around a payment service helper which provides the specific mapping for that service. <% payment_service_for 1000, 'paypalemail@mystore.com', :amount => 50.00, :currency => 'CAD', :service => :paypal, :html => { :id => 'payment-form' } do |service| %> <% service.customer :first_name => 'Cody', :last_name => 'Fauser', :phone => '(555)555-5555', :email => 'cody@example.com' %> <% service.billing_address :city => 'Ottawa', :address1 => '21 Snowy Brook Lane', :address2 => 'Apt. 36', :state => 'ON', :country => 'CA', :zip => 'K1J1E5' %> <% service.invoice '#1000' %> <% service.shipping '0.00' %> <% service.tax '0.00' %> <% service.notify_url url_for(:only_path => false, :action => 'notify') %> <% service.return_url url_for(:only_path => false, :action => 'done') %> <% service.cancel_return_url 'http://mystore.com' %> <% end %>
[ "This", "helper", "allows", "the", "usage", "of", "different", "payment", "integrations", "through", "a", "single", "form", "helper", ".", "Payment", "integrations", "are", "the", "type", "of", "service", "where", "the", "user", "is", "redirected", "to", "the", "secure", "site", "of", "the", "service", "like", "Paypal", "or", "Chronopay", "." ]
e331582d3d7b4cc479c83355f1748ea407efc66f
https://github.com/activemerchant/offsite_payments/blob/e331582d3d7b4cc479c83355f1748ea407efc66f/lib/offsite_payments/action_view_helper.rb#L42-L70
16,536
activemerchant/offsite_payments
lib/offsite_payments/notification.rb
OffsitePayments.Notification.valid_sender?
def valid_sender?(ip) return true if OffsitePayments.mode == :test || production_ips.blank? production_ips.include?(ip) end
ruby
def valid_sender?(ip) return true if OffsitePayments.mode == :test || production_ips.blank? production_ips.include?(ip) end
[ "def", "valid_sender?", "(", "ip", ")", "return", "true", "if", "OffsitePayments", ".", "mode", "==", ":test", "||", "production_ips", ".", "blank?", "production_ips", ".", "include?", "(", "ip", ")", "end" ]
Check if the request comes from an official IP
[ "Check", "if", "the", "request", "comes", "from", "an", "official", "IP" ]
e331582d3d7b4cc479c83355f1748ea407efc66f
https://github.com/activemerchant/offsite_payments/blob/e331582d3d7b4cc479c83355f1748ea407efc66f/lib/offsite_payments/notification.rb#L46-L49
16,537
activemerchant/offsite_payments
lib/offsite_payments/helper.rb
OffsitePayments.Helper.add_field
def add_field(name, value) return if name.blank? || value.blank? @fields[name.to_s] = value.to_s end
ruby
def add_field(name, value) return if name.blank? || value.blank? @fields[name.to_s] = value.to_s end
[ "def", "add_field", "(", "name", ",", "value", ")", "return", "if", "name", ".", "blank?", "||", "value", ".", "blank?", "@fields", "[", "name", ".", "to_s", "]", "=", "value", ".", "to_s", "end" ]
Add an input in the form. Useful when gateway requires some uncommon fields not provided by the gem. # inside `payment_service_for do |service|` block service.add_field('c_id','_xclick') Gateway implementor can also use this to add default fields in the form: # in a subclass of ActiveMerchant::Billing::Integrations::Helper def initialize(order, account, options = {}) super # mandatory fields add_field('Rvg2c', 1) end @param name [String] input name @param value [String] input value
[ "Add", "an", "input", "in", "the", "form", ".", "Useful", "when", "gateway", "requires", "some", "uncommon", "fields", "not", "provided", "by", "the", "gem", "." ]
e331582d3d7b4cc479c83355f1748ea407efc66f
https://github.com/activemerchant/offsite_payments/blob/e331582d3d7b4cc479c83355f1748ea407efc66f/lib/offsite_payments/helper.rb#L93-L96
16,538
Airtable/airtable-ruby
lib/airtable/record.rb
Airtable.Record.[]=
def []=(name, value) @column_keys << name @attrs[to_key(name)] = value define_accessor(name) unless respond_to?(name) end
ruby
def []=(name, value) @column_keys << name @attrs[to_key(name)] = value define_accessor(name) unless respond_to?(name) end
[ "def", "[]=", "(", "name", ",", "value", ")", "@column_keys", "<<", "name", "@attrs", "[", "to_key", "(", "name", ")", "]", "=", "value", "define_accessor", "(", "name", ")", "unless", "respond_to?", "(", "name", ")", "end" ]
Set the given attribute to value
[ "Set", "the", "given", "attribute", "to", "value" ]
041a8baf8ae59279630912d6ff329faa64398cb2
https://github.com/Airtable/airtable-ruby/blob/041a8baf8ae59279630912d6ff329faa64398cb2/lib/airtable/record.rb#L17-L21
16,539
Airtable/airtable-ruby
lib/airtable/record.rb
Airtable.Record.override_attributes!
def override_attributes!(attrs={}) @column_keys = attrs.keys @attrs = HashWithIndifferentAccess.new(Hash[attrs.map { |k, v| [ to_key(k), v ] }]) @attrs.map { |k, v| define_accessor(k) } end
ruby
def override_attributes!(attrs={}) @column_keys = attrs.keys @attrs = HashWithIndifferentAccess.new(Hash[attrs.map { |k, v| [ to_key(k), v ] }]) @attrs.map { |k, v| define_accessor(k) } end
[ "def", "override_attributes!", "(", "attrs", "=", "{", "}", ")", "@column_keys", "=", "attrs", ".", "keys", "@attrs", "=", "HashWithIndifferentAccess", ".", "new", "(", "Hash", "[", "attrs", ".", "map", "{", "|", "k", ",", "v", "|", "[", "to_key", "(", "k", ")", ",", "v", "]", "}", "]", ")", "@attrs", ".", "map", "{", "|", "k", ",", "v", "|", "define_accessor", "(", "k", ")", "}", "end" ]
Removes old and add new attributes for the record
[ "Removes", "old", "and", "add", "new", "attributes", "for", "the", "record" ]
041a8baf8ae59279630912d6ff329faa64398cb2
https://github.com/Airtable/airtable-ruby/blob/041a8baf8ae59279630912d6ff329faa64398cb2/lib/airtable/record.rb#L31-L35
16,540
Airtable/airtable-ruby
lib/airtable/table.rb
Airtable.Table.find
def find(id) result = self.class.get(worksheet_url + "/" + id).parsed_response check_and_raise_error(result) Record.new(result_attributes(result)) if result.present? && result["id"] end
ruby
def find(id) result = self.class.get(worksheet_url + "/" + id).parsed_response check_and_raise_error(result) Record.new(result_attributes(result)) if result.present? && result["id"] end
[ "def", "find", "(", "id", ")", "result", "=", "self", ".", "class", ".", "get", "(", "worksheet_url", "+", "\"/\"", "+", "id", ")", ".", "parsed_response", "check_and_raise_error", "(", "result", ")", "Record", ".", "new", "(", "result_attributes", "(", "result", ")", ")", "if", "result", ".", "present?", "&&", "result", "[", "\"id\"", "]", "end" ]
Returns record based given row id
[ "Returns", "record", "based", "given", "row", "id" ]
041a8baf8ae59279630912d6ff329faa64398cb2
https://github.com/Airtable/airtable-ruby/blob/041a8baf8ae59279630912d6ff329faa64398cb2/lib/airtable/table.rb#L55-L59
16,541
Airtable/airtable-ruby
lib/airtable/table.rb
Airtable.Table.create
def create(record) result = self.class.post(worksheet_url, :body => { "fields" => record.fields }.to_json, :headers => { "Content-type" => "application/json" }).parsed_response check_and_raise_error(result) record.override_attributes!(result_attributes(result)) record end
ruby
def create(record) result = self.class.post(worksheet_url, :body => { "fields" => record.fields }.to_json, :headers => { "Content-type" => "application/json" }).parsed_response check_and_raise_error(result) record.override_attributes!(result_attributes(result)) record end
[ "def", "create", "(", "record", ")", "result", "=", "self", ".", "class", ".", "post", "(", "worksheet_url", ",", ":body", "=>", "{", "\"fields\"", "=>", "record", ".", "fields", "}", ".", "to_json", ",", ":headers", "=>", "{", "\"Content-type\"", "=>", "\"application/json\"", "}", ")", ".", "parsed_response", "check_and_raise_error", "(", "result", ")", "record", ".", "override_attributes!", "(", "result_attributes", "(", "result", ")", ")", "record", "end" ]
Creates a record by posting to airtable
[ "Creates", "a", "record", "by", "posting", "to", "airtable" ]
041a8baf8ae59279630912d6ff329faa64398cb2
https://github.com/Airtable/airtable-ruby/blob/041a8baf8ae59279630912d6ff329faa64398cb2/lib/airtable/table.rb#L62-L71
16,542
Airtable/airtable-ruby
lib/airtable/table.rb
Airtable.Table.update
def update(record) result = self.class.put(worksheet_url + "/" + record.id, :body => { "fields" => record.fields_for_update }.to_json, :headers => { "Content-type" => "application/json" }).parsed_response check_and_raise_error(result) record.override_attributes!(result_attributes(result)) record end
ruby
def update(record) result = self.class.put(worksheet_url + "/" + record.id, :body => { "fields" => record.fields_for_update }.to_json, :headers => { "Content-type" => "application/json" }).parsed_response check_and_raise_error(result) record.override_attributes!(result_attributes(result)) record end
[ "def", "update", "(", "record", ")", "result", "=", "self", ".", "class", ".", "put", "(", "worksheet_url", "+", "\"/\"", "+", "record", ".", "id", ",", ":body", "=>", "{", "\"fields\"", "=>", "record", ".", "fields_for_update", "}", ".", "to_json", ",", ":headers", "=>", "{", "\"Content-type\"", "=>", "\"application/json\"", "}", ")", ".", "parsed_response", "check_and_raise_error", "(", "result", ")", "record", ".", "override_attributes!", "(", "result_attributes", "(", "result", ")", ")", "record", "end" ]
Replaces record in airtable based on id
[ "Replaces", "record", "in", "airtable", "based", "on", "id" ]
041a8baf8ae59279630912d6ff329faa64398cb2
https://github.com/Airtable/airtable-ruby/blob/041a8baf8ae59279630912d6ff329faa64398cb2/lib/airtable/table.rb#L74-L84
16,543
ruby-numo/numo-narray
lib/numo/narray/extra.rb
Numo.NArray.triu!
def triu!(k=0) if ndim < 2 raise NArray::ShapeError, "must be >= 2-dimensional array" end if contiguous? *shp,m,n = shape idx = tril_indices(k-1) reshape!(*shp,m*n) self[false,idx] = 0 reshape!(*shp,m,n) else store(triu(k)) end end
ruby
def triu!(k=0) if ndim < 2 raise NArray::ShapeError, "must be >= 2-dimensional array" end if contiguous? *shp,m,n = shape idx = tril_indices(k-1) reshape!(*shp,m*n) self[false,idx] = 0 reshape!(*shp,m,n) else store(triu(k)) end end
[ "def", "triu!", "(", "k", "=", "0", ")", "if", "ndim", "<", "2", "raise", "NArray", "::", "ShapeError", ",", "\"must be >= 2-dimensional array\"", "end", "if", "contiguous?", "*", "shp", ",", "m", ",", "n", "=", "shape", "idx", "=", "tril_indices", "(", "k", "-", "1", ")", "reshape!", "(", "shp", ",", "m", "n", ")", "self", "[", "false", ",", "idx", "]", "=", "0", "reshape!", "(", "shp", ",", "m", ",", "n", ")", "else", "store", "(", "triu", "(", "k", ")", ")", "end", "end" ]
Upper triangular matrix. Fill the self elements below the k-th diagonal with zero.
[ "Upper", "triangular", "matrix", ".", "Fill", "the", "self", "elements", "below", "the", "k", "-", "th", "diagonal", "with", "zero", "." ]
69c12dad12040486ac305d68d1f5fb32f07aba78
https://github.com/ruby-numo/numo-narray/blob/69c12dad12040486ac305d68d1f5fb32f07aba78/lib/numo/narray/extra.rb#L1024-L1037
16,544
ruby-numo/numo-narray
lib/numo/narray/extra.rb
Numo.NArray.tril!
def tril!(k=0) if ndim < 2 raise NArray::ShapeError, "must be >= 2-dimensional array" end if contiguous? idx = triu_indices(k+1) *shp,m,n = shape reshape!(*shp,m*n) self[false,idx] = 0 reshape!(*shp,m,n) else store(tril(k)) end end
ruby
def tril!(k=0) if ndim < 2 raise NArray::ShapeError, "must be >= 2-dimensional array" end if contiguous? idx = triu_indices(k+1) *shp,m,n = shape reshape!(*shp,m*n) self[false,idx] = 0 reshape!(*shp,m,n) else store(tril(k)) end end
[ "def", "tril!", "(", "k", "=", "0", ")", "if", "ndim", "<", "2", "raise", "NArray", "::", "ShapeError", ",", "\"must be >= 2-dimensional array\"", "end", "if", "contiguous?", "idx", "=", "triu_indices", "(", "k", "+", "1", ")", "*", "shp", ",", "m", ",", "n", "=", "shape", "reshape!", "(", "shp", ",", "m", "n", ")", "self", "[", "false", ",", "idx", "]", "=", "0", "reshape!", "(", "shp", ",", "m", ",", "n", ")", "else", "store", "(", "tril", "(", "k", ")", ")", "end", "end" ]
Lower triangular matrix. Fill the self elements above the k-th diagonal with zero.
[ "Lower", "triangular", "matrix", ".", "Fill", "the", "self", "elements", "above", "the", "k", "-", "th", "diagonal", "with", "zero", "." ]
69c12dad12040486ac305d68d1f5fb32f07aba78
https://github.com/ruby-numo/numo-narray/blob/69c12dad12040486ac305d68d1f5fb32f07aba78/lib/numo/narray/extra.rb#L1063-L1076
16,545
ruby-numo/numo-narray
lib/numo/narray/extra.rb
Numo.NArray.diag_indices
def diag_indices(k=0) if ndim < 2 raise NArray::ShapeError, "must be >= 2-dimensional array" end m,n = shape[-2..-1] NArray.diag_indices(m,n,k) end
ruby
def diag_indices(k=0) if ndim < 2 raise NArray::ShapeError, "must be >= 2-dimensional array" end m,n = shape[-2..-1] NArray.diag_indices(m,n,k) end
[ "def", "diag_indices", "(", "k", "=", "0", ")", "if", "ndim", "<", "2", "raise", "NArray", "::", "ShapeError", ",", "\"must be >= 2-dimensional array\"", "end", "m", ",", "n", "=", "shape", "[", "-", "2", "..", "-", "1", "]", "NArray", ".", "diag_indices", "(", "m", ",", "n", ",", "k", ")", "end" ]
Return the k-th diagonal indices.
[ "Return", "the", "k", "-", "th", "diagonal", "indices", "." ]
69c12dad12040486ac305d68d1f5fb32f07aba78
https://github.com/ruby-numo/numo-narray/blob/69c12dad12040486ac305d68d1f5fb32f07aba78/lib/numo/narray/extra.rb#L1095-L1101
16,546
ruby-numo/numo-narray
lib/numo/narray/extra.rb
Numo.NArray.diag
def diag(k=0) *shp,n = shape n += k.abs a = self.class.zeros(*shp,n,n) a.diagonal(k).store(self) a end
ruby
def diag(k=0) *shp,n = shape n += k.abs a = self.class.zeros(*shp,n,n) a.diagonal(k).store(self) a end
[ "def", "diag", "(", "k", "=", "0", ")", "*", "shp", ",", "n", "=", "shape", "n", "+=", "k", ".", "abs", "a", "=", "self", ".", "class", ".", "zeros", "(", "shp", ",", "n", ",", "n", ")", "a", ".", "diagonal", "(", "k", ")", ".", "store", "(", "self", ")", "a", "end" ]
Return a matrix whose diagonal is constructed by self along the last axis.
[ "Return", "a", "matrix", "whose", "diagonal", "is", "constructed", "by", "self", "along", "the", "last", "axis", "." ]
69c12dad12040486ac305d68d1f5fb32f07aba78
https://github.com/ruby-numo/numo-narray/blob/69c12dad12040486ac305d68d1f5fb32f07aba78/lib/numo/narray/extra.rb#L1111-L1117
16,547
ruby-numo/numo-narray
lib/numo/narray/extra.rb
Numo.NArray.trace
def trace(offset=nil,axis=nil,nan:false) diagonal(offset,axis).sum(nan:nan,axis:-1) end
ruby
def trace(offset=nil,axis=nil,nan:false) diagonal(offset,axis).sum(nan:nan,axis:-1) end
[ "def", "trace", "(", "offset", "=", "nil", ",", "axis", "=", "nil", ",", "nan", ":", "false", ")", "diagonal", "(", "offset", ",", "axis", ")", ".", "sum", "(", "nan", ":", "nan", ",", "axis", ":", "-", "1", ")", "end" ]
Return the sum along diagonals of the array. If 2-D array, computes the summation along its diagonal with the given offset, i.e., sum of `a[i,i+offset]`. If more than 2-D array, the diagonal is determined from the axes specified by axis argument. The default is axis=[-2,-1]. @param offset [Integer] (optional, default=0) diagonal offset @param axis [Array] (optional, default=[-2,-1]) diagonal axis @param nan [Bool] (optional, default=false) nan-aware algorithm, i.e., if true then it ignores nan.
[ "Return", "the", "sum", "along", "diagonals", "of", "the", "array", "." ]
69c12dad12040486ac305d68d1f5fb32f07aba78
https://github.com/ruby-numo/numo-narray/blob/69c12dad12040486ac305d68d1f5fb32f07aba78/lib/numo/narray/extra.rb#L1129-L1131
16,548
ruby-numo/numo-narray
lib/numo/narray/extra.rb
Numo.NArray.dot
def dot(b) t = self.class::UPCAST[b.class] if defined?(Linalg) && [SFloat,DFloat,SComplex,DComplex].include?(t) Linalg.dot(self,b) else b = self.class.asarray(b) case b.ndim when 1 mulsum(b, axis:-1) else case ndim when 0 b.mulsum(self, axis:-2) when 1 self[true,:new].mulsum(b, axis:-2) else unless @@warn_slow_dot nx = 200 ns = 200000 am,an = shape[-2..-1] bm,bn = b.shape[-2..-1] if am > nx && an > nx && bm > nx && bn > nx && size > ns && b.size > ns @@warn_slow_dot = true warn "\nwarning: Built-in matrix dot is slow. Consider installing Numo::Linalg.\n\n" end end self[false,:new].mulsum(b[false,:new,true,true], axis:-2) end end end end
ruby
def dot(b) t = self.class::UPCAST[b.class] if defined?(Linalg) && [SFloat,DFloat,SComplex,DComplex].include?(t) Linalg.dot(self,b) else b = self.class.asarray(b) case b.ndim when 1 mulsum(b, axis:-1) else case ndim when 0 b.mulsum(self, axis:-2) when 1 self[true,:new].mulsum(b, axis:-2) else unless @@warn_slow_dot nx = 200 ns = 200000 am,an = shape[-2..-1] bm,bn = b.shape[-2..-1] if am > nx && an > nx && bm > nx && bn > nx && size > ns && b.size > ns @@warn_slow_dot = true warn "\nwarning: Built-in matrix dot is slow. Consider installing Numo::Linalg.\n\n" end end self[false,:new].mulsum(b[false,:new,true,true], axis:-2) end end end end
[ "def", "dot", "(", "b", ")", "t", "=", "self", ".", "class", "::", "UPCAST", "[", "b", ".", "class", "]", "if", "defined?", "(", "Linalg", ")", "&&", "[", "SFloat", ",", "DFloat", ",", "SComplex", ",", "DComplex", "]", ".", "include?", "(", "t", ")", "Linalg", ".", "dot", "(", "self", ",", "b", ")", "else", "b", "=", "self", ".", "class", ".", "asarray", "(", "b", ")", "case", "b", ".", "ndim", "when", "1", "mulsum", "(", "b", ",", "axis", ":", "-", "1", ")", "else", "case", "ndim", "when", "0", "b", ".", "mulsum", "(", "self", ",", "axis", ":", "-", "2", ")", "when", "1", "self", "[", "true", ",", ":new", "]", ".", "mulsum", "(", "b", ",", "axis", ":", "-", "2", ")", "else", "unless", "@@warn_slow_dot", "nx", "=", "200", "ns", "=", "200000", "am", ",", "an", "=", "shape", "[", "-", "2", "..", "-", "1", "]", "bm", ",", "bn", "=", "b", ".", "shape", "[", "-", "2", "..", "-", "1", "]", "if", "am", ">", "nx", "&&", "an", ">", "nx", "&&", "bm", ">", "nx", "&&", "bn", ">", "nx", "&&", "size", ">", "ns", "&&", "b", ".", "size", ">", "ns", "@@warn_slow_dot", "=", "true", "warn", "\"\\nwarning: Built-in matrix dot is slow. Consider installing Numo::Linalg.\\n\\n\"", "end", "end", "self", "[", "false", ",", ":new", "]", ".", "mulsum", "(", "b", "[", "false", ",", ":new", ",", "true", ",", "true", "]", ",", "axis", ":", "-", "2", ")", "end", "end", "end", "end" ]
Dot product of two arrays. @param b [Numo::NArray] @return [Numo::NArray] return dot product
[ "Dot", "product", "of", "two", "arrays", "." ]
69c12dad12040486ac305d68d1f5fb32f07aba78
https://github.com/ruby-numo/numo-narray/blob/69c12dad12040486ac305d68d1f5fb32f07aba78/lib/numo/narray/extra.rb#L1140-L1171
16,549
ruby-numo/numo-narray
lib/numo/narray/extra.rb
Numo.NArray.kron
def kron(b) b = NArray.cast(b) nda = ndim ndb = b.ndim shpa = shape shpb = b.shape adim = [:new]*(2*[ndb-nda,0].max) + [true,:new]*nda bdim = [:new]*(2*[nda-ndb,0].max) + [:new,true]*ndb shpr = (-[nda,ndb].max..-1).map{|i| (shpa[i]||1) * (shpb[i]||1)} (self[*adim] * b[*bdim]).reshape(*shpr) end
ruby
def kron(b) b = NArray.cast(b) nda = ndim ndb = b.ndim shpa = shape shpb = b.shape adim = [:new]*(2*[ndb-nda,0].max) + [true,:new]*nda bdim = [:new]*(2*[nda-ndb,0].max) + [:new,true]*ndb shpr = (-[nda,ndb].max..-1).map{|i| (shpa[i]||1) * (shpb[i]||1)} (self[*adim] * b[*bdim]).reshape(*shpr) end
[ "def", "kron", "(", "b", ")", "b", "=", "NArray", ".", "cast", "(", "b", ")", "nda", "=", "ndim", "ndb", "=", "b", ".", "ndim", "shpa", "=", "shape", "shpb", "=", "b", ".", "shape", "adim", "=", "[", ":new", "]", "*", "(", "2", "*", "[", "ndb", "-", "nda", ",", "0", "]", ".", "max", ")", "+", "[", "true", ",", ":new", "]", "*", "nda", "bdim", "=", "[", ":new", "]", "*", "(", "2", "*", "[", "nda", "-", "ndb", ",", "0", "]", ".", "max", ")", "+", "[", ":new", ",", "true", "]", "*", "ndb", "shpr", "=", "(", "-", "[", "nda", ",", "ndb", "]", ".", "max", "..", "-", "1", ")", ".", "map", "{", "|", "i", "|", "(", "shpa", "[", "i", "]", "||", "1", ")", "*", "(", "shpb", "[", "i", "]", "||", "1", ")", "}", "(", "self", "[", "adim", "]", "*", "b", "[", "bdim", "]", ")", ".", "reshape", "(", "shpr", ")", "end" ]
Kronecker product of two arrays. kron(a,b)[k_0, k_1, ...] = a[i_0, i_1, ...] * b[j_0, j_1, ...] where: k_n = i_n * b.shape[n] + j_n @param b [Numo::NArray] @return [Numo::NArray] return Kronecker product @example Numo::DFloat[1,10,100].kron([5,6,7]) => Numo::DFloat#shape=[9] [5, 6, 7, 50, 60, 70, 500, 600, 700] Numo::DFloat[5,6,7].kron([1,10,100]) => Numo::DFloat#shape=[9] [5, 50, 500, 6, 60, 600, 7, 70, 700] Numo::DFloat.eye(2).kron(Numo::DFloat.ones(2,2)) => Numo::DFloat#shape=[4,4] [[1, 1, 0, 0], [1, 1, 0, 0], [0, 0, 1, 1], [0, 0, 1, 1]]
[ "Kronecker", "product", "of", "two", "arrays", "." ]
69c12dad12040486ac305d68d1f5fb32f07aba78
https://github.com/ruby-numo/numo-narray/blob/69c12dad12040486ac305d68d1f5fb32f07aba78/lib/numo/narray/extra.rb#L1243-L1253
16,550
cburnette/boxr
lib/boxr/collaborations.rb
Boxr.Client.pending_collaborations
def pending_collaborations(fields: []) query = build_fields_query(fields, COLLABORATION_FIELDS_QUERY) query[:status] = :pending pending_collaborations, response = get(COLLABORATIONS_URI, query: query) pending_collaborations['entries'] end
ruby
def pending_collaborations(fields: []) query = build_fields_query(fields, COLLABORATION_FIELDS_QUERY) query[:status] = :pending pending_collaborations, response = get(COLLABORATIONS_URI, query: query) pending_collaborations['entries'] end
[ "def", "pending_collaborations", "(", "fields", ":", "[", "]", ")", "query", "=", "build_fields_query", "(", "fields", ",", "COLLABORATION_FIELDS_QUERY", ")", "query", "[", ":status", "]", "=", ":pending", "pending_collaborations", ",", "response", "=", "get", "(", "COLLABORATIONS_URI", ",", "query", ":", "query", ")", "pending_collaborations", "[", "'entries'", "]", "end" ]
these are pending collaborations for the current user; use the As-User Header to request for different users
[ "these", "are", "pending", "collaborations", "for", "the", "current", "user", ";", "use", "the", "As", "-", "User", "Header", "to", "request", "for", "different", "users" ]
5e68c8c3640f33d709d4830ce34631864b1f5db5
https://github.com/cburnette/boxr/blob/5e68c8c3640f33d709d4830ce34631864b1f5db5/lib/boxr/collaborations.rb#L56-L61
16,551
hanami/router
lib/hanami/router.rb
Hanami.Router.redirect
def redirect(path, options = {}, &endpoint) destination_path = @router.find(options) get(path).redirect(destination_path, options[:code] || 301).tap do |route| route.dest = Hanami::Routing::RedirectEndpoint.new(destination_path, route.dest) end end
ruby
def redirect(path, options = {}, &endpoint) destination_path = @router.find(options) get(path).redirect(destination_path, options[:code] || 301).tap do |route| route.dest = Hanami::Routing::RedirectEndpoint.new(destination_path, route.dest) end end
[ "def", "redirect", "(", "path", ",", "options", "=", "{", "}", ",", "&", "endpoint", ")", "destination_path", "=", "@router", ".", "find", "(", "options", ")", "get", "(", "path", ")", ".", "redirect", "(", "destination_path", ",", "options", "[", ":code", "]", "||", "301", ")", ".", "tap", "do", "|", "route", "|", "route", ".", "dest", "=", "Hanami", "::", "Routing", "::", "RedirectEndpoint", ".", "new", "(", "destination_path", ",", "route", ".", "dest", ")", "end", "end" ]
Defines an HTTP redirect @param path [String] the path that needs to be redirected @param options [Hash] the options to customize the redirect behavior @option options [Fixnum] the HTTP status to return (defaults to `301`) @return [Hanami::Routing::Route] the generated route. This may vary according to the `:route` option passed to the initializer @since 0.1.0 @see Hanami::Router @example require 'hanami/router' Hanami::Router.new do redirect '/legacy', to: '/new_endpoint' redirect '/legacy2', to: '/new_endpoint2', code: 302 end @example require 'hanami/router' router = Hanami::Router.new router.redirect '/legacy', to: '/new_endpoint'
[ "Defines", "an", "HTTP", "redirect" ]
05bb4fb3fce8ff9a9f32858412cc31890d3c1aa7
https://github.com/hanami/router/blob/05bb4fb3fce8ff9a9f32858412cc31890d3c1aa7/lib/hanami/router.rb#L624-L629
16,552
hanami/router
lib/hanami/router.rb
Hanami.Router.recognize
def recognize(env, options = {}, params = nil) require 'hanami/routing/recognized_route' env = env_for(env, options, params) responses, _ = *@router.recognize(env) Routing::RecognizedRoute.new( responses.nil? ? responses : responses.first, env, @router) end
ruby
def recognize(env, options = {}, params = nil) require 'hanami/routing/recognized_route' env = env_for(env, options, params) responses, _ = *@router.recognize(env) Routing::RecognizedRoute.new( responses.nil? ? responses : responses.first, env, @router) end
[ "def", "recognize", "(", "env", ",", "options", "=", "{", "}", ",", "params", "=", "nil", ")", "require", "'hanami/routing/recognized_route'", "env", "=", "env_for", "(", "env", ",", "options", ",", "params", ")", "responses", ",", "_", "=", "@router", ".", "recognize", "(", "env", ")", "Routing", "::", "RecognizedRoute", ".", "new", "(", "responses", ".", "nil?", "?", "responses", ":", "responses", ".", "first", ",", "env", ",", "@router", ")", "end" ]
Recognize the given env, path, or name and return a route for testing inspection. If the route cannot be recognized, it still returns an object for testing inspection. @param env [Hash, String, Symbol] Rack env, path or route name @param options [Hash] a set of options for Rack env or route params @param params [Hash] a set of params @return [Hanami::Routing::RecognizedRoute] the recognized route @since 0.5.0 @see Hanami::Router#env_for @see Hanami::Routing::RecognizedRoute @example Successful Path Recognition require 'hanami/router' router = Hanami::Router.new do get '/books/:id', to: 'books#show', as: :book end route = router.recognize('/books/23') route.verb # => "GET" (default) route.routable? # => true route.params # => {:id=>"23"} @example Successful Rack Env Recognition require 'hanami/router' router = Hanami::Router.new do get '/books/:id', to: 'books#show', as: :book end route = router.recognize(Rack::MockRequest.env_for('/books/23')) route.verb # => "GET" (default) route.routable? # => true route.params # => {:id=>"23"} @example Successful Named Route Recognition require 'hanami/router' router = Hanami::Router.new do get '/books/:id', to: 'books#show', as: :book end route = router.recognize(:book, id: 23) route.verb # => "GET" (default) route.routable? # => true route.params # => {:id=>"23"} @example Failing Recognition For Unknown Path require 'hanami/router' router = Hanami::Router.new do get '/books/:id', to: 'books#show', as: :book end route = router.recognize('/books') route.verb # => "GET" (default) route.routable? # => false @example Failing Recognition For Path With Wrong HTTP Verb require 'hanami/router' router = Hanami::Router.new do get '/books/:id', to: 'books#show', as: :book end route = router.recognize('/books/23', method: :post) route.verb # => "POST" route.routable? # => false @example Failing Recognition For Rack Env With Wrong HTTP Verb require 'hanami/router' router = Hanami::Router.new do get '/books/:id', to: 'books#show', as: :book end route = router.recognize(Rack::MockRequest.env_for('/books/23', method: :post)) route.verb # => "POST" route.routable? # => false @example Failing Recognition Named Route With Wrong Params require 'hanami/router' router = Hanami::Router.new do get '/books/:id', to: 'books#show', as: :book end route = router.recognize(:book) route.verb # => "GET" (default) route.routable? # => false @example Failing Recognition Named Route With Wrong HTTP Verb require 'hanami/router' router = Hanami::Router.new do get '/books/:id', to: 'books#show', as: :book end route = router.recognize(:book, {method: :post}, {id: 1}) route.verb # => "POST" route.routable? # => false route.params # => {:id=>"1"}
[ "Recognize", "the", "given", "env", "path", "or", "name", "and", "return", "a", "route", "for", "testing", "inspection", "." ]
05bb4fb3fce8ff9a9f32858412cc31890d3c1aa7
https://github.com/hanami/router/blob/05bb4fb3fce8ff9a9f32858412cc31890d3c1aa7/lib/hanami/router.rb#L1130-L1139
16,553
hanami/router
lib/hanami/router.rb
Hanami.Router.env_for
def env_for(env, options = {}, params = nil) env = case env when String Rack::MockRequest.env_for(env, options) when Symbol begin url = path(env, params || options) return env_for(url, options) rescue Hanami::Routing::InvalidRouteException {} end else env end end
ruby
def env_for(env, options = {}, params = nil) env = case env when String Rack::MockRequest.env_for(env, options) when Symbol begin url = path(env, params || options) return env_for(url, options) rescue Hanami::Routing::InvalidRouteException {} end else env end end
[ "def", "env_for", "(", "env", ",", "options", "=", "{", "}", ",", "params", "=", "nil", ")", "env", "=", "case", "env", "when", "String", "Rack", "::", "MockRequest", ".", "env_for", "(", "env", ",", "options", ")", "when", "Symbol", "begin", "url", "=", "path", "(", "env", ",", "params", "||", "options", ")", "return", "env_for", "(", "url", ",", "options", ")", "rescue", "Hanami", "::", "Routing", "::", "InvalidRouteException", "{", "}", "end", "else", "env", "end", "end" ]
Fabricate Rack env for the given Rack env, path or named route @param env [Hash, String, Symbol] Rack env, path or route name @param options [Hash] a set of options for Rack env or route params @param params [Hash] a set of params @return [Hash] Rack env @since 0.5.0 @api private @see Hanami::Router#recognize @see http://www.rubydoc.info/github/rack/rack/Rack%2FMockRequest.env_for
[ "Fabricate", "Rack", "env", "for", "the", "given", "Rack", "env", "path", "or", "named", "route" ]
05bb4fb3fce8ff9a9f32858412cc31890d3c1aa7
https://github.com/hanami/router/blob/05bb4fb3fce8ff9a9f32858412cc31890d3c1aa7/lib/hanami/router.rb#L1236-L1250
16,554
biola/turnout
lib/turnout/i18n/accept_language_parser.rb
Turnout.AcceptLanguageParser.user_preferred_languages
def user_preferred_languages return [] if header.to_s.strip.empty? @user_preferred_languages ||= begin header.to_s.gsub(/\s+/, '').split(',').map do |language| locale, quality = language.split(';q=') raise ArgumentError, 'Not correctly formatted' unless locale =~ /^[a-z\-0-9]+|\*$/i locale = locale.downcase.gsub(/-[a-z0-9]+$/i, &:upcase) # Uppercase territory locale = nil if locale == '*' # Ignore wildcards quality = quality ? quality.to_f : 1.0 [locale, quality] end.sort do |(_, left), (_, right)| right <=> left end.map(&:first).compact rescue ArgumentError # Just rescue anything if the browser messed up badly. [] end end
ruby
def user_preferred_languages return [] if header.to_s.strip.empty? @user_preferred_languages ||= begin header.to_s.gsub(/\s+/, '').split(',').map do |language| locale, quality = language.split(';q=') raise ArgumentError, 'Not correctly formatted' unless locale =~ /^[a-z\-0-9]+|\*$/i locale = locale.downcase.gsub(/-[a-z0-9]+$/i, &:upcase) # Uppercase territory locale = nil if locale == '*' # Ignore wildcards quality = quality ? quality.to_f : 1.0 [locale, quality] end.sort do |(_, left), (_, right)| right <=> left end.map(&:first).compact rescue ArgumentError # Just rescue anything if the browser messed up badly. [] end end
[ "def", "user_preferred_languages", "return", "[", "]", "if", "header", ".", "to_s", ".", "strip", ".", "empty?", "@user_preferred_languages", "||=", "begin", "header", ".", "to_s", ".", "gsub", "(", "/", "\\s", "/", ",", "''", ")", ".", "split", "(", "','", ")", ".", "map", "do", "|", "language", "|", "locale", ",", "quality", "=", "language", ".", "split", "(", "';q='", ")", "raise", "ArgumentError", ",", "'Not correctly formatted'", "unless", "locale", "=~", "/", "\\-", "\\*", "/i", "locale", "=", "locale", ".", "downcase", ".", "gsub", "(", "/", "/i", ",", ":upcase", ")", "# Uppercase territory", "locale", "=", "nil", "if", "locale", "==", "'*'", "# Ignore wildcards", "quality", "=", "quality", "?", "quality", ".", "to_f", ":", "1.0", "[", "locale", ",", "quality", "]", "end", ".", "sort", "do", "|", "(", "_", ",", "left", ")", ",", "(", "_", ",", "right", ")", "|", "right", "<=>", "left", "end", ".", "map", "(", ":first", ")", ".", "compact", "rescue", "ArgumentError", "# Just rescue anything if the browser messed up badly.", "[", "]", "end", "end" ]
Returns a sorted array based on user preference in HTTP_ACCEPT_LANGUAGE. Browsers send this HTTP header, so don't think this is holy. Example: request.user_preferred_languages # => [ 'nl-NL', 'nl-BE', 'nl', 'en-US', 'en' ]
[ "Returns", "a", "sorted", "array", "based", "on", "user", "preference", "in", "HTTP_ACCEPT_LANGUAGE", ".", "Browsers", "send", "this", "HTTP", "header", "so", "don", "t", "think", "this", "is", "holy", "." ]
9c57f9d75e31904bc345ecceb9ec392ce3fdb634
https://github.com/biola/turnout/blob/9c57f9d75e31904bc345ecceb9ec392ce3fdb634/lib/turnout/i18n/accept_language_parser.rb#L17-L36
16,555
biola/turnout
lib/turnout/i18n/accept_language_parser.rb
Turnout.AcceptLanguageParser.compatible_language_from
def compatible_language_from(available_languages) user_preferred_languages.map do |preferred| #en-US preferred = preferred.downcase preferred_language = preferred.split('-', 2).first available_languages.find do |available| # en available = available.to_s.downcase preferred == available || preferred_language == available.split('-', 2).first end end.compact.first end
ruby
def compatible_language_from(available_languages) user_preferred_languages.map do |preferred| #en-US preferred = preferred.downcase preferred_language = preferred.split('-', 2).first available_languages.find do |available| # en available = available.to_s.downcase preferred == available || preferred_language == available.split('-', 2).first end end.compact.first end
[ "def", "compatible_language_from", "(", "available_languages", ")", "user_preferred_languages", ".", "map", "do", "|", "preferred", "|", "#en-US", "preferred", "=", "preferred", ".", "downcase", "preferred_language", "=", "preferred", ".", "split", "(", "'-'", ",", "2", ")", ".", "first", "available_languages", ".", "find", "do", "|", "available", "|", "# en", "available", "=", "available", ".", "to_s", ".", "downcase", "preferred", "==", "available", "||", "preferred_language", "==", "available", ".", "split", "(", "'-'", ",", "2", ")", ".", "first", "end", "end", ".", "compact", ".", "first", "end" ]
Returns the first of the user_preferred_languages that is compatible with the available locales. Ignores region. Example: request.compatible_language_from I18n.available_locales
[ "Returns", "the", "first", "of", "the", "user_preferred_languages", "that", "is", "compatible", "with", "the", "available", "locales", ".", "Ignores", "region", "." ]
9c57f9d75e31904bc345ecceb9ec392ce3fdb634
https://github.com/biola/turnout/blob/9c57f9d75e31904bc345ecceb9ec392ce3fdb634/lib/turnout/i18n/accept_language_parser.rb#L62-L72
16,556
biola/turnout
lib/turnout/i18n/accept_language_parser.rb
Turnout.AcceptLanguageParser.sanitize_available_locales
def sanitize_available_locales(available_languages) available_languages.map do |available| available.to_s.split(/[_-]/).reject { |part| part.start_with?("x") }.join("-") end end
ruby
def sanitize_available_locales(available_languages) available_languages.map do |available| available.to_s.split(/[_-]/).reject { |part| part.start_with?("x") }.join("-") end end
[ "def", "sanitize_available_locales", "(", "available_languages", ")", "available_languages", ".", "map", "do", "|", "available", "|", "available", ".", "to_s", ".", "split", "(", "/", "/", ")", ".", "reject", "{", "|", "part", "|", "part", ".", "start_with?", "(", "\"x\"", ")", "}", ".", "join", "(", "\"-\"", ")", "end", "end" ]
Returns a supplied list of available locals without any extra application info that may be attached to the locale for storage in the application. Example: [ja_JP-x1, en-US-x4, en_UK-x5, fr-FR-x3] => [ja-JP, en-US, en-UK, fr-FR]
[ "Returns", "a", "supplied", "list", "of", "available", "locals", "without", "any", "extra", "application", "info", "that", "may", "be", "attached", "to", "the", "locale", "for", "storage", "in", "the", "application", "." ]
9c57f9d75e31904bc345ecceb9ec392ce3fdb634
https://github.com/biola/turnout/blob/9c57f9d75e31904bc345ecceb9ec392ce3fdb634/lib/turnout/i18n/accept_language_parser.rb#L80-L84
16,557
biola/turnout
lib/turnout/i18n/accept_language_parser.rb
Turnout.AcceptLanguageParser.language_region_compatible_from
def language_region_compatible_from(available_languages) available_languages = sanitize_available_locales(available_languages) user_preferred_languages.map do |preferred| #en-US preferred = preferred.downcase preferred_language = preferred.split('-', 2).first lang_group = available_languages.select do |available| # en preferred_language == available.downcase.split('-', 2).first end lang_group.find { |lang| lang.downcase == preferred } || lang_group.first #en-US, en-UK end.compact.first end
ruby
def language_region_compatible_from(available_languages) available_languages = sanitize_available_locales(available_languages) user_preferred_languages.map do |preferred| #en-US preferred = preferred.downcase preferred_language = preferred.split('-', 2).first lang_group = available_languages.select do |available| # en preferred_language == available.downcase.split('-', 2).first end lang_group.find { |lang| lang.downcase == preferred } || lang_group.first #en-US, en-UK end.compact.first end
[ "def", "language_region_compatible_from", "(", "available_languages", ")", "available_languages", "=", "sanitize_available_locales", "(", "available_languages", ")", "user_preferred_languages", ".", "map", "do", "|", "preferred", "|", "#en-US", "preferred", "=", "preferred", ".", "downcase", "preferred_language", "=", "preferred", ".", "split", "(", "'-'", ",", "2", ")", ".", "first", "lang_group", "=", "available_languages", ".", "select", "do", "|", "available", "|", "# en", "preferred_language", "==", "available", ".", "downcase", ".", "split", "(", "'-'", ",", "2", ")", ".", "first", "end", "lang_group", ".", "find", "{", "|", "lang", "|", "lang", ".", "downcase", "==", "preferred", "}", "||", "lang_group", ".", "first", "#en-US, en-UK", "end", ".", "compact", ".", "first", "end" ]
Returns the first of the user preferred languages that is also found in available languages. Finds best fit by matching on primary language first and secondarily on region. If no matching region is found, return the first language in the group matching that primary language. Example: request.language_region_compatible(available_languages)
[ "Returns", "the", "first", "of", "the", "user", "preferred", "languages", "that", "is", "also", "found", "in", "available", "languages", ".", "Finds", "best", "fit", "by", "matching", "on", "primary", "language", "first", "and", "secondarily", "on", "region", ".", "If", "no", "matching", "region", "is", "found", "return", "the", "first", "language", "in", "the", "group", "matching", "that", "primary", "language", "." ]
9c57f9d75e31904bc345ecceb9ec392ce3fdb634
https://github.com/biola/turnout/blob/9c57f9d75e31904bc345ecceb9ec392ce3fdb634/lib/turnout/i18n/accept_language_parser.rb#L95-L107
16,558
biola/turnout
lib/turnout/ordered_options.rb
Turnout.OrderedOptions.update
def update(other_hash) if other_hash.is_a? Hash super(other_hash) else other_hash.to_hash.each_pair do |key, value| if block_given? value = yield(key, value) end self[key] = value end self end end
ruby
def update(other_hash) if other_hash.is_a? Hash super(other_hash) else other_hash.to_hash.each_pair do |key, value| if block_given? value = yield(key, value) end self[key] = value end self end end
[ "def", "update", "(", "other_hash", ")", "if", "other_hash", ".", "is_a?", "Hash", "super", "(", "other_hash", ")", "else", "other_hash", ".", "to_hash", ".", "each_pair", "do", "|", "key", ",", "value", "|", "if", "block_given?", "value", "=", "yield", "(", "key", ",", "value", ")", "end", "self", "[", "key", "]", "=", "value", "end", "self", "end", "end" ]
make it protected
[ "make", "it", "protected" ]
9c57f9d75e31904bc345ecceb9ec392ce3fdb634
https://github.com/biola/turnout/blob/9c57f9d75e31904bc345ecceb9ec392ce3fdb634/lib/turnout/ordered_options.rb#L19-L31
16,559
schacon/git-scribe
docbook-xsl/epub/bin/lib/docbook.rb
DocBook.Epub.has_callouts?
def has_callouts? parser = REXML::Parsers::PullParser.new(File.new(@docbook_file)) while parser.has_next? el = parser.pull if el.start_element? and (el[0] == "calloutlist" or el[0] == "co") return true end end return false end
ruby
def has_callouts? parser = REXML::Parsers::PullParser.new(File.new(@docbook_file)) while parser.has_next? el = parser.pull if el.start_element? and (el[0] == "calloutlist" or el[0] == "co") return true end end return false end
[ "def", "has_callouts?", "parser", "=", "REXML", "::", "Parsers", "::", "PullParser", ".", "new", "(", "File", ".", "new", "(", "@docbook_file", ")", ")", "while", "parser", ".", "has_next?", "el", "=", "parser", ".", "pull", "if", "el", ".", "start_element?", "and", "(", "el", "[", "0", "]", "==", "\"calloutlist\"", "or", "el", "[", "0", "]", "==", "\"co\"", ")", "return", "true", "end", "end", "return", "false", "end" ]
Returns true if the document has code callouts
[ "Returns", "true", "if", "the", "document", "has", "code", "callouts" ]
41424bb312975cc49ed9716a932e216485ebf2d3
https://github.com/schacon/git-scribe/blob/41424bb312975cc49ed9716a932e216485ebf2d3/docbook-xsl/epub/bin/lib/docbook.rb#L195-L204
16,560
piotrmurach/pastel
lib/pastel/delegator.rb
Pastel.Delegator.evaluate_block
def evaluate_block(&block) delegator = self.class.new(resolver, DecoratorChain.empty) delegator.instance_eval(&block) end
ruby
def evaluate_block(&block) delegator = self.class.new(resolver, DecoratorChain.empty) delegator.instance_eval(&block) end
[ "def", "evaluate_block", "(", "&", "block", ")", "delegator", "=", "self", ".", "class", ".", "new", "(", "resolver", ",", "DecoratorChain", ".", "empty", ")", "delegator", ".", "instance_eval", "(", "block", ")", "end" ]
Evaluate color block @api private
[ "Evaluate", "color", "block" ]
799c122b88de4f3676a960bdf620199ad7219d3f
https://github.com/piotrmurach/pastel/blob/799c122b88de4f3676a960bdf620199ad7219d3f/lib/pastel/delegator.rb#L87-L90
16,561
piotrmurach/pastel
lib/pastel/color.rb
Pastel.Color.decorate
def decorate(string, *colors) return string if blank?(string) || !enabled || colors.empty? ansi_colors = lookup(*colors.dup.uniq) if eachline string.dup.split(eachline).map! do |line| apply_codes(line, ansi_colors) end.join(eachline) else apply_codes(string.dup, ansi_colors) end end
ruby
def decorate(string, *colors) return string if blank?(string) || !enabled || colors.empty? ansi_colors = lookup(*colors.dup.uniq) if eachline string.dup.split(eachline).map! do |line| apply_codes(line, ansi_colors) end.join(eachline) else apply_codes(string.dup, ansi_colors) end end
[ "def", "decorate", "(", "string", ",", "*", "colors", ")", "return", "string", "if", "blank?", "(", "string", ")", "||", "!", "enabled", "||", "colors", ".", "empty?", "ansi_colors", "=", "lookup", "(", "colors", ".", "dup", ".", "uniq", ")", "if", "eachline", "string", ".", "dup", ".", "split", "(", "eachline", ")", ".", "map!", "do", "|", "line", "|", "apply_codes", "(", "line", ",", "ansi_colors", ")", "end", ".", "join", "(", "eachline", ")", "else", "apply_codes", "(", "string", ".", "dup", ",", "ansi_colors", ")", "end", "end" ]
Apply ANSI color to the given string. Wraps eachline with clear escape. @param [String] string text to add ANSI strings @param [Array[Symbol]] colors the color names @example color.decorate "text", :yellow, :on_green, :underline @return [String] the colored string @api public
[ "Apply", "ANSI", "color", "to", "the", "given", "string", "." ]
799c122b88de4f3676a960bdf620199ad7219d3f
https://github.com/piotrmurach/pastel/blob/799c122b88de4f3676a960bdf620199ad7219d3f/lib/pastel/color.rb#L57-L68
16,562
piotrmurach/pastel
lib/pastel/color.rb
Pastel.Color.strip
def strip(*strings) modified = strings.map { |string| string.dup.gsub(ANSI_COLOR_REGEXP, '') } modified.size == 1 ? modified[0] : modified end
ruby
def strip(*strings) modified = strings.map { |string| string.dup.gsub(ANSI_COLOR_REGEXP, '') } modified.size == 1 ? modified[0] : modified end
[ "def", "strip", "(", "*", "strings", ")", "modified", "=", "strings", ".", "map", "{", "|", "string", "|", "string", ".", "dup", ".", "gsub", "(", "ANSI_COLOR_REGEXP", ",", "''", ")", "}", "modified", ".", "size", "==", "1", "?", "modified", "[", "0", "]", ":", "modified", "end" ]
Strip ANSI color codes from a string. Only ANSI color codes are removed, not movement codes or other escapes sequences are stripped. @param [Array[String]] strings a string or array of strings to sanitize @example strip("foo\e[1mbar\e[0m") # => "foobar" @return [String] @api public
[ "Strip", "ANSI", "color", "codes", "from", "a", "string", "." ]
799c122b88de4f3676a960bdf620199ad7219d3f
https://github.com/piotrmurach/pastel/blob/799c122b88de4f3676a960bdf620199ad7219d3f/lib/pastel/color.rb#L106-L109
16,563
piotrmurach/pastel
lib/pastel/color.rb
Pastel.Color.code
def code(*colors) attribute = [] colors.each do |color| value = ANSI::ATTRIBUTES[color] || ALIASES[color] if value attribute << value else validate(color) end end attribute end
ruby
def code(*colors) attribute = [] colors.each do |color| value = ANSI::ATTRIBUTES[color] || ALIASES[color] if value attribute << value else validate(color) end end attribute end
[ "def", "code", "(", "*", "colors", ")", "attribute", "=", "[", "]", "colors", ".", "each", "do", "|", "color", "|", "value", "=", "ANSI", "::", "ATTRIBUTES", "[", "color", "]", "||", "ALIASES", "[", "color", "]", "if", "value", "attribute", "<<", "value", "else", "validate", "(", "color", ")", "end", "end", "attribute", "end" ]
Return raw color code without embeding it into a string. @return [Array[String]] ANSI escape codes @api public
[ "Return", "raw", "color", "code", "without", "embeding", "it", "into", "a", "string", "." ]
799c122b88de4f3676a960bdf620199ad7219d3f
https://github.com/piotrmurach/pastel/blob/799c122b88de4f3676a960bdf620199ad7219d3f/lib/pastel/color.rb#L151-L162
16,564
piotrmurach/pastel
lib/pastel/color.rb
Pastel.Color.alias_color
def alias_color(alias_name, *colors) validate(*colors) if !(alias_name.to_s =~ /^[\w]+$/) fail InvalidAliasNameError, "Invalid alias name `#{alias_name}`" elsif ANSI::ATTRIBUTES[alias_name] fail InvalidAliasNameError, "Cannot alias standard color `#{alias_name}`" end ALIASES[alias_name.to_sym] = colors.map(&ANSI::ATTRIBUTES.method(:[])) colors end
ruby
def alias_color(alias_name, *colors) validate(*colors) if !(alias_name.to_s =~ /^[\w]+$/) fail InvalidAliasNameError, "Invalid alias name `#{alias_name}`" elsif ANSI::ATTRIBUTES[alias_name] fail InvalidAliasNameError, "Cannot alias standard color `#{alias_name}`" end ALIASES[alias_name.to_sym] = colors.map(&ANSI::ATTRIBUTES.method(:[])) colors end
[ "def", "alias_color", "(", "alias_name", ",", "*", "colors", ")", "validate", "(", "colors", ")", "if", "!", "(", "alias_name", ".", "to_s", "=~", "/", "\\w", "/", ")", "fail", "InvalidAliasNameError", ",", "\"Invalid alias name `#{alias_name}`\"", "elsif", "ANSI", "::", "ATTRIBUTES", "[", "alias_name", "]", "fail", "InvalidAliasNameError", ",", "\"Cannot alias standard color `#{alias_name}`\"", "end", "ALIASES", "[", "alias_name", ".", "to_sym", "]", "=", "colors", ".", "map", "(", "ANSI", "::", "ATTRIBUTES", ".", "method", "(", ":[]", ")", ")", "colors", "end" ]
Define a new colors alias @param [String] alias_name the colors alias to define @param [Array[Symbol,String]] color the colors the alias will correspond to @return [Array[String]] the standard color values of the alias @api public
[ "Define", "a", "new", "colors", "alias" ]
799c122b88de4f3676a960bdf620199ad7219d3f
https://github.com/piotrmurach/pastel/blob/799c122b88de4f3676a960bdf620199ad7219d3f/lib/pastel/color.rb#L209-L221
16,565
piotrmurach/pastel
lib/pastel/alias_importer.rb
Pastel.AliasImporter.import
def import color_aliases = env['PASTEL_COLORS_ALIASES'] return unless color_aliases color_aliases.split(',').each do |color_alias| new_color, old_colors = color_alias.split('=') if !new_color || !old_colors output.puts "Bad color mapping `#{color_alias}`" else color.alias_color(new_color.to_sym, *old_colors.split('.').map(&:to_sym)) end end end
ruby
def import color_aliases = env['PASTEL_COLORS_ALIASES'] return unless color_aliases color_aliases.split(',').each do |color_alias| new_color, old_colors = color_alias.split('=') if !new_color || !old_colors output.puts "Bad color mapping `#{color_alias}`" else color.alias_color(new_color.to_sym, *old_colors.split('.').map(&:to_sym)) end end end
[ "def", "import", "color_aliases", "=", "env", "[", "'PASTEL_COLORS_ALIASES'", "]", "return", "unless", "color_aliases", "color_aliases", ".", "split", "(", "','", ")", ".", "each", "do", "|", "color_alias", "|", "new_color", ",", "old_colors", "=", "color_alias", ".", "split", "(", "'='", ")", "if", "!", "new_color", "||", "!", "old_colors", "output", ".", "puts", "\"Bad color mapping `#{color_alias}`\"", "else", "color", ".", "alias_color", "(", "new_color", ".", "to_sym", ",", "old_colors", ".", "split", "(", "'.'", ")", ".", "map", "(", ":to_sym", ")", ")", "end", "end", "end" ]
Create alias importer @example importer = Pastel::AliasImporter.new(Pastel::Color.new, {}) @api public Import aliases from the environment @example importer = Pastel::AliasImporter.new(Pastel::Color.new, {}) importer.import @return [nil] @api public
[ "Create", "alias", "importer" ]
799c122b88de4f3676a960bdf620199ad7219d3f
https://github.com/piotrmurach/pastel/blob/799c122b88de4f3676a960bdf620199ad7219d3f/lib/pastel/alias_importer.rb#L27-L39
16,566
SciRuby/daru-view
lib/daru/view/adapters/googlecharts/base_chart.rb
GoogleVisualr.BaseChart.draw_js_spreadsheet
def draw_js_spreadsheet(data, element_id=SecureRandom.uuid) js = '' js << "\n function #{chart_function_name(element_id)}() {" js << "\n var query = new google.visualization.Query('#{data}');" js << "\n query.send(#{query_response_function_name(element_id)});" js << "\n }" js << "\n function #{query_response_function_name(element_id)}(response) {" js << "\n var data_table = response.getDataTable();" js << "\n var chart = new google.#{chart_class}.#{chart_name}"\ "(document.getElementById('#{element_id}'));" js << add_listeners_js('chart') js << "\n chart.draw(data_table, #{js_parameters(@options)});" js << "\n };" js end
ruby
def draw_js_spreadsheet(data, element_id=SecureRandom.uuid) js = '' js << "\n function #{chart_function_name(element_id)}() {" js << "\n var query = new google.visualization.Query('#{data}');" js << "\n query.send(#{query_response_function_name(element_id)});" js << "\n }" js << "\n function #{query_response_function_name(element_id)}(response) {" js << "\n var data_table = response.getDataTable();" js << "\n var chart = new google.#{chart_class}.#{chart_name}"\ "(document.getElementById('#{element_id}'));" js << add_listeners_js('chart') js << "\n chart.draw(data_table, #{js_parameters(@options)});" js << "\n };" js end
[ "def", "draw_js_spreadsheet", "(", "data", ",", "element_id", "=", "SecureRandom", ".", "uuid", ")", "js", "=", "''", "js", "<<", "\"\\n function #{chart_function_name(element_id)}() {\"", "js", "<<", "\"\\n \tvar query = new google.visualization.Query('#{data}');\"", "js", "<<", "\"\\n \tquery.send(#{query_response_function_name(element_id)});\"", "js", "<<", "\"\\n }\"", "js", "<<", "\"\\n function #{query_response_function_name(element_id)}(response) {\"", "js", "<<", "\"\\n \tvar data_table = response.getDataTable();\"", "js", "<<", "\"\\n \tvar chart = new google.#{chart_class}.#{chart_name}\"", "\"(document.getElementById('#{element_id}'));\"", "js", "<<", "add_listeners_js", "(", "'chart'", ")", "js", "<<", "\"\\n \tchart.draw(data_table, #{js_parameters(@options)});\"", "js", "<<", "\"\\n };\"", "js", "end" ]
Generates JavaScript function for rendering the chart when data is URL of the google spreadsheet @param (see #to_js_spreadsheet) @return [String] JS function to render the google chart when data is URL of the google spreadsheet
[ "Generates", "JavaScript", "function", "for", "rendering", "the", "chart", "when", "data", "is", "URL", "of", "the", "google", "spreadsheet" ]
7662fae07a2f339d9600c1dda263b8e409fc5592
https://github.com/SciRuby/daru-view/blob/7662fae07a2f339d9600c1dda263b8e409fc5592/lib/daru/view/adapters/googlecharts/base_chart.rb#L40-L54
16,567
SciRuby/daru-view
lib/daru/view/adapters/googlecharts/data_table_iruby.rb
GoogleVisualr.DataTable.to_js_full_script
def to_js_full_script(element_id=SecureRandom.uuid) js = '' js << '\n<script type=\'text/javascript\'>' js << load_js(element_id) js << draw_js(element_id) js << '\n</script>' js end
ruby
def to_js_full_script(element_id=SecureRandom.uuid) js = '' js << '\n<script type=\'text/javascript\'>' js << load_js(element_id) js << draw_js(element_id) js << '\n</script>' js end
[ "def", "to_js_full_script", "(", "element_id", "=", "SecureRandom", ".", "uuid", ")", "js", "=", "''", "js", "<<", "'\\n<script type=\\'text/javascript\\'>'", "js", "<<", "load_js", "(", "element_id", ")", "js", "<<", "draw_js", "(", "element_id", ")", "js", "<<", "'\\n</script>'", "js", "end" ]
Generates JavaScript and renders the Google Chart DataTable in the final HTML output @param element_id [String] The ID of the DIV element that the Google Chart DataTable should be rendered in @return [String] Javascript code to render the Google Chart DataTable
[ "Generates", "JavaScript", "and", "renders", "the", "Google", "Chart", "DataTable", "in", "the", "final", "HTML", "output" ]
7662fae07a2f339d9600c1dda263b8e409fc5592
https://github.com/SciRuby/daru-view/blob/7662fae07a2f339d9600c1dda263b8e409fc5592/lib/daru/view/adapters/googlecharts/data_table_iruby.rb#L58-L65
16,568
SciRuby/daru-view
lib/daru/view/adapters/googlecharts/data_table_iruby.rb
GoogleVisualr.DataTable.draw_js
def draw_js(element_id) js = '' js << "\n function #{chart_function_name(element_id)}() {" js << "\n #{to_js}" js << "\n var table = new google.visualization.Table(" js << "document.getElementById('#{element_id}'));" js << add_listeners_js('table') js << "\n table.draw(data_table, #{js_parameters(@options)}); " js << "\n };" js end
ruby
def draw_js(element_id) js = '' js << "\n function #{chart_function_name(element_id)}() {" js << "\n #{to_js}" js << "\n var table = new google.visualization.Table(" js << "document.getElementById('#{element_id}'));" js << add_listeners_js('table') js << "\n table.draw(data_table, #{js_parameters(@options)}); " js << "\n };" js end
[ "def", "draw_js", "(", "element_id", ")", "js", "=", "''", "js", "<<", "\"\\n function #{chart_function_name(element_id)}() {\"", "js", "<<", "\"\\n #{to_js}\"", "js", "<<", "\"\\n var table = new google.visualization.Table(\"", "js", "<<", "\"document.getElementById('#{element_id}'));\"", "js", "<<", "add_listeners_js", "(", "'table'", ")", "js", "<<", "\"\\n table.draw(data_table, #{js_parameters(@options)}); \"", "js", "<<", "\"\\n };\"", "js", "end" ]
Generates JavaScript function for rendering the google chart table. @param element_id [String] The ID of the DIV element that the Google Chart DataTable should be rendered in @return [String] JS function to render the google chart table
[ "Generates", "JavaScript", "function", "for", "rendering", "the", "google", "chart", "table", "." ]
7662fae07a2f339d9600c1dda263b8e409fc5592
https://github.com/SciRuby/daru-view/blob/7662fae07a2f339d9600c1dda263b8e409fc5592/lib/daru/view/adapters/googlecharts/data_table_iruby.rb#L109-L119
16,569
SciRuby/daru-view
lib/daru/view/adapters/googlecharts/data_table_iruby.rb
GoogleVisualr.DataTable.draw_js_spreadsheet
def draw_js_spreadsheet(data, element_id) js = '' js << "\n function #{chart_function_name(element_id)}() {" js << "\n var query = new google.visualization.Query('#{data}');" js << "\n query.send(#{query_response_function_name(element_id)});" js << "\n }" js << "\n function #{query_response_function_name(element_id)}(response) {" js << "\n var data_table = response.getDataTable();" js << "\n var table = new google.visualization.Table"\ "(document.getElementById('#{element_id}'));" js << add_listeners_js('table') js << "\n table.draw(data_table, #{js_parameters(@options)});" js << "\n };" js end
ruby
def draw_js_spreadsheet(data, element_id) js = '' js << "\n function #{chart_function_name(element_id)}() {" js << "\n var query = new google.visualization.Query('#{data}');" js << "\n query.send(#{query_response_function_name(element_id)});" js << "\n }" js << "\n function #{query_response_function_name(element_id)}(response) {" js << "\n var data_table = response.getDataTable();" js << "\n var table = new google.visualization.Table"\ "(document.getElementById('#{element_id}'));" js << add_listeners_js('table') js << "\n table.draw(data_table, #{js_parameters(@options)});" js << "\n };" js end
[ "def", "draw_js_spreadsheet", "(", "data", ",", "element_id", ")", "js", "=", "''", "js", "<<", "\"\\n function #{chart_function_name(element_id)}() {\"", "js", "<<", "\"\\n var query = new google.visualization.Query('#{data}');\"", "js", "<<", "\"\\n query.send(#{query_response_function_name(element_id)});\"", "js", "<<", "\"\\n }\"", "js", "<<", "\"\\n function #{query_response_function_name(element_id)}(response) {\"", "js", "<<", "\"\\n var data_table = response.getDataTable();\"", "js", "<<", "\"\\n var table = new google.visualization.Table\"", "\"(document.getElementById('#{element_id}'));\"", "js", "<<", "add_listeners_js", "(", "'table'", ")", "js", "<<", "\"\\n \ttable.draw(data_table, #{js_parameters(@options)});\"", "js", "<<", "\"\\n };\"", "js", "end" ]
Generates JavaScript function for rendering the google chart table when data is URL of the google spreadsheet @param (see #to_js_full_script_spreadsheet) @return [String] JS function to render the google chart table when data is URL of the google spreadsheet
[ "Generates", "JavaScript", "function", "for", "rendering", "the", "google", "chart", "table", "when", "data", "is", "URL", "of", "the", "google", "spreadsheet" ]
7662fae07a2f339d9600c1dda263b8e409fc5592
https://github.com/SciRuby/daru-view/blob/7662fae07a2f339d9600c1dda263b8e409fc5592/lib/daru/view/adapters/googlecharts/data_table_iruby.rb#L127-L141
16,570
SciRuby/daru-view
lib/daru/view/adapters/highcharts/display.rb
LazyHighCharts.HighChart.to_html_iruby
def to_html_iruby(placeholder=random_canvas_id) # TODO : placeholder pass, in plot#div @div_id = placeholder load_dependencies('iruby') chart_hash_must_be_present script = high_chart_css(placeholder) script << high_chart_iruby(extract_chart_class, placeholder, self) script end
ruby
def to_html_iruby(placeholder=random_canvas_id) # TODO : placeholder pass, in plot#div @div_id = placeholder load_dependencies('iruby') chart_hash_must_be_present script = high_chart_css(placeholder) script << high_chart_iruby(extract_chart_class, placeholder, self) script end
[ "def", "to_html_iruby", "(", "placeholder", "=", "random_canvas_id", ")", "# TODO : placeholder pass, in plot#div", "@div_id", "=", "placeholder", "load_dependencies", "(", "'iruby'", ")", "chart_hash_must_be_present", "script", "=", "high_chart_css", "(", "placeholder", ")", "script", "<<", "high_chart_iruby", "(", "extract_chart_class", ",", "placeholder", ",", "self", ")", "script", "end" ]
This method is not needed if `to_html` generates the same code. Here `to_html` generates the code with `onload`, so there is need of `high_chart_iruby` which doesn't use `onload` in chart script.
[ "This", "method", "is", "not", "needed", "if", "to_html", "generates", "the", "same", "code", ".", "Here", "to_html", "generates", "the", "code", "with", "onload", "so", "there", "is", "need", "of", "high_chart_iruby", "which", "doesn", "t", "use", "onload", "in", "chart", "script", "." ]
7662fae07a2f339d9600c1dda263b8e409fc5592
https://github.com/SciRuby/daru-view/blob/7662fae07a2f339d9600c1dda263b8e409fc5592/lib/daru/view/adapters/highcharts/display.rb#L95-L103
16,571
SciRuby/daru-view
lib/daru/view/adapters/highcharts/display.rb
LazyHighCharts.HighChart.load_dependencies
def load_dependencies(type) dep_js = extract_dependencies if type == 'iruby' LazyHighCharts.init_iruby(dep_js) unless dep_js.nil? elsif type == 'web_frameworks' dep_js.nil? ? '' : LazyHighCharts.init_javascript(dep_js) end end
ruby
def load_dependencies(type) dep_js = extract_dependencies if type == 'iruby' LazyHighCharts.init_iruby(dep_js) unless dep_js.nil? elsif type == 'web_frameworks' dep_js.nil? ? '' : LazyHighCharts.init_javascript(dep_js) end end
[ "def", "load_dependencies", "(", "type", ")", "dep_js", "=", "extract_dependencies", "if", "type", "==", "'iruby'", "LazyHighCharts", ".", "init_iruby", "(", "dep_js", ")", "unless", "dep_js", ".", "nil?", "elsif", "type", "==", "'web_frameworks'", "dep_js", ".", "nil?", "?", "''", ":", "LazyHighCharts", ".", "init_javascript", "(", "dep_js", ")", "end", "end" ]
Loads the dependent mapdata and dependent modules of the chart @param [String] to determine whether to load modules in IRuby or web frameworks @return [void, String] loads the initial script of the modules for IRuby notebook and returns initial script of the modules for web frameworks
[ "Loads", "the", "dependent", "mapdata", "and", "dependent", "modules", "of", "the", "chart" ]
7662fae07a2f339d9600c1dda263b8e409fc5592
https://github.com/SciRuby/daru-view/blob/7662fae07a2f339d9600c1dda263b8e409fc5592/lib/daru/view/adapters/highcharts/display.rb#L134-L141
16,572
SciRuby/daru-view
lib/daru/view/adapters/highcharts/display.rb
LazyHighCharts.HighChart.export_iruby
def export_iruby(export_type='png', file_name='chart') js = '' js << to_html_iruby js << extract_export_code_iruby(@div_id, export_type, file_name) IRuby.html js end
ruby
def export_iruby(export_type='png', file_name='chart') js = '' js << to_html_iruby js << extract_export_code_iruby(@div_id, export_type, file_name) IRuby.html js end
[ "def", "export_iruby", "(", "export_type", "=", "'png'", ",", "file_name", "=", "'chart'", ")", "js", "=", "''", "js", "<<", "to_html_iruby", "js", "<<", "extract_export_code_iruby", "(", "@div_id", ",", "export_type", ",", "file_name", ")", "IRuby", ".", "html", "js", "end" ]
Exports chart to different formats in IRuby notebook @param type [String] format to which chart has to be exported @param file_name [String] The name of the file after exporting the chart @return [void] loads the js code of chart along with the code to export in IRuby notebook
[ "Exports", "chart", "to", "different", "formats", "in", "IRuby", "notebook" ]
7662fae07a2f339d9600c1dda263b8e409fc5592
https://github.com/SciRuby/daru-view/blob/7662fae07a2f339d9600c1dda263b8e409fc5592/lib/daru/view/adapters/highcharts/display.rb#L189-L194
16,573
SciRuby/daru-view
lib/daru/view/adapters/highcharts/display.rb
LazyHighCharts.HighChart.extract_export_code
def extract_export_code( placeholder=random_canvas_id, export_type='png', file_name='chart' ) js = '' js << "\n <script>" js << "\n (function() {" js << "\n \tvar onload = window.onload;" js << "\n \twindow.onload = function(){" js << "\n \t\tif (typeof onload == 'function') onload();" js << "\n \t\tvar chartDom = document.getElementById('#{placeholder}');" js << "\n \t\tvar chart = Highcharts.charts[Highcharts.attr(chartDom," js << " 'data-highcharts-chart')]" js << "\n \t\tchart.exportChartLocal({" js << "\n \t\t\t" + append_chart_type(export_type) js << "\n \t\t\tfilename: '#{file_name}'" js << "\n \t\t});\n \t};\n })();" js << "\n </script>" js end
ruby
def extract_export_code( placeholder=random_canvas_id, export_type='png', file_name='chart' ) js = '' js << "\n <script>" js << "\n (function() {" js << "\n \tvar onload = window.onload;" js << "\n \twindow.onload = function(){" js << "\n \t\tif (typeof onload == 'function') onload();" js << "\n \t\tvar chartDom = document.getElementById('#{placeholder}');" js << "\n \t\tvar chart = Highcharts.charts[Highcharts.attr(chartDom," js << " 'data-highcharts-chart')]" js << "\n \t\tchart.exportChartLocal({" js << "\n \t\t\t" + append_chart_type(export_type) js << "\n \t\t\tfilename: '#{file_name}'" js << "\n \t\t});\n \t};\n })();" js << "\n </script>" js end
[ "def", "extract_export_code", "(", "placeholder", "=", "random_canvas_id", ",", "export_type", "=", "'png'", ",", "file_name", "=", "'chart'", ")", "js", "=", "''", "js", "<<", "\"\\n <script>\"", "js", "<<", "\"\\n (function() {\"", "js", "<<", "\"\\n \\tvar onload = window.onload;\"", "js", "<<", "\"\\n \\twindow.onload = function(){\"", "js", "<<", "\"\\n \\t\\tif (typeof onload == 'function') onload();\"", "js", "<<", "\"\\n \\t\\tvar chartDom = document.getElementById('#{placeholder}');\"", "js", "<<", "\"\\n \\t\\tvar chart = Highcharts.charts[Highcharts.attr(chartDom,\"", "js", "<<", "\" 'data-highcharts-chart')]\"", "js", "<<", "\"\\n \\t\\tchart.exportChartLocal({\"", "js", "<<", "\"\\n \\t\\t\\t\"", "+", "append_chart_type", "(", "export_type", ")", "js", "<<", "\"\\n \\t\\t\\tfilename: '#{file_name}'\"", "js", "<<", "\"\\n \\t\\t});\\n \\t};\\n })();\"", "js", "<<", "\"\\n </script>\"", "js", "end" ]
Returns the script to export the chart in different formats for web frameworks @param file_name [String] The name of the file after exporting the chart @param placeholder [String] The ID of the DIV element that the HighChart should be rendered in @param type [String] format to which chart has to be exported @return [String] the script to export the chart in web frameworks
[ "Returns", "the", "script", "to", "export", "the", "chart", "in", "different", "formats", "for", "web", "frameworks" ]
7662fae07a2f339d9600c1dda263b8e409fc5592
https://github.com/SciRuby/daru-view/blob/7662fae07a2f339d9600c1dda263b8e409fc5592/lib/daru/view/adapters/highcharts/display.rb#L204-L222
16,574
SciRuby/daru-view
lib/daru/view/adapters/highcharts/display.rb
LazyHighCharts.HighChart.extract_export_code_iruby
def extract_export_code_iruby( placeholder=random_canvas_id, export_type='png', file_name='chart' ) js = '' js << "\n <script>" js << "\n (function() {" js << "\n \tvar chartDom = document.getElementById('#{placeholder}');" js << "\n \tvar chart = Highcharts.charts[Highcharts.attr(chartDom," js << " 'data-highcharts-chart')]" js << "\n \tchart.exportChart({" js << "\n \t\t" + append_chart_type(export_type) js << "\n \t\tfilename: '#{file_name}'" js << "\n \t});" js << "\n })();" js << "\n </script>" js end
ruby
def extract_export_code_iruby( placeholder=random_canvas_id, export_type='png', file_name='chart' ) js = '' js << "\n <script>" js << "\n (function() {" js << "\n \tvar chartDom = document.getElementById('#{placeholder}');" js << "\n \tvar chart = Highcharts.charts[Highcharts.attr(chartDom," js << " 'data-highcharts-chart')]" js << "\n \tchart.exportChart({" js << "\n \t\t" + append_chart_type(export_type) js << "\n \t\tfilename: '#{file_name}'" js << "\n \t});" js << "\n })();" js << "\n </script>" js end
[ "def", "extract_export_code_iruby", "(", "placeholder", "=", "random_canvas_id", ",", "export_type", "=", "'png'", ",", "file_name", "=", "'chart'", ")", "js", "=", "''", "js", "<<", "\"\\n <script>\"", "js", "<<", "\"\\n (function() {\"", "js", "<<", "\"\\n \\tvar chartDom = document.getElementById('#{placeholder}');\"", "js", "<<", "\"\\n \\tvar chart = Highcharts.charts[Highcharts.attr(chartDom,\"", "js", "<<", "\" 'data-highcharts-chart')]\"", "js", "<<", "\"\\n \\tchart.exportChart({\"", "js", "<<", "\"\\n \\t\\t\"", "+", "append_chart_type", "(", "export_type", ")", "js", "<<", "\"\\n \\t\\tfilename: '#{file_name}'\"", "js", "<<", "\"\\n \\t});\"", "js", "<<", "\"\\n })();\"", "js", "<<", "\"\\n </script>\"", "js", "end" ]
Returns the script to export the chart in different formats in IRuby notebook @param (see #extract_export_code) @return [String] the script to export the chart in IRuby notebook
[ "Returns", "the", "script", "to", "export", "the", "chart", "in", "different", "formats", "in", "IRuby", "notebook" ]
7662fae07a2f339d9600c1dda263b8e409fc5592
https://github.com/SciRuby/daru-view/blob/7662fae07a2f339d9600c1dda263b8e409fc5592/lib/daru/view/adapters/highcharts/display.rb#L229-L245
16,575
chef/omnibus-ctl
lib/omnibus-ctl.rb
Omnibus.Ctl.get_all_commands_hash
def get_all_commands_hash without_categories = {} category_command_map.each do |category, commands| without_categories.merge!(commands) end command_map.merge(without_categories) end
ruby
def get_all_commands_hash without_categories = {} category_command_map.each do |category, commands| without_categories.merge!(commands) end command_map.merge(without_categories) end
[ "def", "get_all_commands_hash", "without_categories", "=", "{", "}", "category_command_map", ".", "each", "do", "|", "category", ",", "commands", "|", "without_categories", ".", "merge!", "(", "commands", ")", "end", "command_map", ".", "merge", "(", "without_categories", ")", "end" ]
merges category_command_map and command_map, removing categories
[ "merges", "category_command_map", "and", "command_map", "removing", "categories" ]
e160156deaa0afc037748b10d1c9ef0a5be97dc1
https://github.com/chef/omnibus-ctl/blob/e160156deaa0afc037748b10d1c9ef0a5be97dc1/lib/omnibus-ctl.rb#L173-L179
16,576
chef/omnibus-ctl
lib/omnibus-ctl.rb
Omnibus.Ctl.run_sv_command_for_service
def run_sv_command_for_service(sv_cmd, service_name) if service_enabled?(service_name) status = run_command("#{base_path}/init/#{service_name} #{sv_cmd}") status.exitstatus else log "#{service_name} disabled" if sv_cmd == "status" && verbose 0 end end
ruby
def run_sv_command_for_service(sv_cmd, service_name) if service_enabled?(service_name) status = run_command("#{base_path}/init/#{service_name} #{sv_cmd}") status.exitstatus else log "#{service_name} disabled" if sv_cmd == "status" && verbose 0 end end
[ "def", "run_sv_command_for_service", "(", "sv_cmd", ",", "service_name", ")", "if", "service_enabled?", "(", "service_name", ")", "status", "=", "run_command", "(", "\"#{base_path}/init/#{service_name} #{sv_cmd}\"", ")", "status", ".", "exitstatus", "else", "log", "\"#{service_name} disabled\"", "if", "sv_cmd", "==", "\"status\"", "&&", "verbose", "0", "end", "end" ]
run an sv command for a specific service name
[ "run", "an", "sv", "command", "for", "a", "specific", "service", "name" ]
e160156deaa0afc037748b10d1c9ef0a5be97dc1
https://github.com/chef/omnibus-ctl/blob/e160156deaa0afc037748b10d1c9ef0a5be97dc1/lib/omnibus-ctl.rb#L363-L371
16,577
chef/omnibus-ctl
lib/omnibus-ctl.rb
Omnibus.Ctl.parse_options
def parse_options(args) args.select do |option| case option when "--quiet", "-q" @quiet = true false when "--verbose", "-v" @verbose = true false end end end
ruby
def parse_options(args) args.select do |option| case option when "--quiet", "-q" @quiet = true false when "--verbose", "-v" @verbose = true false end end end
[ "def", "parse_options", "(", "args", ")", "args", ".", "select", "do", "|", "option", "|", "case", "option", "when", "\"--quiet\"", ",", "\"-q\"", "@quiet", "=", "true", "false", "when", "\"--verbose\"", ",", "\"-v\"", "@verbose", "=", "true", "false", "end", "end", "end" ]
Set global options and remove them from the args list we pass into commands.
[ "Set", "global", "options", "and", "remove", "them", "from", "the", "args", "list", "we", "pass", "into", "commands", "." ]
e160156deaa0afc037748b10d1c9ef0a5be97dc1
https://github.com/chef/omnibus-ctl/blob/e160156deaa0afc037748b10d1c9ef0a5be97dc1/lib/omnibus-ctl.rb#L651-L662
16,578
chef/omnibus-ctl
lib/omnibus-ctl.rb
Omnibus.Ctl.retrieve_command
def retrieve_command(command_to_run) if command_map.has_key?(command_to_run) command_map[command_to_run] else command = nil category_command_map.each do |category, commands| command = commands[command_to_run] if commands.has_key?(command_to_run) end # return the command, or nil if it wasn't found command end end
ruby
def retrieve_command(command_to_run) if command_map.has_key?(command_to_run) command_map[command_to_run] else command = nil category_command_map.each do |category, commands| command = commands[command_to_run] if commands.has_key?(command_to_run) end # return the command, or nil if it wasn't found command end end
[ "def", "retrieve_command", "(", "command_to_run", ")", "if", "command_map", ".", "has_key?", "(", "command_to_run", ")", "command_map", "[", "command_to_run", "]", "else", "command", "=", "nil", "category_command_map", ".", "each", "do", "|", "category", ",", "commands", "|", "command", "=", "commands", "[", "command_to_run", "]", "if", "commands", ".", "has_key?", "(", "command_to_run", ")", "end", "# return the command, or nil if it wasn't found", "command", "end", "end" ]
retrieves the commmand from either the command_map or the category_command_map, if the command is not found return nil
[ "retrieves", "the", "commmand", "from", "either", "the", "command_map", "or", "the", "category_command_map", "if", "the", "command", "is", "not", "found", "return", "nil" ]
e160156deaa0afc037748b10d1c9ef0a5be97dc1
https://github.com/chef/omnibus-ctl/blob/e160156deaa0afc037748b10d1c9ef0a5be97dc1/lib/omnibus-ctl.rb#L672-L683
16,579
chef/omnibus-ctl
lib/omnibus-ctl.rb
Omnibus.Ctl.run
def run(args) # Ensure Omnibus related binaries are in the PATH ENV["PATH"] = [File.join(base_path, "bin"), File.join(base_path, "embedded","bin"), ENV['PATH']].join(":") command_to_run = args[0] ## when --help is run as the command itself, we need to strip off the ## `--` to ensure the command maps correctly. if command_to_run == "--help" command_to_run = "help" end # This piece of code checks if the argument is an option. If it is, # then it sets service to nil and adds the argument into the options # argument. This is ugly. A better solution is having a proper parser. # But if we are going to implement a proper parser, we might as well # port this to Thor rather than reinventing Thor. For now, this preserves # the behavior to complain and exit with an error if one attempts to invoke # a pcc command that does not accept an argument. Like "help". options = args[2..-1] || [] if is_option?(args[1]) options.unshift(args[1]) service = nil else service = args[1] end # returns either hash content of command or nil command = retrieve_command(command_to_run) if command.nil? log "I don't know that command." if args.length == 2 log "Did you mean: #{exe_name} #{service} #{command_to_run}?" end help Kernel.exit 1 end if args.length > 1 && command[:arity] != 2 log "The command #{command_to_run} does not accept any arguments" Kernel.exit 2 end parse_options options @force_exit = false exit_code = 0 run_global_pre_hooks # Filter args to just command and service. If you are loading # custom commands and need access to the command line argument, # use ARGV directly. actual_args = [command_to_run, service].reject(&:nil?) if command_pre_hook(*actual_args) method_to_call = to_method_name(command_to_run) begin ret = send(method_to_call, *actual_args) rescue SystemExit => e @force_exit = true ret = e.status end command_post_hook(*actual_args) exit_code = ret unless ret.nil? else exit_code = 8 @force_exit = true end if @force_exit Kernel.exit exit_code else exit_code end end
ruby
def run(args) # Ensure Omnibus related binaries are in the PATH ENV["PATH"] = [File.join(base_path, "bin"), File.join(base_path, "embedded","bin"), ENV['PATH']].join(":") command_to_run = args[0] ## when --help is run as the command itself, we need to strip off the ## `--` to ensure the command maps correctly. if command_to_run == "--help" command_to_run = "help" end # This piece of code checks if the argument is an option. If it is, # then it sets service to nil and adds the argument into the options # argument. This is ugly. A better solution is having a proper parser. # But if we are going to implement a proper parser, we might as well # port this to Thor rather than reinventing Thor. For now, this preserves # the behavior to complain and exit with an error if one attempts to invoke # a pcc command that does not accept an argument. Like "help". options = args[2..-1] || [] if is_option?(args[1]) options.unshift(args[1]) service = nil else service = args[1] end # returns either hash content of command or nil command = retrieve_command(command_to_run) if command.nil? log "I don't know that command." if args.length == 2 log "Did you mean: #{exe_name} #{service} #{command_to_run}?" end help Kernel.exit 1 end if args.length > 1 && command[:arity] != 2 log "The command #{command_to_run} does not accept any arguments" Kernel.exit 2 end parse_options options @force_exit = false exit_code = 0 run_global_pre_hooks # Filter args to just command and service. If you are loading # custom commands and need access to the command line argument, # use ARGV directly. actual_args = [command_to_run, service].reject(&:nil?) if command_pre_hook(*actual_args) method_to_call = to_method_name(command_to_run) begin ret = send(method_to_call, *actual_args) rescue SystemExit => e @force_exit = true ret = e.status end command_post_hook(*actual_args) exit_code = ret unless ret.nil? else exit_code = 8 @force_exit = true end if @force_exit Kernel.exit exit_code else exit_code end end
[ "def", "run", "(", "args", ")", "# Ensure Omnibus related binaries are in the PATH", "ENV", "[", "\"PATH\"", "]", "=", "[", "File", ".", "join", "(", "base_path", ",", "\"bin\"", ")", ",", "File", ".", "join", "(", "base_path", ",", "\"embedded\"", ",", "\"bin\"", ")", ",", "ENV", "[", "'PATH'", "]", "]", ".", "join", "(", "\":\"", ")", "command_to_run", "=", "args", "[", "0", "]", "## when --help is run as the command itself, we need to strip off the", "## `--` to ensure the command maps correctly.", "if", "command_to_run", "==", "\"--help\"", "command_to_run", "=", "\"help\"", "end", "# This piece of code checks if the argument is an option. If it is,", "# then it sets service to nil and adds the argument into the options", "# argument. This is ugly. A better solution is having a proper parser.", "# But if we are going to implement a proper parser, we might as well", "# port this to Thor rather than reinventing Thor. For now, this preserves", "# the behavior to complain and exit with an error if one attempts to invoke", "# a pcc command that does not accept an argument. Like \"help\".", "options", "=", "args", "[", "2", "..", "-", "1", "]", "||", "[", "]", "if", "is_option?", "(", "args", "[", "1", "]", ")", "options", ".", "unshift", "(", "args", "[", "1", "]", ")", "service", "=", "nil", "else", "service", "=", "args", "[", "1", "]", "end", "# returns either hash content of command or nil", "command", "=", "retrieve_command", "(", "command_to_run", ")", "if", "command", ".", "nil?", "log", "\"I don't know that command.\"", "if", "args", ".", "length", "==", "2", "log", "\"Did you mean: #{exe_name} #{service} #{command_to_run}?\"", "end", "help", "Kernel", ".", "exit", "1", "end", "if", "args", ".", "length", ">", "1", "&&", "command", "[", ":arity", "]", "!=", "2", "log", "\"The command #{command_to_run} does not accept any arguments\"", "Kernel", ".", "exit", "2", "end", "parse_options", "options", "@force_exit", "=", "false", "exit_code", "=", "0", "run_global_pre_hooks", "# Filter args to just command and service. If you are loading", "# custom commands and need access to the command line argument,", "# use ARGV directly.", "actual_args", "=", "[", "command_to_run", ",", "service", "]", ".", "reject", "(", ":nil?", ")", "if", "command_pre_hook", "(", "actual_args", ")", "method_to_call", "=", "to_method_name", "(", "command_to_run", ")", "begin", "ret", "=", "send", "(", "method_to_call", ",", "actual_args", ")", "rescue", "SystemExit", "=>", "e", "@force_exit", "=", "true", "ret", "=", "e", ".", "status", "end", "command_post_hook", "(", "actual_args", ")", "exit_code", "=", "ret", "unless", "ret", ".", "nil?", "else", "exit_code", "=", "8", "@force_exit", "=", "true", "end", "if", "@force_exit", "Kernel", ".", "exit", "exit_code", "else", "exit_code", "end", "end" ]
Previously this would exit immediately with the provided exit code; however this would prevent post-run hooks from continuing Instead, we'll just track whether a an exit was requested and use that to determine how we exit from 'run'
[ "Previously", "this", "would", "exit", "immediately", "with", "the", "provided", "exit", "code", ";", "however", "this", "would", "prevent", "post", "-", "run", "hooks", "from", "continuing", "Instead", "we", "ll", "just", "track", "whether", "a", "an", "exit", "was", "requested", "and", "use", "that", "to", "determine", "how", "we", "exit", "from", "run" ]
e160156deaa0afc037748b10d1c9ef0a5be97dc1
https://github.com/chef/omnibus-ctl/blob/e160156deaa0afc037748b10d1c9ef0a5be97dc1/lib/omnibus-ctl.rb#L689-L764
16,580
chef/omnibus-ctl
lib/omnibus-ctl.rb
Omnibus.Ctl.status_post_hook
def status_post_hook(service = nil) if service.nil? log_external_service_header external_services.each_key do |service_name| status = send(to_method_name("external_status_#{service_name}"), :sparse) log status end else # Request verbose status if the service is asked for by name. if service_external?(service) status = send(to_method_name("external_status_#{service}"), :verbose) log status end end end
ruby
def status_post_hook(service = nil) if service.nil? log_external_service_header external_services.each_key do |service_name| status = send(to_method_name("external_status_#{service_name}"), :sparse) log status end else # Request verbose status if the service is asked for by name. if service_external?(service) status = send(to_method_name("external_status_#{service}"), :verbose) log status end end end
[ "def", "status_post_hook", "(", "service", "=", "nil", ")", "if", "service", ".", "nil?", "log_external_service_header", "external_services", ".", "each_key", "do", "|", "service_name", "|", "status", "=", "send", "(", "to_method_name", "(", "\"external_status_#{service_name}\"", ")", ",", ":sparse", ")", "log", "status", "end", "else", "# Request verbose status if the service is asked for by name.", "if", "service_external?", "(", "service", ")", "status", "=", "send", "(", "to_method_name", "(", "\"external_status_#{service}\"", ")", ",", ":verbose", ")", "log", "status", "end", "end", "end" ]
Status gets its own hook because each externalized service will have its own things to do in order to report status. As above, we may also include an output header to show that we're reporting on external services. Your callback for this function should be in the form 'external_status_#{service_name}(detail_level) where detail_level is :sparse|:verbose :sparse is used when it's a summary service status list, eg "$appname-ctl status" :verbose is used when the specific service has been named, eg "$appname-ctl status postgresql"
[ "Status", "gets", "its", "own", "hook", "because", "each", "externalized", "service", "will", "have", "its", "own", "things", "to", "do", "in", "order", "to", "report", "status", ".", "As", "above", "we", "may", "also", "include", "an", "output", "header", "to", "show", "that", "we", "re", "reporting", "on", "external", "services", "." ]
e160156deaa0afc037748b10d1c9ef0a5be97dc1
https://github.com/chef/omnibus-ctl/blob/e160156deaa0afc037748b10d1c9ef0a5be97dc1/lib/omnibus-ctl.rb#L834-L848
16,581
algolia/algoliasearch-client-ruby
lib/algolia/client.rb
Algolia.Client.enable_rate_limit_forward
def enable_rate_limit_forward(admin_api_key, end_user_ip, rate_limit_api_key) headers[Protocol::HEADER_API_KEY] = admin_api_key headers[Protocol::HEADER_FORWARDED_IP] = end_user_ip headers[Protocol::HEADER_FORWARDED_API_KEY] = rate_limit_api_key end
ruby
def enable_rate_limit_forward(admin_api_key, end_user_ip, rate_limit_api_key) headers[Protocol::HEADER_API_KEY] = admin_api_key headers[Protocol::HEADER_FORWARDED_IP] = end_user_ip headers[Protocol::HEADER_FORWARDED_API_KEY] = rate_limit_api_key end
[ "def", "enable_rate_limit_forward", "(", "admin_api_key", ",", "end_user_ip", ",", "rate_limit_api_key", ")", "headers", "[", "Protocol", "::", "HEADER_API_KEY", "]", "=", "admin_api_key", "headers", "[", "Protocol", "::", "HEADER_FORWARDED_IP", "]", "=", "end_user_ip", "headers", "[", "Protocol", "::", "HEADER_FORWARDED_API_KEY", "]", "=", "rate_limit_api_key", "end" ]
Allow to use IP rate limit when you have a proxy between end-user and Algolia. This option will set the X-Forwarded-For HTTP header with the client IP and the X-Forwarded-API-Key with the API Key having rate limits. @param admin_api_key the admin API Key you can find in your dashboard @param end_user_ip the end user IP (you can use both IPV4 or IPV6 syntax) @param rate_limit_api_key the API key on which you have a rate limit
[ "Allow", "to", "use", "IP", "rate", "limit", "when", "you", "have", "a", "proxy", "between", "end", "-", "user", "and", "Algolia", ".", "This", "option", "will", "set", "the", "X", "-", "Forwarded", "-", "For", "HTTP", "header", "with", "the", "client", "IP", "and", "the", "X", "-", "Forwarded", "-", "API", "-", "Key", "with", "the", "API", "Key", "having", "rate", "limits", "." ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/client.rb#L85-L89
16,582
algolia/algoliasearch-client-ruby
lib/algolia/client.rb
Algolia.Client.multiple_queries
def multiple_queries(queries, options = nil, strategy = nil) if options.is_a?(Hash) index_name_key = options.delete(:index_name_key) || options.delete('index_name_key') strategy = options.delete(:strategy) || options.delete('strategy') request_options = options.delete(:request_options) || options.delete('request_options') else # Deprecated def multiple_queries(queries, index_name_key, strategy) index_name_key = options end index_name_key ||= :index_name strategy ||= 'none' request_options ||= {} requests = { :requests => queries.map do |query| query = query.dup index_name = query.delete(index_name_key) || query.delete(index_name_key.to_s) raise ArgumentError.new("Missing '#{index_name_key}' option") if index_name.nil? encoded_params = Hash[query.map { |k, v| [k.to_s, v.is_a?(Array) ? v.to_json : v] }] { :indexName => index_name, :params => Protocol.to_query(encoded_params) } end } post(Protocol.multiple_queries_uri(strategy), requests.to_json, :search, request_options) end
ruby
def multiple_queries(queries, options = nil, strategy = nil) if options.is_a?(Hash) index_name_key = options.delete(:index_name_key) || options.delete('index_name_key') strategy = options.delete(:strategy) || options.delete('strategy') request_options = options.delete(:request_options) || options.delete('request_options') else # Deprecated def multiple_queries(queries, index_name_key, strategy) index_name_key = options end index_name_key ||= :index_name strategy ||= 'none' request_options ||= {} requests = { :requests => queries.map do |query| query = query.dup index_name = query.delete(index_name_key) || query.delete(index_name_key.to_s) raise ArgumentError.new("Missing '#{index_name_key}' option") if index_name.nil? encoded_params = Hash[query.map { |k, v| [k.to_s, v.is_a?(Array) ? v.to_json : v] }] { :indexName => index_name, :params => Protocol.to_query(encoded_params) } end } post(Protocol.multiple_queries_uri(strategy), requests.to_json, :search, request_options) end
[ "def", "multiple_queries", "(", "queries", ",", "options", "=", "nil", ",", "strategy", "=", "nil", ")", "if", "options", ".", "is_a?", "(", "Hash", ")", "index_name_key", "=", "options", ".", "delete", "(", ":index_name_key", ")", "||", "options", ".", "delete", "(", "'index_name_key'", ")", "strategy", "=", "options", ".", "delete", "(", ":strategy", ")", "||", "options", ".", "delete", "(", "'strategy'", ")", "request_options", "=", "options", ".", "delete", "(", ":request_options", ")", "||", "options", ".", "delete", "(", "'request_options'", ")", "else", "# Deprecated def multiple_queries(queries, index_name_key, strategy)", "index_name_key", "=", "options", "end", "index_name_key", "||=", ":index_name", "strategy", "||=", "'none'", "request_options", "||=", "{", "}", "requests", "=", "{", ":requests", "=>", "queries", ".", "map", "do", "|", "query", "|", "query", "=", "query", ".", "dup", "index_name", "=", "query", ".", "delete", "(", "index_name_key", ")", "||", "query", ".", "delete", "(", "index_name_key", ".", "to_s", ")", "raise", "ArgumentError", ".", "new", "(", "\"Missing '#{index_name_key}' option\"", ")", "if", "index_name", ".", "nil?", "encoded_params", "=", "Hash", "[", "query", ".", "map", "{", "|", "k", ",", "v", "|", "[", "k", ".", "to_s", ",", "v", ".", "is_a?", "(", "Array", ")", "?", "v", ".", "to_json", ":", "v", "]", "}", "]", "{", ":indexName", "=>", "index_name", ",", ":params", "=>", "Protocol", ".", "to_query", "(", "encoded_params", ")", "}", "end", "}", "post", "(", "Protocol", ".", "multiple_queries_uri", "(", "strategy", ")", ",", "requests", ".", "to_json", ",", ":search", ",", "request_options", ")", "end" ]
This method allows to query multiple indexes with one API call @param queries the array of hash representing the query and associated index name @param options - accepts those keys: - index_name_key the name of the key used to fetch the index_name (:index_name by default) - strategy define the strategy applied on the sequential searches (none by default) - request_options contains extra parameters to send with your query
[ "This", "method", "allows", "to", "query", "multiple", "indexes", "with", "one", "API", "call" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/client.rb#L121-L144
16,583
algolia/algoliasearch-client-ruby
lib/algolia/client.rb
Algolia.Client.move_index
def move_index(src_index, dst_index, request_options = {}) request = { 'operation' => 'move', 'destination' => dst_index } post(Protocol.index_operation_uri(src_index), request.to_json, :write, request_options) end
ruby
def move_index(src_index, dst_index, request_options = {}) request = { 'operation' => 'move', 'destination' => dst_index } post(Protocol.index_operation_uri(src_index), request.to_json, :write, request_options) end
[ "def", "move_index", "(", "src_index", ",", "dst_index", ",", "request_options", "=", "{", "}", ")", "request", "=", "{", "'operation'", "=>", "'move'", ",", "'destination'", "=>", "dst_index", "}", "post", "(", "Protocol", ".", "index_operation_uri", "(", "src_index", ")", ",", "request", ".", "to_json", ",", ":write", ",", "request_options", ")", "end" ]
Move an existing index. @param src_index the name of index to copy. @param dst_index the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist). @param request_options contains extra parameters to send with your query
[ "Move", "an", "existing", "index", "." ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/client.rb#L177-L180
16,584
algolia/algoliasearch-client-ruby
lib/algolia/client.rb
Algolia.Client.move_index!
def move_index!(src_index, dst_index, request_options = {}) res = move_index(src_index, dst_index, request_options) wait_task(dst_index, res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
ruby
def move_index!(src_index, dst_index, request_options = {}) res = move_index(src_index, dst_index, request_options) wait_task(dst_index, res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
[ "def", "move_index!", "(", "src_index", ",", "dst_index", ",", "request_options", "=", "{", "}", ")", "res", "=", "move_index", "(", "src_index", ",", "dst_index", ",", "request_options", ")", "wait_task", "(", "dst_index", ",", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "res", "end" ]
Move an existing index and wait until the move has been processed @param src_index the name of index to copy. @param dst_index the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist). @param request_options contains extra parameters to send with your query
[ "Move", "an", "existing", "index", "and", "wait", "until", "the", "move", "has", "been", "processed" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/client.rb#L189-L193
16,585
algolia/algoliasearch-client-ruby
lib/algolia/client.rb
Algolia.Client.copy_index
def copy_index(src_index, dst_index, scope = nil, request_options = {}) request = { 'operation' => 'copy', 'destination' => dst_index } request['scope'] = scope unless scope.nil? post(Protocol.index_operation_uri(src_index), request.to_json, :write, request_options) end
ruby
def copy_index(src_index, dst_index, scope = nil, request_options = {}) request = { 'operation' => 'copy', 'destination' => dst_index } request['scope'] = scope unless scope.nil? post(Protocol.index_operation_uri(src_index), request.to_json, :write, request_options) end
[ "def", "copy_index", "(", "src_index", ",", "dst_index", ",", "scope", "=", "nil", ",", "request_options", "=", "{", "}", ")", "request", "=", "{", "'operation'", "=>", "'copy'", ",", "'destination'", "=>", "dst_index", "}", "request", "[", "'scope'", "]", "=", "scope", "unless", "scope", ".", "nil?", "post", "(", "Protocol", ".", "index_operation_uri", "(", "src_index", ")", ",", "request", ".", "to_json", ",", ":write", ",", "request_options", ")", "end" ]
Copy an existing index. @param src_index the name of index to copy. @param dst_index the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist). @param scope the optional list of scopes to copy (all if not specified). @param request_options contains extra parameters to send with your query
[ "Copy", "an", "existing", "index", "." ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/client.rb#L203-L207
16,586
algolia/algoliasearch-client-ruby
lib/algolia/client.rb
Algolia.Client.copy_index!
def copy_index!(src_index, dst_index, scope = nil, request_options = {}) res = copy_index(src_index, dst_index, scope, request_options) wait_task(dst_index, res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
ruby
def copy_index!(src_index, dst_index, scope = nil, request_options = {}) res = copy_index(src_index, dst_index, scope, request_options) wait_task(dst_index, res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
[ "def", "copy_index!", "(", "src_index", ",", "dst_index", ",", "scope", "=", "nil", ",", "request_options", "=", "{", "}", ")", "res", "=", "copy_index", "(", "src_index", ",", "dst_index", ",", "scope", ",", "request_options", ")", "wait_task", "(", "dst_index", ",", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "res", "end" ]
Copy an existing index and wait until the copy has been processed. @param src_index the name of index to copy. @param dst_index the new index name that will contains a copy of srcIndexName (destination will be overriten if it already exist). @param scope the optional list of scopes to copy (all if not specified). @param request_options contains extra parameters to send with your query
[ "Copy", "an", "existing", "index", "and", "wait", "until", "the", "copy", "has", "been", "processed", "." ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/client.rb#L217-L221
16,587
algolia/algoliasearch-client-ruby
lib/algolia/client.rb
Algolia.Client.copy_settings!
def copy_settings!(src_index, dst_index, request_options = {}) res = copy_settings(src_index, dst_index, request_options) wait_task(dst_index, res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
ruby
def copy_settings!(src_index, dst_index, request_options = {}) res = copy_settings(src_index, dst_index, request_options) wait_task(dst_index, res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
[ "def", "copy_settings!", "(", "src_index", ",", "dst_index", ",", "request_options", "=", "{", "}", ")", "res", "=", "copy_settings", "(", "src_index", ",", "dst_index", ",", "request_options", ")", "wait_task", "(", "dst_index", ",", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "res", "end" ]
Copy an existing index settings and wait until the copy has been processed. @param src_index the name of index to copy. @param dst_index the new index name that will contains a copy of srcIndexName settings (destination settings will be overriten if it already exist). @param request_options contains extra parameters to send with your query
[ "Copy", "an", "existing", "index", "settings", "and", "wait", "until", "the", "copy", "has", "been", "processed", "." ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/client.rb#L241-L245
16,588
algolia/algoliasearch-client-ruby
lib/algolia/client.rb
Algolia.Client.copy_synonyms!
def copy_synonyms!(src_index, dst_index, request_options = {}) res = copy_synonyms(src_index, dst_index, request_options) wait_task(dst_index, res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
ruby
def copy_synonyms!(src_index, dst_index, request_options = {}) res = copy_synonyms(src_index, dst_index, request_options) wait_task(dst_index, res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
[ "def", "copy_synonyms!", "(", "src_index", ",", "dst_index", ",", "request_options", "=", "{", "}", ")", "res", "=", "copy_synonyms", "(", "src_index", ",", "dst_index", ",", "request_options", ")", "wait_task", "(", "dst_index", ",", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "res", "end" ]
Copy an existing index synonyms and wait until the copy has been processed. @param src_index the name of index to copy. @param dst_index the new index name that will contains a copy of srcIndexName synonyms (destination synonyms will be overriten if it already exist). @param request_options contains extra parameters to send with your query
[ "Copy", "an", "existing", "index", "synonyms", "and", "wait", "until", "the", "copy", "has", "been", "processed", "." ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/client.rb#L265-L269
16,589
algolia/algoliasearch-client-ruby
lib/algolia/client.rb
Algolia.Client.copy_rules!
def copy_rules!(src_index, dst_index, request_options = {}) res = copy_rules(src_index, dst_index, request_options) wait_task(dst_index, res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
ruby
def copy_rules!(src_index, dst_index, request_options = {}) res = copy_rules(src_index, dst_index, request_options) wait_task(dst_index, res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
[ "def", "copy_rules!", "(", "src_index", ",", "dst_index", ",", "request_options", "=", "{", "}", ")", "res", "=", "copy_rules", "(", "src_index", ",", "dst_index", ",", "request_options", ")", "wait_task", "(", "dst_index", ",", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "res", "end" ]
Copy an existing index rules and wait until the copy has been processed. @param src_index the name of index to copy. @param dst_index the new index name that will contains a copy of srcIndexName rules (destination rules will be overriten if it already exist). @param request_options contains extra parameters to send with your query
[ "Copy", "an", "existing", "index", "rules", "and", "wait", "until", "the", "copy", "has", "been", "processed", "." ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/client.rb#L289-L293
16,590
algolia/algoliasearch-client-ruby
lib/algolia/client.rb
Algolia.Client.get_logs
def get_logs(options = nil, length = nil, type = nil) if options.is_a?(Hash) offset = options.delete('offset') || options.delete(:offset) length = options.delete('length') || options.delete(:length) type = options.delete('type') || options.delete(:type) request_options = options.delete('request_options') || options.delete(:request_options) else # Deprecated def get_logs(offset, length, type) offset = options end length ||= 10 type = 'all' if type.nil? type = type ? 'error' : 'all' if type.is_a?(true.class) request_options ||= {} get(Protocol.logs(offset, length, type), :write, request_options) end
ruby
def get_logs(options = nil, length = nil, type = nil) if options.is_a?(Hash) offset = options.delete('offset') || options.delete(:offset) length = options.delete('length') || options.delete(:length) type = options.delete('type') || options.delete(:type) request_options = options.delete('request_options') || options.delete(:request_options) else # Deprecated def get_logs(offset, length, type) offset = options end length ||= 10 type = 'all' if type.nil? type = type ? 'error' : 'all' if type.is_a?(true.class) request_options ||= {} get(Protocol.logs(offset, length, type), :write, request_options) end
[ "def", "get_logs", "(", "options", "=", "nil", ",", "length", "=", "nil", ",", "type", "=", "nil", ")", "if", "options", ".", "is_a?", "(", "Hash", ")", "offset", "=", "options", ".", "delete", "(", "'offset'", ")", "||", "options", ".", "delete", "(", ":offset", ")", "length", "=", "options", ".", "delete", "(", "'length'", ")", "||", "options", ".", "delete", "(", ":length", ")", "type", "=", "options", ".", "delete", "(", "'type'", ")", "||", "options", ".", "delete", "(", ":type", ")", "request_options", "=", "options", ".", "delete", "(", "'request_options'", ")", "||", "options", ".", "delete", "(", ":request_options", ")", "else", "# Deprecated def get_logs(offset, length, type)", "offset", "=", "options", "end", "length", "||=", "10", "type", "=", "'all'", "if", "type", ".", "nil?", "type", "=", "type", "?", "'error'", ":", "'all'", "if", "type", ".", "is_a?", "(", "true", ".", "class", ")", "request_options", "||=", "{", "}", "get", "(", "Protocol", ".", "logs", "(", "offset", ",", "length", ",", "type", ")", ",", ":write", ",", "request_options", ")", "end" ]
Return last logs entries. @param options - accepts those keys: - offset Specify the first entry to retrieve (0-based, 0 is the most recent log entry) - Default = 0 - length Specify the maximum number of entries to retrieve starting at offset. Maximum allowed value: 1000 - Default = 10 - type Type of log entries to retrieve ("all", "query", "build" or "error") - Default = 'all' - request_options contains extra parameters to send with your query
[ "Return", "last", "logs", "entries", "." ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/client.rb#L322-L338
16,591
algolia/algoliasearch-client-ruby
lib/algolia/client.rb
Algolia.Client.batch!
def batch!(operations, request_options = {}) res = batch(operations, request_options) res['taskID'].each do |index, taskID| wait_task(index, taskID, WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) end end
ruby
def batch!(operations, request_options = {}) res = batch(operations, request_options) res['taskID'].each do |index, taskID| wait_task(index, taskID, WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) end end
[ "def", "batch!", "(", "operations", ",", "request_options", "=", "{", "}", ")", "res", "=", "batch", "(", "operations", ",", "request_options", ")", "res", "[", "'taskID'", "]", ".", "each", "do", "|", "index", ",", "taskID", "|", "wait_task", "(", "index", ",", "taskID", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "end", "end" ]
Send a batch request targeting multiple indices and wait the end of the indexing
[ "Send", "a", "batch", "request", "targeting", "multiple", "indices", "and", "wait", "the", "end", "of", "the", "indexing" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/client.rb#L475-L480
16,592
algolia/algoliasearch-client-ruby
lib/algolia/client.rb
Algolia.Client.get_task_status
def get_task_status(index_name, taskID, request_options = {}) get(Protocol.task_uri(index_name, taskID), :read, request_options)['status'] end
ruby
def get_task_status(index_name, taskID, request_options = {}) get(Protocol.task_uri(index_name, taskID), :read, request_options)['status'] end
[ "def", "get_task_status", "(", "index_name", ",", "taskID", ",", "request_options", "=", "{", "}", ")", "get", "(", "Protocol", ".", "task_uri", "(", "index_name", ",", "taskID", ")", ",", ":read", ",", "request_options", ")", "[", "'status'", "]", "end" ]
Check the status of a task on the server. All server task are asynchronous and you can check the status of a task with this method. @param index_name the index name owning the taskID @param taskID the id of the task returned by server @param request_options contains extra parameters to send with your query
[ "Check", "the", "status", "of", "a", "task", "on", "the", "server", ".", "All", "server", "task", "are", "asynchronous", "and", "you", "can", "check", "the", "status", "of", "a", "task", "with", "this", "method", "." ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/client.rb#L490-L492
16,593
algolia/algoliasearch-client-ruby
lib/algolia/client.rb
Algolia.Client.request
def request(uri, method, data = nil, type = :write, request_options = {}) exceptions = [] connect_timeout = @connect_timeout send_timeout = if type == :search @search_timeout elsif type == :batch type = :write @batch_timeout else @send_timeout end receive_timeout = type == :search ? @search_timeout : @receive_timeout thread_local_hosts(type != :write).each_with_index do |host, i| connect_timeout += 2 if i == 2 send_timeout += 10 if i == 2 receive_timeout += 10 if i == 2 thread_index_key = type != :write ? "algolia_search_host_index_#{application_id}" : "algolia_host_index_#{application_id}" Thread.current[thread_index_key] = host[:index] host[:last_call] = Time.now.to_i host[:session].connect_timeout = connect_timeout host[:session].send_timeout = send_timeout host[:session].receive_timeout = receive_timeout begin return perform_request(host[:session], host[:base_url] + uri, method, data, request_options) rescue AlgoliaProtocolError => e raise if e.code / 100 == 4 exceptions << e rescue => e exceptions << e end host[:session].reset_all end raise AlgoliaProtocolError.new(0, "Cannot reach any host: #{exceptions.map { |e| e.to_s }.join(', ')}") end
ruby
def request(uri, method, data = nil, type = :write, request_options = {}) exceptions = [] connect_timeout = @connect_timeout send_timeout = if type == :search @search_timeout elsif type == :batch type = :write @batch_timeout else @send_timeout end receive_timeout = type == :search ? @search_timeout : @receive_timeout thread_local_hosts(type != :write).each_with_index do |host, i| connect_timeout += 2 if i == 2 send_timeout += 10 if i == 2 receive_timeout += 10 if i == 2 thread_index_key = type != :write ? "algolia_search_host_index_#{application_id}" : "algolia_host_index_#{application_id}" Thread.current[thread_index_key] = host[:index] host[:last_call] = Time.now.to_i host[:session].connect_timeout = connect_timeout host[:session].send_timeout = send_timeout host[:session].receive_timeout = receive_timeout begin return perform_request(host[:session], host[:base_url] + uri, method, data, request_options) rescue AlgoliaProtocolError => e raise if e.code / 100 == 4 exceptions << e rescue => e exceptions << e end host[:session].reset_all end raise AlgoliaProtocolError.new(0, "Cannot reach any host: #{exceptions.map { |e| e.to_s }.join(', ')}") end
[ "def", "request", "(", "uri", ",", "method", ",", "data", "=", "nil", ",", "type", "=", ":write", ",", "request_options", "=", "{", "}", ")", "exceptions", "=", "[", "]", "connect_timeout", "=", "@connect_timeout", "send_timeout", "=", "if", "type", "==", ":search", "@search_timeout", "elsif", "type", "==", ":batch", "type", "=", ":write", "@batch_timeout", "else", "@send_timeout", "end", "receive_timeout", "=", "type", "==", ":search", "?", "@search_timeout", ":", "@receive_timeout", "thread_local_hosts", "(", "type", "!=", ":write", ")", ".", "each_with_index", "do", "|", "host", ",", "i", "|", "connect_timeout", "+=", "2", "if", "i", "==", "2", "send_timeout", "+=", "10", "if", "i", "==", "2", "receive_timeout", "+=", "10", "if", "i", "==", "2", "thread_index_key", "=", "type", "!=", ":write", "?", "\"algolia_search_host_index_#{application_id}\"", ":", "\"algolia_host_index_#{application_id}\"", "Thread", ".", "current", "[", "thread_index_key", "]", "=", "host", "[", ":index", "]", "host", "[", ":last_call", "]", "=", "Time", ".", "now", ".", "to_i", "host", "[", ":session", "]", ".", "connect_timeout", "=", "connect_timeout", "host", "[", ":session", "]", ".", "send_timeout", "=", "send_timeout", "host", "[", ":session", "]", ".", "receive_timeout", "=", "receive_timeout", "begin", "return", "perform_request", "(", "host", "[", ":session", "]", ",", "host", "[", ":base_url", "]", "+", "uri", ",", "method", ",", "data", ",", "request_options", ")", "rescue", "AlgoliaProtocolError", "=>", "e", "raise", "if", "e", ".", "code", "/", "100", "==", "4", "exceptions", "<<", "e", "rescue", "=>", "e", "exceptions", "<<", "e", "end", "host", "[", ":session", "]", ".", "reset_all", "end", "raise", "AlgoliaProtocolError", ".", "new", "(", "0", ",", "\"Cannot reach any host: #{exceptions.map { |e| e.to_s }.join(', ')}\"", ")", "end" ]
Perform an HTTP request for the given uri and method with common basic response handling. Will raise a AlgoliaProtocolError if the response has an error status code, and will return the parsed JSON body on success, if there is one.
[ "Perform", "an", "HTTP", "request", "for", "the", "given", "uri", "and", "method", "with", "common", "basic", "response", "handling", ".", "Will", "raise", "a", "AlgoliaProtocolError", "if", "the", "response", "has", "an", "error", "status", "code", "and", "will", "return", "the", "parsed", "JSON", "body", "on", "success", "if", "there", "is", "one", "." ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/client.rb#L566-L603
16,594
algolia/algoliasearch-client-ruby
lib/algolia/client.rb
Algolia.Client.thread_local_hosts
def thread_local_hosts(read) thread_hosts_key = read ? "algolia_search_hosts_#{application_id}" : "algolia_hosts_#{application_id}" Thread.current[thread_hosts_key] ||= (read ? search_hosts : hosts).each_with_index.map do |host, i| client = HTTPClient.new client.ssl_config.ssl_version = @ssl_version if @ssl && @ssl_version client.transparent_gzip_decompression = @gzip client.ssl_config.add_trust_ca File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'resources', 'ca-bundle.crt')) { :index => i, :base_url => "http#{@ssl ? 's' : ''}://#{host}", :session => client, :last_call => nil } end hosts = Thread.current[thread_hosts_key] thread_index_key = read ? "algolia_search_host_index_#{application_id}" : "algolia_host_index_#{application_id}" current_host = Thread.current[thread_index_key].to_i # `to_i` to ensure first call is 0 # we want to always target host 0 first # if the current host is not 0, then we want to use it first only if (we never used it OR we're using it since less than 1 minute) if current_host != 0 && (hosts[current_host][:last_call].nil? || hosts[current_host][:last_call] > Time.now.to_i - 60) # first host will be `current_host` first = hosts[current_host] [first] + hosts.reject { |h| h[:index] == 0 || h == first } + hosts.select { |h| h[:index] == 0 } else # first host will be `0` hosts end end
ruby
def thread_local_hosts(read) thread_hosts_key = read ? "algolia_search_hosts_#{application_id}" : "algolia_hosts_#{application_id}" Thread.current[thread_hosts_key] ||= (read ? search_hosts : hosts).each_with_index.map do |host, i| client = HTTPClient.new client.ssl_config.ssl_version = @ssl_version if @ssl && @ssl_version client.transparent_gzip_decompression = @gzip client.ssl_config.add_trust_ca File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'resources', 'ca-bundle.crt')) { :index => i, :base_url => "http#{@ssl ? 's' : ''}://#{host}", :session => client, :last_call => nil } end hosts = Thread.current[thread_hosts_key] thread_index_key = read ? "algolia_search_host_index_#{application_id}" : "algolia_host_index_#{application_id}" current_host = Thread.current[thread_index_key].to_i # `to_i` to ensure first call is 0 # we want to always target host 0 first # if the current host is not 0, then we want to use it first only if (we never used it OR we're using it since less than 1 minute) if current_host != 0 && (hosts[current_host][:last_call].nil? || hosts[current_host][:last_call] > Time.now.to_i - 60) # first host will be `current_host` first = hosts[current_host] [first] + hosts.reject { |h| h[:index] == 0 || h == first } + hosts.select { |h| h[:index] == 0 } else # first host will be `0` hosts end end
[ "def", "thread_local_hosts", "(", "read", ")", "thread_hosts_key", "=", "read", "?", "\"algolia_search_hosts_#{application_id}\"", ":", "\"algolia_hosts_#{application_id}\"", "Thread", ".", "current", "[", "thread_hosts_key", "]", "||=", "(", "read", "?", "search_hosts", ":", "hosts", ")", ".", "each_with_index", ".", "map", "do", "|", "host", ",", "i", "|", "client", "=", "HTTPClient", ".", "new", "client", ".", "ssl_config", ".", "ssl_version", "=", "@ssl_version", "if", "@ssl", "&&", "@ssl_version", "client", ".", "transparent_gzip_decompression", "=", "@gzip", "client", ".", "ssl_config", ".", "add_trust_ca", "File", ".", "expand_path", "(", "File", ".", "join", "(", "File", ".", "dirname", "(", "__FILE__", ")", ",", "'..'", ",", "'..'", ",", "'resources'", ",", "'ca-bundle.crt'", ")", ")", "{", ":index", "=>", "i", ",", ":base_url", "=>", "\"http#{@ssl ? 's' : ''}://#{host}\"", ",", ":session", "=>", "client", ",", ":last_call", "=>", "nil", "}", "end", "hosts", "=", "Thread", ".", "current", "[", "thread_hosts_key", "]", "thread_index_key", "=", "read", "?", "\"algolia_search_host_index_#{application_id}\"", ":", "\"algolia_host_index_#{application_id}\"", "current_host", "=", "Thread", ".", "current", "[", "thread_index_key", "]", ".", "to_i", "# `to_i` to ensure first call is 0", "# we want to always target host 0 first", "# if the current host is not 0, then we want to use it first only if (we never used it OR we're using it since less than 1 minute)", "if", "current_host", "!=", "0", "&&", "(", "hosts", "[", "current_host", "]", "[", ":last_call", "]", ".", "nil?", "||", "hosts", "[", "current_host", "]", "[", ":last_call", "]", ">", "Time", ".", "now", ".", "to_i", "-", "60", ")", "# first host will be `current_host`", "first", "=", "hosts", "[", "current_host", "]", "[", "first", "]", "+", "hosts", ".", "reject", "{", "|", "h", "|", "h", "[", ":index", "]", "==", "0", "||", "h", "==", "first", "}", "+", "hosts", ".", "select", "{", "|", "h", "|", "h", "[", ":index", "]", "==", "0", "}", "else", "# first host will be `0`", "hosts", "end", "end" ]
This method returns a thread-local array of sessions
[ "This", "method", "returns", "a", "thread", "-", "local", "array", "of", "sessions" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/client.rb#L626-L653
16,595
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.delete!
def delete!(request_options = {}) res = delete(request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
ruby
def delete!(request_options = {}) res = delete(request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
[ "def", "delete!", "(", "request_options", "=", "{", "}", ")", "res", "=", "delete", "(", "request_options", ")", "wait_task", "(", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "res", "end" ]
Delete an index and wait until the deletion has been processed @param request_options contains extra parameters to send with your query return an hash of the form { "deletedAt" => "2013-01-18T15:33:13.556Z", "taskID" => "42" }
[ "Delete", "an", "index", "and", "wait", "until", "the", "deletion", "has", "been", "processed" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L33-L37
16,596
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.add_object
def add_object(object, objectID = nil, request_options = {}) check_object(object) if objectID.nil? || objectID.to_s.empty? client.post(Protocol.index_uri(name), object.to_json, :write, request_options) else client.put(Protocol.object_uri(name, objectID), object.to_json, :write, request_options) end end
ruby
def add_object(object, objectID = nil, request_options = {}) check_object(object) if objectID.nil? || objectID.to_s.empty? client.post(Protocol.index_uri(name), object.to_json, :write, request_options) else client.put(Protocol.object_uri(name, objectID), object.to_json, :write, request_options) end end
[ "def", "add_object", "(", "object", ",", "objectID", "=", "nil", ",", "request_options", "=", "{", "}", ")", "check_object", "(", "object", ")", "if", "objectID", ".", "nil?", "||", "objectID", ".", "to_s", ".", "empty?", "client", ".", "post", "(", "Protocol", ".", "index_uri", "(", "name", ")", ",", "object", ".", "to_json", ",", ":write", ",", "request_options", ")", "else", "client", ".", "put", "(", "Protocol", ".", "object_uri", "(", "name", ",", "objectID", ")", ",", "object", ".", "to_json", ",", ":write", ",", "request_options", ")", "end", "end" ]
Add an object in this index @param object the object to add to the index. The object is represented by an associative array @param objectID (optional) an objectID you want to attribute to this object (if the attribute already exist the old object will be overridden) @param request_options contains extra parameters to send with your query
[ "Add", "an", "object", "in", "this", "index" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L49-L56
16,597
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.add_object!
def add_object!(object, objectID = nil, request_options = {}) res = add_object(object, objectID, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
ruby
def add_object!(object, objectID = nil, request_options = {}) res = add_object(object, objectID, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
[ "def", "add_object!", "(", "object", ",", "objectID", "=", "nil", ",", "request_options", "=", "{", "}", ")", "res", "=", "add_object", "(", "object", ",", "objectID", ",", "request_options", ")", "wait_task", "(", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "res", "end" ]
Add an object in this index and wait end of indexing @param object the object to add to the index. The object is represented by an associative array @param objectID (optional) an objectID you want to attribute to this object (if the attribute already exist the old object will be overridden) @param Request options object. Contains extra URL parameters or headers
[ "Add", "an", "object", "in", "this", "index", "and", "wait", "end", "of", "indexing" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L67-L71
16,598
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.add_objects!
def add_objects!(objects, request_options = {}) res = add_objects(objects, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
ruby
def add_objects!(objects, request_options = {}) res = add_objects(objects, request_options) wait_task(res['taskID'], WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY, request_options) res end
[ "def", "add_objects!", "(", "objects", ",", "request_options", "=", "{", "}", ")", "res", "=", "add_objects", "(", "objects", ",", "request_options", ")", "wait_task", "(", "res", "[", "'taskID'", "]", ",", "WAIT_TASK_DEFAULT_TIME_BEFORE_RETRY", ",", "request_options", ")", "res", "end" ]
Add several objects in this index and wait end of indexing @param objects the array of objects to add inside the index. Each object is represented by an associative array @param request_options contains extra parameters to send with your query
[ "Add", "several", "objects", "in", "this", "index", "and", "wait", "end", "of", "indexing" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L91-L95
16,599
algolia/algoliasearch-client-ruby
lib/algolia/index.rb
Algolia.Index.search
def search(query, params = {}, request_options = {}) encoded_params = Hash[params.map { |k, v| [k.to_s, v.is_a?(Array) ? v.to_json : v] }] encoded_params[:query] = query client.post(Protocol.search_post_uri(name), { :params => Protocol.to_query(encoded_params) }.to_json, :search, request_options) end
ruby
def search(query, params = {}, request_options = {}) encoded_params = Hash[params.map { |k, v| [k.to_s, v.is_a?(Array) ? v.to_json : v] }] encoded_params[:query] = query client.post(Protocol.search_post_uri(name), { :params => Protocol.to_query(encoded_params) }.to_json, :search, request_options) end
[ "def", "search", "(", "query", ",", "params", "=", "{", "}", ",", "request_options", "=", "{", "}", ")", "encoded_params", "=", "Hash", "[", "params", ".", "map", "{", "|", "k", ",", "v", "|", "[", "k", ".", "to_s", ",", "v", ".", "is_a?", "(", "Array", ")", "?", "v", ".", "to_json", ":", "v", "]", "}", "]", "encoded_params", "[", ":query", "]", "=", "query", "client", ".", "post", "(", "Protocol", ".", "search_post_uri", "(", "name", ")", ",", "{", ":params", "=>", "Protocol", ".", "to_query", "(", "encoded_params", ")", "}", ".", "to_json", ",", ":search", ",", "request_options", ")", "end" ]
Search inside the index @param query the full text query @param args (optional) if set, contains an associative array with query parameters: - page: (integer) Pagination parameter used to select the page to retrieve. Page is zero-based and defaults to 0. Thus, to retrieve the 10th page you need to set page=9 - hitsPerPage: (integer) Pagination parameter used to select the number of hits per page. Defaults to 20. - attributesToRetrieve: a string that contains the list of object attributes you want to retrieve (let you minimize the answer size). Attributes are separated with a comma (for example "name,address"). You can also use a string array encoding (for example ["name","address"]). By default, all attributes are retrieved. You can also use '*' to retrieve all values when an attributesToRetrieve setting is specified for your index. - attributesToHighlight: a string that contains the list of attributes you want to highlight according to the query. Attributes are separated by a comma. You can also use a string array encoding (for example ["name","address"]). If an attribute has no match for the query, the raw value is returned. By default all indexed text attributes are highlighted. You can use `*` if you want to highlight all textual attributes. Numerical attributes are not highlighted. A matchLevel is returned for each highlighted attribute and can contain: - full: if all the query terms were found in the attribute, - partial: if only some of the query terms were found, - none: if none of the query terms were found. - attributesToSnippet: a string that contains the list of attributes to snippet alongside the number of words to return (syntax is `attributeName:nbWords`). Attributes are separated by a comma (Example: attributesToSnippet=name:10,content:10). You can also use a string array encoding (Example: attributesToSnippet: ["name:10","content:10"]). By default no snippet is computed. - minWordSizefor1Typo: the minimum number of characters in a query word to accept one typo in this word. Defaults to 3. - minWordSizefor2Typos: the minimum number of characters in a query word to accept two typos in this word. Defaults to 7. - getRankingInfo: if set to 1, the result hits will contain ranking information in _rankingInfo attribute. - aroundLatLng: search for entries around a given latitude/longitude (specified as two floats separated by a comma). For example aroundLatLng=47.316669,5.016670). You can specify the maximum distance in meters with the aroundRadius parameter (in meters) and the precision for ranking with aroundPrecision (for example if you set aroundPrecision=100, two objects that are distant of less than 100m will be considered as identical for "geo" ranking parameter). At indexing, you should specify geoloc of an object with the _geoloc attribute (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) - insideBoundingBox: search entries inside a given area defined by the two extreme points of a rectangle (defined by 4 floats: p1Lat,p1Lng,p2Lat,p2Lng). For example insideBoundingBox=47.3165,4.9665,47.3424,5.0201). At indexing, you should specify geoloc of an object with the _geoloc attribute (in the form {"_geoloc":{"lat":48.853409, "lng":2.348800}}) - numericFilters: a string that contains the list of numeric filters you want to apply separated by a comma. The syntax of one filter is `attributeName` followed by `operand` followed by `value`. Supported operands are `<`, `<=`, `=`, `>` and `>=`. You can have multiple conditions on one attribute like for example numericFilters=price>100,price<1000. You can also use a string array encoding (for example numericFilters: ["price>100","price<1000"]). - tagFilters: filter the query by a set of tags. You can AND tags by separating them by commas. To OR tags, you must add parentheses. For example, tags=tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3). You can also use a string array encoding, for example tagFilters: ["tag1",["tag2","tag3"]] means tag1 AND (tag2 OR tag3). At indexing, tags should be added in the _tags** attribute of objects (for example {"_tags":["tag1","tag2"]}). - facetFilters: filter the query by a list of facets. Facets are separated by commas and each facet is encoded as `attributeName:value`. For example: `facetFilters=category:Book,author:John%20Doe`. You can also use a string array encoding (for example `["category:Book","author:John%20Doe"]`). - facets: List of object attributes that you want to use for faceting. Attributes are separated with a comma (for example `"category,author"` ). You can also use a JSON string array encoding (for example ["category","author"]). Only attributes that have been added in **attributesForFaceting** index setting can be used in this parameter. You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**. - queryType: select how the query words are interpreted, it can be one of the following value: - prefixAll: all query words are interpreted as prefixes, - prefixLast: only the last word is interpreted as a prefix (default behavior), - prefixNone: no query word is interpreted as a prefix. This option is not recommended. - optionalWords: a string that contains the list of words that should be considered as optional when found in the query. The list of words is comma separated. - distinct: If set to 1, enable the distinct feature (disabled by default) if the attributeForDistinct index setting is set. This feature is similar to the SQL "distinct" keyword: when enabled in a query with the distinct=1 parameter, all hits containing a duplicate value for the attributeForDistinct attribute are removed from results. For example, if the chosen attribute is show_name and several hits have the same value for show_name, then only the best one is kept and others are removed. @param request_options contains extra parameters to send with your query
[ "Search", "inside", "the", "index" ]
5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b
https://github.com/algolia/algoliasearch-client-ruby/blob/5292cd9b1029f879e4e0257a3e89d0dc9ad0df3b/lib/algolia/index.rb#L161-L165