id
int32 0
24.9k
| repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
|
---|---|---|---|---|---|---|---|---|---|---|---|
23,400 | ploubser/JSON-Grep | lib/parser/scanner.rb | JGrep.Scanner.get_token | def get_token
return nil if @token_index >= @arguments.size
begin
case chr(@arguments[@token_index])
when "["
return "statement", gen_substatement
when "]"
return "]"
when "("
return "(", "("
when ")"
return ")", ")"
when "n"
if (chr(@arguments[@token_index + 1]) == "o") && (chr(@arguments[@token_index + 2]) == "t") && ((chr(@arguments[@token_index + 3]) == " ") || (chr(@arguments[@token_index + 3]) == "("))
@token_index += 2
return "not", "not"
else
gen_statement
end
when "!"
return "not", "not"
when "a"
if (chr(@arguments[@token_index + 1]) == "n") && (chr(@arguments[@token_index + 2]) == "d") && ((chr(@arguments[@token_index + 3]) == " ") || (chr(@arguments[@token_index + 3]) == "("))
@token_index += 2
return "and", "and"
else
gen_statement
end
when "&"
if chr(@arguments[@token_index + 1]) == "&"
@token_index += 1
return "and", "and"
else
gen_statement
end
when "o"
if (chr(@arguments[@token_index + 1]) == "r") && ((chr(@arguments[@token_index + 2]) == " ") || (chr(@arguments[@token_index + 2]) == "("))
@token_index += 1
return "or", "or"
else
gen_statement
end
when "|"
if chr(@arguments[@token_index + 1]) == "|"
@token_index += 1
return "or", "or"
else
gen_statement
end
when "+"
value = ""
i = @token_index + 1
begin
value += chr(@arguments[i])
i += 1
end until (i >= @arguments.size) || (chr(@arguments[i]) =~ /\s|\)/)
@token_index = i - 1
return "+", value
when "-"
value = ""
i = @token_index + 1
begin
value += chr(@arguments[i])
i += 1
end until (i >= @arguments.size) || (chr(@arguments[i]) =~ /\s|\)/)
@token_index = i - 1
return "-", value
when " "
return " ", " "
else
gen_statement
end
end
rescue NoMethodError
raise "Error. Expression cannot be parsed."
end | ruby | def get_token
return nil if @token_index >= @arguments.size
begin
case chr(@arguments[@token_index])
when "["
return "statement", gen_substatement
when "]"
return "]"
when "("
return "(", "("
when ")"
return ")", ")"
when "n"
if (chr(@arguments[@token_index + 1]) == "o") && (chr(@arguments[@token_index + 2]) == "t") && ((chr(@arguments[@token_index + 3]) == " ") || (chr(@arguments[@token_index + 3]) == "("))
@token_index += 2
return "not", "not"
else
gen_statement
end
when "!"
return "not", "not"
when "a"
if (chr(@arguments[@token_index + 1]) == "n") && (chr(@arguments[@token_index + 2]) == "d") && ((chr(@arguments[@token_index + 3]) == " ") || (chr(@arguments[@token_index + 3]) == "("))
@token_index += 2
return "and", "and"
else
gen_statement
end
when "&"
if chr(@arguments[@token_index + 1]) == "&"
@token_index += 1
return "and", "and"
else
gen_statement
end
when "o"
if (chr(@arguments[@token_index + 1]) == "r") && ((chr(@arguments[@token_index + 2]) == " ") || (chr(@arguments[@token_index + 2]) == "("))
@token_index += 1
return "or", "or"
else
gen_statement
end
when "|"
if chr(@arguments[@token_index + 1]) == "|"
@token_index += 1
return "or", "or"
else
gen_statement
end
when "+"
value = ""
i = @token_index + 1
begin
value += chr(@arguments[i])
i += 1
end until (i >= @arguments.size) || (chr(@arguments[i]) =~ /\s|\)/)
@token_index = i - 1
return "+", value
when "-"
value = ""
i = @token_index + 1
begin
value += chr(@arguments[i])
i += 1
end until (i >= @arguments.size) || (chr(@arguments[i]) =~ /\s|\)/)
@token_index = i - 1
return "-", value
when " "
return " ", " "
else
gen_statement
end
end
rescue NoMethodError
raise "Error. Expression cannot be parsed."
end | [
"def",
"get_token",
"return",
"nil",
"if",
"@token_index",
">=",
"@arguments",
".",
"size",
"begin",
"case",
"chr",
"(",
"@arguments",
"[",
"@token_index",
"]",
")",
"when",
"\"[\"",
"return",
"\"statement\"",
",",
"gen_substatement",
"when",
"\"]\"",
"return",
"\"]\"",
"when",
"\"(\"",
"return",
"\"(\"",
",",
"\"(\"",
"when",
"\")\"",
"return",
"\")\"",
",",
"\")\"",
"when",
"\"n\"",
"if",
"(",
"chr",
"(",
"@arguments",
"[",
"@token_index",
"+",
"1",
"]",
")",
"==",
"\"o\"",
")",
"&&",
"(",
"chr",
"(",
"@arguments",
"[",
"@token_index",
"+",
"2",
"]",
")",
"==",
"\"t\"",
")",
"&&",
"(",
"(",
"chr",
"(",
"@arguments",
"[",
"@token_index",
"+",
"3",
"]",
")",
"==",
"\" \"",
")",
"||",
"(",
"chr",
"(",
"@arguments",
"[",
"@token_index",
"+",
"3",
"]",
")",
"==",
"\"(\"",
")",
")",
"@token_index",
"+=",
"2",
"return",
"\"not\"",
",",
"\"not\"",
"else",
"gen_statement",
"end",
"when",
"\"!\"",
"return",
"\"not\"",
",",
"\"not\"",
"when",
"\"a\"",
"if",
"(",
"chr",
"(",
"@arguments",
"[",
"@token_index",
"+",
"1",
"]",
")",
"==",
"\"n\"",
")",
"&&",
"(",
"chr",
"(",
"@arguments",
"[",
"@token_index",
"+",
"2",
"]",
")",
"==",
"\"d\"",
")",
"&&",
"(",
"(",
"chr",
"(",
"@arguments",
"[",
"@token_index",
"+",
"3",
"]",
")",
"==",
"\" \"",
")",
"||",
"(",
"chr",
"(",
"@arguments",
"[",
"@token_index",
"+",
"3",
"]",
")",
"==",
"\"(\"",
")",
")",
"@token_index",
"+=",
"2",
"return",
"\"and\"",
",",
"\"and\"",
"else",
"gen_statement",
"end",
"when",
"\"&\"",
"if",
"chr",
"(",
"@arguments",
"[",
"@token_index",
"+",
"1",
"]",
")",
"==",
"\"&\"",
"@token_index",
"+=",
"1",
"return",
"\"and\"",
",",
"\"and\"",
"else",
"gen_statement",
"end",
"when",
"\"o\"",
"if",
"(",
"chr",
"(",
"@arguments",
"[",
"@token_index",
"+",
"1",
"]",
")",
"==",
"\"r\"",
")",
"&&",
"(",
"(",
"chr",
"(",
"@arguments",
"[",
"@token_index",
"+",
"2",
"]",
")",
"==",
"\" \"",
")",
"||",
"(",
"chr",
"(",
"@arguments",
"[",
"@token_index",
"+",
"2",
"]",
")",
"==",
"\"(\"",
")",
")",
"@token_index",
"+=",
"1",
"return",
"\"or\"",
",",
"\"or\"",
"else",
"gen_statement",
"end",
"when",
"\"|\"",
"if",
"chr",
"(",
"@arguments",
"[",
"@token_index",
"+",
"1",
"]",
")",
"==",
"\"|\"",
"@token_index",
"+=",
"1",
"return",
"\"or\"",
",",
"\"or\"",
"else",
"gen_statement",
"end",
"when",
"\"+\"",
"value",
"=",
"\"\"",
"i",
"=",
"@token_index",
"+",
"1",
"begin",
"value",
"+=",
"chr",
"(",
"@arguments",
"[",
"i",
"]",
")",
"i",
"+=",
"1",
"end",
"until",
"(",
"i",
">=",
"@arguments",
".",
"size",
")",
"||",
"(",
"chr",
"(",
"@arguments",
"[",
"i",
"]",
")",
"=~",
"/",
"\\s",
"\\)",
"/",
")",
"@token_index",
"=",
"i",
"-",
"1",
"return",
"\"+\"",
",",
"value",
"when",
"\"-\"",
"value",
"=",
"\"\"",
"i",
"=",
"@token_index",
"+",
"1",
"begin",
"value",
"+=",
"chr",
"(",
"@arguments",
"[",
"i",
"]",
")",
"i",
"+=",
"1",
"end",
"until",
"(",
"i",
">=",
"@arguments",
".",
"size",
")",
"||",
"(",
"chr",
"(",
"@arguments",
"[",
"i",
"]",
")",
"=~",
"/",
"\\s",
"\\)",
"/",
")",
"@token_index",
"=",
"i",
"-",
"1",
"return",
"\"-\"",
",",
"value",
"when",
"\" \"",
"return",
"\" \"",
",",
"\" \"",
"else",
"gen_statement",
"end",
"end",
"rescue",
"NoMethodError",
"raise",
"\"Error. Expression cannot be parsed.\"",
"end"
] | Scans the input string and identifies single language tokens | [
"Scans",
"the",
"input",
"string",
"and",
"identifies",
"single",
"language",
"tokens"
] | 3d96a6bb6d090d3fcb956e5d8aef96b493034115 | https://github.com/ploubser/JSON-Grep/blob/3d96a6bb6d090d3fcb956e5d8aef96b493034115/lib/parser/scanner.rb#L11-L104 |
23,401 | agardiner/arg-parser | lib/arg-parser/definition.rb | ArgParser.Definition.<< | def <<(arg)
case arg
when PositionalArgument, KeywordArgument, FlagArgument, RestArgument
if @arguments[arg.key]
raise ArgumentError, "An argument with key '#{arg.key}' has already been defined"
end
if arg.short_key && @short_keys[arg.short_key]
raise ArgumentError, "The short key '#{arg.short_key}' has already been registered by the '#{
@short_keys[arg.short_key]}' argument"
end
if arg.is_a?(RestArgument) && rest_args
raise ArgumentError, "Only one rest argument can be defined"
end
@arguments[arg.key] = arg
@short_keys[arg.short_key] = arg if arg.short_key
else
raise ArgumentError, "arg must be an instance of PositionalArgument, KeywordArgument, " +
"FlagArgument or RestArgument"
end
end | ruby | def <<(arg)
case arg
when PositionalArgument, KeywordArgument, FlagArgument, RestArgument
if @arguments[arg.key]
raise ArgumentError, "An argument with key '#{arg.key}' has already been defined"
end
if arg.short_key && @short_keys[arg.short_key]
raise ArgumentError, "The short key '#{arg.short_key}' has already been registered by the '#{
@short_keys[arg.short_key]}' argument"
end
if arg.is_a?(RestArgument) && rest_args
raise ArgumentError, "Only one rest argument can be defined"
end
@arguments[arg.key] = arg
@short_keys[arg.short_key] = arg if arg.short_key
else
raise ArgumentError, "arg must be an instance of PositionalArgument, KeywordArgument, " +
"FlagArgument or RestArgument"
end
end | [
"def",
"<<",
"(",
"arg",
")",
"case",
"arg",
"when",
"PositionalArgument",
",",
"KeywordArgument",
",",
"FlagArgument",
",",
"RestArgument",
"if",
"@arguments",
"[",
"arg",
".",
"key",
"]",
"raise",
"ArgumentError",
",",
"\"An argument with key '#{arg.key}' has already been defined\"",
"end",
"if",
"arg",
".",
"short_key",
"&&",
"@short_keys",
"[",
"arg",
".",
"short_key",
"]",
"raise",
"ArgumentError",
",",
"\"The short key '#{arg.short_key}' has already been registered by the '#{\n @short_keys[arg.short_key]}' argument\"",
"end",
"if",
"arg",
".",
"is_a?",
"(",
"RestArgument",
")",
"&&",
"rest_args",
"raise",
"ArgumentError",
",",
"\"Only one rest argument can be defined\"",
"end",
"@arguments",
"[",
"arg",
".",
"key",
"]",
"=",
"arg",
"@short_keys",
"[",
"arg",
".",
"short_key",
"]",
"=",
"arg",
"if",
"arg",
".",
"short_key",
"else",
"raise",
"ArgumentError",
",",
"\"arg must be an instance of PositionalArgument, KeywordArgument, \"",
"+",
"\"FlagArgument or RestArgument\"",
"end",
"end"
] | Adds the specified argument to the command-line definition.
@param arg [Argument] An Argument sub-class to be added to the command-
line definition. | [
"Adds",
"the",
"specified",
"argument",
"to",
"the",
"command",
"-",
"line",
"definition",
"."
] | 43c04fb7af45ef4f00bc52253780152a38aeb257 | https://github.com/agardiner/arg-parser/blob/43c04fb7af45ef4f00bc52253780152a38aeb257/lib/arg-parser/definition.rb#L54-L73 |
23,402 | agardiner/arg-parser | lib/arg-parser/definition.rb | ArgParser.Definition.positional_arg | def positional_arg(key, desc, opts = {}, &block)
self << ArgParser::PositionalArgument.new(key, desc, opts, &block)
end | ruby | def positional_arg(key, desc, opts = {}, &block)
self << ArgParser::PositionalArgument.new(key, desc, opts, &block)
end | [
"def",
"positional_arg",
"(",
"key",
",",
"desc",
",",
"opts",
"=",
"{",
"}",
",",
"&",
"block",
")",
"self",
"<<",
"ArgParser",
"::",
"PositionalArgument",
".",
"new",
"(",
"key",
",",
"desc",
",",
"opts",
",",
"block",
")",
"end"
] | Add a positional argument to the set of arguments in this command-line
argument definition.
@see PositionalArgument#initialize | [
"Add",
"a",
"positional",
"argument",
"to",
"the",
"set",
"of",
"arguments",
"in",
"this",
"command",
"-",
"line",
"argument",
"definition",
"."
] | 43c04fb7af45ef4f00bc52253780152a38aeb257 | https://github.com/agardiner/arg-parser/blob/43c04fb7af45ef4f00bc52253780152a38aeb257/lib/arg-parser/definition.rb#L79-L81 |
23,403 | agardiner/arg-parser | lib/arg-parser/definition.rb | ArgParser.Definition.keyword_arg | def keyword_arg(key, desc, opts = {}, &block)
self << ArgParser::KeywordArgument.new(key, desc, opts, &block)
end | ruby | def keyword_arg(key, desc, opts = {}, &block)
self << ArgParser::KeywordArgument.new(key, desc, opts, &block)
end | [
"def",
"keyword_arg",
"(",
"key",
",",
"desc",
",",
"opts",
"=",
"{",
"}",
",",
"&",
"block",
")",
"self",
"<<",
"ArgParser",
"::",
"KeywordArgument",
".",
"new",
"(",
"key",
",",
"desc",
",",
"opts",
",",
"block",
")",
"end"
] | Add a keyword argument to the set of arguments in this command-line
argument definition.
@see KeywordArgument#initialize | [
"Add",
"a",
"keyword",
"argument",
"to",
"the",
"set",
"of",
"arguments",
"in",
"this",
"command",
"-",
"line",
"argument",
"definition",
"."
] | 43c04fb7af45ef4f00bc52253780152a38aeb257 | https://github.com/agardiner/arg-parser/blob/43c04fb7af45ef4f00bc52253780152a38aeb257/lib/arg-parser/definition.rb#L87-L89 |
23,404 | agardiner/arg-parser | lib/arg-parser/definition.rb | ArgParser.Definition.flag_arg | def flag_arg(key, desc, opts = {}, &block)
self << ArgParser::FlagArgument.new(key, desc, opts, &block)
end | ruby | def flag_arg(key, desc, opts = {}, &block)
self << ArgParser::FlagArgument.new(key, desc, opts, &block)
end | [
"def",
"flag_arg",
"(",
"key",
",",
"desc",
",",
"opts",
"=",
"{",
"}",
",",
"&",
"block",
")",
"self",
"<<",
"ArgParser",
"::",
"FlagArgument",
".",
"new",
"(",
"key",
",",
"desc",
",",
"opts",
",",
"block",
")",
"end"
] | Add a flag argument to the set of arguments in this command-line
argument definition.
@see FlagArgument#initialize | [
"Add",
"a",
"flag",
"argument",
"to",
"the",
"set",
"of",
"arguments",
"in",
"this",
"command",
"-",
"line",
"argument",
"definition",
"."
] | 43c04fb7af45ef4f00bc52253780152a38aeb257 | https://github.com/agardiner/arg-parser/blob/43c04fb7af45ef4f00bc52253780152a38aeb257/lib/arg-parser/definition.rb#L95-L97 |
23,405 | agardiner/arg-parser | lib/arg-parser/definition.rb | ArgParser.Definition.rest_arg | def rest_arg(key, desc, opts = {}, &block)
self << ArgParser::RestArgument.new(key, desc, opts, &block)
end | ruby | def rest_arg(key, desc, opts = {}, &block)
self << ArgParser::RestArgument.new(key, desc, opts, &block)
end | [
"def",
"rest_arg",
"(",
"key",
",",
"desc",
",",
"opts",
"=",
"{",
"}",
",",
"&",
"block",
")",
"self",
"<<",
"ArgParser",
"::",
"RestArgument",
".",
"new",
"(",
"key",
",",
"desc",
",",
"opts",
",",
"block",
")",
"end"
] | Add a rest argument to the set of arguments in this command-line
argument definition.
@see RestArgument#initialize | [
"Add",
"a",
"rest",
"argument",
"to",
"the",
"set",
"of",
"arguments",
"in",
"this",
"command",
"-",
"line",
"argument",
"definition",
"."
] | 43c04fb7af45ef4f00bc52253780152a38aeb257 | https://github.com/agardiner/arg-parser/blob/43c04fb7af45ef4f00bc52253780152a38aeb257/lib/arg-parser/definition.rb#L103-L105 |
23,406 | agardiner/arg-parser | lib/arg-parser/definition.rb | ArgParser.Definition.validate_requirements | def validate_requirements(args)
errors = []
@require_set.each do |req, sets|
sets.each do |set|
count = set.count{ |arg| args.has_key?(arg.key) && args[arg.key] }
case req
when :one
if count == 0
errors << "No argument has been specified for one of: #{set.join(', ')}"
elsif count > 1
errors << "Only one argument can been specified from: #{set.join(', ')}"
end
when :any
if count == 0
errors << "At least one of the arguments must be specified from: #{set.join(', ')}"
end
end
end
end
errors
end | ruby | def validate_requirements(args)
errors = []
@require_set.each do |req, sets|
sets.each do |set|
count = set.count{ |arg| args.has_key?(arg.key) && args[arg.key] }
case req
when :one
if count == 0
errors << "No argument has been specified for one of: #{set.join(', ')}"
elsif count > 1
errors << "Only one argument can been specified from: #{set.join(', ')}"
end
when :any
if count == 0
errors << "At least one of the arguments must be specified from: #{set.join(', ')}"
end
end
end
end
errors
end | [
"def",
"validate_requirements",
"(",
"args",
")",
"errors",
"=",
"[",
"]",
"@require_set",
".",
"each",
"do",
"|",
"req",
",",
"sets",
"|",
"sets",
".",
"each",
"do",
"|",
"set",
"|",
"count",
"=",
"set",
".",
"count",
"{",
"|",
"arg",
"|",
"args",
".",
"has_key?",
"(",
"arg",
".",
"key",
")",
"&&",
"args",
"[",
"arg",
".",
"key",
"]",
"}",
"case",
"req",
"when",
":one",
"if",
"count",
"==",
"0",
"errors",
"<<",
"\"No argument has been specified for one of: #{set.join(', ')}\"",
"elsif",
"count",
">",
"1",
"errors",
"<<",
"\"Only one argument can been specified from: #{set.join(', ')}\"",
"end",
"when",
":any",
"if",
"count",
"==",
"0",
"errors",
"<<",
"\"At least one of the arguments must be specified from: #{set.join(', ')}\"",
"end",
"end",
"end",
"end",
"errors",
"end"
] | Validates the supplied +args+ Hash object, verifying that any argument
set requirements have been satisfied. Returns an array of error
messages for each set requirement that is not satisfied.
@param args [Hash] a Hash containing the keys and values identified
by the parser.
@return [Array] a list of errors for any argument requirements that
have not been satisfied. | [
"Validates",
"the",
"supplied",
"+",
"args",
"+",
"Hash",
"object",
"verifying",
"that",
"any",
"argument",
"set",
"requirements",
"have",
"been",
"satisfied",
".",
"Returns",
"an",
"array",
"of",
"error",
"messages",
"for",
"each",
"set",
"requirement",
"that",
"is",
"not",
"satisfied",
"."
] | 43c04fb7af45ef4f00bc52253780152a38aeb257 | https://github.com/agardiner/arg-parser/blob/43c04fb7af45ef4f00bc52253780152a38aeb257/lib/arg-parser/definition.rb#L208-L228 |
23,407 | agardiner/arg-parser | lib/arg-parser/definition.rb | ArgParser.Definition.show_usage | def show_usage(out = STDERR, width = 80)
lines = ['']
pos_args = positional_args
opt_args = size - pos_args.size
usage_args = pos_args.map(&:to_use)
usage_args << (requires_some? ? 'OPTIONS' : '[OPTIONS]') if opt_args > 0
usage_args << rest_args.to_use if rest_args?
lines.concat(wrap_text("USAGE: #{RUBY_ENGINE} #{$0} #{usage_args.join(' ')}", width))
lines << ''
lines << 'Specify the /? or --help option for more detailed help'
lines << ''
lines.each{ |line| out.puts line } if out
lines
end | ruby | def show_usage(out = STDERR, width = 80)
lines = ['']
pos_args = positional_args
opt_args = size - pos_args.size
usage_args = pos_args.map(&:to_use)
usage_args << (requires_some? ? 'OPTIONS' : '[OPTIONS]') if opt_args > 0
usage_args << rest_args.to_use if rest_args?
lines.concat(wrap_text("USAGE: #{RUBY_ENGINE} #{$0} #{usage_args.join(' ')}", width))
lines << ''
lines << 'Specify the /? or --help option for more detailed help'
lines << ''
lines.each{ |line| out.puts line } if out
lines
end | [
"def",
"show_usage",
"(",
"out",
"=",
"STDERR",
",",
"width",
"=",
"80",
")",
"lines",
"=",
"[",
"''",
"]",
"pos_args",
"=",
"positional_args",
"opt_args",
"=",
"size",
"-",
"pos_args",
".",
"size",
"usage_args",
"=",
"pos_args",
".",
"map",
"(",
":to_use",
")",
"usage_args",
"<<",
"(",
"requires_some?",
"?",
"'OPTIONS'",
":",
"'[OPTIONS]'",
")",
"if",
"opt_args",
">",
"0",
"usage_args",
"<<",
"rest_args",
".",
"to_use",
"if",
"rest_args?",
"lines",
".",
"concat",
"(",
"wrap_text",
"(",
"\"USAGE: #{RUBY_ENGINE} #{$0} #{usage_args.join(' ')}\"",
",",
"width",
")",
")",
"lines",
"<<",
"''",
"lines",
"<<",
"'Specify the /? or --help option for more detailed help'",
"lines",
"<<",
"''",
"lines",
".",
"each",
"{",
"|",
"line",
"|",
"out",
".",
"puts",
"line",
"}",
"if",
"out",
"lines",
"end"
] | Generates a usage display string | [
"Generates",
"a",
"usage",
"display",
"string"
] | 43c04fb7af45ef4f00bc52253780152a38aeb257 | https://github.com/agardiner/arg-parser/blob/43c04fb7af45ef4f00bc52253780152a38aeb257/lib/arg-parser/definition.rb#L325-L338 |
23,408 | agardiner/arg-parser | lib/arg-parser/definition.rb | ArgParser.Definition.show_help | def show_help(out = STDOUT, width = 80)
lines = ['', '']
lines << title
lines << title.gsub(/./, '=')
lines << ''
if purpose
lines.concat(wrap_text(purpose, width))
lines << ''
end
if copyright
lines.concat(wrap_text("Copyright (c) #{copyright}", width))
lines << ''
end
lines << 'USAGE'
lines << '-----'
pos_args = positional_args
opt_args = size - pos_args.size
usage_args = pos_args.map(&:to_use)
usage_args << (requires_some? ? 'OPTIONS' : '[OPTIONS]') if opt_args > 0
usage_args << rest_args.to_use if rest_args?
lines.concat(wrap_text(" #{RUBY_ENGINE} #{$0} #{usage_args.join(' ')}", width))
lines << ''
if positional_args?
max = positional_args.map{ |a| a.to_s.length }.max
pos_args = positional_args
pos_args << rest_args if rest_args?
pos_args.each do |arg|
if arg.usage_break
lines << ''
lines << arg.usage_break
end
desc = arg.description
desc << "\n[Default: #{arg.default}]" unless arg.default.nil?
wrap_text(desc, width - max - 6).each_with_index do |line, i|
lines << " %-#{max}s %s" % [[arg.to_s][i], line]
end
end
lines << ''
end
if non_positional_args?
lines << ''
lines << 'OPTIONS'
lines << '-------'
max = non_positional_args.map{ |a| a.to_use.length }.max
non_positional_args.each do |arg|
if arg.usage_break
lines << ''
lines << arg.usage_break
end
desc = arg.description
desc << "\n[Default: #{arg.default}]" unless arg.default.nil?
wrap_text(desc, width - max - 6).each_with_index do |line, i|
lines << " %-#{max}s %s" % [[arg.to_use][i], line]
end
end
end
lines << ''
lines.each{ |line| line.length < width ? out.puts(line) : out.print(line) } if out
lines
end | ruby | def show_help(out = STDOUT, width = 80)
lines = ['', '']
lines << title
lines << title.gsub(/./, '=')
lines << ''
if purpose
lines.concat(wrap_text(purpose, width))
lines << ''
end
if copyright
lines.concat(wrap_text("Copyright (c) #{copyright}", width))
lines << ''
end
lines << 'USAGE'
lines << '-----'
pos_args = positional_args
opt_args = size - pos_args.size
usage_args = pos_args.map(&:to_use)
usage_args << (requires_some? ? 'OPTIONS' : '[OPTIONS]') if opt_args > 0
usage_args << rest_args.to_use if rest_args?
lines.concat(wrap_text(" #{RUBY_ENGINE} #{$0} #{usage_args.join(' ')}", width))
lines << ''
if positional_args?
max = positional_args.map{ |a| a.to_s.length }.max
pos_args = positional_args
pos_args << rest_args if rest_args?
pos_args.each do |arg|
if arg.usage_break
lines << ''
lines << arg.usage_break
end
desc = arg.description
desc << "\n[Default: #{arg.default}]" unless arg.default.nil?
wrap_text(desc, width - max - 6).each_with_index do |line, i|
lines << " %-#{max}s %s" % [[arg.to_s][i], line]
end
end
lines << ''
end
if non_positional_args?
lines << ''
lines << 'OPTIONS'
lines << '-------'
max = non_positional_args.map{ |a| a.to_use.length }.max
non_positional_args.each do |arg|
if arg.usage_break
lines << ''
lines << arg.usage_break
end
desc = arg.description
desc << "\n[Default: #{arg.default}]" unless arg.default.nil?
wrap_text(desc, width - max - 6).each_with_index do |line, i|
lines << " %-#{max}s %s" % [[arg.to_use][i], line]
end
end
end
lines << ''
lines.each{ |line| line.length < width ? out.puts(line) : out.print(line) } if out
lines
end | [
"def",
"show_help",
"(",
"out",
"=",
"STDOUT",
",",
"width",
"=",
"80",
")",
"lines",
"=",
"[",
"''",
",",
"''",
"]",
"lines",
"<<",
"title",
"lines",
"<<",
"title",
".",
"gsub",
"(",
"/",
"/",
",",
"'='",
")",
"lines",
"<<",
"''",
"if",
"purpose",
"lines",
".",
"concat",
"(",
"wrap_text",
"(",
"purpose",
",",
"width",
")",
")",
"lines",
"<<",
"''",
"end",
"if",
"copyright",
"lines",
".",
"concat",
"(",
"wrap_text",
"(",
"\"Copyright (c) #{copyright}\"",
",",
"width",
")",
")",
"lines",
"<<",
"''",
"end",
"lines",
"<<",
"'USAGE'",
"lines",
"<<",
"'-----'",
"pos_args",
"=",
"positional_args",
"opt_args",
"=",
"size",
"-",
"pos_args",
".",
"size",
"usage_args",
"=",
"pos_args",
".",
"map",
"(",
":to_use",
")",
"usage_args",
"<<",
"(",
"requires_some?",
"?",
"'OPTIONS'",
":",
"'[OPTIONS]'",
")",
"if",
"opt_args",
">",
"0",
"usage_args",
"<<",
"rest_args",
".",
"to_use",
"if",
"rest_args?",
"lines",
".",
"concat",
"(",
"wrap_text",
"(",
"\" #{RUBY_ENGINE} #{$0} #{usage_args.join(' ')}\"",
",",
"width",
")",
")",
"lines",
"<<",
"''",
"if",
"positional_args?",
"max",
"=",
"positional_args",
".",
"map",
"{",
"|",
"a",
"|",
"a",
".",
"to_s",
".",
"length",
"}",
".",
"max",
"pos_args",
"=",
"positional_args",
"pos_args",
"<<",
"rest_args",
"if",
"rest_args?",
"pos_args",
".",
"each",
"do",
"|",
"arg",
"|",
"if",
"arg",
".",
"usage_break",
"lines",
"<<",
"''",
"lines",
"<<",
"arg",
".",
"usage_break",
"end",
"desc",
"=",
"arg",
".",
"description",
"desc",
"<<",
"\"\\n[Default: #{arg.default}]\"",
"unless",
"arg",
".",
"default",
".",
"nil?",
"wrap_text",
"(",
"desc",
",",
"width",
"-",
"max",
"-",
"6",
")",
".",
"each_with_index",
"do",
"|",
"line",
",",
"i",
"|",
"lines",
"<<",
"\" %-#{max}s %s\"",
"%",
"[",
"[",
"arg",
".",
"to_s",
"]",
"[",
"i",
"]",
",",
"line",
"]",
"end",
"end",
"lines",
"<<",
"''",
"end",
"if",
"non_positional_args?",
"lines",
"<<",
"''",
"lines",
"<<",
"'OPTIONS'",
"lines",
"<<",
"'-------'",
"max",
"=",
"non_positional_args",
".",
"map",
"{",
"|",
"a",
"|",
"a",
".",
"to_use",
".",
"length",
"}",
".",
"max",
"non_positional_args",
".",
"each",
"do",
"|",
"arg",
"|",
"if",
"arg",
".",
"usage_break",
"lines",
"<<",
"''",
"lines",
"<<",
"arg",
".",
"usage_break",
"end",
"desc",
"=",
"arg",
".",
"description",
"desc",
"<<",
"\"\\n[Default: #{arg.default}]\"",
"unless",
"arg",
".",
"default",
".",
"nil?",
"wrap_text",
"(",
"desc",
",",
"width",
"-",
"max",
"-",
"6",
")",
".",
"each_with_index",
"do",
"|",
"line",
",",
"i",
"|",
"lines",
"<<",
"\" %-#{max}s %s\"",
"%",
"[",
"[",
"arg",
".",
"to_use",
"]",
"[",
"i",
"]",
",",
"line",
"]",
"end",
"end",
"end",
"lines",
"<<",
"''",
"lines",
".",
"each",
"{",
"|",
"line",
"|",
"line",
".",
"length",
"<",
"width",
"?",
"out",
".",
"puts",
"(",
"line",
")",
":",
"out",
".",
"print",
"(",
"line",
")",
"}",
"if",
"out",
"lines",
"end"
] | Generates a more detailed help screen.
@param out [IO] an IO object on which the help information will be
output. Pass +nil+ if no output to any device is desired.
@param width [Integer] the width at which to wrap text.
@return [Array] An array of lines of text, containing the help text. | [
"Generates",
"a",
"more",
"detailed",
"help",
"screen",
"."
] | 43c04fb7af45ef4f00bc52253780152a38aeb257 | https://github.com/agardiner/arg-parser/blob/43c04fb7af45ef4f00bc52253780152a38aeb257/lib/arg-parser/definition.rb#L346-L408 |
23,409 | agardiner/arg-parser | lib/arg-parser/definition.rb | ArgParser.Definition.wrap_text | def wrap_text(text, width)
if width > 0 && (text.length > width || text.index("\n"))
lines = []
start, nl_pos, ws_pos, wb_pos, end_pos = 0, 0, 0, 0, text.rindex(/[^\s]/)
while start < end_pos
last_start = start
nl_pos = text.index("\n", start)
ws_pos = text.rindex(/ +/, start + width)
wb_pos = text.rindex(/[\-,.;#)}\]\/\\]/, start + width - 1)
### Debug code ###
#STDERR.puts self
#ind = ' ' * end_pos
#ind[start] = '('
#ind[start+width < end_pos ? start+width : end_pos] = ']'
#ind[nl_pos] = 'n' if nl_pos
#ind[wb_pos] = 'b' if wb_pos
#ind[ws_pos] = 's' if ws_pos
#STDERR.puts ind
### End debug code ###
if nl_pos && nl_pos <= start + width
lines << text[start...nl_pos].strip
start = nl_pos + 1
elsif end_pos < start + width
lines << text[start..end_pos]
start = end_pos
elsif ws_pos && ws_pos > start && ((wb_pos.nil? || ws_pos > wb_pos) ||
(wb_pos && wb_pos > 5 && wb_pos - 5 < ws_pos))
lines << text[start...ws_pos]
start = text.index(/[^\s]/, ws_pos + 1)
elsif wb_pos && wb_pos > start
lines << text[start..wb_pos]
start = wb_pos + 1
else
lines << text[start...(start+width)]
start += width
end
if start <= last_start
# Detect an infinite loop, and just return the original text
STDERR.puts "Inifinite loop detected at #{__FILE__}:#{__LINE__}"
STDERR.puts " width: #{width}, start: #{start}, nl_pos: #{nl_pos}, " +
"ws_pos: #{ws_pos}, wb_pos: #{wb_pos}"
return [text]
end
end
lines
else
[text]
end
end | ruby | def wrap_text(text, width)
if width > 0 && (text.length > width || text.index("\n"))
lines = []
start, nl_pos, ws_pos, wb_pos, end_pos = 0, 0, 0, 0, text.rindex(/[^\s]/)
while start < end_pos
last_start = start
nl_pos = text.index("\n", start)
ws_pos = text.rindex(/ +/, start + width)
wb_pos = text.rindex(/[\-,.;#)}\]\/\\]/, start + width - 1)
### Debug code ###
#STDERR.puts self
#ind = ' ' * end_pos
#ind[start] = '('
#ind[start+width < end_pos ? start+width : end_pos] = ']'
#ind[nl_pos] = 'n' if nl_pos
#ind[wb_pos] = 'b' if wb_pos
#ind[ws_pos] = 's' if ws_pos
#STDERR.puts ind
### End debug code ###
if nl_pos && nl_pos <= start + width
lines << text[start...nl_pos].strip
start = nl_pos + 1
elsif end_pos < start + width
lines << text[start..end_pos]
start = end_pos
elsif ws_pos && ws_pos > start && ((wb_pos.nil? || ws_pos > wb_pos) ||
(wb_pos && wb_pos > 5 && wb_pos - 5 < ws_pos))
lines << text[start...ws_pos]
start = text.index(/[^\s]/, ws_pos + 1)
elsif wb_pos && wb_pos > start
lines << text[start..wb_pos]
start = wb_pos + 1
else
lines << text[start...(start+width)]
start += width
end
if start <= last_start
# Detect an infinite loop, and just return the original text
STDERR.puts "Inifinite loop detected at #{__FILE__}:#{__LINE__}"
STDERR.puts " width: #{width}, start: #{start}, nl_pos: #{nl_pos}, " +
"ws_pos: #{ws_pos}, wb_pos: #{wb_pos}"
return [text]
end
end
lines
else
[text]
end
end | [
"def",
"wrap_text",
"(",
"text",
",",
"width",
")",
"if",
"width",
">",
"0",
"&&",
"(",
"text",
".",
"length",
">",
"width",
"||",
"text",
".",
"index",
"(",
"\"\\n\"",
")",
")",
"lines",
"=",
"[",
"]",
"start",
",",
"nl_pos",
",",
"ws_pos",
",",
"wb_pos",
",",
"end_pos",
"=",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"text",
".",
"rindex",
"(",
"/",
"\\s",
"/",
")",
"while",
"start",
"<",
"end_pos",
"last_start",
"=",
"start",
"nl_pos",
"=",
"text",
".",
"index",
"(",
"\"\\n\"",
",",
"start",
")",
"ws_pos",
"=",
"text",
".",
"rindex",
"(",
"/",
"/",
",",
"start",
"+",
"width",
")",
"wb_pos",
"=",
"text",
".",
"rindex",
"(",
"/",
"\\-",
"\\]",
"\\/",
"\\\\",
"/",
",",
"start",
"+",
"width",
"-",
"1",
")",
"### Debug code ###",
"#STDERR.puts self",
"#ind = ' ' * end_pos",
"#ind[start] = '('",
"#ind[start+width < end_pos ? start+width : end_pos] = ']'",
"#ind[nl_pos] = 'n' if nl_pos",
"#ind[wb_pos] = 'b' if wb_pos",
"#ind[ws_pos] = 's' if ws_pos",
"#STDERR.puts ind",
"### End debug code ###",
"if",
"nl_pos",
"&&",
"nl_pos",
"<=",
"start",
"+",
"width",
"lines",
"<<",
"text",
"[",
"start",
"...",
"nl_pos",
"]",
".",
"strip",
"start",
"=",
"nl_pos",
"+",
"1",
"elsif",
"end_pos",
"<",
"start",
"+",
"width",
"lines",
"<<",
"text",
"[",
"start",
"..",
"end_pos",
"]",
"start",
"=",
"end_pos",
"elsif",
"ws_pos",
"&&",
"ws_pos",
">",
"start",
"&&",
"(",
"(",
"wb_pos",
".",
"nil?",
"||",
"ws_pos",
">",
"wb_pos",
")",
"||",
"(",
"wb_pos",
"&&",
"wb_pos",
">",
"5",
"&&",
"wb_pos",
"-",
"5",
"<",
"ws_pos",
")",
")",
"lines",
"<<",
"text",
"[",
"start",
"...",
"ws_pos",
"]",
"start",
"=",
"text",
".",
"index",
"(",
"/",
"\\s",
"/",
",",
"ws_pos",
"+",
"1",
")",
"elsif",
"wb_pos",
"&&",
"wb_pos",
">",
"start",
"lines",
"<<",
"text",
"[",
"start",
"..",
"wb_pos",
"]",
"start",
"=",
"wb_pos",
"+",
"1",
"else",
"lines",
"<<",
"text",
"[",
"start",
"...",
"(",
"start",
"+",
"width",
")",
"]",
"start",
"+=",
"width",
"end",
"if",
"start",
"<=",
"last_start",
"# Detect an infinite loop, and just return the original text",
"STDERR",
".",
"puts",
"\"Inifinite loop detected at #{__FILE__}:#{__LINE__}\"",
"STDERR",
".",
"puts",
"\" width: #{width}, start: #{start}, nl_pos: #{nl_pos}, \"",
"+",
"\"ws_pos: #{ws_pos}, wb_pos: #{wb_pos}\"",
"return",
"[",
"text",
"]",
"end",
"end",
"lines",
"else",
"[",
"text",
"]",
"end",
"end"
] | Utility method for wrapping lines of +text+ at +width+ characters.
@param text [String] a string of text that is to be wrapped to a
maximum width.
@param width [Integer] the maximum length of each line of text.
@return [Array] an Array of lines of text, each no longer than +width+
characters. | [
"Utility",
"method",
"for",
"wrapping",
"lines",
"of",
"+",
"text",
"+",
"at",
"+",
"width",
"+",
"characters",
"."
] | 43c04fb7af45ef4f00bc52253780152a38aeb257 | https://github.com/agardiner/arg-parser/blob/43c04fb7af45ef4f00bc52253780152a38aeb257/lib/arg-parser/definition.rb#L418-L466 |
23,410 | agardiner/arg-parser | lib/arg-parser/parser.rb | ArgParser.Parser.parse | def parse(tokens = ARGV)
@show_usage = nil
@show_help = nil
@errors = []
begin
pos_vals, kw_vals, rest_vals = classify_tokens(tokens)
args = process_args(pos_vals, kw_vals, rest_vals) unless @show_help
rescue NoSuchArgumentError => ex
self.errors << ex.message
@show_usage = true
end
(@show_usage || @show_help) ? false : args
end | ruby | def parse(tokens = ARGV)
@show_usage = nil
@show_help = nil
@errors = []
begin
pos_vals, kw_vals, rest_vals = classify_tokens(tokens)
args = process_args(pos_vals, kw_vals, rest_vals) unless @show_help
rescue NoSuchArgumentError => ex
self.errors << ex.message
@show_usage = true
end
(@show_usage || @show_help) ? false : args
end | [
"def",
"parse",
"(",
"tokens",
"=",
"ARGV",
")",
"@show_usage",
"=",
"nil",
"@show_help",
"=",
"nil",
"@errors",
"=",
"[",
"]",
"begin",
"pos_vals",
",",
"kw_vals",
",",
"rest_vals",
"=",
"classify_tokens",
"(",
"tokens",
")",
"args",
"=",
"process_args",
"(",
"pos_vals",
",",
"kw_vals",
",",
"rest_vals",
")",
"unless",
"@show_help",
"rescue",
"NoSuchArgumentError",
"=>",
"ex",
"self",
".",
"errors",
"<<",
"ex",
".",
"message",
"@show_usage",
"=",
"true",
"end",
"(",
"@show_usage",
"||",
"@show_help",
")",
"?",
"false",
":",
"args",
"end"
] | Instantiates a new command-line parser, with the specified command-
line definition. A Parser instance delegates unknown methods to the
Definition, so its possible to work only with a Parser instance to
both define and parse a command-line.
@param [Definition] definition A Definition object that defines the
possible arguments that may appear in a command-line. If no definition
is supplied, an empty definition is created.
Parse the specified Array[String] of +tokens+, or ARGV if +tokens+ is
nil. Returns false if unable to parse successfully, or an OpenStruct
with accessors for every defined argument. Arguments whose values are
not specified will contain the agument default value, or nil if no
default is specified. | [
"Instantiates",
"a",
"new",
"command",
"-",
"line",
"parser",
"with",
"the",
"specified",
"command",
"-",
"line",
"definition",
".",
"A",
"Parser",
"instance",
"delegates",
"unknown",
"methods",
"to",
"the",
"Definition",
"so",
"its",
"possible",
"to",
"work",
"only",
"with",
"a",
"Parser",
"instance",
"to",
"both",
"define",
"and",
"parse",
"a",
"command",
"-",
"line",
"."
] | 43c04fb7af45ef4f00bc52253780152a38aeb257 | https://github.com/agardiner/arg-parser/blob/43c04fb7af45ef4f00bc52253780152a38aeb257/lib/arg-parser/parser.rb#L48-L60 |
23,411 | agardiner/arg-parser | lib/arg-parser/parser.rb | ArgParser.Parser.process_arg_val | def process_arg_val(arg, val, hsh, is_default = false)
if is_default && arg.required? && (val.nil? || val.empty?)
self.errors << "No value was specified for required argument '#{arg}'"
return
end
if !is_default && val.nil? && KeywordArgument === arg
if arg.value_optional?
val = arg.value_optional
else
self.errors << "No value was specified for keyword argument '#{arg}'"
return
end
end
# Argument value validation
if ValueArgument === arg && arg.validation && val
case arg.validation
when Regexp
[val].flatten.each do |v|
add_value_error(arg, val) unless v =~ arg.validation
end
when Array
[val].flatten.each do |v|
add_value_error(arg, val) unless arg.validation.include?(v)
end
when Proc
begin
arg.validation.call(val, arg, hsh)
rescue StandardError => ex
self.errors << "An error occurred in the validation handler for argument '#{arg}': #{ex}"
return
end
else
raise "Unknown validation type: #{arg.validation.class.name}"
end
end
# TODO: Argument value coercion
# Call any registered on_parse handler
begin
val = arg.on_parse.call(val, arg, hsh) if val && arg.on_parse
rescue StandardError => ex
self.errors << "An error occurred in the on_parse handler for argument '#{arg}': #{ex}"
return
end
# Return result
val
end | ruby | def process_arg_val(arg, val, hsh, is_default = false)
if is_default && arg.required? && (val.nil? || val.empty?)
self.errors << "No value was specified for required argument '#{arg}'"
return
end
if !is_default && val.nil? && KeywordArgument === arg
if arg.value_optional?
val = arg.value_optional
else
self.errors << "No value was specified for keyword argument '#{arg}'"
return
end
end
# Argument value validation
if ValueArgument === arg && arg.validation && val
case arg.validation
when Regexp
[val].flatten.each do |v|
add_value_error(arg, val) unless v =~ arg.validation
end
when Array
[val].flatten.each do |v|
add_value_error(arg, val) unless arg.validation.include?(v)
end
when Proc
begin
arg.validation.call(val, arg, hsh)
rescue StandardError => ex
self.errors << "An error occurred in the validation handler for argument '#{arg}': #{ex}"
return
end
else
raise "Unknown validation type: #{arg.validation.class.name}"
end
end
# TODO: Argument value coercion
# Call any registered on_parse handler
begin
val = arg.on_parse.call(val, arg, hsh) if val && arg.on_parse
rescue StandardError => ex
self.errors << "An error occurred in the on_parse handler for argument '#{arg}': #{ex}"
return
end
# Return result
val
end | [
"def",
"process_arg_val",
"(",
"arg",
",",
"val",
",",
"hsh",
",",
"is_default",
"=",
"false",
")",
"if",
"is_default",
"&&",
"arg",
".",
"required?",
"&&",
"(",
"val",
".",
"nil?",
"||",
"val",
".",
"empty?",
")",
"self",
".",
"errors",
"<<",
"\"No value was specified for required argument '#{arg}'\"",
"return",
"end",
"if",
"!",
"is_default",
"&&",
"val",
".",
"nil?",
"&&",
"KeywordArgument",
"===",
"arg",
"if",
"arg",
".",
"value_optional?",
"val",
"=",
"arg",
".",
"value_optional",
"else",
"self",
".",
"errors",
"<<",
"\"No value was specified for keyword argument '#{arg}'\"",
"return",
"end",
"end",
"# Argument value validation",
"if",
"ValueArgument",
"===",
"arg",
"&&",
"arg",
".",
"validation",
"&&",
"val",
"case",
"arg",
".",
"validation",
"when",
"Regexp",
"[",
"val",
"]",
".",
"flatten",
".",
"each",
"do",
"|",
"v",
"|",
"add_value_error",
"(",
"arg",
",",
"val",
")",
"unless",
"v",
"=~",
"arg",
".",
"validation",
"end",
"when",
"Array",
"[",
"val",
"]",
".",
"flatten",
".",
"each",
"do",
"|",
"v",
"|",
"add_value_error",
"(",
"arg",
",",
"val",
")",
"unless",
"arg",
".",
"validation",
".",
"include?",
"(",
"v",
")",
"end",
"when",
"Proc",
"begin",
"arg",
".",
"validation",
".",
"call",
"(",
"val",
",",
"arg",
",",
"hsh",
")",
"rescue",
"StandardError",
"=>",
"ex",
"self",
".",
"errors",
"<<",
"\"An error occurred in the validation handler for argument '#{arg}': #{ex}\"",
"return",
"end",
"else",
"raise",
"\"Unknown validation type: #{arg.validation.class.name}\"",
"end",
"end",
"# TODO: Argument value coercion",
"# Call any registered on_parse handler",
"begin",
"val",
"=",
"arg",
".",
"on_parse",
".",
"call",
"(",
"val",
",",
"arg",
",",
"hsh",
")",
"if",
"val",
"&&",
"arg",
".",
"on_parse",
"rescue",
"StandardError",
"=>",
"ex",
"self",
".",
"errors",
"<<",
"\"An error occurred in the on_parse handler for argument '#{arg}': #{ex}\"",
"return",
"end",
"# Return result",
"val",
"end"
] | Process a single argument value | [
"Process",
"a",
"single",
"argument",
"value"
] | 43c04fb7af45ef4f00bc52253780152a38aeb257 | https://github.com/agardiner/arg-parser/blob/43c04fb7af45ef4f00bc52253780152a38aeb257/lib/arg-parser/parser.rb#L200-L249 |
23,412 | jamesruston/postcodes_io | lib/postcodes_io/base.rb | Postcodes.Base.method_missing | def method_missing(name, *args, &block)
return @info[name.to_s] if @info.key? name.to_s
return @info[name] if @info.key? name
super.method_missing name
end | ruby | def method_missing(name, *args, &block)
return @info[name.to_s] if @info.key? name.to_s
return @info[name] if @info.key? name
super.method_missing name
end | [
"def",
"method_missing",
"(",
"name",
",",
"*",
"args",
",",
"&",
"block",
")",
"return",
"@info",
"[",
"name",
".",
"to_s",
"]",
"if",
"@info",
".",
"key?",
"name",
".",
"to_s",
"return",
"@info",
"[",
"name",
"]",
"if",
"@info",
".",
"key?",
"name",
"super",
".",
"method_missing",
"name",
"end"
] | allow accessing info values with dot notation | [
"allow",
"accessing",
"info",
"values",
"with",
"dot",
"notation"
] | 29283c42ef3b441578177dd4b2606243617e4250 | https://github.com/jamesruston/postcodes_io/blob/29283c42ef3b441578177dd4b2606243617e4250/lib/postcodes_io/base.rb#L4-L8 |
23,413 | kares/jruby-rack-worker | src/main/ruby/resque/jruby_worker.rb | Resque.JRubyWorker.prune_dead_workers | def prune_dead_workers
all_workers = self.class.all
return if all_workers.empty?
known_workers = JRUBY ? worker_thread_ids : []
pids = nil, hostname = self.hostname
all_workers.each do |worker|
host, pid, thread, queues = self.class.split_id(worker.id)
next if host != hostname
next if known_workers.include?(thread) && pid == self.pid.to_s
# NOTE: allow flexibility of running workers :
# 1. worker might run in another JVM instance
# 2. worker might run as a process (with MRI)
next if (pids ||= system_pids).include?(pid)
log! "Pruning dead worker: #{worker}"
if worker.respond_to?(:unregister_worker)
worker.unregister_worker
else # Resque 2.x
Registry.for(worker).unregister
end
end
end | ruby | def prune_dead_workers
all_workers = self.class.all
return if all_workers.empty?
known_workers = JRUBY ? worker_thread_ids : []
pids = nil, hostname = self.hostname
all_workers.each do |worker|
host, pid, thread, queues = self.class.split_id(worker.id)
next if host != hostname
next if known_workers.include?(thread) && pid == self.pid.to_s
# NOTE: allow flexibility of running workers :
# 1. worker might run in another JVM instance
# 2. worker might run as a process (with MRI)
next if (pids ||= system_pids).include?(pid)
log! "Pruning dead worker: #{worker}"
if worker.respond_to?(:unregister_worker)
worker.unregister_worker
else # Resque 2.x
Registry.for(worker).unregister
end
end
end | [
"def",
"prune_dead_workers",
"all_workers",
"=",
"self",
".",
"class",
".",
"all",
"return",
"if",
"all_workers",
".",
"empty?",
"known_workers",
"=",
"JRUBY",
"?",
"worker_thread_ids",
":",
"[",
"]",
"pids",
"=",
"nil",
",",
"hostname",
"=",
"self",
".",
"hostname",
"all_workers",
".",
"each",
"do",
"|",
"worker",
"|",
"host",
",",
"pid",
",",
"thread",
",",
"queues",
"=",
"self",
".",
"class",
".",
"split_id",
"(",
"worker",
".",
"id",
")",
"next",
"if",
"host",
"!=",
"hostname",
"next",
"if",
"known_workers",
".",
"include?",
"(",
"thread",
")",
"&&",
"pid",
"==",
"self",
".",
"pid",
".",
"to_s",
"# NOTE: allow flexibility of running workers :",
"# 1. worker might run in another JVM instance",
"# 2. worker might run as a process (with MRI)",
"next",
"if",
"(",
"pids",
"||=",
"system_pids",
")",
".",
"include?",
"(",
"pid",
")",
"log!",
"\"Pruning dead worker: #{worker}\"",
"if",
"worker",
".",
"respond_to?",
"(",
":unregister_worker",
")",
"worker",
".",
"unregister_worker",
"else",
"# Resque 2.x",
"Registry",
".",
"for",
"(",
"worker",
")",
".",
"unregister",
"end",
"end",
"end"
] | similar to the original pruning but accounts for thread-based workers
@see Resque::Worker#prune_dead_workers | [
"similar",
"to",
"the",
"original",
"pruning",
"but",
"accounts",
"for",
"thread",
"-",
"based",
"workers"
] | d6bb51b063d8da6e1c5aedf74f62d7c70ea0aa4d | https://github.com/kares/jruby-rack-worker/blob/d6bb51b063d8da6e1c5aedf74f62d7c70ea0aa4d/src/main/ruby/resque/jruby_worker.rb#L188-L208 |
23,414 | kares/jruby-rack-worker | src/main/ruby/resque/jruby_worker.rb | Resque.JRubyWorker.worker_thread_ids | def worker_thread_ids
thread_group = java.lang.Thread.currentThread.getThreadGroup
threads = java.lang.reflect.Array.newInstance(
java.lang.Thread.java_class, thread_group.activeCount)
thread_group.enumerate(threads)
# NOTE: we shall check the name from $servlet_context.getServletContextName
# but that's an implementation detail of the factory currently that threads
# are named including their context name. thread grouping should be fine !
threads.map do |thread| # a convention is to name threads as "worker" :
thread && thread.getName.index(WORKER_THREAD_ID) ? thread.getName : nil
end.compact
end | ruby | def worker_thread_ids
thread_group = java.lang.Thread.currentThread.getThreadGroup
threads = java.lang.reflect.Array.newInstance(
java.lang.Thread.java_class, thread_group.activeCount)
thread_group.enumerate(threads)
# NOTE: we shall check the name from $servlet_context.getServletContextName
# but that's an implementation detail of the factory currently that threads
# are named including their context name. thread grouping should be fine !
threads.map do |thread| # a convention is to name threads as "worker" :
thread && thread.getName.index(WORKER_THREAD_ID) ? thread.getName : nil
end.compact
end | [
"def",
"worker_thread_ids",
"thread_group",
"=",
"java",
".",
"lang",
".",
"Thread",
".",
"currentThread",
".",
"getThreadGroup",
"threads",
"=",
"java",
".",
"lang",
".",
"reflect",
".",
"Array",
".",
"newInstance",
"(",
"java",
".",
"lang",
".",
"Thread",
".",
"java_class",
",",
"thread_group",
".",
"activeCount",
")",
"thread_group",
".",
"enumerate",
"(",
"threads",
")",
"# NOTE: we shall check the name from $servlet_context.getServletContextName",
"# but that's an implementation detail of the factory currently that threads",
"# are named including their context name. thread grouping should be fine !",
"threads",
".",
"map",
"do",
"|",
"thread",
"|",
"# a convention is to name threads as \"worker\" :",
"thread",
"&&",
"thread",
".",
"getName",
".",
"index",
"(",
"WORKER_THREAD_ID",
")",
"?",
"thread",
".",
"getName",
":",
"nil",
"end",
".",
"compact",
"end"
] | returns worker thread names that supposely belong to the current application | [
"returns",
"worker",
"thread",
"names",
"that",
"supposely",
"belong",
"to",
"the",
"current",
"application"
] | d6bb51b063d8da6e1c5aedf74f62d7c70ea0aa4d | https://github.com/kares/jruby-rack-worker/blob/d6bb51b063d8da6e1c5aedf74f62d7c70ea0aa4d/src/main/ruby/resque/jruby_worker.rb#L215-L226 |
23,415 | kares/jruby-rack-worker | src/main/ruby/resque/jruby_worker.rb | Resque.JRubyWorker.update_native_thread_name | def update_native_thread_name
thread = JRuby.reference(Thread.current)
set_thread_name = Proc.new do |prefix, suffix|
self.class.with_global_lock do
count = self.class.system_registered_workers.size
thread.native_thread.name = "#{prefix}##{count}#{suffix}"
end
end
if ! name = thread.native_thread.name
# "#{THREAD_ID}##{count}" :
set_thread_name.call(WORKER_THREAD_ID, nil)
elsif ! name.index(WORKER_THREAD_ID)
# "#{name}(#{THREAD_ID}##{count})" :
set_thread_name.call("#{name} (#{WORKER_THREAD_ID}", ')')
end
end | ruby | def update_native_thread_name
thread = JRuby.reference(Thread.current)
set_thread_name = Proc.new do |prefix, suffix|
self.class.with_global_lock do
count = self.class.system_registered_workers.size
thread.native_thread.name = "#{prefix}##{count}#{suffix}"
end
end
if ! name = thread.native_thread.name
# "#{THREAD_ID}##{count}" :
set_thread_name.call(WORKER_THREAD_ID, nil)
elsif ! name.index(WORKER_THREAD_ID)
# "#{name}(#{THREAD_ID}##{count})" :
set_thread_name.call("#{name} (#{WORKER_THREAD_ID}", ')')
end
end | [
"def",
"update_native_thread_name",
"thread",
"=",
"JRuby",
".",
"reference",
"(",
"Thread",
".",
"current",
")",
"set_thread_name",
"=",
"Proc",
".",
"new",
"do",
"|",
"prefix",
",",
"suffix",
"|",
"self",
".",
"class",
".",
"with_global_lock",
"do",
"count",
"=",
"self",
".",
"class",
".",
"system_registered_workers",
".",
"size",
"thread",
".",
"native_thread",
".",
"name",
"=",
"\"#{prefix}##{count}#{suffix}\"",
"end",
"end",
"if",
"!",
"name",
"=",
"thread",
".",
"native_thread",
".",
"name",
"# \"#{THREAD_ID}##{count}\" :",
"set_thread_name",
".",
"call",
"(",
"WORKER_THREAD_ID",
",",
"nil",
")",
"elsif",
"!",
"name",
".",
"index",
"(",
"WORKER_THREAD_ID",
")",
"# \"#{name}(#{THREAD_ID}##{count})\" :",
"set_thread_name",
".",
"call",
"(",
"\"#{name} (#{WORKER_THREAD_ID}\"",
",",
"')'",
")",
"end",
"end"
] | so that we can later identify a "live" worker thread | [
"so",
"that",
"we",
"can",
"later",
"identify",
"a",
"live",
"worker",
"thread"
] | d6bb51b063d8da6e1c5aedf74f62d7c70ea0aa4d | https://github.com/kares/jruby-rack-worker/blob/d6bb51b063d8da6e1c5aedf74f62d7c70ea0aa4d/src/main/ruby/resque/jruby_worker.rb#L398-L413 |
23,416 | kares/jruby-rack-worker | src/main/ruby/resque/jruby_worker.rb | Resque.JRubyWorker.system_unregister_worker | def system_unregister_worker # :nodoc
self.class.with_global_lock do
workers = self.class.system_registered_workers
workers.delete(self.id)
self.class.store_global_property(WORKERS_KEY, workers.join(','))
end
end | ruby | def system_unregister_worker # :nodoc
self.class.with_global_lock do
workers = self.class.system_registered_workers
workers.delete(self.id)
self.class.store_global_property(WORKERS_KEY, workers.join(','))
end
end | [
"def",
"system_unregister_worker",
"# :nodoc",
"self",
".",
"class",
".",
"with_global_lock",
"do",
"workers",
"=",
"self",
".",
"class",
".",
"system_registered_workers",
"workers",
".",
"delete",
"(",
"self",
".",
"id",
")",
"self",
".",
"class",
".",
"store_global_property",
"(",
"WORKERS_KEY",
",",
"workers",
".",
"join",
"(",
"','",
")",
")",
"end",
"end"
] | unregister a worked id globally | [
"unregister",
"a",
"worked",
"id",
"globally"
] | d6bb51b063d8da6e1c5aedf74f62d7c70ea0aa4d | https://github.com/kares/jruby-rack-worker/blob/d6bb51b063d8da6e1c5aedf74f62d7c70ea0aa4d/src/main/ruby/resque/jruby_worker.rb#L426-L432 |
23,417 | kikonen/ngannotate-rails | lib/ngannotate/processor_common.rb | Ngannotate.ProcessorCommon.parse_ngannotate_options | def parse_ngannotate_options
opt = config.options.clone
if ENV['NG_OPT']
opt_str = ENV['NG_OPT']
if opt_str
opt = Hash[opt_str.split(',').map { |e| e.split('=') }]
opt.symbolize_keys!
end
end
regexp = ENV['NG_REGEXP']
if regexp
opt[:regexp] = regexp
end
opt
end | ruby | def parse_ngannotate_options
opt = config.options.clone
if ENV['NG_OPT']
opt_str = ENV['NG_OPT']
if opt_str
opt = Hash[opt_str.split(',').map { |e| e.split('=') }]
opt.symbolize_keys!
end
end
regexp = ENV['NG_REGEXP']
if regexp
opt[:regexp] = regexp
end
opt
end | [
"def",
"parse_ngannotate_options",
"opt",
"=",
"config",
".",
"options",
".",
"clone",
"if",
"ENV",
"[",
"'NG_OPT'",
"]",
"opt_str",
"=",
"ENV",
"[",
"'NG_OPT'",
"]",
"if",
"opt_str",
"opt",
"=",
"Hash",
"[",
"opt_str",
".",
"split",
"(",
"','",
")",
".",
"map",
"{",
"|",
"e",
"|",
"e",
".",
"split",
"(",
"'='",
")",
"}",
"]",
"opt",
".",
"symbolize_keys!",
"end",
"end",
"regexp",
"=",
"ENV",
"[",
"'NG_REGEXP'",
"]",
"if",
"regexp",
"opt",
"[",
":regexp",
"]",
"=",
"regexp",
"end",
"opt",
"end"
] | Parse extra options for ngannotate | [
"Parse",
"extra",
"options",
"for",
"ngannotate"
] | 5297556590b73be868e7e30fcb866a681067b80d | https://github.com/kikonen/ngannotate-rails/blob/5297556590b73be868e7e30fcb866a681067b80d/lib/ngannotate/processor_common.rb#L94-L111 |
23,418 | mattray/spiceweasel | lib/spiceweasel/knife.rb | Spiceweasel.Knife.validate | def validate(command, allknifes)
return if allknifes.index { |x| x.start_with?("knife #{command}") }
STDERR.puts "ERROR: 'knife #{command}' is not a currently supported command for knife."
exit(-1)
end | ruby | def validate(command, allknifes)
return if allknifes.index { |x| x.start_with?("knife #{command}") }
STDERR.puts "ERROR: 'knife #{command}' is not a currently supported command for knife."
exit(-1)
end | [
"def",
"validate",
"(",
"command",
",",
"allknifes",
")",
"return",
"if",
"allknifes",
".",
"index",
"{",
"|",
"x",
"|",
"x",
".",
"start_with?",
"(",
"\"knife #{command}\"",
")",
"}",
"STDERR",
".",
"puts",
"\"ERROR: 'knife #{command}' is not a currently supported command for knife.\"",
"exit",
"(",
"-",
"1",
")",
"end"
] | test that the knife command exists | [
"test",
"that",
"the",
"knife",
"command",
"exists"
] | c7f01a127a542989f8525486890cf12249b6db44 | https://github.com/mattray/spiceweasel/blob/c7f01a127a542989f8525486890cf12249b6db44/lib/spiceweasel/knife.rb#L48-L53 |
23,419 | arangodb-helper/guacamole | lib/guacamole/document_model_mapper.rb | Guacamole.DocumentModelMapper.document_to_model | def document_to_model(document)
identity_map.retrieve_or_store model_class, document.key do
model = model_class.new(document.to_h)
model.key = document.key
model.rev = document.revision
handle_related_documents(model)
model
end
end | ruby | def document_to_model(document)
identity_map.retrieve_or_store model_class, document.key do
model = model_class.new(document.to_h)
model.key = document.key
model.rev = document.revision
handle_related_documents(model)
model
end
end | [
"def",
"document_to_model",
"(",
"document",
")",
"identity_map",
".",
"retrieve_or_store",
"model_class",
",",
"document",
".",
"key",
"do",
"model",
"=",
"model_class",
".",
"new",
"(",
"document",
".",
"to_h",
")",
"model",
".",
"key",
"=",
"document",
".",
"key",
"model",
".",
"rev",
"=",
"document",
".",
"revision",
"handle_related_documents",
"(",
"model",
")",
"model",
"end",
"end"
] | Map a document to a model
Sets the revision, key and all attributes on the model
@param [Ashikawa::Core::Document] document
@return [Model] the resulting model with the given Model class | [
"Map",
"a",
"document",
"to",
"a",
"model"
] | 90505fc0276ea529073c0e8d1087f51f193840b6 | https://github.com/arangodb-helper/guacamole/blob/90505fc0276ea529073c0e8d1087f51f193840b6/lib/guacamole/document_model_mapper.rb#L152-L163 |
23,420 | arangodb-helper/guacamole | lib/guacamole/document_model_mapper.rb | Guacamole.DocumentModelMapper.model_to_document | def model_to_document(model)
document = model.attributes.dup.except(:key, :rev)
handle_embedded_models(model, document)
handle_related_models(document)
document
end | ruby | def model_to_document(model)
document = model.attributes.dup.except(:key, :rev)
handle_embedded_models(model, document)
handle_related_models(document)
document
end | [
"def",
"model_to_document",
"(",
"model",
")",
"document",
"=",
"model",
".",
"attributes",
".",
"dup",
".",
"except",
"(",
":key",
",",
":rev",
")",
"handle_embedded_models",
"(",
"model",
",",
"document",
")",
"handle_related_models",
"(",
"document",
")",
"document",
"end"
] | Map a model to a document
This will include all embedded models
@param [Model] model
@return [Ashikawa::Core::Document] the resulting document | [
"Map",
"a",
"model",
"to",
"a",
"document"
] | 90505fc0276ea529073c0e8d1087f51f193840b6 | https://github.com/arangodb-helper/guacamole/blob/90505fc0276ea529073c0e8d1087f51f193840b6/lib/guacamole/document_model_mapper.rb#L171-L178 |
23,421 | pgharts/trusty-cms | lib/trusty_cms/initializer.rb | TrustyCms.Initializer.initialize_metal | def initialize_metal
Rails::Rack::Metal.requested_metals = configuration.metals
Rails::Rack::Metal.metal_paths = ["#{TRUSTY_CMS_ROOT}/app/metal"] # reset Rails default to TRUSTY_CMS_ROOT
Rails::Rack::Metal.metal_paths += plugin_loader.engine_metal_paths
Rails::Rack::Metal.metal_paths += extension_loader.paths(:metal)
Rails::Rack::Metal.metal_paths.uniq!
configuration.middleware.insert_before(
:"ActionController::ParamsParser",
Rails::Rack::Metal, :if => Rails::Rack::Metal.metals.any?)
end | ruby | def initialize_metal
Rails::Rack::Metal.requested_metals = configuration.metals
Rails::Rack::Metal.metal_paths = ["#{TRUSTY_CMS_ROOT}/app/metal"] # reset Rails default to TRUSTY_CMS_ROOT
Rails::Rack::Metal.metal_paths += plugin_loader.engine_metal_paths
Rails::Rack::Metal.metal_paths += extension_loader.paths(:metal)
Rails::Rack::Metal.metal_paths.uniq!
configuration.middleware.insert_before(
:"ActionController::ParamsParser",
Rails::Rack::Metal, :if => Rails::Rack::Metal.metals.any?)
end | [
"def",
"initialize_metal",
"Rails",
"::",
"Rack",
"::",
"Metal",
".",
"requested_metals",
"=",
"configuration",
".",
"metals",
"Rails",
"::",
"Rack",
"::",
"Metal",
".",
"metal_paths",
"=",
"[",
"\"#{TRUSTY_CMS_ROOT}/app/metal\"",
"]",
"# reset Rails default to TRUSTY_CMS_ROOT",
"Rails",
"::",
"Rack",
"::",
"Metal",
".",
"metal_paths",
"+=",
"plugin_loader",
".",
"engine_metal_paths",
"Rails",
"::",
"Rack",
"::",
"Metal",
".",
"metal_paths",
"+=",
"extension_loader",
".",
"paths",
"(",
":metal",
")",
"Rails",
"::",
"Rack",
"::",
"Metal",
".",
"metal_paths",
".",
"uniq!",
"configuration",
".",
"middleware",
".",
"insert_before",
"(",
":\"",
"\"",
",",
"Rails",
"::",
"Rack",
"::",
"Metal",
",",
":if",
"=>",
"Rails",
"::",
"Rack",
"::",
"Metal",
".",
"metals",
".",
"any?",
")",
"end"
] | Overrides the Rails initializer to load metal from TRUSTY_CMS_ROOT and from radiant extensions. | [
"Overrides",
"the",
"Rails",
"initializer",
"to",
"load",
"metal",
"from",
"TRUSTY_CMS_ROOT",
"and",
"from",
"radiant",
"extensions",
"."
] | 444ad7010c28a8aa5194cc13dd4a376a6bddd1fd | https://github.com/pgharts/trusty-cms/blob/444ad7010c28a8aa5194cc13dd4a376a6bddd1fd/lib/trusty_cms/initializer.rb#L48-L58 |
23,422 | pgharts/trusty-cms | lib/trusty_cms/initializer.rb | TrustyCms.Initializer.initialize_i18n | def initialize_i18n
radiant_locale_paths = Dir[File.join(TRUSTY_CMS_ROOT, 'config', 'locales', '*.{rb,yml}')]
configuration.i18n.load_path = radiant_locale_paths + extension_loader.paths(:locale)
super
end | ruby | def initialize_i18n
radiant_locale_paths = Dir[File.join(TRUSTY_CMS_ROOT, 'config', 'locales', '*.{rb,yml}')]
configuration.i18n.load_path = radiant_locale_paths + extension_loader.paths(:locale)
super
end | [
"def",
"initialize_i18n",
"radiant_locale_paths",
"=",
"Dir",
"[",
"File",
".",
"join",
"(",
"TRUSTY_CMS_ROOT",
",",
"'config'",
",",
"'locales'",
",",
"'*.{rb,yml}'",
")",
"]",
"configuration",
".",
"i18n",
".",
"load_path",
"=",
"radiant_locale_paths",
"+",
"extension_loader",
".",
"paths",
"(",
":locale",
")",
"super",
"end"
] | Extends the Rails initializer to add locale paths from TRUSTY_CMS_ROOT and from radiant extensions. | [
"Extends",
"the",
"Rails",
"initializer",
"to",
"add",
"locale",
"paths",
"from",
"TRUSTY_CMS_ROOT",
"and",
"from",
"radiant",
"extensions",
"."
] | 444ad7010c28a8aa5194cc13dd4a376a6bddd1fd | https://github.com/pgharts/trusty-cms/blob/444ad7010c28a8aa5194cc13dd4a376a6bddd1fd/lib/trusty_cms/initializer.rb#L62-L66 |
23,423 | mattray/spiceweasel | lib/spiceweasel/nodes.rb | Spiceweasel.Nodes.validate_run_list | def validate_run_list(node, run_list, cookbooks, roles)
run_list.split(",").each do |item|
if item.start_with?("recipe[")
# recipe[foo] or recipe[foo::bar]
cb = item.split(/\[|\]/)[1].split(":")[0]
unless cookbooks.member?(cb)
STDERR.puts "ERROR: '#{node}' run list cookbook '#{cb}' is missing from the list of cookbooks in the manifest."
exit(-1)
end
elsif item.start_with?("role[")
# role[blah]
role = item.split(/\[|\]/)[1]
unless roles.member?(role)
STDERR.puts "ERROR: '#{node}' run list role '#{role}' is missing from the list of roles in the manifest."
exit(-1)
end
else
STDERR.puts "ERROR: '#{node}' run list '#{item}' is an invalid run list entry in the manifest."
exit(-1)
end
end
end | ruby | def validate_run_list(node, run_list, cookbooks, roles)
run_list.split(",").each do |item|
if item.start_with?("recipe[")
# recipe[foo] or recipe[foo::bar]
cb = item.split(/\[|\]/)[1].split(":")[0]
unless cookbooks.member?(cb)
STDERR.puts "ERROR: '#{node}' run list cookbook '#{cb}' is missing from the list of cookbooks in the manifest."
exit(-1)
end
elsif item.start_with?("role[")
# role[blah]
role = item.split(/\[|\]/)[1]
unless roles.member?(role)
STDERR.puts "ERROR: '#{node}' run list role '#{role}' is missing from the list of roles in the manifest."
exit(-1)
end
else
STDERR.puts "ERROR: '#{node}' run list '#{item}' is an invalid run list entry in the manifest."
exit(-1)
end
end
end | [
"def",
"validate_run_list",
"(",
"node",
",",
"run_list",
",",
"cookbooks",
",",
"roles",
")",
"run_list",
".",
"split",
"(",
"\",\"",
")",
".",
"each",
"do",
"|",
"item",
"|",
"if",
"item",
".",
"start_with?",
"(",
"\"recipe[\"",
")",
"# recipe[foo] or recipe[foo::bar]",
"cb",
"=",
"item",
".",
"split",
"(",
"/",
"\\[",
"\\]",
"/",
")",
"[",
"1",
"]",
".",
"split",
"(",
"\":\"",
")",
"[",
"0",
"]",
"unless",
"cookbooks",
".",
"member?",
"(",
"cb",
")",
"STDERR",
".",
"puts",
"\"ERROR: '#{node}' run list cookbook '#{cb}' is missing from the list of cookbooks in the manifest.\"",
"exit",
"(",
"-",
"1",
")",
"end",
"elsif",
"item",
".",
"start_with?",
"(",
"\"role[\"",
")",
"# role[blah]",
"role",
"=",
"item",
".",
"split",
"(",
"/",
"\\[",
"\\]",
"/",
")",
"[",
"1",
"]",
"unless",
"roles",
".",
"member?",
"(",
"role",
")",
"STDERR",
".",
"puts",
"\"ERROR: '#{node}' run list role '#{role}' is missing from the list of roles in the manifest.\"",
"exit",
"(",
"-",
"1",
")",
"end",
"else",
"STDERR",
".",
"puts",
"\"ERROR: '#{node}' run list '#{item}' is an invalid run list entry in the manifest.\"",
"exit",
"(",
"-",
"1",
")",
"end",
"end",
"end"
] | ensure run_list contents are listed previously. | [
"ensure",
"run_list",
"contents",
"are",
"listed",
"previously",
"."
] | c7f01a127a542989f8525486890cf12249b6db44 | https://github.com/mattray/spiceweasel/blob/c7f01a127a542989f8525486890cf12249b6db44/lib/spiceweasel/nodes.rb#L102-L123 |
23,424 | mattray/spiceweasel | lib/spiceweasel/nodes.rb | Spiceweasel.Nodes.validate_options | def validate_options(node, options, environments)
if options =~ /-E/ # check for environments
env = options.split("-E")[1].split[0]
unless environments.member?(env)
STDERR.puts "ERROR: '#{node}' environment '#{env}' is missing from the list of environments in the manifest."
exit(-1)
end
end
end | ruby | def validate_options(node, options, environments)
if options =~ /-E/ # check for environments
env = options.split("-E")[1].split[0]
unless environments.member?(env)
STDERR.puts "ERROR: '#{node}' environment '#{env}' is missing from the list of environments in the manifest."
exit(-1)
end
end
end | [
"def",
"validate_options",
"(",
"node",
",",
"options",
",",
"environments",
")",
"if",
"options",
"=~",
"/",
"/",
"# check for environments",
"env",
"=",
"options",
".",
"split",
"(",
"\"-E\"",
")",
"[",
"1",
"]",
".",
"split",
"[",
"0",
"]",
"unless",
"environments",
".",
"member?",
"(",
"env",
")",
"STDERR",
".",
"puts",
"\"ERROR: '#{node}' environment '#{env}' is missing from the list of environments in the manifest.\"",
"exit",
"(",
"-",
"1",
")",
"end",
"end",
"end"
] | for now, just check that -E is legit | [
"for",
"now",
"just",
"check",
"that",
"-",
"E",
"is",
"legit"
] | c7f01a127a542989f8525486890cf12249b6db44 | https://github.com/mattray/spiceweasel/blob/c7f01a127a542989f8525486890cf12249b6db44/lib/spiceweasel/nodes.rb#L126-L134 |
23,425 | mattray/spiceweasel | lib/spiceweasel/nodes.rb | Spiceweasel.Nodes.validate_node_file | def validate_node_file(name)
# read in the file
node = Chef::JSONCompat.from_json(IO.read("nodes/#{name}.json"))
# check the node name vs. contents of the file
return unless node["name"] != name
STDERR.puts "ERROR: Node '#{name}' listed in the manifest does not match the name '#{node['name']}' within the nodes/#{name}.json file."
exit(-1)
end | ruby | def validate_node_file(name)
# read in the file
node = Chef::JSONCompat.from_json(IO.read("nodes/#{name}.json"))
# check the node name vs. contents of the file
return unless node["name"] != name
STDERR.puts "ERROR: Node '#{name}' listed in the manifest does not match the name '#{node['name']}' within the nodes/#{name}.json file."
exit(-1)
end | [
"def",
"validate_node_file",
"(",
"name",
")",
"# read in the file",
"node",
"=",
"Chef",
"::",
"JSONCompat",
".",
"from_json",
"(",
"IO",
".",
"read",
"(",
"\"nodes/#{name}.json\"",
")",
")",
"# check the node name vs. contents of the file",
"return",
"unless",
"node",
"[",
"\"name\"",
"]",
"!=",
"name",
"STDERR",
".",
"puts",
"\"ERROR: Node '#{name}' listed in the manifest does not match the name '#{node['name']}' within the nodes/#{name}.json file.\"",
"exit",
"(",
"-",
"1",
")",
"end"
] | validate individual node files | [
"validate",
"individual",
"node",
"files"
] | c7f01a127a542989f8525486890cf12249b6db44 | https://github.com/mattray/spiceweasel/blob/c7f01a127a542989f8525486890cf12249b6db44/lib/spiceweasel/nodes.rb#L184-L193 |
23,426 | mattray/spiceweasel | lib/spiceweasel/nodes.rb | Spiceweasel.Nodes.process_providers | def process_providers(names, count, name, options, run_list, create_command_options, knifecommands) # rubocop:disable CyclomaticComplexity
provider = names[0]
validate_provider(provider, names, count, options, knifecommands) unless Spiceweasel::Config[:novalidation]
provided_names = []
if name.nil? && options.split.index("-N") # pull this out for deletes
name = options.split[options.split.index("-N") + 1]
count.to_i.times { |i| provided_names << node_numerate(name, i + 1, count) } if name
end
# google can have names or numbers
if provider.eql?("google") && names[1].to_i == 0
do_google_numeric_provider(create_command_options, names, options, provided_names, run_list)
elsif Spiceweasel::Config[:parallel]
process_parallel(count, create_command_options, name, options, provider, run_list)
else
determine_cloud_provider(count, create_command_options, name, options, provider, run_list)
end
if Spiceweasel::Config[:bulkdelete] && provided_names.empty?
do_bulk_delete(provider)
else
provided_names.each do |p_name|
do_provided_names(p_name, provider)
end
end
end | ruby | def process_providers(names, count, name, options, run_list, create_command_options, knifecommands) # rubocop:disable CyclomaticComplexity
provider = names[0]
validate_provider(provider, names, count, options, knifecommands) unless Spiceweasel::Config[:novalidation]
provided_names = []
if name.nil? && options.split.index("-N") # pull this out for deletes
name = options.split[options.split.index("-N") + 1]
count.to_i.times { |i| provided_names << node_numerate(name, i + 1, count) } if name
end
# google can have names or numbers
if provider.eql?("google") && names[1].to_i == 0
do_google_numeric_provider(create_command_options, names, options, provided_names, run_list)
elsif Spiceweasel::Config[:parallel]
process_parallel(count, create_command_options, name, options, provider, run_list)
else
determine_cloud_provider(count, create_command_options, name, options, provider, run_list)
end
if Spiceweasel::Config[:bulkdelete] && provided_names.empty?
do_bulk_delete(provider)
else
provided_names.each do |p_name|
do_provided_names(p_name, provider)
end
end
end | [
"def",
"process_providers",
"(",
"names",
",",
"count",
",",
"name",
",",
"options",
",",
"run_list",
",",
"create_command_options",
",",
"knifecommands",
")",
"# rubocop:disable CyclomaticComplexity",
"provider",
"=",
"names",
"[",
"0",
"]",
"validate_provider",
"(",
"provider",
",",
"names",
",",
"count",
",",
"options",
",",
"knifecommands",
")",
"unless",
"Spiceweasel",
"::",
"Config",
"[",
":novalidation",
"]",
"provided_names",
"=",
"[",
"]",
"if",
"name",
".",
"nil?",
"&&",
"options",
".",
"split",
".",
"index",
"(",
"\"-N\"",
")",
"# pull this out for deletes",
"name",
"=",
"options",
".",
"split",
"[",
"options",
".",
"split",
".",
"index",
"(",
"\"-N\"",
")",
"+",
"1",
"]",
"count",
".",
"to_i",
".",
"times",
"{",
"|",
"i",
"|",
"provided_names",
"<<",
"node_numerate",
"(",
"name",
",",
"i",
"+",
"1",
",",
"count",
")",
"}",
"if",
"name",
"end",
"# google can have names or numbers",
"if",
"provider",
".",
"eql?",
"(",
"\"google\"",
")",
"&&",
"names",
"[",
"1",
"]",
".",
"to_i",
"==",
"0",
"do_google_numeric_provider",
"(",
"create_command_options",
",",
"names",
",",
"options",
",",
"provided_names",
",",
"run_list",
")",
"elsif",
"Spiceweasel",
"::",
"Config",
"[",
":parallel",
"]",
"process_parallel",
"(",
"count",
",",
"create_command_options",
",",
"name",
",",
"options",
",",
"provider",
",",
"run_list",
")",
"else",
"determine_cloud_provider",
"(",
"count",
",",
"create_command_options",
",",
"name",
",",
"options",
",",
"provider",
",",
"run_list",
")",
"end",
"if",
"Spiceweasel",
"::",
"Config",
"[",
":bulkdelete",
"]",
"&&",
"provided_names",
".",
"empty?",
"do_bulk_delete",
"(",
"provider",
")",
"else",
"provided_names",
".",
"each",
"do",
"|",
"p_name",
"|",
"do_provided_names",
"(",
"p_name",
",",
"provider",
")",
"end",
"end",
"end"
] | manage all the provider logic | [
"manage",
"all",
"the",
"provider",
"logic"
] | c7f01a127a542989f8525486890cf12249b6db44 | https://github.com/mattray/spiceweasel/blob/c7f01a127a542989f8525486890cf12249b6db44/lib/spiceweasel/nodes.rb#L196-L220 |
23,427 | mattray/spiceweasel | lib/spiceweasel/nodes.rb | Spiceweasel.Nodes.validate_provider | def validate_provider(provider, names, _count, options, knifecommands)
unless knifecommands.index { |x| x.start_with?("knife #{provider}") }
STDERR.puts "ERROR: 'knife #{provider}' is not a currently installed plugin for knife."
exit(-1)
end
return unless provider.eql?("google")
return unless names[1].to_i != 0 && !options.split.member?("-N")
STDERR.puts "ERROR: 'knife google' currently requires providing a name. Please use -N within the options."
exit(-1)
end | ruby | def validate_provider(provider, names, _count, options, knifecommands)
unless knifecommands.index { |x| x.start_with?("knife #{provider}") }
STDERR.puts "ERROR: 'knife #{provider}' is not a currently installed plugin for knife."
exit(-1)
end
return unless provider.eql?("google")
return unless names[1].to_i != 0 && !options.split.member?("-N")
STDERR.puts "ERROR: 'knife google' currently requires providing a name. Please use -N within the options."
exit(-1)
end | [
"def",
"validate_provider",
"(",
"provider",
",",
"names",
",",
"_count",
",",
"options",
",",
"knifecommands",
")",
"unless",
"knifecommands",
".",
"index",
"{",
"|",
"x",
"|",
"x",
".",
"start_with?",
"(",
"\"knife #{provider}\"",
")",
"}",
"STDERR",
".",
"puts",
"\"ERROR: 'knife #{provider}' is not a currently installed plugin for knife.\"",
"exit",
"(",
"-",
"1",
")",
"end",
"return",
"unless",
"provider",
".",
"eql?",
"(",
"\"google\"",
")",
"return",
"unless",
"names",
"[",
"1",
"]",
".",
"to_i",
"!=",
"0",
"&&",
"!",
"options",
".",
"split",
".",
"member?",
"(",
"\"-N\"",
")",
"STDERR",
".",
"puts",
"\"ERROR: 'knife google' currently requires providing a name. Please use -N within the options.\"",
"exit",
"(",
"-",
"1",
")",
"end"
] | check that the knife plugin is installed | [
"check",
"that",
"the",
"knife",
"plugin",
"is",
"installed"
] | c7f01a127a542989f8525486890cf12249b6db44 | https://github.com/mattray/spiceweasel/blob/c7f01a127a542989f8525486890cf12249b6db44/lib/spiceweasel/nodes.rb#L321-L333 |
23,428 | mattray/spiceweasel | lib/spiceweasel/nodes.rb | Spiceweasel.Nodes.chef_client_search | def chef_client_search(name, run_list, environment)
search = []
search.push("name:#{name}") if name
search.push("chef_environment:#{environment}") if environment
run_list.split(",").each do |item|
item.sub!(/\[/, ":")
item.chop!
item.sub!(/::/, '\:\:')
search.push(item)
end
"#{search.join(' AND ')}"
end | ruby | def chef_client_search(name, run_list, environment)
search = []
search.push("name:#{name}") if name
search.push("chef_environment:#{environment}") if environment
run_list.split(",").each do |item|
item.sub!(/\[/, ":")
item.chop!
item.sub!(/::/, '\:\:')
search.push(item)
end
"#{search.join(' AND ')}"
end | [
"def",
"chef_client_search",
"(",
"name",
",",
"run_list",
",",
"environment",
")",
"search",
"=",
"[",
"]",
"search",
".",
"push",
"(",
"\"name:#{name}\"",
")",
"if",
"name",
"search",
".",
"push",
"(",
"\"chef_environment:#{environment}\"",
")",
"if",
"environment",
"run_list",
".",
"split",
"(",
"\",\"",
")",
".",
"each",
"do",
"|",
"item",
"|",
"item",
".",
"sub!",
"(",
"/",
"\\[",
"/",
",",
"\":\"",
")",
"item",
".",
"chop!",
"item",
".",
"sub!",
"(",
"/",
"/",
",",
"'\\:\\:'",
")",
"search",
".",
"push",
"(",
"item",
")",
"end",
"\"#{search.join(' AND ')}\"",
"end"
] | create the knife ssh chef-client search pattern | [
"create",
"the",
"knife",
"ssh",
"chef",
"-",
"client",
"search",
"pattern"
] | c7f01a127a542989f8525486890cf12249b6db44 | https://github.com/mattray/spiceweasel/blob/c7f01a127a542989f8525486890cf12249b6db44/lib/spiceweasel/nodes.rb#L474-L485 |
23,429 | mattray/spiceweasel | lib/spiceweasel/cookbooks.rb | Spiceweasel.Cookbooks.validate_metadata | def validate_metadata(cookbook, version)
# check metadata.rb for requested version
metadata = @loader.cookbooks_by_name[cookbook].metadata
Spiceweasel::Log.debug("validate_metadata: #{cookbook} #{metadata.name} #{metadata.version}")
# Should the cookbook directory match the name in the metadata?
if metadata.name.empty?
Spiceweasel::Log.warn("No cookbook name in the #{cookbook} metadata.rb.")
elsif cookbook != metadata.name
STDERR.puts "ERROR: Cookbook '#{cookbook}' does not match the name '#{metadata.name}' in #{cookbook}/metadata.rb."
exit(-1)
end
if version && metadata.version != version
STDERR.puts "ERROR: Invalid version '#{version}' of '#{cookbook}' requested, '#{metadata.version}' is already in the cookbooks directory."
exit(-1)
end
metadata.dependencies.each do |dependency|
Spiceweasel::Log.debug("cookbook #{cookbook} metadata dependency: #{dependency}")
@dependencies.push(dependency[0])
end
end | ruby | def validate_metadata(cookbook, version)
# check metadata.rb for requested version
metadata = @loader.cookbooks_by_name[cookbook].metadata
Spiceweasel::Log.debug("validate_metadata: #{cookbook} #{metadata.name} #{metadata.version}")
# Should the cookbook directory match the name in the metadata?
if metadata.name.empty?
Spiceweasel::Log.warn("No cookbook name in the #{cookbook} metadata.rb.")
elsif cookbook != metadata.name
STDERR.puts "ERROR: Cookbook '#{cookbook}' does not match the name '#{metadata.name}' in #{cookbook}/metadata.rb."
exit(-1)
end
if version && metadata.version != version
STDERR.puts "ERROR: Invalid version '#{version}' of '#{cookbook}' requested, '#{metadata.version}' is already in the cookbooks directory."
exit(-1)
end
metadata.dependencies.each do |dependency|
Spiceweasel::Log.debug("cookbook #{cookbook} metadata dependency: #{dependency}")
@dependencies.push(dependency[0])
end
end | [
"def",
"validate_metadata",
"(",
"cookbook",
",",
"version",
")",
"# check metadata.rb for requested version",
"metadata",
"=",
"@loader",
".",
"cookbooks_by_name",
"[",
"cookbook",
"]",
".",
"metadata",
"Spiceweasel",
"::",
"Log",
".",
"debug",
"(",
"\"validate_metadata: #{cookbook} #{metadata.name} #{metadata.version}\"",
")",
"# Should the cookbook directory match the name in the metadata?",
"if",
"metadata",
".",
"name",
".",
"empty?",
"Spiceweasel",
"::",
"Log",
".",
"warn",
"(",
"\"No cookbook name in the #{cookbook} metadata.rb.\"",
")",
"elsif",
"cookbook",
"!=",
"metadata",
".",
"name",
"STDERR",
".",
"puts",
"\"ERROR: Cookbook '#{cookbook}' does not match the name '#{metadata.name}' in #{cookbook}/metadata.rb.\"",
"exit",
"(",
"-",
"1",
")",
"end",
"if",
"version",
"&&",
"metadata",
".",
"version",
"!=",
"version",
"STDERR",
".",
"puts",
"\"ERROR: Invalid version '#{version}' of '#{cookbook}' requested, '#{metadata.version}' is already in the cookbooks directory.\"",
"exit",
"(",
"-",
"1",
")",
"end",
"metadata",
".",
"dependencies",
".",
"each",
"do",
"|",
"dependency",
"|",
"Spiceweasel",
"::",
"Log",
".",
"debug",
"(",
"\"cookbook #{cookbook} metadata dependency: #{dependency}\"",
")",
"@dependencies",
".",
"push",
"(",
"dependency",
"[",
"0",
"]",
")",
"end",
"end"
] | check the metadata for versions and gather deps | [
"check",
"the",
"metadata",
"for",
"versions",
"and",
"gather",
"deps"
] | c7f01a127a542989f8525486890cf12249b6db44 | https://github.com/mattray/spiceweasel/blob/c7f01a127a542989f8525486890cf12249b6db44/lib/spiceweasel/cookbooks.rb#L105-L124 |
23,430 | mattray/spiceweasel | lib/spiceweasel/cookbooks.rb | Spiceweasel.Cookbooks.validate_dependencies | def validate_dependencies
Spiceweasel::Log.debug("cookbook validate_dependencies: '#{@dependencies}'")
@dependencies.each do |dep|
unless member?(dep)
STDERR.puts "ERROR: Cookbook dependency '#{dep}' is missing from the list of cookbooks in the manifest."
exit(-1)
end
end
end | ruby | def validate_dependencies
Spiceweasel::Log.debug("cookbook validate_dependencies: '#{@dependencies}'")
@dependencies.each do |dep|
unless member?(dep)
STDERR.puts "ERROR: Cookbook dependency '#{dep}' is missing from the list of cookbooks in the manifest."
exit(-1)
end
end
end | [
"def",
"validate_dependencies",
"Spiceweasel",
"::",
"Log",
".",
"debug",
"(",
"\"cookbook validate_dependencies: '#{@dependencies}'\"",
")",
"@dependencies",
".",
"each",
"do",
"|",
"dep",
"|",
"unless",
"member?",
"(",
"dep",
")",
"STDERR",
".",
"puts",
"\"ERROR: Cookbook dependency '#{dep}' is missing from the list of cookbooks in the manifest.\"",
"exit",
"(",
"-",
"1",
")",
"end",
"end",
"end"
] | compare the list of cookbook deps with those specified | [
"compare",
"the",
"list",
"of",
"cookbook",
"deps",
"with",
"those",
"specified"
] | c7f01a127a542989f8525486890cf12249b6db44 | https://github.com/mattray/spiceweasel/blob/c7f01a127a542989f8525486890cf12249b6db44/lib/spiceweasel/cookbooks.rb#L127-L135 |
23,431 | DDAZZA/renogen | lib/renogen/generator.rb | Renogen.Generator.generate! | def generate!
changelog = extraction_stratagy.extract
changelog.version = version
changelog.date = options['release_date']
writer.write!(changelog)
end | ruby | def generate!
changelog = extraction_stratagy.extract
changelog.version = version
changelog.date = options['release_date']
writer.write!(changelog)
end | [
"def",
"generate!",
"changelog",
"=",
"extraction_stratagy",
".",
"extract",
"changelog",
".",
"version",
"=",
"version",
"changelog",
".",
"date",
"=",
"options",
"[",
"'release_date'",
"]",
"writer",
".",
"write!",
"(",
"changelog",
")",
"end"
] | Create the change log | [
"Create",
"the",
"change",
"log"
] | 4c9b3db56b1e56c95f457c1a92e43f411c18a4f7 | https://github.com/DDAZZA/renogen/blob/4c9b3db56b1e56c95f457c1a92e43f411c18a4f7/lib/renogen/generator.rb#L14-L20 |
23,432 | arangodb-helper/guacamole | lib/guacamole/aql_query.rb | Guacamole.AqlQuery.perfom_query | def perfom_query(iterator_with_mapping, &block)
iterator = perform_mapping? ? iterator_with_mapping : iterator_without_mapping(&block)
connection.execute(aql_string, options).each(&iterator)
end | ruby | def perfom_query(iterator_with_mapping, &block)
iterator = perform_mapping? ? iterator_with_mapping : iterator_without_mapping(&block)
connection.execute(aql_string, options).each(&iterator)
end | [
"def",
"perfom_query",
"(",
"iterator_with_mapping",
",",
"&",
"block",
")",
"iterator",
"=",
"perform_mapping?",
"?",
"iterator_with_mapping",
":",
"iterator_without_mapping",
"(",
"block",
")",
"connection",
".",
"execute",
"(",
"aql_string",
",",
"options",
")",
".",
"each",
"(",
"iterator",
")",
"end"
] | Executes an AQL query with bind parameters
@see Query#perfom_query | [
"Executes",
"an",
"AQL",
"query",
"with",
"bind",
"parameters"
] | 90505fc0276ea529073c0e8d1087f51f193840b6 | https://github.com/arangodb-helper/guacamole/blob/90505fc0276ea529073c0e8d1087f51f193840b6/lib/guacamole/aql_query.rb#L96-L99 |
23,433 | mattray/spiceweasel | lib/spiceweasel/clusters.rb | Spiceweasel.Clusters.cluster_process_nodes | def cluster_process_nodes(cluster, environment, cookbooks, environments, roles, knifecommands, rootoptions)
Spiceweasel::Log.debug("cluster::cluster_process_nodes '#{environment}' '#{cluster[environment]}'")
cluster[environment].each do |node|
node_name = node.keys.first
options = node[node_name]["options"] || ""
validate_environment(options, environment, environments) unless Spiceweasel::Config[:novalidation]
# push the Environment back on the options
node[node_name]["options"] = options + " -E #{environment}"
end
# let's reuse the Nodes logic
nodes = Spiceweasel::Nodes.new(cluster[environment], cookbooks, environments, roles, knifecommands, rootoptions)
@create.concat(nodes.create)
# what about providers??
nodes.delete.each do |del|
@delete.push(del) unless del.to_s =~ /^knife client|^knife node/
end
if bundler?
@delete.push(Command.new("for N in $(bundle exec knife node list -E #{environment}); do bundle exec knife client delete $N -y; bundle exec knife node delete $N -y; done"))
else
@delete.push(Command.new("for N in $(knife node list -E #{environment}); do knife client delete $N -y; knife node delete $N -y; done"))
end
end | ruby | def cluster_process_nodes(cluster, environment, cookbooks, environments, roles, knifecommands, rootoptions)
Spiceweasel::Log.debug("cluster::cluster_process_nodes '#{environment}' '#{cluster[environment]}'")
cluster[environment].each do |node|
node_name = node.keys.first
options = node[node_name]["options"] || ""
validate_environment(options, environment, environments) unless Spiceweasel::Config[:novalidation]
# push the Environment back on the options
node[node_name]["options"] = options + " -E #{environment}"
end
# let's reuse the Nodes logic
nodes = Spiceweasel::Nodes.new(cluster[environment], cookbooks, environments, roles, knifecommands, rootoptions)
@create.concat(nodes.create)
# what about providers??
nodes.delete.each do |del|
@delete.push(del) unless del.to_s =~ /^knife client|^knife node/
end
if bundler?
@delete.push(Command.new("for N in $(bundle exec knife node list -E #{environment}); do bundle exec knife client delete $N -y; bundle exec knife node delete $N -y; done"))
else
@delete.push(Command.new("for N in $(knife node list -E #{environment}); do knife client delete $N -y; knife node delete $N -y; done"))
end
end | [
"def",
"cluster_process_nodes",
"(",
"cluster",
",",
"environment",
",",
"cookbooks",
",",
"environments",
",",
"roles",
",",
"knifecommands",
",",
"rootoptions",
")",
"Spiceweasel",
"::",
"Log",
".",
"debug",
"(",
"\"cluster::cluster_process_nodes '#{environment}' '#{cluster[environment]}'\"",
")",
"cluster",
"[",
"environment",
"]",
".",
"each",
"do",
"|",
"node",
"|",
"node_name",
"=",
"node",
".",
"keys",
".",
"first",
"options",
"=",
"node",
"[",
"node_name",
"]",
"[",
"\"options\"",
"]",
"||",
"\"\"",
"validate_environment",
"(",
"options",
",",
"environment",
",",
"environments",
")",
"unless",
"Spiceweasel",
"::",
"Config",
"[",
":novalidation",
"]",
"# push the Environment back on the options",
"node",
"[",
"node_name",
"]",
"[",
"\"options\"",
"]",
"=",
"options",
"+",
"\" -E #{environment}\"",
"end",
"# let's reuse the Nodes logic",
"nodes",
"=",
"Spiceweasel",
"::",
"Nodes",
".",
"new",
"(",
"cluster",
"[",
"environment",
"]",
",",
"cookbooks",
",",
"environments",
",",
"roles",
",",
"knifecommands",
",",
"rootoptions",
")",
"@create",
".",
"concat",
"(",
"nodes",
".",
"create",
")",
"# what about providers??",
"nodes",
".",
"delete",
".",
"each",
"do",
"|",
"del",
"|",
"@delete",
".",
"push",
"(",
"del",
")",
"unless",
"del",
".",
"to_s",
"=~",
"/",
"/",
"end",
"if",
"bundler?",
"@delete",
".",
"push",
"(",
"Command",
".",
"new",
"(",
"\"for N in $(bundle exec knife node list -E #{environment}); do bundle exec knife client delete $N -y; bundle exec knife node delete $N -y; done\"",
")",
")",
"else",
"@delete",
".",
"push",
"(",
"Command",
".",
"new",
"(",
"\"for N in $(knife node list -E #{environment}); do knife client delete $N -y; knife node delete $N -y; done\"",
")",
")",
"end",
"end"
] | configure the individual nodes within the cluster | [
"configure",
"the",
"individual",
"nodes",
"within",
"the",
"cluster"
] | c7f01a127a542989f8525486890cf12249b6db44 | https://github.com/mattray/spiceweasel/blob/c7f01a127a542989f8525486890cf12249b6db44/lib/spiceweasel/clusters.rb#L37-L58 |
23,434 | pgharts/trusty-cms | lib/trusty_cms/extension_loader.rb | TrustyCms.ExtensionLoader.activate_extensions | def activate_extensions
initializer.initialize_views
ordered_extensions = []
configuration = TrustyCms::Application.config
if configuration.extensions.first == :all
ordered_extensions = extensions
else
configuration.extensions.each {|name| ordered_extensions << select_extension(name) }
end
ordered_extensions.flatten.each(&:activate)
Page.load_subclasses
end | ruby | def activate_extensions
initializer.initialize_views
ordered_extensions = []
configuration = TrustyCms::Application.config
if configuration.extensions.first == :all
ordered_extensions = extensions
else
configuration.extensions.each {|name| ordered_extensions << select_extension(name) }
end
ordered_extensions.flatten.each(&:activate)
Page.load_subclasses
end | [
"def",
"activate_extensions",
"initializer",
".",
"initialize_views",
"ordered_extensions",
"=",
"[",
"]",
"configuration",
"=",
"TrustyCms",
"::",
"Application",
".",
"config",
"if",
"configuration",
".",
"extensions",
".",
"first",
"==",
":all",
"ordered_extensions",
"=",
"extensions",
"else",
"configuration",
".",
"extensions",
".",
"each",
"{",
"|",
"name",
"|",
"ordered_extensions",
"<<",
"select_extension",
"(",
"name",
")",
"}",
"end",
"ordered_extensions",
".",
"flatten",
".",
"each",
"(",
":activate",
")",
"Page",
".",
"load_subclasses",
"end"
] | Activates all enabled extensions and makes sure that any newly declared subclasses of Page are recognised.
The admin UI and views have to be reinitialized each time to pick up changes and avoid duplicates. | [
"Activates",
"all",
"enabled",
"extensions",
"and",
"makes",
"sure",
"that",
"any",
"newly",
"declared",
"subclasses",
"of",
"Page",
"are",
"recognised",
".",
"The",
"admin",
"UI",
"and",
"views",
"have",
"to",
"be",
"reinitialized",
"each",
"time",
"to",
"pick",
"up",
"changes",
"and",
"avoid",
"duplicates",
"."
] | 444ad7010c28a8aa5194cc13dd4a376a6bddd1fd | https://github.com/pgharts/trusty-cms/blob/444ad7010c28a8aa5194cc13dd4a376a6bddd1fd/lib/trusty_cms/extension_loader.rb#L100-L111 |
23,435 | jamesramsay/jekyll-app-engine | lib/jekyll-app-engine.rb | Jekyll.JekyllAppEngine.source_partial_exists? | def source_partial_exists?
if @site.respond_to?(:in_source_dir)
File.exists? @site.in_source_dir("_app.yaml")
else
File.exists? Jekyll.sanitized_path(@site.source, "_app.yaml")
end
end | ruby | def source_partial_exists?
if @site.respond_to?(:in_source_dir)
File.exists? @site.in_source_dir("_app.yaml")
else
File.exists? Jekyll.sanitized_path(@site.source, "_app.yaml")
end
end | [
"def",
"source_partial_exists?",
"if",
"@site",
".",
"respond_to?",
"(",
":in_source_dir",
")",
"File",
".",
"exists?",
"@site",
".",
"in_source_dir",
"(",
"\"_app.yaml\"",
")",
"else",
"File",
".",
"exists?",
"Jekyll",
".",
"sanitized_path",
"(",
"@site",
".",
"source",
",",
"\"_app.yaml\"",
")",
"end",
"end"
] | Checks if a optional _app.yaml partial already exists | [
"Checks",
"if",
"a",
"optional",
"_app",
".",
"yaml",
"partial",
"already",
"exists"
] | e562baf54ebb4496bdd77183b2bd4b83d015d843 | https://github.com/jamesramsay/jekyll-app-engine/blob/e562baf54ebb4496bdd77183b2bd4b83d015d843/lib/jekyll-app-engine.rb#L50-L56 |
23,436 | jamesramsay/jekyll-app-engine | lib/jekyll-app-engine.rb | Jekyll.JekyllAppEngine.document_overrides | def document_overrides(document)
if document.respond_to?(:data) and document.data.has_key?("app_engine")
document.data.fetch("app_engine")
else
{}
end
end | ruby | def document_overrides(document)
if document.respond_to?(:data) and document.data.has_key?("app_engine")
document.data.fetch("app_engine")
else
{}
end
end | [
"def",
"document_overrides",
"(",
"document",
")",
"if",
"document",
".",
"respond_to?",
"(",
":data",
")",
"and",
"document",
".",
"data",
".",
"has_key?",
"(",
"\"app_engine\"",
")",
"document",
".",
"data",
".",
"fetch",
"(",
"\"app_engine\"",
")",
"else",
"{",
"}",
"end",
"end"
] | Document specific app.yaml configuration provided in yaml frontmatter | [
"Document",
"specific",
"app",
".",
"yaml",
"configuration",
"provided",
"in",
"yaml",
"frontmatter"
] | e562baf54ebb4496bdd77183b2bd4b83d015d843 | https://github.com/jamesramsay/jekyll-app-engine/blob/e562baf54ebb4496bdd77183b2bd4b83d015d843/lib/jekyll-app-engine.rb#L161-L167 |
23,437 | jamesramsay/jekyll-app-engine | lib/jekyll-app-engine.rb | Jekyll.JekyllAppEngine.app_yaml_exists? | def app_yaml_exists?
if @site.respond_to?(:in_source_dir)
File.exists? @site.in_source_dir("app.yaml")
else
File.exists? Jekyll.sanitized_path(@site.source, "app.yaml")
end
end | ruby | def app_yaml_exists?
if @site.respond_to?(:in_source_dir)
File.exists? @site.in_source_dir("app.yaml")
else
File.exists? Jekyll.sanitized_path(@site.source, "app.yaml")
end
end | [
"def",
"app_yaml_exists?",
"if",
"@site",
".",
"respond_to?",
"(",
":in_source_dir",
")",
"File",
".",
"exists?",
"@site",
".",
"in_source_dir",
"(",
"\"app.yaml\"",
")",
"else",
"File",
".",
"exists?",
"Jekyll",
".",
"sanitized_path",
"(",
"@site",
".",
"source",
",",
"\"app.yaml\"",
")",
"end",
"end"
] | Checks if a app.yaml already exists in the site source | [
"Checks",
"if",
"a",
"app",
".",
"yaml",
"already",
"exists",
"in",
"the",
"site",
"source"
] | e562baf54ebb4496bdd77183b2bd4b83d015d843 | https://github.com/jamesramsay/jekyll-app-engine/blob/e562baf54ebb4496bdd77183b2bd4b83d015d843/lib/jekyll-app-engine.rb#L170-L176 |
23,438 | mattray/spiceweasel | lib/spiceweasel/data_bags.rb | Spiceweasel.DataBags.validate_item | def validate_item(db, item)
unless File.exist?("data_bags/#{db}/#{item}.json")
STDERR.puts "ERROR: data bag '#{db}' item '#{item}' file 'data_bags/#{db}/#{item}.json' does not exist"
exit(-1)
end
f = File.read("data_bags/#{db}/#{item}.json")
begin
itemfile = JSON.parse(f)
rescue JSON::ParserError => e # invalid JSON
STDERR.puts "ERROR: data bag '#{db} item '#{item}' has JSON errors."
STDERR.puts e.message
exit(-1)
end
# validate the id matches the file name
item = item.split("/").last if item =~ /\// # pull out directories
return if item.eql?(itemfile["id"])
STDERR.puts "ERROR: data bag '#{db}' item '#{item}' listed in the manifest does not match the id '#{itemfile['id']}' within the 'data_bags/#{db}/#{item}.json' file."
exit(-1)
end | ruby | def validate_item(db, item)
unless File.exist?("data_bags/#{db}/#{item}.json")
STDERR.puts "ERROR: data bag '#{db}' item '#{item}' file 'data_bags/#{db}/#{item}.json' does not exist"
exit(-1)
end
f = File.read("data_bags/#{db}/#{item}.json")
begin
itemfile = JSON.parse(f)
rescue JSON::ParserError => e # invalid JSON
STDERR.puts "ERROR: data bag '#{db} item '#{item}' has JSON errors."
STDERR.puts e.message
exit(-1)
end
# validate the id matches the file name
item = item.split("/").last if item =~ /\// # pull out directories
return if item.eql?(itemfile["id"])
STDERR.puts "ERROR: data bag '#{db}' item '#{item}' listed in the manifest does not match the id '#{itemfile['id']}' within the 'data_bags/#{db}/#{item}.json' file."
exit(-1)
end | [
"def",
"validate_item",
"(",
"db",
",",
"item",
")",
"unless",
"File",
".",
"exist?",
"(",
"\"data_bags/#{db}/#{item}.json\"",
")",
"STDERR",
".",
"puts",
"\"ERROR: data bag '#{db}' item '#{item}' file 'data_bags/#{db}/#{item}.json' does not exist\"",
"exit",
"(",
"-",
"1",
")",
"end",
"f",
"=",
"File",
".",
"read",
"(",
"\"data_bags/#{db}/#{item}.json\"",
")",
"begin",
"itemfile",
"=",
"JSON",
".",
"parse",
"(",
"f",
")",
"rescue",
"JSON",
"::",
"ParserError",
"=>",
"e",
"# invalid JSON",
"STDERR",
".",
"puts",
"\"ERROR: data bag '#{db} item '#{item}' has JSON errors.\"",
"STDERR",
".",
"puts",
"e",
".",
"message",
"exit",
"(",
"-",
"1",
")",
"end",
"# validate the id matches the file name",
"item",
"=",
"item",
".",
"split",
"(",
"\"/\"",
")",
".",
"last",
"if",
"item",
"=~",
"/",
"\\/",
"/",
"# pull out directories",
"return",
"if",
"item",
".",
"eql?",
"(",
"itemfile",
"[",
"\"id\"",
"]",
")",
"STDERR",
".",
"puts",
"\"ERROR: data bag '#{db}' item '#{item}' listed in the manifest does not match the id '#{itemfile['id']}' within the 'data_bags/#{db}/#{item}.json' file.\"",
"exit",
"(",
"-",
"1",
")",
"end"
] | validate the item to be loaded | [
"validate",
"the",
"item",
"to",
"be",
"loaded"
] | c7f01a127a542989f8525486890cf12249b6db44 | https://github.com/mattray/spiceweasel/blob/c7f01a127a542989f8525486890cf12249b6db44/lib/spiceweasel/data_bags.rb#L114-L134 |
23,439 | solnic/coercible | lib/coercible/coercer.rb | Coercible.Coercer.initialize_coercer | def initialize_coercer(klass)
coercers[klass] =
begin
coercer = Coercer::Object.determine_type(klass) || Coercer::Object
args = [ self ]
args << config_for(coercer) if coercer.respond_to?(:config_name)
coercer.new(*args)
end
end | ruby | def initialize_coercer(klass)
coercers[klass] =
begin
coercer = Coercer::Object.determine_type(klass) || Coercer::Object
args = [ self ]
args << config_for(coercer) if coercer.respond_to?(:config_name)
coercer.new(*args)
end
end | [
"def",
"initialize_coercer",
"(",
"klass",
")",
"coercers",
"[",
"klass",
"]",
"=",
"begin",
"coercer",
"=",
"Coercer",
"::",
"Object",
".",
"determine_type",
"(",
"klass",
")",
"||",
"Coercer",
"::",
"Object",
"args",
"=",
"[",
"self",
"]",
"args",
"<<",
"config_for",
"(",
"coercer",
")",
"if",
"coercer",
".",
"respond_to?",
"(",
":config_name",
")",
"coercer",
".",
"new",
"(",
"args",
")",
"end",
"end"
] | Initialize a new coercer instance for the given type
If a coercer class supports configuration it will receive it from the
global configuration object
@return [Coercer::Object]
@api private | [
"Initialize",
"a",
"new",
"coercer",
"instance",
"for",
"the",
"given",
"type"
] | c076869838531abb5783280da108aa3cbddbd61a | https://github.com/solnic/coercible/blob/c076869838531abb5783280da108aa3cbddbd61a/lib/coercible/coercer.rb#L115-L123 |
23,440 | arangodb-helper/guacamole | lib/guacamole/transaction.rb | Guacamole.Transaction.write_collections | def write_collections
edge_collections.flat_map do |target_state|
[target_state.edge_collection_name] +
(target_state.from_vertices + target_state.to_vertices).map(&:collection)
end.uniq.compact
end | ruby | def write_collections
edge_collections.flat_map do |target_state|
[target_state.edge_collection_name] +
(target_state.from_vertices + target_state.to_vertices).map(&:collection)
end.uniq.compact
end | [
"def",
"write_collections",
"edge_collections",
".",
"flat_map",
"do",
"|",
"target_state",
"|",
"[",
"target_state",
".",
"edge_collection_name",
"]",
"+",
"(",
"target_state",
".",
"from_vertices",
"+",
"target_state",
".",
"to_vertices",
")",
".",
"map",
"(",
":collection",
")",
"end",
".",
"uniq",
".",
"compact",
"end"
] | A list of collections we will write to
@return [Array<String>] A list of the collection names we will write to | [
"A",
"list",
"of",
"collections",
"we",
"will",
"write",
"to"
] | 90505fc0276ea529073c0e8d1087f51f193840b6 | https://github.com/arangodb-helper/guacamole/blob/90505fc0276ea529073c0e8d1087f51f193840b6/lib/guacamole/transaction.rb#L308-L313 |
23,441 | arangodb-helper/guacamole | lib/guacamole/transaction.rb | Guacamole.Transaction.transaction | def transaction
transaction = database.create_transaction(transaction_code,
write: write_collections,
read: read_collections)
transaction.wait_for_sync = true
transaction
end | ruby | def transaction
transaction = database.create_transaction(transaction_code,
write: write_collections,
read: read_collections)
transaction.wait_for_sync = true
transaction
end | [
"def",
"transaction",
"transaction",
"=",
"database",
".",
"create_transaction",
"(",
"transaction_code",
",",
"write",
":",
"write_collections",
",",
"read",
":",
"read_collections",
")",
"transaction",
".",
"wait_for_sync",
"=",
"true",
"transaction",
"end"
] | A transaction instance from the database
return [Ashikawa::Core::Transaction] A raw transaction to execute the Transaction on the database
@api private | [
"A",
"transaction",
"instance",
"from",
"the",
"database"
] | 90505fc0276ea529073c0e8d1087f51f193840b6 | https://github.com/arangodb-helper/guacamole/blob/90505fc0276ea529073c0e8d1087f51f193840b6/lib/guacamole/transaction.rb#L352-L359 |
23,442 | tulak/pdu_tools | lib/pdu_tools/helpers.rb | PDUTools.Helpers.decode16bit | def decode16bit data, length
data.split('').in_groups_of(4).collect()
double_octets = data.split('').in_groups_of(4).map(&:join).map{|x| x.to_i(16) }[0, length / 2] # integer values
double_octets.collect do |o|
[o].pack('S')
end.join.force_encoding('utf-16le').encode('utf-8')
end | ruby | def decode16bit data, length
data.split('').in_groups_of(4).collect()
double_octets = data.split('').in_groups_of(4).map(&:join).map{|x| x.to_i(16) }[0, length / 2] # integer values
double_octets.collect do |o|
[o].pack('S')
end.join.force_encoding('utf-16le').encode('utf-8')
end | [
"def",
"decode16bit",
"data",
",",
"length",
"data",
".",
"split",
"(",
"''",
")",
".",
"in_groups_of",
"(",
"4",
")",
".",
"collect",
"(",
")",
"double_octets",
"=",
"data",
".",
"split",
"(",
"''",
")",
".",
"in_groups_of",
"(",
"4",
")",
".",
"map",
"(",
":join",
")",
".",
"map",
"{",
"|",
"x",
"|",
"x",
".",
"to_i",
"(",
"16",
")",
"}",
"[",
"0",
",",
"length",
"/",
"2",
"]",
"# integer values",
"double_octets",
".",
"collect",
"do",
"|",
"o",
"|",
"[",
"o",
"]",
".",
"pack",
"(",
"'S'",
")",
"end",
".",
"join",
".",
"force_encoding",
"(",
"'utf-16le'",
")",
".",
"encode",
"(",
"'utf-8'",
")",
"end"
] | Decodes 16bit UTF-16 string into UTF-8 string | [
"Decodes",
"16bit",
"UTF",
"-",
"16",
"string",
"into",
"UTF",
"-",
"8",
"string"
] | dd542ac0c30a32246d31613a7fb5d7e8a93dc847 | https://github.com/tulak/pdu_tools/blob/dd542ac0c30a32246d31613a7fb5d7e8a93dc847/lib/pdu_tools/helpers.rb#L118-L124 |
23,443 | arangodb-helper/guacamole | lib/guacamole/query.rb | Guacamole.Query.each | def each(&block)
return to_enum(__callee__) unless block_given?
perfom_query ->(document) { block.call mapper.document_to_model(document) }, &block
end | ruby | def each(&block)
return to_enum(__callee__) unless block_given?
perfom_query ->(document) { block.call mapper.document_to_model(document) }, &block
end | [
"def",
"each",
"(",
"&",
"block",
")",
"return",
"to_enum",
"(",
"__callee__",
")",
"unless",
"block_given?",
"perfom_query",
"->",
"(",
"document",
")",
"{",
"block",
".",
"call",
"mapper",
".",
"document_to_model",
"(",
"document",
")",
"}",
",",
"block",
"end"
] | Create a new Query
@param [Ashikawa::Core::Collection] connection The collection to use to talk to the database
@param [Class] mapper the class of the mapper to use
Iterate over the result of the query
This will execute the query you have build | [
"Create",
"a",
"new",
"Query"
] | 90505fc0276ea529073c0e8d1087f51f193840b6 | https://github.com/arangodb-helper/guacamole/blob/90505fc0276ea529073c0e8d1087f51f193840b6/lib/guacamole/query.rb#L41-L45 |
23,444 | arangodb-helper/guacamole | lib/guacamole/query.rb | Guacamole.Query.perfom_query | def perfom_query(iterator, &block)
if example
connection.by_example(example, options).each(&iterator)
else
connection.all(options).each(&iterator)
end
end | ruby | def perfom_query(iterator, &block)
if example
connection.by_example(example, options).each(&iterator)
else
connection.all(options).each(&iterator)
end
end | [
"def",
"perfom_query",
"(",
"iterator",
",",
"&",
"block",
")",
"if",
"example",
"connection",
".",
"by_example",
"(",
"example",
",",
"options",
")",
".",
"each",
"(",
"iterator",
")",
"else",
"connection",
".",
"all",
"(",
"options",
")",
".",
"each",
"(",
"iterator",
")",
"end",
"end"
] | Performs the query against the database connection.
This can be changed by subclasses to implement other types
of queries, such as AQL queries.
@param [Lambda] iterator To be called on each document returned from
the database | [
"Performs",
"the",
"query",
"against",
"the",
"database",
"connection",
"."
] | 90505fc0276ea529073c0e8d1087f51f193840b6 | https://github.com/arangodb-helper/guacamole/blob/90505fc0276ea529073c0e8d1087f51f193840b6/lib/guacamole/query.rb#L85-L91 |
23,445 | mapnik/Ruby-Mapnik | lib/ruby_mapnik/mapnik/map.rb | Mapnik.Map.style | def style(name)
style = Mapnik::Style.new
yield style
styles[name] = style
end | ruby | def style(name)
style = Mapnik::Style.new
yield style
styles[name] = style
end | [
"def",
"style",
"(",
"name",
")",
"style",
"=",
"Mapnik",
"::",
"Style",
".",
"new",
"yield",
"style",
"styles",
"[",
"name",
"]",
"=",
"style",
"end"
] | Creates and yeilds a new style object, then adds that style to the
map's collection of styles, under the name passed in. Makes no effort
to de-dupe style name collisions.
@return [Mapnik::Style] | [
"Creates",
"and",
"yeilds",
"a",
"new",
"style",
"object",
"then",
"adds",
"that",
"style",
"to",
"the",
"map",
"s",
"collection",
"of",
"styles",
"under",
"the",
"name",
"passed",
"in",
".",
"Makes",
"no",
"effort",
"to",
"de",
"-",
"dupe",
"style",
"name",
"collisions",
"."
] | 39e76e0f786fbc1e322bc115fbbaeb49c84d3bd0 | https://github.com/mapnik/Ruby-Mapnik/blob/39e76e0f786fbc1e322bc115fbbaeb49c84d3bd0/lib/ruby_mapnik/mapnik/map.rb#L117-L121 |
23,446 | mapnik/Ruby-Mapnik | lib/ruby_mapnik/mapnik/map.rb | Mapnik.Map.layer | def layer(name, srs = nil)
layer = Mapnik::Layer.new(name, srs)
layer.map = self
yield layer
layers << layer
end | ruby | def layer(name, srs = nil)
layer = Mapnik::Layer.new(name, srs)
layer.map = self
yield layer
layers << layer
end | [
"def",
"layer",
"(",
"name",
",",
"srs",
"=",
"nil",
")",
"layer",
"=",
"Mapnik",
"::",
"Layer",
".",
"new",
"(",
"name",
",",
"srs",
")",
"layer",
".",
"map",
"=",
"self",
"yield",
"layer",
"layers",
"<<",
"layer",
"end"
] | Creates and yields a new layer object, then adds that layer to the map's
collection of layers. If the srs is not provided in the initial call,
it will need to be provided in the block.
@return [Mapnik::Layer] | [
"Creates",
"and",
"yields",
"a",
"new",
"layer",
"object",
"then",
"adds",
"that",
"layer",
"to",
"the",
"map",
"s",
"collection",
"of",
"layers",
".",
"If",
"the",
"srs",
"is",
"not",
"provided",
"in",
"the",
"initial",
"call",
"it",
"will",
"need",
"to",
"be",
"provided",
"in",
"the",
"block",
"."
] | 39e76e0f786fbc1e322bc115fbbaeb49c84d3bd0 | https://github.com/mapnik/Ruby-Mapnik/blob/39e76e0f786fbc1e322bc115fbbaeb49c84d3bd0/lib/ruby_mapnik/mapnik/map.rb#L135-L140 |
23,447 | mapnik/Ruby-Mapnik | lib/ruby_mapnik/mapnik/map.rb | Mapnik.Map.render_to_file | def render_to_file(filename, format = nil)
if format
__render_to_file_with_format__(filename, format)
else
__render_to_file__(filename)
end
return File.exists?(filename)
end | ruby | def render_to_file(filename, format = nil)
if format
__render_to_file_with_format__(filename, format)
else
__render_to_file__(filename)
end
return File.exists?(filename)
end | [
"def",
"render_to_file",
"(",
"filename",
",",
"format",
"=",
"nil",
")",
"if",
"format",
"__render_to_file_with_format__",
"(",
"filename",
",",
"format",
")",
"else",
"__render_to_file__",
"(",
"filename",
")",
"end",
"return",
"File",
".",
"exists?",
"(",
"filename",
")",
"end"
] | Renders the map to a file. Returns true or false depending if the
render was successful. The image type is inferred from the filename.
@param [String] filename Should end in one of "png", "jpg", or "tiff" if format not specified
@param [String] format Should be one of formats supported by Mapnik or nil (to be guessed from filename)
@return [Boolean] | [
"Renders",
"the",
"map",
"to",
"a",
"file",
".",
"Returns",
"true",
"or",
"false",
"depending",
"if",
"the",
"render",
"was",
"successful",
".",
"The",
"image",
"type",
"is",
"inferred",
"from",
"the",
"filename",
"."
] | 39e76e0f786fbc1e322bc115fbbaeb49c84d3bd0 | https://github.com/mapnik/Ruby-Mapnik/blob/39e76e0f786fbc1e322bc115fbbaeb49c84d3bd0/lib/ruby_mapnik/mapnik/map.rb#L155-L162 |
23,448 | lardawge/rfm | lib/rfm/error.rb | Rfm.Error.getError | def getError(code, message=nil)
klass = find_by_code(code)
message = build_message(klass, code, message)
error = klass.new(code, message)
error
end | ruby | def getError(code, message=nil)
klass = find_by_code(code)
message = build_message(klass, code, message)
error = klass.new(code, message)
error
end | [
"def",
"getError",
"(",
"code",
",",
"message",
"=",
"nil",
")",
"klass",
"=",
"find_by_code",
"(",
"code",
")",
"message",
"=",
"build_message",
"(",
"klass",
",",
"code",
",",
"message",
")",
"error",
"=",
"klass",
".",
"new",
"(",
"code",
",",
"message",
")",
"error",
"end"
] | This method returns the appropriate FileMaker object depending on the error code passed to it. It
also accepts an optional message. | [
"This",
"method",
"returns",
"the",
"appropriate",
"FileMaker",
"object",
"depending",
"on",
"the",
"error",
"code",
"passed",
"to",
"it",
".",
"It",
"also",
"accepts",
"an",
"optional",
"message",
"."
] | f52601d3a6e685428be99a48397f50f3db53ae4f | https://github.com/lardawge/rfm/blob/f52601d3a6e685428be99a48397f50f3db53ae4f/lib/rfm/error.rb#L126-L131 |
23,449 | monzo/mondo-ruby | lib/mondo/client.rb | Mondo.Client.request | def request(method, path, opts = {})
raise ClientError, 'Access token missing' unless @access_token
opts[:headers] = {} if opts[:headers].nil?
opts[:headers]['Accept'] = 'application/json'
opts[:headers]['Content-Type'] = 'application/json' unless method == :get
opts[:headers]['User-Agent'] = user_agent
opts[:headers]['Authorization'] = "Bearer #{@access_token}"
if !opts[:data].nil?
opts[:body] = opts[:data].to_param
puts "SETTING BODY #{opts[:body]}"
opts[:headers]['Content-Type'] = 'application/x-www-form-urlencoded' # sob sob
end
path = URI.encode(path)
resp = connection.run_request(method, path, opts[:body], opts[:headers]) do |req|
req.params = opts[:params] if !opts[:params].nil?
end
response = Response.new(resp)
case response.status
when 301, 302, 303, 307
# TODO
when 200..299, 300..399
# on non-redirecting 3xx statuses, just return the response
response
when 400..599
error = ApiError.new(response)
raise(error, "Status code #{response.status}")
else
error = ApiError.new(response)
raise(error, "Unhandled status code value of #{response.status}")
end
end | ruby | def request(method, path, opts = {})
raise ClientError, 'Access token missing' unless @access_token
opts[:headers] = {} if opts[:headers].nil?
opts[:headers]['Accept'] = 'application/json'
opts[:headers]['Content-Type'] = 'application/json' unless method == :get
opts[:headers]['User-Agent'] = user_agent
opts[:headers]['Authorization'] = "Bearer #{@access_token}"
if !opts[:data].nil?
opts[:body] = opts[:data].to_param
puts "SETTING BODY #{opts[:body]}"
opts[:headers]['Content-Type'] = 'application/x-www-form-urlencoded' # sob sob
end
path = URI.encode(path)
resp = connection.run_request(method, path, opts[:body], opts[:headers]) do |req|
req.params = opts[:params] if !opts[:params].nil?
end
response = Response.new(resp)
case response.status
when 301, 302, 303, 307
# TODO
when 200..299, 300..399
# on non-redirecting 3xx statuses, just return the response
response
when 400..599
error = ApiError.new(response)
raise(error, "Status code #{response.status}")
else
error = ApiError.new(response)
raise(error, "Unhandled status code value of #{response.status}")
end
end | [
"def",
"request",
"(",
"method",
",",
"path",
",",
"opts",
"=",
"{",
"}",
")",
"raise",
"ClientError",
",",
"'Access token missing'",
"unless",
"@access_token",
"opts",
"[",
":headers",
"]",
"=",
"{",
"}",
"if",
"opts",
"[",
":headers",
"]",
".",
"nil?",
"opts",
"[",
":headers",
"]",
"[",
"'Accept'",
"]",
"=",
"'application/json'",
"opts",
"[",
":headers",
"]",
"[",
"'Content-Type'",
"]",
"=",
"'application/json'",
"unless",
"method",
"==",
":get",
"opts",
"[",
":headers",
"]",
"[",
"'User-Agent'",
"]",
"=",
"user_agent",
"opts",
"[",
":headers",
"]",
"[",
"'Authorization'",
"]",
"=",
"\"Bearer #{@access_token}\"",
"if",
"!",
"opts",
"[",
":data",
"]",
".",
"nil?",
"opts",
"[",
":body",
"]",
"=",
"opts",
"[",
":data",
"]",
".",
"to_param",
"puts",
"\"SETTING BODY #{opts[:body]}\"",
"opts",
"[",
":headers",
"]",
"[",
"'Content-Type'",
"]",
"=",
"'application/x-www-form-urlencoded'",
"# sob sob",
"end",
"path",
"=",
"URI",
".",
"encode",
"(",
"path",
")",
"resp",
"=",
"connection",
".",
"run_request",
"(",
"method",
",",
"path",
",",
"opts",
"[",
":body",
"]",
",",
"opts",
"[",
":headers",
"]",
")",
"do",
"|",
"req",
"|",
"req",
".",
"params",
"=",
"opts",
"[",
":params",
"]",
"if",
"!",
"opts",
"[",
":params",
"]",
".",
"nil?",
"end",
"response",
"=",
"Response",
".",
"new",
"(",
"resp",
")",
"case",
"response",
".",
"status",
"when",
"301",
",",
"302",
",",
"303",
",",
"307",
"# TODO",
"when",
"200",
"..",
"299",
",",
"300",
"..",
"399",
"# on non-redirecting 3xx statuses, just return the response",
"response",
"when",
"400",
"..",
"599",
"error",
"=",
"ApiError",
".",
"new",
"(",
"response",
")",
"raise",
"(",
"error",
",",
"\"Status code #{response.status}\"",
")",
"else",
"error",
"=",
"ApiError",
".",
"new",
"(",
"response",
")",
"raise",
"(",
"error",
",",
"\"Unhandled status code value of #{response.status}\"",
")",
"end",
"end"
] | Send a request to the Mondo API servers
@param [Symbol] method the HTTP method to use (e.g. +:get+, +:post+)
@param [String] path the path fragment of the URL
@option [Hash] opts query string parameters, headers | [
"Send",
"a",
"request",
"to",
"the",
"Mondo",
"API",
"servers"
] | 74d52e050d2cf7ccf5dd35a00795aef9e13a7fe9 | https://github.com/monzo/mondo-ruby/blob/74d52e050d2cf7ccf5dd35a00795aef9e13a7fe9/lib/mondo/client.rb#L191-L229 |
23,450 | lardawge/rfm | lib/rfm/server.rb | Rfm.Server.connect | def connect(action, args, options = {})
post = args.merge(expand_options(options)).merge({action => ''})
http_fetch("/fmi/xml/fmresultset.xml", post)
end | ruby | def connect(action, args, options = {})
post = args.merge(expand_options(options)).merge({action => ''})
http_fetch("/fmi/xml/fmresultset.xml", post)
end | [
"def",
"connect",
"(",
"action",
",",
"args",
",",
"options",
"=",
"{",
"}",
")",
"post",
"=",
"args",
".",
"merge",
"(",
"expand_options",
"(",
"options",
")",
")",
".",
"merge",
"(",
"{",
"action",
"=>",
"''",
"}",
")",
"http_fetch",
"(",
"\"/fmi/xml/fmresultset.xml\"",
",",
"post",
")",
"end"
] | Performs a raw FileMaker action. You will generally not call this method directly, but it
is exposed in case you need to do something "under the hood."
The +action+ parameter is any valid FileMaker web url action. For example, +-find+, +-finadny+ etc.
The +args+ parameter is a hash of arguments to be included in the action url. It will be serialized
and url-encoded appropriately.
The +options+ parameter is a hash of RFM-specific options, which correspond to the more esoteric
FileMaker URL parameters. They are exposed separately because they can also be passed into
various methods on the Layout object, which is a much more typical way of sending an action to
FileMaker.
This method returns the Net::HTTP response object representing the response from FileMaker.
For example, if you wanted to send a raw command to FileMaker to find the first 20 people in the
"Customers" database whose first name is "Bill" you might do this:
response = myServer.connect(
'-find',
{
"-db" => "Customers",
"-lay" => "Details",
"First Name" => "Bill"
},
{ :max_records => 20 }
) | [
"Performs",
"a",
"raw",
"FileMaker",
"action",
".",
"You",
"will",
"generally",
"not",
"call",
"this",
"method",
"directly",
"but",
"it",
"is",
"exposed",
"in",
"case",
"you",
"need",
"to",
"do",
"something",
"under",
"the",
"hood",
"."
] | f52601d3a6e685428be99a48397f50f3db53ae4f | https://github.com/lardawge/rfm/blob/f52601d3a6e685428be99a48397f50f3db53ae4f/lib/rfm/server.rb#L262-L265 |
23,451 | copycopter/copycopter-ruby-client | lib/copycopter_client/i18n_backend.rb | CopycopterClient.I18nBackend.available_locales | def available_locales
cached_locales = cache.keys.map { |key| key.split('.').first }
(cached_locales + super).uniq.map { |locale| locale.to_sym }
end | ruby | def available_locales
cached_locales = cache.keys.map { |key| key.split('.').first }
(cached_locales + super).uniq.map { |locale| locale.to_sym }
end | [
"def",
"available_locales",
"cached_locales",
"=",
"cache",
".",
"keys",
".",
"map",
"{",
"|",
"key",
"|",
"key",
".",
"split",
"(",
"'.'",
")",
".",
"first",
"}",
"(",
"cached_locales",
"+",
"super",
")",
".",
"uniq",
".",
"map",
"{",
"|",
"locale",
"|",
"locale",
".",
"to_sym",
"}",
"end"
] | Returns locales availabile for this Copycopter project.
@return [Array<String>] available locales | [
"Returns",
"locales",
"availabile",
"for",
"this",
"Copycopter",
"project",
"."
] | 9996c7fa323f7251e0668e6a47dc26dd35fed391 | https://github.com/copycopter/copycopter-ruby-client/blob/9996c7fa323f7251e0668e6a47dc26dd35fed391/lib/copycopter_client/i18n_backend.rb#L36-L39 |
23,452 | mkroman/rar | library/rar/archive.rb | RAR.Archive.create! | def create!
rar_process = IO.popen command_line
# Wait for the child rar process to finish.
_, status = Process.wait2 rar_process.pid
if status.exitstatus > 1
if message = ExitCodeMessages[status.exitstatus]
raise CommandLineError, message
else
raise CommandLineError, "Unknown exit status: #{status}"
end
else
true
end
end | ruby | def create!
rar_process = IO.popen command_line
# Wait for the child rar process to finish.
_, status = Process.wait2 rar_process.pid
if status.exitstatus > 1
if message = ExitCodeMessages[status.exitstatus]
raise CommandLineError, message
else
raise CommandLineError, "Unknown exit status: #{status}"
end
else
true
end
end | [
"def",
"create!",
"rar_process",
"=",
"IO",
".",
"popen",
"command_line",
"# Wait for the child rar process to finish.",
"_",
",",
"status",
"=",
"Process",
".",
"wait2",
"rar_process",
".",
"pid",
"if",
"status",
".",
"exitstatus",
">",
"1",
"if",
"message",
"=",
"ExitCodeMessages",
"[",
"status",
".",
"exitstatus",
"]",
"raise",
"CommandLineError",
",",
"message",
"else",
"raise",
"CommandLineError",
",",
"\"Unknown exit status: #{status}\"",
"end",
"else",
"true",
"end",
"end"
] | Create the final archive.
@return true if the command executes without a hitch.
@raise CommandLineError if the exit code indicates an error. | [
"Create",
"the",
"final",
"archive",
"."
] | aac4f055493bacf78b8a16602d8121934f7db347 | https://github.com/mkroman/rar/blob/aac4f055493bacf78b8a16602d8121934f7db347/library/rar/archive.rb#L52-L67 |
23,453 | copycopter/copycopter-ruby-client | lib/copycopter_client/client.rb | CopycopterClient.Client.upload | def upload(data)
connect do |http|
response = http.post(uri('draft_blurbs'), data.to_json, 'Content-Type' => 'application/json')
check response
log 'Uploaded missing translations'
end
end | ruby | def upload(data)
connect do |http|
response = http.post(uri('draft_blurbs'), data.to_json, 'Content-Type' => 'application/json')
check response
log 'Uploaded missing translations'
end
end | [
"def",
"upload",
"(",
"data",
")",
"connect",
"do",
"|",
"http",
"|",
"response",
"=",
"http",
".",
"post",
"(",
"uri",
"(",
"'draft_blurbs'",
")",
",",
"data",
".",
"to_json",
",",
"'Content-Type'",
"=>",
"'application/json'",
")",
"check",
"response",
"log",
"'Uploaded missing translations'",
"end",
"end"
] | Uploads the given hash of blurbs as draft content.
@param data [Hash] the blurbs to upload
@raise [ConnectionError] if the connection fails | [
"Uploads",
"the",
"given",
"hash",
"of",
"blurbs",
"as",
"draft",
"content",
"."
] | 9996c7fa323f7251e0668e6a47dc26dd35fed391 | https://github.com/copycopter/copycopter-ruby-client/blob/9996c7fa323f7251e0668e6a47dc26dd35fed391/lib/copycopter_client/client.rb#L65-L71 |
23,454 | copycopter/copycopter-ruby-client | lib/copycopter_client/client.rb | CopycopterClient.Client.deploy | def deploy
connect do |http|
response = http.post(uri('deploys'), '')
check response
log 'Deployed'
end
end | ruby | def deploy
connect do |http|
response = http.post(uri('deploys'), '')
check response
log 'Deployed'
end
end | [
"def",
"deploy",
"connect",
"do",
"|",
"http",
"|",
"response",
"=",
"http",
".",
"post",
"(",
"uri",
"(",
"'deploys'",
")",
",",
"''",
")",
"check",
"response",
"log",
"'Deployed'",
"end",
"end"
] | Issues a deploy, marking all draft content as published for this project.
@raise [ConnectionError] if the connection fails | [
"Issues",
"a",
"deploy",
"marking",
"all",
"draft",
"content",
"as",
"published",
"for",
"this",
"project",
"."
] | 9996c7fa323f7251e0668e6a47dc26dd35fed391 | https://github.com/copycopter/copycopter-ruby-client/blob/9996c7fa323f7251e0668e6a47dc26dd35fed391/lib/copycopter_client/client.rb#L75-L81 |
23,455 | nofxx/hooray | lib/hooray/seek.rb | Hooray.Seek.nodes | def nodes
return @nodes if @nodes
@nodes = sweep.map do |k, v|
Node.new(ip: k, mac: Hooray::Local.arp_table[k.to_s], ports: v)
end # .reject { |n| n.mac.nil? } # remove those without mac
end | ruby | def nodes
return @nodes if @nodes
@nodes = sweep.map do |k, v|
Node.new(ip: k, mac: Hooray::Local.arp_table[k.to_s], ports: v)
end # .reject { |n| n.mac.nil? } # remove those without mac
end | [
"def",
"nodes",
"return",
"@nodes",
"if",
"@nodes",
"@nodes",
"=",
"sweep",
".",
"map",
"do",
"|",
"k",
",",
"v",
"|",
"Node",
".",
"new",
"(",
"ip",
":",
"k",
",",
"mac",
":",
"Hooray",
"::",
"Local",
".",
"arp_table",
"[",
"k",
".",
"to_s",
"]",
",",
"ports",
":",
"v",
")",
"end",
"# .reject { |n| n.mac.nil? } # remove those without mac",
"end"
] | Map results to @nodes << Node.new() | [
"Map",
"results",
"to"
] | 31243bfbb0d69c8139e52ead5358f1c9ca3d07e3 | https://github.com/nofxx/hooray/blob/31243bfbb0d69c8139e52ead5358f1c9ca3d07e3/lib/hooray/seek.rb#L38-L43 |
23,456 | nofxx/hooray | lib/hooray/seek.rb | Hooray.Seek.ping_class | def ping_class
return Net::Ping::External unless ports
return Net::Ping::TCP unless @protocol =~ /tcp|udp|http|wmi/
Net::Ping.const_get(@protocol.upcase)
end | ruby | def ping_class
return Net::Ping::External unless ports
return Net::Ping::TCP unless @protocol =~ /tcp|udp|http|wmi/
Net::Ping.const_get(@protocol.upcase)
end | [
"def",
"ping_class",
"return",
"Net",
"::",
"Ping",
"::",
"External",
"unless",
"ports",
"return",
"Net",
"::",
"Ping",
"::",
"TCP",
"unless",
"@protocol",
"=~",
"/",
"/",
"Net",
"::",
"Ping",
".",
"const_get",
"(",
"@protocol",
".",
"upcase",
")",
"end"
] | Decide how to ping | [
"Decide",
"how",
"to",
"ping"
] | 31243bfbb0d69c8139e52ead5358f1c9ca3d07e3 | https://github.com/nofxx/hooray/blob/31243bfbb0d69c8139e52ead5358f1c9ca3d07e3/lib/hooray/seek.rb#L48-L52 |
23,457 | nofxx/hooray | lib/hooray/seek.rb | Hooray.Seek.scan_bot | def scan_bot(ip)
(ports || [nil]).each do |port|
Thread.new do
if ping_class.new(ip.to_s, port, TIMEOUT).ping?
@scan[ip] << port
print '.'
end
end
end
end | ruby | def scan_bot(ip)
(ports || [nil]).each do |port|
Thread.new do
if ping_class.new(ip.to_s, port, TIMEOUT).ping?
@scan[ip] << port
print '.'
end
end
end
end | [
"def",
"scan_bot",
"(",
"ip",
")",
"(",
"ports",
"||",
"[",
"nil",
"]",
")",
".",
"each",
"do",
"|",
"port",
"|",
"Thread",
".",
"new",
"do",
"if",
"ping_class",
".",
"new",
"(",
"ip",
".",
"to_s",
",",
"port",
",",
"TIMEOUT",
")",
".",
"ping?",
"@scan",
"[",
"ip",
"]",
"<<",
"port",
"print",
"'.'",
"end",
"end",
"end",
"end"
] | Creates a bot per port on IP | [
"Creates",
"a",
"bot",
"per",
"port",
"on",
"IP"
] | 31243bfbb0d69c8139e52ead5358f1c9ca3d07e3 | https://github.com/nofxx/hooray/blob/31243bfbb0d69c8139e52ead5358f1c9ca3d07e3/lib/hooray/seek.rb#L56-L65 |
23,458 | nofxx/hooray | lib/hooray/seek.rb | Hooray.Seek.sweep | def sweep
network.to_range.each do |ip|
@scan[ip] = []
scan_bot(ip)
end
Thread.list.reject { |t| t == Thread.current }.each(&:join)
@scan.reject! { |_k, v| v.empty? }
end | ruby | def sweep
network.to_range.each do |ip|
@scan[ip] = []
scan_bot(ip)
end
Thread.list.reject { |t| t == Thread.current }.each(&:join)
@scan.reject! { |_k, v| v.empty? }
end | [
"def",
"sweep",
"network",
".",
"to_range",
".",
"each",
"do",
"|",
"ip",
"|",
"@scan",
"[",
"ip",
"]",
"=",
"[",
"]",
"scan_bot",
"(",
"ip",
")",
"end",
"Thread",
".",
"list",
".",
"reject",
"{",
"|",
"t",
"|",
"t",
"==",
"Thread",
".",
"current",
"}",
".",
"each",
"(",
":join",
")",
"@scan",
".",
"reject!",
"{",
"|",
"_k",
",",
"v",
"|",
"v",
".",
"empty?",
"}",
"end"
] | fast -> -sn -PA | [
"fast",
"-",
">",
"-",
"sn",
"-",
"PA"
] | 31243bfbb0d69c8139e52ead5358f1c9ca3d07e3 | https://github.com/nofxx/hooray/blob/31243bfbb0d69c8139e52ead5358f1c9ca3d07e3/lib/hooray/seek.rb#L70-L77 |
23,459 | copycopter/copycopter-ruby-client | lib/copycopter_client/cache.rb | CopycopterClient.Cache.export | def export
keys = {}
lock do
@blurbs.sort.each do |(blurb_key, value)|
current = keys
yaml_keys = blurb_key.split('.')
0.upto(yaml_keys.size - 2) do |i|
key = yaml_keys[i]
# Overwrite en.key with en.sub.key
unless current[key].class == Hash
current[key] = {}
end
current = current[key]
end
current[yaml_keys.last] = value
end
end
unless keys.size < 1
keys.to_yaml
end
end | ruby | def export
keys = {}
lock do
@blurbs.sort.each do |(blurb_key, value)|
current = keys
yaml_keys = blurb_key.split('.')
0.upto(yaml_keys.size - 2) do |i|
key = yaml_keys[i]
# Overwrite en.key with en.sub.key
unless current[key].class == Hash
current[key] = {}
end
current = current[key]
end
current[yaml_keys.last] = value
end
end
unless keys.size < 1
keys.to_yaml
end
end | [
"def",
"export",
"keys",
"=",
"{",
"}",
"lock",
"do",
"@blurbs",
".",
"sort",
".",
"each",
"do",
"|",
"(",
"blurb_key",
",",
"value",
")",
"|",
"current",
"=",
"keys",
"yaml_keys",
"=",
"blurb_key",
".",
"split",
"(",
"'.'",
")",
"0",
".",
"upto",
"(",
"yaml_keys",
".",
"size",
"-",
"2",
")",
"do",
"|",
"i",
"|",
"key",
"=",
"yaml_keys",
"[",
"i",
"]",
"# Overwrite en.key with en.sub.key",
"unless",
"current",
"[",
"key",
"]",
".",
"class",
"==",
"Hash",
"current",
"[",
"key",
"]",
"=",
"{",
"}",
"end",
"current",
"=",
"current",
"[",
"key",
"]",
"end",
"current",
"[",
"yaml_keys",
".",
"last",
"]",
"=",
"value",
"end",
"end",
"unless",
"keys",
".",
"size",
"<",
"1",
"keys",
".",
"to_yaml",
"end",
"end"
] | Yaml representation of all blurbs
@return [String] yaml | [
"Yaml",
"representation",
"of",
"all",
"blurbs"
] | 9996c7fa323f7251e0668e6a47dc26dd35fed391 | https://github.com/copycopter/copycopter-ruby-client/blob/9996c7fa323f7251e0668e6a47dc26dd35fed391/lib/copycopter_client/cache.rb#L48-L73 |
23,460 | copycopter/copycopter-ruby-client | lib/copycopter_client/cache.rb | CopycopterClient.Cache.wait_for_download | def wait_for_download
if pending?
logger.info 'Waiting for first download'
if logger.respond_to? :flush
logger.flush
end
while pending?
sleep 0.1
end
end
end | ruby | def wait_for_download
if pending?
logger.info 'Waiting for first download'
if logger.respond_to? :flush
logger.flush
end
while pending?
sleep 0.1
end
end
end | [
"def",
"wait_for_download",
"if",
"pending?",
"logger",
".",
"info",
"'Waiting for first download'",
"if",
"logger",
".",
"respond_to?",
":flush",
"logger",
".",
"flush",
"end",
"while",
"pending?",
"sleep",
"0.1",
"end",
"end",
"end"
] | Waits until the first download has finished. | [
"Waits",
"until",
"the",
"first",
"download",
"has",
"finished",
"."
] | 9996c7fa323f7251e0668e6a47dc26dd35fed391 | https://github.com/copycopter/copycopter-ruby-client/blob/9996c7fa323f7251e0668e6a47dc26dd35fed391/lib/copycopter_client/cache.rb#L76-L88 |
23,461 | ryantate/rturk | lib/rturk/operations/register_hit_type.rb | RTurk.RegisterHITType.validate | def validate
missing_parameters = []
required_fields.each do |param|
missing_parameters << param.to_s unless self.send(param)
end
raise RTurk::MissingParameters, "Parameters: '#{missing_parameters.join(', ')}'" unless missing_parameters.empty?
end | ruby | def validate
missing_parameters = []
required_fields.each do |param|
missing_parameters << param.to_s unless self.send(param)
end
raise RTurk::MissingParameters, "Parameters: '#{missing_parameters.join(', ')}'" unless missing_parameters.empty?
end | [
"def",
"validate",
"missing_parameters",
"=",
"[",
"]",
"required_fields",
".",
"each",
"do",
"|",
"param",
"|",
"missing_parameters",
"<<",
"param",
".",
"to_s",
"unless",
"self",
".",
"send",
"(",
"param",
")",
"end",
"raise",
"RTurk",
"::",
"MissingParameters",
",",
"\"Parameters: '#{missing_parameters.join(', ')}'\"",
"unless",
"missing_parameters",
".",
"empty?",
"end"
] | More complicated validation run before request | [
"More",
"complicated",
"validation",
"run",
"before",
"request"
] | d98daab65a0049472d632ffda45e350f5845938d | https://github.com/ryantate/rturk/blob/d98daab65a0049472d632ffda45e350f5845938d/lib/rturk/operations/register_hit_type.rb#L32-L38 |
23,462 | pluginaweek/table_helper | lib/table_helper/collection_table.rb | TableHelper.CollectionTable.default_class | def default_class
if collection.respond_to?(:proxy_reflection)
collection.proxy_reflection.klass
elsif !collection.empty?
collection.first.class
end
end | ruby | def default_class
if collection.respond_to?(:proxy_reflection)
collection.proxy_reflection.klass
elsif !collection.empty?
collection.first.class
end
end | [
"def",
"default_class",
"if",
"collection",
".",
"respond_to?",
"(",
":proxy_reflection",
")",
"collection",
".",
"proxy_reflection",
".",
"klass",
"elsif",
"!",
"collection",
".",
"empty?",
"collection",
".",
"first",
".",
"class",
"end",
"end"
] | Finds the class representing the objects within the collection | [
"Finds",
"the",
"class",
"representing",
"the",
"objects",
"within",
"the",
"collection"
] | 8456c014f919b344b4bf6261b7eab055d888d945 | https://github.com/pluginaweek/table_helper/blob/8456c014f919b344b4bf6261b7eab055d888d945/lib/table_helper/collection_table.rb#L118-L124 |
23,463 | pluginaweek/table_helper | lib/table_helper/row.rb | TableHelper.RowBuilder.undef_cell | def undef_cell(name)
method_name = name.gsub('-', '_')
klass = class << self; self; end
klass.class_eval do
remove_method(method_name)
end
end | ruby | def undef_cell(name)
method_name = name.gsub('-', '_')
klass = class << self; self; end
klass.class_eval do
remove_method(method_name)
end
end | [
"def",
"undef_cell",
"(",
"name",
")",
"method_name",
"=",
"name",
".",
"gsub",
"(",
"'-'",
",",
"'_'",
")",
"klass",
"=",
"class",
"<<",
"self",
";",
"self",
";",
"end",
"klass",
".",
"class_eval",
"do",
"remove_method",
"(",
"method_name",
")",
"end",
"end"
] | Removes the definition for the given cell | [
"Removes",
"the",
"definition",
"for",
"the",
"given",
"cell"
] | 8456c014f919b344b4bf6261b7eab055d888d945 | https://github.com/pluginaweek/table_helper/blob/8456c014f919b344b4bf6261b7eab055d888d945/lib/table_helper/row.rb#L40-L47 |
23,464 | pluginaweek/table_helper | lib/table_helper/row.rb | TableHelper.Row.cell | def cell(name, *args)
name = name.to_s if name
options = args.last.is_a?(Hash) ? args.pop : {}
options[:namespace] = table.object_name
args << options
cell = Cell.new(name, *args)
cells[name] = cell
builder.define_cell(name) if name
cell
end | ruby | def cell(name, *args)
name = name.to_s if name
options = args.last.is_a?(Hash) ? args.pop : {}
options[:namespace] = table.object_name
args << options
cell = Cell.new(name, *args)
cells[name] = cell
builder.define_cell(name) if name
cell
end | [
"def",
"cell",
"(",
"name",
",",
"*",
"args",
")",
"name",
"=",
"name",
".",
"to_s",
"if",
"name",
"options",
"=",
"args",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"args",
".",
"pop",
":",
"{",
"}",
"options",
"[",
":namespace",
"]",
"=",
"table",
".",
"object_name",
"args",
"<<",
"options",
"cell",
"=",
"Cell",
".",
"new",
"(",
"name",
",",
"args",
")",
"cells",
"[",
"name",
"]",
"=",
"cell",
"builder",
".",
"define_cell",
"(",
"name",
")",
"if",
"name",
"cell",
"end"
] | Creates a new cell with the given name and generates shortcut
accessors for the method. | [
"Creates",
"a",
"new",
"cell",
"with",
"the",
"given",
"name",
"and",
"generates",
"shortcut",
"accessors",
"for",
"the",
"method",
"."
] | 8456c014f919b344b4bf6261b7eab055d888d945 | https://github.com/pluginaweek/table_helper/blob/8456c014f919b344b4bf6261b7eab055d888d945/lib/table_helper/row.rb#L75-L87 |
23,465 | pluginaweek/table_helper | lib/table_helper/header.rb | TableHelper.Header.column | def column(*names)
# Clear the header row if this is being customized by the user
unless @customized
@customized = true
clear
end
# Extract configuration
options = names.last.is_a?(Hash) ? names.pop : {}
content = names.last.is_a?(String) ? names.pop : nil
args = [content, options].compact
names.collect! do |name|
column = row.cell(name, *args)
column.content_type = :header
column[:scope] ||= 'col'
column
end
names.length == 1 ? names.first : names
end | ruby | def column(*names)
# Clear the header row if this is being customized by the user
unless @customized
@customized = true
clear
end
# Extract configuration
options = names.last.is_a?(Hash) ? names.pop : {}
content = names.last.is_a?(String) ? names.pop : nil
args = [content, options].compact
names.collect! do |name|
column = row.cell(name, *args)
column.content_type = :header
column[:scope] ||= 'col'
column
end
names.length == 1 ? names.first : names
end | [
"def",
"column",
"(",
"*",
"names",
")",
"# Clear the header row if this is being customized by the user",
"unless",
"@customized",
"@customized",
"=",
"true",
"clear",
"end",
"# Extract configuration",
"options",
"=",
"names",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"names",
".",
"pop",
":",
"{",
"}",
"content",
"=",
"names",
".",
"last",
".",
"is_a?",
"(",
"String",
")",
"?",
"names",
".",
"pop",
":",
"nil",
"args",
"=",
"[",
"content",
",",
"options",
"]",
".",
"compact",
"names",
".",
"collect!",
"do",
"|",
"name",
"|",
"column",
"=",
"row",
".",
"cell",
"(",
"name",
",",
"args",
")",
"column",
".",
"content_type",
"=",
":header",
"column",
"[",
":scope",
"]",
"||=",
"'col'",
"column",
"end",
"names",
".",
"length",
"==",
"1",
"?",
"names",
".",
"first",
":",
"names",
"end"
] | Creates one or more to columns in the header. This will clear any
pre-existing columns if it is being customized for the first time after
it was initially created. | [
"Creates",
"one",
"or",
"more",
"to",
"columns",
"in",
"the",
"header",
".",
"This",
"will",
"clear",
"any",
"pre",
"-",
"existing",
"columns",
"if",
"it",
"is",
"being",
"customized",
"for",
"the",
"first",
"time",
"after",
"it",
"was",
"initially",
"created",
"."
] | 8456c014f919b344b4bf6261b7eab055d888d945 | https://github.com/pluginaweek/table_helper/blob/8456c014f919b344b4bf6261b7eab055d888d945/lib/table_helper/header.rb#L70-L90 |
23,466 | pluginaweek/table_helper | lib/table_helper/header.rb | TableHelper.Header.html | def html
html_options = @html_options.dup
html_options[:style] = 'display: none;' if table.empty? && hide_when_empty
content_tag(tag_name, content, html_options)
end | ruby | def html
html_options = @html_options.dup
html_options[:style] = 'display: none;' if table.empty? && hide_when_empty
content_tag(tag_name, content, html_options)
end | [
"def",
"html",
"html_options",
"=",
"@html_options",
".",
"dup",
"html_options",
"[",
":style",
"]",
"=",
"'display: none;'",
"if",
"table",
".",
"empty?",
"&&",
"hide_when_empty",
"content_tag",
"(",
"tag_name",
",",
"content",
",",
"html_options",
")",
"end"
] | Creates and returns the generated html for the header | [
"Creates",
"and",
"returns",
"the",
"generated",
"html",
"for",
"the",
"header"
] | 8456c014f919b344b4bf6261b7eab055d888d945 | https://github.com/pluginaweek/table_helper/blob/8456c014f919b344b4bf6261b7eab055d888d945/lib/table_helper/header.rb#L93-L98 |
23,467 | Lax/aliyun | lib/aliyun/common.rb | Aliyun.Service.gen_request_parameters | def gen_request_parameters method, params
#add common parameters
params.merge! self.service.default_parameters
params.merge! self.options
params[:Action] = method.to_s
params[:Timestamp] = Time.now.utc.iso8601
params[:SignatureNonce] = SecureRandom.uuid
params[:Signature] = compute_signature params
params
end | ruby | def gen_request_parameters method, params
#add common parameters
params.merge! self.service.default_parameters
params.merge! self.options
params[:Action] = method.to_s
params[:Timestamp] = Time.now.utc.iso8601
params[:SignatureNonce] = SecureRandom.uuid
params[:Signature] = compute_signature params
params
end | [
"def",
"gen_request_parameters",
"method",
",",
"params",
"#add common parameters",
"params",
".",
"merge!",
"self",
".",
"service",
".",
"default_parameters",
"params",
".",
"merge!",
"self",
".",
"options",
"params",
"[",
":Action",
"]",
"=",
"method",
".",
"to_s",
"params",
"[",
":Timestamp",
"]",
"=",
"Time",
".",
"now",
".",
"utc",
".",
"iso8601",
"params",
"[",
":SignatureNonce",
"]",
"=",
"SecureRandom",
".",
"uuid",
"params",
"[",
":Signature",
"]",
"=",
"compute_signature",
"params",
"params",
"end"
] | generate the parameters | [
"generate",
"the",
"parameters"
] | abbc3dd3a3ca5e1514d5994965d87d590b714301 | https://github.com/Lax/aliyun/blob/abbc3dd3a3ca5e1514d5994965d87d590b714301/lib/aliyun/common.rb#L65-L77 |
23,468 | Lax/aliyun | lib/aliyun/common.rb | Aliyun.Service.compute_signature | def compute_signature params
if $DEBUG
puts "keys before sorted: #{params.keys}"
end
sorted_keys = params.keys.sort
if $DEBUG
puts "keys after sorted: #{sorted_keys}"
end
canonicalized_query_string = ""
canonicalized_query_string = sorted_keys.map {|key|
"%s=%s" % [safe_encode(key.to_s), safe_encode(params[key])]
}.join(self.service.separator)
length = canonicalized_query_string.length
string_to_sign = self.service.http_method + self.service.separator + safe_encode('/') + self.service.separator + safe_encode(canonicalized_query_string)
if $DEBUG
puts "string_to_sign is #{string_to_sign}"
end
signature = calculate_signature access_key_secret+"&", string_to_sign
end | ruby | def compute_signature params
if $DEBUG
puts "keys before sorted: #{params.keys}"
end
sorted_keys = params.keys.sort
if $DEBUG
puts "keys after sorted: #{sorted_keys}"
end
canonicalized_query_string = ""
canonicalized_query_string = sorted_keys.map {|key|
"%s=%s" % [safe_encode(key.to_s), safe_encode(params[key])]
}.join(self.service.separator)
length = canonicalized_query_string.length
string_to_sign = self.service.http_method + self.service.separator + safe_encode('/') + self.service.separator + safe_encode(canonicalized_query_string)
if $DEBUG
puts "string_to_sign is #{string_to_sign}"
end
signature = calculate_signature access_key_secret+"&", string_to_sign
end | [
"def",
"compute_signature",
"params",
"if",
"$DEBUG",
"puts",
"\"keys before sorted: #{params.keys}\"",
"end",
"sorted_keys",
"=",
"params",
".",
"keys",
".",
"sort",
"if",
"$DEBUG",
"puts",
"\"keys after sorted: #{sorted_keys}\"",
"end",
"canonicalized_query_string",
"=",
"\"\"",
"canonicalized_query_string",
"=",
"sorted_keys",
".",
"map",
"{",
"|",
"key",
"|",
"\"%s=%s\"",
"%",
"[",
"safe_encode",
"(",
"key",
".",
"to_s",
")",
",",
"safe_encode",
"(",
"params",
"[",
"key",
"]",
")",
"]",
"}",
".",
"join",
"(",
"self",
".",
"service",
".",
"separator",
")",
"length",
"=",
"canonicalized_query_string",
".",
"length",
"string_to_sign",
"=",
"self",
".",
"service",
".",
"http_method",
"+",
"self",
".",
"service",
".",
"separator",
"+",
"safe_encode",
"(",
"'/'",
")",
"+",
"self",
".",
"service",
".",
"separator",
"+",
"safe_encode",
"(",
"canonicalized_query_string",
")",
"if",
"$DEBUG",
"puts",
"\"string_to_sign is #{string_to_sign}\"",
"end",
"signature",
"=",
"calculate_signature",
"access_key_secret",
"+",
"\"&\"",
",",
"string_to_sign",
"end"
] | compute the signature of the parameters String | [
"compute",
"the",
"signature",
"of",
"the",
"parameters",
"String"
] | abbc3dd3a3ca5e1514d5994965d87d590b714301 | https://github.com/Lax/aliyun/blob/abbc3dd3a3ca5e1514d5994965d87d590b714301/lib/aliyun/common.rb#L80-L106 |
23,469 | Lax/aliyun | lib/aliyun/common.rb | Aliyun.Service.calculate_signature | def calculate_signature key, string_to_sign
hmac = HMAC::SHA1.new(key)
hmac.update(string_to_sign)
signature = Base64.encode64(hmac.digest).gsub("\n", '')
if $DEBUG
puts "Signature #{signature}"
end
signature
end | ruby | def calculate_signature key, string_to_sign
hmac = HMAC::SHA1.new(key)
hmac.update(string_to_sign)
signature = Base64.encode64(hmac.digest).gsub("\n", '')
if $DEBUG
puts "Signature #{signature}"
end
signature
end | [
"def",
"calculate_signature",
"key",
",",
"string_to_sign",
"hmac",
"=",
"HMAC",
"::",
"SHA1",
".",
"new",
"(",
"key",
")",
"hmac",
".",
"update",
"(",
"string_to_sign",
")",
"signature",
"=",
"Base64",
".",
"encode64",
"(",
"hmac",
".",
"digest",
")",
".",
"gsub",
"(",
"\"\\n\"",
",",
"''",
")",
"if",
"$DEBUG",
"puts",
"\"Signature #{signature}\"",
"end",
"signature",
"end"
] | calculate the signature | [
"calculate",
"the",
"signature"
] | abbc3dd3a3ca5e1514d5994965d87d590b714301 | https://github.com/Lax/aliyun/blob/abbc3dd3a3ca5e1514d5994965d87d590b714301/lib/aliyun/common.rb#L109-L117 |
23,470 | nofxx/subtitle_it | lib/subtitle_it/subtitle.rb | SubtitleIt.Subtitle.encode_dump | def encode_dump(dump)
dump = dump.read unless dump.is_a?(String)
enc = CharlockHolmes::EncodingDetector.detect(dump)
if enc[:encoding] != 'UTF-8'
puts "Converting `#{enc[:encoding]}` to `UTF-8`".yellow
dump = CharlockHolmes::Converter.convert dump, enc[:encoding], 'UTF-8'
end
dump
end | ruby | def encode_dump(dump)
dump = dump.read unless dump.is_a?(String)
enc = CharlockHolmes::EncodingDetector.detect(dump)
if enc[:encoding] != 'UTF-8'
puts "Converting `#{enc[:encoding]}` to `UTF-8`".yellow
dump = CharlockHolmes::Converter.convert dump, enc[:encoding], 'UTF-8'
end
dump
end | [
"def",
"encode_dump",
"(",
"dump",
")",
"dump",
"=",
"dump",
".",
"read",
"unless",
"dump",
".",
"is_a?",
"(",
"String",
")",
"enc",
"=",
"CharlockHolmes",
"::",
"EncodingDetector",
".",
"detect",
"(",
"dump",
")",
"if",
"enc",
"[",
":encoding",
"]",
"!=",
"'UTF-8'",
"puts",
"\"Converting `#{enc[:encoding]}` to `UTF-8`\"",
".",
"yellow",
"dump",
"=",
"CharlockHolmes",
"::",
"Converter",
".",
"convert",
"dump",
",",
"enc",
"[",
":encoding",
"]",
",",
"'UTF-8'",
"end",
"dump",
"end"
] | Force subtitles to be UTF-8 | [
"Force",
"subtitles",
"to",
"be",
"UTF",
"-",
"8"
] | 21ba59f4ebd860b1c9127f60eed9e0d3077f1bca | https://github.com/nofxx/subtitle_it/blob/21ba59f4ebd860b1c9127f60eed9e0d3077f1bca/lib/subtitle_it/subtitle.rb#L66-L75 |
23,471 | BlockScore/blockscore-ruby | lib/blockscore/collection.rb | BlockScore.Collection.create | def create(params = {})
fail Error, 'Create parent first' unless parent.id
assoc_params = default_params.merge(params)
add_instance(member_class.create(assoc_params))
end | ruby | def create(params = {})
fail Error, 'Create parent first' unless parent.id
assoc_params = default_params.merge(params)
add_instance(member_class.create(assoc_params))
end | [
"def",
"create",
"(",
"params",
"=",
"{",
"}",
")",
"fail",
"Error",
",",
"'Create parent first'",
"unless",
"parent",
".",
"id",
"assoc_params",
"=",
"default_params",
".",
"merge",
"(",
"params",
")",
"add_instance",
"(",
"member_class",
".",
"create",
"(",
"assoc_params",
")",
")",
"end"
] | Initialize a collection member and save it
@example
>> person.question_sets.create
=> #<BlockScore::QuestionSet:0x3fc67a6007f4 JSON:{
"object": "question_set",
"id": "55ef5d5b62386200030001b3",
"created_at": 1441750363,
...
}
@param params [Hash] params
@return new saved instance of {member_class}
@api public | [
"Initialize",
"a",
"collection",
"member",
"and",
"save",
"it"
] | 3f837729f9997d92468966e4478ea2f4aaea0156 | https://github.com/BlockScore/blockscore-ruby/blob/3f837729f9997d92468966e4478ea2f4aaea0156/lib/blockscore/collection.rb#L113-L118 |
23,472 | BlockScore/blockscore-ruby | lib/blockscore/collection.rb | BlockScore.Collection.retrieve | def retrieve(id)
each do |item|
return item if item.id.eql?(id)
end
add_instance(member_class.retrieve(id))
end | ruby | def retrieve(id)
each do |item|
return item if item.id.eql?(id)
end
add_instance(member_class.retrieve(id))
end | [
"def",
"retrieve",
"(",
"id",
")",
"each",
"do",
"|",
"item",
"|",
"return",
"item",
"if",
"item",
".",
"id",
".",
"eql?",
"(",
"id",
")",
"end",
"add_instance",
"(",
"member_class",
".",
"retrieve",
"(",
"id",
")",
")",
"end"
] | Retrieve a collection member by its id
@example usage
person.question_sets.retrieve('55ef5b4e3532630003000178')
=> instance of QuestionSet
@param id [String] resource id
@return instance of {member_class} if found
@raise [BlockScore::NotFoundError] otherwise
@api public | [
"Retrieve",
"a",
"collection",
"member",
"by",
"its",
"id"
] | 3f837729f9997d92468966e4478ea2f4aaea0156 | https://github.com/BlockScore/blockscore-ruby/blob/3f837729f9997d92468966e4478ea2f4aaea0156/lib/blockscore/collection.rb#L132-L138 |
23,473 | BlockScore/blockscore-ruby | lib/blockscore/collection.rb | BlockScore.Collection.parent_id? | def parent_id?(item)
parent.id && item.send(foreign_key).eql?(parent.id)
end | ruby | def parent_id?(item)
parent.id && item.send(foreign_key).eql?(parent.id)
end | [
"def",
"parent_id?",
"(",
"item",
")",
"parent",
".",
"id",
"&&",
"item",
".",
"send",
"(",
"foreign_key",
")",
".",
"eql?",
"(",
"parent",
".",
"id",
")",
"end"
] | Check if `parent_id` is defined on `item`
@param item [BlockScore::Base] any resource
@return [Boolean]
@api private | [
"Check",
"if",
"parent_id",
"is",
"defined",
"on",
"item"
] | 3f837729f9997d92468966e4478ea2f4aaea0156 | https://github.com/BlockScore/blockscore-ruby/blob/3f837729f9997d92468966e4478ea2f4aaea0156/lib/blockscore/collection.rb#L194-L196 |
23,474 | BlockScore/blockscore-ruby | lib/blockscore/collection.rb | BlockScore.Collection.register_to_parent | def register_to_parent(item)
fail Error, 'None belonging' unless parent_id?(item)
ids << item.id
self << item
item
end | ruby | def register_to_parent(item)
fail Error, 'None belonging' unless parent_id?(item)
ids << item.id
self << item
item
end | [
"def",
"register_to_parent",
"(",
"item",
")",
"fail",
"Error",
",",
"'None belonging'",
"unless",
"parent_id?",
"(",
"item",
")",
"ids",
"<<",
"item",
".",
"id",
"self",
"<<",
"item",
"item",
"end"
] | Register a resource in collection
@param item [BlockScore::Base] a resource
@raise [BlockScore::Error] if no `parent_id`
@return [BlockScore::Base] otherwise
@api private | [
"Register",
"a",
"resource",
"in",
"collection"
] | 3f837729f9997d92468966e4478ea2f4aaea0156 | https://github.com/BlockScore/blockscore-ruby/blob/3f837729f9997d92468966e4478ea2f4aaea0156/lib/blockscore/collection.rb#L206-L211 |
23,475 | pluginaweek/table_helper | lib/table_helper/body.rb | TableHelper.Body.build_row | def build_row(object, index = table.collection.index(object))
row = BodyRow.new(object, self)
row.alternate = alternate ? index.send("#{alternate}?") : false
@builder.call(row.builder, object, index) if @builder
row.html
end | ruby | def build_row(object, index = table.collection.index(object))
row = BodyRow.new(object, self)
row.alternate = alternate ? index.send("#{alternate}?") : false
@builder.call(row.builder, object, index) if @builder
row.html
end | [
"def",
"build_row",
"(",
"object",
",",
"index",
"=",
"table",
".",
"collection",
".",
"index",
"(",
"object",
")",
")",
"row",
"=",
"BodyRow",
".",
"new",
"(",
"object",
",",
"self",
")",
"row",
".",
"alternate",
"=",
"alternate",
"?",
"index",
".",
"send",
"(",
"\"#{alternate}?\"",
")",
":",
"false",
"@builder",
".",
"call",
"(",
"row",
".",
"builder",
",",
"object",
",",
"index",
")",
"if",
"@builder",
"row",
".",
"html",
"end"
] | Builds a row for an object in the table.
The provided block should set the values for each cell in the row. | [
"Builds",
"a",
"row",
"for",
"an",
"object",
"in",
"the",
"table",
"."
] | 8456c014f919b344b4bf6261b7eab055d888d945 | https://github.com/pluginaweek/table_helper/blob/8456c014f919b344b4bf6261b7eab055d888d945/lib/table_helper/body.rb#L79-L84 |
23,476 | kanevk/poker-engine | lib/poker_engine/cards.rb | PokerEngine.Cards.values_desc_by_occurency | def values_desc_by_occurency
values = cards.map(&:value)
values.sort do |a, b|
coefficient_occurency = (values.count(a) <=> values.count(b))
coefficient_occurency.zero? ? -(a <=> b) : -coefficient_occurency
end
end | ruby | def values_desc_by_occurency
values = cards.map(&:value)
values.sort do |a, b|
coefficient_occurency = (values.count(a) <=> values.count(b))
coefficient_occurency.zero? ? -(a <=> b) : -coefficient_occurency
end
end | [
"def",
"values_desc_by_occurency",
"values",
"=",
"cards",
".",
"map",
"(",
":value",
")",
"values",
".",
"sort",
"do",
"|",
"a",
",",
"b",
"|",
"coefficient_occurency",
"=",
"(",
"values",
".",
"count",
"(",
"a",
")",
"<=>",
"values",
".",
"count",
"(",
"b",
")",
")",
"coefficient_occurency",
".",
"zero?",
"?",
"-",
"(",
"a",
"<=>",
"b",
")",
":",
"-",
"coefficient_occurency",
"end",
"end"
] | Make descending order primary by occurency and secondary by value | [
"Make",
"descending",
"order",
"primary",
"by",
"occurency",
"and",
"secondary",
"by",
"value"
] | 83a4fbf459281225df074f276efe6fb123bb8d69 | https://github.com/kanevk/poker-engine/blob/83a4fbf459281225df074f276efe6fb123bb8d69/lib/poker_engine/cards.rb#L54-L62 |
23,477 | pluginaweek/table_helper | lib/table_helper/body_row.rb | TableHelper.BodyRow.content | def content
number_to_skip = 0 # Keeps track of the # of columns to skip
html = ''
table.header.column_names.each do |column|
number_to_skip -= 1 and next if number_to_skip > 0
if cell = @cells[column]
number_to_skip = (cell[:colspan] || 1) - 1
else
cell = Cell.new(column, nil)
end
html << cell.html
end
html
end | ruby | def content
number_to_skip = 0 # Keeps track of the # of columns to skip
html = ''
table.header.column_names.each do |column|
number_to_skip -= 1 and next if number_to_skip > 0
if cell = @cells[column]
number_to_skip = (cell[:colspan] || 1) - 1
else
cell = Cell.new(column, nil)
end
html << cell.html
end
html
end | [
"def",
"content",
"number_to_skip",
"=",
"0",
"# Keeps track of the # of columns to skip",
"html",
"=",
"''",
"table",
".",
"header",
".",
"column_names",
".",
"each",
"do",
"|",
"column",
"|",
"number_to_skip",
"-=",
"1",
"and",
"next",
"if",
"number_to_skip",
">",
"0",
"if",
"cell",
"=",
"@cells",
"[",
"column",
"]",
"number_to_skip",
"=",
"(",
"cell",
"[",
":colspan",
"]",
"||",
"1",
")",
"-",
"1",
"else",
"cell",
"=",
"Cell",
".",
"new",
"(",
"column",
",",
"nil",
")",
"end",
"html",
"<<",
"cell",
".",
"html",
"end",
"html",
"end"
] | Builds the row's cells based on the order of the columns in the
header. If a cell cannot be found for a specific column, then a blank
cell is rendered. | [
"Builds",
"the",
"row",
"s",
"cells",
"based",
"on",
"the",
"order",
"of",
"the",
"columns",
"in",
"the",
"header",
".",
"If",
"a",
"cell",
"cannot",
"be",
"found",
"for",
"a",
"specific",
"column",
"then",
"a",
"blank",
"cell",
"is",
"rendered",
"."
] | 8456c014f919b344b4bf6261b7eab055d888d945 | https://github.com/pluginaweek/table_helper/blob/8456c014f919b344b4bf6261b7eab055d888d945/lib/table_helper/body_row.rb#L55-L72 |
23,478 | puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.kill_instances | def kill_instances(instances)
running_instances = instances.compact.select do |instance|
instance_by_id(instance.instance_id).state.name == 'running'
end
instance_ids = running_instances.map(&:instance_id)
return nil if instance_ids.empty?
@logger.notify("aws-sdk: killing EC2 instance(s) #{instance_ids.join(', ')}")
client.terminate_instances(:instance_ids => instance_ids)
nil
end | ruby | def kill_instances(instances)
running_instances = instances.compact.select do |instance|
instance_by_id(instance.instance_id).state.name == 'running'
end
instance_ids = running_instances.map(&:instance_id)
return nil if instance_ids.empty?
@logger.notify("aws-sdk: killing EC2 instance(s) #{instance_ids.join(', ')}")
client.terminate_instances(:instance_ids => instance_ids)
nil
end | [
"def",
"kill_instances",
"(",
"instances",
")",
"running_instances",
"=",
"instances",
".",
"compact",
".",
"select",
"do",
"|",
"instance",
"|",
"instance_by_id",
"(",
"instance",
".",
"instance_id",
")",
".",
"state",
".",
"name",
"==",
"'running'",
"end",
"instance_ids",
"=",
"running_instances",
".",
"map",
"(",
":instance_id",
")",
"return",
"nil",
"if",
"instance_ids",
".",
"empty?",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: killing EC2 instance(s) #{instance_ids.join(', ')}\"",
")",
"client",
".",
"terminate_instances",
"(",
":instance_ids",
"=>",
"instance_ids",
")",
"nil",
"end"
] | Kill all instances.
@param instances [Enumerable<Aws::EC2::Types::Instance>]
@return [void] | [
"Kill",
"all",
"instances",
"."
] | f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L106-L118 |
23,479 | puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.kill_zombie_volumes | def kill_zombie_volumes
# Occasionaly, tearing down ec2 instances leaves orphaned EBS volumes behind -- these stack up quickly.
# This simply looks for EBS volumes that are not in use
@logger.notify("aws-sdk: Kill Zombie Volumes!")
volume_count = 0
regions.each do |region|
@logger.debug "Reviewing: #{region}"
available_volumes = client(region).describe_volumes(
:filters => [
{ :name => 'status', :values => ['available'], }
]
).volumes
available_volumes.each do |volume|
begin
client(region).delete_volume(:volume_id => volume.id)
volume_count += 1
rescue Aws::EC2::Errors::InvalidVolume::NotFound => e
@logger.debug "Failed to remove volume: #{volume.id} #{e}"
end
end
end
@logger.notify "Freed #{volume_count} volume(s)"
end | ruby | def kill_zombie_volumes
# Occasionaly, tearing down ec2 instances leaves orphaned EBS volumes behind -- these stack up quickly.
# This simply looks for EBS volumes that are not in use
@logger.notify("aws-sdk: Kill Zombie Volumes!")
volume_count = 0
regions.each do |region|
@logger.debug "Reviewing: #{region}"
available_volumes = client(region).describe_volumes(
:filters => [
{ :name => 'status', :values => ['available'], }
]
).volumes
available_volumes.each do |volume|
begin
client(region).delete_volume(:volume_id => volume.id)
volume_count += 1
rescue Aws::EC2::Errors::InvalidVolume::NotFound => e
@logger.debug "Failed to remove volume: #{volume.id} #{e}"
end
end
end
@logger.notify "Freed #{volume_count} volume(s)"
end | [
"def",
"kill_zombie_volumes",
"# Occasionaly, tearing down ec2 instances leaves orphaned EBS volumes behind -- these stack up quickly.",
"# This simply looks for EBS volumes that are not in use",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: Kill Zombie Volumes!\"",
")",
"volume_count",
"=",
"0",
"regions",
".",
"each",
"do",
"|",
"region",
"|",
"@logger",
".",
"debug",
"\"Reviewing: #{region}\"",
"available_volumes",
"=",
"client",
"(",
"region",
")",
".",
"describe_volumes",
"(",
":filters",
"=>",
"[",
"{",
":name",
"=>",
"'status'",
",",
":values",
"=>",
"[",
"'available'",
"]",
",",
"}",
"]",
")",
".",
"volumes",
"available_volumes",
".",
"each",
"do",
"|",
"volume",
"|",
"begin",
"client",
"(",
"region",
")",
".",
"delete_volume",
"(",
":volume_id",
"=>",
"volume",
".",
"id",
")",
"volume_count",
"+=",
"1",
"rescue",
"Aws",
"::",
"EC2",
"::",
"Errors",
"::",
"InvalidVolume",
"::",
"NotFound",
"=>",
"e",
"@logger",
".",
"debug",
"\"Failed to remove volume: #{volume.id} #{e}\"",
"end",
"end",
"end",
"@logger",
".",
"notify",
"\"Freed #{volume_count} volume(s)\"",
"end"
] | Destroy any volumes marked 'available', INCLUDING THOSE YOU DON'T OWN! Use with care. | [
"Destroy",
"any",
"volumes",
"marked",
"available",
"INCLUDING",
"THOSE",
"YOU",
"DON",
"T",
"OWN!",
"Use",
"with",
"care",
"."
] | f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L241-L266 |
23,480 | puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.launch_all_nodes | def launch_all_nodes
@logger.notify("aws-sdk: launch all hosts in configuration")
ami_spec = YAML.load_file(@options[:ec2_yaml])["AMI"]
global_subnet_id = @options['subnet_id']
global_subnets = @options['subnet_ids']
if global_subnet_id and global_subnets
raise RuntimeError, 'Config specifies both subnet_id and subnet_ids'
end
no_subnet_hosts = []
specific_subnet_hosts = []
some_subnet_hosts = []
@hosts.each do |host|
if global_subnet_id or host['subnet_id']
specific_subnet_hosts.push(host)
elsif global_subnets
some_subnet_hosts.push(host)
else
no_subnet_hosts.push(host)
end
end
instances = [] # Each element is {:instance => i, :host => h}
begin
@logger.notify("aws-sdk: launch instances not particular about subnet")
launch_nodes_on_some_subnet(some_subnet_hosts, global_subnets, ami_spec,
instances)
@logger.notify("aws-sdk: launch instances requiring a specific subnet")
specific_subnet_hosts.each do |host|
subnet_id = host['subnet_id'] || global_subnet_id
instance = create_instance(host, ami_spec, subnet_id)
instances.push({:instance => instance, :host => host})
end
@logger.notify("aws-sdk: launch instances requiring no subnet")
no_subnet_hosts.each do |host|
instance = create_instance(host, ami_spec, nil)
instances.push({:instance => instance, :host => host})
end
wait_for_status(:running, instances)
rescue Exception => ex
@logger.notify("aws-sdk: exception #{ex.class}: #{ex}")
kill_instances(instances.map{|x| x[:instance]})
raise ex
end
# At this point, all instances should be running since wait
# either returns on success or throws an exception.
if instances.empty?
raise RuntimeError, "Didn't manage to launch any EC2 instances"
end
# Assign the now known running instances to their hosts.
instances.each {|x| x[:host]['instance'] = x[:instance]}
nil
end | ruby | def launch_all_nodes
@logger.notify("aws-sdk: launch all hosts in configuration")
ami_spec = YAML.load_file(@options[:ec2_yaml])["AMI"]
global_subnet_id = @options['subnet_id']
global_subnets = @options['subnet_ids']
if global_subnet_id and global_subnets
raise RuntimeError, 'Config specifies both subnet_id and subnet_ids'
end
no_subnet_hosts = []
specific_subnet_hosts = []
some_subnet_hosts = []
@hosts.each do |host|
if global_subnet_id or host['subnet_id']
specific_subnet_hosts.push(host)
elsif global_subnets
some_subnet_hosts.push(host)
else
no_subnet_hosts.push(host)
end
end
instances = [] # Each element is {:instance => i, :host => h}
begin
@logger.notify("aws-sdk: launch instances not particular about subnet")
launch_nodes_on_some_subnet(some_subnet_hosts, global_subnets, ami_spec,
instances)
@logger.notify("aws-sdk: launch instances requiring a specific subnet")
specific_subnet_hosts.each do |host|
subnet_id = host['subnet_id'] || global_subnet_id
instance = create_instance(host, ami_spec, subnet_id)
instances.push({:instance => instance, :host => host})
end
@logger.notify("aws-sdk: launch instances requiring no subnet")
no_subnet_hosts.each do |host|
instance = create_instance(host, ami_spec, nil)
instances.push({:instance => instance, :host => host})
end
wait_for_status(:running, instances)
rescue Exception => ex
@logger.notify("aws-sdk: exception #{ex.class}: #{ex}")
kill_instances(instances.map{|x| x[:instance]})
raise ex
end
# At this point, all instances should be running since wait
# either returns on success or throws an exception.
if instances.empty?
raise RuntimeError, "Didn't manage to launch any EC2 instances"
end
# Assign the now known running instances to their hosts.
instances.each {|x| x[:host]['instance'] = x[:instance]}
nil
end | [
"def",
"launch_all_nodes",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: launch all hosts in configuration\"",
")",
"ami_spec",
"=",
"YAML",
".",
"load_file",
"(",
"@options",
"[",
":ec2_yaml",
"]",
")",
"[",
"\"AMI\"",
"]",
"global_subnet_id",
"=",
"@options",
"[",
"'subnet_id'",
"]",
"global_subnets",
"=",
"@options",
"[",
"'subnet_ids'",
"]",
"if",
"global_subnet_id",
"and",
"global_subnets",
"raise",
"RuntimeError",
",",
"'Config specifies both subnet_id and subnet_ids'",
"end",
"no_subnet_hosts",
"=",
"[",
"]",
"specific_subnet_hosts",
"=",
"[",
"]",
"some_subnet_hosts",
"=",
"[",
"]",
"@hosts",
".",
"each",
"do",
"|",
"host",
"|",
"if",
"global_subnet_id",
"or",
"host",
"[",
"'subnet_id'",
"]",
"specific_subnet_hosts",
".",
"push",
"(",
"host",
")",
"elsif",
"global_subnets",
"some_subnet_hosts",
".",
"push",
"(",
"host",
")",
"else",
"no_subnet_hosts",
".",
"push",
"(",
"host",
")",
"end",
"end",
"instances",
"=",
"[",
"]",
"# Each element is {:instance => i, :host => h}",
"begin",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: launch instances not particular about subnet\"",
")",
"launch_nodes_on_some_subnet",
"(",
"some_subnet_hosts",
",",
"global_subnets",
",",
"ami_spec",
",",
"instances",
")",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: launch instances requiring a specific subnet\"",
")",
"specific_subnet_hosts",
".",
"each",
"do",
"|",
"host",
"|",
"subnet_id",
"=",
"host",
"[",
"'subnet_id'",
"]",
"||",
"global_subnet_id",
"instance",
"=",
"create_instance",
"(",
"host",
",",
"ami_spec",
",",
"subnet_id",
")",
"instances",
".",
"push",
"(",
"{",
":instance",
"=>",
"instance",
",",
":host",
"=>",
"host",
"}",
")",
"end",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: launch instances requiring no subnet\"",
")",
"no_subnet_hosts",
".",
"each",
"do",
"|",
"host",
"|",
"instance",
"=",
"create_instance",
"(",
"host",
",",
"ami_spec",
",",
"nil",
")",
"instances",
".",
"push",
"(",
"{",
":instance",
"=>",
"instance",
",",
":host",
"=>",
"host",
"}",
")",
"end",
"wait_for_status",
"(",
":running",
",",
"instances",
")",
"rescue",
"Exception",
"=>",
"ex",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: exception #{ex.class}: #{ex}\"",
")",
"kill_instances",
"(",
"instances",
".",
"map",
"{",
"|",
"x",
"|",
"x",
"[",
":instance",
"]",
"}",
")",
"raise",
"ex",
"end",
"# At this point, all instances should be running since wait",
"# either returns on success or throws an exception.",
"if",
"instances",
".",
"empty?",
"raise",
"RuntimeError",
",",
"\"Didn't manage to launch any EC2 instances\"",
"end",
"# Assign the now known running instances to their hosts.",
"instances",
".",
"each",
"{",
"|",
"x",
"|",
"x",
"[",
":host",
"]",
"[",
"'instance'",
"]",
"=",
"x",
"[",
":instance",
"]",
"}",
"nil",
"end"
] | Create EC2 instances for all hosts, tag them, and wait until
they're running. When a host provides a subnet_id, create the
instance in that subnet, otherwise prefer a CONFIG subnet_id.
If neither are set but there is a CONFIG subnet_ids list,
attempt to create the host in each specified subnet, which might
fail due to capacity constraints, for example. Specifying both
a CONFIG subnet_id and subnet_ids will provoke an error.
@return [void]
@api private | [
"Create",
"EC2",
"instances",
"for",
"all",
"hosts",
"tag",
"them",
"and",
"wait",
"until",
"they",
"re",
"running",
".",
"When",
"a",
"host",
"provides",
"a",
"subnet_id",
"create",
"the",
"instance",
"in",
"that",
"subnet",
"otherwise",
"prefer",
"a",
"CONFIG",
"subnet_id",
".",
"If",
"neither",
"are",
"set",
"but",
"there",
"is",
"a",
"CONFIG",
"subnet_ids",
"list",
"attempt",
"to",
"create",
"the",
"host",
"in",
"each",
"specified",
"subnet",
"which",
"might",
"fail",
"due",
"to",
"capacity",
"constraints",
"for",
"example",
".",
"Specifying",
"both",
"a",
"CONFIG",
"subnet_id",
"and",
"subnet_ids",
"will",
"provoke",
"an",
"error",
"."
] | f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L432-L482 |
23,481 | puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.wait_for_status_netdev | def wait_for_status_netdev()
@hosts.each do |host|
if host['platform'] =~ /f5-|netscaler/
wait_for_status(:running, @hosts)
wait_for_status(nil, @hosts) do |instance|
instance_status_collection = client.describe_instance_status({:instance_ids => [instance.instance_id]})
first_instance = instance_status_collection.first[:instance_statuses].first
first_instance[:instance_status][:status] == "ok" if first_instance
end
break
end
end
end | ruby | def wait_for_status_netdev()
@hosts.each do |host|
if host['platform'] =~ /f5-|netscaler/
wait_for_status(:running, @hosts)
wait_for_status(nil, @hosts) do |instance|
instance_status_collection = client.describe_instance_status({:instance_ids => [instance.instance_id]})
first_instance = instance_status_collection.first[:instance_statuses].first
first_instance[:instance_status][:status] == "ok" if first_instance
end
break
end
end
end | [
"def",
"wait_for_status_netdev",
"(",
")",
"@hosts",
".",
"each",
"do",
"|",
"host",
"|",
"if",
"host",
"[",
"'platform'",
"]",
"=~",
"/",
"/",
"wait_for_status",
"(",
":running",
",",
"@hosts",
")",
"wait_for_status",
"(",
"nil",
",",
"@hosts",
")",
"do",
"|",
"instance",
"|",
"instance_status_collection",
"=",
"client",
".",
"describe_instance_status",
"(",
"{",
":instance_ids",
"=>",
"[",
"instance",
".",
"instance_id",
"]",
"}",
")",
"first_instance",
"=",
"instance_status_collection",
".",
"first",
"[",
":instance_statuses",
"]",
".",
"first",
"first_instance",
"[",
":instance_status",
"]",
"[",
":status",
"]",
"==",
"\"ok\"",
"if",
"first_instance",
"end",
"break",
"end",
"end",
"end"
] | Handles special checks needed for netdev platforms.
@note if any host is an netdev one, these checks will happen once across all
of the hosts, and then we'll exit
@return [void]
@api private | [
"Handles",
"special",
"checks",
"needed",
"for",
"netdev",
"platforms",
"."
] | f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L539-L553 |
23,482 | puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.add_tags | def add_tags
@hosts.each do |host|
instance = host['instance']
# Define tags for the instance
@logger.notify("aws-sdk: Add tags for #{host.name}")
tags = [
{
:key => 'jenkins_build_url',
:value => @options[:jenkins_build_url],
},
{
:key => 'Name',
:value => host.name,
},
{
:key => 'department',
:value => @options[:department],
},
{
:key => 'project',
:value => @options[:project],
},
{
:key => 'created_by',
:value => @options[:created_by],
},
]
host[:host_tags].each do |name, val|
tags << { :key => name.to_s, :value => val }
end
client.create_tags(
:resources => [instance.instance_id],
:tags => tags.reject { |r| r[:value].nil? },
)
end
nil
end | ruby | def add_tags
@hosts.each do |host|
instance = host['instance']
# Define tags for the instance
@logger.notify("aws-sdk: Add tags for #{host.name}")
tags = [
{
:key => 'jenkins_build_url',
:value => @options[:jenkins_build_url],
},
{
:key => 'Name',
:value => host.name,
},
{
:key => 'department',
:value => @options[:department],
},
{
:key => 'project',
:value => @options[:project],
},
{
:key => 'created_by',
:value => @options[:created_by],
},
]
host[:host_tags].each do |name, val|
tags << { :key => name.to_s, :value => val }
end
client.create_tags(
:resources => [instance.instance_id],
:tags => tags.reject { |r| r[:value].nil? },
)
end
nil
end | [
"def",
"add_tags",
"@hosts",
".",
"each",
"do",
"|",
"host",
"|",
"instance",
"=",
"host",
"[",
"'instance'",
"]",
"# Define tags for the instance",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: Add tags for #{host.name}\"",
")",
"tags",
"=",
"[",
"{",
":key",
"=>",
"'jenkins_build_url'",
",",
":value",
"=>",
"@options",
"[",
":jenkins_build_url",
"]",
",",
"}",
",",
"{",
":key",
"=>",
"'Name'",
",",
":value",
"=>",
"host",
".",
"name",
",",
"}",
",",
"{",
":key",
"=>",
"'department'",
",",
":value",
"=>",
"@options",
"[",
":department",
"]",
",",
"}",
",",
"{",
":key",
"=>",
"'project'",
",",
":value",
"=>",
"@options",
"[",
":project",
"]",
",",
"}",
",",
"{",
":key",
"=>",
"'created_by'",
",",
":value",
"=>",
"@options",
"[",
":created_by",
"]",
",",
"}",
",",
"]",
"host",
"[",
":host_tags",
"]",
".",
"each",
"do",
"|",
"name",
",",
"val",
"|",
"tags",
"<<",
"{",
":key",
"=>",
"name",
".",
"to_s",
",",
":value",
"=>",
"val",
"}",
"end",
"client",
".",
"create_tags",
"(",
":resources",
"=>",
"[",
"instance",
".",
"instance_id",
"]",
",",
":tags",
"=>",
"tags",
".",
"reject",
"{",
"|",
"r",
"|",
"r",
"[",
":value",
"]",
".",
"nil?",
"}",
",",
")",
"end",
"nil",
"end"
] | Add metadata tags to all instances
@return [void]
@api private | [
"Add",
"metadata",
"tags",
"to",
"all",
"instances"
] | f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L559-L600 |
23,483 | puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.modify_network_interface | def modify_network_interface
@hosts.each do |host|
instance = host['instance']
host['sg_cidr_ips'] = host['sg_cidr_ips'] || '0.0.0.0/0';
sg_cidr_ips = host['sg_cidr_ips'].split(',')
# Define tags for the instance
@logger.notify("aws-sdk: Update network_interface for #{host.name}")
security_group = ensure_group(instance[:network_interfaces].first, Beaker::EC2Helper.amiports(host), sg_cidr_ips)
ping_security_group = ensure_ping_group(instance[:network_interfaces].first, sg_cidr_ips)
client.modify_network_interface_attribute(
:network_interface_id => "#{instance[:network_interfaces].first[:network_interface_id]}",
:groups => [security_group.group_id, ping_security_group.group_id],
)
end
nil
end | ruby | def modify_network_interface
@hosts.each do |host|
instance = host['instance']
host['sg_cidr_ips'] = host['sg_cidr_ips'] || '0.0.0.0/0';
sg_cidr_ips = host['sg_cidr_ips'].split(',')
# Define tags for the instance
@logger.notify("aws-sdk: Update network_interface for #{host.name}")
security_group = ensure_group(instance[:network_interfaces].first, Beaker::EC2Helper.amiports(host), sg_cidr_ips)
ping_security_group = ensure_ping_group(instance[:network_interfaces].first, sg_cidr_ips)
client.modify_network_interface_attribute(
:network_interface_id => "#{instance[:network_interfaces].first[:network_interface_id]}",
:groups => [security_group.group_id, ping_security_group.group_id],
)
end
nil
end | [
"def",
"modify_network_interface",
"@hosts",
".",
"each",
"do",
"|",
"host",
"|",
"instance",
"=",
"host",
"[",
"'instance'",
"]",
"host",
"[",
"'sg_cidr_ips'",
"]",
"=",
"host",
"[",
"'sg_cidr_ips'",
"]",
"||",
"'0.0.0.0/0'",
";",
"sg_cidr_ips",
"=",
"host",
"[",
"'sg_cidr_ips'",
"]",
".",
"split",
"(",
"','",
")",
"# Define tags for the instance",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: Update network_interface for #{host.name}\"",
")",
"security_group",
"=",
"ensure_group",
"(",
"instance",
"[",
":network_interfaces",
"]",
".",
"first",
",",
"Beaker",
"::",
"EC2Helper",
".",
"amiports",
"(",
"host",
")",
",",
"sg_cidr_ips",
")",
"ping_security_group",
"=",
"ensure_ping_group",
"(",
"instance",
"[",
":network_interfaces",
"]",
".",
"first",
",",
"sg_cidr_ips",
")",
"client",
".",
"modify_network_interface_attribute",
"(",
":network_interface_id",
"=>",
"\"#{instance[:network_interfaces].first[:network_interface_id]}\"",
",",
":groups",
"=>",
"[",
"security_group",
".",
"group_id",
",",
"ping_security_group",
".",
"group_id",
"]",
",",
")",
"end",
"nil",
"end"
] | Add correct security groups to hosts network_interface
as during the create_instance stage it is too early in process
to configure
@return [void]
@api private | [
"Add",
"correct",
"security",
"groups",
"to",
"hosts",
"network_interface",
"as",
"during",
"the",
"create_instance",
"stage",
"it",
"is",
"too",
"early",
"in",
"process",
"to",
"configure"
] | f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L608-L627 |
23,484 | puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.populate_dns | def populate_dns
# Obtain the IP addresses and dns_name for each host
@hosts.each do |host|
@logger.notify("aws-sdk: Populate DNS for #{host.name}")
instance = host['instance']
host['ip'] = instance.public_ip_address || instance.private_ip_address
host['private_ip'] = instance.private_ip_address
host['dns_name'] = instance.public_dns_name || instance.private_dns_name
@logger.notify("aws-sdk: name: #{host.name} ip: #{host['ip']} private_ip: #{host['private_ip']} dns_name: #{host['dns_name']}")
end
nil
end | ruby | def populate_dns
# Obtain the IP addresses and dns_name for each host
@hosts.each do |host|
@logger.notify("aws-sdk: Populate DNS for #{host.name}")
instance = host['instance']
host['ip'] = instance.public_ip_address || instance.private_ip_address
host['private_ip'] = instance.private_ip_address
host['dns_name'] = instance.public_dns_name || instance.private_dns_name
@logger.notify("aws-sdk: name: #{host.name} ip: #{host['ip']} private_ip: #{host['private_ip']} dns_name: #{host['dns_name']}")
end
nil
end | [
"def",
"populate_dns",
"# Obtain the IP addresses and dns_name for each host",
"@hosts",
".",
"each",
"do",
"|",
"host",
"|",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: Populate DNS for #{host.name}\"",
")",
"instance",
"=",
"host",
"[",
"'instance'",
"]",
"host",
"[",
"'ip'",
"]",
"=",
"instance",
".",
"public_ip_address",
"||",
"instance",
".",
"private_ip_address",
"host",
"[",
"'private_ip'",
"]",
"=",
"instance",
".",
"private_ip_address",
"host",
"[",
"'dns_name'",
"]",
"=",
"instance",
".",
"public_dns_name",
"||",
"instance",
".",
"private_dns_name",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: name: #{host.name} ip: #{host['ip']} private_ip: #{host['private_ip']} dns_name: #{host['dns_name']}\"",
")",
"end",
"nil",
"end"
] | Populate the hosts IP address from the EC2 dns_name
@return [void]
@api private | [
"Populate",
"the",
"hosts",
"IP",
"address",
"from",
"the",
"EC2",
"dns_name"
] | f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L633-L645 |
23,485 | puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.enable_root | def enable_root(host)
if host['user'] != 'root'
if host['platform'] =~ /f5-/
enable_root_f5(host)
elsif host['platform'] =~ /netscaler/
enable_root_netscaler(host)
else
copy_ssh_to_root(host, @options)
enable_root_login(host, @options)
host['user'] = 'root'
end
host.close
end
end | ruby | def enable_root(host)
if host['user'] != 'root'
if host['platform'] =~ /f5-/
enable_root_f5(host)
elsif host['platform'] =~ /netscaler/
enable_root_netscaler(host)
else
copy_ssh_to_root(host, @options)
enable_root_login(host, @options)
host['user'] = 'root'
end
host.close
end
end | [
"def",
"enable_root",
"(",
"host",
")",
"if",
"host",
"[",
"'user'",
"]",
"!=",
"'root'",
"if",
"host",
"[",
"'platform'",
"]",
"=~",
"/",
"/",
"enable_root_f5",
"(",
"host",
")",
"elsif",
"host",
"[",
"'platform'",
"]",
"=~",
"/",
"/",
"enable_root_netscaler",
"(",
"host",
")",
"else",
"copy_ssh_to_root",
"(",
"host",
",",
"@options",
")",
"enable_root_login",
"(",
"host",
",",
"@options",
")",
"host",
"[",
"'user'",
"]",
"=",
"'root'",
"end",
"host",
".",
"close",
"end",
"end"
] | Enables root access for a host when username is not root
@return [void]
@api private | [
"Enables",
"root",
"access",
"for",
"a",
"host",
"when",
"username",
"is",
"not",
"root"
] | f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L697-L710 |
23,486 | puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.ensure_key_pair | def ensure_key_pair(region)
pair_name = key_name()
delete_key_pair(region, pair_name)
create_new_key_pair(region, pair_name)
end | ruby | def ensure_key_pair(region)
pair_name = key_name()
delete_key_pair(region, pair_name)
create_new_key_pair(region, pair_name)
end | [
"def",
"ensure_key_pair",
"(",
"region",
")",
"pair_name",
"=",
"key_name",
"(",
")",
"delete_key_pair",
"(",
"region",
",",
"pair_name",
")",
"create_new_key_pair",
"(",
"region",
",",
"pair_name",
")",
"end"
] | Creates the KeyPair for this test run
@param region [Aws::EC2::Region] region to create the key pair in
@return [Aws::EC2::KeyPair] created key_pair
@api private | [
"Creates",
"the",
"KeyPair",
"for",
"this",
"test",
"run"
] | f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L876-L880 |
23,487 | puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.delete_key_pair_all_regions | def delete_key_pair_all_regions(keypair_name_filter=nil)
region_keypairs_hash = my_key_pairs(keypair_name_filter)
region_keypairs_hash.each_pair do |region, keypair_name_array|
keypair_name_array.each do |keypair_name|
delete_key_pair(region, keypair_name)
end
end
end | ruby | def delete_key_pair_all_regions(keypair_name_filter=nil)
region_keypairs_hash = my_key_pairs(keypair_name_filter)
region_keypairs_hash.each_pair do |region, keypair_name_array|
keypair_name_array.each do |keypair_name|
delete_key_pair(region, keypair_name)
end
end
end | [
"def",
"delete_key_pair_all_regions",
"(",
"keypair_name_filter",
"=",
"nil",
")",
"region_keypairs_hash",
"=",
"my_key_pairs",
"(",
"keypair_name_filter",
")",
"region_keypairs_hash",
".",
"each_pair",
"do",
"|",
"region",
",",
"keypair_name_array",
"|",
"keypair_name_array",
".",
"each",
"do",
"|",
"keypair_name",
"|",
"delete_key_pair",
"(",
"region",
",",
"keypair_name",
")",
"end",
"end",
"end"
] | Deletes key pairs from all regions
@param [String] keypair_name_filter if given, will get all keypairs that match
a simple {::String#start_with?} filter. If no filter is given, the basic key
name returned by {#key_name} will be used.
@return nil
@api private | [
"Deletes",
"key",
"pairs",
"from",
"all",
"regions"
] | f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L890-L897 |
23,488 | puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.my_key_pairs | def my_key_pairs(name_filter=nil)
keypairs_by_region = {}
key_name_filter = name_filter ? "#{name_filter}-*" : key_name
regions.each do |region|
keypairs_by_region[region] = client(region).describe_key_pairs(
:filters => [{ :name => 'key-name', :values => [key_name_filter] }]
).key_pairs.map(&:key_name)
end
keypairs_by_region
end | ruby | def my_key_pairs(name_filter=nil)
keypairs_by_region = {}
key_name_filter = name_filter ? "#{name_filter}-*" : key_name
regions.each do |region|
keypairs_by_region[region] = client(region).describe_key_pairs(
:filters => [{ :name => 'key-name', :values => [key_name_filter] }]
).key_pairs.map(&:key_name)
end
keypairs_by_region
end | [
"def",
"my_key_pairs",
"(",
"name_filter",
"=",
"nil",
")",
"keypairs_by_region",
"=",
"{",
"}",
"key_name_filter",
"=",
"name_filter",
"?",
"\"#{name_filter}-*\"",
":",
"key_name",
"regions",
".",
"each",
"do",
"|",
"region",
"|",
"keypairs_by_region",
"[",
"region",
"]",
"=",
"client",
"(",
"region",
")",
".",
"describe_key_pairs",
"(",
":filters",
"=>",
"[",
"{",
":name",
"=>",
"'key-name'",
",",
":values",
"=>",
"[",
"key_name_filter",
"]",
"}",
"]",
")",
".",
"key_pairs",
".",
"map",
"(",
":key_name",
")",
"end",
"keypairs_by_region",
"end"
] | Gets the Beaker user's keypairs by region
@param [String] name_filter if given, will get all keypairs that match
a simple {::String#start_with?} filter. If no filter is given, the basic key
name returned by {#key_name} will be used.
@return [Hash{String=>Array[String]}] a hash of region name to
an array of the keypair names that match for the filter
@api private | [
"Gets",
"the",
"Beaker",
"user",
"s",
"keypairs",
"by",
"region"
] | f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L908-L919 |
23,489 | puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.delete_key_pair | def delete_key_pair(region, pair_name)
kp = client(region).describe_key_pairs(:key_names => [pair_name]).key_pairs.first
unless kp.nil?
@logger.debug("aws-sdk: delete key pair in region: #{region}")
client(region).delete_key_pair(:key_name => pair_name)
end
rescue Aws::EC2::Errors::InvalidKeyPairNotFound
nil
end | ruby | def delete_key_pair(region, pair_name)
kp = client(region).describe_key_pairs(:key_names => [pair_name]).key_pairs.first
unless kp.nil?
@logger.debug("aws-sdk: delete key pair in region: #{region}")
client(region).delete_key_pair(:key_name => pair_name)
end
rescue Aws::EC2::Errors::InvalidKeyPairNotFound
nil
end | [
"def",
"delete_key_pair",
"(",
"region",
",",
"pair_name",
")",
"kp",
"=",
"client",
"(",
"region",
")",
".",
"describe_key_pairs",
"(",
":key_names",
"=>",
"[",
"pair_name",
"]",
")",
".",
"key_pairs",
".",
"first",
"unless",
"kp",
".",
"nil?",
"@logger",
".",
"debug",
"(",
"\"aws-sdk: delete key pair in region: #{region}\"",
")",
"client",
"(",
"region",
")",
".",
"delete_key_pair",
"(",
":key_name",
"=>",
"pair_name",
")",
"end",
"rescue",
"Aws",
"::",
"EC2",
"::",
"Errors",
"::",
"InvalidKeyPairNotFound",
"nil",
"end"
] | Deletes a given key pair
@param [Aws::EC2::Region] region the region the key belongs to
@param [String] pair_name the name of the key to be deleted
@api private | [
"Deletes",
"a",
"given",
"key",
"pair"
] | f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L927-L935 |
23,490 | puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.create_new_key_pair | def create_new_key_pair(region, pair_name)
@logger.debug("aws-sdk: importing new key pair: #{pair_name}")
client(region).import_key_pair(:key_name => pair_name, :public_key_material => public_key)
begin
client(region).wait_until(:key_pair_exists, { :key_names => [pair_name] }, :max_attempts => 5, :delay => 2)
rescue Aws::Waiters::Errors::WaiterFailed
raise RuntimeError, "AWS key pair #{pair_name} can not be queried, even after import"
end
end | ruby | def create_new_key_pair(region, pair_name)
@logger.debug("aws-sdk: importing new key pair: #{pair_name}")
client(region).import_key_pair(:key_name => pair_name, :public_key_material => public_key)
begin
client(region).wait_until(:key_pair_exists, { :key_names => [pair_name] }, :max_attempts => 5, :delay => 2)
rescue Aws::Waiters::Errors::WaiterFailed
raise RuntimeError, "AWS key pair #{pair_name} can not be queried, even after import"
end
end | [
"def",
"create_new_key_pair",
"(",
"region",
",",
"pair_name",
")",
"@logger",
".",
"debug",
"(",
"\"aws-sdk: importing new key pair: #{pair_name}\"",
")",
"client",
"(",
"region",
")",
".",
"import_key_pair",
"(",
":key_name",
"=>",
"pair_name",
",",
":public_key_material",
"=>",
"public_key",
")",
"begin",
"client",
"(",
"region",
")",
".",
"wait_until",
"(",
":key_pair_exists",
",",
"{",
":key_names",
"=>",
"[",
"pair_name",
"]",
"}",
",",
":max_attempts",
"=>",
"5",
",",
":delay",
"=>",
"2",
")",
"rescue",
"Aws",
"::",
"Waiters",
"::",
"Errors",
"::",
"WaiterFailed",
"raise",
"RuntimeError",
",",
"\"AWS key pair #{pair_name} can not be queried, even after import\"",
"end",
"end"
] | Create a new key pair for a given Beaker run
@param [Aws::EC2::Region] region the region the key pair will be imported into
@param [String] pair_name the name of the key to be created
@return [Aws::EC2::KeyPair] key pair created
@raise [RuntimeError] raised if AWS keypair not created | [
"Create",
"a",
"new",
"key",
"pair",
"for",
"a",
"given",
"Beaker",
"run"
] | f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L944-L953 |
23,491 | puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.group_id | def group_id(ports)
if ports.nil? or ports.empty?
raise ArgumentError, "Ports list cannot be nil or empty"
end
unless ports.is_a? Set
ports = Set.new(ports)
end
# Lolwut, #hash is inconsistent between ruby processes
"Beaker-#{Zlib.crc32(ports.inspect)}"
end | ruby | def group_id(ports)
if ports.nil? or ports.empty?
raise ArgumentError, "Ports list cannot be nil or empty"
end
unless ports.is_a? Set
ports = Set.new(ports)
end
# Lolwut, #hash is inconsistent between ruby processes
"Beaker-#{Zlib.crc32(ports.inspect)}"
end | [
"def",
"group_id",
"(",
"ports",
")",
"if",
"ports",
".",
"nil?",
"or",
"ports",
".",
"empty?",
"raise",
"ArgumentError",
",",
"\"Ports list cannot be nil or empty\"",
"end",
"unless",
"ports",
".",
"is_a?",
"Set",
"ports",
"=",
"Set",
".",
"new",
"(",
"ports",
")",
"end",
"# Lolwut, #hash is inconsistent between ruby processes",
"\"Beaker-#{Zlib.crc32(ports.inspect)}\"",
"end"
] | Return a reproducable security group identifier based on input ports
@param ports [Array<Number>] array of port numbers
@return [String] group identifier
@api private | [
"Return",
"a",
"reproducable",
"security",
"group",
"identifier",
"based",
"on",
"input",
"ports"
] | f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L960-L971 |
23,492 | puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.create_ping_group | def create_ping_group(region_or_vpc, sg_cidr_ips = ['0.0.0.0/0'])
@logger.notify("aws-sdk: Creating group #{PING_SECURITY_GROUP_NAME}")
cl = region_or_vpc.is_a?(String) ? client(region_or_vpc) : client
params = {
:description => 'Custom Beaker security group to enable ping',
:group_name => PING_SECURITY_GROUP_NAME,
}
params[:vpc_id] = region_or_vpc.vpc_id if region_or_vpc.is_a?(Aws::EC2::Types::Vpc)
group = cl.create_security_group(params)
sg_cidr_ips.each do |cidr_ip|
add_ingress_rule(
cl,
group,
cidr_ip,
'8', # 8 == ICMPv4 ECHO request
'-1', # -1 == All ICMP codes
'icmp',
)
end
group
end | ruby | def create_ping_group(region_or_vpc, sg_cidr_ips = ['0.0.0.0/0'])
@logger.notify("aws-sdk: Creating group #{PING_SECURITY_GROUP_NAME}")
cl = region_or_vpc.is_a?(String) ? client(region_or_vpc) : client
params = {
:description => 'Custom Beaker security group to enable ping',
:group_name => PING_SECURITY_GROUP_NAME,
}
params[:vpc_id] = region_or_vpc.vpc_id if region_or_vpc.is_a?(Aws::EC2::Types::Vpc)
group = cl.create_security_group(params)
sg_cidr_ips.each do |cidr_ip|
add_ingress_rule(
cl,
group,
cidr_ip,
'8', # 8 == ICMPv4 ECHO request
'-1', # -1 == All ICMP codes
'icmp',
)
end
group
end | [
"def",
"create_ping_group",
"(",
"region_or_vpc",
",",
"sg_cidr_ips",
"=",
"[",
"'0.0.0.0/0'",
"]",
")",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: Creating group #{PING_SECURITY_GROUP_NAME}\"",
")",
"cl",
"=",
"region_or_vpc",
".",
"is_a?",
"(",
"String",
")",
"?",
"client",
"(",
"region_or_vpc",
")",
":",
"client",
"params",
"=",
"{",
":description",
"=>",
"'Custom Beaker security group to enable ping'",
",",
":group_name",
"=>",
"PING_SECURITY_GROUP_NAME",
",",
"}",
"params",
"[",
":vpc_id",
"]",
"=",
"region_or_vpc",
".",
"vpc_id",
"if",
"region_or_vpc",
".",
"is_a?",
"(",
"Aws",
"::",
"EC2",
"::",
"Types",
"::",
"Vpc",
")",
"group",
"=",
"cl",
".",
"create_security_group",
"(",
"params",
")",
"sg_cidr_ips",
".",
"each",
"do",
"|",
"cidr_ip",
"|",
"add_ingress_rule",
"(",
"cl",
",",
"group",
",",
"cidr_ip",
",",
"'8'",
",",
"# 8 == ICMPv4 ECHO request",
"'-1'",
",",
"# -1 == All ICMP codes",
"'icmp'",
",",
")",
"end",
"group",
"end"
] | Create a new ping enabled security group
Accepts a region or VPC for group creation.
@param region_or_vpc [Aws::EC2::Region, Aws::EC2::VPC] the AWS region or vpc control object
@param sg_cidr_ips [Array<String>] CIDRs used for outbound security group rule
@return [Aws::EC2::SecurityGroup] created security group
@api private | [
"Create",
"a",
"new",
"ping",
"enabled",
"security",
"group"
] | f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L1033-L1057 |
23,493 | puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.create_group | def create_group(region_or_vpc, ports, sg_cidr_ips = ['0.0.0.0/0'])
name = group_id(ports)
@logger.notify("aws-sdk: Creating group #{name} for ports #{ports.to_s}")
@logger.notify("aws-sdk: Creating group #{name} with CIDR IPs #{sg_cidr_ips.to_s}")
cl = region_or_vpc.is_a?(String) ? client(region_or_vpc) : client
params = {
:description => "Custom Beaker security group for #{ports.to_a}",
:group_name => name,
}
params[:vpc_id] = region_or_vpc.vpc_id if region_or_vpc.is_a?(Aws::EC2::Types::Vpc)
group = cl.create_security_group(params)
unless ports.is_a? Set
ports = Set.new(ports)
end
sg_cidr_ips.each do |cidr_ip|
ports.each do |port|
add_ingress_rule(cl, group, cidr_ip, port, port)
end
end
group
end | ruby | def create_group(region_or_vpc, ports, sg_cidr_ips = ['0.0.0.0/0'])
name = group_id(ports)
@logger.notify("aws-sdk: Creating group #{name} for ports #{ports.to_s}")
@logger.notify("aws-sdk: Creating group #{name} with CIDR IPs #{sg_cidr_ips.to_s}")
cl = region_or_vpc.is_a?(String) ? client(region_or_vpc) : client
params = {
:description => "Custom Beaker security group for #{ports.to_a}",
:group_name => name,
}
params[:vpc_id] = region_or_vpc.vpc_id if region_or_vpc.is_a?(Aws::EC2::Types::Vpc)
group = cl.create_security_group(params)
unless ports.is_a? Set
ports = Set.new(ports)
end
sg_cidr_ips.each do |cidr_ip|
ports.each do |port|
add_ingress_rule(cl, group, cidr_ip, port, port)
end
end
group
end | [
"def",
"create_group",
"(",
"region_or_vpc",
",",
"ports",
",",
"sg_cidr_ips",
"=",
"[",
"'0.0.0.0/0'",
"]",
")",
"name",
"=",
"group_id",
"(",
"ports",
")",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: Creating group #{name} for ports #{ports.to_s}\"",
")",
"@logger",
".",
"notify",
"(",
"\"aws-sdk: Creating group #{name} with CIDR IPs #{sg_cidr_ips.to_s}\"",
")",
"cl",
"=",
"region_or_vpc",
".",
"is_a?",
"(",
"String",
")",
"?",
"client",
"(",
"region_or_vpc",
")",
":",
"client",
"params",
"=",
"{",
":description",
"=>",
"\"Custom Beaker security group for #{ports.to_a}\"",
",",
":group_name",
"=>",
"name",
",",
"}",
"params",
"[",
":vpc_id",
"]",
"=",
"region_or_vpc",
".",
"vpc_id",
"if",
"region_or_vpc",
".",
"is_a?",
"(",
"Aws",
"::",
"EC2",
"::",
"Types",
"::",
"Vpc",
")",
"group",
"=",
"cl",
".",
"create_security_group",
"(",
"params",
")",
"unless",
"ports",
".",
"is_a?",
"Set",
"ports",
"=",
"Set",
".",
"new",
"(",
"ports",
")",
"end",
"sg_cidr_ips",
".",
"each",
"do",
"|",
"cidr_ip",
"|",
"ports",
".",
"each",
"do",
"|",
"port",
"|",
"add_ingress_rule",
"(",
"cl",
",",
"group",
",",
"cidr_ip",
",",
"port",
",",
"port",
")",
"end",
"end",
"group",
"end"
] | Create a new security group
Accepts a region or VPC for group creation.
@param region_or_vpc [Aws::EC2::Region, Aws::EC2::VPC] the AWS region or vpc control object
@param ports [Array<Number>] an array of port numbers
@param sg_cidr_ips [Array<String>] CIDRs used for outbound security group rule
@return [Aws::EC2::SecurityGroup] created security group
@api private | [
"Create",
"a",
"new",
"security",
"group"
] | f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L1068-L1094 |
23,494 | puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.add_ingress_rule | def add_ingress_rule(cl, sg_group, cidr_ip, from_port, to_port, protocol = 'tcp')
cl.authorize_security_group_ingress(
:cidr_ip => cidr_ip,
:ip_protocol => protocol,
:from_port => from_port,
:to_port => to_port,
:group_id => sg_group.group_id,
)
end | ruby | def add_ingress_rule(cl, sg_group, cidr_ip, from_port, to_port, protocol = 'tcp')
cl.authorize_security_group_ingress(
:cidr_ip => cidr_ip,
:ip_protocol => protocol,
:from_port => from_port,
:to_port => to_port,
:group_id => sg_group.group_id,
)
end | [
"def",
"add_ingress_rule",
"(",
"cl",
",",
"sg_group",
",",
"cidr_ip",
",",
"from_port",
",",
"to_port",
",",
"protocol",
"=",
"'tcp'",
")",
"cl",
".",
"authorize_security_group_ingress",
"(",
":cidr_ip",
"=>",
"cidr_ip",
",",
":ip_protocol",
"=>",
"protocol",
",",
":from_port",
"=>",
"from_port",
",",
":to_port",
"=>",
"to_port",
",",
":group_id",
"=>",
"sg_group",
".",
"group_id",
",",
")",
"end"
] | Authorizes connections from certain CIDR to a range of ports
@param cl [Aws::EC2::Client]
@param sg_group [Aws::EC2::SecurityGroup] the AWS security group
@param cidr_ip [String] CIDR used for outbound security group rule
@param from_port [String] Starting Port number in the range
@param to_port [String] Ending Port number in the range
@return [void]
@api private | [
"Authorizes",
"connections",
"from",
"certain",
"CIDR",
"to",
"a",
"range",
"of",
"ports"
] | f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L1105-L1113 |
23,495 | puppetlabs/beaker-aws | lib/beaker/hypervisor/aws_sdk.rb | Beaker.AwsSdk.load_fog_credentials | def load_fog_credentials(dot_fog = '.fog')
default = get_fog_credentials(dot_fog)
raise "You must specify an aws_access_key_id in your .fog file (#{dot_fog}) for ec2 instances!" unless default[:aws_access_key_id]
raise "You must specify an aws_secret_access_key in your .fog file (#{dot_fog}) for ec2 instances!" unless default[:aws_secret_access_key]
Aws::Credentials.new(
default[:aws_access_key_id],
default[:aws_secret_access_key],
default[:aws_session_token]
)
end | ruby | def load_fog_credentials(dot_fog = '.fog')
default = get_fog_credentials(dot_fog)
raise "You must specify an aws_access_key_id in your .fog file (#{dot_fog}) for ec2 instances!" unless default[:aws_access_key_id]
raise "You must specify an aws_secret_access_key in your .fog file (#{dot_fog}) for ec2 instances!" unless default[:aws_secret_access_key]
Aws::Credentials.new(
default[:aws_access_key_id],
default[:aws_secret_access_key],
default[:aws_session_token]
)
end | [
"def",
"load_fog_credentials",
"(",
"dot_fog",
"=",
"'.fog'",
")",
"default",
"=",
"get_fog_credentials",
"(",
"dot_fog",
")",
"raise",
"\"You must specify an aws_access_key_id in your .fog file (#{dot_fog}) for ec2 instances!\"",
"unless",
"default",
"[",
":aws_access_key_id",
"]",
"raise",
"\"You must specify an aws_secret_access_key in your .fog file (#{dot_fog}) for ec2 instances!\"",
"unless",
"default",
"[",
":aws_secret_access_key",
"]",
"Aws",
"::",
"Credentials",
".",
"new",
"(",
"default",
"[",
":aws_access_key_id",
"]",
",",
"default",
"[",
":aws_secret_access_key",
"]",
",",
"default",
"[",
":aws_session_token",
"]",
")",
"end"
] | Return a hash containing the fog credentials for EC2
@param dot_fog [String] dot fog path
@return [Aws::Credentials] ec2 credentials
@api private | [
"Return",
"a",
"hash",
"containing",
"the",
"fog",
"credentials",
"for",
"EC2"
] | f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39 | https://github.com/puppetlabs/beaker-aws/blob/f2e448b4e7c7ccb17940b86afc25cee5eb5cbb39/lib/beaker/hypervisor/aws_sdk.rb#L1142-L1153 |
23,496 | terry90/rails_api_benchmark | lib/rails_api_benchmark/result_set.rb | RailsApiBenchmark.ResultSet.compute_relative_speed | def compute_relative_speed
@results = @results.map do |r|
avgs = averages
res = r[:results]
avg_rt = avgs[:response_time]
avg_rps = avgs[:req_per_sec]
f_rt = ((res[:response_time].to_f - avg_rt) / avg_rt * 100).round(1)
f_rps = ((res[:req_per_sec].to_f - avg_rps) / avg_rps * 100).round(1)
r.merge(factors: { response_time: f_rt, req_per_sec: f_rps })
end
end | ruby | def compute_relative_speed
@results = @results.map do |r|
avgs = averages
res = r[:results]
avg_rt = avgs[:response_time]
avg_rps = avgs[:req_per_sec]
f_rt = ((res[:response_time].to_f - avg_rt) / avg_rt * 100).round(1)
f_rps = ((res[:req_per_sec].to_f - avg_rps) / avg_rps * 100).round(1)
r.merge(factors: { response_time: f_rt, req_per_sec: f_rps })
end
end | [
"def",
"compute_relative_speed",
"@results",
"=",
"@results",
".",
"map",
"do",
"|",
"r",
"|",
"avgs",
"=",
"averages",
"res",
"=",
"r",
"[",
":results",
"]",
"avg_rt",
"=",
"avgs",
"[",
":response_time",
"]",
"avg_rps",
"=",
"avgs",
"[",
":req_per_sec",
"]",
"f_rt",
"=",
"(",
"(",
"res",
"[",
":response_time",
"]",
".",
"to_f",
"-",
"avg_rt",
")",
"/",
"avg_rt",
"*",
"100",
")",
".",
"round",
"(",
"1",
")",
"f_rps",
"=",
"(",
"(",
"res",
"[",
":req_per_sec",
"]",
".",
"to_f",
"-",
"avg_rps",
")",
"/",
"avg_rps",
"*",
"100",
")",
".",
"round",
"(",
"1",
")",
"r",
".",
"merge",
"(",
"factors",
":",
"{",
"response_time",
":",
"f_rt",
",",
"req_per_sec",
":",
"f_rps",
"}",
")",
"end",
"end"
] | Returns only the results with the relative speed | [
"Returns",
"only",
"the",
"results",
"with",
"the",
"relative",
"speed"
] | 2991765ff639b2efdf4aa1a56587247ed5ee22d0 | https://github.com/terry90/rails_api_benchmark/blob/2991765ff639b2efdf4aa1a56587247ed5ee22d0/lib/rails_api_benchmark/result_set.rb#L24-L36 |
23,497 | jetrockets/attrio | lib/attrio/helpers.rb | Attrio.Helpers.symbolize_hash_keys | def symbolize_hash_keys(hash)
hash.inject({}) do |new_hash, (key, value)|
new_hash[(key.to_sym rescue key) || key] = value
new_hash
end
hash
end | ruby | def symbolize_hash_keys(hash)
hash.inject({}) do |new_hash, (key, value)|
new_hash[(key.to_sym rescue key) || key] = value
new_hash
end
hash
end | [
"def",
"symbolize_hash_keys",
"(",
"hash",
")",
"hash",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"new_hash",
",",
"(",
"key",
",",
"value",
")",
"|",
"new_hash",
"[",
"(",
"key",
".",
"to_sym",
"rescue",
"key",
")",
"||",
"key",
"]",
"=",
"value",
"new_hash",
"end",
"hash",
"end"
] | note that returning hash without symbolizing anything
does not cause this to fail | [
"note",
"that",
"returning",
"hash",
"without",
"symbolizing",
"anything",
"does",
"not",
"cause",
"this",
"to",
"fail"
] | 4e3abd7ac120d53483fcdcd15f89b01c57b22fd8 | https://github.com/jetrockets/attrio/blob/4e3abd7ac120d53483fcdcd15f89b01c57b22fd8/lib/attrio/helpers.rb#L17-L23 |
23,498 | cbeer/fcrepo_wrapper | lib/fcrepo_wrapper/instance.rb | FcrepoWrapper.Instance.start | def start
extract_and_configure
if config.managed?
@pid = spawn(config.env, *process_arguments)
# Wait for fcrepo to start
while !status
sleep 1
end
end
end | ruby | def start
extract_and_configure
if config.managed?
@pid = spawn(config.env, *process_arguments)
# Wait for fcrepo to start
while !status
sleep 1
end
end
end | [
"def",
"start",
"extract_and_configure",
"if",
"config",
".",
"managed?",
"@pid",
"=",
"spawn",
"(",
"config",
".",
"env",
",",
"process_arguments",
")",
"# Wait for fcrepo to start",
"while",
"!",
"status",
"sleep",
"1",
"end",
"end",
"end"
] | Start fcrepo and wait for it to become available | [
"Start",
"fcrepo",
"and",
"wait",
"for",
"it",
"to",
"become",
"available"
] | 6b91a72e1c91848364a30b73b6e6e4b9b2d21296 | https://github.com/cbeer/fcrepo_wrapper/blob/6b91a72e1c91848364a30b73b6e6e4b9b2d21296/lib/fcrepo_wrapper/instance.rb#L55-L65 |
23,499 | cbeer/fcrepo_wrapper | lib/fcrepo_wrapper/instance.rb | FcrepoWrapper.Instance.stop | def stop
if config.managed? && started?
Process.kill 'HUP', pid
# Wait for fcrepo to stop
while status
sleep 1
end
Process.waitpid(pid)
end
@pid = nil
end | ruby | def stop
if config.managed? && started?
Process.kill 'HUP', pid
# Wait for fcrepo to stop
while status
sleep 1
end
Process.waitpid(pid)
end
@pid = nil
end | [
"def",
"stop",
"if",
"config",
".",
"managed?",
"&&",
"started?",
"Process",
".",
"kill",
"'HUP'",
",",
"pid",
"# Wait for fcrepo to stop",
"while",
"status",
"sleep",
"1",
"end",
"Process",
".",
"waitpid",
"(",
"pid",
")",
"end",
"@pid",
"=",
"nil",
"end"
] | Stop fcrepo and wait for it to finish exiting | [
"Stop",
"fcrepo",
"and",
"wait",
"for",
"it",
"to",
"finish",
"exiting"
] | 6b91a72e1c91848364a30b73b6e6e4b9b2d21296 | https://github.com/cbeer/fcrepo_wrapper/blob/6b91a72e1c91848364a30b73b6e6e4b9b2d21296/lib/fcrepo_wrapper/instance.rb#L69-L82 |
Subsets and Splits