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 |
---|---|---|---|---|---|---|---|---|---|---|---|
wapcaplet/kelp | lib/kelp/xpath.rb | Kelp.XPaths.xpath_row_containing | def xpath_row_containing(texts)
texts = [texts] if texts.class == String
conditions = texts.collect do |text|
"contains(., #{xpath_sanitize(text)})"
end.join(' and ')
return ".//tr[#{conditions}]"
end | ruby | def xpath_row_containing(texts)
texts = [texts] if texts.class == String
conditions = texts.collect do |text|
"contains(., #{xpath_sanitize(text)})"
end.join(' and ')
return ".//tr[#{conditions}]"
end | [
"def",
"xpath_row_containing",
"(",
"texts",
")",
"texts",
"=",
"[",
"texts",
"]",
"if",
"texts",
".",
"class",
"==",
"String",
"conditions",
"=",
"texts",
".",
"collect",
"do",
"|",
"text",
"|",
"\"contains(., #{xpath_sanitize(text)})\"",
"end",
".",
"join",
"(",
"' and '",
")",
"return",
"\".//tr[#{conditions}]\"",
"end"
] | Return an XPath for any table row containing all strings in `texts`,
within the current context. | [
"Return",
"an",
"XPath",
"for",
"any",
"table",
"row",
"containing",
"all",
"strings",
"in",
"texts",
"within",
"the",
"current",
"context",
"."
] | 592fe188db5a3d05e6120ed2157ad8d781601b7a | https://github.com/wapcaplet/kelp/blob/592fe188db5a3d05e6120ed2157ad8d781601b7a/lib/kelp/xpath.rb#L7-L13 | train |
ianwhite/response_for | lib/response_for/action_controller.rb | ResponseFor.ActionController.respond_to_action_responses | def respond_to_action_responses
if !respond_to_performed? && action_responses.any?
respond_to do |responder|
action_responses.each {|response| instance_exec(responder, &response) }
end
end
end | ruby | def respond_to_action_responses
if !respond_to_performed? && action_responses.any?
respond_to do |responder|
action_responses.each {|response| instance_exec(responder, &response) }
end
end
end | [
"def",
"respond_to_action_responses",
"if",
"!",
"respond_to_performed?",
"&&",
"action_responses",
".",
"any?",
"respond_to",
"do",
"|",
"responder",
"|",
"action_responses",
".",
"each",
"{",
"|",
"response",
"|",
"instance_exec",
"(",
"responder",
",",
"response",
")",
"}",
"end",
"end",
"end"
] | if the response.content_type has not been set (if it has, then responthere are responses for the current action, then respond_to them
we rescue the case where there were no responses, so that the default_render
action will be performed | [
"if",
"the",
"response",
".",
"content_type",
"has",
"not",
"been",
"set",
"(",
"if",
"it",
"has",
"then",
"responthere",
"are",
"responses",
"for",
"the",
"current",
"action",
"then",
"respond_to",
"them"
] | 76c8b451868c4ddc48fa51410a391e614192a6a9 | https://github.com/ianwhite/response_for/blob/76c8b451868c4ddc48fa51410a391e614192a6a9/lib/response_for/action_controller.rb#L135-L141 | train |
sue445/sengiri_yaml | lib/sengiri_yaml/loader.rb | SengiriYaml.Loader.load_dir | def load_dir(src_dir)
merged_content = ""
Pathname.glob("#{src_dir}/*.yml").sort.each do |yaml_path|
content = yaml_path.read.gsub(/^---$/, "")
merged_content << content
end
YAML.load(merged_content)
end | ruby | def load_dir(src_dir)
merged_content = ""
Pathname.glob("#{src_dir}/*.yml").sort.each do |yaml_path|
content = yaml_path.read.gsub(/^---$/, "")
merged_content << content
end
YAML.load(merged_content)
end | [
"def",
"load_dir",
"(",
"src_dir",
")",
"merged_content",
"=",
"\"\"",
"Pathname",
".",
"glob",
"(",
"\"#{src_dir}/*.yml\"",
")",
".",
"sort",
".",
"each",
"do",
"|",
"yaml_path",
"|",
"content",
"=",
"yaml_path",
".",
"read",
".",
"gsub",
"(",
"/",
"/",
",",
"\"\"",
")",
"merged_content",
"<<",
"content",
"end",
"YAML",
".",
"load",
"(",
"merged_content",
")",
"end"
] | load divided yaml files
@param src_dir [String] divided yaml dir
@return [Hash] merged yaml hash | [
"load",
"divided",
"yaml",
"files"
] | f9595c5c05802bbbdd5228e808e7cb2b9cc3a049 | https://github.com/sue445/sengiri_yaml/blob/f9595c5c05802bbbdd5228e808e7cb2b9cc3a049/lib/sengiri_yaml/loader.rb#L9-L18 | train |
samlown/translate_columns | lib/translate_columns.rb | TranslateColumns.InstanceMethods.translation_locale | def translation_locale
locale = @translation_locale || I18n.locale.to_s
locale == I18n.default_locale.to_s ? nil : locale
end | ruby | def translation_locale
locale = @translation_locale || I18n.locale.to_s
locale == I18n.default_locale.to_s ? nil : locale
end | [
"def",
"translation_locale",
"locale",
"=",
"@translation_locale",
"||",
"I18n",
".",
"locale",
".",
"to_s",
"locale",
"==",
"I18n",
".",
"default_locale",
".",
"to_s",
"?",
"nil",
":",
"locale",
"end"
] | Provide the locale which is currently in use with the object or the current global locale.
If the default is in use, always return nil. | [
"Provide",
"the",
"locale",
"which",
"is",
"currently",
"in",
"use",
"with",
"the",
"object",
"or",
"the",
"current",
"global",
"locale",
".",
"If",
"the",
"default",
"is",
"in",
"use",
"always",
"return",
"nil",
"."
] | 799d7cd4a0c3ad8d2dd1512be0129daef3643cac | https://github.com/samlown/translate_columns/blob/799d7cd4a0c3ad8d2dd1512be0129daef3643cac/lib/translate_columns.rb#L130-L133 | train |
samlown/translate_columns | lib/translate_columns.rb | TranslateColumns.InstanceMethods.translation | def translation
if translation_enabled?
if !@translation || (@translation.locale != translation_locale)
raise MissingParent, "Cannot create translations without a stored parent" if new_record?
# try to find translation or build a new one
@translation = translations.where(:locale => translation_locale).first || translations.build(:locale => translation_locale)
end
@translation
else
nil
end
end | ruby | def translation
if translation_enabled?
if !@translation || (@translation.locale != translation_locale)
raise MissingParent, "Cannot create translations without a stored parent" if new_record?
# try to find translation or build a new one
@translation = translations.where(:locale => translation_locale).first || translations.build(:locale => translation_locale)
end
@translation
else
nil
end
end | [
"def",
"translation",
"if",
"translation_enabled?",
"if",
"!",
"@translation",
"||",
"(",
"@translation",
".",
"locale",
"!=",
"translation_locale",
")",
"raise",
"MissingParent",
",",
"\"Cannot create translations without a stored parent\"",
"if",
"new_record?",
"# try to find translation or build a new one",
"@translation",
"=",
"translations",
".",
"where",
"(",
":locale",
"=>",
"translation_locale",
")",
".",
"first",
"||",
"translations",
".",
"build",
"(",
":locale",
"=>",
"translation_locale",
")",
"end",
"@translation",
"else",
"nil",
"end",
"end"
] | Provide a translation object based on the parent and the translation_locale
current value. | [
"Provide",
"a",
"translation",
"object",
"based",
"on",
"the",
"parent",
"and",
"the",
"translation_locale",
"current",
"value",
"."
] | 799d7cd4a0c3ad8d2dd1512be0129daef3643cac | https://github.com/samlown/translate_columns/blob/799d7cd4a0c3ad8d2dd1512be0129daef3643cac/lib/translate_columns.rb#L165-L176 | train |
samlown/translate_columns | lib/translate_columns.rb | TranslateColumns.InstanceMethods.attributes_with_locale= | def attributes_with_locale=(new_attributes, guard_protected_attributes = true)
return if new_attributes.nil?
attributes = new_attributes.dup
attributes.stringify_keys!
attributes = sanitize_for_mass_assignment(attributes) if guard_protected_attributes
send(:locale=, attributes["locale"]) if attributes.has_key?("locale") and respond_to?(:locale=)
send(:attributes_without_locale=, attributes, guard_protected_attributes)
end | ruby | def attributes_with_locale=(new_attributes, guard_protected_attributes = true)
return if new_attributes.nil?
attributes = new_attributes.dup
attributes.stringify_keys!
attributes = sanitize_for_mass_assignment(attributes) if guard_protected_attributes
send(:locale=, attributes["locale"]) if attributes.has_key?("locale") and respond_to?(:locale=)
send(:attributes_without_locale=, attributes, guard_protected_attributes)
end | [
"def",
"attributes_with_locale",
"=",
"(",
"new_attributes",
",",
"guard_protected_attributes",
"=",
"true",
")",
"return",
"if",
"new_attributes",
".",
"nil?",
"attributes",
"=",
"new_attributes",
".",
"dup",
"attributes",
".",
"stringify_keys!",
"attributes",
"=",
"sanitize_for_mass_assignment",
"(",
"attributes",
")",
"if",
"guard_protected_attributes",
"send",
"(",
":locale=",
",",
"attributes",
"[",
"\"locale\"",
"]",
")",
"if",
"attributes",
".",
"has_key?",
"(",
"\"locale\"",
")",
"and",
"respond_to?",
"(",
":locale=",
")",
"send",
"(",
":attributes_without_locale=",
",",
"attributes",
",",
"guard_protected_attributes",
")",
"end"
] | Override the default mass assignment method so that the locale variable is always
given preference. | [
"Override",
"the",
"default",
"mass",
"assignment",
"method",
"so",
"that",
"the",
"locale",
"variable",
"is",
"always",
"given",
"preference",
"."
] | 799d7cd4a0c3ad8d2dd1512be0129daef3643cac | https://github.com/samlown/translate_columns/blob/799d7cd4a0c3ad8d2dd1512be0129daef3643cac/lib/translate_columns.rb#L216-L225 | train |
mkristian/ixtlan-datamapper | lib/ixtlan/datamapper/validations_ext.rb | DataMapper.ValidationsExt.validate_parents | def validate_parents
parent_relationships.each do |relationship|
parent = relationship.get(self)
unless parent.valid?
unless errors[relationship.name].include?(parent.errors)
errors[relationship.name] = parent.errors
end
end
end
end | ruby | def validate_parents
parent_relationships.each do |relationship|
parent = relationship.get(self)
unless parent.valid?
unless errors[relationship.name].include?(parent.errors)
errors[relationship.name] = parent.errors
end
end
end
end | [
"def",
"validate_parents",
"parent_relationships",
".",
"each",
"do",
"|",
"relationship",
"|",
"parent",
"=",
"relationship",
".",
"get",
"(",
"self",
")",
"unless",
"parent",
".",
"valid?",
"unless",
"errors",
"[",
"relationship",
".",
"name",
"]",
".",
"include?",
"(",
"parent",
".",
"errors",
")",
"errors",
"[",
"relationship",
".",
"name",
"]",
"=",
"parent",
".",
"errors",
"end",
"end",
"end",
"end"
] | Run validations on the associated parent resources
@api semipublic | [
"Run",
"validations",
"on",
"the",
"associated",
"parent",
"resources"
] | f7b39d4bbfea3d3c45dd697fc566b2d79c73f34e | https://github.com/mkristian/ixtlan-datamapper/blob/f7b39d4bbfea3d3c45dd697fc566b2d79c73f34e/lib/ixtlan/datamapper/validations_ext.rb#L30-L39 | train |
mkristian/ixtlan-datamapper | lib/ixtlan/datamapper/validations_ext.rb | DataMapper.ValidationsExt.validate_children | def validate_children
child_associations.each do |collection|
if collection.dirty?
collection.each do |child|
unless child.valid?
relationship_errors = (errors[collection.relationship.name] ||= [])
unless relationship_errors.include?(child.errors)
relationship_errors << child.errors
end
end
end
end
end
end | ruby | def validate_children
child_associations.each do |collection|
if collection.dirty?
collection.each do |child|
unless child.valid?
relationship_errors = (errors[collection.relationship.name] ||= [])
unless relationship_errors.include?(child.errors)
relationship_errors << child.errors
end
end
end
end
end
end | [
"def",
"validate_children",
"child_associations",
".",
"each",
"do",
"|",
"collection",
"|",
"if",
"collection",
".",
"dirty?",
"collection",
".",
"each",
"do",
"|",
"child",
"|",
"unless",
"child",
".",
"valid?",
"relationship_errors",
"=",
"(",
"errors",
"[",
"collection",
".",
"relationship",
".",
"name",
"]",
"||=",
"[",
"]",
")",
"unless",
"relationship_errors",
".",
"include?",
"(",
"child",
".",
"errors",
")",
"relationship_errors",
"<<",
"child",
".",
"errors",
"end",
"end",
"end",
"end",
"end",
"end"
] | Run validations on the associated child resources
@api semipublic | [
"Run",
"validations",
"on",
"the",
"associated",
"child",
"resources"
] | f7b39d4bbfea3d3c45dd697fc566b2d79c73f34e | https://github.com/mkristian/ixtlan-datamapper/blob/f7b39d4bbfea3d3c45dd697fc566b2d79c73f34e/lib/ixtlan/datamapper/validations_ext.rb#L44-L57 | train |
dyoung522/nosequel | lib/nosequel/container.rb | NoSequel.Container.method_missing | def method_missing(meth, *args, &block)
db.to_hash(:key, :value).send(meth, *args, &block)
end | ruby | def method_missing(meth, *args, &block)
db.to_hash(:key, :value).send(meth, *args, &block)
end | [
"def",
"method_missing",
"(",
"meth",
",",
"*",
"args",
",",
"&",
"block",
")",
"db",
".",
"to_hash",
"(",
":key",
",",
":value",
")",
".",
"send",
"(",
"meth",
",",
"args",
",",
"block",
")",
"end"
] | Handle all other Hash methods | [
"Handle",
"all",
"other",
"Hash",
"methods"
] | b8788846a36ce03d426bfe3e575a81a6fb3c5c76 | https://github.com/dyoung522/nosequel/blob/b8788846a36ce03d426bfe3e575a81a6fb3c5c76/lib/nosequel/container.rb#L68-L70 | train |
dyoung522/nosequel | lib/nosequel/container.rb | NoSequel.Container.validate_key | def validate_key(key)
unless key.is_a?(Symbol) || key.is_a?(String)
raise ArgumentError, 'Key must be a string or symbol'
end
key
end | ruby | def validate_key(key)
unless key.is_a?(Symbol) || key.is_a?(String)
raise ArgumentError, 'Key must be a string or symbol'
end
key
end | [
"def",
"validate_key",
"(",
"key",
")",
"unless",
"key",
".",
"is_a?",
"(",
"Symbol",
")",
"||",
"key",
".",
"is_a?",
"(",
"String",
")",
"raise",
"ArgumentError",
",",
"'Key must be a string or symbol'",
"end",
"key",
"end"
] | Make sure the key is valid | [
"Make",
"sure",
"the",
"key",
"is",
"valid"
] | b8788846a36ce03d426bfe3e575a81a6fb3c5c76 | https://github.com/dyoung522/nosequel/blob/b8788846a36ce03d426bfe3e575a81a6fb3c5c76/lib/nosequel/container.rb#L88-L93 | train |
boza/interaction | lib/simple_interaction/class_methods.rb | SimpleInteraction.ClassMethods.run | def run(**options)
@options = options
fail RequirementsNotMet.new("#{self} requires the following parameters #{requirements}") unless requirements_met?
new(@options).tap do |interaction|
interaction.__send__(:run)
end
end | ruby | def run(**options)
@options = options
fail RequirementsNotMet.new("#{self} requires the following parameters #{requirements}") unless requirements_met?
new(@options).tap do |interaction|
interaction.__send__(:run)
end
end | [
"def",
"run",
"(",
"**",
"options",
")",
"@options",
"=",
"options",
"fail",
"RequirementsNotMet",
".",
"new",
"(",
"\"#{self} requires the following parameters #{requirements}\"",
")",
"unless",
"requirements_met?",
"new",
"(",
"@options",
")",
".",
"tap",
"do",
"|",
"interaction",
"|",
"interaction",
".",
"__send__",
"(",
":run",
")",
"end",
"end"
] | checks if requirements are met from the requires params
creates an instance of the interaction
calls run on the instance | [
"checks",
"if",
"requirements",
"are",
"met",
"from",
"the",
"requires",
"params",
"creates",
"an",
"instance",
"of",
"the",
"interaction",
"calls",
"run",
"on",
"the",
"instance"
] | e2afc7d127795a957e76da05ed053b4a38a78070 | https://github.com/boza/interaction/blob/e2afc7d127795a957e76da05ed053b4a38a78070/lib/simple_interaction/class_methods.rb#L29-L35 | train |
boza/interaction | lib/simple_interaction/class_methods.rb | SimpleInteraction.ClassMethods.run! | def run!(**options)
interaction = run(options)
raise error_class.new(interaction.error) unless interaction.success?
interaction.result
end | ruby | def run!(**options)
interaction = run(options)
raise error_class.new(interaction.error) unless interaction.success?
interaction.result
end | [
"def",
"run!",
"(",
"**",
"options",
")",
"interaction",
"=",
"run",
"(",
"options",
")",
"raise",
"error_class",
".",
"new",
"(",
"interaction",
".",
"error",
")",
"unless",
"interaction",
".",
"success?",
"interaction",
".",
"result",
"end"
] | runs interaction raises if any error or returns the interaction result | [
"runs",
"interaction",
"raises",
"if",
"any",
"error",
"or",
"returns",
"the",
"interaction",
"result"
] | e2afc7d127795a957e76da05ed053b4a38a78070 | https://github.com/boza/interaction/blob/e2afc7d127795a957e76da05ed053b4a38a78070/lib/simple_interaction/class_methods.rb#L38-L42 | train |
lokalportal/chain_options | lib/chain_options/option_set.rb | ChainOptions.OptionSet.add_option | def add_option(name, parameters)
self.class.handle_warnings(name, **parameters.dup)
chain_options.merge(name => parameters.merge(method_hash(parameters)))
end | ruby | def add_option(name, parameters)
self.class.handle_warnings(name, **parameters.dup)
chain_options.merge(name => parameters.merge(method_hash(parameters)))
end | [
"def",
"add_option",
"(",
"name",
",",
"parameters",
")",
"self",
".",
"class",
".",
"handle_warnings",
"(",
"name",
",",
"**",
"parameters",
".",
"dup",
")",
"chain_options",
".",
"merge",
"(",
"name",
"=>",
"parameters",
".",
"merge",
"(",
"method_hash",
"(",
"parameters",
")",
")",
")",
"end"
] | Checks the given option-parameters for incompatibilities and registers a
new option. | [
"Checks",
"the",
"given",
"option",
"-",
"parameters",
"for",
"incompatibilities",
"and",
"registers",
"a",
"new",
"option",
"."
] | b42cd6c03aeca8938b274225ebaa38fe3803866a | https://github.com/lokalportal/chain_options/blob/b42cd6c03aeca8938b274225ebaa38fe3803866a/lib/chain_options/option_set.rb#L49-L52 | train |
lokalportal/chain_options | lib/chain_options/option_set.rb | ChainOptions.OptionSet.option | def option(name)
config = chain_options[name] || raise_no_option_error(name)
Option.new(config).tap { |o| o.initial_value(values[name]) if values.key?(name) }
end | ruby | def option(name)
config = chain_options[name] || raise_no_option_error(name)
Option.new(config).tap { |o| o.initial_value(values[name]) if values.key?(name) }
end | [
"def",
"option",
"(",
"name",
")",
"config",
"=",
"chain_options",
"[",
"name",
"]",
"||",
"raise_no_option_error",
"(",
"name",
")",
"Option",
".",
"new",
"(",
"config",
")",
".",
"tap",
"{",
"|",
"o",
"|",
"o",
".",
"initial_value",
"(",
"values",
"[",
"name",
"]",
")",
"if",
"values",
".",
"key?",
"(",
"name",
")",
"}",
"end"
] | Returns an option registered under `name`. | [
"Returns",
"an",
"option",
"registered",
"under",
"name",
"."
] | b42cd6c03aeca8938b274225ebaa38fe3803866a | https://github.com/lokalportal/chain_options/blob/b42cd6c03aeca8938b274225ebaa38fe3803866a/lib/chain_options/option_set.rb#L64-L67 | train |
jhliberty/brat-cli | lib/brat/request.rb | Brat.Request.set_request_defaults | def set_request_defaults(endpoint, private_token, sudo=nil)
raise Error::MissingCredentials.new("Please set an endpoint to API") unless endpoint
@private_token = private_token
self.class.base_uri endpoint
self.class.default_params :sudo => sudo
self.class.default_params.delete(:sudo) if sudo.nil?
end | ruby | def set_request_defaults(endpoint, private_token, sudo=nil)
raise Error::MissingCredentials.new("Please set an endpoint to API") unless endpoint
@private_token = private_token
self.class.base_uri endpoint
self.class.default_params :sudo => sudo
self.class.default_params.delete(:sudo) if sudo.nil?
end | [
"def",
"set_request_defaults",
"(",
"endpoint",
",",
"private_token",
",",
"sudo",
"=",
"nil",
")",
"raise",
"Error",
"::",
"MissingCredentials",
".",
"new",
"(",
"\"Please set an endpoint to API\"",
")",
"unless",
"endpoint",
"@private_token",
"=",
"private_token",
"self",
".",
"class",
".",
"base_uri",
"endpoint",
"self",
".",
"class",
".",
"default_params",
":sudo",
"=>",
"sudo",
"self",
".",
"class",
".",
"default_params",
".",
"delete",
"(",
":sudo",
")",
"if",
"sudo",
".",
"nil?",
"end"
] | Sets a base_uri and default_params for requests.
@raise [Error::MissingCredentials] if endpoint not set. | [
"Sets",
"a",
"base_uri",
"and",
"default_params",
"for",
"requests",
"."
] | 36183e543fd0e11b1840da2db4f41aa425404b8d | https://github.com/jhliberty/brat-cli/blob/36183e543fd0e11b1840da2db4f41aa425404b8d/lib/brat/request.rb#L76-L83 | train |
J3RN/spellrb | lib/spell/spell.rb | Spell.Spell.best_match | def best_match(given_word)
words = (@word_list.is_a? Array) ? @word_list : @word_list.keys
word_bigrams = bigramate(given_word)
word_hash = words.map do |key|
[key, bigram_compare(word_bigrams, bigramate(key))]
end
word_hash = Hash[word_hash]
# Weight by word usage, if logical
word_hash = apply_usage_weights(word_hash) if @word_list.is_a? Hash
word_hash.max_by { |_key, value| value }.first
end | ruby | def best_match(given_word)
words = (@word_list.is_a? Array) ? @word_list : @word_list.keys
word_bigrams = bigramate(given_word)
word_hash = words.map do |key|
[key, bigram_compare(word_bigrams, bigramate(key))]
end
word_hash = Hash[word_hash]
# Weight by word usage, if logical
word_hash = apply_usage_weights(word_hash) if @word_list.is_a? Hash
word_hash.max_by { |_key, value| value }.first
end | [
"def",
"best_match",
"(",
"given_word",
")",
"words",
"=",
"(",
"@word_list",
".",
"is_a?",
"Array",
")",
"?",
"@word_list",
":",
"@word_list",
".",
"keys",
"word_bigrams",
"=",
"bigramate",
"(",
"given_word",
")",
"word_hash",
"=",
"words",
".",
"map",
"do",
"|",
"key",
"|",
"[",
"key",
",",
"bigram_compare",
"(",
"word_bigrams",
",",
"bigramate",
"(",
"key",
")",
")",
"]",
"end",
"word_hash",
"=",
"Hash",
"[",
"word_hash",
"]",
"# Weight by word usage, if logical",
"word_hash",
"=",
"apply_usage_weights",
"(",
"word_hash",
")",
"if",
"@word_list",
".",
"is_a?",
"Hash",
"word_hash",
".",
"max_by",
"{",
"|",
"_key",
",",
"value",
"|",
"value",
"}",
".",
"first",
"end"
] | Returns the closest matching word in the dictionary | [
"Returns",
"the",
"closest",
"matching",
"word",
"in",
"the",
"dictionary"
] | 0c9a187489428c4b441d2555c05d87ef3af0df8e | https://github.com/J3RN/spellrb/blob/0c9a187489428c4b441d2555c05d87ef3af0df8e/lib/spell/spell.rb#L18-L31 | train |
J3RN/spellrb | lib/spell/spell.rb | Spell.Spell.num_matching | def num_matching(one_bigrams, two_bigrams, acc = 0)
return acc if one_bigrams.empty? || two_bigrams.empty?
one_two = one_bigrams.index(two_bigrams[0])
two_one = two_bigrams.index(one_bigrams[0])
if one_two.nil? && two_one.nil?
num_matching(one_bigrams.drop(1), two_bigrams.drop(1), acc)
else
# If one is nil, it is set to the other
two_one ||= one_two
one_two ||= two_one
if one_two < two_one
num_matching(one_bigrams.drop(one_two + 1),
two_bigrams.drop(1), acc + 1)
else
num_matching(one_bigrams.drop(1),
two_bigrams.drop(two_one + 1), acc + 1)
end
end
end | ruby | def num_matching(one_bigrams, two_bigrams, acc = 0)
return acc if one_bigrams.empty? || two_bigrams.empty?
one_two = one_bigrams.index(two_bigrams[0])
two_one = two_bigrams.index(one_bigrams[0])
if one_two.nil? && two_one.nil?
num_matching(one_bigrams.drop(1), two_bigrams.drop(1), acc)
else
# If one is nil, it is set to the other
two_one ||= one_two
one_two ||= two_one
if one_two < two_one
num_matching(one_bigrams.drop(one_two + 1),
two_bigrams.drop(1), acc + 1)
else
num_matching(one_bigrams.drop(1),
two_bigrams.drop(two_one + 1), acc + 1)
end
end
end | [
"def",
"num_matching",
"(",
"one_bigrams",
",",
"two_bigrams",
",",
"acc",
"=",
"0",
")",
"return",
"acc",
"if",
"one_bigrams",
".",
"empty?",
"||",
"two_bigrams",
".",
"empty?",
"one_two",
"=",
"one_bigrams",
".",
"index",
"(",
"two_bigrams",
"[",
"0",
"]",
")",
"two_one",
"=",
"two_bigrams",
".",
"index",
"(",
"one_bigrams",
"[",
"0",
"]",
")",
"if",
"one_two",
".",
"nil?",
"&&",
"two_one",
".",
"nil?",
"num_matching",
"(",
"one_bigrams",
".",
"drop",
"(",
"1",
")",
",",
"two_bigrams",
".",
"drop",
"(",
"1",
")",
",",
"acc",
")",
"else",
"# If one is nil, it is set to the other",
"two_one",
"||=",
"one_two",
"one_two",
"||=",
"two_one",
"if",
"one_two",
"<",
"two_one",
"num_matching",
"(",
"one_bigrams",
".",
"drop",
"(",
"one_two",
"+",
"1",
")",
",",
"two_bigrams",
".",
"drop",
"(",
"1",
")",
",",
"acc",
"+",
"1",
")",
"else",
"num_matching",
"(",
"one_bigrams",
".",
"drop",
"(",
"1",
")",
",",
"two_bigrams",
".",
"drop",
"(",
"two_one",
"+",
"1",
")",
",",
"acc",
"+",
"1",
")",
"end",
"end",
"end"
] | Returns the number of matching bigrams between the two sets of bigrams | [
"Returns",
"the",
"number",
"of",
"matching",
"bigrams",
"between",
"the",
"two",
"sets",
"of",
"bigrams"
] | 0c9a187489428c4b441d2555c05d87ef3af0df8e | https://github.com/J3RN/spellrb/blob/0c9a187489428c4b441d2555c05d87ef3af0df8e/lib/spell/spell.rb#L50-L71 | train |
J3RN/spellrb | lib/spell/spell.rb | Spell.Spell.bigram_compare | def bigram_compare(word1_bigrams, word2_bigrams)
most_bigrams = [word1_bigrams.count, word2_bigrams.count].max
num_matching(word1_bigrams, word2_bigrams).to_f / most_bigrams
end | ruby | def bigram_compare(word1_bigrams, word2_bigrams)
most_bigrams = [word1_bigrams.count, word2_bigrams.count].max
num_matching(word1_bigrams, word2_bigrams).to_f / most_bigrams
end | [
"def",
"bigram_compare",
"(",
"word1_bigrams",
",",
"word2_bigrams",
")",
"most_bigrams",
"=",
"[",
"word1_bigrams",
".",
"count",
",",
"word2_bigrams",
".",
"count",
"]",
".",
"max",
"num_matching",
"(",
"word1_bigrams",
",",
"word2_bigrams",
")",
".",
"to_f",
"/",
"most_bigrams",
"end"
] | Returns a value from 0 to 1 for how likely these two words are to be a
match | [
"Returns",
"a",
"value",
"from",
"0",
"to",
"1",
"for",
"how",
"likely",
"these",
"two",
"words",
"are",
"to",
"be",
"a",
"match"
] | 0c9a187489428c4b441d2555c05d87ef3af0df8e | https://github.com/J3RN/spellrb/blob/0c9a187489428c4b441d2555c05d87ef3af0df8e/lib/spell/spell.rb#L80-L83 | train |
J3RN/spellrb | lib/spell/spell.rb | Spell.Spell.apply_usage_weights | def apply_usage_weights(word_hash)
max_usage = @word_list.values.max.to_f
max_usage = 1 if max_usage == 0
weighted_array = word_hash.map do |word, bigram_score|
usage_score = @word_list[word].to_f / max_usage
[word, (bigram_score * (1 - @alpha)) + (usage_score * @alpha)]
end
Hash[weighted_array]
end | ruby | def apply_usage_weights(word_hash)
max_usage = @word_list.values.max.to_f
max_usage = 1 if max_usage == 0
weighted_array = word_hash.map do |word, bigram_score|
usage_score = @word_list[word].to_f / max_usage
[word, (bigram_score * (1 - @alpha)) + (usage_score * @alpha)]
end
Hash[weighted_array]
end | [
"def",
"apply_usage_weights",
"(",
"word_hash",
")",
"max_usage",
"=",
"@word_list",
".",
"values",
".",
"max",
".",
"to_f",
"max_usage",
"=",
"1",
"if",
"max_usage",
"==",
"0",
"weighted_array",
"=",
"word_hash",
".",
"map",
"do",
"|",
"word",
",",
"bigram_score",
"|",
"usage_score",
"=",
"@word_list",
"[",
"word",
"]",
".",
"to_f",
"/",
"max_usage",
"[",
"word",
",",
"(",
"bigram_score",
"*",
"(",
"1",
"-",
"@alpha",
")",
")",
"+",
"(",
"usage_score",
"*",
"@alpha",
")",
"]",
"end",
"Hash",
"[",
"weighted_array",
"]",
"end"
] | For each word, adjust it's score by usage
v = s * (1 - a) + u * a
Where v is the new value
a is @alpha
s is the bigram score (0..1)
u is the usage score (0..1) | [
"For",
"each",
"word",
"adjust",
"it",
"s",
"score",
"by",
"usage"
] | 0c9a187489428c4b441d2555c05d87ef3af0df8e | https://github.com/J3RN/spellrb/blob/0c9a187489428c4b441d2555c05d87ef3af0df8e/lib/spell/spell.rb#L92-L102 | train |
NUBIC/aker | lib/aker/rack/failure.rb | Aker::Rack.Failure.call | def call(env)
conf = configuration(env)
if login_required?(env)
if interactive?(env)
::Warden::Strategies[conf.ui_mode].new(env).on_ui_failure.finish
else
headers = {}
headers["WWW-Authenticate"] =
conf.api_modes.collect { |mode_key|
::Warden::Strategies[mode_key].new(env).challenge
}.join("\n")
headers["Content-Type"] = "text/plain"
[401, headers, ["Authentication required"]]
end
else
log_authorization_failure(env)
msg = "#{user(env).username} may not use this page."
Rack::Response.
new("<html><head><title>Authorization denied</title></head><body>#{msg}</body></html>",
403,
"Content-Type" => "text/html").finish
end
end | ruby | def call(env)
conf = configuration(env)
if login_required?(env)
if interactive?(env)
::Warden::Strategies[conf.ui_mode].new(env).on_ui_failure.finish
else
headers = {}
headers["WWW-Authenticate"] =
conf.api_modes.collect { |mode_key|
::Warden::Strategies[mode_key].new(env).challenge
}.join("\n")
headers["Content-Type"] = "text/plain"
[401, headers, ["Authentication required"]]
end
else
log_authorization_failure(env)
msg = "#{user(env).username} may not use this page."
Rack::Response.
new("<html><head><title>Authorization denied</title></head><body>#{msg}</body></html>",
403,
"Content-Type" => "text/html").finish
end
end | [
"def",
"call",
"(",
"env",
")",
"conf",
"=",
"configuration",
"(",
"env",
")",
"if",
"login_required?",
"(",
"env",
")",
"if",
"interactive?",
"(",
"env",
")",
"::",
"Warden",
"::",
"Strategies",
"[",
"conf",
".",
"ui_mode",
"]",
".",
"new",
"(",
"env",
")",
".",
"on_ui_failure",
".",
"finish",
"else",
"headers",
"=",
"{",
"}",
"headers",
"[",
"\"WWW-Authenticate\"",
"]",
"=",
"conf",
".",
"api_modes",
".",
"collect",
"{",
"|",
"mode_key",
"|",
"::",
"Warden",
"::",
"Strategies",
"[",
"mode_key",
"]",
".",
"new",
"(",
"env",
")",
".",
"challenge",
"}",
".",
"join",
"(",
"\"\\n\"",
")",
"headers",
"[",
"\"Content-Type\"",
"]",
"=",
"\"text/plain\"",
"[",
"401",
",",
"headers",
",",
"[",
"\"Authentication required\"",
"]",
"]",
"end",
"else",
"log_authorization_failure",
"(",
"env",
")",
"msg",
"=",
"\"#{user(env).username} may not use this page.\"",
"Rack",
"::",
"Response",
".",
"new",
"(",
"\"<html><head><title>Authorization denied</title></head><body>#{msg}</body></html>\"",
",",
"403",
",",
"\"Content-Type\"",
"=>",
"\"text/html\"",
")",
".",
"finish",
"end",
"end"
] | Receives the rack environment in case of a failure and renders a
response based on the interactiveness of the request and the
nature of the configured modes.
@param [Hash] env a rack environment
@return [Array] a rack response | [
"Receives",
"the",
"rack",
"environment",
"in",
"case",
"of",
"a",
"failure",
"and",
"renders",
"a",
"response",
"based",
"on",
"the",
"interactiveness",
"of",
"the",
"request",
"and",
"the",
"nature",
"of",
"the",
"configured",
"modes",
"."
] | ff43606a8812e38f96bbe71b46e7f631cbeacf1c | https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/rack/failure.rb#L22-L44 | train |
mwatts15/xmms2_utils | lib/xmms2_utils.rb | Xmms.Client.shuffle_by | def shuffle_by(playlist, field)
pl = playlist.entries.wait.value
artists = Hash.new
rnd = Random.new
playlist.clear.wait
field = field.to_sym
pl.each do |id|
infos = self.medialib_get_info(id).wait.value
a = infos[field].first[1]
if artists.has_key?(a)
artists[a].insert(0,id)
else
artists[a] = [id]
end
end
artist_names = artists.keys
for _ in pl
artist_idx = (rnd.rand * artist_names.length).to_i
artist = artist_names[artist_idx]
songs = artists[artist]
song_idx = rnd.rand * songs.length
song = songs[song_idx]
playlist.add_entry(song).wait
songs.delete(song)
if songs.empty?
artists.delete(artist)
artist_names.delete(artist)
end
end
end | ruby | def shuffle_by(playlist, field)
pl = playlist.entries.wait.value
artists = Hash.new
rnd = Random.new
playlist.clear.wait
field = field.to_sym
pl.each do |id|
infos = self.medialib_get_info(id).wait.value
a = infos[field].first[1]
if artists.has_key?(a)
artists[a].insert(0,id)
else
artists[a] = [id]
end
end
artist_names = artists.keys
for _ in pl
artist_idx = (rnd.rand * artist_names.length).to_i
artist = artist_names[artist_idx]
songs = artists[artist]
song_idx = rnd.rand * songs.length
song = songs[song_idx]
playlist.add_entry(song).wait
songs.delete(song)
if songs.empty?
artists.delete(artist)
artist_names.delete(artist)
end
end
end | [
"def",
"shuffle_by",
"(",
"playlist",
",",
"field",
")",
"pl",
"=",
"playlist",
".",
"entries",
".",
"wait",
".",
"value",
"artists",
"=",
"Hash",
".",
"new",
"rnd",
"=",
"Random",
".",
"new",
"playlist",
".",
"clear",
".",
"wait",
"field",
"=",
"field",
".",
"to_sym",
"pl",
".",
"each",
"do",
"|",
"id",
"|",
"infos",
"=",
"self",
".",
"medialib_get_info",
"(",
"id",
")",
".",
"wait",
".",
"value",
"a",
"=",
"infos",
"[",
"field",
"]",
".",
"first",
"[",
"1",
"]",
"if",
"artists",
".",
"has_key?",
"(",
"a",
")",
"artists",
"[",
"a",
"]",
".",
"insert",
"(",
"0",
",",
"id",
")",
"else",
"artists",
"[",
"a",
"]",
"=",
"[",
"id",
"]",
"end",
"end",
"artist_names",
"=",
"artists",
".",
"keys",
"for",
"_",
"in",
"pl",
"artist_idx",
"=",
"(",
"rnd",
".",
"rand",
"*",
"artist_names",
".",
"length",
")",
".",
"to_i",
"artist",
"=",
"artist_names",
"[",
"artist_idx",
"]",
"songs",
"=",
"artists",
"[",
"artist",
"]",
"song_idx",
"=",
"rnd",
".",
"rand",
"*",
"songs",
".",
"length",
"song",
"=",
"songs",
"[",
"song_idx",
"]",
"playlist",
".",
"add_entry",
"(",
"song",
")",
".",
"wait",
"songs",
".",
"delete",
"(",
"song",
")",
"if",
"songs",
".",
"empty?",
"artists",
".",
"delete",
"(",
"artist",
")",
"artist_names",
".",
"delete",
"(",
"artist",
")",
"end",
"end",
"end"
] | Shuffles the playlist by selecting randomly among the tracks as
grouped by the given field
shuffle_by is intended to change between different
artists/albums/genres more frequently than if all tracks were
shuffled based on a uniform distribution. In particular, it works
well at preventing one very large group of songs (like A. R.
Rahman's full discography) from dominating your playlist, but
leaves many such entries at the end of the playlist. | [
"Shuffles",
"the",
"playlist",
"by",
"selecting",
"randomly",
"among",
"the",
"tracks",
"as",
"grouped",
"by",
"the",
"given",
"field"
] | f549ab65c50a2bce7922c8c75621fb218885e460 | https://github.com/mwatts15/xmms2_utils/blob/f549ab65c50a2bce7922c8c75621fb218885e460/lib/xmms2_utils.rb#L77-L107 | train |
mwatts15/xmms2_utils | lib/xmms2_utils.rb | Xmms.Client.extract_medialib_info | def extract_medialib_info(id, *fields)
infos = self.medialib_get_info(id).wait.value
res = Hash.new
if !infos.nil?
fields = fields.map! {|f| f.to_sym }
fields.each do |field|
values = infos[field]
if not values.nil?
my_value = values.first[1] # actual value from the top source [0]
if field == :url
my_value = Xmms::decode_xmms2_url(my_value)
end
res[field] = my_value.to_s.force_encoding("utf-8")
end
end
end
res
end | ruby | def extract_medialib_info(id, *fields)
infos = self.medialib_get_info(id).wait.value
res = Hash.new
if !infos.nil?
fields = fields.map! {|f| f.to_sym }
fields.each do |field|
values = infos[field]
if not values.nil?
my_value = values.first[1] # actual value from the top source [0]
if field == :url
my_value = Xmms::decode_xmms2_url(my_value)
end
res[field] = my_value.to_s.force_encoding("utf-8")
end
end
end
res
end | [
"def",
"extract_medialib_info",
"(",
"id",
",",
"*",
"fields",
")",
"infos",
"=",
"self",
".",
"medialib_get_info",
"(",
"id",
")",
".",
"wait",
".",
"value",
"res",
"=",
"Hash",
".",
"new",
"if",
"!",
"infos",
".",
"nil?",
"fields",
"=",
"fields",
".",
"map!",
"{",
"|",
"f",
"|",
"f",
".",
"to_sym",
"}",
"fields",
".",
"each",
"do",
"|",
"field",
"|",
"values",
"=",
"infos",
"[",
"field",
"]",
"if",
"not",
"values",
".",
"nil?",
"my_value",
"=",
"values",
".",
"first",
"[",
"1",
"]",
"# actual value from the top source [0]",
"if",
"field",
"==",
":url",
"my_value",
"=",
"Xmms",
"::",
"decode_xmms2_url",
"(",
"my_value",
")",
"end",
"res",
"[",
"field",
"]",
"=",
"my_value",
".",
"to_s",
".",
"force_encoding",
"(",
"\"utf-8\"",
")",
"end",
"end",
"end",
"res",
"end"
] | returns a hash of the passed in fields
with the first-found values for the fields | [
"returns",
"a",
"hash",
"of",
"the",
"passed",
"in",
"fields",
"with",
"the",
"first",
"-",
"found",
"values",
"for",
"the",
"fields"
] | f549ab65c50a2bce7922c8c75621fb218885e460 | https://github.com/mwatts15/xmms2_utils/blob/f549ab65c50a2bce7922c8c75621fb218885e460/lib/xmms2_utils.rb#L111-L128 | train |
iv-mexx/git-releaselog | lib/git-releaselog/change.rb | Releaselog.Change.check_scope | def check_scope(scope = nil)
# If no scope is requested or the change has no scope include this change unchanged
return self unless scope
change_scope = /^\s*\[\w+\]/.match(@note)
return self unless change_scope
# change_scope is a string of format `[scope]`, need to strip the `[]` to compare the scope
if change_scope[0][1..-2] == scope
# Change has the scope that is requested, strip the whole scope scope from the change note
@note = change_scope.post_match.strip
return self
else
# Change has a different scope than requested
return nil
end
end | ruby | def check_scope(scope = nil)
# If no scope is requested or the change has no scope include this change unchanged
return self unless scope
change_scope = /^\s*\[\w+\]/.match(@note)
return self unless change_scope
# change_scope is a string of format `[scope]`, need to strip the `[]` to compare the scope
if change_scope[0][1..-2] == scope
# Change has the scope that is requested, strip the whole scope scope from the change note
@note = change_scope.post_match.strip
return self
else
# Change has a different scope than requested
return nil
end
end | [
"def",
"check_scope",
"(",
"scope",
"=",
"nil",
")",
"# If no scope is requested or the change has no scope include this change unchanged",
"return",
"self",
"unless",
"scope",
"change_scope",
"=",
"/",
"\\s",
"\\[",
"\\w",
"\\]",
"/",
".",
"match",
"(",
"@note",
")",
"return",
"self",
"unless",
"change_scope",
"# change_scope is a string of format `[scope]`, need to strip the `[]` to compare the scope",
"if",
"change_scope",
"[",
"0",
"]",
"[",
"1",
"..",
"-",
"2",
"]",
"==",
"scope",
"# Change has the scope that is requested, strip the whole scope scope from the change note",
"@note",
"=",
"change_scope",
".",
"post_match",
".",
"strip",
"return",
"self",
"else",
"# Change has a different scope than requested",
"return",
"nil",
"end",
"end"
] | Checks the scope of the `Change` and the change out if the scope does not match. | [
"Checks",
"the",
"scope",
"of",
"the",
"Change",
"and",
"the",
"change",
"out",
"if",
"the",
"scope",
"does",
"not",
"match",
"."
] | 393d5d9b12f9dd808ccb2d13ab0ada12d72d2849 | https://github.com/iv-mexx/git-releaselog/blob/393d5d9b12f9dd808ccb2d13ab0ada12d72d2849/lib/git-releaselog/change.rb#L48-L63 | train |
m-31/vcenter_lib | lib/vcenter_lib/vcenter.rb | VcenterLib.Vcenter.vms | def vms
logger.debug "get all VMs in all datacenters: begin"
result = dcs.inject([]) do |r, dc|
r + serviceContent.viewManager.CreateContainerView(
container: dc.vmFolder,
type: ['VirtualMachine'],
recursive: true
).view
end
logger.debug "get all VMs in all datacenters: end"
result
end | ruby | def vms
logger.debug "get all VMs in all datacenters: begin"
result = dcs.inject([]) do |r, dc|
r + serviceContent.viewManager.CreateContainerView(
container: dc.vmFolder,
type: ['VirtualMachine'],
recursive: true
).view
end
logger.debug "get all VMs in all datacenters: end"
result
end | [
"def",
"vms",
"logger",
".",
"debug",
"\"get all VMs in all datacenters: begin\"",
"result",
"=",
"dcs",
".",
"inject",
"(",
"[",
"]",
")",
"do",
"|",
"r",
",",
"dc",
"|",
"r",
"+",
"serviceContent",
".",
"viewManager",
".",
"CreateContainerView",
"(",
"container",
":",
"dc",
".",
"vmFolder",
",",
"type",
":",
"[",
"'VirtualMachine'",
"]",
",",
"recursive",
":",
"true",
")",
".",
"view",
"end",
"logger",
".",
"debug",
"\"get all VMs in all datacenters: end\"",
"result",
"end"
] | get all vms in all datacenters | [
"get",
"all",
"vms",
"in",
"all",
"datacenters"
] | 28ed325c73a1faaa5347919006d5a63c1bef6588 | https://github.com/m-31/vcenter_lib/blob/28ed325c73a1faaa5347919006d5a63c1bef6588/lib/vcenter_lib/vcenter.rb#L21-L32 | train |
filip-d/7digital | lib/sevendigital/model/artist.rb | Sevendigital.Artist.various? | def various?
joined_names = "#{name} #{appears_as}".downcase
various_variations = ["vario", "v???????????????rio", "v.a", "vaious", "varios" "vaious", "varoius", "variuos", \
"soundtrack", "karaoke", "original cast", "diverse artist"]
various_variations.each{|various_variation| return true if joined_names.include?(various_variation)}
return false
end | ruby | def various?
joined_names = "#{name} #{appears_as}".downcase
various_variations = ["vario", "v???????????????rio", "v.a", "vaious", "varios" "vaious", "varoius", "variuos", \
"soundtrack", "karaoke", "original cast", "diverse artist"]
various_variations.each{|various_variation| return true if joined_names.include?(various_variation)}
return false
end | [
"def",
"various?",
"joined_names",
"=",
"\"#{name} #{appears_as}\"",
".",
"downcase",
"various_variations",
"=",
"[",
"\"vario\"",
",",
"\"v???????????????rio\"",
",",
"\"v.a\"",
",",
"\"vaious\"",
",",
"\"varios\"",
"\"vaious\"",
",",
"\"varoius\"",
",",
"\"variuos\"",
",",
"\"soundtrack\"",
",",
"\"karaoke\"",
",",
"\"original cast\"",
",",
"\"diverse artist\"",
"]",
"various_variations",
".",
"each",
"{",
"|",
"various_variation",
"|",
"return",
"true",
"if",
"joined_names",
".",
"include?",
"(",
"various_variation",
")",
"}",
"return",
"false",
"end"
] | does this artist represents various artists?
@return [Boolean] | [
"does",
"this",
"artist",
"represents",
"various",
"artists?"
] | 20373ab8664c7c4ebe5dcb4719017c25dde90736 | https://github.com/filip-d/7digital/blob/20373ab8664c7c4ebe5dcb4719017c25dde90736/lib/sevendigital/model/artist.rb#L94-L101 | train |
dominikh/weechat-ruby | lib/weechat.rb | Weechat.Helper.command_callback | def command_callback(id, buffer, args)
Weechat::Command.find_by_id(id).call(Weechat::Buffer.from_ptr(buffer), args)
end | ruby | def command_callback(id, buffer, args)
Weechat::Command.find_by_id(id).call(Weechat::Buffer.from_ptr(buffer), args)
end | [
"def",
"command_callback",
"(",
"id",
",",
"buffer",
",",
"args",
")",
"Weechat",
"::",
"Command",
".",
"find_by_id",
"(",
"id",
")",
".",
"call",
"(",
"Weechat",
"::",
"Buffer",
".",
"from_ptr",
"(",
"buffer",
")",
",",
"args",
")",
"end"
] | low level Callback method used for commands | [
"low",
"level",
"Callback",
"method",
"used",
"for",
"commands"
] | b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb | https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat.rb#L48-L50 | train |
dominikh/weechat-ruby | lib/weechat.rb | Weechat.Helper.command_run_callback | def command_run_callback(id, buffer, command)
Weechat::Hooks::CommandRunHook.find_by_id(id).call(Weechat::Buffer.from_ptr(buffer), command)
end | ruby | def command_run_callback(id, buffer, command)
Weechat::Hooks::CommandRunHook.find_by_id(id).call(Weechat::Buffer.from_ptr(buffer), command)
end | [
"def",
"command_run_callback",
"(",
"id",
",",
"buffer",
",",
"command",
")",
"Weechat",
"::",
"Hooks",
"::",
"CommandRunHook",
".",
"find_by_id",
"(",
"id",
")",
".",
"call",
"(",
"Weechat",
"::",
"Buffer",
".",
"from_ptr",
"(",
"buffer",
")",
",",
"command",
")",
"end"
] | low level Callback used for running commands | [
"low",
"level",
"Callback",
"used",
"for",
"running",
"commands"
] | b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb | https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat.rb#L53-L55 | train |
dominikh/weechat-ruby | lib/weechat.rb | Weechat.Helper.timer_callback | def timer_callback(id, remaining)
Weechat::Timer.find_by_id(id).call(remaining.to_i)
end | ruby | def timer_callback(id, remaining)
Weechat::Timer.find_by_id(id).call(remaining.to_i)
end | [
"def",
"timer_callback",
"(",
"id",
",",
"remaining",
")",
"Weechat",
"::",
"Timer",
".",
"find_by_id",
"(",
"id",
")",
".",
"call",
"(",
"remaining",
".",
"to_i",
")",
"end"
] | low level Timer callback | [
"low",
"level",
"Timer",
"callback"
] | b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb | https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat.rb#L58-L60 | train |
dominikh/weechat-ruby | lib/weechat.rb | Weechat.Helper.input_callback | def input_callback(method, buffer, input)
Weechat::Buffer.call_input_callback(method, buffer, input)
end | ruby | def input_callback(method, buffer, input)
Weechat::Buffer.call_input_callback(method, buffer, input)
end | [
"def",
"input_callback",
"(",
"method",
",",
"buffer",
",",
"input",
")",
"Weechat",
"::",
"Buffer",
".",
"call_input_callback",
"(",
"method",
",",
"buffer",
",",
"input",
")",
"end"
] | low level buffer input callback | [
"low",
"level",
"buffer",
"input",
"callback"
] | b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb | https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat.rb#L63-L65 | train |
dominikh/weechat-ruby | lib/weechat.rb | Weechat.Helper.bar_build_callback | def bar_build_callback(id, item, window)
Weechat::Bar::Item.call_build_callback(id, window)
end | ruby | def bar_build_callback(id, item, window)
Weechat::Bar::Item.call_build_callback(id, window)
end | [
"def",
"bar_build_callback",
"(",
"id",
",",
"item",
",",
"window",
")",
"Weechat",
"::",
"Bar",
"::",
"Item",
".",
"call_build_callback",
"(",
"id",
",",
"window",
")",
"end"
] | low level bar build callback | [
"low",
"level",
"bar",
"build",
"callback"
] | b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb | https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat.rb#L73-L75 | train |
dominikh/weechat-ruby | lib/weechat.rb | Weechat.Helper.info_callback | def info_callback(id, info, arguments)
Weechat::Info.find_by_id(id).call(arguments).to_s
end | ruby | def info_callback(id, info, arguments)
Weechat::Info.find_by_id(id).call(arguments).to_s
end | [
"def",
"info_callback",
"(",
"id",
",",
"info",
",",
"arguments",
")",
"Weechat",
"::",
"Info",
".",
"find_by_id",
"(",
"id",
")",
".",
"call",
"(",
"arguments",
")",
".",
"to_s",
"end"
] | low level info callback | [
"low",
"level",
"info",
"callback"
] | b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb | https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat.rb#L78-L80 | train |
dominikh/weechat-ruby | lib/weechat.rb | Weechat.Helper.print_callback | def print_callback(id, buffer, date, tags, displayed, highlight, prefix, message)
buffer = Weechat::Buffer.from_ptr(buffer)
date = Time.at(date.to_i)
tags = tags.split(",")
displayed = Weechat.integer_to_bool(displayed)
highlight = Weechat.integer_to_bool(highlight)
line = PrintedLine.new(buffer, date, tags, displayed, highlight, prefix, message)
Weechat::Hooks::Print.find_by_id(id).call(line)
end | ruby | def print_callback(id, buffer, date, tags, displayed, highlight, prefix, message)
buffer = Weechat::Buffer.from_ptr(buffer)
date = Time.at(date.to_i)
tags = tags.split(",")
displayed = Weechat.integer_to_bool(displayed)
highlight = Weechat.integer_to_bool(highlight)
line = PrintedLine.new(buffer, date, tags, displayed, highlight, prefix, message)
Weechat::Hooks::Print.find_by_id(id).call(line)
end | [
"def",
"print_callback",
"(",
"id",
",",
"buffer",
",",
"date",
",",
"tags",
",",
"displayed",
",",
"highlight",
",",
"prefix",
",",
"message",
")",
"buffer",
"=",
"Weechat",
"::",
"Buffer",
".",
"from_ptr",
"(",
"buffer",
")",
"date",
"=",
"Time",
".",
"at",
"(",
"date",
".",
"to_i",
")",
"tags",
"=",
"tags",
".",
"split",
"(",
"\",\"",
")",
"displayed",
"=",
"Weechat",
".",
"integer_to_bool",
"(",
"displayed",
")",
"highlight",
"=",
"Weechat",
".",
"integer_to_bool",
"(",
"highlight",
")",
"line",
"=",
"PrintedLine",
".",
"new",
"(",
"buffer",
",",
"date",
",",
"tags",
",",
"displayed",
",",
"highlight",
",",
"prefix",
",",
"message",
")",
"Weechat",
"::",
"Hooks",
"::",
"Print",
".",
"find_by_id",
"(",
"id",
")",
".",
"call",
"(",
"line",
")",
"end"
] | low level print callback | [
"low",
"level",
"print",
"callback"
] | b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb | https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat.rb#L83-L91 | train |
dominikh/weechat-ruby | lib/weechat.rb | Weechat.Helper.signal_callback | def signal_callback(id, signal, data)
data = Weechat::Utilities.apply_transformation(signal, data, SignalCallbackTransformations)
Weechat::Hooks::Signal.find_by_id(id).call(signal, data)
end | ruby | def signal_callback(id, signal, data)
data = Weechat::Utilities.apply_transformation(signal, data, SignalCallbackTransformations)
Weechat::Hooks::Signal.find_by_id(id).call(signal, data)
end | [
"def",
"signal_callback",
"(",
"id",
",",
"signal",
",",
"data",
")",
"data",
"=",
"Weechat",
"::",
"Utilities",
".",
"apply_transformation",
"(",
"signal",
",",
"data",
",",
"SignalCallbackTransformations",
")",
"Weechat",
"::",
"Hooks",
"::",
"Signal",
".",
"find_by_id",
"(",
"id",
")",
".",
"call",
"(",
"signal",
",",
"data",
")",
"end"
] | low level callback for signal hooks | [
"low",
"level",
"callback",
"for",
"signal",
"hooks"
] | b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb | https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat.rb#L114-L117 | train |
dominikh/weechat-ruby | lib/weechat.rb | Weechat.Helper.config_callback | def config_callback(id, option, value)
ret = Weechat::Hooks::Config.find_by_id(id).call(option, value)
end | ruby | def config_callback(id, option, value)
ret = Weechat::Hooks::Config.find_by_id(id).call(option, value)
end | [
"def",
"config_callback",
"(",
"id",
",",
"option",
",",
"value",
")",
"ret",
"=",
"Weechat",
"::",
"Hooks",
"::",
"Config",
".",
"find_by_id",
"(",
"id",
")",
".",
"call",
"(",
"option",
",",
"value",
")",
"end"
] | low level config callback | [
"low",
"level",
"config",
"callback"
] | b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb | https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat.rb#L120-L122 | train |
dominikh/weechat-ruby | lib/weechat.rb | Weechat.Helper.process_callback | def process_callback(id, command, code, stdout, stderr)
code = case code
when Weechat::WEECHAT_HOOK_PROCESS_RUNNING
:running
when Weechat::WEECHAT_HOOK_PROCESS_ERROR
:error
else
code
end
process = Weechat::Process.find_by_id(id)
if process.collect?
process.buffer(stdout, stderr)
if code == :error || code != :running
process.call(code, process.stdout, process.stderr)
end
else
process.call(code, stdout, stderr)
end
end | ruby | def process_callback(id, command, code, stdout, stderr)
code = case code
when Weechat::WEECHAT_HOOK_PROCESS_RUNNING
:running
when Weechat::WEECHAT_HOOK_PROCESS_ERROR
:error
else
code
end
process = Weechat::Process.find_by_id(id)
if process.collect?
process.buffer(stdout, stderr)
if code == :error || code != :running
process.call(code, process.stdout, process.stderr)
end
else
process.call(code, stdout, stderr)
end
end | [
"def",
"process_callback",
"(",
"id",
",",
"command",
",",
"code",
",",
"stdout",
",",
"stderr",
")",
"code",
"=",
"case",
"code",
"when",
"Weechat",
"::",
"WEECHAT_HOOK_PROCESS_RUNNING",
":running",
"when",
"Weechat",
"::",
"WEECHAT_HOOK_PROCESS_ERROR",
":error",
"else",
"code",
"end",
"process",
"=",
"Weechat",
"::",
"Process",
".",
"find_by_id",
"(",
"id",
")",
"if",
"process",
".",
"collect?",
"process",
".",
"buffer",
"(",
"stdout",
",",
"stderr",
")",
"if",
"code",
"==",
":error",
"||",
"code",
"!=",
":running",
"process",
".",
"call",
"(",
"code",
",",
"process",
".",
"stdout",
",",
"process",
".",
"stderr",
")",
"end",
"else",
"process",
".",
"call",
"(",
"code",
",",
"stdout",
",",
"stderr",
")",
"end",
"end"
] | low level process callback | [
"low",
"level",
"process",
"callback"
] | b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb | https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat.rb#L125-L144 | train |
dominikh/weechat-ruby | lib/weechat.rb | Weechat.Helper.modifier_callback | def modifier_callback(id, modifier, modifier_data, s)
classes = Weechat::Hook.hook_classes
modifier_data = Weechat::Utilities.apply_transformation(modifier, modifier_data, ModifierCallbackTransformations)
modifier_data = [modifier_data] unless modifier_data.is_a?(Array)
args = modifier_data + [Weechat::Line.parse(s)]
callback = classes.map {|cls| cls.find_by_id(id)}.compact.first
ret = callback.call(*args)
return Weechat::Utilities.apply_transformation(modifier, ret, ModifierCallbackRTransformations).to_s
end | ruby | def modifier_callback(id, modifier, modifier_data, s)
classes = Weechat::Hook.hook_classes
modifier_data = Weechat::Utilities.apply_transformation(modifier, modifier_data, ModifierCallbackTransformations)
modifier_data = [modifier_data] unless modifier_data.is_a?(Array)
args = modifier_data + [Weechat::Line.parse(s)]
callback = classes.map {|cls| cls.find_by_id(id)}.compact.first
ret = callback.call(*args)
return Weechat::Utilities.apply_transformation(modifier, ret, ModifierCallbackRTransformations).to_s
end | [
"def",
"modifier_callback",
"(",
"id",
",",
"modifier",
",",
"modifier_data",
",",
"s",
")",
"classes",
"=",
"Weechat",
"::",
"Hook",
".",
"hook_classes",
"modifier_data",
"=",
"Weechat",
"::",
"Utilities",
".",
"apply_transformation",
"(",
"modifier",
",",
"modifier_data",
",",
"ModifierCallbackTransformations",
")",
"modifier_data",
"=",
"[",
"modifier_data",
"]",
"unless",
"modifier_data",
".",
"is_a?",
"(",
"Array",
")",
"args",
"=",
"modifier_data",
"+",
"[",
"Weechat",
"::",
"Line",
".",
"parse",
"(",
"s",
")",
"]",
"callback",
"=",
"classes",
".",
"map",
"{",
"|",
"cls",
"|",
"cls",
".",
"find_by_id",
"(",
"id",
")",
"}",
".",
"compact",
".",
"first",
"ret",
"=",
"callback",
".",
"call",
"(",
"args",
")",
"return",
"Weechat",
"::",
"Utilities",
".",
"apply_transformation",
"(",
"modifier",
",",
"ret",
",",
"ModifierCallbackRTransformations",
")",
".",
"to_s",
"end"
] | low level modifier hook callback | [
"low",
"level",
"modifier",
"hook",
"callback"
] | b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb | https://github.com/dominikh/weechat-ruby/blob/b3bbe37e5c0cc0a41e9107a23b7cfbb39c0e59eb/lib/weechat.rb#L172-L182 | train |
alexggordon/basecampeverest | lib/basecampeverest/connect.rb | Basecampeverest.Connect.auth= | def auth=(authorization)
clensed_auth_hash = {}
authorization.each {|k, v|
clensed_auth_hash[k.to_sym] = v
}
# nice and pretty now
authorization = clensed_auth_hash
if authorization.has_key? :access_token
# clear the basic_auth, if it's set
self.class.default_options.reject!{ |k| k == :basic_auth }
# set the Authorization headers
self.class.headers.merge!("Authorization" => "Bearer #{authorization[:access_token]}")
elsif authorization.has_key?(:username) && authorization.has_key?(:password)
# ... then we pass it off to basic auth
self.class.basic_auth authorization[:username], authorization[:password]
# check if the user tried passing in some other stupid stuff.
# this should never be the case if the user follows instructions.
self.class.headers.reject!{ |k, v| k == "Authorization" }
else
# something inportant is missing if we get here.
raise "Incomplete Authorization hash. Please check the Authentication Hash."
#end else
end
# end method
end | ruby | def auth=(authorization)
clensed_auth_hash = {}
authorization.each {|k, v|
clensed_auth_hash[k.to_sym] = v
}
# nice and pretty now
authorization = clensed_auth_hash
if authorization.has_key? :access_token
# clear the basic_auth, if it's set
self.class.default_options.reject!{ |k| k == :basic_auth }
# set the Authorization headers
self.class.headers.merge!("Authorization" => "Bearer #{authorization[:access_token]}")
elsif authorization.has_key?(:username) && authorization.has_key?(:password)
# ... then we pass it off to basic auth
self.class.basic_auth authorization[:username], authorization[:password]
# check if the user tried passing in some other stupid stuff.
# this should never be the case if the user follows instructions.
self.class.headers.reject!{ |k, v| k == "Authorization" }
else
# something inportant is missing if we get here.
raise "Incomplete Authorization hash. Please check the Authentication Hash."
#end else
end
# end method
end | [
"def",
"auth",
"=",
"(",
"authorization",
")",
"clensed_auth_hash",
"=",
"{",
"}",
"authorization",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"clensed_auth_hash",
"[",
"k",
".",
"to_sym",
"]",
"=",
"v",
"}",
"# nice and pretty now",
"authorization",
"=",
"clensed_auth_hash",
"if",
"authorization",
".",
"has_key?",
":access_token",
"# clear the basic_auth, if it's set",
"self",
".",
"class",
".",
"default_options",
".",
"reject!",
"{",
"|",
"k",
"|",
"k",
"==",
":basic_auth",
"}",
"# set the Authorization headers",
"self",
".",
"class",
".",
"headers",
".",
"merge!",
"(",
"\"Authorization\"",
"=>",
"\"Bearer #{authorization[:access_token]}\"",
")",
"elsif",
"authorization",
".",
"has_key?",
"(",
":username",
")",
"&&",
"authorization",
".",
"has_key?",
"(",
":password",
")",
"# ... then we pass it off to basic auth",
"self",
".",
"class",
".",
"basic_auth",
"authorization",
"[",
":username",
"]",
",",
"authorization",
"[",
":password",
"]",
"# check if the user tried passing in some other stupid stuff.",
"# this should never be the case if the user follows instructions. ",
"self",
".",
"class",
".",
"headers",
".",
"reject!",
"{",
"|",
"k",
",",
"v",
"|",
"k",
"==",
"\"Authorization\"",
"}",
"else",
"# something inportant is missing if we get here. ",
"raise",
"\"Incomplete Authorization hash. Please check the Authentication Hash.\"",
"#end else ",
"end",
"# end method",
"end"
] | Initializes the connection to Basecamp using httparty.
@param basecamp_id [String] the Basecamp company ID
@param authorization [Hash] authorization hash consisting of a username and password combination (:username, :password) or an access_token (:access_token)
@param user_agent [String] the user-agent string to include in header of requests
Sets the authorization information.
Need to
@param authorization [Hash] authorization hash consisting of a username and password combination (:username, :password) or an access_token (:access_token) | [
"Initializes",
"the",
"connection",
"to",
"Basecamp",
"using",
"httparty",
"."
] | dd6aede7c43f9ea81c4e8a80103c1d2f01d61fb0 | https://github.com/alexggordon/basecampeverest/blob/dd6aede7c43f9ea81c4e8a80103c1d2f01d61fb0/lib/basecampeverest/connect.rb#L83-L117 | train |
tbuehlmann/ponder | lib/ponder/user_list.rb | Ponder.UserList.kill_zombie_users | def kill_zombie_users(users)
@mutex.synchronize do
(@users - users - Set.new([@thaum_user])).each do |user|
@users.delete(user)
end
end
end | ruby | def kill_zombie_users(users)
@mutex.synchronize do
(@users - users - Set.new([@thaum_user])).each do |user|
@users.delete(user)
end
end
end | [
"def",
"kill_zombie_users",
"(",
"users",
")",
"@mutex",
".",
"synchronize",
"do",
"(",
"@users",
"-",
"users",
"-",
"Set",
".",
"new",
"(",
"[",
"@thaum_user",
"]",
")",
")",
".",
"each",
"do",
"|",
"user",
"|",
"@users",
".",
"delete",
"(",
"user",
")",
"end",
"end",
"end"
] | Removes all users from the UserList that don't share channels with the
Thaum. | [
"Removes",
"all",
"users",
"from",
"the",
"UserList",
"that",
"don",
"t",
"share",
"channels",
"with",
"the",
"Thaum",
"."
] | 930912e1b78b41afa1359121aca46197e9edff9c | https://github.com/tbuehlmann/ponder/blob/930912e1b78b41afa1359121aca46197e9edff9c/lib/ponder/user_list.rb#L44-L50 | train |
tech-angels/annotator | lib/annotator/attributes.rb | Annotator.Attributes.lines | def lines
ret = [Attributes::HEADER]
# Sort by name, but id goes first
@attrs.sort_by{|x| x[:name] == 'id' ? '_' : x[:name]}.each do |row|
line = "# * #{row[:name]} [#{row[:type]}]#{row[:desc].to_s.empty? ? "" : " - #{row[:desc]}"}"
# split into lines that don't exceed 80 chars
lt = wrap_text(line, MAX_CHARS_PER_LINE-3).split("\n")
line = ([lt[0]] + lt[1..-1].map{|x| "# #{x}"}).join("\n")
ret << line
end
ret
end | ruby | def lines
ret = [Attributes::HEADER]
# Sort by name, but id goes first
@attrs.sort_by{|x| x[:name] == 'id' ? '_' : x[:name]}.each do |row|
line = "# * #{row[:name]} [#{row[:type]}]#{row[:desc].to_s.empty? ? "" : " - #{row[:desc]}"}"
# split into lines that don't exceed 80 chars
lt = wrap_text(line, MAX_CHARS_PER_LINE-3).split("\n")
line = ([lt[0]] + lt[1..-1].map{|x| "# #{x}"}).join("\n")
ret << line
end
ret
end | [
"def",
"lines",
"ret",
"=",
"[",
"Attributes",
"::",
"HEADER",
"]",
"# Sort by name, but id goes first",
"@attrs",
".",
"sort_by",
"{",
"|",
"x",
"|",
"x",
"[",
":name",
"]",
"==",
"'id'",
"?",
"'_'",
":",
"x",
"[",
":name",
"]",
"}",
".",
"each",
"do",
"|",
"row",
"|",
"line",
"=",
"\"# * #{row[:name]} [#{row[:type]}]#{row[:desc].to_s.empty? ? \"\" : \" - #{row[:desc]}\"}\"",
"# split into lines that don't exceed 80 chars",
"lt",
"=",
"wrap_text",
"(",
"line",
",",
"MAX_CHARS_PER_LINE",
"-",
"3",
")",
".",
"split",
"(",
"\"\\n\"",
")",
"line",
"=",
"(",
"[",
"lt",
"[",
"0",
"]",
"]",
"+",
"lt",
"[",
"1",
"..",
"-",
"1",
"]",
".",
"map",
"{",
"|",
"x",
"|",
"\"# #{x}\"",
"}",
")",
".",
"join",
"(",
"\"\\n\"",
")",
"ret",
"<<",
"line",
"end",
"ret",
"end"
] | Convert attributes array back to attributes lines representation to be put into file | [
"Convert",
"attributes",
"array",
"back",
"to",
"attributes",
"lines",
"representation",
"to",
"be",
"put",
"into",
"file"
] | ad8f203635633eb3428105be7c39b80694184a2b | https://github.com/tech-angels/annotator/blob/ad8f203635633eb3428105be7c39b80694184a2b/lib/annotator/attributes.rb#L20-L31 | train |
tech-angels/annotator | lib/annotator/attributes.rb | Annotator.Attributes.update! | def update!
@model.columns.each do |column|
if row = @attrs.find {|x| x[:name] == column.name}
if row[:type] != type_str(column)
puts " M #{@model}##{column.name} [#{row[:type]} -> #{type_str(column)}]"
row[:type] = type_str(column)
elsif row[:desc] == InitialDescription::DEFAULT_DESCRIPTION
new_desc = InitialDescription.for(@model, column.name)
if row[:desc] != new_desc
puts " M #{@model}##{column.name} description updated"
row[:desc] = new_desc
end
end
else
puts " A #{@model}##{column.name} [#{type_str(column)}]"
@attrs << {
:name => column.name,
:type => type_str(column),
:desc => InitialDescription.for(@model, column.name)
}
end
end
# find columns that no more exist in db
orphans = @attrs.map{|x| x[:name]} - @model.columns.map(&:name)
unless orphans.empty?
orphans.each do |orphan|
puts " D #{@model}##{orphan}"
@attrs = @attrs.select {|x| x[:name] != orphan}
end
end
@attrs
end | ruby | def update!
@model.columns.each do |column|
if row = @attrs.find {|x| x[:name] == column.name}
if row[:type] != type_str(column)
puts " M #{@model}##{column.name} [#{row[:type]} -> #{type_str(column)}]"
row[:type] = type_str(column)
elsif row[:desc] == InitialDescription::DEFAULT_DESCRIPTION
new_desc = InitialDescription.for(@model, column.name)
if row[:desc] != new_desc
puts " M #{@model}##{column.name} description updated"
row[:desc] = new_desc
end
end
else
puts " A #{@model}##{column.name} [#{type_str(column)}]"
@attrs << {
:name => column.name,
:type => type_str(column),
:desc => InitialDescription.for(@model, column.name)
}
end
end
# find columns that no more exist in db
orphans = @attrs.map{|x| x[:name]} - @model.columns.map(&:name)
unless orphans.empty?
orphans.each do |orphan|
puts " D #{@model}##{orphan}"
@attrs = @attrs.select {|x| x[:name] != orphan}
end
end
@attrs
end | [
"def",
"update!",
"@model",
".",
"columns",
".",
"each",
"do",
"|",
"column",
"|",
"if",
"row",
"=",
"@attrs",
".",
"find",
"{",
"|",
"x",
"|",
"x",
"[",
":name",
"]",
"==",
"column",
".",
"name",
"}",
"if",
"row",
"[",
":type",
"]",
"!=",
"type_str",
"(",
"column",
")",
"puts",
"\" M #{@model}##{column.name} [#{row[:type]} -> #{type_str(column)}]\"",
"row",
"[",
":type",
"]",
"=",
"type_str",
"(",
"column",
")",
"elsif",
"row",
"[",
":desc",
"]",
"==",
"InitialDescription",
"::",
"DEFAULT_DESCRIPTION",
"new_desc",
"=",
"InitialDescription",
".",
"for",
"(",
"@model",
",",
"column",
".",
"name",
")",
"if",
"row",
"[",
":desc",
"]",
"!=",
"new_desc",
"puts",
"\" M #{@model}##{column.name} description updated\"",
"row",
"[",
":desc",
"]",
"=",
"new_desc",
"end",
"end",
"else",
"puts",
"\" A #{@model}##{column.name} [#{type_str(column)}]\"",
"@attrs",
"<<",
"{",
":name",
"=>",
"column",
".",
"name",
",",
":type",
"=>",
"type_str",
"(",
"column",
")",
",",
":desc",
"=>",
"InitialDescription",
".",
"for",
"(",
"@model",
",",
"column",
".",
"name",
")",
"}",
"end",
"end",
"# find columns that no more exist in db",
"orphans",
"=",
"@attrs",
".",
"map",
"{",
"|",
"x",
"|",
"x",
"[",
":name",
"]",
"}",
"-",
"@model",
".",
"columns",
".",
"map",
"(",
":name",
")",
"unless",
"orphans",
".",
"empty?",
"orphans",
".",
"each",
"do",
"|",
"orphan",
"|",
"puts",
"\" D #{@model}##{orphan}\"",
"@attrs",
"=",
"@attrs",
".",
"select",
"{",
"|",
"x",
"|",
"x",
"[",
":name",
"]",
"!=",
"orphan",
"}",
"end",
"end",
"@attrs",
"end"
] | Update attribudes array to the current database state | [
"Update",
"attribudes",
"array",
"to",
"the",
"current",
"database",
"state"
] | ad8f203635633eb3428105be7c39b80694184a2b | https://github.com/tech-angels/annotator/blob/ad8f203635633eb3428105be7c39b80694184a2b/lib/annotator/attributes.rb#L34-L67 | train |
tech-angels/annotator | lib/annotator/attributes.rb | Annotator.Attributes.parse | def parse
@lines.each do |line|
if m = line.match(R_ATTRIBUTE)
@attrs << {:name => m[1].strip, :type => m[2].strip, :desc => m[4].strip}
elsif m = line.match(R_ATTRIBUTE_NEXT_LINE)
@attrs[-1][:desc] += " #{m[1].strip}"
end
end
end | ruby | def parse
@lines.each do |line|
if m = line.match(R_ATTRIBUTE)
@attrs << {:name => m[1].strip, :type => m[2].strip, :desc => m[4].strip}
elsif m = line.match(R_ATTRIBUTE_NEXT_LINE)
@attrs[-1][:desc] += " #{m[1].strip}"
end
end
end | [
"def",
"parse",
"@lines",
".",
"each",
"do",
"|",
"line",
"|",
"if",
"m",
"=",
"line",
".",
"match",
"(",
"R_ATTRIBUTE",
")",
"@attrs",
"<<",
"{",
":name",
"=>",
"m",
"[",
"1",
"]",
".",
"strip",
",",
":type",
"=>",
"m",
"[",
"2",
"]",
".",
"strip",
",",
":desc",
"=>",
"m",
"[",
"4",
"]",
".",
"strip",
"}",
"elsif",
"m",
"=",
"line",
".",
"match",
"(",
"R_ATTRIBUTE_NEXT_LINE",
")",
"@attrs",
"[",
"-",
"1",
"]",
"[",
":desc",
"]",
"+=",
"\" #{m[1].strip}\"",
"end",
"end",
"end"
] | Convert attributes lines into meaniningful array | [
"Convert",
"attributes",
"lines",
"into",
"meaniningful",
"array"
] | ad8f203635633eb3428105be7c39b80694184a2b | https://github.com/tech-angels/annotator/blob/ad8f203635633eb3428105be7c39b80694184a2b/lib/annotator/attributes.rb#L72-L80 | train |
tech-angels/annotator | lib/annotator/attributes.rb | Annotator.Attributes.truncate_default | def truncate_default(str)
return str unless str.kind_of? String
str.sub!(/^'(.*)'$/m,'\1')
str = "#{str[0..10]}..." if str.size > 10
str.inspect
end | ruby | def truncate_default(str)
return str unless str.kind_of? String
str.sub!(/^'(.*)'$/m,'\1')
str = "#{str[0..10]}..." if str.size > 10
str.inspect
end | [
"def",
"truncate_default",
"(",
"str",
")",
"return",
"str",
"unless",
"str",
".",
"kind_of?",
"String",
"str",
".",
"sub!",
"(",
"/",
"/m",
",",
"'\\1'",
")",
"str",
"=",
"\"#{str[0..10]}...\"",
"if",
"str",
".",
"size",
">",
"10",
"str",
".",
"inspect",
"end"
] | default value could be a multiple lines string, which would ruin annotations,
so we truncate it and display inspect of that string | [
"default",
"value",
"could",
"be",
"a",
"multiple",
"lines",
"string",
"which",
"would",
"ruin",
"annotations",
"so",
"we",
"truncate",
"it",
"and",
"display",
"inspect",
"of",
"that",
"string"
] | ad8f203635633eb3428105be7c39b80694184a2b | https://github.com/tech-angels/annotator/blob/ad8f203635633eb3428105be7c39b80694184a2b/lib/annotator/attributes.rb#L84-L89 | train |
tech-angels/annotator | lib/annotator/attributes.rb | Annotator.Attributes.type_str | def type_str(c)
ret = c.type.to_s
ret << ", primary" if c.primary
ret << ", default=#{truncate_default(c.default)}" if c.default
ret << ", not null" unless c.null
ret << ", limit=#{c.limit}" if c.limit && (c.limit != 255 && c.type != :string)
ret
end | ruby | def type_str(c)
ret = c.type.to_s
ret << ", primary" if c.primary
ret << ", default=#{truncate_default(c.default)}" if c.default
ret << ", not null" unless c.null
ret << ", limit=#{c.limit}" if c.limit && (c.limit != 255 && c.type != :string)
ret
end | [
"def",
"type_str",
"(",
"c",
")",
"ret",
"=",
"c",
".",
"type",
".",
"to_s",
"ret",
"<<",
"\", primary\"",
"if",
"c",
".",
"primary",
"ret",
"<<",
"\", default=#{truncate_default(c.default)}\"",
"if",
"c",
".",
"default",
"ret",
"<<",
"\", not null\"",
"unless",
"c",
".",
"null",
"ret",
"<<",
"\", limit=#{c.limit}\"",
"if",
"c",
".",
"limit",
"&&",
"(",
"c",
".",
"limit",
"!=",
"255",
"&&",
"c",
".",
"type",
"!=",
":string",
")",
"ret",
"end"
] | Human readable description of given column type | [
"Human",
"readable",
"description",
"of",
"given",
"column",
"type"
] | ad8f203635633eb3428105be7c39b80694184a2b | https://github.com/tech-angels/annotator/blob/ad8f203635633eb3428105be7c39b80694184a2b/lib/annotator/attributes.rb#L92-L99 | train |
colbell/bitsa | lib/bitsa.rb | Bitsa.BitsaApp.run | def run(global_opts, cmd, search_data)
settings = load_settings(global_opts)
process_cmd(cmd, search_data, settings.login, settings.password,
ContactsCache.new(settings.cache_file_path,
settings.auto_check))
end | ruby | def run(global_opts, cmd, search_data)
settings = load_settings(global_opts)
process_cmd(cmd, search_data, settings.login, settings.password,
ContactsCache.new(settings.cache_file_path,
settings.auto_check))
end | [
"def",
"run",
"(",
"global_opts",
",",
"cmd",
",",
"search_data",
")",
"settings",
"=",
"load_settings",
"(",
"global_opts",
")",
"process_cmd",
"(",
"cmd",
",",
"search_data",
",",
"settings",
".",
"login",
",",
"settings",
".",
"password",
",",
"ContactsCache",
".",
"new",
"(",
"settings",
".",
"cache_file_path",
",",
"settings",
".",
"auto_check",
")",
")",
"end"
] | Run application.
@example run the application
args = Bitsa::CLI.new
args.parse(ARGV)
app = Bitsa::BitsaApp.new
app.run(args.global_opts, args.cmd, args.search_data)
@param global_opts [Hash] Application arguments
@param cmd [String] The command requested.
@param search_data [String] Data to search for from cmd line.
@return [nil] ignored | [
"Run",
"application",
"."
] | 8b73c4988bde1bf8e64d9cb999164c3e5988dba5 | https://github.com/colbell/bitsa/blob/8b73c4988bde1bf8e64d9cb999164c3e5988dba5/lib/bitsa.rb#L47-L52 | train |
colbell/bitsa | lib/bitsa.rb | Bitsa.BitsaApp.load_settings | def load_settings(global_opts)
settings = Settings.new
settings.load(ConfigFile.new(global_opts[:config_file]), global_opts)
settings
end | ruby | def load_settings(global_opts)
settings = Settings.new
settings.load(ConfigFile.new(global_opts[:config_file]), global_opts)
settings
end | [
"def",
"load_settings",
"(",
"global_opts",
")",
"settings",
"=",
"Settings",
".",
"new",
"settings",
".",
"load",
"(",
"ConfigFile",
".",
"new",
"(",
"global_opts",
"[",
":config_file",
"]",
")",
",",
"global_opts",
")",
"settings",
"end"
] | Load settings, combining arguments from cmd lien and the settings file.
@param global_opts [Hash] Application arguments
@return [Settings] Object representing the settings for this run of the
app. | [
"Load",
"settings",
"combining",
"arguments",
"from",
"cmd",
"lien",
"and",
"the",
"settings",
"file",
"."
] | 8b73c4988bde1bf8e64d9cb999164c3e5988dba5 | https://github.com/colbell/bitsa/blob/8b73c4988bde1bf8e64d9cb999164c3e5988dba5/lib/bitsa.rb#L83-L87 | train |
colbell/bitsa | lib/bitsa.rb | Bitsa.BitsaApp.search | def search(cache, search_data)
puts '' # Force first entry to be displayed in mutt
# Write out as EMAIL <TAB> NAME
cache.search(search_data).each { |k, v| puts "#{k}\t#{v}" }
end | ruby | def search(cache, search_data)
puts '' # Force first entry to be displayed in mutt
# Write out as EMAIL <TAB> NAME
cache.search(search_data).each { |k, v| puts "#{k}\t#{v}" }
end | [
"def",
"search",
"(",
"cache",
",",
"search_data",
")",
"puts",
"''",
"# Force first entry to be displayed in mutt",
"# Write out as EMAIL <TAB> NAME",
"cache",
".",
"search",
"(",
"search_data",
")",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"puts",
"\"#{k}\\t#{v}\"",
"}",
"end"
] | Search the cache for the requested search_data and write the results to
std output.
@param cache [ContactsCache] Cache of contacts to be searched.
@param search_data [String] Data to search cache for. | [
"Search",
"the",
"cache",
"for",
"the",
"requested",
"search_data",
"and",
"write",
"the",
"results",
"to",
"std",
"output",
"."
] | 8b73c4988bde1bf8e64d9cb999164c3e5988dba5 | https://github.com/colbell/bitsa/blob/8b73c4988bde1bf8e64d9cb999164c3e5988dba5/lib/bitsa.rb#L104-L108 | train |
NUBIC/aker | lib/aker/form/login_form_asset_provider.rb | Aker::Form.LoginFormAssetProvider.asset_root | def asset_root
File.expand_path(File.join(File.dirname(__FILE__),
%w(.. .. ..),
%w(assets aker form)))
end | ruby | def asset_root
File.expand_path(File.join(File.dirname(__FILE__),
%w(.. .. ..),
%w(assets aker form)))
end | [
"def",
"asset_root",
"File",
".",
"expand_path",
"(",
"File",
".",
"join",
"(",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
",",
"%w(",
"..",
"..",
"..",
")",
",",
"%w(",
"assets",
"aker",
"form",
")",
")",
")",
"end"
] | Where to look for HTML and CSS assets.
This is currently hardcoded as `(aker gem root)/assets/aker/form`.
@return [String] a directory path | [
"Where",
"to",
"look",
"for",
"HTML",
"and",
"CSS",
"assets",
"."
] | ff43606a8812e38f96bbe71b46e7f631cbeacf1c | https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/form/login_form_asset_provider.rb#L20-L24 | train |
NUBIC/aker | lib/aker/form/login_form_asset_provider.rb | Aker::Form.LoginFormAssetProvider.login_html | def login_html(env, options = {})
login_base = env['SCRIPT_NAME'] + login_path(env)
template = File.read(File.join(asset_root, 'login.html.erb'))
ERB.new(template).result(binding)
end | ruby | def login_html(env, options = {})
login_base = env['SCRIPT_NAME'] + login_path(env)
template = File.read(File.join(asset_root, 'login.html.erb'))
ERB.new(template).result(binding)
end | [
"def",
"login_html",
"(",
"env",
",",
"options",
"=",
"{",
"}",
")",
"login_base",
"=",
"env",
"[",
"'SCRIPT_NAME'",
"]",
"+",
"login_path",
"(",
"env",
")",
"template",
"=",
"File",
".",
"read",
"(",
"File",
".",
"join",
"(",
"asset_root",
",",
"'login.html.erb'",
")",
")",
"ERB",
".",
"new",
"(",
"template",
")",
".",
"result",
"(",
"binding",
")",
"end"
] | Provides the HTML for the login form.
This method expects to find a `login.html.erb` ERB template in
{#asset_root}. The ERB template is evaluated in an environment where
a local variable named `script_name` is bound to the value of the
`SCRIPT_NAME` Rack environment variable, which is useful for CSS and
form action URL generation.
@param env [Rack environment] a Rack environment
@param [Hash] options rendering options
@option options [Boolean] :login_failed If true, will render a failure message
@option options [Boolean] :logged_out If true, will render a logout notification
@option options [String] :username Text for the username field
@option options [String] :url A URL to redirect to upon successful login
@return [String] HTML data | [
"Provides",
"the",
"HTML",
"for",
"the",
"login",
"form",
"."
] | ff43606a8812e38f96bbe71b46e7f631cbeacf1c | https://github.com/NUBIC/aker/blob/ff43606a8812e38f96bbe71b46e7f631cbeacf1c/lib/aker/form/login_form_asset_provider.rb#L42-L46 | train |
GeoffWilliams/puppetbox | lib/puppetbox/result.rb | PuppetBox.Result.passed? | def passed?
passed = nil
@report.each { |r|
if passed == nil
passed = (r[:status] == PS_OK)
else
passed &= (r[:status] == PS_OK)
end
}
passed
end | ruby | def passed?
passed = nil
@report.each { |r|
if passed == nil
passed = (r[:status] == PS_OK)
else
passed &= (r[:status] == PS_OK)
end
}
passed
end | [
"def",
"passed?",
"passed",
"=",
"nil",
"@report",
".",
"each",
"{",
"|",
"r",
"|",
"if",
"passed",
"==",
"nil",
"passed",
"=",
"(",
"r",
"[",
":status",
"]",
"==",
"PS_OK",
")",
"else",
"passed",
"&=",
"(",
"r",
"[",
":status",
"]",
"==",
"PS_OK",
")",
"end",
"}",
"passed",
"end"
] | Test whether this set of results passed or not
@return true if tests were executed and passed, nil if no tests were
executed, false if tests were exectued and there were failures | [
"Test",
"whether",
"this",
"set",
"of",
"results",
"passed",
"or",
"not"
] | 8ace050aa46e8908c1b266b9307f01929e222e53 | https://github.com/GeoffWilliams/puppetbox/blob/8ace050aa46e8908c1b266b9307f01929e222e53/lib/puppetbox/result.rb#L52-L63 | train |
pvijayror/rails_exception_logger | app/controllers/rails_exception_logger/logged_exceptions_controller.rb | RailsExceptionLogger.LoggedExceptionsController.get_auth_data | def get_auth_data
auth_key = @@http_auth_headers.detect { |h| request.env.has_key?(h) }
auth_data = request.env[auth_key].to_s.split unless auth_key.blank?
return auth_data && auth_data[0] == 'Basic' ? Base64.decode64(auth_data[1]).split(':')[0..1] : [nil, nil]
end | ruby | def get_auth_data
auth_key = @@http_auth_headers.detect { |h| request.env.has_key?(h) }
auth_data = request.env[auth_key].to_s.split unless auth_key.blank?
return auth_data && auth_data[0] == 'Basic' ? Base64.decode64(auth_data[1]).split(':')[0..1] : [nil, nil]
end | [
"def",
"get_auth_data",
"auth_key",
"=",
"@@http_auth_headers",
".",
"detect",
"{",
"|",
"h",
"|",
"request",
".",
"env",
".",
"has_key?",
"(",
"h",
")",
"}",
"auth_data",
"=",
"request",
".",
"env",
"[",
"auth_key",
"]",
".",
"to_s",
".",
"split",
"unless",
"auth_key",
".",
"blank?",
"return",
"auth_data",
"&&",
"auth_data",
"[",
"0",
"]",
"==",
"'Basic'",
"?",
"Base64",
".",
"decode64",
"(",
"auth_data",
"[",
"1",
"]",
")",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"..",
"1",
"]",
":",
"[",
"nil",
",",
"nil",
"]",
"end"
] | gets BASIC auth info | [
"gets",
"BASIC",
"auth",
"info"
] | aa58eb0a018ad6318002b87a333b71d04373116a | https://github.com/pvijayror/rails_exception_logger/blob/aa58eb0a018ad6318002b87a333b71d04373116a/app/controllers/rails_exception_logger/logged_exceptions_controller.rb#L99-L103 | train |
marcboeker/mongolicious | lib/mongolicious/backup.rb | Mongolicious.Backup.parse_jobfile | def parse_jobfile(jobfile)
YAML.load(File.read(jobfile))
rescue Errno::ENOENT
Mongolicious.logger.error("Could not find job file at #{ARGV[0]}")
exit
rescue ArgumentError => e
Mongolicious.logger.error("Could not parse job file #{ARGV[0]} - #{e}")
exit
end | ruby | def parse_jobfile(jobfile)
YAML.load(File.read(jobfile))
rescue Errno::ENOENT
Mongolicious.logger.error("Could not find job file at #{ARGV[0]}")
exit
rescue ArgumentError => e
Mongolicious.logger.error("Could not parse job file #{ARGV[0]} - #{e}")
exit
end | [
"def",
"parse_jobfile",
"(",
"jobfile",
")",
"YAML",
".",
"load",
"(",
"File",
".",
"read",
"(",
"jobfile",
")",
")",
"rescue",
"Errno",
"::",
"ENOENT",
"Mongolicious",
".",
"logger",
".",
"error",
"(",
"\"Could not find job file at #{ARGV[0]}\"",
")",
"exit",
"rescue",
"ArgumentError",
"=>",
"e",
"Mongolicious",
".",
"logger",
".",
"error",
"(",
"\"Could not parse job file #{ARGV[0]} - #{e}\"",
")",
"exit",
"end"
] | Parse YAML job configuration.
@param [String] jobfile the path of the job configuration file.
@return [Hash] | [
"Parse",
"YAML",
"job",
"configuration",
"."
] | bc1553188df97d3df825de6d826b34ab7185a431 | https://github.com/marcboeker/mongolicious/blob/bc1553188df97d3df825de6d826b34ab7185a431/lib/mongolicious/backup.rb#L26-L34 | train |
marcboeker/mongolicious | lib/mongolicious/backup.rb | Mongolicious.Backup.schedule_jobs | def schedule_jobs(jobs)
scheduler = Rufus::Scheduler.start_new
jobs.each do |job|
if job['cron']
Mongolicious.logger.info("Scheduled new job for #{job['db'].split('/').last} with cron: #{job['cron']}")
scheduler.cron job['cron'] do
backup(job)
end
else
scheduler.every job['interval'] do
Mongolicious.logger.info("Scheduled new job for #{job['db'].split('/').last} with interval: #{job['interval']}")
backup(job)
end
end
end
scheduler.join
end | ruby | def schedule_jobs(jobs)
scheduler = Rufus::Scheduler.start_new
jobs.each do |job|
if job['cron']
Mongolicious.logger.info("Scheduled new job for #{job['db'].split('/').last} with cron: #{job['cron']}")
scheduler.cron job['cron'] do
backup(job)
end
else
scheduler.every job['interval'] do
Mongolicious.logger.info("Scheduled new job for #{job['db'].split('/').last} with interval: #{job['interval']}")
backup(job)
end
end
end
scheduler.join
end | [
"def",
"schedule_jobs",
"(",
"jobs",
")",
"scheduler",
"=",
"Rufus",
"::",
"Scheduler",
".",
"start_new",
"jobs",
".",
"each",
"do",
"|",
"job",
"|",
"if",
"job",
"[",
"'cron'",
"]",
"Mongolicious",
".",
"logger",
".",
"info",
"(",
"\"Scheduled new job for #{job['db'].split('/').last} with cron: #{job['cron']}\"",
")",
"scheduler",
".",
"cron",
"job",
"[",
"'cron'",
"]",
"do",
"backup",
"(",
"job",
")",
"end",
"else",
"scheduler",
".",
"every",
"job",
"[",
"'interval'",
"]",
"do",
"Mongolicious",
".",
"logger",
".",
"info",
"(",
"\"Scheduled new job for #{job['db'].split('/').last} with interval: #{job['interval']}\"",
")",
"backup",
"(",
"job",
")",
"end",
"end",
"end",
"scheduler",
".",
"join",
"end"
] | Schedule the jobs to be executed in the given interval.
This method will block and keep running until it gets interrupted.
@param [Array] jobs the list of jobs to be scheduled.
@return [nil] | [
"Schedule",
"the",
"jobs",
"to",
"be",
"executed",
"in",
"the",
"given",
"interval",
"."
] | bc1553188df97d3df825de6d826b34ab7185a431 | https://github.com/marcboeker/mongolicious/blob/bc1553188df97d3df825de6d826b34ab7185a431/lib/mongolicious/backup.rb#L43-L61 | train |
kamui/kanpachi | lib/kanpachi/resource_list.rb | Kanpachi.ResourceList.add | def add(resource)
if @list.key? resource.route
raise DuplicateResource, "A resource accessible via #{resource.http_verb} #{resource.url} already exists"
end
@list[resource.route] = resource
end | ruby | def add(resource)
if @list.key? resource.route
raise DuplicateResource, "A resource accessible via #{resource.http_verb} #{resource.url} already exists"
end
@list[resource.route] = resource
end | [
"def",
"add",
"(",
"resource",
")",
"if",
"@list",
".",
"key?",
"resource",
".",
"route",
"raise",
"DuplicateResource",
",",
"\"A resource accessible via #{resource.http_verb} #{resource.url} already exists\"",
"end",
"@list",
"[",
"resource",
".",
"route",
"]",
"=",
"resource",
"end"
] | Add a resource to the list
@param [Kanpachi::Resource] The resource to add.
@return [Hash<Kanpachi::Resource>] All the added resources.
@raise DuplicateResource If a resource is being duplicated.
@api public | [
"Add",
"a",
"resource",
"to",
"the",
"list"
] | dbd09646bd8779ab874e1578b57a13f5747b0da7 | https://github.com/kamui/kanpachi/blob/dbd09646bd8779ab874e1578b57a13f5747b0da7/lib/kanpachi/resource_list.rb#L35-L40 | train |
kamui/kanpachi | lib/kanpachi/resource_list.rb | Kanpachi.ResourceList.named | def named(name)
resource = all.detect { |resource| resource.name == name }
if resource.nil?
raise UnknownResource, "Resource named #{name} doesn't exist"
else
resource
end
end | ruby | def named(name)
resource = all.detect { |resource| resource.name == name }
if resource.nil?
raise UnknownResource, "Resource named #{name} doesn't exist"
else
resource
end
end | [
"def",
"named",
"(",
"name",
")",
"resource",
"=",
"all",
".",
"detect",
"{",
"|",
"resource",
"|",
"resource",
".",
"name",
"==",
"name",
"}",
"if",
"resource",
".",
"nil?",
"raise",
"UnknownResource",
",",
"\"Resource named #{name} doesn't exist\"",
"else",
"resource",
"end",
"end"
] | Returns a resource based on its name
@param [String] name The name of the resource you are looking for.
@raise [UnknownResource] if a resource with the passed name isn't found.
@return [Kanpachi::Resource] The found resource.
@api public | [
"Returns",
"a",
"resource",
"based",
"on",
"its",
"name"
] | dbd09646bd8779ab874e1578b57a13f5747b0da7 | https://github.com/kamui/kanpachi/blob/dbd09646bd8779ab874e1578b57a13f5747b0da7/lib/kanpachi/resource_list.rb#L49-L56 | train |
crapooze/em-xmpp | lib/em-xmpp/cert_store.rb | EM::Xmpp.CertStore.trusted? | def trusted?(pem)
if cert = OpenSSL::X509::Certificate.new(pem) rescue nil
@store.verify(cert).tap do |trusted|
@store.add_cert(cert) if trusted rescue nil
end
end
end | ruby | def trusted?(pem)
if cert = OpenSSL::X509::Certificate.new(pem) rescue nil
@store.verify(cert).tap do |trusted|
@store.add_cert(cert) if trusted rescue nil
end
end
end | [
"def",
"trusted?",
"(",
"pem",
")",
"if",
"cert",
"=",
"OpenSSL",
"::",
"X509",
"::",
"Certificate",
".",
"new",
"(",
"pem",
")",
"rescue",
"nil",
"@store",
".",
"verify",
"(",
"cert",
")",
".",
"tap",
"do",
"|",
"trusted",
"|",
"@store",
".",
"add_cert",
"(",
"cert",
")",
"if",
"trusted",
"rescue",
"nil",
"end",
"end",
"end"
] | Return true if the certificate is signed by a CA certificate in the
store. If the certificate can be trusted, it's added to the store so
it can be used to trust other certs. | [
"Return",
"true",
"if",
"the",
"certificate",
"is",
"signed",
"by",
"a",
"CA",
"certificate",
"in",
"the",
"store",
".",
"If",
"the",
"certificate",
"can",
"be",
"trusted",
"it",
"s",
"added",
"to",
"the",
"store",
"so",
"it",
"can",
"be",
"used",
"to",
"trust",
"other",
"certs",
"."
] | 804e139944c88bc317b359754d5ad69b75f42319 | https://github.com/crapooze/em-xmpp/blob/804e139944c88bc317b359754d5ad69b75f42319/lib/em-xmpp/cert_store.rb#L44-L50 | train |
crapooze/em-xmpp | lib/em-xmpp/cert_store.rb | EM::Xmpp.CertStore.certs | def certs
unless @@certs
pattern = /-{5}BEGIN CERTIFICATE-{5}\n.*?-{5}END CERTIFICATE-{5}\n/m
dir = @cert_directory
certs = Dir[File.join(dir, '*.crt')].map {|f| File.read(f) }
certs = certs.map {|c| c.scan(pattern) }.flatten
certs.map! {|c| OpenSSL::X509::Certificate.new(c) }
@@certs = certs.reject {|c| c.not_after < Time.now }
end
@@certs
end | ruby | def certs
unless @@certs
pattern = /-{5}BEGIN CERTIFICATE-{5}\n.*?-{5}END CERTIFICATE-{5}\n/m
dir = @cert_directory
certs = Dir[File.join(dir, '*.crt')].map {|f| File.read(f) }
certs = certs.map {|c| c.scan(pattern) }.flatten
certs.map! {|c| OpenSSL::X509::Certificate.new(c) }
@@certs = certs.reject {|c| c.not_after < Time.now }
end
@@certs
end | [
"def",
"certs",
"unless",
"@@certs",
"pattern",
"=",
"/",
"\\n",
"\\n",
"/m",
"dir",
"=",
"@cert_directory",
"certs",
"=",
"Dir",
"[",
"File",
".",
"join",
"(",
"dir",
",",
"'*.crt'",
")",
"]",
".",
"map",
"{",
"|",
"f",
"|",
"File",
".",
"read",
"(",
"f",
")",
"}",
"certs",
"=",
"certs",
".",
"map",
"{",
"|",
"c",
"|",
"c",
".",
"scan",
"(",
"pattern",
")",
"}",
".",
"flatten",
"certs",
".",
"map!",
"{",
"|",
"c",
"|",
"OpenSSL",
"::",
"X509",
"::",
"Certificate",
".",
"new",
"(",
"c",
")",
"}",
"@@certs",
"=",
"certs",
".",
"reject",
"{",
"|",
"c",
"|",
"c",
".",
"not_after",
"<",
"Time",
".",
"now",
"}",
"end",
"@@certs",
"end"
] | Return the trusted root CA certificates installed in the @cert_directory. These
certificates are used to start the trust chain needed to validate certs
we receive from clients and servers. | [
"Return",
"the",
"trusted",
"root",
"CA",
"certificates",
"installed",
"in",
"the"
] | 804e139944c88bc317b359754d5ad69b75f42319 | https://github.com/crapooze/em-xmpp/blob/804e139944c88bc317b359754d5ad69b75f42319/lib/em-xmpp/cert_store.rb#L64-L74 | train |
thriventures/storage_room_gem | lib/storage_room/embeddeds/image.rb | StorageRoom.Image.url | def url(name = nil)
if name
if version_identifiers.include?(name.to_s)
self[:@versions][name.to_s][:@url]
else
raise "Invalid Image Version identifier: '#{name}' (must be #{version_identifiers.join(', ')})"
end
else
self[:@url]
end
end | ruby | def url(name = nil)
if name
if version_identifiers.include?(name.to_s)
self[:@versions][name.to_s][:@url]
else
raise "Invalid Image Version identifier: '#{name}' (must be #{version_identifiers.join(', ')})"
end
else
self[:@url]
end
end | [
"def",
"url",
"(",
"name",
"=",
"nil",
")",
"if",
"name",
"if",
"version_identifiers",
".",
"include?",
"(",
"name",
".",
"to_s",
")",
"self",
"[",
":@versions",
"]",
"[",
"name",
".",
"to_s",
"]",
"[",
":@url",
"]",
"else",
"raise",
"\"Invalid Image Version identifier: '#{name}' (must be #{version_identifiers.join(', ')})\"",
"end",
"else",
"self",
"[",
":@url",
"]",
"end",
"end"
] | Returns the URL of an Image or the URL of a version if a string or symbol is passed | [
"Returns",
"the",
"URL",
"of",
"an",
"Image",
"or",
"the",
"URL",
"of",
"a",
"version",
"if",
"a",
"string",
"or",
"symbol",
"is",
"passed"
] | cadf132b865ff82f7b09fadfec1d294a714c6728 | https://github.com/thriventures/storage_room_gem/blob/cadf132b865ff82f7b09fadfec1d294a714c6728/lib/storage_room/embeddeds/image.rb#L10-L20 | train |
Aethelflaed/iord | lib/iord/fields.rb | Iord.Fields.field_attribute | def field_attribute(attr)
return 'id' if attr == :_id
# default, simply return name
return attr unless attr.is_a? Hash
# else, Hash
return attr[:object] if attr.has_key? :object
return attr[:array] if attr.has_key? :array
return attr[:value] if attr.has_key? :value
return attr[:link] if attr.has_key? :link
attr.keys[0]
end | ruby | def field_attribute(attr)
return 'id' if attr == :_id
# default, simply return name
return attr unless attr.is_a? Hash
# else, Hash
return attr[:object] if attr.has_key? :object
return attr[:array] if attr.has_key? :array
return attr[:value] if attr.has_key? :value
return attr[:link] if attr.has_key? :link
attr.keys[0]
end | [
"def",
"field_attribute",
"(",
"attr",
")",
"return",
"'id'",
"if",
"attr",
"==",
":_id",
"# default, simply return name",
"return",
"attr",
"unless",
"attr",
".",
"is_a?",
"Hash",
"# else, Hash",
"return",
"attr",
"[",
":object",
"]",
"if",
"attr",
".",
"has_key?",
":object",
"return",
"attr",
"[",
":array",
"]",
"if",
"attr",
".",
"has_key?",
":array",
"return",
"attr",
"[",
":value",
"]",
"if",
"attr",
".",
"has_key?",
":value",
"return",
"attr",
"[",
":link",
"]",
"if",
"attr",
".",
"has_key?",
":link",
"attr",
".",
"keys",
"[",
"0",
"]",
"end"
] | Use for sort_if_enabled which requires the attribute name | [
"Use",
"for",
"sort_if_enabled",
"which",
"requires",
"the",
"attribute",
"name"
] | 5f7d5c1ddb91b6ed7f5db90f9420566477b1268a | https://github.com/Aethelflaed/iord/blob/5f7d5c1ddb91b6ed7f5db90f9420566477b1268a/lib/iord/fields.rb#L22-L33 | train |
webdestroya/ffaker-taxonomy | lib/ffaker/taxonomy.rb | Faker.Taxonomy.lookup | def lookup(code)
TAXONOMY.select {|t| t.code.eql?(code) }.first
end | ruby | def lookup(code)
TAXONOMY.select {|t| t.code.eql?(code) }.first
end | [
"def",
"lookup",
"(",
"code",
")",
"TAXONOMY",
".",
"select",
"{",
"|",
"t",
"|",
"t",
".",
"code",
".",
"eql?",
"(",
"code",
")",
"}",
".",
"first",
"end"
] | Use this method if you have a taxonomy code and need to lookup the
information about that code | [
"Use",
"this",
"method",
"if",
"you",
"have",
"a",
"taxonomy",
"code",
"and",
"need",
"to",
"lookup",
"the",
"information",
"about",
"that",
"code"
] | 272f8cbcf4604d504f5f8e28d033b17f6c57bade | https://github.com/webdestroya/ffaker-taxonomy/blob/272f8cbcf4604d504f5f8e28d033b17f6c57bade/lib/ffaker/taxonomy.rb#L24-L26 | train |
kamui/kanpachi | lib/kanpachi/error_list.rb | Kanpachi.ErrorList.add | def add(error)
if @list.key? error.name
raise DuplicateError, "An error named #{error.name} already exists"
end
@list[error.name] = error
end | ruby | def add(error)
if @list.key? error.name
raise DuplicateError, "An error named #{error.name} already exists"
end
@list[error.name] = error
end | [
"def",
"add",
"(",
"error",
")",
"if",
"@list",
".",
"key?",
"error",
".",
"name",
"raise",
"DuplicateError",
",",
"\"An error named #{error.name} already exists\"",
"end",
"@list",
"[",
"error",
".",
"name",
"]",
"=",
"error",
"end"
] | Add a error to the list
@param [Kanpachi::Error] error The error to add.
@return [Hash<Kanpachi::Error>] All the added errors.
@raise DuplicateError If a error is being duplicated.
@api public | [
"Add",
"a",
"error",
"to",
"the",
"list"
] | dbd09646bd8779ab874e1578b57a13f5747b0da7 | https://github.com/kamui/kanpachi/blob/dbd09646bd8779ab874e1578b57a13f5747b0da7/lib/kanpachi/error_list.rb#L34-L39 | train |
onurkucukkece/lotto | lib/lotto/draw.rb | Lotto.Draw.draw | def draw
drawns = []
@options[:include].each { |n| drawns << n } unless @options[:include].nil?
count = @options[:include] ? @options[:pick] - @options[:include].count : @options[:pick]
count.times { drawns << pick(drawns) }
drawns
end | ruby | def draw
drawns = []
@options[:include].each { |n| drawns << n } unless @options[:include].nil?
count = @options[:include] ? @options[:pick] - @options[:include].count : @options[:pick]
count.times { drawns << pick(drawns) }
drawns
end | [
"def",
"draw",
"drawns",
"=",
"[",
"]",
"@options",
"[",
":include",
"]",
".",
"each",
"{",
"|",
"n",
"|",
"drawns",
"<<",
"n",
"}",
"unless",
"@options",
"[",
":include",
"]",
".",
"nil?",
"count",
"=",
"@options",
"[",
":include",
"]",
"?",
"@options",
"[",
":pick",
"]",
"-",
"@options",
"[",
":include",
"]",
".",
"count",
":",
"@options",
"[",
":pick",
"]",
"count",
".",
"times",
"{",
"drawns",
"<<",
"pick",
"(",
"drawns",
")",
"}",
"drawns",
"end"
] | Returns a set of drawn numbers | [
"Returns",
"a",
"set",
"of",
"drawn",
"numbers"
] | c4236ac13c3a5b894a65d7e2fb90645e961f24c3 | https://github.com/onurkucukkece/lotto/blob/c4236ac13c3a5b894a65d7e2fb90645e961f24c3/lib/lotto/draw.rb#L12-L18 | train |
onurkucukkece/lotto | lib/lotto/draw.rb | Lotto.Draw.basket | def basket
numbers = (1..@options[:of])
numbers = numbers.reject { |n| @options[:include].include? n } unless @options[:include].nil?
numbers = numbers.reject { |n| @options[:exclude].include? n } unless @options[:exclude].nil?
numbers
end | ruby | def basket
numbers = (1..@options[:of])
numbers = numbers.reject { |n| @options[:include].include? n } unless @options[:include].nil?
numbers = numbers.reject { |n| @options[:exclude].include? n } unless @options[:exclude].nil?
numbers
end | [
"def",
"basket",
"numbers",
"=",
"(",
"1",
"..",
"@options",
"[",
":of",
"]",
")",
"numbers",
"=",
"numbers",
".",
"reject",
"{",
"|",
"n",
"|",
"@options",
"[",
":include",
"]",
".",
"include?",
"n",
"}",
"unless",
"@options",
"[",
":include",
"]",
".",
"nil?",
"numbers",
"=",
"numbers",
".",
"reject",
"{",
"|",
"n",
"|",
"@options",
"[",
":exclude",
"]",
".",
"include?",
"n",
"}",
"unless",
"@options",
"[",
":exclude",
"]",
".",
"nil?",
"numbers",
"end"
] | Returns the basket with numbers | [
"Returns",
"the",
"basket",
"with",
"numbers"
] | c4236ac13c3a5b894a65d7e2fb90645e961f24c3 | https://github.com/onurkucukkece/lotto/blob/c4236ac13c3a5b894a65d7e2fb90645e961f24c3/lib/lotto/draw.rb#L33-L38 | train |
checkdin/checkdin-ruby | lib/checkdin/activities.rb | Checkdin.Activities.activities | def activities(options={})
response = connection.get do |req|
req.url "activities", options
end
return_error_or_body(response)
end | ruby | def activities(options={})
response = connection.get do |req|
req.url "activities", options
end
return_error_or_body(response)
end | [
"def",
"activities",
"(",
"options",
"=",
"{",
"}",
")",
"response",
"=",
"connection",
".",
"get",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"\"activities\"",
",",
"options",
"end",
"return_error_or_body",
"(",
"response",
")",
"end"
] | Get a list of all activities for the authenticating client.
@param [Hash] options
@option options Integer :campaign_id - Only return won rewards for this campaign.
@option options String :classification - Only return activities for users in this classification.
@option options Integer :user_id - Only return won rewards for this user.
@option options Integer :since - Only fetch updates since this time (UNIX timestamp)
@option options Integer :limit - The maximum number of records to return. | [
"Get",
"a",
"list",
"of",
"all",
"activities",
"for",
"the",
"authenticating",
"client",
"."
] | c3c4b38b0f8c710e1f805100dcf3a70649215b48 | https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/activities.rb#L22-L27 | train |
henvo/digistore24 | lib/digistore24/notification.rb | Digistore24.Notification.signature | def signature
# Remove 'sha_sign' key from request params and concatenate all
# key value pairs
params = payload.to_h
.reject { |key, value| key == :sha_sign }
.reject { |key, value| value == '' || value == false }.sort
.map { | key, value| "#{key}=#{value}#{passphrase}" }.join
# Calculate SHA512 and upcase all letters, since Digistore will
# also return upcased letters in the signature.
Digest::SHA512.hexdigest(params).upcase
end | ruby | def signature
# Remove 'sha_sign' key from request params and concatenate all
# key value pairs
params = payload.to_h
.reject { |key, value| key == :sha_sign }
.reject { |key, value| value == '' || value == false }.sort
.map { | key, value| "#{key}=#{value}#{passphrase}" }.join
# Calculate SHA512 and upcase all letters, since Digistore will
# also return upcased letters in the signature.
Digest::SHA512.hexdigest(params).upcase
end | [
"def",
"signature",
"# Remove 'sha_sign' key from request params and concatenate all",
"# key value pairs",
"params",
"=",
"payload",
".",
"to_h",
".",
"reject",
"{",
"|",
"key",
",",
"value",
"|",
"key",
"==",
":sha_sign",
"}",
".",
"reject",
"{",
"|",
"key",
",",
"value",
"|",
"value",
"==",
"''",
"||",
"value",
"==",
"false",
"}",
".",
"sort",
".",
"map",
"{",
"|",
"key",
",",
"value",
"|",
"\"#{key}=#{value}#{passphrase}\"",
"}",
".",
"join",
"# Calculate SHA512 and upcase all letters, since Digistore will",
"# also return upcased letters in the signature.",
"Digest",
"::",
"SHA512",
".",
"hexdigest",
"(",
"params",
")",
".",
"upcase",
"end"
] | Initialize the notification.
@param params [Hash] The request parameters from Digistore24.
@return [Notification]
Calculate SHA512 signature for payload.
@return [String] The signature. | [
"Initialize",
"the",
"notification",
"."
] | f9e43665f61af3f36e72807eda12562b9befac86 | https://github.com/henvo/digistore24/blob/f9e43665f61af3f36e72807eda12562b9befac86/lib/digistore24/notification.rb#L25-L36 | train |
jeremyz/edoors-ruby | lib/edoors/board.rb | Edoors.Board.process_p | def process_p p
@viewer.receive_p p if @viewer
if p.action!=Edoors::ACT_ERROR and p.action!=Edoors::ACT_PASS_THROUGH
p2 = @postponed[p.link_value] ||= p
return if p2==p
@postponed.delete p.link_value
p,p2 = p2,p if p.action==Edoors::ACT_FOLLOW
p.merge! p2
end
@saved = p
receive_p p
_garbage if not @saved.nil?
end | ruby | def process_p p
@viewer.receive_p p if @viewer
if p.action!=Edoors::ACT_ERROR and p.action!=Edoors::ACT_PASS_THROUGH
p2 = @postponed[p.link_value] ||= p
return if p2==p
@postponed.delete p.link_value
p,p2 = p2,p if p.action==Edoors::ACT_FOLLOW
p.merge! p2
end
@saved = p
receive_p p
_garbage if not @saved.nil?
end | [
"def",
"process_p",
"p",
"@viewer",
".",
"receive_p",
"p",
"if",
"@viewer",
"if",
"p",
".",
"action!",
"=",
"Edoors",
"::",
"ACT_ERROR",
"and",
"p",
".",
"action!",
"=",
"Edoors",
"::",
"ACT_PASS_THROUGH",
"p2",
"=",
"@postponed",
"[",
"p",
".",
"link_value",
"]",
"||=",
"p",
"return",
"if",
"p2",
"==",
"p",
"@postponed",
".",
"delete",
"p",
".",
"link_value",
"p",
",",
"p2",
"=",
"p2",
",",
"p",
"if",
"p",
".",
"action",
"==",
"Edoors",
"::",
"ACT_FOLLOW",
"p",
".",
"merge!",
"p2",
"end",
"@saved",
"=",
"p",
"receive_p",
"p",
"_garbage",
"if",
"not",
"@saved",
".",
"nil?",
"end"
] | process the given particle then forward it to user code
@param [Particle] p the Particle to be processed | [
"process",
"the",
"given",
"particle",
"then",
"forward",
"it",
"to",
"user",
"code"
] | 4f065f63125907b3a4f72fbab8722c58ccab41c1 | https://github.com/jeremyz/edoors-ruby/blob/4f065f63125907b3a4f72fbab8722c58ccab41c1/lib/edoors/board.rb#L71-L83 | train |
tdg5/tco_method | lib/tco_method/block_extractor.rb | TCOMethod.BlockExtractor.determine_offsets | def determine_offsets(block, source)
tokens = Ripper.lex(source)
start_offset, start_token = determine_start_offset(block, tokens)
expected_match = start_token == :on_kw ? :on_kw : :on_rbrace
end_offset = determine_end_offset(block, tokens, source, expected_match)
[start_offset, end_offset]
end | ruby | def determine_offsets(block, source)
tokens = Ripper.lex(source)
start_offset, start_token = determine_start_offset(block, tokens)
expected_match = start_token == :on_kw ? :on_kw : :on_rbrace
end_offset = determine_end_offset(block, tokens, source, expected_match)
[start_offset, end_offset]
end | [
"def",
"determine_offsets",
"(",
"block",
",",
"source",
")",
"tokens",
"=",
"Ripper",
".",
"lex",
"(",
"source",
")",
"start_offset",
",",
"start_token",
"=",
"determine_start_offset",
"(",
"block",
",",
"tokens",
")",
"expected_match",
"=",
"start_token",
"==",
":on_kw",
"?",
":on_kw",
":",
":on_rbrace",
"end_offset",
"=",
"determine_end_offset",
"(",
"block",
",",
"tokens",
",",
"source",
",",
"expected_match",
")",
"[",
"start_offset",
",",
"end_offset",
"]",
"end"
] | Tokenizes the source of the block as determined by the `method_source` gem
and determines the beginning and end of the block.
In both cases the entire line is checked to ensure there's no unexpected
ambiguity as to the start or end of the block. See the test file for this
class for examples of ambiguous situations.
@param [Proc] block The proc for which the starting offset of its source
code should be determined.
@param [String] source The source code of the provided block.
@raise [AmbiguousSourceError] Raised when the source of the block cannot
be determined unambiguously.
@return [Array<Integer>] The start and end offsets of the block's source
code as 2-element Array. | [
"Tokenizes",
"the",
"source",
"of",
"the",
"block",
"as",
"determined",
"by",
"the",
"method_source",
"gem",
"and",
"determines",
"the",
"beginning",
"and",
"end",
"of",
"the",
"block",
"."
] | fc89b884b68ce2a4bc58abb22270b1f7685efbe9 | https://github.com/tdg5/tco_method/blob/fc89b884b68ce2a4bc58abb22270b1f7685efbe9/lib/tco_method/block_extractor.rb#L71-L77 | train |
anga/extend_at | lib/extend_at.rb | ExtendModelAt.Extention.method_missing | def method_missing(m, *args, &block)
column_name = m.to_s.gsub(/\=$/, '')
raise ExtendModelAt::InvalidColumn, "#{column_name} not exist" if @static == true and not (@columns.try(:keys).try(:include?, column_name.to_sym) )
# If the method don't finish with "=" is fore read
if m !~ /\=$/
self[m.to_s]
# but if finish with "=" is for wirte
else
self[column_name.to_s] = args.first
end
end | ruby | def method_missing(m, *args, &block)
column_name = m.to_s.gsub(/\=$/, '')
raise ExtendModelAt::InvalidColumn, "#{column_name} not exist" if @static == true and not (@columns.try(:keys).try(:include?, column_name.to_sym) )
# If the method don't finish with "=" is fore read
if m !~ /\=$/
self[m.to_s]
# but if finish with "=" is for wirte
else
self[column_name.to_s] = args.first
end
end | [
"def",
"method_missing",
"(",
"m",
",",
"*",
"args",
",",
"&",
"block",
")",
"column_name",
"=",
"m",
".",
"to_s",
".",
"gsub",
"(",
"/",
"\\=",
"/",
",",
"''",
")",
"raise",
"ExtendModelAt",
"::",
"InvalidColumn",
",",
"\"#{column_name} not exist\"",
"if",
"@static",
"==",
"true",
"and",
"not",
"(",
"@columns",
".",
"try",
"(",
":keys",
")",
".",
"try",
"(",
":include?",
",",
"column_name",
".",
"to_sym",
")",
")",
"# If the method don't finish with \"=\" is fore read",
"if",
"m",
"!~",
"/",
"\\=",
"/",
"self",
"[",
"m",
".",
"to_s",
"]",
"# but if finish with \"=\" is for wirte",
"else",
"self",
"[",
"column_name",
".",
"to_s",
"]",
"=",
"args",
".",
"first",
"end",
"end"
] | Use the undefined method as a column | [
"Use",
"the",
"undefined",
"method",
"as",
"a",
"column"
] | db77cf981108b401af0d92a8d7b1008317d9a17d | https://github.com/anga/extend_at/blob/db77cf981108b401af0d92a8d7b1008317d9a17d/lib/extend_at.rb#L462-L472 | train |
anga/extend_at | lib/extend_at.rb | ExtendModelAt.Extention.get_adapter | def get_adapter(column, value)
if @columns[column.to_sym][:type] == String
return :to_s
elsif @columns[column.to_sym][:type] == Fixnum
return :to_i if value.respond_to? :to_i
elsif @columns[column.to_sym][:type] == Float
return :to_f if value.respond_to? :to_f
elsif @columns[column.to_sym][:type] == Time
return :to_time if value.respond_to? :to_time
elsif @columns[column.to_sym][:type] == Date
return :to_date if value.respond_to? :to_date
end
nil
end | ruby | def get_adapter(column, value)
if @columns[column.to_sym][:type] == String
return :to_s
elsif @columns[column.to_sym][:type] == Fixnum
return :to_i if value.respond_to? :to_i
elsif @columns[column.to_sym][:type] == Float
return :to_f if value.respond_to? :to_f
elsif @columns[column.to_sym][:type] == Time
return :to_time if value.respond_to? :to_time
elsif @columns[column.to_sym][:type] == Date
return :to_date if value.respond_to? :to_date
end
nil
end | [
"def",
"get_adapter",
"(",
"column",
",",
"value",
")",
"if",
"@columns",
"[",
"column",
".",
"to_sym",
"]",
"[",
":type",
"]",
"==",
"String",
"return",
":to_s",
"elsif",
"@columns",
"[",
"column",
".",
"to_sym",
"]",
"[",
":type",
"]",
"==",
"Fixnum",
"return",
":to_i",
"if",
"value",
".",
"respond_to?",
":to_i",
"elsif",
"@columns",
"[",
"column",
".",
"to_sym",
"]",
"[",
":type",
"]",
"==",
"Float",
"return",
":to_f",
"if",
"value",
".",
"respond_to?",
":to_f",
"elsif",
"@columns",
"[",
"column",
".",
"to_sym",
"]",
"[",
":type",
"]",
"==",
"Time",
"return",
":to_time",
"if",
"value",
".",
"respond_to?",
":to_time",
"elsif",
"@columns",
"[",
"column",
".",
"to_sym",
"]",
"[",
":type",
"]",
"==",
"Date",
"return",
":to_date",
"if",
"value",
".",
"respond_to?",
":to_date",
"end",
"nil",
"end"
] | Meta functions
Return the correct method used to transform the column value the correct Ruby class | [
"Meta",
"functions",
"Return",
"the",
"correct",
"method",
"used",
"to",
"transform",
"the",
"column",
"value",
"the",
"correct",
"Ruby",
"class"
] | db77cf981108b401af0d92a8d7b1008317d9a17d | https://github.com/anga/extend_at/blob/db77cf981108b401af0d92a8d7b1008317d9a17d/lib/extend_at.rb#L567-L580 | train |
anga/extend_at | lib/extend_at.rb | ExtendModelAt.Extention.get_defaults_values | def get_defaults_values(options = {})
defaults_ = {}
options[:columns].each do |column, config|
defaults_[column.to_s] = @columns[column.to_sym][:default] || nil
end
defaults_
end | ruby | def get_defaults_values(options = {})
defaults_ = {}
options[:columns].each do |column, config|
defaults_[column.to_s] = @columns[column.to_sym][:default] || nil
end
defaults_
end | [
"def",
"get_defaults_values",
"(",
"options",
"=",
"{",
"}",
")",
"defaults_",
"=",
"{",
"}",
"options",
"[",
":columns",
"]",
".",
"each",
"do",
"|",
"column",
",",
"config",
"|",
"defaults_",
"[",
"column",
".",
"to_s",
"]",
"=",
"@columns",
"[",
"column",
".",
"to_sym",
"]",
"[",
":default",
"]",
"||",
"nil",
"end",
"defaults_",
"end"
] | Get all default values | [
"Get",
"all",
"default",
"values"
] | db77cf981108b401af0d92a8d7b1008317d9a17d | https://github.com/anga/extend_at/blob/db77cf981108b401af0d92a8d7b1008317d9a17d/lib/extend_at.rb#L594-L600 | train |
checkdin/checkdin-ruby | lib/checkdin/point_account_entries.rb | Checkdin.PointAccountEntries.point_account_entries | def point_account_entries(options={})
response = connection.get do |req|
req.url "point_account_entries", options
end
return_error_or_body(response)
end | ruby | def point_account_entries(options={})
response = connection.get do |req|
req.url "point_account_entries", options
end
return_error_or_body(response)
end | [
"def",
"point_account_entries",
"(",
"options",
"=",
"{",
"}",
")",
"response",
"=",
"connection",
".",
"get",
"do",
"|",
"req",
"|",
"req",
".",
"url",
"\"point_account_entries\"",
",",
"options",
"end",
"return_error_or_body",
"(",
"response",
")",
"end"
] | Get a list of point account entries.
@param [Hash] options
@option options Integer :user_id - Return entries only for this user
@option options Integer :campaign_id - Return entries only for this campaign
@option options Integer :point_account_id - Return entries only for this point account.
@option options Integer :limit - The maximum number of records to return. | [
"Get",
"a",
"list",
"of",
"point",
"account",
"entries",
"."
] | c3c4b38b0f8c710e1f805100dcf3a70649215b48 | https://github.com/checkdin/checkdin-ruby/blob/c3c4b38b0f8c710e1f805100dcf3a70649215b48/lib/checkdin/point_account_entries.rb#L12-L17 | train |
bogrobotten/fetch | lib/fetch/request.rb | Fetch.Request.process! | def process!(body, url, effective_url)
before_process!
body = parse!(body)
@process_callback.call(body, url, effective_url) if @process_callback
after_process!
rescue => e
error!(e)
end | ruby | def process!(body, url, effective_url)
before_process!
body = parse!(body)
@process_callback.call(body, url, effective_url) if @process_callback
after_process!
rescue => e
error!(e)
end | [
"def",
"process!",
"(",
"body",
",",
"url",
",",
"effective_url",
")",
"before_process!",
"body",
"=",
"parse!",
"(",
"body",
")",
"@process_callback",
".",
"call",
"(",
"body",
",",
"url",
",",
"effective_url",
")",
"if",
"@process_callback",
"after_process!",
"rescue",
"=>",
"e",
"error!",
"(",
"e",
")",
"end"
] | Runs the process callback. If it fails with an exception, it will send
the exception to the error callback. | [
"Runs",
"the",
"process",
"callback",
".",
"If",
"it",
"fails",
"with",
"an",
"exception",
"it",
"will",
"send",
"the",
"exception",
"to",
"the",
"error",
"callback",
"."
] | 8a9e1fb42ed0719dd7b4d1a965d11b0f5decca4f | https://github.com/bogrobotten/fetch/blob/8a9e1fb42ed0719dd7b4d1a965d11b0f5decca4f/lib/fetch/request.rb#L123-L130 | train |
groupdocs-signature-cloud/groupdocs-signature-cloud-ruby | lib/groupdocs_signature_cloud/api/signature_api.rb | GroupDocsSignatureCloud.SignatureApi.get_qr_codes_with_http_info | def get_qr_codes_with_http_info()
@api_client.config.logger.debug 'Calling API: SignatureApi.get_qr_codes ...' if @api_client.config.debugging
# resource path
local_var_path = '/signature/qrcodes'
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml'])
# form parameters
form_params = {}
# http body (model)
post_body = nil
data, status_code, headers = @api_client.call_api(:GET, local_var_path,
header_params: header_params,
query_params: query_params,
form_params: form_params,
body: post_body,
access_token: get_access_token,
return_type: 'QRCodeCollection')
if @api_client.config.debugging
@api_client.config.logger.debug "API called:
SignatureApi#get_qr_codes\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
[data, status_code, headers]
end | ruby | def get_qr_codes_with_http_info()
@api_client.config.logger.debug 'Calling API: SignatureApi.get_qr_codes ...' if @api_client.config.debugging
# resource path
local_var_path = '/signature/qrcodes'
# query parameters
query_params = {}
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml'])
# form parameters
form_params = {}
# http body (model)
post_body = nil
data, status_code, headers = @api_client.call_api(:GET, local_var_path,
header_params: header_params,
query_params: query_params,
form_params: form_params,
body: post_body,
access_token: get_access_token,
return_type: 'QRCodeCollection')
if @api_client.config.debugging
@api_client.config.logger.debug "API called:
SignatureApi#get_qr_codes\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
[data, status_code, headers]
end | [
"def",
"get_qr_codes_with_http_info",
"(",
")",
"@api_client",
".",
"config",
".",
"logger",
".",
"debug",
"'Calling API: SignatureApi.get_qr_codes ...'",
"if",
"@api_client",
".",
"config",
".",
"debugging",
"# resource path",
"local_var_path",
"=",
"'/signature/qrcodes'",
"# query parameters",
"query_params",
"=",
"{",
"}",
"# header parameters",
"header_params",
"=",
"{",
"}",
"# HTTP header 'Accept' (if needed)",
"header_params",
"[",
"'Accept'",
"]",
"=",
"@api_client",
".",
"select_header_accept",
"(",
"[",
"'application/json'",
",",
"'application/xml'",
"]",
")",
"# HTTP header 'Content-Type'",
"header_params",
"[",
"'Content-Type'",
"]",
"=",
"@api_client",
".",
"select_header_content_type",
"(",
"[",
"'application/json'",
",",
"'application/xml'",
"]",
")",
"# form parameters",
"form_params",
"=",
"{",
"}",
"# http body (model)",
"post_body",
"=",
"nil",
"data",
",",
"status_code",
",",
"headers",
"=",
"@api_client",
".",
"call_api",
"(",
":GET",
",",
"local_var_path",
",",
"header_params",
":",
"header_params",
",",
"query_params",
":",
"query_params",
",",
"form_params",
":",
"form_params",
",",
"body",
":",
"post_body",
",",
"access_token",
":",
"get_access_token",
",",
"return_type",
":",
"'QRCodeCollection'",
")",
"if",
"@api_client",
".",
"config",
".",
"debugging",
"@api_client",
".",
"config",
".",
"logger",
".",
"debug",
"\"API called:\n SignatureApi#get_qr_codes\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"",
"end",
"[",
"data",
",",
"status_code",
",",
"headers",
"]",
"end"
] | Retrieves list of supported QR-Code type names.
@return [Array<(QRCodeCollection, Fixnum, Hash)>]
QRCodeCollection data, response status code and response headers | [
"Retrieves",
"list",
"of",
"supported",
"QR",
"-",
"Code",
"type",
"names",
"."
] | d16e6f4bdd6cb9196d4e28ef3fc2123da94f0ef0 | https://github.com/groupdocs-signature-cloud/groupdocs-signature-cloud-ruby/blob/d16e6f4bdd6cb9196d4e28ef3fc2123da94f0ef0/lib/groupdocs_signature_cloud/api/signature_api.rb#L265-L299 | train |
groupdocs-signature-cloud/groupdocs-signature-cloud-ruby | lib/groupdocs_signature_cloud/api/signature_api.rb | GroupDocsSignatureCloud.SignatureApi.post_verification_collection_with_http_info | def post_verification_collection_with_http_info(request)
raise ArgumentError, 'Incorrect request type' unless request.is_a? PostVerificationCollectionRequest
@api_client.config.logger.debug 'Calling API: SignatureApi.post_verification_collection ...' if @api_client.config.debugging
# verify the required parameter 'name' is set
raise ArgumentError, 'Missing the required parameter name when calling SignatureApi.post_verification_collection' if @api_client.config.client_side_validation && request.name.nil?
# resource path
local_var_path = '/signature/{name}/collection/verification'
local_var_path = local_var_path.sub('{' + downcase_first_letter('Name') + '}', request.name.to_s)
# query parameters
query_params = {}
if local_var_path.include? ('{' + downcase_first_letter('Password') + '}')
local_var_path = local_var_path.sub('{' + downcase_first_letter('Password') + '}', request.password.to_s)
else
query_params[downcase_first_letter('Password')] = request.password unless request.password.nil?
end
if local_var_path.include? ('{' + downcase_first_letter('Folder') + '}')
local_var_path = local_var_path.sub('{' + downcase_first_letter('Folder') + '}', request.folder.to_s)
else
query_params[downcase_first_letter('Folder')] = request.folder unless request.folder.nil?
end
if local_var_path.include? ('{' + downcase_first_letter('Storage') + '}')
local_var_path = local_var_path.sub('{' + downcase_first_letter('Storage') + '}', request.storage.to_s)
else
query_params[downcase_first_letter('Storage')] = request.storage unless request.storage.nil?
end
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml'])
# form parameters
form_params = {}
# http body (model)
post_body = @api_client.object_to_http_body(request.verify_options_collection_data)
data, status_code, headers = @api_client.call_api(:POST, local_var_path,
header_params: header_params,
query_params: query_params,
form_params: form_params,
body: post_body,
access_token: get_access_token,
return_type: 'VerifiedDocumentResponse')
if @api_client.config.debugging
@api_client.config.logger.debug "API called:
SignatureApi#post_verification_collection\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
[data, status_code, headers]
end | ruby | def post_verification_collection_with_http_info(request)
raise ArgumentError, 'Incorrect request type' unless request.is_a? PostVerificationCollectionRequest
@api_client.config.logger.debug 'Calling API: SignatureApi.post_verification_collection ...' if @api_client.config.debugging
# verify the required parameter 'name' is set
raise ArgumentError, 'Missing the required parameter name when calling SignatureApi.post_verification_collection' if @api_client.config.client_side_validation && request.name.nil?
# resource path
local_var_path = '/signature/{name}/collection/verification'
local_var_path = local_var_path.sub('{' + downcase_first_letter('Name') + '}', request.name.to_s)
# query parameters
query_params = {}
if local_var_path.include? ('{' + downcase_first_letter('Password') + '}')
local_var_path = local_var_path.sub('{' + downcase_first_letter('Password') + '}', request.password.to_s)
else
query_params[downcase_first_letter('Password')] = request.password unless request.password.nil?
end
if local_var_path.include? ('{' + downcase_first_letter('Folder') + '}')
local_var_path = local_var_path.sub('{' + downcase_first_letter('Folder') + '}', request.folder.to_s)
else
query_params[downcase_first_letter('Folder')] = request.folder unless request.folder.nil?
end
if local_var_path.include? ('{' + downcase_first_letter('Storage') + '}')
local_var_path = local_var_path.sub('{' + downcase_first_letter('Storage') + '}', request.storage.to_s)
else
query_params[downcase_first_letter('Storage')] = request.storage unless request.storage.nil?
end
# header parameters
header_params = {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml'])
# form parameters
form_params = {}
# http body (model)
post_body = @api_client.object_to_http_body(request.verify_options_collection_data)
data, status_code, headers = @api_client.call_api(:POST, local_var_path,
header_params: header_params,
query_params: query_params,
form_params: form_params,
body: post_body,
access_token: get_access_token,
return_type: 'VerifiedDocumentResponse')
if @api_client.config.debugging
@api_client.config.logger.debug "API called:
SignatureApi#post_verification_collection\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
[data, status_code, headers]
end | [
"def",
"post_verification_collection_with_http_info",
"(",
"request",
")",
"raise",
"ArgumentError",
",",
"'Incorrect request type'",
"unless",
"request",
".",
"is_a?",
"PostVerificationCollectionRequest",
"@api_client",
".",
"config",
".",
"logger",
".",
"debug",
"'Calling API: SignatureApi.post_verification_collection ...'",
"if",
"@api_client",
".",
"config",
".",
"debugging",
"# verify the required parameter 'name' is set",
"raise",
"ArgumentError",
",",
"'Missing the required parameter name when calling SignatureApi.post_verification_collection'",
"if",
"@api_client",
".",
"config",
".",
"client_side_validation",
"&&",
"request",
".",
"name",
".",
"nil?",
"# resource path",
"local_var_path",
"=",
"'/signature/{name}/collection/verification'",
"local_var_path",
"=",
"local_var_path",
".",
"sub",
"(",
"'{'",
"+",
"downcase_first_letter",
"(",
"'Name'",
")",
"+",
"'}'",
",",
"request",
".",
"name",
".",
"to_s",
")",
"# query parameters",
"query_params",
"=",
"{",
"}",
"if",
"local_var_path",
".",
"include?",
"(",
"'{'",
"+",
"downcase_first_letter",
"(",
"'Password'",
")",
"+",
"'}'",
")",
"local_var_path",
"=",
"local_var_path",
".",
"sub",
"(",
"'{'",
"+",
"downcase_first_letter",
"(",
"'Password'",
")",
"+",
"'}'",
",",
"request",
".",
"password",
".",
"to_s",
")",
"else",
"query_params",
"[",
"downcase_first_letter",
"(",
"'Password'",
")",
"]",
"=",
"request",
".",
"password",
"unless",
"request",
".",
"password",
".",
"nil?",
"end",
"if",
"local_var_path",
".",
"include?",
"(",
"'{'",
"+",
"downcase_first_letter",
"(",
"'Folder'",
")",
"+",
"'}'",
")",
"local_var_path",
"=",
"local_var_path",
".",
"sub",
"(",
"'{'",
"+",
"downcase_first_letter",
"(",
"'Folder'",
")",
"+",
"'}'",
",",
"request",
".",
"folder",
".",
"to_s",
")",
"else",
"query_params",
"[",
"downcase_first_letter",
"(",
"'Folder'",
")",
"]",
"=",
"request",
".",
"folder",
"unless",
"request",
".",
"folder",
".",
"nil?",
"end",
"if",
"local_var_path",
".",
"include?",
"(",
"'{'",
"+",
"downcase_first_letter",
"(",
"'Storage'",
")",
"+",
"'}'",
")",
"local_var_path",
"=",
"local_var_path",
".",
"sub",
"(",
"'{'",
"+",
"downcase_first_letter",
"(",
"'Storage'",
")",
"+",
"'}'",
",",
"request",
".",
"storage",
".",
"to_s",
")",
"else",
"query_params",
"[",
"downcase_first_letter",
"(",
"'Storage'",
")",
"]",
"=",
"request",
".",
"storage",
"unless",
"request",
".",
"storage",
".",
"nil?",
"end",
"# header parameters",
"header_params",
"=",
"{",
"}",
"# HTTP header 'Accept' (if needed)",
"header_params",
"[",
"'Accept'",
"]",
"=",
"@api_client",
".",
"select_header_accept",
"(",
"[",
"'application/json'",
",",
"'application/xml'",
"]",
")",
"# HTTP header 'Content-Type'",
"header_params",
"[",
"'Content-Type'",
"]",
"=",
"@api_client",
".",
"select_header_content_type",
"(",
"[",
"'application/json'",
",",
"'application/xml'",
"]",
")",
"# form parameters",
"form_params",
"=",
"{",
"}",
"# http body (model)",
"post_body",
"=",
"@api_client",
".",
"object_to_http_body",
"(",
"request",
".",
"verify_options_collection_data",
")",
"data",
",",
"status_code",
",",
"headers",
"=",
"@api_client",
".",
"call_api",
"(",
":POST",
",",
"local_var_path",
",",
"header_params",
":",
"header_params",
",",
"query_params",
":",
"query_params",
",",
"form_params",
":",
"form_params",
",",
"body",
":",
"post_body",
",",
"access_token",
":",
"get_access_token",
",",
"return_type",
":",
"'VerifiedDocumentResponse'",
")",
"if",
"@api_client",
".",
"config",
".",
"debugging",
"@api_client",
".",
"config",
".",
"logger",
".",
"debug",
"\"API called:\n SignatureApi#post_verification_collection\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"",
"end",
"[",
"data",
",",
"status_code",
",",
"headers",
"]",
"end"
] | Verify the Document.
@param request PostVerificationCollectionRequest
@return [Array<(VerifiedDocumentResponse, Fixnum, Hash)>]
VerifiedDocumentResponse data, response status code and response headers | [
"Verify",
"the",
"Document",
"."
] | d16e6f4bdd6cb9196d4e28ef3fc2123da94f0ef0 | https://github.com/groupdocs-signature-cloud/groupdocs-signature-cloud-ruby/blob/d16e6f4bdd6cb9196d4e28ef3fc2123da94f0ef0/lib/groupdocs_signature_cloud/api/signature_api.rb#L1978-L2030 | train |
boof/xbel | lib/nokogiri/decorators/xbel.rb | Nokogiri::Decorators::XBEL.Entry.desc= | def desc=(value)
node = at './desc'
node ||= add_child Nokogiri::XML::Node.new('desc', document)
node.content = value
end | ruby | def desc=(value)
node = at './desc'
node ||= add_child Nokogiri::XML::Node.new('desc', document)
node.content = value
end | [
"def",
"desc",
"=",
"(",
"value",
")",
"node",
"=",
"at",
"'./desc'",
"node",
"||=",
"add_child",
"Nokogiri",
"::",
"XML",
"::",
"Node",
".",
"new",
"(",
"'desc'",
",",
"document",
")",
"node",
".",
"content",
"=",
"value",
"end"
] | Sets description of node. | [
"Sets",
"description",
"of",
"node",
"."
] | a1997a0ff61e99f390cc4f05ef9ec4757557048e | https://github.com/boof/xbel/blob/a1997a0ff61e99f390cc4f05ef9ec4757557048e/lib/nokogiri/decorators/xbel.rb#L47-L52 | train |
boof/xbel | lib/nokogiri/decorators/xbel.rb | Nokogiri::Decorators::XBEL.Entry.added= | def added=(value)
set_attribute 'added', case value
when Time; value.strftime '%Y-%m-%d'
when String; value
else
raise ArgumentError
end
end | ruby | def added=(value)
set_attribute 'added', case value
when Time; value.strftime '%Y-%m-%d'
when String; value
else
raise ArgumentError
end
end | [
"def",
"added",
"=",
"(",
"value",
")",
"set_attribute",
"'added'",
",",
"case",
"value",
"when",
"Time",
";",
"value",
".",
"strftime",
"'%Y-%m-%d'",
"when",
"String",
";",
"value",
"else",
"raise",
"ArgumentError",
"end",
"end"
] | Sets addition date. | [
"Sets",
"addition",
"date",
"."
] | a1997a0ff61e99f390cc4f05ef9ec4757557048e | https://github.com/boof/xbel/blob/a1997a0ff61e99f390cc4f05ef9ec4757557048e/lib/nokogiri/decorators/xbel.rb#L83-L90 | train |
nilsding/Empyrean | lib/empyrean/tweetparser.rb | Empyrean.TweetParser.parse | def parse(tweets)
retdict = {
mentions: {},
hashtags: {},
clients: {},
smileys: {},
times_of_day: [0] * 24,
tweet_count: 0,
retweet_count: 0,
selftweet_count: 0,
}
tweets.each do |tweet|
parsed_tweet = self.parse_one tweet
if parsed_tweet[:retweet] # the tweet was a retweet
# increase retweeted tweets count
retdict[:retweet_count] += 1
else
parsed_tweet[:mentions].each do |user, data| # add mentions to the mentions dict
retdict[:mentions][user] ||= { count: 0 }
retdict[:mentions][user][:count] += data[:count]
retdict[:mentions][user][:name] ||= data[:name]
retdict[:mentions][user][:examples] ||= []
retdict[:mentions][user][:examples] << data[:example]
end
parsed_tweet[:hashtags].each do |hashtag, data| # add hashtags to the hashtags dict
retdict[:hashtags][hashtag] ||= { count: 0 }
retdict[:hashtags][hashtag][:count] += data[:count]
retdict[:hashtags][hashtag][:hashtag] ||= data[:hashtag]
retdict[:hashtags][hashtag][:examples] ||= []
retdict[:hashtags][hashtag][:examples] << data[:example]
end
parsed_tweet[:smileys].each do |smile, data|
retdict[:smileys][smile] ||= { count: 0 }
retdict[:smileys][smile][:frown] ||= data[:frown]
retdict[:smileys][smile][:count] += data[:count]
retdict[:smileys][smile][:smiley] ||= data[:smiley]
retdict[:smileys][smile][:examples] ||= []
retdict[:smileys][smile][:examples] << data[:example]
end
# increase self tweeted tweets count
retdict[:selftweet_count] += 1
end
# add client to the clients dict
client_dict = parsed_tweet[:client][:name]
retdict[:clients][client_dict] ||= { count: 0 }
retdict[:clients][client_dict][:count] += 1
retdict[:clients][client_dict][:name] = parsed_tweet[:client][:name]
retdict[:clients][client_dict][:url] = parsed_tweet[:client][:url]
retdict[:times_of_day][parsed_tweet[:time_of_day]] += 1
# increase tweet count
retdict[:tweet_count] += 1
end
retdict
end | ruby | def parse(tweets)
retdict = {
mentions: {},
hashtags: {},
clients: {},
smileys: {},
times_of_day: [0] * 24,
tweet_count: 0,
retweet_count: 0,
selftweet_count: 0,
}
tweets.each do |tweet|
parsed_tweet = self.parse_one tweet
if parsed_tweet[:retweet] # the tweet was a retweet
# increase retweeted tweets count
retdict[:retweet_count] += 1
else
parsed_tweet[:mentions].each do |user, data| # add mentions to the mentions dict
retdict[:mentions][user] ||= { count: 0 }
retdict[:mentions][user][:count] += data[:count]
retdict[:mentions][user][:name] ||= data[:name]
retdict[:mentions][user][:examples] ||= []
retdict[:mentions][user][:examples] << data[:example]
end
parsed_tweet[:hashtags].each do |hashtag, data| # add hashtags to the hashtags dict
retdict[:hashtags][hashtag] ||= { count: 0 }
retdict[:hashtags][hashtag][:count] += data[:count]
retdict[:hashtags][hashtag][:hashtag] ||= data[:hashtag]
retdict[:hashtags][hashtag][:examples] ||= []
retdict[:hashtags][hashtag][:examples] << data[:example]
end
parsed_tweet[:smileys].each do |smile, data|
retdict[:smileys][smile] ||= { count: 0 }
retdict[:smileys][smile][:frown] ||= data[:frown]
retdict[:smileys][smile][:count] += data[:count]
retdict[:smileys][smile][:smiley] ||= data[:smiley]
retdict[:smileys][smile][:examples] ||= []
retdict[:smileys][smile][:examples] << data[:example]
end
# increase self tweeted tweets count
retdict[:selftweet_count] += 1
end
# add client to the clients dict
client_dict = parsed_tweet[:client][:name]
retdict[:clients][client_dict] ||= { count: 0 }
retdict[:clients][client_dict][:count] += 1
retdict[:clients][client_dict][:name] = parsed_tweet[:client][:name]
retdict[:clients][client_dict][:url] = parsed_tweet[:client][:url]
retdict[:times_of_day][parsed_tweet[:time_of_day]] += 1
# increase tweet count
retdict[:tweet_count] += 1
end
retdict
end | [
"def",
"parse",
"(",
"tweets",
")",
"retdict",
"=",
"{",
"mentions",
":",
"{",
"}",
",",
"hashtags",
":",
"{",
"}",
",",
"clients",
":",
"{",
"}",
",",
"smileys",
":",
"{",
"}",
",",
"times_of_day",
":",
"[",
"0",
"]",
"*",
"24",
",",
"tweet_count",
":",
"0",
",",
"retweet_count",
":",
"0",
",",
"selftweet_count",
":",
"0",
",",
"}",
"tweets",
".",
"each",
"do",
"|",
"tweet",
"|",
"parsed_tweet",
"=",
"self",
".",
"parse_one",
"tweet",
"if",
"parsed_tweet",
"[",
":retweet",
"]",
"# the tweet was a retweet",
"# increase retweeted tweets count",
"retdict",
"[",
":retweet_count",
"]",
"+=",
"1",
"else",
"parsed_tweet",
"[",
":mentions",
"]",
".",
"each",
"do",
"|",
"user",
",",
"data",
"|",
"# add mentions to the mentions dict",
"retdict",
"[",
":mentions",
"]",
"[",
"user",
"]",
"||=",
"{",
"count",
":",
"0",
"}",
"retdict",
"[",
":mentions",
"]",
"[",
"user",
"]",
"[",
":count",
"]",
"+=",
"data",
"[",
":count",
"]",
"retdict",
"[",
":mentions",
"]",
"[",
"user",
"]",
"[",
":name",
"]",
"||=",
"data",
"[",
":name",
"]",
"retdict",
"[",
":mentions",
"]",
"[",
"user",
"]",
"[",
":examples",
"]",
"||=",
"[",
"]",
"retdict",
"[",
":mentions",
"]",
"[",
"user",
"]",
"[",
":examples",
"]",
"<<",
"data",
"[",
":example",
"]",
"end",
"parsed_tweet",
"[",
":hashtags",
"]",
".",
"each",
"do",
"|",
"hashtag",
",",
"data",
"|",
"# add hashtags to the hashtags dict",
"retdict",
"[",
":hashtags",
"]",
"[",
"hashtag",
"]",
"||=",
"{",
"count",
":",
"0",
"}",
"retdict",
"[",
":hashtags",
"]",
"[",
"hashtag",
"]",
"[",
":count",
"]",
"+=",
"data",
"[",
":count",
"]",
"retdict",
"[",
":hashtags",
"]",
"[",
"hashtag",
"]",
"[",
":hashtag",
"]",
"||=",
"data",
"[",
":hashtag",
"]",
"retdict",
"[",
":hashtags",
"]",
"[",
"hashtag",
"]",
"[",
":examples",
"]",
"||=",
"[",
"]",
"retdict",
"[",
":hashtags",
"]",
"[",
"hashtag",
"]",
"[",
":examples",
"]",
"<<",
"data",
"[",
":example",
"]",
"end",
"parsed_tweet",
"[",
":smileys",
"]",
".",
"each",
"do",
"|",
"smile",
",",
"data",
"|",
"retdict",
"[",
":smileys",
"]",
"[",
"smile",
"]",
"||=",
"{",
"count",
":",
"0",
"}",
"retdict",
"[",
":smileys",
"]",
"[",
"smile",
"]",
"[",
":frown",
"]",
"||=",
"data",
"[",
":frown",
"]",
"retdict",
"[",
":smileys",
"]",
"[",
"smile",
"]",
"[",
":count",
"]",
"+=",
"data",
"[",
":count",
"]",
"retdict",
"[",
":smileys",
"]",
"[",
"smile",
"]",
"[",
":smiley",
"]",
"||=",
"data",
"[",
":smiley",
"]",
"retdict",
"[",
":smileys",
"]",
"[",
"smile",
"]",
"[",
":examples",
"]",
"||=",
"[",
"]",
"retdict",
"[",
":smileys",
"]",
"[",
"smile",
"]",
"[",
":examples",
"]",
"<<",
"data",
"[",
":example",
"]",
"end",
"# increase self tweeted tweets count",
"retdict",
"[",
":selftweet_count",
"]",
"+=",
"1",
"end",
"# add client to the clients dict",
"client_dict",
"=",
"parsed_tweet",
"[",
":client",
"]",
"[",
":name",
"]",
"retdict",
"[",
":clients",
"]",
"[",
"client_dict",
"]",
"||=",
"{",
"count",
":",
"0",
"}",
"retdict",
"[",
":clients",
"]",
"[",
"client_dict",
"]",
"[",
":count",
"]",
"+=",
"1",
"retdict",
"[",
":clients",
"]",
"[",
"client_dict",
"]",
"[",
":name",
"]",
"=",
"parsed_tweet",
"[",
":client",
"]",
"[",
":name",
"]",
"retdict",
"[",
":clients",
"]",
"[",
"client_dict",
"]",
"[",
":url",
"]",
"=",
"parsed_tweet",
"[",
":client",
"]",
"[",
":url",
"]",
"retdict",
"[",
":times_of_day",
"]",
"[",
"parsed_tweet",
"[",
":time_of_day",
"]",
"]",
"+=",
"1",
"# increase tweet count",
"retdict",
"[",
":tweet_count",
"]",
"+=",
"1",
"end",
"retdict",
"end"
] | Parses an array of tweets
Returns a dict of things | [
"Parses",
"an",
"array",
"of",
"tweets"
] | e652fb8966dfcd32968789af75e8d5a4f63134ec | https://github.com/nilsding/Empyrean/blob/e652fb8966dfcd32968789af75e8d5a4f63134ec/lib/empyrean/tweetparser.rb#L32-L92 | train |
Fullscreen/fb-support | lib/fb/http_request.rb | Fb.HTTPRequest.run | def run
if response.is_a? @expected_response
self.class.on_response.call(self, response)
response.tap do
parse_response!
end
else
raise HTTPError.new(error_message, response: response)
end
end | ruby | def run
if response.is_a? @expected_response
self.class.on_response.call(self, response)
response.tap do
parse_response!
end
else
raise HTTPError.new(error_message, response: response)
end
end | [
"def",
"run",
"if",
"response",
".",
"is_a?",
"@expected_response",
"self",
".",
"class",
".",
"on_response",
".",
"call",
"(",
"self",
",",
"response",
")",
"response",
".",
"tap",
"do",
"parse_response!",
"end",
"else",
"raise",
"HTTPError",
".",
"new",
"(",
"error_message",
",",
"response",
":",
"response",
")",
"end",
"end"
] | Sends the request and returns the response with the body parsed from JSON.
@return [Net::HTTPResponse] if the request succeeds.
@raise [Fb::HTTPError] if the request fails. | [
"Sends",
"the",
"request",
"and",
"returns",
"the",
"response",
"with",
"the",
"body",
"parsed",
"from",
"JSON",
"."
] | 4f4633cfa06dda7bb3934acb1929cbb10a4ed018 | https://github.com/Fullscreen/fb-support/blob/4f4633cfa06dda7bb3934acb1929cbb10a4ed018/lib/fb/http_request.rb#L58-L67 | train |
userhello/bit_magic | lib/bit_magic/bits.rb | BitMagic.Bits.read | def read(name, field = nil)
field ||= self.field
if name.is_a?(Integer)
field.read_field(name)
elsif bits = @field_list[name]
field.read_field(bits)
end
end | ruby | def read(name, field = nil)
field ||= self.field
if name.is_a?(Integer)
field.read_field(name)
elsif bits = @field_list[name]
field.read_field(bits)
end
end | [
"def",
"read",
"(",
"name",
",",
"field",
"=",
"nil",
")",
"field",
"||=",
"self",
".",
"field",
"if",
"name",
".",
"is_a?",
"(",
"Integer",
")",
"field",
".",
"read_field",
"(",
"name",
")",
"elsif",
"bits",
"=",
"@field_list",
"[",
"name",
"]",
"field",
".",
"read_field",
"(",
"bits",
")",
"end",
"end"
] | Read a field or bit from its bit index or name
@param [Symbol, Integer] name either the name of the bit (a key in field_list)
or a integer bit position
@param [BitField optional] field a specific BitField to read from.
default: return value of #field
@example Read bit values
# The struct is just an example, normally you would define a new class
Example = Struct.new('Example', :flags)
exo = Example.new(9)
bits = Bits.new(exo, {:is_odd => 0, :amount => [1, 2, 3], :is_cool => 4})
bits.read(:is_odd) #=> 1
bits.read(:amount) #=> 4
bits.read(:is_cool) #=> 0
bits.read(:amount, BitField.new(78)) #=> 7
# Bonus: aliased as []
bits[:is_odd] #=> 1
@return [Integer] a value of the bit (0 or 1) or bits (number from 0 to
(2**bit_length) - 1) or nil if the field name is not in the list | [
"Read",
"a",
"field",
"or",
"bit",
"from",
"its",
"bit",
"index",
"or",
"name"
] | 78b7fc28313af9c9506220812573576d229186bb | https://github.com/userhello/bit_magic/blob/78b7fc28313af9c9506220812573576d229186bb/lib/bit_magic/bits.rb#L219-L227 | train |
userhello/bit_magic | lib/bit_magic/bits.rb | BitMagic.Bits.write | def write(name, target_value)
if name.is_a?(Symbol)
self.write(@field_list[name], target_value)
elsif name.is_a?(Integer)
self.update self.field.write_bits(name => @options[:bool_caster].call(target_value))
elsif name.respond_to?(:[]) and target_value.respond_to?(:[])
bits = {}
name.each_with_index do |bit, i|
bits[bit] = @options[:bool_caster].call(target_value[i])
end
self.update self.field.write_bits bits
end
end | ruby | def write(name, target_value)
if name.is_a?(Symbol)
self.write(@field_list[name], target_value)
elsif name.is_a?(Integer)
self.update self.field.write_bits(name => @options[:bool_caster].call(target_value))
elsif name.respond_to?(:[]) and target_value.respond_to?(:[])
bits = {}
name.each_with_index do |bit, i|
bits[bit] = @options[:bool_caster].call(target_value[i])
end
self.update self.field.write_bits bits
end
end | [
"def",
"write",
"(",
"name",
",",
"target_value",
")",
"if",
"name",
".",
"is_a?",
"(",
"Symbol",
")",
"self",
".",
"write",
"(",
"@field_list",
"[",
"name",
"]",
",",
"target_value",
")",
"elsif",
"name",
".",
"is_a?",
"(",
"Integer",
")",
"self",
".",
"update",
"self",
".",
"field",
".",
"write_bits",
"(",
"name",
"=>",
"@options",
"[",
":bool_caster",
"]",
".",
"call",
"(",
"target_value",
")",
")",
"elsif",
"name",
".",
"respond_to?",
"(",
":[]",
")",
"and",
"target_value",
".",
"respond_to?",
"(",
":[]",
")",
"bits",
"=",
"{",
"}",
"name",
".",
"each_with_index",
"do",
"|",
"bit",
",",
"i",
"|",
"bits",
"[",
"bit",
"]",
"=",
"@options",
"[",
":bool_caster",
"]",
".",
"call",
"(",
"target_value",
"[",
"i",
"]",
")",
"end",
"self",
".",
"update",
"self",
".",
"field",
".",
"write_bits",
"bits",
"end",
"end"
] | Write a field or bit from its field name or index
Note: only the total bits of the field is used from the given value, so
any additional bits are ignored. eg: writing a field with one bit as value
of 4 will set the bit to 0, writing 5 sets it to 1.
@param [Symbol, Integer, Array<Integer>] name a field name, or bit position,
or array of bit positions
@param [Integer, Array<Integer>] target_value the target value for the field
(note: technically, this can be anything that responds to :[](index), but
usage in that type of context is discouraged without adapter support)
@example Write values to bit fields
# The struct is just an example, normally you would define a new class
Example = Struct.new('Example', :flags)
exo = Example.new(0)
bits = Bits.new(exo, {:is_odd => 0, :amount => [1, 2, 3], :is_cool => 4})
bits.write(:is_odd, 1) #=> 1
bits.write(:amount, 5) #=> 11
exo.flags #=> 11
# Bonus, aliased as :[]=, but note in this mode, the return value is same as given value
bits[:is_cool] = 1 #=> 1
exo.flags #=> 27
@return the return value of the updater Proc, usually is equal to the final
master value (with all the bits) after writing this bit | [
"Write",
"a",
"field",
"or",
"bit",
"from",
"its",
"field",
"name",
"or",
"index"
] | 78b7fc28313af9c9506220812573576d229186bb | https://github.com/userhello/bit_magic/blob/78b7fc28313af9c9506220812573576d229186bb/lib/bit_magic/bits.rb#L257-L271 | train |
zobar/mass_shootings | lib/mass_shootings/shooting.rb | MassShootings.Shooting.as_json | def as_json(_=nil)
json = {'id' => id}
json['allegedShooters'] = alleged_shooters unless alleged_shooters.nil?
json.merge(
'casualties' => casualties.stringify_keys,
'date' => date.iso8601,
'location' => location,
'references' => references.map(&:to_s))
end | ruby | def as_json(_=nil)
json = {'id' => id}
json['allegedShooters'] = alleged_shooters unless alleged_shooters.nil?
json.merge(
'casualties' => casualties.stringify_keys,
'date' => date.iso8601,
'location' => location,
'references' => references.map(&:to_s))
end | [
"def",
"as_json",
"(",
"_",
"=",
"nil",
")",
"json",
"=",
"{",
"'id'",
"=>",
"id",
"}",
"json",
"[",
"'allegedShooters'",
"]",
"=",
"alleged_shooters",
"unless",
"alleged_shooters",
".",
"nil?",
"json",
".",
"merge",
"(",
"'casualties'",
"=>",
"casualties",
".",
"stringify_keys",
",",
"'date'",
"=>",
"date",
".",
"iso8601",
",",
"'location'",
"=>",
"location",
",",
"'references'",
"=>",
"references",
".",
"map",
"(",
":to_s",
")",
")",
"end"
] | Returns a hash representing the shooting.
@return [Hash{String => Object}] | [
"Returns",
"a",
"hash",
"representing",
"the",
"shooting",
"."
] | dfed9c68c7216c30e7d3a9962dc7d684b28299bf | https://github.com/zobar/mass_shootings/blob/dfed9c68c7216c30e7d3a9962dc7d684b28299bf/lib/mass_shootings/shooting.rb#L45-L53 | train |
kmewhort/similarity_tree | lib/similarity_tree/similarity_tree.rb | SimilarityTree.SimilarityTree.prune | def prune(nodes)
nodes.each do |node|
node.parent.children.reject!{|n| n == node} if (node != @root) && (node.diff_score < @score_threshold)
end
end | ruby | def prune(nodes)
nodes.each do |node|
node.parent.children.reject!{|n| n == node} if (node != @root) && (node.diff_score < @score_threshold)
end
end | [
"def",
"prune",
"(",
"nodes",
")",
"nodes",
".",
"each",
"do",
"|",
"node",
"|",
"node",
".",
"parent",
".",
"children",
".",
"reject!",
"{",
"|",
"n",
"|",
"n",
"==",
"node",
"}",
"if",
"(",
"node",
"!=",
"@root",
")",
"&&",
"(",
"node",
".",
"diff_score",
"<",
"@score_threshold",
")",
"end",
"end"
] | prune away nodes that don't meet the configured score threshold | [
"prune",
"away",
"nodes",
"that",
"don",
"t",
"meet",
"the",
"configured",
"score",
"threshold"
] | d688c6d86e2a5a81ff71e81ef805c9af6cb8c8e7 | https://github.com/kmewhort/similarity_tree/blob/d688c6d86e2a5a81ff71e81ef805c9af6cb8c8e7/lib/similarity_tree/similarity_tree.rb#L75-L79 | train |
aprescott/redhead | lib/redhead/redhead_string.rb | Redhead.String.headers! | def headers!(hash)
changing = headers.select { |header| hash.has_key?(header.key) }
# modifies its elements!
changing.each do |header|
new_values = hash[header.key]
header.raw = new_values[:raw] if new_values[:raw]
header.key = new_values[:key] if new_values[:key]
end
Redhead::HeaderSet.new(changing)
end | ruby | def headers!(hash)
changing = headers.select { |header| hash.has_key?(header.key) }
# modifies its elements!
changing.each do |header|
new_values = hash[header.key]
header.raw = new_values[:raw] if new_values[:raw]
header.key = new_values[:key] if new_values[:key]
end
Redhead::HeaderSet.new(changing)
end | [
"def",
"headers!",
"(",
"hash",
")",
"changing",
"=",
"headers",
".",
"select",
"{",
"|",
"header",
"|",
"hash",
".",
"has_key?",
"(",
"header",
".",
"key",
")",
"}",
"# modifies its elements!",
"changing",
".",
"each",
"do",
"|",
"header",
"|",
"new_values",
"=",
"hash",
"[",
"header",
".",
"key",
"]",
"header",
".",
"raw",
"=",
"new_values",
"[",
":raw",
"]",
"if",
"new_values",
"[",
":raw",
"]",
"header",
".",
"key",
"=",
"new_values",
"[",
":key",
"]",
"if",
"new_values",
"[",
":key",
"]",
"end",
"Redhead",
"::",
"HeaderSet",
".",
"new",
"(",
"changing",
")",
"end"
] | Returns true if self.headers == other.headers and self.string == other.string.
Modifies the headers in the set, using the given _hash_, which has the form
{ some_header: { raw: a, key: b }, another_header: ..., ... }
Change the header with key :some_header such that its new raw name is _a_ and its new key name
is _b_. Returns a HeaderSet object containing the changed Header objects. | [
"Returns",
"true",
"if",
"self",
".",
"headers",
"==",
"other",
".",
"headers",
"and",
"self",
".",
"string",
"==",
"other",
".",
"string",
".",
"Modifies",
"the",
"headers",
"in",
"the",
"set",
"using",
"the",
"given",
"_hash_",
"which",
"has",
"the",
"form"
] | 4fe032029e6d3e5ebe88d61bbb0d5150fe204b3d | https://github.com/aprescott/redhead/blob/4fe032029e6d3e5ebe88d61bbb0d5150fe204b3d/lib/redhead/redhead_string.rb#L82-L93 | train |
fugroup/easymongo | lib/easymongo/document.rb | Easymongo.Document.method_missing | def method_missing(name, *args, &block)
return attr(name[0..-2], args[0]) if args.size == 1 and name[-1] == '='
end | ruby | def method_missing(name, *args, &block)
return attr(name[0..-2], args[0]) if args.size == 1 and name[-1] == '='
end | [
"def",
"method_missing",
"(",
"name",
",",
"*",
"args",
",",
"&",
"block",
")",
"return",
"attr",
"(",
"name",
"[",
"0",
"..",
"-",
"2",
"]",
",",
"args",
"[",
"0",
"]",
")",
"if",
"args",
".",
"size",
"==",
"1",
"and",
"name",
"[",
"-",
"1",
"]",
"==",
"'='",
"end"
] | Dynamically write value | [
"Dynamically",
"write",
"value"
] | a48675248eafcd4885278d3196600c8ebda46240 | https://github.com/fugroup/easymongo/blob/a48675248eafcd4885278d3196600c8ebda46240/lib/easymongo/document.rb#L41-L43 | train |
bcobb/and_feathers | lib/and_feathers/sugar.rb | AndFeathers.Sugar.dir | def dir(name, mode = 16877, &block)
name_parts = name.split(::File::SEPARATOR)
innermost_child_name = name_parts.pop
if name_parts.empty?
Directory.new(name, mode).tap do |directory|
add_directory(directory)
block.call(directory) if block
end
else
innermost_parent = name_parts.reduce(self) do |parent, child_name|
parent.dir(child_name)
end
innermost_parent.dir(innermost_child_name, &block)
end
end | ruby | def dir(name, mode = 16877, &block)
name_parts = name.split(::File::SEPARATOR)
innermost_child_name = name_parts.pop
if name_parts.empty?
Directory.new(name, mode).tap do |directory|
add_directory(directory)
block.call(directory) if block
end
else
innermost_parent = name_parts.reduce(self) do |parent, child_name|
parent.dir(child_name)
end
innermost_parent.dir(innermost_child_name, &block)
end
end | [
"def",
"dir",
"(",
"name",
",",
"mode",
"=",
"16877",
",",
"&",
"block",
")",
"name_parts",
"=",
"name",
".",
"split",
"(",
"::",
"File",
"::",
"SEPARATOR",
")",
"innermost_child_name",
"=",
"name_parts",
".",
"pop",
"if",
"name_parts",
".",
"empty?",
"Directory",
".",
"new",
"(",
"name",
",",
"mode",
")",
".",
"tap",
"do",
"|",
"directory",
"|",
"add_directory",
"(",
"directory",
")",
"block",
".",
"call",
"(",
"directory",
")",
"if",
"block",
"end",
"else",
"innermost_parent",
"=",
"name_parts",
".",
"reduce",
"(",
"self",
")",
"do",
"|",
"parent",
",",
"child_name",
"|",
"parent",
".",
"dir",
"(",
"child_name",
")",
"end",
"innermost_parent",
".",
"dir",
"(",
"innermost_child_name",
",",
"block",
")",
"end",
"end"
] | Add a +Directory+ named +name+ to this entity's list of children. The
+name+ may simply be the name of the directory, or may be a path to the
directory.
In the case of the latter, +dir+ will create the +Directory+ tree
specified by the path. The block parameter yielded in this case will be
the innermost directory.
@example
archive = Directory.new
archive.dir('app') do |app|
app.name == 'app'
app.path == './app'
end
@example
archive.dir('app/controllers/concerns') do |concerns|
concerns.name == 'concerns'
concerns.path == './app/controllers/concerns'
end
@param name [String] the directory name
@param mode [Fixnum] the directory mode
@yieldparam directory [AndFeathers::Directory] the newly-created
+Directory+ | [
"Add",
"a",
"+",
"Directory",
"+",
"named",
"+",
"name",
"+",
"to",
"this",
"entity",
"s",
"list",
"of",
"children",
".",
"The",
"+",
"name",
"+",
"may",
"simply",
"be",
"the",
"name",
"of",
"the",
"directory",
"or",
"may",
"be",
"a",
"path",
"to",
"the",
"directory",
"."
] | f35b156f8ae6930851712bbaf502f97b3aa9a1b1 | https://github.com/bcobb/and_feathers/blob/f35b156f8ae6930851712bbaf502f97b3aa9a1b1/lib/and_feathers/sugar.rb#L35-L53 | train |
bcobb/and_feathers | lib/and_feathers/sugar.rb | AndFeathers.Sugar.file | def file(name, mode = 33188, &content)
content ||= NO_CONTENT
name_parts = name.split(::File::SEPARATOR)
file_name = name_parts.pop
if name_parts.empty?
File.new(name, mode, content).tap do |file|
add_file(file)
end
else
dir(name_parts.join(::File::SEPARATOR)) do |parent|
parent.file(file_name, mode, &content)
end
end
end | ruby | def file(name, mode = 33188, &content)
content ||= NO_CONTENT
name_parts = name.split(::File::SEPARATOR)
file_name = name_parts.pop
if name_parts.empty?
File.new(name, mode, content).tap do |file|
add_file(file)
end
else
dir(name_parts.join(::File::SEPARATOR)) do |parent|
parent.file(file_name, mode, &content)
end
end
end | [
"def",
"file",
"(",
"name",
",",
"mode",
"=",
"33188",
",",
"&",
"content",
")",
"content",
"||=",
"NO_CONTENT",
"name_parts",
"=",
"name",
".",
"split",
"(",
"::",
"File",
"::",
"SEPARATOR",
")",
"file_name",
"=",
"name_parts",
".",
"pop",
"if",
"name_parts",
".",
"empty?",
"File",
".",
"new",
"(",
"name",
",",
"mode",
",",
"content",
")",
".",
"tap",
"do",
"|",
"file",
"|",
"add_file",
"(",
"file",
")",
"end",
"else",
"dir",
"(",
"name_parts",
".",
"join",
"(",
"::",
"File",
"::",
"SEPARATOR",
")",
")",
"do",
"|",
"parent",
"|",
"parent",
".",
"file",
"(",
"file_name",
",",
"mode",
",",
"content",
")",
"end",
"end",
"end"
] | Add a +File+ named +name+ to this entity's list of children. The +name+
may simply be the name of the file or may be a path to the file.
In the case of the latter, +file+ will create the +Directory+ tree
which contains the +File+ specified by the path.
Either way, the +File+'s contents will be set to the result of the
given block, or to a blank string if no block is given
@example
archive = Directory.new
archive.file('README') do
"Cool"
end
@example
archive = Directory.new
archive.file('app/models/user.rb') do
"class User < ActiveRecord::Base\nend"
end
@param name [String] the file name
@param mode [Fixnum] the file mode
@yieldreturn [String] the file contents | [
"Add",
"a",
"+",
"File",
"+",
"named",
"+",
"name",
"+",
"to",
"this",
"entity",
"s",
"list",
"of",
"children",
".",
"The",
"+",
"name",
"+",
"may",
"simply",
"be",
"the",
"name",
"of",
"the",
"file",
"or",
"may",
"be",
"a",
"path",
"to",
"the",
"file",
"."
] | f35b156f8ae6930851712bbaf502f97b3aa9a1b1 | https://github.com/bcobb/and_feathers/blob/f35b156f8ae6930851712bbaf502f97b3aa9a1b1/lib/and_feathers/sugar.rb#L87-L103 | train |
dwilkie/tropo_message | lib/tropo_message.rb | Tropo.Message.request_xml | def request_xml
request_params = @params.dup
token = request_params.delete("token")
xml = ""
request_params.each do |key, value|
xml << "<var name=\"#{escape(key)}\" value=\"#{escape(value)}\"/>"
end
"<sessions><token>#{token}</token>#{xml}</sessions>"
end | ruby | def request_xml
request_params = @params.dup
token = request_params.delete("token")
xml = ""
request_params.each do |key, value|
xml << "<var name=\"#{escape(key)}\" value=\"#{escape(value)}\"/>"
end
"<sessions><token>#{token}</token>#{xml}</sessions>"
end | [
"def",
"request_xml",
"request_params",
"=",
"@params",
".",
"dup",
"token",
"=",
"request_params",
".",
"delete",
"(",
"\"token\"",
")",
"xml",
"=",
"\"\"",
"request_params",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"xml",
"<<",
"\"<var name=\\\"#{escape(key)}\\\" value=\\\"#{escape(value)}\\\"/>\"",
"end",
"\"<sessions><token>#{token}</token>#{xml}</sessions>\"",
"end"
] | Generates xml suitable for an XML POST request to Tropo
Example:
tropo_message = Tropo::Message.new
tropo_message.to = "44122782474"
tropo_message.text = "Hi John, how r u today?"
tropo_message.token = "1234512345"
tropo_message.request_xml # =>
# <sessions>
# <token>1234512345</token>
# <var name="to" value="44122782474"/>
# <var name="text" value="Hi+John%2C+how+r+u+today%3F"/>
# </sessions>" | [
"Generates",
"xml",
"suitable",
"for",
"an",
"XML",
"POST",
"request",
"to",
"Tropo"
] | a04b7ed96e8398baebbcf44d0b959c23e525d400 | https://github.com/dwilkie/tropo_message/blob/a04b7ed96e8398baebbcf44d0b959c23e525d400/lib/tropo_message.rb#L52-L60 | train |
phallguy/shamu | lib/shamu/attributes.rb | Shamu.Attributes.to_attributes | def to_attributes( only: nil, except: nil )
self.class.attributes.each_with_object({}) do |(name, options), attrs|
next if ( only && !match_attribute?( only, name ) ) || ( except && match_attribute?( except, name ) )
next unless serialize_attribute?( name, options )
attrs[name] = send( name )
end
end | ruby | def to_attributes( only: nil, except: nil )
self.class.attributes.each_with_object({}) do |(name, options), attrs|
next if ( only && !match_attribute?( only, name ) ) || ( except && match_attribute?( except, name ) )
next unless serialize_attribute?( name, options )
attrs[name] = send( name )
end
end | [
"def",
"to_attributes",
"(",
"only",
":",
"nil",
",",
"except",
":",
"nil",
")",
"self",
".",
"class",
".",
"attributes",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"(",
"name",
",",
"options",
")",
",",
"attrs",
"|",
"next",
"if",
"(",
"only",
"&&",
"!",
"match_attribute?",
"(",
"only",
",",
"name",
")",
")",
"||",
"(",
"except",
"&&",
"match_attribute?",
"(",
"except",
",",
"name",
")",
")",
"next",
"unless",
"serialize_attribute?",
"(",
"name",
",",
"options",
")",
"attrs",
"[",
"name",
"]",
"=",
"send",
"(",
"name",
")",
"end",
"end"
] | Project the current state of the object to a hash of attributes that can
be used to restore the attribute object at a later time.
@param [Array, Regex] only include matching attributes
@param [Array, Regex] except matching attributes
@return [Hash] of attributes | [
"Project",
"the",
"current",
"state",
"of",
"the",
"object",
"to",
"a",
"hash",
"of",
"attributes",
"that",
"can",
"be",
"used",
"to",
"restore",
"the",
"attribute",
"object",
"at",
"a",
"later",
"time",
"."
] | 527d5cc8ebc45a9d3f35ea43681cee6fa9255093 | https://github.com/phallguy/shamu/blob/527d5cc8ebc45a9d3f35ea43681cee6fa9255093/lib/shamu/attributes.rb#L46-L53 | train |
mccraigmccraig/rsxml | lib/rsxml/namespace.rb | Rsxml.Namespace.compact_attr_qnames | def compact_attr_qnames(ns_stack, attrs)
Hash[attrs.map do |name,value|
[compact_qname(ns_stack, name), value]
end]
end | ruby | def compact_attr_qnames(ns_stack, attrs)
Hash[attrs.map do |name,value|
[compact_qname(ns_stack, name), value]
end]
end | [
"def",
"compact_attr_qnames",
"(",
"ns_stack",
",",
"attrs",
")",
"Hash",
"[",
"attrs",
".",
"map",
"do",
"|",
"name",
",",
"value",
"|",
"[",
"compact_qname",
"(",
"ns_stack",
",",
"name",
")",
",",
"value",
"]",
"end",
"]",
"end"
] | compact all attribute QNames to Strings | [
"compact",
"all",
"attribute",
"QNames",
"to",
"Strings"
] | 3699c186f01be476a5942d64cd5c39f4d6bbe175 | https://github.com/mccraigmccraig/rsxml/blob/3699c186f01be476a5942d64cd5c39f4d6bbe175/lib/rsxml/namespace.rb#L6-L10 | train |
mccraigmccraig/rsxml | lib/rsxml/namespace.rb | Rsxml.Namespace.find_namespace_uri | def find_namespace_uri(ns_stack, prefix, uri_check=nil)
tns = ns_stack.reverse.find{|ns| ns.has_key?(prefix)}
uri = tns[prefix] if tns
raise "prefix: '#{prefix}' is bound to uri: '#{uri}', but should be '#{uri_check}'" if uri_check && uri && uri!=uri_check
uri
end | ruby | def find_namespace_uri(ns_stack, prefix, uri_check=nil)
tns = ns_stack.reverse.find{|ns| ns.has_key?(prefix)}
uri = tns[prefix] if tns
raise "prefix: '#{prefix}' is bound to uri: '#{uri}', but should be '#{uri_check}'" if uri_check && uri && uri!=uri_check
uri
end | [
"def",
"find_namespace_uri",
"(",
"ns_stack",
",",
"prefix",
",",
"uri_check",
"=",
"nil",
")",
"tns",
"=",
"ns_stack",
".",
"reverse",
".",
"find",
"{",
"|",
"ns",
"|",
"ns",
".",
"has_key?",
"(",
"prefix",
")",
"}",
"uri",
"=",
"tns",
"[",
"prefix",
"]",
"if",
"tns",
"raise",
"\"prefix: '#{prefix}' is bound to uri: '#{uri}', but should be '#{uri_check}'\"",
"if",
"uri_check",
"&&",
"uri",
"&&",
"uri!",
"=",
"uri_check",
"uri",
"end"
] | returns the namespace uri for a prefix, if declared in the stack | [
"returns",
"the",
"namespace",
"uri",
"for",
"a",
"prefix",
"if",
"declared",
"in",
"the",
"stack"
] | 3699c186f01be476a5942d64cd5c39f4d6bbe175 | https://github.com/mccraigmccraig/rsxml/blob/3699c186f01be476a5942d64cd5c39f4d6bbe175/lib/rsxml/namespace.rb#L96-L101 | train |
mccraigmccraig/rsxml | lib/rsxml/namespace.rb | Rsxml.Namespace.undeclared_namespace_bindings | def undeclared_namespace_bindings(ns_stack, ns_explicit)
Hash[ns_explicit.map do |prefix,uri|
[prefix, uri] if !find_namespace_uri(ns_stack, prefix, uri)
end.compact]
end | ruby | def undeclared_namespace_bindings(ns_stack, ns_explicit)
Hash[ns_explicit.map do |prefix,uri|
[prefix, uri] if !find_namespace_uri(ns_stack, prefix, uri)
end.compact]
end | [
"def",
"undeclared_namespace_bindings",
"(",
"ns_stack",
",",
"ns_explicit",
")",
"Hash",
"[",
"ns_explicit",
".",
"map",
"do",
"|",
"prefix",
",",
"uri",
"|",
"[",
"prefix",
",",
"uri",
"]",
"if",
"!",
"find_namespace_uri",
"(",
"ns_stack",
",",
"prefix",
",",
"uri",
")",
"end",
".",
"compact",
"]",
"end"
] | figure out which explicit namespaces need declaring
+ns_stack+ is the stack of namespace bindings
+ns_explicit+ is the explicit refs for a element | [
"figure",
"out",
"which",
"explicit",
"namespaces",
"need",
"declaring"
] | 3699c186f01be476a5942d64cd5c39f4d6bbe175 | https://github.com/mccraigmccraig/rsxml/blob/3699c186f01be476a5942d64cd5c39f4d6bbe175/lib/rsxml/namespace.rb#L140-L144 | train |
mccraigmccraig/rsxml | lib/rsxml/namespace.rb | Rsxml.Namespace.exploded_namespace_declarations | def exploded_namespace_declarations(ns)
Hash[ns.map do |prefix, uri|
if prefix==""
["xmlns", uri]
else
[[prefix, "xmlns"], uri]
end
end]
end | ruby | def exploded_namespace_declarations(ns)
Hash[ns.map do |prefix, uri|
if prefix==""
["xmlns", uri]
else
[[prefix, "xmlns"], uri]
end
end]
end | [
"def",
"exploded_namespace_declarations",
"(",
"ns",
")",
"Hash",
"[",
"ns",
".",
"map",
"do",
"|",
"prefix",
",",
"uri",
"|",
"if",
"prefix",
"==",
"\"\"",
"[",
"\"xmlns\"",
",",
"uri",
"]",
"else",
"[",
"[",
"prefix",
",",
"\"xmlns\"",
"]",
",",
"uri",
"]",
"end",
"end",
"]",
"end"
] | produce a Hash of namespace declaration attributes with exploded
QNames, from
a Hash of namespace prefix bindings | [
"produce",
"a",
"Hash",
"of",
"namespace",
"declaration",
"attributes",
"with",
"exploded",
"QNames",
"from",
"a",
"Hash",
"of",
"namespace",
"prefix",
"bindings"
] | 3699c186f01be476a5942d64cd5c39f4d6bbe175 | https://github.com/mccraigmccraig/rsxml/blob/3699c186f01be476a5942d64cd5c39f4d6bbe175/lib/rsxml/namespace.rb#L149-L157 | train |
mccraigmccraig/rsxml | lib/rsxml/namespace.rb | Rsxml.Namespace.namespace_attributes | def namespace_attributes(ns)
Hash[ns.map do |prefix, uri|
if prefix==""
["xmlns", uri]
else
[["xmlns", prefix].join(":"), uri]
end
end]
end | ruby | def namespace_attributes(ns)
Hash[ns.map do |prefix, uri|
if prefix==""
["xmlns", uri]
else
[["xmlns", prefix].join(":"), uri]
end
end]
end | [
"def",
"namespace_attributes",
"(",
"ns",
")",
"Hash",
"[",
"ns",
".",
"map",
"do",
"|",
"prefix",
",",
"uri",
"|",
"if",
"prefix",
"==",
"\"\"",
"[",
"\"xmlns\"",
",",
"uri",
"]",
"else",
"[",
"[",
"\"xmlns\"",
",",
"prefix",
"]",
".",
"join",
"(",
"\":\"",
")",
",",
"uri",
"]",
"end",
"end",
"]",
"end"
] | produces a Hash of compact namespace attributes from a
Hash of namespace bindings | [
"produces",
"a",
"Hash",
"of",
"compact",
"namespace",
"attributes",
"from",
"a",
"Hash",
"of",
"namespace",
"bindings"
] | 3699c186f01be476a5942d64cd5c39f4d6bbe175 | https://github.com/mccraigmccraig/rsxml/blob/3699c186f01be476a5942d64cd5c39f4d6bbe175/lib/rsxml/namespace.rb#L161-L169 | train |
mccraigmccraig/rsxml | lib/rsxml/namespace.rb | Rsxml.Namespace.merge_namespace_bindings | def merge_namespace_bindings(ns1, ns2)
m = ns1.clone
ns2.each do |k,v|
raise "bindings clash: '#{k}'=>'#{m[k]}' , '#{k}'=>'#{v}'" if m.has_key?(k) && m[k]!=v
m[k]=v
end
m
end | ruby | def merge_namespace_bindings(ns1, ns2)
m = ns1.clone
ns2.each do |k,v|
raise "bindings clash: '#{k}'=>'#{m[k]}' , '#{k}'=>'#{v}'" if m.has_key?(k) && m[k]!=v
m[k]=v
end
m
end | [
"def",
"merge_namespace_bindings",
"(",
"ns1",
",",
"ns2",
")",
"m",
"=",
"ns1",
".",
"clone",
"ns2",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"raise",
"\"bindings clash: '#{k}'=>'#{m[k]}' , '#{k}'=>'#{v}'\"",
"if",
"m",
".",
"has_key?",
"(",
"k",
")",
"&&",
"m",
"[",
"k",
"]",
"!=",
"v",
"m",
"[",
"k",
"]",
"=",
"v",
"end",
"m",
"end"
] | merges two sets of namespace bindings, raising error on clash | [
"merges",
"two",
"sets",
"of",
"namespace",
"bindings",
"raising",
"error",
"on",
"clash"
] | 3699c186f01be476a5942d64cd5c39f4d6bbe175 | https://github.com/mccraigmccraig/rsxml/blob/3699c186f01be476a5942d64cd5c39f4d6bbe175/lib/rsxml/namespace.rb#L172-L179 | train |
LRDesign/Caliph | lib/caliph/shell.rb | Caliph.Shell.spawn_process | def spawn_process(command_line)
host_stdout, cmd_stdout = IO.pipe
host_stderr, cmd_stderr = IO.pipe
pid = Process.spawn(command_line.command_environment, command_line.command, :out => cmd_stdout, :err => cmd_stderr)
cmd_stdout.close
cmd_stderr.close
return pid, host_stdout, host_stderr
end | ruby | def spawn_process(command_line)
host_stdout, cmd_stdout = IO.pipe
host_stderr, cmd_stderr = IO.pipe
pid = Process.spawn(command_line.command_environment, command_line.command, :out => cmd_stdout, :err => cmd_stderr)
cmd_stdout.close
cmd_stderr.close
return pid, host_stdout, host_stderr
end | [
"def",
"spawn_process",
"(",
"command_line",
")",
"host_stdout",
",",
"cmd_stdout",
"=",
"IO",
".",
"pipe",
"host_stderr",
",",
"cmd_stderr",
"=",
"IO",
".",
"pipe",
"pid",
"=",
"Process",
".",
"spawn",
"(",
"command_line",
".",
"command_environment",
",",
"command_line",
".",
"command",
",",
":out",
"=>",
"cmd_stdout",
",",
":err",
"=>",
"cmd_stderr",
")",
"cmd_stdout",
".",
"close",
"cmd_stderr",
".",
"close",
"return",
"pid",
",",
"host_stdout",
",",
"host_stderr",
"end"
] | Creates a process to run a command. Handles connecting pipes to stardard
streams, launching the process and returning a pid for it.
@return [pid, host_stdout, host_stderr] the process id and streams
associated with the child process | [
"Creates",
"a",
"process",
"to",
"run",
"a",
"command",
".",
"Handles",
"connecting",
"pipes",
"to",
"stardard",
"streams",
"launching",
"the",
"process",
"and",
"returning",
"a",
"pid",
"for",
"it",
"."
] | 9ad99fb72f75b87fa76eb28d4fc3ab811b29bb99 | https://github.com/LRDesign/Caliph/blob/9ad99fb72f75b87fa76eb28d4fc3ab811b29bb99/lib/caliph/shell.rb#L77-L86 | train |
LRDesign/Caliph | lib/caliph/shell.rb | Caliph.Shell.execute | def execute(command_line)
result = collect_result(command_line, *spawn_process(command_line))
result.wait
result
end | ruby | def execute(command_line)
result = collect_result(command_line, *spawn_process(command_line))
result.wait
result
end | [
"def",
"execute",
"(",
"command_line",
")",
"result",
"=",
"collect_result",
"(",
"command_line",
",",
"spawn_process",
"(",
"command_line",
")",
")",
"result",
".",
"wait",
"result",
"end"
] | Run the command, wait for termination, and collect the results.
Returns an instance of CommandRunResult that contains the output
and exit code of the command. | [
"Run",
"the",
"command",
"wait",
"for",
"termination",
"and",
"collect",
"the",
"results",
".",
"Returns",
"an",
"instance",
"of",
"CommandRunResult",
"that",
"contains",
"the",
"output",
"and",
"exit",
"code",
"of",
"the",
"command",
"."
] | 9ad99fb72f75b87fa76eb28d4fc3ab811b29bb99 | https://github.com/LRDesign/Caliph/blob/9ad99fb72f75b87fa76eb28d4fc3ab811b29bb99/lib/caliph/shell.rb#L92-L96 | train |
LRDesign/Caliph | lib/caliph/shell.rb | Caliph.Shell.run_as_replacement | def run_as_replacement(*args, &block)
command_line = normalize_command_line(*args, &block)
report "Ceding execution to: "
report command_line.string_format
Process.exec(command_line.command_environment, command_line.command)
end | ruby | def run_as_replacement(*args, &block)
command_line = normalize_command_line(*args, &block)
report "Ceding execution to: "
report command_line.string_format
Process.exec(command_line.command_environment, command_line.command)
end | [
"def",
"run_as_replacement",
"(",
"*",
"args",
",",
"&",
"block",
")",
"command_line",
"=",
"normalize_command_line",
"(",
"args",
",",
"block",
")",
"report",
"\"Ceding execution to: \"",
"report",
"command_line",
".",
"string_format",
"Process",
".",
"exec",
"(",
"command_line",
".",
"command_environment",
",",
"command_line",
".",
"command",
")",
"end"
] | Completely replace the running process with a command. Good for setting
up a command and then running it, without worrying about what happens
after that. Uses `exec` under the hood.
@macro normalized
@example Using replace_us
# The last thing we'll ever do:
shell.run_as_replacement('echo', "Everything is okay")
# don't worry, we never get here.
shell.run("sudo", "shutdown -h now") | [
"Completely",
"replace",
"the",
"running",
"process",
"with",
"a",
"command",
".",
"Good",
"for",
"setting",
"up",
"a",
"command",
"and",
"then",
"running",
"it",
"without",
"worrying",
"about",
"what",
"happens",
"after",
"that",
".",
"Uses",
"exec",
"under",
"the",
"hood",
"."
] | 9ad99fb72f75b87fa76eb28d4fc3ab811b29bb99 | https://github.com/LRDesign/Caliph/blob/9ad99fb72f75b87fa76eb28d4fc3ab811b29bb99/lib/caliph/shell.rb#L134-L140 | train |
LRDesign/Caliph | lib/caliph/shell.rb | Caliph.Shell.run_detached | def run_detached(*args, &block)
command_line = normalize_command_line(*args, &block)
pid, out, err = spawn_process(command_line)
Process.detach(pid)
return collect_result(command_line, pid, out, err)
end | ruby | def run_detached(*args, &block)
command_line = normalize_command_line(*args, &block)
pid, out, err = spawn_process(command_line)
Process.detach(pid)
return collect_result(command_line, pid, out, err)
end | [
"def",
"run_detached",
"(",
"*",
"args",
",",
"&",
"block",
")",
"command_line",
"=",
"normalize_command_line",
"(",
"args",
",",
"block",
")",
"pid",
",",
"out",
",",
"err",
"=",
"spawn_process",
"(",
"command_line",
")",
"Process",
".",
"detach",
"(",
"pid",
")",
"return",
"collect_result",
"(",
"command_line",
",",
"pid",
",",
"out",
",",
"err",
")",
"end"
] | Run the command in the background. The command can survive the caller.
Works, for instance, to kick off some long running processes that we
don't care about. Note that this isn't quite full daemonization - we
don't close the streams of the other process, or scrub its environment or
anything.
@macro normalized | [
"Run",
"the",
"command",
"in",
"the",
"background",
".",
"The",
"command",
"can",
"survive",
"the",
"caller",
".",
"Works",
"for",
"instance",
"to",
"kick",
"off",
"some",
"long",
"running",
"processes",
"that",
"we",
"don",
"t",
"care",
"about",
".",
"Note",
"that",
"this",
"isn",
"t",
"quite",
"full",
"daemonization",
"-",
"we",
"don",
"t",
"close",
"the",
"streams",
"of",
"the",
"other",
"process",
"or",
"scrub",
"its",
"environment",
"or",
"anything",
"."
] | 9ad99fb72f75b87fa76eb28d4fc3ab811b29bb99 | https://github.com/LRDesign/Caliph/blob/9ad99fb72f75b87fa76eb28d4fc3ab811b29bb99/lib/caliph/shell.rb#L149-L155 | train |
neiljohari/scram | lib/scram/concerns/holder.rb | Scram.Holder.can? | def can? action, target
target = target.to_s if target.is_a? Symbol
action = action.to_s
# Checks policies in priority order for explicit allow or deny.
policies.sort_by(&:priority).reverse.each do |policy|
opinion = policy.can?(self, action, target)
return opinion.to_bool if %i[allow deny].include? opinion
end
return false
end | ruby | def can? action, target
target = target.to_s if target.is_a? Symbol
action = action.to_s
# Checks policies in priority order for explicit allow or deny.
policies.sort_by(&:priority).reverse.each do |policy|
opinion = policy.can?(self, action, target)
return opinion.to_bool if %i[allow deny].include? opinion
end
return false
end | [
"def",
"can?",
"action",
",",
"target",
"target",
"=",
"target",
".",
"to_s",
"if",
"target",
".",
"is_a?",
"Symbol",
"action",
"=",
"action",
".",
"to_s",
"# Checks policies in priority order for explicit allow or deny.",
"policies",
".",
"sort_by",
"(",
":priority",
")",
".",
"reverse",
".",
"each",
"do",
"|",
"policy",
"|",
"opinion",
"=",
"policy",
".",
"can?",
"(",
"self",
",",
"action",
",",
"target",
")",
"return",
"opinion",
".",
"to_bool",
"if",
"%i[",
"allow",
"deny",
"]",
".",
"include?",
"opinion",
"end",
"return",
"false",
"end"
] | Checks if this holder can perform some action on an object by checking the Holder's policies
@param action [String] What the user is trying to do to obj
@param obj [Object] The receiver of the action
@return [Boolean] Whether or not holder can action to object. We define a full abstainment as a failure to perform the action. | [
"Checks",
"if",
"this",
"holder",
"can",
"perform",
"some",
"action",
"on",
"an",
"object",
"by",
"checking",
"the",
"Holder",
"s",
"policies"
] | df3e48e9e9cab4b363b1370df5991319d21c256d | https://github.com/neiljohari/scram/blob/df3e48e9e9cab4b363b1370df5991319d21c256d/lib/scram/concerns/holder.rb#L23-L34 | train |
kevgo/sections_rails | lib/sections_rails/section.rb | SectionsRails.Section.referenced_sections | def referenced_sections recursive = true
result = PartialParser.find_sections partial_content
# Find all sections within the already known sections.
if recursive
i = -1
while (i += 1) < result.size
Section.new(result[i]).referenced_sections(false).each do |referenced_section|
result << referenced_section unless result.include? referenced_section
end
end
end
result.sort!
end | ruby | def referenced_sections recursive = true
result = PartialParser.find_sections partial_content
# Find all sections within the already known sections.
if recursive
i = -1
while (i += 1) < result.size
Section.new(result[i]).referenced_sections(false).each do |referenced_section|
result << referenced_section unless result.include? referenced_section
end
end
end
result.sort!
end | [
"def",
"referenced_sections",
"recursive",
"=",
"true",
"result",
"=",
"PartialParser",
".",
"find_sections",
"partial_content",
"# Find all sections within the already known sections.",
"if",
"recursive",
"i",
"=",
"-",
"1",
"while",
"(",
"i",
"+=",
"1",
")",
"<",
"result",
".",
"size",
"Section",
".",
"new",
"(",
"result",
"[",
"i",
"]",
")",
".",
"referenced_sections",
"(",
"false",
")",
".",
"each",
"do",
"|",
"referenced_section",
"|",
"result",
"<<",
"referenced_section",
"unless",
"result",
".",
"include?",
"referenced_section",
"end",
"end",
"end",
"result",
".",
"sort!",
"end"
] | Returns the sections that this section references.
If 'recursive = true' is given, searches recursively for sections referenced by the referenced sections.
Otherwise, simply returns the sections that are referenced by this section. | [
"Returns",
"the",
"sections",
"that",
"this",
"section",
"references",
".",
"If",
"recursive",
"=",
"true",
"is",
"given",
"searches",
"recursively",
"for",
"sections",
"referenced",
"by",
"the",
"referenced",
"sections",
".",
"Otherwise",
"simply",
"returns",
"the",
"sections",
"that",
"are",
"referenced",
"by",
"this",
"section",
"."
] | e6e451e0888e16cc50978fe5b69797f47fdbe481 | https://github.com/kevgo/sections_rails/blob/e6e451e0888e16cc50978fe5b69797f47fdbe481/lib/sections_rails/section.rb#L42-L55 | train |
kevgo/sections_rails | lib/sections_rails/section.rb | SectionsRails.Section.render | def render &block
raise "Section #{folder_filepath} doesn't exist." unless Dir.exists? folder_filepath
result = []
render_assets result if Rails.application.config.assets.compile
render_partial result, &block
result.join("\n").html_safe
end | ruby | def render &block
raise "Section #{folder_filepath} doesn't exist." unless Dir.exists? folder_filepath
result = []
render_assets result if Rails.application.config.assets.compile
render_partial result, &block
result.join("\n").html_safe
end | [
"def",
"render",
"&",
"block",
"raise",
"\"Section #{folder_filepath} doesn't exist.\"",
"unless",
"Dir",
".",
"exists?",
"folder_filepath",
"result",
"=",
"[",
"]",
"render_assets",
"result",
"if",
"Rails",
".",
"application",
".",
"config",
".",
"assets",
".",
"compile",
"render_partial",
"result",
",",
"block",
"result",
".",
"join",
"(",
"\"\\n\"",
")",
".",
"html_safe",
"end"
] | Renders this section, i.e. returns the HTML for this section. | [
"Renders",
"this",
"section",
"i",
".",
"e",
".",
"returns",
"the",
"HTML",
"for",
"this",
"section",
"."
] | e6e451e0888e16cc50978fe5b69797f47fdbe481 | https://github.com/kevgo/sections_rails/blob/e6e451e0888e16cc50978fe5b69797f47fdbe481/lib/sections_rails/section.rb#L59-L66 | train |
Subsets and Splits