repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
brainmap/nifti | lib/nifti/stream.rb | NIFTI.Stream.decode | def decode(length, type)
# Check if values are valid:
if (@index + length) > @string.length
# The index number is bigger then the length of the binary string.
# We have reached the end and will return nil.
value = nil
else
if type == "AT"
value = decode_tag
else
# Decode the binary string and return value:
value = @string.slice(@index, length).unpack(vr_to_str(type))
# If the result is an array of one element, return the element instead of the array.
# If result is contained in a multi-element array, the original array is returned.
if value.length == 1
value = value[0]
# If value is a string, strip away possible trailing whitespace:
# Do this using gsub instead of ruby-core #strip to keep trailing carriage
# returns, etc., because that is valid whitespace that we want to have included
# (i.e. in extended header data, AFNI writes a \n at the end of it's xml info,
# and that must be kept in order to not change the file on writing back out).
value.gsub!(/\000*$/, "") if value.respond_to? :gsub!
end
# Update our position in the string:
skip(length)
end
end
return value
end | ruby | def decode(length, type)
# Check if values are valid:
if (@index + length) > @string.length
# The index number is bigger then the length of the binary string.
# We have reached the end and will return nil.
value = nil
else
if type == "AT"
value = decode_tag
else
# Decode the binary string and return value:
value = @string.slice(@index, length).unpack(vr_to_str(type))
# If the result is an array of one element, return the element instead of the array.
# If result is contained in a multi-element array, the original array is returned.
if value.length == 1
value = value[0]
# If value is a string, strip away possible trailing whitespace:
# Do this using gsub instead of ruby-core #strip to keep trailing carriage
# returns, etc., because that is valid whitespace that we want to have included
# (i.e. in extended header data, AFNI writes a \n at the end of it's xml info,
# and that must be kept in order to not change the file on writing back out).
value.gsub!(/\000*$/, "") if value.respond_to? :gsub!
end
# Update our position in the string:
skip(length)
end
end
return value
end | [
"def",
"decode",
"(",
"length",
",",
"type",
")",
"if",
"(",
"@index",
"+",
"length",
")",
">",
"@string",
".",
"length",
"value",
"=",
"nil",
"else",
"if",
"type",
"==",
"\"AT\"",
"value",
"=",
"decode_tag",
"else",
"value",
"=",
"@string",
".",
"slice",
"(",
"@index",
",",
"length",
")",
".",
"unpack",
"(",
"vr_to_str",
"(",
"type",
")",
")",
"if",
"value",
".",
"length",
"==",
"1",
"value",
"=",
"value",
"[",
"0",
"]",
"value",
".",
"gsub!",
"(",
"/",
"\\000",
"/",
",",
"\"\"",
")",
"if",
"value",
".",
"respond_to?",
":gsub!",
"end",
"skip",
"(",
"length",
")",
"end",
"end",
"return",
"value",
"end"
] | Creates a Stream instance.
=== Parameters
* <tt>binary</tt> -- A binary string.
* <tt>string_endian</tt> -- Boolean. The endianness of the instance string (true for big endian, false for small endian).
* <tt>options</tt> -- A hash of parameters.
=== Options
* <tt>:index</tt> -- Fixnum. A position (offset) in the instance string where reading will start.
Decodes a section of the instance string and returns the formatted data.
The instance index is offset in accordance with the length read.
=== Notes
* If multiple numbers are decoded, these are returned in an array.
=== Parameters
* <tt>length</tt> -- Fixnum. The string length which will be decoded.
* <tt>type</tt> -- String. The type (vr) of data to decode. | [
"Creates",
"a",
"Stream",
"instance",
"."
] | a252ee91b4964116a72373aa5008f218fd695e57 | https://github.com/brainmap/nifti/blob/a252ee91b4964116a72373aa5008f218fd695e57/lib/nifti/stream.rb#L53-L81 | train |
brainmap/nifti | lib/nifti/stream.rb | NIFTI.Stream.encode | def encode(value, type)
value = [value] unless value.is_a?(Array)
return value.pack(vr_to_str(type))
end | ruby | def encode(value, type)
value = [value] unless value.is_a?(Array)
return value.pack(vr_to_str(type))
end | [
"def",
"encode",
"(",
"value",
",",
"type",
")",
"value",
"=",
"[",
"value",
"]",
"unless",
"value",
".",
"is_a?",
"(",
"Array",
")",
"return",
"value",
".",
"pack",
"(",
"vr_to_str",
"(",
"type",
")",
")",
"end"
] | Encodes a value and returns the resulting binary string.
=== Parameters
* <tt>value</tt> -- A custom value (String, Fixnum, etc..) or an array of numbers.
* <tt>type</tt> -- String. The type (vr) of data to encode. | [
"Encodes",
"a",
"value",
"and",
"returns",
"the",
"resulting",
"binary",
"string",
"."
] | a252ee91b4964116a72373aa5008f218fd695e57 | https://github.com/brainmap/nifti/blob/a252ee91b4964116a72373aa5008f218fd695e57/lib/nifti/stream.rb#L200-L203 | train |
pjotrp/bioruby-table | lib/bio-table/table_apply.rb | BioTable.TableApply.parse_row | def parse_row(line_num, line, header, column_idx, prev_fields, options)
fields = LineParser::parse(line, options[:in_format], options[:split_on])
return nil,nil if fields.compact == []
if options[:pad_fields] and fields.size < header.size
fields += [''] * (header.size - fields.size)
end
fields = Formatter::strip_quotes(fields) if @strip_quotes
fields = Formatter::transform_row_ids(@transform_ids, fields) if @transform_ids
fields = Filter::apply_column_filter(fields,column_idx)
return nil,nil if fields.compact == []
rowname = fields[0]
data_fields = fields[@first_column..-1]
if data_fields.size > 0
return nil,nil if not Validator::valid_row?(line_num, data_fields, prev_fields)
return nil,nil if not Filter::numeric(@num_filter,data_fields,header)
return nil,nil if not Filter::generic(@filter,data_fields,header)
(rowname, data_fields) = Rewrite::rewrite(@rewrite,rowname,data_fields)
end
return rowname, data_fields
end | ruby | def parse_row(line_num, line, header, column_idx, prev_fields, options)
fields = LineParser::parse(line, options[:in_format], options[:split_on])
return nil,nil if fields.compact == []
if options[:pad_fields] and fields.size < header.size
fields += [''] * (header.size - fields.size)
end
fields = Formatter::strip_quotes(fields) if @strip_quotes
fields = Formatter::transform_row_ids(@transform_ids, fields) if @transform_ids
fields = Filter::apply_column_filter(fields,column_idx)
return nil,nil if fields.compact == []
rowname = fields[0]
data_fields = fields[@first_column..-1]
if data_fields.size > 0
return nil,nil if not Validator::valid_row?(line_num, data_fields, prev_fields)
return nil,nil if not Filter::numeric(@num_filter,data_fields,header)
return nil,nil if not Filter::generic(@filter,data_fields,header)
(rowname, data_fields) = Rewrite::rewrite(@rewrite,rowname,data_fields)
end
return rowname, data_fields
end | [
"def",
"parse_row",
"(",
"line_num",
",",
"line",
",",
"header",
",",
"column_idx",
",",
"prev_fields",
",",
"options",
")",
"fields",
"=",
"LineParser",
"::",
"parse",
"(",
"line",
",",
"options",
"[",
":in_format",
"]",
",",
"options",
"[",
":split_on",
"]",
")",
"return",
"nil",
",",
"nil",
"if",
"fields",
".",
"compact",
"==",
"[",
"]",
"if",
"options",
"[",
":pad_fields",
"]",
"and",
"fields",
".",
"size",
"<",
"header",
".",
"size",
"fields",
"+=",
"[",
"''",
"]",
"*",
"(",
"header",
".",
"size",
"-",
"fields",
".",
"size",
")",
"end",
"fields",
"=",
"Formatter",
"::",
"strip_quotes",
"(",
"fields",
")",
"if",
"@strip_quotes",
"fields",
"=",
"Formatter",
"::",
"transform_row_ids",
"(",
"@transform_ids",
",",
"fields",
")",
"if",
"@transform_ids",
"fields",
"=",
"Filter",
"::",
"apply_column_filter",
"(",
"fields",
",",
"column_idx",
")",
"return",
"nil",
",",
"nil",
"if",
"fields",
".",
"compact",
"==",
"[",
"]",
"rowname",
"=",
"fields",
"[",
"0",
"]",
"data_fields",
"=",
"fields",
"[",
"@first_column",
"..",
"-",
"1",
"]",
"if",
"data_fields",
".",
"size",
">",
"0",
"return",
"nil",
",",
"nil",
"if",
"not",
"Validator",
"::",
"valid_row?",
"(",
"line_num",
",",
"data_fields",
",",
"prev_fields",
")",
"return",
"nil",
",",
"nil",
"if",
"not",
"Filter",
"::",
"numeric",
"(",
"@num_filter",
",",
"data_fields",
",",
"header",
")",
"return",
"nil",
",",
"nil",
"if",
"not",
"Filter",
"::",
"generic",
"(",
"@filter",
",",
"data_fields",
",",
"header",
")",
"(",
"rowname",
",",
"data_fields",
")",
"=",
"Rewrite",
"::",
"rewrite",
"(",
"@rewrite",
",",
"rowname",
",",
"data_fields",
")",
"end",
"return",
"rowname",
",",
"data_fields",
"end"
] | Take a line as a string and return it as a tuple of rowname and datafields | [
"Take",
"a",
"line",
"as",
"a",
"string",
"and",
"return",
"it",
"as",
"a",
"tuple",
"of",
"rowname",
"and",
"datafields"
] | e7cc97bb598743e7d69e63f16f76a2ce0ed9006d | https://github.com/pjotrp/bioruby-table/blob/e7cc97bb598743e7d69e63f16f76a2ce0ed9006d/lib/bio-table/table_apply.rb#L55-L74 | train |
flydata/elastic-mapreduce | lib/json/lexer.rb | JSON.Lexer.nextclean | def nextclean
while true
c = self.nextchar()
if (c == '/')
case self.nextchar()
when '/'
c = self.nextchar()
while c != "\n" && c != "\r" && c != "\0"
c = self.nextchar()
end
when '*'
while true
c = self.nextchar()
raise "unclosed comment" if (c == "\0")
if (c == '*')
break if (self.nextchar() == '/')
self.back()
end
end
else
self.back()
return '/';
end
elsif c == "\0" || c[0] > " "[0]
return(c)
end
end
end | ruby | def nextclean
while true
c = self.nextchar()
if (c == '/')
case self.nextchar()
when '/'
c = self.nextchar()
while c != "\n" && c != "\r" && c != "\0"
c = self.nextchar()
end
when '*'
while true
c = self.nextchar()
raise "unclosed comment" if (c == "\0")
if (c == '*')
break if (self.nextchar() == '/')
self.back()
end
end
else
self.back()
return '/';
end
elsif c == "\0" || c[0] > " "[0]
return(c)
end
end
end | [
"def",
"nextclean",
"while",
"true",
"c",
"=",
"self",
".",
"nextchar",
"(",
")",
"if",
"(",
"c",
"==",
"'/'",
")",
"case",
"self",
".",
"nextchar",
"(",
")",
"when",
"'/'",
"c",
"=",
"self",
".",
"nextchar",
"(",
")",
"while",
"c",
"!=",
"\"\\n\"",
"&&",
"c",
"!=",
"\"\\r\"",
"&&",
"c",
"!=",
"\"\\0\"",
"c",
"=",
"self",
".",
"nextchar",
"(",
")",
"end",
"when",
"'*'",
"while",
"true",
"c",
"=",
"self",
".",
"nextchar",
"(",
")",
"raise",
"\"unclosed comment\"",
"if",
"(",
"c",
"==",
"\"\\0\"",
")",
"if",
"(",
"c",
"==",
"'*'",
")",
"break",
"if",
"(",
"self",
".",
"nextchar",
"(",
")",
"==",
"'/'",
")",
"self",
".",
"back",
"(",
")",
"end",
"end",
"else",
"self",
".",
"back",
"(",
")",
"return",
"'/'",
";",
"end",
"elsif",
"c",
"==",
"\"\\0\"",
"||",
"c",
"[",
"0",
"]",
">",
"\" \"",
"[",
"0",
"]",
"return",
"(",
"c",
")",
"end",
"end",
"end"
] | Read the next n characters from the string with escape sequence
processing. | [
"Read",
"the",
"next",
"n",
"characters",
"from",
"the",
"string",
"with",
"escape",
"sequence",
"processing",
"."
] | fc96593d27c7e4797aef67ff4f8c76ee35609d57 | https://github.com/flydata/elastic-mapreduce/blob/fc96593d27c7e4797aef67ff4f8c76ee35609d57/lib/json/lexer.rb#L78-L105 | train |
flydata/elastic-mapreduce | lib/json/lexer.rb | JSON.Lexer.utf8str | def utf8str(code)
if (code & ~(0x7f)) == 0
# UCS-4 range 0x00000000 - 0x0000007F
return(code.chr)
end
buf = ""
if (code & ~(0x7ff)) == 0
# UCS-4 range 0x00000080 - 0x000007FF
buf << (0b11000000 | (code >> 6)).chr
buf << (0b10000000 | (code & 0b00111111)).chr
return(buf)
end
if (code & ~(0x000ffff)) == 0
# UCS-4 range 0x00000800 - 0x0000FFFF
buf << (0b11100000 | (code >> 12)).chr
buf << (0b10000000 | ((code >> 6) & 0b00111111)).chr
buf << (0b10000000 | (code & 0b0011111)).chr
return(buf)
end
# Not used -- JSON only has UCS-2, but for the sake
# of completeness
if (code & ~(0x1FFFFF)) == 0
# UCS-4 range 0x00010000 - 0x001FFFFF
buf << (0b11110000 | (code >> 18)).chr
buf << (0b10000000 | ((code >> 12) & 0b00111111)).chr
buf << (0b10000000 | ((code >> 6) & 0b00111111)).chr
buf << (0b10000000 | (code & 0b0011111)).chr
return(buf)
end
if (code & ~(0x03FFFFFF)) == 0
# UCS-4 range 0x00200000 - 0x03FFFFFF
buf << (0b11110000 | (code >> 24)).chr
buf << (0b10000000 | ((code >> 18) & 0b00111111)).chr
buf << (0b10000000 | ((code >> 12) & 0b00111111)).chr
buf << (0b10000000 | ((code >> 6) & 0b00111111)).chr
buf << (0b10000000 | (code & 0b0011111)).chr
return(buf)
end
# UCS-4 range 0x04000000 - 0x7FFFFFFF
buf << (0b11111000 | (code >> 30)).chr
buf << (0b10000000 | ((code >> 24) & 0b00111111)).chr
buf << (0b10000000 | ((code >> 18) & 0b00111111)).chr
buf << (0b10000000 | ((code >> 12) & 0b00111111)).chr
buf << (0b10000000 | ((code >> 6) & 0b00111111)).chr
buf << (0b10000000 | (code & 0b0011111)).chr
return(buf)
end | ruby | def utf8str(code)
if (code & ~(0x7f)) == 0
# UCS-4 range 0x00000000 - 0x0000007F
return(code.chr)
end
buf = ""
if (code & ~(0x7ff)) == 0
# UCS-4 range 0x00000080 - 0x000007FF
buf << (0b11000000 | (code >> 6)).chr
buf << (0b10000000 | (code & 0b00111111)).chr
return(buf)
end
if (code & ~(0x000ffff)) == 0
# UCS-4 range 0x00000800 - 0x0000FFFF
buf << (0b11100000 | (code >> 12)).chr
buf << (0b10000000 | ((code >> 6) & 0b00111111)).chr
buf << (0b10000000 | (code & 0b0011111)).chr
return(buf)
end
# Not used -- JSON only has UCS-2, but for the sake
# of completeness
if (code & ~(0x1FFFFF)) == 0
# UCS-4 range 0x00010000 - 0x001FFFFF
buf << (0b11110000 | (code >> 18)).chr
buf << (0b10000000 | ((code >> 12) & 0b00111111)).chr
buf << (0b10000000 | ((code >> 6) & 0b00111111)).chr
buf << (0b10000000 | (code & 0b0011111)).chr
return(buf)
end
if (code & ~(0x03FFFFFF)) == 0
# UCS-4 range 0x00200000 - 0x03FFFFFF
buf << (0b11110000 | (code >> 24)).chr
buf << (0b10000000 | ((code >> 18) & 0b00111111)).chr
buf << (0b10000000 | ((code >> 12) & 0b00111111)).chr
buf << (0b10000000 | ((code >> 6) & 0b00111111)).chr
buf << (0b10000000 | (code & 0b0011111)).chr
return(buf)
end
# UCS-4 range 0x04000000 - 0x7FFFFFFF
buf << (0b11111000 | (code >> 30)).chr
buf << (0b10000000 | ((code >> 24) & 0b00111111)).chr
buf << (0b10000000 | ((code >> 18) & 0b00111111)).chr
buf << (0b10000000 | ((code >> 12) & 0b00111111)).chr
buf << (0b10000000 | ((code >> 6) & 0b00111111)).chr
buf << (0b10000000 | (code & 0b0011111)).chr
return(buf)
end | [
"def",
"utf8str",
"(",
"code",
")",
"if",
"(",
"code",
"&",
"~",
"(",
"0x7f",
")",
")",
"==",
"0",
"return",
"(",
"code",
".",
"chr",
")",
"end",
"buf",
"=",
"\"\"",
"if",
"(",
"code",
"&",
"~",
"(",
"0x7ff",
")",
")",
"==",
"0",
"buf",
"<<",
"(",
"0b11000000",
"|",
"(",
"code",
">>",
"6",
")",
")",
".",
"chr",
"buf",
"<<",
"(",
"0b10000000",
"|",
"(",
"code",
"&",
"0b00111111",
")",
")",
".",
"chr",
"return",
"(",
"buf",
")",
"end",
"if",
"(",
"code",
"&",
"~",
"(",
"0x000ffff",
")",
")",
"==",
"0",
"buf",
"<<",
"(",
"0b11100000",
"|",
"(",
"code",
">>",
"12",
")",
")",
".",
"chr",
"buf",
"<<",
"(",
"0b10000000",
"|",
"(",
"(",
"code",
">>",
"6",
")",
"&",
"0b00111111",
")",
")",
".",
"chr",
"buf",
"<<",
"(",
"0b10000000",
"|",
"(",
"code",
"&",
"0b0011111",
")",
")",
".",
"chr",
"return",
"(",
"buf",
")",
"end",
"if",
"(",
"code",
"&",
"~",
"(",
"0x1FFFFF",
")",
")",
"==",
"0",
"buf",
"<<",
"(",
"0b11110000",
"|",
"(",
"code",
">>",
"18",
")",
")",
".",
"chr",
"buf",
"<<",
"(",
"0b10000000",
"|",
"(",
"(",
"code",
">>",
"12",
")",
"&",
"0b00111111",
")",
")",
".",
"chr",
"buf",
"<<",
"(",
"0b10000000",
"|",
"(",
"(",
"code",
">>",
"6",
")",
"&",
"0b00111111",
")",
")",
".",
"chr",
"buf",
"<<",
"(",
"0b10000000",
"|",
"(",
"code",
"&",
"0b0011111",
")",
")",
".",
"chr",
"return",
"(",
"buf",
")",
"end",
"if",
"(",
"code",
"&",
"~",
"(",
"0x03FFFFFF",
")",
")",
"==",
"0",
"buf",
"<<",
"(",
"0b11110000",
"|",
"(",
"code",
">>",
"24",
")",
")",
".",
"chr",
"buf",
"<<",
"(",
"0b10000000",
"|",
"(",
"(",
"code",
">>",
"18",
")",
"&",
"0b00111111",
")",
")",
".",
"chr",
"buf",
"<<",
"(",
"0b10000000",
"|",
"(",
"(",
"code",
">>",
"12",
")",
"&",
"0b00111111",
")",
")",
".",
"chr",
"buf",
"<<",
"(",
"0b10000000",
"|",
"(",
"(",
"code",
">>",
"6",
")",
"&",
"0b00111111",
")",
")",
".",
"chr",
"buf",
"<<",
"(",
"0b10000000",
"|",
"(",
"code",
"&",
"0b0011111",
")",
")",
".",
"chr",
"return",
"(",
"buf",
")",
"end",
"buf",
"<<",
"(",
"0b11111000",
"|",
"(",
"code",
">>",
"30",
")",
")",
".",
"chr",
"buf",
"<<",
"(",
"0b10000000",
"|",
"(",
"(",
"code",
">>",
"24",
")",
"&",
"0b00111111",
")",
")",
".",
"chr",
"buf",
"<<",
"(",
"0b10000000",
"|",
"(",
"(",
"code",
">>",
"18",
")",
"&",
"0b00111111",
")",
")",
".",
"chr",
"buf",
"<<",
"(",
"0b10000000",
"|",
"(",
"(",
"code",
">>",
"12",
")",
"&",
"0b00111111",
")",
")",
".",
"chr",
"buf",
"<<",
"(",
"0b10000000",
"|",
"(",
"(",
"code",
">>",
"6",
")",
"&",
"0b00111111",
")",
")",
".",
"chr",
"buf",
"<<",
"(",
"0b10000000",
"|",
"(",
"code",
"&",
"0b0011111",
")",
")",
".",
"chr",
"return",
"(",
"buf",
")",
"end"
] | Given a Unicode code point, return a string giving its UTF-8
representation based on RFC 2279. | [
"Given",
"a",
"Unicode",
"code",
"point",
"return",
"a",
"string",
"giving",
"its",
"UTF",
"-",
"8",
"representation",
"based",
"on",
"RFC",
"2279",
"."
] | fc96593d27c7e4797aef67ff4f8c76ee35609d57 | https://github.com/flydata/elastic-mapreduce/blob/fc96593d27c7e4797aef67ff4f8c76ee35609d57/lib/json/lexer.rb#L109-L160 | train |
flydata/elastic-mapreduce | lib/json/lexer.rb | JSON.Lexer.nextto | def nextto(regex)
buf = ""
while (true)
c = self.nextchar()
if !(regex =~ c).nil? || c == '\0' || c == '\n' || c == '\r'
self.back() if (c != '\0')
return(buf.chomp())
end
buf += c
end
end | ruby | def nextto(regex)
buf = ""
while (true)
c = self.nextchar()
if !(regex =~ c).nil? || c == '\0' || c == '\n' || c == '\r'
self.back() if (c != '\0')
return(buf.chomp())
end
buf += c
end
end | [
"def",
"nextto",
"(",
"regex",
")",
"buf",
"=",
"\"\"",
"while",
"(",
"true",
")",
"c",
"=",
"self",
".",
"nextchar",
"(",
")",
"if",
"!",
"(",
"regex",
"=~",
"c",
")",
".",
"nil?",
"||",
"c",
"==",
"'\\0'",
"||",
"c",
"==",
"'\\n'",
"||",
"c",
"==",
"'\\r'",
"self",
".",
"back",
"(",
")",
"if",
"(",
"c",
"!=",
"'\\0'",
")",
"return",
"(",
"buf",
".",
"chomp",
"(",
")",
")",
"end",
"buf",
"+=",
"c",
"end",
"end"
] | Reads the next group of characters that match a regular
expresion. | [
"Reads",
"the",
"next",
"group",
"of",
"characters",
"that",
"match",
"a",
"regular",
"expresion",
"."
] | fc96593d27c7e4797aef67ff4f8c76ee35609d57 | https://github.com/flydata/elastic-mapreduce/blob/fc96593d27c7e4797aef67ff4f8c76ee35609d57/lib/json/lexer.rb#L200-L210 | train |
flydata/elastic-mapreduce | lib/json/lexer.rb | JSON.Lexer.nextvalue | def nextvalue
c = self.nextclean
s = ""
case c
when /\"|\'/
return(self.nextstring(c))
when '{'
self.back()
return(Hash.new.from_json(self))
when '['
self.back()
return(Array.new.from_json(self))
else
buf = ""
while ((c =~ /"| |:|,|\]|\}|\/|\0/).nil?)
buf += c
c = self.nextchar()
end
self.back()
s = buf.chomp
case s
when "true"
return(true)
when "false"
return(false)
when "null"
return(nil)
when /^[0-9]|\.|-|\+/
if s =~ /[.]/ then
return Float(s)
else
return Integer(s)
end
end
if (s == "")
s = nil
end
return(s)
end
end | ruby | def nextvalue
c = self.nextclean
s = ""
case c
when /\"|\'/
return(self.nextstring(c))
when '{'
self.back()
return(Hash.new.from_json(self))
when '['
self.back()
return(Array.new.from_json(self))
else
buf = ""
while ((c =~ /"| |:|,|\]|\}|\/|\0/).nil?)
buf += c
c = self.nextchar()
end
self.back()
s = buf.chomp
case s
when "true"
return(true)
when "false"
return(false)
when "null"
return(nil)
when /^[0-9]|\.|-|\+/
if s =~ /[.]/ then
return Float(s)
else
return Integer(s)
end
end
if (s == "")
s = nil
end
return(s)
end
end | [
"def",
"nextvalue",
"c",
"=",
"self",
".",
"nextclean",
"s",
"=",
"\"\"",
"case",
"c",
"when",
"/",
"\\\"",
"\\'",
"/",
"return",
"(",
"self",
".",
"nextstring",
"(",
"c",
")",
")",
"when",
"'{'",
"self",
".",
"back",
"(",
")",
"return",
"(",
"Hash",
".",
"new",
".",
"from_json",
"(",
"self",
")",
")",
"when",
"'['",
"self",
".",
"back",
"(",
")",
"return",
"(",
"Array",
".",
"new",
".",
"from_json",
"(",
"self",
")",
")",
"else",
"buf",
"=",
"\"\"",
"while",
"(",
"(",
"c",
"=~",
"/",
"\\]",
"\\}",
"\\/",
"\\0",
"/",
")",
".",
"nil?",
")",
"buf",
"+=",
"c",
"c",
"=",
"self",
".",
"nextchar",
"(",
")",
"end",
"self",
".",
"back",
"(",
")",
"s",
"=",
"buf",
".",
"chomp",
"case",
"s",
"when",
"\"true\"",
"return",
"(",
"true",
")",
"when",
"\"false\"",
"return",
"(",
"false",
")",
"when",
"\"null\"",
"return",
"(",
"nil",
")",
"when",
"/",
"\\.",
"\\+",
"/",
"if",
"s",
"=~",
"/",
"/",
"then",
"return",
"Float",
"(",
"s",
")",
"else",
"return",
"Integer",
"(",
"s",
")",
"end",
"end",
"if",
"(",
"s",
"==",
"\"\"",
")",
"s",
"=",
"nil",
"end",
"return",
"(",
"s",
")",
"end",
"end"
] | Reads the next value from the string. This can return either a
string, a FixNum, a floating point value, a JSON array, or a
JSON object. | [
"Reads",
"the",
"next",
"value",
"from",
"the",
"string",
".",
"This",
"can",
"return",
"either",
"a",
"string",
"a",
"FixNum",
"a",
"floating",
"point",
"value",
"a",
"JSON",
"array",
"or",
"a",
"JSON",
"object",
"."
] | fc96593d27c7e4797aef67ff4f8c76ee35609d57 | https://github.com/flydata/elastic-mapreduce/blob/fc96593d27c7e4797aef67ff4f8c76ee35609d57/lib/json/lexer.rb#L215-L255 | train |
rossmeissl/bombshell | lib/bombshell/completor.rb | Bombshell.Completor.complete | def complete(fragment)
self.class.filter(shell.instance_methods).grep Regexp.new(Regexp.quote(fragment))
end | ruby | def complete(fragment)
self.class.filter(shell.instance_methods).grep Regexp.new(Regexp.quote(fragment))
end | [
"def",
"complete",
"(",
"fragment",
")",
"self",
".",
"class",
".",
"filter",
"(",
"shell",
".",
"instance_methods",
")",
".",
"grep",
"Regexp",
".",
"new",
"(",
"Regexp",
".",
"quote",
"(",
"fragment",
")",
")",
"end"
] | Provide completion for a given fragment.
@param [String] fragment the fragment to complete for | [
"Provide",
"completion",
"for",
"a",
"given",
"fragment",
"."
] | 542c855eb741095b1e88cc1bbfa1c1bacfcd9ebd | https://github.com/rossmeissl/bombshell/blob/542c855eb741095b1e88cc1bbfa1c1bacfcd9ebd/lib/bombshell/completor.rb#L13-L15 | train |
puppetlabs/beaker-openstack | lib/beaker/hypervisor/openstack.rb | Beaker.Openstack.flavor | def flavor f
@logger.debug "OpenStack: Looking up flavor '#{f}'"
@compute_client.flavors.find { |x| x.name == f } || raise("Couldn't find flavor: #{f}")
end | ruby | def flavor f
@logger.debug "OpenStack: Looking up flavor '#{f}'"
@compute_client.flavors.find { |x| x.name == f } || raise("Couldn't find flavor: #{f}")
end | [
"def",
"flavor",
"f",
"@logger",
".",
"debug",
"\"OpenStack: Looking up flavor '#{f}'\"",
"@compute_client",
".",
"flavors",
".",
"find",
"{",
"|",
"x",
"|",
"x",
".",
"name",
"==",
"f",
"}",
"||",
"raise",
"(",
"\"Couldn't find flavor: #{f}\"",
")",
"end"
] | Create a new instance of the OpenStack hypervisor object
@param [<Host>] openstack_hosts The array of OpenStack hosts to provision
@param [Hash{Symbol=>String}] options The options hash containing configuration values
@option options [String] :openstack_api_key The key to access the OpenStack instance with (required)
@option options [String] :openstack_username The username to access the OpenStack instance with (required)
@option options [String] :openstack_auth_url The URL to access the OpenStack instance with (required)
@option options [String] :openstack_tenant The tenant to access the OpenStack instance with (required)
@option options [String] :openstack_region The region that each OpenStack instance should be provisioned on (optional)
@option options [String] :openstack_network The network that each OpenStack instance should be contacted through (required)
@option options [String] :openstack_keyname The name of an existing key pair that should be auto-loaded onto each
@option options [Hash] :security_group An array of security groups to associate with the instance
OpenStack instance (optional)
@option options [String] :jenkins_build_url Added as metadata to each OpenStack instance
@option options [String] :department Added as metadata to each OpenStack instance
@option options [String] :project Added as metadata to each OpenStack instance
@option options [Integer] :timeout The amount of time to attempt execution before quiting and exiting with failure
Provided a flavor name return the OpenStack id for that flavor
@param [String] f The flavor name
@return [String] Openstack id for provided flavor name | [
"Create",
"a",
"new",
"instance",
"of",
"the",
"OpenStack",
"hypervisor",
"object"
] | 129227e23f3fbc412d5b9f6e46ced3b059af9e19 | https://github.com/puppetlabs/beaker-openstack/blob/129227e23f3fbc412d5b9f6e46ced3b059af9e19/lib/beaker/hypervisor/openstack.rb#L76-L79 | train |
puppetlabs/beaker-openstack | lib/beaker/hypervisor/openstack.rb | Beaker.Openstack.image | def image i
@logger.debug "OpenStack: Looking up image '#{i}'"
@compute_client.images.find { |x| x.name == i } || raise("Couldn't find image: #{i}")
end | ruby | def image i
@logger.debug "OpenStack: Looking up image '#{i}'"
@compute_client.images.find { |x| x.name == i } || raise("Couldn't find image: #{i}")
end | [
"def",
"image",
"i",
"@logger",
".",
"debug",
"\"OpenStack: Looking up image '#{i}'\"",
"@compute_client",
".",
"images",
".",
"find",
"{",
"|",
"x",
"|",
"x",
".",
"name",
"==",
"i",
"}",
"||",
"raise",
"(",
"\"Couldn't find image: #{i}\"",
")",
"end"
] | Provided an image name return the OpenStack id for that image
@param [String] i The image name
@return [String] Openstack id for provided image name | [
"Provided",
"an",
"image",
"name",
"return",
"the",
"OpenStack",
"id",
"for",
"that",
"image"
] | 129227e23f3fbc412d5b9f6e46ced3b059af9e19 | https://github.com/puppetlabs/beaker-openstack/blob/129227e23f3fbc412d5b9f6e46ced3b059af9e19/lib/beaker/hypervisor/openstack.rb#L84-L87 | train |
puppetlabs/beaker-openstack | lib/beaker/hypervisor/openstack.rb | Beaker.Openstack.network | def network n
@logger.debug "OpenStack: Looking up network '#{n}'"
@network_client.networks.find { |x| x.name == n } || raise("Couldn't find network: #{n}")
end | ruby | def network n
@logger.debug "OpenStack: Looking up network '#{n}'"
@network_client.networks.find { |x| x.name == n } || raise("Couldn't find network: #{n}")
end | [
"def",
"network",
"n",
"@logger",
".",
"debug",
"\"OpenStack: Looking up network '#{n}'\"",
"@network_client",
".",
"networks",
".",
"find",
"{",
"|",
"x",
"|",
"x",
".",
"name",
"==",
"n",
"}",
"||",
"raise",
"(",
"\"Couldn't find network: #{n}\"",
")",
"end"
] | Provided a network name return the OpenStack id for that network
@param [String] n The network name
@return [String] Openstack id for provided network name | [
"Provided",
"a",
"network",
"name",
"return",
"the",
"OpenStack",
"id",
"for",
"that",
"network"
] | 129227e23f3fbc412d5b9f6e46ced3b059af9e19 | https://github.com/puppetlabs/beaker-openstack/blob/129227e23f3fbc412d5b9f6e46ced3b059af9e19/lib/beaker/hypervisor/openstack.rb#L92-L95 | train |
puppetlabs/beaker-openstack | lib/beaker/hypervisor/openstack.rb | Beaker.Openstack.security_groups | def security_groups sgs
for sg in sgs
@logger.debug "Openstack: Looking up security group '#{sg}'"
@compute_client.security_groups.find { |x| x.name == sg } || raise("Couldn't find security group: #{sg}")
sgs
end
end | ruby | def security_groups sgs
for sg in sgs
@logger.debug "Openstack: Looking up security group '#{sg}'"
@compute_client.security_groups.find { |x| x.name == sg } || raise("Couldn't find security group: #{sg}")
sgs
end
end | [
"def",
"security_groups",
"sgs",
"for",
"sg",
"in",
"sgs",
"@logger",
".",
"debug",
"\"Openstack: Looking up security group '#{sg}'\"",
"@compute_client",
".",
"security_groups",
".",
"find",
"{",
"|",
"x",
"|",
"x",
".",
"name",
"==",
"sg",
"}",
"||",
"raise",
"(",
"\"Couldn't find security group: #{sg}\"",
")",
"sgs",
"end",
"end"
] | Provided an array of security groups return that array if all
security groups are present
@param [Array] sgs The array of security group names
@return [Array] The array of security group names | [
"Provided",
"an",
"array",
"of",
"security",
"groups",
"return",
"that",
"array",
"if",
"all",
"security",
"groups",
"are",
"present"
] | 129227e23f3fbc412d5b9f6e46ced3b059af9e19 | https://github.com/puppetlabs/beaker-openstack/blob/129227e23f3fbc412d5b9f6e46ced3b059af9e19/lib/beaker/hypervisor/openstack.rb#L101-L107 | train |
puppetlabs/beaker-openstack | lib/beaker/hypervisor/openstack.rb | Beaker.Openstack.provision_storage | def provision_storage host, vm
volumes = get_volumes(host)
if !volumes.empty?
# Lazily create the volume client if needed
volume_client_create
volumes.keys.each_with_index do |volume, index|
@logger.debug "Creating volume #{volume} for OpenStack host #{host.name}"
# The node defintion file defines volume sizes in MB (due to precedent
# with the vagrant virtualbox implementation) however OpenStack requires
# this translating into GB
openstack_size = volumes[volume]['size'].to_i / 1000
# Set up the volume creation arguments
args = {
:size => openstack_size,
:description => "Beaker volume: host=#{host.name} volume=#{volume}",
}
# Between version 1 and subsequent versions the API was updated to
# rename 'display_name' to just 'name' for better consistency
if get_volume_api_version == 1
args[:display_name] = volume
else
args[:name] = volume
end
# Create the volume and wait for it to become available
vol = @volume_client.volumes.create(**args)
vol.wait_for { ready? }
# Fog needs a device name to attach as, so invent one. The guest
# doesn't pay any attention to this
device = "/dev/vd#{('b'.ord + index).chr}"
vm.attach_volume(vol.id, device)
end
end
end | ruby | def provision_storage host, vm
volumes = get_volumes(host)
if !volumes.empty?
# Lazily create the volume client if needed
volume_client_create
volumes.keys.each_with_index do |volume, index|
@logger.debug "Creating volume #{volume} for OpenStack host #{host.name}"
# The node defintion file defines volume sizes in MB (due to precedent
# with the vagrant virtualbox implementation) however OpenStack requires
# this translating into GB
openstack_size = volumes[volume]['size'].to_i / 1000
# Set up the volume creation arguments
args = {
:size => openstack_size,
:description => "Beaker volume: host=#{host.name} volume=#{volume}",
}
# Between version 1 and subsequent versions the API was updated to
# rename 'display_name' to just 'name' for better consistency
if get_volume_api_version == 1
args[:display_name] = volume
else
args[:name] = volume
end
# Create the volume and wait for it to become available
vol = @volume_client.volumes.create(**args)
vol.wait_for { ready? }
# Fog needs a device name to attach as, so invent one. The guest
# doesn't pay any attention to this
device = "/dev/vd#{('b'.ord + index).chr}"
vm.attach_volume(vol.id, device)
end
end
end | [
"def",
"provision_storage",
"host",
",",
"vm",
"volumes",
"=",
"get_volumes",
"(",
"host",
")",
"if",
"!",
"volumes",
".",
"empty?",
"volume_client_create",
"volumes",
".",
"keys",
".",
"each_with_index",
"do",
"|",
"volume",
",",
"index",
"|",
"@logger",
".",
"debug",
"\"Creating volume #{volume} for OpenStack host #{host.name}\"",
"openstack_size",
"=",
"volumes",
"[",
"volume",
"]",
"[",
"'size'",
"]",
".",
"to_i",
"/",
"1000",
"args",
"=",
"{",
":size",
"=>",
"openstack_size",
",",
":description",
"=>",
"\"Beaker volume: host=#{host.name} volume=#{volume}\"",
",",
"}",
"if",
"get_volume_api_version",
"==",
"1",
"args",
"[",
":display_name",
"]",
"=",
"volume",
"else",
"args",
"[",
":name",
"]",
"=",
"volume",
"end",
"vol",
"=",
"@volume_client",
".",
"volumes",
".",
"create",
"(",
"**",
"args",
")",
"vol",
".",
"wait_for",
"{",
"ready?",
"}",
"device",
"=",
"\"/dev/vd#{('b'.ord + index).chr}\"",
"vm",
".",
"attach_volume",
"(",
"vol",
".",
"id",
",",
"device",
")",
"end",
"end",
"end"
] | Create and attach dynamic volumes
Creates an array of volumes and attaches them to the current host.
The host bus type is determined by the image type, so by default
devices appear as /dev/vdb, /dev/vdc etc. Setting the glance
properties hw_disk_bus=scsi, hw_scsi_model=virtio-scsi will present
them as /dev/sdb, /dev/sdc (or 2:0:0:1, 2:0:0:2 in SCSI addresses)
@param host [Hash] thet current host defined in the nodeset
@param vm [Fog::Compute::OpenStack::Server] the server to attach to | [
"Create",
"and",
"attach",
"dynamic",
"volumes"
] | 129227e23f3fbc412d5b9f6e46ced3b059af9e19 | https://github.com/puppetlabs/beaker-openstack/blob/129227e23f3fbc412d5b9f6e46ced3b059af9e19/lib/beaker/hypervisor/openstack.rb#L148-L185 | train |
puppetlabs/beaker-openstack | lib/beaker/hypervisor/openstack.rb | Beaker.Openstack.cleanup_storage | def cleanup_storage vm
vm.volumes.each do |vol|
@logger.debug "Deleting volume #{vol.name} for OpenStack host #{vm.name}"
vm.detach_volume(vol.id)
vol.wait_for { ready? }
vol.destroy
end
end | ruby | def cleanup_storage vm
vm.volumes.each do |vol|
@logger.debug "Deleting volume #{vol.name} for OpenStack host #{vm.name}"
vm.detach_volume(vol.id)
vol.wait_for { ready? }
vol.destroy
end
end | [
"def",
"cleanup_storage",
"vm",
"vm",
".",
"volumes",
".",
"each",
"do",
"|",
"vol",
"|",
"@logger",
".",
"debug",
"\"Deleting volume #{vol.name} for OpenStack host #{vm.name}\"",
"vm",
".",
"detach_volume",
"(",
"vol",
".",
"id",
")",
"vol",
".",
"wait_for",
"{",
"ready?",
"}",
"vol",
".",
"destroy",
"end",
"end"
] | Detach and delete guest volumes
@param vm [Fog::Compute::OpenStack::Server] the server to detach from | [
"Detach",
"and",
"delete",
"guest",
"volumes"
] | 129227e23f3fbc412d5b9f6e46ced3b059af9e19 | https://github.com/puppetlabs/beaker-openstack/blob/129227e23f3fbc412d5b9f6e46ced3b059af9e19/lib/beaker/hypervisor/openstack.rb#L189-L196 | train |
puppetlabs/beaker-openstack | lib/beaker/hypervisor/openstack.rb | Beaker.Openstack.get_ip | def get_ip
begin
@logger.debug "Creating IP"
ip = @compute_client.addresses.create
rescue Fog::Compute::OpenStack::NotFound
# If there are no more floating IP addresses, allocate a
# new one and try again.
@compute_client.allocate_address(@options[:floating_ip_pool])
ip = @compute_client.addresses.find { |ip| ip.instance_id.nil? }
end
raise 'Could not find or allocate an address' if not ip
ip
end | ruby | def get_ip
begin
@logger.debug "Creating IP"
ip = @compute_client.addresses.create
rescue Fog::Compute::OpenStack::NotFound
# If there are no more floating IP addresses, allocate a
# new one and try again.
@compute_client.allocate_address(@options[:floating_ip_pool])
ip = @compute_client.addresses.find { |ip| ip.instance_id.nil? }
end
raise 'Could not find or allocate an address' if not ip
ip
end | [
"def",
"get_ip",
"begin",
"@logger",
".",
"debug",
"\"Creating IP\"",
"ip",
"=",
"@compute_client",
".",
"addresses",
".",
"create",
"rescue",
"Fog",
"::",
"Compute",
"::",
"OpenStack",
"::",
"NotFound",
"@compute_client",
".",
"allocate_address",
"(",
"@options",
"[",
":floating_ip_pool",
"]",
")",
"ip",
"=",
"@compute_client",
".",
"addresses",
".",
"find",
"{",
"|",
"ip",
"|",
"ip",
".",
"instance_id",
".",
"nil?",
"}",
"end",
"raise",
"'Could not find or allocate an address'",
"if",
"not",
"ip",
"ip",
"end"
] | Get a floating IP address to associate with the instance, try
to allocate a new one from the specified pool if none are available | [
"Get",
"a",
"floating",
"IP",
"address",
"to",
"associate",
"with",
"the",
"instance",
"try",
"to",
"allocate",
"a",
"new",
"one",
"from",
"the",
"specified",
"pool",
"if",
"none",
"are",
"available"
] | 129227e23f3fbc412d5b9f6e46ced3b059af9e19 | https://github.com/puppetlabs/beaker-openstack/blob/129227e23f3fbc412d5b9f6e46ced3b059af9e19/lib/beaker/hypervisor/openstack.rb#L200-L212 | train |
puppetlabs/beaker-openstack | lib/beaker/hypervisor/openstack.rb | Beaker.Openstack.provision | def provision
@logger.notify "Provisioning OpenStack"
@hosts.each do |host|
ip = get_ip
hostname = ip.ip.gsub('.','-')
host[:vmhostname] = hostname + '.rfc1918.puppetlabs.net'
create_or_associate_keypair(host, hostname)
@logger.debug "Provisioning #{host.name} (#{host[:vmhostname]})"
options = {
:flavor_ref => flavor(host[:flavor]).id,
:image_ref => image(host[:image]).id,
:nics => [ {'net_id' => network(@options[:openstack_network]).id } ],
:name => host[:vmhostname],
:hostname => host[:vmhostname],
:user_data => host[:user_data] || "#cloud-config\nmanage_etc_hosts: true\n",
:key_name => host[:keyname],
}
options[:security_groups] = security_groups(@options[:security_group]) unless @options[:security_group].nil?
vm = @compute_client.servers.create(options)
#wait for the new instance to start up
try = 1
attempts = @options[:timeout].to_i / SLEEPWAIT
while try <= attempts
begin
vm.wait_for(5) { ready? }
break
rescue Fog::Errors::TimeoutError => e
if try >= attempts
@logger.debug "Failed to connect to new OpenStack instance #{host.name} (#{host[:vmhostname]})"
raise e
end
@logger.debug "Timeout connecting to instance #{host.name} (#{host[:vmhostname]}), trying again..."
end
sleep SLEEPWAIT
try += 1
end
# Associate a public IP to the server
ip.server = vm
host[:ip] = ip.ip
@logger.debug "OpenStack host #{host.name} (#{host[:vmhostname]}) assigned ip: #{host[:ip]}"
#set metadata
vm.metadata.update({:jenkins_build_url => @options[:jenkins_build_url].to_s,
:department => @options[:department].to_s,
:project => @options[:project].to_s })
@vms << vm
# Wait for the host to accept ssh logins
host.wait_for_port(22)
#enable root if user is not root
enable_root(host)
provision_storage(host, vm) if @options[:openstack_volume_support]
@logger.notify "OpenStack Volume Support Disabled, can't provision volumes" if not @options[:openstack_volume_support]
end
hack_etc_hosts @hosts, @options
end | ruby | def provision
@logger.notify "Provisioning OpenStack"
@hosts.each do |host|
ip = get_ip
hostname = ip.ip.gsub('.','-')
host[:vmhostname] = hostname + '.rfc1918.puppetlabs.net'
create_or_associate_keypair(host, hostname)
@logger.debug "Provisioning #{host.name} (#{host[:vmhostname]})"
options = {
:flavor_ref => flavor(host[:flavor]).id,
:image_ref => image(host[:image]).id,
:nics => [ {'net_id' => network(@options[:openstack_network]).id } ],
:name => host[:vmhostname],
:hostname => host[:vmhostname],
:user_data => host[:user_data] || "#cloud-config\nmanage_etc_hosts: true\n",
:key_name => host[:keyname],
}
options[:security_groups] = security_groups(@options[:security_group]) unless @options[:security_group].nil?
vm = @compute_client.servers.create(options)
#wait for the new instance to start up
try = 1
attempts = @options[:timeout].to_i / SLEEPWAIT
while try <= attempts
begin
vm.wait_for(5) { ready? }
break
rescue Fog::Errors::TimeoutError => e
if try >= attempts
@logger.debug "Failed to connect to new OpenStack instance #{host.name} (#{host[:vmhostname]})"
raise e
end
@logger.debug "Timeout connecting to instance #{host.name} (#{host[:vmhostname]}), trying again..."
end
sleep SLEEPWAIT
try += 1
end
# Associate a public IP to the server
ip.server = vm
host[:ip] = ip.ip
@logger.debug "OpenStack host #{host.name} (#{host[:vmhostname]}) assigned ip: #{host[:ip]}"
#set metadata
vm.metadata.update({:jenkins_build_url => @options[:jenkins_build_url].to_s,
:department => @options[:department].to_s,
:project => @options[:project].to_s })
@vms << vm
# Wait for the host to accept ssh logins
host.wait_for_port(22)
#enable root if user is not root
enable_root(host)
provision_storage(host, vm) if @options[:openstack_volume_support]
@logger.notify "OpenStack Volume Support Disabled, can't provision volumes" if not @options[:openstack_volume_support]
end
hack_etc_hosts @hosts, @options
end | [
"def",
"provision",
"@logger",
".",
"notify",
"\"Provisioning OpenStack\"",
"@hosts",
".",
"each",
"do",
"|",
"host",
"|",
"ip",
"=",
"get_ip",
"hostname",
"=",
"ip",
".",
"ip",
".",
"gsub",
"(",
"'.'",
",",
"'-'",
")",
"host",
"[",
":vmhostname",
"]",
"=",
"hostname",
"+",
"'.rfc1918.puppetlabs.net'",
"create_or_associate_keypair",
"(",
"host",
",",
"hostname",
")",
"@logger",
".",
"debug",
"\"Provisioning #{host.name} (#{host[:vmhostname]})\"",
"options",
"=",
"{",
":flavor_ref",
"=>",
"flavor",
"(",
"host",
"[",
":flavor",
"]",
")",
".",
"id",
",",
":image_ref",
"=>",
"image",
"(",
"host",
"[",
":image",
"]",
")",
".",
"id",
",",
":nics",
"=>",
"[",
"{",
"'net_id'",
"=>",
"network",
"(",
"@options",
"[",
":openstack_network",
"]",
")",
".",
"id",
"}",
"]",
",",
":name",
"=>",
"host",
"[",
":vmhostname",
"]",
",",
":hostname",
"=>",
"host",
"[",
":vmhostname",
"]",
",",
":user_data",
"=>",
"host",
"[",
":user_data",
"]",
"||",
"\"#cloud-config\\nmanage_etc_hosts: true\\n\"",
",",
":key_name",
"=>",
"host",
"[",
":keyname",
"]",
",",
"}",
"options",
"[",
":security_groups",
"]",
"=",
"security_groups",
"(",
"@options",
"[",
":security_group",
"]",
")",
"unless",
"@options",
"[",
":security_group",
"]",
".",
"nil?",
"vm",
"=",
"@compute_client",
".",
"servers",
".",
"create",
"(",
"options",
")",
"try",
"=",
"1",
"attempts",
"=",
"@options",
"[",
":timeout",
"]",
".",
"to_i",
"/",
"SLEEPWAIT",
"while",
"try",
"<=",
"attempts",
"begin",
"vm",
".",
"wait_for",
"(",
"5",
")",
"{",
"ready?",
"}",
"break",
"rescue",
"Fog",
"::",
"Errors",
"::",
"TimeoutError",
"=>",
"e",
"if",
"try",
">=",
"attempts",
"@logger",
".",
"debug",
"\"Failed to connect to new OpenStack instance #{host.name} (#{host[:vmhostname]})\"",
"raise",
"e",
"end",
"@logger",
".",
"debug",
"\"Timeout connecting to instance #{host.name} (#{host[:vmhostname]}), trying again...\"",
"end",
"sleep",
"SLEEPWAIT",
"try",
"+=",
"1",
"end",
"ip",
".",
"server",
"=",
"vm",
"host",
"[",
":ip",
"]",
"=",
"ip",
".",
"ip",
"@logger",
".",
"debug",
"\"OpenStack host #{host.name} (#{host[:vmhostname]}) assigned ip: #{host[:ip]}\"",
"vm",
".",
"metadata",
".",
"update",
"(",
"{",
":jenkins_build_url",
"=>",
"@options",
"[",
":jenkins_build_url",
"]",
".",
"to_s",
",",
":department",
"=>",
"@options",
"[",
":department",
"]",
".",
"to_s",
",",
":project",
"=>",
"@options",
"[",
":project",
"]",
".",
"to_s",
"}",
")",
"@vms",
"<<",
"vm",
"host",
".",
"wait_for_port",
"(",
"22",
")",
"enable_root",
"(",
"host",
")",
"provision_storage",
"(",
"host",
",",
"vm",
")",
"if",
"@options",
"[",
":openstack_volume_support",
"]",
"@logger",
".",
"notify",
"\"OpenStack Volume Support Disabled, can't provision volumes\"",
"if",
"not",
"@options",
"[",
":openstack_volume_support",
"]",
"end",
"hack_etc_hosts",
"@hosts",
",",
"@options",
"end"
] | Create new instances in OpenStack | [
"Create",
"new",
"instances",
"in",
"OpenStack"
] | 129227e23f3fbc412d5b9f6e46ced3b059af9e19 | https://github.com/puppetlabs/beaker-openstack/blob/129227e23f3fbc412d5b9f6e46ced3b059af9e19/lib/beaker/hypervisor/openstack.rb#L215-L279 | train |
puppetlabs/beaker-openstack | lib/beaker/hypervisor/openstack.rb | Beaker.Openstack.cleanup | def cleanup
@logger.notify "Cleaning up OpenStack"
@vms.each do |vm|
cleanup_storage(vm) if @options[:openstack_volume_support]
@logger.debug "Release floating IPs for OpenStack host #{vm.name}"
floating_ips = vm.all_addresses # fetch and release its floating IPs
floating_ips.each do |address|
@compute_client.disassociate_address(vm.id, address['ip'])
@compute_client.release_address(address['id'])
end
@logger.debug "Destroying OpenStack host #{vm.name}"
vm.destroy
if @options[:openstack_keyname].nil?
@logger.debug "Deleting random keypair"
@compute_client.delete_key_pair vm.key_name
end
end
end | ruby | def cleanup
@logger.notify "Cleaning up OpenStack"
@vms.each do |vm|
cleanup_storage(vm) if @options[:openstack_volume_support]
@logger.debug "Release floating IPs for OpenStack host #{vm.name}"
floating_ips = vm.all_addresses # fetch and release its floating IPs
floating_ips.each do |address|
@compute_client.disassociate_address(vm.id, address['ip'])
@compute_client.release_address(address['id'])
end
@logger.debug "Destroying OpenStack host #{vm.name}"
vm.destroy
if @options[:openstack_keyname].nil?
@logger.debug "Deleting random keypair"
@compute_client.delete_key_pair vm.key_name
end
end
end | [
"def",
"cleanup",
"@logger",
".",
"notify",
"\"Cleaning up OpenStack\"",
"@vms",
".",
"each",
"do",
"|",
"vm",
"|",
"cleanup_storage",
"(",
"vm",
")",
"if",
"@options",
"[",
":openstack_volume_support",
"]",
"@logger",
".",
"debug",
"\"Release floating IPs for OpenStack host #{vm.name}\"",
"floating_ips",
"=",
"vm",
".",
"all_addresses",
"floating_ips",
".",
"each",
"do",
"|",
"address",
"|",
"@compute_client",
".",
"disassociate_address",
"(",
"vm",
".",
"id",
",",
"address",
"[",
"'ip'",
"]",
")",
"@compute_client",
".",
"release_address",
"(",
"address",
"[",
"'id'",
"]",
")",
"end",
"@logger",
".",
"debug",
"\"Destroying OpenStack host #{vm.name}\"",
"vm",
".",
"destroy",
"if",
"@options",
"[",
":openstack_keyname",
"]",
".",
"nil?",
"@logger",
".",
"debug",
"\"Deleting random keypair\"",
"@compute_client",
".",
"delete_key_pair",
"vm",
".",
"key_name",
"end",
"end",
"end"
] | Destroy any OpenStack instances | [
"Destroy",
"any",
"OpenStack",
"instances"
] | 129227e23f3fbc412d5b9f6e46ced3b059af9e19 | https://github.com/puppetlabs/beaker-openstack/blob/129227e23f3fbc412d5b9f6e46ced3b059af9e19/lib/beaker/hypervisor/openstack.rb#L282-L299 | train |
puppetlabs/beaker-openstack | lib/beaker/hypervisor/openstack.rb | Beaker.Openstack.create_or_associate_keypair | def create_or_associate_keypair(host, keyname)
if @options[:openstack_keyname]
@logger.debug "Adding optional key_name #{@options[:openstack_keyname]} to #{host.name} (#{host[:vmhostname]})"
keyname = @options[:openstack_keyname]
else
@logger.debug "Generate a new rsa key"
# There is apparently an error that can occur when generating RSA keys, probably
# due to some timing issue, probably similar to the issue described here:
# https://github.com/negativecode/vines/issues/34
# In order to mitigate this error, we will simply try again up to three times, and
# then fail if we continue to error out.
begin
retries ||= 0
key = OpenSSL::PKey::RSA.new 2048
rescue OpenSSL::PKey::RSAError => e
retries += 1
if retries > 2
@logger.notify "error generating RSA key #{retries} times, exiting"
raise e
end
retry
end
type = key.ssh_type
data = [ key.to_blob ].pack('m0')
@logger.debug "Creating Openstack keypair '#{keyname}' for public key '#{type} #{data}'"
@compute_client.create_key_pair keyname, "#{type} #{data}"
host['ssh'][:key_data] = [ key.to_pem ]
end
host[:keyname] = keyname
end | ruby | def create_or_associate_keypair(host, keyname)
if @options[:openstack_keyname]
@logger.debug "Adding optional key_name #{@options[:openstack_keyname]} to #{host.name} (#{host[:vmhostname]})"
keyname = @options[:openstack_keyname]
else
@logger.debug "Generate a new rsa key"
# There is apparently an error that can occur when generating RSA keys, probably
# due to some timing issue, probably similar to the issue described here:
# https://github.com/negativecode/vines/issues/34
# In order to mitigate this error, we will simply try again up to three times, and
# then fail if we continue to error out.
begin
retries ||= 0
key = OpenSSL::PKey::RSA.new 2048
rescue OpenSSL::PKey::RSAError => e
retries += 1
if retries > 2
@logger.notify "error generating RSA key #{retries} times, exiting"
raise e
end
retry
end
type = key.ssh_type
data = [ key.to_blob ].pack('m0')
@logger.debug "Creating Openstack keypair '#{keyname}' for public key '#{type} #{data}'"
@compute_client.create_key_pair keyname, "#{type} #{data}"
host['ssh'][:key_data] = [ key.to_pem ]
end
host[:keyname] = keyname
end | [
"def",
"create_or_associate_keypair",
"(",
"host",
",",
"keyname",
")",
"if",
"@options",
"[",
":openstack_keyname",
"]",
"@logger",
".",
"debug",
"\"Adding optional key_name #{@options[:openstack_keyname]} to #{host.name} (#{host[:vmhostname]})\"",
"keyname",
"=",
"@options",
"[",
":openstack_keyname",
"]",
"else",
"@logger",
".",
"debug",
"\"Generate a new rsa key\"",
"begin",
"retries",
"||=",
"0",
"key",
"=",
"OpenSSL",
"::",
"PKey",
"::",
"RSA",
".",
"new",
"2048",
"rescue",
"OpenSSL",
"::",
"PKey",
"::",
"RSAError",
"=>",
"e",
"retries",
"+=",
"1",
"if",
"retries",
">",
"2",
"@logger",
".",
"notify",
"\"error generating RSA key #{retries} times, exiting\"",
"raise",
"e",
"end",
"retry",
"end",
"type",
"=",
"key",
".",
"ssh_type",
"data",
"=",
"[",
"key",
".",
"to_blob",
"]",
".",
"pack",
"(",
"'m0'",
")",
"@logger",
".",
"debug",
"\"Creating Openstack keypair '#{keyname}' for public key '#{type} #{data}'\"",
"@compute_client",
".",
"create_key_pair",
"keyname",
",",
"\"#{type} #{data}\"",
"host",
"[",
"'ssh'",
"]",
"[",
":key_data",
"]",
"=",
"[",
"key",
".",
"to_pem",
"]",
"end",
"host",
"[",
":keyname",
"]",
"=",
"keyname",
"end"
] | Get key_name from options or generate a new rsa key and add it to
OpenStack keypairs
@param [Host] host The OpenStack host to provision
@api private | [
"Get",
"key_name",
"from",
"options",
"or",
"generate",
"a",
"new",
"rsa",
"key",
"and",
"add",
"it",
"to",
"OpenStack",
"keypairs"
] | 129227e23f3fbc412d5b9f6e46ced3b059af9e19 | https://github.com/puppetlabs/beaker-openstack/blob/129227e23f3fbc412d5b9f6e46ced3b059af9e19/lib/beaker/hypervisor/openstack.rb#L329-L361 | train |
ryw/pinboard | lib/pinboard/client.rb | Pinboard.Client.get | def get(params = {})
params[:dt] = params[:dt].to_date.to_s if params.is_a? Time
params[:meta] = params[:meta] ? 'yes' : 'no' if params.has_key?(:meta)
options = create_params(params)
posts = self.class.get('/posts/get', options)['posts']['post']
posts = [] if posts.nil?
posts = [posts] if posts.class != Array
posts.map { |p| Post.new(Util.symbolize_keys(p)) }
end | ruby | def get(params = {})
params[:dt] = params[:dt].to_date.to_s if params.is_a? Time
params[:meta] = params[:meta] ? 'yes' : 'no' if params.has_key?(:meta)
options = create_params(params)
posts = self.class.get('/posts/get', options)['posts']['post']
posts = [] if posts.nil?
posts = [posts] if posts.class != Array
posts.map { |p| Post.new(Util.symbolize_keys(p)) }
end | [
"def",
"get",
"(",
"params",
"=",
"{",
"}",
")",
"params",
"[",
":dt",
"]",
"=",
"params",
"[",
":dt",
"]",
".",
"to_date",
".",
"to_s",
"if",
"params",
".",
"is_a?",
"Time",
"params",
"[",
":meta",
"]",
"=",
"params",
"[",
":meta",
"]",
"?",
"'yes'",
":",
"'no'",
"if",
"params",
".",
"has_key?",
"(",
":meta",
")",
"options",
"=",
"create_params",
"(",
"params",
")",
"posts",
"=",
"self",
".",
"class",
".",
"get",
"(",
"'/posts/get'",
",",
"options",
")",
"[",
"'posts'",
"]",
"[",
"'post'",
"]",
"posts",
"=",
"[",
"]",
"if",
"posts",
".",
"nil?",
"posts",
"=",
"[",
"posts",
"]",
"if",
"posts",
".",
"class",
"!=",
"Array",
"posts",
".",
"map",
"{",
"|",
"p",
"|",
"Post",
".",
"new",
"(",
"Util",
".",
"symbolize_keys",
"(",
"p",
")",
")",
"}",
"end"
] | Returns one or more posts on a single day matching the arguments.
If no date or url is given, date of most recent bookmark will be used.
@option params [String] :tag filter by up to three tags
@option params [Time] :dt return results bookmarked on this day
@option params [String] :url return bookmark for this URL
@option params [Boolean] :meta include a change detection signature in a meta attribute
@return [Array<Post>] the list of bookmarks | [
"Returns",
"one",
"or",
"more",
"posts",
"on",
"a",
"single",
"day",
"matching",
"the",
"arguments",
".",
"If",
"no",
"date",
"or",
"url",
"is",
"given",
"date",
"of",
"most",
"recent",
"bookmark",
"will",
"be",
"used",
"."
] | 65d3b2f38b56d0f9f236d0041f4a697157905cf9 | https://github.com/ryw/pinboard/blob/65d3b2f38b56d0f9f236d0041f4a697157905cf9/lib/pinboard/client.rb#L57-L65 | train |
ryw/pinboard | lib/pinboard/client.rb | Pinboard.Client.suggest | def suggest(url)
options = create_params({url: url})
suggested = self.class.get('/posts/suggest', options)['suggested']
popular = suggested['popular']
popular = [] if popular.nil?
popular = [popular] if popular.class != Array
recommended = suggested['recommended']
recommended = [] if recommended.nil?
recommended = [recommended] if recommended.class != Array
{:popular => popular, :recommended => recommended}
end | ruby | def suggest(url)
options = create_params({url: url})
suggested = self.class.get('/posts/suggest', options)['suggested']
popular = suggested['popular']
popular = [] if popular.nil?
popular = [popular] if popular.class != Array
recommended = suggested['recommended']
recommended = [] if recommended.nil?
recommended = [recommended] if recommended.class != Array
{:popular => popular, :recommended => recommended}
end | [
"def",
"suggest",
"(",
"url",
")",
"options",
"=",
"create_params",
"(",
"{",
"url",
":",
"url",
"}",
")",
"suggested",
"=",
"self",
".",
"class",
".",
"get",
"(",
"'/posts/suggest'",
",",
"options",
")",
"[",
"'suggested'",
"]",
"popular",
"=",
"suggested",
"[",
"'popular'",
"]",
"popular",
"=",
"[",
"]",
"if",
"popular",
".",
"nil?",
"popular",
"=",
"[",
"popular",
"]",
"if",
"popular",
".",
"class",
"!=",
"Array",
"recommended",
"=",
"suggested",
"[",
"'recommended'",
"]",
"recommended",
"=",
"[",
"]",
"if",
"recommended",
".",
"nil?",
"recommended",
"=",
"[",
"recommended",
"]",
"if",
"recommended",
".",
"class",
"!=",
"Array",
"{",
":popular",
"=>",
"popular",
",",
":recommended",
"=>",
"recommended",
"}",
"end"
] | Returns a list of popular tags and recommended tags for a given URL.
Popular tags are tags used site-wide for the url; recommended tags
are drawn from the user's own tags.
@param [String] url
@return [Hash<String, Array>] | [
"Returns",
"a",
"list",
"of",
"popular",
"tags",
"and",
"recommended",
"tags",
"for",
"a",
"given",
"URL",
".",
"Popular",
"tags",
"are",
"tags",
"used",
"site",
"-",
"wide",
"for",
"the",
"url",
";",
"recommended",
"tags",
"are",
"drawn",
"from",
"the",
"user",
"s",
"own",
"tags",
"."
] | 65d3b2f38b56d0f9f236d0041f4a697157905cf9 | https://github.com/ryw/pinboard/blob/65d3b2f38b56d0f9f236d0041f4a697157905cf9/lib/pinboard/client.rb#L73-L85 | train |
ryw/pinboard | lib/pinboard/client.rb | Pinboard.Client.recent | def recent(params={})
options = create_params(params)
posts = self.class.get('/posts/recent', options)['posts']['post']
posts = [] if posts.nil?
posts = [*posts]
posts.map { |p| Post.new(Util.symbolize_keys(p)) }
end | ruby | def recent(params={})
options = create_params(params)
posts = self.class.get('/posts/recent', options)['posts']['post']
posts = [] if posts.nil?
posts = [*posts]
posts.map { |p| Post.new(Util.symbolize_keys(p)) }
end | [
"def",
"recent",
"(",
"params",
"=",
"{",
"}",
")",
"options",
"=",
"create_params",
"(",
"params",
")",
"posts",
"=",
"self",
".",
"class",
".",
"get",
"(",
"'/posts/recent'",
",",
"options",
")",
"[",
"'posts'",
"]",
"[",
"'post'",
"]",
"posts",
"=",
"[",
"]",
"if",
"posts",
".",
"nil?",
"posts",
"=",
"[",
"*",
"posts",
"]",
"posts",
".",
"map",
"{",
"|",
"p",
"|",
"Post",
".",
"new",
"(",
"Util",
".",
"symbolize_keys",
"(",
"p",
")",
")",
"}",
"end"
] | Returns a list of the user's most recent posts, filtered by tag.
@param <Hash> params the options to filter current posts
@option params [String] :tag filter by up to three tags
@option params [String] :count Number of results to return.
Default is 15, max is 100
@return [Array<Post>] the list of recent posts | [
"Returns",
"a",
"list",
"of",
"the",
"user",
"s",
"most",
"recent",
"posts",
"filtered",
"by",
"tag",
"."
] | 65d3b2f38b56d0f9f236d0041f4a697157905cf9 | https://github.com/ryw/pinboard/blob/65d3b2f38b56d0f9f236d0041f4a697157905cf9/lib/pinboard/client.rb#L150-L156 | train |
ryw/pinboard | lib/pinboard/client.rb | Pinboard.Client.dates | def dates(tag=nil)
params = {}
params[:tag] = tag if tag
options = create_params(params)
dates = self.class.get('/posts/dates', options)['dates']['date']
dates = [] if dates.nil?
dates = [*dates]
dates.each_with_object({}) { |value, hash|
hash[value["date"]] = value["count"].to_i
}
end | ruby | def dates(tag=nil)
params = {}
params[:tag] = tag if tag
options = create_params(params)
dates = self.class.get('/posts/dates', options)['dates']['date']
dates = [] if dates.nil?
dates = [*dates]
dates.each_with_object({}) { |value, hash|
hash[value["date"]] = value["count"].to_i
}
end | [
"def",
"dates",
"(",
"tag",
"=",
"nil",
")",
"params",
"=",
"{",
"}",
"params",
"[",
":tag",
"]",
"=",
"tag",
"if",
"tag",
"options",
"=",
"create_params",
"(",
"params",
")",
"dates",
"=",
"self",
".",
"class",
".",
"get",
"(",
"'/posts/dates'",
",",
"options",
")",
"[",
"'dates'",
"]",
"[",
"'date'",
"]",
"dates",
"=",
"[",
"]",
"if",
"dates",
".",
"nil?",
"dates",
"=",
"[",
"*",
"dates",
"]",
"dates",
".",
"each_with_object",
"(",
"{",
"}",
")",
"{",
"|",
"value",
",",
"hash",
"|",
"hash",
"[",
"value",
"[",
"\"date\"",
"]",
"]",
"=",
"value",
"[",
"\"count\"",
"]",
".",
"to_i",
"}",
"end"
] | Returns a list of dates with the number of posts at each date
@param [String] tag Filter by up to three tags
@return [Hash<String,Fixnum>] List of dates with number of posts
at each date | [
"Returns",
"a",
"list",
"of",
"dates",
"with",
"the",
"number",
"of",
"posts",
"at",
"each",
"date"
] | 65d3b2f38b56d0f9f236d0041f4a697157905cf9 | https://github.com/ryw/pinboard/blob/65d3b2f38b56d0f9f236d0041f4a697157905cf9/lib/pinboard/client.rb#L164-L175 | train |
ryw/pinboard | lib/pinboard/client.rb | Pinboard.Client.tags_get | def tags_get(params={})
options = create_params(params)
tags = self.class.get('/tags/get', options)['tags']['tag']
tags = [] if tags.nil?
tags = [*tags]
tags.map { |p| Tag.new(Util.symbolize_keys(p)) }
end | ruby | def tags_get(params={})
options = create_params(params)
tags = self.class.get('/tags/get', options)['tags']['tag']
tags = [] if tags.nil?
tags = [*tags]
tags.map { |p| Tag.new(Util.symbolize_keys(p)) }
end | [
"def",
"tags_get",
"(",
"params",
"=",
"{",
"}",
")",
"options",
"=",
"create_params",
"(",
"params",
")",
"tags",
"=",
"self",
".",
"class",
".",
"get",
"(",
"'/tags/get'",
",",
"options",
")",
"[",
"'tags'",
"]",
"[",
"'tag'",
"]",
"tags",
"=",
"[",
"]",
"if",
"tags",
".",
"nil?",
"tags",
"=",
"[",
"*",
"tags",
"]",
"tags",
".",
"map",
"{",
"|",
"p",
"|",
"Tag",
".",
"new",
"(",
"Util",
".",
"symbolize_keys",
"(",
"p",
")",
")",
"}",
"end"
] | Returns a full list of the user's tags along with the number of
times they were used.
@return [Array<Tag>] List of all tags | [
"Returns",
"a",
"full",
"list",
"of",
"the",
"user",
"s",
"tags",
"along",
"with",
"the",
"number",
"of",
"times",
"they",
"were",
"used",
"."
] | 65d3b2f38b56d0f9f236d0041f4a697157905cf9 | https://github.com/ryw/pinboard/blob/65d3b2f38b56d0f9f236d0041f4a697157905cf9/lib/pinboard/client.rb#L198-L204 | train |
ryw/pinboard | lib/pinboard/client.rb | Pinboard.Client.tags_rename | def tags_rename(old_tag, new_tag=nil)
params = {}
params[:old] = old_tag
params[:new] = new_tag if new_tag
options = create_params(params)
result_code = self.class.get('/tags/rename', options).parsed_response["result"]
raise Error.new(result_code) if result_code != "done"
result_code
end | ruby | def tags_rename(old_tag, new_tag=nil)
params = {}
params[:old] = old_tag
params[:new] = new_tag if new_tag
options = create_params(params)
result_code = self.class.get('/tags/rename', options).parsed_response["result"]
raise Error.new(result_code) if result_code != "done"
result_code
end | [
"def",
"tags_rename",
"(",
"old_tag",
",",
"new_tag",
"=",
"nil",
")",
"params",
"=",
"{",
"}",
"params",
"[",
":old",
"]",
"=",
"old_tag",
"params",
"[",
":new",
"]",
"=",
"new_tag",
"if",
"new_tag",
"options",
"=",
"create_params",
"(",
"params",
")",
"result_code",
"=",
"self",
".",
"class",
".",
"get",
"(",
"'/tags/rename'",
",",
"options",
")",
".",
"parsed_response",
"[",
"\"result\"",
"]",
"raise",
"Error",
".",
"new",
"(",
"result_code",
")",
"if",
"result_code",
"!=",
"\"done\"",
"result_code",
"end"
] | Rename an tag or fold it into an existing tag
@param [String] old_tag Tag to rename (not case sensitive)
@param [String] new_tag New tag (if empty nothing will happen)
@return [String] "done" when everything went as expected
@raise [Error] if result code is not "done" | [
"Rename",
"an",
"tag",
"or",
"fold",
"it",
"into",
"an",
"existing",
"tag"
] | 65d3b2f38b56d0f9f236d0041f4a697157905cf9 | https://github.com/ryw/pinboard/blob/65d3b2f38b56d0f9f236d0041f4a697157905cf9/lib/pinboard/client.rb#L213-L224 | train |
ryw/pinboard | lib/pinboard/client.rb | Pinboard.Client.tags_delete | def tags_delete(tag)
params = { tag: tag }
options = create_params(params)
self.class.get('/tags/delete', options)
nil
end | ruby | def tags_delete(tag)
params = { tag: tag }
options = create_params(params)
self.class.get('/tags/delete', options)
nil
end | [
"def",
"tags_delete",
"(",
"tag",
")",
"params",
"=",
"{",
"tag",
":",
"tag",
"}",
"options",
"=",
"create_params",
"(",
"params",
")",
"self",
".",
"class",
".",
"get",
"(",
"'/tags/delete'",
",",
"options",
")",
"nil",
"end"
] | Delete an existing tag
@param [String] tag Tag to delete
@return [nil] | [
"Delete",
"an",
"existing",
"tag"
] | 65d3b2f38b56d0f9f236d0041f4a697157905cf9 | https://github.com/ryw/pinboard/blob/65d3b2f38b56d0f9f236d0041f4a697157905cf9/lib/pinboard/client.rb#L230-L236 | train |
ryw/pinboard | lib/pinboard/client.rb | Pinboard.Client.notes_list | def notes_list
options = create_params({})
notes = self.class.get('/notes/list', options)['notes']['note']
notes = [] if notes.nil?
notes = [*notes]
notes.map { |p| Note.new(Util.symbolize_keys(p)) }
end | ruby | def notes_list
options = create_params({})
notes = self.class.get('/notes/list', options)['notes']['note']
notes = [] if notes.nil?
notes = [*notes]
notes.map { |p| Note.new(Util.symbolize_keys(p)) }
end | [
"def",
"notes_list",
"options",
"=",
"create_params",
"(",
"{",
"}",
")",
"notes",
"=",
"self",
".",
"class",
".",
"get",
"(",
"'/notes/list'",
",",
"options",
")",
"[",
"'notes'",
"]",
"[",
"'note'",
"]",
"notes",
"=",
"[",
"]",
"if",
"notes",
".",
"nil?",
"notes",
"=",
"[",
"*",
"notes",
"]",
"notes",
".",
"map",
"{",
"|",
"p",
"|",
"Note",
".",
"new",
"(",
"Util",
".",
"symbolize_keys",
"(",
"p",
")",
")",
"}",
"end"
] | Returns a list of the user's notes
@return [Array<Note>] list of notes | [
"Returns",
"a",
"list",
"of",
"the",
"user",
"s",
"notes"
] | 65d3b2f38b56d0f9f236d0041f4a697157905cf9 | https://github.com/ryw/pinboard/blob/65d3b2f38b56d0f9f236d0041f4a697157905cf9/lib/pinboard/client.rb#L256-L262 | train |
ryw/pinboard | lib/pinboard/client.rb | Pinboard.Client.notes_get | def notes_get(id)
options = create_params({})
note = self.class.get("/notes/#{id}", options)['note']
return nil unless note
# Complete hack, because the API is still broken
content = '__content__'
Note.new({
id: note['id'],
# Remove whitespace around the title,
# because of missing xml tag around
title: note[content].gsub(/\n| +/, ''),
length: note['length'][content].to_i,
text: note['text'][content]
})
end | ruby | def notes_get(id)
options = create_params({})
note = self.class.get("/notes/#{id}", options)['note']
return nil unless note
# Complete hack, because the API is still broken
content = '__content__'
Note.new({
id: note['id'],
# Remove whitespace around the title,
# because of missing xml tag around
title: note[content].gsub(/\n| +/, ''),
length: note['length'][content].to_i,
text: note['text'][content]
})
end | [
"def",
"notes_get",
"(",
"id",
")",
"options",
"=",
"create_params",
"(",
"{",
"}",
")",
"note",
"=",
"self",
".",
"class",
".",
"get",
"(",
"\"/notes/#{id}\"",
",",
"options",
")",
"[",
"'note'",
"]",
"return",
"nil",
"unless",
"note",
"content",
"=",
"'__content__'",
"Note",
".",
"new",
"(",
"{",
"id",
":",
"note",
"[",
"'id'",
"]",
",",
"title",
":",
"note",
"[",
"content",
"]",
".",
"gsub",
"(",
"/",
"\\n",
"/",
",",
"''",
")",
",",
"length",
":",
"note",
"[",
"'length'",
"]",
"[",
"content",
"]",
".",
"to_i",
",",
"text",
":",
"note",
"[",
"'text'",
"]",
"[",
"content",
"]",
"}",
")",
"end"
] | Returns an individual user note. The hash property is a
20 character long sha1 hash of the note text.
@return [Note] the note | [
"Returns",
"an",
"individual",
"user",
"note",
".",
"The",
"hash",
"property",
"is",
"a",
"20",
"character",
"long",
"sha1",
"hash",
"of",
"the",
"note",
"text",
"."
] | 65d3b2f38b56d0f9f236d0041f4a697157905cf9 | https://github.com/ryw/pinboard/blob/65d3b2f38b56d0f9f236d0041f4a697157905cf9/lib/pinboard/client.rb#L268-L284 | train |
ryw/pinboard | lib/pinboard/client.rb | Pinboard.Client.create_params | def create_params params
options = {}
options[:query] = params
if @auth_token
options[:query].merge!(auth_token: @auth_token)
else
options[:basic_auth] = @auth
end
options
end | ruby | def create_params params
options = {}
options[:query] = params
if @auth_token
options[:query].merge!(auth_token: @auth_token)
else
options[:basic_auth] = @auth
end
options
end | [
"def",
"create_params",
"params",
"options",
"=",
"{",
"}",
"options",
"[",
":query",
"]",
"=",
"params",
"if",
"@auth_token",
"options",
"[",
":query",
"]",
".",
"merge!",
"(",
"auth_token",
":",
"@auth_token",
")",
"else",
"options",
"[",
":basic_auth",
"]",
"=",
"@auth",
"end",
"options",
"end"
] | Construct params hash for HTTP request
@param [Hash] params Query arguments to include in request
@return [Hash] Options hash for request | [
"Construct",
"params",
"hash",
"for",
"HTTP",
"request"
] | 65d3b2f38b56d0f9f236d0041f4a697157905cf9 | https://github.com/ryw/pinboard/blob/65d3b2f38b56d0f9f236d0041f4a697157905cf9/lib/pinboard/client.rb#L291-L302 | train |
vchs/ruby_vcloud_sdk | lib/ruby_vcloud_sdk/vm.rb | VCloudSdk.VM.memory | def memory
m = entity_xml
.hardware_section
.memory
allocation_units = m.get_rasd_content(Xml::RASD_TYPES[:ALLOCATION_UNITS])
bytes = eval_memory_allocation_units(allocation_units)
virtual_quantity = m.get_rasd_content(Xml::RASD_TYPES[:VIRTUAL_QUANTITY]).to_i
memory_mb = virtual_quantity * bytes / BYTES_PER_MEGABYTE
fail CloudError,
"Size of memory is less than 1 MB." if memory_mb == 0
memory_mb
end | ruby | def memory
m = entity_xml
.hardware_section
.memory
allocation_units = m.get_rasd_content(Xml::RASD_TYPES[:ALLOCATION_UNITS])
bytes = eval_memory_allocation_units(allocation_units)
virtual_quantity = m.get_rasd_content(Xml::RASD_TYPES[:VIRTUAL_QUANTITY]).to_i
memory_mb = virtual_quantity * bytes / BYTES_PER_MEGABYTE
fail CloudError,
"Size of memory is less than 1 MB." if memory_mb == 0
memory_mb
end | [
"def",
"memory",
"m",
"=",
"entity_xml",
".",
"hardware_section",
".",
"memory",
"allocation_units",
"=",
"m",
".",
"get_rasd_content",
"(",
"Xml",
"::",
"RASD_TYPES",
"[",
":ALLOCATION_UNITS",
"]",
")",
"bytes",
"=",
"eval_memory_allocation_units",
"(",
"allocation_units",
")",
"virtual_quantity",
"=",
"m",
".",
"get_rasd_content",
"(",
"Xml",
"::",
"RASD_TYPES",
"[",
":VIRTUAL_QUANTITY",
"]",
")",
".",
"to_i",
"memory_mb",
"=",
"virtual_quantity",
"*",
"bytes",
"/",
"BYTES_PER_MEGABYTE",
"fail",
"CloudError",
",",
"\"Size of memory is less than 1 MB.\"",
"if",
"memory_mb",
"==",
"0",
"memory_mb",
"end"
] | returns size of memory in megabytes | [
"returns",
"size",
"of",
"memory",
"in",
"megabytes"
] | 92d56db4fea4321068ab300ca60bcc6cec3e459b | https://github.com/vchs/ruby_vcloud_sdk/blob/92d56db4fea4321068ab300ca60bcc6cec3e459b/lib/ruby_vcloud_sdk/vm.rb#L25-L37 | train |
vchs/ruby_vcloud_sdk | lib/ruby_vcloud_sdk/vm.rb | VCloudSdk.VM.memory= | def memory=(size)
fail(CloudError,
"Invalid vm memory size #{size}MB") if size <= 0
Config
.logger
.info "Changing the vm memory to #{size}MB."
payload = entity_xml
payload.change_memory(size)
task = connection.post(payload.reconfigure_link.href,
payload,
Xml::MEDIA_TYPE[:VM])
monitor_task(task)
self
end | ruby | def memory=(size)
fail(CloudError,
"Invalid vm memory size #{size}MB") if size <= 0
Config
.logger
.info "Changing the vm memory to #{size}MB."
payload = entity_xml
payload.change_memory(size)
task = connection.post(payload.reconfigure_link.href,
payload,
Xml::MEDIA_TYPE[:VM])
monitor_task(task)
self
end | [
"def",
"memory",
"=",
"(",
"size",
")",
"fail",
"(",
"CloudError",
",",
"\"Invalid vm memory size #{size}MB\"",
")",
"if",
"size",
"<=",
"0",
"Config",
".",
"logger",
".",
"info",
"\"Changing the vm memory to #{size}MB.\"",
"payload",
"=",
"entity_xml",
"payload",
".",
"change_memory",
"(",
"size",
")",
"task",
"=",
"connection",
".",
"post",
"(",
"payload",
".",
"reconfigure_link",
".",
"href",
",",
"payload",
",",
"Xml",
"::",
"MEDIA_TYPE",
"[",
":VM",
"]",
")",
"monitor_task",
"(",
"task",
")",
"self",
"end"
] | sets size of memory in megabytes | [
"sets",
"size",
"of",
"memory",
"in",
"megabytes"
] | 92d56db4fea4321068ab300ca60bcc6cec3e459b | https://github.com/vchs/ruby_vcloud_sdk/blob/92d56db4fea4321068ab300ca60bcc6cec3e459b/lib/ruby_vcloud_sdk/vm.rb#L40-L56 | train |
vchs/ruby_vcloud_sdk | lib/ruby_vcloud_sdk/vm.rb | VCloudSdk.VM.vcpu | def vcpu
cpus = entity_xml
.hardware_section
.cpu
.get_rasd_content(Xml::RASD_TYPES[:VIRTUAL_QUANTITY])
fail CloudError,
"Uable to retrieve number of virtual cpus of VM #{name}" if cpus.nil?
cpus.to_i
end | ruby | def vcpu
cpus = entity_xml
.hardware_section
.cpu
.get_rasd_content(Xml::RASD_TYPES[:VIRTUAL_QUANTITY])
fail CloudError,
"Uable to retrieve number of virtual cpus of VM #{name}" if cpus.nil?
cpus.to_i
end | [
"def",
"vcpu",
"cpus",
"=",
"entity_xml",
".",
"hardware_section",
".",
"cpu",
".",
"get_rasd_content",
"(",
"Xml",
"::",
"RASD_TYPES",
"[",
":VIRTUAL_QUANTITY",
"]",
")",
"fail",
"CloudError",
",",
"\"Uable to retrieve number of virtual cpus of VM #{name}\"",
"if",
"cpus",
".",
"nil?",
"cpus",
".",
"to_i",
"end"
] | returns number of virtual cpus of VM | [
"returns",
"number",
"of",
"virtual",
"cpus",
"of",
"VM"
] | 92d56db4fea4321068ab300ca60bcc6cec3e459b | https://github.com/vchs/ruby_vcloud_sdk/blob/92d56db4fea4321068ab300ca60bcc6cec3e459b/lib/ruby_vcloud_sdk/vm.rb#L59-L68 | train |
vchs/ruby_vcloud_sdk | lib/ruby_vcloud_sdk/vm.rb | VCloudSdk.VM.vcpu= | def vcpu=(count)
fail(CloudError,
"Invalid virtual CPU count #{count}") if count <= 0
Config
.logger
.info "Changing the virtual CPU count to #{count}."
payload = entity_xml
payload.change_cpu_count(count)
task = connection.post(payload.reconfigure_link.href,
payload,
Xml::MEDIA_TYPE[:VM])
monitor_task(task)
self
end | ruby | def vcpu=(count)
fail(CloudError,
"Invalid virtual CPU count #{count}") if count <= 0
Config
.logger
.info "Changing the virtual CPU count to #{count}."
payload = entity_xml
payload.change_cpu_count(count)
task = connection.post(payload.reconfigure_link.href,
payload,
Xml::MEDIA_TYPE[:VM])
monitor_task(task)
self
end | [
"def",
"vcpu",
"=",
"(",
"count",
")",
"fail",
"(",
"CloudError",
",",
"\"Invalid virtual CPU count #{count}\"",
")",
"if",
"count",
"<=",
"0",
"Config",
".",
"logger",
".",
"info",
"\"Changing the virtual CPU count to #{count}.\"",
"payload",
"=",
"entity_xml",
"payload",
".",
"change_cpu_count",
"(",
"count",
")",
"task",
"=",
"connection",
".",
"post",
"(",
"payload",
".",
"reconfigure_link",
".",
"href",
",",
"payload",
",",
"Xml",
"::",
"MEDIA_TYPE",
"[",
":VM",
"]",
")",
"monitor_task",
"(",
"task",
")",
"self",
"end"
] | sets number of virtual cpus of VM | [
"sets",
"number",
"of",
"virtual",
"cpus",
"of",
"VM"
] | 92d56db4fea4321068ab300ca60bcc6cec3e459b | https://github.com/vchs/ruby_vcloud_sdk/blob/92d56db4fea4321068ab300ca60bcc6cec3e459b/lib/ruby_vcloud_sdk/vm.rb#L71-L87 | train |
maxivak/simple_search_filter | lib/simple_search_filter/filter.rb | SimpleSearchFilter.Filter.get_order_dir_for_column | def get_order_dir_for_column(name)
name = name.to_s
current_column = get_order_column
return nil unless current_column==name
dir = get_order_dir
return nil if dir.nil?
dir
end | ruby | def get_order_dir_for_column(name)
name = name.to_s
current_column = get_order_column
return nil unless current_column==name
dir = get_order_dir
return nil if dir.nil?
dir
end | [
"def",
"get_order_dir_for_column",
"(",
"name",
")",
"name",
"=",
"name",
".",
"to_s",
"current_column",
"=",
"get_order_column",
"return",
"nil",
"unless",
"current_column",
"==",
"name",
"dir",
"=",
"get_order_dir",
"return",
"nil",
"if",
"dir",
".",
"nil?",
"dir",
"end"
] | return nil if not sorted by this column
return order dir if sorted by this column | [
"return",
"nil",
"if",
"not",
"sorted",
"by",
"this",
"column",
"return",
"order",
"dir",
"if",
"sorted",
"by",
"this",
"column"
] | 3bece03360f9895b037ca11a9a98fd0e9665e37c | https://github.com/maxivak/simple_search_filter/blob/3bece03360f9895b037ca11a9a98fd0e9665e37c/lib/simple_search_filter/filter.rb#L348-L358 | train |
raulanatol/el_finder_s3 | lib/el_finder_s3/connector.rb | ElFinderS3.Connector.run | def run(params)
@adapter = ElFinderS3::Adapter.new(@options[:server], @options[:cache_connector])
@root = ElFinderS3::Pathname.new(adapter, @options[:root]) #Change - Pass the root dir here
begin
@params = params.dup
@headers = {}
@response = {}
@response[:errorData] = {}
if VALID_COMMANDS.include?(@params[:cmd])
if @options[:thumbs]
@thumb_directory = @root + @options[:thumbs_directory]
@thumb_directory.mkdir unless @thumb_directory.exist?
raise(RuntimeError, "Unable to create thumbs directory") unless @thumb_directory.directory?
end
@current = @params[:current] ? from_hash(@params[:current]) : nil
@target = (@params[:target] and !@params[:target].empty?) ? from_hash(@params[:target]) : nil
if params[:targets]
@targets = @params[:targets].map { |t| from_hash(t) }
end
begin
send("_#{@params[:cmd]}")
rescue Exception => exception
puts exception.message
puts exception.backtrace.inspect
@response[:error] = 'Access Denied'
end
else
invalid_request
end
@response.delete(:errorData) if @response[:errorData].empty?
return @headers, @response
ensure
adapter.close
end
end | ruby | def run(params)
@adapter = ElFinderS3::Adapter.new(@options[:server], @options[:cache_connector])
@root = ElFinderS3::Pathname.new(adapter, @options[:root]) #Change - Pass the root dir here
begin
@params = params.dup
@headers = {}
@response = {}
@response[:errorData] = {}
if VALID_COMMANDS.include?(@params[:cmd])
if @options[:thumbs]
@thumb_directory = @root + @options[:thumbs_directory]
@thumb_directory.mkdir unless @thumb_directory.exist?
raise(RuntimeError, "Unable to create thumbs directory") unless @thumb_directory.directory?
end
@current = @params[:current] ? from_hash(@params[:current]) : nil
@target = (@params[:target] and !@params[:target].empty?) ? from_hash(@params[:target]) : nil
if params[:targets]
@targets = @params[:targets].map { |t| from_hash(t) }
end
begin
send("_#{@params[:cmd]}")
rescue Exception => exception
puts exception.message
puts exception.backtrace.inspect
@response[:error] = 'Access Denied'
end
else
invalid_request
end
@response.delete(:errorData) if @response[:errorData].empty?
return @headers, @response
ensure
adapter.close
end
end | [
"def",
"run",
"(",
"params",
")",
"@adapter",
"=",
"ElFinderS3",
"::",
"Adapter",
".",
"new",
"(",
"@options",
"[",
":server",
"]",
",",
"@options",
"[",
":cache_connector",
"]",
")",
"@root",
"=",
"ElFinderS3",
"::",
"Pathname",
".",
"new",
"(",
"adapter",
",",
"@options",
"[",
":root",
"]",
")",
"begin",
"@params",
"=",
"params",
".",
"dup",
"@headers",
"=",
"{",
"}",
"@response",
"=",
"{",
"}",
"@response",
"[",
":errorData",
"]",
"=",
"{",
"}",
"if",
"VALID_COMMANDS",
".",
"include?",
"(",
"@params",
"[",
":cmd",
"]",
")",
"if",
"@options",
"[",
":thumbs",
"]",
"@thumb_directory",
"=",
"@root",
"+",
"@options",
"[",
":thumbs_directory",
"]",
"@thumb_directory",
".",
"mkdir",
"unless",
"@thumb_directory",
".",
"exist?",
"raise",
"(",
"RuntimeError",
",",
"\"Unable to create thumbs directory\"",
")",
"unless",
"@thumb_directory",
".",
"directory?",
"end",
"@current",
"=",
"@params",
"[",
":current",
"]",
"?",
"from_hash",
"(",
"@params",
"[",
":current",
"]",
")",
":",
"nil",
"@target",
"=",
"(",
"@params",
"[",
":target",
"]",
"and",
"!",
"@params",
"[",
":target",
"]",
".",
"empty?",
")",
"?",
"from_hash",
"(",
"@params",
"[",
":target",
"]",
")",
":",
"nil",
"if",
"params",
"[",
":targets",
"]",
"@targets",
"=",
"@params",
"[",
":targets",
"]",
".",
"map",
"{",
"|",
"t",
"|",
"from_hash",
"(",
"t",
")",
"}",
"end",
"begin",
"send",
"(",
"\"_#{@params[:cmd]}\"",
")",
"rescue",
"Exception",
"=>",
"exception",
"puts",
"exception",
".",
"message",
"puts",
"exception",
".",
"backtrace",
".",
"inspect",
"@response",
"[",
":error",
"]",
"=",
"'Access Denied'",
"end",
"else",
"invalid_request",
"end",
"@response",
".",
"delete",
"(",
":errorData",
")",
"if",
"@response",
"[",
":errorData",
"]",
".",
"empty?",
"return",
"@headers",
",",
"@response",
"ensure",
"adapter",
".",
"close",
"end",
"end"
] | Runs request-response cycle.
@param [Hash] params Request parameters. :cmd option is required.
@option params [String] :cmd Command to be performed.
@see VALID_COMMANDS | [
"Runs",
"request",
"-",
"response",
"cycle",
"."
] | df7e9d5792949f466cafecdbac9b6289ebbe4224 | https://github.com/raulanatol/el_finder_s3/blob/df7e9d5792949f466cafecdbac9b6289ebbe4224/lib/el_finder_s3/connector.rb#L78-L120 | train |
rkday/ruby-diameter | lib/diameter/stack.rb | Diameter.Stack.add_handler | def add_handler(app_id, opts={}, &blk)
vendor = opts.fetch(:vendor, 0)
auth = opts.fetch(:auth, false)
acct = opts.fetch(:acct, false)
raise ArgumentError.new("Must specify at least one of auth or acct") unless auth or acct
@acct_apps << [app_id, vendor] if acct
@auth_apps << [app_id, vendor] if auth
@handlers[app_id] = blk
end | ruby | def add_handler(app_id, opts={}, &blk)
vendor = opts.fetch(:vendor, 0)
auth = opts.fetch(:auth, false)
acct = opts.fetch(:acct, false)
raise ArgumentError.new("Must specify at least one of auth or acct") unless auth or acct
@acct_apps << [app_id, vendor] if acct
@auth_apps << [app_id, vendor] if auth
@handlers[app_id] = blk
end | [
"def",
"add_handler",
"(",
"app_id",
",",
"opts",
"=",
"{",
"}",
",",
"&",
"blk",
")",
"vendor",
"=",
"opts",
".",
"fetch",
"(",
":vendor",
",",
"0",
")",
"auth",
"=",
"opts",
".",
"fetch",
"(",
":auth",
",",
"false",
")",
"acct",
"=",
"opts",
".",
"fetch",
"(",
":acct",
",",
"false",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"Must specify at least one of auth or acct\"",
")",
"unless",
"auth",
"or",
"acct",
"@acct_apps",
"<<",
"[",
"app_id",
",",
"vendor",
"]",
"if",
"acct",
"@auth_apps",
"<<",
"[",
"app_id",
",",
"vendor",
"]",
"if",
"auth",
"@handlers",
"[",
"app_id",
"]",
"=",
"blk",
"end"
] | Adds a handler for a specific Diameter application.
@note If you expect to only send requests for this application,
not receive them, the block can be a no-op (e.g. `{ nil }`)
@param app_id [Fixnum] The Diameter application ID.
@option opts [true, false] auth
Whether we should advertise support for this application in
the Auth-Application-ID AVP. Note that at least one of auth or
acct must be specified.
@option opts [true, false] acct
Whether we should advertise support for this application in
the Acct-Application-ID AVP. Note that at least one of auth or
acct must be specified.
@option opts [Fixnum] vendor
If we should advertise support for this application in a
Vendor-Specific-Application-Id AVP, this specifies the
associated Vendor-Id.
@yield [req, cxn] Passes a Diameter message (and its originating
connection) for application-specific handling.
@yieldparam [Message] req The parsed Diameter message from the peer.
@yieldparam [Socket] cxn The TCP connection to the peer, to be
passed to {Stack#send_answer}. | [
"Adds",
"a",
"handler",
"for",
"a",
"specific",
"Diameter",
"application",
"."
] | 83def68f67cf660aa227eac4c74719dc98aacab2 | https://github.com/rkday/ruby-diameter/blob/83def68f67cf660aa227eac4c74719dc98aacab2/lib/diameter/stack.rb#L91-L102 | train |
rkday/ruby-diameter | lib/diameter/stack.rb | Diameter.Stack.connect_to_peer | def connect_to_peer(peer_uri, peer_host, realm)
peer = Peer.new(peer_host, realm)
@peer_table[peer_host] = peer
@peer_table[peer_host].state = :WAITING
# Will move to :UP when the CEA is received
uri = URI(peer_uri)
cxn = @tcp_helper.setup_new_connection(uri.host, uri.port)
@peer_table[peer_host].cxn = cxn
avps = [AVP.create('Origin-Host', @local_host),
AVP.create('Origin-Realm', @local_realm),
AVP.create('Host-IP-Address', IPAddr.new('127.0.0.1')),
AVP.create('Vendor-Id', 100),
AVP.create('Product-Name', 'ruby-diameter')
]
avps += app_avps
cer_bytes = Message.new(version: 1, command_code: 257, app_id: 0, request: true, proxyable: false, retransmitted: false, error: false, avps: avps).to_wire
@tcp_helper.send(cer_bytes, cxn)
peer
end | ruby | def connect_to_peer(peer_uri, peer_host, realm)
peer = Peer.new(peer_host, realm)
@peer_table[peer_host] = peer
@peer_table[peer_host].state = :WAITING
# Will move to :UP when the CEA is received
uri = URI(peer_uri)
cxn = @tcp_helper.setup_new_connection(uri.host, uri.port)
@peer_table[peer_host].cxn = cxn
avps = [AVP.create('Origin-Host', @local_host),
AVP.create('Origin-Realm', @local_realm),
AVP.create('Host-IP-Address', IPAddr.new('127.0.0.1')),
AVP.create('Vendor-Id', 100),
AVP.create('Product-Name', 'ruby-diameter')
]
avps += app_avps
cer_bytes = Message.new(version: 1, command_code: 257, app_id: 0, request: true, proxyable: false, retransmitted: false, error: false, avps: avps).to_wire
@tcp_helper.send(cer_bytes, cxn)
peer
end | [
"def",
"connect_to_peer",
"(",
"peer_uri",
",",
"peer_host",
",",
"realm",
")",
"peer",
"=",
"Peer",
".",
"new",
"(",
"peer_host",
",",
"realm",
")",
"@peer_table",
"[",
"peer_host",
"]",
"=",
"peer",
"@peer_table",
"[",
"peer_host",
"]",
".",
"state",
"=",
":WAITING",
"uri",
"=",
"URI",
"(",
"peer_uri",
")",
"cxn",
"=",
"@tcp_helper",
".",
"setup_new_connection",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"@peer_table",
"[",
"peer_host",
"]",
".",
"cxn",
"=",
"cxn",
"avps",
"=",
"[",
"AVP",
".",
"create",
"(",
"'Origin-Host'",
",",
"@local_host",
")",
",",
"AVP",
".",
"create",
"(",
"'Origin-Realm'",
",",
"@local_realm",
")",
",",
"AVP",
".",
"create",
"(",
"'Host-IP-Address'",
",",
"IPAddr",
".",
"new",
"(",
"'127.0.0.1'",
")",
")",
",",
"AVP",
".",
"create",
"(",
"'Vendor-Id'",
",",
"100",
")",
",",
"AVP",
".",
"create",
"(",
"'Product-Name'",
",",
"'ruby-diameter'",
")",
"]",
"avps",
"+=",
"app_avps",
"cer_bytes",
"=",
"Message",
".",
"new",
"(",
"version",
":",
"1",
",",
"command_code",
":",
"257",
",",
"app_id",
":",
"0",
",",
"request",
":",
"true",
",",
"proxyable",
":",
"false",
",",
"retransmitted",
":",
"false",
",",
"error",
":",
"false",
",",
"avps",
":",
"avps",
")",
".",
"to_wire",
"@tcp_helper",
".",
"send",
"(",
"cer_bytes",
",",
"cxn",
")",
"peer",
"end"
] | Creates a Peer connection to a Diameter agent at the specific
network location indicated by peer_uri.
@param peer_uri [URI] The aaa:// URI identifying the peer. Should
contain a hostname/IP; may contain a port (default 3868).
@param peer_host [String] The DiameterIdentity of this peer, which
will uniquely identify it in the peer table.
@param realm [String] The Diameter realm of this peer.
@return [Peer] The Diameter peer chosen. | [
"Creates",
"a",
"Peer",
"connection",
"to",
"a",
"Diameter",
"agent",
"at",
"the",
"specific",
"network",
"location",
"indicated",
"by",
"peer_uri",
"."
] | 83def68f67cf660aa227eac4c74719dc98aacab2 | https://github.com/rkday/ruby-diameter/blob/83def68f67cf660aa227eac4c74719dc98aacab2/lib/diameter/stack.rb#L161-L182 | train |
qw3/getnet_api | lib/getnet_api/credit.rb | GetnetApi.Credit.to_request | def to_request
credit = {
delayed: self.delayed,
authenticated: self.authenticated,
pre_authorization: self.pre_authorization,
save_card_data: self.save_card_data,
transaction_type: self.transaction_type,
number_installments: self.number_installments.to_i,
soft_descriptor: self.soft_descriptor,
dynamic_mcc: self.dynamic_mcc,
card: self.card.to_request,
}
return credit
end | ruby | def to_request
credit = {
delayed: self.delayed,
authenticated: self.authenticated,
pre_authorization: self.pre_authorization,
save_card_data: self.save_card_data,
transaction_type: self.transaction_type,
number_installments: self.number_installments.to_i,
soft_descriptor: self.soft_descriptor,
dynamic_mcc: self.dynamic_mcc,
card: self.card.to_request,
}
return credit
end | [
"def",
"to_request",
"credit",
"=",
"{",
"delayed",
":",
"self",
".",
"delayed",
",",
"authenticated",
":",
"self",
".",
"authenticated",
",",
"pre_authorization",
":",
"self",
".",
"pre_authorization",
",",
"save_card_data",
":",
"self",
".",
"save_card_data",
",",
"transaction_type",
":",
"self",
".",
"transaction_type",
",",
"number_installments",
":",
"self",
".",
"number_installments",
".",
"to_i",
",",
"soft_descriptor",
":",
"self",
".",
"soft_descriptor",
",",
"dynamic_mcc",
":",
"self",
".",
"dynamic_mcc",
",",
"card",
":",
"self",
".",
"card",
".",
"to_request",
",",
"}",
"return",
"credit",
"end"
] | Nova instancia da classe Credit
@param [Hash] campos
Montar o Hash de dados do pagamento no padrão utilizado pela Getnet | [
"Nova",
"instancia",
"da",
"classe",
"Credit"
] | 94cbda66aab03d83ea38bc5325ea2a02a639e922 | https://github.com/qw3/getnet_api/blob/94cbda66aab03d83ea38bc5325ea2a02a639e922/lib/getnet_api/credit.rb#L71-L85 | train |
chrismagnacca/newegg-api | lib/newegg/api.rb | Newegg.Api.stores | def stores
return self._stores if not self._stores.empty?
response = api_get("Stores.egg")
stores = JSON.parse(response.body)
stores.each do |store|
self._stores << Newegg::Store.new(store['Title'], store['StoreDepa'], store['StoreID'], store['ShowSeeAllDeals'])
end
self._stores
end | ruby | def stores
return self._stores if not self._stores.empty?
response = api_get("Stores.egg")
stores = JSON.parse(response.body)
stores.each do |store|
self._stores << Newegg::Store.new(store['Title'], store['StoreDepa'], store['StoreID'], store['ShowSeeAllDeals'])
end
self._stores
end | [
"def",
"stores",
"return",
"self",
".",
"_stores",
"if",
"not",
"self",
".",
"_stores",
".",
"empty?",
"response",
"=",
"api_get",
"(",
"\"Stores.egg\"",
")",
"stores",
"=",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
")",
"stores",
".",
"each",
"do",
"|",
"store",
"|",
"self",
".",
"_stores",
"<<",
"Newegg",
"::",
"Store",
".",
"new",
"(",
"store",
"[",
"'Title'",
"]",
",",
"store",
"[",
"'StoreDepa'",
"]",
",",
"store",
"[",
"'StoreID'",
"]",
",",
"store",
"[",
"'ShowSeeAllDeals'",
"]",
")",
"end",
"self",
".",
"_stores",
"end"
] | retrieve and populate a list of available stores | [
"retrieve",
"and",
"populate",
"a",
"list",
"of",
"available",
"stores"
] | c362058eef09a8966625a88d6b3e25c4345f757c | https://github.com/chrismagnacca/newegg-api/blob/c362058eef09a8966625a88d6b3e25c4345f757c/lib/newegg/api.rb#L32-L40 | train |
chrismagnacca/newegg-api | lib/newegg/api.rb | Newegg.Api.categories | def categories(store_id)
return [] if store_id.nil?
response = api_get("Stores.egg", "Categories", store_id)
categories = JSON.parse(response.body)
categories = categories.collect do |category|
Newegg::Category.new(category['Description'], category['CategoryType'], category['CategoryID'],
category['StoreID'], category['ShowSeeAllDeals'], category['NodeId'])
end
categories
end | ruby | def categories(store_id)
return [] if store_id.nil?
response = api_get("Stores.egg", "Categories", store_id)
categories = JSON.parse(response.body)
categories = categories.collect do |category|
Newegg::Category.new(category['Description'], category['CategoryType'], category['CategoryID'],
category['StoreID'], category['ShowSeeAllDeals'], category['NodeId'])
end
categories
end | [
"def",
"categories",
"(",
"store_id",
")",
"return",
"[",
"]",
"if",
"store_id",
".",
"nil?",
"response",
"=",
"api_get",
"(",
"\"Stores.egg\"",
",",
"\"Categories\"",
",",
"store_id",
")",
"categories",
"=",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
")",
"categories",
"=",
"categories",
".",
"collect",
"do",
"|",
"category",
"|",
"Newegg",
"::",
"Category",
".",
"new",
"(",
"category",
"[",
"'Description'",
"]",
",",
"category",
"[",
"'CategoryType'",
"]",
",",
"category",
"[",
"'CategoryID'",
"]",
",",
"category",
"[",
"'StoreID'",
"]",
",",
"category",
"[",
"'ShowSeeAllDeals'",
"]",
",",
"category",
"[",
"'NodeId'",
"]",
")",
"end",
"categories",
"end"
] | retrieve and populate list of categories for a given store_id
@param [Integer] store_id of the store | [
"retrieve",
"and",
"populate",
"list",
"of",
"categories",
"for",
"a",
"given",
"store_id"
] | c362058eef09a8966625a88d6b3e25c4345f757c | https://github.com/chrismagnacca/newegg-api/blob/c362058eef09a8966625a88d6b3e25c4345f757c/lib/newegg/api.rb#L47-L58 | train |
chrismagnacca/newegg-api | lib/newegg/api.rb | Newegg.Api.store_content | def store_content(store_id, category_id = -1, node_id = -1, store_type = 4, page_number = 1)
params = {
'storeId' => store_id,
'categoryId' => category_id,
'nodeId' => node_id,
'storeType' => store_type,
'pageNumber' => page_number
}
JSON.parse(api_get('Stores.egg', 'Content', nil, params).body)
end | ruby | def store_content(store_id, category_id = -1, node_id = -1, store_type = 4, page_number = 1)
params = {
'storeId' => store_id,
'categoryId' => category_id,
'nodeId' => node_id,
'storeType' => store_type,
'pageNumber' => page_number
}
JSON.parse(api_get('Stores.egg', 'Content', nil, params).body)
end | [
"def",
"store_content",
"(",
"store_id",
",",
"category_id",
"=",
"-",
"1",
",",
"node_id",
"=",
"-",
"1",
",",
"store_type",
"=",
"4",
",",
"page_number",
"=",
"1",
")",
"params",
"=",
"{",
"'storeId'",
"=>",
"store_id",
",",
"'categoryId'",
"=>",
"category_id",
",",
"'nodeId'",
"=>",
"node_id",
",",
"'storeType'",
"=>",
"store_type",
",",
"'pageNumber'",
"=>",
"page_number",
"}",
"JSON",
".",
"parse",
"(",
"api_get",
"(",
"'Stores.egg'",
",",
"'Content'",
",",
"nil",
",",
"params",
")",
".",
"body",
")",
"end"
] | retrieves store content | [
"retrieves",
"store",
"content"
] | c362058eef09a8966625a88d6b3e25c4345f757c | https://github.com/chrismagnacca/newegg-api/blob/c362058eef09a8966625a88d6b3e25c4345f757c/lib/newegg/api.rb#L75-L84 | train |
chrismagnacca/newegg-api | lib/newegg/api.rb | Newegg.Api.search | def search(options={})
options = {store_id: -1, category_id: -1, sub_category_id: -1, node_id: -1, page_number: 1, sort: "FEATURED",
keywords: ""}.merge(options)
request = {
'IsUPCCodeSearch' => false,
'IsSubCategorySearch' => options[:sub_category_id] > 0,
'isGuideAdvanceSearch' => false,
'StoreDepaId' => options[:store_id],
'CategoryId' => options[:category_id],
'SubCategoryId' => options[:sub_category_id],
'NodeId' => options[:node_id],
'BrandId' => -1,
'NValue' => "",
'Keyword' => options[:keywords],
'Sort' => options[:sort],
'PageNumber' => options[:page_number]
}
JSON.parse(api_post("Search.egg", "Advanced", request).body, {quirks_mode: true})
end | ruby | def search(options={})
options = {store_id: -1, category_id: -1, sub_category_id: -1, node_id: -1, page_number: 1, sort: "FEATURED",
keywords: ""}.merge(options)
request = {
'IsUPCCodeSearch' => false,
'IsSubCategorySearch' => options[:sub_category_id] > 0,
'isGuideAdvanceSearch' => false,
'StoreDepaId' => options[:store_id],
'CategoryId' => options[:category_id],
'SubCategoryId' => options[:sub_category_id],
'NodeId' => options[:node_id],
'BrandId' => -1,
'NValue' => "",
'Keyword' => options[:keywords],
'Sort' => options[:sort],
'PageNumber' => options[:page_number]
}
JSON.parse(api_post("Search.egg", "Advanced", request).body, {quirks_mode: true})
end | [
"def",
"search",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"store_id",
":",
"-",
"1",
",",
"category_id",
":",
"-",
"1",
",",
"sub_category_id",
":",
"-",
"1",
",",
"node_id",
":",
"-",
"1",
",",
"page_number",
":",
"1",
",",
"sort",
":",
"\"FEATURED\"",
",",
"keywords",
":",
"\"\"",
"}",
".",
"merge",
"(",
"options",
")",
"request",
"=",
"{",
"'IsUPCCodeSearch'",
"=>",
"false",
",",
"'IsSubCategorySearch'",
"=>",
"options",
"[",
":sub_category_id",
"]",
">",
"0",
",",
"'isGuideAdvanceSearch'",
"=>",
"false",
",",
"'StoreDepaId'",
"=>",
"options",
"[",
":store_id",
"]",
",",
"'CategoryId'",
"=>",
"options",
"[",
":category_id",
"]",
",",
"'SubCategoryId'",
"=>",
"options",
"[",
":sub_category_id",
"]",
",",
"'NodeId'",
"=>",
"options",
"[",
":node_id",
"]",
",",
"'BrandId'",
"=>",
"-",
"1",
",",
"'NValue'",
"=>",
"\"\"",
",",
"'Keyword'",
"=>",
"options",
"[",
":keywords",
"]",
",",
"'Sort'",
"=>",
"options",
"[",
":sort",
"]",
",",
"'PageNumber'",
"=>",
"options",
"[",
":page_number",
"]",
"}",
"JSON",
".",
"parse",
"(",
"api_post",
"(",
"\"Search.egg\"",
",",
"\"Advanced\"",
",",
"request",
")",
".",
"body",
",",
"{",
"quirks_mode",
":",
"true",
"}",
")",
"end"
] | retrieves a single page of products given a query specified by an options hash. See options below.
node_id, page_number, and an optional sorting method
@param [Integer] store_id, from @api.navigation, returned as StoreID
@param [Integer] category_id from @api.navigation, returned as CategoryType
@param [Integer] sub_category_id from @api.navigation, returned as CategoryID
@param [Integer] node_id from @api.navigation, returned as NodeId
@param [Integer] page_number of the paginated search results, returned as PaginationInfo from search
@param [String] sort style of the returned search results, default is FEATURED (can also be RATING, PRICE, PRICED, REVIEWS)
@param [String] keywords | [
"retrieves",
"a",
"single",
"page",
"of",
"products",
"given",
"a",
"query",
"specified",
"by",
"an",
"options",
"hash",
".",
"See",
"options",
"below",
".",
"node_id",
"page_number",
"and",
"an",
"optional",
"sorting",
"method"
] | c362058eef09a8966625a88d6b3e25c4345f757c | https://github.com/chrismagnacca/newegg-api/blob/c362058eef09a8966625a88d6b3e25c4345f757c/lib/newegg/api.rb#L127-L146 | train |
chrismagnacca/newegg-api | lib/newegg/api.rb | Newegg.Api.combo_deals | def combo_deals(item_number, options={})
options = {sub_category: -1, sort_field: 0, page_number: 1}.merge(options)
params = {
'SubCategory' => options[:sub_category],
'SortField' => options[:sort_field],
'PageNumber' => options[:page_number]
}
JSON.parse(api_get('Products.egg', item_number, 'ComboDeals', params).body)
end | ruby | def combo_deals(item_number, options={})
options = {sub_category: -1, sort_field: 0, page_number: 1}.merge(options)
params = {
'SubCategory' => options[:sub_category],
'SortField' => options[:sort_field],
'PageNumber' => options[:page_number]
}
JSON.parse(api_get('Products.egg', item_number, 'ComboDeals', params).body)
end | [
"def",
"combo_deals",
"(",
"item_number",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"sub_category",
":",
"-",
"1",
",",
"sort_field",
":",
"0",
",",
"page_number",
":",
"1",
"}",
".",
"merge",
"(",
"options",
")",
"params",
"=",
"{",
"'SubCategory'",
"=>",
"options",
"[",
":sub_category",
"]",
",",
"'SortField'",
"=>",
"options",
"[",
":sort_field",
"]",
",",
"'PageNumber'",
"=>",
"options",
"[",
":page_number",
"]",
"}",
"JSON",
".",
"parse",
"(",
"api_get",
"(",
"'Products.egg'",
",",
"item_number",
",",
"'ComboDeals'",
",",
"params",
")",
".",
"body",
")",
"end"
] | retrieve product combo deals given an item number
@param [String] item_number of the product
@param [Integer] sub_category
@param [Integer] sort_field
@param [Integer] page_number | [
"retrieve",
"product",
"combo",
"deals",
"given",
"an",
"item",
"number"
] | c362058eef09a8966625a88d6b3e25c4345f757c | https://github.com/chrismagnacca/newegg-api/blob/c362058eef09a8966625a88d6b3e25c4345f757c/lib/newegg/api.rb#L262-L270 | train |
chrismagnacca/newegg-api | lib/newegg/api.rb | Newegg.Api.reviews | def reviews(item_number, page_number = 1, options={})
options = {time: 'all', rating: 'All', sort: 'date posted'}.merge(options)
params = {
'filter.time' => options[:time],
'filter.rating' => options[:rating],
'sort' => options[:sort]
}
JSON.parse(api_get('Products.egg', item_number, "Reviewsinfo/#{page_number}", params).body)
end | ruby | def reviews(item_number, page_number = 1, options={})
options = {time: 'all', rating: 'All', sort: 'date posted'}.merge(options)
params = {
'filter.time' => options[:time],
'filter.rating' => options[:rating],
'sort' => options[:sort]
}
JSON.parse(api_get('Products.egg', item_number, "Reviewsinfo/#{page_number}", params).body)
end | [
"def",
"reviews",
"(",
"item_number",
",",
"page_number",
"=",
"1",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"time",
":",
"'all'",
",",
"rating",
":",
"'All'",
",",
"sort",
":",
"'date posted'",
"}",
".",
"merge",
"(",
"options",
")",
"params",
"=",
"{",
"'filter.time'",
"=>",
"options",
"[",
":time",
"]",
",",
"'filter.rating'",
"=>",
"options",
"[",
":rating",
"]",
",",
"'sort'",
"=>",
"options",
"[",
":sort",
"]",
"}",
"JSON",
".",
"parse",
"(",
"api_get",
"(",
"'Products.egg'",
",",
"item_number",
",",
"\"Reviewsinfo/#{page_number}\"",
",",
"params",
")",
".",
"body",
")",
"end"
] | retrieve product reviews given an item number
@param [String] item_number of the product
@param [Integer] page_number
@param [String] time
@param [String] rating default All (can also be 5, 4, 3, 2, 1)
@param [String] sort default 'date posted' (can also be 'most helpful', 'highest rated', 'lowest rated', 'ownership') | [
"retrieve",
"product",
"reviews",
"given",
"an",
"item",
"number"
] | c362058eef09a8966625a88d6b3e25c4345f757c | https://github.com/chrismagnacca/newegg-api/blob/c362058eef09a8966625a88d6b3e25c4345f757c/lib/newegg/api.rb#L281-L289 | train |
zerowidth/camper_van | lib/camper_van/channel.rb | CamperVan.Channel.current_mode_string | def current_mode_string
n = room.membership_limit
s = room.open_to_guests? ? "" : "s"
i = room.locked? ? "i" : ""
"+#{i}l#{s}"
end | ruby | def current_mode_string
n = room.membership_limit
s = room.open_to_guests? ? "" : "s"
i = room.locked? ? "i" : ""
"+#{i}l#{s}"
end | [
"def",
"current_mode_string",
"n",
"=",
"room",
".",
"membership_limit",
"s",
"=",
"room",
".",
"open_to_guests?",
"?",
"\"\"",
":",
"\"s\"",
"i",
"=",
"room",
".",
"locked?",
"?",
"\"i\"",
":",
"\"\"",
"\"+#{i}l#{s}\"",
"end"
] | Returns the current mode string | [
"Returns",
"the",
"current",
"mode",
"string"
] | 984351a3b472e936a451f1d1cd987ca27d981d23 | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/lib/camper_van/channel.rb#L169-L174 | train |
zerowidth/camper_van | lib/camper_van/channel.rb | CamperVan.Channel.user_for_message | def user_for_message(message)
if user = users[message.user_id]
yield message, user
else
message.user do |user|
yield message, user
end
end
end | ruby | def user_for_message(message)
if user = users[message.user_id]
yield message, user
else
message.user do |user|
yield message, user
end
end
end | [
"def",
"user_for_message",
"(",
"message",
")",
"if",
"user",
"=",
"users",
"[",
"message",
".",
"user_id",
"]",
"yield",
"message",
",",
"user",
"else",
"message",
".",
"user",
"do",
"|",
"user",
"|",
"yield",
"message",
",",
"user",
"end",
"end",
"end"
] | Retrieve the user from a message, either by finding it in the current
list of known users, or by asking campfire for the user.
message - the message for which to look up the user
Yields the message and the user associated with the message | [
"Retrieve",
"the",
"user",
"from",
"a",
"message",
"either",
"by",
"finding",
"it",
"in",
"the",
"current",
"list",
"of",
"known",
"users",
"or",
"by",
"asking",
"campfire",
"for",
"the",
"user",
"."
] | 984351a3b472e936a451f1d1cd987ca27d981d23 | https://github.com/zerowidth/camper_van/blob/984351a3b472e936a451f1d1cd987ca27d981d23/lib/camper_van/channel.rb#L381-L389 | train |
sleewoo/minispec | lib/minispec/api/class/around.rb | MiniSpec.ClassAPI.around | def around *matchers, &proc
proc || raise(ArgumentError, 'block is missing')
matchers.flatten!
matchers = [:*] if matchers.empty?
return if around?.find {|x| x[0] == matchers && x[1].source_location == proc.source_location}
around?.push([matchers, proc])
end | ruby | def around *matchers, &proc
proc || raise(ArgumentError, 'block is missing')
matchers.flatten!
matchers = [:*] if matchers.empty?
return if around?.find {|x| x[0] == matchers && x[1].source_location == proc.source_location}
around?.push([matchers, proc])
end | [
"def",
"around",
"*",
"matchers",
",",
"&",
"proc",
"proc",
"||",
"raise",
"(",
"ArgumentError",
",",
"'block is missing'",
")",
"matchers",
".",
"flatten!",
"matchers",
"=",
"[",
":*",
"]",
"if",
"matchers",
".",
"empty?",
"return",
"if",
"around?",
".",
"find",
"{",
"|",
"x",
"|",
"x",
"[",
"0",
"]",
"==",
"matchers",
"&&",
"x",
"[",
"1",
"]",
".",
"source_location",
"==",
"proc",
".",
"source_location",
"}",
"around?",
".",
"push",
"(",
"[",
"matchers",
",",
"proc",
"]",
")",
"end"
] | a block to wrap each test evaluation
@example
describe SomeClass do
around do |test|
DB.connect
test.run
DB.disconnect
end
end | [
"a",
"block",
"to",
"wrap",
"each",
"test",
"evaluation"
] | 6dcdacd041cc031c21f2fe70b6e5b22c6af636c5 | https://github.com/sleewoo/minispec/blob/6dcdacd041cc031c21f2fe70b6e5b22c6af636c5/lib/minispec/api/class/around.rb#L16-L22 | train |
AssemDeghady/questionpro_rails | lib/questionpro_rails/email_list.rb | QuestionproRails.EmailList.statistics | def statistics
extracted_statistics = []
unless self.qp_statistics.nil?
extracted_statistics.push(EmailListStatistic.new(qp_statistics))
end
return extracted_statistics
end | ruby | def statistics
extracted_statistics = []
unless self.qp_statistics.nil?
extracted_statistics.push(EmailListStatistic.new(qp_statistics))
end
return extracted_statistics
end | [
"def",
"statistics",
"extracted_statistics",
"=",
"[",
"]",
"unless",
"self",
".",
"qp_statistics",
".",
"nil?",
"extracted_statistics",
".",
"push",
"(",
"EmailListStatistic",
".",
"new",
"(",
"qp_statistics",
")",
")",
"end",
"return",
"extracted_statistics",
"end"
] | Extract the email list statistics from qp_statistics attribute.
@return [QuestionproRails::EmailListStatistic] Email List Statistics. | [
"Extract",
"the",
"email",
"list",
"statistics",
"from",
"qp_statistics",
"attribute",
"."
] | 79f295f193b6ad593f4d56d8edfa3076a23d8e4f | https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/email_list.rb#L31-L39 | train |
ezkl/capit | lib/capit/capture.rb | CapIt.Capture.capture_command | def capture_command
cmd = "#{@cutycapt_path} --url='#{@url}'"
cmd += " --out='#{@folder}/#{@filename}'"
cmd += " --max-wait=#{@max_wait}"
cmd += " --delay=#{@delay}" if @delay
cmd += " --user-agent='#{@user_agent}'"
cmd += " --min-width='#{@min_width}'"
cmd += " --min-height='#{@min_height}'"
if determine_os == :linux and check_xvfb
xvfb = 'xvfb-run --server-args="-screen 0, 1024x768x24" '
xvfb.concat(cmd)
else
cmd
end
end | ruby | def capture_command
cmd = "#{@cutycapt_path} --url='#{@url}'"
cmd += " --out='#{@folder}/#{@filename}'"
cmd += " --max-wait=#{@max_wait}"
cmd += " --delay=#{@delay}" if @delay
cmd += " --user-agent='#{@user_agent}'"
cmd += " --min-width='#{@min_width}'"
cmd += " --min-height='#{@min_height}'"
if determine_os == :linux and check_xvfb
xvfb = 'xvfb-run --server-args="-screen 0, 1024x768x24" '
xvfb.concat(cmd)
else
cmd
end
end | [
"def",
"capture_command",
"cmd",
"=",
"\"#{@cutycapt_path} --url='#{@url}'\"",
"cmd",
"+=",
"\" --out='#{@folder}/#{@filename}'\"",
"cmd",
"+=",
"\" --max-wait=#{@max_wait}\"",
"cmd",
"+=",
"\" --delay=#{@delay}\"",
"if",
"@delay",
"cmd",
"+=",
"\" --user-agent='#{@user_agent}'\"",
"cmd",
"+=",
"\" --min-width='#{@min_width}'\"",
"cmd",
"+=",
"\" --min-height='#{@min_height}'\"",
"if",
"determine_os",
"==",
":linux",
"and",
"check_xvfb",
"xvfb",
"=",
"'xvfb-run --server-args=\"-screen 0, 1024x768x24\" '",
"xvfb",
".",
"concat",
"(",
"cmd",
")",
"else",
"cmd",
"end",
"end"
] | Produces the command used to run CutyCapt.
@return [String] | [
"Produces",
"the",
"command",
"used",
"to",
"run",
"CutyCapt",
"."
] | f726e1774a25c4c61f0eab1118e6cffa6ccdbd64 | https://github.com/ezkl/capit/blob/f726e1774a25c4c61f0eab1118e6cffa6ccdbd64/lib/capit/capture.rb#L118-L134 | train |
sosedoff/munin-ruby | lib/munin-ruby/parser.rb | Munin.Parser.parse_config | def parse_config(data)
config = {'graph' => {}, 'metrics' => {}}
data.each do |l|
if l =~ /^graph_/
key_name, value = l.scan(/^graph_([\w]+)\s(.*)/).flatten
config['graph'][key_name] = value
# according to http://munin-monitoring.org/wiki/notes_on_datasource_names
elsif l =~ /^[a-zA-Z_][a-zA-Z\d_]*\./
# according to http://munin-monitoring.org/wiki/fieldnames the second one
# can only be [a-z]
matches = l.scan(/^([a-zA-Z_][a-zA-Z\d_]*)\.([a-z]+)\s(.*)/).flatten
config['metrics'][matches[0]] ||= {}
config['metrics'][matches[0]][matches[1]] = matches[2]
end
end
# Now, lets process the args hash
if config['graph'].key?('args')
config['graph']['args'] = parse_config_args(config['graph']['args'])
end
config
end | ruby | def parse_config(data)
config = {'graph' => {}, 'metrics' => {}}
data.each do |l|
if l =~ /^graph_/
key_name, value = l.scan(/^graph_([\w]+)\s(.*)/).flatten
config['graph'][key_name] = value
# according to http://munin-monitoring.org/wiki/notes_on_datasource_names
elsif l =~ /^[a-zA-Z_][a-zA-Z\d_]*\./
# according to http://munin-monitoring.org/wiki/fieldnames the second one
# can only be [a-z]
matches = l.scan(/^([a-zA-Z_][a-zA-Z\d_]*)\.([a-z]+)\s(.*)/).flatten
config['metrics'][matches[0]] ||= {}
config['metrics'][matches[0]][matches[1]] = matches[2]
end
end
# Now, lets process the args hash
if config['graph'].key?('args')
config['graph']['args'] = parse_config_args(config['graph']['args'])
end
config
end | [
"def",
"parse_config",
"(",
"data",
")",
"config",
"=",
"{",
"'graph'",
"=>",
"{",
"}",
",",
"'metrics'",
"=>",
"{",
"}",
"}",
"data",
".",
"each",
"do",
"|",
"l",
"|",
"if",
"l",
"=~",
"/",
"/",
"key_name",
",",
"value",
"=",
"l",
".",
"scan",
"(",
"/",
"\\w",
"\\s",
"/",
")",
".",
"flatten",
"config",
"[",
"'graph'",
"]",
"[",
"key_name",
"]",
"=",
"value",
"elsif",
"l",
"=~",
"/",
"\\d",
"\\.",
"/",
"matches",
"=",
"l",
".",
"scan",
"(",
"/",
"\\d",
"\\.",
"\\s",
"/",
")",
".",
"flatten",
"config",
"[",
"'metrics'",
"]",
"[",
"matches",
"[",
"0",
"]",
"]",
"||=",
"{",
"}",
"config",
"[",
"'metrics'",
"]",
"[",
"matches",
"[",
"0",
"]",
"]",
"[",
"matches",
"[",
"1",
"]",
"]",
"=",
"matches",
"[",
"2",
"]",
"end",
"end",
"if",
"config",
"[",
"'graph'",
"]",
".",
"key?",
"(",
"'args'",
")",
"config",
"[",
"'graph'",
"]",
"[",
"'args'",
"]",
"=",
"parse_config_args",
"(",
"config",
"[",
"'graph'",
"]",
"[",
"'args'",
"]",
")",
"end",
"config",
"end"
] | Parse 'config' request | [
"Parse",
"config",
"request"
] | 28f65b0abb88fc40e234b6af327094992504be6a | https://github.com/sosedoff/munin-ruby/blob/28f65b0abb88fc40e234b6af327094992504be6a/lib/munin-ruby/parser.rb#L27-L49 | train |
sosedoff/munin-ruby | lib/munin-ruby/parser.rb | Munin.Parser.parse_error | def parse_error(lines)
if lines.size == 1
case lines.first
when '# Unknown service' then raise UnknownService
when '# Bad exit' then raise BadExit
end
end
end | ruby | def parse_error(lines)
if lines.size == 1
case lines.first
when '# Unknown service' then raise UnknownService
when '# Bad exit' then raise BadExit
end
end
end | [
"def",
"parse_error",
"(",
"lines",
")",
"if",
"lines",
".",
"size",
"==",
"1",
"case",
"lines",
".",
"first",
"when",
"'# Unknown service'",
"then",
"raise",
"UnknownService",
"when",
"'# Bad exit'",
"then",
"raise",
"BadExit",
"end",
"end",
"end"
] | Detect error from output | [
"Detect",
"error",
"from",
"output"
] | 28f65b0abb88fc40e234b6af327094992504be6a | https://github.com/sosedoff/munin-ruby/blob/28f65b0abb88fc40e234b6af327094992504be6a/lib/munin-ruby/parser.rb#L59-L66 | train |
sosedoff/munin-ruby | lib/munin-ruby/parser.rb | Munin.Parser.parse_config_args | def parse_config_args(args)
result = {}
args.scan(/--?([a-z\-\_]+)\s([\d]+)\s?/).each do |arg|
result[arg.first] = arg.last
end
{'raw' => args, 'parsed' => result}
end | ruby | def parse_config_args(args)
result = {}
args.scan(/--?([a-z\-\_]+)\s([\d]+)\s?/).each do |arg|
result[arg.first] = arg.last
end
{'raw' => args, 'parsed' => result}
end | [
"def",
"parse_config_args",
"(",
"args",
")",
"result",
"=",
"{",
"}",
"args",
".",
"scan",
"(",
"/",
"\\-",
"\\_",
"\\s",
"\\d",
"\\s",
"/",
")",
".",
"each",
"do",
"|",
"arg",
"|",
"result",
"[",
"arg",
".",
"first",
"]",
"=",
"arg",
".",
"last",
"end",
"{",
"'raw'",
"=>",
"args",
",",
"'parsed'",
"=>",
"result",
"}",
"end"
] | Parse configuration arguments | [
"Parse",
"configuration",
"arguments"
] | 28f65b0abb88fc40e234b6af327094992504be6a | https://github.com/sosedoff/munin-ruby/blob/28f65b0abb88fc40e234b6af327094992504be6a/lib/munin-ruby/parser.rb#L70-L76 | train |
ocha/devise_ott | lib/devise_ott/tokens.rb | DeviseOtt.Tokens.register | def register(token, email, granted_to_email, access_count, expire)
save_config(token, {email: email, granted_to_email: granted_to_email, access_count: access_count})
@redis.expire(token, expire)
token
end | ruby | def register(token, email, granted_to_email, access_count, expire)
save_config(token, {email: email, granted_to_email: granted_to_email, access_count: access_count})
@redis.expire(token, expire)
token
end | [
"def",
"register",
"(",
"token",
",",
"email",
",",
"granted_to_email",
",",
"access_count",
",",
"expire",
")",
"save_config",
"(",
"token",
",",
"{",
"email",
":",
"email",
",",
"granted_to_email",
":",
"granted_to_email",
",",
"access_count",
":",
"access_count",
"}",
")",
"@redis",
".",
"expire",
"(",
"token",
",",
"expire",
")",
"token",
"end"
] | register one time token for given user in redis
the generated token will have a field "email" in order to identify the associated user later | [
"register",
"one",
"time",
"token",
"for",
"given",
"user",
"in",
"redis",
"the",
"generated",
"token",
"will",
"have",
"a",
"field",
"email",
"in",
"order",
"to",
"identify",
"the",
"associated",
"user",
"later"
] | ebf39fff2ef1d4f901db11994b0ebafdfcddb0ea | https://github.com/ocha/devise_ott/blob/ebf39fff2ef1d4f901db11994b0ebafdfcddb0ea/lib/devise_ott/tokens.rb#L18-L23 | train |
ocha/devise_ott | lib/devise_ott/tokens.rb | DeviseOtt.Tokens.access | def access(token, email)
config = load_config(token)
return false unless config
return false unless config[:email].to_s == email.to_s
return false unless config[:access_count] > 0
save_config(token, config.merge(access_count: config[:access_count] - 1))
true
end | ruby | def access(token, email)
config = load_config(token)
return false unless config
return false unless config[:email].to_s == email.to_s
return false unless config[:access_count] > 0
save_config(token, config.merge(access_count: config[:access_count] - 1))
true
end | [
"def",
"access",
"(",
"token",
",",
"email",
")",
"config",
"=",
"load_config",
"(",
"token",
")",
"return",
"false",
"unless",
"config",
"return",
"false",
"unless",
"config",
"[",
":email",
"]",
".",
"to_s",
"==",
"email",
".",
"to_s",
"return",
"false",
"unless",
"config",
"[",
":access_count",
"]",
">",
"0",
"save_config",
"(",
"token",
",",
"config",
".",
"merge",
"(",
"access_count",
":",
"config",
"[",
":access_count",
"]",
"-",
"1",
")",
")",
"true",
"end"
] | accesses token for given email if it is allowed | [
"accesses",
"token",
"for",
"given",
"email",
"if",
"it",
"is",
"allowed"
] | ebf39fff2ef1d4f901db11994b0ebafdfcddb0ea | https://github.com/ocha/devise_ott/blob/ebf39fff2ef1d4f901db11994b0ebafdfcddb0ea/lib/devise_ott/tokens.rb#L31-L41 | train |
dryade/georuby-ext | lib/georuby-ext/geokit.rb | GeoKit.LatLng.wgs84_to_google | def wgs84_to_google
ActiveSupport::Deprecation.warn "use Point geometry which supports srid"
self.class.from_pro4j Proj4::Projection.wgs84.transform Proj4::Projection.google, self.proj4_point(Math::PI / 180).x, self.proj4_point(Math::PI / 180).y
end | ruby | def wgs84_to_google
ActiveSupport::Deprecation.warn "use Point geometry which supports srid"
self.class.from_pro4j Proj4::Projection.wgs84.transform Proj4::Projection.google, self.proj4_point(Math::PI / 180).x, self.proj4_point(Math::PI / 180).y
end | [
"def",
"wgs84_to_google",
"ActiveSupport",
"::",
"Deprecation",
".",
"warn",
"\"use Point geometry which supports srid\"",
"self",
".",
"class",
".",
"from_pro4j",
"Proj4",
"::",
"Projection",
".",
"wgs84",
".",
"transform",
"Proj4",
"::",
"Projection",
".",
"google",
",",
"self",
".",
"proj4_point",
"(",
"Math",
"::",
"PI",
"/",
"180",
")",
".",
"x",
",",
"self",
".",
"proj4_point",
"(",
"Math",
"::",
"PI",
"/",
"180",
")",
".",
"y",
"end"
] | DEPRECATED
Use Point geometry which supports srid | [
"DEPRECATED",
"Use",
"Point",
"geometry",
"which",
"supports",
"srid"
] | 8c5aa1436868f970ea07c169ad9761b495e3a798 | https://github.com/dryade/georuby-ext/blob/8c5aa1436868f970ea07c169ad9761b495e3a798/lib/georuby-ext/geokit.rb#L13-L16 | train |
unipept/unipept-cli | lib/server_message.rb | Unipept.ServerMessage.print | def print
return unless $stdout.tty?
return if recently_fetched?
resp = fetch_server_message
update_fetched
puts resp unless resp.empty?
end | ruby | def print
return unless $stdout.tty?
return if recently_fetched?
resp = fetch_server_message
update_fetched
puts resp unless resp.empty?
end | [
"def",
"print",
"return",
"unless",
"$stdout",
".",
"tty?",
"return",
"if",
"recently_fetched?",
"resp",
"=",
"fetch_server_message",
"update_fetched",
"puts",
"resp",
"unless",
"resp",
".",
"empty?",
"end"
] | Checks if the server has a message and prints it if not empty.
We will only check this once a day and won't print anything if the quiet
option is set or if we output to a file. | [
"Checks",
"if",
"the",
"server",
"has",
"a",
"message",
"and",
"prints",
"it",
"if",
"not",
"empty",
".",
"We",
"will",
"only",
"check",
"this",
"once",
"a",
"day",
"and",
"won",
"t",
"print",
"anything",
"if",
"the",
"quiet",
"option",
"is",
"set",
"or",
"if",
"we",
"output",
"to",
"a",
"file",
"."
] | 183779bd1dffcd01ed623685c789160153b78681 | https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/server_message.rb#L19-L26 | train |
phatworx/rails_paginate | lib/rails_paginate/renderers/html_default.rb | RailsPaginate::Renderers.HtmlDefault.render | def render
content_tag(:ul) do
html = "\n"
if show_first_page?
html += content_tag(:li, :class => "first_page") do
link_to_page collection.first_page, 'paginate.first_page_label'
end
html += "\n"
end
if show_previous_page?
html += content_tag(:li, :class => "previous_page") do
link_to_page collection.previous_page, 'paginate.previous_page_label'
end
html += "\n"
end
html += render_pager
if show_next_page?
html += content_tag(:li, :class => "next_page") do
link_to_page collection.next_page, 'paginate.next_page_label'
end
html += "\n"
end
if show_last_page?
html += content_tag(:li, :class => "last_page") do
link_to_page collection.last_page, 'paginate.last_page_label'
end
html += "\n"
end
html.html_safe
end
end | ruby | def render
content_tag(:ul) do
html = "\n"
if show_first_page?
html += content_tag(:li, :class => "first_page") do
link_to_page collection.first_page, 'paginate.first_page_label'
end
html += "\n"
end
if show_previous_page?
html += content_tag(:li, :class => "previous_page") do
link_to_page collection.previous_page, 'paginate.previous_page_label'
end
html += "\n"
end
html += render_pager
if show_next_page?
html += content_tag(:li, :class => "next_page") do
link_to_page collection.next_page, 'paginate.next_page_label'
end
html += "\n"
end
if show_last_page?
html += content_tag(:li, :class => "last_page") do
link_to_page collection.last_page, 'paginate.last_page_label'
end
html += "\n"
end
html.html_safe
end
end | [
"def",
"render",
"content_tag",
"(",
":ul",
")",
"do",
"html",
"=",
"\"\\n\"",
"if",
"show_first_page?",
"html",
"+=",
"content_tag",
"(",
":li",
",",
":class",
"=>",
"\"first_page\"",
")",
"do",
"link_to_page",
"collection",
".",
"first_page",
",",
"'paginate.first_page_label'",
"end",
"html",
"+=",
"\"\\n\"",
"end",
"if",
"show_previous_page?",
"html",
"+=",
"content_tag",
"(",
":li",
",",
":class",
"=>",
"\"previous_page\"",
")",
"do",
"link_to_page",
"collection",
".",
"previous_page",
",",
"'paginate.previous_page_label'",
"end",
"html",
"+=",
"\"\\n\"",
"end",
"html",
"+=",
"render_pager",
"if",
"show_next_page?",
"html",
"+=",
"content_tag",
"(",
":li",
",",
":class",
"=>",
"\"next_page\"",
")",
"do",
"link_to_page",
"collection",
".",
"next_page",
",",
"'paginate.next_page_label'",
"end",
"html",
"+=",
"\"\\n\"",
"end",
"if",
"show_last_page?",
"html",
"+=",
"content_tag",
"(",
":li",
",",
":class",
"=>",
"\"last_page\"",
")",
"do",
"link_to_page",
"collection",
".",
"last_page",
",",
"'paginate.last_page_label'",
"end",
"html",
"+=",
"\"\\n\"",
"end",
"html",
".",
"html_safe",
"end",
"end"
] | render html for pagination | [
"render",
"html",
"for",
"pagination"
] | ae8cbc12030853b236dc2cbf6ede8700fb835771 | https://github.com/phatworx/rails_paginate/blob/ae8cbc12030853b236dc2cbf6ede8700fb835771/lib/rails_paginate/renderers/html_default.rb#L22-L57 | train |
smolnar/squire | lib/squire/configuration.rb | Squire.Configuration.namespace | def namespace(namespace = nil, options = {})
return @namespace unless namespace
@namespace = namespace.to_sym if namespace
@base_namespace = options[:base].to_sym if options[:base]
end | ruby | def namespace(namespace = nil, options = {})
return @namespace unless namespace
@namespace = namespace.to_sym if namespace
@base_namespace = options[:base].to_sym if options[:base]
end | [
"def",
"namespace",
"(",
"namespace",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"return",
"@namespace",
"unless",
"namespace",
"@namespace",
"=",
"namespace",
".",
"to_sym",
"if",
"namespace",
"@base_namespace",
"=",
"options",
"[",
":base",
"]",
".",
"to_sym",
"if",
"options",
"[",
":base",
"]",
"end"
] | Sets and returns +namespace+.
If called without parameters, returns +namespace+.
Possible options:
* <tt>:base</tt> - base namespace used for deep merging of values of other namespaces | [
"Sets",
"and",
"returns",
"+",
"namespace",
"+",
".",
"If",
"called",
"without",
"parameters",
"returns",
"+",
"namespace",
"+",
"."
] | f9175cf007ccadefe4cd77f34271f76e311c2d60 | https://github.com/smolnar/squire/blob/f9175cf007ccadefe4cd77f34271f76e311c2d60/lib/squire/configuration.rb#L11-L16 | train |
smolnar/squire | lib/squire/configuration.rb | Squire.Configuration.source | def source(source = nil, options = {})
return @source unless source
@source = source
@parser = options[:parser]
@type = options[:type]
@type ||= source.is_a?(Hash) ? :hash : File.extname(@source)[1..-1].to_sym
end | ruby | def source(source = nil, options = {})
return @source unless source
@source = source
@parser = options[:parser]
@type = options[:type]
@type ||= source.is_a?(Hash) ? :hash : File.extname(@source)[1..-1].to_sym
end | [
"def",
"source",
"(",
"source",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"return",
"@source",
"unless",
"source",
"@source",
"=",
"source",
"@parser",
"=",
"options",
"[",
":parser",
"]",
"@type",
"=",
"options",
"[",
":type",
"]",
"@type",
"||=",
"source",
".",
"is_a?",
"(",
"Hash",
")",
"?",
":hash",
":",
"File",
".",
"extname",
"(",
"@source",
")",
"[",
"1",
"..",
"-",
"1",
"]",
".",
"to_sym",
"end"
] | Sets +source+ for the configuration
If called without parameters, returns +source+.
Possible options:
* <tt>:type</tt> - type of +source+ (optional, based on file extension)
* <tt>:parser</tt> - parse of input +source+ (optional, based on +:type+) | [
"Sets",
"+",
"source",
"+",
"for",
"the",
"configuration",
"If",
"called",
"without",
"parameters",
"returns",
"+",
"source",
"+",
"."
] | f9175cf007ccadefe4cd77f34271f76e311c2d60 | https://github.com/smolnar/squire/blob/f9175cf007ccadefe4cd77f34271f76e311c2d60/lib/squire/configuration.rb#L25-L33 | train |
smolnar/squire | lib/squire/configuration.rb | Squire.Configuration.settings | def settings(&block)
@settings ||= setup
settings = instance_variable_defined?(:@namespace) ? @settings.get_value(@namespace) : @settings
if block_given?
block.arity == 0 ? settings.instance_eval(&block) : block.call(settings)
end
settings
end | ruby | def settings(&block)
@settings ||= setup
settings = instance_variable_defined?(:@namespace) ? @settings.get_value(@namespace) : @settings
if block_given?
block.arity == 0 ? settings.instance_eval(&block) : block.call(settings)
end
settings
end | [
"def",
"settings",
"(",
"&",
"block",
")",
"@settings",
"||=",
"setup",
"settings",
"=",
"instance_variable_defined?",
"(",
":@namespace",
")",
"?",
"@settings",
".",
"get_value",
"(",
"@namespace",
")",
":",
"@settings",
"if",
"block_given?",
"block",
".",
"arity",
"==",
"0",
"?",
"settings",
".",
"instance_eval",
"(",
"&",
"block",
")",
":",
"block",
".",
"call",
"(",
"settings",
")",
"end",
"settings",
"end"
] | Loaded configuration stored in Settings class.
Accepts +block+ as parameter.
== Examples
settings do |settings|
settings.a = 1
end
settings do
a 1
end
settings.a = 1 | [
"Loaded",
"configuration",
"stored",
"in",
"Settings",
"class",
".",
"Accepts",
"+",
"block",
"+",
"as",
"parameter",
"."
] | f9175cf007ccadefe4cd77f34271f76e311c2d60 | https://github.com/smolnar/squire/blob/f9175cf007ccadefe4cd77f34271f76e311c2d60/lib/squire/configuration.rb#L49-L59 | train |
smolnar/squire | lib/squire/configuration.rb | Squire.Configuration.setup | def setup
return Squire::Settings.new unless @source
parser = Squire::Parser.of(@type)
hash = parser.parse(source).with_indifferent_access
if base_namespace
hash.except(base_namespace).each do |key, values|
# favours value from namespace over value from defaults
hash[key] = hash[base_namespace].deep_merge(values) { |_, default, value| value.nil? ? default : value }
end
end
Squire::Settings.from_hash(hash)
end | ruby | def setup
return Squire::Settings.new unless @source
parser = Squire::Parser.of(@type)
hash = parser.parse(source).with_indifferent_access
if base_namespace
hash.except(base_namespace).each do |key, values|
# favours value from namespace over value from defaults
hash[key] = hash[base_namespace].deep_merge(values) { |_, default, value| value.nil? ? default : value }
end
end
Squire::Settings.from_hash(hash)
end | [
"def",
"setup",
"return",
"Squire",
"::",
"Settings",
".",
"new",
"unless",
"@source",
"parser",
"=",
"Squire",
"::",
"Parser",
".",
"of",
"(",
"@type",
")",
"hash",
"=",
"parser",
".",
"parse",
"(",
"source",
")",
".",
"with_indifferent_access",
"if",
"base_namespace",
"hash",
".",
"except",
"(",
"base_namespace",
")",
".",
"each",
"do",
"|",
"key",
",",
"values",
"|",
"hash",
"[",
"key",
"]",
"=",
"hash",
"[",
"base_namespace",
"]",
".",
"deep_merge",
"(",
"values",
")",
"{",
"|",
"_",
",",
"default",
",",
"value",
"|",
"value",
".",
"nil?",
"?",
"default",
":",
"value",
"}",
"end",
"end",
"Squire",
"::",
"Settings",
".",
"from_hash",
"(",
"hash",
")",
"end"
] | Sets up the configuration based on +namespace+ and +source+.
If +base_namespace+ provided, merges it's values with other namespaces for handling
nested overriding of values.
Favours values from +namespace+ over values from +base_namespace+. | [
"Sets",
"up",
"the",
"configuration",
"based",
"on",
"+",
"namespace",
"+",
"and",
"+",
"source",
"+",
".",
"If",
"+",
"base_namespace",
"+",
"provided",
"merges",
"it",
"s",
"values",
"with",
"other",
"namespaces",
"for",
"handling",
"nested",
"overriding",
"of",
"values",
"."
] | f9175cf007ccadefe4cd77f34271f76e311c2d60 | https://github.com/smolnar/squire/blob/f9175cf007ccadefe4cd77f34271f76e311c2d60/lib/squire/configuration.rb#L69-L84 | train |
isabanin/mercurial-ruby | lib/mercurial-ruby/factories/commit_factory.rb | Mercurial.CommitFactory.count_range | def count_range(hash_a, hash_b, cmd_options={})
hg_to_array([%Q[log -r ?:? --template "{node}\n"], hash_a, hash_b], {}, cmd_options) do |line|
line
end.size
end | ruby | def count_range(hash_a, hash_b, cmd_options={})
hg_to_array([%Q[log -r ?:? --template "{node}\n"], hash_a, hash_b], {}, cmd_options) do |line|
line
end.size
end | [
"def",
"count_range",
"(",
"hash_a",
",",
"hash_b",
",",
"cmd_options",
"=",
"{",
"}",
")",
"hg_to_array",
"(",
"[",
"%Q[log -r ?:? --template \"{node}\\n\"]",
",",
"hash_a",
",",
"hash_b",
"]",
",",
"{",
"}",
",",
"cmd_options",
")",
"do",
"|",
"line",
"|",
"line",
"end",
".",
"size",
"end"
] | Count changesets in the range from hash_a to hash_b in the repository.
=== Example:
repository.commits.count_range(hash_a, hash_b) | [
"Count",
"changesets",
"in",
"the",
"range",
"from",
"hash_a",
"to",
"hash_b",
"in",
"the",
"repository",
"."
] | d7cc2d3bfeaa7564f6ea8d622fbddd92ca5a3d0a | https://github.com/isabanin/mercurial-ruby/blob/d7cc2d3bfeaa7564f6ea8d622fbddd92ca5a3d0a/lib/mercurial-ruby/factories/commit_factory.rb#L69-L73 | train |
pacop/adfly | lib/adfly/adfly.rb | Adfly.API.create_link | def create_link data
body = http_get URL_API, {key: @key, uid: @uid}.merge(data)
raise ArgumentError if body.nil? || body.empty?
body
end | ruby | def create_link data
body = http_get URL_API, {key: @key, uid: @uid}.merge(data)
raise ArgumentError if body.nil? || body.empty?
body
end | [
"def",
"create_link",
"data",
"body",
"=",
"http_get",
"URL_API",
",",
"{",
"key",
":",
"@key",
",",
"uid",
":",
"@uid",
"}",
".",
"merge",
"(",
"data",
")",
"raise",
"ArgumentError",
"if",
"body",
".",
"nil?",
"||",
"body",
".",
"empty?",
"body",
"end"
] | Create instance to use API adfly
If you want to get API key from https://adf.ly/publisher/tools#tools-api
@param uid [String] Uid
@param key [String] Key
Create single link
Maybe you want to see https://adf.ly/publisher/tools#tools-api
@param data [Hash] data to send api
@option data [String] :url Link to be converted
@option data [Symbol] :advert_type Type of advertisement(:int or :banner)
@option data [String] :domain Alias domain to be used for ther generated link
@example Simple use
adfly.create_link(url: 'http://www.google.es')
@return [String] Short link
@raise [ArgumentError] Invalid parameters, link cannot be created | [
"Create",
"instance",
"to",
"use",
"API",
"adfly"
] | e27bdaf22fafc83657ebbd696b2591306362d2b0 | https://github.com/pacop/adfly/blob/e27bdaf22fafc83657ebbd696b2591306362d2b0/lib/adfly/adfly.rb#L37-L42 | train |
Mik-die/mongoid_globalize | lib/mongoid_globalize/fields_builder.rb | Mongoid::Globalize.FieldsBuilder.field | def field(name, *params)
@model.translated_attribute_names.push name.to_sym
@model.translated_attr_accessor(name)
@model.translation_class.field name, *params
end | ruby | def field(name, *params)
@model.translated_attribute_names.push name.to_sym
@model.translated_attr_accessor(name)
@model.translation_class.field name, *params
end | [
"def",
"field",
"(",
"name",
",",
"*",
"params",
")",
"@model",
".",
"translated_attribute_names",
".",
"push",
"name",
".",
"to_sym",
"@model",
".",
"translated_attr_accessor",
"(",
"name",
")",
"@model",
".",
"translation_class",
".",
"field",
"name",
",",
"*",
"params",
"end"
] | Initializes new istance of FieldsBuilder.
Param Class
Creates new field in translation document.
Param String or Symbol
Other params are the same as for Mongoid's +field+ | [
"Initializes",
"new",
"istance",
"of",
"FieldsBuilder",
".",
"Param",
"Class",
"Creates",
"new",
"field",
"in",
"translation",
"document",
".",
"Param",
"String",
"or",
"Symbol",
"Other",
"params",
"are",
"the",
"same",
"as",
"for",
"Mongoid",
"s",
"+",
"field",
"+"
] | 458105154574950aed98119fd54ffaae4e1a55ee | https://github.com/Mik-die/mongoid_globalize/blob/458105154574950aed98119fd54ffaae4e1a55ee/lib/mongoid_globalize/fields_builder.rb#L12-L16 | train |
marcelofabri/danger-simplecov_json | lib/simplecov_json/plugin.rb | Danger.DangerSimpleCovJson.report | def report(coverage_path, sticky: true)
if File.exist? coverage_path
coverage_json = JSON.parse(File.read(coverage_path), symbolize_names: true)
metrics = coverage_json[:metrics]
percentage = metrics[:covered_percent]
lines = metrics[:covered_lines]
total_lines = metrics[:total_lines]
formatted_percentage = format('%.02f', percentage)
message("Code coverage is now at #{formatted_percentage}% (#{lines}/#{total_lines} lines)", sticky: sticky)
else
fail('Code coverage data not found')
end
end | ruby | def report(coverage_path, sticky: true)
if File.exist? coverage_path
coverage_json = JSON.parse(File.read(coverage_path), symbolize_names: true)
metrics = coverage_json[:metrics]
percentage = metrics[:covered_percent]
lines = metrics[:covered_lines]
total_lines = metrics[:total_lines]
formatted_percentage = format('%.02f', percentage)
message("Code coverage is now at #{formatted_percentage}% (#{lines}/#{total_lines} lines)", sticky: sticky)
else
fail('Code coverage data not found')
end
end | [
"def",
"report",
"(",
"coverage_path",
",",
"sticky",
":",
"true",
")",
"if",
"File",
".",
"exist?",
"coverage_path",
"coverage_json",
"=",
"JSON",
".",
"parse",
"(",
"File",
".",
"read",
"(",
"coverage_path",
")",
",",
"symbolize_names",
":",
"true",
")",
"metrics",
"=",
"coverage_json",
"[",
":metrics",
"]",
"percentage",
"=",
"metrics",
"[",
":covered_percent",
"]",
"lines",
"=",
"metrics",
"[",
":covered_lines",
"]",
"total_lines",
"=",
"metrics",
"[",
":total_lines",
"]",
"formatted_percentage",
"=",
"format",
"(",
"'%.02f'",
",",
"percentage",
")",
"message",
"(",
"\"Code coverage is now at #{formatted_percentage}% (#{lines}/#{total_lines} lines)\"",
",",
"sticky",
":",
"sticky",
")",
"else",
"fail",
"(",
"'Code coverage data not found'",
")",
"end",
"end"
] | Parse a JSON code coverage file and report that information as a
message in Danger.
@return [void] | [
"Parse",
"a",
"JSON",
"code",
"coverage",
"file",
"and",
"report",
"that",
"information",
"as",
"a",
"message",
"in",
"Danger",
"."
] | 95a0649a3f542741203a3dfed67755ac8dcbfcb1 | https://github.com/marcelofabri/danger-simplecov_json/blob/95a0649a3f542741203a3dfed67755ac8dcbfcb1/lib/simplecov_json/plugin.rb#L22-L35 | train |
marcelofabri/danger-simplecov_json | lib/simplecov_json/plugin.rb | Danger.DangerSimpleCovJson.individual_coverage_message | def individual_coverage_message(covered_files)
require 'terminal-table'
message = "### Code Coverage\n\n"
table = Terminal::Table.new(
headings: %w(File Coverage),
style: { border_i: '|' },
rows: covered_files.map do |file|
[file[:filename], "#{format('%.02f', file[:covered_percent])}%"]
end
).to_s
message + table.split("\n")[1..-2].join("\n")
end | ruby | def individual_coverage_message(covered_files)
require 'terminal-table'
message = "### Code Coverage\n\n"
table = Terminal::Table.new(
headings: %w(File Coverage),
style: { border_i: '|' },
rows: covered_files.map do |file|
[file[:filename], "#{format('%.02f', file[:covered_percent])}%"]
end
).to_s
message + table.split("\n")[1..-2].join("\n")
end | [
"def",
"individual_coverage_message",
"(",
"covered_files",
")",
"require",
"'terminal-table'",
"message",
"=",
"\"### Code Coverage\\n\\n\"",
"table",
"=",
"Terminal",
"::",
"Table",
".",
"new",
"(",
"headings",
":",
"%w(",
"File",
"Coverage",
")",
",",
"style",
":",
"{",
"border_i",
":",
"'|'",
"}",
",",
"rows",
":",
"covered_files",
".",
"map",
"do",
"|",
"file",
"|",
"[",
"file",
"[",
":filename",
"]",
",",
"\"#{format('%.02f', file[:covered_percent])}%\"",
"]",
"end",
")",
".",
"to_s",
"message",
"+",
"table",
".",
"split",
"(",
"\"\\n\"",
")",
"[",
"1",
"..",
"-",
"2",
"]",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] | Builds the markdown table displaying coverage on individual files
@param [Array] covered_files
@return [String] Markdown table | [
"Builds",
"the",
"markdown",
"table",
"displaying",
"coverage",
"on",
"individual",
"files"
] | 95a0649a3f542741203a3dfed67755ac8dcbfcb1 | https://github.com/marcelofabri/danger-simplecov_json/blob/95a0649a3f542741203a3dfed67755ac8dcbfcb1/lib/simplecov_json/plugin.rb#L69-L81 | train |
miketheman/knife-community | lib/chef/knife/community_release.rb | KnifeCommunity.CommunityRelease.validate_args | def validate_args
if name_args.size < 1
ui.error('No cookbook has been specified')
show_usage
exit 1
end
if name_args.size > 2
ui.error('Too many arguments are being passed. Please verify.')
show_usage
exit 1
end
end | ruby | def validate_args
if name_args.size < 1
ui.error('No cookbook has been specified')
show_usage
exit 1
end
if name_args.size > 2
ui.error('Too many arguments are being passed. Please verify.')
show_usage
exit 1
end
end | [
"def",
"validate_args",
"if",
"name_args",
".",
"size",
"<",
"1",
"ui",
".",
"error",
"(",
"'No cookbook has been specified'",
")",
"show_usage",
"exit",
"1",
"end",
"if",
"name_args",
".",
"size",
">",
"2",
"ui",
".",
"error",
"(",
"'Too many arguments are being passed. Please verify.'",
")",
"show_usage",
"exit",
"1",
"end",
"end"
] | Ensure argumanets are valid, assign values of arguments
@param [Array] the global `name_args` object | [
"Ensure",
"argumanets",
"are",
"valid",
"assign",
"values",
"of",
"arguments"
] | fc7b4f7482d0ff9b8ac32636ad369227eb909be7 | https://github.com/miketheman/knife-community/blob/fc7b4f7482d0ff9b8ac32636ad369227eb909be7/lib/chef/knife/community_release.rb#L119-L130 | train |
miketheman/knife-community | lib/chef/knife/community_release.rb | KnifeCommunity.CommunityRelease.validate_repo_clean | def validate_repo_clean
@gitrepo = Grit::Repo.new(@repo_root)
status = @gitrepo.status
if !status.changed.nil? || status.changed.size != 0 # This has to be a convoluted way to determine a non-empty...
# Test each for the magic sha_index. Ref: https://github.com/mojombo/grit/issues/142
status.changed.each do |file|
case file[1].sha_index
when '0' * 40
ui.error 'There seem to be unstaged changes in your repo. Either stash or add them.'
exit 4
else
ui.msg 'There are modified files that have been staged, and will be included in the push.'
end
end
elsif status.untracked.size > 0
ui.warn 'There are untracked files in your repo. You might want to look into that.'
end
end | ruby | def validate_repo_clean
@gitrepo = Grit::Repo.new(@repo_root)
status = @gitrepo.status
if !status.changed.nil? || status.changed.size != 0 # This has to be a convoluted way to determine a non-empty...
# Test each for the magic sha_index. Ref: https://github.com/mojombo/grit/issues/142
status.changed.each do |file|
case file[1].sha_index
when '0' * 40
ui.error 'There seem to be unstaged changes in your repo. Either stash or add them.'
exit 4
else
ui.msg 'There are modified files that have been staged, and will be included in the push.'
end
end
elsif status.untracked.size > 0
ui.warn 'There are untracked files in your repo. You might want to look into that.'
end
end | [
"def",
"validate_repo_clean",
"@gitrepo",
"=",
"Grit",
"::",
"Repo",
".",
"new",
"(",
"@repo_root",
")",
"status",
"=",
"@gitrepo",
".",
"status",
"if",
"!",
"status",
".",
"changed",
".",
"nil?",
"||",
"status",
".",
"changed",
".",
"size",
"!=",
"0",
"status",
".",
"changed",
".",
"each",
"do",
"|",
"file",
"|",
"case",
"file",
"[",
"1",
"]",
".",
"sha_index",
"when",
"'0'",
"*",
"40",
"ui",
".",
"error",
"'There seem to be unstaged changes in your repo. Either stash or add them.'",
"exit",
"4",
"else",
"ui",
".",
"msg",
"'There are modified files that have been staged, and will be included in the push.'",
"end",
"end",
"elsif",
"status",
".",
"untracked",
".",
"size",
">",
"0",
"ui",
".",
"warn",
"'There are untracked files in your repo. You might want to look into that.'",
"end",
"end"
] | Inspect the cookbook directory's git status is good to push.
Any existing tracked files should be staged, otherwise error & exit.
Untracked files are warned about, but will allow continue.
This needs more testing. | [
"Inspect",
"the",
"cookbook",
"directory",
"s",
"git",
"status",
"is",
"good",
"to",
"push",
".",
"Any",
"existing",
"tracked",
"files",
"should",
"be",
"staged",
"otherwise",
"error",
"&",
"exit",
".",
"Untracked",
"files",
"are",
"warned",
"about",
"but",
"will",
"allow",
"continue",
".",
"This",
"needs",
"more",
"testing",
"."
] | fc7b4f7482d0ff9b8ac32636ad369227eb909be7 | https://github.com/miketheman/knife-community/blob/fc7b4f7482d0ff9b8ac32636ad369227eb909be7/lib/chef/knife/community_release.rb#L150-L167 | train |
miketheman/knife-community | lib/chef/knife/community_release.rb | KnifeCommunity.CommunityRelease.validate_no_existing_tag | def validate_no_existing_tag(tag_string)
existing_tags = []
@gitrepo.tags.each { |tag| existing_tags << tag.name }
if existing_tags.include?(tag_string)
ui.error 'This version tag has already been committed to the repo.'
ui.error "Are you sure you haven't released this already?"
exit 6
end
end | ruby | def validate_no_existing_tag(tag_string)
existing_tags = []
@gitrepo.tags.each { |tag| existing_tags << tag.name }
if existing_tags.include?(tag_string)
ui.error 'This version tag has already been committed to the repo.'
ui.error "Are you sure you haven't released this already?"
exit 6
end
end | [
"def",
"validate_no_existing_tag",
"(",
"tag_string",
")",
"existing_tags",
"=",
"[",
"]",
"@gitrepo",
".",
"tags",
".",
"each",
"{",
"|",
"tag",
"|",
"existing_tags",
"<<",
"tag",
".",
"name",
"}",
"if",
"existing_tags",
".",
"include?",
"(",
"tag_string",
")",
"ui",
".",
"error",
"'This version tag has already been committed to the repo.'",
"ui",
".",
"error",
"\"Are you sure you haven't released this already?\"",
"exit",
"6",
"end",
"end"
] | Ensure that there isn't already a git tag for this version. | [
"Ensure",
"that",
"there",
"isn",
"t",
"already",
"a",
"git",
"tag",
"for",
"this",
"version",
"."
] | fc7b4f7482d0ff9b8ac32636ad369227eb909be7 | https://github.com/miketheman/knife-community/blob/fc7b4f7482d0ff9b8ac32636ad369227eb909be7/lib/chef/knife/community_release.rb#L170-L178 | train |
miketheman/knife-community | lib/chef/knife/community_release.rb | KnifeCommunity.CommunityRelease.validate_target_remote_branch | def validate_target_remote_branch
remote_path = File.join(config[:remote], config[:branch])
remotes = []
@gitrepo.remotes.each { |remote| remotes << remote.name }
unless remotes.include?(remote_path)
ui.error 'The remote/branch specified does not seem to exist.'
exit 7
end
end | ruby | def validate_target_remote_branch
remote_path = File.join(config[:remote], config[:branch])
remotes = []
@gitrepo.remotes.each { |remote| remotes << remote.name }
unless remotes.include?(remote_path)
ui.error 'The remote/branch specified does not seem to exist.'
exit 7
end
end | [
"def",
"validate_target_remote_branch",
"remote_path",
"=",
"File",
".",
"join",
"(",
"config",
"[",
":remote",
"]",
",",
"config",
"[",
":branch",
"]",
")",
"remotes",
"=",
"[",
"]",
"@gitrepo",
".",
"remotes",
".",
"each",
"{",
"|",
"remote",
"|",
"remotes",
"<<",
"remote",
".",
"name",
"}",
"unless",
"remotes",
".",
"include?",
"(",
"remote_path",
")",
"ui",
".",
"error",
"'The remote/branch specified does not seem to exist.'",
"exit",
"7",
"end",
"end"
] | Ensure that the remote and branch are indeed valid. We provide defaults in options. | [
"Ensure",
"that",
"the",
"remote",
"and",
"branch",
"are",
"indeed",
"valid",
".",
"We",
"provide",
"defaults",
"in",
"options",
"."
] | fc7b4f7482d0ff9b8ac32636ad369227eb909be7 | https://github.com/miketheman/knife-community/blob/fc7b4f7482d0ff9b8ac32636ad369227eb909be7/lib/chef/knife/community_release.rb#L181-L190 | train |
sosedoff/munin-ruby | lib/munin-ruby/node.rb | Munin.Node.nodes | def nodes
nodes = []
cache 'nodes' do
connection.send_data("nodes")
while ( ( line = connection.read_line ) != "." )
nodes << line
end
nodes
end
end | ruby | def nodes
nodes = []
cache 'nodes' do
connection.send_data("nodes")
while ( ( line = connection.read_line ) != "." )
nodes << line
end
nodes
end
end | [
"def",
"nodes",
"nodes",
"=",
"[",
"]",
"cache",
"'nodes'",
"do",
"connection",
".",
"send_data",
"(",
"\"nodes\"",
")",
"while",
"(",
"(",
"line",
"=",
"connection",
".",
"read_line",
")",
"!=",
"\".\"",
")",
"nodes",
"<<",
"line",
"end",
"nodes",
"end",
"end"
] | Get a list of all available nodes | [
"Get",
"a",
"list",
"of",
"all",
"available",
"nodes"
] | 28f65b0abb88fc40e234b6af327094992504be6a | https://github.com/sosedoff/munin-ruby/blob/28f65b0abb88fc40e234b6af327094992504be6a/lib/munin-ruby/node.rb#L47-L56 | train |
sosedoff/munin-ruby | lib/munin-ruby/node.rb | Munin.Node.list | def list(node = "")
cache "list_#{node.empty? ? 'default' : node}" do
connection.send_data("list #{node}")
if ( line = connection.read_line ) != "."
line.split
else
connection.read_line.split
end
end
end | ruby | def list(node = "")
cache "list_#{node.empty? ? 'default' : node}" do
connection.send_data("list #{node}")
if ( line = connection.read_line ) != "."
line.split
else
connection.read_line.split
end
end
end | [
"def",
"list",
"(",
"node",
"=",
"\"\"",
")",
"cache",
"\"list_#{node.empty? ? 'default' : node}\"",
"do",
"connection",
".",
"send_data",
"(",
"\"list #{node}\"",
")",
"if",
"(",
"line",
"=",
"connection",
".",
"read_line",
")",
"!=",
"\".\"",
"line",
".",
"split",
"else",
"connection",
".",
"read_line",
".",
"split",
"end",
"end",
"end"
] | Get a list of all available metrics | [
"Get",
"a",
"list",
"of",
"all",
"available",
"metrics"
] | 28f65b0abb88fc40e234b6af327094992504be6a | https://github.com/sosedoff/munin-ruby/blob/28f65b0abb88fc40e234b6af327094992504be6a/lib/munin-ruby/node.rb#L60-L69 | train |
sosedoff/munin-ruby | lib/munin-ruby/node.rb | Munin.Node.config | def config(services, raw=false)
unless [String, Array].include?(services.class)
raise ArgumentError, "Service(s) argument required"
end
results = {}
names = [services].flatten.uniq
if names.empty?
raise ArgumentError, "Service(s) argument required"
end
key = 'config_' + Digest::MD5.hexdigest(names.to_s) + "_#{raw}"
cache(key) do
names.each do |service|
begin
connection.send_data("config #{service}")
lines = connection.read_packet
results[service] = raw ? lines.join("\n") : parse_config(lines)
rescue UnknownService, BadExit
# TODO
end
end
results
end
end | ruby | def config(services, raw=false)
unless [String, Array].include?(services.class)
raise ArgumentError, "Service(s) argument required"
end
results = {}
names = [services].flatten.uniq
if names.empty?
raise ArgumentError, "Service(s) argument required"
end
key = 'config_' + Digest::MD5.hexdigest(names.to_s) + "_#{raw}"
cache(key) do
names.each do |service|
begin
connection.send_data("config #{service}")
lines = connection.read_packet
results[service] = raw ? lines.join("\n") : parse_config(lines)
rescue UnknownService, BadExit
# TODO
end
end
results
end
end | [
"def",
"config",
"(",
"services",
",",
"raw",
"=",
"false",
")",
"unless",
"[",
"String",
",",
"Array",
"]",
".",
"include?",
"(",
"services",
".",
"class",
")",
"raise",
"ArgumentError",
",",
"\"Service(s) argument required\"",
"end",
"results",
"=",
"{",
"}",
"names",
"=",
"[",
"services",
"]",
".",
"flatten",
".",
"uniq",
"if",
"names",
".",
"empty?",
"raise",
"ArgumentError",
",",
"\"Service(s) argument required\"",
"end",
"key",
"=",
"'config_'",
"+",
"Digest",
"::",
"MD5",
".",
"hexdigest",
"(",
"names",
".",
"to_s",
")",
"+",
"\"_#{raw}\"",
"cache",
"(",
"key",
")",
"do",
"names",
".",
"each",
"do",
"|",
"service",
"|",
"begin",
"connection",
".",
"send_data",
"(",
"\"config #{service}\"",
")",
"lines",
"=",
"connection",
".",
"read_packet",
"results",
"[",
"service",
"]",
"=",
"raw",
"?",
"lines",
".",
"join",
"(",
"\"\\n\"",
")",
":",
"parse_config",
"(",
"lines",
")",
"rescue",
"UnknownService",
",",
"BadExit",
"end",
"end",
"results",
"end",
"end"
] | Get a configuration information for service
services - Name of the service, or list of service names | [
"Get",
"a",
"configuration",
"information",
"for",
"service"
] | 28f65b0abb88fc40e234b6af327094992504be6a | https://github.com/sosedoff/munin-ruby/blob/28f65b0abb88fc40e234b6af327094992504be6a/lib/munin-ruby/node.rb#L75-L101 | train |
sosedoff/munin-ruby | lib/munin-ruby/node.rb | Munin.Node.fetch | def fetch(services)
unless [String, Array].include?(services.class)
raise ArgumentError, "Service(s) argument required"
end
results = {}
names = [services].flatten
if names.empty?
raise ArgumentError, "Service(s) argument required"
end
names.each do |service|
begin
connection.send_data("fetch #{service}")
lines = connection.read_packet
results[service] = parse_fetch(lines)
rescue UnknownService, BadExit
# TODO
end
end
results
end | ruby | def fetch(services)
unless [String, Array].include?(services.class)
raise ArgumentError, "Service(s) argument required"
end
results = {}
names = [services].flatten
if names.empty?
raise ArgumentError, "Service(s) argument required"
end
names.each do |service|
begin
connection.send_data("fetch #{service}")
lines = connection.read_packet
results[service] = parse_fetch(lines)
rescue UnknownService, BadExit
# TODO
end
end
results
end | [
"def",
"fetch",
"(",
"services",
")",
"unless",
"[",
"String",
",",
"Array",
"]",
".",
"include?",
"(",
"services",
".",
"class",
")",
"raise",
"ArgumentError",
",",
"\"Service(s) argument required\"",
"end",
"results",
"=",
"{",
"}",
"names",
"=",
"[",
"services",
"]",
".",
"flatten",
"if",
"names",
".",
"empty?",
"raise",
"ArgumentError",
",",
"\"Service(s) argument required\"",
"end",
"names",
".",
"each",
"do",
"|",
"service",
"|",
"begin",
"connection",
".",
"send_data",
"(",
"\"fetch #{service}\"",
")",
"lines",
"=",
"connection",
".",
"read_packet",
"results",
"[",
"service",
"]",
"=",
"parse_fetch",
"(",
"lines",
")",
"rescue",
"UnknownService",
",",
"BadExit",
"end",
"end",
"results",
"end"
] | Get all service metrics values
services - Name of the service, or list of service names | [
"Get",
"all",
"service",
"metrics",
"values"
] | 28f65b0abb88fc40e234b6af327094992504be6a | https://github.com/sosedoff/munin-ruby/blob/28f65b0abb88fc40e234b6af327094992504be6a/lib/munin-ruby/node.rb#L107-L129 | train |
smolnar/squire | lib/squire/settings.rb | Squire.Settings.get_value | def get_value(key, &block)
key = key.to_sym
value = @table[key]
if block_given?
block.arity == 0 ? value.instance_eval(&block) : block.call(value)
end
value
end | ruby | def get_value(key, &block)
key = key.to_sym
value = @table[key]
if block_given?
block.arity == 0 ? value.instance_eval(&block) : block.call(value)
end
value
end | [
"def",
"get_value",
"(",
"key",
",",
"&",
"block",
")",
"key",
"=",
"key",
".",
"to_sym",
"value",
"=",
"@table",
"[",
"key",
"]",
"if",
"block_given?",
"block",
".",
"arity",
"==",
"0",
"?",
"value",
".",
"instance_eval",
"(",
"&",
"block",
")",
":",
"block",
".",
"call",
"(",
"value",
")",
"end",
"value",
"end"
] | Returns a value for +key+ from settings table.
Yields +value+ of +key+ if +block+ provided.
== Examples:
.key do |key|
...
end
# or
.key do
...
end | [
"Returns",
"a",
"value",
"for",
"+",
"key",
"+",
"from",
"settings",
"table",
".",
"Yields",
"+",
"value",
"+",
"of",
"+",
"key",
"+",
"if",
"+",
"block",
"+",
"provided",
"."
] | f9175cf007ccadefe4cd77f34271f76e311c2d60 | https://github.com/smolnar/squire/blob/f9175cf007ccadefe4cd77f34271f76e311c2d60/lib/squire/settings.rb#L85-L94 | train |
smolnar/squire | lib/squire/settings.rb | Squire.Settings.to_hash | def to_hash
result = ::Hash.new
@table.each do |key, value|
if value.is_a? Settings
value = value.to_hash
end
result[key] = value
end
result
end | ruby | def to_hash
result = ::Hash.new
@table.each do |key, value|
if value.is_a? Settings
value = value.to_hash
end
result[key] = value
end
result
end | [
"def",
"to_hash",
"result",
"=",
"::",
"Hash",
".",
"new",
"@table",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"value",
".",
"is_a?",
"Settings",
"value",
"=",
"value",
".",
"to_hash",
"end",
"result",
"[",
"key",
"]",
"=",
"value",
"end",
"result",
"end"
] | Dumps settings as hash. | [
"Dumps",
"settings",
"as",
"hash",
"."
] | f9175cf007ccadefe4cd77f34271f76e311c2d60 | https://github.com/smolnar/squire/blob/f9175cf007ccadefe4cd77f34271f76e311c2d60/lib/squire/settings.rb#L106-L118 | train |
AssemDeghady/questionpro_rails | lib/questionpro_rails/question.rb | QuestionproRails.Question.choices | def choices
extracted_choices = []
unless self.qp_answers.nil?
self.qp_answers.each do |choice|
extracted_choices.push(Choice.new(choice))
end
end
return extracted_choices
end | ruby | def choices
extracted_choices = []
unless self.qp_answers.nil?
self.qp_answers.each do |choice|
extracted_choices.push(Choice.new(choice))
end
end
return extracted_choices
end | [
"def",
"choices",
"extracted_choices",
"=",
"[",
"]",
"unless",
"self",
".",
"qp_answers",
".",
"nil?",
"self",
".",
"qp_answers",
".",
"each",
"do",
"|",
"choice",
"|",
"extracted_choices",
".",
"push",
"(",
"Choice",
".",
"new",
"(",
"choice",
")",
")",
"end",
"end",
"return",
"extracted_choices",
"end"
] | Extract the choices from the hashes stored
inside qp_answers attribute.
@return [Array<QuestionproRails::Choice>] Choices. | [
"Extract",
"the",
"choices",
"from",
"the",
"hashes",
"stored",
"inside",
"qp_answers",
"attribute",
"."
] | 79f295f193b6ad593f4d56d8edfa3076a23d8e4f | https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/question.rb#L22-L32 | train |
dropofwill/rtasklib | lib/rtasklib/helpers.rb | Rtasklib.Helpers.filter | def filter ids: nil, tags: nil, dom: nil
id_s = tag_s = dom_s = ""
id_s = process_ids(ids) unless ids.nil?
tag_s = process_tags(tags) unless tags.nil?
dom_s = process_dom(dom) unless dom.nil?
return "#{id_s} #{tag_s} #{dom_s}".strip
end | ruby | def filter ids: nil, tags: nil, dom: nil
id_s = tag_s = dom_s = ""
id_s = process_ids(ids) unless ids.nil?
tag_s = process_tags(tags) unless tags.nil?
dom_s = process_dom(dom) unless dom.nil?
return "#{id_s} #{tag_s} #{dom_s}".strip
end | [
"def",
"filter",
"ids",
":",
"nil",
",",
"tags",
":",
"nil",
",",
"dom",
":",
"nil",
"id_s",
"=",
"tag_s",
"=",
"dom_s",
"=",
"\"\"",
"id_s",
"=",
"process_ids",
"(",
"ids",
")",
"unless",
"ids",
".",
"nil?",
"tag_s",
"=",
"process_tags",
"(",
"tags",
")",
"unless",
"tags",
".",
"nil?",
"dom_s",
"=",
"process_dom",
"(",
"dom",
")",
"unless",
"dom",
".",
"nil?",
"return",
"\"#{id_s} #{tag_s} #{dom_s}\"",
".",
"strip",
"end"
] | Converts ids, tags, and dom queries to a single string ready to pass
directly to task.
@param ids[Range, Array<String, Range, Fixnum>, String, Fixnum]
@param tags[String, Array<String>]
@param dom[String, Array<String>]
@return [String] a string with ids tags and dom joined by a space
@api public | [
"Converts",
"ids",
"tags",
"and",
"dom",
"queries",
"to",
"a",
"single",
"string",
"ready",
"to",
"pass",
"directly",
"to",
"task",
"."
] | c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c | https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/helpers.rb#L49-L55 | train |
dropofwill/rtasklib | lib/rtasklib/helpers.rb | Rtasklib.Helpers.process_ids | def process_ids ids
case ids
when Range
return id_range_to_s(ids)
when Array
return id_a_to_s(ids)
when String
return ids.delete(" ")
when Fixnum
return ids
end
end | ruby | def process_ids ids
case ids
when Range
return id_range_to_s(ids)
when Array
return id_a_to_s(ids)
when String
return ids.delete(" ")
when Fixnum
return ids
end
end | [
"def",
"process_ids",
"ids",
"case",
"ids",
"when",
"Range",
"return",
"id_range_to_s",
"(",
"ids",
")",
"when",
"Array",
"return",
"id_a_to_s",
"(",
"ids",
")",
"when",
"String",
"return",
"ids",
".",
"delete",
"(",
"\" \"",
")",
"when",
"Fixnum",
"return",
"ids",
"end",
"end"
] | Converts arbitrary id input to a task safe string
@param ids[Range, Array<String, Range, Fixnum>, String, Fixnum]
@api public | [
"Converts",
"arbitrary",
"id",
"input",
"to",
"a",
"task",
"safe",
"string"
] | c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c | https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/helpers.rb#L79-L90 | train |
dropofwill/rtasklib | lib/rtasklib/helpers.rb | Rtasklib.Helpers.process_tags | def process_tags tags
case tags
when String
tags.split(" ").map { |t| process_tag t }.join(" ")
when Array
tags.map { |t| process_tags t }.join(" ")
end
end | ruby | def process_tags tags
case tags
when String
tags.split(" ").map { |t| process_tag t }.join(" ")
when Array
tags.map { |t| process_tags t }.join(" ")
end
end | [
"def",
"process_tags",
"tags",
"case",
"tags",
"when",
"String",
"tags",
".",
"split",
"(",
"\" \"",
")",
".",
"map",
"{",
"|",
"t",
"|",
"process_tag",
"t",
"}",
".",
"join",
"(",
"\" \"",
")",
"when",
"Array",
"tags",
".",
"map",
"{",
"|",
"t",
"|",
"process_tags",
"t",
"}",
".",
"join",
"(",
"\" \"",
")",
"end",
"end"
] | Convert a tag string or an array of strings to a space separated string
@param tags [String, Array<String>]
@api private | [
"Convert",
"a",
"tag",
"string",
"or",
"an",
"array",
"of",
"strings",
"to",
"a",
"space",
"separated",
"string"
] | c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c | https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/helpers.rb#L105-L112 | train |
dropofwill/rtasklib | lib/rtasklib/helpers.rb | Rtasklib.Helpers.json? | def json? value
begin
return false unless value.is_a? String
MultiJson.load(value)
true
rescue MultiJson::ParseError
false
end
end | ruby | def json? value
begin
return false unless value.is_a? String
MultiJson.load(value)
true
rescue MultiJson::ParseError
false
end
end | [
"def",
"json?",
"value",
"begin",
"return",
"false",
"unless",
"value",
".",
"is_a?",
"String",
"MultiJson",
".",
"load",
"(",
"value",
")",
"true",
"rescue",
"MultiJson",
"::",
"ParseError",
"false",
"end",
"end"
] | Can the input be coerced to a JSON object without losing information?
@return [Boolean] true if coercible, false if not
@api private | [
"Can",
"the",
"input",
"be",
"coerced",
"to",
"a",
"JSON",
"object",
"without",
"losing",
"information?"
] | c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c | https://github.com/dropofwill/rtasklib/blob/c3a69a7188765e5d662d9d0d1fd5d4f87dc74d8c/lib/rtasklib/helpers.rb#L243-L251 | train |
couchrest/couchrest_extended_document | lib/couchrest/property.rb | CouchRest.Property.cast_value | def cast_value(parent, value)
raise "An array inside an array cannot be casted, use CastedModel" if value.is_a?(Array)
value = typecast_value(value, self)
associate_casted_value_to_parent(parent, value)
end | ruby | def cast_value(parent, value)
raise "An array inside an array cannot be casted, use CastedModel" if value.is_a?(Array)
value = typecast_value(value, self)
associate_casted_value_to_parent(parent, value)
end | [
"def",
"cast_value",
"(",
"parent",
",",
"value",
")",
"raise",
"\"An array inside an array cannot be casted, use CastedModel\"",
"if",
"value",
".",
"is_a?",
"(",
"Array",
")",
"value",
"=",
"typecast_value",
"(",
"value",
",",
"self",
")",
"associate_casted_value_to_parent",
"(",
"parent",
",",
"value",
")",
"end"
] | Cast an individual value, not an array | [
"Cast",
"an",
"individual",
"value",
"not",
"an",
"array"
] | 71511202ae10d3010dcf7b98fcba017cb37c76da | https://github.com/couchrest/couchrest_extended_document/blob/71511202ae10d3010dcf7b98fcba017cb37c76da/lib/couchrest/property.rb#L44-L48 | train |
couchrest/couchrest_extended_document | lib/couchrest/property.rb | CouchRest.Property.type_class | def type_class
return String unless casted # This is rubbish, to handle validations
return @type_class unless @type_class.nil?
base = @type.is_a?(Array) ? @type.first : @type
base = String if base.nil?
base = TrueClass if base.is_a?(String) && base.downcase == 'boolean'
@type_class = base.is_a?(Class) ? base : base.constantize
end | ruby | def type_class
return String unless casted # This is rubbish, to handle validations
return @type_class unless @type_class.nil?
base = @type.is_a?(Array) ? @type.first : @type
base = String if base.nil?
base = TrueClass if base.is_a?(String) && base.downcase == 'boolean'
@type_class = base.is_a?(Class) ? base : base.constantize
end | [
"def",
"type_class",
"return",
"String",
"unless",
"casted",
"return",
"@type_class",
"unless",
"@type_class",
".",
"nil?",
"base",
"=",
"@type",
".",
"is_a?",
"(",
"Array",
")",
"?",
"@type",
".",
"first",
":",
"@type",
"base",
"=",
"String",
"if",
"base",
".",
"nil?",
"base",
"=",
"TrueClass",
"if",
"base",
".",
"is_a?",
"(",
"String",
")",
"&&",
"base",
".",
"downcase",
"==",
"'boolean'",
"@type_class",
"=",
"base",
".",
"is_a?",
"(",
"Class",
")",
"?",
"base",
":",
"base",
".",
"constantize",
"end"
] | Always provide the basic type as a class. If the type
is an array, the class will be extracted. | [
"Always",
"provide",
"the",
"basic",
"type",
"as",
"a",
"class",
".",
"If",
"the",
"type",
"is",
"an",
"array",
"the",
"class",
"will",
"be",
"extracted",
"."
] | 71511202ae10d3010dcf7b98fcba017cb37c76da | https://github.com/couchrest/couchrest_extended_document/blob/71511202ae10d3010dcf7b98fcba017cb37c76da/lib/couchrest/property.rb#L61-L68 | train |
unipept/unipept-cli | lib/batch_iterator.rb | Unipept.BatchIterator.fasta_iterator | def fasta_iterator(first_line, next_lines)
current_fasta_header = first_line.chomp
next_lines.each_slice(batch_size).with_index do |slice, i|
fasta_mapper = []
input_set = Set.new
slice.each do |line|
line.chomp!
if fasta? line
current_fasta_header = line
else
fasta_mapper << [current_fasta_header, line]
input_set << line
end
end
yield(input_set.to_a, i, fasta_mapper)
end
end | ruby | def fasta_iterator(first_line, next_lines)
current_fasta_header = first_line.chomp
next_lines.each_slice(batch_size).with_index do |slice, i|
fasta_mapper = []
input_set = Set.new
slice.each do |line|
line.chomp!
if fasta? line
current_fasta_header = line
else
fasta_mapper << [current_fasta_header, line]
input_set << line
end
end
yield(input_set.to_a, i, fasta_mapper)
end
end | [
"def",
"fasta_iterator",
"(",
"first_line",
",",
"next_lines",
")",
"current_fasta_header",
"=",
"first_line",
".",
"chomp",
"next_lines",
".",
"each_slice",
"(",
"batch_size",
")",
".",
"with_index",
"do",
"|",
"slice",
",",
"i",
"|",
"fasta_mapper",
"=",
"[",
"]",
"input_set",
"=",
"Set",
".",
"new",
"slice",
".",
"each",
"do",
"|",
"line",
"|",
"line",
".",
"chomp!",
"if",
"fasta?",
"line",
"current_fasta_header",
"=",
"line",
"else",
"fasta_mapper",
"<<",
"[",
"current_fasta_header",
",",
"line",
"]",
"input_set",
"<<",
"line",
"end",
"end",
"yield",
"(",
"input_set",
".",
"to_a",
",",
"i",
",",
"fasta_mapper",
")",
"end",
"end"
] | Splits the input lines in fasta format into slices, based on the
batch_size of the current command. Executes the given block for each of
the batches. | [
"Splits",
"the",
"input",
"lines",
"in",
"fasta",
"format",
"into",
"slices",
"based",
"on",
"the",
"batch_size",
"of",
"the",
"current",
"command",
".",
"Executes",
"the",
"given",
"block",
"for",
"each",
"of",
"the",
"batches",
"."
] | 183779bd1dffcd01ed623685c789160153b78681 | https://github.com/unipept/unipept-cli/blob/183779bd1dffcd01ed623685c789160153b78681/lib/batch_iterator.rb#L42-L60 | train |
yoyo0906/ruby-adb-sdklib | lib/adb_sdklib/device.rb | AdbSdkLib.Device.properties | def properties
convert_map_to_hash(@device.getProperties) do |hash, key, value|
hash[key.toString] = value.toString
end
end | ruby | def properties
convert_map_to_hash(@device.getProperties) do |hash, key, value|
hash[key.toString] = value.toString
end
end | [
"def",
"properties",
"convert_map_to_hash",
"(",
"@device",
".",
"getProperties",
")",
"do",
"|",
"hash",
",",
"key",
",",
"value",
"|",
"hash",
"[",
"key",
".",
"toString",
"]",
"=",
"value",
".",
"toString",
"end",
"end"
] | Returns the device properties. It contains the whole output of 'getprop'
@return [Hash<String, String>] the device properties | [
"Returns",
"the",
"device",
"properties",
".",
"It",
"contains",
"the",
"whole",
"output",
"of",
"getprop"
] | 9f8a5c88ee8e7b572600ca7919b506bfc0e8d105 | https://github.com/yoyo0906/ruby-adb-sdklib/blob/9f8a5c88ee8e7b572600ca7919b506bfc0e8d105/lib/adb_sdklib/device.rb#L81-L85 | train |
yoyo0906/ruby-adb-sdklib | lib/adb_sdklib/device.rb | AdbSdkLib.Device.shell | def shell(command, &block)
capture = CommandCapture.new(block_given? ? block : nil)
receiver = Rjb::bind(capture, 'com.android.ddmlib.IShellOutputReceiver')
@device.executeShellCommand(command.to_s, receiver)
block_given? ? self : capture.to_s
end | ruby | def shell(command, &block)
capture = CommandCapture.new(block_given? ? block : nil)
receiver = Rjb::bind(capture, 'com.android.ddmlib.IShellOutputReceiver')
@device.executeShellCommand(command.to_s, receiver)
block_given? ? self : capture.to_s
end | [
"def",
"shell",
"(",
"command",
",",
"&",
"block",
")",
"capture",
"=",
"CommandCapture",
".",
"new",
"(",
"block_given?",
"?",
"block",
":",
"nil",
")",
"receiver",
"=",
"Rjb",
"::",
"bind",
"(",
"capture",
",",
"'com.android.ddmlib.IShellOutputReceiver'",
")",
"@device",
".",
"executeShellCommand",
"(",
"command",
".",
"to_s",
",",
"receiver",
")",
"block_given?",
"?",
"self",
":",
"capture",
".",
"to_s",
"end"
] | Executes a shell command on the device, and receives the result.
@!method shell(command)
@return [String, self]
@overload shell(command)
@param [String] command the command to execute
@return [String] all results of the command.
@overload shell(command)
@param [String] command the command to execute
@return [self] self
@yield [line]
@yieldparam [String] line each line of results of the command. | [
"Executes",
"a",
"shell",
"command",
"on",
"the",
"device",
"and",
"receives",
"the",
"result",
"."
] | 9f8a5c88ee8e7b572600ca7919b506bfc0e8d105 | https://github.com/yoyo0906/ruby-adb-sdklib/blob/9f8a5c88ee8e7b572600ca7919b506bfc0e8d105/lib/adb_sdklib/device.rb#L145-L150 | train |
yoyo0906/ruby-adb-sdklib | lib/adb_sdklib/device.rb | AdbSdkLib.Device.push | def push(localfile, remotefile)
raise ArgumentError, "Not found #{localfile}" unless File.exist?(localfile)
if remotefile.end_with?('/')
remotefile = "#{remotefile}#{File.basename(localfile)}"
end
@device.pushFile(localfile, remotefile)
self
end | ruby | def push(localfile, remotefile)
raise ArgumentError, "Not found #{localfile}" unless File.exist?(localfile)
if remotefile.end_with?('/')
remotefile = "#{remotefile}#{File.basename(localfile)}"
end
@device.pushFile(localfile, remotefile)
self
end | [
"def",
"push",
"(",
"localfile",
",",
"remotefile",
")",
"raise",
"ArgumentError",
",",
"\"Not found #{localfile}\"",
"unless",
"File",
".",
"exist?",
"(",
"localfile",
")",
"if",
"remotefile",
".",
"end_with?",
"(",
"'/'",
")",
"remotefile",
"=",
"\"#{remotefile}#{File.basename(localfile)}\"",
"end",
"@device",
".",
"pushFile",
"(",
"localfile",
",",
"remotefile",
")",
"self",
"end"
] | Pushes a file to the device.
If *remotefile* path ends with '/', complements by the basename of
*localfile*.
@example
device = AdbSdkLib::Adb.new.devices.first
device.push('path/to/local.txt', '/data/local/tmp/remote.txt')
device.push('path/to/file.txt', '/data/local/tmp/') # uses file.txt
@param [String] localfile the name of the local file to send
@param [String] remotefile the name of the remote file or directory
on the device
@return [self] self
@raise [ArgumentError] If *localfile* is not found | [
"Pushes",
"a",
"file",
"to",
"the",
"device",
"."
] | 9f8a5c88ee8e7b572600ca7919b506bfc0e8d105 | https://github.com/yoyo0906/ruby-adb-sdklib/blob/9f8a5c88ee8e7b572600ca7919b506bfc0e8d105/lib/adb_sdklib/device.rb#L165-L172 | train |
yoyo0906/ruby-adb-sdklib | lib/adb_sdklib/device.rb | AdbSdkLib.Device.pull | def pull(remotefile, localfile)
if localfile.end_with?('/') || File.directory?(localfile)
localdir = localfile.chomp('/')
localfilename = nil
else
localdir = File.dirname(localfile)
localfilename = File.basename(localfile)
end
unless File.exist?(localdir)
FileUtils.mkdir_p(localdir)
end
localfilename = File.basename(remotefile) if localfilename.nil?
@device.pullFile(remotefile, "#{localdir}/#{localfilename}")
self
end | ruby | def pull(remotefile, localfile)
if localfile.end_with?('/') || File.directory?(localfile)
localdir = localfile.chomp('/')
localfilename = nil
else
localdir = File.dirname(localfile)
localfilename = File.basename(localfile)
end
unless File.exist?(localdir)
FileUtils.mkdir_p(localdir)
end
localfilename = File.basename(remotefile) if localfilename.nil?
@device.pullFile(remotefile, "#{localdir}/#{localfilename}")
self
end | [
"def",
"pull",
"(",
"remotefile",
",",
"localfile",
")",
"if",
"localfile",
".",
"end_with?",
"(",
"'/'",
")",
"||",
"File",
".",
"directory?",
"(",
"localfile",
")",
"localdir",
"=",
"localfile",
".",
"chomp",
"(",
"'/'",
")",
"localfilename",
"=",
"nil",
"else",
"localdir",
"=",
"File",
".",
"dirname",
"(",
"localfile",
")",
"localfilename",
"=",
"File",
".",
"basename",
"(",
"localfile",
")",
"end",
"unless",
"File",
".",
"exist?",
"(",
"localdir",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"localdir",
")",
"end",
"localfilename",
"=",
"File",
".",
"basename",
"(",
"remotefile",
")",
"if",
"localfilename",
".",
"nil?",
"@device",
".",
"pullFile",
"(",
"remotefile",
",",
"\"#{localdir}/#{localfilename}\"",
")",
"self",
"end"
] | Pulls a file from the device.
If *localfile* path ends with '/', complements by the basename of
*remotefile*.
@example
device = AdbSdkLib::Adb.new.devices.first
device.pull('/data/local/tmp/remote.txt', 'path/to/local.txt')
device.pull('/data/local/tmp/file.txt', 'path/to/dir/') # uses file.txt
@param [String] remotefile the name of the remote file on the device to get
@param [String] localfile the name of the local file or directory
@return [self] self | [
"Pulls",
"a",
"file",
"from",
"the",
"device",
"."
] | 9f8a5c88ee8e7b572600ca7919b506bfc0e8d105 | https://github.com/yoyo0906/ruby-adb-sdklib/blob/9f8a5c88ee8e7b572600ca7919b506bfc0e8d105/lib/adb_sdklib/device.rb#L185-L200 | train |
samvera-labs/geo_works | app/models/concerns/geo_works/raster_file_behavior.rb | GeoWorks.RasterFileBehavior.raster_work | def raster_work
parents.select do |parent|
parent.class.included_modules.include?(::GeoWorks::RasterWorkBehavior)
end.to_a
end | ruby | def raster_work
parents.select do |parent|
parent.class.included_modules.include?(::GeoWorks::RasterWorkBehavior)
end.to_a
end | [
"def",
"raster_work",
"parents",
".",
"select",
"do",
"|",
"parent",
"|",
"parent",
".",
"class",
".",
"included_modules",
".",
"include?",
"(",
"::",
"GeoWorks",
"::",
"RasterWorkBehavior",
")",
"end",
".",
"to_a",
"end"
] | Retrieve the Raster Work of which this Object is a member
@return [GeoWorks::Raster] | [
"Retrieve",
"the",
"Raster",
"Work",
"of",
"which",
"this",
"Object",
"is",
"a",
"member"
] | df1eff35fd01469a623fafeb9d71b44fd6160ca8 | https://github.com/samvera-labs/geo_works/blob/df1eff35fd01469a623fafeb9d71b44fd6160ca8/app/models/concerns/geo_works/raster_file_behavior.rb#L8-L12 | train |
yoyo0906/ruby-adb-sdklib | lib/adb_sdklib/raw_image.rb | AdbSdkLib.RawImage.pixel | def pixel(x,y)
Pixel.new(x,y,@image.getARGB(point_to_index(x,y)))
end | ruby | def pixel(x,y)
Pixel.new(x,y,@image.getARGB(point_to_index(x,y)))
end | [
"def",
"pixel",
"(",
"x",
",",
"y",
")",
"Pixel",
".",
"new",
"(",
"x",
",",
"y",
",",
"@image",
".",
"getARGB",
"(",
"point_to_index",
"(",
"x",
",",
"y",
")",
")",
")",
"end"
] | Returns pixel content
@param [Integer, Integer] pixel position x,y
@return [AdbSdkLib::Pixel] pixel content | [
"Returns",
"pixel",
"content"
] | 9f8a5c88ee8e7b572600ca7919b506bfc0e8d105 | https://github.com/yoyo0906/ruby-adb-sdklib/blob/9f8a5c88ee8e7b572600ca7919b506bfc0e8d105/lib/adb_sdklib/raw_image.rb#L67-L69 | train |
yoyo0906/ruby-adb-sdklib | lib/adb_sdklib/raw_image.rb | AdbSdkLib.RawImage.each_pixel | def each_pixel()
return to_enum :each_pixel unless block_given?
@image.height.times do |y|
@image.width.times do |x|
yield pixel(x,y)
end
end
self
end | ruby | def each_pixel()
return to_enum :each_pixel unless block_given?
@image.height.times do |y|
@image.width.times do |x|
yield pixel(x,y)
end
end
self
end | [
"def",
"each_pixel",
"(",
")",
"return",
"to_enum",
":each_pixel",
"unless",
"block_given?",
"@image",
".",
"height",
".",
"times",
"do",
"|",
"y",
"|",
"@image",
".",
"width",
".",
"times",
"do",
"|",
"x",
"|",
"yield",
"pixel",
"(",
"x",
",",
"y",
")",
"end",
"end",
"self",
"end"
] | Calls block once for each pixel in data, passing that device as a parameter.
If no block is given, an enumerator is returned instead.
@return [Enumerator] if not block given
@return [self] if block given
@yield [pixel] called with each pixel
@yieldparam [Pixel] pixel a pixel instance | [
"Calls",
"block",
"once",
"for",
"each",
"pixel",
"in",
"data",
"passing",
"that",
"device",
"as",
"a",
"parameter",
".",
"If",
"no",
"block",
"is",
"given",
"an",
"enumerator",
"is",
"returned",
"instead",
"."
] | 9f8a5c88ee8e7b572600ca7919b506bfc0e8d105 | https://github.com/yoyo0906/ruby-adb-sdklib/blob/9f8a5c88ee8e7b572600ca7919b506bfc0e8d105/lib/adb_sdklib/raw_image.rb#L77-L85 | train |
AssemDeghady/questionpro_rails | lib/questionpro_rails/api_request.rb | QuestionproRails.ApiRequest.options | def options
{id: self.survey_id, surveyID: self.survey_id, responseID: self.response_id,
resultMode: self.result_mode, startDate: self.start_date, userID: self.user_id,
endDate: self.end_date, startingResponseCounter: self.starting_response_counter,
emailGroupID: self.email_group_id, templateID: self.template_id}.compact.to_json
end | ruby | def options
{id: self.survey_id, surveyID: self.survey_id, responseID: self.response_id,
resultMode: self.result_mode, startDate: self.start_date, userID: self.user_id,
endDate: self.end_date, startingResponseCounter: self.starting_response_counter,
emailGroupID: self.email_group_id, templateID: self.template_id}.compact.to_json
end | [
"def",
"options",
"{",
"id",
":",
"self",
".",
"survey_id",
",",
"surveyID",
":",
"self",
".",
"survey_id",
",",
"responseID",
":",
"self",
".",
"response_id",
",",
"resultMode",
":",
"self",
".",
"result_mode",
",",
"startDate",
":",
"self",
".",
"start_date",
",",
"userID",
":",
"self",
".",
"user_id",
",",
"endDate",
":",
"self",
".",
"end_date",
",",
"startingResponseCounter",
":",
"self",
".",
"starting_response_counter",
",",
"emailGroupID",
":",
"self",
".",
"email_group_id",
",",
"templateID",
":",
"self",
".",
"template_id",
"}",
".",
"compact",
".",
"to_json",
"end"
] | Transform the object to the acceptable json format by questionpro.
@return [Json] options in the call request. | [
"Transform",
"the",
"object",
"to",
"the",
"acceptable",
"json",
"format",
"by",
"questionpro",
"."
] | 79f295f193b6ad593f4d56d8edfa3076a23d8e4f | https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/api_request.rb#L56-L61 | train |
AssemDeghady/questionpro_rails | lib/questionpro_rails/api_request.rb | QuestionproRails.ApiRequest.list_surveys | def list_surveys
url = ApiRequest.base_path("questionpro.survey.getAllSurveys")
result = self.class.get(url, body: self.options)
self.full_response = result
self.status = result['status']
surveys = []
result_surveys = result['response']['surveys']
result_surveys.each do |survey|
surveys.push(Survey.new(survey))
end
return surveys
end | ruby | def list_surveys
url = ApiRequest.base_path("questionpro.survey.getAllSurveys")
result = self.class.get(url, body: self.options)
self.full_response = result
self.status = result['status']
surveys = []
result_surveys = result['response']['surveys']
result_surveys.each do |survey|
surveys.push(Survey.new(survey))
end
return surveys
end | [
"def",
"list_surveys",
"url",
"=",
"ApiRequest",
".",
"base_path",
"(",
"\"questionpro.survey.getAllSurveys\"",
")",
"result",
"=",
"self",
".",
"class",
".",
"get",
"(",
"url",
",",
"body",
":",
"self",
".",
"options",
")",
"self",
".",
"full_response",
"=",
"result",
"self",
".",
"status",
"=",
"result",
"[",
"'status'",
"]",
"surveys",
"=",
"[",
"]",
"result_surveys",
"=",
"result",
"[",
"'response'",
"]",
"[",
"'surveys'",
"]",
"result_surveys",
".",
"each",
"do",
"|",
"survey",
"|",
"surveys",
".",
"push",
"(",
"Survey",
".",
"new",
"(",
"survey",
")",
")",
"end",
"return",
"surveys",
"end"
] | Get all the surveys that belongs to the api key's owner.
@return [Array<QuestionproRails::Survey>] Surveys. | [
"Get",
"all",
"the",
"surveys",
"that",
"belongs",
"to",
"the",
"api",
"key",
"s",
"owner",
"."
] | 79f295f193b6ad593f4d56d8edfa3076a23d8e4f | https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/api_request.rb#L66-L80 | train |
AssemDeghady/questionpro_rails | lib/questionpro_rails/api_request.rb | QuestionproRails.ApiRequest.get_survey | def get_survey
url = ApiRequest.base_path("questionpro.survey.getSurvey")
result = self.class.get(url, body: self.options)
self.full_response = result
self.status = result['status']
survey = Survey.new(result['response'])
return survey
end | ruby | def get_survey
url = ApiRequest.base_path("questionpro.survey.getSurvey")
result = self.class.get(url, body: self.options)
self.full_response = result
self.status = result['status']
survey = Survey.new(result['response'])
return survey
end | [
"def",
"get_survey",
"url",
"=",
"ApiRequest",
".",
"base_path",
"(",
"\"questionpro.survey.getSurvey\"",
")",
"result",
"=",
"self",
".",
"class",
".",
"get",
"(",
"url",
",",
"body",
":",
"self",
".",
"options",
")",
"self",
".",
"full_response",
"=",
"result",
"self",
".",
"status",
"=",
"result",
"[",
"'status'",
"]",
"survey",
"=",
"Survey",
".",
"new",
"(",
"result",
"[",
"'response'",
"]",
")",
"return",
"survey",
"end"
] | Get a specific survey.
Survey ID must be set inside the api request object.
@return [QuestionproRails::Survey] Survey. | [
"Get",
"a",
"specific",
"survey",
".",
"Survey",
"ID",
"must",
"be",
"set",
"inside",
"the",
"api",
"request",
"object",
"."
] | 79f295f193b6ad593f4d56d8edfa3076a23d8e4f | https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/api_request.rb#L86-L96 | train |
AssemDeghady/questionpro_rails | lib/questionpro_rails/api_request.rb | QuestionproRails.ApiRequest.get_survey_responses | def get_survey_responses
url = ApiRequest.base_path("questionpro.survey.surveyResponses")
result = self.class.get(url, body: self.options)
self.full_response = result
self.status = result['status']
survey_responses = []
result_responses = result['response']['responses']
result_responses.each do |response|
survey_responses.push(SurveyResponse.new(response))
end
return survey_responses
end | ruby | def get_survey_responses
url = ApiRequest.base_path("questionpro.survey.surveyResponses")
result = self.class.get(url, body: self.options)
self.full_response = result
self.status = result['status']
survey_responses = []
result_responses = result['response']['responses']
result_responses.each do |response|
survey_responses.push(SurveyResponse.new(response))
end
return survey_responses
end | [
"def",
"get_survey_responses",
"url",
"=",
"ApiRequest",
".",
"base_path",
"(",
"\"questionpro.survey.surveyResponses\"",
")",
"result",
"=",
"self",
".",
"class",
".",
"get",
"(",
"url",
",",
"body",
":",
"self",
".",
"options",
")",
"self",
".",
"full_response",
"=",
"result",
"self",
".",
"status",
"=",
"result",
"[",
"'status'",
"]",
"survey_responses",
"=",
"[",
"]",
"result_responses",
"=",
"result",
"[",
"'response'",
"]",
"[",
"'responses'",
"]",
"result_responses",
".",
"each",
"do",
"|",
"response",
"|",
"survey_responses",
".",
"push",
"(",
"SurveyResponse",
".",
"new",
"(",
"response",
")",
")",
"end",
"return",
"survey_responses",
"end"
] | Get list of survey Responses.
Survey ID must be set inside the api request object.
@return [Array<QuestionproRails::SurveyResponse>] Survey Responses. | [
"Get",
"list",
"of",
"survey",
"Responses",
".",
"Survey",
"ID",
"must",
"be",
"set",
"inside",
"the",
"api",
"request",
"object",
"."
] | 79f295f193b6ad593f4d56d8edfa3076a23d8e4f | https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/api_request.rb#L117-L131 | train |
AssemDeghady/questionpro_rails | lib/questionpro_rails/api_request.rb | QuestionproRails.ApiRequest.get_survey_reponse | def get_survey_reponse
url = ApiRequest.base_path("questionpro.survey.surveyResponse")
result = self.class.get(url, body: self.options)
self.full_response = result
self.status = result['status']
response = SurveyResponse.new(result['response']['surveyResponse'])
return response
end | ruby | def get_survey_reponse
url = ApiRequest.base_path("questionpro.survey.surveyResponse")
result = self.class.get(url, body: self.options)
self.full_response = result
self.status = result['status']
response = SurveyResponse.new(result['response']['surveyResponse'])
return response
end | [
"def",
"get_survey_reponse",
"url",
"=",
"ApiRequest",
".",
"base_path",
"(",
"\"questionpro.survey.surveyResponse\"",
")",
"result",
"=",
"self",
".",
"class",
".",
"get",
"(",
"url",
",",
"body",
":",
"self",
".",
"options",
")",
"self",
".",
"full_response",
"=",
"result",
"self",
".",
"status",
"=",
"result",
"[",
"'status'",
"]",
"response",
"=",
"SurveyResponse",
".",
"new",
"(",
"result",
"[",
"'response'",
"]",
"[",
"'surveyResponse'",
"]",
")",
"return",
"response",
"end"
] | Get a specific survey Response.
Survey ID must be set inside the api request object.
Response ID must be set inside the api request object.
@return [QuestionproRails::SurveyResponse] Survey Response. | [
"Get",
"a",
"specific",
"survey",
"Response",
".",
"Survey",
"ID",
"must",
"be",
"set",
"inside",
"the",
"api",
"request",
"object",
".",
"Response",
"ID",
"must",
"be",
"set",
"inside",
"the",
"api",
"request",
"object",
"."
] | 79f295f193b6ad593f4d56d8edfa3076a23d8e4f | https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/api_request.rb#L138-L148 | train |
AssemDeghady/questionpro_rails | lib/questionpro_rails/api_request.rb | QuestionproRails.ApiRequest.get_survey_response_count | def get_survey_response_count
url = ApiRequest.base_path("questionpro.survey.responseCount")
result = self.class.get(url, body: self.options)
self.full_response = result
self.status = result['status']
response_count = SurveyResponseCount.new(result['response'])
return response_count
end | ruby | def get_survey_response_count
url = ApiRequest.base_path("questionpro.survey.responseCount")
result = self.class.get(url, body: self.options)
self.full_response = result
self.status = result['status']
response_count = SurveyResponseCount.new(result['response'])
return response_count
end | [
"def",
"get_survey_response_count",
"url",
"=",
"ApiRequest",
".",
"base_path",
"(",
"\"questionpro.survey.responseCount\"",
")",
"result",
"=",
"self",
".",
"class",
".",
"get",
"(",
"url",
",",
"body",
":",
"self",
".",
"options",
")",
"self",
".",
"full_response",
"=",
"result",
"self",
".",
"status",
"=",
"result",
"[",
"'status'",
"]",
"response_count",
"=",
"SurveyResponseCount",
".",
"new",
"(",
"result",
"[",
"'response'",
"]",
")",
"return",
"response_count",
"end"
] | Get a specific survey Response Statistics.
Survey ID must be set inside the api request object.
@return [QuestionproRails::SurveyResponseCount] Survey Response Statistics. | [
"Get",
"a",
"specific",
"survey",
"Response",
"Statistics",
".",
"Survey",
"ID",
"must",
"be",
"set",
"inside",
"the",
"api",
"request",
"object",
"."
] | 79f295f193b6ad593f4d56d8edfa3076a23d8e4f | https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/api_request.rb#L154-L164 | train |
AssemDeghady/questionpro_rails | lib/questionpro_rails/api_request.rb | QuestionproRails.ApiRequest.delete_response | def delete_response
url = ApiRequest.base_path("questionpro.survey.deleteResponse")
result = self.class.get(url, body: self.options)
self.full_response = result
self.status = result['status']
self.success = result['response']['success']
return self
end | ruby | def delete_response
url = ApiRequest.base_path("questionpro.survey.deleteResponse")
result = self.class.get(url, body: self.options)
self.full_response = result
self.status = result['status']
self.success = result['response']['success']
return self
end | [
"def",
"delete_response",
"url",
"=",
"ApiRequest",
".",
"base_path",
"(",
"\"questionpro.survey.deleteResponse\"",
")",
"result",
"=",
"self",
".",
"class",
".",
"get",
"(",
"url",
",",
"body",
":",
"self",
".",
"options",
")",
"self",
".",
"full_response",
"=",
"result",
"self",
".",
"status",
"=",
"result",
"[",
"'status'",
"]",
"self",
".",
"success",
"=",
"result",
"[",
"'response'",
"]",
"[",
"'success'",
"]",
"return",
"self",
"end"
] | Delete a specific survey response.
Survey ID must be set inside the api request object.
Response ID must be set inside the api request object.
@return sets ApiRequest success attribute to 1. | [
"Delete",
"a",
"specific",
"survey",
"response",
".",
"Survey",
"ID",
"must",
"be",
"set",
"inside",
"the",
"api",
"request",
"object",
".",
"Response",
"ID",
"must",
"be",
"set",
"inside",
"the",
"api",
"request",
"object",
"."
] | 79f295f193b6ad593f4d56d8edfa3076a23d8e4f | https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/api_request.rb#L171-L180 | train |
AssemDeghady/questionpro_rails | lib/questionpro_rails/api_request.rb | QuestionproRails.ApiRequest.get_email_lists | def get_email_lists
url = ApiRequest.base_path("questionpro.survey.getEmailLists")
result = self.class.get(url, body: self.options)
self.full_response = result
self.status = result['status']
email_lists = []
result_email_lists = result['response']['emailLists']
result_email_lists.each do |email_list|
email_lists.push(EmailList.new(email_list))
end
return email_lists
end | ruby | def get_email_lists
url = ApiRequest.base_path("questionpro.survey.getEmailLists")
result = self.class.get(url, body: self.options)
self.full_response = result
self.status = result['status']
email_lists = []
result_email_lists = result['response']['emailLists']
result_email_lists.each do |email_list|
email_lists.push(EmailList.new(email_list))
end
return email_lists
end | [
"def",
"get_email_lists",
"url",
"=",
"ApiRequest",
".",
"base_path",
"(",
"\"questionpro.survey.getEmailLists\"",
")",
"result",
"=",
"self",
".",
"class",
".",
"get",
"(",
"url",
",",
"body",
":",
"self",
".",
"options",
")",
"self",
".",
"full_response",
"=",
"result",
"self",
".",
"status",
"=",
"result",
"[",
"'status'",
"]",
"email_lists",
"=",
"[",
"]",
"result_email_lists",
"=",
"result",
"[",
"'response'",
"]",
"[",
"'emailLists'",
"]",
"result_email_lists",
".",
"each",
"do",
"|",
"email_list",
"|",
"email_lists",
".",
"push",
"(",
"EmailList",
".",
"new",
"(",
"email_list",
")",
")",
"end",
"return",
"email_lists",
"end"
] | Get Email Lists related to a specific survey.
Survey ID must be set inside the api request object.
@return [Array<QuestionproRails::EmailList>] Email Lists. | [
"Get",
"Email",
"Lists",
"related",
"to",
"a",
"specific",
"survey",
".",
"Survey",
"ID",
"must",
"be",
"set",
"inside",
"the",
"api",
"request",
"object",
"."
] | 79f295f193b6ad593f4d56d8edfa3076a23d8e4f | https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/api_request.rb#L186-L200 | train |
AssemDeghady/questionpro_rails | lib/questionpro_rails/api_request.rb | QuestionproRails.ApiRequest.get_email_list | def get_email_list
url = ApiRequest.base_path("questionpro.survey.getEmailList")
result = self.class.get(url, body: self.options)
self.full_response = result
self.status = result['status']
email_list = EmailList.new(result['response']['emailList'])
return email_list
end | ruby | def get_email_list
url = ApiRequest.base_path("questionpro.survey.getEmailList")
result = self.class.get(url, body: self.options)
self.full_response = result
self.status = result['status']
email_list = EmailList.new(result['response']['emailList'])
return email_list
end | [
"def",
"get_email_list",
"url",
"=",
"ApiRequest",
".",
"base_path",
"(",
"\"questionpro.survey.getEmailList\"",
")",
"result",
"=",
"self",
".",
"class",
".",
"get",
"(",
"url",
",",
"body",
":",
"self",
".",
"options",
")",
"self",
".",
"full_response",
"=",
"result",
"self",
".",
"status",
"=",
"result",
"[",
"'status'",
"]",
"email_list",
"=",
"EmailList",
".",
"new",
"(",
"result",
"[",
"'response'",
"]",
"[",
"'emailList'",
"]",
")",
"return",
"email_list",
"end"
] | Get Specific Email List.
Email Group ID must be set inside the api request object.
@return [QuestionproRails::EmailList] Email List. | [
"Get",
"Specific",
"Email",
"List",
".",
"Email",
"Group",
"ID",
"must",
"be",
"set",
"inside",
"the",
"api",
"request",
"object",
"."
] | 79f295f193b6ad593f4d56d8edfa3076a23d8e4f | https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/api_request.rb#L206-L216 | train |
AssemDeghady/questionpro_rails | lib/questionpro_rails/api_request.rb | QuestionproRails.ApiRequest.get_email_templates | def get_email_templates
url = ApiRequest.base_path("questionpro.survey.getEmailTemplates")
result = self.class.get(url, body: self.options)
self.full_response = result
self.status = result['status']
email_templates = []
result_email_templates = result['response']['emailTemplates']
result_email_templates.each do |email_template|
email_templates.push(EmailTemplate.new(email_template))
end
return email_templates
end | ruby | def get_email_templates
url = ApiRequest.base_path("questionpro.survey.getEmailTemplates")
result = self.class.get(url, body: self.options)
self.full_response = result
self.status = result['status']
email_templates = []
result_email_templates = result['response']['emailTemplates']
result_email_templates.each do |email_template|
email_templates.push(EmailTemplate.new(email_template))
end
return email_templates
end | [
"def",
"get_email_templates",
"url",
"=",
"ApiRequest",
".",
"base_path",
"(",
"\"questionpro.survey.getEmailTemplates\"",
")",
"result",
"=",
"self",
".",
"class",
".",
"get",
"(",
"url",
",",
"body",
":",
"self",
".",
"options",
")",
"self",
".",
"full_response",
"=",
"result",
"self",
".",
"status",
"=",
"result",
"[",
"'status'",
"]",
"email_templates",
"=",
"[",
"]",
"result_email_templates",
"=",
"result",
"[",
"'response'",
"]",
"[",
"'emailTemplates'",
"]",
"result_email_templates",
".",
"each",
"do",
"|",
"email_template",
"|",
"email_templates",
".",
"push",
"(",
"EmailTemplate",
".",
"new",
"(",
"email_template",
")",
")",
"end",
"return",
"email_templates",
"end"
] | Get Templates related to a specific survey.
Survey ID must be set inside the api request object.
@return [Array<QuestionproRails::Template>] Templates. | [
"Get",
"Templates",
"related",
"to",
"a",
"specific",
"survey",
".",
"Survey",
"ID",
"must",
"be",
"set",
"inside",
"the",
"api",
"request",
"object",
"."
] | 79f295f193b6ad593f4d56d8edfa3076a23d8e4f | https://github.com/AssemDeghady/questionpro_rails/blob/79f295f193b6ad593f4d56d8edfa3076a23d8e4f/lib/questionpro_rails/api_request.rb#L237-L251 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.