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 |
---|---|---|---|---|---|---|---|---|---|---|---|
jduckett/duck_map | lib/duck_map/view_helpers.rb | DuckMap.ActionViewHelpers.sitemap_meta_description | def sitemap_meta_description
return controller.sitemap_meta_data[:description].blank? ? nil : tag(:meta, {name: :description, content: controller.sitemap_meta_data[:description]}, false, false)
end | ruby | def sitemap_meta_description
return controller.sitemap_meta_data[:description].blank? ? nil : tag(:meta, {name: :description, content: controller.sitemap_meta_data[:description]}, false, false)
end | [
"def",
"sitemap_meta_description",
"return",
"controller",
".",
"sitemap_meta_data",
"[",
":description",
"]",
".",
"blank?",
"?",
"nil",
":",
"tag",
"(",
":meta",
",",
"{",
"name",
":",
":description",
",",
"content",
":",
"controller",
".",
"sitemap_meta_data",
"[",
":description",
"]",
"}",
",",
"false",
",",
"false",
")",
"end"
] | Generates a description meta tag for use inside HTML header area.
@return [String] HTML safe description meta tag. | [
"Generates",
"a",
"description",
"meta",
"tag",
"for",
"use",
"inside",
"HTML",
"header",
"area",
"."
] | c510acfa95e8ad4afb1501366058ae88a73704df | https://github.com/jduckett/duck_map/blob/c510acfa95e8ad4afb1501366058ae88a73704df/lib/duck_map/view_helpers.rb#L65-L67 | train |
jduckett/duck_map | lib/duck_map/view_helpers.rb | DuckMap.ActionViewHelpers.sitemap_meta_lastmod | def sitemap_meta_lastmod
return controller.sitemap_meta_data[:lastmod].blank? ? nil : tag(:meta, {name: "Last-Modified", content: controller.sitemap_meta_data[:lastmod]}, false, false)
end | ruby | def sitemap_meta_lastmod
return controller.sitemap_meta_data[:lastmod].blank? ? nil : tag(:meta, {name: "Last-Modified", content: controller.sitemap_meta_data[:lastmod]}, false, false)
end | [
"def",
"sitemap_meta_lastmod",
"return",
"controller",
".",
"sitemap_meta_data",
"[",
":lastmod",
"]",
".",
"blank?",
"?",
"nil",
":",
"tag",
"(",
":meta",
",",
"{",
"name",
":",
"\"Last-Modified\"",
",",
"content",
":",
"controller",
".",
"sitemap_meta_data",
"[",
":lastmod",
"]",
"}",
",",
"false",
",",
"false",
")",
"end"
] | Generates a Last-Modified meta tag for use inside HTML header area.
@return [String] HTML safe Last-Modified meta tag. | [
"Generates",
"a",
"Last",
"-",
"Modified",
"meta",
"tag",
"for",
"use",
"inside",
"HTML",
"header",
"area",
"."
] | c510acfa95e8ad4afb1501366058ae88a73704df | https://github.com/jduckett/duck_map/blob/c510acfa95e8ad4afb1501366058ae88a73704df/lib/duck_map/view_helpers.rb#L76-L78 | train |
jduckett/duck_map | lib/duck_map/view_helpers.rb | DuckMap.ActionViewHelpers.sitemap_meta_canonical | def sitemap_meta_canonical
return controller.sitemap_meta_data[:canonical].blank? ? nil : tag(:link, {rel: :canonical, href: controller.sitemap_meta_data[:canonical]}, false, false)
end | ruby | def sitemap_meta_canonical
return controller.sitemap_meta_data[:canonical].blank? ? nil : tag(:link, {rel: :canonical, href: controller.sitemap_meta_data[:canonical]}, false, false)
end | [
"def",
"sitemap_meta_canonical",
"return",
"controller",
".",
"sitemap_meta_data",
"[",
":canonical",
"]",
".",
"blank?",
"?",
"nil",
":",
"tag",
"(",
":link",
",",
"{",
"rel",
":",
":canonical",
",",
"href",
":",
"controller",
".",
"sitemap_meta_data",
"[",
":canonical",
"]",
"}",
",",
"false",
",",
"false",
")",
"end"
] | Generates a canonical link tag for use inside HTML header area.
@return [String] HTML safe canonical link tag. | [
"Generates",
"a",
"canonical",
"link",
"tag",
"for",
"use",
"inside",
"HTML",
"header",
"area",
"."
] | c510acfa95e8ad4afb1501366058ae88a73704df | https://github.com/jduckett/duck_map/blob/c510acfa95e8ad4afb1501366058ae88a73704df/lib/duck_map/view_helpers.rb#L87-L89 | train |
asaaki/sjekksum | lib/sjekksum/primitive97.rb | Sjekksum.Primitive97.valid? | def valid? number
raise_on_type_mismatch number
num, check = split_number(number)
self.of(num) == check
end | ruby | def valid? number
raise_on_type_mismatch number
num, check = split_number(number)
self.of(num) == check
end | [
"def",
"valid?",
"number",
"raise_on_type_mismatch",
"number",
"num",
",",
"check",
"=",
"split_number",
"(",
"number",
")",
"self",
".",
"of",
"(",
"num",
")",
"==",
"check",
"end"
] | Primitive97 validation of provided number
@example
Sjekksum::Primitive97.valid?(235695) #=> true
@param number [Integer, String] number with included checksum
@return [Boolean] | [
"Primitive97",
"validation",
"of",
"provided",
"number"
] | 47a21c19dcffc67a3bef11d4f2de7c167fd20087 | https://github.com/asaaki/sjekksum/blob/47a21c19dcffc67a3bef11d4f2de7c167fd20087/lib/sjekksum/primitive97.rb#L35-L39 | train |
kamui/rack-accept_headers | lib/rack/accept_headers/context.rb | Rack::AcceptHeaders.Context.check! | def check!(request)
@check_headers.each do |header_name|
values = @checks[header_name]
header = request.send(header_name)
raise AcceptError unless values.any? {|v| header.accept?(v) }
end
end | ruby | def check!(request)
@check_headers.each do |header_name|
values = @checks[header_name]
header = request.send(header_name)
raise AcceptError unless values.any? {|v| header.accept?(v) }
end
end | [
"def",
"check!",
"(",
"request",
")",
"@check_headers",
".",
"each",
"do",
"|",
"header_name",
"|",
"values",
"=",
"@checks",
"[",
"header_name",
"]",
"header",
"=",
"request",
".",
"send",
"(",
"header_name",
")",
"raise",
"AcceptError",
"unless",
"values",
".",
"any?",
"{",
"|",
"v",
"|",
"header",
".",
"accept?",
"(",
"v",
")",
"}",
"end",
"end"
] | Raises an AcceptError if this server is not able to serve an acceptable
response. | [
"Raises",
"an",
"AcceptError",
"if",
"this",
"server",
"is",
"not",
"able",
"to",
"serve",
"an",
"acceptable",
"response",
"."
] | 099bfbb919de86b5842c8e14be42b8b784e53f03 | https://github.com/kamui/rack-accept_headers/blob/099bfbb919de86b5842c8e14be42b8b784e53f03/lib/rack/accept_headers/context.rb#L59-L65 | train |
asaaki/sjekksum | lib/sjekksum/verhoeff.rb | Sjekksum.Verhoeff.of | def of number
raise_on_type_mismatch number
digits = convert_number_to_digits(number)
INVERSE[digits.reverse_each.with_index.reduce(0) { |check, (digit, idx)|
d_row = DIHEDRAL_GROUP_D5[check]
d_row[ PERMUTATION[idx.next % 8][digit] ]
}]
end | ruby | def of number
raise_on_type_mismatch number
digits = convert_number_to_digits(number)
INVERSE[digits.reverse_each.with_index.reduce(0) { |check, (digit, idx)|
d_row = DIHEDRAL_GROUP_D5[check]
d_row[ PERMUTATION[idx.next % 8][digit] ]
}]
end | [
"def",
"of",
"number",
"raise_on_type_mismatch",
"number",
"digits",
"=",
"convert_number_to_digits",
"(",
"number",
")",
"INVERSE",
"[",
"digits",
".",
"reverse_each",
".",
"with_index",
".",
"reduce",
"(",
"0",
")",
"{",
"|",
"check",
",",
"(",
"digit",
",",
"idx",
")",
"|",
"d_row",
"=",
"DIHEDRAL_GROUP_D5",
"[",
"check",
"]",
"d_row",
"[",
"PERMUTATION",
"[",
"idx",
".",
"next",
"%",
"8",
"]",
"[",
"digit",
"]",
"]",
"}",
"]",
"end"
] | Calculates Verhoeff checksum
@example
Sjekksum::Verhoeff.of(142857) #=> 0
@param number [Integer, String] number for which the checksum should be calculated
@return [Integer] calculated checksum | [
"Calculates",
"Verhoeff",
"checksum"
] | 47a21c19dcffc67a3bef11d4f2de7c167fd20087 | https://github.com/asaaki/sjekksum/blob/47a21c19dcffc67a3bef11d4f2de7c167fd20087/lib/sjekksum/verhoeff.rb#L49-L57 | train |
sosedoff/lxc-ruby | lib/lxc/configuration.rb | LXC.Configuration.save_to_file | def save_to_file(path)
fullpath = File.expand_path(path)
lines = []
@content.each_pair do |key,value|
k = "lxc.#{key.gsub('_', '.')}"
if value.kind_of?(Array)
lines << value.map { |v| "#{k} = #{v}" }
else
lines << "#{k} = #{value}"
end
end
File.open(path, "w") do |f|
f.write(lines.flatten.join("\n"))
end
end | ruby | def save_to_file(path)
fullpath = File.expand_path(path)
lines = []
@content.each_pair do |key,value|
k = "lxc.#{key.gsub('_', '.')}"
if value.kind_of?(Array)
lines << value.map { |v| "#{k} = #{v}" }
else
lines << "#{k} = #{value}"
end
end
File.open(path, "w") do |f|
f.write(lines.flatten.join("\n"))
end
end | [
"def",
"save_to_file",
"(",
"path",
")",
"fullpath",
"=",
"File",
".",
"expand_path",
"(",
"path",
")",
"lines",
"=",
"[",
"]",
"@content",
".",
"each_pair",
"do",
"|",
"key",
",",
"value",
"|",
"k",
"=",
"\"lxc.#{key.gsub('_', '.')}\"",
"if",
"value",
".",
"kind_of?",
"(",
"Array",
")",
"lines",
"<<",
"value",
".",
"map",
"{",
"|",
"v",
"|",
"\"#{k} = #{v}\"",
"}",
"else",
"lines",
"<<",
"\"#{k} = #{value}\"",
"end",
"end",
"File",
".",
"open",
"(",
"path",
",",
"\"w\"",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"lines",
".",
"flatten",
".",
"join",
"(",
"\"\\n\"",
")",
")",
"end",
"end"
] | Save configuration into file
@param [path] path to output file | [
"Save",
"configuration",
"into",
"file"
] | 6d82c2ae3513789b2856d07a156e9131369f95fe | https://github.com/sosedoff/lxc-ruby/blob/6d82c2ae3513789b2856d07a156e9131369f95fe/lib/lxc/configuration.rb#L47-L64 | train |
sportngin/typhoid | lib/typhoid/request_builder.rb | Typhoid.RequestBuilder.symbolize_keys | def symbolize_keys(hash)
hash = hash.to_hash
if hash.respond_to?(:symbolize_keys)
hash.symbolize_keys
else
hash.inject({}) do |new_hash, (key, value)|
new_hash[symbolize_key(key)] = value
new_hash
end
end
end | ruby | def symbolize_keys(hash)
hash = hash.to_hash
if hash.respond_to?(:symbolize_keys)
hash.symbolize_keys
else
hash.inject({}) do |new_hash, (key, value)|
new_hash[symbolize_key(key)] = value
new_hash
end
end
end | [
"def",
"symbolize_keys",
"(",
"hash",
")",
"hash",
"=",
"hash",
".",
"to_hash",
"if",
"hash",
".",
"respond_to?",
"(",
":symbolize_keys",
")",
"hash",
".",
"symbolize_keys",
"else",
"hash",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"new_hash",
",",
"(",
"key",
",",
"value",
")",
"|",
"new_hash",
"[",
"symbolize_key",
"(",
"key",
")",
"]",
"=",
"value",
"new_hash",
"end",
"end",
"end"
] | Ethon hates on hash with indifferent access for some reason | [
"Ethon",
"hates",
"on",
"hash",
"with",
"indifferent",
"access",
"for",
"some",
"reason"
] | c711dddf86ffc356ea4700626086daaf1567dc30 | https://github.com/sportngin/typhoid/blob/c711dddf86ffc356ea4700626086daaf1567dc30/lib/typhoid/request_builder.rb#L30-L40 | train |
ghn/transprt | lib/transprt/rate_limiting.rb | Transprt.RateLimiting.get | def get(url)
begin
response = perform_get(url)
rescue RestClient::TooManyRequests => e
# API uses HTTP 429 to notify us,
# @see https://github.com/OpendataCH/Transport/blob/master/lib/Transport/Application.php
return nil unless wait_for_quota
sleep_until_quota_reset(e.response)
response = perform_get(url)
end
response
end | ruby | def get(url)
begin
response = perform_get(url)
rescue RestClient::TooManyRequests => e
# API uses HTTP 429 to notify us,
# @see https://github.com/OpendataCH/Transport/blob/master/lib/Transport/Application.php
return nil unless wait_for_quota
sleep_until_quota_reset(e.response)
response = perform_get(url)
end
response
end | [
"def",
"get",
"(",
"url",
")",
"begin",
"response",
"=",
"perform_get",
"(",
"url",
")",
"rescue",
"RestClient",
"::",
"TooManyRequests",
"=>",
"e",
"return",
"nil",
"unless",
"wait_for_quota",
"sleep_until_quota_reset",
"(",
"e",
".",
"response",
")",
"response",
"=",
"perform_get",
"(",
"url",
")",
"end",
"response",
"end"
] | Performs HTTP queries while respecting the rate limit.
@param wait_for_quota [Boolean] whether to wait for quota reset
and query again if the rate limit (300 requests/s) is exceeded.
@return The HTTP response or nil if we're hitting the rate limit and
wait_for_quota is false (@see #initialize). | [
"Performs",
"HTTP",
"queries",
"while",
"respecting",
"the",
"rate",
"limit",
"."
] | da609d39cd1907ec86814c7c5412e889a807193c | https://github.com/ghn/transprt/blob/da609d39cd1907ec86814c7c5412e889a807193c/lib/transprt/rate_limiting.rb#L13-L27 | train |
kamui/rack-accept_headers | lib/rack/accept_headers/language.rb | Rack::AcceptHeaders.Language.matches | def matches(language)
values.select {|v|
v = v.match(/^(.+?)-/) ? $1 : v if @first_level_match
v == language || v == '*' || (language.match(/^(.+?)-/) && v == $1)
}.sort {|a, b|
# "*" gets least precedence, any others are compared based on length.
a == '*' ? -1 : (b == '*' ? 1 : a.length <=> b.length)
}.reverse
end | ruby | def matches(language)
values.select {|v|
v = v.match(/^(.+?)-/) ? $1 : v if @first_level_match
v == language || v == '*' || (language.match(/^(.+?)-/) && v == $1)
}.sort {|a, b|
# "*" gets least precedence, any others are compared based on length.
a == '*' ? -1 : (b == '*' ? 1 : a.length <=> b.length)
}.reverse
end | [
"def",
"matches",
"(",
"language",
")",
"values",
".",
"select",
"{",
"|",
"v",
"|",
"v",
"=",
"v",
".",
"match",
"(",
"/",
"/",
")",
"?",
"$1",
":",
"v",
"if",
"@first_level_match",
"v",
"==",
"language",
"||",
"v",
"==",
"'*'",
"||",
"(",
"language",
".",
"match",
"(",
"/",
"/",
")",
"&&",
"v",
"==",
"$1",
")",
"}",
".",
"sort",
"{",
"|",
"a",
",",
"b",
"|",
"a",
"==",
"'*'",
"?",
"-",
"1",
":",
"(",
"b",
"==",
"'*'",
"?",
"1",
":",
"a",
".",
"length",
"<=>",
"b",
".",
"length",
")",
"}",
".",
"reverse",
"end"
] | Returns an array of languages from this header that match the given
+language+, ordered by precedence. | [
"Returns",
"an",
"array",
"of",
"languages",
"from",
"this",
"header",
"that",
"match",
"the",
"given",
"+",
"language",
"+",
"ordered",
"by",
"precedence",
"."
] | 099bfbb919de86b5842c8e14be42b8b784e53f03 | https://github.com/kamui/rack-accept_headers/blob/099bfbb919de86b5842c8e14be42b8b784e53f03/lib/rack/accept_headers/language.rb#L26-L34 | train |
dalehamel/ruby-pandoc | lib/ruby-pandoc/converter.rb | RubyPandoc.Converter.convert | def convert(*args)
@options += args if args
outputfile = @options.map{ |x| x[:output] }.compact
tmp_file = Tempfile.new('pandoc-conversion')
@options += [{ output: tmp_file.path }] if outputfile.empty?
@option_string = prepare_options(@options)
begin
run_pandoc
IO.binread(tmp_file)
ensure
tmp_file.close
tmp_file.unlink
end
end | ruby | def convert(*args)
@options += args if args
outputfile = @options.map{ |x| x[:output] }.compact
tmp_file = Tempfile.new('pandoc-conversion')
@options += [{ output: tmp_file.path }] if outputfile.empty?
@option_string = prepare_options(@options)
begin
run_pandoc
IO.binread(tmp_file)
ensure
tmp_file.close
tmp_file.unlink
end
end | [
"def",
"convert",
"(",
"*",
"args",
")",
"@options",
"+=",
"args",
"if",
"args",
"outputfile",
"=",
"@options",
".",
"map",
"{",
"|",
"x",
"|",
"x",
"[",
":output",
"]",
"}",
".",
"compact",
"tmp_file",
"=",
"Tempfile",
".",
"new",
"(",
"'pandoc-conversion'",
")",
"@options",
"+=",
"[",
"{",
"output",
":",
"tmp_file",
".",
"path",
"}",
"]",
"if",
"outputfile",
".",
"empty?",
"@option_string",
"=",
"prepare_options",
"(",
"@options",
")",
"begin",
"run_pandoc",
"IO",
".",
"binread",
"(",
"tmp_file",
")",
"ensure",
"tmp_file",
".",
"close",
"tmp_file",
".",
"unlink",
"end",
"end"
] | Create a new RubyPandoc converter object. The first argument contains the
input either as string or as an array of filenames.
Any other arguments will be converted to pandoc options.
Usage:
new("# A String", :option1 => :value, :option2)
new(["/path/to/file.md"], :option1 => :value, :option2)
new(["/to/file1.html", "/to/file2.html"], :option1 => :value)
Run the conversion. The convert method can take any number of arguments,
which will be converted to pandoc options. If options were already
specified in an initializer or reader method, they will be combined with
any that are passed to this method.
Returns a string with the converted content.
Example:
RubyPandoc.new("# text").convert
# => "<h1 id=\"text\">text</h1>\n" | [
"Create",
"a",
"new",
"RubyPandoc",
"converter",
"object",
".",
"The",
"first",
"argument",
"contains",
"the",
"input",
"either",
"as",
"string",
"or",
"as",
"an",
"array",
"of",
"filenames",
"."
] | 43a4081c137bc9b7308651dd616e571b63b5ad6a | https://github.com/dalehamel/ruby-pandoc/blob/43a4081c137bc9b7308651dd616e571b63b5ad6a/lib/ruby-pandoc/converter.rb#L99-L112 | train |
dalehamel/ruby-pandoc | lib/ruby-pandoc/converter.rb | RubyPandoc.Converter.run_pandoc | def run_pandoc
command = unless @input_files.nil? || @input_files.empty?
"#{@@pandoc_path} #{@input_files} #{@option_string}"
else
"#{@@pandoc_path} #{@option_string}"
end
output = error = exit_status = nil
options = {}
options[:stdin_data] = @input_string if @input_string
output, error, exit_status = Open3.capture3(command, **options)
raise error unless exit_status && exit_status.success?
output
end | ruby | def run_pandoc
command = unless @input_files.nil? || @input_files.empty?
"#{@@pandoc_path} #{@input_files} #{@option_string}"
else
"#{@@pandoc_path} #{@option_string}"
end
output = error = exit_status = nil
options = {}
options[:stdin_data] = @input_string if @input_string
output, error, exit_status = Open3.capture3(command, **options)
raise error unless exit_status && exit_status.success?
output
end | [
"def",
"run_pandoc",
"command",
"=",
"unless",
"@input_files",
".",
"nil?",
"||",
"@input_files",
".",
"empty?",
"\"#{@@pandoc_path} #{@input_files} #{@option_string}\"",
"else",
"\"#{@@pandoc_path} #{@option_string}\"",
"end",
"output",
"=",
"error",
"=",
"exit_status",
"=",
"nil",
"options",
"=",
"{",
"}",
"options",
"[",
":stdin_data",
"]",
"=",
"@input_string",
"if",
"@input_string",
"output",
",",
"error",
",",
"exit_status",
"=",
"Open3",
".",
"capture3",
"(",
"command",
",",
"**",
"options",
")",
"raise",
"error",
"unless",
"exit_status",
"&&",
"exit_status",
".",
"success?",
"output",
"end"
] | Wrapper to run pandoc in a consistent, DRY way | [
"Wrapper",
"to",
"run",
"pandoc",
"in",
"a",
"consistent",
"DRY",
"way"
] | 43a4081c137bc9b7308651dd616e571b63b5ad6a | https://github.com/dalehamel/ruby-pandoc/blob/43a4081c137bc9b7308651dd616e571b63b5ad6a/lib/ruby-pandoc/converter.rb#L156-L168 | train |
dalehamel/ruby-pandoc | lib/ruby-pandoc/converter.rb | RubyPandoc.Converter.prepare_options | def prepare_options(opts = [])
opts.inject('') do |string, (option, value)|
string += case
when value
create_option(option, value)
when option.respond_to?(:each_pair)
prepare_options(option)
else
create_option(option)
end
end
end | ruby | def prepare_options(opts = [])
opts.inject('') do |string, (option, value)|
string += case
when value
create_option(option, value)
when option.respond_to?(:each_pair)
prepare_options(option)
else
create_option(option)
end
end
end | [
"def",
"prepare_options",
"(",
"opts",
"=",
"[",
"]",
")",
"opts",
".",
"inject",
"(",
"''",
")",
"do",
"|",
"string",
",",
"(",
"option",
",",
"value",
")",
"|",
"string",
"+=",
"case",
"when",
"value",
"create_option",
"(",
"option",
",",
"value",
")",
"when",
"option",
".",
"respond_to?",
"(",
":each_pair",
")",
"prepare_options",
"(",
"option",
")",
"else",
"create_option",
"(",
"option",
")",
"end",
"end",
"end"
] | Builds the option string to be passed to pandoc by iterating over the
opts passed in. Recursively calls itself in order to handle hash options. | [
"Builds",
"the",
"option",
"string",
"to",
"be",
"passed",
"to",
"pandoc",
"by",
"iterating",
"over",
"the",
"opts",
"passed",
"in",
".",
"Recursively",
"calls",
"itself",
"in",
"order",
"to",
"handle",
"hash",
"options",
"."
] | 43a4081c137bc9b7308651dd616e571b63b5ad6a | https://github.com/dalehamel/ruby-pandoc/blob/43a4081c137bc9b7308651dd616e571b63b5ad6a/lib/ruby-pandoc/converter.rb#L172-L183 | train |
dalehamel/ruby-pandoc | lib/ruby-pandoc/converter.rb | RubyPandoc.Converter.create_option | def create_option(flag, argument = nil)
return '' unless flag
flag = flag.to_s
return " #{argument}" if flag == 'extra'
set_pandoc_ruby_options(flag, argument)
if !argument.nil?
"#{format_flag(flag)} #{argument}"
else
format_flag(flag)
end
end | ruby | def create_option(flag, argument = nil)
return '' unless flag
flag = flag.to_s
return " #{argument}" if flag == 'extra'
set_pandoc_ruby_options(flag, argument)
if !argument.nil?
"#{format_flag(flag)} #{argument}"
else
format_flag(flag)
end
end | [
"def",
"create_option",
"(",
"flag",
",",
"argument",
"=",
"nil",
")",
"return",
"''",
"unless",
"flag",
"flag",
"=",
"flag",
".",
"to_s",
"return",
"\" #{argument}\"",
"if",
"flag",
"==",
"'extra'",
"set_pandoc_ruby_options",
"(",
"flag",
",",
"argument",
")",
"if",
"!",
"argument",
".",
"nil?",
"\"#{format_flag(flag)} #{argument}\"",
"else",
"format_flag",
"(",
"flag",
")",
"end",
"end"
] | Takes a flag and optional argument, uses it to set any relevant options
used by the library, and returns string with the option formatted as a
command line options. If the option has an argument, it is also included. | [
"Takes",
"a",
"flag",
"and",
"optional",
"argument",
"uses",
"it",
"to",
"set",
"any",
"relevant",
"options",
"used",
"by",
"the",
"library",
"and",
"returns",
"string",
"with",
"the",
"option",
"formatted",
"as",
"a",
"command",
"line",
"options",
".",
"If",
"the",
"option",
"has",
"an",
"argument",
"it",
"is",
"also",
"included",
"."
] | 43a4081c137bc9b7308651dd616e571b63b5ad6a | https://github.com/dalehamel/ruby-pandoc/blob/43a4081c137bc9b7308651dd616e571b63b5ad6a/lib/ruby-pandoc/converter.rb#L188-L198 | train |
dalehamel/ruby-pandoc | lib/ruby-pandoc/converter.rb | RubyPandoc.Converter.set_pandoc_ruby_options | def set_pandoc_ruby_options(flag, argument = nil)
case flag
when 't', 'to'
@writer = argument.to_s
@binary_output = true if BINARY_WRITERS.keys.include?(@writer)
end
end | ruby | def set_pandoc_ruby_options(flag, argument = nil)
case flag
when 't', 'to'
@writer = argument.to_s
@binary_output = true if BINARY_WRITERS.keys.include?(@writer)
end
end | [
"def",
"set_pandoc_ruby_options",
"(",
"flag",
",",
"argument",
"=",
"nil",
")",
"case",
"flag",
"when",
"'t'",
",",
"'to'",
"@writer",
"=",
"argument",
".",
"to_s",
"@binary_output",
"=",
"true",
"if",
"BINARY_WRITERS",
".",
"keys",
".",
"include?",
"(",
"@writer",
")",
"end",
"end"
] | Takes an option and optional argument and uses them to set any flags
used by RubyPandoc. | [
"Takes",
"an",
"option",
"and",
"optional",
"argument",
"and",
"uses",
"them",
"to",
"set",
"any",
"flags",
"used",
"by",
"RubyPandoc",
"."
] | 43a4081c137bc9b7308651dd616e571b63b5ad6a | https://github.com/dalehamel/ruby-pandoc/blob/43a4081c137bc9b7308651dd616e571b63b5ad6a/lib/ruby-pandoc/converter.rb#L212-L218 | train |
jarhart/rattler | lib/rattler/parsers/attributed_sequence.rb | Rattler::Parsers.AttributedSequence.parse | def parse(scanner, rules, scope = ParserScope.empty)
result = false
backtracking(scanner) do
if scope = parse_children(scanner, rules, scope.nest) {|r| result = r }
yield scope if block_given?
result
end
end
end | ruby | def parse(scanner, rules, scope = ParserScope.empty)
result = false
backtracking(scanner) do
if scope = parse_children(scanner, rules, scope.nest) {|r| result = r }
yield scope if block_given?
result
end
end
end | [
"def",
"parse",
"(",
"scanner",
",",
"rules",
",",
"scope",
"=",
"ParserScope",
".",
"empty",
")",
"result",
"=",
"false",
"backtracking",
"(",
"scanner",
")",
"do",
"if",
"scope",
"=",
"parse_children",
"(",
"scanner",
",",
"rules",
",",
"scope",
".",
"nest",
")",
"{",
"|",
"r",
"|",
"result",
"=",
"r",
"}",
"yield",
"scope",
"if",
"block_given?",
"result",
"end",
"end",
"end"
] | Parse each parser in sequence, and if they all succeed return the result
of applying the semantic action to the captured results.
@param (see Match#parse)
@return the result of applying the semantic action to the captured
results of each parser, or +false | [
"Parse",
"each",
"parser",
"in",
"sequence",
"and",
"if",
"they",
"all",
"succeed",
"return",
"the",
"result",
"of",
"applying",
"the",
"semantic",
"action",
"to",
"the",
"captured",
"results",
"."
] | 8b4efde2a05e9e790955bb635d4a1a9615893719 | https://github.com/jarhart/rattler/blob/8b4efde2a05e9e790955bb635d4a1a9615893719/lib/rattler/parsers/attributed_sequence.rb#L24-L32 | train |
evanrolfe/ruby-holdem | lib/ruby_holdem/deck.rb | RubyHoldem.Deck.burn | def burn(burn_cards)
return false if burn_cards.is_a?(Integer)
if burn_cards.is_a?(Card) || burn_cards.is_a?(String)
burn_cards = [burn_cards]
end
burn_cards.map! do |c|
c = Card.new(c) unless c.class == Card
@cards.delete(c)
end
true
end | ruby | def burn(burn_cards)
return false if burn_cards.is_a?(Integer)
if burn_cards.is_a?(Card) || burn_cards.is_a?(String)
burn_cards = [burn_cards]
end
burn_cards.map! do |c|
c = Card.new(c) unless c.class == Card
@cards.delete(c)
end
true
end | [
"def",
"burn",
"(",
"burn_cards",
")",
"return",
"false",
"if",
"burn_cards",
".",
"is_a?",
"(",
"Integer",
")",
"if",
"burn_cards",
".",
"is_a?",
"(",
"Card",
")",
"||",
"burn_cards",
".",
"is_a?",
"(",
"String",
")",
"burn_cards",
"=",
"[",
"burn_cards",
"]",
"end",
"burn_cards",
".",
"map!",
"do",
"|",
"c",
"|",
"c",
"=",
"Card",
".",
"new",
"(",
"c",
")",
"unless",
"c",
".",
"class",
"==",
"Card",
"@cards",
".",
"delete",
"(",
"c",
")",
"end",
"true",
"end"
] | delete an array or a single card from the deck
converts a string to a new card, if a string is given | [
"delete",
"an",
"array",
"or",
"a",
"single",
"card",
"from",
"the",
"deck",
"converts",
"a",
"string",
"to",
"a",
"new",
"card",
"if",
"a",
"string",
"is",
"given"
] | e0745c476de2c4bd50896433be24791420760e26 | https://github.com/evanrolfe/ruby-holdem/blob/e0745c476de2c4bd50896433be24791420760e26/lib/ruby_holdem/deck.rb#L29-L40 | train |
robotex82/itsf_backend | app/concerns/routing/itsf_backend_resource_concern.rb | Routing.ItsfBackendResourceConcern.backend_resources | def backend_resources(*args, &block)
resources(*args, &block)
# additional_member_actions = (Itsf::Backend::Configuration.default_resource_pages - [:show])
# if additional_member_actions.any?
# resources_name = args.first
# resources resources_name, only: [] do
# member do
# additional_member_actions.each do |action|
# get action
# end
# end
# end
# end
additional_resource_route_blocks = Itsf::Backend::Configuration.additional_resource_route_blocks
if additional_resource_route_blocks.any?
resources_name = args.first
additional_resource_route_blocks.each do |route_block|
resources resources_name, only: [] do
route_block.call(self)
end
end
end
end | ruby | def backend_resources(*args, &block)
resources(*args, &block)
# additional_member_actions = (Itsf::Backend::Configuration.default_resource_pages - [:show])
# if additional_member_actions.any?
# resources_name = args.first
# resources resources_name, only: [] do
# member do
# additional_member_actions.each do |action|
# get action
# end
# end
# end
# end
additional_resource_route_blocks = Itsf::Backend::Configuration.additional_resource_route_blocks
if additional_resource_route_blocks.any?
resources_name = args.first
additional_resource_route_blocks.each do |route_block|
resources resources_name, only: [] do
route_block.call(self)
end
end
end
end | [
"def",
"backend_resources",
"(",
"*",
"args",
",",
"&",
"block",
")",
"resources",
"(",
"*",
"args",
",",
"&",
"block",
")",
"additional_resource_route_blocks",
"=",
"Itsf",
"::",
"Backend",
"::",
"Configuration",
".",
"additional_resource_route_blocks",
"if",
"additional_resource_route_blocks",
".",
"any?",
"resources_name",
"=",
"args",
".",
"first",
"additional_resource_route_blocks",
".",
"each",
"do",
"|",
"route_block",
"|",
"resources",
"resources_name",
",",
"only",
":",
"[",
"]",
"do",
"route_block",
".",
"call",
"(",
"self",
")",
"end",
"end",
"end",
"end"
] | Using this method instead of resources, adds member routes for pages added in the
itsf_backend configuration. | [
"Using",
"this",
"method",
"instead",
"of",
"resources",
"adds",
"member",
"routes",
"for",
"pages",
"added",
"in",
"the",
"itsf_backend",
"configuration",
"."
] | 24a531e204b1c3de173edeb1bb7cd3d9cdfae412 | https://github.com/robotex82/itsf_backend/blob/24a531e204b1c3de173edeb1bb7cd3d9cdfae412/app/concerns/routing/itsf_backend_resource_concern.rb#L7-L32 | train |
hubertlepicki/apidocs | lib/apidocs.rb | Apidocs.ApiDocs.generate_html | def generate_html
FileUtils.rm_rf(Rails.root.join('tmp/apidocs'))
options = [Rails.root.join("app/controllers").to_s, "--op=#{Rails.root.join('tmp/apidocs')}"]
self.store = RDoc::Store.new
@options = load_options
@options.parse options
@exclude = @options.exclude
@last_modified = setup_output_dir @options.op_dir, @options.force_update
@store.encoding = @options.encoding if @options.respond_to? :encoding
@store.dry_run = @options.dry_run
@store.main = @options.main_page
@store.title = @options.title
@store.path = @options.op_dir
@start_time = Time.now
@store.load_cache
@options.default_title = "RDoc Documentation"
parse_files @options.files
@store.complete @options.visibility
formatter = RDoc::Markup::ToHtml.new(RDoc::Options.new)
routes = routes_by_regex.map do |r|
{verb: r[:verb],
path: r[:path].sub('(.:format)', ''),
class_name: gen_class_name(r),
action_name: gen_action_name(r)
}
end.each do |r|
doc = document_route(r)
r[:html_comment] = doc ? doc.accept(formatter) : ""
end.select { |r| r[:class_name] != "ApidocsController" }
puts routes.inspect
routes
end | ruby | def generate_html
FileUtils.rm_rf(Rails.root.join('tmp/apidocs'))
options = [Rails.root.join("app/controllers").to_s, "--op=#{Rails.root.join('tmp/apidocs')}"]
self.store = RDoc::Store.new
@options = load_options
@options.parse options
@exclude = @options.exclude
@last_modified = setup_output_dir @options.op_dir, @options.force_update
@store.encoding = @options.encoding if @options.respond_to? :encoding
@store.dry_run = @options.dry_run
@store.main = @options.main_page
@store.title = @options.title
@store.path = @options.op_dir
@start_time = Time.now
@store.load_cache
@options.default_title = "RDoc Documentation"
parse_files @options.files
@store.complete @options.visibility
formatter = RDoc::Markup::ToHtml.new(RDoc::Options.new)
routes = routes_by_regex.map do |r|
{verb: r[:verb],
path: r[:path].sub('(.:format)', ''),
class_name: gen_class_name(r),
action_name: gen_action_name(r)
}
end.each do |r|
doc = document_route(r)
r[:html_comment] = doc ? doc.accept(formatter) : ""
end.select { |r| r[:class_name] != "ApidocsController" }
puts routes.inspect
routes
end | [
"def",
"generate_html",
"FileUtils",
".",
"rm_rf",
"(",
"Rails",
".",
"root",
".",
"join",
"(",
"'tmp/apidocs'",
")",
")",
"options",
"=",
"[",
"Rails",
".",
"root",
".",
"join",
"(",
"\"app/controllers\"",
")",
".",
"to_s",
",",
"\"--op=#{Rails.root.join('tmp/apidocs')}\"",
"]",
"self",
".",
"store",
"=",
"RDoc",
"::",
"Store",
".",
"new",
"@options",
"=",
"load_options",
"@options",
".",
"parse",
"options",
"@exclude",
"=",
"@options",
".",
"exclude",
"@last_modified",
"=",
"setup_output_dir",
"@options",
".",
"op_dir",
",",
"@options",
".",
"force_update",
"@store",
".",
"encoding",
"=",
"@options",
".",
"encoding",
"if",
"@options",
".",
"respond_to?",
":encoding",
"@store",
".",
"dry_run",
"=",
"@options",
".",
"dry_run",
"@store",
".",
"main",
"=",
"@options",
".",
"main_page",
"@store",
".",
"title",
"=",
"@options",
".",
"title",
"@store",
".",
"path",
"=",
"@options",
".",
"op_dir",
"@start_time",
"=",
"Time",
".",
"now",
"@store",
".",
"load_cache",
"@options",
".",
"default_title",
"=",
"\"RDoc Documentation\"",
"parse_files",
"@options",
".",
"files",
"@store",
".",
"complete",
"@options",
".",
"visibility",
"formatter",
"=",
"RDoc",
"::",
"Markup",
"::",
"ToHtml",
".",
"new",
"(",
"RDoc",
"::",
"Options",
".",
"new",
")",
"routes",
"=",
"routes_by_regex",
".",
"map",
"do",
"|",
"r",
"|",
"{",
"verb",
":",
"r",
"[",
":verb",
"]",
",",
"path",
":",
"r",
"[",
":path",
"]",
".",
"sub",
"(",
"'(.:format)'",
",",
"''",
")",
",",
"class_name",
":",
"gen_class_name",
"(",
"r",
")",
",",
"action_name",
":",
"gen_action_name",
"(",
"r",
")",
"}",
"end",
".",
"each",
"do",
"|",
"r",
"|",
"doc",
"=",
"document_route",
"(",
"r",
")",
"r",
"[",
":html_comment",
"]",
"=",
"doc",
"?",
"doc",
".",
"accept",
"(",
"formatter",
")",
":",
"\"\"",
"end",
".",
"select",
"{",
"|",
"r",
"|",
"r",
"[",
":class_name",
"]",
"!=",
"\"ApidocsController\"",
"}",
"puts",
"routes",
".",
"inspect",
"routes",
"end"
] | generate_html entry point for on fly document generation | [
"generate_html",
"entry",
"point",
"for",
"on",
"fly",
"document",
"generation"
] | d8650776243fed5b64a5e14518eb7345cedf7ca2 | https://github.com/hubertlepicki/apidocs/blob/d8650776243fed5b64a5e14518eb7345cedf7ca2/lib/apidocs.rb#L14-L54 | train |
marcmo/cxxproject | lib/cxxproject/buildingblocks/has_sources_mixin.rb | Cxxproject.HasSources.collect_sources_and_toolchains | def collect_sources_and_toolchains
sources_to_build = {}
exclude_files = Set.new
exclude_sources.each do |p|
if p.include?("..")
Printer.printError "Error: Exclude source file pattern '#{p}' must not include '..'"
return nil
end
Dir.glob(p).each {|f| exclude_files << f}
end
files = Set.new # do not build the same file twice
add_to_sources_to_build(sources_to_build, exclude_files, sources)
source_patterns.each do |p|
if p.include?("..")
Printer.printError "Error: Source file pattern '#{p}' must not include '..'"
return nil
end
globRes = Dir.glob(p)
if (globRes.length == 0)
Printer.printWarning "Warning: Source file pattern '#{p}' did not match to any file"
end
add_to_sources_to_build(sources_to_build, exclude_files, globRes, tcs4source(p))
end
return sources_to_build
end | ruby | def collect_sources_and_toolchains
sources_to_build = {}
exclude_files = Set.new
exclude_sources.each do |p|
if p.include?("..")
Printer.printError "Error: Exclude source file pattern '#{p}' must not include '..'"
return nil
end
Dir.glob(p).each {|f| exclude_files << f}
end
files = Set.new # do not build the same file twice
add_to_sources_to_build(sources_to_build, exclude_files, sources)
source_patterns.each do |p|
if p.include?("..")
Printer.printError "Error: Source file pattern '#{p}' must not include '..'"
return nil
end
globRes = Dir.glob(p)
if (globRes.length == 0)
Printer.printWarning "Warning: Source file pattern '#{p}' did not match to any file"
end
add_to_sources_to_build(sources_to_build, exclude_files, globRes, tcs4source(p))
end
return sources_to_build
end | [
"def",
"collect_sources_and_toolchains",
"sources_to_build",
"=",
"{",
"}",
"exclude_files",
"=",
"Set",
".",
"new",
"exclude_sources",
".",
"each",
"do",
"|",
"p",
"|",
"if",
"p",
".",
"include?",
"(",
"\"..\"",
")",
"Printer",
".",
"printError",
"\"Error: Exclude source file pattern '#{p}' must not include '..'\"",
"return",
"nil",
"end",
"Dir",
".",
"glob",
"(",
"p",
")",
".",
"each",
"{",
"|",
"f",
"|",
"exclude_files",
"<<",
"f",
"}",
"end",
"files",
"=",
"Set",
".",
"new",
"add_to_sources_to_build",
"(",
"sources_to_build",
",",
"exclude_files",
",",
"sources",
")",
"source_patterns",
".",
"each",
"do",
"|",
"p",
"|",
"if",
"p",
".",
"include?",
"(",
"\"..\"",
")",
"Printer",
".",
"printError",
"\"Error: Source file pattern '#{p}' must not include '..'\"",
"return",
"nil",
"end",
"globRes",
"=",
"Dir",
".",
"glob",
"(",
"p",
")",
"if",
"(",
"globRes",
".",
"length",
"==",
"0",
")",
"Printer",
".",
"printWarning",
"\"Warning: Source file pattern '#{p}' did not match to any file\"",
"end",
"add_to_sources_to_build",
"(",
"sources_to_build",
",",
"exclude_files",
",",
"globRes",
",",
"tcs4source",
"(",
"p",
")",
")",
"end",
"return",
"sources_to_build",
"end"
] | returns a hash from all sources to the toolchain that should be used for a source | [
"returns",
"a",
"hash",
"from",
"all",
"sources",
"to",
"the",
"toolchain",
"that",
"should",
"be",
"used",
"for",
"a",
"source"
] | 3740a09d6a143acd96bde3d2ff79055a6b810da4 | https://github.com/marcmo/cxxproject/blob/3740a09d6a143acd96bde3d2ff79055a6b810da4/lib/cxxproject/buildingblocks/has_sources_mixin.rb#L193-L222 | train |
marcmo/cxxproject | lib/cxxproject/buildingblocks/has_sources_mixin.rb | Cxxproject.HasSources.calc_dirs_with_files | def calc_dirs_with_files(sources)
filemap = {}
sources.keys.sort.reverse.each do |o|
d = File.dirname(o)
if filemap.include?(d)
filemap[d] << o
else
filemap[d] = [o]
end
end
return filemap
end | ruby | def calc_dirs_with_files(sources)
filemap = {}
sources.keys.sort.reverse.each do |o|
d = File.dirname(o)
if filemap.include?(d)
filemap[d] << o
else
filemap[d] = [o]
end
end
return filemap
end | [
"def",
"calc_dirs_with_files",
"(",
"sources",
")",
"filemap",
"=",
"{",
"}",
"sources",
".",
"keys",
".",
"sort",
".",
"reverse",
".",
"each",
"do",
"|",
"o",
"|",
"d",
"=",
"File",
".",
"dirname",
"(",
"o",
")",
"if",
"filemap",
".",
"include?",
"(",
"d",
")",
"filemap",
"[",
"d",
"]",
"<<",
"o",
"else",
"filemap",
"[",
"d",
"]",
"=",
"[",
"o",
"]",
"end",
"end",
"return",
"filemap",
"end"
] | calcs a map from unique directories to array of sources within this dir | [
"calcs",
"a",
"map",
"from",
"unique",
"directories",
"to",
"array",
"of",
"sources",
"within",
"this",
"dir"
] | 3740a09d6a143acd96bde3d2ff79055a6b810da4 | https://github.com/marcmo/cxxproject/blob/3740a09d6a143acd96bde3d2ff79055a6b810da4/lib/cxxproject/buildingblocks/has_sources_mixin.rb#L225-L236 | train |
postmodern/rprogram | lib/rprogram/argument.rb | RProgram.Argument.arguments | def arguments(value)
value = case value
when Hash
value.map do |key,sub_value|
if sub_value == true then key.to_s
elsif sub_value then "#{key}=#{sub_value}"
end
end
when false, nil
[]
else
Array(value)
end
return value.compact
end | ruby | def arguments(value)
value = case value
when Hash
value.map do |key,sub_value|
if sub_value == true then key.to_s
elsif sub_value then "#{key}=#{sub_value}"
end
end
when false, nil
[]
else
Array(value)
end
return value.compact
end | [
"def",
"arguments",
"(",
"value",
")",
"value",
"=",
"case",
"value",
"when",
"Hash",
"value",
".",
"map",
"do",
"|",
"key",
",",
"sub_value",
"|",
"if",
"sub_value",
"==",
"true",
"then",
"key",
".",
"to_s",
"elsif",
"sub_value",
"then",
"\"#{key}=#{sub_value}\"",
"end",
"end",
"when",
"false",
",",
"nil",
"[",
"]",
"else",
"Array",
"(",
"value",
")",
"end",
"return",
"value",
".",
"compact",
"end"
] | Formats a value into an Array of arguments.
@param [Hash, Array, String] value
The value to format.
@return [Array]
The formatted arguments. | [
"Formats",
"a",
"value",
"into",
"an",
"Array",
"of",
"arguments",
"."
] | 94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be | https://github.com/postmodern/rprogram/blob/94c32a72c98c7310d6e6b767b55ea8b8fbf0c0be/lib/rprogram/argument.rb#L13-L28 | train |
locks/halibut | lib/halibut/core/relation_map.rb | Halibut::Core.RelationMap.add | def add(relation, item)
unless item.respond_to?(:to_hash)
raise ArgumentError.new('only items that can be converted to hashes with #to_hash are permitted')
end
@relations[relation] = @relations.fetch(relation, []) << item
end | ruby | def add(relation, item)
unless item.respond_to?(:to_hash)
raise ArgumentError.new('only items that can be converted to hashes with #to_hash are permitted')
end
@relations[relation] = @relations.fetch(relation, []) << item
end | [
"def",
"add",
"(",
"relation",
",",
"item",
")",
"unless",
"item",
".",
"respond_to?",
"(",
":to_hash",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"'only items that can be converted to hashes with #to_hash are permitted'",
")",
"end",
"@relations",
"[",
"relation",
"]",
"=",
"@relations",
".",
"fetch",
"(",
"relation",
",",
"[",
"]",
")",
"<<",
"item",
"end"
] | Adds an object to a relation.
@example
relations = RelationMap.new
relations.add 'self', Link.new('/resource/1')
relations['self']
# => [#<Halibut::Core::Link:0x007fa0ca5b92b8 @href=\"/resource/1\",
@options=#<Halibut::Core::Link::Options:0x007fa0ca5b9240
@templated=nil, @type=nil, @name=nil, @profile=nil,
@title=nil, @hreflang=nil>>]
@param [String] relation relation that the object belongs to
@param [Object] item the object to add to the relation | [
"Adds",
"an",
"object",
"to",
"a",
"relation",
"."
] | b8da6aa0796c9db317b9cd3d377915499a52383c | https://github.com/locks/halibut/blob/b8da6aa0796c9db317b9cd3d377915499a52383c/lib/halibut/core/relation_map.rb#L31-L37 | train |
locks/halibut | lib/halibut/core/relation_map.rb | Halibut::Core.RelationMap.to_hash | def to_hash
@relations.each_with_object({}) do |(rel,val), obj|
rel = rel.to_s
hashed_val = val.map(&:to_hash)
if val.length == 1 && !single_item_arrays?
hashed_val = val.first.to_hash
end
obj[rel] = hashed_val
end
end | ruby | def to_hash
@relations.each_with_object({}) do |(rel,val), obj|
rel = rel.to_s
hashed_val = val.map(&:to_hash)
if val.length == 1 && !single_item_arrays?
hashed_val = val.first.to_hash
end
obj[rel] = hashed_val
end
end | [
"def",
"to_hash",
"@relations",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"(",
"rel",
",",
"val",
")",
",",
"obj",
"|",
"rel",
"=",
"rel",
".",
"to_s",
"hashed_val",
"=",
"val",
".",
"map",
"(",
"&",
":to_hash",
")",
"if",
"val",
".",
"length",
"==",
"1",
"&&",
"!",
"single_item_arrays?",
"hashed_val",
"=",
"val",
".",
"first",
".",
"to_hash",
"end",
"obj",
"[",
"rel",
"]",
"=",
"hashed_val",
"end",
"end"
] | Returns a hash corresponding to the object.
RelationMap doens't just return @relations because it needs to convert
correctly when a relation only has a single item.
@return [Hash] relation map in hash format | [
"Returns",
"a",
"hash",
"corresponding",
"to",
"the",
"object",
"."
] | b8da6aa0796c9db317b9cd3d377915499a52383c | https://github.com/locks/halibut/blob/b8da6aa0796c9db317b9cd3d377915499a52383c/lib/halibut/core/relation_map.rb#L45-L56 | train |
anthonator/dirigible | lib/dirigible/request.rb | Dirigible.Request.request | def request(method, path, options, headers)
headers.merge!({
'User-Agent' => user_agent,
'Accept' => 'application/vnd.urbanairship+json; version=3;',
})
response = connection.send(method) do |request|
request.url("#{endpoint}#{path}/")
if [:post, :put].member?(method)
request.body = options.to_json
else
request.params.merge!(options)
end
request.headers.merge!(headers)
end
Utils.handle_api_error(response) unless (200..399).include?(response.status)
Utils.parse_message(response)
end | ruby | def request(method, path, options, headers)
headers.merge!({
'User-Agent' => user_agent,
'Accept' => 'application/vnd.urbanairship+json; version=3;',
})
response = connection.send(method) do |request|
request.url("#{endpoint}#{path}/")
if [:post, :put].member?(method)
request.body = options.to_json
else
request.params.merge!(options)
end
request.headers.merge!(headers)
end
Utils.handle_api_error(response) unless (200..399).include?(response.status)
Utils.parse_message(response)
end | [
"def",
"request",
"(",
"method",
",",
"path",
",",
"options",
",",
"headers",
")",
"headers",
".",
"merge!",
"(",
"{",
"'User-Agent'",
"=>",
"user_agent",
",",
"'Accept'",
"=>",
"'application/vnd.urbanairship+json; version=3;'",
",",
"}",
")",
"response",
"=",
"connection",
".",
"send",
"(",
"method",
")",
"do",
"|",
"request",
"|",
"request",
".",
"url",
"(",
"\"#{endpoint}#{path}/\"",
")",
"if",
"[",
":post",
",",
":put",
"]",
".",
"member?",
"(",
"method",
")",
"request",
".",
"body",
"=",
"options",
".",
"to_json",
"else",
"request",
".",
"params",
".",
"merge!",
"(",
"options",
")",
"end",
"request",
".",
"headers",
".",
"merge!",
"(",
"headers",
")",
"end",
"Utils",
".",
"handle_api_error",
"(",
"response",
")",
"unless",
"(",
"200",
"..",
"399",
")",
".",
"include?",
"(",
"response",
".",
"status",
")",
"Utils",
".",
"parse_message",
"(",
"response",
")",
"end"
] | Perform an HTTP request. | [
"Perform",
"an",
"HTTP",
"request",
"."
] | 829b265ae4e54e3d4b284900b2a51a707afb6105 | https://github.com/anthonator/dirigible/blob/829b265ae4e54e3d4b284900b2a51a707afb6105/lib/dirigible/request.rb#L21-L42 | train |
alecguintu/mongoid_follow | lib/mongoid_follow/follower.rb | Mongoid.Follower.follow | def follow(model)
if self.id != model.id && !self.follows?(model)
model.before_followed_by(self) if model.respond_to?('before_followed_by')
model.followers.create!(:ff_type => self.class.name, :ff_id => self.id)
model.inc(:fferc, 1)
model.after_followed_by(self) if model.respond_to?('after_followed_by')
self.before_follow(model) if self.respond_to?('before_follow')
self.followees.create!(:ff_type => model.class.name, :ff_id => model.id)
self.inc(:ffeec, 1)
self.after_follow(model) if self.respond_to?('after_follow')
else
return false
end
end | ruby | def follow(model)
if self.id != model.id && !self.follows?(model)
model.before_followed_by(self) if model.respond_to?('before_followed_by')
model.followers.create!(:ff_type => self.class.name, :ff_id => self.id)
model.inc(:fferc, 1)
model.after_followed_by(self) if model.respond_to?('after_followed_by')
self.before_follow(model) if self.respond_to?('before_follow')
self.followees.create!(:ff_type => model.class.name, :ff_id => model.id)
self.inc(:ffeec, 1)
self.after_follow(model) if self.respond_to?('after_follow')
else
return false
end
end | [
"def",
"follow",
"(",
"model",
")",
"if",
"self",
".",
"id",
"!=",
"model",
".",
"id",
"&&",
"!",
"self",
".",
"follows?",
"(",
"model",
")",
"model",
".",
"before_followed_by",
"(",
"self",
")",
"if",
"model",
".",
"respond_to?",
"(",
"'before_followed_by'",
")",
"model",
".",
"followers",
".",
"create!",
"(",
":ff_type",
"=>",
"self",
".",
"class",
".",
"name",
",",
":ff_id",
"=>",
"self",
".",
"id",
")",
"model",
".",
"inc",
"(",
":fferc",
",",
"1",
")",
"model",
".",
"after_followed_by",
"(",
"self",
")",
"if",
"model",
".",
"respond_to?",
"(",
"'after_followed_by'",
")",
"self",
".",
"before_follow",
"(",
"model",
")",
"if",
"self",
".",
"respond_to?",
"(",
"'before_follow'",
")",
"self",
".",
"followees",
".",
"create!",
"(",
":ff_type",
"=>",
"model",
".",
"class",
".",
"name",
",",
":ff_id",
"=>",
"model",
".",
"id",
")",
"self",
".",
"inc",
"(",
":ffeec",
",",
"1",
")",
"self",
".",
"after_follow",
"(",
"model",
")",
"if",
"self",
".",
"respond_to?",
"(",
"'after_follow'",
")",
"else",
"return",
"false",
"end",
"end"
] | follow a model
Example:
=> @bonnie.follow(@clyde) | [
"follow",
"a",
"model"
] | 18573ccdf3e24bdae72a7e25f03dc25c27752545 | https://github.com/alecguintu/mongoid_follow/blob/18573ccdf3e24bdae72a7e25f03dc25c27752545/lib/mongoid_follow/follower.rb#L14-L30 | train |
alecguintu/mongoid_follow | lib/mongoid_follow/follower.rb | Mongoid.Follower.unfollow | def unfollow(model)
if self.id != model.id && self.follows?(model)
model.before_unfollowed_by(self) if model.respond_to?('before_unfollowed_by')
model.followers.where(:ff_type => self.class.name, :ff_id => self.id).destroy
model.inc(:fferc, -1)
model.after_unfollowed_by(self) if model.respond_to?('after_unfollowed_by')
self.before_unfollow(model) if self.respond_to?('before_unfollow')
self.followees.where(:ff_type => model.class.name, :ff_id => model.id).destroy
self.inc(:ffeec, -1)
self.after_unfollow(model) if self.respond_to?('after_unfollow')
else
return false
end
end | ruby | def unfollow(model)
if self.id != model.id && self.follows?(model)
model.before_unfollowed_by(self) if model.respond_to?('before_unfollowed_by')
model.followers.where(:ff_type => self.class.name, :ff_id => self.id).destroy
model.inc(:fferc, -1)
model.after_unfollowed_by(self) if model.respond_to?('after_unfollowed_by')
self.before_unfollow(model) if self.respond_to?('before_unfollow')
self.followees.where(:ff_type => model.class.name, :ff_id => model.id).destroy
self.inc(:ffeec, -1)
self.after_unfollow(model) if self.respond_to?('after_unfollow')
else
return false
end
end | [
"def",
"unfollow",
"(",
"model",
")",
"if",
"self",
".",
"id",
"!=",
"model",
".",
"id",
"&&",
"self",
".",
"follows?",
"(",
"model",
")",
"model",
".",
"before_unfollowed_by",
"(",
"self",
")",
"if",
"model",
".",
"respond_to?",
"(",
"'before_unfollowed_by'",
")",
"model",
".",
"followers",
".",
"where",
"(",
":ff_type",
"=>",
"self",
".",
"class",
".",
"name",
",",
":ff_id",
"=>",
"self",
".",
"id",
")",
".",
"destroy",
"model",
".",
"inc",
"(",
":fferc",
",",
"-",
"1",
")",
"model",
".",
"after_unfollowed_by",
"(",
"self",
")",
"if",
"model",
".",
"respond_to?",
"(",
"'after_unfollowed_by'",
")",
"self",
".",
"before_unfollow",
"(",
"model",
")",
"if",
"self",
".",
"respond_to?",
"(",
"'before_unfollow'",
")",
"self",
".",
"followees",
".",
"where",
"(",
":ff_type",
"=>",
"model",
".",
"class",
".",
"name",
",",
":ff_id",
"=>",
"model",
".",
"id",
")",
".",
"destroy",
"self",
".",
"inc",
"(",
":ffeec",
",",
"-",
"1",
")",
"self",
".",
"after_unfollow",
"(",
"model",
")",
"if",
"self",
".",
"respond_to?",
"(",
"'after_unfollow'",
")",
"else",
"return",
"false",
"end",
"end"
] | unfollow a model
Example:
=> @bonnie.unfollow(@clyde) | [
"unfollow",
"a",
"model"
] | 18573ccdf3e24bdae72a7e25f03dc25c27752545 | https://github.com/alecguintu/mongoid_follow/blob/18573ccdf3e24bdae72a7e25f03dc25c27752545/lib/mongoid_follow/follower.rb#L36-L52 | train |
jaredbeck/template_params | lib/template_params/assertion.rb | TemplateParams.Assertion.assert_type | def assert_type(value)
unless @type.nil? || value.is_a?(@type) || allow_nil && value.nil?
raise TypeError, format("Expected %s, got %s", @type, value.class)
end
end | ruby | def assert_type(value)
unless @type.nil? || value.is_a?(@type) || allow_nil && value.nil?
raise TypeError, format("Expected %s, got %s", @type, value.class)
end
end | [
"def",
"assert_type",
"(",
"value",
")",
"unless",
"@type",
".",
"nil?",
"||",
"value",
".",
"is_a?",
"(",
"@type",
")",
"||",
"allow_nil",
"&&",
"value",
".",
"nil?",
"raise",
"TypeError",
",",
"format",
"(",
"\"Expected %s, got %s\"",
",",
"@type",
",",
"value",
".",
"class",
")",
"end",
"end"
] | Raises a `TypeError` if `value` is not of `@type`.
@api private | [
"Raises",
"a",
"TypeError",
"if",
"value",
"is",
"not",
"of"
] | 32dba5caef32646f663bc46a7a44b55de225e76e | https://github.com/jaredbeck/template_params/blob/32dba5caef32646f663bc46a7a44b55de225e76e/lib/template_params/assertion.rb#L48-L52 | train |
birarda/logan | lib/logan/todolist.rb | Logan.TodoList.todo_with_substring | def todo_with_substring(substring)
issue_todo = @remaining_todos.detect{ |t| !t.content.index(substring).nil? }
issue_todo ||= @completed_todos.detect { |t| !t.content.index(substring).nil? }
end | ruby | def todo_with_substring(substring)
issue_todo = @remaining_todos.detect{ |t| !t.content.index(substring).nil? }
issue_todo ||= @completed_todos.detect { |t| !t.content.index(substring).nil? }
end | [
"def",
"todo_with_substring",
"(",
"substring",
")",
"issue_todo",
"=",
"@remaining_todos",
".",
"detect",
"{",
"|",
"t",
"|",
"!",
"t",
".",
"content",
".",
"index",
"(",
"substring",
")",
".",
"nil?",
"}",
"issue_todo",
"||=",
"@completed_todos",
".",
"detect",
"{",
"|",
"t",
"|",
"!",
"t",
".",
"content",
".",
"index",
"(",
"substring",
")",
".",
"nil?",
"}",
"end"
] | searches the remaining and completed todos for the first todo with the substring in its content
@param [String] substring substring to look for
@return [Logan::Todo] the matched todo, or nil if there wasn't one | [
"searches",
"the",
"remaining",
"and",
"completed",
"todos",
"for",
"the",
"first",
"todo",
"with",
"the",
"substring",
"in",
"its",
"content"
] | c007081c7dbb5b98ef5312db78f84867c6075ab0 | https://github.com/birarda/logan/blob/c007081c7dbb5b98ef5312db78f84867c6075ab0/lib/logan/todolist.rb#L81-L84 | train |
birarda/logan | lib/logan/todolist.rb | Logan.TodoList.create_todo | def create_todo(todo)
post_params = {
:body => todo.post_json,
:headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'})
}
response = Logan::Client.post "/projects/#{@project_id}/todolists/#{@id}/todos.json", post_params
Logan::Todo.new response
end | ruby | def create_todo(todo)
post_params = {
:body => todo.post_json,
:headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'})
}
response = Logan::Client.post "/projects/#{@project_id}/todolists/#{@id}/todos.json", post_params
Logan::Todo.new response
end | [
"def",
"create_todo",
"(",
"todo",
")",
"post_params",
"=",
"{",
":body",
"=>",
"todo",
".",
"post_json",
",",
":headers",
"=>",
"Logan",
"::",
"Client",
".",
"headers",
".",
"merge",
"(",
"{",
"'Content-Type'",
"=>",
"'application/json'",
"}",
")",
"}",
"response",
"=",
"Logan",
"::",
"Client",
".",
"post",
"\"/projects/#{@project_id}/todolists/#{@id}/todos.json\"",
",",
"post_params",
"Logan",
"::",
"Todo",
".",
"new",
"response",
"end"
] | create a todo in this todo list via the Basecamp API
@param [Logan::Todo] todo the todo instance to create in this todo lost
@return [Logan::Todo] the created todo returned from the Basecamp API | [
"create",
"a",
"todo",
"in",
"this",
"todo",
"list",
"via",
"the",
"Basecamp",
"API"
] | c007081c7dbb5b98ef5312db78f84867c6075ab0 | https://github.com/birarda/logan/blob/c007081c7dbb5b98ef5312db78f84867c6075ab0/lib/logan/todolist.rb#L90-L98 | train |
birarda/logan | lib/logan/todolist.rb | Logan.TodoList.update_todo | def update_todo(todo)
put_params = {
:body => todo.put_json,
:headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'})
}
response = Logan::Client.put "/projects/#{@project_id}/todos/#{todo.id}.json", put_params
Logan::Todo.new response
end | ruby | def update_todo(todo)
put_params = {
:body => todo.put_json,
:headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'})
}
response = Logan::Client.put "/projects/#{@project_id}/todos/#{todo.id}.json", put_params
Logan::Todo.new response
end | [
"def",
"update_todo",
"(",
"todo",
")",
"put_params",
"=",
"{",
":body",
"=>",
"todo",
".",
"put_json",
",",
":headers",
"=>",
"Logan",
"::",
"Client",
".",
"headers",
".",
"merge",
"(",
"{",
"'Content-Type'",
"=>",
"'application/json'",
"}",
")",
"}",
"response",
"=",
"Logan",
"::",
"Client",
".",
"put",
"\"/projects/#{@project_id}/todos/#{todo.id}.json\"",
",",
"put_params",
"Logan",
"::",
"Todo",
".",
"new",
"response",
"end"
] | update a todo in this todo list via the Basecamp API
@param [Logan::Todo] todo the todo instance to update in this todo list
@return [Logan::Todo] the updated todo instance returned from the Basecamp API | [
"update",
"a",
"todo",
"in",
"this",
"todo",
"list",
"via",
"the",
"Basecamp",
"API"
] | c007081c7dbb5b98ef5312db78f84867c6075ab0 | https://github.com/birarda/logan/blob/c007081c7dbb5b98ef5312db78f84867c6075ab0/lib/logan/todolist.rb#L104-L112 | train |
boost/safety_cone | lib/safety_cone/filter.rb | SafetyCone.Filter.safety_cone_filter | def safety_cone_filter
if cone = fetch_cone
if cone.type == 'notice'
flash.now["safetycone_#{notice_type(cone.type)}"] = cone.message
else
flash["safetycone_#{notice_type(cone.type)}"] = cone.message
end
redirect_to safety_redirect if cone.type == 'block'
end
end | ruby | def safety_cone_filter
if cone = fetch_cone
if cone.type == 'notice'
flash.now["safetycone_#{notice_type(cone.type)}"] = cone.message
else
flash["safetycone_#{notice_type(cone.type)}"] = cone.message
end
redirect_to safety_redirect if cone.type == 'block'
end
end | [
"def",
"safety_cone_filter",
"if",
"cone",
"=",
"fetch_cone",
"if",
"cone",
".",
"type",
"==",
"'notice'",
"flash",
".",
"now",
"[",
"\"safetycone_#{notice_type(cone.type)}\"",
"]",
"=",
"cone",
".",
"message",
"else",
"flash",
"[",
"\"safetycone_#{notice_type(cone.type)}\"",
"]",
"=",
"cone",
".",
"message",
"end",
"redirect_to",
"safety_redirect",
"if",
"cone",
".",
"type",
"==",
"'block'",
"end",
"end"
] | Filter method that does the SafetyCone action
based on the configuration. | [
"Filter",
"method",
"that",
"does",
"the",
"SafetyCone",
"action",
"based",
"on",
"the",
"configuration",
"."
] | 45dfcb0a9f9702386f8f0af8254c72cb5162b0cb | https://github.com/boost/safety_cone/blob/45dfcb0a9f9702386f8f0af8254c72cb5162b0cb/lib/safety_cone/filter.rb#L17-L27 | train |
boost/safety_cone | lib/safety_cone/filter.rb | SafetyCone.Filter.fetch_cone | def fetch_cone
paths = SafetyCone.paths
if path = paths[request_action]
key = request_action
elsif cone = paths[request_method]
key = request_method
else
return false
end
path = Path.new(key, path)
path.fetch
%w[notice block].include?(path.type) ? path : false
end | ruby | def fetch_cone
paths = SafetyCone.paths
if path = paths[request_action]
key = request_action
elsif cone = paths[request_method]
key = request_method
else
return false
end
path = Path.new(key, path)
path.fetch
%w[notice block].include?(path.type) ? path : false
end | [
"def",
"fetch_cone",
"paths",
"=",
"SafetyCone",
".",
"paths",
"if",
"path",
"=",
"paths",
"[",
"request_action",
"]",
"key",
"=",
"request_action",
"elsif",
"cone",
"=",
"paths",
"[",
"request_method",
"]",
"key",
"=",
"request_method",
"else",
"return",
"false",
"end",
"path",
"=",
"Path",
".",
"new",
"(",
"key",
",",
"path",
")",
"path",
".",
"fetch",
"%w[",
"notice",
"block",
"]",
".",
"include?",
"(",
"path",
".",
"type",
")",
"?",
"path",
":",
"false",
"end"
] | Fetches a configuration based on current request | [
"Fetches",
"a",
"configuration",
"based",
"on",
"current",
"request"
] | 45dfcb0a9f9702386f8f0af8254c72cb5162b0cb | https://github.com/boost/safety_cone/blob/45dfcb0a9f9702386f8f0af8254c72cb5162b0cb/lib/safety_cone/filter.rb#L32-L47 | train |
holman/stars | lib/stars/client.rb | Stars.Client.star_loop | def star_loop
selection = ''
while true
puts "Type the number of the post that you want to learn about"
print " (or hit return to view all again, you ego-maniac) >> "
selection = $stdin.gets.chomp
break if ['','q','quit','exit','fuckthis'].include?(selection.downcase)
show(selection)
end
display if selection == ''
end | ruby | def star_loop
selection = ''
while true
puts "Type the number of the post that you want to learn about"
print " (or hit return to view all again, you ego-maniac) >> "
selection = $stdin.gets.chomp
break if ['','q','quit','exit','fuckthis'].include?(selection.downcase)
show(selection)
end
display if selection == ''
end | [
"def",
"star_loop",
"selection",
"=",
"''",
"while",
"true",
"puts",
"\"Type the number of the post that you want to learn about\"",
"print",
"\" (or hit return to view all again, you ego-maniac) >> \"",
"selection",
"=",
"$stdin",
".",
"gets",
".",
"chomp",
"break",
"if",
"[",
"''",
",",
"'q'",
",",
"'quit'",
",",
"'exit'",
",",
"'fuckthis'",
"]",
".",
"include?",
"(",
"selection",
".",
"downcase",
")",
"show",
"(",
"selection",
")",
"end",
"display",
"if",
"selection",
"==",
"''",
"end"
] | Initializes a new Client.
Returns nothing.
Run a loop FOREVER until we kill it or we make a selection.
Returns nothing. | [
"Initializes",
"a",
"new",
"Client",
"."
] | 4c12a7d2fa935fe746d263aad5208ed0630c0b1e | https://github.com/holman/stars/blob/4c12a7d2fa935fe746d263aad5208ed0630c0b1e/lib/stars/client.rb#L28-L38 | train |
holman/stars | lib/stars/client.rb | Stars.Client.show | def show(id)
post = @posts[id.to_i-1]
return puts("\nMake a valid selection. Pretty please?\n") unless post
puts post.more
display
end | ruby | def show(id)
post = @posts[id.to_i-1]
return puts("\nMake a valid selection. Pretty please?\n") unless post
puts post.more
display
end | [
"def",
"show",
"(",
"id",
")",
"post",
"=",
"@posts",
"[",
"id",
".",
"to_i",
"-",
"1",
"]",
"return",
"puts",
"(",
"\"\\nMake a valid selection. Pretty please?\\n\"",
")",
"unless",
"post",
"puts",
"post",
".",
"more",
"display",
"end"
] | Displays all of the star tables and information we have.
Returns nothing.
Show more information about a particular post.
id - the Integer id entered by the user, which we map to a Post
Returns nothing (although does delegate to the Post to show #more). | [
"Displays",
"all",
"of",
"the",
"star",
"tables",
"and",
"information",
"we",
"have",
"."
] | 4c12a7d2fa935fe746d263aad5208ed0630c0b1e | https://github.com/holman/stars/blob/4c12a7d2fa935fe746d263aad5208ed0630c0b1e/lib/stars/client.rb#L66-L71 | train |
holman/stars | lib/stars/client.rb | Stars.Client.print_posts | def print_posts(posts)
table do |t|
t.headings = headings
posts.each_with_index do |post,i|
t << [
{ :value => i+1, :alignment => :right },
post.service.capitalize,
{ :value => post.stars_count, :alignment => :center },
post.short_name
]
end
end
end | ruby | def print_posts(posts)
table do |t|
t.headings = headings
posts.each_with_index do |post,i|
t << [
{ :value => i+1, :alignment => :right },
post.service.capitalize,
{ :value => post.stars_count, :alignment => :center },
post.short_name
]
end
end
end | [
"def",
"print_posts",
"(",
"posts",
")",
"table",
"do",
"|",
"t",
"|",
"t",
".",
"headings",
"=",
"headings",
"posts",
".",
"each_with_index",
"do",
"|",
"post",
",",
"i",
"|",
"t",
"<<",
"[",
"{",
":value",
"=>",
"i",
"+",
"1",
",",
":alignment",
"=>",
":right",
"}",
",",
"post",
".",
"service",
".",
"capitalize",
",",
"{",
":value",
"=>",
"post",
".",
"stars_count",
",",
":alignment",
"=>",
":center",
"}",
",",
"post",
".",
"short_name",
"]",
"end",
"end",
"end"
] | This does the actual printing of posts.
posts - an Array of Post objects
It loops through the Array of posts and sends them to `terminal-table`. | [
"This",
"does",
"the",
"actual",
"printing",
"of",
"posts",
"."
] | 4c12a7d2fa935fe746d263aad5208ed0630c0b1e | https://github.com/holman/stars/blob/4c12a7d2fa935fe746d263aad5208ed0630c0b1e/lib/stars/client.rb#L78-L90 | train |
thejonanshow/gatherer | lib/gatherer/card_parser.rb | Gatherer.CardParser.loyalty | def loyalty(parsed_text = extract_power_toughness)
if parsed_text && !parsed_text.include?('/')
parsed_text.to_i if parsed_text.to_i > 0
end
end | ruby | def loyalty(parsed_text = extract_power_toughness)
if parsed_text && !parsed_text.include?('/')
parsed_text.to_i if parsed_text.to_i > 0
end
end | [
"def",
"loyalty",
"(",
"parsed_text",
"=",
"extract_power_toughness",
")",
"if",
"parsed_text",
"&&",
"!",
"parsed_text",
".",
"include?",
"(",
"'/'",
")",
"parsed_text",
".",
"to_i",
"if",
"parsed_text",
".",
"to_i",
">",
"0",
"end",
"end"
] | gatherer uses the pt row to display loyalty | [
"gatherer",
"uses",
"the",
"pt",
"row",
"to",
"display",
"loyalty"
] | b14b7a2cdf4fe536631dd16b6bd45bccccc0e5b6 | https://github.com/thejonanshow/gatherer/blob/b14b7a2cdf4fe536631dd16b6bd45bccccc0e5b6/lib/gatherer/card_parser.rb#L203-L207 | train |
KDEJewellers/aptly-api | lib/aptly/repository.rb | Aptly.Repository.add_file | def add_file(path, **kwords)
# Don't mangle query, the file API is inconsistently using camelCase
# rather than CamelCase.
response = connection.send(:post, "/repos/#{self.Name}/file/#{path}",
query: kwords,
query_mangle: false)
hash = JSON.parse(response.body)
error = Errors::RepositoryFileError.from_hash(hash)
raise error if error
hash['Report']['Added']
end | ruby | def add_file(path, **kwords)
# Don't mangle query, the file API is inconsistently using camelCase
# rather than CamelCase.
response = connection.send(:post, "/repos/#{self.Name}/file/#{path}",
query: kwords,
query_mangle: false)
hash = JSON.parse(response.body)
error = Errors::RepositoryFileError.from_hash(hash)
raise error if error
hash['Report']['Added']
end | [
"def",
"add_file",
"(",
"path",
",",
"**",
"kwords",
")",
"response",
"=",
"connection",
".",
"send",
"(",
":post",
",",
"\"/repos/#{self.Name}/file/#{path}\"",
",",
"query",
":",
"kwords",
",",
"query_mangle",
":",
"false",
")",
"hash",
"=",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
")",
"error",
"=",
"Errors",
"::",
"RepositoryFileError",
".",
"from_hash",
"(",
"hash",
")",
"raise",
"error",
"if",
"error",
"hash",
"[",
"'Report'",
"]",
"[",
"'Added'",
"]",
"end"
] | Add a previously uploaded file to the Repository.
@return [Hash] report data as specified in the API.
FIXME: this should be called file | [
"Add",
"a",
"previously",
"uploaded",
"file",
"to",
"the",
"Repository",
"."
] | 71a13417618d81ca0dcb7834559de1f31ec46e29 | https://github.com/KDEJewellers/aptly-api/blob/71a13417618d81ca0dcb7834559de1f31ec46e29/lib/aptly/repository.rb#L43-L53 | train |
KDEJewellers/aptly-api | lib/aptly/repository.rb | Aptly.Repository.packages | def packages(**kwords)
response = connection.send(:get, "/repos/#{self.Name}/packages",
query: kwords,
query_mangle: false)
JSON.parse(response.body)
end | ruby | def packages(**kwords)
response = connection.send(:get, "/repos/#{self.Name}/packages",
query: kwords,
query_mangle: false)
JSON.parse(response.body)
end | [
"def",
"packages",
"(",
"**",
"kwords",
")",
"response",
"=",
"connection",
".",
"send",
"(",
":get",
",",
"\"/repos/#{self.Name}/packages\"",
",",
"query",
":",
"kwords",
",",
"query_mangle",
":",
"false",
")",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
")",
"end"
] | List all packages in the repository
@return [Array<String>] list of packages in the repository | [
"List",
"all",
"packages",
"in",
"the",
"repository"
] | 71a13417618d81ca0dcb7834559de1f31ec46e29 | https://github.com/KDEJewellers/aptly-api/blob/71a13417618d81ca0dcb7834559de1f31ec46e29/lib/aptly/repository.rb#L65-L70 | train |
KDEJewellers/aptly-api | lib/aptly/repository.rb | Aptly.Repository.edit! | def edit!(**kwords)
response = connection.send(:put,
"/repos/#{self.Name}",
body: JSON.generate(kwords))
hash = JSON.parse(response.body, symbolize_names: true)
return nil if hash == marshal_dump
marshal_load(hash)
self
end | ruby | def edit!(**kwords)
response = connection.send(:put,
"/repos/#{self.Name}",
body: JSON.generate(kwords))
hash = JSON.parse(response.body, symbolize_names: true)
return nil if hash == marshal_dump
marshal_load(hash)
self
end | [
"def",
"edit!",
"(",
"**",
"kwords",
")",
"response",
"=",
"connection",
".",
"send",
"(",
":put",
",",
"\"/repos/#{self.Name}\"",
",",
"body",
":",
"JSON",
".",
"generate",
"(",
"kwords",
")",
")",
"hash",
"=",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
",",
"symbolize_names",
":",
"true",
")",
"return",
"nil",
"if",
"hash",
"==",
"marshal_dump",
"marshal_load",
"(",
"hash",
")",
"self",
"end"
] | Edit this repository's attributes as per the parameters.
@note this possibly mutates the attributes depending on the HTTP response
@return [self] if the instance data was mutated
@return [nil] if the instance data was not mutated | [
"Edit",
"this",
"repository",
"s",
"attributes",
"as",
"per",
"the",
"parameters",
"."
] | 71a13417618d81ca0dcb7834559de1f31ec46e29 | https://github.com/KDEJewellers/aptly-api/blob/71a13417618d81ca0dcb7834559de1f31ec46e29/lib/aptly/repository.rb#L110-L118 | train |
boston-library/mei | lib/mei/loc.rb | Mei.Loc.parse_authority_response | def parse_authority_response
threaded_responses = []
#end_response = Array.new(20)
end_response = []
position_counter = 0
@raw_response.select {|response| response[0] == "atom:entry"}.map do |response|
threaded_responses << Thread.new(position_counter) { |local_pos|
end_response[local_pos] = loc_response_to_qa(response_to_struct(response), position_counter)
}
position_counter+=1
#sleep(0.05)
#loc_response_to_qa(response_to_struct(response))
end
threaded_responses.each { |thr| thr.join }
end_response
end | ruby | def parse_authority_response
threaded_responses = []
#end_response = Array.new(20)
end_response = []
position_counter = 0
@raw_response.select {|response| response[0] == "atom:entry"}.map do |response|
threaded_responses << Thread.new(position_counter) { |local_pos|
end_response[local_pos] = loc_response_to_qa(response_to_struct(response), position_counter)
}
position_counter+=1
#sleep(0.05)
#loc_response_to_qa(response_to_struct(response))
end
threaded_responses.each { |thr| thr.join }
end_response
end | [
"def",
"parse_authority_response",
"threaded_responses",
"=",
"[",
"]",
"end_response",
"=",
"[",
"]",
"position_counter",
"=",
"0",
"@raw_response",
".",
"select",
"{",
"|",
"response",
"|",
"response",
"[",
"0",
"]",
"==",
"\"atom:entry\"",
"}",
".",
"map",
"do",
"|",
"response",
"|",
"threaded_responses",
"<<",
"Thread",
".",
"new",
"(",
"position_counter",
")",
"{",
"|",
"local_pos",
"|",
"end_response",
"[",
"local_pos",
"]",
"=",
"loc_response_to_qa",
"(",
"response_to_struct",
"(",
"response",
")",
",",
"position_counter",
")",
"}",
"position_counter",
"+=",
"1",
"end",
"threaded_responses",
".",
"each",
"{",
"|",
"thr",
"|",
"thr",
".",
"join",
"}",
"end_response",
"end"
] | Reformats the data received from the LOC service | [
"Reformats",
"the",
"data",
"received",
"from",
"the",
"LOC",
"service"
] | 57279df72a2f45d0fb79fd31c22f495b3a0ae290 | https://github.com/boston-library/mei/blob/57279df72a2f45d0fb79fd31c22f495b3a0ae290/lib/mei/loc.rb#L63-L79 | train |
boston-library/mei | lib/mei/loc.rb | Mei.Loc.loc_response_to_qa | def loc_response_to_qa(data, counter)
json_link = data.links.select { |link| link.first == 'application/json' }
if json_link.present?
json_link = json_link[0][1]
broader, narrower, variants = get_skos_concepts(json_link.gsub('.json',''))
end
#count = ActiveFedora::Base.find_with_conditions("subject_tesim:#{data.id.gsub('info:lc', 'http://id.loc.gov').gsub(':','\:')}", rows: '100', fl: 'id' ).length
#FIXME
count = ActiveFedora::Base.search_with_conditions("#{@solr_field}:#{solr_clean(data.id.gsub('info:lc', 'http://id.loc.gov'))}", rows: '100', fl: 'id' ).length
#count = 0
if count >= 99
count = "99+"
else
count = count.to_s
end
{
"uri_link" => data.id.gsub('info:lc', 'http://id.loc.gov') || data.title,
"label" => data.title,
"broader" => broader,
"narrower" => narrower,
"variants" => variants,
"count" => count
}
end | ruby | def loc_response_to_qa(data, counter)
json_link = data.links.select { |link| link.first == 'application/json' }
if json_link.present?
json_link = json_link[0][1]
broader, narrower, variants = get_skos_concepts(json_link.gsub('.json',''))
end
#count = ActiveFedora::Base.find_with_conditions("subject_tesim:#{data.id.gsub('info:lc', 'http://id.loc.gov').gsub(':','\:')}", rows: '100', fl: 'id' ).length
#FIXME
count = ActiveFedora::Base.search_with_conditions("#{@solr_field}:#{solr_clean(data.id.gsub('info:lc', 'http://id.loc.gov'))}", rows: '100', fl: 'id' ).length
#count = 0
if count >= 99
count = "99+"
else
count = count.to_s
end
{
"uri_link" => data.id.gsub('info:lc', 'http://id.loc.gov') || data.title,
"label" => data.title,
"broader" => broader,
"narrower" => narrower,
"variants" => variants,
"count" => count
}
end | [
"def",
"loc_response_to_qa",
"(",
"data",
",",
"counter",
")",
"json_link",
"=",
"data",
".",
"links",
".",
"select",
"{",
"|",
"link",
"|",
"link",
".",
"first",
"==",
"'application/json'",
"}",
"if",
"json_link",
".",
"present?",
"json_link",
"=",
"json_link",
"[",
"0",
"]",
"[",
"1",
"]",
"broader",
",",
"narrower",
",",
"variants",
"=",
"get_skos_concepts",
"(",
"json_link",
".",
"gsub",
"(",
"'.json'",
",",
"''",
")",
")",
"end",
"count",
"=",
"ActiveFedora",
"::",
"Base",
".",
"search_with_conditions",
"(",
"\"#{@solr_field}:#{solr_clean(data.id.gsub('info:lc', 'http://id.loc.gov'))}\"",
",",
"rows",
":",
"'100'",
",",
"fl",
":",
"'id'",
")",
".",
"length",
"if",
"count",
">=",
"99",
"count",
"=",
"\"99+\"",
"else",
"count",
"=",
"count",
".",
"to_s",
"end",
"{",
"\"uri_link\"",
"=>",
"data",
".",
"id",
".",
"gsub",
"(",
"'info:lc'",
",",
"'http://id.loc.gov'",
")",
"||",
"data",
".",
"title",
",",
"\"label\"",
"=>",
"data",
".",
"title",
",",
"\"broader\"",
"=>",
"broader",
",",
"\"narrower\"",
"=>",
"narrower",
",",
"\"variants\"",
"=>",
"variants",
",",
"\"count\"",
"=>",
"count",
"}",
"end"
] | Simple conversion from LoC-based struct to QA hash | [
"Simple",
"conversion",
"from",
"LoC",
"-",
"based",
"struct",
"to",
"QA",
"hash"
] | 57279df72a2f45d0fb79fd31c22f495b3a0ae290 | https://github.com/boston-library/mei/blob/57279df72a2f45d0fb79fd31c22f495b3a0ae290/lib/mei/loc.rb#L82-L110 | train |
postmodern/pullr | lib/pullr/remote_repository.rb | Pullr.RemoteRepository.name | def name
dirs = File.expand_path(@uri.path).split(File::SEPARATOR)
unless dirs.empty?
if @scm == :sub_version
if dirs[-1] == 'trunk'
dirs.pop
elsif (dirs[-2] == 'branches' || dirs[-2] == 'tags')
dirs.pop
dirs.pop
end
elsif @scm == :git
dirs.last.chomp!('.git')
end
end
return (dirs.last || @uri.host)
end | ruby | def name
dirs = File.expand_path(@uri.path).split(File::SEPARATOR)
unless dirs.empty?
if @scm == :sub_version
if dirs[-1] == 'trunk'
dirs.pop
elsif (dirs[-2] == 'branches' || dirs[-2] == 'tags')
dirs.pop
dirs.pop
end
elsif @scm == :git
dirs.last.chomp!('.git')
end
end
return (dirs.last || @uri.host)
end | [
"def",
"name",
"dirs",
"=",
"File",
".",
"expand_path",
"(",
"@uri",
".",
"path",
")",
".",
"split",
"(",
"File",
"::",
"SEPARATOR",
")",
"unless",
"dirs",
".",
"empty?",
"if",
"@scm",
"==",
":sub_version",
"if",
"dirs",
"[",
"-",
"1",
"]",
"==",
"'trunk'",
"dirs",
".",
"pop",
"elsif",
"(",
"dirs",
"[",
"-",
"2",
"]",
"==",
"'branches'",
"||",
"dirs",
"[",
"-",
"2",
"]",
"==",
"'tags'",
")",
"dirs",
".",
"pop",
"dirs",
".",
"pop",
"end",
"elsif",
"@scm",
"==",
":git",
"dirs",
".",
"last",
".",
"chomp!",
"(",
"'.git'",
")",
"end",
"end",
"return",
"(",
"dirs",
".",
"last",
"||",
"@uri",
".",
"host",
")",
"end"
] | Initializes the remote repository.
@param [Hash] options
Options for the remote repository.
@option options [URI::Generic] :uri
The URI of the remote repository.
@option options [Symbol, String] :scm
The SCM used for the remote repository.
The name of the repository.
@return [String]
The remote repository name.
@since 0.1.2 | [
"Initializes",
"the",
"remote",
"repository",
"."
] | 96993fdbf4765a75c539bdb3c4902373458093e7 | https://github.com/postmodern/pullr/blob/96993fdbf4765a75c539bdb3c4902373458093e7/lib/pullr/remote_repository.rb#L48-L65 | train |
jeanlescure/hipster_sql_to_hbase | lib/executor.rb | HipsterSqlToHbase.Executor.execute | def execute(thrift_call_group,host_s=nil,port_n=nil,incr=false)
@@host = host_s if !host_s.nil?
@@port = port_n if !port_n.nil?
socket = Thrift::Socket.new(@@host, @@port)
transport = Thrift::BufferedTransport.new(socket)
transport.open
protocol = Thrift::BinaryProtocol.new(transport)
client = HBase::Client.new(protocol)
results = []
if incr
not_incr = true
c_row = 0
end
thrift_call_group.each do |thrift_call|
if incr
if not_incr
c_row = increment_table_row_index(thrift_call[:arguments][0],thrift_call_group.length,client)
not_incr = false
end
c_row += 1
thrift_call[:arguments][1] = c_row.to_s
end
results << client.send(thrift_call[:method],*thrift_call[:arguments])
end
results.flatten
end | ruby | def execute(thrift_call_group,host_s=nil,port_n=nil,incr=false)
@@host = host_s if !host_s.nil?
@@port = port_n if !port_n.nil?
socket = Thrift::Socket.new(@@host, @@port)
transport = Thrift::BufferedTransport.new(socket)
transport.open
protocol = Thrift::BinaryProtocol.new(transport)
client = HBase::Client.new(protocol)
results = []
if incr
not_incr = true
c_row = 0
end
thrift_call_group.each do |thrift_call|
if incr
if not_incr
c_row = increment_table_row_index(thrift_call[:arguments][0],thrift_call_group.length,client)
not_incr = false
end
c_row += 1
thrift_call[:arguments][1] = c_row.to_s
end
results << client.send(thrift_call[:method],*thrift_call[:arguments])
end
results.flatten
end | [
"def",
"execute",
"(",
"thrift_call_group",
",",
"host_s",
"=",
"nil",
",",
"port_n",
"=",
"nil",
",",
"incr",
"=",
"false",
")",
"@@host",
"=",
"host_s",
"if",
"!",
"host_s",
".",
"nil?",
"@@port",
"=",
"port_n",
"if",
"!",
"port_n",
".",
"nil?",
"socket",
"=",
"Thrift",
"::",
"Socket",
".",
"new",
"(",
"@@host",
",",
"@@port",
")",
"transport",
"=",
"Thrift",
"::",
"BufferedTransport",
".",
"new",
"(",
"socket",
")",
"transport",
".",
"open",
"protocol",
"=",
"Thrift",
"::",
"BinaryProtocol",
".",
"new",
"(",
"transport",
")",
"client",
"=",
"HBase",
"::",
"Client",
".",
"new",
"(",
"protocol",
")",
"results",
"=",
"[",
"]",
"if",
"incr",
"not_incr",
"=",
"true",
"c_row",
"=",
"0",
"end",
"thrift_call_group",
".",
"each",
"do",
"|",
"thrift_call",
"|",
"if",
"incr",
"if",
"not_incr",
"c_row",
"=",
"increment_table_row_index",
"(",
"thrift_call",
"[",
":arguments",
"]",
"[",
"0",
"]",
",",
"thrift_call_group",
".",
"length",
",",
"client",
")",
"not_incr",
"=",
"false",
"end",
"c_row",
"+=",
"1",
"thrift_call",
"[",
":arguments",
"]",
"[",
"1",
"]",
"=",
"c_row",
".",
"to_s",
"end",
"results",
"<<",
"client",
".",
"send",
"(",
"thrift_call",
"[",
":method",
"]",
",",
"*",
"thrift_call",
"[",
":arguments",
"]",
")",
"end",
"results",
".",
"flatten",
"end"
] | Initialize a Thrift connection to the specified host and port
and execute the provided ThriftCallGroup object. | [
"Initialize",
"a",
"Thrift",
"connection",
"to",
"the",
"specified",
"host",
"and",
"port",
"and",
"execute",
"the",
"provided",
"ThriftCallGroup",
"object",
"."
] | eb181f2f869606a8fd68e88bde0a485051f262b8 | https://github.com/jeanlescure/hipster_sql_to_hbase/blob/eb181f2f869606a8fd68e88bde0a485051f262b8/lib/executor.rb#L52-L83 | train |
birarda/logan | lib/logan/project.rb | Logan.Project.todolists | def todolists
active_response = Logan::Client.get "/projects/#{@id}/todolists.json"
lists_array = active_response.parsed_response.map do |h|
Logan::TodoList.new h.merge({ :project_id => @id })
end
end | ruby | def todolists
active_response = Logan::Client.get "/projects/#{@id}/todolists.json"
lists_array = active_response.parsed_response.map do |h|
Logan::TodoList.new h.merge({ :project_id => @id })
end
end | [
"def",
"todolists",
"active_response",
"=",
"Logan",
"::",
"Client",
".",
"get",
"\"/projects/#{@id}/todolists.json\"",
"lists_array",
"=",
"active_response",
".",
"parsed_response",
".",
"map",
"do",
"|",
"h",
"|",
"Logan",
"::",
"TodoList",
".",
"new",
"h",
".",
"merge",
"(",
"{",
":project_id",
"=>",
"@id",
"}",
")",
"end",
"end"
] | get active todo lists for this project from Basecamp API
@return [Array<Logan::TodoList>] array of active todo lists for this project | [
"get",
"active",
"todo",
"lists",
"for",
"this",
"project",
"from",
"Basecamp",
"API"
] | c007081c7dbb5b98ef5312db78f84867c6075ab0 | https://github.com/birarda/logan/blob/c007081c7dbb5b98ef5312db78f84867c6075ab0/lib/logan/project.rb#L27-L32 | train |
birarda/logan | lib/logan/project.rb | Logan.Project.publish | def publish
post_params = {
:body => {}.to_json,
:headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'})
}
response = Logan::Client.post "/projects/#{@id}/publish.json", post_params
end | ruby | def publish
post_params = {
:body => {}.to_json,
:headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'})
}
response = Logan::Client.post "/projects/#{@id}/publish.json", post_params
end | [
"def",
"publish",
"post_params",
"=",
"{",
":body",
"=>",
"{",
"}",
".",
"to_json",
",",
":headers",
"=>",
"Logan",
"::",
"Client",
".",
"headers",
".",
"merge",
"(",
"{",
"'Content-Type'",
"=>",
"'application/json'",
"}",
")",
"}",
"response",
"=",
"Logan",
"::",
"Client",
".",
"post",
"\"/projects/#{@id}/publish.json\"",
",",
"post_params",
"end"
] | publish this project from Basecamp API
@return <Logan::Project> this project | [
"publish",
"this",
"project",
"from",
"Basecamp",
"API"
] | c007081c7dbb5b98ef5312db78f84867c6075ab0 | https://github.com/birarda/logan/blob/c007081c7dbb5b98ef5312db78f84867c6075ab0/lib/logan/project.rb#L37-L44 | train |
birarda/logan | lib/logan/project.rb | Logan.Project.completed_todolists | def completed_todolists
completed_response = Logan::Client.get "/projects/#{@id}/todolists/completed.json"
lists_array = completed_response.parsed_response.map do |h|
Logan::TodoList.new h.merge({ :project_id => @id })
end
end | ruby | def completed_todolists
completed_response = Logan::Client.get "/projects/#{@id}/todolists/completed.json"
lists_array = completed_response.parsed_response.map do |h|
Logan::TodoList.new h.merge({ :project_id => @id })
end
end | [
"def",
"completed_todolists",
"completed_response",
"=",
"Logan",
"::",
"Client",
".",
"get",
"\"/projects/#{@id}/todolists/completed.json\"",
"lists_array",
"=",
"completed_response",
".",
"parsed_response",
".",
"map",
"do",
"|",
"h",
"|",
"Logan",
"::",
"TodoList",
".",
"new",
"h",
".",
"merge",
"(",
"{",
":project_id",
"=>",
"@id",
"}",
")",
"end",
"end"
] | get completed todo lists for this project from Basecamp API
@return [Array<Logan::TodoList>] array of completed todo lists for this project | [
"get",
"completed",
"todo",
"lists",
"for",
"this",
"project",
"from",
"Basecamp",
"API"
] | c007081c7dbb5b98ef5312db78f84867c6075ab0 | https://github.com/birarda/logan/blob/c007081c7dbb5b98ef5312db78f84867c6075ab0/lib/logan/project.rb#L49-L54 | train |
birarda/logan | lib/logan/project.rb | Logan.Project.todolist | def todolist(list_id)
response = Logan::Client.get "/projects/#{@id}/todolists/#{list_id}.json"
Logan::TodoList.new response.parsed_response.merge({ :project_id => @id })
end | ruby | def todolist(list_id)
response = Logan::Client.get "/projects/#{@id}/todolists/#{list_id}.json"
Logan::TodoList.new response.parsed_response.merge({ :project_id => @id })
end | [
"def",
"todolist",
"(",
"list_id",
")",
"response",
"=",
"Logan",
"::",
"Client",
".",
"get",
"\"/projects/#{@id}/todolists/#{list_id}.json\"",
"Logan",
"::",
"TodoList",
".",
"new",
"response",
".",
"parsed_response",
".",
"merge",
"(",
"{",
":project_id",
"=>",
"@id",
"}",
")",
"end"
] | get an individual todo list for this project from Basecamp API
@param [String] list_id id for the todo list
@return [Logan::TodoList] todo list instance | [
"get",
"an",
"individual",
"todo",
"list",
"for",
"this",
"project",
"from",
"Basecamp",
"API"
] | c007081c7dbb5b98ef5312db78f84867c6075ab0 | https://github.com/birarda/logan/blob/c007081c7dbb5b98ef5312db78f84867c6075ab0/lib/logan/project.rb#L67-L70 | train |
birarda/logan | lib/logan/project.rb | Logan.Project.create_todolist | def create_todolist(todo_list)
post_params = {
:body => todo_list.post_json,
:headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'})
}
response = Logan::Client.post "/projects/#{@id}/todolists.json", post_params
Logan::TodoList.new response.merge({ :project_id => @id })
end | ruby | def create_todolist(todo_list)
post_params = {
:body => todo_list.post_json,
:headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'})
}
response = Logan::Client.post "/projects/#{@id}/todolists.json", post_params
Logan::TodoList.new response.merge({ :project_id => @id })
end | [
"def",
"create_todolist",
"(",
"todo_list",
")",
"post_params",
"=",
"{",
":body",
"=>",
"todo_list",
".",
"post_json",
",",
":headers",
"=>",
"Logan",
"::",
"Client",
".",
"headers",
".",
"merge",
"(",
"{",
"'Content-Type'",
"=>",
"'application/json'",
"}",
")",
"}",
"response",
"=",
"Logan",
"::",
"Client",
".",
"post",
"\"/projects/#{@id}/todolists.json\"",
",",
"post_params",
"Logan",
"::",
"TodoList",
".",
"new",
"response",
".",
"merge",
"(",
"{",
":project_id",
"=>",
"@id",
"}",
")",
"end"
] | create a todo list in this project via Basecamp API
@param [Logan::TodoList] todo_list todo list instance to be created
@return [Logan::TodoList] todo list instance from Basecamp API response | [
"create",
"a",
"todo",
"list",
"in",
"this",
"project",
"via",
"Basecamp",
"API"
] | c007081c7dbb5b98ef5312db78f84867c6075ab0 | https://github.com/birarda/logan/blob/c007081c7dbb5b98ef5312db78f84867c6075ab0/lib/logan/project.rb#L76-L84 | train |
birarda/logan | lib/logan/project.rb | Logan.Project.create_message | def create_message(subject, content, subscribers, private)
post_params = {
:body => {subject: subject, content: content, subscribers: subscribers, private: private}.to_json,
:headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'})
}
response = Logan::Client.post "/projects/#{@id}/messages.json", post_params
Logan::Project.new response
end | ruby | def create_message(subject, content, subscribers, private)
post_params = {
:body => {subject: subject, content: content, subscribers: subscribers, private: private}.to_json,
:headers => Logan::Client.headers.merge({'Content-Type' => 'application/json'})
}
response = Logan::Client.post "/projects/#{@id}/messages.json", post_params
Logan::Project.new response
end | [
"def",
"create_message",
"(",
"subject",
",",
"content",
",",
"subscribers",
",",
"private",
")",
"post_params",
"=",
"{",
":body",
"=>",
"{",
"subject",
":",
"subject",
",",
"content",
":",
"content",
",",
"subscribers",
":",
"subscribers",
",",
"private",
":",
"private",
"}",
".",
"to_json",
",",
":headers",
"=>",
"Logan",
"::",
"Client",
".",
"headers",
".",
"merge",
"(",
"{",
"'Content-Type'",
"=>",
"'application/json'",
"}",
")",
"}",
"response",
"=",
"Logan",
"::",
"Client",
".",
"post",
"\"/projects/#{@id}/messages.json\"",
",",
"post_params",
"Logan",
"::",
"Project",
".",
"new",
"response",
"end"
] | create a message via Basecamp API
@param [String] subject subject for the new message
@param [String] content content for the new message
@param [Array] subscribers array of subscriber ids for the new message
@param [Bool] private should the private flag be set for the new message
@return [Logan::Message] message instance from Basecamp API response | [
"create",
"a",
"message",
"via",
"Basecamp",
"API"
] | c007081c7dbb5b98ef5312db78f84867c6075ab0 | https://github.com/birarda/logan/blob/c007081c7dbb5b98ef5312db78f84867c6075ab0/lib/logan/project.rb#L134-L142 | train |
jarhart/rattler | lib/rattler/parsers/rule.rb | Rattler::Parsers.Rule.parse | def parse(scanner, rules, scope = ParserScope.empty)
catch(:rule_failed) do
return expr.parse(scanner, rules, scope)
end
false
end | ruby | def parse(scanner, rules, scope = ParserScope.empty)
catch(:rule_failed) do
return expr.parse(scanner, rules, scope)
end
false
end | [
"def",
"parse",
"(",
"scanner",
",",
"rules",
",",
"scope",
"=",
"ParserScope",
".",
"empty",
")",
"catch",
"(",
":rule_failed",
")",
"do",
"return",
"expr",
".",
"parse",
"(",
"scanner",
",",
"rules",
",",
"scope",
")",
"end",
"false",
"end"
] | Parse using the rule body and on success return the result, on failure
return a false value.
@param (see Match#parse)
@return (see Match#parse) | [
"Parse",
"using",
"the",
"rule",
"body",
"and",
"on",
"success",
"return",
"the",
"result",
"on",
"failure",
"return",
"a",
"false",
"value",
"."
] | 8b4efde2a05e9e790955bb635d4a1a9615893719 | https://github.com/jarhart/rattler/blob/8b4efde2a05e9e790955bb635d4a1a9615893719/lib/rattler/parsers/rule.rb#L26-L31 | train |
crashlog/crashlog | lib/crash_log/configuration.rb | CrashLog.Configuration.development_mode= | def development_mode=(flag)
self[:development_mode] = flag
self.level = Logger::DEBUG
if new_logger
new_logger.level = self.level if self.logger.respond_to?(:level=)
end
end | ruby | def development_mode=(flag)
self[:development_mode] = flag
self.level = Logger::DEBUG
if new_logger
new_logger.level = self.level if self.logger.respond_to?(:level=)
end
end | [
"def",
"development_mode",
"=",
"(",
"flag",
")",
"self",
"[",
":development_mode",
"]",
"=",
"flag",
"self",
".",
"level",
"=",
"Logger",
"::",
"DEBUG",
"if",
"new_logger",
"new_logger",
".",
"level",
"=",
"self",
".",
"level",
"if",
"self",
".",
"logger",
".",
"respond_to?",
"(",
":level=",
")",
"end",
"end"
] | Helps to enable debug logging when in development mode | [
"Helps",
"to",
"enable",
"debug",
"logging",
"when",
"in",
"development",
"mode"
] | a70a41b58ce53eb75b8ee0bed79ab421c7650ad4 | https://github.com/crashlog/crashlog/blob/a70a41b58ce53eb75b8ee0bed79ab421c7650ad4/lib/crash_log/configuration.rb#L241-L247 | train |
Burgestrand/mellon | lib/mellon/keychain.rb | Mellon.Keychain.[]= | def []=(key, data)
info, _ = read(key)
info ||= {}
if data
write(key, data, info)
else
delete(key, info)
end
end | ruby | def []=(key, data)
info, _ = read(key)
info ||= {}
if data
write(key, data, info)
else
delete(key, info)
end
end | [
"def",
"[]=",
"(",
"key",
",",
"data",
")",
"info",
",",
"_",
"=",
"read",
"(",
"key",
")",
"info",
"||=",
"{",
"}",
"if",
"data",
"write",
"(",
"key",
",",
"data",
",",
"info",
")",
"else",
"delete",
"(",
"key",
",",
"info",
")",
"end",
"end"
] | Write data to entry key, or updating existing one if it exists.
@param [String] key
@param [String] data | [
"Write",
"data",
"to",
"entry",
"key",
"or",
"updating",
"existing",
"one",
"if",
"it",
"exists",
"."
] | 4ded7e28fee192a777605e5f9dcd3b1bd05770ef | https://github.com/Burgestrand/mellon/blob/4ded7e28fee192a777605e5f9dcd3b1bd05770ef/lib/mellon/keychain.rb#L95-L104 | train |
Burgestrand/mellon | lib/mellon/keychain.rb | Mellon.Keychain.read | def read(key)
command "find-generic-password", "-g", "-l", key do |info, password_info|
[Utils.parse_info(info), Utils.parse_contents(password_info)]
end
rescue CommandError => e
raise unless e.message =~ ENTRY_MISSING
nil
end | ruby | def read(key)
command "find-generic-password", "-g", "-l", key do |info, password_info|
[Utils.parse_info(info), Utils.parse_contents(password_info)]
end
rescue CommandError => e
raise unless e.message =~ ENTRY_MISSING
nil
end | [
"def",
"read",
"(",
"key",
")",
"command",
"\"find-generic-password\"",
",",
"\"-g\"",
",",
"\"-l\"",
",",
"key",
"do",
"|",
"info",
",",
"password_info",
"|",
"[",
"Utils",
".",
"parse_info",
"(",
"info",
")",
",",
"Utils",
".",
"parse_contents",
"(",
"password_info",
")",
"]",
"end",
"rescue",
"CommandError",
"=>",
"e",
"raise",
"unless",
"e",
".",
"message",
"=~",
"ENTRY_MISSING",
"nil",
"end"
] | Read a key from the keychain.
@param [String] key
@return [Array<Hash, String>, nil] tuple of entry info, and text contents, or nil if key does not exist | [
"Read",
"a",
"key",
"from",
"the",
"keychain",
"."
] | 4ded7e28fee192a777605e5f9dcd3b1bd05770ef | https://github.com/Burgestrand/mellon/blob/4ded7e28fee192a777605e5f9dcd3b1bd05770ef/lib/mellon/keychain.rb#L142-L149 | train |
Burgestrand/mellon | lib/mellon/keychain.rb | Mellon.Keychain.write | def write(key, data, options = {})
info = Utils.build_info(key, options)
command "add-generic-password",
"-a", info[:account_name],
"-s", info[:service_name],
"-l", info[:label],
"-D", info[:kind],
"-C", info[:type],
"-T", "", # which applications have access (none)
"-U", # upsert
"-w", data
end | ruby | def write(key, data, options = {})
info = Utils.build_info(key, options)
command "add-generic-password",
"-a", info[:account_name],
"-s", info[:service_name],
"-l", info[:label],
"-D", info[:kind],
"-C", info[:type],
"-T", "", # which applications have access (none)
"-U", # upsert
"-w", data
end | [
"def",
"write",
"(",
"key",
",",
"data",
",",
"options",
"=",
"{",
"}",
")",
"info",
"=",
"Utils",
".",
"build_info",
"(",
"key",
",",
"options",
")",
"command",
"\"add-generic-password\"",
",",
"\"-a\"",
",",
"info",
"[",
":account_name",
"]",
",",
"\"-s\"",
",",
"info",
"[",
":service_name",
"]",
",",
"\"-l\"",
",",
"info",
"[",
":label",
"]",
",",
"\"-D\"",
",",
"info",
"[",
":kind",
"]",
",",
"\"-C\"",
",",
"info",
"[",
":type",
"]",
",",
"\"-T\"",
",",
"\"\"",
",",
"\"-U\"",
",",
"\"-w\"",
",",
"data",
"end"
] | Write data with given key to the keychain, or update existing key if it exists.
@note keychain entries are not unique by key, but also by the information
provided through options; two entries with same key but different
account name (for example), will become two different entries when
writing.
@param [String] key
@param [String] data
@param [Hash] options
@option options [#to_s] :type (:note) one of Mellon::TYPES
@option options [String] :account_name ("")
@option options [String] :service_name (key)
@option options [String] :label (service_name)
@raise [CommandError] if writing fails | [
"Write",
"data",
"with",
"given",
"key",
"to",
"the",
"keychain",
"or",
"update",
"existing",
"key",
"if",
"it",
"exists",
"."
] | 4ded7e28fee192a777605e5f9dcd3b1bd05770ef | https://github.com/Burgestrand/mellon/blob/4ded7e28fee192a777605e5f9dcd3b1bd05770ef/lib/mellon/keychain.rb#L166-L178 | train |
Burgestrand/mellon | lib/mellon/keychain.rb | Mellon.Keychain.delete | def delete(key, options = {})
info = Utils.build_info(key, options)
command "delete-generic-password",
"-a", info[:account_name],
"-s", info[:service_name],
"-l", info[:label],
"-D", info[:kind],
"-C", info[:type]
end | ruby | def delete(key, options = {})
info = Utils.build_info(key, options)
command "delete-generic-password",
"-a", info[:account_name],
"-s", info[:service_name],
"-l", info[:label],
"-D", info[:kind],
"-C", info[:type]
end | [
"def",
"delete",
"(",
"key",
",",
"options",
"=",
"{",
"}",
")",
"info",
"=",
"Utils",
".",
"build_info",
"(",
"key",
",",
"options",
")",
"command",
"\"delete-generic-password\"",
",",
"\"-a\"",
",",
"info",
"[",
":account_name",
"]",
",",
"\"-s\"",
",",
"info",
"[",
":service_name",
"]",
",",
"\"-l\"",
",",
"info",
"[",
":label",
"]",
",",
"\"-D\"",
",",
"info",
"[",
":kind",
"]",
",",
"\"-C\"",
",",
"info",
"[",
":type",
"]",
"end"
] | Delete the entry matching key and options.
@param [String] key
@param [Hash] options
@option (see #write) | [
"Delete",
"the",
"entry",
"matching",
"key",
"and",
"options",
"."
] | 4ded7e28fee192a777605e5f9dcd3b1bd05770ef | https://github.com/Burgestrand/mellon/blob/4ded7e28fee192a777605e5f9dcd3b1bd05770ef/lib/mellon/keychain.rb#L185-L194 | train |
coreyward/typekit | lib/typekit/family.rb | Typekit.Family.variation | def variation(id)
variations.select { |v| v.id.split(':').last == id }.first
end | ruby | def variation(id)
variations.select { |v| v.id.split(':').last == id }.first
end | [
"def",
"variation",
"(",
"id",
")",
"variations",
".",
"select",
"{",
"|",
"v",
"|",
"v",
".",
"id",
".",
"split",
"(",
"':'",
")",
".",
"last",
"==",
"id",
"}",
".",
"first",
"end"
] | Find a variation in this Family by the Font Variation Description
@param id [String] Family/Font variation ID/Description (e.g. n4 or i7) | [
"Find",
"a",
"variation",
"in",
"this",
"Family",
"by",
"the",
"Font",
"Variation",
"Description"
] | 1e9f3749ad6066eec7fbdad50abe2ab5802e32d0 | https://github.com/coreyward/typekit/blob/1e9f3749ad6066eec7fbdad50abe2ab5802e32d0/lib/typekit/family.rb#L10-L12 | train |
einzige/framework | lib/framework/application.rb | Framework.Application.load_application_files | def load_application_files
if %w(development test).include?(env.to_s)
config['autoload_paths'].each(&method(:autoreload_constants))
autoreload_yml
end
config['autoload_paths'].each(&method(:require_dependencies))
end | ruby | def load_application_files
if %w(development test).include?(env.to_s)
config['autoload_paths'].each(&method(:autoreload_constants))
autoreload_yml
end
config['autoload_paths'].each(&method(:require_dependencies))
end | [
"def",
"load_application_files",
"if",
"%w(",
"development",
"test",
")",
".",
"include?",
"(",
"env",
".",
"to_s",
")",
"config",
"[",
"'autoload_paths'",
"]",
".",
"each",
"(",
"&",
"method",
"(",
":autoreload_constants",
")",
")",
"autoreload_yml",
"end",
"config",
"[",
"'autoload_paths'",
"]",
".",
"each",
"(",
"&",
"method",
"(",
":require_dependencies",
")",
")",
"end"
] | Autoloads all app-specific files | [
"Autoloads",
"all",
"app",
"-",
"specific",
"files"
] | 5a8a2255265118aa244cdabac29fd1ce7f885118 | https://github.com/einzige/framework/blob/5a8a2255265118aa244cdabac29fd1ce7f885118/lib/framework/application.rb#L121-L127 | train |
spoved/ruby-comicvine-api | lib/comicvine/resource.rb | ComicVine.Resource.fetch! | def fetch!
obj = ComicVine::API.get_details_by_url(self.api_detail_url)
self.methods.each do |m|
# Look for methods that can be set (i.e. ends with a =)
if m.to_s =~ /^(?!_)([\w\d\_]+)=$/
# Save our method symbols in a more readable fashion
get_m = $1.to_sym
set_m = m
# Skip setting ids, as this should be handled by the classes when setting the children objects if needed
next if get_m.to_s =~ /\_ids?$/ || set_m.to_s =~ /attributes/
# Verify the new object has a get method and it is not nil or empty
if self.respond_to?(set_m) && obj.respond_to?(get_m) && !obj.method(get_m).call.nil?
# Now set the method to the new value
self.method(set_m).call obj.method(get_m).call
end
end
end
self
end | ruby | def fetch!
obj = ComicVine::API.get_details_by_url(self.api_detail_url)
self.methods.each do |m|
# Look for methods that can be set (i.e. ends with a =)
if m.to_s =~ /^(?!_)([\w\d\_]+)=$/
# Save our method symbols in a more readable fashion
get_m = $1.to_sym
set_m = m
# Skip setting ids, as this should be handled by the classes when setting the children objects if needed
next if get_m.to_s =~ /\_ids?$/ || set_m.to_s =~ /attributes/
# Verify the new object has a get method and it is not nil or empty
if self.respond_to?(set_m) && obj.respond_to?(get_m) && !obj.method(get_m).call.nil?
# Now set the method to the new value
self.method(set_m).call obj.method(get_m).call
end
end
end
self
end | [
"def",
"fetch!",
"obj",
"=",
"ComicVine",
"::",
"API",
".",
"get_details_by_url",
"(",
"self",
".",
"api_detail_url",
")",
"self",
".",
"methods",
".",
"each",
"do",
"|",
"m",
"|",
"if",
"m",
".",
"to_s",
"=~",
"/",
"\\w",
"\\d",
"\\_",
"/",
"get_m",
"=",
"$1",
".",
"to_sym",
"set_m",
"=",
"m",
"next",
"if",
"get_m",
".",
"to_s",
"=~",
"/",
"\\_",
"/",
"||",
"set_m",
".",
"to_s",
"=~",
"/",
"/",
"if",
"self",
".",
"respond_to?",
"(",
"set_m",
")",
"&&",
"obj",
".",
"respond_to?",
"(",
"get_m",
")",
"&&",
"!",
"obj",
".",
"method",
"(",
"get_m",
")",
".",
"call",
".",
"nil?",
"self",
".",
"method",
"(",
"set_m",
")",
".",
"call",
"obj",
".",
"method",
"(",
"get_m",
")",
".",
"call",
"end",
"end",
"end",
"self",
"end"
] | Fetches data from ComicVine based on objects api_detail_url and updates self with new values
@return [ComicVine::Resource]
@since 0.1.2 | [
"Fetches",
"data",
"from",
"ComicVine",
"based",
"on",
"objects",
"api_detail_url",
"and",
"updates",
"self",
"with",
"new",
"values"
] | 08c993487ce4a513529d11a2e86f69e6f8d53bb3 | https://github.com/spoved/ruby-comicvine-api/blob/08c993487ce4a513529d11a2e86f69e6f8d53bb3/lib/comicvine/resource.rb#L41-L61 | train |
simplelogica/pluckers | lib/pluckers/base.rb | Pluckers.Base.configure_query | def configure_query
@query_to_pluck = @records
@attributes_to_pluck = [{ name: @query_to_pluck.primary_key.to_sym, sql: "\"#{@query_to_pluck.table_name}\".#{@query_to_pluck.primary_key}" }]
@results = {}
@klass_reflections = @query_to_pluck.reflections.with_indifferent_access
pluck_reflections = @options[:reflections] || {}
# Validate that all relations exists in the model
if (missing_reflections = pluck_reflections.symbolize_keys.keys - @klass_reflections.symbolize_keys.keys).any?
raise ArgumentError.new("Plucker reflections '#{missing_reflections.to_sentence}', are missing in #{@records.klass}")
end
end | ruby | def configure_query
@query_to_pluck = @records
@attributes_to_pluck = [{ name: @query_to_pluck.primary_key.to_sym, sql: "\"#{@query_to_pluck.table_name}\".#{@query_to_pluck.primary_key}" }]
@results = {}
@klass_reflections = @query_to_pluck.reflections.with_indifferent_access
pluck_reflections = @options[:reflections] || {}
# Validate that all relations exists in the model
if (missing_reflections = pluck_reflections.symbolize_keys.keys - @klass_reflections.symbolize_keys.keys).any?
raise ArgumentError.new("Plucker reflections '#{missing_reflections.to_sentence}', are missing in #{@records.klass}")
end
end | [
"def",
"configure_query",
"@query_to_pluck",
"=",
"@records",
"@attributes_to_pluck",
"=",
"[",
"{",
"name",
":",
"@query_to_pluck",
".",
"primary_key",
".",
"to_sym",
",",
"sql",
":",
"\"\\\"#{@query_to_pluck.table_name}\\\".#{@query_to_pluck.primary_key}\"",
"}",
"]",
"@results",
"=",
"{",
"}",
"@klass_reflections",
"=",
"@query_to_pluck",
".",
"reflections",
".",
"with_indifferent_access",
"pluck_reflections",
"=",
"@options",
"[",
":reflections",
"]",
"||",
"{",
"}",
"if",
"(",
"missing_reflections",
"=",
"pluck_reflections",
".",
"symbolize_keys",
".",
"keys",
"-",
"@klass_reflections",
".",
"symbolize_keys",
".",
"keys",
")",
".",
"any?",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"Plucker reflections '#{missing_reflections.to_sentence}', are missing in #{@records.klass}\"",
")",
"end",
"end"
] | In this base implementation we just reset all the query information.
Features and subclasses must redefine this method if they are interested
in adding some behaviour. | [
"In",
"this",
"base",
"implementation",
"we",
"just",
"reset",
"all",
"the",
"query",
"information",
".",
"Features",
"and",
"subclasses",
"must",
"redefine",
"this",
"method",
"if",
"they",
"are",
"interested",
"in",
"adding",
"some",
"behaviour",
"."
] | 73fabd5ba058722bac2950efa5549f417e435651 | https://github.com/simplelogica/pluckers/blob/73fabd5ba058722bac2950efa5549f417e435651/lib/pluckers/base.rb#L107-L119 | train |
simplelogica/pluckers | lib/pluckers/base.rb | Pluckers.Base.build_results | def build_results
# Now we uinq the attributes
@attributes_to_pluck.uniq!{|f| f[:name] }
# Obtain both the names and SQL columns
names_to_pluck = @attributes_to_pluck.map{|f| f[:name] }
sql_to_pluck = @attributes_to_pluck.map{|f| f[:sql] }
# And perform the real ActiveRecord pluck.
pluck_records(sql_to_pluck).each_with_index do |record, index|
# After the pluck we have to create the hash for each record.
# If there's only a field we will not receive an array. But we need it
# so we built it.
record = [record] unless record.is_a? Array
# Now we zip it with the attribute names and create a hash. If we have
# have a record: [1, "Test title 1", "Test text 1"] and the
# names_to_pluck are [:id, :title, :text] we will end with {:id=>1,
# :title=>"Test title 1", :text=>"Test text 1"}
attributes_to_return = Hash[names_to_pluck.zip(record)]
# Now we store it in the results hash
@results[attributes_to_return[:id]] = attributes_to_return
end
end | ruby | def build_results
# Now we uinq the attributes
@attributes_to_pluck.uniq!{|f| f[:name] }
# Obtain both the names and SQL columns
names_to_pluck = @attributes_to_pluck.map{|f| f[:name] }
sql_to_pluck = @attributes_to_pluck.map{|f| f[:sql] }
# And perform the real ActiveRecord pluck.
pluck_records(sql_to_pluck).each_with_index do |record, index|
# After the pluck we have to create the hash for each record.
# If there's only a field we will not receive an array. But we need it
# so we built it.
record = [record] unless record.is_a? Array
# Now we zip it with the attribute names and create a hash. If we have
# have a record: [1, "Test title 1", "Test text 1"] and the
# names_to_pluck are [:id, :title, :text] we will end with {:id=>1,
# :title=>"Test title 1", :text=>"Test text 1"}
attributes_to_return = Hash[names_to_pluck.zip(record)]
# Now we store it in the results hash
@results[attributes_to_return[:id]] = attributes_to_return
end
end | [
"def",
"build_results",
"@attributes_to_pluck",
".",
"uniq!",
"{",
"|",
"f",
"|",
"f",
"[",
":name",
"]",
"}",
"names_to_pluck",
"=",
"@attributes_to_pluck",
".",
"map",
"{",
"|",
"f",
"|",
"f",
"[",
":name",
"]",
"}",
"sql_to_pluck",
"=",
"@attributes_to_pluck",
".",
"map",
"{",
"|",
"f",
"|",
"f",
"[",
":sql",
"]",
"}",
"pluck_records",
"(",
"sql_to_pluck",
")",
".",
"each_with_index",
"do",
"|",
"record",
",",
"index",
"|",
"record",
"=",
"[",
"record",
"]",
"unless",
"record",
".",
"is_a?",
"Array",
"attributes_to_return",
"=",
"Hash",
"[",
"names_to_pluck",
".",
"zip",
"(",
"record",
")",
"]",
"@results",
"[",
"attributes_to_return",
"[",
":id",
"]",
"]",
"=",
"attributes_to_return",
"end",
"end"
] | In this base implementation we perform the real pluck execution.
The method collects all the attributes and columns to pluck and add it
to the results array. | [
"In",
"this",
"base",
"implementation",
"we",
"perform",
"the",
"real",
"pluck",
"execution",
"."
] | 73fabd5ba058722bac2950efa5549f417e435651 | https://github.com/simplelogica/pluckers/blob/73fabd5ba058722bac2950efa5549f417e435651/lib/pluckers/base.rb#L126-L152 | train |
jemmyw/bisques | lib/bisques/aws_request_authorization.rb | Bisques.AwsRequestAuthorization.signing_key | def signing_key
digest = "SHA256"
kDate = OpenSSL::HMAC.digest(digest, "AWS4" + credentials.aws_secret, request_datestamp)
kRegion = OpenSSL::HMAC.digest(digest, kDate, region)
kService = OpenSSL::HMAC.digest(digest, kRegion, service)
OpenSSL::HMAC.digest(digest, kService, "aws4_request")
end | ruby | def signing_key
digest = "SHA256"
kDate = OpenSSL::HMAC.digest(digest, "AWS4" + credentials.aws_secret, request_datestamp)
kRegion = OpenSSL::HMAC.digest(digest, kDate, region)
kService = OpenSSL::HMAC.digest(digest, kRegion, service)
OpenSSL::HMAC.digest(digest, kService, "aws4_request")
end | [
"def",
"signing_key",
"digest",
"=",
"\"SHA256\"",
"kDate",
"=",
"OpenSSL",
"::",
"HMAC",
".",
"digest",
"(",
"digest",
",",
"\"AWS4\"",
"+",
"credentials",
".",
"aws_secret",
",",
"request_datestamp",
")",
"kRegion",
"=",
"OpenSSL",
"::",
"HMAC",
".",
"digest",
"(",
"digest",
",",
"kDate",
",",
"region",
")",
"kService",
"=",
"OpenSSL",
"::",
"HMAC",
".",
"digest",
"(",
"digest",
",",
"kRegion",
",",
"service",
")",
"OpenSSL",
"::",
"HMAC",
".",
"digest",
"(",
"digest",
",",
"kService",
",",
"\"aws4_request\"",
")",
"end"
] | Calculate the signing key for task 3. | [
"Calculate",
"the",
"signing",
"key",
"for",
"task",
"3",
"."
] | c48ab555f07664752bcbf9e8deb99bd75cbdc41b | https://github.com/jemmyw/bisques/blob/c48ab555f07664752bcbf9e8deb99bd75cbdc41b/lib/bisques/aws_request_authorization.rb#L103-L109 | train |
jemmyw/bisques | lib/bisques/aws_request_authorization.rb | Bisques.AwsRequestAuthorization.canonical_headers | def canonical_headers
hash = headers.dup
hash["host"] ||= Addressable::URI.parse(url).host
hash = hash.map{|name,value| [name.downcase,value]}
hash.reject!{|name,value| name == "authorization"}
hash.sort
end | ruby | def canonical_headers
hash = headers.dup
hash["host"] ||= Addressable::URI.parse(url).host
hash = hash.map{|name,value| [name.downcase,value]}
hash.reject!{|name,value| name == "authorization"}
hash.sort
end | [
"def",
"canonical_headers",
"hash",
"=",
"headers",
".",
"dup",
"hash",
"[",
"\"host\"",
"]",
"||=",
"Addressable",
"::",
"URI",
".",
"parse",
"(",
"url",
")",
".",
"host",
"hash",
"=",
"hash",
".",
"map",
"{",
"|",
"name",
",",
"value",
"|",
"[",
"name",
".",
"downcase",
",",
"value",
"]",
"}",
"hash",
".",
"reject!",
"{",
"|",
"name",
",",
"value",
"|",
"name",
"==",
"\"authorization\"",
"}",
"hash",
".",
"sort",
"end"
] | The canonical headers, including the Host. | [
"The",
"canonical",
"headers",
"including",
"the",
"Host",
"."
] | c48ab555f07664752bcbf9e8deb99bd75cbdc41b | https://github.com/jemmyw/bisques/blob/c48ab555f07664752bcbf9e8deb99bd75cbdc41b/lib/bisques/aws_request_authorization.rb#L162-L168 | train |
layerhq/migration_bundler | lib/migration_bundler/actions.rb | MigrationBundler.Actions.git | def git(commands={})
if commands.is_a?(Symbol)
run "git #{commands}"
else
commands.each do |cmd, options|
run "git #{cmd} #{options}"
end
end
end | ruby | def git(commands={})
if commands.is_a?(Symbol)
run "git #{commands}"
else
commands.each do |cmd, options|
run "git #{cmd} #{options}"
end
end
end | [
"def",
"git",
"(",
"commands",
"=",
"{",
"}",
")",
"if",
"commands",
".",
"is_a?",
"(",
"Symbol",
")",
"run",
"\"git #{commands}\"",
"else",
"commands",
".",
"each",
"do",
"|",
"cmd",
",",
"options",
"|",
"run",
"\"git #{cmd} #{options}\"",
"end",
"end",
"end"
] | Run a command in git.
git :init
git add: "this.file that.rb"
git add: "onefile.rb", rm: "badfile.cxx" | [
"Run",
"a",
"command",
"in",
"git",
"."
] | de7a3345daccd3a9fe47da818742812944c8daa4 | https://github.com/layerhq/migration_bundler/blob/de7a3345daccd3a9fe47da818742812944c8daa4/lib/migration_bundler/actions.rb#L8-L16 | train |
m-31/puppetdb_query | lib/puppetdb_query/puppetdb.rb | PuppetDBQuery.PuppetDB.node_properties | def node_properties
result = {}
api_nodes.each do |data|
next if data['deactivated']
# in '/v3/nodes' we must take 'name'
name = data['certname']
values = data.dup
%w[deactivated certname].each { |key| values.delete(key) }
result[name] = values
end
result
end | ruby | def node_properties
result = {}
api_nodes.each do |data|
next if data['deactivated']
# in '/v3/nodes' we must take 'name'
name = data['certname']
values = data.dup
%w[deactivated certname].each { |key| values.delete(key) }
result[name] = values
end
result
end | [
"def",
"node_properties",
"result",
"=",
"{",
"}",
"api_nodes",
".",
"each",
"do",
"|",
"data",
"|",
"next",
"if",
"data",
"[",
"'deactivated'",
"]",
"name",
"=",
"data",
"[",
"'certname'",
"]",
"values",
"=",
"data",
".",
"dup",
"%w[",
"deactivated",
"certname",
"]",
".",
"each",
"{",
"|",
"key",
"|",
"values",
".",
"delete",
"(",
"key",
")",
"}",
"result",
"[",
"name",
"]",
"=",
"values",
"end",
"result",
"end"
] | get hash of node update properties | [
"get",
"hash",
"of",
"node",
"update",
"properties"
] | 58103c91f291de8ce28d679256e50ae391b93ecb | https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/puppetdb.rb#L26-L37 | train |
m-31/puppetdb_query | lib/puppetdb_query/puppetdb.rb | PuppetDBQuery.PuppetDB.nodes_update_facts_since | def nodes_update_facts_since(timestamp)
ts = (timestamp.is_a?(String) ? Time.iso8601(ts) : timestamp)
node_properties.delete_if do |_k, data|
# in '/v3/nodes' we must take 'facts-timestamp'
!data["facts_timestamp"] || Time.iso8601(data["facts_timestamp"]) < ts
end.keys
end | ruby | def nodes_update_facts_since(timestamp)
ts = (timestamp.is_a?(String) ? Time.iso8601(ts) : timestamp)
node_properties.delete_if do |_k, data|
# in '/v3/nodes' we must take 'facts-timestamp'
!data["facts_timestamp"] || Time.iso8601(data["facts_timestamp"]) < ts
end.keys
end | [
"def",
"nodes_update_facts_since",
"(",
"timestamp",
")",
"ts",
"=",
"(",
"timestamp",
".",
"is_a?",
"(",
"String",
")",
"?",
"Time",
".",
"iso8601",
"(",
"ts",
")",
":",
"timestamp",
")",
"node_properties",
".",
"delete_if",
"do",
"|",
"_k",
",",
"data",
"|",
"!",
"data",
"[",
"\"facts_timestamp\"",
"]",
"||",
"Time",
".",
"iso8601",
"(",
"data",
"[",
"\"facts_timestamp\"",
"]",
")",
"<",
"ts",
"end",
".",
"keys",
"end"
] | get all nodes that have updated facts | [
"get",
"all",
"nodes",
"that",
"have",
"updated",
"facts"
] | 58103c91f291de8ce28d679256e50ae391b93ecb | https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/puppetdb.rb#L40-L46 | train |
m-31/puppetdb_query | lib/puppetdb_query/puppetdb.rb | PuppetDBQuery.PuppetDB.single_node_facts | def single_node_facts(node)
json = get_json("#{@nodes_url}/#{node}/facts", 10)
return nil if json.include?("error")
Hash[json.map { |data| [data["name"], data["value"]] }]
end | ruby | def single_node_facts(node)
json = get_json("#{@nodes_url}/#{node}/facts", 10)
return nil if json.include?("error")
Hash[json.map { |data| [data["name"], data["value"]] }]
end | [
"def",
"single_node_facts",
"(",
"node",
")",
"json",
"=",
"get_json",
"(",
"\"#{@nodes_url}/#{node}/facts\"",
",",
"10",
")",
"return",
"nil",
"if",
"json",
".",
"include?",
"(",
"\"error\"",
")",
"Hash",
"[",
"json",
".",
"map",
"{",
"|",
"data",
"|",
"[",
"data",
"[",
"\"name\"",
"]",
",",
"data",
"[",
"\"value\"",
"]",
"]",
"}",
"]",
"end"
] | get hash of facts for given node name | [
"get",
"hash",
"of",
"facts",
"for",
"given",
"node",
"name"
] | 58103c91f291de8ce28d679256e50ae391b93ecb | https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/puppetdb.rb#L49-L53 | train |
m-31/puppetdb_query | lib/puppetdb_query/puppetdb.rb | PuppetDBQuery.PuppetDB.facts | def facts
json = get_json(@facts_url, 60)
result = {}
json.each do |fact|
data = result[fact["certname"]]
result[fact["certname"]] = data = {} unless data
data[fact["name"]] = fact["value"]
end
result
end | ruby | def facts
json = get_json(@facts_url, 60)
result = {}
json.each do |fact|
data = result[fact["certname"]]
result[fact["certname"]] = data = {} unless data
data[fact["name"]] = fact["value"]
end
result
end | [
"def",
"facts",
"json",
"=",
"get_json",
"(",
"@facts_url",
",",
"60",
")",
"result",
"=",
"{",
"}",
"json",
".",
"each",
"do",
"|",
"fact",
"|",
"data",
"=",
"result",
"[",
"fact",
"[",
"\"certname\"",
"]",
"]",
"result",
"[",
"fact",
"[",
"\"certname\"",
"]",
"]",
"=",
"data",
"=",
"{",
"}",
"unless",
"data",
"data",
"[",
"fact",
"[",
"\"name\"",
"]",
"]",
"=",
"fact",
"[",
"\"value\"",
"]",
"end",
"result",
"end"
] | get all nodes with all facts | [
"get",
"all",
"nodes",
"with",
"all",
"facts"
] | 58103c91f291de8ce28d679256e50ae391b93ecb | https://github.com/m-31/puppetdb_query/blob/58103c91f291de8ce28d679256e50ae391b93ecb/lib/puppetdb_query/puppetdb.rb#L56-L65 | train |
bmizerany/swirl | lib/swirl/aws.rb | Swirl.AWS.call | def call(action, query={}, &blk)
call!(action, expand(query)) do |code, data|
case code
when 200
response = compact(data)
when 400...500
messages = if data["Response"]
Array(data["Response"]["Errors"]).map {|_, e| e["Message"] }
elsif data["ErrorResponse"]
Array(data["ErrorResponse"]["Error"]["Code"])
end
raise InvalidRequest, messages.join(",")
else
msg = "unexpected response #{code} -> #{data.inspect}"
raise InvalidRequest, msg
end
if blk
blk.call(response)
else
response
end
end
end | ruby | def call(action, query={}, &blk)
call!(action, expand(query)) do |code, data|
case code
when 200
response = compact(data)
when 400...500
messages = if data["Response"]
Array(data["Response"]["Errors"]).map {|_, e| e["Message"] }
elsif data["ErrorResponse"]
Array(data["ErrorResponse"]["Error"]["Code"])
end
raise InvalidRequest, messages.join(",")
else
msg = "unexpected response #{code} -> #{data.inspect}"
raise InvalidRequest, msg
end
if blk
blk.call(response)
else
response
end
end
end | [
"def",
"call",
"(",
"action",
",",
"query",
"=",
"{",
"}",
",",
"&",
"blk",
")",
"call!",
"(",
"action",
",",
"expand",
"(",
"query",
")",
")",
"do",
"|",
"code",
",",
"data",
"|",
"case",
"code",
"when",
"200",
"response",
"=",
"compact",
"(",
"data",
")",
"when",
"400",
"...",
"500",
"messages",
"=",
"if",
"data",
"[",
"\"Response\"",
"]",
"Array",
"(",
"data",
"[",
"\"Response\"",
"]",
"[",
"\"Errors\"",
"]",
")",
".",
"map",
"{",
"|",
"_",
",",
"e",
"|",
"e",
"[",
"\"Message\"",
"]",
"}",
"elsif",
"data",
"[",
"\"ErrorResponse\"",
"]",
"Array",
"(",
"data",
"[",
"\"ErrorResponse\"",
"]",
"[",
"\"Error\"",
"]",
"[",
"\"Code\"",
"]",
")",
"end",
"raise",
"InvalidRequest",
",",
"messages",
".",
"join",
"(",
"\",\"",
")",
"else",
"msg",
"=",
"\"unexpected response #{code} -> #{data.inspect}\"",
"raise",
"InvalidRequest",
",",
"msg",
"end",
"if",
"blk",
"blk",
".",
"call",
"(",
"response",
")",
"else",
"response",
"end",
"end",
"end"
] | Execute an EC2 command, expand the input,
and compact the output
Examples:
ec2.call("DescribeInstances")
ec2.call("TerminateInstances", "InstanceId" => ["i-1234", "i-993j"] | [
"Execute",
"an",
"EC2",
"command",
"expand",
"the",
"input",
"and",
"compact",
"the",
"output"
] | e3fe63a7067329fb95752d96e50332af386c776b | https://github.com/bmizerany/swirl/blob/e3fe63a7067329fb95752d96e50332af386c776b/lib/swirl/aws.rb#L95-L118 | train |
roja/words | lib/wordnet_connectors/pure_wordnet_connection.rb | Words.PureWordnetConnection.open! | def open!
raise BadWordnetDataset, "Failed to locate the wordnet database. Please ensure it is installed and that if it resides at a custom path that path is given as an argument when constructing the Words object." if @wordnet_path.nil?
@connected = true
# try and open evocations too
evocation_path = @data_path + 'evocations.dmp'
File.open(evocation_path, 'r') do |file|
@evocations = Marshal.load file.read
end if evocation_path.exist?
return nil
end | ruby | def open!
raise BadWordnetDataset, "Failed to locate the wordnet database. Please ensure it is installed and that if it resides at a custom path that path is given as an argument when constructing the Words object." if @wordnet_path.nil?
@connected = true
# try and open evocations too
evocation_path = @data_path + 'evocations.dmp'
File.open(evocation_path, 'r') do |file|
@evocations = Marshal.load file.read
end if evocation_path.exist?
return nil
end | [
"def",
"open!",
"raise",
"BadWordnetDataset",
",",
"\"Failed to locate the wordnet database. Please ensure it is installed and that if it resides at a custom path that path is given as an argument when constructing the Words object.\"",
"if",
"@wordnet_path",
".",
"nil?",
"@connected",
"=",
"true",
"evocation_path",
"=",
"@data_path",
"+",
"'evocations.dmp'",
"File",
".",
"open",
"(",
"evocation_path",
",",
"'r'",
")",
"do",
"|",
"file",
"|",
"@evocations",
"=",
"Marshal",
".",
"load",
"file",
".",
"read",
"end",
"if",
"evocation_path",
".",
"exist?",
"return",
"nil",
"end"
] | Constructs a new pure ruby connector for use with the words wordnet class.
@param [Pathname] data_path Specifies the directory within which constructed datasets can be found (evocations etc...)
@param [Pathname] wordnet_path Specifies the directory within which the wordnet dictionary can be found.
@return [PureWordnetConnection] A new wordnet connection.
@raise [BadWordnetConnector] If an invalid connector type is provided.
Causes the connection specified within the wordnet object to be reopened if currently closed.
@raise [BadWordnetConnector] If an invalid connector type is provided. | [
"Constructs",
"a",
"new",
"pure",
"ruby",
"connector",
"for",
"use",
"with",
"the",
"words",
"wordnet",
"class",
"."
] | 4d6302e7218533fcc2afb4cd993686dd56fe2cde | https://github.com/roja/words/blob/4d6302e7218533fcc2afb4cd993686dd56fe2cde/lib/wordnet_connectors/pure_wordnet_connection.rb#L64-L77 | train |
roja/words | lib/wordnet_connectors/pure_wordnet_connection.rb | Words.PureWordnetConnection.homographs | def homographs(term, use_cache = true)
raise NoWordnetConnection, "There is presently no connection to wordnet. To attempt to reistablish a connection you should use the 'open!' command on the Wordnet object." unless connected?
# Ensure that the term is either in the cache. If not, locate and add it if possable.
cache_ensure_from_wordnet(term, use_cache)
# We should either have the word in cache now or nowt... we should now change that into homograph input format (we do this here to improve performance during the cacheing performed above)
cached_entry_to_homograph_hash(term)
end | ruby | def homographs(term, use_cache = true)
raise NoWordnetConnection, "There is presently no connection to wordnet. To attempt to reistablish a connection you should use the 'open!' command on the Wordnet object." unless connected?
# Ensure that the term is either in the cache. If not, locate and add it if possable.
cache_ensure_from_wordnet(term, use_cache)
# We should either have the word in cache now or nowt... we should now change that into homograph input format (we do this here to improve performance during the cacheing performed above)
cached_entry_to_homograph_hash(term)
end | [
"def",
"homographs",
"(",
"term",
",",
"use_cache",
"=",
"true",
")",
"raise",
"NoWordnetConnection",
",",
"\"There is presently no connection to wordnet. To attempt to reistablish a connection you should use the 'open!' command on the Wordnet object.\"",
"unless",
"connected?",
"cache_ensure_from_wordnet",
"(",
"term",
",",
"use_cache",
")",
"cached_entry_to_homograph_hash",
"(",
"term",
")",
"end"
] | Locates from a term any relevent homographs and constructs a homographs hash.
@param [String] term The specific term that is desired from within wordnet.
@param [true, false] use_cache Specify whether to use caching when finding and retreving terms.
@result [Hash, nil] A hash in the format { 'lemma' => ..., 'tagsense_counts' => ..., 'synset_ids' => ... }, or nil if no homographs are available.
@raise [NoWordnetConnection] If there is currently no wordnet connection. | [
"Locates",
"from",
"a",
"term",
"any",
"relevent",
"homographs",
"and",
"constructs",
"a",
"homographs",
"hash",
"."
] | 4d6302e7218533fcc2afb4cd993686dd56fe2cde | https://github.com/roja/words/blob/4d6302e7218533fcc2afb4cd993686dd56fe2cde/lib/wordnet_connectors/pure_wordnet_connection.rb#L94-L104 | train |
roja/words | lib/wordnet_connectors/pure_wordnet_connection.rb | Words.PureWordnetConnection.synset | def synset(synset_id)
raise NoWordnetConnection, "There is presently no connection to wordnet. To attempt to reistablish a connection you should use the 'open!' command on the Wordnet object." unless connected?
pos = synset_id[0,1]
File.open(@wordnet_path + "data.#{SHORT_TO_POS_FILE_TYPE[pos]}","r") do |file|
file.seek(synset_id[1..-1].to_i)
data_line, gloss = file.readline.strip.split(" | ")
lexical_filenum, synset_type, word_count, *data_parts = data_line.split(" ")[1..-1]
words = Array.new(word_count.to_i(16)).map { "#{data_parts.shift}.#{data_parts.shift}" }
relations = Array.new(data_parts.shift.to_i).map { "#{data_parts.shift}.#{data_parts.shift}.#{data_parts.shift}.#{data_parts.shift}" }
return { "synset_id" => synset_id, "lexical_filenum" => lexical_filenum, "synset_type" => synset_type, "words" => words.join('|'), "relations" => relations.join('|'), "gloss" => gloss.strip }
end
end | ruby | def synset(synset_id)
raise NoWordnetConnection, "There is presently no connection to wordnet. To attempt to reistablish a connection you should use the 'open!' command on the Wordnet object." unless connected?
pos = synset_id[0,1]
File.open(@wordnet_path + "data.#{SHORT_TO_POS_FILE_TYPE[pos]}","r") do |file|
file.seek(synset_id[1..-1].to_i)
data_line, gloss = file.readline.strip.split(" | ")
lexical_filenum, synset_type, word_count, *data_parts = data_line.split(" ")[1..-1]
words = Array.new(word_count.to_i(16)).map { "#{data_parts.shift}.#{data_parts.shift}" }
relations = Array.new(data_parts.shift.to_i).map { "#{data_parts.shift}.#{data_parts.shift}.#{data_parts.shift}.#{data_parts.shift}" }
return { "synset_id" => synset_id, "lexical_filenum" => lexical_filenum, "synset_type" => synset_type, "words" => words.join('|'), "relations" => relations.join('|'), "gloss" => gloss.strip }
end
end | [
"def",
"synset",
"(",
"synset_id",
")",
"raise",
"NoWordnetConnection",
",",
"\"There is presently no connection to wordnet. To attempt to reistablish a connection you should use the 'open!' command on the Wordnet object.\"",
"unless",
"connected?",
"pos",
"=",
"synset_id",
"[",
"0",
",",
"1",
"]",
"File",
".",
"open",
"(",
"@wordnet_path",
"+",
"\"data.#{SHORT_TO_POS_FILE_TYPE[pos]}\"",
",",
"\"r\"",
")",
"do",
"|",
"file",
"|",
"file",
".",
"seek",
"(",
"synset_id",
"[",
"1",
"..",
"-",
"1",
"]",
".",
"to_i",
")",
"data_line",
",",
"gloss",
"=",
"file",
".",
"readline",
".",
"strip",
".",
"split",
"(",
"\" | \"",
")",
"lexical_filenum",
",",
"synset_type",
",",
"word_count",
",",
"*",
"data_parts",
"=",
"data_line",
".",
"split",
"(",
"\" \"",
")",
"[",
"1",
"..",
"-",
"1",
"]",
"words",
"=",
"Array",
".",
"new",
"(",
"word_count",
".",
"to_i",
"(",
"16",
")",
")",
".",
"map",
"{",
"\"#{data_parts.shift}.#{data_parts.shift}\"",
"}",
"relations",
"=",
"Array",
".",
"new",
"(",
"data_parts",
".",
"shift",
".",
"to_i",
")",
".",
"map",
"{",
"\"#{data_parts.shift}.#{data_parts.shift}.#{data_parts.shift}.#{data_parts.shift}\"",
"}",
"return",
"{",
"\"synset_id\"",
"=>",
"synset_id",
",",
"\"lexical_filenum\"",
"=>",
"lexical_filenum",
",",
"\"synset_type\"",
"=>",
"synset_type",
",",
"\"words\"",
"=>",
"words",
".",
"join",
"(",
"'|'",
")",
",",
"\"relations\"",
"=>",
"relations",
".",
"join",
"(",
"'|'",
")",
",",
"\"gloss\"",
"=>",
"gloss",
".",
"strip",
"}",
"end",
"end"
] | Locates from a synset_id a specific synset and constructs a synset hash.
@param [String] synset_id The synset id to locate.
@result [Hash, nil] A hash in the format { "synset_id" => ..., "lexical_filenum" => ..., "synset_type" => ..., "words" => ..., "relations" => ..., "gloss" => ... }, or nil if no synset is available.
@raise [NoWordnetConnection] If there is currently no wordnet connection. | [
"Locates",
"from",
"a",
"synset_id",
"a",
"specific",
"synset",
"and",
"constructs",
"a",
"synset",
"hash",
"."
] | 4d6302e7218533fcc2afb4cd993686dd56fe2cde | https://github.com/roja/words/blob/4d6302e7218533fcc2afb4cd993686dd56fe2cde/lib/wordnet_connectors/pure_wordnet_connection.rb#L111-L125 | train |
roja/words | lib/wordnet_connectors/pure_wordnet_connection.rb | Words.PureWordnetConnection.evocations | def evocations(synset_id)
raise NoWordnetConnection, "There is presently no connection to wordnet. To attempt to reistablish a connection you should use the 'open!' command on the Wordnet object." unless connected?
if defined? @evocations
raw_evocations = @evocations[synset_id + "s"]
{ 'relations' => raw_evocations[0], 'means' => raw_evocations[1], 'medians' => raw_evocations[2]} unless raw_evocations.nil?
else
nil
end
end | ruby | def evocations(synset_id)
raise NoWordnetConnection, "There is presently no connection to wordnet. To attempt to reistablish a connection you should use the 'open!' command on the Wordnet object." unless connected?
if defined? @evocations
raw_evocations = @evocations[synset_id + "s"]
{ 'relations' => raw_evocations[0], 'means' => raw_evocations[1], 'medians' => raw_evocations[2]} unless raw_evocations.nil?
else
nil
end
end | [
"def",
"evocations",
"(",
"synset_id",
")",
"raise",
"NoWordnetConnection",
",",
"\"There is presently no connection to wordnet. To attempt to reistablish a connection you should use the 'open!' command on the Wordnet object.\"",
"unless",
"connected?",
"if",
"defined?",
"@evocations",
"raw_evocations",
"=",
"@evocations",
"[",
"synset_id",
"+",
"\"s\"",
"]",
"{",
"'relations'",
"=>",
"raw_evocations",
"[",
"0",
"]",
",",
"'means'",
"=>",
"raw_evocations",
"[",
"1",
"]",
",",
"'medians'",
"=>",
"raw_evocations",
"[",
"2",
"]",
"}",
"unless",
"raw_evocations",
".",
"nil?",
"else",
"nil",
"end",
"end"
] | Locates from a synset id any relevent evocations and constructs an evocations hash.
@see Synset
@param [String] senset_id The id number of a specific synset.
@result [Hash, nil] A hash in the format { 'relations' => ..., 'means' => ..., 'medians' => ... }, or nil if no evocations are available.
@raise [NoWordnetConnection] If there is currently no wordnet connection. | [
"Locates",
"from",
"a",
"synset",
"id",
"any",
"relevent",
"evocations",
"and",
"constructs",
"an",
"evocations",
"hash",
"."
] | 4d6302e7218533fcc2afb4cd993686dd56fe2cde | https://github.com/roja/words/blob/4d6302e7218533fcc2afb4cd993686dd56fe2cde/lib/wordnet_connectors/pure_wordnet_connection.rb#L142-L153 | train |
jackjennings/hey | lib/hey/account.rb | Hey.Account.create | def create name, password, params = {}
params.merge!({
new_account_username: name,
new_account_passcode: password
})
post 'accounts', params
end | ruby | def create name, password, params = {}
params.merge!({
new_account_username: name,
new_account_passcode: password
})
post 'accounts', params
end | [
"def",
"create",
"name",
",",
"password",
",",
"params",
"=",
"{",
"}",
"params",
".",
"merge!",
"(",
"{",
"new_account_username",
":",
"name",
",",
"new_account_passcode",
":",
"password",
"}",
")",
"post",
"'accounts'",
",",
"params",
"end"
] | Sends a request to create an account using the +accounts+ endpoint.
Raises a +MissingAPITokenError+ error if an API token
hasn't been set on the Hey module or Yo instance.
Accepts an optional hash of additional parameters to
send with the request.
Hey::Account.new.create "worldcup", "somepass", email: "[email protected]" | [
"Sends",
"a",
"request",
"to",
"create",
"an",
"account",
"using",
"the",
"+",
"accounts",
"+",
"endpoint",
".",
"Raises",
"a",
"+",
"MissingAPITokenError",
"+",
"error",
"if",
"an",
"API",
"token",
"hasn",
"t",
"been",
"set",
"on",
"the",
"Hey",
"module",
"or",
"Yo",
"instance",
".",
"Accepts",
"an",
"optional",
"hash",
"of",
"additional",
"parameters",
"to",
"send",
"with",
"the",
"request",
"."
] | 51eb3412f39f51d6f5e3bea5a0c1483766cf6139 | https://github.com/jackjennings/hey/blob/51eb3412f39f51d6f5e3bea5a0c1483766cf6139/lib/hey/account.rb#L14-L20 | train |
nanodeath/threadz | lib/threadz/batch.rb | Threadz.Batch.when_done | def when_done(&block)
call_block = false
@job_lock.synchronize do
if completed?
call_block = true
else
@when_done_callbacks << block
end
end
yield if call_block
end | ruby | def when_done(&block)
call_block = false
@job_lock.synchronize do
if completed?
call_block = true
else
@when_done_callbacks << block
end
end
yield if call_block
end | [
"def",
"when_done",
"(",
"&",
"block",
")",
"call_block",
"=",
"false",
"@job_lock",
".",
"synchronize",
"do",
"if",
"completed?",
"call_block",
"=",
"true",
"else",
"@when_done_callbacks",
"<<",
"block",
"end",
"end",
"yield",
"if",
"call_block",
"end"
] | Execute a given block when the batch has finished processing. If the batch
has already finished executing, execute immediately. | [
"Execute",
"a",
"given",
"block",
"when",
"the",
"batch",
"has",
"finished",
"processing",
".",
"If",
"the",
"batch",
"has",
"already",
"finished",
"executing",
"execute",
"immediately",
"."
] | 5d96e052567076d5e86690f3d3703f1082330dd5 | https://github.com/nanodeath/threadz/blob/5d96e052567076d5e86690f3d3703f1082330dd5/lib/threadz/batch.rb#L118-L128 | train |
rightscale/right_develop | lib/right_develop/commands/git.rb | RightDevelop::Commands.Git.prune | def prune(options={})
puts describe_prune(options)
puts "Fetching latest branches and tags from remotes"
@git.fetch_all(:prune => true)
branches = @git.branches(:all => true)
#Filter by name prefix
branches = branches.select { |x| x =~ options[:only] } if options[:only]
branches = branches.reject { |x| x =~ options[:except] } if options[:except]
#Filter by location (local/remote)
if options[:local] && !options[:remote]
branches = branches.local
elsif options[:remote] && !options[:local]
branches = branches.remote
elsif options[:remote] && options[:local]
raise ArgumentError, "Cannot specify both --local and --remote!"
end
#Filter by merge status
if options[:merged]
puts "Checking merge status of #{branches.size} branches; please be patient"
branches = branches.merged(options[:merged])
end
old = {}
branches.each do |branch|
latest = @git.log(branch, :tail => 1).first
timestamp = latest.timestamp
if timestamp < options[:age] &&
old[branch] = timestamp
end
end
if old.empty?
STDERR.puts "No branches found; try different options"
exit -2
end
puts
all_by_prefix = branches.group_by { |b| b.name.split(NAME_SPLIT_CHARS).first }
all_by_prefix.each_pair do |prefix, branches|
old_in_group = branches.select { |b| old.key?(b) }
next if old_in_group.empty?
old_in_group = old_in_group.sort { |a, b| old[a] <=> old[b] }
puts prefix
puts '-' * prefix.length
old_in_group.each do |b|
puts "\t" + b.display(40) + "\t" + time_ago_in_words(old[b])
end
puts
end
unless options[:force]
return unless prompt("Delete all #{old.size} branches above?", true)
end
old.each do |branch, timestamp|
branch.delete
puts " deleted #{branch}"
end
end | ruby | def prune(options={})
puts describe_prune(options)
puts "Fetching latest branches and tags from remotes"
@git.fetch_all(:prune => true)
branches = @git.branches(:all => true)
#Filter by name prefix
branches = branches.select { |x| x =~ options[:only] } if options[:only]
branches = branches.reject { |x| x =~ options[:except] } if options[:except]
#Filter by location (local/remote)
if options[:local] && !options[:remote]
branches = branches.local
elsif options[:remote] && !options[:local]
branches = branches.remote
elsif options[:remote] && options[:local]
raise ArgumentError, "Cannot specify both --local and --remote!"
end
#Filter by merge status
if options[:merged]
puts "Checking merge status of #{branches.size} branches; please be patient"
branches = branches.merged(options[:merged])
end
old = {}
branches.each do |branch|
latest = @git.log(branch, :tail => 1).first
timestamp = latest.timestamp
if timestamp < options[:age] &&
old[branch] = timestamp
end
end
if old.empty?
STDERR.puts "No branches found; try different options"
exit -2
end
puts
all_by_prefix = branches.group_by { |b| b.name.split(NAME_SPLIT_CHARS).first }
all_by_prefix.each_pair do |prefix, branches|
old_in_group = branches.select { |b| old.key?(b) }
next if old_in_group.empty?
old_in_group = old_in_group.sort { |a, b| old[a] <=> old[b] }
puts prefix
puts '-' * prefix.length
old_in_group.each do |b|
puts "\t" + b.display(40) + "\t" + time_ago_in_words(old[b])
end
puts
end
unless options[:force]
return unless prompt("Delete all #{old.size} branches above?", true)
end
old.each do |branch, timestamp|
branch.delete
puts " deleted #{branch}"
end
end | [
"def",
"prune",
"(",
"options",
"=",
"{",
"}",
")",
"puts",
"describe_prune",
"(",
"options",
")",
"puts",
"\"Fetching latest branches and tags from remotes\"",
"@git",
".",
"fetch_all",
"(",
":prune",
"=>",
"true",
")",
"branches",
"=",
"@git",
".",
"branches",
"(",
":all",
"=>",
"true",
")",
"branches",
"=",
"branches",
".",
"select",
"{",
"|",
"x",
"|",
"x",
"=~",
"options",
"[",
":only",
"]",
"}",
"if",
"options",
"[",
":only",
"]",
"branches",
"=",
"branches",
".",
"reject",
"{",
"|",
"x",
"|",
"x",
"=~",
"options",
"[",
":except",
"]",
"}",
"if",
"options",
"[",
":except",
"]",
"if",
"options",
"[",
":local",
"]",
"&&",
"!",
"options",
"[",
":remote",
"]",
"branches",
"=",
"branches",
".",
"local",
"elsif",
"options",
"[",
":remote",
"]",
"&&",
"!",
"options",
"[",
":local",
"]",
"branches",
"=",
"branches",
".",
"remote",
"elsif",
"options",
"[",
":remote",
"]",
"&&",
"options",
"[",
":local",
"]",
"raise",
"ArgumentError",
",",
"\"Cannot specify both --local and --remote!\"",
"end",
"if",
"options",
"[",
":merged",
"]",
"puts",
"\"Checking merge status of #{branches.size} branches; please be patient\"",
"branches",
"=",
"branches",
".",
"merged",
"(",
"options",
"[",
":merged",
"]",
")",
"end",
"old",
"=",
"{",
"}",
"branches",
".",
"each",
"do",
"|",
"branch",
"|",
"latest",
"=",
"@git",
".",
"log",
"(",
"branch",
",",
":tail",
"=>",
"1",
")",
".",
"first",
"timestamp",
"=",
"latest",
".",
"timestamp",
"if",
"timestamp",
"<",
"options",
"[",
":age",
"]",
"&&",
"old",
"[",
"branch",
"]",
"=",
"timestamp",
"end",
"end",
"if",
"old",
".",
"empty?",
"STDERR",
".",
"puts",
"\"No branches found; try different options\"",
"exit",
"-",
"2",
"end",
"puts",
"all_by_prefix",
"=",
"branches",
".",
"group_by",
"{",
"|",
"b",
"|",
"b",
".",
"name",
".",
"split",
"(",
"NAME_SPLIT_CHARS",
")",
".",
"first",
"}",
"all_by_prefix",
".",
"each_pair",
"do",
"|",
"prefix",
",",
"branches",
"|",
"old_in_group",
"=",
"branches",
".",
"select",
"{",
"|",
"b",
"|",
"old",
".",
"key?",
"(",
"b",
")",
"}",
"next",
"if",
"old_in_group",
".",
"empty?",
"old_in_group",
"=",
"old_in_group",
".",
"sort",
"{",
"|",
"a",
",",
"b",
"|",
"old",
"[",
"a",
"]",
"<=>",
"old",
"[",
"b",
"]",
"}",
"puts",
"prefix",
"puts",
"'-'",
"*",
"prefix",
".",
"length",
"old_in_group",
".",
"each",
"do",
"|",
"b",
"|",
"puts",
"\"\\t\"",
"+",
"b",
".",
"display",
"(",
"40",
")",
"+",
"\"\\t\"",
"+",
"time_ago_in_words",
"(",
"old",
"[",
"b",
"]",
")",
"end",
"puts",
"end",
"unless",
"options",
"[",
":force",
"]",
"return",
"unless",
"prompt",
"(",
"\"Delete all #{old.size} branches above?\"",
",",
"true",
")",
"end",
"old",
".",
"each",
"do",
"|",
"branch",
",",
"timestamp",
"|",
"branch",
".",
"delete",
"puts",
"\" deleted #{branch}\"",
"end",
"end"
] | Prune dead branches from the repository.
@option options [Time] :age Ignore branches whose HEAD commit is newer than this timestamp
@option options [Regexp] :except Ignore branches matching this pattern
@option options [Regexp] :only Consider only branches matching this pattern
@option options [Boolean] :local Consider only local branches
@option options [Boolean] :remote Consider only remote branches
@option options [String] :merged Consider only branches that are fully merged into this branch (e.g. master) | [
"Prune",
"dead",
"branches",
"from",
"the",
"repository",
"."
] | 52527b3c32200b542ed590f6f9a275c76758df0e | https://github.com/rightscale/right_develop/blob/52527b3c32200b542ed590f6f9a275c76758df0e/lib/right_develop/commands/git.rb#L165-L230 | train |
rightscale/right_develop | lib/right_develop/commands/git.rb | RightDevelop::Commands.Git.describe_prune | def describe_prune(options)
statement = ['Pruning']
if options[:remote]
statement << 'remote'
elsif options[:local]
statement << 'local'
end
statement << 'branches'
if options[:age]
statement << "older than #{time_ago_in_words(options[:age])}"
end
if options[:merged]
statement << "that are fully merged into #{options[:merged]}"
end
if options[:only]
naming = "with a name containing '#{options[:only]}'"
if options[:except]
naming << " (but not '#{options[:except]}')"
end
statement << naming
end
statement.join(' ')
end | ruby | def describe_prune(options)
statement = ['Pruning']
if options[:remote]
statement << 'remote'
elsif options[:local]
statement << 'local'
end
statement << 'branches'
if options[:age]
statement << "older than #{time_ago_in_words(options[:age])}"
end
if options[:merged]
statement << "that are fully merged into #{options[:merged]}"
end
if options[:only]
naming = "with a name containing '#{options[:only]}'"
if options[:except]
naming << " (but not '#{options[:except]}')"
end
statement << naming
end
statement.join(' ')
end | [
"def",
"describe_prune",
"(",
"options",
")",
"statement",
"=",
"[",
"'Pruning'",
"]",
"if",
"options",
"[",
":remote",
"]",
"statement",
"<<",
"'remote'",
"elsif",
"options",
"[",
":local",
"]",
"statement",
"<<",
"'local'",
"end",
"statement",
"<<",
"'branches'",
"if",
"options",
"[",
":age",
"]",
"statement",
"<<",
"\"older than #{time_ago_in_words(options[:age])}\"",
"end",
"if",
"options",
"[",
":merged",
"]",
"statement",
"<<",
"\"that are fully merged into #{options[:merged]}\"",
"end",
"if",
"options",
"[",
":only",
"]",
"naming",
"=",
"\"with a name containing '#{options[:only]}'\"",
"if",
"options",
"[",
":except",
"]",
"naming",
"<<",
"\" (but not '#{options[:except]}')\"",
"end",
"statement",
"<<",
"naming",
"end",
"statement",
".",
"join",
"(",
"' '",
")",
"end"
] | Build a plain-English description of a prune command based on the
options given.
@param [Hash] options | [
"Build",
"a",
"plain",
"-",
"English",
"description",
"of",
"a",
"prune",
"command",
"based",
"on",
"the",
"options",
"given",
"."
] | 52527b3c32200b542ed590f6f9a275c76758df0e | https://github.com/rightscale/right_develop/blob/52527b3c32200b542ed590f6f9a275c76758df0e/lib/right_develop/commands/git.rb#L288-L316 | train |
rightscale/right_develop | lib/right_develop/commands/git.rb | RightDevelop::Commands.Git.prompt | def prompt(p, yes_no=false)
puts #newline for newline's sake!
loop do
print p, ' '
line = STDIN.readline.strip
if yes_no
return true if line =~ YES
return false if line =~ NO
else
return line
end
end
end | ruby | def prompt(p, yes_no=false)
puts #newline for newline's sake!
loop do
print p, ' '
line = STDIN.readline.strip
if yes_no
return true if line =~ YES
return false if line =~ NO
else
return line
end
end
end | [
"def",
"prompt",
"(",
"p",
",",
"yes_no",
"=",
"false",
")",
"puts",
"loop",
"do",
"print",
"p",
",",
"' '",
"line",
"=",
"STDIN",
".",
"readline",
".",
"strip",
"if",
"yes_no",
"return",
"true",
"if",
"line",
"=~",
"YES",
"return",
"false",
"if",
"line",
"=~",
"NO",
"else",
"return",
"line",
"end",
"end",
"end"
] | Ask the user a yes-or-no question | [
"Ask",
"the",
"user",
"a",
"yes",
"-",
"or",
"-",
"no",
"question"
] | 52527b3c32200b542ed590f6f9a275c76758df0e | https://github.com/rightscale/right_develop/blob/52527b3c32200b542ed590f6f9a275c76758df0e/lib/right_develop/commands/git.rb#L319-L332 | train |
rightscale/right_develop | lib/right_develop/commands/git.rb | RightDevelop::Commands.Git.parse_age | def parse_age(str)
ord, word = str.split(/[. ]+/, 2)
ord = Integer(ord)
word.gsub!(/s$/, '')
ago = nil
TIME_INTERVALS.each do |pair|
mag, term = pair.first, pair.last
if term == word
ago = Time.at(Time.now.to_i - ord * mag)
break
end
end
if ago
ago
else
raise ArgumentError, "Cannot parse '#{str}' as an age"
end
end | ruby | def parse_age(str)
ord, word = str.split(/[. ]+/, 2)
ord = Integer(ord)
word.gsub!(/s$/, '')
ago = nil
TIME_INTERVALS.each do |pair|
mag, term = pair.first, pair.last
if term == word
ago = Time.at(Time.now.to_i - ord * mag)
break
end
end
if ago
ago
else
raise ArgumentError, "Cannot parse '#{str}' as an age"
end
end | [
"def",
"parse_age",
"(",
"str",
")",
"ord",
",",
"word",
"=",
"str",
".",
"split",
"(",
"/",
"/",
",",
"2",
")",
"ord",
"=",
"Integer",
"(",
"ord",
")",
"word",
".",
"gsub!",
"(",
"/",
"/",
",",
"''",
")",
"ago",
"=",
"nil",
"TIME_INTERVALS",
".",
"each",
"do",
"|",
"pair",
"|",
"mag",
",",
"term",
"=",
"pair",
".",
"first",
",",
"pair",
".",
"last",
"if",
"term",
"==",
"word",
"ago",
"=",
"Time",
".",
"at",
"(",
"Time",
".",
"now",
".",
"to_i",
"-",
"ord",
"*",
"mag",
")",
"break",
"end",
"end",
"if",
"ago",
"ago",
"else",
"raise",
"ArgumentError",
",",
"\"Cannot parse '#{str}' as an age\"",
"end",
"end"
] | Given a natural-language English description of a time duration, return a Time in the past,
that is the same duration from Time.now that is expressed in the string.
@param [String] str an English time duration
@return [Time] a Time object in the past, as described relative to now by str | [
"Given",
"a",
"natural",
"-",
"language",
"English",
"description",
"of",
"a",
"time",
"duration",
"return",
"a",
"Time",
"in",
"the",
"past",
"that",
"is",
"the",
"same",
"duration",
"from",
"Time",
".",
"now",
"that",
"is",
"expressed",
"in",
"the",
"string",
"."
] | 52527b3c32200b542ed590f6f9a275c76758df0e | https://github.com/rightscale/right_develop/blob/52527b3c32200b542ed590f6f9a275c76758df0e/lib/right_develop/commands/git.rb#L382-L403 | train |
wilkosz/squash_matrix | lib/squash_matrix/client.rb | SquashMatrix.Client.get_save_params | def get_save_params
{
player: @player,
email: @email,
password: @password,
suppress_errors: @suppress_errors,
timeout: @timeout,
user_agent: @user_agent,
cookie: get_cookie_string,
expires: @expires.to_s,
proxy_addr: @proxy_addr,
proxy_port: @proxy_port
}.delete_if { |_k, v| v.nil? }
end | ruby | def get_save_params
{
player: @player,
email: @email,
password: @password,
suppress_errors: @suppress_errors,
timeout: @timeout,
user_agent: @user_agent,
cookie: get_cookie_string,
expires: @expires.to_s,
proxy_addr: @proxy_addr,
proxy_port: @proxy_port
}.delete_if { |_k, v| v.nil? }
end | [
"def",
"get_save_params",
"{",
"player",
":",
"@player",
",",
"email",
":",
"@email",
",",
"password",
":",
"@password",
",",
"suppress_errors",
":",
"@suppress_errors",
",",
"timeout",
":",
"@timeout",
",",
"user_agent",
":",
"@user_agent",
",",
"cookie",
":",
"get_cookie_string",
",",
"expires",
":",
"@expires",
".",
"to_s",
",",
"proxy_addr",
":",
"@proxy_addr",
",",
"proxy_port",
":",
"@proxy_port",
"}",
".",
"delete_if",
"{",
"|",
"_k",
",",
"v",
"|",
"v",
".",
"nil?",
"}",
"end"
] | Returns params to create existing authenticated client
@return [Hash] | [
"Returns",
"params",
"to",
"create",
"existing",
"authenticated",
"client"
] | ce3d3e191004905d31fdc96e4439c6290141d8da | https://github.com/wilkosz/squash_matrix/blob/ce3d3e191004905d31fdc96e4439c6290141d8da/lib/squash_matrix/client.rb#L22-L35 | train |
wilkosz/squash_matrix | lib/squash_matrix/client.rb | SquashMatrix.Client.get_club_info | def get_club_info(id = nil)
return unless id.to_i.positive?
uri = URI::HTTP.build(
host: SquashMatrix::Constants::SQUASH_MATRIX_URL,
path: SquashMatrix::Constants::CLUB_PATH.gsub(':id', id.to_s)
)
success_proc = lambda do |res|
SquashMatrix::NokogiriParser.get_club_info(res.body)
end
handle_http_request(uri, success_proc)
end | ruby | def get_club_info(id = nil)
return unless id.to_i.positive?
uri = URI::HTTP.build(
host: SquashMatrix::Constants::SQUASH_MATRIX_URL,
path: SquashMatrix::Constants::CLUB_PATH.gsub(':id', id.to_s)
)
success_proc = lambda do |res|
SquashMatrix::NokogiriParser.get_club_info(res.body)
end
handle_http_request(uri, success_proc)
end | [
"def",
"get_club_info",
"(",
"id",
"=",
"nil",
")",
"return",
"unless",
"id",
".",
"to_i",
".",
"positive?",
"uri",
"=",
"URI",
"::",
"HTTP",
".",
"build",
"(",
"host",
":",
"SquashMatrix",
"::",
"Constants",
"::",
"SQUASH_MATRIX_URL",
",",
"path",
":",
"SquashMatrix",
"::",
"Constants",
"::",
"CLUB_PATH",
".",
"gsub",
"(",
"':id'",
",",
"id",
".",
"to_s",
")",
")",
"success_proc",
"=",
"lambda",
"do",
"|",
"res",
"|",
"SquashMatrix",
"::",
"NokogiriParser",
".",
"get_club_info",
"(",
"res",
".",
"body",
")",
"end",
"handle_http_request",
"(",
"uri",
",",
"success_proc",
")",
"end"
] | Returns newly created Client
@note If suppress_errors == false SquashMatrix::Errors::AuthorizationError will be raised if specified credentials are incorrect and squash matrix authentication returns forbidden
@param [Hash] opts the options to create client
@return [Client]
Returns club info.
@note If suppress_errors == false SquashMatrix Errors will be raised upon HttpNotFound, HttpConflict, Timeout::Error, etc...
@param id [Fixnum] club id found on squash matrix
@return [Hash] hash object containing club information | [
"Returns",
"newly",
"created",
"Client"
] | ce3d3e191004905d31fdc96e4439c6290141d8da | https://github.com/wilkosz/squash_matrix/blob/ce3d3e191004905d31fdc96e4439c6290141d8da/lib/squash_matrix/client.rb#L85-L95 | train |
wilkosz/squash_matrix | lib/squash_matrix/client.rb | SquashMatrix.Client.get_player_results | def get_player_results(id = nil)
return unless id.to_i.positive?
uri = URI::HTTP.build(
host: SquashMatrix::Constants::SQUASH_MATRIX_URL,
path: SquashMatrix::Constants::PLAYER_RESULTS_PATH.gsub(':id', id.to_s),
query: SquashMatrix::Constants::PLAYER_RSULTS_QUERY
)
success_proc = lambda do |res|
SquashMatrix::NokogiriParser.get_player_results(res.body)
end
handle_http_request(uri, success_proc)
end | ruby | def get_player_results(id = nil)
return unless id.to_i.positive?
uri = URI::HTTP.build(
host: SquashMatrix::Constants::SQUASH_MATRIX_URL,
path: SquashMatrix::Constants::PLAYER_RESULTS_PATH.gsub(':id', id.to_s),
query: SquashMatrix::Constants::PLAYER_RSULTS_QUERY
)
success_proc = lambda do |res|
SquashMatrix::NokogiriParser.get_player_results(res.body)
end
handle_http_request(uri, success_proc)
end | [
"def",
"get_player_results",
"(",
"id",
"=",
"nil",
")",
"return",
"unless",
"id",
".",
"to_i",
".",
"positive?",
"uri",
"=",
"URI",
"::",
"HTTP",
".",
"build",
"(",
"host",
":",
"SquashMatrix",
"::",
"Constants",
"::",
"SQUASH_MATRIX_URL",
",",
"path",
":",
"SquashMatrix",
"::",
"Constants",
"::",
"PLAYER_RESULTS_PATH",
".",
"gsub",
"(",
"':id'",
",",
"id",
".",
"to_s",
")",
",",
"query",
":",
"SquashMatrix",
"::",
"Constants",
"::",
"PLAYER_RSULTS_QUERY",
")",
"success_proc",
"=",
"lambda",
"do",
"|",
"res",
"|",
"SquashMatrix",
"::",
"NokogiriParser",
".",
"get_player_results",
"(",
"res",
".",
"body",
")",
"end",
"handle_http_request",
"(",
"uri",
",",
"success_proc",
")",
"end"
] | Returns player results.
@note If suppress_errors == false SquashMatrix Errors will be raised upon HttpNotFound, HttpConflict, Timeout::Error, etc...
@param id [Fixnum] played id found on squash matrix
@return [Array<Hash>] Array of player match results | [
"Returns",
"player",
"results",
"."
] | ce3d3e191004905d31fdc96e4439c6290141d8da | https://github.com/wilkosz/squash_matrix/blob/ce3d3e191004905d31fdc96e4439c6290141d8da/lib/squash_matrix/client.rb#L102-L113 | train |
wilkosz/squash_matrix | lib/squash_matrix/client.rb | SquashMatrix.Client.get_search_results | def get_search_results(query = nil,
squash_only: false,
racquetball_only: false)
return if query.to_s.empty?
uri = URI::HTTP.build(
host: SquashMatrix::Constants::SQUASH_MATRIX_URL,
path: SquashMatrix::Constants::SEARCH_RESULTS_PATH
)
query_params = {
Criteria: query,
SquashOnly: squash_only,
RacquetballOnly: racquetball_only
}
success_proc = lambda do |res|
SquashMatrix::NokogiriParser.get_search_results(res.body)
end
handle_http_request(uri, success_proc,
is_get_request: false,
query_params: query_params)
end | ruby | def get_search_results(query = nil,
squash_only: false,
racquetball_only: false)
return if query.to_s.empty?
uri = URI::HTTP.build(
host: SquashMatrix::Constants::SQUASH_MATRIX_URL,
path: SquashMatrix::Constants::SEARCH_RESULTS_PATH
)
query_params = {
Criteria: query,
SquashOnly: squash_only,
RacquetballOnly: racquetball_only
}
success_proc = lambda do |res|
SquashMatrix::NokogiriParser.get_search_results(res.body)
end
handle_http_request(uri, success_proc,
is_get_request: false,
query_params: query_params)
end | [
"def",
"get_search_results",
"(",
"query",
"=",
"nil",
",",
"squash_only",
":",
"false",
",",
"racquetball_only",
":",
"false",
")",
"return",
"if",
"query",
".",
"to_s",
".",
"empty?",
"uri",
"=",
"URI",
"::",
"HTTP",
".",
"build",
"(",
"host",
":",
"SquashMatrix",
"::",
"Constants",
"::",
"SQUASH_MATRIX_URL",
",",
"path",
":",
"SquashMatrix",
"::",
"Constants",
"::",
"SEARCH_RESULTS_PATH",
")",
"query_params",
"=",
"{",
"Criteria",
":",
"query",
",",
"SquashOnly",
":",
"squash_only",
",",
"RacquetballOnly",
":",
"racquetball_only",
"}",
"success_proc",
"=",
"lambda",
"do",
"|",
"res",
"|",
"SquashMatrix",
"::",
"NokogiriParser",
".",
"get_search_results",
"(",
"res",
".",
"body",
")",
"end",
"handle_http_request",
"(",
"uri",
",",
"success_proc",
",",
"is_get_request",
":",
"false",
",",
"query_params",
":",
"query_params",
")",
"end"
] | Returns get_search_results results
@note If suppress_errors == false SquashMatrix Errors will be raised upon HttpNotFound, HttpConflict, Timeout::Error, etc...
@param query [String] get_search_results query
@return [Hash] hash object containing get_search_results results | [
"Returns",
"get_search_results",
"results"
] | ce3d3e191004905d31fdc96e4439c6290141d8da | https://github.com/wilkosz/squash_matrix/blob/ce3d3e191004905d31fdc96e4439c6290141d8da/lib/squash_matrix/client.rb#L137-L156 | train |
atomicobject/hardmock | lib/hardmock/mock.rb | Hardmock.Mock.expects | def expects(*args, &block)
expector = Expector.new(self,@control,@expectation_builder)
# If there are no args, we return the Expector
return expector if args.empty?
# If there ARE args, we set up the expectation right here and return it
expector.send(args.shift.to_sym, *args, &block)
end | ruby | def expects(*args, &block)
expector = Expector.new(self,@control,@expectation_builder)
# If there are no args, we return the Expector
return expector if args.empty?
# If there ARE args, we set up the expectation right here and return it
expector.send(args.shift.to_sym, *args, &block)
end | [
"def",
"expects",
"(",
"*",
"args",
",",
"&",
"block",
")",
"expector",
"=",
"Expector",
".",
"new",
"(",
"self",
",",
"@control",
",",
"@expectation_builder",
")",
"return",
"expector",
"if",
"args",
".",
"empty?",
"expector",
".",
"send",
"(",
"args",
".",
"shift",
".",
"to_sym",
",",
"*",
"args",
",",
"&",
"block",
")",
"end"
] | Begin declaring an expectation for this Mock.
== Simple Examples
Expect the +customer+ to be queried for +account+, and return <tt>"The
Account"</tt>:
@customer.expects.account.returns "The Account"
Expect the +withdraw+ method to be called, and raise an exception when it
is (see Expectation#raises for more info):
@cash_machine.expects.withdraw(20,:dollars).raises("not enough money")
Expect +customer+ to have its +user_name+ set
@customer.expects.user_name = 'Big Boss'
Expect +customer+ to have its +user_name+ set, and raise a RuntimeException when
that happens:
@customer.expects('user_name=', "Big Boss").raises "lost connection"
Expect +evaluate+ to be passed a block, and when that happens, pass a value
to the block (see Expectation#yields for more info):
@cruncher.expects.evaluate.yields("some data").returns("some results")
== Expectation Blocks
To do special handling of expected method calls when they occur, you
may pass a block to your expectation, like:
@page_scraper.expects.handle_content do |address,request,status|
assert_not_nil address, "Can't abide nil addresses"
assert_equal "http-get", request.method, "Can only handle GET"
assert status > 200 and status < 300, status, "Failed status"
"Simulated results #{request.content.downcase}"
end
In this example, when <tt>page_scraper.handle_content</tt> is called, its
three arguments are passed to the <i>expectation block</i> and evaluated
using the above assertions. The last value in the block will be used
as the return value for +handle_content+
You may specify arguments to the expected method call, just like any normal
expectation, and those arguments will be pre-validated before being passed
to the expectation block. This is useful when you know all of the
expected values but still need to do something programmatic.
If the method being invoked on the mock accepts a block, that block will be
passed to your expectation block as the last (or only) argument. Eg, the
convenience method +yields+ can be replaced with the more explicit:
@cruncher.expects.evaluate do |block|
block.call "some data"
"some results"
end
The result value of the expectation block becomes the return value for the
expected method call. This can be overidden by using the +returns+ method:
@cruncher.expects.evaluate do |block|
block.call "some data"
"some results"
end.returns("the actual value")
<b>Additionally</b>, the resulting value of the expectation block is stored
in the +block_value+ field on the expectation. If you've saved a reference
to your expectation, you may retrieve the block value once the expectation
has been met.
evaluation_event = @cruncher.expects.evaluate do |block|
block.call "some data"
"some results"
end.returns("the actual value")
result = @cruncher.evaluate do |input|
puts input # => 'some data'
end
# result is 'the actual value'
evaluation_event.block_value # => 'some results' | [
"Begin",
"declaring",
"an",
"expectation",
"for",
"this",
"Mock",
"."
] | a2c01c2cbd28f56a71cc824f04b40ea1d14be367 | https://github.com/atomicobject/hardmock/blob/a2c01c2cbd28f56a71cc824f04b40ea1d14be367/lib/hardmock/mock.rb#L108-L114 | train |
adamluzsi/download | lib/download.rb | Download.Object.file_path | def file_path
self.path= File.join(Dir.pwd, uri_file_name) unless path
if File.directory?(path)
self.path= File.join(self.path, uri_file_name)
end
self.path
end | ruby | def file_path
self.path= File.join(Dir.pwd, uri_file_name) unless path
if File.directory?(path)
self.path= File.join(self.path, uri_file_name)
end
self.path
end | [
"def",
"file_path",
"self",
".",
"path",
"=",
"File",
".",
"join",
"(",
"Dir",
".",
"pwd",
",",
"uri_file_name",
")",
"unless",
"path",
"if",
"File",
".",
"directory?",
"(",
"path",
")",
"self",
".",
"path",
"=",
"File",
".",
"join",
"(",
"self",
".",
"path",
",",
"uri_file_name",
")",
"end",
"self",
".",
"path",
"end"
] | return a string with a file path where the file will be saved | [
"return",
"a",
"string",
"with",
"a",
"file",
"path",
"where",
"the",
"file",
"will",
"be",
"saved"
] | 6de4193aeb6444e5fe2e0dbe7bd2da07c290baa3 | https://github.com/adamluzsi/download/blob/6de4193aeb6444e5fe2e0dbe7bd2da07c290baa3/lib/download.rb#L20-L29 | train |
adamluzsi/download | lib/download.rb | Download.Object.start | def start(hash={})
set_multi(hash)
File.delete(file_path) if File.exist?(file_path)
File.open(file_path, 'wb') do |file_obj|
Kernel.open(*[url,options].compact) do |fin|
while (buf = fin.read(8192))
file_obj << buf
end
end
end
return file_path
end | ruby | def start(hash={})
set_multi(hash)
File.delete(file_path) if File.exist?(file_path)
File.open(file_path, 'wb') do |file_obj|
Kernel.open(*[url,options].compact) do |fin|
while (buf = fin.read(8192))
file_obj << buf
end
end
end
return file_path
end | [
"def",
"start",
"(",
"hash",
"=",
"{",
"}",
")",
"set_multi",
"(",
"hash",
")",
"File",
".",
"delete",
"(",
"file_path",
")",
"if",
"File",
".",
"exist?",
"(",
"file_path",
")",
"File",
".",
"open",
"(",
"file_path",
",",
"'wb'",
")",
"do",
"|",
"file_obj",
"|",
"Kernel",
".",
"open",
"(",
"*",
"[",
"url",
",",
"options",
"]",
".",
"compact",
")",
"do",
"|",
"fin",
"|",
"while",
"(",
"buf",
"=",
"fin",
".",
"read",
"(",
"8192",
")",
")",
"file_obj",
"<<",
"buf",
"end",
"end",
"end",
"return",
"file_path",
"end"
] | start the downloading process | [
"start",
"the",
"downloading",
"process"
] | 6de4193aeb6444e5fe2e0dbe7bd2da07c290baa3 | https://github.com/adamluzsi/download/blob/6de4193aeb6444e5fe2e0dbe7bd2da07c290baa3/lib/download.rb#L32-L47 | train |
sloppycoder/fixed_width_file_validator | lib/fixed_width_file_validator/validator.rb | FixedWidthFileValidator.FieldValidator.validate | def validate(record, field_name, bindings = {})
if validations
validations.collect do |validation|
unless valid_value?(validation, record, field_name, bindings)
FieldValidationError.new(validation, record, field_name, pos, width)
end
end.compact
elsif record && record[field_name]
# when no validation rules exist for the field, just check if the field exists in the record
[]
else
raise "found field value nil in #{record} field #{field_name}, shouldn't be possible?"
end
end | ruby | def validate(record, field_name, bindings = {})
if validations
validations.collect do |validation|
unless valid_value?(validation, record, field_name, bindings)
FieldValidationError.new(validation, record, field_name, pos, width)
end
end.compact
elsif record && record[field_name]
# when no validation rules exist for the field, just check if the field exists in the record
[]
else
raise "found field value nil in #{record} field #{field_name}, shouldn't be possible?"
end
end | [
"def",
"validate",
"(",
"record",
",",
"field_name",
",",
"bindings",
"=",
"{",
"}",
")",
"if",
"validations",
"validations",
".",
"collect",
"do",
"|",
"validation",
"|",
"unless",
"valid_value?",
"(",
"validation",
",",
"record",
",",
"field_name",
",",
"bindings",
")",
"FieldValidationError",
".",
"new",
"(",
"validation",
",",
"record",
",",
"field_name",
",",
"pos",
",",
"width",
")",
"end",
"end",
".",
"compact",
"elsif",
"record",
"&&",
"record",
"[",
"field_name",
"]",
"[",
"]",
"else",
"raise",
"\"found field value nil in #{record} field #{field_name}, shouldn't be possible?\"",
"end",
"end"
] | return an array of error objects
empty array if all validation passes | [
"return",
"an",
"array",
"of",
"error",
"objects",
"empty",
"array",
"if",
"all",
"validation",
"passes"
] | 0dce83b0b73f65bc80c7fc61d5117a6a3acc1828 | https://github.com/sloppycoder/fixed_width_file_validator/blob/0dce83b0b73f65bc80c7fc61d5117a6a3acc1828/lib/fixed_width_file_validator/validator.rb#L35-L48 | train |
etailer/parcel_api | lib/parcel_api/label.rb | ParcelApi.Label.details | def details(label_id)
details_url = File.join(LABEL_URL, "#{label_id}.json")
response = connection.get details_url
details = response.parsed.tap {|d| d.delete('success')}
OpenStruct.new(details)
end | ruby | def details(label_id)
details_url = File.join(LABEL_URL, "#{label_id}.json")
response = connection.get details_url
details = response.parsed.tap {|d| d.delete('success')}
OpenStruct.new(details)
end | [
"def",
"details",
"(",
"label_id",
")",
"details_url",
"=",
"File",
".",
"join",
"(",
"LABEL_URL",
",",
"\"#{label_id}.json\"",
")",
"response",
"=",
"connection",
".",
"get",
"details_url",
"details",
"=",
"response",
".",
"parsed",
".",
"tap",
"{",
"|",
"d",
"|",
"d",
".",
"delete",
"(",
"'success'",
")",
"}",
"OpenStruct",
".",
"new",
"(",
"details",
")",
"end"
] | Get label details
@param label_id [String]
@return Object of label details | [
"Get",
"label",
"details"
] | fcb8d64e45f7ba72bab48f143ac5115b0441aced | https://github.com/etailer/parcel_api/blob/fcb8d64e45f7ba72bab48f143ac5115b0441aced/lib/parcel_api/label.rb#L37-L42 | train |
bilus/akasha | lib/akasha/event_router.rb | Akasha.EventRouter.connect! | def connect!(repository)
repository.subscribe do |aggregate_id, event|
route(event.name, aggregate_id, **event.data)
end
end | ruby | def connect!(repository)
repository.subscribe do |aggregate_id, event|
route(event.name, aggregate_id, **event.data)
end
end | [
"def",
"connect!",
"(",
"repository",
")",
"repository",
".",
"subscribe",
"do",
"|",
"aggregate_id",
",",
"event",
"|",
"route",
"(",
"event",
".",
"name",
",",
"aggregate_id",
",",
"**",
"event",
".",
"data",
")",
"end",
"end"
] | Connects to the repository. | [
"Connects",
"to",
"the",
"repository",
"."
] | 5fadefc249f520ae909b762956ac23a6f916b021 | https://github.com/bilus/akasha/blob/5fadefc249f520ae909b762956ac23a6f916b021/lib/akasha/event_router.rb#L9-L13 | train |
jodigiordano/calendarize | app/helpers/calendarize_helper.rb | CalendarizeHelper.MonthlyCalendarBuilder.days_range | def days_range
ws = Date::DAYS_INTO_WEEK[@options[:week_start]]
(ws...ws+number_of_days_per_week).map{ |d| d % 7 }
end | ruby | def days_range
ws = Date::DAYS_INTO_WEEK[@options[:week_start]]
(ws...ws+number_of_days_per_week).map{ |d| d % 7 }
end | [
"def",
"days_range",
"ws",
"=",
"Date",
"::",
"DAYS_INTO_WEEK",
"[",
"@options",
"[",
":week_start",
"]",
"]",
"(",
"ws",
"...",
"ws",
"+",
"number_of_days_per_week",
")",
".",
"map",
"{",
"|",
"d",
"|",
"d",
"%",
"7",
"}",
"end"
] | Get the range of days to show | [
"Get",
"the",
"range",
"of",
"days",
"to",
"show"
] | 9131ead3434066367f5ccfce58eaaec9ba406678 | https://github.com/jodigiordano/calendarize/blob/9131ead3434066367f5ccfce58eaaec9ba406678/app/helpers/calendarize_helper.rb#L1008-L1011 | train |
jodigiordano/calendarize | app/helpers/calendarize_helper.rb | CalendarizeHelper.MonthlyCalendarBuilder.row_to_day | def row_to_day(i, j)
starting_wday = @day_start.wday - 1
starting_wday = 6 if starting_wday < 0
# day without taking into account the :week_start so every 1st
# of the month is on a :monday on case [0, 0]
base = (i * 7) + j
# we add the :week_start
base += Date::DAYS_INTO_WEEK[@options[:week_start]]
# we adjust with the starting day of the month
base -= starting_wday
base += 1
return nil if base < 1 || base > days_in_month(@day_start)
base
end | ruby | def row_to_day(i, j)
starting_wday = @day_start.wday - 1
starting_wday = 6 if starting_wday < 0
# day without taking into account the :week_start so every 1st
# of the month is on a :monday on case [0, 0]
base = (i * 7) + j
# we add the :week_start
base += Date::DAYS_INTO_WEEK[@options[:week_start]]
# we adjust with the starting day of the month
base -= starting_wday
base += 1
return nil if base < 1 || base > days_in_month(@day_start)
base
end | [
"def",
"row_to_day",
"(",
"i",
",",
"j",
")",
"starting_wday",
"=",
"@day_start",
".",
"wday",
"-",
"1",
"starting_wday",
"=",
"6",
"if",
"starting_wday",
"<",
"0",
"base",
"=",
"(",
"i",
"*",
"7",
")",
"+",
"j",
"base",
"+=",
"Date",
"::",
"DAYS_INTO_WEEK",
"[",
"@options",
"[",
":week_start",
"]",
"]",
"base",
"-=",
"starting_wday",
"base",
"+=",
"1",
"return",
"nil",
"if",
"base",
"<",
"1",
"||",
"base",
">",
"days_in_month",
"(",
"@day_start",
")",
"base",
"end"
] | Get the month's day corresponding to a row. Nil is returned if none. | [
"Get",
"the",
"month",
"s",
"day",
"corresponding",
"to",
"a",
"row",
".",
"Nil",
"is",
"returned",
"if",
"none",
"."
] | 9131ead3434066367f5ccfce58eaaec9ba406678 | https://github.com/jodigiordano/calendarize/blob/9131ead3434066367f5ccfce58eaaec9ba406678/app/helpers/calendarize_helper.rb#L1031-L1049 | train |
coreyward/typekit | lib/typekit/variation.rb | Typekit.Variation.fetch | def fetch(attribute)
family_id, variation_id = @id.split(':')
mass_assign Client.get("/families/#{family_id}/#{variation_id}")
attribute ? instance_variable_get("@#{attribute}") : self
end | ruby | def fetch(attribute)
family_id, variation_id = @id.split(':')
mass_assign Client.get("/families/#{family_id}/#{variation_id}")
attribute ? instance_variable_get("@#{attribute}") : self
end | [
"def",
"fetch",
"(",
"attribute",
")",
"family_id",
",",
"variation_id",
"=",
"@id",
".",
"split",
"(",
"':'",
")",
"mass_assign",
"Client",
".",
"get",
"(",
"\"/families/#{family_id}/#{variation_id}\"",
")",
"attribute",
"?",
"instance_variable_get",
"(",
"\"@#{attribute}\"",
")",
":",
"self",
"end"
] | Get detailed information about this Family Variation from Typekit
@note This is called lazily when you access any non-loaded attribute
and doesn't need to be called manually unless you want to reload the
data. This means we can return an array of Variation objects for {Family#variations}
without making N+1 requests to the API.
@param attribute [Symbol] Optionally return a single attribute after data is loaded
@return Returns @attribute if attribute argument is specified; otherwise returns self | [
"Get",
"detailed",
"information",
"about",
"this",
"Family",
"Variation",
"from",
"Typekit"
] | 1e9f3749ad6066eec7fbdad50abe2ab5802e32d0 | https://github.com/coreyward/typekit/blob/1e9f3749ad6066eec7fbdad50abe2ab5802e32d0/lib/typekit/variation.rb#L30-L34 | train |
wikiti/scaleapi-ruby | lib/scale/api.rb | Scale.API.method_missing | def method_missing(m, *array)
endpoint = Scale.descendants(Scale::Endpoints::Endpoint).find { |e| e.match? m }
return endpoint.new(self, *array).process if endpoint
super
end | ruby | def method_missing(m, *array)
endpoint = Scale.descendants(Scale::Endpoints::Endpoint).find { |e| e.match? m }
return endpoint.new(self, *array).process if endpoint
super
end | [
"def",
"method_missing",
"(",
"m",
",",
"*",
"array",
")",
"endpoint",
"=",
"Scale",
".",
"descendants",
"(",
"Scale",
"::",
"Endpoints",
"::",
"Endpoint",
")",
".",
"find",
"{",
"|",
"e",
"|",
"e",
".",
"match?",
"m",
"}",
"return",
"endpoint",
".",
"new",
"(",
"self",
",",
"*",
"array",
")",
".",
"process",
"if",
"endpoint",
"super",
"end"
] | Endpoint helper. If the method is not defined, then try looking into the available endpoints. | [
"Endpoint",
"helper",
".",
"If",
"the",
"method",
"is",
"not",
"defined",
"then",
"try",
"looking",
"into",
"the",
"available",
"endpoints",
"."
] | aece53c99e135bdf018f35f0c68aa673f3377258 | https://github.com/wikiti/scaleapi-ruby/blob/aece53c99e135bdf018f35f0c68aa673f3377258/lib/scale/api.rb#L50-L54 | train |
mirego/bourgeois | lib/bourgeois/presenter.rb | Bourgeois.Presenter.execute_helper | def execute_helper(block, opts)
if_condition = execute_helper_condition(opts[:if])
unless_condition = !execute_helper_condition(opts[:unless], false)
block.call if if_condition && unless_condition
end | ruby | def execute_helper(block, opts)
if_condition = execute_helper_condition(opts[:if])
unless_condition = !execute_helper_condition(opts[:unless], false)
block.call if if_condition && unless_condition
end | [
"def",
"execute_helper",
"(",
"block",
",",
"opts",
")",
"if_condition",
"=",
"execute_helper_condition",
"(",
"opts",
"[",
":if",
"]",
")",
"unless_condition",
"=",
"!",
"execute_helper_condition",
"(",
"opts",
"[",
":unless",
"]",
",",
"false",
")",
"block",
".",
"call",
"if",
"if_condition",
"&&",
"unless_condition",
"end"
] | Execute a helper block if it matches conditions | [
"Execute",
"a",
"helper",
"block",
"if",
"it",
"matches",
"conditions"
] | 94618e0c442f8ac4c91ddc6623ee3e03c3665c4f | https://github.com/mirego/bourgeois/blob/94618e0c442f8ac4c91ddc6623ee3e03c3665c4f/lib/bourgeois/presenter.rb#L92-L97 | train |
jarhart/rattler | lib/rattler/runtime/parse_node.rb | Rattler::Runtime.ParseNode.method_missing | def method_missing(symbol, *args)
(args.empty? and labeled.has_key?(symbol)) ? labeled[symbol] : super
end | ruby | def method_missing(symbol, *args)
(args.empty? and labeled.has_key?(symbol)) ? labeled[symbol] : super
end | [
"def",
"method_missing",
"(",
"symbol",
",",
"*",
"args",
")",
"(",
"args",
".",
"empty?",
"and",
"labeled",
".",
"has_key?",
"(",
"symbol",
")",
")",
"?",
"labeled",
"[",
"symbol",
"]",
":",
"super",
"end"
] | Return +true+ if the node has the same value as +other+, i.e. +other+
is an instance of the same class and has equal children and attributes
and the children are labeled the same.
@return [Boolean] +true+ the node has the same value as +other+
Allow labeled children to be accessed as methods. | [
"Return",
"+",
"true",
"+",
"if",
"the",
"node",
"has",
"the",
"same",
"value",
"as",
"+",
"other",
"+",
"i",
".",
"e",
".",
"+",
"other",
"+",
"is",
"an",
"instance",
"of",
"the",
"same",
"class",
"and",
"has",
"equal",
"children",
"and",
"attributes",
"and",
"the",
"children",
"are",
"labeled",
"the",
"same",
"."
] | 8b4efde2a05e9e790955bb635d4a1a9615893719 | https://github.com/jarhart/rattler/blob/8b4efde2a05e9e790955bb635d4a1a9615893719/lib/rattler/runtime/parse_node.rb#L66-L68 | train |
profitbricks/profitbricks-sdk-ruby | lib/profitbricks/volume.rb | ProfitBricks.Volume.create_snapshot | def create_snapshot(options = {})
response = ProfitBricks.request(
method: :post,
path: "/datacenters/#{datacenterId}/volumes/#{id}/create-snapshot",
headers: { 'Content-Type' => 'application/x-www-form-urlencoded' },
expects: 202,
body: URI.encode_www_form(options)
)
ProfitBricks::Snapshot.new(response)
end | ruby | def create_snapshot(options = {})
response = ProfitBricks.request(
method: :post,
path: "/datacenters/#{datacenterId}/volumes/#{id}/create-snapshot",
headers: { 'Content-Type' => 'application/x-www-form-urlencoded' },
expects: 202,
body: URI.encode_www_form(options)
)
ProfitBricks::Snapshot.new(response)
end | [
"def",
"create_snapshot",
"(",
"options",
"=",
"{",
"}",
")",
"response",
"=",
"ProfitBricks",
".",
"request",
"(",
"method",
":",
":post",
",",
"path",
":",
"\"/datacenters/#{datacenterId}/volumes/#{id}/create-snapshot\"",
",",
"headers",
":",
"{",
"'Content-Type'",
"=>",
"'application/x-www-form-urlencoded'",
"}",
",",
"expects",
":",
"202",
",",
"body",
":",
"URI",
".",
"encode_www_form",
"(",
"options",
")",
")",
"ProfitBricks",
"::",
"Snapshot",
".",
"new",
"(",
"response",
")",
"end"
] | Create volume snapshot.
==== Parameters
* +options+<Hash>:
- +name+<String> - *Optional*, name of the snapshot
- +description+<String> - *Optional*, description of the snapshot
==== Returns
* +id+<String> - Universally unique identifer of resource
* +type+<String> - Resource type
* +href+<String> - Resource URL representation
* +metadata+<Hash>:
- +lastModifiedDate+
- +lastModifiedBy+
- +createdDate+
- +createdBy+
- +state+
- +etag+
* +properties+<Hash>:
- +name+<Integer>
- +description+<Array>
- +location+<String>
- +cpuHotPlug+<Boolean>
- +cpuHotUnPlug+<Boolean>
- +ramHotPlug+<Boolean>
- +ramHotUnPlug+<Boolean>
- +nicHotPlug+<Boolean>
- +nicHotUnPlug+<Boolean>
- +discVirtioHotPlug+<Boolean>
- +discVirtioHotUnPlug+<Boolean>
- +discScsiHotPlug+<Boolean>
- +discScsiHotUnPlug+<Boolean>
- +licenceType+<String> | [
"Create",
"volume",
"snapshot",
"."
] | 03a379e412b0e6c0789ed14f2449f18bda622742 | https://github.com/profitbricks/profitbricks-sdk-ruby/blob/03a379e412b0e6c0789ed14f2449f18bda622742/lib/profitbricks/volume.rb#L84-L93 | train |
kamui/rack-accept_headers | lib/rack/accept_headers/header.rb | Rack::AcceptHeaders.Header.parse_range_params | def parse_range_params(params)
params.split(';').inject({'q' => '1'}) do |m, p|
k, v = p.split('=', 2)
m[k.strip] = v.strip if v
m
end
end | ruby | def parse_range_params(params)
params.split(';').inject({'q' => '1'}) do |m, p|
k, v = p.split('=', 2)
m[k.strip] = v.strip if v
m
end
end | [
"def",
"parse_range_params",
"(",
"params",
")",
"params",
".",
"split",
"(",
"';'",
")",
".",
"inject",
"(",
"{",
"'q'",
"=>",
"'1'",
"}",
")",
"do",
"|",
"m",
",",
"p",
"|",
"k",
",",
"v",
"=",
"p",
".",
"split",
"(",
"'='",
",",
"2",
")",
"m",
"[",
"k",
".",
"strip",
"]",
"=",
"v",
".",
"strip",
"if",
"v",
"m",
"end",
"end"
] | Parses a string of media type range parameters into a hash of parameters
to their respective values. | [
"Parses",
"a",
"string",
"of",
"media",
"type",
"range",
"parameters",
"into",
"a",
"hash",
"of",
"parameters",
"to",
"their",
"respective",
"values",
"."
] | 099bfbb919de86b5842c8e14be42b8b784e53f03 | https://github.com/kamui/rack-accept_headers/blob/099bfbb919de86b5842c8e14be42b8b784e53f03/lib/rack/accept_headers/header.rb#L50-L56 | train |
kamui/rack-accept_headers | lib/rack/accept_headers/header.rb | Rack::AcceptHeaders.Header.normalize_qvalue | def normalize_qvalue(q)
(q == 1 || q == 0) && q.is_a?(Float) ? q.to_i : q
end | ruby | def normalize_qvalue(q)
(q == 1 || q == 0) && q.is_a?(Float) ? q.to_i : q
end | [
"def",
"normalize_qvalue",
"(",
"q",
")",
"(",
"q",
"==",
"1",
"||",
"q",
"==",
"0",
")",
"&&",
"q",
".",
"is_a?",
"(",
"Float",
")",
"?",
"q",
".",
"to_i",
":",
"q",
"end"
] | Converts 1.0 and 0.0 qvalues to 1 and 0 respectively. Used to maintain
consistency across qvalue methods. | [
"Converts",
"1",
".",
"0",
"and",
"0",
".",
"0",
"qvalues",
"to",
"1",
"and",
"0",
"respectively",
".",
"Used",
"to",
"maintain",
"consistency",
"across",
"qvalue",
"methods",
"."
] | 099bfbb919de86b5842c8e14be42b8b784e53f03 | https://github.com/kamui/rack-accept_headers/blob/099bfbb919de86b5842c8e14be42b8b784e53f03/lib/rack/accept_headers/header.rb#L61-L63 | train |
jduckett/duck_map | lib/duck_map/route_filter.rb | DuckMap.RouteFilter.match_any? | def match_any?(data = nil, values = [])
unless data.blank?
unless values.kind_of?(Array)
# wow, this worked!!??
# values was not an array, so, add values to a new array and assign back to values
values = [values]
end
values.each do |value|
if value.kind_of?(String) && (data.to_s.downcase.eql?(value.downcase) || value.eql?("all"))
return true
elsif value.kind_of?(Symbol) && (data.downcase.to_sym.eql?(value) || value.eql?(:all))
return true
elsif value.kind_of?(Regexp) && data.match(value)
return true
end
end
end
return false
end | ruby | def match_any?(data = nil, values = [])
unless data.blank?
unless values.kind_of?(Array)
# wow, this worked!!??
# values was not an array, so, add values to a new array and assign back to values
values = [values]
end
values.each do |value|
if value.kind_of?(String) && (data.to_s.downcase.eql?(value.downcase) || value.eql?("all"))
return true
elsif value.kind_of?(Symbol) && (data.downcase.to_sym.eql?(value) || value.eql?(:all))
return true
elsif value.kind_of?(Regexp) && data.match(value)
return true
end
end
end
return false
end | [
"def",
"match_any?",
"(",
"data",
"=",
"nil",
",",
"values",
"=",
"[",
"]",
")",
"unless",
"data",
".",
"blank?",
"unless",
"values",
".",
"kind_of?",
"(",
"Array",
")",
"values",
"=",
"[",
"values",
"]",
"end",
"values",
".",
"each",
"do",
"|",
"value",
"|",
"if",
"value",
".",
"kind_of?",
"(",
"String",
")",
"&&",
"(",
"data",
".",
"to_s",
".",
"downcase",
".",
"eql?",
"(",
"value",
".",
"downcase",
")",
"||",
"value",
".",
"eql?",
"(",
"\"all\"",
")",
")",
"return",
"true",
"elsif",
"value",
".",
"kind_of?",
"(",
"Symbol",
")",
"&&",
"(",
"data",
".",
"downcase",
".",
"to_sym",
".",
"eql?",
"(",
"value",
")",
"||",
"value",
".",
"eql?",
"(",
":all",
")",
")",
"return",
"true",
"elsif",
"value",
".",
"kind_of?",
"(",
"Regexp",
")",
"&&",
"data",
".",
"match",
"(",
"value",
")",
"return",
"true",
"end",
"end",
"end",
"return",
"false",
"end"
] | Matches a single value against an array of Strings, Symbols, and Regexp's.
@param [String] data Any value as a String to compare against any of the Strings, Symbols, or Regexp's in the values argument.
@param [Array] values An array of Strings, Symbols, or Regexp's to compare against the data argument. The array can be a mix of all three possible types.
@return [Boolean] True if data matches any of the values or expressions in the values argument, otherwise, false. | [
"Matches",
"a",
"single",
"value",
"against",
"an",
"array",
"of",
"Strings",
"Symbols",
"and",
"Regexp",
"s",
"."
] | c510acfa95e8ad4afb1501366058ae88a73704df | https://github.com/jduckett/duck_map/blob/c510acfa95e8ad4afb1501366058ae88a73704df/lib/duck_map/route_filter.rb#L161-L188 | train |
crowdint/cached_belongs_to | lib/cached_belongs_to.rb | CachedBelongsTo.ClassMethods.cached_belongs_to | def cached_belongs_to(*args)
caches = Array(args[1].delete(:caches))
association = belongs_to(*args)
create_cached_belongs_to_child_callbacks(caches, association)
create_cached_belongs_to_parent_callbacks(caches, association)
end | ruby | def cached_belongs_to(*args)
caches = Array(args[1].delete(:caches))
association = belongs_to(*args)
create_cached_belongs_to_child_callbacks(caches, association)
create_cached_belongs_to_parent_callbacks(caches, association)
end | [
"def",
"cached_belongs_to",
"(",
"*",
"args",
")",
"caches",
"=",
"Array",
"(",
"args",
"[",
"1",
"]",
".",
"delete",
"(",
":caches",
")",
")",
"association",
"=",
"belongs_to",
"(",
"*",
"args",
")",
"create_cached_belongs_to_child_callbacks",
"(",
"caches",
",",
"association",
")",
"create_cached_belongs_to_parent_callbacks",
"(",
"caches",
",",
"association",
")",
"end"
] | Creates a many to one association between two models. Works
exactly as ActiveRecord's belongs_to, except that it adds
caching to it.
Usage:
class Book < ActiveRecord::Base
cached_belongs_to :author, :caches => :name
end | [
"Creates",
"a",
"many",
"to",
"one",
"association",
"between",
"two",
"models",
".",
"Works",
"exactly",
"as",
"ActiveRecord",
"s",
"belongs_to",
"except",
"that",
"it",
"adds",
"caching",
"to",
"it",
"."
] | 7dc5c07ff1a622286fdc739d0a98a7788bd2f13e | https://github.com/crowdint/cached_belongs_to/blob/7dc5c07ff1a622286fdc739d0a98a7788bd2f13e/lib/cached_belongs_to.rb#L17-L23 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.