repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
infinitered/rmq | motion/ruby_motion_query/subviews.rb | RubyMotionQuery.RMQ.unshift | def unshift(view_or_constant, style=nil, opts = {}, &block)
opts[:at_index] = 0
opts[:style] = style
opts[:block] = block if block
add_subview view_or_constant, opts
end | ruby | def unshift(view_or_constant, style=nil, opts = {}, &block)
opts[:at_index] = 0
opts[:style] = style
opts[:block] = block if block
add_subview view_or_constant, opts
end | [
"def",
"unshift",
"(",
"view_or_constant",
",",
"style",
"=",
"nil",
",",
"opts",
"=",
"{",
"}",
",",
"&",
"block",
")",
"opts",
"[",
":at_index",
"]",
"=",
"0",
"opts",
"[",
":style",
"]",
"=",
"style",
"opts",
"[",
":block",
"]",
"=",
"block",
"if",
"block",
"add_subview",
"view_or_constant",
",",
"opts",
"end"
]
| Just like append, but inserts the view at index 0 of the subview array
@return [RMQ] | [
"Just",
"like",
"append",
"but",
"inserts",
"the",
"view",
"at",
"index",
"0",
"of",
"the",
"subview",
"array"
]
| a8329e1574ce3275c9fe56b91127c8b5e4b7693e | https://github.com/infinitered/rmq/blob/a8329e1574ce3275c9fe56b91127c8b5e4b7693e/motion/ruby_motion_query/subviews.rb#L141-L146 | train |
infinitered/rmq | motion/ruby_motion_query/subviews.rb | RubyMotionQuery.RMQ.build | def build(view, style = nil, opts = {}, &block)
opts[:do_not_add] = true
opts[:style] = style
opts[:block] = block if block
add_subview view, opts
end | ruby | def build(view, style = nil, opts = {}, &block)
opts[:do_not_add] = true
opts[:style] = style
opts[:block] = block if block
add_subview view, opts
end | [
"def",
"build",
"(",
"view",
",",
"style",
"=",
"nil",
",",
"opts",
"=",
"{",
"}",
",",
"&",
"block",
")",
"opts",
"[",
":do_not_add",
"]",
"=",
"true",
"opts",
"[",
":style",
"]",
"=",
"style",
"opts",
"[",
":block",
"]",
"=",
"block",
"if",
"block",
"add_subview",
"view",
",",
"opts",
"end"
]
| Build a view, similar to create and append, but only inits an existing view. Usefull
in collectionview cells for example
@example
# In your collectionview
rmq.build(cell) unless cell.reused
# Then in your cell
def rmq_build
rmq.append(UIView, :foo)
end | [
"Build",
"a",
"view",
"similar",
"to",
"create",
"and",
"append",
"but",
"only",
"inits",
"an",
"existing",
"view",
".",
"Usefull",
"in",
"collectionview",
"cells",
"for",
"example"
]
| a8329e1574ce3275c9fe56b91127c8b5e4b7693e | https://github.com/infinitered/rmq/blob/a8329e1574ce3275c9fe56b91127c8b5e4b7693e/motion/ruby_motion_query/subviews.rb#L209-L214 | train |
infinitered/rmq | motion/ruby_motion_query/validation.rb | RubyMotionQuery.Validation.universal_validation_checks | def universal_validation_checks (data, options={})
# shortcircuit if debugging
return true if RubyMotionQuery::RMQ.debugging?
# allow blank data if specified
return true if (options[:allow_blank] && (data.nil? || data.empty?))
# allow whitelist data if specified
return true if (options[:white_list] && options[:white_list].include?(data))
false
end | ruby | def universal_validation_checks (data, options={})
# shortcircuit if debugging
return true if RubyMotionQuery::RMQ.debugging?
# allow blank data if specified
return true if (options[:allow_blank] && (data.nil? || data.empty?))
# allow whitelist data if specified
return true if (options[:white_list] && options[:white_list].include?(data))
false
end | [
"def",
"universal_validation_checks",
"(",
"data",
",",
"options",
"=",
"{",
"}",
")",
"return",
"true",
"if",
"RubyMotionQuery",
"::",
"RMQ",
".",
"debugging?",
"return",
"true",
"if",
"(",
"options",
"[",
":allow_blank",
"]",
"&&",
"(",
"data",
".",
"nil?",
"||",
"data",
".",
"empty?",
")",
")",
"return",
"true",
"if",
"(",
"options",
"[",
":white_list",
"]",
"&&",
"options",
"[",
":white_list",
"]",
".",
"include?",
"(",
"data",
")",
")",
"false",
"end"
]
| this method shortcuts specific validation rules. As such it should only be
added to for universal validation needs. It must be kept as efficient as possible. | [
"this",
"method",
"shortcuts",
"specific",
"validation",
"rules",
".",
"As",
"such",
"it",
"should",
"only",
"be",
"added",
"to",
"for",
"universal",
"validation",
"needs",
".",
"It",
"must",
"be",
"kept",
"as",
"efficient",
"as",
"possible",
"."
]
| a8329e1574ce3275c9fe56b91127c8b5e4b7693e | https://github.com/infinitered/rmq/blob/a8329e1574ce3275c9fe56b91127c8b5e4b7693e/motion/ruby_motion_query/validation.rb#L110-L119 | train |
infinitered/rmq | motion/ruby_motion_query/debug.rb | RubyMotionQuery.Debug.log_detailed | def log_detailed(label, params = {})
return unless RMQ.app.development? || RMQ.app.test?
objects = params[:objects]
skip_first_caller = params[:skip_first_caller]
if block_given? && !objects
objects = yield
end
callers = caller
callers = callers.drop(1) if skip_first_caller
out = %(
------------------------------------------------
Deep log - #{label}
At: #{Time.now.to_s}
Callers:
#{callers.join("\n - ")}
Objects:
#{objects.map{|k, v| "#{k.to_s}: #{v.inspect}" }.join("\n\n")}
------------------------------------------------
).gsub(/^ +/, '')
NSLog out
label
end | ruby | def log_detailed(label, params = {})
return unless RMQ.app.development? || RMQ.app.test?
objects = params[:objects]
skip_first_caller = params[:skip_first_caller]
if block_given? && !objects
objects = yield
end
callers = caller
callers = callers.drop(1) if skip_first_caller
out = %(
------------------------------------------------
Deep log - #{label}
At: #{Time.now.to_s}
Callers:
#{callers.join("\n - ")}
Objects:
#{objects.map{|k, v| "#{k.to_s}: #{v.inspect}" }.join("\n\n")}
------------------------------------------------
).gsub(/^ +/, '')
NSLog out
label
end | [
"def",
"log_detailed",
"(",
"label",
",",
"params",
"=",
"{",
"}",
")",
"return",
"unless",
"RMQ",
".",
"app",
".",
"development?",
"||",
"RMQ",
".",
"app",
".",
"test?",
"objects",
"=",
"params",
"[",
":objects",
"]",
"skip_first_caller",
"=",
"params",
"[",
":skip_first_caller",
"]",
"if",
"block_given?",
"&&",
"!",
"objects",
"objects",
"=",
"yield",
"end",
"callers",
"=",
"caller",
"callers",
"=",
"callers",
".",
"drop",
"(",
"1",
")",
"if",
"skip_first_caller",
"out",
"=",
"%( ------------------------------------------------ Deep log - #{label} At: #{Time.now.to_s} Callers: #{callers.join(\"\\n - \")} Objects: #{objects.map{|k, v| \"#{k.to_s}: #{v.inspect}\" }.join(\"\\n\\n\")} ------------------------------------------------ )",
".",
"gsub",
"(",
"/",
"/",
",",
"''",
")",
"NSLog",
"out",
"label",
"end"
]
| Warning, this is very slow | [
"Warning",
"this",
"is",
"very",
"slow"
]
| a8329e1574ce3275c9fe56b91127c8b5e4b7693e | https://github.com/infinitered/rmq/blob/a8329e1574ce3275c9fe56b91127c8b5e4b7693e/motion/ruby_motion_query/debug.rb#L41-L71 | train |
infinitered/rmq | motion/ruby_motion_query/debug.rb | RubyMotionQuery.Debug.assert | def assert(truthy, label = nil, objects = nil)
if (RMQ.app.development? || RMQ.app.test?) && !truthy
label ||= 'Assert failed'
if block_given? && !objects
objects = yield
end
log_detailed label, objects: objects, skip_first_caller: true
end
end | ruby | def assert(truthy, label = nil, objects = nil)
if (RMQ.app.development? || RMQ.app.test?) && !truthy
label ||= 'Assert failed'
if block_given? && !objects
objects = yield
end
log_detailed label, objects: objects, skip_first_caller: true
end
end | [
"def",
"assert",
"(",
"truthy",
",",
"label",
"=",
"nil",
",",
"objects",
"=",
"nil",
")",
"if",
"(",
"RMQ",
".",
"app",
".",
"development?",
"||",
"RMQ",
".",
"app",
".",
"test?",
")",
"&&",
"!",
"truthy",
"label",
"||=",
"'Assert failed'",
"if",
"block_given?",
"&&",
"!",
"objects",
"objects",
"=",
"yield",
"end",
"log_detailed",
"label",
",",
"objects",
":",
"objects",
",",
"skip_first_caller",
":",
"true",
"end",
"end"
]
| Warning, this is very slow to output log, checking truthy however is
basically as performant as an if statement
@example
# foo and bar are objects we want to inspect
rmq.debug.assert(1==2, 'Bad stuff happened', {
foo: foo,
bar: bar
}) | [
"Warning",
"this",
"is",
"very",
"slow",
"to",
"output",
"log",
"checking",
"truthy",
"however",
"is",
"basically",
"as",
"performant",
"as",
"an",
"if",
"statement"
]
| a8329e1574ce3275c9fe56b91127c8b5e4b7693e | https://github.com/infinitered/rmq/blob/a8329e1574ce3275c9fe56b91127c8b5e4b7693e/motion/ruby_motion_query/debug.rb#L83-L91 | train |
infinitered/rmq | motion/ruby_motion_query/position.rb | RubyMotionQuery.RMQ.subviews_bottom_right | def subviews_bottom_right(view, args = {})
w = 0
h = 0
view.subviews.each do |subview|
rect = subview.rmq.frame
w = [rect.right, w].max
h = [rect.bottom, h].max
end
rect = view.rmq.frame
w = rect.width if (w == 0 || args[:only_height])
h = rect.height if (h == 0 || args[:only_width])
{w: (w + (args[:right] || 0)), h: (h + (args[:bottom] || 0))}
end | ruby | def subviews_bottom_right(view, args = {})
w = 0
h = 0
view.subviews.each do |subview|
rect = subview.rmq.frame
w = [rect.right, w].max
h = [rect.bottom, h].max
end
rect = view.rmq.frame
w = rect.width if (w == 0 || args[:only_height])
h = rect.height if (h == 0 || args[:only_width])
{w: (w + (args[:right] || 0)), h: (h + (args[:bottom] || 0))}
end | [
"def",
"subviews_bottom_right",
"(",
"view",
",",
"args",
"=",
"{",
"}",
")",
"w",
"=",
"0",
"h",
"=",
"0",
"view",
".",
"subviews",
".",
"each",
"do",
"|",
"subview",
"|",
"rect",
"=",
"subview",
".",
"rmq",
".",
"frame",
"w",
"=",
"[",
"rect",
".",
"right",
",",
"w",
"]",
".",
"max",
"h",
"=",
"[",
"rect",
".",
"bottom",
",",
"h",
"]",
".",
"max",
"end",
"rect",
"=",
"view",
".",
"rmq",
".",
"frame",
"w",
"=",
"rect",
".",
"width",
"if",
"(",
"w",
"==",
"0",
"||",
"args",
"[",
":only_height",
"]",
")",
"h",
"=",
"rect",
".",
"height",
"if",
"(",
"h",
"==",
"0",
"||",
"args",
"[",
":only_width",
"]",
")",
"{",
"w",
":",
"(",
"w",
"+",
"(",
"args",
"[",
":right",
"]",
"||",
"0",
")",
")",
",",
"h",
":",
"(",
"h",
"+",
"(",
"args",
"[",
":bottom",
"]",
"||",
"0",
")",
")",
"}",
"end"
]
| Calculates the bottom right of a view using its subviews
@return [Hash] | [
"Calculates",
"the",
"bottom",
"right",
"of",
"a",
"view",
"using",
"its",
"subviews"
]
| a8329e1574ce3275c9fe56b91127c8b5e4b7693e | https://github.com/infinitered/rmq/blob/a8329e1574ce3275c9fe56b91127c8b5e4b7693e/motion/ruby_motion_query/position.rb#L189-L204 | train |
infinitered/rmq | motion/ruby_motion_query/base.rb | RubyMotionQuery.RMQ.context= | def context=(value)
if value
if value.is_a?(UIViewController)
@context = RubyMotionQuery::RMQ.weak_ref(value)
elsif value.is_a?(UIView)
@context = value
#else
#debug.log_detailed('Invalid context', objects: {value: value})
end
else
@context = nil
end
@context
end | ruby | def context=(value)
if value
if value.is_a?(UIViewController)
@context = RubyMotionQuery::RMQ.weak_ref(value)
elsif value.is_a?(UIView)
@context = value
#else
#debug.log_detailed('Invalid context', objects: {value: value})
end
else
@context = nil
end
@context
end | [
"def",
"context",
"=",
"(",
"value",
")",
"if",
"value",
"if",
"value",
".",
"is_a?",
"(",
"UIViewController",
")",
"@context",
"=",
"RubyMotionQuery",
"::",
"RMQ",
".",
"weak_ref",
"(",
"value",
")",
"elsif",
"value",
".",
"is_a?",
"(",
"UIView",
")",
"@context",
"=",
"value",
"end",
"else",
"@context",
"=",
"nil",
"end",
"@context",
"end"
]
| This is mostly used internally
If rmq was called in a view, context will be that view. If it was called
in a UIViewController, it will be that controller. If it is called in another
object, it will be current controller's rmq instance and thus context will be
that controller | [
"This",
"is",
"mostly",
"used",
"internally"
]
| a8329e1574ce3275c9fe56b91127c8b5e4b7693e | https://github.com/infinitered/rmq/blob/a8329e1574ce3275c9fe56b91127c8b5e4b7693e/motion/ruby_motion_query/base.rb#L30-L43 | train |
infinitered/rmq | motion/ruby_motion_query/base.rb | RubyMotionQuery.RMQ.selected | def selected
if @selected_dirty
@_selected = []
if RMQ.is_blank?(self.selectors)
@_selected << context_or_context_view
else
working_selectors = self.selectors.dup
extract_views_from_selectors(@_selected, working_selectors)
unless RMQ.is_blank?(working_selectors)
subviews = all_subviews_for(root_view)
subviews.each do |subview|
@_selected << subview if match(subview, working_selectors)
end
end
@_selected.uniq!
end
@selected_dirty = false
else
@_selected ||= []
end
@_selected
end | ruby | def selected
if @selected_dirty
@_selected = []
if RMQ.is_blank?(self.selectors)
@_selected << context_or_context_view
else
working_selectors = self.selectors.dup
extract_views_from_selectors(@_selected, working_selectors)
unless RMQ.is_blank?(working_selectors)
subviews = all_subviews_for(root_view)
subviews.each do |subview|
@_selected << subview if match(subview, working_selectors)
end
end
@_selected.uniq!
end
@selected_dirty = false
else
@_selected ||= []
end
@_selected
end | [
"def",
"selected",
"if",
"@selected_dirty",
"@_selected",
"=",
"[",
"]",
"if",
"RMQ",
".",
"is_blank?",
"(",
"self",
".",
"selectors",
")",
"@_selected",
"<<",
"context_or_context_view",
"else",
"working_selectors",
"=",
"self",
".",
"selectors",
".",
"dup",
"extract_views_from_selectors",
"(",
"@_selected",
",",
"working_selectors",
")",
"unless",
"RMQ",
".",
"is_blank?",
"(",
"working_selectors",
")",
"subviews",
"=",
"all_subviews_for",
"(",
"root_view",
")",
"subviews",
".",
"each",
"do",
"|",
"subview",
"|",
"@_selected",
"<<",
"subview",
"if",
"match",
"(",
"subview",
",",
"working_selectors",
")",
"end",
"end",
"@_selected",
".",
"uniq!",
"end",
"@selected_dirty",
"=",
"false",
"else",
"@_selected",
"||=",
"[",
"]",
"end",
"@_selected",
"end"
]
| The UIViews currently selected
Use {#get} instead to get the actual UIView objects
@return [Array] | [
"The",
"UIViews",
"currently",
"selected"
]
| a8329e1574ce3275c9fe56b91127c8b5e4b7693e | https://github.com/infinitered/rmq/blob/a8329e1574ce3275c9fe56b91127c8b5e4b7693e/motion/ruby_motion_query/base.rb#L60-L86 | train |
infinitered/rmq | motion/ruby_motion_query/base.rb | RubyMotionQuery.RMQ.wrap | def wrap(*views)
views.flatten!
views.select!{ |v| v.is_a?(UIView) }
RMQ.create_with_array_and_selectors(views, views, views.first, self)
end | ruby | def wrap(*views)
views.flatten!
views.select!{ |v| v.is_a?(UIView) }
RMQ.create_with_array_and_selectors(views, views, views.first, self)
end | [
"def",
"wrap",
"(",
"*",
"views",
")",
"views",
".",
"flatten!",
"views",
".",
"select!",
"{",
"|",
"v",
"|",
"v",
".",
"is_a?",
"(",
"UIView",
")",
"}",
"RMQ",
".",
"create_with_array_and_selectors",
"(",
"views",
",",
"views",
",",
"views",
".",
"first",
",",
"self",
")",
"end"
]
| Wraps 1 or more views in an rmq instance.
Normally you select a view or views using rmq(my_view). Which doesn't
work if you have an instance of a RMQ, in which case it isn't a method.
In some cases you want to save an instance of rmq and use it like the rmq
method, for this you'd use #wrap
@example
q = RubyMotionQuery::RMQ.new
# Bad
q(my_view).view_controller
# Good
q.wrap(my_view).view_controller | [
"Wraps",
"1",
"or",
"more",
"views",
"in",
"an",
"rmq",
"instance",
"."
]
| a8329e1574ce3275c9fe56b91127c8b5e4b7693e | https://github.com/infinitered/rmq/blob/a8329e1574ce3275c9fe56b91127c8b5e4b7693e/motion/ruby_motion_query/base.rb#L103-L107 | train |
infinitered/rmq | motion/ruby_motion_query/base.rb | RubyMotionQuery.RMQ.log | def log(opt = nil)
if opt == :tree
puts tree_to_s(selected)
return
end
wide = (opt == :wide)
out = "\n object_id | class | style_name | frame |"
out << "\n" unless wide
out << " sv id | superview | subviews count | tags |"
line = " - - - - - - | - - - - - - - - - - - | - - - - - - - - - - - - | - - - - - - - - - - - - - - - - |\n"
out << "\n"
out << line.chop if wide
out << line
selected.each do |view|
out << " #{view.object_id.to_s.ljust(12)}|"
out << " #{view.class.name[0..21].ljust(22)}|"
out << " #{(view.rmq_data.style_name || '')[0..23].ljust(24)}|"
s = ""
if view.origin
format = '#0.#'
s = " {l: #{RMQ.format.numeric(view.origin.x, format)}"
s << ", t: #{RMQ.format.numeric(view.origin.y, format)}"
s << ", w: #{RMQ.format.numeric(view.size.width, format)}"
s << ", h: #{RMQ.format.numeric(view.size.height, format)}}"
end
out << s.ljust(33)
out << '|'
out << "\n" unless wide
out << " #{view.superview.object_id.to_s.ljust(12)}|"
out << " #{(view.superview ? view.superview.class.name : '')[0..21].ljust(22)}|"
out << " #{view.subviews.length.to_s.ljust(23)} |"
#out << " #{view.subviews.length.to_s.rjust(8)} #{view.superview.class.name.ljust(20)} #{view.superview.object_id.to_s.rjust(10)}"
out << " #{view.rmq_data.tag_names.join(',').ljust(32)}|"
out << "\n"
out << line unless wide
end
out << "RMQ #{self.object_id}. #{self.count} selected. selectors: #{self.selectors}"
puts out
end | ruby | def log(opt = nil)
if opt == :tree
puts tree_to_s(selected)
return
end
wide = (opt == :wide)
out = "\n object_id | class | style_name | frame |"
out << "\n" unless wide
out << " sv id | superview | subviews count | tags |"
line = " - - - - - - | - - - - - - - - - - - | - - - - - - - - - - - - | - - - - - - - - - - - - - - - - |\n"
out << "\n"
out << line.chop if wide
out << line
selected.each do |view|
out << " #{view.object_id.to_s.ljust(12)}|"
out << " #{view.class.name[0..21].ljust(22)}|"
out << " #{(view.rmq_data.style_name || '')[0..23].ljust(24)}|"
s = ""
if view.origin
format = '#0.#'
s = " {l: #{RMQ.format.numeric(view.origin.x, format)}"
s << ", t: #{RMQ.format.numeric(view.origin.y, format)}"
s << ", w: #{RMQ.format.numeric(view.size.width, format)}"
s << ", h: #{RMQ.format.numeric(view.size.height, format)}}"
end
out << s.ljust(33)
out << '|'
out << "\n" unless wide
out << " #{view.superview.object_id.to_s.ljust(12)}|"
out << " #{(view.superview ? view.superview.class.name : '')[0..21].ljust(22)}|"
out << " #{view.subviews.length.to_s.ljust(23)} |"
#out << " #{view.subviews.length.to_s.rjust(8)} #{view.superview.class.name.ljust(20)} #{view.superview.object_id.to_s.rjust(10)}"
out << " #{view.rmq_data.tag_names.join(',').ljust(32)}|"
out << "\n"
out << line unless wide
end
out << "RMQ #{self.object_id}. #{self.count} selected. selectors: #{self.selectors}"
puts out
end | [
"def",
"log",
"(",
"opt",
"=",
"nil",
")",
"if",
"opt",
"==",
":tree",
"puts",
"tree_to_s",
"(",
"selected",
")",
"return",
"end",
"wide",
"=",
"(",
"opt",
"==",
":wide",
")",
"out",
"=",
"\"\\n object_id | class | style_name | frame |\"",
"out",
"<<",
"\"\\n\"",
"unless",
"wide",
"out",
"<<",
"\" sv id | superview | subviews count | tags |\"",
"line",
"=",
"\" - - - - - - | - - - - - - - - - - - | - - - - - - - - - - - - | - - - - - - - - - - - - - - - - |\\n\"",
"out",
"<<",
"\"\\n\"",
"out",
"<<",
"line",
".",
"chop",
"if",
"wide",
"out",
"<<",
"line",
"selected",
".",
"each",
"do",
"|",
"view",
"|",
"out",
"<<",
"\" #{view.object_id.to_s.ljust(12)}|\"",
"out",
"<<",
"\" #{view.class.name[0..21].ljust(22)}|\"",
"out",
"<<",
"\" #{(view.rmq_data.style_name || '')[0..23].ljust(24)}|\"",
"s",
"=",
"\"\"",
"if",
"view",
".",
"origin",
"format",
"=",
"'#0.#'",
"s",
"=",
"\" {l: #{RMQ.format.numeric(view.origin.x, format)}\"",
"s",
"<<",
"\", t: #{RMQ.format.numeric(view.origin.y, format)}\"",
"s",
"<<",
"\", w: #{RMQ.format.numeric(view.size.width, format)}\"",
"s",
"<<",
"\", h: #{RMQ.format.numeric(view.size.height, format)}}\"",
"end",
"out",
"<<",
"s",
".",
"ljust",
"(",
"33",
")",
"out",
"<<",
"'|'",
"out",
"<<",
"\"\\n\"",
"unless",
"wide",
"out",
"<<",
"\" #{view.superview.object_id.to_s.ljust(12)}|\"",
"out",
"<<",
"\" #{(view.superview ? view.superview.class.name : '')[0..21].ljust(22)}|\"",
"out",
"<<",
"\" #{view.subviews.length.to_s.ljust(23)} |\"",
"out",
"<<",
"\" #{view.rmq_data.tag_names.join(',').ljust(32)}|\"",
"out",
"<<",
"\"\\n\"",
"out",
"<<",
"line",
"unless",
"wide",
"end",
"out",
"<<",
"\"RMQ #{self.object_id}. #{self.count} selected. selectors: #{self.selectors}\"",
"puts",
"out",
"end"
]
| Super useful in the console. log outputs to the console a table of the selected views
@param :wide outputs wide format (really wide, but awesome: rmq.all.log :wide). :tree outputs the
log in a tree form
@return [String]
@example
(main)> rmq(UIImageView).log
object_id | class | style_name | frame |
sv id | superview | subviews count | tags |
- - - - - - | - - - - - - - - - - - | - - - - - - - - - - - - | - - - - - - - - - - - - - - - - |
168150976 | UIImageView | logo | {l: 60, t: 10, w: 200, h: 95.5} |
168128784 | UIView | 0 | |
- - - - - - | - - - - - - - - - - - | - - - - - - - - - - - - | - - - - - - - - - - - - - - - - |
168180640 | UIImageView | | {l: 1, t: 1, w: 148, h: 19} |
168173616 | UIRoundedRectButton | 0 | |
- - - - - - | - - - - - - - - - - - | - - - - - - - - - - - - | - - - - - - - - - - - - - - - - |
168204336 | UIImageView | | {l: 1, t: 0, w: 77, h: 27} |
168201952 | _UISwitchInternalView | 0 | |
- - - - - - | - - - - - - - - - - - | - - - - - - - - - - - - | - - - - - - - - - - - - - - - - |
172600352 | UIImageView | | {l: -2, t: 0, w: 79, h: 27} |
168204512 | UIView | 0 | |
- - - - - - | - - - - - - - - - - - | - - - - - - - - - - - - | - - - - - - - - - - - - - - - - |
168205504 | UIImageView | | {l: -2, t: 0, w: 131, h: 27} |
168204512 | UIView | 0 | |
- - - - - - | - - - - - - - - - - - | - - - - - - - - - - - - | - - - - - - - - - - - - - - - - |
168205600 | UIImageView | | {l: 49, t: 0, w: 29, h: 27} |
168204512 | UIView | 0 | |
- - - - - - | - - - - - - - - - - - | - - - - - - - - - - - - | - - - - - - - - - - - - - - - - |
RMQ 278442176. 6 selected. selectors: [UIImageView]
@example
rmq.log :tree
@example
rmq.all.log :wide | [
"Super",
"useful",
"in",
"the",
"console",
".",
"log",
"outputs",
"to",
"the",
"console",
"a",
"table",
"of",
"the",
"selected",
"views"
]
| a8329e1574ce3275c9fe56b91127c8b5e4b7693e | https://github.com/infinitered/rmq/blob/a8329e1574ce3275c9fe56b91127c8b5e4b7693e/motion/ruby_motion_query/base.rb#L228-L272 | train |
gcao/aspector | lib/aspector/interception.rb | Aspector.Interception.apply_to_method | def apply_to_method(method)
filtered_advices = filter_advices advices, method
return if filtered_advices.empty?
logger.debug 'apply-to-method', method
scope ||= context.instance_method_type(method)
recreate_method method, filtered_advices, scope
end | ruby | def apply_to_method(method)
filtered_advices = filter_advices advices, method
return if filtered_advices.empty?
logger.debug 'apply-to-method', method
scope ||= context.instance_method_type(method)
recreate_method method, filtered_advices, scope
end | [
"def",
"apply_to_method",
"(",
"method",
")",
"filtered_advices",
"=",
"filter_advices",
"advices",
",",
"method",
"return",
"if",
"filtered_advices",
".",
"empty?",
"logger",
".",
"debug",
"'apply-to-method'",
",",
"method",
"scope",
"||=",
"context",
".",
"instance_method_type",
"(",
"method",
")",
"recreate_method",
"method",
",",
"filtered_advices",
",",
"scope",
"end"
]
| Applies advices to a given method
@note This method is public only because we use it from define_method on a module
@note If will figure out the method scope (private/public/protected) on its own
@param method [Symbol] method to which we want to apply this interception | [
"Applies",
"advices",
"to",
"a",
"given",
"method"
]
| c82396dc8678bf632959fdaf25aa28e76b0e4605 | https://github.com/gcao/aspector/blob/c82396dc8678bf632959fdaf25aa28e76b0e4605/lib/aspector/interception.rb#L57-L66 | train |
gcao/aspector | lib/aspector/interception.rb | Aspector.Interception.define_methods_for_advice_blocks | def define_methods_for_advice_blocks
advices.each do |advice|
next if advice.raw?
next unless advice.advice_block
context.send :define_method, advice.with_method, advice.advice_block
context.send :private, advice.with_method
end
end | ruby | def define_methods_for_advice_blocks
advices.each do |advice|
next if advice.raw?
next unless advice.advice_block
context.send :define_method, advice.with_method, advice.advice_block
context.send :private, advice.with_method
end
end | [
"def",
"define_methods_for_advice_blocks",
"advices",
".",
"each",
"do",
"|",
"advice",
"|",
"next",
"if",
"advice",
".",
"raw?",
"next",
"unless",
"advice",
".",
"advice_block",
"context",
".",
"send",
":define_method",
",",
"advice",
".",
"with_method",
",",
"advice",
".",
"advice_block",
"context",
".",
"send",
":private",
",",
"advice",
".",
"with_method",
"end",
"end"
]
| Defines on a target element new methods that will contain advices logic
as long as their blocks. Then we can invoke advices logic as a normal methods
In a way it just casts a block to methods for peformance reasons
If we have advices that just execute already existing methods, this won't create
anything
@note All methods like this are set to private - they should stay as an internal
implementation detail | [
"Defines",
"on",
"a",
"target",
"element",
"new",
"methods",
"that",
"will",
"contain",
"advices",
"logic",
"as",
"long",
"as",
"their",
"blocks",
".",
"Then",
"we",
"can",
"invoke",
"advices",
"logic",
"as",
"a",
"normal",
"methods",
"In",
"a",
"way",
"it",
"just",
"casts",
"a",
"block",
"to",
"methods",
"for",
"peformance",
"reasons",
"If",
"we",
"have",
"advices",
"that",
"just",
"execute",
"already",
"existing",
"methods",
"this",
"won",
"t",
"create",
"anything"
]
| c82396dc8678bf632959fdaf25aa28e76b0e4605 | https://github.com/gcao/aspector/blob/c82396dc8678bf632959fdaf25aa28e76b0e4605/lib/aspector/interception.rb#L77-L84 | train |
gcao/aspector | lib/aspector/interception.rb | Aspector.Interception.apply_to_methods | def apply_to_methods
# If method/methods option is set and all are String or Symbol, apply to those only, instead of
# iterating through all methods
methods = [@options[:method] || @options[:methods]]
methods.compact!
methods.flatten!
if !methods.empty? && methods.all?{ |method| method.is_a?(String) || method.is_a?(Symbol) }
methods.each do |method|
apply_to_method(method.to_s)
end
return
end
context.public_instance_methods.each do |method|
apply_to_method(method.to_s)
end
context.protected_instance_methods.each do |method|
apply_to_method(method.to_s)
end
if @options[:private_methods]
context.private_instance_methods.each do |method|
apply_to_method(method.to_s)
end
end
end | ruby | def apply_to_methods
# If method/methods option is set and all are String or Symbol, apply to those only, instead of
# iterating through all methods
methods = [@options[:method] || @options[:methods]]
methods.compact!
methods.flatten!
if !methods.empty? && methods.all?{ |method| method.is_a?(String) || method.is_a?(Symbol) }
methods.each do |method|
apply_to_method(method.to_s)
end
return
end
context.public_instance_methods.each do |method|
apply_to_method(method.to_s)
end
context.protected_instance_methods.each do |method|
apply_to_method(method.to_s)
end
if @options[:private_methods]
context.private_instance_methods.each do |method|
apply_to_method(method.to_s)
end
end
end | [
"def",
"apply_to_methods",
"methods",
"=",
"[",
"@options",
"[",
":method",
"]",
"||",
"@options",
"[",
":methods",
"]",
"]",
"methods",
".",
"compact!",
"methods",
".",
"flatten!",
"if",
"!",
"methods",
".",
"empty?",
"&&",
"methods",
".",
"all?",
"{",
"|",
"method",
"|",
"method",
".",
"is_a?",
"(",
"String",
")",
"||",
"method",
".",
"is_a?",
"(",
"Symbol",
")",
"}",
"methods",
".",
"each",
"do",
"|",
"method",
"|",
"apply_to_method",
"(",
"method",
".",
"to_s",
")",
"end",
"return",
"end",
"context",
".",
"public_instance_methods",
".",
"each",
"do",
"|",
"method",
"|",
"apply_to_method",
"(",
"method",
".",
"to_s",
")",
"end",
"context",
".",
"protected_instance_methods",
".",
"each",
"do",
"|",
"method",
"|",
"apply_to_method",
"(",
"method",
".",
"to_s",
")",
"end",
"if",
"@options",
"[",
":private_methods",
"]",
"context",
".",
"private_instance_methods",
".",
"each",
"do",
"|",
"method",
"|",
"apply_to_method",
"(",
"method",
".",
"to_s",
")",
"end",
"end",
"end"
]
| Will apply all the advices to all methods that match | [
"Will",
"apply",
"all",
"the",
"advices",
"to",
"all",
"methods",
"that",
"match"
]
| c82396dc8678bf632959fdaf25aa28e76b0e4605 | https://github.com/gcao/aspector/blob/c82396dc8678bf632959fdaf25aa28e76b0e4605/lib/aspector/interception.rb#L97-L125 | train |
gcao/aspector | lib/aspector/interception.rb | Aspector.Interception.invoke_deferred_logics | def invoke_deferred_logics
logics = @aspect.class.storage.deferred_logics
return if logics.empty?
logics.each do |logic|
result = logic.apply context, aspect
if advices.detect { |advice| advice.use_deferred_logic? logic }
@deferred_logic_results ||= {}
@deferred_logic_results[logic] = result
end
end
end | ruby | def invoke_deferred_logics
logics = @aspect.class.storage.deferred_logics
return if logics.empty?
logics.each do |logic|
result = logic.apply context, aspect
if advices.detect { |advice| advice.use_deferred_logic? logic }
@deferred_logic_results ||= {}
@deferred_logic_results[logic] = result
end
end
end | [
"def",
"invoke_deferred_logics",
"logics",
"=",
"@aspect",
".",
"class",
".",
"storage",
".",
"deferred_logics",
"return",
"if",
"logics",
".",
"empty?",
"logics",
".",
"each",
"do",
"|",
"logic",
"|",
"result",
"=",
"logic",
".",
"apply",
"context",
",",
"aspect",
"if",
"advices",
".",
"detect",
"{",
"|",
"advice",
"|",
"advice",
".",
"use_deferred_logic?",
"logic",
"}",
"@deferred_logic_results",
"||=",
"{",
"}",
"@deferred_logic_results",
"[",
"logic",
"]",
"=",
"result",
"end",
"end",
"end"
]
| Invokes deferred logics blocks on a target element and stores deferred logic
invokations results | [
"Invokes",
"deferred",
"logics",
"blocks",
"on",
"a",
"target",
"element",
"and",
"stores",
"deferred",
"logic",
"invokations",
"results"
]
| c82396dc8678bf632959fdaf25aa28e76b0e4605 | https://github.com/gcao/aspector/blob/c82396dc8678bf632959fdaf25aa28e76b0e4605/lib/aspector/interception.rb#L141-L152 | train |
gcao/aspector | lib/aspector/interception.rb | Aspector.Interception.add_method_hooks | def add_method_hooks
eigen_class = @target.singleton_class
if @options[:class_methods]
return unless @target.is_a?(Module)
orig_singleton_method_added = @target.method(:singleton_method_added)
eigen_class.send :define_method, :singleton_method_added do |method|
aspector_singleton_method_added(method)
orig_singleton_method_added.call(method)
end
else
if @target.is_a? Module
orig_method_added = @target.method(:method_added)
else
orig_method_added = eigen_class.method(:method_added)
end
eigen_class.send :define_method, :method_added do |method|
aspector_instance_method_added(method)
orig_method_added.call(method)
end
end
end | ruby | def add_method_hooks
eigen_class = @target.singleton_class
if @options[:class_methods]
return unless @target.is_a?(Module)
orig_singleton_method_added = @target.method(:singleton_method_added)
eigen_class.send :define_method, :singleton_method_added do |method|
aspector_singleton_method_added(method)
orig_singleton_method_added.call(method)
end
else
if @target.is_a? Module
orig_method_added = @target.method(:method_added)
else
orig_method_added = eigen_class.method(:method_added)
end
eigen_class.send :define_method, :method_added do |method|
aspector_instance_method_added(method)
orig_method_added.call(method)
end
end
end | [
"def",
"add_method_hooks",
"eigen_class",
"=",
"@target",
".",
"singleton_class",
"if",
"@options",
"[",
":class_methods",
"]",
"return",
"unless",
"@target",
".",
"is_a?",
"(",
"Module",
")",
"orig_singleton_method_added",
"=",
"@target",
".",
"method",
"(",
":singleton_method_added",
")",
"eigen_class",
".",
"send",
":define_method",
",",
":singleton_method_added",
"do",
"|",
"method",
"|",
"aspector_singleton_method_added",
"(",
"method",
")",
"orig_singleton_method_added",
".",
"call",
"(",
"method",
")",
"end",
"else",
"if",
"@target",
".",
"is_a?",
"Module",
"orig_method_added",
"=",
"@target",
".",
"method",
"(",
":method_added",
")",
"else",
"orig_method_added",
"=",
"eigen_class",
".",
"method",
"(",
":method_added",
")",
"end",
"eigen_class",
".",
"send",
":define_method",
",",
":method_added",
"do",
"|",
"method",
"|",
"aspector_instance_method_added",
"(",
"method",
")",
"orig_method_added",
".",
"call",
"(",
"method",
")",
"end",
"end",
"end"
]
| Redefines singleton_method_added and method_added methods so they are monitored
If new method is added we will apply to it appropriate advices | [
"Redefines",
"singleton_method_added",
"and",
"method_added",
"methods",
"so",
"they",
"are",
"monitored",
"If",
"new",
"method",
"is",
"added",
"we",
"will",
"apply",
"to",
"it",
"appropriate",
"advices"
]
| c82396dc8678bf632959fdaf25aa28e76b0e4605 | https://github.com/gcao/aspector/blob/c82396dc8678bf632959fdaf25aa28e76b0e4605/lib/aspector/interception.rb#L173-L197 | train |
gcao/aspector | lib/aspector/interception.rb | Aspector.Interception.recreate_method | def recreate_method(method, advices, scope)
context.instance_variable_set(:@aspector_creating_method, true)
raw_advices = advices.select(&:raw?)
if raw_advices.size > 0
raw_advices.each do |advice|
if @target.is_a?(Module) && !@options[:class_methods]
@target.class_exec method, self, &advice.advice_block
else
@target.instance_exec method, self, &advice.advice_block
end
end
return if raw_advices.size == advices.size
end
begin
@wrapped_methods[method] = context.instance_method(method)
rescue
# ignore undefined method error
if @options[:existing_methods_only]
logger.log Logging::WARN, 'method-not-found', method
end
return
end
before_advices = advices.select(&:before?) + advices.select(&:before_filter?)
after_advices = advices.select(&:after?)
around_advices = advices.select(&:around?)
(around_advices.size - 1).downto(1) do |i|
advice = around_advices[i]
recreate_method_with_advices method, [], [], advice
end
recreate_method_with_advices(
method,
before_advices,
after_advices,
around_advices.first
)
context.send scope, method if scope != :public
ensure
context.send :remove_instance_variable, :@aspector_creating_method
end | ruby | def recreate_method(method, advices, scope)
context.instance_variable_set(:@aspector_creating_method, true)
raw_advices = advices.select(&:raw?)
if raw_advices.size > 0
raw_advices.each do |advice|
if @target.is_a?(Module) && !@options[:class_methods]
@target.class_exec method, self, &advice.advice_block
else
@target.instance_exec method, self, &advice.advice_block
end
end
return if raw_advices.size == advices.size
end
begin
@wrapped_methods[method] = context.instance_method(method)
rescue
# ignore undefined method error
if @options[:existing_methods_only]
logger.log Logging::WARN, 'method-not-found', method
end
return
end
before_advices = advices.select(&:before?) + advices.select(&:before_filter?)
after_advices = advices.select(&:after?)
around_advices = advices.select(&:around?)
(around_advices.size - 1).downto(1) do |i|
advice = around_advices[i]
recreate_method_with_advices method, [], [], advice
end
recreate_method_with_advices(
method,
before_advices,
after_advices,
around_advices.first
)
context.send scope, method if scope != :public
ensure
context.send :remove_instance_variable, :@aspector_creating_method
end | [
"def",
"recreate_method",
"(",
"method",
",",
"advices",
",",
"scope",
")",
"context",
".",
"instance_variable_set",
"(",
":@aspector_creating_method",
",",
"true",
")",
"raw_advices",
"=",
"advices",
".",
"select",
"(",
"&",
":raw?",
")",
"if",
"raw_advices",
".",
"size",
">",
"0",
"raw_advices",
".",
"each",
"do",
"|",
"advice",
"|",
"if",
"@target",
".",
"is_a?",
"(",
"Module",
")",
"&&",
"!",
"@options",
"[",
":class_methods",
"]",
"@target",
".",
"class_exec",
"method",
",",
"self",
",",
"&",
"advice",
".",
"advice_block",
"else",
"@target",
".",
"instance_exec",
"method",
",",
"self",
",",
"&",
"advice",
".",
"advice_block",
"end",
"end",
"return",
"if",
"raw_advices",
".",
"size",
"==",
"advices",
".",
"size",
"end",
"begin",
"@wrapped_methods",
"[",
"method",
"]",
"=",
"context",
".",
"instance_method",
"(",
"method",
")",
"rescue",
"if",
"@options",
"[",
":existing_methods_only",
"]",
"logger",
".",
"log",
"Logging",
"::",
"WARN",
",",
"'method-not-found'",
",",
"method",
"end",
"return",
"end",
"before_advices",
"=",
"advices",
".",
"select",
"(",
"&",
":before?",
")",
"+",
"advices",
".",
"select",
"(",
"&",
":before_filter?",
")",
"after_advices",
"=",
"advices",
".",
"select",
"(",
"&",
":after?",
")",
"around_advices",
"=",
"advices",
".",
"select",
"(",
"&",
":around?",
")",
"(",
"around_advices",
".",
"size",
"-",
"1",
")",
".",
"downto",
"(",
"1",
")",
"do",
"|",
"i",
"|",
"advice",
"=",
"around_advices",
"[",
"i",
"]",
"recreate_method_with_advices",
"method",
",",
"[",
"]",
",",
"[",
"]",
",",
"advice",
"end",
"recreate_method_with_advices",
"(",
"method",
",",
"before_advices",
",",
"after_advices",
",",
"around_advices",
".",
"first",
")",
"context",
".",
"send",
"scope",
",",
"method",
"if",
"scope",
"!=",
":public",
"ensure",
"context",
".",
"send",
":remove_instance_variable",
",",
":@aspector_creating_method",
"end"
]
| Recreates a given method applying all the advices one by one
@param method [String] method name of a method that we want to recreate
@param advices [Array<Aspector::Advice>] all the advices that
should be applied (after filtering)
@param scope [Symbol] method visibility (private, protected, public) | [
"Recreates",
"a",
"given",
"method",
"applying",
"all",
"the",
"advices",
"one",
"by",
"one"
]
| c82396dc8678bf632959fdaf25aa28e76b0e4605 | https://github.com/gcao/aspector/blob/c82396dc8678bf632959fdaf25aa28e76b0e4605/lib/aspector/interception.rb#L214-L261 | train |
gcao/aspector | lib/aspector/logger.rb | Aspector.Logger.message | def message(*args)
msg = []
if context.is_a? Aspector::Base
msg << context.class.to_s
msg << context.target.to_s
else
msg << context.to_s
end
msg += args
msg.join(' | ')
end | ruby | def message(*args)
msg = []
if context.is_a? Aspector::Base
msg << context.class.to_s
msg << context.target.to_s
else
msg << context.to_s
end
msg += args
msg.join(' | ')
end | [
"def",
"message",
"(",
"*",
"args",
")",
"msg",
"=",
"[",
"]",
"if",
"context",
".",
"is_a?",
"Aspector",
"::",
"Base",
"msg",
"<<",
"context",
".",
"class",
".",
"to_s",
"msg",
"<<",
"context",
".",
"target",
".",
"to_s",
"else",
"msg",
"<<",
"context",
".",
"to_s",
"end",
"msg",
"+=",
"args",
"msg",
".",
"join",
"(",
"' | '",
")",
"end"
]
| Creates a full messages that we want to log
@param args any arguments that we want to log based on
@return [String] message string for logging - provides additional context information
@example Create a message based on a single argument
message('action taken') #=> 'Aspector::Base | ExampleClass | action taken' | [
"Creates",
"a",
"full",
"messages",
"that",
"we",
"want",
"to",
"log"
]
| c82396dc8678bf632959fdaf25aa28e76b0e4605 | https://github.com/gcao/aspector/blob/c82396dc8678bf632959fdaf25aa28e76b0e4605/lib/aspector/logger.rb#L36-L49 | train |
Fullscreen/squid | lib/squid/plotter.rb | Squid.Plotter.legend | def legend(labels, height:, right: 0, colors: [])
left = @pdf.bounds.width/2
box(x: left, y: @pdf.bounds.top, w: left, h: height) do
x = @pdf.bounds.right - right
options = {size: 7, height: @pdf.bounds.height, valign: :center}
labels.each.with_index do |label, i|
index = labels.size - 1 - i
series_color = colors.fetch index, series_colors(index)
color = Array.wrap(series_color).first
x = legend_item label, x, color, options
end
end
end | ruby | def legend(labels, height:, right: 0, colors: [])
left = @pdf.bounds.width/2
box(x: left, y: @pdf.bounds.top, w: left, h: height) do
x = @pdf.bounds.right - right
options = {size: 7, height: @pdf.bounds.height, valign: :center}
labels.each.with_index do |label, i|
index = labels.size - 1 - i
series_color = colors.fetch index, series_colors(index)
color = Array.wrap(series_color).first
x = legend_item label, x, color, options
end
end
end | [
"def",
"legend",
"(",
"labels",
",",
"height",
":",
",",
"right",
":",
"0",
",",
"colors",
":",
"[",
"]",
")",
"left",
"=",
"@pdf",
".",
"bounds",
".",
"width",
"/",
"2",
"box",
"(",
"x",
":",
"left",
",",
"y",
":",
"@pdf",
".",
"bounds",
".",
"top",
",",
"w",
":",
"left",
",",
"h",
":",
"height",
")",
"do",
"x",
"=",
"@pdf",
".",
"bounds",
".",
"right",
"-",
"right",
"options",
"=",
"{",
"size",
":",
"7",
",",
"height",
":",
"@pdf",
".",
"bounds",
".",
"height",
",",
"valign",
":",
":center",
"}",
"labels",
".",
"each",
".",
"with_index",
"do",
"|",
"label",
",",
"i",
"|",
"index",
"=",
"labels",
".",
"size",
"-",
"1",
"-",
"i",
"series_color",
"=",
"colors",
".",
"fetch",
"index",
",",
"series_colors",
"(",
"index",
")",
"color",
"=",
"Array",
".",
"wrap",
"(",
"series_color",
")",
".",
"first",
"x",
"=",
"legend_item",
"label",
",",
"x",
",",
"color",
",",
"options",
"end",
"end",
"end"
]
| Draws the graph legend with the given labels.
@param [Array<LegendItem>] The labels to write as part of the legend. | [
"Draws",
"the",
"graph",
"legend",
"with",
"the",
"given",
"labels",
"."
]
| c8fa02c185d41b880219bc72707b9d72a54b374b | https://github.com/Fullscreen/squid/blob/c8fa02c185d41b880219bc72707b9d72a54b374b/lib/squid/plotter.rb#L25-L37 | train |
Fullscreen/squid | lib/squid/plotter.rb | Squid.Plotter.horizontal_line | def horizontal_line(y, options = {})
with options do
at = y + @bottom
@pdf.stroke_horizontal_line left, @pdf.bounds.right - right, at: at
end
end | ruby | def horizontal_line(y, options = {})
with options do
at = y + @bottom
@pdf.stroke_horizontal_line left, @pdf.bounds.right - right, at: at
end
end | [
"def",
"horizontal_line",
"(",
"y",
",",
"options",
"=",
"{",
"}",
")",
"with",
"options",
"do",
"at",
"=",
"y",
"+",
"@bottom",
"@pdf",
".",
"stroke_horizontal_line",
"left",
",",
"@pdf",
".",
"bounds",
".",
"right",
"-",
"right",
",",
"at",
":",
"at",
"end",
"end"
]
| Draws a horizontal line. | [
"Draws",
"a",
"horizontal",
"line",
"."
]
| c8fa02c185d41b880219bc72707b9d72a54b374b | https://github.com/Fullscreen/squid/blob/c8fa02c185d41b880219bc72707b9d72a54b374b/lib/squid/plotter.rb#L45-L50 | train |
Fullscreen/squid | lib/squid/plotter.rb | Squid.Plotter.legend_item | def legend_item(label, x, color, options)
size, symbol_padding, entry_padding = 5, 3, 12
x -= @pdf.width_of(label, size: 7).ceil
@pdf.text_box label, options.merge(at: [x, @pdf.bounds.height])
x -= (symbol_padding + size)
with fill_color: color do
@pdf.fill_rectangle [x, @pdf.bounds.height - size], size, size
end
x - entry_padding
end | ruby | def legend_item(label, x, color, options)
size, symbol_padding, entry_padding = 5, 3, 12
x -= @pdf.width_of(label, size: 7).ceil
@pdf.text_box label, options.merge(at: [x, @pdf.bounds.height])
x -= (symbol_padding + size)
with fill_color: color do
@pdf.fill_rectangle [x, @pdf.bounds.height - size], size, size
end
x - entry_padding
end | [
"def",
"legend_item",
"(",
"label",
",",
"x",
",",
"color",
",",
"options",
")",
"size",
",",
"symbol_padding",
",",
"entry_padding",
"=",
"5",
",",
"3",
",",
"12",
"x",
"-=",
"@pdf",
".",
"width_of",
"(",
"label",
",",
"size",
":",
"7",
")",
".",
"ceil",
"@pdf",
".",
"text_box",
"label",
",",
"options",
".",
"merge",
"(",
"at",
":",
"[",
"x",
",",
"@pdf",
".",
"bounds",
".",
"height",
"]",
")",
"x",
"-=",
"(",
"symbol_padding",
"+",
"size",
")",
"with",
"fill_color",
":",
"color",
"do",
"@pdf",
".",
"fill_rectangle",
"[",
"x",
",",
"@pdf",
".",
"bounds",
".",
"height",
"-",
"size",
"]",
",",
"size",
",",
"size",
"end",
"x",
"-",
"entry_padding",
"end"
]
| Draws a single item of the legend, which includes the label and the
symbol with the matching color. Labels are written from right to left.
@param | [
"Draws",
"a",
"single",
"item",
"of",
"the",
"legend",
"which",
"includes",
"the",
"label",
"and",
"the",
"symbol",
"with",
"the",
"matching",
"color",
".",
"Labels",
"are",
"written",
"from",
"right",
"to",
"left",
"."
]
| c8fa02c185d41b880219bc72707b9d72a54b374b | https://github.com/Fullscreen/squid/blob/c8fa02c185d41b880219bc72707b9d72a54b374b/lib/squid/plotter.rb#L172-L181 | train |
Fullscreen/squid | lib/squid/plotter.rb | Squid.Plotter.with | def with(new_values = {})
transparency = new_values.delete(:transparency) { 1.0 }
old_values = Hash[new_values.map{|k,_| [k,@pdf.public_send(k)]}]
new_values.each{|k, new_value| @pdf.public_send "#{k}=", new_value }
@pdf.transparent(transparency) do
@pdf.stroke { yield }
end
old_values.each{|k, old_value| @pdf.public_send "#{k}=", old_value }
end | ruby | def with(new_values = {})
transparency = new_values.delete(:transparency) { 1.0 }
old_values = Hash[new_values.map{|k,_| [k,@pdf.public_send(k)]}]
new_values.each{|k, new_value| @pdf.public_send "#{k}=", new_value }
@pdf.transparent(transparency) do
@pdf.stroke { yield }
end
old_values.each{|k, old_value| @pdf.public_send "#{k}=", old_value }
end | [
"def",
"with",
"(",
"new_values",
"=",
"{",
"}",
")",
"transparency",
"=",
"new_values",
".",
"delete",
"(",
":transparency",
")",
"{",
"1.0",
"}",
"old_values",
"=",
"Hash",
"[",
"new_values",
".",
"map",
"{",
"|",
"k",
",",
"_",
"|",
"[",
"k",
",",
"@pdf",
".",
"public_send",
"(",
"k",
")",
"]",
"}",
"]",
"new_values",
".",
"each",
"{",
"|",
"k",
",",
"new_value",
"|",
"@pdf",
".",
"public_send",
"\"#{k}=\"",
",",
"new_value",
"}",
"@pdf",
".",
"transparent",
"(",
"transparency",
")",
"do",
"@pdf",
".",
"stroke",
"{",
"yield",
"}",
"end",
"old_values",
".",
"each",
"{",
"|",
"k",
",",
"old_value",
"|",
"@pdf",
".",
"public_send",
"\"#{k}=\"",
",",
"old_value",
"}",
"end"
]
| Convenience method to wrap a block by setting and unsetting a Prawn
property such as line_width. | [
"Convenience",
"method",
"to",
"wrap",
"a",
"block",
"by",
"setting",
"and",
"unsetting",
"a",
"Prawn",
"property",
"such",
"as",
"line_width",
"."
]
| c8fa02c185d41b880219bc72707b9d72a54b374b | https://github.com/Fullscreen/squid/blob/c8fa02c185d41b880219bc72707b9d72a54b374b/lib/squid/plotter.rb#L185-L193 | train |
poise/application | lib/poise_application/utils.rb | PoiseApplication.Utils.primary_group_for | def primary_group_for(user)
# Force a reload in case any users were created earlier in the run.
Etc.endpwent
Etc.endgrent
user = if user.is_a?(Integer)
Etc.getpwuid(user)
else
Etc.getpwnam(user.to_s)
end
Etc.getgrgid(user.gid).name
rescue ArgumentError
# One of the get* calls exploded. ¯\_(ツ)_/¯
user.to_s
end | ruby | def primary_group_for(user)
# Force a reload in case any users were created earlier in the run.
Etc.endpwent
Etc.endgrent
user = if user.is_a?(Integer)
Etc.getpwuid(user)
else
Etc.getpwnam(user.to_s)
end
Etc.getgrgid(user.gid).name
rescue ArgumentError
# One of the get* calls exploded. ¯\_(ツ)_/¯
user.to_s
end | [
"def",
"primary_group_for",
"(",
"user",
")",
"Etc",
".",
"endpwent",
"Etc",
".",
"endgrent",
"user",
"=",
"if",
"user",
".",
"is_a?",
"(",
"Integer",
")",
"Etc",
".",
"getpwuid",
"(",
"user",
")",
"else",
"Etc",
".",
"getpwnam",
"(",
"user",
".",
"to_s",
")",
"end",
"Etc",
".",
"getgrgid",
"(",
"user",
".",
"gid",
")",
".",
"name",
"rescue",
"ArgumentError",
"user",
".",
"to_s",
"end"
]
| Try to find the primary group name for a given user.
@param user [String, Integer] User to check, if given as an integer this
is used as a UID, otherwise it is the username.
@return [String]
@example
attribute(:group, kind_of: [String, Integer], default: lazy { PoiseApplication::Utils.primary_group_for(user) }) | [
"Try",
"to",
"find",
"the",
"primary",
"group",
"name",
"for",
"a",
"given",
"user",
"."
]
| 1c9d273210c5fbbde4329d8809368daeac4711ff | https://github.com/poise/application/blob/1c9d273210c5fbbde4329d8809368daeac4711ff/lib/poise_application/utils.rb#L36-L49 | train |
cmeerbeek/fluent-plugin-splunkhec | lib/fluent/plugin/out_splunkhec.rb | Fluent::Plugin.SplunkHECOutput.write | def write(chunk)
body = ''
chunk.msgpack_each {|(tag,time,record)|
# define index and sourcetype dynamically
begin
index = expand_param(@index, tag, time, record)
sourcetype = expand_param(@sourcetype, tag, time, record)
event_host = expand_param(@event_host, tag, time, record)
token = expand_param(@token, tag, time, record)
rescue => e
# handle dynamic parameters misconfigurations
router.emit_error_event(tag, time, record, e)
next
end
log.debug "routing event from #{event_host} to #{index} index"
log.debug "expanded token #{token}"
# Parse record to Splunk event format
case record
when Integer
event = record.to_s
when Hash
if @send_event_as_json
event = record.to_json
else
event = record.to_json.gsub("\"", %q(\\\"))
end
else
event = record
end
sourcetype = @sourcetype == 'tag' ? tag : @sourcetype
# Build body for the POST request
if !@usejson
event = record["time"]+ " " + record["message"].to_json.gsub(/^"|"$/,"")
body << '{"time":"'+ DateTime.parse(record["time"]).strftime("%Q") +'", "event":"' + event + '", "sourcetype" :"' + sourcetype + '", "source" :"' + @source + '", "index" :"' + index + '", "host" : "' + event_host + '"}'
elsif @send_event_as_json
body << '{"time" :' + time.to_s + ', "event" :' + event + ', "sourcetype" :"' + sourcetype + '", "source" :"' + source + '", "index" :"' + index + '", "host" : "' + event_host + '"}'
else
body << '{"time" :' + time.to_s + ', "event" :"' + event + '", "sourcetype" :"' + sourcetype + '", "source" :"' + source + '", "index" :"' + index + '", "host" : "' + event_host + '"}'
end
if @send_batched_events
body << "\n"
else
send_to_splunk(body, token)
body = ''
end
}
if @send_batched_events
send_to_splunk(body, token)
end
end | ruby | def write(chunk)
body = ''
chunk.msgpack_each {|(tag,time,record)|
# define index and sourcetype dynamically
begin
index = expand_param(@index, tag, time, record)
sourcetype = expand_param(@sourcetype, tag, time, record)
event_host = expand_param(@event_host, tag, time, record)
token = expand_param(@token, tag, time, record)
rescue => e
# handle dynamic parameters misconfigurations
router.emit_error_event(tag, time, record, e)
next
end
log.debug "routing event from #{event_host} to #{index} index"
log.debug "expanded token #{token}"
# Parse record to Splunk event format
case record
when Integer
event = record.to_s
when Hash
if @send_event_as_json
event = record.to_json
else
event = record.to_json.gsub("\"", %q(\\\"))
end
else
event = record
end
sourcetype = @sourcetype == 'tag' ? tag : @sourcetype
# Build body for the POST request
if !@usejson
event = record["time"]+ " " + record["message"].to_json.gsub(/^"|"$/,"")
body << '{"time":"'+ DateTime.parse(record["time"]).strftime("%Q") +'", "event":"' + event + '", "sourcetype" :"' + sourcetype + '", "source" :"' + @source + '", "index" :"' + index + '", "host" : "' + event_host + '"}'
elsif @send_event_as_json
body << '{"time" :' + time.to_s + ', "event" :' + event + ', "sourcetype" :"' + sourcetype + '", "source" :"' + source + '", "index" :"' + index + '", "host" : "' + event_host + '"}'
else
body << '{"time" :' + time.to_s + ', "event" :"' + event + '", "sourcetype" :"' + sourcetype + '", "source" :"' + source + '", "index" :"' + index + '", "host" : "' + event_host + '"}'
end
if @send_batched_events
body << "\n"
else
send_to_splunk(body, token)
body = ''
end
}
if @send_batched_events
send_to_splunk(body, token)
end
end | [
"def",
"write",
"(",
"chunk",
")",
"body",
"=",
"''",
"chunk",
".",
"msgpack_each",
"{",
"|",
"(",
"tag",
",",
"time",
",",
"record",
")",
"|",
"begin",
"index",
"=",
"expand_param",
"(",
"@index",
",",
"tag",
",",
"time",
",",
"record",
")",
"sourcetype",
"=",
"expand_param",
"(",
"@sourcetype",
",",
"tag",
",",
"time",
",",
"record",
")",
"event_host",
"=",
"expand_param",
"(",
"@event_host",
",",
"tag",
",",
"time",
",",
"record",
")",
"token",
"=",
"expand_param",
"(",
"@token",
",",
"tag",
",",
"time",
",",
"record",
")",
"rescue",
"=>",
"e",
"router",
".",
"emit_error_event",
"(",
"tag",
",",
"time",
",",
"record",
",",
"e",
")",
"next",
"end",
"log",
".",
"debug",
"\"routing event from #{event_host} to #{index} index\"",
"log",
".",
"debug",
"\"expanded token #{token}\"",
"case",
"record",
"when",
"Integer",
"event",
"=",
"record",
".",
"to_s",
"when",
"Hash",
"if",
"@send_event_as_json",
"event",
"=",
"record",
".",
"to_json",
"else",
"event",
"=",
"record",
".",
"to_json",
".",
"gsub",
"(",
"\"\\\"\"",
",",
"%q(\\\\\\\")",
")",
"end",
"else",
"event",
"=",
"record",
"end",
"sourcetype",
"=",
"@sourcetype",
"==",
"'tag'",
"?",
"tag",
":",
"@sourcetype",
"if",
"!",
"@usejson",
"event",
"=",
"record",
"[",
"\"time\"",
"]",
"+",
"\" \"",
"+",
"record",
"[",
"\"message\"",
"]",
".",
"to_json",
".",
"gsub",
"(",
"/",
"/",
",",
"\"\"",
")",
"body",
"<<",
"'{\"time\":\"'",
"+",
"DateTime",
".",
"parse",
"(",
"record",
"[",
"\"time\"",
"]",
")",
".",
"strftime",
"(",
"\"%Q\"",
")",
"+",
"'\", \"event\":\"'",
"+",
"event",
"+",
"'\", \"sourcetype\" :\"'",
"+",
"sourcetype",
"+",
"'\", \"source\" :\"'",
"+",
"@source",
"+",
"'\", \"index\" :\"'",
"+",
"index",
"+",
"'\", \"host\" : \"'",
"+",
"event_host",
"+",
"'\"}'",
"elsif",
"@send_event_as_json",
"body",
"<<",
"'{\"time\" :'",
"+",
"time",
".",
"to_s",
"+",
"', \"event\" :'",
"+",
"event",
"+",
"', \"sourcetype\" :\"'",
"+",
"sourcetype",
"+",
"'\", \"source\" :\"'",
"+",
"source",
"+",
"'\", \"index\" :\"'",
"+",
"index",
"+",
"'\", \"host\" : \"'",
"+",
"event_host",
"+",
"'\"}'",
"else",
"body",
"<<",
"'{\"time\" :'",
"+",
"time",
".",
"to_s",
"+",
"', \"event\" :\"'",
"+",
"event",
"+",
"'\", \"sourcetype\" :\"'",
"+",
"sourcetype",
"+",
"'\", \"source\" :\"'",
"+",
"source",
"+",
"'\", \"index\" :\"'",
"+",
"index",
"+",
"'\", \"host\" : \"'",
"+",
"event_host",
"+",
"'\"}'",
"end",
"if",
"@send_batched_events",
"body",
"<<",
"\"\\n\"",
"else",
"send_to_splunk",
"(",
"body",
",",
"token",
")",
"body",
"=",
"''",
"end",
"}",
"if",
"@send_batched_events",
"send_to_splunk",
"(",
"body",
",",
"token",
")",
"end",
"end"
]
| Loop through all records and sent them to Splunk | [
"Loop",
"through",
"all",
"records",
"and",
"sent",
"them",
"to",
"Splunk"
]
| 2382bf7e8f8e6dd92679e4060896434b0d7e3d1d | https://github.com/cmeerbeek/fluent-plugin-splunkhec/blob/2382bf7e8f8e6dd92679e4060896434b0d7e3d1d/lib/fluent/plugin/out_splunkhec.rb#L102-L157 | train |
poise/poise | lib/poise/utils.rb | Poise.Utils.find_cookbook_name | def find_cookbook_name(run_context, filename)
possibles = {}
Poise.debug("[Poise] Checking cookbook for #{filename.inspect}")
run_context.cookbook_collection.each do |name, ver|
# This special method is added by Halite::Gem#as_cookbook_version.
if ver.respond_to?(:halite_root)
# The join is there because ../poise-ruby/lib starts with ../poise so
# we want a trailing /.
if filename.start_with?(File.join(ver.halite_root, ''))
Poise.debug("[Poise] Found matching halite_root in #{name}: #{ver.halite_root.inspect}")
possibles[ver.halite_root] = name
end
else
Chef::CookbookVersion::COOKBOOK_SEGMENTS.each do |seg|
ver.segment_filenames(seg).each do |file|
if ::File::ALT_SEPARATOR
file = file.gsub(::File::ALT_SEPARATOR, ::File::SEPARATOR)
end
# Put this behind an environment variable because it is verbose
# even for normal debugging-level output.
Poise.debug("[Poise] Checking #{seg} in #{name}: #{file.inspect}")
if file == filename
Poise.debug("[Poise] Found matching #{seg} in #{name}: #{file.inspect}")
possibles[file] = name
end
end
end
end
end
raise Poise::Error.new("Unable to find cookbook for file #{filename.inspect}") if possibles.empty?
# Sort the items by matching path length, pick the name attached to the longest.
possibles.sort_by{|key, value| key.length }.last[1]
end | ruby | def find_cookbook_name(run_context, filename)
possibles = {}
Poise.debug("[Poise] Checking cookbook for #{filename.inspect}")
run_context.cookbook_collection.each do |name, ver|
# This special method is added by Halite::Gem#as_cookbook_version.
if ver.respond_to?(:halite_root)
# The join is there because ../poise-ruby/lib starts with ../poise so
# we want a trailing /.
if filename.start_with?(File.join(ver.halite_root, ''))
Poise.debug("[Poise] Found matching halite_root in #{name}: #{ver.halite_root.inspect}")
possibles[ver.halite_root] = name
end
else
Chef::CookbookVersion::COOKBOOK_SEGMENTS.each do |seg|
ver.segment_filenames(seg).each do |file|
if ::File::ALT_SEPARATOR
file = file.gsub(::File::ALT_SEPARATOR, ::File::SEPARATOR)
end
# Put this behind an environment variable because it is verbose
# even for normal debugging-level output.
Poise.debug("[Poise] Checking #{seg} in #{name}: #{file.inspect}")
if file == filename
Poise.debug("[Poise] Found matching #{seg} in #{name}: #{file.inspect}")
possibles[file] = name
end
end
end
end
end
raise Poise::Error.new("Unable to find cookbook for file #{filename.inspect}") if possibles.empty?
# Sort the items by matching path length, pick the name attached to the longest.
possibles.sort_by{|key, value| key.length }.last[1]
end | [
"def",
"find_cookbook_name",
"(",
"run_context",
",",
"filename",
")",
"possibles",
"=",
"{",
"}",
"Poise",
".",
"debug",
"(",
"\"[Poise] Checking cookbook for #{filename.inspect}\"",
")",
"run_context",
".",
"cookbook_collection",
".",
"each",
"do",
"|",
"name",
",",
"ver",
"|",
"if",
"ver",
".",
"respond_to?",
"(",
":halite_root",
")",
"if",
"filename",
".",
"start_with?",
"(",
"File",
".",
"join",
"(",
"ver",
".",
"halite_root",
",",
"''",
")",
")",
"Poise",
".",
"debug",
"(",
"\"[Poise] Found matching halite_root in #{name}: #{ver.halite_root.inspect}\"",
")",
"possibles",
"[",
"ver",
".",
"halite_root",
"]",
"=",
"name",
"end",
"else",
"Chef",
"::",
"CookbookVersion",
"::",
"COOKBOOK_SEGMENTS",
".",
"each",
"do",
"|",
"seg",
"|",
"ver",
".",
"segment_filenames",
"(",
"seg",
")",
".",
"each",
"do",
"|",
"file",
"|",
"if",
"::",
"File",
"::",
"ALT_SEPARATOR",
"file",
"=",
"file",
".",
"gsub",
"(",
"::",
"File",
"::",
"ALT_SEPARATOR",
",",
"::",
"File",
"::",
"SEPARATOR",
")",
"end",
"Poise",
".",
"debug",
"(",
"\"[Poise] Checking #{seg} in #{name}: #{file.inspect}\"",
")",
"if",
"file",
"==",
"filename",
"Poise",
".",
"debug",
"(",
"\"[Poise] Found matching #{seg} in #{name}: #{file.inspect}\"",
")",
"possibles",
"[",
"file",
"]",
"=",
"name",
"end",
"end",
"end",
"end",
"end",
"raise",
"Poise",
"::",
"Error",
".",
"new",
"(",
"\"Unable to find cookbook for file #{filename.inspect}\"",
")",
"if",
"possibles",
".",
"empty?",
"possibles",
".",
"sort_by",
"{",
"|",
"key",
",",
"value",
"|",
"key",
".",
"length",
"}",
".",
"last",
"[",
"1",
"]",
"end"
]
| Find the cookbook name for a given filename. The can used to find the
cookbook that corresponds to a caller of a file.
@param run_context [Chef::RunContext] Context to check.
@param filename [String] Absolute filename to check for.
@return [String]
@example
def my_thing
caller_filename = caller.first.split(':').first
cookbook = Poise::Utils.find_cookbook_name(run_context, caller_filename)
# ...
end | [
"Find",
"the",
"cookbook",
"name",
"for",
"a",
"given",
"filename",
".",
"The",
"can",
"used",
"to",
"find",
"the",
"cookbook",
"that",
"corresponds",
"to",
"a",
"caller",
"of",
"a",
"file",
"."
]
| 07c33d4f844cf6e97cf349a12f06448d0db9a8d2 | https://github.com/poise/poise/blob/07c33d4f844cf6e97cf349a12f06448d0db9a8d2/lib/poise/utils.rb#L40-L72 | train |
poise/poise | lib/poise/utils.rb | Poise.Utils.ancestor_send | def ancestor_send(obj, msg, *args, default: nil, ignore: [default])
# Class is a subclass of Module, if we get something else use its class.
obj = obj.class unless obj.is_a?(Module)
ancestors = []
if obj.respond_to?(:superclass)
# Check the superclass first if present.
ancestors << obj.superclass
end
# Make sure we don't check obj itself.
ancestors.concat(obj.ancestors.drop(1))
ancestors.each do |mod|
if mod.respond_to?(msg)
val = mod.send(msg, *args)
# If we get the default back, assume we should keep trying.
return val unless ignore.include?(val)
end
end
# Nothing valid found, use the default.
default
end | ruby | def ancestor_send(obj, msg, *args, default: nil, ignore: [default])
# Class is a subclass of Module, if we get something else use its class.
obj = obj.class unless obj.is_a?(Module)
ancestors = []
if obj.respond_to?(:superclass)
# Check the superclass first if present.
ancestors << obj.superclass
end
# Make sure we don't check obj itself.
ancestors.concat(obj.ancestors.drop(1))
ancestors.each do |mod|
if mod.respond_to?(msg)
val = mod.send(msg, *args)
# If we get the default back, assume we should keep trying.
return val unless ignore.include?(val)
end
end
# Nothing valid found, use the default.
default
end | [
"def",
"ancestor_send",
"(",
"obj",
",",
"msg",
",",
"*",
"args",
",",
"default",
":",
"nil",
",",
"ignore",
":",
"[",
"default",
"]",
")",
"obj",
"=",
"obj",
".",
"class",
"unless",
"obj",
".",
"is_a?",
"(",
"Module",
")",
"ancestors",
"=",
"[",
"]",
"if",
"obj",
".",
"respond_to?",
"(",
":superclass",
")",
"ancestors",
"<<",
"obj",
".",
"superclass",
"end",
"ancestors",
".",
"concat",
"(",
"obj",
".",
"ancestors",
".",
"drop",
"(",
"1",
")",
")",
"ancestors",
".",
"each",
"do",
"|",
"mod",
"|",
"if",
"mod",
".",
"respond_to?",
"(",
"msg",
")",
"val",
"=",
"mod",
".",
"send",
"(",
"msg",
",",
"*",
"args",
")",
"return",
"val",
"unless",
"ignore",
".",
"include?",
"(",
"val",
")",
"end",
"end",
"default",
"end"
]
| Try to find an ancestor to call a method on.
@since 2.2.3
@since 2.3.0
Added ignore parameter.
@param obj [Object] Self from the caller.
@param msg [Symbol] Method to try to call.
@param args [Array<Object>] Method arguments.
@param default [Object] Default return value if no valid ancestor exists.
@param ignore [Array<Object>] Return value to ignore when scanning ancesors.
@return [Object]
@example
val = @val || Poise::Utils.ancestor_send(self, :val) | [
"Try",
"to",
"find",
"an",
"ancestor",
"to",
"call",
"a",
"method",
"on",
"."
]
| 07c33d4f844cf6e97cf349a12f06448d0db9a8d2 | https://github.com/poise/poise/blob/07c33d4f844cf6e97cf349a12f06448d0db9a8d2/lib/poise/utils.rb#L87-L106 | train |
poise/poise | lib/poise/utils.rb | Poise.Utils.parameterized_module | def parameterized_module(mod, &block)
raise Poise::Error.new("Cannot parameterize an anonymous module") unless mod.name && !mod.name.empty?
parent_name_parts = mod.name.split(/::/)
# Grab the last piece which will be the method name.
mod_name = parent_name_parts.pop
# Find the enclosing module or class object.
parent = parent_name_parts.inject(Object) {|memo, name| memo.const_get(name) }
# Object is a special case since we need #define_method instead.
method_type = if parent == Object
:define_method
else
:define_singleton_method
end
# Scoping hack.
self_ = self
# Construct the method.
parent.send(method_type, mod_name) do |*args|
self_.send(:check_block_arity!, block, args)
# Create a new anonymous module to be returned from the method.
Module.new do
# Fake the name.
define_singleton_method(:name) do
super() || mod.name
end
# When the stub module gets included, activate our behaviors.
define_singleton_method(:included) do |klass|
super(klass)
klass.send(:include, mod)
klass.instance_exec(*args, &block)
end
end
end
end | ruby | def parameterized_module(mod, &block)
raise Poise::Error.new("Cannot parameterize an anonymous module") unless mod.name && !mod.name.empty?
parent_name_parts = mod.name.split(/::/)
# Grab the last piece which will be the method name.
mod_name = parent_name_parts.pop
# Find the enclosing module or class object.
parent = parent_name_parts.inject(Object) {|memo, name| memo.const_get(name) }
# Object is a special case since we need #define_method instead.
method_type = if parent == Object
:define_method
else
:define_singleton_method
end
# Scoping hack.
self_ = self
# Construct the method.
parent.send(method_type, mod_name) do |*args|
self_.send(:check_block_arity!, block, args)
# Create a new anonymous module to be returned from the method.
Module.new do
# Fake the name.
define_singleton_method(:name) do
super() || mod.name
end
# When the stub module gets included, activate our behaviors.
define_singleton_method(:included) do |klass|
super(klass)
klass.send(:include, mod)
klass.instance_exec(*args, &block)
end
end
end
end | [
"def",
"parameterized_module",
"(",
"mod",
",",
"&",
"block",
")",
"raise",
"Poise",
"::",
"Error",
".",
"new",
"(",
"\"Cannot parameterize an anonymous module\"",
")",
"unless",
"mod",
".",
"name",
"&&",
"!",
"mod",
".",
"name",
".",
"empty?",
"parent_name_parts",
"=",
"mod",
".",
"name",
".",
"split",
"(",
"/",
"/",
")",
"mod_name",
"=",
"parent_name_parts",
".",
"pop",
"parent",
"=",
"parent_name_parts",
".",
"inject",
"(",
"Object",
")",
"{",
"|",
"memo",
",",
"name",
"|",
"memo",
".",
"const_get",
"(",
"name",
")",
"}",
"method_type",
"=",
"if",
"parent",
"==",
"Object",
":define_method",
"else",
":define_singleton_method",
"end",
"self_",
"=",
"self",
"parent",
".",
"send",
"(",
"method_type",
",",
"mod_name",
")",
"do",
"|",
"*",
"args",
"|",
"self_",
".",
"send",
"(",
":check_block_arity!",
",",
"block",
",",
"args",
")",
"Module",
".",
"new",
"do",
"define_singleton_method",
"(",
":name",
")",
"do",
"super",
"(",
")",
"||",
"mod",
".",
"name",
"end",
"define_singleton_method",
"(",
":included",
")",
"do",
"|",
"klass",
"|",
"super",
"(",
"klass",
")",
"klass",
".",
"send",
"(",
":include",
",",
"mod",
")",
"klass",
".",
"instance_exec",
"(",
"*",
"args",
",",
"&",
"block",
")",
"end",
"end",
"end",
"end"
]
| Create a helper to invoke a module with some parameters.
@since 2.3.0
@param mod [Module] The module to wrap.
@param block [Proc] The module to implement to parameterization.
@return [void]
@example
module MyMixin
def self.my_mixin_name(name)
# ...
end
end
Poise::Utils.parameterized_module(MyMixin) do |name|
my_mixin_name(name)
end | [
"Create",
"a",
"helper",
"to",
"invoke",
"a",
"module",
"with",
"some",
"parameters",
"."
]
| 07c33d4f844cf6e97cf349a12f06448d0db9a8d2 | https://github.com/poise/poise/blob/07c33d4f844cf6e97cf349a12f06448d0db9a8d2/lib/poise/utils.rb#L124-L157 | train |
poise/poise | lib/poise/utils.rb | Poise.Utils.check_block_arity! | def check_block_arity!(block, args)
# Convert the block to a lambda-style proc. You can't make this shit up.
obj = Object.new
obj.define_singleton_method(:block, &block)
block = obj.method(:block).to_proc
# Check
required_args = block.arity < 0 ? ~block.arity : block.arity
if args.length < required_args || (block.arity >= 0 && args.length > block.arity)
raise ArgumentError.new("wrong number of arguments (#{args.length} for #{required_args}#{block.arity < 0 ? '+' : ''})")
end
end | ruby | def check_block_arity!(block, args)
# Convert the block to a lambda-style proc. You can't make this shit up.
obj = Object.new
obj.define_singleton_method(:block, &block)
block = obj.method(:block).to_proc
# Check
required_args = block.arity < 0 ? ~block.arity : block.arity
if args.length < required_args || (block.arity >= 0 && args.length > block.arity)
raise ArgumentError.new("wrong number of arguments (#{args.length} for #{required_args}#{block.arity < 0 ? '+' : ''})")
end
end | [
"def",
"check_block_arity!",
"(",
"block",
",",
"args",
")",
"obj",
"=",
"Object",
".",
"new",
"obj",
".",
"define_singleton_method",
"(",
":block",
",",
"&",
"block",
")",
"block",
"=",
"obj",
".",
"method",
"(",
":block",
")",
".",
"to_proc",
"required_args",
"=",
"block",
".",
"arity",
"<",
"0",
"?",
"~",
"block",
".",
"arity",
":",
"block",
".",
"arity",
"if",
"args",
".",
"length",
"<",
"required_args",
"||",
"(",
"block",
".",
"arity",
">=",
"0",
"&&",
"args",
".",
"length",
">",
"block",
".",
"arity",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"wrong number of arguments (#{args.length} for #{required_args}#{block.arity < 0 ? '+' : ''})\"",
")",
"end",
"end"
]
| Check that the given arguments match the given block. This is needed
because Ruby will nil-pad mismatched argspecs on blocks rather than error.
@since 2.3.0
@param block [Proc] Block to check.
@param args [Array<Object>] Arguments to check.
@return [void] | [
"Check",
"that",
"the",
"given",
"arguments",
"match",
"the",
"given",
"block",
".",
"This",
"is",
"needed",
"because",
"Ruby",
"will",
"nil",
"-",
"pad",
"mismatched",
"argspecs",
"on",
"blocks",
"rather",
"than",
"error",
"."
]
| 07c33d4f844cf6e97cf349a12f06448d0db9a8d2 | https://github.com/poise/poise/blob/07c33d4f844cf6e97cf349a12f06448d0db9a8d2/lib/poise/utils.rb#L168-L178 | train |
kontena/kong-client-ruby | lib/kong/consumer.rb | Kong.Consumer.oauth_apps | def oauth_apps
apps = []
response = client.get("#{@api_end_point}#{self.id}/oauth2") rescue nil
if response
response['data'].each do |attributes|
apps << Kong::OAuthApp.new(attributes)
end
end
apps
end | ruby | def oauth_apps
apps = []
response = client.get("#{@api_end_point}#{self.id}/oauth2") rescue nil
if response
response['data'].each do |attributes|
apps << Kong::OAuthApp.new(attributes)
end
end
apps
end | [
"def",
"oauth_apps",
"apps",
"=",
"[",
"]",
"response",
"=",
"client",
".",
"get",
"(",
"\"#{@api_end_point}#{self.id}/oauth2\"",
")",
"rescue",
"nil",
"if",
"response",
"response",
"[",
"'data'",
"]",
".",
"each",
"do",
"|",
"attributes",
"|",
"apps",
"<<",
"Kong",
"::",
"OAuthApp",
".",
"new",
"(",
"attributes",
")",
"end",
"end",
"apps",
"end"
]
| List OAuth applications
@return [Array<Kong::OAuthApp>] | [
"List",
"OAuth",
"applications"
]
| 028c8913388f46c7b3a41984f36687d147f74442 | https://github.com/kontena/kong-client-ruby/blob/028c8913388f46c7b3a41984f36687d147f74442/lib/kong/consumer.rb#L25-L34 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/bgp_af.rb | Cisco.RouterBgpAF.dampening_half_time | def dampening_half_time
return nil if dampening.nil? || dampening_routemap_configured?
if dampening.is_a?(Array) && !dampening.empty?
dampening[0].to_i
else
default_dampening_half_time
end
end | ruby | def dampening_half_time
return nil if dampening.nil? || dampening_routemap_configured?
if dampening.is_a?(Array) && !dampening.empty?
dampening[0].to_i
else
default_dampening_half_time
end
end | [
"def",
"dampening_half_time",
"return",
"nil",
"if",
"dampening",
".",
"nil?",
"||",
"dampening_routemap_configured?",
"if",
"dampening",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"!",
"dampening",
".",
"empty?",
"dampening",
"[",
"0",
"]",
".",
"to_i",
"else",
"default_dampening_half_time",
"end",
"end"
]
| For all of the following dampening getters, half_time, reuse_time,
suppress_time, and max_suppress_time, return nil if dampening
is not configured, but also return nil if a dampening routemap
is configured because they are mutually exclusive. | [
"For",
"all",
"of",
"the",
"following",
"dampening",
"getters",
"half_time",
"reuse_time",
"suppress_time",
"and",
"max_suppress_time",
"return",
"nil",
"if",
"dampening",
"is",
"not",
"configured",
"but",
"also",
"return",
"nil",
"if",
"a",
"dampening",
"routemap",
"is",
"configured",
"because",
"they",
"are",
"mutually",
"exclusive",
"."
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/bgp_af.rb#L229-L236 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/bgp_af.rb | Cisco.RouterBgpAF.method_missing | def method_missing(*args)
name = args[0].to_s
if args.length == 1 # Getter
if name =~ /^default_(.*)$/
config_get_default('bgp_af', Regexp.last_match(1))
else
config_get('bgp_af', name, @get_args)
end
elsif args.length == 2 && name =~ /^(.*)=$/ # Setter
set_args_keys(state: args[1] ? '' : 'no')
config_set('bgp_af', Regexp.last_match(1), @set_args)
else
super
end
end | ruby | def method_missing(*args)
name = args[0].to_s
if args.length == 1 # Getter
if name =~ /^default_(.*)$/
config_get_default('bgp_af', Regexp.last_match(1))
else
config_get('bgp_af', name, @get_args)
end
elsif args.length == 2 && name =~ /^(.*)=$/ # Setter
set_args_keys(state: args[1] ? '' : 'no')
config_set('bgp_af', Regexp.last_match(1), @set_args)
else
super
end
end | [
"def",
"method_missing",
"(",
"*",
"args",
")",
"name",
"=",
"args",
"[",
"0",
"]",
".",
"to_s",
"if",
"args",
".",
"length",
"==",
"1",
"if",
"name",
"=~",
"/",
"/",
"config_get_default",
"(",
"'bgp_af'",
",",
"Regexp",
".",
"last_match",
"(",
"1",
")",
")",
"else",
"config_get",
"(",
"'bgp_af'",
",",
"name",
",",
"@get_args",
")",
"end",
"elsif",
"args",
".",
"length",
"==",
"2",
"&&",
"name",
"=~",
"/",
"/",
"set_args_keys",
"(",
"state",
":",
"args",
"[",
"1",
"]",
"?",
"''",
":",
"'no'",
")",
"config_set",
"(",
"'bgp_af'",
",",
"Regexp",
".",
"last_match",
"(",
"1",
")",
",",
"@set_args",
")",
"else",
"super",
"end",
"end"
]
| Universal Getter, Default Getter, and Setter | [
"Universal",
"Getter",
"Default",
"Getter",
"and",
"Setter"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/bgp_af.rb#L508-L522 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/bgp_af.rb | Cisco.RouterBgpAF.respond_to? | def respond_to?(method_sym, _include_private=false)
name = method_sym.to_s
key = :getter?
if name =~ /^(.*)=$/
name = Regexp.last_match(1)
# Use table_map_set() to set these properties
return false if name == 'table_map' || name == 'table_map_filter'
key = :setter?
elsif name =~ /^default_(.*)$/
name = Regexp.last_match(1)
key = :default_value?
end
begin
ref = node.cmd_ref.lookup('bgp_af', name)
ref.send(key)
rescue IndexError
super
end
end | ruby | def respond_to?(method_sym, _include_private=false)
name = method_sym.to_s
key = :getter?
if name =~ /^(.*)=$/
name = Regexp.last_match(1)
# Use table_map_set() to set these properties
return false if name == 'table_map' || name == 'table_map_filter'
key = :setter?
elsif name =~ /^default_(.*)$/
name = Regexp.last_match(1)
key = :default_value?
end
begin
ref = node.cmd_ref.lookup('bgp_af', name)
ref.send(key)
rescue IndexError
super
end
end | [
"def",
"respond_to?",
"(",
"method_sym",
",",
"_include_private",
"=",
"false",
")",
"name",
"=",
"method_sym",
".",
"to_s",
"key",
"=",
":getter?",
"if",
"name",
"=~",
"/",
"/",
"name",
"=",
"Regexp",
".",
"last_match",
"(",
"1",
")",
"return",
"false",
"if",
"name",
"==",
"'table_map'",
"||",
"name",
"==",
"'table_map_filter'",
"key",
"=",
":setter?",
"elsif",
"name",
"=~",
"/",
"/",
"name",
"=",
"Regexp",
".",
"last_match",
"(",
"1",
")",
"key",
"=",
":default_value?",
"end",
"begin",
"ref",
"=",
"node",
".",
"cmd_ref",
".",
"lookup",
"(",
"'bgp_af'",
",",
"name",
")",
"ref",
".",
"send",
"(",
"key",
")",
"rescue",
"IndexError",
"super",
"end",
"end"
]
| Is the given name available in the YAML? | [
"Is",
"the",
"given",
"name",
"available",
"in",
"the",
"YAML?"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/bgp_af.rb#L525-L543 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/ace.rb | Cisco.Ace.ace_get | def ace_get
str = config_get('acl', 'ace', @get_args)
return nil if str.nil?
remark = Regexp.new('(?<seqno>\d+) remark (?<remark>.*)').match(str)
return remark unless remark.nil?
# specialized icmp protocol handling
return icmp_ace_get(str) if str.include?('icmp')
# rubocop:disable Metrics/LineLength
regexp = Regexp.new('(?<seqno>\d+) (?<action>\S+)'\
' *(?<proto>\d+|\S+)'\
' *(?<src_addr>any|host \S+|[:\.0-9a-fA-F]+ [:\.0-9a-fA-F]+|[:\.0-9a-fA-F]+\/\d+|addrgroup \S+)'\
' *(?<src_port>range \S+ \S+|(lt|eq|gt|neq|portgroup) \S+)?'\
' *(?<dst_addr>any|host \S+|[:\.0-9a-fA-F]+ [:\.0-9a-fA-F]+|[:\.0-9a-fA-F]+\/\d+|addrgroup \S+)'\
' *(?<dst_port>range \S+ \S+|(lt|eq|gt|neq|portgroup) \S+)?'\
' *(?<tcp_flags>(ack *|fin *|urg *|syn *|psh *|rst *)*)?'\
' *(?<established>established)?'\
' *(?<precedence>precedence \S+)?'\
' *(?<dscp>dscp \S+)?'\
' *(?<time_range>time-range \S+)?'\
' *(?<packet_length>packet-length (range \d+ \d+|(lt|eq|gt|neq) \d+))?'\
' *(?<ttl>ttl \d+)?'\
' *(?<http_method>http-method (\d+|connect|delete|get|head|post|put|trace))?'\
' *(?<tcp_option_length>tcp-option-length \d+)?'\
' *(?<redirect>redirect \S+)?'\
' *(?<log>log)?')
# rubocop:enable Metrics/LineLength
regexp.match(str)
end | ruby | def ace_get
str = config_get('acl', 'ace', @get_args)
return nil if str.nil?
remark = Regexp.new('(?<seqno>\d+) remark (?<remark>.*)').match(str)
return remark unless remark.nil?
# specialized icmp protocol handling
return icmp_ace_get(str) if str.include?('icmp')
# rubocop:disable Metrics/LineLength
regexp = Regexp.new('(?<seqno>\d+) (?<action>\S+)'\
' *(?<proto>\d+|\S+)'\
' *(?<src_addr>any|host \S+|[:\.0-9a-fA-F]+ [:\.0-9a-fA-F]+|[:\.0-9a-fA-F]+\/\d+|addrgroup \S+)'\
' *(?<src_port>range \S+ \S+|(lt|eq|gt|neq|portgroup) \S+)?'\
' *(?<dst_addr>any|host \S+|[:\.0-9a-fA-F]+ [:\.0-9a-fA-F]+|[:\.0-9a-fA-F]+\/\d+|addrgroup \S+)'\
' *(?<dst_port>range \S+ \S+|(lt|eq|gt|neq|portgroup) \S+)?'\
' *(?<tcp_flags>(ack *|fin *|urg *|syn *|psh *|rst *)*)?'\
' *(?<established>established)?'\
' *(?<precedence>precedence \S+)?'\
' *(?<dscp>dscp \S+)?'\
' *(?<time_range>time-range \S+)?'\
' *(?<packet_length>packet-length (range \d+ \d+|(lt|eq|gt|neq) \d+))?'\
' *(?<ttl>ttl \d+)?'\
' *(?<http_method>http-method (\d+|connect|delete|get|head|post|put|trace))?'\
' *(?<tcp_option_length>tcp-option-length \d+)?'\
' *(?<redirect>redirect \S+)?'\
' *(?<log>log)?')
# rubocop:enable Metrics/LineLength
regexp.match(str)
end | [
"def",
"ace_get",
"str",
"=",
"config_get",
"(",
"'acl'",
",",
"'ace'",
",",
"@get_args",
")",
"return",
"nil",
"if",
"str",
".",
"nil?",
"remark",
"=",
"Regexp",
".",
"new",
"(",
"'(?<seqno>\\d+) remark (?<remark>.*)'",
")",
".",
"match",
"(",
"str",
")",
"return",
"remark",
"unless",
"remark",
".",
"nil?",
"return",
"icmp_ace_get",
"(",
"str",
")",
"if",
"str",
".",
"include?",
"(",
"'icmp'",
")",
"regexp",
"=",
"Regexp",
".",
"new",
"(",
"'(?<seqno>\\d+) (?<action>\\S+)'",
"' *(?<proto>\\d+|\\S+)'",
"' *(?<src_addr>any|host \\S+|[:\\.0-9a-fA-F]+ [:\\.0-9a-fA-F]+|[:\\.0-9a-fA-F]+\\/\\d+|addrgroup \\S+)'",
"' *(?<src_port>range \\S+ \\S+|(lt|eq|gt|neq|portgroup) \\S+)?'",
"' *(?<dst_addr>any|host \\S+|[:\\.0-9a-fA-F]+ [:\\.0-9a-fA-F]+|[:\\.0-9a-fA-F]+\\/\\d+|addrgroup \\S+)'",
"' *(?<dst_port>range \\S+ \\S+|(lt|eq|gt|neq|portgroup) \\S+)?'",
"' *(?<tcp_flags>(ack *|fin *|urg *|syn *|psh *|rst *)*)?'",
"' *(?<established>established)?'",
"' *(?<precedence>precedence \\S+)?'",
"' *(?<dscp>dscp \\S+)?'",
"' *(?<time_range>time-range \\S+)?'",
"' *(?<packet_length>packet-length (range \\d+ \\d+|(lt|eq|gt|neq) \\d+))?'",
"' *(?<ttl>ttl \\d+)?'",
"' *(?<http_method>http-method (\\d+|connect|delete|get|head|post|put|trace))?'",
"' *(?<tcp_option_length>tcp-option-length \\d+)?'",
"' *(?<redirect>redirect \\S+)?'",
"' *(?<log>log)?'",
")",
"regexp",
".",
"match",
"(",
"str",
")",
"end"
]
| common ace getter | [
"common",
"ace",
"getter"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/ace.rb#L70-L100 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/ace.rb | Cisco.Ace.icmp_ace_get | def icmp_ace_get(str)
# rubocop:disable Metrics/LineLength
# fragments is nvgen at a different location than all other
# proto_option so get rid of it so as not to mess up other fields
str.sub!('fragments ', '')
regexp = Regexp.new('(?<seqno>\d+) (?<action>\S+)'\
' *(?<proto>\d+|\S+)'\
' *(?<src_addr>any|host \S+|[:\.0-9a-fA-F]+ [:\.0-9a-fA-F]+|[:\.0-9a-fA-F]+\/\d+|addrgroup \S+)'\
' *(?<dst_addr>any|host \S+|[:\.0-9a-fA-F]+ [:\.0-9a-fA-F]+|[:\.0-9a-fA-F]+\/\d+|addrgroup \S+)'\
' *(?<proto_option>\S+)?'\
' *(?<precedence>precedence \S+)?'\
' *(?<dscp>dscp \S+)?'\
' *(?<time_range>time-range \S+)?'\
' *(?<packet_length>packet-length (range \d+ \d+|(lt|eq|gt|neq) \d+))?'\
' *(?<ttl>ttl \d+)?'\
' *(?<vlan>vlan \d+)?'\
' *(?<set_erspan_gre_proto>set-erspan-gre-proto \d+)?'\
' *(?<set_erspan_dscp>set-erspan-dscp \d+)?'\
' *(?<redirect>redirect \S+)?')
regexp_no_proto_option = Regexp.new('(?<seqno>\d+) (?<action>\S+)'\
' *(?<proto>\d+|\S+)'\
' *(?<src_addr>any|host \S+|[:\.0-9a-fA-F]+ [:\.0-9a-fA-F]+|[:\.0-9a-fA-F]+\/\d+|addrgroup \S+)'\
' *(?<dst_addr>any|host \S+|[:\.0-9a-fA-F]+ [:\.0-9a-fA-F]+|[:\.0-9a-fA-F]+\/\d+|addrgroup \S+)'\
' *(?<precedence>precedence \S+)?'\
' *(?<dscp>dscp \S+)?'\
' *(?<time_range>time-range \S+)?'\
' *(?<packet_length>packet-length (range \d+ \d+|(lt|eq|gt|neq) \d+))?'\
' *(?<ttl>ttl \d+)?'\
' *(?<vlan>vlan \d+)?'\
' *(?<set_erspan_gre_proto>set-erspan-gre-proto \d+)?'\
' *(?<set_erspan_dscp>set-erspan-dscp \d+)?'\
' *(?<redirect>redirect \S+)?')
temp = regexp.match(str)
po = temp[:proto_option]
if po.nil?
return temp
# redirect can be proto_option or an actual redirect to interface
elsif po.strip.match(/redirect$/)
if str.match(/Ethernet|port-channel/)
# if proto_option is given as redirect and also redirect to intf
# we need to do extra processing
return temp if check_redirect_repeat(str)
return regexp_no_proto_option.match(str)
end
# the reserved keywords check
elsif po.strip.match(/precedence$|dscp$|time-range$|packet-length$|ttl$|vlan$|set-erspan-gre-proto$|set-erspan-dscp$|log$/)
return regexp_no_proto_option.match(str)
else
return temp
end
# rubocop:enable Metrics/LineLength
end | ruby | def icmp_ace_get(str)
# rubocop:disable Metrics/LineLength
# fragments is nvgen at a different location than all other
# proto_option so get rid of it so as not to mess up other fields
str.sub!('fragments ', '')
regexp = Regexp.new('(?<seqno>\d+) (?<action>\S+)'\
' *(?<proto>\d+|\S+)'\
' *(?<src_addr>any|host \S+|[:\.0-9a-fA-F]+ [:\.0-9a-fA-F]+|[:\.0-9a-fA-F]+\/\d+|addrgroup \S+)'\
' *(?<dst_addr>any|host \S+|[:\.0-9a-fA-F]+ [:\.0-9a-fA-F]+|[:\.0-9a-fA-F]+\/\d+|addrgroup \S+)'\
' *(?<proto_option>\S+)?'\
' *(?<precedence>precedence \S+)?'\
' *(?<dscp>dscp \S+)?'\
' *(?<time_range>time-range \S+)?'\
' *(?<packet_length>packet-length (range \d+ \d+|(lt|eq|gt|neq) \d+))?'\
' *(?<ttl>ttl \d+)?'\
' *(?<vlan>vlan \d+)?'\
' *(?<set_erspan_gre_proto>set-erspan-gre-proto \d+)?'\
' *(?<set_erspan_dscp>set-erspan-dscp \d+)?'\
' *(?<redirect>redirect \S+)?')
regexp_no_proto_option = Regexp.new('(?<seqno>\d+) (?<action>\S+)'\
' *(?<proto>\d+|\S+)'\
' *(?<src_addr>any|host \S+|[:\.0-9a-fA-F]+ [:\.0-9a-fA-F]+|[:\.0-9a-fA-F]+\/\d+|addrgroup \S+)'\
' *(?<dst_addr>any|host \S+|[:\.0-9a-fA-F]+ [:\.0-9a-fA-F]+|[:\.0-9a-fA-F]+\/\d+|addrgroup \S+)'\
' *(?<precedence>precedence \S+)?'\
' *(?<dscp>dscp \S+)?'\
' *(?<time_range>time-range \S+)?'\
' *(?<packet_length>packet-length (range \d+ \d+|(lt|eq|gt|neq) \d+))?'\
' *(?<ttl>ttl \d+)?'\
' *(?<vlan>vlan \d+)?'\
' *(?<set_erspan_gre_proto>set-erspan-gre-proto \d+)?'\
' *(?<set_erspan_dscp>set-erspan-dscp \d+)?'\
' *(?<redirect>redirect \S+)?')
temp = regexp.match(str)
po = temp[:proto_option]
if po.nil?
return temp
# redirect can be proto_option or an actual redirect to interface
elsif po.strip.match(/redirect$/)
if str.match(/Ethernet|port-channel/)
# if proto_option is given as redirect and also redirect to intf
# we need to do extra processing
return temp if check_redirect_repeat(str)
return regexp_no_proto_option.match(str)
end
# the reserved keywords check
elsif po.strip.match(/precedence$|dscp$|time-range$|packet-length$|ttl$|vlan$|set-erspan-gre-proto$|set-erspan-dscp$|log$/)
return regexp_no_proto_option.match(str)
else
return temp
end
# rubocop:enable Metrics/LineLength
end | [
"def",
"icmp_ace_get",
"(",
"str",
")",
"str",
".",
"sub!",
"(",
"'fragments '",
",",
"''",
")",
"regexp",
"=",
"Regexp",
".",
"new",
"(",
"'(?<seqno>\\d+) (?<action>\\S+)'",
"' *(?<proto>\\d+|\\S+)'",
"' *(?<src_addr>any|host \\S+|[:\\.0-9a-fA-F]+ [:\\.0-9a-fA-F]+|[:\\.0-9a-fA-F]+\\/\\d+|addrgroup \\S+)'",
"' *(?<dst_addr>any|host \\S+|[:\\.0-9a-fA-F]+ [:\\.0-9a-fA-F]+|[:\\.0-9a-fA-F]+\\/\\d+|addrgroup \\S+)'",
"' *(?<proto_option>\\S+)?'",
"' *(?<precedence>precedence \\S+)?'",
"' *(?<dscp>dscp \\S+)?'",
"' *(?<time_range>time-range \\S+)?'",
"' *(?<packet_length>packet-length (range \\d+ \\d+|(lt|eq|gt|neq) \\d+))?'",
"' *(?<ttl>ttl \\d+)?'",
"' *(?<vlan>vlan \\d+)?'",
"' *(?<set_erspan_gre_proto>set-erspan-gre-proto \\d+)?'",
"' *(?<set_erspan_dscp>set-erspan-dscp \\d+)?'",
"' *(?<redirect>redirect \\S+)?'",
")",
"regexp_no_proto_option",
"=",
"Regexp",
".",
"new",
"(",
"'(?<seqno>\\d+) (?<action>\\S+)'",
"' *(?<proto>\\d+|\\S+)'",
"' *(?<src_addr>any|host \\S+|[:\\.0-9a-fA-F]+ [:\\.0-9a-fA-F]+|[:\\.0-9a-fA-F]+\\/\\d+|addrgroup \\S+)'",
"' *(?<dst_addr>any|host \\S+|[:\\.0-9a-fA-F]+ [:\\.0-9a-fA-F]+|[:\\.0-9a-fA-F]+\\/\\d+|addrgroup \\S+)'",
"' *(?<precedence>precedence \\S+)?'",
"' *(?<dscp>dscp \\S+)?'",
"' *(?<time_range>time-range \\S+)?'",
"' *(?<packet_length>packet-length (range \\d+ \\d+|(lt|eq|gt|neq) \\d+))?'",
"' *(?<ttl>ttl \\d+)?'",
"' *(?<vlan>vlan \\d+)?'",
"' *(?<set_erspan_gre_proto>set-erspan-gre-proto \\d+)?'",
"' *(?<set_erspan_dscp>set-erspan-dscp \\d+)?'",
"' *(?<redirect>redirect \\S+)?'",
")",
"temp",
"=",
"regexp",
".",
"match",
"(",
"str",
")",
"po",
"=",
"temp",
"[",
":proto_option",
"]",
"if",
"po",
".",
"nil?",
"return",
"temp",
"elsif",
"po",
".",
"strip",
".",
"match",
"(",
"/",
"/",
")",
"if",
"str",
".",
"match",
"(",
"/",
"/",
")",
"return",
"temp",
"if",
"check_redirect_repeat",
"(",
"str",
")",
"return",
"regexp_no_proto_option",
".",
"match",
"(",
"str",
")",
"end",
"elsif",
"po",
".",
"strip",
".",
"match",
"(",
"/",
"/",
")",
"return",
"regexp_no_proto_option",
".",
"match",
"(",
"str",
")",
"else",
"return",
"temp",
"end",
"end"
]
| icmp ace getter | [
"icmp",
"ace",
"getter"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/ace.rb#L103-L154 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/interface.rb | Cisco.Interface.hsrp_delay_minimum= | def hsrp_delay_minimum=(val)
Feature.hsrp_enable if val
config_set('interface', 'hsrp_delay', name: @name,
minimum: 'minimum', min: val, reload: '', rel: '')
end | ruby | def hsrp_delay_minimum=(val)
Feature.hsrp_enable if val
config_set('interface', 'hsrp_delay', name: @name,
minimum: 'minimum', min: val, reload: '', rel: '')
end | [
"def",
"hsrp_delay_minimum",
"=",
"(",
"val",
")",
"Feature",
".",
"hsrp_enable",
"if",
"val",
"config_set",
"(",
"'interface'",
",",
"'hsrp_delay'",
",",
"name",
":",
"@name",
",",
"minimum",
":",
"'minimum'",
",",
"min",
":",
"val",
",",
"reload",
":",
"''",
",",
"rel",
":",
"''",
")",
"end"
]
| hsrp delay minimum and reload are in the same CLI
but both can be set independent of each other | [
"hsrp",
"delay",
"minimum",
"and",
"reload",
"are",
"in",
"the",
"same",
"CLI",
"but",
"both",
"can",
"be",
"set",
"independent",
"of",
"each",
"other"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/interface.rb#L337-L341 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/stp_global.rb | Cisco.StpGlobal.bd_total_range_with_vlans | def bd_total_range_with_vlans
hash = Vlan.vlans
arr = []
hash.keys.each do |id|
arr << id.to_i
end
Utils.array_to_str(arr)
ret_arr = []
ret_arr << Utils.array_to_str(arr)
end | ruby | def bd_total_range_with_vlans
hash = Vlan.vlans
arr = []
hash.keys.each do |id|
arr << id.to_i
end
Utils.array_to_str(arr)
ret_arr = []
ret_arr << Utils.array_to_str(arr)
end | [
"def",
"bd_total_range_with_vlans",
"hash",
"=",
"Vlan",
".",
"vlans",
"arr",
"=",
"[",
"]",
"hash",
".",
"keys",
".",
"each",
"do",
"|",
"id",
"|",
"arr",
"<<",
"id",
".",
"to_i",
"end",
"Utils",
".",
"array_to_str",
"(",
"arr",
")",
"ret_arr",
"=",
"[",
"]",
"ret_arr",
"<<",
"Utils",
".",
"array_to_str",
"(",
"arr",
")",
"end"
]
| bridge-domain and vlans are mutually exclusive
so when there are vlans, we need to remove them
from the bd range while restting | [
"bridge",
"-",
"domain",
"and",
"vlans",
"are",
"mutually",
"exclusive",
"so",
"when",
"there",
"are",
"vlans",
"we",
"need",
"to",
"remove",
"them",
"from",
"the",
"bd",
"range",
"while",
"restting"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/stp_global.rb#L652-L661 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/itd_device_group_node.rb | Cisco.ItdDeviceGroupNode.hs_weight | def hs_weight(hs, wt)
if hs != hot_standby && hot_standby == default_hot_standby
self.lweight = wt unless weight == wt
self.lhot_standby = hs
elsif hs != hot_standby && hot_standby != default_hot_standby
self.lhot_standby = hs
self.lweight = wt unless weight == wt
elsif wt != weight && weight == default_weight
self.lweight = wt
elsif wt != weight && weight != default_weight
self.lweight = wt
end
set_args_keys_default
end | ruby | def hs_weight(hs, wt)
if hs != hot_standby && hot_standby == default_hot_standby
self.lweight = wt unless weight == wt
self.lhot_standby = hs
elsif hs != hot_standby && hot_standby != default_hot_standby
self.lhot_standby = hs
self.lweight = wt unless weight == wt
elsif wt != weight && weight == default_weight
self.lweight = wt
elsif wt != weight && weight != default_weight
self.lweight = wt
end
set_args_keys_default
end | [
"def",
"hs_weight",
"(",
"hs",
",",
"wt",
")",
"if",
"hs",
"!=",
"hot_standby",
"&&",
"hot_standby",
"==",
"default_hot_standby",
"self",
".",
"lweight",
"=",
"wt",
"unless",
"weight",
"==",
"wt",
"self",
".",
"lhot_standby",
"=",
"hs",
"elsif",
"hs",
"!=",
"hot_standby",
"&&",
"hot_standby",
"!=",
"default_hot_standby",
"self",
".",
"lhot_standby",
"=",
"hs",
"self",
".",
"lweight",
"=",
"wt",
"unless",
"weight",
"==",
"wt",
"elsif",
"wt",
"!=",
"weight",
"&&",
"weight",
"==",
"default_weight",
"self",
".",
"lweight",
"=",
"wt",
"elsif",
"wt",
"!=",
"weight",
"&&",
"weight",
"!=",
"default_weight",
"self",
".",
"lweight",
"=",
"wt",
"end",
"set_args_keys_default",
"end"
]
| Call this for setting hot_standby and weight together because
the CLI is pretty weird and it accepts these params in a very
particular way and they cannot even be reset unless proper
order is followed | [
"Call",
"this",
"for",
"setting",
"hot_standby",
"and",
"weight",
"together",
"because",
"the",
"CLI",
"is",
"pretty",
"weird",
"and",
"it",
"accepts",
"these",
"params",
"in",
"a",
"very",
"particular",
"way",
"and",
"they",
"cannot",
"even",
"be",
"reset",
"unless",
"proper",
"order",
"is",
"followed"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/itd_device_group_node.rb#L125-L138 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/bridge_domain_vni.rb | Cisco.BridgeDomainVNI.curr_bd_vni_hash | def curr_bd_vni_hash
final_bd_vni = {}
curr_vni = config_get('bridge_domain_vni', 'member_vni')
curr_bd_vni = config_get('bridge_domain_vni', 'member_vni_bd')
return final_bd_vni if curr_vni.empty? || curr_bd_vni.empty?
curr_vni_list = BridgeDomainVNI.string_to_array(curr_vni)
curr_bd_vni_list = BridgeDomainVNI.string_to_array(curr_bd_vni)
hash_map = Hash[curr_bd_vni_list.zip(curr_vni_list.map)]
@bd_ids_list.each do |bd|
final_bd_vni[bd.to_i] = hash_map[bd.to_i] if hash_map.key?(bd.to_i)
end
final_bd_vni
end | ruby | def curr_bd_vni_hash
final_bd_vni = {}
curr_vni = config_get('bridge_domain_vni', 'member_vni')
curr_bd_vni = config_get('bridge_domain_vni', 'member_vni_bd')
return final_bd_vni if curr_vni.empty? || curr_bd_vni.empty?
curr_vni_list = BridgeDomainVNI.string_to_array(curr_vni)
curr_bd_vni_list = BridgeDomainVNI.string_to_array(curr_bd_vni)
hash_map = Hash[curr_bd_vni_list.zip(curr_vni_list.map)]
@bd_ids_list.each do |bd|
final_bd_vni[bd.to_i] = hash_map[bd.to_i] if hash_map.key?(bd.to_i)
end
final_bd_vni
end | [
"def",
"curr_bd_vni_hash",
"final_bd_vni",
"=",
"{",
"}",
"curr_vni",
"=",
"config_get",
"(",
"'bridge_domain_vni'",
",",
"'member_vni'",
")",
"curr_bd_vni",
"=",
"config_get",
"(",
"'bridge_domain_vni'",
",",
"'member_vni_bd'",
")",
"return",
"final_bd_vni",
"if",
"curr_vni",
".",
"empty?",
"||",
"curr_bd_vni",
".",
"empty?",
"curr_vni_list",
"=",
"BridgeDomainVNI",
".",
"string_to_array",
"(",
"curr_vni",
")",
"curr_bd_vni_list",
"=",
"BridgeDomainVNI",
".",
"string_to_array",
"(",
"curr_bd_vni",
")",
"hash_map",
"=",
"Hash",
"[",
"curr_bd_vni_list",
".",
"zip",
"(",
"curr_vni_list",
".",
"map",
")",
"]",
"@bd_ids_list",
".",
"each",
"do",
"|",
"bd",
"|",
"final_bd_vni",
"[",
"bd",
".",
"to_i",
"]",
"=",
"hash_map",
"[",
"bd",
".",
"to_i",
"]",
"if",
"hash_map",
".",
"key?",
"(",
"bd",
".",
"to_i",
")",
"end",
"final_bd_vni",
"end"
]
| Example clis;
system bridge-domain 101-200
bridge-domain 101-200
bridge-domain 101-110,120,141-145,180
member vni 6001-6011,5041-5044,8000,9000
config_get('bridge_domain_vni', 'member_vni')
will get the current member vni in this case
6001-6011,5041-5044,8000,9000
config_get('bridge_domain_vni', 'member_vni_bd')
will get the current bd's mapped to member vni in this case
101-110,120,141-145,180
The @bd_ids_list which is created when the BridgeDomainVNI object is
initialized which could be 101-110 bd range.
hash_map will have 101=>6001,102=>6002...120=>6011,141=>5041...180=>9000
And the final_bd_vni hash will be based of the initialized list
101=>6001,102=>6002,103=>6003....110=>6010 only. | [
"Example",
"clis",
";",
"system",
"bridge",
"-",
"domain",
"101",
"-",
"200",
"bridge",
"-",
"domain",
"101",
"-",
"200",
"bridge",
"-",
"domain",
"101",
"-",
"110",
"120",
"141",
"-",
"145",
"180",
"member",
"vni",
"6001",
"-",
"6011",
"5041",
"-",
"5044",
"8000",
"9000"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/bridge_domain_vni.rb#L88-L102 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/node.rb | Cisco.Node.massage_structured | def massage_structured(get_args, ref)
# Nothing to do unless nxapi_structured.
return [get_args, ref] unless
ref.hash['get_data_format'] == :nxapi_structured
# The CmdRef object will contain a get_value Array with 2 values.
# The first value is the key to identify the correct row in the table
# of structured output and the second is the key to identify the data
# to retrieve.
#
# Example: Get vlanshowbr-vlanname in the row that contains a specific
# vlan_id.
# "get_value"=>["vlanshowbr-vlanid-utf <vlan_id>", "vlanshowbr-vlanname"]
#
# TBD: Why do we need to check is_a?(Array) here?
if ref.hash['get_value'].is_a?(Array) && ref.hash['get_value'].size >= 2
# Replace the get_value hash entry with the value after any tokens
# specified in the yaml file have been replaced and set get_args[:value]
# to nil so that the structured table data can be retrieved properly.
ref.hash['get_value'] = get_args[:value]
ref.hash['drill_down'] = true
get_args[:value] = nil
cache_flush
end
[get_args, ref]
end | ruby | def massage_structured(get_args, ref)
# Nothing to do unless nxapi_structured.
return [get_args, ref] unless
ref.hash['get_data_format'] == :nxapi_structured
# The CmdRef object will contain a get_value Array with 2 values.
# The first value is the key to identify the correct row in the table
# of structured output and the second is the key to identify the data
# to retrieve.
#
# Example: Get vlanshowbr-vlanname in the row that contains a specific
# vlan_id.
# "get_value"=>["vlanshowbr-vlanid-utf <vlan_id>", "vlanshowbr-vlanname"]
#
# TBD: Why do we need to check is_a?(Array) here?
if ref.hash['get_value'].is_a?(Array) && ref.hash['get_value'].size >= 2
# Replace the get_value hash entry with the value after any tokens
# specified in the yaml file have been replaced and set get_args[:value]
# to nil so that the structured table data can be retrieved properly.
ref.hash['get_value'] = get_args[:value]
ref.hash['drill_down'] = true
get_args[:value] = nil
cache_flush
end
[get_args, ref]
end | [
"def",
"massage_structured",
"(",
"get_args",
",",
"ref",
")",
"return",
"[",
"get_args",
",",
"ref",
"]",
"unless",
"ref",
".",
"hash",
"[",
"'get_data_format'",
"]",
"==",
":nxapi_structured",
"if",
"ref",
".",
"hash",
"[",
"'get_value'",
"]",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"ref",
".",
"hash",
"[",
"'get_value'",
"]",
".",
"size",
">=",
"2",
"ref",
".",
"hash",
"[",
"'get_value'",
"]",
"=",
"get_args",
"[",
":value",
"]",
"ref",
".",
"hash",
"[",
"'drill_down'",
"]",
"=",
"true",
"get_args",
"[",
":value",
"]",
"=",
"nil",
"cache_flush",
"end",
"[",
"get_args",
",",
"ref",
"]",
"end"
]
| The yaml file may specifiy an Array as the get_value to drill down into
nxapi_structured table output. The table may contain multiple rows but
only one of the rows has the interesting data. | [
"The",
"yaml",
"file",
"may",
"specifiy",
"an",
"Array",
"as",
"the",
"get_value",
"to",
"drill",
"down",
"into",
"nxapi_structured",
"table",
"output",
".",
"The",
"table",
"may",
"contain",
"multiple",
"rows",
"but",
"only",
"one",
"of",
"the",
"rows",
"has",
"the",
"interesting",
"data",
"."
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/node.rb#L70-L95 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/node.rb | Cisco.Node.massage | def massage(value, ref)
Cisco::Logger.debug "Massaging '#{value}' (#{value.inspect})"
value = drill_down_structured(value, ref)
if value.is_a?(Array) && !ref.multiple
fail "Expected zero/one value but got '#{value}'" if value.length > 1
value = value[0]
end
if (value.nil? || value.to_s.empty?) &&
ref.default_value? && ref.auto_default
Cisco::Logger.debug "Default: #{ref.default_value}"
return ref.default_value
end
if ref.multiple && ref.hash['get_data_format'] == :nxapi_structured
return value if value.nil?
value = [value.to_s] if value.is_a?(String) || value.is_a?(Fixnum)
end
return value unless ref.kind
value = massage_kind(value, ref)
Cisco::Logger.debug "Massaged to '#{value}'"
value
end | ruby | def massage(value, ref)
Cisco::Logger.debug "Massaging '#{value}' (#{value.inspect})"
value = drill_down_structured(value, ref)
if value.is_a?(Array) && !ref.multiple
fail "Expected zero/one value but got '#{value}'" if value.length > 1
value = value[0]
end
if (value.nil? || value.to_s.empty?) &&
ref.default_value? && ref.auto_default
Cisco::Logger.debug "Default: #{ref.default_value}"
return ref.default_value
end
if ref.multiple && ref.hash['get_data_format'] == :nxapi_structured
return value if value.nil?
value = [value.to_s] if value.is_a?(String) || value.is_a?(Fixnum)
end
return value unless ref.kind
value = massage_kind(value, ref)
Cisco::Logger.debug "Massaged to '#{value}'"
value
end | [
"def",
"massage",
"(",
"value",
",",
"ref",
")",
"Cisco",
"::",
"Logger",
".",
"debug",
"\"Massaging '#{value}' (#{value.inspect})\"",
"value",
"=",
"drill_down_structured",
"(",
"value",
",",
"ref",
")",
"if",
"value",
".",
"is_a?",
"(",
"Array",
")",
"&&",
"!",
"ref",
".",
"multiple",
"fail",
"\"Expected zero/one value but got '#{value}'\"",
"if",
"value",
".",
"length",
">",
"1",
"value",
"=",
"value",
"[",
"0",
"]",
"end",
"if",
"(",
"value",
".",
"nil?",
"||",
"value",
".",
"to_s",
".",
"empty?",
")",
"&&",
"ref",
".",
"default_value?",
"&&",
"ref",
".",
"auto_default",
"Cisco",
"::",
"Logger",
".",
"debug",
"\"Default: #{ref.default_value}\"",
"return",
"ref",
".",
"default_value",
"end",
"if",
"ref",
".",
"multiple",
"&&",
"ref",
".",
"hash",
"[",
"'get_data_format'",
"]",
"==",
":nxapi_structured",
"return",
"value",
"if",
"value",
".",
"nil?",
"value",
"=",
"[",
"value",
".",
"to_s",
"]",
"if",
"value",
".",
"is_a?",
"(",
"String",
")",
"||",
"value",
".",
"is_a?",
"(",
"Fixnum",
")",
"end",
"return",
"value",
"unless",
"ref",
".",
"kind",
"value",
"=",
"massage_kind",
"(",
"value",
",",
"ref",
")",
"Cisco",
"::",
"Logger",
".",
"debug",
"\"Massaged to '#{value}'\"",
"value",
"end"
]
| Attempt to massage the given value into the format specified by the
given CmdRef object. | [
"Attempt",
"to",
"massage",
"the",
"given",
"value",
"into",
"the",
"format",
"specified",
"by",
"the",
"given",
"CmdRef",
"object",
"."
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/node.rb#L140-L160 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/command_reference.rb | Cisco.CommandReference.lookup | def lookup(feature, name)
value = @hash[feature]
value = value[name] if value.is_a? Hash
fail IndexError, "No CmdRef defined for #{feature}, #{name}" if value.nil?
value
end | ruby | def lookup(feature, name)
value = @hash[feature]
value = value[name] if value.is_a? Hash
fail IndexError, "No CmdRef defined for #{feature}, #{name}" if value.nil?
value
end | [
"def",
"lookup",
"(",
"feature",
",",
"name",
")",
"value",
"=",
"@hash",
"[",
"feature",
"]",
"value",
"=",
"value",
"[",
"name",
"]",
"if",
"value",
".",
"is_a?",
"Hash",
"fail",
"IndexError",
",",
"\"No CmdRef defined for #{feature}, #{name}\"",
"if",
"value",
".",
"nil?",
"value",
"end"
]
| Get the command reference | [
"Get",
"the",
"command",
"reference"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/command_reference.rb#L424-L429 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/command_reference.rb | Cisco.CommandReference.validate_yaml | def validate_yaml(node, filename, depth=0, parents=nil)
return unless node && (mapping?(node) || node.children)
# Psych wraps everything in a Document instance, which we ignore.
unless node.class.ancestors.any? { |name| /Document/ =~ name.to_s }
depth += 1
end
debug "Validating #{node.class} at depth #{depth}"
# No special validation for non-mapping nodes - just recurse
unless mapping?(node)
node.children.each do |child|
validate_yaml(child, filename, depth, parents)
end
return
end
# For Mappings, we validate more extensively:
# 1. no duplicate keys are allowed (Psych doesn't catch this)
# 2. Features must be listed in alphabetical order for maintainability
# Take advantage of our known YAML structure to assign labels by depth
label = %w(feature name param).fetch(depth, 'key')
# Get the key nodes and value nodes under this mapping
key_children, val_children = get_keys_values_from_map(node)
# Get an array of key names
key_arr = key_children.map(&:value)
# Make sure no duplicate key names.
# If searching from the start of the array finds a name at one index,
# but searching from the end of the array finds it at a different one,
# then we have a duplicate.
dup = key_arr.detect { |e| key_arr.index(e) != key_arr.rindex(e) }
if dup
msg = "Duplicate #{label} '#{dup}'#{parents} in #{filename}!"
fail msg
end
# Enforce alphabetical ordering of features (only).
# We can extend this later to enforce ordering of names if desired
# by checking at depth 2 as well.
if depth == 1
last_key = nil
key_arr.each do |key|
if last_key && key < last_key
fail "features out of order in #{filename}: (#{last_key} > #{key})"
end
last_key = key
end
end
# Recurse to the children. We get a little fancy here so as to be able
# to provide more meaningful debug/error messages, such as:
# Duplicate param 'default_value' under feature 'foo', name 'bar'
key_children.zip(val_children).each do |key_node, val_node|
if parents
new_parents = parents + ", #{label} '#{key_node.value}'"
else
new_parents = " under #{label} '#{key_node.value}'"
end
validate_yaml(key_node, filename, depth, new_parents) # unnecessary?
validate_yaml(val_node, filename, depth, new_parents)
end
end | ruby | def validate_yaml(node, filename, depth=0, parents=nil)
return unless node && (mapping?(node) || node.children)
# Psych wraps everything in a Document instance, which we ignore.
unless node.class.ancestors.any? { |name| /Document/ =~ name.to_s }
depth += 1
end
debug "Validating #{node.class} at depth #{depth}"
# No special validation for non-mapping nodes - just recurse
unless mapping?(node)
node.children.each do |child|
validate_yaml(child, filename, depth, parents)
end
return
end
# For Mappings, we validate more extensively:
# 1. no duplicate keys are allowed (Psych doesn't catch this)
# 2. Features must be listed in alphabetical order for maintainability
# Take advantage of our known YAML structure to assign labels by depth
label = %w(feature name param).fetch(depth, 'key')
# Get the key nodes and value nodes under this mapping
key_children, val_children = get_keys_values_from_map(node)
# Get an array of key names
key_arr = key_children.map(&:value)
# Make sure no duplicate key names.
# If searching from the start of the array finds a name at one index,
# but searching from the end of the array finds it at a different one,
# then we have a duplicate.
dup = key_arr.detect { |e| key_arr.index(e) != key_arr.rindex(e) }
if dup
msg = "Duplicate #{label} '#{dup}'#{parents} in #{filename}!"
fail msg
end
# Enforce alphabetical ordering of features (only).
# We can extend this later to enforce ordering of names if desired
# by checking at depth 2 as well.
if depth == 1
last_key = nil
key_arr.each do |key|
if last_key && key < last_key
fail "features out of order in #{filename}: (#{last_key} > #{key})"
end
last_key = key
end
end
# Recurse to the children. We get a little fancy here so as to be able
# to provide more meaningful debug/error messages, such as:
# Duplicate param 'default_value' under feature 'foo', name 'bar'
key_children.zip(val_children).each do |key_node, val_node|
if parents
new_parents = parents + ", #{label} '#{key_node.value}'"
else
new_parents = " under #{label} '#{key_node.value}'"
end
validate_yaml(key_node, filename, depth, new_parents) # unnecessary?
validate_yaml(val_node, filename, depth, new_parents)
end
end | [
"def",
"validate_yaml",
"(",
"node",
",",
"filename",
",",
"depth",
"=",
"0",
",",
"parents",
"=",
"nil",
")",
"return",
"unless",
"node",
"&&",
"(",
"mapping?",
"(",
"node",
")",
"||",
"node",
".",
"children",
")",
"unless",
"node",
".",
"class",
".",
"ancestors",
".",
"any?",
"{",
"|",
"name",
"|",
"/",
"/",
"=~",
"name",
".",
"to_s",
"}",
"depth",
"+=",
"1",
"end",
"debug",
"\"Validating #{node.class} at depth #{depth}\"",
"unless",
"mapping?",
"(",
"node",
")",
"node",
".",
"children",
".",
"each",
"do",
"|",
"child",
"|",
"validate_yaml",
"(",
"child",
",",
"filename",
",",
"depth",
",",
"parents",
")",
"end",
"return",
"end",
"label",
"=",
"%w(",
"feature",
"name",
"param",
")",
".",
"fetch",
"(",
"depth",
",",
"'key'",
")",
"key_children",
",",
"val_children",
"=",
"get_keys_values_from_map",
"(",
"node",
")",
"key_arr",
"=",
"key_children",
".",
"map",
"(",
"&",
":value",
")",
"dup",
"=",
"key_arr",
".",
"detect",
"{",
"|",
"e",
"|",
"key_arr",
".",
"index",
"(",
"e",
")",
"!=",
"key_arr",
".",
"rindex",
"(",
"e",
")",
"}",
"if",
"dup",
"msg",
"=",
"\"Duplicate #{label} '#{dup}'#{parents} in #{filename}!\"",
"fail",
"msg",
"end",
"if",
"depth",
"==",
"1",
"last_key",
"=",
"nil",
"key_arr",
".",
"each",
"do",
"|",
"key",
"|",
"if",
"last_key",
"&&",
"key",
"<",
"last_key",
"fail",
"\"features out of order in #{filename}: (#{last_key} > #{key})\"",
"end",
"last_key",
"=",
"key",
"end",
"end",
"key_children",
".",
"zip",
"(",
"val_children",
")",
".",
"each",
"do",
"|",
"key_node",
",",
"val_node",
"|",
"if",
"parents",
"new_parents",
"=",
"parents",
"+",
"\", #{label} '#{key_node.value}'\"",
"else",
"new_parents",
"=",
"\" under #{label} '#{key_node.value}'\"",
"end",
"validate_yaml",
"(",
"key_node",
",",
"filename",
",",
"depth",
",",
"new_parents",
")",
"validate_yaml",
"(",
"val_node",
",",
"filename",
",",
"depth",
",",
"new_parents",
")",
"end",
"end"
]
| Validate the YAML node tree before converting it into Ruby
data structures.
@raise RuntimeError if the node tree is not valid by our constraints.
@param node Node to be validated, then recurse to its children.
@param filename File that YAML was parsed from, for messages
@param depth Depth into the node tree
@param parents String describing parents of this node, for messages | [
"Validate",
"the",
"YAML",
"node",
"tree",
"before",
"converting",
"it",
"into",
"Ruby",
"data",
"structures",
"."
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/command_reference.rb#L621-L684 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/command_reference.rb | Cisco.CommandReference.load_yaml | def load_yaml(yaml_file)
fail "File #{yaml_file} doesn't exist." unless File.exist?(yaml_file)
# Parse YAML file into a tree of nodes
# Psych::SyntaxError doesn't inherit from StandardError in some versions,
# so we want to explicitly catch it if using Psych.
rescue_errors = [::StandardError, ::Psych::SyntaxError]
yaml_parsed = File.open(yaml_file, 'r') do |f|
begin
YAML.parse(f)
rescue *rescue_errors => e
raise "unable to parse #{yaml_file}: #{e}"
end
end
return {} unless yaml_parsed
# Validate the node tree
validate_yaml(yaml_parsed, yaml_file)
# If validation passed, convert the node tree to a Ruby Hash.
yaml_parsed.transform
end | ruby | def load_yaml(yaml_file)
fail "File #{yaml_file} doesn't exist." unless File.exist?(yaml_file)
# Parse YAML file into a tree of nodes
# Psych::SyntaxError doesn't inherit from StandardError in some versions,
# so we want to explicitly catch it if using Psych.
rescue_errors = [::StandardError, ::Psych::SyntaxError]
yaml_parsed = File.open(yaml_file, 'r') do |f|
begin
YAML.parse(f)
rescue *rescue_errors => e
raise "unable to parse #{yaml_file}: #{e}"
end
end
return {} unless yaml_parsed
# Validate the node tree
validate_yaml(yaml_parsed, yaml_file)
# If validation passed, convert the node tree to a Ruby Hash.
yaml_parsed.transform
end | [
"def",
"load_yaml",
"(",
"yaml_file",
")",
"fail",
"\"File #{yaml_file} doesn't exist.\"",
"unless",
"File",
".",
"exist?",
"(",
"yaml_file",
")",
"rescue_errors",
"=",
"[",
"::",
"StandardError",
",",
"::",
"Psych",
"::",
"SyntaxError",
"]",
"yaml_parsed",
"=",
"File",
".",
"open",
"(",
"yaml_file",
",",
"'r'",
")",
"do",
"|",
"f",
"|",
"begin",
"YAML",
".",
"parse",
"(",
"f",
")",
"rescue",
"*",
"rescue_errors",
"=>",
"e",
"raise",
"\"unable to parse #{yaml_file}: #{e}\"",
"end",
"end",
"return",
"{",
"}",
"unless",
"yaml_parsed",
"validate_yaml",
"(",
"yaml_parsed",
",",
"yaml_file",
")",
"yaml_parsed",
".",
"transform",
"end"
]
| Read in yaml file.
The expectation is that a file corresponds to a feature | [
"Read",
"in",
"yaml",
"file",
".",
"The",
"expectation",
"is",
"that",
"a",
"file",
"corresponds",
"to",
"a",
"feature"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/command_reference.rb#L689-L707 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/interface_ospf.rb | Cisco.InterfaceOspf.message_digest_key_set | def message_digest_key_set(keyid, algtype, enctype, enc)
current_keyid = message_digest_key_id
if keyid == default_message_digest_key_id && current_keyid != keyid
config_set('interface_ospf', 'message_digest_key_set',
@interface.name, 'no', current_keyid,
'', '', '')
elsif keyid != default_message_digest_key_id
fail TypeError unless enc.is_a?(String)
fail ArgumentError unless enc.length > 0
enctype = Encryption.symbol_to_cli(enctype)
config_set('interface_ospf', 'message_digest_key_set',
@interface.name, '', keyid, algtype, enctype, enc)
end
end | ruby | def message_digest_key_set(keyid, algtype, enctype, enc)
current_keyid = message_digest_key_id
if keyid == default_message_digest_key_id && current_keyid != keyid
config_set('interface_ospf', 'message_digest_key_set',
@interface.name, 'no', current_keyid,
'', '', '')
elsif keyid != default_message_digest_key_id
fail TypeError unless enc.is_a?(String)
fail ArgumentError unless enc.length > 0
enctype = Encryption.symbol_to_cli(enctype)
config_set('interface_ospf', 'message_digest_key_set',
@interface.name, '', keyid, algtype, enctype, enc)
end
end | [
"def",
"message_digest_key_set",
"(",
"keyid",
",",
"algtype",
",",
"enctype",
",",
"enc",
")",
"current_keyid",
"=",
"message_digest_key_id",
"if",
"keyid",
"==",
"default_message_digest_key_id",
"&&",
"current_keyid",
"!=",
"keyid",
"config_set",
"(",
"'interface_ospf'",
",",
"'message_digest_key_set'",
",",
"@interface",
".",
"name",
",",
"'no'",
",",
"current_keyid",
",",
"''",
",",
"''",
",",
"''",
")",
"elsif",
"keyid",
"!=",
"default_message_digest_key_id",
"fail",
"TypeError",
"unless",
"enc",
".",
"is_a?",
"(",
"String",
")",
"fail",
"ArgumentError",
"unless",
"enc",
".",
"length",
">",
"0",
"enctype",
"=",
"Encryption",
".",
"symbol_to_cli",
"(",
"enctype",
")",
"config_set",
"(",
"'interface_ospf'",
",",
"'message_digest_key_set'",
",",
"@interface",
".",
"name",
",",
"''",
",",
"keyid",
",",
"algtype",
",",
"enctype",
",",
"enc",
")",
"end",
"end"
]
| interface %s
%s ip ospf message-digest-key %d %s %d %s | [
"interface",
"%s",
"%s",
"ip",
"ospf",
"message",
"-",
"digest",
"-",
"key",
"%d",
"%s",
"%d",
"%s"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/interface_ospf.rb#L160-L173 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/interface_ospf.rb | Cisco.InterfaceOspf.bfd | def bfd
val = config_get('interface_ospf', 'bfd', @interface.name)
return if val.nil?
val.include?('disable') ? false : true
end | ruby | def bfd
val = config_get('interface_ospf', 'bfd', @interface.name)
return if val.nil?
val.include?('disable') ? false : true
end | [
"def",
"bfd",
"val",
"=",
"config_get",
"(",
"'interface_ospf'",
",",
"'bfd'",
",",
"@interface",
".",
"name",
")",
"return",
"if",
"val",
".",
"nil?",
"val",
".",
"include?",
"(",
"'disable'",
")",
"?",
"false",
":",
"true",
"end"
]
| CLI can be either of the following or none
ip ospf bfd
ip ospf bfd disable | [
"CLI",
"can",
"be",
"either",
"of",
"the",
"following",
"or",
"none",
"ip",
"ospf",
"bfd",
"ip",
"ospf",
"bfd",
"disable"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/interface_ospf.rb#L226-L230 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/interface_ospf.rb | Cisco.InterfaceOspf.bfd= | def bfd=(val)
return if val == bfd
Feature.bfd_enable
state = (val == default_bfd) ? 'no' : ''
disable = val ? '' : 'disable'
config_set('interface_ospf', 'bfd', @interface.name,
state, disable)
end | ruby | def bfd=(val)
return if val == bfd
Feature.bfd_enable
state = (val == default_bfd) ? 'no' : ''
disable = val ? '' : 'disable'
config_set('interface_ospf', 'bfd', @interface.name,
state, disable)
end | [
"def",
"bfd",
"=",
"(",
"val",
")",
"return",
"if",
"val",
"==",
"bfd",
"Feature",
".",
"bfd_enable",
"state",
"=",
"(",
"val",
"==",
"default_bfd",
")",
"?",
"'no'",
":",
"''",
"disable",
"=",
"val",
"?",
"''",
":",
"'disable'",
"config_set",
"(",
"'interface_ospf'",
",",
"'bfd'",
",",
"@interface",
".",
"name",
",",
"state",
",",
"disable",
")",
"end"
]
| interface %s
%s ip ospf bfd %s | [
"interface",
"%s",
"%s",
"ip",
"ospf",
"bfd",
"%s"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/interface_ospf.rb#L234-L241 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/interface_ospf.rb | Cisco.InterfaceOspf.network_type= | def network_type=(type)
no_cmd = (type == default_network_type) ? 'no' : ''
network = (type == default_network_type) ? '' : type
network = 'point-to-point' if type.to_s == 'p2p'
config_set('interface_ospf', 'network_type', @interface.name,
no_cmd, network)
end | ruby | def network_type=(type)
no_cmd = (type == default_network_type) ? 'no' : ''
network = (type == default_network_type) ? '' : type
network = 'point-to-point' if type.to_s == 'p2p'
config_set('interface_ospf', 'network_type', @interface.name,
no_cmd, network)
end | [
"def",
"network_type",
"=",
"(",
"type",
")",
"no_cmd",
"=",
"(",
"type",
"==",
"default_network_type",
")",
"?",
"'no'",
":",
"''",
"network",
"=",
"(",
"type",
"==",
"default_network_type",
")",
"?",
"''",
":",
"type",
"network",
"=",
"'point-to-point'",
"if",
"type",
".",
"to_s",
"==",
"'p2p'",
"config_set",
"(",
"'interface_ospf'",
",",
"'network_type'",
",",
"@interface",
".",
"name",
",",
"no_cmd",
",",
"network",
")",
"end"
]
| interface %s
%s ip ospf network %s | [
"interface",
"%s",
"%s",
"ip",
"ospf",
"network",
"%s"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/interface_ospf.rb#L281-L287 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/interface_ospf.rb | Cisco.InterfaceOspf.passive_interface= | def passive_interface=(enable)
fail TypeError unless enable == true || enable == false
config_set('interface_ospf', 'passive_interface', @interface.name,
enable ? '' : 'no')
end | ruby | def passive_interface=(enable)
fail TypeError unless enable == true || enable == false
config_set('interface_ospf', 'passive_interface', @interface.name,
enable ? '' : 'no')
end | [
"def",
"passive_interface",
"=",
"(",
"enable",
")",
"fail",
"TypeError",
"unless",
"enable",
"==",
"true",
"||",
"enable",
"==",
"false",
"config_set",
"(",
"'interface_ospf'",
",",
"'passive_interface'",
",",
"@interface",
".",
"name",
",",
"enable",
"?",
"''",
":",
"'no'",
")",
"end"
]
| interface %s
%s ip ospf passive-interface | [
"interface",
"%s",
"%s",
"ip",
"ospf",
"passive",
"-",
"interface"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/interface_ospf.rb#L299-L303 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/interface_ospf.rb | Cisco.InterfaceOspf.priority= | def priority=(val)
no_cmd = (val == default_priority) ? 'no' : ''
pri = (val == default_priority) ? '' : val
config_set('interface_ospf', 'priority',
@interface.name, no_cmd, pri)
end | ruby | def priority=(val)
no_cmd = (val == default_priority) ? 'no' : ''
pri = (val == default_priority) ? '' : val
config_set('interface_ospf', 'priority',
@interface.name, no_cmd, pri)
end | [
"def",
"priority",
"=",
"(",
"val",
")",
"no_cmd",
"=",
"(",
"val",
"==",
"default_priority",
")",
"?",
"'no'",
":",
"''",
"pri",
"=",
"(",
"val",
"==",
"default_priority",
")",
"?",
"''",
":",
"val",
"config_set",
"(",
"'interface_ospf'",
",",
"'priority'",
",",
"@interface",
".",
"name",
",",
"no_cmd",
",",
"pri",
")",
"end"
]
| interface %s
ip ospf priority %d | [
"interface",
"%s",
"ip",
"ospf",
"priority",
"%d"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/interface_ospf.rb#L311-L316 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/interface_ospf.rb | Cisco.InterfaceOspf.transmit_delay= | def transmit_delay=(val)
no_cmd = (val == default_transmit_delay) ? 'no' : ''
delay = (val == default_transmit_delay) ? '' : val
config_set('interface_ospf', 'transmit_delay',
@interface.name, no_cmd, delay)
end | ruby | def transmit_delay=(val)
no_cmd = (val == default_transmit_delay) ? 'no' : ''
delay = (val == default_transmit_delay) ? '' : val
config_set('interface_ospf', 'transmit_delay',
@interface.name, no_cmd, delay)
end | [
"def",
"transmit_delay",
"=",
"(",
"val",
")",
"no_cmd",
"=",
"(",
"val",
"==",
"default_transmit_delay",
")",
"?",
"'no'",
":",
"''",
"delay",
"=",
"(",
"val",
"==",
"default_transmit_delay",
")",
"?",
"''",
":",
"val",
"config_set",
"(",
"'interface_ospf'",
",",
"'transmit_delay'",
",",
"@interface",
".",
"name",
",",
"no_cmd",
",",
"delay",
")",
"end"
]
| interface %s
ip ospf transmit-delay %d | [
"interface",
"%s",
"ip",
"ospf",
"transmit",
"-",
"delay",
"%d"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/interface_ospf.rb#L343-L348 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/bfd_global.rb | Cisco.BfdGlobal.destroy | def destroy
return unless Feature.bfd_enabled?
[:interval,
:ipv4_interval,
:ipv6_interval,
:fabricpath_interval,
:echo_interface,
:echo_rx_interval,
:ipv4_echo_rx_interval,
:ipv6_echo_rx_interval,
:fabricpath_vlan,
:slow_timer,
:ipv4_slow_timer,
:ipv6_slow_timer,
:fabricpath_slow_timer,
:startup_timer,
].each do |prop|
send("#{prop}=", send("default_#{prop}")) if
send prop
end
set_args_keys_default
end | ruby | def destroy
return unless Feature.bfd_enabled?
[:interval,
:ipv4_interval,
:ipv6_interval,
:fabricpath_interval,
:echo_interface,
:echo_rx_interval,
:ipv4_echo_rx_interval,
:ipv6_echo_rx_interval,
:fabricpath_vlan,
:slow_timer,
:ipv4_slow_timer,
:ipv6_slow_timer,
:fabricpath_slow_timer,
:startup_timer,
].each do |prop|
send("#{prop}=", send("default_#{prop}")) if
send prop
end
set_args_keys_default
end | [
"def",
"destroy",
"return",
"unless",
"Feature",
".",
"bfd_enabled?",
"[",
":interval",
",",
":ipv4_interval",
",",
":ipv6_interval",
",",
":fabricpath_interval",
",",
":echo_interface",
",",
":echo_rx_interval",
",",
":ipv4_echo_rx_interval",
",",
":ipv6_echo_rx_interval",
",",
":fabricpath_vlan",
",",
":slow_timer",
",",
":ipv4_slow_timer",
",",
":ipv6_slow_timer",
",",
":fabricpath_slow_timer",
",",
":startup_timer",
",",
"]",
".",
"each",
"do",
"|",
"prop",
"|",
"send",
"(",
"\"#{prop}=\"",
",",
"send",
"(",
"\"default_#{prop}\"",
")",
")",
"if",
"send",
"prop",
"end",
"set_args_keys_default",
"end"
]
| Reset everything back to default | [
"Reset",
"everything",
"back",
"to",
"default"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/bfd_global.rb#L34-L55 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/vtp.rb | Cisco.Vtp.domain= | def domain=(d)
d = d.to_s
fail ArgumentError unless d.length.between?(1, MAX_VTP_DOMAIN_NAME_SIZE)
config_set('vtp', 'domain', domain: d)
end | ruby | def domain=(d)
d = d.to_s
fail ArgumentError unless d.length.between?(1, MAX_VTP_DOMAIN_NAME_SIZE)
config_set('vtp', 'domain', domain: d)
end | [
"def",
"domain",
"=",
"(",
"d",
")",
"d",
"=",
"d",
".",
"to_s",
"fail",
"ArgumentError",
"unless",
"d",
".",
"length",
".",
"between?",
"(",
"1",
",",
"MAX_VTP_DOMAIN_NAME_SIZE",
")",
"config_set",
"(",
"'vtp'",
",",
"'domain'",
",",
"domain",
":",
"d",
")",
"end"
]
| Set vtp domain name | [
"Set",
"vtp",
"domain",
"name"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/vtp.rb#L55-L59 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/vtp.rb | Cisco.Vtp.password | def password
# Unfortunately nxapi returns "\\" when the password is not set
password = config_get('vtp', 'password') if Feature.vtp_enabled?
return '' if password.nil? || password == '\\'
password
rescue Cisco::RequestNotSupported => e
# Certain platforms generate a Cisco::RequestNotSupported when the
# vtp password is not set. We catch this specific error and
# return empty '' for the password.
return '' if e.message[/Structured output not supported/]
end | ruby | def password
# Unfortunately nxapi returns "\\" when the password is not set
password = config_get('vtp', 'password') if Feature.vtp_enabled?
return '' if password.nil? || password == '\\'
password
rescue Cisco::RequestNotSupported => e
# Certain platforms generate a Cisco::RequestNotSupported when the
# vtp password is not set. We catch this specific error and
# return empty '' for the password.
return '' if e.message[/Structured output not supported/]
end | [
"def",
"password",
"password",
"=",
"config_get",
"(",
"'vtp'",
",",
"'password'",
")",
"if",
"Feature",
".",
"vtp_enabled?",
"return",
"''",
"if",
"password",
".",
"nil?",
"||",
"password",
"==",
"'\\\\'",
"password",
"rescue",
"Cisco",
"::",
"RequestNotSupported",
"=>",
"e",
"return",
"''",
"if",
"e",
".",
"message",
"[",
"/",
"/",
"]",
"end"
]
| Get vtp password | [
"Get",
"vtp",
"password"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/vtp.rb#L62-L72 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/vtp.rb | Cisco.Vtp.password= | def password=(password)
fail TypeError if password.nil?
fail TypeError unless password.is_a? String
fail ArgumentError if password.length > MAX_VTP_PASSWORD_SIZE
Feature.vtp_enable
state = (password == default_password) ? 'no' : ''
config_set('vtp', 'password', state: state, password: password)
end | ruby | def password=(password)
fail TypeError if password.nil?
fail TypeError unless password.is_a? String
fail ArgumentError if password.length > MAX_VTP_PASSWORD_SIZE
Feature.vtp_enable
state = (password == default_password) ? 'no' : ''
config_set('vtp', 'password', state: state, password: password)
end | [
"def",
"password",
"=",
"(",
"password",
")",
"fail",
"TypeError",
"if",
"password",
".",
"nil?",
"fail",
"TypeError",
"unless",
"password",
".",
"is_a?",
"String",
"fail",
"ArgumentError",
"if",
"password",
".",
"length",
">",
"MAX_VTP_PASSWORD_SIZE",
"Feature",
".",
"vtp_enable",
"state",
"=",
"(",
"password",
"==",
"default_password",
")",
"?",
"'no'",
":",
"''",
"config_set",
"(",
"'vtp'",
",",
"'password'",
",",
"state",
":",
"state",
",",
"password",
":",
"password",
")",
"end"
]
| Set vtp password | [
"Set",
"vtp",
"password"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/vtp.rb#L75-L82 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/vtp.rb | Cisco.Vtp.filename= | def filename=(uri)
fail TypeError if uri.nil?
Feature.vtp_enable
uri = uri.to_s
state = uri.empty? ? 'no' : ''
config_set('vtp', 'filename', state: state, uri: uri)
end | ruby | def filename=(uri)
fail TypeError if uri.nil?
Feature.vtp_enable
uri = uri.to_s
state = uri.empty? ? 'no' : ''
config_set('vtp', 'filename', state: state, uri: uri)
end | [
"def",
"filename",
"=",
"(",
"uri",
")",
"fail",
"TypeError",
"if",
"uri",
".",
"nil?",
"Feature",
".",
"vtp_enable",
"uri",
"=",
"uri",
".",
"to_s",
"state",
"=",
"uri",
".",
"empty?",
"?",
"'no'",
":",
"''",
"config_set",
"(",
"'vtp'",
",",
"'filename'",
",",
"state",
":",
"state",
",",
"uri",
":",
"uri",
")",
"end"
]
| Set vtp filename | [
"Set",
"vtp",
"filename"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/vtp.rb#L96-L102 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/bgp.rb | Cisco.RouterBgp.graceful_restart= | def graceful_restart=(enable)
if platform == :ios_xr && @vrf != 'default'
fail Cisco::UnsupportedError.new('bgp', 'graceful_restart', 'set',
'graceful_restart is not ' \
'configurable ' \
'on a per-VRF basis on IOS XR')
end
@set_args[:state] = (enable ? '' : 'no')
config_set('bgp', 'graceful_restart', @set_args)
set_args_keys_default
end | ruby | def graceful_restart=(enable)
if platform == :ios_xr && @vrf != 'default'
fail Cisco::UnsupportedError.new('bgp', 'graceful_restart', 'set',
'graceful_restart is not ' \
'configurable ' \
'on a per-VRF basis on IOS XR')
end
@set_args[:state] = (enable ? '' : 'no')
config_set('bgp', 'graceful_restart', @set_args)
set_args_keys_default
end | [
"def",
"graceful_restart",
"=",
"(",
"enable",
")",
"if",
"platform",
"==",
":ios_xr",
"&&",
"@vrf",
"!=",
"'default'",
"fail",
"Cisco",
"::",
"UnsupportedError",
".",
"new",
"(",
"'bgp'",
",",
"'graceful_restart'",
",",
"'set'",
",",
"'graceful_restart is not '",
"'configurable '",
"'on a per-VRF basis on IOS XR'",
")",
"end",
"@set_args",
"[",
":state",
"]",
"=",
"(",
"enable",
"?",
"''",
":",
"'no'",
")",
"config_set",
"(",
"'bgp'",
",",
"'graceful_restart'",
",",
"@set_args",
")",
"set_args_keys_default",
"end"
]
| Graceful Restart Setters | [
"Graceful",
"Restart",
"Setters"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/bgp.rb#L632-L642 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/bgp.rb | Cisco.RouterBgp.timer_bgp_keepalive_hold_set | def timer_bgp_keepalive_hold_set(keepalive, hold)
if keepalive == default_timer_bgp_keepalive &&
hold == default_timer_bgp_holdtime
@set_args[:state] = 'no'
@set_args[:keepalive] = keepalive
@set_args[:hold] = hold
else
@set_args[:state] = ''
@set_args[:keepalive] = keepalive
@set_args[:hold] = hold
end
config_set('bgp', 'timer_bgp_keepalive_hold', @set_args)
set_args_keys_default
end | ruby | def timer_bgp_keepalive_hold_set(keepalive, hold)
if keepalive == default_timer_bgp_keepalive &&
hold == default_timer_bgp_holdtime
@set_args[:state] = 'no'
@set_args[:keepalive] = keepalive
@set_args[:hold] = hold
else
@set_args[:state] = ''
@set_args[:keepalive] = keepalive
@set_args[:hold] = hold
end
config_set('bgp', 'timer_bgp_keepalive_hold', @set_args)
set_args_keys_default
end | [
"def",
"timer_bgp_keepalive_hold_set",
"(",
"keepalive",
",",
"hold",
")",
"if",
"keepalive",
"==",
"default_timer_bgp_keepalive",
"&&",
"hold",
"==",
"default_timer_bgp_holdtime",
"@set_args",
"[",
":state",
"]",
"=",
"'no'",
"@set_args",
"[",
":keepalive",
"]",
"=",
"keepalive",
"@set_args",
"[",
":hold",
"]",
"=",
"hold",
"else",
"@set_args",
"[",
":state",
"]",
"=",
"''",
"@set_args",
"[",
":keepalive",
"]",
"=",
"keepalive",
"@set_args",
"[",
":hold",
"]",
"=",
"hold",
"end",
"config_set",
"(",
"'bgp'",
",",
"'timer_bgp_keepalive_hold'",
",",
"@set_args",
")",
"set_args_keys_default",
"end"
]
| BGP Timers Setters | [
"BGP",
"Timers",
"Setters"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/bgp.rb#L933-L946 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/route_map.rb | Cisco.RouteMap.match_community | def match_community
str = config_get('route_map', 'match_community', @get_args)
if str.empty?
val = default_match_community
else
val = str.split
val.delete('exact-match')
end
val
end | ruby | def match_community
str = config_get('route_map', 'match_community', @get_args)
if str.empty?
val = default_match_community
else
val = str.split
val.delete('exact-match')
end
val
end | [
"def",
"match_community",
"str",
"=",
"config_get",
"(",
"'route_map'",
",",
"'match_community'",
",",
"@get_args",
")",
"if",
"str",
".",
"empty?",
"val",
"=",
"default_match_community",
"else",
"val",
"=",
"str",
".",
"split",
"val",
".",
"delete",
"(",
"'exact-match'",
")",
"end",
"val",
"end"
]
| match community public private exact-match | [
"match",
"community",
"public",
"private",
"exact",
"-",
"match"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/route_map.rb#L156-L165 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/route_map.rb | Cisco.RouteMap.match_metric | def match_metric
str = config_get('route_map', 'match_metric', @get_args)
return default_match_metric if str.empty?
rarr = []
larr = []
metrics = str.split
deviation = false
metrics.each do |metric|
deviation = true if metric == '+-'
if !larr.empty? && !deviation
larr << '0'
rarr << larr
larr = []
end
next if metric == '+-'
if !larr.empty? && deviation
larr << metric
rarr << larr
larr = []
deviation = false
next
end
larr << metric if larr.empty?
end
unless larr.empty?
larr << '0'
rarr << larr
end
rarr
end | ruby | def match_metric
str = config_get('route_map', 'match_metric', @get_args)
return default_match_metric if str.empty?
rarr = []
larr = []
metrics = str.split
deviation = false
metrics.each do |metric|
deviation = true if metric == '+-'
if !larr.empty? && !deviation
larr << '0'
rarr << larr
larr = []
end
next if metric == '+-'
if !larr.empty? && deviation
larr << metric
rarr << larr
larr = []
deviation = false
next
end
larr << metric if larr.empty?
end
unless larr.empty?
larr << '0'
rarr << larr
end
rarr
end | [
"def",
"match_metric",
"str",
"=",
"config_get",
"(",
"'route_map'",
",",
"'match_metric'",
",",
"@get_args",
")",
"return",
"default_match_metric",
"if",
"str",
".",
"empty?",
"rarr",
"=",
"[",
"]",
"larr",
"=",
"[",
"]",
"metrics",
"=",
"str",
".",
"split",
"deviation",
"=",
"false",
"metrics",
".",
"each",
"do",
"|",
"metric",
"|",
"deviation",
"=",
"true",
"if",
"metric",
"==",
"'+-'",
"if",
"!",
"larr",
".",
"empty?",
"&&",
"!",
"deviation",
"larr",
"<<",
"'0'",
"rarr",
"<<",
"larr",
"larr",
"=",
"[",
"]",
"end",
"next",
"if",
"metric",
"==",
"'+-'",
"if",
"!",
"larr",
".",
"empty?",
"&&",
"deviation",
"larr",
"<<",
"metric",
"rarr",
"<<",
"larr",
"larr",
"=",
"[",
"]",
"deviation",
"=",
"false",
"next",
"end",
"larr",
"<<",
"metric",
"if",
"larr",
".",
"empty?",
"end",
"unless",
"larr",
".",
"empty?",
"larr",
"<<",
"'0'",
"rarr",
"<<",
"larr",
"end",
"rarr",
"end"
]
| match metric 1 8 224 +- 9 23 5 +- 8 6 | [
"match",
"metric",
"1",
"8",
"224",
"+",
"-",
"9",
"23",
"5",
"+",
"-",
"8",
"6"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/route_map.rb#L847-L876 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/route_map.rb | Cisco.RouteMap.match_ospf_area | def match_ospf_area
str = config_get('route_map', 'match_ospf_area', @get_args)
return if str.nil?
str.empty? ? default_match_ospf_area : str.split
end | ruby | def match_ospf_area
str = config_get('route_map', 'match_ospf_area', @get_args)
return if str.nil?
str.empty? ? default_match_ospf_area : str.split
end | [
"def",
"match_ospf_area",
"str",
"=",
"config_get",
"(",
"'route_map'",
",",
"'match_ospf_area'",
",",
"@get_args",
")",
"return",
"if",
"str",
".",
"nil?",
"str",
".",
"empty?",
"?",
"default_match_ospf_area",
":",
"str",
".",
"split",
"end"
]
| match ospf-area 10 7 | [
"match",
"ospf",
"-",
"area",
"10",
"7"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/route_map.rb#L1107-L1111 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/route_map.rb | Cisco.RouteMap.match_mac_list | def match_mac_list
str = config_get('route_map', 'match_mac_list', @get_args)
return if str.nil?
str.empty? ? default_match_mac_list : str.split
end | ruby | def match_mac_list
str = config_get('route_map', 'match_mac_list', @get_args)
return if str.nil?
str.empty? ? default_match_mac_list : str.split
end | [
"def",
"match_mac_list",
"str",
"=",
"config_get",
"(",
"'route_map'",
",",
"'match_mac_list'",
",",
"@get_args",
")",
"return",
"if",
"str",
".",
"nil?",
"str",
".",
"empty?",
"?",
"default_match_mac_list",
":",
"str",
".",
"split",
"end"
]
| match mac-list m1 m2 | [
"match",
"mac",
"-",
"list",
"m1",
"m2"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/route_map.rb#L1139-L1143 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/route_map.rb | Cisco.RouteMap.match_evpn_route_type_get | def match_evpn_route_type_get
arr = config_get('route_map', 'match_evpn_route_type', @get_args)
return nil if arr.nil?
hash = {}
hash[:type1] = false
hash[:type3] = false
hash[:type4] = false
hash[:type5] = false
hash[:type6] = false
hash[:type_all] = false
hash[:type2_all] = false
hash[:type2_mac_ip] = false
hash[:type2_mac_only] = false
return hash if arr.empty?
hash[:type1] = true if arr.include?('1')
hash[:type3] = true if arr.include?('3')
hash[:type4] = true if arr.include?('4')
hash[:type5] = true if arr.include?('5')
hash[:type6] = true if arr.include?('6')
hash[:type_all] = true if arr.include?('all')
hash[:type2_all] = true if arr.include?('2 all')
hash[:type2_mac_ip] = true if arr.include?('2 mac-ip')
hash[:type2_mac_only] = true if arr.include?('2 mac-only')
hash
end | ruby | def match_evpn_route_type_get
arr = config_get('route_map', 'match_evpn_route_type', @get_args)
return nil if arr.nil?
hash = {}
hash[:type1] = false
hash[:type3] = false
hash[:type4] = false
hash[:type5] = false
hash[:type6] = false
hash[:type_all] = false
hash[:type2_all] = false
hash[:type2_mac_ip] = false
hash[:type2_mac_only] = false
return hash if arr.empty?
hash[:type1] = true if arr.include?('1')
hash[:type3] = true if arr.include?('3')
hash[:type4] = true if arr.include?('4')
hash[:type5] = true if arr.include?('5')
hash[:type6] = true if arr.include?('6')
hash[:type_all] = true if arr.include?('all')
hash[:type2_all] = true if arr.include?('2 all')
hash[:type2_mac_ip] = true if arr.include?('2 mac-ip')
hash[:type2_mac_only] = true if arr.include?('2 mac-only')
hash
end | [
"def",
"match_evpn_route_type_get",
"arr",
"=",
"config_get",
"(",
"'route_map'",
",",
"'match_evpn_route_type'",
",",
"@get_args",
")",
"return",
"nil",
"if",
"arr",
".",
"nil?",
"hash",
"=",
"{",
"}",
"hash",
"[",
":type1",
"]",
"=",
"false",
"hash",
"[",
":type3",
"]",
"=",
"false",
"hash",
"[",
":type4",
"]",
"=",
"false",
"hash",
"[",
":type5",
"]",
"=",
"false",
"hash",
"[",
":type6",
"]",
"=",
"false",
"hash",
"[",
":type_all",
"]",
"=",
"false",
"hash",
"[",
":type2_all",
"]",
"=",
"false",
"hash",
"[",
":type2_mac_ip",
"]",
"=",
"false",
"hash",
"[",
":type2_mac_only",
"]",
"=",
"false",
"return",
"hash",
"if",
"arr",
".",
"empty?",
"hash",
"[",
":type1",
"]",
"=",
"true",
"if",
"arr",
".",
"include?",
"(",
"'1'",
")",
"hash",
"[",
":type3",
"]",
"=",
"true",
"if",
"arr",
".",
"include?",
"(",
"'3'",
")",
"hash",
"[",
":type4",
"]",
"=",
"true",
"if",
"arr",
".",
"include?",
"(",
"'4'",
")",
"hash",
"[",
":type5",
"]",
"=",
"true",
"if",
"arr",
".",
"include?",
"(",
"'5'",
")",
"hash",
"[",
":type6",
"]",
"=",
"true",
"if",
"arr",
".",
"include?",
"(",
"'6'",
")",
"hash",
"[",
":type_all",
"]",
"=",
"true",
"if",
"arr",
".",
"include?",
"(",
"'all'",
")",
"hash",
"[",
":type2_all",
"]",
"=",
"true",
"if",
"arr",
".",
"include?",
"(",
"'2 all'",
")",
"hash",
"[",
":type2_mac_ip",
"]",
"=",
"true",
"if",
"arr",
".",
"include?",
"(",
"'2 mac-ip'",
")",
"hash",
"[",
":type2_mac_only",
"]",
"=",
"true",
"if",
"arr",
".",
"include?",
"(",
"'2 mac-only'",
")",
"hash",
"end"
]
| match evpn route-type 1
match evpn route-type 2 all
match evpn route-type 2 mac-ip
match evpn route-type 2 mac-only
match evpn route-type 3 etc. | [
"match",
"evpn",
"route",
"-",
"type",
"1",
"match",
"evpn",
"route",
"-",
"type",
"2",
"all",
"match",
"evpn",
"route",
"-",
"type",
"2",
"mac",
"-",
"ip",
"match",
"evpn",
"route",
"-",
"type",
"2",
"mac",
"-",
"only",
"match",
"evpn",
"route",
"-",
"type",
"3",
"etc",
"."
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/route_map.rb#L1214-L1238 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/route_map.rb | Cisco.RouteMap.set_metric_get | def set_metric_get
hash = {}
hash[:additive] = false
hash[:bandwidth] = false
hash[:delay] = false
hash[:reliability] = false
hash[:effective_bandwidth] = false
hash[:mtu] = false
str = config_get('route_map', 'set_metric', @get_args)
return hash if str.nil?
arr = str.split
hash[:additive] = true if arr[0].include?('+')
hash[:bandwidth] = arr[0].delete('+').to_i
return hash if arr.size == 1
hash[:delay] = arr[1].to_i
hash[:reliability] = arr[2].to_i
hash[:effective_bandwidth] = arr[3].to_i
hash[:mtu] = arr[4].to_i
hash
end | ruby | def set_metric_get
hash = {}
hash[:additive] = false
hash[:bandwidth] = false
hash[:delay] = false
hash[:reliability] = false
hash[:effective_bandwidth] = false
hash[:mtu] = false
str = config_get('route_map', 'set_metric', @get_args)
return hash if str.nil?
arr = str.split
hash[:additive] = true if arr[0].include?('+')
hash[:bandwidth] = arr[0].delete('+').to_i
return hash if arr.size == 1
hash[:delay] = arr[1].to_i
hash[:reliability] = arr[2].to_i
hash[:effective_bandwidth] = arr[3].to_i
hash[:mtu] = arr[4].to_i
hash
end | [
"def",
"set_metric_get",
"hash",
"=",
"{",
"}",
"hash",
"[",
":additive",
"]",
"=",
"false",
"hash",
"[",
":bandwidth",
"]",
"=",
"false",
"hash",
"[",
":delay",
"]",
"=",
"false",
"hash",
"[",
":reliability",
"]",
"=",
"false",
"hash",
"[",
":effective_bandwidth",
"]",
"=",
"false",
"hash",
"[",
":mtu",
"]",
"=",
"false",
"str",
"=",
"config_get",
"(",
"'route_map'",
",",
"'set_metric'",
",",
"@get_args",
")",
"return",
"hash",
"if",
"str",
".",
"nil?",
"arr",
"=",
"str",
".",
"split",
"hash",
"[",
":additive",
"]",
"=",
"true",
"if",
"arr",
"[",
"0",
"]",
".",
"include?",
"(",
"'+'",
")",
"hash",
"[",
":bandwidth",
"]",
"=",
"arr",
"[",
"0",
"]",
".",
"delete",
"(",
"'+'",
")",
".",
"to_i",
"return",
"hash",
"if",
"arr",
".",
"size",
"==",
"1",
"hash",
"[",
":delay",
"]",
"=",
"arr",
"[",
"1",
"]",
".",
"to_i",
"hash",
"[",
":reliability",
"]",
"=",
"arr",
"[",
"2",
"]",
".",
"to_i",
"hash",
"[",
":effective_bandwidth",
"]",
"=",
"arr",
"[",
"3",
"]",
".",
"to_i",
"hash",
"[",
":mtu",
"]",
"=",
"arr",
"[",
"4",
"]",
".",
"to_i",
"hash",
"end"
]
| set metric 44 55 66 77 88
set metric +33 | [
"set",
"metric",
"44",
"55",
"66",
"77",
"88",
"set",
"metric",
"+",
"33"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/route_map.rb#L1556-L1575 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/route_map.rb | Cisco.RouteMap.set_dampening_get | def set_dampening_get
hash = {}
hash[:half_life] = false
hash[:reuse] = false
hash[:suppress] = false
hash[:max] = false
str = config_get('route_map', 'set_dampening', @get_args)
return hash if str.nil?
arr = str.split
hash[:half_life] = arr[0].to_i
hash[:reuse] = arr[1].to_i
hash[:suppress] = arr[2].to_i
hash[:max] = arr[3].to_i
hash
end | ruby | def set_dampening_get
hash = {}
hash[:half_life] = false
hash[:reuse] = false
hash[:suppress] = false
hash[:max] = false
str = config_get('route_map', 'set_dampening', @get_args)
return hash if str.nil?
arr = str.split
hash[:half_life] = arr[0].to_i
hash[:reuse] = arr[1].to_i
hash[:suppress] = arr[2].to_i
hash[:max] = arr[3].to_i
hash
end | [
"def",
"set_dampening_get",
"hash",
"=",
"{",
"}",
"hash",
"[",
":half_life",
"]",
"=",
"false",
"hash",
"[",
":reuse",
"]",
"=",
"false",
"hash",
"[",
":suppress",
"]",
"=",
"false",
"hash",
"[",
":max",
"]",
"=",
"false",
"str",
"=",
"config_get",
"(",
"'route_map'",
",",
"'set_dampening'",
",",
"@get_args",
")",
"return",
"hash",
"if",
"str",
".",
"nil?",
"arr",
"=",
"str",
".",
"split",
"hash",
"[",
":half_life",
"]",
"=",
"arr",
"[",
"0",
"]",
".",
"to_i",
"hash",
"[",
":reuse",
"]",
"=",
"arr",
"[",
"1",
"]",
".",
"to_i",
"hash",
"[",
":suppress",
"]",
"=",
"arr",
"[",
"2",
"]",
".",
"to_i",
"hash",
"[",
":max",
"]",
"=",
"arr",
"[",
"3",
"]",
".",
"to_i",
"hash",
"end"
]
| set dampening 6 22 44 55 | [
"set",
"dampening",
"6",
"22",
"44",
"55"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/route_map.rb#L1648-L1662 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/route_map.rb | Cisco.RouteMap.set_as_path_prepend | def set_as_path_prepend
arr = []
match = config_get('route_map', 'set_as_path_prepend', @get_args)
if arr
match.each do |line|
next if line.include?('last-as')
arr = line.strip.split
end
end
arr
end | ruby | def set_as_path_prepend
arr = []
match = config_get('route_map', 'set_as_path_prepend', @get_args)
if arr
match.each do |line|
next if line.include?('last-as')
arr = line.strip.split
end
end
arr
end | [
"def",
"set_as_path_prepend",
"arr",
"=",
"[",
"]",
"match",
"=",
"config_get",
"(",
"'route_map'",
",",
"'set_as_path_prepend'",
",",
"@get_args",
")",
"if",
"arr",
"match",
".",
"each",
"do",
"|",
"line",
"|",
"next",
"if",
"line",
".",
"include?",
"(",
"'last-as'",
")",
"arr",
"=",
"line",
".",
"strip",
".",
"split",
"end",
"end",
"arr",
"end"
]
| set as-path prepend 55.77 44 33.5
set as-path prepend last-as 1 | [
"set",
"as",
"-",
"path",
"prepend",
"55",
".",
"77",
"44",
"33",
".",
"5",
"set",
"as",
"-",
"path",
"prepend",
"last",
"-",
"as",
"1"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/route_map.rb#L1794-L1804 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/route_map.rb | Cisco.RouteMap.set_ipv4_default_next_hop | def set_ipv4_default_next_hop
str = config_get('route_map', 'set_ipv4_default_next_hop', @get_args)
return if str.nil?
if str.empty?
val = default_set_ipv4_default_next_hop
else
val = str.split
val.delete('load-share')
end
val
end | ruby | def set_ipv4_default_next_hop
str = config_get('route_map', 'set_ipv4_default_next_hop', @get_args)
return if str.nil?
if str.empty?
val = default_set_ipv4_default_next_hop
else
val = str.split
val.delete('load-share')
end
val
end | [
"def",
"set_ipv4_default_next_hop",
"str",
"=",
"config_get",
"(",
"'route_map'",
",",
"'set_ipv4_default_next_hop'",
",",
"@get_args",
")",
"return",
"if",
"str",
".",
"nil?",
"if",
"str",
".",
"empty?",
"val",
"=",
"default_set_ipv4_default_next_hop",
"else",
"val",
"=",
"str",
".",
"split",
"val",
".",
"delete",
"(",
"'load-share'",
")",
"end",
"val",
"end"
]
| set ip default next-hop 1.1.1.1 2.2.2.2 3.3.3.3 | [
"set",
"ip",
"default",
"next",
"-",
"hop",
"1",
".",
"1",
".",
"1",
".",
"1",
"2",
".",
"2",
".",
"2",
".",
"2",
"3",
".",
"3",
".",
"3",
".",
"3"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/route_map.rb#L1870-L1880 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/route_map.rb | Cisco.RouteMap.set_ipv4_next_hop | def set_ipv4_next_hop
arr = config_get('route_map', 'set_ipv4_next_hop', @get_args)
val = default_set_ipv4_next_hop
arr.each do |str|
next if str.empty?
next if str.include?('peer-address')
next if str.include?('unchanged')
next if str.include?('redist-unchanged')
val = str.split
val.delete('load-share')
end
val
end | ruby | def set_ipv4_next_hop
arr = config_get('route_map', 'set_ipv4_next_hop', @get_args)
val = default_set_ipv4_next_hop
arr.each do |str|
next if str.empty?
next if str.include?('peer-address')
next if str.include?('unchanged')
next if str.include?('redist-unchanged')
val = str.split
val.delete('load-share')
end
val
end | [
"def",
"set_ipv4_next_hop",
"arr",
"=",
"config_get",
"(",
"'route_map'",
",",
"'set_ipv4_next_hop'",
",",
"@get_args",
")",
"val",
"=",
"default_set_ipv4_next_hop",
"arr",
".",
"each",
"do",
"|",
"str",
"|",
"next",
"if",
"str",
".",
"empty?",
"next",
"if",
"str",
".",
"include?",
"(",
"'peer-address'",
")",
"next",
"if",
"str",
".",
"include?",
"(",
"'unchanged'",
")",
"next",
"if",
"str",
".",
"include?",
"(",
"'redist-unchanged'",
")",
"val",
"=",
"str",
".",
"split",
"val",
".",
"delete",
"(",
"'load-share'",
")",
"end",
"val",
"end"
]
| set ip next-hop 1.1.1.1 2.2.2.2 3.3.3.3 | [
"set",
"ip",
"next",
"-",
"hop",
"1",
".",
"1",
".",
"1",
".",
"1",
"2",
".",
"2",
".",
"2",
".",
"2",
"3",
".",
"3",
".",
"3",
".",
"3"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/route_map.rb#L1922-L1934 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/route_map.rb | Cisco.RouteMap.set_ipv4_next_hop_load_share | def set_ipv4_next_hop_load_share
arr = config_get('route_map', 'set_ipv4_next_hop', @get_args)
val = default_set_ipv4_next_hop_load_share
arr.each do |str|
next if str.empty?
return true if str.include?('load-share')
end
val
end | ruby | def set_ipv4_next_hop_load_share
arr = config_get('route_map', 'set_ipv4_next_hop', @get_args)
val = default_set_ipv4_next_hop_load_share
arr.each do |str|
next if str.empty?
return true if str.include?('load-share')
end
val
end | [
"def",
"set_ipv4_next_hop_load_share",
"arr",
"=",
"config_get",
"(",
"'route_map'",
",",
"'set_ipv4_next_hop'",
",",
"@get_args",
")",
"val",
"=",
"default_set_ipv4_next_hop_load_share",
"arr",
".",
"each",
"do",
"|",
"str",
"|",
"next",
"if",
"str",
".",
"empty?",
"return",
"true",
"if",
"str",
".",
"include?",
"(",
"'load-share'",
")",
"end",
"val",
"end"
]
| set ip next-hop 1.1.1.1 2.2.2.2 3.3.3.3 load-share
set ip next-hop load-share | [
"set",
"ip",
"next",
"-",
"hop",
"1",
".",
"1",
".",
"1",
".",
"1",
"2",
".",
"2",
".",
"2",
".",
"2",
"3",
".",
"3",
".",
"3",
".",
"3",
"load",
"-",
"share",
"set",
"ip",
"next",
"-",
"hop",
"load",
"-",
"share"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/route_map.rb#L1963-L1971 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/route_map.rb | Cisco.RouteMap.set_ipv6_default_next_hop | def set_ipv6_default_next_hop
str = config_get('route_map', 'set_ipv6_default_next_hop', @get_args)
return if str.nil?
if str.empty?
val = default_set_ipv6_default_next_hop
else
val = str.split
val.delete('load-share')
end
val
end | ruby | def set_ipv6_default_next_hop
str = config_get('route_map', 'set_ipv6_default_next_hop', @get_args)
return if str.nil?
if str.empty?
val = default_set_ipv6_default_next_hop
else
val = str.split
val.delete('load-share')
end
val
end | [
"def",
"set_ipv6_default_next_hop",
"str",
"=",
"config_get",
"(",
"'route_map'",
",",
"'set_ipv6_default_next_hop'",
",",
"@get_args",
")",
"return",
"if",
"str",
".",
"nil?",
"if",
"str",
".",
"empty?",
"val",
"=",
"default_set_ipv6_default_next_hop",
"else",
"val",
"=",
"str",
".",
"split",
"val",
".",
"delete",
"(",
"'load-share'",
")",
"end",
"val",
"end"
]
| set ipv6 default next-hop 1.1.1.1 2.2.2.2 3.3.3.3 | [
"set",
"ipv6",
"default",
"next",
"-",
"hop",
"1",
".",
"1",
".",
"1",
".",
"1",
"2",
".",
"2",
".",
"2",
".",
"2",
"3",
".",
"3",
".",
"3",
".",
"3"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/route_map.rb#L2057-L2067 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/route_map.rb | Cisco.RouteMap.set_ipv6_next_hop | def set_ipv6_next_hop
arr = config_get('route_map', 'set_ipv6_next_hop', @get_args)
val = default_set_ipv6_next_hop
arr.each do |str|
next if str.empty?
next if str.include?('peer-address')
next if str.include?('unchanged')
next if str.include?('redist-unchanged')
val = str.split
val.delete('load-share')
end
val
end | ruby | def set_ipv6_next_hop
arr = config_get('route_map', 'set_ipv6_next_hop', @get_args)
val = default_set_ipv6_next_hop
arr.each do |str|
next if str.empty?
next if str.include?('peer-address')
next if str.include?('unchanged')
next if str.include?('redist-unchanged')
val = str.split
val.delete('load-share')
end
val
end | [
"def",
"set_ipv6_next_hop",
"arr",
"=",
"config_get",
"(",
"'route_map'",
",",
"'set_ipv6_next_hop'",
",",
"@get_args",
")",
"val",
"=",
"default_set_ipv6_next_hop",
"arr",
".",
"each",
"do",
"|",
"str",
"|",
"next",
"if",
"str",
".",
"empty?",
"next",
"if",
"str",
".",
"include?",
"(",
"'peer-address'",
")",
"next",
"if",
"str",
".",
"include?",
"(",
"'unchanged'",
")",
"next",
"if",
"str",
".",
"include?",
"(",
"'redist-unchanged'",
")",
"val",
"=",
"str",
".",
"split",
"val",
".",
"delete",
"(",
"'load-share'",
")",
"end",
"val",
"end"
]
| set ipv6 next-hop 1.1.1.1 2.2.2.2 3.3.3.3 | [
"set",
"ipv6",
"next",
"-",
"hop",
"1",
".",
"1",
".",
"1",
".",
"1",
"2",
".",
"2",
".",
"2",
".",
"2",
"3",
".",
"3",
".",
"3",
".",
"3"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/route_map.rb#L2109-L2121 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/route_map.rb | Cisco.RouteMap.set_ipv6_next_hop_load_share | def set_ipv6_next_hop_load_share
arr = config_get('route_map', 'set_ipv6_next_hop', @get_args)
val = default_set_ipv6_next_hop_load_share
arr.each do |str|
next if str.empty?
return true if str.include?('load-share')
end
val
end | ruby | def set_ipv6_next_hop_load_share
arr = config_get('route_map', 'set_ipv6_next_hop', @get_args)
val = default_set_ipv6_next_hop_load_share
arr.each do |str|
next if str.empty?
return true if str.include?('load-share')
end
val
end | [
"def",
"set_ipv6_next_hop_load_share",
"arr",
"=",
"config_get",
"(",
"'route_map'",
",",
"'set_ipv6_next_hop'",
",",
"@get_args",
")",
"val",
"=",
"default_set_ipv6_next_hop_load_share",
"arr",
".",
"each",
"do",
"|",
"str",
"|",
"next",
"if",
"str",
".",
"empty?",
"return",
"true",
"if",
"str",
".",
"include?",
"(",
"'load-share'",
")",
"end",
"val",
"end"
]
| set ipv6 default next-hop 1.1.1.1 2.2.2.2 3.3.3.3 load-share
set ipv6 default next-hop load-share | [
"set",
"ipv6",
"default",
"next",
"-",
"hop",
"1",
".",
"1",
".",
"1",
".",
"1",
"2",
".",
"2",
".",
"2",
".",
"2",
"3",
".",
"3",
".",
"3",
".",
"3",
"load",
"-",
"share",
"set",
"ipv6",
"default",
"next",
"-",
"hop",
"load",
"-",
"share"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/route_map.rb#L2150-L2158 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/route_map.rb | Cisco.RouteMap.set_extcommunity_cost_set | def set_extcommunity_cost_set(igp, pre)
str = ''
# reset first
if set_extcommunity_cost_device
cpre = set_extcommunity_cost_pre_bestpath
cigp = set_extcommunity_cost_igp
cpre.each do |id, val|
str.concat('pre-bestpath ' + id.to_s + ' ' + val.to_s + ' ')
end
cigp.each do |id, val|
str.concat('igp ' + id.to_s + ' ' + val.to_s + ' ')
end
end
set_args_keys(state: 'no', string: str)
config_set('route_map', 'set_extcommunity_cost', @set_args)
return if igp.empty? && pre.empty?
str = ''
pre.each do |id, val|
str.concat('pre-bestpath ' + id.to_s + ' ' + val.to_s + ' ')
end
igp.each do |id, val|
str.concat('igp ' + id.to_s + ' ' + val.to_s + ' ')
end
set_args_keys(state: '', string: str)
config_set('route_map', 'set_extcommunity_cost', @set_args)
end | ruby | def set_extcommunity_cost_set(igp, pre)
str = ''
# reset first
if set_extcommunity_cost_device
cpre = set_extcommunity_cost_pre_bestpath
cigp = set_extcommunity_cost_igp
cpre.each do |id, val|
str.concat('pre-bestpath ' + id.to_s + ' ' + val.to_s + ' ')
end
cigp.each do |id, val|
str.concat('igp ' + id.to_s + ' ' + val.to_s + ' ')
end
end
set_args_keys(state: 'no', string: str)
config_set('route_map', 'set_extcommunity_cost', @set_args)
return if igp.empty? && pre.empty?
str = ''
pre.each do |id, val|
str.concat('pre-bestpath ' + id.to_s + ' ' + val.to_s + ' ')
end
igp.each do |id, val|
str.concat('igp ' + id.to_s + ' ' + val.to_s + ' ')
end
set_args_keys(state: '', string: str)
config_set('route_map', 'set_extcommunity_cost', @set_args)
end | [
"def",
"set_extcommunity_cost_set",
"(",
"igp",
",",
"pre",
")",
"str",
"=",
"''",
"if",
"set_extcommunity_cost_device",
"cpre",
"=",
"set_extcommunity_cost_pre_bestpath",
"cigp",
"=",
"set_extcommunity_cost_igp",
"cpre",
".",
"each",
"do",
"|",
"id",
",",
"val",
"|",
"str",
".",
"concat",
"(",
"'pre-bestpath '",
"+",
"id",
".",
"to_s",
"+",
"' '",
"+",
"val",
".",
"to_s",
"+",
"' '",
")",
"end",
"cigp",
".",
"each",
"do",
"|",
"id",
",",
"val",
"|",
"str",
".",
"concat",
"(",
"'igp '",
"+",
"id",
".",
"to_s",
"+",
"' '",
"+",
"val",
".",
"to_s",
"+",
"' '",
")",
"end",
"end",
"set_args_keys",
"(",
"state",
":",
"'no'",
",",
"string",
":",
"str",
")",
"config_set",
"(",
"'route_map'",
",",
"'set_extcommunity_cost'",
",",
"@set_args",
")",
"return",
"if",
"igp",
".",
"empty?",
"&&",
"pre",
".",
"empty?",
"str",
"=",
"''",
"pre",
".",
"each",
"do",
"|",
"id",
",",
"val",
"|",
"str",
".",
"concat",
"(",
"'pre-bestpath '",
"+",
"id",
".",
"to_s",
"+",
"' '",
"+",
"val",
".",
"to_s",
"+",
"' '",
")",
"end",
"igp",
".",
"each",
"do",
"|",
"id",
",",
"val",
"|",
"str",
".",
"concat",
"(",
"'igp '",
"+",
"id",
".",
"to_s",
"+",
"' '",
"+",
"val",
".",
"to_s",
"+",
"' '",
")",
"end",
"set_args_keys",
"(",
"state",
":",
"''",
",",
"string",
":",
"str",
")",
"config_set",
"(",
"'route_map'",
",",
"'set_extcommunity_cost'",
",",
"@set_args",
")",
"end"
]
| set extcommunity cost igp 0 22 igp 3 23
set extcommunity cost pre-bestpath 1 222 pre-bestpath 2 54
set extcommunity cost pre-bestpath 1 222 pre-bestpath 2 54 igp 0 22 | [
"set",
"extcommunity",
"cost",
"igp",
"0",
"22",
"igp",
"3",
"23",
"set",
"extcommunity",
"cost",
"pre",
"-",
"bestpath",
"1",
"222",
"pre",
"-",
"bestpath",
"2",
"54",
"set",
"extcommunity",
"cost",
"pre",
"-",
"bestpath",
"1",
"222",
"pre",
"-",
"bestpath",
"2",
"54",
"igp",
"0",
"22"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/route_map.rb#L2475-L2500 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/overlay_global.rb | Cisco.OverlayGlobal.anycast_gateway_mac | def anycast_gateway_mac
mac = config_get('overlay_global', 'anycast_gateway_mac')
mac.nil? || mac.empty? ? default_anycast_gateway_mac : mac.downcase
end | ruby | def anycast_gateway_mac
mac = config_get('overlay_global', 'anycast_gateway_mac')
mac.nil? || mac.empty? ? default_anycast_gateway_mac : mac.downcase
end | [
"def",
"anycast_gateway_mac",
"mac",
"=",
"config_get",
"(",
"'overlay_global'",
",",
"'anycast_gateway_mac'",
")",
"mac",
".",
"nil?",
"||",
"mac",
".",
"empty?",
"?",
"default_anycast_gateway_mac",
":",
"mac",
".",
"downcase",
"end"
]
| anycast-gateway-mac | [
"anycast",
"-",
"gateway",
"-",
"mac"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/overlay_global.rb#L118-L121 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/tacacs_server.rb | Cisco.TacacsServer.encryption_key_set | def encryption_key_set(enctype, password)
password = Utils.add_quotes(password)
# if enctype is TACACS_SERVER_ENC_UNKNOWN, we will unset the key
if enctype == TACACS_SERVER_ENC_UNKNOWN
# if current encryption type is not TACACS_SERVER_ENC_UNKNOWN, we
# need to unset it. Otherwise the box is not configured with key, we
# don't need to do anything
if encryption_type != TACACS_SERVER_ENC_UNKNOWN
config_set('tacacs_server', 'encryption', state: 'no',
option: encryption_type,
key: encryption_password)
end
else
config_set('tacacs_server', 'encryption', state: '', option: enctype,
key: password)
end
end | ruby | def encryption_key_set(enctype, password)
password = Utils.add_quotes(password)
# if enctype is TACACS_SERVER_ENC_UNKNOWN, we will unset the key
if enctype == TACACS_SERVER_ENC_UNKNOWN
# if current encryption type is not TACACS_SERVER_ENC_UNKNOWN, we
# need to unset it. Otherwise the box is not configured with key, we
# don't need to do anything
if encryption_type != TACACS_SERVER_ENC_UNKNOWN
config_set('tacacs_server', 'encryption', state: 'no',
option: encryption_type,
key: encryption_password)
end
else
config_set('tacacs_server', 'encryption', state: '', option: enctype,
key: password)
end
end | [
"def",
"encryption_key_set",
"(",
"enctype",
",",
"password",
")",
"password",
"=",
"Utils",
".",
"add_quotes",
"(",
"password",
")",
"if",
"enctype",
"==",
"TACACS_SERVER_ENC_UNKNOWN",
"if",
"encryption_type",
"!=",
"TACACS_SERVER_ENC_UNKNOWN",
"config_set",
"(",
"'tacacs_server'",
",",
"'encryption'",
",",
"state",
":",
"'no'",
",",
"option",
":",
"encryption_type",
",",
"key",
":",
"encryption_password",
")",
"end",
"else",
"config_set",
"(",
"'tacacs_server'",
",",
"'encryption'",
",",
"state",
":",
"''",
",",
"option",
":",
"enctype",
",",
"key",
":",
"password",
")",
"end",
"end"
]
| Set encryption type and password | [
"Set",
"encryption",
"type",
"and",
"password"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/tacacs_server.rb#L155-L171 | train |
cisco/cisco-network-node-utils | lib/cisco_node_utils/itd_service.rb | Cisco.ItdService.ingress_interface= | def ingress_interface=(list)
ingress_interface_cleanup
@set_args[:state] = ''
list.each do |intf, next_hop|
@set_args[:interface] = intf
@set_args[:next] = ''
@set_args[:nhop] = ''
unless next_hop == '' || next_hop == 'default'
@set_args[:next] = 'next-hop'
@set_args[:nhop] = next_hop
end
config_set('itd_service', 'ingress_interface', @set_args)
end
set_args_keys_default
end | ruby | def ingress_interface=(list)
ingress_interface_cleanup
@set_args[:state] = ''
list.each do |intf, next_hop|
@set_args[:interface] = intf
@set_args[:next] = ''
@set_args[:nhop] = ''
unless next_hop == '' || next_hop == 'default'
@set_args[:next] = 'next-hop'
@set_args[:nhop] = next_hop
end
config_set('itd_service', 'ingress_interface', @set_args)
end
set_args_keys_default
end | [
"def",
"ingress_interface",
"=",
"(",
"list",
")",
"ingress_interface_cleanup",
"@set_args",
"[",
":state",
"]",
"=",
"''",
"list",
".",
"each",
"do",
"|",
"intf",
",",
"next_hop",
"|",
"@set_args",
"[",
":interface",
"]",
"=",
"intf",
"@set_args",
"[",
":next",
"]",
"=",
"''",
"@set_args",
"[",
":nhop",
"]",
"=",
"''",
"unless",
"next_hop",
"==",
"''",
"||",
"next_hop",
"==",
"'default'",
"@set_args",
"[",
":next",
"]",
"=",
"'next-hop'",
"@set_args",
"[",
":nhop",
"]",
"=",
"next_hop",
"end",
"config_set",
"(",
"'itd_service'",
",",
"'ingress_interface'",
",",
"@set_args",
")",
"end",
"set_args_keys_default",
"end"
]
| only one next-hop is allowed per interface but
due to nxos issues, it allows more than one;
so the workaround is to clean up the current ingress
intf and configure all of them again | [
"only",
"one",
"next",
"-",
"hop",
"is",
"allowed",
"per",
"interface",
"but",
"due",
"to",
"nxos",
"issues",
"it",
"allows",
"more",
"than",
"one",
";",
"so",
"the",
"workaround",
"is",
"to",
"clean",
"up",
"the",
"current",
"ingress",
"intf",
"and",
"configure",
"all",
"of",
"them",
"again"
]
| a617a9ef9d6bd18f35f2e2f2591033e1ddd46145 | https://github.com/cisco/cisco-network-node-utils/blob/a617a9ef9d6bd18f35f2e2f2591033e1ddd46145/lib/cisco_node_utils/itd_service.rb#L199-L213 | train |
emancu/toml-rb | lib/toml-rb/keygroup.rb | TomlRB.Keygroup.ensure_key_not_defined | def ensure_key_not_defined(visited_keys)
fail ValueOverwriteError.new(full_key) if visited_keys.include?(full_key)
visited_keys << full_key
end | ruby | def ensure_key_not_defined(visited_keys)
fail ValueOverwriteError.new(full_key) if visited_keys.include?(full_key)
visited_keys << full_key
end | [
"def",
"ensure_key_not_defined",
"(",
"visited_keys",
")",
"fail",
"ValueOverwriteError",
".",
"new",
"(",
"full_key",
")",
"if",
"visited_keys",
".",
"include?",
"(",
"full_key",
")",
"visited_keys",
"<<",
"full_key",
"end"
]
| Fail if the key was already defined with a ValueOverwriteError | [
"Fail",
"if",
"the",
"key",
"was",
"already",
"defined",
"with",
"a",
"ValueOverwriteError"
]
| 1b649547ed1cc1855b11eb7880c1ad03b8ab52e9 | https://github.com/emancu/toml-rb/blob/1b649547ed1cc1855b11eb7880c1ad03b8ab52e9/lib/toml-rb/keygroup.rb#L21-L24 | train |
samnissen/watir-screenshot-stitch | lib/watir-screenshot-stitch.rb | Watir.Screenshot.save_stitch | def save_stitch(path, opts = {})
return @browser.screenshot.save(path) if base64_capable?
@options = opts
@path = path
calculate_dimensions
return self.save(@path) if (one_shot? || bug_shot?)
build_canvas
gather_slices
stitch_together
@combined_screenshot.write @path
end | ruby | def save_stitch(path, opts = {})
return @browser.screenshot.save(path) if base64_capable?
@options = opts
@path = path
calculate_dimensions
return self.save(@path) if (one_shot? || bug_shot?)
build_canvas
gather_slices
stitch_together
@combined_screenshot.write @path
end | [
"def",
"save_stitch",
"(",
"path",
",",
"opts",
"=",
"{",
"}",
")",
"return",
"@browser",
".",
"screenshot",
".",
"save",
"(",
"path",
")",
"if",
"base64_capable?",
"@options",
"=",
"opts",
"@path",
"=",
"path",
"calculate_dimensions",
"return",
"self",
".",
"save",
"(",
"@path",
")",
"if",
"(",
"one_shot?",
"||",
"bug_shot?",
")",
"build_canvas",
"gather_slices",
"stitch_together",
"@combined_screenshot",
".",
"write",
"@path",
"end"
]
| Represents stitched together screenshot and writes to file.
@example
opts = {:page_height_limit => 5000}
browser.screenshot.save_stitch("path/abc.png", browser, opts)
@param [String] path
@deprecated
@param [Watir::Browser] browser
@param [Hash] opts | [
"Represents",
"stitched",
"together",
"screenshot",
"and",
"writes",
"to",
"file",
"."
]
| 4cb9ac14ec974751b185391f6832bfb7e205f531 | https://github.com/samnissen/watir-screenshot-stitch/blob/4cb9ac14ec974751b185391f6832bfb7e205f531/lib/watir-screenshot-stitch.rb#L57-L70 | train |
samnissen/watir-screenshot-stitch | lib/watir-screenshot-stitch.rb | Watir.Screenshot.base64_canvas | def base64_canvas
return self.base64 if base64_capable?
output = nil
return self.base64 if one_shot? || bug_shot?
@browser.execute_script html2canvas_payload
@browser.execute_script h2c_activator
@browser.wait_until(timeout: MAXIMUM_SCREENSHOT_GENERATION_WAIT_TIME) {
output = @browser.execute_script "return window.canvasImgContentDecoded;"
}
raise "Could not generate screenshot blob within #{MAXIMUM_SCREENSHOT_GENERATION_WAIT_TIME} seconds" unless output
output.sub!(/^data\:image\/png\;base64,/, '')
end | ruby | def base64_canvas
return self.base64 if base64_capable?
output = nil
return self.base64 if one_shot? || bug_shot?
@browser.execute_script html2canvas_payload
@browser.execute_script h2c_activator
@browser.wait_until(timeout: MAXIMUM_SCREENSHOT_GENERATION_WAIT_TIME) {
output = @browser.execute_script "return window.canvasImgContentDecoded;"
}
raise "Could not generate screenshot blob within #{MAXIMUM_SCREENSHOT_GENERATION_WAIT_TIME} seconds" unless output
output.sub!(/^data\:image\/png\;base64,/, '')
end | [
"def",
"base64_canvas",
"return",
"self",
".",
"base64",
"if",
"base64_capable?",
"output",
"=",
"nil",
"return",
"self",
".",
"base64",
"if",
"one_shot?",
"||",
"bug_shot?",
"@browser",
".",
"execute_script",
"html2canvas_payload",
"@browser",
".",
"execute_script",
"h2c_activator",
"@browser",
".",
"wait_until",
"(",
"timeout",
":",
"MAXIMUM_SCREENSHOT_GENERATION_WAIT_TIME",
")",
"{",
"output",
"=",
"@browser",
".",
"execute_script",
"\"return window.canvasImgContentDecoded;\"",
"}",
"raise",
"\"Could not generate screenshot blob within #{MAXIMUM_SCREENSHOT_GENERATION_WAIT_TIME} seconds\"",
"unless",
"output",
"output",
".",
"sub!",
"(",
"/",
"\\:",
"\\/",
"\\;",
"/",
",",
"''",
")",
"end"
]
| Employs html2canvas to produce a Base64 encoded string
of a full page screenshot.
@example
browser.screenshot.base64_canvas(browser)
#=> '7HWJ43tZDscPleeUuPW6HhN3x+z7vU/lufmH0qNTtTum94IBWMT46evImci1vnFGT'
@deprecated
@param [Watir::Browser] browser
@return [String] | [
"Employs",
"html2canvas",
"to",
"produce",
"a",
"Base64",
"encoded",
"string",
"of",
"a",
"full",
"page",
"screenshot",
"."
]
| 4cb9ac14ec974751b185391f6832bfb7e205f531 | https://github.com/samnissen/watir-screenshot-stitch/blob/4cb9ac14ec974751b185391f6832bfb7e205f531/lib/watir-screenshot-stitch.rb#L86-L102 | train |
ryanlecompte/redis_failover | lib/redis_failover/client.rb | RedisFailover.Client.setup_zk | def setup_zk
@zk = ZK.new(@zkservers) if @zkservers
@zk.register(redis_nodes_path) { |event| handle_zk_event(event) }
if @safe_mode
@zk.on_expired_session { purge_clients }
end
@zk.on_connected { @zk.stat(redis_nodes_path, :watch => true) }
@zk.stat(redis_nodes_path, :watch => true)
update_znode_timestamp
end | ruby | def setup_zk
@zk = ZK.new(@zkservers) if @zkservers
@zk.register(redis_nodes_path) { |event| handle_zk_event(event) }
if @safe_mode
@zk.on_expired_session { purge_clients }
end
@zk.on_connected { @zk.stat(redis_nodes_path, :watch => true) }
@zk.stat(redis_nodes_path, :watch => true)
update_znode_timestamp
end | [
"def",
"setup_zk",
"@zk",
"=",
"ZK",
".",
"new",
"(",
"@zkservers",
")",
"if",
"@zkservers",
"@zk",
".",
"register",
"(",
"redis_nodes_path",
")",
"{",
"|",
"event",
"|",
"handle_zk_event",
"(",
"event",
")",
"}",
"if",
"@safe_mode",
"@zk",
".",
"on_expired_session",
"{",
"purge_clients",
"}",
"end",
"@zk",
".",
"on_connected",
"{",
"@zk",
".",
"stat",
"(",
"redis_nodes_path",
",",
":watch",
"=>",
"true",
")",
"}",
"@zk",
".",
"stat",
"(",
"redis_nodes_path",
",",
":watch",
"=>",
"true",
")",
"update_znode_timestamp",
"end"
]
| Sets up the underlying ZooKeeper connection. | [
"Sets",
"up",
"the",
"underlying",
"ZooKeeper",
"connection",
"."
]
| be1208240b9b817fb0288edc7535e3f445f767cd | https://github.com/ryanlecompte/redis_failover/blob/be1208240b9b817fb0288edc7535e3f445f767cd/lib/redis_failover/client.rb#L188-L197 | train |
ryanlecompte/redis_failover | lib/redis_failover/client.rb | RedisFailover.Client.handle_zk_event | def handle_zk_event(event)
update_znode_timestamp
if event.node_created? || event.node_changed?
build_clients
elsif event.node_deleted?
purge_clients
@zk.stat(redis_nodes_path, :watch => true)
else
logger.error("Unknown ZK node event: #{event.inspect}")
end
ensure
@zk.stat(redis_nodes_path, :watch => true)
end | ruby | def handle_zk_event(event)
update_znode_timestamp
if event.node_created? || event.node_changed?
build_clients
elsif event.node_deleted?
purge_clients
@zk.stat(redis_nodes_path, :watch => true)
else
logger.error("Unknown ZK node event: #{event.inspect}")
end
ensure
@zk.stat(redis_nodes_path, :watch => true)
end | [
"def",
"handle_zk_event",
"(",
"event",
")",
"update_znode_timestamp",
"if",
"event",
".",
"node_created?",
"||",
"event",
".",
"node_changed?",
"build_clients",
"elsif",
"event",
".",
"node_deleted?",
"purge_clients",
"@zk",
".",
"stat",
"(",
"redis_nodes_path",
",",
":watch",
"=>",
"true",
")",
"else",
"logger",
".",
"error",
"(",
"\"Unknown ZK node event: #{event.inspect}\"",
")",
"end",
"ensure",
"@zk",
".",
"stat",
"(",
"redis_nodes_path",
",",
":watch",
"=>",
"true",
")",
"end"
]
| Handles a ZK event.
@param [ZK::Event] event the ZK event to handle | [
"Handles",
"a",
"ZK",
"event",
"."
]
| be1208240b9b817fb0288edc7535e3f445f767cd | https://github.com/ryanlecompte/redis_failover/blob/be1208240b9b817fb0288edc7535e3f445f767cd/lib/redis_failover/client.rb#L202-L214 | train |
ryanlecompte/redis_failover | lib/redis_failover/client.rb | RedisFailover.Client.dispatch | def dispatch(method, *args, &block)
if @safe_mode && !recently_heard_from_node_manager?
build_clients
end
verify_supported!(method)
tries = 0
begin
client_for(method).send(method, *args, &block)
rescue *CONNECTIVITY_ERRORS => ex
logger.error("Error while handling `#{method}` - #{ex.inspect}")
logger.error(ex.backtrace.join("\n"))
if tries < @max_retries
tries += 1
free_client
build_clients
sleep(RETRY_WAIT_TIME)
retry
end
raise
ensure
free_client
end
end | ruby | def dispatch(method, *args, &block)
if @safe_mode && !recently_heard_from_node_manager?
build_clients
end
verify_supported!(method)
tries = 0
begin
client_for(method).send(method, *args, &block)
rescue *CONNECTIVITY_ERRORS => ex
logger.error("Error while handling `#{method}` - #{ex.inspect}")
logger.error(ex.backtrace.join("\n"))
if tries < @max_retries
tries += 1
free_client
build_clients
sleep(RETRY_WAIT_TIME)
retry
end
raise
ensure
free_client
end
end | [
"def",
"dispatch",
"(",
"method",
",",
"*",
"args",
",",
"&",
"block",
")",
"if",
"@safe_mode",
"&&",
"!",
"recently_heard_from_node_manager?",
"build_clients",
"end",
"verify_supported!",
"(",
"method",
")",
"tries",
"=",
"0",
"begin",
"client_for",
"(",
"method",
")",
".",
"send",
"(",
"method",
",",
"*",
"args",
",",
"&",
"block",
")",
"rescue",
"*",
"CONNECTIVITY_ERRORS",
"=>",
"ex",
"logger",
".",
"error",
"(",
"\"Error while handling `#{method}` - #{ex.inspect}\"",
")",
"logger",
".",
"error",
"(",
"ex",
".",
"backtrace",
".",
"join",
"(",
"\"\\n\"",
")",
")",
"if",
"tries",
"<",
"@max_retries",
"tries",
"+=",
"1",
"free_client",
"build_clients",
"sleep",
"(",
"RETRY_WAIT_TIME",
")",
"retry",
"end",
"raise",
"ensure",
"free_client",
"end",
"end"
]
| Dispatches a redis operation to a master or slave.
@param [Symbol] method the method to dispatch
@param [Array] args the arguments to pass to the method
@param [Proc] block an optional block to pass to the method
@return [Object] the result of dispatching the command | [
"Dispatches",
"a",
"redis",
"operation",
"to",
"a",
"master",
"or",
"slave",
"."
]
| be1208240b9b817fb0288edc7535e3f445f767cd | https://github.com/ryanlecompte/redis_failover/blob/be1208240b9b817fb0288edc7535e3f445f767cd/lib/redis_failover/client.rb#L230-L254 | train |
ryanlecompte/redis_failover | lib/redis_failover/client.rb | RedisFailover.Client.fetch_nodes | def fetch_nodes
data = @zk.get(redis_nodes_path, :watch => true).first
nodes = symbolize_keys(decode(data))
logger.debug("Fetched nodes: #{nodes.inspect}")
nodes
rescue Zookeeper::Exceptions::InheritedConnectionError, ZK::Exceptions::InterruptedSession => ex
logger.debug { "Caught #{ex.class} '#{ex.message}' - reopening ZK client" }
@zk.reopen
retry
rescue *ZK_ERRORS => ex
logger.warn { "Caught #{ex.class} '#{ex.message}' - retrying" }
sleep(RETRY_WAIT_TIME)
retry
end | ruby | def fetch_nodes
data = @zk.get(redis_nodes_path, :watch => true).first
nodes = symbolize_keys(decode(data))
logger.debug("Fetched nodes: #{nodes.inspect}")
nodes
rescue Zookeeper::Exceptions::InheritedConnectionError, ZK::Exceptions::InterruptedSession => ex
logger.debug { "Caught #{ex.class} '#{ex.message}' - reopening ZK client" }
@zk.reopen
retry
rescue *ZK_ERRORS => ex
logger.warn { "Caught #{ex.class} '#{ex.message}' - retrying" }
sleep(RETRY_WAIT_TIME)
retry
end | [
"def",
"fetch_nodes",
"data",
"=",
"@zk",
".",
"get",
"(",
"redis_nodes_path",
",",
":watch",
"=>",
"true",
")",
".",
"first",
"nodes",
"=",
"symbolize_keys",
"(",
"decode",
"(",
"data",
")",
")",
"logger",
".",
"debug",
"(",
"\"Fetched nodes: #{nodes.inspect}\"",
")",
"nodes",
"rescue",
"Zookeeper",
"::",
"Exceptions",
"::",
"InheritedConnectionError",
",",
"ZK",
"::",
"Exceptions",
"::",
"InterruptedSession",
"=>",
"ex",
"logger",
".",
"debug",
"{",
"\"Caught #{ex.class} '#{ex.message}' - reopening ZK client\"",
"}",
"@zk",
".",
"reopen",
"retry",
"rescue",
"*",
"ZK_ERRORS",
"=>",
"ex",
"logger",
".",
"warn",
"{",
"\"Caught #{ex.class} '#{ex.message}' - retrying\"",
"}",
"sleep",
"(",
"RETRY_WAIT_TIME",
")",
"retry",
"end"
]
| Fetches the known redis nodes from ZooKeeper.
@return [Hash] the known master/slave redis servers | [
"Fetches",
"the",
"known",
"redis",
"nodes",
"from",
"ZooKeeper",
"."
]
| be1208240b9b817fb0288edc7535e3f445f767cd | https://github.com/ryanlecompte/redis_failover/blob/be1208240b9b817fb0288edc7535e3f445f767cd/lib/redis_failover/client.rb#L322-L336 | train |
ryanlecompte/redis_failover | lib/redis_failover/client.rb | RedisFailover.Client.new_clients_for | def new_clients_for(*nodes)
nodes.map do |node|
host, port = node.split(':')
opts = {:host => host, :port => port}
opts.update(:db => @db) if @db
opts.update(:password => @password) if @password
client = Redis.new(@redis_client_options.merge(opts))
if @namespace
client = Redis::Namespace.new(@namespace, :redis => client)
end
@node_addresses[client] = node
client
end
end | ruby | def new_clients_for(*nodes)
nodes.map do |node|
host, port = node.split(':')
opts = {:host => host, :port => port}
opts.update(:db => @db) if @db
opts.update(:password => @password) if @password
client = Redis.new(@redis_client_options.merge(opts))
if @namespace
client = Redis::Namespace.new(@namespace, :redis => client)
end
@node_addresses[client] = node
client
end
end | [
"def",
"new_clients_for",
"(",
"*",
"nodes",
")",
"nodes",
".",
"map",
"do",
"|",
"node",
"|",
"host",
",",
"port",
"=",
"node",
".",
"split",
"(",
"':'",
")",
"opts",
"=",
"{",
":host",
"=>",
"host",
",",
":port",
"=>",
"port",
"}",
"opts",
".",
"update",
"(",
":db",
"=>",
"@db",
")",
"if",
"@db",
"opts",
".",
"update",
"(",
":password",
"=>",
"@password",
")",
"if",
"@password",
"client",
"=",
"Redis",
".",
"new",
"(",
"@redis_client_options",
".",
"merge",
"(",
"opts",
")",
")",
"if",
"@namespace",
"client",
"=",
"Redis",
"::",
"Namespace",
".",
"new",
"(",
"@namespace",
",",
":redis",
"=>",
"client",
")",
"end",
"@node_addresses",
"[",
"client",
"]",
"=",
"node",
"client",
"end",
"end"
]
| Builds new Redis clients for the specified nodes.
@param [Array<String>] nodes the array of redis host:port pairs
@return [Array<Redis>] the array of corresponding Redis clients | [
"Builds",
"new",
"Redis",
"clients",
"for",
"the",
"specified",
"nodes",
"."
]
| be1208240b9b817fb0288edc7535e3f445f767cd | https://github.com/ryanlecompte/redis_failover/blob/be1208240b9b817fb0288edc7535e3f445f767cd/lib/redis_failover/client.rb#L342-L355 | train |
ryanlecompte/redis_failover | lib/redis_failover/client.rb | RedisFailover.Client.verify_role! | def verify_role!(node, role)
current_role = node.info['role']
if current_role.to_sym != role
raise InvalidNodeRoleError.new(address_for(node), role, current_role)
end
role
end | ruby | def verify_role!(node, role)
current_role = node.info['role']
if current_role.to_sym != role
raise InvalidNodeRoleError.new(address_for(node), role, current_role)
end
role
end | [
"def",
"verify_role!",
"(",
"node",
",",
"role",
")",
"current_role",
"=",
"node",
".",
"info",
"[",
"'role'",
"]",
"if",
"current_role",
".",
"to_sym",
"!=",
"role",
"raise",
"InvalidNodeRoleError",
".",
"new",
"(",
"address_for",
"(",
"node",
")",
",",
"role",
",",
"current_role",
")",
"end",
"role",
"end"
]
| Verifies the actual role for a redis node.
@param [Redis] node the redis node to check
@param [Symbol] role the role to verify
@return [Symbol] the verified role
@raise [InvalidNodeRoleError] if the role is invalid | [
"Verifies",
"the",
"actual",
"role",
"for",
"a",
"redis",
"node",
"."
]
| be1208240b9b817fb0288edc7535e3f445f767cd | https://github.com/ryanlecompte/redis_failover/blob/be1208240b9b817fb0288edc7535e3f445f767cd/lib/redis_failover/client.rb#L374-L380 | train |
ryanlecompte/redis_failover | lib/redis_failover/client.rb | RedisFailover.Client.nodes_changed? | def nodes_changed?(new_nodes)
return true if address_for(@master) != new_nodes[:master]
return true if different?(addresses_for(@slaves), new_nodes[:slaves])
false
end | ruby | def nodes_changed?(new_nodes)
return true if address_for(@master) != new_nodes[:master]
return true if different?(addresses_for(@slaves), new_nodes[:slaves])
false
end | [
"def",
"nodes_changed?",
"(",
"new_nodes",
")",
"return",
"true",
"if",
"address_for",
"(",
"@master",
")",
"!=",
"new_nodes",
"[",
":master",
"]",
"return",
"true",
"if",
"different?",
"(",
"addresses_for",
"(",
"@slaves",
")",
",",
"new_nodes",
"[",
":slaves",
"]",
")",
"false",
"end"
]
| Determines if the currently known redis servers is different
from the nodes returned by ZooKeeper.
@param [Array<String>] new_nodes the new redis nodes
@return [Boolean] true if nodes are different, false otherwise | [
"Determines",
"if",
"the",
"currently",
"known",
"redis",
"servers",
"is",
"different",
"from",
"the",
"nodes",
"returned",
"by",
"ZooKeeper",
"."
]
| be1208240b9b817fb0288edc7535e3f445f767cd | https://github.com/ryanlecompte/redis_failover/blob/be1208240b9b817fb0288edc7535e3f445f767cd/lib/redis_failover/client.rb#L413-L417 | train |
ryanlecompte/redis_failover | lib/redis_failover/client.rb | RedisFailover.Client.client_for | def client_for(method)
stack = Thread.current[@current_client_key] ||= []
client = if stack.last
stack.last
elsif @master_only
master
elsif REDIS_READ_OPS.include?(method)
slave
else
master
end
stack << client
client
end | ruby | def client_for(method)
stack = Thread.current[@current_client_key] ||= []
client = if stack.last
stack.last
elsif @master_only
master
elsif REDIS_READ_OPS.include?(method)
slave
else
master
end
stack << client
client
end | [
"def",
"client_for",
"(",
"method",
")",
"stack",
"=",
"Thread",
".",
"current",
"[",
"@current_client_key",
"]",
"||=",
"[",
"]",
"client",
"=",
"if",
"stack",
".",
"last",
"stack",
".",
"last",
"elsif",
"@master_only",
"master",
"elsif",
"REDIS_READ_OPS",
".",
"include?",
"(",
"method",
")",
"slave",
"else",
"master",
"end",
"stack",
"<<",
"client",
"client",
"end"
]
| Acquires a client to use for the specified operation.
@param [Symbol] method the method for which to retrieve a client
@return [Redis] a redis client to use
@note
This method stores a stack of clients used to handle the case
where the same RedisFailover::Client instance is referenced by
nested blocks (e.g., block passed to multi). | [
"Acquires",
"a",
"client",
"to",
"use",
"for",
"the",
"specified",
"operation",
"."
]
| be1208240b9b817fb0288edc7535e3f445f767cd | https://github.com/ryanlecompte/redis_failover/blob/be1208240b9b817fb0288edc7535e3f445f767cd/lib/redis_failover/client.rb#L464-L478 | train |
ryanlecompte/redis_failover | lib/redis_failover/client.rb | RedisFailover.Client.parse_options | def parse_options(options)
@zk, @zkservers = options.values_at(:zk, :zkservers)
if [@zk, @zkservers].all? || [@zk, @zkservers].none?
raise ArgumentError, 'must specify :zk or :zkservers'
end
@root_znode = options.fetch(:znode_path, Util::DEFAULT_ROOT_ZNODE_PATH)
@namespace = options[:namespace]
@password = options[:password]
@db = options[:db]
@retry = options.fetch(:retry_failure, true)
@max_retries = @retry ? options.fetch(:max_retries, 3) : 0
@safe_mode = options.fetch(:safe_mode, true)
@master_only = options.fetch(:master_only, false)
@verify_role = options.fetch(:verify_role, true)
@redis_client_options = Redis::Client::DEFAULTS.keys.each_with_object({}) do |key, hash|
hash[key] = options[key]
end
end | ruby | def parse_options(options)
@zk, @zkservers = options.values_at(:zk, :zkservers)
if [@zk, @zkservers].all? || [@zk, @zkservers].none?
raise ArgumentError, 'must specify :zk or :zkservers'
end
@root_znode = options.fetch(:znode_path, Util::DEFAULT_ROOT_ZNODE_PATH)
@namespace = options[:namespace]
@password = options[:password]
@db = options[:db]
@retry = options.fetch(:retry_failure, true)
@max_retries = @retry ? options.fetch(:max_retries, 3) : 0
@safe_mode = options.fetch(:safe_mode, true)
@master_only = options.fetch(:master_only, false)
@verify_role = options.fetch(:verify_role, true)
@redis_client_options = Redis::Client::DEFAULTS.keys.each_with_object({}) do |key, hash|
hash[key] = options[key]
end
end | [
"def",
"parse_options",
"(",
"options",
")",
"@zk",
",",
"@zkservers",
"=",
"options",
".",
"values_at",
"(",
":zk",
",",
":zkservers",
")",
"if",
"[",
"@zk",
",",
"@zkservers",
"]",
".",
"all?",
"||",
"[",
"@zk",
",",
"@zkservers",
"]",
".",
"none?",
"raise",
"ArgumentError",
",",
"'must specify :zk or :zkservers'",
"end",
"@root_znode",
"=",
"options",
".",
"fetch",
"(",
":znode_path",
",",
"Util",
"::",
"DEFAULT_ROOT_ZNODE_PATH",
")",
"@namespace",
"=",
"options",
"[",
":namespace",
"]",
"@password",
"=",
"options",
"[",
":password",
"]",
"@db",
"=",
"options",
"[",
":db",
"]",
"@retry",
"=",
"options",
".",
"fetch",
"(",
":retry_failure",
",",
"true",
")",
"@max_retries",
"=",
"@retry",
"?",
"options",
".",
"fetch",
"(",
":max_retries",
",",
"3",
")",
":",
"0",
"@safe_mode",
"=",
"options",
".",
"fetch",
"(",
":safe_mode",
",",
"true",
")",
"@master_only",
"=",
"options",
".",
"fetch",
"(",
":master_only",
",",
"false",
")",
"@verify_role",
"=",
"options",
".",
"fetch",
"(",
":verify_role",
",",
"true",
")",
"@redis_client_options",
"=",
"Redis",
"::",
"Client",
"::",
"DEFAULTS",
".",
"keys",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"key",
",",
"hash",
"|",
"hash",
"[",
"key",
"]",
"=",
"options",
"[",
"key",
"]",
"end",
"end"
]
| Parses the configuration operations.
@param [Hash] options the configuration options | [
"Parses",
"the",
"configuration",
"operations",
"."
]
| be1208240b9b817fb0288edc7535e3f445f767cd | https://github.com/ryanlecompte/redis_failover/blob/be1208240b9b817fb0288edc7535e3f445f767cd/lib/redis_failover/client.rb#L491-L510 | train |
ryanlecompte/redis_failover | lib/redis_failover/node.rb | RedisFailover.Node.make_slave! | def make_slave!(node)
perform_operation do |redis|
unless slave_of?(node)
redis.slaveof(node.host, node.port)
logger.info("#{self} is now a slave of #{node}")
wakeup
end
end
end | ruby | def make_slave!(node)
perform_operation do |redis|
unless slave_of?(node)
redis.slaveof(node.host, node.port)
logger.info("#{self} is now a slave of #{node}")
wakeup
end
end
end | [
"def",
"make_slave!",
"(",
"node",
")",
"perform_operation",
"do",
"|",
"redis",
"|",
"unless",
"slave_of?",
"(",
"node",
")",
"redis",
".",
"slaveof",
"(",
"node",
".",
"host",
",",
"node",
".",
"port",
")",
"logger",
".",
"info",
"(",
"\"#{self} is now a slave of #{node}\"",
")",
"wakeup",
"end",
"end",
"end"
]
| Makes this node a slave of the given node.
@param [Node] node the node of which to become a slave | [
"Makes",
"this",
"node",
"a",
"slave",
"of",
"the",
"given",
"node",
"."
]
| be1208240b9b817fb0288edc7535e3f445f767cd | https://github.com/ryanlecompte/redis_failover/blob/be1208240b9b817fb0288edc7535e3f445f767cd/lib/redis_failover/node.rb#L80-L88 | train |
ryanlecompte/redis_failover | lib/redis_failover/node.rb | RedisFailover.Node.perform_operation | def perform_operation
redis = nil
Timeout.timeout(MAX_OP_WAIT_TIME) do
redis = new_client
yield redis
end
rescue Exception => ex
raise NodeUnavailableError, "#{ex.class}: #{ex.message}", ex.backtrace
ensure
if redis
begin
redis.client.disconnect
rescue Exception => ex
raise NodeUnavailableError, "#{ex.class}: #{ex.message}", ex.backtrace
end
end
end | ruby | def perform_operation
redis = nil
Timeout.timeout(MAX_OP_WAIT_TIME) do
redis = new_client
yield redis
end
rescue Exception => ex
raise NodeUnavailableError, "#{ex.class}: #{ex.message}", ex.backtrace
ensure
if redis
begin
redis.client.disconnect
rescue Exception => ex
raise NodeUnavailableError, "#{ex.class}: #{ex.message}", ex.backtrace
end
end
end | [
"def",
"perform_operation",
"redis",
"=",
"nil",
"Timeout",
".",
"timeout",
"(",
"MAX_OP_WAIT_TIME",
")",
"do",
"redis",
"=",
"new_client",
"yield",
"redis",
"end",
"rescue",
"Exception",
"=>",
"ex",
"raise",
"NodeUnavailableError",
",",
"\"#{ex.class}: #{ex.message}\"",
",",
"ex",
".",
"backtrace",
"ensure",
"if",
"redis",
"begin",
"redis",
".",
"client",
".",
"disconnect",
"rescue",
"Exception",
"=>",
"ex",
"raise",
"NodeUnavailableError",
",",
"\"#{ex.class}: #{ex.message}\"",
",",
"ex",
".",
"backtrace",
"end",
"end",
"end"
]
| Safely performs a redis operation within a given timeout window.
@yield [Redis] the redis client to use for the operation
@raise [NodeUnavailableError] if node is currently unreachable | [
"Safely",
"performs",
"a",
"redis",
"operation",
"within",
"a",
"given",
"timeout",
"window",
"."
]
| be1208240b9b817fb0288edc7535e3f445f767cd | https://github.com/ryanlecompte/redis_failover/blob/be1208240b9b817fb0288edc7535e3f445f767cd/lib/redis_failover/node.rb#L172-L188 | train |
ryanlecompte/redis_failover | lib/redis_failover/node_manager.rb | RedisFailover.NodeManager.setup_zk | def setup_zk
unless @zk
@zk = ZK.new("#{@options[:zkservers]}#{@options[:chroot] || ''}")
@zk.register(manual_failover_path) do |event|
handle_manual_failover_update(event)
end
@zk.on_connected { @zk.stat(manual_failover_path, :watch => true) }
end
create_path(@root_znode)
create_path(current_state_root)
@zk.stat(manual_failover_path, :watch => true)
end | ruby | def setup_zk
unless @zk
@zk = ZK.new("#{@options[:zkservers]}#{@options[:chroot] || ''}")
@zk.register(manual_failover_path) do |event|
handle_manual_failover_update(event)
end
@zk.on_connected { @zk.stat(manual_failover_path, :watch => true) }
end
create_path(@root_znode)
create_path(current_state_root)
@zk.stat(manual_failover_path, :watch => true)
end | [
"def",
"setup_zk",
"unless",
"@zk",
"@zk",
"=",
"ZK",
".",
"new",
"(",
"\"#{@options[:zkservers]}#{@options[:chroot] || ''}\"",
")",
"@zk",
".",
"register",
"(",
"manual_failover_path",
")",
"do",
"|",
"event",
"|",
"handle_manual_failover_update",
"(",
"event",
")",
"end",
"@zk",
".",
"on_connected",
"{",
"@zk",
".",
"stat",
"(",
"manual_failover_path",
",",
":watch",
"=>",
"true",
")",
"}",
"end",
"create_path",
"(",
"@root_znode",
")",
"create_path",
"(",
"current_state_root",
")",
"@zk",
".",
"stat",
"(",
"manual_failover_path",
",",
":watch",
"=>",
"true",
")",
"end"
]
| Configures the ZooKeeper client. | [
"Configures",
"the",
"ZooKeeper",
"client",
"."
]
| be1208240b9b817fb0288edc7535e3f445f767cd | https://github.com/ryanlecompte/redis_failover/blob/be1208240b9b817fb0288edc7535e3f445f767cd/lib/redis_failover/node_manager.rb#L110-L122 | train |
ryanlecompte/redis_failover | lib/redis_failover/node_manager.rb | RedisFailover.NodeManager.handle_unavailable | def handle_unavailable(node, snapshots)
# no-op if we already know about this node
return if @unavailable.include?(node)
logger.info("Handling unavailable node: #{node}")
@unavailable << node
# find a new master if this node was a master
if node == @master
logger.info("Demoting currently unavailable master #{node}.")
promote_new_master(snapshots)
else
@slaves.delete(node)
end
end | ruby | def handle_unavailable(node, snapshots)
# no-op if we already know about this node
return if @unavailable.include?(node)
logger.info("Handling unavailable node: #{node}")
@unavailable << node
# find a new master if this node was a master
if node == @master
logger.info("Demoting currently unavailable master #{node}.")
promote_new_master(snapshots)
else
@slaves.delete(node)
end
end | [
"def",
"handle_unavailable",
"(",
"node",
",",
"snapshots",
")",
"return",
"if",
"@unavailable",
".",
"include?",
"(",
"node",
")",
"logger",
".",
"info",
"(",
"\"Handling unavailable node: #{node}\"",
")",
"@unavailable",
"<<",
"node",
"if",
"node",
"==",
"@master",
"logger",
".",
"info",
"(",
"\"Demoting currently unavailable master #{node}.\"",
")",
"promote_new_master",
"(",
"snapshots",
")",
"else",
"@slaves",
".",
"delete",
"(",
"node",
")",
"end",
"end"
]
| Handles an unavailable node.
@param [Node] node the unavailable node
@param [Hash<Node, NodeSnapshot>] snapshots the current set of snapshots | [
"Handles",
"an",
"unavailable",
"node",
"."
]
| be1208240b9b817fb0288edc7535e3f445f767cd | https://github.com/ryanlecompte/redis_failover/blob/be1208240b9b817fb0288edc7535e3f445f767cd/lib/redis_failover/node_manager.rb#L128-L141 | train |
ryanlecompte/redis_failover | lib/redis_failover/node_manager.rb | RedisFailover.NodeManager.handle_available | def handle_available(node, snapshots)
reconcile(node)
# no-op if we already know about this node
return if @master == node || (@master && @slaves.include?(node))
logger.info("Handling available node: #{node}")
if @master
# master already exists, make a slave
node.make_slave!(@master)
@slaves << node
else
# no master exists, make this the new master
promote_new_master(snapshots, node)
end
@unavailable.delete(node)
end | ruby | def handle_available(node, snapshots)
reconcile(node)
# no-op if we already know about this node
return if @master == node || (@master && @slaves.include?(node))
logger.info("Handling available node: #{node}")
if @master
# master already exists, make a slave
node.make_slave!(@master)
@slaves << node
else
# no master exists, make this the new master
promote_new_master(snapshots, node)
end
@unavailable.delete(node)
end | [
"def",
"handle_available",
"(",
"node",
",",
"snapshots",
")",
"reconcile",
"(",
"node",
")",
"return",
"if",
"@master",
"==",
"node",
"||",
"(",
"@master",
"&&",
"@slaves",
".",
"include?",
"(",
"node",
")",
")",
"logger",
".",
"info",
"(",
"\"Handling available node: #{node}\"",
")",
"if",
"@master",
"node",
".",
"make_slave!",
"(",
"@master",
")",
"@slaves",
"<<",
"node",
"else",
"promote_new_master",
"(",
"snapshots",
",",
"node",
")",
"end",
"@unavailable",
".",
"delete",
"(",
"node",
")",
"end"
]
| Handles an available node.
@param [Node] node the available node
@param [Hash<Node, NodeSnapshot>] snapshots the current set of snapshots | [
"Handles",
"an",
"available",
"node",
"."
]
| be1208240b9b817fb0288edc7535e3f445f767cd | https://github.com/ryanlecompte/redis_failover/blob/be1208240b9b817fb0288edc7535e3f445f767cd/lib/redis_failover/node_manager.rb#L147-L164 | train |
ryanlecompte/redis_failover | lib/redis_failover/node_manager.rb | RedisFailover.NodeManager.handle_syncing | def handle_syncing(node, snapshots)
reconcile(node)
if node.syncing_with_master? && node.prohibits_stale_reads?
logger.info("Node #{node} not ready yet, still syncing with master.")
force_unavailable_slave(node)
else
# otherwise, we can use this node
handle_available(node, snapshots)
end
end | ruby | def handle_syncing(node, snapshots)
reconcile(node)
if node.syncing_with_master? && node.prohibits_stale_reads?
logger.info("Node #{node} not ready yet, still syncing with master.")
force_unavailable_slave(node)
else
# otherwise, we can use this node
handle_available(node, snapshots)
end
end | [
"def",
"handle_syncing",
"(",
"node",
",",
"snapshots",
")",
"reconcile",
"(",
"node",
")",
"if",
"node",
".",
"syncing_with_master?",
"&&",
"node",
".",
"prohibits_stale_reads?",
"logger",
".",
"info",
"(",
"\"Node #{node} not ready yet, still syncing with master.\"",
")",
"force_unavailable_slave",
"(",
"node",
")",
"else",
"handle_available",
"(",
"node",
",",
"snapshots",
")",
"end",
"end"
]
| Handles a node that is currently syncing.
@param [Node] node the syncing node
@param [Hash<Node, NodeSnapshot>] snapshots the current set of snapshots | [
"Handles",
"a",
"node",
"that",
"is",
"currently",
"syncing",
"."
]
| be1208240b9b817fb0288edc7535e3f445f767cd | https://github.com/ryanlecompte/redis_failover/blob/be1208240b9b817fb0288edc7535e3f445f767cd/lib/redis_failover/node_manager.rb#L170-L180 | train |
ryanlecompte/redis_failover | lib/redis_failover/node_manager.rb | RedisFailover.NodeManager.handle_manual_failover | def handle_manual_failover(node, snapshots)
# no-op if node to be failed over is already master
return if @master == node
logger.info("Handling manual failover")
# ensure we can talk to the node
node.ping
# make current master a slave, and promote new master
@slaves << @master if @master
@slaves.delete(node)
promote_new_master(snapshots, node)
end | ruby | def handle_manual_failover(node, snapshots)
# no-op if node to be failed over is already master
return if @master == node
logger.info("Handling manual failover")
# ensure we can talk to the node
node.ping
# make current master a slave, and promote new master
@slaves << @master if @master
@slaves.delete(node)
promote_new_master(snapshots, node)
end | [
"def",
"handle_manual_failover",
"(",
"node",
",",
"snapshots",
")",
"return",
"if",
"@master",
"==",
"node",
"logger",
".",
"info",
"(",
"\"Handling manual failover\"",
")",
"node",
".",
"ping",
"@slaves",
"<<",
"@master",
"if",
"@master",
"@slaves",
".",
"delete",
"(",
"node",
")",
"promote_new_master",
"(",
"snapshots",
",",
"node",
")",
"end"
]
| Handles a manual failover request to the given node.
@param [Node] node the candidate node for failover
@param [Hash<Node, NodeSnapshot>] snapshots the current set of snapshots | [
"Handles",
"a",
"manual",
"failover",
"request",
"to",
"the",
"given",
"node",
"."
]
| be1208240b9b817fb0288edc7535e3f445f767cd | https://github.com/ryanlecompte/redis_failover/blob/be1208240b9b817fb0288edc7535e3f445f767cd/lib/redis_failover/node_manager.rb#L186-L198 | train |
ryanlecompte/redis_failover | lib/redis_failover/node_manager.rb | RedisFailover.NodeManager.promote_new_master | def promote_new_master(snapshots, node = nil)
delete_path(redis_nodes_path)
@master = nil
# make a specific node or selected candidate the new master
candidate = node || failover_strategy_candidate(snapshots)
if candidate.nil?
logger.error('Failed to promote a new master, no candidate available.')
else
@slaves.delete(candidate)
@unavailable.delete(candidate)
redirect_slaves_to(candidate)
candidate.make_master!
@master = candidate
write_current_redis_nodes
@master_promotion_attempts = 0
logger.info("Successfully promoted #{candidate} to master.")
end
end | ruby | def promote_new_master(snapshots, node = nil)
delete_path(redis_nodes_path)
@master = nil
# make a specific node or selected candidate the new master
candidate = node || failover_strategy_candidate(snapshots)
if candidate.nil?
logger.error('Failed to promote a new master, no candidate available.')
else
@slaves.delete(candidate)
@unavailable.delete(candidate)
redirect_slaves_to(candidate)
candidate.make_master!
@master = candidate
write_current_redis_nodes
@master_promotion_attempts = 0
logger.info("Successfully promoted #{candidate} to master.")
end
end | [
"def",
"promote_new_master",
"(",
"snapshots",
",",
"node",
"=",
"nil",
")",
"delete_path",
"(",
"redis_nodes_path",
")",
"@master",
"=",
"nil",
"candidate",
"=",
"node",
"||",
"failover_strategy_candidate",
"(",
"snapshots",
")",
"if",
"candidate",
".",
"nil?",
"logger",
".",
"error",
"(",
"'Failed to promote a new master, no candidate available.'",
")",
"else",
"@slaves",
".",
"delete",
"(",
"candidate",
")",
"@unavailable",
".",
"delete",
"(",
"candidate",
")",
"redirect_slaves_to",
"(",
"candidate",
")",
"candidate",
".",
"make_master!",
"@master",
"=",
"candidate",
"write_current_redis_nodes",
"@master_promotion_attempts",
"=",
"0",
"logger",
".",
"info",
"(",
"\"Successfully promoted #{candidate} to master.\"",
")",
"end",
"end"
]
| Promotes a new master.
@param [Hash<Node, NodeSnapshot>] snapshots the current set of snapshots
@param [Node] node the optional node to promote | [
"Promotes",
"a",
"new",
"master",
"."
]
| be1208240b9b817fb0288edc7535e3f445f767cd | https://github.com/ryanlecompte/redis_failover/blob/be1208240b9b817fb0288edc7535e3f445f767cd/lib/redis_failover/node_manager.rb#L204-L223 | train |
ryanlecompte/redis_failover | lib/redis_failover/node_manager.rb | RedisFailover.NodeManager.find_existing_master | def find_existing_master
if data = @zk.get(redis_nodes_path).first
nodes = symbolize_keys(decode(data))
master = node_from(nodes[:master])
logger.info("Master from existing znode config: #{master || 'none'}")
# Check for case where a node previously thought to be the master was
# somehow manually reconfigured to be a slave outside of the node manager's
# control.
begin
if master && master.slave?
raise InvalidNodeRoleError.new(master, :master, :slave)
end
rescue RedisFailover::NodeUnavailableError => ex
logger.warn("Failed to check whether existing master has invalid role: #{ex.inspect}")
end
master
end
rescue ZK::Exceptions::NoNode
# blank slate, no last known master
nil
end | ruby | def find_existing_master
if data = @zk.get(redis_nodes_path).first
nodes = symbolize_keys(decode(data))
master = node_from(nodes[:master])
logger.info("Master from existing znode config: #{master || 'none'}")
# Check for case where a node previously thought to be the master was
# somehow manually reconfigured to be a slave outside of the node manager's
# control.
begin
if master && master.slave?
raise InvalidNodeRoleError.new(master, :master, :slave)
end
rescue RedisFailover::NodeUnavailableError => ex
logger.warn("Failed to check whether existing master has invalid role: #{ex.inspect}")
end
master
end
rescue ZK::Exceptions::NoNode
# blank slate, no last known master
nil
end | [
"def",
"find_existing_master",
"if",
"data",
"=",
"@zk",
".",
"get",
"(",
"redis_nodes_path",
")",
".",
"first",
"nodes",
"=",
"symbolize_keys",
"(",
"decode",
"(",
"data",
")",
")",
"master",
"=",
"node_from",
"(",
"nodes",
"[",
":master",
"]",
")",
"logger",
".",
"info",
"(",
"\"Master from existing znode config: #{master || 'none'}\"",
")",
"begin",
"if",
"master",
"&&",
"master",
".",
"slave?",
"raise",
"InvalidNodeRoleError",
".",
"new",
"(",
"master",
",",
":master",
",",
":slave",
")",
"end",
"rescue",
"RedisFailover",
"::",
"NodeUnavailableError",
"=>",
"ex",
"logger",
".",
"warn",
"(",
"\"Failed to check whether existing master has invalid role: #{ex.inspect}\"",
")",
"end",
"master",
"end",
"rescue",
"ZK",
"::",
"Exceptions",
"::",
"NoNode",
"nil",
"end"
]
| Seeds the initial node master from an existing znode config. | [
"Seeds",
"the",
"initial",
"node",
"master",
"from",
"an",
"existing",
"znode",
"config",
"."
]
| be1208240b9b817fb0288edc7535e3f445f767cd | https://github.com/ryanlecompte/redis_failover/blob/be1208240b9b817fb0288edc7535e3f445f767cd/lib/redis_failover/node_manager.rb#L254-L275 | train |
ryanlecompte/redis_failover | lib/redis_failover/node_manager.rb | RedisFailover.NodeManager.node_from | def node_from(node_string)
return if node_string.nil?
host, port = node_string.split(':', 2)
Node.new(:host => host, :port => port, :password => @options[:password])
end | ruby | def node_from(node_string)
return if node_string.nil?
host, port = node_string.split(':', 2)
Node.new(:host => host, :port => port, :password => @options[:password])
end | [
"def",
"node_from",
"(",
"node_string",
")",
"return",
"if",
"node_string",
".",
"nil?",
"host",
",",
"port",
"=",
"node_string",
".",
"split",
"(",
"':'",
",",
"2",
")",
"Node",
".",
"new",
"(",
":host",
"=>",
"host",
",",
":port",
"=>",
"port",
",",
":password",
"=>",
"@options",
"[",
":password",
"]",
")",
"end"
]
| Creates a Node instance from a string.
@param [String] node_string a string representation of a node (e.g., host:port)
@return [Node] the Node representation | [
"Creates",
"a",
"Node",
"instance",
"from",
"a",
"string",
"."
]
| be1208240b9b817fb0288edc7535e3f445f767cd | https://github.com/ryanlecompte/redis_failover/blob/be1208240b9b817fb0288edc7535e3f445f767cd/lib/redis_failover/node_manager.rb#L281-L285 | train |
ryanlecompte/redis_failover | lib/redis_failover/node_manager.rb | RedisFailover.NodeManager.guess_master | def guess_master(nodes)
master_nodes = nodes.select { |node| node.master? }
raise NoMasterError if master_nodes.empty?
raise MultipleMastersError.new(master_nodes) if master_nodes.size > 1
master_nodes.first
end | ruby | def guess_master(nodes)
master_nodes = nodes.select { |node| node.master? }
raise NoMasterError if master_nodes.empty?
raise MultipleMastersError.new(master_nodes) if master_nodes.size > 1
master_nodes.first
end | [
"def",
"guess_master",
"(",
"nodes",
")",
"master_nodes",
"=",
"nodes",
".",
"select",
"{",
"|",
"node",
"|",
"node",
".",
"master?",
"}",
"raise",
"NoMasterError",
"if",
"master_nodes",
".",
"empty?",
"raise",
"MultipleMastersError",
".",
"new",
"(",
"master_nodes",
")",
"if",
"master_nodes",
".",
"size",
">",
"1",
"master_nodes",
".",
"first",
"end"
]
| Searches for the master node.
@param [Array<Node>] nodes the nodes to search
@return [Node] the found master node, nil if not found | [
"Searches",
"for",
"the",
"master",
"node",
"."
]
| be1208240b9b817fb0288edc7535e3f445f767cd | https://github.com/ryanlecompte/redis_failover/blob/be1208240b9b817fb0288edc7535e3f445f767cd/lib/redis_failover/node_manager.rb#L302-L307 | train |
ryanlecompte/redis_failover | lib/redis_failover/node_manager.rb | RedisFailover.NodeManager.redirect_slaves_to | def redirect_slaves_to(node)
@slaves.dup.each do |slave|
begin
slave.make_slave!(node)
rescue NodeUnavailableError
logger.info("Failed to redirect unreachable slave #{slave} to #{node}")
force_unavailable_slave(slave)
end
end
end | ruby | def redirect_slaves_to(node)
@slaves.dup.each do |slave|
begin
slave.make_slave!(node)
rescue NodeUnavailableError
logger.info("Failed to redirect unreachable slave #{slave} to #{node}")
force_unavailable_slave(slave)
end
end
end | [
"def",
"redirect_slaves_to",
"(",
"node",
")",
"@slaves",
".",
"dup",
".",
"each",
"do",
"|",
"slave",
"|",
"begin",
"slave",
".",
"make_slave!",
"(",
"node",
")",
"rescue",
"NodeUnavailableError",
"logger",
".",
"info",
"(",
"\"Failed to redirect unreachable slave #{slave} to #{node}\"",
")",
"force_unavailable_slave",
"(",
"slave",
")",
"end",
"end",
"end"
]
| Redirects all slaves to the specified node.
@param [Node] node the node to which slaves are redirected | [
"Redirects",
"all",
"slaves",
"to",
"the",
"specified",
"node",
"."
]
| be1208240b9b817fb0288edc7535e3f445f767cd | https://github.com/ryanlecompte/redis_failover/blob/be1208240b9b817fb0288edc7535e3f445f767cd/lib/redis_failover/node_manager.rb#L312-L321 | train |
ryanlecompte/redis_failover | lib/redis_failover/node_manager.rb | RedisFailover.NodeManager.reconcile | def reconcile(node)
return if @master == node && node.master?
return if @master && node.slave_of?(@master)
logger.info("Reconciling node #{node}")
if @master == node && !node.master?
# we think the node is a master, but the node doesn't
node.make_master!
return
end
# verify that node is a slave for the current master
if @master && !node.slave_of?(@master)
node.make_slave!(@master)
end
end | ruby | def reconcile(node)
return if @master == node && node.master?
return if @master && node.slave_of?(@master)
logger.info("Reconciling node #{node}")
if @master == node && !node.master?
# we think the node is a master, but the node doesn't
node.make_master!
return
end
# verify that node is a slave for the current master
if @master && !node.slave_of?(@master)
node.make_slave!(@master)
end
end | [
"def",
"reconcile",
"(",
"node",
")",
"return",
"if",
"@master",
"==",
"node",
"&&",
"node",
".",
"master?",
"return",
"if",
"@master",
"&&",
"node",
".",
"slave_of?",
"(",
"@master",
")",
"logger",
".",
"info",
"(",
"\"Reconciling node #{node}\"",
")",
"if",
"@master",
"==",
"node",
"&&",
"!",
"node",
".",
"master?",
"node",
".",
"make_master!",
"return",
"end",
"if",
"@master",
"&&",
"!",
"node",
".",
"slave_of?",
"(",
"@master",
")",
"node",
".",
"make_slave!",
"(",
"@master",
")",
"end",
"end"
]
| It's possible that a newly available node may have been restarted
and completely lost its dynamically set run-time role by the node
manager. This method ensures that the node resumes its role as
determined by the manager.
@param [Node] node the node to reconcile | [
"It",
"s",
"possible",
"that",
"a",
"newly",
"available",
"node",
"may",
"have",
"been",
"restarted",
"and",
"completely",
"lost",
"its",
"dynamically",
"set",
"run",
"-",
"time",
"role",
"by",
"the",
"node",
"manager",
".",
"This",
"method",
"ensures",
"that",
"the",
"node",
"resumes",
"its",
"role",
"as",
"determined",
"by",
"the",
"manager",
"."
]
| be1208240b9b817fb0288edc7535e3f445f767cd | https://github.com/ryanlecompte/redis_failover/blob/be1208240b9b817fb0288edc7535e3f445f767cd/lib/redis_failover/node_manager.rb#L337-L352 | train |
ryanlecompte/redis_failover | lib/redis_failover/node_manager.rb | RedisFailover.NodeManager.delete_path | def delete_path(path)
@zk.delete(path)
logger.info("Deleted ZK node #{path}")
rescue ZK::Exceptions::NoNode => ex
logger.info("Tried to delete missing znode: #{ex.inspect}")
end | ruby | def delete_path(path)
@zk.delete(path)
logger.info("Deleted ZK node #{path}")
rescue ZK::Exceptions::NoNode => ex
logger.info("Tried to delete missing znode: #{ex.inspect}")
end | [
"def",
"delete_path",
"(",
"path",
")",
"@zk",
".",
"delete",
"(",
"path",
")",
"logger",
".",
"info",
"(",
"\"Deleted ZK node #{path}\"",
")",
"rescue",
"ZK",
"::",
"Exceptions",
"::",
"NoNode",
"=>",
"ex",
"logger",
".",
"info",
"(",
"\"Tried to delete missing znode: #{ex.inspect}\"",
")",
"end"
]
| Deletes the znode path containing the redis nodes.
@param [String] path the znode path to delete | [
"Deletes",
"the",
"znode",
"path",
"containing",
"the",
"redis",
"nodes",
"."
]
| be1208240b9b817fb0288edc7535e3f445f767cd | https://github.com/ryanlecompte/redis_failover/blob/be1208240b9b817fb0288edc7535e3f445f767cd/lib/redis_failover/node_manager.rb#L375-L380 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.