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 |
---|---|---|---|---|---|---|---|---|---|---|---|
notCalle/ruby-keytree | lib/key_tree/path.rb | KeyTree.Path.prefix? | def prefix?(other)
other = other.to_key_path
return false if other.length > length
key_enum = each
other.all? { |other_key| key_enum.next == other_key }
end | ruby | def prefix?(other)
other = other.to_key_path
return false if other.length > length
key_enum = each
other.all? { |other_key| key_enum.next == other_key }
end | [
"def",
"prefix?",
"(",
"other",
")",
"other",
"=",
"other",
".",
"to_key_path",
"return",
"false",
"if",
"other",
".",
"length",
">",
"length",
"key_enum",
"=",
"each",
"other",
".",
"all?",
"{",
"|",
"other_key",
"|",
"key_enum",
".",
"next",
"==",
"other_key",
"}",
"end"
] | Is +other+ a prefix?
:call-seq:
prefix?(other) => boolean | [
"Is",
"+",
"other",
"+",
"a",
"prefix?"
] | 1a88c902c8b5d14f21fd350338776fc094eae8e3 | https://github.com/notCalle/ruby-keytree/blob/1a88c902c8b5d14f21fd350338776fc094eae8e3/lib/key_tree/path.rb#L79-L85 | train |
gemeraldbeanstalk/stalk_climber | lib/stalk_climber/climber.rb | StalkClimber.Climber.max_job_ids | def max_job_ids
connection_pairs = connection_pool.connections.map do |connection|
[connection, connection.max_job_id]
end
return Hash[connection_pairs]
end | ruby | def max_job_ids
connection_pairs = connection_pool.connections.map do |connection|
[connection, connection.max_job_id]
end
return Hash[connection_pairs]
end | [
"def",
"max_job_ids",
"connection_pairs",
"=",
"connection_pool",
".",
"connections",
".",
"map",
"do",
"|",
"connection",
"|",
"[",
"connection",
",",
"connection",
".",
"max_job_id",
"]",
"end",
"return",
"Hash",
"[",
"connection_pairs",
"]",
"end"
] | Creates a new Climber instance, optionally yielding the instance for
configuration if a block is given
Climber.new('beanstalk://localhost:11300', 'stalk_climber')
#=> #<StalkClimber::Job beanstalk_addresses="beanstalk://localhost:11300" test_tube="stalk_climber">
:call-seq:
max_job_ids() => Hash{Beaneater::Connection => Integer}
Returns a Hash with connections as keys and max_job_ids as values
climber = Climber.new('beanstalk://localhost:11300', 'stalk_climber')
climber.max_job_ids
#=> {#<Beaneater::Connection host="localhost" port=11300>=>1183} | [
"Creates",
"a",
"new",
"Climber",
"instance",
"optionally",
"yielding",
"the",
"instance",
"for",
"configuration",
"if",
"a",
"block",
"is",
"given"
] | d22f74bbae864ca2771d15621ccbf29d8e86521a | https://github.com/gemeraldbeanstalk/stalk_climber/blob/d22f74bbae864ca2771d15621ccbf29d8e86521a/lib/stalk_climber/climber.rb#L52-L57 | train |
johnny/role-auth | lib/role-auth/parser.rb | RoleAuth.Parser.task | def task(name, options = {})
options[:is] = options[:is].is_a?(Array) ? options[:is] : [options[:is]].compact
@tasks[name] = Task.new(name,options)
end | ruby | def task(name, options = {})
options[:is] = options[:is].is_a?(Array) ? options[:is] : [options[:is]].compact
@tasks[name] = Task.new(name,options)
end | [
"def",
"task",
"(",
"name",
",",
"options",
"=",
"{",
"}",
")",
"options",
"[",
":is",
"]",
"=",
"options",
"[",
":is",
"]",
".",
"is_a?",
"(",
"Array",
")",
"?",
"options",
"[",
":is",
"]",
":",
"[",
"options",
"[",
":is",
"]",
"]",
".",
"compact",
"@tasks",
"[",
"name",
"]",
"=",
"Task",
".",
"new",
"(",
"name",
",",
"options",
")",
"end"
] | Define a new task.
@example Define an entirely new task
task :push
@example Define a publish task
task :publish, :is => :update, :if => only_changed(:published)
@example Define a joined manage task
task :manage, :is => [:update, :create, :delete]
@see #can More examples for the :if option
@see DEFAULT_TASKS Default tasks
@param [Symbol] name The name of the task.
@param [Hash] options
@option options [Symbol, Array<Symbol>] :is Optional parent tasks. The options of the parents will be inherited.
@option options [String, Hash, Array<String,Hash>] :if The conditions for this task. | [
"Define",
"a",
"new",
"task",
"."
] | 2f22e7e7766647483ca0f793be52e27fb8f96a87 | https://github.com/johnny/role-auth/blob/2f22e7e7766647483ca0f793be52e27fb8f96a87/lib/role-auth/parser.rb#L105-L108 | train |
johnny/role-auth | lib/role-auth/parser.rb | RoleAuth.Parser.add_permission | def add_permission(target, *args)
raise '#can and #can_not have to be used inside a role block' unless @role
options = args.last.is_a?(Hash) ? args.pop : {}
tasks = []
models = []
models << args.pop if args.last == :any
args.each {|arg| arg.is_a?(Symbol) ? tasks << arg : models << arg}
tasks.each do |task|
models.each do |model|
if permission = target[task][model][@role]
permission.load_options(options)
else
target[task][model][@role] = Permission.new(@role, task, model, options)
end
end
end
end | ruby | def add_permission(target, *args)
raise '#can and #can_not have to be used inside a role block' unless @role
options = args.last.is_a?(Hash) ? args.pop : {}
tasks = []
models = []
models << args.pop if args.last == :any
args.each {|arg| arg.is_a?(Symbol) ? tasks << arg : models << arg}
tasks.each do |task|
models.each do |model|
if permission = target[task][model][@role]
permission.load_options(options)
else
target[task][model][@role] = Permission.new(@role, task, model, options)
end
end
end
end | [
"def",
"add_permission",
"(",
"target",
",",
"*",
"args",
")",
"raise",
"'#can and #can_not have to be used inside a role block'",
"unless",
"@role",
"options",
"=",
"args",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"args",
".",
"pop",
":",
"{",
"}",
"tasks",
"=",
"[",
"]",
"models",
"=",
"[",
"]",
"models",
"<<",
"args",
".",
"pop",
"if",
"args",
".",
"last",
"==",
":any",
"args",
".",
"each",
"{",
"|",
"arg",
"|",
"arg",
".",
"is_a?",
"(",
"Symbol",
")",
"?",
"tasks",
"<<",
"arg",
":",
"models",
"<<",
"arg",
"}",
"tasks",
".",
"each",
"do",
"|",
"task",
"|",
"models",
".",
"each",
"do",
"|",
"model",
"|",
"if",
"permission",
"=",
"target",
"[",
"task",
"]",
"[",
"model",
"]",
"[",
"@role",
"]",
"permission",
".",
"load_options",
"(",
"options",
")",
"else",
"target",
"[",
"task",
"]",
"[",
"model",
"]",
"[",
"@role",
"]",
"=",
"Permission",
".",
"new",
"(",
"@role",
",",
"task",
",",
"model",
",",
"options",
")",
"end",
"end",
"end",
"end"
] | Creates an internal Permission
@param [Hash] target Either the permissions or the restrictions hash
@param [Array] args The function arguments to the #can, #can_not methods | [
"Creates",
"an",
"internal",
"Permission"
] | 2f22e7e7766647483ca0f793be52e27fb8f96a87 | https://github.com/johnny/role-auth/blob/2f22e7e7766647483ca0f793be52e27fb8f96a87/lib/role-auth/parser.rb#L132-L150 | train |
johnny/role-auth | lib/role-auth/parser.rb | RoleAuth.Parser.process_tasks | def process_tasks
@tasks.each_value do |task|
task.options[:ancestors] = []
set_ancestor_tasks(task)
set_alternative_tasks(task) if @permissions.key? task.name
end
end | ruby | def process_tasks
@tasks.each_value do |task|
task.options[:ancestors] = []
set_ancestor_tasks(task)
set_alternative_tasks(task) if @permissions.key? task.name
end
end | [
"def",
"process_tasks",
"@tasks",
".",
"each_value",
"do",
"|",
"task",
"|",
"task",
".",
"options",
"[",
":ancestors",
"]",
"=",
"[",
"]",
"set_ancestor_tasks",
"(",
"task",
")",
"set_alternative_tasks",
"(",
"task",
")",
"if",
"@permissions",
".",
"key?",
"task",
".",
"name",
"end",
"end"
] | Flattens the tasks. It sets the ancestors and the alternative tasks | [
"Flattens",
"the",
"tasks",
".",
"It",
"sets",
"the",
"ancestors",
"and",
"the",
"alternative",
"tasks"
] | 2f22e7e7766647483ca0f793be52e27fb8f96a87 | https://github.com/johnny/role-auth/blob/2f22e7e7766647483ca0f793be52e27fb8f96a87/lib/role-auth/parser.rb#L153-L159 | train |
johnny/role-auth | lib/role-auth/parser.rb | RoleAuth.Parser.set_ancestor_tasks | def set_ancestor_tasks(task, ancestor = nil)
task.options[:ancestors] += (ancestor || task).options[:is]
(ancestor || task).options[:is].each do |parent_task|
set_ancestor_tasks(task, @tasks[parent_task])
end
end | ruby | def set_ancestor_tasks(task, ancestor = nil)
task.options[:ancestors] += (ancestor || task).options[:is]
(ancestor || task).options[:is].each do |parent_task|
set_ancestor_tasks(task, @tasks[parent_task])
end
end | [
"def",
"set_ancestor_tasks",
"(",
"task",
",",
"ancestor",
"=",
"nil",
")",
"task",
".",
"options",
"[",
":ancestors",
"]",
"+=",
"(",
"ancestor",
"||",
"task",
")",
".",
"options",
"[",
":is",
"]",
"(",
"ancestor",
"||",
"task",
")",
".",
"options",
"[",
":is",
"]",
".",
"each",
"do",
"|",
"parent_task",
"|",
"set_ancestor_tasks",
"(",
"task",
",",
"@tasks",
"[",
"parent_task",
"]",
")",
"end",
"end"
] | Set the ancestors on task.
@param [Task] task The task for which the ancestors are set
@param [Task] ancestor The ancestor to process. This is the recursive parameter | [
"Set",
"the",
"ancestors",
"on",
"task",
"."
] | 2f22e7e7766647483ca0f793be52e27fb8f96a87 | https://github.com/johnny/role-auth/blob/2f22e7e7766647483ca0f793be52e27fb8f96a87/lib/role-auth/parser.rb#L165-L170 | train |
johnny/role-auth | lib/role-auth/parser.rb | RoleAuth.Parser.set_alternative_tasks | def set_alternative_tasks(task, ancestor = nil)
(ancestor || task).options[:is].each do |task_name|
if @permissions.key? task_name
(@tasks[task_name].options[:alternatives] ||= []) << task.name
else
set_alternative_tasks(task, @tasks[task_name])
end
end
end | ruby | def set_alternative_tasks(task, ancestor = nil)
(ancestor || task).options[:is].each do |task_name|
if @permissions.key? task_name
(@tasks[task_name].options[:alternatives] ||= []) << task.name
else
set_alternative_tasks(task, @tasks[task_name])
end
end
end | [
"def",
"set_alternative_tasks",
"(",
"task",
",",
"ancestor",
"=",
"nil",
")",
"(",
"ancestor",
"||",
"task",
")",
".",
"options",
"[",
":is",
"]",
".",
"each",
"do",
"|",
"task_name",
"|",
"if",
"@permissions",
".",
"key?",
"task_name",
"(",
"@tasks",
"[",
"task_name",
"]",
".",
"options",
"[",
":alternatives",
"]",
"||=",
"[",
"]",
")",
"<<",
"task",
".",
"name",
"else",
"set_alternative_tasks",
"(",
"task",
",",
"@tasks",
"[",
"task_name",
"]",
")",
"end",
"end",
"end"
] | Set the alternatives of the task.
Alternatives are the nearest ancestors, which are used in permission definitions.
@param [Task] task The task for which the alternatives are set
@param [Task] ancestor The ancestor to process. This is the recursive parameter | [
"Set",
"the",
"alternatives",
"of",
"the",
"task",
".",
"Alternatives",
"are",
"the",
"nearest",
"ancestors",
"which",
"are",
"used",
"in",
"permission",
"definitions",
"."
] | 2f22e7e7766647483ca0f793be52e27fb8f96a87 | https://github.com/johnny/role-auth/blob/2f22e7e7766647483ca0f793be52e27fb8f96a87/lib/role-auth/parser.rb#L177-L185 | train |
johnny/role-auth | lib/role-auth/parser.rb | RoleAuth.Parser.set_descendant_roles | def set_descendant_roles(descendant_role, ancestor_role = nil)
role = ancestor_role || descendant_role
return unless role[:is]
role[:is].each do |role_name|
(@roles[role_name][:descendants] ||= []) << descendant_role[:name]
set_descendant_roles(descendant_role, @roles[role_name])
end
end | ruby | def set_descendant_roles(descendant_role, ancestor_role = nil)
role = ancestor_role || descendant_role
return unless role[:is]
role[:is].each do |role_name|
(@roles[role_name][:descendants] ||= []) << descendant_role[:name]
set_descendant_roles(descendant_role, @roles[role_name])
end
end | [
"def",
"set_descendant_roles",
"(",
"descendant_role",
",",
"ancestor_role",
"=",
"nil",
")",
"role",
"=",
"ancestor_role",
"||",
"descendant_role",
"return",
"unless",
"role",
"[",
":is",
"]",
"role",
"[",
":is",
"]",
".",
"each",
"do",
"|",
"role_name",
"|",
"(",
"@roles",
"[",
"role_name",
"]",
"[",
":descendants",
"]",
"||=",
"[",
"]",
")",
"<<",
"descendant_role",
"[",
":name",
"]",
"set_descendant_roles",
"(",
"descendant_role",
",",
"@roles",
"[",
"role_name",
"]",
")",
"end",
"end"
] | Set the descendant_role as a descendant of the ancestor | [
"Set",
"the",
"descendant_role",
"as",
"a",
"descendant",
"of",
"the",
"ancestor"
] | 2f22e7e7766647483ca0f793be52e27fb8f96a87 | https://github.com/johnny/role-auth/blob/2f22e7e7766647483ca0f793be52e27fb8f96a87/lib/role-auth/parser.rb#L193-L201 | train |
anga/BetterRailsDebugger | app/models/better_rails_debugger/group_instance.rb | BetterRailsDebugger.GroupInstance.big_classes | def big_classes(max_size=1.megabytes)
return @big_classes if @big_classes
@big_classes = {}
ObjectInformation.where(:group_instance_id => self.id, :memsize.gt => max_size).all.each do |object|
@big_classes[object.class_name] ||= {total_mem: 0, average: 0, count: 0}
@big_classes[object.class_name][:total_mem] += object.memsize
@big_classes[object.class_name][:count] += 1
end
@big_classes.each_pair do |klass, hash|
@big_classes[klass][:average] = @big_classes[klass][:total_mem] / @big_classes[klass][:count]
end
@big_classes
end | ruby | def big_classes(max_size=1.megabytes)
return @big_classes if @big_classes
@big_classes = {}
ObjectInformation.where(:group_instance_id => self.id, :memsize.gt => max_size).all.each do |object|
@big_classes[object.class_name] ||= {total_mem: 0, average: 0, count: 0}
@big_classes[object.class_name][:total_mem] += object.memsize
@big_classes[object.class_name][:count] += 1
end
@big_classes.each_pair do |klass, hash|
@big_classes[klass][:average] = @big_classes[klass][:total_mem] / @big_classes[klass][:count]
end
@big_classes
end | [
"def",
"big_classes",
"(",
"max_size",
"=",
"1",
".",
"megabytes",
")",
"return",
"@big_classes",
"if",
"@big_classes",
"@big_classes",
"=",
"{",
"}",
"ObjectInformation",
".",
"where",
"(",
":group_instance_id",
"=>",
"self",
".",
"id",
",",
":memsize",
".",
"gt",
"=>",
"max_size",
")",
".",
"all",
".",
"each",
"do",
"|",
"object",
"|",
"@big_classes",
"[",
"object",
".",
"class_name",
"]",
"||=",
"{",
"total_mem",
":",
"0",
",",
"average",
":",
"0",
",",
"count",
":",
"0",
"}",
"@big_classes",
"[",
"object",
".",
"class_name",
"]",
"[",
":total_mem",
"]",
"+=",
"object",
".",
"memsize",
"@big_classes",
"[",
"object",
".",
"class_name",
"]",
"[",
":count",
"]",
"+=",
"1",
"end",
"@big_classes",
".",
"each_pair",
"do",
"|",
"klass",
",",
"hash",
"|",
"@big_classes",
"[",
"klass",
"]",
"[",
":average",
"]",
"=",
"@big_classes",
"[",
"klass",
"]",
"[",
":total_mem",
"]",
"/",
"@big_classes",
"[",
"klass",
"]",
"[",
":count",
"]",
"end",
"@big_classes",
"end"
] | Return an array of hashed that contains some information about the classes that consume more than `max_size` bytess | [
"Return",
"an",
"array",
"of",
"hashed",
"that",
"contains",
"some",
"information",
"about",
"the",
"classes",
"that",
"consume",
"more",
"than",
"max_size",
"bytess"
] | 2ac7af13b8ee12483bd9a92680d8f43042f1f1d5 | https://github.com/anga/BetterRailsDebugger/blob/2ac7af13b8ee12483bd9a92680d8f43042f1f1d5/app/models/better_rails_debugger/group_instance.rb#L72-L84 | train |
mrsimonfletcher/roroacms | app/controllers/roroacms/admin/terms_controller.rb | Roroacms.Admin::TermsController.categories | def categories
# add breadcrumb and set title
add_breadcrumb I18n.t("generic.categories"), :admin_article_categories_path, :title => I18n.t("controllers.admin.terms.categories.breadcrumb_title")
set_title(I18n.t("generic.categories"))
@type = 'category'
@records = Term.term_cats('category', nil, true)
# render view template as it is the same as the tag view
render 'view'
end | ruby | def categories
# add breadcrumb and set title
add_breadcrumb I18n.t("generic.categories"), :admin_article_categories_path, :title => I18n.t("controllers.admin.terms.categories.breadcrumb_title")
set_title(I18n.t("generic.categories"))
@type = 'category'
@records = Term.term_cats('category', nil, true)
# render view template as it is the same as the tag view
render 'view'
end | [
"def",
"categories",
"add_breadcrumb",
"I18n",
".",
"t",
"(",
"\"generic.categories\"",
")",
",",
":admin_article_categories_path",
",",
":title",
"=>",
"I18n",
".",
"t",
"(",
"\"controllers.admin.terms.categories.breadcrumb_title\"",
")",
"set_title",
"(",
"I18n",
".",
"t",
"(",
"\"generic.categories\"",
")",
")",
"@type",
"=",
"'category'",
"@records",
"=",
"Term",
".",
"term_cats",
"(",
"'category'",
",",
"nil",
",",
"true",
")",
"render",
"'view'",
"end"
] | displays all the current categories and creates a new category object for creating a new one | [
"displays",
"all",
"the",
"current",
"categories",
"and",
"creates",
"a",
"new",
"category",
"object",
"for",
"creating",
"a",
"new",
"one"
] | 62654a2f2a48e3adb3105f4dafb6e315b460eaf4 | https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/terms_controller.rb#L7-L16 | train |
mrsimonfletcher/roroacms | app/controllers/roroacms/admin/terms_controller.rb | Roroacms.Admin::TermsController.create | def create
@category = Term.new(term_params)
redirect_url = Term.get_redirect_url(params)
respond_to do |format|
if @category.save
@term_anatomy = @category.create_term_anatomy(:taxonomy => params[:type_taxonomy])
format.html { redirect_to URI.parse(redirect_url).path, only_path: true, notice: I18n.t("controllers.admin.terms.create.flash.success", term: Term.get_type_of_term(params)) }
else
flash[:error] = I18n.t("controllers.admin.terms.create.flash.error")
format.html { redirect_to URI.parse(redirect_url).path, only_path: true }
end
end
end | ruby | def create
@category = Term.new(term_params)
redirect_url = Term.get_redirect_url(params)
respond_to do |format|
if @category.save
@term_anatomy = @category.create_term_anatomy(:taxonomy => params[:type_taxonomy])
format.html { redirect_to URI.parse(redirect_url).path, only_path: true, notice: I18n.t("controllers.admin.terms.create.flash.success", term: Term.get_type_of_term(params)) }
else
flash[:error] = I18n.t("controllers.admin.terms.create.flash.error")
format.html { redirect_to URI.parse(redirect_url).path, only_path: true }
end
end
end | [
"def",
"create",
"@category",
"=",
"Term",
".",
"new",
"(",
"term_params",
")",
"redirect_url",
"=",
"Term",
".",
"get_redirect_url",
"(",
"params",
")",
"respond_to",
"do",
"|",
"format",
"|",
"if",
"@category",
".",
"save",
"@term_anatomy",
"=",
"@category",
".",
"create_term_anatomy",
"(",
":taxonomy",
"=>",
"params",
"[",
":type_taxonomy",
"]",
")",
"format",
".",
"html",
"{",
"redirect_to",
"URI",
".",
"parse",
"(",
"redirect_url",
")",
".",
"path",
",",
"only_path",
":",
"true",
",",
"notice",
":",
"I18n",
".",
"t",
"(",
"\"controllers.admin.terms.create.flash.success\"",
",",
"term",
":",
"Term",
".",
"get_type_of_term",
"(",
"params",
")",
")",
"}",
"else",
"flash",
"[",
":error",
"]",
"=",
"I18n",
".",
"t",
"(",
"\"controllers.admin.terms.create.flash.error\"",
")",
"format",
".",
"html",
"{",
"redirect_to",
"URI",
".",
"parse",
"(",
"redirect_url",
")",
".",
"path",
",",
"only_path",
":",
"true",
"}",
"end",
"end",
"end"
] | create tag or category - this is set within the form | [
"create",
"tag",
"or",
"category",
"-",
"this",
"is",
"set",
"within",
"the",
"form"
] | 62654a2f2a48e3adb3105f4dafb6e315b460eaf4 | https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/terms_controller.rb#L34-L53 | train |
mrsimonfletcher/roroacms | app/controllers/roroacms/admin/terms_controller.rb | Roroacms.Admin::TermsController.update | def update
@category = Term.find(params[:id])
@category.deal_with_cover(params[:has_cover_image])
respond_to do |format|
# deal with abnormalaties - update the structure url
if @category.update_attributes(term_params)
format.html { redirect_to edit_admin_term_path(@category), notice: I18n.t("controllers.admin.terms.update.flash.success", term: Term.get_type_of_term(params)) }
else
format.html {
render action: "edit"
}
end
end
end | ruby | def update
@category = Term.find(params[:id])
@category.deal_with_cover(params[:has_cover_image])
respond_to do |format|
# deal with abnormalaties - update the structure url
if @category.update_attributes(term_params)
format.html { redirect_to edit_admin_term_path(@category), notice: I18n.t("controllers.admin.terms.update.flash.success", term: Term.get_type_of_term(params)) }
else
format.html {
render action: "edit"
}
end
end
end | [
"def",
"update",
"@category",
"=",
"Term",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"@category",
".",
"deal_with_cover",
"(",
"params",
"[",
":has_cover_image",
"]",
")",
"respond_to",
"do",
"|",
"format",
"|",
"if",
"@category",
".",
"update_attributes",
"(",
"term_params",
")",
"format",
".",
"html",
"{",
"redirect_to",
"edit_admin_term_path",
"(",
"@category",
")",
",",
"notice",
":",
"I18n",
".",
"t",
"(",
"\"controllers.admin.terms.update.flash.success\"",
",",
"term",
":",
"Term",
".",
"get_type_of_term",
"(",
"params",
")",
")",
"}",
"else",
"format",
".",
"html",
"{",
"render",
"action",
":",
"\"edit\"",
"}",
"end",
"end",
"end"
] | update the term record with the given parameters | [
"update",
"the",
"term",
"record",
"with",
"the",
"given",
"parameters"
] | 62654a2f2a48e3adb3105f4dafb6e315b460eaf4 | https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/terms_controller.rb#L67-L81 | train |
mrsimonfletcher/roroacms | app/controllers/roroacms/admin/terms_controller.rb | Roroacms.Admin::TermsController.destroy | def destroy
@term = Term.find(params[:id])
# return url will be different for either tag or category
redirect_url = Term.get_redirect_url({ type_taxonomy: @term.term_anatomy.taxonomy })
@term.destroy
respond_to do |format|
format.html { redirect_to URI.parse(redirect_url).path, notice: I18n.t("controllers.admin.terms.destroy.flash.success") }
end
end | ruby | def destroy
@term = Term.find(params[:id])
# return url will be different for either tag or category
redirect_url = Term.get_redirect_url({ type_taxonomy: @term.term_anatomy.taxonomy })
@term.destroy
respond_to do |format|
format.html { redirect_to URI.parse(redirect_url).path, notice: I18n.t("controllers.admin.terms.destroy.flash.success") }
end
end | [
"def",
"destroy",
"@term",
"=",
"Term",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"redirect_url",
"=",
"Term",
".",
"get_redirect_url",
"(",
"{",
"type_taxonomy",
":",
"@term",
".",
"term_anatomy",
".",
"taxonomy",
"}",
")",
"@term",
".",
"destroy",
"respond_to",
"do",
"|",
"format",
"|",
"format",
".",
"html",
"{",
"redirect_to",
"URI",
".",
"parse",
"(",
"redirect_url",
")",
".",
"path",
",",
"notice",
":",
"I18n",
".",
"t",
"(",
"\"controllers.admin.terms.destroy.flash.success\"",
")",
"}",
"end",
"end"
] | delete the term | [
"delete",
"the",
"term"
] | 62654a2f2a48e3adb3105f4dafb6e315b460eaf4 | https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/terms_controller.rb#L86-L95 | train |
mrsimonfletcher/roroacms | app/controllers/roroacms/admin/terms_controller.rb | Roroacms.Admin::TermsController.edit_title | def edit_title
if @category.term_anatomy.taxonomy == 'category'
add_breadcrumb I18n.t("generic.categories"), :admin_article_categories_path, :title => I18n.t("controllers.admin.terms.edit_title.category.breadcrumb_title")
add_breadcrumb I18n.t("controllers.admin.terms.edit_title.category.title")
title = I18n.t("controllers.admin.terms.edit_title.category.title")
else
add_breadcrumb I18n.t("generic.tags"), :admin_article_tags_path, :title => I18n.t("controllers.admin.terms.edit_title.tag.breadcrumb_title")
add_breadcrumb I18n.t("controllers.admin.terms.edit_title.tag.title")
title = I18n.t("controllers.admin.terms.edit_title.tag.title")
end
return title
end | ruby | def edit_title
if @category.term_anatomy.taxonomy == 'category'
add_breadcrumb I18n.t("generic.categories"), :admin_article_categories_path, :title => I18n.t("controllers.admin.terms.edit_title.category.breadcrumb_title")
add_breadcrumb I18n.t("controllers.admin.terms.edit_title.category.title")
title = I18n.t("controllers.admin.terms.edit_title.category.title")
else
add_breadcrumb I18n.t("generic.tags"), :admin_article_tags_path, :title => I18n.t("controllers.admin.terms.edit_title.tag.breadcrumb_title")
add_breadcrumb I18n.t("controllers.admin.terms.edit_title.tag.title")
title = I18n.t("controllers.admin.terms.edit_title.tag.title")
end
return title
end | [
"def",
"edit_title",
"if",
"@category",
".",
"term_anatomy",
".",
"taxonomy",
"==",
"'category'",
"add_breadcrumb",
"I18n",
".",
"t",
"(",
"\"generic.categories\"",
")",
",",
":admin_article_categories_path",
",",
":title",
"=>",
"I18n",
".",
"t",
"(",
"\"controllers.admin.terms.edit_title.category.breadcrumb_title\"",
")",
"add_breadcrumb",
"I18n",
".",
"t",
"(",
"\"controllers.admin.terms.edit_title.category.title\"",
")",
"title",
"=",
"I18n",
".",
"t",
"(",
"\"controllers.admin.terms.edit_title.category.title\"",
")",
"else",
"add_breadcrumb",
"I18n",
".",
"t",
"(",
"\"generic.tags\"",
")",
",",
":admin_article_tags_path",
",",
":title",
"=>",
"I18n",
".",
"t",
"(",
"\"controllers.admin.terms.edit_title.tag.breadcrumb_title\"",
")",
"add_breadcrumb",
"I18n",
".",
"t",
"(",
"\"controllers.admin.terms.edit_title.tag.title\"",
")",
"title",
"=",
"I18n",
".",
"t",
"(",
"\"controllers.admin.terms.edit_title.tag.title\"",
")",
"end",
"return",
"title",
"end"
] | set the title and breadcrumbs for the edit screen | [
"set",
"the",
"title",
"and",
"breadcrumbs",
"for",
"the",
"edit",
"screen"
] | 62654a2f2a48e3adb3105f4dafb6e315b460eaf4 | https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/controllers/roroacms/admin/terms_controller.rb#L116-L130 | train |
buzzware/yore | lib/yore/yore_core.rb | YoreCore.Yore.upload | def upload(aFile)
#ensure_bucket()
logger.debug "Uploading #{aFile} to S3 bucket #{config[:bucket]} ..."
logger.info "Uploading #{File.basename(aFile)} to S3 bucket #{config[:bucket]} ..."
s3client.upload_backup(aFile,config[:bucket],File.basename(aFile))
end | ruby | def upload(aFile)
#ensure_bucket()
logger.debug "Uploading #{aFile} to S3 bucket #{config[:bucket]} ..."
logger.info "Uploading #{File.basename(aFile)} to S3 bucket #{config[:bucket]} ..."
s3client.upload_backup(aFile,config[:bucket],File.basename(aFile))
end | [
"def",
"upload",
"(",
"aFile",
")",
"logger",
".",
"debug",
"\"Uploading #{aFile} to S3 bucket #{config[:bucket]} ...\"",
"logger",
".",
"info",
"\"Uploading #{File.basename(aFile)} to S3 bucket #{config[:bucket]} ...\"",
"s3client",
".",
"upload_backup",
"(",
"aFile",
",",
"config",
"[",
":bucket",
"]",
",",
"File",
".",
"basename",
"(",
"aFile",
")",
")",
"end"
] | uploads the given file to the current bucket as its basename | [
"uploads",
"the",
"given",
"file",
"to",
"the",
"current",
"bucket",
"as",
"its",
"basename"
] | 96ace47e0574e1405becd4dafb5de0226896ea1e | https://github.com/buzzware/yore/blob/96ace47e0574e1405becd4dafb5de0226896ea1e/lib/yore/yore_core.rb#L308-L313 | train |
buzzware/yore | lib/yore/yore_core.rb | YoreCore.Yore.decode_file_name | def decode_file_name(aFilename)
prefix,date,ext = aFilename.scan(/(.*?)\-(.*?)\.(.*)/).flatten
return Time.from_date_numeric(date)
end | ruby | def decode_file_name(aFilename)
prefix,date,ext = aFilename.scan(/(.*?)\-(.*?)\.(.*)/).flatten
return Time.from_date_numeric(date)
end | [
"def",
"decode_file_name",
"(",
"aFilename",
")",
"prefix",
",",
"date",
",",
"ext",
"=",
"aFilename",
".",
"scan",
"(",
"/",
"\\-",
"\\.",
"/",
")",
".",
"flatten",
"return",
"Time",
".",
"from_date_numeric",
"(",
"date",
")",
"end"
] | return date based on filename | [
"return",
"date",
"based",
"on",
"filename"
] | 96ace47e0574e1405becd4dafb5de0226896ea1e | https://github.com/buzzware/yore/blob/96ace47e0574e1405becd4dafb5de0226896ea1e/lib/yore/yore_core.rb#L334-L337 | train |
Fire-Dragon-DoL/fried-schema | lib/fried/schema/attribute/define_reader.rb | Fried::Schema::Attribute.DefineReader.call | def call(definition, klass)
variable = definition.instance_variable
klass.instance_eval do
define_method(definition.reader) { instance_variable_get(variable) }
end
end | ruby | def call(definition, klass)
variable = definition.instance_variable
klass.instance_eval do
define_method(definition.reader) { instance_variable_get(variable) }
end
end | [
"def",
"call",
"(",
"definition",
",",
"klass",
")",
"variable",
"=",
"definition",
".",
"instance_variable",
"klass",
".",
"instance_eval",
"do",
"define_method",
"(",
"definition",
".",
"reader",
")",
"{",
"instance_variable_get",
"(",
"variable",
")",
"}",
"end",
"end"
] | Creates read method
@param definition [Definition]
@param klass [Class, Module]
@return [Definition] | [
"Creates",
"read",
"method"
] | 85c5a093f319fc0f0d242264fdd7a2acfd805eea | https://github.com/Fire-Dragon-DoL/fried-schema/blob/85c5a093f319fc0f0d242264fdd7a2acfd805eea/lib/fried/schema/attribute/define_reader.rb#L19-L25 | train |
barkerest/barkest_core | app/helpers/barkest_core/misc_helper.rb | BarkestCore.MiscHelper.fixed | def fixed(value, places = 2)
value = value.to_s.to_f unless value.is_a?(Float)
sprintf("%0.#{places}f", value.round(places))
end | ruby | def fixed(value, places = 2)
value = value.to_s.to_f unless value.is_a?(Float)
sprintf("%0.#{places}f", value.round(places))
end | [
"def",
"fixed",
"(",
"value",
",",
"places",
"=",
"2",
")",
"value",
"=",
"value",
".",
"to_s",
".",
"to_f",
"unless",
"value",
".",
"is_a?",
"(",
"Float",
")",
"sprintf",
"(",
"\"%0.#{places}f\"",
",",
"value",
".",
"round",
"(",
"places",
")",
")",
"end"
] | Formats a number to the specified number of decimal places.
The +value+ can be either any valid numeric expression that can be converted to a float. | [
"Formats",
"a",
"number",
"to",
"the",
"specified",
"number",
"of",
"decimal",
"places",
"."
] | 3eeb025ec870888cacbc9bae252a39ebf9295f61 | https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/helpers/barkest_core/misc_helper.rb#L27-L30 | train |
barkerest/barkest_core | app/helpers/barkest_core/misc_helper.rb | BarkestCore.MiscHelper.split_name | def split_name(name)
name ||= ''
if name.include?(',')
last,first = name.split(',', 2)
first,middle = first.to_s.strip.split(' ', 2)
else
first,middle,last = name.split(' ', 3)
if middle && !last
middle,last = last,middle
end
end
[ first.to_s.strip, middle.to_s.strip, last.to_s.strip ]
end | ruby | def split_name(name)
name ||= ''
if name.include?(',')
last,first = name.split(',', 2)
first,middle = first.to_s.strip.split(' ', 2)
else
first,middle,last = name.split(' ', 3)
if middle && !last
middle,last = last,middle
end
end
[ first.to_s.strip, middle.to_s.strip, last.to_s.strip ]
end | [
"def",
"split_name",
"(",
"name",
")",
"name",
"||=",
"''",
"if",
"name",
".",
"include?",
"(",
"','",
")",
"last",
",",
"first",
"=",
"name",
".",
"split",
"(",
"','",
",",
"2",
")",
"first",
",",
"middle",
"=",
"first",
".",
"to_s",
".",
"strip",
".",
"split",
"(",
"' '",
",",
"2",
")",
"else",
"first",
",",
"middle",
",",
"last",
"=",
"name",
".",
"split",
"(",
"' '",
",",
"3",
")",
"if",
"middle",
"&&",
"!",
"last",
"middle",
",",
"last",
"=",
"last",
",",
"middle",
"end",
"end",
"[",
"first",
".",
"to_s",
".",
"strip",
",",
"middle",
".",
"to_s",
".",
"strip",
",",
"last",
".",
"to_s",
".",
"strip",
"]",
"end"
] | Splits a name into First, Middle, and Last parts.
Returns an array containing [ First, Middle, Last ]
Any part that is missing will be nil.
'John Doe' => [ 'John', nil, 'Doe' ]
'Doe, John' => [ 'John', nil, 'Doe' ]
'John A. Doe' => [ 'John', 'A.', 'Doe' ]
'Doe, John A.' => [ 'John', 'A.', 'Doe' ]
'John A. Doe Jr.' => [ 'John', 'A.', 'Doe Jr.' ]
'Doe Jr., John A.' => [ 'John', 'A.', 'Doe Jr.' ]
Since it doesn't check very hard, there are some known bugs as well.
'John Doe Jr.' => [ 'John', 'Doe', 'Jr.' ]
'John Doe, Jr.' => [ 'Jr.', nil, 'John Doe' ]
'Doe, John A., Jr.' => [ 'John', 'A., Jr.', 'Doe' ]
It should work in most cases. | [
"Splits",
"a",
"name",
"into",
"First",
"Middle",
"and",
"Last",
"parts",
"."
] | 3eeb025ec870888cacbc9bae252a39ebf9295f61 | https://github.com/barkerest/barkest_core/blob/3eeb025ec870888cacbc9bae252a39ebf9295f61/app/helpers/barkest_core/misc_helper.rb#L53-L65 | train |
gabebw/pipio | lib/pipio/parsers/basic_parser.rb | Pipio.BasicParser.parse | def parse
if pre_parse
messages = @file_reader.other_lines.map do |line|
basic_message_match = @line_regex.match(line)
meta_message_match = @line_regex_status.match(line)
if basic_message_match
create_message(basic_message_match)
elsif meta_message_match
create_status_or_event_message(meta_message_match)
end
end
Chat.new(messages, @metadata)
end
end | ruby | def parse
if pre_parse
messages = @file_reader.other_lines.map do |line|
basic_message_match = @line_regex.match(line)
meta_message_match = @line_regex_status.match(line)
if basic_message_match
create_message(basic_message_match)
elsif meta_message_match
create_status_or_event_message(meta_message_match)
end
end
Chat.new(messages, @metadata)
end
end | [
"def",
"parse",
"if",
"pre_parse",
"messages",
"=",
"@file_reader",
".",
"other_lines",
".",
"map",
"do",
"|",
"line",
"|",
"basic_message_match",
"=",
"@line_regex",
".",
"match",
"(",
"line",
")",
"meta_message_match",
"=",
"@line_regex_status",
".",
"match",
"(",
"line",
")",
"if",
"basic_message_match",
"create_message",
"(",
"basic_message_match",
")",
"elsif",
"meta_message_match",
"create_status_or_event_message",
"(",
"meta_message_match",
")",
"end",
"end",
"Chat",
".",
"new",
"(",
"messages",
",",
"@metadata",
")",
"end",
"end"
] | This method returns a Chat instance, or false if it could not parse the
file. | [
"This",
"method",
"returns",
"a",
"Chat",
"instance",
"or",
"false",
"if",
"it",
"could",
"not",
"parse",
"the",
"file",
"."
] | ce8abe90c9e75d916fd3a5a0f5d73e7ac9c4eacd | https://github.com/gabebw/pipio/blob/ce8abe90c9e75d916fd3a5a0f5d73e7ac9c4eacd/lib/pipio/parsers/basic_parser.rb#L14-L28 | train |
gabebw/pipio | lib/pipio/parsers/basic_parser.rb | Pipio.BasicParser.pre_parse | def pre_parse
@file_reader.read
metadata = Metadata.new(MetadataParser.new(@file_reader.first_line).parse)
if metadata.valid?
@metadata = metadata
@alias_registry = AliasRegistry.new(@metadata.their_screen_name)
@my_aliases.each do |my_alias|
@alias_registry[my_alias] = @metadata.my_screen_name
end
end
end | ruby | def pre_parse
@file_reader.read
metadata = Metadata.new(MetadataParser.new(@file_reader.first_line).parse)
if metadata.valid?
@metadata = metadata
@alias_registry = AliasRegistry.new(@metadata.their_screen_name)
@my_aliases.each do |my_alias|
@alias_registry[my_alias] = @metadata.my_screen_name
end
end
end | [
"def",
"pre_parse",
"@file_reader",
".",
"read",
"metadata",
"=",
"Metadata",
".",
"new",
"(",
"MetadataParser",
".",
"new",
"(",
"@file_reader",
".",
"first_line",
")",
".",
"parse",
")",
"if",
"metadata",
".",
"valid?",
"@metadata",
"=",
"metadata",
"@alias_registry",
"=",
"AliasRegistry",
".",
"new",
"(",
"@metadata",
".",
"their_screen_name",
")",
"@my_aliases",
".",
"each",
"do",
"|",
"my_alias",
"|",
"@alias_registry",
"[",
"my_alias",
"]",
"=",
"@metadata",
".",
"my_screen_name",
"end",
"end",
"end"
] | Extract required data from the file. Run by parse. | [
"Extract",
"required",
"data",
"from",
"the",
"file",
".",
"Run",
"by",
"parse",
"."
] | ce8abe90c9e75d916fd3a5a0f5d73e7ac9c4eacd | https://github.com/gabebw/pipio/blob/ce8abe90c9e75d916fd3a5a0f5d73e7ac9c4eacd/lib/pipio/parsers/basic_parser.rb#L31-L41 | train |
ajsharp/em-stathat | lib/em-stathat.rb | EventMachine.StatHat.time | def time(name, opts = {})
opts[:ez] ||= true
start = Time.now
yield if block_given?
if opts[:ez] == true
ez_value(name, (Time.now - start))
else
value(name, (Time.now - start))
end
end | ruby | def time(name, opts = {})
opts[:ez] ||= true
start = Time.now
yield if block_given?
if opts[:ez] == true
ez_value(name, (Time.now - start))
else
value(name, (Time.now - start))
end
end | [
"def",
"time",
"(",
"name",
",",
"opts",
"=",
"{",
"}",
")",
"opts",
"[",
":ez",
"]",
"||=",
"true",
"start",
"=",
"Time",
".",
"now",
"yield",
"if",
"block_given?",
"if",
"opts",
"[",
":ez",
"]",
"==",
"true",
"ez_value",
"(",
"name",
",",
"(",
"Time",
".",
"now",
"-",
"start",
")",
")",
"else",
"value",
"(",
"name",
",",
"(",
"Time",
".",
"now",
"-",
"start",
")",
")",
"end",
"end"
] | Time a block of code and send the duration as a value
@example
StatHat.new.time('some identifying name') do
# code
end
@param [String] name the name of the stat
@param [Hash] opts a hash of options
@option [Symbol] :ez Send data via the ez api (default: true) | [
"Time",
"a",
"block",
"of",
"code",
"and",
"send",
"the",
"duration",
"as",
"a",
"value"
] | a5b19339e9720f8b9858d65e020371511ca91b63 | https://github.com/ajsharp/em-stathat/blob/a5b19339e9720f8b9858d65e020371511ca91b63/lib/em-stathat.rb#L47-L58 | train |
mudasobwa/qipowl | lib/qipowl/core/bowler.rb | Qipowl::Bowlers.Bowler.add_entity | def add_entity section, key, value, enclosure_value = null
if (tags = self.class.const_get("#{section.upcase}_TAGS"))
key = key.bowl.to_sym
tags[key] = value.to_sym
self.class.const_get("ENCLOSURES_TAGS")[key] = enclosure_value.to_sym if enclosure_value
self.class.const_get("ENTITIES")[section.to_sym][key] = value.to_sym
self.class.class_eval %Q{
alias_method :#{key}, :∀_#{section}
} # unless self.class.instance_methods(true).include?(key.bowl)
@shadows = nil
else
logger.warn "Trying to add key “#{key}” in an invalid section “#{section}”. Ignoring…"
end
end | ruby | def add_entity section, key, value, enclosure_value = null
if (tags = self.class.const_get("#{section.upcase}_TAGS"))
key = key.bowl.to_sym
tags[key] = value.to_sym
self.class.const_get("ENCLOSURES_TAGS")[key] = enclosure_value.to_sym if enclosure_value
self.class.const_get("ENTITIES")[section.to_sym][key] = value.to_sym
self.class.class_eval %Q{
alias_method :#{key}, :∀_#{section}
} # unless self.class.instance_methods(true).include?(key.bowl)
@shadows = nil
else
logger.warn "Trying to add key “#{key}” in an invalid section “#{section}”. Ignoring…"
end
end | [
"def",
"add_entity",
"section",
",",
"key",
",",
"value",
",",
"enclosure_value",
"=",
"null",
"if",
"(",
"tags",
"=",
"self",
".",
"class",
".",
"const_get",
"(",
"\"#{section.upcase}_TAGS\"",
")",
")",
"key",
"=",
"key",
".",
"bowl",
".",
"to_sym",
"tags",
"[",
"key",
"]",
"=",
"value",
".",
"to_sym",
"self",
".",
"class",
".",
"const_get",
"(",
"\"ENCLOSURES_TAGS\"",
")",
"[",
"key",
"]",
"=",
"enclosure_value",
".",
"to_sym",
"if",
"enclosure_value",
"self",
".",
"class",
".",
"const_get",
"(",
"\"ENTITIES\"",
")",
"[",
"section",
".",
"to_sym",
"]",
"[",
"key",
"]",
"=",
"value",
".",
"to_sym",
"self",
".",
"class",
".",
"class_eval",
"%Q{ alias_method :#{key}, :∀_#{section} }",
"@shadows",
"=",
"nil",
"else",
"logger",
".",
"warn",
"\"Trying to add key “#{key}” in an invalid section “#{section}”. Ignoring…\"",
"end",
"end"
] | Adds new +entity+ in the section specified.
E. g., call to
add_spice :linewide, :°, :deg, :degrees
in HTML implementation adds a support for specifying something like:
° 15
° 30
° 45
which is to be converted to the following:
<degrees>
<deg>15</deg>
<deg>30</deg>
<deg>45</deg>
</degrees>
@param [Symbol] section the section (it must be one of {Mapping.SPICES}) to add new key to
@param [Symbol] key the name for the key
@param [Symbol] value the value
@param [Symbol] enclosure_value optional value to be added for the key into enclosures section | [
"Adds",
"new",
"+",
"entity",
"+",
"in",
"the",
"section",
"specified",
".",
"E",
".",
"g",
".",
"call",
"to"
] | 1d4643a53914d963daa73c649a043ad0ac0d71c8 | https://github.com/mudasobwa/qipowl/blob/1d4643a53914d963daa73c649a043ad0ac0d71c8/lib/qipowl/core/bowler.rb#L99-L112 | train |
jinx/core | lib/jinx/metadata/property.rb | Jinx.Property.restrict_flags | def restrict_flags(declarer, *flags)
copy = restrict(declarer)
copy.qualify(*flags)
copy
end | ruby | def restrict_flags(declarer, *flags)
copy = restrict(declarer)
copy.qualify(*flags)
copy
end | [
"def",
"restrict_flags",
"(",
"declarer",
",",
"*",
"flags",
")",
"copy",
"=",
"restrict",
"(",
"declarer",
")",
"copy",
".",
"qualify",
"(",
"*",
"flags",
")",
"copy",
"end"
] | Creates a new declarer attribute which qualifies this attribute for the given declarer.
@param declarer (see #restrict)
@param [<Symbol>] flags the additional flags for the restricted attribute
@return (see #restrict) | [
"Creates",
"a",
"new",
"declarer",
"attribute",
"which",
"qualifies",
"this",
"attribute",
"for",
"the",
"given",
"declarer",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/property.rb#L95-L99 | train |
jinx/core | lib/jinx/metadata/property.rb | Jinx.Property.inverse= | def inverse=(attribute)
return if inverse == attribute
# if no attribute, then the clear the existing inverse, if any
return clear_inverse if attribute.nil?
# the inverse attribute meta-data
begin
@inv_prop = type.property(attribute)
rescue NameError => e
raise MetadataError.new("#{@declarer.qp}.#{self} inverse attribute #{type.qp}.#{attribute} not found")
end
# the inverse of the inverse
inv_inv_prop = @inv_prop.inverse_property
# If the inverse of the inverse is already set to a different attribute, then raise an exception.
if inv_inv_prop and not (inv_inv_prop == self or inv_inv_prop.restriction?(self))
raise MetadataError.new("Cannot set #{type.qp}.#{attribute} inverse attribute to #{@declarer.qp}.#{self}@#{object_id} since it conflicts with existing inverse #{inv_inv_prop.declarer.qp}.#{inv_inv_prop}@#{inv_inv_prop.object_id}")
end
# Set the inverse of the inverse to this attribute.
@inv_prop.inverse = @attribute
# If this attribute is disjoint, then so is the inverse.
@inv_prop.qualify(:disjoint) if disjoint?
logger.debug { "Assigned #{@declarer.qp}.#{self} attribute inverse to #{type.qp}.#{attribute}." }
end | ruby | def inverse=(attribute)
return if inverse == attribute
# if no attribute, then the clear the existing inverse, if any
return clear_inverse if attribute.nil?
# the inverse attribute meta-data
begin
@inv_prop = type.property(attribute)
rescue NameError => e
raise MetadataError.new("#{@declarer.qp}.#{self} inverse attribute #{type.qp}.#{attribute} not found")
end
# the inverse of the inverse
inv_inv_prop = @inv_prop.inverse_property
# If the inverse of the inverse is already set to a different attribute, then raise an exception.
if inv_inv_prop and not (inv_inv_prop == self or inv_inv_prop.restriction?(self))
raise MetadataError.new("Cannot set #{type.qp}.#{attribute} inverse attribute to #{@declarer.qp}.#{self}@#{object_id} since it conflicts with existing inverse #{inv_inv_prop.declarer.qp}.#{inv_inv_prop}@#{inv_inv_prop.object_id}")
end
# Set the inverse of the inverse to this attribute.
@inv_prop.inverse = @attribute
# If this attribute is disjoint, then so is the inverse.
@inv_prop.qualify(:disjoint) if disjoint?
logger.debug { "Assigned #{@declarer.qp}.#{self} attribute inverse to #{type.qp}.#{attribute}." }
end | [
"def",
"inverse",
"=",
"(",
"attribute",
")",
"return",
"if",
"inverse",
"==",
"attribute",
"return",
"clear_inverse",
"if",
"attribute",
".",
"nil?",
"begin",
"@inv_prop",
"=",
"type",
".",
"property",
"(",
"attribute",
")",
"rescue",
"NameError",
"=>",
"e",
"raise",
"MetadataError",
".",
"new",
"(",
"\"#{@declarer.qp}.#{self} inverse attribute #{type.qp}.#{attribute} not found\"",
")",
"end",
"inv_inv_prop",
"=",
"@inv_prop",
".",
"inverse_property",
"if",
"inv_inv_prop",
"and",
"not",
"(",
"inv_inv_prop",
"==",
"self",
"or",
"inv_inv_prop",
".",
"restriction?",
"(",
"self",
")",
")",
"raise",
"MetadataError",
".",
"new",
"(",
"\"Cannot set #{type.qp}.#{attribute} inverse attribute to #{@declarer.qp}.#{self}@#{object_id} since it conflicts with existing inverse #{inv_inv_prop.declarer.qp}.#{inv_inv_prop}@#{inv_inv_prop.object_id}\"",
")",
"end",
"@inv_prop",
".",
"inverse",
"=",
"@attribute",
"@inv_prop",
".",
"qualify",
"(",
":disjoint",
")",
"if",
"disjoint?",
"logger",
".",
"debug",
"{",
"\"Assigned #{@declarer.qp}.#{self} attribute inverse to #{type.qp}.#{attribute}.\"",
"}",
"end"
] | Sets the inverse of the subject attribute to the given attribute.
The inverse relation is symmetric, i.e. the inverse of the referenced Property
is set to this Property's subject attribute.
@param [Symbol, nil] attribute the inverse attribute
@raise [MetadataError] if the the inverse of the inverse is already set to a different attribute | [
"Sets",
"the",
"inverse",
"of",
"the",
"subject",
"attribute",
"to",
"the",
"given",
"attribute",
".",
"The",
"inverse",
"relation",
"is",
"symmetric",
"i",
".",
"e",
".",
"the",
"inverse",
"of",
"the",
"referenced",
"Property",
"is",
"set",
"to",
"this",
"Property",
"s",
"subject",
"attribute",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/property.rb#L107-L128 | train |
jinx/core | lib/jinx/metadata/property.rb | Jinx.Property.owner_flag_set | def owner_flag_set
if dependent? then
raise MetadataError.new("#{declarer.qp}.#{self} cannot be set as a #{type.qp} owner since it is already defined as a #{type.qp} dependent")
end
inv_prop = inverse_property
if inv_prop then
inv_prop.qualify(:dependent) unless inv_prop.dependent?
else
inv_attr = type.dependent_attribute(@declarer)
if inv_attr.nil? then
raise MetadataError.new("The #{@declarer.qp} owner attribute #{self} of type #{type.qp} does not have an inverse")
end
logger.debug { "#{declarer.qp}.#{self} inverse is the #{type.qp} dependent attribute #{inv_attr}." }
self.inverse = inv_attr
end
end | ruby | def owner_flag_set
if dependent? then
raise MetadataError.new("#{declarer.qp}.#{self} cannot be set as a #{type.qp} owner since it is already defined as a #{type.qp} dependent")
end
inv_prop = inverse_property
if inv_prop then
inv_prop.qualify(:dependent) unless inv_prop.dependent?
else
inv_attr = type.dependent_attribute(@declarer)
if inv_attr.nil? then
raise MetadataError.new("The #{@declarer.qp} owner attribute #{self} of type #{type.qp} does not have an inverse")
end
logger.debug { "#{declarer.qp}.#{self} inverse is the #{type.qp} dependent attribute #{inv_attr}." }
self.inverse = inv_attr
end
end | [
"def",
"owner_flag_set",
"if",
"dependent?",
"then",
"raise",
"MetadataError",
".",
"new",
"(",
"\"#{declarer.qp}.#{self} cannot be set as a #{type.qp} owner since it is already defined as a #{type.qp} dependent\"",
")",
"end",
"inv_prop",
"=",
"inverse_property",
"if",
"inv_prop",
"then",
"inv_prop",
".",
"qualify",
"(",
":dependent",
")",
"unless",
"inv_prop",
".",
"dependent?",
"else",
"inv_attr",
"=",
"type",
".",
"dependent_attribute",
"(",
"@declarer",
")",
"if",
"inv_attr",
".",
"nil?",
"then",
"raise",
"MetadataError",
".",
"new",
"(",
"\"The #{@declarer.qp} owner attribute #{self} of type #{type.qp} does not have an inverse\"",
")",
"end",
"logger",
".",
"debug",
"{",
"\"#{declarer.qp}.#{self} inverse is the #{type.qp} dependent attribute #{inv_attr}.\"",
"}",
"self",
".",
"inverse",
"=",
"inv_attr",
"end",
"end"
] | This method is called when the owner flag is set.
The inverse is inferred as the referenced owner type's dependent attribute which references
this attribute's type.
@raise [MetadataError] if this attribute is dependent or an inverse could not be inferred | [
"This",
"method",
"is",
"called",
"when",
"the",
"owner",
"flag",
"is",
"set",
".",
"The",
"inverse",
"is",
"inferred",
"as",
"the",
"referenced",
"owner",
"type",
"s",
"dependent",
"attribute",
"which",
"references",
"this",
"attribute",
"s",
"type",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/metadata/property.rb#L285-L300 | train |
7compass/truncus | lib/truncus.rb | Truncus.Client.get_token | def get_token(url)
req = Net::HTTP::Post.new('/', initheader = {'Content-Type' => 'application/json'})
req.body = {url: url, format: 'json'}.to_json
res = @http.request(req)
data = JSON::parse(res.body)
data['trunct']['token']
end | ruby | def get_token(url)
req = Net::HTTP::Post.new('/', initheader = {'Content-Type' => 'application/json'})
req.body = {url: url, format: 'json'}.to_json
res = @http.request(req)
data = JSON::parse(res.body)
data['trunct']['token']
end | [
"def",
"get_token",
"(",
"url",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"'/'",
",",
"initheader",
"=",
"{",
"'Content-Type'",
"=>",
"'application/json'",
"}",
")",
"req",
".",
"body",
"=",
"{",
"url",
":",
"url",
",",
"format",
":",
"'json'",
"}",
".",
"to_json",
"res",
"=",
"@http",
".",
"request",
"(",
"req",
")",
"data",
"=",
"JSON",
"::",
"parse",
"(",
"res",
".",
"body",
")",
"data",
"[",
"'trunct'",
"]",
"[",
"'token'",
"]",
"end"
] | Shortens a URL, returns the shortened token | [
"Shortens",
"a",
"URL",
"returns",
"the",
"shortened",
"token"
] | 504d1bbcb97a862da889fb22d120c070e1877650 | https://github.com/7compass/truncus/blob/504d1bbcb97a862da889fb22d120c070e1877650/lib/truncus.rb#L44-L51 | train |
riddopic/garcun | lib/garcon/task/thread_pool/executor.rb | Garcon.ThreadPoolExecutor.on_worker_exit | def on_worker_exit(worker)
mutex.synchronize do
@pool.delete(worker)
if @pool.empty? && !running?
stop_event.set
stopped_event.set
end
end
end | ruby | def on_worker_exit(worker)
mutex.synchronize do
@pool.delete(worker)
if @pool.empty? && !running?
stop_event.set
stopped_event.set
end
end
end | [
"def",
"on_worker_exit",
"(",
"worker",
")",
"mutex",
".",
"synchronize",
"do",
"@pool",
".",
"delete",
"(",
"worker",
")",
"if",
"@pool",
".",
"empty?",
"&&",
"!",
"running?",
"stop_event",
".",
"set",
"stopped_event",
".",
"set",
"end",
"end",
"end"
] | Run when a thread worker exits.
@!visibility private | [
"Run",
"when",
"a",
"thread",
"worker",
"exits",
"."
] | c2409bd8cf9c14b967a719810dab5269d69b42de | https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/thread_pool/executor.rb#L178-L186 | train |
riddopic/garcun | lib/garcon/task/thread_pool/executor.rb | Garcon.ThreadPoolExecutor.execute | def execute(*args, &task)
if ensure_capacity?
@scheduled_task_count += 1
@queue << [args, task]
else
if @max_queue != 0 && @queue.length >= @max_queue
handle_fallback(*args, &task)
end
end
prune_pool
end | ruby | def execute(*args, &task)
if ensure_capacity?
@scheduled_task_count += 1
@queue << [args, task]
else
if @max_queue != 0 && @queue.length >= @max_queue
handle_fallback(*args, &task)
end
end
prune_pool
end | [
"def",
"execute",
"(",
"*",
"args",
",",
"&",
"task",
")",
"if",
"ensure_capacity?",
"@scheduled_task_count",
"+=",
"1",
"@queue",
"<<",
"[",
"args",
",",
"task",
"]",
"else",
"if",
"@max_queue",
"!=",
"0",
"&&",
"@queue",
".",
"length",
">=",
"@max_queue",
"handle_fallback",
"(",
"*",
"args",
",",
"&",
"task",
")",
"end",
"end",
"prune_pool",
"end"
] | A T T E N Z I O N E A R E A P R O T E T T A
@!visibility private | [
"A",
"T",
"T",
"E",
"N",
"Z",
"I",
"O",
"N",
"E",
"A",
"R",
"E",
"A",
"P",
"R",
"O",
"T",
"E",
"T",
"T",
"A"
] | c2409bd8cf9c14b967a719810dab5269d69b42de | https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/thread_pool/executor.rb#L191-L201 | train |
riddopic/garcun | lib/garcon/task/thread_pool/executor.rb | Garcon.ThreadPoolExecutor.ensure_capacity? | def ensure_capacity?
additional = 0
capacity = true
if @pool.size < @min_length
additional = @min_length - @pool.size
elsif @queue.empty? && @queue.num_waiting >= 1
additional = 0
elsif @pool.size == 0 && @min_length == 0
additional = 1
elsif @pool.size < @max_length || @max_length == 0
additional = 1
elsif @max_queue == 0 || @queue.size < @max_queue
additional = 0
else
capacity = false
end
additional.times do
@pool << create_worker_thread
end
if additional > 0
@largest_length = [@largest_length, @pool.length].max
end
capacity
end | ruby | def ensure_capacity?
additional = 0
capacity = true
if @pool.size < @min_length
additional = @min_length - @pool.size
elsif @queue.empty? && @queue.num_waiting >= 1
additional = 0
elsif @pool.size == 0 && @min_length == 0
additional = 1
elsif @pool.size < @max_length || @max_length == 0
additional = 1
elsif @max_queue == 0 || @queue.size < @max_queue
additional = 0
else
capacity = false
end
additional.times do
@pool << create_worker_thread
end
if additional > 0
@largest_length = [@largest_length, @pool.length].max
end
capacity
end | [
"def",
"ensure_capacity?",
"additional",
"=",
"0",
"capacity",
"=",
"true",
"if",
"@pool",
".",
"size",
"<",
"@min_length",
"additional",
"=",
"@min_length",
"-",
"@pool",
".",
"size",
"elsif",
"@queue",
".",
"empty?",
"&&",
"@queue",
".",
"num_waiting",
">=",
"1",
"additional",
"=",
"0",
"elsif",
"@pool",
".",
"size",
"==",
"0",
"&&",
"@min_length",
"==",
"0",
"additional",
"=",
"1",
"elsif",
"@pool",
".",
"size",
"<",
"@max_length",
"||",
"@max_length",
"==",
"0",
"additional",
"=",
"1",
"elsif",
"@max_queue",
"==",
"0",
"||",
"@queue",
".",
"size",
"<",
"@max_queue",
"additional",
"=",
"0",
"else",
"capacity",
"=",
"false",
"end",
"additional",
".",
"times",
"do",
"@pool",
"<<",
"create_worker_thread",
"end",
"if",
"additional",
">",
"0",
"@largest_length",
"=",
"[",
"@largest_length",
",",
"@pool",
".",
"length",
"]",
".",
"max",
"end",
"capacity",
"end"
] | Check the thread pool configuration and determine if the pool
has enought capacity to handle the request. Will grow the size
of the pool if necessary.
@return [Boolean] true if the pool has enough capacity else false
@!visibility private | [
"Check",
"the",
"thread",
"pool",
"configuration",
"and",
"determine",
"if",
"the",
"pool",
"has",
"enought",
"capacity",
"to",
"handle",
"the",
"request",
".",
"Will",
"grow",
"the",
"size",
"of",
"the",
"pool",
"if",
"necessary",
"."
] | c2409bd8cf9c14b967a719810dab5269d69b42de | https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/thread_pool/executor.rb#L225-L252 | train |
riddopic/garcun | lib/garcon/task/thread_pool/executor.rb | Garcon.ThreadPoolExecutor.prune_pool | def prune_pool
if Garcon.monotonic_time - @gc_interval >= @last_gc_time
@pool.delete_if { |worker| worker.dead? }
# send :stop for each thread over idletime
@pool.select { |worker| @idletime != 0 &&
Garcon.monotonic_time - @idletime > worker.last_activity
}.each { @queue << :stop }
@last_gc_time = Garcon.monotonic_time
end
end | ruby | def prune_pool
if Garcon.monotonic_time - @gc_interval >= @last_gc_time
@pool.delete_if { |worker| worker.dead? }
# send :stop for each thread over idletime
@pool.select { |worker| @idletime != 0 &&
Garcon.monotonic_time - @idletime > worker.last_activity
}.each { @queue << :stop }
@last_gc_time = Garcon.monotonic_time
end
end | [
"def",
"prune_pool",
"if",
"Garcon",
".",
"monotonic_time",
"-",
"@gc_interval",
">=",
"@last_gc_time",
"@pool",
".",
"delete_if",
"{",
"|",
"worker",
"|",
"worker",
".",
"dead?",
"}",
"@pool",
".",
"select",
"{",
"|",
"worker",
"|",
"@idletime",
"!=",
"0",
"&&",
"Garcon",
".",
"monotonic_time",
"-",
"@idletime",
">",
"worker",
".",
"last_activity",
"}",
".",
"each",
"{",
"@queue",
"<<",
":stop",
"}",
"@last_gc_time",
"=",
"Garcon",
".",
"monotonic_time",
"end",
"end"
] | Scan all threads in the pool and reclaim any that are dead or
have been idle too long. Will check the last time the pool was
pruned and only run if the configured garbage collection
interval has passed.
@!visibility private | [
"Scan",
"all",
"threads",
"in",
"the",
"pool",
"and",
"reclaim",
"any",
"that",
"are",
"dead",
"or",
"have",
"been",
"idle",
"too",
"long",
".",
"Will",
"check",
"the",
"last",
"time",
"the",
"pool",
"was",
"pruned",
"and",
"only",
"run",
"if",
"the",
"configured",
"garbage",
"collection",
"interval",
"has",
"passed",
"."
] | c2409bd8cf9c14b967a719810dab5269d69b42de | https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/thread_pool/executor.rb#L260-L269 | train |
riddopic/garcun | lib/garcon/task/thread_pool/executor.rb | Garcon.ThreadPoolExecutor.create_worker_thread | def create_worker_thread
wrkr = ThreadPoolWorker.new(@queue, self)
Thread.new(wrkr, self) do |worker, parent|
Thread.current.abort_on_exception = false
worker.run
parent.on_worker_exit(worker)
end
return wrkr
end | ruby | def create_worker_thread
wrkr = ThreadPoolWorker.new(@queue, self)
Thread.new(wrkr, self) do |worker, parent|
Thread.current.abort_on_exception = false
worker.run
parent.on_worker_exit(worker)
end
return wrkr
end | [
"def",
"create_worker_thread",
"wrkr",
"=",
"ThreadPoolWorker",
".",
"new",
"(",
"@queue",
",",
"self",
")",
"Thread",
".",
"new",
"(",
"wrkr",
",",
"self",
")",
"do",
"|",
"worker",
",",
"parent",
"|",
"Thread",
".",
"current",
".",
"abort_on_exception",
"=",
"false",
"worker",
".",
"run",
"parent",
".",
"on_worker_exit",
"(",
"worker",
")",
"end",
"return",
"wrkr",
"end"
] | Create a single worker thread to be added to the pool.
@return [Thread] the new thread.
@!visibility private | [
"Create",
"a",
"single",
"worker",
"thread",
"to",
"be",
"added",
"to",
"the",
"pool",
"."
] | c2409bd8cf9c14b967a719810dab5269d69b42de | https://github.com/riddopic/garcun/blob/c2409bd8cf9c14b967a719810dab5269d69b42de/lib/garcon/task/thread_pool/executor.rb#L284-L292 | train |
omegainteractive/comfypress | lib/comfypress/tag.rb | ComfyPress::Tag.InstanceMethods.render | def render
ignore = [ComfyPress::Tag::Partial, ComfyPress::Tag::Helper].member?(self.class)
ComfyPress::Tag.sanitize_irb(content, ignore)
end | ruby | def render
ignore = [ComfyPress::Tag::Partial, ComfyPress::Tag::Helper].member?(self.class)
ComfyPress::Tag.sanitize_irb(content, ignore)
end | [
"def",
"render",
"ignore",
"=",
"[",
"ComfyPress",
"::",
"Tag",
"::",
"Partial",
",",
"ComfyPress",
"::",
"Tag",
"::",
"Helper",
"]",
".",
"member?",
"(",
"self",
".",
"class",
")",
"ComfyPress",
"::",
"Tag",
".",
"sanitize_irb",
"(",
"content",
",",
"ignore",
")",
"end"
] | Content that is used during page rendering. Outputting existing content
as a default. | [
"Content",
"that",
"is",
"used",
"during",
"page",
"rendering",
".",
"Outputting",
"existing",
"content",
"as",
"a",
"default",
"."
] | 3b64699bf16774b636cb13ecd89281f6e2acb264 | https://github.com/omegainteractive/comfypress/blob/3b64699bf16774b636cb13ecd89281f6e2acb264/lib/comfypress/tag.rb#L83-L86 | train |
jinx/core | lib/jinx/resource/mergeable.rb | Jinx.Mergeable.merge_attributes | def merge_attributes(other, attributes=nil, matches=nil, &filter)
return self if other.nil? or other.equal?(self)
attributes = [attributes] if Symbol === attributes
attributes ||= self.class.mergeable_attributes
# If the source object is not a hash, then convert it to an attribute => value hash.
vh = Hasher === other ? other : other.value_hash(attributes)
# Merge the Java values hash.
vh.each { |pa, value| merge_attribute(pa, value, matches, &filter) }
self
end | ruby | def merge_attributes(other, attributes=nil, matches=nil, &filter)
return self if other.nil? or other.equal?(self)
attributes = [attributes] if Symbol === attributes
attributes ||= self.class.mergeable_attributes
# If the source object is not a hash, then convert it to an attribute => value hash.
vh = Hasher === other ? other : other.value_hash(attributes)
# Merge the Java values hash.
vh.each { |pa, value| merge_attribute(pa, value, matches, &filter) }
self
end | [
"def",
"merge_attributes",
"(",
"other",
",",
"attributes",
"=",
"nil",
",",
"matches",
"=",
"nil",
",",
"&",
"filter",
")",
"return",
"self",
"if",
"other",
".",
"nil?",
"or",
"other",
".",
"equal?",
"(",
"self",
")",
"attributes",
"=",
"[",
"attributes",
"]",
"if",
"Symbol",
"===",
"attributes",
"attributes",
"||=",
"self",
".",
"class",
".",
"mergeable_attributes",
"vh",
"=",
"Hasher",
"===",
"other",
"?",
"other",
":",
"other",
".",
"value_hash",
"(",
"attributes",
")",
"vh",
".",
"each",
"{",
"|",
"pa",
",",
"value",
"|",
"merge_attribute",
"(",
"pa",
",",
"value",
",",
"matches",
",",
"&",
"filter",
")",
"}",
"self",
"end"
] | Merges the values of the other attributes into this object and returns self.
The other argument can be either a Hash or an object whose class responds to the
+mergeable_attributes+ method.
The optional attributes argument can be either a single attribute symbol or a
collection of attribute symbols.
A hash argument consists of attribute name => value associations.
For example, given a Mergeable +person+ object with attributes +ssn+ and +children+, the call:
person.merge_attributes(:ssn => '555-55-5555', :children => children)
is equivalent to:
person.ssn ||= '555-55-5555'
person.children ||= []
person.children.merge(children, :deep)
An unrecognized attribute is ignored.
If other is not a Hash, then the other object's attributes values are merged into
this object. The default attributes is this mergeable's class
{Propertied#mergeable_attributes}.
The merge is performed by calling {#merge_attribute} on each attribute with the matches
and filter block given to this method.
@param [Mergeable, {Symbol => Object}] other the source domain object or value hash to merge from
@param [<Symbol>, nil] attributes the attributes to merge (default {Propertied#nondomain_attributes})
@param [{Resource => Resource}, nil] the optional merge source => target reference matches
@yield [value] the optional filter block
@yieldparam value the source merge attribute value
@return [Mergeable] self
@raise [ArgumentError] if none of the following are true:
* other is a Hash
* attributes is non-nil
* the other class responds to +mergeable_attributes+ | [
"Merges",
"the",
"values",
"of",
"the",
"other",
"attributes",
"into",
"this",
"object",
"and",
"returns",
"self",
".",
"The",
"other",
"argument",
"can",
"be",
"either",
"a",
"Hash",
"or",
"an",
"object",
"whose",
"class",
"responds",
"to",
"the",
"+",
"mergeable_attributes",
"+",
"method",
".",
"The",
"optional",
"attributes",
"argument",
"can",
"be",
"either",
"a",
"single",
"attribute",
"symbol",
"or",
"a",
"collection",
"of",
"attribute",
"symbols",
"."
] | 964a274cc9d7ab74613910e8375e12ed210a434d | https://github.com/jinx/core/blob/964a274cc9d7ab74613910e8375e12ed210a434d/lib/jinx/resource/mergeable.rb#L38-L47 | train |
jamescook/layabout | lib/layabout/slack_request.rb | Layabout.SlackRequest.perform_webhook | def perform_webhook
http_request.body = {'text' => params[:text]}.to_json.to_s
http_request.query = {'token' => params[:token]}
HTTPI.post(http_request)
end | ruby | def perform_webhook
http_request.body = {'text' => params[:text]}.to_json.to_s
http_request.query = {'token' => params[:token]}
HTTPI.post(http_request)
end | [
"def",
"perform_webhook",
"http_request",
".",
"body",
"=",
"{",
"'text'",
"=>",
"params",
"[",
":text",
"]",
"}",
".",
"to_json",
".",
"to_s",
"http_request",
".",
"query",
"=",
"{",
"'token'",
"=>",
"params",
"[",
":token",
"]",
"}",
"HTTPI",
".",
"post",
"(",
"http_request",
")",
"end"
] | Webhooks are handled in a non-compatible way with the other APIs | [
"Webhooks",
"are",
"handled",
"in",
"a",
"non",
"-",
"compatible",
"way",
"with",
"the",
"other",
"APIs"
] | 87d4cf3f03cd617fba55112ef5339a43ddf828a3 | https://github.com/jamescook/layabout/blob/87d4cf3f03cd617fba55112ef5339a43ddf828a3/lib/layabout/slack_request.rb#L25-L29 | train |
hinrik/ircsupport | lib/ircsupport/case.rb | IRCSupport.Case.irc_upcase! | def irc_upcase!(irc_string, casemapping = :rfc1459)
case casemapping
when :ascii
irc_string.tr!(*@@ascii_map)
when :rfc1459
irc_string.tr!(*@@rfc1459_map)
when :'strict-rfc1459'
irc_string.tr!(*@@strict_rfc1459_map)
else
raise ArgumentError, "Unsupported casemapping #{casemapping}"
end
return irc_string
end | ruby | def irc_upcase!(irc_string, casemapping = :rfc1459)
case casemapping
when :ascii
irc_string.tr!(*@@ascii_map)
when :rfc1459
irc_string.tr!(*@@rfc1459_map)
when :'strict-rfc1459'
irc_string.tr!(*@@strict_rfc1459_map)
else
raise ArgumentError, "Unsupported casemapping #{casemapping}"
end
return irc_string
end | [
"def",
"irc_upcase!",
"(",
"irc_string",
",",
"casemapping",
"=",
":rfc1459",
")",
"case",
"casemapping",
"when",
":ascii",
"irc_string",
".",
"tr!",
"(",
"*",
"@@ascii_map",
")",
"when",
":rfc1459",
"irc_string",
".",
"tr!",
"(",
"*",
"@@rfc1459_map",
")",
"when",
":'",
"'",
"irc_string",
".",
"tr!",
"(",
"*",
"@@strict_rfc1459_map",
")",
"else",
"raise",
"ArgumentError",
",",
"\"Unsupported casemapping #{casemapping}\"",
"end",
"return",
"irc_string",
"end"
] | Turn a string into IRC upper case, modifying it in place.
@param [String] irc_string An IRC string (nickname, channel, etc).
@param [Symbol] casemapping An IRC casemapping.
@return [String] An upper case version of the IRC string according to
the casemapping. | [
"Turn",
"a",
"string",
"into",
"IRC",
"upper",
"case",
"modifying",
"it",
"in",
"place",
"."
] | d028b7d5ccc604a6af175ee2264c18d25b1f7dff | https://github.com/hinrik/ircsupport/blob/d028b7d5ccc604a6af175ee2264c18d25b1f7dff/lib/ircsupport/case.rb#L17-L30 | train |
hinrik/ircsupport | lib/ircsupport/case.rb | IRCSupport.Case.irc_upcase | def irc_upcase(irc_string, casemapping = :rfc1459)
result = irc_string.dup
irc_upcase!(result, casemapping)
return result
end | ruby | def irc_upcase(irc_string, casemapping = :rfc1459)
result = irc_string.dup
irc_upcase!(result, casemapping)
return result
end | [
"def",
"irc_upcase",
"(",
"irc_string",
",",
"casemapping",
"=",
":rfc1459",
")",
"result",
"=",
"irc_string",
".",
"dup",
"irc_upcase!",
"(",
"result",
",",
"casemapping",
")",
"return",
"result",
"end"
] | Turn a string into IRC upper case.
@param [String] irc_string An IRC string (nickname, channel, etc)
@param [Symbol] casemapping An IRC casemapping
@return [String] An upper case version of the IRC string according to
the casemapping. | [
"Turn",
"a",
"string",
"into",
"IRC",
"upper",
"case",
"."
] | d028b7d5ccc604a6af175ee2264c18d25b1f7dff | https://github.com/hinrik/ircsupport/blob/d028b7d5ccc604a6af175ee2264c18d25b1f7dff/lib/ircsupport/case.rb#L37-L41 | train |
hinrik/ircsupport | lib/ircsupport/case.rb | IRCSupport.Case.irc_downcase! | def irc_downcase!(irc_string, casemapping = :rfc1459)
case casemapping
when :ascii
irc_string.tr!(*@@ascii_map.reverse)
when :rfc1459
irc_string.tr!(*@@rfc1459_map.reverse)
when :'strict-rfc1459'
irc_string.tr!(*@@strict_rfc1459_map.reverse)
else
raise ArgumentError, "Unsupported casemapping #{casemapping}"
end
return irc_string
end | ruby | def irc_downcase!(irc_string, casemapping = :rfc1459)
case casemapping
when :ascii
irc_string.tr!(*@@ascii_map.reverse)
when :rfc1459
irc_string.tr!(*@@rfc1459_map.reverse)
when :'strict-rfc1459'
irc_string.tr!(*@@strict_rfc1459_map.reverse)
else
raise ArgumentError, "Unsupported casemapping #{casemapping}"
end
return irc_string
end | [
"def",
"irc_downcase!",
"(",
"irc_string",
",",
"casemapping",
"=",
":rfc1459",
")",
"case",
"casemapping",
"when",
":ascii",
"irc_string",
".",
"tr!",
"(",
"*",
"@@ascii_map",
".",
"reverse",
")",
"when",
":rfc1459",
"irc_string",
".",
"tr!",
"(",
"*",
"@@rfc1459_map",
".",
"reverse",
")",
"when",
":'",
"'",
"irc_string",
".",
"tr!",
"(",
"*",
"@@strict_rfc1459_map",
".",
"reverse",
")",
"else",
"raise",
"ArgumentError",
",",
"\"Unsupported casemapping #{casemapping}\"",
"end",
"return",
"irc_string",
"end"
] | Turn a string into IRC lower case, modifying it in place.
@param [String] irc_string An IRC string (nickname, channel, etc)
@param [Symbol] casemapping An IRC casemapping
@return [String] A lower case version of the IRC string according to
the casemapping | [
"Turn",
"a",
"string",
"into",
"IRC",
"lower",
"case",
"modifying",
"it",
"in",
"place",
"."
] | d028b7d5ccc604a6af175ee2264c18d25b1f7dff | https://github.com/hinrik/ircsupport/blob/d028b7d5ccc604a6af175ee2264c18d25b1f7dff/lib/ircsupport/case.rb#L48-L61 | train |
hinrik/ircsupport | lib/ircsupport/case.rb | IRCSupport.Case.irc_downcase | def irc_downcase(irc_string, casemapping = :rfc1459)
result = irc_string.dup
irc_downcase!(result, casemapping)
return result
end | ruby | def irc_downcase(irc_string, casemapping = :rfc1459)
result = irc_string.dup
irc_downcase!(result, casemapping)
return result
end | [
"def",
"irc_downcase",
"(",
"irc_string",
",",
"casemapping",
"=",
":rfc1459",
")",
"result",
"=",
"irc_string",
".",
"dup",
"irc_downcase!",
"(",
"result",
",",
"casemapping",
")",
"return",
"result",
"end"
] | Turn a string into IRC lower case.
@param [String] irc_string An IRC string (nickname, channel, etc).
@param [Symbol] casemapping An IRC casemapping.
@return [String] A lower case version of the IRC string according to
the casemapping | [
"Turn",
"a",
"string",
"into",
"IRC",
"lower",
"case",
"."
] | d028b7d5ccc604a6af175ee2264c18d25b1f7dff | https://github.com/hinrik/ircsupport/blob/d028b7d5ccc604a6af175ee2264c18d25b1f7dff/lib/ircsupport/case.rb#L68-L72 | train |
paydro/js_message | lib/js_message/controller_methods.rb | JsMessage.ControllerMethods.render_js_message | def render_js_message(type, hash = {})
unless [ :ok, :redirect, :error ].include?(type)
raise "Invalid js_message response type: #{type}"
end
js_message = {
:status => type,
:html => nil,
:message => nil,
:to => nil
}.merge(hash)
render_options = {:json => js_message}
render_options[:status] = 400 if type == :error
render(render_options)
end | ruby | def render_js_message(type, hash = {})
unless [ :ok, :redirect, :error ].include?(type)
raise "Invalid js_message response type: #{type}"
end
js_message = {
:status => type,
:html => nil,
:message => nil,
:to => nil
}.merge(hash)
render_options = {:json => js_message}
render_options[:status] = 400 if type == :error
render(render_options)
end | [
"def",
"render_js_message",
"(",
"type",
",",
"hash",
"=",
"{",
"}",
")",
"unless",
"[",
":ok",
",",
":redirect",
",",
":error",
"]",
".",
"include?",
"(",
"type",
")",
"raise",
"\"Invalid js_message response type: #{type}\"",
"end",
"js_message",
"=",
"{",
":status",
"=>",
"type",
",",
":html",
"=>",
"nil",
",",
":message",
"=>",
"nil",
",",
":to",
"=>",
"nil",
"}",
".",
"merge",
"(",
"hash",
")",
"render_options",
"=",
"{",
":json",
"=>",
"js_message",
"}",
"render_options",
"[",
":status",
"]",
"=",
"400",
"if",
"type",
"==",
":error",
"render",
"(",
"render_options",
")",
"end"
] | Helper to render the js_message response.
Pass in a type of message (:ok, :error, :redirect) and any other
data you need. Default data attributes in the response are:
* html
* message
* to (used for redirects)
Examples:
# Send a successful response with some html
render_js_message :ok, :html => "<p>It worked!</p>"
# Send a redirect
render_js_message :redirect, :to => "http://www.google.com"
# Send an error response with a message
render_js_message :error, :message => "Something broke!"
Of course, if you don't need other data sent back in the response
this works as well:
render_js_message :ok | [
"Helper",
"to",
"render",
"the",
"js_message",
"response",
"."
] | 6adda30f204ef917db3f3595f46f0db8208214e1 | https://github.com/paydro/js_message/blob/6adda30f204ef917db3f3595f46f0db8208214e1/lib/js_message/controller_methods.rb#L28-L44 | train |
jgoizueta/numerals | lib/numerals/format/base_scaler.rb | Numerals.Format::BaseScaler.scaled_digit | def scaled_digit(group)
unless group.size == @base_scale
raise "Invalid digits group size for scaled_digit (is #{group.size}; should be #{@base_scale})"
end
v = 0
group.each do |digit|
v *= @setter.base
v += digit
end
v
end | ruby | def scaled_digit(group)
unless group.size == @base_scale
raise "Invalid digits group size for scaled_digit (is #{group.size}; should be #{@base_scale})"
end
v = 0
group.each do |digit|
v *= @setter.base
v += digit
end
v
end | [
"def",
"scaled_digit",
"(",
"group",
")",
"unless",
"group",
".",
"size",
"==",
"@base_scale",
"raise",
"\"Invalid digits group size for scaled_digit (is #{group.size}; should be #{@base_scale})\"",
"end",
"v",
"=",
"0",
"group",
".",
"each",
"do",
"|",
"digit",
"|",
"v",
"*=",
"@setter",
".",
"base",
"v",
"+=",
"digit",
"end",
"v",
"end"
] | Return the `scaled_base` digit corresponding to a group of `base_scale` `exponent_base` digits | [
"Return",
"the",
"scaled_base",
"digit",
"corresponding",
"to",
"a",
"group",
"of",
"base_scale",
"exponent_base",
"digits"
] | a195e75f689af926537f791441bf8d11590c99c0 | https://github.com/jgoizueta/numerals/blob/a195e75f689af926537f791441bf8d11590c99c0/lib/numerals/format/base_scaler.rb#L97-L107 | train |
jgoizueta/numerals | lib/numerals/format/base_scaler.rb | Numerals.Format::BaseScaler.grouped_digits | def grouped_digits(digits)
unless (digits.size % @base_scale) == 0
raise "Invalid number of digits for group_digits (#{digits.size} is not a multiple of #{@base_scale})"
end
digits.each_slice(@base_scale).map{|group| scaled_digit(group)}
end | ruby | def grouped_digits(digits)
unless (digits.size % @base_scale) == 0
raise "Invalid number of digits for group_digits (#{digits.size} is not a multiple of #{@base_scale})"
end
digits.each_slice(@base_scale).map{|group| scaled_digit(group)}
end | [
"def",
"grouped_digits",
"(",
"digits",
")",
"unless",
"(",
"digits",
".",
"size",
"%",
"@base_scale",
")",
"==",
"0",
"raise",
"\"Invalid number of digits for group_digits (#{digits.size} is not a multiple of #{@base_scale})\"",
"end",
"digits",
".",
"each_slice",
"(",
"@base_scale",
")",
".",
"map",
"{",
"|",
"group",
"|",
"scaled_digit",
"(",
"group",
")",
"}",
"end"
] | Convert base `exponent_base` digits to base `scaled_base` digits
the number of digits must be a multiple of base_scale | [
"Convert",
"base",
"exponent_base",
"digits",
"to",
"base",
"scaled_base",
"digits",
"the",
"number",
"of",
"digits",
"must",
"be",
"a",
"multiple",
"of",
"base_scale"
] | a195e75f689af926537f791441bf8d11590c99c0 | https://github.com/jgoizueta/numerals/blob/a195e75f689af926537f791441bf8d11590c99c0/lib/numerals/format/base_scaler.rb#L111-L116 | train |
nrser/nrser.rb | lib/nrser/meta/lazy_attr.rb | NRSER.LazyAttr.call | def call target_method, receiver, *args, &block
unless target_method.parameters.empty?
raise NRSER::ArgumentError.new \
"{NRSER::LazyAttr} can only decorate methods with 0 params",
receiver: receiver,
target_method: target_method
end
unless args.empty?
raise NRSER::ArgumentError.new \
"wrong number of arguments for", target_method,
"(given", args.length, "expected 0)",
receiver: receiver,
target_method: target_method
end
unless block.nil?
raise NRSER::ArgumentError.new \
"wrong number of arguments (given #{ args.length }, expected 0)",
receiver: receiver,
target_method: target_method
end
var_name = self.class.instance_var_name target_method
unless receiver.instance_variable_defined? var_name
receiver.instance_variable_set var_name, target_method.call
end
receiver.instance_variable_get var_name
end | ruby | def call target_method, receiver, *args, &block
unless target_method.parameters.empty?
raise NRSER::ArgumentError.new \
"{NRSER::LazyAttr} can only decorate methods with 0 params",
receiver: receiver,
target_method: target_method
end
unless args.empty?
raise NRSER::ArgumentError.new \
"wrong number of arguments for", target_method,
"(given", args.length, "expected 0)",
receiver: receiver,
target_method: target_method
end
unless block.nil?
raise NRSER::ArgumentError.new \
"wrong number of arguments (given #{ args.length }, expected 0)",
receiver: receiver,
target_method: target_method
end
var_name = self.class.instance_var_name target_method
unless receiver.instance_variable_defined? var_name
receiver.instance_variable_set var_name, target_method.call
end
receiver.instance_variable_get var_name
end | [
"def",
"call",
"target_method",
",",
"receiver",
",",
"*",
"args",
",",
"&",
"block",
"unless",
"target_method",
".",
"parameters",
".",
"empty?",
"raise",
"NRSER",
"::",
"ArgumentError",
".",
"new",
"\"{NRSER::LazyAttr} can only decorate methods with 0 params\"",
",",
"receiver",
":",
"receiver",
",",
"target_method",
":",
"target_method",
"end",
"unless",
"args",
".",
"empty?",
"raise",
"NRSER",
"::",
"ArgumentError",
".",
"new",
"\"wrong number of arguments for\"",
",",
"target_method",
",",
"\"(given\"",
",",
"args",
".",
"length",
",",
"\"expected 0)\"",
",",
"receiver",
":",
"receiver",
",",
"target_method",
":",
"target_method",
"end",
"unless",
"block",
".",
"nil?",
"raise",
"NRSER",
"::",
"ArgumentError",
".",
"new",
"\"wrong number of arguments (given #{ args.length }, expected 0)\"",
",",
"receiver",
":",
"receiver",
",",
"target_method",
":",
"target_method",
"end",
"var_name",
"=",
"self",
".",
"class",
".",
"instance_var_name",
"target_method",
"unless",
"receiver",
".",
"instance_variable_defined?",
"var_name",
"receiver",
".",
"instance_variable_set",
"var_name",
",",
"target_method",
".",
"call",
"end",
"receiver",
".",
"instance_variable_get",
"var_name",
"end"
] | .instance_var_name
Execute the decorator.
@param [Method] target_method
The decorated method, already bound to the receiver.
The `method_decorators` gem calls this `orig`, but I thought
`target_method` made more sense.
@param [*] receiver
The object that will receive the call to `target`.
The `method_decorators` gem calls this `this`, but I thought `receiver`
made more sense.
It's just `target.receiver`, but the API is how it is.
@param [Array] args
Any arguments the decorated method was called with.
@param [Proc?] block
The block the decorated method was called with (if any).
@return
Whatever `target_method` returns. | [
".",
"instance_var_name",
"Execute",
"the",
"decorator",
"."
] | 7db9a729ec65894dfac13fd50851beae8b809738 | https://github.com/nrser/nrser.rb/blob/7db9a729ec65894dfac13fd50851beae8b809738/lib/nrser/meta/lazy_attr.rb#L75-L106 | train |
renz45/table_me | lib/table_me/builder.rb | TableMe.Builder.column | def column name,options = {}, &block
@columns << TableMe::Column.new(name,options, &block)
@names << name
end | ruby | def column name,options = {}, &block
@columns << TableMe::Column.new(name,options, &block)
@names << name
end | [
"def",
"column",
"name",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
"@columns",
"<<",
"TableMe",
"::",
"Column",
".",
"new",
"(",
"name",
",",
"options",
",",
"&",
"block",
")",
"@names",
"<<",
"name",
"end"
] | Define a column | [
"Define",
"a",
"column"
] | a04bd7c26497828b2f8f0178631253b6749025cf | https://github.com/renz45/table_me/blob/a04bd7c26497828b2f8f0178631253b6749025cf/lib/table_me/builder.rb#L17-L20 | train |
bossmc/milenage | lib/milenage.rb | Milenage.Kernel.op= | def op=(op)
fail "OP must be 128 bits" unless op.each_byte.to_a.length == 16
@opc = xor(enc(op), op)
end | ruby | def op=(op)
fail "OP must be 128 bits" unless op.each_byte.to_a.length == 16
@opc = xor(enc(op), op)
end | [
"def",
"op",
"=",
"(",
"op",
")",
"fail",
"\"OP must be 128 bits\"",
"unless",
"op",
".",
"each_byte",
".",
"to_a",
".",
"length",
"==",
"16",
"@opc",
"=",
"xor",
"(",
"enc",
"(",
"op",
")",
",",
"op",
")",
"end"
] | Create a single user's kernel instance, remember to set OP or OPc before
attempting to use the security functions.
To change the algorithm variables as described in TS 35.206 subclass
this Kernel class and modify `@c`, `@r` or `@kernel` after calling
super. E.G.
class MyKernel < Kernel
def initialize(key)
super
@r = [10, 20, 30, 40, 50]
end
end
When doing this, `@kernel` should be set to a 128-bit MAC function with
the same API as `OpenSSL::Cipher`, if this is not the case, you may
need to overload {#enc} as well to match the API.
Set the Operator Variant Algorithm Configuration field.
Either this or {#opc=} must be called before any of the security
functions are evaluated. | [
"Create",
"a",
"single",
"user",
"s",
"kernel",
"instance",
"remember",
"to",
"set",
"OP",
"or",
"OPc",
"before",
"attempting",
"to",
"use",
"the",
"security",
"functions",
"."
] | 7966c0910f66232ea53a50512fd80d3a6b3ad18a | https://github.com/bossmc/milenage/blob/7966c0910f66232ea53a50512fd80d3a6b3ad18a/lib/milenage.rb#L59-L62 | train |
dbalatero/typhoeus_spec_cache | lib/typhoeus/spec_cache.rb | Typhoeus.SpecCache.remove_unnecessary_cache_files! | def remove_unnecessary_cache_files!
current_keys = cache_files.map do |file|
get_cache_key_from_filename(file)
end
inmemory_keys = responses.keys
unneeded_keys = current_keys - inmemory_keys
unneeded_keys.each do |key|
File.unlink(filepath_for(key))
end
end | ruby | def remove_unnecessary_cache_files!
current_keys = cache_files.map do |file|
get_cache_key_from_filename(file)
end
inmemory_keys = responses.keys
unneeded_keys = current_keys - inmemory_keys
unneeded_keys.each do |key|
File.unlink(filepath_for(key))
end
end | [
"def",
"remove_unnecessary_cache_files!",
"current_keys",
"=",
"cache_files",
".",
"map",
"do",
"|",
"file",
"|",
"get_cache_key_from_filename",
"(",
"file",
")",
"end",
"inmemory_keys",
"=",
"responses",
".",
"keys",
"unneeded_keys",
"=",
"current_keys",
"-",
"inmemory_keys",
"unneeded_keys",
".",
"each",
"do",
"|",
"key",
"|",
"File",
".",
"unlink",
"(",
"filepath_for",
"(",
"key",
")",
")",
"end",
"end"
] | Removes any cache files that aren't needed anymore | [
"Removes",
"any",
"cache",
"files",
"that",
"aren",
"t",
"needed",
"anymore"
] | 7141c311c76fe001428c143d90ad927bd8b178e9 | https://github.com/dbalatero/typhoeus_spec_cache/blob/7141c311c76fe001428c143d90ad927bd8b178e9/lib/typhoeus/spec_cache.rb#L35-L45 | train |
dbalatero/typhoeus_spec_cache | lib/typhoeus/spec_cache.rb | Typhoeus.SpecCache.read_cache_fixtures! | def read_cache_fixtures!
files = cache_files
files.each do |file|
cache_key = get_cache_key_from_filename(file)
responses[cache_key] = Marshal.load(File.read(file))
end
end | ruby | def read_cache_fixtures!
files = cache_files
files.each do |file|
cache_key = get_cache_key_from_filename(file)
responses[cache_key] = Marshal.load(File.read(file))
end
end | [
"def",
"read_cache_fixtures!",
"files",
"=",
"cache_files",
"files",
".",
"each",
"do",
"|",
"file",
"|",
"cache_key",
"=",
"get_cache_key_from_filename",
"(",
"file",
")",
"responses",
"[",
"cache_key",
"]",
"=",
"Marshal",
".",
"load",
"(",
"File",
".",
"read",
"(",
"file",
")",
")",
"end",
"end"
] | Reads in the cache fixture files to in-memory cache. | [
"Reads",
"in",
"the",
"cache",
"fixture",
"files",
"to",
"in",
"-",
"memory",
"cache",
"."
] | 7141c311c76fe001428c143d90ad927bd8b178e9 | https://github.com/dbalatero/typhoeus_spec_cache/blob/7141c311c76fe001428c143d90ad927bd8b178e9/lib/typhoeus/spec_cache.rb#L48-L54 | train |
dbalatero/typhoeus_spec_cache | lib/typhoeus/spec_cache.rb | Typhoeus.SpecCache.dump_cache_fixtures! | def dump_cache_fixtures!
responses.each do |cache_key, response|
path = filepath_for(cache_key)
unless File.exist?(path)
File.open(path, "wb") do |fp|
fp.write(Marshal.dump(response))
end
end
end
end | ruby | def dump_cache_fixtures!
responses.each do |cache_key, response|
path = filepath_for(cache_key)
unless File.exist?(path)
File.open(path, "wb") do |fp|
fp.write(Marshal.dump(response))
end
end
end
end | [
"def",
"dump_cache_fixtures!",
"responses",
".",
"each",
"do",
"|",
"cache_key",
",",
"response",
"|",
"path",
"=",
"filepath_for",
"(",
"cache_key",
")",
"unless",
"File",
".",
"exist?",
"(",
"path",
")",
"File",
".",
"open",
"(",
"path",
",",
"\"wb\"",
")",
"do",
"|",
"fp",
"|",
"fp",
".",
"write",
"(",
"Marshal",
".",
"dump",
"(",
"response",
")",
")",
"end",
"end",
"end",
"end"
] | Dumps out any cached items to disk. | [
"Dumps",
"out",
"any",
"cached",
"items",
"to",
"disk",
"."
] | 7141c311c76fe001428c143d90ad927bd8b178e9 | https://github.com/dbalatero/typhoeus_spec_cache/blob/7141c311c76fe001428c143d90ad927bd8b178e9/lib/typhoeus/spec_cache.rb#L57-L66 | train |
mrsimonfletcher/roroacms | app/helpers/roroacms/admin_roroa_helper.rb | Roroacms.AdminRoroaHelper.get_theme_options | def get_theme_options
hash = []
Dir.glob("#{Rails.root}/app/views/themes/*/") do |themes|
opt = themes.split('/').last
if File.exists?("#{themes}theme.yml")
info = YAML.load(File.read("#{themes}theme.yml"))
hash << info if !info['name'].blank? && !info['author'].blank? && !info['foldername'].blank? && !info['view_extension'].blank?
end
end
hash
end | ruby | def get_theme_options
hash = []
Dir.glob("#{Rails.root}/app/views/themes/*/") do |themes|
opt = themes.split('/').last
if File.exists?("#{themes}theme.yml")
info = YAML.load(File.read("#{themes}theme.yml"))
hash << info if !info['name'].blank? && !info['author'].blank? && !info['foldername'].blank? && !info['view_extension'].blank?
end
end
hash
end | [
"def",
"get_theme_options",
"hash",
"=",
"[",
"]",
"Dir",
".",
"glob",
"(",
"\"#{Rails.root}/app/views/themes/*/\"",
")",
"do",
"|",
"themes",
"|",
"opt",
"=",
"themes",
".",
"split",
"(",
"'/'",
")",
".",
"last",
"if",
"File",
".",
"exists?",
"(",
"\"#{themes}theme.yml\"",
")",
"info",
"=",
"YAML",
".",
"load",
"(",
"File",
".",
"read",
"(",
"\"#{themes}theme.yml\"",
")",
")",
"hash",
"<<",
"info",
"if",
"!",
"info",
"[",
"'name'",
"]",
".",
"blank?",
"&&",
"!",
"info",
"[",
"'author'",
"]",
".",
"blank?",
"&&",
"!",
"info",
"[",
"'foldername'",
"]",
".",
"blank?",
"&&",
"!",
"info",
"[",
"'view_extension'",
"]",
".",
"blank?",
"end",
"end",
"hash",
"end"
] | returns a hash of the different themes as a hash with the details kept in the theme.yml file | [
"returns",
"a",
"hash",
"of",
"the",
"different",
"themes",
"as",
"a",
"hash",
"with",
"the",
"details",
"kept",
"in",
"the",
"theme",
".",
"yml",
"file"
] | 62654a2f2a48e3adb3105f4dafb6e315b460eaf4 | https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/helpers/roroacms/admin_roroa_helper.rb#L15-L27 | train |
mrsimonfletcher/roroacms | app/helpers/roroacms/admin_roroa_helper.rb | Roroacms.AdminRoroaHelper.get_templates | def get_templates
hash = []
current_theme = Setting.get('theme_folder')
Dir.glob("#{Rails.root}/app/views/themes/#{current_theme}/template-*.html.erb") do |my_text_file|
opt = my_text_file.split('/').last
opt['template-'] = ''
opt['.html.erb'] = ''
# strips out the template- and .html.erb extention and returns the middle as the template name for the admin
hash << opt.titleize
end
hash
end | ruby | def get_templates
hash = []
current_theme = Setting.get('theme_folder')
Dir.glob("#{Rails.root}/app/views/themes/#{current_theme}/template-*.html.erb") do |my_text_file|
opt = my_text_file.split('/').last
opt['template-'] = ''
opt['.html.erb'] = ''
# strips out the template- and .html.erb extention and returns the middle as the template name for the admin
hash << opt.titleize
end
hash
end | [
"def",
"get_templates",
"hash",
"=",
"[",
"]",
"current_theme",
"=",
"Setting",
".",
"get",
"(",
"'theme_folder'",
")",
"Dir",
".",
"glob",
"(",
"\"#{Rails.root}/app/views/themes/#{current_theme}/template-*.html.erb\"",
")",
"do",
"|",
"my_text_file",
"|",
"opt",
"=",
"my_text_file",
".",
"split",
"(",
"'/'",
")",
".",
"last",
"opt",
"[",
"'template-'",
"]",
"=",
"''",
"opt",
"[",
"'.html.erb'",
"]",
"=",
"''",
"hash",
"<<",
"opt",
".",
"titleize",
"end",
"hash",
"end"
] | retuns a hash of the template files within the current theme | [
"retuns",
"a",
"hash",
"of",
"the",
"template",
"files",
"within",
"the",
"current",
"theme"
] | 62654a2f2a48e3adb3105f4dafb6e315b460eaf4 | https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/helpers/roroacms/admin_roroa_helper.rb#L41-L54 | train |
mrsimonfletcher/roroacms | app/helpers/roroacms/admin_roroa_helper.rb | Roroacms.AdminRoroaHelper.theme_exists | def theme_exists
if !Dir.exists?("app/views/themes/#{Setting.get('theme_folder')}/")
html = "<div class='alert alert-danger'><strong>" + I18n.t("helpers.admin_roroa_helper.theme_exists.warning") + "!</strong> " + I18n.t("helpers.admin_roroa_helper.theme_exists.message") + "!</div>"
render :inline => html.html_safe
end
end | ruby | def theme_exists
if !Dir.exists?("app/views/themes/#{Setting.get('theme_folder')}/")
html = "<div class='alert alert-danger'><strong>" + I18n.t("helpers.admin_roroa_helper.theme_exists.warning") + "!</strong> " + I18n.t("helpers.admin_roroa_helper.theme_exists.message") + "!</div>"
render :inline => html.html_safe
end
end | [
"def",
"theme_exists",
"if",
"!",
"Dir",
".",
"exists?",
"(",
"\"app/views/themes/#{Setting.get('theme_folder')}/\"",
")",
"html",
"=",
"\"<div class='alert alert-danger'><strong>\"",
"+",
"I18n",
".",
"t",
"(",
"\"helpers.admin_roroa_helper.theme_exists.warning\"",
")",
"+",
"\"!</strong> \"",
"+",
"I18n",
".",
"t",
"(",
"\"helpers.admin_roroa_helper.theme_exists.message\"",
")",
"+",
"\"!</div>\"",
"render",
":inline",
"=>",
"html",
".",
"html_safe",
"end",
"end"
] | checks if the current theme being used actually exists. If not it will return an error message to the user | [
"checks",
"if",
"the",
"current",
"theme",
"being",
"used",
"actually",
"exists",
".",
"If",
"not",
"it",
"will",
"return",
"an",
"error",
"message",
"to",
"the",
"user"
] | 62654a2f2a48e3adb3105f4dafb6e315b460eaf4 | https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/helpers/roroacms/admin_roroa_helper.rb#L126-L133 | train |
mrsimonfletcher/roroacms | app/helpers/roroacms/admin_roroa_helper.rb | Roroacms.AdminRoroaHelper.get_notifications | def get_notifications
html = ''
if flash[:error]
html += "<div class='alert alert-danger'><button type='button' class='close' data-dismiss='alert'>x</button><strong>" + I18n.t("helpers.view_helper.generic.flash.error") + "!</strong> #{flash[:error]}</div>"
end
if flash[:notice]
html += "<div class='alert alert-success'><button type='button' class='close' data-dismiss='alert'>x</button><strong>" + I18n.t("helpers.view_helper.generic.flash.success") + "!</strong> #{flash[:notice]}</div>"
end
render :inline => html.html_safe
end | ruby | def get_notifications
html = ''
if flash[:error]
html += "<div class='alert alert-danger'><button type='button' class='close' data-dismiss='alert'>x</button><strong>" + I18n.t("helpers.view_helper.generic.flash.error") + "!</strong> #{flash[:error]}</div>"
end
if flash[:notice]
html += "<div class='alert alert-success'><button type='button' class='close' data-dismiss='alert'>x</button><strong>" + I18n.t("helpers.view_helper.generic.flash.success") + "!</strong> #{flash[:notice]}</div>"
end
render :inline => html.html_safe
end | [
"def",
"get_notifications",
"html",
"=",
"''",
"if",
"flash",
"[",
":error",
"]",
"html",
"+=",
"\"<div class='alert alert-danger'><button type='button' class='close' data-dismiss='alert'>x</button><strong>\"",
"+",
"I18n",
".",
"t",
"(",
"\"helpers.view_helper.generic.flash.error\"",
")",
"+",
"\"!</strong> #{flash[:error]}</div>\"",
"end",
"if",
"flash",
"[",
":notice",
"]",
"html",
"+=",
"\"<div class='alert alert-success'><button type='button' class='close' data-dismiss='alert'>x</button><strong>\"",
"+",
"I18n",
".",
"t",
"(",
"\"helpers.view_helper.generic.flash.success\"",
")",
"+",
"\"!</strong> #{flash[:notice]}</div>\"",
"end",
"render",
":inline",
"=>",
"html",
".",
"html_safe",
"end"
] | Returns generic notifications if the flash data exists | [
"Returns",
"generic",
"notifications",
"if",
"the",
"flash",
"data",
"exists"
] | 62654a2f2a48e3adb3105f4dafb6e315b460eaf4 | https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/helpers/roroacms/admin_roroa_helper.rb#L302-L315 | train |
mrsimonfletcher/roroacms | app/helpers/roroacms/admin_roroa_helper.rb | Roroacms.AdminRoroaHelper.append_application_menu | def append_application_menu
html = ''
Roroacms.append_menu.each do |f|
html += (render :partial => 'roroacms/admin/partials/append_sidebar_menu', :locals => { :menu_block => f })
end
html.html_safe
end | ruby | def append_application_menu
html = ''
Roroacms.append_menu.each do |f|
html += (render :partial => 'roroacms/admin/partials/append_sidebar_menu', :locals => { :menu_block => f })
end
html.html_safe
end | [
"def",
"append_application_menu",
"html",
"=",
"''",
"Roroacms",
".",
"append_menu",
".",
"each",
"do",
"|",
"f",
"|",
"html",
"+=",
"(",
"render",
":partial",
"=>",
"'roroacms/admin/partials/append_sidebar_menu'",
",",
":locals",
"=>",
"{",
":menu_block",
"=>",
"f",
"}",
")",
"end",
"html",
".",
"html_safe",
"end"
] | appends any extra menu items that are set in the applications configurations | [
"appends",
"any",
"extra",
"menu",
"items",
"that",
"are",
"set",
"in",
"the",
"applications",
"configurations"
] | 62654a2f2a48e3adb3105f4dafb6e315b460eaf4 | https://github.com/mrsimonfletcher/roroacms/blob/62654a2f2a48e3adb3105f4dafb6e315b460eaf4/app/helpers/roroacms/admin_roroa_helper.rb#L339-L345 | train |
PRX/pmp | lib/pmp/collection_document.rb | PMP.CollectionDocument.request | def request(method, url, body=nil) # :nodoc:
unless ['/', ''].include?(URI::parse(url).path)
setup_oauth_token
end
begin
raw = connection(current_options.merge({url: url})).send(method) do |req|
if [:post, :put].include?(method.to_sym) && !body.blank?
req.body = PMP::CollectionDocument.to_persist_json(body)
end
end
rescue Faraday::Error::ResourceNotFound => not_found_ex
if (method.to_sym == :get)
raw = OpenStruct.new(body: nil, status: 404)
else
raise not_found_ex
end
end
# may not need this, but remember how we made this response
PMP::Response.new(raw, {method: method, url: url, body: body})
end | ruby | def request(method, url, body=nil) # :nodoc:
unless ['/', ''].include?(URI::parse(url).path)
setup_oauth_token
end
begin
raw = connection(current_options.merge({url: url})).send(method) do |req|
if [:post, :put].include?(method.to_sym) && !body.blank?
req.body = PMP::CollectionDocument.to_persist_json(body)
end
end
rescue Faraday::Error::ResourceNotFound => not_found_ex
if (method.to_sym == :get)
raw = OpenStruct.new(body: nil, status: 404)
else
raise not_found_ex
end
end
# may not need this, but remember how we made this response
PMP::Response.new(raw, {method: method, url: url, body: body})
end | [
"def",
"request",
"(",
"method",
",",
"url",
",",
"body",
"=",
"nil",
")",
"unless",
"[",
"'/'",
",",
"''",
"]",
".",
"include?",
"(",
"URI",
"::",
"parse",
"(",
"url",
")",
".",
"path",
")",
"setup_oauth_token",
"end",
"begin",
"raw",
"=",
"connection",
"(",
"current_options",
".",
"merge",
"(",
"{",
"url",
":",
"url",
"}",
")",
")",
".",
"send",
"(",
"method",
")",
"do",
"|",
"req",
"|",
"if",
"[",
":post",
",",
":put",
"]",
".",
"include?",
"(",
"method",
".",
"to_sym",
")",
"&&",
"!",
"body",
".",
"blank?",
"req",
".",
"body",
"=",
"PMP",
"::",
"CollectionDocument",
".",
"to_persist_json",
"(",
"body",
")",
"end",
"end",
"rescue",
"Faraday",
"::",
"Error",
"::",
"ResourceNotFound",
"=>",
"not_found_ex",
"if",
"(",
"method",
".",
"to_sym",
"==",
":get",
")",
"raw",
"=",
"OpenStruct",
".",
"new",
"(",
"body",
":",
"nil",
",",
"status",
":",
"404",
")",
"else",
"raise",
"not_found_ex",
"end",
"end",
"PMP",
"::",
"Response",
".",
"new",
"(",
"raw",
",",
"{",
"method",
":",
"method",
",",
"url",
":",
"url",
",",
"body",
":",
"body",
"}",
")",
"end"
] | url includes any params - full url | [
"url",
"includes",
"any",
"params",
"-",
"full",
"url"
] | b0628529405f90dfb59166f8c6966752f8216260 | https://github.com/PRX/pmp/blob/b0628529405f90dfb59166f8c6966752f8216260/lib/pmp/collection_document.rb#L168-L190 | train |
dingxizheng/mongoid_likes | lib/mongoid/likes/liker.rb | Mongoid.Liker.like | def like(likeable)
if !self.disliked?(likeable) and @@likeable_model_names.include? likeable.class.to_s.downcase
likeable.likers << self
self.save
else
false
end
end | ruby | def like(likeable)
if !self.disliked?(likeable) and @@likeable_model_names.include? likeable.class.to_s.downcase
likeable.likers << self
self.save
else
false
end
end | [
"def",
"like",
"(",
"likeable",
")",
"if",
"!",
"self",
".",
"disliked?",
"(",
"likeable",
")",
"and",
"@@likeable_model_names",
".",
"include?",
"likeable",
".",
"class",
".",
"to_s",
".",
"downcase",
"likeable",
".",
"likers",
"<<",
"self",
"self",
".",
"save",
"else",
"false",
"end",
"end"
] | user likes a likeable
example
===========
user.like(likeable) | [
"user",
"likes",
"a",
"likeable"
] | 6c9bc703421f1e24ad3b7eac9a1a47cc93d737b2 | https://github.com/dingxizheng/mongoid_likes/blob/6c9bc703421f1e24ad3b7eac9a1a47cc93d737b2/lib/mongoid/likes/liker.rb#L72-L79 | train |
dingxizheng/mongoid_likes | lib/mongoid/likes/liker.rb | Mongoid.Liker.unlike | def unlike(likeable)
if @@likeable_model_names.include? likeable.class.to_s.downcase
likeable.likers.delete self
self.save
else
false
end
end | ruby | def unlike(likeable)
if @@likeable_model_names.include? likeable.class.to_s.downcase
likeable.likers.delete self
self.save
else
false
end
end | [
"def",
"unlike",
"(",
"likeable",
")",
"if",
"@@likeable_model_names",
".",
"include?",
"likeable",
".",
"class",
".",
"to_s",
".",
"downcase",
"likeable",
".",
"likers",
".",
"delete",
"self",
"self",
".",
"save",
"else",
"false",
"end",
"end"
] | user unlike a likeable
example
===========
user.unlike(likeable) | [
"user",
"unlike",
"a",
"likeable"
] | 6c9bc703421f1e24ad3b7eac9a1a47cc93d737b2 | https://github.com/dingxizheng/mongoid_likes/blob/6c9bc703421f1e24ad3b7eac9a1a47cc93d737b2/lib/mongoid/likes/liker.rb#L88-L95 | train |
jimmyz/ruby-fs-stack | lib/ruby-fs-stack/familytree/person.rb | Org::Familysearch::Ws::Familytree::V2::Schema.Person.birth | def birth
birth = births.find{|b|!b.selected.nil?}
birth ||= births[0]
birth
end | ruby | def birth
birth = births.find{|b|!b.selected.nil?}
birth ||= births[0]
birth
end | [
"def",
"birth",
"birth",
"=",
"births",
".",
"find",
"{",
"|",
"b",
"|",
"!",
"b",
".",
"selected",
".",
"nil?",
"}",
"birth",
"||=",
"births",
"[",
"0",
"]",
"birth",
"end"
] | It should return the selected birth assertion unless it is
not set in which case it will return the first | [
"It",
"should",
"return",
"the",
"selected",
"birth",
"assertion",
"unless",
"it",
"is",
"not",
"set",
"in",
"which",
"case",
"it",
"will",
"return",
"the",
"first"
] | 11281818635984971026e750d32a5c4599557dd1 | https://github.com/jimmyz/ruby-fs-stack/blob/11281818635984971026e750d32a5c4599557dd1/lib/ruby-fs-stack/familytree/person.rb#L134-L138 | train |
jimmyz/ruby-fs-stack | lib/ruby-fs-stack/familytree/person.rb | Org::Familysearch::Ws::Familytree::V2::Schema.Person.death | def death
death = deaths.find{|b|!b.selected.nil?}
death ||= deaths[0]
death
end | ruby | def death
death = deaths.find{|b|!b.selected.nil?}
death ||= deaths[0]
death
end | [
"def",
"death",
"death",
"=",
"deaths",
".",
"find",
"{",
"|",
"b",
"|",
"!",
"b",
".",
"selected",
".",
"nil?",
"}",
"death",
"||=",
"deaths",
"[",
"0",
"]",
"death",
"end"
] | It should return the selected death assertion unless it is
not set in which case it will return the first | [
"It",
"should",
"return",
"the",
"selected",
"death",
"assertion",
"unless",
"it",
"is",
"not",
"set",
"in",
"which",
"case",
"it",
"will",
"return",
"the",
"first"
] | 11281818635984971026e750d32a5c4599557dd1 | https://github.com/jimmyz/ruby-fs-stack/blob/11281818635984971026e750d32a5c4599557dd1/lib/ruby-fs-stack/familytree/person.rb#L146-L150 | train |
jimmyz/ruby-fs-stack | lib/ruby-fs-stack/familytree/person.rb | Org::Familysearch::Ws::Familytree::V2::Schema.Person.select_mother_summary | def select_mother_summary(person_id)
add_parents!
couple = parents[0] || ParentsReference.new
couple.select_parent(person_id,'Female')
parents[0] = couple
end | ruby | def select_mother_summary(person_id)
add_parents!
couple = parents[0] || ParentsReference.new
couple.select_parent(person_id,'Female')
parents[0] = couple
end | [
"def",
"select_mother_summary",
"(",
"person_id",
")",
"add_parents!",
"couple",
"=",
"parents",
"[",
"0",
"]",
"||",
"ParentsReference",
".",
"new",
"couple",
".",
"select_parent",
"(",
"person_id",
",",
"'Female'",
")",
"parents",
"[",
"0",
"]",
"=",
"couple",
"end"
] | Select the mother for the summary view. This should be called on a Person record that
contains a person id and version.
Make sure you set both the mother and father before saving the person. Otherwise you will
set a single parent as the summary.
====Params
<tt>person_id</tt> - the person id of the mother that you would like to set as the summary
===Example
person = com.familytree_v2.person 'KWQS-BBR', :names => 'none', :genders => 'none', :events => 'none'
person.select_mother_summary('KWQS-BBQ')
person.select_father_summary('KWQS-BBT')
com.familytree_v2.save_person person
This is the recommended approach, to start with a "Version" person (no names, genders, or events) | [
"Select",
"the",
"mother",
"for",
"the",
"summary",
"view",
".",
"This",
"should",
"be",
"called",
"on",
"a",
"Person",
"record",
"that",
"contains",
"a",
"person",
"id",
"and",
"version",
"."
] | 11281818635984971026e750d32a5c4599557dd1 | https://github.com/jimmyz/ruby-fs-stack/blob/11281818635984971026e750d32a5c4599557dd1/lib/ruby-fs-stack/familytree/person.rb#L240-L245 | train |
jimmyz/ruby-fs-stack | lib/ruby-fs-stack/familytree/person.rb | Org::Familysearch::Ws::Familytree::V2::Schema.Person.select_father_summary | def select_father_summary(person_id)
add_parents!
couple = parents[0] || ParentsReference.new
couple.select_parent(person_id,'Male')
parents[0] = couple
end | ruby | def select_father_summary(person_id)
add_parents!
couple = parents[0] || ParentsReference.new
couple.select_parent(person_id,'Male')
parents[0] = couple
end | [
"def",
"select_father_summary",
"(",
"person_id",
")",
"add_parents!",
"couple",
"=",
"parents",
"[",
"0",
"]",
"||",
"ParentsReference",
".",
"new",
"couple",
".",
"select_parent",
"(",
"person_id",
",",
"'Male'",
")",
"parents",
"[",
"0",
"]",
"=",
"couple",
"end"
] | Select the father for the summary view. This should be called on a Person record that
contains a person id and version.
Make sure you set both the mother and father before saving the person. Otherwise you will
set a single parent as the summary.
====Params
<tt>person_id</tt> - the person id of the father that you would like to set as the summary
===Example
person = com.familytree_v2.person 'KWQS-BBR', :names => 'none', :genders => 'none', :events => 'none'
person.select_father_summary('KWQS-BBQ')
person.select_mother_summary('KWQS-BBT')
com.familytree_v2.save_person person
This is the recommended approach, to start with a "Version" person (no names, genders, or events) | [
"Select",
"the",
"father",
"for",
"the",
"summary",
"view",
".",
"This",
"should",
"be",
"called",
"on",
"a",
"Person",
"record",
"that",
"contains",
"a",
"person",
"id",
"and",
"version",
"."
] | 11281818635984971026e750d32a5c4599557dd1 | https://github.com/jimmyz/ruby-fs-stack/blob/11281818635984971026e750d32a5c4599557dd1/lib/ruby-fs-stack/familytree/person.rb#L263-L268 | train |
jimmyz/ruby-fs-stack | lib/ruby-fs-stack/familytree/person.rb | Org::Familysearch::Ws::Familytree::V2::Schema.Person.select_spouse_summary | def select_spouse_summary(person_id)
add_families!
family = FamilyReference.new
family.select_spouse(person_id)
families << family
end | ruby | def select_spouse_summary(person_id)
add_families!
family = FamilyReference.new
family.select_spouse(person_id)
families << family
end | [
"def",
"select_spouse_summary",
"(",
"person_id",
")",
"add_families!",
"family",
"=",
"FamilyReference",
".",
"new",
"family",
".",
"select_spouse",
"(",
"person_id",
")",
"families",
"<<",
"family",
"end"
] | Select the spouse for the summary view. This should be called on a Person record that
contains a person id and version.
====Params
<tt>person_id</tt> - the person id of the spouse that you would like to set as the summary
===Example
person = com.familytree_v2.person 'KWQS-BBR', :names => 'none', :genders => 'none', :events => 'none'
person.select_spouse_summary('KWQS-BBQ')
com.familytree_v2.save_person person
This is the recommended approach, to start with a "Version" person (no names, genders, or events) | [
"Select",
"the",
"spouse",
"for",
"the",
"summary",
"view",
".",
"This",
"should",
"be",
"called",
"on",
"a",
"Person",
"record",
"that",
"contains",
"a",
"person",
"id",
"and",
"version",
"."
] | 11281818635984971026e750d32a5c4599557dd1 | https://github.com/jimmyz/ruby-fs-stack/blob/11281818635984971026e750d32a5c4599557dd1/lib/ruby-fs-stack/familytree/person.rb#L282-L287 | train |
jimmyz/ruby-fs-stack | lib/ruby-fs-stack/familytree/person.rb | Org::Familysearch::Ws::Familytree::V2::Schema.Person.add_sealing_to_parents | def add_sealing_to_parents(options)
raise ArgumentError, ":mother option is required" if options[:mother].nil?
raise ArgumentError, ":father option is required" if options[:father].nil?
add_assertions!
options[:type] = OrdinanceType::Sealing_to_Parents
assertions.add_ordinance(options)
end | ruby | def add_sealing_to_parents(options)
raise ArgumentError, ":mother option is required" if options[:mother].nil?
raise ArgumentError, ":father option is required" if options[:father].nil?
add_assertions!
options[:type] = OrdinanceType::Sealing_to_Parents
assertions.add_ordinance(options)
end | [
"def",
"add_sealing_to_parents",
"(",
"options",
")",
"raise",
"ArgumentError",
",",
"\":mother option is required\"",
"if",
"options",
"[",
":mother",
"]",
".",
"nil?",
"raise",
"ArgumentError",
",",
"\":father option is required\"",
"if",
"options",
"[",
":father",
"]",
".",
"nil?",
"add_assertions!",
"options",
"[",
":type",
"]",
"=",
"OrdinanceType",
"::",
"Sealing_to_Parents",
"assertions",
".",
"add_ordinance",
"(",
"options",
")",
"end"
] | Add a sealing to parents ordinance
====Params
* <tt>options</tt> - accepts a :date, :place, :temple, :mother, and :father option
====Example
person.add_sealing_to_parents :date => '14 Aug 2009', :temple => 'SGEOR', :place => 'Salt Lake City, Utah' | [
"Add",
"a",
"sealing",
"to",
"parents",
"ordinance"
] | 11281818635984971026e750d32a5c4599557dd1 | https://github.com/jimmyz/ruby-fs-stack/blob/11281818635984971026e750d32a5c4599557dd1/lib/ruby-fs-stack/familytree/person.rb#L377-L383 | train |
jimmyz/ruby-fs-stack | lib/ruby-fs-stack/familytree/person.rb | Org::Familysearch::Ws::Familytree::V2::Schema.Person.select_relationship_ordinances | def select_relationship_ordinances(options)
raise ArgumentError, ":id required" if options[:id].nil?
if self.relationships
spouse_relationship = self.relationships.spouses.find{|s|s.id == options[:id]}
if spouse_relationship && spouse_relationship.assertions && spouse_relationship.assertions.ordinances
spouse_relationship.assertions.ordinances
else
[]
end
end
end | ruby | def select_relationship_ordinances(options)
raise ArgumentError, ":id required" if options[:id].nil?
if self.relationships
spouse_relationship = self.relationships.spouses.find{|s|s.id == options[:id]}
if spouse_relationship && spouse_relationship.assertions && spouse_relationship.assertions.ordinances
spouse_relationship.assertions.ordinances
else
[]
end
end
end | [
"def",
"select_relationship_ordinances",
"(",
"options",
")",
"raise",
"ArgumentError",
",",
"\":id required\"",
"if",
"options",
"[",
":id",
"]",
".",
"nil?",
"if",
"self",
".",
"relationships",
"spouse_relationship",
"=",
"self",
".",
"relationships",
".",
"spouses",
".",
"find",
"{",
"|",
"s",
"|",
"s",
".",
"id",
"==",
"options",
"[",
":id",
"]",
"}",
"if",
"spouse_relationship",
"&&",
"spouse_relationship",
".",
"assertions",
"&&",
"spouse_relationship",
".",
"assertions",
".",
"ordinances",
"spouse_relationship",
".",
"assertions",
".",
"ordinances",
"else",
"[",
"]",
"end",
"end",
"end"
] | only ordinance type is Sealing_to_Spouse | [
"only",
"ordinance",
"type",
"is",
"Sealing_to_Spouse"
] | 11281818635984971026e750d32a5c4599557dd1 | https://github.com/jimmyz/ruby-fs-stack/blob/11281818635984971026e750d32a5c4599557dd1/lib/ruby-fs-stack/familytree/person.rb#L482-L492 | train |
martinpoljak/em-files | lib/em-files.rb | EM.File.read | def read(length = nil, filter = nil, &block)
buffer = ""
pos = 0
# Arguments
if length.kind_of? Proc
filter = length
end
worker = Proc::new do
# Sets length for read
if not length.nil?
rlen = length - buffer.length
if rlen > @rw_len
rlen = @rw_len
end
else
rlen = @rw_len
end
# Reads
begin
chunk = @native.read(rlen)
if not filter.nil?
chunk = filter.call(chunk)
end
buffer << chunk
rescue Errno::EBADF
if @native.kind_of? ::File
self.reopen!
@native.seek(pos)
redo
else
raise
end
end
pos = @native.pos
# Returns or continues work
if @native.eof? or (buffer.length == length)
if not block.nil?
yield buffer # returns result
end
else
EM::next_tick { worker.call() } # continues work
end
end
worker.call()
end | ruby | def read(length = nil, filter = nil, &block)
buffer = ""
pos = 0
# Arguments
if length.kind_of? Proc
filter = length
end
worker = Proc::new do
# Sets length for read
if not length.nil?
rlen = length - buffer.length
if rlen > @rw_len
rlen = @rw_len
end
else
rlen = @rw_len
end
# Reads
begin
chunk = @native.read(rlen)
if not filter.nil?
chunk = filter.call(chunk)
end
buffer << chunk
rescue Errno::EBADF
if @native.kind_of? ::File
self.reopen!
@native.seek(pos)
redo
else
raise
end
end
pos = @native.pos
# Returns or continues work
if @native.eof? or (buffer.length == length)
if not block.nil?
yield buffer # returns result
end
else
EM::next_tick { worker.call() } # continues work
end
end
worker.call()
end | [
"def",
"read",
"(",
"length",
"=",
"nil",
",",
"filter",
"=",
"nil",
",",
"&",
"block",
")",
"buffer",
"=",
"\"\"",
"pos",
"=",
"0",
"if",
"length",
".",
"kind_of?",
"Proc",
"filter",
"=",
"length",
"end",
"worker",
"=",
"Proc",
"::",
"new",
"do",
"if",
"not",
"length",
".",
"nil?",
"rlen",
"=",
"length",
"-",
"buffer",
".",
"length",
"if",
"rlen",
">",
"@rw_len",
"rlen",
"=",
"@rw_len",
"end",
"else",
"rlen",
"=",
"@rw_len",
"end",
"begin",
"chunk",
"=",
"@native",
".",
"read",
"(",
"rlen",
")",
"if",
"not",
"filter",
".",
"nil?",
"chunk",
"=",
"filter",
".",
"call",
"(",
"chunk",
")",
"end",
"buffer",
"<<",
"chunk",
"rescue",
"Errno",
"::",
"EBADF",
"if",
"@native",
".",
"kind_of?",
"::",
"File",
"self",
".",
"reopen!",
"@native",
".",
"seek",
"(",
"pos",
")",
"redo",
"else",
"raise",
"end",
"end",
"pos",
"=",
"@native",
".",
"pos",
"if",
"@native",
".",
"eof?",
"or",
"(",
"buffer",
".",
"length",
"==",
"length",
")",
"if",
"not",
"block",
".",
"nil?",
"yield",
"buffer",
"end",
"else",
"EM",
"::",
"next_tick",
"{",
"worker",
".",
"call",
"(",
")",
"}",
"end",
"end",
"worker",
".",
"call",
"(",
")",
"end"
] | Constructor. If IO object is given instead of filepath, uses
it as native one and +mode+ argument is ignored.
@param [String, IO, StringIO] filepath path to file or IO object
@param [String] mode file access mode (see equivalent Ruby method)
@param [Integer] rwsize size of block operated during one tick
Reads data from file.
It will reopen the file if +EBADF: Bad file descriptor+ of
+File+ class IO object will occur.
@overload read(length, &block)
Reads specified amount of data from file.
@param [Integer] length length for read from file
@param [Proc] filter filter which for postprocessing each
read chunk
@param [Proc] block callback for returning the result
@yield [String] read data
@overload read(&block)
Reads whole content of file.
@param [Proc] filter filter which for processing each block
@param [Proc] block callback for returning the result
@yield [String] read data | [
"Constructor",
".",
"If",
"IO",
"object",
"is",
"given",
"instead",
"of",
"filepath",
"uses",
"it",
"as",
"native",
"one",
"and",
"+",
"mode",
"+",
"argument",
"is",
"ignored",
"."
] | 177666c2395d58432a10941282a4c687bad765d2 | https://github.com/martinpoljak/em-files/blob/177666c2395d58432a10941282a4c687bad765d2/lib/em-files.rb#L174-L227 | train |
martinpoljak/em-files | lib/em-files.rb | EM.File.write | def write(data, filter = nil, &block)
pos = 0
if data.kind_of? IO
io = data
else
io = StringIO::new(data)
end
worker = Proc::new do
# Writes
begin
chunk = io.read(@rw_len)
if not filter.nil?
chunk = filter.call(chunk)
end
@native.write(chunk)
rescue Errno::EBADF
if @native.kind_of? File
self.reopen!
@native.seek(pos)
redo
else
raise
end
end
pos = @native.pos
# Returns or continues work
if io.eof?
if not block.nil?
yield pos # returns result
end
else
EM::next_tick { worker.call() } # continues work
end
end
worker.call()
end | ruby | def write(data, filter = nil, &block)
pos = 0
if data.kind_of? IO
io = data
else
io = StringIO::new(data)
end
worker = Proc::new do
# Writes
begin
chunk = io.read(@rw_len)
if not filter.nil?
chunk = filter.call(chunk)
end
@native.write(chunk)
rescue Errno::EBADF
if @native.kind_of? File
self.reopen!
@native.seek(pos)
redo
else
raise
end
end
pos = @native.pos
# Returns or continues work
if io.eof?
if not block.nil?
yield pos # returns result
end
else
EM::next_tick { worker.call() } # continues work
end
end
worker.call()
end | [
"def",
"write",
"(",
"data",
",",
"filter",
"=",
"nil",
",",
"&",
"block",
")",
"pos",
"=",
"0",
"if",
"data",
".",
"kind_of?",
"IO",
"io",
"=",
"data",
"else",
"io",
"=",
"StringIO",
"::",
"new",
"(",
"data",
")",
"end",
"worker",
"=",
"Proc",
"::",
"new",
"do",
"begin",
"chunk",
"=",
"io",
".",
"read",
"(",
"@rw_len",
")",
"if",
"not",
"filter",
".",
"nil?",
"chunk",
"=",
"filter",
".",
"call",
"(",
"chunk",
")",
"end",
"@native",
".",
"write",
"(",
"chunk",
")",
"rescue",
"Errno",
"::",
"EBADF",
"if",
"@native",
".",
"kind_of?",
"File",
"self",
".",
"reopen!",
"@native",
".",
"seek",
"(",
"pos",
")",
"redo",
"else",
"raise",
"end",
"end",
"pos",
"=",
"@native",
".",
"pos",
"if",
"io",
".",
"eof?",
"if",
"not",
"block",
".",
"nil?",
"yield",
"pos",
"end",
"else",
"EM",
"::",
"next_tick",
"{",
"worker",
".",
"call",
"(",
")",
"}",
"end",
"end",
"worker",
".",
"call",
"(",
")",
"end"
] | Writes data to file. Supports writing both strings or copying
from another IO object. Returns length of written data to
callback if filename given or current position of output
string if IO used.
It will reopen the file if +EBADF: Bad file descriptor+ of
+File+ class IO object will occur on +File+ object.
@param [String, IO, StringIO] data data for write or IO object
@param [Proc] filter filter which for preprocessing each
written chunk
@param [Proc] block callback called when finish and for giving
back the length of written data
@yield [Integer] length of really written data | [
"Writes",
"data",
"to",
"file",
".",
"Supports",
"writing",
"both",
"strings",
"or",
"copying",
"from",
"another",
"IO",
"object",
".",
"Returns",
"length",
"of",
"written",
"data",
"to",
"callback",
"if",
"filename",
"given",
"or",
"current",
"position",
"of",
"output",
"string",
"if",
"IO",
"used",
"."
] | 177666c2395d58432a10941282a4c687bad765d2 | https://github.com/martinpoljak/em-files/blob/177666c2395d58432a10941282a4c687bad765d2/lib/em-files.rb#L254-L296 | train |
tatey/simple_mock | lib/simple_mock/tracer.rb | SimpleMock.Tracer.verify | def verify
differences = expected_calls.keys - actual_calls.keys
if differences.any?
raise MockExpectationError, "expected #{differences.first.inspect}"
else
true
end
end | ruby | def verify
differences = expected_calls.keys - actual_calls.keys
if differences.any?
raise MockExpectationError, "expected #{differences.first.inspect}"
else
true
end
end | [
"def",
"verify",
"differences",
"=",
"expected_calls",
".",
"keys",
"-",
"actual_calls",
".",
"keys",
"if",
"differences",
".",
"any?",
"raise",
"MockExpectationError",
",",
"\"expected #{differences.first.inspect}\"",
"else",
"true",
"end",
"end"
] | Verify that all methods were called as expected. Raises
+MockExpectationError+ if not called as expected. | [
"Verify",
"that",
"all",
"methods",
"were",
"called",
"as",
"expected",
".",
"Raises",
"+",
"MockExpectationError",
"+",
"if",
"not",
"called",
"as",
"expected",
"."
] | 3081f714228903745d66f32cc6186946a9f2524e | https://github.com/tatey/simple_mock/blob/3081f714228903745d66f32cc6186946a9f2524e/lib/simple_mock/tracer.rb#L27-L34 | train |
bblack16/bblib-ruby | lib/bblib/core/classes/task_timer.rb | BBLib.TaskTimer.time | def time(task = :default, type = :current)
return nil unless tasks.keys.include?(task)
numbers = tasks[task][:history].map { |v| v[:time] }
case type
when :current
return nil unless tasks[task][:current]
Time.now.to_f - tasks[task][:current]
when :min, :max, :first, :last
numbers.send(type)
when :avg
numbers.size.zero? ? nil : numbers.inject { |sum, n| sum + n }.to_f / numbers.size
when :sum
numbers.inject { |sum, n| sum + n }
when :all
numbers
when :count
numbers.size
end
end | ruby | def time(task = :default, type = :current)
return nil unless tasks.keys.include?(task)
numbers = tasks[task][:history].map { |v| v[:time] }
case type
when :current
return nil unless tasks[task][:current]
Time.now.to_f - tasks[task][:current]
when :min, :max, :first, :last
numbers.send(type)
when :avg
numbers.size.zero? ? nil : numbers.inject { |sum, n| sum + n }.to_f / numbers.size
when :sum
numbers.inject { |sum, n| sum + n }
when :all
numbers
when :count
numbers.size
end
end | [
"def",
"time",
"(",
"task",
"=",
":default",
",",
"type",
"=",
":current",
")",
"return",
"nil",
"unless",
"tasks",
".",
"keys",
".",
"include?",
"(",
"task",
")",
"numbers",
"=",
"tasks",
"[",
"task",
"]",
"[",
":history",
"]",
".",
"map",
"{",
"|",
"v",
"|",
"v",
"[",
":time",
"]",
"}",
"case",
"type",
"when",
":current",
"return",
"nil",
"unless",
"tasks",
"[",
"task",
"]",
"[",
":current",
"]",
"Time",
".",
"now",
".",
"to_f",
"-",
"tasks",
"[",
"task",
"]",
"[",
":current",
"]",
"when",
":min",
",",
":max",
",",
":first",
",",
":last",
"numbers",
".",
"send",
"(",
"type",
")",
"when",
":avg",
"numbers",
".",
"size",
".",
"zero?",
"?",
"nil",
":",
"numbers",
".",
"inject",
"{",
"|",
"sum",
",",
"n",
"|",
"sum",
"+",
"n",
"}",
".",
"to_f",
"/",
"numbers",
".",
"size",
"when",
":sum",
"numbers",
".",
"inject",
"{",
"|",
"sum",
",",
"n",
"|",
"sum",
"+",
"n",
"}",
"when",
":all",
"numbers",
"when",
":count",
"numbers",
".",
"size",
"end",
"end"
] | Returns an aggregated metric for a given type.
@param [Symbol] task The key value of the task to retrieve
@param [Symbol] type The metric to return.
Options are :avg, :min, :max, :first, :last, :sum, :all and :count.
@return [Float, Integer, Array] Returns either the aggregation (Numeric) or an Array in the case of :all. | [
"Returns",
"an",
"aggregated",
"metric",
"for",
"a",
"given",
"type",
"."
] | 274eedeb583cc56243884fd041645488d5bd08a9 | https://github.com/bblack16/bblib-ruby/blob/274eedeb583cc56243884fd041645488d5bd08a9/lib/bblib/core/classes/task_timer.rb#L21-L39 | train |
bblack16/bblib-ruby | lib/bblib/core/classes/task_timer.rb | BBLib.TaskTimer.clear | def clear(task = :default)
return nil unless tasks.keys.include?(task)
stop task
tasks[task][:history].clear
end | ruby | def clear(task = :default)
return nil unless tasks.keys.include?(task)
stop task
tasks[task][:history].clear
end | [
"def",
"clear",
"(",
"task",
"=",
":default",
")",
"return",
"nil",
"unless",
"tasks",
".",
"keys",
".",
"include?",
"(",
"task",
")",
"stop",
"task",
"tasks",
"[",
"task",
"]",
"[",
":history",
"]",
".",
"clear",
"end"
] | Removes all history for a given task
@param [Symbol] task The name of the task to clear history from.
@return [NilClass] Returns nil | [
"Removes",
"all",
"history",
"for",
"a",
"given",
"task"
] | 274eedeb583cc56243884fd041645488d5bd08a9 | https://github.com/bblack16/bblib-ruby/blob/274eedeb583cc56243884fd041645488d5bd08a9/lib/bblib/core/classes/task_timer.rb#L45-L49 | train |
bblack16/bblib-ruby | lib/bblib/core/classes/task_timer.rb | BBLib.TaskTimer.start | def start(task = :default)
tasks[task] = { history: [], current: nil } unless tasks.keys.include?(task)
stop task if tasks[task][:current]
tasks[task][:current] = Time.now.to_f
0
end | ruby | def start(task = :default)
tasks[task] = { history: [], current: nil } unless tasks.keys.include?(task)
stop task if tasks[task][:current]
tasks[task][:current] = Time.now.to_f
0
end | [
"def",
"start",
"(",
"task",
"=",
":default",
")",
"tasks",
"[",
"task",
"]",
"=",
"{",
"history",
":",
"[",
"]",
",",
"current",
":",
"nil",
"}",
"unless",
"tasks",
".",
"keys",
".",
"include?",
"(",
"task",
")",
"stop",
"task",
"if",
"tasks",
"[",
"task",
"]",
"[",
":current",
"]",
"tasks",
"[",
"task",
"]",
"[",
":current",
"]",
"=",
"Time",
".",
"now",
".",
"to_f",
"0",
"end"
] | Start a new timer for the referenced task. If a timer is already running for that task it will be stopped first.
@param [Symbol] task The name of the task to start.
@return [Integer] Returns 0 | [
"Start",
"a",
"new",
"timer",
"for",
"the",
"referenced",
"task",
".",
"If",
"a",
"timer",
"is",
"already",
"running",
"for",
"that",
"task",
"it",
"will",
"be",
"stopped",
"first",
"."
] | 274eedeb583cc56243884fd041645488d5bd08a9 | https://github.com/bblack16/bblib-ruby/blob/274eedeb583cc56243884fd041645488d5bd08a9/lib/bblib/core/classes/task_timer.rb#L55-L60 | train |
bblack16/bblib-ruby | lib/bblib/core/classes/task_timer.rb | BBLib.TaskTimer.stop | def stop(task = :default)
return nil unless tasks.keys.include?(task) && active?(task)
time_taken = Time.now.to_f - tasks[task][:current].to_f
tasks[task][:history] << { start: tasks[task][:current], stop: Time.now.to_f, time: time_taken }
tasks[task][:current] = nil
if retention && tasks[task][:history].size > retention then tasks[task][:history].shift end
time_taken
end | ruby | def stop(task = :default)
return nil unless tasks.keys.include?(task) && active?(task)
time_taken = Time.now.to_f - tasks[task][:current].to_f
tasks[task][:history] << { start: tasks[task][:current], stop: Time.now.to_f, time: time_taken }
tasks[task][:current] = nil
if retention && tasks[task][:history].size > retention then tasks[task][:history].shift end
time_taken
end | [
"def",
"stop",
"(",
"task",
"=",
":default",
")",
"return",
"nil",
"unless",
"tasks",
".",
"keys",
".",
"include?",
"(",
"task",
")",
"&&",
"active?",
"(",
"task",
")",
"time_taken",
"=",
"Time",
".",
"now",
".",
"to_f",
"-",
"tasks",
"[",
"task",
"]",
"[",
":current",
"]",
".",
"to_f",
"tasks",
"[",
"task",
"]",
"[",
":history",
"]",
"<<",
"{",
"start",
":",
"tasks",
"[",
"task",
"]",
"[",
":current",
"]",
",",
"stop",
":",
"Time",
".",
"now",
".",
"to_f",
",",
"time",
":",
"time_taken",
"}",
"tasks",
"[",
"task",
"]",
"[",
":current",
"]",
"=",
"nil",
"if",
"retention",
"&&",
"tasks",
"[",
"task",
"]",
"[",
":history",
"]",
".",
"size",
">",
"retention",
"then",
"tasks",
"[",
"task",
"]",
"[",
":history",
"]",
".",
"shift",
"end",
"time_taken",
"end"
] | Stop the referenced timer.
@param [Symbol] task The name of the task to stop.
@return [Float, NilClass] The amount of time the task had been running or nil if no matching task was found. | [
"Stop",
"the",
"referenced",
"timer",
"."
] | 274eedeb583cc56243884fd041645488d5bd08a9 | https://github.com/bblack16/bblib-ruby/blob/274eedeb583cc56243884fd041645488d5bd08a9/lib/bblib/core/classes/task_timer.rb#L66-L73 | train |
elm-city-craftworks/rails_setup | lib/rails_setup/environment.rb | RailsSetup.Environment.create_file | def create_file(file, name, requires_edit=false)
FileUtils.cp(file + '.example', file)
if requires_edit
puts "Update #{file} and run `bundle exec rake setup` to continue".color(:red)
system(ENV['EDITOR'], file) unless ENV['EDITOR'].blank?
exit
end
end | ruby | def create_file(file, name, requires_edit=false)
FileUtils.cp(file + '.example', file)
if requires_edit
puts "Update #{file} and run `bundle exec rake setup` to continue".color(:red)
system(ENV['EDITOR'], file) unless ENV['EDITOR'].blank?
exit
end
end | [
"def",
"create_file",
"(",
"file",
",",
"name",
",",
"requires_edit",
"=",
"false",
")",
"FileUtils",
".",
"cp",
"(",
"file",
"+",
"'.example'",
",",
"file",
")",
"if",
"requires_edit",
"puts",
"\"Update #{file} and run `bundle exec rake setup` to continue\"",
".",
"color",
"(",
":red",
")",
"system",
"(",
"ENV",
"[",
"'EDITOR'",
"]",
",",
"file",
")",
"unless",
"ENV",
"[",
"'EDITOR'",
"]",
".",
"blank?",
"exit",
"end",
"end"
] | Creates a file based on a '.example' version saved in the same folder
Will optionally open the new file in the default editor after creation | [
"Creates",
"a",
"file",
"based",
"on",
"a",
".",
"example",
"version",
"saved",
"in",
"the",
"same",
"folder",
"Will",
"optionally",
"open",
"the",
"new",
"file",
"in",
"the",
"default",
"editor",
"after",
"creation"
] | 77c15fb51565aaa666db2571e37e077e94b1a1c0 | https://github.com/elm-city-craftworks/rails_setup/blob/77c15fb51565aaa666db2571e37e077e94b1a1c0/lib/rails_setup/environment.rb#L55-L63 | train |
elm-city-craftworks/rails_setup | lib/rails_setup/environment.rb | RailsSetup.Environment.find_or_create_file | def find_or_create_file(file, name, requires_edit=false)
if File.exists?(file)
file
else
create_file(file, name, requires_edit)
end
end | ruby | def find_or_create_file(file, name, requires_edit=false)
if File.exists?(file)
file
else
create_file(file, name, requires_edit)
end
end | [
"def",
"find_or_create_file",
"(",
"file",
",",
"name",
",",
"requires_edit",
"=",
"false",
")",
"if",
"File",
".",
"exists?",
"(",
"file",
")",
"file",
"else",
"create_file",
"(",
"file",
",",
"name",
",",
"requires_edit",
")",
"end",
"end"
] | Looks for the specificed file and creates it if it does not exist | [
"Looks",
"for",
"the",
"specificed",
"file",
"and",
"creates",
"it",
"if",
"it",
"does",
"not",
"exist"
] | 77c15fb51565aaa666db2571e37e077e94b1a1c0 | https://github.com/elm-city-craftworks/rails_setup/blob/77c15fb51565aaa666db2571e37e077e94b1a1c0/lib/rails_setup/environment.rb#L67-L73 | train |
dprandzioch/avocado | lib/avodeploy/config.rb | AvoDeploy.Config.inherit_strategy | def inherit_strategy(strategy)
AvoDeploy::Deployment.instance.log.debug "Loading deployment strategy #{strategy.to_s}..."
strategy_file_path = File.dirname(__FILE__) + "/strategy/#{strategy.to_s}.rb"
if File.exist?(strategy_file_path)
require strategy_file_path
else
raise RuntimeError, "The requested strategy '#{strategy.to_s}' does not exist"
end
end | ruby | def inherit_strategy(strategy)
AvoDeploy::Deployment.instance.log.debug "Loading deployment strategy #{strategy.to_s}..."
strategy_file_path = File.dirname(__FILE__) + "/strategy/#{strategy.to_s}.rb"
if File.exist?(strategy_file_path)
require strategy_file_path
else
raise RuntimeError, "The requested strategy '#{strategy.to_s}' does not exist"
end
end | [
"def",
"inherit_strategy",
"(",
"strategy",
")",
"AvoDeploy",
"::",
"Deployment",
".",
"instance",
".",
"log",
".",
"debug",
"\"Loading deployment strategy #{strategy.to_s}...\"",
"strategy_file_path",
"=",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
"+",
"\"/strategy/#{strategy.to_s}.rb\"",
"if",
"File",
".",
"exist?",
"(",
"strategy_file_path",
")",
"require",
"strategy_file_path",
"else",
"raise",
"RuntimeError",
",",
"\"The requested strategy '#{strategy.to_s}' does not exist\"",
"end",
"end"
] | Loads a strategy. Because the strategy files are loaded in
the specified order, it's possible to override tasks.
This is how inheritance of strategies is realized.
@param strategy [Symbol] the strategy to load | [
"Loads",
"a",
"strategy",
".",
"Because",
"the",
"strategy",
"files",
"are",
"loaded",
"in",
"the",
"specified",
"order",
"it",
"s",
"possible",
"to",
"override",
"tasks",
".",
"This",
"is",
"how",
"inheritance",
"of",
"strategies",
"is",
"realized",
"."
] | 473dd86b0e2334fe5e7981227892ba5ca4b18bb3 | https://github.com/dprandzioch/avocado/blob/473dd86b0e2334fe5e7981227892ba5ca4b18bb3/lib/avodeploy/config.rb#L54-L64 | train |
dprandzioch/avocado | lib/avodeploy/config.rb | AvoDeploy.Config.task | def task(name, options = {}, &block)
AvoDeploy::Deployment.instance.log.debug "registering task #{name}..."
AvoDeploy::Deployment.instance.task_manager.add_task(name, options, &block)
end | ruby | def task(name, options = {}, &block)
AvoDeploy::Deployment.instance.log.debug "registering task #{name}..."
AvoDeploy::Deployment.instance.task_manager.add_task(name, options, &block)
end | [
"def",
"task",
"(",
"name",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"AvoDeploy",
"::",
"Deployment",
".",
"instance",
".",
"log",
".",
"debug",
"\"registering task #{name}...\"",
"AvoDeploy",
"::",
"Deployment",
".",
"instance",
".",
"task_manager",
".",
"add_task",
"(",
"name",
",",
"options",
",",
"&",
"block",
")",
"end"
] | Defines a task
@param name [Symbol] task name
@param options [Hash] task options
@param block [Block] the code to be executed when the task is started | [
"Defines",
"a",
"task"
] | 473dd86b0e2334fe5e7981227892ba5ca4b18bb3 | https://github.com/dprandzioch/avocado/blob/473dd86b0e2334fe5e7981227892ba5ca4b18bb3/lib/avodeploy/config.rb#L81-L84 | train |
dprandzioch/avocado | lib/avodeploy/config.rb | AvoDeploy.Config.setup_stage | def setup_stage(name, options = {}, &block)
stages[name] = ''
if options.has_key?(:desc)
stages[name] = options[:desc]
end
if name.to_s == get(:stage).to_s
@loaded_stage = name
instance_eval(&block)
end
end | ruby | def setup_stage(name, options = {}, &block)
stages[name] = ''
if options.has_key?(:desc)
stages[name] = options[:desc]
end
if name.to_s == get(:stage).to_s
@loaded_stage = name
instance_eval(&block)
end
end | [
"def",
"setup_stage",
"(",
"name",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"stages",
"[",
"name",
"]",
"=",
"''",
"if",
"options",
".",
"has_key?",
"(",
":desc",
")",
"stages",
"[",
"name",
"]",
"=",
"options",
"[",
":desc",
"]",
"end",
"if",
"name",
".",
"to_s",
"==",
"get",
"(",
":stage",
")",
".",
"to_s",
"@loaded_stage",
"=",
"name",
"instance_eval",
"(",
"&",
"block",
")",
"end",
"end"
] | Defines a stage
@param name [Symbol] stage name
@param options [Hash] stage options
@param block [Block] the stage configuration | [
"Defines",
"a",
"stage"
] | 473dd86b0e2334fe5e7981227892ba5ca4b18bb3 | https://github.com/dprandzioch/avocado/blob/473dd86b0e2334fe5e7981227892ba5ca4b18bb3/lib/avodeploy/config.rb#L91-L103 | train |
jns/Aims | lib/aims/vectorize.rb | Aims.Vectorize.dot | def dot(a, b)
unless a.size == b.size
raise "Vectors must be the same length"
end
# Make element-by-element array of pairs
(a.to_a).zip(b.to_a).inject(0) {|tot, pair| tot = tot + pair[0]*pair[1]}
end | ruby | def dot(a, b)
unless a.size == b.size
raise "Vectors must be the same length"
end
# Make element-by-element array of pairs
(a.to_a).zip(b.to_a).inject(0) {|tot, pair| tot = tot + pair[0]*pair[1]}
end | [
"def",
"dot",
"(",
"a",
",",
"b",
")",
"unless",
"a",
".",
"size",
"==",
"b",
".",
"size",
"raise",
"\"Vectors must be the same length\"",
"end",
"(",
"a",
".",
"to_a",
")",
".",
"zip",
"(",
"b",
".",
"to_a",
")",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"tot",
",",
"pair",
"|",
"tot",
"=",
"tot",
"+",
"pair",
"[",
"0",
"]",
"*",
"pair",
"[",
"1",
"]",
"}",
"end"
] | Dot product of two n-element arrays | [
"Dot",
"product",
"of",
"two",
"n",
"-",
"element",
"arrays"
] | 2dcb6c02cd05b2d0c8ab72be4e85d60375df296c | https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/vectorize.rb#L5-L12 | train |
jns/Aims | lib/aims/vectorize.rb | Aims.Vectorize.cross | def cross(b,c)
unless b.size == 3 and c.size == 3
raise "Vectors must be of length 3"
end
Vector[b[1]*c[2] - b[2]*c[1], b[2]*c[0] - b[0]*c[2], b[0]*c[1] - b[1]*c[0]]
end | ruby | def cross(b,c)
unless b.size == 3 and c.size == 3
raise "Vectors must be of length 3"
end
Vector[b[1]*c[2] - b[2]*c[1], b[2]*c[0] - b[0]*c[2], b[0]*c[1] - b[1]*c[0]]
end | [
"def",
"cross",
"(",
"b",
",",
"c",
")",
"unless",
"b",
".",
"size",
"==",
"3",
"and",
"c",
".",
"size",
"==",
"3",
"raise",
"\"Vectors must be of length 3\"",
"end",
"Vector",
"[",
"b",
"[",
"1",
"]",
"*",
"c",
"[",
"2",
"]",
"-",
"b",
"[",
"2",
"]",
"*",
"c",
"[",
"1",
"]",
",",
"b",
"[",
"2",
"]",
"*",
"c",
"[",
"0",
"]",
"-",
"b",
"[",
"0",
"]",
"*",
"c",
"[",
"2",
"]",
",",
"b",
"[",
"0",
"]",
"*",
"c",
"[",
"1",
"]",
"-",
"b",
"[",
"1",
"]",
"*",
"c",
"[",
"0",
"]",
"]",
"end"
] | Cross product of two arrays of length 3 | [
"Cross",
"product",
"of",
"two",
"arrays",
"of",
"length",
"3"
] | 2dcb6c02cd05b2d0c8ab72be4e85d60375df296c | https://github.com/jns/Aims/blob/2dcb6c02cd05b2d0c8ab72be4e85d60375df296c/lib/aims/vectorize.rb#L15-L20 | train |
arvicco/poster | lib/poster/encoding.rb | Poster.Encoding.xml_encode | def xml_encode string
puts string.each_char.size
string.each_char.map do |p|
case
when CONVERTIBLES[p]
CONVERTIBLES[p]
when XML_ENTITIES[p]
"&##{XML_ENTITIES[p]};"
else
p
end
end.reduce(:+)
end | ruby | def xml_encode string
puts string.each_char.size
string.each_char.map do |p|
case
when CONVERTIBLES[p]
CONVERTIBLES[p]
when XML_ENTITIES[p]
"&##{XML_ENTITIES[p]};"
else
p
end
end.reduce(:+)
end | [
"def",
"xml_encode",
"string",
"puts",
"string",
".",
"each_char",
".",
"size",
"string",
".",
"each_char",
".",
"map",
"do",
"|",
"p",
"|",
"case",
"when",
"CONVERTIBLES",
"[",
"p",
"]",
"CONVERTIBLES",
"[",
"p",
"]",
"when",
"XML_ENTITIES",
"[",
"p",
"]",
"\"&##{XML_ENTITIES[p]};\"",
"else",
"p",
"end",
"end",
".",
"reduce",
"(",
":+",
")",
"end"
] | Encode Russian UTF-8 string to XML Entities format,
converting weird Unicode chars along the way | [
"Encode",
"Russian",
"UTF",
"-",
"8",
"string",
"to",
"XML",
"Entities",
"format",
"converting",
"weird",
"Unicode",
"chars",
"along",
"the",
"way"
] | a5f22f7cb02116ab4dc5b7f2bdb672306b3dac63 | https://github.com/arvicco/poster/blob/a5f22f7cb02116ab4dc5b7f2bdb672306b3dac63/lib/poster/encoding.rb#L127-L139 | train |
chrisjones-tripletri/action_command | lib/action_command/result.rb | ActionCommand.Result.debug | def debug(msg = nil)
if @logger
msg = build_log(msg || yield, ActionCommand::LOG_KIND_DEBUG)
@logger.info(format_log(msg))
end
end | ruby | def debug(msg = nil)
if @logger
msg = build_log(msg || yield, ActionCommand::LOG_KIND_DEBUG)
@logger.info(format_log(msg))
end
end | [
"def",
"debug",
"(",
"msg",
"=",
"nil",
")",
"if",
"@logger",
"msg",
"=",
"build_log",
"(",
"msg",
"||",
"yield",
",",
"ActionCommand",
"::",
"LOG_KIND_DEBUG",
")",
"@logger",
".",
"info",
"(",
"format_log",
"(",
"msg",
")",
")",
"end",
"end"
] | display an debugging message to the logger, if there is one.
@yield return a message or hash | [
"display",
"an",
"debugging",
"message",
"to",
"the",
"logger",
"if",
"there",
"is",
"one",
"."
] | 9b9a8ba30e407ca6d88a62a164d1dc22ba149874 | https://github.com/chrisjones-tripletri/action_command/blob/9b9a8ba30e407ca6d88a62a164d1dc22ba149874/lib/action_command/result.rb#L31-L36 | train |
chrisjones-tripletri/action_command | lib/action_command/result.rb | ActionCommand.Result.info | def info(msg = nil)
if @logger
msg = build_log(msg || yield, ActionCommand::LOG_KIND_INFO)
@logger.info(format_log(msg))
end
end | ruby | def info(msg = nil)
if @logger
msg = build_log(msg || yield, ActionCommand::LOG_KIND_INFO)
@logger.info(format_log(msg))
end
end | [
"def",
"info",
"(",
"msg",
"=",
"nil",
")",
"if",
"@logger",
"msg",
"=",
"build_log",
"(",
"msg",
"||",
"yield",
",",
"ActionCommand",
"::",
"LOG_KIND_INFO",
")",
"@logger",
".",
"info",
"(",
"format_log",
"(",
"msg",
")",
")",
"end",
"end"
] | display an informational message to the logger, if there is one.
@yield return a message or hash | [
"display",
"an",
"informational",
"message",
"to",
"the",
"logger",
"if",
"there",
"is",
"one",
"."
] | 9b9a8ba30e407ca6d88a62a164d1dc22ba149874 | https://github.com/chrisjones-tripletri/action_command/blob/9b9a8ba30e407ca6d88a62a164d1dc22ba149874/lib/action_command/result.rb#L40-L45 | train |
chrisjones-tripletri/action_command | lib/action_command/result.rb | ActionCommand.Result.error | def error(msg)
if @logger
msg = build_log(msg, ActionCommand::LOG_KIND_ERROR)
@logger.error(format_log(msg))
end
end | ruby | def error(msg)
if @logger
msg = build_log(msg, ActionCommand::LOG_KIND_ERROR)
@logger.error(format_log(msg))
end
end | [
"def",
"error",
"(",
"msg",
")",
"if",
"@logger",
"msg",
"=",
"build_log",
"(",
"msg",
",",
"ActionCommand",
"::",
"LOG_KIND_ERROR",
")",
"@logger",
".",
"error",
"(",
"format_log",
"(",
"msg",
")",
")",
"end",
"end"
] | display an error message to the logger, if there is one. | [
"display",
"an",
"error",
"message",
"to",
"the",
"logger",
"if",
"there",
"is",
"one",
"."
] | 9b9a8ba30e407ca6d88a62a164d1dc22ba149874 | https://github.com/chrisjones-tripletri/action_command/blob/9b9a8ba30e407ca6d88a62a164d1dc22ba149874/lib/action_command/result.rb#L48-L53 | train |
chrisjones-tripletri/action_command | lib/action_command/result.rb | ActionCommand.Result.push | def push(key, cmd)
return unless key
old_cur = current
if old_cur.key?(key)
@values << old_cur[key]
else
@values << {}
old_cur[key] = @values.last
end
@stack << { key: key, cmd: cmd } if @logger
end | ruby | def push(key, cmd)
return unless key
old_cur = current
if old_cur.key?(key)
@values << old_cur[key]
else
@values << {}
old_cur[key] = @values.last
end
@stack << { key: key, cmd: cmd } if @logger
end | [
"def",
"push",
"(",
"key",
",",
"cmd",
")",
"return",
"unless",
"key",
"old_cur",
"=",
"current",
"if",
"old_cur",
".",
"key?",
"(",
"key",
")",
"@values",
"<<",
"old_cur",
"[",
"key",
"]",
"else",
"@values",
"<<",
"{",
"}",
"old_cur",
"[",
"key",
"]",
"=",
"@values",
".",
"last",
"end",
"@stack",
"<<",
"{",
"key",
":",
"key",
",",
"cmd",
":",
"cmd",
"}",
"if",
"@logger",
"end"
] | adds results under the subkey until pop is called | [
"adds",
"results",
"under",
"the",
"subkey",
"until",
"pop",
"is",
"called"
] | 9b9a8ba30e407ca6d88a62a164d1dc22ba149874 | https://github.com/chrisjones-tripletri/action_command/blob/9b9a8ba30e407ca6d88a62a164d1dc22ba149874/lib/action_command/result.rb#L86-L96 | train |
chrisjones-tripletri/action_command | lib/action_command/result.rb | ActionCommand.Result.log_input | def log_input(params)
return unless @logger
output = params.reject { |k, _v| internal_key?(k) }
log_info_hash(output, ActionCommand::LOG_KIND_COMMAND_INPUT)
end | ruby | def log_input(params)
return unless @logger
output = params.reject { |k, _v| internal_key?(k) }
log_info_hash(output, ActionCommand::LOG_KIND_COMMAND_INPUT)
end | [
"def",
"log_input",
"(",
"params",
")",
"return",
"unless",
"@logger",
"output",
"=",
"params",
".",
"reject",
"{",
"|",
"k",
",",
"_v",
"|",
"internal_key?",
"(",
"k",
")",
"}",
"log_info_hash",
"(",
"output",
",",
"ActionCommand",
"::",
"LOG_KIND_COMMAND_INPUT",
")",
"end"
] | Used internally to log the input parameters to a command | [
"Used",
"internally",
"to",
"log",
"the",
"input",
"parameters",
"to",
"a",
"command"
] | 9b9a8ba30e407ca6d88a62a164d1dc22ba149874 | https://github.com/chrisjones-tripletri/action_command/blob/9b9a8ba30e407ca6d88a62a164d1dc22ba149874/lib/action_command/result.rb#L131-L135 | train |
chrisjones-tripletri/action_command | lib/action_command/result.rb | ActionCommand.Result.log_output | def log_output
return unless @logger
# only log the first level parameters, subcommands will log
# their own output.
output = current.reject { |k, v| v.is_a?(Hash) || internal_key?(k) }
log_info_hash(output, ActionCommand::LOG_KIND_COMMAND_OUTPUT)
end | ruby | def log_output
return unless @logger
# only log the first level parameters, subcommands will log
# their own output.
output = current.reject { |k, v| v.is_a?(Hash) || internal_key?(k) }
log_info_hash(output, ActionCommand::LOG_KIND_COMMAND_OUTPUT)
end | [
"def",
"log_output",
"return",
"unless",
"@logger",
"output",
"=",
"current",
".",
"reject",
"{",
"|",
"k",
",",
"v",
"|",
"v",
".",
"is_a?",
"(",
"Hash",
")",
"||",
"internal_key?",
"(",
"k",
")",
"}",
"log_info_hash",
"(",
"output",
",",
"ActionCommand",
"::",
"LOG_KIND_COMMAND_OUTPUT",
")",
"end"
] | Used internally to log the output parameters for a command. | [
"Used",
"internally",
"to",
"log",
"the",
"output",
"parameters",
"for",
"a",
"command",
"."
] | 9b9a8ba30e407ca6d88a62a164d1dc22ba149874 | https://github.com/chrisjones-tripletri/action_command/blob/9b9a8ba30e407ca6d88a62a164d1dc22ba149874/lib/action_command/result.rb#L138-L144 | train |
triglav-dataflow/triglav-agent-framework-ruby | lib/triglav/agent/status.rb | Triglav::Agent.Status.merge! | def merge!(*args)
val = args.pop
keys = args.flatten
StorageFile.merge!(path, [*@parents, *keys], val)
end | ruby | def merge!(*args)
val = args.pop
keys = args.flatten
StorageFile.merge!(path, [*@parents, *keys], val)
end | [
"def",
"merge!",
"(",
"*",
"args",
")",
"val",
"=",
"args",
".",
"pop",
"keys",
"=",
"args",
".",
"flatten",
"StorageFile",
".",
"merge!",
"(",
"path",
",",
"[",
"*",
"@parents",
",",
"*",
"keys",
"]",
",",
"val",
")",
"end"
] | Merge Hash value with existing Hash value.
merge!(val)
merge!(key, val)
merge!(key1, key2, val)
merge!([key], val)
merge!([key1, key2], val) | [
"Merge",
"Hash",
"value",
"with",
"existing",
"Hash",
"value",
"."
] | a2517253a2b151b8ece3c22f389e5a2c38d93a88 | https://github.com/triglav-dataflow/triglav-agent-framework-ruby/blob/a2517253a2b151b8ece3c22f389e5a2c38d93a88/lib/triglav/agent/status.rb#L36-L40 | train |
rit-sse-mycroft/template-ruby | lib/mycroft/helpers.rb | Mycroft.Helpers.parse_message | def parse_message(msg)
msg = msg.to_s
re = /([A-Z_]+) ({.*})$/
msg_split = re.match(msg)
if msg_split.nil?
re = /^([A-Z_]+)$/
msg_split = re.match(msg)
raise "Error: Malformed Message" if not msg_split
type = msg_split[1]
data = {}
else
type = msg_split[1]
data = JSON.parse(msg_split[2])
end
{type: type, data: data}
end | ruby | def parse_message(msg)
msg = msg.to_s
re = /([A-Z_]+) ({.*})$/
msg_split = re.match(msg)
if msg_split.nil?
re = /^([A-Z_]+)$/
msg_split = re.match(msg)
raise "Error: Malformed Message" if not msg_split
type = msg_split[1]
data = {}
else
type = msg_split[1]
data = JSON.parse(msg_split[2])
end
{type: type, data: data}
end | [
"def",
"parse_message",
"(",
"msg",
")",
"msg",
"=",
"msg",
".",
"to_s",
"re",
"=",
"/",
"/",
"msg_split",
"=",
"re",
".",
"match",
"(",
"msg",
")",
"if",
"msg_split",
".",
"nil?",
"re",
"=",
"/",
"/",
"msg_split",
"=",
"re",
".",
"match",
"(",
"msg",
")",
"raise",
"\"Error: Malformed Message\"",
"if",
"not",
"msg_split",
"type",
"=",
"msg_split",
"[",
"1",
"]",
"data",
"=",
"{",
"}",
"else",
"type",
"=",
"msg_split",
"[",
"1",
"]",
"data",
"=",
"JSON",
".",
"parse",
"(",
"msg_split",
"[",
"2",
"]",
")",
"end",
"{",
"type",
":",
"type",
",",
"data",
":",
"data",
"}",
"end"
] | Parses a message | [
"Parses",
"a",
"message"
] | 60ede42375b4647b9770bc9a03e614f8d90233ac | https://github.com/rit-sse-mycroft/template-ruby/blob/60ede42375b4647b9770bc9a03e614f8d90233ac/lib/mycroft/helpers.rb#L5-L20 | train |
rit-sse-mycroft/template-ruby | lib/mycroft/helpers.rb | Mycroft.Helpers.send_message | def send_message(type, message=nil)
message = message.nil? ? message = '' : message.to_json
body = type + ' ' + message
body.strip!
length = body.bytesize
@client.write("#{length}\n#{body}")
end | ruby | def send_message(type, message=nil)
message = message.nil? ? message = '' : message.to_json
body = type + ' ' + message
body.strip!
length = body.bytesize
@client.write("#{length}\n#{body}")
end | [
"def",
"send_message",
"(",
"type",
",",
"message",
"=",
"nil",
")",
"message",
"=",
"message",
".",
"nil?",
"?",
"message",
"=",
"''",
":",
"message",
".",
"to_json",
"body",
"=",
"type",
"+",
"' '",
"+",
"message",
"body",
".",
"strip!",
"length",
"=",
"body",
".",
"bytesize",
"@client",
".",
"write",
"(",
"\"#{length}\\n#{body}\"",
")",
"end"
] | Sends a message of a specific type | [
"Sends",
"a",
"message",
"of",
"a",
"specific",
"type"
] | 60ede42375b4647b9770bc9a03e614f8d90233ac | https://github.com/rit-sse-mycroft/template-ruby/blob/60ede42375b4647b9770bc9a03e614f8d90233ac/lib/mycroft/helpers.rb#L23-L29 | train |
triglav-dataflow/triglav-agent-framework-ruby | lib/triglav/agent/api_client.rb | Triglav::Agent.ApiClient.list_aggregated_resources | def list_aggregated_resources(uri_prefix)
$logger.debug { "ApiClient#list_aggregated_resources(#{uri_prefix.inspect})" }
resources_api = TriglavClient::ResourcesApi.new(@api_client)
handle_error { resources_api.list_aggregated_resources(uri_prefix) }
end | ruby | def list_aggregated_resources(uri_prefix)
$logger.debug { "ApiClient#list_aggregated_resources(#{uri_prefix.inspect})" }
resources_api = TriglavClient::ResourcesApi.new(@api_client)
handle_error { resources_api.list_aggregated_resources(uri_prefix) }
end | [
"def",
"list_aggregated_resources",
"(",
"uri_prefix",
")",
"$logger",
".",
"debug",
"{",
"\"ApiClient#list_aggregated_resources(#{uri_prefix.inspect})\"",
"}",
"resources_api",
"=",
"TriglavClient",
"::",
"ResourcesApi",
".",
"new",
"(",
"@api_client",
")",
"handle_error",
"{",
"resources_api",
".",
"list_aggregated_resources",
"(",
"uri_prefix",
")",
"}",
"end"
] | List resources required to be monitored
@param [String] uri_prefix
@return [Array of TriglavClient::ResourceEachResponse] array of resources
@see TriglavClient::ResourceEachResponse | [
"List",
"resources",
"required",
"to",
"be",
"monitored"
] | a2517253a2b151b8ece3c22f389e5a2c38d93a88 | https://github.com/triglav-dataflow/triglav-agent-framework-ruby/blob/a2517253a2b151b8ece3c22f389e5a2c38d93a88/lib/triglav/agent/api_client.rb#L59-L63 | train |
daws/exact_target_sdk | lib/exact_target_sdk/api_object.rb | ExactTargetSDK.APIObject.render_properties! | def render_properties!(xml)
self.class.properties.each do |property, options|
next unless instance_variable_get("@_set_#{property}")
property_value = self.send(property)
render_property!(property, property_value, xml, options)
end
end | ruby | def render_properties!(xml)
self.class.properties.each do |property, options|
next unless instance_variable_get("@_set_#{property}")
property_value = self.send(property)
render_property!(property, property_value, xml, options)
end
end | [
"def",
"render_properties!",
"(",
"xml",
")",
"self",
".",
"class",
".",
"properties",
".",
"each",
"do",
"|",
"property",
",",
"options",
"|",
"next",
"unless",
"instance_variable_get",
"(",
"\"@_set_#{property}\"",
")",
"property_value",
"=",
"self",
".",
"send",
"(",
"property",
")",
"render_property!",
"(",
"property",
",",
"property_value",
",",
"xml",
",",
"options",
")",
"end",
"end"
] | By default, loops through all registered properties, and renders
each that has been explicitly set.
May be overridden. | [
"By",
"default",
"loops",
"through",
"all",
"registered",
"properties",
"and",
"renders",
"each",
"that",
"has",
"been",
"explicitly",
"set",
"."
] | 64fde8f61356a5f0c75586a10b07d175adfeac12 | https://github.com/daws/exact_target_sdk/blob/64fde8f61356a5f0c75586a10b07d175adfeac12/lib/exact_target_sdk/api_object.rb#L130-L136 | train |
hinrik/ircsupport | lib/ircsupport/parser.rb | IRCSupport.Parser.compose | def compose(line)
raise ArgumentError, "You must specify a command" if !line.command
raw_line = ''
raw_line << ":#{line.prefix} " if line.prefix
raw_line << line.command
if line.args
line.args.each_with_index do |arg, idx|
raw_line << ' '
if idx != line.args.count-1 and arg.match(@@space)
raise ArgumentError, "Only the last argument may contain spaces"
end
if idx == line.args.count-1
raw_line << ':' if arg.match(@@space)
end
raw_line << arg
end
end
return raw_line
end | ruby | def compose(line)
raise ArgumentError, "You must specify a command" if !line.command
raw_line = ''
raw_line << ":#{line.prefix} " if line.prefix
raw_line << line.command
if line.args
line.args.each_with_index do |arg, idx|
raw_line << ' '
if idx != line.args.count-1 and arg.match(@@space)
raise ArgumentError, "Only the last argument may contain spaces"
end
if idx == line.args.count-1
raw_line << ':' if arg.match(@@space)
end
raw_line << arg
end
end
return raw_line
end | [
"def",
"compose",
"(",
"line",
")",
"raise",
"ArgumentError",
",",
"\"You must specify a command\"",
"if",
"!",
"line",
".",
"command",
"raw_line",
"=",
"''",
"raw_line",
"<<",
"\":#{line.prefix} \"",
"if",
"line",
".",
"prefix",
"raw_line",
"<<",
"line",
".",
"command",
"if",
"line",
".",
"args",
"line",
".",
"args",
".",
"each_with_index",
"do",
"|",
"arg",
",",
"idx",
"|",
"raw_line",
"<<",
"' '",
"if",
"idx",
"!=",
"line",
".",
"args",
".",
"count",
"-",
"1",
"and",
"arg",
".",
"match",
"(",
"@@space",
")",
"raise",
"ArgumentError",
",",
"\"Only the last argument may contain spaces\"",
"end",
"if",
"idx",
"==",
"line",
".",
"args",
".",
"count",
"-",
"1",
"raw_line",
"<<",
"':'",
"if",
"arg",
".",
"match",
"(",
"@@space",
")",
"end",
"raw_line",
"<<",
"arg",
"end",
"end",
"return",
"raw_line",
"end"
] | Compose an IRC protocol line.
@param [IRCSupport::Line] line An IRC protocol line object
(as returned by {#decompose}).
@return [String] An IRC protocol line. | [
"Compose",
"an",
"IRC",
"protocol",
"line",
"."
] | d028b7d5ccc604a6af175ee2264c18d25b1f7dff | https://github.com/hinrik/ircsupport/blob/d028b7d5ccc604a6af175ee2264c18d25b1f7dff/lib/ircsupport/parser.rb#L136-L156 | train |
hinrik/ircsupport | lib/ircsupport/parser.rb | IRCSupport.Parser.parse | def parse(raw_line)
line = decompose(raw_line)
if line.command =~ /^(PRIVMSG|NOTICE)$/ && line.args[1] =~ /\x01/
return handle_ctcp_message(line)
end
msg_class = case
when line.command =~ /^\d{3}$/
begin
constantize("IRCSupport::Message::Numeric#{line.command}")
rescue
constantize("IRCSupport::Message::Numeric")
end
when line.command == "MODE"
if @isupport['CHANTYPES'].include?(line.args[0][0])
constantize("IRCSupport::Message::ChannelModeChange")
else
constantize("IRCSupport::Message::UserModeChange")
end
when line.command == "NOTICE" && (!line.prefix || line.prefix !~ /!/)
constantize("IRCSupport::Message::ServerNotice")
when line.command == "CAP" && %w{LS LIST ACK}.include?(line.args[0])
constantize("IRCSupport::Message::CAP::#{line.args[0]}")
else
begin
constantize("IRCSupport::Message::#{line.command.capitalize}")
rescue
constantize("IRCSupport::Message")
end
end
message = msg_class.new(line, @isupport, @capabilities)
case message.type
when :'005'
@isupport.merge! message.isupport
when :cap_ack
message.capabilities.each do |capability, options|
if options.include?(:disable)
@capabilities = @capabilities - [capability]
elsif options.include?(:enable)
@capabilities = @capabilities + [capability]
end
end
end
return message
end | ruby | def parse(raw_line)
line = decompose(raw_line)
if line.command =~ /^(PRIVMSG|NOTICE)$/ && line.args[1] =~ /\x01/
return handle_ctcp_message(line)
end
msg_class = case
when line.command =~ /^\d{3}$/
begin
constantize("IRCSupport::Message::Numeric#{line.command}")
rescue
constantize("IRCSupport::Message::Numeric")
end
when line.command == "MODE"
if @isupport['CHANTYPES'].include?(line.args[0][0])
constantize("IRCSupport::Message::ChannelModeChange")
else
constantize("IRCSupport::Message::UserModeChange")
end
when line.command == "NOTICE" && (!line.prefix || line.prefix !~ /!/)
constantize("IRCSupport::Message::ServerNotice")
when line.command == "CAP" && %w{LS LIST ACK}.include?(line.args[0])
constantize("IRCSupport::Message::CAP::#{line.args[0]}")
else
begin
constantize("IRCSupport::Message::#{line.command.capitalize}")
rescue
constantize("IRCSupport::Message")
end
end
message = msg_class.new(line, @isupport, @capabilities)
case message.type
when :'005'
@isupport.merge! message.isupport
when :cap_ack
message.capabilities.each do |capability, options|
if options.include?(:disable)
@capabilities = @capabilities - [capability]
elsif options.include?(:enable)
@capabilities = @capabilities + [capability]
end
end
end
return message
end | [
"def",
"parse",
"(",
"raw_line",
")",
"line",
"=",
"decompose",
"(",
"raw_line",
")",
"if",
"line",
".",
"command",
"=~",
"/",
"/",
"&&",
"line",
".",
"args",
"[",
"1",
"]",
"=~",
"/",
"\\x01",
"/",
"return",
"handle_ctcp_message",
"(",
"line",
")",
"end",
"msg_class",
"=",
"case",
"when",
"line",
".",
"command",
"=~",
"/",
"\\d",
"/",
"begin",
"constantize",
"(",
"\"IRCSupport::Message::Numeric#{line.command}\"",
")",
"rescue",
"constantize",
"(",
"\"IRCSupport::Message::Numeric\"",
")",
"end",
"when",
"line",
".",
"command",
"==",
"\"MODE\"",
"if",
"@isupport",
"[",
"'CHANTYPES'",
"]",
".",
"include?",
"(",
"line",
".",
"args",
"[",
"0",
"]",
"[",
"0",
"]",
")",
"constantize",
"(",
"\"IRCSupport::Message::ChannelModeChange\"",
")",
"else",
"constantize",
"(",
"\"IRCSupport::Message::UserModeChange\"",
")",
"end",
"when",
"line",
".",
"command",
"==",
"\"NOTICE\"",
"&&",
"(",
"!",
"line",
".",
"prefix",
"||",
"line",
".",
"prefix",
"!~",
"/",
"/",
")",
"constantize",
"(",
"\"IRCSupport::Message::ServerNotice\"",
")",
"when",
"line",
".",
"command",
"==",
"\"CAP\"",
"&&",
"%w{",
"LS",
"LIST",
"ACK",
"}",
".",
"include?",
"(",
"line",
".",
"args",
"[",
"0",
"]",
")",
"constantize",
"(",
"\"IRCSupport::Message::CAP::#{line.args[0]}\"",
")",
"else",
"begin",
"constantize",
"(",
"\"IRCSupport::Message::#{line.command.capitalize}\"",
")",
"rescue",
"constantize",
"(",
"\"IRCSupport::Message\"",
")",
"end",
"end",
"message",
"=",
"msg_class",
".",
"new",
"(",
"line",
",",
"@isupport",
",",
"@capabilities",
")",
"case",
"message",
".",
"type",
"when",
":'",
"'",
"@isupport",
".",
"merge!",
"message",
".",
"isupport",
"when",
":cap_ack",
"message",
".",
"capabilities",
".",
"each",
"do",
"|",
"capability",
",",
"options",
"|",
"if",
"options",
".",
"include?",
"(",
":disable",
")",
"@capabilities",
"=",
"@capabilities",
"-",
"[",
"capability",
"]",
"elsif",
"options",
".",
"include?",
"(",
":enable",
")",
"@capabilities",
"=",
"@capabilities",
"+",
"[",
"capability",
"]",
"end",
"end",
"end",
"return",
"message",
"end"
] | Parse an IRC protocol line into a complete message object.
@param [String] raw_line An IRC protocol line.
@return [IRCSupport::Message] A parsed message object. | [
"Parse",
"an",
"IRC",
"protocol",
"line",
"into",
"a",
"complete",
"message",
"object",
"."
] | d028b7d5ccc604a6af175ee2264c18d25b1f7dff | https://github.com/hinrik/ircsupport/blob/d028b7d5ccc604a6af175ee2264c18d25b1f7dff/lib/ircsupport/parser.rb#L161-L209 | train |
robfors/ruby-sumac | lib/sumac/handshake.rb | Sumac.Handshake.send_initialization_message | def send_initialization_message
entry_properties = @connection.objects.convert_object_to_properties(@connection.local_entry)
message = Messages::Initialization.build(entry: entry_properties)
@connection.messenger.send(message)
end | ruby | def send_initialization_message
entry_properties = @connection.objects.convert_object_to_properties(@connection.local_entry)
message = Messages::Initialization.build(entry: entry_properties)
@connection.messenger.send(message)
end | [
"def",
"send_initialization_message",
"entry_properties",
"=",
"@connection",
".",
"objects",
".",
"convert_object_to_properties",
"(",
"@connection",
".",
"local_entry",
")",
"message",
"=",
"Messages",
"::",
"Initialization",
".",
"build",
"(",
"entry",
":",
"entry_properties",
")",
"@connection",
".",
"messenger",
".",
"send",
"(",
"message",
")",
"end"
] | Build and send an initialization message.
@note make sure [email protected]_entry+ is sendable before calling this
@return [void] | [
"Build",
"and",
"send",
"an",
"initialization",
"message",
"."
] | 524fa68b7d1bb10a74baa69cd594ab2b8cae20a3 | https://github.com/robfors/ruby-sumac/blob/524fa68b7d1bb10a74baa69cd594ab2b8cae20a3/lib/sumac/handshake.rb#L24-L28 | train |
robfors/ruby-sumac | lib/sumac/handshake.rb | Sumac.Handshake.process_initialization_message | def process_initialization_message(message)
entry = @connection.objects.convert_properties_to_object(message.entry)
@connection.remote_entry.set(entry)
end | ruby | def process_initialization_message(message)
entry = @connection.objects.convert_properties_to_object(message.entry)
@connection.remote_entry.set(entry)
end | [
"def",
"process_initialization_message",
"(",
"message",
")",
"entry",
"=",
"@connection",
".",
"objects",
".",
"convert_properties_to_object",
"(",
"message",
".",
"entry",
")",
"@connection",
".",
"remote_entry",
".",
"set",
"(",
"entry",
")",
"end"
] | Processes a initialization message from the remote endpoint.
@param message [Messages::Initialization]
@raise [ProtocolError] if a {LocalObject} does not exist with id received for the entry object
@return [void] | [
"Processes",
"a",
"initialization",
"message",
"from",
"the",
"remote",
"endpoint",
"."
] | 524fa68b7d1bb10a74baa69cd594ab2b8cae20a3 | https://github.com/robfors/ruby-sumac/blob/524fa68b7d1bb10a74baa69cd594ab2b8cae20a3/lib/sumac/handshake.rb#L42-L45 | train |
westlakedesign/stripe_webhooks | app/models/stripe_webhooks/callback.rb | StripeWebhooks.Callback.run_once | def run_once(event)
unless StripeWebhooks::PerformedCallback.exists?(stripe_event_id: event.id, label: label)
run(event)
StripeWebhooks::PerformedCallback.create(stripe_event_id: event.id, label: label)
end
end | ruby | def run_once(event)
unless StripeWebhooks::PerformedCallback.exists?(stripe_event_id: event.id, label: label)
run(event)
StripeWebhooks::PerformedCallback.create(stripe_event_id: event.id, label: label)
end
end | [
"def",
"run_once",
"(",
"event",
")",
"unless",
"StripeWebhooks",
"::",
"PerformedCallback",
".",
"exists?",
"(",
"stripe_event_id",
":",
"event",
".",
"id",
",",
"label",
":",
"label",
")",
"run",
"(",
"event",
")",
"StripeWebhooks",
"::",
"PerformedCallback",
".",
"create",
"(",
"stripe_event_id",
":",
"event",
".",
"id",
",",
"label",
":",
"label",
")",
"end",
"end"
] | Run the callback only if we have not run it once before | [
"Run",
"the",
"callback",
"only",
"if",
"we",
"have",
"not",
"run",
"it",
"once",
"before"
] | a6f5088fc1b3827c12571ccc0f3ac303ec372b08 | https://github.com/westlakedesign/stripe_webhooks/blob/a6f5088fc1b3827c12571ccc0f3ac303ec372b08/app/models/stripe_webhooks/callback.rb#L56-L61 | train |
jinx/migrate | lib/jinx/migration/migrator.rb | Jinx.Migrator.migrate | def migrate(&block)
unless block_given? then
return migrate { |tgt, row| tgt }
end
# If there is an extract, then wrap the migration in an extract
# writer block.
if @extract then
if String === @extract then
logger.debug { "Opening migration extract #{@extract}..." }
FileUtils::mkdir_p(File.dirname(@extract))
if @extract_hdrs then
logger.debug { "Migration extract headers: #{@extract_hdrs.join(', ')}." }
CsvIO.open(@extract, :mode => 'w', :headers => @extract_hdrs) do |io|
@extract = io
return migrate(&block)
end
else
File.open(@extract, 'w') do |io|
@extract = io
return migrate(&block)
end
end
end
# Copy the extract into a local variable and clear the extract i.v.
# prior to a recursive call with an extract writer block.
io, @extract = @extract, nil
return migrate do |tgt, row|
res = yield(tgt, row)
tgt.extract(io)
res
end
end
begin
migrate_rows(&block)
ensure
@rejects.close if @rejects
remove_migration_methods
end
end | ruby | def migrate(&block)
unless block_given? then
return migrate { |tgt, row| tgt }
end
# If there is an extract, then wrap the migration in an extract
# writer block.
if @extract then
if String === @extract then
logger.debug { "Opening migration extract #{@extract}..." }
FileUtils::mkdir_p(File.dirname(@extract))
if @extract_hdrs then
logger.debug { "Migration extract headers: #{@extract_hdrs.join(', ')}." }
CsvIO.open(@extract, :mode => 'w', :headers => @extract_hdrs) do |io|
@extract = io
return migrate(&block)
end
else
File.open(@extract, 'w') do |io|
@extract = io
return migrate(&block)
end
end
end
# Copy the extract into a local variable and clear the extract i.v.
# prior to a recursive call with an extract writer block.
io, @extract = @extract, nil
return migrate do |tgt, row|
res = yield(tgt, row)
tgt.extract(io)
res
end
end
begin
migrate_rows(&block)
ensure
@rejects.close if @rejects
remove_migration_methods
end
end | [
"def",
"migrate",
"(",
"&",
"block",
")",
"unless",
"block_given?",
"then",
"return",
"migrate",
"{",
"|",
"tgt",
",",
"row",
"|",
"tgt",
"}",
"end",
"if",
"@extract",
"then",
"if",
"String",
"===",
"@extract",
"then",
"logger",
".",
"debug",
"{",
"\"Opening migration extract #{@extract}...\"",
"}",
"FileUtils",
"::",
"mkdir_p",
"(",
"File",
".",
"dirname",
"(",
"@extract",
")",
")",
"if",
"@extract_hdrs",
"then",
"logger",
".",
"debug",
"{",
"\"Migration extract headers: #{@extract_hdrs.join(', ')}.\"",
"}",
"CsvIO",
".",
"open",
"(",
"@extract",
",",
":mode",
"=>",
"'w'",
",",
":headers",
"=>",
"@extract_hdrs",
")",
"do",
"|",
"io",
"|",
"@extract",
"=",
"io",
"return",
"migrate",
"(",
"&",
"block",
")",
"end",
"else",
"File",
".",
"open",
"(",
"@extract",
",",
"'w'",
")",
"do",
"|",
"io",
"|",
"@extract",
"=",
"io",
"return",
"migrate",
"(",
"&",
"block",
")",
"end",
"end",
"end",
"io",
",",
"@extract",
"=",
"@extract",
",",
"nil",
"return",
"migrate",
"do",
"|",
"tgt",
",",
"row",
"|",
"res",
"=",
"yield",
"(",
"tgt",
",",
"row",
")",
"tgt",
".",
"extract",
"(",
"io",
")",
"res",
"end",
"end",
"begin",
"migrate_rows",
"(",
"&",
"block",
")",
"ensure",
"@rejects",
".",
"close",
"if",
"@rejects",
"remove_migration_methods",
"end",
"end"
] | Creates a new Migrator from the given options.
@param [{Symbol => Object}] opts the migration options
@option opts [Class] :target the required target domain class
@option opts [<String>, String] :mapping the required input field => caTissue attribute mapping file(s)
@option opts [String, Migration::Reader] :input the required input file name or an adapter which
implements the {Migration::Reader} methods
@option opts [<String>, String] :defaults the optional caTissue attribute => value default mapping file(s)
@option opts [<String>, String] :filters the optional caTissue attribute input value => caTissue value filter file(s)
@option opts [<String>, String] :shims the optional shim file(s) to load
@option opts [String] :unique the optional flag which ensures that migrator calls the +uniquify+ method on
those migrated objects whose class includes the +Unique+ module
@option opts [String] :create the optional flag indicating that existing target objects are ignored
@option opts [String] :bad the optional invalid record file
@option opts [String, IO] :extract the optional extract file or object that responds to +<<+
@option opts [<String>] :extract_headers the optional extract CSV field headers
@option opts [Integer] :from the optional starting source record number to process
@option opts [Integer] :to the optional ending source record number to process
@option opts [Boolean] :quiet the optional flag which suppress output messages
@option opts [Boolean] :verbose the optional flag to print the migration progress
Imports this migrator's CSV file and calls the given block on each migrated target
domain object. If no block is given, then this method returns an array of the
migrated target objects.
@yield [target, row] operates on the migration target
@yieldparam [Resource] target the migrated target domain object
@yieldparam [{Symbol => Object}] row the migration source record | [
"Creates",
"a",
"new",
"Migrator",
"from",
"the",
"given",
"options",
"."
] | 309957a470d72da3bd074f8173dbbe2f12449883 | https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L56-L94 | train |
jinx/migrate | lib/jinx/migration/migrator.rb | Jinx.Migrator.remove_migration_methods | def remove_migration_methods
# remove the migrate_<attribute> methods
@mgt_mths.each do | klass, hash|
hash.each_value do |sym|
while klass.method_defined?(sym)
klass.instance_method(sym).owner.module_eval { remove_method(sym) }
end
end
end
# remove the migrate method
@creatable_classes.each do |klass|
while (k = klass.instance_method(:migrate).owner) < Migratable
k.module_eval { remove_method(:migrate) }
end
end
# remove the target extract method
remove_extract_method(@target) if @extract
end | ruby | def remove_migration_methods
# remove the migrate_<attribute> methods
@mgt_mths.each do | klass, hash|
hash.each_value do |sym|
while klass.method_defined?(sym)
klass.instance_method(sym).owner.module_eval { remove_method(sym) }
end
end
end
# remove the migrate method
@creatable_classes.each do |klass|
while (k = klass.instance_method(:migrate).owner) < Migratable
k.module_eval { remove_method(:migrate) }
end
end
# remove the target extract method
remove_extract_method(@target) if @extract
end | [
"def",
"remove_migration_methods",
"@mgt_mths",
".",
"each",
"do",
"|",
"klass",
",",
"hash",
"|",
"hash",
".",
"each_value",
"do",
"|",
"sym",
"|",
"while",
"klass",
".",
"method_defined?",
"(",
"sym",
")",
"klass",
".",
"instance_method",
"(",
"sym",
")",
".",
"owner",
".",
"module_eval",
"{",
"remove_method",
"(",
"sym",
")",
"}",
"end",
"end",
"end",
"@creatable_classes",
".",
"each",
"do",
"|",
"klass",
"|",
"while",
"(",
"k",
"=",
"klass",
".",
"instance_method",
"(",
":migrate",
")",
".",
"owner",
")",
"<",
"Migratable",
"k",
".",
"module_eval",
"{",
"remove_method",
"(",
":migrate",
")",
"}",
"end",
"end",
"remove_extract_method",
"(",
"@target",
")",
"if",
"@extract",
"end"
] | Cleans up after the migration by removing the methods injected by migration
shims. | [
"Cleans",
"up",
"after",
"the",
"migration",
"by",
"removing",
"the",
"methods",
"injected",
"by",
"migration",
"shims",
"."
] | 309957a470d72da3bd074f8173dbbe2f12449883 | https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L106-L123 | train |
jinx/migrate | lib/jinx/migration/migrator.rb | Jinx.Migrator.load_shims | def load_shims(files)
logger.debug { "Loading the migration shims with load path #{$:.pp_s}..." }
files.enumerate do |file|
load file
logger.info { "The migrator loaded the shim file #{file}." }
end
end | ruby | def load_shims(files)
logger.debug { "Loading the migration shims with load path #{$:.pp_s}..." }
files.enumerate do |file|
load file
logger.info { "The migrator loaded the shim file #{file}." }
end
end | [
"def",
"load_shims",
"(",
"files",
")",
"logger",
".",
"debug",
"{",
"\"Loading the migration shims with load path #{$:.pp_s}...\"",
"}",
"files",
".",
"enumerate",
"do",
"|",
"file",
"|",
"load",
"file",
"logger",
".",
"info",
"{",
"\"The migrator loaded the shim file #{file}.\"",
"}",
"end",
"end"
] | Loads the shim files.
@param [<String>, String] files the file or file array | [
"Loads",
"the",
"shim",
"files",
"."
] | 309957a470d72da3bd074f8173dbbe2f12449883 | https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L421-L427 | train |
jinx/migrate | lib/jinx/migration/migrator.rb | Jinx.Migrator.migrate_rows | def migrate_rows
# open an CSV output for rejects if the bad option is set
if @bad_file then
@rejects = open_rejects(@bad_file)
logger.info("Unmigrated records will be written to #{File.expand_path(@bad_file)}.")
end
@rec_cnt = mgt_cnt = 0
logger.info { "Migrating #{@input}..." }
puts "Migrating #{@input}..." if @verbose
@reader.each do |row|
# the one-based current record number
rec_no = @rec_cnt + 1
# skip if the row precedes the from option
if rec_no == @from and @rec_cnt > 0 then
logger.info("Skipped the initial #{@rec_cnt} records.")
elsif rec_no == @to then
logger.info("Ending the migration after processing record #{@rec_cnt}.")
return
elsif rec_no < @from then
@rec_cnt += 1
next
end
begin
# migrate the row
logger.debug { "Migrating record #{rec_no}..." }
tgt = migrate_row(row)
# call the block on the migrated target
if tgt then
logger.debug { "The migrator built #{tgt} with the following content:\n#{tgt.dump}" }
yield(tgt, row)
end
rescue Exception => e
logger.error("Migration error on record #{rec_no} - #{e.message}:\n#{e.backtrace.pp_s}")
# If there is a reject file, then don't propagate the error.
raise unless @rejects
# try to clear the migration state
clear(tgt) rescue nil
# clear the target
tgt = nil
end
if tgt then
# replace the log message below with the commented alternative to detect a memory leak
logger.info { "Migrated record #{rec_no}." }
#memory_usage = `ps -o rss= -p #{Process.pid}`.to_f / 1024 # in megabytes
#logger.debug { "Migrated rec #{@rec_cnt}; memory usage: #{sprintf("%.1f", memory_usage)} MB." }
mgt_cnt += 1
if @verbose then print_progress(mgt_cnt) end
# clear the migration state
clear(tgt)
elsif @rejects then
# If there is a rejects file then warn, write the reject and continue.
logger.warn("Migration not performed on record #{rec_no}.")
@rejects << row
@rejects.flush
logger.debug("Invalid record #{rec_no} was written to the rejects file #{@bad_file}.")
else
raise MigrationError.new("Migration not performed on record #{rec_no}")
end
# Bump the record count.
@rec_cnt += 1
end
logger.info("Migrated #{mgt_cnt} of #{@rec_cnt} records.")
if @verbose then
puts
puts "Migrated #{mgt_cnt} of #{@rec_cnt} records."
end
end | ruby | def migrate_rows
# open an CSV output for rejects if the bad option is set
if @bad_file then
@rejects = open_rejects(@bad_file)
logger.info("Unmigrated records will be written to #{File.expand_path(@bad_file)}.")
end
@rec_cnt = mgt_cnt = 0
logger.info { "Migrating #{@input}..." }
puts "Migrating #{@input}..." if @verbose
@reader.each do |row|
# the one-based current record number
rec_no = @rec_cnt + 1
# skip if the row precedes the from option
if rec_no == @from and @rec_cnt > 0 then
logger.info("Skipped the initial #{@rec_cnt} records.")
elsif rec_no == @to then
logger.info("Ending the migration after processing record #{@rec_cnt}.")
return
elsif rec_no < @from then
@rec_cnt += 1
next
end
begin
# migrate the row
logger.debug { "Migrating record #{rec_no}..." }
tgt = migrate_row(row)
# call the block on the migrated target
if tgt then
logger.debug { "The migrator built #{tgt} with the following content:\n#{tgt.dump}" }
yield(tgt, row)
end
rescue Exception => e
logger.error("Migration error on record #{rec_no} - #{e.message}:\n#{e.backtrace.pp_s}")
# If there is a reject file, then don't propagate the error.
raise unless @rejects
# try to clear the migration state
clear(tgt) rescue nil
# clear the target
tgt = nil
end
if tgt then
# replace the log message below with the commented alternative to detect a memory leak
logger.info { "Migrated record #{rec_no}." }
#memory_usage = `ps -o rss= -p #{Process.pid}`.to_f / 1024 # in megabytes
#logger.debug { "Migrated rec #{@rec_cnt}; memory usage: #{sprintf("%.1f", memory_usage)} MB." }
mgt_cnt += 1
if @verbose then print_progress(mgt_cnt) end
# clear the migration state
clear(tgt)
elsif @rejects then
# If there is a rejects file then warn, write the reject and continue.
logger.warn("Migration not performed on record #{rec_no}.")
@rejects << row
@rejects.flush
logger.debug("Invalid record #{rec_no} was written to the rejects file #{@bad_file}.")
else
raise MigrationError.new("Migration not performed on record #{rec_no}")
end
# Bump the record count.
@rec_cnt += 1
end
logger.info("Migrated #{mgt_cnt} of #{@rec_cnt} records.")
if @verbose then
puts
puts "Migrated #{mgt_cnt} of #{@rec_cnt} records."
end
end | [
"def",
"migrate_rows",
"if",
"@bad_file",
"then",
"@rejects",
"=",
"open_rejects",
"(",
"@bad_file",
")",
"logger",
".",
"info",
"(",
"\"Unmigrated records will be written to #{File.expand_path(@bad_file)}.\"",
")",
"end",
"@rec_cnt",
"=",
"mgt_cnt",
"=",
"0",
"logger",
".",
"info",
"{",
"\"Migrating #{@input}...\"",
"}",
"puts",
"\"Migrating #{@input}...\"",
"if",
"@verbose",
"@reader",
".",
"each",
"do",
"|",
"row",
"|",
"rec_no",
"=",
"@rec_cnt",
"+",
"1",
"if",
"rec_no",
"==",
"@from",
"and",
"@rec_cnt",
">",
"0",
"then",
"logger",
".",
"info",
"(",
"\"Skipped the initial #{@rec_cnt} records.\"",
")",
"elsif",
"rec_no",
"==",
"@to",
"then",
"logger",
".",
"info",
"(",
"\"Ending the migration after processing record #{@rec_cnt}.\"",
")",
"return",
"elsif",
"rec_no",
"<",
"@from",
"then",
"@rec_cnt",
"+=",
"1",
"next",
"end",
"begin",
"logger",
".",
"debug",
"{",
"\"Migrating record #{rec_no}...\"",
"}",
"tgt",
"=",
"migrate_row",
"(",
"row",
")",
"if",
"tgt",
"then",
"logger",
".",
"debug",
"{",
"\"The migrator built #{tgt} with the following content:\\n#{tgt.dump}\"",
"}",
"yield",
"(",
"tgt",
",",
"row",
")",
"end",
"rescue",
"Exception",
"=>",
"e",
"logger",
".",
"error",
"(",
"\"Migration error on record #{rec_no} - #{e.message}:\\n#{e.backtrace.pp_s}\"",
")",
"raise",
"unless",
"@rejects",
"clear",
"(",
"tgt",
")",
"rescue",
"nil",
"tgt",
"=",
"nil",
"end",
"if",
"tgt",
"then",
"logger",
".",
"info",
"{",
"\"Migrated record #{rec_no}.\"",
"}",
"mgt_cnt",
"+=",
"1",
"if",
"@verbose",
"then",
"print_progress",
"(",
"mgt_cnt",
")",
"end",
"clear",
"(",
"tgt",
")",
"elsif",
"@rejects",
"then",
"logger",
".",
"warn",
"(",
"\"Migration not performed on record #{rec_no}.\"",
")",
"@rejects",
"<<",
"row",
"@rejects",
".",
"flush",
"logger",
".",
"debug",
"(",
"\"Invalid record #{rec_no} was written to the rejects file #{@bad_file}.\"",
")",
"else",
"raise",
"MigrationError",
".",
"new",
"(",
"\"Migration not performed on record #{rec_no}\"",
")",
"end",
"@rec_cnt",
"+=",
"1",
"end",
"logger",
".",
"info",
"(",
"\"Migrated #{mgt_cnt} of #{@rec_cnt} records.\"",
")",
"if",
"@verbose",
"then",
"puts",
"puts",
"\"Migrated #{mgt_cnt} of #{@rec_cnt} records.\"",
"end",
"end"
] | Migrates all rows in the input.
@yield (see #migrate)
@yieldparam (see #migrate) | [
"Migrates",
"all",
"rows",
"in",
"the",
"input",
"."
] | 309957a470d72da3bd074f8173dbbe2f12449883 | https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L433-L500 | train |
jinx/migrate | lib/jinx/migration/migrator.rb | Jinx.Migrator.open_rejects | def open_rejects(file)
# Make the parent directory.
FileUtils.mkdir_p(File.dirname(file))
# Open the file.
FasterCSV.open(file, 'w', :headers => true, :header_converters => :symbol, :write_headers => true)
end | ruby | def open_rejects(file)
# Make the parent directory.
FileUtils.mkdir_p(File.dirname(file))
# Open the file.
FasterCSV.open(file, 'w', :headers => true, :header_converters => :symbol, :write_headers => true)
end | [
"def",
"open_rejects",
"(",
"file",
")",
"FileUtils",
".",
"mkdir_p",
"(",
"File",
".",
"dirname",
"(",
"file",
")",
")",
"FasterCSV",
".",
"open",
"(",
"file",
",",
"'w'",
",",
":headers",
"=>",
"true",
",",
":header_converters",
"=>",
":symbol",
",",
":write_headers",
"=>",
"true",
")",
"end"
] | Makes the rejects CSV output file.
@param [String] file the output file
@return [IO] the reject stream | [
"Makes",
"the",
"rejects",
"CSV",
"output",
"file",
"."
] | 309957a470d72da3bd074f8173dbbe2f12449883 | https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L506-L511 | train |
jinx/migrate | lib/jinx/migration/migrator.rb | Jinx.Migrator.migrate_row | def migrate_row(row)
# create an instance for each creatable class
created = Set.new
# the migrated objects
migrated = @creatable_classes.map { |klass| create_instance(klass, row, created) }
# migrate each object from the input row
migrated.each do |obj|
# First uniquify the object if necessary.
if @unique and Unique === obj then
logger.debug { "The migrator is making #{obj} unique..." }
obj.uniquify
end
obj.migrate(row, migrated)
end
# the valid migrated objects
@migrated = migrate_valid_references(row, migrated)
# the candidate target objects
tgts = @migrated.select { |obj| @target_class === obj }
if tgts.size > 1 then
raise MigrationError.new("Ambiguous #{@target_class} targets #{tgts.to_series}")
end
target = tgts.first || return
logger.debug { "Migrated target #{target}." }
target
end | ruby | def migrate_row(row)
# create an instance for each creatable class
created = Set.new
# the migrated objects
migrated = @creatable_classes.map { |klass| create_instance(klass, row, created) }
# migrate each object from the input row
migrated.each do |obj|
# First uniquify the object if necessary.
if @unique and Unique === obj then
logger.debug { "The migrator is making #{obj} unique..." }
obj.uniquify
end
obj.migrate(row, migrated)
end
# the valid migrated objects
@migrated = migrate_valid_references(row, migrated)
# the candidate target objects
tgts = @migrated.select { |obj| @target_class === obj }
if tgts.size > 1 then
raise MigrationError.new("Ambiguous #{@target_class} targets #{tgts.to_series}")
end
target = tgts.first || return
logger.debug { "Migrated target #{target}." }
target
end | [
"def",
"migrate_row",
"(",
"row",
")",
"created",
"=",
"Set",
".",
"new",
"migrated",
"=",
"@creatable_classes",
".",
"map",
"{",
"|",
"klass",
"|",
"create_instance",
"(",
"klass",
",",
"row",
",",
"created",
")",
"}",
"migrated",
".",
"each",
"do",
"|",
"obj",
"|",
"if",
"@unique",
"and",
"Unique",
"===",
"obj",
"then",
"logger",
".",
"debug",
"{",
"\"The migrator is making #{obj} unique...\"",
"}",
"obj",
".",
"uniquify",
"end",
"obj",
".",
"migrate",
"(",
"row",
",",
"migrated",
")",
"end",
"@migrated",
"=",
"migrate_valid_references",
"(",
"row",
",",
"migrated",
")",
"tgts",
"=",
"@migrated",
".",
"select",
"{",
"|",
"obj",
"|",
"@target_class",
"===",
"obj",
"}",
"if",
"tgts",
".",
"size",
">",
"1",
"then",
"raise",
"MigrationError",
".",
"new",
"(",
"\"Ambiguous #{@target_class} targets #{tgts.to_series}\"",
")",
"end",
"target",
"=",
"tgts",
".",
"first",
"||",
"return",
"logger",
".",
"debug",
"{",
"\"Migrated target #{target}.\"",
"}",
"target",
"end"
] | Imports the given CSV row into a target object.
@param [{Symbol => Object}] row the input row field => value hash
@return the migrated target object if the migration is valid, nil otherwise | [
"Imports",
"the",
"given",
"CSV",
"row",
"into",
"a",
"target",
"object",
"."
] | 309957a470d72da3bd074f8173dbbe2f12449883 | https://github.com/jinx/migrate/blob/309957a470d72da3bd074f8173dbbe2f12449883/lib/jinx/migration/migrator.rb#L535-L560 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.