repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
shortdudey123/yamllint | lib/yamllint/linter.rb | YamlLint.Linter.check_stream | def check_stream(io_stream)
yaml_data = io_stream.read
error_array = []
valid = check_data(yaml_data, error_array)
errors[''] = error_array unless error_array.empty?
valid
end | ruby | def check_stream(io_stream)
yaml_data = io_stream.read
error_array = []
valid = check_data(yaml_data, error_array)
errors[''] = error_array unless error_array.empty?
valid
end | [
"def",
"check_stream",
"(",
"io_stream",
")",
"yaml_data",
"=",
"io_stream",
".",
"read",
"error_array",
"=",
"[",
"]",
"valid",
"=",
"check_data",
"(",
"yaml_data",
",",
"error_array",
")",
"errors",
"[",
"''",
"]",
"=",
"error_array",
"unless",
"error_array",
".",
"empty?",
"valid",
"end"
] | Check an IO stream | [
"Check",
"an",
"IO",
"stream"
] | aa8e0538882eddcd2996f6f62fabaafda3fdb942 | https://github.com/shortdudey123/yamllint/blob/aa8e0538882eddcd2996f6f62fabaafda3fdb942/lib/yamllint/linter.rb#L56-L64 | train |
shortdudey123/yamllint | lib/yamllint/linter.rb | YamlLint.Linter.display_errors | def display_errors
errors.each do |path, errors|
puts path
errors.each do |err|
puts " #{err}"
end
end
end | ruby | def display_errors
errors.each do |path, errors|
puts path
errors.each do |err|
puts " #{err}"
end
end
end | [
"def",
"display_errors",
"errors",
".",
"each",
"do",
"|",
"path",
",",
"errors",
"|",
"puts",
"path",
"errors",
".",
"each",
"do",
"|",
"err",
"|",
"puts",
"\" #{err}\"",
"end",
"end",
"end"
] | Output the lint errors | [
"Output",
"the",
"lint",
"errors"
] | aa8e0538882eddcd2996f6f62fabaafda3fdb942 | https://github.com/shortdudey123/yamllint/blob/aa8e0538882eddcd2996f6f62fabaafda3fdb942/lib/yamllint/linter.rb#L77-L84 | train |
shortdudey123/yamllint | lib/yamllint/linter.rb | YamlLint.Linter.check_filename | def check_filename(filename)
extension = filename.split('.').last
return true if valid_extensions.include?(extension)
false
end | ruby | def check_filename(filename)
extension = filename.split('.').last
return true if valid_extensions.include?(extension)
false
end | [
"def",
"check_filename",
"(",
"filename",
")",
"extension",
"=",
"filename",
".",
"split",
"(",
"'.'",
")",
".",
"last",
"return",
"true",
"if",
"valid_extensions",
".",
"include?",
"(",
"extension",
")",
"false",
"end"
] | Check file extension | [
"Check",
"file",
"extension"
] | aa8e0538882eddcd2996f6f62fabaafda3fdb942 | https://github.com/shortdudey123/yamllint/blob/aa8e0538882eddcd2996f6f62fabaafda3fdb942/lib/yamllint/linter.rb#L89-L93 | train |
shortdudey123/yamllint | lib/yamllint/linter.rb | YamlLint.Linter.check_data | def check_data(yaml_data, errors_array)
valid = check_not_empty?(yaml_data, errors_array)
valid &&= check_syntax_valid?(yaml_data, errors_array)
valid &&= check_overlapping_keys?(yaml_data, errors_array)
valid
end | ruby | def check_data(yaml_data, errors_array)
valid = check_not_empty?(yaml_data, errors_array)
valid &&= check_syntax_valid?(yaml_data, errors_array)
valid &&= check_overlapping_keys?(yaml_data, errors_array)
valid
end | [
"def",
"check_data",
"(",
"yaml_data",
",",
"errors_array",
")",
"valid",
"=",
"check_not_empty?",
"(",
"yaml_data",
",",
"errors_array",
")",
"valid",
"&&=",
"check_syntax_valid?",
"(",
"yaml_data",
",",
"errors_array",
")",
"valid",
"&&=",
"check_overlapping_keys?",
"(",
"yaml_data",
",",
"errors_array",
")",
"valid",
"end"
] | Check the data in the file or stream | [
"Check",
"the",
"data",
"in",
"the",
"file",
"or",
"stream"
] | aa8e0538882eddcd2996f6f62fabaafda3fdb942 | https://github.com/shortdudey123/yamllint/blob/aa8e0538882eddcd2996f6f62fabaafda3fdb942/lib/yamllint/linter.rb#L96-L102 | train |
shortdudey123/yamllint | lib/yamllint/linter.rb | YamlLint.Linter.check_not_empty? | def check_not_empty?(yaml_data, errors_array)
if yaml_data.empty?
errors_array << 'The YAML should not be an empty string'
false
elsif yaml_data.strip.empty?
errors_array << 'The YAML should not just be spaces'
false
else
true
end
end | ruby | def check_not_empty?(yaml_data, errors_array)
if yaml_data.empty?
errors_array << 'The YAML should not be an empty string'
false
elsif yaml_data.strip.empty?
errors_array << 'The YAML should not just be spaces'
false
else
true
end
end | [
"def",
"check_not_empty?",
"(",
"yaml_data",
",",
"errors_array",
")",
"if",
"yaml_data",
".",
"empty?",
"errors_array",
"<<",
"'The YAML should not be an empty string'",
"false",
"elsif",
"yaml_data",
".",
"strip",
".",
"empty?",
"errors_array",
"<<",
"'The YAML should not just be spaces'",
"false",
"else",
"true",
"end",
"end"
] | Check that the data is not empty | [
"Check",
"that",
"the",
"data",
"is",
"not",
"empty"
] | aa8e0538882eddcd2996f6f62fabaafda3fdb942 | https://github.com/shortdudey123/yamllint/blob/aa8e0538882eddcd2996f6f62fabaafda3fdb942/lib/yamllint/linter.rb#L105-L115 | train |
shortdudey123/yamllint | lib/yamllint/linter.rb | YamlLint.Linter.check_syntax_valid? | def check_syntax_valid?(yaml_data, errors_array)
YAML.safe_load(yaml_data)
true
rescue YAML::SyntaxError => e
errors_array << e.message
false
end | ruby | def check_syntax_valid?(yaml_data, errors_array)
YAML.safe_load(yaml_data)
true
rescue YAML::SyntaxError => e
errors_array << e.message
false
end | [
"def",
"check_syntax_valid?",
"(",
"yaml_data",
",",
"errors_array",
")",
"YAML",
".",
"safe_load",
"(",
"yaml_data",
")",
"true",
"rescue",
"YAML",
"::",
"SyntaxError",
"=>",
"e",
"errors_array",
"<<",
"e",
".",
"message",
"false",
"end"
] | Check that the data is valid YAML | [
"Check",
"that",
"the",
"data",
"is",
"valid",
"YAML"
] | aa8e0538882eddcd2996f6f62fabaafda3fdb942 | https://github.com/shortdudey123/yamllint/blob/aa8e0538882eddcd2996f6f62fabaafda3fdb942/lib/yamllint/linter.rb#L118-L124 | train |
shortdudey123/yamllint | lib/yamllint/linter.rb | YamlLint.Linter.check_overlapping_keys? | def check_overlapping_keys?(yaml_data, errors_array)
overlap_detector = KeyOverlapDetector.new
data = Psych.parser.parse(yaml_data)
overlap_detector.parse(data)
overlap_detector.overlapping_keys.each do |key|
err_meg = "The same key is defined more than once: #{key.join('.')}"
errors_array << err_meg
end
overlap_detector.overlapping_keys.empty?
end | ruby | def check_overlapping_keys?(yaml_data, errors_array)
overlap_detector = KeyOverlapDetector.new
data = Psych.parser.parse(yaml_data)
overlap_detector.parse(data)
overlap_detector.overlapping_keys.each do |key|
err_meg = "The same key is defined more than once: #{key.join('.')}"
errors_array << err_meg
end
overlap_detector.overlapping_keys.empty?
end | [
"def",
"check_overlapping_keys?",
"(",
"yaml_data",
",",
"errors_array",
")",
"overlap_detector",
"=",
"KeyOverlapDetector",
".",
"new",
"data",
"=",
"Psych",
".",
"parser",
".",
"parse",
"(",
"yaml_data",
")",
"overlap_detector",
".",
"parse",
"(",
"data",
")",
"overlap_detector",
".",
"overlapping_keys",
".",
"each",
"do",
"|",
"key",
"|",
"err_meg",
"=",
"\"The same key is defined more than once: #{key.join('.')}\"",
"errors_array",
"<<",
"err_meg",
"end",
"overlap_detector",
".",
"overlapping_keys",
".",
"empty?",
"end"
] | Check if there is overlapping key | [
"Check",
"if",
"there",
"is",
"overlapping",
"key"
] | aa8e0538882eddcd2996f6f62fabaafda3fdb942 | https://github.com/shortdudey123/yamllint/blob/aa8e0538882eddcd2996f6f62fabaafda3fdb942/lib/yamllint/linter.rb#L258-L270 | train |
flori/term-ansicolor | lib/term/ansicolor.rb | Term.ANSIColor.uncolor | def uncolor(string = nil) # :yields:
if block_given?
yield.to_str.gsub(COLORED_REGEXP, '')
elsif string.respond_to?(:to_str)
string.to_str.gsub(COLORED_REGEXP, '')
elsif respond_to?(:to_str)
to_str.gsub(COLORED_REGEXP, '')
else
''
end.extend(Term::ANSIColor)
end | ruby | def uncolor(string = nil) # :yields:
if block_given?
yield.to_str.gsub(COLORED_REGEXP, '')
elsif string.respond_to?(:to_str)
string.to_str.gsub(COLORED_REGEXP, '')
elsif respond_to?(:to_str)
to_str.gsub(COLORED_REGEXP, '')
else
''
end.extend(Term::ANSIColor)
end | [
"def",
"uncolor",
"(",
"string",
"=",
"nil",
")",
"if",
"block_given?",
"yield",
".",
"to_str",
".",
"gsub",
"(",
"COLORED_REGEXP",
",",
"''",
")",
"elsif",
"string",
".",
"respond_to?",
"(",
":to_str",
")",
"string",
".",
"to_str",
".",
"gsub",
"(",
"COLORED_REGEXP",
",",
"''",
")",
"elsif",
"respond_to?",
"(",
":to_str",
")",
"to_str",
".",
"gsub",
"(",
"COLORED_REGEXP",
",",
"''",
")",
"else",
"''",
"end",
".",
"extend",
"(",
"Term",
"::",
"ANSIColor",
")",
"end"
] | Returns an uncolored version of the string, that is all
ANSI-Attributes are stripped from the string. | [
"Returns",
"an",
"uncolored",
"version",
"of",
"the",
"string",
"that",
"is",
"all",
"ANSI",
"-",
"Attributes",
"are",
"stripped",
"from",
"the",
"string",
"."
] | 678eaee3e72bf51a02385fa27890e88175670dc0 | https://github.com/flori/term-ansicolor/blob/678eaee3e72bf51a02385fa27890e88175670dc0/lib/term/ansicolor.rb#L70-L80 | train |
flori/term-ansicolor | lib/term/ansicolor.rb | Term.ANSIColor.color | def color(name, string = nil, &block)
attribute = Attribute[name] or raise ArgumentError, "unknown attribute #{name.inspect}"
result = ''
result << "\e[#{attribute.code}m" if Term::ANSIColor.coloring?
if block_given?
result << yield.to_s
elsif string.respond_to?(:to_str)
result << string.to_str
elsif respond_to?(:to_str)
result << to_str
else
return result #only switch on
end
result << "\e[0m" if Term::ANSIColor.coloring?
result.extend(Term::ANSIColor)
end | ruby | def color(name, string = nil, &block)
attribute = Attribute[name] or raise ArgumentError, "unknown attribute #{name.inspect}"
result = ''
result << "\e[#{attribute.code}m" if Term::ANSIColor.coloring?
if block_given?
result << yield.to_s
elsif string.respond_to?(:to_str)
result << string.to_str
elsif respond_to?(:to_str)
result << to_str
else
return result #only switch on
end
result << "\e[0m" if Term::ANSIColor.coloring?
result.extend(Term::ANSIColor)
end | [
"def",
"color",
"(",
"name",
",",
"string",
"=",
"nil",
",",
"&",
"block",
")",
"attribute",
"=",
"Attribute",
"[",
"name",
"]",
"or",
"raise",
"ArgumentError",
",",
"\"unknown attribute #{name.inspect}\"",
"result",
"=",
"''",
"result",
"<<",
"\"\\e[#{attribute.code}m\"",
"if",
"Term",
"::",
"ANSIColor",
".",
"coloring?",
"if",
"block_given?",
"result",
"<<",
"yield",
".",
"to_s",
"elsif",
"string",
".",
"respond_to?",
"(",
":to_str",
")",
"result",
"<<",
"string",
".",
"to_str",
"elsif",
"respond_to?",
"(",
":to_str",
")",
"result",
"<<",
"to_str",
"else",
"return",
"result",
"end",
"result",
"<<",
"\"\\e[0m\"",
"if",
"Term",
"::",
"ANSIColor",
".",
"coloring?",
"result",
".",
"extend",
"(",
"Term",
"::",
"ANSIColor",
")",
"end"
] | Return +string+ or the result string of the given +block+ colored with
color +name+. If string isn't a string only the escape sequence to switch
on the color +name+ is returned. | [
"Return",
"+",
"string",
"+",
"or",
"the",
"result",
"string",
"of",
"the",
"given",
"+",
"block",
"+",
"colored",
"with",
"color",
"+",
"name",
"+",
".",
"If",
"string",
"isn",
"t",
"a",
"string",
"only",
"the",
"escape",
"sequence",
"to",
"switch",
"on",
"the",
"color",
"+",
"name",
"+",
"is",
"returned",
"."
] | 678eaee3e72bf51a02385fa27890e88175670dc0 | https://github.com/flori/term-ansicolor/blob/678eaee3e72bf51a02385fa27890e88175670dc0/lib/term/ansicolor.rb#L87-L102 | train |
shortdudey123/yamllint | lib/yamllint/cli.rb | YamlLint.CLI.execute! | def execute!
files_to_check = parse_options.leftovers
YamlLint.logger.level = Logger::DEBUG if opts.debug
no_yamls_to_check_msg = "Error: need at least one YAML file to check.\n"\
'Try --help for help.'
abort(no_yamls_to_check_msg) if files_to_check.empty?
lint(files_to_check)
end | ruby | def execute!
files_to_check = parse_options.leftovers
YamlLint.logger.level = Logger::DEBUG if opts.debug
no_yamls_to_check_msg = "Error: need at least one YAML file to check.\n"\
'Try --help for help.'
abort(no_yamls_to_check_msg) if files_to_check.empty?
lint(files_to_check)
end | [
"def",
"execute!",
"files_to_check",
"=",
"parse_options",
".",
"leftovers",
"YamlLint",
".",
"logger",
".",
"level",
"=",
"Logger",
"::",
"DEBUG",
"if",
"opts",
".",
"debug",
"no_yamls_to_check_msg",
"=",
"\"Error: need at least one YAML file to check.\\n\"",
"'Try --help for help.'",
"abort",
"(",
"no_yamls_to_check_msg",
")",
"if",
"files_to_check",
".",
"empty?",
"lint",
"(",
"files_to_check",
")",
"end"
] | setup CLI options
Run the CLI command | [
"setup",
"CLI",
"options",
"Run",
"the",
"CLI",
"command"
] | aa8e0538882eddcd2996f6f62fabaafda3fdb942 | https://github.com/shortdudey123/yamllint/blob/aa8e0538882eddcd2996f6f62fabaafda3fdb942/lib/yamllint/cli.rb#L22-L31 | train |
yaauie/cliver | lib/cliver/detector.rb | Cliver.Detector.detect_version | def detect_version(executable_path)
capture = ShellCapture.new(version_command(executable_path))
unless capture.command_found
raise Cliver::Dependency::NotFound.new(
"Could not find an executable at given path '#{executable_path}'." +
"If this path was not specified explicitly, it is probably a " +
"bug in [Cliver](https://github.com/yaauie/cliver/issues)."
)
end
capture.stdout[version_pattern] || capture.stderr[version_pattern]
end | ruby | def detect_version(executable_path)
capture = ShellCapture.new(version_command(executable_path))
unless capture.command_found
raise Cliver::Dependency::NotFound.new(
"Could not find an executable at given path '#{executable_path}'." +
"If this path was not specified explicitly, it is probably a " +
"bug in [Cliver](https://github.com/yaauie/cliver/issues)."
)
end
capture.stdout[version_pattern] || capture.stderr[version_pattern]
end | [
"def",
"detect_version",
"(",
"executable_path",
")",
"capture",
"=",
"ShellCapture",
".",
"new",
"(",
"version_command",
"(",
"executable_path",
")",
")",
"unless",
"capture",
".",
"command_found",
"raise",
"Cliver",
"::",
"Dependency",
"::",
"NotFound",
".",
"new",
"(",
"\"Could not find an executable at given path '#{executable_path}'.\"",
"+",
"\"If this path was not specified explicitly, it is probably a \"",
"+",
"\"bug in [Cliver](https://github.com/yaauie/cliver/issues).\"",
")",
"end",
"capture",
".",
"stdout",
"[",
"version_pattern",
"]",
"||",
"capture",
".",
"stderr",
"[",
"version_pattern",
"]",
"end"
] | Forgiving input, allows either argument if only one supplied.
@overload initialize(*command_args)
@param command_args [Array<String>]
@overload initialize(version_pattern)
@param version_pattern [Regexp]
@overload initialize(*command_args, version_pattern)
@param command_args [Array<String>]
@param version_pattern [Regexp]
@param executable_path [String] - the path to the executable to test
@return [String] - should be contain {Gem::Version}-parsable
version number. | [
"Forgiving",
"input",
"allows",
"either",
"argument",
"if",
"only",
"one",
"supplied",
"."
] | 3d72e99af19c273a3f88adcd4b96c4b65b1b6d4b | https://github.com/yaauie/cliver/blob/3d72e99af19c273a3f88adcd4b96c4b65b1b6d4b/lib/cliver/detector.rb#L42-L52 | train |
fusioncharts/rails-wrapper | samples/lib/fusioncharts/rails/chart.rb | Fusioncharts.Chart.render | def render
config = json_escape JSON.generate(self.options)
if @timeSeriesSource
config.gsub! '"__DataSource__"', json_escape(@timeSeriesSource)
end
dataUrlFormat = self.jsonUrl? ? "json" : ( self.xmlUrl ? "xml" : nil )
template = File.read(File.expand_path("../../../templates/chart.erb", __FILE__))
renderer = ERB.new(template)
return raw renderer.result(binding)
end | ruby | def render
config = json_escape JSON.generate(self.options)
if @timeSeriesSource
config.gsub! '"__DataSource__"', json_escape(@timeSeriesSource)
end
dataUrlFormat = self.jsonUrl? ? "json" : ( self.xmlUrl ? "xml" : nil )
template = File.read(File.expand_path("../../../templates/chart.erb", __FILE__))
renderer = ERB.new(template)
return raw renderer.result(binding)
end | [
"def",
"render",
"config",
"=",
"json_escape",
"JSON",
".",
"generate",
"(",
"self",
".",
"options",
")",
"if",
"@timeSeriesSource",
"config",
".",
"gsub!",
"'\"__DataSource__\"'",
",",
"json_escape",
"(",
"@timeSeriesSource",
")",
"end",
"dataUrlFormat",
"=",
"self",
".",
"jsonUrl?",
"?",
"\"json\"",
":",
"(",
"self",
".",
"xmlUrl",
"?",
"\"xml\"",
":",
"nil",
")",
"template",
"=",
"File",
".",
"read",
"(",
"File",
".",
"expand_path",
"(",
"\"../../../templates/chart.erb\"",
",",
"__FILE__",
")",
")",
"renderer",
"=",
"ERB",
".",
"new",
"(",
"template",
")",
"return",
"raw",
"renderer",
".",
"result",
"(",
"binding",
")",
"end"
] | Render the chart | [
"Render",
"the",
"chart"
] | 277c20fe97b29f94c64e31345c36eb4e0715c93f | https://github.com/fusioncharts/rails-wrapper/blob/277c20fe97b29f94c64e31345c36eb4e0715c93f/samples/lib/fusioncharts/rails/chart.rb#L102-L111 | train |
fusioncharts/rails-wrapper | samples/lib/fusioncharts/rails/chart.rb | Fusioncharts.Chart.parse_options | def parse_options
newOptions = nil
@options.each do |key, value|
if key.downcase.to_s.eql? "timeseries"
@timeSeriesData = value.GetDataStore()
@timeSeriesSource = value.GetDataSource()
newOptions = {}
newOptions['dataSource'] = "__DataSource__"
@options.delete(key)
end
end
if newOptions
@options.merge!(newOptions)
end
keys = @options.keys
keys.each{ |k| instance_variable_set "@#{k}".to_sym, @options[k] if self.respond_to? k }
#parse_datasource_json
end | ruby | def parse_options
newOptions = nil
@options.each do |key, value|
if key.downcase.to_s.eql? "timeseries"
@timeSeriesData = value.GetDataStore()
@timeSeriesSource = value.GetDataSource()
newOptions = {}
newOptions['dataSource'] = "__DataSource__"
@options.delete(key)
end
end
if newOptions
@options.merge!(newOptions)
end
keys = @options.keys
keys.each{ |k| instance_variable_set "@#{k}".to_sym, @options[k] if self.respond_to? k }
#parse_datasource_json
end | [
"def",
"parse_options",
"newOptions",
"=",
"nil",
"@options",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"key",
".",
"downcase",
".",
"to_s",
".",
"eql?",
"\"timeseries\"",
"@timeSeriesData",
"=",
"value",
".",
"GetDataStore",
"(",
")",
"@timeSeriesSource",
"=",
"value",
".",
"GetDataSource",
"(",
")",
"newOptions",
"=",
"{",
"}",
"newOptions",
"[",
"'dataSource'",
"]",
"=",
"\"__DataSource__\"",
"@options",
".",
"delete",
"(",
"key",
")",
"end",
"end",
"if",
"newOptions",
"@options",
".",
"merge!",
"(",
"newOptions",
")",
"end",
"keys",
"=",
"@options",
".",
"keys",
"keys",
".",
"each",
"{",
"|",
"k",
"|",
"instance_variable_set",
"\"@#{k}\"",
".",
"to_sym",
",",
"@options",
"[",
"k",
"]",
"if",
"self",
".",
"respond_to?",
"k",
"}",
"end"
] | Helper method that converts the constructor params into instance variables | [
"Helper",
"method",
"that",
"converts",
"the",
"constructor",
"params",
"into",
"instance",
"variables"
] | 277c20fe97b29f94c64e31345c36eb4e0715c93f | https://github.com/fusioncharts/rails-wrapper/blob/277c20fe97b29f94c64e31345c36eb4e0715c93f/samples/lib/fusioncharts/rails/chart.rb#L133-L151 | train |
dougfales/gpx | lib/gpx/segment.rb | GPX.Segment.smooth_location_by_average | def smooth_location_by_average(opts = {})
seconds_either_side = opts[:averaging_window] || 20
# calculate the first and last points to which the smoothing should be applied
earliest = (find_point_by_time_or_offset(opts[:start]) || @earliest_point).time
latest = (find_point_by_time_or_offset(opts[:end]) || @latest_point).time
tmp_points = []
@points.each do |point|
if point.time > latest || point.time < earliest
tmp_points.push point # add the point unaltered
next
end
lat_av = 0.to_f
lon_av = 0.to_f
alt_av = 0.to_f
n = 0
# k ranges from the time of the current point +/- 20s
(-1 * seconds_either_side..seconds_either_side).each do |k|
# find the point nearest to the time offset indicated by k
contributing_point = closest_point(point.time + k)
# sum up the contributions to the average
lat_av += contributing_point.lat
lon_av += contributing_point.lon
alt_av += contributing_point.elevation
n += 1
end
# calculate the averages
tmp_point = point.clone
tmp_point.lon = (lon_av / n).round(7)
tmp_point.elevation = (alt_av / n).round(2)
tmp_point.lat = (lat_av / n).round(7)
tmp_points.push tmp_point
end
@points.clear
reset_meta_data
# now commit the averages back and recalculate the distances
tmp_points.each do |point|
append_point(point)
end
end | ruby | def smooth_location_by_average(opts = {})
seconds_either_side = opts[:averaging_window] || 20
# calculate the first and last points to which the smoothing should be applied
earliest = (find_point_by_time_or_offset(opts[:start]) || @earliest_point).time
latest = (find_point_by_time_or_offset(opts[:end]) || @latest_point).time
tmp_points = []
@points.each do |point|
if point.time > latest || point.time < earliest
tmp_points.push point # add the point unaltered
next
end
lat_av = 0.to_f
lon_av = 0.to_f
alt_av = 0.to_f
n = 0
# k ranges from the time of the current point +/- 20s
(-1 * seconds_either_side..seconds_either_side).each do |k|
# find the point nearest to the time offset indicated by k
contributing_point = closest_point(point.time + k)
# sum up the contributions to the average
lat_av += contributing_point.lat
lon_av += contributing_point.lon
alt_av += contributing_point.elevation
n += 1
end
# calculate the averages
tmp_point = point.clone
tmp_point.lon = (lon_av / n).round(7)
tmp_point.elevation = (alt_av / n).round(2)
tmp_point.lat = (lat_av / n).round(7)
tmp_points.push tmp_point
end
@points.clear
reset_meta_data
# now commit the averages back and recalculate the distances
tmp_points.each do |point|
append_point(point)
end
end | [
"def",
"smooth_location_by_average",
"(",
"opts",
"=",
"{",
"}",
")",
"seconds_either_side",
"=",
"opts",
"[",
":averaging_window",
"]",
"||",
"20",
"earliest",
"=",
"(",
"find_point_by_time_or_offset",
"(",
"opts",
"[",
":start",
"]",
")",
"||",
"@earliest_point",
")",
".",
"time",
"latest",
"=",
"(",
"find_point_by_time_or_offset",
"(",
"opts",
"[",
":end",
"]",
")",
"||",
"@latest_point",
")",
".",
"time",
"tmp_points",
"=",
"[",
"]",
"@points",
".",
"each",
"do",
"|",
"point",
"|",
"if",
"point",
".",
"time",
">",
"latest",
"||",
"point",
".",
"time",
"<",
"earliest",
"tmp_points",
".",
"push",
"point",
"next",
"end",
"lat_av",
"=",
"0",
".",
"to_f",
"lon_av",
"=",
"0",
".",
"to_f",
"alt_av",
"=",
"0",
".",
"to_f",
"n",
"=",
"0",
"(",
"-",
"1",
"*",
"seconds_either_side",
"..",
"seconds_either_side",
")",
".",
"each",
"do",
"|",
"k",
"|",
"contributing_point",
"=",
"closest_point",
"(",
"point",
".",
"time",
"+",
"k",
")",
"lat_av",
"+=",
"contributing_point",
".",
"lat",
"lon_av",
"+=",
"contributing_point",
".",
"lon",
"alt_av",
"+=",
"contributing_point",
".",
"elevation",
"n",
"+=",
"1",
"end",
"tmp_point",
"=",
"point",
".",
"clone",
"tmp_point",
".",
"lon",
"=",
"(",
"lon_av",
"/",
"n",
")",
".",
"round",
"(",
"7",
")",
"tmp_point",
".",
"elevation",
"=",
"(",
"alt_av",
"/",
"n",
")",
".",
"round",
"(",
"2",
")",
"tmp_point",
".",
"lat",
"=",
"(",
"lat_av",
"/",
"n",
")",
".",
"round",
"(",
"7",
")",
"tmp_points",
".",
"push",
"tmp_point",
"end",
"@points",
".",
"clear",
"reset_meta_data",
"tmp_points",
".",
"each",
"do",
"|",
"point",
"|",
"append_point",
"(",
"point",
")",
"end",
"end"
] | smooths the location data in the segment (by recalculating the location as an average of 20 neighbouring points. Useful for removing noise from GPS traces. | [
"smooths",
"the",
"location",
"data",
"in",
"the",
"segment",
"(",
"by",
"recalculating",
"the",
"location",
"as",
"an",
"average",
"of",
"20",
"neighbouring",
"points",
".",
"Useful",
"for",
"removing",
"noise",
"from",
"GPS",
"traces",
"."
] | 632fcda922488ca410aabce451871755ef2b544c | https://github.com/dougfales/gpx/blob/632fcda922488ca410aabce451871755ef2b544c/lib/gpx/segment.rb#L132-L173 | train |
dougfales/gpx | lib/gpx/gpx_file.rb | GPX.GPXFile.crop | def crop(area)
reset_meta_data
keep_tracks = []
tracks.each do |trk|
trk.crop(area)
unless trk.empty?
update_meta_data(trk)
keep_tracks << trk
end
end
@tracks = keep_tracks
routes.each { |rte| rte.crop(area) }
waypoints.each { |wpt| wpt.crop(area) }
end | ruby | def crop(area)
reset_meta_data
keep_tracks = []
tracks.each do |trk|
trk.crop(area)
unless trk.empty?
update_meta_data(trk)
keep_tracks << trk
end
end
@tracks = keep_tracks
routes.each { |rte| rte.crop(area) }
waypoints.each { |wpt| wpt.crop(area) }
end | [
"def",
"crop",
"(",
"area",
")",
"reset_meta_data",
"keep_tracks",
"=",
"[",
"]",
"tracks",
".",
"each",
"do",
"|",
"trk",
"|",
"trk",
".",
"crop",
"(",
"area",
")",
"unless",
"trk",
".",
"empty?",
"update_meta_data",
"(",
"trk",
")",
"keep_tracks",
"<<",
"trk",
"end",
"end",
"@tracks",
"=",
"keep_tracks",
"routes",
".",
"each",
"{",
"|",
"rte",
"|",
"rte",
".",
"crop",
"(",
"area",
")",
"}",
"waypoints",
".",
"each",
"{",
"|",
"wpt",
"|",
"wpt",
".",
"crop",
"(",
"area",
")",
"}",
"end"
] | Crops any points falling within a rectangular area. Identical to the
delete_area method in every respect except that the points outside of
the given area are deleted. Note that this method automatically causes
the meta data to be updated after deletion. | [
"Crops",
"any",
"points",
"falling",
"within",
"a",
"rectangular",
"area",
".",
"Identical",
"to",
"the",
"delete_area",
"method",
"in",
"every",
"respect",
"except",
"that",
"the",
"points",
"outside",
"of",
"the",
"given",
"area",
"are",
"deleted",
".",
"Note",
"that",
"this",
"method",
"automatically",
"causes",
"the",
"meta",
"data",
"to",
"be",
"updated",
"after",
"deletion",
"."
] | 632fcda922488ca410aabce451871755ef2b544c | https://github.com/dougfales/gpx/blob/632fcda922488ca410aabce451871755ef2b544c/lib/gpx/gpx_file.rb#L145-L158 | train |
dougfales/gpx | lib/gpx/gpx_file.rb | GPX.GPXFile.calculate_duration | def calculate_duration
@duration = 0
if @tracks.nil? || @tracks.size.zero? || @tracks[0].segments.nil? || @tracks[0].segments.size.zero?
return @duration
end
@duration = (@tracks[-1].segments[-1].points[-1].time - @tracks.first.segments.first.points.first.time)
rescue StandardError
@duration = 0
end | ruby | def calculate_duration
@duration = 0
if @tracks.nil? || @tracks.size.zero? || @tracks[0].segments.nil? || @tracks[0].segments.size.zero?
return @duration
end
@duration = (@tracks[-1].segments[-1].points[-1].time - @tracks.first.segments.first.points.first.time)
rescue StandardError
@duration = 0
end | [
"def",
"calculate_duration",
"@duration",
"=",
"0",
"if",
"@tracks",
".",
"nil?",
"||",
"@tracks",
".",
"size",
".",
"zero?",
"||",
"@tracks",
"[",
"0",
"]",
".",
"segments",
".",
"nil?",
"||",
"@tracks",
"[",
"0",
"]",
".",
"segments",
".",
"size",
".",
"zero?",
"return",
"@duration",
"end",
"@duration",
"=",
"(",
"@tracks",
"[",
"-",
"1",
"]",
".",
"segments",
"[",
"-",
"1",
"]",
".",
"points",
"[",
"-",
"1",
"]",
".",
"time",
"-",
"@tracks",
".",
"first",
".",
"segments",
".",
"first",
".",
"points",
".",
"first",
".",
"time",
")",
"rescue",
"StandardError",
"@duration",
"=",
"0",
"end"
] | Calculates and sets the duration attribute by subtracting the time on
the very first point from the time on the very last point. | [
"Calculates",
"and",
"sets",
"the",
"duration",
"attribute",
"by",
"subtracting",
"the",
"time",
"on",
"the",
"very",
"first",
"point",
"from",
"the",
"time",
"on",
"the",
"very",
"last",
"point",
"."
] | 632fcda922488ca410aabce451871755ef2b544c | https://github.com/dougfales/gpx/blob/632fcda922488ca410aabce451871755ef2b544c/lib/gpx/gpx_file.rb#L342-L350 | train |
dougfales/gpx | lib/gpx/bounds.rb | GPX.Bounds.contains? | def contains?(pt)
((pt.lat >= min_lat) && (pt.lat <= max_lat) && (pt.lon >= min_lon) && (pt.lon <= max_lon))
end | ruby | def contains?(pt)
((pt.lat >= min_lat) && (pt.lat <= max_lat) && (pt.lon >= min_lon) && (pt.lon <= max_lon))
end | [
"def",
"contains?",
"(",
"pt",
")",
"(",
"(",
"pt",
".",
"lat",
">=",
"min_lat",
")",
"&&",
"(",
"pt",
".",
"lat",
"<=",
"max_lat",
")",
"&&",
"(",
"pt",
".",
"lon",
">=",
"min_lon",
")",
"&&",
"(",
"pt",
".",
"lon",
"<=",
"max_lon",
")",
")",
"end"
] | Returns true if the pt is within these bounds. | [
"Returns",
"true",
"if",
"the",
"pt",
"is",
"within",
"these",
"bounds",
"."
] | 632fcda922488ca410aabce451871755ef2b544c | https://github.com/dougfales/gpx/blob/632fcda922488ca410aabce451871755ef2b544c/lib/gpx/bounds.rb#L27-L29 | train |
dougfales/gpx | lib/gpx/track.rb | GPX.Track.contains_time? | def contains_time?(time)
segments.each do |seg|
return true if seg.contains_time?(time)
end
false
end | ruby | def contains_time?(time)
segments.each do |seg|
return true if seg.contains_time?(time)
end
false
end | [
"def",
"contains_time?",
"(",
"time",
")",
"segments",
".",
"each",
"do",
"|",
"seg",
"|",
"return",
"true",
"if",
"seg",
".",
"contains_time?",
"(",
"time",
")",
"end",
"false",
"end"
] | Returns true if the given time occurs within any of the segments of this track. | [
"Returns",
"true",
"if",
"the",
"given",
"time",
"occurs",
"within",
"any",
"of",
"the",
"segments",
"of",
"this",
"track",
"."
] | 632fcda922488ca410aabce451871755ef2b544c | https://github.com/dougfales/gpx/blob/632fcda922488ca410aabce451871755ef2b544c/lib/gpx/track.rb#L52-L57 | train |
dougfales/gpx | lib/gpx/track.rb | GPX.Track.delete_area | def delete_area(area)
reset_meta_data
segments.each do |seg|
seg.delete_area(area)
update_meta_data(seg) unless seg.empty?
end
segments.delete_if(&:empty?)
end | ruby | def delete_area(area)
reset_meta_data
segments.each do |seg|
seg.delete_area(area)
update_meta_data(seg) unless seg.empty?
end
segments.delete_if(&:empty?)
end | [
"def",
"delete_area",
"(",
"area",
")",
"reset_meta_data",
"segments",
".",
"each",
"do",
"|",
"seg",
"|",
"seg",
".",
"delete_area",
"(",
"area",
")",
"update_meta_data",
"(",
"seg",
")",
"unless",
"seg",
".",
"empty?",
"end",
"segments",
".",
"delete_if",
"(",
"&",
":empty?",
")",
"end"
] | Deletes all points within a given area and updates the meta data. | [
"Deletes",
"all",
"points",
"within",
"a",
"given",
"area",
"and",
"updates",
"the",
"meta",
"data",
"."
] | 632fcda922488ca410aabce451871755ef2b544c | https://github.com/dougfales/gpx/blob/632fcda922488ca410aabce451871755ef2b544c/lib/gpx/track.rb#L79-L86 | train |
elucid/resque-delayed | lib/resque-delayed/worker.rb | Resque::Delayed.Worker.work | def work(interval = 5.0)
interval = Float(interval)
$0 = "resque-delayed: harvesting"
startup
loop do
break if shutdown?
# harvest delayed jobs while they are available
while job = Resque::Delayed.next do
log "got: #{job.inspect}"
queue, klass, *args = job
Resque::Job.create(queue, klass, *args)
end
break if interval.zero?
log! "Sleeping for #{interval} seconds"
sleep interval
end
end | ruby | def work(interval = 5.0)
interval = Float(interval)
$0 = "resque-delayed: harvesting"
startup
loop do
break if shutdown?
# harvest delayed jobs while they are available
while job = Resque::Delayed.next do
log "got: #{job.inspect}"
queue, klass, *args = job
Resque::Job.create(queue, klass, *args)
end
break if interval.zero?
log! "Sleeping for #{interval} seconds"
sleep interval
end
end | [
"def",
"work",
"(",
"interval",
"=",
"5.0",
")",
"interval",
"=",
"Float",
"(",
"interval",
")",
"$0",
"=",
"\"resque-delayed: harvesting\"",
"startup",
"loop",
"do",
"break",
"if",
"shutdown?",
"while",
"job",
"=",
"Resque",
"::",
"Delayed",
".",
"next",
"do",
"log",
"\"got: #{job.inspect}\"",
"queue",
",",
"klass",
",",
"*",
"args",
"=",
"job",
"Resque",
"::",
"Job",
".",
"create",
"(",
"queue",
",",
"klass",
",",
"*",
"args",
")",
"end",
"break",
"if",
"interval",
".",
"zero?",
"log!",
"\"Sleeping for #{interval} seconds\"",
"sleep",
"interval",
"end",
"end"
] | Can be passed a float representing the polling frequency.
The default is 5 seconds, but for a semi-active site you may
want to use a smaller value. | [
"Can",
"be",
"passed",
"a",
"float",
"representing",
"the",
"polling",
"frequency",
".",
"The",
"default",
"is",
"5",
"seconds",
"but",
"for",
"a",
"semi",
"-",
"active",
"site",
"you",
"may",
"want",
"to",
"use",
"a",
"smaller",
"value",
"."
] | 3b93fb8252cdc443250ba0c640f458634c9515d6 | https://github.com/elucid/resque-delayed/blob/3b93fb8252cdc443250ba0c640f458634c9515d6/lib/resque-delayed/worker.rb#L19-L38 | train |
elucid/resque-delayed | lib/resque-delayed/worker.rb | Resque::Delayed.Worker.log | def log(message)
if verbose
puts "*** #{message}"
elsif very_verbose
time = Time.now.strftime('%H:%M:%S %Y-%m-%d')
puts "** [#{time}] #$$: #{message}"
end
end | ruby | def log(message)
if verbose
puts "*** #{message}"
elsif very_verbose
time = Time.now.strftime('%H:%M:%S %Y-%m-%d')
puts "** [#{time}] #$$: #{message}"
end
end | [
"def",
"log",
"(",
"message",
")",
"if",
"verbose",
"puts",
"\"*** #{message}\"",
"elsif",
"very_verbose",
"time",
"=",
"Time",
".",
"now",
".",
"strftime",
"(",
"'%H:%M:%S %Y-%m-%d'",
")",
"puts",
"\"** [#{time}] #$$: #{message}\"",
"end",
"end"
] | Log a message to STDOUT if we are verbose or very_verbose. | [
"Log",
"a",
"message",
"to",
"STDOUT",
"if",
"we",
"are",
"verbose",
"or",
"very_verbose",
"."
] | 3b93fb8252cdc443250ba0c640f458634c9515d6 | https://github.com/elucid/resque-delayed/blob/3b93fb8252cdc443250ba0c640f458634c9515d6/lib/resque-delayed/worker.rb#L106-L113 | train |
myles/jekyll-typogrify | lib/jekyll/typogrify.rb | Jekyll.TypogrifyFilter.custom_caps | def custom_caps(text)
# $1 and $2 are excluded HTML tags, $3 is the part before the caps and $4 is the caps match
text.gsub(%r{
(<[^/][^>]*?>)| # Ignore any opening tag, so we don't mess up attribute values
(\s| |^|'|"|>|) # Make sure our capture is preceded by whitespace or quotes
([A-Z\d](?:(\.|'|-|&|&|&\#38;)?[A-Z\d][\.']?){1,}) # Capture capital words, with optional dots, numbers or ampersands in between
(?!\w) # ...which must not be followed by a word character.
}x) do |str|
tag, before, caps = $1, $2, $3
# Do nothing with the contents if ignored tags, the inside of an opening HTML element
# so we don't mess up attribute values, or if our capture is only digits.
if tag || caps =~ /^\d+\.?$/
str
elsif $3 =~ /^[\d\.]+$/
before + caps
else
before + '<span class="caps">' + caps + '</span>'
end
end
end | ruby | def custom_caps(text)
# $1 and $2 are excluded HTML tags, $3 is the part before the caps and $4 is the caps match
text.gsub(%r{
(<[^/][^>]*?>)| # Ignore any opening tag, so we don't mess up attribute values
(\s| |^|'|"|>|) # Make sure our capture is preceded by whitespace or quotes
([A-Z\d](?:(\.|'|-|&|&|&\#38;)?[A-Z\d][\.']?){1,}) # Capture capital words, with optional dots, numbers or ampersands in between
(?!\w) # ...which must not be followed by a word character.
}x) do |str|
tag, before, caps = $1, $2, $3
# Do nothing with the contents if ignored tags, the inside of an opening HTML element
# so we don't mess up attribute values, or if our capture is only digits.
if tag || caps =~ /^\d+\.?$/
str
elsif $3 =~ /^[\d\.]+$/
before + caps
else
before + '<span class="caps">' + caps + '</span>'
end
end
end | [
"def",
"custom_caps",
"(",
"text",
")",
"text",
".",
"gsub",
"(",
"%r{",
"\\s",
"\\d",
"\\.",
"\\#",
"\\d",
"\\.",
"\\w",
"}x",
")",
"do",
"|",
"str",
"|",
"tag",
",",
"before",
",",
"caps",
"=",
"$1",
",",
"$2",
",",
"$3",
"if",
"tag",
"||",
"caps",
"=~",
"/",
"\\d",
"\\.",
"/",
"str",
"elsif",
"$3",
"=~",
"/",
"\\d",
"\\.",
"/",
"before",
"+",
"caps",
"else",
"before",
"+",
"'<span class=\"caps\">'",
"+",
"caps",
"+",
"'</span>'",
"end",
"end",
"end"
] | custom modules to jekyll-typogrify
surrounds two or more consecutive capital letters, perhaps with
interspersed digits and periods in a span with a styled class.
@param [String] text input text
@return [String] input text with caps wrapped | [
"custom",
"modules",
"to",
"jekyll",
"-",
"typogrify",
"surrounds",
"two",
"or",
"more",
"consecutive",
"capital",
"letters",
"perhaps",
"with",
"interspersed",
"digits",
"and",
"periods",
"in",
"a",
"span",
"with",
"a",
"styled",
"class",
"."
] | edfebe97d029682d71d19741c2bf52e741e8b252 | https://github.com/myles/jekyll-typogrify/blob/edfebe97d029682d71d19741c2bf52e741e8b252/lib/jekyll/typogrify.rb#L124-L144 | train |
take-five/activerecord-hierarchical_query | lib/active_record/hierarchical_query.rb | ActiveRecord.HierarchicalQuery.join_recursive | def join_recursive(join_options = {}, &block)
raise ArgumentError, 'block expected' unless block_given?
query = Query.new(klass)
if block.arity == 0
query.instance_eval(&block)
else
block.call(query)
end
query.join_to(self, join_options)
end | ruby | def join_recursive(join_options = {}, &block)
raise ArgumentError, 'block expected' unless block_given?
query = Query.new(klass)
if block.arity == 0
query.instance_eval(&block)
else
block.call(query)
end
query.join_to(self, join_options)
end | [
"def",
"join_recursive",
"(",
"join_options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"raise",
"ArgumentError",
",",
"'block expected'",
"unless",
"block_given?",
"query",
"=",
"Query",
".",
"new",
"(",
"klass",
")",
"if",
"block",
".",
"arity",
"==",
"0",
"query",
".",
"instance_eval",
"(",
"&",
"block",
")",
"else",
"block",
".",
"call",
"(",
"query",
")",
"end",
"query",
".",
"join_to",
"(",
"self",
",",
"join_options",
")",
"end"
] | Performs a join to recursive subquery
which should be built within a block.
@example
MyModel.join_recursive do |query|
query.start_with(parent_id: nil)
.connect_by(id: :parent_id)
.where('depth < ?', 5)
.order_siblings(name: :desc)
end
@param [Hash] join_options
@option join_options [String, Symbol] :as aliased name of joined
table (`%table_name%__recursive` by default)
@yield [query]
@yieldparam [ActiveRecord::HierarchicalQuery::Query] query Hierarchical query
@raise [ArgumentError] if block is omitted | [
"Performs",
"a",
"join",
"to",
"recursive",
"subquery",
"which",
"should",
"be",
"built",
"within",
"a",
"block",
"."
] | 8adb826d35e39640641397bccd21468b3443d026 | https://github.com/take-five/activerecord-hierarchical_query/blob/8adb826d35e39640641397bccd21468b3443d026/lib/active_record/hierarchical_query.rb#L31-L43 | train |
harley/auditable | lib/auditable/auditing.rb | Auditable.Auditing.audit_tag_with | def audit_tag_with(tag)
if audit = last_audit
audit.update_attribute(:tag, tag)
# Force the trigger of a reload if audited_version is used. Happens automatically otherwise
audits.reload if self.class.audited_version
else
self.audit_tag = tag
snap!
end
end | ruby | def audit_tag_with(tag)
if audit = last_audit
audit.update_attribute(:tag, tag)
# Force the trigger of a reload if audited_version is used. Happens automatically otherwise
audits.reload if self.class.audited_version
else
self.audit_tag = tag
snap!
end
end | [
"def",
"audit_tag_with",
"(",
"tag",
")",
"if",
"audit",
"=",
"last_audit",
"audit",
".",
"update_attribute",
"(",
":tag",
",",
"tag",
")",
"audits",
".",
"reload",
"if",
"self",
".",
"class",
".",
"audited_version",
"else",
"self",
".",
"audit_tag",
"=",
"tag",
"snap!",
"end",
"end"
] | Mark the latest record with a tag in order to easily find and perform diff against later
If there are no audits for this record, create a new audit with this tag | [
"Mark",
"the",
"latest",
"record",
"with",
"a",
"tag",
"in",
"order",
"to",
"easily",
"find",
"and",
"perform",
"diff",
"against",
"later",
"If",
"there",
"are",
"no",
"audits",
"for",
"this",
"record",
"create",
"a",
"new",
"audit",
"with",
"this",
"tag"
] | c309fa345864719718045e9b4f13a0e87a8597a2 | https://github.com/harley/auditable/blob/c309fa345864719718045e9b4f13a0e87a8597a2/lib/auditable/auditing.rb#L196-L206 | train |
harley/auditable | lib/auditable/auditing.rb | Auditable.Auditing.snap | def snap
serialize_attribute = lambda do |attribute|
# If a proc, do nothing, cannot be serialized
# XXX: raise warning on passing in a proc?
if attribute.is_a? Proc
# noop
# Is an ActiveRecord, serialize as hash instead of serializing the object
elsif attribute.class.ancestors.include?(ActiveRecord::Base)
attribute.serializable_hash
# If an array, such as from an association, serialize the elements in the array
elsif attribute.is_a?(Array) || attribute.is_a?(ActiveRecord::Associations::CollectionProxy)
attribute.map { |element| serialize_attribute.call(element) }
# otherwise, return val
else
attribute
end
end
{}.tap do |s|
self.class.audited_attributes.each do |attr|
val = self.send attr
s[attr.to_s] = serialize_attribute.call(val)
end
end
end | ruby | def snap
serialize_attribute = lambda do |attribute|
# If a proc, do nothing, cannot be serialized
# XXX: raise warning on passing in a proc?
if attribute.is_a? Proc
# noop
# Is an ActiveRecord, serialize as hash instead of serializing the object
elsif attribute.class.ancestors.include?(ActiveRecord::Base)
attribute.serializable_hash
# If an array, such as from an association, serialize the elements in the array
elsif attribute.is_a?(Array) || attribute.is_a?(ActiveRecord::Associations::CollectionProxy)
attribute.map { |element| serialize_attribute.call(element) }
# otherwise, return val
else
attribute
end
end
{}.tap do |s|
self.class.audited_attributes.each do |attr|
val = self.send attr
s[attr.to_s] = serialize_attribute.call(val)
end
end
end | [
"def",
"snap",
"serialize_attribute",
"=",
"lambda",
"do",
"|",
"attribute",
"|",
"if",
"attribute",
".",
"is_a?",
"Proc",
"elsif",
"attribute",
".",
"class",
".",
"ancestors",
".",
"include?",
"(",
"ActiveRecord",
"::",
"Base",
")",
"attribute",
".",
"serializable_hash",
"elsif",
"attribute",
".",
"is_a?",
"(",
"Array",
")",
"||",
"attribute",
".",
"is_a?",
"(",
"ActiveRecord",
"::",
"Associations",
"::",
"CollectionProxy",
")",
"attribute",
".",
"map",
"{",
"|",
"element",
"|",
"serialize_attribute",
".",
"call",
"(",
"element",
")",
"}",
"else",
"attribute",
"end",
"end",
"{",
"}",
".",
"tap",
"do",
"|",
"s",
"|",
"self",
".",
"class",
".",
"audited_attributes",
".",
"each",
"do",
"|",
"attr",
"|",
"val",
"=",
"self",
".",
"send",
"attr",
"s",
"[",
"attr",
".",
"to_s",
"]",
"=",
"serialize_attribute",
".",
"call",
"(",
"val",
")",
"end",
"end",
"end"
] | Take a snapshot of the current state of the audited record's audited attributes | [
"Take",
"a",
"snapshot",
"of",
"the",
"current",
"state",
"of",
"the",
"audited",
"record",
"s",
"audited",
"attributes"
] | c309fa345864719718045e9b4f13a0e87a8597a2 | https://github.com/harley/auditable/blob/c309fa345864719718045e9b4f13a0e87a8597a2/lib/auditable/auditing.rb#L209-L236 | train |
harley/auditable | lib/auditable/auditing.rb | Auditable.Auditing.snap! | def snap!(options = {})
data = options.merge(:modifications => self.snap)
data[:tag] = self.audit_tag if self.audit_tag
data[:action] = self.audit_action if self.audit_action
data[:changed_by] = self.audit_changed_by if self.audit_changed_by
self.save_audit( data )
end | ruby | def snap!(options = {})
data = options.merge(:modifications => self.snap)
data[:tag] = self.audit_tag if self.audit_tag
data[:action] = self.audit_action if self.audit_action
data[:changed_by] = self.audit_changed_by if self.audit_changed_by
self.save_audit( data )
end | [
"def",
"snap!",
"(",
"options",
"=",
"{",
"}",
")",
"data",
"=",
"options",
".",
"merge",
"(",
":modifications",
"=>",
"self",
".",
"snap",
")",
"data",
"[",
":tag",
"]",
"=",
"self",
".",
"audit_tag",
"if",
"self",
".",
"audit_tag",
"data",
"[",
":action",
"]",
"=",
"self",
".",
"audit_action",
"if",
"self",
".",
"audit_action",
"data",
"[",
":changed_by",
"]",
"=",
"self",
".",
"audit_changed_by",
"if",
"self",
".",
"audit_changed_by",
"self",
".",
"save_audit",
"(",
"data",
")",
"end"
] | Take a snapshot of and save the current state of the audited record's audited attributes
Accept values for :tag, :action and :user in the argument hash. However, these are overridden by the values set by the auditable record's virtual attributes (#audit_tag, #audit_action, #changed_by) if defined | [
"Take",
"a",
"snapshot",
"of",
"and",
"save",
"the",
"current",
"state",
"of",
"the",
"audited",
"record",
"s",
"audited",
"attributes"
] | c309fa345864719718045e9b4f13a0e87a8597a2 | https://github.com/harley/auditable/blob/c309fa345864719718045e9b4f13a0e87a8597a2/lib/auditable/auditing.rb#L241-L249 | train |
harley/auditable | lib/auditable/auditing.rb | Auditable.Auditing.last_change_of | def last_change_of(attribute)
raise "#{attribute} is not audited for model #{self.class}. Audited attributes: #{self.class.audited_attributes}" unless self.class.audited_attributes.include? attribute.to_sym
attribute = attribute.to_s # support symbol as well
last = audits.size - 1
last.downto(1) do |i|
if audits[i].modifications[attribute] != audits[i-1].modifications[attribute]
return audits[i].diff(audits[i-1])[attribute]
end
end
nil
end | ruby | def last_change_of(attribute)
raise "#{attribute} is not audited for model #{self.class}. Audited attributes: #{self.class.audited_attributes}" unless self.class.audited_attributes.include? attribute.to_sym
attribute = attribute.to_s # support symbol as well
last = audits.size - 1
last.downto(1) do |i|
if audits[i].modifications[attribute] != audits[i-1].modifications[attribute]
return audits[i].diff(audits[i-1])[attribute]
end
end
nil
end | [
"def",
"last_change_of",
"(",
"attribute",
")",
"raise",
"\"#{attribute} is not audited for model #{self.class}. Audited attributes: #{self.class.audited_attributes}\"",
"unless",
"self",
".",
"class",
".",
"audited_attributes",
".",
"include?",
"attribute",
".",
"to_sym",
"attribute",
"=",
"attribute",
".",
"to_s",
"last",
"=",
"audits",
".",
"size",
"-",
"1",
"last",
".",
"downto",
"(",
"1",
")",
"do",
"|",
"i",
"|",
"if",
"audits",
"[",
"i",
"]",
".",
"modifications",
"[",
"attribute",
"]",
"!=",
"audits",
"[",
"i",
"-",
"1",
"]",
".",
"modifications",
"[",
"attribute",
"]",
"return",
"audits",
"[",
"i",
"]",
".",
"diff",
"(",
"audits",
"[",
"i",
"-",
"1",
"]",
")",
"[",
"attribute",
"]",
"end",
"end",
"nil",
"end"
] | Return last attribute's change
This method may be slow and inefficient on model with lots of audit objects.
Go through each audit in the reverse order and find the first occurrence when
audit.modifications[attribute] changed | [
"Return",
"last",
"attribute",
"s",
"change"
] | c309fa345864719718045e9b4f13a0e87a8597a2 | https://github.com/harley/auditable/blob/c309fa345864719718045e9b4f13a0e87a8597a2/lib/auditable/auditing.rb#L291-L301 | train |
harley/auditable | lib/auditable/base.rb | Auditable.Base.diff | def diff(other_audit)
other_modifications = other_audit ? other_audit.modifications : {}
{}.tap do |d|
# find keys present only in this audit
(self.modifications.keys - other_modifications.keys).each do |k|
d[k] = [nil, self.modifications[k]] if self.modifications[k]
end
# find keys present only in other audit
(other_modifications.keys - self.modifications.keys).each do |k|
d[k] = [other_modifications[k], nil] if other_modifications[k]
end
# find common keys and diff values
self.modifications.keys.each do |k|
if self.modifications[k] != other_modifications[k]
d[k] = [other_modifications[k], self.modifications[k]]
end
end
end
end | ruby | def diff(other_audit)
other_modifications = other_audit ? other_audit.modifications : {}
{}.tap do |d|
# find keys present only in this audit
(self.modifications.keys - other_modifications.keys).each do |k|
d[k] = [nil, self.modifications[k]] if self.modifications[k]
end
# find keys present only in other audit
(other_modifications.keys - self.modifications.keys).each do |k|
d[k] = [other_modifications[k], nil] if other_modifications[k]
end
# find common keys and diff values
self.modifications.keys.each do |k|
if self.modifications[k] != other_modifications[k]
d[k] = [other_modifications[k], self.modifications[k]]
end
end
end
end | [
"def",
"diff",
"(",
"other_audit",
")",
"other_modifications",
"=",
"other_audit",
"?",
"other_audit",
".",
"modifications",
":",
"{",
"}",
"{",
"}",
".",
"tap",
"do",
"|",
"d",
"|",
"(",
"self",
".",
"modifications",
".",
"keys",
"-",
"other_modifications",
".",
"keys",
")",
".",
"each",
"do",
"|",
"k",
"|",
"d",
"[",
"k",
"]",
"=",
"[",
"nil",
",",
"self",
".",
"modifications",
"[",
"k",
"]",
"]",
"if",
"self",
".",
"modifications",
"[",
"k",
"]",
"end",
"(",
"other_modifications",
".",
"keys",
"-",
"self",
".",
"modifications",
".",
"keys",
")",
".",
"each",
"do",
"|",
"k",
"|",
"d",
"[",
"k",
"]",
"=",
"[",
"other_modifications",
"[",
"k",
"]",
",",
"nil",
"]",
"if",
"other_modifications",
"[",
"k",
"]",
"end",
"self",
".",
"modifications",
".",
"keys",
".",
"each",
"do",
"|",
"k",
"|",
"if",
"self",
".",
"modifications",
"[",
"k",
"]",
"!=",
"other_modifications",
"[",
"k",
"]",
"d",
"[",
"k",
"]",
"=",
"[",
"other_modifications",
"[",
"k",
"]",
",",
"self",
".",
"modifications",
"[",
"k",
"]",
"]",
"end",
"end",
"end",
"end"
] | Diffing two audits' modifications
Returns a hash containing arrays of the form
{
:key_1 => [<value_in_other_audit>, <value_in_this_audit>],
:key_2 => [<value_in_other_audit>, <value_in_this_audit>],
:other_audit_own_key => [<value_in_other_audit>, nil],
:this_audio_own_key => [nil, <value_in_this_audit>]
} | [
"Diffing",
"two",
"audits",
"modifications"
] | c309fa345864719718045e9b4f13a0e87a8597a2 | https://github.com/harley/auditable/blob/c309fa345864719718045e9b4f13a0e87a8597a2/lib/auditable/base.rb#L22-L43 | train |
harley/auditable | lib/auditable/base.rb | Auditable.Base.diff_since | def diff_since(time)
other_audit = auditable.audits.where("created_at <= ? AND id != ?", time, id).order("id DESC").limit(1).first
diff(other_audit)
end | ruby | def diff_since(time)
other_audit = auditable.audits.where("created_at <= ? AND id != ?", time, id).order("id DESC").limit(1).first
diff(other_audit)
end | [
"def",
"diff_since",
"(",
"time",
")",
"other_audit",
"=",
"auditable",
".",
"audits",
".",
"where",
"(",
"\"created_at <= ? AND id != ?\"",
",",
"time",
",",
"id",
")",
".",
"order",
"(",
"\"id DESC\"",
")",
".",
"limit",
"(",
"1",
")",
".",
"first",
"diff",
"(",
"other_audit",
")",
"end"
] | Diff this audit with the latest audit created before the `time` variable passed | [
"Diff",
"this",
"audit",
"with",
"the",
"latest",
"audit",
"created",
"before",
"the",
"time",
"variable",
"passed"
] | c309fa345864719718045e9b4f13a0e87a8597a2 | https://github.com/harley/auditable/blob/c309fa345864719718045e9b4f13a0e87a8597a2/lib/auditable/base.rb#L72-L76 | train |
harley/auditable | lib/auditable/base.rb | Auditable.Base.diff_since_version | def diff_since_version(version)
other_audit = auditable.audits.where("version <= ? AND id != ?", version, id).order("version DESC").limit(1).first
diff(other_audit)
end | ruby | def diff_since_version(version)
other_audit = auditable.audits.where("version <= ? AND id != ?", version, id).order("version DESC").limit(1).first
diff(other_audit)
end | [
"def",
"diff_since_version",
"(",
"version",
")",
"other_audit",
"=",
"auditable",
".",
"audits",
".",
"where",
"(",
"\"version <= ? AND id != ?\"",
",",
"version",
",",
"id",
")",
".",
"order",
"(",
"\"version DESC\"",
")",
".",
"limit",
"(",
"1",
")",
".",
"first",
"diff",
"(",
"other_audit",
")",
"end"
] | Diff this audit with the latest audit created before this version | [
"Diff",
"this",
"audit",
"with",
"the",
"latest",
"audit",
"created",
"before",
"this",
"version"
] | c309fa345864719718045e9b4f13a0e87a8597a2 | https://github.com/harley/auditable/blob/c309fa345864719718045e9b4f13a0e87a8597a2/lib/auditable/base.rb#L79-L83 | train |
pjotrp/bioruby-vcf | lib/bio-vcf/vcfheader.rb | BioVcf.VcfHeader.tag | def tag h
h2 = h.dup
[:show_help,:skip_header,:verbose,:quiet,:debug].each { |key| h2.delete(key) }
info = h2.map { |k,v| k.to_s.capitalize+'='+'"'+v.to_s+'"' }.join(',')
line = '##BioVcf=<'+info+'>'
@lines.insert(-2,line)
line
end | ruby | def tag h
h2 = h.dup
[:show_help,:skip_header,:verbose,:quiet,:debug].each { |key| h2.delete(key) }
info = h2.map { |k,v| k.to_s.capitalize+'='+'"'+v.to_s+'"' }.join(',')
line = '##BioVcf=<'+info+'>'
@lines.insert(-2,line)
line
end | [
"def",
"tag",
"h",
"h2",
"=",
"h",
".",
"dup",
"[",
":show_help",
",",
":skip_header",
",",
":verbose",
",",
":quiet",
",",
":debug",
"]",
".",
"each",
"{",
"|",
"key",
"|",
"h2",
".",
"delete",
"(",
"key",
")",
"}",
"info",
"=",
"h2",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"k",
".",
"to_s",
".",
"capitalize",
"+",
"'='",
"+",
"'\"'",
"+",
"v",
".",
"to_s",
"+",
"'\"'",
"}",
".",
"join",
"(",
"','",
")",
"line",
"=",
"'##BioVcf=<'",
"+",
"info",
"+",
"'>'",
"@lines",
".",
"insert",
"(",
"-",
"2",
",",
"line",
")",
"line",
"end"
] | Push a special key value list to the header | [
"Push",
"a",
"special",
"key",
"value",
"list",
"to",
"the",
"header"
] | bb9a3f9c10ffbd0304690bbca001ad775f6ea54e | https://github.com/pjotrp/bioruby-vcf/blob/bb9a3f9c10ffbd0304690bbca001ad775f6ea54e/lib/bio-vcf/vcfheader.rb#L51-L58 | train |
pjotrp/bioruby-vcf | lib/bio-vcf/vcfrecord.rb | BioVcf.VcfRecord.method_missing | def method_missing(m, *args, &block)
name = m.to_s
if name =~ /\?$/
# Query for empty sample name
@sample_index ||= @header.sample_index
return !VcfSample::empty?(@fields[@sample_index[name.chop]])
else
sample[name]
end
end | ruby | def method_missing(m, *args, &block)
name = m.to_s
if name =~ /\?$/
# Query for empty sample name
@sample_index ||= @header.sample_index
return !VcfSample::empty?(@fields[@sample_index[name.chop]])
else
sample[name]
end
end | [
"def",
"method_missing",
"(",
"m",
",",
"*",
"args",
",",
"&",
"block",
")",
"name",
"=",
"m",
".",
"to_s",
"if",
"name",
"=~",
"/",
"\\?",
"/",
"@sample_index",
"||=",
"@header",
".",
"sample_index",
"return",
"!",
"VcfSample",
"::",
"empty?",
"(",
"@fields",
"[",
"@sample_index",
"[",
"name",
".",
"chop",
"]",
"]",
")",
"else",
"sample",
"[",
"name",
"]",
"end",
"end"
] | Return the sample | [
"Return",
"the",
"sample"
] | bb9a3f9c10ffbd0304690bbca001ad775f6ea54e | https://github.com/pjotrp/bioruby-vcf/blob/bb9a3f9c10ffbd0304690bbca001ad775f6ea54e/lib/bio-vcf/vcfrecord.rb#L314-L323 | train |
pjotrp/bioruby-vcf | lib/bio-vcf/vcffile.rb | BioVcf.VCFfile.each | def each
return enum_for(:each) unless block_given?
io = nil
if @is_gz
infile = open(@file)
io = Zlib::GzipReader.new(infile)
else
io = File.open(@file)
end
header = BioVcf::VcfHeader.new
io.each_line do |line|
line.chomp!
if line =~ /^##fileformat=/
header.add(line)
next
end
if line =~ /^#/
header.add(line)
next
end
fields = BioVcf::VcfLine.parse(line)
rec = BioVcf::VcfRecord.new(fields,header)
yield rec
end
end | ruby | def each
return enum_for(:each) unless block_given?
io = nil
if @is_gz
infile = open(@file)
io = Zlib::GzipReader.new(infile)
else
io = File.open(@file)
end
header = BioVcf::VcfHeader.new
io.each_line do |line|
line.chomp!
if line =~ /^##fileformat=/
header.add(line)
next
end
if line =~ /^#/
header.add(line)
next
end
fields = BioVcf::VcfLine.parse(line)
rec = BioVcf::VcfRecord.new(fields,header)
yield rec
end
end | [
"def",
"each",
"return",
"enum_for",
"(",
":each",
")",
"unless",
"block_given?",
"io",
"=",
"nil",
"if",
"@is_gz",
"infile",
"=",
"open",
"(",
"@file",
")",
"io",
"=",
"Zlib",
"::",
"GzipReader",
".",
"new",
"(",
"infile",
")",
"else",
"io",
"=",
"File",
".",
"open",
"(",
"@file",
")",
"end",
"header",
"=",
"BioVcf",
"::",
"VcfHeader",
".",
"new",
"io",
".",
"each_line",
"do",
"|",
"line",
"|",
"line",
".",
"chomp!",
"if",
"line",
"=~",
"/",
"/",
"header",
".",
"add",
"(",
"line",
")",
"next",
"end",
"if",
"line",
"=~",
"/",
"/",
"header",
".",
"add",
"(",
"line",
")",
"next",
"end",
"fields",
"=",
"BioVcf",
"::",
"VcfLine",
".",
"parse",
"(",
"line",
")",
"rec",
"=",
"BioVcf",
"::",
"VcfRecord",
".",
"new",
"(",
"fields",
",",
"header",
")",
"yield",
"rec",
"end",
"end"
] | Returns an enum that can be used as an iterator. | [
"Returns",
"an",
"enum",
"that",
"can",
"be",
"used",
"as",
"an",
"iterator",
"."
] | bb9a3f9c10ffbd0304690bbca001ad775f6ea54e | https://github.com/pjotrp/bioruby-vcf/blob/bb9a3f9c10ffbd0304690bbca001ad775f6ea54e/lib/bio-vcf/vcffile.rb#L19-L44 | train |
pjotrp/bioruby-vcf | lib/bio-vcf/vcfgenotypefield.rb | BioVcf.VcfGenotypeField.method_missing | def method_missing(m, *args, &block)
return nil if @is_empty
if m =~ /\?$/
# query if a value exists, e.g., r.info.dp? or s.dp?
v = values[fetch(m.to_s.upcase.chop)]
return (not VcfValue::empty?(v))
else
v = values[fetch(m.to_s.upcase)]
return nil if VcfValue::empty?(v)
v = v.to_i if v =~ /^\d+$/
v = v.to_f if v =~ /^\d+\.\d+$/
v
end
end | ruby | def method_missing(m, *args, &block)
return nil if @is_empty
if m =~ /\?$/
# query if a value exists, e.g., r.info.dp? or s.dp?
v = values[fetch(m.to_s.upcase.chop)]
return (not VcfValue::empty?(v))
else
v = values[fetch(m.to_s.upcase)]
return nil if VcfValue::empty?(v)
v = v.to_i if v =~ /^\d+$/
v = v.to_f if v =~ /^\d+\.\d+$/
v
end
end | [
"def",
"method_missing",
"(",
"m",
",",
"*",
"args",
",",
"&",
"block",
")",
"return",
"nil",
"if",
"@is_empty",
"if",
"m",
"=~",
"/",
"\\?",
"/",
"v",
"=",
"values",
"[",
"fetch",
"(",
"m",
".",
"to_s",
".",
"upcase",
".",
"chop",
")",
"]",
"return",
"(",
"not",
"VcfValue",
"::",
"empty?",
"(",
"v",
")",
")",
"else",
"v",
"=",
"values",
"[",
"fetch",
"(",
"m",
".",
"to_s",
".",
"upcase",
")",
"]",
"return",
"nil",
"if",
"VcfValue",
"::",
"empty?",
"(",
"v",
")",
"v",
"=",
"v",
".",
"to_i",
"if",
"v",
"=~",
"/",
"\\d",
"/",
"v",
"=",
"v",
".",
"to_f",
"if",
"v",
"=~",
"/",
"\\d",
"\\.",
"\\d",
"/",
"v",
"end",
"end"
] | Returns the value of a field | [
"Returns",
"the",
"value",
"of",
"a",
"field"
] | bb9a3f9c10ffbd0304690bbca001ad775f6ea54e | https://github.com/pjotrp/bioruby-vcf/blob/bb9a3f9c10ffbd0304690bbca001ad775f6ea54e/lib/bio-vcf/vcfgenotypefield.rb#L172-L185 | train |
pjotrp/bioruby-vcf | lib/bio-vcf/vcfgenotypefield.rb | BioVcf.VcfGenotypeField.ilist | def ilist name
v = fetch_value(name)
return nil if not v
v.split(',').map{|i| i.to_i}
end | ruby | def ilist name
v = fetch_value(name)
return nil if not v
v.split(',').map{|i| i.to_i}
end | [
"def",
"ilist",
"name",
"v",
"=",
"fetch_value",
"(",
"name",
")",
"return",
"nil",
"if",
"not",
"v",
"v",
".",
"split",
"(",
"','",
")",
".",
"map",
"{",
"|",
"i",
"|",
"i",
".",
"to_i",
"}",
"end"
] | Return an integer list | [
"Return",
"an",
"integer",
"list"
] | bb9a3f9c10ffbd0304690bbca001ad775f6ea54e | https://github.com/pjotrp/bioruby-vcf/blob/bb9a3f9c10ffbd0304690bbca001ad775f6ea54e/lib/bio-vcf/vcfgenotypefield.rb#L200-L204 | train |
zverok/saharspec | lib/saharspec/matchers/be_json.rb | RSpec.Matchers.be_json | def be_json(expected = Saharspec::Matchers::BeJson::NONE)
Saharspec::Matchers::BeJson.new(expected)
end | ruby | def be_json(expected = Saharspec::Matchers::BeJson::NONE)
Saharspec::Matchers::BeJson.new(expected)
end | [
"def",
"be_json",
"(",
"expected",
"=",
"Saharspec",
"::",
"Matchers",
"::",
"BeJson",
"::",
"NONE",
")",
"Saharspec",
"::",
"Matchers",
"::",
"BeJson",
".",
"new",
"(",
"expected",
")",
"end"
] | `be_json` checks if provided value is JSON, and optionally checks it contents.
If you need to check against some hashes, it is more convenient to use `be_json_sym`, which
parses JSON with `symbolize_names: true`.
@example
expect('{}').to be_json # ok
expect('garbage').to be_json
# expected value to be a valid JSON string but failed: 765: unexpected token at 'garbage'
expect('{"foo": "bar"}').to be_json('foo' => 'bar') # ok
expect('{"foo": "bar"}').to be_json_sym(foo: 'bar') # more convenient
expect('{"foo": [1, 2, 3]').to be_json_sym(foo: array_including(3)) # nested matchers work
expect(something_large).to be_json_sym(include(meta: include(next_page: Integer)))
@param expected Value or matcher to check JSON against. It should implement `#===` method,
so all standard and custom RSpec matchers work. | [
"be_json",
"checks",
"if",
"provided",
"value",
"is",
"JSON",
"and",
"optionally",
"checks",
"it",
"contents",
"."
] | 6b014308a5399059284f9f24a1acfc6e7df96e30 | https://github.com/zverok/saharspec/blob/6b014308a5399059284f9f24a1acfc6e7df96e30/lib/saharspec/matchers/be_json.rb#L84-L86 | train |
estum/growlyflash | lib/growlyflash/controller_additions.rb | Growlyflash.ControllerAdditions.flash_to_headers | def flash_to_headers
if response.xhr? && growlyhash(true).size > 0
response.headers['X-Message'] = URI.escape(growlyhash.to_json)
growlyhash.each_key { |k| flash.discard(k) }
end
end | ruby | def flash_to_headers
if response.xhr? && growlyhash(true).size > 0
response.headers['X-Message'] = URI.escape(growlyhash.to_json)
growlyhash.each_key { |k| flash.discard(k) }
end
end | [
"def",
"flash_to_headers",
"if",
"response",
".",
"xhr?",
"&&",
"growlyhash",
"(",
"true",
")",
".",
"size",
">",
"0",
"response",
".",
"headers",
"[",
"'X-Message'",
"]",
"=",
"URI",
".",
"escape",
"(",
"growlyhash",
".",
"to_json",
")",
"growlyhash",
".",
"each_key",
"{",
"|",
"k",
"|",
"flash",
".",
"discard",
"(",
"k",
")",
"}",
"end",
"end"
] | Dumps available messages to headers and discards them to prevent appear
it again after refreshing a page | [
"Dumps",
"available",
"messages",
"to",
"headers",
"and",
"discards",
"them",
"to",
"prevent",
"appear",
"it",
"again",
"after",
"refreshing",
"a",
"page"
] | 21028453f23e2acc0a270ebe65700c645e4f97bc | https://github.com/estum/growlyflash/blob/21028453f23e2acc0a270ebe65700c645e4f97bc/lib/growlyflash/controller_additions.rb#L28-L33 | train |
estum/growlyflash | lib/growlyflash/controller_additions.rb | Growlyflash.ControllerAdditions.growlyflash_static_notices | def growlyflash_static_notices(js_var = 'window.flashes')
return if flash.empty?
script = "#{js_var} = #{growlyhash.to_json.html_safe};".freeze
view_context.javascript_tag(script, defer: 'defer')
end | ruby | def growlyflash_static_notices(js_var = 'window.flashes')
return if flash.empty?
script = "#{js_var} = #{growlyhash.to_json.html_safe};".freeze
view_context.javascript_tag(script, defer: 'defer')
end | [
"def",
"growlyflash_static_notices",
"(",
"js_var",
"=",
"'window.flashes'",
")",
"return",
"if",
"flash",
".",
"empty?",
"script",
"=",
"\"#{js_var} = #{growlyhash.to_json.html_safe};\"",
".",
"freeze",
"view_context",
".",
"javascript_tag",
"(",
"script",
",",
"defer",
":",
"'defer'",
")",
"end"
] | View helper method which renders flash messages to js variable if they
weren't dumped to headers with XHR request | [
"View",
"helper",
"method",
"which",
"renders",
"flash",
"messages",
"to",
"js",
"variable",
"if",
"they",
"weren",
"t",
"dumped",
"to",
"headers",
"with",
"XHR",
"request"
] | 21028453f23e2acc0a270ebe65700c645e4f97bc | https://github.com/estum/growlyflash/blob/21028453f23e2acc0a270ebe65700c645e4f97bc/lib/growlyflash/controller_additions.rb#L37-L41 | train |
estum/growlyflash | lib/growlyflash/controller_additions.rb | Growlyflash.ControllerAdditions.growlyhash | def growlyhash(force = false)
@growlyhash = nil if force
@growlyhash ||= flash.to_hash.select { |k, v| v.is_a? String }
end | ruby | def growlyhash(force = false)
@growlyhash = nil if force
@growlyhash ||= flash.to_hash.select { |k, v| v.is_a? String }
end | [
"def",
"growlyhash",
"(",
"force",
"=",
"false",
")",
"@growlyhash",
"=",
"nil",
"if",
"force",
"@growlyhash",
"||=",
"flash",
".",
"to_hash",
".",
"select",
"{",
"|",
"k",
",",
"v",
"|",
"v",
".",
"is_a?",
"String",
"}",
"end"
] | Hash with available growl flash messages which contains a string object. | [
"Hash",
"with",
"available",
"growl",
"flash",
"messages",
"which",
"contains",
"a",
"string",
"object",
"."
] | 21028453f23e2acc0a270ebe65700c645e4f97bc | https://github.com/estum/growlyflash/blob/21028453f23e2acc0a270ebe65700c645e4f97bc/lib/growlyflash/controller_additions.rb#L54-L57 | train |
celsodantas/protokoll | lib/protokoll/protokoll.rb | Protokoll.ClassMethods.protokoll | def protokoll(column, _options = {})
options = { :pattern => "%Y%m#####",
:number_symbol => "#",
:column => column,
:start => 0,
:scope_by => nil }
options.merge!(_options)
raise ArgumentError.new("pattern can't be nil!") if options[:pattern].nil?
raise ArgumentError.new("pattern requires at least one counter symbol #{options[:number_symbol]}") unless pattern_includes_symbols?(options)
# Defining custom method
send :define_method, "reserve_#{options[:column]}!".to_sym do
self[column] = Counter.next(self, options)
end
# Signing before_create
before_create do |record|
unless record[column].present?
record[column] = Counter.next(self, options)
end
end
end | ruby | def protokoll(column, _options = {})
options = { :pattern => "%Y%m#####",
:number_symbol => "#",
:column => column,
:start => 0,
:scope_by => nil }
options.merge!(_options)
raise ArgumentError.new("pattern can't be nil!") if options[:pattern].nil?
raise ArgumentError.new("pattern requires at least one counter symbol #{options[:number_symbol]}") unless pattern_includes_symbols?(options)
# Defining custom method
send :define_method, "reserve_#{options[:column]}!".to_sym do
self[column] = Counter.next(self, options)
end
# Signing before_create
before_create do |record|
unless record[column].present?
record[column] = Counter.next(self, options)
end
end
end | [
"def",
"protokoll",
"(",
"column",
",",
"_options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
":pattern",
"=>",
"\"%Y%m#####\"",
",",
":number_symbol",
"=>",
"\"#\"",
",",
":column",
"=>",
"column",
",",
":start",
"=>",
"0",
",",
":scope_by",
"=>",
"nil",
"}",
"options",
".",
"merge!",
"(",
"_options",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"pattern can't be nil!\"",
")",
"if",
"options",
"[",
":pattern",
"]",
".",
"nil?",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"pattern requires at least one counter symbol #{options[:number_symbol]}\"",
")",
"unless",
"pattern_includes_symbols?",
"(",
"options",
")",
"send",
":define_method",
",",
"\"reserve_#{options[:column]}!\"",
".",
"to_sym",
"do",
"self",
"[",
"column",
"]",
"=",
"Counter",
".",
"next",
"(",
"self",
",",
"options",
")",
"end",
"before_create",
"do",
"|",
"record",
"|",
"unless",
"record",
"[",
"column",
"]",
".",
"present?",
"record",
"[",
"column",
"]",
"=",
"Counter",
".",
"next",
"(",
"self",
",",
"options",
")",
"end",
"end",
"end"
] | Class method available in models
== Example
class Order < ActiveRecord::Base
protokoll :number
end | [
"Class",
"method",
"available",
"in",
"models"
] | 6f4e72aebbb239b30d9cc6b34db87881a3f83d64 | https://github.com/celsodantas/protokoll/blob/6f4e72aebbb239b30d9cc6b34db87881a3f83d64/lib/protokoll/protokoll.rb#L13-L35 | train |
piotrmurach/lex | lib/lex/lexer.rb | Lex.Lexer.lex | def lex(input)
@input = input
return enum_for(:lex, input) unless block_given?
if debug
logger.info "lex: tokens = #{@dsl.lex_tokens}"
logger.info "lex: states = #{@dsl.state_info}"
logger.info "lex: ignore = #{@dsl.state_ignore}"
logger.info "lex: error = #{@dsl.state_error}"
end
stream_tokens(input) do |token|
yield token
end
end | ruby | def lex(input)
@input = input
return enum_for(:lex, input) unless block_given?
if debug
logger.info "lex: tokens = #{@dsl.lex_tokens}"
logger.info "lex: states = #{@dsl.state_info}"
logger.info "lex: ignore = #{@dsl.state_ignore}"
logger.info "lex: error = #{@dsl.state_error}"
end
stream_tokens(input) do |token|
yield token
end
end | [
"def",
"lex",
"(",
"input",
")",
"@input",
"=",
"input",
"return",
"enum_for",
"(",
":lex",
",",
"input",
")",
"unless",
"block_given?",
"if",
"debug",
"logger",
".",
"info",
"\"lex: tokens = #{@dsl.lex_tokens}\"",
"logger",
".",
"info",
"\"lex: states = #{@dsl.state_info}\"",
"logger",
".",
"info",
"\"lex: ignore = #{@dsl.state_ignore}\"",
"logger",
".",
"info",
"\"lex: error = #{@dsl.state_error}\"",
"end",
"stream_tokens",
"(",
"input",
")",
"do",
"|",
"token",
"|",
"yield",
"token",
"end",
"end"
] | Tokenizes input and returns all tokens
@param [String] input
@return [Enumerator]
the tokens found
@api public | [
"Tokenizes",
"input",
"and",
"returns",
"all",
"tokens"
] | 28460ecafb8b92cf9a31e821f9f088c8f7573665 | https://github.com/piotrmurach/lex/blob/28460ecafb8b92cf9a31e821f9f088c8f7573665/lib/lex/lexer.rb#L51-L66 | train |
piotrmurach/lex | lib/lex/lexer.rb | Lex.Lexer.stream_tokens | def stream_tokens(input, &block)
scanner = StringScanner.new(input)
while !scanner.eos?
current_char = scanner.peek(1)
if @dsl.state_ignore[current_state].include?(current_char)
scanner.pos += current_char.size
@char_pos_in_line += current_char.size
next
end
if debug
logger.info "lex: [#{current_state}]: lexemes = #{@dsl.state_lexemes[current_state].map(&:name)}"
end
# Look for regex match
longest_token = nil
@dsl.state_lexemes[current_state].each do |lexeme|
match = lexeme.match(scanner)
next if match.nil?
longest_token = match if longest_token.nil?
next if longest_token.value.length >= match.value.length
longest_token = match
end
if longest_token
if longest_token.action
new_token = longest_token.action.call(self, longest_token)
# No value returned from action move to the next token
if new_token.nil? || !new_token.is_a?(Token)
chars_to_skip = longest_token.value.to_s.length
scanner.pos += chars_to_skip
unless longest_token.name == :newline
@char_pos_in_line += chars_to_skip
end
next
end
end
move_by = longest_token.value.to_s.length
start_char_pos_in_token = @char_pos_in_line + current_char.size
longest_token.update_line(current_line, start_char_pos_in_token)
advance_column(move_by)
scanner.pos += move_by
end
# No match
if longest_token.nil?
# Check in errors
if @dsl.state_error[current_state]
token = Token.new(:error, current_char)
start_char_pos_in_token = @char_pos_in_line + current_char.size
token.update_line(current_line, start_char_pos_in_token)
new_token = @dsl.state_error[current_state].call(self, token)
advance_column(current_char.length)
scanner.pos += current_char.length
if new_token.is_a?(Token) || !new_token.nil?
longest_token = new_token
else
next
end
end
if longest_token.nil?
complain("Illegal character `#{current_char}`")
end
end
logger.info "lex: #{longest_token}" if debug
block.call(longest_token)
end
end | ruby | def stream_tokens(input, &block)
scanner = StringScanner.new(input)
while !scanner.eos?
current_char = scanner.peek(1)
if @dsl.state_ignore[current_state].include?(current_char)
scanner.pos += current_char.size
@char_pos_in_line += current_char.size
next
end
if debug
logger.info "lex: [#{current_state}]: lexemes = #{@dsl.state_lexemes[current_state].map(&:name)}"
end
# Look for regex match
longest_token = nil
@dsl.state_lexemes[current_state].each do |lexeme|
match = lexeme.match(scanner)
next if match.nil?
longest_token = match if longest_token.nil?
next if longest_token.value.length >= match.value.length
longest_token = match
end
if longest_token
if longest_token.action
new_token = longest_token.action.call(self, longest_token)
# No value returned from action move to the next token
if new_token.nil? || !new_token.is_a?(Token)
chars_to_skip = longest_token.value.to_s.length
scanner.pos += chars_to_skip
unless longest_token.name == :newline
@char_pos_in_line += chars_to_skip
end
next
end
end
move_by = longest_token.value.to_s.length
start_char_pos_in_token = @char_pos_in_line + current_char.size
longest_token.update_line(current_line, start_char_pos_in_token)
advance_column(move_by)
scanner.pos += move_by
end
# No match
if longest_token.nil?
# Check in errors
if @dsl.state_error[current_state]
token = Token.new(:error, current_char)
start_char_pos_in_token = @char_pos_in_line + current_char.size
token.update_line(current_line, start_char_pos_in_token)
new_token = @dsl.state_error[current_state].call(self, token)
advance_column(current_char.length)
scanner.pos += current_char.length
if new_token.is_a?(Token) || !new_token.nil?
longest_token = new_token
else
next
end
end
if longest_token.nil?
complain("Illegal character `#{current_char}`")
end
end
logger.info "lex: #{longest_token}" if debug
block.call(longest_token)
end
end | [
"def",
"stream_tokens",
"(",
"input",
",",
"&",
"block",
")",
"scanner",
"=",
"StringScanner",
".",
"new",
"(",
"input",
")",
"while",
"!",
"scanner",
".",
"eos?",
"current_char",
"=",
"scanner",
".",
"peek",
"(",
"1",
")",
"if",
"@dsl",
".",
"state_ignore",
"[",
"current_state",
"]",
".",
"include?",
"(",
"current_char",
")",
"scanner",
".",
"pos",
"+=",
"current_char",
".",
"size",
"@char_pos_in_line",
"+=",
"current_char",
".",
"size",
"next",
"end",
"if",
"debug",
"logger",
".",
"info",
"\"lex: [#{current_state}]: lexemes = #{@dsl.state_lexemes[current_state].map(&:name)}\"",
"end",
"longest_token",
"=",
"nil",
"@dsl",
".",
"state_lexemes",
"[",
"current_state",
"]",
".",
"each",
"do",
"|",
"lexeme",
"|",
"match",
"=",
"lexeme",
".",
"match",
"(",
"scanner",
")",
"next",
"if",
"match",
".",
"nil?",
"longest_token",
"=",
"match",
"if",
"longest_token",
".",
"nil?",
"next",
"if",
"longest_token",
".",
"value",
".",
"length",
">=",
"match",
".",
"value",
".",
"length",
"longest_token",
"=",
"match",
"end",
"if",
"longest_token",
"if",
"longest_token",
".",
"action",
"new_token",
"=",
"longest_token",
".",
"action",
".",
"call",
"(",
"self",
",",
"longest_token",
")",
"if",
"new_token",
".",
"nil?",
"||",
"!",
"new_token",
".",
"is_a?",
"(",
"Token",
")",
"chars_to_skip",
"=",
"longest_token",
".",
"value",
".",
"to_s",
".",
"length",
"scanner",
".",
"pos",
"+=",
"chars_to_skip",
"unless",
"longest_token",
".",
"name",
"==",
":newline",
"@char_pos_in_line",
"+=",
"chars_to_skip",
"end",
"next",
"end",
"end",
"move_by",
"=",
"longest_token",
".",
"value",
".",
"to_s",
".",
"length",
"start_char_pos_in_token",
"=",
"@char_pos_in_line",
"+",
"current_char",
".",
"size",
"longest_token",
".",
"update_line",
"(",
"current_line",
",",
"start_char_pos_in_token",
")",
"advance_column",
"(",
"move_by",
")",
"scanner",
".",
"pos",
"+=",
"move_by",
"end",
"if",
"longest_token",
".",
"nil?",
"if",
"@dsl",
".",
"state_error",
"[",
"current_state",
"]",
"token",
"=",
"Token",
".",
"new",
"(",
":error",
",",
"current_char",
")",
"start_char_pos_in_token",
"=",
"@char_pos_in_line",
"+",
"current_char",
".",
"size",
"token",
".",
"update_line",
"(",
"current_line",
",",
"start_char_pos_in_token",
")",
"new_token",
"=",
"@dsl",
".",
"state_error",
"[",
"current_state",
"]",
".",
"call",
"(",
"self",
",",
"token",
")",
"advance_column",
"(",
"current_char",
".",
"length",
")",
"scanner",
".",
"pos",
"+=",
"current_char",
".",
"length",
"if",
"new_token",
".",
"is_a?",
"(",
"Token",
")",
"||",
"!",
"new_token",
".",
"nil?",
"longest_token",
"=",
"new_token",
"else",
"next",
"end",
"end",
"if",
"longest_token",
".",
"nil?",
"complain",
"(",
"\"Illegal character `#{current_char}`\"",
")",
"end",
"end",
"logger",
".",
"info",
"\"lex: #{longest_token}\"",
"if",
"debug",
"block",
".",
"call",
"(",
"longest_token",
")",
"end",
"end"
] | Advances through input and streams tokens
@param [String] input
@yield [Lex::Token]
@api public | [
"Advances",
"through",
"input",
"and",
"streams",
"tokens"
] | 28460ecafb8b92cf9a31e821f9f088c8f7573665 | https://github.com/piotrmurach/lex/blob/28460ecafb8b92cf9a31e821f9f088c8f7573665/lib/lex/lexer.rb#L75-L143 | train |
leishman/kraken_ruby | lib/kraken_ruby/client.rb | Kraken.Client.add_order | def add_order(opts={})
required_opts = %w{ pair type ordertype volume }
leftover = required_opts - opts.keys.map(&:to_s)
if leftover.length > 0
raise ArgumentError.new("Required options, not given. Input must include #{leftover}")
end
post_private 'AddOrder', opts
end | ruby | def add_order(opts={})
required_opts = %w{ pair type ordertype volume }
leftover = required_opts - opts.keys.map(&:to_s)
if leftover.length > 0
raise ArgumentError.new("Required options, not given. Input must include #{leftover}")
end
post_private 'AddOrder', opts
end | [
"def",
"add_order",
"(",
"opts",
"=",
"{",
"}",
")",
"required_opts",
"=",
"%w{",
"pair",
"type",
"ordertype",
"volume",
"}",
"leftover",
"=",
"required_opts",
"-",
"opts",
".",
"keys",
".",
"map",
"(",
"&",
":to_s",
")",
"if",
"leftover",
".",
"length",
">",
"0",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"Required options, not given. Input must include #{leftover}\"",
")",
"end",
"post_private",
"'AddOrder'",
",",
"opts",
"end"
] | Private User Trading | [
"Private",
"User",
"Trading"
] | bce2daad1f5fd761c5b07c018c5a911c3922d66d | https://github.com/leishman/kraken_ruby/blob/bce2daad1f5fd761c5b07c018c5a911c3922d66d/lib/kraken_ruby/client.rb#L115-L122 | train |
sosedoff/xml-sitemap | lib/xml-sitemap/render_engine.rb | XmlSitemap.RenderEngine.render_nokogiri | def render_nokogiri
unless defined? Nokogiri
raise ArgumentError, "Nokogiri not found!"
end
builder = Nokogiri::XML::Builder.new(:encoding => "UTF-8") do |xml|
xml.urlset(XmlSitemap::MAP_SCHEMA_OPTIONS) { |s|
@items.each do |item|
s.url do |u|
u.loc item.target
# Format and image tag specifications found at http://support.google.com/webmasters/bin/answer.py?hl=en&answer=178636
if item.image_location
u["image"].image do |a|
a["image"].loc item.image_location
a["image"].caption item.image_caption if item.image_caption
a["image"].title item.image_title if item.image_title
a["image"].license item.image_license if item.image_license
a["image"].geo_location item.image_geolocation if item.image_geolocation
end
end
# Format and video tag specifications found at http://support.google.com/webmasters/bin/answer.py?hl=en&answer=80472&topic=10079&ctx=topic#2
if item.video_thumbnail_location && item.video_title && item.video_description && (item.video_content_location || item.video_player_location)
u["video"].video do |a|
a["video"].thumbnail_loc item.video_thumbnail_location
a["video"].title item.video_title
a["video"].description item.video_description
a["video"].content_loc item.video_content_location if item.video_content_location
a["video"].player_loc item.video_player_location if item.video_player_location
a["video"].duration item.video_duration.to_s if item.video_duration
a["video"].expiration_date item.video_expiration_date_value if item.video_expiration_date
a["video"].rating item.video_rating.to_s if item.video_rating
a["video"].view_count item.video_view_count.to_s if item.video_view_count
a["video"].publication_date item.video_publication_date_value if item.video_publication_date
a["video"].family_friendly item.video_family_friendly if item.video_family_friendly
a["video"].category item.video_category if item.video_category
a["video"].restriction item.video_restriction, :relationship => "allow" if item.video_restriction
a["video"].gallery_loc item.video_gallery_location if item.video_gallery_location
a["video"].price item.video_price.to_s, :currency => "USD" if item.video_price
a["video"].requires_subscription item.video_requires_subscription if item.video_requires_subscription
a["video"].uploader item.video_uploader if item.video_uploader
a["video"].platform item.video_platform, :relationship => "allow" if item.video_platform
a["video"].live item.video_live if item.video_live
end
end
u.lastmod item.lastmod_value
u.changefreq item.changefreq.to_s if item.changefreq
u.priority item.priority.to_s if item.priority
end
end
}
end
builder.to_xml
end | ruby | def render_nokogiri
unless defined? Nokogiri
raise ArgumentError, "Nokogiri not found!"
end
builder = Nokogiri::XML::Builder.new(:encoding => "UTF-8") do |xml|
xml.urlset(XmlSitemap::MAP_SCHEMA_OPTIONS) { |s|
@items.each do |item|
s.url do |u|
u.loc item.target
# Format and image tag specifications found at http://support.google.com/webmasters/bin/answer.py?hl=en&answer=178636
if item.image_location
u["image"].image do |a|
a["image"].loc item.image_location
a["image"].caption item.image_caption if item.image_caption
a["image"].title item.image_title if item.image_title
a["image"].license item.image_license if item.image_license
a["image"].geo_location item.image_geolocation if item.image_geolocation
end
end
# Format and video tag specifications found at http://support.google.com/webmasters/bin/answer.py?hl=en&answer=80472&topic=10079&ctx=topic#2
if item.video_thumbnail_location && item.video_title && item.video_description && (item.video_content_location || item.video_player_location)
u["video"].video do |a|
a["video"].thumbnail_loc item.video_thumbnail_location
a["video"].title item.video_title
a["video"].description item.video_description
a["video"].content_loc item.video_content_location if item.video_content_location
a["video"].player_loc item.video_player_location if item.video_player_location
a["video"].duration item.video_duration.to_s if item.video_duration
a["video"].expiration_date item.video_expiration_date_value if item.video_expiration_date
a["video"].rating item.video_rating.to_s if item.video_rating
a["video"].view_count item.video_view_count.to_s if item.video_view_count
a["video"].publication_date item.video_publication_date_value if item.video_publication_date
a["video"].family_friendly item.video_family_friendly if item.video_family_friendly
a["video"].category item.video_category if item.video_category
a["video"].restriction item.video_restriction, :relationship => "allow" if item.video_restriction
a["video"].gallery_loc item.video_gallery_location if item.video_gallery_location
a["video"].price item.video_price.to_s, :currency => "USD" if item.video_price
a["video"].requires_subscription item.video_requires_subscription if item.video_requires_subscription
a["video"].uploader item.video_uploader if item.video_uploader
a["video"].platform item.video_platform, :relationship => "allow" if item.video_platform
a["video"].live item.video_live if item.video_live
end
end
u.lastmod item.lastmod_value
u.changefreq item.changefreq.to_s if item.changefreq
u.priority item.priority.to_s if item.priority
end
end
}
end
builder.to_xml
end | [
"def",
"render_nokogiri",
"unless",
"defined?",
"Nokogiri",
"raise",
"ArgumentError",
",",
"\"Nokogiri not found!\"",
"end",
"builder",
"=",
"Nokogiri",
"::",
"XML",
"::",
"Builder",
".",
"new",
"(",
":encoding",
"=>",
"\"UTF-8\"",
")",
"do",
"|",
"xml",
"|",
"xml",
".",
"urlset",
"(",
"XmlSitemap",
"::",
"MAP_SCHEMA_OPTIONS",
")",
"{",
"|",
"s",
"|",
"@items",
".",
"each",
"do",
"|",
"item",
"|",
"s",
".",
"url",
"do",
"|",
"u",
"|",
"u",
".",
"loc",
"item",
".",
"target",
"if",
"item",
".",
"image_location",
"u",
"[",
"\"image\"",
"]",
".",
"image",
"do",
"|",
"a",
"|",
"a",
"[",
"\"image\"",
"]",
".",
"loc",
"item",
".",
"image_location",
"a",
"[",
"\"image\"",
"]",
".",
"caption",
"item",
".",
"image_caption",
"if",
"item",
".",
"image_caption",
"a",
"[",
"\"image\"",
"]",
".",
"title",
"item",
".",
"image_title",
"if",
"item",
".",
"image_title",
"a",
"[",
"\"image\"",
"]",
".",
"license",
"item",
".",
"image_license",
"if",
"item",
".",
"image_license",
"a",
"[",
"\"image\"",
"]",
".",
"geo_location",
"item",
".",
"image_geolocation",
"if",
"item",
".",
"image_geolocation",
"end",
"end",
"if",
"item",
".",
"video_thumbnail_location",
"&&",
"item",
".",
"video_title",
"&&",
"item",
".",
"video_description",
"&&",
"(",
"item",
".",
"video_content_location",
"||",
"item",
".",
"video_player_location",
")",
"u",
"[",
"\"video\"",
"]",
".",
"video",
"do",
"|",
"a",
"|",
"a",
"[",
"\"video\"",
"]",
".",
"thumbnail_loc",
"item",
".",
"video_thumbnail_location",
"a",
"[",
"\"video\"",
"]",
".",
"title",
"item",
".",
"video_title",
"a",
"[",
"\"video\"",
"]",
".",
"description",
"item",
".",
"video_description",
"a",
"[",
"\"video\"",
"]",
".",
"content_loc",
"item",
".",
"video_content_location",
"if",
"item",
".",
"video_content_location",
"a",
"[",
"\"video\"",
"]",
".",
"player_loc",
"item",
".",
"video_player_location",
"if",
"item",
".",
"video_player_location",
"a",
"[",
"\"video\"",
"]",
".",
"duration",
"item",
".",
"video_duration",
".",
"to_s",
"if",
"item",
".",
"video_duration",
"a",
"[",
"\"video\"",
"]",
".",
"expiration_date",
"item",
".",
"video_expiration_date_value",
"if",
"item",
".",
"video_expiration_date",
"a",
"[",
"\"video\"",
"]",
".",
"rating",
"item",
".",
"video_rating",
".",
"to_s",
"if",
"item",
".",
"video_rating",
"a",
"[",
"\"video\"",
"]",
".",
"view_count",
"item",
".",
"video_view_count",
".",
"to_s",
"if",
"item",
".",
"video_view_count",
"a",
"[",
"\"video\"",
"]",
".",
"publication_date",
"item",
".",
"video_publication_date_value",
"if",
"item",
".",
"video_publication_date",
"a",
"[",
"\"video\"",
"]",
".",
"family_friendly",
"item",
".",
"video_family_friendly",
"if",
"item",
".",
"video_family_friendly",
"a",
"[",
"\"video\"",
"]",
".",
"category",
"item",
".",
"video_category",
"if",
"item",
".",
"video_category",
"a",
"[",
"\"video\"",
"]",
".",
"restriction",
"item",
".",
"video_restriction",
",",
":relationship",
"=>",
"\"allow\"",
"if",
"item",
".",
"video_restriction",
"a",
"[",
"\"video\"",
"]",
".",
"gallery_loc",
"item",
".",
"video_gallery_location",
"if",
"item",
".",
"video_gallery_location",
"a",
"[",
"\"video\"",
"]",
".",
"price",
"item",
".",
"video_price",
".",
"to_s",
",",
":currency",
"=>",
"\"USD\"",
"if",
"item",
".",
"video_price",
"a",
"[",
"\"video\"",
"]",
".",
"requires_subscription",
"item",
".",
"video_requires_subscription",
"if",
"item",
".",
"video_requires_subscription",
"a",
"[",
"\"video\"",
"]",
".",
"uploader",
"item",
".",
"video_uploader",
"if",
"item",
".",
"video_uploader",
"a",
"[",
"\"video\"",
"]",
".",
"platform",
"item",
".",
"video_platform",
",",
":relationship",
"=>",
"\"allow\"",
"if",
"item",
".",
"video_platform",
"a",
"[",
"\"video\"",
"]",
".",
"live",
"item",
".",
"video_live",
"if",
"item",
".",
"video_live",
"end",
"end",
"u",
".",
"lastmod",
"item",
".",
"lastmod_value",
"u",
".",
"changefreq",
"item",
".",
"changefreq",
".",
"to_s",
"if",
"item",
".",
"changefreq",
"u",
".",
"priority",
"item",
".",
"priority",
".",
"to_s",
"if",
"item",
".",
"priority",
"end",
"end",
"}",
"end",
"builder",
".",
"to_xml",
"end"
] | Render with Nokogiri gem | [
"Render",
"with",
"Nokogiri",
"gem"
] | a9b510d49297d219c5b19a9c778cb8c6f0f1ae16 | https://github.com/sosedoff/xml-sitemap/blob/a9b510d49297d219c5b19a9c778cb8c6f0f1ae16/lib/xml-sitemap/render_engine.rb#L7-L62 | train |
sosedoff/xml-sitemap | lib/xml-sitemap/render_engine.rb | XmlSitemap.RenderEngine.render_string | def render_string
result = '<?xml version="1.0" encoding="UTF-8"?>' + "\n<urlset"
XmlSitemap::MAP_SCHEMA_OPTIONS.each do |key, val|
result << ' ' + key + '="' + val + '"'
end
result << ">\n"
item_results = []
@items.each do |item|
item_string = " <url>\n"
item_string << " <loc>#{CGI::escapeHTML(item.target)}</loc>\n"
# Format and image tag specifications found at http://support.google.com/webmasters/bin/answer.py?hl=en&answer=178636
if item.image_location
item_string << " <image:image>\n"
item_string << " <image:loc>#{CGI::escapeHTML(item.image_location)}</image:loc>\n"
item_string << " <image:caption>#{CGI::escapeHTML(item.image_caption)}</image:caption>\n" if item.image_caption
item_string << " <image:title>#{CGI::escapeHTML(item.image_title)}</image:title>\n" if item.image_title
item_string << " <image:license>#{CGI::escapeHTML(item.image_license)}</image:license>\n" if item.image_license
item_string << " <image:geo_location>#{CGI::escapeHTML(item.image_geolocation)}</image:geo_location>\n" if item.image_geolocation
item_string << " </image:image>\n"
end
# Format and video tag specifications found at http://support.google.com/webmasters/bin/answer.py?hl=en&answer=80472&topic=10079&ctx=topic#2
if item.video_thumbnail_location && item.video_title && item.video_description && (item.video_content_location || item.video_player_location)
item_string << " <video:video>\n"
item_string << " <video:thumbnail_loc>#{CGI::escapeHTML(item.video_thumbnail_location)}</video:thumbnail_loc>\n"
item_string << " <video:title>#{CGI::escapeHTML(item.video_title)}</video:title>\n"
item_string << " <video:description>#{CGI::escapeHTML(item.video_description)}</video:description>\n"
item_string << " <video:content_loc>#{CGI::escapeHTML(item.video_content_location)}</video:content_loc>\n" if item.video_content_location
item_string << " <video:player_loc>#{CGI::escapeHTML(item.video_player_location)}</video:player_loc>\n" if item.video_player_location
item_string << " <video:duration>#{CGI::escapeHTML(item.video_duration.to_s)}</video:duration>\n" if item.video_duration
item_string << " <video:expiration_date>#{item.video_expiration_date_value}</video:expiration_date>\n" if item.video_expiration_date
item_string << " <video:rating>#{CGI::escapeHTML(item.video_rating.to_s)}</video:rating>\n" if item.video_rating
item_string << " <video:view_count>#{CGI::escapeHTML(item.video_view_count.to_s)}</video:view_count>\n" if item.video_view_count
item_string << " <video:publication_date>#{item.video_publication_date_value}</video:publication_date>\n" if item.video_publication_date
item_string << " <video:family_friendly>#{CGI::escapeHTML(item.video_family_friendly)}</video:family_friendly>\n" if item.video_family_friendly
item_string << " <video:category>#{CGI::escapeHTML(item.video_category)}</video:category>\n" if item.video_category
item_string << " <video:restriction relationship=\"allow\">#{CGI::escapeHTML(item.video_restriction)}</video:restriction>\n" if item.video_restriction
item_string << " <video:gallery_loc>#{CGI::escapeHTML(item.video_gallery_location)}</video:gallery_loc>\n" if item.video_gallery_location
item_string << " <video:price currency=\"USD\">#{CGI::escapeHTML(item.video_price.to_s)}</video:price>\n" if item.video_price
item_string << " <video:requires_subscription>#{CGI::escapeHTML(item.video_requires_subscription)}</video:requires_subscription>\n" if item.video_requires_subscription
item_string << " <video:uploader>#{CGI::escapeHTML(item.video_uploader)}</video:uploader>\n" if item.video_uploader
item_string << " <video:platform relationship=\"allow\">#{CGI::escapeHTML(item.video_platform)}</video:platform>\n" if item.video_platform
item_string << " <video:live>#{CGI::escapeHTML(item.video_live)}</video:live>\n" if item.video_live
item_string << " </video:video>\n"
end
item_string << " <lastmod>#{item.lastmod_value}</lastmod>\n"
item_string << " <changefreq>#{item.changefreq}</changefreq>\n" if item.changefreq
item_string << " <priority>#{item.priority}</priority>\n" if item.priority
item_string << " </url>\n"
item_results << item_string
end
result << item_results.join("")
result << "</urlset>\n"
result
end | ruby | def render_string
result = '<?xml version="1.0" encoding="UTF-8"?>' + "\n<urlset"
XmlSitemap::MAP_SCHEMA_OPTIONS.each do |key, val|
result << ' ' + key + '="' + val + '"'
end
result << ">\n"
item_results = []
@items.each do |item|
item_string = " <url>\n"
item_string << " <loc>#{CGI::escapeHTML(item.target)}</loc>\n"
# Format and image tag specifications found at http://support.google.com/webmasters/bin/answer.py?hl=en&answer=178636
if item.image_location
item_string << " <image:image>\n"
item_string << " <image:loc>#{CGI::escapeHTML(item.image_location)}</image:loc>\n"
item_string << " <image:caption>#{CGI::escapeHTML(item.image_caption)}</image:caption>\n" if item.image_caption
item_string << " <image:title>#{CGI::escapeHTML(item.image_title)}</image:title>\n" if item.image_title
item_string << " <image:license>#{CGI::escapeHTML(item.image_license)}</image:license>\n" if item.image_license
item_string << " <image:geo_location>#{CGI::escapeHTML(item.image_geolocation)}</image:geo_location>\n" if item.image_geolocation
item_string << " </image:image>\n"
end
# Format and video tag specifications found at http://support.google.com/webmasters/bin/answer.py?hl=en&answer=80472&topic=10079&ctx=topic#2
if item.video_thumbnail_location && item.video_title && item.video_description && (item.video_content_location || item.video_player_location)
item_string << " <video:video>\n"
item_string << " <video:thumbnail_loc>#{CGI::escapeHTML(item.video_thumbnail_location)}</video:thumbnail_loc>\n"
item_string << " <video:title>#{CGI::escapeHTML(item.video_title)}</video:title>\n"
item_string << " <video:description>#{CGI::escapeHTML(item.video_description)}</video:description>\n"
item_string << " <video:content_loc>#{CGI::escapeHTML(item.video_content_location)}</video:content_loc>\n" if item.video_content_location
item_string << " <video:player_loc>#{CGI::escapeHTML(item.video_player_location)}</video:player_loc>\n" if item.video_player_location
item_string << " <video:duration>#{CGI::escapeHTML(item.video_duration.to_s)}</video:duration>\n" if item.video_duration
item_string << " <video:expiration_date>#{item.video_expiration_date_value}</video:expiration_date>\n" if item.video_expiration_date
item_string << " <video:rating>#{CGI::escapeHTML(item.video_rating.to_s)}</video:rating>\n" if item.video_rating
item_string << " <video:view_count>#{CGI::escapeHTML(item.video_view_count.to_s)}</video:view_count>\n" if item.video_view_count
item_string << " <video:publication_date>#{item.video_publication_date_value}</video:publication_date>\n" if item.video_publication_date
item_string << " <video:family_friendly>#{CGI::escapeHTML(item.video_family_friendly)}</video:family_friendly>\n" if item.video_family_friendly
item_string << " <video:category>#{CGI::escapeHTML(item.video_category)}</video:category>\n" if item.video_category
item_string << " <video:restriction relationship=\"allow\">#{CGI::escapeHTML(item.video_restriction)}</video:restriction>\n" if item.video_restriction
item_string << " <video:gallery_loc>#{CGI::escapeHTML(item.video_gallery_location)}</video:gallery_loc>\n" if item.video_gallery_location
item_string << " <video:price currency=\"USD\">#{CGI::escapeHTML(item.video_price.to_s)}</video:price>\n" if item.video_price
item_string << " <video:requires_subscription>#{CGI::escapeHTML(item.video_requires_subscription)}</video:requires_subscription>\n" if item.video_requires_subscription
item_string << " <video:uploader>#{CGI::escapeHTML(item.video_uploader)}</video:uploader>\n" if item.video_uploader
item_string << " <video:platform relationship=\"allow\">#{CGI::escapeHTML(item.video_platform)}</video:platform>\n" if item.video_platform
item_string << " <video:live>#{CGI::escapeHTML(item.video_live)}</video:live>\n" if item.video_live
item_string << " </video:video>\n"
end
item_string << " <lastmod>#{item.lastmod_value}</lastmod>\n"
item_string << " <changefreq>#{item.changefreq}</changefreq>\n" if item.changefreq
item_string << " <priority>#{item.priority}</priority>\n" if item.priority
item_string << " </url>\n"
item_results << item_string
end
result << item_results.join("")
result << "</urlset>\n"
result
end | [
"def",
"render_string",
"result",
"=",
"'<?xml version=\"1.0\" encoding=\"UTF-8\"?>'",
"+",
"\"\\n<urlset\"",
"XmlSitemap",
"::",
"MAP_SCHEMA_OPTIONS",
".",
"each",
"do",
"|",
"key",
",",
"val",
"|",
"result",
"<<",
"' '",
"+",
"key",
"+",
"'=\"'",
"+",
"val",
"+",
"'\"'",
"end",
"result",
"<<",
"\">\\n\"",
"item_results",
"=",
"[",
"]",
"@items",
".",
"each",
"do",
"|",
"item",
"|",
"item_string",
"=",
"\" <url>\\n\"",
"item_string",
"<<",
"\" <loc>#{CGI::escapeHTML(item.target)}</loc>\\n\"",
"if",
"item",
".",
"image_location",
"item_string",
"<<",
"\" <image:image>\\n\"",
"item_string",
"<<",
"\" <image:loc>#{CGI::escapeHTML(item.image_location)}</image:loc>\\n\"",
"item_string",
"<<",
"\" <image:caption>#{CGI::escapeHTML(item.image_caption)}</image:caption>\\n\"",
"if",
"item",
".",
"image_caption",
"item_string",
"<<",
"\" <image:title>#{CGI::escapeHTML(item.image_title)}</image:title>\\n\"",
"if",
"item",
".",
"image_title",
"item_string",
"<<",
"\" <image:license>#{CGI::escapeHTML(item.image_license)}</image:license>\\n\"",
"if",
"item",
".",
"image_license",
"item_string",
"<<",
"\" <image:geo_location>#{CGI::escapeHTML(item.image_geolocation)}</image:geo_location>\\n\"",
"if",
"item",
".",
"image_geolocation",
"item_string",
"<<",
"\" </image:image>\\n\"",
"end",
"if",
"item",
".",
"video_thumbnail_location",
"&&",
"item",
".",
"video_title",
"&&",
"item",
".",
"video_description",
"&&",
"(",
"item",
".",
"video_content_location",
"||",
"item",
".",
"video_player_location",
")",
"item_string",
"<<",
"\" <video:video>\\n\"",
"item_string",
"<<",
"\" <video:thumbnail_loc>#{CGI::escapeHTML(item.video_thumbnail_location)}</video:thumbnail_loc>\\n\"",
"item_string",
"<<",
"\" <video:title>#{CGI::escapeHTML(item.video_title)}</video:title>\\n\"",
"item_string",
"<<",
"\" <video:description>#{CGI::escapeHTML(item.video_description)}</video:description>\\n\"",
"item_string",
"<<",
"\" <video:content_loc>#{CGI::escapeHTML(item.video_content_location)}</video:content_loc>\\n\"",
"if",
"item",
".",
"video_content_location",
"item_string",
"<<",
"\" <video:player_loc>#{CGI::escapeHTML(item.video_player_location)}</video:player_loc>\\n\"",
"if",
"item",
".",
"video_player_location",
"item_string",
"<<",
"\" <video:duration>#{CGI::escapeHTML(item.video_duration.to_s)}</video:duration>\\n\"",
"if",
"item",
".",
"video_duration",
"item_string",
"<<",
"\" <video:expiration_date>#{item.video_expiration_date_value}</video:expiration_date>\\n\"",
"if",
"item",
".",
"video_expiration_date",
"item_string",
"<<",
"\" <video:rating>#{CGI::escapeHTML(item.video_rating.to_s)}</video:rating>\\n\"",
"if",
"item",
".",
"video_rating",
"item_string",
"<<",
"\" <video:view_count>#{CGI::escapeHTML(item.video_view_count.to_s)}</video:view_count>\\n\"",
"if",
"item",
".",
"video_view_count",
"item_string",
"<<",
"\" <video:publication_date>#{item.video_publication_date_value}</video:publication_date>\\n\"",
"if",
"item",
".",
"video_publication_date",
"item_string",
"<<",
"\" <video:family_friendly>#{CGI::escapeHTML(item.video_family_friendly)}</video:family_friendly>\\n\"",
"if",
"item",
".",
"video_family_friendly",
"item_string",
"<<",
"\" <video:category>#{CGI::escapeHTML(item.video_category)}</video:category>\\n\"",
"if",
"item",
".",
"video_category",
"item_string",
"<<",
"\" <video:restriction relationship=\\\"allow\\\">#{CGI::escapeHTML(item.video_restriction)}</video:restriction>\\n\"",
"if",
"item",
".",
"video_restriction",
"item_string",
"<<",
"\" <video:gallery_loc>#{CGI::escapeHTML(item.video_gallery_location)}</video:gallery_loc>\\n\"",
"if",
"item",
".",
"video_gallery_location",
"item_string",
"<<",
"\" <video:price currency=\\\"USD\\\">#{CGI::escapeHTML(item.video_price.to_s)}</video:price>\\n\"",
"if",
"item",
".",
"video_price",
"item_string",
"<<",
"\" <video:requires_subscription>#{CGI::escapeHTML(item.video_requires_subscription)}</video:requires_subscription>\\n\"",
"if",
"item",
".",
"video_requires_subscription",
"item_string",
"<<",
"\" <video:uploader>#{CGI::escapeHTML(item.video_uploader)}</video:uploader>\\n\"",
"if",
"item",
".",
"video_uploader",
"item_string",
"<<",
"\" <video:platform relationship=\\\"allow\\\">#{CGI::escapeHTML(item.video_platform)}</video:platform>\\n\"",
"if",
"item",
".",
"video_platform",
"item_string",
"<<",
"\" <video:live>#{CGI::escapeHTML(item.video_live)}</video:live>\\n\"",
"if",
"item",
".",
"video_live",
"item_string",
"<<",
"\" </video:video>\\n\"",
"end",
"item_string",
"<<",
"\" <lastmod>#{item.lastmod_value}</lastmod>\\n\"",
"item_string",
"<<",
"\" <changefreq>#{item.changefreq}</changefreq>\\n\"",
"if",
"item",
".",
"changefreq",
"item_string",
"<<",
"\" <priority>#{item.priority}</priority>\\n\"",
"if",
"item",
".",
"priority",
"item_string",
"<<",
"\" </url>\\n\"",
"item_results",
"<<",
"item_string",
"end",
"result",
"<<",
"item_results",
".",
"join",
"(",
"\"\"",
")",
"result",
"<<",
"\"</urlset>\\n\"",
"result",
"end"
] | Render with plain strings | [
"Render",
"with",
"plain",
"strings"
] | a9b510d49297d219c5b19a9c778cb8c6f0f1ae16 | https://github.com/sosedoff/xml-sitemap/blob/a9b510d49297d219c5b19a9c778cb8c6f0f1ae16/lib/xml-sitemap/render_engine.rb#L121-L183 | train |
SimplyBuilt/SimonSays | lib/simon_says/authorizer.rb | SimonSays.Authorizer.find_resource | def find_resource(resource, options = {})
resource = resource.to_s
scope, query = resource_scope_and_query(resource, options)
through = options[:through] ? options[:through].to_s : nil
assoc = through || (options[:from] ? resource.pluralize : nil)
scope = scope.send(assoc) if assoc && scope.respond_to?(assoc)
record = scope.where(query).first!
if through
instance_variable_set "@#{through.singularize}", record
record = record.send(resource)
end
instance_variable_set "@#{resource}", record
end | ruby | def find_resource(resource, options = {})
resource = resource.to_s
scope, query = resource_scope_and_query(resource, options)
through = options[:through] ? options[:through].to_s : nil
assoc = through || (options[:from] ? resource.pluralize : nil)
scope = scope.send(assoc) if assoc && scope.respond_to?(assoc)
record = scope.where(query).first!
if through
instance_variable_set "@#{through.singularize}", record
record = record.send(resource)
end
instance_variable_set "@#{resource}", record
end | [
"def",
"find_resource",
"(",
"resource",
",",
"options",
"=",
"{",
"}",
")",
"resource",
"=",
"resource",
".",
"to_s",
"scope",
",",
"query",
"=",
"resource_scope_and_query",
"(",
"resource",
",",
"options",
")",
"through",
"=",
"options",
"[",
":through",
"]",
"?",
"options",
"[",
":through",
"]",
".",
"to_s",
":",
"nil",
"assoc",
"=",
"through",
"||",
"(",
"options",
"[",
":from",
"]",
"?",
"resource",
".",
"pluralize",
":",
"nil",
")",
"scope",
"=",
"scope",
".",
"send",
"(",
"assoc",
")",
"if",
"assoc",
"&&",
"scope",
".",
"respond_to?",
"(",
"assoc",
")",
"record",
"=",
"scope",
".",
"where",
"(",
"query",
")",
".",
"first!",
"if",
"through",
"instance_variable_set",
"\"@#{through.singularize}\"",
",",
"record",
"record",
"=",
"record",
".",
"send",
"(",
"resource",
")",
"end",
"instance_variable_set",
"\"@#{resource}\"",
",",
"record",
"end"
] | Internal find_resource instance method
@private
@param [Symbol, String] resource name of resource to find
@param [Hash] options finder options | [
"Internal",
"find_resource",
"instance",
"method"
] | d3e937f49118c7b7a405fed806d043e412adac2b | https://github.com/SimplyBuilt/SimonSays/blob/d3e937f49118c7b7a405fed806d043e412adac2b/lib/simon_says/authorizer.rb#L123-L140 | train |
SimplyBuilt/SimonSays | lib/simon_says/authorizer.rb | SimonSays.Authorizer.authorize | def authorize(required = nil, options)
if through = options[:through]
name = through.to_s.singularize.to_sym
else
name = options[:resource]
end
record = instance_variable_get("@#{name}")
if record.nil? # must be devise scope
record = send("current_#{name}")
send "authenticate_#{name}!"
end
role_attr = record.class.role_attribute_name
actual = record.send(role_attr)
required ||= options[role_attr]
required = [required] unless Array === required
# actual roles must have at least
# one required role (array intersection)
((required & actual).size > 0).tap do |res|
raise Denied.new(role_attr, required, actual) unless res
end
end | ruby | def authorize(required = nil, options)
if through = options[:through]
name = through.to_s.singularize.to_sym
else
name = options[:resource]
end
record = instance_variable_get("@#{name}")
if record.nil? # must be devise scope
record = send("current_#{name}")
send "authenticate_#{name}!"
end
role_attr = record.class.role_attribute_name
actual = record.send(role_attr)
required ||= options[role_attr]
required = [required] unless Array === required
# actual roles must have at least
# one required role (array intersection)
((required & actual).size > 0).tap do |res|
raise Denied.new(role_attr, required, actual) unless res
end
end | [
"def",
"authorize",
"(",
"required",
"=",
"nil",
",",
"options",
")",
"if",
"through",
"=",
"options",
"[",
":through",
"]",
"name",
"=",
"through",
".",
"to_s",
".",
"singularize",
".",
"to_sym",
"else",
"name",
"=",
"options",
"[",
":resource",
"]",
"end",
"record",
"=",
"instance_variable_get",
"(",
"\"@#{name}\"",
")",
"if",
"record",
".",
"nil?",
"record",
"=",
"send",
"(",
"\"current_#{name}\"",
")",
"send",
"\"authenticate_#{name}!\"",
"end",
"role_attr",
"=",
"record",
".",
"class",
".",
"role_attribute_name",
"actual",
"=",
"record",
".",
"send",
"(",
"role_attr",
")",
"required",
"||=",
"options",
"[",
"role_attr",
"]",
"required",
"=",
"[",
"required",
"]",
"unless",
"Array",
"===",
"required",
"(",
"(",
"required",
"&",
"actual",
")",
".",
"size",
">",
"0",
")",
".",
"tap",
"do",
"|",
"res",
"|",
"raise",
"Denied",
".",
"new",
"(",
"role_attr",
",",
"required",
",",
"actual",
")",
"unless",
"res",
"end",
"end"
] | Internal authorize instance method
@private
@param [Symbol, String] one or more required roles
@param [Hash] options authorizer options | [
"Internal",
"authorize",
"instance",
"method"
] | d3e937f49118c7b7a405fed806d043e412adac2b | https://github.com/SimplyBuilt/SimonSays/blob/d3e937f49118c7b7a405fed806d043e412adac2b/lib/simon_says/authorizer.rb#L147-L172 | train |
sosedoff/xml-sitemap | lib/xml-sitemap/index.rb | XmlSitemap.Index.add | def add(map, use_offsets=true)
raise ArgumentError, 'XmlSitemap::Map object required!' unless map.kind_of?(XmlSitemap::Map)
raise ArgumentError, 'Map is empty!' if map.empty?
@maps << {
:loc => use_offsets ? map.index_url(@offsets[map.group], @secure) : map.plain_index_url(@secure),
:lastmod => map.created_at.utc.iso8601
}
@offsets[map.group] += 1
end | ruby | def add(map, use_offsets=true)
raise ArgumentError, 'XmlSitemap::Map object required!' unless map.kind_of?(XmlSitemap::Map)
raise ArgumentError, 'Map is empty!' if map.empty?
@maps << {
:loc => use_offsets ? map.index_url(@offsets[map.group], @secure) : map.plain_index_url(@secure),
:lastmod => map.created_at.utc.iso8601
}
@offsets[map.group] += 1
end | [
"def",
"add",
"(",
"map",
",",
"use_offsets",
"=",
"true",
")",
"raise",
"ArgumentError",
",",
"'XmlSitemap::Map object required!'",
"unless",
"map",
".",
"kind_of?",
"(",
"XmlSitemap",
"::",
"Map",
")",
"raise",
"ArgumentError",
",",
"'Map is empty!'",
"if",
"map",
".",
"empty?",
"@maps",
"<<",
"{",
":loc",
"=>",
"use_offsets",
"?",
"map",
".",
"index_url",
"(",
"@offsets",
"[",
"map",
".",
"group",
"]",
",",
"@secure",
")",
":",
"map",
".",
"plain_index_url",
"(",
"@secure",
")",
",",
":lastmod",
"=>",
"map",
".",
"created_at",
".",
"utc",
".",
"iso8601",
"}",
"@offsets",
"[",
"map",
".",
"group",
"]",
"+=",
"1",
"end"
] | Initialize a new Index instance
opts - Index options
opts[:secure] - Force HTTPS for all items. (default: false)
Add map object to index
map - XmlSitemap::Map instance | [
"Initialize",
"a",
"new",
"Index",
"instance"
] | a9b510d49297d219c5b19a9c778cb8c6f0f1ae16 | https://github.com/sosedoff/xml-sitemap/blob/a9b510d49297d219c5b19a9c778cb8c6f0f1ae16/lib/xml-sitemap/index.rb#L23-L32 | train |
sosedoff/xml-sitemap | lib/xml-sitemap/index.rb | XmlSitemap.Index.render | def render
xml = Builder::XmlMarkup.new(:indent => 2)
xml.instruct!(:xml, :version => '1.0', :encoding => 'UTF-8')
xml.sitemapindex(XmlSitemap::INDEX_SCHEMA_OPTIONS) { |s|
@maps.each do |item|
s.sitemap do |m|
m.loc item[:loc]
m.lastmod item[:lastmod]
end
end
}.to_s
end | ruby | def render
xml = Builder::XmlMarkup.new(:indent => 2)
xml.instruct!(:xml, :version => '1.0', :encoding => 'UTF-8')
xml.sitemapindex(XmlSitemap::INDEX_SCHEMA_OPTIONS) { |s|
@maps.each do |item|
s.sitemap do |m|
m.loc item[:loc]
m.lastmod item[:lastmod]
end
end
}.to_s
end | [
"def",
"render",
"xml",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"(",
":indent",
"=>",
"2",
")",
"xml",
".",
"instruct!",
"(",
":xml",
",",
":version",
"=>",
"'1.0'",
",",
":encoding",
"=>",
"'UTF-8'",
")",
"xml",
".",
"sitemapindex",
"(",
"XmlSitemap",
"::",
"INDEX_SCHEMA_OPTIONS",
")",
"{",
"|",
"s",
"|",
"@maps",
".",
"each",
"do",
"|",
"item",
"|",
"s",
".",
"sitemap",
"do",
"|",
"m",
"|",
"m",
".",
"loc",
"item",
"[",
":loc",
"]",
"m",
".",
"lastmod",
"item",
"[",
":lastmod",
"]",
"end",
"end",
"}",
".",
"to_s",
"end"
] | Generate sitemap XML index | [
"Generate",
"sitemap",
"XML",
"index"
] | a9b510d49297d219c5b19a9c778cb8c6f0f1ae16 | https://github.com/sosedoff/xml-sitemap/blob/a9b510d49297d219c5b19a9c778cb8c6f0f1ae16/lib/xml-sitemap/index.rb#L36-L47 | train |
sosedoff/xml-sitemap | lib/xml-sitemap/index.rb | XmlSitemap.Index.render_to | def render_to(path, options={})
overwrite = options[:overwrite] || true
path = File.expand_path(path)
if File.exists?(path) && !overwrite
raise RuntimeError, "File already exists and not overwritable!"
end
File.open(path, 'w') { |f| f.write(self.render) }
end | ruby | def render_to(path, options={})
overwrite = options[:overwrite] || true
path = File.expand_path(path)
if File.exists?(path) && !overwrite
raise RuntimeError, "File already exists and not overwritable!"
end
File.open(path, 'w') { |f| f.write(self.render) }
end | [
"def",
"render_to",
"(",
"path",
",",
"options",
"=",
"{",
"}",
")",
"overwrite",
"=",
"options",
"[",
":overwrite",
"]",
"||",
"true",
"path",
"=",
"File",
".",
"expand_path",
"(",
"path",
")",
"if",
"File",
".",
"exists?",
"(",
"path",
")",
"&&",
"!",
"overwrite",
"raise",
"RuntimeError",
",",
"\"File already exists and not overwritable!\"",
"end",
"File",
".",
"open",
"(",
"path",
",",
"'w'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"self",
".",
"render",
")",
"}",
"end"
] | Render XML sitemap index into the file
path - Output filename
options - Options hash
options[:ovewrite] - Overwrite file contents (default: true) | [
"Render",
"XML",
"sitemap",
"index",
"into",
"the",
"file"
] | a9b510d49297d219c5b19a9c778cb8c6f0f1ae16 | https://github.com/sosedoff/xml-sitemap/blob/a9b510d49297d219c5b19a9c778cb8c6f0f1ae16/lib/xml-sitemap/index.rb#L56-L65 | train |
sosedoff/xml-sitemap | lib/xml-sitemap/map.rb | XmlSitemap.Map.add | def add(target, opts={})
raise RuntimeError, 'Only up to 50k records allowed!' if @items.size > 50000
raise ArgumentError, 'Target required!' if target.nil?
raise ArgumentError, 'Target is empty!' if target.to_s.strip.empty?
url = process_target(target)
if url.length > 2048
raise ArgumentError, "Target can't be longer than 2,048 characters!"
end
opts[:updated] = @created_at unless opts.key?(:updated)
item = XmlSitemap::Item.new(url, opts)
@items << item
item
end | ruby | def add(target, opts={})
raise RuntimeError, 'Only up to 50k records allowed!' if @items.size > 50000
raise ArgumentError, 'Target required!' if target.nil?
raise ArgumentError, 'Target is empty!' if target.to_s.strip.empty?
url = process_target(target)
if url.length > 2048
raise ArgumentError, "Target can't be longer than 2,048 characters!"
end
opts[:updated] = @created_at unless opts.key?(:updated)
item = XmlSitemap::Item.new(url, opts)
@items << item
item
end | [
"def",
"add",
"(",
"target",
",",
"opts",
"=",
"{",
"}",
")",
"raise",
"RuntimeError",
",",
"'Only up to 50k records allowed!'",
"if",
"@items",
".",
"size",
">",
"50000",
"raise",
"ArgumentError",
",",
"'Target required!'",
"if",
"target",
".",
"nil?",
"raise",
"ArgumentError",
",",
"'Target is empty!'",
"if",
"target",
".",
"to_s",
".",
"strip",
".",
"empty?",
"url",
"=",
"process_target",
"(",
"target",
")",
"if",
"url",
".",
"length",
">",
"2048",
"raise",
"ArgumentError",
",",
"\"Target can't be longer than 2,048 characters!\"",
"end",
"opts",
"[",
":updated",
"]",
"=",
"@created_at",
"unless",
"opts",
".",
"key?",
"(",
":updated",
")",
"item",
"=",
"XmlSitemap",
"::",
"Item",
".",
"new",
"(",
"url",
",",
"opts",
")",
"@items",
"<<",
"item",
"item",
"end"
] | Initializa a new Map instance
domain - Primary domain for the map (required)
opts - Map options
opts[:home] - Automatic homepage creation. To disable set to false. (default: true)
opts[:secure] - Force HTTPS for all items. (default: false)
opts[:time] - Set default lastmod timestamp for items (default: current time)
opts[:group] - Group name for sitemap index. (default: sitemap)
opts[:root] - Force all links to fall under the main domain.
You can add full urls (not paths) if set to false. (default: true)
Adds a new item to the map
target - Path or url
opts - Item options
opts[:updated] - Lastmod property of the item
opts[:period] - Update frequency.
opts[:priority] - Item priority.
opts[:validate_time] - Skip time validation if want to insert raw strings. | [
"Initializa",
"a",
"new",
"Map",
"instance"
] | a9b510d49297d219c5b19a9c778cb8c6f0f1ae16 | https://github.com/sosedoff/xml-sitemap/blob/a9b510d49297d219c5b19a9c778cb8c6f0f1ae16/lib/xml-sitemap/map.rb#L49-L64 | train |
sosedoff/xml-sitemap | lib/xml-sitemap/map.rb | XmlSitemap.Map.render_to | def render_to(path, options={})
overwrite = options[:overwrite] == true || true
compress = options[:gzip] == true || false
path = File.expand_path(path)
path << ".gz" unless path =~ /\.gz\z/i if compress
if File.exists?(path) && !overwrite
raise RuntimeError, "File already exists and not overwritable!"
end
File.open(path, 'wb') do |f|
unless compress
f.write(self.render)
else
gz = Zlib::GzipWriter.new(f)
gz.write(self.render)
gz.close
end
end
end | ruby | def render_to(path, options={})
overwrite = options[:overwrite] == true || true
compress = options[:gzip] == true || false
path = File.expand_path(path)
path << ".gz" unless path =~ /\.gz\z/i if compress
if File.exists?(path) && !overwrite
raise RuntimeError, "File already exists and not overwritable!"
end
File.open(path, 'wb') do |f|
unless compress
f.write(self.render)
else
gz = Zlib::GzipWriter.new(f)
gz.write(self.render)
gz.close
end
end
end | [
"def",
"render_to",
"(",
"path",
",",
"options",
"=",
"{",
"}",
")",
"overwrite",
"=",
"options",
"[",
":overwrite",
"]",
"==",
"true",
"||",
"true",
"compress",
"=",
"options",
"[",
":gzip",
"]",
"==",
"true",
"||",
"false",
"path",
"=",
"File",
".",
"expand_path",
"(",
"path",
")",
"path",
"<<",
"\".gz\"",
"unless",
"path",
"=~",
"/",
"\\.",
"\\z",
"/i",
"if",
"compress",
"if",
"File",
".",
"exists?",
"(",
"path",
")",
"&&",
"!",
"overwrite",
"raise",
"RuntimeError",
",",
"\"File already exists and not overwritable!\"",
"end",
"File",
".",
"open",
"(",
"path",
",",
"'wb'",
")",
"do",
"|",
"f",
"|",
"unless",
"compress",
"f",
".",
"write",
"(",
"self",
".",
"render",
")",
"else",
"gz",
"=",
"Zlib",
"::",
"GzipWriter",
".",
"new",
"(",
"f",
")",
"gz",
".",
"write",
"(",
"self",
".",
"render",
")",
"gz",
".",
"close",
"end",
"end",
"end"
] | Render XML sitemap into the file
path - Output filename
options - Options hash
options[:overwrite] - Overwrite the file contents (default: true)
options[:gzip] - Gzip file contents (default: false) | [
"Render",
"XML",
"sitemap",
"into",
"the",
"file"
] | a9b510d49297d219c5b19a9c778cb8c6f0f1ae16 | https://github.com/sosedoff/xml-sitemap/blob/a9b510d49297d219c5b19a9c778cb8c6f0f1ae16/lib/xml-sitemap/map.rb#L118-L138 | train |
sosedoff/xml-sitemap | lib/xml-sitemap/map.rb | XmlSitemap.Map.process_target | def process_target(str)
if @root == true
url(str =~ /^\// ? str : "/#{str}")
else
str =~ /^(http|https)/i ? str : url(str =~ /^\// ? str : "/#{str}")
end
end | ruby | def process_target(str)
if @root == true
url(str =~ /^\// ? str : "/#{str}")
else
str =~ /^(http|https)/i ? str : url(str =~ /^\// ? str : "/#{str}")
end
end | [
"def",
"process_target",
"(",
"str",
")",
"if",
"@root",
"==",
"true",
"url",
"(",
"str",
"=~",
"/",
"\\/",
"/",
"?",
"str",
":",
"\"/#{str}\"",
")",
"else",
"str",
"=~",
"/",
"/i",
"?",
"str",
":",
"url",
"(",
"str",
"=~",
"/",
"\\/",
"/",
"?",
"str",
":",
"\"/#{str}\"",
")",
"end",
"end"
] | Process target path or url | [
"Process",
"target",
"path",
"or",
"url"
] | a9b510d49297d219c5b19a9c778cb8c6f0f1ae16 | https://github.com/sosedoff/xml-sitemap/blob/a9b510d49297d219c5b19a9c778cb8c6f0f1ae16/lib/xml-sitemap/map.rb#L144-L150 | train |
piotrmurach/lex | lib/lex/linter.rb | Lex.Linter.validate_tokens | def validate_tokens(lexer)
if lexer.lex_tokens.empty?
complain("No token list defined")
end
if !lexer.lex_tokens.respond_to?(:to_ary)
complain("Tokens must be a list or enumerable")
end
terminals = []
lexer.lex_tokens.each do |token|
if !identifier?(token)
complain("Bad token name `#{token}`")
end
if terminals.include?(token)
complain("Token `#{token}` already defined")
end
terminals << token
end
end | ruby | def validate_tokens(lexer)
if lexer.lex_tokens.empty?
complain("No token list defined")
end
if !lexer.lex_tokens.respond_to?(:to_ary)
complain("Tokens must be a list or enumerable")
end
terminals = []
lexer.lex_tokens.each do |token|
if !identifier?(token)
complain("Bad token name `#{token}`")
end
if terminals.include?(token)
complain("Token `#{token}` already defined")
end
terminals << token
end
end | [
"def",
"validate_tokens",
"(",
"lexer",
")",
"if",
"lexer",
".",
"lex_tokens",
".",
"empty?",
"complain",
"(",
"\"No token list defined\"",
")",
"end",
"if",
"!",
"lexer",
".",
"lex_tokens",
".",
"respond_to?",
"(",
":to_ary",
")",
"complain",
"(",
"\"Tokens must be a list or enumerable\"",
")",
"end",
"terminals",
"=",
"[",
"]",
"lexer",
".",
"lex_tokens",
".",
"each",
"do",
"|",
"token",
"|",
"if",
"!",
"identifier?",
"(",
"token",
")",
"complain",
"(",
"\"Bad token name `#{token}`\"",
")",
"end",
"if",
"terminals",
".",
"include?",
"(",
"token",
")",
"complain",
"(",
"\"Token `#{token}` already defined\"",
")",
"end",
"terminals",
"<<",
"token",
"end",
"end"
] | Validate provided tokens
@api private | [
"Validate",
"provided",
"tokens"
] | 28460ecafb8b92cf9a31e821f9f088c8f7573665 | https://github.com/piotrmurach/lex/blob/28460ecafb8b92cf9a31e821f9f088c8f7573665/lib/lex/linter.rb#L43-L61 | train |
piotrmurach/lex | lib/lex/linter.rb | Lex.Linter.validate_states | def validate_states(lexer)
if !lexer.state_info.respond_to?(:each_pair)
complain("States must be defined as a hash")
end
lexer.state_info.each do |state_name, state_type|
if ![:inclusive, :exclusive].include?(state_type)
complain("State type for state #{state_name}" \
" must be :inclusive or :exclusive")
end
if state_type == :exclusive
if !lexer.state_error.key?(state_name)
lexer.logger.warn("No error rule is defined " \
"for exclusive state '#{state_name}'")
end
if !lexer.state_ignore.key?(state_name)
lexer.logger.warn("No ignore rule is defined " \
"for exclusive state '#{state_name}'")
end
end
end
end | ruby | def validate_states(lexer)
if !lexer.state_info.respond_to?(:each_pair)
complain("States must be defined as a hash")
end
lexer.state_info.each do |state_name, state_type|
if ![:inclusive, :exclusive].include?(state_type)
complain("State type for state #{state_name}" \
" must be :inclusive or :exclusive")
end
if state_type == :exclusive
if !lexer.state_error.key?(state_name)
lexer.logger.warn("No error rule is defined " \
"for exclusive state '#{state_name}'")
end
if !lexer.state_ignore.key?(state_name)
lexer.logger.warn("No ignore rule is defined " \
"for exclusive state '#{state_name}'")
end
end
end
end | [
"def",
"validate_states",
"(",
"lexer",
")",
"if",
"!",
"lexer",
".",
"state_info",
".",
"respond_to?",
"(",
":each_pair",
")",
"complain",
"(",
"\"States must be defined as a hash\"",
")",
"end",
"lexer",
".",
"state_info",
".",
"each",
"do",
"|",
"state_name",
",",
"state_type",
"|",
"if",
"!",
"[",
":inclusive",
",",
":exclusive",
"]",
".",
"include?",
"(",
"state_type",
")",
"complain",
"(",
"\"State type for state #{state_name}\"",
"\" must be :inclusive or :exclusive\"",
")",
"end",
"if",
"state_type",
"==",
":exclusive",
"if",
"!",
"lexer",
".",
"state_error",
".",
"key?",
"(",
"state_name",
")",
"lexer",
".",
"logger",
".",
"warn",
"(",
"\"No error rule is defined \"",
"\"for exclusive state '#{state_name}'\"",
")",
"end",
"if",
"!",
"lexer",
".",
"state_ignore",
".",
"key?",
"(",
"state_name",
")",
"lexer",
".",
"logger",
".",
"warn",
"(",
"\"No ignore rule is defined \"",
"\"for exclusive state '#{state_name}'\"",
")",
"end",
"end",
"end",
"end"
] | Validate provided state names
@api private | [
"Validate",
"provided",
"state",
"names"
] | 28460ecafb8b92cf9a31e821f9f088c8f7573665 | https://github.com/piotrmurach/lex/blob/28460ecafb8b92cf9a31e821f9f088c8f7573665/lib/lex/linter.rb#L66-L88 | train |
Wardrop/Scorched | lib/scorched/response.rb | Scorched.Response.body= | def body=(value)
value = [] if !value || value == ''
super(value.respond_to?(:each) ? value : [value.to_s])
end | ruby | def body=(value)
value = [] if !value || value == ''
super(value.respond_to?(:each) ? value : [value.to_s])
end | [
"def",
"body",
"=",
"(",
"value",
")",
"value",
"=",
"[",
"]",
"if",
"!",
"value",
"||",
"value",
"==",
"''",
"super",
"(",
"value",
".",
"respond_to?",
"(",
":each",
")",
"?",
"value",
":",
"[",
"value",
".",
"to_s",
"]",
")",
"end"
] | Automatically wraps the assigned value in an array if it doesn't respond to ``each``.
Also filters out non-true values and empty strings. | [
"Automatically",
"wraps",
"the",
"assigned",
"value",
"in",
"an",
"array",
"if",
"it",
"doesn",
"t",
"respond",
"to",
"each",
".",
"Also",
"filters",
"out",
"non",
"-",
"true",
"values",
"and",
"empty",
"strings",
"."
] | 0833a6f9ed9ff42976577e5bbe5f23b7323eacb5 | https://github.com/Wardrop/Scorched/blob/0833a6f9ed9ff42976577e5bbe5f23b7323eacb5/lib/scorched/response.rb#L17-L20 | train |
Wardrop/Scorched | lib/scorched/response.rb | Scorched.Response.finish | def finish(*args, &block)
self['Content-Type'] ||= 'text/html;charset=utf-8'
@block = block if block
if [204, 205, 304].include?(status.to_i)
header.delete "Content-Type"
header.delete "Content-Length"
close
[status.to_i, header, []]
else
[status.to_i, header, body]
end
end | ruby | def finish(*args, &block)
self['Content-Type'] ||= 'text/html;charset=utf-8'
@block = block if block
if [204, 205, 304].include?(status.to_i)
header.delete "Content-Type"
header.delete "Content-Length"
close
[status.to_i, header, []]
else
[status.to_i, header, body]
end
end | [
"def",
"finish",
"(",
"*",
"args",
",",
"&",
"block",
")",
"self",
"[",
"'Content-Type'",
"]",
"||=",
"'text/html;charset=utf-8'",
"@block",
"=",
"block",
"if",
"block",
"if",
"[",
"204",
",",
"205",
",",
"304",
"]",
".",
"include?",
"(",
"status",
".",
"to_i",
")",
"header",
".",
"delete",
"\"Content-Type\"",
"header",
".",
"delete",
"\"Content-Length\"",
"close",
"[",
"status",
".",
"to_i",
",",
"header",
",",
"[",
"]",
"]",
"else",
"[",
"status",
".",
"to_i",
",",
"header",
",",
"body",
"]",
"end",
"end"
] | Override finish to avoid using BodyProxy | [
"Override",
"finish",
"to",
"avoid",
"using",
"BodyProxy"
] | 0833a6f9ed9ff42976577e5bbe5f23b7323eacb5 | https://github.com/Wardrop/Scorched/blob/0833a6f9ed9ff42976577e5bbe5f23b7323eacb5/lib/scorched/response.rb#L23-L34 | train |
Wardrop/Scorched | lib/scorched/controller.rb | Scorched.Controller.try_matches | def try_matches
eligable_matches.each do |match,idx|
request.breadcrumb << match
catch(:pass) {
dispatch(match)
return true
}
request.breadcrumb.pop # Current match passed, so pop the breadcrumb before the next iteration.
end
response.status = (!matches.empty? && eligable_matches.empty?) ? 403 : 404
end | ruby | def try_matches
eligable_matches.each do |match,idx|
request.breadcrumb << match
catch(:pass) {
dispatch(match)
return true
}
request.breadcrumb.pop # Current match passed, so pop the breadcrumb before the next iteration.
end
response.status = (!matches.empty? && eligable_matches.empty?) ? 403 : 404
end | [
"def",
"try_matches",
"eligable_matches",
".",
"each",
"do",
"|",
"match",
",",
"idx",
"|",
"request",
".",
"breadcrumb",
"<<",
"match",
"catch",
"(",
":pass",
")",
"{",
"dispatch",
"(",
"match",
")",
"return",
"true",
"}",
"request",
".",
"breadcrumb",
".",
"pop",
"end",
"response",
".",
"status",
"=",
"(",
"!",
"matches",
".",
"empty?",
"&&",
"eligable_matches",
".",
"empty?",
")",
"?",
"403",
":",
"404",
"end"
] | Tries to dispatch to each eligable match. If the first match _passes_, tries the second match and so on.
If there are no eligable matches, or all eligable matches pass, an appropriate 4xx response status is set. | [
"Tries",
"to",
"dispatch",
"to",
"each",
"eligable",
"match",
".",
"If",
"the",
"first",
"match",
"_passes_",
"tries",
"the",
"second",
"match",
"and",
"so",
"on",
".",
"If",
"there",
"are",
"no",
"eligable",
"matches",
"or",
"all",
"eligable",
"matches",
"pass",
"an",
"appropriate",
"4xx",
"response",
"status",
"is",
"set",
"."
] | 0833a6f9ed9ff42976577e5bbe5f23b7323eacb5 | https://github.com/Wardrop/Scorched/blob/0833a6f9ed9ff42976577e5bbe5f23b7323eacb5/lib/scorched/controller.rb#L315-L325 | train |
Wardrop/Scorched | lib/scorched/controller.rb | Scorched.Controller.dispatch | def dispatch(match)
@_dispatched = true
target = match.mapping[:target]
response.merge! begin
if Proc === target
instance_exec(&target)
else
target.call(env.merge(
'SCRIPT_NAME' => request.matched_path.chomp('/'),
'PATH_INFO' => request.unmatched_path[match.path.chomp('/').length..-1]
))
end
end
end | ruby | def dispatch(match)
@_dispatched = true
target = match.mapping[:target]
response.merge! begin
if Proc === target
instance_exec(&target)
else
target.call(env.merge(
'SCRIPT_NAME' => request.matched_path.chomp('/'),
'PATH_INFO' => request.unmatched_path[match.path.chomp('/').length..-1]
))
end
end
end | [
"def",
"dispatch",
"(",
"match",
")",
"@_dispatched",
"=",
"true",
"target",
"=",
"match",
".",
"mapping",
"[",
":target",
"]",
"response",
".",
"merge!",
"begin",
"if",
"Proc",
"===",
"target",
"instance_exec",
"(",
"&",
"target",
")",
"else",
"target",
".",
"call",
"(",
"env",
".",
"merge",
"(",
"'SCRIPT_NAME'",
"=>",
"request",
".",
"matched_path",
".",
"chomp",
"(",
"'/'",
")",
",",
"'PATH_INFO'",
"=>",
"request",
".",
"unmatched_path",
"[",
"match",
".",
"path",
".",
"chomp",
"(",
"'/'",
")",
".",
"length",
"..",
"-",
"1",
"]",
")",
")",
"end",
"end",
"end"
] | Dispatches the request to the matched target.
Overriding this method provides the opportunity for one to have more control over how mapping targets are invoked. | [
"Dispatches",
"the",
"request",
"to",
"the",
"matched",
"target",
".",
"Overriding",
"this",
"method",
"provides",
"the",
"opportunity",
"for",
"one",
"to",
"have",
"more",
"control",
"over",
"how",
"mapping",
"targets",
"are",
"invoked",
"."
] | 0833a6f9ed9ff42976577e5bbe5f23b7323eacb5 | https://github.com/Wardrop/Scorched/blob/0833a6f9ed9ff42976577e5bbe5f23b7323eacb5/lib/scorched/controller.rb#L329-L342 | train |
Wardrop/Scorched | lib/scorched/controller.rb | Scorched.Controller.matches | def matches
@_matches ||= begin
to_match = request.unmatched_path
to_match = to_match.chomp('/') if config[:strip_trailing_slash] == :ignore && to_match =~ %r{./$}
mappings.map { |mapping|
mapping[:pattern].match(to_match) do |match_data|
if match_data.pre_match == ''
if match_data.names.empty?
captures = match_data.captures
else
captures = Hash[match_data.names.map {|v| v.to_sym}.zip(match_data.captures)]
captures.each do |k,v|
captures[k] = symbol_matchers[k][1].call(v) if Array === symbol_matchers[k]
end
end
Match.new(mapping, captures, match_data.to_s, check_for_failed_condition(mapping[:conditions]))
end
end
}.compact
end
end | ruby | def matches
@_matches ||= begin
to_match = request.unmatched_path
to_match = to_match.chomp('/') if config[:strip_trailing_slash] == :ignore && to_match =~ %r{./$}
mappings.map { |mapping|
mapping[:pattern].match(to_match) do |match_data|
if match_data.pre_match == ''
if match_data.names.empty?
captures = match_data.captures
else
captures = Hash[match_data.names.map {|v| v.to_sym}.zip(match_data.captures)]
captures.each do |k,v|
captures[k] = symbol_matchers[k][1].call(v) if Array === symbol_matchers[k]
end
end
Match.new(mapping, captures, match_data.to_s, check_for_failed_condition(mapping[:conditions]))
end
end
}.compact
end
end | [
"def",
"matches",
"@_matches",
"||=",
"begin",
"to_match",
"=",
"request",
".",
"unmatched_path",
"to_match",
"=",
"to_match",
".",
"chomp",
"(",
"'/'",
")",
"if",
"config",
"[",
":strip_trailing_slash",
"]",
"==",
":ignore",
"&&",
"to_match",
"=~",
"%r{",
"}",
"mappings",
".",
"map",
"{",
"|",
"mapping",
"|",
"mapping",
"[",
":pattern",
"]",
".",
"match",
"(",
"to_match",
")",
"do",
"|",
"match_data",
"|",
"if",
"match_data",
".",
"pre_match",
"==",
"''",
"if",
"match_data",
".",
"names",
".",
"empty?",
"captures",
"=",
"match_data",
".",
"captures",
"else",
"captures",
"=",
"Hash",
"[",
"match_data",
".",
"names",
".",
"map",
"{",
"|",
"v",
"|",
"v",
".",
"to_sym",
"}",
".",
"zip",
"(",
"match_data",
".",
"captures",
")",
"]",
"captures",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"captures",
"[",
"k",
"]",
"=",
"symbol_matchers",
"[",
"k",
"]",
"[",
"1",
"]",
".",
"call",
"(",
"v",
")",
"if",
"Array",
"===",
"symbol_matchers",
"[",
"k",
"]",
"end",
"end",
"Match",
".",
"new",
"(",
"mapping",
",",
"captures",
",",
"match_data",
".",
"to_s",
",",
"check_for_failed_condition",
"(",
"mapping",
"[",
":conditions",
"]",
")",
")",
"end",
"end",
"}",
".",
"compact",
"end",
"end"
] | Finds mappings that match the unmatched portion of the request path, returning an array of `Match` objects, or an
empty array if no matches were found.
The `:eligable` attribute of the `Match` object indicates whether the conditions for that mapping passed.
The result is cached for the life time of the controller instance, for the sake of effecient recalling. | [
"Finds",
"mappings",
"that",
"match",
"the",
"unmatched",
"portion",
"of",
"the",
"request",
"path",
"returning",
"an",
"array",
"of",
"Match",
"objects",
"or",
"an",
"empty",
"array",
"if",
"no",
"matches",
"were",
"found",
"."
] | 0833a6f9ed9ff42976577e5bbe5f23b7323eacb5 | https://github.com/Wardrop/Scorched/blob/0833a6f9ed9ff42976577e5bbe5f23b7323eacb5/lib/scorched/controller.rb#L349-L369 | train |
Wardrop/Scorched | lib/scorched/controller.rb | Scorched.Controller.eligable_matches | def eligable_matches
@_eligable_matches ||= begin
matches.select { |m| m.failed_condition.nil? }.each_with_index.sort_by do |m,idx|
priority = m.mapping[:priority] || 0
media_type_rank = [*m.mapping[:conditions][:media_type]].map { |type|
env['scorched.accept'][:accept].rank(type, true)
}.max || 0
order = -idx
[priority, media_type_rank, order]
end.reverse
end
end | ruby | def eligable_matches
@_eligable_matches ||= begin
matches.select { |m| m.failed_condition.nil? }.each_with_index.sort_by do |m,idx|
priority = m.mapping[:priority] || 0
media_type_rank = [*m.mapping[:conditions][:media_type]].map { |type|
env['scorched.accept'][:accept].rank(type, true)
}.max || 0
order = -idx
[priority, media_type_rank, order]
end.reverse
end
end | [
"def",
"eligable_matches",
"@_eligable_matches",
"||=",
"begin",
"matches",
".",
"select",
"{",
"|",
"m",
"|",
"m",
".",
"failed_condition",
".",
"nil?",
"}",
".",
"each_with_index",
".",
"sort_by",
"do",
"|",
"m",
",",
"idx",
"|",
"priority",
"=",
"m",
".",
"mapping",
"[",
":priority",
"]",
"||",
"0",
"media_type_rank",
"=",
"[",
"*",
"m",
".",
"mapping",
"[",
":conditions",
"]",
"[",
":media_type",
"]",
"]",
".",
"map",
"{",
"|",
"type",
"|",
"env",
"[",
"'scorched.accept'",
"]",
"[",
":accept",
"]",
".",
"rank",
"(",
"type",
",",
"true",
")",
"}",
".",
"max",
"||",
"0",
"order",
"=",
"-",
"idx",
"[",
"priority",
",",
"media_type_rank",
",",
"order",
"]",
"end",
".",
"reverse",
"end",
"end"
] | Returns an ordered list of eligable matches.
Orders matches based on media_type, ensuring priority and definition order are respected appropriately.
Sorts by mapping priority first, media type appropriateness second, and definition order third. | [
"Returns",
"an",
"ordered",
"list",
"of",
"eligable",
"matches",
".",
"Orders",
"matches",
"based",
"on",
"media_type",
"ensuring",
"priority",
"and",
"definition",
"order",
"are",
"respected",
"appropriately",
".",
"Sorts",
"by",
"mapping",
"priority",
"first",
"media",
"type",
"appropriateness",
"second",
"and",
"definition",
"order",
"third",
"."
] | 0833a6f9ed9ff42976577e5bbe5f23b7323eacb5 | https://github.com/Wardrop/Scorched/blob/0833a6f9ed9ff42976577e5bbe5f23b7323eacb5/lib/scorched/controller.rb#L374-L385 | train |
Wardrop/Scorched | lib/scorched/controller.rb | Scorched.Controller.check_for_failed_condition | def check_for_failed_condition(conds)
failed = (conds || []).find { |c, v| !check_condition?(c, v) }
if failed
failed[0] = failed[0][0..-2].to_sym if failed[0][-1] == '!'
end
failed
end | ruby | def check_for_failed_condition(conds)
failed = (conds || []).find { |c, v| !check_condition?(c, v) }
if failed
failed[0] = failed[0][0..-2].to_sym if failed[0][-1] == '!'
end
failed
end | [
"def",
"check_for_failed_condition",
"(",
"conds",
")",
"failed",
"=",
"(",
"conds",
"||",
"[",
"]",
")",
".",
"find",
"{",
"|",
"c",
",",
"v",
"|",
"!",
"check_condition?",
"(",
"c",
",",
"v",
")",
"}",
"if",
"failed",
"failed",
"[",
"0",
"]",
"=",
"failed",
"[",
"0",
"]",
"[",
"0",
"..",
"-",
"2",
"]",
".",
"to_sym",
"if",
"failed",
"[",
"0",
"]",
"[",
"-",
"1",
"]",
"==",
"'!'",
"end",
"failed",
"end"
] | Tests the given conditions, returning the name of the first failed condition, or nil otherwise. | [
"Tests",
"the",
"given",
"conditions",
"returning",
"the",
"name",
"of",
"the",
"first",
"failed",
"condition",
"or",
"nil",
"otherwise",
"."
] | 0833a6f9ed9ff42976577e5bbe5f23b7323eacb5 | https://github.com/Wardrop/Scorched/blob/0833a6f9ed9ff42976577e5bbe5f23b7323eacb5/lib/scorched/controller.rb#L388-L394 | train |
Wardrop/Scorched | lib/scorched/controller.rb | Scorched.Controller.check_condition? | def check_condition?(c, v)
c = c[0..-2].to_sym if invert = (c[-1] == '!')
raise Error, "The condition `#{c}` either does not exist, or is not an instance of Proc" unless Proc === self.conditions[c]
retval = instance_exec(v, &self.conditions[c])
invert ? !retval : !!retval
end | ruby | def check_condition?(c, v)
c = c[0..-2].to_sym if invert = (c[-1] == '!')
raise Error, "The condition `#{c}` either does not exist, or is not an instance of Proc" unless Proc === self.conditions[c]
retval = instance_exec(v, &self.conditions[c])
invert ? !retval : !!retval
end | [
"def",
"check_condition?",
"(",
"c",
",",
"v",
")",
"c",
"=",
"c",
"[",
"0",
"..",
"-",
"2",
"]",
".",
"to_sym",
"if",
"invert",
"=",
"(",
"c",
"[",
"-",
"1",
"]",
"==",
"'!'",
")",
"raise",
"Error",
",",
"\"The condition `#{c}` either does not exist, or is not an instance of Proc\"",
"unless",
"Proc",
"===",
"self",
".",
"conditions",
"[",
"c",
"]",
"retval",
"=",
"instance_exec",
"(",
"v",
",",
"&",
"self",
".",
"conditions",
"[",
"c",
"]",
")",
"invert",
"?",
"!",
"retval",
":",
"!",
"!",
"retval",
"end"
] | Test the given condition, returning true if the condition passes, or false otherwise. | [
"Test",
"the",
"given",
"condition",
"returning",
"true",
"if",
"the",
"condition",
"passes",
"or",
"false",
"otherwise",
"."
] | 0833a6f9ed9ff42976577e5bbe5f23b7323eacb5 | https://github.com/Wardrop/Scorched/blob/0833a6f9ed9ff42976577e5bbe5f23b7323eacb5/lib/scorched/controller.rb#L397-L402 | train |
Wardrop/Scorched | lib/scorched/controller.rb | Scorched.Controller.redirect | def redirect(url, status: (env['HTTP_VERSION'] == 'HTTP/1.1') ? 303 : 302, halt: true)
response['Location'] = absolute(url)
response.status = status
self.halt if halt
end | ruby | def redirect(url, status: (env['HTTP_VERSION'] == 'HTTP/1.1') ? 303 : 302, halt: true)
response['Location'] = absolute(url)
response.status = status
self.halt if halt
end | [
"def",
"redirect",
"(",
"url",
",",
"status",
":",
"(",
"env",
"[",
"'HTTP_VERSION'",
"]",
"==",
"'HTTP/1.1'",
")",
"?",
"303",
":",
"302",
",",
"halt",
":",
"true",
")",
"response",
"[",
"'Location'",
"]",
"=",
"absolute",
"(",
"url",
")",
"response",
".",
"status",
"=",
"status",
"self",
".",
"halt",
"if",
"halt",
"end"
] | Redirects to the specified path or URL. An optional HTTP status is also accepted. | [
"Redirects",
"to",
"the",
"specified",
"path",
"or",
"URL",
".",
"An",
"optional",
"HTTP",
"status",
"is",
"also",
"accepted",
"."
] | 0833a6f9ed9ff42976577e5bbe5f23b7323eacb5 | https://github.com/Wardrop/Scorched/blob/0833a6f9ed9ff42976577e5bbe5f23b7323eacb5/lib/scorched/controller.rb#L405-L409 | train |
Wardrop/Scorched | lib/scorched/controller.rb | Scorched.Controller.flash | def flash(key = :flash)
raise Error, "Flash session data cannot be used without a valid Rack session" unless session
flash_hash = env['scorched.flash'] ||= {}
flash_hash[key] ||= {}
session[key] ||= {}
unless session[key].methods(false).include? :[]=
session[key].define_singleton_method(:[]=) do |k, v|
flash_hash[key][k] = v
end
end
session[key]
end | ruby | def flash(key = :flash)
raise Error, "Flash session data cannot be used without a valid Rack session" unless session
flash_hash = env['scorched.flash'] ||= {}
flash_hash[key] ||= {}
session[key] ||= {}
unless session[key].methods(false).include? :[]=
session[key].define_singleton_method(:[]=) do |k, v|
flash_hash[key][k] = v
end
end
session[key]
end | [
"def",
"flash",
"(",
"key",
"=",
":flash",
")",
"raise",
"Error",
",",
"\"Flash session data cannot be used without a valid Rack session\"",
"unless",
"session",
"flash_hash",
"=",
"env",
"[",
"'scorched.flash'",
"]",
"||=",
"{",
"}",
"flash_hash",
"[",
"key",
"]",
"||=",
"{",
"}",
"session",
"[",
"key",
"]",
"||=",
"{",
"}",
"unless",
"session",
"[",
"key",
"]",
".",
"methods",
"(",
"false",
")",
".",
"include?",
":[]=",
"session",
"[",
"key",
"]",
".",
"define_singleton_method",
"(",
":[]=",
")",
"do",
"|",
"k",
",",
"v",
"|",
"flash_hash",
"[",
"key",
"]",
"[",
"k",
"]",
"=",
"v",
"end",
"end",
"session",
"[",
"key",
"]",
"end"
] | Flash session storage helper.
Stores session data until the next time this method is called with the same arguments, at which point it's reset.
The typical use case is to provide feedback to the user on the previous action they performed. | [
"Flash",
"session",
"storage",
"helper",
".",
"Stores",
"session",
"data",
"until",
"the",
"next",
"time",
"this",
"method",
"is",
"called",
"with",
"the",
"same",
"arguments",
"at",
"which",
"point",
"it",
"s",
"reset",
".",
"The",
"typical",
"use",
"case",
"is",
"to",
"provide",
"feedback",
"to",
"the",
"user",
"on",
"the",
"previous",
"action",
"they",
"performed",
"."
] | 0833a6f9ed9ff42976577e5bbe5f23b7323eacb5 | https://github.com/Wardrop/Scorched/blob/0833a6f9ed9ff42976577e5bbe5f23b7323eacb5/lib/scorched/controller.rb#L440-L451 | train |
Wardrop/Scorched | lib/scorched/controller.rb | Scorched.Controller.run_filters | def run_filters(type)
halted = false
tracker = env['scorched.executed_filters'] ||= {before: Set.new, after: Set.new}
filters[type].reject { |f| tracker[type].include?(f) }.each do |f|
unless check_for_failed_condition(f[:conditions]) || (halted && !f[:force])
tracker[type] << f
halted = true unless run_filter(f)
end
end
!halted
end | ruby | def run_filters(type)
halted = false
tracker = env['scorched.executed_filters'] ||= {before: Set.new, after: Set.new}
filters[type].reject { |f| tracker[type].include?(f) }.each do |f|
unless check_for_failed_condition(f[:conditions]) || (halted && !f[:force])
tracker[type] << f
halted = true unless run_filter(f)
end
end
!halted
end | [
"def",
"run_filters",
"(",
"type",
")",
"halted",
"=",
"false",
"tracker",
"=",
"env",
"[",
"'scorched.executed_filters'",
"]",
"||=",
"{",
"before",
":",
"Set",
".",
"new",
",",
"after",
":",
"Set",
".",
"new",
"}",
"filters",
"[",
"type",
"]",
".",
"reject",
"{",
"|",
"f",
"|",
"tracker",
"[",
"type",
"]",
".",
"include?",
"(",
"f",
")",
"}",
".",
"each",
"do",
"|",
"f",
"|",
"unless",
"check_for_failed_condition",
"(",
"f",
"[",
":conditions",
"]",
")",
"||",
"(",
"halted",
"&&",
"!",
"f",
"[",
":force",
"]",
")",
"tracker",
"[",
"type",
"]",
"<<",
"f",
"halted",
"=",
"true",
"unless",
"run_filter",
"(",
"f",
")",
"end",
"end",
"!",
"halted",
"end"
] | Returns false if any of the filters halted the request. True otherwise. | [
"Returns",
"false",
"if",
"any",
"of",
"the",
"filters",
"halted",
"the",
"request",
".",
"True",
"otherwise",
"."
] | 0833a6f9ed9ff42976577e5bbe5f23b7323eacb5 | https://github.com/Wardrop/Scorched/blob/0833a6f9ed9ff42976577e5bbe5f23b7323eacb5/lib/scorched/controller.rb#L598-L608 | train |
Wardrop/Scorched | lib/scorched/request.rb | Scorched.Request.unescaped_path | def unescaped_path
path_info.split(/(%25|%2F)/i).each_slice(2).map { |v, m| URI.unescape(v) << (m || '') }.join('')
end | ruby | def unescaped_path
path_info.split(/(%25|%2F)/i).each_slice(2).map { |v, m| URI.unescape(v) << (m || '') }.join('')
end | [
"def",
"unescaped_path",
"path_info",
".",
"split",
"(",
"/",
"/i",
")",
".",
"each_slice",
"(",
"2",
")",
".",
"map",
"{",
"|",
"v",
",",
"m",
"|",
"URI",
".",
"unescape",
"(",
"v",
")",
"<<",
"(",
"m",
"||",
"''",
")",
"}",
".",
"join",
"(",
"''",
")",
"end"
] | The unescaped URL, excluding the escaped forward-slash and percent. The resulting string will always be safe
to unescape again in situations where the forward-slash or percent are expected and valid characters. | [
"The",
"unescaped",
"URL",
"excluding",
"the",
"escaped",
"forward",
"-",
"slash",
"and",
"percent",
".",
"The",
"resulting",
"string",
"will",
"always",
"be",
"safe",
"to",
"unescape",
"again",
"in",
"situations",
"where",
"the",
"forward",
"-",
"slash",
"or",
"percent",
"are",
"expected",
"and",
"valid",
"characters",
"."
] | 0833a6f9ed9ff42976577e5bbe5f23b7323eacb5 | https://github.com/Wardrop/Scorched/blob/0833a6f9ed9ff42976577e5bbe5f23b7323eacb5/lib/scorched/request.rb#L35-L37 | train |
softlayer/softlayer-ruby | lib/softlayer/Server.rb | SoftLayer.Server.reboot! | def reboot!(reboot_technique = :default_reboot)
case reboot_technique
when :default_reboot
self.service.rebootDefault
when :os_reboot
self.service.rebootSoft
when :power_cycle
self.service.rebootHard
else
raise ArgumentError, "Unrecognized reboot technique in SoftLayer::Server#reboot!}"
end
end | ruby | def reboot!(reboot_technique = :default_reboot)
case reboot_technique
when :default_reboot
self.service.rebootDefault
when :os_reboot
self.service.rebootSoft
when :power_cycle
self.service.rebootHard
else
raise ArgumentError, "Unrecognized reboot technique in SoftLayer::Server#reboot!}"
end
end | [
"def",
"reboot!",
"(",
"reboot_technique",
"=",
":default_reboot",
")",
"case",
"reboot_technique",
"when",
":default_reboot",
"self",
".",
"service",
".",
"rebootDefault",
"when",
":os_reboot",
"self",
".",
"service",
".",
"rebootSoft",
"when",
":power_cycle",
"self",
".",
"service",
".",
"rebootHard",
"else",
"raise",
"ArgumentError",
",",
"\"Unrecognized reboot technique in SoftLayer::Server#reboot!}\"",
"end",
"end"
] | Construct a server from the given client using the network data found in +network_hash+
Most users should not have to call this method directly. Instead you should access the
servers property of an Account object, or use methods like BareMetalServer#find_servers
or VirtualServer#find_servers
Reboot the server. This action is taken immediately.
Servers can be rebooted in three different ways:
:default_reboot - (Try soft, then hard) Attempts to reboot a server using the :os_reboot technique then, if that is not successful, tries the :power_cycle method
:os_reboot - (aka. soft reboot) instructs the server's host operating system to reboot
:power_cycle - (aka. hard reboot) The actual (for hardware) or metaphorical (for virtual servers) equivalent to pulling the plug on the server then plugging it back in. | [
"Construct",
"a",
"server",
"from",
"the",
"given",
"client",
"using",
"the",
"network",
"data",
"found",
"in",
"+",
"network_hash",
"+"
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/Server.rb#L174-L185 | train |
softlayer/softlayer-ruby | lib/softlayer/Server.rb | SoftLayer.Server.notes= | def notes=(new_notes)
raise ArgumentError, "The new notes cannot be nil" unless new_notes
edit_template = {
"notes" => new_notes
}
self.service.editObject(edit_template)
self.refresh_details()
end | ruby | def notes=(new_notes)
raise ArgumentError, "The new notes cannot be nil" unless new_notes
edit_template = {
"notes" => new_notes
}
self.service.editObject(edit_template)
self.refresh_details()
end | [
"def",
"notes",
"=",
"(",
"new_notes",
")",
"raise",
"ArgumentError",
",",
"\"The new notes cannot be nil\"",
"unless",
"new_notes",
"edit_template",
"=",
"{",
"\"notes\"",
"=>",
"new_notes",
"}",
"self",
".",
"service",
".",
"editObject",
"(",
"edit_template",
")",
"self",
".",
"refresh_details",
"(",
")",
"end"
] | Change the notes of the server
raises ArgumentError if you pass nil as the notes | [
"Change",
"the",
"notes",
"of",
"the",
"server",
"raises",
"ArgumentError",
"if",
"you",
"pass",
"nil",
"as",
"the",
"notes"
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/Server.rb#L205-L214 | train |
softlayer/softlayer-ruby | lib/softlayer/Server.rb | SoftLayer.Server.set_hostname! | def set_hostname!(new_hostname)
raise ArgumentError, "The new hostname cannot be nil" unless new_hostname
raise ArgumentError, "The new hostname cannot be empty" if new_hostname.empty?
edit_template = {
"hostname" => new_hostname
}
self.service.editObject(edit_template)
self.refresh_details()
end | ruby | def set_hostname!(new_hostname)
raise ArgumentError, "The new hostname cannot be nil" unless new_hostname
raise ArgumentError, "The new hostname cannot be empty" if new_hostname.empty?
edit_template = {
"hostname" => new_hostname
}
self.service.editObject(edit_template)
self.refresh_details()
end | [
"def",
"set_hostname!",
"(",
"new_hostname",
")",
"raise",
"ArgumentError",
",",
"\"The new hostname cannot be nil\"",
"unless",
"new_hostname",
"raise",
"ArgumentError",
",",
"\"The new hostname cannot be empty\"",
"if",
"new_hostname",
".",
"empty?",
"edit_template",
"=",
"{",
"\"hostname\"",
"=>",
"new_hostname",
"}",
"self",
".",
"service",
".",
"editObject",
"(",
"edit_template",
")",
"self",
".",
"refresh_details",
"(",
")",
"end"
] | Change the hostname of this server
Raises an ArgumentError if the new hostname is nil or empty | [
"Change",
"the",
"hostname",
"of",
"this",
"server",
"Raises",
"an",
"ArgumentError",
"if",
"the",
"new",
"hostname",
"is",
"nil",
"or",
"empty"
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/Server.rb#L229-L239 | train |
softlayer/softlayer-ruby | lib/softlayer/Server.rb | SoftLayer.Server.set_domain! | def set_domain!(new_domain)
raise ArgumentError, "The new hostname cannot be nil" unless new_domain
raise ArgumentError, "The new hostname cannot be empty" if new_domain.empty?
edit_template = {
"domain" => new_domain
}
self.service.editObject(edit_template)
self.refresh_details()
end | ruby | def set_domain!(new_domain)
raise ArgumentError, "The new hostname cannot be nil" unless new_domain
raise ArgumentError, "The new hostname cannot be empty" if new_domain.empty?
edit_template = {
"domain" => new_domain
}
self.service.editObject(edit_template)
self.refresh_details()
end | [
"def",
"set_domain!",
"(",
"new_domain",
")",
"raise",
"ArgumentError",
",",
"\"The new hostname cannot be nil\"",
"unless",
"new_domain",
"raise",
"ArgumentError",
",",
"\"The new hostname cannot be empty\"",
"if",
"new_domain",
".",
"empty?",
"edit_template",
"=",
"{",
"\"domain\"",
"=>",
"new_domain",
"}",
"self",
".",
"service",
".",
"editObject",
"(",
"edit_template",
")",
"self",
".",
"refresh_details",
"(",
")",
"end"
] | Change the domain of this server
Raises an ArgumentError if the new domain is nil or empty
no further validation is done on the domain name | [
"Change",
"the",
"domain",
"of",
"this",
"server"
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/Server.rb#L247-L257 | train |
softlayer/softlayer-ruby | lib/softlayer/Server.rb | SoftLayer.Server.change_port_speed | def change_port_speed(new_speed, public = true)
if public
self.service.setPublicNetworkInterfaceSpeed(new_speed)
else
self.service.setPrivateNetworkInterfaceSpeed(new_speed)
end
self.refresh_details()
self
end | ruby | def change_port_speed(new_speed, public = true)
if public
self.service.setPublicNetworkInterfaceSpeed(new_speed)
else
self.service.setPrivateNetworkInterfaceSpeed(new_speed)
end
self.refresh_details()
self
end | [
"def",
"change_port_speed",
"(",
"new_speed",
",",
"public",
"=",
"true",
")",
"if",
"public",
"self",
".",
"service",
".",
"setPublicNetworkInterfaceSpeed",
"(",
"new_speed",
")",
"else",
"self",
".",
"service",
".",
"setPrivateNetworkInterfaceSpeed",
"(",
"new_speed",
")",
"end",
"self",
".",
"refresh_details",
"(",
")",
"self",
"end"
] | Change the current port speed of the server
+new_speed+ is expressed Mbps and should be 0, 10, 100, or 1000.
Ports have a maximum speed that will limit the actual speed set
on the port.
Set +public+ to +false+ in order to change the speed of the
private network interface. | [
"Change",
"the",
"current",
"port",
"speed",
"of",
"the",
"server"
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/Server.rb#L278-L287 | train |
softlayer/softlayer-ruby | lib/softlayer/Server.rb | SoftLayer.Server.reload_os! | def reload_os!(token = '', provisioning_script_uri = nil, ssh_keys = nil)
configuration = {}
configuration['customProvisionScriptUri'] = provisioning_script_uri if provisioning_script_uri
configuration['sshKeyIds'] = ssh_keys if ssh_keys
self.service.reloadOperatingSystem(token, configuration)
end | ruby | def reload_os!(token = '', provisioning_script_uri = nil, ssh_keys = nil)
configuration = {}
configuration['customProvisionScriptUri'] = provisioning_script_uri if provisioning_script_uri
configuration['sshKeyIds'] = ssh_keys if ssh_keys
self.service.reloadOperatingSystem(token, configuration)
end | [
"def",
"reload_os!",
"(",
"token",
"=",
"''",
",",
"provisioning_script_uri",
"=",
"nil",
",",
"ssh_keys",
"=",
"nil",
")",
"configuration",
"=",
"{",
"}",
"configuration",
"[",
"'customProvisionScriptUri'",
"]",
"=",
"provisioning_script_uri",
"if",
"provisioning_script_uri",
"configuration",
"[",
"'sshKeyIds'",
"]",
"=",
"ssh_keys",
"if",
"ssh_keys",
"self",
".",
"service",
".",
"reloadOperatingSystem",
"(",
"token",
",",
"configuration",
")",
"end"
] | Begins an OS reload on this server.
The OS reload can wipe out the data on your server so this method uses a
confirmation mechanism built into the underlying SoftLayer API. If you
call this method once without a token, it will not actually start the
reload. Instead it will return a token to you. That token is good for
10 minutes. If you call this method again and pass that token **then**
the OS reload will actually begin.
If you wish to force the OS Reload and bypass the token safety mechanism
pass the token 'FORCE' as the first parameter. If you do so
the reload will proceed immediately. | [
"Begins",
"an",
"OS",
"reload",
"on",
"this",
"server",
"."
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/Server.rb#L303-L310 | train |
drone/drone-ruby | lib/drone/plugin.rb | Drone.Plugin.parse | def parse
self.result ||= Payload.new.tap do |payload|
PayloadRepresenter.new(
payload
).from_json(
input
)
end
rescue MultiJson::ParseError
raise InvalidJsonError
end | ruby | def parse
self.result ||= Payload.new.tap do |payload|
PayloadRepresenter.new(
payload
).from_json(
input
)
end
rescue MultiJson::ParseError
raise InvalidJsonError
end | [
"def",
"parse",
"self",
".",
"result",
"||=",
"Payload",
".",
"new",
".",
"tap",
"do",
"|",
"payload",
"|",
"PayloadRepresenter",
".",
"new",
"(",
"payload",
")",
".",
"from_json",
"(",
"input",
")",
"end",
"rescue",
"MultiJson",
"::",
"ParseError",
"raise",
"InvalidJsonError",
"end"
] | Initialize the plugin parser
@param input [String] the JSON as a string to parse
@return [Drone::Plugin] the instance of that class
Parse the provided payload
@return [Drone::Payload] the parsed payload within model
@raise [Drone::InvalidJsonError] if the provided JSON is invalid | [
"Initialize",
"the",
"plugin",
"parser"
] | 4b95286c45a9c44f2e38c393b804f753fb286b50 | https://github.com/drone/drone-ruby/blob/4b95286c45a9c44f2e38c393b804f753fb286b50/lib/drone/plugin.rb#L43-L53 | train |
softlayer/softlayer-ruby | lib/softlayer/APIParameterFilter.rb | SoftLayer.APIParameterFilter.object_filter | def object_filter(filter)
raise ArgumentError, "object_filter expects an instance of SoftLayer::ObjectFilter" if filter.nil? || !filter.kind_of?(SoftLayer::ObjectFilter)
# we create a new object in case the user wants to store off the
# filter chain and reuse it later
APIParameterFilter.new(self.target, @parameters.merge({:object_filter => filter}));
end | ruby | def object_filter(filter)
raise ArgumentError, "object_filter expects an instance of SoftLayer::ObjectFilter" if filter.nil? || !filter.kind_of?(SoftLayer::ObjectFilter)
# we create a new object in case the user wants to store off the
# filter chain and reuse it later
APIParameterFilter.new(self.target, @parameters.merge({:object_filter => filter}));
end | [
"def",
"object_filter",
"(",
"filter",
")",
"raise",
"ArgumentError",
",",
"\"object_filter expects an instance of SoftLayer::ObjectFilter\"",
"if",
"filter",
".",
"nil?",
"||",
"!",
"filter",
".",
"kind_of?",
"(",
"SoftLayer",
"::",
"ObjectFilter",
")",
"APIParameterFilter",
".",
"new",
"(",
"self",
".",
"target",
",",
"@parameters",
".",
"merge",
"(",
"{",
":object_filter",
"=>",
"filter",
"}",
")",
")",
";",
"end"
] | Adds an object_filter to the result. An Object Filter allows you
to specify criteria which are used to filter the results returned
by the server. | [
"Adds",
"an",
"object_filter",
"to",
"the",
"result",
".",
"An",
"Object",
"Filter",
"allows",
"you",
"to",
"specify",
"criteria",
"which",
"are",
"used",
"to",
"filter",
"the",
"results",
"returned",
"by",
"the",
"server",
"."
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/APIParameterFilter.rb#L114-L120 | train |
softlayer/softlayer-ruby | lib/softlayer/VirtualServerUpgradeOrder.rb | SoftLayer.VirtualServerUpgradeOrder.verify | def verify()
if has_order_items?
order_template = order_object
order_template = yield order_object if block_given?
@virtual_server.softlayer_client[:Product_Order].verifyOrder(order_template)
end
end | ruby | def verify()
if has_order_items?
order_template = order_object
order_template = yield order_object if block_given?
@virtual_server.softlayer_client[:Product_Order].verifyOrder(order_template)
end
end | [
"def",
"verify",
"(",
")",
"if",
"has_order_items?",
"order_template",
"=",
"order_object",
"order_template",
"=",
"yield",
"order_object",
"if",
"block_given?",
"@virtual_server",
".",
"softlayer_client",
"[",
":Product_Order",
"]",
".",
"verifyOrder",
"(",
"order_template",
")",
"end",
"end"
] | Create an upgrade order for the virtual server provided.
Sends the order represented by this object to SoftLayer for validation.
If a block is passed to verify, the code will send the order template
being constructed to the block before the order is actually sent for
validation. | [
"Create",
"an",
"upgrade",
"order",
"for",
"the",
"virtual",
"server",
"provided",
"."
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/VirtualServerUpgradeOrder.rb#L52-L58 | train |
softlayer/softlayer-ruby | lib/softlayer/VirtualServerUpgradeOrder.rb | SoftLayer.VirtualServerUpgradeOrder.place_order! | def place_order!()
if has_order_items?
order_template = order_object
order_template = yield order_object if block_given?
@virtual_server.softlayer_client[:Product_Order].placeOrder(order_template)
end
end | ruby | def place_order!()
if has_order_items?
order_template = order_object
order_template = yield order_object if block_given?
@virtual_server.softlayer_client[:Product_Order].placeOrder(order_template)
end
end | [
"def",
"place_order!",
"(",
")",
"if",
"has_order_items?",
"order_template",
"=",
"order_object",
"order_template",
"=",
"yield",
"order_object",
"if",
"block_given?",
"@virtual_server",
".",
"softlayer_client",
"[",
":Product_Order",
"]",
".",
"placeOrder",
"(",
"order_template",
")",
"end",
"end"
] | Places the order represented by this object. This is likely to
involve a change to the charges on an account.
If a block is passed to this routine, the code will send the order template
being constructed to that block before the order is sent | [
"Places",
"the",
"order",
"represented",
"by",
"this",
"object",
".",
"This",
"is",
"likely",
"to",
"involve",
"a",
"change",
"to",
"the",
"charges",
"on",
"an",
"account",
"."
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/VirtualServerUpgradeOrder.rb#L67-L74 | train |
softlayer/softlayer-ruby | lib/softlayer/VirtualServerUpgradeOrder.rb | SoftLayer.VirtualServerUpgradeOrder._item_prices_in_category | def _item_prices_in_category(which_category)
@virtual_server.upgrade_options.select { |item_price| item_price['categories'].find { |category| category['categoryCode'] == which_category } }
end | ruby | def _item_prices_in_category(which_category)
@virtual_server.upgrade_options.select { |item_price| item_price['categories'].find { |category| category['categoryCode'] == which_category } }
end | [
"def",
"_item_prices_in_category",
"(",
"which_category",
")",
"@virtual_server",
".",
"upgrade_options",
".",
"select",
"{",
"|",
"item_price",
"|",
"item_price",
"[",
"'categories'",
"]",
".",
"find",
"{",
"|",
"category",
"|",
"category",
"[",
"'categoryCode'",
"]",
"==",
"which_category",
"}",
"}",
"end"
] | Returns a list of the update item prices, in the given category, for the server | [
"Returns",
"a",
"list",
"of",
"the",
"update",
"item",
"prices",
"in",
"the",
"given",
"category",
"for",
"the",
"server"
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/VirtualServerUpgradeOrder.rb#L106-L108 | train |
softlayer/softlayer-ruby | lib/softlayer/VirtualServerUpgradeOrder.rb | SoftLayer.VirtualServerUpgradeOrder._item_price_with_capacity | def _item_price_with_capacity(which_category, capacity)
_item_prices_in_category(which_category).find { |item_price| item_price['item']['capacity'].to_i == capacity}
end | ruby | def _item_price_with_capacity(which_category, capacity)
_item_prices_in_category(which_category).find { |item_price| item_price['item']['capacity'].to_i == capacity}
end | [
"def",
"_item_price_with_capacity",
"(",
"which_category",
",",
"capacity",
")",
"_item_prices_in_category",
"(",
"which_category",
")",
".",
"find",
"{",
"|",
"item_price",
"|",
"item_price",
"[",
"'item'",
"]",
"[",
"'capacity'",
"]",
".",
"to_i",
"==",
"capacity",
"}",
"end"
] | Searches through the upgrade items prices known to this server for the one that is in a particular category
and whose capacity matches the value given. Returns the item_price or nil | [
"Searches",
"through",
"the",
"upgrade",
"items",
"prices",
"known",
"to",
"this",
"server",
"for",
"the",
"one",
"that",
"is",
"in",
"a",
"particular",
"category",
"and",
"whose",
"capacity",
"matches",
"the",
"value",
"given",
".",
"Returns",
"the",
"item_price",
"or",
"nil"
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/VirtualServerUpgradeOrder.rb#L114-L116 | train |
softlayer/softlayer-ruby | lib/softlayer/VirtualServerUpgradeOrder.rb | SoftLayer.VirtualServerUpgradeOrder.order_object | def order_object
prices = []
cores_price_item = @cores ? _item_price_with_capacity("guest_core", @cores) : nil
ram_price_item = @ram ? _item_price_with_capacity("ram", @ram) : nil
max_port_speed_price_item = @max_port_speed ? _item_price_with_capacity("port_speed", @max_port_speed) : nil
prices << { "id" => cores_price_item['id'] } if cores_price_item
prices << { "id" => ram_price_item['id'] } if ram_price_item
prices << { "id" => max_port_speed_price_item['id'] } if max_port_speed_price_item
# put together an order
upgrade_order = {
'complexType' => 'SoftLayer_Container_Product_Order_Virtual_Guest_Upgrade',
'virtualGuests' => [{'id' => @virtual_server.id }],
'properties' => [{'name' => 'MAINTENANCE_WINDOW', 'value' => @upgrade_at ? @upgrade_at.iso8601 : Time.now.iso8601}],
'prices' => prices
}
end | ruby | def order_object
prices = []
cores_price_item = @cores ? _item_price_with_capacity("guest_core", @cores) : nil
ram_price_item = @ram ? _item_price_with_capacity("ram", @ram) : nil
max_port_speed_price_item = @max_port_speed ? _item_price_with_capacity("port_speed", @max_port_speed) : nil
prices << { "id" => cores_price_item['id'] } if cores_price_item
prices << { "id" => ram_price_item['id'] } if ram_price_item
prices << { "id" => max_port_speed_price_item['id'] } if max_port_speed_price_item
# put together an order
upgrade_order = {
'complexType' => 'SoftLayer_Container_Product_Order_Virtual_Guest_Upgrade',
'virtualGuests' => [{'id' => @virtual_server.id }],
'properties' => [{'name' => 'MAINTENANCE_WINDOW', 'value' => @upgrade_at ? @upgrade_at.iso8601 : Time.now.iso8601}],
'prices' => prices
}
end | [
"def",
"order_object",
"prices",
"=",
"[",
"]",
"cores_price_item",
"=",
"@cores",
"?",
"_item_price_with_capacity",
"(",
"\"guest_core\"",
",",
"@cores",
")",
":",
"nil",
"ram_price_item",
"=",
"@ram",
"?",
"_item_price_with_capacity",
"(",
"\"ram\"",
",",
"@ram",
")",
":",
"nil",
"max_port_speed_price_item",
"=",
"@max_port_speed",
"?",
"_item_price_with_capacity",
"(",
"\"port_speed\"",
",",
"@max_port_speed",
")",
":",
"nil",
"prices",
"<<",
"{",
"\"id\"",
"=>",
"cores_price_item",
"[",
"'id'",
"]",
"}",
"if",
"cores_price_item",
"prices",
"<<",
"{",
"\"id\"",
"=>",
"ram_price_item",
"[",
"'id'",
"]",
"}",
"if",
"ram_price_item",
"prices",
"<<",
"{",
"\"id\"",
"=>",
"max_port_speed_price_item",
"[",
"'id'",
"]",
"}",
"if",
"max_port_speed_price_item",
"upgrade_order",
"=",
"{",
"'complexType'",
"=>",
"'SoftLayer_Container_Product_Order_Virtual_Guest_Upgrade'",
",",
"'virtualGuests'",
"=>",
"[",
"{",
"'id'",
"=>",
"@virtual_server",
".",
"id",
"}",
"]",
",",
"'properties'",
"=>",
"[",
"{",
"'name'",
"=>",
"'MAINTENANCE_WINDOW'",
",",
"'value'",
"=>",
"@upgrade_at",
"?",
"@upgrade_at",
".",
"iso8601",
":",
"Time",
".",
"now",
".",
"iso8601",
"}",
"]",
",",
"'prices'",
"=>",
"prices",
"}",
"end"
] | construct an order object | [
"construct",
"an",
"order",
"object"
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/VirtualServerUpgradeOrder.rb#L121-L139 | train |
softlayer/softlayer-ruby | lib/softlayer/NetworkStorage.rb | SoftLayer.NetworkStorage.assign_credential | def assign_credential(username)
raise ArgumentError, "The username cannot be nil" unless username
raise ArgumentError, "The username cannot be empty" if username.empty?
self.service.assignCredential(username.to_s)
@credentials = nil
end | ruby | def assign_credential(username)
raise ArgumentError, "The username cannot be nil" unless username
raise ArgumentError, "The username cannot be empty" if username.empty?
self.service.assignCredential(username.to_s)
@credentials = nil
end | [
"def",
"assign_credential",
"(",
"username",
")",
"raise",
"ArgumentError",
",",
"\"The username cannot be nil\"",
"unless",
"username",
"raise",
"ArgumentError",
",",
"\"The username cannot be empty\"",
"if",
"username",
".",
"empty?",
"self",
".",
"service",
".",
"assignCredential",
"(",
"username",
".",
"to_s",
")",
"@credentials",
"=",
"nil",
"end"
] | Assign an existing network storage credential specified by the username to the network storage instance | [
"Assign",
"an",
"existing",
"network",
"storage",
"credential",
"specified",
"by",
"the",
"username",
"to",
"the",
"network",
"storage",
"instance"
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/NetworkStorage.rb#L141-L148 | train |
softlayer/softlayer-ruby | lib/softlayer/NetworkStorage.rb | SoftLayer.NetworkStorage.password= | def password=(password)
raise ArgumentError, "The new password cannot be nil" unless password
raise ArgumentError, "The new password cannot be empty" if password.empty?
self.service.editObject({ "password" => password.to_s })
self.refresh_details()
end | ruby | def password=(password)
raise ArgumentError, "The new password cannot be nil" unless password
raise ArgumentError, "The new password cannot be empty" if password.empty?
self.service.editObject({ "password" => password.to_s })
self.refresh_details()
end | [
"def",
"password",
"=",
"(",
"password",
")",
"raise",
"ArgumentError",
",",
"\"The new password cannot be nil\"",
"unless",
"password",
"raise",
"ArgumentError",
",",
"\"The new password cannot be empty\"",
"if",
"password",
".",
"empty?",
"self",
".",
"service",
".",
"editObject",
"(",
"{",
"\"password\"",
"=>",
"password",
".",
"to_s",
"}",
")",
"self",
".",
"refresh_details",
"(",
")",
"end"
] | Updates the password for the network storage instance. | [
"Updates",
"the",
"password",
"for",
"the",
"network",
"storage",
"instance",
"."
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/NetworkStorage.rb#L168-L174 | train |
softlayer/softlayer-ruby | lib/softlayer/NetworkStorage.rb | SoftLayer.NetworkStorage.remove_credential | def remove_credential(username)
raise ArgumentError, "The username cannot be nil" unless username
raise ArgumentError, "The username cannot be empty" if username.empty?
self.service.removeCredential(username.to_s)
@credentials = nil
end | ruby | def remove_credential(username)
raise ArgumentError, "The username cannot be nil" unless username
raise ArgumentError, "The username cannot be empty" if username.empty?
self.service.removeCredential(username.to_s)
@credentials = nil
end | [
"def",
"remove_credential",
"(",
"username",
")",
"raise",
"ArgumentError",
",",
"\"The username cannot be nil\"",
"unless",
"username",
"raise",
"ArgumentError",
",",
"\"The username cannot be empty\"",
"if",
"username",
".",
"empty?",
"self",
".",
"service",
".",
"removeCredential",
"(",
"username",
".",
"to_s",
")",
"@credentials",
"=",
"nil",
"end"
] | Remove an existing network storage credential specified by the username from the network storage instance | [
"Remove",
"an",
"existing",
"network",
"storage",
"credential",
"specified",
"by",
"the",
"username",
"from",
"the",
"network",
"storage",
"instance"
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/NetworkStorage.rb#L179-L186 | train |
softlayer/softlayer-ruby | lib/softlayer/NetworkStorage.rb | SoftLayer.NetworkStorage.softlayer_properties | def softlayer_properties(object_mask = nil)
my_service = self.service
if(object_mask)
my_service = my_service.object_mask(object_mask)
else
my_service = my_service.object_mask(self.class.default_object_mask)
end
my_service.getObject()
end | ruby | def softlayer_properties(object_mask = nil)
my_service = self.service
if(object_mask)
my_service = my_service.object_mask(object_mask)
else
my_service = my_service.object_mask(self.class.default_object_mask)
end
my_service.getObject()
end | [
"def",
"softlayer_properties",
"(",
"object_mask",
"=",
"nil",
")",
"my_service",
"=",
"self",
".",
"service",
"if",
"(",
"object_mask",
")",
"my_service",
"=",
"my_service",
".",
"object_mask",
"(",
"object_mask",
")",
"else",
"my_service",
"=",
"my_service",
".",
"object_mask",
"(",
"self",
".",
"class",
".",
"default_object_mask",
")",
"end",
"my_service",
".",
"getObject",
"(",
")",
"end"
] | Make an API request to SoftLayer and return the latest properties hash
for this object. | [
"Make",
"an",
"API",
"request",
"to",
"SoftLayer",
"and",
"return",
"the",
"latest",
"properties",
"hash",
"for",
"this",
"object",
"."
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/NetworkStorage.rb#L310-L320 | train |
softlayer/softlayer-ruby | lib/softlayer/NetworkStorage.rb | SoftLayer.NetworkStorage.update_credential_password | def update_credential_password(username, password)
raise ArgumentError, "The new password cannot be nil" unless password
raise ArgumentError, "The new username cannot be nil" unless username
raise ArgumentError, "The new password cannot be empty" if password.empty?
raise ArgumentError, "The new username cannot be empty" if username.empty?
self.service.editCredential(username.to_s, password.to_s)
@credentials = nil
end | ruby | def update_credential_password(username, password)
raise ArgumentError, "The new password cannot be nil" unless password
raise ArgumentError, "The new username cannot be nil" unless username
raise ArgumentError, "The new password cannot be empty" if password.empty?
raise ArgumentError, "The new username cannot be empty" if username.empty?
self.service.editCredential(username.to_s, password.to_s)
@credentials = nil
end | [
"def",
"update_credential_password",
"(",
"username",
",",
"password",
")",
"raise",
"ArgumentError",
",",
"\"The new password cannot be nil\"",
"unless",
"password",
"raise",
"ArgumentError",
",",
"\"The new username cannot be nil\"",
"unless",
"username",
"raise",
"ArgumentError",
",",
"\"The new password cannot be empty\"",
"if",
"password",
".",
"empty?",
"raise",
"ArgumentError",
",",
"\"The new username cannot be empty\"",
"if",
"username",
".",
"empty?",
"self",
".",
"service",
".",
"editCredential",
"(",
"username",
".",
"to_s",
",",
"password",
".",
"to_s",
")",
"@credentials",
"=",
"nil",
"end"
] | Updates the password for the network storage credential of the username specified. | [
"Updates",
"the",
"password",
"for",
"the",
"network",
"storage",
"credential",
"of",
"the",
"username",
"specified",
"."
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/NetworkStorage.rb#L325-L334 | train |
softlayer/softlayer-ruby | lib/softlayer/ProductPackage.rb | SoftLayer.ProductPackage.items_with_description | def items_with_description(expected_description)
filter = ObjectFilter.new { |filter| filter.accept("items.description").when_it is(expected_description) }
items_data = self.service.object_filter(filter).getItems()
items_data.collect do |item_data|
first_price = item_data['prices'][0]
ProductConfigurationOption.new(item_data, first_price)
end
end | ruby | def items_with_description(expected_description)
filter = ObjectFilter.new { |filter| filter.accept("items.description").when_it is(expected_description) }
items_data = self.service.object_filter(filter).getItems()
items_data.collect do |item_data|
first_price = item_data['prices'][0]
ProductConfigurationOption.new(item_data, first_price)
end
end | [
"def",
"items_with_description",
"(",
"expected_description",
")",
"filter",
"=",
"ObjectFilter",
".",
"new",
"{",
"|",
"filter",
"|",
"filter",
".",
"accept",
"(",
"\"items.description\"",
")",
".",
"when_it",
"is",
"(",
"expected_description",
")",
"}",
"items_data",
"=",
"self",
".",
"service",
".",
"object_filter",
"(",
"filter",
")",
".",
"getItems",
"(",
")",
"items_data",
".",
"collect",
"do",
"|",
"item_data",
"|",
"first_price",
"=",
"item_data",
"[",
"'prices'",
"]",
"[",
"0",
"]",
"ProductConfigurationOption",
".",
"new",
"(",
"item_data",
",",
"first_price",
")",
"end",
"end"
] | Returns the package items with the given description
Currently this is returning the low-level hash representation directly from the Network API | [
"Returns",
"the",
"package",
"items",
"with",
"the",
"given",
"description",
"Currently",
"this",
"is",
"returning",
"the",
"low",
"-",
"level",
"hash",
"representation",
"directly",
"from",
"the",
"Network",
"API"
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/ProductPackage.rb#L143-L151 | train |
softlayer/softlayer-ruby | lib/softlayer/ImageTemplate.rb | SoftLayer.ImageTemplate.available_datacenters | def available_datacenters
datacenters_data = self.service.getStorageLocations()
datacenters_data.collect { |datacenter_data| SoftLayer::Datacenter.datacenter_named(datacenter_data['name']) }
end | ruby | def available_datacenters
datacenters_data = self.service.getStorageLocations()
datacenters_data.collect { |datacenter_data| SoftLayer::Datacenter.datacenter_named(datacenter_data['name']) }
end | [
"def",
"available_datacenters",
"datacenters_data",
"=",
"self",
".",
"service",
".",
"getStorageLocations",
"(",
")",
"datacenters_data",
".",
"collect",
"{",
"|",
"datacenter_data",
"|",
"SoftLayer",
"::",
"Datacenter",
".",
"datacenter_named",
"(",
"datacenter_data",
"[",
"'name'",
"]",
")",
"}",
"end"
] | Returns an array of the datacenters that this image can be stored in.
This is the set of datacenters that you may choose from, when putting
together a list you will send to the datacenters= setter. | [
"Returns",
"an",
"array",
"of",
"the",
"datacenters",
"that",
"this",
"image",
"can",
"be",
"stored",
"in",
".",
"This",
"is",
"the",
"set",
"of",
"datacenters",
"that",
"you",
"may",
"choose",
"from",
"when",
"putting",
"together",
"a",
"list",
"you",
"will",
"send",
"to",
"the",
"datacenters",
"=",
"setter",
"."
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/ImageTemplate.rb#L110-L113 | train |
softlayer/softlayer-ruby | lib/softlayer/ImageTemplate.rb | SoftLayer.ImageTemplate.shared_with_accounts= | def shared_with_accounts= (account_id_list)
already_sharing_with = self.shared_with_accounts
accounts_to_add = account_id_list.select { |account_id| !already_sharing_with.include?(account_id) }
# Note, using the network API, it is possible to "unshare" an image template
# with the account that owns it, however, this leads to a rather odd state
# where the image has allocated resources (that the account may be charged for)
# but no way to delete those resources. For that reason this model
# always includes the account ID that owns the image in the list of
# accounts the image will be shared with.
my_account_id = self['accountId']
accounts_to_add.push(my_account_id) if !already_sharing_with.include?(my_account_id) && !accounts_to_add.include?(my_account_id)
accounts_to_remove = already_sharing_with.select { |account_id| (account_id != my_account_id) && !account_id_list.include?(account_id) }
accounts_to_add.each {|account_id| self.service.permitSharingAccess account_id }
accounts_to_remove.each {|account_id| self.service.denySharingAccess account_id }
end | ruby | def shared_with_accounts= (account_id_list)
already_sharing_with = self.shared_with_accounts
accounts_to_add = account_id_list.select { |account_id| !already_sharing_with.include?(account_id) }
# Note, using the network API, it is possible to "unshare" an image template
# with the account that owns it, however, this leads to a rather odd state
# where the image has allocated resources (that the account may be charged for)
# but no way to delete those resources. For that reason this model
# always includes the account ID that owns the image in the list of
# accounts the image will be shared with.
my_account_id = self['accountId']
accounts_to_add.push(my_account_id) if !already_sharing_with.include?(my_account_id) && !accounts_to_add.include?(my_account_id)
accounts_to_remove = already_sharing_with.select { |account_id| (account_id != my_account_id) && !account_id_list.include?(account_id) }
accounts_to_add.each {|account_id| self.service.permitSharingAccess account_id }
accounts_to_remove.each {|account_id| self.service.denySharingAccess account_id }
end | [
"def",
"shared_with_accounts",
"=",
"(",
"account_id_list",
")",
"already_sharing_with",
"=",
"self",
".",
"shared_with_accounts",
"accounts_to_add",
"=",
"account_id_list",
".",
"select",
"{",
"|",
"account_id",
"|",
"!",
"already_sharing_with",
".",
"include?",
"(",
"account_id",
")",
"}",
"my_account_id",
"=",
"self",
"[",
"'accountId'",
"]",
"accounts_to_add",
".",
"push",
"(",
"my_account_id",
")",
"if",
"!",
"already_sharing_with",
".",
"include?",
"(",
"my_account_id",
")",
"&&",
"!",
"accounts_to_add",
".",
"include?",
"(",
"my_account_id",
")",
"accounts_to_remove",
"=",
"already_sharing_with",
".",
"select",
"{",
"|",
"account_id",
"|",
"(",
"account_id",
"!=",
"my_account_id",
")",
"&&",
"!",
"account_id_list",
".",
"include?",
"(",
"account_id",
")",
"}",
"accounts_to_add",
".",
"each",
"{",
"|",
"account_id",
"|",
"self",
".",
"service",
".",
"permitSharingAccess",
"account_id",
"}",
"accounts_to_remove",
".",
"each",
"{",
"|",
"account_id",
"|",
"self",
".",
"service",
".",
"denySharingAccess",
"account_id",
"}",
"end"
] | Change the set of accounts that this image is shared with.
The parameter is an array of account ID's.
Note that this routine will "unshare" with any accounts
not included in the list passed in so the list should
be comprehensive | [
"Change",
"the",
"set",
"of",
"accounts",
"that",
"this",
"image",
"is",
"shared",
"with",
".",
"The",
"parameter",
"is",
"an",
"array",
"of",
"account",
"ID",
"s",
"."
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/ImageTemplate.rb#L132-L150 | train |
softlayer/softlayer-ruby | lib/softlayer/ImageTemplate.rb | SoftLayer.ImageTemplate.wait_until_ready | def wait_until_ready(max_trials, seconds_between_tries = 2)
# pessimistically assume the server is not ready
num_trials = 0
begin
self.refresh_details()
parent_ready = !(has_sl_property? :transactionId) || (self[:transactionId] == "")
children_ready = (nil == self['children'].find { |child| child['transactionId'] != "" })
ready = parent_ready && children_ready
yield ready if block_given?
num_trials = num_trials + 1
sleep(seconds_between_tries) if !ready && (num_trials <= max_trials)
end until ready || (num_trials >= max_trials)
ready
end | ruby | def wait_until_ready(max_trials, seconds_between_tries = 2)
# pessimistically assume the server is not ready
num_trials = 0
begin
self.refresh_details()
parent_ready = !(has_sl_property? :transactionId) || (self[:transactionId] == "")
children_ready = (nil == self['children'].find { |child| child['transactionId'] != "" })
ready = parent_ready && children_ready
yield ready if block_given?
num_trials = num_trials + 1
sleep(seconds_between_tries) if !ready && (num_trials <= max_trials)
end until ready || (num_trials >= max_trials)
ready
end | [
"def",
"wait_until_ready",
"(",
"max_trials",
",",
"seconds_between_tries",
"=",
"2",
")",
"num_trials",
"=",
"0",
"begin",
"self",
".",
"refresh_details",
"(",
")",
"parent_ready",
"=",
"!",
"(",
"has_sl_property?",
":transactionId",
")",
"||",
"(",
"self",
"[",
":transactionId",
"]",
"==",
"\"\"",
")",
"children_ready",
"=",
"(",
"nil",
"==",
"self",
"[",
"'children'",
"]",
".",
"find",
"{",
"|",
"child",
"|",
"child",
"[",
"'transactionId'",
"]",
"!=",
"\"\"",
"}",
")",
"ready",
"=",
"parent_ready",
"&&",
"children_ready",
"yield",
"ready",
"if",
"block_given?",
"num_trials",
"=",
"num_trials",
"+",
"1",
"sleep",
"(",
"seconds_between_tries",
")",
"if",
"!",
"ready",
"&&",
"(",
"num_trials",
"<=",
"max_trials",
")",
"end",
"until",
"ready",
"||",
"(",
"num_trials",
">=",
"max_trials",
")",
"ready",
"end"
] | Repeatedly poll the network API until transactions related to this image
template are finished
A template is not 'ready' until all the transactions on the template
itself, and all its children are complete.
At each trial, the routine will yield to a block if one is given
The block is passed one parameter, a boolean flag indicating
whether or not the image template is 'ready'. | [
"Repeatedly",
"poll",
"the",
"network",
"API",
"until",
"transactions",
"related",
"to",
"this",
"image",
"template",
"are",
"finished"
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/ImageTemplate.rb#L175-L192 | train |
softlayer/softlayer-ruby | lib/softlayer/ServerFirewallOrder.rb | SoftLayer.ServerFirewallOrder.verify | def verify()
order_template = firewall_order_template
order_template = yield order_template if block_given?
server.softlayer_client[:Product_Order].verifyOrder(order_template)
end | ruby | def verify()
order_template = firewall_order_template
order_template = yield order_template if block_given?
server.softlayer_client[:Product_Order].verifyOrder(order_template)
end | [
"def",
"verify",
"(",
")",
"order_template",
"=",
"firewall_order_template",
"order_template",
"=",
"yield",
"order_template",
"if",
"block_given?",
"server",
".",
"softlayer_client",
"[",
":Product_Order",
"]",
".",
"verifyOrder",
"(",
"order_template",
")",
"end"
] | Create a new order for the given server
Calls the SoftLayer API to verify that the template provided by this order is valid
This routine will return the order template generated by the API or will throw an exception
This routine will not actually create a Bare Metal Instance and will not affect billing.
If you provide a block, it will receive the order template as a parameter and
the block may make changes to the template before it is submitted. | [
"Create",
"a",
"new",
"order",
"for",
"the",
"given",
"server"
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/ServerFirewallOrder.rb#L31-L36 | train |
softlayer/softlayer-ruby | lib/softlayer/VLANFirewall.rb | SoftLayer.VLANFirewall.cancel! | def cancel!(notes = nil)
user = self.softlayer_client[:Account].object_mask("mask[id,account.id]").getCurrentUser
notes = "Cancelled by a call to #{__method__} in the softlayer_api gem" if notes == nil || notes == ""
cancellation_request = {
'accountId' => user['account']['id'],
'userId' => user['id'],
'items' => [ {
'billingItemId' => self['networkVlanFirewall']['billingItem']['id'],
'immediateCancellationFlag' => true
} ],
'notes' => notes
}
self.softlayer_client[:Billing_Item_Cancellation_Request].createObject(cancellation_request)
end | ruby | def cancel!(notes = nil)
user = self.softlayer_client[:Account].object_mask("mask[id,account.id]").getCurrentUser
notes = "Cancelled by a call to #{__method__} in the softlayer_api gem" if notes == nil || notes == ""
cancellation_request = {
'accountId' => user['account']['id'],
'userId' => user['id'],
'items' => [ {
'billingItemId' => self['networkVlanFirewall']['billingItem']['id'],
'immediateCancellationFlag' => true
} ],
'notes' => notes
}
self.softlayer_client[:Billing_Item_Cancellation_Request].createObject(cancellation_request)
end | [
"def",
"cancel!",
"(",
"notes",
"=",
"nil",
")",
"user",
"=",
"self",
".",
"softlayer_client",
"[",
":Account",
"]",
".",
"object_mask",
"(",
"\"mask[id,account.id]\"",
")",
".",
"getCurrentUser",
"notes",
"=",
"\"Cancelled by a call to #{__method__} in the softlayer_api gem\"",
"if",
"notes",
"==",
"nil",
"||",
"notes",
"==",
"\"\"",
"cancellation_request",
"=",
"{",
"'accountId'",
"=>",
"user",
"[",
"'account'",
"]",
"[",
"'id'",
"]",
",",
"'userId'",
"=>",
"user",
"[",
"'id'",
"]",
",",
"'items'",
"=>",
"[",
"{",
"'billingItemId'",
"=>",
"self",
"[",
"'networkVlanFirewall'",
"]",
"[",
"'billingItem'",
"]",
"[",
"'id'",
"]",
",",
"'immediateCancellationFlag'",
"=>",
"true",
"}",
"]",
",",
"'notes'",
"=>",
"notes",
"}",
"self",
".",
"softlayer_client",
"[",
":Billing_Item_Cancellation_Request",
"]",
".",
"createObject",
"(",
"cancellation_request",
")",
"end"
] | Cancel the firewall
This method cancels the firewall and releases its
resources. The cancellation is processed immediately!
Call this method with careful deliberation!
Notes is a string that describes the reason for the
cancellation. If empty or nil, a default string will
be added. | [
"Cancel",
"the",
"firewall"
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/VLANFirewall.rb#L123-L138 | train |
softlayer/softlayer-ruby | lib/softlayer/VLANFirewall.rb | SoftLayer.VLANFirewall.change_rules_bypass! | def change_rules_bypass!(bypass_symbol)
change_object = {
"firewallContextAccessControlListId" => rules_ACL_id(),
"rules" => self.rules
}
case bypass_symbol
when :apply_firewall_rules
change_object['bypassFlag'] = false
self.softlayer_client[:Network_Firewall_Update_Request].createObject(change_object)
when :bypass_firewall_rules
change_object['bypassFlag'] = true
self.softlayer_client[:Network_Firewall_Update_Request].createObject(change_object)
else
raise ArgumentError, "An invalid parameter was sent to #{__method__}. It accepts :apply_firewall_rules and :bypass_firewall_rules"
end
end | ruby | def change_rules_bypass!(bypass_symbol)
change_object = {
"firewallContextAccessControlListId" => rules_ACL_id(),
"rules" => self.rules
}
case bypass_symbol
when :apply_firewall_rules
change_object['bypassFlag'] = false
self.softlayer_client[:Network_Firewall_Update_Request].createObject(change_object)
when :bypass_firewall_rules
change_object['bypassFlag'] = true
self.softlayer_client[:Network_Firewall_Update_Request].createObject(change_object)
else
raise ArgumentError, "An invalid parameter was sent to #{__method__}. It accepts :apply_firewall_rules and :bypass_firewall_rules"
end
end | [
"def",
"change_rules_bypass!",
"(",
"bypass_symbol",
")",
"change_object",
"=",
"{",
"\"firewallContextAccessControlListId\"",
"=>",
"rules_ACL_id",
"(",
")",
",",
"\"rules\"",
"=>",
"self",
".",
"rules",
"}",
"case",
"bypass_symbol",
"when",
":apply_firewall_rules",
"change_object",
"[",
"'bypassFlag'",
"]",
"=",
"false",
"self",
".",
"softlayer_client",
"[",
":Network_Firewall_Update_Request",
"]",
".",
"createObject",
"(",
"change_object",
")",
"when",
":bypass_firewall_rules",
"change_object",
"[",
"'bypassFlag'",
"]",
"=",
"true",
"self",
".",
"softlayer_client",
"[",
":Network_Firewall_Update_Request",
"]",
".",
"createObject",
"(",
"change_object",
")",
"else",
"raise",
"ArgumentError",
",",
"\"An invalid parameter was sent to #{__method__}. It accepts :apply_firewall_rules and :bypass_firewall_rules\"",
"end",
"end"
] | This method asks the firewall to ignore its rule set and pass all traffic
through the firewall. Compare the behavior of this routine with
change_routing_bypass!
It is important to note that changing the bypass to :bypass_firewall_rules
removes ALL the protection offered by the firewall. This routine should be
used with extreme discretion.
Note that this routine queues a rule change and rule changes may take
time to process. The change will probably not take effect immediately.
The two symbols accepted as arguments by this routine are:
:apply_firewall_rules - The rules of the firewall are applied to traffic. This is the default operating mode of the firewall
:bypass_firewall_rules - The rules of the firewall are ignored. In this configuration the firewall provides no protection. | [
"This",
"method",
"asks",
"the",
"firewall",
"to",
"ignore",
"its",
"rule",
"set",
"and",
"pass",
"all",
"traffic",
"through",
"the",
"firewall",
".",
"Compare",
"the",
"behavior",
"of",
"this",
"routine",
"with",
"change_routing_bypass!"
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/VLANFirewall.rb#L187-L203 | train |
softlayer/softlayer-ruby | lib/softlayer/VLANFirewall.rb | SoftLayer.VLANFirewall.change_routing_bypass! | def change_routing_bypass!(routing_symbol)
vlan_firewall_id = self['networkVlanFirewall']['id']
raise "Could not identify the device for a VLAN firewall" if !vlan_firewall_id
case routing_symbol
when :route_through_firewall
self.softlayer_client[:Network_Vlan_Firewall].object_with_id(vlan_firewall_id).updateRouteBypass(false)
when :route_around_firewall
self.softlayer_client[:Network_Vlan_Firewall].object_with_id(vlan_firewall_id).updateRouteBypass(true)
else
raise ArgumentError, "An invalid parameter was sent to #{__method__}. It accepts :route_through_firewall and :route_around_firewall"
end
end | ruby | def change_routing_bypass!(routing_symbol)
vlan_firewall_id = self['networkVlanFirewall']['id']
raise "Could not identify the device for a VLAN firewall" if !vlan_firewall_id
case routing_symbol
when :route_through_firewall
self.softlayer_client[:Network_Vlan_Firewall].object_with_id(vlan_firewall_id).updateRouteBypass(false)
when :route_around_firewall
self.softlayer_client[:Network_Vlan_Firewall].object_with_id(vlan_firewall_id).updateRouteBypass(true)
else
raise ArgumentError, "An invalid parameter was sent to #{__method__}. It accepts :route_through_firewall and :route_around_firewall"
end
end | [
"def",
"change_routing_bypass!",
"(",
"routing_symbol",
")",
"vlan_firewall_id",
"=",
"self",
"[",
"'networkVlanFirewall'",
"]",
"[",
"'id'",
"]",
"raise",
"\"Could not identify the device for a VLAN firewall\"",
"if",
"!",
"vlan_firewall_id",
"case",
"routing_symbol",
"when",
":route_through_firewall",
"self",
".",
"softlayer_client",
"[",
":Network_Vlan_Firewall",
"]",
".",
"object_with_id",
"(",
"vlan_firewall_id",
")",
".",
"updateRouteBypass",
"(",
"false",
")",
"when",
":route_around_firewall",
"self",
".",
"softlayer_client",
"[",
":Network_Vlan_Firewall",
"]",
".",
"object_with_id",
"(",
"vlan_firewall_id",
")",
".",
"updateRouteBypass",
"(",
"true",
")",
"else",
"raise",
"ArgumentError",
",",
"\"An invalid parameter was sent to #{__method__}. It accepts :route_through_firewall and :route_around_firewall\"",
"end",
"end"
] | This method allows you to route traffic around the firewall
and directly to the servers it protects. Compare the behavior of this routine with
change_rules_bypass!
It is important to note that changing the routing to :route_around_firewall
removes ALL the protection offered by the firewall. This routine should be
used with extreme discretion.
Note that this routine constructs a transaction. The Routing change
may not happen immediately.
The two symbols accepted as arguments by the routine are:
:route_through_firewall - Network traffic is sent through the firewall to the servers in the VLAN segment it protects. This is the usual operating mode of the firewall.
:route_around_firewall - Network traffic will be sent directly to the servers in the VLAN segment protected by this firewall. This means that the firewall will *NOT* be protecting those servers. | [
"This",
"method",
"allows",
"you",
"to",
"route",
"traffic",
"around",
"the",
"firewall",
"and",
"directly",
"to",
"the",
"servers",
"it",
"protects",
".",
"Compare",
"the",
"behavior",
"of",
"this",
"routine",
"with",
"change_rules_bypass!"
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/VLANFirewall.rb#L221-L234 | train |
softlayer/softlayer-ruby | lib/softlayer/VLANFirewall.rb | SoftLayer.VLANFirewall.rules_ACL_id | def rules_ACL_id
outside_interface_data = self['firewallInterfaces'].find { |interface_data| interface_data['name'] == 'outside' }
incoming_ACL = outside_interface_data['firewallContextAccessControlLists'].find { |firewallACL_data| firewallACL_data['direction'] == 'in' } if outside_interface_data
if incoming_ACL
return incoming_ACL['id']
else
return nil
end
end | ruby | def rules_ACL_id
outside_interface_data = self['firewallInterfaces'].find { |interface_data| interface_data['name'] == 'outside' }
incoming_ACL = outside_interface_data['firewallContextAccessControlLists'].find { |firewallACL_data| firewallACL_data['direction'] == 'in' } if outside_interface_data
if incoming_ACL
return incoming_ACL['id']
else
return nil
end
end | [
"def",
"rules_ACL_id",
"outside_interface_data",
"=",
"self",
"[",
"'firewallInterfaces'",
"]",
".",
"find",
"{",
"|",
"interface_data",
"|",
"interface_data",
"[",
"'name'",
"]",
"==",
"'outside'",
"}",
"incoming_ACL",
"=",
"outside_interface_data",
"[",
"'firewallContextAccessControlLists'",
"]",
".",
"find",
"{",
"|",
"firewallACL_data",
"|",
"firewallACL_data",
"[",
"'direction'",
"]",
"==",
"'in'",
"}",
"if",
"outside_interface_data",
"if",
"incoming_ACL",
"return",
"incoming_ACL",
"[",
"'id'",
"]",
"else",
"return",
"nil",
"end",
"end"
] | Searches the set of access control lists for the firewall device in order to locate the one that
sits on the "outside" side of the network and handles 'in'coming traffic. | [
"Searches",
"the",
"set",
"of",
"access",
"control",
"lists",
"for",
"the",
"firewall",
"device",
"in",
"order",
"to",
"locate",
"the",
"one",
"that",
"sits",
"on",
"the",
"outside",
"side",
"of",
"the",
"network",
"and",
"handles",
"in",
"coming",
"traffic",
"."
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/VLANFirewall.rb#L277-L286 | train |
softlayer/softlayer-ruby | lib/softlayer/VirtualServerOrder.rb | SoftLayer.VirtualServerOrder.place_order! | def place_order!()
order_template = virtual_guest_template
order_template = yield order_template if block_given?
virtual_server_hash = @softlayer_client[:Virtual_Guest].createObject(order_template)
SoftLayer::VirtualServer.server_with_id(virtual_server_hash['id'], :client => @softlayer_client) if virtual_server_hash
end | ruby | def place_order!()
order_template = virtual_guest_template
order_template = yield order_template if block_given?
virtual_server_hash = @softlayer_client[:Virtual_Guest].createObject(order_template)
SoftLayer::VirtualServer.server_with_id(virtual_server_hash['id'], :client => @softlayer_client) if virtual_server_hash
end | [
"def",
"place_order!",
"(",
")",
"order_template",
"=",
"virtual_guest_template",
"order_template",
"=",
"yield",
"order_template",
"if",
"block_given?",
"virtual_server_hash",
"=",
"@softlayer_client",
"[",
":Virtual_Guest",
"]",
".",
"createObject",
"(",
"order_template",
")",
"SoftLayer",
"::",
"VirtualServer",
".",
"server_with_id",
"(",
"virtual_server_hash",
"[",
"'id'",
"]",
",",
":client",
"=>",
"@softlayer_client",
")",
"if",
"virtual_server_hash",
"end"
] | Calls the SoftLayer API to place an order for a new virtual server based on the template in this
order. If this succeeds then you will be billed for the new Virtual Server.
If you provide a block, it will receive the order template as a parameter and
should return an order template, **carefully** modified, that will be
sent to create the server | [
"Calls",
"the",
"SoftLayer",
"API",
"to",
"place",
"an",
"order",
"for",
"a",
"new",
"virtual",
"server",
"based",
"on",
"the",
"template",
"in",
"this",
"order",
".",
"If",
"this",
"succeeds",
"then",
"you",
"will",
"be",
"billed",
"for",
"the",
"new",
"Virtual",
"Server",
"."
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/VirtualServerOrder.rb#L141-L147 | train |
softlayer/softlayer-ruby | lib/softlayer/Software.rb | SoftLayer.Software.delete_user_password! | def delete_user_password!(username)
user_password = self.passwords.select { |sw_pw| sw_pw.username == username.to_s }
unless user_password.empty?
softlayer_client[:Software_Component_Password].object_with_id(user_password.first['id']).deleteObject
@passwords = nil
end
end | ruby | def delete_user_password!(username)
user_password = self.passwords.select { |sw_pw| sw_pw.username == username.to_s }
unless user_password.empty?
softlayer_client[:Software_Component_Password].object_with_id(user_password.first['id']).deleteObject
@passwords = nil
end
end | [
"def",
"delete_user_password!",
"(",
"username",
")",
"user_password",
"=",
"self",
".",
"passwords",
".",
"select",
"{",
"|",
"sw_pw",
"|",
"sw_pw",
".",
"username",
"==",
"username",
".",
"to_s",
"}",
"unless",
"user_password",
".",
"empty?",
"softlayer_client",
"[",
":Software_Component_Password",
"]",
".",
"object_with_id",
"(",
"user_password",
".",
"first",
"[",
"'id'",
"]",
")",
".",
"deleteObject",
"@passwords",
"=",
"nil",
"end",
"end"
] | Deletes specified username password from current software instance
This is a final action and cannot be undone.
the transaction will proceed immediately.
Call it with extreme care! | [
"Deletes",
"specified",
"username",
"password",
"from",
"current",
"software",
"instance"
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/Software.rb#L109-L116 | train |
hanneskaeufler/danger-todoist | lib/todoist/plugin.rb | Danger.DangerTodoist.print_todos_table | def print_todos_table
find_todos if @todos.nil?
return if @todos.empty?
markdown("#### Todos left in files")
@todos
.group_by(&:file)
.each { |file, todos| print_todos_per_file(file, todos) }
end | ruby | def print_todos_table
find_todos if @todos.nil?
return if @todos.empty?
markdown("#### Todos left in files")
@todos
.group_by(&:file)
.each { |file, todos| print_todos_per_file(file, todos) }
end | [
"def",
"print_todos_table",
"find_todos",
"if",
"@todos",
".",
"nil?",
"return",
"if",
"@todos",
".",
"empty?",
"markdown",
"(",
"\"#### Todos left in files\"",
")",
"@todos",
".",
"group_by",
"(",
"&",
":file",
")",
".",
"each",
"{",
"|",
"file",
",",
"todos",
"|",
"print_todos_per_file",
"(",
"file",
",",
"todos",
")",
"}",
"end"
] | Adds a list of offending files to the danger comment
@return [void] | [
"Adds",
"a",
"list",
"of",
"offending",
"files",
"to",
"the",
"danger",
"comment"
] | 6f2075fc6a1ca1426b473885f90f7234c4ed0ce7 | https://github.com/hanneskaeufler/danger-todoist/blob/6f2075fc6a1ca1426b473885f90f7234c4ed0ce7/lib/todoist/plugin.rb#L72-L81 | train |
softlayer/softlayer-ruby | lib/softlayer/VirtualServerOrder_Package.rb | SoftLayer.VirtualServerOrder_Package.virtual_server_order | def virtual_server_order
product_order = {
'packageId' => @package.id,
'useHourlyPricing' => !!@hourly,
'virtualGuests' => [{
'domain' => @domain,
'hostname' => @hostname
}]
}
#Note that the use of image_template and SoftLayer::ProductPackage os/guest_diskX configuration category
#item prices is mutually exclusive.
product_order['imageTemplateGlobalIdentifier'] = @image_template.global_id if @image_template
product_order['location'] = @datacenter.id if @datacenter
product_order['provisionScripts'] = [@provision_script_URI.to_s] if @provision_script_URI
product_order['provisionScripts'] = [@provision_script_uri.to_s] if @provision_script_uri
product_order['sshKeys'] = [{ 'sshKeyIds' => @ssh_key_ids }] if @ssh_key_ids
product_order['virtualGuests'][0]['userData'] = @user_metadata if @user_metadata
product_order['primaryNetworkComponent'] = { "networkVlan" => { "id" => @public_vlan_id.to_i } } if @public_vlan_id
product_order['primaryBackendNetworkComponent'] = { "networkVlan" => {"id" => @private_vlan_id.to_i } } if @private_vlan_id
product_order['prices'] = @configuration_options.collect do |key, value|
if value.respond_to?(:price_id)
price_id = value.price_id
else
price_id = value.to_i
end
{ 'id' => price_id }
end
product_order
end | ruby | def virtual_server_order
product_order = {
'packageId' => @package.id,
'useHourlyPricing' => !!@hourly,
'virtualGuests' => [{
'domain' => @domain,
'hostname' => @hostname
}]
}
#Note that the use of image_template and SoftLayer::ProductPackage os/guest_diskX configuration category
#item prices is mutually exclusive.
product_order['imageTemplateGlobalIdentifier'] = @image_template.global_id if @image_template
product_order['location'] = @datacenter.id if @datacenter
product_order['provisionScripts'] = [@provision_script_URI.to_s] if @provision_script_URI
product_order['provisionScripts'] = [@provision_script_uri.to_s] if @provision_script_uri
product_order['sshKeys'] = [{ 'sshKeyIds' => @ssh_key_ids }] if @ssh_key_ids
product_order['virtualGuests'][0]['userData'] = @user_metadata if @user_metadata
product_order['primaryNetworkComponent'] = { "networkVlan" => { "id" => @public_vlan_id.to_i } } if @public_vlan_id
product_order['primaryBackendNetworkComponent'] = { "networkVlan" => {"id" => @private_vlan_id.to_i } } if @private_vlan_id
product_order['prices'] = @configuration_options.collect do |key, value|
if value.respond_to?(:price_id)
price_id = value.price_id
else
price_id = value.to_i
end
{ 'id' => price_id }
end
product_order
end | [
"def",
"virtual_server_order",
"product_order",
"=",
"{",
"'packageId'",
"=>",
"@package",
".",
"id",
",",
"'useHourlyPricing'",
"=>",
"!",
"!",
"@hourly",
",",
"'virtualGuests'",
"=>",
"[",
"{",
"'domain'",
"=>",
"@domain",
",",
"'hostname'",
"=>",
"@hostname",
"}",
"]",
"}",
"product_order",
"[",
"'imageTemplateGlobalIdentifier'",
"]",
"=",
"@image_template",
".",
"global_id",
"if",
"@image_template",
"product_order",
"[",
"'location'",
"]",
"=",
"@datacenter",
".",
"id",
"if",
"@datacenter",
"product_order",
"[",
"'provisionScripts'",
"]",
"=",
"[",
"@provision_script_URI",
".",
"to_s",
"]",
"if",
"@provision_script_URI",
"product_order",
"[",
"'provisionScripts'",
"]",
"=",
"[",
"@provision_script_uri",
".",
"to_s",
"]",
"if",
"@provision_script_uri",
"product_order",
"[",
"'sshKeys'",
"]",
"=",
"[",
"{",
"'sshKeyIds'",
"=>",
"@ssh_key_ids",
"}",
"]",
"if",
"@ssh_key_ids",
"product_order",
"[",
"'virtualGuests'",
"]",
"[",
"0",
"]",
"[",
"'userData'",
"]",
"=",
"@user_metadata",
"if",
"@user_metadata",
"product_order",
"[",
"'primaryNetworkComponent'",
"]",
"=",
"{",
"\"networkVlan\"",
"=>",
"{",
"\"id\"",
"=>",
"@public_vlan_id",
".",
"to_i",
"}",
"}",
"if",
"@public_vlan_id",
"product_order",
"[",
"'primaryBackendNetworkComponent'",
"]",
"=",
"{",
"\"networkVlan\"",
"=>",
"{",
"\"id\"",
"=>",
"@private_vlan_id",
".",
"to_i",
"}",
"}",
"if",
"@private_vlan_id",
"product_order",
"[",
"'prices'",
"]",
"=",
"@configuration_options",
".",
"collect",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"value",
".",
"respond_to?",
"(",
":price_id",
")",
"price_id",
"=",
"value",
".",
"price_id",
"else",
"price_id",
"=",
"value",
".",
"to_i",
"end",
"{",
"'id'",
"=>",
"price_id",
"}",
"end",
"product_order",
"end"
] | Construct and return a hash representing a +SoftLayer_Container_Product_Order_Virtual_Guest+
based on the configuration options given. | [
"Construct",
"and",
"return",
"a",
"hash",
"representing",
"a",
"+",
"SoftLayer_Container_Product_Order_Virtual_Guest",
"+",
"based",
"on",
"the",
"configuration",
"options",
"given",
"."
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/VirtualServerOrder_Package.rb#L145-L177 | train |
softlayer/softlayer-ruby | lib/softlayer/VirtualServer.rb | SoftLayer.VirtualServer.capture_image | def capture_image(image_name, include_attached_storage = false, image_notes = '')
image_notes = '' if !image_notes
image_name = 'Captured Image' if !image_name
disk_filter = lambda { |disk| disk['device'] == '0' }
disk_filter = lambda { |disk| disk['device'] != '1' } if include_attached_storage
disks = self.blockDevices.select(&disk_filter)
self.service.createArchiveTransaction(image_name, disks, image_notes) if disks && !disks.empty?
image_templates = SoftLayer::ImageTemplate.find_private_templates(:name => image_name)
image_templates[0] if !image_templates.empty?
end | ruby | def capture_image(image_name, include_attached_storage = false, image_notes = '')
image_notes = '' if !image_notes
image_name = 'Captured Image' if !image_name
disk_filter = lambda { |disk| disk['device'] == '0' }
disk_filter = lambda { |disk| disk['device'] != '1' } if include_attached_storage
disks = self.blockDevices.select(&disk_filter)
self.service.createArchiveTransaction(image_name, disks, image_notes) if disks && !disks.empty?
image_templates = SoftLayer::ImageTemplate.find_private_templates(:name => image_name)
image_templates[0] if !image_templates.empty?
end | [
"def",
"capture_image",
"(",
"image_name",
",",
"include_attached_storage",
"=",
"false",
",",
"image_notes",
"=",
"''",
")",
"image_notes",
"=",
"''",
"if",
"!",
"image_notes",
"image_name",
"=",
"'Captured Image'",
"if",
"!",
"image_name",
"disk_filter",
"=",
"lambda",
"{",
"|",
"disk",
"|",
"disk",
"[",
"'device'",
"]",
"==",
"'0'",
"}",
"disk_filter",
"=",
"lambda",
"{",
"|",
"disk",
"|",
"disk",
"[",
"'device'",
"]",
"!=",
"'1'",
"}",
"if",
"include_attached_storage",
"disks",
"=",
"self",
".",
"blockDevices",
".",
"select",
"(",
"&",
"disk_filter",
")",
"self",
".",
"service",
".",
"createArchiveTransaction",
"(",
"image_name",
",",
"disks",
",",
"image_notes",
")",
"if",
"disks",
"&&",
"!",
"disks",
".",
"empty?",
"image_templates",
"=",
"SoftLayer",
"::",
"ImageTemplate",
".",
"find_private_templates",
"(",
":name",
"=>",
"image_name",
")",
"image_templates",
"[",
"0",
"]",
"if",
"!",
"image_templates",
".",
"empty?",
"end"
] | Capture a disk image of this virtual server for use with other servers.
image_name will become the name of the image in the portal.
If include_attached_storage is true, the images of attached storage will be
included as well.
The image_notes should be a string and will be added to the image as notes.
The routine returns the instance of SoftLayer::ImageTemplate that is
created. That image template will probably not be available immediately, however.
You may use the wait_until_ready routine of SoftLayer::ImageTemplate to
wait on it. | [
"Capture",
"a",
"disk",
"image",
"of",
"this",
"virtual",
"server",
"for",
"use",
"with",
"other",
"servers",
"."
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/VirtualServer.rb#L132-L145 | train |
softlayer/softlayer-ruby | lib/softlayer/VirtualServer.rb | SoftLayer.VirtualServer.wait_until_ready | def wait_until_ready(max_trials, wait_for_transactions = false, seconds_between_tries = 2)
# pessimistically assume the server is not ready
num_trials = 0
begin
self.refresh_details()
has_os_reload = has_sl_property? :lastOperatingSystemReload
has_active_transaction = has_sl_property? :activeTransaction
reloading_os = has_active_transaction && has_os_reload && (self.last_operating_system_reload['id'] == self.active_transaction['id'])
provisioned = has_sl_property?(:provisionDate) && ! self['provisionDate'].empty?
# a server is ready when it is provisioned, not reloading the OS
# (and if wait_for_transactions is true, when there are no active transactions).
ready = provisioned && !reloading_os && (!wait_for_transactions || !has_active_transaction)
num_trials = num_trials + 1
yield ready if block_given?
sleep(seconds_between_tries) if !ready && (num_trials <= max_trials)
end until ready || (num_trials >= max_trials)
ready
end | ruby | def wait_until_ready(max_trials, wait_for_transactions = false, seconds_between_tries = 2)
# pessimistically assume the server is not ready
num_trials = 0
begin
self.refresh_details()
has_os_reload = has_sl_property? :lastOperatingSystemReload
has_active_transaction = has_sl_property? :activeTransaction
reloading_os = has_active_transaction && has_os_reload && (self.last_operating_system_reload['id'] == self.active_transaction['id'])
provisioned = has_sl_property?(:provisionDate) && ! self['provisionDate'].empty?
# a server is ready when it is provisioned, not reloading the OS
# (and if wait_for_transactions is true, when there are no active transactions).
ready = provisioned && !reloading_os && (!wait_for_transactions || !has_active_transaction)
num_trials = num_trials + 1
yield ready if block_given?
sleep(seconds_between_tries) if !ready && (num_trials <= max_trials)
end until ready || (num_trials >= max_trials)
ready
end | [
"def",
"wait_until_ready",
"(",
"max_trials",
",",
"wait_for_transactions",
"=",
"false",
",",
"seconds_between_tries",
"=",
"2",
")",
"num_trials",
"=",
"0",
"begin",
"self",
".",
"refresh_details",
"(",
")",
"has_os_reload",
"=",
"has_sl_property?",
":lastOperatingSystemReload",
"has_active_transaction",
"=",
"has_sl_property?",
":activeTransaction",
"reloading_os",
"=",
"has_active_transaction",
"&&",
"has_os_reload",
"&&",
"(",
"self",
".",
"last_operating_system_reload",
"[",
"'id'",
"]",
"==",
"self",
".",
"active_transaction",
"[",
"'id'",
"]",
")",
"provisioned",
"=",
"has_sl_property?",
"(",
":provisionDate",
")",
"&&",
"!",
"self",
"[",
"'provisionDate'",
"]",
".",
"empty?",
"ready",
"=",
"provisioned",
"&&",
"!",
"reloading_os",
"&&",
"(",
"!",
"wait_for_transactions",
"||",
"!",
"has_active_transaction",
")",
"num_trials",
"=",
"num_trials",
"+",
"1",
"yield",
"ready",
"if",
"block_given?",
"sleep",
"(",
"seconds_between_tries",
")",
"if",
"!",
"ready",
"&&",
"(",
"num_trials",
"<=",
"max_trials",
")",
"end",
"until",
"ready",
"||",
"(",
"num_trials",
">=",
"max_trials",
")",
"ready",
"end"
] | Repeatedly polls the API to find out if this server is 'ready'.
The server is ready when it is provisioned and any operating system reloads have completed.
If wait_for_transactions is true, then the routine will poll until all transactions
(not just an OS Reload) have completed on the server.
max_trials is the maximum number of times the routine will poll the API
seconds_between_tries is the polling interval (in seconds)
The routine returns true if the server was found to be ready. If max_trials
is exceeded and the server is still not ready, the routine returns false
If a block is passed to this routine it will be called on each trial with
a boolean argument representing whether or not the server is ready
Calling this routine will (in essence) block the thread on which the request is made. | [
"Repeatedly",
"polls",
"the",
"API",
"to",
"find",
"out",
"if",
"this",
"server",
"is",
"ready",
"."
] | 48d7e0e36a3b02d832e7e303a513020a8fbde93b | https://github.com/softlayer/softlayer-ruby/blob/48d7e0e36a3b02d832e7e303a513020a8fbde93b/lib/softlayer/VirtualServer.rb#L166-L190 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.