repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
outcomesinsights/sequelizer | lib/sequelizer/env_config.rb | Sequelizer.EnvConfig.options | def options
Dotenv.load
seq_config = ENV.keys.select { |key| key =~ /^SEQUELIZER_/ }.inject({}) do |config, key|
new_key = key.gsub(/^SEQUELIZER_/, '').downcase
config[new_key] = ENV[key]
config
end
db_config = ENV.keys.select { |key| key =~ /_DB_OPT_/ }.inject({}) do |config, key|
new_key = key.downcase
config[new_key] = ENV[key]
config
end
db_config.merge(seq_config)
end | ruby | def options
Dotenv.load
seq_config = ENV.keys.select { |key| key =~ /^SEQUELIZER_/ }.inject({}) do |config, key|
new_key = key.gsub(/^SEQUELIZER_/, '').downcase
config[new_key] = ENV[key]
config
end
db_config = ENV.keys.select { |key| key =~ /_DB_OPT_/ }.inject({}) do |config, key|
new_key = key.downcase
config[new_key] = ENV[key]
config
end
db_config.merge(seq_config)
end | [
"def",
"options",
"Dotenv",
".",
"load",
"seq_config",
"=",
"ENV",
".",
"keys",
".",
"select",
"{",
"|",
"key",
"|",
"key",
"=~",
"/",
"/",
"}",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"config",
",",
"key",
"|",
"new_key",
"=",
"key",
".",
"gsub",
"(",
"/",
"/",
",",
"''",
")",
".",
"downcase",
"config",
"[",
"new_key",
"]",
"=",
"ENV",
"[",
"key",
"]",
"config",
"end",
"db_config",
"=",
"ENV",
".",
"keys",
".",
"select",
"{",
"|",
"key",
"|",
"key",
"=~",
"/",
"/",
"}",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"config",
",",
"key",
"|",
"new_key",
"=",
"key",
".",
"downcase",
"config",
"[",
"new_key",
"]",
"=",
"ENV",
"[",
"key",
"]",
"config",
"end",
"db_config",
".",
"merge",
"(",
"seq_config",
")",
"end"
] | Any environment variables in the .env file are loaded and then
any environment variable starting with SEQUELIZER_ will be used
as an option for the database | [
"Any",
"environment",
"variables",
"in",
"the",
".",
"env",
"file",
"are",
"loaded",
"and",
"then",
"any",
"environment",
"variable",
"starting",
"with",
"SEQUELIZER_",
"will",
"be",
"used",
"as",
"an",
"option",
"for",
"the",
"database"
] | 2a8b4a78410b1cf82ec19b45afdb4f65629b2ce2 | https://github.com/outcomesinsights/sequelizer/blob/2a8b4a78410b1cf82ec19b45afdb4f65629b2ce2/lib/sequelizer/env_config.rb#L10-L26 | train |
Tylerjd/minecraft-query | lib/rcon/rcon.rb | RCON.Query.cvar | def cvar(cvar_name)
response = command(cvar_name)
match = /^.+?\s(?:is|=)\s"([^"]+)".*$/.match response
match = match[1]
if /\D/.match match
return match
else
return match.to_i
end
end | ruby | def cvar(cvar_name)
response = command(cvar_name)
match = /^.+?\s(?:is|=)\s"([^"]+)".*$/.match response
match = match[1]
if /\D/.match match
return match
else
return match.to_i
end
end | [
"def",
"cvar",
"(",
"cvar_name",
")",
"response",
"=",
"command",
"(",
"cvar_name",
")",
"match",
"=",
"/",
"\\s",
"\\s",
"/",
".",
"match",
"response",
"match",
"=",
"match",
"[",
"1",
"]",
"if",
"/",
"\\D",
"/",
".",
"match",
"match",
"return",
"match",
"else",
"return",
"match",
".",
"to_i",
"end",
"end"
] | Convenience method to scrape input from cvar output and return that data.
Returns integers as a numeric type if possible.
ex: rcon.cvar("mp_friendlyfire") => 1
NOTE: This file has not been updated since previous version. Please be aware there may be outstanding Ruby2 bugs | [
"Convenience",
"method",
"to",
"scrape",
"input",
"from",
"cvar",
"output",
"and",
"return",
"that",
"data",
".",
"Returns",
"integers",
"as",
"a",
"numeric",
"type",
"if",
"possible",
"."
] | 41f369826a0364d5916dd5ea45ed28c10035e47d | https://github.com/Tylerjd/minecraft-query/blob/41f369826a0364d5916dd5ea45ed28c10035e47d/lib/rcon/rcon.rb#L13-L22 | train |
Tylerjd/minecraft-query | lib/rcon/rcon.rb | RCON.Source.command | def command(command)
if ! @authed
raise NetworkException.new("You must authenticate the connection successfully before sending commands.")
end
@packet = Packet::Source.new
@packet.command(command)
@socket.print @packet.to_s
rpacket = build_response_packet
if rpacket.command_type != Packet::Source::RESPONSE_NORM
raise NetworkException.new("error sending command: #{rpacket.command_type}")
end
if @return_packets
return rpacket
else
return rpacket.string1
end
end | ruby | def command(command)
if ! @authed
raise NetworkException.new("You must authenticate the connection successfully before sending commands.")
end
@packet = Packet::Source.new
@packet.command(command)
@socket.print @packet.to_s
rpacket = build_response_packet
if rpacket.command_type != Packet::Source::RESPONSE_NORM
raise NetworkException.new("error sending command: #{rpacket.command_type}")
end
if @return_packets
return rpacket
else
return rpacket.string1
end
end | [
"def",
"command",
"(",
"command",
")",
"if",
"!",
"@authed",
"raise",
"NetworkException",
".",
"new",
"(",
"\"You must authenticate the connection successfully before sending commands.\"",
")",
"end",
"@packet",
"=",
"Packet",
"::",
"Source",
".",
"new",
"@packet",
".",
"command",
"(",
"command",
")",
"@socket",
".",
"print",
"@packet",
".",
"to_s",
"rpacket",
"=",
"build_response_packet",
"if",
"rpacket",
".",
"command_type",
"!=",
"Packet",
"::",
"Source",
"::",
"RESPONSE_NORM",
"raise",
"NetworkException",
".",
"new",
"(",
"\"error sending command: #{rpacket.command_type}\"",
")",
"end",
"if",
"@return_packets",
"return",
"rpacket",
"else",
"return",
"rpacket",
".",
"string1",
"end",
"end"
] | Sends a RCon command to the server. May be used multiple times
after an authentication is successful. | [
"Sends",
"a",
"RCon",
"command",
"to",
"the",
"server",
".",
"May",
"be",
"used",
"multiple",
"times",
"after",
"an",
"authentication",
"is",
"successful",
"."
] | 41f369826a0364d5916dd5ea45ed28c10035e47d | https://github.com/Tylerjd/minecraft-query/blob/41f369826a0364d5916dd5ea45ed28c10035e47d/lib/rcon/rcon.rb#L150-L171 | train |
Tylerjd/minecraft-query | lib/rcon/rcon.rb | RCON.Source.auth | def auth(password)
establish_connection
@packet = Packet::Source.new
@packet.auth(password)
@socket.print @packet.to_s
# on auth, one junk packet is sent
rpacket = nil
2.times { rpacket = build_response_packet }
if rpacket.command_type != Packet::Source::RESPONSE_AUTH
raise NetworkException.new("error authenticating: #{rpacket.command_type}")
end
@authed = true
if @return_packets
return rpacket
else
return true
end
end | ruby | def auth(password)
establish_connection
@packet = Packet::Source.new
@packet.auth(password)
@socket.print @packet.to_s
# on auth, one junk packet is sent
rpacket = nil
2.times { rpacket = build_response_packet }
if rpacket.command_type != Packet::Source::RESPONSE_AUTH
raise NetworkException.new("error authenticating: #{rpacket.command_type}")
end
@authed = true
if @return_packets
return rpacket
else
return true
end
end | [
"def",
"auth",
"(",
"password",
")",
"establish_connection",
"@packet",
"=",
"Packet",
"::",
"Source",
".",
"new",
"@packet",
".",
"auth",
"(",
"password",
")",
"@socket",
".",
"print",
"@packet",
".",
"to_s",
"rpacket",
"=",
"nil",
"2",
".",
"times",
"{",
"rpacket",
"=",
"build_response_packet",
"}",
"if",
"rpacket",
".",
"command_type",
"!=",
"Packet",
"::",
"Source",
"::",
"RESPONSE_AUTH",
"raise",
"NetworkException",
".",
"new",
"(",
"\"error authenticating: #{rpacket.command_type}\"",
")",
"end",
"@authed",
"=",
"true",
"if",
"@return_packets",
"return",
"rpacket",
"else",
"return",
"true",
"end",
"end"
] | Requests authentication from the RCon server, given a
password. Is only expected to be used once. | [
"Requests",
"authentication",
"from",
"the",
"RCon",
"server",
"given",
"a",
"password",
".",
"Is",
"only",
"expected",
"to",
"be",
"used",
"once",
"."
] | 41f369826a0364d5916dd5ea45ed28c10035e47d | https://github.com/Tylerjd/minecraft-query/blob/41f369826a0364d5916dd5ea45ed28c10035e47d/lib/rcon/rcon.rb#L178-L199 | train |
arkes/sorting_table_for | lib/sorting_table_for/format_line.rb | SortingTableFor.FormatLine.add_cell | def add_cell(object, args, type = nil, block = nil)
@cells << FormatCell.new(object, args, type, block)
end | ruby | def add_cell(object, args, type = nil, block = nil)
@cells << FormatCell.new(object, args, type, block)
end | [
"def",
"add_cell",
"(",
"object",
",",
"args",
",",
"type",
"=",
"nil",
",",
"block",
"=",
"nil",
")",
"@cells",
"<<",
"FormatCell",
".",
"new",
"(",
"object",
",",
"args",
",",
"type",
",",
"block",
")",
"end"
] | Create a new cell with the class FormatCell
Add the object in @cells | [
"Create",
"a",
"new",
"cell",
"with",
"the",
"class",
"FormatCell",
"Add",
"the",
"object",
"in"
] | cfc41f033ed1babd9b3536cd63ef854eafb6e94e | https://github.com/arkes/sorting_table_for/blob/cfc41f033ed1babd9b3536cd63ef854eafb6e94e/lib/sorting_table_for/format_line.rb#L15-L17 | train |
arkes/sorting_table_for | lib/sorting_table_for/format_line.rb | SortingTableFor.FormatLine.content_columns | def content_columns
model_name(@object).constantize.content_columns.collect { |c| c.name.to_sym }.compact rescue []
end | ruby | def content_columns
model_name(@object).constantize.content_columns.collect { |c| c.name.to_sym }.compact rescue []
end | [
"def",
"content_columns",
"model_name",
"(",
"@object",
")",
".",
"constantize",
".",
"content_columns",
".",
"collect",
"{",
"|",
"c",
"|",
"c",
".",
"name",
".",
"to_sym",
"}",
".",
"compact",
"rescue",
"[",
"]",
"end"
] | Return each column in the model's database table | [
"Return",
"each",
"column",
"in",
"the",
"model",
"s",
"database",
"table"
] | cfc41f033ed1babd9b3536cd63ef854eafb6e94e | https://github.com/arkes/sorting_table_for/blob/cfc41f033ed1babd9b3536cd63ef854eafb6e94e/lib/sorting_table_for/format_line.rb#L38-L40 | train |
arkes/sorting_table_for | lib/sorting_table_for/format_line.rb | SortingTableFor.FormatLine.model_have_column? | def model_have_column?(column)
model_name(@object).constantize.content_columns.each do |model_column|
return true if model_column.name == column.to_s
end
false
end | ruby | def model_have_column?(column)
model_name(@object).constantize.content_columns.each do |model_column|
return true if model_column.name == column.to_s
end
false
end | [
"def",
"model_have_column?",
"(",
"column",
")",
"model_name",
"(",
"@object",
")",
".",
"constantize",
".",
"content_columns",
".",
"each",
"do",
"|",
"model_column",
"|",
"return",
"true",
"if",
"model_column",
".",
"name",
"==",
"column",
".",
"to_s",
"end",
"false",
"end"
] | Return true if the column is in the model's database table | [
"Return",
"true",
"if",
"the",
"column",
"is",
"in",
"the",
"model",
"s",
"database",
"table"
] | cfc41f033ed1babd9b3536cd63ef854eafb6e94e | https://github.com/arkes/sorting_table_for/blob/cfc41f033ed1babd9b3536cd63ef854eafb6e94e/lib/sorting_table_for/format_line.rb#L43-L48 | train |
arkes/sorting_table_for | lib/sorting_table_for/format_line.rb | SortingTableFor.FormatLine.format_options_to_cell | def format_options_to_cell(ask, options = @column_options)
options.each do |key, value|
if only_cell_option?(key)
if ask.is_a? Hash
ask.merge!(key => value)
else
ask = [ask] unless ask.is_a? Array
(ask.last.is_a? Hash and ask.last.has_key? :html) ? ask.last[:html].merge!(key => value) : ask << { :html => { key => value }}
end
end
end
ask
end | ruby | def format_options_to_cell(ask, options = @column_options)
options.each do |key, value|
if only_cell_option?(key)
if ask.is_a? Hash
ask.merge!(key => value)
else
ask = [ask] unless ask.is_a? Array
(ask.last.is_a? Hash and ask.last.has_key? :html) ? ask.last[:html].merge!(key => value) : ask << { :html => { key => value }}
end
end
end
ask
end | [
"def",
"format_options_to_cell",
"(",
"ask",
",",
"options",
"=",
"@column_options",
")",
"options",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"only_cell_option?",
"(",
"key",
")",
"if",
"ask",
".",
"is_a?",
"Hash",
"ask",
".",
"merge!",
"(",
"key",
"=>",
"value",
")",
"else",
"ask",
"=",
"[",
"ask",
"]",
"unless",
"ask",
".",
"is_a?",
"Array",
"(",
"ask",
".",
"last",
".",
"is_a?",
"Hash",
"and",
"ask",
".",
"last",
".",
"has_key?",
":html",
")",
"?",
"ask",
".",
"last",
"[",
":html",
"]",
".",
"merge!",
"(",
"key",
"=>",
"value",
")",
":",
"ask",
"<<",
"{",
":html",
"=>",
"{",
"key",
"=>",
"value",
"}",
"}",
"end",
"end",
"end",
"ask",
"end"
] | Format ask to send options to cell | [
"Format",
"ask",
"to",
"send",
"options",
"to",
"cell"
] | cfc41f033ed1babd9b3536cd63ef854eafb6e94e | https://github.com/arkes/sorting_table_for/blob/cfc41f033ed1babd9b3536cd63ef854eafb6e94e/lib/sorting_table_for/format_line.rb#L56-L68 | train |
AnkurGel/dictionary-rb | lib/dictionary-rb/word.rb | DictionaryRB.Word.dictionary_meaning | def dictionary_meaning
if @dictionary_meaning.nil?
@dictionary = Dictionary.new(@word)
meanings = @dictionary.meanings
if meanings.is_a? Array and not meanings.empty?
@dictionary_meanings = meanings
@dictionary_meaning = @dictionary.meaning
end
end
@dictionary_meaning
end | ruby | def dictionary_meaning
if @dictionary_meaning.nil?
@dictionary = Dictionary.new(@word)
meanings = @dictionary.meanings
if meanings.is_a? Array and not meanings.empty?
@dictionary_meanings = meanings
@dictionary_meaning = @dictionary.meaning
end
end
@dictionary_meaning
end | [
"def",
"dictionary_meaning",
"if",
"@dictionary_meaning",
".",
"nil?",
"@dictionary",
"=",
"Dictionary",
".",
"new",
"(",
"@word",
")",
"meanings",
"=",
"@dictionary",
".",
"meanings",
"if",
"meanings",
".",
"is_a?",
"Array",
"and",
"not",
"meanings",
".",
"empty?",
"@dictionary_meanings",
"=",
"meanings",
"@dictionary_meaning",
"=",
"@dictionary",
".",
"meaning",
"end",
"end",
"@dictionary_meaning",
"end"
] | Gives dictionary meaning for the word
@example
word.dictionary_meaning
#or
word.meaning
@note This method will hit the {Dictionary::PREFIX ENDPOINT} and will consume some time to generate result
@return [String] containing meaning from Reference {Dictionary} for the word | [
"Gives",
"dictionary",
"meaning",
"for",
"the",
"word"
] | 92566325aee598f46b584817373017e6097300b4 | https://github.com/AnkurGel/dictionary-rb/blob/92566325aee598f46b584817373017e6097300b4/lib/dictionary-rb/word.rb#L39-L49 | train |
AnkurGel/dictionary-rb | lib/dictionary-rb/word.rb | DictionaryRB.Word.urban_meaning | def urban_meaning
if @urban_meaning.nil?
@urban = Urban.new(@word)
meanings = @urban.meanings
if meanings.is_a?(Array) and not meanings.empty?
@urban_meanings = meanings
@urban_meaning = @urban.meaning
end
end
@urban_meaning
end | ruby | def urban_meaning
if @urban_meaning.nil?
@urban = Urban.new(@word)
meanings = @urban.meanings
if meanings.is_a?(Array) and not meanings.empty?
@urban_meanings = meanings
@urban_meaning = @urban.meaning
end
end
@urban_meaning
end | [
"def",
"urban_meaning",
"if",
"@urban_meaning",
".",
"nil?",
"@urban",
"=",
"Urban",
".",
"new",
"(",
"@word",
")",
"meanings",
"=",
"@urban",
".",
"meanings",
"if",
"meanings",
".",
"is_a?",
"(",
"Array",
")",
"and",
"not",
"meanings",
".",
"empty?",
"@urban_meanings",
"=",
"meanings",
"@urban_meaning",
"=",
"@urban",
".",
"meaning",
"end",
"end",
"@urban_meaning",
"end"
] | Fetches the first meaning from Urban Dictionary for the word.
@note This method will hit the {Urban::PREFIX ENDPOINT} and will consume some time to generate result
@example
word.urban_meaning
@see #urban_meanings
@return [String] containing meaning from {Urban} Dictionary for the word | [
"Fetches",
"the",
"first",
"meaning",
"from",
"Urban",
"Dictionary",
"for",
"the",
"word",
"."
] | 92566325aee598f46b584817373017e6097300b4 | https://github.com/AnkurGel/dictionary-rb/blob/92566325aee598f46b584817373017e6097300b4/lib/dictionary-rb/word.rb#L81-L91 | train |
adhearsion/adhearsion-asr | lib/adhearsion-asr/controller_methods.rb | AdhearsionASR.ControllerMethods.ask | def ask(*args)
options = args.last.kind_of?(Hash) ? args.pop : {}
prompts = args.flatten.compact
if block_given?
logger.warn "You passed a block to #ask, but this functionality is not available in adhearsion-asr. If you're looking for the block validator functionality, you should avoid using it in favour of grammars, and it is deprecated in Adhearsion Core."
end
options[:grammar] || options[:grammar_url] || options[:limit] || options[:terminator] || raise(ArgumentError, "You must specify at least one of limit, terminator or grammar")
grammars = AskGrammarBuilder.new(options).grammars
output_document = prompts.empty? ? nil : output_formatter.ssml_for_collection(prompts)
PromptBuilder.new(output_document, grammars, options).execute self
end | ruby | def ask(*args)
options = args.last.kind_of?(Hash) ? args.pop : {}
prompts = args.flatten.compact
if block_given?
logger.warn "You passed a block to #ask, but this functionality is not available in adhearsion-asr. If you're looking for the block validator functionality, you should avoid using it in favour of grammars, and it is deprecated in Adhearsion Core."
end
options[:grammar] || options[:grammar_url] || options[:limit] || options[:terminator] || raise(ArgumentError, "You must specify at least one of limit, terminator or grammar")
grammars = AskGrammarBuilder.new(options).grammars
output_document = prompts.empty? ? nil : output_formatter.ssml_for_collection(prompts)
PromptBuilder.new(output_document, grammars, options).execute self
end | [
"def",
"ask",
"(",
"*",
"args",
")",
"options",
"=",
"args",
".",
"last",
".",
"kind_of?",
"(",
"Hash",
")",
"?",
"args",
".",
"pop",
":",
"{",
"}",
"prompts",
"=",
"args",
".",
"flatten",
".",
"compact",
"if",
"block_given?",
"logger",
".",
"warn",
"\"You passed a block to #ask, but this functionality is not available in adhearsion-asr. If you're looking for the block validator functionality, you should avoid using it in favour of grammars, and it is deprecated in Adhearsion Core.\"",
"end",
"options",
"[",
":grammar",
"]",
"||",
"options",
"[",
":grammar_url",
"]",
"||",
"options",
"[",
":limit",
"]",
"||",
"options",
"[",
":terminator",
"]",
"||",
"raise",
"(",
"ArgumentError",
",",
"\"You must specify at least one of limit, terminator or grammar\"",
")",
"grammars",
"=",
"AskGrammarBuilder",
".",
"new",
"(",
"options",
")",
".",
"grammars",
"output_document",
"=",
"prompts",
".",
"empty?",
"?",
"nil",
":",
"output_formatter",
".",
"ssml_for_collection",
"(",
"prompts",
")",
"PromptBuilder",
".",
"new",
"(",
"output_document",
",",
"grammars",
",",
"options",
")",
".",
"execute",
"self",
"end"
] | Prompts for input, handling playback of prompts, DTMF grammar construction, and execution
@example A basic DTMF digit collection:
ask "Welcome, ", "/opt/sounds/menu-prompt.mp3",
timeout: 10, terminator: '#', limit: 3
The first arguments will be a list of sounds to play, as accepted by #play, including strings for TTS, Date and Time objects, and file paths.
:timeout, :terminator and :limit options may be specified to automatically construct a grammar, or grammars may be manually specified.
@param [Object, Array<Object>] args A list of outputs to play, as accepted by #play
@param [Hash] options Options to modify the grammar
@option options [Boolean] :interruptible If the prompt should be interruptible or not. Defaults to true
@option options [Integer] :limit Digit limit (causes collection to cease after a specified number of digits have been collected)
@option options [Integer] :timeout Timeout in seconds before the first and between each input digit
@option options [String] :terminator Digit to terminate input
@option options [RubySpeech::GRXML::Grammar, Array<RubySpeech::GRXML::Grammar>] :grammar One of a collection of grammars to execute
@option options [String, Array<String>] :grammar_url One of a collection of URLs for grammars to execute
@option options [Hash] :input_options A hash of options passed directly to the Punchblock Input constructor. See
@option options [Hash] :output_options A hash of options passed directly to the Punchblock Output constructor
@return [Result] a result object from which the details of the utterance may be established
@see Output#play
@see http://rdoc.info/gems/punchblock/Punchblock/Component/Input.new Punchblock::Component::Input.new
@see http://rdoc.info/gems/punchblock/Punchblock/Component/Output.new Punchblock::Component::Output.new | [
"Prompts",
"for",
"input",
"handling",
"playback",
"of",
"prompts",
"DTMF",
"grammar",
"construction",
"and",
"execution"
] | 66f966ee752433e382082570a5886a0fb3f8b169 | https://github.com/adhearsion/adhearsion-asr/blob/66f966ee752433e382082570a5886a0fb3f8b169/lib/adhearsion-asr/controller_methods.rb#L35-L50 | train |
adhearsion/adhearsion-asr | lib/adhearsion-asr/controller_methods.rb | AdhearsionASR.ControllerMethods.menu | def menu(*args, &block)
raise ArgumentError, "You must specify a block to build the menu" unless block
options = args.last.kind_of?(Hash) ? args.pop : {}
prompts = args.flatten.compact
menu_builder = MenuBuilder.new(options, &block)
output_document = prompts.empty? ? nil : output_formatter.ssml_for_collection(prompts)
menu_builder.execute output_document, self
end | ruby | def menu(*args, &block)
raise ArgumentError, "You must specify a block to build the menu" unless block
options = args.last.kind_of?(Hash) ? args.pop : {}
prompts = args.flatten.compact
menu_builder = MenuBuilder.new(options, &block)
output_document = prompts.empty? ? nil : output_formatter.ssml_for_collection(prompts)
menu_builder.execute output_document, self
end | [
"def",
"menu",
"(",
"*",
"args",
",",
"&",
"block",
")",
"raise",
"ArgumentError",
",",
"\"You must specify a block to build the menu\"",
"unless",
"block",
"options",
"=",
"args",
".",
"last",
".",
"kind_of?",
"(",
"Hash",
")",
"?",
"args",
".",
"pop",
":",
"{",
"}",
"prompts",
"=",
"args",
".",
"flatten",
".",
"compact",
"menu_builder",
"=",
"MenuBuilder",
".",
"new",
"(",
"options",
",",
"&",
"block",
")",
"output_document",
"=",
"prompts",
".",
"empty?",
"?",
"nil",
":",
"output_formatter",
".",
"ssml_for_collection",
"(",
"prompts",
")",
"menu_builder",
".",
"execute",
"output_document",
",",
"self",
"end"
] | Creates and manages a multiple choice menu driven by DTMF, handling playback of prompts,
invalid input, retries and timeouts, and final failures.
@example A complete example of the method is as follows:
menu "Welcome, ", "/opt/sounds/menu-prompt.mp3", tries: 2, timeout: 10 do
match 1, OperatorController
match 10..19 do
pass DirectController
end
match 5, 6, 9 do |exten|
play "The #{exten} extension is currently not active"
end
match '7', OfficeController
invalid { play "Please choose a valid extension" }
timeout { play "Input timed out, try again." }
failure { pass OperatorController }
end
The first arguments will be a list of sounds to play, as accepted by #play, including strings for TTS, Date and Time objects, and file paths.
:tries and :timeout options respectively specify the number of tries before going into failure, and the timeout in seconds allowed on each digit input.
The most important part is the following block, which specifies how the menu will be constructed and handled.
#match handles connecting an input pattern to a payload.
The pattern can be one or more of: an integer, a Range, a string, an Array of the possible single types.
Input is matched against patterns, and the first exact match has it's payload executed.
Matched input is passed in to the associated block, or to the controller through #options.
Allowed payloads are the name of a controller class, in which case it is executed through its #run method, or a block, which is executed in the context of the current controller.
#invalid has its associated block executed when the input does not possibly match any pattern.
#timeout's block is run when timeout expires before receiving any input
#failure runs its block when the maximum number of tries is reached without an input match.
Execution of the current context resumes after #menu finishes. If you wish to jump to an entirely different controller, use #pass.
Menu will return :failed if failure was reached, or :done if a match was executed.
@param [Object] args A list of outputs to play, as accepted by #play
@param [Hash] options Options to use for the menu
@option options [Integer] :tries Number of tries allowed before failure
@option options [Integer] :timeout Timeout in seconds before the first and between each input digit
@option options [Boolean] :interruptible If the prompt should be interruptible or not. Defaults to true
@option options [String, Symbol] :mode Input mode to accept. May be :voice or :dtmf.
@option options [Hash] :input_options A hash of options passed directly to the Punchblock Input constructor
@option options [Hash] :output_options A hash of options passed directly to the Punchblock Output constructor
@return [Result] a result object from which the details of the utterance may be established
@see Output#play
@see CallController#pass | [
"Creates",
"and",
"manages",
"a",
"multiple",
"choice",
"menu",
"driven",
"by",
"DTMF",
"handling",
"playback",
"of",
"prompts",
"invalid",
"input",
"retries",
"and",
"timeouts",
"and",
"final",
"failures",
"."
] | 66f966ee752433e382082570a5886a0fb3f8b169 | https://github.com/adhearsion/adhearsion-asr/blob/66f966ee752433e382082570a5886a0fb3f8b169/lib/adhearsion-asr/controller_methods.rb#L106-L116 | train |
culturecode/spatial_features | lib/spatial_features/has_spatial_features.rb | SpatialFeatures.ClassMethods.spatial_join | def spatial_join(other, buffer = 0, table_alias = 'features', other_alias = 'other_features', geom = 'geom_lowres')
scope = features_scope(self).select("#{geom} AS geom").select(:spatial_model_id)
other_scope = features_scope(other)
other_scope = other_scope.select("ST_Union(#{geom}) AS geom").select("ST_Buffer(ST_Union(#{geom}), #{buffer.to_i}) AS buffered_geom")
return joins(%Q(INNER JOIN (#{scope.to_sql}) AS #{table_alias} ON #{table_alias}.spatial_model_id = #{table_name}.id))
.joins(%Q(INNER JOIN (#{other_scope.to_sql}) AS #{other_alias} ON ST_Intersects(#{table_alias}.geom, #{other_alias}.buffered_geom)))
end | ruby | def spatial_join(other, buffer = 0, table_alias = 'features', other_alias = 'other_features', geom = 'geom_lowres')
scope = features_scope(self).select("#{geom} AS geom").select(:spatial_model_id)
other_scope = features_scope(other)
other_scope = other_scope.select("ST_Union(#{geom}) AS geom").select("ST_Buffer(ST_Union(#{geom}), #{buffer.to_i}) AS buffered_geom")
return joins(%Q(INNER JOIN (#{scope.to_sql}) AS #{table_alias} ON #{table_alias}.spatial_model_id = #{table_name}.id))
.joins(%Q(INNER JOIN (#{other_scope.to_sql}) AS #{other_alias} ON ST_Intersects(#{table_alias}.geom, #{other_alias}.buffered_geom)))
end | [
"def",
"spatial_join",
"(",
"other",
",",
"buffer",
"=",
"0",
",",
"table_alias",
"=",
"'features'",
",",
"other_alias",
"=",
"'other_features'",
",",
"geom",
"=",
"'geom_lowres'",
")",
"scope",
"=",
"features_scope",
"(",
"self",
")",
".",
"select",
"(",
"\"#{geom} AS geom\"",
")",
".",
"select",
"(",
":spatial_model_id",
")",
"other_scope",
"=",
"features_scope",
"(",
"other",
")",
"other_scope",
"=",
"other_scope",
".",
"select",
"(",
"\"ST_Union(#{geom}) AS geom\"",
")",
".",
"select",
"(",
"\"ST_Buffer(ST_Union(#{geom}), #{buffer.to_i}) AS buffered_geom\"",
")",
"return",
"joins",
"(",
"%Q(INNER JOIN (#{scope.to_sql}) AS #{table_alias} ON #{table_alias}.spatial_model_id = #{table_name}.id)",
")",
".",
"joins",
"(",
"%Q(INNER JOIN (#{other_scope.to_sql}) AS #{other_alias} ON ST_Intersects(#{table_alias}.geom, #{other_alias}.buffered_geom))",
")",
"end"
] | Returns a scope that includes the features for this record as the table_alias and the features for other as other_alias
Performs a spatial intersection between the two sets of features, within the buffer distance given in meters | [
"Returns",
"a",
"scope",
"that",
"includes",
"the",
"features",
"for",
"this",
"record",
"as",
"the",
"table_alias",
"and",
"the",
"features",
"for",
"other",
"as",
"other_alias",
"Performs",
"a",
"spatial",
"intersection",
"between",
"the",
"two",
"sets",
"of",
"features",
"within",
"the",
"buffer",
"distance",
"given",
"in",
"meters"
] | 557a4b8a855129dd51a3c2cfcdad8312083fb73a | https://github.com/culturecode/spatial_features/blob/557a4b8a855129dd51a3c2cfcdad8312083fb73a/lib/spatial_features/has_spatial_features.rb#L144-L152 | train |
dpla/KriKri | lib/krikri/enricher.rb | Krikri.Enricher.chain_enrichments! | def chain_enrichments!(agg)
chain.keys.each do |e|
enrichment = enrichment_cache(e)
if enrichment.is_a? Audumbla::FieldEnrichment
agg = do_field_enrichment(agg, enrichment, chain[e])
else
agg = do_basic_enrichment(agg, enrichment, chain[e])
end
end
end | ruby | def chain_enrichments!(agg)
chain.keys.each do |e|
enrichment = enrichment_cache(e)
if enrichment.is_a? Audumbla::FieldEnrichment
agg = do_field_enrichment(agg, enrichment, chain[e])
else
agg = do_basic_enrichment(agg, enrichment, chain[e])
end
end
end | [
"def",
"chain_enrichments!",
"(",
"agg",
")",
"chain",
".",
"keys",
".",
"each",
"do",
"|",
"e",
"|",
"enrichment",
"=",
"enrichment_cache",
"(",
"e",
")",
"if",
"enrichment",
".",
"is_a?",
"Audumbla",
"::",
"FieldEnrichment",
"agg",
"=",
"do_field_enrichment",
"(",
"agg",
",",
"enrichment",
",",
"chain",
"[",
"e",
"]",
")",
"else",
"agg",
"=",
"do_basic_enrichment",
"(",
"agg",
",",
"enrichment",
",",
"chain",
"[",
"e",
"]",
")",
"end",
"end",
"end"
] | Given an aggregation, take each enrichment specified by the `chain'
given in our instantiation, and apply that enrichment, with the given
options, modifying the aggregation in-place. | [
"Given",
"an",
"aggregation",
"take",
"each",
"enrichment",
"specified",
"by",
"the",
"chain",
"given",
"in",
"our",
"instantiation",
"and",
"apply",
"that",
"enrichment",
"with",
"the",
"given",
"options",
"modifying",
"the",
"aggregation",
"in",
"-",
"place",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/enricher.rb#L73-L82 | train |
dpla/KriKri | lib/krikri/enricher.rb | Krikri.Enricher.deep_sym | def deep_sym(obj)
if obj.is_a? Hash
return obj.inject({}) do |memo, (k, v)|
memo[k.to_sym] = deep_sym(v)
memo
end
elsif obj.is_a? Array
return obj.inject([]) do |memo, el|
memo << deep_sym(el)
memo
end
elsif obj.respond_to? :to_sym
return obj.to_sym
else
return nil
end
end | ruby | def deep_sym(obj)
if obj.is_a? Hash
return obj.inject({}) do |memo, (k, v)|
memo[k.to_sym] = deep_sym(v)
memo
end
elsif obj.is_a? Array
return obj.inject([]) do |memo, el|
memo << deep_sym(el)
memo
end
elsif obj.respond_to? :to_sym
return obj.to_sym
else
return nil
end
end | [
"def",
"deep_sym",
"(",
"obj",
")",
"if",
"obj",
".",
"is_a?",
"Hash",
"return",
"obj",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"memo",
",",
"(",
"k",
",",
"v",
")",
"|",
"memo",
"[",
"k",
".",
"to_sym",
"]",
"=",
"deep_sym",
"(",
"v",
")",
"memo",
"end",
"elsif",
"obj",
".",
"is_a?",
"Array",
"return",
"obj",
".",
"inject",
"(",
"[",
"]",
")",
"do",
"|",
"memo",
",",
"el",
"|",
"memo",
"<<",
"deep_sym",
"(",
"el",
")",
"memo",
"end",
"elsif",
"obj",
".",
"respond_to?",
":to_sym",
"return",
"obj",
".",
"to_sym",
"else",
"return",
"nil",
"end",
"end"
] | Transform the given hash recursively by turning all of its string keys
and values into symbols.
Symbols are expected in the enrichment classes, and we will usually be
dealing with values that have been deserialized from JSON. | [
"Transform",
"the",
"given",
"hash",
"recursively",
"by",
"turning",
"all",
"of",
"its",
"string",
"keys",
"and",
"values",
"into",
"symbols",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/enricher.rb#L126-L142 | train |
schrodingersbox/meter_cat | app/models/meter_cat/meter.rb | MeterCat.Meter.add | def add
meter = nil
Meter.uncached { meter = Meter.find_by_name_and_created_on(name, created_on) }
meter ||= Meter.new(name: name, created_on: created_on)
meter.value += value
return meter.save
end | ruby | def add
meter = nil
Meter.uncached { meter = Meter.find_by_name_and_created_on(name, created_on) }
meter ||= Meter.new(name: name, created_on: created_on)
meter.value += value
return meter.save
end | [
"def",
"add",
"meter",
"=",
"nil",
"Meter",
".",
"uncached",
"{",
"meter",
"=",
"Meter",
".",
"find_by_name_and_created_on",
"(",
"name",
",",
"created_on",
")",
"}",
"meter",
"||=",
"Meter",
".",
"new",
"(",
"name",
":",
"name",
",",
"created_on",
":",
"created_on",
")",
"meter",
".",
"value",
"+=",
"value",
"return",
"meter",
".",
"save",
"end"
] | Instance methods
Create an object for this name+date in the db if one does not already exist.
Add the value from this object to the one in the DB.
Returns the result of the ActiveRecord save operation. | [
"Instance",
"methods",
"Create",
"an",
"object",
"for",
"this",
"name",
"+",
"date",
"in",
"the",
"db",
"if",
"one",
"does",
"not",
"already",
"exist",
".",
"Add",
"the",
"value",
"from",
"this",
"object",
"to",
"the",
"one",
"in",
"the",
"DB",
".",
"Returns",
"the",
"result",
"of",
"the",
"ActiveRecord",
"save",
"operation",
"."
] | b20d579749ef2facbf3b308d4fb39215a7eac2a1 | https://github.com/schrodingersbox/meter_cat/blob/b20d579749ef2facbf3b308d4fb39215a7eac2a1/app/models/meter_cat/meter.rb#L34-L40 | train |
Esri/geotrigger-ruby | lib/geotrigger/tag.rb | Geotrigger.Tag.post_update | def post_update
raise StateError.new 'device access_token prohibited' if @session.device?
post_data = @data.dup
post_data['tags'] = post_data.delete 'name'
grok_self_from post 'tag/permissions/update', post_data
self
end | ruby | def post_update
raise StateError.new 'device access_token prohibited' if @session.device?
post_data = @data.dup
post_data['tags'] = post_data.delete 'name'
grok_self_from post 'tag/permissions/update', post_data
self
end | [
"def",
"post_update",
"raise",
"StateError",
".",
"new",
"'device access_token prohibited'",
"if",
"@session",
".",
"device?",
"post_data",
"=",
"@data",
".",
"dup",
"post_data",
"[",
"'tags'",
"]",
"=",
"post_data",
".",
"delete",
"'name'",
"grok_self_from",
"post",
"'tag/permissions/update'",
",",
"post_data",
"self",
"end"
] | POST the tag's +@data+ to the API via 'tag/permissions/update', and return
the same object with the new +@data+ returned from API call. | [
"POST",
"the",
"tag",
"s",
"+"
] | 41fbac4a25ec43427a51dc235a0dbc158e80ce02 | https://github.com/Esri/geotrigger-ruby/blob/41fbac4a25ec43427a51dc235a0dbc158e80ce02/lib/geotrigger/tag.rb#L64-L70 | train |
Esri/geotrigger-ruby | lib/geotrigger/device.rb | Geotrigger.Device.post_update | def post_update
post_data = @data.dup
case @session.type
when :application
post_data['deviceIds'] = post_data.delete 'deviceId'
when :device
post_data.delete 'deviceId'
end
post_data.delete 'tags'
post_data.delete 'lastSeen'
grok_self_from post 'device/update', post_data
self
end | ruby | def post_update
post_data = @data.dup
case @session.type
when :application
post_data['deviceIds'] = post_data.delete 'deviceId'
when :device
post_data.delete 'deviceId'
end
post_data.delete 'tags'
post_data.delete 'lastSeen'
grok_self_from post 'device/update', post_data
self
end | [
"def",
"post_update",
"post_data",
"=",
"@data",
".",
"dup",
"case",
"@session",
".",
"type",
"when",
":application",
"post_data",
"[",
"'deviceIds'",
"]",
"=",
"post_data",
".",
"delete",
"'deviceId'",
"when",
":device",
"post_data",
".",
"delete",
"'deviceId'",
"end",
"post_data",
".",
"delete",
"'tags'",
"post_data",
".",
"delete",
"'lastSeen'",
"grok_self_from",
"post",
"'device/update'",
",",
"post_data",
"self",
"end"
] | POST the device's +@data+ to the API via 'device/update', and return
the same object with the new +@data+ returned from API call. | [
"POST",
"the",
"device",
"s",
"+"
] | 41fbac4a25ec43427a51dc235a0dbc158e80ce02 | https://github.com/Esri/geotrigger-ruby/blob/41fbac4a25ec43427a51dc235a0dbc158e80ce02/lib/geotrigger/device.rb#L44-L57 | train |
AnkurGel/dictionary-rb | lib/dictionary-rb/urban.rb | DictionaryRB.Urban.meanings | def meanings
url = PREFIX + CGI::escape(@word)
@doc ||= Nokogiri::HTML(open(url))
#nodes = @doc.css('div#outer.container div.row.three_columns div.span6 div#content div.box div.inner div.meaning')
nodes = @doc.css('.meaning')
results = nodes.map(&:text).map(&:strip).reject(&:empty?)
@meaning = results.first
results
end | ruby | def meanings
url = PREFIX + CGI::escape(@word)
@doc ||= Nokogiri::HTML(open(url))
#nodes = @doc.css('div#outer.container div.row.three_columns div.span6 div#content div.box div.inner div.meaning')
nodes = @doc.css('.meaning')
results = nodes.map(&:text).map(&:strip).reject(&:empty?)
@meaning = results.first
results
end | [
"def",
"meanings",
"url",
"=",
"PREFIX",
"+",
"CGI",
"::",
"escape",
"(",
"@word",
")",
"@doc",
"||=",
"Nokogiri",
"::",
"HTML",
"(",
"open",
"(",
"url",
")",
")",
"nodes",
"=",
"@doc",
".",
"css",
"(",
"'.meaning'",
")",
"results",
"=",
"nodes",
".",
"map",
"(",
"&",
":text",
")",
".",
"map",
"(",
"&",
":strip",
")",
".",
"reject",
"(",
"&",
":empty?",
")",
"@meaning",
"=",
"results",
".",
"first",
"results",
"end"
] | Fetches and gives meanings for the word from Urban Dictionary
@example
word.meanings
#=> ["A fuck, nothing more, just a fuck",
"Describes someone as being the sexiest beast alive. Anyone who is blessed with the name Krunal should get a medal.",..]
@see #meaning
@return [Array] containing the meanings for the word. | [
"Fetches",
"and",
"gives",
"meanings",
"for",
"the",
"word",
"from",
"Urban",
"Dictionary"
] | 92566325aee598f46b584817373017e6097300b4 | https://github.com/AnkurGel/dictionary-rb/blob/92566325aee598f46b584817373017e6097300b4/lib/dictionary-rb/urban.rb#L39-L48 | train |
dpla/KriKri | lib/krikri/mapper.rb | Krikri.Mapper.define | def define(name, opts = {}, &block)
klass = opts.fetch(:class, DPLA::MAP::Aggregation)
parser = opts.fetch(:parser, Krikri::XmlParser)
parser_args = opts.fetch(:parser_args, nil)
map = Krikri::Mapping.new(klass, parser, *parser_args)
map.instance_eval(&block) if block_given?
Registry.register!(name, map)
end | ruby | def define(name, opts = {}, &block)
klass = opts.fetch(:class, DPLA::MAP::Aggregation)
parser = opts.fetch(:parser, Krikri::XmlParser)
parser_args = opts.fetch(:parser_args, nil)
map = Krikri::Mapping.new(klass, parser, *parser_args)
map.instance_eval(&block) if block_given?
Registry.register!(name, map)
end | [
"def",
"define",
"(",
"name",
",",
"opts",
"=",
"{",
"}",
",",
"&",
"block",
")",
"klass",
"=",
"opts",
".",
"fetch",
"(",
":class",
",",
"DPLA",
"::",
"MAP",
"::",
"Aggregation",
")",
"parser",
"=",
"opts",
".",
"fetch",
"(",
":parser",
",",
"Krikri",
"::",
"XmlParser",
")",
"parser_args",
"=",
"opts",
".",
"fetch",
"(",
":parser_args",
",",
"nil",
")",
"map",
"=",
"Krikri",
"::",
"Mapping",
".",
"new",
"(",
"klass",
",",
"parser",
",",
"*",
"parser_args",
")",
"map",
".",
"instance_eval",
"(",
"&",
"block",
")",
"if",
"block_given?",
"Registry",
".",
"register!",
"(",
"name",
",",
"map",
")",
"end"
] | Creates mappings and passes DSL methods through to them, then adds them to
a global registry.
@param name [Symbol] a unique name for the mapper in the registry.
@param opts [Hash] options to pass to the mapping instance, options are:
:class, :parser, and :parser_args
@yield A block passed through to the mapping instance containing the
mapping in the language specified by MappingDSL | [
"Creates",
"mappings",
"and",
"passes",
"DSL",
"methods",
"through",
"to",
"them",
"then",
"adds",
"them",
"to",
"a",
"global",
"registry",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/mapper.rb#L40-L47 | train |
dpla/KriKri | lib/krikri/harvester.rb | Krikri.Harvester.run | def run(activity_uri = nil)
records.each do |rec|
next if rec.nil?
begin
process_record(rec, activity_uri)
rescue => e
Krikri::Logger.log :error, "Error harvesting record:\n" \
"#{rec.content}\n\twith message:\n"\
"#{e.message}"
next
end
end
true
end | ruby | def run(activity_uri = nil)
records.each do |rec|
next if rec.nil?
begin
process_record(rec, activity_uri)
rescue => e
Krikri::Logger.log :error, "Error harvesting record:\n" \
"#{rec.content}\n\twith message:\n"\
"#{e.message}"
next
end
end
true
end | [
"def",
"run",
"(",
"activity_uri",
"=",
"nil",
")",
"records",
".",
"each",
"do",
"|",
"rec",
"|",
"next",
"if",
"rec",
".",
"nil?",
"begin",
"process_record",
"(",
"rec",
",",
"activity_uri",
")",
"rescue",
"=>",
"e",
"Krikri",
"::",
"Logger",
".",
"log",
":error",
",",
"\"Error harvesting record:\\n\"",
"\"#{rec.content}\\n\\twith message:\\n\"",
"\"#{e.message}\"",
"next",
"end",
"end",
"true",
"end"
] | Run the harvest.
Individual records are processed through `#process_record` which is
delegated to the harvester's `@harvest_behavior` by default.
@return [Boolean]
@see Krirki::Harvesters:HarvestBehavior | [
"Run",
"the",
"harvest",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/harvester.rb#L131-L144 | train |
dpla/KriKri | lib/krikri/provenance_query_client.rb | Krikri.ProvenanceQueryClient.find_by_activity | def find_by_activity(activity_uri, include_invalidated = false)
raise ArgumentError, 'activity_uri must be an RDF::URI' unless
activity_uri.respond_to? :to_term
query = SPARQL_CLIENT.select(:record)
.where([:record,
[RDF::PROV.wasGeneratedBy, '|', RDF::DPLA.wasRevisedBy],
activity_uri.to_term])
if include_invalidated
query
else
# We need to say "and if RDF::PROV.invalidatedAtTime is not set."
#
# The SPARQL query should be:
#
# PREFIX prov: <http://www.w3.org/ns/prov#>
# SELECT * WHERE {
# ?subject prov:wasGeneratedBy <http://xampl.org/ldp/activity/n> .
# FILTER NOT EXISTS { ?subject prov:invalidatedAtTime ?x }
# }
#
# ... However there doesn't appear to be a way of constructing
# 'FILTER NOT EXISTS' with SPARQL::Client. Instead, we've managed to
# hack the following solution together.
#
# SPARQL::Client#filter is labeled @private in its YARD comment (and
# has no other documentation) but it's not private, at least for
# now.
query.filter \
'NOT EXISTS ' \
'{ ?record <http://www.w3.org/ns/prov#invalidatedAtTime> ?x }'
end
end | ruby | def find_by_activity(activity_uri, include_invalidated = false)
raise ArgumentError, 'activity_uri must be an RDF::URI' unless
activity_uri.respond_to? :to_term
query = SPARQL_CLIENT.select(:record)
.where([:record,
[RDF::PROV.wasGeneratedBy, '|', RDF::DPLA.wasRevisedBy],
activity_uri.to_term])
if include_invalidated
query
else
# We need to say "and if RDF::PROV.invalidatedAtTime is not set."
#
# The SPARQL query should be:
#
# PREFIX prov: <http://www.w3.org/ns/prov#>
# SELECT * WHERE {
# ?subject prov:wasGeneratedBy <http://xampl.org/ldp/activity/n> .
# FILTER NOT EXISTS { ?subject prov:invalidatedAtTime ?x }
# }
#
# ... However there doesn't appear to be a way of constructing
# 'FILTER NOT EXISTS' with SPARQL::Client. Instead, we've managed to
# hack the following solution together.
#
# SPARQL::Client#filter is labeled @private in its YARD comment (and
# has no other documentation) but it's not private, at least for
# now.
query.filter \
'NOT EXISTS ' \
'{ ?record <http://www.w3.org/ns/prov#invalidatedAtTime> ?x }'
end
end | [
"def",
"find_by_activity",
"(",
"activity_uri",
",",
"include_invalidated",
"=",
"false",
")",
"raise",
"ArgumentError",
",",
"'activity_uri must be an RDF::URI'",
"unless",
"activity_uri",
".",
"respond_to?",
":to_term",
"query",
"=",
"SPARQL_CLIENT",
".",
"select",
"(",
":record",
")",
".",
"where",
"(",
"[",
":record",
",",
"[",
"RDF",
"::",
"PROV",
".",
"wasGeneratedBy",
",",
"'|'",
",",
"RDF",
"::",
"DPLA",
".",
"wasRevisedBy",
"]",
",",
"activity_uri",
".",
"to_term",
"]",
")",
"if",
"include_invalidated",
"query",
"else",
"query",
".",
"filter",
"'NOT EXISTS '",
"'{ ?record <http://www.w3.org/ns/prov#invalidatedAtTime> ?x }'",
"end",
"end"
] | Finds all entities generated or revised by the activity whose URI is
given.
@param activity_uri [#to_uri] the URI of the activity to search
@param include_invalidated [Boolean] Whether to include entities that
have been invalidated with <http://www.w3.org/ns/prov#invalidatedAtTime>
@see https://www.w3.org/TR/prov-o/#invalidatedAtTime
@see Krikri::LDP::Invalidatable
@return [RDF::SPARQL::Query] a query object that, when executed, will
give solutions containing the URIs for the resources in `#record`. | [
"Finds",
"all",
"entities",
"generated",
"or",
"revised",
"by",
"the",
"activity",
"whose",
"URI",
"is",
"given",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/provenance_query_client.rb#L23-L55 | train |
estiens/nanoleaf_ruby | lib/nanoleaf_ruby.rb | NanoleafRuby.Api.ct_increment | def ct_increment(increment = 1)
params = { ct: {} }
params[:ct][:increment] = increment
@requester.put(url: "#{@api_url}/state", params: params)
end | ruby | def ct_increment(increment = 1)
params = { ct: {} }
params[:ct][:increment] = increment
@requester.put(url: "#{@api_url}/state", params: params)
end | [
"def",
"ct_increment",
"(",
"increment",
"=",
"1",
")",
"params",
"=",
"{",
"ct",
":",
"{",
"}",
"}",
"params",
"[",
":ct",
"]",
"[",
":increment",
"]",
"=",
"increment",
"@requester",
".",
"put",
"(",
"url",
":",
"\"#{@api_url}/state\"",
",",
"params",
":",
"params",
")",
"end"
] | color temperature commands | [
"color",
"temperature",
"commands"
] | 3ab1d4646e01026c174084816e9642f16aedcca9 | https://github.com/estiens/nanoleaf_ruby/blob/3ab1d4646e01026c174084816e9642f16aedcca9/lib/nanoleaf_ruby.rb#L101-L105 | train |
opentox/qsar-report | lib/qmrf-report.rb | OpenTox.QMRFReport.change_catalog | def change_catalog catalog, id, valuehash
catalog_exists? catalog
if @report.at_css("#{catalog}").at("[@id='#{id}']")
valuehash.each do |key, value|
@report.at_css("#{catalog}").at("[@id='#{id}']")["#{key}"]= value
end
else
cat = @report.at_css("#{catalog}")
newentry = Nokogiri::XML::Node.new("#{catalog.to_s.gsub(/s?_catalog/,'')}", self.report)
newentry["id"] = id
valuehash.each do |key, value|
newentry["#{key}"] = value
end
cat << newentry
end
end | ruby | def change_catalog catalog, id, valuehash
catalog_exists? catalog
if @report.at_css("#{catalog}").at("[@id='#{id}']")
valuehash.each do |key, value|
@report.at_css("#{catalog}").at("[@id='#{id}']")["#{key}"]= value
end
else
cat = @report.at_css("#{catalog}")
newentry = Nokogiri::XML::Node.new("#{catalog.to_s.gsub(/s?_catalog/,'')}", self.report)
newentry["id"] = id
valuehash.each do |key, value|
newentry["#{key}"] = value
end
cat << newentry
end
end | [
"def",
"change_catalog",
"catalog",
",",
"id",
",",
"valuehash",
"catalog_exists?",
"catalog",
"if",
"@report",
".",
"at_css",
"(",
"\"#{catalog}\"",
")",
".",
"at",
"(",
"\"[@id='#{id}']\"",
")",
"valuehash",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"@report",
".",
"at_css",
"(",
"\"#{catalog}\"",
")",
".",
"at",
"(",
"\"[@id='#{id}']\"",
")",
"[",
"\"#{key}\"",
"]",
"=",
"value",
"end",
"else",
"cat",
"=",
"@report",
".",
"at_css",
"(",
"\"#{catalog}\"",
")",
"newentry",
"=",
"Nokogiri",
"::",
"XML",
"::",
"Node",
".",
"new",
"(",
"\"#{catalog.to_s.gsub(/s?_catalog/,'')}\"",
",",
"self",
".",
"report",
")",
"newentry",
"[",
"\"id\"",
"]",
"=",
"id",
"valuehash",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"newentry",
"[",
"\"#{key}\"",
"]",
"=",
"value",
"end",
"cat",
"<<",
"newentry",
"end",
"end"
] | Change a catalog
@param [String] catalog Name of the catalog - One of {OpenTox::QMRFReport::CATALOGS CATALOGS}.
@param [String] id Single entry node in the catalog e.G.: "<software contact='[email protected]' description="My QSAR Software " id="software_catalog_2" name="MySoftware" number="" url="https://mydomain.dom"/>
@param [Hash] valuehash Key-Value Hash with attributes for a single catalog node
@return [Error] returns Error message if fails | [
"Change",
"a",
"catalog"
] | 2b1074342284fbaa5403dd95f970e089f1ace5a6 | https://github.com/opentox/qsar-report/blob/2b1074342284fbaa5403dd95f970e089f1ace5a6/lib/qmrf-report.rb#L89-L104 | train |
opentox/qsar-report | lib/qmrf-report.rb | OpenTox.QMRFReport.get_catalog_value | def get_catalog_value catalog, id, key
catalog_exists? catalog
if @report.at_css("#{catalog}").at("[@id='#{id}']")
@report.at_css("#{catalog}").at("[@id='#{id}']")["#{key}"]
else
return false
end
end | ruby | def get_catalog_value catalog, id, key
catalog_exists? catalog
if @report.at_css("#{catalog}").at("[@id='#{id}']")
@report.at_css("#{catalog}").at("[@id='#{id}']")["#{key}"]
else
return false
end
end | [
"def",
"get_catalog_value",
"catalog",
",",
"id",
",",
"key",
"catalog_exists?",
"catalog",
"if",
"@report",
".",
"at_css",
"(",
"\"#{catalog}\"",
")",
".",
"at",
"(",
"\"[@id='#{id}']\"",
")",
"@report",
".",
"at_css",
"(",
"\"#{catalog}\"",
")",
".",
"at",
"(",
"\"[@id='#{id}']\"",
")",
"[",
"\"#{key}\"",
"]",
"else",
"return",
"false",
"end",
"end"
] | get an attribute from a catalog entry
@param [String] catalog Name of the catalog. One of {OpenTox::QMRFReport::CATALOGS CATALOGS}.
@param [String] id entry id in the catalog
@param [String] key returns value of a key in a catalog node
@return [String, false] returns value of a key in a catalog node or false if catalog entry do not exists. | [
"get",
"an",
"attribute",
"from",
"a",
"catalog",
"entry"
] | 2b1074342284fbaa5403dd95f970e089f1ace5a6 | https://github.com/opentox/qsar-report/blob/2b1074342284fbaa5403dd95f970e089f1ace5a6/lib/qmrf-report.rb#L132-L139 | train |
dpla/KriKri | app/helpers/krikri/application_helper.rb | Krikri.ApplicationHelper.link_to_current_page_by_provider | def link_to_current_page_by_provider(provider)
provider = Krikri::Provider.find(provider) if provider.is_a? String
return link_to_provider_page(provider) if params[:controller] ==
'krikri/providers'
params[:provider] = provider.id
params[:session_provider] = provider.id
link_to provider_name(provider), params
end | ruby | def link_to_current_page_by_provider(provider)
provider = Krikri::Provider.find(provider) if provider.is_a? String
return link_to_provider_page(provider) if params[:controller] ==
'krikri/providers'
params[:provider] = provider.id
params[:session_provider] = provider.id
link_to provider_name(provider), params
end | [
"def",
"link_to_current_page_by_provider",
"(",
"provider",
")",
"provider",
"=",
"Krikri",
"::",
"Provider",
".",
"find",
"(",
"provider",
")",
"if",
"provider",
".",
"is_a?",
"String",
"return",
"link_to_provider_page",
"(",
"provider",
")",
"if",
"params",
"[",
":controller",
"]",
"==",
"'krikri/providers'",
"params",
"[",
":provider",
"]",
"=",
"provider",
".",
"id",
"params",
"[",
":session_provider",
"]",
"=",
"provider",
".",
"id",
"link_to",
"provider_name",
"(",
"provider",
")",
",",
"params",
"end"
] | Link to the current page, changing the session provider the given
value.
@param provider [String, nil] | [
"Link",
"to",
"the",
"current",
"page",
"changing",
"the",
"session",
"provider",
"the",
"given",
"value",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/app/helpers/krikri/application_helper.rb#L37-L45 | train |
schrodingersbox/meter_cat | app/helpers/meter_cat/meters_helper.rb | MeterCat.MetersHelper.meter_description | def meter_description(name)
content_tag(:p) do
concat content_tag(:b, name)
concat ' - '
concat t(name, scope: :meter_cat)
end
end | ruby | def meter_description(name)
content_tag(:p) do
concat content_tag(:b, name)
concat ' - '
concat t(name, scope: :meter_cat)
end
end | [
"def",
"meter_description",
"(",
"name",
")",
"content_tag",
"(",
":p",
")",
"do",
"concat",
"content_tag",
"(",
":b",
",",
"name",
")",
"concat",
"' - '",
"concat",
"t",
"(",
"name",
",",
"scope",
":",
":meter_cat",
")",
"end",
"end"
] | Constructs a single meter description | [
"Constructs",
"a",
"single",
"meter",
"description"
] | b20d579749ef2facbf3b308d4fb39215a7eac2a1 | https://github.com/schrodingersbox/meter_cat/blob/b20d579749ef2facbf3b308d4fb39215a7eac2a1/app/helpers/meter_cat/meters_helper.rb#L6-L12 | train |
schrodingersbox/meter_cat | app/helpers/meter_cat/meters_helper.rb | MeterCat.MetersHelper.meter_descriptions | def meter_descriptions(meters)
content_tag(:ul) do
meters.keys.sort.each do |name|
concat content_tag(:li, meter_description(name))
end
end
end | ruby | def meter_descriptions(meters)
content_tag(:ul) do
meters.keys.sort.each do |name|
concat content_tag(:li, meter_description(name))
end
end
end | [
"def",
"meter_descriptions",
"(",
"meters",
")",
"content_tag",
"(",
":ul",
")",
"do",
"meters",
".",
"keys",
".",
"sort",
".",
"each",
"do",
"|",
"name",
"|",
"concat",
"content_tag",
"(",
":li",
",",
"meter_description",
"(",
"name",
")",
")",
"end",
"end",
"end"
] | Constructs a list of meter descriptions | [
"Constructs",
"a",
"list",
"of",
"meter",
"descriptions"
] | b20d579749ef2facbf3b308d4fb39215a7eac2a1 | https://github.com/schrodingersbox/meter_cat/blob/b20d579749ef2facbf3b308d4fb39215a7eac2a1/app/helpers/meter_cat/meters_helper.rb#L16-L22 | train |
schrodingersbox/meter_cat | app/helpers/meter_cat/meters_helper.rb | MeterCat.MetersHelper.meter_form | def meter_form(date, days, names, all_names)
render partial: 'form', locals: { date: date, days: days, names: names, all_names: all_names }
end | ruby | def meter_form(date, days, names, all_names)
render partial: 'form', locals: { date: date, days: days, names: names, all_names: all_names }
end | [
"def",
"meter_form",
"(",
"date",
",",
"days",
",",
"names",
",",
"all_names",
")",
"render",
"partial",
":",
"'form'",
",",
"locals",
":",
"{",
"date",
":",
"date",
",",
"days",
":",
"days",
",",
"names",
":",
"names",
",",
"all_names",
":",
"all_names",
"}",
"end"
] | Renders the _form partial with locals | [
"Renders",
"the",
"_form",
"partial",
"with",
"locals"
] | b20d579749ef2facbf3b308d4fb39215a7eac2a1 | https://github.com/schrodingersbox/meter_cat/blob/b20d579749ef2facbf3b308d4fb39215a7eac2a1/app/helpers/meter_cat/meters_helper.rb#L26-L28 | train |
gurix/helena_administration | app/helpers/helena_administration/application_helper.rb | HelenaAdministration.ApplicationHelper.truncate_between | def truncate_between(str, after = 30)
str = '' if str.nil?
str.length > after ? "#{str[0..(after / 2) - 2]}...#{str[(str.length - ((after / 2) - 2))..str.length]}" : str
end | ruby | def truncate_between(str, after = 30)
str = '' if str.nil?
str.length > after ? "#{str[0..(after / 2) - 2]}...#{str[(str.length - ((after / 2) - 2))..str.length]}" : str
end | [
"def",
"truncate_between",
"(",
"str",
",",
"after",
"=",
"30",
")",
"str",
"=",
"''",
"if",
"str",
".",
"nil?",
"str",
".",
"length",
">",
"after",
"?",
"\"#{str[0..(after / 2) - 2]}...#{str[(str.length - ((after / 2) - 2))..str.length]}\"",
":",
"str",
"end"
] | adds ... in between like if you have to long names in apple finder so you can i.e see the beginning and the suffix | [
"adds",
"...",
"in",
"between",
"like",
"if",
"you",
"have",
"to",
"long",
"names",
"in",
"apple",
"finder",
"so",
"you",
"can",
"i",
".",
"e",
"see",
"the",
"beginning",
"and",
"the",
"suffix"
] | d7c5019b3c741a882a3d2192950cdfd92ab72faa | https://github.com/gurix/helena_administration/blob/d7c5019b3c741a882a3d2192950cdfd92ab72faa/app/helpers/helena_administration/application_helper.rb#L9-L12 | train |
Esri/geotrigger-ruby | lib/geotrigger/session.rb | Geotrigger.Session.post | def post path, params = {}, other_headers = {}
r = @hc.post BASE_URL % path, params.to_json, headers(other_headers)
raise GeotriggerError.new r.body unless r.status == 200
h = JSON.parse r.body
raise_error h['error'] if h['error']
h
end | ruby | def post path, params = {}, other_headers = {}
r = @hc.post BASE_URL % path, params.to_json, headers(other_headers)
raise GeotriggerError.new r.body unless r.status == 200
h = JSON.parse r.body
raise_error h['error'] if h['error']
h
end | [
"def",
"post",
"path",
",",
"params",
"=",
"{",
"}",
",",
"other_headers",
"=",
"{",
"}",
"r",
"=",
"@hc",
".",
"post",
"BASE_URL",
"%",
"path",
",",
"params",
".",
"to_json",
",",
"headers",
"(",
"other_headers",
")",
"raise",
"GeotriggerError",
".",
"new",
"r",
".",
"body",
"unless",
"r",
".",
"status",
"==",
"200",
"h",
"=",
"JSON",
".",
"parse",
"r",
".",
"body",
"raise_error",
"h",
"[",
"'error'",
"]",
"if",
"h",
"[",
"'error'",
"]",
"h",
"end"
] | POST an API request to the given path, with optional params and
headers. Returns a normal Ruby +Hash+ of the response data.
[params] +Hash+ parameters to include in the request (will be converted to JSON)
[other_headers] +Hash+ headers to include in the request in addition to the defaults. | [
"POST",
"an",
"API",
"request",
"to",
"the",
"given",
"path",
"with",
"optional",
"params",
"and",
"headers",
".",
"Returns",
"a",
"normal",
"Ruby",
"+",
"Hash",
"+",
"of",
"the",
"response",
"data",
"."
] | 41fbac4a25ec43427a51dc235a0dbc158e80ce02 | https://github.com/Esri/geotrigger-ruby/blob/41fbac4a25ec43427a51dc235a0dbc158e80ce02/lib/geotrigger/session.rb#L125-L131 | train |
Esri/geotrigger-ruby | lib/geotrigger/session.rb | Geotrigger.Session.raise_error | def raise_error error
ge = GeotriggerError.new error['message']
ge.code = error['code']
ge.headers = error['headers']
ge.message = error['message']
ge.parameters = error['parameters']
jj error
raise ge
end | ruby | def raise_error error
ge = GeotriggerError.new error['message']
ge.code = error['code']
ge.headers = error['headers']
ge.message = error['message']
ge.parameters = error['parameters']
jj error
raise ge
end | [
"def",
"raise_error",
"error",
"ge",
"=",
"GeotriggerError",
".",
"new",
"error",
"[",
"'message'",
"]",
"ge",
".",
"code",
"=",
"error",
"[",
"'code'",
"]",
"ge",
".",
"headers",
"=",
"error",
"[",
"'headers'",
"]",
"ge",
".",
"message",
"=",
"error",
"[",
"'message'",
"]",
"ge",
".",
"parameters",
"=",
"error",
"[",
"'parameters'",
"]",
"jj",
"error",
"raise",
"ge",
"end"
] | Creates and raises a +GeotriggerError+ from an API error response. | [
"Creates",
"and",
"raises",
"a",
"+",
"GeotriggerError",
"+",
"from",
"an",
"API",
"error",
"response",
"."
] | 41fbac4a25ec43427a51dc235a0dbc158e80ce02 | https://github.com/Esri/geotrigger-ruby/blob/41fbac4a25ec43427a51dc235a0dbc158e80ce02/lib/geotrigger/session.rb#L135-L143 | train |
dpla/KriKri | lib/krikri/enrichments/split_coordinates.rb | Krikri::Enrichments.SplitCoordinates.coord_values | def coord_values(s)
coords = s.split(/ *, */)
return [nil, nil] if coords.size != 2
coords.map! { |c| c.to_f.to_s == c ? c : nil } # must be decimal ...
return [nil, nil] unless coords[0] && coords[1] # ... i.e. not nil
[coords[0], coords[1]]
end | ruby | def coord_values(s)
coords = s.split(/ *, */)
return [nil, nil] if coords.size != 2
coords.map! { |c| c.to_f.to_s == c ? c : nil } # must be decimal ...
return [nil, nil] unless coords[0] && coords[1] # ... i.e. not nil
[coords[0], coords[1]]
end | [
"def",
"coord_values",
"(",
"s",
")",
"coords",
"=",
"s",
".",
"split",
"(",
"/",
"/",
")",
"return",
"[",
"nil",
",",
"nil",
"]",
"if",
"coords",
".",
"size",
"!=",
"2",
"coords",
".",
"map!",
"{",
"|",
"c",
"|",
"c",
".",
"to_f",
".",
"to_s",
"==",
"c",
"?",
"c",
":",
"nil",
"}",
"return",
"[",
"nil",
",",
"nil",
"]",
"unless",
"coords",
"[",
"0",
"]",
"&&",
"coords",
"[",
"1",
"]",
"[",
"coords",
"[",
"0",
"]",
",",
"coords",
"[",
"1",
"]",
"]",
"end"
] | Given a String `s', return an array of two elements split on a comma
and any whitespace around the comma.
If the string does not split into two strings representing decimal
values, then return [nil, nil] because the string does not make sense as
coordinates.
@param s [String] String of, hopefully, comma-separated decimals
@return [Array] | [
"Given",
"a",
"String",
"s",
"return",
"an",
"array",
"of",
"two",
"elements",
"split",
"on",
"a",
"comma",
"and",
"any",
"whitespace",
"around",
"the",
"comma",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/enrichments/split_coordinates.rb#L60-L66 | train |
nofxx/rspec_spinner | lib/rspec_spinner/base.rb | RspecSpinner.RspecSpinnerBase.example_pending | def example_pending(example, message, deprecated_pending_location=nil)
immediately_dump_pending(example.description, message, example.location)
mark_error_state_pending
increment
end | ruby | def example_pending(example, message, deprecated_pending_location=nil)
immediately_dump_pending(example.description, message, example.location)
mark_error_state_pending
increment
end | [
"def",
"example_pending",
"(",
"example",
",",
"message",
",",
"deprecated_pending_location",
"=",
"nil",
")",
"immediately_dump_pending",
"(",
"example",
".",
"description",
",",
"message",
",",
"example",
".",
"location",
")",
"mark_error_state_pending",
"increment",
"end"
] | third param is optional, because earlier versions of rspec sent only two args | [
"third",
"param",
"is",
"optional",
"because",
"earlier",
"versions",
"of",
"rspec",
"sent",
"only",
"two",
"args"
] | eeea8961197e07ad46f71442fc0dd79c1ea26ed3 | https://github.com/nofxx/rspec_spinner/blob/eeea8961197e07ad46f71442fc0dd79c1ea26ed3/lib/rspec_spinner/base.rb#L46-L50 | train |
dpla/KriKri | lib/krikri/ldp/resource.rb | Krikri::LDP.Resource.make_request | def make_request(method, body = nil, headers = {})
validate_subject
ldp_connection.send(method) do |request|
request.url rdf_subject
request.headers = headers if headers
request.body = body
end
end | ruby | def make_request(method, body = nil, headers = {})
validate_subject
ldp_connection.send(method) do |request|
request.url rdf_subject
request.headers = headers if headers
request.body = body
end
end | [
"def",
"make_request",
"(",
"method",
",",
"body",
"=",
"nil",
",",
"headers",
"=",
"{",
"}",
")",
"validate_subject",
"ldp_connection",
".",
"send",
"(",
"method",
")",
"do",
"|",
"request",
"|",
"request",
".",
"url",
"rdf_subject",
"request",
".",
"headers",
"=",
"headers",
"if",
"headers",
"request",
".",
"body",
"=",
"body",
"end",
"end"
] | Lightly wraps Faraday to manage requests of various types, their bodies
and headers.
@param method [Symbol] HTTP method/verb.
@param body [#to_s] the request body.
@param headers [Hash<String, String>] a hash of HTTP headers;
e.g. {'Content-Type' => 'text/plain'}.
@raise [Faraday::ClientError] if the server responds with an error status.
Faraday::ClientError#response contains the full response.
@return [Faraday::Response] the server's response | [
"Lightly",
"wraps",
"Faraday",
"to",
"manage",
"requests",
"of",
"various",
"types",
"their",
"bodies",
"and",
"headers",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/ldp/resource.rb#L154-L161 | train |
dpla/KriKri | app/controllers/krikri/providers_controller.rb | Krikri.ProvidersController.show | def show
if params[:set_session]
session[:current_provider] = params[:id]
redirect_to :back, provider: params[:id]
elsif params[:clear_session]
session.delete :current_provider
redirect_to providers_path
end
@current_provider = Krikri::Provider.find(params[:id])
end | ruby | def show
if params[:set_session]
session[:current_provider] = params[:id]
redirect_to :back, provider: params[:id]
elsif params[:clear_session]
session.delete :current_provider
redirect_to providers_path
end
@current_provider = Krikri::Provider.find(params[:id])
end | [
"def",
"show",
"if",
"params",
"[",
":set_session",
"]",
"session",
"[",
":current_provider",
"]",
"=",
"params",
"[",
":id",
"]",
"redirect_to",
":back",
",",
"provider",
":",
"params",
"[",
":id",
"]",
"elsif",
"params",
"[",
":clear_session",
"]",
"session",
".",
"delete",
":current_provider",
"redirect_to",
"providers_path",
"end",
"@current_provider",
"=",
"Krikri",
"::",
"Provider",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"end"
] | Renders the show view for the provider given by `id`. | [
"Renders",
"the",
"show",
"view",
"for",
"the",
"provider",
"given",
"by",
"id",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/app/controllers/krikri/providers_controller.rb#L16-L25 | train |
Fluxx/distillery | lib/distillery/document.rb | Distillery.Document.remove_unlikely_elements! | def remove_unlikely_elements!
search('*').each do |element|
idclass = "#{element['class']}#{element['id']}"
if idclass =~ UNLIKELY_IDENTIFIERS && !REMOVAL_WHITELIST.include?(element.name)
element.remove
end
end
end | ruby | def remove_unlikely_elements!
search('*').each do |element|
idclass = "#{element['class']}#{element['id']}"
if idclass =~ UNLIKELY_IDENTIFIERS && !REMOVAL_WHITELIST.include?(element.name)
element.remove
end
end
end | [
"def",
"remove_unlikely_elements!",
"search",
"(",
"'*'",
")",
".",
"each",
"do",
"|",
"element",
"|",
"idclass",
"=",
"\"#{element['class']}#{element['id']}\"",
"if",
"idclass",
"=~",
"UNLIKELY_IDENTIFIERS",
"&&",
"!",
"REMOVAL_WHITELIST",
".",
"include?",
"(",
"element",
".",
"name",
")",
"element",
".",
"remove",
"end",
"end",
"end"
] | Removes unlikely elements from the document. These are elements who have classes
that seem to indicate they are comments, headers, footers, nav, etc | [
"Removes",
"unlikely",
"elements",
"from",
"the",
"document",
".",
"These",
"are",
"elements",
"who",
"have",
"classes",
"that",
"seem",
"to",
"indicate",
"they",
"are",
"comments",
"headers",
"footers",
"nav",
"etc"
] | 5d6dfb430398e1c092d65edc305b9c77dda1532b | https://github.com/Fluxx/distillery/blob/5d6dfb430398e1c092d65edc305b9c77dda1532b/lib/distillery/document.rb#L61-L69 | train |
Fluxx/distillery | lib/distillery/document.rb | Distillery.Document.score! | def score!
mark_scorable_elements!
scorable_elements.each do |element|
points = 1
points += element.text.split(',').length
points += [element.text.length / 100, 3].min
scores[element.path] = points
scores[element.parent.path] += points
scores[element.parent.parent.path] += points.to_f/2
end
augment_scores_by_link_weight!
end | ruby | def score!
mark_scorable_elements!
scorable_elements.each do |element|
points = 1
points += element.text.split(',').length
points += [element.text.length / 100, 3].min
scores[element.path] = points
scores[element.parent.path] += points
scores[element.parent.parent.path] += points.to_f/2
end
augment_scores_by_link_weight!
end | [
"def",
"score!",
"mark_scorable_elements!",
"scorable_elements",
".",
"each",
"do",
"|",
"element",
"|",
"points",
"=",
"1",
"points",
"+=",
"element",
".",
"text",
".",
"split",
"(",
"','",
")",
".",
"length",
"points",
"+=",
"[",
"element",
".",
"text",
".",
"length",
"/",
"100",
",",
"3",
"]",
".",
"min",
"scores",
"[",
"element",
".",
"path",
"]",
"=",
"points",
"scores",
"[",
"element",
".",
"parent",
".",
"path",
"]",
"+=",
"points",
"scores",
"[",
"element",
".",
"parent",
".",
"parent",
".",
"path",
"]",
"+=",
"points",
".",
"to_f",
"/",
"2",
"end",
"augment_scores_by_link_weight!",
"end"
] | Scores the document elements based on an algorithm to find elements which hold page
content. | [
"Scores",
"the",
"document",
"elements",
"based",
"on",
"an",
"algorithm",
"to",
"find",
"elements",
"which",
"hold",
"page",
"content",
"."
] | 5d6dfb430398e1c092d65edc305b9c77dda1532b | https://github.com/Fluxx/distillery/blob/5d6dfb430398e1c092d65edc305b9c77dda1532b/lib/distillery/document.rb#L82-L96 | train |
Fluxx/distillery | lib/distillery/document.rb | Distillery.Document.distill! | def distill!(options = {})
remove_irrelevant_elements!
remove_unlikely_elements!
score!
clean_top_scoring_elements!(options) unless options.delete(:clean) == false
top_scoring_elements.map(&:inner_html).join("\n")
end | ruby | def distill!(options = {})
remove_irrelevant_elements!
remove_unlikely_elements!
score!
clean_top_scoring_elements!(options) unless options.delete(:clean) == false
top_scoring_elements.map(&:inner_html).join("\n")
end | [
"def",
"distill!",
"(",
"options",
"=",
"{",
"}",
")",
"remove_irrelevant_elements!",
"remove_unlikely_elements!",
"score!",
"clean_top_scoring_elements!",
"(",
"options",
")",
"unless",
"options",
".",
"delete",
"(",
":clean",
")",
"==",
"false",
"top_scoring_elements",
".",
"map",
"(",
"&",
":inner_html",
")",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] | Distills the document down to just its content.
@param [Hash] options Distillation options
@option options [Symbol] :dirty Do not clean the content element HTML | [
"Distills",
"the",
"document",
"down",
"to",
"just",
"its",
"content",
"."
] | 5d6dfb430398e1c092d65edc305b9c77dda1532b | https://github.com/Fluxx/distillery/blob/5d6dfb430398e1c092d65edc305b9c77dda1532b/lib/distillery/document.rb#L102-L110 | train |
Fluxx/distillery | lib/distillery/document.rb | Distillery.Document.clean_top_scoring_elements! | def clean_top_scoring_elements!(options = {})
keep_images = !!options[:images]
top_scoring_elements.each do |element|
element.search("*").each do |node|
if cleanable?(node, keep_images)
debugger if node.to_s =~ /maximum flavor/
node.remove
end
end
end
end | ruby | def clean_top_scoring_elements!(options = {})
keep_images = !!options[:images]
top_scoring_elements.each do |element|
element.search("*").each do |node|
if cleanable?(node, keep_images)
debugger if node.to_s =~ /maximum flavor/
node.remove
end
end
end
end | [
"def",
"clean_top_scoring_elements!",
"(",
"options",
"=",
"{",
"}",
")",
"keep_images",
"=",
"!",
"!",
"options",
"[",
":images",
"]",
"top_scoring_elements",
".",
"each",
"do",
"|",
"element",
"|",
"element",
".",
"search",
"(",
"\"*\"",
")",
".",
"each",
"do",
"|",
"node",
"|",
"if",
"cleanable?",
"(",
"node",
",",
"keep_images",
")",
"debugger",
"if",
"node",
".",
"to_s",
"=~",
"/",
"/",
"node",
".",
"remove",
"end",
"end",
"end",
"end"
] | Attempts to clean the top scoring node from non-page content items, such as
advertisements, widgets, etc | [
"Attempts",
"to",
"clean",
"the",
"top",
"scoring",
"node",
"from",
"non",
"-",
"page",
"content",
"items",
"such",
"as",
"advertisements",
"widgets",
"etc"
] | 5d6dfb430398e1c092d65edc305b9c77dda1532b | https://github.com/Fluxx/distillery/blob/5d6dfb430398e1c092d65edc305b9c77dda1532b/lib/distillery/document.rb#L114-L125 | train |
gurix/helena_administration | app/controllers/helena_administration/sessions_controller.rb | HelenaAdministration.SessionsController.unique_question_codes | def unique_question_codes
codes = @survey.versions.map(&:question_codes).flatten.uniq
codes.map do |code|
session_fields.include?(code) ? "answer_#{code}" : code
end
end | ruby | def unique_question_codes
codes = @survey.versions.map(&:question_codes).flatten.uniq
codes.map do |code|
session_fields.include?(code) ? "answer_#{code}" : code
end
end | [
"def",
"unique_question_codes",
"codes",
"=",
"@survey",
".",
"versions",
".",
"map",
"(",
"&",
":question_codes",
")",
".",
"flatten",
".",
"uniq",
"codes",
".",
"map",
"do",
"|",
"code",
"|",
"session_fields",
".",
"include?",
"(",
"code",
")",
"?",
"\"answer_#{code}\"",
":",
"code",
"end",
"end"
] | It could be possible that an answer code equals a session field. We add "answer_" in that case so that we get uniqe question codes for sure | [
"It",
"could",
"be",
"possible",
"that",
"an",
"answer",
"code",
"equals",
"a",
"session",
"field",
".",
"We",
"add",
"answer_",
"in",
"that",
"case",
"so",
"that",
"we",
"get",
"uniqe",
"question",
"codes",
"for",
"sure"
] | d7c5019b3c741a882a3d2192950cdfd92ab72faa | https://github.com/gurix/helena_administration/blob/d7c5019b3c741a882a3d2192950cdfd92ab72faa/app/controllers/helena_administration/sessions_controller.rb#L94-L99 | train |
dpla/KriKri | lib/krikri/harvesters/oai_harvester.rb | Krikri::Harvesters.OAIHarvester.records | def records(opts = {})
opts = @opts.merge(opts)
request_with_sets(opts) do |set_opts|
client.list_records(set_opts).full.lazy.flat_map do |rec|
begin
@record_class.build(mint_id(get_identifier(rec)),
record_xml(rec))
rescue => e
Krikri::Logger.log(:error, e.message)
next
end
end
end
end | ruby | def records(opts = {})
opts = @opts.merge(opts)
request_with_sets(opts) do |set_opts|
client.list_records(set_opts).full.lazy.flat_map do |rec|
begin
@record_class.build(mint_id(get_identifier(rec)),
record_xml(rec))
rescue => e
Krikri::Logger.log(:error, e.message)
next
end
end
end
end | [
"def",
"records",
"(",
"opts",
"=",
"{",
"}",
")",
"opts",
"=",
"@opts",
".",
"merge",
"(",
"opts",
")",
"request_with_sets",
"(",
"opts",
")",
"do",
"|",
"set_opts",
"|",
"client",
".",
"list_records",
"(",
"set_opts",
")",
".",
"full",
".",
"lazy",
".",
"flat_map",
"do",
"|",
"rec",
"|",
"begin",
"@record_class",
".",
"build",
"(",
"mint_id",
"(",
"get_identifier",
"(",
"rec",
")",
")",
",",
"record_xml",
"(",
"rec",
")",
")",
"rescue",
"=>",
"e",
"Krikri",
"::",
"Logger",
".",
"log",
"(",
":error",
",",
"e",
".",
"message",
")",
"next",
"end",
"end",
"end",
"end"
] | Sends ListRecords requests lazily.
The following will only send requests to the endpoint until it
has 1000 records:
records.take(1000)
@param opts [Hash] opts to pass to OAI::Client
@see #expected_opts | [
"Sends",
"ListRecords",
"requests",
"lazily",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/harvesters/oai_harvester.rb#L91-L104 | train |
dpla/KriKri | lib/krikri/harvesters/oai_harvester.rb | Krikri::Harvesters.OAIHarvester.get_record | def get_record(identifier, opts = {})
opts[:identifier] = identifier
opts = @opts.merge(opts)
@record_class.build(mint_id(identifier),
record_xml(client.get_record(opts).record))
end | ruby | def get_record(identifier, opts = {})
opts[:identifier] = identifier
opts = @opts.merge(opts)
@record_class.build(mint_id(identifier),
record_xml(client.get_record(opts).record))
end | [
"def",
"get_record",
"(",
"identifier",
",",
"opts",
"=",
"{",
"}",
")",
"opts",
"[",
":identifier",
"]",
"=",
"identifier",
"opts",
"=",
"@opts",
".",
"merge",
"(",
"opts",
")",
"@record_class",
".",
"build",
"(",
"mint_id",
"(",
"identifier",
")",
",",
"record_xml",
"(",
"client",
".",
"get_record",
"(",
"opts",
")",
".",
"record",
")",
")",
"end"
] | Gets a single record with the given identifier from the OAI endpoint
@param identifier [#to_s] the identifier of the record to get
@param opts [Hash] options to pass to the OAI client | [
"Gets",
"a",
"single",
"record",
"with",
"the",
"given",
"identifier",
"from",
"the",
"OAI",
"endpoint"
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/harvesters/oai_harvester.rb#L111-L116 | train |
dpla/KriKri | lib/krikri/harvesters/oai_harvester.rb | Krikri::Harvesters.OAIHarvester.concat_enum | def concat_enum(enum_enum)
Enumerator.new do |yielder|
enum_enum.each do |enum|
enum.each { |i| yielder << i }
end
end
end | ruby | def concat_enum(enum_enum)
Enumerator.new do |yielder|
enum_enum.each do |enum|
enum.each { |i| yielder << i }
end
end
end | [
"def",
"concat_enum",
"(",
"enum_enum",
")",
"Enumerator",
".",
"new",
"do",
"|",
"yielder",
"|",
"enum_enum",
".",
"each",
"do",
"|",
"enum",
"|",
"enum",
".",
"each",
"{",
"|",
"i",
"|",
"yielder",
"<<",
"i",
"}",
"end",
"end",
"end"
] | Concatinates two enumerators
@todo find a better home for this. Reopen Enumerable? or use the
`Enumerating` gem: https://github.com/mdub/enumerating | [
"Concatinates",
"two",
"enumerators"
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/harvesters/oai_harvester.rb#L159-L165 | train |
dpla/KriKri | lib/krikri/harvesters/oai_harvester.rb | Krikri::Harvesters.OAIHarvester.request_with_sets | def request_with_sets(opts, &block)
sets = Array(opts.delete(:set))
if opts[:skip_set]
sets = self.sets(&:spec) if sets.empty?
skips = Array(opts.delete(:skip_set))
sets.reject! { |s| skips.include? s }
end
sets = [nil] if sets.empty?
set_enums = sets.lazy.map do |set|
set_opts = opts.dup
set_opts[:set] = set unless set.nil?
begin
yield(set_opts) if block_given?
rescue OAI::Exception => e
Krikri::Logger.log :warn, "Skipping set #{set} with error: #{e}"
[]
end
end
concat_enum(set_enums).lazy
end | ruby | def request_with_sets(opts, &block)
sets = Array(opts.delete(:set))
if opts[:skip_set]
sets = self.sets(&:spec) if sets.empty?
skips = Array(opts.delete(:skip_set))
sets.reject! { |s| skips.include? s }
end
sets = [nil] if sets.empty?
set_enums = sets.lazy.map do |set|
set_opts = opts.dup
set_opts[:set] = set unless set.nil?
begin
yield(set_opts) if block_given?
rescue OAI::Exception => e
Krikri::Logger.log :warn, "Skipping set #{set} with error: #{e}"
[]
end
end
concat_enum(set_enums).lazy
end | [
"def",
"request_with_sets",
"(",
"opts",
",",
"&",
"block",
")",
"sets",
"=",
"Array",
"(",
"opts",
".",
"delete",
"(",
":set",
")",
")",
"if",
"opts",
"[",
":skip_set",
"]",
"sets",
"=",
"self",
".",
"sets",
"(",
"&",
":spec",
")",
"if",
"sets",
".",
"empty?",
"skips",
"=",
"Array",
"(",
"opts",
".",
"delete",
"(",
":skip_set",
")",
")",
"sets",
".",
"reject!",
"{",
"|",
"s",
"|",
"skips",
".",
"include?",
"s",
"}",
"end",
"sets",
"=",
"[",
"nil",
"]",
"if",
"sets",
".",
"empty?",
"set_enums",
"=",
"sets",
".",
"lazy",
".",
"map",
"do",
"|",
"set",
"|",
"set_opts",
"=",
"opts",
".",
"dup",
"set_opts",
"[",
":set",
"]",
"=",
"set",
"unless",
"set",
".",
"nil?",
"begin",
"yield",
"(",
"set_opts",
")",
"if",
"block_given?",
"rescue",
"OAI",
"::",
"Exception",
"=>",
"e",
"Krikri",
"::",
"Logger",
".",
"log",
":warn",
",",
"\"Skipping set #{set} with error: #{e}\"",
"[",
"]",
"end",
"end",
"concat_enum",
"(",
"set_enums",
")",
".",
"lazy",
"end"
] | Runs the request in the given block against the sets specified in `opts`.
Results are concatenated into a single enumerator.
Sets that respond with an error (`OAI::Exception`) will return empty
and be skipped.
@param opts [Hash] the options to pass, including all sets to process.
@yield gives options to the block once for each set. The
block should run the harvest action with the options and give an
Enumerable.
@yieldparam set_opts [Hash]
@yieldreturn [Enumerable] a result set to wrap into the retured lazy
enumerator
@return [Enumerator::Lazy] A lazy enumerator concatenating the results
of the block with each set. | [
"Runs",
"the",
"request",
"in",
"the",
"given",
"block",
"against",
"the",
"sets",
"specified",
"in",
"opts",
".",
"Results",
"are",
"concatenated",
"into",
"a",
"single",
"enumerator",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/harvesters/oai_harvester.rb#L186-L206 | train |
Esri/geotrigger-ruby | lib/geotrigger/trigger.rb | Geotrigger.Trigger.post_update | def post_update opts = {}
post_data = @data.dup
post_data['triggerIds'] = post_data.delete 'triggerId'
post_data.delete 'tags'
if circle?
post_data['condition']['geo'].delete 'geojson'
post_data['condition']['geo'].delete 'esrijson'
end
grok_self_from post 'trigger/update', post_data.merge(opts)
self
end | ruby | def post_update opts = {}
post_data = @data.dup
post_data['triggerIds'] = post_data.delete 'triggerId'
post_data.delete 'tags'
if circle?
post_data['condition']['geo'].delete 'geojson'
post_data['condition']['geo'].delete 'esrijson'
end
grok_self_from post 'trigger/update', post_data.merge(opts)
self
end | [
"def",
"post_update",
"opts",
"=",
"{",
"}",
"post_data",
"=",
"@data",
".",
"dup",
"post_data",
"[",
"'triggerIds'",
"]",
"=",
"post_data",
".",
"delete",
"'triggerId'",
"post_data",
".",
"delete",
"'tags'",
"if",
"circle?",
"post_data",
"[",
"'condition'",
"]",
"[",
"'geo'",
"]",
".",
"delete",
"'geojson'",
"post_data",
"[",
"'condition'",
"]",
"[",
"'geo'",
"]",
".",
"delete",
"'esrijson'",
"end",
"grok_self_from",
"post",
"'trigger/update'",
",",
"post_data",
".",
"merge",
"(",
"opts",
")",
"self",
"end"
] | POST the trigger's +@data+ to the API via 'trigger/update', and return
the same object with the new +@data+ returned from API call. | [
"POST",
"the",
"trigger",
"s",
"+"
] | 41fbac4a25ec43427a51dc235a0dbc158e80ce02 | https://github.com/Esri/geotrigger-ruby/blob/41fbac4a25ec43427a51dc235a0dbc158e80ce02/lib/geotrigger/trigger.rb#L58-L70 | train |
outcomesinsights/sequelizer | lib/sequelizer/options.rb | Sequelizer.Options.fix_options | def fix_options(passed_options)
return passed_options unless passed_options.nil? || passed_options.is_a?(Hash)
sequelizer_options = db_config.merge(OptionsHash.new(passed_options || {}).to_hash)
if sequelizer_options[:adapter] =~ /^postgres/
sequelizer_options[:adapter] = 'postgres'
paths = %w(search_path schema_search_path schema).map { |key| sequelizer_options.delete(key) }.compact
unless paths.empty?
sequelizer_options[:search_path] = paths.first
sequelizer_options[:after_connect] = after_connect(paths.first)
end
end
if sequelizer_options[:timeout]
# I'm doing a merge! here because the indifferent access part
# of OptionsHash seemed to not work when I tried
# sequelizer_options[:timeout] = sequelizer_options[:timeout].to_i
sequelizer_options.merge!(timeout: sequelizer_options[:timeout].to_i)
end
sequelizer_options.merge(after_connect: make_ac(sequelizer_options))
end | ruby | def fix_options(passed_options)
return passed_options unless passed_options.nil? || passed_options.is_a?(Hash)
sequelizer_options = db_config.merge(OptionsHash.new(passed_options || {}).to_hash)
if sequelizer_options[:adapter] =~ /^postgres/
sequelizer_options[:adapter] = 'postgres'
paths = %w(search_path schema_search_path schema).map { |key| sequelizer_options.delete(key) }.compact
unless paths.empty?
sequelizer_options[:search_path] = paths.first
sequelizer_options[:after_connect] = after_connect(paths.first)
end
end
if sequelizer_options[:timeout]
# I'm doing a merge! here because the indifferent access part
# of OptionsHash seemed to not work when I tried
# sequelizer_options[:timeout] = sequelizer_options[:timeout].to_i
sequelizer_options.merge!(timeout: sequelizer_options[:timeout].to_i)
end
sequelizer_options.merge(after_connect: make_ac(sequelizer_options))
end | [
"def",
"fix_options",
"(",
"passed_options",
")",
"return",
"passed_options",
"unless",
"passed_options",
".",
"nil?",
"||",
"passed_options",
".",
"is_a?",
"(",
"Hash",
")",
"sequelizer_options",
"=",
"db_config",
".",
"merge",
"(",
"OptionsHash",
".",
"new",
"(",
"passed_options",
"||",
"{",
"}",
")",
".",
"to_hash",
")",
"if",
"sequelizer_options",
"[",
":adapter",
"]",
"=~",
"/",
"/",
"sequelizer_options",
"[",
":adapter",
"]",
"=",
"'postgres'",
"paths",
"=",
"%w(",
"search_path",
"schema_search_path",
"schema",
")",
".",
"map",
"{",
"|",
"key",
"|",
"sequelizer_options",
".",
"delete",
"(",
"key",
")",
"}",
".",
"compact",
"unless",
"paths",
".",
"empty?",
"sequelizer_options",
"[",
":search_path",
"]",
"=",
"paths",
".",
"first",
"sequelizer_options",
"[",
":after_connect",
"]",
"=",
"after_connect",
"(",
"paths",
".",
"first",
")",
"end",
"end",
"if",
"sequelizer_options",
"[",
":timeout",
"]",
"sequelizer_options",
".",
"merge!",
"(",
"timeout",
":",
"sequelizer_options",
"[",
":timeout",
"]",
".",
"to_i",
")",
"end",
"sequelizer_options",
".",
"merge",
"(",
"after_connect",
":",
"make_ac",
"(",
"sequelizer_options",
")",
")",
"end"
] | If passed a hash, scans hash for certain options and sets up hash
to be fed to Sequel.connect
If fed anything, like a string that represents the URL for a DB,
the string is returned without modification | [
"If",
"passed",
"a",
"hash",
"scans",
"hash",
"for",
"certain",
"options",
"and",
"sets",
"up",
"hash",
"to",
"be",
"fed",
"to",
"Sequel",
".",
"connect"
] | 2a8b4a78410b1cf82ec19b45afdb4f65629b2ce2 | https://github.com/outcomesinsights/sequelizer/blob/2a8b4a78410b1cf82ec19b45afdb4f65629b2ce2/lib/sequelizer/options.rb#L40-L62 | train |
outcomesinsights/sequelizer | lib/sequelizer/options.rb | Sequelizer.Options.after_connect | def after_connect(search_path)
Proc.new do |conn|
search_path.split(',').map(&:strip).each do |schema|
conn.execute("CREATE SCHEMA IF NOT EXISTS #{schema}")
end
conn.execute("SET search_path TO #{search_path}")
end
end | ruby | def after_connect(search_path)
Proc.new do |conn|
search_path.split(',').map(&:strip).each do |schema|
conn.execute("CREATE SCHEMA IF NOT EXISTS #{schema}")
end
conn.execute("SET search_path TO #{search_path}")
end
end | [
"def",
"after_connect",
"(",
"search_path",
")",
"Proc",
".",
"new",
"do",
"|",
"conn",
"|",
"search_path",
".",
"split",
"(",
"','",
")",
".",
"map",
"(",
"&",
":strip",
")",
".",
"each",
"do",
"|",
"schema",
"|",
"conn",
".",
"execute",
"(",
"\"CREATE SCHEMA IF NOT EXISTS #{schema}\"",
")",
"end",
"conn",
".",
"execute",
"(",
"\"SET search_path TO #{search_path}\"",
")",
"end",
"end"
] | Returns a proc that should be executed after Sequel connects to the
datebase.
Right now, the only thing that happens is if we're connecting to
PostgreSQL and the schema_search_path is defined, each schema
is created if it doesn't exist, then the search_path is set for
the connection. | [
"Returns",
"a",
"proc",
"that",
"should",
"be",
"executed",
"after",
"Sequel",
"connects",
"to",
"the",
"datebase",
"."
] | 2a8b4a78410b1cf82ec19b45afdb4f65629b2ce2 | https://github.com/outcomesinsights/sequelizer/blob/2a8b4a78410b1cf82ec19b45afdb4f65629b2ce2/lib/sequelizer/options.rb#L84-L91 | train |
technoweenie/running_man | lib/running_man/block.rb | RunningMan.Block.run_once | def run_once(binding)
@ivars.clear
before = binding.instance_variables
binding.instance_eval(&@block)
(binding.instance_variables - before).each do |ivar|
@ivars[ivar] = binding.instance_variable_get(ivar)
end
end | ruby | def run_once(binding)
@ivars.clear
before = binding.instance_variables
binding.instance_eval(&@block)
(binding.instance_variables - before).each do |ivar|
@ivars[ivar] = binding.instance_variable_get(ivar)
end
end | [
"def",
"run_once",
"(",
"binding",
")",
"@ivars",
".",
"clear",
"before",
"=",
"binding",
".",
"instance_variables",
"binding",
".",
"instance_eval",
"(",
"&",
"@block",
")",
"(",
"binding",
".",
"instance_variables",
"-",
"before",
")",
".",
"each",
"do",
"|",
"ivar",
"|",
"@ivars",
"[",
"ivar",
"]",
"=",
"binding",
".",
"instance_variable_get",
"(",
"ivar",
")",
"end",
"end"
] | This runs the block and stores any new instance variables that were set.
binding - The same Object that is given to #run.
Returns nothing. | [
"This",
"runs",
"the",
"block",
"and",
"stores",
"any",
"new",
"instance",
"variables",
"that",
"were",
"set",
"."
] | 1e7a1b1d276dc7bbfb25f523de5c521e070854ab | https://github.com/technoweenie/running_man/blob/1e7a1b1d276dc7bbfb25f523de5c521e070854ab/lib/running_man/block.rb#L59-L66 | train |
technoweenie/running_man | lib/running_man/active_record_block.rb | RunningMan.ActiveRecordBlock.setup | def setup(test_class)
block = self
test_class.setup { block.run(self) }
test_class.teardown { block.teardown_transaction }
end | ruby | def setup(test_class)
block = self
test_class.setup { block.run(self) }
test_class.teardown { block.teardown_transaction }
end | [
"def",
"setup",
"(",
"test_class",
")",
"block",
"=",
"self",
"test_class",
".",
"setup",
"{",
"block",
".",
"run",
"(",
"self",
")",
"}",
"test_class",
".",
"teardown",
"{",
"block",
".",
"teardown_transaction",
"}",
"end"
] | Ensure the block is setup to run first, and that the test run is wrapped
in a database transaction. | [
"Ensure",
"the",
"block",
"is",
"setup",
"to",
"run",
"first",
"and",
"that",
"the",
"test",
"run",
"is",
"wrapped",
"in",
"a",
"database",
"transaction",
"."
] | 1e7a1b1d276dc7bbfb25f523de5c521e070854ab | https://github.com/technoweenie/running_man/blob/1e7a1b1d276dc7bbfb25f523de5c521e070854ab/lib/running_man/active_record_block.rb#L48-L52 | train |
technoweenie/running_man | lib/running_man/active_record_block.rb | RunningMan.ActiveRecordBlock.set_ivar | def set_ivar(binding, ivar, value)
if value.class.respond_to?(:find)
value = value.class.find(value.id)
end
super(binding, ivar, value)
end | ruby | def set_ivar(binding, ivar, value)
if value.class.respond_to?(:find)
value = value.class.find(value.id)
end
super(binding, ivar, value)
end | [
"def",
"set_ivar",
"(",
"binding",
",",
"ivar",
",",
"value",
")",
"if",
"value",
".",
"class",
".",
"respond_to?",
"(",
":find",
")",
"value",
"=",
"value",
".",
"class",
".",
"find",
"(",
"value",
".",
"id",
")",
"end",
"super",
"(",
"binding",
",",
"ivar",
",",
"value",
")",
"end"
] | reload any AR instances | [
"reload",
"any",
"AR",
"instances"
] | 1e7a1b1d276dc7bbfb25f523de5c521e070854ab | https://github.com/technoweenie/running_man/blob/1e7a1b1d276dc7bbfb25f523de5c521e070854ab/lib/running_man/active_record_block.rb#L67-L72 | train |
pengwynn/topsy | lib/topsy/client.rb | Topsy.Client.experts | def experts(q, options={})
options = set_window_or_default(options)
result = handle_response(get("/experts.json", :query => {:q => q}.merge(options)))
Topsy::Page.new(result, Topsy::Author)
end | ruby | def experts(q, options={})
options = set_window_or_default(options)
result = handle_response(get("/experts.json", :query => {:q => q}.merge(options)))
Topsy::Page.new(result, Topsy::Author)
end | [
"def",
"experts",
"(",
"q",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"set_window_or_default",
"(",
"options",
")",
"result",
"=",
"handle_response",
"(",
"get",
"(",
"\"/experts.json\"",
",",
":query",
"=>",
"{",
":q",
"=>",
"q",
"}",
".",
"merge",
"(",
"options",
")",
")",
")",
"Topsy",
"::",
"Page",
".",
"new",
"(",
"result",
",",
"Topsy",
"::",
"Author",
")",
"end"
] | Returns list of authors that talk about the query. The list is sorted by frequency of posts and the influence of authors.
@param [String] q the search query string
@param [Hash] options method options
@option options [Symbol] :window Time window for results. (default: :all) Options: :dynamic most relevant, :hour last hour, :day last day, :week last week, :month last month, :all all time. You can also use the h6 (6 hours) d3 (3 days) syntax.
@option options [Integer] :page page number of the result set. (default: 1, max: 10)
@option options [Integer] :perpage limit number of results per page. (default: 10, max: 50)
@return [Hashie::Mash] | [
"Returns",
"list",
"of",
"authors",
"that",
"talk",
"about",
"the",
"query",
".",
"The",
"list",
"is",
"sorted",
"by",
"frequency",
"of",
"posts",
"and",
"the",
"influence",
"of",
"authors",
"."
] | 20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170 | https://github.com/pengwynn/topsy/blob/20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170/lib/topsy/client.rb#L52-L56 | train |
pengwynn/topsy | lib/topsy/client.rb | Topsy.Client.link_posts | def link_posts(url, options={})
linkposts = handle_response(get("/linkposts.json", :query => {:url => url}.merge(options)))
Topsy::Page.new(linkposts,Topsy::Linkpost)
end | ruby | def link_posts(url, options={})
linkposts = handle_response(get("/linkposts.json", :query => {:url => url}.merge(options)))
Topsy::Page.new(linkposts,Topsy::Linkpost)
end | [
"def",
"link_posts",
"(",
"url",
",",
"options",
"=",
"{",
"}",
")",
"linkposts",
"=",
"handle_response",
"(",
"get",
"(",
"\"/linkposts.json\"",
",",
":query",
"=>",
"{",
":url",
"=>",
"url",
"}",
".",
"merge",
"(",
"options",
")",
")",
")",
"Topsy",
"::",
"Page",
".",
"new",
"(",
"linkposts",
",",
"Topsy",
"::",
"Linkpost",
")",
"end"
] | Returns list of URLs posted by an author
@param [String] url URL string for the author.
@param [Hash] options method options
@option options [String] :contains Query string to filter results
@option options [Integer] :page page number of the result set. (default: 1, max: 10)
@option options [Integer] :perpage limit number of results per page. (default: 10, max: 50)
@return [Topsy::Page] | [
"Returns",
"list",
"of",
"URLs",
"posted",
"by",
"an",
"author"
] | 20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170 | https://github.com/pengwynn/topsy/blob/20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170/lib/topsy/client.rb#L66-L69 | train |
pengwynn/topsy | lib/topsy/client.rb | Topsy.Client.related | def related(url, options={})
response = handle_response(get("/related.json", :query => {:url => url}.merge(options)))
Topsy::Page.new(response,Topsy::LinkSearchResult)
end | ruby | def related(url, options={})
response = handle_response(get("/related.json", :query => {:url => url}.merge(options)))
Topsy::Page.new(response,Topsy::LinkSearchResult)
end | [
"def",
"related",
"(",
"url",
",",
"options",
"=",
"{",
"}",
")",
"response",
"=",
"handle_response",
"(",
"get",
"(",
"\"/related.json\"",
",",
":query",
"=>",
"{",
":url",
"=>",
"url",
"}",
".",
"merge",
"(",
"options",
")",
")",
")",
"Topsy",
"::",
"Page",
".",
"new",
"(",
"response",
",",
"Topsy",
"::",
"LinkSearchResult",
")",
"end"
] | Returns list of URLs related to a given URL
@param [String] url URL string for the author.
@param [Hash] options method options
@option options [Integer] :page page number of the result set. (default: 1, max: 10)
@option options [Integer] :perpage limit number of results per page. (default: 10, max: 50)
@return [Topsy::Page] | [
"Returns",
"list",
"of",
"URLs",
"related",
"to",
"a",
"given",
"URL"
] | 20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170 | https://github.com/pengwynn/topsy/blob/20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170/lib/topsy/client.rb#L89-L92 | train |
pengwynn/topsy | lib/topsy/client.rb | Topsy.Client.search | def search(q, options={})
if q.is_a?(Hash)
options = q
q = "site:#{options.delete(:site)}" if options[:site]
else
q += " site:#{options.delete(:site)}" if options[:site]
end
options = set_window_or_default(options)
results = handle_response(get("/search.json", :query => {:q => q}.merge(options)))
Topsy::Page.new(results,Topsy::LinkSearchResult)
end | ruby | def search(q, options={})
if q.is_a?(Hash)
options = q
q = "site:#{options.delete(:site)}" if options[:site]
else
q += " site:#{options.delete(:site)}" if options[:site]
end
options = set_window_or_default(options)
results = handle_response(get("/search.json", :query => {:q => q}.merge(options)))
Topsy::Page.new(results,Topsy::LinkSearchResult)
end | [
"def",
"search",
"(",
"q",
",",
"options",
"=",
"{",
"}",
")",
"if",
"q",
".",
"is_a?",
"(",
"Hash",
")",
"options",
"=",
"q",
"q",
"=",
"\"site:#{options.delete(:site)}\"",
"if",
"options",
"[",
":site",
"]",
"else",
"q",
"+=",
"\" site:#{options.delete(:site)}\"",
"if",
"options",
"[",
":site",
"]",
"end",
"options",
"=",
"set_window_or_default",
"(",
"options",
")",
"results",
"=",
"handle_response",
"(",
"get",
"(",
"\"/search.json\"",
",",
":query",
"=>",
"{",
":q",
"=>",
"q",
"}",
".",
"merge",
"(",
"options",
")",
")",
")",
"Topsy",
"::",
"Page",
".",
"new",
"(",
"results",
",",
"Topsy",
"::",
"LinkSearchResult",
")",
"end"
] | Returns list of results for a query.
@param [String] q the search query string
@param [Hash] options method options
@option options [Symbol] :window Time window for results. (default: :all) Options: :dynamic most relevant, :hour last hour, :day last day, :week last week, :month last month, :all all time. You can also use the h6 (6 hours) d3 (3 days) syntax.
@option options [Integer] :page page number of the result set. (default: 1, max: 10)
@option options [Integer] :perpage limit number of results per page. (default: 10, max: 50)
@option options [String] :site narrow results to a domain
@return [Topsy::Page] | [
"Returns",
"list",
"of",
"results",
"for",
"a",
"query",
"."
] | 20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170 | https://github.com/pengwynn/topsy/blob/20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170/lib/topsy/client.rb#L103-L113 | train |
pengwynn/topsy | lib/topsy/client.rb | Topsy.Client.search_count | def search_count(q)
counts = handle_response(get("/searchcount.json", :query => {:q => q}))
Topsy::SearchCounts.new(counts)
end | ruby | def search_count(q)
counts = handle_response(get("/searchcount.json", :query => {:q => q}))
Topsy::SearchCounts.new(counts)
end | [
"def",
"search_count",
"(",
"q",
")",
"counts",
"=",
"handle_response",
"(",
"get",
"(",
"\"/searchcount.json\"",
",",
":query",
"=>",
"{",
":q",
"=>",
"q",
"}",
")",
")",
"Topsy",
"::",
"SearchCounts",
".",
"new",
"(",
"counts",
")",
"end"
] | Returns count of results for a search query.
@param [String] q the search query string
@return [Topsy::SearchCounts] | [
"Returns",
"count",
"of",
"results",
"for",
"a",
"search",
"query",
"."
] | 20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170 | https://github.com/pengwynn/topsy/blob/20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170/lib/topsy/client.rb#L119-L122 | train |
pengwynn/topsy | lib/topsy/client.rb | Topsy.Client.search_histogram | def search_histogram( q , count_method = 'target' , slice = 86400 , period = 30 )
response = handle_response(get("/searchhistogram.json" , :query => { :q => q , :slice => slice , :period => period , :count_method => count_method } ))
Topsy::SearchHistogram.new(response)
end | ruby | def search_histogram( q , count_method = 'target' , slice = 86400 , period = 30 )
response = handle_response(get("/searchhistogram.json" , :query => { :q => q , :slice => slice , :period => period , :count_method => count_method } ))
Topsy::SearchHistogram.new(response)
end | [
"def",
"search_histogram",
"(",
"q",
",",
"count_method",
"=",
"'target'",
",",
"slice",
"=",
"86400",
",",
"period",
"=",
"30",
")",
"response",
"=",
"handle_response",
"(",
"get",
"(",
"\"/searchhistogram.json\"",
",",
":query",
"=>",
"{",
":q",
"=>",
"q",
",",
":slice",
"=>",
"slice",
",",
":period",
"=>",
"period",
",",
":count_method",
"=>",
"count_method",
"}",
")",
")",
"Topsy",
"::",
"SearchHistogram",
".",
"new",
"(",
"response",
")",
"end"
] | Returns mention count data for the given query
@param [String] q - The query. Use site:domain.com to get domain counts and @username to get mention counts.
@param [String] count_method - what is being counted - "target" (default) - the number of unique links , or "citation" - cthe number of unique tweets about links
@param [Integer] slice -
@param [Integer] period - | [
"Returns",
"mention",
"count",
"data",
"for",
"the",
"given",
"query"
] | 20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170 | https://github.com/pengwynn/topsy/blob/20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170/lib/topsy/client.rb#L131-L134 | train |
pengwynn/topsy | lib/topsy/client.rb | Topsy.Client.stats | def stats(url, options={})
query = {:url => url}
query.merge!(options)
response = handle_response(get("/stats.json", :query => query))
Topsy::Stats.new(response)
end | ruby | def stats(url, options={})
query = {:url => url}
query.merge!(options)
response = handle_response(get("/stats.json", :query => query))
Topsy::Stats.new(response)
end | [
"def",
"stats",
"(",
"url",
",",
"options",
"=",
"{",
"}",
")",
"query",
"=",
"{",
":url",
"=>",
"url",
"}",
"query",
".",
"merge!",
"(",
"options",
")",
"response",
"=",
"handle_response",
"(",
"get",
"(",
"\"/stats.json\"",
",",
":query",
"=>",
"query",
")",
")",
"Topsy",
"::",
"Stats",
".",
"new",
"(",
"response",
")",
"end"
] | Returns counts of tweets for a URL
@param [String] url the url to look up
@param [Hash] options method options
@option options [String] :contains Query string to filter results
@return [Topsy::Stats] | [
"Returns",
"counts",
"of",
"tweets",
"for",
"a",
"URL"
] | 20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170 | https://github.com/pengwynn/topsy/blob/20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170/lib/topsy/client.rb#L142-L147 | train |
pengwynn/topsy | lib/topsy/client.rb | Topsy.Client.tags | def tags(url, options={})
response = handle_response(get("/tags.json", :query => {:url => url}.merge(options)))
Topsy::Page.new(response,Topsy::Tag)
end | ruby | def tags(url, options={})
response = handle_response(get("/tags.json", :query => {:url => url}.merge(options)))
Topsy::Page.new(response,Topsy::Tag)
end | [
"def",
"tags",
"(",
"url",
",",
"options",
"=",
"{",
"}",
")",
"response",
"=",
"handle_response",
"(",
"get",
"(",
"\"/tags.json\"",
",",
":query",
"=>",
"{",
":url",
"=>",
"url",
"}",
".",
"merge",
"(",
"options",
")",
")",
")",
"Topsy",
"::",
"Page",
".",
"new",
"(",
"response",
",",
"Topsy",
"::",
"Tag",
")",
"end"
] | Returns list of tags for a URL.
@param [String] url the search query string
@param [Hash] options method options
@option options [Integer] :page page number of the result set. (default: 1, max: 10)
@option options [Integer] :perpage limit number of results per page. (default: 10, max: 50)
@return [Topsy::Page] | [
"Returns",
"list",
"of",
"tags",
"for",
"a",
"URL",
"."
] | 20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170 | https://github.com/pengwynn/topsy/blob/20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170/lib/topsy/client.rb#L156-L159 | train |
pengwynn/topsy | lib/topsy/client.rb | Topsy.Client.trending | def trending(options={})
response = handle_response(get("/trending.json", :query => options))
Topsy::Page.new(response,Topsy::Trend)
end | ruby | def trending(options={})
response = handle_response(get("/trending.json", :query => options))
Topsy::Page.new(response,Topsy::Trend)
end | [
"def",
"trending",
"(",
"options",
"=",
"{",
"}",
")",
"response",
"=",
"handle_response",
"(",
"get",
"(",
"\"/trending.json\"",
",",
":query",
"=>",
"options",
")",
")",
"Topsy",
"::",
"Page",
".",
"new",
"(",
"response",
",",
"Topsy",
"::",
"Trend",
")",
"end"
] | Returns list of trending terms
@param [Hash] options method options
@option options [Integer] :page page number of the result set. (default: 1, max: 10)
@option options [Integer] :perpage limit number of results per page. (default: 10, max: 50)
@return [Topsy::Page] | [
"Returns",
"list",
"of",
"trending",
"terms"
] | 20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170 | https://github.com/pengwynn/topsy/blob/20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170/lib/topsy/client.rb#L184-L187 | train |
pengwynn/topsy | lib/topsy/client.rb | Topsy.Client.url_info | def url_info(url)
response = handle_response(get("/urlinfo.json", :query => {:url => url}))
Topsy::UrlInfo.new(response)
end | ruby | def url_info(url)
response = handle_response(get("/urlinfo.json", :query => {:url => url}))
Topsy::UrlInfo.new(response)
end | [
"def",
"url_info",
"(",
"url",
")",
"response",
"=",
"handle_response",
"(",
"get",
"(",
"\"/urlinfo.json\"",
",",
":query",
"=>",
"{",
":url",
"=>",
"url",
"}",
")",
")",
"Topsy",
"::",
"UrlInfo",
".",
"new",
"(",
"response",
")",
"end"
] | Returns info about a URL
@param [String] url the url to look up
@return [Topsy::UrlInfo] | [
"Returns",
"info",
"about",
"a",
"URL"
] | 20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170 | https://github.com/pengwynn/topsy/blob/20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170/lib/topsy/client.rb#L193-L196 | train |
pengwynn/topsy | lib/topsy/client.rb | Topsy.Client.extract_header_value | def extract_header_value(response, key)
response.headers[key].class == Array ? response.headers[key].first.to_i : response.headers[key].to_i
end | ruby | def extract_header_value(response, key)
response.headers[key].class == Array ? response.headers[key].first.to_i : response.headers[key].to_i
end | [
"def",
"extract_header_value",
"(",
"response",
",",
"key",
")",
"response",
".",
"headers",
"[",
"key",
"]",
".",
"class",
"==",
"Array",
"?",
"response",
".",
"headers",
"[",
"key",
"]",
".",
"first",
".",
"to_i",
":",
"response",
".",
"headers",
"[",
"key",
"]",
".",
"to_i",
"end"
] | extracts the header key | [
"extracts",
"the",
"header",
"key"
] | 20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170 | https://github.com/pengwynn/topsy/blob/20fd2c7e80d6fcb8f88b874b3c915e1b2b97a170/lib/topsy/client.rb#L232-L234 | train |
rightscale/right_agent | lib/right_agent/clients/non_blocking_client.rb | RightScale.NonBlockingClient.poll_again | def poll_again(fiber, connection, request_options, stop_at)
http = connection.send(:get, request_options)
http.errback { fiber.resume(*handle_error("POLL", http.error)) }
http.callback do
code, body, headers = http.response_header.status, http.response, http.response_header
if code == 200 && (body.nil? || body == "null") && Time.now < stop_at
poll_again(fiber, connection, request_options, stop_at)
else
fiber.resume(code, body, headers)
end
end
true
end | ruby | def poll_again(fiber, connection, request_options, stop_at)
http = connection.send(:get, request_options)
http.errback { fiber.resume(*handle_error("POLL", http.error)) }
http.callback do
code, body, headers = http.response_header.status, http.response, http.response_header
if code == 200 && (body.nil? || body == "null") && Time.now < stop_at
poll_again(fiber, connection, request_options, stop_at)
else
fiber.resume(code, body, headers)
end
end
true
end | [
"def",
"poll_again",
"(",
"fiber",
",",
"connection",
",",
"request_options",
",",
"stop_at",
")",
"http",
"=",
"connection",
".",
"send",
"(",
":get",
",",
"request_options",
")",
"http",
".",
"errback",
"{",
"fiber",
".",
"resume",
"(",
"*",
"handle_error",
"(",
"\"POLL\"",
",",
"http",
".",
"error",
")",
")",
"}",
"http",
".",
"callback",
"do",
"code",
",",
"body",
",",
"headers",
"=",
"http",
".",
"response_header",
".",
"status",
",",
"http",
".",
"response",
",",
"http",
".",
"response_header",
"if",
"code",
"==",
"200",
"&&",
"(",
"body",
".",
"nil?",
"||",
"body",
"==",
"\"null\"",
")",
"&&",
"Time",
".",
"now",
"<",
"stop_at",
"poll_again",
"(",
"fiber",
",",
"connection",
",",
"request_options",
",",
"stop_at",
")",
"else",
"fiber",
".",
"resume",
"(",
"code",
",",
"body",
",",
"headers",
")",
"end",
"end",
"true",
"end"
] | Repeatedly make long-polling request until receive data, hit error, or timeout
Treat "terminating" and "reconnecting" errors as an empty poll result
@param [Symbol] verb for HTTP REST request
@param [EM:HttpRequest] connection to server from previous request
@param [Hash] request_options for HTTP request
@param [Time] stop_at time for polling
@return [TrueClass] always true
@raise [HttpException] HTTP failure with associated status code | [
"Repeatedly",
"make",
"long",
"-",
"polling",
"request",
"until",
"receive",
"data",
"hit",
"error",
"or",
"timeout",
"Treat",
"terminating",
"and",
"reconnecting",
"errors",
"as",
"an",
"empty",
"poll",
"result"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/non_blocking_client.rb#L184-L196 | train |
rightscale/right_agent | lib/right_agent/clients/non_blocking_client.rb | RightScale.NonBlockingClient.beautify_headers | def beautify_headers(headers)
headers.inject({}) { |out, (key, value)| out[key.gsub(/-/, '_').downcase.to_sym] = value; out }
end | ruby | def beautify_headers(headers)
headers.inject({}) { |out, (key, value)| out[key.gsub(/-/, '_').downcase.to_sym] = value; out }
end | [
"def",
"beautify_headers",
"(",
"headers",
")",
"headers",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"out",
",",
"(",
"key",
",",
"value",
")",
"|",
"out",
"[",
"key",
".",
"gsub",
"(",
"/",
"/",
",",
"'_'",
")",
".",
"downcase",
".",
"to_sym",
"]",
"=",
"value",
";",
"out",
"}",
"end"
] | Beautify response header keys so that in same form as RestClient
@param [Hash] headers from response
@return [Hash] response headers with keys as lower case symbols | [
"Beautify",
"response",
"header",
"keys",
"so",
"that",
"in",
"same",
"form",
"as",
"RestClient"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/non_blocking_client.rb#L218-L220 | train |
rightscale/right_agent | lib/right_agent/agent_tag_manager.rb | RightScale.AgentTagManager.tags | def tags(options = {})
# TODO remove use of agent identity when fully drop AMQP
do_query(nil, @agent.mode == :http ? @agent.self_href : @agent.identity, options) do |result|
if result.kind_of?(Hash)
yield(result.size == 1 ? result.values.first['tags'] : [])
else
yield result
end
end
end | ruby | def tags(options = {})
# TODO remove use of agent identity when fully drop AMQP
do_query(nil, @agent.mode == :http ? @agent.self_href : @agent.identity, options) do |result|
if result.kind_of?(Hash)
yield(result.size == 1 ? result.values.first['tags'] : [])
else
yield result
end
end
end | [
"def",
"tags",
"(",
"options",
"=",
"{",
"}",
")",
"do_query",
"(",
"nil",
",",
"@agent",
".",
"mode",
"==",
":http",
"?",
"@agent",
".",
"self_href",
":",
"@agent",
".",
"identity",
",",
"options",
")",
"do",
"|",
"result",
"|",
"if",
"result",
".",
"kind_of?",
"(",
"Hash",
")",
"yield",
"(",
"result",
".",
"size",
"==",
"1",
"?",
"result",
".",
"values",
".",
"first",
"[",
"'tags'",
"]",
":",
"[",
"]",
")",
"else",
"yield",
"result",
"end",
"end",
"end"
] | Retrieve current agent tags and give result to block
=== Parameters
options(Hash):: Request options
:raw(Boolean):: true to yield raw tag response instead of deserialized tags
:timeout(Integer):: timeout in seconds before giving up and yielding an error message
=== Block
Given block should take one argument which will be set with an array
initialized with the tags of this instance
=== Return
true:: Always return true | [
"Retrieve",
"current",
"agent",
"tags",
"and",
"give",
"result",
"to",
"block"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent_tag_manager.rb#L46-L55 | train |
rightscale/right_agent | lib/right_agent/agent_tag_manager.rb | RightScale.AgentTagManager.query_tags | def query_tags(tags, options = {})
tags = ensure_flat_array_value(tags) unless tags.nil? || tags.empty?
do_query(tags, nil, options) { |result| yield result }
end | ruby | def query_tags(tags, options = {})
tags = ensure_flat_array_value(tags) unless tags.nil? || tags.empty?
do_query(tags, nil, options) { |result| yield result }
end | [
"def",
"query_tags",
"(",
"tags",
",",
"options",
"=",
"{",
"}",
")",
"tags",
"=",
"ensure_flat_array_value",
"(",
"tags",
")",
"unless",
"tags",
".",
"nil?",
"||",
"tags",
".",
"empty?",
"do_query",
"(",
"tags",
",",
"nil",
",",
"options",
")",
"{",
"|",
"result",
"|",
"yield",
"result",
"}",
"end"
] | Queries a list of servers in the current deployment which have one or more
of the given tags.
=== Parameters
tags(String, Array):: Tag or tags to query or empty
options(Hash):: Request options
:raw(Boolean):: true to yield raw tag response instead of deserialized tags
:timeout(Integer):: timeout in seconds before giving up and yielding an error message
=== Block
Given block should take one argument which will be set with an array
initialized with the tags of this instance
=== Return
true:: Always return true | [
"Queries",
"a",
"list",
"of",
"servers",
"in",
"the",
"current",
"deployment",
"which",
"have",
"one",
"or",
"more",
"of",
"the",
"given",
"tags",
"."
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent_tag_manager.rb#L72-L75 | train |
rightscale/right_agent | lib/right_agent/agent_tag_manager.rb | RightScale.AgentTagManager.add_tags | def add_tags(new_tags, options = {})
new_tags = ensure_flat_array_value(new_tags) unless new_tags.nil? || new_tags.empty?
do_update(new_tags, [], options) { |raw_response| yield raw_response if block_given? }
end | ruby | def add_tags(new_tags, options = {})
new_tags = ensure_flat_array_value(new_tags) unless new_tags.nil? || new_tags.empty?
do_update(new_tags, [], options) { |raw_response| yield raw_response if block_given? }
end | [
"def",
"add_tags",
"(",
"new_tags",
",",
"options",
"=",
"{",
"}",
")",
"new_tags",
"=",
"ensure_flat_array_value",
"(",
"new_tags",
")",
"unless",
"new_tags",
".",
"nil?",
"||",
"new_tags",
".",
"empty?",
"do_update",
"(",
"new_tags",
",",
"[",
"]",
",",
"options",
")",
"{",
"|",
"raw_response",
"|",
"yield",
"raw_response",
"if",
"block_given?",
"}",
"end"
] | Add given tags to agent
=== Parameters
new_tags(String, Array):: Tag or tags to be added
options(Hash):: Request options
:timeout(Integer):: timeout in seconds before giving up and yielding an error message
=== Block
A block is optional. If provided, should take one argument which will be set with the
raw response
=== Return
true always return true | [
"Add",
"given",
"tags",
"to",
"agent"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent_tag_manager.rb#L110-L113 | train |
rightscale/right_agent | lib/right_agent/agent_tag_manager.rb | RightScale.AgentTagManager.remove_tags | def remove_tags(old_tags, options = {})
old_tags = ensure_flat_array_value(old_tags) unless old_tags.nil? || old_tags.empty?
do_update([], old_tags, options) { |raw_response| yield raw_response if block_given? }
end | ruby | def remove_tags(old_tags, options = {})
old_tags = ensure_flat_array_value(old_tags) unless old_tags.nil? || old_tags.empty?
do_update([], old_tags, options) { |raw_response| yield raw_response if block_given? }
end | [
"def",
"remove_tags",
"(",
"old_tags",
",",
"options",
"=",
"{",
"}",
")",
"old_tags",
"=",
"ensure_flat_array_value",
"(",
"old_tags",
")",
"unless",
"old_tags",
".",
"nil?",
"||",
"old_tags",
".",
"empty?",
"do_update",
"(",
"[",
"]",
",",
"old_tags",
",",
"options",
")",
"{",
"|",
"raw_response",
"|",
"yield",
"raw_response",
"if",
"block_given?",
"}",
"end"
] | Remove given tags from agent
=== Parameters
old_tags(String, Array):: Tag or tags to be removed
options(Hash):: Request options
:timeout(Integer):: timeout in seconds before giving up and yielding an error message
=== Block
A block is optional. If provided, should take one argument which will be set with the
raw response
=== Return
true always return true | [
"Remove",
"given",
"tags",
"from",
"agent"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent_tag_manager.rb#L128-L131 | train |
rightscale/right_agent | lib/right_agent/agent_tag_manager.rb | RightScale.AgentTagManager.do_query | def do_query(tags = nil, hrefs = nil, options = {})
raw = options[:raw]
timeout = options[:timeout]
request_options = {}
request_options[:timeout] = timeout if timeout
agent_check
payload = {:agent_identity => @agent.identity}
payload[:tags] = ensure_flat_array_value(tags) unless tags.nil? || tags.empty?
# TODO remove use of agent identity when fully drop AMQP
if @agent.mode == :http
payload[:hrefs] = ensure_flat_array_value(hrefs) unless hrefs.nil? || hrefs.empty?
else
payload[:agent_ids] = ensure_flat_array_value(hrefs) unless hrefs.nil? || hrefs.empty?
end
request = RightScale::RetryableRequest.new("/router/query_tags", payload, request_options)
request.callback { |result| yield raw ? request.raw_response : result }
request.errback do |message|
ErrorTracker.log(self, "Failed to query tags (#{message})")
yield((raw ? request.raw_response : nil) || message)
end
request.run
true
end | ruby | def do_query(tags = nil, hrefs = nil, options = {})
raw = options[:raw]
timeout = options[:timeout]
request_options = {}
request_options[:timeout] = timeout if timeout
agent_check
payload = {:agent_identity => @agent.identity}
payload[:tags] = ensure_flat_array_value(tags) unless tags.nil? || tags.empty?
# TODO remove use of agent identity when fully drop AMQP
if @agent.mode == :http
payload[:hrefs] = ensure_flat_array_value(hrefs) unless hrefs.nil? || hrefs.empty?
else
payload[:agent_ids] = ensure_flat_array_value(hrefs) unless hrefs.nil? || hrefs.empty?
end
request = RightScale::RetryableRequest.new("/router/query_tags", payload, request_options)
request.callback { |result| yield raw ? request.raw_response : result }
request.errback do |message|
ErrorTracker.log(self, "Failed to query tags (#{message})")
yield((raw ? request.raw_response : nil) || message)
end
request.run
true
end | [
"def",
"do_query",
"(",
"tags",
"=",
"nil",
",",
"hrefs",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"raw",
"=",
"options",
"[",
":raw",
"]",
"timeout",
"=",
"options",
"[",
":timeout",
"]",
"request_options",
"=",
"{",
"}",
"request_options",
"[",
":timeout",
"]",
"=",
"timeout",
"if",
"timeout",
"agent_check",
"payload",
"=",
"{",
":agent_identity",
"=>",
"@agent",
".",
"identity",
"}",
"payload",
"[",
":tags",
"]",
"=",
"ensure_flat_array_value",
"(",
"tags",
")",
"unless",
"tags",
".",
"nil?",
"||",
"tags",
".",
"empty?",
"if",
"@agent",
".",
"mode",
"==",
":http",
"payload",
"[",
":hrefs",
"]",
"=",
"ensure_flat_array_value",
"(",
"hrefs",
")",
"unless",
"hrefs",
".",
"nil?",
"||",
"hrefs",
".",
"empty?",
"else",
"payload",
"[",
":agent_ids",
"]",
"=",
"ensure_flat_array_value",
"(",
"hrefs",
")",
"unless",
"hrefs",
".",
"nil?",
"||",
"hrefs",
".",
"empty?",
"end",
"request",
"=",
"RightScale",
"::",
"RetryableRequest",
".",
"new",
"(",
"\"/router/query_tags\"",
",",
"payload",
",",
"request_options",
")",
"request",
".",
"callback",
"{",
"|",
"result",
"|",
"yield",
"raw",
"?",
"request",
".",
"raw_response",
":",
"result",
"}",
"request",
".",
"errback",
"do",
"|",
"message",
"|",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Failed to query tags (#{message})\"",
")",
"yield",
"(",
"(",
"raw",
"?",
"request",
".",
"raw_response",
":",
"nil",
")",
"||",
"message",
")",
"end",
"request",
".",
"run",
"true",
"end"
] | Runs a tag query with an optional list of tags.
=== Parameters
tags(Array):: Tags to query or empty or nil
hrefs(Array):: hrefs of resources to query with empty or nil meaning all instances in deployment
options(Hash):: Request options
:raw(Boolean):: true to yield raw tag response instead of unserialized tags
:timeout(Integer):: timeout in seconds before giving up and yielding an error message
=== Block
Given block should take one argument which will be set with an array
initialized with the tags of this instance
=== Return
true:: Always return true | [
"Runs",
"a",
"tag",
"query",
"with",
"an",
"optional",
"list",
"of",
"tags",
"."
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent_tag_manager.rb#L169-L193 | train |
rightscale/right_agent | lib/right_agent/agent_tag_manager.rb | RightScale.AgentTagManager.do_update | def do_update(new_tags, old_tags, options = {}, &block)
agent_check
raise ArgumentError.new("Cannot add and remove tags in same update") if new_tags.any? && old_tags.any?
tags = @agent.tags
tags += new_tags
tags -= old_tags
tags.uniq!
if new_tags.any?
request = RightScale::RetryableRequest.new("/router/add_tags", {:tags => new_tags}, options)
elsif old_tags.any?
request = RightScale::RetryableRequest.new("/router/delete_tags", {:tags => old_tags}, options)
else
return
end
if block
# Always yield raw response
request.callback do |_|
# Refresh agent's copy of tags on successful update
@agent.tags = tags
block.call(request.raw_response)
end
request.errback { |message| block.call(request.raw_response || message) }
end
request.run
true
end | ruby | def do_update(new_tags, old_tags, options = {}, &block)
agent_check
raise ArgumentError.new("Cannot add and remove tags in same update") if new_tags.any? && old_tags.any?
tags = @agent.tags
tags += new_tags
tags -= old_tags
tags.uniq!
if new_tags.any?
request = RightScale::RetryableRequest.new("/router/add_tags", {:tags => new_tags}, options)
elsif old_tags.any?
request = RightScale::RetryableRequest.new("/router/delete_tags", {:tags => old_tags}, options)
else
return
end
if block
# Always yield raw response
request.callback do |_|
# Refresh agent's copy of tags on successful update
@agent.tags = tags
block.call(request.raw_response)
end
request.errback { |message| block.call(request.raw_response || message) }
end
request.run
true
end | [
"def",
"do_update",
"(",
"new_tags",
",",
"old_tags",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"agent_check",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"Cannot add and remove tags in same update\"",
")",
"if",
"new_tags",
".",
"any?",
"&&",
"old_tags",
".",
"any?",
"tags",
"=",
"@agent",
".",
"tags",
"tags",
"+=",
"new_tags",
"tags",
"-=",
"old_tags",
"tags",
".",
"uniq!",
"if",
"new_tags",
".",
"any?",
"request",
"=",
"RightScale",
"::",
"RetryableRequest",
".",
"new",
"(",
"\"/router/add_tags\"",
",",
"{",
":tags",
"=>",
"new_tags",
"}",
",",
"options",
")",
"elsif",
"old_tags",
".",
"any?",
"request",
"=",
"RightScale",
"::",
"RetryableRequest",
".",
"new",
"(",
"\"/router/delete_tags\"",
",",
"{",
":tags",
"=>",
"old_tags",
"}",
",",
"options",
")",
"else",
"return",
"end",
"if",
"block",
"request",
".",
"callback",
"do",
"|",
"_",
"|",
"@agent",
".",
"tags",
"=",
"tags",
"block",
".",
"call",
"(",
"request",
".",
"raw_response",
")",
"end",
"request",
".",
"errback",
"{",
"|",
"message",
"|",
"block",
".",
"call",
"(",
"request",
".",
"raw_response",
"||",
"message",
")",
"}",
"end",
"request",
".",
"run",
"true",
"end"
] | Runs a tag update with a list of new or old tags
=== Parameters
new_tags(Array):: new tags to add or empty
old_tags(Array):: old tags to remove or empty
block(Block):: optional callback for update response
=== Block
A block is optional. If provided, should take one argument which will be set with the
raw response
=== Return
true:: Always return true | [
"Runs",
"a",
"tag",
"update",
"with",
"a",
"list",
"of",
"new",
"or",
"old",
"tags"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/agent_tag_manager.rb#L208-L235 | train |
rightscale/right_agent | lib/right_agent/error_tracker.rb | RightScale.ErrorTracker.init | def init(agent, agent_name, options = {})
@agent = agent
@trace_level = options[:trace_level] || {}
notify_init(agent_name, options)
reset_stats
true
end | ruby | def init(agent, agent_name, options = {})
@agent = agent
@trace_level = options[:trace_level] || {}
notify_init(agent_name, options)
reset_stats
true
end | [
"def",
"init",
"(",
"agent",
",",
"agent_name",
",",
"options",
"=",
"{",
"}",
")",
"@agent",
"=",
"agent",
"@trace_level",
"=",
"options",
"[",
":trace_level",
"]",
"||",
"{",
"}",
"notify_init",
"(",
"agent_name",
",",
"options",
")",
"reset_stats",
"true",
"end"
] | Initialize error tracker
@param [Object] agent object using this tracker
@param [String] agent_name uniquely identifying agent process on given server
@option options [Integer, NilClass] :shard_id identifying shard of database in use
@option options [Hash] :trace_level for restricting backtracing and Errbit reporting
with exception class as key and :no_trace, :caller, or :trace as value; exceptions
with :no_trace are not backtraced when logging nor are they recorded in stats
or reported to Errbit
@option options [Array<Symbol, String>] :filter_params names whose values are to be
filtered when notifying
@option options [String] :airbrake_endpoint URL for Airbrake for reporting exceptions
to Errbit
@option options [String] :airbrake_api_key for using the Airbrake API to access Errbit
@return [TrueClass] always true | [
"Initialize",
"error",
"tracker"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/error_tracker.rb#L45-L51 | train |
rightscale/right_agent | lib/right_agent/error_tracker.rb | RightScale.ErrorTracker.log | def log(component, description, exception = nil, packet = nil, trace = nil)
if exception.nil?
Log.error(description)
elsif exception.is_a?(String)
Log.error(description, exception)
else
trace = (@trace_level && @trace_level[exception.class]) || trace || :trace
Log.error(description, exception, trace)
track(component, exception, packet) if trace != :no_trace
end
true
rescue StandardError => e
Log.error("Failed to log error", e, :trace) rescue nil
false
end | ruby | def log(component, description, exception = nil, packet = nil, trace = nil)
if exception.nil?
Log.error(description)
elsif exception.is_a?(String)
Log.error(description, exception)
else
trace = (@trace_level && @trace_level[exception.class]) || trace || :trace
Log.error(description, exception, trace)
track(component, exception, packet) if trace != :no_trace
end
true
rescue StandardError => e
Log.error("Failed to log error", e, :trace) rescue nil
false
end | [
"def",
"log",
"(",
"component",
",",
"description",
",",
"exception",
"=",
"nil",
",",
"packet",
"=",
"nil",
",",
"trace",
"=",
"nil",
")",
"if",
"exception",
".",
"nil?",
"Log",
".",
"error",
"(",
"description",
")",
"elsif",
"exception",
".",
"is_a?",
"(",
"String",
")",
"Log",
".",
"error",
"(",
"description",
",",
"exception",
")",
"else",
"trace",
"=",
"(",
"@trace_level",
"&&",
"@trace_level",
"[",
"exception",
".",
"class",
"]",
")",
"||",
"trace",
"||",
":trace",
"Log",
".",
"error",
"(",
"description",
",",
"exception",
",",
"trace",
")",
"track",
"(",
"component",
",",
"exception",
",",
"packet",
")",
"if",
"trace",
"!=",
":no_trace",
"end",
"true",
"rescue",
"StandardError",
"=>",
"e",
"Log",
".",
"error",
"(",
"\"Failed to log error\"",
",",
"e",
",",
":trace",
")",
"rescue",
"nil",
"false",
"end"
] | Log error and optionally track in stats
Errbit notification is left to the callback configured in the stats tracker
Logging works even if init was never called
@param [String, Object] component reporting error; non-string is snake-cased
@param [String] description of failure for use in logging
@param [Exception, String] exception to be logged and tracked in stats;
string errors are logged but not tracked in stats
@param [Packet, Hash, NilClass] packet associated with exception
@param [Symbol, NilClass] trace level override unless excluded by configured
trace levels
@return [Boolean] true if successfully logged, otherwise false | [
"Log",
"error",
"and",
"optionally",
"track",
"in",
"stats",
"Errbit",
"notification",
"is",
"left",
"to",
"the",
"callback",
"configured",
"in",
"the",
"stats",
"tracker",
"Logging",
"works",
"even",
"if",
"init",
"was",
"never",
"called"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/error_tracker.rb#L66-L80 | train |
rightscale/right_agent | lib/right_agent/error_tracker.rb | RightScale.ErrorTracker.track | def track(component, exception, packet = nil)
if @exception_stats
component = component.class.name.split("::").last.snake_case unless component.is_a?(String)
@exception_stats.track(component, exception, packet)
end
true
end | ruby | def track(component, exception, packet = nil)
if @exception_stats
component = component.class.name.split("::").last.snake_case unless component.is_a?(String)
@exception_stats.track(component, exception, packet)
end
true
end | [
"def",
"track",
"(",
"component",
",",
"exception",
",",
"packet",
"=",
"nil",
")",
"if",
"@exception_stats",
"component",
"=",
"component",
".",
"class",
".",
"name",
".",
"split",
"(",
"\"::\"",
")",
".",
"last",
".",
"snake_case",
"unless",
"component",
".",
"is_a?",
"(",
"String",
")",
"@exception_stats",
".",
"track",
"(",
"component",
",",
"exception",
",",
"packet",
")",
"end",
"true",
"end"
] | Track error in stats
@param [String] component reporting error
@param [Exception] exception to be tracked
@param [Packet, Hash, NilClass] packet associated with exception
@return [TrueClass] always true | [
"Track",
"error",
"in",
"stats"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/error_tracker.rb#L89-L95 | train |
rightscale/right_agent | lib/right_agent/error_tracker.rb | RightScale.ErrorTracker.notify | def notify(exception, packet = nil, agent = nil, component = nil)
if @notify_enabled
if packet && packet.is_a?(Packet)
action = packet.type.split("/").last if packet.respond_to?(:type)
params = packet.respond_to?(:payload) && packet.payload
uuid = packet.respond_to?(:token) && packet.token
elsif packet.is_a?(Hash)
action_path = packet[:path] || packet["path"]
action = action_path.split("/").last if action_path
params = packet[:data] || packet["data"]
uuid = packet[:uuid] || packet["uuid"]
else
params = uuid = nil
end
component = component.class.name unless component.is_a?(String)
n = Airbrake.build_notice(
exception,
{ component: component, action: action },
:right_agent )
n[:params] = params.is_a?(Hash) ? filter(params) : {:param => params} if params
n[:session] = { :uuid => uuid } if uuid
if agent
n[:environment] = (@cgi_data || {}).merge(:agent_class => agent.class.name)
elsif @cgi_data
n[:environment] = @cgi_data || {}
end
Airbrake.notify(n, {}, :right_agent)
end
true
rescue Exception => e
raise if e.class.name =~ /^RSpec/ # keep us from going insane while running tests
Log.error("Failed to notify Errbit", e, :trace)
end | ruby | def notify(exception, packet = nil, agent = nil, component = nil)
if @notify_enabled
if packet && packet.is_a?(Packet)
action = packet.type.split("/").last if packet.respond_to?(:type)
params = packet.respond_to?(:payload) && packet.payload
uuid = packet.respond_to?(:token) && packet.token
elsif packet.is_a?(Hash)
action_path = packet[:path] || packet["path"]
action = action_path.split("/").last if action_path
params = packet[:data] || packet["data"]
uuid = packet[:uuid] || packet["uuid"]
else
params = uuid = nil
end
component = component.class.name unless component.is_a?(String)
n = Airbrake.build_notice(
exception,
{ component: component, action: action },
:right_agent )
n[:params] = params.is_a?(Hash) ? filter(params) : {:param => params} if params
n[:session] = { :uuid => uuid } if uuid
if agent
n[:environment] = (@cgi_data || {}).merge(:agent_class => agent.class.name)
elsif @cgi_data
n[:environment] = @cgi_data || {}
end
Airbrake.notify(n, {}, :right_agent)
end
true
rescue Exception => e
raise if e.class.name =~ /^RSpec/ # keep us from going insane while running tests
Log.error("Failed to notify Errbit", e, :trace)
end | [
"def",
"notify",
"(",
"exception",
",",
"packet",
"=",
"nil",
",",
"agent",
"=",
"nil",
",",
"component",
"=",
"nil",
")",
"if",
"@notify_enabled",
"if",
"packet",
"&&",
"packet",
".",
"is_a?",
"(",
"Packet",
")",
"action",
"=",
"packet",
".",
"type",
".",
"split",
"(",
"\"/\"",
")",
".",
"last",
"if",
"packet",
".",
"respond_to?",
"(",
":type",
")",
"params",
"=",
"packet",
".",
"respond_to?",
"(",
":payload",
")",
"&&",
"packet",
".",
"payload",
"uuid",
"=",
"packet",
".",
"respond_to?",
"(",
":token",
")",
"&&",
"packet",
".",
"token",
"elsif",
"packet",
".",
"is_a?",
"(",
"Hash",
")",
"action_path",
"=",
"packet",
"[",
":path",
"]",
"||",
"packet",
"[",
"\"path\"",
"]",
"action",
"=",
"action_path",
".",
"split",
"(",
"\"/\"",
")",
".",
"last",
"if",
"action_path",
"params",
"=",
"packet",
"[",
":data",
"]",
"||",
"packet",
"[",
"\"data\"",
"]",
"uuid",
"=",
"packet",
"[",
":uuid",
"]",
"||",
"packet",
"[",
"\"uuid\"",
"]",
"else",
"params",
"=",
"uuid",
"=",
"nil",
"end",
"component",
"=",
"component",
".",
"class",
".",
"name",
"unless",
"component",
".",
"is_a?",
"(",
"String",
")",
"n",
"=",
"Airbrake",
".",
"build_notice",
"(",
"exception",
",",
"{",
"component",
":",
"component",
",",
"action",
":",
"action",
"}",
",",
":right_agent",
")",
"n",
"[",
":params",
"]",
"=",
"params",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"filter",
"(",
"params",
")",
":",
"{",
":param",
"=>",
"params",
"}",
"if",
"params",
"n",
"[",
":session",
"]",
"=",
"{",
":uuid",
"=>",
"uuid",
"}",
"if",
"uuid",
"if",
"agent",
"n",
"[",
":environment",
"]",
"=",
"(",
"@cgi_data",
"||",
"{",
"}",
")",
".",
"merge",
"(",
":agent_class",
"=>",
"agent",
".",
"class",
".",
"name",
")",
"elsif",
"@cgi_data",
"n",
"[",
":environment",
"]",
"=",
"@cgi_data",
"||",
"{",
"}",
"end",
"Airbrake",
".",
"notify",
"(",
"n",
",",
"{",
"}",
",",
":right_agent",
")",
"end",
"true",
"rescue",
"Exception",
"=>",
"e",
"raise",
"if",
"e",
".",
"class",
".",
"name",
"=~",
"/",
"/",
"Log",
".",
"error",
"(",
"\"Failed to notify Errbit\"",
",",
"e",
",",
":trace",
")",
"end"
] | Notify Errbit of error if notification enabled
@param [Exception, String] exception raised
@param [Packet, Hash] packet associated with exception
@param [Object] agent object reporting error
@param [String,Object] component or service area where error occurred
@return [TrueClass] always true | [
"Notify",
"Errbit",
"of",
"error",
"if",
"notification",
"enabled"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/error_tracker.rb#L105-L142 | train |
rightscale/right_agent | lib/right_agent/error_tracker.rb | RightScale.ErrorTracker.notify_callback | def notify_callback
Proc.new do |exception, packet, agent, component|
notify(exception, packet, agent, component)
end
end | ruby | def notify_callback
Proc.new do |exception, packet, agent, component|
notify(exception, packet, agent, component)
end
end | [
"def",
"notify_callback",
"Proc",
".",
"new",
"do",
"|",
"exception",
",",
"packet",
",",
"agent",
",",
"component",
"|",
"notify",
"(",
"exception",
",",
"packet",
",",
"agent",
",",
"component",
")",
"end",
"end"
] | Create proc for making callback to notifier
@return [Proc] notifier callback | [
"Create",
"proc",
"for",
"making",
"callback",
"to",
"notifier"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/error_tracker.rb#L147-L151 | train |
rightscale/right_agent | lib/right_agent/error_tracker.rb | RightScale.ErrorTracker.notify_init | def notify_init(agent_name, options)
if options[:airbrake_endpoint] && options[:airbrake_api_key]
unless require_succeeds?("airbrake-ruby")
raise RuntimeError, "airbrake-ruby gem missing - required if airbrake options used in ErrorTracker"
end
@cgi_data = {
:process => $0,
:pid => Process.pid,
:agent_name => agent_name
}
@cgi_data[:shard_id] = options[:shard_id] if options[:shard_id]
@filter_params = (options[:filter_params] || []).map { |p| p.to_s }
@notify_enabled = true
return true if Airbrake.send(:configured?, :right_agent)
Airbrake.configure(:right_agent) do |config|
config.host = options[:airbrake_endpoint]
config.project_id = options[:airbrake_api_key]
config.project_key = options[:airbrake_api_key]
config.root_directory = AgentConfig.root_dir
config.environment = ENV['RAILS_ENV']
config.app_version = CURRENT_SOURCE_SHA if defined?(CURRENT_SOURCE_SHA)
end
else
@notify_enabled = false
end
true
end | ruby | def notify_init(agent_name, options)
if options[:airbrake_endpoint] && options[:airbrake_api_key]
unless require_succeeds?("airbrake-ruby")
raise RuntimeError, "airbrake-ruby gem missing - required if airbrake options used in ErrorTracker"
end
@cgi_data = {
:process => $0,
:pid => Process.pid,
:agent_name => agent_name
}
@cgi_data[:shard_id] = options[:shard_id] if options[:shard_id]
@filter_params = (options[:filter_params] || []).map { |p| p.to_s }
@notify_enabled = true
return true if Airbrake.send(:configured?, :right_agent)
Airbrake.configure(:right_agent) do |config|
config.host = options[:airbrake_endpoint]
config.project_id = options[:airbrake_api_key]
config.project_key = options[:airbrake_api_key]
config.root_directory = AgentConfig.root_dir
config.environment = ENV['RAILS_ENV']
config.app_version = CURRENT_SOURCE_SHA if defined?(CURRENT_SOURCE_SHA)
end
else
@notify_enabled = false
end
true
end | [
"def",
"notify_init",
"(",
"agent_name",
",",
"options",
")",
"if",
"options",
"[",
":airbrake_endpoint",
"]",
"&&",
"options",
"[",
":airbrake_api_key",
"]",
"unless",
"require_succeeds?",
"(",
"\"airbrake-ruby\"",
")",
"raise",
"RuntimeError",
",",
"\"airbrake-ruby gem missing - required if airbrake options used in ErrorTracker\"",
"end",
"@cgi_data",
"=",
"{",
":process",
"=>",
"$0",
",",
":pid",
"=>",
"Process",
".",
"pid",
",",
":agent_name",
"=>",
"agent_name",
"}",
"@cgi_data",
"[",
":shard_id",
"]",
"=",
"options",
"[",
":shard_id",
"]",
"if",
"options",
"[",
":shard_id",
"]",
"@filter_params",
"=",
"(",
"options",
"[",
":filter_params",
"]",
"||",
"[",
"]",
")",
".",
"map",
"{",
"|",
"p",
"|",
"p",
".",
"to_s",
"}",
"@notify_enabled",
"=",
"true",
"return",
"true",
"if",
"Airbrake",
".",
"send",
"(",
":configured?",
",",
":right_agent",
")",
"Airbrake",
".",
"configure",
"(",
":right_agent",
")",
"do",
"|",
"config",
"|",
"config",
".",
"host",
"=",
"options",
"[",
":airbrake_endpoint",
"]",
"config",
".",
"project_id",
"=",
"options",
"[",
":airbrake_api_key",
"]",
"config",
".",
"project_key",
"=",
"options",
"[",
":airbrake_api_key",
"]",
"config",
".",
"root_directory",
"=",
"AgentConfig",
".",
"root_dir",
"config",
".",
"environment",
"=",
"ENV",
"[",
"'RAILS_ENV'",
"]",
"config",
".",
"app_version",
"=",
"CURRENT_SOURCE_SHA",
"if",
"defined?",
"(",
"CURRENT_SOURCE_SHA",
")",
"end",
"else",
"@notify_enabled",
"=",
"false",
"end",
"true",
"end"
] | Configure Airbrake for exception notification
@param [String] agent_name uniquely identifying agent process on given server
@option options [Integer, NilClass] :shard_id identifying shard of database in use
@option options [Array<Symbol, String>] :filter_params names whose values are to be
filtered when notifying
@option options [String] :airbrake_endpoint URL for Airbrake for reporting exceptions
to Errbit
@option options [String] :airbrake_api_key for using the Airbrake API to access Errbit
@return [TrueClass] always true
@raise [RuntimeError] airbrake gem missing | [
"Configure",
"Airbrake",
"for",
"exception",
"notification"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/error_tracker.rb#L189-L219 | train |
rightscale/right_agent | lib/right_agent/error_tracker.rb | RightScale.ErrorTracker.filter | def filter(params)
if @filter_params
filtered_params = {}
params.each { |k, p| filtered_params[k] = @filter_params.include?(k.to_s) ? FILTERED_PARAM_VALUE : p }
filtered_params
end
end | ruby | def filter(params)
if @filter_params
filtered_params = {}
params.each { |k, p| filtered_params[k] = @filter_params.include?(k.to_s) ? FILTERED_PARAM_VALUE : p }
filtered_params
end
end | [
"def",
"filter",
"(",
"params",
")",
"if",
"@filter_params",
"filtered_params",
"=",
"{",
"}",
"params",
".",
"each",
"{",
"|",
"k",
",",
"p",
"|",
"filtered_params",
"[",
"k",
"]",
"=",
"@filter_params",
".",
"include?",
"(",
"k",
".",
"to_s",
")",
"?",
"FILTERED_PARAM_VALUE",
":",
"p",
"}",
"filtered_params",
"end",
"end"
] | Apply parameter filter
@param [Hash] params to be filtered
@return [Hash] filtered parameters | [
"Apply",
"parameter",
"filter"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/error_tracker.rb#L226-L232 | train |
rightscale/right_agent | lib/right_agent/connectivity_checker.rb | RightScale.ConnectivityChecker.message_received | def message_received(&callback)
if block_given?
@message_received_callbacks << callback
else
@message_received_callbacks.each { |c| c.call }
if @check_interval > 0
now = Time.now
if (now - @last_received) > MIN_RESTART_INACTIVITY_TIMER_INTERVAL
@last_received = now
restart_inactivity_timer
end
end
end
true
end | ruby | def message_received(&callback)
if block_given?
@message_received_callbacks << callback
else
@message_received_callbacks.each { |c| c.call }
if @check_interval > 0
now = Time.now
if (now - @last_received) > MIN_RESTART_INACTIVITY_TIMER_INTERVAL
@last_received = now
restart_inactivity_timer
end
end
end
true
end | [
"def",
"message_received",
"(",
"&",
"callback",
")",
"if",
"block_given?",
"@message_received_callbacks",
"<<",
"callback",
"else",
"@message_received_callbacks",
".",
"each",
"{",
"|",
"c",
"|",
"c",
".",
"call",
"}",
"if",
"@check_interval",
">",
"0",
"now",
"=",
"Time",
".",
"now",
"if",
"(",
"now",
"-",
"@last_received",
")",
">",
"MIN_RESTART_INACTIVITY_TIMER_INTERVAL",
"@last_received",
"=",
"now",
"restart_inactivity_timer",
"end",
"end",
"end",
"true",
"end"
] | Update the time this agent last received a request or response message
and restart the inactivity timer thus deferring the next connectivity check
Also forward this message receipt notification to any callbacks that have registered
=== Block
Optional block without parameters that is activated when a message is received
=== Return
true:: Always return true | [
"Update",
"the",
"time",
"this",
"agent",
"last",
"received",
"a",
"request",
"or",
"response",
"message",
"and",
"restart",
"the",
"inactivity",
"timer",
"thus",
"deferring",
"the",
"next",
"connectivity",
"check",
"Also",
"forward",
"this",
"message",
"receipt",
"notification",
"to",
"any",
"callbacks",
"that",
"have",
"registered"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/connectivity_checker.rb#L61-L75 | train |
rightscale/right_agent | lib/right_agent/connectivity_checker.rb | RightScale.ConnectivityChecker.check | def check(id = nil, max_ping_timeouts = MAX_PING_TIMEOUTS)
unless @terminating || @ping_timer || (id && [email protected]?(id))
@ping_id = id
@ping_timer = EM::Timer.new(PING_TIMEOUT) do
if @ping_id
begin
@ping_stats.update("timeout")
@ping_timer = nil
@ping_timeouts[@ping_id] = (@ping_timeouts[@ping_id] || 0) + 1
if @ping_timeouts[@ping_id] >= max_ping_timeouts
ErrorTracker.log(self, "Mapper ping via broker #{@ping_id} timed out after #{PING_TIMEOUT} seconds and now " +
"reached maximum of #{max_ping_timeouts} timeout#{max_ping_timeouts > 1 ? 's' : ''}, " +
"attempting to reconnect")
host, port, index, priority = @sender.client.identity_parts(@ping_id)
@sender.agent.connect(host, port, index, priority, force = true)
else
Log.warning("Mapper ping via broker #{@ping_id} timed out after #{PING_TIMEOUT} seconds")
end
rescue Exception => e
ErrorTracker.log(self, "Failed to reconnect to broker #{@ping_id}", e)
end
else
@ping_timer = nil
end
end
handler = lambda do |_|
begin
if @ping_timer
@ping_stats.update("success")
@ping_timer.cancel
@ping_timer = nil
@ping_timeouts[@ping_id] = 0
@ping_id = nil
end
rescue Exception => e
ErrorTracker.log(self, "Failed to cancel router ping", e)
end
end
request = Request.new("/router/ping", nil, {:from => @sender.identity, :token => AgentIdentity.generate})
@sender.pending_requests[request.token] = PendingRequest.new(Request, Time.now, handler)
ids = [@ping_id] if @ping_id
@ping_id = @sender.send(:publish, request, ids).first
end
true
end | ruby | def check(id = nil, max_ping_timeouts = MAX_PING_TIMEOUTS)
unless @terminating || @ping_timer || (id && [email protected]?(id))
@ping_id = id
@ping_timer = EM::Timer.new(PING_TIMEOUT) do
if @ping_id
begin
@ping_stats.update("timeout")
@ping_timer = nil
@ping_timeouts[@ping_id] = (@ping_timeouts[@ping_id] || 0) + 1
if @ping_timeouts[@ping_id] >= max_ping_timeouts
ErrorTracker.log(self, "Mapper ping via broker #{@ping_id} timed out after #{PING_TIMEOUT} seconds and now " +
"reached maximum of #{max_ping_timeouts} timeout#{max_ping_timeouts > 1 ? 's' : ''}, " +
"attempting to reconnect")
host, port, index, priority = @sender.client.identity_parts(@ping_id)
@sender.agent.connect(host, port, index, priority, force = true)
else
Log.warning("Mapper ping via broker #{@ping_id} timed out after #{PING_TIMEOUT} seconds")
end
rescue Exception => e
ErrorTracker.log(self, "Failed to reconnect to broker #{@ping_id}", e)
end
else
@ping_timer = nil
end
end
handler = lambda do |_|
begin
if @ping_timer
@ping_stats.update("success")
@ping_timer.cancel
@ping_timer = nil
@ping_timeouts[@ping_id] = 0
@ping_id = nil
end
rescue Exception => e
ErrorTracker.log(self, "Failed to cancel router ping", e)
end
end
request = Request.new("/router/ping", nil, {:from => @sender.identity, :token => AgentIdentity.generate})
@sender.pending_requests[request.token] = PendingRequest.new(Request, Time.now, handler)
ids = [@ping_id] if @ping_id
@ping_id = @sender.send(:publish, request, ids).first
end
true
end | [
"def",
"check",
"(",
"id",
"=",
"nil",
",",
"max_ping_timeouts",
"=",
"MAX_PING_TIMEOUTS",
")",
"unless",
"@terminating",
"||",
"@ping_timer",
"||",
"(",
"id",
"&&",
"!",
"@sender",
".",
"agent",
".",
"client",
".",
"connected?",
"(",
"id",
")",
")",
"@ping_id",
"=",
"id",
"@ping_timer",
"=",
"EM",
"::",
"Timer",
".",
"new",
"(",
"PING_TIMEOUT",
")",
"do",
"if",
"@ping_id",
"begin",
"@ping_stats",
".",
"update",
"(",
"\"timeout\"",
")",
"@ping_timer",
"=",
"nil",
"@ping_timeouts",
"[",
"@ping_id",
"]",
"=",
"(",
"@ping_timeouts",
"[",
"@ping_id",
"]",
"||",
"0",
")",
"+",
"1",
"if",
"@ping_timeouts",
"[",
"@ping_id",
"]",
">=",
"max_ping_timeouts",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Mapper ping via broker #{@ping_id} timed out after #{PING_TIMEOUT} seconds and now \"",
"+",
"\"reached maximum of #{max_ping_timeouts} timeout#{max_ping_timeouts > 1 ? 's' : ''}, \"",
"+",
"\"attempting to reconnect\"",
")",
"host",
",",
"port",
",",
"index",
",",
"priority",
"=",
"@sender",
".",
"client",
".",
"identity_parts",
"(",
"@ping_id",
")",
"@sender",
".",
"agent",
".",
"connect",
"(",
"host",
",",
"port",
",",
"index",
",",
"priority",
",",
"force",
"=",
"true",
")",
"else",
"Log",
".",
"warning",
"(",
"\"Mapper ping via broker #{@ping_id} timed out after #{PING_TIMEOUT} seconds\"",
")",
"end",
"rescue",
"Exception",
"=>",
"e",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Failed to reconnect to broker #{@ping_id}\"",
",",
"e",
")",
"end",
"else",
"@ping_timer",
"=",
"nil",
"end",
"end",
"handler",
"=",
"lambda",
"do",
"|",
"_",
"|",
"begin",
"if",
"@ping_timer",
"@ping_stats",
".",
"update",
"(",
"\"success\"",
")",
"@ping_timer",
".",
"cancel",
"@ping_timer",
"=",
"nil",
"@ping_timeouts",
"[",
"@ping_id",
"]",
"=",
"0",
"@ping_id",
"=",
"nil",
"end",
"rescue",
"Exception",
"=>",
"e",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Failed to cancel router ping\"",
",",
"e",
")",
"end",
"end",
"request",
"=",
"Request",
".",
"new",
"(",
"\"/router/ping\"",
",",
"nil",
",",
"{",
":from",
"=>",
"@sender",
".",
"identity",
",",
":token",
"=>",
"AgentIdentity",
".",
"generate",
"}",
")",
"@sender",
".",
"pending_requests",
"[",
"request",
".",
"token",
"]",
"=",
"PendingRequest",
".",
"new",
"(",
"Request",
",",
"Time",
".",
"now",
",",
"handler",
")",
"ids",
"=",
"[",
"@ping_id",
"]",
"if",
"@ping_id",
"@ping_id",
"=",
"@sender",
".",
"send",
"(",
":publish",
",",
"request",
",",
"ids",
")",
".",
"first",
"end",
"true",
"end"
] | Check whether broker connection is usable by pinging a router via that broker
Attempt to reconnect if ping does not respond in PING_TIMEOUT seconds and
if have reached timeout limit
Ignore request if already checking a connection
=== Parameters
id(String):: Identity of specific broker to use to send ping, defaults to any
currently connected broker
max_ping_timeouts(Integer):: Maximum number of ping timeouts before attempt
to reconnect, defaults to MAX_PING_TIMEOUTS
=== Return
true:: Always return true | [
"Check",
"whether",
"broker",
"connection",
"is",
"usable",
"by",
"pinging",
"a",
"router",
"via",
"that",
"broker",
"Attempt",
"to",
"reconnect",
"if",
"ping",
"does",
"not",
"respond",
"in",
"PING_TIMEOUT",
"seconds",
"and",
"if",
"have",
"reached",
"timeout",
"limit",
"Ignore",
"request",
"if",
"already",
"checking",
"a",
"connection"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/connectivity_checker.rb#L90-L135 | train |
rightscale/right_agent | lib/right_agent/connectivity_checker.rb | RightScale.ConnectivityChecker.restart_inactivity_timer | def restart_inactivity_timer
@inactivity_timer.cancel if @inactivity_timer
@inactivity_timer = EM::Timer.new(@check_interval) do
begin
check(id = nil, max_ping_timeouts = 1)
rescue Exception => e
ErrorTracker.log(self, "Failed connectivity check", e)
end
end
true
end | ruby | def restart_inactivity_timer
@inactivity_timer.cancel if @inactivity_timer
@inactivity_timer = EM::Timer.new(@check_interval) do
begin
check(id = nil, max_ping_timeouts = 1)
rescue Exception => e
ErrorTracker.log(self, "Failed connectivity check", e)
end
end
true
end | [
"def",
"restart_inactivity_timer",
"@inactivity_timer",
".",
"cancel",
"if",
"@inactivity_timer",
"@inactivity_timer",
"=",
"EM",
"::",
"Timer",
".",
"new",
"(",
"@check_interval",
")",
"do",
"begin",
"check",
"(",
"id",
"=",
"nil",
",",
"max_ping_timeouts",
"=",
"1",
")",
"rescue",
"Exception",
"=>",
"e",
"ErrorTracker",
".",
"log",
"(",
"self",
",",
"\"Failed connectivity check\"",
",",
"e",
")",
"end",
"end",
"true",
"end"
] | Start timer that waits for inactive messaging period to end before checking connectivity
=== Return
true:: Always return true | [
"Start",
"timer",
"that",
"waits",
"for",
"inactive",
"messaging",
"period",
"to",
"end",
"before",
"checking",
"connectivity"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/connectivity_checker.rb#L161-L171 | train |
rightscale/right_agent | lib/right_agent/dispatched_cache.rb | RightScale.DispatchedCache.serviced_by | def serviced_by(token)
if @cache[token]
@cache[token] = Time.now.to_i
@lru.push(@lru.delete(token))
@identity
end
end | ruby | def serviced_by(token)
if @cache[token]
@cache[token] = Time.now.to_i
@lru.push(@lru.delete(token))
@identity
end
end | [
"def",
"serviced_by",
"(",
"token",
")",
"if",
"@cache",
"[",
"token",
"]",
"@cache",
"[",
"token",
"]",
"=",
"Time",
".",
"now",
".",
"to_i",
"@lru",
".",
"push",
"(",
"@lru",
".",
"delete",
"(",
"token",
")",
")",
"@identity",
"end",
"end"
] | Determine whether request has already been serviced
=== Parameters
token(String):: Generated message identifier
=== Return
(String|nil):: Identity of agent that already serviced request, or nil if none | [
"Determine",
"whether",
"request",
"has",
"already",
"been",
"serviced"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/dispatched_cache.rb#L75-L81 | train |
rightscale/right_agent | lib/right_agent/dispatched_cache.rb | RightScale.DispatchedCache.stats | def stats
if (s = size) > 0
now = Time.now.to_i
{
"local total" => s,
"local max age" => RightSupport::Stats.elapsed(now - @cache[@lru.first])
}
end
end | ruby | def stats
if (s = size) > 0
now = Time.now.to_i
{
"local total" => s,
"local max age" => RightSupport::Stats.elapsed(now - @cache[@lru.first])
}
end
end | [
"def",
"stats",
"if",
"(",
"s",
"=",
"size",
")",
">",
"0",
"now",
"=",
"Time",
".",
"now",
".",
"to_i",
"{",
"\"local total\"",
"=>",
"s",
",",
"\"local max age\"",
"=>",
"RightSupport",
"::",
"Stats",
".",
"elapsed",
"(",
"now",
"-",
"@cache",
"[",
"@lru",
".",
"first",
"]",
")",
"}",
"end",
"end"
] | Get local cache statistics
=== Return
stats(Hash|nil):: Current statistics, or nil if cache empty
"local total"(Integer):: Total number in local cache, or nil if none
"local max age"(String):: Time since oldest local cache entry created or updated | [
"Get",
"local",
"cache",
"statistics"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/dispatched_cache.rb#L89-L97 | train |
rightscale/right_agent | lib/right_agent/scripts/agent_controller.rb | RightScale.AgentController.control | def control(options)
# Initialize directory settings
AgentConfig.cfg_dir = options[:cfg_dir]
AgentConfig.pid_dir = options[:pid_dir]
# List agents if requested
list_configured_agents if options[:list]
# Validate arguments
action = options.delete(:action)
fail("No action specified on the command line.", print_usage = true) unless action
if action == 'kill' && (options[:pid_file].nil? || !File.file?(options[:pid_file]))
fail("Missing or invalid pid file #{options[:pid_file]}", print_usage = true)
end
if options[:agent_name]
if action == 'start'
cfg = configure_agent(action, options)
else
cfg = AgentConfig.load_cfg(options[:agent_name])
fail("Deployment is missing configuration file #{AgentConfig.cfg_file(options[:agent_name]).inspect}.") unless cfg
end
options.delete(:identity)
options = cfg.merge(options)
AgentConfig.root_dir = options[:root_dir]
AgentConfig.pid_dir = options[:pid_dir]
Log.program_name = syslog_program_name(options)
Log.facility = syslog_facility(options)
Log.log_to_file_only(options[:log_to_file_only])
configure_proxy(options[:http_proxy], options[:http_no_proxy]) if options[:http_proxy]
elsif options[:identity]
options[:agent_name] = AgentConfig.agent_name(options[:identity])
end
@options = DEFAULT_OPTIONS.clone.merge(options.merge(FORCED_OPTIONS))
FileUtils.mkdir_p(@options[:pid_dir]) unless @options[:pid_dir].nil? || File.directory?(@options[:pid_dir])
# Execute request
success = case action
when /show|killall/
action = 'stop' if action == 'killall'
s = true
AgentConfig.cfg_agents.each { |agent_name| s &&= dispatch(action, agent_name) }
s
when 'kill'
kill_process
else
dispatch(action, @options[:agent_name])
end
exit(1) unless success
end | ruby | def control(options)
# Initialize directory settings
AgentConfig.cfg_dir = options[:cfg_dir]
AgentConfig.pid_dir = options[:pid_dir]
# List agents if requested
list_configured_agents if options[:list]
# Validate arguments
action = options.delete(:action)
fail("No action specified on the command line.", print_usage = true) unless action
if action == 'kill' && (options[:pid_file].nil? || !File.file?(options[:pid_file]))
fail("Missing or invalid pid file #{options[:pid_file]}", print_usage = true)
end
if options[:agent_name]
if action == 'start'
cfg = configure_agent(action, options)
else
cfg = AgentConfig.load_cfg(options[:agent_name])
fail("Deployment is missing configuration file #{AgentConfig.cfg_file(options[:agent_name]).inspect}.") unless cfg
end
options.delete(:identity)
options = cfg.merge(options)
AgentConfig.root_dir = options[:root_dir]
AgentConfig.pid_dir = options[:pid_dir]
Log.program_name = syslog_program_name(options)
Log.facility = syslog_facility(options)
Log.log_to_file_only(options[:log_to_file_only])
configure_proxy(options[:http_proxy], options[:http_no_proxy]) if options[:http_proxy]
elsif options[:identity]
options[:agent_name] = AgentConfig.agent_name(options[:identity])
end
@options = DEFAULT_OPTIONS.clone.merge(options.merge(FORCED_OPTIONS))
FileUtils.mkdir_p(@options[:pid_dir]) unless @options[:pid_dir].nil? || File.directory?(@options[:pid_dir])
# Execute request
success = case action
when /show|killall/
action = 'stop' if action == 'killall'
s = true
AgentConfig.cfg_agents.each { |agent_name| s &&= dispatch(action, agent_name) }
s
when 'kill'
kill_process
else
dispatch(action, @options[:agent_name])
end
exit(1) unless success
end | [
"def",
"control",
"(",
"options",
")",
"AgentConfig",
".",
"cfg_dir",
"=",
"options",
"[",
":cfg_dir",
"]",
"AgentConfig",
".",
"pid_dir",
"=",
"options",
"[",
":pid_dir",
"]",
"list_configured_agents",
"if",
"options",
"[",
":list",
"]",
"action",
"=",
"options",
".",
"delete",
"(",
":action",
")",
"fail",
"(",
"\"No action specified on the command line.\"",
",",
"print_usage",
"=",
"true",
")",
"unless",
"action",
"if",
"action",
"==",
"'kill'",
"&&",
"(",
"options",
"[",
":pid_file",
"]",
".",
"nil?",
"||",
"!",
"File",
".",
"file?",
"(",
"options",
"[",
":pid_file",
"]",
")",
")",
"fail",
"(",
"\"Missing or invalid pid file #{options[:pid_file]}\"",
",",
"print_usage",
"=",
"true",
")",
"end",
"if",
"options",
"[",
":agent_name",
"]",
"if",
"action",
"==",
"'start'",
"cfg",
"=",
"configure_agent",
"(",
"action",
",",
"options",
")",
"else",
"cfg",
"=",
"AgentConfig",
".",
"load_cfg",
"(",
"options",
"[",
":agent_name",
"]",
")",
"fail",
"(",
"\"Deployment is missing configuration file #{AgentConfig.cfg_file(options[:agent_name]).inspect}.\"",
")",
"unless",
"cfg",
"end",
"options",
".",
"delete",
"(",
":identity",
")",
"options",
"=",
"cfg",
".",
"merge",
"(",
"options",
")",
"AgentConfig",
".",
"root_dir",
"=",
"options",
"[",
":root_dir",
"]",
"AgentConfig",
".",
"pid_dir",
"=",
"options",
"[",
":pid_dir",
"]",
"Log",
".",
"program_name",
"=",
"syslog_program_name",
"(",
"options",
")",
"Log",
".",
"facility",
"=",
"syslog_facility",
"(",
"options",
")",
"Log",
".",
"log_to_file_only",
"(",
"options",
"[",
":log_to_file_only",
"]",
")",
"configure_proxy",
"(",
"options",
"[",
":http_proxy",
"]",
",",
"options",
"[",
":http_no_proxy",
"]",
")",
"if",
"options",
"[",
":http_proxy",
"]",
"elsif",
"options",
"[",
":identity",
"]",
"options",
"[",
":agent_name",
"]",
"=",
"AgentConfig",
".",
"agent_name",
"(",
"options",
"[",
":identity",
"]",
")",
"end",
"@options",
"=",
"DEFAULT_OPTIONS",
".",
"clone",
".",
"merge",
"(",
"options",
".",
"merge",
"(",
"FORCED_OPTIONS",
")",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"@options",
"[",
":pid_dir",
"]",
")",
"unless",
"@options",
"[",
":pid_dir",
"]",
".",
"nil?",
"||",
"File",
".",
"directory?",
"(",
"@options",
"[",
":pid_dir",
"]",
")",
"success",
"=",
"case",
"action",
"when",
"/",
"/",
"action",
"=",
"'stop'",
"if",
"action",
"==",
"'killall'",
"s",
"=",
"true",
"AgentConfig",
".",
"cfg_agents",
".",
"each",
"{",
"|",
"agent_name",
"|",
"s",
"&&=",
"dispatch",
"(",
"action",
",",
"agent_name",
")",
"}",
"s",
"when",
"'kill'",
"kill_process",
"else",
"dispatch",
"(",
"action",
",",
"@options",
"[",
":agent_name",
"]",
")",
"end",
"exit",
"(",
"1",
")",
"unless",
"success",
"end"
] | Parse arguments and execute request
=== Parameters
options(Hash):: Command line options
=== Return
true:: Always return true | [
"Parse",
"arguments",
"and",
"execute",
"request"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/agent_controller.rb#L116-L166 | train |
rightscale/right_agent | lib/right_agent/scripts/agent_controller.rb | RightScale.AgentController.kill_process | def kill_process(sig = 'TERM')
content = IO.read(@options[:pid_file])
pid = content.to_i
fail("Invalid pid file content #{content.inspect}") if pid == 0
begin
Process.kill(sig, pid)
rescue Errno::ESRCH => e
fail("Could not find process with pid #{pid}")
rescue Errno::EPERM => e
fail("You don't have permissions to stop process #{pid}")
rescue Exception => e
fail(e.message)
end
true
end | ruby | def kill_process(sig = 'TERM')
content = IO.read(@options[:pid_file])
pid = content.to_i
fail("Invalid pid file content #{content.inspect}") if pid == 0
begin
Process.kill(sig, pid)
rescue Errno::ESRCH => e
fail("Could not find process with pid #{pid}")
rescue Errno::EPERM => e
fail("You don't have permissions to stop process #{pid}")
rescue Exception => e
fail(e.message)
end
true
end | [
"def",
"kill_process",
"(",
"sig",
"=",
"'TERM'",
")",
"content",
"=",
"IO",
".",
"read",
"(",
"@options",
"[",
":pid_file",
"]",
")",
"pid",
"=",
"content",
".",
"to_i",
"fail",
"(",
"\"Invalid pid file content #{content.inspect}\"",
")",
"if",
"pid",
"==",
"0",
"begin",
"Process",
".",
"kill",
"(",
"sig",
",",
"pid",
")",
"rescue",
"Errno",
"::",
"ESRCH",
"=>",
"e",
"fail",
"(",
"\"Could not find process with pid #{pid}\"",
")",
"rescue",
"Errno",
"::",
"EPERM",
"=>",
"e",
"fail",
"(",
"\"You don't have permissions to stop process #{pid}\"",
")",
"rescue",
"Exception",
"=>",
"e",
"fail",
"(",
"e",
".",
"message",
")",
"end",
"true",
"end"
] | Kill process defined in pid file
=== Parameters
sig(String):: Signal to be used for kill
=== Return
true:: Always return true | [
"Kill",
"process",
"defined",
"in",
"pid",
"file"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/agent_controller.rb#L308-L322 | train |
rightscale/right_agent | lib/right_agent/scripts/agent_controller.rb | RightScale.AgentController.stop_agent | def stop_agent(agent_name)
res = false
if (pid_file = AgentConfig.pid_file(agent_name))
name = human_readable_name(agent_name, pid_file.identity)
if (pid = pid_file.read_pid[:pid])
begin
Process.kill('TERM', pid)
res = true
puts "#{name} stopped"
rescue Errno::ESRCH
puts "#{name} not running"
end
elsif File.file?(pid_file.to_s)
puts "Invalid pid file '#{pid_file.to_s}' content: #{IO.read(pid_file.to_s)}"
else
puts "#{name} not running"
end
else
puts "Non-existent pid file for #{agent_name}"
end
res
end | ruby | def stop_agent(agent_name)
res = false
if (pid_file = AgentConfig.pid_file(agent_name))
name = human_readable_name(agent_name, pid_file.identity)
if (pid = pid_file.read_pid[:pid])
begin
Process.kill('TERM', pid)
res = true
puts "#{name} stopped"
rescue Errno::ESRCH
puts "#{name} not running"
end
elsif File.file?(pid_file.to_s)
puts "Invalid pid file '#{pid_file.to_s}' content: #{IO.read(pid_file.to_s)}"
else
puts "#{name} not running"
end
else
puts "Non-existent pid file for #{agent_name}"
end
res
end | [
"def",
"stop_agent",
"(",
"agent_name",
")",
"res",
"=",
"false",
"if",
"(",
"pid_file",
"=",
"AgentConfig",
".",
"pid_file",
"(",
"agent_name",
")",
")",
"name",
"=",
"human_readable_name",
"(",
"agent_name",
",",
"pid_file",
".",
"identity",
")",
"if",
"(",
"pid",
"=",
"pid_file",
".",
"read_pid",
"[",
":pid",
"]",
")",
"begin",
"Process",
".",
"kill",
"(",
"'TERM'",
",",
"pid",
")",
"res",
"=",
"true",
"puts",
"\"#{name} stopped\"",
"rescue",
"Errno",
"::",
"ESRCH",
"puts",
"\"#{name} not running\"",
"end",
"elsif",
"File",
".",
"file?",
"(",
"pid_file",
".",
"to_s",
")",
"puts",
"\"Invalid pid file '#{pid_file.to_s}' content: #{IO.read(pid_file.to_s)}\"",
"else",
"puts",
"\"#{name} not running\"",
"end",
"else",
"puts",
"\"Non-existent pid file for #{agent_name}\"",
"end",
"res",
"end"
] | Stop agent process
=== Parameters
agent_name(String):: Agent name
=== Return
(Boolean):: true if process was stopped, otherwise false | [
"Stop",
"agent",
"process"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/agent_controller.rb#L371-L392 | train |
rightscale/right_agent | lib/right_agent/scripts/agent_controller.rb | RightScale.AgentController.list_configured_agents | def list_configured_agents
agents = AgentConfig.cfg_agents
if agents.empty?
puts "Found no configured agents"
else
puts "Configured agents:"
agents.each { |a| puts " - #{a}" }
end
exit
end | ruby | def list_configured_agents
agents = AgentConfig.cfg_agents
if agents.empty?
puts "Found no configured agents"
else
puts "Configured agents:"
agents.each { |a| puts " - #{a}" }
end
exit
end | [
"def",
"list_configured_agents",
"agents",
"=",
"AgentConfig",
".",
"cfg_agents",
"if",
"agents",
".",
"empty?",
"puts",
"\"Found no configured agents\"",
"else",
"puts",
"\"Configured agents:\"",
"agents",
".",
"each",
"{",
"|",
"a",
"|",
"puts",
"\" - #{a}\"",
"}",
"end",
"exit",
"end"
] | List all configured agents
=== Return
never | [
"List",
"all",
"configured",
"agents"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/agent_controller.rb#L439-L448 | train |
rightscale/right_agent | lib/right_agent/scripts/agent_controller.rb | RightScale.AgentController.configure_agent | def configure_agent(action, options)
agent_type = options[:agent_type]
agent_name = options[:agent_name]
if agent_name != agent_type && (cfg = AgentConfig.load_cfg(agent_type))
base_id = (options[:base_id] || AgentIdentity.parse(cfg[:identity]).base_id.to_s).to_i
unless (identity = AgentConfig.agent_options(agent_name)[:identity]) &&
AgentIdentity.parse(identity).base_id == base_id
identity = AgentIdentity.new(options[:prefix] || 'rs', options[:agent_type], base_id, options[:token]).to_s
end
cfg.merge!(:identity => identity)
cfg_file = AgentConfig.store_cfg(agent_name, cfg)
puts "Generated configuration file for #{agent_name} agent: #{cfg_file}"
elsif !(cfg = AgentConfig.load_cfg(agent_name))
fail("Deployment is missing configuration file #{AgentConfig.cfg_file(agent_name).inspect}")
end
cfg
end | ruby | def configure_agent(action, options)
agent_type = options[:agent_type]
agent_name = options[:agent_name]
if agent_name != agent_type && (cfg = AgentConfig.load_cfg(agent_type))
base_id = (options[:base_id] || AgentIdentity.parse(cfg[:identity]).base_id.to_s).to_i
unless (identity = AgentConfig.agent_options(agent_name)[:identity]) &&
AgentIdentity.parse(identity).base_id == base_id
identity = AgentIdentity.new(options[:prefix] || 'rs', options[:agent_type], base_id, options[:token]).to_s
end
cfg.merge!(:identity => identity)
cfg_file = AgentConfig.store_cfg(agent_name, cfg)
puts "Generated configuration file for #{agent_name} agent: #{cfg_file}"
elsif !(cfg = AgentConfig.load_cfg(agent_name))
fail("Deployment is missing configuration file #{AgentConfig.cfg_file(agent_name).inspect}")
end
cfg
end | [
"def",
"configure_agent",
"(",
"action",
",",
"options",
")",
"agent_type",
"=",
"options",
"[",
":agent_type",
"]",
"agent_name",
"=",
"options",
"[",
":agent_name",
"]",
"if",
"agent_name",
"!=",
"agent_type",
"&&",
"(",
"cfg",
"=",
"AgentConfig",
".",
"load_cfg",
"(",
"agent_type",
")",
")",
"base_id",
"=",
"(",
"options",
"[",
":base_id",
"]",
"||",
"AgentIdentity",
".",
"parse",
"(",
"cfg",
"[",
":identity",
"]",
")",
".",
"base_id",
".",
"to_s",
")",
".",
"to_i",
"unless",
"(",
"identity",
"=",
"AgentConfig",
".",
"agent_options",
"(",
"agent_name",
")",
"[",
":identity",
"]",
")",
"&&",
"AgentIdentity",
".",
"parse",
"(",
"identity",
")",
".",
"base_id",
"==",
"base_id",
"identity",
"=",
"AgentIdentity",
".",
"new",
"(",
"options",
"[",
":prefix",
"]",
"||",
"'rs'",
",",
"options",
"[",
":agent_type",
"]",
",",
"base_id",
",",
"options",
"[",
":token",
"]",
")",
".",
"to_s",
"end",
"cfg",
".",
"merge!",
"(",
":identity",
"=>",
"identity",
")",
"cfg_file",
"=",
"AgentConfig",
".",
"store_cfg",
"(",
"agent_name",
",",
"cfg",
")",
"puts",
"\"Generated configuration file for #{agent_name} agent: #{cfg_file}\"",
"elsif",
"!",
"(",
"cfg",
"=",
"AgentConfig",
".",
"load_cfg",
"(",
"agent_name",
")",
")",
"fail",
"(",
"\"Deployment is missing configuration file #{AgentConfig.cfg_file(agent_name).inspect}\"",
")",
"end",
"cfg",
"end"
] | Determine configuration settings for this agent and persist them if needed
Reuse existing agent identity when possible
=== Parameters
action(String):: Requested action
options(Hash):: Command line options
=== Return
cfg(Hash):: Persisted configuration options | [
"Determine",
"configuration",
"settings",
"for",
"this",
"agent",
"and",
"persist",
"them",
"if",
"needed",
"Reuse",
"existing",
"agent",
"identity",
"when",
"possible"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/agent_controller.rb#L481-L497 | train |
rightscale/right_agent | lib/right_agent/scripts/agent_controller.rb | RightScale.AgentController.configure_proxy | def configure_proxy(proxy_setting, exceptions)
ENV['HTTP_PROXY'] = proxy_setting
ENV['http_proxy'] = proxy_setting
ENV['HTTPS_PROXY'] = proxy_setting
ENV['https_proxy'] = proxy_setting
ENV['NO_PROXY'] = exceptions
ENV['no_proxy'] = exceptions
true
end | ruby | def configure_proxy(proxy_setting, exceptions)
ENV['HTTP_PROXY'] = proxy_setting
ENV['http_proxy'] = proxy_setting
ENV['HTTPS_PROXY'] = proxy_setting
ENV['https_proxy'] = proxy_setting
ENV['NO_PROXY'] = exceptions
ENV['no_proxy'] = exceptions
true
end | [
"def",
"configure_proxy",
"(",
"proxy_setting",
",",
"exceptions",
")",
"ENV",
"[",
"'HTTP_PROXY'",
"]",
"=",
"proxy_setting",
"ENV",
"[",
"'http_proxy'",
"]",
"=",
"proxy_setting",
"ENV",
"[",
"'HTTPS_PROXY'",
"]",
"=",
"proxy_setting",
"ENV",
"[",
"'https_proxy'",
"]",
"=",
"proxy_setting",
"ENV",
"[",
"'NO_PROXY'",
"]",
"=",
"exceptions",
"ENV",
"[",
"'no_proxy'",
"]",
"=",
"exceptions",
"true",
"end"
] | Enable the use of an HTTP proxy for this process and its subprocesses
=== Parameters
proxy_setting(String):: Proxy to use
exceptions(String):: Comma-separated list of proxy exceptions (e.g. metadata server)
=== Return
true:: Always return true | [
"Enable",
"the",
"use",
"of",
"an",
"HTTP",
"proxy",
"for",
"this",
"process",
"and",
"its",
"subprocesses"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/agent_controller.rb#L507-L515 | train |
rightscale/right_agent | lib/right_agent/serialize/serializer.rb | RightScale.Serializer.cascade_serializers | def cascade_serializers(action, packet, serializers, id = nil)
errors = []
serializers.map do |serializer|
obj = nil
begin
obj = serializer == SecureSerializer ? serializer.send(action, packet, id) : serializer.send(action, packet)
rescue RightSupport::Net::NoResult, SocketError => e
raise Exceptions::ConnectivityFailure.new("Failed to #{action} with #{serializer.name} due to external " +
"service access failures (#{e.class.name}: #{e.message})", e)
rescue SecureSerializer::MissingCertificate, SecureSerializer::MissingPrivateKey, SecureSerializer::InvalidSignature => e
errors << Log.format("Failed to #{action} with #{serializer.name}", e)
rescue StandardError => e
errors << Log.format("Failed to #{action} with #{serializer.name}", e, :trace)
end
return obj if obj
end
raise SerializationError.new(action, packet, serializers, errors.join("\n"))
end | ruby | def cascade_serializers(action, packet, serializers, id = nil)
errors = []
serializers.map do |serializer|
obj = nil
begin
obj = serializer == SecureSerializer ? serializer.send(action, packet, id) : serializer.send(action, packet)
rescue RightSupport::Net::NoResult, SocketError => e
raise Exceptions::ConnectivityFailure.new("Failed to #{action} with #{serializer.name} due to external " +
"service access failures (#{e.class.name}: #{e.message})", e)
rescue SecureSerializer::MissingCertificate, SecureSerializer::MissingPrivateKey, SecureSerializer::InvalidSignature => e
errors << Log.format("Failed to #{action} with #{serializer.name}", e)
rescue StandardError => e
errors << Log.format("Failed to #{action} with #{serializer.name}", e, :trace)
end
return obj if obj
end
raise SerializationError.new(action, packet, serializers, errors.join("\n"))
end | [
"def",
"cascade_serializers",
"(",
"action",
",",
"packet",
",",
"serializers",
",",
"id",
"=",
"nil",
")",
"errors",
"=",
"[",
"]",
"serializers",
".",
"map",
"do",
"|",
"serializer",
"|",
"obj",
"=",
"nil",
"begin",
"obj",
"=",
"serializer",
"==",
"SecureSerializer",
"?",
"serializer",
".",
"send",
"(",
"action",
",",
"packet",
",",
"id",
")",
":",
"serializer",
".",
"send",
"(",
"action",
",",
"packet",
")",
"rescue",
"RightSupport",
"::",
"Net",
"::",
"NoResult",
",",
"SocketError",
"=>",
"e",
"raise",
"Exceptions",
"::",
"ConnectivityFailure",
".",
"new",
"(",
"\"Failed to #{action} with #{serializer.name} due to external \"",
"+",
"\"service access failures (#{e.class.name}: #{e.message})\"",
",",
"e",
")",
"rescue",
"SecureSerializer",
"::",
"MissingCertificate",
",",
"SecureSerializer",
"::",
"MissingPrivateKey",
",",
"SecureSerializer",
"::",
"InvalidSignature",
"=>",
"e",
"errors",
"<<",
"Log",
".",
"format",
"(",
"\"Failed to #{action} with #{serializer.name}\"",
",",
"e",
")",
"rescue",
"StandardError",
"=>",
"e",
"errors",
"<<",
"Log",
".",
"format",
"(",
"\"Failed to #{action} with #{serializer.name}\"",
",",
"e",
",",
":trace",
")",
"end",
"return",
"obj",
"if",
"obj",
"end",
"raise",
"SerializationError",
".",
"new",
"(",
"action",
",",
"packet",
",",
"serializers",
",",
"errors",
".",
"join",
"(",
"\"\\n\"",
")",
")",
"end"
] | Apply serializers in order until one succeeds
=== Parameters
action(Symbol):: Serialization action: :dump or :load
packet(Object|String):: Object or serialized data on which action is to be performed
serializers(Array):: Serializers to apply in order
id(String):: Optional identifier of source of data for use in determining who is the receiver
=== Return
(String|Object):: Result of serialization action
=== Raises
SerializationError:: If none of the serializers can perform the requested action
RightScale::Exceptions::ConnectivityFailure:: If cannot access external services | [
"Apply",
"serializers",
"in",
"order",
"until",
"one",
"succeeds"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/serialize/serializer.rb#L135-L152 | train |
rightscale/right_agent | lib/right_agent/multiplexer.rb | RightScale.Multiplexer.method_missing | def method_missing(m, *args)
res = @targets.inject([]) { |res, t| res << t.send(m, *args) }
res[0]
end | ruby | def method_missing(m, *args)
res = @targets.inject([]) { |res, t| res << t.send(m, *args) }
res[0]
end | [
"def",
"method_missing",
"(",
"m",
",",
"*",
"args",
")",
"res",
"=",
"@targets",
".",
"inject",
"(",
"[",
"]",
")",
"{",
"|",
"res",
",",
"t",
"|",
"res",
"<<",
"t",
".",
"send",
"(",
"m",
",",
"*",
"args",
")",
"}",
"res",
"[",
"0",
"]",
"end"
] | Forward any method invocation to targets
=== Parameters
m(Symbol):: Method that should be multiplexed
args(Array):: Arguments
=== Return
res(Object):: Result of first target in list | [
"Forward",
"any",
"method",
"invocation",
"to",
"targets"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/multiplexer.rb#L85-L88 | train |
rightscale/right_agent | lib/right_agent/multiplexer.rb | RightScale.Multiplexer.respond_to? | def respond_to?(m, *args)
super(m, *args) || @targets.all? { |t| t.respond_to?(m, *args) }
end | ruby | def respond_to?(m, *args)
super(m, *args) || @targets.all? { |t| t.respond_to?(m, *args) }
end | [
"def",
"respond_to?",
"(",
"m",
",",
"*",
"args",
")",
"super",
"(",
"m",
",",
"*",
"args",
")",
"||",
"@targets",
".",
"all?",
"{",
"|",
"t",
"|",
"t",
".",
"respond_to?",
"(",
"m",
",",
"*",
"args",
")",
"}",
"end"
] | Determine whether this object, or ALL of its targets, responds to
the named method.
=== Parameters
m(Symbol):: Forwarded method name
=== Return
(true|false):: True if this object, or ALL targets, respond to the names method; false otherwise | [
"Determine",
"whether",
"this",
"object",
"or",
"ALL",
"of",
"its",
"targets",
"responds",
"to",
"the",
"named",
"method",
"."
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/multiplexer.rb#L98-L100 | train |
rightscale/right_agent | lib/right_agent/operation_result.rb | RightScale.OperationResult.status | def status(reason = false)
case @status_code
when SUCCESS then 'success'
when ERROR then 'error' + (reason ? " (#{truncated_error})" : "")
when CONTINUE then 'continue'
when RETRY then 'retry' + (reason ? " (#{@content})" : "")
when NON_DELIVERY then 'non-delivery' + (reason ? " (#{@content})" : "")
when MULTICAST then 'multicast'
when CANCEL then 'cancel' + (reason ? " (#{@content})" : "")
end
end | ruby | def status(reason = false)
case @status_code
when SUCCESS then 'success'
when ERROR then 'error' + (reason ? " (#{truncated_error})" : "")
when CONTINUE then 'continue'
when RETRY then 'retry' + (reason ? " (#{@content})" : "")
when NON_DELIVERY then 'non-delivery' + (reason ? " (#{@content})" : "")
when MULTICAST then 'multicast'
when CANCEL then 'cancel' + (reason ? " (#{@content})" : "")
end
end | [
"def",
"status",
"(",
"reason",
"=",
"false",
")",
"case",
"@status_code",
"when",
"SUCCESS",
"then",
"'success'",
"when",
"ERROR",
"then",
"'error'",
"+",
"(",
"reason",
"?",
"\" (#{truncated_error})\"",
":",
"\"\"",
")",
"when",
"CONTINUE",
"then",
"'continue'",
"when",
"RETRY",
"then",
"'retry'",
"+",
"(",
"reason",
"?",
"\" (#{@content})\"",
":",
"\"\"",
")",
"when",
"NON_DELIVERY",
"then",
"'non-delivery'",
"+",
"(",
"reason",
"?",
"\" (#{@content})\"",
":",
"\"\"",
")",
"when",
"MULTICAST",
"then",
"'multicast'",
"when",
"CANCEL",
"then",
"'cancel'",
"+",
"(",
"reason",
"?",
"\" (#{@content})\"",
":",
"\"\"",
")",
"end",
"end"
] | User friendly result status
=== Parameters
reason(Boolean):: Whether to include failure reason information, default to false
=== Return
(String):: Name of result code | [
"User",
"friendly",
"result",
"status"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/operation_result.rb#L80-L90 | train |
rightscale/right_agent | lib/right_agent/operation_result.rb | RightScale.OperationResult.truncated_error | def truncated_error
e = @content.is_a?(String) ? @content : @content.inspect
e = e[0, MAX_ERROR_SIZE - 3] + "..." if e.size > (MAX_ERROR_SIZE - 3)
e
end | ruby | def truncated_error
e = @content.is_a?(String) ? @content : @content.inspect
e = e[0, MAX_ERROR_SIZE - 3] + "..." if e.size > (MAX_ERROR_SIZE - 3)
e
end | [
"def",
"truncated_error",
"e",
"=",
"@content",
".",
"is_a?",
"(",
"String",
")",
"?",
"@content",
":",
"@content",
".",
"inspect",
"e",
"=",
"e",
"[",
"0",
",",
"MAX_ERROR_SIZE",
"-",
"3",
"]",
"+",
"\"...\"",
"if",
"e",
".",
"size",
">",
"(",
"MAX_ERROR_SIZE",
"-",
"3",
")",
"e",
"end"
] | Limited length error string
=== Return
e(String):: String of no more than MAX_ERROR_SIZE characters | [
"Limited",
"length",
"error",
"string"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/operation_result.rb#L96-L100 | train |
rightscale/right_agent | lib/right_agent/command/command_io.rb | RightScale.CommandIO.listen | def listen(socket_port, &block)
raise ArgumentError, 'Missing listener block' unless block_given?
raise Exceptions::Application, 'Already listening' if listening
begin
@conn = EM.start_server('127.0.0.1', socket_port, ServerInputHandler, block)
rescue Exception => e
raise Exceptions::IO, 'Listen port unavailable' if e.message =~ /no acceptor/
end
true
end | ruby | def listen(socket_port, &block)
raise ArgumentError, 'Missing listener block' unless block_given?
raise Exceptions::Application, 'Already listening' if listening
begin
@conn = EM.start_server('127.0.0.1', socket_port, ServerInputHandler, block)
rescue Exception => e
raise Exceptions::IO, 'Listen port unavailable' if e.message =~ /no acceptor/
end
true
end | [
"def",
"listen",
"(",
"socket_port",
",",
"&",
"block",
")",
"raise",
"ArgumentError",
",",
"'Missing listener block'",
"unless",
"block_given?",
"raise",
"Exceptions",
"::",
"Application",
",",
"'Already listening'",
"if",
"listening",
"begin",
"@conn",
"=",
"EM",
".",
"start_server",
"(",
"'127.0.0.1'",
",",
"socket_port",
",",
"ServerInputHandler",
",",
"block",
")",
"rescue",
"Exception",
"=>",
"e",
"raise",
"Exceptions",
"::",
"IO",
",",
"'Listen port unavailable'",
"if",
"e",
".",
"message",
"=~",
"/",
"/",
"end",
"true",
"end"
] | Open command socket and wait for input on it
This can only be called again after 'stop_listening' was called
=== Parameters
socket_port(Integer):: Socket port on which to listen
=== Block
The given block should take two arguments:
* First argument will be given the commands sent through the socket
Commands should be serialized using RightScale::CommandSerializer.
* Second argument contains the connection that should be given back to
+reply+ to send reply
=== Return
true:: Always return true
=== Raise
(ArgumentError):: If block is missing
(Exceptions::Application):: If +listen+ has already been called and +stop+ hasn't since
(Exceptions::Application):: If port is already bound | [
"Open",
"command",
"socket",
"and",
"wait",
"for",
"input",
"on",
"it",
"This",
"can",
"only",
"be",
"called",
"again",
"after",
"stop_listening",
"was",
"called"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/command/command_io.rb#L82-L91 | train |
rightscale/right_agent | lib/right_agent/command/command_io.rb | RightScale.CommandIO.reply | def reply(conn, data, close_after_writing=true)
conn.send_data(CommandSerializer.dump(data))
conn.close_connection_after_writing if close_after_writing
true
end | ruby | def reply(conn, data, close_after_writing=true)
conn.send_data(CommandSerializer.dump(data))
conn.close_connection_after_writing if close_after_writing
true
end | [
"def",
"reply",
"(",
"conn",
",",
"data",
",",
"close_after_writing",
"=",
"true",
")",
"conn",
".",
"send_data",
"(",
"CommandSerializer",
".",
"dump",
"(",
"data",
")",
")",
"conn",
".",
"close_connection_after_writing",
"if",
"close_after_writing",
"true",
"end"
] | Write given data to socket, must be listening
=== Parameters
conn(EM::Connection):: Connection used to send data
data(String):: Data that should be written
close_after_writing(TrueClass|FalseClass):: Whether TCP connection with client should be
closed after reply is sent
=== Return
true:: Always return true | [
"Write",
"given",
"data",
"to",
"socket",
"must",
"be",
"listening"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/command/command_io.rb#L118-L122 | train |
rightscale/right_agent | lib/right_agent/scripts/log_level_manager.rb | RightScale.LogLevelManager.manage | def manage(options)
# Initialize configuration directory setting
AgentConfig.cfg_dir = options[:cfg_dir]
# Determine command
level = options[:level]
command = { :name => (level ? 'set_log_level' : 'get_log_level') }
command[:level] = level.to_sym if level
# Determine candidate agents
agent_names = if options[:agent_name]
[options[:agent_name]]
else
AgentConfig.cfg_agents
end
fail("No agents configured") if agent_names.empty?
# Perform command for each agent
count = 0
agent_names.each do |agent_name|
count += 1 if request_log_level(agent_name, command, options)
end
puts("No agents running") if count == 0
true
end | ruby | def manage(options)
# Initialize configuration directory setting
AgentConfig.cfg_dir = options[:cfg_dir]
# Determine command
level = options[:level]
command = { :name => (level ? 'set_log_level' : 'get_log_level') }
command[:level] = level.to_sym if level
# Determine candidate agents
agent_names = if options[:agent_name]
[options[:agent_name]]
else
AgentConfig.cfg_agents
end
fail("No agents configured") if agent_names.empty?
# Perform command for each agent
count = 0
agent_names.each do |agent_name|
count += 1 if request_log_level(agent_name, command, options)
end
puts("No agents running") if count == 0
true
end | [
"def",
"manage",
"(",
"options",
")",
"AgentConfig",
".",
"cfg_dir",
"=",
"options",
"[",
":cfg_dir",
"]",
"level",
"=",
"options",
"[",
":level",
"]",
"command",
"=",
"{",
":name",
"=>",
"(",
"level",
"?",
"'set_log_level'",
":",
"'get_log_level'",
")",
"}",
"command",
"[",
":level",
"]",
"=",
"level",
".",
"to_sym",
"if",
"level",
"agent_names",
"=",
"if",
"options",
"[",
":agent_name",
"]",
"[",
"options",
"[",
":agent_name",
"]",
"]",
"else",
"AgentConfig",
".",
"cfg_agents",
"end",
"fail",
"(",
"\"No agents configured\"",
")",
"if",
"agent_names",
".",
"empty?",
"count",
"=",
"0",
"agent_names",
".",
"each",
"do",
"|",
"agent_name",
"|",
"count",
"+=",
"1",
"if",
"request_log_level",
"(",
"agent_name",
",",
"command",
",",
"options",
")",
"end",
"puts",
"(",
"\"No agents running\"",
")",
"if",
"count",
"==",
"0",
"true",
"end"
] | Handle log level request
=== Parameters
options(Hash):: Command line options
=== Return
true:: Always return true | [
"Handle",
"log",
"level",
"request"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/log_level_manager.rb#L60-L84 | train |
rightscale/right_agent | lib/right_agent/scripts/log_level_manager.rb | RightScale.LogLevelManager.request_log_level | def request_log_level(agent_name, command, options)
res = false
config_options = AgentConfig.agent_options(agent_name)
unless config_options.empty? || (listen_port = config_options[:listen_port]).nil?
fail("Could not retrieve #{agent_name} agent listen port") unless listen_port
client = CommandClient.new(listen_port, config_options[:cookie])
begin
client.send_command(command, options[:verbose], timeout = 5) do |level|
puts "Agent #{agent_name} log level: #{level.to_s.upcase}"
end
res = true
rescue Exception => e
puts "Command #{command.inspect} to #{agent_name} agent failed (#{e})"
end
end
res
end | ruby | def request_log_level(agent_name, command, options)
res = false
config_options = AgentConfig.agent_options(agent_name)
unless config_options.empty? || (listen_port = config_options[:listen_port]).nil?
fail("Could not retrieve #{agent_name} agent listen port") unless listen_port
client = CommandClient.new(listen_port, config_options[:cookie])
begin
client.send_command(command, options[:verbose], timeout = 5) do |level|
puts "Agent #{agent_name} log level: #{level.to_s.upcase}"
end
res = true
rescue Exception => e
puts "Command #{command.inspect} to #{agent_name} agent failed (#{e})"
end
end
res
end | [
"def",
"request_log_level",
"(",
"agent_name",
",",
"command",
",",
"options",
")",
"res",
"=",
"false",
"config_options",
"=",
"AgentConfig",
".",
"agent_options",
"(",
"agent_name",
")",
"unless",
"config_options",
".",
"empty?",
"||",
"(",
"listen_port",
"=",
"config_options",
"[",
":listen_port",
"]",
")",
".",
"nil?",
"fail",
"(",
"\"Could not retrieve #{agent_name} agent listen port\"",
")",
"unless",
"listen_port",
"client",
"=",
"CommandClient",
".",
"new",
"(",
"listen_port",
",",
"config_options",
"[",
":cookie",
"]",
")",
"begin",
"client",
".",
"send_command",
"(",
"command",
",",
"options",
"[",
":verbose",
"]",
",",
"timeout",
"=",
"5",
")",
"do",
"|",
"level",
"|",
"puts",
"\"Agent #{agent_name} log level: #{level.to_s.upcase}\"",
"end",
"res",
"=",
"true",
"rescue",
"Exception",
"=>",
"e",
"puts",
"\"Command #{command.inspect} to #{agent_name} agent failed (#{e})\"",
"end",
"end",
"res",
"end"
] | Send log level request to agent
=== Parameters
agent_name(String):: Agent name
command(String):: Command request
options(Hash):: Command line options
=== Return
(Boolean):: true if agent running, otherwise false | [
"Send",
"log",
"level",
"request",
"to",
"agent"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/log_level_manager.rb#L136-L152 | train |
rightscale/right_agent | lib/right_agent/scripts/common_parser.rb | RightScale.CommonParser.parse_common | def parse_common(opts, options)
opts.on("--test") do
options[:user] = 'test'
options[:pass] = 'testing'
options[:vhost] = '/right_net'
options[:test] = true
options[:pid_dir] = Dir.tmpdir
options[:base_id] = "#{rand(1000000)}"
options[:options][:log_dir] = Dir.tmpdir
end
opts.on("-i", "--identity ID") do |id|
options[:base_id] = id
end
opts.on("-t", "--token TOKEN") do |t|
options[:token] = t
end
opts.on("-S", "--secure-identity") do
options[:secure_identity] = true
end
opts.on("-x", "--prefix PREFIX") do |p|
options[:prefix] = p
end
opts.on("--url URL") do |url|
uri = URI.parse(url)
options[:user] = uri.user if uri.user
options[:pass] = uri.password if uri.password
options[:host] = uri.host
options[:port] = uri.port if uri.port
options[:vhost] = uri.path if (uri.path && !uri.path.empty?)
end
opts.on("-u", "--user USER") do |user|
options[:user] = user
end
opts.on("-p", "--pass PASSWORD") do |pass|
options[:pass] = pass
end
opts.on("-v", "--vhost VHOST") do |vhost|
options[:vhost] = vhost
end
opts.on("-P", "--port PORT") do |port|
options[:port] = port
end
opts.on("-h", "--host HOST") do |host|
options[:host] = host
end
opts.on('--type TYPE') do |t|
options[:agent_type] = t
end
opts.on_tail("--help") do
puts Usage.scan(__FILE__)
exit
end
opts.on_tail("--version") do
puts version
exit
end
true
end | ruby | def parse_common(opts, options)
opts.on("--test") do
options[:user] = 'test'
options[:pass] = 'testing'
options[:vhost] = '/right_net'
options[:test] = true
options[:pid_dir] = Dir.tmpdir
options[:base_id] = "#{rand(1000000)}"
options[:options][:log_dir] = Dir.tmpdir
end
opts.on("-i", "--identity ID") do |id|
options[:base_id] = id
end
opts.on("-t", "--token TOKEN") do |t|
options[:token] = t
end
opts.on("-S", "--secure-identity") do
options[:secure_identity] = true
end
opts.on("-x", "--prefix PREFIX") do |p|
options[:prefix] = p
end
opts.on("--url URL") do |url|
uri = URI.parse(url)
options[:user] = uri.user if uri.user
options[:pass] = uri.password if uri.password
options[:host] = uri.host
options[:port] = uri.port if uri.port
options[:vhost] = uri.path if (uri.path && !uri.path.empty?)
end
opts.on("-u", "--user USER") do |user|
options[:user] = user
end
opts.on("-p", "--pass PASSWORD") do |pass|
options[:pass] = pass
end
opts.on("-v", "--vhost VHOST") do |vhost|
options[:vhost] = vhost
end
opts.on("-P", "--port PORT") do |port|
options[:port] = port
end
opts.on("-h", "--host HOST") do |host|
options[:host] = host
end
opts.on('--type TYPE') do |t|
options[:agent_type] = t
end
opts.on_tail("--help") do
puts Usage.scan(__FILE__)
exit
end
opts.on_tail("--version") do
puts version
exit
end
true
end | [
"def",
"parse_common",
"(",
"opts",
",",
"options",
")",
"opts",
".",
"on",
"(",
"\"--test\"",
")",
"do",
"options",
"[",
":user",
"]",
"=",
"'test'",
"options",
"[",
":pass",
"]",
"=",
"'testing'",
"options",
"[",
":vhost",
"]",
"=",
"'/right_net'",
"options",
"[",
":test",
"]",
"=",
"true",
"options",
"[",
":pid_dir",
"]",
"=",
"Dir",
".",
"tmpdir",
"options",
"[",
":base_id",
"]",
"=",
"\"#{rand(1000000)}\"",
"options",
"[",
":options",
"]",
"[",
":log_dir",
"]",
"=",
"Dir",
".",
"tmpdir",
"end",
"opts",
".",
"on",
"(",
"\"-i\"",
",",
"\"--identity ID\"",
")",
"do",
"|",
"id",
"|",
"options",
"[",
":base_id",
"]",
"=",
"id",
"end",
"opts",
".",
"on",
"(",
"\"-t\"",
",",
"\"--token TOKEN\"",
")",
"do",
"|",
"t",
"|",
"options",
"[",
":token",
"]",
"=",
"t",
"end",
"opts",
".",
"on",
"(",
"\"-S\"",
",",
"\"--secure-identity\"",
")",
"do",
"options",
"[",
":secure_identity",
"]",
"=",
"true",
"end",
"opts",
".",
"on",
"(",
"\"-x\"",
",",
"\"--prefix PREFIX\"",
")",
"do",
"|",
"p",
"|",
"options",
"[",
":prefix",
"]",
"=",
"p",
"end",
"opts",
".",
"on",
"(",
"\"--url URL\"",
")",
"do",
"|",
"url",
"|",
"uri",
"=",
"URI",
".",
"parse",
"(",
"url",
")",
"options",
"[",
":user",
"]",
"=",
"uri",
".",
"user",
"if",
"uri",
".",
"user",
"options",
"[",
":pass",
"]",
"=",
"uri",
".",
"password",
"if",
"uri",
".",
"password",
"options",
"[",
":host",
"]",
"=",
"uri",
".",
"host",
"options",
"[",
":port",
"]",
"=",
"uri",
".",
"port",
"if",
"uri",
".",
"port",
"options",
"[",
":vhost",
"]",
"=",
"uri",
".",
"path",
"if",
"(",
"uri",
".",
"path",
"&&",
"!",
"uri",
".",
"path",
".",
"empty?",
")",
"end",
"opts",
".",
"on",
"(",
"\"-u\"",
",",
"\"--user USER\"",
")",
"do",
"|",
"user",
"|",
"options",
"[",
":user",
"]",
"=",
"user",
"end",
"opts",
".",
"on",
"(",
"\"-p\"",
",",
"\"--pass PASSWORD\"",
")",
"do",
"|",
"pass",
"|",
"options",
"[",
":pass",
"]",
"=",
"pass",
"end",
"opts",
".",
"on",
"(",
"\"-v\"",
",",
"\"--vhost VHOST\"",
")",
"do",
"|",
"vhost",
"|",
"options",
"[",
":vhost",
"]",
"=",
"vhost",
"end",
"opts",
".",
"on",
"(",
"\"-P\"",
",",
"\"--port PORT\"",
")",
"do",
"|",
"port",
"|",
"options",
"[",
":port",
"]",
"=",
"port",
"end",
"opts",
".",
"on",
"(",
"\"-h\"",
",",
"\"--host HOST\"",
")",
"do",
"|",
"host",
"|",
"options",
"[",
":host",
"]",
"=",
"host",
"end",
"opts",
".",
"on",
"(",
"'--type TYPE'",
")",
"do",
"|",
"t",
"|",
"options",
"[",
":agent_type",
"]",
"=",
"t",
"end",
"opts",
".",
"on_tail",
"(",
"\"--help\"",
")",
"do",
"puts",
"Usage",
".",
"scan",
"(",
"__FILE__",
")",
"exit",
"end",
"opts",
".",
"on_tail",
"(",
"\"--version\"",
")",
"do",
"puts",
"version",
"exit",
"end",
"true",
"end"
] | Parse common options between rad and rnac
=== Parameters
opts(OptionParser):: Options parser with options to be parsed
options(Hash):: Storage for options that are parsed
=== Return
true:: Always return true | [
"Parse",
"common",
"options",
"between",
"rad",
"and",
"rnac"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/common_parser.rb#L41-L112 | train |
rightscale/right_agent | lib/right_agent/scripts/common_parser.rb | RightScale.CommonParser.resolve_identity | def resolve_identity(options)
options[:agent_type] = agent_type(options[:agent_type], options[:agent_name])
if options[:base_id]
base_id = options[:base_id].to_i
if base_id.abs.to_s != options[:base_id]
puts "** Identity needs to be a positive integer"
exit(1)
end
token = if options[:secure_identity]
RightScale::SecureIdentity.derive(base_id, options[:token])
else
options[:token]
end
options[:identity] = AgentIdentity.new(options[:prefix] || 'rs', options[:agent_type], base_id, token).to_s
end
end | ruby | def resolve_identity(options)
options[:agent_type] = agent_type(options[:agent_type], options[:agent_name])
if options[:base_id]
base_id = options[:base_id].to_i
if base_id.abs.to_s != options[:base_id]
puts "** Identity needs to be a positive integer"
exit(1)
end
token = if options[:secure_identity]
RightScale::SecureIdentity.derive(base_id, options[:token])
else
options[:token]
end
options[:identity] = AgentIdentity.new(options[:prefix] || 'rs', options[:agent_type], base_id, token).to_s
end
end | [
"def",
"resolve_identity",
"(",
"options",
")",
"options",
"[",
":agent_type",
"]",
"=",
"agent_type",
"(",
"options",
"[",
":agent_type",
"]",
",",
"options",
"[",
":agent_name",
"]",
")",
"if",
"options",
"[",
":base_id",
"]",
"base_id",
"=",
"options",
"[",
":base_id",
"]",
".",
"to_i",
"if",
"base_id",
".",
"abs",
".",
"to_s",
"!=",
"options",
"[",
":base_id",
"]",
"puts",
"\"** Identity needs to be a positive integer\"",
"exit",
"(",
"1",
")",
"end",
"token",
"=",
"if",
"options",
"[",
":secure_identity",
"]",
"RightScale",
"::",
"SecureIdentity",
".",
"derive",
"(",
"base_id",
",",
"options",
"[",
":token",
"]",
")",
"else",
"options",
"[",
":token",
"]",
"end",
"options",
"[",
":identity",
"]",
"=",
"AgentIdentity",
".",
"new",
"(",
"options",
"[",
":prefix",
"]",
"||",
"'rs'",
",",
"options",
"[",
":agent_type",
"]",
",",
"base_id",
",",
"token",
")",
".",
"to_s",
"end",
"end"
] | Generate agent identity from options
Build identity from base_id, token, prefix and agent name
=== Parameters
options(Hash):: Hash containing identity components
=== Return
options(Hash):: | [
"Generate",
"agent",
"identity",
"from",
"options",
"Build",
"identity",
"from",
"base_id",
"token",
"prefix",
"and",
"agent",
"name"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/common_parser.rb#L122-L137 | train |
rightscale/right_agent | lib/right_agent/scripts/common_parser.rb | RightScale.CommonParser.agent_type | def agent_type(type, name)
unless type
if name =~ /^(.*)_[0-9]+$/
type = Regexp.last_match(1)
else
type = name || "instance"
end
end
type
end | ruby | def agent_type(type, name)
unless type
if name =~ /^(.*)_[0-9]+$/
type = Regexp.last_match(1)
else
type = name || "instance"
end
end
type
end | [
"def",
"agent_type",
"(",
"type",
",",
"name",
")",
"unless",
"type",
"if",
"name",
"=~",
"/",
"/",
"type",
"=",
"Regexp",
".",
"last_match",
"(",
"1",
")",
"else",
"type",
"=",
"name",
"||",
"\"instance\"",
"end",
"end",
"type",
"end"
] | Determine agent type
=== Parameters
type(String):: Agent type
name(String):: Agent name
=== Return
(String):: Agent type | [
"Determine",
"agent",
"type"
] | 64c68c162692f0a70543d10def5e4bf56505bd82 | https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/scripts/common_parser.rb#L147-L156 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.