repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
avinashbot/lazy_lazer | lib/lazy_lazer/internal_model.rb | LazyLazer.InternalModel.exists_locally? | def exists_locally?(key_name)
return true if @cache.key?(key_name) || @writethrough.key?(key_name)
meta = ensure_metadata_exists(key_name)
@source.key?(meta.source_key)
end | ruby | def exists_locally?(key_name)
return true if @cache.key?(key_name) || @writethrough.key?(key_name)
meta = ensure_metadata_exists(key_name)
@source.key?(meta.source_key)
end | [
"def",
"exists_locally?",
"(",
"key_name",
")",
"return",
"true",
"if",
"@cache",
".",
"key?",
"(",
"key_name",
")",
"||",
"@writethrough",
".",
"key?",
"(",
"key_name",
")",
"meta",
"=",
"ensure_metadata_exists",
"(",
"key_name",
")",
"@source",
".",
"key?"... | Whether the key doesn't need to be lazily loaded.
@param key_name [Symbol] the key to check
@return [Boolean] whether the key exists locally. | [
"Whether",
"the",
"key",
"doesn",
"t",
"need",
"to",
"be",
"lazily",
"loaded",
"."
] | ed23f152697e76816872301363ab1daff2d2cfc7 | https://github.com/avinashbot/lazy_lazer/blob/ed23f152697e76816872301363ab1daff2d2cfc7/lib/lazy_lazer/internal_model.rb#L39-L43 | valid |
avinashbot/lazy_lazer | lib/lazy_lazer/internal_model.rb | LazyLazer.InternalModel.write_attribute | def write_attribute(key_name, new_value)
meta = ensure_metadata_exists(key_name)
@source.delete(meta.source_key)
@writethrough[key_name] = @cache[key_name] = new_value
end | ruby | def write_attribute(key_name, new_value)
meta = ensure_metadata_exists(key_name)
@source.delete(meta.source_key)
@writethrough[key_name] = @cache[key_name] = new_value
end | [
"def",
"write_attribute",
"(",
"key_name",
",",
"new_value",
")",
"meta",
"=",
"ensure_metadata_exists",
"(",
"key_name",
")",
"@source",
".",
"delete",
"(",
"meta",
".",
"source_key",
")",
"@writethrough",
"[",
"key_name",
"]",
"=",
"@cache",
"[",
"key_name",... | Update an attribute.
@param key_name [Symbol] the attribute to update
@param new_value [Object] the new value
@return [Object] the written value | [
"Update",
"an",
"attribute",
"."
] | ed23f152697e76816872301363ab1daff2d2cfc7 | https://github.com/avinashbot/lazy_lazer/blob/ed23f152697e76816872301363ab1daff2d2cfc7/lib/lazy_lazer/internal_model.rb#L57-L61 | valid |
avinashbot/lazy_lazer | lib/lazy_lazer/internal_model.rb | LazyLazer.InternalModel.delete_attribute | def delete_attribute(key_name)
key_name_sym = key_name.to_sym
meta = ensure_metadata_exists(key_name_sym)
@cache.delete(key_name)
@writethrough.delete(key_name)
@source.delete(meta.source_key)
nil
end | ruby | def delete_attribute(key_name)
key_name_sym = key_name.to_sym
meta = ensure_metadata_exists(key_name_sym)
@cache.delete(key_name)
@writethrough.delete(key_name)
@source.delete(meta.source_key)
nil
end | [
"def",
"delete_attribute",
"(",
"key_name",
")",
"key_name_sym",
"=",
"key_name",
".",
"to_sym",
"meta",
"=",
"ensure_metadata_exists",
"(",
"key_name_sym",
")",
"@cache",
".",
"delete",
"(",
"key_name",
")",
"@writethrough",
".",
"delete",
"(",
"key_name",
")",... | Delete an attribute
@param key_name [Symbol] the name of the key
@return [void] | [
"Delete",
"an",
"attribute"
] | ed23f152697e76816872301363ab1daff2d2cfc7 | https://github.com/avinashbot/lazy_lazer/blob/ed23f152697e76816872301363ab1daff2d2cfc7/lib/lazy_lazer/internal_model.rb#L66-L73 | valid |
avinashbot/lazy_lazer | lib/lazy_lazer/internal_model.rb | LazyLazer.InternalModel.verify_required! | def verify_required!
@key_metadata.required_properties.each do |key_name|
next if @source.key?(@key_metadata.get(key_name).source_key)
raise RequiredAttribute, "#{@parent} requires `#{key_name}`"
end
end | ruby | def verify_required!
@key_metadata.required_properties.each do |key_name|
next if @source.key?(@key_metadata.get(key_name).source_key)
raise RequiredAttribute, "#{@parent} requires `#{key_name}`"
end
end | [
"def",
"verify_required!",
"@key_metadata",
".",
"required_properties",
".",
"each",
"do",
"|",
"key_name",
"|",
"next",
"if",
"@source",
".",
"key?",
"(",
"@key_metadata",
".",
"get",
"(",
"key_name",
")",
".",
"source_key",
")",
"raise",
"RequiredAttribute",
... | Verify that all the keys marked as required are present.
@api private
@raise RequiredAttribute if a required attribute is missing
@return [void] | [
"Verify",
"that",
"all",
"the",
"keys",
"marked",
"as",
"required",
"are",
"present",
"."
] | ed23f152697e76816872301363ab1daff2d2cfc7 | https://github.com/avinashbot/lazy_lazer/blob/ed23f152697e76816872301363ab1daff2d2cfc7/lib/lazy_lazer/internal_model.rb#L96-L101 | valid |
avinashbot/lazy_lazer | lib/lazy_lazer/internal_model.rb | LazyLazer.InternalModel.transform_value | def transform_value(value, transform)
case transform
when nil
value
when Proc
@parent.instance_exec(value, &transform)
when Symbol
value.public_send(transform)
end
end | ruby | def transform_value(value, transform)
case transform
when nil
value
when Proc
@parent.instance_exec(value, &transform)
when Symbol
value.public_send(transform)
end
end | [
"def",
"transform_value",
"(",
"value",
",",
"transform",
")",
"case",
"transform",
"when",
"nil",
"value",
"when",
"Proc",
"@parent",
".",
"instance_exec",
"(",
"value",
",",
"&",
"transform",
")",
"when",
"Symbol",
"value",
".",
"public_send",
"(",
"transf... | Apply a transformation to a value.
@param value [Object] a value
@param transform [nil, Proc, Symbol] a transform type
@return [Object] the transformed value | [
"Apply",
"a",
"transformation",
"to",
"a",
"value",
"."
] | ed23f152697e76816872301363ab1daff2d2cfc7 | https://github.com/avinashbot/lazy_lazer/blob/ed23f152697e76816872301363ab1daff2d2cfc7/lib/lazy_lazer/internal_model.rb#L168-L177 | valid |
a14m/EGP-Rates | lib/egp_rates/bank.rb | EGPRates.Bank.response | def response
response = Net::HTTP.get_response(@uri)
if response.is_a? Net::HTTPRedirection
response = Net::HTTP.get_response(URI.parse(response['location']))
end
fail ResponseError, response.code unless response.is_a? Net::HTTPSuccess
response
end | ruby | def response
response = Net::HTTP.get_response(@uri)
if response.is_a? Net::HTTPRedirection
response = Net::HTTP.get_response(URI.parse(response['location']))
end
fail ResponseError, response.code unless response.is_a? Net::HTTPSuccess
response
end | [
"def",
"response",
"response",
"=",
"Net",
"::",
"HTTP",
".",
"get_response",
"(",
"@uri",
")",
"if",
"response",
".",
"is_a?",
"Net",
"::",
"HTTPRedirection",
"response",
"=",
"Net",
"::",
"HTTP",
".",
"get_response",
"(",
"URI",
".",
"parse",
"(",
"res... | Make a call to the @uri to get the raw_response
@return [Net::HTTPSuccess] of the raw response
@raises [ResponseError] if response is not 200 OK | [
"Make",
"a",
"call",
"to",
"the"
] | ebb960c8cae62c5823aef50bb4121397276c7af6 | https://github.com/a14m/EGP-Rates/blob/ebb960c8cae62c5823aef50bb4121397276c7af6/lib/egp_rates/bank.rb#L20-L27 | valid |
a14m/EGP-Rates | lib/egp_rates/adib.rb | EGPRates.ADIB.currencies | def currencies(table_rows)
table_rows.lazy.map do |e|
e.css('img').map { |img| img.attribute('src').value }
end.force.flatten
end | ruby | def currencies(table_rows)
table_rows.lazy.map do |e|
e.css('img').map { |img| img.attribute('src').value }
end.force.flatten
end | [
"def",
"currencies",
"(",
"table_rows",
")",
"table_rows",
".",
"lazy",
".",
"map",
"do",
"|",
"e",
"|",
"e",
".",
"css",
"(",
"'img'",
")",
".",
"map",
"{",
"|",
"img",
"|",
"img",
".",
"attribute",
"(",
"'src'",
")",
".",
"value",
"}",
"end",
... | Extract the currencies from the image components src attribute
@return [Array<String>] containing the URL to image of the currency | [
"Extract",
"the",
"currencies",
"from",
"the",
"image",
"components",
"src",
"attribute"
] | ebb960c8cae62c5823aef50bb4121397276c7af6 | https://github.com/a14m/EGP-Rates/blob/ebb960c8cae62c5823aef50bb4121397276c7af6/lib/egp_rates/adib.rb#L38-L42 | valid |
avinashbot/lazy_lazer | lib/lazy_lazer/key_metadata_store.rb | LazyLazer.KeyMetadataStore.add | def add(key, meta)
@collection[key] = meta
if meta.required?
@required_properties << key
else
@required_properties.delete(key)
end
meta
end | ruby | def add(key, meta)
@collection[key] = meta
if meta.required?
@required_properties << key
else
@required_properties.delete(key)
end
meta
end | [
"def",
"add",
"(",
"key",
",",
"meta",
")",
"@collection",
"[",
"key",
"]",
"=",
"meta",
"if",
"meta",
".",
"required?",
"@required_properties",
"<<",
"key",
"else",
"@required_properties",
".",
"delete",
"(",
"key",
")",
"end",
"meta",
"end"
] | Add a KeyMetadata to the store.
@param key [Symbol] the key
@param meta [KeyMetadata] the key metadata
@return [KeyMetadata] the provided meta | [
"Add",
"a",
"KeyMetadata",
"to",
"the",
"store",
"."
] | ed23f152697e76816872301363ab1daff2d2cfc7 | https://github.com/avinashbot/lazy_lazer/blob/ed23f152697e76816872301363ab1daff2d2cfc7/lib/lazy_lazer/key_metadata_store.rb#L25-L33 | valid |
nicolasdespres/respect | lib/respect/has_constraints.rb | Respect.HasConstraints.validate_constraints | def validate_constraints(value)
options.each do |option, arg|
if validator_class = Respect.validator_for(option)
validator_class.new(arg).validate(value)
end
end
end | ruby | def validate_constraints(value)
options.each do |option, arg|
if validator_class = Respect.validator_for(option)
validator_class.new(arg).validate(value)
end
end
end | [
"def",
"validate_constraints",
"(",
"value",
")",
"options",
".",
"each",
"do",
"|",
"option",
",",
"arg",
"|",
"if",
"validator_class",
"=",
"Respect",
".",
"validator_for",
"(",
"option",
")",
"validator_class",
".",
"new",
"(",
"arg",
")",
".",
"validat... | Validate all the constraints listed in +options+ to the
given +value+. | [
"Validate",
"all",
"the",
"constraints",
"listed",
"in",
"+",
"options",
"+",
"to",
"the",
"given",
"+",
"value",
"+",
"."
] | 916bef1c3a84788507a45cfb75b8f7d0c56b685f | https://github.com/nicolasdespres/respect/blob/916bef1c3a84788507a45cfb75b8f7d0c56b685f/lib/respect/has_constraints.rb#L12-L18 | valid |
nicolasdespres/respect | lib/respect/has_constraints.rb | Respect.HasConstraints.validate | def validate(object)
sanitized_object = validate_type(object)
validate_constraints(sanitized_object) unless sanitized_object.nil? && allow_nil?
self.sanitized_object = sanitized_object
true
rescue ValidationError => e
# Reset sanitized object.
self.sanitized_object = nil
raise e
end | ruby | def validate(object)
sanitized_object = validate_type(object)
validate_constraints(sanitized_object) unless sanitized_object.nil? && allow_nil?
self.sanitized_object = sanitized_object
true
rescue ValidationError => e
# Reset sanitized object.
self.sanitized_object = nil
raise e
end | [
"def",
"validate",
"(",
"object",
")",
"sanitized_object",
"=",
"validate_type",
"(",
"object",
")",
"validate_constraints",
"(",
"sanitized_object",
")",
"unless",
"sanitized_object",
".",
"nil?",
"&&",
"allow_nil?",
"self",
".",
"sanitized_object",
"=",
"sanitized... | Call +validate_type+ with the given +object+, apply the constraints
and assign the sanitized object. | [
"Call",
"+",
"validate_type",
"+",
"with",
"the",
"given",
"+",
"object",
"+",
"apply",
"the",
"constraints",
"and",
"assign",
"the",
"sanitized",
"object",
"."
] | 916bef1c3a84788507a45cfb75b8f7d0c56b685f | https://github.com/nicolasdespres/respect/blob/916bef1c3a84788507a45cfb75b8f7d0c56b685f/lib/respect/has_constraints.rb#L22-L31 | valid |
nicolasdespres/respect | lib/respect/hash_schema.rb | Respect.HashSchema.[]= | def []=(name, schema)
case name
when Symbol, String, Regexp
if @properties.has_key?(name)
raise InvalidSchemaError, "property '#{name}' already defined"
end
@properties[name] = schema
else
raise InvalidSchemaError, "unsupported property name type #{name}:#{name.class}"
end
end | ruby | def []=(name, schema)
case name
when Symbol, String, Regexp
if @properties.has_key?(name)
raise InvalidSchemaError, "property '#{name}' already defined"
end
@properties[name] = schema
else
raise InvalidSchemaError, "unsupported property name type #{name}:#{name.class}"
end
end | [
"def",
"[]=",
"(",
"name",
",",
"schema",
")",
"case",
"name",
"when",
"Symbol",
",",
"String",
",",
"Regexp",
"if",
"@properties",
".",
"has_key?",
"(",
"name",
")",
"raise",
"InvalidSchemaError",
",",
"\"property '#{name}' already defined\"",
"end",
"@properti... | Set the given +schema+ for the given property +name+. A name can be
a Symbol, a String or a Regexp. | [
"Set",
"the",
"given",
"+",
"schema",
"+",
"for",
"the",
"given",
"property",
"+",
"name",
"+",
".",
"A",
"name",
"can",
"be",
"a",
"Symbol",
"a",
"String",
"or",
"a",
"Regexp",
"."
] | 916bef1c3a84788507a45cfb75b8f7d0c56b685f | https://github.com/nicolasdespres/respect/blob/916bef1c3a84788507a45cfb75b8f7d0c56b685f/lib/respect/hash_schema.rb#L61-L71 | valid |
nicolasdespres/respect | lib/respect/hash_def.rb | Respect.HashDef.[]= | def []=(key, value)
case value
when String
string(key, equal_to: value.to_s)
else
any(key, equal_to: value.to_s)
end
end | ruby | def []=(key, value)
case value
when String
string(key, equal_to: value.to_s)
else
any(key, equal_to: value.to_s)
end
end | [
"def",
"[]=",
"(",
"key",
",",
"value",
")",
"case",
"value",
"when",
"String",
"string",
"(",
"key",
",",
"equal_to",
":",
"value",
".",
"to_s",
")",
"else",
"any",
"(",
"key",
",",
"equal_to",
":",
"value",
".",
"to_s",
")",
"end",
"end"
] | Shortcut to say a schema +key+ must be equal to a given +value+. When it
does not recognize the value type it creates a "any" schema.
Example:
HashSchema.define do |s|
s["a_string"] = "value" # equivalent to: s.string("a_string", equal_to: "value")
s["a_key"] = 0..5 # equivalent to: s.any("a_key", equal_to: "0..5")
end | [
"Shortcut",
"to",
"say",
"a",
"schema",
"+",
"key",
"+",
"must",
"be",
"equal",
"to",
"a",
"given",
"+",
"value",
"+",
".",
"When",
"it",
"does",
"not",
"recognize",
"the",
"value",
"type",
"it",
"creates",
"a",
"any",
"schema",
"."
] | 916bef1c3a84788507a45cfb75b8f7d0c56b685f | https://github.com/nicolasdespres/respect/blob/916bef1c3a84788507a45cfb75b8f7d0c56b685f/lib/respect/hash_def.rb#L21-L28 | valid |
sue445/google_holiday_calendar | lib/google_holiday_calendar/calendar.rb | GoogleHolidayCalendar.Calendar.holiday? | def holiday?(arg)
date = to_date(arg)
holidays(start_date: date, end_date: date + 1.day, limit: 1).length > 0
end | ruby | def holiday?(arg)
date = to_date(arg)
holidays(start_date: date, end_date: date + 1.day, limit: 1).length > 0
end | [
"def",
"holiday?",
"(",
"arg",
")",
"date",
"=",
"to_date",
"(",
"arg",
")",
"holidays",
"(",
"start_date",
":",
"date",
",",
"end_date",
":",
"date",
"+",
"1",
".",
"day",
",",
"limit",
":",
"1",
")",
".",
"length",
">",
"0",
"end"
] | whether arg is holiday
@param arg [#to_date, String] {Date}, {Time}, or date like String (ex. "YYYY-MM-DD") | [
"whether",
"arg",
"is",
"holiday"
] | 167384881ec1c970322aa4d7e5dd0d5d736ba875 | https://github.com/sue445/google_holiday_calendar/blob/167384881ec1c970322aa4d7e5dd0d5d736ba875/lib/google_holiday_calendar/calendar.rb#L53-L56 | valid |
defunkt/choice | lib/choice/parser.rb | Choice.Parser.arrayize_arguments | def arrayize_arguments(args)
# Go through trailing arguments and suck them in if they don't seem
# to have an owner.
array = []
until args.empty? || args.first.match(/^-/)
array << args.shift
end
array
end | ruby | def arrayize_arguments(args)
# Go through trailing arguments and suck them in if they don't seem
# to have an owner.
array = []
until args.empty? || args.first.match(/^-/)
array << args.shift
end
array
end | [
"def",
"arrayize_arguments",
"(",
"args",
")",
"array",
"=",
"[",
"]",
"until",
"args",
".",
"empty?",
"||",
"args",
".",
"first",
".",
"match",
"(",
"/",
"/",
")",
"array",
"<<",
"args",
".",
"shift",
"end",
"array",
"end"
] | Turns trailing command line arguments into an array for an arrayed value | [
"Turns",
"trailing",
"command",
"line",
"arguments",
"into",
"an",
"array",
"for",
"an",
"arrayed",
"value"
] | 16e9431519463a9aa22138c0a3d07fda11486847 | https://github.com/defunkt/choice/blob/16e9431519463a9aa22138c0a3d07fda11486847/lib/choice/parser.rb#L206-L214 | valid |
defunkt/choice | lib/choice/option.rb | Choice.Option.to_a | def to_a
[
required,
short,
long,
desc,
default,
filter,
action,
cast,
valid,
validate
].compact
end | ruby | def to_a
[
required,
short,
long,
desc,
default,
filter,
action,
cast,
valid,
validate
].compact
end | [
"def",
"to_a",
"[",
"required",
",",
"short",
",",
"long",
",",
"desc",
",",
"default",
",",
"filter",
",",
"action",
",",
"cast",
",",
"valid",
",",
"validate",
"]",
".",
"compact",
"end"
] | Returns Option converted to an array. | [
"Returns",
"Option",
"converted",
"to",
"an",
"array",
"."
] | 16e9431519463a9aa22138c0a3d07fda11486847 | https://github.com/defunkt/choice/blob/16e9431519463a9aa22138c0a3d07fda11486847/lib/choice/option.rb#L110-L123 | valid |
defunkt/choice | lib/choice/option.rb | Choice.Option.to_h | def to_h
{
"required" => required,
"short" => short,
"long" => long,
"desc" => desc,
"default" => default,
"filter" => filter,
"action" => action,
"cast" => cast,
"valid" => valid,
"validate" => validate
}.reject {|k, v| v.nil? }
end | ruby | def to_h
{
"required" => required,
"short" => short,
"long" => long,
"desc" => desc,
"default" => default,
"filter" => filter,
"action" => action,
"cast" => cast,
"valid" => valid,
"validate" => validate
}.reject {|k, v| v.nil? }
end | [
"def",
"to_h",
"{",
"\"required\"",
"=>",
"required",
",",
"\"short\"",
"=>",
"short",
",",
"\"long\"",
"=>",
"long",
",",
"\"desc\"",
"=>",
"desc",
",",
"\"default\"",
"=>",
"default",
",",
"\"filter\"",
"=>",
"filter",
",",
"\"action\"",
"=>",
"action",
... | Returns Option converted to a hash. | [
"Returns",
"Option",
"converted",
"to",
"a",
"hash",
"."
] | 16e9431519463a9aa22138c0a3d07fda11486847 | https://github.com/defunkt/choice/blob/16e9431519463a9aa22138c0a3d07fda11486847/lib/choice/option.rb#L126-L139 | valid |
thomis/eventhub-processor2 | lib/eventhub/configuration.rb | EventHub.Configuration.parse_options | def parse_options(argv = ARGV)
@config_file = File.join(Dir.getwd, 'config', "#{@name}.json")
OptionParser.new do |opts|
note = 'Define environment'
opts.on('-e', '--environment ENVIRONMENT', note) do |environment|
@environment = environment
end
opts.on('-d', '--detached', 'Run processor detached as a daemon') do
@detached = true
end
note = 'Define configuration file'
opts.on('-c', '--config CONFIG', note) do |config|
@config_file = config
end
end.parse!(argv)
true
rescue OptionParser::InvalidOption => e
EventHub.logger.warn("Argument Parsing: #{e}")
false
rescue OptionParser::MissingArgument => e
EventHub.logger.warn("Argument Parsing: #{e}")
false
end | ruby | def parse_options(argv = ARGV)
@config_file = File.join(Dir.getwd, 'config', "#{@name}.json")
OptionParser.new do |opts|
note = 'Define environment'
opts.on('-e', '--environment ENVIRONMENT', note) do |environment|
@environment = environment
end
opts.on('-d', '--detached', 'Run processor detached as a daemon') do
@detached = true
end
note = 'Define configuration file'
opts.on('-c', '--config CONFIG', note) do |config|
@config_file = config
end
end.parse!(argv)
true
rescue OptionParser::InvalidOption => e
EventHub.logger.warn("Argument Parsing: #{e}")
false
rescue OptionParser::MissingArgument => e
EventHub.logger.warn("Argument Parsing: #{e}")
false
end | [
"def",
"parse_options",
"(",
"argv",
"=",
"ARGV",
")",
"@config_file",
"=",
"File",
".",
"join",
"(",
"Dir",
".",
"getwd",
",",
"'config'",
",",
"\"#{@name}.json\"",
")",
"OptionParser",
".",
"new",
"do",
"|",
"opts",
"|",
"note",
"=",
"'Define environment... | parse options from argument list | [
"parse",
"options",
"from",
"argument",
"list"
] | 74271f30d0ec35f1f44421b7ae92c2f4ccf51786 | https://github.com/thomis/eventhub-processor2/blob/74271f30d0ec35f1f44421b7ae92c2f4ccf51786/lib/eventhub/configuration.rb#L35-L61 | valid |
thomis/eventhub-processor2 | lib/eventhub/configuration.rb | EventHub.Configuration.load! | def load!(args = {})
# for better rspec testing
@config_file = args[:config_file] if args[:config_file]
@environment = args[:environment] if args[:environment]
new_data = {}
begin
new_data = JSON.parse(File.read(@config_file), symbolize_names: true)
rescue => e
EventHub.logger.warn("Exception while loading configuration file: #{e}")
EventHub.logger.info('Using default configuration values')
end
deep_merge!(@config_data, default_configuration)
new_data = new_data[@environment.to_sym]
deep_merge!(@config_data, new_data)
end | ruby | def load!(args = {})
# for better rspec testing
@config_file = args[:config_file] if args[:config_file]
@environment = args[:environment] if args[:environment]
new_data = {}
begin
new_data = JSON.parse(File.read(@config_file), symbolize_names: true)
rescue => e
EventHub.logger.warn("Exception while loading configuration file: #{e}")
EventHub.logger.info('Using default configuration values')
end
deep_merge!(@config_data, default_configuration)
new_data = new_data[@environment.to_sym]
deep_merge!(@config_data, new_data)
end | [
"def",
"load!",
"(",
"args",
"=",
"{",
"}",
")",
"@config_file",
"=",
"args",
"[",
":config_file",
"]",
"if",
"args",
"[",
":config_file",
"]",
"@environment",
"=",
"args",
"[",
":environment",
"]",
"if",
"args",
"[",
":environment",
"]",
"new_data",
"="... | load configuration from file | [
"load",
"configuration",
"from",
"file"
] | 74271f30d0ec35f1f44421b7ae92c2f4ccf51786 | https://github.com/thomis/eventhub-processor2/blob/74271f30d0ec35f1f44421b7ae92c2f4ccf51786/lib/eventhub/configuration.rb#L64-L80 | valid |
vidibus/vidibus-words | lib/vidibus/words.rb | Vidibus.Words.keywords | def keywords(limit = 20)
@keywords ||= {}
@keywords[limit] ||= begin
list = []
count = 0
_stopwords = Vidibus::Words.stopwords(*locales)
for word in sort
clean = word.permalink.gsub('-','')
unless _stopwords.include?(clean)
list << word
count += 1
break if count >= limit
end
end
list
end
end | ruby | def keywords(limit = 20)
@keywords ||= {}
@keywords[limit] ||= begin
list = []
count = 0
_stopwords = Vidibus::Words.stopwords(*locales)
for word in sort
clean = word.permalink.gsub('-','')
unless _stopwords.include?(clean)
list << word
count += 1
break if count >= limit
end
end
list
end
end | [
"def",
"keywords",
"(",
"limit",
"=",
"20",
")",
"@keywords",
"||=",
"{",
"}",
"@keywords",
"[",
"limit",
"]",
"||=",
"begin",
"list",
"=",
"[",
"]",
"count",
"=",
"0",
"_stopwords",
"=",
"Vidibus",
"::",
"Words",
".",
"stopwords",
"(",
"*",
"locales... | Returns top keywords from input string. | [
"Returns",
"top",
"keywords",
"from",
"input",
"string",
"."
] | de01b2e84feec75ca175d44db4f4765a5ae41b1f | https://github.com/vidibus/vidibus-words/blob/de01b2e84feec75ca175d44db4f4765a5ae41b1f/lib/vidibus/words.rb#L39-L55 | valid |
yob/onix | lib/onix/normaliser.rb | ONIX.Normaliser.next_tempfile | def next_tempfile
p = nil
Tempfile.open("onix") do |tf|
p = tf.path
tf.close!
end
p
end | ruby | def next_tempfile
p = nil
Tempfile.open("onix") do |tf|
p = tf.path
tf.close!
end
p
end | [
"def",
"next_tempfile",
"p",
"=",
"nil",
"Tempfile",
".",
"open",
"(",
"\"onix\"",
")",
"do",
"|",
"tf",
"|",
"p",
"=",
"tf",
".",
"path",
"tf",
".",
"close!",
"end",
"p",
"end"
] | generate a temp filename | [
"generate",
"a",
"temp",
"filename"
] | 0d4c9a966f47868ea4dd01690e118bea87442ced | https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/normaliser.rb#L78-L85 | valid |
yob/onix | lib/onix/reader.rb | ONIX.Reader.each | def each(&block)
@reader.each do |node|
if @reader.node_type == 1 && @reader.name == "Product"
str = @reader.outer_xml
if str.nil?
yield @product_klass.new
else
yield @product_klass.from_xml(str)
end
end
end
end | ruby | def each(&block)
@reader.each do |node|
if @reader.node_type == 1 && @reader.name == "Product"
str = @reader.outer_xml
if str.nil?
yield @product_klass.new
else
yield @product_klass.from_xml(str)
end
end
end
end | [
"def",
"each",
"(",
"&",
"block",
")",
"@reader",
".",
"each",
"do",
"|",
"node",
"|",
"if",
"@reader",
".",
"node_type",
"==",
"1",
"&&",
"@reader",
".",
"name",
"==",
"\"Product\"",
"str",
"=",
"@reader",
".",
"outer_xml",
"if",
"str",
".",
"nil?",... | Iterate over all the products in an ONIX file | [
"Iterate",
"over",
"all",
"the",
"products",
"in",
"an",
"ONIX",
"file"
] | 0d4c9a966f47868ea4dd01690e118bea87442ced | https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/reader.rb#L106-L117 | valid |
yob/onix | lib/onix/apa_product.rb | ONIX.APAProduct.title | def title
composite = product.titles.first
if composite.nil?
nil
else
composite.title_text || composite.title_without_prefix
end
end | ruby | def title
composite = product.titles.first
if composite.nil?
nil
else
composite.title_text || composite.title_without_prefix
end
end | [
"def",
"title",
"composite",
"=",
"product",
".",
"titles",
".",
"first",
"if",
"composite",
".",
"nil?",
"nil",
"else",
"composite",
".",
"title_text",
"||",
"composite",
".",
"title_without_prefix",
"end",
"end"
] | retrieve the current title | [
"retrieve",
"the",
"current",
"title"
] | 0d4c9a966f47868ea4dd01690e118bea87442ced | https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L68-L75 | valid |
yob/onix | lib/onix/apa_product.rb | ONIX.APAProduct.title= | def title=(str)
composite = product.titles.first
if composite.nil?
composite = ONIX::Title.new
composite.title_type = 1
product.titles << composite
end
composite.title_text = str
end | ruby | def title=(str)
composite = product.titles.first
if composite.nil?
composite = ONIX::Title.new
composite.title_type = 1
product.titles << composite
end
composite.title_text = str
end | [
"def",
"title",
"=",
"(",
"str",
")",
"composite",
"=",
"product",
".",
"titles",
".",
"first",
"if",
"composite",
".",
"nil?",
"composite",
"=",
"ONIX",
"::",
"Title",
".",
"new",
"composite",
".",
"title_type",
"=",
"1",
"product",
".",
"titles",
"<<... | set a new title | [
"set",
"a",
"new",
"title"
] | 0d4c9a966f47868ea4dd01690e118bea87442ced | https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L78-L86 | valid |
yob/onix | lib/onix/apa_product.rb | ONIX.APAProduct.subtitle= | def subtitle=(str)
composite = product.titles.first
if composite.nil?
composite = ONIX::Title.new
composite.title_type = 1
product.titles << composite
end
composite.subtitle = str
end | ruby | def subtitle=(str)
composite = product.titles.first
if composite.nil?
composite = ONIX::Title.new
composite.title_type = 1
product.titles << composite
end
composite.subtitle = str
end | [
"def",
"subtitle",
"=",
"(",
"str",
")",
"composite",
"=",
"product",
".",
"titles",
".",
"first",
"if",
"composite",
".",
"nil?",
"composite",
"=",
"ONIX",
"::",
"Title",
".",
"new",
"composite",
".",
"title_type",
"=",
"1",
"product",
".",
"titles",
... | set a new subtitle | [
"set",
"a",
"new",
"subtitle"
] | 0d4c9a966f47868ea4dd01690e118bea87442ced | https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L99-L107 | valid |
yob/onix | lib/onix/apa_product.rb | ONIX.APAProduct.bic_subjects | def bic_subjects
subjects = product.subjects.select { |sub| sub.subject_scheme_id.to_i == 12 }
subjects.collect { |sub| sub.subject_code}
end | ruby | def bic_subjects
subjects = product.subjects.select { |sub| sub.subject_scheme_id.to_i == 12 }
subjects.collect { |sub| sub.subject_code}
end | [
"def",
"bic_subjects",
"subjects",
"=",
"product",
".",
"subjects",
".",
"select",
"{",
"|",
"sub",
"|",
"sub",
".",
"subject_scheme_id",
".",
"to_i",
"==",
"12",
"}",
"subjects",
".",
"collect",
"{",
"|",
"sub",
"|",
"sub",
".",
"subject_code",
"}",
"... | return an array of BIC subjects for this title
could be version 1 or version 2, most ONIX files don't
specifiy | [
"return",
"an",
"array",
"of",
"BIC",
"subjects",
"for",
"this",
"title",
"could",
"be",
"version",
"1",
"or",
"version",
"2",
"most",
"ONIX",
"files",
"don",
"t",
"specifiy"
] | 0d4c9a966f47868ea4dd01690e118bea87442ced | https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L161-L164 | valid |
yob/onix | lib/onix/apa_product.rb | ONIX.APAProduct.imprint= | def imprint=(str)
composite = product.imprints.first
if composite.nil?
composite = ONIX::Imprint.new
product.imprints << composite
end
composite.imprint_name = str
end | ruby | def imprint=(str)
composite = product.imprints.first
if composite.nil?
composite = ONIX::Imprint.new
product.imprints << composite
end
composite.imprint_name = str
end | [
"def",
"imprint",
"=",
"(",
"str",
")",
"composite",
"=",
"product",
".",
"imprints",
".",
"first",
"if",
"composite",
".",
"nil?",
"composite",
"=",
"ONIX",
"::",
"Imprint",
".",
"new",
"product",
".",
"imprints",
"<<",
"composite",
"end",
"composite",
... | set a new imprint | [
"set",
"a",
"new",
"imprint"
] | 0d4c9a966f47868ea4dd01690e118bea87442ced | https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L255-L262 | valid |
yob/onix | lib/onix/apa_product.rb | ONIX.APAProduct.sales_restriction_type= | def sales_restriction_type=(type)
composite = product.sales_restrictions.first
if composite.nil?
composite = ONIX::SalesRestriction.new
product.sales_restrictions << composite
end
composite.sales_restriction_type = type
end | ruby | def sales_restriction_type=(type)
composite = product.sales_restrictions.first
if composite.nil?
composite = ONIX::SalesRestriction.new
product.sales_restrictions << composite
end
composite.sales_restriction_type = type
end | [
"def",
"sales_restriction_type",
"=",
"(",
"type",
")",
"composite",
"=",
"product",
".",
"sales_restrictions",
".",
"first",
"if",
"composite",
".",
"nil?",
"composite",
"=",
"ONIX",
"::",
"SalesRestriction",
".",
"new",
"product",
".",
"sales_restrictions",
"<... | set a new sales restriction type | [
"set",
"a",
"new",
"sales",
"restriction",
"type"
] | 0d4c9a966f47868ea4dd01690e118bea87442ced | https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L281-L288 | valid |
yob/onix | lib/onix/apa_product.rb | ONIX.APAProduct.on_order | def on_order
supply = find_or_create_supply_detail
composite = supply.stock.first
if composite.nil?
composite = ONIX::Stock.new
supply.stock << composite
end
composite.on_order
end | ruby | def on_order
supply = find_or_create_supply_detail
composite = supply.stock.first
if composite.nil?
composite = ONIX::Stock.new
supply.stock << composite
end
composite.on_order
end | [
"def",
"on_order",
"supply",
"=",
"find_or_create_supply_detail",
"composite",
"=",
"supply",
".",
"stock",
".",
"first",
"if",
"composite",
".",
"nil?",
"composite",
"=",
"ONIX",
"::",
"Stock",
".",
"new",
"supply",
".",
"stock",
"<<",
"composite",
"end",
"... | retrieve the number on order | [
"retrieve",
"the",
"number",
"on",
"order"
] | 0d4c9a966f47868ea4dd01690e118bea87442ced | https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L385-L393 | valid |
yob/onix | lib/onix/apa_product.rb | ONIX.APAProduct.proprietry_discount_code_for_rrp | def proprietry_discount_code_for_rrp
price = price_get(2)
return nil if price.nil?
discount = price.discounts_coded.find { |disc| disc.discount_code_type == 2 }
discount.andand.discount_code
end | ruby | def proprietry_discount_code_for_rrp
price = price_get(2)
return nil if price.nil?
discount = price.discounts_coded.find { |disc| disc.discount_code_type == 2 }
discount.andand.discount_code
end | [
"def",
"proprietry_discount_code_for_rrp",
"price",
"=",
"price_get",
"(",
"2",
")",
"return",
"nil",
"if",
"price",
".",
"nil?",
"discount",
"=",
"price",
".",
"discounts_coded",
".",
"find",
"{",
"|",
"disc",
"|",
"disc",
".",
"discount_code_type",
"==",
"... | retrieve the discount code that describes the rrp in this file | [
"retrieve",
"the",
"discount",
"code",
"that",
"describes",
"the",
"rrp",
"in",
"this",
"file"
] | 0d4c9a966f47868ea4dd01690e118bea87442ced | https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L449-L455 | valid |
yob/onix | lib/onix/apa_product.rb | ONIX.APAProduct.proprietry_discount_code_for_rrp= | def proprietry_discount_code_for_rrp=(code)
price = price_get(2)
if price.nil?
self.rrp_inc_sales_tax = 0
price = price_get(2)
end
discount = price.discounts_coded.find { |disc| disc.discount_code_type == 2 }
if discount.nil?
discount = ONIX::DiscountCoded.new
discount.discount_code_type = 2
price.discounts_coded << discount
end
discount.discount_code = code
end | ruby | def proprietry_discount_code_for_rrp=(code)
price = price_get(2)
if price.nil?
self.rrp_inc_sales_tax = 0
price = price_get(2)
end
discount = price.discounts_coded.find { |disc| disc.discount_code_type == 2 }
if discount.nil?
discount = ONIX::DiscountCoded.new
discount.discount_code_type = 2
price.discounts_coded << discount
end
discount.discount_code = code
end | [
"def",
"proprietry_discount_code_for_rrp",
"=",
"(",
"code",
")",
"price",
"=",
"price_get",
"(",
"2",
")",
"if",
"price",
".",
"nil?",
"self",
".",
"rrp_inc_sales_tax",
"=",
"0",
"price",
"=",
"price_get",
"(",
"2",
")",
"end",
"discount",
"=",
"price",
... | set the discount code that describes the rrp in this file | [
"set",
"the",
"discount",
"code",
"that",
"describes",
"the",
"rrp",
"in",
"this",
"file"
] | 0d4c9a966f47868ea4dd01690e118bea87442ced | https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L458-L473 | valid |
yob/onix | lib/onix/apa_product.rb | ONIX.APAProduct.add_subject | def add_subject(str, type = "12")
subject = ::ONIX::Subject.new
subject.subject_scheme_id = type.to_i
subject.subject_code = str
product.subjects << subject
end | ruby | def add_subject(str, type = "12")
subject = ::ONIX::Subject.new
subject.subject_scheme_id = type.to_i
subject.subject_code = str
product.subjects << subject
end | [
"def",
"add_subject",
"(",
"str",
",",
"type",
"=",
"\"12\"",
")",
"subject",
"=",
"::",
"ONIX",
"::",
"Subject",
".",
"new",
"subject",
".",
"subject_scheme_id",
"=",
"type",
".",
"to_i",
"subject",
".",
"subject_code",
"=",
"str",
"product",
".",
"subj... | add a new subject to this product
str should be the subject code
type should be the code for the subject scheme you're using. See ONIX codelist 27.
12 is BIC | [
"add",
"a",
"new",
"subject",
"to",
"this",
"product",
"str",
"should",
"be",
"the",
"subject",
"code",
"type",
"should",
"be",
"the",
"code",
"for",
"the",
"subject",
"scheme",
"you",
"re",
"using",
".",
"See",
"ONIX",
"codelist",
"27",
".",
"12",
"is... | 0d4c9a966f47868ea4dd01690e118bea87442ced | https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L624-L629 | valid |
yob/onix | lib/onix/apa_product.rb | ONIX.APAProduct.measurement_set | def measurement_set(type, value, unit)
measure = measurement(type)
# create a new isbn record if we need to
if measure.nil?
measure = ONIX::Measure.new
measure.measure_type_code = type
product.measurements << measure
end
# store the new value
measure.measurement = value
measure.measure_unit_code = unit.to_s
end | ruby | def measurement_set(type, value, unit)
measure = measurement(type)
# create a new isbn record if we need to
if measure.nil?
measure = ONIX::Measure.new
measure.measure_type_code = type
product.measurements << measure
end
# store the new value
measure.measurement = value
measure.measure_unit_code = unit.to_s
end | [
"def",
"measurement_set",
"(",
"type",
",",
"value",
",",
"unit",
")",
"measure",
"=",
"measurement",
"(",
"type",
")",
"if",
"measure",
".",
"nil?",
"measure",
"=",
"ONIX",
"::",
"Measure",
".",
"new",
"measure",
".",
"measure_type_code",
"=",
"type",
"... | set the value of a particular measurement | [
"set",
"the",
"value",
"of",
"a",
"particular",
"measurement"
] | 0d4c9a966f47868ea4dd01690e118bea87442ced | https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L665-L678 | valid |
yob/onix | lib/onix/apa_product.rb | ONIX.APAProduct.price_get | def price_get(type)
supply = find_or_create_supply_detail
if type.nil?
supply.prices.first
else
supply.prices.find { |p| p.price_type_code == type }
end
end | ruby | def price_get(type)
supply = find_or_create_supply_detail
if type.nil?
supply.prices.first
else
supply.prices.find { |p| p.price_type_code == type }
end
end | [
"def",
"price_get",
"(",
"type",
")",
"supply",
"=",
"find_or_create_supply_detail",
"if",
"type",
".",
"nil?",
"supply",
".",
"prices",
".",
"first",
"else",
"supply",
".",
"prices",
".",
"find",
"{",
"|",
"p",
"|",
"p",
".",
"price_type_code",
"==",
"t... | retrieve the value of a particular price | [
"retrieve",
"the",
"value",
"of",
"a",
"particular",
"price"
] | 0d4c9a966f47868ea4dd01690e118bea87442ced | https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L702-L709 | valid |
yob/onix | lib/onix/apa_product.rb | ONIX.APAProduct.price_set | def price_set(type, num)
p = price_get(type)
# create a new isbn record if we need to
if p.nil?
supply = find_or_create_supply_detail
p = ONIX::Price.new
p.price_type_code = type
supply.prices << p
end
# store the new value
p.price_amount = num
end | ruby | def price_set(type, num)
p = price_get(type)
# create a new isbn record if we need to
if p.nil?
supply = find_or_create_supply_detail
p = ONIX::Price.new
p.price_type_code = type
supply.prices << p
end
# store the new value
p.price_amount = num
end | [
"def",
"price_set",
"(",
"type",
",",
"num",
")",
"p",
"=",
"price_get",
"(",
"type",
")",
"if",
"p",
".",
"nil?",
"supply",
"=",
"find_or_create_supply_detail",
"p",
"=",
"ONIX",
"::",
"Price",
".",
"new",
"p",
".",
"price_type_code",
"=",
"type",
"su... | set the value of a particular price | [
"set",
"the",
"value",
"of",
"a",
"particular",
"price"
] | 0d4c9a966f47868ea4dd01690e118bea87442ced | https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L712-L725 | valid |
yob/onix | lib/onix/apa_product.rb | ONIX.APAProduct.other_text_set | def other_text_set(type, value)
text = other_text(type)
if text.nil?
text = ONIX::OtherText.new
text.text_type_code = type
product.text << text
end
# store the new value
text.text = value.to_s
end | ruby | def other_text_set(type, value)
text = other_text(type)
if text.nil?
text = ONIX::OtherText.new
text.text_type_code = type
product.text << text
end
# store the new value
text.text = value.to_s
end | [
"def",
"other_text_set",
"(",
"type",
",",
"value",
")",
"text",
"=",
"other_text",
"(",
"type",
")",
"if",
"text",
".",
"nil?",
"text",
"=",
"ONIX",
"::",
"OtherText",
".",
"new",
"text",
".",
"text_type_code",
"=",
"type",
"product",
".",
"text",
"<<... | set the value of a particular other text value | [
"set",
"the",
"value",
"of",
"a",
"particular",
"other",
"text",
"value"
] | 0d4c9a966f47868ea4dd01690e118bea87442ced | https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L753-L764 | valid |
yob/onix | lib/onix/apa_product.rb | ONIX.APAProduct.website_set | def website_set(type, value)
site = website(type)
# create a new website record if we need to
if site.nil?
site = ONIX::Website.new
site.website_role = type
product.websites << site
end
site.website_link = value.to_s
end | ruby | def website_set(type, value)
site = website(type)
# create a new website record if we need to
if site.nil?
site = ONIX::Website.new
site.website_role = type
product.websites << site
end
site.website_link = value.to_s
end | [
"def",
"website_set",
"(",
"type",
",",
"value",
")",
"site",
"=",
"website",
"(",
"type",
")",
"if",
"site",
".",
"nil?",
"site",
"=",
"ONIX",
"::",
"Website",
".",
"new",
"site",
".",
"website_role",
"=",
"type",
"product",
".",
"websites",
"<<",
"... | set the value of a particular website | [
"set",
"the",
"value",
"of",
"a",
"particular",
"website"
] | 0d4c9a966f47868ea4dd01690e118bea87442ced | https://github.com/yob/onix/blob/0d4c9a966f47868ea4dd01690e118bea87442ced/lib/onix/apa_product.rb#L772-L783 | valid |
thejchap/popular | lib/popular/popular.rb | Popular.Popular.befriend | def befriend new_friend
run_callbacks :befriend do
friendships.create friend_id: new_friend.id, friend_type: new_friend.class.name
end
end | ruby | def befriend new_friend
run_callbacks :befriend do
friendships.create friend_id: new_friend.id, friend_type: new_friend.class.name
end
end | [
"def",
"befriend",
"new_friend",
"run_callbacks",
":befriend",
"do",
"friendships",
".",
"create",
"friend_id",
":",
"new_friend",
".",
"id",
",",
"friend_type",
":",
"new_friend",
".",
"class",
".",
"name",
"end",
"end"
] | Adds a friend to an instance's friend's list
@param [Object] new_friend a popular_model that the instance is not already friends with
@example
user = User.create name: "Justin"
other_user = User.create name: "Jenny"
user.befriend other_user
user.friends_with? other_user #=> true | [
"Adds",
"a",
"friend",
"to",
"an",
"instance",
"s",
"friend",
"s",
"list"
] | 9c0b63c9409b3e2bc0bbd356c60eead04de7a4df | https://github.com/thejchap/popular/blob/9c0b63c9409b3e2bc0bbd356c60eead04de7a4df/lib/popular/popular.rb#L49-L53 | valid |
thejchap/popular | lib/popular/popular.rb | Popular.Popular.befriend! | def befriend! new_friend
run_callbacks :befriend do
friendships.create! friend_id: new_friend.id, friend_type: new_friend.class.name
end
end | ruby | def befriend! new_friend
run_callbacks :befriend do
friendships.create! friend_id: new_friend.id, friend_type: new_friend.class.name
end
end | [
"def",
"befriend!",
"new_friend",
"run_callbacks",
":befriend",
"do",
"friendships",
".",
"create!",
"friend_id",
":",
"new_friend",
".",
"id",
",",
"friend_type",
":",
"new_friend",
".",
"class",
".",
"name",
"end",
"end"
] | Adds a friend to an instance's friend's list
Similar to .befriend, but will raise an error if the operation is not successful
@param [Object] new_friend a popular_model that the instance is not already friends with
@example
user = User.create name: "Justin"
other_user = User.create name: "Jenny"
user.befriend! other_user
user.friends_with? other_user # => true | [
"Adds",
"a",
"friend",
"to",
"an",
"instance",
"s",
"friend",
"s",
"list",
"Similar",
"to",
".",
"befriend",
"but",
"will",
"raise",
"an",
"error",
"if",
"the",
"operation",
"is",
"not",
"successful"
] | 9c0b63c9409b3e2bc0bbd356c60eead04de7a4df | https://github.com/thejchap/popular/blob/9c0b63c9409b3e2bc0bbd356c60eead04de7a4df/lib/popular/popular.rb#L66-L70 | valid |
thejchap/popular | lib/popular/popular.rb | Popular.Popular.unfriend | def unfriend friend
run_callbacks :unfriend do
friendships
.where( friend_type: friend.class.name )
.where( friend_id: friend.id )
.first.destroy
end
end | ruby | def unfriend friend
run_callbacks :unfriend do
friendships
.where( friend_type: friend.class.name )
.where( friend_id: friend.id )
.first.destroy
end
end | [
"def",
"unfriend",
"friend",
"run_callbacks",
":unfriend",
"do",
"friendships",
".",
"where",
"(",
"friend_type",
":",
"friend",
".",
"class",
".",
"name",
")",
".",
"where",
"(",
"friend_id",
":",
"friend",
".",
"id",
")",
".",
"first",
".",
"destroy",
... | Removes a friend from an instance's friend's list
@param [Object] friend a popular_model in this instance's friends list
@example
user = User.create name: "Justin"
other_user = User.create name: "Jenny"
user.befriend other_user
user.unfriend other_user
user.friends_with? other_user # => false | [
"Removes",
"a",
"friend",
"from",
"an",
"instance",
"s",
"friend",
"s",
"list"
] | 9c0b63c9409b3e2bc0bbd356c60eead04de7a4df | https://github.com/thejchap/popular/blob/9c0b63c9409b3e2bc0bbd356c60eead04de7a4df/lib/popular/popular.rb#L83-L90 | valid |
ferndopolis/timecop-console | lib/timecop_console/controller_methods.rb | TimecopConsole.ControllerMethods.handle_timecop_offset | def handle_timecop_offset
# Establish now
if session[TimecopConsole::SESSION_KEY_NAME].present?
Rails.logger.debug "[timecop-console] Time traveling to #{session[TimecopConsole::SESSION_KEY_NAME].to_s}"
Timecop.travel(session[TimecopConsole::SESSION_KEY_NAME])
else
Timecop.return
end
# Run the intended action
yield
if session[TimecopConsole::SESSION_KEY_NAME].present?
# we want to continue to slide time forward, even if it's only 3 seconds at a time.
# this ensures that subsequent calls during the same "time travel" actually pass time
adjusted_time = Time.now + 3
Rails.logger.debug "[timecop-console] Resetting session to: #{adjusted_time}"
session[TimecopConsole::SESSION_KEY_NAME] = adjusted_time
end
end | ruby | def handle_timecop_offset
# Establish now
if session[TimecopConsole::SESSION_KEY_NAME].present?
Rails.logger.debug "[timecop-console] Time traveling to #{session[TimecopConsole::SESSION_KEY_NAME].to_s}"
Timecop.travel(session[TimecopConsole::SESSION_KEY_NAME])
else
Timecop.return
end
# Run the intended action
yield
if session[TimecopConsole::SESSION_KEY_NAME].present?
# we want to continue to slide time forward, even if it's only 3 seconds at a time.
# this ensures that subsequent calls during the same "time travel" actually pass time
adjusted_time = Time.now + 3
Rails.logger.debug "[timecop-console] Resetting session to: #{adjusted_time}"
session[TimecopConsole::SESSION_KEY_NAME] = adjusted_time
end
end | [
"def",
"handle_timecop_offset",
"if",
"session",
"[",
"TimecopConsole",
"::",
"SESSION_KEY_NAME",
"]",
".",
"present?",
"Rails",
".",
"logger",
".",
"debug",
"\"[timecop-console] Time traveling to #{session[TimecopConsole::SESSION_KEY_NAME].to_s}\"",
"Timecop",
".",
"travel",
... | to be used as an around_filter | [
"to",
"be",
"used",
"as",
"an",
"around_filter"
] | 30491e690e9882701ef0609e2fe87b3573b5efcb | https://github.com/ferndopolis/timecop-console/blob/30491e690e9882701ef0609e2fe87b3573b5efcb/lib/timecop_console/controller_methods.rb#L11-L30 | valid |
bf4/code_metrics | lib/code_metrics/stats_directories.rb | CodeMetrics.StatsDirectories.default_app_directories | def default_app_directories
StatDirectory.from_list([
%w(Controllers app/controllers),
%w(Helpers app/helpers),
%w(Models app/models),
%w(Mailers app/mailers),
%w(Javascripts app/assets/javascripts),
%w(Libraries lib),
%w(APIs app/apis)
], @root)
end | ruby | def default_app_directories
StatDirectory.from_list([
%w(Controllers app/controllers),
%w(Helpers app/helpers),
%w(Models app/models),
%w(Mailers app/mailers),
%w(Javascripts app/assets/javascripts),
%w(Libraries lib),
%w(APIs app/apis)
], @root)
end | [
"def",
"default_app_directories",
"StatDirectory",
".",
"from_list",
"(",
"[",
"%w(",
"Controllers",
"app/controllers",
")",
",",
"%w(",
"Helpers",
"app/helpers",
")",
",",
"%w(",
"Models",
"app/models",
")",
",",
"%w(",
"Mailers",
"app/mailers",
")",
",",
"%w("... | What Rails expects | [
"What",
"Rails",
"expects"
] | 115cb539ccc494ac151c34a5d61b4e010e45d21b | https://github.com/bf4/code_metrics/blob/115cb539ccc494ac151c34a5d61b4e010e45d21b/lib/code_metrics/stats_directories.rb#L38-L48 | valid |
bf4/code_metrics | lib/code_metrics/stats_directories.rb | CodeMetrics.StatsDirectories.collect_directories | def collect_directories(glob_pattern, file_pattern='')
Pathname.glob(glob_pattern).select{|f| f.basename.to_s.include?(file_pattern) }.map(&:dirname).uniq.map(&:realpath)
end | ruby | def collect_directories(glob_pattern, file_pattern='')
Pathname.glob(glob_pattern).select{|f| f.basename.to_s.include?(file_pattern) }.map(&:dirname).uniq.map(&:realpath)
end | [
"def",
"collect_directories",
"(",
"glob_pattern",
",",
"file_pattern",
"=",
"''",
")",
"Pathname",
".",
"glob",
"(",
"glob_pattern",
")",
".",
"select",
"{",
"|",
"f",
"|",
"f",
".",
"basename",
".",
"to_s",
".",
"include?",
"(",
"file_pattern",
")",
"}... | collects non empty directories and names the metric by the folder name
parent? or dirname? or basename? | [
"collects",
"non",
"empty",
"directories",
"and",
"names",
"the",
"metric",
"by",
"the",
"folder",
"name",
"parent?",
"or",
"dirname?",
"or",
"basename?"
] | 115cb539ccc494ac151c34a5d61b4e010e45d21b | https://github.com/bf4/code_metrics/blob/115cb539ccc494ac151c34a5d61b4e010e45d21b/lib/code_metrics/stats_directories.rb#L107-L109 | valid |
wejn/ws2812 | lib/ws2812/basic.rb | Ws2812.Basic.[]= | def []=(index, color)
if index.respond_to?(:to_a)
index.to_a.each do |i|
check_index(i)
ws2811_led_set(@channel, i, color.to_i)
end
else
check_index(index)
ws2811_led_set(@channel, index, color.to_i)
end
end | ruby | def []=(index, color)
if index.respond_to?(:to_a)
index.to_a.each do |i|
check_index(i)
ws2811_led_set(@channel, i, color.to_i)
end
else
check_index(index)
ws2811_led_set(@channel, index, color.to_i)
end
end | [
"def",
"[]=",
"(",
"index",
",",
"color",
")",
"if",
"index",
".",
"respond_to?",
"(",
":to_a",
")",
"index",
".",
"to_a",
".",
"each",
"do",
"|",
"i",
"|",
"check_index",
"(",
"i",
")",
"ws2811_led_set",
"(",
"@channel",
",",
"i",
",",
"color",
".... | Set given pixel identified by +index+ to +color+
See +set+ for a method that takes individual +r+, +g+, +b+
components | [
"Set",
"given",
"pixel",
"identified",
"by",
"+",
"index",
"+",
"to",
"+",
"color",
"+"
] | 69195f827052e30f989e8502f0caabb19b343dfd | https://github.com/wejn/ws2812/blob/69195f827052e30f989e8502f0caabb19b343dfd/lib/ws2812/basic.rb#L116-L126 | valid |
wejn/ws2812 | lib/ws2812/basic.rb | Ws2812.Basic.set | def set(index, r, g, b)
check_index(index)
self[index] = Color.new(r, g, b)
end | ruby | def set(index, r, g, b)
check_index(index)
self[index] = Color.new(r, g, b)
end | [
"def",
"set",
"(",
"index",
",",
"r",
",",
"g",
",",
"b",
")",
"check_index",
"(",
"index",
")",
"self",
"[",
"index",
"]",
"=",
"Color",
".",
"new",
"(",
"r",
",",
"g",
",",
"b",
")",
"end"
] | Set given pixel identified by +index+ to +r+, +g+, +b+
See <tt>[]=</tt> for a method that takes +Color+ instance instead
of individual components | [
"Set",
"given",
"pixel",
"identified",
"by",
"+",
"index",
"+",
"to",
"+",
"r",
"+",
"+",
"g",
"+",
"+",
"b",
"+"
] | 69195f827052e30f989e8502f0caabb19b343dfd | https://github.com/wejn/ws2812/blob/69195f827052e30f989e8502f0caabb19b343dfd/lib/ws2812/basic.rb#L133-L136 | valid |
wejn/ws2812 | lib/ws2812/basic.rb | Ws2812.Basic.[] | def [](index)
if index.respond_to?(:to_a)
index.to_a.map do |i|
check_index(i)
Color.from_i(ws2811_led_get(@channel, i))
end
else
check_index(index)
Color.from_i(ws2811_led_get(@channel, index))
end
end | ruby | def [](index)
if index.respond_to?(:to_a)
index.to_a.map do |i|
check_index(i)
Color.from_i(ws2811_led_get(@channel, i))
end
else
check_index(index)
Color.from_i(ws2811_led_get(@channel, index))
end
end | [
"def",
"[]",
"(",
"index",
")",
"if",
"index",
".",
"respond_to?",
"(",
":to_a",
")",
"index",
".",
"to_a",
".",
"map",
"do",
"|",
"i",
"|",
"check_index",
"(",
"i",
")",
"Color",
".",
"from_i",
"(",
"ws2811_led_get",
"(",
"@channel",
",",
"i",
")"... | Return +Color+ of led located at given index
Indexed from 0 upto <tt>#count - 1</tt> | [
"Return",
"+",
"Color",
"+",
"of",
"led",
"located",
"at",
"given",
"index"
] | 69195f827052e30f989e8502f0caabb19b343dfd | https://github.com/wejn/ws2812/blob/69195f827052e30f989e8502f0caabb19b343dfd/lib/ws2812/basic.rb#L169-L179 | valid |
jkeiser/knife-essentials | lib/chef_fs/config.rb | ChefFS.Config.format_path | def format_path(entry)
server_path = entry.path
if base_path && server_path[0,base_path.length] == base_path
if server_path == base_path
return "."
elsif server_path[base_path.length,1] == "/"
return server_path[base_path.length + 1, server_path.length - base_path.length - 1]
elsif base_path == "/" && server_path[0,1] == "/"
return server_path[1, server_path.length - 1]
end
end
server_path
end | ruby | def format_path(entry)
server_path = entry.path
if base_path && server_path[0,base_path.length] == base_path
if server_path == base_path
return "."
elsif server_path[base_path.length,1] == "/"
return server_path[base_path.length + 1, server_path.length - base_path.length - 1]
elsif base_path == "/" && server_path[0,1] == "/"
return server_path[1, server_path.length - 1]
end
end
server_path
end | [
"def",
"format_path",
"(",
"entry",
")",
"server_path",
"=",
"entry",
".",
"path",
"if",
"base_path",
"&&",
"server_path",
"[",
"0",
",",
"base_path",
".",
"length",
"]",
"==",
"base_path",
"if",
"server_path",
"==",
"base_path",
"return",
"\".\"",
"elsif",
... | Print the given server path, relative to the current directory | [
"Print",
"the",
"given",
"server",
"path",
"relative",
"to",
"the",
"current",
"directory"
] | ae8dcebd4694e9bda618eac52228d07d88813ce8 | https://github.com/jkeiser/knife-essentials/blob/ae8dcebd4694e9bda618eac52228d07d88813ce8/lib/chef_fs/config.rb#L118-L130 | valid |
jkeiser/knife-essentials | lib/chef_fs/file_pattern.rb | ChefFS.FilePattern.exact_path | def exact_path
return nil if has_double_star || exact_parts.any? { |part| part.nil? }
result = ChefFS::PathUtils::join(*exact_parts)
is_absolute ? ChefFS::PathUtils::join('', result) : result
end | ruby | def exact_path
return nil if has_double_star || exact_parts.any? { |part| part.nil? }
result = ChefFS::PathUtils::join(*exact_parts)
is_absolute ? ChefFS::PathUtils::join('', result) : result
end | [
"def",
"exact_path",
"return",
"nil",
"if",
"has_double_star",
"||",
"exact_parts",
".",
"any?",
"{",
"|",
"part",
"|",
"part",
".",
"nil?",
"}",
"result",
"=",
"ChefFS",
"::",
"PathUtils",
"::",
"join",
"(",
"*",
"exact_parts",
")",
"is_absolute",
"?",
... | If this pattern represents an exact path, returns the exact path.
abc/def.exact_path == 'abc/def'
abc/*def.exact_path == 'abc/def'
abc/x\\yz.exact_path == 'abc/xyz' | [
"If",
"this",
"pattern",
"represents",
"an",
"exact",
"path",
"returns",
"the",
"exact",
"path",
"."
] | ae8dcebd4694e9bda618eac52228d07d88813ce8 | https://github.com/jkeiser/knife-essentials/blob/ae8dcebd4694e9bda618eac52228d07d88813ce8/lib/chef_fs/file_pattern.rb#L124-L128 | valid |
wejn/ws2812 | lib/ws2812/unicornhat.rb | Ws2812.UnicornHAT.[]= | def []=(x, y, color)
check_coords(x, y)
@pixels[x][y] = color
@hat[map_coords(x, y)] = color
end | ruby | def []=(x, y, color)
check_coords(x, y)
@pixels[x][y] = color
@hat[map_coords(x, y)] = color
end | [
"def",
"[]=",
"(",
"x",
",",
"y",
",",
"color",
")",
"check_coords",
"(",
"x",
",",
"y",
")",
"@pixels",
"[",
"x",
"]",
"[",
"y",
"]",
"=",
"color",
"@hat",
"[",
"map_coords",
"(",
"x",
",",
"y",
")",
"]",
"=",
"color",
"end"
] | Set given pixel identified by +x+, +y+ to +color+
See +set+ for a method that takes individual +r+, +g+, +b+
components.
You still have to call +show+ to make the changes visible. | [
"Set",
"given",
"pixel",
"identified",
"by",
"+",
"x",
"+",
"+",
"y",
"+",
"to",
"+",
"color",
"+"
] | 69195f827052e30f989e8502f0caabb19b343dfd | https://github.com/wejn/ws2812/blob/69195f827052e30f989e8502f0caabb19b343dfd/lib/ws2812/unicornhat.rb#L79-L83 | valid |
wejn/ws2812 | lib/ws2812/unicornhat.rb | Ws2812.UnicornHAT.set | def set(x, y, r, g, b)
check_coords(x, y)
self[x, y] = Color.new(r, g, b)
end | ruby | def set(x, y, r, g, b)
check_coords(x, y)
self[x, y] = Color.new(r, g, b)
end | [
"def",
"set",
"(",
"x",
",",
"y",
",",
"r",
",",
"g",
",",
"b",
")",
"check_coords",
"(",
"x",
",",
"y",
")",
"self",
"[",
"x",
",",
"y",
"]",
"=",
"Color",
".",
"new",
"(",
"r",
",",
"g",
",",
"b",
")",
"end"
] | Set given pixel identified by +x+, +y+ to +r+, +g+, +b+
See <tt>[]=</tt> for a method that takes +Color+ instance instead
of individual components.
You still have to call +show+ to make the changes visible. | [
"Set",
"given",
"pixel",
"identified",
"by",
"+",
"x",
"+",
"+",
"y",
"+",
"to",
"+",
"r",
"+",
"+",
"g",
"+",
"+",
"b",
"+"
] | 69195f827052e30f989e8502f0caabb19b343dfd | https://github.com/wejn/ws2812/blob/69195f827052e30f989e8502f0caabb19b343dfd/lib/ws2812/unicornhat.rb#L92-L95 | valid |
wejn/ws2812 | lib/ws2812/unicornhat.rb | Ws2812.UnicornHAT.rotation= | def rotation=(val)
permissible = [0, 90, 180, 270]
fail ArgumentError, "invalid rotation, permissible: #{permissible.join(', ')}" unless permissible.include?(val % 360)
@rotation = val % 360
push_all_pixels
end | ruby | def rotation=(val)
permissible = [0, 90, 180, 270]
fail ArgumentError, "invalid rotation, permissible: #{permissible.join(', ')}" unless permissible.include?(val % 360)
@rotation = val % 360
push_all_pixels
end | [
"def",
"rotation",
"=",
"(",
"val",
")",
"permissible",
"=",
"[",
"0",
",",
"90",
",",
"180",
",",
"270",
"]",
"fail",
"ArgumentError",
",",
"\"invalid rotation, permissible: #{permissible.join(', ')}\"",
"unless",
"permissible",
".",
"include?",
"(",
"val",
"%"... | Set rotation of the Unicorn HAT to +val+
Permissible values for rotation are [0, 90, 180, 270] (mod 360).
You still have to call +show+ to make the changes visible. | [
"Set",
"rotation",
"of",
"the",
"Unicorn",
"HAT",
"to",
"+",
"val",
"+"
] | 69195f827052e30f989e8502f0caabb19b343dfd | https://github.com/wejn/ws2812/blob/69195f827052e30f989e8502f0caabb19b343dfd/lib/ws2812/unicornhat.rb#L135-L140 | valid |
wejn/ws2812 | lib/ws2812/unicornhat.rb | Ws2812.UnicornHAT.check_coords | def check_coords(x, y)
if 0 <= x && x < 8 && 0 <= y && y < 8
true
else
fail ArgumentError, "coord (#{x},#{y}) outside of permitted range ((0..7), (0..7))"
end
end | ruby | def check_coords(x, y)
if 0 <= x && x < 8 && 0 <= y && y < 8
true
else
fail ArgumentError, "coord (#{x},#{y}) outside of permitted range ((0..7), (0..7))"
end
end | [
"def",
"check_coords",
"(",
"x",
",",
"y",
")",
"if",
"0",
"<=",
"x",
"&&",
"x",
"<",
"8",
"&&",
"0",
"<=",
"y",
"&&",
"y",
"<",
"8",
"true",
"else",
"fail",
"ArgumentError",
",",
"\"coord (#{x},#{y}) outside of permitted range ((0..7), (0..7))\"",
"end",
... | Verify supplied coords +x+ and +y+
Raises ArgumentError if the supplied coords are invalid
(doesn't address configured pixel) | [
"Verify",
"supplied",
"coords",
"+",
"x",
"+",
"and",
"+",
"y",
"+"
] | 69195f827052e30f989e8502f0caabb19b343dfd | https://github.com/wejn/ws2812/blob/69195f827052e30f989e8502f0caabb19b343dfd/lib/ws2812/unicornhat.rb#L200-L206 | valid |
jpmckinney/pupa-ruby | lib/pupa/models/model.rb | Pupa.Model.validate! | def validate!
if self.class.json_schema
self.class.validator.instance_variable_set('@errors', [])
self.class.validator.instance_variable_set('@data', stringify_keys(to_h(persist: true)))
self.class.validator.validate
true
end
end | ruby | def validate!
if self.class.json_schema
self.class.validator.instance_variable_set('@errors', [])
self.class.validator.instance_variable_set('@data', stringify_keys(to_h(persist: true)))
self.class.validator.validate
true
end
end | [
"def",
"validate!",
"if",
"self",
".",
"class",
".",
"json_schema",
"self",
".",
"class",
".",
"validator",
".",
"instance_variable_set",
"(",
"'@errors'",
",",
"[",
"]",
")",
"self",
".",
"class",
".",
"validator",
".",
"instance_variable_set",
"(",
"'@data... | Validates the object against the schema.
@raises [JSON::Schema::ValidationError] if the object is invalid | [
"Validates",
"the",
"object",
"against",
"the",
"schema",
"."
] | cb1485a42c1ee1a81cdf113a3199ad2993a45db1 | https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/models/model.rb#L165-L172 | valid |
jpmckinney/pupa-ruby | lib/pupa/models/model.rb | Pupa.Model.to_h | def to_h(persist: false)
{}.tap do |hash|
(persist ? properties - foreign_objects : properties).each do |property|
value = self[property]
if value == false || value.present?
hash[property] = value
end
end
end
end | ruby | def to_h(persist: false)
{}.tap do |hash|
(persist ? properties - foreign_objects : properties).each do |property|
value = self[property]
if value == false || value.present?
hash[property] = value
end
end
end
end | [
"def",
"to_h",
"(",
"persist",
":",
"false",
")",
"{",
"}",
".",
"tap",
"do",
"|",
"hash",
"|",
"(",
"persist",
"?",
"properties",
"-",
"foreign_objects",
":",
"properties",
")",
".",
"each",
"do",
"|",
"property",
"|",
"value",
"=",
"self",
"[",
"... | Returns the object as a hash.
@param [Boolean] persist whether the object is being persisted, validated,
or used as a database selector, in which case foreign objects (hints)
are excluded
@return [Hash] the object as a hash | [
"Returns",
"the",
"object",
"as",
"a",
"hash",
"."
] | cb1485a42c1ee1a81cdf113a3199ad2993a45db1 | https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/models/model.rb#L180-L189 | valid |
shawn42/tmx | lib/tmx/map.rb | Tmx.Map.export_to_file | def export_to_file(filename, options={})
content_string = export_to_string(default_options(filename).merge(:filename => filename))
File.open(filename, "w") { |f| f.write(content_string) }
nil
end | ruby | def export_to_file(filename, options={})
content_string = export_to_string(default_options(filename).merge(:filename => filename))
File.open(filename, "w") { |f| f.write(content_string) }
nil
end | [
"def",
"export_to_file",
"(",
"filename",
",",
"options",
"=",
"{",
"}",
")",
"content_string",
"=",
"export_to_string",
"(",
"default_options",
"(",
"filename",
")",
".",
"merge",
"(",
":filename",
"=>",
"filename",
")",
")",
"File",
".",
"open",
"(",
"fi... | Export this map to the given filename in the appropriate format.
@param filename [String] The file path to export to
@param options [Hash] Options for exporting
@option options [Symbol] format The format to export to, such as :tmx or :json
@return [void] | [
"Export",
"this",
"map",
"to",
"the",
"given",
"filename",
"in",
"the",
"appropriate",
"format",
"."
] | 9c1948e586781610b926b6019db21e0894118d33 | https://github.com/shawn42/tmx/blob/9c1948e586781610b926b6019db21e0894118d33/lib/tmx/map.rb#L19-L23 | valid |
shawn42/tmx | lib/tmx/map.rb | Tmx.Map.export_to_string | def export_to_string(options = {})
hash = self.to_h
# Need to add back all non-tilelayers to hash["layers"]
image_layers = hash.delete(:image_layers)
object_groups = hash.delete(:object_groups)
hash[:layers] += image_layers
hash[:layers] += object_groups
hash[:layers].sort_by! { |l| l[:name] }
hash.delete(:contents)
object_groups.each do |object_layer|
object_layer["objects"].each do |object|
# If present, "shape" and "points" should be removed
object.delete("shape")
object.delete("points")
end
end
MultiJson.dump(hash)
end | ruby | def export_to_string(options = {})
hash = self.to_h
# Need to add back all non-tilelayers to hash["layers"]
image_layers = hash.delete(:image_layers)
object_groups = hash.delete(:object_groups)
hash[:layers] += image_layers
hash[:layers] += object_groups
hash[:layers].sort_by! { |l| l[:name] }
hash.delete(:contents)
object_groups.each do |object_layer|
object_layer["objects"].each do |object|
# If present, "shape" and "points" should be removed
object.delete("shape")
object.delete("points")
end
end
MultiJson.dump(hash)
end | [
"def",
"export_to_string",
"(",
"options",
"=",
"{",
"}",
")",
"hash",
"=",
"self",
".",
"to_h",
"image_layers",
"=",
"hash",
".",
"delete",
"(",
":image_layers",
")",
"object_groups",
"=",
"hash",
".",
"delete",
"(",
":object_groups",
")",
"hash",
"[",
... | Export this map as a string in the appropriate format.
@param options [Hash] Options for exporting
@option options [Symbol,String] :format The format to export to, such as :tmx or :json
@option options [String] :filename The eventual filename, which gives a relative path for linked TSX files
@return [String] The exported content in the appropriate format | [
"Export",
"this",
"map",
"as",
"a",
"string",
"in",
"the",
"appropriate",
"format",
"."
] | 9c1948e586781610b926b6019db21e0894118d33 | https://github.com/shawn42/tmx/blob/9c1948e586781610b926b6019db21e0894118d33/lib/tmx/map.rb#L33-L53 | valid |
jpmckinney/pupa-ruby | lib/pupa/processor.rb | Pupa.Processor.dump_scraped_objects | def dump_scraped_objects(task_name)
counts = Hash.new(0)
@store.pipelined do
send(task_name).each do |object|
counts[object._type] += 1
dump_scraped_object(object)
end
end
counts
end | ruby | def dump_scraped_objects(task_name)
counts = Hash.new(0)
@store.pipelined do
send(task_name).each do |object|
counts[object._type] += 1
dump_scraped_object(object)
end
end
counts
end | [
"def",
"dump_scraped_objects",
"(",
"task_name",
")",
"counts",
"=",
"Hash",
".",
"new",
"(",
"0",
")",
"@store",
".",
"pipelined",
"do",
"send",
"(",
"task_name",
")",
".",
"each",
"do",
"|",
"object",
"|",
"counts",
"[",
"object",
".",
"_type",
"]",
... | Dumps scraped objects to disk.
@param [Symbol] task_name the name of the scraping task to perform
@return [Hash] the number of scraped objects by type
@raises [Pupa::Errors::DuplicateObjectIdError] | [
"Dumps",
"scraped",
"objects",
"to",
"disk",
"."
] | cb1485a42c1ee1a81cdf113a3199ad2993a45db1 | https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/processor.rb#L112-L121 | valid |
jpmckinney/pupa-ruby | lib/pupa/processor.rb | Pupa.Processor.import | def import
@report[:import] = {}
objects = deduplicate(load_scraped_objects)
object_id_to_database_id = {}
if use_dependency_graph?(objects)
dependency_graph = build_dependency_graph(objects)
# Replace object IDs with database IDs in foreign keys and save objects.
dependency_graph.tsort.each do |id|
object = objects[id]
resolve_foreign_keys(object, object_id_to_database_id)
# The dependency graph strategy only works if there are no foreign objects.
database_id = import_object(object)
object_id_to_database_id[id] = database_id
object_id_to_database_id[database_id] = database_id
end
else
size = objects.size
# Should be O(n²). If there are foreign objects, we do not know all the
# edges in the graph, and therefore cannot build a dependency graph or
# derive any evaluation order.
#
# An exception is raised if a foreign object matches multiple documents
# in the database. However, if a matching object is not yet saved, this
# exception may not be raised.
loop do
progress_made = false
objects.delete_if do |id,object|
begin
resolve_foreign_keys(object, object_id_to_database_id)
resolve_foreign_objects(object, object_id_to_database_id)
progress_made = true
database_id = import_object(object)
object_id_to_database_id[id] = database_id
object_id_to_database_id[database_id] = database_id
rescue Pupa::Errors::MissingDatabaseIdError
false
end
end
break if objects.empty? || !progress_made
end
unless objects.empty?
raise Errors::UnprocessableEntity, "couldn't resolve #{objects.size}/#{size} objects:\n #{objects.values.map{|object| JSON.dump(object.foreign_properties)}.join("\n ")}"
end
end
# Ensure that fingerprints uniquely identified objects.
counts = {}
object_id_to_database_id.each do |object_id,database_id|
unless object_id == database_id
(counts[database_id] ||= []) << object_id
end
end
duplicates = counts.select do |_,object_ids|
object_ids.size > 1
end
unless duplicates.empty?
raise Errors::DuplicateDocumentError, "multiple objects written to same document:\n" + duplicates.map{|database_id,object_ids| " #{database_id} <- #{object_ids.join(' ')}"}.join("\n")
end
end | ruby | def import
@report[:import] = {}
objects = deduplicate(load_scraped_objects)
object_id_to_database_id = {}
if use_dependency_graph?(objects)
dependency_graph = build_dependency_graph(objects)
# Replace object IDs with database IDs in foreign keys and save objects.
dependency_graph.tsort.each do |id|
object = objects[id]
resolve_foreign_keys(object, object_id_to_database_id)
# The dependency graph strategy only works if there are no foreign objects.
database_id = import_object(object)
object_id_to_database_id[id] = database_id
object_id_to_database_id[database_id] = database_id
end
else
size = objects.size
# Should be O(n²). If there are foreign objects, we do not know all the
# edges in the graph, and therefore cannot build a dependency graph or
# derive any evaluation order.
#
# An exception is raised if a foreign object matches multiple documents
# in the database. However, if a matching object is not yet saved, this
# exception may not be raised.
loop do
progress_made = false
objects.delete_if do |id,object|
begin
resolve_foreign_keys(object, object_id_to_database_id)
resolve_foreign_objects(object, object_id_to_database_id)
progress_made = true
database_id = import_object(object)
object_id_to_database_id[id] = database_id
object_id_to_database_id[database_id] = database_id
rescue Pupa::Errors::MissingDatabaseIdError
false
end
end
break if objects.empty? || !progress_made
end
unless objects.empty?
raise Errors::UnprocessableEntity, "couldn't resolve #{objects.size}/#{size} objects:\n #{objects.values.map{|object| JSON.dump(object.foreign_properties)}.join("\n ")}"
end
end
# Ensure that fingerprints uniquely identified objects.
counts = {}
object_id_to_database_id.each do |object_id,database_id|
unless object_id == database_id
(counts[database_id] ||= []) << object_id
end
end
duplicates = counts.select do |_,object_ids|
object_ids.size > 1
end
unless duplicates.empty?
raise Errors::DuplicateDocumentError, "multiple objects written to same document:\n" + duplicates.map{|database_id,object_ids| " #{database_id} <- #{object_ids.join(' ')}"}.join("\n")
end
end | [
"def",
"import",
"@report",
"[",
":import",
"]",
"=",
"{",
"}",
"objects",
"=",
"deduplicate",
"(",
"load_scraped_objects",
")",
"object_id_to_database_id",
"=",
"{",
"}",
"if",
"use_dependency_graph?",
"(",
"objects",
")",
"dependency_graph",
"=",
"build_dependen... | Saves scraped objects to a database.
@raises [TSort::Cyclic] if the dependency graph is cyclic
@raises [Pupa::Errors::UnprocessableEntity] if an object's foreign keys or
foreign objects cannot be resolved
@raises [Pupa::Errors::DuplicateDocumentError] if duplicate objects were
inadvertently saved to the database | [
"Saves",
"scraped",
"objects",
"to",
"a",
"database",
"."
] | cb1485a42c1ee1a81cdf113a3199ad2993a45db1 | https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/processor.rb#L130-L198 | valid |
jpmckinney/pupa-ruby | lib/pupa/processor.rb | Pupa.Processor.dump_scraped_object | def dump_scraped_object(object)
type = object.class.to_s.demodulize.underscore
name = "#{type}_#{object._id.gsub(File::SEPARATOR, '_')}.json"
if @store.write_unless_exists(name, object.to_h)
info {"save #{type} #{object.to_s} as #{name}"}
else
raise Errors::DuplicateObjectIdError, "duplicate object ID: #{object._id} (was the same objected yielded twice?)"
end
if @validate
begin
object.validate!
rescue JSON::Schema::ValidationError => e
warn {e.message}
end
end
end | ruby | def dump_scraped_object(object)
type = object.class.to_s.demodulize.underscore
name = "#{type}_#{object._id.gsub(File::SEPARATOR, '_')}.json"
if @store.write_unless_exists(name, object.to_h)
info {"save #{type} #{object.to_s} as #{name}"}
else
raise Errors::DuplicateObjectIdError, "duplicate object ID: #{object._id} (was the same objected yielded twice?)"
end
if @validate
begin
object.validate!
rescue JSON::Schema::ValidationError => e
warn {e.message}
end
end
end | [
"def",
"dump_scraped_object",
"(",
"object",
")",
"type",
"=",
"object",
".",
"class",
".",
"to_s",
".",
"demodulize",
".",
"underscore",
"name",
"=",
"\"#{type}_#{object._id.gsub(File::SEPARATOR, '_')}.json\"",
"if",
"@store",
".",
"write_unless_exists",
"(",
"name",... | Dumps an scraped object to disk.
@param [Object] object an scraped object
@raises [Pupa::Errors::DuplicateObjectIdError] | [
"Dumps",
"an",
"scraped",
"object",
"to",
"disk",
"."
] | cb1485a42c1ee1a81cdf113a3199ad2993a45db1 | https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/processor.rb#L219-L236 | valid |
jpmckinney/pupa-ruby | lib/pupa/processor.rb | Pupa.Processor.load_scraped_objects | def load_scraped_objects
{}.tap do |objects|
@store.read_multi(@store.entries).each do |properties|
object = load_scraped_object(properties)
objects[object._id] = object
end
end
end | ruby | def load_scraped_objects
{}.tap do |objects|
@store.read_multi(@store.entries).each do |properties|
object = load_scraped_object(properties)
objects[object._id] = object
end
end
end | [
"def",
"load_scraped_objects",
"{",
"}",
".",
"tap",
"do",
"|",
"objects",
"|",
"@store",
".",
"read_multi",
"(",
"@store",
".",
"entries",
")",
".",
"each",
"do",
"|",
"properties",
"|",
"object",
"=",
"load_scraped_object",
"(",
"properties",
")",
"objec... | Loads scraped objects from disk.
@return [Hash] a hash of scraped objects keyed by ID | [
"Loads",
"scraped",
"objects",
"from",
"disk",
"."
] | cb1485a42c1ee1a81cdf113a3199ad2993a45db1 | https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/processor.rb#L241-L248 | valid |
jpmckinney/pupa-ruby | lib/pupa/processor.rb | Pupa.Processor.load_scraped_object | def load_scraped_object(properties)
type = properties['_type'] || properties[:_type]
if type
type.camelize.constantize.new(properties)
else
raise Errors::MissingObjectTypeError, "missing _type: #{JSON.dump(properties)}"
end
end | ruby | def load_scraped_object(properties)
type = properties['_type'] || properties[:_type]
if type
type.camelize.constantize.new(properties)
else
raise Errors::MissingObjectTypeError, "missing _type: #{JSON.dump(properties)}"
end
end | [
"def",
"load_scraped_object",
"(",
"properties",
")",
"type",
"=",
"properties",
"[",
"'_type'",
"]",
"||",
"properties",
"[",
":_type",
"]",
"if",
"type",
"type",
".",
"camelize",
".",
"constantize",
".",
"new",
"(",
"properties",
")",
"else",
"raise",
"E... | Loads a scraped object from its properties.
@param [Hash] properties the object's properties
@return [Object] a scraped object
@raises [Pupa::Errors::MissingObjectTypeError] if the scraped object is
missing a `_type` property. | [
"Loads",
"a",
"scraped",
"object",
"from",
"its",
"properties",
"."
] | cb1485a42c1ee1a81cdf113a3199ad2993a45db1 | https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/processor.rb#L256-L263 | valid |
jpmckinney/pupa-ruby | lib/pupa/processor.rb | Pupa.Processor.deduplicate | def deduplicate(objects)
losers_to_winners = build_losers_to_winners_map(objects)
# Remove all losers.
losers_to_winners.each_key do |key|
objects.delete(key)
end
# Swap the IDs of losers for the IDs of winners.
objects.each do |id,object|
object.foreign_keys.each do |property|
value = object[property]
if value && losers_to_winners.key?(value)
object[property] = losers_to_winners[value]
end
end
end
objects
end | ruby | def deduplicate(objects)
losers_to_winners = build_losers_to_winners_map(objects)
# Remove all losers.
losers_to_winners.each_key do |key|
objects.delete(key)
end
# Swap the IDs of losers for the IDs of winners.
objects.each do |id,object|
object.foreign_keys.each do |property|
value = object[property]
if value && losers_to_winners.key?(value)
object[property] = losers_to_winners[value]
end
end
end
objects
end | [
"def",
"deduplicate",
"(",
"objects",
")",
"losers_to_winners",
"=",
"build_losers_to_winners_map",
"(",
"objects",
")",
"losers_to_winners",
".",
"each_key",
"do",
"|",
"key",
"|",
"objects",
".",
"delete",
"(",
"key",
")",
"end",
"objects",
".",
"each",
"do"... | Removes all duplicate objects and re-assigns any foreign keys.
@param [Hash] objects a hash of scraped objects keyed by ID
@return [Hash] the objects without duplicates | [
"Removes",
"all",
"duplicate",
"objects",
"and",
"re",
"-",
"assigns",
"any",
"foreign",
"keys",
"."
] | cb1485a42c1ee1a81cdf113a3199ad2993a45db1 | https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/processor.rb#L269-L288 | valid |
jpmckinney/pupa-ruby | lib/pupa/processor.rb | Pupa.Processor.build_losers_to_winners_map | def build_losers_to_winners_map(objects)
inverse = {}
objects.each do |id,object|
(inverse[object.to_h.except(:_id)] ||= []) << id
end
{}.tap do |map|
inverse.values.each do |ids|
ids.drop(1).each do |id|
map[id] = ids[0]
end
end
end
end | ruby | def build_losers_to_winners_map(objects)
inverse = {}
objects.each do |id,object|
(inverse[object.to_h.except(:_id)] ||= []) << id
end
{}.tap do |map|
inverse.values.each do |ids|
ids.drop(1).each do |id|
map[id] = ids[0]
end
end
end
end | [
"def",
"build_losers_to_winners_map",
"(",
"objects",
")",
"inverse",
"=",
"{",
"}",
"objects",
".",
"each",
"do",
"|",
"id",
",",
"object",
"|",
"(",
"inverse",
"[",
"object",
".",
"to_h",
".",
"except",
"(",
":_id",
")",
"]",
"||=",
"[",
"]",
")",
... | For each object, map its ID to the ID of its duplicate, if any.
@param [Hash] objects a hash of scraped objects keyed by ID
@return [Hash] a mapping from an object ID to the ID of its duplicate | [
"For",
"each",
"object",
"map",
"its",
"ID",
"to",
"the",
"ID",
"of",
"its",
"duplicate",
"if",
"any",
"."
] | cb1485a42c1ee1a81cdf113a3199ad2993a45db1 | https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/processor.rb#L294-L307 | valid |
jpmckinney/pupa-ruby | lib/pupa/processor.rb | Pupa.Processor.use_dependency_graph? | def use_dependency_graph?(objects)
objects.each do |id,object|
object.foreign_objects.each do |property|
if object[property].present?
return false
end
end
end
true
end | ruby | def use_dependency_graph?(objects)
objects.each do |id,object|
object.foreign_objects.each do |property|
if object[property].present?
return false
end
end
end
true
end | [
"def",
"use_dependency_graph?",
"(",
"objects",
")",
"objects",
".",
"each",
"do",
"|",
"id",
",",
"object",
"|",
"object",
".",
"foreign_objects",
".",
"each",
"do",
"|",
"property",
"|",
"if",
"object",
"[",
"property",
"]",
".",
"present?",
"return",
... | If any objects have unresolved foreign objects, we cannot derive an
evaluation order using a dependency graph.
@param [Hash] objects a hash of scraped objects keyed by ID
@return [Boolean] whether a dependency graph can be used to derive an
evaluation order | [
"If",
"any",
"objects",
"have",
"unresolved",
"foreign",
"objects",
"we",
"cannot",
"derive",
"an",
"evaluation",
"order",
"using",
"a",
"dependency",
"graph",
"."
] | cb1485a42c1ee1a81cdf113a3199ad2993a45db1 | https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/processor.rb#L315-L324 | valid |
jpmckinney/pupa-ruby | lib/pupa/processor.rb | Pupa.Processor.build_dependency_graph | def build_dependency_graph(objects)
DependencyGraph.new.tap do |graph|
objects.each do |id,object|
graph[id] = [] # no duplicate IDs
object.foreign_keys.each do |property|
value = object[property]
if value
graph[id] << value
end
end
end
end
end | ruby | def build_dependency_graph(objects)
DependencyGraph.new.tap do |graph|
objects.each do |id,object|
graph[id] = [] # no duplicate IDs
object.foreign_keys.each do |property|
value = object[property]
if value
graph[id] << value
end
end
end
end
end | [
"def",
"build_dependency_graph",
"(",
"objects",
")",
"DependencyGraph",
".",
"new",
".",
"tap",
"do",
"|",
"graph",
"|",
"objects",
".",
"each",
"do",
"|",
"id",
",",
"object",
"|",
"graph",
"[",
"id",
"]",
"=",
"[",
"]",
"object",
".",
"foreign_keys"... | Builds a dependency graph.
@param [Hash] objects a hash of scraped objects keyed by ID
@return [DependencyGraph] the dependency graph | [
"Builds",
"a",
"dependency",
"graph",
"."
] | cb1485a42c1ee1a81cdf113a3199ad2993a45db1 | https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/processor.rb#L330-L342 | valid |
jpmckinney/pupa-ruby | lib/pupa/processor.rb | Pupa.Processor.resolve_foreign_keys | def resolve_foreign_keys(object, map)
object.foreign_keys.each do |property|
value = object[property]
if value
if map.key?(value)
object[property] = map[value]
else
raise Errors::MissingDatabaseIdError, "couldn't resolve foreign key: #{property} #{value}"
end
end
end
end | ruby | def resolve_foreign_keys(object, map)
object.foreign_keys.each do |property|
value = object[property]
if value
if map.key?(value)
object[property] = map[value]
else
raise Errors::MissingDatabaseIdError, "couldn't resolve foreign key: #{property} #{value}"
end
end
end
end | [
"def",
"resolve_foreign_keys",
"(",
"object",
",",
"map",
")",
"object",
".",
"foreign_keys",
".",
"each",
"do",
"|",
"property",
"|",
"value",
"=",
"object",
"[",
"property",
"]",
"if",
"value",
"if",
"map",
".",
"key?",
"(",
"value",
")",
"object",
"... | Resolves an object's foreign keys from object IDs to database IDs.
@param [Object] an object
@param [Hash] a map from object ID to database ID
@raises [Pupa::Errors::MissingDatabaseIdError] if a foreign key cannot be
resolved | [
"Resolves",
"an",
"object",
"s",
"foreign",
"keys",
"from",
"object",
"IDs",
"to",
"database",
"IDs",
"."
] | cb1485a42c1ee1a81cdf113a3199ad2993a45db1 | https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/processor.rb#L350-L361 | valid |
jpmckinney/pupa-ruby | lib/pupa/processor.rb | Pupa.Processor.resolve_foreign_objects | def resolve_foreign_objects(object, map)
object.foreign_objects.each do |property|
value = object[property]
if value.present?
foreign_object = ForeignObject.new(value)
resolve_foreign_keys(foreign_object, map)
document = connection.find(foreign_object.to_h)
if document
object["#{property}_id"] = document['_id']
else
raise Errors::MissingDatabaseIdError, "couldn't resolve foreign object: #{property} #{value}"
end
end
end
end | ruby | def resolve_foreign_objects(object, map)
object.foreign_objects.each do |property|
value = object[property]
if value.present?
foreign_object = ForeignObject.new(value)
resolve_foreign_keys(foreign_object, map)
document = connection.find(foreign_object.to_h)
if document
object["#{property}_id"] = document['_id']
else
raise Errors::MissingDatabaseIdError, "couldn't resolve foreign object: #{property} #{value}"
end
end
end
end | [
"def",
"resolve_foreign_objects",
"(",
"object",
",",
"map",
")",
"object",
".",
"foreign_objects",
".",
"each",
"do",
"|",
"property",
"|",
"value",
"=",
"object",
"[",
"property",
"]",
"if",
"value",
".",
"present?",
"foreign_object",
"=",
"ForeignObject",
... | Resolves an object's foreign objects to database IDs.
@param [Object] object an object
@param [Hash] a map from object ID to database ID
@raises [Pupa::Errors::MissingDatabaseIdError] if a foreign object cannot
be resolved | [
"Resolves",
"an",
"object",
"s",
"foreign",
"objects",
"to",
"database",
"IDs",
"."
] | cb1485a42c1ee1a81cdf113a3199ad2993a45db1 | https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/processor.rb#L369-L384 | valid |
jpmckinney/pupa-ruby | lib/pupa/runner.rb | Pupa.Runner.run | def run(args, overrides = {})
rest = opts.parse!(args)
@options = OpenStruct.new(options.to_h.merge(overrides))
if options.actions.empty?
options.actions = %w(scrape import)
end
if options.tasks.empty?
options.tasks = @processor_class.tasks
end
processor = @processor_class.new(options.output_dir,
pipelined: options.pipelined,
cache_dir: options.cache_dir,
expires_in: options.expires_in,
value_max_bytes: options.value_max_bytes,
memcached_username: options.memcached_username,
memcached_password: options.memcached_password,
database_url: options.database_url,
validate: options.validate,
level: options.level,
faraday_options: options.faraday_options,
options: Hash[*rest])
options.actions.each do |action|
unless action == 'scrape' || processor.respond_to?(action)
abort %(`#{action}` is not a #{opts.program_name} action. See `#{opts.program_name} --help` for a list of available actions.)
end
end
if %w(DEBUG INFO).include?(options.level)
puts "processor: #{@processor_class}"
puts "actions: #{options.actions.join(', ')}"
puts "tasks: #{options.tasks.join(', ')}"
end
if options.level == 'DEBUG'
%w(output_dir pipelined cache_dir expires_in value_max_bytes memcached_username memcached_password database_url validate level).each do |option|
puts "#{option}: #{options[option]}"
end
unless rest.empty?
puts "options: #{rest.join(' ')}"
end
end
exit if options.dry_run
report = {
plan: {
processor: @processor_class,
options: Marshal.load(Marshal.dump(options)).to_h,
arguments: rest,
},
start: Time.now.utc,
}
if options.actions.delete('scrape')
processor.store.clear
report[:scrape] = {}
options.tasks.each do |task_name|
report[:scrape][task_name] = processor.dump_scraped_objects(task_name)
end
end
options.actions.each do |action|
processor.send(action)
if processor.report.key?(action.to_sym)
report.update(action.to_sym => processor.report[action.to_sym])
end
end
if %w(DEBUG INFO).include?(options.level)
report[:end] = Time.now.utc
report[:time] = report[:end] - report[:start]
puts JSON.dump(report)
end
end | ruby | def run(args, overrides = {})
rest = opts.parse!(args)
@options = OpenStruct.new(options.to_h.merge(overrides))
if options.actions.empty?
options.actions = %w(scrape import)
end
if options.tasks.empty?
options.tasks = @processor_class.tasks
end
processor = @processor_class.new(options.output_dir,
pipelined: options.pipelined,
cache_dir: options.cache_dir,
expires_in: options.expires_in,
value_max_bytes: options.value_max_bytes,
memcached_username: options.memcached_username,
memcached_password: options.memcached_password,
database_url: options.database_url,
validate: options.validate,
level: options.level,
faraday_options: options.faraday_options,
options: Hash[*rest])
options.actions.each do |action|
unless action == 'scrape' || processor.respond_to?(action)
abort %(`#{action}` is not a #{opts.program_name} action. See `#{opts.program_name} --help` for a list of available actions.)
end
end
if %w(DEBUG INFO).include?(options.level)
puts "processor: #{@processor_class}"
puts "actions: #{options.actions.join(', ')}"
puts "tasks: #{options.tasks.join(', ')}"
end
if options.level == 'DEBUG'
%w(output_dir pipelined cache_dir expires_in value_max_bytes memcached_username memcached_password database_url validate level).each do |option|
puts "#{option}: #{options[option]}"
end
unless rest.empty?
puts "options: #{rest.join(' ')}"
end
end
exit if options.dry_run
report = {
plan: {
processor: @processor_class,
options: Marshal.load(Marshal.dump(options)).to_h,
arguments: rest,
},
start: Time.now.utc,
}
if options.actions.delete('scrape')
processor.store.clear
report[:scrape] = {}
options.tasks.each do |task_name|
report[:scrape][task_name] = processor.dump_scraped_objects(task_name)
end
end
options.actions.each do |action|
processor.send(action)
if processor.report.key?(action.to_sym)
report.update(action.to_sym => processor.report[action.to_sym])
end
end
if %w(DEBUG INFO).include?(options.level)
report[:end] = Time.now.utc
report[:time] = report[:end] - report[:start]
puts JSON.dump(report)
end
end | [
"def",
"run",
"(",
"args",
",",
"overrides",
"=",
"{",
"}",
")",
"rest",
"=",
"opts",
".",
"parse!",
"(",
"args",
")",
"@options",
"=",
"OpenStruct",
".",
"new",
"(",
"options",
".",
"to_h",
".",
"merge",
"(",
"overrides",
")",
")",
"if",
"options"... | Runs the action.
@example Run from a command-line script
runner.run(ARGV)
@example Override the command-line options
runner.run(ARGV, expires_in: 3600) # 1 hour
@param [Array] args command-line arguments
@param [Hash] overrides any overridden options | [
"Runs",
"the",
"action",
"."
] | cb1485a42c1ee1a81cdf113a3199ad2993a45db1 | https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/runner.rb#L145-L222 | valid |
jpmckinney/pupa-ruby | lib/pupa/models/vote_event.rb | Pupa.VoteEvent.add_group_result | def add_group_result(result, group: nil)
data = {result: result}
if group
data[:group] = group
end
if result.present?
@group_results << data
end
end | ruby | def add_group_result(result, group: nil)
data = {result: result}
if group
data[:group] = group
end
if result.present?
@group_results << data
end
end | [
"def",
"add_group_result",
"(",
"result",
",",
"group",
":",
"nil",
")",
"data",
"=",
"{",
"result",
":",
"result",
"}",
"if",
"group",
"data",
"[",
":group",
"]",
"=",
"group",
"end",
"if",
"result",
".",
"present?",
"@group_results",
"<<",
"data",
"e... | Adds a group result.
@param [String] result the result of the vote event within a group of voters
@param [String] group a group of voters | [
"Adds",
"a",
"group",
"result",
"."
] | cb1485a42c1ee1a81cdf113a3199ad2993a45db1 | https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/models/vote_event.rb#L47-L55 | valid |
jpmckinney/pupa-ruby | lib/pupa/models/vote_event.rb | Pupa.VoteEvent.add_count | def add_count(option, value, group: nil)
data = {option: option, value: value}
if group
data[:group] = group
end
if option.present? && value.present?
@counts << data
end
end | ruby | def add_count(option, value, group: nil)
data = {option: option, value: value}
if group
data[:group] = group
end
if option.present? && value.present?
@counts << data
end
end | [
"def",
"add_count",
"(",
"option",
",",
"value",
",",
"group",
":",
"nil",
")",
"data",
"=",
"{",
"option",
":",
"option",
",",
"value",
":",
"value",
"}",
"if",
"group",
"data",
"[",
":group",
"]",
"=",
"group",
"end",
"if",
"option",
".",
"presen... | Adds a count.
@param [String] option an option in a vote event
@param [String] value the number of votes for an option
@param [String] group a group of voters | [
"Adds",
"a",
"count",
"."
] | cb1485a42c1ee1a81cdf113a3199ad2993a45db1 | https://github.com/jpmckinney/pupa-ruby/blob/cb1485a42c1ee1a81cdf113a3199ad2993a45db1/lib/pupa/models/vote_event.rb#L62-L70 | valid |
thiagofelix/danger-jenkins | lib/jenkins/plugin.rb | Danger.DangerJenkins.print_artifacts | def print_artifacts
artifacts = build.artifacts
return if artifacts.empty?
content = "### Jenkins artifacts:\n\n"
content << "<img width='40' align='right' src='#{JENKINS_ICON}'></img>\n"
artifacts.each do |artifact|
content << "* #{artifact_link(artifact)}\n"
end
markdown content
end | ruby | def print_artifacts
artifacts = build.artifacts
return if artifacts.empty?
content = "### Jenkins artifacts:\n\n"
content << "<img width='40' align='right' src='#{JENKINS_ICON}'></img>\n"
artifacts.each do |artifact|
content << "* #{artifact_link(artifact)}\n"
end
markdown content
end | [
"def",
"print_artifacts",
"artifacts",
"=",
"build",
".",
"artifacts",
"return",
"if",
"artifacts",
".",
"empty?",
"content",
"=",
"\"### Jenkins artifacts:\\n\\n\"",
"content",
"<<",
"\"<img width='40' align='right' src='#{JENKINS_ICON}'></img>\\n\"",
"artifacts",
".",
"each... | Adds a list of artifacts to the danger comment
@return [void] | [
"Adds",
"a",
"list",
"of",
"artifacts",
"to",
"the",
"danger",
"comment"
] | 8c7f4f5517a3edc15dad151d9291c50de9d26cb4 | https://github.com/thiagofelix/danger-jenkins/blob/8c7f4f5517a3edc15dad151d9291c50de9d26cb4/lib/jenkins/plugin.rb#L77-L89 | valid |
dmacvicar/ruby-rpm-ffi | lib/rpm/transaction.rb | RPM.Transaction.delete | def delete(pkg)
iterator = case pkg
when Package
pkg[:sigmd5] ? each_match(:sigmd5, pkg[:sigmd5]) : each_match(:label, pkg[:label])
when String
each_match(:label, pkg)
when Dependency
each_match(:label, pkg.name).set_iterator_version(pkg.version)
else
raise TypeError, 'illegal argument type'
end
iterator.each do |header|
ret = RPM::C.rpmtsAddEraseElement(@ptr, header.ptr, iterator.offset)
raise "Error while adding erase/#{pkg} to transaction" if ret != 0
end
end | ruby | def delete(pkg)
iterator = case pkg
when Package
pkg[:sigmd5] ? each_match(:sigmd5, pkg[:sigmd5]) : each_match(:label, pkg[:label])
when String
each_match(:label, pkg)
when Dependency
each_match(:label, pkg.name).set_iterator_version(pkg.version)
else
raise TypeError, 'illegal argument type'
end
iterator.each do |header|
ret = RPM::C.rpmtsAddEraseElement(@ptr, header.ptr, iterator.offset)
raise "Error while adding erase/#{pkg} to transaction" if ret != 0
end
end | [
"def",
"delete",
"(",
"pkg",
")",
"iterator",
"=",
"case",
"pkg",
"when",
"Package",
"pkg",
"[",
":sigmd5",
"]",
"?",
"each_match",
"(",
":sigmd5",
",",
"pkg",
"[",
":sigmd5",
"]",
")",
":",
"each_match",
"(",
":label",
",",
"pkg",
"[",
":label",
"]"... | Add a delete operation to the transaction
@param [String, Package, Dependency] pkg Package to delete | [
"Add",
"a",
"delete",
"operation",
"to",
"the",
"transaction"
] | f5302d3717d3e2d489ebbd522a65447e3ccefa64 | https://github.com/dmacvicar/ruby-rpm-ffi/blob/f5302d3717d3e2d489ebbd522a65447e3ccefa64/lib/rpm/transaction.rb#L85-L101 | valid |
dmacvicar/ruby-rpm-ffi | lib/rpm/transaction.rb | RPM.Transaction.commit | def commit
flags = RPM::C::TransFlags[:none]
callback = proc do |hdr, type, amount, total, key_ptr, data_ignored|
key_id = key_ptr.address
key = @keys.include?(key_id) ? @keys[key_id] : nil
if block_given?
package = hdr.null? ? nil : Package.new(hdr)
data = CallbackData.new(type, key, package, amount, total)
yield(data)
else
RPM::C.rpmShowProgress(hdr, type, amount, total, key, data_ignored)
end
end
# We create a callback to pass to the C method and we
# call the user supplied callback from there
#
# The C callback expects you to return a file handle,
# We expect from the user to get a File, which we
# then convert to a file handle to return.
callback = proc do |hdr, type, amount, total, key_ptr, data_ignored|
key_id = key_ptr.address
key = @keys.include?(key_id) ? @keys[key_id] : nil
if block_given?
package = hdr.null? ? nil : Package.new(hdr)
data = CallbackData.new(type, key, package, amount, total)
ret = yield(data)
# For OPEN_FILE we need to do some type conversion
# for certain callback types we need to do some
case type
when :inst_open_file
# For :inst_open_file the user callback has to
# return the open file
unless ret.is_a?(::File)
raise TypeError, "illegal return value type #{ret.class}. Expected File."
end
fdt = RPM::C.fdDup(ret.to_i)
if fdt.null? || RPM::C.Ferror(fdt) != 0
raise "Can't use opened file #{data.key}: #{RPM::C.Fstrerror(fdt)}"
RPM::C.Fclose(fdt) unless fdt.nil?
else
fdt = RPM::C.fdLink(fdt)
@fdt = fdt
end
# return the (RPM type) file handle
fdt
when :inst_close_file
fdt = @fdt
RPM::C.Fclose(fdt)
@fdt = nil
else
ret
end
else
# No custom callback given, use the default to show progress
RPM::C.rpmShowProgress(hdr, type, amount, total, key, data_ignored)
end
end
rc = RPM::C.rpmtsSetNotifyCallback(@ptr, callback, nil)
raise "Can't set commit callback" if rc != 0
rc = RPM::C.rpmtsRun(@ptr, nil, :none)
raise "#{self}: #{RPM::C.rpmlogMessage}" if rc < 0
if rc > 0
ps = RPM::C.rpmtsProblems(@ptr)
psi = RPM::C.rpmpsInitIterator(ps)
while RPM::C.rpmpsNextIterator(psi) >= 0
problem = Problem.from_ptr(RPM::C.rpmpsGetProblem(psi))
STDERR.puts problem
end
RPM::C.rpmpsFree(ps)
end
end | ruby | def commit
flags = RPM::C::TransFlags[:none]
callback = proc do |hdr, type, amount, total, key_ptr, data_ignored|
key_id = key_ptr.address
key = @keys.include?(key_id) ? @keys[key_id] : nil
if block_given?
package = hdr.null? ? nil : Package.new(hdr)
data = CallbackData.new(type, key, package, amount, total)
yield(data)
else
RPM::C.rpmShowProgress(hdr, type, amount, total, key, data_ignored)
end
end
# We create a callback to pass to the C method and we
# call the user supplied callback from there
#
# The C callback expects you to return a file handle,
# We expect from the user to get a File, which we
# then convert to a file handle to return.
callback = proc do |hdr, type, amount, total, key_ptr, data_ignored|
key_id = key_ptr.address
key = @keys.include?(key_id) ? @keys[key_id] : nil
if block_given?
package = hdr.null? ? nil : Package.new(hdr)
data = CallbackData.new(type, key, package, amount, total)
ret = yield(data)
# For OPEN_FILE we need to do some type conversion
# for certain callback types we need to do some
case type
when :inst_open_file
# For :inst_open_file the user callback has to
# return the open file
unless ret.is_a?(::File)
raise TypeError, "illegal return value type #{ret.class}. Expected File."
end
fdt = RPM::C.fdDup(ret.to_i)
if fdt.null? || RPM::C.Ferror(fdt) != 0
raise "Can't use opened file #{data.key}: #{RPM::C.Fstrerror(fdt)}"
RPM::C.Fclose(fdt) unless fdt.nil?
else
fdt = RPM::C.fdLink(fdt)
@fdt = fdt
end
# return the (RPM type) file handle
fdt
when :inst_close_file
fdt = @fdt
RPM::C.Fclose(fdt)
@fdt = nil
else
ret
end
else
# No custom callback given, use the default to show progress
RPM::C.rpmShowProgress(hdr, type, amount, total, key, data_ignored)
end
end
rc = RPM::C.rpmtsSetNotifyCallback(@ptr, callback, nil)
raise "Can't set commit callback" if rc != 0
rc = RPM::C.rpmtsRun(@ptr, nil, :none)
raise "#{self}: #{RPM::C.rpmlogMessage}" if rc < 0
if rc > 0
ps = RPM::C.rpmtsProblems(@ptr)
psi = RPM::C.rpmpsInitIterator(ps)
while RPM::C.rpmpsNextIterator(psi) >= 0
problem = Problem.from_ptr(RPM::C.rpmpsGetProblem(psi))
STDERR.puts problem
end
RPM::C.rpmpsFree(ps)
end
end | [
"def",
"commit",
"flags",
"=",
"RPM",
"::",
"C",
"::",
"TransFlags",
"[",
":none",
"]",
"callback",
"=",
"proc",
"do",
"|",
"hdr",
",",
"type",
",",
"amount",
",",
"total",
",",
"key_ptr",
",",
"data_ignored",
"|",
"key_id",
"=",
"key_ptr",
".",
"add... | Performs the transaction.
@param [Number] flag Transaction flags, default +RPM::TRANS_FLAG_NONE+
@param [Number] filter Transaction filter, default +RPM::PROB_FILTER_NONE+
@example
transaction.commit
You can supply your own callback
@example
transaction.commit do |data|
end
end
@yield [CallbackData] sig Transaction progress | [
"Performs",
"the",
"transaction",
"."
] | f5302d3717d3e2d489ebbd522a65447e3ccefa64 | https://github.com/dmacvicar/ruby-rpm-ffi/blob/f5302d3717d3e2d489ebbd522a65447e3ccefa64/lib/rpm/transaction.rb#L166-L244 | valid |
shawn42/tmx | lib/tmx/objects.rb | Tmx.Objects.find | def find(params)
params = { type: params } if params.is_a?(String)
found_objects = find_all do |object|
params.any? {|key,value| object.send(key) == value.to_s }
end.compact
self.class.new found_objects
end | ruby | def find(params)
params = { type: params } if params.is_a?(String)
found_objects = find_all do |object|
params.any? {|key,value| object.send(key) == value.to_s }
end.compact
self.class.new found_objects
end | [
"def",
"find",
"(",
"params",
")",
"params",
"=",
"{",
"type",
":",
"params",
"}",
"if",
"params",
".",
"is_a?",
"(",
"String",
")",
"found_objects",
"=",
"find_all",
"do",
"|",
"object",
"|",
"params",
".",
"any?",
"{",
"|",
"key",
",",
"value",
"... | Allows finding by type or a specfied hash of parameters
@example Find all objects that have the type 'ground'
objects.find(:floor)
objects.find(type: 'floor')
@example Find all objects that have the name 'mushroom'
objects.find(name: "mushroom") | [
"Allows",
"finding",
"by",
"type",
"or",
"a",
"specfied",
"hash",
"of",
"parameters"
] | 9c1948e586781610b926b6019db21e0894118d33 | https://github.com/shawn42/tmx/blob/9c1948e586781610b926b6019db21e0894118d33/lib/tmx/objects.rb#L20-L28 | valid |
lzap/deacon | lib/deacon/random_generator.rb | Deacon.RandomGenerator.next_lfsr25 | def next_lfsr25(seed)
i = 1
i = (seed + 1) & MASK
raise ArgumentError, "Seed #{seed} out of bounds" if seed && i == 0
i = (seed + 1) & MASK while i == 0
i = (i >> 1) | ((i[0]^i[1]^i[2]^i[3]) << 0x18)
i = (i >> 1) | ((i[0]^i[1]^i[2]^i[3]) << 0x18) while i > MASK
i - 1
end | ruby | def next_lfsr25(seed)
i = 1
i = (seed + 1) & MASK
raise ArgumentError, "Seed #{seed} out of bounds" if seed && i == 0
i = (seed + 1) & MASK while i == 0
i = (i >> 1) | ((i[0]^i[1]^i[2]^i[3]) << 0x18)
i = (i >> 1) | ((i[0]^i[1]^i[2]^i[3]) << 0x18) while i > MASK
i - 1
end | [
"def",
"next_lfsr25",
"(",
"seed",
")",
"i",
"=",
"1",
"i",
"=",
"(",
"seed",
"+",
"1",
")",
"&",
"MASK",
"raise",
"ArgumentError",
",",
"\"Seed #{seed} out of bounds\"",
"if",
"seed",
"&&",
"i",
"==",
"0",
"i",
"=",
"(",
"seed",
"+",
"1",
")",
"&"... | Fibonacci linear feedback shift register with x^25 + x^24 + x^23 + x^22 + 1 poly | [
"Fibonacci",
"linear",
"feedback",
"shift",
"register",
"with",
"x^25",
"+",
"x^24",
"+",
"x^23",
"+",
"x^22",
"+",
"1",
"poly"
] | bf52b5e741bcbaacb4e34b0f24b5397ce2051a50 | https://github.com/lzap/deacon/blob/bf52b5e741bcbaacb4e34b0f24b5397ce2051a50/lib/deacon/random_generator.rb#L6-L14 | valid |
YorickPeterse/shebang | lib/shebang/command.rb | Shebang.Command.parse | def parse(argv = [])
@option_parser.parse!(argv)
options.each do |option|
if option.required? and !option.has_value?
Shebang.error("The -#{option.short} option is required")
end
end
return argv
end | ruby | def parse(argv = [])
@option_parser.parse!(argv)
options.each do |option|
if option.required? and !option.has_value?
Shebang.error("The -#{option.short} option is required")
end
end
return argv
end | [
"def",
"parse",
"(",
"argv",
"=",
"[",
"]",
")",
"@option_parser",
".",
"parse!",
"(",
"argv",
")",
"options",
".",
"each",
"do",
"|",
"option",
"|",
"if",
"option",
".",
"required?",
"and",
"!",
"option",
".",
"has_value?",
"Shebang",
".",
"error",
... | Creates a new instance of the command and sets up OptionParser.
@author Yorick Peterse
@since 0.1
Parses the command line arguments using OptionParser.
@author Yorick Peterse
@since 0.1
@param [Array] argv Array containing the command line arguments to parse.
@return [Array] argv Array containing all the command line arguments after
it has been processed. | [
"Creates",
"a",
"new",
"instance",
"of",
"the",
"command",
"and",
"sets",
"up",
"OptionParser",
"."
] | efea81648ac22016619780bc9859cbdddcc88ea3 | https://github.com/YorickPeterse/shebang/blob/efea81648ac22016619780bc9859cbdddcc88ea3/lib/shebang/command.rb#L186-L196 | valid |
YorickPeterse/shebang | lib/shebang/command.rb | Shebang.Command.option | def option(opt)
opt = opt.to_sym
options.each do |op|
if op.short === opt or op.long === opt
return op.value
end
end
end | ruby | def option(opt)
opt = opt.to_sym
options.each do |op|
if op.short === opt or op.long === opt
return op.value
end
end
end | [
"def",
"option",
"(",
"opt",
")",
"opt",
"=",
"opt",
".",
"to_sym",
"options",
".",
"each",
"do",
"|",
"op",
"|",
"if",
"op",
".",
"short",
"===",
"opt",
"or",
"op",
".",
"long",
"===",
"opt",
"return",
"op",
".",
"value",
"end",
"end",
"end"
] | Returns the value of a given option. The option can be specified using
either the short or long name.
@example
puts "Hello #{option(:name)}
@author Yorick Peterse
@since 0.1
@param [#to_sym] opt The name of the option.
@return [Mixed] | [
"Returns",
"the",
"value",
"of",
"a",
"given",
"option",
".",
"The",
"option",
"can",
"be",
"specified",
"using",
"either",
"the",
"short",
"or",
"long",
"name",
"."
] | efea81648ac22016619780bc9859cbdddcc88ea3 | https://github.com/YorickPeterse/shebang/blob/efea81648ac22016619780bc9859cbdddcc88ea3/lib/shebang/command.rb#L253-L261 | valid |
markquezada/fcs | lib/fcs/client.rb | FCS.Client.method_missing | def method_missing(method, *args, &block)
klass = class_for_api_command(method)
return klass.new(@socket).send(method, *args, &block) if klass
super(method, *args, &block)
end | ruby | def method_missing(method, *args, &block)
klass = class_for_api_command(method)
return klass.new(@socket).send(method, *args, &block) if klass
super(method, *args, &block)
end | [
"def",
"method_missing",
"(",
"method",
",",
"*",
"args",
",",
"&",
"block",
")",
"klass",
"=",
"class_for_api_command",
"(",
"method",
")",
"return",
"klass",
".",
"new",
"(",
"@socket",
")",
".",
"send",
"(",
"method",
",",
"*",
"args",
",",
"&",
"... | Delgate api call to Request | [
"Delgate",
"api",
"call",
"to",
"Request"
] | 500ff5bf43082d98a89a3bb0843056b76aa9e9c9 | https://github.com/markquezada/fcs/blob/500ff5bf43082d98a89a3bb0843056b76aa9e9c9/lib/fcs/client.rb#L32-L37 | valid |
seblindberg/ruby-linked | lib/linked/listable.rb | Linked.Listable.in_chain? | def in_chain?(other)
return false unless other.is_a? Listable
chain_head.equal? other.chain_head
end | ruby | def in_chain?(other)
return false unless other.is_a? Listable
chain_head.equal? other.chain_head
end | [
"def",
"in_chain?",
"(",
"other",
")",
"return",
"false",
"unless",
"other",
".",
"is_a?",
"Listable",
"chain_head",
".",
"equal?",
"other",
".",
"chain_head",
"end"
] | Check if this object is in a chain.
@param other [Object] the object to check.
@return [true] if this object is in the same chain as the given one.
@return [false] otherwise. | [
"Check",
"if",
"this",
"object",
"is",
"in",
"a",
"chain",
"."
] | ea4e7ee23a26db599b48b0e32c0c1ecf46adf682 | https://github.com/seblindberg/ruby-linked/blob/ea4e7ee23a26db599b48b0e32c0c1ecf46adf682/lib/linked/listable.rb#L126-L129 | valid |
seblindberg/ruby-linked | lib/linked/listable.rb | Linked.Listable.before | def before
return to_enum(__callee__) unless block_given?
return if chain_head?
item = prev
loop do
yield item
item = item.prev
end
end | ruby | def before
return to_enum(__callee__) unless block_given?
return if chain_head?
item = prev
loop do
yield item
item = item.prev
end
end | [
"def",
"before",
"return",
"to_enum",
"(",
"__callee__",
")",
"unless",
"block_given?",
"return",
"if",
"chain_head?",
"item",
"=",
"prev",
"loop",
"do",
"yield",
"item",
"item",
"=",
"item",
".",
"prev",
"end",
"end"
] | Iterates over each item before this, in reverse order. If a block is not
given an enumerator is returned.
Note that raising a StopIteraion inside the block will cause the loop to
silently stop the iteration early. | [
"Iterates",
"over",
"each",
"item",
"before",
"this",
"in",
"reverse",
"order",
".",
"If",
"a",
"block",
"is",
"not",
"given",
"an",
"enumerator",
"is",
"returned",
"."
] | ea4e7ee23a26db599b48b0e32c0c1ecf46adf682 | https://github.com/seblindberg/ruby-linked/blob/ea4e7ee23a26db599b48b0e32c0c1ecf46adf682/lib/linked/listable.rb#L173-L183 | valid |
seblindberg/ruby-linked | lib/linked/listable.rb | Linked.Listable.after | def after
return to_enum(__callee__) unless block_given?
return if chain_tail?
item = self.next
loop do
yield item
item = item.next
end
end | ruby | def after
return to_enum(__callee__) unless block_given?
return if chain_tail?
item = self.next
loop do
yield item
item = item.next
end
end | [
"def",
"after",
"return",
"to_enum",
"(",
"__callee__",
")",
"unless",
"block_given?",
"return",
"if",
"chain_tail?",
"item",
"=",
"self",
".",
"next",
"loop",
"do",
"yield",
"item",
"item",
"=",
"item",
".",
"next",
"end",
"end"
] | Iterates over each item after this. If a block is not given an enumerator
is returned.
Note that raising a StopIteraion inside the block will cause the loop to
silently stop the iteration early. | [
"Iterates",
"over",
"each",
"item",
"after",
"this",
".",
"If",
"a",
"block",
"is",
"not",
"given",
"an",
"enumerator",
"is",
"returned",
"."
] | ea4e7ee23a26db599b48b0e32c0c1ecf46adf682 | https://github.com/seblindberg/ruby-linked/blob/ea4e7ee23a26db599b48b0e32c0c1ecf46adf682/lib/linked/listable.rb#L190-L200 | valid |
berkes/bitkassa | lib/bitkassa/payment_result.rb | Bitkassa.PaymentResult.valid? | def valid?
return false if raw_payload.nil? || raw_payload.empty?
return false if raw_authentication.nil? || raw_authentication.empty?
return false unless json_valid?
Authentication.valid?(raw_authentication, json_payload)
end | ruby | def valid?
return false if raw_payload.nil? || raw_payload.empty?
return false if raw_authentication.nil? || raw_authentication.empty?
return false unless json_valid?
Authentication.valid?(raw_authentication, json_payload)
end | [
"def",
"valid?",
"return",
"false",
"if",
"raw_payload",
".",
"nil?",
"||",
"raw_payload",
".",
"empty?",
"return",
"false",
"if",
"raw_authentication",
".",
"nil?",
"||",
"raw_authentication",
".",
"empty?",
"return",
"false",
"unless",
"json_valid?",
"Authentica... | Wether or not this payment result can be considered valid.
Authentication is checked, payload and authentication should be available
and the decoded JSON should be valid JSON.
When the result is valid, it is safe to assume no-one tampered with it
and that it was sent by Bitkassa. | [
"Wether",
"or",
"not",
"this",
"payment",
"result",
"can",
"be",
"considered",
"valid",
".",
"Authentication",
"is",
"checked",
"payload",
"and",
"authentication",
"should",
"be",
"available",
"and",
"the",
"decoded",
"JSON",
"should",
"be",
"valid",
"JSON",
"... | ba51277d2d542840d3411f981e3846fb13c7dd23 | https://github.com/berkes/bitkassa/blob/ba51277d2d542840d3411f981e3846fb13c7dd23/lib/bitkassa/payment_result.rb#L52-L58 | valid |
lasseebert/incremental_backup | lib/incremental_backup/task.rb | IncrementalBackup.Task.run | def run
# Validate - this will throw an exception if settings are not valid
validate_settings
# Run everything inside a lock, ensuring that only one instance of this
# task is running.
Lock.create(self) do
# Find the schedule to run
schedule = find_schedule
unless schedule
logger.info "No backup needed - exiting"
return
end
logger.info "Starting #{schedule} backup to #{settings.remote_server}"
# Paths and other options
timestamp = Time.now.strftime('backup_%Y-%m-%d-T%H-%M-%S')
current_path = File.join(settings.remote_path, 'current')
progress_path = File.join(settings.remote_path, 'incomplete')
complete_path = File.join(schedule_path(schedule), timestamp)
login = "#{settings.remote_user}@#{settings.remote_server}"
rsync_path = "#{login}:#{progress_path}"
# Make schedule folder
execute_ssh "mkdir --verbose --parents #{schedule_path schedule}"
# Rsync
Rsync.execute(logger, settings.local_path, rsync_path, {
exclude_file: settings.exclude_file,
link_dest: current_path,
max_upload_speed: settings.max_upload_speed,
max_download_speed: settings.max_download_speed
})
# shuffle backups around
logger.info "Do the backup shuffle"
execute_ssh [
"mv --verbose #{progress_path} #{complete_path}",
"rm --verbose --force #{current_path}",
"ln --verbose --symbolic #{complete_path} #{current_path}",
]
delete_old_backups schedule
logger.info "#{schedule} backup done"
end
rescue Exception => exception
logger.error exception.message
logger.error exception.backtrace
end | ruby | def run
# Validate - this will throw an exception if settings are not valid
validate_settings
# Run everything inside a lock, ensuring that only one instance of this
# task is running.
Lock.create(self) do
# Find the schedule to run
schedule = find_schedule
unless schedule
logger.info "No backup needed - exiting"
return
end
logger.info "Starting #{schedule} backup to #{settings.remote_server}"
# Paths and other options
timestamp = Time.now.strftime('backup_%Y-%m-%d-T%H-%M-%S')
current_path = File.join(settings.remote_path, 'current')
progress_path = File.join(settings.remote_path, 'incomplete')
complete_path = File.join(schedule_path(schedule), timestamp)
login = "#{settings.remote_user}@#{settings.remote_server}"
rsync_path = "#{login}:#{progress_path}"
# Make schedule folder
execute_ssh "mkdir --verbose --parents #{schedule_path schedule}"
# Rsync
Rsync.execute(logger, settings.local_path, rsync_path, {
exclude_file: settings.exclude_file,
link_dest: current_path,
max_upload_speed: settings.max_upload_speed,
max_download_speed: settings.max_download_speed
})
# shuffle backups around
logger.info "Do the backup shuffle"
execute_ssh [
"mv --verbose #{progress_path} #{complete_path}",
"rm --verbose --force #{current_path}",
"ln --verbose --symbolic #{complete_path} #{current_path}",
]
delete_old_backups schedule
logger.info "#{schedule} backup done"
end
rescue Exception => exception
logger.error exception.message
logger.error exception.backtrace
end | [
"def",
"run",
"validate_settings",
"Lock",
".",
"create",
"(",
"self",
")",
"do",
"schedule",
"=",
"find_schedule",
"unless",
"schedule",
"logger",
".",
"info",
"\"No backup needed - exiting\"",
"return",
"end",
"logger",
".",
"info",
"\"Starting #{schedule} backup to... | Perform the backup | [
"Perform",
"the",
"backup"
] | afa50dd612e1a34d23fc346b705c77b2eecc0ddb | https://github.com/lasseebert/incremental_backup/blob/afa50dd612e1a34d23fc346b705c77b2eecc0ddb/lib/incremental_backup/task.rb#L18-L71 | valid |
lasseebert/incremental_backup | lib/incremental_backup/task.rb | IncrementalBackup.Task.execute_ssh | def execute_ssh(commands)
commands = [commands] unless commands.is_a? Array
result = ""
Net::SSH.start settings.remote_server, settings.remote_user do |ssh|
commands.each do |command|
was_error = false
logger.info "ssh: #{command}"
ssh.exec! command do |channel, stream, data|
case stream
when :stdout
logger.info data
result += "#{data}\n" unless data.empty?
when :stderr
logger.error data
was_error = true
end
end
throw "Exception during ssh, look in log file" if was_error
end
end
result
end | ruby | def execute_ssh(commands)
commands = [commands] unless commands.is_a? Array
result = ""
Net::SSH.start settings.remote_server, settings.remote_user do |ssh|
commands.each do |command|
was_error = false
logger.info "ssh: #{command}"
ssh.exec! command do |channel, stream, data|
case stream
when :stdout
logger.info data
result += "#{data}\n" unless data.empty?
when :stderr
logger.error data
was_error = true
end
end
throw "Exception during ssh, look in log file" if was_error
end
end
result
end | [
"def",
"execute_ssh",
"(",
"commands",
")",
"commands",
"=",
"[",
"commands",
"]",
"unless",
"commands",
".",
"is_a?",
"Array",
"result",
"=",
"\"\"",
"Net",
"::",
"SSH",
".",
"start",
"settings",
".",
"remote_server",
",",
"settings",
".",
"remote_user",
... | Runs one ore more commands remotely via ssh | [
"Runs",
"one",
"ore",
"more",
"commands",
"remotely",
"via",
"ssh"
] | afa50dd612e1a34d23fc346b705c77b2eecc0ddb | https://github.com/lasseebert/incremental_backup/blob/afa50dd612e1a34d23fc346b705c77b2eecc0ddb/lib/incremental_backup/task.rb#L118-L139 | valid |
lasseebert/incremental_backup | lib/incremental_backup/task.rb | IncrementalBackup.Task.find_schedule | def find_schedule
minutes = {
# If a cron job is run hourly it can be off by a couple of seconds
# from the last run. Set hourly to 58 minutes
hourly: 58,
daily: 24*60,
weekly: 7*24*60,
monthly: 30*24*60,
yearly: 365*24*60
}
now = DateTime.now
[:yearly, :monthly, :weekly, :daily, :hourly].each do |schedule|
next if backups_to_keep(schedule) <= 0
list = list_backup_dir schedule
date = list.map { |path| parse_backup_dir_name path, now.offset }.max
return schedule if !date || (now - date) * 24 * 60 >= minutes[schedule]
end
nil
end | ruby | def find_schedule
minutes = {
# If a cron job is run hourly it can be off by a couple of seconds
# from the last run. Set hourly to 58 minutes
hourly: 58,
daily: 24*60,
weekly: 7*24*60,
monthly: 30*24*60,
yearly: 365*24*60
}
now = DateTime.now
[:yearly, :monthly, :weekly, :daily, :hourly].each do |schedule|
next if backups_to_keep(schedule) <= 0
list = list_backup_dir schedule
date = list.map { |path| parse_backup_dir_name path, now.offset }.max
return schedule if !date || (now - date) * 24 * 60 >= minutes[schedule]
end
nil
end | [
"def",
"find_schedule",
"minutes",
"=",
"{",
"hourly",
":",
"58",
",",
"daily",
":",
"24",
"*",
"60",
",",
"weekly",
":",
"7",
"*",
"24",
"*",
"60",
",",
"monthly",
":",
"30",
"*",
"24",
"*",
"60",
",",
"yearly",
":",
"365",
"*",
"24",
"*",
"... | Find out which schedule to run | [
"Find",
"out",
"which",
"schedule",
"to",
"run"
] | afa50dd612e1a34d23fc346b705c77b2eecc0ddb | https://github.com/lasseebert/incremental_backup/blob/afa50dd612e1a34d23fc346b705c77b2eecc0ddb/lib/incremental_backup/task.rb#L142-L162 | valid |
berkes/bitkassa | lib/bitkassa/config.rb | Bitkassa.Config.debug= | def debug=(mode)
@debug = mode
if mode
HTTPI.log = true
HTTPI.log_level = :debug
else
HTTPI.log = false
end
end | ruby | def debug=(mode)
@debug = mode
if mode
HTTPI.log = true
HTTPI.log_level = :debug
else
HTTPI.log = false
end
end | [
"def",
"debug",
"=",
"(",
"mode",
")",
"@debug",
"=",
"mode",
"if",
"mode",
"HTTPI",
".",
"log",
"=",
"true",
"HTTPI",
".",
"log_level",
"=",
":debug",
"else",
"HTTPI",
".",
"log",
"=",
"false",
"end",
"end"
] | Sets defaults for the configuration.
Enable or disable debug mode. Boolean. | [
"Sets",
"defaults",
"for",
"the",
"configuration",
".",
"Enable",
"or",
"disable",
"debug",
"mode",
".",
"Boolean",
"."
] | ba51277d2d542840d3411f981e3846fb13c7dd23 | https://github.com/berkes/bitkassa/blob/ba51277d2d542840d3411f981e3846fb13c7dd23/lib/bitkassa/config.rb#L24-L33 | valid |
YorickPeterse/shebang | lib/shebang/option.rb | Shebang.Option.option_parser | def option_parser
params = ["-#{@short}", "--#{@long}", nil, @options[:type]]
if !@description.nil? and !@description.empty?
params[2] = @description
end
# Set the correct format for the long/short option based on the type.
if ![TrueClass, FalseClass].include?(@options[:type])
params[1] += " #{@options[:key]}"
end
return params
end | ruby | def option_parser
params = ["-#{@short}", "--#{@long}", nil, @options[:type]]
if !@description.nil? and !@description.empty?
params[2] = @description
end
# Set the correct format for the long/short option based on the type.
if ![TrueClass, FalseClass].include?(@options[:type])
params[1] += " #{@options[:key]}"
end
return params
end | [
"def",
"option_parser",
"params",
"=",
"[",
"\"-#{@short}\"",
",",
"\"--#{@long}\"",
",",
"nil",
",",
"@options",
"[",
":type",
"]",
"]",
"if",
"!",
"@description",
".",
"nil?",
"and",
"!",
"@description",
".",
"empty?",
"params",
"[",
"2",
"]",
"=",
"@d... | Creates a new instance of the Option class.
@author Yorick Peterse
@since 0.1
@param [#to_sym] short The short option name such as :h.
@param [#to_sym] long The long option name such as :help.
@param [String] desc The description of the option.
@param [Hash] options Hash containing various configuration options for
the OptionParser option.
@option options :type The type of value for the option, set to TrueClass
by default.
@option options :key The key to use to indicate a value whenever the type
of an option is something else than TrueClass or FalseClass. This option
is set to "VALUE" by default.
@option options :method A symbol that refers to a method that should be
called whenever the option is specified.
@option options :required Indicates that the option has to be specified.
@option options :default The default value of the option.
Builds an array containing all the required parameters for
OptionParser#on().
@author Yorick Peterse
@since 0.1
@return [Array] | [
"Creates",
"a",
"new",
"instance",
"of",
"the",
"Option",
"class",
"."
] | efea81648ac22016619780bc9859cbdddcc88ea3 | https://github.com/YorickPeterse/shebang/blob/efea81648ac22016619780bc9859cbdddcc88ea3/lib/shebang/option.rb#L54-L67 | valid |
seblindberg/ruby-linked | lib/linked/list.rb | Linked.List.shift | def shift
return nil if empty?
if list_head.last?
@_chain.tap { @_chain = nil }
else
old_head = list_head
@_chain = list_head.next
old_head.delete
end
end | ruby | def shift
return nil if empty?
if list_head.last?
@_chain.tap { @_chain = nil }
else
old_head = list_head
@_chain = list_head.next
old_head.delete
end
end | [
"def",
"shift",
"return",
"nil",
"if",
"empty?",
"if",
"list_head",
".",
"last?",
"@_chain",
".",
"tap",
"{",
"@_chain",
"=",
"nil",
"}",
"else",
"old_head",
"=",
"list_head",
"@_chain",
"=",
"list_head",
".",
"next",
"old_head",
".",
"delete",
"end",
"e... | Shift the first item off the list.
@return [Listable, nil] the first item in the list, or nil if the list is
empty. | [
"Shift",
"the",
"first",
"item",
"off",
"the",
"list",
"."
] | ea4e7ee23a26db599b48b0e32c0c1ecf46adf682 | https://github.com/seblindberg/ruby-linked/blob/ea4e7ee23a26db599b48b0e32c0c1ecf46adf682/lib/linked/list.rb#L114-L124 | valid |
PGSSoft/GoldenRose | lib/golden_rose/results_filterer.rb | GoldenRose.ResultsFilterer.compact_results | def compact_results(items)
items.map do |subtest|
subtests = subtest[:subtests]
if subtests.size > 1
subtests
elsif subtests.size == 1
compact_results(subtests)
end
end.flatten.compact
end | ruby | def compact_results(items)
items.map do |subtest|
subtests = subtest[:subtests]
if subtests.size > 1
subtests
elsif subtests.size == 1
compact_results(subtests)
end
end.flatten.compact
end | [
"def",
"compact_results",
"(",
"items",
")",
"items",
".",
"map",
"do",
"|",
"subtest",
"|",
"subtests",
"=",
"subtest",
"[",
":subtests",
"]",
"if",
"subtests",
".",
"size",
">",
"1",
"subtests",
"elsif",
"subtests",
".",
"size",
"==",
"1",
"compact_res... | This method simplify results structure,
it sets only one level of nesting
by leaving parents only with collection as child | [
"This",
"method",
"simplify",
"results",
"structure",
"it",
"sets",
"only",
"one",
"level",
"of",
"nesting",
"by",
"leaving",
"parents",
"only",
"with",
"collection",
"as",
"child"
] | c5af1e1968b77c89058a76ba30fc5533c34b1763 | https://github.com/PGSSoft/GoldenRose/blob/c5af1e1968b77c89058a76ba30fc5533c34b1763/lib/golden_rose/results_filterer.rb#L42-L51 | valid |
tconnolly/BnetApi | lib/bnet_api/wow.rb | BnetApi.WoW.pet_stats | def pet_stats(species_id, options = {})
level = options[:level] || 1
breedId = options[:breedId] || 3
qualityId = options[:qualityId] || 1
BnetApi.make_request_with_params("/wow/pet/stats/#{species_id}",
{
level: level,
breedId: breedId,
qualityId: qualityId }
)
end | ruby | def pet_stats(species_id, options = {})
level = options[:level] || 1
breedId = options[:breedId] || 3
qualityId = options[:qualityId] || 1
BnetApi.make_request_with_params("/wow/pet/stats/#{species_id}",
{
level: level,
breedId: breedId,
qualityId: qualityId }
)
end | [
"def",
"pet_stats",
"(",
"species_id",
",",
"options",
"=",
"{",
"}",
")",
"level",
"=",
"options",
"[",
":level",
"]",
"||",
"1",
"breedId",
"=",
"options",
"[",
":breedId",
"]",
"||",
"3",
"qualityId",
"=",
"options",
"[",
":qualityId",
"]",
"||",
... | Retrieves the stats for the pet with the specified ID.
@param species_id [Integer] The ID of the pet species.
@param options [Hash] Any additional options.
@option options [Integer] :level The level of the species.
@option options [Integer] :breedId The ID of the breed.
@option options [Integer] :qualityId The quality of the pet.
@return [Hash] A hash containing the pet stats data. | [
"Retrieves",
"the",
"stats",
"for",
"the",
"pet",
"with",
"the",
"specified",
"ID",
"."
] | 0d1c75822e1faafa8f148e0228371ebb04b24bfb | https://github.com/tconnolly/BnetApi/blob/0d1c75822e1faafa8f148e0228371ebb04b24bfb/lib/bnet_api/wow.rb#L112-L123 | valid |
tconnolly/BnetApi | lib/bnet_api/wow.rb | BnetApi.WoW.realm_status | def realm_status(*realms)
if realms.count > 0
BnetApi.make_request_with_params("/wow/realm/status", { realms: realms.join(',') })
else
BnetApi.make_request("/wow/realm/status")
end
end | ruby | def realm_status(*realms)
if realms.count > 0
BnetApi.make_request_with_params("/wow/realm/status", { realms: realms.join(',') })
else
BnetApi.make_request("/wow/realm/status")
end
end | [
"def",
"realm_status",
"(",
"*",
"realms",
")",
"if",
"realms",
".",
"count",
">",
"0",
"BnetApi",
".",
"make_request_with_params",
"(",
"\"/wow/realm/status\"",
",",
"{",
"realms",
":",
"realms",
".",
"join",
"(",
"','",
")",
"}",
")",
"else",
"BnetApi",
... | Retrieves the realm status for the region. If any realms are specified as parameters,
only the status of these realms will be returned.
@param *realms [Array<String>] Any realms to restrict the data to.
@return [Hash] A hash containing the realm status data. | [
"Retrieves",
"the",
"realm",
"status",
"for",
"the",
"region",
".",
"If",
"any",
"realms",
"are",
"specified",
"as",
"parameters",
"only",
"the",
"status",
"of",
"these",
"realms",
"will",
"be",
"returned",
"."
] | 0d1c75822e1faafa8f148e0228371ebb04b24bfb | https://github.com/tconnolly/BnetApi/blob/0d1c75822e1faafa8f148e0228371ebb04b24bfb/lib/bnet_api/wow.rb#L146-L152 | valid |
klaustopher/cloudmade | lib/cloudmade/tiles.rb | CloudMade.TilesService.get_tile | def get_tile(lat, lon, zoom, style_id = nil, tile_size = nil)
get_xy_tile(xtile(lon, zoom), ytile(lat, zoom), zoom, style_id, tile_size)
end | ruby | def get_tile(lat, lon, zoom, style_id = nil, tile_size = nil)
get_xy_tile(xtile(lon, zoom), ytile(lat, zoom), zoom, style_id, tile_size)
end | [
"def",
"get_tile",
"(",
"lat",
",",
"lon",
",",
"zoom",
",",
"style_id",
"=",
"nil",
",",
"tile_size",
"=",
"nil",
")",
"get_xy_tile",
"(",
"xtile",
"(",
"lon",
",",
"zoom",
")",
",",
"ytile",
"(",
"lat",
",",
"zoom",
")",
",",
"zoom",
",",
"styl... | Get tile with given latitude, longitude and zoom.
Returns Raw PNG data which could be saved to file
* +lat+ Latitude of requested tile
* +lon+ Longitude of requested tile
* +zoom+ Zoom level, on which tile is being requested
* +style_id+ CloudMade's style id, if not given, default style is used (usually 1)
* +tile_size+ size of tile, if not given the default 256 is used | [
"Get",
"tile",
"with",
"given",
"latitude",
"longitude",
"and",
"zoom",
".",
"Returns",
"Raw",
"PNG",
"data",
"which",
"could",
"be",
"saved",
"to",
"file"
] | 3d3554b6048970eed7d95af40e9055f003cdb1e1 | https://github.com/klaustopher/cloudmade/blob/3d3554b6048970eed7d95af40e9055f003cdb1e1/lib/cloudmade/tiles.rb#L84-L86 | valid |
klaustopher/cloudmade | lib/cloudmade/tiles.rb | CloudMade.TilesService.get_xy_tile | def get_xy_tile(xtile, ytile, zoom, style_id = nil, tile_size = nil)
style_id = self.default_style_id if style_id == nil
tile_size = self.default_tile_size if tile_size == nil
connect "/#{style_id}/#{tile_size}/#{zoom}/#{xtile}/#{ytile}.png"
end | ruby | def get_xy_tile(xtile, ytile, zoom, style_id = nil, tile_size = nil)
style_id = self.default_style_id if style_id == nil
tile_size = self.default_tile_size if tile_size == nil
connect "/#{style_id}/#{tile_size}/#{zoom}/#{xtile}/#{ytile}.png"
end | [
"def",
"get_xy_tile",
"(",
"xtile",
",",
"ytile",
",",
"zoom",
",",
"style_id",
"=",
"nil",
",",
"tile_size",
"=",
"nil",
")",
"style_id",
"=",
"self",
".",
"default_style_id",
"if",
"style_id",
"==",
"nil",
"tile_size",
"=",
"self",
".",
"default_tile_siz... | Get tile with given x, y numbers and zoom
Returns Raw PNG data which could be saved to file
* +xtile+
* +ytile+
* +zoom+ Zoom level, on which tile is being requested
* +style_id+ CloudMade's style id, if not given, default style is used (usually 1)
* +tile_size+ size of tile, if not given the default 256 is used | [
"Get",
"tile",
"with",
"given",
"x",
"y",
"numbers",
"and",
"zoom",
"Returns",
"Raw",
"PNG",
"data",
"which",
"could",
"be",
"saved",
"to",
"file"
] | 3d3554b6048970eed7d95af40e9055f003cdb1e1 | https://github.com/klaustopher/cloudmade/blob/3d3554b6048970eed7d95af40e9055f003cdb1e1/lib/cloudmade/tiles.rb#L96-L100 | valid |
seblindberg/ruby-linked | lib/linked/list_enumerable.rb | Linked.ListEnumerable.each_item | def each_item
return to_enum(__method__) { count } unless block_given?
return if empty?
item = list_head
loop do
yield item
item = item.next
end
end | ruby | def each_item
return to_enum(__method__) { count } unless block_given?
return if empty?
item = list_head
loop do
yield item
item = item.next
end
end | [
"def",
"each_item",
"return",
"to_enum",
"(",
"__method__",
")",
"{",
"count",
"}",
"unless",
"block_given?",
"return",
"if",
"empty?",
"item",
"=",
"list_head",
"loop",
"do",
"yield",
"item",
"item",
"=",
"item",
".",
"next",
"end",
"end"
] | Iterates over each item in the list If a block is not given an enumerator
is returned. | [
"Iterates",
"over",
"each",
"item",
"in",
"the",
"list",
"If",
"a",
"block",
"is",
"not",
"given",
"an",
"enumerator",
"is",
"returned",
"."
] | ea4e7ee23a26db599b48b0e32c0c1ecf46adf682 | https://github.com/seblindberg/ruby-linked/blob/ea4e7ee23a26db599b48b0e32c0c1ecf46adf682/lib/linked/list_enumerable.rb#L10-L19 | valid |
seblindberg/ruby-linked | lib/linked/list_enumerable.rb | Linked.ListEnumerable.reverse_each_item | def reverse_each_item
return to_enum(__method__) { count } unless block_given?
return if empty?
item = list_tail
loop do
yield item
item = item.prev
end
end | ruby | def reverse_each_item
return to_enum(__method__) { count } unless block_given?
return if empty?
item = list_tail
loop do
yield item
item = item.prev
end
end | [
"def",
"reverse_each_item",
"return",
"to_enum",
"(",
"__method__",
")",
"{",
"count",
"}",
"unless",
"block_given?",
"return",
"if",
"empty?",
"item",
"=",
"list_tail",
"loop",
"do",
"yield",
"item",
"item",
"=",
"item",
".",
"prev",
"end",
"end"
] | Iterates over each item in the list in reverse order. If a block is not
given an enumerator is returned.
@yield [Listable] each item in the list.
@return [Enumerable] if no block is given. | [
"Iterates",
"over",
"each",
"item",
"in",
"the",
"list",
"in",
"reverse",
"order",
".",
"If",
"a",
"block",
"is",
"not",
"given",
"an",
"enumerator",
"is",
"returned",
"."
] | ea4e7ee23a26db599b48b0e32c0c1ecf46adf682 | https://github.com/seblindberg/ruby-linked/blob/ea4e7ee23a26db599b48b0e32c0c1ecf46adf682/lib/linked/list_enumerable.rb#L28-L37 | valid |
ridiculous/duck_puncher | lib/duck_puncher/registration.rb | DuckPuncher.Registration.register | def register(target, *mods, &block)
options = mods.last.is_a?(Hash) ? mods.pop : {}
mods << Module.new(&block) if block
target = DuckPuncher.lookup_constant target
Ducks.list[target] = Set.new [] unless Ducks.list.key?(target)
mods = Array(mods).each do |mod|
duck = UniqueDuck.new Duck.new(target, mod, options)
Ducks.list[target] << duck
end
[target, *mods]
end | ruby | def register(target, *mods, &block)
options = mods.last.is_a?(Hash) ? mods.pop : {}
mods << Module.new(&block) if block
target = DuckPuncher.lookup_constant target
Ducks.list[target] = Set.new [] unless Ducks.list.key?(target)
mods = Array(mods).each do |mod|
duck = UniqueDuck.new Duck.new(target, mod, options)
Ducks.list[target] << duck
end
[target, *mods]
end | [
"def",
"register",
"(",
"target",
",",
"*",
"mods",
",",
"&",
"block",
")",
"options",
"=",
"mods",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"mods",
".",
"pop",
":",
"{",
"}",
"mods",
"<<",
"Module",
".",
"new",
"(",
"&",
"block",
")",... | Register an extension with a target class
When given a block, the block is used to create an anonymous module
@param target [Class,Module,Object] constant or instance to extend
@param mods [Array<Module>] modules to extend or mix into the target. The last argument can be a hash of options to customize the extension
@option :only [Symbol, Array<Symbol>] list of methods to extend onto the target (the module must have these defined)
@option :method [Symbol,String] the method used to apply the module, e.g. :extend (:include)
@option :before [Proc] A hook that is called with the target class before #punch
@option :after [Proc] A hook that is called with the target class after #punch | [
"Register",
"an",
"extension",
"with",
"a",
"target",
"class",
"When",
"given",
"a",
"block",
"the",
"block",
"is",
"used",
"to",
"create",
"an",
"anonymous",
"module"
] | 146753a42832dbcc2b006343c8360aaa302bd1db | https://github.com/ridiculous/duck_puncher/blob/146753a42832dbcc2b006343c8360aaa302bd1db/lib/duck_puncher/registration.rb#L12-L22 | valid |
ridiculous/duck_puncher | lib/duck_puncher/registration.rb | DuckPuncher.Registration.deregister | def deregister(*targets)
targets.each &Ducks.list.method(:delete)
targets.each &decorators.method(:delete)
end | ruby | def deregister(*targets)
targets.each &Ducks.list.method(:delete)
targets.each &decorators.method(:delete)
end | [
"def",
"deregister",
"(",
"*",
"targets",
")",
"targets",
".",
"each",
"&",
"Ducks",
".",
"list",
".",
"method",
"(",
":delete",
")",
"targets",
".",
"each",
"&",
"decorators",
".",
"method",
"(",
":delete",
")",
"end"
] | Remove extensions for a given class or list of classes | [
"Remove",
"extensions",
"for",
"a",
"given",
"class",
"or",
"list",
"of",
"classes"
] | 146753a42832dbcc2b006343c8360aaa302bd1db | https://github.com/ridiculous/duck_puncher/blob/146753a42832dbcc2b006343c8360aaa302bd1db/lib/duck_puncher/registration.rb#L32-L35 | valid |
hetznerZA/logstash_auditor | lib/logstash_auditor/auditor.rb | LogstashAuditor.LogstashAuditor.audit | def audit(audit_data)
request = create_request(audit_data)
http = create_http_transport
send_request_to_server(http, request)
end | ruby | def audit(audit_data)
request = create_request(audit_data)
http = create_http_transport
send_request_to_server(http, request)
end | [
"def",
"audit",
"(",
"audit_data",
")",
"request",
"=",
"create_request",
"(",
"audit_data",
")",
"http",
"=",
"create_http_transport",
"send_request_to_server",
"(",
"http",
",",
"request",
")",
"end"
] | inversion of control method required by the AuditorAPI | [
"inversion",
"of",
"control",
"method",
"required",
"by",
"the",
"AuditorAPI"
] | 584899dbaa451afbd45baee842d9aca58f5c4c33 | https://github.com/hetznerZA/logstash_auditor/blob/584899dbaa451afbd45baee842d9aca58f5c4c33/lib/logstash_auditor/auditor.rb#L19-L23 | valid |
knaveofdiamonds/sequel_migration_builder | lib/sequel/migration_builder.rb | Sequel.MigrationBuilder.generate_migration | def generate_migration(tables)
return if tables.empty? && @db_tables.empty?
result.clear
add_line "Sequel.migration do"
indent do
generate_migration_body(tables)
end
add_line "end\n"
result.join("\n")
end | ruby | def generate_migration(tables)
return if tables.empty? && @db_tables.empty?
result.clear
add_line "Sequel.migration do"
indent do
generate_migration_body(tables)
end
add_line "end\n"
result.join("\n")
end | [
"def",
"generate_migration",
"(",
"tables",
")",
"return",
"if",
"tables",
".",
"empty?",
"&&",
"@db_tables",
".",
"empty?",
"result",
".",
"clear",
"add_line",
"\"Sequel.migration do\"",
"indent",
"do",
"generate_migration_body",
"(",
"tables",
")",
"end",
"add_l... | Creates a migration builder for the given database.
Generates a string of ruby code to define a sequel
migration, based on the differences between the database schema
of this MigrationBuilder and the tables passed. | [
"Creates",
"a",
"migration",
"builder",
"for",
"the",
"given",
"database",
"."
] | 8e640d1af39ccd83418ae408f62d68519363fa7b | https://github.com/knaveofdiamonds/sequel_migration_builder/blob/8e640d1af39ccd83418ae408f62d68519363fa7b/lib/sequel/migration_builder.rb#L32-L43 | valid |
knaveofdiamonds/sequel_migration_builder | lib/sequel/migration_builder.rb | Sequel.MigrationBuilder.generate_migration_body | def generate_migration_body(tables)
current_tables, new_tables = table_names(tables).partition do |table_name|
@db_table_names.include?(table_name)
end
add_line "change do"
create_new_tables(new_tables, tables)
alter_tables(current_tables, tables)
add_line "end"
end | ruby | def generate_migration_body(tables)
current_tables, new_tables = table_names(tables).partition do |table_name|
@db_table_names.include?(table_name)
end
add_line "change do"
create_new_tables(new_tables, tables)
alter_tables(current_tables, tables)
add_line "end"
end | [
"def",
"generate_migration_body",
"(",
"tables",
")",
"current_tables",
",",
"new_tables",
"=",
"table_names",
"(",
"tables",
")",
".",
"partition",
"do",
"|",
"table_name",
"|",
"@db_table_names",
".",
"include?",
"(",
"table_name",
")",
"end",
"add_line",
"\"c... | Generates the 'change' block of the migration. | [
"Generates",
"the",
"change",
"block",
"of",
"the",
"migration",
"."
] | 8e640d1af39ccd83418ae408f62d68519363fa7b | https://github.com/knaveofdiamonds/sequel_migration_builder/blob/8e640d1af39ccd83418ae408f62d68519363fa7b/lib/sequel/migration_builder.rb#L47-L56 | valid |
knaveofdiamonds/sequel_migration_builder | lib/sequel/migration_builder.rb | Sequel.MigrationBuilder.create_new_tables | def create_new_tables(new_table_names, tables)
each_table(new_table_names, tables) do |table_name, table, last_table|
create_table_statement table_name, table
add_blank_line unless last_table
end
end | ruby | def create_new_tables(new_table_names, tables)
each_table(new_table_names, tables) do |table_name, table, last_table|
create_table_statement table_name, table
add_blank_line unless last_table
end
end | [
"def",
"create_new_tables",
"(",
"new_table_names",
",",
"tables",
")",
"each_table",
"(",
"new_table_names",
",",
"tables",
")",
"do",
"|",
"table_name",
",",
"table",
",",
"last_table",
"|",
"create_table_statement",
"table_name",
",",
"table",
"add_blank_line",
... | Generates any create table statements for new tables. | [
"Generates",
"any",
"create",
"table",
"statements",
"for",
"new",
"tables",
"."
] | 8e640d1af39ccd83418ae408f62d68519363fa7b | https://github.com/knaveofdiamonds/sequel_migration_builder/blob/8e640d1af39ccd83418ae408f62d68519363fa7b/lib/sequel/migration_builder.rb#L60-L65 | valid |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.