repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
Dev-Crea/swagger-docs-generator | lib/swagger_docs_generator/generator.rb | SwaggerDocsGenerator.Generator.generate_swagger_file | def generate_swagger_file
delete_file_before
File.open(@swagger_file, 'a+') do |file|
file.write(if SwaggerDocsGenerator.configure.compress
write_in_swagger_file.to_json
else
JSON.pretty_generate write_in_swagger_file
end)
end
end | ruby | def generate_swagger_file
delete_file_before
File.open(@swagger_file, 'a+') do |file|
file.write(if SwaggerDocsGenerator.configure.compress
write_in_swagger_file.to_json
else
JSON.pretty_generate write_in_swagger_file
end)
end
end | [
"def",
"generate_swagger_file",
"delete_file_before",
"File",
".",
"open",
"(",
"@swagger_file",
",",
"'a+'",
")",
"do",
"|",
"file",
"|",
"file",
".",
"write",
"(",
"if",
"SwaggerDocsGenerator",
".",
"configure",
".",
"compress",
"write_in_swagger_file",
".",
"to_json",
"else",
"JSON",
".",
"pretty_generate",
"write_in_swagger_file",
"end",
")",
"end",
"end"
] | Open or create a swagger.json file | [
"Open",
"or",
"create",
"a",
"swagger",
".",
"json",
"file"
] | 5d3de176aa1119cb38100b451bee028d66c0809d | https://github.com/Dev-Crea/swagger-docs-generator/blob/5d3de176aa1119cb38100b451bee028d66c0809d/lib/swagger_docs_generator/generator.rb#L26-L35 | train |
mharris717/ascension | lib/ascension/parse/card.rb | Parse.Card.mod_for_phrases | def mod_for_phrases(raw_cell, method_name_or_ability_class, card_to_setup)
return unless raw_cell
#puts [raw,cat,card_class,name].inspect
raw_cell.split(/[,;]/).each do |raw_cell_part|
p = make_parsed_phrase_obj(raw_cell_part,method_name_or_ability_class)
p.mod_card(card_to_setup) if p
end
end | ruby | def mod_for_phrases(raw_cell, method_name_or_ability_class, card_to_setup)
return unless raw_cell
#puts [raw,cat,card_class,name].inspect
raw_cell.split(/[,;]/).each do |raw_cell_part|
p = make_parsed_phrase_obj(raw_cell_part,method_name_or_ability_class)
p.mod_card(card_to_setup) if p
end
end | [
"def",
"mod_for_phrases",
"(",
"raw_cell",
",",
"method_name_or_ability_class",
",",
"card_to_setup",
")",
"return",
"unless",
"raw_cell",
"raw_cell",
".",
"split",
"(",
"/",
"/",
")",
".",
"each",
"do",
"|",
"raw_cell_part",
"|",
"p",
"=",
"make_parsed_phrase_obj",
"(",
"raw_cell_part",
",",
"method_name_or_ability_class",
")",
"p",
".",
"mod_card",
"(",
"card_to_setup",
")",
"if",
"p",
"end",
"end"
] | Raw Cell is the text from the csv file for this column
method_name_or_ability_class is one of two things:
1. the symbol for the method to call for this column
2. The Class that represents this ability | [
"Raw",
"Cell",
"is",
"the",
"text",
"from",
"the",
"csv",
"file",
"for",
"this",
"column"
] | d4f4b9a603524d53b03436c370adf4756e5ca616 | https://github.com/mharris717/ascension/blob/d4f4b9a603524d53b03436c370adf4756e5ca616/lib/ascension/parse/card.rb#L25-L32 | train |
lyjia/zog | lib/zog/heart.rb | Zog.Heart.method_missing | def method_missing(meth, *args, &block)
if @categories.include?(meth)
if block_given?
args[0] = yield block
end
self::msg(meth, args[0])
else
super
end
end | ruby | def method_missing(meth, *args, &block)
if @categories.include?(meth)
if block_given?
args[0] = yield block
end
self::msg(meth, args[0])
else
super
end
end | [
"def",
"method_missing",
"(",
"meth",
",",
"*",
"args",
",",
"&",
"block",
")",
"if",
"@categories",
".",
"include?",
"(",
"meth",
")",
"if",
"block_given?",
"args",
"[",
"0",
"]",
"=",
"yield",
"block",
"end",
"self",
"::",
"msg",
"(",
"meth",
",",
"args",
"[",
"0",
"]",
")",
"else",
"super",
"end",
"end"
] | This is what responds to Zog.info, Zog.error, etc | [
"This",
"is",
"what",
"responds",
"to",
"Zog",
".",
"info",
"Zog",
".",
"error",
"etc"
] | c7db39ee324f925e19ed8ed7b96b51ec734f6992 | https://github.com/lyjia/zog/blob/c7db39ee324f925e19ed8ed7b96b51ec734f6992/lib/zog/heart.rb#L100-L114 | train |
phildionne/associates | lib/associates.rb | Associates.ClassMethods.associate | def associate(model, options = {})
options[:only] = Array(options[:only])
options[:except] = Array(options[:except])
options[:depends_on] = Array(options[:depends_on])
options = {
delegate: true
}.merge(options)
associate = build_associate(model, options)
self.associates << associate
define_associate_delegation(associate) if options[:delegate]
define_associate_instance_setter_method(associate)
define_associate_instance_getter_method(associate)
end | ruby | def associate(model, options = {})
options[:only] = Array(options[:only])
options[:except] = Array(options[:except])
options[:depends_on] = Array(options[:depends_on])
options = {
delegate: true
}.merge(options)
associate = build_associate(model, options)
self.associates << associate
define_associate_delegation(associate) if options[:delegate]
define_associate_instance_setter_method(associate)
define_associate_instance_getter_method(associate)
end | [
"def",
"associate",
"(",
"model",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":only",
"]",
"=",
"Array",
"(",
"options",
"[",
":only",
"]",
")",
"options",
"[",
":except",
"]",
"=",
"Array",
"(",
"options",
"[",
":except",
"]",
")",
"options",
"[",
":depends_on",
"]",
"=",
"Array",
"(",
"options",
"[",
":depends_on",
"]",
")",
"options",
"=",
"{",
"delegate",
":",
"true",
"}",
".",
"merge",
"(",
"options",
")",
"associate",
"=",
"build_associate",
"(",
"model",
",",
"options",
")",
"self",
".",
"associates",
"<<",
"associate",
"define_associate_delegation",
"(",
"associate",
")",
"if",
"options",
"[",
":delegate",
"]",
"define_associate_instance_setter_method",
"(",
"associate",
")",
"define_associate_instance_getter_method",
"(",
"associate",
")",
"end"
] | Defines an associated model
@example
class User
include Associates
associate :user, only: :username
end
@param model [Symbol, Class]
@param [Hash] options
@option options [Symbol, Array] :only Only generate methods for the given attributes
@option options [Symbol, Array] :except Generate all the model's methods except
for the given attributes
@option options [Symbol] :depends_on Specify one or more associate name on
which the current associate model depends to be valid. Allow to automatically
setup `belongs_to` associations between models
@option options [String, Class] :class_name Specify the class name of the associate.
Use it only if that name can’t be inferred from the associate's name
@option options [Boolean] :delegate (true) Wether or not to delegate the associate's
attributes getter and setters methods to the associate instance | [
"Defines",
"an",
"associated",
"model"
] | 630edcc47340a73ad787feaf2cdf326b4487bb9f | https://github.com/phildionne/associates/blob/630edcc47340a73ad787feaf2cdf326b4487bb9f/lib/associates.rb#L64-L79 | train |
phildionne/associates | lib/associates.rb | Associates.ClassMethods.build_associate | def build_associate(model, options = {})
model_name = model.to_s.underscore
model_klass = (options[:class_name] || model).to_s.classify.constantize
dependent_associate_names = options[:depends_on].map(&:to_s)
attribute_names = extract_attribute_names(model_klass, options)
ensure_name_uniqueness(associates.map(&:name), model_name)
ensure_attribute_uniqueness(associates.map(&:attribute_names), attribute_names) if options[:delegate]
ensure_dependent_names_existence(associates.map(&:name), dependent_associate_names)
Item.new(model_name, model_klass, attribute_names, dependent_associate_names, options)
end | ruby | def build_associate(model, options = {})
model_name = model.to_s.underscore
model_klass = (options[:class_name] || model).to_s.classify.constantize
dependent_associate_names = options[:depends_on].map(&:to_s)
attribute_names = extract_attribute_names(model_klass, options)
ensure_name_uniqueness(associates.map(&:name), model_name)
ensure_attribute_uniqueness(associates.map(&:attribute_names), attribute_names) if options[:delegate]
ensure_dependent_names_existence(associates.map(&:name), dependent_associate_names)
Item.new(model_name, model_klass, attribute_names, dependent_associate_names, options)
end | [
"def",
"build_associate",
"(",
"model",
",",
"options",
"=",
"{",
"}",
")",
"model_name",
"=",
"model",
".",
"to_s",
".",
"underscore",
"model_klass",
"=",
"(",
"options",
"[",
":class_name",
"]",
"||",
"model",
")",
".",
"to_s",
".",
"classify",
".",
"constantize",
"dependent_associate_names",
"=",
"options",
"[",
":depends_on",
"]",
".",
"map",
"(",
"&",
":to_s",
")",
"attribute_names",
"=",
"extract_attribute_names",
"(",
"model_klass",
",",
"options",
")",
"ensure_name_uniqueness",
"(",
"associates",
".",
"map",
"(",
"&",
":name",
")",
",",
"model_name",
")",
"ensure_attribute_uniqueness",
"(",
"associates",
".",
"map",
"(",
"&",
":attribute_names",
")",
",",
"attribute_names",
")",
"if",
"options",
"[",
":delegate",
"]",
"ensure_dependent_names_existence",
"(",
"associates",
".",
"map",
"(",
"&",
":name",
")",
",",
"dependent_associate_names",
")",
"Item",
".",
"new",
"(",
"model_name",
",",
"model_klass",
",",
"attribute_names",
",",
"dependent_associate_names",
",",
"options",
")",
"end"
] | Builds an associate
@param model [Symbol, Class]
@param options [Hash]
@return [Item] | [
"Builds",
"an",
"associate"
] | 630edcc47340a73ad787feaf2cdf326b4487bb9f | https://github.com/phildionne/associates/blob/630edcc47340a73ad787feaf2cdf326b4487bb9f/lib/associates.rb#L89-L100 | train |
phildionne/associates | lib/associates.rb | Associates.ClassMethods.ensure_attribute_uniqueness | def ensure_attribute_uniqueness(associates_attribute_names, attribute_names)
attribute_names.each do |attribute_name|
if associates_attribute_names.include?(attribute_name)
raise NameError, "already defined attribute name '#{attribute_name}' for #{name}(#{object_id})"
end
end
end | ruby | def ensure_attribute_uniqueness(associates_attribute_names, attribute_names)
attribute_names.each do |attribute_name|
if associates_attribute_names.include?(attribute_name)
raise NameError, "already defined attribute name '#{attribute_name}' for #{name}(#{object_id})"
end
end
end | [
"def",
"ensure_attribute_uniqueness",
"(",
"associates_attribute_names",
",",
"attribute_names",
")",
"attribute_names",
".",
"each",
"do",
"|",
"attribute_name",
"|",
"if",
"associates_attribute_names",
".",
"include?",
"(",
"attribute_name",
")",
"raise",
"NameError",
",",
"\"already defined attribute name '#{attribute_name}' for #{name}(#{object_id})\"",
"end",
"end",
"end"
] | Ensure associate attribute names don't clash with already declared ones
@param associates_attribute_names [Array]
@param attribute_names [Array] | [
"Ensure",
"associate",
"attribute",
"names",
"don",
"t",
"clash",
"with",
"already",
"declared",
"ones"
] | 630edcc47340a73ad787feaf2cdf326b4487bb9f | https://github.com/phildionne/associates/blob/630edcc47340a73ad787feaf2cdf326b4487bb9f/lib/associates.rb#L116-L122 | train |
phildionne/associates | lib/associates.rb | Associates.ClassMethods.ensure_dependent_names_existence | def ensure_dependent_names_existence(associates_names, dependent_associate_names)
dependent_associate_names.each do |dependent_name|
unless associates_names.include?(dependent_name)
raise NameError, "undefined associated model '#{dependent_name}' for #{name}(#{object_id})"
end
end
end | ruby | def ensure_dependent_names_existence(associates_names, dependent_associate_names)
dependent_associate_names.each do |dependent_name|
unless associates_names.include?(dependent_name)
raise NameError, "undefined associated model '#{dependent_name}' for #{name}(#{object_id})"
end
end
end | [
"def",
"ensure_dependent_names_existence",
"(",
"associates_names",
",",
"dependent_associate_names",
")",
"dependent_associate_names",
".",
"each",
"do",
"|",
"dependent_name",
"|",
"unless",
"associates_names",
".",
"include?",
"(",
"dependent_name",
")",
"raise",
"NameError",
",",
"\"undefined associated model '#{dependent_name}' for #{name}(#{object_id})\"",
"end",
"end",
"end"
] | Ensure associate dependent names exists
@param associates_names [Array]
@param dependent_associate_names [Array] | [
"Ensure",
"associate",
"dependent",
"names",
"exists"
] | 630edcc47340a73ad787feaf2cdf326b4487bb9f | https://github.com/phildionne/associates/blob/630edcc47340a73ad787feaf2cdf326b4487bb9f/lib/associates.rb#L128-L134 | train |
phildionne/associates | lib/associates.rb | Associates.ClassMethods.define_associate_delegation | def define_associate_delegation(associate)
methods = [associate.attribute_names, associate.attribute_names.map { |attr| "#{attr}=" }].flatten
send(:delegate, *methods, to: associate.name)
end | ruby | def define_associate_delegation(associate)
methods = [associate.attribute_names, associate.attribute_names.map { |attr| "#{attr}=" }].flatten
send(:delegate, *methods, to: associate.name)
end | [
"def",
"define_associate_delegation",
"(",
"associate",
")",
"methods",
"=",
"[",
"associate",
".",
"attribute_names",
",",
"associate",
".",
"attribute_names",
".",
"map",
"{",
"|",
"attr",
"|",
"\"#{attr}=\"",
"}",
"]",
".",
"flatten",
"send",
"(",
":delegate",
",",
"*",
"methods",
",",
"to",
":",
"associate",
".",
"name",
")",
"end"
] | Define associated model attribute methods delegation
@param associate [Item] | [
"Define",
"associated",
"model",
"attribute",
"methods",
"delegation"
] | 630edcc47340a73ad787feaf2cdf326b4487bb9f | https://github.com/phildionne/associates/blob/630edcc47340a73ad787feaf2cdf326b4487bb9f/lib/associates.rb#L156-L159 | train |
phildionne/associates | lib/associates.rb | Associates.ClassMethods.define_associate_instance_setter_method | def define_associate_instance_setter_method(associate)
define_method "#{associate.name}=" do |object|
unless object.is_a?(associate.klass)
raise ArgumentError, "#{associate.klass}(##{associate.klass.object_id}) expected, got #{object.class}(##{object.class.object_id})"
end
instance = instance_variable_set("@#{associate.name}", object)
depending = associates.select { |_associate| _associate.dependent_names.include?(associate.name) }
depending.each do |_associate|
send(_associate.name).send("#{associate.name}=", instance)
end
instance
end
end | ruby | def define_associate_instance_setter_method(associate)
define_method "#{associate.name}=" do |object|
unless object.is_a?(associate.klass)
raise ArgumentError, "#{associate.klass}(##{associate.klass.object_id}) expected, got #{object.class}(##{object.class.object_id})"
end
instance = instance_variable_set("@#{associate.name}", object)
depending = associates.select { |_associate| _associate.dependent_names.include?(associate.name) }
depending.each do |_associate|
send(_associate.name).send("#{associate.name}=", instance)
end
instance
end
end | [
"def",
"define_associate_instance_setter_method",
"(",
"associate",
")",
"define_method",
"\"#{associate.name}=\"",
"do",
"|",
"object",
"|",
"unless",
"object",
".",
"is_a?",
"(",
"associate",
".",
"klass",
")",
"raise",
"ArgumentError",
",",
"\"#{associate.klass}(##{associate.klass.object_id}) expected, got #{object.class}(##{object.class.object_id})\"",
"end",
"instance",
"=",
"instance_variable_set",
"(",
"\"@#{associate.name}\"",
",",
"object",
")",
"depending",
"=",
"associates",
".",
"select",
"{",
"|",
"_associate",
"|",
"_associate",
".",
"dependent_names",
".",
"include?",
"(",
"associate",
".",
"name",
")",
"}",
"depending",
".",
"each",
"do",
"|",
"_associate",
"|",
"send",
"(",
"_associate",
".",
"name",
")",
".",
"send",
"(",
"\"#{associate.name}=\"",
",",
"instance",
")",
"end",
"instance",
"end",
"end"
] | Define associated model instance setter method
@example
@association.user = User.new
@param associate [Item] | [
"Define",
"associated",
"model",
"instance",
"setter",
"method"
] | 630edcc47340a73ad787feaf2cdf326b4487bb9f | https://github.com/phildionne/associates/blob/630edcc47340a73ad787feaf2cdf326b4487bb9f/lib/associates.rb#L168-L183 | train |
phildionne/associates | lib/associates.rb | Associates.ClassMethods.define_associate_instance_getter_method | def define_associate_instance_getter_method(associate)
define_method associate.name do
instance = instance_variable_get("@#{associate.name}") || instance_variable_set("@#{associate.name}", associate.klass.new)
depending = associates.select { |_associate| _associate.dependent_names.include?(associate.name) }
depending.each do |_associate|
existing = send(_associate.name).send(associate.name)
send(_associate.name).send("#{associate.name}=", instance) unless existing
end
instance
end
end | ruby | def define_associate_instance_getter_method(associate)
define_method associate.name do
instance = instance_variable_get("@#{associate.name}") || instance_variable_set("@#{associate.name}", associate.klass.new)
depending = associates.select { |_associate| _associate.dependent_names.include?(associate.name) }
depending.each do |_associate|
existing = send(_associate.name).send(associate.name)
send(_associate.name).send("#{associate.name}=", instance) unless existing
end
instance
end
end | [
"def",
"define_associate_instance_getter_method",
"(",
"associate",
")",
"define_method",
"associate",
".",
"name",
"do",
"instance",
"=",
"instance_variable_get",
"(",
"\"@#{associate.name}\"",
")",
"||",
"instance_variable_set",
"(",
"\"@#{associate.name}\"",
",",
"associate",
".",
"klass",
".",
"new",
")",
"depending",
"=",
"associates",
".",
"select",
"{",
"|",
"_associate",
"|",
"_associate",
".",
"dependent_names",
".",
"include?",
"(",
"associate",
".",
"name",
")",
"}",
"depending",
".",
"each",
"do",
"|",
"_associate",
"|",
"existing",
"=",
"send",
"(",
"_associate",
".",
"name",
")",
".",
"send",
"(",
"associate",
".",
"name",
")",
"send",
"(",
"_associate",
".",
"name",
")",
".",
"send",
"(",
"\"#{associate.name}=\"",
",",
"instance",
")",
"unless",
"existing",
"end",
"instance",
"end",
"end"
] | Define associated model instance getter method
@example
@association.user
@param associate [Item] | [
"Define",
"associated",
"model",
"instance",
"getter",
"method"
] | 630edcc47340a73ad787feaf2cdf326b4487bb9f | https://github.com/phildionne/associates/blob/630edcc47340a73ad787feaf2cdf326b4487bb9f/lib/associates.rb#L192-L204 | train |
barkerest/incline | app/mailers/incline/user_mailer.rb | Incline.UserMailer.account_activation | def account_activation(data = {})
@data = {
user: nil,
client_ip: '0.0.0.0'
}.merge(data || {})
raise unless data[:user]
mail to: data[:user].email, subject: 'Account activation'
end | ruby | def account_activation(data = {})
@data = {
user: nil,
client_ip: '0.0.0.0'
}.merge(data || {})
raise unless data[:user]
mail to: data[:user].email, subject: 'Account activation'
end | [
"def",
"account_activation",
"(",
"data",
"=",
"{",
"}",
")",
"@data",
"=",
"{",
"user",
":",
"nil",
",",
"client_ip",
":",
"'0.0.0.0'",
"}",
".",
"merge",
"(",
"data",
"||",
"{",
"}",
")",
"raise",
"unless",
"data",
"[",
":user",
"]",
"mail",
"to",
":",
"data",
"[",
":user",
"]",
".",
"email",
",",
"subject",
":",
"'Account activation'",
"end"
] | Sends the activation email to a new user. | [
"Sends",
"the",
"activation",
"email",
"to",
"a",
"new",
"user",
"."
] | 1ff08db7aa8ab7f86b223268b700bc67d15bb8aa | https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/mailers/incline/user_mailer.rb#L11-L18 | train |
barkerest/incline | app/mailers/incline/user_mailer.rb | Incline.UserMailer.invalid_password_reset | def invalid_password_reset(data = {})
@data = {
email: nil,
message: 'This email address is not associated with an existing account.',
client_ip: '0.0.0.0'
}.merge(data || {})
raise unless data[:email]
mail to: data[:email], subject: 'Password reset request'
end | ruby | def invalid_password_reset(data = {})
@data = {
email: nil,
message: 'This email address is not associated with an existing account.',
client_ip: '0.0.0.0'
}.merge(data || {})
raise unless data[:email]
mail to: data[:email], subject: 'Password reset request'
end | [
"def",
"invalid_password_reset",
"(",
"data",
"=",
"{",
"}",
")",
"@data",
"=",
"{",
"email",
":",
"nil",
",",
"message",
":",
"'This email address is not associated with an existing account.'",
",",
"client_ip",
":",
"'0.0.0.0'",
"}",
".",
"merge",
"(",
"data",
"||",
"{",
"}",
")",
"raise",
"unless",
"data",
"[",
":email",
"]",
"mail",
"to",
":",
"data",
"[",
":email",
"]",
",",
"subject",
":",
"'Password reset request'",
"end"
] | Sends an invalid password reset attempt message to a user whether they exist or not. | [
"Sends",
"an",
"invalid",
"password",
"reset",
"attempt",
"message",
"to",
"a",
"user",
"whether",
"they",
"exist",
"or",
"not",
"."
] | 1ff08db7aa8ab7f86b223268b700bc67d15bb8aa | https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/app/mailers/incline/user_mailer.rb#L33-L41 | train |
siefca/configuration-blocks | lib/configuration-blocks/core.rb | ConfigurationBlocks.ClassMethods.configuration_module | def configuration_module(base = self)
Module.new.tap do |cm|
delegators = get_configuration_methods
base = send(base) if base.is_a?(Symbol)
cm.extend Module.new {
delegators.each do |method|
module_eval do
define_method(method) do |*args|
base.send(method, *args)
end
end
end
}
end
end | ruby | def configuration_module(base = self)
Module.new.tap do |cm|
delegators = get_configuration_methods
base = send(base) if base.is_a?(Symbol)
cm.extend Module.new {
delegators.each do |method|
module_eval do
define_method(method) do |*args|
base.send(method, *args)
end
end
end
}
end
end | [
"def",
"configuration_module",
"(",
"base",
"=",
"self",
")",
"Module",
".",
"new",
".",
"tap",
"do",
"|",
"cm",
"|",
"delegators",
"=",
"get_configuration_methods",
"base",
"=",
"send",
"(",
"base",
")",
"if",
"base",
".",
"is_a?",
"(",
"Symbol",
")",
"cm",
".",
"extend",
"Module",
".",
"new",
"{",
"delegators",
".",
"each",
"do",
"|",
"method",
"|",
"module_eval",
"do",
"define_method",
"(",
"method",
")",
"do",
"|",
"*",
"args",
"|",
"base",
".",
"send",
"(",
"method",
",",
"*",
"args",
")",
"end",
"end",
"end",
"}",
"end",
"end"
] | Creates and returns anonymous module containing
delegators that point to methods from a class this module is included in
or the given +base+.
@param base [Object,Symbol] base object which delegators will point to (defaults to object on which
this method has been called). If symbol is given, then it should contain the name of a method that
will be called on current object.
@return [Module] anonymous module with proxy module methods delegating actions to +base+ object | [
"Creates",
"and",
"returns",
"anonymous",
"module",
"containing",
"delegators",
"that",
"point",
"to",
"methods",
"from",
"a",
"class",
"this",
"module",
"is",
"included",
"in",
"or",
"the",
"given",
"+",
"base",
"+",
"."
] | 1b04f5f3e97639b455a473c5f9c2200cf9f18c26 | https://github.com/siefca/configuration-blocks/blob/1b04f5f3e97639b455a473c5f9c2200cf9f18c26/lib/configuration-blocks/core.rb#L84-L98 | train |
siefca/configuration-blocks | lib/configuration-blocks/core.rb | ConfigurationBlocks.ClassMethods.get_configuration_methods | def get_configuration_methods(local_only = false)
all_delegators = singleton_class.send(:cf_block_delegators) + cf_block_delegators
return all_delegators if local_only
ancestors.each_with_object(all_delegators) do |ancestor, all|
all.merge(ancestor.send(__method__, true)) if ancestor.respond_to?(__method__)
end
end | ruby | def get_configuration_methods(local_only = false)
all_delegators = singleton_class.send(:cf_block_delegators) + cf_block_delegators
return all_delegators if local_only
ancestors.each_with_object(all_delegators) do |ancestor, all|
all.merge(ancestor.send(__method__, true)) if ancestor.respond_to?(__method__)
end
end | [
"def",
"get_configuration_methods",
"(",
"local_only",
"=",
"false",
")",
"all_delegators",
"=",
"singleton_class",
".",
"send",
"(",
":cf_block_delegators",
")",
"+",
"cf_block_delegators",
"return",
"all_delegators",
"if",
"local_only",
"ancestors",
".",
"each_with_object",
"(",
"all_delegators",
")",
"do",
"|",
"ancestor",
",",
"all",
"|",
"all",
".",
"merge",
"(",
"ancestor",
".",
"send",
"(",
"__method__",
",",
"true",
")",
")",
"if",
"ancestor",
".",
"respond_to?",
"(",
"__method__",
")",
"end",
"end"
] | Gets all method names known to configuration engine.
@param local_only [Boolean] optional flag that if set, causes only methods added
by current class or module to be listed.
@return [Array<Symbol>] delegated method names | [
"Gets",
"all",
"method",
"names",
"known",
"to",
"configuration",
"engine",
"."
] | 1b04f5f3e97639b455a473c5f9c2200cf9f18c26 | https://github.com/siefca/configuration-blocks/blob/1b04f5f3e97639b455a473c5f9c2200cf9f18c26/lib/configuration-blocks/core.rb#L106-L112 | train |
siefca/configuration-blocks | lib/configuration-blocks/core.rb | ConfigurationBlocks.ClassMethods.configuration_block_delegate | def configuration_block_delegate(*methods)
methods.flatten.each { |m| cf_block_delegators.add(m.to_sym) }
@cb_conf_module = nil if @cb_conf_module
nil
end | ruby | def configuration_block_delegate(*methods)
methods.flatten.each { |m| cf_block_delegators.add(m.to_sym) }
@cb_conf_module = nil if @cb_conf_module
nil
end | [
"def",
"configuration_block_delegate",
"(",
"*",
"methods",
")",
"methods",
".",
"flatten",
".",
"each",
"{",
"|",
"m",
"|",
"cf_block_delegators",
".",
"add",
"(",
"m",
".",
"to_sym",
")",
"}",
"@cb_conf_module",
"=",
"nil",
"if",
"@cb_conf_module",
"nil",
"end"
] | This DSL method is intended to be used in a class or module to indicate which methods
should be delegated.
@param methods [Array<Symbol,String>] list of method names
@return [nil] | [
"This",
"DSL",
"method",
"is",
"intended",
"to",
"be",
"used",
"in",
"a",
"class",
"or",
"module",
"to",
"indicate",
"which",
"methods",
"should",
"be",
"delegated",
"."
] | 1b04f5f3e97639b455a473c5f9c2200cf9f18c26 | https://github.com/siefca/configuration-blocks/blob/1b04f5f3e97639b455a473c5f9c2200cf9f18c26/lib/configuration-blocks/core.rb#L119-L123 | train |
siefca/configuration-blocks | lib/configuration-blocks/core.rb | ConfigurationBlocks.ClassMethods.configuration_block_core | def configuration_block_core(conf_module, &block)
return conf_module unless block_given?
return conf_module.tap(&block) unless block.arity == 0
conf_module.module_eval(&block)
conf_module
end | ruby | def configuration_block_core(conf_module, &block)
return conf_module unless block_given?
return conf_module.tap(&block) unless block.arity == 0
conf_module.module_eval(&block)
conf_module
end | [
"def",
"configuration_block_core",
"(",
"conf_module",
",",
"&",
"block",
")",
"return",
"conf_module",
"unless",
"block_given?",
"return",
"conf_module",
".",
"tap",
"(",
"&",
"block",
")",
"unless",
"block",
".",
"arity",
"==",
"0",
"conf_module",
".",
"module_eval",
"(",
"&",
"block",
")",
"conf_module",
"end"
] | Evaluates configuration block within a context of the given module. | [
"Evaluates",
"configuration",
"block",
"within",
"a",
"context",
"of",
"the",
"given",
"module",
"."
] | 1b04f5f3e97639b455a473c5f9c2200cf9f18c26 | https://github.com/siefca/configuration-blocks/blob/1b04f5f3e97639b455a473c5f9c2200cf9f18c26/lib/configuration-blocks/core.rb#L136-L141 | train |
barkerest/barkest_core | app/helpers/barkest_core/status_helper.rb | BarkestCore.StatusHelper.show_system_status | def show_system_status(options = {})
options = {
url_on_completion: nil,
completion_button: 'Continue',
main_status: 'System is busy'
}.merge(options || {})
if block_given?
clear_system_status
Spawnling.new do
status = BarkestCore::GlobalStatus.new
if status.acquire_lock
status.set_message options[:main_status]
begin
yield status
ensure
status.release_lock
end
else
yield false
end
end
end
session[:status_comp_url] = options[:url_on_completion]
session[:status_comp_lbl] = options[:completion_button]
redirect_to status_current_url
end | ruby | def show_system_status(options = {})
options = {
url_on_completion: nil,
completion_button: 'Continue',
main_status: 'System is busy'
}.merge(options || {})
if block_given?
clear_system_status
Spawnling.new do
status = BarkestCore::GlobalStatus.new
if status.acquire_lock
status.set_message options[:main_status]
begin
yield status
ensure
status.release_lock
end
else
yield false
end
end
end
session[:status_comp_url] = options[:url_on_completion]
session[:status_comp_lbl] = options[:completion_button]
redirect_to status_current_url
end | [
"def",
"show_system_status",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"url_on_completion",
":",
"nil",
",",
"completion_button",
":",
"'Continue'",
",",
"main_status",
":",
"'System is busy'",
"}",
".",
"merge",
"(",
"options",
"||",
"{",
"}",
")",
"if",
"block_given?",
"clear_system_status",
"Spawnling",
".",
"new",
"do",
"status",
"=",
"BarkestCore",
"::",
"GlobalStatus",
".",
"new",
"if",
"status",
".",
"acquire_lock",
"status",
".",
"set_message",
"options",
"[",
":main_status",
"]",
"begin",
"yield",
"status",
"ensure",
"status",
".",
"release_lock",
"end",
"else",
"yield",
"false",
"end",
"end",
"end",
"session",
"[",
":status_comp_url",
"]",
"=",
"options",
"[",
":url_on_completion",
"]",
"session",
"[",
":status_comp_lbl",
"]",
"=",
"options",
"[",
":completion_button",
"]",
"redirect_to",
"status_current_url",
"end"
] | Shows the system status while optionally performing a long running code block.
Accepted options:
url_on_completion::
This is the URL you want to redirect to when the long running code completes.
If not set, then the completion button will have an empty HREF which means it will simply reload the status page.
It is therefore highly recommended that you provide this value when using this method.
completion_button::
This is the label for the button that becomes visible when the long running code completes.
Defaults to 'Continue'.
main_status::
This is the initial status to report for the system when a long running code block is provided.
If a code block is provided, this will reset the system status and spawn a thread to run the code block.
Before running the code block, it will acquire a GlobalStatus lock and set the initial status.
When the code block exits, either through error or normal behavior, the GlobalStatus lock will be released.
It will yield the +status+ object to the code block on a successful lock, or it will yield false to the code
block to let it know that a lock could not be acquired. You should check for this in your code block and
handle the error as appropriate.
Example 1:
def my_action
Spawling.new do
GlobalStatus.lock_for do |status|
if status
clear_system_status # reset the log file.
# Do something that takes a long time.
...
end
end
end
show_system_status(:url_on_completion => my_target_url)
end
Example 2:
def my_action
show_system_status(:url_on_completion => my_target_url) do |status|
if status
# Do something that takes a long time.
...
end
end
end
The benefits of Example 2 is that it handles the thread spawning and status locking for you. | [
"Shows",
"the",
"system",
"status",
"while",
"optionally",
"performing",
"a",
"long",
"running",
"code",
"block",
"."
] | 3eeb025ec870888cacbc9bae252a39ebf9295f61 | https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/helpers/barkest_core/status_helper.rb#L60-L88 | train |
barkerest/barkest_core | app/helpers/barkest_core/status_helper.rb | BarkestCore.StatusHelper.clear_system_status | def clear_system_status
unless BarkestCore::GlobalStatus.locked?
# open, truncate, and close.
File.open(BarkestCore::WorkPath.system_status_file,'w').close
end
end | ruby | def clear_system_status
unless BarkestCore::GlobalStatus.locked?
# open, truncate, and close.
File.open(BarkestCore::WorkPath.system_status_file,'w').close
end
end | [
"def",
"clear_system_status",
"unless",
"BarkestCore",
"::",
"GlobalStatus",
".",
"locked?",
"File",
".",
"open",
"(",
"BarkestCore",
"::",
"WorkPath",
".",
"system_status_file",
",",
"'w'",
")",
".",
"close",
"end",
"end"
] | Clears the system status log file.
If the file does not exist, it is created as a zero byte file.
This is important for the status checking, since if there is no log file it will report an error. | [
"Clears",
"the",
"system",
"status",
"log",
"file",
"."
] | 3eeb025ec870888cacbc9bae252a39ebf9295f61 | https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/helpers/barkest_core/status_helper.rb#L96-L101 | train |
bblack16/bblib-ruby | lib/bblib/core/mixins/numeric_enhancements.rb | BBLib.NumericEnhancements.to_delimited_s | def to_delimited_s(delim = ',')
split = self.to_s.split('.')
split[0] = split.first.reverse.gsub(/(\d{3})/, "\\1#{delim}").reverse
split.join('.').uncapsulate(',')
end | ruby | def to_delimited_s(delim = ',')
split = self.to_s.split('.')
split[0] = split.first.reverse.gsub(/(\d{3})/, "\\1#{delim}").reverse
split.join('.').uncapsulate(',')
end | [
"def",
"to_delimited_s",
"(",
"delim",
"=",
"','",
")",
"split",
"=",
"self",
".",
"to_s",
".",
"split",
"(",
"'.'",
")",
"split",
"[",
"0",
"]",
"=",
"split",
".",
"first",
".",
"reverse",
".",
"gsub",
"(",
"/",
"\\d",
"/",
",",
"\"\\\\1#{delim}\"",
")",
".",
"reverse",
"split",
".",
"join",
"(",
"'.'",
")",
".",
"uncapsulate",
"(",
"','",
")",
"end"
] | Convert this integer into a string with every three digits separated by a delimiter
on the left side of the decimal | [
"Convert",
"this",
"integer",
"into",
"a",
"string",
"with",
"every",
"three",
"digits",
"separated",
"by",
"a",
"delimiter",
"on",
"the",
"left",
"side",
"of",
"the",
"decimal"
] | 274eedeb583cc56243884fd041645488d5bd08a9 | https://github.com/bblack16/bblib-ruby/blob/274eedeb583cc56243884fd041645488d5bd08a9/lib/bblib/core/mixins/numeric_enhancements.rb#L24-L28 | train |
barkerest/incline | lib/incline/json_log_formatter.rb | Incline.JsonLogFormatter.call | def call(sev, time, _, msg) #:nodoc:
level = ({
Logger::DEBUG => 'DEBUG',
Logger::INFO => 'INFO',
Logger::WARN => 'WARN',
Logger::ERROR => 'ERROR',
Logger::FATAL => 'FATAL',
}[sev] || sev.to_s).upcase
if msg.present? && AUTO_DEBUG_PATTERNS.find{|pattern| msg =~ pattern}
return '' if debug_skip?
level = 'DEBUG'
end
if msg.present?
# And we'll expand exceptions so we get as much info as possible.
# If you just want the message, make sure you just pass the message.
if msg.is_a?(::Exception)
msg = "#{msg.message} (#{msg.class})\n#{(msg.backtrace || []).join("\n")}"
elsif !msg.is_a?(::String)
msg = msg.inspect
end
msg = rm_fmt msg
{
level: level,
time: time.strftime('%Y-%m-%d %H:%M:%S'),
message: msg,
app_name: app_name,
app_version: app_version,
process_id: Process.pid,
}.to_json + "\r\n"
else
''
end
end | ruby | def call(sev, time, _, msg) #:nodoc:
level = ({
Logger::DEBUG => 'DEBUG',
Logger::INFO => 'INFO',
Logger::WARN => 'WARN',
Logger::ERROR => 'ERROR',
Logger::FATAL => 'FATAL',
}[sev] || sev.to_s).upcase
if msg.present? && AUTO_DEBUG_PATTERNS.find{|pattern| msg =~ pattern}
return '' if debug_skip?
level = 'DEBUG'
end
if msg.present?
# And we'll expand exceptions so we get as much info as possible.
# If you just want the message, make sure you just pass the message.
if msg.is_a?(::Exception)
msg = "#{msg.message} (#{msg.class})\n#{(msg.backtrace || []).join("\n")}"
elsif !msg.is_a?(::String)
msg = msg.inspect
end
msg = rm_fmt msg
{
level: level,
time: time.strftime('%Y-%m-%d %H:%M:%S'),
message: msg,
app_name: app_name,
app_version: app_version,
process_id: Process.pid,
}.to_json + "\r\n"
else
''
end
end | [
"def",
"call",
"(",
"sev",
",",
"time",
",",
"_",
",",
"msg",
")",
"level",
"=",
"(",
"{",
"Logger",
"::",
"DEBUG",
"=>",
"'DEBUG'",
",",
"Logger",
"::",
"INFO",
"=>",
"'INFO'",
",",
"Logger",
"::",
"WARN",
"=>",
"'WARN'",
",",
"Logger",
"::",
"ERROR",
"=>",
"'ERROR'",
",",
"Logger",
"::",
"FATAL",
"=>",
"'FATAL'",
",",
"}",
"[",
"sev",
"]",
"||",
"sev",
".",
"to_s",
")",
".",
"upcase",
"if",
"msg",
".",
"present?",
"&&",
"AUTO_DEBUG_PATTERNS",
".",
"find",
"{",
"|",
"pattern",
"|",
"msg",
"=~",
"pattern",
"}",
"return",
"''",
"if",
"debug_skip?",
"level",
"=",
"'DEBUG'",
"end",
"if",
"msg",
".",
"present?",
"if",
"msg",
".",
"is_a?",
"(",
"::",
"Exception",
")",
"msg",
"=",
"\"#{msg.message} (#{msg.class})\\n#{(msg.backtrace || []).join(\"\\n\")}\"",
"elsif",
"!",
"msg",
".",
"is_a?",
"(",
"::",
"String",
")",
"msg",
"=",
"msg",
".",
"inspect",
"end",
"msg",
"=",
"rm_fmt",
"msg",
"{",
"level",
":",
"level",
",",
"time",
":",
"time",
".",
"strftime",
"(",
"'%Y-%m-%d %H:%M:%S'",
")",
",",
"message",
":",
"msg",
",",
"app_name",
":",
"app_name",
",",
"app_version",
":",
"app_version",
",",
"process_id",
":",
"Process",
".",
"pid",
",",
"}",
".",
"to_json",
"+",
"\"\\r\\n\"",
"else",
"''",
"end",
"end"
] | Overrides the default formatter behavior to log a JSON line. | [
"Overrides",
"the",
"default",
"formatter",
"behavior",
"to",
"log",
"a",
"JSON",
"line",
"."
] | 1ff08db7aa8ab7f86b223268b700bc67d15bb8aa | https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/json_log_formatter.rb#L17-L53 | train |
ffmike/shoehorn | lib/shoehorn/business_cards.rb | Shoehorn.BusinessCards.estimate_pdf_business_card_report | def estimate_pdf_business_card_report
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.EstimatePdfBusinessCardReport
end
response = connection.post_xml(xml)
document = REXML::Document.new(response)
number_of_cards = document.elements["EstimatePdfBusinessCardReportCallResponse"].elements["NumberOfBusinessCards"].text.to_i rescue 0
number_of_pages = document.elements["EstimatePdfBusinessCardReportCallResponse"].elements["NumberOfPages"].text.to_i rescue 0
return number_of_cards, number_of_pages
end | ruby | def estimate_pdf_business_card_report
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.EstimatePdfBusinessCardReport
end
response = connection.post_xml(xml)
document = REXML::Document.new(response)
number_of_cards = document.elements["EstimatePdfBusinessCardReportCallResponse"].elements["NumberOfBusinessCards"].text.to_i rescue 0
number_of_pages = document.elements["EstimatePdfBusinessCardReportCallResponse"].elements["NumberOfPages"].text.to_i rescue 0
return number_of_cards, number_of_pages
end | [
"def",
"estimate_pdf_business_card_report",
"xml",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"xml",
".",
"instruct!",
"xml",
".",
"Request",
"(",
":xmlns",
"=>",
"\"urn:sbx:apis:SbxBaseComponents\"",
")",
"do",
"|",
"xml",
"|",
"connection",
".",
"requester_credentials_block",
"(",
"xml",
")",
"xml",
".",
"EstimatePdfBusinessCardReport",
"end",
"response",
"=",
"connection",
".",
"post_xml",
"(",
"xml",
")",
"document",
"=",
"REXML",
"::",
"Document",
".",
"new",
"(",
"response",
")",
"number_of_cards",
"=",
"document",
".",
"elements",
"[",
"\"EstimatePdfBusinessCardReportCallResponse\"",
"]",
".",
"elements",
"[",
"\"NumberOfBusinessCards\"",
"]",
".",
"text",
".",
"to_i",
"rescue",
"0",
"number_of_pages",
"=",
"document",
".",
"elements",
"[",
"\"EstimatePdfBusinessCardReportCallResponse\"",
"]",
".",
"elements",
"[",
"\"NumberOfPages\"",
"]",
".",
"text",
".",
"to_i",
"rescue",
"0",
"return",
"number_of_cards",
",",
"number_of_pages",
"end"
] | Returns the estimated number of cards and number of pages for exporting Business Cards as PDF | [
"Returns",
"the",
"estimated",
"number",
"of",
"cards",
"and",
"number",
"of",
"pages",
"for",
"exporting",
"Business",
"Cards",
"as",
"PDF"
] | b3da6d2bc4bd49652ac76197d01077b14bafb70a | https://github.com/ffmike/shoehorn/blob/b3da6d2bc4bd49652ac76197d01077b14bafb70a/lib/shoehorn/business_cards.rb#L56-L68 | train |
ffmike/shoehorn | lib/shoehorn/business_cards.rb | Shoehorn.BusinessCards.generate_pdf_business_card_report | def generate_pdf_business_card_report
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.GeneratePdfBusinessCardReport
end
response = connection.post_xml(xml)
document = REXML::Document.new(response)
document.elements["GeneratePdfBusinessCardReportCallResponse"].elements["URL"].text
end | ruby | def generate_pdf_business_card_report
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.GeneratePdfBusinessCardReport
end
response = connection.post_xml(xml)
document = REXML::Document.new(response)
document.elements["GeneratePdfBusinessCardReportCallResponse"].elements["URL"].text
end | [
"def",
"generate_pdf_business_card_report",
"xml",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"xml",
".",
"instruct!",
"xml",
".",
"Request",
"(",
":xmlns",
"=>",
"\"urn:sbx:apis:SbxBaseComponents\"",
")",
"do",
"|",
"xml",
"|",
"connection",
".",
"requester_credentials_block",
"(",
"xml",
")",
"xml",
".",
"GeneratePdfBusinessCardReport",
"end",
"response",
"=",
"connection",
".",
"post_xml",
"(",
"xml",
")",
"document",
"=",
"REXML",
"::",
"Document",
".",
"new",
"(",
"response",
")",
"document",
".",
"elements",
"[",
"\"GeneratePdfBusinessCardReportCallResponse\"",
"]",
".",
"elements",
"[",
"\"URL\"",
"]",
".",
"text",
"end"
] | Returns a URL for one-time download of Business Cards as PDF | [
"Returns",
"a",
"URL",
"for",
"one",
"-",
"time",
"download",
"of",
"Business",
"Cards",
"as",
"PDF"
] | b3da6d2bc4bd49652ac76197d01077b14bafb70a | https://github.com/ffmike/shoehorn/blob/b3da6d2bc4bd49652ac76197d01077b14bafb70a/lib/shoehorn/business_cards.rb#L71-L81 | train |
ffmike/shoehorn | lib/shoehorn/business_cards.rb | Shoehorn.BusinessCards.notify_preference | def notify_preference
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.GetBusinessCardNotifyPreferenceCall
end
response = connection.post_xml(xml)
document = REXML::Document.new(response)
document.elements["GetBusinessCardNotifyPreferenceCallResponse"].elements["BusinessCardNotifyPreference"].text == "1"
end | ruby | def notify_preference
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.GetBusinessCardNotifyPreferenceCall
end
response = connection.post_xml(xml)
document = REXML::Document.new(response)
document.elements["GetBusinessCardNotifyPreferenceCallResponse"].elements["BusinessCardNotifyPreference"].text == "1"
end | [
"def",
"notify_preference",
"xml",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"xml",
".",
"instruct!",
"xml",
".",
"Request",
"(",
":xmlns",
"=>",
"\"urn:sbx:apis:SbxBaseComponents\"",
")",
"do",
"|",
"xml",
"|",
"connection",
".",
"requester_credentials_block",
"(",
"xml",
")",
"xml",
".",
"GetBusinessCardNotifyPreferenceCall",
"end",
"response",
"=",
"connection",
".",
"post_xml",
"(",
"xml",
")",
"document",
"=",
"REXML",
"::",
"Document",
".",
"new",
"(",
"response",
")",
"document",
".",
"elements",
"[",
"\"GetBusinessCardNotifyPreferenceCallResponse\"",
"]",
".",
"elements",
"[",
"\"BusinessCardNotifyPreference\"",
"]",
".",
"text",
"==",
"\"1\"",
"end"
] | Does the user have business card auto-share mode turned on? | [
"Does",
"the",
"user",
"have",
"business",
"card",
"auto",
"-",
"share",
"mode",
"turned",
"on?"
] | b3da6d2bc4bd49652ac76197d01077b14bafb70a | https://github.com/ffmike/shoehorn/blob/b3da6d2bc4bd49652ac76197d01077b14bafb70a/lib/shoehorn/business_cards.rb#L106-L116 | train |
ffmike/shoehorn | lib/shoehorn/business_cards.rb | Shoehorn.BusinessCards.notify_preference= | def notify_preference=(value)
if value
translated_value = "1"
else
translated_value = "0"
end
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.SetBusinessCardNotifyPreferenceCall do |xml|
xml.BusinessCardNotifyPreference(translated_value)
end
end
response = connection.post_xml(xml)
# TODO: Retrieve the new value to make sure it worked?
value
end | ruby | def notify_preference=(value)
if value
translated_value = "1"
else
translated_value = "0"
end
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.SetBusinessCardNotifyPreferenceCall do |xml|
xml.BusinessCardNotifyPreference(translated_value)
end
end
response = connection.post_xml(xml)
# TODO: Retrieve the new value to make sure it worked?
value
end | [
"def",
"notify_preference",
"=",
"(",
"value",
")",
"if",
"value",
"translated_value",
"=",
"\"1\"",
"else",
"translated_value",
"=",
"\"0\"",
"end",
"xml",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"xml",
".",
"instruct!",
"xml",
".",
"Request",
"(",
":xmlns",
"=>",
"\"urn:sbx:apis:SbxBaseComponents\"",
")",
"do",
"|",
"xml",
"|",
"connection",
".",
"requester_credentials_block",
"(",
"xml",
")",
"xml",
".",
"SetBusinessCardNotifyPreferenceCall",
"do",
"|",
"xml",
"|",
"xml",
".",
"BusinessCardNotifyPreference",
"(",
"translated_value",
")",
"end",
"end",
"response",
"=",
"connection",
".",
"post_xml",
"(",
"xml",
")",
"value",
"end"
] | Turn auto-share mode on or off | [
"Turn",
"auto",
"-",
"share",
"mode",
"on",
"or",
"off"
] | b3da6d2bc4bd49652ac76197d01077b14bafb70a | https://github.com/ffmike/shoehorn/blob/b3da6d2bc4bd49652ac76197d01077b14bafb70a/lib/shoehorn/business_cards.rb#L119-L136 | train |
ffmike/shoehorn | lib/shoehorn/business_cards.rb | Shoehorn.BusinessCards.auto_share_contact_details | def auto_share_contact_details
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.GetAutoShareContactDetailsCall
end
response = connection.post_xml(xml)
details = Hash.new
document = REXML::Document.new(response)
details_element = document.elements["GetAutoShareContactDetailsCallResponse"]
details[:first_name] = details_element.elements["FirstName"].text
details[:last_name] = details_element.elements["LastName"].text
details[:email] = details_element.elements["Email"].text
details[:additional_contact_info] = details_element.elements["AdditionalContactInfo"].text
details
end | ruby | def auto_share_contact_details
xml = Builder::XmlMarkup.new
xml.instruct!
xml.Request(:xmlns => "urn:sbx:apis:SbxBaseComponents") do |xml|
connection.requester_credentials_block(xml)
xml.GetAutoShareContactDetailsCall
end
response = connection.post_xml(xml)
details = Hash.new
document = REXML::Document.new(response)
details_element = document.elements["GetAutoShareContactDetailsCallResponse"]
details[:first_name] = details_element.elements["FirstName"].text
details[:last_name] = details_element.elements["LastName"].text
details[:email] = details_element.elements["Email"].text
details[:additional_contact_info] = details_element.elements["AdditionalContactInfo"].text
details
end | [
"def",
"auto_share_contact_details",
"xml",
"=",
"Builder",
"::",
"XmlMarkup",
".",
"new",
"xml",
".",
"instruct!",
"xml",
".",
"Request",
"(",
":xmlns",
"=>",
"\"urn:sbx:apis:SbxBaseComponents\"",
")",
"do",
"|",
"xml",
"|",
"connection",
".",
"requester_credentials_block",
"(",
"xml",
")",
"xml",
".",
"GetAutoShareContactDetailsCall",
"end",
"response",
"=",
"connection",
".",
"post_xml",
"(",
"xml",
")",
"details",
"=",
"Hash",
".",
"new",
"document",
"=",
"REXML",
"::",
"Document",
".",
"new",
"(",
"response",
")",
"details_element",
"=",
"document",
".",
"elements",
"[",
"\"GetAutoShareContactDetailsCallResponse\"",
"]",
"details",
"[",
":first_name",
"]",
"=",
"details_element",
".",
"elements",
"[",
"\"FirstName\"",
"]",
".",
"text",
"details",
"[",
":last_name",
"]",
"=",
"details_element",
".",
"elements",
"[",
"\"LastName\"",
"]",
".",
"text",
"details",
"[",
":email",
"]",
"=",
"details_element",
".",
"elements",
"[",
"\"Email\"",
"]",
".",
"text",
"details",
"[",
":additional_contact_info",
"]",
"=",
"details_element",
".",
"elements",
"[",
"\"AdditionalContactInfo\"",
"]",
".",
"text",
"details",
"end"
] | Get user's contact information that is sent out with business cards | [
"Get",
"user",
"s",
"contact",
"information",
"that",
"is",
"sent",
"out",
"with",
"business",
"cards"
] | b3da6d2bc4bd49652ac76197d01077b14bafb70a | https://github.com/ffmike/shoehorn/blob/b3da6d2bc4bd49652ac76197d01077b14bafb70a/lib/shoehorn/business_cards.rb#L151-L167 | train |
devnull-tools/yummi | lib/yummi/colorizers.rb | Yummi.Colorizer.color_for | def color_for (arg)
arg = Yummi::Context::new(arg) unless arg.is_a? Context
call(arg)
end | ruby | def color_for (arg)
arg = Yummi::Context::new(arg) unless arg.is_a? Context
call(arg)
end | [
"def",
"color_for",
"(",
"arg",
")",
"arg",
"=",
"Yummi",
"::",
"Context",
"::",
"new",
"(",
"arg",
")",
"unless",
"arg",
".",
"is_a?",
"Context",
"call",
"(",
"arg",
")",
"end"
] | Returns the color for the given value
=== Args
A context or a value. | [
"Returns",
"the",
"color",
"for",
"the",
"given",
"value"
] | b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df | https://github.com/devnull-tools/yummi/blob/b31cc1ef9a9f4ca1c22e0b77a84a1995bde5c2df/lib/yummi/colorizers.rb#L53-L56 | train |
inside-track/remi | lib/remi/data_subjects/csv_file.rb | Remi.Parser::CsvFile.parse | def parse(data)
# Assumes that each file has exactly the same structure
result_df = nil
Array(data).each_with_index do |filename, idx|
filename = filename.to_s
logger.info "Converting #{filename} to a dataframe"
processed_filename = preprocess(filename)
csv_df = Daru::DataFrame.from_csv processed_filename, @csv_options
# Daru 0.1.4 doesn't add vectors if it's a headers-only file
if csv_df.vectors.size == 0
headers_df = Daru::DataFrame.from_csv processed_filename, @csv_options.merge(return_headers: true)
csv_df = Daru::DataFrame.new([], order: headers_df.vectors.to_a)
end
csv_df[@filename_field] = Daru::Vector.new([filename] * csv_df.size, index: csv_df.index) if @filename_field
if idx == 0
result_df = csv_df
else
result_df = result_df.concat csv_df
end
end
Remi::DataFrame.create(:daru, result_df)
end | ruby | def parse(data)
# Assumes that each file has exactly the same structure
result_df = nil
Array(data).each_with_index do |filename, idx|
filename = filename.to_s
logger.info "Converting #{filename} to a dataframe"
processed_filename = preprocess(filename)
csv_df = Daru::DataFrame.from_csv processed_filename, @csv_options
# Daru 0.1.4 doesn't add vectors if it's a headers-only file
if csv_df.vectors.size == 0
headers_df = Daru::DataFrame.from_csv processed_filename, @csv_options.merge(return_headers: true)
csv_df = Daru::DataFrame.new([], order: headers_df.vectors.to_a)
end
csv_df[@filename_field] = Daru::Vector.new([filename] * csv_df.size, index: csv_df.index) if @filename_field
if idx == 0
result_df = csv_df
else
result_df = result_df.concat csv_df
end
end
Remi::DataFrame.create(:daru, result_df)
end | [
"def",
"parse",
"(",
"data",
")",
"result_df",
"=",
"nil",
"Array",
"(",
"data",
")",
".",
"each_with_index",
"do",
"|",
"filename",
",",
"idx",
"|",
"filename",
"=",
"filename",
".",
"to_s",
"logger",
".",
"info",
"\"Converting #{filename} to a dataframe\"",
"processed_filename",
"=",
"preprocess",
"(",
"filename",
")",
"csv_df",
"=",
"Daru",
"::",
"DataFrame",
".",
"from_csv",
"processed_filename",
",",
"@csv_options",
"if",
"csv_df",
".",
"vectors",
".",
"size",
"==",
"0",
"headers_df",
"=",
"Daru",
"::",
"DataFrame",
".",
"from_csv",
"processed_filename",
",",
"@csv_options",
".",
"merge",
"(",
"return_headers",
":",
"true",
")",
"csv_df",
"=",
"Daru",
"::",
"DataFrame",
".",
"new",
"(",
"[",
"]",
",",
"order",
":",
"headers_df",
".",
"vectors",
".",
"to_a",
")",
"end",
"csv_df",
"[",
"@filename_field",
"]",
"=",
"Daru",
"::",
"Vector",
".",
"new",
"(",
"[",
"filename",
"]",
"*",
"csv_df",
".",
"size",
",",
"index",
":",
"csv_df",
".",
"index",
")",
"if",
"@filename_field",
"if",
"idx",
"==",
"0",
"result_df",
"=",
"csv_df",
"else",
"result_df",
"=",
"result_df",
".",
"concat",
"csv_df",
"end",
"end",
"Remi",
"::",
"DataFrame",
".",
"create",
"(",
":daru",
",",
"result_df",
")",
"end"
] | Converts a list of filenames into a dataframe after parsing them
according ot the csv options that were set
@param data [Object] Extracted data that needs to be parsed
@return [Remi::DataFrame] The data converted into a dataframe | [
"Converts",
"a",
"list",
"of",
"filenames",
"into",
"a",
"dataframe",
"after",
"parsing",
"them",
"according",
"ot",
"the",
"csv",
"options",
"that",
"were",
"set"
] | f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7 | https://github.com/inside-track/remi/blob/f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7/lib/remi/data_subjects/csv_file.rb#L71-L96 | train |
inside-track/remi | lib/remi/data_subjects/csv_file.rb | Remi.Encoder::CsvFile.encode | def encode(dataframe)
logger.info "Writing CSV file to temporary location #{@working_file}"
label_columns = self.fields.reduce({}) { |h, (k, v)|
if v[:label]
h[k] = v[:label].to_sym
end
h
}
dataframe.rename_vectors label_columns
dataframe.write_csv @working_file, @csv_options
@working_file
end | ruby | def encode(dataframe)
logger.info "Writing CSV file to temporary location #{@working_file}"
label_columns = self.fields.reduce({}) { |h, (k, v)|
if v[:label]
h[k] = v[:label].to_sym
end
h
}
dataframe.rename_vectors label_columns
dataframe.write_csv @working_file, @csv_options
@working_file
end | [
"def",
"encode",
"(",
"dataframe",
")",
"logger",
".",
"info",
"\"Writing CSV file to temporary location #{@working_file}\"",
"label_columns",
"=",
"self",
".",
"fields",
".",
"reduce",
"(",
"{",
"}",
")",
"{",
"|",
"h",
",",
"(",
"k",
",",
"v",
")",
"|",
"if",
"v",
"[",
":label",
"]",
"h",
"[",
"k",
"]",
"=",
"v",
"[",
":label",
"]",
".",
"to_sym",
"end",
"h",
"}",
"dataframe",
".",
"rename_vectors",
"label_columns",
"dataframe",
".",
"write_csv",
"@working_file",
",",
"@csv_options",
"@working_file",
"end"
] | Converts the dataframe to a CSV file stored in the local work directory.
If labels are present write the CSV file with those headers but maintain
the structure of the original dataframe
@param dataframe [Remi::DataFrame] The dataframe to be encoded
@return [Object] The path to the file | [
"Converts",
"the",
"dataframe",
"to",
"a",
"CSV",
"file",
"stored",
"in",
"the",
"local",
"work",
"directory",
".",
"If",
"labels",
"are",
"present",
"write",
"the",
"CSV",
"file",
"with",
"those",
"headers",
"but",
"maintain",
"the",
"structure",
"of",
"the",
"original",
"dataframe"
] | f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7 | https://github.com/inside-track/remi/blob/f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7/lib/remi/data_subjects/csv_file.rb#L167-L179 | train |
riddopic/garcun | lib/garcon/task/immediate_executor.rb | Garcon.ImmediateExecutor.post | def post(*args, &task)
raise ArgumentError, 'no block given' unless block_given?
return false unless running?
task.call(*args)
true
end | ruby | def post(*args, &task)
raise ArgumentError, 'no block given' unless block_given?
return false unless running?
task.call(*args)
true
end | [
"def",
"post",
"(",
"*",
"args",
",",
"&",
"task",
")",
"raise",
"ArgumentError",
",",
"'no block given'",
"unless",
"block_given?",
"return",
"false",
"unless",
"running?",
"task",
".",
"call",
"(",
"*",
"args",
")",
"true",
"end"
] | Creates a new executor
@!macro executor_method_post | [
"Creates",
"a",
"new",
"executor"
] | c2409bd8cf9c14b967a719810dab5269d69b42de | https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/immediate_executor.rb#L44-L49 | train |
DigitPaint/html_mockup | lib/html_mockup/template.rb | HtmlMockup.Template.target_extension | def target_extension
return @target_extension if @target_extension
if type = MIME::Types[self.target_mime_type].first
# Dirty little hack to enforce the use of .html instead of .htm
if type.sub_type == "html"
@target_extension = "html"
else
@target_extension = type.extensions.first
end
else
@target_extension = File.extname(self.source_path.to_s).sub(/^\./, "")
end
end | ruby | def target_extension
return @target_extension if @target_extension
if type = MIME::Types[self.target_mime_type].first
# Dirty little hack to enforce the use of .html instead of .htm
if type.sub_type == "html"
@target_extension = "html"
else
@target_extension = type.extensions.first
end
else
@target_extension = File.extname(self.source_path.to_s).sub(/^\./, "")
end
end | [
"def",
"target_extension",
"return",
"@target_extension",
"if",
"@target_extension",
"if",
"type",
"=",
"MIME",
"::",
"Types",
"[",
"self",
".",
"target_mime_type",
"]",
".",
"first",
"if",
"type",
".",
"sub_type",
"==",
"\"html\"",
"@target_extension",
"=",
"\"html\"",
"else",
"@target_extension",
"=",
"type",
".",
"extensions",
".",
"first",
"end",
"else",
"@target_extension",
"=",
"File",
".",
"extname",
"(",
"self",
".",
"source_path",
".",
"to_s",
")",
".",
"sub",
"(",
"/",
"\\.",
"/",
",",
"\"\"",
")",
"end",
"end"
] | Try to infer the final extension of the output file. | [
"Try",
"to",
"infer",
"the",
"final",
"extension",
"of",
"the",
"output",
"file",
"."
] | 976edadc01216b82a8cea177f53fb32559eaf41e | https://github.com/DigitPaint/html_mockup/blob/976edadc01216b82a8cea177f53fb32559eaf41e/lib/html_mockup/template.rb#L79-L92 | train |
meloncargo/dragonfly-azure_data_store | lib/dragonfly/azure_data_store.rb | Dragonfly.AzureDataStore.update_metadata | def update_metadata(uid)
return false unless store_meta
path = full_path(uid)
meta = storage(:get_blob, container_name, path)[0].metadata
return false if meta.present?
meta = meta_from_file(path)
return false if meta.blank?
storage(:set_blob_metadata, container_name, path, meta)
storage(:delete_blob, container_name, meta_path(path))
true
rescue Azure::Core::Http::HTTPError
nil
end | ruby | def update_metadata(uid)
return false unless store_meta
path = full_path(uid)
meta = storage(:get_blob, container_name, path)[0].metadata
return false if meta.present?
meta = meta_from_file(path)
return false if meta.blank?
storage(:set_blob_metadata, container_name, path, meta)
storage(:delete_blob, container_name, meta_path(path))
true
rescue Azure::Core::Http::HTTPError
nil
end | [
"def",
"update_metadata",
"(",
"uid",
")",
"return",
"false",
"unless",
"store_meta",
"path",
"=",
"full_path",
"(",
"uid",
")",
"meta",
"=",
"storage",
"(",
":get_blob",
",",
"container_name",
",",
"path",
")",
"[",
"0",
"]",
".",
"metadata",
"return",
"false",
"if",
"meta",
".",
"present?",
"meta",
"=",
"meta_from_file",
"(",
"path",
")",
"return",
"false",
"if",
"meta",
".",
"blank?",
"storage",
"(",
":set_blob_metadata",
",",
"container_name",
",",
"path",
",",
"meta",
")",
"storage",
"(",
":delete_blob",
",",
"container_name",
",",
"meta_path",
"(",
"path",
")",
")",
"true",
"rescue",
"Azure",
"::",
"Core",
"::",
"Http",
"::",
"HTTPError",
"nil",
"end"
] | Updates metadata of file and deletes old meta file from legacy mode. | [
"Updates",
"metadata",
"of",
"file",
"and",
"deletes",
"old",
"meta",
"file",
"from",
"legacy",
"mode",
"."
] | fd7d1e7507660fc2f5bc7dae8d9dbb2bfc634dc4 | https://github.com/meloncargo/dragonfly-azure_data_store/blob/fd7d1e7507660fc2f5bc7dae8d9dbb2bfc634dc4/lib/dragonfly/azure_data_store.rb#L46-L58 | train |
Thermatix/ruta | lib/ruta/router.rb | Ruta.Router.map | def map ref,route, options={}
context = Context.collection[get_context]
context.routes[ref]= Route.new(route, context,options)
end | ruby | def map ref,route, options={}
context = Context.collection[get_context]
context.routes[ref]= Route.new(route, context,options)
end | [
"def",
"map",
"ref",
",",
"route",
",",
"options",
"=",
"{",
"}",
"context",
"=",
"Context",
".",
"collection",
"[",
"get_context",
"]",
"context",
".",
"routes",
"[",
"ref",
"]",
"=",
"Route",
".",
"new",
"(",
"route",
",",
"context",
",",
"options",
")",
"end"
] | map a route
@param [Symbol] ref to map route to for easy future reference | [
"map",
"a",
"route"
] | b4a6e3bc7c0c4b66c804023d638b173e3f61e157 | https://github.com/Thermatix/ruta/blob/b4a6e3bc7c0c4b66c804023d638b173e3f61e157/lib/ruta/router.rb#L32-L35 | train |
Thermatix/ruta | lib/ruta/router.rb | Ruta.Router.root_to | def root_to reference
Router.set_root_to reference
context = Context.collection[reference]
context.routes[:root]= Route.new('/', context,{ context: reference})
end | ruby | def root_to reference
Router.set_root_to reference
context = Context.collection[reference]
context.routes[:root]= Route.new('/', context,{ context: reference})
end | [
"def",
"root_to",
"reference",
"Router",
".",
"set_root_to",
"reference",
"context",
"=",
"Context",
".",
"collection",
"[",
"reference",
"]",
"context",
".",
"routes",
"[",
":root",
"]",
"=",
"Route",
".",
"new",
"(",
"'/'",
",",
"context",
",",
"{",
"context",
":",
"reference",
"}",
")",
"end"
] | set the root context, this is the initial context that will be renered by the router
@note there is only ever one root, calling this multiple times will over right the original root
@param [Symbol] reference to context | [
"set",
"the",
"root",
"context",
"this",
"is",
"the",
"initial",
"context",
"that",
"will",
"be",
"renered",
"by",
"the",
"router"
] | b4a6e3bc7c0c4b66c804023d638b173e3f61e157 | https://github.com/Thermatix/ruta/blob/b4a6e3bc7c0c4b66c804023d638b173e3f61e157/lib/ruta/router.rb#L41-L45 | train |
maynard/kenna | lib/kenna.rb | Kenna.Api.fakeUser | def fakeUser
@roles = ['administrator', 'normal user', 'Linux Test Environment']
@role = @roles[rand(0..2)]
@fake_user = {
"user":
{
"firstname": Faker::Name.first_name,
"lastname": Faker::Name.last_name,
"email": Faker::Internet.email,
"role": @role
}
}
end | ruby | def fakeUser
@roles = ['administrator', 'normal user', 'Linux Test Environment']
@role = @roles[rand(0..2)]
@fake_user = {
"user":
{
"firstname": Faker::Name.first_name,
"lastname": Faker::Name.last_name,
"email": Faker::Internet.email,
"role": @role
}
}
end | [
"def",
"fakeUser",
"@roles",
"=",
"[",
"'administrator'",
",",
"'normal user'",
",",
"'Linux Test Environment'",
"]",
"@role",
"=",
"@roles",
"[",
"rand",
"(",
"0",
"..",
"2",
")",
"]",
"@fake_user",
"=",
"{",
"\"user\"",
":",
"{",
"\"firstname\"",
":",
"Faker",
"::",
"Name",
".",
"first_name",
",",
"\"lastname\"",
":",
"Faker",
"::",
"Name",
".",
"last_name",
",",
"\"email\"",
":",
"Faker",
"::",
"Internet",
".",
"email",
",",
"\"role\"",
":",
"@role",
"}",
"}",
"end"
] | Generate a unique fake user for testing | [
"Generate",
"a",
"unique",
"fake",
"user",
"for",
"testing"
] | 71eebceccf37ac571d1bd161c4cfaa0a276fe513 | https://github.com/maynard/kenna/blob/71eebceccf37ac571d1bd161c4cfaa0a276fe513/lib/kenna.rb#L106-L118 | train |
chrisjones-tripletri/action_command | lib/action_command/log_parser.rb | ActionCommand.LogMessage.populate | def populate(line, msg)
@line = line
@sequence = msg['sequence']
@depth = msg['depth']
@cmd = msg['cmd']
@kind = msg['kind']
@msg = msg['msg']
@key = msg['key']
end | ruby | def populate(line, msg)
@line = line
@sequence = msg['sequence']
@depth = msg['depth']
@cmd = msg['cmd']
@kind = msg['kind']
@msg = msg['msg']
@key = msg['key']
end | [
"def",
"populate",
"(",
"line",
",",
"msg",
")",
"@line",
"=",
"line",
"@sequence",
"=",
"msg",
"[",
"'sequence'",
"]",
"@depth",
"=",
"msg",
"[",
"'depth'",
"]",
"@cmd",
"=",
"msg",
"[",
"'cmd'",
"]",
"@kind",
"=",
"msg",
"[",
"'kind'",
"]",
"@msg",
"=",
"msg",
"[",
"'msg'",
"]",
"@key",
"=",
"msg",
"[",
"'key'",
"]",
"end"
] | Create a new log message | [
"Create",
"a",
"new",
"log",
"message"
] | 9b9a8ba30e407ca6d88a62a164d1dc22ba149874 | https://github.com/chrisjones-tripletri/action_command/blob/9b9a8ba30e407ca6d88a62a164d1dc22ba149874/lib/action_command/log_parser.rb#L11-L19 | train |
chrisjones-tripletri/action_command | lib/action_command/log_parser.rb | ActionCommand.LogParser.next | def next(msg)
# be tolerant of the fact that there might be other
# stuff in the log file.
next_line do |input, line|
if input.key?('sequence')
msg.populate(line, input) unless @sequence && @sequence != input['sequence']
return true
end
end
return false
end | ruby | def next(msg)
# be tolerant of the fact that there might be other
# stuff in the log file.
next_line do |input, line|
if input.key?('sequence')
msg.populate(line, input) unless @sequence && @sequence != input['sequence']
return true
end
end
return false
end | [
"def",
"next",
"(",
"msg",
")",
"next_line",
"do",
"|",
"input",
",",
"line",
"|",
"if",
"input",
".",
"key?",
"(",
"'sequence'",
")",
"msg",
".",
"populate",
"(",
"line",
",",
"input",
")",
"unless",
"@sequence",
"&&",
"@sequence",
"!=",
"input",
"[",
"'sequence'",
"]",
"return",
"true",
"end",
"end",
"return",
"false",
"end"
] | Populates a message from the next line in the | [
"Populates",
"a",
"message",
"from",
"the",
"next",
"line",
"in",
"the"
] | 9b9a8ba30e407ca6d88a62a164d1dc22ba149874 | https://github.com/chrisjones-tripletri/action_command/blob/9b9a8ba30e407ca6d88a62a164d1dc22ba149874/lib/action_command/log_parser.rb#L80-L90 | train |
codescrum/bebox | lib/bebox/project.rb | Bebox.Project.generate_ruby_version | def generate_ruby_version
ruby_version = (RUBY_PATCHLEVEL == 0) ? RUBY_VERSION : "#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}"
File.open("#{self.path}/.ruby-version", 'w') do |f|
f.write ruby_version
end
end | ruby | def generate_ruby_version
ruby_version = (RUBY_PATCHLEVEL == 0) ? RUBY_VERSION : "#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}"
File.open("#{self.path}/.ruby-version", 'w') do |f|
f.write ruby_version
end
end | [
"def",
"generate_ruby_version",
"ruby_version",
"=",
"(",
"RUBY_PATCHLEVEL",
"==",
"0",
")",
"?",
"RUBY_VERSION",
":",
"\"#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}\"",
"File",
".",
"open",
"(",
"\"#{self.path}/.ruby-version\"",
",",
"'w'",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"ruby_version",
"end",
"end"
] | Create rbenv local | [
"Create",
"rbenv",
"local"
] | 0d19315847103341e599d32837ab0bd75524e5be | https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/project.rb#L84-L89 | train |
codescrum/bebox | lib/bebox/project.rb | Bebox.Project.generate_steps_templates | def generate_steps_templates
Bebox::PROVISION_STEPS.each do |step|
ssh_key = ''
step_dir = Bebox::Provision.step_name(step)
templates_path = Bebox::Project::templates_path
# Generate site.pp template
generate_file_from_template("#{templates_path}/puppet/#{step}/manifests/site.pp.erb", "#{self.path}/puppet/steps/#{step_dir}/manifests/site.pp", {nodes: []})
# Generate hiera.yaml template
generate_file_from_template("#{templates_path}/puppet/#{step}/hiera/hiera.yaml.erb", "#{self.path}/puppet/steps/#{step_dir}/hiera/hiera.yaml", {step_dir: step_dir})
# Generate common.yaml template
generate_file_from_template("#{templates_path}/puppet/#{step}/hiera/data/common.yaml.erb", "#{self.path}/puppet/steps/#{step_dir}/hiera/data/common.yaml", {step_dir: step_dir, ssh_key: ssh_key, project_name: self.shortname})
end
end | ruby | def generate_steps_templates
Bebox::PROVISION_STEPS.each do |step|
ssh_key = ''
step_dir = Bebox::Provision.step_name(step)
templates_path = Bebox::Project::templates_path
# Generate site.pp template
generate_file_from_template("#{templates_path}/puppet/#{step}/manifests/site.pp.erb", "#{self.path}/puppet/steps/#{step_dir}/manifests/site.pp", {nodes: []})
# Generate hiera.yaml template
generate_file_from_template("#{templates_path}/puppet/#{step}/hiera/hiera.yaml.erb", "#{self.path}/puppet/steps/#{step_dir}/hiera/hiera.yaml", {step_dir: step_dir})
# Generate common.yaml template
generate_file_from_template("#{templates_path}/puppet/#{step}/hiera/data/common.yaml.erb", "#{self.path}/puppet/steps/#{step_dir}/hiera/data/common.yaml", {step_dir: step_dir, ssh_key: ssh_key, project_name: self.shortname})
end
end | [
"def",
"generate_steps_templates",
"Bebox",
"::",
"PROVISION_STEPS",
".",
"each",
"do",
"|",
"step",
"|",
"ssh_key",
"=",
"''",
"step_dir",
"=",
"Bebox",
"::",
"Provision",
".",
"step_name",
"(",
"step",
")",
"templates_path",
"=",
"Bebox",
"::",
"Project",
"::",
"templates_path",
"generate_file_from_template",
"(",
"\"#{templates_path}/puppet/#{step}/manifests/site.pp.erb\"",
",",
"\"#{self.path}/puppet/steps/#{step_dir}/manifests/site.pp\"",
",",
"{",
"nodes",
":",
"[",
"]",
"}",
")",
"generate_file_from_template",
"(",
"\"#{templates_path}/puppet/#{step}/hiera/hiera.yaml.erb\"",
",",
"\"#{self.path}/puppet/steps/#{step_dir}/hiera/hiera.yaml\"",
",",
"{",
"step_dir",
":",
"step_dir",
"}",
")",
"generate_file_from_template",
"(",
"\"#{templates_path}/puppet/#{step}/hiera/data/common.yaml.erb\"",
",",
"\"#{self.path}/puppet/steps/#{step_dir}/hiera/data/common.yaml\"",
",",
"{",
"step_dir",
":",
"step_dir",
",",
"ssh_key",
":",
"ssh_key",
",",
"project_name",
":",
"self",
".",
"shortname",
"}",
")",
"end",
"end"
] | Generate steps templates for hiera and manifests files | [
"Generate",
"steps",
"templates",
"for",
"hiera",
"and",
"manifests",
"files"
] | 0d19315847103341e599d32837ab0bd75524e5be | https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/project.rb#L165-L177 | train |
codescrum/bebox | lib/bebox/wizards/provision_wizard.rb | Bebox.ProvisionWizard.apply_step | def apply_step(project_root, environment, step)
# Check if environment has configured the ssh keys
(return warn _('wizard.provision.ssh_key_advice')%{environment: environment}) unless Bebox::Environment.check_environment_access(project_root, environment)
nodes_to_step = Bebox::Node.nodes_in_environment(project_root, environment, previous_checkpoint(step))
# Check if there are nodes for provisioning step-N
(return warn _('wizard.provision.no_provision_nodes')%{step: step}) unless nodes_to_step.count > 0
nodes_for_provisioning(nodes_to_step, step)
# Apply the nodes provisioning for step-N
in_step_nodes = Bebox::Node.list(project_root, environment, "steps/#{step}")
outputs = []
nodes_to_step.each do |node|
next unless check_node_to_step(node, in_step_nodes, step)
outputs << provision_step_in_node(project_root, environment, step, in_step_nodes, node)
end
return outputs
end | ruby | def apply_step(project_root, environment, step)
# Check if environment has configured the ssh keys
(return warn _('wizard.provision.ssh_key_advice')%{environment: environment}) unless Bebox::Environment.check_environment_access(project_root, environment)
nodes_to_step = Bebox::Node.nodes_in_environment(project_root, environment, previous_checkpoint(step))
# Check if there are nodes for provisioning step-N
(return warn _('wizard.provision.no_provision_nodes')%{step: step}) unless nodes_to_step.count > 0
nodes_for_provisioning(nodes_to_step, step)
# Apply the nodes provisioning for step-N
in_step_nodes = Bebox::Node.list(project_root, environment, "steps/#{step}")
outputs = []
nodes_to_step.each do |node|
next unless check_node_to_step(node, in_step_nodes, step)
outputs << provision_step_in_node(project_root, environment, step, in_step_nodes, node)
end
return outputs
end | [
"def",
"apply_step",
"(",
"project_root",
",",
"environment",
",",
"step",
")",
"(",
"return",
"warn",
"_",
"(",
"'wizard.provision.ssh_key_advice'",
")",
"%",
"{",
"environment",
":",
"environment",
"}",
")",
"unless",
"Bebox",
"::",
"Environment",
".",
"check_environment_access",
"(",
"project_root",
",",
"environment",
")",
"nodes_to_step",
"=",
"Bebox",
"::",
"Node",
".",
"nodes_in_environment",
"(",
"project_root",
",",
"environment",
",",
"previous_checkpoint",
"(",
"step",
")",
")",
"(",
"return",
"warn",
"_",
"(",
"'wizard.provision.no_provision_nodes'",
")",
"%",
"{",
"step",
":",
"step",
"}",
")",
"unless",
"nodes_to_step",
".",
"count",
">",
"0",
"nodes_for_provisioning",
"(",
"nodes_to_step",
",",
"step",
")",
"in_step_nodes",
"=",
"Bebox",
"::",
"Node",
".",
"list",
"(",
"project_root",
",",
"environment",
",",
"\"steps/#{step}\"",
")",
"outputs",
"=",
"[",
"]",
"nodes_to_step",
".",
"each",
"do",
"|",
"node",
"|",
"next",
"unless",
"check_node_to_step",
"(",
"node",
",",
"in_step_nodes",
",",
"step",
")",
"outputs",
"<<",
"provision_step_in_node",
"(",
"project_root",
",",
"environment",
",",
"step",
",",
"in_step_nodes",
",",
"node",
")",
"end",
"return",
"outputs",
"end"
] | Apply a step for the nodes in a environment | [
"Apply",
"a",
"step",
"for",
"the",
"nodes",
"in",
"a",
"environment"
] | 0d19315847103341e599d32837ab0bd75524e5be | https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/provision_wizard.rb#L7-L22 | train |
GemHQ/coin-op | lib/coin-op/bit/fee.rb | CoinOp::Bit.Fee.estimate | def estimate(unspents, payees, network:, tx_size: nil, fee_per_kb: nil)
# https://en.bitcoin.it/wiki/Transaction_fees
# dupe because we'll need to add a change output
payees = payees.dup
unspent_total = unspents.inject(0) { |sum, output| sum += output.value }
payee_total = payees.inject(0) { |sum, payee| sum += payee.value }
nominal_change = unspent_total - payee_total
payees << Output.new(value: nominal_change, network: network) if nominal_change > 0
tx_size ||= estimate_tx_size(unspents, payees)
# conditions for 0-fee transactions
small = tx_size < 1000
min_payee = payees.min_by { |payee| payee.value }
big_outputs = min_payee.value > 1_000_000
high_priority = priority(
size: tx_size,
unspents: unspents.map { |output| { value: output.value, age: output.confirmations } }
) > PRIORITY_THRESHOLD
# 0-fee requirements met
return 0 if small && big_outputs && high_priority
# Otherwise, calculate the fee by size
fee_for_bytes(tx_size, network: network, fee_per_kb: fee_per_kb)
end | ruby | def estimate(unspents, payees, network:, tx_size: nil, fee_per_kb: nil)
# https://en.bitcoin.it/wiki/Transaction_fees
# dupe because we'll need to add a change output
payees = payees.dup
unspent_total = unspents.inject(0) { |sum, output| sum += output.value }
payee_total = payees.inject(0) { |sum, payee| sum += payee.value }
nominal_change = unspent_total - payee_total
payees << Output.new(value: nominal_change, network: network) if nominal_change > 0
tx_size ||= estimate_tx_size(unspents, payees)
# conditions for 0-fee transactions
small = tx_size < 1000
min_payee = payees.min_by { |payee| payee.value }
big_outputs = min_payee.value > 1_000_000
high_priority = priority(
size: tx_size,
unspents: unspents.map { |output| { value: output.value, age: output.confirmations } }
) > PRIORITY_THRESHOLD
# 0-fee requirements met
return 0 if small && big_outputs && high_priority
# Otherwise, calculate the fee by size
fee_for_bytes(tx_size, network: network, fee_per_kb: fee_per_kb)
end | [
"def",
"estimate",
"(",
"unspents",
",",
"payees",
",",
"network",
":",
",",
"tx_size",
":",
"nil",
",",
"fee_per_kb",
":",
"nil",
")",
"payees",
"=",
"payees",
".",
"dup",
"unspent_total",
"=",
"unspents",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"sum",
",",
"output",
"|",
"sum",
"+=",
"output",
".",
"value",
"}",
"payee_total",
"=",
"payees",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"sum",
",",
"payee",
"|",
"sum",
"+=",
"payee",
".",
"value",
"}",
"nominal_change",
"=",
"unspent_total",
"-",
"payee_total",
"payees",
"<<",
"Output",
".",
"new",
"(",
"value",
":",
"nominal_change",
",",
"network",
":",
"network",
")",
"if",
"nominal_change",
">",
"0",
"tx_size",
"||=",
"estimate_tx_size",
"(",
"unspents",
",",
"payees",
")",
"small",
"=",
"tx_size",
"<",
"1000",
"min_payee",
"=",
"payees",
".",
"min_by",
"{",
"|",
"payee",
"|",
"payee",
".",
"value",
"}",
"big_outputs",
"=",
"min_payee",
".",
"value",
">",
"1_000_000",
"high_priority",
"=",
"priority",
"(",
"size",
":",
"tx_size",
",",
"unspents",
":",
"unspents",
".",
"map",
"{",
"|",
"output",
"|",
"{",
"value",
":",
"output",
".",
"value",
",",
"age",
":",
"output",
".",
"confirmations",
"}",
"}",
")",
">",
"PRIORITY_THRESHOLD",
"return",
"0",
"if",
"small",
"&&",
"big_outputs",
"&&",
"high_priority",
"fee_for_bytes",
"(",
"tx_size",
",",
"network",
":",
"network",
",",
"fee_per_kb",
":",
"fee_per_kb",
")",
"end"
] | Given an array of unspent Outputs and an array of Outputs for a
Transaction, estimate the fee required for the transaction to be
included in a block.
Optionally takes an Integer tx_size specifying the transaction size in bytes
This is useful if you have the scriptSigs for the unspents, because
you can get a more accurate size than the estimate which is generated
here by default
Optionally takes an Integer fee_per_kb specifying the chosen cost per 1000
bytes to use
Returns the estimated fee in satoshis. | [
"Given",
"an",
"array",
"of",
"unspent",
"Outputs",
"and",
"an",
"array",
"of",
"Outputs",
"for",
"a",
"Transaction",
"estimate",
"the",
"fee",
"required",
"for",
"the",
"transaction",
"to",
"be",
"included",
"in",
"a",
"block",
"."
] | 0b704b52d9826405cffb1606e914bf21b8dcc681 | https://github.com/GemHQ/coin-op/blob/0b704b52d9826405cffb1606e914bf21b8dcc681/lib/coin-op/bit/fee.rb#L28-L57 | train |
Thoughtwright-LLC/httpmagic | lib/http_magic/api.rb | HttpMagic.Api.post | def post(data = {})
request = Request.new(@uri,
headers: @headers,
data: data,
)
request.post
end | ruby | def post(data = {})
request = Request.new(@uri,
headers: @headers,
data: data,
)
request.post
end | [
"def",
"post",
"(",
"data",
"=",
"{",
"}",
")",
"request",
"=",
"Request",
".",
"new",
"(",
"@uri",
",",
"headers",
":",
"@headers",
",",
"data",
":",
"data",
",",
")",
"request",
".",
"post",
"end"
] | POST's a resource from the URI and returns the result based on its content
type. JSON content will be parsed and returned as equivalent Ruby objects.
All other content types will be returned as text.
Assuming an api where each resource is namespaced with 'api/v1' and where
the url http://www.example.com/api/v1/foo/create responds with the
following when a 'name' is sent with the request.
Header:
Content-Type: application/json
Body:
{
"name": "New Foo"
}
== Example
class ExampleApi < HttpMagic::Api
url 'www.example.com'
namespace 'api/v1'
end
ExampleApi.foo.create.post(name: 'New Foo')
=> { "name" => "New Foo" } | [
"POST",
"s",
"a",
"resource",
"from",
"the",
"URI",
"and",
"returns",
"the",
"result",
"based",
"on",
"its",
"content",
"type",
".",
"JSON",
"content",
"will",
"be",
"parsed",
"and",
"returned",
"as",
"equivalent",
"Ruby",
"objects",
".",
"All",
"other",
"content",
"types",
"will",
"be",
"returned",
"as",
"text",
"."
] | e37dba9965eae7252a6f9e5c5a6641683a275a75 | https://github.com/Thoughtwright-LLC/httpmagic/blob/e37dba9965eae7252a6f9e5c5a6641683a275a75/lib/http_magic/api.rb#L220-L226 | train |
Thoughtwright-LLC/httpmagic | lib/http_magic/api.rb | HttpMagic.Api.put | def put(data = {})
request = Request.new(@uri,
headers: @headers,
data: data,
)
request.put
end | ruby | def put(data = {})
request = Request.new(@uri,
headers: @headers,
data: data,
)
request.put
end | [
"def",
"put",
"(",
"data",
"=",
"{",
"}",
")",
"request",
"=",
"Request",
".",
"new",
"(",
"@uri",
",",
"headers",
":",
"@headers",
",",
"data",
":",
"data",
",",
")",
"request",
".",
"put",
"end"
] | PUT's a resource to the URI and returns the result based on its content
type. JSON content will be parsed and returned as equivalent Ruby objects.
All other content types will be returned as text.
Assuming an api where each resource is namespaced with 'api/v1' and where
a GET to the url http://www.example.com/api/v1/foo/99 responds with the
following.
Header:
Content-Type: application/json
Body:
{
"name": "Foo"
}
== Example
class ExampleApi < HttpMagic::Api
url 'www.example.com'
namespace 'api/v1'
end
ExampleApi.foo[99].put(name: 'Changed Foo')
=> { "name" => "Changed Foo" } | [
"PUT",
"s",
"a",
"resource",
"to",
"the",
"URI",
"and",
"returns",
"the",
"result",
"based",
"on",
"its",
"content",
"type",
".",
"JSON",
"content",
"will",
"be",
"parsed",
"and",
"returned",
"as",
"equivalent",
"Ruby",
"objects",
".",
"All",
"other",
"content",
"types",
"will",
"be",
"returned",
"as",
"text",
"."
] | e37dba9965eae7252a6f9e5c5a6641683a275a75 | https://github.com/Thoughtwright-LLC/httpmagic/blob/e37dba9965eae7252a6f9e5c5a6641683a275a75/lib/http_magic/api.rb#L255-L261 | train |
mayth/Chizuru | lib/chizuru/bot.rb | Chizuru.Bot.consumer | def consumer(cons, *init_args, &block)
if cons.instance_of? Class
cons = cons.new(*init_args)
end
ch = ConsumerHelper.new(cons, credential)
ch.instance_eval &block
provider.add_consumer(ch.consumer)
end | ruby | def consumer(cons, *init_args, &block)
if cons.instance_of? Class
cons = cons.new(*init_args)
end
ch = ConsumerHelper.new(cons, credential)
ch.instance_eval &block
provider.add_consumer(ch.consumer)
end | [
"def",
"consumer",
"(",
"cons",
",",
"*",
"init_args",
",",
"&",
"block",
")",
"if",
"cons",
".",
"instance_of?",
"Class",
"cons",
"=",
"cons",
".",
"new",
"(",
"*",
"init_args",
")",
"end",
"ch",
"=",
"ConsumerHelper",
".",
"new",
"(",
"cons",
",",
"credential",
")",
"ch",
".",
"instance_eval",
"&",
"block",
"provider",
".",
"add_consumer",
"(",
"ch",
".",
"consumer",
")",
"end"
] | Adds a consumer.
* If an instance of Consumer or its subclasses is given, it is used.
* If Class is given, initialize its instance, and use it. In this case, the rest arguments are passed to the constructor of the given class. | [
"Adds",
"a",
"consumer",
"."
] | 361bc595c2e4257313d134fe0f4f4cca65c88383 | https://github.com/mayth/Chizuru/blob/361bc595c2e4257313d134fe0f4f4cca65c88383/lib/chizuru/bot.rb#L46-L53 | train |
RISCfuture/has_metadata_column | lib/has_metadata_column.rb | HasMetadataColumn.Extensions.attribute | def attribute(attr)
return super unless self.class.metadata_column_fields.include?(attr.to_sym)
options = self.class.metadata_column_fields[attr.to_sym] || {}
default = options.include?(:default) ? options[:default] : nil
_metadata_hash.include?(attr) ? HasMetadataColumn.metadata_typecast(_metadata_hash[attr], options[:type]) : default
end | ruby | def attribute(attr)
return super unless self.class.metadata_column_fields.include?(attr.to_sym)
options = self.class.metadata_column_fields[attr.to_sym] || {}
default = options.include?(:default) ? options[:default] : nil
_metadata_hash.include?(attr) ? HasMetadataColumn.metadata_typecast(_metadata_hash[attr], options[:type]) : default
end | [
"def",
"attribute",
"(",
"attr",
")",
"return",
"super",
"unless",
"self",
".",
"class",
".",
"metadata_column_fields",
".",
"include?",
"(",
"attr",
".",
"to_sym",
")",
"options",
"=",
"self",
".",
"class",
".",
"metadata_column_fields",
"[",
"attr",
".",
"to_sym",
"]",
"||",
"{",
"}",
"default",
"=",
"options",
".",
"include?",
"(",
":default",
")",
"?",
"options",
"[",
":default",
"]",
":",
"nil",
"_metadata_hash",
".",
"include?",
"(",
"attr",
")",
"?",
"HasMetadataColumn",
".",
"metadata_typecast",
"(",
"_metadata_hash",
"[",
"attr",
"]",
",",
"options",
"[",
":type",
"]",
")",
":",
"default",
"end"
] | ATTRIBUTE MATCHER METHODS | [
"ATTRIBUTE",
"MATCHER",
"METHODS"
] | cd9793dfd137fac0c8d5168f83623347157c6f98 | https://github.com/RISCfuture/has_metadata_column/blob/cd9793dfd137fac0c8d5168f83623347157c6f98/lib/has_metadata_column.rb#L251-L257 | train |
riddopic/hoodie | lib/hoodie/utils/ansi.rb | Hoodie.ANSI.build_ansi_methods | def build_ansi_methods(hash)
hash.each do |key, value|
define_method(key) do |string=nil, &block|
result = Array.new
result << %(\e[#{value}m)
if block_given?
result << block.call
elsif string.respond_to?(:to_str)
result << string.to_str
elsif respond_to?(:to_str)
result << to_str
else
return result
end
result << %(\e[0m)
result.join
end
end
true
end | ruby | def build_ansi_methods(hash)
hash.each do |key, value|
define_method(key) do |string=nil, &block|
result = Array.new
result << %(\e[#{value}m)
if block_given?
result << block.call
elsif string.respond_to?(:to_str)
result << string.to_str
elsif respond_to?(:to_str)
result << to_str
else
return result
end
result << %(\e[0m)
result.join
end
end
true
end | [
"def",
"build_ansi_methods",
"(",
"hash",
")",
"hash",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"define_method",
"(",
"key",
")",
"do",
"|",
"string",
"=",
"nil",
",",
"&",
"block",
"|",
"result",
"=",
"Array",
".",
"new",
"result",
"<<",
"%(\\e[#{value}m)",
"if",
"block_given?",
"result",
"<<",
"block",
".",
"call",
"elsif",
"string",
".",
"respond_to?",
"(",
":to_str",
")",
"result",
"<<",
"string",
".",
"to_str",
"elsif",
"respond_to?",
"(",
":to_str",
")",
"result",
"<<",
"to_str",
"else",
"return",
"result",
"end",
"result",
"<<",
"%(\\e[0m)",
"result",
".",
"join",
"end",
"end",
"true",
"end"
] | Dynamicly constructs ANSI methods for the color methods based on the ANSI
code hash passed in.
@param [Hash] hash
A hash where the keys represent the method names and the values are the
ANSI codes.
@return [Boolean]
True if successful. | [
"Dynamicly",
"constructs",
"ANSI",
"methods",
"for",
"the",
"color",
"methods",
"based",
"on",
"the",
"ANSI",
"code",
"hash",
"passed",
"in",
"."
] | 921601dd4849845d3f5d3765dafcf00178b2aa66 | https://github.com/riddopic/hoodie/blob/921601dd4849845d3f5d3765dafcf00178b2aa66/lib/hoodie/utils/ansi.rb#L127-L150 | train |
riddopic/hoodie | lib/hoodie/utils/ansi.rb | Hoodie.ANSI.uncolor | def uncolor(string = nil, &block)
if block_given?
block.call.to_str.gsub(ANSI_REGEX, '')
elsif string.respond_to?(:to_str)
string.to_str.gsub(ANSI_REGEX, '')
elsif respond_to?(:to_str)
to_str.gsub(ANSI_REGEX, '')
else
''
end
end | ruby | def uncolor(string = nil, &block)
if block_given?
block.call.to_str.gsub(ANSI_REGEX, '')
elsif string.respond_to?(:to_str)
string.to_str.gsub(ANSI_REGEX, '')
elsif respond_to?(:to_str)
to_str.gsub(ANSI_REGEX, '')
else
''
end
end | [
"def",
"uncolor",
"(",
"string",
"=",
"nil",
",",
"&",
"block",
")",
"if",
"block_given?",
"block",
".",
"call",
".",
"to_str",
".",
"gsub",
"(",
"ANSI_REGEX",
",",
"''",
")",
"elsif",
"string",
".",
"respond_to?",
"(",
":to_str",
")",
"string",
".",
"to_str",
".",
"gsub",
"(",
"ANSI_REGEX",
",",
"''",
")",
"elsif",
"respond_to?",
"(",
":to_str",
")",
"to_str",
".",
"gsub",
"(",
"ANSI_REGEX",
",",
"''",
")",
"else",
"''",
"end",
"end"
] | Removes ANSI code sequences from a string.
@param [String] string
The string to operate on.
@yieldreturn [String]
The string to operate on.
@return [String]
The supplied string stripped of ANSI codes. | [
"Removes",
"ANSI",
"code",
"sequences",
"from",
"a",
"string",
"."
] | 921601dd4849845d3f5d3765dafcf00178b2aa66 | https://github.com/riddopic/hoodie/blob/921601dd4849845d3f5d3765dafcf00178b2aa66/lib/hoodie/utils/ansi.rb#L163-L173 | train |
barkerest/incline | lib/incline/validators/recaptcha_validator.rb | Incline.RecaptchaValidator.validate_each | def validate_each(record, attribute, value)
# Do NOT raise an error if nil.
return if value.blank?
# Make sure the response only gets processed once.
return if value == :verified
# Automatically skip validation if paused.
return if Incline::Recaptcha::paused?
# If the user form includes the recaptcha field, then something will come in
# and then we want to check it.
remote_ip, _, response = value.partition('|')
if remote_ip.blank? || response.blank?
record.errors[:base] << (options[:message] || 'Requires reCAPTCHA challenge to be completed')
else
if Incline::Recaptcha::verify(response: response, remote_ip: remote_ip)
record.send "#{attribute}=", :verified
else
record.errors[:base] << (options[:message] || 'Invalid response from reCAPTCHA challenge')
end
end
end | ruby | def validate_each(record, attribute, value)
# Do NOT raise an error if nil.
return if value.blank?
# Make sure the response only gets processed once.
return if value == :verified
# Automatically skip validation if paused.
return if Incline::Recaptcha::paused?
# If the user form includes the recaptcha field, then something will come in
# and then we want to check it.
remote_ip, _, response = value.partition('|')
if remote_ip.blank? || response.blank?
record.errors[:base] << (options[:message] || 'Requires reCAPTCHA challenge to be completed')
else
if Incline::Recaptcha::verify(response: response, remote_ip: remote_ip)
record.send "#{attribute}=", :verified
else
record.errors[:base] << (options[:message] || 'Invalid response from reCAPTCHA challenge')
end
end
end | [
"def",
"validate_each",
"(",
"record",
",",
"attribute",
",",
"value",
")",
"return",
"if",
"value",
".",
"blank?",
"return",
"if",
"value",
"==",
":verified",
"return",
"if",
"Incline",
"::",
"Recaptcha",
"::",
"paused?",
"remote_ip",
",",
"_",
",",
"response",
"=",
"value",
".",
"partition",
"(",
"'|'",
")",
"if",
"remote_ip",
".",
"blank?",
"||",
"response",
".",
"blank?",
"record",
".",
"errors",
"[",
":base",
"]",
"<<",
"(",
"options",
"[",
":message",
"]",
"||",
"'Requires reCAPTCHA challenge to be completed'",
")",
"else",
"if",
"Incline",
"::",
"Recaptcha",
"::",
"verify",
"(",
"response",
":",
"response",
",",
"remote_ip",
":",
"remote_ip",
")",
"record",
".",
"send",
"\"#{attribute}=\"",
",",
":verified",
"else",
"record",
".",
"errors",
"[",
":base",
"]",
"<<",
"(",
"options",
"[",
":message",
"]",
"||",
"'Invalid response from reCAPTCHA challenge'",
")",
"end",
"end",
"end"
] | Validates a reCAPTCHA attribute.
The value of the attribute should be a hash with two keys: :response, :remote_ip | [
"Validates",
"a",
"reCAPTCHA",
"attribute",
"."
] | 1ff08db7aa8ab7f86b223268b700bc67d15bb8aa | https://github.com/barkerest/incline/blob/1ff08db7aa8ab7f86b223268b700bc67d15bb8aa/lib/incline/validators/recaptcha_validator.rb#L11-L34 | train |
djspinmonkey/classy | lib/classy/aliasable.rb | Aliasable.ControllingClassMethods.included | def included( klass )
klass.extend AliasingClassMethods
klass.extend UniversalClassMethods
# Hoo boy. We need to set the @@classy_aliases class variable in the
# including class to point to the same actual hash object that the
# @@classy_aliases variable on the controlling module points to. When
# everything is class based, this is done automatically, since
# sub-classes share class variables.
#
klass.send(:class_variable_set, :@@classy_aliases, self.send(:class_variable_get, :@@classy_aliases))
super
end | ruby | def included( klass )
klass.extend AliasingClassMethods
klass.extend UniversalClassMethods
# Hoo boy. We need to set the @@classy_aliases class variable in the
# including class to point to the same actual hash object that the
# @@classy_aliases variable on the controlling module points to. When
# everything is class based, this is done automatically, since
# sub-classes share class variables.
#
klass.send(:class_variable_set, :@@classy_aliases, self.send(:class_variable_get, :@@classy_aliases))
super
end | [
"def",
"included",
"(",
"klass",
")",
"klass",
".",
"extend",
"AliasingClassMethods",
"klass",
".",
"extend",
"UniversalClassMethods",
"klass",
".",
"send",
"(",
":class_variable_set",
",",
":@@classy_aliases",
",",
"self",
".",
"send",
"(",
":class_variable_get",
",",
":@@classy_aliases",
")",
")",
"super",
"end"
] | Handle a class including a module that has included Aliasable. Since the
contolling module has extended this module, this method ends up being
called when the controlling module is included.
As a minor side effect, an instance method named #included ends up on any
class that directly includes Aliasable. If you know an elegant way to
avoid this, I welcome pull requests. :-)
:nodoc: | [
"Handle",
"a",
"class",
"including",
"a",
"module",
"that",
"has",
"included",
"Aliasable",
".",
"Since",
"the",
"contolling",
"module",
"has",
"extended",
"this",
"module",
"this",
"method",
"ends",
"up",
"being",
"called",
"when",
"the",
"controlling",
"module",
"is",
"included",
"."
] | 1589e2ae33c7fb7fc7ec88b0c24d7df18e2594b3 | https://github.com/djspinmonkey/classy/blob/1589e2ae33c7fb7fc7ec88b0c24d7df18e2594b3/lib/classy/aliasable.rb#L73-L86 | train |
rayko/da_face | lib/da_face/utilities.rb | DaFace.Utilities.symbolize_keys | def symbolize_keys keys, hash
new_hash = {}
keys.each do |key|
if hash[key].kind_of? Hash
new_hash[key.to_sym] = symbolize_keys(hash[key].keys, hash[key])
elsif hash[key].kind_of? Array
new_hash[key.to_sym] = []
hash[key].each do |item|
if item.kind_of? Hash
new_hash[key.to_sym] << symbolize_keys(item.keys, item)
else
new_hash[key.to_sym] << item
end
end
else
new_hash[key.to_sym] = hash[key]
end
end
return new_hash
end | ruby | def symbolize_keys keys, hash
new_hash = {}
keys.each do |key|
if hash[key].kind_of? Hash
new_hash[key.to_sym] = symbolize_keys(hash[key].keys, hash[key])
elsif hash[key].kind_of? Array
new_hash[key.to_sym] = []
hash[key].each do |item|
if item.kind_of? Hash
new_hash[key.to_sym] << symbolize_keys(item.keys, item)
else
new_hash[key.to_sym] << item
end
end
else
new_hash[key.to_sym] = hash[key]
end
end
return new_hash
end | [
"def",
"symbolize_keys",
"keys",
",",
"hash",
"new_hash",
"=",
"{",
"}",
"keys",
".",
"each",
"do",
"|",
"key",
"|",
"if",
"hash",
"[",
"key",
"]",
".",
"kind_of?",
"Hash",
"new_hash",
"[",
"key",
".",
"to_sym",
"]",
"=",
"symbolize_keys",
"(",
"hash",
"[",
"key",
"]",
".",
"keys",
",",
"hash",
"[",
"key",
"]",
")",
"elsif",
"hash",
"[",
"key",
"]",
".",
"kind_of?",
"Array",
"new_hash",
"[",
"key",
".",
"to_sym",
"]",
"=",
"[",
"]",
"hash",
"[",
"key",
"]",
".",
"each",
"do",
"|",
"item",
"|",
"if",
"item",
".",
"kind_of?",
"Hash",
"new_hash",
"[",
"key",
".",
"to_sym",
"]",
"<<",
"symbolize_keys",
"(",
"item",
".",
"keys",
",",
"item",
")",
"else",
"new_hash",
"[",
"key",
".",
"to_sym",
"]",
"<<",
"item",
"end",
"end",
"else",
"new_hash",
"[",
"key",
".",
"to_sym",
"]",
"=",
"hash",
"[",
"key",
"]",
"end",
"end",
"return",
"new_hash",
"end"
] | Creates a new hash with all keys as symbols, can be
any level of depth | [
"Creates",
"a",
"new",
"hash",
"with",
"all",
"keys",
"as",
"symbols",
"can",
"be",
"any",
"level",
"of",
"depth"
] | 6260f4dc420fcc59a6985be0df248cb4773c4bf2 | https://github.com/rayko/da_face/blob/6260f4dc420fcc59a6985be0df248cb4773c4bf2/lib/da_face/utilities.rb#L6-L26 | train |
wedesoft/multiarray | lib/multiarray/shortcuts.rb | Hornetseye.MultiArrayConstructor.constructor_shortcut | def constructor_shortcut( target )
define_method target.to_s.downcase do |*args|
new target, *args
end
end | ruby | def constructor_shortcut( target )
define_method target.to_s.downcase do |*args|
new target, *args
end
end | [
"def",
"constructor_shortcut",
"(",
"target",
")",
"define_method",
"target",
".",
"to_s",
".",
"downcase",
"do",
"|",
"*",
"args",
"|",
"new",
"target",
",",
"*",
"args",
"end",
"end"
] | Meta-programming method for creating constructor shortcut methods
@param [Class] target Element-type to create constructor shortcut for.
@return [Proc] The new method.
@private | [
"Meta",
"-",
"programming",
"method",
"for",
"creating",
"constructor",
"shortcut",
"methods"
] | 1ae1d98bacb4b941d6f406e44ccb184de12f83d9 | https://github.com/wedesoft/multiarray/blob/1ae1d98bacb4b941d6f406e44ccb184de12f83d9/lib/multiarray/shortcuts.rb#L30-L34 | train |
anga/BetterRailsDebugger | lib/better_rails_debugger/analyzer.rb | BetterRailsDebugger.Analyzer.collect_information | def collect_information(identifier, group_id)
group = ::BetterRailsDebugger::AnalysisGroup.find group_id
if not group.present?
Rails.logger.error "[BetterRailsDebugger] Group '#{recorded[:group_id]}' not found. Skiping..."
return
end
# Load Mongo db if required
if not Mongoid::Config.configured?
Mongoid.load!(BetterRailsDebugger::Configuration.instance.mongoid_config_file, Rails.env.to_sym)
Mongoid.logger.level = Logger::FATAL
end
instance = ::BetterRailsDebugger::GroupInstance.create identifier: identifier, analysis_group_id: group_id, caller_file: caller[3][/[^:]+/], status: 'pending'
collect_memory_information(instance)
collect_trace_point_history(instance)
# Now, it's time to analyze all collected data and generate a report
::BetterRailsDebugger::AnalysisRecorderJob.perform_later({ instance_id: instance.id.to_s })
end | ruby | def collect_information(identifier, group_id)
group = ::BetterRailsDebugger::AnalysisGroup.find group_id
if not group.present?
Rails.logger.error "[BetterRailsDebugger] Group '#{recorded[:group_id]}' not found. Skiping..."
return
end
# Load Mongo db if required
if not Mongoid::Config.configured?
Mongoid.load!(BetterRailsDebugger::Configuration.instance.mongoid_config_file, Rails.env.to_sym)
Mongoid.logger.level = Logger::FATAL
end
instance = ::BetterRailsDebugger::GroupInstance.create identifier: identifier, analysis_group_id: group_id, caller_file: caller[3][/[^:]+/], status: 'pending'
collect_memory_information(instance)
collect_trace_point_history(instance)
# Now, it's time to analyze all collected data and generate a report
::BetterRailsDebugger::AnalysisRecorderJob.perform_later({ instance_id: instance.id.to_s })
end | [
"def",
"collect_information",
"(",
"identifier",
",",
"group_id",
")",
"group",
"=",
"::",
"BetterRailsDebugger",
"::",
"AnalysisGroup",
".",
"find",
"group_id",
"if",
"not",
"group",
".",
"present?",
"Rails",
".",
"logger",
".",
"error",
"\"[BetterRailsDebugger] Group '#{recorded[:group_id]}' not found. Skiping...\"",
"return",
"end",
"if",
"not",
"Mongoid",
"::",
"Config",
".",
"configured?",
"Mongoid",
".",
"load!",
"(",
"BetterRailsDebugger",
"::",
"Configuration",
".",
"instance",
".",
"mongoid_config_file",
",",
"Rails",
".",
"env",
".",
"to_sym",
")",
"Mongoid",
".",
"logger",
".",
"level",
"=",
"Logger",
"::",
"FATAL",
"end",
"instance",
"=",
"::",
"BetterRailsDebugger",
"::",
"GroupInstance",
".",
"create",
"identifier",
":",
"identifier",
",",
"analysis_group_id",
":",
"group_id",
",",
"caller_file",
":",
"caller",
"[",
"3",
"]",
"[",
"/",
"/",
"]",
",",
"status",
":",
"'pending'",
"collect_memory_information",
"(",
"instance",
")",
"collect_trace_point_history",
"(",
"instance",
")",
"::",
"BetterRailsDebugger",
"::",
"AnalysisRecorderJob",
".",
"perform_later",
"(",
"{",
"instance_id",
":",
"instance",
".",
"id",
".",
"to_s",
"}",
")",
"end"
] | Record into db, information about object creation | [
"Record",
"into",
"db",
"information",
"about",
"object",
"creation"
] | 2ac7af13b8ee12483bd9a92680d8f43042f1f1d5 | https://github.com/anga/BetterRailsDebugger/blob/2ac7af13b8ee12483bd9a92680d8f43042f1f1d5/lib/better_rails_debugger/analyzer.rb#L63-L83 | train |
tclaus/keytechkit.gem | lib/keytechKit/elements/element_files/element_file_handler.rb | KeytechKit.ElementFileHandler.masterfile? | def masterfile?(element_key)
if Tools.class_type(element_key) == 'DO' # Only DO Types can have a file
file_list = load(element_key)
unless file_list.nil?
file_list.each do |file|
return true if file.fileStorageType.casecmp('master').zero?
end
end
end
false
end | ruby | def masterfile?(element_key)
if Tools.class_type(element_key) == 'DO' # Only DO Types can have a file
file_list = load(element_key)
unless file_list.nil?
file_list.each do |file|
return true if file.fileStorageType.casecmp('master').zero?
end
end
end
false
end | [
"def",
"masterfile?",
"(",
"element_key",
")",
"if",
"Tools",
".",
"class_type",
"(",
"element_key",
")",
"==",
"'DO'",
"file_list",
"=",
"load",
"(",
"element_key",
")",
"unless",
"file_list",
".",
"nil?",
"file_list",
".",
"each",
"do",
"|",
"file",
"|",
"return",
"true",
"if",
"file",
".",
"fileStorageType",
".",
"casecmp",
"(",
"'master'",
")",
".",
"zero?",
"end",
"end",
"end",
"false",
"end"
] | Returns true or false if a masterfile exist | [
"Returns",
"true",
"or",
"false",
"if",
"a",
"masterfile",
"exist"
] | caa7a6bee32b75ec18a4004179ae10cb69d148c2 | https://github.com/tclaus/keytechkit.gem/blob/caa7a6bee32b75ec18a4004179ae10cb69d148c2/lib/keytechKit/elements/element_files/element_file_handler.rb#L17-L27 | train |
tclaus/keytechkit.gem | lib/keytechKit/elements/element_files/element_file_handler.rb | KeytechKit.ElementFileHandler.masterfile_name | def masterfile_name(element_key)
file_list = load(element_key)
unless file_list.nil?
file_list.each do |file|
return file.fileName if file.fileStorageType.downcase! == 'master'
end
end
''
end | ruby | def masterfile_name(element_key)
file_list = load(element_key)
unless file_list.nil?
file_list.each do |file|
return file.fileName if file.fileStorageType.downcase! == 'master'
end
end
''
end | [
"def",
"masterfile_name",
"(",
"element_key",
")",
"file_list",
"=",
"load",
"(",
"element_key",
")",
"unless",
"file_list",
".",
"nil?",
"file_list",
".",
"each",
"do",
"|",
"file",
"|",
"return",
"file",
".",
"fileName",
"if",
"file",
".",
"fileStorageType",
".",
"downcase!",
"==",
"'master'",
"end",
"end",
"''",
"end"
] | Returns the name of a masterfile if present | [
"Returns",
"the",
"name",
"of",
"a",
"masterfile",
"if",
"present"
] | caa7a6bee32b75ec18a4004179ae10cb69d148c2 | https://github.com/tclaus/keytechkit.gem/blob/caa7a6bee32b75ec18a4004179ae10cb69d148c2/lib/keytechKit/elements/element_files/element_file_handler.rb#L43-L51 | train |
tclaus/keytechkit.gem | lib/keytechKit/elements/element_files/element_file_handler.rb | KeytechKit.ElementFileHandler.load | def load(element_key)
parameter = { basic_auth: @auth }
response = self.class.get("/elements/#{element_key}/files", parameter)
parse_files(response['FileInfos']) if response.success?
end | ruby | def load(element_key)
parameter = { basic_auth: @auth }
response = self.class.get("/elements/#{element_key}/files", parameter)
parse_files(response['FileInfos']) if response.success?
end | [
"def",
"load",
"(",
"element_key",
")",
"parameter",
"=",
"{",
"basic_auth",
":",
"@auth",
"}",
"response",
"=",
"self",
".",
"class",
".",
"get",
"(",
"\"/elements/#{element_key}/files\"",
",",
"parameter",
")",
"parse_files",
"(",
"response",
"[",
"'FileInfos'",
"]",
")",
"if",
"response",
".",
"success?",
"end"
] | Loads the filelist
Returns a full list of file data | [
"Loads",
"the",
"filelist",
"Returns",
"a",
"full",
"list",
"of",
"file",
"data"
] | caa7a6bee32b75ec18a4004179ae10cb69d148c2 | https://github.com/tclaus/keytechkit.gem/blob/caa7a6bee32b75ec18a4004179ae10cb69d148c2/lib/keytechKit/elements/element_files/element_file_handler.rb#L55-L59 | train |
tclaus/keytechkit.gem | lib/keytechKit/elements/element_files/element_file_handler.rb | KeytechKit.ElementFileHandler.load_masterfile | def load_masterfile(element_key)
parameter = { basic_auth: @auth }
response = self.class.get("/elements/#{element_key}/files/masterfile", parameter)
return response if response.success?
end | ruby | def load_masterfile(element_key)
parameter = { basic_auth: @auth }
response = self.class.get("/elements/#{element_key}/files/masterfile", parameter)
return response if response.success?
end | [
"def",
"load_masterfile",
"(",
"element_key",
")",
"parameter",
"=",
"{",
"basic_auth",
":",
"@auth",
"}",
"response",
"=",
"self",
".",
"class",
".",
"get",
"(",
"\"/elements/#{element_key}/files/masterfile\"",
",",
"parameter",
")",
"return",
"response",
"if",
"response",
".",
"success?",
"end"
] | Loads the masterfile directly | [
"Loads",
"the",
"masterfile",
"directly"
] | caa7a6bee32b75ec18a4004179ae10cb69d148c2 | https://github.com/tclaus/keytechkit.gem/blob/caa7a6bee32b75ec18a4004179ae10cb69d148c2/lib/keytechKit/elements/element_files/element_file_handler.rb#L62-L66 | train |
tclaus/keytechkit.gem | lib/keytechKit/elements/element_files/element_file_handler.rb | KeytechKit.ElementFileHandler.upload_masterfile | def upload_masterfile(element_key, file, original_filename)
# file, elementkey , name??
content_length = file.size
content_type = 'application/octet-stream; charset=utf-8'
parameter = { basic_auth: @auth,
headers: { 'Content-Type' => content_type,
'Content-Length' => content_length.to_s,
'storageType' => 'MASTER',
'filename' => original_filename.to_s },
body: file.read }
upload_file element_key, parameter
end | ruby | def upload_masterfile(element_key, file, original_filename)
# file, elementkey , name??
content_length = file.size
content_type = 'application/octet-stream; charset=utf-8'
parameter = { basic_auth: @auth,
headers: { 'Content-Type' => content_type,
'Content-Length' => content_length.to_s,
'storageType' => 'MASTER',
'filename' => original_filename.to_s },
body: file.read }
upload_file element_key, parameter
end | [
"def",
"upload_masterfile",
"(",
"element_key",
",",
"file",
",",
"original_filename",
")",
"content_length",
"=",
"file",
".",
"size",
"content_type",
"=",
"'application/octet-stream; charset=utf-8'",
"parameter",
"=",
"{",
"basic_auth",
":",
"@auth",
",",
"headers",
":",
"{",
"'Content-Type'",
"=>",
"content_type",
",",
"'Content-Length'",
"=>",
"content_length",
".",
"to_s",
",",
"'storageType'",
"=>",
"'MASTER'",
",",
"'filename'",
"=>",
"original_filename",
".",
"to_s",
"}",
",",
"body",
":",
"file",
".",
"read",
"}",
"upload_file",
"element_key",
",",
"parameter",
"end"
] | Masterfile is the main file attached to a document | [
"Masterfile",
"is",
"the",
"main",
"file",
"attached",
"to",
"a",
"document"
] | caa7a6bee32b75ec18a4004179ae10cb69d148c2 | https://github.com/tclaus/keytechkit.gem/blob/caa7a6bee32b75ec18a4004179ae10cb69d148c2/lib/keytechKit/elements/element_files/element_file_handler.rb#L70-L81 | train |
barkerest/shells | lib/shells/shell_base/options.rb | Shells.ShellBase.change_quit | def change_quit(quit_command)
raise Shells::NotRunning unless running?
self.options = options.dup.merge( quit: quit_command ).freeze
self
end | ruby | def change_quit(quit_command)
raise Shells::NotRunning unless running?
self.options = options.dup.merge( quit: quit_command ).freeze
self
end | [
"def",
"change_quit",
"(",
"quit_command",
")",
"raise",
"Shells",
"::",
"NotRunning",
"unless",
"running?",
"self",
".",
"options",
"=",
"options",
".",
"dup",
".",
"merge",
"(",
"quit",
":",
"quit_command",
")",
".",
"freeze",
"self",
"end"
] | Initializes the shell with the supplied options.
These options are common to all shells.
+prompt+::
Defaults to "~~#". Most special characters will be stripped.
+retrieve_exit_code+::
Defaults to false. Can also be true.
+on_non_zero_exit_code+::
Defaults to :ignore. Can also be :raise.
+silence_timeout+::
Defaults to 0.
If greater than zero, will raise an error after waiting this many seconds for a prompt.
+command_timeout+::
Defaults to 0.
If greater than zero, will raise an error after a command runs for this long without finishing.
+unbuffered_input+::
Defaults to false.
If non-false, then input is sent one character at a time, otherwise input is sent in whole strings.
If set to :echo, then input is sent one character at a time and the character must be echoed back
from the shell before the next character will be sent.
Please check the documentation for each shell class for specific shell options.
Allows you to change the :quit option inside of a session.
This is useful if you need to change the quit command for some reason.
e.g. - Changing the command to "reboot".
Returns the shell instance. | [
"Initializes",
"the",
"shell",
"with",
"the",
"supplied",
"options",
"."
] | 674a0254f48cea01b0ae8979933f13892e398506 | https://github.com/barkerest/shells/blob/674a0254f48cea01b0ae8979933f13892e398506/lib/shells/shell_base/options.rb#L103-L107 | train |
BUEZE/taaze | lib/taaze/comments.rb | Taaze.TaazeComments.url_get_html | def url_get_html(url_str)
url = URI.parse(URI.encode(url_str)) # first get total size
req = Net::HTTP::Get.new(url.to_s)
res = Net::HTTP.start(url.host, url.port) { |http| http.request(req) }
res.body
end | ruby | def url_get_html(url_str)
url = URI.parse(URI.encode(url_str)) # first get total size
req = Net::HTTP::Get.new(url.to_s)
res = Net::HTTP.start(url.host, url.port) { |http| http.request(req) }
res.body
end | [
"def",
"url_get_html",
"(",
"url_str",
")",
"url",
"=",
"URI",
".",
"parse",
"(",
"URI",
".",
"encode",
"(",
"url_str",
")",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"url",
".",
"to_s",
")",
"res",
"=",
"Net",
"::",
"HTTP",
".",
"start",
"(",
"url",
".",
"host",
",",
"url",
".",
"port",
")",
"{",
"|",
"http",
"|",
"http",
".",
"request",
"(",
"req",
")",
"}",
"res",
".",
"body",
"end"
] | Send url to get response | [
"Send",
"url",
"to",
"get",
"response"
] | ef95e1ad71140a7eaf9e2c65830d900f651bc184 | https://github.com/BUEZE/taaze/blob/ef95e1ad71140a7eaf9e2c65830d900f651bc184/lib/taaze/comments.rb#L74-L79 | train |
BUEZE/taaze | lib/taaze/comments.rb | Taaze.TaazeComments.extract_comments | def extract_comments(content, user_id)
# Json format~
# "content":"勇氣就是熱誠,來自於我們對自己工作的自信心;.....",
# "title":"",
# "status":"C",
# "stars":"5",
# "prodId":"11100597685",
# "titleMain":"行銷之神原一平全集(精裝版)",
# "orgProdId":"11100597685",
# "pkNo":"1000243977",
# "mdf_time":"2015/10/15",
# "crt_time":"2015/10/15"
#
# orgProdId -> bookID -> 11100597685
# title -> book title
# content -> comment
# comment_url
# pkNo -> comment ID ->13313301
#
# http://www.taaze.tw/container_zekeaclt_view.html?co=1000238964&ci=12522728&cp=3
# co->comment ci->user
data_arr = []
if content
content.each do |cmtItem|
data_hash_sub = Hash.new {}
data_hash_sub['title'] = cmtItem['titleMain']
data_hash_sub['comment'] = cmtItem['content']
data_hash_sub['book_url'] = BOOK_URL + cmtItem['orgProdId']
url = MAIN_URL + 'co=' + cmtItem['pkNo'] + '&ci=' + user_id + '&cp=3'
data_hash_sub['comment_url'] = url
data_hash_sub['crt_time'] = cmtItem['crt_time']
data_arr.push(data_hash_sub)
end
else
data_arr = []
end
@comments_found ||= data_arr
end | ruby | def extract_comments(content, user_id)
# Json format~
# "content":"勇氣就是熱誠,來自於我們對自己工作的自信心;.....",
# "title":"",
# "status":"C",
# "stars":"5",
# "prodId":"11100597685",
# "titleMain":"行銷之神原一平全集(精裝版)",
# "orgProdId":"11100597685",
# "pkNo":"1000243977",
# "mdf_time":"2015/10/15",
# "crt_time":"2015/10/15"
#
# orgProdId -> bookID -> 11100597685
# title -> book title
# content -> comment
# comment_url
# pkNo -> comment ID ->13313301
#
# http://www.taaze.tw/container_zekeaclt_view.html?co=1000238964&ci=12522728&cp=3
# co->comment ci->user
data_arr = []
if content
content.each do |cmtItem|
data_hash_sub = Hash.new {}
data_hash_sub['title'] = cmtItem['titleMain']
data_hash_sub['comment'] = cmtItem['content']
data_hash_sub['book_url'] = BOOK_URL + cmtItem['orgProdId']
url = MAIN_URL + 'co=' + cmtItem['pkNo'] + '&ci=' + user_id + '&cp=3'
data_hash_sub['comment_url'] = url
data_hash_sub['crt_time'] = cmtItem['crt_time']
data_arr.push(data_hash_sub)
end
else
data_arr = []
end
@comments_found ||= data_arr
end | [
"def",
"extract_comments",
"(",
"content",
",",
"user_id",
")",
"data_arr",
"=",
"[",
"]",
"if",
"content",
"content",
".",
"each",
"do",
"|",
"cmtItem",
"|",
"data_hash_sub",
"=",
"Hash",
".",
"new",
"{",
"}",
"data_hash_sub",
"[",
"'title'",
"]",
"=",
"cmtItem",
"[",
"'titleMain'",
"]",
"data_hash_sub",
"[",
"'comment'",
"]",
"=",
"cmtItem",
"[",
"'content'",
"]",
"data_hash_sub",
"[",
"'book_url'",
"]",
"=",
"BOOK_URL",
"+",
"cmtItem",
"[",
"'orgProdId'",
"]",
"url",
"=",
"MAIN_URL",
"+",
"'co='",
"+",
"cmtItem",
"[",
"'pkNo'",
"]",
"+",
"'&ci='",
"+",
"user_id",
"+",
"'&cp=3'",
"data_hash_sub",
"[",
"'comment_url'",
"]",
"=",
"url",
"data_hash_sub",
"[",
"'crt_time'",
"]",
"=",
"cmtItem",
"[",
"'crt_time'",
"]",
"data_arr",
".",
"push",
"(",
"data_hash_sub",
")",
"end",
"else",
"data_arr",
"=",
"[",
"]",
"end",
"@comments_found",
"||=",
"data_arr",
"end"
] | Return the comments in the format specified in spec. | [
"Return",
"the",
"comments",
"in",
"the",
"format",
"specified",
"in",
"spec",
"."
] | ef95e1ad71140a7eaf9e2c65830d900f651bc184 | https://github.com/BUEZE/taaze/blob/ef95e1ad71140a7eaf9e2c65830d900f651bc184/lib/taaze/comments.rb#L82-L119 | train |
kukushkin/aerogel-core | lib/aerogel/core/db/model.rb | Model.ClassMethods.find! | def find!( *args )
raise_not_found_error_was = Mongoid.raise_not_found_error
begin
Mongoid.raise_not_found_error = true
self.find( *args )
ensure
Mongoid.raise_not_found_error = raise_not_found_error_was
end
end | ruby | def find!( *args )
raise_not_found_error_was = Mongoid.raise_not_found_error
begin
Mongoid.raise_not_found_error = true
self.find( *args )
ensure
Mongoid.raise_not_found_error = raise_not_found_error_was
end
end | [
"def",
"find!",
"(",
"*",
"args",
")",
"raise_not_found_error_was",
"=",
"Mongoid",
".",
"raise_not_found_error",
"begin",
"Mongoid",
".",
"raise_not_found_error",
"=",
"true",
"self",
".",
"find",
"(",
"*",
"args",
")",
"ensure",
"Mongoid",
".",
"raise_not_found_error",
"=",
"raise_not_found_error_was",
"end",
"end"
] | Finds document by id.
Raises error if document is not found. | [
"Finds",
"document",
"by",
"id",
".",
"Raises",
"error",
"if",
"document",
"is",
"not",
"found",
"."
] | e156af6b237c410c1ee75e5cdf1b10075e7fbb8b | https://github.com/kukushkin/aerogel-core/blob/e156af6b237c410c1ee75e5cdf1b10075e7fbb8b/lib/aerogel/core/db/model.rb#L19-L27 | train |
NU-CBITS/think_feel_do_dashboard | app/helpers/think_feel_do_dashboard/application_helper.rb | ThinkFeelDoDashboard.ApplicationHelper.breadcrumbs | def breadcrumbs
return unless show_breadcrumbs?
content_for(
:breadcrumbs,
content_tag(:ol, class: "breadcrumb") do
concat(content_tag(:li, link_to("Home", root_path)))
if can_view_resource_index?
concat(
content_tag(
:li, controller_link
)
)
end
end
)
end | ruby | def breadcrumbs
return unless show_breadcrumbs?
content_for(
:breadcrumbs,
content_tag(:ol, class: "breadcrumb") do
concat(content_tag(:li, link_to("Home", root_path)))
if can_view_resource_index?
concat(
content_tag(
:li, controller_link
)
)
end
end
)
end | [
"def",
"breadcrumbs",
"return",
"unless",
"show_breadcrumbs?",
"content_for",
"(",
":breadcrumbs",
",",
"content_tag",
"(",
":ol",
",",
"class",
":",
"\"breadcrumb\"",
")",
"do",
"concat",
"(",
"content_tag",
"(",
":li",
",",
"link_to",
"(",
"\"Home\"",
",",
"root_path",
")",
")",
")",
"if",
"can_view_resource_index?",
"concat",
"(",
"content_tag",
"(",
":li",
",",
"controller_link",
")",
")",
"end",
"end",
")",
"end"
] | Render navigational information in the form of breadcrumbs | [
"Render",
"navigational",
"information",
"in",
"the",
"form",
"of",
"breadcrumbs"
] | ff88b539d18a41b71fb93187607d74039f87215a | https://github.com/NU-CBITS/think_feel_do_dashboard/blob/ff88b539d18a41b71fb93187607d74039f87215a/app/helpers/think_feel_do_dashboard/application_helper.rb#L8-L25 | train |
grandcloud/sndacs-ruby | lib/sndacs/bucket.rb | Sndacs.Bucket.put_bucket_policy | def put_bucket_policy(bucket_policy)
if bucket_policy && bucket_policy.is_a?(String) && bucket_policy.strip != ''
bucket_request(:put,:body => bucket_policy,:subresource=>"policy")
true
else
false
end
end | ruby | def put_bucket_policy(bucket_policy)
if bucket_policy && bucket_policy.is_a?(String) && bucket_policy.strip != ''
bucket_request(:put,:body => bucket_policy,:subresource=>"policy")
true
else
false
end
end | [
"def",
"put_bucket_policy",
"(",
"bucket_policy",
")",
"if",
"bucket_policy",
"&&",
"bucket_policy",
".",
"is_a?",
"(",
"String",
")",
"&&",
"bucket_policy",
".",
"strip",
"!=",
"''",
"bucket_request",
"(",
":put",
",",
":body",
"=>",
"bucket_policy",
",",
":subresource",
"=>",
"\"policy\"",
")",
"true",
"else",
"false",
"end",
"end"
] | Set bucket policy for the given bucket | [
"Set",
"bucket",
"policy",
"for",
"the",
"given",
"bucket"
] | 4565e926473e3af9df2ae17f728c423662ca750a | https://github.com/grandcloud/sndacs-ruby/blob/4565e926473e3af9df2ae17f728c423662ca750a/lib/sndacs/bucket.rb#L66-L73 | train |
codescrum/bebox | lib/bebox/wizards/profile_wizard.rb | Bebox.ProfileWizard.create_new_profile | def create_new_profile(project_root, profile_name, profile_base_path)
# Clean the profile_path to make it a valid path
profile_base_path = Bebox::Profile.cleanpath(profile_base_path)
# Check if the profile name is valid
return unless name_valid?(profile_name, profile_base_path)
# Check if the profile exist
profile_path = profile_base_path.empty? ? profile_name : profile_complete_path(profile_base_path, profile_name)
return error(_('wizard.profile.name_exist')%{profile: profile_path}) if profile_exists?(project_root, profile_path)
# Profile creation
profile = Bebox::Profile.new(profile_name, project_root, profile_base_path)
output = profile.create
ok _('wizard.profile.creation_success')%{profile: profile_path}
return output
end | ruby | def create_new_profile(project_root, profile_name, profile_base_path)
# Clean the profile_path to make it a valid path
profile_base_path = Bebox::Profile.cleanpath(profile_base_path)
# Check if the profile name is valid
return unless name_valid?(profile_name, profile_base_path)
# Check if the profile exist
profile_path = profile_base_path.empty? ? profile_name : profile_complete_path(profile_base_path, profile_name)
return error(_('wizard.profile.name_exist')%{profile: profile_path}) if profile_exists?(project_root, profile_path)
# Profile creation
profile = Bebox::Profile.new(profile_name, project_root, profile_base_path)
output = profile.create
ok _('wizard.profile.creation_success')%{profile: profile_path}
return output
end | [
"def",
"create_new_profile",
"(",
"project_root",
",",
"profile_name",
",",
"profile_base_path",
")",
"profile_base_path",
"=",
"Bebox",
"::",
"Profile",
".",
"cleanpath",
"(",
"profile_base_path",
")",
"return",
"unless",
"name_valid?",
"(",
"profile_name",
",",
"profile_base_path",
")",
"profile_path",
"=",
"profile_base_path",
".",
"empty?",
"?",
"profile_name",
":",
"profile_complete_path",
"(",
"profile_base_path",
",",
"profile_name",
")",
"return",
"error",
"(",
"_",
"(",
"'wizard.profile.name_exist'",
")",
"%",
"{",
"profile",
":",
"profile_path",
"}",
")",
"if",
"profile_exists?",
"(",
"project_root",
",",
"profile_path",
")",
"profile",
"=",
"Bebox",
"::",
"Profile",
".",
"new",
"(",
"profile_name",
",",
"project_root",
",",
"profile_base_path",
")",
"output",
"=",
"profile",
".",
"create",
"ok",
"_",
"(",
"'wizard.profile.creation_success'",
")",
"%",
"{",
"profile",
":",
"profile_path",
"}",
"return",
"output",
"end"
] | Create a new profile | [
"Create",
"a",
"new",
"profile"
] | 0d19315847103341e599d32837ab0bd75524e5be | https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/profile_wizard.rb#L8-L21 | train |
codescrum/bebox | lib/bebox/wizards/profile_wizard.rb | Bebox.ProfileWizard.name_valid? | def name_valid?(profile_name, profile_base_path)
unless valid_puppet_class_name?(profile_name)
error _('wizard.profile.invalid_name')%{words: Bebox::RESERVED_WORDS.join(', ')}
return false
end
return true if profile_base_path.empty?
# Check if the path name is valid
unless Bebox::Profile.valid_pathname?(profile_base_path)
error _('wizard.profile.invalid_path')%{words: Bebox::RESERVED_WORDS.join(', ')}
return false
end
true
end | ruby | def name_valid?(profile_name, profile_base_path)
unless valid_puppet_class_name?(profile_name)
error _('wizard.profile.invalid_name')%{words: Bebox::RESERVED_WORDS.join(', ')}
return false
end
return true if profile_base_path.empty?
# Check if the path name is valid
unless Bebox::Profile.valid_pathname?(profile_base_path)
error _('wizard.profile.invalid_path')%{words: Bebox::RESERVED_WORDS.join(', ')}
return false
end
true
end | [
"def",
"name_valid?",
"(",
"profile_name",
",",
"profile_base_path",
")",
"unless",
"valid_puppet_class_name?",
"(",
"profile_name",
")",
"error",
"_",
"(",
"'wizard.profile.invalid_name'",
")",
"%",
"{",
"words",
":",
"Bebox",
"::",
"RESERVED_WORDS",
".",
"join",
"(",
"', '",
")",
"}",
"return",
"false",
"end",
"return",
"true",
"if",
"profile_base_path",
".",
"empty?",
"unless",
"Bebox",
"::",
"Profile",
".",
"valid_pathname?",
"(",
"profile_base_path",
")",
"error",
"_",
"(",
"'wizard.profile.invalid_path'",
")",
"%",
"{",
"words",
":",
"Bebox",
"::",
"RESERVED_WORDS",
".",
"join",
"(",
"', '",
")",
"}",
"return",
"false",
"end",
"true",
"end"
] | Check if the profile name is valid | [
"Check",
"if",
"the",
"profile",
"name",
"is",
"valid"
] | 0d19315847103341e599d32837ab0bd75524e5be | https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/profile_wizard.rb#L24-L36 | train |
codescrum/bebox | lib/bebox/wizards/profile_wizard.rb | Bebox.ProfileWizard.remove_profile | def remove_profile(project_root)
# Choose a profile from the availables
profiles = Bebox::Profile.list(project_root)
# Get a profile if exist
if profiles.count > 0
profile = choose_option(profiles, _('wizard.choose_remove_profile'))
else
return error _('wizard.profile.no_deletion_profiles')
end
# Ask for deletion confirmation
return warn(_('wizard.no_changes')) unless confirm_action?(_('wizard.profile.confirm_deletion'))
# Profile deletion
profile_name = profile.split('/').last
profile_base_path = profile.split('/')[0...-1].join('/')
profile = Bebox::Profile.new(profile_name, project_root, profile_base_path)
output = profile.remove
ok _('wizard.profile.deletion_success')
return output
end | ruby | def remove_profile(project_root)
# Choose a profile from the availables
profiles = Bebox::Profile.list(project_root)
# Get a profile if exist
if profiles.count > 0
profile = choose_option(profiles, _('wizard.choose_remove_profile'))
else
return error _('wizard.profile.no_deletion_profiles')
end
# Ask for deletion confirmation
return warn(_('wizard.no_changes')) unless confirm_action?(_('wizard.profile.confirm_deletion'))
# Profile deletion
profile_name = profile.split('/').last
profile_base_path = profile.split('/')[0...-1].join('/')
profile = Bebox::Profile.new(profile_name, project_root, profile_base_path)
output = profile.remove
ok _('wizard.profile.deletion_success')
return output
end | [
"def",
"remove_profile",
"(",
"project_root",
")",
"profiles",
"=",
"Bebox",
"::",
"Profile",
".",
"list",
"(",
"project_root",
")",
"if",
"profiles",
".",
"count",
">",
"0",
"profile",
"=",
"choose_option",
"(",
"profiles",
",",
"_",
"(",
"'wizard.choose_remove_profile'",
")",
")",
"else",
"return",
"error",
"_",
"(",
"'wizard.profile.no_deletion_profiles'",
")",
"end",
"return",
"warn",
"(",
"_",
"(",
"'wizard.no_changes'",
")",
")",
"unless",
"confirm_action?",
"(",
"_",
"(",
"'wizard.profile.confirm_deletion'",
")",
")",
"profile_name",
"=",
"profile",
".",
"split",
"(",
"'/'",
")",
".",
"last",
"profile_base_path",
"=",
"profile",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"...",
"-",
"1",
"]",
".",
"join",
"(",
"'/'",
")",
"profile",
"=",
"Bebox",
"::",
"Profile",
".",
"new",
"(",
"profile_name",
",",
"project_root",
",",
"profile_base_path",
")",
"output",
"=",
"profile",
".",
"remove",
"ok",
"_",
"(",
"'wizard.profile.deletion_success'",
")",
"return",
"output",
"end"
] | Removes an existing profile | [
"Removes",
"an",
"existing",
"profile"
] | 0d19315847103341e599d32837ab0bd75524e5be | https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/wizards/profile_wizard.rb#L39-L57 | train |
inside-track/remi | lib/remi/data_subject.rb | Remi.DataSubject.field_symbolizer | def field_symbolizer(arg = nil)
return @field_symbolizer unless arg
@field_symbolizer = if arg.is_a? Symbol
Remi::FieldSymbolizers[arg]
else
arg
end
end | ruby | def field_symbolizer(arg = nil)
return @field_symbolizer unless arg
@field_symbolizer = if arg.is_a? Symbol
Remi::FieldSymbolizers[arg]
else
arg
end
end | [
"def",
"field_symbolizer",
"(",
"arg",
"=",
"nil",
")",
"return",
"@field_symbolizer",
"unless",
"arg",
"@field_symbolizer",
"=",
"if",
"arg",
".",
"is_a?",
"Symbol",
"Remi",
"::",
"FieldSymbolizers",
"[",
"arg",
"]",
"else",
"arg",
"end",
"end"
] | Field symbolizer used to convert field names into symbols. This method sets
the symbolizer for the data subject and also sets the symbolizers for
any associated parser and encoders.
@return [Proc] the method for symbolizing field names | [
"Field",
"symbolizer",
"used",
"to",
"convert",
"field",
"names",
"into",
"symbols",
".",
"This",
"method",
"sets",
"the",
"symbolizer",
"for",
"the",
"data",
"subject",
"and",
"also",
"sets",
"the",
"symbolizers",
"for",
"any",
"associated",
"parser",
"and",
"encoders",
"."
] | f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7 | https://github.com/inside-track/remi/blob/f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7/lib/remi/data_subject.rb#L56-L63 | train |
inside-track/remi | lib/remi/data_subject.rb | Remi.DataSubject.df= | def df=(new_dataframe)
dsl_eval
if new_dataframe.respond_to? :df_type
@dataframe = new_dataframe
else
@dataframe = Remi::DataFrame.create(df_type, new_dataframe)
end
end | ruby | def df=(new_dataframe)
dsl_eval
if new_dataframe.respond_to? :df_type
@dataframe = new_dataframe
else
@dataframe = Remi::DataFrame.create(df_type, new_dataframe)
end
end | [
"def",
"df",
"=",
"(",
"new_dataframe",
")",
"dsl_eval",
"if",
"new_dataframe",
".",
"respond_to?",
":df_type",
"@dataframe",
"=",
"new_dataframe",
"else",
"@dataframe",
"=",
"Remi",
"::",
"DataFrame",
".",
"create",
"(",
"df_type",
",",
"new_dataframe",
")",
"end",
"end"
] | Reassigns the dataframe associated with this DataSubject.
@param new_dataframe [Object] The new dataframe object to be associated.
@return [Remi::DataFrame] the associated dataframe | [
"Reassigns",
"the",
"dataframe",
"associated",
"with",
"this",
"DataSubject",
"."
] | f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7 | https://github.com/inside-track/remi/blob/f7e5f28f08f8c0403e04cd82d6fc14b6b2c362a7/lib/remi/data_subject.rb#L74-L81 | train |
jinx/core | lib/jinx/helpers/multi_enumerator.rb | Jinx.MultiEnumerator.method_missing | def method_missing(symbol, *args)
self.class.new(@components.map { |enum|enum.send(symbol, *args) })
end | ruby | def method_missing(symbol, *args)
self.class.new(@components.map { |enum|enum.send(symbol, *args) })
end | [
"def",
"method_missing",
"(",
"symbol",
",",
"*",
"args",
")",
"self",
".",
"class",
".",
"new",
"(",
"@components",
".",
"map",
"{",
"|",
"enum",
"|",
"enum",
".",
"send",
"(",
"symbol",
",",
"*",
"args",
")",
"}",
")",
"end"
] | Returns the union of the results of calling the given method symbol on each component. | [
"Returns",
"the",
"union",
"of",
"the",
"results",
"of",
"calling",
"the",
"given",
"method",
"symbol",
"on",
"each",
"component",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/helpers/multi_enumerator.rb#L43-L45 | train |
itisnotdone/gogetit | lib/providers/lxd.rb | Gogetit.GogetLXD.generate_user_data | def generate_user_data(lxd_params, options)
logger.info("Calling <#{__method__.to_s}>")
lxd_params[:config] = {}
if options[:'no-maas']
lxd_params[:config][:"user.user-data"] = {}
else
sshkeys = maas.get_sshkeys
pkg_repos = maas.get_package_repos
lxd_params[:config][:'user.user-data'] = { 'ssh_authorized_keys' => [] }
sshkeys.each do |key|
lxd_params[:config][:'user.user-data']['ssh_authorized_keys'].push(key['key'])
end
pkg_repos.each do |repo|
if repo['name'] == 'main_archive'
lxd_params[:config][:'user.user-data']['apt_mirror'] = repo['url']
end
end
lxd_params[:config][:"user.user-data"]['source_image_alias'] = lxd_params[:alias]
lxd_params[:config][:"user.user-data"]['maas'] = true
end
if options[:'maas-on-lxc']
lxd_params[:config][:"security.privileged"] = "true"
end
if options[:'lxd-in-lxd']
lxd_params[:config][:"security.privileged"] = "true"
lxd_params[:config][:"security.nesting"] = "true"
end
if options[:'kvm-in-lxd']
lxd_params[:config][:"security.nesting"] = "true"
lxd_params[:config][:"linux.kernel_modules"] = "iptable_nat, ip6table_nat, ebtables, openvswitch, kvm, kvm_intel, tap, vhost, vhost_net, vhost_scsi, vhost_vsock"
end
lxd_params[:config][:"user.user-data"]['gogetit'] = true
# To disable to update apt database on first boot
# so chef client can keep doing its job.
lxd_params[:config][:'user.user-data']['package_update'] = false
lxd_params[:config][:'user.user-data']['package_upgrade'] = false
lxd_params[:config][:'user.user-data'] = generate_cloud_init_config(
options,
config,
lxd_params[:config][:'user.user-data']
)
lxd_params[:config][:"user.user-data"] = \
"#cloud-config\n" + YAML.dump(lxd_params[:config][:"user.user-data"])[4..-1]
return lxd_params
end | ruby | def generate_user_data(lxd_params, options)
logger.info("Calling <#{__method__.to_s}>")
lxd_params[:config] = {}
if options[:'no-maas']
lxd_params[:config][:"user.user-data"] = {}
else
sshkeys = maas.get_sshkeys
pkg_repos = maas.get_package_repos
lxd_params[:config][:'user.user-data'] = { 'ssh_authorized_keys' => [] }
sshkeys.each do |key|
lxd_params[:config][:'user.user-data']['ssh_authorized_keys'].push(key['key'])
end
pkg_repos.each do |repo|
if repo['name'] == 'main_archive'
lxd_params[:config][:'user.user-data']['apt_mirror'] = repo['url']
end
end
lxd_params[:config][:"user.user-data"]['source_image_alias'] = lxd_params[:alias]
lxd_params[:config][:"user.user-data"]['maas'] = true
end
if options[:'maas-on-lxc']
lxd_params[:config][:"security.privileged"] = "true"
end
if options[:'lxd-in-lxd']
lxd_params[:config][:"security.privileged"] = "true"
lxd_params[:config][:"security.nesting"] = "true"
end
if options[:'kvm-in-lxd']
lxd_params[:config][:"security.nesting"] = "true"
lxd_params[:config][:"linux.kernel_modules"] = "iptable_nat, ip6table_nat, ebtables, openvswitch, kvm, kvm_intel, tap, vhost, vhost_net, vhost_scsi, vhost_vsock"
end
lxd_params[:config][:"user.user-data"]['gogetit'] = true
# To disable to update apt database on first boot
# so chef client can keep doing its job.
lxd_params[:config][:'user.user-data']['package_update'] = false
lxd_params[:config][:'user.user-data']['package_upgrade'] = false
lxd_params[:config][:'user.user-data'] = generate_cloud_init_config(
options,
config,
lxd_params[:config][:'user.user-data']
)
lxd_params[:config][:"user.user-data"] = \
"#cloud-config\n" + YAML.dump(lxd_params[:config][:"user.user-data"])[4..-1]
return lxd_params
end | [
"def",
"generate_user_data",
"(",
"lxd_params",
",",
"options",
")",
"logger",
".",
"info",
"(",
"\"Calling <#{__method__.to_s}>\"",
")",
"lxd_params",
"[",
":config",
"]",
"=",
"{",
"}",
"if",
"options",
"[",
":'",
"'",
"]",
"lxd_params",
"[",
":config",
"]",
"[",
":\"",
"\"",
"]",
"=",
"{",
"}",
"else",
"sshkeys",
"=",
"maas",
".",
"get_sshkeys",
"pkg_repos",
"=",
"maas",
".",
"get_package_repos",
"lxd_params",
"[",
":config",
"]",
"[",
":'",
"'",
"]",
"=",
"{",
"'ssh_authorized_keys'",
"=>",
"[",
"]",
"}",
"sshkeys",
".",
"each",
"do",
"|",
"key",
"|",
"lxd_params",
"[",
":config",
"]",
"[",
":'",
"'",
"]",
"[",
"'ssh_authorized_keys'",
"]",
".",
"push",
"(",
"key",
"[",
"'key'",
"]",
")",
"end",
"pkg_repos",
".",
"each",
"do",
"|",
"repo",
"|",
"if",
"repo",
"[",
"'name'",
"]",
"==",
"'main_archive'",
"lxd_params",
"[",
":config",
"]",
"[",
":'",
"'",
"]",
"[",
"'apt_mirror'",
"]",
"=",
"repo",
"[",
"'url'",
"]",
"end",
"end",
"lxd_params",
"[",
":config",
"]",
"[",
":\"",
"\"",
"]",
"[",
"'source_image_alias'",
"]",
"=",
"lxd_params",
"[",
":alias",
"]",
"lxd_params",
"[",
":config",
"]",
"[",
":\"",
"\"",
"]",
"[",
"'maas'",
"]",
"=",
"true",
"end",
"if",
"options",
"[",
":'",
"'",
"]",
"lxd_params",
"[",
":config",
"]",
"[",
":\"",
"\"",
"]",
"=",
"\"true\"",
"end",
"if",
"options",
"[",
":'",
"'",
"]",
"lxd_params",
"[",
":config",
"]",
"[",
":\"",
"\"",
"]",
"=",
"\"true\"",
"lxd_params",
"[",
":config",
"]",
"[",
":\"",
"\"",
"]",
"=",
"\"true\"",
"end",
"if",
"options",
"[",
":'",
"'",
"]",
"lxd_params",
"[",
":config",
"]",
"[",
":\"",
"\"",
"]",
"=",
"\"true\"",
"lxd_params",
"[",
":config",
"]",
"[",
":\"",
"\"",
"]",
"=",
"\"iptable_nat, ip6table_nat, ebtables, openvswitch, kvm, kvm_intel, tap, vhost, vhost_net, vhost_scsi, vhost_vsock\"",
"end",
"lxd_params",
"[",
":config",
"]",
"[",
":\"",
"\"",
"]",
"[",
"'gogetit'",
"]",
"=",
"true",
"lxd_params",
"[",
":config",
"]",
"[",
":'",
"'",
"]",
"[",
"'package_update'",
"]",
"=",
"false",
"lxd_params",
"[",
":config",
"]",
"[",
":'",
"'",
"]",
"[",
"'package_upgrade'",
"]",
"=",
"false",
"lxd_params",
"[",
":config",
"]",
"[",
":'",
"'",
"]",
"=",
"generate_cloud_init_config",
"(",
"options",
",",
"config",
",",
"lxd_params",
"[",
":config",
"]",
"[",
":'",
"'",
"]",
")",
"lxd_params",
"[",
":config",
"]",
"[",
":\"",
"\"",
"]",
"=",
"\"#cloud-config\\n\"",
"+",
"YAML",
".",
"dump",
"(",
"lxd_params",
"[",
":config",
"]",
"[",
":\"",
"\"",
"]",
")",
"[",
"4",
"..",
"-",
"1",
"]",
"return",
"lxd_params",
"end"
] | to generate 'user.user-data' | [
"to",
"generate",
"user",
".",
"user",
"-",
"data"
] | 62628c04c0310567178c4738aa5b64645ed5c4bd | https://github.com/itisnotdone/gogetit/blob/62628c04c0310567178c4738aa5b64645ed5c4bd/lib/providers/lxd.rb#L49-L107 | train |
mintdigital/pyrite | lib/pyrite/dsl.rb | Pyrite.Dsl.fill_in | def fill_in(element, value)
if element.match /date/ # Try to guess at date selects
select_date(element, value)
else
browser.type("jquery=#{element}", value)
end
end | ruby | def fill_in(element, value)
if element.match /date/ # Try to guess at date selects
select_date(element, value)
else
browser.type("jquery=#{element}", value)
end
end | [
"def",
"fill_in",
"(",
"element",
",",
"value",
")",
"if",
"element",
".",
"match",
"/",
"/",
"select_date",
"(",
"element",
",",
"value",
")",
"else",
"browser",
".",
"type",
"(",
"\"jquery=#{element}\"",
",",
"value",
")",
"end",
"end"
] | Fill in a form field | [
"Fill",
"in",
"a",
"form",
"field"
] | acba5d6b460e4262b29be522a0bde0c29ef14cb1 | https://github.com/mintdigital/pyrite/blob/acba5d6b460e4262b29be522a0bde0c29ef14cb1/lib/pyrite/dsl.rb#L5-L11 | train |
mintdigital/pyrite | lib/pyrite/dsl.rb | Pyrite.Dsl.select_date | def select_date(element, value)
suffixes = {
:year => '1i',
:month => '2i',
:day => '3i',
:hour => '4i',
:minute => '5i'
}
date = value.respond_to?(:year) ? value : Date.parse(value)
browser.select "jquery=#{element}_#{suffixes[:year]}", date.year
browser.select "jquery=#{element}_#{suffixes[:month]}", date.strftime('%B')
browser.select "jquery=#{element}_#{suffixes[:day]}", date.day
end | ruby | def select_date(element, value)
suffixes = {
:year => '1i',
:month => '2i',
:day => '3i',
:hour => '4i',
:minute => '5i'
}
date = value.respond_to?(:year) ? value : Date.parse(value)
browser.select "jquery=#{element}_#{suffixes[:year]}", date.year
browser.select "jquery=#{element}_#{suffixes[:month]}", date.strftime('%B')
browser.select "jquery=#{element}_#{suffixes[:day]}", date.day
end | [
"def",
"select_date",
"(",
"element",
",",
"value",
")",
"suffixes",
"=",
"{",
":year",
"=>",
"'1i'",
",",
":month",
"=>",
"'2i'",
",",
":day",
"=>",
"'3i'",
",",
":hour",
"=>",
"'4i'",
",",
":minute",
"=>",
"'5i'",
"}",
"date",
"=",
"value",
".",
"respond_to?",
"(",
":year",
")",
"?",
"value",
":",
"Date",
".",
"parse",
"(",
"value",
")",
"browser",
".",
"select",
"\"jquery=#{element}_#{suffixes[:year]}\"",
",",
"date",
".",
"year",
"browser",
".",
"select",
"\"jquery=#{element}_#{suffixes[:month]}\"",
",",
"date",
".",
"strftime",
"(",
"'%B'",
")",
"browser",
".",
"select",
"\"jquery=#{element}_#{suffixes[:day]}\"",
",",
"date",
".",
"day",
"end"
] | Fill in a Rails-ish set of date_select fields | [
"Fill",
"in",
"a",
"Rails",
"-",
"ish",
"set",
"of",
"date_select",
"fields"
] | acba5d6b460e4262b29be522a0bde0c29ef14cb1 | https://github.com/mintdigital/pyrite/blob/acba5d6b460e4262b29be522a0bde0c29ef14cb1/lib/pyrite/dsl.rb#L14-L26 | train |
mintdigital/pyrite | lib/pyrite/dsl.rb | Pyrite.Dsl.wait_for | def wait_for(element)
case element
when :page_load
browser.wait_for(:wait_for => :page)
when :ajax
browser.wait_for(:wait_for => :ajax, :javascript_framework => Pyrite.js_framework)
else
browser.wait_for(:element => "jquery=#{element}")
end
end | ruby | def wait_for(element)
case element
when :page_load
browser.wait_for(:wait_for => :page)
when :ajax
browser.wait_for(:wait_for => :ajax, :javascript_framework => Pyrite.js_framework)
else
browser.wait_for(:element => "jquery=#{element}")
end
end | [
"def",
"wait_for",
"(",
"element",
")",
"case",
"element",
"when",
":page_load",
"browser",
".",
"wait_for",
"(",
":wait_for",
"=>",
":page",
")",
"when",
":ajax",
"browser",
".",
"wait_for",
"(",
":wait_for",
"=>",
":ajax",
",",
":javascript_framework",
"=>",
"Pyrite",
".",
"js_framework",
")",
"else",
"browser",
".",
"wait_for",
"(",
":element",
"=>",
"\"jquery=#{element}\"",
")",
"end",
"end"
] | Wait for a specific element, the page to load
or an AJAX request to return | [
"Wait",
"for",
"a",
"specific",
"element",
"the",
"page",
"to",
"load",
"or",
"an",
"AJAX",
"request",
"to",
"return"
] | acba5d6b460e4262b29be522a0bde0c29ef14cb1 | https://github.com/mintdigital/pyrite/blob/acba5d6b460e4262b29be522a0bde0c29ef14cb1/lib/pyrite/dsl.rb#L61-L70 | train |
Bottega8/maguro | lib/maguro/features.rb | Maguro.Features.create_database_files | def create_database_files
username = builder.options['database-username']
password = builder.options['database-password']
builder.remove_file "config/database.yml"
create_database_yml_file("config/database.sample.yml", "username", "pass")
create_database_yml_file("config/database.yml", username, password)
end | ruby | def create_database_files
username = builder.options['database-username']
password = builder.options['database-password']
builder.remove_file "config/database.yml"
create_database_yml_file("config/database.sample.yml", "username", "pass")
create_database_yml_file("config/database.yml", username, password)
end | [
"def",
"create_database_files",
"username",
"=",
"builder",
".",
"options",
"[",
"'database-username'",
"]",
"password",
"=",
"builder",
".",
"options",
"[",
"'database-password'",
"]",
"builder",
".",
"remove_file",
"\"config/database.yml\"",
"create_database_yml_file",
"(",
"\"config/database.sample.yml\"",
",",
"\"username\"",
",",
"\"pass\"",
")",
"create_database_yml_file",
"(",
"\"config/database.yml\"",
",",
"username",
",",
"password",
")",
"end"
] | create a new database.yml that works with PG. | [
"create",
"a",
"new",
"database",
".",
"yml",
"that",
"works",
"with",
"PG",
"."
] | 9bfff4e3a9e823d57d55f86394dcb9353fd8205e | https://github.com/Bottega8/maguro/blob/9bfff4e3a9e823d57d55f86394dcb9353fd8205e/lib/maguro/features.rb#L165-L172 | train |
SwagDevOps/kamaze-project | lib/kamaze/project/concern/observable.rb | Kamaze::Project::Concern::Observable.ClassMethods.add_observer | def add_observer(observer_class, func = :handle_event)
func = func.to_sym
unless observer_class.instance_methods.include?(func)
m = "#<#{observer_class}> does not respond to `#{func}'"
raise NoMethodError, m
end
observer_peers[observer_class] = func
self
end | ruby | def add_observer(observer_class, func = :handle_event)
func = func.to_sym
unless observer_class.instance_methods.include?(func)
m = "#<#{observer_class}> does not respond to `#{func}'"
raise NoMethodError, m
end
observer_peers[observer_class] = func
self
end | [
"def",
"add_observer",
"(",
"observer_class",
",",
"func",
"=",
":handle_event",
")",
"func",
"=",
"func",
".",
"to_sym",
"unless",
"observer_class",
".",
"instance_methods",
".",
"include?",
"(",
"func",
")",
"m",
"=",
"\"#<#{observer_class}> does not respond to `#{func}'\"",
"raise",
"NoMethodError",
",",
"m",
"end",
"observer_peers",
"[",
"observer_class",
"]",
"=",
"func",
"self",
"end"
] | Add observer.
@param [Class] observer_class
@return [self] | [
"Add",
"observer",
"."
] | a0451ff204ed3072c1d6ae980811a32b3eb50345 | https://github.com/SwagDevOps/kamaze-project/blob/a0451ff204ed3072c1d6ae980811a32b3eb50345/lib/kamaze/project/concern/observable.rb#L58-L69 | train |
tatemae/muck-engine | lib/muck-engine/controllers/ssl_requirement.rb | MuckEngine.SslRequirement.ssl_required? | def ssl_required?
return ENV['SSL'] == 'on' ? true : false if defined? ENV['SSL']
return false if local_request?
return false if RAILS_ENV == 'test'
((self.class.read_inheritable_attribute(:ssl_required_actions) || []).include?(action_name.to_sym)) && (::Rails.env == 'production' || ::Rails.env == 'staging')
end | ruby | def ssl_required?
return ENV['SSL'] == 'on' ? true : false if defined? ENV['SSL']
return false if local_request?
return false if RAILS_ENV == 'test'
((self.class.read_inheritable_attribute(:ssl_required_actions) || []).include?(action_name.to_sym)) && (::Rails.env == 'production' || ::Rails.env == 'staging')
end | [
"def",
"ssl_required?",
"return",
"ENV",
"[",
"'SSL'",
"]",
"==",
"'on'",
"?",
"true",
":",
"false",
"if",
"defined?",
"ENV",
"[",
"'SSL'",
"]",
"return",
"false",
"if",
"local_request?",
"return",
"false",
"if",
"RAILS_ENV",
"==",
"'test'",
"(",
"(",
"self",
".",
"class",
".",
"read_inheritable_attribute",
"(",
":ssl_required_actions",
")",
"||",
"[",
"]",
")",
".",
"include?",
"(",
"action_name",
".",
"to_sym",
")",
")",
"&&",
"(",
"::",
"Rails",
".",
"env",
"==",
"'production'",
"||",
"::",
"Rails",
".",
"env",
"==",
"'staging'",
")",
"end"
] | Only require ssl if we are in production | [
"Only",
"require",
"ssl",
"if",
"we",
"are",
"in",
"production"
] | 41fc072dce3a365b3ce4a73d4f60a4ff24026d51 | https://github.com/tatemae/muck-engine/blob/41fc072dce3a365b3ce4a73d4f60a4ff24026d51/lib/muck-engine/controllers/ssl_requirement.rb#L24-L29 | train |
seblindberg/ruby-rooted_tree | lib/rooted_tree/node.rb | RootedTree.Node.ancestors | def ancestors
return to_enum(__callee__) unless block_given?
node = self
loop do
node = node.parent
yield node
end
end | ruby | def ancestors
return to_enum(__callee__) unless block_given?
node = self
loop do
node = node.parent
yield node
end
end | [
"def",
"ancestors",
"return",
"to_enum",
"(",
"__callee__",
")",
"unless",
"block_given?",
"node",
"=",
"self",
"loop",
"do",
"node",
"=",
"node",
".",
"parent",
"yield",
"node",
"end",
"end"
] | Iterates over the nodes above this in the tree hierarchy and yields them
to a block. If no block is given an enumerator is returned.
@yield [Node] each parent node.
@return [Enumerator] if no block is given. | [
"Iterates",
"over",
"the",
"nodes",
"above",
"this",
"in",
"the",
"tree",
"hierarchy",
"and",
"yields",
"them",
"to",
"a",
"block",
".",
"If",
"no",
"block",
"is",
"given",
"an",
"enumerator",
"is",
"returned",
"."
] | 59013fc0fd59f137b5e40d86c49afe08ea678941 | https://github.com/seblindberg/ruby-rooted_tree/blob/59013fc0fd59f137b5e40d86c49afe08ea678941/lib/rooted_tree/node.rb#L109-L116 | train |
seblindberg/ruby-rooted_tree | lib/rooted_tree/node.rb | RootedTree.Node.child | def child(index = nil)
unless index
raise ArgumentError, 'No index for node with degree != 1' if degree != 1
return first
end
rtl, index = wrap_index index
raise RangeError, 'Child index out of range' if index >= degree
children(rtl: rtl).each do |c|
break c if index.zero?
index -= 1
end
end | ruby | def child(index = nil)
unless index
raise ArgumentError, 'No index for node with degree != 1' if degree != 1
return first
end
rtl, index = wrap_index index
raise RangeError, 'Child index out of range' if index >= degree
children(rtl: rtl).each do |c|
break c if index.zero?
index -= 1
end
end | [
"def",
"child",
"(",
"index",
"=",
"nil",
")",
"unless",
"index",
"raise",
"ArgumentError",
",",
"'No index for node with degree != 1'",
"if",
"degree",
"!=",
"1",
"return",
"first",
"end",
"rtl",
",",
"index",
"=",
"wrap_index",
"index",
"raise",
"RangeError",
",",
"'Child index out of range'",
"if",
"index",
">=",
"degree",
"children",
"(",
"rtl",
":",
"rtl",
")",
".",
"each",
"do",
"|",
"c",
"|",
"break",
"c",
"if",
"index",
".",
"zero?",
"index",
"-=",
"1",
"end",
"end"
] | Accessor method for any of the n children under this node. If called
without an argument and the node has anything but exactly one child an
exception will be raised.
@param index [Integer] the n:th child to be returned. If the index is
negative the indexing will be reversed and the children counted from the
last to the first.
@return [Node] the child at the n:th index. | [
"Accessor",
"method",
"for",
"any",
"of",
"the",
"n",
"children",
"under",
"this",
"node",
".",
"If",
"called",
"without",
"an",
"argument",
"and",
"the",
"node",
"has",
"anything",
"but",
"exactly",
"one",
"child",
"an",
"exception",
"will",
"be",
"raised",
"."
] | 59013fc0fd59f137b5e40d86c49afe08ea678941 | https://github.com/seblindberg/ruby-rooted_tree/blob/59013fc0fd59f137b5e40d86c49afe08ea678941/lib/rooted_tree/node.rb#L139-L153 | train |
seblindberg/ruby-rooted_tree | lib/rooted_tree/node.rb | RootedTree.Node.edges | def edges(&block)
return to_enum(__callee__) unless block_given?
children do |v|
yield self, v
v.edges(&block)
end
end | ruby | def edges(&block)
return to_enum(__callee__) unless block_given?
children do |v|
yield self, v
v.edges(&block)
end
end | [
"def",
"edges",
"(",
"&",
"block",
")",
"return",
"to_enum",
"(",
"__callee__",
")",
"unless",
"block_given?",
"children",
"do",
"|",
"v",
"|",
"yield",
"self",
",",
"v",
"v",
".",
"edges",
"(",
"&",
"block",
")",
"end",
"end"
] | Iterates over each edge in the tree.
@yield [Array<Node>] each connected node pair.
@return [Enumerator] if no block is given. | [
"Iterates",
"over",
"each",
"edge",
"in",
"the",
"tree",
"."
] | 59013fc0fd59f137b5e40d86c49afe08ea678941 | https://github.com/seblindberg/ruby-rooted_tree/blob/59013fc0fd59f137b5e40d86c49afe08ea678941/lib/rooted_tree/node.rb#L200-L207 | train |
seblindberg/ruby-rooted_tree | lib/rooted_tree/node.rb | RootedTree.Node.+ | def +(other)
unless root? && other.root?
raise StructureException, 'Only roots can be added'
end
a = frozen? ? dup : self
b = other.frozen? ? other.dup : other
ab = self.class.new
ab << a << b
end | ruby | def +(other)
unless root? && other.root?
raise StructureException, 'Only roots can be added'
end
a = frozen? ? dup : self
b = other.frozen? ? other.dup : other
ab = self.class.new
ab << a << b
end | [
"def",
"+",
"(",
"other",
")",
"unless",
"root?",
"&&",
"other",
".",
"root?",
"raise",
"StructureException",
",",
"'Only roots can be added'",
"end",
"a",
"=",
"frozen?",
"?",
"dup",
":",
"self",
"b",
"=",
"other",
".",
"frozen?",
"?",
"other",
".",
"dup",
":",
"other",
"ab",
"=",
"self",
".",
"class",
".",
"new",
"ab",
"<<",
"a",
"<<",
"b",
"end"
] | Add two roots together to create a larger tree. A new common root will be
created and returned. Note that if the any of the root nodes are not
frozen they will be modified, and as a result seize to be roots.
@param other [Node] a Node-like object that responds true to #root?
@return [Node] a new root with the two nodes as children. | [
"Add",
"two",
"roots",
"together",
"to",
"create",
"a",
"larger",
"tree",
".",
"A",
"new",
"common",
"root",
"will",
"be",
"created",
"and",
"returned",
".",
"Note",
"that",
"if",
"the",
"any",
"of",
"the",
"root",
"nodes",
"are",
"not",
"frozen",
"they",
"will",
"be",
"modified",
"and",
"as",
"a",
"result",
"seize",
"to",
"be",
"roots",
"."
] | 59013fc0fd59f137b5e40d86c49afe08ea678941 | https://github.com/seblindberg/ruby-rooted_tree/blob/59013fc0fd59f137b5e40d86c49afe08ea678941/lib/rooted_tree/node.rb#L215-L225 | train |
Dev-Crea/swagger-docs-generator | lib/swagger_docs_generator/methods.rb | SwaggerDocsGenerator.Methods.swagger_doc | def swagger_doc(action, &block)
parse = ParserAction.new(action, &block)
parse.adding_path
end | ruby | def swagger_doc(action, &block)
parse = ParserAction.new(action, &block)
parse.adding_path
end | [
"def",
"swagger_doc",
"(",
"action",
",",
"&",
"block",
")",
"parse",
"=",
"ParserAction",
".",
"new",
"(",
"action",
",",
"&",
"block",
")",
"parse",
".",
"adding_path",
"end"
] | Complete json file with datas to method and controller. Each action to
controller is writing in temporary file. | [
"Complete",
"json",
"file",
"with",
"datas",
"to",
"method",
"and",
"controller",
".",
"Each",
"action",
"to",
"controller",
"is",
"writing",
"in",
"temporary",
"file",
"."
] | 5d3de176aa1119cb38100b451bee028d66c0809d | https://github.com/Dev-Crea/swagger-docs-generator/blob/5d3de176aa1119cb38100b451bee028d66c0809d/lib/swagger_docs_generator/methods.rb#L18-L21 | train |
Dev-Crea/swagger-docs-generator | lib/swagger_docs_generator/methods.rb | SwaggerDocsGenerator.Methods.swagger_definition | def swagger_definition(name, &block)
parse = ParserDefinition.new(name, &block)
parse.adding_definition
end | ruby | def swagger_definition(name, &block)
parse = ParserDefinition.new(name, &block)
parse.adding_definition
end | [
"def",
"swagger_definition",
"(",
"name",
",",
"&",
"block",
")",
"parse",
"=",
"ParserDefinition",
".",
"new",
"(",
"name",
",",
"&",
"block",
")",
"parse",
".",
"adding_definition",
"end"
] | Complete definitions objects for each controller. | [
"Complete",
"definitions",
"objects",
"for",
"each",
"controller",
"."
] | 5d3de176aa1119cb38100b451bee028d66c0809d | https://github.com/Dev-Crea/swagger-docs-generator/blob/5d3de176aa1119cb38100b451bee028d66c0809d/lib/swagger_docs_generator/methods.rb#L24-L27 | train |
avdgaag/whenner | lib/whenner/conversions.rb | Whenner.Conversions.Promise | def Promise(obj)
return obj.to_promise if obj.respond_to?(:to_promise)
Deferred.new.fulfill(obj)
end | ruby | def Promise(obj)
return obj.to_promise if obj.respond_to?(:to_promise)
Deferred.new.fulfill(obj)
end | [
"def",
"Promise",
"(",
"obj",
")",
"return",
"obj",
".",
"to_promise",
"if",
"obj",
".",
"respond_to?",
"(",
":to_promise",
")",
"Deferred",
".",
"new",
".",
"fulfill",
"(",
"obj",
")",
"end"
] | Convert any object to a promise. When the object in question responds to
`to_promise`, the result of that method will be returned. If not, a new
deferred object is created and immediately fulfilled with the given
object.
@param [Object] obj
@return [Promise] | [
"Convert",
"any",
"object",
"to",
"a",
"promise",
".",
"When",
"the",
"object",
"in",
"question",
"responds",
"to",
"to_promise",
"the",
"result",
"of",
"that",
"method",
"will",
"be",
"returned",
".",
"If",
"not",
"a",
"new",
"deferred",
"object",
"is",
"created",
"and",
"immediately",
"fulfilled",
"with",
"the",
"given",
"object",
"."
] | f27331435402648d02377bef9fce9ff8ae84845a | https://github.com/avdgaag/whenner/blob/f27331435402648d02377bef9fce9ff8ae84845a/lib/whenner/conversions.rb#L12-L15 | train |
DigitPaint/roger_eslint | lib/roger_eslint/lint.rb | RogerEslint.Lint.normalize_path | def normalize_path(test, path)
Pathname.new(path).relative_path_from(test.project.path.realpath).to_s
end | ruby | def normalize_path(test, path)
Pathname.new(path).relative_path_from(test.project.path.realpath).to_s
end | [
"def",
"normalize_path",
"(",
"test",
",",
"path",
")",
"Pathname",
".",
"new",
"(",
"path",
")",
".",
"relative_path_from",
"(",
"test",
".",
"project",
".",
"path",
".",
"realpath",
")",
".",
"to_s",
"end"
] | Will make path relative to project dir
@return [String] relative path | [
"Will",
"make",
"path",
"relative",
"to",
"project",
"dir"
] | 8d14a44b12fba27c6df9fc5f71920fc6cdecbf3d | https://github.com/DigitPaint/roger_eslint/blob/8d14a44b12fba27c6df9fc5f71920fc6cdecbf3d/lib/roger_eslint/lint.rb#L156-L158 | train |
syborg/mme_tools | lib/mme_tools/args_proc.rb | MMETools.ArgsProc.assert_valid_keys | def assert_valid_keys(options, valid_options)
unknown_keys = options.keys - valid_options.keys
raise(ArgumentError, "Unknown options(s): #{unknown_keys.join(", ")}") unless unknown_keys.empty?
end | ruby | def assert_valid_keys(options, valid_options)
unknown_keys = options.keys - valid_options.keys
raise(ArgumentError, "Unknown options(s): #{unknown_keys.join(", ")}") unless unknown_keys.empty?
end | [
"def",
"assert_valid_keys",
"(",
"options",
",",
"valid_options",
")",
"unknown_keys",
"=",
"options",
".",
"keys",
"-",
"valid_options",
".",
"keys",
"raise",
"(",
"ArgumentError",
",",
"\"Unknown options(s): #{unknown_keys.join(\", \")}\"",
")",
"unless",
"unknown_keys",
".",
"empty?",
"end"
] | Tests if +options+ includes only valid keys. Raises an error if
any key is not included within +valid_options+.
+valid_options+ is a Hash that must include all accepted keys. values
aren't taken into account. | [
"Tests",
"if",
"+",
"options",
"+",
"includes",
"only",
"valid",
"keys",
".",
"Raises",
"an",
"error",
"if",
"any",
"key",
"is",
"not",
"included",
"within",
"+",
"valid_options",
"+",
".",
"+",
"valid_options",
"+",
"is",
"a",
"Hash",
"that",
"must",
"include",
"all",
"accepted",
"keys",
".",
"values",
"aren",
"t",
"taken",
"into",
"account",
"."
] | e93919f7fcfb408b941d6144290991a7feabaa7d | https://github.com/syborg/mme_tools/blob/e93919f7fcfb408b941d6144290991a7feabaa7d/lib/mme_tools/args_proc.rb#L18-L21 | train |
mrackwitz/CLIntegracon | lib/CLIntegracon/formatter.rb | CLIntegracon.Formatter.describe_file_diff | def describe_file_diff(diff, max_width=80)
description = []
description << "File comparison error `#{diff.relative_path}` for #{spec.spec_folder}:"
description << "--- DIFF ".ljust(max_width, '-')
description += diff.map do |line|
case line
when /^\+/ then line.green
when /^-/ then line.red
else line
end.gsub("\n",'').gsub("\r", '\r')
end
description << "--- END ".ljust(max_width, '-')
description << ''
description * "\n"
end | ruby | def describe_file_diff(diff, max_width=80)
description = []
description << "File comparison error `#{diff.relative_path}` for #{spec.spec_folder}:"
description << "--- DIFF ".ljust(max_width, '-')
description += diff.map do |line|
case line
when /^\+/ then line.green
when /^-/ then line.red
else line
end.gsub("\n",'').gsub("\r", '\r')
end
description << "--- END ".ljust(max_width, '-')
description << ''
description * "\n"
end | [
"def",
"describe_file_diff",
"(",
"diff",
",",
"max_width",
"=",
"80",
")",
"description",
"=",
"[",
"]",
"description",
"<<",
"\"File comparison error `#{diff.relative_path}` for #{spec.spec_folder}:\"",
"description",
"<<",
"\"--- DIFF \"",
".",
"ljust",
"(",
"max_width",
",",
"'-'",
")",
"description",
"+=",
"diff",
".",
"map",
"do",
"|",
"line",
"|",
"case",
"line",
"when",
"/",
"\\+",
"/",
"then",
"line",
".",
"green",
"when",
"/",
"/",
"then",
"line",
".",
"red",
"else",
"line",
"end",
".",
"gsub",
"(",
"\"\\n\"",
",",
"''",
")",
".",
"gsub",
"(",
"\"\\r\"",
",",
"'\\r'",
")",
"end",
"description",
"<<",
"\"--- END \"",
".",
"ljust",
"(",
"max_width",
",",
"'-'",
")",
"description",
"<<",
"''",
"description",
"*",
"\"\\n\"",
"end"
] | Return a description text for an expectation that two files were
expected to be the same, but are not.
@param [Diff] diff
the diff which holds the difference
@param [Integer] max_width
the max width of the terminal to print matching separators
@return [String] | [
"Return",
"a",
"description",
"text",
"for",
"an",
"expectation",
"that",
"two",
"files",
"were",
"expected",
"to",
"be",
"the",
"same",
"but",
"are",
"not",
"."
] | b675f23762d10e527487aa5576d6a77f9c623485 | https://github.com/mrackwitz/CLIntegracon/blob/b675f23762d10e527487aa5576d6a77f9c623485/lib/CLIntegracon/formatter.rb#L145-L159 | train |
mohan/gitkite | app/controllers/gitkite/gitkit_controller.rb | Gitkite.GitkitController.sign_in_success | def sign_in_success
g_user = signed_in?
if g_user
user = {
:email => g_user.email,
:user_id => g_user.user_id,
:name => g_user.name,
:photo_url => g_user.photo_url,
:provider_id => g_user.provider_id
}
@user = User.find_by(user_id: user[:user_id])
if @user.nil?
@user = User.create user
else
@user.update user
end
session[:user] = @user.id
if session[:previous_url]
previous_url = session[:previous_url]
session.delete :previous_url
redirect_to previous_url
else
redirect_to main_app.root_url
end
else
@user = false
session.delete :user
flash.alert = "Sign in failed. Please try again."
redirect_to gitkit_sign_in_url
end
end | ruby | def sign_in_success
g_user = signed_in?
if g_user
user = {
:email => g_user.email,
:user_id => g_user.user_id,
:name => g_user.name,
:photo_url => g_user.photo_url,
:provider_id => g_user.provider_id
}
@user = User.find_by(user_id: user[:user_id])
if @user.nil?
@user = User.create user
else
@user.update user
end
session[:user] = @user.id
if session[:previous_url]
previous_url = session[:previous_url]
session.delete :previous_url
redirect_to previous_url
else
redirect_to main_app.root_url
end
else
@user = false
session.delete :user
flash.alert = "Sign in failed. Please try again."
redirect_to gitkit_sign_in_url
end
end | [
"def",
"sign_in_success",
"g_user",
"=",
"signed_in?",
"if",
"g_user",
"user",
"=",
"{",
":email",
"=>",
"g_user",
".",
"email",
",",
":user_id",
"=>",
"g_user",
".",
"user_id",
",",
":name",
"=>",
"g_user",
".",
"name",
",",
":photo_url",
"=>",
"g_user",
".",
"photo_url",
",",
":provider_id",
"=>",
"g_user",
".",
"provider_id",
"}",
"@user",
"=",
"User",
".",
"find_by",
"(",
"user_id",
":",
"user",
"[",
":user_id",
"]",
")",
"if",
"@user",
".",
"nil?",
"@user",
"=",
"User",
".",
"create",
"user",
"else",
"@user",
".",
"update",
"user",
"end",
"session",
"[",
":user",
"]",
"=",
"@user",
".",
"id",
"if",
"session",
"[",
":previous_url",
"]",
"previous_url",
"=",
"session",
"[",
":previous_url",
"]",
"session",
".",
"delete",
":previous_url",
"redirect_to",
"previous_url",
"else",
"redirect_to",
"main_app",
".",
"root_url",
"end",
"else",
"@user",
"=",
"false",
"session",
".",
"delete",
":user",
"flash",
".",
"alert",
"=",
"\"Sign in failed. Please try again.\"",
"redirect_to",
"gitkit_sign_in_url",
"end",
"end"
] | This will be called after successfull signin | [
"This",
"will",
"be",
"called",
"after",
"successfull",
"signin"
] | c6ebefecdd44d1dfd30a41190e7661da877c091d | https://github.com/mohan/gitkite/blob/c6ebefecdd44d1dfd30a41190e7661da877c091d/app/controllers/gitkite/gitkit_controller.rb#L18-L54 | train |
codescrum/bebox | lib/bebox/files_helper.rb | Bebox.FilesHelper.render_erb_template | def render_erb_template(template_path, options)
require 'tilt'
Tilt::ERBTemplate.new(template_path).render(nil, options)
end | ruby | def render_erb_template(template_path, options)
require 'tilt'
Tilt::ERBTemplate.new(template_path).render(nil, options)
end | [
"def",
"render_erb_template",
"(",
"template_path",
",",
"options",
")",
"require",
"'tilt'",
"Tilt",
"::",
"ERBTemplate",
".",
"new",
"(",
"template_path",
")",
".",
"render",
"(",
"nil",
",",
"options",
")",
"end"
] | Render a template for file content | [
"Render",
"a",
"template",
"for",
"file",
"content"
] | 0d19315847103341e599d32837ab0bd75524e5be | https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/files_helper.rb#L15-L18 | train |
codescrum/bebox | lib/bebox/files_helper.rb | Bebox.FilesHelper.write_content_to_file | def write_content_to_file(file_path, content)
File.open(file_path, 'w') do |f|
f.write content
end
end | ruby | def write_content_to_file(file_path, content)
File.open(file_path, 'w') do |f|
f.write content
end
end | [
"def",
"write_content_to_file",
"(",
"file_path",
",",
"content",
")",
"File",
".",
"open",
"(",
"file_path",
",",
"'w'",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"content",
"end",
"end"
] | Write content to a file | [
"Write",
"content",
"to",
"a",
"file"
] | 0d19315847103341e599d32837ab0bd75524e5be | https://github.com/codescrum/bebox/blob/0d19315847103341e599d32837ab0bd75524e5be/lib/bebox/files_helper.rb#L21-L25 | train |
triglav-dataflow/triglav-client-ruby | lib/triglav_client/api/resources_api.rb | TriglavClient.ResourcesApi.create_resource | def create_resource(resource, opts = {})
data, _status_code, _headers = create_resource_with_http_info(resource, opts)
return data
end | ruby | def create_resource(resource, opts = {})
data, _status_code, _headers = create_resource_with_http_info(resource, opts)
return data
end | [
"def",
"create_resource",
"(",
"resource",
",",
"opts",
"=",
"{",
"}",
")",
"data",
",",
"_status_code",
",",
"_headers",
"=",
"create_resource_with_http_info",
"(",
"resource",
",",
"opts",
")",
"return",
"data",
"end"
] | Creates a new resource
@param resource Resource to add
@param [Hash] opts the optional parameters
@return [ResourceResponse] | [
"Creates",
"a",
"new",
"resource"
] | b2f3781d65ee032ba96eb703fbd789c713a5e0bd | https://github.com/triglav-dataflow/triglav-client-ruby/blob/b2f3781d65ee032ba96eb703fbd789c713a5e0bd/lib/triglav_client/api/resources_api.rb#L39-L42 | train |
triglav-dataflow/triglav-client-ruby | lib/triglav_client/api/resources_api.rb | TriglavClient.ResourcesApi.get_resource | def get_resource(id_or_uri, opts = {})
data, _status_code, _headers = get_resource_with_http_info(id_or_uri, opts)
return data
end | ruby | def get_resource(id_or_uri, opts = {})
data, _status_code, _headers = get_resource_with_http_info(id_or_uri, opts)
return data
end | [
"def",
"get_resource",
"(",
"id_or_uri",
",",
"opts",
"=",
"{",
"}",
")",
"data",
",",
"_status_code",
",",
"_headers",
"=",
"get_resource_with_http_info",
"(",
"id_or_uri",
",",
"opts",
")",
"return",
"data",
"end"
] | Returns a single resource
@param id_or_uri ID or URI of resource to fetch
@param [Hash] opts the optional parameters
@return [ResourceResponse] | [
"Returns",
"a",
"single",
"resource"
] | b2f3781d65ee032ba96eb703fbd789c713a5e0bd | https://github.com/triglav-dataflow/triglav-client-ruby/blob/b2f3781d65ee032ba96eb703fbd789c713a5e0bd/lib/triglav_client/api/resources_api.rb#L152-L155 | train |
triglav-dataflow/triglav-client-ruby | lib/triglav_client/api/resources_api.rb | TriglavClient.ResourcesApi.list_aggregated_resources | def list_aggregated_resources(uri_prefix, opts = {})
data, _status_code, _headers = list_aggregated_resources_with_http_info(uri_prefix, opts)
return data
end | ruby | def list_aggregated_resources(uri_prefix, opts = {})
data, _status_code, _headers = list_aggregated_resources_with_http_info(uri_prefix, opts)
return data
end | [
"def",
"list_aggregated_resources",
"(",
"uri_prefix",
",",
"opts",
"=",
"{",
"}",
")",
"data",
",",
"_status_code",
",",
"_headers",
"=",
"list_aggregated_resources_with_http_info",
"(",
"uri_prefix",
",",
"opts",
")",
"return",
"data",
"end"
] | Returns aggregated resources to be monitored
@param uri_prefix Prefix of Resource URI
@param [Hash] opts the optional parameters
@return [Array<AggregatedResourceEachResponse>] | [
"Returns",
"aggregated",
"resources",
"to",
"be",
"monitored"
] | b2f3781d65ee032ba96eb703fbd789c713a5e0bd | https://github.com/triglav-dataflow/triglav-client-ruby/blob/b2f3781d65ee032ba96eb703fbd789c713a5e0bd/lib/triglav_client/api/resources_api.rb#L209-L212 | train |
triglav-dataflow/triglav-client-ruby | lib/triglav_client/api/resources_api.rb | TriglavClient.ResourcesApi.update_resource | def update_resource(id_or_uri, resource, opts = {})
data, _status_code, _headers = update_resource_with_http_info(id_or_uri, resource, opts)
return data
end | ruby | def update_resource(id_or_uri, resource, opts = {})
data, _status_code, _headers = update_resource_with_http_info(id_or_uri, resource, opts)
return data
end | [
"def",
"update_resource",
"(",
"id_or_uri",
",",
"resource",
",",
"opts",
"=",
"{",
"}",
")",
"data",
",",
"_status_code",
",",
"_headers",
"=",
"update_resource_with_http_info",
"(",
"id_or_uri",
",",
"resource",
",",
"opts",
")",
"return",
"data",
"end"
] | Updates a single resource
@param id_or_uri ID or URI of resource to fetch
@param resource Resource parameters to update
@param [Hash] opts the optional parameters
@return [ResourceResponse] | [
"Updates",
"a",
"single",
"resource"
] | b2f3781d65ee032ba96eb703fbd789c713a5e0bd | https://github.com/triglav-dataflow/triglav-client-ruby/blob/b2f3781d65ee032ba96eb703fbd789c713a5e0bd/lib/triglav_client/api/resources_api.rb#L324-L327 | train |
tnorthb/coinstack | lib/coinstack/list.rb | Coinstack.UserPair.add_list_data | def add_list_data(data)
raise symbol.to_s if data.nil?
self.exchange_rate = data['price_usd'].to_f
self.perchant_change_week = data['percent_change_7d'].to_f
self.perchant_change_day = data['percent_change_24h'].to_f
end | ruby | def add_list_data(data)
raise symbol.to_s if data.nil?
self.exchange_rate = data['price_usd'].to_f
self.perchant_change_week = data['percent_change_7d'].to_f
self.perchant_change_day = data['percent_change_24h'].to_f
end | [
"def",
"add_list_data",
"(",
"data",
")",
"raise",
"symbol",
".",
"to_s",
"if",
"data",
".",
"nil?",
"self",
".",
"exchange_rate",
"=",
"data",
"[",
"'price_usd'",
"]",
".",
"to_f",
"self",
".",
"perchant_change_week",
"=",
"data",
"[",
"'percent_change_7d'",
"]",
".",
"to_f",
"self",
".",
"perchant_change_day",
"=",
"data",
"[",
"'percent_change_24h'",
"]",
".",
"to_f",
"end"
] | Builds a UserPair given the related CMC data | [
"Builds",
"a",
"UserPair",
"given",
"the",
"related",
"CMC",
"data"
] | 1316fd069f502fa04fe15bc6ab7e63302aa29fd8 | https://github.com/tnorthb/coinstack/blob/1316fd069f502fa04fe15bc6ab7e63302aa29fd8/lib/coinstack/list.rb#L87-L92 | train |
arvicco/poster | lib/poster/forum.rb | Poster.Forum.new_topic | def new_topic board: 92, subj: 'test', msg: 'msg', icon: "exclamation"
board = board.instance_of?(Symbol) ? @opts[:boards][board] : board
# Check board posting page first (to get sequence numbers)
get "/index.php?action=post;board=#{board}.0"
raise "Not logged, cannot post!" unless logged?
p msg
# Create new post
seqnum, sc = find_fields 'seqnum', 'sc'
subj = xml_encode(subj_encode(subj))
msg = xml_encode(msg)
# p subj, msg
# exit
post "/index.php?action=post2;start=0;board=#{board}",
content_type: 'multipart/form-data; charset=ISO-8859-1',
body: { topic: 0, subject: subj, icon: icon, message: msg,
notify: 0, do_watch: 0, selfmod: 0, lock: 0, goback: 1, ns: "NS", post: "Post",
additional_options: 0, sc: sc, seqnum: seqnum },
options: {timeout: 5} # open/read timeout in seconds
# Make sure the message was posted, return topic page
new_topic = @response.headers['location']
# p @response.body
raise "No redirect to posted topic!" unless new_topic && @response.status == 302
get new_topic
end | ruby | def new_topic board: 92, subj: 'test', msg: 'msg', icon: "exclamation"
board = board.instance_of?(Symbol) ? @opts[:boards][board] : board
# Check board posting page first (to get sequence numbers)
get "/index.php?action=post;board=#{board}.0"
raise "Not logged, cannot post!" unless logged?
p msg
# Create new post
seqnum, sc = find_fields 'seqnum', 'sc'
subj = xml_encode(subj_encode(subj))
msg = xml_encode(msg)
# p subj, msg
# exit
post "/index.php?action=post2;start=0;board=#{board}",
content_type: 'multipart/form-data; charset=ISO-8859-1',
body: { topic: 0, subject: subj, icon: icon, message: msg,
notify: 0, do_watch: 0, selfmod: 0, lock: 0, goback: 1, ns: "NS", post: "Post",
additional_options: 0, sc: sc, seqnum: seqnum },
options: {timeout: 5} # open/read timeout in seconds
# Make sure the message was posted, return topic page
new_topic = @response.headers['location']
# p @response.body
raise "No redirect to posted topic!" unless new_topic && @response.status == 302
get new_topic
end | [
"def",
"new_topic",
"board",
":",
"92",
",",
"subj",
":",
"'test'",
",",
"msg",
":",
"'msg'",
",",
"icon",
":",
"\"exclamation\"",
"board",
"=",
"board",
".",
"instance_of?",
"(",
"Symbol",
")",
"?",
"@opts",
"[",
":boards",
"]",
"[",
"board",
"]",
":",
"board",
"get",
"\"/index.php?action=post;board=#{board}.0\"",
"raise",
"\"Not logged, cannot post!\"",
"unless",
"logged?",
"p",
"msg",
"seqnum",
",",
"sc",
"=",
"find_fields",
"'seqnum'",
",",
"'sc'",
"subj",
"=",
"xml_encode",
"(",
"subj_encode",
"(",
"subj",
")",
")",
"msg",
"=",
"xml_encode",
"(",
"msg",
")",
"post",
"\"/index.php?action=post2;start=0;board=#{board}\"",
",",
"content_type",
":",
"'multipart/form-data; charset=ISO-8859-1'",
",",
"body",
":",
"{",
"topic",
":",
"0",
",",
"subject",
":",
"subj",
",",
"icon",
":",
"icon",
",",
"message",
":",
"msg",
",",
"notify",
":",
"0",
",",
"do_watch",
":",
"0",
",",
"selfmod",
":",
"0",
",",
"lock",
":",
"0",
",",
"goback",
":",
"1",
",",
"ns",
":",
"\"NS\"",
",",
"post",
":",
"\"Post\"",
",",
"additional_options",
":",
"0",
",",
"sc",
":",
"sc",
",",
"seqnum",
":",
"seqnum",
"}",
",",
"options",
":",
"{",
"timeout",
":",
"5",
"}",
"new_topic",
"=",
"@response",
".",
"headers",
"[",
"'location'",
"]",
"raise",
"\"No redirect to posted topic!\"",
"unless",
"new_topic",
"&&",
"@response",
".",
"status",
"==",
"302",
"get",
"new_topic",
"end"
] | Post new topic | [
"Post",
"new",
"topic"
] | a5f22f7cb02116ab4dc5b7f2bdb672306b3dac63 | https://github.com/arvicco/poster/blob/a5f22f7cb02116ab4dc5b7f2bdb672306b3dac63/lib/poster/forum.rb#L21-L46 | train |
notCalle/ruby-tangle | lib/tangle/base_graph_private.rb | Tangle.BaseGraphPrivate.each_vertex_breadth_first | def each_vertex_breadth_first(start_vertex, walk_method)
remaining = [start_vertex]
remaining.each_with_object([]) do |vertex, history|
history << vertex
yield vertex
send(walk_method, vertex).each do |other|
remaining << other unless history.include?(other)
end
end
end | ruby | def each_vertex_breadth_first(start_vertex, walk_method)
remaining = [start_vertex]
remaining.each_with_object([]) do |vertex, history|
history << vertex
yield vertex
send(walk_method, vertex).each do |other|
remaining << other unless history.include?(other)
end
end
end | [
"def",
"each_vertex_breadth_first",
"(",
"start_vertex",
",",
"walk_method",
")",
"remaining",
"=",
"[",
"start_vertex",
"]",
"remaining",
".",
"each_with_object",
"(",
"[",
"]",
")",
"do",
"|",
"vertex",
",",
"history",
"|",
"history",
"<<",
"vertex",
"yield",
"vertex",
"send",
"(",
"walk_method",
",",
"vertex",
")",
".",
"each",
"do",
"|",
"other",
"|",
"remaining",
"<<",
"other",
"unless",
"history",
".",
"include?",
"(",
"other",
")",
"end",
"end",
"end"
] | Yield each reachable vertex to a block, breadth first | [
"Yield",
"each",
"reachable",
"vertex",
"to",
"a",
"block",
"breadth",
"first"
] | ccafab96835a0644b05ae749066d7ec7ecada260 | https://github.com/notCalle/ruby-tangle/blob/ccafab96835a0644b05ae749066d7ec7ecada260/lib/tangle/base_graph_private.rb#L25-L34 | train |
LifebookerInc/requires_approval | lib/requires_approval.rb | RequiresApproval.ClassMethods.create_versions_class | def create_versions_class
versions_table_name = self.versions_table_name
self.const_set self.versions_class_name, Class.new(ActiveRecord::Base)
self.versions_class.class_eval do
self.table_name = versions_table_name
# Whitelist public attributes
# Everything since this class is for internal use only
public_attributes = self.column_names.reject{|attr| self.protected_attributes.deny?(attr)}
self.attr_accessible(*public_attributes)
end
end | ruby | def create_versions_class
versions_table_name = self.versions_table_name
self.const_set self.versions_class_name, Class.new(ActiveRecord::Base)
self.versions_class.class_eval do
self.table_name = versions_table_name
# Whitelist public attributes
# Everything since this class is for internal use only
public_attributes = self.column_names.reject{|attr| self.protected_attributes.deny?(attr)}
self.attr_accessible(*public_attributes)
end
end | [
"def",
"create_versions_class",
"versions_table_name",
"=",
"self",
".",
"versions_table_name",
"self",
".",
"const_set",
"self",
".",
"versions_class_name",
",",
"Class",
".",
"new",
"(",
"ActiveRecord",
"::",
"Base",
")",
"self",
".",
"versions_class",
".",
"class_eval",
"do",
"self",
".",
"table_name",
"=",
"versions_table_name",
"public_attributes",
"=",
"self",
".",
"column_names",
".",
"reject",
"{",
"|",
"attr",
"|",
"self",
".",
"protected_attributes",
".",
"deny?",
"(",
"attr",
")",
"}",
"self",
".",
"attr_accessible",
"(",
"*",
"public_attributes",
")",
"end",
"end"
] | create a class | [
"create",
"a",
"class"
] | 83b18b4693143777108b5e066b252ebff9263cbc | https://github.com/LifebookerInc/requires_approval/blob/83b18b4693143777108b5e066b252ebff9263cbc/lib/requires_approval.rb#L294-L307 | train |
jns/Aims | lib/aims/geometry.rb | Aims.Geometry.make_bonds | def make_bonds(bond_length = 3.0)
# initialize an empty array
@bonds = Array.new
# Make bonds between all atoms
# stack = atoms.dup
atoms_extended = atoms.dup
if periodic?
v1 = lattice_vectors[0]
v2 = lattice_vectors[1]
atoms.each{|a|
[-1, 0, 1].each{|n1|
[-1, 0, 1].each{|n2|
atoms_extended << a.displace(n1*v1[0] + n2*v2[0], n1*v1[1] + n2*v2[1], n1*v1[2] + n2*v2[2])
}
}
}
end
tree = KDTree.new(atoms_extended, 3)
atoms.each{|a|
r = 4
neighbors = tree.find([a.x-r, a.x+r], [a.y-r, a.y+r], [a.z-r, a.z+r])
neighbors.each{|n|
b = Bond.new(a, n)
@bonds << b if b.length < bond_length
}
}
# atom1 = stack.pop
# while (not stack.empty?)
# stack.each{|atom2|
# b = Bond.new(atom1, atom2)
# @bonds << b if b.length < bond_length
# if periodic?
# v1 = lattice_vectors[0]
# v2 = lattice_vectors[1]
# [-1, 0, 1].each{|n1|
# [-1, 0, 1].each{|n2|
# b = Bond.new(atom1, atom2.displace(n1*v1[0] + n2*v2[0], n1*v1[1] + n2*v2[1], n1*v1[2] + n2*v2[2]))
# @bonds << b if b.length < bond_length
# }
# }
# end
# }
# atom1 = stack.pop
# end
end | ruby | def make_bonds(bond_length = 3.0)
# initialize an empty array
@bonds = Array.new
# Make bonds between all atoms
# stack = atoms.dup
atoms_extended = atoms.dup
if periodic?
v1 = lattice_vectors[0]
v2 = lattice_vectors[1]
atoms.each{|a|
[-1, 0, 1].each{|n1|
[-1, 0, 1].each{|n2|
atoms_extended << a.displace(n1*v1[0] + n2*v2[0], n1*v1[1] + n2*v2[1], n1*v1[2] + n2*v2[2])
}
}
}
end
tree = KDTree.new(atoms_extended, 3)
atoms.each{|a|
r = 4
neighbors = tree.find([a.x-r, a.x+r], [a.y-r, a.y+r], [a.z-r, a.z+r])
neighbors.each{|n|
b = Bond.new(a, n)
@bonds << b if b.length < bond_length
}
}
# atom1 = stack.pop
# while (not stack.empty?)
# stack.each{|atom2|
# b = Bond.new(atom1, atom2)
# @bonds << b if b.length < bond_length
# if periodic?
# v1 = lattice_vectors[0]
# v2 = lattice_vectors[1]
# [-1, 0, 1].each{|n1|
# [-1, 0, 1].each{|n2|
# b = Bond.new(atom1, atom2.displace(n1*v1[0] + n2*v2[0], n1*v1[1] + n2*v2[1], n1*v1[2] + n2*v2[2]))
# @bonds << b if b.length < bond_length
# }
# }
# end
# }
# atom1 = stack.pop
# end
end | [
"def",
"make_bonds",
"(",
"bond_length",
"=",
"3.0",
")",
"@bonds",
"=",
"Array",
".",
"new",
"atoms_extended",
"=",
"atoms",
".",
"dup",
"if",
"periodic?",
"v1",
"=",
"lattice_vectors",
"[",
"0",
"]",
"v2",
"=",
"lattice_vectors",
"[",
"1",
"]",
"atoms",
".",
"each",
"{",
"|",
"a",
"|",
"[",
"-",
"1",
",",
"0",
",",
"1",
"]",
".",
"each",
"{",
"|",
"n1",
"|",
"[",
"-",
"1",
",",
"0",
",",
"1",
"]",
".",
"each",
"{",
"|",
"n2",
"|",
"atoms_extended",
"<<",
"a",
".",
"displace",
"(",
"n1",
"*",
"v1",
"[",
"0",
"]",
"+",
"n2",
"*",
"v2",
"[",
"0",
"]",
",",
"n1",
"*",
"v1",
"[",
"1",
"]",
"+",
"n2",
"*",
"v2",
"[",
"1",
"]",
",",
"n1",
"*",
"v1",
"[",
"2",
"]",
"+",
"n2",
"*",
"v2",
"[",
"2",
"]",
")",
"}",
"}",
"}",
"end",
"tree",
"=",
"KDTree",
".",
"new",
"(",
"atoms_extended",
",",
"3",
")",
"atoms",
".",
"each",
"{",
"|",
"a",
"|",
"r",
"=",
"4",
"neighbors",
"=",
"tree",
".",
"find",
"(",
"[",
"a",
".",
"x",
"-",
"r",
",",
"a",
".",
"x",
"+",
"r",
"]",
",",
"[",
"a",
".",
"y",
"-",
"r",
",",
"a",
".",
"y",
"+",
"r",
"]",
",",
"[",
"a",
".",
"z",
"-",
"r",
",",
"a",
".",
"z",
"+",
"r",
"]",
")",
"neighbors",
".",
"each",
"{",
"|",
"n",
"|",
"b",
"=",
"Bond",
".",
"new",
"(",
"a",
",",
"n",
")",
"@bonds",
"<<",
"b",
"if",
"b",
".",
"length",
"<",
"bond_length",
"}",
"}",
"end"
] | Generate and cache bonds for this geometry.
A bond will be generated for every pair of atoms closer than +bond_length+ | [
"Generate",
"and",
"cache",
"bonds",
"for",
"this",
"geometry",
".",
"A",
"bond",
"will",
"be",
"generated",
"for",
"every",
"pair",
"of",
"atoms",
"closer",
"than",
"+",
"bond_length",
"+"
] | 2dcb6c02cd05b2d0c8ab72be4e85d60375df296c | https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/geometry.rb#L128-L175 | train |
jns/Aims | lib/aims/geometry.rb | Aims.Geometry.recache_visible_atoms | def recache_visible_atoms(makeBonds = false)
plane_count = (@clip_planes ? @clip_planes.length : 0)
return if plane_count == 0
if @visibleAtoms
@visibleAtoms.clear
else
@visibleAtoms = []
end
@atoms.each{|a|
i = plane_count
@clip_planes.each{|p|
i = i-1 if 0 >= p.distance_to_point(a.x, a.y, a.z)
}
@visibleAtoms << a if i == 0
}
if @visibleBonds
@visibleBonds.clear
else
@visibleBonds = []
end
make_bonds if (makeBonds or @bonds.nil?)
@bonds.each{|b|
a0 = b[0]
a1 = b[1]
i0 = plane_count
i1 = plane_count
@clip_planes.each{|p|
i0 = i0-1 if 0 >= p.distance_to_point(a0.x, a0.y, a0.z)
i1 = i1-1 if 0 >= p.distance_to_point(a1.x, a1.y, a1.z)
}
@visibleBonds << b if (i0 + i1) < 2
}
end | ruby | def recache_visible_atoms(makeBonds = false)
plane_count = (@clip_planes ? @clip_planes.length : 0)
return if plane_count == 0
if @visibleAtoms
@visibleAtoms.clear
else
@visibleAtoms = []
end
@atoms.each{|a|
i = plane_count
@clip_planes.each{|p|
i = i-1 if 0 >= p.distance_to_point(a.x, a.y, a.z)
}
@visibleAtoms << a if i == 0
}
if @visibleBonds
@visibleBonds.clear
else
@visibleBonds = []
end
make_bonds if (makeBonds or @bonds.nil?)
@bonds.each{|b|
a0 = b[0]
a1 = b[1]
i0 = plane_count
i1 = plane_count
@clip_planes.each{|p|
i0 = i0-1 if 0 >= p.distance_to_point(a0.x, a0.y, a0.z)
i1 = i1-1 if 0 >= p.distance_to_point(a1.x, a1.y, a1.z)
}
@visibleBonds << b if (i0 + i1) < 2
}
end | [
"def",
"recache_visible_atoms",
"(",
"makeBonds",
"=",
"false",
")",
"plane_count",
"=",
"(",
"@clip_planes",
"?",
"@clip_planes",
".",
"length",
":",
"0",
")",
"return",
"if",
"plane_count",
"==",
"0",
"if",
"@visibleAtoms",
"@visibleAtoms",
".",
"clear",
"else",
"@visibleAtoms",
"=",
"[",
"]",
"end",
"@atoms",
".",
"each",
"{",
"|",
"a",
"|",
"i",
"=",
"plane_count",
"@clip_planes",
".",
"each",
"{",
"|",
"p",
"|",
"i",
"=",
"i",
"-",
"1",
"if",
"0",
">=",
"p",
".",
"distance_to_point",
"(",
"a",
".",
"x",
",",
"a",
".",
"y",
",",
"a",
".",
"z",
")",
"}",
"@visibleAtoms",
"<<",
"a",
"if",
"i",
"==",
"0",
"}",
"if",
"@visibleBonds",
"@visibleBonds",
".",
"clear",
"else",
"@visibleBonds",
"=",
"[",
"]",
"end",
"make_bonds",
"if",
"(",
"makeBonds",
"or",
"@bonds",
".",
"nil?",
")",
"@bonds",
".",
"each",
"{",
"|",
"b",
"|",
"a0",
"=",
"b",
"[",
"0",
"]",
"a1",
"=",
"b",
"[",
"1",
"]",
"i0",
"=",
"plane_count",
"i1",
"=",
"plane_count",
"@clip_planes",
".",
"each",
"{",
"|",
"p",
"|",
"i0",
"=",
"i0",
"-",
"1",
"if",
"0",
">=",
"p",
".",
"distance_to_point",
"(",
"a0",
".",
"x",
",",
"a0",
".",
"y",
",",
"a0",
".",
"z",
")",
"i1",
"=",
"i1",
"-",
"1",
"if",
"0",
">=",
"p",
".",
"distance_to_point",
"(",
"a1",
".",
"x",
",",
"a1",
".",
"y",
",",
"a1",
".",
"z",
")",
"}",
"@visibleBonds",
"<<",
"b",
"if",
"(",
"i0",
"+",
"i1",
")",
"<",
"2",
"}",
"end"
] | Recompute the atoms that are behind all the clip planes
Atoms that are in front of any clip-plane are considered invisible. | [
"Recompute",
"the",
"atoms",
"that",
"are",
"behind",
"all",
"the",
"clip",
"planes",
"Atoms",
"that",
"are",
"in",
"front",
"of",
"any",
"clip",
"-",
"plane",
"are",
"considered",
"invisible",
"."
] | 2dcb6c02cd05b2d0c8ab72be4e85d60375df296c | https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/geometry.rb#L299-L337 | train |
jns/Aims | lib/aims/geometry.rb | Aims.Geometry.center | def center(visible_only = true)
if atoms.empty?
return Atom.new(0,0,0)
else
bounds = bounding_box(visible_only)
x = (bounds[0].x + bounds[1].x)/2.0
y = (bounds[0].y + bounds[1].y)/2.0
z = (bounds[0].z + bounds[1].z)/2.0
return Atom.new(x,y,z)
end
end | ruby | def center(visible_only = true)
if atoms.empty?
return Atom.new(0,0,0)
else
bounds = bounding_box(visible_only)
x = (bounds[0].x + bounds[1].x)/2.0
y = (bounds[0].y + bounds[1].y)/2.0
z = (bounds[0].z + bounds[1].z)/2.0
return Atom.new(x,y,z)
end
end | [
"def",
"center",
"(",
"visible_only",
"=",
"true",
")",
"if",
"atoms",
".",
"empty?",
"return",
"Atom",
".",
"new",
"(",
"0",
",",
"0",
",",
"0",
")",
"else",
"bounds",
"=",
"bounding_box",
"(",
"visible_only",
")",
"x",
"=",
"(",
"bounds",
"[",
"0",
"]",
".",
"x",
"+",
"bounds",
"[",
"1",
"]",
".",
"x",
")",
"/",
"2.0",
"y",
"=",
"(",
"bounds",
"[",
"0",
"]",
".",
"y",
"+",
"bounds",
"[",
"1",
"]",
".",
"y",
")",
"/",
"2.0",
"z",
"=",
"(",
"bounds",
"[",
"0",
"]",
".",
"z",
"+",
"bounds",
"[",
"1",
"]",
".",
"z",
")",
"/",
"2.0",
"return",
"Atom",
".",
"new",
"(",
"x",
",",
"y",
",",
"z",
")",
"end",
"end"
] | Return an Atom whose coordinates are the center of the unit-cell. | [
"Return",
"an",
"Atom",
"whose",
"coordinates",
"are",
"the",
"center",
"of",
"the",
"unit",
"-",
"cell",
"."
] | 2dcb6c02cd05b2d0c8ab72be4e85d60375df296c | https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/geometry.rb#L429-L439 | train |
jns/Aims | lib/aims/geometry.rb | Aims.Geometry.displace | def displace(x,y,z)
Geometry.new(atoms(:all).collect{|a|
a.displace(x,y,z)
}, self.lattice_vectors)
#TODO copy miller indices
end | ruby | def displace(x,y,z)
Geometry.new(atoms(:all).collect{|a|
a.displace(x,y,z)
}, self.lattice_vectors)
#TODO copy miller indices
end | [
"def",
"displace",
"(",
"x",
",",
"y",
",",
"z",
")",
"Geometry",
".",
"new",
"(",
"atoms",
"(",
":all",
")",
".",
"collect",
"{",
"|",
"a",
"|",
"a",
".",
"displace",
"(",
"x",
",",
"y",
",",
"z",
")",
"}",
",",
"self",
".",
"lattice_vectors",
")",
"end"
] | Return a new unit cell with all the atoms displaced by the amount x,y,z | [
"Return",
"a",
"new",
"unit",
"cell",
"with",
"all",
"the",
"atoms",
"displaced",
"by",
"the",
"amount",
"x",
"y",
"z"
] | 2dcb6c02cd05b2d0c8ab72be4e85d60375df296c | https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/geometry.rb#L463-L468 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.