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
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
openplacos/openplacos | components/LibComponent.rb | LibComponent.Component.run | def run
# execute startup methods
@inputs.each do |inp|
inp.start if inp.respond_to?(:start)
end
@outputs.each do |outp|
outp.start if outp.respond_to?(:start)
end
intro = introspect
if @options[:introspect]
print intro.to_yaml
else
@bus = create_bus
#create dbus input pins
dbusinputs = LibComponent::DbusInput.create_dbusinputs_from_introspect(intro["input"]["pin"],self)
name = "org.openplacos.components.#{@name.downcase}"
if (@bus.proxy.ListNames[0].member?(name))
quit_server(255, "#{name} already exists")
end
@service = @bus.request_service(name)
dbusinputs.each { |pin|
@service.export(pin)
}
#create and connect output pins
if options[:debug]
@dbusoutputs = LibComponent::DebugOutput.create_dbusoutputs_from_introspect(intro["output"]["pin"],self)
else
@dbusoutputs = LibComponent::DbusOutput.create_dbusoutputs_from_introspect(intro["output"]["pin"],self)
@servicesignal = Servicesignal.new(@bus, self) # listen for service signal from server
end
Signal.trap('INT') do
self.quit_callback
end
@main = DBus::Main.new
@main << @bus
@main.run
end
end | ruby | def run
# execute startup methods
@inputs.each do |inp|
inp.start if inp.respond_to?(:start)
end
@outputs.each do |outp|
outp.start if outp.respond_to?(:start)
end
intro = introspect
if @options[:introspect]
print intro.to_yaml
else
@bus = create_bus
#create dbus input pins
dbusinputs = LibComponent::DbusInput.create_dbusinputs_from_introspect(intro["input"]["pin"],self)
name = "org.openplacos.components.#{@name.downcase}"
if (@bus.proxy.ListNames[0].member?(name))
quit_server(255, "#{name} already exists")
end
@service = @bus.request_service(name)
dbusinputs.each { |pin|
@service.export(pin)
}
#create and connect output pins
if options[:debug]
@dbusoutputs = LibComponent::DebugOutput.create_dbusoutputs_from_introspect(intro["output"]["pin"],self)
else
@dbusoutputs = LibComponent::DbusOutput.create_dbusoutputs_from_introspect(intro["output"]["pin"],self)
@servicesignal = Servicesignal.new(@bus, self) # listen for service signal from server
end
Signal.trap('INT') do
self.quit_callback
end
@main = DBus::Main.new
@main << @bus
@main.run
end
end | [
"def",
"run",
"@inputs",
".",
"each",
"do",
"|",
"inp",
"|",
"inp",
".",
"start",
"if",
"inp",
".",
"respond_to?",
"(",
":start",
")",
"end",
"@outputs",
".",
"each",
"do",
"|",
"outp",
"|",
"outp",
".",
"start",
"if",
"outp",
".",
"respond_to?",
"(",
":start",
")",
"end",
"intro",
"=",
"introspect",
"if",
"@options",
"[",
":introspect",
"]",
"print",
"intro",
".",
"to_yaml",
"else",
"@bus",
"=",
"create_bus",
"dbusinputs",
"=",
"LibComponent",
"::",
"DbusInput",
".",
"create_dbusinputs_from_introspect",
"(",
"intro",
"[",
"\"input\"",
"]",
"[",
"\"pin\"",
"]",
",",
"self",
")",
"name",
"=",
"\"org.openplacos.components.#{@name.downcase}\"",
"if",
"(",
"@bus",
".",
"proxy",
".",
"ListNames",
"[",
"0",
"]",
".",
"member?",
"(",
"name",
")",
")",
"quit_server",
"(",
"255",
",",
"\"#{name} already exists\"",
")",
"end",
"@service",
"=",
"@bus",
".",
"request_service",
"(",
"name",
")",
"dbusinputs",
".",
"each",
"{",
"|",
"pin",
"|",
"@service",
".",
"export",
"(",
"pin",
")",
"}",
"if",
"options",
"[",
":debug",
"]",
"@dbusoutputs",
"=",
"LibComponent",
"::",
"DebugOutput",
".",
"create_dbusoutputs_from_introspect",
"(",
"intro",
"[",
"\"output\"",
"]",
"[",
"\"pin\"",
"]",
",",
"self",
")",
"else",
"@dbusoutputs",
"=",
"LibComponent",
"::",
"DbusOutput",
".",
"create_dbusoutputs_from_introspect",
"(",
"intro",
"[",
"\"output\"",
"]",
"[",
"\"pin\"",
"]",
",",
"self",
")",
"@servicesignal",
"=",
"Servicesignal",
".",
"new",
"(",
"@bus",
",",
"self",
")",
"end",
"Signal",
".",
"trap",
"(",
"'INT'",
")",
"do",
"self",
".",
"quit_callback",
"end",
"@main",
"=",
"DBus",
"::",
"Main",
".",
"new",
"@main",
"<<",
"@bus",
"@main",
".",
"run",
"end",
"end"
] | Let's rock! Run the component | [
"Let",
"s",
"rock!",
"Run",
"the",
"component"
] | 75e1d2862bcf74773b9064f1f59015726ebc5256 | https://github.com/openplacos/openplacos/blob/75e1d2862bcf74773b9064f1f59015726ebc5256/components/LibComponent.rb#L315-L357 | train |
openplacos/openplacos | components/LibComponent.rb | LibComponent.Component.introspect | def introspect
inputs_h = Hash.new
outputs_h = Hash.new
#call all inputs introspect and merge values
@inputs.each { |input|
inputs_h.merge!(input.introspect) { |key, old, new| old.merge(new) }
}
#call all outputs introspect and merge values
@outputs.each { |output|
outputs_h.merge!(output.introspect) { |key, old, new| old.merge(new) }
}
res = Hash.new
res["input"] = {"pin" => inputs_h}
res["output"] = {"pin" => outputs_h}
# component options
opt = @options.dup
opt.delete(:introspect)
opt.delete(:debug)
optmod = Hash.new
opt.each_pair do |key,value|
optmod[key.to_s] = value
end
res["component"] ={"options" => optmod}
# component description
res["component"]["description"] = @description
res["component"]["category"] = @category
res["component"]["ttl"] = @ttl
return res
end | ruby | def introspect
inputs_h = Hash.new
outputs_h = Hash.new
#call all inputs introspect and merge values
@inputs.each { |input|
inputs_h.merge!(input.introspect) { |key, old, new| old.merge(new) }
}
#call all outputs introspect and merge values
@outputs.each { |output|
outputs_h.merge!(output.introspect) { |key, old, new| old.merge(new) }
}
res = Hash.new
res["input"] = {"pin" => inputs_h}
res["output"] = {"pin" => outputs_h}
# component options
opt = @options.dup
opt.delete(:introspect)
opt.delete(:debug)
optmod = Hash.new
opt.each_pair do |key,value|
optmod[key.to_s] = value
end
res["component"] ={"options" => optmod}
# component description
res["component"]["description"] = @description
res["component"]["category"] = @category
res["component"]["ttl"] = @ttl
return res
end | [
"def",
"introspect",
"inputs_h",
"=",
"Hash",
".",
"new",
"outputs_h",
"=",
"Hash",
".",
"new",
"@inputs",
".",
"each",
"{",
"|",
"input",
"|",
"inputs_h",
".",
"merge!",
"(",
"input",
".",
"introspect",
")",
"{",
"|",
"key",
",",
"old",
",",
"new",
"|",
"old",
".",
"merge",
"(",
"new",
")",
"}",
"}",
"@outputs",
".",
"each",
"{",
"|",
"output",
"|",
"outputs_h",
".",
"merge!",
"(",
"output",
".",
"introspect",
")",
"{",
"|",
"key",
",",
"old",
",",
"new",
"|",
"old",
".",
"merge",
"(",
"new",
")",
"}",
"}",
"res",
"=",
"Hash",
".",
"new",
"res",
"[",
"\"input\"",
"]",
"=",
"{",
"\"pin\"",
"=>",
"inputs_h",
"}",
"res",
"[",
"\"output\"",
"]",
"=",
"{",
"\"pin\"",
"=>",
"outputs_h",
"}",
"opt",
"=",
"@options",
".",
"dup",
"opt",
".",
"delete",
"(",
":introspect",
")",
"opt",
".",
"delete",
"(",
":debug",
")",
"optmod",
"=",
"Hash",
".",
"new",
"opt",
".",
"each_pair",
"do",
"|",
"key",
",",
"value",
"|",
"optmod",
"[",
"key",
".",
"to_s",
"]",
"=",
"value",
"end",
"res",
"[",
"\"component\"",
"]",
"=",
"{",
"\"options\"",
"=>",
"optmod",
"}",
"res",
"[",
"\"component\"",
"]",
"[",
"\"description\"",
"]",
"=",
"@description",
"res",
"[",
"\"component\"",
"]",
"[",
"\"category\"",
"]",
"=",
"@category",
"res",
"[",
"\"component\"",
"]",
"[",
"\"ttl\"",
"]",
"=",
"@ttl",
"return",
"res",
"end"
] | Parse inputs and outputs to communicate with server | [
"Parse",
"inputs",
"and",
"outputs",
"to",
"communicate",
"with",
"server"
] | 75e1d2862bcf74773b9064f1f59015726ebc5256 | https://github.com/openplacos/openplacos/blob/75e1d2862bcf74773b9064f1f59015726ebc5256/components/LibComponent.rb#L367-L399 | train |
openplacos/openplacos | components/LibComponent.rb | LibComponent.Component.quit_server | def quit_server(status_, str_)
$stderr.puts str_
if ([email protected]?) && !@options[:debug]
bus = DBus::ASessionBus.new
server = bus.service("org.openplacos.server.internal")
opos = server.object("/plugins")
opos.introspect
opos.default_iface = "org.openplacos.plugins"
opos.exit(status_, str_)
else
Process.exit 1
end
end | ruby | def quit_server(status_, str_)
$stderr.puts str_
if ([email protected]?) && !@options[:debug]
bus = DBus::ASessionBus.new
server = bus.service("org.openplacos.server.internal")
opos = server.object("/plugins")
opos.introspect
opos.default_iface = "org.openplacos.plugins"
opos.exit(status_, str_)
else
Process.exit 1
end
end | [
"def",
"quit_server",
"(",
"status_",
",",
"str_",
")",
"$stderr",
".",
"puts",
"str_",
"if",
"(",
"!",
"@options",
".",
"nil?",
")",
"&&",
"!",
"@options",
"[",
":debug",
"]",
"bus",
"=",
"DBus",
"::",
"ASessionBus",
".",
"new",
"server",
"=",
"bus",
".",
"service",
"(",
"\"org.openplacos.server.internal\"",
")",
"opos",
"=",
"server",
".",
"object",
"(",
"\"/plugins\"",
")",
"opos",
".",
"introspect",
"opos",
".",
"default_iface",
"=",
"\"org.openplacos.plugins\"",
"opos",
".",
"exit",
"(",
"status_",
",",
"str_",
")",
"else",
"Process",
".",
"exit",
"1",
"end",
"end"
] | Print an error message and make the server quit | [
"Print",
"an",
"error",
"message",
"and",
"make",
"the",
"server",
"quit"
] | 75e1d2862bcf74773b9064f1f59015726ebc5256 | https://github.com/openplacos/openplacos/blob/75e1d2862bcf74773b9064f1f59015726ebc5256/components/LibComponent.rb#L437-L450 | train |
MrMicrowaveOven/zadt | lib/zadt/AbstractDataTypes/Graph/face_graph.rb | Zadt.FaceGraph.make_original_face | def make_original_face(num_edges)
num_edges_check(num_edges)
# Make the vertices
vert_ref = Array.new(num_edges) {Vertex.new}
edge_ref = []
# Connect each vertex to the one before it (including the first one :)
(num_edges).times do |vert_id|
edge_ref << make_connection(vert_ref[vert_id - 1], vert_ref[vert_id])
end
# Make the face and store it
face = add_face(edge_ref)
# Store the new vertices
@vertices += vert_ref
# Store the new edges
@edges += edge_ref
face
end | ruby | def make_original_face(num_edges)
num_edges_check(num_edges)
# Make the vertices
vert_ref = Array.new(num_edges) {Vertex.new}
edge_ref = []
# Connect each vertex to the one before it (including the first one :)
(num_edges).times do |vert_id|
edge_ref << make_connection(vert_ref[vert_id - 1], vert_ref[vert_id])
end
# Make the face and store it
face = add_face(edge_ref)
# Store the new vertices
@vertices += vert_ref
# Store the new edges
@edges += edge_ref
face
end | [
"def",
"make_original_face",
"(",
"num_edges",
")",
"num_edges_check",
"(",
"num_edges",
")",
"vert_ref",
"=",
"Array",
".",
"new",
"(",
"num_edges",
")",
"{",
"Vertex",
".",
"new",
"}",
"edge_ref",
"=",
"[",
"]",
"(",
"num_edges",
")",
".",
"times",
"do",
"|",
"vert_id",
"|",
"edge_ref",
"<<",
"make_connection",
"(",
"vert_ref",
"[",
"vert_id",
"-",
"1",
"]",
",",
"vert_ref",
"[",
"vert_id",
"]",
")",
"end",
"face",
"=",
"add_face",
"(",
"edge_ref",
")",
"@vertices",
"+=",
"vert_ref",
"@edges",
"+=",
"edge_ref",
"face",
"end"
] | Makes a face with num_edges edges, which will be attached to nothing. | [
"Makes",
"a",
"face",
"with",
"num_edges",
"edges",
"which",
"will",
"be",
"attached",
"to",
"nothing",
"."
] | 789420b1e05f7545f886309c07b235dd560f6696 | https://github.com/MrMicrowaveOven/zadt/blob/789420b1e05f7545f886309c07b235dd560f6696/lib/zadt/AbstractDataTypes/Graph/face_graph.rb#L27-L46 | train |
MrMicrowaveOven/zadt | lib/zadt/AbstractDataTypes/Graph/face_graph.rb | Zadt.FaceGraph.add_attached_face | def add_attached_face(vertex_array, num_edges)
vertex_array_check(vertex_array)
num_edges_check(num_edges)
# Make the vertices into a line
vertex_line = confirm_vertex_line(vertex_array)
# This finds the "ends" of the vertex line
end_vertices = [vertex_line.first, vertex_line.last]
# Find the neighbors that will be added later
new_neighbors = find_neighbors(vertex_array)
# How many vertices and edges to be made
vertices_to_make = num_edges - vertex_array.length
edges_to_make = vertices_to_make + 1
# Make new vertices
vert_ref = Array.new(vertices_to_make) {Vertex.new}
edge_ref = []
# Connect new vertices in a line
(edges_to_make - 2).times do |vert_id|
# Connect each vertex to the one after it
edge_ref << make_connection(vert_ref[vert_id], vert_ref[vert_id + 1])
end
# Connect "ends" of new vertices to "ends" of vertex line (making a circuit)
# Connect "first" of new vertices to "last end" of old ones
edge_ref << make_connection(vert_ref.first, end_vertices.last)
# Connect "last" of new vertices to "first end" of old ones
edge_ref << make_connection(vert_ref.last, end_vertices.first)
# Add edges from vertex_line to edge_ref
(vertex_line.length - 1).times do |vert_id|
edge_ref << find_connection(vertex_line[vert_id], vertex_line[vert_id + 1])
end
face_border = edge_ref
# Make a face out of the new circuit, and store it
face = add_face(face_border)
# Store the new vertices
@vertices += vert_ref
# Store the new edges
@edges += edge_ref
face
end | ruby | def add_attached_face(vertex_array, num_edges)
vertex_array_check(vertex_array)
num_edges_check(num_edges)
# Make the vertices into a line
vertex_line = confirm_vertex_line(vertex_array)
# This finds the "ends" of the vertex line
end_vertices = [vertex_line.first, vertex_line.last]
# Find the neighbors that will be added later
new_neighbors = find_neighbors(vertex_array)
# How many vertices and edges to be made
vertices_to_make = num_edges - vertex_array.length
edges_to_make = vertices_to_make + 1
# Make new vertices
vert_ref = Array.new(vertices_to_make) {Vertex.new}
edge_ref = []
# Connect new vertices in a line
(edges_to_make - 2).times do |vert_id|
# Connect each vertex to the one after it
edge_ref << make_connection(vert_ref[vert_id], vert_ref[vert_id + 1])
end
# Connect "ends" of new vertices to "ends" of vertex line (making a circuit)
# Connect "first" of new vertices to "last end" of old ones
edge_ref << make_connection(vert_ref.first, end_vertices.last)
# Connect "last" of new vertices to "first end" of old ones
edge_ref << make_connection(vert_ref.last, end_vertices.first)
# Add edges from vertex_line to edge_ref
(vertex_line.length - 1).times do |vert_id|
edge_ref << find_connection(vertex_line[vert_id], vertex_line[vert_id + 1])
end
face_border = edge_ref
# Make a face out of the new circuit, and store it
face = add_face(face_border)
# Store the new vertices
@vertices += vert_ref
# Store the new edges
@edges += edge_ref
face
end | [
"def",
"add_attached_face",
"(",
"vertex_array",
",",
"num_edges",
")",
"vertex_array_check",
"(",
"vertex_array",
")",
"num_edges_check",
"(",
"num_edges",
")",
"vertex_line",
"=",
"confirm_vertex_line",
"(",
"vertex_array",
")",
"end_vertices",
"=",
"[",
"vertex_line",
".",
"first",
",",
"vertex_line",
".",
"last",
"]",
"new_neighbors",
"=",
"find_neighbors",
"(",
"vertex_array",
")",
"vertices_to_make",
"=",
"num_edges",
"-",
"vertex_array",
".",
"length",
"edges_to_make",
"=",
"vertices_to_make",
"+",
"1",
"vert_ref",
"=",
"Array",
".",
"new",
"(",
"vertices_to_make",
")",
"{",
"Vertex",
".",
"new",
"}",
"edge_ref",
"=",
"[",
"]",
"(",
"edges_to_make",
"-",
"2",
")",
".",
"times",
"do",
"|",
"vert_id",
"|",
"edge_ref",
"<<",
"make_connection",
"(",
"vert_ref",
"[",
"vert_id",
"]",
",",
"vert_ref",
"[",
"vert_id",
"+",
"1",
"]",
")",
"end",
"edge_ref",
"<<",
"make_connection",
"(",
"vert_ref",
".",
"first",
",",
"end_vertices",
".",
"last",
")",
"edge_ref",
"<<",
"make_connection",
"(",
"vert_ref",
".",
"last",
",",
"end_vertices",
".",
"first",
")",
"(",
"vertex_line",
".",
"length",
"-",
"1",
")",
".",
"times",
"do",
"|",
"vert_id",
"|",
"edge_ref",
"<<",
"find_connection",
"(",
"vertex_line",
"[",
"vert_id",
"]",
",",
"vertex_line",
"[",
"vert_id",
"+",
"1",
"]",
")",
"end",
"face_border",
"=",
"edge_ref",
"face",
"=",
"add_face",
"(",
"face_border",
")",
"@vertices",
"+=",
"vert_ref",
"@edges",
"+=",
"edge_ref",
"face",
"end"
] | This adds a face that will be attached to the given vertices
Make sure the vertices are connected, or it will raise an error
All new vertices and edges will be created
This will automatically make_neighbors with any faces that share
a vertex with the new face | [
"This",
"adds",
"a",
"face",
"that",
"will",
"be",
"attached",
"to",
"the",
"given",
"vertices",
"Make",
"sure",
"the",
"vertices",
"are",
"connected",
"or",
"it",
"will",
"raise",
"an",
"error",
"All",
"new",
"vertices",
"and",
"edges",
"will",
"be",
"created",
"This",
"will",
"automatically",
"make_neighbors",
"with",
"any",
"faces",
"that",
"share",
"a",
"vertex",
"with",
"the",
"new",
"face"
] | 789420b1e05f7545f886309c07b235dd560f6696 | https://github.com/MrMicrowaveOven/zadt/blob/789420b1e05f7545f886309c07b235dd560f6696/lib/zadt/AbstractDataTypes/Graph/face_graph.rb#L53-L95 | train |
MrMicrowaveOven/zadt | lib/zadt/AbstractDataTypes/Graph/face_graph.rb | Zadt.FaceGraph.find_neighbors | def find_neighbors(vertex_array)
vertex_array_check(vertex_array)
neighbors = []
vertex_array.each do |vertex|
@faces.each do |face|
neighbors << face if face.vertices.include?(vertex)
end
end
neighbors.uniq
end | ruby | def find_neighbors(vertex_array)
vertex_array_check(vertex_array)
neighbors = []
vertex_array.each do |vertex|
@faces.each do |face|
neighbors << face if face.vertices.include?(vertex)
end
end
neighbors.uniq
end | [
"def",
"find_neighbors",
"(",
"vertex_array",
")",
"vertex_array_check",
"(",
"vertex_array",
")",
"neighbors",
"=",
"[",
"]",
"vertex_array",
".",
"each",
"do",
"|",
"vertex",
"|",
"@faces",
".",
"each",
"do",
"|",
"face",
"|",
"neighbors",
"<<",
"face",
"if",
"face",
".",
"vertices",
".",
"include?",
"(",
"vertex",
")",
"end",
"end",
"neighbors",
".",
"uniq",
"end"
] | Return all faces containing the given vertices | [
"Return",
"all",
"faces",
"containing",
"the",
"given",
"vertices"
] | 789420b1e05f7545f886309c07b235dd560f6696 | https://github.com/MrMicrowaveOven/zadt/blob/789420b1e05f7545f886309c07b235dd560f6696/lib/zadt/AbstractDataTypes/Graph/face_graph.rb#L98-L107 | train |
MrMicrowaveOven/zadt | lib/zadt/AbstractDataTypes/Graph/face_graph.rb | Zadt.FaceGraph.find_face_neighbors | def find_face_neighbors(face)
raise "not a face" unless face.is_a?(Face)
neighbors = find_neighbors(face.vertices)
neighbors - [face]
end | ruby | def find_face_neighbors(face)
raise "not a face" unless face.is_a?(Face)
neighbors = find_neighbors(face.vertices)
neighbors - [face]
end | [
"def",
"find_face_neighbors",
"(",
"face",
")",
"raise",
"\"not a face\"",
"unless",
"face",
".",
"is_a?",
"(",
"Face",
")",
"neighbors",
"=",
"find_neighbors",
"(",
"face",
".",
"vertices",
")",
"neighbors",
"-",
"[",
"face",
"]",
"end"
] | Return all neighbors of the given faces
Neighbor is defined as sharing a vertex,
not necessarily sharing an edge. | [
"Return",
"all",
"neighbors",
"of",
"the",
"given",
"faces",
"Neighbor",
"is",
"defined",
"as",
"sharing",
"a",
"vertex",
"not",
"necessarily",
"sharing",
"an",
"edge",
"."
] | 789420b1e05f7545f886309c07b235dd560f6696 | https://github.com/MrMicrowaveOven/zadt/blob/789420b1e05f7545f886309c07b235dd560f6696/lib/zadt/AbstractDataTypes/Graph/face_graph.rb#L112-L116 | train |
4rlm/crm_formatter | lib/crm_formatter/proper.rb | CrmFormatter.Proper.check_proper_status | def check_proper_status(hsh)
proper = hsh[:proper]
proper_f = hsh[:proper_f]
status = 'invalid'
status = proper != proper_f ? 'formatted' : 'unchanged' if proper && proper_f
hsh[:proper_status] = status if status.present?
hsh
end | ruby | def check_proper_status(hsh)
proper = hsh[:proper]
proper_f = hsh[:proper_f]
status = 'invalid'
status = proper != proper_f ? 'formatted' : 'unchanged' if proper && proper_f
hsh[:proper_status] = status if status.present?
hsh
end | [
"def",
"check_proper_status",
"(",
"hsh",
")",
"proper",
"=",
"hsh",
"[",
":proper",
"]",
"proper_f",
"=",
"hsh",
"[",
":proper_f",
"]",
"status",
"=",
"'invalid'",
"status",
"=",
"proper",
"!=",
"proper_f",
"?",
"'formatted'",
":",
"'unchanged'",
"if",
"proper",
"&&",
"proper_f",
"hsh",
"[",
":proper_status",
"]",
"=",
"status",
"if",
"status",
".",
"present?",
"hsh",
"end"
] | COMPARE ORIGINAL AND FORMATTED PROPER | [
"COMPARE",
"ORIGINAL",
"AND",
"FORMATTED",
"PROPER"
] | 5060d27552a3871257cd08612c8e93b7b2b6a350 | https://github.com/4rlm/crm_formatter/blob/5060d27552a3871257cd08612c8e93b7b2b6a350/lib/crm_formatter/proper.rb#L13-L20 | train |
blambeau/finitio-rb | lib/finitio/type/union_type.rb | Finitio.UnionType.dress | def dress(value, handler = DressHelper.new)
error = nil
# Do nothing on TypeError as the next candidate could be the good one!
candidates.each do |c|
success, uped = handler.just_try do
c.dress(value, handler)
end
return uped if success
error ||= uped
end
# No one succeed, just fail
handler.failed!(self, value, error)
end | ruby | def dress(value, handler = DressHelper.new)
error = nil
# Do nothing on TypeError as the next candidate could be the good one!
candidates.each do |c|
success, uped = handler.just_try do
c.dress(value, handler)
end
return uped if success
error ||= uped
end
# No one succeed, just fail
handler.failed!(self, value, error)
end | [
"def",
"dress",
"(",
"value",
",",
"handler",
"=",
"DressHelper",
".",
"new",
")",
"error",
"=",
"nil",
"candidates",
".",
"each",
"do",
"|",
"c",
"|",
"success",
",",
"uped",
"=",
"handler",
".",
"just_try",
"do",
"c",
".",
"dress",
"(",
"value",
",",
"handler",
")",
"end",
"return",
"uped",
"if",
"success",
"error",
"||=",
"uped",
"end",
"handler",
".",
"failed!",
"(",
"self",
",",
"value",
",",
"error",
")",
"end"
] | Invoke `dress` on each candidate type in turn. Return the value
returned by the first one that does not fail. Fail with an TypeError if no
candidate succeeds at tranforming `value`. | [
"Invoke",
"dress",
"on",
"each",
"candidate",
"type",
"in",
"turn",
".",
"Return",
"the",
"value",
"returned",
"by",
"the",
"first",
"one",
"that",
"does",
"not",
"fail",
".",
"Fail",
"with",
"an",
"TypeError",
"if",
"no",
"candidate",
"succeeds",
"at",
"tranforming",
"value",
"."
] | c07a3887a6af26b2ed1eb3c50b101e210d3d8b40 | https://github.com/blambeau/finitio-rb/blob/c07a3887a6af26b2ed1eb3c50b101e210d3d8b40/lib/finitio/type/union_type.rb#L53-L67 | train |
arrac/eluka | lib/eluka/feature_vector.rb | Eluka.FeatureVectors.define_features | def define_features
@fvs.each do |vector, label|
vector.each do |term, value|
@features.add(term)
end
end
end | ruby | def define_features
@fvs.each do |vector, label|
vector.each do |term, value|
@features.add(term)
end
end
end | [
"def",
"define_features",
"@fvs",
".",
"each",
"do",
"|",
"vector",
",",
"label",
"|",
"vector",
".",
"each",
"do",
"|",
"term",
",",
"value",
"|",
"@features",
".",
"add",
"(",
"term",
")",
"end",
"end",
"end"
] | For training data points we make sure all the features
are added to the feature list | [
"For",
"training",
"data",
"points",
"we",
"make",
"sure",
"all",
"the",
"features",
"are",
"added",
"to",
"the",
"feature",
"list"
] | 1293f0cc6f9810a1a289ad74c8fab234db786212 | https://github.com/arrac/eluka/blob/1293f0cc6f9810a1a289ad74c8fab234db786212/lib/eluka/feature_vector.rb#L41-L47 | train |
talis/blueprint_rb | lib/blueprint_ruby_client/api/integrations_api.rb | BlueprintClient.IntegrationsApi.add_integration | def add_integration(namespace, body, opts = {})
data, _status_code, _headers = add_integration_with_http_info(namespace, body, opts)
return data
end | ruby | def add_integration(namespace, body, opts = {})
data, _status_code, _headers = add_integration_with_http_info(namespace, body, opts)
return data
end | [
"def",
"add_integration",
"(",
"namespace",
",",
"body",
",",
"opts",
"=",
"{",
"}",
")",
"data",
",",
"_status_code",
",",
"_headers",
"=",
"add_integration_with_http_info",
"(",
"namespace",
",",
"body",
",",
"opts",
")",
"return",
"data",
"end"
] | Add an integration
@param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores.
@param body integration
@param [Hash] opts the optional parameters
@return [IntegrationBody] | [
"Add",
"an",
"integration"
] | 0ded0734161d288ba2d81485b3d3ec82a4063e1e | https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/integrations_api.rb#L29-L32 | train |
talis/blueprint_rb | lib/blueprint_ruby_client/api/integrations_api.rb | BlueprintClient.IntegrationsApi.delete_integration | def delete_integration(namespace, integration_id, integration_type, opts = {})
delete_integration_with_http_info(namespace, integration_id, integration_type, opts)
return nil
end | ruby | def delete_integration(namespace, integration_id, integration_type, opts = {})
delete_integration_with_http_info(namespace, integration_id, integration_type, opts)
return nil
end | [
"def",
"delete_integration",
"(",
"namespace",
",",
"integration_id",
",",
"integration_type",
",",
"opts",
"=",
"{",
"}",
")",
"delete_integration_with_http_info",
"(",
"namespace",
",",
"integration_id",
",",
"integration_type",
",",
"opts",
")",
"return",
"nil",
"end"
] | Delete an integration
@param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores.
@param integration_id id of an integration
@param integration_type Type of external integration, e.g. 'lti1'
@param [Hash] opts the optional parameters
@return [nil] | [
"Delete",
"an",
"integration"
] | 0ded0734161d288ba2d81485b3d3ec82a4063e1e | https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/integrations_api.rb#L105-L108 | train |
talis/blueprint_rb | lib/blueprint_ruby_client/api/integrations_api.rb | BlueprintClient.IntegrationsApi.get_integration | def get_integration(namespace, integration_type, integration_id, opts = {})
data, _status_code, _headers = get_integration_with_http_info(namespace, integration_type, integration_id, opts)
return data
end | ruby | def get_integration(namespace, integration_type, integration_id, opts = {})
data, _status_code, _headers = get_integration_with_http_info(namespace, integration_type, integration_id, opts)
return data
end | [
"def",
"get_integration",
"(",
"namespace",
",",
"integration_type",
",",
"integration_id",
",",
"opts",
"=",
"{",
"}",
")",
"data",
",",
"_status_code",
",",
"_headers",
"=",
"get_integration_with_http_info",
"(",
"namespace",
",",
"integration_type",
",",
"integration_id",
",",
"opts",
")",
"return",
"data",
"end"
] | Get details of a given integration
@param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores.
@param integration_type Type of external integration, e.g. 'lti1'
@param integration_id id of an integration
@param [Hash] opts the optional parameters
@return [IntegrationBody] | [
"Get",
"details",
"of",
"a",
"given",
"integration"
] | 0ded0734161d288ba2d81485b3d3ec82a4063e1e | https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/integrations_api.rb#L189-L192 | train |
talis/blueprint_rb | lib/blueprint_ruby_client/api/integrations_api.rb | BlueprintClient.IntegrationsApi.replace_integration | def replace_integration(namespace, integration_id, integration_type, body, opts = {})
data, _status_code, _headers = replace_integration_with_http_info(namespace, integration_id, integration_type, body, opts)
return data
end | ruby | def replace_integration(namespace, integration_id, integration_type, body, opts = {})
data, _status_code, _headers = replace_integration_with_http_info(namespace, integration_id, integration_type, body, opts)
return data
end | [
"def",
"replace_integration",
"(",
"namespace",
",",
"integration_id",
",",
"integration_type",
",",
"body",
",",
"opts",
"=",
"{",
"}",
")",
"data",
",",
"_status_code",
",",
"_headers",
"=",
"replace_integration_with_http_info",
"(",
"namespace",
",",
"integration_id",
",",
"integration_type",
",",
"body",
",",
"opts",
")",
"return",
"data",
"end"
] | Replace an integration
@param namespace identifier namespacing the blueprint. It must start with a letter or underscore and can only be followed by letters, numbers and underscores.
@param integration_id id of an integration
@param integration_type Type of external integration, e.g. 'lti1'
@param body integration
@param [Hash] opts the optional parameters
@return [IntegrationBody] | [
"Replace",
"an",
"integration"
] | 0ded0734161d288ba2d81485b3d3ec82a4063e1e | https://github.com/talis/blueprint_rb/blob/0ded0734161d288ba2d81485b3d3ec82a4063e1e/lib/blueprint_ruby_client/api/integrations_api.rb#L528-L531 | train |
JonnieCache/tinyci | lib/tinyci/git_utils.rb | TinyCI.GitUtils.repo_root | def repo_root
return git_directory_path if inside_bare_repo?
if inside_git_directory?
File.expand_path('..', git_directory_path)
elsif inside_work_tree?
execute(git_cmd('rev-parse', '--show-toplevel'))
else
raise 'not in git directory or work tree!?'
end
end | ruby | def repo_root
return git_directory_path if inside_bare_repo?
if inside_git_directory?
File.expand_path('..', git_directory_path)
elsif inside_work_tree?
execute(git_cmd('rev-parse', '--show-toplevel'))
else
raise 'not in git directory or work tree!?'
end
end | [
"def",
"repo_root",
"return",
"git_directory_path",
"if",
"inside_bare_repo?",
"if",
"inside_git_directory?",
"File",
".",
"expand_path",
"(",
"'..'",
",",
"git_directory_path",
")",
"elsif",
"inside_work_tree?",
"execute",
"(",
"git_cmd",
"(",
"'rev-parse'",
",",
"'--show-toplevel'",
")",
")",
"else",
"raise",
"'not in git directory or work tree!?'",
"end",
"end"
] | Returns the absolute path to the root of the current git directory
@return [String] the path | [
"Returns",
"the",
"absolute",
"path",
"to",
"the",
"root",
"of",
"the",
"current",
"git",
"directory"
] | 6dc23fc201f3527718afd814223eee0238ef8b06 | https://github.com/JonnieCache/tinyci/blob/6dc23fc201f3527718afd814223eee0238ef8b06/lib/tinyci/git_utils.rb#L11-L21 | train |
dcrec1/acts_as_solr_reloaded | lib/acts_as_solr/parser_methods.rb | ActsAsSolr.ParserMethods.parse_results | def parse_results(solr_data, options = {})
results = {
:docs => [],
:total => 0
}
configuration = {
:format => :objects
}
results.update(:spellcheck => solr_data.data['spellcheck']) unless solr_data.nil?
results.update(:facets => {'facet_fields' => []}) if options[:facets]
unless solr_data.nil? or solr_data.header['params'].nil?
header = solr_data.header
results.update :rows => header['params']['rows']
results.update :start => header['params']['start']
end
return SearchResults.new(results) if (solr_data.nil? || solr_data.total_hits == 0)
configuration.update(options) if options.is_a?(Hash)
ids = solr_data.hits.collect {|doc| doc["#{solr_configuration[:primary_key_field]}"]}.flatten
result = find_objects(ids, options, configuration)
add_scores(result, solr_data) if configuration[:format] == :objects && options[:scores]
highlighted = {}
solr_data.highlighting.map do |x,y|
e={}
y1=y.map{|x1,y1| e[x1.gsub(/_[^_]*/,"")]=y1} unless y.nil?
highlighted[x.gsub(/[^:]*:/,"").to_i]=e
end unless solr_data.highlighting.nil?
results.update(:facets => solr_data.data['facet_counts']) if options[:facets]
results.update({:docs => result, :total => solr_data.total_hits, :max_score => solr_data.max_score, :query_time => solr_data.data['responseHeader']['QTime']})
results.update({:highlights=>highlighted})
SearchResults.new(results)
end | ruby | def parse_results(solr_data, options = {})
results = {
:docs => [],
:total => 0
}
configuration = {
:format => :objects
}
results.update(:spellcheck => solr_data.data['spellcheck']) unless solr_data.nil?
results.update(:facets => {'facet_fields' => []}) if options[:facets]
unless solr_data.nil? or solr_data.header['params'].nil?
header = solr_data.header
results.update :rows => header['params']['rows']
results.update :start => header['params']['start']
end
return SearchResults.new(results) if (solr_data.nil? || solr_data.total_hits == 0)
configuration.update(options) if options.is_a?(Hash)
ids = solr_data.hits.collect {|doc| doc["#{solr_configuration[:primary_key_field]}"]}.flatten
result = find_objects(ids, options, configuration)
add_scores(result, solr_data) if configuration[:format] == :objects && options[:scores]
highlighted = {}
solr_data.highlighting.map do |x,y|
e={}
y1=y.map{|x1,y1| e[x1.gsub(/_[^_]*/,"")]=y1} unless y.nil?
highlighted[x.gsub(/[^:]*:/,"").to_i]=e
end unless solr_data.highlighting.nil?
results.update(:facets => solr_data.data['facet_counts']) if options[:facets]
results.update({:docs => result, :total => solr_data.total_hits, :max_score => solr_data.max_score, :query_time => solr_data.data['responseHeader']['QTime']})
results.update({:highlights=>highlighted})
SearchResults.new(results)
end | [
"def",
"parse_results",
"(",
"solr_data",
",",
"options",
"=",
"{",
"}",
")",
"results",
"=",
"{",
":docs",
"=>",
"[",
"]",
",",
":total",
"=>",
"0",
"}",
"configuration",
"=",
"{",
":format",
"=>",
":objects",
"}",
"results",
".",
"update",
"(",
":spellcheck",
"=>",
"solr_data",
".",
"data",
"[",
"'spellcheck'",
"]",
")",
"unless",
"solr_data",
".",
"nil?",
"results",
".",
"update",
"(",
":facets",
"=>",
"{",
"'facet_fields'",
"=>",
"[",
"]",
"}",
")",
"if",
"options",
"[",
":facets",
"]",
"unless",
"solr_data",
".",
"nil?",
"or",
"solr_data",
".",
"header",
"[",
"'params'",
"]",
".",
"nil?",
"header",
"=",
"solr_data",
".",
"header",
"results",
".",
"update",
":rows",
"=>",
"header",
"[",
"'params'",
"]",
"[",
"'rows'",
"]",
"results",
".",
"update",
":start",
"=>",
"header",
"[",
"'params'",
"]",
"[",
"'start'",
"]",
"end",
"return",
"SearchResults",
".",
"new",
"(",
"results",
")",
"if",
"(",
"solr_data",
".",
"nil?",
"||",
"solr_data",
".",
"total_hits",
"==",
"0",
")",
"configuration",
".",
"update",
"(",
"options",
")",
"if",
"options",
".",
"is_a?",
"(",
"Hash",
")",
"ids",
"=",
"solr_data",
".",
"hits",
".",
"collect",
"{",
"|",
"doc",
"|",
"doc",
"[",
"\"#{solr_configuration[:primary_key_field]}\"",
"]",
"}",
".",
"flatten",
"result",
"=",
"find_objects",
"(",
"ids",
",",
"options",
",",
"configuration",
")",
"add_scores",
"(",
"result",
",",
"solr_data",
")",
"if",
"configuration",
"[",
":format",
"]",
"==",
":objects",
"&&",
"options",
"[",
":scores",
"]",
"highlighted",
"=",
"{",
"}",
"solr_data",
".",
"highlighting",
".",
"map",
"do",
"|",
"x",
",",
"y",
"|",
"e",
"=",
"{",
"}",
"y1",
"=",
"y",
".",
"map",
"{",
"|",
"x1",
",",
"y1",
"|",
"e",
"[",
"x1",
".",
"gsub",
"(",
"/",
"/",
",",
"\"\"",
")",
"]",
"=",
"y1",
"}",
"unless",
"y",
".",
"nil?",
"highlighted",
"[",
"x",
".",
"gsub",
"(",
"/",
"/",
",",
"\"\"",
")",
".",
"to_i",
"]",
"=",
"e",
"end",
"unless",
"solr_data",
".",
"highlighting",
".",
"nil?",
"results",
".",
"update",
"(",
":facets",
"=>",
"solr_data",
".",
"data",
"[",
"'facet_counts'",
"]",
")",
"if",
"options",
"[",
":facets",
"]",
"results",
".",
"update",
"(",
"{",
":docs",
"=>",
"result",
",",
":total",
"=>",
"solr_data",
".",
"total_hits",
",",
":max_score",
"=>",
"solr_data",
".",
"max_score",
",",
":query_time",
"=>",
"solr_data",
".",
"data",
"[",
"'responseHeader'",
"]",
"[",
"'QTime'",
"]",
"}",
")",
"results",
".",
"update",
"(",
"{",
":highlights",
"=>",
"highlighted",
"}",
")",
"SearchResults",
".",
"new",
"(",
"results",
")",
"end"
] | Parses the data returned from Solr | [
"Parses",
"the",
"data",
"returned",
"from",
"Solr"
] | 20900d1339daa1f805c74c0d2203afb37edde3db | https://github.com/dcrec1/acts_as_solr_reloaded/blob/20900d1339daa1f805c74c0d2203afb37edde3db/lib/acts_as_solr/parser_methods.rb#L134-L171 | train |
dcrec1/acts_as_solr_reloaded | lib/acts_as_solr/parser_methods.rb | ActsAsSolr.ParserMethods.reorder | def reorder(things, ids)
ordered_things = []
ids.each do |id|
thing = things.find{ |t| t.id.to_s == id.to_s }
ordered_things |= [thing] if thing
end
ordered_things
end | ruby | def reorder(things, ids)
ordered_things = []
ids.each do |id|
thing = things.find{ |t| t.id.to_s == id.to_s }
ordered_things |= [thing] if thing
end
ordered_things
end | [
"def",
"reorder",
"(",
"things",
",",
"ids",
")",
"ordered_things",
"=",
"[",
"]",
"ids",
".",
"each",
"do",
"|",
"id",
"|",
"thing",
"=",
"things",
".",
"find",
"{",
"|",
"t",
"|",
"t",
".",
"id",
".",
"to_s",
"==",
"id",
".",
"to_s",
"}",
"ordered_things",
"|=",
"[",
"thing",
"]",
"if",
"thing",
"end",
"ordered_things",
"end"
] | Reorders the instances keeping the order returned from Solr | [
"Reorders",
"the",
"instances",
"keeping",
"the",
"order",
"returned",
"from",
"Solr"
] | 20900d1339daa1f805c74c0d2203afb37edde3db | https://github.com/dcrec1/acts_as_solr_reloaded/blob/20900d1339daa1f805c74c0d2203afb37edde3db/lib/acts_as_solr/parser_methods.rb#L191-L198 | train |
dcrec1/acts_as_solr_reloaded | lib/acts_as_solr/parser_methods.rb | ActsAsSolr.ParserMethods.add_scores | def add_scores(results, solr_data)
with_score = []
solr_data.hits.each do |doc|
with_score.push([doc["score"],
results.find {|record| scorable_record?(record, doc) }])
end
with_score.each do |score, object|
class << object; attr_accessor :solr_score; end
object.solr_score = score
end
end | ruby | def add_scores(results, solr_data)
with_score = []
solr_data.hits.each do |doc|
with_score.push([doc["score"],
results.find {|record| scorable_record?(record, doc) }])
end
with_score.each do |score, object|
class << object; attr_accessor :solr_score; end
object.solr_score = score
end
end | [
"def",
"add_scores",
"(",
"results",
",",
"solr_data",
")",
"with_score",
"=",
"[",
"]",
"solr_data",
".",
"hits",
".",
"each",
"do",
"|",
"doc",
"|",
"with_score",
".",
"push",
"(",
"[",
"doc",
"[",
"\"score\"",
"]",
",",
"results",
".",
"find",
"{",
"|",
"record",
"|",
"scorable_record?",
"(",
"record",
",",
"doc",
")",
"}",
"]",
")",
"end",
"with_score",
".",
"each",
"do",
"|",
"score",
",",
"object",
"|",
"class",
"<<",
"object",
";",
"attr_accessor",
":solr_score",
";",
"end",
"object",
".",
"solr_score",
"=",
"score",
"end",
"end"
] | Adds the score to each one of the instances found | [
"Adds",
"the",
"score",
"to",
"each",
"one",
"of",
"the",
"instances",
"found"
] | 20900d1339daa1f805c74c0d2203afb37edde3db | https://github.com/dcrec1/acts_as_solr_reloaded/blob/20900d1339daa1f805c74c0d2203afb37edde3db/lib/acts_as_solr/parser_methods.rb#L223-L233 | train |
4rlm/crm_formatter | lib/crm_formatter/web.rb | CrmFormatter.Web.check_web_status | def check_web_status(hsh)
status = 'invalid' if hsh[:web_neg]&.include?('error')
if hsh[:url] && hsh[:url_f] && status.nil?
status = hsh[:url] != hsh[:url_f] ? 'formatted' : 'unchanged'
end
hsh[:web_status] = status if status.present?
hsh
end | ruby | def check_web_status(hsh)
status = 'invalid' if hsh[:web_neg]&.include?('error')
if hsh[:url] && hsh[:url_f] && status.nil?
status = hsh[:url] != hsh[:url_f] ? 'formatted' : 'unchanged'
end
hsh[:web_status] = status if status.present?
hsh
end | [
"def",
"check_web_status",
"(",
"hsh",
")",
"status",
"=",
"'invalid'",
"if",
"hsh",
"[",
":web_neg",
"]",
"&.",
"include?",
"(",
"'error'",
")",
"if",
"hsh",
"[",
":url",
"]",
"&&",
"hsh",
"[",
":url_f",
"]",
"&&",
"status",
".",
"nil?",
"status",
"=",
"hsh",
"[",
":url",
"]",
"!=",
"hsh",
"[",
":url_f",
"]",
"?",
"'formatted'",
":",
"'unchanged'",
"end",
"hsh",
"[",
":web_status",
"]",
"=",
"status",
"if",
"status",
".",
"present?",
"hsh",
"end"
] | COMPARE ORIGINAL AND FORMATTED URL | [
"COMPARE",
"ORIGINAL",
"AND",
"FORMATTED",
"URL"
] | 5060d27552a3871257cd08612c8e93b7b2b6a350 | https://github.com/4rlm/crm_formatter/blob/5060d27552a3871257cd08612c8e93b7b2b6a350/lib/crm_formatter/web.rb#L31-L40 | train |
4rlm/crm_formatter | lib/crm_formatter/web.rb | CrmFormatter.Web.extract_path | def extract_path(url_hash)
path_parts = url_hash[:url_f].split('//').last.split('/')[1..-1]
path = "/#{path_parts.join('/')}"
if path&.length > 2
url_hash[:url_path] = path
url_hash[:url_f] = url_hash[:url_f].gsub(url_hash[:url_path], '')
end
url_hash
end | ruby | def extract_path(url_hash)
path_parts = url_hash[:url_f].split('//').last.split('/')[1..-1]
path = "/#{path_parts.join('/')}"
if path&.length > 2
url_hash[:url_path] = path
url_hash[:url_f] = url_hash[:url_f].gsub(url_hash[:url_path], '')
end
url_hash
end | [
"def",
"extract_path",
"(",
"url_hash",
")",
"path_parts",
"=",
"url_hash",
"[",
":url_f",
"]",
".",
"split",
"(",
"'//'",
")",
".",
"last",
".",
"split",
"(",
"'/'",
")",
"[",
"1",
"..",
"-",
"1",
"]",
"path",
"=",
"\"/#{path_parts.join('/')}\"",
"if",
"path",
"&.",
"length",
">",
"2",
"url_hash",
"[",
":url_path",
"]",
"=",
"path",
"url_hash",
"[",
":url_f",
"]",
"=",
"url_hash",
"[",
":url_f",
"]",
".",
"gsub",
"(",
"url_hash",
"[",
":url_path",
"]",
",",
"''",
")",
"end",
"url_hash",
"end"
] | Supporting Methods Below | [
"Supporting",
"Methods",
"Below"
] | 5060d27552a3871257cd08612c8e93b7b2b6a350 | https://github.com/4rlm/crm_formatter/blob/5060d27552a3871257cd08612c8e93b7b2b6a350/lib/crm_formatter/web.rb#L143-L151 | train |
justintanner/column_pack | lib/column_pack/view_helpers.rb | ColumnPack.ViewHelpers.pack_element | def pack_element(height, content = nil, &block)
return if @column_packer.nil?
if block_given?
@column_packer.add(height.to_i, capture(&block))
else
@column_packer.add(height.to_i, content)
end
end | ruby | def pack_element(height, content = nil, &block)
return if @column_packer.nil?
if block_given?
@column_packer.add(height.to_i, capture(&block))
else
@column_packer.add(height.to_i, content)
end
end | [
"def",
"pack_element",
"(",
"height",
",",
"content",
"=",
"nil",
",",
"&",
"block",
")",
"return",
"if",
"@column_packer",
".",
"nil?",
"if",
"block_given?",
"@column_packer",
".",
"add",
"(",
"height",
".",
"to_i",
",",
"capture",
"(",
"&",
"block",
")",
")",
"else",
"@column_packer",
".",
"add",
"(",
"height",
".",
"to_i",
",",
"content",
")",
"end",
"end"
] | Packs a single element with a given height into a column.
pack_element should be called withing pack_in_columns's block:
pack_in_columns(3) do
pack_element(100) do
"A"
end
end
Accepts parameter strings or block content (ERB, strings, etc). | [
"Packs",
"a",
"single",
"element",
"with",
"a",
"given",
"height",
"into",
"a",
"column",
"."
] | bffe22f74063718fdcf7b9c5dce1001ceabe8046 | https://github.com/justintanner/column_pack/blob/bffe22f74063718fdcf7b9c5dce1001ceabe8046/lib/column_pack/view_helpers.rb#L40-L48 | train |
LAS-IT/ps_utilities | lib/ps_utilities/pre_built_post.rb | PsUtilities.PreBuiltPost.u_students_extension | def u_students_extension(data)
db_extensions = { "name"=>"u_students_extension", "recordFound"=>false,
"_field"=> [] }
data.each do |key, value|
db_extensions["_field"] << {"name"=>"#{key}", "type"=>"String", "value"=>"#{value}"}
end
db_extensions
end | ruby | def u_students_extension(data)
db_extensions = { "name"=>"u_students_extension", "recordFound"=>false,
"_field"=> [] }
data.each do |key, value|
db_extensions["_field"] << {"name"=>"#{key}", "type"=>"String", "value"=>"#{value}"}
end
db_extensions
end | [
"def",
"u_students_extension",
"(",
"data",
")",
"db_extensions",
"=",
"{",
"\"name\"",
"=>",
"\"u_students_extension\"",
",",
"\"recordFound\"",
"=>",
"false",
",",
"\"_field\"",
"=>",
"[",
"]",
"}",
"data",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"db_extensions",
"[",
"\"_field\"",
"]",
"<<",
"{",
"\"name\"",
"=>",
"\"#{key}\"",
",",
"\"type\"",
"=>",
"\"String\"",
",",
"\"value\"",
"=>",
"\"#{value}\"",
"}",
"end",
"db_extensions",
"end"
] | prepare data to update student database extensions
@param data [Hash] - with the format: {u_students_extension: {field1: data1, field2: data2}}
@return [Hash] - with data like below:
{ "name"=>"u_students_extension",
"recordFound"=>false,
"_field"=> [
{"name"=>"preferredname", "type"=>"String", "value"=>"Joe"},
{"name"=>"student_email", "type"=>"String", "value"=>"[email protected]"},
]
} | [
"prepare",
"data",
"to",
"update",
"student",
"database",
"extensions"
] | 85fbb528d982b66ca706de5fdb70b4410f21e637 | https://github.com/LAS-IT/ps_utilities/blob/85fbb528d982b66ca706de5fdb70b4410f21e637/lib/ps_utilities/pre_built_post.rb#L124-L131 | train |
LAS-IT/ps_utilities | lib/ps_utilities/pre_built_post.rb | PsUtilities.PreBuiltPost.u_studentsuserfields | def u_studentsuserfields(data)
db_extensions = { "name"=>"u_studentsuserfields", "recordFound"=>false,
"_field"=> [] }
data.each do |key, value|
db_extensions["_field"] << {"name"=>"#{key}", "type"=>"String", "value"=>"#{value}"}
end
db_extensions
end | ruby | def u_studentsuserfields(data)
db_extensions = { "name"=>"u_studentsuserfields", "recordFound"=>false,
"_field"=> [] }
data.each do |key, value|
db_extensions["_field"] << {"name"=>"#{key}", "type"=>"String", "value"=>"#{value}"}
end
db_extensions
end | [
"def",
"u_studentsuserfields",
"(",
"data",
")",
"db_extensions",
"=",
"{",
"\"name\"",
"=>",
"\"u_studentsuserfields\"",
",",
"\"recordFound\"",
"=>",
"false",
",",
"\"_field\"",
"=>",
"[",
"]",
"}",
"data",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"db_extensions",
"[",
"\"_field\"",
"]",
"<<",
"{",
"\"name\"",
"=>",
"\"#{key}\"",
",",
"\"type\"",
"=>",
"\"String\"",
",",
"\"value\"",
"=>",
"\"#{value}\"",
"}",
"end",
"db_extensions",
"end"
] | prepare data to built-in database extensions
@param data [Hash] - with the format: {u_studentsuserfields: {field1: data1, field2: data2}}
@return [Hash] - with data like below:
{ "name"=>"u_students_extension",
"recordFound"=>false,
"_field"=> [
{"name"=>"transcriptaddrzip", "type"=>"String", "value"=>75230},
{"name"=>"transcriptaddrcountry", "type"=>"String", "value"=>"United States"},
{"name"=>"transcriptaddrcity", "type"=>"String", "value"=>"dallas"},
{"name"=>"transcriptaddrstate", "type"=>"String", "value"=>"Texas"},
{"name"=>"transcriptaddrline1", "type"=>"String", "value"=>"6138 meadow rd"}
]
} | [
"prepare",
"data",
"to",
"built",
"-",
"in",
"database",
"extensions"
] | 85fbb528d982b66ca706de5fdb70b4410f21e637 | https://github.com/LAS-IT/ps_utilities/blob/85fbb528d982b66ca706de5fdb70b4410f21e637/lib/ps_utilities/pre_built_post.rb#L146-L153 | train |
trampoline/rews | lib/rews/util.rb | Rews.Util.strip_bang | def strip_bang(k)
if k.is_a? Symbol
k.to_s[0...-1].to_sym
else
k.to_s[0...-1]
end
end | ruby | def strip_bang(k)
if k.is_a? Symbol
k.to_s[0...-1].to_sym
else
k.to_s[0...-1]
end
end | [
"def",
"strip_bang",
"(",
"k",
")",
"if",
"k",
".",
"is_a?",
"Symbol",
"k",
".",
"to_s",
"[",
"0",
"...",
"-",
"1",
"]",
".",
"to_sym",
"else",
"k",
".",
"to_s",
"[",
"0",
"...",
"-",
"1",
"]",
"end",
"end"
] | strip a ! from the end of a +String+ or +Symbol+ | [
"strip",
"a",
"!",
"from",
"the",
"end",
"of",
"a",
"+",
"String",
"+",
"or",
"+",
"Symbol",
"+"
] | 3f18671a25750b9045714af587c1989679f84de8 | https://github.com/trampoline/rews/blob/3f18671a25750b9045714af587c1989679f84de8/lib/rews/util.rb#L48-L54 | train |
trampoline/rews | lib/rews/util.rb | Rews.Util.camelize | def camelize(s)
if s.is_a?(Symbol)
s.to_s.split('_').map(&:capitalize).join.to_sym
else
s.split('_').map(&:capitalize).join
end
end | ruby | def camelize(s)
if s.is_a?(Symbol)
s.to_s.split('_').map(&:capitalize).join.to_sym
else
s.split('_').map(&:capitalize).join
end
end | [
"def",
"camelize",
"(",
"s",
")",
"if",
"s",
".",
"is_a?",
"(",
"Symbol",
")",
"s",
".",
"to_s",
".",
"split",
"(",
"'_'",
")",
".",
"map",
"(",
"&",
":capitalize",
")",
".",
"join",
".",
"to_sym",
"else",
"s",
".",
"split",
"(",
"'_'",
")",
".",
"map",
"(",
"&",
":capitalize",
")",
".",
"join",
"end",
"end"
] | camel-case a +String+ | [
"camel",
"-",
"case",
"a",
"+",
"String",
"+"
] | 3f18671a25750b9045714af587c1989679f84de8 | https://github.com/trampoline/rews/blob/3f18671a25750b9045714af587c1989679f84de8/lib/rews/util.rb#L57-L63 | train |
trampoline/rews | lib/rews/util.rb | Rews.Util.camel_keys | def camel_keys(h)
Hash[h.map{|k,v| [camelize(k.to_s), v]}]
end | ruby | def camel_keys(h)
Hash[h.map{|k,v| [camelize(k.to_s), v]}]
end | [
"def",
"camel_keys",
"(",
"h",
")",
"Hash",
"[",
"h",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"[",
"camelize",
"(",
"k",
".",
"to_s",
")",
",",
"v",
"]",
"}",
"]",
"end"
] | camel-case the keys of a +Hash+ | [
"camel",
"-",
"case",
"the",
"keys",
"of",
"a",
"+",
"Hash",
"+"
] | 3f18671a25750b9045714af587c1989679f84de8 | https://github.com/trampoline/rews/blob/3f18671a25750b9045714af587c1989679f84de8/lib/rews/util.rb#L66-L68 | train |
trampoline/rews | lib/rews/util.rb | Rews.Util.apply_namespace | def apply_namespace(qname, apply_prefix, apply_uri)
local_part, prefix, uri = qname
if !prefix
prefix = apply_prefix
uri = apply_uri
end
[local_part, prefix, uri].compact
end | ruby | def apply_namespace(qname, apply_prefix, apply_uri)
local_part, prefix, uri = qname
if !prefix
prefix = apply_prefix
uri = apply_uri
end
[local_part, prefix, uri].compact
end | [
"def",
"apply_namespace",
"(",
"qname",
",",
"apply_prefix",
",",
"apply_uri",
")",
"local_part",
",",
"prefix",
",",
"uri",
"=",
"qname",
"if",
"!",
"prefix",
"prefix",
"=",
"apply_prefix",
"uri",
"=",
"apply_uri",
"end",
"[",
"local_part",
",",
"prefix",
",",
"uri",
"]",
".",
"compact",
"end"
] | given an exploded qname, apply a given namespace and uri if the qname
has no namespace already | [
"given",
"an",
"exploded",
"qname",
"apply",
"a",
"given",
"namespace",
"and",
"uri",
"if",
"the",
"qname",
"has",
"no",
"namespace",
"already"
] | 3f18671a25750b9045714af587c1989679f84de8 | https://github.com/trampoline/rews/blob/3f18671a25750b9045714af587c1989679f84de8/lib/rews/util.rb#L72-L81 | train |
trampoline/rews | lib/rews/util.rb | Rews.Util.camelize_qname | def camelize_qname(qname)
local_part, prefix, uri = qname
[camelize(local_part), prefix, uri].compact
end | ruby | def camelize_qname(qname)
local_part, prefix, uri = qname
[camelize(local_part), prefix, uri].compact
end | [
"def",
"camelize_qname",
"(",
"qname",
")",
"local_part",
",",
"prefix",
",",
"uri",
"=",
"qname",
"[",
"camelize",
"(",
"local_part",
")",
",",
"prefix",
",",
"uri",
"]",
".",
"compact",
"end"
] | given an exploded qname, camelize the local_part | [
"given",
"an",
"exploded",
"qname",
"camelize",
"the",
"local_part"
] | 3f18671a25750b9045714af587c1989679f84de8 | https://github.com/trampoline/rews/blob/3f18671a25750b9045714af587c1989679f84de8/lib/rews/util.rb#L84-L87 | train |
trampoline/rews | lib/rews/util.rb | Rews.Util.with_error_check | def with_error_check(client, *response_msg_keys)
raise "no block" if !block_given?
begin
response = yield
hash_response = response.to_hash
statuses = hash_response.fetch_in(*response_msg_keys)
if statuses.is_a?(Array)
all_statuses = statuses
else
all_statuses = [statuses]
end
errors = all_statuses.map{|s| single_error_check(client, s)}.compact
rescue Exception=>e
Rews.log{|logger| logger.warn(e)}
tag_exception(e, :savon_response=>response)
raise e
end
raise Error.new(errors.join("\n")) if !errors.empty?
statuses
end | ruby | def with_error_check(client, *response_msg_keys)
raise "no block" if !block_given?
begin
response = yield
hash_response = response.to_hash
statuses = hash_response.fetch_in(*response_msg_keys)
if statuses.is_a?(Array)
all_statuses = statuses
else
all_statuses = [statuses]
end
errors = all_statuses.map{|s| single_error_check(client, s)}.compact
rescue Exception=>e
Rews.log{|logger| logger.warn(e)}
tag_exception(e, :savon_response=>response)
raise e
end
raise Error.new(errors.join("\n")) if !errors.empty?
statuses
end | [
"def",
"with_error_check",
"(",
"client",
",",
"*",
"response_msg_keys",
")",
"raise",
"\"no block\"",
"if",
"!",
"block_given?",
"begin",
"response",
"=",
"yield",
"hash_response",
"=",
"response",
".",
"to_hash",
"statuses",
"=",
"hash_response",
".",
"fetch_in",
"(",
"*",
"response_msg_keys",
")",
"if",
"statuses",
".",
"is_a?",
"(",
"Array",
")",
"all_statuses",
"=",
"statuses",
"else",
"all_statuses",
"=",
"[",
"statuses",
"]",
"end",
"errors",
"=",
"all_statuses",
".",
"map",
"{",
"|",
"s",
"|",
"single_error_check",
"(",
"client",
",",
"s",
")",
"}",
".",
"compact",
"rescue",
"Exception",
"=>",
"e",
"Rews",
".",
"log",
"{",
"|",
"logger",
"|",
"logger",
".",
"warn",
"(",
"e",
")",
"}",
"tag_exception",
"(",
"e",
",",
":savon_response",
"=>",
"response",
")",
"raise",
"e",
"end",
"raise",
"Error",
".",
"new",
"(",
"errors",
".",
"join",
"(",
"\"\\n\"",
")",
")",
"if",
"!",
"errors",
".",
"empty?",
"statuses",
"end"
] | check the response codes of an Exchange Web Services request.
the supplied block makes a SOAP request, and the response is parsed
out and checked | [
"check",
"the",
"response",
"codes",
"of",
"an",
"Exchange",
"Web",
"Services",
"request",
".",
"the",
"supplied",
"block",
"makes",
"a",
"SOAP",
"request",
"and",
"the",
"response",
"is",
"parsed",
"out",
"and",
"checked"
] | 3f18671a25750b9045714af587c1989679f84de8 | https://github.com/trampoline/rews/blob/3f18671a25750b9045714af587c1989679f84de8/lib/rews/util.rb#L107-L130 | train |
trampoline/rews | lib/rews/util.rb | Rews.Util.single_error_check | def single_error_check(client, status)
begin
response_class = status[:response_class]
rescue
raise "no response_class found: #{status.inspect}" if !response_class
end
if status[:response_class] == "Error"
return "#{status[:response_code]} - #{status[:message_text]}"
elsif status[:response_class] == "Warning"
Rews.log{|logger| logger.warn("#{status[:response_code]} - #{status[:message_text]}")}
end
end | ruby | def single_error_check(client, status)
begin
response_class = status[:response_class]
rescue
raise "no response_class found: #{status.inspect}" if !response_class
end
if status[:response_class] == "Error"
return "#{status[:response_code]} - #{status[:message_text]}"
elsif status[:response_class] == "Warning"
Rews.log{|logger| logger.warn("#{status[:response_code]} - #{status[:message_text]}")}
end
end | [
"def",
"single_error_check",
"(",
"client",
",",
"status",
")",
"begin",
"response_class",
"=",
"status",
"[",
":response_class",
"]",
"rescue",
"raise",
"\"no response_class found: #{status.inspect}\"",
"if",
"!",
"response_class",
"end",
"if",
"status",
"[",
":response_class",
"]",
"==",
"\"Error\"",
"return",
"\"#{status[:response_code]} - #{status[:message_text]}\"",
"elsif",
"status",
"[",
":response_class",
"]",
"==",
"\"Warning\"",
"Rews",
".",
"log",
"{",
"|",
"logger",
"|",
"logger",
".",
"warn",
"(",
"\"#{status[:response_code]} - #{status[:message_text]}\"",
")",
"}",
"end",
"end"
] | check the status of the response of a single part of a multi-part request | [
"check",
"the",
"status",
"of",
"the",
"response",
"of",
"a",
"single",
"part",
"of",
"a",
"multi",
"-",
"part",
"request"
] | 3f18671a25750b9045714af587c1989679f84de8 | https://github.com/trampoline/rews/blob/3f18671a25750b9045714af587c1989679f84de8/lib/rews/util.rb#L133-L145 | train |
blambeau/finitio-rb | lib/finitio/support/attribute.rb | Finitio.Attribute.fetch_on | def fetch_on(arg, &bl)
unless arg.respond_to?(:fetch)
raise ArgumentError, "Object responding to `fetch` expected"
end
arg.fetch(name) do
arg.fetch(name.to_s, &bl)
end
end | ruby | def fetch_on(arg, &bl)
unless arg.respond_to?(:fetch)
raise ArgumentError, "Object responding to `fetch` expected"
end
arg.fetch(name) do
arg.fetch(name.to_s, &bl)
end
end | [
"def",
"fetch_on",
"(",
"arg",
",",
"&",
"bl",
")",
"unless",
"arg",
".",
"respond_to?",
"(",
":fetch",
")",
"raise",
"ArgumentError",
",",
"\"Object responding to `fetch` expected\"",
"end",
"arg",
".",
"fetch",
"(",
"name",
")",
"do",
"arg",
".",
"fetch",
"(",
"name",
".",
"to_s",
",",
"&",
"bl",
")",
"end",
"end"
] | Fetch the attribute on `arg`, which is expected to be a Hash object.
This method allows working with ruby hashes having either Symbols or
Strings as keys. It ensures that no Symbol is created by the rest of the
code, since this would provide a DoS attack vector under MRI. | [
"Fetch",
"the",
"attribute",
"on",
"arg",
"which",
"is",
"expected",
"to",
"be",
"a",
"Hash",
"object",
"."
] | c07a3887a6af26b2ed1eb3c50b101e210d3d8b40 | https://github.com/blambeau/finitio-rb/blob/c07a3887a6af26b2ed1eb3c50b101e210d3d8b40/lib/finitio/support/attribute.rb#L35-L42 | train |
tanalab2/ya_lorem_ja | lib/ya_lorem_ja/word_resource.rb | YaLoremJa.WordResource.sentences | def sentences(total)
list = []
total.times do
word_count = rand(word_count_range_in_a_sentence)
sentence_len = word_count.times.inject(0){ |sum| sum + rand(char_count_range_in_a_word) }
sentence_key = bsearch(sentence_map_keys, sentence_len)
unless sentence_key
sentence_key = sentence_map.keys.min
end
list << sentence_map[sentence_key].sample
end
return list.join(@line_break)
end | ruby | def sentences(total)
list = []
total.times do
word_count = rand(word_count_range_in_a_sentence)
sentence_len = word_count.times.inject(0){ |sum| sum + rand(char_count_range_in_a_word) }
sentence_key = bsearch(sentence_map_keys, sentence_len)
unless sentence_key
sentence_key = sentence_map.keys.min
end
list << sentence_map[sentence_key].sample
end
return list.join(@line_break)
end | [
"def",
"sentences",
"(",
"total",
")",
"list",
"=",
"[",
"]",
"total",
".",
"times",
"do",
"word_count",
"=",
"rand",
"(",
"word_count_range_in_a_sentence",
")",
"sentence_len",
"=",
"word_count",
".",
"times",
".",
"inject",
"(",
"0",
")",
"{",
"|",
"sum",
"|",
"sum",
"+",
"rand",
"(",
"char_count_range_in_a_word",
")",
"}",
"sentence_key",
"=",
"bsearch",
"(",
"sentence_map_keys",
",",
"sentence_len",
")",
"unless",
"sentence_key",
"sentence_key",
"=",
"sentence_map",
".",
"keys",
".",
"min",
"end",
"list",
"<<",
"sentence_map",
"[",
"sentence_key",
"]",
".",
"sample",
"end",
"return",
"list",
".",
"join",
"(",
"@line_break",
")",
"end"
] | return rondom sentences from word resource
@param [Fixnum] total count of sentence
@return [String] words | [
"return",
"rondom",
"sentences",
"from",
"word",
"resource"
] | 9f2e36ab3f0543492d0bb9918431105b73e90c8e | https://github.com/tanalab2/ya_lorem_ja/blob/9f2e36ab3f0543492d0bb9918431105b73e90c8e/lib/ya_lorem_ja/word_resource.rb#L113-L125 | train |
Antti/skyper | lib/skyper/skype_object.rb | Skyper.SkypeObject.set_property | def set_property(property, value)
cmd = ["SET",self.class.object_name, id, property, value].compact.join(" ")
Skyper::Skype.send_command(cmd)
end | ruby | def set_property(property, value)
cmd = ["SET",self.class.object_name, id, property, value].compact.join(" ")
Skyper::Skype.send_command(cmd)
end | [
"def",
"set_property",
"(",
"property",
",",
"value",
")",
"cmd",
"=",
"[",
"\"SET\"",
",",
"self",
".",
"class",
".",
"object_name",
",",
"id",
",",
"property",
",",
"value",
"]",
".",
"compact",
".",
"join",
"(",
"\" \"",
")",
"Skyper",
"::",
"Skype",
".",
"send_command",
"(",
"cmd",
")",
"end"
] | Invokes SET command for a given object with id, property and value
@param[String] property Property to be set
@param[String] value Property value | [
"Invokes",
"SET",
"command",
"for",
"a",
"given",
"object",
"with",
"id",
"property",
"and",
"value"
] | 16c1c19a485be24376acfa0b7e0a7775ec16b30c | https://github.com/Antti/skyper/blob/16c1c19a485be24376acfa0b7e0a7775ec16b30c/lib/skyper/skype_object.rb#L26-L29 | train |
blambeau/finitio-rb | lib/finitio/support/type_factory.rb | Finitio.TypeFactory.subtype | def subtype(super_type, constraints = nil, name = nil, metadata = nil, &bl)
super_type = type(super_type)
constraints = constraints(constraints, &bl)
name = name(name)
meta = metadata(metadata)
SubType.new(super_type, constraints, name, metadata)
end | ruby | def subtype(super_type, constraints = nil, name = nil, metadata = nil, &bl)
super_type = type(super_type)
constraints = constraints(constraints, &bl)
name = name(name)
meta = metadata(metadata)
SubType.new(super_type, constraints, name, metadata)
end | [
"def",
"subtype",
"(",
"super_type",
",",
"constraints",
"=",
"nil",
",",
"name",
"=",
"nil",
",",
"metadata",
"=",
"nil",
",",
"&",
"bl",
")",
"super_type",
"=",
"type",
"(",
"super_type",
")",
"constraints",
"=",
"constraints",
"(",
"constraints",
",",
"&",
"bl",
")",
"name",
"=",
"name",
"(",
"name",
")",
"meta",
"=",
"metadata",
"(",
"metadata",
")",
"SubType",
".",
"new",
"(",
"super_type",
",",
"constraints",
",",
"name",
",",
"metadata",
")",
"end"
] | Sub and union | [
"Sub",
"and",
"union"
] | c07a3887a6af26b2ed1eb3c50b101e210d3d8b40 | https://github.com/blambeau/finitio-rb/blob/c07a3887a6af26b2ed1eb3c50b101e210d3d8b40/lib/finitio/support/type_factory.rb#L192-L199 | train |
blambeau/finitio-rb | lib/finitio/support/type_factory.rb | Finitio.TypeFactory.tuple | def tuple(heading, name = nil, metadata = nil)
heading = heading(heading)
name = name(name)
meta = metadata(metadata)
TupleType.new(heading, name, meta)
end | ruby | def tuple(heading, name = nil, metadata = nil)
heading = heading(heading)
name = name(name)
meta = metadata(metadata)
TupleType.new(heading, name, meta)
end | [
"def",
"tuple",
"(",
"heading",
",",
"name",
"=",
"nil",
",",
"metadata",
"=",
"nil",
")",
"heading",
"=",
"heading",
"(",
"heading",
")",
"name",
"=",
"name",
"(",
"name",
")",
"meta",
"=",
"metadata",
"(",
"metadata",
")",
"TupleType",
".",
"new",
"(",
"heading",
",",
"name",
",",
"meta",
")",
"end"
] | Tuples and relations | [
"Tuples",
"and",
"relations"
] | c07a3887a6af26b2ed1eb3c50b101e210d3d8b40 | https://github.com/blambeau/finitio-rb/blob/c07a3887a6af26b2ed1eb3c50b101e210d3d8b40/lib/finitio/support/type_factory.rb#L243-L249 | train |
tanalab2/ya_lorem_ja | lib/ya_lorem_ja.rb | YaLoremJa.Lorem.image | def image(size, options={})
domain = options[:domain] || 'http://placehold.it'
src = "#{domain}/#{size}"
hex = %w(a b c d e f 0 1 2 3 4 5 6 7 8 9)
background_color = options[:background_color]
color = options[:color]
if options[:random_color]
background_color = hex.shuffle[0...6].join
color = hex.shuffle[0...6].join
end
src << "/#{background_color.sub(/^#/, '')}" if background_color
src << '/ccc' if background_color.nil? && color
src << "/#{color.sub(/^#/, '')}" if color
src << "&text=#{Rack::Utils.escape(options[:text])}" if options[:text]
src
end | ruby | def image(size, options={})
domain = options[:domain] || 'http://placehold.it'
src = "#{domain}/#{size}"
hex = %w(a b c d e f 0 1 2 3 4 5 6 7 8 9)
background_color = options[:background_color]
color = options[:color]
if options[:random_color]
background_color = hex.shuffle[0...6].join
color = hex.shuffle[0...6].join
end
src << "/#{background_color.sub(/^#/, '')}" if background_color
src << '/ccc' if background_color.nil? && color
src << "/#{color.sub(/^#/, '')}" if color
src << "&text=#{Rack::Utils.escape(options[:text])}" if options[:text]
src
end | [
"def",
"image",
"(",
"size",
",",
"options",
"=",
"{",
"}",
")",
"domain",
"=",
"options",
"[",
":domain",
"]",
"||",
"'http://placehold.it'",
"src",
"=",
"\"#{domain}/#{size}\"",
"hex",
"=",
"%w(",
"a",
"b",
"c",
"d",
"e",
"f",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
")",
"background_color",
"=",
"options",
"[",
":background_color",
"]",
"color",
"=",
"options",
"[",
":color",
"]",
"if",
"options",
"[",
":random_color",
"]",
"background_color",
"=",
"hex",
".",
"shuffle",
"[",
"0",
"...",
"6",
"]",
".",
"join",
"color",
"=",
"hex",
".",
"shuffle",
"[",
"0",
"...",
"6",
"]",
".",
"join",
"end",
"src",
"<<",
"\"/#{background_color.sub(/^#/, '')}\"",
"if",
"background_color",
"src",
"<<",
"'/ccc'",
"if",
"background_color",
".",
"nil?",
"&&",
"color",
"src",
"<<",
"\"/#{color.sub(/^#/, '')}\"",
"if",
"color",
"src",
"<<",
"\"&text=#{Rack::Utils.escape(options[:text])}\"",
"if",
"options",
"[",
":text",
"]",
"src",
"end"
] | Get a placeholder image, using placehold.it by default
@param [String] size
@param [Hash] options
@return [String] | [
"Get",
"a",
"placeholder",
"image",
"using",
"placehold",
".",
"it",
"by",
"default"
] | 9f2e36ab3f0543492d0bb9918431105b73e90c8e | https://github.com/tanalab2/ya_lorem_ja/blob/9f2e36ab3f0543492d0bb9918431105b73e90c8e/lib/ya_lorem_ja.rb#L142-L160 | train |
orzFly/ruby-ripple-rest | lib/ripple-rest/schemas.rb | RippleRest.AccountSettings.save | def save
raise ArgumentError.new("Account is missing.") unless account
account.require_secret
hash = {}
hash["settings"] = to_hash
hash["secret"] = account.secret
RippleRest.post "v1/accounts/#{account.address}/settings", hash
end | ruby | def save
raise ArgumentError.new("Account is missing.") unless account
account.require_secret
hash = {}
hash["settings"] = to_hash
hash["secret"] = account.secret
RippleRest.post "v1/accounts/#{account.address}/settings", hash
end | [
"def",
"save",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"Account is missing.\"",
")",
"unless",
"account",
"account",
".",
"require_secret",
"hash",
"=",
"{",
"}",
"hash",
"[",
"\"settings\"",
"]",
"=",
"to_hash",
"hash",
"[",
"\"secret\"",
"]",
"=",
"account",
".",
"secret",
"RippleRest",
".",
"post",
"\"v1/accounts/#{account.address}/settings\"",
",",
"hash",
"end"
] | Save the account settings
@raise [ArgumentError] if secret is missing from the Account object
@raise [RippleRestError] if RippleRest server returns an error
@raise [ProtocolError] if protocol is wrong or network is down
@return [void] | [
"Save",
"the",
"account",
"settings"
] | 86c9a49c07fb2068d0bbe0edb2490b65efb6972d | https://github.com/orzFly/ruby-ripple-rest/blob/86c9a49c07fb2068d0bbe0edb2490b65efb6972d/lib/ripple-rest/schemas.rb#L11-L21 | train |
orzFly/ruby-ripple-rest | lib/ripple-rest/schemas.rb | RippleRest.Payment.submit | def submit
@account.require_secret
hash = {}
hash["payment"] = self.to_hash
hash["secret"] = @account.secret
hash["client_resource_id"] = client_resource_id = RippleRest.next_uuid
source_account = self.to_hash[:source_account]
RippleRest.post("v1/accounts/#{source_account}/payments", hash)["client_resource_id"]
end | ruby | def submit
@account.require_secret
hash = {}
hash["payment"] = self.to_hash
hash["secret"] = @account.secret
hash["client_resource_id"] = client_resource_id = RippleRest.next_uuid
source_account = self.to_hash[:source_account]
RippleRest.post("v1/accounts/#{source_account}/payments", hash)["client_resource_id"]
end | [
"def",
"submit",
"@account",
".",
"require_secret",
"hash",
"=",
"{",
"}",
"hash",
"[",
"\"payment\"",
"]",
"=",
"self",
".",
"to_hash",
"hash",
"[",
"\"secret\"",
"]",
"=",
"@account",
".",
"secret",
"hash",
"[",
"\"client_resource_id\"",
"]",
"=",
"client_resource_id",
"=",
"RippleRest",
".",
"next_uuid",
"source_account",
"=",
"self",
".",
"to_hash",
"[",
":source_account",
"]",
"RippleRest",
".",
"post",
"(",
"\"v1/accounts/#{source_account}/payments\"",
",",
"hash",
")",
"[",
"\"client_resource_id\"",
"]",
"end"
] | Submits a payment
@return [String] Client resource ID
@raise [ArgumentError] if secret is missing from the Account object
@raise [RippleRestError] if RippleRest server returns an error
@raise [ProtocolError] if protocol is wrong or network is down | [
"Submits",
"a",
"payment"
] | 86c9a49c07fb2068d0bbe0edb2490b65efb6972d | https://github.com/orzFly/ruby-ripple-rest/blob/86c9a49c07fb2068d0bbe0edb2490b65efb6972d/lib/ripple-rest/schemas.rb#L69-L79 | train |
trampoline/rews | lib/rews/item.rb | Rews.Item.read_items | def read_items(client, items)
return [] if !items
items.map do |item_class,items_of_class|
items_of_class = [items_of_class] if !items_of_class.is_a?(Array)
items_of_class.map do |item|
Item.new(client, item_class, item)
end
end.flatten
end | ruby | def read_items(client, items)
return [] if !items
items.map do |item_class,items_of_class|
items_of_class = [items_of_class] if !items_of_class.is_a?(Array)
items_of_class.map do |item|
Item.new(client, item_class, item)
end
end.flatten
end | [
"def",
"read_items",
"(",
"client",
",",
"items",
")",
"return",
"[",
"]",
"if",
"!",
"items",
"items",
".",
"map",
"do",
"|",
"item_class",
",",
"items_of_class",
"|",
"items_of_class",
"=",
"[",
"items_of_class",
"]",
"if",
"!",
"items_of_class",
".",
"is_a?",
"(",
"Array",
")",
"items_of_class",
".",
"map",
"do",
"|",
"item",
"|",
"Item",
".",
"new",
"(",
"client",
",",
"item_class",
",",
"item",
")",
"end",
"end",
".",
"flatten",
"end"
] | return a list of Item objects given a hash formed from an Items element | [
"return",
"a",
"list",
"of",
"Item",
"objects",
"given",
"a",
"hash",
"formed",
"from",
"an",
"Items",
"element"
] | 3f18671a25750b9045714af587c1989679f84de8 | https://github.com/trampoline/rews/blob/3f18671a25750b9045714af587c1989679f84de8/lib/rews/item.rb#L6-L14 | train |
trampoline/rews | lib/rews/item.rb | Rews.Item.read_get_item_response_messages | def read_get_item_response_messages(client, get_item_response_messages)
get_item_response_messages = [get_item_response_messages] if !get_item_response_messages.is_a?(Array)
items = get_item_response_messages.map do |girm|
read_items(client, girm[:items])
end.flatten
end | ruby | def read_get_item_response_messages(client, get_item_response_messages)
get_item_response_messages = [get_item_response_messages] if !get_item_response_messages.is_a?(Array)
items = get_item_response_messages.map do |girm|
read_items(client, girm[:items])
end.flatten
end | [
"def",
"read_get_item_response_messages",
"(",
"client",
",",
"get_item_response_messages",
")",
"get_item_response_messages",
"=",
"[",
"get_item_response_messages",
"]",
"if",
"!",
"get_item_response_messages",
".",
"is_a?",
"(",
"Array",
")",
"items",
"=",
"get_item_response_messages",
".",
"map",
"do",
"|",
"girm",
"|",
"read_items",
"(",
"client",
",",
"girm",
"[",
":items",
"]",
")",
"end",
".",
"flatten",
"end"
] | return a list of Item objects from a list of GetItemResponseMessages | [
"return",
"a",
"list",
"of",
"Item",
"objects",
"from",
"a",
"list",
"of",
"GetItemResponseMessages"
] | 3f18671a25750b9045714af587c1989679f84de8 | https://github.com/trampoline/rews/blob/3f18671a25750b9045714af587c1989679f84de8/lib/rews/item.rb#L17-L22 | train |
dpla/KriKri | lib/krikri/enrichments/dcmi_type_map.rb | Krikri::Enrichments.DcmiTypeMap.most_similar | def most_similar(value, threshold = 0.5)
@white ||= Text::WhiteSimilarity.new
result = @map.max_by { |str, _| @white.similarity(value, str) }
return result[1] if @white.similarity(value, result.first) > threshold
nil
end | ruby | def most_similar(value, threshold = 0.5)
@white ||= Text::WhiteSimilarity.new
result = @map.max_by { |str, _| @white.similarity(value, str) }
return result[1] if @white.similarity(value, result.first) > threshold
nil
end | [
"def",
"most_similar",
"(",
"value",
",",
"threshold",
"=",
"0.5",
")",
"@white",
"||=",
"Text",
"::",
"WhiteSimilarity",
".",
"new",
"result",
"=",
"@map",
".",
"max_by",
"{",
"|",
"str",
",",
"_",
"|",
"@white",
".",
"similarity",
"(",
"value",
",",
"str",
")",
"}",
"return",
"result",
"[",
"1",
"]",
"if",
"@white",
".",
"similarity",
"(",
"value",
",",
"result",
".",
"first",
")",
">",
"threshold",
"nil",
"end"
] | Performs White Similarity comparison against the keys, and gives the
value of the closest match.
@param value [String] a string value to compare to the hash map keys.
@param threshold [Float] the value at which a string is considered to
be a match
@return [RDF::Vocabulary::Term, nil] the closest DCMI type match, or `nil`
if none is sufficiently close
@see Text::WhiteSimilarity
@see http://www.catalysoft.com/articles/strikeamatch.html article defining
the White Similarity algorithm
@todo consider text similarity algorithms/strategies and move text
matching to a utility and behind a Facade interface. | [
"Performs",
"White",
"Similarity",
"comparison",
"against",
"the",
"keys",
"and",
"gives",
"the",
"value",
"of",
"the",
"closest",
"match",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/enrichments/dcmi_type_map.rb#L121-L127 | train |
mariochavez/restful | lib/restful/actions.rb | Restful.Actions.index | def index(options = {}, &block)
respond_with(collection, options, &block) if stale?(collection, last_modified: collection.maximum(:updated_at))
end | ruby | def index(options = {}, &block)
respond_with(collection, options, &block) if stale?(collection, last_modified: collection.maximum(:updated_at))
end | [
"def",
"index",
"(",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"respond_with",
"(",
"collection",
",",
"options",
",",
"&",
"block",
")",
"if",
"stale?",
"(",
"collection",
",",
"last_modified",
":",
"collection",
".",
"maximum",
"(",
":updated_at",
")",
")",
"end"
] | index action, this set a collection of objects to an instance variable
which can be accessed from the view using the collection helper method.
The instance variable name is a pluralization of the model name defined
in the restful macro. | [
"index",
"action",
"this",
"set",
"a",
"collection",
"of",
"objects",
"to",
"an",
"instance",
"variable",
"which",
"can",
"be",
"accessed",
"from",
"the",
"view",
"using",
"the",
"collection",
"helper",
"method",
".",
"The",
"instance",
"variable",
"name",
"is",
"a",
"pluralization",
"of",
"the",
"model",
"name",
"defined",
"in",
"the",
"restful",
"macro",
"."
] | 4b421ef6b448a8dfbd72dac183561fe829095aef | https://github.com/mariochavez/restful/blob/4b421ef6b448a8dfbd72dac183561fe829095aef/lib/restful/actions.rb#L72-L74 | train |
mariochavez/restful | lib/restful/actions.rb | Restful.Actions.create | def create(options = {}, &block)
object = get_resource_ivar || create_resource
options[:location] = collection_path if object.errors.empty?
respond_with_dual(object, options, &block)
end | ruby | def create(options = {}, &block)
object = get_resource_ivar || create_resource
options[:location] = collection_path if object.errors.empty?
respond_with_dual(object, options, &block)
end | [
"def",
"create",
"(",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"object",
"=",
"get_resource_ivar",
"||",
"create_resource",
"options",
"[",
":location",
"]",
"=",
"collection_path",
"if",
"object",
".",
"errors",
".",
"empty?",
"respond_with_dual",
"(",
"object",
",",
"options",
",",
"&",
"block",
")",
"end"
] | create action, creates a new object off the received params and sets an
instance variable if record is saved then a redirect to index action is
made.
If record fail to be saved, the new form is renderd and the instance
variable can be accessed from the view using the resource
helper method. The instance variable is named after the model name
defined in the restful macro. | [
"create",
"action",
"creates",
"a",
"new",
"object",
"off",
"the",
"received",
"params",
"and",
"sets",
"an",
"instance",
"variable",
"if",
"record",
"is",
"saved",
"then",
"a",
"redirect",
"to",
"index",
"action",
"is",
"made",
"."
] | 4b421ef6b448a8dfbd72dac183561fe829095aef | https://github.com/mariochavez/restful/blob/4b421ef6b448a8dfbd72dac183561fe829095aef/lib/restful/actions.rb#L95-L101 | train |
dpla/KriKri | lib/krikri/harvesters/primo_harvester.rb | Krikri::Harvesters.PrimoHarvester.enumerate_records | def enumerate_records(xml)
doc = Nokogiri::XML(xml)
doc.root.add_namespace_definition('nmbib', PRIMO_NS)
doc.xpath('//sear:DOC').lazy.map do |record|
identifier = record.xpath('./nmbib:PrimoNMBib/nmbib:record/' \
'nmbib:control/nmbib:recordid')
.first.text
record = record.dup
record.add_namespace_definition('sear', SEAR_NS)
@record_class.build(mint_id(identifier), record.to_xml)
end
end | ruby | def enumerate_records(xml)
doc = Nokogiri::XML(xml)
doc.root.add_namespace_definition('nmbib', PRIMO_NS)
doc.xpath('//sear:DOC').lazy.map do |record|
identifier = record.xpath('./nmbib:PrimoNMBib/nmbib:record/' \
'nmbib:control/nmbib:recordid')
.first.text
record = record.dup
record.add_namespace_definition('sear', SEAR_NS)
@record_class.build(mint_id(identifier), record.to_xml)
end
end | [
"def",
"enumerate_records",
"(",
"xml",
")",
"doc",
"=",
"Nokogiri",
"::",
"XML",
"(",
"xml",
")",
"doc",
".",
"root",
".",
"add_namespace_definition",
"(",
"'nmbib'",
",",
"PRIMO_NS",
")",
"doc",
".",
"xpath",
"(",
"'//sear:DOC'",
")",
".",
"lazy",
".",
"map",
"do",
"|",
"record",
"|",
"identifier",
"=",
"record",
".",
"xpath",
"(",
"'./nmbib:PrimoNMBib/nmbib:record/'",
"'nmbib:control/nmbib:recordid'",
")",
".",
"first",
".",
"text",
"record",
"=",
"record",
".",
"dup",
"record",
".",
"add_namespace_definition",
"(",
"'sear'",
",",
"SEAR_NS",
")",
"@record_class",
".",
"build",
"(",
"mint_id",
"(",
"identifier",
")",
",",
"record",
".",
"to_xml",
")",
"end",
"end"
] | Extract a page's worth of records from a Primo XML search result.
@param xml [String] an XML document returned from a Primo search
@return [Array] an array of @record_class instances | [
"Extract",
"a",
"page",
"s",
"worth",
"of",
"records",
"from",
"a",
"Primo",
"XML",
"search",
"result",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/harvesters/primo_harvester.rb#L91-L104 | train |
lambda2/rice_cooker | lib/rice_cooker/base/helpers.rb | RiceCooker.Helpers.sortable_fields_for | def sortable_fields_for(model)
if model.respond_to?(:sortable_fields)
model.sortable_fields.map(&:to_sym)
elsif model.respond_to?(:column_names)
model.column_names.map(&:to_sym)
else
[]
end
end | ruby | def sortable_fields_for(model)
if model.respond_to?(:sortable_fields)
model.sortable_fields.map(&:to_sym)
elsif model.respond_to?(:column_names)
model.column_names.map(&:to_sym)
else
[]
end
end | [
"def",
"sortable_fields_for",
"(",
"model",
")",
"if",
"model",
".",
"respond_to?",
"(",
":sortable_fields",
")",
"model",
".",
"sortable_fields",
".",
"map",
"(",
"&",
":to_sym",
")",
"elsif",
"model",
".",
"respond_to?",
"(",
":column_names",
")",
"model",
".",
"column_names",
".",
"map",
"(",
"&",
":to_sym",
")",
"else",
"[",
"]",
"end",
"end"
] | Overridable method for available sortable fields | [
"Overridable",
"method",
"for",
"available",
"sortable",
"fields"
] | b7ce285d3bd76ae979111f0374c5a43815473332 | https://github.com/lambda2/rice_cooker/blob/b7ce285d3bd76ae979111f0374c5a43815473332/lib/rice_cooker/base/helpers.rb#L30-L38 | train |
lambda2/rice_cooker | lib/rice_cooker/base/helpers.rb | RiceCooker.Helpers.filterable_fields_for | def filterable_fields_for(model)
if model.respond_to?(:filterable_fields)
model.filterable_fields.map(&:to_sym)
elsif model.respond_to?(:column_names)
model.column_names.map(&:to_sym)
else
[]
end
end | ruby | def filterable_fields_for(model)
if model.respond_to?(:filterable_fields)
model.filterable_fields.map(&:to_sym)
elsif model.respond_to?(:column_names)
model.column_names.map(&:to_sym)
else
[]
end
end | [
"def",
"filterable_fields_for",
"(",
"model",
")",
"if",
"model",
".",
"respond_to?",
"(",
":filterable_fields",
")",
"model",
".",
"filterable_fields",
".",
"map",
"(",
"&",
":to_sym",
")",
"elsif",
"model",
".",
"respond_to?",
"(",
":column_names",
")",
"model",
".",
"column_names",
".",
"map",
"(",
"&",
":to_sym",
")",
"else",
"[",
"]",
"end",
"end"
] | Overridable method for available filterable fields | [
"Overridable",
"method",
"for",
"available",
"filterable",
"fields"
] | b7ce285d3bd76ae979111f0374c5a43815473332 | https://github.com/lambda2/rice_cooker/blob/b7ce285d3bd76ae979111f0374c5a43815473332/lib/rice_cooker/base/helpers.rb#L41-L49 | train |
schrodingersbox/status_cat | app/helpers/status_cat/status_helper.rb | StatusCat.StatusHelper.status_report | def status_report(checkers)
format, format_length = status_report_format(checkers)
header = status_report_header(format)
length = [format_length, header.length].max
separator = ('-' * length) + "\n"
result = separator + header + separator
checkers.each { |checker| result << checker.to_s(format) }
result << separator
return result
end | ruby | def status_report(checkers)
format, format_length = status_report_format(checkers)
header = status_report_header(format)
length = [format_length, header.length].max
separator = ('-' * length) + "\n"
result = separator + header + separator
checkers.each { |checker| result << checker.to_s(format) }
result << separator
return result
end | [
"def",
"status_report",
"(",
"checkers",
")",
"format",
",",
"format_length",
"=",
"status_report_format",
"(",
"checkers",
")",
"header",
"=",
"status_report_header",
"(",
"format",
")",
"length",
"=",
"[",
"format_length",
",",
"header",
".",
"length",
"]",
".",
"max",
"separator",
"=",
"(",
"'-'",
"*",
"length",
")",
"+",
"\"\\n\"",
"result",
"=",
"separator",
"+",
"header",
"+",
"separator",
"checkers",
".",
"each",
"{",
"|",
"checker",
"|",
"result",
"<<",
"checker",
".",
"to_s",
"(",
"format",
")",
"}",
"result",
"<<",
"separator",
"return",
"result",
"end"
] | Constructs a text status report | [
"Constructs",
"a",
"text",
"status",
"report"
] | af56e3e79999d4a608ab6fe682e0a7c76becd6ca | https://github.com/schrodingersbox/status_cat/blob/af56e3e79999d4a608ab6fe682e0a7c76becd6ca/app/helpers/status_cat/status_helper.rb#L56-L67 | train |
schrodingersbox/status_cat | app/helpers/status_cat/status_helper.rb | StatusCat.StatusHelper.status_report_format | def status_report_format(checkers)
name_max = status_report_format_max_length(checkers, :name)
value_max = status_report_format_max_length(checkers, :value)
status_max = status_report_format_max_length(checkers, :status)
format = "%#{name_max}s | %#{value_max}s | %#{status_max}s\n"
length = name_max + 3 + value_max + 3 + status_max
return format, length
end | ruby | def status_report_format(checkers)
name_max = status_report_format_max_length(checkers, :name)
value_max = status_report_format_max_length(checkers, :value)
status_max = status_report_format_max_length(checkers, :status)
format = "%#{name_max}s | %#{value_max}s | %#{status_max}s\n"
length = name_max + 3 + value_max + 3 + status_max
return format, length
end | [
"def",
"status_report_format",
"(",
"checkers",
")",
"name_max",
"=",
"status_report_format_max_length",
"(",
"checkers",
",",
":name",
")",
"value_max",
"=",
"status_report_format_max_length",
"(",
"checkers",
",",
":value",
")",
"status_max",
"=",
"status_report_format_max_length",
"(",
"checkers",
",",
":status",
")",
"format",
"=",
"\"%#{name_max}s | %#{value_max}s | %#{status_max}s\\n\"",
"length",
"=",
"name_max",
"+",
"3",
"+",
"value_max",
"+",
"3",
"+",
"status_max",
"return",
"format",
",",
"length",
"end"
] | Generate a format string to justify all values | [
"Generate",
"a",
"format",
"string",
"to",
"justify",
"all",
"values"
] | af56e3e79999d4a608ab6fe682e0a7c76becd6ca | https://github.com/schrodingersbox/status_cat/blob/af56e3e79999d4a608ab6fe682e0a7c76becd6ca/app/helpers/status_cat/status_helper.rb#L71-L80 | train |
schrodingersbox/status_cat | app/helpers/status_cat/status_helper.rb | StatusCat.StatusHelper.status_report_header | def status_report_header(format = StatusCat::Checkers::Base::FORMAT)
name = I18n.t(:name, scope: :status_cat)
value = I18n.t(:value, scope: :status_cat)
status = I18n.t(:status, scope: :status_cat)
return format(format, name, value, status)
end | ruby | def status_report_header(format = StatusCat::Checkers::Base::FORMAT)
name = I18n.t(:name, scope: :status_cat)
value = I18n.t(:value, scope: :status_cat)
status = I18n.t(:status, scope: :status_cat)
return format(format, name, value, status)
end | [
"def",
"status_report_header",
"(",
"format",
"=",
"StatusCat",
"::",
"Checkers",
"::",
"Base",
"::",
"FORMAT",
")",
"name",
"=",
"I18n",
".",
"t",
"(",
":name",
",",
"scope",
":",
":status_cat",
")",
"value",
"=",
"I18n",
".",
"t",
"(",
":value",
",",
"scope",
":",
":status_cat",
")",
"status",
"=",
"I18n",
".",
"t",
"(",
":status",
",",
"scope",
":",
":status_cat",
")",
"return",
"format",
"(",
"format",
",",
"name",
",",
"value",
",",
"status",
")",
"end"
] | Generate a header string | [
"Generate",
"a",
"header",
"string"
] | af56e3e79999d4a608ab6fe682e0a7c76becd6ca | https://github.com/schrodingersbox/status_cat/blob/af56e3e79999d4a608ab6fe682e0a7c76becd6ca/app/helpers/status_cat/status_helper.rb#L88-L93 | train |
tlux/vnstat-ruby | lib/vnstat/parser.rb | Vnstat.Parser.extract_month_from_xml_element | def extract_month_from_xml_element(element)
month = element.xpath('date/month').text.to_i
year = element.xpath('date/year').text.to_i
[year, month]
end | ruby | def extract_month_from_xml_element(element)
month = element.xpath('date/month').text.to_i
year = element.xpath('date/year').text.to_i
[year, month]
end | [
"def",
"extract_month_from_xml_element",
"(",
"element",
")",
"month",
"=",
"element",
".",
"xpath",
"(",
"'date/month'",
")",
".",
"text",
".",
"to_i",
"year",
"=",
"element",
".",
"xpath",
"(",
"'date/year'",
")",
".",
"text",
".",
"to_i",
"[",
"year",
",",
"month",
"]",
"end"
] | Extracts the year and month from the given XML element.
@param [Nokogiri::XML::Element] element The XML element.
@return [Array<Integer, Integer>] An Array consisting of year and month. | [
"Extracts",
"the",
"year",
"and",
"month",
"from",
"the",
"given",
"XML",
"element",
"."
] | 06939a65f8453b49b8bae749efcbe08ce86099e8 | https://github.com/tlux/vnstat-ruby/blob/06939a65f8453b49b8bae749efcbe08ce86099e8/lib/vnstat/parser.rb#L15-L19 | train |
tlux/vnstat-ruby | lib/vnstat/parser.rb | Vnstat.Parser.extract_date_from_xml_element | def extract_date_from_xml_element(element)
day = element.xpath('date/day').text.to_i
year, month = extract_month_from_xml_element(element)
Date.new(year, month, day)
end | ruby | def extract_date_from_xml_element(element)
day = element.xpath('date/day').text.to_i
year, month = extract_month_from_xml_element(element)
Date.new(year, month, day)
end | [
"def",
"extract_date_from_xml_element",
"(",
"element",
")",
"day",
"=",
"element",
".",
"xpath",
"(",
"'date/day'",
")",
".",
"text",
".",
"to_i",
"year",
",",
"month",
"=",
"extract_month_from_xml_element",
"(",
"element",
")",
"Date",
".",
"new",
"(",
"year",
",",
"month",
",",
"day",
")",
"end"
] | Extracts the date from the given XML element.
@param [Nokogiri::XML::Element] element The XML element.
@return [Date] | [
"Extracts",
"the",
"date",
"from",
"the",
"given",
"XML",
"element",
"."
] | 06939a65f8453b49b8bae749efcbe08ce86099e8 | https://github.com/tlux/vnstat-ruby/blob/06939a65f8453b49b8bae749efcbe08ce86099e8/lib/vnstat/parser.rb#L26-L30 | train |
tlux/vnstat-ruby | lib/vnstat/parser.rb | Vnstat.Parser.extract_datetime_from_xml_element | def extract_datetime_from_xml_element(element)
date = extract_date_from_xml_element(element)
hour = element.xpath('time/hour').text.to_i
minute = element.xpath('time/minute').text.to_i
offset = Time.now.strftime('%:z')
Time.new(date.year, date.month, date.day, hour, minute, 0, offset)
end | ruby | def extract_datetime_from_xml_element(element)
date = extract_date_from_xml_element(element)
hour = element.xpath('time/hour').text.to_i
minute = element.xpath('time/minute').text.to_i
offset = Time.now.strftime('%:z')
Time.new(date.year, date.month, date.day, hour, minute, 0, offset)
end | [
"def",
"extract_datetime_from_xml_element",
"(",
"element",
")",
"date",
"=",
"extract_date_from_xml_element",
"(",
"element",
")",
"hour",
"=",
"element",
".",
"xpath",
"(",
"'time/hour'",
")",
".",
"text",
".",
"to_i",
"minute",
"=",
"element",
".",
"xpath",
"(",
"'time/minute'",
")",
".",
"text",
".",
"to_i",
"offset",
"=",
"Time",
".",
"now",
".",
"strftime",
"(",
"'%:z'",
")",
"Time",
".",
"new",
"(",
"date",
".",
"year",
",",
"date",
".",
"month",
",",
"date",
".",
"day",
",",
"hour",
",",
"minute",
",",
"0",
",",
"offset",
")",
"end"
] | Extracts the date and time from the given XML element.
@param [Nokogiri::XML::Element] element The XML element.
@return [DateTime] | [
"Extracts",
"the",
"date",
"and",
"time",
"from",
"the",
"given",
"XML",
"element",
"."
] | 06939a65f8453b49b8bae749efcbe08ce86099e8 | https://github.com/tlux/vnstat-ruby/blob/06939a65f8453b49b8bae749efcbe08ce86099e8/lib/vnstat/parser.rb#L37-L43 | train |
tlux/vnstat-ruby | lib/vnstat/parser.rb | Vnstat.Parser.extract_transmitted_bytes_from_xml_element | def extract_transmitted_bytes_from_xml_element(element)
bytes_received = element.xpath('rx').text.to_i * 1024
bytes_sent = element.xpath('tx').text.to_i * 1024
[bytes_received, bytes_sent]
end | ruby | def extract_transmitted_bytes_from_xml_element(element)
bytes_received = element.xpath('rx').text.to_i * 1024
bytes_sent = element.xpath('tx').text.to_i * 1024
[bytes_received, bytes_sent]
end | [
"def",
"extract_transmitted_bytes_from_xml_element",
"(",
"element",
")",
"bytes_received",
"=",
"element",
".",
"xpath",
"(",
"'rx'",
")",
".",
"text",
".",
"to_i",
"*",
"1024",
"bytes_sent",
"=",
"element",
".",
"xpath",
"(",
"'tx'",
")",
".",
"text",
".",
"to_i",
"*",
"1024",
"[",
"bytes_received",
",",
"bytes_sent",
"]",
"end"
] | Extracts the bytes received and sent from the given XML element.
@param [Nokogiri::XML::Element] element The XML element.
@return [Array<Integer, Integer>] An Array consisting of bytes received
and bytes sent. | [
"Extracts",
"the",
"bytes",
"received",
"and",
"sent",
"from",
"the",
"given",
"XML",
"element",
"."
] | 06939a65f8453b49b8bae749efcbe08ce86099e8 | https://github.com/tlux/vnstat-ruby/blob/06939a65f8453b49b8bae749efcbe08ce86099e8/lib/vnstat/parser.rb#L51-L55 | train |
12spokes/tandem | app/helpers/tandem/pages_helper.rb | Tandem.PagesHelper.tandem_navigation_tag | def tandem_navigation_tag(active_page, pages_collection = nil, html_options = {})
html_options, pages_collection = pages_collection, nil if pages_collection.is_a?(Hash)
html_options[:class] ||= 'nav'
page_groups = (pages_collection || Page.all).inject({}) do |groups, page|
if groups[page.parent_id.to_s]
groups[page.parent_id.to_s] << page
else
groups[page.parent_id.to_s] = [page]
end
groups
end
# generate must be in scope for the iterate proc declaration, but must be defined below iterate, so that iterate is recursively in scope
generate = nil
iterate = Proc.new do |parent_id|
#very important to delete the group from the collection, or it is possible users can create looping relationships
(page_groups.delete(parent_id.to_s) || {}).inject(''.html_safe) do |buffer, page|
buffer + generate.call(page)
end
end
generate = Proc.new do |page|
content_tag_for(:li, page, :tandem, class: "#{page == active_page ? 'active' : ''}") do
link_to(page.link_label, tandem.page_path(page), class: "#{page == active_page ? 'active' : ''}") +
content_tag(:ul) do
iterate.call(page.id)
end
end
end
content_tag(:ul, html_options) do
iterate.call(page_groups.keys.first)
end
end | ruby | def tandem_navigation_tag(active_page, pages_collection = nil, html_options = {})
html_options, pages_collection = pages_collection, nil if pages_collection.is_a?(Hash)
html_options[:class] ||= 'nav'
page_groups = (pages_collection || Page.all).inject({}) do |groups, page|
if groups[page.parent_id.to_s]
groups[page.parent_id.to_s] << page
else
groups[page.parent_id.to_s] = [page]
end
groups
end
# generate must be in scope for the iterate proc declaration, but must be defined below iterate, so that iterate is recursively in scope
generate = nil
iterate = Proc.new do |parent_id|
#very important to delete the group from the collection, or it is possible users can create looping relationships
(page_groups.delete(parent_id.to_s) || {}).inject(''.html_safe) do |buffer, page|
buffer + generate.call(page)
end
end
generate = Proc.new do |page|
content_tag_for(:li, page, :tandem, class: "#{page == active_page ? 'active' : ''}") do
link_to(page.link_label, tandem.page_path(page), class: "#{page == active_page ? 'active' : ''}") +
content_tag(:ul) do
iterate.call(page.id)
end
end
end
content_tag(:ul, html_options) do
iterate.call(page_groups.keys.first)
end
end | [
"def",
"tandem_navigation_tag",
"(",
"active_page",
",",
"pages_collection",
"=",
"nil",
",",
"html_options",
"=",
"{",
"}",
")",
"html_options",
",",
"pages_collection",
"=",
"pages_collection",
",",
"nil",
"if",
"pages_collection",
".",
"is_a?",
"(",
"Hash",
")",
"html_options",
"[",
":class",
"]",
"||=",
"'nav'",
"page_groups",
"=",
"(",
"pages_collection",
"||",
"Page",
".",
"all",
")",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"groups",
",",
"page",
"|",
"if",
"groups",
"[",
"page",
".",
"parent_id",
".",
"to_s",
"]",
"groups",
"[",
"page",
".",
"parent_id",
".",
"to_s",
"]",
"<<",
"page",
"else",
"groups",
"[",
"page",
".",
"parent_id",
".",
"to_s",
"]",
"=",
"[",
"page",
"]",
"end",
"groups",
"end",
"generate",
"=",
"nil",
"iterate",
"=",
"Proc",
".",
"new",
"do",
"|",
"parent_id",
"|",
"(",
"page_groups",
".",
"delete",
"(",
"parent_id",
".",
"to_s",
")",
"||",
"{",
"}",
")",
".",
"inject",
"(",
"''",
".",
"html_safe",
")",
"do",
"|",
"buffer",
",",
"page",
"|",
"buffer",
"+",
"generate",
".",
"call",
"(",
"page",
")",
"end",
"end",
"generate",
"=",
"Proc",
".",
"new",
"do",
"|",
"page",
"|",
"content_tag_for",
"(",
":li",
",",
"page",
",",
":tandem",
",",
"class",
":",
"\"#{page == active_page ? 'active' : ''}\"",
")",
"do",
"link_to",
"(",
"page",
".",
"link_label",
",",
"tandem",
".",
"page_path",
"(",
"page",
")",
",",
"class",
":",
"\"#{page == active_page ? 'active' : ''}\"",
")",
"+",
"content_tag",
"(",
":ul",
")",
"do",
"iterate",
".",
"call",
"(",
"page",
".",
"id",
")",
"end",
"end",
"end",
"content_tag",
"(",
":ul",
",",
"html_options",
")",
"do",
"iterate",
".",
"call",
"(",
"page_groups",
".",
"keys",
".",
"first",
")",
"end",
"end"
] | todo... document this | [
"todo",
"...",
"document",
"this"
] | 6ad1cd041158c721c84a8c27809c1ddac1dbf6ce | https://github.com/12spokes/tandem/blob/6ad1cd041158c721c84a8c27809c1ddac1dbf6ce/app/helpers/tandem/pages_helper.rb#L137-L173 | train |
CryptoProcessing/cryptoprocessing.rb | lib/cryptoprocessing/connection.rb | Cryptoprocessing.Connection.get | def get(path, params = {})
uri = path
if params.count > 0
uri += "?#{URI.encode_www_form(params)}"
end
headers = {}
request('GET', uri, nil, headers) do |resp|
if params[:fetch_all] == true &&
resp.body.has_key?('pagination') &&
resp.body['pagination']['next_uri'] != nil
params[:starting_after] = resp.body['data'].last['id']
get(path, params) do |page|
body = resp.body
body['data'] += page.data
resp.body = body
yield(resp) if block_given?
end
else
yield(resp) if block_given?
end
end
end | ruby | def get(path, params = {})
uri = path
if params.count > 0
uri += "?#{URI.encode_www_form(params)}"
end
headers = {}
request('GET', uri, nil, headers) do |resp|
if params[:fetch_all] == true &&
resp.body.has_key?('pagination') &&
resp.body['pagination']['next_uri'] != nil
params[:starting_after] = resp.body['data'].last['id']
get(path, params) do |page|
body = resp.body
body['data'] += page.data
resp.body = body
yield(resp) if block_given?
end
else
yield(resp) if block_given?
end
end
end | [
"def",
"get",
"(",
"path",
",",
"params",
"=",
"{",
"}",
")",
"uri",
"=",
"path",
"if",
"params",
".",
"count",
">",
"0",
"uri",
"+=",
"\"?#{URI.encode_www_form(params)}\"",
"end",
"headers",
"=",
"{",
"}",
"request",
"(",
"'GET'",
",",
"uri",
",",
"nil",
",",
"headers",
")",
"do",
"|",
"resp",
"|",
"if",
"params",
"[",
":fetch_all",
"]",
"==",
"true",
"&&",
"resp",
".",
"body",
".",
"has_key?",
"(",
"'pagination'",
")",
"&&",
"resp",
".",
"body",
"[",
"'pagination'",
"]",
"[",
"'next_uri'",
"]",
"!=",
"nil",
"params",
"[",
":starting_after",
"]",
"=",
"resp",
".",
"body",
"[",
"'data'",
"]",
".",
"last",
"[",
"'id'",
"]",
"get",
"(",
"path",
",",
"params",
")",
"do",
"|",
"page",
"|",
"body",
"=",
"resp",
".",
"body",
"body",
"[",
"'data'",
"]",
"+=",
"page",
".",
"data",
"resp",
".",
"body",
"=",
"body",
"yield",
"(",
"resp",
")",
"if",
"block_given?",
"end",
"else",
"yield",
"(",
"resp",
")",
"if",
"block_given?",
"end",
"end",
"end"
] | HTTP GET method
@param [String] path | [
"HTTP",
"GET",
"method"
] | 54cd6c697e47cd1124dd348e96b0f11facac9b79 | https://github.com/CryptoProcessing/cryptoprocessing.rb/blob/54cd6c697e47cd1124dd348e96b0f11facac9b79/lib/cryptoprocessing/connection.rb#L79-L102 | train |
CryptoProcessing/cryptoprocessing.rb | lib/cryptoprocessing/connection.rb | Cryptoprocessing.Connection.put | def put(path, params)
headers = {}
request('PUT', path, params.to_json, headers) do |resp|
yield(resp) if block_given?
end
end | ruby | def put(path, params)
headers = {}
request('PUT', path, params.to_json, headers) do |resp|
yield(resp) if block_given?
end
end | [
"def",
"put",
"(",
"path",
",",
"params",
")",
"headers",
"=",
"{",
"}",
"request",
"(",
"'PUT'",
",",
"path",
",",
"params",
".",
"to_json",
",",
"headers",
")",
"do",
"|",
"resp",
"|",
"yield",
"(",
"resp",
")",
"if",
"block_given?",
"end",
"end"
] | HTTP PUT method
@param [String] path | [
"HTTP",
"PUT",
"method"
] | 54cd6c697e47cd1124dd348e96b0f11facac9b79 | https://github.com/CryptoProcessing/cryptoprocessing.rb/blob/54cd6c697e47cd1124dd348e96b0f11facac9b79/lib/cryptoprocessing/connection.rb#L108-L114 | train |
CryptoProcessing/cryptoprocessing.rb | lib/cryptoprocessing/connection.rb | Cryptoprocessing.Connection.post | def post(path, params)
headers = {}
request('POST', path, params.to_json, headers) do |resp|
yield(resp) if block_given?
end
end | ruby | def post(path, params)
headers = {}
request('POST', path, params.to_json, headers) do |resp|
yield(resp) if block_given?
end
end | [
"def",
"post",
"(",
"path",
",",
"params",
")",
"headers",
"=",
"{",
"}",
"request",
"(",
"'POST'",
",",
"path",
",",
"params",
".",
"to_json",
",",
"headers",
")",
"do",
"|",
"resp",
"|",
"yield",
"(",
"resp",
")",
"if",
"block_given?",
"end",
"end"
] | HTTP POST method
@param [String] path | [
"HTTP",
"POST",
"method"
] | 54cd6c697e47cd1124dd348e96b0f11facac9b79 | https://github.com/CryptoProcessing/cryptoprocessing.rb/blob/54cd6c697e47cd1124dd348e96b0f11facac9b79/lib/cryptoprocessing/connection.rb#L120-L126 | train |
CryptoProcessing/cryptoprocessing.rb | lib/cryptoprocessing/connection.rb | Cryptoprocessing.Connection.delete | def delete(path, params)
headers = {}
request('DELETE', path, nil, headers) do |resp|
yield(resp) if block_given?
end
end | ruby | def delete(path, params)
headers = {}
request('DELETE', path, nil, headers) do |resp|
yield(resp) if block_given?
end
end | [
"def",
"delete",
"(",
"path",
",",
"params",
")",
"headers",
"=",
"{",
"}",
"request",
"(",
"'DELETE'",
",",
"path",
",",
"nil",
",",
"headers",
")",
"do",
"|",
"resp",
"|",
"yield",
"(",
"resp",
")",
"if",
"block_given?",
"end",
"end"
] | HTTP DELETE method
@param [String] path | [
"HTTP",
"DELETE",
"method"
] | 54cd6c697e47cd1124dd348e96b0f11facac9b79 | https://github.com/CryptoProcessing/cryptoprocessing.rb/blob/54cd6c697e47cd1124dd348e96b0f11facac9b79/lib/cryptoprocessing/connection.rb#L132-L138 | train |
huffpostdata/ruby-pollster | lib/pollster/api.rb | Pollster.Api.charts_slug_get | def charts_slug_get(slug, opts = {})
data, _status_code, _headers = charts_slug_get_with_http_info(slug, opts)
return data
end | ruby | def charts_slug_get(slug, opts = {})
data, _status_code, _headers = charts_slug_get_with_http_info(slug, opts)
return data
end | [
"def",
"charts_slug_get",
"(",
"slug",
",",
"opts",
"=",
"{",
"}",
")",
"data",
",",
"_status_code",
",",
"_headers",
"=",
"charts_slug_get_with_http_info",
"(",
"slug",
",",
"opts",
")",
"return",
"data",
"end"
] | Chart
A Chart is chosen by Pollster editors. One example is \"Obama job approval - Democrats\". It is always based upon a single Question. Users should strongly consider basing their analysis on Questions instead. Charts are derived data; Pollster editors publish them and change them as editorial priorities change.
@param slug Unique identifier for a Chart
@param [Hash] opts the optional parameters
@return [Chart] | [
"Chart",
"A",
"Chart",
"is",
"chosen",
"by",
"Pollster",
"editors",
".",
"One",
"example",
"is",
"\\",
"Obama",
"job",
"approval",
"-",
"Democrats",
"\\",
".",
"It",
"is",
"always",
"based",
"upon",
"a",
"single",
"Question",
".",
"Users",
"should",
"strongly",
"consider",
"basing",
"their",
"analysis",
"on",
"Questions",
"instead",
".",
"Charts",
"are",
"derived",
"data",
";",
"Pollster",
"editors",
"publish",
"them",
"and",
"change",
"them",
"as",
"editorial",
"priorities",
"change",
"."
] | 32fb81b58e7fb39787a7591b8ede579301cd2b8b | https://github.com/huffpostdata/ruby-pollster/blob/32fb81b58e7fb39787a7591b8ede579301cd2b8b/lib/pollster/api.rb#L78-L81 | train |
huffpostdata/ruby-pollster | lib/pollster/api.rb | Pollster.Api.polls_slug_get | def polls_slug_get(slug, opts = {})
data, _status_code, _headers = polls_slug_get_with_http_info(slug, opts)
return data
end | ruby | def polls_slug_get(slug, opts = {})
data, _status_code, _headers = polls_slug_get_with_http_info(slug, opts)
return data
end | [
"def",
"polls_slug_get",
"(",
"slug",
",",
"opts",
"=",
"{",
"}",
")",
"data",
",",
"_status_code",
",",
"_headers",
"=",
"polls_slug_get_with_http_info",
"(",
"slug",
",",
"opts",
")",
"return",
"data",
"end"
] | Poll
A Poll on Pollster is a collection of questions and responses published by a reputable survey house. This endpoint provides raw data from the survey house, plus Pollster-provided metadata about each question. Pollster editors don't include every question when they enter Polls, and they don't necessarily enter every subpopulation for the responses they _do_ enter. They make editorial decisions about which questions belong in the database.
@param slug Unique Poll identifier. For example: `gallup-26892`.
@param [Hash] opts the optional parameters
@return [Poll] | [
"Poll",
"A",
"Poll",
"on",
"Pollster",
"is",
"a",
"collection",
"of",
"questions",
"and",
"responses",
"published",
"by",
"a",
"reputable",
"survey",
"house",
".",
"This",
"endpoint",
"provides",
"raw",
"data",
"from",
"the",
"survey",
"house",
"plus",
"Pollster",
"-",
"provided",
"metadata",
"about",
"each",
"question",
".",
"Pollster",
"editors",
"don",
"t",
"include",
"every",
"question",
"when",
"they",
"enter",
"Polls",
"and",
"they",
"don",
"t",
"necessarily",
"enter",
"every",
"subpopulation",
"for",
"the",
"responses",
"they",
"_do_",
"enter",
".",
"They",
"make",
"editorial",
"decisions",
"about",
"which",
"questions",
"belong",
"in",
"the",
"database",
"."
] | 32fb81b58e7fb39787a7591b8ede579301cd2b8b | https://github.com/huffpostdata/ruby-pollster/blob/32fb81b58e7fb39787a7591b8ede579301cd2b8b/lib/pollster/api.rb#L317-L320 | train |
dark-prince/currency_converter | lib/currency_converter/xe.rb | CurrencyConverter.XE.exchange_rate | def exchange_rate
url = "/currencyconverter/convert/?Amount=1&From=#{from_currency.to_s.upcase}&To=#{to_currency.to_s.upcase}"
uri = URI.parse('https://www.xe.com')
request = Net::HTTP.new(uri.host, uri.port)
request.use_ssl = true
response = request.get(url)
doc = Nokogiri::HTML(response.body)
result = doc.css('span.uccResultAmount').text
regexp = Regexp.new('(\\d+(?:\\.\\d+)?)')
regexp.match result
return $1
rescue Timeout::Error
raise StandardError, 'Please check your internet connection'
end | ruby | def exchange_rate
url = "/currencyconverter/convert/?Amount=1&From=#{from_currency.to_s.upcase}&To=#{to_currency.to_s.upcase}"
uri = URI.parse('https://www.xe.com')
request = Net::HTTP.new(uri.host, uri.port)
request.use_ssl = true
response = request.get(url)
doc = Nokogiri::HTML(response.body)
result = doc.css('span.uccResultAmount').text
regexp = Regexp.new('(\\d+(?:\\.\\d+)?)')
regexp.match result
return $1
rescue Timeout::Error
raise StandardError, 'Please check your internet connection'
end | [
"def",
"exchange_rate",
"url",
"=",
"\"/currencyconverter/convert/?Amount=1&From=#{from_currency.to_s.upcase}&To=#{to_currency.to_s.upcase}\"",
"uri",
"=",
"URI",
".",
"parse",
"(",
"'https://www.xe.com'",
")",
"request",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
")",
"request",
".",
"use_ssl",
"=",
"true",
"response",
"=",
"request",
".",
"get",
"(",
"url",
")",
"doc",
"=",
"Nokogiri",
"::",
"HTML",
"(",
"response",
".",
"body",
")",
"result",
"=",
"doc",
".",
"css",
"(",
"'span.uccResultAmount'",
")",
".",
"text",
"regexp",
"=",
"Regexp",
".",
"new",
"(",
"'(\\\\d+(?:\\\\.\\\\d+)?)'",
")",
"regexp",
".",
"match",
"result",
"return",
"$1",
"rescue",
"Timeout",
"::",
"Error",
"raise",
"StandardError",
",",
"'Please check your internet connection'",
"end"
] | Returns the Float value of rate or nil | [
"Returns",
"the",
"Float",
"value",
"of",
"rate",
"or",
"nil"
] | 5aa6cc5f4a5f500dcd227bd5516e22ca43ffce46 | https://github.com/dark-prince/currency_converter/blob/5aa6cc5f4a5f500dcd227bd5516e22ca43ffce46/lib/currency_converter/xe.rb#L40-L57 | train |
dpla/KriKri | lib/krikri/logger.rb | Krikri.Logger.log | def log(priority, msg)
@logger.tagged(Time.now.to_s, Process.pid, to_s) do
@logger.send(priority, msg)
end
end | ruby | def log(priority, msg)
@logger.tagged(Time.now.to_s, Process.pid, to_s) do
@logger.send(priority, msg)
end
end | [
"def",
"log",
"(",
"priority",
",",
"msg",
")",
"@logger",
".",
"tagged",
"(",
"Time",
".",
"now",
".",
"to_s",
",",
"Process",
".",
"pid",
",",
"to_s",
")",
"do",
"@logger",
".",
"send",
"(",
"priority",
",",
"msg",
")",
"end",
"end"
] | Log a message, tagged for application-wide consistency
@param [Symbol] priority a priority tag
@param [string] msg the message to log | [
"Log",
"a",
"message",
"tagged",
"for",
"application",
"-",
"wide",
"consistency"
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/logger.rb#L32-L36 | train |
theodi/breasal | lib/breasal/latlng.rb | Breasal.LatLng.to_WGS84 | def to_WGS84
if @type == :ie
@a = 6377340.189
@b = 6356034.447
else
@a = 6377563.396
@b = 6356256.909
end
@eSquared = ((@a * @a) - (@b * @b)) / (@a * @a)
@phi = deg_to_rad(@latitude)
@lambda = deg_to_rad(@longitude)
@v = @a / (Math.sqrt(1 - @eSquared * sin_pow_2(@phi)))
@H = 0
@x = (@v + @H) * Math.cos(@phi) * Math.cos(@lambda)
@y = (@v + @H) * Math.cos(@phi) * Math.sin(@lambda)
@z = ((1 - @eSquared) * @v + @H) * Math.sin(@phi)
@tx = 446.448
@ty = -124.157
@tz = 542.060
@s = -0.0000204894
@rx = deg_to_rad( 0.00004172222)
@ry = deg_to_rad( 0.00006861111)
@rz = deg_to_rad( 0.00023391666)
@xB = @tx + (@x * (1 + @s)) + (-@rx * @y) + (@ry * @z)
@yB = @ty + (@rz * @x) + (@y * (1 + @s)) + (-@rx * @z)
@zB = @tz + (-@ry * @x) + (@rx * @y) + (@z * (1 + @s))
@a = 6378137.000
@b = 6356752.3141
@eSquared = ((@a * @a) - (@b * @b)) / (@a * @a)
@lambdaB = rad_to_deg(Math.atan(@yB / @xB))
@p = Math.sqrt((@xB * @xB) + (@yB * @yB))
@phiN = Math.atan(@zB / (@p * (1 - @eSquared)))
(1..10).each do |i|
@v = @a / (Math.sqrt(1 - @eSquared * sin_pow_2(@phiN)))
@phiN1 = Math.atan((@zB + (@eSquared * @v * Math.sin(@phiN))) / @p)
@phiN = @phiN1
end
@phiB = rad_to_deg(@phiN)
{ :latitude => @phiB, :longitude => @lambdaB }
end | ruby | def to_WGS84
if @type == :ie
@a = 6377340.189
@b = 6356034.447
else
@a = 6377563.396
@b = 6356256.909
end
@eSquared = ((@a * @a) - (@b * @b)) / (@a * @a)
@phi = deg_to_rad(@latitude)
@lambda = deg_to_rad(@longitude)
@v = @a / (Math.sqrt(1 - @eSquared * sin_pow_2(@phi)))
@H = 0
@x = (@v + @H) * Math.cos(@phi) * Math.cos(@lambda)
@y = (@v + @H) * Math.cos(@phi) * Math.sin(@lambda)
@z = ((1 - @eSquared) * @v + @H) * Math.sin(@phi)
@tx = 446.448
@ty = -124.157
@tz = 542.060
@s = -0.0000204894
@rx = deg_to_rad( 0.00004172222)
@ry = deg_to_rad( 0.00006861111)
@rz = deg_to_rad( 0.00023391666)
@xB = @tx + (@x * (1 + @s)) + (-@rx * @y) + (@ry * @z)
@yB = @ty + (@rz * @x) + (@y * (1 + @s)) + (-@rx * @z)
@zB = @tz + (-@ry * @x) + (@rx * @y) + (@z * (1 + @s))
@a = 6378137.000
@b = 6356752.3141
@eSquared = ((@a * @a) - (@b * @b)) / (@a * @a)
@lambdaB = rad_to_deg(Math.atan(@yB / @xB))
@p = Math.sqrt((@xB * @xB) + (@yB * @yB))
@phiN = Math.atan(@zB / (@p * (1 - @eSquared)))
(1..10).each do |i|
@v = @a / (Math.sqrt(1 - @eSquared * sin_pow_2(@phiN)))
@phiN1 = Math.atan((@zB + (@eSquared * @v * Math.sin(@phiN))) / @p)
@phiN = @phiN1
end
@phiB = rad_to_deg(@phiN)
{ :latitude => @phiB, :longitude => @lambdaB }
end | [
"def",
"to_WGS84",
"if",
"@type",
"==",
":ie",
"@a",
"=",
"6377340.189",
"@b",
"=",
"6356034.447",
"else",
"@a",
"=",
"6377563.396",
"@b",
"=",
"6356256.909",
"end",
"@eSquared",
"=",
"(",
"(",
"@a",
"*",
"@a",
")",
"-",
"(",
"@b",
"*",
"@b",
")",
")",
"/",
"(",
"@a",
"*",
"@a",
")",
"@phi",
"=",
"deg_to_rad",
"(",
"@latitude",
")",
"@lambda",
"=",
"deg_to_rad",
"(",
"@longitude",
")",
"@v",
"=",
"@a",
"/",
"(",
"Math",
".",
"sqrt",
"(",
"1",
"-",
"@eSquared",
"*",
"sin_pow_2",
"(",
"@phi",
")",
")",
")",
"@H",
"=",
"0",
"@x",
"=",
"(",
"@v",
"+",
"@H",
")",
"*",
"Math",
".",
"cos",
"(",
"@phi",
")",
"*",
"Math",
".",
"cos",
"(",
"@lambda",
")",
"@y",
"=",
"(",
"@v",
"+",
"@H",
")",
"*",
"Math",
".",
"cos",
"(",
"@phi",
")",
"*",
"Math",
".",
"sin",
"(",
"@lambda",
")",
"@z",
"=",
"(",
"(",
"1",
"-",
"@eSquared",
")",
"*",
"@v",
"+",
"@H",
")",
"*",
"Math",
".",
"sin",
"(",
"@phi",
")",
"@tx",
"=",
"446.448",
"@ty",
"=",
"-",
"124.157",
"@tz",
"=",
"542.060",
"@s",
"=",
"-",
"0.0000204894",
"@rx",
"=",
"deg_to_rad",
"(",
"0.00004172222",
")",
"@ry",
"=",
"deg_to_rad",
"(",
"0.00006861111",
")",
"@rz",
"=",
"deg_to_rad",
"(",
"0.00023391666",
")",
"@xB",
"=",
"@tx",
"+",
"(",
"@x",
"*",
"(",
"1",
"+",
"@s",
")",
")",
"+",
"(",
"-",
"@rx",
"*",
"@y",
")",
"+",
"(",
"@ry",
"*",
"@z",
")",
"@yB",
"=",
"@ty",
"+",
"(",
"@rz",
"*",
"@x",
")",
"+",
"(",
"@y",
"*",
"(",
"1",
"+",
"@s",
")",
")",
"+",
"(",
"-",
"@rx",
"*",
"@z",
")",
"@zB",
"=",
"@tz",
"+",
"(",
"-",
"@ry",
"*",
"@x",
")",
"+",
"(",
"@rx",
"*",
"@y",
")",
"+",
"(",
"@z",
"*",
"(",
"1",
"+",
"@s",
")",
")",
"@a",
"=",
"6378137.000",
"@b",
"=",
"6356752.3141",
"@eSquared",
"=",
"(",
"(",
"@a",
"*",
"@a",
")",
"-",
"(",
"@b",
"*",
"@b",
")",
")",
"/",
"(",
"@a",
"*",
"@a",
")",
"@lambdaB",
"=",
"rad_to_deg",
"(",
"Math",
".",
"atan",
"(",
"@yB",
"/",
"@xB",
")",
")",
"@p",
"=",
"Math",
".",
"sqrt",
"(",
"(",
"@xB",
"*",
"@xB",
")",
"+",
"(",
"@yB",
"*",
"@yB",
")",
")",
"@phiN",
"=",
"Math",
".",
"atan",
"(",
"@zB",
"/",
"(",
"@p",
"*",
"(",
"1",
"-",
"@eSquared",
")",
")",
")",
"(",
"1",
"..",
"10",
")",
".",
"each",
"do",
"|",
"i",
"|",
"@v",
"=",
"@a",
"/",
"(",
"Math",
".",
"sqrt",
"(",
"1",
"-",
"@eSquared",
"*",
"sin_pow_2",
"(",
"@phiN",
")",
")",
")",
"@phiN1",
"=",
"Math",
".",
"atan",
"(",
"(",
"@zB",
"+",
"(",
"@eSquared",
"*",
"@v",
"*",
"Math",
".",
"sin",
"(",
"@phiN",
")",
")",
")",
"/",
"@p",
")",
"@phiN",
"=",
"@phiN1",
"end",
"@phiB",
"=",
"rad_to_deg",
"(",
"@phiN",
")",
"{",
":latitude",
"=>",
"@phiB",
",",
":longitude",
"=>",
"@lambdaB",
"}",
"end"
] | Takes OSGB36 or TM75 Latitude and Longitude coords
and returns WGS84 Latitude and Longitude | [
"Takes",
"OSGB36",
"or",
"TM75",
"Latitude",
"and",
"Longitude",
"coords",
"and",
"returns",
"WGS84",
"Latitude",
"and",
"Longitude"
] | 3f191f9f4fc32d9e52a111ed1acea9caf8a965fc | https://github.com/theodi/breasal/blob/3f191f9f4fc32d9e52a111ed1acea9caf8a965fc/lib/breasal/latlng.rb#L15-L66 | train |
dpla/KriKri | lib/krikri/enrichments/timespan_split.rb | Krikri::Enrichments.TimespanSplit.populate_timespan | def populate_timespan(timespan)
return timespan unless (timespan.begin.empty? || timespan.end.empty?) &&
!timespan.providedLabel.empty?
parsed = parse_labels(timespan.providedLabel)
return timespan if parsed.empty?
parsed.each do |date|
begin_date, end_date = span_from_date(date)
timespan.begin << begin_date
timespan.end << end_date
end
reduce_to_largest_span(timespan)
return timespan
end | ruby | def populate_timespan(timespan)
return timespan unless (timespan.begin.empty? || timespan.end.empty?) &&
!timespan.providedLabel.empty?
parsed = parse_labels(timespan.providedLabel)
return timespan if parsed.empty?
parsed.each do |date|
begin_date, end_date = span_from_date(date)
timespan.begin << begin_date
timespan.end << end_date
end
reduce_to_largest_span(timespan)
return timespan
end | [
"def",
"populate_timespan",
"(",
"timespan",
")",
"return",
"timespan",
"unless",
"(",
"timespan",
".",
"begin",
".",
"empty?",
"||",
"timespan",
".",
"end",
".",
"empty?",
")",
"&&",
"!",
"timespan",
".",
"providedLabel",
".",
"empty?",
"parsed",
"=",
"parse_labels",
"(",
"timespan",
".",
"providedLabel",
")",
"return",
"timespan",
"if",
"parsed",
".",
"empty?",
"parsed",
".",
"each",
"do",
"|",
"date",
"|",
"begin_date",
",",
"end_date",
"=",
"span_from_date",
"(",
"date",
")",
"timespan",
".",
"begin",
"<<",
"begin_date",
"timespan",
".",
"end",
"<<",
"end_date",
"end",
"reduce_to_largest_span",
"(",
"timespan",
")",
"return",
"timespan",
"end"
] | Populates a timespan with a begin and end date.
@param timespan [DPLA::MAP::TimeSpan]
@return [DPLA::MAP::TimeSpan] | [
"Populates",
"a",
"timespan",
"with",
"a",
"begin",
"and",
"end",
"date",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/enrichments/timespan_split.rb#L65-L78 | train |
dpla/KriKri | lib/krikri/enrichments/timespan_split.rb | Krikri::Enrichments.TimespanSplit.span_from_date | def span_from_date(date)
return [nil, nil] if date.nil?
if date.is_a?(Date)
return [date, date] if date.precision == :day
return [date, (date.succ - 1)]
end
[(date.respond_to?(:first) ? date.first : date.from),
(date.respond_to?(:last) ? date.last : date.to)]
end | ruby | def span_from_date(date)
return [nil, nil] if date.nil?
if date.is_a?(Date)
return [date, date] if date.precision == :day
return [date, (date.succ - 1)]
end
[(date.respond_to?(:first) ? date.first : date.from),
(date.respond_to?(:last) ? date.last : date.to)]
end | [
"def",
"span_from_date",
"(",
"date",
")",
"return",
"[",
"nil",
",",
"nil",
"]",
"if",
"date",
".",
"nil?",
"if",
"date",
".",
"is_a?",
"(",
"Date",
")",
"return",
"[",
"date",
",",
"date",
"]",
"if",
"date",
".",
"precision",
"==",
":day",
"return",
"[",
"date",
",",
"(",
"date",
".",
"succ",
"-",
"1",
")",
"]",
"end",
"[",
"(",
"date",
".",
"respond_to?",
"(",
":first",
")",
"?",
"date",
".",
"first",
":",
"date",
".",
"from",
")",
",",
"(",
"date",
".",
"respond_to?",
"(",
":last",
")",
"?",
"date",
".",
"last",
":",
"date",
".",
"to",
")",
"]",
"end"
] | Converts an EDTF date to a begin and end date.
@param date [Date, DateTime, EDTF::Interval] a date, with or without EDTF
precision features; or an interval.
@return [Array<Date, DateTime>] an array of two elements containing the
begin and end dates. | [
"Converts",
"an",
"EDTF",
"date",
"to",
"a",
"begin",
"and",
"end",
"date",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/enrichments/timespan_split.rb#L94-L102 | train |
dpla/KriKri | lib/krikri/enrichments/timespan_split.rb | Krikri::Enrichments.TimespanSplit.reduce_to_largest_span | def reduce_to_largest_span(timespan)
timespan.begin = timespan.begin.sort.first
timespan.end = timespan.end.sort.last
timespan
end | ruby | def reduce_to_largest_span(timespan)
timespan.begin = timespan.begin.sort.first
timespan.end = timespan.end.sort.last
timespan
end | [
"def",
"reduce_to_largest_span",
"(",
"timespan",
")",
"timespan",
".",
"begin",
"=",
"timespan",
".",
"begin",
".",
"sort",
".",
"first",
"timespan",
".",
"end",
"=",
"timespan",
".",
"end",
".",
"sort",
".",
"last",
"timespan",
"end"
] | Reduces a timespan with multiple begin or end dates to a single earliest
begin date and a single latest end date.
@param timespan [DPLA::MAP::TimeSpan] the timespan to reduce
@return [DPLA::MAP::TimeSpan] an updated timespan | [
"Reduces",
"a",
"timespan",
"with",
"multiple",
"begin",
"or",
"end",
"dates",
"to",
"a",
"single",
"earliest",
"begin",
"date",
"and",
"a",
"single",
"latest",
"end",
"date",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/enrichments/timespan_split.rb#L111-L115 | train |
dpla/KriKri | app/models/krikri/activity.rb | Krikri.Activity.run | def run
if block_given?
update_attribute(:end_time, nil) if ended?
Krikri::Logger
.log(:info, "Activity #{agent.constantize}-#{id} is running")
set_start_time
begin
yield agent_instance, rdf_subject
rescue => e
Krikri::Logger.log(:error, "Error performing Activity: #{id}\n" \
"#{e.message}\n#{e.backtrace}")
raise e
ensure
set_end_time
Krikri::Logger
.log(:info, "Activity #{agent.constantize}-#{id} is done")
end
end
end | ruby | def run
if block_given?
update_attribute(:end_time, nil) if ended?
Krikri::Logger
.log(:info, "Activity #{agent.constantize}-#{id} is running")
set_start_time
begin
yield agent_instance, rdf_subject
rescue => e
Krikri::Logger.log(:error, "Error performing Activity: #{id}\n" \
"#{e.message}\n#{e.backtrace}")
raise e
ensure
set_end_time
Krikri::Logger
.log(:info, "Activity #{agent.constantize}-#{id} is done")
end
end
end | [
"def",
"run",
"if",
"block_given?",
"update_attribute",
"(",
":end_time",
",",
"nil",
")",
"if",
"ended?",
"Krikri",
"::",
"Logger",
".",
"log",
"(",
":info",
",",
"\"Activity #{agent.constantize}-#{id} is running\"",
")",
"set_start_time",
"begin",
"yield",
"agent_instance",
",",
"rdf_subject",
"rescue",
"=>",
"e",
"Krikri",
"::",
"Logger",
".",
"log",
"(",
":error",
",",
"\"Error performing Activity: #{id}\\n\"",
"\"#{e.message}\\n#{e.backtrace}\"",
")",
"raise",
"e",
"ensure",
"set_end_time",
"Krikri",
"::",
"Logger",
".",
"log",
"(",
":info",
",",
"\"Activity #{agent.constantize}-#{id} is done\"",
")",
"end",
"end",
"end"
] | Runs the block, setting the start and end time of the run. The given block
is passed an instance of the agent, and a URI representing this Activity.
Handles logging of activity start/stop and failure states.
@raise [RuntimeError] re-raises logged errors on Activity failure | [
"Runs",
"the",
"block",
"setting",
"the",
"start",
"and",
"end",
"time",
"of",
"the",
"run",
".",
"The",
"given",
"block",
"is",
"passed",
"an",
"instance",
"of",
"the",
"agent",
"and",
"a",
"URI",
"representing",
"this",
"Activity",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/app/models/krikri/activity.rb#L72-L90 | train |
basgys/emailvision | lib/emailvision/api.rb | Emailvision.Api.close_connection | def close_connection
if connected?
get.connect.close.call
else
return false
end
rescue Emailvision::Exception => e
ensure
invalidate_token!
not connected?
end | ruby | def close_connection
if connected?
get.connect.close.call
else
return false
end
rescue Emailvision::Exception => e
ensure
invalidate_token!
not connected?
end | [
"def",
"close_connection",
"if",
"connected?",
"get",
".",
"connect",
".",
"close",
".",
"call",
"else",
"return",
"false",
"end",
"rescue",
"Emailvision",
"::",
"Exception",
"=>",
"e",
"ensure",
"invalidate_token!",
"not",
"connected?",
"end"
] | Logout from Emailvision API
@return [Boolean] true if the connection has been destroyed | [
"Logout",
"from",
"Emailvision",
"API"
] | ce163ace77e46062448979debce76e8020ec9509 | https://github.com/basgys/emailvision/blob/ce163ace77e46062448979debce76e8020ec9509/lib/emailvision/api.rb#L56-L66 | train |
rafmagana/prowly | lib/prowly/interface.rb | Prowly.Interface.call | def call(command, params)
@command = command
request = Net::HTTP::Get.new(uri.request_uri + "?" + params)
response = http.request(request)
Response.new(response.body, response)
end | ruby | def call(command, params)
@command = command
request = Net::HTTP::Get.new(uri.request_uri + "?" + params)
response = http.request(request)
Response.new(response.body, response)
end | [
"def",
"call",
"(",
"command",
",",
"params",
")",
"@command",
"=",
"command",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"uri",
".",
"request_uri",
"+",
"\"?\"",
"+",
"params",
")",
"response",
"=",
"http",
".",
"request",
"(",
"request",
")",
"Response",
".",
"new",
"(",
"response",
".",
"body",
",",
"response",
")",
"end"
] | Make the actual call to the prowl api | [
"Make",
"the",
"actual",
"call",
"to",
"the",
"prowl",
"api"
] | d71cd7b7aa6b541808b7259db37469c93ab5b3f9 | https://github.com/rafmagana/prowly/blob/d71cd7b7aa6b541808b7259db37469c93ab5b3f9/lib/prowly/interface.rb#L25-L30 | train |
dpla/KriKri | app/models/krikri/search_index_document.rb | Krikri.SearchIndexDocument.aggregation | def aggregation
agg = DPLA::MAP::Aggregation.new(id)
return nil unless agg.exists?
agg.get
agg
end | ruby | def aggregation
agg = DPLA::MAP::Aggregation.new(id)
return nil unless agg.exists?
agg.get
agg
end | [
"def",
"aggregation",
"agg",
"=",
"DPLA",
"::",
"MAP",
"::",
"Aggregation",
".",
"new",
"(",
"id",
")",
"return",
"nil",
"unless",
"agg",
".",
"exists?",
"agg",
".",
"get",
"agg",
"end"
] | Get the aggregation, populated with data from Marmotta, which corresponds
to this SearchIndexDocument
@return [DPLA::MAP::Aggregation, nil] | [
"Get",
"the",
"aggregation",
"populated",
"with",
"data",
"from",
"Marmotta",
"which",
"corresponds",
"to",
"this",
"SearchIndexDocument"
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/app/models/krikri/search_index_document.rb#L21-L26 | train |
codez/render_inheritable | lib/render_inheritable.rb | RenderInheritable.ClassMethods.find_inheritable_template_folder | def find_inheritable_template_folder(view_context, name, partial, formats, param = nil)
find_inheritable_template_folder_cached(view_context, name, partial, formats, param) do
find_inheritable_artifact(param) do |folder|
view_context.template_exists?(name, folder, partial)
end
end
end | ruby | def find_inheritable_template_folder(view_context, name, partial, formats, param = nil)
find_inheritable_template_folder_cached(view_context, name, partial, formats, param) do
find_inheritable_artifact(param) do |folder|
view_context.template_exists?(name, folder, partial)
end
end
end | [
"def",
"find_inheritable_template_folder",
"(",
"view_context",
",",
"name",
",",
"partial",
",",
"formats",
",",
"param",
"=",
"nil",
")",
"find_inheritable_template_folder_cached",
"(",
"view_context",
",",
"name",
",",
"partial",
",",
"formats",
",",
"param",
")",
"do",
"find_inheritable_artifact",
"(",
"param",
")",
"do",
"|",
"folder",
"|",
"view_context",
".",
"template_exists?",
"(",
"name",
",",
"folder",
",",
"partial",
")",
"end",
"end",
"end"
] | Performs a lookup for the given filename and returns the most specific
folder that contains the file. | [
"Performs",
"a",
"lookup",
"for",
"the",
"given",
"filename",
"and",
"returns",
"the",
"most",
"specific",
"folder",
"that",
"contains",
"the",
"file",
"."
] | ec1ce2d104a1c1fe80a81e38559554dce211a678 | https://github.com/codez/render_inheritable/blob/ec1ce2d104a1c1fe80a81e38559554dce211a678/lib/render_inheritable.rb#L36-L42 | train |
codez/render_inheritable | lib/render_inheritable.rb | RenderInheritable.ClassMethods.inheritance_lookup_path | def inheritance_lookup_path
path = [self]
until path.last == inheritable_root_controller
path << path.last.superclass
end
path.collect(&:controller_path)
end | ruby | def inheritance_lookup_path
path = [self]
until path.last == inheritable_root_controller
path << path.last.superclass
end
path.collect(&:controller_path)
end | [
"def",
"inheritance_lookup_path",
"path",
"=",
"[",
"self",
"]",
"until",
"path",
".",
"last",
"==",
"inheritable_root_controller",
"path",
"<<",
"path",
".",
"last",
".",
"superclass",
"end",
"path",
".",
"collect",
"(",
"&",
":controller_path",
")",
"end"
] | The inheritance path of controllers that is used as default lookup path. | [
"The",
"inheritance",
"path",
"of",
"controllers",
"that",
"is",
"used",
"as",
"default",
"lookup",
"path",
"."
] | ec1ce2d104a1c1fe80a81e38559554dce211a678 | https://github.com/codez/render_inheritable/blob/ec1ce2d104a1c1fe80a81e38559554dce211a678/lib/render_inheritable.rb#L72-L78 | train |
codez/render_inheritable | lib/render_inheritable.rb | RenderInheritable.ClassMethods.find_inheritable_template_folder_cached | def find_inheritable_template_folder_cached(view_context, name, partial, formats, param = nil)
prefix = inheritable_cache_get(formats, name, partial, param)
return prefix if prefix
prefix = yield
if prefix
template = view_context.find_template_without_lookup(name, prefix, partial)
inheritable_cache_set(template.formats, name, partial, param, prefix)
end
prefix
end | ruby | def find_inheritable_template_folder_cached(view_context, name, partial, formats, param = nil)
prefix = inheritable_cache_get(formats, name, partial, param)
return prefix if prefix
prefix = yield
if prefix
template = view_context.find_template_without_lookup(name, prefix, partial)
inheritable_cache_set(template.formats, name, partial, param, prefix)
end
prefix
end | [
"def",
"find_inheritable_template_folder_cached",
"(",
"view_context",
",",
"name",
",",
"partial",
",",
"formats",
",",
"param",
"=",
"nil",
")",
"prefix",
"=",
"inheritable_cache_get",
"(",
"formats",
",",
"name",
",",
"partial",
",",
"param",
")",
"return",
"prefix",
"if",
"prefix",
"prefix",
"=",
"yield",
"if",
"prefix",
"template",
"=",
"view_context",
".",
"find_template_without_lookup",
"(",
"name",
",",
"prefix",
",",
"partial",
")",
"inheritable_cache_set",
"(",
"template",
".",
"formats",
",",
"name",
",",
"partial",
",",
"param",
",",
"prefix",
")",
"end",
"prefix",
"end"
] | Performs a lookup for a template folder using the cache. | [
"Performs",
"a",
"lookup",
"for",
"a",
"template",
"folder",
"using",
"the",
"cache",
"."
] | ec1ce2d104a1c1fe80a81e38559554dce211a678 | https://github.com/codez/render_inheritable/blob/ec1ce2d104a1c1fe80a81e38559554dce211a678/lib/render_inheritable.rb#L92-L103 | train |
codez/render_inheritable | lib/render_inheritable.rb | RenderInheritable.ClassMethods.inheritable_cache | def inheritable_cache #:nodoc:
# do not store keys on each access, only return default structure
@inheritable_cache ||= Hash.new do |h1, k1|
Hash.new do |h2, k2|
Hash.new do |h3, k3|
Hash.new
end
end
end
end | ruby | def inheritable_cache #:nodoc:
# do not store keys on each access, only return default structure
@inheritable_cache ||= Hash.new do |h1, k1|
Hash.new do |h2, k2|
Hash.new do |h3, k3|
Hash.new
end
end
end
end | [
"def",
"inheritable_cache",
"@inheritable_cache",
"||=",
"Hash",
".",
"new",
"do",
"|",
"h1",
",",
"k1",
"|",
"Hash",
".",
"new",
"do",
"|",
"h2",
",",
"k2",
"|",
"Hash",
".",
"new",
"do",
"|",
"h3",
",",
"k3",
"|",
"Hash",
".",
"new",
"end",
"end",
"end",
"end"
] | A simple template lookup cache for each controller. | [
"A",
"simple",
"template",
"lookup",
"cache",
"for",
"each",
"controller",
"."
] | ec1ce2d104a1c1fe80a81e38559554dce211a678 | https://github.com/codez/render_inheritable/blob/ec1ce2d104a1c1fe80a81e38559554dce211a678/lib/render_inheritable.rb#L106-L115 | train |
codez/render_inheritable | lib/render_inheritable.rb | RenderInheritable.ClassMethods.inheritable_cache_get | def inheritable_cache_get(formats, name, partial, param)
prefixes = formats.collect { |format| inheritable_cache[format.to_sym][partial][name][param] }
prefixes.compact!
prefixes.empty? ? nil : prefixes.first
end | ruby | def inheritable_cache_get(formats, name, partial, param)
prefixes = formats.collect { |format| inheritable_cache[format.to_sym][partial][name][param] }
prefixes.compact!
prefixes.empty? ? nil : prefixes.first
end | [
"def",
"inheritable_cache_get",
"(",
"formats",
",",
"name",
",",
"partial",
",",
"param",
")",
"prefixes",
"=",
"formats",
".",
"collect",
"{",
"|",
"format",
"|",
"inheritable_cache",
"[",
"format",
".",
"to_sym",
"]",
"[",
"partial",
"]",
"[",
"name",
"]",
"[",
"param",
"]",
"}",
"prefixes",
".",
"compact!",
"prefixes",
".",
"empty?",
"?",
"nil",
":",
"prefixes",
".",
"first",
"end"
] | Gets the prefix from the cache. Returns nil if it's not there yet. | [
"Gets",
"the",
"prefix",
"from",
"the",
"cache",
".",
"Returns",
"nil",
"if",
"it",
"s",
"not",
"there",
"yet",
"."
] | ec1ce2d104a1c1fe80a81e38559554dce211a678 | https://github.com/codez/render_inheritable/blob/ec1ce2d104a1c1fe80a81e38559554dce211a678/lib/render_inheritable.rb#L118-L122 | train |
codez/render_inheritable | lib/render_inheritable.rb | RenderInheritable.ClassMethods.inheritable_cache_set | def inheritable_cache_set(formats, name, partial, param, prefix)
formats.each do |format|
# assign hash default values to respective key
inheritable_cache[format.to_sym] = hf = inheritable_cache[format.to_sym]
hf[partial] = hp = hf[partial]
hp[name] = hn = hp[name]
# finally store prefix in the deepest hash
hn[param] = prefix
end
end | ruby | def inheritable_cache_set(formats, name, partial, param, prefix)
formats.each do |format|
# assign hash default values to respective key
inheritable_cache[format.to_sym] = hf = inheritable_cache[format.to_sym]
hf[partial] = hp = hf[partial]
hp[name] = hn = hp[name]
# finally store prefix in the deepest hash
hn[param] = prefix
end
end | [
"def",
"inheritable_cache_set",
"(",
"formats",
",",
"name",
",",
"partial",
",",
"param",
",",
"prefix",
")",
"formats",
".",
"each",
"do",
"|",
"format",
"|",
"inheritable_cache",
"[",
"format",
".",
"to_sym",
"]",
"=",
"hf",
"=",
"inheritable_cache",
"[",
"format",
".",
"to_sym",
"]",
"hf",
"[",
"partial",
"]",
"=",
"hp",
"=",
"hf",
"[",
"partial",
"]",
"hp",
"[",
"name",
"]",
"=",
"hn",
"=",
"hp",
"[",
"name",
"]",
"hn",
"[",
"param",
"]",
"=",
"prefix",
"end",
"end"
] | Stores the found prefix in the cache. | [
"Stores",
"the",
"found",
"prefix",
"in",
"the",
"cache",
"."
] | ec1ce2d104a1c1fe80a81e38559554dce211a678 | https://github.com/codez/render_inheritable/blob/ec1ce2d104a1c1fe80a81e38559554dce211a678/lib/render_inheritable.rb#L125-L134 | train |
codez/render_inheritable | lib/render_inheritable.rb | RenderInheritable.View.find_template_with_lookup | def find_template_with_lookup(name, prefix = nil, partial = false)
if prefix == controller_path
folder = controller.find_inheritable_template_folder(name, partial)
prefix = folder if folder
end
find_template_without_lookup(name, prefix, partial)
end | ruby | def find_template_with_lookup(name, prefix = nil, partial = false)
if prefix == controller_path
folder = controller.find_inheritable_template_folder(name, partial)
prefix = folder if folder
end
find_template_without_lookup(name, prefix, partial)
end | [
"def",
"find_template_with_lookup",
"(",
"name",
",",
"prefix",
"=",
"nil",
",",
"partial",
"=",
"false",
")",
"if",
"prefix",
"==",
"controller_path",
"folder",
"=",
"controller",
".",
"find_inheritable_template_folder",
"(",
"name",
",",
"partial",
")",
"prefix",
"=",
"folder",
"if",
"folder",
"end",
"find_template_without_lookup",
"(",
"name",
",",
"prefix",
",",
"partial",
")",
"end"
] | Perform a template lookup if the prefix corresponds to the current controller's path. | [
"Perform",
"a",
"template",
"lookup",
"if",
"the",
"prefix",
"corresponds",
"to",
"the",
"current",
"controller",
"s",
"path",
"."
] | ec1ce2d104a1c1fe80a81e38559554dce211a678 | https://github.com/codez/render_inheritable/blob/ec1ce2d104a1c1fe80a81e38559554dce211a678/lib/render_inheritable.rb#L145-L151 | train |
schrodingersbox/meter_cat | app/models/meter_cat/cache.rb | MeterCat.Cache.add | def add(name, value, created_on)
meter = fetch(name, nil)
# If the name isn't cached, cache it and return
return cache(name, value, created_on) unless meter
# If the cached value is for a different day, flush it, cache the new value and return
if meter.created_on != created_on
flush(name)
cache(name, value, created_on)
return
end
# Add the new value to the cached value and flush if expired
meter.value += value
flush(name) if meter.expired?
end | ruby | def add(name, value, created_on)
meter = fetch(name, nil)
# If the name isn't cached, cache it and return
return cache(name, value, created_on) unless meter
# If the cached value is for a different day, flush it, cache the new value and return
if meter.created_on != created_on
flush(name)
cache(name, value, created_on)
return
end
# Add the new value to the cached value and flush if expired
meter.value += value
flush(name) if meter.expired?
end | [
"def",
"add",
"(",
"name",
",",
"value",
",",
"created_on",
")",
"meter",
"=",
"fetch",
"(",
"name",
",",
"nil",
")",
"return",
"cache",
"(",
"name",
",",
"value",
",",
"created_on",
")",
"unless",
"meter",
"if",
"meter",
".",
"created_on",
"!=",
"created_on",
"flush",
"(",
"name",
")",
"cache",
"(",
"name",
",",
"value",
",",
"created_on",
")",
"return",
"end",
"meter",
".",
"value",
"+=",
"value",
"flush",
"(",
"name",
")",
"if",
"meter",
".",
"expired?",
"end"
] | Adds the given value to the hash
Flushes expired data to DB | [
"Adds",
"the",
"given",
"value",
"to",
"the",
"hash",
"Flushes",
"expired",
"data",
"to",
"DB"
] | b20d579749ef2facbf3b308d4fb39215a7eac2a1 | https://github.com/schrodingersbox/meter_cat/blob/b20d579749ef2facbf3b308d4fb39215a7eac2a1/app/models/meter_cat/cache.rb#L15-L31 | train |
schrodingersbox/meter_cat | app/models/meter_cat/cache.rb | MeterCat.Cache.cache | def cache(name, value, created_on)
meter = Meter.new(name: name, value: value, created_on: created_on, created_at: Time.now)
store(name, meter)
end | ruby | def cache(name, value, created_on)
meter = Meter.new(name: name, value: value, created_on: created_on, created_at: Time.now)
store(name, meter)
end | [
"def",
"cache",
"(",
"name",
",",
"value",
",",
"created_on",
")",
"meter",
"=",
"Meter",
".",
"new",
"(",
"name",
":",
"name",
",",
"value",
":",
"value",
",",
"created_on",
":",
"created_on",
",",
"created_at",
":",
"Time",
".",
"now",
")",
"store",
"(",
"name",
",",
"meter",
")",
"end"
] | Creates a new Meter and stores is in the hash | [
"Creates",
"a",
"new",
"Meter",
"and",
"stores",
"is",
"in",
"the",
"hash"
] | b20d579749ef2facbf3b308d4fb39215a7eac2a1 | https://github.com/schrodingersbox/meter_cat/blob/b20d579749ef2facbf3b308d4fb39215a7eac2a1/app/models/meter_cat/cache.rb#L35-L38 | train |
dpla/KriKri | lib/krikri/mapping_dsl.rb | Krikri.MappingDSL.add_child | def add_child(name, opts = {}, &block)
delete_property(name)
properties << ChildDeclaration.new(name, opts.delete(:class), opts, &block)
end | ruby | def add_child(name, opts = {}, &block)
delete_property(name)
properties << ChildDeclaration.new(name, opts.delete(:class), opts, &block)
end | [
"def",
"add_child",
"(",
"name",
",",
"opts",
"=",
"{",
"}",
",",
"&",
"block",
")",
"delete_property",
"(",
"name",
")",
"properties",
"<<",
"ChildDeclaration",
".",
"new",
"(",
"name",
",",
"opts",
".",
"delete",
"(",
":class",
")",
",",
"opts",
",",
"&",
"block",
")",
"end"
] | Add a ChildDeclaration to this mapping
@param [Symbol] name
@param [Hash] opts accepts options; expected options: :class
@return [ChildDeclaration] | [
"Add",
"a",
"ChildDeclaration",
"to",
"this",
"mapping"
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/mapping_dsl.rb#L50-L53 | train |
dpla/KriKri | lib/krikri/mapping_dsl.rb | Krikri.MappingDSL.add_property | def add_property(name, value = nil, &block)
delete_property(name)
properties << PropertyDeclaration.new(name, value, &block)
end | ruby | def add_property(name, value = nil, &block)
delete_property(name)
properties << PropertyDeclaration.new(name, value, &block)
end | [
"def",
"add_property",
"(",
"name",
",",
"value",
"=",
"nil",
",",
"&",
"block",
")",
"delete_property",
"(",
"name",
")",
"properties",
"<<",
"PropertyDeclaration",
".",
"new",
"(",
"name",
",",
"value",
",",
"&",
"block",
")",
"end"
] | Add a PropertyDeclaration to this mapping
@param [Symbol] name
@param [Hash] value ; defaults to nil
@return [ChildDeclaration] | [
"Add",
"a",
"PropertyDeclaration",
"to",
"this",
"mapping"
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/mapping_dsl.rb#L62-L65 | train |
iagox86/nesser | lib/nesser/packets/packet.rb | Nesser.Packet.to_bytes | def to_bytes()
packer = Packer.new()
full_flags = ((@qr << 15) & 0x8000) |
((@opcode << 11) & 0x7800) |
((@flags << 7) & 0x0780) |
((@rcode << 0) & 0x000F)
packer.pack('nnnnnn',
@trn_id, # trn_id
full_flags, # qr, opcode, flags, rcode
@questions.length(), # qdcount
@answers.length(), # ancount
0, # nscount (we don't handle)
0, # arcount (we don't handle)
)
questions.each do |q|
q.pack(packer)
end
answers.each do |a|
a.pack(packer)
end
return packer.get()
end | ruby | def to_bytes()
packer = Packer.new()
full_flags = ((@qr << 15) & 0x8000) |
((@opcode << 11) & 0x7800) |
((@flags << 7) & 0x0780) |
((@rcode << 0) & 0x000F)
packer.pack('nnnnnn',
@trn_id, # trn_id
full_flags, # qr, opcode, flags, rcode
@questions.length(), # qdcount
@answers.length(), # ancount
0, # nscount (we don't handle)
0, # arcount (we don't handle)
)
questions.each do |q|
q.pack(packer)
end
answers.each do |a|
a.pack(packer)
end
return packer.get()
end | [
"def",
"to_bytes",
"(",
")",
"packer",
"=",
"Packer",
".",
"new",
"(",
")",
"full_flags",
"=",
"(",
"(",
"@qr",
"<<",
"15",
")",
"&",
"0x8000",
")",
"|",
"(",
"(",
"@opcode",
"<<",
"11",
")",
"&",
"0x7800",
")",
"|",
"(",
"(",
"@flags",
"<<",
"7",
")",
"&",
"0x0780",
")",
"|",
"(",
"(",
"@rcode",
"<<",
"0",
")",
"&",
"0x000F",
")",
"packer",
".",
"pack",
"(",
"'nnnnnn'",
",",
"@trn_id",
",",
"full_flags",
",",
"@questions",
".",
"length",
"(",
")",
",",
"@answers",
".",
"length",
"(",
")",
",",
"0",
",",
"0",
",",
")",
"questions",
".",
"each",
"do",
"|",
"q",
"|",
"q",
".",
"pack",
"(",
"packer",
")",
"end",
"answers",
".",
"each",
"do",
"|",
"a",
"|",
"a",
".",
"pack",
"(",
"packer",
")",
"end",
"return",
"packer",
".",
"get",
"(",
")",
"end"
] | Serialize the packet to an array of bytes. | [
"Serialize",
"the",
"packet",
"to",
"an",
"array",
"of",
"bytes",
"."
] | 1d84cf1d0a9de3d6c5a9b418d0731b5214d14667 | https://github.com/iagox86/nesser/blob/1d84cf1d0a9de3d6c5a9b418d0731b5214d14667/lib/nesser/packets/packet.rb#L158-L184 | train |
rondale-sc/EspnRb | lib/espn_rb/headline.rb | EspnRb.Headline.get_results | def get_results(resource, method)
http = Net::HTTP.new("api.espn.com")
request = Net::HTTP::Get.new("/#{EspnRb::API_VERSION}#{resource}#{method}?apikey=#{@api_key}")
HeadlineResponse.new JSON.parse(http.request(request).body)
end | ruby | def get_results(resource, method)
http = Net::HTTP.new("api.espn.com")
request = Net::HTTP::Get.new("/#{EspnRb::API_VERSION}#{resource}#{method}?apikey=#{@api_key}")
HeadlineResponse.new JSON.parse(http.request(request).body)
end | [
"def",
"get_results",
"(",
"resource",
",",
"method",
")",
"http",
"=",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"\"api.espn.com\"",
")",
"request",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"\"/#{EspnRb::API_VERSION}#{resource}#{method}?apikey=#{@api_key}\"",
")",
"HeadlineResponse",
".",
"new",
"JSON",
".",
"parse",
"(",
"http",
".",
"request",
"(",
"request",
")",
".",
"body",
")",
"end"
] | The final request to ESPN api after all option parsing has been completed.
@return [HeadlineResponse] a headline response object. | [
"The",
"final",
"request",
"to",
"ESPN",
"api",
"after",
"all",
"option",
"parsing",
"has",
"been",
"completed",
"."
] | fd2723dd80a2f5cd26f9a62c24d4db06606b4693 | https://github.com/rondale-sc/EspnRb/blob/fd2723dd80a2f5cd26f9a62c24d4db06606b4693/lib/espn_rb/headline.rb#L29-L33 | train |
dpla/KriKri | lib/krikri/util/extended_date_parser.rb | Krikri::Util.ExtendedDateParser.parse | def parse(date_str, allow_interval = false)
str = preprocess(date_str.dup)
date = parse_interval(str) if allow_interval
date ||= parse_m_d_y(str)
date ||= Date.edtf(str.gsub('.', '-'))
date ||= partial_edtf(str)
date ||= decade_hyphen(str)
date ||= month_year(str)
date ||= decade_s(str)
date ||= hyphenated_partial_range(str)
date ||= parse_date(str)
# Only do this if certian letters are present to avoid infinite loops.
date ||= circa(str) if str.match(/[circabout]/i)
date = date.first if date.is_a? EDTF::Set
date || nil
end | ruby | def parse(date_str, allow_interval = false)
str = preprocess(date_str.dup)
date = parse_interval(str) if allow_interval
date ||= parse_m_d_y(str)
date ||= Date.edtf(str.gsub('.', '-'))
date ||= partial_edtf(str)
date ||= decade_hyphen(str)
date ||= month_year(str)
date ||= decade_s(str)
date ||= hyphenated_partial_range(str)
date ||= parse_date(str)
# Only do this if certian letters are present to avoid infinite loops.
date ||= circa(str) if str.match(/[circabout]/i)
date = date.first if date.is_a? EDTF::Set
date || nil
end | [
"def",
"parse",
"(",
"date_str",
",",
"allow_interval",
"=",
"false",
")",
"str",
"=",
"preprocess",
"(",
"date_str",
".",
"dup",
")",
"date",
"=",
"parse_interval",
"(",
"str",
")",
"if",
"allow_interval",
"date",
"||=",
"parse_m_d_y",
"(",
"str",
")",
"date",
"||=",
"Date",
".",
"edtf",
"(",
"str",
".",
"gsub",
"(",
"'.'",
",",
"'-'",
")",
")",
"date",
"||=",
"partial_edtf",
"(",
"str",
")",
"date",
"||=",
"decade_hyphen",
"(",
"str",
")",
"date",
"||=",
"month_year",
"(",
"str",
")",
"date",
"||=",
"decade_s",
"(",
"str",
")",
"date",
"||=",
"hyphenated_partial_range",
"(",
"str",
")",
"date",
"||=",
"parse_date",
"(",
"str",
")",
"date",
"||=",
"circa",
"(",
"str",
")",
"if",
"str",
".",
"match",
"(",
"/",
"/i",
")",
"date",
"=",
"date",
".",
"first",
"if",
"date",
".",
"is_a?",
"EDTF",
"::",
"Set",
"date",
"||",
"nil",
"end"
] | Attempts to parse a string into a valid EDTF or `Date` format.
- Attempts to split `#providedLabel` on '-', '/', '..', 'to', 'until', and
looks for EDTF and `Date.parse` patterns on either side, setting them to
`#begin` and `#end`. Both split and unsplit dates are parsed as follows:
- Attempts to parse `#providedLabel` as an EDTF interval and populates
begin and end with their respective values.
- Attempts to match to a number of regular expressions which specify
ranges informally.
- Attempts to parse `#providedLabel` as a single date value with
`Date.parse` and enters that value to both `#begin` and `#end`.
@param date_str [String] a string which may contain a date range
@param allow_interval [Boolean] a flag specifing whethe to use
#range_match to look for range values.
@return [Date, EDTF::Epoch, EDTF::Interval, nil] the date parsed or nil
@see http://www.loc.gov/standards/datetime/ | [
"Attempts",
"to",
"parse",
"a",
"string",
"into",
"a",
"valid",
"EDTF",
"or",
"Date",
"format",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/util/extended_date_parser.rb#L26-L41 | train |
dpla/KriKri | lib/krikri/util/extended_date_parser.rb | Krikri::Util.ExtendedDateParser.range_match | def range_match(str)
str = str.gsub('to', '-').gsub('until', '-')
regexp = %r{
([a-zA-Z]{0,3}\s?[\d\-\/\.xu\?\~a-zA-Z]*,?\s?
\d{3}[\d\-xs][s\d\-\.xu\?\~]*)
\s*[-\.]+\s*
([a-zA-Z]{0,3}\s?[\d\-\/\.xu\?\~a-zA-Z]*,?\s?
\d{3}[\d\-xs][s\d\-\.xu\?\~]*)
}x
regexp.match(str) do |m|
[m[1], m[2]]
end
end | ruby | def range_match(str)
str = str.gsub('to', '-').gsub('until', '-')
regexp = %r{
([a-zA-Z]{0,3}\s?[\d\-\/\.xu\?\~a-zA-Z]*,?\s?
\d{3}[\d\-xs][s\d\-\.xu\?\~]*)
\s*[-\.]+\s*
([a-zA-Z]{0,3}\s?[\d\-\/\.xu\?\~a-zA-Z]*,?\s?
\d{3}[\d\-xs][s\d\-\.xu\?\~]*)
}x
regexp.match(str) do |m|
[m[1], m[2]]
end
end | [
"def",
"range_match",
"(",
"str",
")",
"str",
"=",
"str",
".",
"gsub",
"(",
"'to'",
",",
"'-'",
")",
".",
"gsub",
"(",
"'until'",
",",
"'-'",
")",
"regexp",
"=",
"%r{",
"\\s",
"\\d",
"\\-",
"\\/",
"\\.",
"\\?",
"\\~",
"\\s",
"\\d",
"\\d",
"\\-",
"\\d",
"\\-",
"\\.",
"\\?",
"\\~",
"\\s",
"\\.",
"\\s",
"\\s",
"\\d",
"\\-",
"\\/",
"\\.",
"\\?",
"\\~",
"\\s",
"\\d",
"\\d",
"\\-",
"\\d",
"\\-",
"\\.",
"\\?",
"\\~",
"}x",
"regexp",
".",
"match",
"(",
"str",
")",
"do",
"|",
"m",
"|",
"[",
"m",
"[",
"1",
"]",
",",
"m",
"[",
"2",
"]",
"]",
"end",
"end"
] | Matches a wide variety of date ranges separated by '..' or '-'
@param str [String] a string which may contain a date range
@return [Array(String)] the begining and ending dates of an identified
range | [
"Matches",
"a",
"wide",
"variety",
"of",
"date",
"ranges",
"separated",
"by",
"..",
"or",
"-"
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/util/extended_date_parser.rb#L49-L61 | train |
dpla/KriKri | lib/krikri/util/extended_date_parser.rb | Krikri::Util.ExtendedDateParser.preprocess | def preprocess(str)
str.gsub!(/late/i, '')
str.gsub!(/early/i, '')
str.strip!
str.gsub!(/\s+/, ' ')
str.gsub!('0s', 'x') if str.match(/^[1-9]+0s$/)
str.gsub!('-', 'x') if str.match(/^[1-9]+\-+$/)
str
end | ruby | def preprocess(str)
str.gsub!(/late/i, '')
str.gsub!(/early/i, '')
str.strip!
str.gsub!(/\s+/, ' ')
str.gsub!('0s', 'x') if str.match(/^[1-9]+0s$/)
str.gsub!('-', 'x') if str.match(/^[1-9]+\-+$/)
str
end | [
"def",
"preprocess",
"(",
"str",
")",
"str",
".",
"gsub!",
"(",
"/",
"/i",
",",
"''",
")",
"str",
".",
"gsub!",
"(",
"/",
"/i",
",",
"''",
")",
"str",
".",
"strip!",
"str",
".",
"gsub!",
"(",
"/",
"\\s",
"/",
",",
"' '",
")",
"str",
".",
"gsub!",
"(",
"'0s'",
",",
"'x'",
")",
"if",
"str",
".",
"match",
"(",
"/",
"/",
")",
"str",
".",
"gsub!",
"(",
"'-'",
",",
"'x'",
")",
"if",
"str",
".",
"match",
"(",
"/",
"\\-",
"/",
")",
"str",
"end"
] | Preprocess the date string to remove extra whitespace and convert ad hoc
formatting to equivalent EDTF.
@todo should '-` be intepreted as 'x' or '?'
@see http://www.loc.gov/standards/datetime/pre-submission.html#maskedprecision | [
"Preprocess",
"the",
"date",
"string",
"to",
"remove",
"extra",
"whitespace",
"and",
"convert",
"ad",
"hoc",
"formatting",
"to",
"equivalent",
"EDTF",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/util/extended_date_parser.rb#L69-L77 | train |
dpla/KriKri | lib/krikri/util/extended_date_parser.rb | Krikri::Util.ExtendedDateParser.circa | def circa(str)
run = str.gsub!(/.*c[irca\.]*/i, '')
run ||= str.gsub!(/.*about/i, '')
date = parse(str) if run
return nil if date.nil?
# The EDTF grammar does not support uncertainty on masked precision dates
if date.respond_to? :uncertain!
date.uncertain!
elsif date.is_a? EDTF::Interval
# Interval uncertainty is scoped to the begin and end dates;
# to be safe, we mark both.
date.from = date.from.uncertain! if date.from.respond_to? :uncertain!
date.to = date.to.uncertain! if date.to.respond_to? :uncertain!
end
date
end | ruby | def circa(str)
run = str.gsub!(/.*c[irca\.]*/i, '')
run ||= str.gsub!(/.*about/i, '')
date = parse(str) if run
return nil if date.nil?
# The EDTF grammar does not support uncertainty on masked precision dates
if date.respond_to? :uncertain!
date.uncertain!
elsif date.is_a? EDTF::Interval
# Interval uncertainty is scoped to the begin and end dates;
# to be safe, we mark both.
date.from = date.from.uncertain! if date.from.respond_to? :uncertain!
date.to = date.to.uncertain! if date.to.respond_to? :uncertain!
end
date
end | [
"def",
"circa",
"(",
"str",
")",
"run",
"=",
"str",
".",
"gsub!",
"(",
"/",
"\\.",
"/i",
",",
"''",
")",
"run",
"||=",
"str",
".",
"gsub!",
"(",
"/",
"/i",
",",
"''",
")",
"date",
"=",
"parse",
"(",
"str",
")",
"if",
"run",
"return",
"nil",
"if",
"date",
".",
"nil?",
"if",
"date",
".",
"respond_to?",
":uncertain!",
"date",
".",
"uncertain!",
"elsif",
"date",
".",
"is_a?",
"EDTF",
"::",
"Interval",
"date",
".",
"from",
"=",
"date",
".",
"from",
".",
"uncertain!",
"if",
"date",
".",
"from",
".",
"respond_to?",
":uncertain!",
"date",
".",
"to",
"=",
"date",
".",
"to",
".",
"uncertain!",
"if",
"date",
".",
"to",
".",
"respond_to?",
":uncertain!",
"end",
"date",
"end"
] | Remove 'circa' or 'about' or variations and return an uncertian ETDF
dates.
@param str [String]
@return [Date, nil] an EDTF date, marked uncertian; or `nil`
@see #parse | [
"Remove",
"circa",
"or",
"about",
"or",
"variations",
"and",
"return",
"an",
"uncertian",
"ETDF",
"dates",
"."
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/lib/krikri/util/extended_date_parser.rb#L86-L104 | train |
railsmachine/shadow_puppet | lib/shadow_puppet/manifest.rb | ShadowPuppet.Manifest.execute | def execute(force=false)
return false if executed? && !force
evaluate_recipes
transaction = apply
rescue Exception => e
false
else
not transaction.any_failed?
ensure
@executed = true
end | ruby | def execute(force=false)
return false if executed? && !force
evaluate_recipes
transaction = apply
rescue Exception => e
false
else
not transaction.any_failed?
ensure
@executed = true
end | [
"def",
"execute",
"(",
"force",
"=",
"false",
")",
"return",
"false",
"if",
"executed?",
"&&",
"!",
"force",
"evaluate_recipes",
"transaction",
"=",
"apply",
"rescue",
"Exception",
"=>",
"e",
"false",
"else",
"not",
"transaction",
".",
"any_failed?",
"ensure",
"@executed",
"=",
"true",
"end"
] | Execute this manifest, applying all resources defined. Execute returns
true if successfull, and false if unsucessfull. By default, this
will only execute a manifest that has not already been executed?.
The +force+ argument, if true, removes this check. | [
"Execute",
"this",
"manifest",
"applying",
"all",
"resources",
"defined",
".",
"Execute",
"returns",
"true",
"if",
"successfull",
"and",
"false",
"if",
"unsucessfull",
".",
"By",
"default",
"this",
"will",
"only",
"execute",
"a",
"manifest",
"that",
"has",
"not",
"already",
"been",
"executed?",
".",
"The",
"+",
"force",
"+",
"argument",
"if",
"true",
"removes",
"this",
"check",
"."
] | 92f7f4e71b51ce017ff8bd63df9b7305a25c7b6a | https://github.com/railsmachine/shadow_puppet/blob/92f7f4e71b51ce017ff8bd63df9b7305a25c7b6a/lib/shadow_puppet/manifest.rb#L242-L252 | train |
railsmachine/shadow_puppet | lib/shadow_puppet/manifest.rb | ShadowPuppet.Manifest.execute! | def execute!(force=false)
return false if executed? && !force
evaluate_recipes
transaction = apply
rescue Exception => e
raise e
else
not transaction.any_failed?
ensure
@executed = true
end | ruby | def execute!(force=false)
return false if executed? && !force
evaluate_recipes
transaction = apply
rescue Exception => e
raise e
else
not transaction.any_failed?
ensure
@executed = true
end | [
"def",
"execute!",
"(",
"force",
"=",
"false",
")",
"return",
"false",
"if",
"executed?",
"&&",
"!",
"force",
"evaluate_recipes",
"transaction",
"=",
"apply",
"rescue",
"Exception",
"=>",
"e",
"raise",
"e",
"else",
"not",
"transaction",
".",
"any_failed?",
"ensure",
"@executed",
"=",
"true",
"end"
] | Execute this manifest, applying all resources defined. Execute returns
true if successfull, and raises an exception if not. By default, this
will only execute a manifest that has not already been executed?.
The +force+ argument, if true, removes this check. | [
"Execute",
"this",
"manifest",
"applying",
"all",
"resources",
"defined",
".",
"Execute",
"returns",
"true",
"if",
"successfull",
"and",
"raises",
"an",
"exception",
"if",
"not",
".",
"By",
"default",
"this",
"will",
"only",
"execute",
"a",
"manifest",
"that",
"has",
"not",
"already",
"been",
"executed?",
".",
"The",
"+",
"force",
"+",
"argument",
"if",
"true",
"removes",
"this",
"check",
"."
] | 92f7f4e71b51ce017ff8bd63df9b7305a25c7b6a | https://github.com/railsmachine/shadow_puppet/blob/92f7f4e71b51ce017ff8bd63df9b7305a25c7b6a/lib/shadow_puppet/manifest.rb#L258-L268 | train |
railsmachine/shadow_puppet | lib/shadow_puppet/manifest.rb | ShadowPuppet.Manifest.evaluate_recipes | def evaluate_recipes
self.class.recipes.each do |meth, args|
case arity = method(meth).arity
when 1, -1
send(meth, args)
else
send(meth)
end
end
end | ruby | def evaluate_recipes
self.class.recipes.each do |meth, args|
case arity = method(meth).arity
when 1, -1
send(meth, args)
else
send(meth)
end
end
end | [
"def",
"evaluate_recipes",
"self",
".",
"class",
".",
"recipes",
".",
"each",
"do",
"|",
"meth",
",",
"args",
"|",
"case",
"arity",
"=",
"method",
"(",
"meth",
")",
".",
"arity",
"when",
"1",
",",
"-",
"1",
"send",
"(",
"meth",
",",
"args",
")",
"else",
"send",
"(",
"meth",
")",
"end",
"end",
"end"
] | Evaluate the methods calls queued in self.recipes | [
"Evaluate",
"the",
"methods",
"calls",
"queued",
"in",
"self",
".",
"recipes"
] | 92f7f4e71b51ce017ff8bd63df9b7305a25c7b6a | https://github.com/railsmachine/shadow_puppet/blob/92f7f4e71b51ce017ff8bd63df9b7305a25c7b6a/lib/shadow_puppet/manifest.rb#L299-L308 | train |
railsmachine/shadow_puppet | lib/shadow_puppet/manifest.rb | ShadowPuppet.Manifest.reference | def reference(type, title, params = {})
Puppet::Resource.new(type.name.to_s.capitalize, title.to_s)
end | ruby | def reference(type, title, params = {})
Puppet::Resource.new(type.name.to_s.capitalize, title.to_s)
end | [
"def",
"reference",
"(",
"type",
",",
"title",
",",
"params",
"=",
"{",
"}",
")",
"Puppet",
"::",
"Resource",
".",
"new",
"(",
"type",
".",
"name",
".",
"to_s",
".",
"capitalize",
",",
"title",
".",
"to_s",
")",
"end"
] | Create a reference to another Puppet Resource. | [
"Create",
"a",
"reference",
"to",
"another",
"Puppet",
"Resource",
"."
] | 92f7f4e71b51ce017ff8bd63df9b7305a25c7b6a | https://github.com/railsmachine/shadow_puppet/blob/92f7f4e71b51ce017ff8bd63df9b7305a25c7b6a/lib/shadow_puppet/manifest.rb#L338-L340 | train |
railsmachine/shadow_puppet | lib/shadow_puppet/manifest.rb | ShadowPuppet.Manifest.add_resource | def add_resource(type, title, params = {})
catalog.add_resource(new_resource(type, title, params))
end | ruby | def add_resource(type, title, params = {})
catalog.add_resource(new_resource(type, title, params))
end | [
"def",
"add_resource",
"(",
"type",
",",
"title",
",",
"params",
"=",
"{",
"}",
")",
"catalog",
".",
"add_resource",
"(",
"new_resource",
"(",
"type",
",",
"title",
",",
"params",
")",
")",
"end"
] | Creates a new Puppet Resource and adds it to the Catalog. | [
"Creates",
"a",
"new",
"Puppet",
"Resource",
"and",
"adds",
"it",
"to",
"the",
"Catalog",
"."
] | 92f7f4e71b51ce017ff8bd63df9b7305a25c7b6a | https://github.com/railsmachine/shadow_puppet/blob/92f7f4e71b51ce017ff8bd63df9b7305a25c7b6a/lib/shadow_puppet/manifest.rb#L343-L345 | train |
dpla/KriKri | app/controllers/krikri/reports_controller.rb | Krikri.ReportsController.index | def index
@current_provider = params[:provider]
report = Krikri::ValidationReport.new
report.provider_id = @current_provider
@validation_reports = report.all
if @current_provider
@provider = Krikri::Provider.find(@current_provider)
@qa_reports = Array(Krikri::QAReport.find_by(provider: @current_provider))
else
@qa_reports = Krikri::QAReport.all
end
end | ruby | def index
@current_provider = params[:provider]
report = Krikri::ValidationReport.new
report.provider_id = @current_provider
@validation_reports = report.all
if @current_provider
@provider = Krikri::Provider.find(@current_provider)
@qa_reports = Array(Krikri::QAReport.find_by(provider: @current_provider))
else
@qa_reports = Krikri::QAReport.all
end
end | [
"def",
"index",
"@current_provider",
"=",
"params",
"[",
":provider",
"]",
"report",
"=",
"Krikri",
"::",
"ValidationReport",
".",
"new",
"report",
".",
"provider_id",
"=",
"@current_provider",
"@validation_reports",
"=",
"report",
".",
"all",
"if",
"@current_provider",
"@provider",
"=",
"Krikri",
"::",
"Provider",
".",
"find",
"(",
"@current_provider",
")",
"@qa_reports",
"=",
"Array",
"(",
"Krikri",
"::",
"QAReport",
".",
"find_by",
"(",
"provider",
":",
"@current_provider",
")",
")",
"else",
"@qa_reports",
"=",
"Krikri",
"::",
"QAReport",
".",
"all",
"end",
"end"
] | Renders the index view, giving `@validation_reports` and `@qa_reports`
for the specified provider. | [
"Renders",
"the",
"index",
"view",
"giving"
] | 0ac26e60ce1bba60caa40263a562796267cf833f | https://github.com/dpla/KriKri/blob/0ac26e60ce1bba60caa40263a562796267cf833f/app/controllers/krikri/reports_controller.rb#L11-L23 | train |
nbulaj/alpha_card | lib/alpha_card/resources/order.rb | AlphaCard.Order.attributes_for_request | def attributes_for_request(*)
attributes = filled_attributes.dup
billing = attributes.delete(:billing)
attributes.merge!(billing.attributes_for_request) if billing
shipping = attributes.delete(:shipping)
attributes.merge!(shipping.attributes_for_request) if shipping
super(attributes)
end | ruby | def attributes_for_request(*)
attributes = filled_attributes.dup
billing = attributes.delete(:billing)
attributes.merge!(billing.attributes_for_request) if billing
shipping = attributes.delete(:shipping)
attributes.merge!(shipping.attributes_for_request) if shipping
super(attributes)
end | [
"def",
"attributes_for_request",
"(",
"*",
")",
"attributes",
"=",
"filled_attributes",
".",
"dup",
"billing",
"=",
"attributes",
".",
"delete",
"(",
":billing",
")",
"attributes",
".",
"merge!",
"(",
"billing",
".",
"attributes_for_request",
")",
"if",
"billing",
"shipping",
"=",
"attributes",
".",
"delete",
"(",
":shipping",
")",
"attributes",
".",
"merge!",
"(",
"shipping",
".",
"attributes_for_request",
")",
"if",
"shipping",
"super",
"(",
"attributes",
")",
"end"
] | Overloaded method to return all the attributes from the
sale + billing + shipping objects.
@return [Hash]
Filled attributes with the original Alpha Card Services
transaction variables names.
@example
billing = AlphaCard::Billing.new(email: '[email protected]')
shipping = AlphaCard::Shipping.new(first_name: 'John', last_name: 'Doe')
order = AlphaCard::Order.new(id: '1', billing: billing, shipping: shipping)
order.attributes_for_request
#=> { orderid: '1', email: '[email protected]', shipping_first_name: 'John', shipping_last_name: 'Doe' } | [
"Overloaded",
"method",
"to",
"return",
"all",
"the",
"attributes",
"from",
"the",
"sale",
"+",
"billing",
"+",
"shipping",
"objects",
"."
] | 06fefc2dbbf0e7002fabb2be361b8d72a178f559 | https://github.com/nbulaj/alpha_card/blob/06fefc2dbbf0e7002fabb2be361b8d72a178f559/lib/alpha_card/resources/order.rb#L40-L50 | train |
mikemackintosh/ruby-easyrsa | lib/easyrsa/revoke.rb | EasyRSA.Revoke.revoke! | def revoke!(cakey=nil, crl=nil, next_update=36000)
if cakey.nil?
fail EasyRSA::Revoke::MissingCARootKey,
'Please provide the root CA cert for the CRL'
end
# Get cert details if it's in a file
unless cakey.is_a? OpenSSL::PKey::RSA
if cakey.include?('BEGIN RSA PRIVATE KEY')
cakey = OpenSSL::PKey::RSA.new cakey
else
begin
cakey = OpenSSL::PKey::RSA.new File.read cakey
rescue OpenSSL::PKey::RSAError => e
fail EasyRSA::Revoke::InvalidCARootPrivateKey,
'This is not a valid Private key file.'
end
end
end
# This is not a private key
unless cakey.private?
fail EasyRSA::Revoke::InvalidCARootPrivateKey,
'This is not a valid Private key file.'
end
# Create or load the CRL
unless crl.nil?
begin
@crl = OpenSSL::X509::CRL.new crl
rescue
fail EasyRSA::Revoke::InvalidCertificateRevocationList,
'Invalid CRL provided.'
end
else
@crl = OpenSSL::X509::CRL.new
end
# Add the revoked cert
@crl.add_revoked(@revoked)
# Needed CRL options
@crl.last_update = @revoked.time
@crl.next_update = Time.now + next_update
@crl.version = 1
# Update the CRL issuer
@crl.issuer = EasyRSA::gen_issuer
# Sign the CRL
@updated_crl = @crl.sign(cakey, OpenSSL::Digest::SHA256.new)
@updated_crl
end | ruby | def revoke!(cakey=nil, crl=nil, next_update=36000)
if cakey.nil?
fail EasyRSA::Revoke::MissingCARootKey,
'Please provide the root CA cert for the CRL'
end
# Get cert details if it's in a file
unless cakey.is_a? OpenSSL::PKey::RSA
if cakey.include?('BEGIN RSA PRIVATE KEY')
cakey = OpenSSL::PKey::RSA.new cakey
else
begin
cakey = OpenSSL::PKey::RSA.new File.read cakey
rescue OpenSSL::PKey::RSAError => e
fail EasyRSA::Revoke::InvalidCARootPrivateKey,
'This is not a valid Private key file.'
end
end
end
# This is not a private key
unless cakey.private?
fail EasyRSA::Revoke::InvalidCARootPrivateKey,
'This is not a valid Private key file.'
end
# Create or load the CRL
unless crl.nil?
begin
@crl = OpenSSL::X509::CRL.new crl
rescue
fail EasyRSA::Revoke::InvalidCertificateRevocationList,
'Invalid CRL provided.'
end
else
@crl = OpenSSL::X509::CRL.new
end
# Add the revoked cert
@crl.add_revoked(@revoked)
# Needed CRL options
@crl.last_update = @revoked.time
@crl.next_update = Time.now + next_update
@crl.version = 1
# Update the CRL issuer
@crl.issuer = EasyRSA::gen_issuer
# Sign the CRL
@updated_crl = @crl.sign(cakey, OpenSSL::Digest::SHA256.new)
@updated_crl
end | [
"def",
"revoke!",
"(",
"cakey",
"=",
"nil",
",",
"crl",
"=",
"nil",
",",
"next_update",
"=",
"36000",
")",
"if",
"cakey",
".",
"nil?",
"fail",
"EasyRSA",
"::",
"Revoke",
"::",
"MissingCARootKey",
",",
"'Please provide the root CA cert for the CRL'",
"end",
"unless",
"cakey",
".",
"is_a?",
"OpenSSL",
"::",
"PKey",
"::",
"RSA",
"if",
"cakey",
".",
"include?",
"(",
"'BEGIN RSA PRIVATE KEY'",
")",
"cakey",
"=",
"OpenSSL",
"::",
"PKey",
"::",
"RSA",
".",
"new",
"cakey",
"else",
"begin",
"cakey",
"=",
"OpenSSL",
"::",
"PKey",
"::",
"RSA",
".",
"new",
"File",
".",
"read",
"cakey",
"rescue",
"OpenSSL",
"::",
"PKey",
"::",
"RSAError",
"=>",
"e",
"fail",
"EasyRSA",
"::",
"Revoke",
"::",
"InvalidCARootPrivateKey",
",",
"'This is not a valid Private key file.'",
"end",
"end",
"end",
"unless",
"cakey",
".",
"private?",
"fail",
"EasyRSA",
"::",
"Revoke",
"::",
"InvalidCARootPrivateKey",
",",
"'This is not a valid Private key file.'",
"end",
"unless",
"crl",
".",
"nil?",
"begin",
"@crl",
"=",
"OpenSSL",
"::",
"X509",
"::",
"CRL",
".",
"new",
"crl",
"rescue",
"fail",
"EasyRSA",
"::",
"Revoke",
"::",
"InvalidCertificateRevocationList",
",",
"'Invalid CRL provided.'",
"end",
"else",
"@crl",
"=",
"OpenSSL",
"::",
"X509",
"::",
"CRL",
".",
"new",
"end",
"@crl",
".",
"add_revoked",
"(",
"@revoked",
")",
"@crl",
".",
"last_update",
"=",
"@revoked",
".",
"time",
"@crl",
".",
"next_update",
"=",
"Time",
".",
"now",
"+",
"next_update",
"@crl",
".",
"version",
"=",
"1",
"@crl",
".",
"issuer",
"=",
"EasyRSA",
"::",
"gen_issuer",
"@updated_crl",
"=",
"@crl",
".",
"sign",
"(",
"cakey",
",",
"OpenSSL",
"::",
"Digest",
"::",
"SHA256",
".",
"new",
")",
"@updated_crl",
"end"
] | Lets get revoking | [
"Lets",
"get",
"revoking"
] | a3ae2d420454e04f0c75e1a4e54caa7cda6fe29a | https://github.com/mikemackintosh/ruby-easyrsa/blob/a3ae2d420454e04f0c75e1a4e54caa7cda6fe29a/lib/easyrsa/revoke.rb#L35-L87 | train |
scryptmouse/dux | lib/dux/enum.rb | Dux.Enum.with_return_type | def with_return_type(value)
if value.nil? && allow_nil?
if allow_nil?
nil
else
# :nocov:
raise ArgumentError, "Cannot return `nil` without allow_nil: true"
# :nocov:
end
elsif @return_type == :symbol
value.to_sym
elsif @return_type == :string
value.to_s
end
end | ruby | def with_return_type(value)
if value.nil? && allow_nil?
if allow_nil?
nil
else
# :nocov:
raise ArgumentError, "Cannot return `nil` without allow_nil: true"
# :nocov:
end
elsif @return_type == :symbol
value.to_sym
elsif @return_type == :string
value.to_s
end
end | [
"def",
"with_return_type",
"(",
"value",
")",
"if",
"value",
".",
"nil?",
"&&",
"allow_nil?",
"if",
"allow_nil?",
"nil",
"else",
"raise",
"ArgumentError",
",",
"\"Cannot return `nil` without allow_nil: true\"",
"end",
"elsif",
"@return_type",
"==",
":symbol",
"value",
".",
"to_sym",
"elsif",
"@return_type",
"==",
":string",
"value",
".",
"to_s",
"end",
"end"
] | Ensure the value is returned with the correct type
@param [String, Symbol, nil] value
@return [String, Symbol, nil] | [
"Ensure",
"the",
"value",
"is",
"returned",
"with",
"the",
"correct",
"type"
] | 94a9b05fcfede36369e93d9c3a339365e55dc38a | https://github.com/scryptmouse/dux/blob/94a9b05fcfede36369e93d9c3a339365e55dc38a/lib/dux/enum.rb#L115-L129 | train |
scryptmouse/dux | lib/dux/enum.rb | Dux.Enum.valid_fallback? | def valid_fallback?(fallback)
return true if fallback.nil? && allow_nil?
return true if include? fallback
false
end | ruby | def valid_fallback?(fallback)
return true if fallback.nil? && allow_nil?
return true if include? fallback
false
end | [
"def",
"valid_fallback?",
"(",
"fallback",
")",
"return",
"true",
"if",
"fallback",
".",
"nil?",
"&&",
"allow_nil?",
"return",
"true",
"if",
"include?",
"fallback",
"false",
"end"
] | Check if the provided `fallback` is valid
@param [String, Symbol, nil] fallback | [
"Check",
"if",
"the",
"provided",
"fallback",
"is",
"valid"
] | 94a9b05fcfede36369e93d9c3a339365e55dc38a | https://github.com/scryptmouse/dux/blob/94a9b05fcfede36369e93d9c3a339365e55dc38a/lib/dux/enum.rb#L164-L169 | train |
scryptmouse/dux | lib/dux/enum.rb | Dux.Enum.set_default | def set_default(fallback)
if valid_fallback?(fallback) || fallback == NO_DEFAULT
@default = fallback
else
raise InvalidFallback, "Cannot set #{fallback.inspect} as default", caller
end
end | ruby | def set_default(fallback)
if valid_fallback?(fallback) || fallback == NO_DEFAULT
@default = fallback
else
raise InvalidFallback, "Cannot set #{fallback.inspect} as default", caller
end
end | [
"def",
"set_default",
"(",
"fallback",
")",
"if",
"valid_fallback?",
"(",
"fallback",
")",
"||",
"fallback",
"==",
"NO_DEFAULT",
"@default",
"=",
"fallback",
"else",
"raise",
"InvalidFallback",
",",
"\"Cannot set #{fallback.inspect} as default\"",
",",
"caller",
"end",
"end"
] | Set the default fallback value.
@param [String, Symbol, nil] fallback
@return [void] | [
"Set",
"the",
"default",
"fallback",
"value",
"."
] | 94a9b05fcfede36369e93d9c3a339365e55dc38a | https://github.com/scryptmouse/dux/blob/94a9b05fcfede36369e93d9c3a339365e55dc38a/lib/dux/enum.rb#L175-L181 | train |
dark-panda/active-profiling | lib/active-profiling/gc_statistics.rb | ActiveProfiling.GCStatistics.gc_statistics | def gc_statistics(*args)
options = Rails.application.config.active_profiling.gc_statistics.merge(args.extract_options!)
result, gc_report = gc_statistics_report(options) do
yield
end
ActiveSupport::Notifications.instrument('gc_statistics.active_profiling', {
:report => gc_report,
:title => options[:title] || args.first
})
result
end | ruby | def gc_statistics(*args)
options = Rails.application.config.active_profiling.gc_statistics.merge(args.extract_options!)
result, gc_report = gc_statistics_report(options) do
yield
end
ActiveSupport::Notifications.instrument('gc_statistics.active_profiling', {
:report => gc_report,
:title => options[:title] || args.first
})
result
end | [
"def",
"gc_statistics",
"(",
"*",
"args",
")",
"options",
"=",
"Rails",
".",
"application",
".",
"config",
".",
"active_profiling",
".",
"gc_statistics",
".",
"merge",
"(",
"args",
".",
"extract_options!",
")",
"result",
",",
"gc_report",
"=",
"gc_statistics_report",
"(",
"options",
")",
"do",
"yield",
"end",
"ActiveSupport",
"::",
"Notifications",
".",
"instrument",
"(",
"'gc_statistics.active_profiling'",
",",
"{",
":report",
"=>",
"gc_report",
",",
":title",
"=>",
"options",
"[",
":title",
"]",
"||",
"args",
".",
"first",
"}",
")",
"result",
"end"
] | Profiles a block, capturing information on the garbage collector. The
return value is an Array containing the result of the yielded block
and a String with a report on the profiling results.
Options:
* +:disable_gc+ - disables garbage collection for the duration of the
block and then renables it immediately afterwards. This allows you to
control when GC is run and see the results.
* +:title+ - a title to use for logging.
More options for this method can be found in the default settings,
located in ActiveProfiling::Railtie::DEFAULT_GC_STATISTICS_OPTIONS.
This method only works with versions of Ruby that implement
GC::Profiler or that have been patched to implement some additional
garbage collection statistics. In older versions, such as version
1.8.7, you can either use Ruby Enterprise Edition or patch your build
with the GC statistics patch found here:
http://blog.pluron.com/2008/02/memory-profilin.html | [
"Profiles",
"a",
"block",
"capturing",
"information",
"on",
"the",
"garbage",
"collector",
".",
"The",
"return",
"value",
"is",
"an",
"Array",
"containing",
"the",
"result",
"of",
"the",
"yielded",
"block",
"and",
"a",
"String",
"with",
"a",
"report",
"on",
"the",
"profiling",
"results",
"."
] | c9931255325444d0eab08e46ed4fa8a6d9618f1e | https://github.com/dark-panda/active-profiling/blob/c9931255325444d0eab08e46ed4fa8a6d9618f1e/lib/active-profiling/gc_statistics.rb#L88-L101 | train |
kschiess/zack | lib/zack/server.rb | Zack.Server.process_request | def process_request(control, sym, args)
instance = factory.call(control)
instance.send(sym, *args)
end | ruby | def process_request(control, sym, args)
instance = factory.call(control)
instance.send(sym, *args)
end | [
"def",
"process_request",
"(",
"control",
",",
"sym",
",",
"args",
")",
"instance",
"=",
"factory",
".",
"call",
"(",
"control",
")",
"instance",
".",
"send",
"(",
"sym",
",",
"*",
"args",
")",
"end"
] | Processes exactly one request, but doesn't define how the request gets
here.
@private | [
"Processes",
"exactly",
"one",
"request",
"but",
"doesn",
"t",
"define",
"how",
"the",
"request",
"gets",
"here",
"."
] | a9ac7cc672f1760961fae45bfe8f4be68b2ca7d9 | https://github.com/kschiess/zack/blob/a9ac7cc672f1760961fae45bfe8f4be68b2ca7d9/lib/zack/server.rb#L63-L67 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.