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 |
---|---|---|---|---|---|---|---|---|---|---|---|
google/google-id-token | lib/google-id-token.rb | GoogleIDToken.Validator.check | def check(token, aud, cid = nil)
synchronize do
payload = check_cached_certs(token, aud, cid)
unless payload
# no certs worked, might've expired, refresh
if refresh_certs
payload = check_cached_certs(token, aud, cid)
unless payload
raise SignatureError, 'Token not verified as issued by Google'
end
else
raise CertificateError, 'Unable to retrieve Google public keys'
end
end
payload
end
end | ruby | def check(token, aud, cid = nil)
synchronize do
payload = check_cached_certs(token, aud, cid)
unless payload
# no certs worked, might've expired, refresh
if refresh_certs
payload = check_cached_certs(token, aud, cid)
unless payload
raise SignatureError, 'Token not verified as issued by Google'
end
else
raise CertificateError, 'Unable to retrieve Google public keys'
end
end
payload
end
end | [
"def",
"check",
"(",
"token",
",",
"aud",
",",
"cid",
"=",
"nil",
")",
"synchronize",
"do",
"payload",
"=",
"check_cached_certs",
"(",
"token",
",",
"aud",
",",
"cid",
")",
"unless",
"payload",
"# no certs worked, might've expired, refresh",
"if",
"refresh_certs",
"payload",
"=",
"check_cached_certs",
"(",
"token",
",",
"aud",
",",
"cid",
")",
"unless",
"payload",
"raise",
"SignatureError",
",",
"'Token not verified as issued by Google'",
"end",
"else",
"raise",
"CertificateError",
",",
"'Unable to retrieve Google public keys'",
"end",
"end",
"payload",
"end",
"end"
] | If it validates, returns a hash with the JWT payload from the ID Token.
You have to provide an "aud" value, which must match the
token's field with that name, and will similarly check cid if provided.
If something fails, raises an error
@param [String] token
The string form of the token
@param [String] aud
The required audience value
@param [String] cid
The optional client-id ("azp" field) value
@return [Hash] The decoded ID token | [
"If",
"it",
"validates",
"returns",
"a",
"hash",
"with",
"the",
"JWT",
"payload",
"from",
"the",
"ID",
"Token",
".",
"You",
"have",
"to",
"provide",
"an",
"aud",
"value",
"which",
"must",
"match",
"the",
"token",
"s",
"field",
"with",
"that",
"name",
"and",
"will",
"similarly",
"check",
"cid",
"if",
"provided",
"."
] | 2cfd6876856995df3d96fa8f3b8e9137526bfb46 | https://github.com/google/google-id-token/blob/2cfd6876856995df3d96fa8f3b8e9137526bfb46/lib/google-id-token.rb#L82-L101 | train |
google/google-id-token | lib/google-id-token.rb | GoogleIDToken.Validator.check_cached_certs | def check_cached_certs(token, aud, cid)
payload = nil
# find first public key that validates this token
@certs.detect do |key, cert|
begin
public_key = cert.public_key
decoded_token = JWT.decode(token, public_key, !!public_key, { :algorithm => 'RS256' })
payload = decoded_token.first
# in Feb 2013, the 'cid' claim became the 'azp' claim per changes
# in the OIDC draft. At some future point we can go all-azp, but
# this should keep everything running for a while
if payload['azp']
payload['cid'] = payload['azp']
elsif payload['cid']
payload['azp'] = payload['cid']
end
payload
rescue JWT::ExpiredSignature
raise ExpiredTokenError, 'Token signature is expired'
rescue JWT::DecodeError
nil # go on, try the next cert
end
end
if payload
if !(payload.has_key?('aud') && payload['aud'] == aud)
raise AudienceMismatchError, 'Token audience mismatch'
end
if cid && payload['cid'] != cid
raise ClientIDMismatchError, 'Token client-id mismatch'
end
if !GOOGLE_ISSUERS.include?(payload['iss'])
raise InvalidIssuerError, 'Token issuer mismatch'
end
payload
else
nil
end
end | ruby | def check_cached_certs(token, aud, cid)
payload = nil
# find first public key that validates this token
@certs.detect do |key, cert|
begin
public_key = cert.public_key
decoded_token = JWT.decode(token, public_key, !!public_key, { :algorithm => 'RS256' })
payload = decoded_token.first
# in Feb 2013, the 'cid' claim became the 'azp' claim per changes
# in the OIDC draft. At some future point we can go all-azp, but
# this should keep everything running for a while
if payload['azp']
payload['cid'] = payload['azp']
elsif payload['cid']
payload['azp'] = payload['cid']
end
payload
rescue JWT::ExpiredSignature
raise ExpiredTokenError, 'Token signature is expired'
rescue JWT::DecodeError
nil # go on, try the next cert
end
end
if payload
if !(payload.has_key?('aud') && payload['aud'] == aud)
raise AudienceMismatchError, 'Token audience mismatch'
end
if cid && payload['cid'] != cid
raise ClientIDMismatchError, 'Token client-id mismatch'
end
if !GOOGLE_ISSUERS.include?(payload['iss'])
raise InvalidIssuerError, 'Token issuer mismatch'
end
payload
else
nil
end
end | [
"def",
"check_cached_certs",
"(",
"token",
",",
"aud",
",",
"cid",
")",
"payload",
"=",
"nil",
"# find first public key that validates this token",
"@certs",
".",
"detect",
"do",
"|",
"key",
",",
"cert",
"|",
"begin",
"public_key",
"=",
"cert",
".",
"public_key",
"decoded_token",
"=",
"JWT",
".",
"decode",
"(",
"token",
",",
"public_key",
",",
"!",
"!",
"public_key",
",",
"{",
":algorithm",
"=>",
"'RS256'",
"}",
")",
"payload",
"=",
"decoded_token",
".",
"first",
"# in Feb 2013, the 'cid' claim became the 'azp' claim per changes",
"# in the OIDC draft. At some future point we can go all-azp, but",
"# this should keep everything running for a while",
"if",
"payload",
"[",
"'azp'",
"]",
"payload",
"[",
"'cid'",
"]",
"=",
"payload",
"[",
"'azp'",
"]",
"elsif",
"payload",
"[",
"'cid'",
"]",
"payload",
"[",
"'azp'",
"]",
"=",
"payload",
"[",
"'cid'",
"]",
"end",
"payload",
"rescue",
"JWT",
"::",
"ExpiredSignature",
"raise",
"ExpiredTokenError",
",",
"'Token signature is expired'",
"rescue",
"JWT",
"::",
"DecodeError",
"nil",
"# go on, try the next cert",
"end",
"end",
"if",
"payload",
"if",
"!",
"(",
"payload",
".",
"has_key?",
"(",
"'aud'",
")",
"&&",
"payload",
"[",
"'aud'",
"]",
"==",
"aud",
")",
"raise",
"AudienceMismatchError",
",",
"'Token audience mismatch'",
"end",
"if",
"cid",
"&&",
"payload",
"[",
"'cid'",
"]",
"!=",
"cid",
"raise",
"ClientIDMismatchError",
",",
"'Token client-id mismatch'",
"end",
"if",
"!",
"GOOGLE_ISSUERS",
".",
"include?",
"(",
"payload",
"[",
"'iss'",
"]",
")",
"raise",
"InvalidIssuerError",
",",
"'Token issuer mismatch'",
"end",
"payload",
"else",
"nil",
"end",
"end"
] | tries to validate the token against each cached cert.
Returns the token payload or raises a ValidationError or
nil, which means none of the certs validated. | [
"tries",
"to",
"validate",
"the",
"token",
"against",
"each",
"cached",
"cert",
".",
"Returns",
"the",
"token",
"payload",
"or",
"raises",
"a",
"ValidationError",
"or",
"nil",
"which",
"means",
"none",
"of",
"the",
"certs",
"validated",
"."
] | 2cfd6876856995df3d96fa8f3b8e9137526bfb46 | https://github.com/google/google-id-token/blob/2cfd6876856995df3d96fa8f3b8e9137526bfb46/lib/google-id-token.rb#L108-L148 | train |
walle/gimli | lib/gimli/wkhtmltopdf.rb | Gimli.Wkhtmltopdf.output_pdf | def output_pdf(html, filename)
args = command(filename)
invoke = args.join(' ')
IO.popen(invoke, "wb+") do |pdf|
pdf.puts(html)
pdf.close_write
pdf.gets(nil)
end
end | ruby | def output_pdf(html, filename)
args = command(filename)
invoke = args.join(' ')
IO.popen(invoke, "wb+") do |pdf|
pdf.puts(html)
pdf.close_write
pdf.gets(nil)
end
end | [
"def",
"output_pdf",
"(",
"html",
",",
"filename",
")",
"args",
"=",
"command",
"(",
"filename",
")",
"invoke",
"=",
"args",
".",
"join",
"(",
"' '",
")",
"IO",
".",
"popen",
"(",
"invoke",
",",
"\"wb+\"",
")",
"do",
"|",
"pdf",
"|",
"pdf",
".",
"puts",
"(",
"html",
")",
"pdf",
".",
"close_write",
"pdf",
".",
"gets",
"(",
"nil",
")",
"end",
"end"
] | Set up options for wkhtmltopdf
@param [String] parameters
Convert the html to pdf and write it to file
@param [String] html the html input
@param [String] filename the name of the output file | [
"Set",
"up",
"options",
"for",
"wkhtmltopdf"
] | 17f46bb860545ae155f93bc29c55c7487d29169b | https://github.com/walle/gimli/blob/17f46bb860545ae155f93bc29c55c7487d29169b/lib/gimli/wkhtmltopdf.rb#L15-L24 | train |
walle/gimli | lib/gimli/converter.rb | Gimli.Converter.convert! | def convert!
merged_contents = []
@files.each do |file|
markup = Markup::Renderer.new file, @config.remove_front_matter
html = convert_image_urls markup.render, file.filename
if @config.merge
html = "<div class=\"page-break\"></div>#{html}" unless merged_contents.empty?
merged_contents << html
else
output_pdf(html, file)
end
puts html if @config.debug
end
unless merged_contents.empty?
html = merged_contents.join
output_pdf(html, nil)
end
end | ruby | def convert!
merged_contents = []
@files.each do |file|
markup = Markup::Renderer.new file, @config.remove_front_matter
html = convert_image_urls markup.render, file.filename
if @config.merge
html = "<div class=\"page-break\"></div>#{html}" unless merged_contents.empty?
merged_contents << html
else
output_pdf(html, file)
end
puts html if @config.debug
end
unless merged_contents.empty?
html = merged_contents.join
output_pdf(html, nil)
end
end | [
"def",
"convert!",
"merged_contents",
"=",
"[",
"]",
"@files",
".",
"each",
"do",
"|",
"file",
"|",
"markup",
"=",
"Markup",
"::",
"Renderer",
".",
"new",
"file",
",",
"@config",
".",
"remove_front_matter",
"html",
"=",
"convert_image_urls",
"markup",
".",
"render",
",",
"file",
".",
"filename",
"if",
"@config",
".",
"merge",
"html",
"=",
"\"<div class=\\\"page-break\\\"></div>#{html}\"",
"unless",
"merged_contents",
".",
"empty?",
"merged_contents",
"<<",
"html",
"else",
"output_pdf",
"(",
"html",
",",
"file",
")",
"end",
"puts",
"html",
"if",
"@config",
".",
"debug",
"end",
"unless",
"merged_contents",
".",
"empty?",
"html",
"=",
"merged_contents",
".",
"join",
"output_pdf",
"(",
"html",
",",
"nil",
")",
"end",
"end"
] | Initialize the converter with a File
@param [Array] files The list of Gimli::MarkupFile to convert (passing a single file will still work)
@param [Gimli::Config] config
Convert the file and save it as a PDF file | [
"Initialize",
"the",
"converter",
"with",
"a",
"File"
] | 17f46bb860545ae155f93bc29c55c7487d29169b | https://github.com/walle/gimli/blob/17f46bb860545ae155f93bc29c55c7487d29169b/lib/gimli/converter.rb#L29-L47 | train |
walle/gimli | lib/gimli/converter.rb | Gimli.Converter.convert_image_urls | def convert_image_urls(html, filename)
dir_string = ::File.dirname(::File.expand_path(filename))
html.scan(/<img[^>]+src="([^"]+)"/).each do |url|
html.gsub!(url[0], ::File.expand_path(url[0], dir_string)) unless url[0] =~ /^https?/
end
html
end | ruby | def convert_image_urls(html, filename)
dir_string = ::File.dirname(::File.expand_path(filename))
html.scan(/<img[^>]+src="([^"]+)"/).each do |url|
html.gsub!(url[0], ::File.expand_path(url[0], dir_string)) unless url[0] =~ /^https?/
end
html
end | [
"def",
"convert_image_urls",
"(",
"html",
",",
"filename",
")",
"dir_string",
"=",
"::",
"File",
".",
"dirname",
"(",
"::",
"File",
".",
"expand_path",
"(",
"filename",
")",
")",
"html",
".",
"scan",
"(",
"/",
"/",
")",
".",
"each",
"do",
"|",
"url",
"|",
"html",
".",
"gsub!",
"(",
"url",
"[",
"0",
"]",
",",
"::",
"File",
".",
"expand_path",
"(",
"url",
"[",
"0",
"]",
",",
"dir_string",
")",
")",
"unless",
"url",
"[",
"0",
"]",
"=~",
"/",
"/",
"end",
"html",
"end"
] | Rewrite relative image urls to absolute
@param [String] html some html to parse
@return [String] the html with all image urls replaced to absolute | [
"Rewrite",
"relative",
"image",
"urls",
"to",
"absolute"
] | 17f46bb860545ae155f93bc29c55c7487d29169b | https://github.com/walle/gimli/blob/17f46bb860545ae155f93bc29c55c7487d29169b/lib/gimli/converter.rb#L52-L59 | train |
walle/gimli | lib/gimli/converter.rb | Gimli.Converter.output_pdf | def output_pdf(html, filename)
html = add_head html
load_stylesheets
generate_cover!
append_stylesheets html
puts @wkhtmltopdf.command(output_file(filename)).join(' ') if @config.debug
@wkhtmltopdf.output_pdf html, output_file(filename)
end | ruby | def output_pdf(html, filename)
html = add_head html
load_stylesheets
generate_cover!
append_stylesheets html
puts @wkhtmltopdf.command(output_file(filename)).join(' ') if @config.debug
@wkhtmltopdf.output_pdf html, output_file(filename)
end | [
"def",
"output_pdf",
"(",
"html",
",",
"filename",
")",
"html",
"=",
"add_head",
"html",
"load_stylesheets",
"generate_cover!",
"append_stylesheets",
"html",
"puts",
"@wkhtmltopdf",
".",
"command",
"(",
"output_file",
"(",
"filename",
")",
")",
".",
"join",
"(",
"' '",
")",
"if",
"@config",
".",
"debug",
"@wkhtmltopdf",
".",
"output_pdf",
"html",
",",
"output_file",
"(",
"filename",
")",
"end"
] | Create the pdf
@param [String] html the html input
@param [String] filename the name of the output file | [
"Create",
"the",
"pdf"
] | 17f46bb860545ae155f93bc29c55c7487d29169b | https://github.com/walle/gimli/blob/17f46bb860545ae155f93bc29c55c7487d29169b/lib/gimli/converter.rb#L64-L71 | train |
walle/gimli | lib/gimli/converter.rb | Gimli.Converter.load_stylesheets | def load_stylesheets
# Load standard stylesheet
style = ::File.expand_path("../../../config/style.css", __FILE__)
@stylesheets << style
@stylesheets << stylesheet if ::File.exists?(stylesheet)
end | ruby | def load_stylesheets
# Load standard stylesheet
style = ::File.expand_path("../../../config/style.css", __FILE__)
@stylesheets << style
@stylesheets << stylesheet if ::File.exists?(stylesheet)
end | [
"def",
"load_stylesheets",
"# Load standard stylesheet",
"style",
"=",
"::",
"File",
".",
"expand_path",
"(",
"\"../../../config/style.css\"",
",",
"__FILE__",
")",
"@stylesheets",
"<<",
"style",
"@stylesheets",
"<<",
"stylesheet",
"if",
"::",
"File",
".",
"exists?",
"(",
"stylesheet",
")",
"end"
] | Load the stylesheets to pdfkit loads the default and the user selected if any | [
"Load",
"the",
"stylesheets",
"to",
"pdfkit",
"loads",
"the",
"default",
"and",
"the",
"user",
"selected",
"if",
"any"
] | 17f46bb860545ae155f93bc29c55c7487d29169b | https://github.com/walle/gimli/blob/17f46bb860545ae155f93bc29c55c7487d29169b/lib/gimli/converter.rb#L78-L83 | train |
walle/gimli | lib/gimli/converter.rb | Gimli.Converter.output_file | def output_file(file = nil)
if file
output_filename = file.name
if [email protected]_filename.nil? && @files.length == 1
output_filename = @config.output_filename
end
else
output_filename = Time.now.to_s.split(' ').join('_')
output_filename = @files.last.name if @files.length == 1 || @config.merge
output_filename = @config.output_filename unless @config.output_filename.nil?
end
::File.join(output_dir, "#{output_filename}.pdf")
end | ruby | def output_file(file = nil)
if file
output_filename = file.name
if [email protected]_filename.nil? && @files.length == 1
output_filename = @config.output_filename
end
else
output_filename = Time.now.to_s.split(' ').join('_')
output_filename = @files.last.name if @files.length == 1 || @config.merge
output_filename = @config.output_filename unless @config.output_filename.nil?
end
::File.join(output_dir, "#{output_filename}.pdf")
end | [
"def",
"output_file",
"(",
"file",
"=",
"nil",
")",
"if",
"file",
"output_filename",
"=",
"file",
".",
"name",
"if",
"!",
"@config",
".",
"output_filename",
".",
"nil?",
"&&",
"@files",
".",
"length",
"==",
"1",
"output_filename",
"=",
"@config",
".",
"output_filename",
"end",
"else",
"output_filename",
"=",
"Time",
".",
"now",
".",
"to_s",
".",
"split",
"(",
"' '",
")",
".",
"join",
"(",
"'_'",
")",
"output_filename",
"=",
"@files",
".",
"last",
".",
"name",
"if",
"@files",
".",
"length",
"==",
"1",
"||",
"@config",
".",
"merge",
"output_filename",
"=",
"@config",
".",
"output_filename",
"unless",
"@config",
".",
"output_filename",
".",
"nil?",
"end",
"::",
"File",
".",
"join",
"(",
"output_dir",
",",
"\"#{output_filename}.pdf\"",
")",
"end"
] | Generate the name of the output file
@return [String]
@param [Gimli::MarkupFile] file optionally, specify a file, otherwise use output filename | [
"Generate",
"the",
"name",
"of",
"the",
"output",
"file"
] | 17f46bb860545ae155f93bc29c55c7487d29169b | https://github.com/walle/gimli/blob/17f46bb860545ae155f93bc29c55c7487d29169b/lib/gimli/converter.rb#L112-L125 | train |
walle/gimli | lib/gimli/converter.rb | Gimli.Converter.generate_cover! | def generate_cover!
return unless @config.cover
cover_file = MarkupFile.new @config.cover
markup = Markup::Renderer.new cover_file
html = "<div class=\"cover\">\n#{markup.render}\n</div>"
append_stylesheets(html)
html = add_head(html)
@coverfile.write(html)
@coverfile.close
end | ruby | def generate_cover!
return unless @config.cover
cover_file = MarkupFile.new @config.cover
markup = Markup::Renderer.new cover_file
html = "<div class=\"cover\">\n#{markup.render}\n</div>"
append_stylesheets(html)
html = add_head(html)
@coverfile.write(html)
@coverfile.close
end | [
"def",
"generate_cover!",
"return",
"unless",
"@config",
".",
"cover",
"cover_file",
"=",
"MarkupFile",
".",
"new",
"@config",
".",
"cover",
"markup",
"=",
"Markup",
"::",
"Renderer",
".",
"new",
"cover_file",
"html",
"=",
"\"<div class=\\\"cover\\\">\\n#{markup.render}\\n</div>\"",
"append_stylesheets",
"(",
"html",
")",
"html",
"=",
"add_head",
"(",
"html",
")",
"@coverfile",
".",
"write",
"(",
"html",
")",
"@coverfile",
".",
"close",
"end"
] | Generate cover file if optional cover was given | [
"Generate",
"cover",
"file",
"if",
"optional",
"cover",
"was",
"given"
] | 17f46bb860545ae155f93bc29c55c7487d29169b | https://github.com/walle/gimli/blob/17f46bb860545ae155f93bc29c55c7487d29169b/lib/gimli/converter.rb#L128-L137 | train |
northworld/google_calendar | lib/google/calendar.rb | Google.Calendar.find_events_in_range | def find_events_in_range(start_min, start_max, options = {})
formatted_start_min = encode_time(start_min)
formatted_start_max = encode_time(start_max)
query = "?timeMin=#{formatted_start_min}&timeMax=#{formatted_start_max}#{parse_options(options)}"
event_lookup(query)
end | ruby | def find_events_in_range(start_min, start_max, options = {})
formatted_start_min = encode_time(start_min)
formatted_start_max = encode_time(start_max)
query = "?timeMin=#{formatted_start_min}&timeMax=#{formatted_start_max}#{parse_options(options)}"
event_lookup(query)
end | [
"def",
"find_events_in_range",
"(",
"start_min",
",",
"start_max",
",",
"options",
"=",
"{",
"}",
")",
"formatted_start_min",
"=",
"encode_time",
"(",
"start_min",
")",
"formatted_start_max",
"=",
"encode_time",
"(",
"start_max",
")",
"query",
"=",
"\"?timeMin=#{formatted_start_min}&timeMax=#{formatted_start_max}#{parse_options(options)}\"",
"event_lookup",
"(",
"query",
")",
"end"
] | Find all of the events associated with this calendar that start in the given time frame.
The lower bound is inclusive, whereas the upper bound is exclusive.
Events that overlap the range are included.
the +options+ parameter accepts
:max_results => the maximum number of results to return defaults to 25 the largest number Google accepts is 2500
:order_by => how you would like the results ordered, can be either 'startTime' or 'updated'. Defaults to 'startTime'. Note: it must be 'updated' if expand_recurring_events is set to false.
:expand_recurring_events => When set to true each instance of a recurring event is returned. Defaults to true.
Returns:
an empty array if nothing found.
an array with one element if only one found.
an array of events if many found. | [
"Find",
"all",
"of",
"the",
"events",
"associated",
"with",
"this",
"calendar",
"that",
"start",
"in",
"the",
"given",
"time",
"frame",
".",
"The",
"lower",
"bound",
"is",
"inclusive",
"whereas",
"the",
"upper",
"bound",
"is",
"exclusive",
".",
"Events",
"that",
"overlap",
"the",
"range",
"are",
"included",
"."
] | a81d685e432ce6c7e1838d14166fb1d5bab39685 | https://github.com/northworld/google_calendar/blob/a81d685e432ce6c7e1838d14166fb1d5bab39685/lib/google/calendar.rb#L260-L265 | train |
northworld/google_calendar | lib/google/calendar.rb | Google.Calendar.find_events_by_extended_properties | def find_events_by_extended_properties(extended_properties, options = {})
query = "?" + parse_extended_properties(extended_properties) + parse_options(options)
event_lookup(query)
end | ruby | def find_events_by_extended_properties(extended_properties, options = {})
query = "?" + parse_extended_properties(extended_properties) + parse_options(options)
event_lookup(query)
end | [
"def",
"find_events_by_extended_properties",
"(",
"extended_properties",
",",
"options",
"=",
"{",
"}",
")",
"query",
"=",
"\"?\"",
"+",
"parse_extended_properties",
"(",
"extended_properties",
")",
"+",
"parse_options",
"(",
"options",
")",
"event_lookup",
"(",
"query",
")",
"end"
] | Find all events that match at least one of the specified extended properties.
the +extended_properties+ parameter is set up the same way that it is configured when creating an event
for example, providing the following hash { 'shared' => {'p1' => 'v1', 'p2' => v2} } will return the list of events
that contain either v1 for shared extended property p1 or v2 for p2.
the +options+ parameter accepts
:max_results => the maximum number of results to return defaults to 25 the largest number Google accepts is 2500
:order_by => how you would like the results ordered, can be either 'startTime' or 'updated'. Defaults to 'startTime'. Note: it must be 'updated' if expand_recurring_events is set to false.
:expand_recurring_events => When set to true each instance of a recurring event is returned. Defaults to true.
Returns:
an empty array if nothing found.
an array with one element if only one found.
an array of events if many found. | [
"Find",
"all",
"events",
"that",
"match",
"at",
"least",
"one",
"of",
"the",
"specified",
"extended",
"properties",
"."
] | a81d685e432ce6c7e1838d14166fb1d5bab39685 | https://github.com/northworld/google_calendar/blob/a81d685e432ce6c7e1838d14166fb1d5bab39685/lib/google/calendar.rb#L303-L306 | train |
northworld/google_calendar | lib/google/calendar.rb | Google.Calendar.find_events_by_extended_properties_in_range | def find_events_by_extended_properties_in_range(extended_properties, start_min, start_max, options = {})
formatted_start_min = encode_time(start_min)
formatted_start_max = encode_time(start_max)
base_query = parse_extended_properties(extended_properties) + parse_options(options)
query = "?" + base_query + (base_query.empty? ? '' : '&') + "timeMin=#{formatted_start_min}&timeMax=#{formatted_start_max}"
event_lookup(query)
end | ruby | def find_events_by_extended_properties_in_range(extended_properties, start_min, start_max, options = {})
formatted_start_min = encode_time(start_min)
formatted_start_max = encode_time(start_max)
base_query = parse_extended_properties(extended_properties) + parse_options(options)
query = "?" + base_query + (base_query.empty? ? '' : '&') + "timeMin=#{formatted_start_min}&timeMax=#{formatted_start_max}"
event_lookup(query)
end | [
"def",
"find_events_by_extended_properties_in_range",
"(",
"extended_properties",
",",
"start_min",
",",
"start_max",
",",
"options",
"=",
"{",
"}",
")",
"formatted_start_min",
"=",
"encode_time",
"(",
"start_min",
")",
"formatted_start_max",
"=",
"encode_time",
"(",
"start_max",
")",
"base_query",
"=",
"parse_extended_properties",
"(",
"extended_properties",
")",
"+",
"parse_options",
"(",
"options",
")",
"query",
"=",
"\"?\"",
"+",
"base_query",
"+",
"(",
"base_query",
".",
"empty?",
"?",
"''",
":",
"'&'",
")",
"+",
"\"timeMin=#{formatted_start_min}&timeMax=#{formatted_start_max}\"",
"event_lookup",
"(",
"query",
")",
"end"
] | Find all events that match at least one of the specified extended properties within a given time frame.
The lower bound is inclusive, whereas the upper bound is exclusive.
Events that overlap the range are included.
the +extended_properties+ parameter is set up the same way that it is configured when creating an event
for example, providing the following hash { 'shared' => {'p1' => 'v1', 'p2' => v2} } will return the list of events
that contain either v1 for shared extended property p1 or v2 for p2.
the +options+ parameter accepts
:max_results => the maximum number of results to return defaults to 25 the largest number Google accepts is 2500
:order_by => how you would like the results ordered, can be either 'startTime' or 'updated'. Defaults to 'startTime'. Note: it must be 'updated' if expand_recurring_events is set to false.
:expand_recurring_events => When set to true each instance of a recurring event is returned. Defaults to true.
Returns:
an empty array if nothing found.
an array with one element if only one found.
an array of events if many found. | [
"Find",
"all",
"events",
"that",
"match",
"at",
"least",
"one",
"of",
"the",
"specified",
"extended",
"properties",
"within",
"a",
"given",
"time",
"frame",
".",
"The",
"lower",
"bound",
"is",
"inclusive",
"whereas",
"the",
"upper",
"bound",
"is",
"exclusive",
".",
"Events",
"that",
"overlap",
"the",
"range",
"are",
"included",
"."
] | a81d685e432ce6c7e1838d14166fb1d5bab39685 | https://github.com/northworld/google_calendar/blob/a81d685e432ce6c7e1838d14166fb1d5bab39685/lib/google/calendar.rb#L327-L333 | train |
northworld/google_calendar | lib/google/calendar.rb | Google.Calendar.find_or_create_event_by_id | def find_or_create_event_by_id(id, &blk)
event = id ? find_event_by_id(id)[0] : nil
if event
setup_event(event, &blk)
elsif id
event = Event.new(id: id, new_event_with_id_specified: true)
setup_event(event, &blk)
else
event = Event.new
setup_event(event, &blk)
end
end | ruby | def find_or_create_event_by_id(id, &blk)
event = id ? find_event_by_id(id)[0] : nil
if event
setup_event(event, &blk)
elsif id
event = Event.new(id: id, new_event_with_id_specified: true)
setup_event(event, &blk)
else
event = Event.new
setup_event(event, &blk)
end
end | [
"def",
"find_or_create_event_by_id",
"(",
"id",
",",
"&",
"blk",
")",
"event",
"=",
"id",
"?",
"find_event_by_id",
"(",
"id",
")",
"[",
"0",
"]",
":",
"nil",
"if",
"event",
"setup_event",
"(",
"event",
",",
"blk",
")",
"elsif",
"id",
"event",
"=",
"Event",
".",
"new",
"(",
"id",
":",
"id",
",",
"new_event_with_id_specified",
":",
"true",
")",
"setup_event",
"(",
"event",
",",
"blk",
")",
"else",
"event",
"=",
"Event",
".",
"new",
"setup_event",
"(",
"event",
",",
"blk",
")",
"end",
"end"
] | Looks for the specified event id.
If it is found it, updates it's vales and returns it.
If the event is no longer on the server it creates a new one with the specified values.
Works like the create_event method. | [
"Looks",
"for",
"the",
"specified",
"event",
"id",
".",
"If",
"it",
"is",
"found",
"it",
"updates",
"it",
"s",
"vales",
"and",
"returns",
"it",
".",
"If",
"the",
"event",
"is",
"no",
"longer",
"on",
"the",
"server",
"it",
"creates",
"a",
"new",
"one",
"with",
"the",
"specified",
"values",
".",
"Works",
"like",
"the",
"create_event",
"method",
"."
] | a81d685e432ce6c7e1838d14166fb1d5bab39685 | https://github.com/northworld/google_calendar/blob/a81d685e432ce6c7e1838d14166fb1d5bab39685/lib/google/calendar.rb#L374-L386 | train |
northworld/google_calendar | lib/google/calendar.rb | Google.Calendar.save_event | def save_event(event)
method = event.new_event? ? :post : :put
body = event.use_quickadd? ? nil : event.to_json
notifications = "sendNotifications=#{event.send_notifications?}"
query_string = if event.use_quickadd?
"/quickAdd?#{notifications}&text=#{event.title}"
elsif event.new_event?
"?#{notifications}"
else # update existing event.
"/#{event.id}?#{notifications}"
end
send_events_request(query_string, method, body)
end | ruby | def save_event(event)
method = event.new_event? ? :post : :put
body = event.use_quickadd? ? nil : event.to_json
notifications = "sendNotifications=#{event.send_notifications?}"
query_string = if event.use_quickadd?
"/quickAdd?#{notifications}&text=#{event.title}"
elsif event.new_event?
"?#{notifications}"
else # update existing event.
"/#{event.id}?#{notifications}"
end
send_events_request(query_string, method, body)
end | [
"def",
"save_event",
"(",
"event",
")",
"method",
"=",
"event",
".",
"new_event?",
"?",
":post",
":",
":put",
"body",
"=",
"event",
".",
"use_quickadd?",
"?",
"nil",
":",
"event",
".",
"to_json",
"notifications",
"=",
"\"sendNotifications=#{event.send_notifications?}\"",
"query_string",
"=",
"if",
"event",
".",
"use_quickadd?",
"\"/quickAdd?#{notifications}&text=#{event.title}\"",
"elsif",
"event",
".",
"new_event?",
"\"?#{notifications}\"",
"else",
"# update existing event.",
"\"/#{event.id}?#{notifications}\"",
"end",
"send_events_request",
"(",
"query_string",
",",
"method",
",",
"body",
")",
"end"
] | Saves the specified event.
This is a callback used by the Event class. | [
"Saves",
"the",
"specified",
"event",
".",
"This",
"is",
"a",
"callback",
"used",
"by",
"the",
"Event",
"class",
"."
] | a81d685e432ce6c7e1838d14166fb1d5bab39685 | https://github.com/northworld/google_calendar/blob/a81d685e432ce6c7e1838d14166fb1d5bab39685/lib/google/calendar.rb#L392-L405 | train |
northworld/google_calendar | lib/google/calendar.rb | Google.Calendar.parse_options | def parse_options(options) # :nodoc
options[:max_results] ||= 25
options[:order_by] ||= 'startTime' # other option is 'updated'
options[:expand_recurring_events] ||= true
query_string = "&orderBy=#{options[:order_by]}"
query_string << "&maxResults=#{options[:max_results]}"
query_string << "&singleEvents=#{options[:expand_recurring_events]}"
query_string << "&q=#{options[:query]}" unless options[:query].nil?
query_string
end | ruby | def parse_options(options) # :nodoc
options[:max_results] ||= 25
options[:order_by] ||= 'startTime' # other option is 'updated'
options[:expand_recurring_events] ||= true
query_string = "&orderBy=#{options[:order_by]}"
query_string << "&maxResults=#{options[:max_results]}"
query_string << "&singleEvents=#{options[:expand_recurring_events]}"
query_string << "&q=#{options[:query]}" unless options[:query].nil?
query_string
end | [
"def",
"parse_options",
"(",
"options",
")",
"# :nodoc",
"options",
"[",
":max_results",
"]",
"||=",
"25",
"options",
"[",
":order_by",
"]",
"||=",
"'startTime'",
"# other option is 'updated'",
"options",
"[",
":expand_recurring_events",
"]",
"||=",
"true",
"query_string",
"=",
"\"&orderBy=#{options[:order_by]}\"",
"query_string",
"<<",
"\"&maxResults=#{options[:max_results]}\"",
"query_string",
"<<",
"\"&singleEvents=#{options[:expand_recurring_events]}\"",
"query_string",
"<<",
"\"&q=#{options[:query]}\"",
"unless",
"options",
"[",
":query",
"]",
".",
"nil?",
"query_string",
"end"
] | Utility method used to centralize the parsing of common query parameters. | [
"Utility",
"method",
"used",
"to",
"centralize",
"the",
"parsing",
"of",
"common",
"query",
"parameters",
"."
] | a81d685e432ce6c7e1838d14166fb1d5bab39685 | https://github.com/northworld/google_calendar/blob/a81d685e432ce6c7e1838d14166fb1d5bab39685/lib/google/calendar.rb#L433-L442 | train |
northworld/google_calendar | lib/google/calendar.rb | Google.Calendar.parse_extended_properties | def parse_extended_properties(extended_properties) # :nodoc
query_parts = []
['shared', 'private'].each do |prop_type|
next unless extended_properties[prop_type]
query_parts << extended_properties[prop_type].map {|key, value| (prop_type == "shared" ? "sharedExtendedProperty=" : "privateExtendedProperty=") + "#{key}%3D#{value}" }.join("&")
end
query_parts.join('&')
end | ruby | def parse_extended_properties(extended_properties) # :nodoc
query_parts = []
['shared', 'private'].each do |prop_type|
next unless extended_properties[prop_type]
query_parts << extended_properties[prop_type].map {|key, value| (prop_type == "shared" ? "sharedExtendedProperty=" : "privateExtendedProperty=") + "#{key}%3D#{value}" }.join("&")
end
query_parts.join('&')
end | [
"def",
"parse_extended_properties",
"(",
"extended_properties",
")",
"# :nodoc",
"query_parts",
"=",
"[",
"]",
"[",
"'shared'",
",",
"'private'",
"]",
".",
"each",
"do",
"|",
"prop_type",
"|",
"next",
"unless",
"extended_properties",
"[",
"prop_type",
"]",
"query_parts",
"<<",
"extended_properties",
"[",
"prop_type",
"]",
".",
"map",
"{",
"|",
"key",
",",
"value",
"|",
"(",
"prop_type",
"==",
"\"shared\"",
"?",
"\"sharedExtendedProperty=\"",
":",
"\"privateExtendedProperty=\"",
")",
"+",
"\"#{key}%3D#{value}\"",
"}",
".",
"join",
"(",
"\"&\"",
")",
"end",
"query_parts",
".",
"join",
"(",
"'&'",
")",
"end"
] | Utility method used to centralize the parsing of extended query parameters. | [
"Utility",
"method",
"used",
"to",
"centralize",
"the",
"parsing",
"of",
"extended",
"query",
"parameters",
"."
] | a81d685e432ce6c7e1838d14166fb1d5bab39685 | https://github.com/northworld/google_calendar/blob/a81d685e432ce6c7e1838d14166fb1d5bab39685/lib/google/calendar.rb#L447-L454 | train |
northworld/google_calendar | lib/google/calendar.rb | Google.Calendar.event_lookup | def event_lookup(query_string = '') #:nodoc:
begin
response = send_events_request(query_string, :get)
parsed_json = JSON.parse(response.body)
@summary = parsed_json['summary']
events = Event.build_from_google_feed(parsed_json, self) || []
return events if events.empty?
events.length > 1 ? events : [events[0]]
rescue Google::HTTPNotFound
return []
end
end | ruby | def event_lookup(query_string = '') #:nodoc:
begin
response = send_events_request(query_string, :get)
parsed_json = JSON.parse(response.body)
@summary = parsed_json['summary']
events = Event.build_from_google_feed(parsed_json, self) || []
return events if events.empty?
events.length > 1 ? events : [events[0]]
rescue Google::HTTPNotFound
return []
end
end | [
"def",
"event_lookup",
"(",
"query_string",
"=",
"''",
")",
"#:nodoc:",
"begin",
"response",
"=",
"send_events_request",
"(",
"query_string",
",",
":get",
")",
"parsed_json",
"=",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
")",
"@summary",
"=",
"parsed_json",
"[",
"'summary'",
"]",
"events",
"=",
"Event",
".",
"build_from_google_feed",
"(",
"parsed_json",
",",
"self",
")",
"||",
"[",
"]",
"return",
"events",
"if",
"events",
".",
"empty?",
"events",
".",
"length",
">",
"1",
"?",
"events",
":",
"[",
"events",
"[",
"0",
"]",
"]",
"rescue",
"Google",
"::",
"HTTPNotFound",
"return",
"[",
"]",
"end",
"end"
] | Utility method used to centralize event lookup. | [
"Utility",
"method",
"used",
"to",
"centralize",
"event",
"lookup",
"."
] | a81d685e432ce6c7e1838d14166fb1d5bab39685 | https://github.com/northworld/google_calendar/blob/a81d685e432ce6c7e1838d14166fb1d5bab39685/lib/google/calendar.rb#L466-L477 | train |
northworld/google_calendar | lib/google/freebusy.rb | Google.Freebusy.json_for_query | def json_for_query(calendar_ids, start_time, end_time)
{}.tap{ |obj|
obj[:items] = calendar_ids.map {|id| Hash[:id, id] }
obj[:timeMin] = start_time.utc.iso8601
obj[:timeMax] = end_time.utc.iso8601
}.to_json
end | ruby | def json_for_query(calendar_ids, start_time, end_time)
{}.tap{ |obj|
obj[:items] = calendar_ids.map {|id| Hash[:id, id] }
obj[:timeMin] = start_time.utc.iso8601
obj[:timeMax] = end_time.utc.iso8601
}.to_json
end | [
"def",
"json_for_query",
"(",
"calendar_ids",
",",
"start_time",
",",
"end_time",
")",
"{",
"}",
".",
"tap",
"{",
"|",
"obj",
"|",
"obj",
"[",
":items",
"]",
"=",
"calendar_ids",
".",
"map",
"{",
"|",
"id",
"|",
"Hash",
"[",
":id",
",",
"id",
"]",
"}",
"obj",
"[",
":timeMin",
"]",
"=",
"start_time",
".",
"utc",
".",
"iso8601",
"obj",
"[",
":timeMax",
"]",
"=",
"end_time",
".",
"utc",
".",
"iso8601",
"}",
".",
"to_json",
"end"
] | Prepare the JSON | [
"Prepare",
"the",
"JSON"
] | a81d685e432ce6c7e1838d14166fb1d5bab39685 | https://github.com/northworld/google_calendar/blob/a81d685e432ce6c7e1838d14166fb1d5bab39685/lib/google/freebusy.rb#L51-L57 | train |
northworld/google_calendar | lib/google/connection.rb | Google.Connection.send | def send(path, method, content = '')
uri = BASE_URI + path
response = @client.fetch_protected_resource(
:uri => uri,
:method => method,
:body => content,
:headers => {'Content-type' => 'application/json'}
)
check_for_errors(response)
return response
end | ruby | def send(path, method, content = '')
uri = BASE_URI + path
response = @client.fetch_protected_resource(
:uri => uri,
:method => method,
:body => content,
:headers => {'Content-type' => 'application/json'}
)
check_for_errors(response)
return response
end | [
"def",
"send",
"(",
"path",
",",
"method",
",",
"content",
"=",
"''",
")",
"uri",
"=",
"BASE_URI",
"+",
"path",
"response",
"=",
"@client",
".",
"fetch_protected_resource",
"(",
":uri",
"=>",
"uri",
",",
":method",
"=>",
"method",
",",
":body",
"=>",
"content",
",",
":headers",
"=>",
"{",
"'Content-type'",
"=>",
"'application/json'",
"}",
")",
"check_for_errors",
"(",
"response",
")",
"return",
"response",
"end"
] | Send a request to google. | [
"Send",
"a",
"request",
"to",
"google",
"."
] | a81d685e432ce6c7e1838d14166fb1d5bab39685 | https://github.com/northworld/google_calendar/blob/a81d685e432ce6c7e1838d14166fb1d5bab39685/lib/google/connection.rb#L126-L139 | train |
northworld/google_calendar | lib/google/connection.rb | Google.Connection.parse_403_error | def parse_403_error(response)
case JSON.parse(response.body)["error"]["message"]
when "Forbidden" then raise ForbiddenError, response.body
when "Daily Limit Exceeded" then raise DailyLimitExceededError, response.body
when "User Rate Limit Exceeded" then raise UserRateLimitExceededError, response.body
when "Rate Limit Exceeded" then raise RateLimitExceededError, response.body
when "Calendar usage limits exceeded." then raise CalendarUsageLimitExceededError, response.body
else raise ForbiddenError, response.body
end
end | ruby | def parse_403_error(response)
case JSON.parse(response.body)["error"]["message"]
when "Forbidden" then raise ForbiddenError, response.body
when "Daily Limit Exceeded" then raise DailyLimitExceededError, response.body
when "User Rate Limit Exceeded" then raise UserRateLimitExceededError, response.body
when "Rate Limit Exceeded" then raise RateLimitExceededError, response.body
when "Calendar usage limits exceeded." then raise CalendarUsageLimitExceededError, response.body
else raise ForbiddenError, response.body
end
end | [
"def",
"parse_403_error",
"(",
"response",
")",
"case",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
")",
"[",
"\"error\"",
"]",
"[",
"\"message\"",
"]",
"when",
"\"Forbidden\"",
"then",
"raise",
"ForbiddenError",
",",
"response",
".",
"body",
"when",
"\"Daily Limit Exceeded\"",
"then",
"raise",
"DailyLimitExceededError",
",",
"response",
".",
"body",
"when",
"\"User Rate Limit Exceeded\"",
"then",
"raise",
"UserRateLimitExceededError",
",",
"response",
".",
"body",
"when",
"\"Rate Limit Exceeded\"",
"then",
"raise",
"RateLimitExceededError",
",",
"response",
".",
"body",
"when",
"\"Calendar usage limits exceeded.\"",
"then",
"raise",
"CalendarUsageLimitExceededError",
",",
"response",
".",
"body",
"else",
"raise",
"ForbiddenError",
",",
"response",
".",
"body",
"end",
"end"
] | Utility method to centralize handling of 403 errors. | [
"Utility",
"method",
"to",
"centralize",
"handling",
"of",
"403",
"errors",
"."
] | a81d685e432ce6c7e1838d14166fb1d5bab39685 | https://github.com/northworld/google_calendar/blob/a81d685e432ce6c7e1838d14166fb1d5bab39685/lib/google/connection.rb#L173-L182 | train |
northworld/google_calendar | lib/google/event.rb | Google.Event.all_day? | def all_day?
time = (@start_time.is_a? String) ? Time.parse(@start_time) : @start_time.dup.utc
duration % (24 * 60 * 60) == 0 && time == Time.local(time.year,time.month,time.day)
end | ruby | def all_day?
time = (@start_time.is_a? String) ? Time.parse(@start_time) : @start_time.dup.utc
duration % (24 * 60 * 60) == 0 && time == Time.local(time.year,time.month,time.day)
end | [
"def",
"all_day?",
"time",
"=",
"(",
"@start_time",
".",
"is_a?",
"String",
")",
"?",
"Time",
".",
"parse",
"(",
"@start_time",
")",
":",
"@start_time",
".",
"dup",
".",
"utc",
"duration",
"%",
"(",
"24",
"*",
"60",
"*",
"60",
")",
"==",
"0",
"&&",
"time",
"==",
"Time",
".",
"local",
"(",
"time",
".",
"year",
",",
"time",
".",
"month",
",",
"time",
".",
"day",
")",
"end"
] | Returns whether the Event is an all-day event, based on whether the event starts at the beginning and ends at the end of the day. | [
"Returns",
"whether",
"the",
"Event",
"is",
"an",
"all",
"-",
"day",
"event",
"based",
"on",
"whether",
"the",
"event",
"starts",
"at",
"the",
"beginning",
"and",
"ends",
"at",
"the",
"end",
"of",
"the",
"day",
"."
] | a81d685e432ce6c7e1838d14166fb1d5bab39685 | https://github.com/northworld/google_calendar/blob/a81d685e432ce6c7e1838d14166fb1d5bab39685/lib/google/event.rb#L122-L125 | train |
northworld/google_calendar | lib/google/event.rb | Google.Event.to_json | def to_json
attributes = {
"summary" => title,
"visibility" => visibility,
"transparency" => transparency,
"description" => description,
"location" => location,
"start" => time_or_all_day(start_time),
"end" => time_or_all_day(end_time),
"reminders" => reminders_attributes,
"guestsCanInviteOthers" => guests_can_invite_others,
"guestsCanSeeOtherGuests" => guests_can_see_other_guests
}
if id
attributes["id"] = id
end
if timezone_needed?
attributes['start'].merge!(local_timezone_attributes)
attributes['end'].merge!(local_timezone_attributes)
end
attributes.merge!(recurrence_attributes)
attributes.merge!(color_attributes)
attributes.merge!(attendees_attributes)
attributes.merge!(extended_properties_attributes)
JSON.generate attributes
end | ruby | def to_json
attributes = {
"summary" => title,
"visibility" => visibility,
"transparency" => transparency,
"description" => description,
"location" => location,
"start" => time_or_all_day(start_time),
"end" => time_or_all_day(end_time),
"reminders" => reminders_attributes,
"guestsCanInviteOthers" => guests_can_invite_others,
"guestsCanSeeOtherGuests" => guests_can_see_other_guests
}
if id
attributes["id"] = id
end
if timezone_needed?
attributes['start'].merge!(local_timezone_attributes)
attributes['end'].merge!(local_timezone_attributes)
end
attributes.merge!(recurrence_attributes)
attributes.merge!(color_attributes)
attributes.merge!(attendees_attributes)
attributes.merge!(extended_properties_attributes)
JSON.generate attributes
end | [
"def",
"to_json",
"attributes",
"=",
"{",
"\"summary\"",
"=>",
"title",
",",
"\"visibility\"",
"=>",
"visibility",
",",
"\"transparency\"",
"=>",
"transparency",
",",
"\"description\"",
"=>",
"description",
",",
"\"location\"",
"=>",
"location",
",",
"\"start\"",
"=>",
"time_or_all_day",
"(",
"start_time",
")",
",",
"\"end\"",
"=>",
"time_or_all_day",
"(",
"end_time",
")",
",",
"\"reminders\"",
"=>",
"reminders_attributes",
",",
"\"guestsCanInviteOthers\"",
"=>",
"guests_can_invite_others",
",",
"\"guestsCanSeeOtherGuests\"",
"=>",
"guests_can_see_other_guests",
"}",
"if",
"id",
"attributes",
"[",
"\"id\"",
"]",
"=",
"id",
"end",
"if",
"timezone_needed?",
"attributes",
"[",
"'start'",
"]",
".",
"merge!",
"(",
"local_timezone_attributes",
")",
"attributes",
"[",
"'end'",
"]",
".",
"merge!",
"(",
"local_timezone_attributes",
")",
"end",
"attributes",
".",
"merge!",
"(",
"recurrence_attributes",
")",
"attributes",
".",
"merge!",
"(",
"color_attributes",
")",
"attributes",
".",
"merge!",
"(",
"attendees_attributes",
")",
"attributes",
".",
"merge!",
"(",
"extended_properties_attributes",
")",
"JSON",
".",
"generate",
"attributes",
"end"
] | Google JSON representation of an event object. | [
"Google",
"JSON",
"representation",
"of",
"an",
"event",
"object",
"."
] | a81d685e432ce6c7e1838d14166fb1d5bab39685 | https://github.com/northworld/google_calendar/blob/a81d685e432ce6c7e1838d14166fb1d5bab39685/lib/google/event.rb#L264-L293 | train |
northworld/google_calendar | lib/google/event.rb | Google.Event.attendees_attributes | def attendees_attributes
return {} unless @attendees
attendees = @attendees.map do |attendee|
attendee.select { |k,_v| ['displayName', 'email', 'responseStatus'].include?(k) }
end
{ "attendees" => attendees }
end | ruby | def attendees_attributes
return {} unless @attendees
attendees = @attendees.map do |attendee|
attendee.select { |k,_v| ['displayName', 'email', 'responseStatus'].include?(k) }
end
{ "attendees" => attendees }
end | [
"def",
"attendees_attributes",
"return",
"{",
"}",
"unless",
"@attendees",
"attendees",
"=",
"@attendees",
".",
"map",
"do",
"|",
"attendee",
"|",
"attendee",
".",
"select",
"{",
"|",
"k",
",",
"_v",
"|",
"[",
"'displayName'",
",",
"'email'",
",",
"'responseStatus'",
"]",
".",
"include?",
"(",
"k",
")",
"}",
"end",
"{",
"\"attendees\"",
"=>",
"attendees",
"}",
"end"
] | Hash representation of attendees | [
"Hash",
"representation",
"of",
"attendees"
] | a81d685e432ce6c7e1838d14166fb1d5bab39685 | https://github.com/northworld/google_calendar/blob/a81d685e432ce6c7e1838d14166fb1d5bab39685/lib/google/event.rb#L313-L321 | train |
northworld/google_calendar | lib/google/event.rb | Google.Event.local_timezone_attributes | def local_timezone_attributes
tz = Time.now.getlocal.zone
tz_name = TimezoneParser::getTimezones(tz).last
{ "timeZone" => tz_name }
end | ruby | def local_timezone_attributes
tz = Time.now.getlocal.zone
tz_name = TimezoneParser::getTimezones(tz).last
{ "timeZone" => tz_name }
end | [
"def",
"local_timezone_attributes",
"tz",
"=",
"Time",
".",
"now",
".",
"getlocal",
".",
"zone",
"tz_name",
"=",
"TimezoneParser",
"::",
"getTimezones",
"(",
"tz",
")",
".",
"last",
"{",
"\"timeZone\"",
"=>",
"tz_name",
"}",
"end"
] | Hash representation of local timezone | [
"Hash",
"representation",
"of",
"local",
"timezone"
] | a81d685e432ce6c7e1838d14166fb1d5bab39685 | https://github.com/northworld/google_calendar/blob/a81d685e432ce6c7e1838d14166fb1d5bab39685/lib/google/event.rb#L359-L363 | train |
northworld/google_calendar | lib/google/event.rb | Google.Event.recurrence_attributes | def recurrence_attributes
return {} unless is_recurring_event?
@recurrence[:until] = @recurrence[:until].strftime('%Y%m%dT%H%M%SZ') if @recurrence[:until]
rrule = "RRULE:" + @recurrence.collect { |k,v| "#{k}=#{v}" }.join(';').upcase
@recurrence[:until] = Time.parse(@recurrence[:until]) if @recurrence[:until]
{ "recurrence" => [rrule] }
end | ruby | def recurrence_attributes
return {} unless is_recurring_event?
@recurrence[:until] = @recurrence[:until].strftime('%Y%m%dT%H%M%SZ') if @recurrence[:until]
rrule = "RRULE:" + @recurrence.collect { |k,v| "#{k}=#{v}" }.join(';').upcase
@recurrence[:until] = Time.parse(@recurrence[:until]) if @recurrence[:until]
{ "recurrence" => [rrule] }
end | [
"def",
"recurrence_attributes",
"return",
"{",
"}",
"unless",
"is_recurring_event?",
"@recurrence",
"[",
":until",
"]",
"=",
"@recurrence",
"[",
":until",
"]",
".",
"strftime",
"(",
"'%Y%m%dT%H%M%SZ'",
")",
"if",
"@recurrence",
"[",
":until",
"]",
"rrule",
"=",
"\"RRULE:\"",
"+",
"@recurrence",
".",
"collect",
"{",
"|",
"k",
",",
"v",
"|",
"\"#{k}=#{v}\"",
"}",
".",
"join",
"(",
"';'",
")",
".",
"upcase",
"@recurrence",
"[",
":until",
"]",
"=",
"Time",
".",
"parse",
"(",
"@recurrence",
"[",
":until",
"]",
")",
"if",
"@recurrence",
"[",
":until",
"]",
"{",
"\"recurrence\"",
"=>",
"[",
"rrule",
"]",
"}",
"end"
] | Hash representation of recurrence rules for repeating events | [
"Hash",
"representation",
"of",
"recurrence",
"rules",
"for",
"repeating",
"events"
] | a81d685e432ce6c7e1838d14166fb1d5bab39685 | https://github.com/northworld/google_calendar/blob/a81d685e432ce6c7e1838d14166fb1d5bab39685/lib/google/event.rb#L375-L383 | train |
northworld/google_calendar | lib/google/calendar_list.rb | Google.CalendarList.fetch_entries | def fetch_entries
response = @connection.send("/users/me/calendarList", :get)
return nil if response.status != 200 || response.body.empty?
CalendarListEntry.build_from_google_feed(JSON.parse(response.body), @connection)
end | ruby | def fetch_entries
response = @connection.send("/users/me/calendarList", :get)
return nil if response.status != 200 || response.body.empty?
CalendarListEntry.build_from_google_feed(JSON.parse(response.body), @connection)
end | [
"def",
"fetch_entries",
"response",
"=",
"@connection",
".",
"send",
"(",
"\"/users/me/calendarList\"",
",",
":get",
")",
"return",
"nil",
"if",
"response",
".",
"status",
"!=",
"200",
"||",
"response",
".",
"body",
".",
"empty?",
"CalendarListEntry",
".",
"build_from_google_feed",
"(",
"JSON",
".",
"parse",
"(",
"response",
".",
"body",
")",
",",
"@connection",
")",
"end"
] | Setup and connect to the user's list of Google Calendars.
The +params+ parameter accepts
* :client_id => the client ID that you received from Google after registering your application with them (https://console.developers.google.com/). REQUIRED
* :client_secret => the client secret you received from Google after registering your application with them. REQUIRED
* :redirect_url => the url where your users will be redirected to after they have successfully permitted access to their calendars. Use 'urn:ietf:wg:oauth:2.0:oob' if you are using an 'application'" REQUIRED
* :refresh_token => if a user has already given you access to their calendars, you can specify their refresh token here and you will be 'logged on' automatically (i.e. they don't need to authorize access again). OPTIONAL
See Readme.rdoc or readme_code.rb for an explication on the OAuth2 authorization process.
Find all entries on the user's calendar list. Returns an array of CalendarListEntry objects. | [
"Setup",
"and",
"connect",
"to",
"the",
"user",
"s",
"list",
"of",
"Google",
"Calendars",
"."
] | a81d685e432ce6c7e1838d14166fb1d5bab39685 | https://github.com/northworld/google_calendar/blob/a81d685e432ce6c7e1838d14166fb1d5bab39685/lib/google/calendar_list.rb#L28-L34 | train |
cryo28/sidekiq_status | lib/sidekiq_status/container.rb | SidekiqStatus.Container.save | def save
data = dump
data = Sidekiq.dump_json(data)
Sidekiq.redis do |conn|
conn.multi do
conn.setex(status_key, self.ttl, data)
conn.zadd(self.class.statuses_key, Time.now.to_f.to_s, self.jid)
end
end
end | ruby | def save
data = dump
data = Sidekiq.dump_json(data)
Sidekiq.redis do |conn|
conn.multi do
conn.setex(status_key, self.ttl, data)
conn.zadd(self.class.statuses_key, Time.now.to_f.to_s, self.jid)
end
end
end | [
"def",
"save",
"data",
"=",
"dump",
"data",
"=",
"Sidekiq",
".",
"dump_json",
"(",
"data",
")",
"Sidekiq",
".",
"redis",
"do",
"|",
"conn",
"|",
"conn",
".",
"multi",
"do",
"conn",
".",
"setex",
"(",
"status_key",
",",
"self",
".",
"ttl",
",",
"data",
")",
"conn",
".",
"zadd",
"(",
"self",
".",
"class",
".",
"statuses_key",
",",
"Time",
".",
"now",
".",
"to_f",
".",
"to_s",
",",
"self",
".",
"jid",
")",
"end",
"end",
"end"
] | Save current container attribute values to redis | [
"Save",
"current",
"container",
"attribute",
"values",
"to",
"redis"
] | afa8bcb85c3c68ad9ffdf445bb1d4da34df83f27 | https://github.com/cryo28/sidekiq_status/blob/afa8bcb85c3c68ad9ffdf445bb1d4da34df83f27/lib/sidekiq_status/container.rb#L205-L215 | train |
cryo28/sidekiq_status | lib/sidekiq_status/container.rb | SidekiqStatus.Container.delete | def delete
Sidekiq.redis do |conn|
conn.multi do
conn.del(status_key)
conn.zrem(self.class.kill_key, self.jid)
conn.zrem(self.class.statuses_key, self.jid)
end
end
end | ruby | def delete
Sidekiq.redis do |conn|
conn.multi do
conn.del(status_key)
conn.zrem(self.class.kill_key, self.jid)
conn.zrem(self.class.statuses_key, self.jid)
end
end
end | [
"def",
"delete",
"Sidekiq",
".",
"redis",
"do",
"|",
"conn",
"|",
"conn",
".",
"multi",
"do",
"conn",
".",
"del",
"(",
"status_key",
")",
"conn",
".",
"zrem",
"(",
"self",
".",
"class",
".",
"kill_key",
",",
"self",
".",
"jid",
")",
"conn",
".",
"zrem",
"(",
"self",
".",
"class",
".",
"statuses_key",
",",
"self",
".",
"jid",
")",
"end",
"end",
"end"
] | Delete current container data from redis | [
"Delete",
"current",
"container",
"data",
"from",
"redis"
] | afa8bcb85c3c68ad9ffdf445bb1d4da34df83f27 | https://github.com/cryo28/sidekiq_status/blob/afa8bcb85c3c68ad9ffdf445bb1d4da34df83f27/lib/sidekiq_status/container.rb#L218-L227 | train |
cryo28/sidekiq_status | lib/sidekiq_status/container.rb | SidekiqStatus.Container.kill | def kill
self.status = 'killed'
Sidekiq.redis do |conn|
conn.multi do
save
conn.zrem(self.class.kill_key, self.jid)
end
end
end | ruby | def kill
self.status = 'killed'
Sidekiq.redis do |conn|
conn.multi do
save
conn.zrem(self.class.kill_key, self.jid)
end
end
end | [
"def",
"kill",
"self",
".",
"status",
"=",
"'killed'",
"Sidekiq",
".",
"redis",
"do",
"|",
"conn",
"|",
"conn",
".",
"multi",
"do",
"save",
"conn",
".",
"zrem",
"(",
"self",
".",
"class",
".",
"kill_key",
",",
"self",
".",
"jid",
")",
"end",
"end",
"end"
] | Reflect the fact that a job has been killed in redis | [
"Reflect",
"the",
"fact",
"that",
"a",
"job",
"has",
"been",
"killed",
"in",
"redis"
] | afa8bcb85c3c68ad9ffdf445bb1d4da34df83f27 | https://github.com/cryo28/sidekiq_status/blob/afa8bcb85c3c68ad9ffdf445bb1d4da34df83f27/lib/sidekiq_status/container.rb#L245-L254 | train |
cryo28/sidekiq_status | lib/sidekiq_status/container.rb | SidekiqStatus.Container.load | def load(data)
data = DEFAULTS.merge(data)
@args, @worker, @queue = data.values_at('args', 'worker', 'queue')
@status, @at, @total, @message = data.values_at('status', 'at', 'total', 'message')
@payload = data['payload']
@last_updated_at = data['last_updated_at'] && Time.at(data['last_updated_at'].to_i)
end | ruby | def load(data)
data = DEFAULTS.merge(data)
@args, @worker, @queue = data.values_at('args', 'worker', 'queue')
@status, @at, @total, @message = data.values_at('status', 'at', 'total', 'message')
@payload = data['payload']
@last_updated_at = data['last_updated_at'] && Time.at(data['last_updated_at'].to_i)
end | [
"def",
"load",
"(",
"data",
")",
"data",
"=",
"DEFAULTS",
".",
"merge",
"(",
"data",
")",
"@args",
",",
"@worker",
",",
"@queue",
"=",
"data",
".",
"values_at",
"(",
"'args'",
",",
"'worker'",
",",
"'queue'",
")",
"@status",
",",
"@at",
",",
"@total",
",",
"@message",
"=",
"data",
".",
"values_at",
"(",
"'status'",
",",
"'at'",
",",
"'total'",
",",
"'message'",
")",
"@payload",
"=",
"data",
"[",
"'payload'",
"]",
"@last_updated_at",
"=",
"data",
"[",
"'last_updated_at'",
"]",
"&&",
"Time",
".",
"at",
"(",
"data",
"[",
"'last_updated_at'",
"]",
".",
"to_i",
")",
"end"
] | Merge-in given data to the current container
@private
@param [Hash] data | [
"Merge",
"-",
"in",
"given",
"data",
"to",
"the",
"current",
"container"
] | afa8bcb85c3c68ad9ffdf445bb1d4da34df83f27 | https://github.com/cryo28/sidekiq_status/blob/afa8bcb85c3c68ad9ffdf445bb1d4da34df83f27/lib/sidekiq_status/container.rb#L327-L334 | train |
cryo28/sidekiq_status | lib/sidekiq_status/container.rb | SidekiqStatus.Container.dump | def dump
{
'args' => self.args,
'worker' => self.worker,
'queue' => self.queue,
'status' => self.status,
'at' => self.at,
'total' => self.total,
'message' => self.message,
'payload' => self.payload,
'last_updated_at' => Time.now.to_i
}
end | ruby | def dump
{
'args' => self.args,
'worker' => self.worker,
'queue' => self.queue,
'status' => self.status,
'at' => self.at,
'total' => self.total,
'message' => self.message,
'payload' => self.payload,
'last_updated_at' => Time.now.to_i
}
end | [
"def",
"dump",
"{",
"'args'",
"=>",
"self",
".",
"args",
",",
"'worker'",
"=>",
"self",
".",
"worker",
",",
"'queue'",
"=>",
"self",
".",
"queue",
",",
"'status'",
"=>",
"self",
".",
"status",
",",
"'at'",
"=>",
"self",
".",
"at",
",",
"'total'",
"=>",
"self",
".",
"total",
",",
"'message'",
"=>",
"self",
".",
"message",
",",
"'payload'",
"=>",
"self",
".",
"payload",
",",
"'last_updated_at'",
"=>",
"Time",
".",
"now",
".",
"to_i",
"}",
"end"
] | Dump current container attribute values to json-serializable hash
@private
@return [Hash] Data for subsequent json-serialization | [
"Dump",
"current",
"container",
"attribute",
"values",
"to",
"json",
"-",
"serializable",
"hash"
] | afa8bcb85c3c68ad9ffdf445bb1d4da34df83f27 | https://github.com/cryo28/sidekiq_status/blob/afa8bcb85c3c68ad9ffdf445bb1d4da34df83f27/lib/sidekiq_status/container.rb#L340-L354 | train |
messagebird/ruby-rest-api | lib/messagebird/client.rb | MessageBird.Client.send_conversation_message | def send_conversation_message(from, to, params={})
ConversationMessage.new(conversation_request(
:post,
'send',
params.merge({
:from => from,
:to => to,
})))
end | ruby | def send_conversation_message(from, to, params={})
ConversationMessage.new(conversation_request(
:post,
'send',
params.merge({
:from => from,
:to => to,
})))
end | [
"def",
"send_conversation_message",
"(",
"from",
",",
"to",
",",
"params",
"=",
"{",
"}",
")",
"ConversationMessage",
".",
"new",
"(",
"conversation_request",
"(",
":post",
",",
"'send'",
",",
"params",
".",
"merge",
"(",
"{",
":from",
"=>",
"from",
",",
":to",
"=>",
"to",
",",
"}",
")",
")",
")",
"end"
] | Conversations
Send a conversation message | [
"Conversations",
"Send",
"a",
"conversation",
"message"
] | 5a4d5f12a97b52e3fa170c23d7a12b91770687a4 | https://github.com/messagebird/ruby-rest-api/blob/5a4d5f12a97b52e3fa170c23d7a12b91770687a4/lib/messagebird/client.rb#L64-L72 | train |
messagebird/ruby-rest-api | lib/messagebird/client.rb | MessageBird.Client.start_conversation | def start_conversation(to, channelId, params={})
Conversation.new(conversation_request(
:post,
'conversations/start',
params.merge({
:to => to,
:channelId => channelId,
})))
end | ruby | def start_conversation(to, channelId, params={})
Conversation.new(conversation_request(
:post,
'conversations/start',
params.merge({
:to => to,
:channelId => channelId,
})))
end | [
"def",
"start_conversation",
"(",
"to",
",",
"channelId",
",",
"params",
"=",
"{",
"}",
")",
"Conversation",
".",
"new",
"(",
"conversation_request",
"(",
":post",
",",
"'conversations/start'",
",",
"params",
".",
"merge",
"(",
"{",
":to",
"=>",
"to",
",",
":channelId",
"=>",
"channelId",
",",
"}",
")",
")",
")",
"end"
] | Start a conversation | [
"Start",
"a",
"conversation"
] | 5a4d5f12a97b52e3fa170c23d7a12b91770687a4 | https://github.com/messagebird/ruby-rest-api/blob/5a4d5f12a97b52e3fa170c23d7a12b91770687a4/lib/messagebird/client.rb#L75-L83 | train |
messagebird/ruby-rest-api | lib/messagebird/client.rb | MessageBird.Client.message_create | def message_create(originator, recipients, body, params={})
# Convert an array of recipients to a comma-separated string.
recipients = recipients.join(',') if recipients.kind_of?(Array)
Message.new(request(
:post,
'messages',
params.merge({
:originator => originator.to_s,
:body => body.to_s,
:recipients => recipients })))
end | ruby | def message_create(originator, recipients, body, params={})
# Convert an array of recipients to a comma-separated string.
recipients = recipients.join(',') if recipients.kind_of?(Array)
Message.new(request(
:post,
'messages',
params.merge({
:originator => originator.to_s,
:body => body.to_s,
:recipients => recipients })))
end | [
"def",
"message_create",
"(",
"originator",
",",
"recipients",
",",
"body",
",",
"params",
"=",
"{",
"}",
")",
"# Convert an array of recipients to a comma-separated string.",
"recipients",
"=",
"recipients",
".",
"join",
"(",
"','",
")",
"if",
"recipients",
".",
"kind_of?",
"(",
"Array",
")",
"Message",
".",
"new",
"(",
"request",
"(",
":post",
",",
"'messages'",
",",
"params",
".",
"merge",
"(",
"{",
":originator",
"=>",
"originator",
".",
"to_s",
",",
":body",
"=>",
"body",
".",
"to_s",
",",
":recipients",
"=>",
"recipients",
"}",
")",
")",
")",
"end"
] | Create a new message. | [
"Create",
"a",
"new",
"message",
"."
] | 5a4d5f12a97b52e3fa170c23d7a12b91770687a4 | https://github.com/messagebird/ruby-rest-api/blob/5a4d5f12a97b52e3fa170c23d7a12b91770687a4/lib/messagebird/client.rb#L186-L197 | train |
messagebird/ruby-rest-api | lib/messagebird/client.rb | MessageBird.Client.voice_message_create | def voice_message_create(recipients, body, params={})
# Convert an array of recipients to a comma-separated string.
recipients = recipients.join(',') if recipients.kind_of?(Array)
VoiceMessage.new(request(
:post,
'voicemessages',
params.merge({ :recipients => recipients, :body => body.to_s })))
end | ruby | def voice_message_create(recipients, body, params={})
# Convert an array of recipients to a comma-separated string.
recipients = recipients.join(',') if recipients.kind_of?(Array)
VoiceMessage.new(request(
:post,
'voicemessages',
params.merge({ :recipients => recipients, :body => body.to_s })))
end | [
"def",
"voice_message_create",
"(",
"recipients",
",",
"body",
",",
"params",
"=",
"{",
"}",
")",
"# Convert an array of recipients to a comma-separated string.",
"recipients",
"=",
"recipients",
".",
"join",
"(",
"','",
")",
"if",
"recipients",
".",
"kind_of?",
"(",
"Array",
")",
"VoiceMessage",
".",
"new",
"(",
"request",
"(",
":post",
",",
"'voicemessages'",
",",
"params",
".",
"merge",
"(",
"{",
":recipients",
"=>",
"recipients",
",",
":body",
"=>",
"body",
".",
"to_s",
"}",
")",
")",
")",
"end"
] | Create a new voice message. | [
"Create",
"a",
"new",
"voice",
"message",
"."
] | 5a4d5f12a97b52e3fa170c23d7a12b91770687a4 | https://github.com/messagebird/ruby-rest-api/blob/5a4d5f12a97b52e3fa170c23d7a12b91770687a4/lib/messagebird/client.rb#L205-L213 | train |
zolrath/marky_markov | lib/marky_markov.rb | MarkyMarkov.TemporaryDictionary.method_missing | def method_missing(method_sym, *args, &block)
if method_sym.to_s =~ /^generate_(\d*)_word[s]*$/
generate_n_words($1.to_i)
elsif method_sym.to_s =~ /^generate_(\d*)_sentence[s]*$/
generate_n_sentences($1.to_i)
else
super
end
end | ruby | def method_missing(method_sym, *args, &block)
if method_sym.to_s =~ /^generate_(\d*)_word[s]*$/
generate_n_words($1.to_i)
elsif method_sym.to_s =~ /^generate_(\d*)_sentence[s]*$/
generate_n_sentences($1.to_i)
else
super
end
end | [
"def",
"method_missing",
"(",
"method_sym",
",",
"*",
"args",
",",
"&",
"block",
")",
"if",
"method_sym",
".",
"to_s",
"=~",
"/",
"\\d",
"/",
"generate_n_words",
"(",
"$1",
".",
"to_i",
")",
"elsif",
"method_sym",
".",
"to_s",
"=~",
"/",
"\\d",
"/",
"generate_n_sentences",
"(",
"$1",
".",
"to_i",
")",
"else",
"super",
"end",
"end"
] | Dynamically call generate_n_words or generate_n_sentences
if an Int is substituted for the n in the method call.
@since 0.1.4
@example Generate a 40 and a 1 word long string of words.
markov.generate_40_words
markov.generate_1_word
@example Generate 2 sentences
markov.generate_2_sentences
@return [String] the sentence generated by the dictionary. | [
"Dynamically",
"call",
"generate_n_words",
"or",
"generate_n_sentences",
"if",
"an",
"Int",
"is",
"substituted",
"for",
"the",
"n",
"in",
"the",
"method",
"call",
"."
] | 79b12a84a1e63cd69f3a0b0eda72062d8c6eb3aa | https://github.com/zolrath/marky_markov/blob/79b12a84a1e63cd69f3a0b0eda72062d8c6eb3aa/lib/marky_markov.rb#L91-L99 | train |
tarcieri/cool.io | lib/cool.io/loop.rb | Coolio.Loop.run | def run(timeout = nil)
raise RuntimeError, "no watchers for this loop" if @watchers.empty?
@running = true
while @running and not @active_watchers.zero?
run_once(timeout)
end
@running = false
end | ruby | def run(timeout = nil)
raise RuntimeError, "no watchers for this loop" if @watchers.empty?
@running = true
while @running and not @active_watchers.zero?
run_once(timeout)
end
@running = false
end | [
"def",
"run",
"(",
"timeout",
"=",
"nil",
")",
"raise",
"RuntimeError",
",",
"\"no watchers for this loop\"",
"if",
"@watchers",
".",
"empty?",
"@running",
"=",
"true",
"while",
"@running",
"and",
"not",
"@active_watchers",
".",
"zero?",
"run_once",
"(",
"timeout",
")",
"end",
"@running",
"=",
"false",
"end"
] | Run the event loop and dispatch events back to Ruby. If there
are no watchers associated with the event loop it will return
immediately. Otherwise, run will continue blocking and making
event callbacks to watchers until all watchers associated with
the loop have been disabled or detached. The loop may be
explicitly stopped by calling the stop method on the loop object. | [
"Run",
"the",
"event",
"loop",
"and",
"dispatch",
"events",
"back",
"to",
"Ruby",
".",
"If",
"there",
"are",
"no",
"watchers",
"associated",
"with",
"the",
"event",
"loop",
"it",
"will",
"return",
"immediately",
".",
"Otherwise",
"run",
"will",
"continue",
"blocking",
"and",
"making",
"event",
"callbacks",
"to",
"watchers",
"until",
"all",
"watchers",
"associated",
"with",
"the",
"loop",
"have",
"been",
"disabled",
"or",
"detached",
".",
"The",
"loop",
"may",
"be",
"explicitly",
"stopped",
"by",
"calling",
"the",
"stop",
"method",
"on",
"the",
"loop",
"object",
"."
] | 0fd3fd1d8e8d81e24f79f809979367abc3f52b92 | https://github.com/tarcieri/cool.io/blob/0fd3fd1d8e8d81e24f79f809979367abc3f52b92/lib/cool.io/loop.rb#L83-L91 | train |
tarcieri/cool.io | lib/cool.io/io.rb | Coolio.IO.on_readable | def on_readable
begin
on_read @_io.read_nonblock(INPUT_SIZE)
rescue Errno::EAGAIN, Errno::EINTR
return
# SystemCallError catches Errno::ECONNRESET amongst others.
rescue SystemCallError, EOFError, IOError, SocketError
close
end
end | ruby | def on_readable
begin
on_read @_io.read_nonblock(INPUT_SIZE)
rescue Errno::EAGAIN, Errno::EINTR
return
# SystemCallError catches Errno::ECONNRESET amongst others.
rescue SystemCallError, EOFError, IOError, SocketError
close
end
end | [
"def",
"on_readable",
"begin",
"on_read",
"@_io",
".",
"read_nonblock",
"(",
"INPUT_SIZE",
")",
"rescue",
"Errno",
"::",
"EAGAIN",
",",
"Errno",
"::",
"EINTR",
"return",
"# SystemCallError catches Errno::ECONNRESET amongst others.",
"rescue",
"SystemCallError",
",",
"EOFError",
",",
"IOError",
",",
"SocketError",
"close",
"end",
"end"
] | Read from the input buffer and dispatch to on_read | [
"Read",
"from",
"the",
"input",
"buffer",
"and",
"dispatch",
"to",
"on_read"
] | 0fd3fd1d8e8d81e24f79f809979367abc3f52b92 | https://github.com/tarcieri/cool.io/blob/0fd3fd1d8e8d81e24f79f809979367abc3f52b92/lib/cool.io/io.rb#L121-L131 | train |
tarcieri/cool.io | lib/cool.io/io.rb | Coolio.IO.on_writable | def on_writable
begin
@_write_buffer.write_to(@_io)
rescue Errno::EINTR
return
# SystemCallError catches Errno::EPIPE & Errno::ECONNRESET amongst others.
rescue SystemCallError, IOError, SocketError
return close
end
if @_write_buffer.empty?
disable_write_watcher
on_write_complete
end
end | ruby | def on_writable
begin
@_write_buffer.write_to(@_io)
rescue Errno::EINTR
return
# SystemCallError catches Errno::EPIPE & Errno::ECONNRESET amongst others.
rescue SystemCallError, IOError, SocketError
return close
end
if @_write_buffer.empty?
disable_write_watcher
on_write_complete
end
end | [
"def",
"on_writable",
"begin",
"@_write_buffer",
".",
"write_to",
"(",
"@_io",
")",
"rescue",
"Errno",
"::",
"EINTR",
"return",
"# SystemCallError catches Errno::EPIPE & Errno::ECONNRESET amongst others.",
"rescue",
"SystemCallError",
",",
"IOError",
",",
"SocketError",
"return",
"close",
"end",
"if",
"@_write_buffer",
".",
"empty?",
"disable_write_watcher",
"on_write_complete",
"end",
"end"
] | Write the contents of the output buffer | [
"Write",
"the",
"contents",
"of",
"the",
"output",
"buffer"
] | 0fd3fd1d8e8d81e24f79f809979367abc3f52b92 | https://github.com/tarcieri/cool.io/blob/0fd3fd1d8e8d81e24f79f809979367abc3f52b92/lib/cool.io/io.rb#L134-L149 | train |
tarcieri/cool.io | lib/cool.io/dns_resolver.rb | Coolio.DNSResolver.send_request | def send_request
nameserver = @nameservers.shift
@nameservers << nameserver # rotate them
begin
@socket.send request_message, 0, @nameservers.first, DNS_PORT
rescue Errno::EHOSTUNREACH # TODO figure out why it has to be wrapper here, when the other wrapper should be wrapping this one!
end
end | ruby | def send_request
nameserver = @nameservers.shift
@nameservers << nameserver # rotate them
begin
@socket.send request_message, 0, @nameservers.first, DNS_PORT
rescue Errno::EHOSTUNREACH # TODO figure out why it has to be wrapper here, when the other wrapper should be wrapping this one!
end
end | [
"def",
"send_request",
"nameserver",
"=",
"@nameservers",
".",
"shift",
"@nameservers",
"<<",
"nameserver",
"# rotate them",
"begin",
"@socket",
".",
"send",
"request_message",
",",
"0",
",",
"@nameservers",
".",
"first",
",",
"DNS_PORT",
"rescue",
"Errno",
"::",
"EHOSTUNREACH",
"# TODO figure out why it has to be wrapper here, when the other wrapper should be wrapping this one!",
"end",
"end"
] | Send a request to the DNS server | [
"Send",
"a",
"request",
"to",
"the",
"DNS",
"server"
] | 0fd3fd1d8e8d81e24f79f809979367abc3f52b92 | https://github.com/tarcieri/cool.io/blob/0fd3fd1d8e8d81e24f79f809979367abc3f52b92/lib/cool.io/dns_resolver.rb#L106-L113 | train |
tarcieri/cool.io | lib/cool.io/dns_resolver.rb | Coolio.DNSResolver.on_readable | def on_readable
datagram = nil
begin
datagram = @socket.recvfrom_nonblock(DATAGRAM_SIZE).first
rescue Errno::ECONNREFUSED
end
address = response_address datagram rescue nil
address ? on_success(address) : on_failure
detach
end | ruby | def on_readable
datagram = nil
begin
datagram = @socket.recvfrom_nonblock(DATAGRAM_SIZE).first
rescue Errno::ECONNREFUSED
end
address = response_address datagram rescue nil
address ? on_success(address) : on_failure
detach
end | [
"def",
"on_readable",
"datagram",
"=",
"nil",
"begin",
"datagram",
"=",
"@socket",
".",
"recvfrom_nonblock",
"(",
"DATAGRAM_SIZE",
")",
".",
"first",
"rescue",
"Errno",
"::",
"ECONNREFUSED",
"end",
"address",
"=",
"response_address",
"datagram",
"rescue",
"nil",
"address",
"?",
"on_success",
"(",
"address",
")",
":",
"on_failure",
"detach",
"end"
] | Called by the subclass when the DNS response is available | [
"Called",
"by",
"the",
"subclass",
"when",
"the",
"DNS",
"response",
"is",
"available"
] | 0fd3fd1d8e8d81e24f79f809979367abc3f52b92 | https://github.com/tarcieri/cool.io/blob/0fd3fd1d8e8d81e24f79f809979367abc3f52b92/lib/cool.io/dns_resolver.rb#L116-L126 | train |
tarcieri/cool.io | lib/cool.io/socket.rb | Coolio.TCPSocket.preinitialize | def preinitialize(addr, port, *args)
@_write_buffer = ::IO::Buffer.new # allow for writing BEFORE DNS has resolved
@remote_host, @remote_addr, @remote_port = addr, addr, port
@_resolver = TCPConnectResolver.new(self, addr, port, *args)
end | ruby | def preinitialize(addr, port, *args)
@_write_buffer = ::IO::Buffer.new # allow for writing BEFORE DNS has resolved
@remote_host, @remote_addr, @remote_port = addr, addr, port
@_resolver = TCPConnectResolver.new(self, addr, port, *args)
end | [
"def",
"preinitialize",
"(",
"addr",
",",
"port",
",",
"*",
"args",
")",
"@_write_buffer",
"=",
"::",
"IO",
"::",
"Buffer",
".",
"new",
"# allow for writing BEFORE DNS has resolved",
"@remote_host",
",",
"@remote_addr",
",",
"@remote_port",
"=",
"addr",
",",
"addr",
",",
"port",
"@_resolver",
"=",
"TCPConnectResolver",
".",
"new",
"(",
"self",
",",
"addr",
",",
"port",
",",
"args",
")",
"end"
] | Called by precreate during asyncronous DNS resolution | [
"Called",
"by",
"precreate",
"during",
"asyncronous",
"DNS",
"resolution"
] | 0fd3fd1d8e8d81e24f79f809979367abc3f52b92 | https://github.com/tarcieri/cool.io/blob/0fd3fd1d8e8d81e24f79f809979367abc3f52b92/lib/cool.io/socket.rb#L132-L136 | train |
tarcieri/cool.io | lib/cool.io/dsl.rb | Coolio.DSL.connect | def connect(host, port, connection_name = nil, *initializer_args, &block)
if block_given?
initializer_args.unshift connection_name if connection_name
klass = Class.new Cool.io::TCPSocket
connection_builder = ConnectionBuilder.new klass
connection_builder.instance_eval(&block)
else
raise ArgumentError, "no connection name or block given" unless connection_name
klass = self[connection_name]
end
client = klass.connect host, port, *initializer_args
client.attach Cool.io::Loop.default
client
end | ruby | def connect(host, port, connection_name = nil, *initializer_args, &block)
if block_given?
initializer_args.unshift connection_name if connection_name
klass = Class.new Cool.io::TCPSocket
connection_builder = ConnectionBuilder.new klass
connection_builder.instance_eval(&block)
else
raise ArgumentError, "no connection name or block given" unless connection_name
klass = self[connection_name]
end
client = klass.connect host, port, *initializer_args
client.attach Cool.io::Loop.default
client
end | [
"def",
"connect",
"(",
"host",
",",
"port",
",",
"connection_name",
"=",
"nil",
",",
"*",
"initializer_args",
",",
"&",
"block",
")",
"if",
"block_given?",
"initializer_args",
".",
"unshift",
"connection_name",
"if",
"connection_name",
"klass",
"=",
"Class",
".",
"new",
"Cool",
".",
"io",
"::",
"TCPSocket",
"connection_builder",
"=",
"ConnectionBuilder",
".",
"new",
"klass",
"connection_builder",
".",
"instance_eval",
"(",
"block",
")",
"else",
"raise",
"ArgumentError",
",",
"\"no connection name or block given\"",
"unless",
"connection_name",
"klass",
"=",
"self",
"[",
"connection_name",
"]",
"end",
"client",
"=",
"klass",
".",
"connect",
"host",
",",
"port",
",",
"initializer_args",
"client",
".",
"attach",
"Cool",
".",
"io",
"::",
"Loop",
".",
"default",
"client",
"end"
] | Connect to the given host and port using the given connection class | [
"Connect",
"to",
"the",
"given",
"host",
"and",
"port",
"using",
"the",
"given",
"connection",
"class"
] | 0fd3fd1d8e8d81e24f79f809979367abc3f52b92 | https://github.com/tarcieri/cool.io/blob/0fd3fd1d8e8d81e24f79f809979367abc3f52b92/lib/cool.io/dsl.rb#L22-L37 | train |
tarcieri/cool.io | lib/cool.io/dsl.rb | Coolio.DSL.[] | def [](connection_name)
class_name = connection_name.to_s.split('_').map { |s| s.capitalize }.join
begin
Coolio::Connections.const_get class_name
rescue NameError
raise NameError, "No connection type registered for #{connection_name.inspect}"
end
end | ruby | def [](connection_name)
class_name = connection_name.to_s.split('_').map { |s| s.capitalize }.join
begin
Coolio::Connections.const_get class_name
rescue NameError
raise NameError, "No connection type registered for #{connection_name.inspect}"
end
end | [
"def",
"[]",
"(",
"connection_name",
")",
"class_name",
"=",
"connection_name",
".",
"to_s",
".",
"split",
"(",
"'_'",
")",
".",
"map",
"{",
"|",
"s",
"|",
"s",
".",
"capitalize",
"}",
".",
"join",
"begin",
"Coolio",
"::",
"Connections",
".",
"const_get",
"class_name",
"rescue",
"NameError",
"raise",
"NameError",
",",
"\"No connection type registered for #{connection_name.inspect}\"",
"end",
"end"
] | Look up a connection class by its name | [
"Look",
"up",
"a",
"connection",
"class",
"by",
"its",
"name"
] | 0fd3fd1d8e8d81e24f79f809979367abc3f52b92 | https://github.com/tarcieri/cool.io/blob/0fd3fd1d8e8d81e24f79f809979367abc3f52b92/lib/cool.io/dsl.rb#L70-L78 | train |
tas50/chef-api | lib/chef-api/util.rb | ChefAPI.Util.safe_read | def safe_read(path)
path = File.expand_path(path)
name = File.basename(path, '.*')
contents = File.read(path)
[name, contents]
rescue Errno::EACCES
raise Error::InsufficientFilePermissions.new(path: path)
rescue Errno::ENOENT
raise Error::FileNotFound.new(path: path)
end | ruby | def safe_read(path)
path = File.expand_path(path)
name = File.basename(path, '.*')
contents = File.read(path)
[name, contents]
rescue Errno::EACCES
raise Error::InsufficientFilePermissions.new(path: path)
rescue Errno::ENOENT
raise Error::FileNotFound.new(path: path)
end | [
"def",
"safe_read",
"(",
"path",
")",
"path",
"=",
"File",
".",
"expand_path",
"(",
"path",
")",
"name",
"=",
"File",
".",
"basename",
"(",
"path",
",",
"'.*'",
")",
"contents",
"=",
"File",
".",
"read",
"(",
"path",
")",
"[",
"name",
",",
"contents",
"]",
"rescue",
"Errno",
"::",
"EACCES",
"raise",
"Error",
"::",
"InsufficientFilePermissions",
".",
"new",
"(",
"path",
":",
"path",
")",
"rescue",
"Errno",
"::",
"ENOENT",
"raise",
"Error",
"::",
"FileNotFound",
".",
"new",
"(",
"path",
":",
"path",
")",
"end"
] | "Safely" read the contents of a file on disk, catching any permission
errors or not found errors and raising a nicer exception.
@example Reading a file that does not exist
safe_read('/non-existent/file') #=> Error::FileNotFound
@example Reading a file with improper permissions
safe_read('/bad-permissions') #=> Error::InsufficientFilePermissions
@example Reading a regular file
safe_read('my-file.txt') #=> ["my-file", "..."]
@param [String] path
the path to the file on disk
@return [Array<String>]
A array where the first value is the basename of the file and the
second value is the literal contents from +File.read+. | [
"Safely",
"read",
"the",
"contents",
"of",
"a",
"file",
"on",
"disk",
"catching",
"any",
"permission",
"errors",
"or",
"not",
"found",
"errors",
"and",
"raising",
"a",
"nicer",
"exception",
"."
] | a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f | https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/util.rb#L78-L88 | train |
tas50/chef-api | lib/chef-api/util.rb | ChefAPI.Util.fast_collect | def fast_collect(collection, &block)
collection.map do |item|
Thread.new do
Thread.current[:result] = block.call(item)
end
end.collect do |thread|
thread.join
thread[:result]
end
end | ruby | def fast_collect(collection, &block)
collection.map do |item|
Thread.new do
Thread.current[:result] = block.call(item)
end
end.collect do |thread|
thread.join
thread[:result]
end
end | [
"def",
"fast_collect",
"(",
"collection",
",",
"&",
"block",
")",
"collection",
".",
"map",
"do",
"|",
"item",
"|",
"Thread",
".",
"new",
"do",
"Thread",
".",
"current",
"[",
":result",
"]",
"=",
"block",
".",
"call",
"(",
"item",
")",
"end",
"end",
".",
"collect",
"do",
"|",
"thread",
"|",
"thread",
".",
"join",
"thread",
"[",
":result",
"]",
"end",
"end"
] | Quickly iterate over a collection using native Ruby threads, preserving
the original order of elements and being all thread-safe and stuff.
@example Parse a collection of JSON files
fast_collect(Dir['**/*.json']) do |item|
JSON.parse(File.read(item))
end
@param [#each] collection
the collection to iterate
@param [Proc] block
the block to evaluate (typically an expensive operation)
@return [Array]
the result of the iteration | [
"Quickly",
"iterate",
"over",
"a",
"collection",
"using",
"native",
"Ruby",
"threads",
"preserving",
"the",
"original",
"order",
"of",
"elements",
"and",
"being",
"all",
"thread",
"-",
"safe",
"and",
"stuff",
"."
] | a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f | https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/util.rb#L108-L117 | train |
tas50/chef-api | lib/chef-api/resources/base.rb | ChefAPI.Resource::Base.save! | def save!
validate!
response = if new_resource?
self.class.post(to_json, _prefix)
else
self.class.put(id, to_json, _prefix)
end
# Update our local copy with any partial information that was returned
# from the server, ignoring an "bad" attributes that aren't defined in
# our schema.
response.each do |key, value|
update_attribute(key, value) if attribute?(key)
end
true
end | ruby | def save!
validate!
response = if new_resource?
self.class.post(to_json, _prefix)
else
self.class.put(id, to_json, _prefix)
end
# Update our local copy with any partial information that was returned
# from the server, ignoring an "bad" attributes that aren't defined in
# our schema.
response.each do |key, value|
update_attribute(key, value) if attribute?(key)
end
true
end | [
"def",
"save!",
"validate!",
"response",
"=",
"if",
"new_resource?",
"self",
".",
"class",
".",
"post",
"(",
"to_json",
",",
"_prefix",
")",
"else",
"self",
".",
"class",
".",
"put",
"(",
"id",
",",
"to_json",
",",
"_prefix",
")",
"end",
"# Update our local copy with any partial information that was returned",
"# from the server, ignoring an \"bad\" attributes that aren't defined in",
"# our schema.",
"response",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"update_attribute",
"(",
"key",
",",
"value",
")",
"if",
"attribute?",
"(",
"key",
")",
"end",
"true",
"end"
] | Commit the resource and any changes to the remote Chef Server. Any errors
will raise an exception in the main thread and the resource will not be
committed back to the Chef Server.
Any response errors (such as server-side responses) that ChefAPI failed
to account for in validations will also raise an exception.
@return [Boolean]
true if the resource was saved | [
"Commit",
"the",
"resource",
"and",
"any",
"changes",
"to",
"the",
"remote",
"Chef",
"Server",
".",
"Any",
"errors",
"will",
"raise",
"an",
"exception",
"in",
"the",
"main",
"thread",
"and",
"the",
"resource",
"will",
"not",
"be",
"committed",
"back",
"to",
"the",
"Chef",
"Server",
"."
] | a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f | https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/resources/base.rb#L679-L696 | train |
tas50/chef-api | lib/chef-api/resources/base.rb | ChefAPI.Resource::Base.update_attribute | def update_attribute(key, value)
unless attribute?(key.to_sym)
raise Error::UnknownAttribute.new(attribute: key)
end
_attributes[key.to_sym] = value
end | ruby | def update_attribute(key, value)
unless attribute?(key.to_sym)
raise Error::UnknownAttribute.new(attribute: key)
end
_attributes[key.to_sym] = value
end | [
"def",
"update_attribute",
"(",
"key",
",",
"value",
")",
"unless",
"attribute?",
"(",
"key",
".",
"to_sym",
")",
"raise",
"Error",
"::",
"UnknownAttribute",
".",
"new",
"(",
"attribute",
":",
"key",
")",
"end",
"_attributes",
"[",
"key",
".",
"to_sym",
"]",
"=",
"value",
"end"
] | Update a single attribute in the attributes hash.
@raise | [
"Update",
"a",
"single",
"attribute",
"in",
"the",
"attributes",
"hash",
"."
] | a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f | https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/resources/base.rb#L745-L751 | train |
tas50/chef-api | lib/chef-api/resources/base.rb | ChefAPI.Resource::Base.validate! | def validate!
unless valid?
sentence = errors.full_messages.join(', ')
raise Error::InvalidResource.new(errors: sentence)
end
true
end | ruby | def validate!
unless valid?
sentence = errors.full_messages.join(', ')
raise Error::InvalidResource.new(errors: sentence)
end
true
end | [
"def",
"validate!",
"unless",
"valid?",
"sentence",
"=",
"errors",
".",
"full_messages",
".",
"join",
"(",
"', '",
")",
"raise",
"Error",
"::",
"InvalidResource",
".",
"new",
"(",
"errors",
":",
"sentence",
")",
"end",
"true",
"end"
] | Run all of this resource's validations, raising an exception if any
validations fail.
@raise [Error::InvalidResource]
if any of the validations fail
@return [Boolean]
true if the validation was successful - this method will never return
anything other than true because an exception is raised if validations
fail | [
"Run",
"all",
"of",
"this",
"resource",
"s",
"validations",
"raising",
"an",
"exception",
"if",
"any",
"validations",
"fail",
"."
] | a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f | https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/resources/base.rb#L776-L783 | train |
tas50/chef-api | lib/chef-api/resources/base.rb | ChefAPI.Resource::Base.valid? | def valid?
errors.clear
validators.each do |validator|
validator.validate(self)
end
errors.empty?
end | ruby | def valid?
errors.clear
validators.each do |validator|
validator.validate(self)
end
errors.empty?
end | [
"def",
"valid?",
"errors",
".",
"clear",
"validators",
".",
"each",
"do",
"|",
"validator",
"|",
"validator",
".",
"validate",
"(",
"self",
")",
"end",
"errors",
".",
"empty?",
"end"
] | Determine if the current resource is valid. This relies on the
validations defined in the schema at initialization.
@return [Boolean]
true if the resource is valid, false otherwise | [
"Determine",
"if",
"the",
"current",
"resource",
"is",
"valid",
".",
"This",
"relies",
"on",
"the",
"validations",
"defined",
"in",
"the",
"schema",
"at",
"initialization",
"."
] | a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f | https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/resources/base.rb#L792-L800 | train |
tas50/chef-api | lib/chef-api/resources/base.rb | ChefAPI.Resource::Base.diff | def diff
diff = {}
remote = self.class.fetch(id, _prefix) || self.class.new({}, _prefix)
remote._attributes.each do |key, value|
unless _attributes[key] == value
diff[key] = { local: _attributes[key], remote: value }
end
end
diff
end | ruby | def diff
diff = {}
remote = self.class.fetch(id, _prefix) || self.class.new({}, _prefix)
remote._attributes.each do |key, value|
unless _attributes[key] == value
diff[key] = { local: _attributes[key], remote: value }
end
end
diff
end | [
"def",
"diff",
"diff",
"=",
"{",
"}",
"remote",
"=",
"self",
".",
"class",
".",
"fetch",
"(",
"id",
",",
"_prefix",
")",
"||",
"self",
".",
"class",
".",
"new",
"(",
"{",
"}",
",",
"_prefix",
")",
"remote",
".",
"_attributes",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"unless",
"_attributes",
"[",
"key",
"]",
"==",
"value",
"diff",
"[",
"key",
"]",
"=",
"{",
"local",
":",
"_attributes",
"[",
"key",
"]",
",",
"remote",
":",
"value",
"}",
"end",
"end",
"diff",
"end"
] | Calculate a differential of the attributes on the local resource with
it's remote Chef Server counterpart.
@example when the local resource is in sync with the remote resource
bacon = Bacon.first
bacon.diff #=> {}
@example when the local resource differs from the remote resource
bacon = Bacon.first
bacon.description = "My new description"
bacon.diff #=> { :description => { :local => "My new description", :remote => "Old description" } }
@note This is a VERY expensive operation - use it sparringly!
@return [Hash] | [
"Calculate",
"a",
"differential",
"of",
"the",
"attributes",
"on",
"the",
"local",
"resource",
"with",
"it",
"s",
"remote",
"Chef",
"Server",
"counterpart",
"."
] | a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f | https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/resources/base.rb#L862-L873 | train |
tas50/chef-api | lib/chef-api/resources/base.rb | ChefAPI.Resource::Base.to_hash | def to_hash
{}.tap do |hash|
_attributes.each do |key, value|
hash[key] = value.respond_to?(:to_hash) ? value.to_hash : value
end
end
end | ruby | def to_hash
{}.tap do |hash|
_attributes.each do |key, value|
hash[key] = value.respond_to?(:to_hash) ? value.to_hash : value
end
end
end | [
"def",
"to_hash",
"{",
"}",
".",
"tap",
"do",
"|",
"hash",
"|",
"_attributes",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"hash",
"[",
"key",
"]",
"=",
"value",
".",
"respond_to?",
"(",
":to_hash",
")",
"?",
"value",
".",
"to_hash",
":",
"value",
"end",
"end",
"end"
] | The hash representation of this resource. All attributes are serialized
and any values that respond to +to_hash+ are also serialized.
@return [Hash] | [
"The",
"hash",
"representation",
"of",
"this",
"resource",
".",
"All",
"attributes",
"are",
"serialized",
"and",
"any",
"values",
"that",
"respond",
"to",
"+",
"to_hash",
"+",
"are",
"also",
"serialized",
"."
] | a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f | https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/resources/base.rb#L917-L923 | train |
tas50/chef-api | lib/chef-api/resources/base.rb | ChefAPI.Resource::Base.inspect | def inspect
attrs = (_prefix).merge(_attributes).map do |key, value|
if value.is_a?(String)
"#{key}: #{Util.truncate(value, length: 50).inspect}"
else
"#{key}: #{value.inspect}"
end
end
"#<#{self.class.classname} #{attrs.join(', ')}>"
end | ruby | def inspect
attrs = (_prefix).merge(_attributes).map do |key, value|
if value.is_a?(String)
"#{key}: #{Util.truncate(value, length: 50).inspect}"
else
"#{key}: #{value.inspect}"
end
end
"#<#{self.class.classname} #{attrs.join(', ')}>"
end | [
"def",
"inspect",
"attrs",
"=",
"(",
"_prefix",
")",
".",
"merge",
"(",
"_attributes",
")",
".",
"map",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"value",
".",
"is_a?",
"(",
"String",
")",
"\"#{key}: #{Util.truncate(value, length: 50).inspect}\"",
"else",
"\"#{key}: #{value.inspect}\"",
"end",
"end",
"\"#<#{self.class.classname} #{attrs.join(', ')}>\"",
"end"
] | Custom inspect method for easier readability.
@return [String] | [
"Custom",
"inspect",
"method",
"for",
"easier",
"readability",
"."
] | a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f | https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/resources/base.rb#L948-L958 | train |
tas50/chef-api | lib/chef-api/validators/type.rb | ChefAPI.Validator::Type.validate | def validate(resource)
value = resource._attributes[attribute]
if value && !types.any? { |type| value.is_a?(type) }
short_name = type.to_s.split('::').last
resource.errors.add(attribute, "must be a kind of #{short_name}")
end
end | ruby | def validate(resource)
value = resource._attributes[attribute]
if value && !types.any? { |type| value.is_a?(type) }
short_name = type.to_s.split('::').last
resource.errors.add(attribute, "must be a kind of #{short_name}")
end
end | [
"def",
"validate",
"(",
"resource",
")",
"value",
"=",
"resource",
".",
"_attributes",
"[",
"attribute",
"]",
"if",
"value",
"&&",
"!",
"types",
".",
"any?",
"{",
"|",
"type",
"|",
"value",
".",
"is_a?",
"(",
"type",
")",
"}",
"short_name",
"=",
"type",
".",
"to_s",
".",
"split",
"(",
"'::'",
")",
".",
"last",
"resource",
".",
"errors",
".",
"add",
"(",
"attribute",
",",
"\"must be a kind of #{short_name}\"",
")",
"end",
"end"
] | Overload the super method to capture the type attribute in the options
hash. | [
"Overload",
"the",
"super",
"method",
"to",
"capture",
"the",
"type",
"attribute",
"in",
"the",
"options",
"hash",
"."
] | a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f | https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/validators/type.rb#L14-L21 | train |
tas50/chef-api | lib/chef-api/authentication.rb | ChefAPI.Authentication.digest_io | def digest_io(io)
digester = Digest::SHA1.new
while buffer = io.read(1024)
digester.update(buffer)
end
io.rewind
Base64.encode64(digester.digest)
end | ruby | def digest_io(io)
digester = Digest::SHA1.new
while buffer = io.read(1024)
digester.update(buffer)
end
io.rewind
Base64.encode64(digester.digest)
end | [
"def",
"digest_io",
"(",
"io",
")",
"digester",
"=",
"Digest",
"::",
"SHA1",
".",
"new",
"while",
"buffer",
"=",
"io",
".",
"read",
"(",
"1024",
")",
"digester",
".",
"update",
"(",
"buffer",
")",
"end",
"io",
".",
"rewind",
"Base64",
".",
"encode64",
"(",
"digester",
".",
"digest",
")",
"end"
] | Hash the given object.
@param [String, IO] object
a string or IO object to hash
@return [String]
the hashed value
Digest the given IO, reading in 1024 bytes at one time.
@param [IO] io
the IO (or File object)
@return [String] | [
"Hash",
"the",
"given",
"object",
"."
] | a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f | https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/authentication.rb#L276-L286 | train |
tas50/chef-api | lib/chef-api/resources/collection_proxy.rb | ChefAPI.Resource::CollectionProxy.fetch | def fetch(id)
return nil unless exists?(id)
cached(id) { klass.from_url(get(id), prefix) }
end | ruby | def fetch(id)
return nil unless exists?(id)
cached(id) { klass.from_url(get(id), prefix) }
end | [
"def",
"fetch",
"(",
"id",
")",
"return",
"nil",
"unless",
"exists?",
"(",
"id",
")",
"cached",
"(",
"id",
")",
"{",
"klass",
".",
"from_url",
"(",
"get",
"(",
"id",
")",
",",
"prefix",
")",
"}",
"end"
] | Fetch a specific resource in the collection by id.
@example Fetch a resource
Bacon.first.items.fetch('crispy')
@param [String, Symbol] id
the id of the resource to fetch
@return [Resource::Base, nil]
the fetched class, or nil if it does not exists | [
"Fetch",
"a",
"specific",
"resource",
"in",
"the",
"collection",
"by",
"id",
"."
] | a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f | https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/resources/collection_proxy.rb#L60-L63 | train |
tas50/chef-api | lib/chef-api/resources/collection_proxy.rb | ChefAPI.Resource::CollectionProxy.each | def each(&block)
collection.each do |id, url|
object = cached(id) { klass.from_url(url, prefix) }
block.call(object) if block
end
end | ruby | def each(&block)
collection.each do |id, url|
object = cached(id) { klass.from_url(url, prefix) }
block.call(object) if block
end
end | [
"def",
"each",
"(",
"&",
"block",
")",
"collection",
".",
"each",
"do",
"|",
"id",
",",
"url",
"|",
"object",
"=",
"cached",
"(",
"id",
")",
"{",
"klass",
".",
"from_url",
"(",
"url",
",",
"prefix",
")",
"}",
"block",
".",
"call",
"(",
"object",
")",
"if",
"block",
"end",
"end"
] | The custom iterator for looping over each object in this collection. For
more information, please see the +Enumerator+ module in Ruby core. | [
"The",
"custom",
"iterator",
"for",
"looping",
"over",
"each",
"object",
"in",
"this",
"collection",
".",
"For",
"more",
"information",
"please",
"see",
"the",
"+",
"Enumerator",
"+",
"module",
"in",
"Ruby",
"core",
"."
] | a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f | https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/resources/collection_proxy.rb#L100-L105 | train |
tas50/chef-api | lib/chef-api/resources/collection_proxy.rb | ChefAPI.Resource::CollectionProxy.inspect | def inspect
objects = collection
.map { |id, _| cached(id) || klass.new(klass.schema.primary_key => id) }
.map { |object| object.to_s }
"#<#{self.class.name} [#{objects.join(', ')}]>"
end | ruby | def inspect
objects = collection
.map { |id, _| cached(id) || klass.new(klass.schema.primary_key => id) }
.map { |object| object.to_s }
"#<#{self.class.name} [#{objects.join(', ')}]>"
end | [
"def",
"inspect",
"objects",
"=",
"collection",
".",
"map",
"{",
"|",
"id",
",",
"_",
"|",
"cached",
"(",
"id",
")",
"||",
"klass",
".",
"new",
"(",
"klass",
".",
"schema",
".",
"primary_key",
"=>",
"id",
")",
"}",
".",
"map",
"{",
"|",
"object",
"|",
"object",
".",
"to_s",
"}",
"\"#<#{self.class.name} [#{objects.join(', ')}]>\"",
"end"
] | The detailed string representation of this collection proxy.
@return [String] | [
"The",
"detailed",
"string",
"representation",
"of",
"this",
"collection",
"proxy",
"."
] | a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f | https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/resources/collection_proxy.rb#L131-L137 | train |
tas50/chef-api | lib/chef-api/connection.rb | ChefAPI.Connection.add_request_headers | def add_request_headers(request)
log.info "Adding request headers..."
headers = {
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Connection' => 'keep-alive',
'Keep-Alive' => '30',
'User-Agent' => user_agent,
'X-Chef-Version' => '11.4.0',
}
headers.each do |key, value|
log.debug "#{key}: #{value}"
request[key] = value
end
end | ruby | def add_request_headers(request)
log.info "Adding request headers..."
headers = {
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Connection' => 'keep-alive',
'Keep-Alive' => '30',
'User-Agent' => user_agent,
'X-Chef-Version' => '11.4.0',
}
headers.each do |key, value|
log.debug "#{key}: #{value}"
request[key] = value
end
end | [
"def",
"add_request_headers",
"(",
"request",
")",
"log",
".",
"info",
"\"Adding request headers...\"",
"headers",
"=",
"{",
"'Accept'",
"=>",
"'application/json'",
",",
"'Content-Type'",
"=>",
"'application/json'",
",",
"'Connection'",
"=>",
"'keep-alive'",
",",
"'Keep-Alive'",
"=>",
"'30'",
",",
"'User-Agent'",
"=>",
"user_agent",
",",
"'X-Chef-Version'",
"=>",
"'11.4.0'",
",",
"}",
"headers",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"log",
".",
"debug",
"\"#{key}: #{value}\"",
"request",
"[",
"key",
"]",
"=",
"value",
"end",
"end"
] | Adds the default headers to the request object.
@param [Net::HTTP::Request] request | [
"Adds",
"the",
"default",
"headers",
"to",
"the",
"request",
"object",
"."
] | a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f | https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/connection.rb#L457-L473 | train |
tas50/chef-api | lib/chef-api/schema.rb | ChefAPI.Schema.attribute | def attribute(key, options = {})
if primary_key = options.delete(:primary)
@primary_key = key.to_sym
end
@attributes[key] = options.delete(:default)
# All remaining options are assumed to be validations
options.each do |validation, options|
if options
@validators << Validator.find(validation).new(key, options)
end
end
key
end | ruby | def attribute(key, options = {})
if primary_key = options.delete(:primary)
@primary_key = key.to_sym
end
@attributes[key] = options.delete(:default)
# All remaining options are assumed to be validations
options.each do |validation, options|
if options
@validators << Validator.find(validation).new(key, options)
end
end
key
end | [
"def",
"attribute",
"(",
"key",
",",
"options",
"=",
"{",
"}",
")",
"if",
"primary_key",
"=",
"options",
".",
"delete",
"(",
":primary",
")",
"@primary_key",
"=",
"key",
".",
"to_sym",
"end",
"@attributes",
"[",
"key",
"]",
"=",
"options",
".",
"delete",
"(",
":default",
")",
"# All remaining options are assumed to be validations",
"options",
".",
"each",
"do",
"|",
"validation",
",",
"options",
"|",
"if",
"options",
"@validators",
"<<",
"Validator",
".",
"find",
"(",
"validation",
")",
".",
"new",
"(",
"key",
",",
"options",
")",
"end",
"end",
"key",
"end"
] | DSL method for defining an attribute.
@param [Symbol] key
the key to use
@param [Hash] options
a list of options to create the attribute with
@return [Symbol]
the attribute | [
"DSL",
"method",
"for",
"defining",
"an",
"attribute",
"."
] | a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f | https://github.com/tas50/chef-api/blob/a53c47efa5f6f5c8bb0f773278e9c0fd79f12b7f/lib/chef-api/schema.rb#L96-L111 | train |
laserlemon/vestal_versions | lib/vestal_versions/version.rb | VestalVersions.Version.original_number | def original_number
if reverted_from.nil?
number
else
version = versioned.versions.at(reverted_from)
version.nil? ? 1 : version.original_number
end
end | ruby | def original_number
if reverted_from.nil?
number
else
version = versioned.versions.at(reverted_from)
version.nil? ? 1 : version.original_number
end
end | [
"def",
"original_number",
"if",
"reverted_from",
".",
"nil?",
"number",
"else",
"version",
"=",
"versioned",
".",
"versions",
".",
"at",
"(",
"reverted_from",
")",
"version",
".",
"nil?",
"?",
"1",
":",
"version",
".",
"original_number",
"end",
"end"
] | Returns the original version number that this version was. | [
"Returns",
"the",
"original",
"version",
"number",
"that",
"this",
"version",
"was",
"."
] | beccc5744ec030664f003d61ffb617edefd7885b | https://github.com/laserlemon/vestal_versions/blob/beccc5744ec030664f003d61ffb617edefd7885b/lib/vestal_versions/version.rb#L41-L48 | train |
laserlemon/vestal_versions | lib/vestal_versions/creation.rb | VestalVersions.Creation.update_version | def update_version
return create_version unless v = versions.last
v.modifications_will_change!
v.update_attribute(:modifications, v.changes.append_changes(version_changes))
reset_version_changes
reset_version
end | ruby | def update_version
return create_version unless v = versions.last
v.modifications_will_change!
v.update_attribute(:modifications, v.changes.append_changes(version_changes))
reset_version_changes
reset_version
end | [
"def",
"update_version",
"return",
"create_version",
"unless",
"v",
"=",
"versions",
".",
"last",
"v",
".",
"modifications_will_change!",
"v",
".",
"update_attribute",
"(",
":modifications",
",",
"v",
".",
"changes",
".",
"append_changes",
"(",
"version_changes",
")",
")",
"reset_version_changes",
"reset_version",
"end"
] | Updates the last version's changes by appending the current version changes. | [
"Updates",
"the",
"last",
"version",
"s",
"changes",
"by",
"appending",
"the",
"current",
"version",
"changes",
"."
] | beccc5744ec030664f003d61ffb617edefd7885b | https://github.com/laserlemon/vestal_versions/blob/beccc5744ec030664f003d61ffb617edefd7885b/lib/vestal_versions/creation.rb#L65-L71 | train |
laserlemon/vestal_versions | lib/vestal_versions/reset.rb | VestalVersions.Reset.reset_to! | def reset_to!(value)
if saved = skip_version{ revert_to!(value) }
versions.send(:delete, versions.after(value))
reset_version
end
saved
end | ruby | def reset_to!(value)
if saved = skip_version{ revert_to!(value) }
versions.send(:delete, versions.after(value))
reset_version
end
saved
end | [
"def",
"reset_to!",
"(",
"value",
")",
"if",
"saved",
"=",
"skip_version",
"{",
"revert_to!",
"(",
"value",
")",
"}",
"versions",
".",
"send",
"(",
":delete",
",",
"versions",
".",
"after",
"(",
"value",
")",
")",
"reset_version",
"end",
"saved",
"end"
] | Adds the instance methods required to reset an object to a previous version.
Similar to +revert_to!+, the +reset_to!+ method reverts an object to a previous version,
only instead of creating a new record in the version history, +reset_to!+ deletes all of
the version history that occurs after the version reverted to.
The action taken on each version record after the point of reversion is determined by the
<tt>:dependent</tt> option given to the +versioned+ method. See the +versioned+ method
documentation for more details. | [
"Adds",
"the",
"instance",
"methods",
"required",
"to",
"reset",
"an",
"object",
"to",
"a",
"previous",
"version",
".",
"Similar",
"to",
"+",
"revert_to!",
"+",
"the",
"+",
"reset_to!",
"+",
"method",
"reverts",
"an",
"object",
"to",
"a",
"previous",
"version",
"only",
"instead",
"of",
"creating",
"a",
"new",
"record",
"in",
"the",
"version",
"history",
"+",
"reset_to!",
"+",
"deletes",
"all",
"of",
"the",
"version",
"history",
"that",
"occurs",
"after",
"the",
"version",
"reverted",
"to",
"."
] | beccc5744ec030664f003d61ffb617edefd7885b | https://github.com/laserlemon/vestal_versions/blob/beccc5744ec030664f003d61ffb617edefd7885b/lib/vestal_versions/reset.rb#L15-L21 | train |
laserlemon/vestal_versions | lib/vestal_versions/version_tagging.rb | VestalVersions.VersionTagging.tag_version | def tag_version(tag)
v = versions.at(version) || versions.build(:number => 1)
t = v.tag!(tag)
versions.reload
t
end | ruby | def tag_version(tag)
v = versions.at(version) || versions.build(:number => 1)
t = v.tag!(tag)
versions.reload
t
end | [
"def",
"tag_version",
"(",
"tag",
")",
"v",
"=",
"versions",
".",
"at",
"(",
"version",
")",
"||",
"versions",
".",
"build",
"(",
":number",
"=>",
"1",
")",
"t",
"=",
"v",
".",
"tag!",
"(",
"tag",
")",
"versions",
".",
"reload",
"t",
"end"
] | Adds an instance method which allows version tagging through the parent object.
Accepts a single string argument which is attached to the version record associated with
the current version number of the parent object.
Returns the given tag if successful, nil if not. Tags must be unique within the scope of
the parent object. Tag creation will fail if non-unique.
Version records corresponding to version number 1 are not typically created, but one will
be built to house the given tag if the parent object's current version number is 1. | [
"Adds",
"an",
"instance",
"method",
"which",
"allows",
"version",
"tagging",
"through",
"the",
"parent",
"object",
".",
"Accepts",
"a",
"single",
"string",
"argument",
"which",
"is",
"attached",
"to",
"the",
"version",
"record",
"associated",
"with",
"the",
"current",
"version",
"number",
"of",
"the",
"parent",
"object",
"."
] | beccc5744ec030664f003d61ffb617edefd7885b | https://github.com/laserlemon/vestal_versions/blob/beccc5744ec030664f003d61ffb617edefd7885b/lib/vestal_versions/version_tagging.rb#L17-L22 | train |
laserlemon/vestal_versions | lib/vestal_versions/reversion.rb | VestalVersions.Reversion.revert_to | def revert_to(value)
to_number = versions.number_at(value)
changes_between(version, to_number).each do |attribute, change|
write_attribute(attribute, change.last)
end
reset_version(to_number)
end | ruby | def revert_to(value)
to_number = versions.number_at(value)
changes_between(version, to_number).each do |attribute, change|
write_attribute(attribute, change.last)
end
reset_version(to_number)
end | [
"def",
"revert_to",
"(",
"value",
")",
"to_number",
"=",
"versions",
".",
"number_at",
"(",
"value",
")",
"changes_between",
"(",
"version",
",",
"to_number",
")",
".",
"each",
"do",
"|",
"attribute",
",",
"change",
"|",
"write_attribute",
"(",
"attribute",
",",
"change",
".",
"last",
")",
"end",
"reset_version",
"(",
"to_number",
")",
"end"
] | Accepts a value corresponding to a specific version record, builds a history of changes
between that version and the current version, and then iterates over that history updating
the object's attributes until the it's reverted to its prior state.
The single argument should adhere to one of the formats as documented in the +at+ method of
VestalVersions::Versions.
After the object is reverted to the target version, it is not saved. In order to save the
object after the reversion, use the +revert_to!+ method.
The version number of the object will reflect whatever version has been reverted to, and
the return value of the +revert_to+ method is also the target version number. | [
"Accepts",
"a",
"value",
"corresponding",
"to",
"a",
"specific",
"version",
"record",
"builds",
"a",
"history",
"of",
"changes",
"between",
"that",
"version",
"and",
"the",
"current",
"version",
"and",
"then",
"iterates",
"over",
"that",
"history",
"updating",
"the",
"object",
"s",
"attributes",
"until",
"the",
"it",
"s",
"reverted",
"to",
"its",
"prior",
"state",
"."
] | beccc5744ec030664f003d61ffb617edefd7885b | https://github.com/laserlemon/vestal_versions/blob/beccc5744ec030664f003d61ffb617edefd7885b/lib/vestal_versions/reversion.rb#L25-L33 | train |
realestate-com-au/stackup | lib/stackup/stack_watcher.rb | Stackup.StackWatcher.zero | def zero
last_event = stack.events.first
@last_processed_event_id = last_event.id unless last_event.nil?
nil
rescue Aws::CloudFormation::Errors::ValidationError
end | ruby | def zero
last_event = stack.events.first
@last_processed_event_id = last_event.id unless last_event.nil?
nil
rescue Aws::CloudFormation::Errors::ValidationError
end | [
"def",
"zero",
"last_event",
"=",
"stack",
".",
"events",
".",
"first",
"@last_processed_event_id",
"=",
"last_event",
".",
"id",
"unless",
"last_event",
".",
"nil?",
"nil",
"rescue",
"Aws",
"::",
"CloudFormation",
"::",
"Errors",
"::",
"ValidationError",
"end"
] | Consume all new events | [
"Consume",
"all",
"new",
"events"
] | 3bb0012bc89ad3c22d344a34ff221473ae5934d9 | https://github.com/realestate-com-au/stackup/blob/3bb0012bc89ad3c22d344a34ff221473ae5934d9/lib/stackup/stack_watcher.rb#L36-L41 | train |
realestate-com-au/stackup | lib/stackup/stack.rb | Stackup.Stack.on_event | def on_event(event_handler = nil, &block)
event_handler ||= block
raise ArgumentError, "no event_handler provided" if event_handler.nil?
@event_handler = event_handler
end | ruby | def on_event(event_handler = nil, &block)
event_handler ||= block
raise ArgumentError, "no event_handler provided" if event_handler.nil?
@event_handler = event_handler
end | [
"def",
"on_event",
"(",
"event_handler",
"=",
"nil",
",",
"&",
"block",
")",
"event_handler",
"||=",
"block",
"raise",
"ArgumentError",
",",
"\"no event_handler provided\"",
"if",
"event_handler",
".",
"nil?",
"@event_handler",
"=",
"event_handler",
"end"
] | Register a handler for reporting of stack events.
@param [Proc] event_handler | [
"Register",
"a",
"handler",
"for",
"reporting",
"of",
"stack",
"events",
"."
] | 3bb0012bc89ad3c22d344a34ff221473ae5934d9 | https://github.com/realestate-com-au/stackup/blob/3bb0012bc89ad3c22d344a34ff221473ae5934d9/lib/stackup/stack.rb#L41-L45 | train |
realestate-com-au/stackup | lib/stackup/stack.rb | Stackup.Stack.create_or_update | def create_or_update(options)
options = options.dup
if (template_data = options.delete(:template))
options[:template_body] = MultiJson.dump(template_data)
end
if (parameters = options[:parameters])
options[:parameters] = Parameters.new(parameters).to_a
end
if (tags = options[:tags])
options[:tags] = normalize_tags(tags)
end
if (policy_data = options.delete(:stack_policy))
options[:stack_policy_body] = MultiJson.dump(policy_data)
end
if (policy_data = options.delete(:stack_policy_during_update))
options[:stack_policy_during_update_body] = MultiJson.dump(policy_data)
end
options[:capabilities] ||= ["CAPABILITY_NAMED_IAM"]
delete if ALMOST_DEAD_STATUSES.include?(status)
update(options)
rescue NoSuchStack
create(options)
end | ruby | def create_or_update(options)
options = options.dup
if (template_data = options.delete(:template))
options[:template_body] = MultiJson.dump(template_data)
end
if (parameters = options[:parameters])
options[:parameters] = Parameters.new(parameters).to_a
end
if (tags = options[:tags])
options[:tags] = normalize_tags(tags)
end
if (policy_data = options.delete(:stack_policy))
options[:stack_policy_body] = MultiJson.dump(policy_data)
end
if (policy_data = options.delete(:stack_policy_during_update))
options[:stack_policy_during_update_body] = MultiJson.dump(policy_data)
end
options[:capabilities] ||= ["CAPABILITY_NAMED_IAM"]
delete if ALMOST_DEAD_STATUSES.include?(status)
update(options)
rescue NoSuchStack
create(options)
end | [
"def",
"create_or_update",
"(",
"options",
")",
"options",
"=",
"options",
".",
"dup",
"if",
"(",
"template_data",
"=",
"options",
".",
"delete",
"(",
":template",
")",
")",
"options",
"[",
":template_body",
"]",
"=",
"MultiJson",
".",
"dump",
"(",
"template_data",
")",
"end",
"if",
"(",
"parameters",
"=",
"options",
"[",
":parameters",
"]",
")",
"options",
"[",
":parameters",
"]",
"=",
"Parameters",
".",
"new",
"(",
"parameters",
")",
".",
"to_a",
"end",
"if",
"(",
"tags",
"=",
"options",
"[",
":tags",
"]",
")",
"options",
"[",
":tags",
"]",
"=",
"normalize_tags",
"(",
"tags",
")",
"end",
"if",
"(",
"policy_data",
"=",
"options",
".",
"delete",
"(",
":stack_policy",
")",
")",
"options",
"[",
":stack_policy_body",
"]",
"=",
"MultiJson",
".",
"dump",
"(",
"policy_data",
")",
"end",
"if",
"(",
"policy_data",
"=",
"options",
".",
"delete",
"(",
":stack_policy_during_update",
")",
")",
"options",
"[",
":stack_policy_during_update_body",
"]",
"=",
"MultiJson",
".",
"dump",
"(",
"policy_data",
")",
"end",
"options",
"[",
":capabilities",
"]",
"||=",
"[",
"\"CAPABILITY_NAMED_IAM\"",
"]",
"delete",
"if",
"ALMOST_DEAD_STATUSES",
".",
"include?",
"(",
"status",
")",
"update",
"(",
"options",
")",
"rescue",
"NoSuchStack",
"create",
"(",
"options",
")",
"end"
] | Create or update the stack.
@param [Hash] options create/update options
accepts a superset of the options supported by
+Aws::CloudFormation::Stack#update+
(see http://docs.aws.amazon.com/sdkforruby/api/Aws/CloudFormation/Stack.html#update-instance_method)
@option options [Array<String>] :capabilities (CAPABILITY_NAMED_IAM)
list of capabilities required for stack template
@option options [boolean] :disable_rollback (false)
if true, disable rollback if stack creation fails
@option options [String] :notification_arns
ARNs for the Amazon SNS topics associated with this stack
@option options [String] :on_failure (ROLLBACK)
if stack creation fails: DO_NOTHING, ROLLBACK, or DELETE
@option options [Hash, Array<Hash>] :parameters
stack parameters, either as a Hash, or an Array of
+Aws::CloudFormation::Types::Parameter+ structures
@option options [Hash, Array<Hash>] :tags
stack tags, either as a Hash, or an Array of
+Aws::CloudFormation::Types::Tag+ structures
@option options [Array<String>] :resource_types
resource types that you have permissions to work with
@option options [Hash] :stack_policy
stack policy, as Ruby data
@option options [String] :stack_policy_body
stack policy, as JSON
@option options [String] :stack_policy_url
location of stack policy
@option options [Hash] :stack_policy_during_update
temporary stack policy, as Ruby data
@option options [String] :stack_policy_during_update_body
temporary stack policy, as JSON
@option options [String] :stack_policy_during_update_url
location of temporary stack policy
@option options [Hash] :template
stack template, as Ruby data
@option options [String] :template_body
stack template, as JSON or YAML
@option options [String] :template_url
location of stack template
@option options [Integer] :timeout_in_minutes
stack creation timeout
@option options [boolean] :use_previous_template
if true, reuse the existing template
@return [String] resulting stack status
@raise [Stackup::StackUpdateError] if operation fails | [
"Create",
"or",
"update",
"the",
"stack",
"."
] | 3bb0012bc89ad3c22d344a34ff221473ae5934d9 | https://github.com/realestate-com-au/stackup/blob/3bb0012bc89ad3c22d344a34ff221473ae5934d9/lib/stackup/stack.rb#L114-L136 | train |
realestate-com-au/stackup | lib/stackup/stack.rb | Stackup.Stack.modify_stack | def modify_stack(target_status, failure_message, &block)
if wait?
status = modify_stack_synchronously(&block)
raise StackUpdateError, failure_message unless target_status === status
status
else
modify_stack_asynchronously(&block)
end
end | ruby | def modify_stack(target_status, failure_message, &block)
if wait?
status = modify_stack_synchronously(&block)
raise StackUpdateError, failure_message unless target_status === status
status
else
modify_stack_asynchronously(&block)
end
end | [
"def",
"modify_stack",
"(",
"target_status",
",",
"failure_message",
",",
"&",
"block",
")",
"if",
"wait?",
"status",
"=",
"modify_stack_synchronously",
"(",
"block",
")",
"raise",
"StackUpdateError",
",",
"failure_message",
"unless",
"target_status",
"===",
"status",
"status",
"else",
"modify_stack_asynchronously",
"(",
"block",
")",
"end",
"end"
] | Execute a block, to modify the stack.
@return the stack status | [
"Execute",
"a",
"block",
"to",
"modify",
"the",
"stack",
"."
] | 3bb0012bc89ad3c22d344a34ff221473ae5934d9 | https://github.com/realestate-com-au/stackup/blob/3bb0012bc89ad3c22d344a34ff221473ae5934d9/lib/stackup/stack.rb#L323-L331 | train |
realestate-com-au/stackup | lib/stackup/stack.rb | Stackup.Stack.modify_stack_synchronously | def modify_stack_synchronously
watch do |watcher|
handling_cf_errors do
yield
end
loop do
watcher.each_new_event(&event_handler)
status = self.status
logger.debug("stack_status=#{status}")
return status if status.nil? || status =~ /_(COMPLETE|FAILED)$/
sleep(wait_poll_interval)
end
end
end | ruby | def modify_stack_synchronously
watch do |watcher|
handling_cf_errors do
yield
end
loop do
watcher.each_new_event(&event_handler)
status = self.status
logger.debug("stack_status=#{status}")
return status if status.nil? || status =~ /_(COMPLETE|FAILED)$/
sleep(wait_poll_interval)
end
end
end | [
"def",
"modify_stack_synchronously",
"watch",
"do",
"|",
"watcher",
"|",
"handling_cf_errors",
"do",
"yield",
"end",
"loop",
"do",
"watcher",
".",
"each_new_event",
"(",
"event_handler",
")",
"status",
"=",
"self",
".",
"status",
"logger",
".",
"debug",
"(",
"\"stack_status=#{status}\"",
")",
"return",
"status",
"if",
"status",
".",
"nil?",
"||",
"status",
"=~",
"/",
"/",
"sleep",
"(",
"wait_poll_interval",
")",
"end",
"end",
"end"
] | Execute a block, reporting stack events, until the stack is stable.
@return the final stack status | [
"Execute",
"a",
"block",
"reporting",
"stack",
"events",
"until",
"the",
"stack",
"is",
"stable",
"."
] | 3bb0012bc89ad3c22d344a34ff221473ae5934d9 | https://github.com/realestate-com-au/stackup/blob/3bb0012bc89ad3c22d344a34ff221473ae5934d9/lib/stackup/stack.rb#L337-L350 | train |
realestate-com-au/stackup | lib/stackup/stack.rb | Stackup.Stack.extract_hash | def extract_hash(collection_name, key_name, value_name)
handling_cf_errors do
{}.tap do |result|
cf_stack.public_send(collection_name).each do |item|
key = item.public_send(key_name)
value = item.public_send(value_name)
result[key] = value
end
end
end
end | ruby | def extract_hash(collection_name, key_name, value_name)
handling_cf_errors do
{}.tap do |result|
cf_stack.public_send(collection_name).each do |item|
key = item.public_send(key_name)
value = item.public_send(value_name)
result[key] = value
end
end
end
end | [
"def",
"extract_hash",
"(",
"collection_name",
",",
"key_name",
",",
"value_name",
")",
"handling_cf_errors",
"do",
"{",
"}",
".",
"tap",
"do",
"|",
"result",
"|",
"cf_stack",
".",
"public_send",
"(",
"collection_name",
")",
".",
"each",
"do",
"|",
"item",
"|",
"key",
"=",
"item",
".",
"public_send",
"(",
"key_name",
")",
"value",
"=",
"item",
".",
"public_send",
"(",
"value_name",
")",
"result",
"[",
"key",
"]",
"=",
"value",
"end",
"end",
"end",
"end"
] | Extract data from a collection attribute of the stack.
@param [Symbol] collection_name collection attribute name
@param [Symbol] key_name name of item attribute that provides key
@param [Symbol] value_name name of item attribute that provides value
@return [Hash<String, String>] mapping of collection | [
"Extract",
"data",
"from",
"a",
"collection",
"attribute",
"of",
"the",
"stack",
"."
] | 3bb0012bc89ad3c22d344a34ff221473ae5934d9 | https://github.com/realestate-com-au/stackup/blob/3bb0012bc89ad3c22d344a34ff221473ae5934d9/lib/stackup/stack.rb#L380-L390 | train |
realestate-com-au/stackup | lib/stackup/change_set.rb | Stackup.ChangeSet.create | def create(options = {})
options = options.dup
options[:stack_name] = stack.name
options[:change_set_name] = name
options[:change_set_type] = stack.exists? ? "UPDATE" : "CREATE"
force = options.delete(:force)
options[:template_body] = MultiJson.dump(options.delete(:template)) if options[:template]
options[:parameters] = Parameters.new(options[:parameters]).to_a if options[:parameters]
options[:tags] = normalize_tags(options[:tags]) if options[:tags]
options[:capabilities] ||= ["CAPABILITY_NAMED_IAM"]
delete if force
handling_cf_errors do
cf_client.create_change_set(options)
loop do
current = describe
logger.debug("change_set_status=#{current.status}")
case current.status
when /COMPLETE/
return current.status
when "FAILED"
logger.error(current.status_reason)
raise StackUpdateError, "change-set creation failed" if status == "FAILED"
end
sleep(wait_poll_interval)
end
status
end
end | ruby | def create(options = {})
options = options.dup
options[:stack_name] = stack.name
options[:change_set_name] = name
options[:change_set_type] = stack.exists? ? "UPDATE" : "CREATE"
force = options.delete(:force)
options[:template_body] = MultiJson.dump(options.delete(:template)) if options[:template]
options[:parameters] = Parameters.new(options[:parameters]).to_a if options[:parameters]
options[:tags] = normalize_tags(options[:tags]) if options[:tags]
options[:capabilities] ||= ["CAPABILITY_NAMED_IAM"]
delete if force
handling_cf_errors do
cf_client.create_change_set(options)
loop do
current = describe
logger.debug("change_set_status=#{current.status}")
case current.status
when /COMPLETE/
return current.status
when "FAILED"
logger.error(current.status_reason)
raise StackUpdateError, "change-set creation failed" if status == "FAILED"
end
sleep(wait_poll_interval)
end
status
end
end | [
"def",
"create",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"options",
".",
"dup",
"options",
"[",
":stack_name",
"]",
"=",
"stack",
".",
"name",
"options",
"[",
":change_set_name",
"]",
"=",
"name",
"options",
"[",
":change_set_type",
"]",
"=",
"stack",
".",
"exists?",
"?",
"\"UPDATE\"",
":",
"\"CREATE\"",
"force",
"=",
"options",
".",
"delete",
"(",
":force",
")",
"options",
"[",
":template_body",
"]",
"=",
"MultiJson",
".",
"dump",
"(",
"options",
".",
"delete",
"(",
":template",
")",
")",
"if",
"options",
"[",
":template",
"]",
"options",
"[",
":parameters",
"]",
"=",
"Parameters",
".",
"new",
"(",
"options",
"[",
":parameters",
"]",
")",
".",
"to_a",
"if",
"options",
"[",
":parameters",
"]",
"options",
"[",
":tags",
"]",
"=",
"normalize_tags",
"(",
"options",
"[",
":tags",
"]",
")",
"if",
"options",
"[",
":tags",
"]",
"options",
"[",
":capabilities",
"]",
"||=",
"[",
"\"CAPABILITY_NAMED_IAM\"",
"]",
"delete",
"if",
"force",
"handling_cf_errors",
"do",
"cf_client",
".",
"create_change_set",
"(",
"options",
")",
"loop",
"do",
"current",
"=",
"describe",
"logger",
".",
"debug",
"(",
"\"change_set_status=#{current.status}\"",
")",
"case",
"current",
".",
"status",
"when",
"/",
"/",
"return",
"current",
".",
"status",
"when",
"\"FAILED\"",
"logger",
".",
"error",
"(",
"current",
".",
"status_reason",
")",
"raise",
"StackUpdateError",
",",
"\"change-set creation failed\"",
"if",
"status",
"==",
"\"FAILED\"",
"end",
"sleep",
"(",
"wait_poll_interval",
")",
"end",
"status",
"end",
"end"
] | Create the change-set.
Refer +Aws::CloudFormation::Client#create_change_set+
(see http://docs.aws.amazon.com/sdkforruby/api/Aws/CloudFormation/Client.html#create_change_set-instance_method)
@param [Hash] options change-set options
@option options [Array<String>] :capabilities (CAPABILITY_NAMED_IAM)
list of capabilities required for stack template
@option options [String] :description
change-set description
@option options [String] :notification_arns
ARNs for the Amazon SNS topics associated with this stack
@option options [Hash, Array<Hash>] :parameters
stack parameters, either as a Hash, or an Array of
+Aws::CloudFormation::Types::Parameter+ structures
@option options [Hash, Array<Hash>] :tags
stack tags, either as a Hash, or an Array of
+Aws::CloudFormation::Types::Tag+ structures
@option options [Array<String>] :resource_types
resource types that you have permissions to work with
@option options [Hash] :template
stack template, as Ruby data
@option options [String] :template_body
stack template, as JSON or YAML
@option options [String] :template_url
location of stack template
@option options [boolean] :use_previous_template
if true, reuse the existing template
@option options [boolean] :force
if true, delete any existing change-set of the same name
@return [String] change-set id
@raise [Stackup::NoSuchStack] if the stack doesn't exist | [
"Create",
"the",
"change",
"-",
"set",
"."
] | 3bb0012bc89ad3c22d344a34ff221473ae5934d9 | https://github.com/realestate-com-au/stackup/blob/3bb0012bc89ad3c22d344a34ff221473ae5934d9/lib/stackup/change_set.rb#L53-L80 | train |
kristianmandrup/cantango | spec/active_record/scenarios/shared/permits/account_permits/user_account_permit.rb | UserAccountPermits.UserRolePermit.static_rules | def static_rules
cannot :manage, User
can :read, Comment
can :read, any(/Post/)
can :read, Article
can :write, any(/Article/)
author_of(Article) do |author|
author.can :manage
end
author_of(Post) do |author|
author.can :manage
end
author_of(Comment) do |author|
author.can :manage
end
# # can :manage, :all
# scope :account do |account|
# account.author_of(Article) do |author|
# author.can :manage
# author.cannot :delete
# end
#
# account.writer_of(Post).can :manage
# end
#
# scope :user do |user|
# user.writer_of(Comment).can :manage
# end
end | ruby | def static_rules
cannot :manage, User
can :read, Comment
can :read, any(/Post/)
can :read, Article
can :write, any(/Article/)
author_of(Article) do |author|
author.can :manage
end
author_of(Post) do |author|
author.can :manage
end
author_of(Comment) do |author|
author.can :manage
end
# # can :manage, :all
# scope :account do |account|
# account.author_of(Article) do |author|
# author.can :manage
# author.cannot :delete
# end
#
# account.writer_of(Post).can :manage
# end
#
# scope :user do |user|
# user.writer_of(Comment).can :manage
# end
end | [
"def",
"static_rules",
"cannot",
":manage",
",",
"User",
"can",
":read",
",",
"Comment",
"can",
":read",
",",
"any",
"(",
"/",
"/",
")",
"can",
":read",
",",
"Article",
"can",
":write",
",",
"any",
"(",
"/",
"/",
")",
"author_of",
"(",
"Article",
")",
"do",
"|",
"author",
"|",
"author",
".",
"can",
":manage",
"end",
"author_of",
"(",
"Post",
")",
"do",
"|",
"author",
"|",
"author",
".",
"can",
":manage",
"end",
"author_of",
"(",
"Comment",
")",
"do",
"|",
"author",
"|",
"author",
".",
"can",
":manage",
"end",
"# # can :manage, :all ",
"# scope :account do |account|",
"# account.author_of(Article) do |author|",
"# author.can :manage",
"# author.cannot :delete",
"# end ",
"# ",
"# account.writer_of(Post).can :manage",
"# end",
"# ",
"# scope :user do |user| ",
"# user.writer_of(Comment).can :manage",
"# end",
"end"
] | should take user and options args here ??? | [
"should",
"take",
"user",
"and",
"options",
"args",
"here",
"???"
] | 1920ea616ab27f702203949c4d199f1534bba89b | https://github.com/kristianmandrup/cantango/blob/1920ea616ab27f702203949c4d199f1534bba89b/spec/active_record/scenarios/shared/permits/account_permits/user_account_permit.rb#L10-L44 | train |
hanklords/flickraw | lib/flickraw/flickr.rb | FlickRaw.Flickr.call | def call(req, args={}, &block)
oauth_args = args.delete(:oauth) || {}
http_response = @oauth_consumer.post_form(REST_PATH, @access_secret, {:oauth_token => @access_token}.merge(oauth_args), build_args(args, req))
process_response(req, http_response.body)
end | ruby | def call(req, args={}, &block)
oauth_args = args.delete(:oauth) || {}
http_response = @oauth_consumer.post_form(REST_PATH, @access_secret, {:oauth_token => @access_token}.merge(oauth_args), build_args(args, req))
process_response(req, http_response.body)
end | [
"def",
"call",
"(",
"req",
",",
"args",
"=",
"{",
"}",
",",
"&",
"block",
")",
"oauth_args",
"=",
"args",
".",
"delete",
"(",
":oauth",
")",
"||",
"{",
"}",
"http_response",
"=",
"@oauth_consumer",
".",
"post_form",
"(",
"REST_PATH",
",",
"@access_secret",
",",
"{",
":oauth_token",
"=>",
"@access_token",
"}",
".",
"merge",
"(",
"oauth_args",
")",
",",
"build_args",
"(",
"args",
",",
"req",
")",
")",
"process_response",
"(",
"req",
",",
"http_response",
".",
"body",
")",
"end"
] | This is the central method. It does the actual request to the flickr server.
Raises FailedResponse if the response status is _failed_. | [
"This",
"is",
"the",
"central",
"method",
".",
"It",
"does",
"the",
"actual",
"request",
"to",
"the",
"flickr",
"server",
"."
] | 6bf254681f8d57e65b352d93fb49237bd178e695 | https://github.com/hanklords/flickraw/blob/6bf254681f8d57e65b352d93fb49237bd178e695/lib/flickraw/flickr.rb#L33-L37 | train |
hanklords/flickraw | lib/flickraw/flickr.rb | FlickRaw.Flickr.get_access_token | def get_access_token(token, secret, verify)
access_token = @oauth_consumer.access_token(FLICKR_OAUTH_ACCESS_TOKEN, secret, :oauth_token => token, :oauth_verifier => verify)
@access_token, @access_secret = access_token['oauth_token'], access_token['oauth_token_secret']
access_token
end | ruby | def get_access_token(token, secret, verify)
access_token = @oauth_consumer.access_token(FLICKR_OAUTH_ACCESS_TOKEN, secret, :oauth_token => token, :oauth_verifier => verify)
@access_token, @access_secret = access_token['oauth_token'], access_token['oauth_token_secret']
access_token
end | [
"def",
"get_access_token",
"(",
"token",
",",
"secret",
",",
"verify",
")",
"access_token",
"=",
"@oauth_consumer",
".",
"access_token",
"(",
"FLICKR_OAUTH_ACCESS_TOKEN",
",",
"secret",
",",
":oauth_token",
"=>",
"token",
",",
":oauth_verifier",
"=>",
"verify",
")",
"@access_token",
",",
"@access_secret",
"=",
"access_token",
"[",
"'oauth_token'",
"]",
",",
"access_token",
"[",
"'oauth_token_secret'",
"]",
"access_token",
"end"
] | Get an oauth access token.
flickr.get_access_token(token['oauth_token'], token['oauth_token_secret'], oauth_verifier) | [
"Get",
"an",
"oauth",
"access",
"token",
"."
] | 6bf254681f8d57e65b352d93fb49237bd178e695 | https://github.com/hanklords/flickraw/blob/6bf254681f8d57e65b352d93fb49237bd178e695/lib/flickraw/flickr.rb#L56-L60 | train |
slideshow-s9/slideshow | slideshow-models/lib/slideshow/helpers/capture_helper.rb | Slideshow.CaptureHelper.capture_erb | def capture_erb( *args, &block )
# get the buffer from the block's binding
buffer = _erb_buffer(block.binding) rescue nil
# If there is no buffer, just call the block and get the contents
if buffer.nil?
block.call(*args)
# If there is a buffer, execute the block, then extract its contents
else
pos = buffer.length
block.call(*args)
# extract the block
data = buffer[pos..-1]
# replace it in the original with empty string
buffer[pos..-1] = ""
data
end
end | ruby | def capture_erb( *args, &block )
# get the buffer from the block's binding
buffer = _erb_buffer(block.binding) rescue nil
# If there is no buffer, just call the block and get the contents
if buffer.nil?
block.call(*args)
# If there is a buffer, execute the block, then extract its contents
else
pos = buffer.length
block.call(*args)
# extract the block
data = buffer[pos..-1]
# replace it in the original with empty string
buffer[pos..-1] = ""
data
end
end | [
"def",
"capture_erb",
"(",
"*",
"args",
",",
"&",
"block",
")",
"# get the buffer from the block's binding\r",
"buffer",
"=",
"_erb_buffer",
"(",
"block",
".",
"binding",
")",
"rescue",
"nil",
"# If there is no buffer, just call the block and get the contents\r",
"if",
"buffer",
".",
"nil?",
"block",
".",
"call",
"(",
"args",
")",
"# If there is a buffer, execute the block, then extract its contents\r",
"else",
"pos",
"=",
"buffer",
".",
"length",
"block",
".",
"call",
"(",
"args",
")",
"# extract the block\r",
"data",
"=",
"buffer",
"[",
"pos",
"..",
"-",
"1",
"]",
"# replace it in the original with empty string\r",
"buffer",
"[",
"pos",
"..",
"-",
"1",
"]",
"=",
"\"\"",
"data",
"end",
"end"
] | This method is used to capture content from an ERB filter evaluation. It
is useful to helpers that need to process chunks of data during ERB filter
processing.
==== Parameters
*args:: Arguments to pass to the block.
&block:: The ERB block to call.
==== Returns
String:: The output of the block.
==== Examples
Capture being used in an ERB page:
<% @foo = capture_erb do %>
<p>Some Foo content!</p>
<% end %> | [
"This",
"method",
"is",
"used",
"to",
"capture",
"content",
"from",
"an",
"ERB",
"filter",
"evaluation",
".",
"It",
"is",
"useful",
"to",
"helpers",
"that",
"need",
"to",
"process",
"chunks",
"of",
"data",
"during",
"ERB",
"filter",
"processing",
"."
] | b7a397f9136f623589816bef498914943980a313 | https://github.com/slideshow-s9/slideshow/blob/b7a397f9136f623589816bef498914943980a313/slideshow-models/lib/slideshow/helpers/capture_helper.rb#L89-L109 | train |
slideshow-s9/slideshow | slideshow-models/lib/slideshow/filters/debug_filter.rb | Slideshow.DebugFilter.dump_content_to_file_debug_text_erb | def dump_content_to_file_debug_text_erb( content )
# NB: using attribs from mixed in class
# - opts
# - outdir
return content unless config.verbose?
outname = "#{outdir}/#{@name}.debug.text.erb"
puts " Dumping content before erb merge to #{outname}..."
File.open( outname, 'w' ) do |f|
f.write( content )
end
content
end | ruby | def dump_content_to_file_debug_text_erb( content )
# NB: using attribs from mixed in class
# - opts
# - outdir
return content unless config.verbose?
outname = "#{outdir}/#{@name}.debug.text.erb"
puts " Dumping content before erb merge to #{outname}..."
File.open( outname, 'w' ) do |f|
f.write( content )
end
content
end | [
"def",
"dump_content_to_file_debug_text_erb",
"(",
"content",
")",
"# NB: using attribs from mixed in class",
"# - opts",
"# - outdir",
"return",
"content",
"unless",
"config",
".",
"verbose?",
"outname",
"=",
"\"#{outdir}/#{@name}.debug.text.erb\"",
"puts",
"\" Dumping content before erb merge to #{outname}...\"",
"File",
".",
"open",
"(",
"outname",
",",
"'w'",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"content",
")",
"end",
"content",
"end"
] | use it to dump content before erb merge | [
"use",
"it",
"to",
"dump",
"content",
"before",
"erb",
"merge"
] | b7a397f9136f623589816bef498914943980a313 | https://github.com/slideshow-s9/slideshow/blob/b7a397f9136f623589816bef498914943980a313/slideshow-models/lib/slideshow/filters/debug_filter.rb#L8-L25 | train |
sjke/pg_ltree | lib/pg_ltree/ltree.rb | PgLtree.Ltree.ltree | def ltree(column = :path, options: { cascade: true })
cattr_accessor :ltree_path_column
self.ltree_path_column = column
if options[:cascade]
after_update :cascade_update
after_destroy :cascade_destroy
end
extend ClassMethods
include InstanceMethods
end | ruby | def ltree(column = :path, options: { cascade: true })
cattr_accessor :ltree_path_column
self.ltree_path_column = column
if options[:cascade]
after_update :cascade_update
after_destroy :cascade_destroy
end
extend ClassMethods
include InstanceMethods
end | [
"def",
"ltree",
"(",
"column",
"=",
":path",
",",
"options",
":",
"{",
"cascade",
":",
"true",
"}",
")",
"cattr_accessor",
":ltree_path_column",
"self",
".",
"ltree_path_column",
"=",
"column",
"if",
"options",
"[",
":cascade",
"]",
"after_update",
":cascade_update",
"after_destroy",
":cascade_destroy",
"end",
"extend",
"ClassMethods",
"include",
"InstanceMethods",
"end"
] | Initialzie ltree for active model
@param column [String] ltree column name | [
"Initialzie",
"ltree",
"for",
"active",
"model"
] | cbd7d4fd7d5d4a04004ee2dd5b185958d7280e2f | https://github.com/sjke/pg_ltree/blob/cbd7d4fd7d5d4a04004ee2dd5b185958d7280e2f/lib/pg_ltree/ltree.rb#L12-L24 | train |
ryz310/rubocop_challenger | lib/rubocop_challenger/go.rb | RubocopChallenger.Go.regenerate_rubocop_todo! | def regenerate_rubocop_todo!
before_version = scan_rubocop_version_in_rubocop_todo_file
pull_request.commit! ':police_car: regenerate rubocop todo' do
Rubocop::Command.new.auto_gen_config
end
after_version = scan_rubocop_version_in_rubocop_todo_file
[before_version, after_version]
end | ruby | def regenerate_rubocop_todo!
before_version = scan_rubocop_version_in_rubocop_todo_file
pull_request.commit! ':police_car: regenerate rubocop todo' do
Rubocop::Command.new.auto_gen_config
end
after_version = scan_rubocop_version_in_rubocop_todo_file
[before_version, after_version]
end | [
"def",
"regenerate_rubocop_todo!",
"before_version",
"=",
"scan_rubocop_version_in_rubocop_todo_file",
"pull_request",
".",
"commit!",
"':police_car: regenerate rubocop todo'",
"do",
"Rubocop",
"::",
"Command",
".",
"new",
".",
"auto_gen_config",
"end",
"after_version",
"=",
"scan_rubocop_version_in_rubocop_todo_file",
"[",
"before_version",
",",
"after_version",
"]",
"end"
] | Re-generate .rubocop_todo.yml and run git commit.
@return [Array<String>]
Returns the versions of RuboCop which created ".rubocop_todo.yml" before
and after re-generate. | [
"Re",
"-",
"generate",
".",
"rubocop_todo",
".",
"yml",
"and",
"run",
"git",
"commit",
"."
] | 267f3b48d1a32f1ef32ab8816cefafa9ee96ea50 | https://github.com/ryz310/rubocop_challenger/blob/267f3b48d1a32f1ef32ab8816cefafa9ee96ea50/lib/rubocop_challenger/go.rb#L49-L57 | train |
ryz310/rubocop_challenger | lib/rubocop_challenger/go.rb | RubocopChallenger.Go.rubocop_challenge! | def rubocop_challenge!(before_version, after_version)
Rubocop::Challenge.exec(options[:file_path], options[:mode]).tap do |rule|
pull_request.commit! ":police_car: #{rule.title}"
end
rescue Errors::NoAutoCorrectableRule => e
create_another_pull_request!(before_version, after_version)
raise e
end | ruby | def rubocop_challenge!(before_version, after_version)
Rubocop::Challenge.exec(options[:file_path], options[:mode]).tap do |rule|
pull_request.commit! ":police_car: #{rule.title}"
end
rescue Errors::NoAutoCorrectableRule => e
create_another_pull_request!(before_version, after_version)
raise e
end | [
"def",
"rubocop_challenge!",
"(",
"before_version",
",",
"after_version",
")",
"Rubocop",
"::",
"Challenge",
".",
"exec",
"(",
"options",
"[",
":file_path",
"]",
",",
"options",
"[",
":mode",
"]",
")",
".",
"tap",
"do",
"|",
"rule",
"|",
"pull_request",
".",
"commit!",
"\":police_car: #{rule.title}\"",
"end",
"rescue",
"Errors",
"::",
"NoAutoCorrectableRule",
"=>",
"e",
"create_another_pull_request!",
"(",
"before_version",
",",
"after_version",
")",
"raise",
"e",
"end"
] | Run rubocop challenge.
@param before_version [String]
The version of RuboCop which created ".rubocop_todo.yml" before
re-generate.
@param after_version [String]
The version of RuboCop which created ".rubocop_todo.yml" after
re-generate
@return [Rubocop::Rule]
The corrected rule
@raise [Errors::NoAutoCorrectableRule]
Raises if there is no auto correctable rule in ".rubocop_todo.yml" | [
"Run",
"rubocop",
"challenge",
"."
] | 267f3b48d1a32f1ef32ab8816cefafa9ee96ea50 | https://github.com/ryz310/rubocop_challenger/blob/267f3b48d1a32f1ef32ab8816cefafa9ee96ea50/lib/rubocop_challenger/go.rb#L76-L83 | train |
ryz310/rubocop_challenger | lib/rubocop_challenger/go.rb | RubocopChallenger.Go.add_to_ignore_list_if_challenge_is_incomplete | def add_to_ignore_list_if_challenge_is_incomplete(rule)
return unless auto_correct_incomplete?(rule)
pull_request.commit! ':police_car: add the rule to the ignore list' do
config_editor = Rubocop::ConfigEditor.new
config_editor.add_ignore(rule)
config_editor.save
end
color_puts DESCRIPTION_THAT_CHALLENGE_IS_INCOMPLETE,
PrComet::CommandLine::YELLOW
end | ruby | def add_to_ignore_list_if_challenge_is_incomplete(rule)
return unless auto_correct_incomplete?(rule)
pull_request.commit! ':police_car: add the rule to the ignore list' do
config_editor = Rubocop::ConfigEditor.new
config_editor.add_ignore(rule)
config_editor.save
end
color_puts DESCRIPTION_THAT_CHALLENGE_IS_INCOMPLETE,
PrComet::CommandLine::YELLOW
end | [
"def",
"add_to_ignore_list_if_challenge_is_incomplete",
"(",
"rule",
")",
"return",
"unless",
"auto_correct_incomplete?",
"(",
"rule",
")",
"pull_request",
".",
"commit!",
"':police_car: add the rule to the ignore list'",
"do",
"config_editor",
"=",
"Rubocop",
"::",
"ConfigEditor",
".",
"new",
"config_editor",
".",
"add_ignore",
"(",
"rule",
")",
"config_editor",
".",
"save",
"end",
"color_puts",
"DESCRIPTION_THAT_CHALLENGE_IS_INCOMPLETE",
",",
"PrComet",
"::",
"CommandLine",
"::",
"YELLOW",
"end"
] | If still exist the rule after a challenge, the rule regard as cannot
correct automatically then add to ignore list and it is not chosen as
target rule from next time.
@param rule [Rubocop::Rule] The corrected rule | [
"If",
"still",
"exist",
"the",
"rule",
"after",
"a",
"challenge",
"the",
"rule",
"regard",
"as",
"cannot",
"correct",
"automatically",
"then",
"add",
"to",
"ignore",
"list",
"and",
"it",
"is",
"not",
"chosen",
"as",
"target",
"rule",
"from",
"next",
"time",
"."
] | 267f3b48d1a32f1ef32ab8816cefafa9ee96ea50 | https://github.com/ryz310/rubocop_challenger/blob/267f3b48d1a32f1ef32ab8816cefafa9ee96ea50/lib/rubocop_challenger/go.rb#L121-L131 | train |
ryz310/rubocop_challenger | lib/rubocop_challenger/go.rb | RubocopChallenger.Go.auto_correct_incomplete? | def auto_correct_incomplete?(rule)
todo_reader = Rubocop::TodoReader.new(options[:file_path])
todo_reader.all_rules.include?(rule)
end | ruby | def auto_correct_incomplete?(rule)
todo_reader = Rubocop::TodoReader.new(options[:file_path])
todo_reader.all_rules.include?(rule)
end | [
"def",
"auto_correct_incomplete?",
"(",
"rule",
")",
"todo_reader",
"=",
"Rubocop",
"::",
"TodoReader",
".",
"new",
"(",
"options",
"[",
":file_path",
"]",
")",
"todo_reader",
".",
"all_rules",
".",
"include?",
"(",
"rule",
")",
"end"
] | Checks the challenge result. If the challenge is successed, the rule
should not exist in the ".rubocop_todo.yml" after regenerate.
@param rule [Rubocop::Rule] The corrected rule
@return [Boolean] Return true if the challenge successed | [
"Checks",
"the",
"challenge",
"result",
".",
"If",
"the",
"challenge",
"is",
"successed",
"the",
"rule",
"should",
"not",
"exist",
"in",
"the",
".",
"rubocop_todo",
".",
"yml",
"after",
"regenerate",
"."
] | 267f3b48d1a32f1ef32ab8816cefafa9ee96ea50 | https://github.com/ryz310/rubocop_challenger/blob/267f3b48d1a32f1ef32ab8816cefafa9ee96ea50/lib/rubocop_challenger/go.rb#L138-L141 | train |
ryz310/rubocop_challenger | lib/rubocop_challenger/pull_request.rb | RubocopChallenger.PullRequest.create_rubocop_challenge_pr! | def create_rubocop_challenge_pr!(rule, template_file_path = nil)
create_pull_request!(
title: "#{rule.title}-#{timestamp}",
body: Github::PrTemplate.new(rule, template_file_path).generate,
labels: labels
)
end | ruby | def create_rubocop_challenge_pr!(rule, template_file_path = nil)
create_pull_request!(
title: "#{rule.title}-#{timestamp}",
body: Github::PrTemplate.new(rule, template_file_path).generate,
labels: labels
)
end | [
"def",
"create_rubocop_challenge_pr!",
"(",
"rule",
",",
"template_file_path",
"=",
"nil",
")",
"create_pull_request!",
"(",
"title",
":",
"\"#{rule.title}-#{timestamp}\"",
",",
"body",
":",
"Github",
"::",
"PrTemplate",
".",
"new",
"(",
"rule",
",",
"template_file_path",
")",
".",
"generate",
",",
"labels",
":",
"labels",
")",
"end"
] | Creates a pull request for the Rubocop Challenge
@param rule [Rubocop::Rule]
The corrected rule
@param template_file_path [String, nil]
The template file name which use to generate the pull request body
@return [Boolean]
Return true if its successed | [
"Creates",
"a",
"pull",
"request",
"for",
"the",
"Rubocop",
"Challenge"
] | 267f3b48d1a32f1ef32ab8816cefafa9ee96ea50 | https://github.com/ryz310/rubocop_challenger/blob/267f3b48d1a32f1ef32ab8816cefafa9ee96ea50/lib/rubocop_challenger/pull_request.rb#L42-L48 | train |
ryz310/rubocop_challenger | lib/rubocop_challenger/pull_request.rb | RubocopChallenger.PullRequest.create_regenerate_todo_pr! | def create_regenerate_todo_pr!(before_version, after_version)
create_pull_request!(
title: "Re-generate .rubocop_todo.yml with RuboCop v#{after_version}",
body: generate_pull_request_body(before_version, after_version),
labels: labels
)
end | ruby | def create_regenerate_todo_pr!(before_version, after_version)
create_pull_request!(
title: "Re-generate .rubocop_todo.yml with RuboCop v#{after_version}",
body: generate_pull_request_body(before_version, after_version),
labels: labels
)
end | [
"def",
"create_regenerate_todo_pr!",
"(",
"before_version",
",",
"after_version",
")",
"create_pull_request!",
"(",
"title",
":",
"\"Re-generate .rubocop_todo.yml with RuboCop v#{after_version}\"",
",",
"body",
":",
"generate_pull_request_body",
"(",
"before_version",
",",
"after_version",
")",
",",
"labels",
":",
"labels",
")",
"end"
] | Creates a pull request which re-generate ".rubocop_todo.yml" with new
version RuboCop.
@param before_version [String]
The version of RuboCop which created ".rubocop_todo.yml" before
re-generate.
@param after_version [String]
The version of RuboCop which created ".rubocop_todo.yml" after
re-generate
@return [Boolean]
Return true if its successed | [
"Creates",
"a",
"pull",
"request",
"which",
"re",
"-",
"generate",
".",
"rubocop_todo",
".",
"yml",
"with",
"new",
"version",
"RuboCop",
"."
] | 267f3b48d1a32f1ef32ab8816cefafa9ee96ea50 | https://github.com/ryz310/rubocop_challenger/blob/267f3b48d1a32f1ef32ab8816cefafa9ee96ea50/lib/rubocop_challenger/pull_request.rb#L61-L67 | train |
ealdent/lda-ruby | lib/lda-ruby.rb | Lda.Lda.print_topics | def print_topics(words_per_topic = 10)
raise 'No vocabulary loaded.' unless @vocab
beta.each_with_index do |topic, topic_num|
# Sort the topic array and return the sorted indices of the best scores
indices = topic.zip(([email protected]).to_a).sort { |x| x[0] }.map { |_i, j| j }.reverse[0...words_per_topic]
puts "Topic #{topic_num}"
puts "\t#{indices.map { |i| @vocab[i] }.join("\n\t")}"
puts ''
end
nil
end | ruby | def print_topics(words_per_topic = 10)
raise 'No vocabulary loaded.' unless @vocab
beta.each_with_index do |topic, topic_num|
# Sort the topic array and return the sorted indices of the best scores
indices = topic.zip(([email protected]).to_a).sort { |x| x[0] }.map { |_i, j| j }.reverse[0...words_per_topic]
puts "Topic #{topic_num}"
puts "\t#{indices.map { |i| @vocab[i] }.join("\n\t")}"
puts ''
end
nil
end | [
"def",
"print_topics",
"(",
"words_per_topic",
"=",
"10",
")",
"raise",
"'No vocabulary loaded.'",
"unless",
"@vocab",
"beta",
".",
"each_with_index",
"do",
"|",
"topic",
",",
"topic_num",
"|",
"# Sort the topic array and return the sorted indices of the best scores",
"indices",
"=",
"topic",
".",
"zip",
"(",
"(",
"0",
"...",
"@vocab",
".",
"size",
")",
".",
"to_a",
")",
".",
"sort",
"{",
"|",
"x",
"|",
"x",
"[",
"0",
"]",
"}",
".",
"map",
"{",
"|",
"_i",
",",
"j",
"|",
"j",
"}",
".",
"reverse",
"[",
"0",
"...",
"words_per_topic",
"]",
"puts",
"\"Topic #{topic_num}\"",
"puts",
"\"\\t#{indices.map { |i| @vocab[i] }.join(\"\\n\\t\")}\"",
"puts",
"''",
"end",
"nil",
"end"
] | Visualization method for printing out the top +words_per_topic+ words
for each topic.
See also +top_words+. | [
"Visualization",
"method",
"for",
"printing",
"out",
"the",
"top",
"+",
"words_per_topic",
"+",
"words",
"for",
"each",
"topic",
"."
] | c8f5f52074cb1518822892b17c769541e1e8f7fc | https://github.com/ealdent/lda-ruby/blob/c8f5f52074cb1518822892b17c769541e1e8f7fc/lib/lda-ruby.rb#L64-L77 | train |
ealdent/lda-ruby | lib/lda-ruby.rb | Lda.Lda.to_s | def to_s
outp = ['LDA Settings:']
outp << ' Initial alpha: %0.6f'.format(init_alpha)
outp << ' # of topics: %d'.format(num_topics)
outp << ' Max iterations: %d'.format(max_iter)
outp << ' Convergence: %0.6f'.format(convergence)
outp << 'EM max iterations: %d'.format(em_max_iter)
outp << ' EM convergence: %0.6f'.format(em_convergence)
outp << ' Estimate alpha: %d'.format(est_alpha)
outp.join("\n")
end | ruby | def to_s
outp = ['LDA Settings:']
outp << ' Initial alpha: %0.6f'.format(init_alpha)
outp << ' # of topics: %d'.format(num_topics)
outp << ' Max iterations: %d'.format(max_iter)
outp << ' Convergence: %0.6f'.format(convergence)
outp << 'EM max iterations: %d'.format(em_max_iter)
outp << ' EM convergence: %0.6f'.format(em_convergence)
outp << ' Estimate alpha: %d'.format(est_alpha)
outp.join("\n")
end | [
"def",
"to_s",
"outp",
"=",
"[",
"'LDA Settings:'",
"]",
"outp",
"<<",
"' Initial alpha: %0.6f'",
".",
"format",
"(",
"init_alpha",
")",
"outp",
"<<",
"' # of topics: %d'",
".",
"format",
"(",
"num_topics",
")",
"outp",
"<<",
"' Max iterations: %d'",
".",
"format",
"(",
"max_iter",
")",
"outp",
"<<",
"' Convergence: %0.6f'",
".",
"format",
"(",
"convergence",
")",
"outp",
"<<",
"'EM max iterations: %d'",
".",
"format",
"(",
"em_max_iter",
")",
"outp",
"<<",
"' EM convergence: %0.6f'",
".",
"format",
"(",
"em_convergence",
")",
"outp",
"<<",
"' Estimate alpha: %d'",
".",
"format",
"(",
"est_alpha",
")",
"outp",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] | String representation displaying current settings. | [
"String",
"representation",
"displaying",
"current",
"settings",
"."
] | c8f5f52074cb1518822892b17c769541e1e8f7fc | https://github.com/ealdent/lda-ruby/blob/c8f5f52074cb1518822892b17c769541e1e8f7fc/lib/lda-ruby.rb#L154-L165 | train |
saturnflyer/casting | lib/casting/super_delegate.rb | Casting.SuperDelegate.super_delegate | def super_delegate(*args, &block)
method_name = name_of_calling_method(caller)
owner = args.first || method_delegate(method_name)
super_delegate_method = unbound_method_from_next_delegate(method_name, owner)
if super_delegate_method.arity == 0
super_delegate_method.bind(self).call
else
super_delegate_method.bind(self).call(*args, &block)
end
rescue NameError
raise NoMethodError.new("super_delegate: no delegate method `#{method_name}' for #{self.inspect} from #{owner}")
end | ruby | def super_delegate(*args, &block)
method_name = name_of_calling_method(caller)
owner = args.first || method_delegate(method_name)
super_delegate_method = unbound_method_from_next_delegate(method_name, owner)
if super_delegate_method.arity == 0
super_delegate_method.bind(self).call
else
super_delegate_method.bind(self).call(*args, &block)
end
rescue NameError
raise NoMethodError.new("super_delegate: no delegate method `#{method_name}' for #{self.inspect} from #{owner}")
end | [
"def",
"super_delegate",
"(",
"*",
"args",
",",
"&",
"block",
")",
"method_name",
"=",
"name_of_calling_method",
"(",
"caller",
")",
"owner",
"=",
"args",
".",
"first",
"||",
"method_delegate",
"(",
"method_name",
")",
"super_delegate_method",
"=",
"unbound_method_from_next_delegate",
"(",
"method_name",
",",
"owner",
")",
"if",
"super_delegate_method",
".",
"arity",
"==",
"0",
"super_delegate_method",
".",
"bind",
"(",
"self",
")",
".",
"call",
"else",
"super_delegate_method",
".",
"bind",
"(",
"self",
")",
".",
"call",
"(",
"args",
",",
"block",
")",
"end",
"rescue",
"NameError",
"raise",
"NoMethodError",
".",
"new",
"(",
"\"super_delegate: no delegate method `#{method_name}' for #{self.inspect} from #{owner}\"",
")",
"end"
] | Call the method of the same name defined in the next delegate stored in your object
Because Casting creates an alternative method lookup path using a collection of delegates,
you may use `super_delegate` to work like `super`.
If you use this feature, be sure that you have created a delegate collection which does
have the method you need or you'll see a NoMethodError.
Example:
module Greeter
def greet
"Hello"
end
end
module FormalGreeter
include Casting::Super
def greet
"#{super_delegate}, how do you do?"
end
end
some_object.cast_as(Greeter, FormalGreeter)
some_object.greet #=> 'Hello, how do you do?' | [
"Call",
"the",
"method",
"of",
"the",
"same",
"name",
"defined",
"in",
"the",
"next",
"delegate",
"stored",
"in",
"your",
"object"
] | 1609cfd2979fab9fc50304275f3524257eb1a45c | https://github.com/saturnflyer/casting/blob/1609cfd2979fab9fc50304275f3524257eb1a45c/lib/casting/super_delegate.rb#L31-L44 | train |
stitchfix/merch_calendar | lib/merch_calendar/merch_week.rb | MerchCalendar.MerchWeek.merch_month | def merch_month
# TODO: This is very inefficient, but less complex than strategic guessing
# maybe switch to a binary search or something
merch_year = calendar.merch_year_from_date(date)
@merch_month ||= (1..12).detect do |num|
calendar.end_of_month(merch_year, num) >= date && date >= calendar.start_of_month(merch_year, num)
end
end | ruby | def merch_month
# TODO: This is very inefficient, but less complex than strategic guessing
# maybe switch to a binary search or something
merch_year = calendar.merch_year_from_date(date)
@merch_month ||= (1..12).detect do |num|
calendar.end_of_month(merch_year, num) >= date && date >= calendar.start_of_month(merch_year, num)
end
end | [
"def",
"merch_month",
"# TODO: This is very inefficient, but less complex than strategic guessing",
"# maybe switch to a binary search or something",
"merch_year",
"=",
"calendar",
".",
"merch_year_from_date",
"(",
"date",
")",
"@merch_month",
"||=",
"(",
"1",
"..",
"12",
")",
".",
"detect",
"do",
"|",
"num",
"|",
"calendar",
".",
"end_of_month",
"(",
"merch_year",
",",
"num",
")",
">=",
"date",
"&&",
"date",
">=",
"calendar",
".",
"start_of_month",
"(",
"merch_year",
",",
"num",
")",
"end",
"end"
] | This returns the "merch month" number for a date
Month 1 is Feb for the retail calendar
Month 1 is August for the fiscal calendar
@return [Integer] | [
"This",
"returns",
"the",
"merch",
"month",
"number",
"for",
"a",
"date",
"Month",
"1",
"is",
"Feb",
"for",
"the",
"retail",
"calendar",
"Month",
"1",
"is",
"August",
"for",
"the",
"fiscal",
"calendar"
] | b24f1f47685928eeec8e808838e2474ddf473afd | https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/merch_week.rb#L100-L107 | train |
stitchfix/merch_calendar | lib/merch_calendar/retail_calendar.rb | MerchCalendar.RetailCalendar.end_of_year | def end_of_year(year)
year_end = Date.new((year + 1), Date::MONTHNAMES.index(LAST_MONTH_OF_THE_YEAR), LAST_DAY_OF_THE_YEAR) # Jan 31st
wday = (year_end.wday + 1) % 7
if wday > 3
year_end += 7 - wday
else
year_end -= wday
end
year_end
end | ruby | def end_of_year(year)
year_end = Date.new((year + 1), Date::MONTHNAMES.index(LAST_MONTH_OF_THE_YEAR), LAST_DAY_OF_THE_YEAR) # Jan 31st
wday = (year_end.wday + 1) % 7
if wday > 3
year_end += 7 - wday
else
year_end -= wday
end
year_end
end | [
"def",
"end_of_year",
"(",
"year",
")",
"year_end",
"=",
"Date",
".",
"new",
"(",
"(",
"year",
"+",
"1",
")",
",",
"Date",
"::",
"MONTHNAMES",
".",
"index",
"(",
"LAST_MONTH_OF_THE_YEAR",
")",
",",
"LAST_DAY_OF_THE_YEAR",
")",
"# Jan 31st",
"wday",
"=",
"(",
"year_end",
".",
"wday",
"+",
"1",
")",
"%",
"7",
"if",
"wday",
">",
"3",
"year_end",
"+=",
"7",
"-",
"wday",
"else",
"year_end",
"-=",
"wday",
"end",
"year_end",
"end"
] | The the first date of the retail year
@param year [Integer] the retail year
@return [Date] the first date of the retail year | [
"The",
"the",
"first",
"date",
"of",
"the",
"retail",
"year"
] | b24f1f47685928eeec8e808838e2474ddf473afd | https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/retail_calendar.rb#L20-L30 | train |
stitchfix/merch_calendar | lib/merch_calendar/retail_calendar.rb | MerchCalendar.RetailCalendar.start_of_month | def start_of_month(year, merch_month)
# 91 = number of days in a single 4-5-4 set
start = start_of_year(year) + ((merch_month - 1) / 3).to_i * 91
case merch_month
when *FOUR_WEEK_MONTHS
# 28 = 4 weeks
start = start + 28
when *FIVE_WEEK_MONTHS
# The 5 week months
# 63 = 4 weeks + 5 weeks
start = start + 63
end
start
end | ruby | def start_of_month(year, merch_month)
# 91 = number of days in a single 4-5-4 set
start = start_of_year(year) + ((merch_month - 1) / 3).to_i * 91
case merch_month
when *FOUR_WEEK_MONTHS
# 28 = 4 weeks
start = start + 28
when *FIVE_WEEK_MONTHS
# The 5 week months
# 63 = 4 weeks + 5 weeks
start = start + 63
end
start
end | [
"def",
"start_of_month",
"(",
"year",
",",
"merch_month",
")",
"# 91 = number of days in a single 4-5-4 set ",
"start",
"=",
"start_of_year",
"(",
"year",
")",
"+",
"(",
"(",
"merch_month",
"-",
"1",
")",
"/",
"3",
")",
".",
"to_i",
"*",
"91",
"case",
"merch_month",
"when",
"FOUR_WEEK_MONTHS",
"# 28 = 4 weeks",
"start",
"=",
"start",
"+",
"28",
"when",
"FIVE_WEEK_MONTHS",
"# The 5 week months",
"# 63 = 4 weeks + 5 weeks",
"start",
"=",
"start",
"+",
"63",
"end",
"start",
"end"
] | The starting date of the given merch month
@param year [Integer] the retail year
@param merch_month [Integer] the nth merch month of the retail calendar
@return [Date] the start date of the merch month | [
"The",
"starting",
"date",
"of",
"the",
"given",
"merch",
"month"
] | b24f1f47685928eeec8e808838e2474ddf473afd | https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/retail_calendar.rb#L45-L60 | train |
stitchfix/merch_calendar | lib/merch_calendar/retail_calendar.rb | MerchCalendar.RetailCalendar.start_of_quarter | def start_of_quarter(year, quarter)
case quarter
when QUARTER_1
start_of_month(year, 1)
when QUARTER_2
start_of_month(year, 4)
when QUARTER_3
start_of_month(year, 7)
when QUARTER_4
start_of_month(year, 10)
else
raise "invalid quarter"
end
end | ruby | def start_of_quarter(year, quarter)
case quarter
when QUARTER_1
start_of_month(year, 1)
when QUARTER_2
start_of_month(year, 4)
when QUARTER_3
start_of_month(year, 7)
when QUARTER_4
start_of_month(year, 10)
else
raise "invalid quarter"
end
end | [
"def",
"start_of_quarter",
"(",
"year",
",",
"quarter",
")",
"case",
"quarter",
"when",
"QUARTER_1",
"start_of_month",
"(",
"year",
",",
"1",
")",
"when",
"QUARTER_2",
"start_of_month",
"(",
"year",
",",
"4",
")",
"when",
"QUARTER_3",
"start_of_month",
"(",
"year",
",",
"7",
")",
"when",
"QUARTER_4",
"start_of_month",
"(",
"year",
",",
"10",
")",
"else",
"raise",
"\"invalid quarter\"",
"end",
"end"
] | Return the starting date for a particular quarter
@param year [Integer] the retail year
@param quarter [Integer] the quarter of the year, a number from 1 - 4
@return [Date] the start date of the quarter | [
"Return",
"the",
"starting",
"date",
"for",
"a",
"particular",
"quarter"
] | b24f1f47685928eeec8e808838e2474ddf473afd | https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/retail_calendar.rb#L100-L113 | train |
stitchfix/merch_calendar | lib/merch_calendar/retail_calendar.rb | MerchCalendar.RetailCalendar.end_of_quarter | def end_of_quarter(year, quarter)
case quarter
when QUARTER_1
end_of_month(year, 3)
when QUARTER_2
end_of_month(year, 6)
when QUARTER_3
end_of_month(year, 9)
when QUARTER_4
end_of_month(year, 12)
else
raise "invalid quarter"
end
end | ruby | def end_of_quarter(year, quarter)
case quarter
when QUARTER_1
end_of_month(year, 3)
when QUARTER_2
end_of_month(year, 6)
when QUARTER_3
end_of_month(year, 9)
when QUARTER_4
end_of_month(year, 12)
else
raise "invalid quarter"
end
end | [
"def",
"end_of_quarter",
"(",
"year",
",",
"quarter",
")",
"case",
"quarter",
"when",
"QUARTER_1",
"end_of_month",
"(",
"year",
",",
"3",
")",
"when",
"QUARTER_2",
"end_of_month",
"(",
"year",
",",
"6",
")",
"when",
"QUARTER_3",
"end_of_month",
"(",
"year",
",",
"9",
")",
"when",
"QUARTER_4",
"end_of_month",
"(",
"year",
",",
"12",
")",
"else",
"raise",
"\"invalid quarter\"",
"end",
"end"
] | Return the ending date for a particular quarter
@param year [Integer] the retail year
@param quarter [Integer] the quarter of the year, a number from 1 - 4
@return [Date] the end date of the quarter | [
"Return",
"the",
"ending",
"date",
"for",
"a",
"particular",
"quarter"
] | b24f1f47685928eeec8e808838e2474ddf473afd | https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/retail_calendar.rb#L120-L133 | train |
stitchfix/merch_calendar | lib/merch_calendar/retail_calendar.rb | MerchCalendar.RetailCalendar.merch_year_from_date | def merch_year_from_date(date)
date_end_of_year = end_of_year(date.year)
date_start_of_year = start_of_year(date.year)
if date < date_start_of_year
date.year - 1
else
date.year
end
end | ruby | def merch_year_from_date(date)
date_end_of_year = end_of_year(date.year)
date_start_of_year = start_of_year(date.year)
if date < date_start_of_year
date.year - 1
else
date.year
end
end | [
"def",
"merch_year_from_date",
"(",
"date",
")",
"date_end_of_year",
"=",
"end_of_year",
"(",
"date",
".",
"year",
")",
"date_start_of_year",
"=",
"start_of_year",
"(",
"date",
".",
"year",
")",
"if",
"date",
"<",
"date_start_of_year",
"date",
".",
"year",
"-",
"1",
"else",
"date",
".",
"year",
"end",
"end"
] | Given any julian date it will return what retail year it belongs to
@param date [Date] the julian date to convert to its Retail Year
@return [Integer] the retail year that the julian date falls into | [
"Given",
"any",
"julian",
"date",
"it",
"will",
"return",
"what",
"retail",
"year",
"it",
"belongs",
"to"
] | b24f1f47685928eeec8e808838e2474ddf473afd | https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/retail_calendar.rb#L181-L189 | train |
stitchfix/merch_calendar | lib/merch_calendar/retail_calendar.rb | MerchCalendar.RetailCalendar.merch_months_in | def merch_months_in(start_date, end_date)
merch_months = []
prev_date = start_date - 2
date = start_date
while date <= end_date do
date = MerchCalendar.start_of_month(date.year, merch_month: date.month)
next if prev_date == date
merch_months.push(date)
prev_date = date
date += 14
end
merch_months
end | ruby | def merch_months_in(start_date, end_date)
merch_months = []
prev_date = start_date - 2
date = start_date
while date <= end_date do
date = MerchCalendar.start_of_month(date.year, merch_month: date.month)
next if prev_date == date
merch_months.push(date)
prev_date = date
date += 14
end
merch_months
end | [
"def",
"merch_months_in",
"(",
"start_date",
",",
"end_date",
")",
"merch_months",
"=",
"[",
"]",
"prev_date",
"=",
"start_date",
"-",
"2",
"date",
"=",
"start_date",
"while",
"date",
"<=",
"end_date",
"do",
"date",
"=",
"MerchCalendar",
".",
"start_of_month",
"(",
"date",
".",
"year",
",",
"merch_month",
":",
"date",
".",
"month",
")",
"next",
"if",
"prev_date",
"==",
"date",
"merch_months",
".",
"push",
"(",
"date",
")",
"prev_date",
"=",
"date",
"date",
"+=",
"14",
"end",
"merch_months",
"end"
] | Given beginning and end dates it will return an array of Retail Month's Start date
@param start_date [Date] the starting date
@param end_date [Date] the ending date
@return [Array] Array of start dates of each Retail Month from given dates | [
"Given",
"beginning",
"and",
"end",
"dates",
"it",
"will",
"return",
"an",
"array",
"of",
"Retail",
"Month",
"s",
"Start",
"date"
] | b24f1f47685928eeec8e808838e2474ddf473afd | https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/retail_calendar.rb#L229-L241 | train |
stitchfix/merch_calendar | lib/merch_calendar/retail_calendar.rb | MerchCalendar.RetailCalendar.weeks_for_month | def weeks_for_month(year, month_param)
merch_month = get_merch_month_param(month_param)
start_date = start_of_month(year, merch_month)
weeks = (end_of_month(year, merch_month) - start_date + 1) / 7
(1..weeks).map do |week_num|
week_start = start_date + ((week_num - 1) * 7)
week_end = week_start + 6
MerchWeek.new(week_start, {
start_of_week: week_start,
end_of_week: week_end,
week: week_num,
calendar: RetailCalendar.new
})
end
end | ruby | def weeks_for_month(year, month_param)
merch_month = get_merch_month_param(month_param)
start_date = start_of_month(year, merch_month)
weeks = (end_of_month(year, merch_month) - start_date + 1) / 7
(1..weeks).map do |week_num|
week_start = start_date + ((week_num - 1) * 7)
week_end = week_start + 6
MerchWeek.new(week_start, {
start_of_week: week_start,
end_of_week: week_end,
week: week_num,
calendar: RetailCalendar.new
})
end
end | [
"def",
"weeks_for_month",
"(",
"year",
",",
"month_param",
")",
"merch_month",
"=",
"get_merch_month_param",
"(",
"month_param",
")",
"start_date",
"=",
"start_of_month",
"(",
"year",
",",
"merch_month",
")",
"weeks",
"=",
"(",
"end_of_month",
"(",
"year",
",",
"merch_month",
")",
"-",
"start_date",
"+",
"1",
")",
"/",
"7",
"(",
"1",
"..",
"weeks",
")",
".",
"map",
"do",
"|",
"week_num",
"|",
"week_start",
"=",
"start_date",
"+",
"(",
"(",
"week_num",
"-",
"1",
")",
"*",
"7",
")",
"week_end",
"=",
"week_start",
"+",
"6",
"MerchWeek",
".",
"new",
"(",
"week_start",
",",
"{",
"start_of_week",
":",
"week_start",
",",
"end_of_week",
":",
"week_end",
",",
"week",
":",
"week_num",
",",
"calendar",
":",
"RetailCalendar",
".",
"new",
"}",
")",
"end",
"end"
] | Returns an array of Merch Weeks that pertains to the Julian Month of a Retail Year
@param year [Integer] the Retail year
@param month_param [Integer] the julian month
@return [Array] Array of MerchWeeks | [
"Returns",
"an",
"array",
"of",
"Merch",
"Weeks",
"that",
"pertains",
"to",
"the",
"Julian",
"Month",
"of",
"a",
"Retail",
"Year"
] | b24f1f47685928eeec8e808838e2474ddf473afd | https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/retail_calendar.rb#L248-L266 | train |
stitchfix/merch_calendar | lib/merch_calendar/stitch_fix_fiscal_year_calendar.rb | MerchCalendar.StitchFixFiscalYearCalendar.merch_year_from_date | def merch_year_from_date(date)
if end_of_year(date.year) >= date
return date.year
else
return date.year + 1
end
end | ruby | def merch_year_from_date(date)
if end_of_year(date.year) >= date
return date.year
else
return date.year + 1
end
end | [
"def",
"merch_year_from_date",
"(",
"date",
")",
"if",
"end_of_year",
"(",
"date",
".",
"year",
")",
">=",
"date",
"return",
"date",
".",
"year",
"else",
"return",
"date",
".",
"year",
"+",
"1",
"end",
"end"
] | Given any julian date it will return what Fiscal Year it belongs to
@param date [Date] the julian date to convert to its Fiscal Year
@return [Integer] the fiscal year that the julian date falls into | [
"Given",
"any",
"julian",
"date",
"it",
"will",
"return",
"what",
"Fiscal",
"Year",
"it",
"belongs",
"to"
] | b24f1f47685928eeec8e808838e2474ddf473afd | https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/stitch_fix_fiscal_year_calendar.rb#L179-L185 | train |
stitchfix/merch_calendar | lib/merch_calendar/stitch_fix_fiscal_year_calendar.rb | MerchCalendar.StitchFixFiscalYearCalendar.merch_months_in | def merch_months_in(start_date, end_date)
merch_months_combos = merch_year_and_month_from_dates(start_date, end_date)
merch_months_combos.map { | merch_month_combo | start_of_month(merch_month_combo[0], merch_month_combo[1]) }
end | ruby | def merch_months_in(start_date, end_date)
merch_months_combos = merch_year_and_month_from_dates(start_date, end_date)
merch_months_combos.map { | merch_month_combo | start_of_month(merch_month_combo[0], merch_month_combo[1]) }
end | [
"def",
"merch_months_in",
"(",
"start_date",
",",
"end_date",
")",
"merch_months_combos",
"=",
"merch_year_and_month_from_dates",
"(",
"start_date",
",",
"end_date",
")",
"merch_months_combos",
".",
"map",
"{",
"|",
"merch_month_combo",
"|",
"start_of_month",
"(",
"merch_month_combo",
"[",
"0",
"]",
",",
"merch_month_combo",
"[",
"1",
"]",
")",
"}",
"end"
] | Given beginning and end dates it will return an array of Fiscal Month's Start date
@param start_date [Date] the starting date
@param end_date [Date] the ending date
@return [Array] Array of start dates of each Fiscal Month from given dates | [
"Given",
"beginning",
"and",
"end",
"dates",
"it",
"will",
"return",
"an",
"array",
"of",
"Fiscal",
"Month",
"s",
"Start",
"date"
] | b24f1f47685928eeec8e808838e2474ddf473afd | https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/stitch_fix_fiscal_year_calendar.rb#L224-L227 | train |
stitchfix/merch_calendar | lib/merch_calendar/stitch_fix_fiscal_year_calendar.rb | MerchCalendar.StitchFixFiscalYearCalendar.merch_year_and_month_from_dates | def merch_year_and_month_from_dates(start_date, end_date)
merch_months = []
middle_of_start_month = Date.new(start_date.year, start_date.month, 14)
middle_of_end_month = Date.new(end_date.year, end_date.month, 14)
date = middle_of_start_month
while date <= middle_of_end_month do
merch_months.push(date_conversion(date))
date = date >> 1
end
merch_months
end | ruby | def merch_year_and_month_from_dates(start_date, end_date)
merch_months = []
middle_of_start_month = Date.new(start_date.year, start_date.month, 14)
middle_of_end_month = Date.new(end_date.year, end_date.month, 14)
date = middle_of_start_month
while date <= middle_of_end_month do
merch_months.push(date_conversion(date))
date = date >> 1
end
merch_months
end | [
"def",
"merch_year_and_month_from_dates",
"(",
"start_date",
",",
"end_date",
")",
"merch_months",
"=",
"[",
"]",
"middle_of_start_month",
"=",
"Date",
".",
"new",
"(",
"start_date",
".",
"year",
",",
"start_date",
".",
"month",
",",
"14",
")",
"middle_of_end_month",
"=",
"Date",
".",
"new",
"(",
"end_date",
".",
"year",
",",
"end_date",
".",
"month",
",",
"14",
")",
"date",
"=",
"middle_of_start_month",
"while",
"date",
"<=",
"middle_of_end_month",
"do",
"merch_months",
".",
"push",
"(",
"date_conversion",
"(",
"date",
")",
")",
"date",
"=",
"date",
">>",
"1",
"end",
"merch_months",
"end"
] | Returns an array of merch_months and year combination that falls in and between the start and end date
Ex: if start_date = August 1, 2018 and end_date = October 1, 2018
it returns [[2019, 1], [ 2019, 2], [2019, 3]] | [
"Returns",
"an",
"array",
"of",
"merch_months",
"and",
"year",
"combination",
"that",
"falls",
"in",
"and",
"between",
"the",
"start",
"and",
"end",
"date"
] | b24f1f47685928eeec8e808838e2474ddf473afd | https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/stitch_fix_fiscal_year_calendar.rb#L260-L272 | train |
stitchfix/merch_calendar | lib/merch_calendar/util.rb | MerchCalendar.Util.start_of_week | def start_of_week(year, month, week)
retail_calendar.start_of_week(year, julian_to_merch(month), week)
end | ruby | def start_of_week(year, month, week)
retail_calendar.start_of_week(year, julian_to_merch(month), week)
end | [
"def",
"start_of_week",
"(",
"year",
",",
"month",
",",
"week",
")",
"retail_calendar",
".",
"start_of_week",
"(",
"year",
",",
"julian_to_merch",
"(",
"month",
")",
",",
"week",
")",
"end"
] | The start date of the week
@param year [Integer] the merch year
@param month [Integer] an integer specifying the julian month.
@param week [Integer] an integer specifying the merch week.
@return [Date] the starting date of the specified week | [
"The",
"start",
"date",
"of",
"the",
"week"
] | b24f1f47685928eeec8e808838e2474ddf473afd | https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/util.rb#L16-L18 | train |
stitchfix/merch_calendar | lib/merch_calendar/util.rb | MerchCalendar.Util.end_of_week | def end_of_week(year, month, week)
retail_calendar.end_of_week(year, julian_to_merch(month), week)
end | ruby | def end_of_week(year, month, week)
retail_calendar.end_of_week(year, julian_to_merch(month), week)
end | [
"def",
"end_of_week",
"(",
"year",
",",
"month",
",",
"week",
")",
"retail_calendar",
".",
"end_of_week",
"(",
"year",
",",
"julian_to_merch",
"(",
"month",
")",
",",
"week",
")",
"end"
] | The end date of the week
@param year [Integer] the merch year
@param month [Integer] an integer specifying the julian month.
@param week [Integer] an integer specifying the merch week.
@return [Date] the ending date of the specified week | [
"The",
"end",
"date",
"of",
"the",
"week"
] | b24f1f47685928eeec8e808838e2474ddf473afd | https://github.com/stitchfix/merch_calendar/blob/b24f1f47685928eeec8e808838e2474ddf473afd/lib/merch_calendar/util.rb#L27-L29 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.