repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
ntalbott/mupnp | lib/UPnP.rb | UPnP.UPnP.totalPacketsSent | def totalPacketsSent()
joinThread()
v = MiniUPnP.UPNP_GetTotalPacketsSent(@urls.controlURL_CIF,
@data.servicetype_CIF);
if v < 0 then
raise UPnPException.new, "Error while retriving total packets sent."
end
return v
end | ruby | def totalPacketsSent()
joinThread()
v = MiniUPnP.UPNP_GetTotalPacketsSent(@urls.controlURL_CIF,
@data.servicetype_CIF);
if v < 0 then
raise UPnPException.new, "Error while retriving total packets sent."
end
return v
end | [
"def",
"totalPacketsSent",
"(",
")",
"joinThread",
"(",
")",
"v",
"=",
"MiniUPnP",
".",
"UPNP_GetTotalPacketsSent",
"(",
"@urls",
".",
"controlURL_CIF",
",",
"@data",
".",
"servicetype_CIF",
")",
";",
"if",
"v",
"<",
"0",
"then",
"raise",
"UPnPException",
".",
"new",
",",
"\"Error while retriving total packets sent.\"",
"end",
"return",
"v",
"end"
] | Total packets sent from the router to the external network. | [
"Total",
"packets",
"sent",
"from",
"the",
"router",
"to",
"the",
"external",
"network",
"."
] | c3c566cd2d7c9ecf1cb2baff253d116be163384d | https://github.com/ntalbott/mupnp/blob/c3c566cd2d7c9ecf1cb2baff253d116be163384d/lib/UPnP.rb#L229-L237 | train |
ntalbott/mupnp | lib/UPnP.rb | UPnP.UPnP.portMappings | def portMappings()
joinThread()
i, r = 0, 0
mappings = Array.new
while r == 0
rhost = getCString()
enabled = getCString()
duration = getCString()
description = getCString()
nport = getCString()
lport = getCString()
duration = getCString()
client = getCString()
protocol = getCString()
r = MiniUPnP.UPNP_GetGenericPortMappingEntry(@urls.controlURL,
@data.servicetype,i.to_s,nport,client,lport,
protocol,description,enabled,rhost,duration)
if r != 0 then
break;
end
i = i+1
mappings << PortMapping.new(client.rstrip,lport.rstrip.to_i,
nport.rstrip.to_i,protocol.rstrip,
description.rstrip,enabled.rstrip,
rhost.rstrip,duration.rstrip)
end
return mappings
end | ruby | def portMappings()
joinThread()
i, r = 0, 0
mappings = Array.new
while r == 0
rhost = getCString()
enabled = getCString()
duration = getCString()
description = getCString()
nport = getCString()
lport = getCString()
duration = getCString()
client = getCString()
protocol = getCString()
r = MiniUPnP.UPNP_GetGenericPortMappingEntry(@urls.controlURL,
@data.servicetype,i.to_s,nport,client,lport,
protocol,description,enabled,rhost,duration)
if r != 0 then
break;
end
i = i+1
mappings << PortMapping.new(client.rstrip,lport.rstrip.to_i,
nport.rstrip.to_i,protocol.rstrip,
description.rstrip,enabled.rstrip,
rhost.rstrip,duration.rstrip)
end
return mappings
end | [
"def",
"portMappings",
"(",
")",
"joinThread",
"(",
")",
"i",
",",
"r",
"=",
"0",
",",
"0",
"mappings",
"=",
"Array",
".",
"new",
"while",
"r",
"==",
"0",
"rhost",
"=",
"getCString",
"(",
")",
"enabled",
"=",
"getCString",
"(",
")",
"duration",
"=",
"getCString",
"(",
")",
"description",
"=",
"getCString",
"(",
")",
"nport",
"=",
"getCString",
"(",
")",
"lport",
"=",
"getCString",
"(",
")",
"duration",
"=",
"getCString",
"(",
")",
"client",
"=",
"getCString",
"(",
")",
"protocol",
"=",
"getCString",
"(",
")",
"r",
"=",
"MiniUPnP",
".",
"UPNP_GetGenericPortMappingEntry",
"(",
"@urls",
".",
"controlURL",
",",
"@data",
".",
"servicetype",
",",
"i",
".",
"to_s",
",",
"nport",
",",
"client",
",",
"lport",
",",
"protocol",
",",
"description",
",",
"enabled",
",",
"rhost",
",",
"duration",
")",
"if",
"r",
"!=",
"0",
"then",
"break",
";",
"end",
"i",
"=",
"i",
"+",
"1",
"mappings",
"<<",
"PortMapping",
".",
"new",
"(",
"client",
".",
"rstrip",
",",
"lport",
".",
"rstrip",
".",
"to_i",
",",
"nport",
".",
"rstrip",
".",
"to_i",
",",
"protocol",
".",
"rstrip",
",",
"description",
".",
"rstrip",
",",
"enabled",
".",
"rstrip",
",",
"rhost",
".",
"rstrip",
",",
"duration",
".",
"rstrip",
")",
"end",
"return",
"mappings",
"end"
] | An array of mappings registered on the router | [
"An",
"array",
"of",
"mappings",
"registered",
"on",
"the",
"router"
] | c3c566cd2d7c9ecf1cb2baff253d116be163384d | https://github.com/ntalbott/mupnp/blob/c3c566cd2d7c9ecf1cb2baff253d116be163384d/lib/UPnP.rb#L275-L303 | train |
ntalbott/mupnp | lib/UPnP.rb | UPnP.UPnP.portMapping | def portMapping(nport,proto)
checkProto(proto)
checkPort(nport)
if nport.to_i == 0 then
raise ArgumentError, "Port must be an int value and greater then 0."
end
joinThread()
client = getCString()
lport = getCString()
if MiniUPnP.UPNP_GetSpecificPortMappingEntry(@urls.controlURL,
@data.servicetype, nport.to_s,proto,
client,lport) != 0 then
raise UPnPException.new, "Error while retriving the port mapping."
end
return client.rstrip, lport.rstrip.to_i
end | ruby | def portMapping(nport,proto)
checkProto(proto)
checkPort(nport)
if nport.to_i == 0 then
raise ArgumentError, "Port must be an int value and greater then 0."
end
joinThread()
client = getCString()
lport = getCString()
if MiniUPnP.UPNP_GetSpecificPortMappingEntry(@urls.controlURL,
@data.servicetype, nport.to_s,proto,
client,lport) != 0 then
raise UPnPException.new, "Error while retriving the port mapping."
end
return client.rstrip, lport.rstrip.to_i
end | [
"def",
"portMapping",
"(",
"nport",
",",
"proto",
")",
"checkProto",
"(",
"proto",
")",
"checkPort",
"(",
"nport",
")",
"if",
"nport",
".",
"to_i",
"==",
"0",
"then",
"raise",
"ArgumentError",
",",
"\"Port must be an int value and greater then 0.\"",
"end",
"joinThread",
"(",
")",
"client",
"=",
"getCString",
"(",
")",
"lport",
"=",
"getCString",
"(",
")",
"if",
"MiniUPnP",
".",
"UPNP_GetSpecificPortMappingEntry",
"(",
"@urls",
".",
"controlURL",
",",
"@data",
".",
"servicetype",
",",
"nport",
".",
"to_s",
",",
"proto",
",",
"client",
",",
"lport",
")",
"!=",
"0",
"then",
"raise",
"UPnPException",
".",
"new",
",",
"\"Error while retriving the port mapping.\"",
"end",
"return",
"client",
".",
"rstrip",
",",
"lport",
".",
"rstrip",
".",
"to_i",
"end"
] | Get the mapping registered for a specific port and protocol | [
"Get",
"the",
"mapping",
"registered",
"for",
"a",
"specific",
"port",
"and",
"protocol"
] | c3c566cd2d7c9ecf1cb2baff253d116be163384d | https://github.com/ntalbott/mupnp/blob/c3c566cd2d7c9ecf1cb2baff253d116be163384d/lib/UPnP.rb#L306-L321 | train |
ntalbott/mupnp | lib/UPnP.rb | UPnP.UPnP.deletePortMapping | def deletePortMapping(nport,proto)
checkProto(proto)
checkPort(nport)
joinThread()
r = MiniUPnP.UPNP_DeletePortMapping(@urls.controlURL,@data.servicetype,
nport.to_s,proto)
if r != 0 then
raise UPnPException.new , "Failed delete mapping: #{code2error(r)}."
end
end | ruby | def deletePortMapping(nport,proto)
checkProto(proto)
checkPort(nport)
joinThread()
r = MiniUPnP.UPNP_DeletePortMapping(@urls.controlURL,@data.servicetype,
nport.to_s,proto)
if r != 0 then
raise UPnPException.new , "Failed delete mapping: #{code2error(r)}."
end
end | [
"def",
"deletePortMapping",
"(",
"nport",
",",
"proto",
")",
"checkProto",
"(",
"proto",
")",
"checkPort",
"(",
"nport",
")",
"joinThread",
"(",
")",
"r",
"=",
"MiniUPnP",
".",
"UPNP_DeletePortMapping",
"(",
"@urls",
".",
"controlURL",
",",
"@data",
".",
"servicetype",
",",
"nport",
".",
"to_s",
",",
"proto",
")",
"if",
"r",
"!=",
"0",
"then",
"raise",
"UPnPException",
".",
"new",
",",
"\"Failed delete mapping: #{code2error(r)}.\"",
"end",
"end"
] | Delete the port mapping for specified network port and protocol | [
"Delete",
"the",
"port",
"mapping",
"for",
"specified",
"network",
"port",
"and",
"protocol"
] | c3c566cd2d7c9ecf1cb2baff253d116be163384d | https://github.com/ntalbott/mupnp/blob/c3c566cd2d7c9ecf1cb2baff253d116be163384d/lib/UPnP.rb#L341-L350 | train |
ntalbott/mupnp | lib/UPnP.rb | UPnP.UPnP.checkProto | def checkProto(proto)
if proto != Protocol::UDP && proto != Protocol::TCP then
raise ArgumentError, "Unknown protocol #{proto}, only Protocol::TCP and Protocol::UDP are valid."
end
end | ruby | def checkProto(proto)
if proto != Protocol::UDP && proto != Protocol::TCP then
raise ArgumentError, "Unknown protocol #{proto}, only Protocol::TCP and Protocol::UDP are valid."
end
end | [
"def",
"checkProto",
"(",
"proto",
")",
"if",
"proto",
"!=",
"Protocol",
"::",
"UDP",
"&&",
"proto",
"!=",
"Protocol",
"::",
"TCP",
"then",
"raise",
"ArgumentError",
",",
"\"Unknown protocol #{proto}, only Protocol::TCP and Protocol::UDP are valid.\"",
"end",
"end"
] | Check that the protocol is a correct value | [
"Check",
"that",
"the",
"protocol",
"is",
"a",
"correct",
"value"
] | c3c566cd2d7c9ecf1cb2baff253d116be163384d | https://github.com/ntalbott/mupnp/blob/c3c566cd2d7c9ecf1cb2baff253d116be163384d/lib/UPnP.rb#L367-L371 | train |
bilus/akasha | lib/akasha/command_router.rb | Akasha.CommandRouter.register | def register(command, aggregate_class = nil, &block)
raise ArgumentError, 'Pass either aggregate class or block' if aggregate_class && block
handler = aggregate_class || block
@routes[command] = handler
end | ruby | def register(command, aggregate_class = nil, &block)
raise ArgumentError, 'Pass either aggregate class or block' if aggregate_class && block
handler = aggregate_class || block
@routes[command] = handler
end | [
"def",
"register",
"(",
"command",
",",
"aggregate_class",
"=",
"nil",
",",
"&",
"block",
")",
"raise",
"ArgumentError",
",",
"'Pass either aggregate class or block'",
"if",
"aggregate_class",
"&&",
"block",
"handler",
"=",
"aggregate_class",
"||",
"block",
"@routes",
"[",
"command",
"]",
"=",
"handler",
"end"
] | Registers a handler.
As a result, when `#route!` is called for that command, the aggregate will be
loaded from repository, the command will be sent to the object to invoke the
object's method, and finally the aggregate will be saved. | [
"Registers",
"a",
"handler",
"."
] | 5fadefc249f520ae909b762956ac23a6f916b021 | https://github.com/bilus/akasha/blob/5fadefc249f520ae909b762956ac23a6f916b021/lib/akasha/command_router.rb#L18-L22 | train |
bilus/akasha | lib/akasha/command_router.rb | Akasha.CommandRouter.route! | def route!(command, aggregate_id, options = {}, **data)
handler = @routes[command]
case handler
when Class
transactor = options.fetch(:transactor, default_transactor)
transactor.call(handler, command, aggregate_id, options, **data)
when handler.respond_to?(:call)
handler.call(command, aggregate_id, options, **data)
when Proc
handler.call(command, aggregate_id, options, **data)
when nil
raise HandlerNotFoundError, "Handler for command #{command.inspect} not found"
else
raise UnsupportedHandlerError, "Unsupported command handler #{handler.inspect}"
end
end | ruby | def route!(command, aggregate_id, options = {}, **data)
handler = @routes[command]
case handler
when Class
transactor = options.fetch(:transactor, default_transactor)
transactor.call(handler, command, aggregate_id, options, **data)
when handler.respond_to?(:call)
handler.call(command, aggregate_id, options, **data)
when Proc
handler.call(command, aggregate_id, options, **data)
when nil
raise HandlerNotFoundError, "Handler for command #{command.inspect} not found"
else
raise UnsupportedHandlerError, "Unsupported command handler #{handler.inspect}"
end
end | [
"def",
"route!",
"(",
"command",
",",
"aggregate_id",
",",
"options",
"=",
"{",
"}",
",",
"**",
"data",
")",
"handler",
"=",
"@routes",
"[",
"command",
"]",
"case",
"handler",
"when",
"Class",
"transactor",
"=",
"options",
".",
"fetch",
"(",
":transactor",
",",
"default_transactor",
")",
"transactor",
".",
"call",
"(",
"handler",
",",
"command",
",",
"aggregate_id",
",",
"options",
",",
"**",
"data",
")",
"when",
"handler",
".",
"respond_to?",
"(",
":call",
")",
"handler",
".",
"call",
"(",
"command",
",",
"aggregate_id",
",",
"options",
",",
"**",
"data",
")",
"when",
"Proc",
"handler",
".",
"call",
"(",
"command",
",",
"aggregate_id",
",",
"options",
",",
"**",
"data",
")",
"when",
"nil",
"raise",
"HandlerNotFoundError",
",",
"\"Handler for command #{command.inspect} not found\"",
"else",
"raise",
"UnsupportedHandlerError",
",",
"\"Unsupported command handler #{handler.inspect}\"",
"end",
"end"
] | Routes a command to the registered target.
Raises `NotFoundError` if no corresponding target can be found.
Arguments:
- command - name of the command
- aggregate_id - aggregate id
- options - flags:
- transactor - transactor instance to replace the default one (`OptimisticTransactor`);
See docs for `OptimisticTransactor` for a list of additional supported options. | [
"Routes",
"a",
"command",
"to",
"the",
"registered",
"target",
".",
"Raises",
"NotFoundError",
"if",
"no",
"corresponding",
"target",
"can",
"be",
"found",
"."
] | 5fadefc249f520ae909b762956ac23a6f916b021 | https://github.com/bilus/akasha/blob/5fadefc249f520ae909b762956ac23a6f916b021/lib/akasha/command_router.rb#L33-L48 | train |
emancu/ork | lib/ork/model/class_methods.rb | Ork::Model.ClassMethods.attribute | def attribute(name, options = {})
attributes << name unless attributes.include?(name)
defaults[name] = options[:default] if options.has_key?(:default)
if options.has_key?(:accessors)
to_define = Array(options[:accessors]) & accessor_options
else # Default methods
to_define = [:reader, :writer]
end
to_define.each{|m| send("#{m}_for", name) }
end | ruby | def attribute(name, options = {})
attributes << name unless attributes.include?(name)
defaults[name] = options[:default] if options.has_key?(:default)
if options.has_key?(:accessors)
to_define = Array(options[:accessors]) & accessor_options
else # Default methods
to_define = [:reader, :writer]
end
to_define.each{|m| send("#{m}_for", name) }
end | [
"def",
"attribute",
"(",
"name",
",",
"options",
"=",
"{",
"}",
")",
"attributes",
"<<",
"name",
"unless",
"attributes",
".",
"include?",
"(",
"name",
")",
"defaults",
"[",
"name",
"]",
"=",
"options",
"[",
":default",
"]",
"if",
"options",
".",
"has_key?",
"(",
":default",
")",
"if",
"options",
".",
"has_key?",
"(",
":accessors",
")",
"to_define",
"=",
"Array",
"(",
"options",
"[",
":accessors",
"]",
")",
"&",
"accessor_options",
"else",
"to_define",
"=",
"[",
":reader",
",",
":writer",
"]",
"end",
"to_define",
".",
"each",
"{",
"|",
"m",
"|",
"send",
"(",
"\"#{m}_for\"",
",",
"name",
")",
"}",
"end"
] | Declares persisted attributes.
All attributes are stored on the Riak hash.
Example:
class User
include Ork::Document
attribute :name
end
# It's the same as:
class User
include Ork::Document
def name
@attributes[:name]
end
def name=(name)
@attributes[:name] = name
end
end | [
"Declares",
"persisted",
"attributes",
".",
"All",
"attributes",
"are",
"stored",
"on",
"the",
"Riak",
"hash",
"."
] | 83b2deaef0e790d90f98c031f254b5f438b19edf | https://github.com/emancu/ork/blob/83b2deaef0e790d90f98c031f254b5f438b19edf/lib/ork/model/class_methods.rb#L83-L94 | train |
emancu/ork | lib/ork/model/class_methods.rb | Ork::Model.ClassMethods.index | def index(name)
indices[name] = Index.new(name) unless indices.include?(name)
end | ruby | def index(name)
indices[name] = Index.new(name) unless indices.include?(name)
end | [
"def",
"index",
"(",
"name",
")",
"indices",
"[",
"name",
"]",
"=",
"Index",
".",
"new",
"(",
"name",
")",
"unless",
"indices",
".",
"include?",
"(",
"name",
")",
"end"
] | Index any attribute on your model. Once you index an attribute,
you can use it in `find` statements. | [
"Index",
"any",
"attribute",
"on",
"your",
"model",
".",
"Once",
"you",
"index",
"an",
"attribute",
"you",
"can",
"use",
"it",
"in",
"find",
"statements",
"."
] | 83b2deaef0e790d90f98c031f254b5f438b19edf | https://github.com/emancu/ork/blob/83b2deaef0e790d90f98c031f254b5f438b19edf/lib/ork/model/class_methods.rb#L99-L101 | train |
gzigzigzeo/stateful_link | lib/stateful_link/action_any_of.rb | StatefulLink.ActionAnyOf.action_any_of? | def action_any_of?(*actions)
actions.any? do |sub_ca|
if sub_ca.present?
sub_controller, sub_action = extract_controller_and_action(sub_ca)
((self.controller_path == sub_controller) || (sub_controller.blank?)) && (self.action_name == sub_action || (sub_action == '' || sub_action == '*'))
end
end
end | ruby | def action_any_of?(*actions)
actions.any? do |sub_ca|
if sub_ca.present?
sub_controller, sub_action = extract_controller_and_action(sub_ca)
((self.controller_path == sub_controller) || (sub_controller.blank?)) && (self.action_name == sub_action || (sub_action == '' || sub_action == '*'))
end
end
end | [
"def",
"action_any_of?",
"(",
"*",
"actions",
")",
"actions",
".",
"any?",
"do",
"|",
"sub_ca",
"|",
"if",
"sub_ca",
".",
"present?",
"sub_controller",
",",
"sub_action",
"=",
"extract_controller_and_action",
"(",
"sub_ca",
")",
"(",
"(",
"self",
".",
"controller_path",
"==",
"sub_controller",
")",
"||",
"(",
"sub_controller",
".",
"blank?",
")",
")",
"&&",
"(",
"self",
".",
"action_name",
"==",
"sub_action",
"||",
"(",
"sub_action",
"==",
"''",
"||",
"sub_action",
"==",
"'*'",
")",
")",
"end",
"end",
"end"
] | Returns true if current controller and action names equals to any of passed.
Asterik as action name matches all controller's action.
Examples:
<%= "we are in PostsController::index" if action_any_of?("posts#index") %>
<%= "we are not in PostsController::index" unless action_any_of?("posts#index") %>
<% if action_any_of?("posts#index", "messages#index") %>
we are in PostsController or in MessagesController
<% end %> | [
"Returns",
"true",
"if",
"current",
"controller",
"and",
"action",
"names",
"equals",
"to",
"any",
"of",
"passed",
".",
"Asterik",
"as",
"action",
"name",
"matches",
"all",
"controller",
"s",
"action",
"."
] | e9073fcb3523bb15e17cc1bf40ca813dd0fd7659 | https://github.com/gzigzigzeo/stateful_link/blob/e9073fcb3523bb15e17cc1bf40ca813dd0fd7659/lib/stateful_link/action_any_of.rb#L21-L28 | train |
gzigzigzeo/stateful_link | lib/stateful_link/action_any_of.rb | StatefulLink.ActionAnyOf.extract_controller_and_action | def extract_controller_and_action(ca)
raise ArgumentError, "Pass the string" if ca.nil?
slash_pos = ca.rindex('#')
raise ArgumentError, "Invalid action: #{ca}" if slash_pos.nil?
controller = ca[0, slash_pos]
action = ca[slash_pos+1..-1] || ""
raise ArgumentError, "Invalid action or controller" if action.nil?
[controller, action]
end | ruby | def extract_controller_and_action(ca)
raise ArgumentError, "Pass the string" if ca.nil?
slash_pos = ca.rindex('#')
raise ArgumentError, "Invalid action: #{ca}" if slash_pos.nil?
controller = ca[0, slash_pos]
action = ca[slash_pos+1..-1] || ""
raise ArgumentError, "Invalid action or controller" if action.nil?
[controller, action]
end | [
"def",
"extract_controller_and_action",
"(",
"ca",
")",
"raise",
"ArgumentError",
",",
"\"Pass the string\"",
"if",
"ca",
".",
"nil?",
"slash_pos",
"=",
"ca",
".",
"rindex",
"(",
"'#'",
")",
"raise",
"ArgumentError",
",",
"\"Invalid action: #{ca}\"",
"if",
"slash_pos",
".",
"nil?",
"controller",
"=",
"ca",
"[",
"0",
",",
"slash_pos",
"]",
"action",
"=",
"ca",
"[",
"slash_pos",
"+",
"1",
"..",
"-",
"1",
"]",
"||",
"\"\"",
"raise",
"ArgumentError",
",",
"\"Invalid action or controller\"",
"if",
"action",
".",
"nil?",
"[",
"controller",
",",
"action",
"]",
"end"
] | Extracts controller and action names from a string.
Examples:
extract_controller_and_action("posts#index") # ["posts", "index"]
extract_controller_and_action("admin/posts#index") # ["admin/posts", "index"]
extract_controller_and_action("admin/posts#index") # raises ArgumentError | [
"Extracts",
"controller",
"and",
"action",
"names",
"from",
"a",
"string",
"."
] | e9073fcb3523bb15e17cc1bf40ca813dd0fd7659 | https://github.com/gzigzigzeo/stateful_link/blob/e9073fcb3523bb15e17cc1bf40ca813dd0fd7659/lib/stateful_link/action_any_of.rb#L38-L47 | train |
bumi/validation_rage | lib/validation_rage/fnord_metric_notifier.rb | ValidationRage.FnordMetricNotifier.call | def call(event_name, payload)
return unless data_present?(payload)
# global validation error event
self.fnord.event({
:_type => event_name,
:payload => payload
})
# class level validation error event
self.fnord.event({
:_type => "validation_rage_error.#{payload.keys.first.to_s.downcase}",
:payload => payload.values.first.keys
})
# two events are enough for now
## attribute level validation error event
#payload.values.first.each do |attribute, error_messages|
# self.fnord.event({
# :_type => "validation_rage_error.#{payload.keys.first.to_s.downcase}.#{attribute}",
# :payload => error_messages
# })
#end
end | ruby | def call(event_name, payload)
return unless data_present?(payload)
# global validation error event
self.fnord.event({
:_type => event_name,
:payload => payload
})
# class level validation error event
self.fnord.event({
:_type => "validation_rage_error.#{payload.keys.first.to_s.downcase}",
:payload => payload.values.first.keys
})
# two events are enough for now
## attribute level validation error event
#payload.values.first.each do |attribute, error_messages|
# self.fnord.event({
# :_type => "validation_rage_error.#{payload.keys.first.to_s.downcase}.#{attribute}",
# :payload => error_messages
# })
#end
end | [
"def",
"call",
"(",
"event_name",
",",
"payload",
")",
"return",
"unless",
"data_present?",
"(",
"payload",
")",
"self",
".",
"fnord",
".",
"event",
"(",
"{",
":_type",
"=>",
"event_name",
",",
":payload",
"=>",
"payload",
"}",
")",
"self",
".",
"fnord",
".",
"event",
"(",
"{",
":_type",
"=>",
"\"validation_rage_error.#{payload.keys.first.to_s.downcase}\"",
",",
":payload",
"=>",
"payload",
".",
"values",
".",
"first",
".",
"keys",
"}",
")",
"end"
] | I guess this is toooooo sloooow but anyhow let's play with it | [
"I",
"guess",
"this",
"is",
"toooooo",
"sloooow",
"but",
"anyhow",
"let",
"s",
"play",
"with",
"it"
] | 0680444bac70e1d9ab42a7b421a09e8ba9d0d7c6 | https://github.com/bumi/validation_rage/blob/0680444bac70e1d9ab42a7b421a09e8ba9d0d7c6/lib/validation_rage/fnord_metric_notifier.rb#L11-L32 | train |
vidibus/vidibus-tempfile | lib/vidibus/tempfile.rb | Vidibus.Tempfile.make_tmpname | def make_tmpname(basename, n)
extension = File.extname(basename)
sprintf("%s,%d,%d%s", File.basename(basename, extension), $$, n.to_i, extension)
end | ruby | def make_tmpname(basename, n)
extension = File.extname(basename)
sprintf("%s,%d,%d%s", File.basename(basename, extension), $$, n.to_i, extension)
end | [
"def",
"make_tmpname",
"(",
"basename",
",",
"n",
")",
"extension",
"=",
"File",
".",
"extname",
"(",
"basename",
")",
"sprintf",
"(",
"\"%s,%d,%d%s\"",
",",
"File",
".",
"basename",
"(",
"basename",
",",
"extension",
")",
",",
"$$",
",",
"n",
".",
"to_i",
",",
"extension",
")",
"end"
] | Replaces Tempfile's +make_tmpname+ with one that honors file extensions.
Copied from Paperclip | [
"Replaces",
"Tempfile",
"s",
"+",
"make_tmpname",
"+",
"with",
"one",
"that",
"honors",
"file",
"extensions",
".",
"Copied",
"from",
"Paperclip"
] | 3c06359ccb28cfc36a4dfcbb856d257a18df7c95 | https://github.com/vidibus/vidibus-tempfile/blob/3c06359ccb28cfc36a4dfcbb856d257a18df7c95/lib/vidibus/tempfile.rb#L34-L37 | train |
kennon/litmos-client | lib/litmos_client.rb | LitmosClient.API.get | def get(path, params={})
dont_parse_response = params.delete(:dont_parse_response)
options = {
:content_type => :json,
:accept => :json,
:params => params.merge(:apikey => @api_key, :source => @source)
}
RestClient.get("#{@litmosURL}/#{path}", options) do |response, request, result|
case response.code
when 200, 201
# 200 Success. User/Course etc updated, deleted or retrieved
# 201 Success. User/Course etc created
if response.blank?
true
else
if dont_parse_response
response
else
parse_response(response)
end
end
when 404 # 404 Not Found. The User/Course etc that you requested does not exist
raise NotFound.new(response)
else
# 400 Bad Request. Check that your Uri and request body is well formed
# 403 Forbidden. Check your API key, HTTPS setting, Source parameter etc
# 409 Conflict. Often occurs when trying to create an item that already exists
raise ApiError.new(response)
end
end
end | ruby | def get(path, params={})
dont_parse_response = params.delete(:dont_parse_response)
options = {
:content_type => :json,
:accept => :json,
:params => params.merge(:apikey => @api_key, :source => @source)
}
RestClient.get("#{@litmosURL}/#{path}", options) do |response, request, result|
case response.code
when 200, 201
# 200 Success. User/Course etc updated, deleted or retrieved
# 201 Success. User/Course etc created
if response.blank?
true
else
if dont_parse_response
response
else
parse_response(response)
end
end
when 404 # 404 Not Found. The User/Course etc that you requested does not exist
raise NotFound.new(response)
else
# 400 Bad Request. Check that your Uri and request body is well formed
# 403 Forbidden. Check your API key, HTTPS setting, Source parameter etc
# 409 Conflict. Often occurs when trying to create an item that already exists
raise ApiError.new(response)
end
end
end | [
"def",
"get",
"(",
"path",
",",
"params",
"=",
"{",
"}",
")",
"dont_parse_response",
"=",
"params",
".",
"delete",
"(",
":dont_parse_response",
")",
"options",
"=",
"{",
":content_type",
"=>",
":json",
",",
":accept",
"=>",
":json",
",",
":params",
"=>",
"params",
".",
"merge",
"(",
":apikey",
"=>",
"@api_key",
",",
":source",
"=>",
"@source",
")",
"}",
"RestClient",
".",
"get",
"(",
"\"#{@litmosURL}/#{path}\"",
",",
"options",
")",
"do",
"|",
"response",
",",
"request",
",",
"result",
"|",
"case",
"response",
".",
"code",
"when",
"200",
",",
"201",
"if",
"response",
".",
"blank?",
"true",
"else",
"if",
"dont_parse_response",
"response",
"else",
"parse_response",
"(",
"response",
")",
"end",
"end",
"when",
"404",
"raise",
"NotFound",
".",
"new",
"(",
"response",
")",
"else",
"raise",
"ApiError",
".",
"new",
"(",
"response",
")",
"end",
"end",
"end"
] | Initialize with an API key and config options | [
"Initialize",
"with",
"an",
"API",
"key",
"and",
"config",
"options"
] | 376008a961ee33543853790a0172c571b31d81f1 | https://github.com/kennon/litmos-client/blob/376008a961ee33543853790a0172c571b31d81f1/lib/litmos_client.rb#L36-L70 | train |
kencrocken/dcmetro | lib/dcmetro.rb | DCMetro.Information.station_time | def station_time(station)
# If a station has multiple stations codes we join the codes together
@station_code = station['Code']
if !station['StationTogether1'].empty?
@station_code += ",#{station['StationTogether1']}"
end
if !station['StationTogether2'].empty?
@station_code += ",#{station['StationTogether2']}"
end
# The call to the api is made and the prediction times are returned
@metro_time = RestClient.get "#{BASE_URL}/StationPrediction.svc/json/GetPrediction/#{@station_code}", :params => {
"api_key" => API_KEY,
"subscription-key" => API_KEY
}
@metro_time
end | ruby | def station_time(station)
# If a station has multiple stations codes we join the codes together
@station_code = station['Code']
if !station['StationTogether1'].empty?
@station_code += ",#{station['StationTogether1']}"
end
if !station['StationTogether2'].empty?
@station_code += ",#{station['StationTogether2']}"
end
# The call to the api is made and the prediction times are returned
@metro_time = RestClient.get "#{BASE_URL}/StationPrediction.svc/json/GetPrediction/#{@station_code}", :params => {
"api_key" => API_KEY,
"subscription-key" => API_KEY
}
@metro_time
end | [
"def",
"station_time",
"(",
"station",
")",
"@station_code",
"=",
"station",
"[",
"'Code'",
"]",
"if",
"!",
"station",
"[",
"'StationTogether1'",
"]",
".",
"empty?",
"@station_code",
"+=",
"\",#{station['StationTogether1']}\"",
"end",
"if",
"!",
"station",
"[",
"'StationTogether2'",
"]",
".",
"empty?",
"@station_code",
"+=",
"\",#{station['StationTogether2']}\"",
"end",
"@metro_time",
"=",
"RestClient",
".",
"get",
"\"#{BASE_URL}/StationPrediction.svc/json/GetPrediction/#{@station_code}\"",
",",
":params",
"=>",
"{",
"\"api_key\"",
"=>",
"API_KEY",
",",
"\"subscription-key\"",
"=>",
"API_KEY",
"}",
"@metro_time",
"end"
] | This makes an api call to grab the train arrival and departure predictions.
If more than one line is present at a station, such is concatenated and
the call is made on all lines. | [
"This",
"makes",
"an",
"api",
"call",
"to",
"grab",
"the",
"train",
"arrival",
"and",
"departure",
"predictions",
".",
"If",
"more",
"than",
"one",
"line",
"is",
"present",
"at",
"a",
"station",
"such",
"is",
"concatenated",
"and",
"the",
"call",
"is",
"made",
"on",
"all",
"lines",
"."
] | 9fecdea1e619da4828ae7b94c156ce705c2975fc | https://github.com/kencrocken/dcmetro/blob/9fecdea1e619da4828ae7b94c156ce705c2975fc/lib/dcmetro.rb#L168-L185 | train |
gnumarcelo/campaigning | lib/campaigning/template.rb | Campaigning.Template.update! | def update!(params)
response = @@soap.updateTemplate(
:apiKey => params[:apiKey] || CAMPAIGN_MONITOR_API_KEY,
:templateID => @templateID,
:templateName => params[:templateName],
:hTMLPageURL => params[:htmlPageURL],
:zipFileURL => params[:zipFileURL],
:screenshotURL => params[:screenshotURL]
)
handle_response response.template_UpdateResult
end | ruby | def update!(params)
response = @@soap.updateTemplate(
:apiKey => params[:apiKey] || CAMPAIGN_MONITOR_API_KEY,
:templateID => @templateID,
:templateName => params[:templateName],
:hTMLPageURL => params[:htmlPageURL],
:zipFileURL => params[:zipFileURL],
:screenshotURL => params[:screenshotURL]
)
handle_response response.template_UpdateResult
end | [
"def",
"update!",
"(",
"params",
")",
"response",
"=",
"@@soap",
".",
"updateTemplate",
"(",
":apiKey",
"=>",
"params",
"[",
":apiKey",
"]",
"||",
"CAMPAIGN_MONITOR_API_KEY",
",",
":templateID",
"=>",
"@templateID",
",",
":templateName",
"=>",
"params",
"[",
":templateName",
"]",
",",
":hTMLPageURL",
"=>",
"params",
"[",
":htmlPageURL",
"]",
",",
":zipFileURL",
"=>",
"params",
"[",
":zipFileURL",
"]",
",",
":screenshotURL",
"=>",
"params",
"[",
":screenshotURL",
"]",
")",
"handle_response",
"response",
".",
"template_UpdateResult",
"end"
] | Updates an existing template.
Available _params_ argument are:
* :templateID - The ID of the template to be updated.
* :templateName - The name of the template. Maximum of 30 characters (will be truncated to 30 characters if longer).
* :htmlPageURL - The URL of the HTML page you have created for the template.
* :zipFileURL - Optional URL of a zip file containing any other files required by the template.
* :screenshotURL - Optional URL of a screenshot of the template. Must be in jpeg format and at least 218 pixels wide.
* :apiKey - optional API key to use to make request. Will use CAMPAIGN_MONITOR_API_KEY if not set.
*Return*:
*Success*: Upon a successful call, this method will return a Campaigning::Result object wich consists of a +code+ and +message+ fields
containing a successful message.
*Error*: An Exception containing the cause of the error will be raised. | [
"Updates",
"an",
"existing",
"template",
"."
] | f3d7da053b65cfa376269533183919dc890964fd | https://github.com/gnumarcelo/campaigning/blob/f3d7da053b65cfa376269533183919dc890964fd/lib/campaigning/template.rb#L79-L89 | train |
godfat/jellyfish | lib/jellyfish/normalized_params.rb | Jellyfish.NormalizedParams.force_encoding | def force_encoding(data, encoding=Encoding.default_external)
return data if data.respond_to?(:rewind) # e.g. Tempfile, File, etc
if data.respond_to?(:force_encoding)
data.force_encoding(encoding).encode!
elsif data.respond_to?(:each_value)
data.each_value{ |v| force_encoding(v, encoding) }
elsif data.respond_to?(:each)
data.each{ |v| force_encoding(v, encoding) }
end
data
end | ruby | def force_encoding(data, encoding=Encoding.default_external)
return data if data.respond_to?(:rewind) # e.g. Tempfile, File, etc
if data.respond_to?(:force_encoding)
data.force_encoding(encoding).encode!
elsif data.respond_to?(:each_value)
data.each_value{ |v| force_encoding(v, encoding) }
elsif data.respond_to?(:each)
data.each{ |v| force_encoding(v, encoding) }
end
data
end | [
"def",
"force_encoding",
"(",
"data",
",",
"encoding",
"=",
"Encoding",
".",
"default_external",
")",
"return",
"data",
"if",
"data",
".",
"respond_to?",
"(",
":rewind",
")",
"if",
"data",
".",
"respond_to?",
"(",
":force_encoding",
")",
"data",
".",
"force_encoding",
"(",
"encoding",
")",
".",
"encode!",
"elsif",
"data",
".",
"respond_to?",
"(",
":each_value",
")",
"data",
".",
"each_value",
"{",
"|",
"v",
"|",
"force_encoding",
"(",
"v",
",",
"encoding",
")",
"}",
"elsif",
"data",
".",
"respond_to?",
"(",
":each",
")",
"data",
".",
"each",
"{",
"|",
"v",
"|",
"force_encoding",
"(",
"v",
",",
"encoding",
")",
"}",
"end",
"data",
"end"
] | stolen from sinatra
Fixes encoding issues by casting params to Encoding.default_external | [
"stolen",
"from",
"sinatra",
"Fixes",
"encoding",
"issues",
"by",
"casting",
"params",
"to",
"Encoding",
".",
"default_external"
] | e0a9e07ee010d5f097dc62348b0b83d17d3143ff | https://github.com/godfat/jellyfish/blob/e0a9e07ee010d5f097dc62348b0b83d17d3143ff/lib/jellyfish/normalized_params.rb#L43-L53 | train |
experteer/codeqa | lib/codeqa/installer.rb | Codeqa.Installer.install_codeqa_git_hook | def install_codeqa_git_hook
git_root = app_path.join('.git')
pre_commit_path = git_root.join 'hooks', 'pre-commit'
return false unless File.exist?(git_root)
return false if File.exist?(pre_commit_path)
# an alternative would be to backup the old hook
# FileUtils.mv(pre_commit_path,
# git_root.join('hooks', 'pre-commit.bkp'),
# :force => true)
pre_commit_path.make_symlink('../../.codeqa/git_hook.rb') # relative path!
true
end | ruby | def install_codeqa_git_hook
git_root = app_path.join('.git')
pre_commit_path = git_root.join 'hooks', 'pre-commit'
return false unless File.exist?(git_root)
return false if File.exist?(pre_commit_path)
# an alternative would be to backup the old hook
# FileUtils.mv(pre_commit_path,
# git_root.join('hooks', 'pre-commit.bkp'),
# :force => true)
pre_commit_path.make_symlink('../../.codeqa/git_hook.rb') # relative path!
true
end | [
"def",
"install_codeqa_git_hook",
"git_root",
"=",
"app_path",
".",
"join",
"(",
"'.git'",
")",
"pre_commit_path",
"=",
"git_root",
".",
"join",
"'hooks'",
",",
"'pre-commit'",
"return",
"false",
"unless",
"File",
".",
"exist?",
"(",
"git_root",
")",
"return",
"false",
"if",
"File",
".",
"exist?",
"(",
"pre_commit_path",
")",
"pre_commit_path",
".",
"make_symlink",
"(",
"'../../.codeqa/git_hook.rb'",
")",
"true",
"end"
] | return true if installation succeeded
return false if either no git repo or hook already present | [
"return",
"true",
"if",
"installation",
"succeeded",
"return",
"false",
"if",
"either",
"no",
"git",
"repo",
"or",
"hook",
"already",
"present"
] | 199fa9b686737293a3c20148ad708a60e6fef667 | https://github.com/experteer/codeqa/blob/199fa9b686737293a3c20148ad708a60e6fef667/lib/codeqa/installer.rb#L34-L46 | train |
jtimberman/ubuntu_ami | lib/chef/knife/ec2_amis_ubuntu.rb | KnifePlugins.Ec2AmisUbuntu.list_amis | def list_amis(distro)
amis = Hash.new
Ubuntu.release(distro).amis.each do |ami|
amis[build_type(ami.region, ami.arch, ami.root_store, ami.virtualization_type)] = ami.name
end
amis
end | ruby | def list_amis(distro)
amis = Hash.new
Ubuntu.release(distro).amis.each do |ami|
amis[build_type(ami.region, ami.arch, ami.root_store, ami.virtualization_type)] = ami.name
end
amis
end | [
"def",
"list_amis",
"(",
"distro",
")",
"amis",
"=",
"Hash",
".",
"new",
"Ubuntu",
".",
"release",
"(",
"distro",
")",
".",
"amis",
".",
"each",
"do",
"|",
"ami",
"|",
"amis",
"[",
"build_type",
"(",
"ami",
".",
"region",
",",
"ami",
".",
"arch",
",",
"ami",
".",
"root_store",
",",
"ami",
".",
"virtualization_type",
")",
"]",
"=",
"ami",
".",
"name",
"end",
"amis",
"end"
] | Iterates over the AMIs available for the specified distro.
=== Parameters
distro<String>:: Release name of the distro to display.
=== Returns
Hash:: Keys are the AMI type, values are the AMI ID. | [
"Iterates",
"over",
"the",
"AMIs",
"available",
"for",
"the",
"specified",
"distro",
"."
] | 6df6308be3c90d038ffb5a93c4967b0444a635c8 | https://github.com/jtimberman/ubuntu_ami/blob/6df6308be3c90d038ffb5a93c4967b0444a635c8/lib/chef/knife/ec2_amis_ubuntu.rb#L110-L116 | train |
26fe/tree.rb | lib/tree_rb/core/tree_node_visitor.rb | TreeRb.TreeNodeVisitor.exit_node | def exit_node(tree_node)
parent = @stack.last
if @delegate
@delegate.exit_node(tree_node) if @delegate.respond_to? :exit_node
else
@on_exit_tree_node_blocks.each do |b|
if b.arity == 1
b.call(tree_node)
elsif b.arity == 2
b.call(tree_node, parent)
end
end
end
@stack.pop
end | ruby | def exit_node(tree_node)
parent = @stack.last
if @delegate
@delegate.exit_node(tree_node) if @delegate.respond_to? :exit_node
else
@on_exit_tree_node_blocks.each do |b|
if b.arity == 1
b.call(tree_node)
elsif b.arity == 2
b.call(tree_node, parent)
end
end
end
@stack.pop
end | [
"def",
"exit_node",
"(",
"tree_node",
")",
"parent",
"=",
"@stack",
".",
"last",
"if",
"@delegate",
"@delegate",
".",
"exit_node",
"(",
"tree_node",
")",
"if",
"@delegate",
".",
"respond_to?",
":exit_node",
"else",
"@on_exit_tree_node_blocks",
".",
"each",
"do",
"|",
"b",
"|",
"if",
"b",
".",
"arity",
"==",
"1",
"b",
".",
"call",
"(",
"tree_node",
")",
"elsif",
"b",
".",
"arity",
"==",
"2",
"b",
".",
"call",
"(",
"tree_node",
",",
"parent",
")",
"end",
"end",
"end",
"@stack",
".",
"pop",
"end"
] | called on tree node at end of the visit i.e. oll subtree are visited | [
"called",
"on",
"tree",
"node",
"at",
"end",
"of",
"the",
"visit",
"i",
".",
"e",
".",
"oll",
"subtree",
"are",
"visited"
] | 5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b | https://github.com/26fe/tree.rb/blob/5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b/lib/tree_rb/core/tree_node_visitor.rb#L64-L78 | train |
26fe/tree.rb | lib/tree_rb/core/tree_node_visitor.rb | TreeRb.TreeNodeVisitor.visit_leaf | def visit_leaf(leaf_node)
parent = @stack.last
if @delegate
@delegate.visit_leaf(leaf_node) if @delegate.respond_to? :visit_leaf
else
@on_visit_leaf_node_blocks.each do |b|
if b.arity == 1
b.call(leaf_node)
elsif b.arity == 2
b.call(leaf_node, parent)
end
end
end
end | ruby | def visit_leaf(leaf_node)
parent = @stack.last
if @delegate
@delegate.visit_leaf(leaf_node) if @delegate.respond_to? :visit_leaf
else
@on_visit_leaf_node_blocks.each do |b|
if b.arity == 1
b.call(leaf_node)
elsif b.arity == 2
b.call(leaf_node, parent)
end
end
end
end | [
"def",
"visit_leaf",
"(",
"leaf_node",
")",
"parent",
"=",
"@stack",
".",
"last",
"if",
"@delegate",
"@delegate",
".",
"visit_leaf",
"(",
"leaf_node",
")",
"if",
"@delegate",
".",
"respond_to?",
":visit_leaf",
"else",
"@on_visit_leaf_node_blocks",
".",
"each",
"do",
"|",
"b",
"|",
"if",
"b",
".",
"arity",
"==",
"1",
"b",
".",
"call",
"(",
"leaf_node",
")",
"elsif",
"b",
".",
"arity",
"==",
"2",
"b",
".",
"call",
"(",
"leaf_node",
",",
"parent",
")",
"end",
"end",
"end",
"end"
] | called when visit leaf node | [
"called",
"when",
"visit",
"leaf",
"node"
] | 5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b | https://github.com/26fe/tree.rb/blob/5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b/lib/tree_rb/core/tree_node_visitor.rb#L83-L96 | train |
kirkbowers/rdoc2md | lib/rdoc2md.rb | Rdoc2md.Document.to_md | def to_md
# Usually ruby is extremely readable, but I think "-1" means "give me all the
# trailing blank lines" is surprisingly opaque. That's what the -1 does...
lines = @text.split("\n", -1)
lines.collect do |line|
result = line
# Leave lines that start with 4 spaces alone. These are code blocks and
# should pass through unchanged.
unless result =~ /^\s{4,}/
# Convert headers
result.sub!(/^(=){1,6}/) { |s| "#" * s.length} unless result =~ /^={7,}/
# Convert strong to have two stars
# The matching pair of stars should start with a single star that is either at
# the beginning of the line or not following a backslash, have at least one
# non-star and non-backslash in between, then end in one star
result.gsub!(/(\A|[^\\\*])\*([^\*]*[^\*\\])\*/, '\1**\2**')
# Convert inline code spans to use backticks
result.gsub!(/(\A|[^\\])\+([^\+]+)\+/, '\1`\2`')
# Convert bare http:, mailto: and ftp: links
result.gsub!(/(\A|\s)(http:|https:|mailto:|ftp:)(\S*)/, '\1[\2\3](\2\3)')
# Convert bare www to an http: link
result.gsub!(/(\A|\s)www\.(\S*)/, '\1[www.\2](http://www.\2)')
# Convert link: links to refer to local files
result.gsub!(/(\A|\s)link:(\S*)/, '\1[\2](\2)')
# Convert multi word labels surrounded by {} with a url
result.gsub!(/\{([^\}]*)\}\[(\S*)\]/, '[\1](\2)')
# Convert one word labels with a url
result.gsub!(/(\A|\s)([^\{\s]\S*)\[(\S*)\]/, '\1[\2](\3)')
end
result
end.join("\n")
end | ruby | def to_md
# Usually ruby is extremely readable, but I think "-1" means "give me all the
# trailing blank lines" is surprisingly opaque. That's what the -1 does...
lines = @text.split("\n", -1)
lines.collect do |line|
result = line
# Leave lines that start with 4 spaces alone. These are code blocks and
# should pass through unchanged.
unless result =~ /^\s{4,}/
# Convert headers
result.sub!(/^(=){1,6}/) { |s| "#" * s.length} unless result =~ /^={7,}/
# Convert strong to have two stars
# The matching pair of stars should start with a single star that is either at
# the beginning of the line or not following a backslash, have at least one
# non-star and non-backslash in between, then end in one star
result.gsub!(/(\A|[^\\\*])\*([^\*]*[^\*\\])\*/, '\1**\2**')
# Convert inline code spans to use backticks
result.gsub!(/(\A|[^\\])\+([^\+]+)\+/, '\1`\2`')
# Convert bare http:, mailto: and ftp: links
result.gsub!(/(\A|\s)(http:|https:|mailto:|ftp:)(\S*)/, '\1[\2\3](\2\3)')
# Convert bare www to an http: link
result.gsub!(/(\A|\s)www\.(\S*)/, '\1[www.\2](http://www.\2)')
# Convert link: links to refer to local files
result.gsub!(/(\A|\s)link:(\S*)/, '\1[\2](\2)')
# Convert multi word labels surrounded by {} with a url
result.gsub!(/\{([^\}]*)\}\[(\S*)\]/, '[\1](\2)')
# Convert one word labels with a url
result.gsub!(/(\A|\s)([^\{\s]\S*)\[(\S*)\]/, '\1[\2](\3)')
end
result
end.join("\n")
end | [
"def",
"to_md",
"lines",
"=",
"@text",
".",
"split",
"(",
"\"\\n\"",
",",
"-",
"1",
")",
"lines",
".",
"collect",
"do",
"|",
"line",
"|",
"result",
"=",
"line",
"unless",
"result",
"=~",
"/",
"\\s",
"/",
"result",
".",
"sub!",
"(",
"/",
"/",
")",
"{",
"|",
"s",
"|",
"\"#\"",
"*",
"s",
".",
"length",
"}",
"unless",
"result",
"=~",
"/",
"/",
"result",
".",
"gsub!",
"(",
"/",
"\\A",
"\\\\",
"\\*",
"\\*",
"\\*",
"\\*",
"\\\\",
"\\*",
"/",
",",
"'\\1**\\2**'",
")",
"result",
".",
"gsub!",
"(",
"/",
"\\A",
"\\\\",
"\\+",
"\\+",
"\\+",
"/",
",",
"'\\1`\\2`'",
")",
"result",
".",
"gsub!",
"(",
"/",
"\\A",
"\\s",
"\\S",
"/",
",",
"'\\1[\\2\\3](\\2\\3)'",
")",
"result",
".",
"gsub!",
"(",
"/",
"\\A",
"\\s",
"\\.",
"\\S",
"/",
",",
"'\\1[www.\\2](http://www.\\2)'",
")",
"result",
".",
"gsub!",
"(",
"/",
"\\A",
"\\s",
"\\S",
"/",
",",
"'\\1[\\2](\\2)'",
")",
"result",
".",
"gsub!",
"(",
"/",
"\\{",
"\\}",
"\\}",
"\\[",
"\\S",
"\\]",
"/",
",",
"'[\\1](\\2)'",
")",
"result",
".",
"gsub!",
"(",
"/",
"\\A",
"\\s",
"\\{",
"\\s",
"\\S",
"\\[",
"\\S",
"\\]",
"/",
",",
"'\\1[\\2](\\3)'",
")",
"end",
"result",
"end",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] | The initializer takes an optional text, which is the document to be converted from
rdoc style to markdown.
Convert the existing document to markdown. The result is returned as a String. | [
"The",
"initializer",
"takes",
"an",
"optional",
"text",
"which",
"is",
"the",
"document",
"to",
"be",
"converted",
"from",
"rdoc",
"style",
"to",
"markdown",
".",
"Convert",
"the",
"existing",
"document",
"to",
"markdown",
".",
"The",
"result",
"is",
"returned",
"as",
"a",
"String",
"."
] | 5e32cc2de9e64140034a3fbb767ef52c8261ce06 | https://github.com/kirkbowers/rdoc2md/blob/5e32cc2de9e64140034a3fbb767ef52c8261ce06/lib/rdoc2md.rb#L23-L65 | train |
gnumarcelo/campaigning | lib/campaigning/client.rb | Campaigning.Client.templates | def templates
response = @@soap.getClientTemplates(:apiKey => @apiKey, :clientID => @clientID)
templates = handle_response response.client_GetTemplatesResult
templates.collect {|template| Template.new(template.templateID, template.name, template.previewURL, template.screenshotURL, :apiKey=> @apiKey)}
end | ruby | def templates
response = @@soap.getClientTemplates(:apiKey => @apiKey, :clientID => @clientID)
templates = handle_response response.client_GetTemplatesResult
templates.collect {|template| Template.new(template.templateID, template.name, template.previewURL, template.screenshotURL, :apiKey=> @apiKey)}
end | [
"def",
"templates",
"response",
"=",
"@@soap",
".",
"getClientTemplates",
"(",
":apiKey",
"=>",
"@apiKey",
",",
":clientID",
"=>",
"@clientID",
")",
"templates",
"=",
"handle_response",
"response",
".",
"client_GetTemplatesResult",
"templates",
".",
"collect",
"{",
"|",
"template",
"|",
"Template",
".",
"new",
"(",
"template",
".",
"templateID",
",",
"template",
".",
"name",
",",
"template",
".",
"previewURL",
",",
"template",
".",
"screenshotURL",
",",
":apiKey",
"=>",
"@apiKey",
")",
"}",
"end"
] | Gets a list of all templates for a client.
*Return*:
*Success*: Upon a successful call, this method will return a collection of Campaigning::Template objects.
*Error*: An Exception containing the cause of the error will be raised. | [
"Gets",
"a",
"list",
"of",
"all",
"templates",
"for",
"a",
"client",
"."
] | f3d7da053b65cfa376269533183919dc890964fd | https://github.com/gnumarcelo/campaigning/blob/f3d7da053b65cfa376269533183919dc890964fd/lib/campaigning/client.rb#L24-L28 | train |
gnumarcelo/campaigning | lib/campaigning/client.rb | Campaigning.Client.lists | def lists
response = @@soap.getClientLists(:apiKey => @apiKey, :clientID => @clientID)
lists = handle_response response.client_GetListsResult
lists.collect {|list| List.new(list.listID, list.name, :apiKey=> @apiKey)}
end | ruby | def lists
response = @@soap.getClientLists(:apiKey => @apiKey, :clientID => @clientID)
lists = handle_response response.client_GetListsResult
lists.collect {|list| List.new(list.listID, list.name, :apiKey=> @apiKey)}
end | [
"def",
"lists",
"response",
"=",
"@@soap",
".",
"getClientLists",
"(",
":apiKey",
"=>",
"@apiKey",
",",
":clientID",
"=>",
"@clientID",
")",
"lists",
"=",
"handle_response",
"response",
".",
"client_GetListsResult",
"lists",
".",
"collect",
"{",
"|",
"list",
"|",
"List",
".",
"new",
"(",
"list",
".",
"listID",
",",
"list",
".",
"name",
",",
":apiKey",
"=>",
"@apiKey",
")",
"}",
"end"
] | Gets a list of all subscriber lists for a client.
*Return*:
*Success*: Upon a successful call, this method will return a collection of Campaigning::List objects.
*Error*: An Exception containing the cause of the error will be raised. | [
"Gets",
"a",
"list",
"of",
"all",
"subscriber",
"lists",
"for",
"a",
"client",
"."
] | f3d7da053b65cfa376269533183919dc890964fd | https://github.com/gnumarcelo/campaigning/blob/f3d7da053b65cfa376269533183919dc890964fd/lib/campaigning/client.rb#L38-L42 | train |
gnumarcelo/campaigning | lib/campaigning/client.rb | Campaigning.Client.campaigns | def campaigns
response = @@soap.getClientCampaigns(:apiKey => @apiKey, :clientID => @clientID )
campaign_list = handle_response response.client_GetCampaignsResult
campaign_list.collect do |campaign|
Campaign.new(campaign.campaignID, campaign.subject, campaign.name, campaign.sentDate, campaign.totalRecipients, :apiKey=> @apiKey)
end
end | ruby | def campaigns
response = @@soap.getClientCampaigns(:apiKey => @apiKey, :clientID => @clientID )
campaign_list = handle_response response.client_GetCampaignsResult
campaign_list.collect do |campaign|
Campaign.new(campaign.campaignID, campaign.subject, campaign.name, campaign.sentDate, campaign.totalRecipients, :apiKey=> @apiKey)
end
end | [
"def",
"campaigns",
"response",
"=",
"@@soap",
".",
"getClientCampaigns",
"(",
":apiKey",
"=>",
"@apiKey",
",",
":clientID",
"=>",
"@clientID",
")",
"campaign_list",
"=",
"handle_response",
"response",
".",
"client_GetCampaignsResult",
"campaign_list",
".",
"collect",
"do",
"|",
"campaign",
"|",
"Campaign",
".",
"new",
"(",
"campaign",
".",
"campaignID",
",",
"campaign",
".",
"subject",
",",
"campaign",
".",
"name",
",",
"campaign",
".",
"sentDate",
",",
"campaign",
".",
"totalRecipients",
",",
":apiKey",
"=>",
"@apiKey",
")",
"end",
"end"
] | Gets a list of all campaigns that have been sent for a client.
*Return*:
*Success*: Upon a successful call, this method will return a collection of Campaigning::Campaign objects.
*Error*: An Exception containing the cause of the error will be raised. | [
"Gets",
"a",
"list",
"of",
"all",
"campaigns",
"that",
"have",
"been",
"sent",
"for",
"a",
"client",
"."
] | f3d7da053b65cfa376269533183919dc890964fd | https://github.com/gnumarcelo/campaigning/blob/f3d7da053b65cfa376269533183919dc890964fd/lib/campaigning/client.rb#L195-L201 | train |
gnumarcelo/campaigning | lib/campaigning/client.rb | Campaigning.Client.update_access_and_billing! | def update_access_and_billing!(params)
response = @@soap.updateClientAccessAndBilling(
:apiKey => @apiKey,
:clientID => @clientID,
:accessLevel => params[:accessLevel],
:username => params.fetch(:username, ""),
:password => params.fetch(:password, ""),
:billingType => params.fetch(:billingType, ""),
:currency => params.fetch(:currency, ""),
:deliveryFee => params.fetch(:deliveryFee, ""),
:costPerRecipient => params.fetch(:costPerRecipient, ""),
:designAndSpamTestFee => params.fetch(:designAndSpamTestFee, "")
)
handle_response response.client_UpdateAccessAndBillingResult
end | ruby | def update_access_and_billing!(params)
response = @@soap.updateClientAccessAndBilling(
:apiKey => @apiKey,
:clientID => @clientID,
:accessLevel => params[:accessLevel],
:username => params.fetch(:username, ""),
:password => params.fetch(:password, ""),
:billingType => params.fetch(:billingType, ""),
:currency => params.fetch(:currency, ""),
:deliveryFee => params.fetch(:deliveryFee, ""),
:costPerRecipient => params.fetch(:costPerRecipient, ""),
:designAndSpamTestFee => params.fetch(:designAndSpamTestFee, "")
)
handle_response response.client_UpdateAccessAndBillingResult
end | [
"def",
"update_access_and_billing!",
"(",
"params",
")",
"response",
"=",
"@@soap",
".",
"updateClientAccessAndBilling",
"(",
":apiKey",
"=>",
"@apiKey",
",",
":clientID",
"=>",
"@clientID",
",",
":accessLevel",
"=>",
"params",
"[",
":accessLevel",
"]",
",",
":username",
"=>",
"params",
".",
"fetch",
"(",
":username",
",",
"\"\"",
")",
",",
":password",
"=>",
"params",
".",
"fetch",
"(",
":password",
",",
"\"\"",
")",
",",
":billingType",
"=>",
"params",
".",
"fetch",
"(",
":billingType",
",",
"\"\"",
")",
",",
":currency",
"=>",
"params",
".",
"fetch",
"(",
":currency",
",",
"\"\"",
")",
",",
":deliveryFee",
"=>",
"params",
".",
"fetch",
"(",
":deliveryFee",
",",
"\"\"",
")",
",",
":costPerRecipient",
"=>",
"params",
".",
"fetch",
"(",
":costPerRecipient",
",",
"\"\"",
")",
",",
":designAndSpamTestFee",
"=>",
"params",
".",
"fetch",
"(",
":designAndSpamTestFee",
",",
"\"\"",
")",
")",
"handle_response",
"response",
".",
"client_UpdateAccessAndBillingResult",
"end"
] | Update the access and billing settings of an existing client, leaving the basic details untouched.
Here's a list of all the parameters you'll need to pass to the Campaigning::Client#update_access_and_billing! method. Only the :+access_level+ parameter
is required for all calls. The relevance and necessity of the other parameters depends on the chosen AccessLevel (and BillingType),
and will be fully described along with each parameter.
Available _params_ argument are:
* :accessLevel - An integer describing the client's ability to access different areas of the application. Influences the significance
and requirements of the following parameters. See http://www.campaignmonitor.com/api/method/client-updateaccessandbilling/#accesslevels
for a full description of available levels.
* :username - Client login username. Not required and ignored if AccessLevel is set to 0.
* :password - Client login password. Not required and ignored if AccessLevel is set to 0.
* :billingType - Client billing type, only required if :accessLevel is set to allow the client to create and send campaigns
* :currency - Billing currency for this client, only required if :billingType is set to either ClientPaysAtStandardRate or
ClientPaysWithMarkup. See full details: http://www.campaignmonitor.com/api/method/client-updateaccessandbilling/#currencies.
* :deliveryFee - Flat rate delivery fee to be charged to the client for each campaign sent, expressed in the chosen currency's
major unit, but without the currency symbol (for example, sending "6.5" means "$6.50" if USD is used). Only
required if BillingType is set to ClientPaysWithMarkup, in which case it should be at least equal to the standard rate.
Further detail is available at http://help.campaignmonitor.com/topic.aspx?t=118.
* :costPerRecipient - Additional cost added to the campaign for each email address the campaign is sent to, expressed in the chosen
currency's minor unit (for example, sending "1.5" means 1.5 cents per email address if USD is used). Only required
if BillingType is set to ClientPaysWithMarkup, in which case it should be at least equal to the standard cost/recipient
rate. Further detail is available at http://help.campaignmonitor.com/topic.aspx?t=118.
* :designAndSpamTestFee - Expressed in the chosen currency's major unit (for example, sending "10" means "$10" if USD is used). Only required
if BillingType is set to ClientPaysWithMarkup and client has access to design and spam tests, in which case the fee
should be equal to or higher than the standard rate (identical to the standard DeliveryFee for that currency).
Please note that for reasons of security there is no way to set a client's credit card details via the API. It will have to be done in the application.
*Return*:
*Success*: Upon a successful call, this method will return a Campaigning::Result object wich consists of a +code+ and +message+ fields
containing a successful message.
*Error*: An Exception containing the cause of the error will be raised. | [
"Update",
"the",
"access",
"and",
"billing",
"settings",
"of",
"an",
"existing",
"client",
"leaving",
"the",
"basic",
"details",
"untouched",
"."
] | f3d7da053b65cfa376269533183919dc890964fd | https://github.com/gnumarcelo/campaigning/blob/f3d7da053b65cfa376269533183919dc890964fd/lib/campaigning/client.rb#L286-L300 | train |
gnumarcelo/campaigning | lib/campaigning/client.rb | Campaigning.Client.update_basics! | def update_basics!(params)
response = @@soap.updateClientBasics(
:apiKey => @apiKey,
:clientID => @clientID,
:companyName => params[:companyName],
:contactName => params[:contactName],
:emailAddress => params[:emailAddress],
:country => params[:country],
:timezone => params[:timezone]
)
handle_response response.client_UpdateBasicsResult
end | ruby | def update_basics!(params)
response = @@soap.updateClientBasics(
:apiKey => @apiKey,
:clientID => @clientID,
:companyName => params[:companyName],
:contactName => params[:contactName],
:emailAddress => params[:emailAddress],
:country => params[:country],
:timezone => params[:timezone]
)
handle_response response.client_UpdateBasicsResult
end | [
"def",
"update_basics!",
"(",
"params",
")",
"response",
"=",
"@@soap",
".",
"updateClientBasics",
"(",
":apiKey",
"=>",
"@apiKey",
",",
":clientID",
"=>",
"@clientID",
",",
":companyName",
"=>",
"params",
"[",
":companyName",
"]",
",",
":contactName",
"=>",
"params",
"[",
":contactName",
"]",
",",
":emailAddress",
"=>",
"params",
"[",
":emailAddress",
"]",
",",
":country",
"=>",
"params",
"[",
":country",
"]",
",",
":timezone",
"=>",
"params",
"[",
":timezone",
"]",
")",
"handle_response",
"response",
".",
"client_UpdateBasicsResult",
"end"
] | Updates the basic details of an existing client.
If you wish to change only some details, the others must be included as they currently are. Please note that the client's existing
access and billing details will remain unchanged by a call to this method.
Available _params_ argument are:
* :companyName - The client company name.
* :contactName - The personal name of the principle contact for this client.
* :emailAddress - An email address to which this client will be sent application-related emails.
* :country - This client's country.
* :timezone - Client timezone for tracking and reporting data. Valid timezone strings are obtainable by means of the
API procedure Campaigning.timezones.
*Return*:
*Success*: Upon a successful call, this method will return a Campaigning::Result object wich consists of a +code+ and +message+ fields
containing a successful message.
*Error*: An Exception containing the cause of the error will be raised. | [
"Updates",
"the",
"basic",
"details",
"of",
"an",
"existing",
"client",
".",
"If",
"you",
"wish",
"to",
"change",
"only",
"some",
"details",
"the",
"others",
"must",
"be",
"included",
"as",
"they",
"currently",
"are",
".",
"Please",
"note",
"that",
"the",
"client",
"s",
"existing",
"access",
"and",
"billing",
"details",
"will",
"remain",
"unchanged",
"by",
"a",
"call",
"to",
"this",
"method",
"."
] | f3d7da053b65cfa376269533183919dc890964fd | https://github.com/gnumarcelo/campaigning/blob/f3d7da053b65cfa376269533183919dc890964fd/lib/campaigning/client.rb#L320-L331 | train |
bilus/akasha | lib/akasha/repository.rb | Akasha.Repository.save_aggregate | def save_aggregate(aggregate, concurrency: :none)
changeset = aggregate.changeset
events = changeset.events.map { |event| event.with_metadata(namespace: @namespace) }
revision = aggregate.revision if concurrency == :optimistic
stream(aggregate.class, changeset.aggregate_id).write_events(events, revision: revision)
notify_subscribers(changeset.aggregate_id, events)
end | ruby | def save_aggregate(aggregate, concurrency: :none)
changeset = aggregate.changeset
events = changeset.events.map { |event| event.with_metadata(namespace: @namespace) }
revision = aggregate.revision if concurrency == :optimistic
stream(aggregate.class, changeset.aggregate_id).write_events(events, revision: revision)
notify_subscribers(changeset.aggregate_id, events)
end | [
"def",
"save_aggregate",
"(",
"aggregate",
",",
"concurrency",
":",
":none",
")",
"changeset",
"=",
"aggregate",
".",
"changeset",
"events",
"=",
"changeset",
".",
"events",
".",
"map",
"{",
"|",
"event",
"|",
"event",
".",
"with_metadata",
"(",
"namespace",
":",
"@namespace",
")",
"}",
"revision",
"=",
"aggregate",
".",
"revision",
"if",
"concurrency",
"==",
":optimistic",
"stream",
"(",
"aggregate",
".",
"class",
",",
"changeset",
".",
"aggregate_id",
")",
".",
"write_events",
"(",
"events",
",",
"revision",
":",
"revision",
")",
"notify_subscribers",
"(",
"changeset",
".",
"aggregate_id",
",",
"events",
")",
"end"
] | Saves an aggregate to the repository, appending events to the corresponding stream. | [
"Saves",
"an",
"aggregate",
"to",
"the",
"repository",
"appending",
"events",
"to",
"the",
"corresponding",
"stream",
"."
] | 5fadefc249f520ae909b762956ac23a6f916b021 | https://github.com/bilus/akasha/blob/5fadefc249f520ae909b762956ac23a6f916b021/lib/akasha/repository.rb#L35-L41 | train |
xinge/gcm_helper | lib/gcm_helper/sender.rb | GcmHelper.Sender.update_status | def update_status(unsent_reg_ids, all_results, multicast_result)
results = multicast_result.results
raise RuntimeError, "Internal error: sizes do not match. currentResults: #{results}; unsentRegIds: #{unsent_reg_ids}" unless results.size==unsent_reg_ids.size
new_unsent_reg_ids = []
unsent_reg_ids.each_with_index {|reg_id, index|
result = results[index]
all_results[reg_id]= result
new_unsent_reg_ids << reg_id unless (result.error_code.nil? || result.error_code.eql?(ERROR_UNAVAILABLE))
}
new_unsent_reg_ids
end | ruby | def update_status(unsent_reg_ids, all_results, multicast_result)
results = multicast_result.results
raise RuntimeError, "Internal error: sizes do not match. currentResults: #{results}; unsentRegIds: #{unsent_reg_ids}" unless results.size==unsent_reg_ids.size
new_unsent_reg_ids = []
unsent_reg_ids.each_with_index {|reg_id, index|
result = results[index]
all_results[reg_id]= result
new_unsent_reg_ids << reg_id unless (result.error_code.nil? || result.error_code.eql?(ERROR_UNAVAILABLE))
}
new_unsent_reg_ids
end | [
"def",
"update_status",
"(",
"unsent_reg_ids",
",",
"all_results",
",",
"multicast_result",
")",
"results",
"=",
"multicast_result",
".",
"results",
"raise",
"RuntimeError",
",",
"\"Internal error: sizes do not match. currentResults: #{results}; unsentRegIds: #{unsent_reg_ids}\"",
"unless",
"results",
".",
"size",
"==",
"unsent_reg_ids",
".",
"size",
"new_unsent_reg_ids",
"=",
"[",
"]",
"unsent_reg_ids",
".",
"each_with_index",
"{",
"|",
"reg_id",
",",
"index",
"|",
"result",
"=",
"results",
"[",
"index",
"]",
"all_results",
"[",
"reg_id",
"]",
"=",
"result",
"new_unsent_reg_ids",
"<<",
"reg_id",
"unless",
"(",
"result",
".",
"error_code",
".",
"nil?",
"||",
"result",
".",
"error_code",
".",
"eql?",
"(",
"ERROR_UNAVAILABLE",
")",
")",
"}",
"new_unsent_reg_ids",
"end"
] | Updates the status of the messages sent to devices and the list of devices that should be retried.
@param [Array] unsent_reg_ids
@param [Hash] all_results
@param [GcmHelper::MulticastResult] multicast_result | [
"Updates",
"the",
"status",
"of",
"the",
"messages",
"sent",
"to",
"devices",
"and",
"the",
"list",
"of",
"devices",
"that",
"should",
"be",
"retried",
"."
] | f998f0e6bde0147613a9cb2ff2f62363adf2b227 | https://github.com/xinge/gcm_helper/blob/f998f0e6bde0147613a9cb2ff2f62363adf2b227/lib/gcm_helper/sender.rb#L218-L228 | train |
nigelr/selections | lib/selections/form_builder_extensions.rb | Selections.FormBuilderExtensions.selections | def selections(field, options = {}, html_options = {})
SelectionTag.new(self, object, field, options, html_options).select_tag
end | ruby | def selections(field, options = {}, html_options = {})
SelectionTag.new(self, object, field, options, html_options).select_tag
end | [
"def",
"selections",
"(",
"field",
",",
"options",
"=",
"{",
"}",
",",
"html_options",
"=",
"{",
"}",
")",
"SelectionTag",
".",
"new",
"(",
"self",
",",
"object",
",",
"field",
",",
"options",
",",
"html_options",
")",
".",
"select_tag",
"end"
] | Create a select list based on the field name finding items within Selection.
Example
form_for(@ticket) do |f|
f.select("priority")
Uses priority_id from the ticket table and creates options list based on items in Selection table with a system_code of
either priority or ticket_priority
options = {} and html_options = {} suport all the keys as the rails library select_tag does.
options
* +system_code+ - Overrides the automatic system_code name based on the fieldname and looks up the list of items in Selection | [
"Create",
"a",
"select",
"list",
"based",
"on",
"the",
"field",
"name",
"finding",
"items",
"within",
"Selection",
"."
] | f4702869ffaf11fbcdc8fdad4c0e91b3d0a1ce45 | https://github.com/nigelr/selections/blob/f4702869ffaf11fbcdc8fdad4c0e91b3d0a1ce45/lib/selections/form_builder_extensions.rb#L17-L19 | train |
nigelr/selections | lib/selections/form_builder_extensions.rb | Selections.FormBuilderExtensions.radios | def radios(field, options = {})
html_options = options.clone
html_options.delete_if {|key, value| key == :system_code}
SelectionTag.new(self, object, field, options, html_options).radio_tag
end | ruby | def radios(field, options = {})
html_options = options.clone
html_options.delete_if {|key, value| key == :system_code}
SelectionTag.new(self, object, field, options, html_options).radio_tag
end | [
"def",
"radios",
"(",
"field",
",",
"options",
"=",
"{",
"}",
")",
"html_options",
"=",
"options",
".",
"clone",
"html_options",
".",
"delete_if",
"{",
"|",
"key",
",",
"value",
"|",
"key",
"==",
":system_code",
"}",
"SelectionTag",
".",
"new",
"(",
"self",
",",
"object",
",",
"field",
",",
"options",
",",
"html_options",
")",
".",
"radio_tag",
"end"
] | Build a radio button list based field name finding items within Selection
Example
form_for(@ticket) do |f|
f.select :priority
options
* +system_code+ - Overrides the automatic system_code name based on the fieldname and looks up the list of items in Selection | [
"Build",
"a",
"radio",
"button",
"list",
"based",
"field",
"name",
"finding",
"items",
"within",
"Selection"
] | f4702869ffaf11fbcdc8fdad4c0e91b3d0a1ce45 | https://github.com/nigelr/selections/blob/f4702869ffaf11fbcdc8fdad4c0e91b3d0a1ce45/lib/selections/form_builder_extensions.rb#L29-L33 | train |
jarhart/rattler | lib/rattler/util/node.rb | Rattler::Util.Node.method_missing | def method_missing(symbol, *args)
(args.empty? and attrs.has_key?(symbol)) ? attrs[symbol] : super
end | ruby | def method_missing(symbol, *args)
(args.empty? and attrs.has_key?(symbol)) ? attrs[symbol] : super
end | [
"def",
"method_missing",
"(",
"symbol",
",",
"*",
"args",
")",
"(",
"args",
".",
"empty?",
"and",
"attrs",
".",
"has_key?",
"(",
"symbol",
")",
")",
"?",
"attrs",
"[",
"symbol",
"]",
":",
"super",
"end"
] | Return +true+ if the node is equal to +other+. Normally this means
+other+ is an instance of the same class or a subclass and has equal
children and attributes.
@return [Boolean] +true+ if the node is equal to +other+
Return +true+ if the node has the same value as +other+, i.e. +other+
is an instance of the same class and has equal children and attributes.
@return [Boolean] +true+ the node has the same value as +other+
Allow attributes to be accessed as methods. | [
"Return",
"+",
"true",
"+",
"if",
"the",
"node",
"is",
"equal",
"to",
"+",
"other",
"+",
".",
"Normally",
"this",
"means",
"+",
"other",
"+",
"is",
"an",
"instance",
"of",
"the",
"same",
"class",
"or",
"a",
"subclass",
"and",
"has",
"equal",
"children",
"and",
"attributes",
"."
] | 8b4efde2a05e9e790955bb635d4a1a9615893719 | https://github.com/jarhart/rattler/blob/8b4efde2a05e9e790955bb635d4a1a9615893719/lib/rattler/util/node.rb#L166-L168 | train |
jmpage/dirty_associations | lib/dirty_associations.rb | DirtyAssociations.ClassMethods.monitor_association_changes | def monitor_association_changes(association)
define_method "#{association}=" do |value|
attribute_will_change!(association.to_s) if _association_will_change?(association, value)
super(value)
end
ids = "#{association.to_s.singularize}_ids"
define_method "#{ids}=" do |value|
attribute_will_change!(association.to_s) if _ids_will_change?(ids, value)
super(value)
end
define_method "#{association}_attributes=" do |value|
attribute_will_change!(association.to_s) if _nested_attributes_will_change?(value)
super(value)
end
[association, ids].each do |name|
define_method "#{name}_change" do
changes[name]
end
define_method "#{name}_changed?" do
changes.has_key?(association.to_s)
end
define_method "#{name}_previously_changed?" do
previous_changes.has_key?(association.to_s)
end
end
end | ruby | def monitor_association_changes(association)
define_method "#{association}=" do |value|
attribute_will_change!(association.to_s) if _association_will_change?(association, value)
super(value)
end
ids = "#{association.to_s.singularize}_ids"
define_method "#{ids}=" do |value|
attribute_will_change!(association.to_s) if _ids_will_change?(ids, value)
super(value)
end
define_method "#{association}_attributes=" do |value|
attribute_will_change!(association.to_s) if _nested_attributes_will_change?(value)
super(value)
end
[association, ids].each do |name|
define_method "#{name}_change" do
changes[name]
end
define_method "#{name}_changed?" do
changes.has_key?(association.to_s)
end
define_method "#{name}_previously_changed?" do
previous_changes.has_key?(association.to_s)
end
end
end | [
"def",
"monitor_association_changes",
"(",
"association",
")",
"define_method",
"\"#{association}=\"",
"do",
"|",
"value",
"|",
"attribute_will_change!",
"(",
"association",
".",
"to_s",
")",
"if",
"_association_will_change?",
"(",
"association",
",",
"value",
")",
"super",
"(",
"value",
")",
"end",
"ids",
"=",
"\"#{association.to_s.singularize}_ids\"",
"define_method",
"\"#{ids}=\"",
"do",
"|",
"value",
"|",
"attribute_will_change!",
"(",
"association",
".",
"to_s",
")",
"if",
"_ids_will_change?",
"(",
"ids",
",",
"value",
")",
"super",
"(",
"value",
")",
"end",
"define_method",
"\"#{association}_attributes=\"",
"do",
"|",
"value",
"|",
"attribute_will_change!",
"(",
"association",
".",
"to_s",
")",
"if",
"_nested_attributes_will_change?",
"(",
"value",
")",
"super",
"(",
"value",
")",
"end",
"[",
"association",
",",
"ids",
"]",
".",
"each",
"do",
"|",
"name",
"|",
"define_method",
"\"#{name}_change\"",
"do",
"changes",
"[",
"name",
"]",
"end",
"define_method",
"\"#{name}_changed?\"",
"do",
"changes",
".",
"has_key?",
"(",
"association",
".",
"to_s",
")",
"end",
"define_method",
"\"#{name}_previously_changed?\"",
"do",
"previous_changes",
".",
"has_key?",
"(",
"association",
".",
"to_s",
")",
"end",
"end",
"end"
] | Creates methods that allows an +association+ to be monitored.
The +association+ parameter should be a string or symbol representing the name of an association. | [
"Creates",
"methods",
"that",
"allows",
"an",
"+",
"association",
"+",
"to",
"be",
"monitored",
"."
] | 33e9cb36e93632d3fee69277063eb42f56c9b7bf | https://github.com/jmpage/dirty_associations/blob/33e9cb36e93632d3fee69277063eb42f56c9b7bf/lib/dirty_associations.rb#L15-L46 | train |
jrochkind/borrow_direct | lib/borrow_direct/encryption.rb | BorrowDirect.Encryption.encode_with_ts | def encode_with_ts(value)
# Not sure if this object is thread-safe, so we re-create
# each time.
public_key = OpenSSL::PKey::RSA.new(self.public_key_str)
payload = "#{value}|#{self.now_timestamp}"
return Base64.encode64(public_key.public_encrypt(payload))
end | ruby | def encode_with_ts(value)
# Not sure if this object is thread-safe, so we re-create
# each time.
public_key = OpenSSL::PKey::RSA.new(self.public_key_str)
payload = "#{value}|#{self.now_timestamp}"
return Base64.encode64(public_key.public_encrypt(payload))
end | [
"def",
"encode_with_ts",
"(",
"value",
")",
"public_key",
"=",
"OpenSSL",
"::",
"PKey",
"::",
"RSA",
".",
"new",
"(",
"self",
".",
"public_key_str",
")",
"payload",
"=",
"\"#{value}|#{self.now_timestamp}\"",
"return",
"Base64",
".",
"encode64",
"(",
"public_key",
".",
"public_encrypt",
"(",
"payload",
")",
")",
"end"
] | Will add on timestamp according to Relais protocol, encrypt,
and Base64-encode, all per Relais protocol. | [
"Will",
"add",
"on",
"timestamp",
"according",
"to",
"Relais",
"protocol",
"encrypt",
"and",
"Base64",
"-",
"encode",
"all",
"per",
"Relais",
"protocol",
"."
] | f2f53760e15d742a5c5584dd641f20dea315f99f | https://github.com/jrochkind/borrow_direct/blob/f2f53760e15d742a5c5584dd641f20dea315f99f/lib/borrow_direct/encryption.rb#L18-L27 | train |
elifoster/weatheruby | lib/weather/actions.rb | Weather.Actions.moon_phase | def moon_phase(location)
response = get('astronomy', location)
{
age: response['moon_phase']['ageOfMoon'].to_i,
illumination: response['moon_phase']['percentIlluminated'].to_i
}
end | ruby | def moon_phase(location)
response = get('astronomy', location)
{
age: response['moon_phase']['ageOfMoon'].to_i,
illumination: response['moon_phase']['percentIlluminated'].to_i
}
end | [
"def",
"moon_phase",
"(",
"location",
")",
"response",
"=",
"get",
"(",
"'astronomy'",
",",
"location",
")",
"{",
"age",
":",
"response",
"[",
"'moon_phase'",
"]",
"[",
"'ageOfMoon'",
"]",
".",
"to_i",
",",
"illumination",
":",
"response",
"[",
"'moon_phase'",
"]",
"[",
"'percentIlluminated'",
"]",
".",
"to_i",
"}",
"end"
] | Gets the current moon phase of the location.
@param location [String] The place to get the phase for.
@return [Hash<Symbol, Integer>] A hash of two integers for the moon phase
information. The `:age` key in the hash contains the moon's age in days,
and the `:illumination` key contains the percentage of how illuminated it
is. | [
"Gets",
"the",
"current",
"moon",
"phase",
"of",
"the",
"location",
"."
] | 4d97db082448765b67ef5112c89346e502a74858 | https://github.com/elifoster/weatheruby/blob/4d97db082448765b67ef5112c89346e502a74858/lib/weather/actions.rb#L39-L45 | train |
elifoster/weatheruby | lib/weather/actions.rb | Weather.Actions.sun_info | def sun_info(location)
response = get('astronomy', location)
{
rise: {
hour: response['moon_phase']['sunrise']['hour'].to_i,
minute: response['moon_phase']['sunrise']['minute'].to_i
},
set: {
hour: response['moon_phase']['sunset']['hour'].to_i,
minute: response['moon_phase']['sunset']['minute'].to_i
}
}
end | ruby | def sun_info(location)
response = get('astronomy', location)
{
rise: {
hour: response['moon_phase']['sunrise']['hour'].to_i,
minute: response['moon_phase']['sunrise']['minute'].to_i
},
set: {
hour: response['moon_phase']['sunset']['hour'].to_i,
minute: response['moon_phase']['sunset']['minute'].to_i
}
}
end | [
"def",
"sun_info",
"(",
"location",
")",
"response",
"=",
"get",
"(",
"'astronomy'",
",",
"location",
")",
"{",
"rise",
":",
"{",
"hour",
":",
"response",
"[",
"'moon_phase'",
"]",
"[",
"'sunrise'",
"]",
"[",
"'hour'",
"]",
".",
"to_i",
",",
"minute",
":",
"response",
"[",
"'moon_phase'",
"]",
"[",
"'sunrise'",
"]",
"[",
"'minute'",
"]",
".",
"to_i",
"}",
",",
"set",
":",
"{",
"hour",
":",
"response",
"[",
"'moon_phase'",
"]",
"[",
"'sunset'",
"]",
"[",
"'hour'",
"]",
".",
"to_i",
",",
"minute",
":",
"response",
"[",
"'moon_phase'",
"]",
"[",
"'sunset'",
"]",
"[",
"'minute'",
"]",
".",
"to_i",
"}",
"}",
"end"
] | Gets sunrise and sunset information for the current day at the current location.
@param location [String] The place to get the info for.
@return [Hash<Symbol, Hash<Symbol, Integer>>] A hash containing two hashes at keys :rise and :set for sunrise
and sunset information respectively. They each contain an :hour key and a :minute key which point to the hour
and minute that the sun will rise or set. | [
"Gets",
"sunrise",
"and",
"sunset",
"information",
"for",
"the",
"current",
"day",
"at",
"the",
"current",
"location",
"."
] | 4d97db082448765b67ef5112c89346e502a74858 | https://github.com/elifoster/weatheruby/blob/4d97db082448765b67ef5112c89346e502a74858/lib/weather/actions.rb#L52-L64 | train |
elifoster/weatheruby | lib/weather/actions.rb | Weather.Actions.parse_simple_forecast | def parse_simple_forecast(response)
ret = {}
response['forecast']['txt_forecast']['forecastday'].each do |f|
ret[f['period']] = {
weekday_name: f['title'],
text: f['fcttext'],
text_metric: f['fcttext_metric'],
image_url: f['icon_url']
}
end
ret
end | ruby | def parse_simple_forecast(response)
ret = {}
response['forecast']['txt_forecast']['forecastday'].each do |f|
ret[f['period']] = {
weekday_name: f['title'],
text: f['fcttext'],
text_metric: f['fcttext_metric'],
image_url: f['icon_url']
}
end
ret
end | [
"def",
"parse_simple_forecast",
"(",
"response",
")",
"ret",
"=",
"{",
"}",
"response",
"[",
"'forecast'",
"]",
"[",
"'txt_forecast'",
"]",
"[",
"'forecastday'",
"]",
".",
"each",
"do",
"|",
"f",
"|",
"ret",
"[",
"f",
"[",
"'period'",
"]",
"]",
"=",
"{",
"weekday_name",
":",
"f",
"[",
"'title'",
"]",
",",
"text",
":",
"f",
"[",
"'fcttext'",
"]",
",",
"text_metric",
":",
"f",
"[",
"'fcttext_metric'",
"]",
",",
"image_url",
":",
"f",
"[",
"'icon_url'",
"]",
"}",
"end",
"ret",
"end"
] | Parses the simple forecast information. | [
"Parses",
"the",
"simple",
"forecast",
"information",
"."
] | 4d97db082448765b67ef5112c89346e502a74858 | https://github.com/elifoster/weatheruby/blob/4d97db082448765b67ef5112c89346e502a74858/lib/weather/actions.rb#L257-L270 | train |
elifoster/weatheruby | lib/weather/actions.rb | Weather.Actions.parse_complex_forecast | def parse_complex_forecast(response)
ret = {}
response['forecast']['simpleforecast']['forecastday'].each do |f|
date = f['date']
ret[f['period'] - 1] = {
date: DateTime.new(date['year'], date['month'], date['day'], date['hour'], date['min'].to_i, date['sec'], date['tz_short']),
weekday_name: date['weekday'],
high_f: f['high']['fahrenheit'].to_i,
high_c: f['high']['celsius'].to_i,
low_f: f['low']['fahrenheit'].to_i,
low_c: f['low']['celsius'].to_i,
conditions: f['conditions'].to_i,
image_url: f['icon_url'],
snow: {
snow_total_in: f['snow_allday']['in'],
snow_total_cm: f['snow_allday']['cm'],
snow_night_in: f['snow_night']['in'],
snow_night_cm: f['snow_night']['cm'],
snow_day_in: f['snow_day']['in'],
snow_day_cm: f['snow_day']['cm']
},
quantative_precipitation: {
qpf_total_in: f['qpf_allday']['in'],
qpf_total_cm: f['qpf_allday']['cm'],
qpf_night_in: f['qpf_night']['in'],
qpf_night_cm: f['qpf_night']['cm'],
qpf_day_in: f['qpf_day']['in'],
qpf_day_cm: f['qpf_day']['cm']
},
wind: {
average_mph: f['avewind']['mph'],
average_kph: f['avewind']['kph'],
average_dir: f['avewind']['dir'],
average_temp: f['avewind']['degrees'],
max_mph: f['maxwind']['mph'],
max_kph: f['maxwind']['kph'],
max_dir: f['maxwind']['dir'],
max_temp: f['maxwind']['degrees']
}
}
end
ret
end | ruby | def parse_complex_forecast(response)
ret = {}
response['forecast']['simpleforecast']['forecastday'].each do |f|
date = f['date']
ret[f['period'] - 1] = {
date: DateTime.new(date['year'], date['month'], date['day'], date['hour'], date['min'].to_i, date['sec'], date['tz_short']),
weekday_name: date['weekday'],
high_f: f['high']['fahrenheit'].to_i,
high_c: f['high']['celsius'].to_i,
low_f: f['low']['fahrenheit'].to_i,
low_c: f['low']['celsius'].to_i,
conditions: f['conditions'].to_i,
image_url: f['icon_url'],
snow: {
snow_total_in: f['snow_allday']['in'],
snow_total_cm: f['snow_allday']['cm'],
snow_night_in: f['snow_night']['in'],
snow_night_cm: f['snow_night']['cm'],
snow_day_in: f['snow_day']['in'],
snow_day_cm: f['snow_day']['cm']
},
quantative_precipitation: {
qpf_total_in: f['qpf_allday']['in'],
qpf_total_cm: f['qpf_allday']['cm'],
qpf_night_in: f['qpf_night']['in'],
qpf_night_cm: f['qpf_night']['cm'],
qpf_day_in: f['qpf_day']['in'],
qpf_day_cm: f['qpf_day']['cm']
},
wind: {
average_mph: f['avewind']['mph'],
average_kph: f['avewind']['kph'],
average_dir: f['avewind']['dir'],
average_temp: f['avewind']['degrees'],
max_mph: f['maxwind']['mph'],
max_kph: f['maxwind']['kph'],
max_dir: f['maxwind']['dir'],
max_temp: f['maxwind']['degrees']
}
}
end
ret
end | [
"def",
"parse_complex_forecast",
"(",
"response",
")",
"ret",
"=",
"{",
"}",
"response",
"[",
"'forecast'",
"]",
"[",
"'simpleforecast'",
"]",
"[",
"'forecastday'",
"]",
".",
"each",
"do",
"|",
"f",
"|",
"date",
"=",
"f",
"[",
"'date'",
"]",
"ret",
"[",
"f",
"[",
"'period'",
"]",
"-",
"1",
"]",
"=",
"{",
"date",
":",
"DateTime",
".",
"new",
"(",
"date",
"[",
"'year'",
"]",
",",
"date",
"[",
"'month'",
"]",
",",
"date",
"[",
"'day'",
"]",
",",
"date",
"[",
"'hour'",
"]",
",",
"date",
"[",
"'min'",
"]",
".",
"to_i",
",",
"date",
"[",
"'sec'",
"]",
",",
"date",
"[",
"'tz_short'",
"]",
")",
",",
"weekday_name",
":",
"date",
"[",
"'weekday'",
"]",
",",
"high_f",
":",
"f",
"[",
"'high'",
"]",
"[",
"'fahrenheit'",
"]",
".",
"to_i",
",",
"high_c",
":",
"f",
"[",
"'high'",
"]",
"[",
"'celsius'",
"]",
".",
"to_i",
",",
"low_f",
":",
"f",
"[",
"'low'",
"]",
"[",
"'fahrenheit'",
"]",
".",
"to_i",
",",
"low_c",
":",
"f",
"[",
"'low'",
"]",
"[",
"'celsius'",
"]",
".",
"to_i",
",",
"conditions",
":",
"f",
"[",
"'conditions'",
"]",
".",
"to_i",
",",
"image_url",
":",
"f",
"[",
"'icon_url'",
"]",
",",
"snow",
":",
"{",
"snow_total_in",
":",
"f",
"[",
"'snow_allday'",
"]",
"[",
"'in'",
"]",
",",
"snow_total_cm",
":",
"f",
"[",
"'snow_allday'",
"]",
"[",
"'cm'",
"]",
",",
"snow_night_in",
":",
"f",
"[",
"'snow_night'",
"]",
"[",
"'in'",
"]",
",",
"snow_night_cm",
":",
"f",
"[",
"'snow_night'",
"]",
"[",
"'cm'",
"]",
",",
"snow_day_in",
":",
"f",
"[",
"'snow_day'",
"]",
"[",
"'in'",
"]",
",",
"snow_day_cm",
":",
"f",
"[",
"'snow_day'",
"]",
"[",
"'cm'",
"]",
"}",
",",
"quantative_precipitation",
":",
"{",
"qpf_total_in",
":",
"f",
"[",
"'qpf_allday'",
"]",
"[",
"'in'",
"]",
",",
"qpf_total_cm",
":",
"f",
"[",
"'qpf_allday'",
"]",
"[",
"'cm'",
"]",
",",
"qpf_night_in",
":",
"f",
"[",
"'qpf_night'",
"]",
"[",
"'in'",
"]",
",",
"qpf_night_cm",
":",
"f",
"[",
"'qpf_night'",
"]",
"[",
"'cm'",
"]",
",",
"qpf_day_in",
":",
"f",
"[",
"'qpf_day'",
"]",
"[",
"'in'",
"]",
",",
"qpf_day_cm",
":",
"f",
"[",
"'qpf_day'",
"]",
"[",
"'cm'",
"]",
"}",
",",
"wind",
":",
"{",
"average_mph",
":",
"f",
"[",
"'avewind'",
"]",
"[",
"'mph'",
"]",
",",
"average_kph",
":",
"f",
"[",
"'avewind'",
"]",
"[",
"'kph'",
"]",
",",
"average_dir",
":",
"f",
"[",
"'avewind'",
"]",
"[",
"'dir'",
"]",
",",
"average_temp",
":",
"f",
"[",
"'avewind'",
"]",
"[",
"'degrees'",
"]",
",",
"max_mph",
":",
"f",
"[",
"'maxwind'",
"]",
"[",
"'mph'",
"]",
",",
"max_kph",
":",
"f",
"[",
"'maxwind'",
"]",
"[",
"'kph'",
"]",
",",
"max_dir",
":",
"f",
"[",
"'maxwind'",
"]",
"[",
"'dir'",
"]",
",",
"max_temp",
":",
"f",
"[",
"'maxwind'",
"]",
"[",
"'degrees'",
"]",
"}",
"}",
"end",
"ret",
"end"
] | Parses the complex forecast information. | [
"Parses",
"the",
"complex",
"forecast",
"information",
"."
] | 4d97db082448765b67ef5112c89346e502a74858 | https://github.com/elifoster/weatheruby/blob/4d97db082448765b67ef5112c89346e502a74858/lib/weather/actions.rb#L273-L317 | train |
wilson/revenant | lib/revenant/manager.rb | Revenant.Manager.reopen_io | def reopen_io(io, path, mode = nil)
begin
if mode
io.reopen(path, mode)
else
io.reopen(path)
end
io.binmode
rescue ::Exception
end
end | ruby | def reopen_io(io, path, mode = nil)
begin
if mode
io.reopen(path, mode)
else
io.reopen(path)
end
io.binmode
rescue ::Exception
end
end | [
"def",
"reopen_io",
"(",
"io",
",",
"path",
",",
"mode",
"=",
"nil",
")",
"begin",
"if",
"mode",
"io",
".",
"reopen",
"(",
"path",
",",
"mode",
")",
"else",
"io",
".",
"reopen",
"(",
"path",
")",
"end",
"io",
".",
"binmode",
"rescue",
"::",
"Exception",
"end",
"end"
] | Attempts to reopen an IO object. | [
"Attempts",
"to",
"reopen",
"an",
"IO",
"object",
"."
] | 80fe65742de54ce0c5a8e6c56cea7003fe286746 | https://github.com/wilson/revenant/blob/80fe65742de54ce0c5a8e6c56cea7003fe286746/lib/revenant/manager.rb#L49-L59 | train |
dlangevin/gxapi_rails | lib/gxapi/controller_methods.rb | Gxapi.ControllerMethods.gxapi_get_variant | def gxapi_get_variant(identifier, ivar_name = :variant)
# handle override
if params[ivar_name]
val = Gxapi::Ostruct.new(
value: {
index: -1,
experiment_id: nil,
name: params[ivar_name]
}
)
else
val = self.gxapi_base.get_variant(identifier)
end
return instance_variable_set("@#{ivar_name}", val)
end | ruby | def gxapi_get_variant(identifier, ivar_name = :variant)
# handle override
if params[ivar_name]
val = Gxapi::Ostruct.new(
value: {
index: -1,
experiment_id: nil,
name: params[ivar_name]
}
)
else
val = self.gxapi_base.get_variant(identifier)
end
return instance_variable_set("@#{ivar_name}", val)
end | [
"def",
"gxapi_get_variant",
"(",
"identifier",
",",
"ivar_name",
"=",
":variant",
")",
"if",
"params",
"[",
"ivar_name",
"]",
"val",
"=",
"Gxapi",
"::",
"Ostruct",
".",
"new",
"(",
"value",
":",
"{",
"index",
":",
"-",
"1",
",",
"experiment_id",
":",
"nil",
",",
"name",
":",
"params",
"[",
"ivar_name",
"]",
"}",
")",
"else",
"val",
"=",
"self",
".",
"gxapi_base",
".",
"get_variant",
"(",
"identifier",
")",
"end",
"return",
"instance_variable_set",
"(",
"\"@#{ivar_name}\"",
",",
"val",
")",
"end"
] | Get the variant and set it as an instance variable, handling
overriding by passing in the URL
@param identifier [String, Hash] Name for the experiment or ID hash
for the experiment
@param ivar_name [String, Symbol] Name for the variable
@example
def my_action
gxapi_get_variant("Name")
end
# OR
def my_action
gxapi_get_variant(id: 'id_from_google')
end
@return [Celluloid::Future, Gxapi::Ostruct] Variant value | [
"Get",
"the",
"variant",
"and",
"set",
"it",
"as",
"an",
"instance",
"variable",
"handling",
"overriding",
"by",
"passing",
"in",
"the",
"URL"
] | 21361227f0c70118b38f7fa372a18c0ae7aab810 | https://github.com/dlangevin/gxapi_rails/blob/21361227f0c70118b38f7fa372a18c0ae7aab810/lib/gxapi/controller_methods.rb#L25-L39 | train |
rack-webprofiler/rack-webprofiler | lib/rack/web_profiler.rb | Rack.WebProfiler.process | def process(request, body, status, headers, exception = nil)
request.env[ENV_RUNTIME] = Time.now.to_f - request.env[ENV_RUNTIME_START]
request.env[ENV_EXCEPTION] = nil
if !exception.nil?
request.env[ENV_EXCEPTION] = exception
WebProfiler::Engine.process_exception(request).finish
else
WebProfiler::Engine.process(request, body, status, headers).finish
end
end | ruby | def process(request, body, status, headers, exception = nil)
request.env[ENV_RUNTIME] = Time.now.to_f - request.env[ENV_RUNTIME_START]
request.env[ENV_EXCEPTION] = nil
if !exception.nil?
request.env[ENV_EXCEPTION] = exception
WebProfiler::Engine.process_exception(request).finish
else
WebProfiler::Engine.process(request, body, status, headers).finish
end
end | [
"def",
"process",
"(",
"request",
",",
"body",
",",
"status",
",",
"headers",
",",
"exception",
"=",
"nil",
")",
"request",
".",
"env",
"[",
"ENV_RUNTIME",
"]",
"=",
"Time",
".",
"now",
".",
"to_f",
"-",
"request",
".",
"env",
"[",
"ENV_RUNTIME_START",
"]",
"request",
".",
"env",
"[",
"ENV_EXCEPTION",
"]",
"=",
"nil",
"if",
"!",
"exception",
".",
"nil?",
"request",
".",
"env",
"[",
"ENV_EXCEPTION",
"]",
"=",
"exception",
"WebProfiler",
"::",
"Engine",
".",
"process_exception",
"(",
"request",
")",
".",
"finish",
"else",
"WebProfiler",
"::",
"Engine",
".",
"process",
"(",
"request",
",",
"body",
",",
"status",
",",
"headers",
")",
".",
"finish",
"end",
"end"
] | Process the request.
@param request [Rack::WebProfiler::Request]
@param body
@param status [Integer]
@param headers [Hash]
@param exception [Exception, nil]
@return [Rack::Response] | [
"Process",
"the",
"request",
"."
] | bdb411fbb41eeddf612bbde91301ff94b3853a12 | https://github.com/rack-webprofiler/rack-webprofiler/blob/bdb411fbb41eeddf612bbde91301ff94b3853a12/lib/rack/web_profiler.rb#L134-L144 | train |
strong-code/pirata | lib/pirata/search.rb | Pirata.Search.search | def search(page = 0)
#build URL ex: http://thepiratebay.se/search/cats/0/99/0
url = Pirata.config[:base_url] + "/search/#{URI.escape(@query)}" + "/#{page.to_s}" + "/#{@sort_type}" + "/#{@category}"
html = Pirata::Search.parse_html(url)
Pirata::Search::parse_search_page(html, self)
end | ruby | def search(page = 0)
#build URL ex: http://thepiratebay.se/search/cats/0/99/0
url = Pirata.config[:base_url] + "/search/#{URI.escape(@query)}" + "/#{page.to_s}" + "/#{@sort_type}" + "/#{@category}"
html = Pirata::Search.parse_html(url)
Pirata::Search::parse_search_page(html, self)
end | [
"def",
"search",
"(",
"page",
"=",
"0",
")",
"url",
"=",
"Pirata",
".",
"config",
"[",
":base_url",
"]",
"+",
"\"/search/#{URI.escape(@query)}\"",
"+",
"\"/#{page.to_s}\"",
"+",
"\"/#{@sort_type}\"",
"+",
"\"/#{@category}\"",
"html",
"=",
"Pirata",
"::",
"Search",
".",
"parse_html",
"(",
"url",
")",
"Pirata",
"::",
"Search",
"::",
"parse_search_page",
"(",
"html",
",",
"self",
")",
"end"
] | Perform a search and return an array of Torrent objects | [
"Perform",
"a",
"search",
"and",
"return",
"an",
"array",
"of",
"Torrent",
"objects"
] | 6b4b0d58bda71caf053aeadaae59834e5a45a1c6 | https://github.com/strong-code/pirata/blob/6b4b0d58bda71caf053aeadaae59834e5a45a1c6/lib/pirata/search.rb#L24-L29 | train |
strong-code/pirata | lib/pirata/search.rb | Pirata.Search.search_page | def search_page(page)
raise "Search must be multipage to search pages" if !multipage?
raise "Page must be a valid, positive integer" if page.class != Fixnum || page < 0
raise "Invalid page range" if page > @pages
self.search(page)
end | ruby | def search_page(page)
raise "Search must be multipage to search pages" if !multipage?
raise "Page must be a valid, positive integer" if page.class != Fixnum || page < 0
raise "Invalid page range" if page > @pages
self.search(page)
end | [
"def",
"search_page",
"(",
"page",
")",
"raise",
"\"Search must be multipage to search pages\"",
"if",
"!",
"multipage?",
"raise",
"\"Page must be a valid, positive integer\"",
"if",
"page",
".",
"class",
"!=",
"Fixnum",
"||",
"page",
"<",
"0",
"raise",
"\"Invalid page range\"",
"if",
"page",
">",
"@pages",
"self",
".",
"search",
"(",
"page",
")",
"end"
] | Return the n page results of a search, assuming it is multipage | [
"Return",
"the",
"n",
"page",
"results",
"of",
"a",
"search",
"assuming",
"it",
"is",
"multipage"
] | 6b4b0d58bda71caf053aeadaae59834e5a45a1c6 | https://github.com/strong-code/pirata/blob/6b4b0d58bda71caf053aeadaae59834e5a45a1c6/lib/pirata/search.rb#L32-L38 | train |
strong-code/pirata | lib/pirata/search.rb | Pirata.Search.parse_html | def parse_html(url)
response = open(url, :allow_redirections => Pirata.config[:redirect])
Nokogiri::HTML(response)
end | ruby | def parse_html(url)
response = open(url, :allow_redirections => Pirata.config[:redirect])
Nokogiri::HTML(response)
end | [
"def",
"parse_html",
"(",
"url",
")",
"response",
"=",
"open",
"(",
"url",
",",
":allow_redirections",
"=>",
"Pirata",
".",
"config",
"[",
":redirect",
"]",
")",
"Nokogiri",
"::",
"HTML",
"(",
"response",
")",
"end"
] | Parse HTML body of a supplied URL | [
"Parse",
"HTML",
"body",
"of",
"a",
"supplied",
"URL"
] | 6b4b0d58bda71caf053aeadaae59834e5a45a1c6 | https://github.com/strong-code/pirata/blob/6b4b0d58bda71caf053aeadaae59834e5a45a1c6/lib/pirata/search.rb#L70-L73 | train |
etailer/parcel_api | lib/parcel_api/shipping_options.rb | ParcelApi.ShippingOptions.get_international | def get_international(parcel_params)
response = @connection.get INTERNATIONAL_URL, params: parcel_params
options = response.parsed.tap do |so|
so.delete('success')
so.delete('message_id')
end
RecursiveOpenStruct.new(options, recurse_over_arrays: true)
end | ruby | def get_international(parcel_params)
response = @connection.get INTERNATIONAL_URL, params: parcel_params
options = response.parsed.tap do |so|
so.delete('success')
so.delete('message_id')
end
RecursiveOpenStruct.new(options, recurse_over_arrays: true)
end | [
"def",
"get_international",
"(",
"parcel_params",
")",
"response",
"=",
"@connection",
".",
"get",
"INTERNATIONAL_URL",
",",
"params",
":",
"parcel_params",
"options",
"=",
"response",
".",
"parsed",
".",
"tap",
"do",
"|",
"so",
"|",
"so",
".",
"delete",
"(",
"'success'",
")",
"so",
".",
"delete",
"(",
"'message_id'",
")",
"end",
"RecursiveOpenStruct",
".",
"new",
"(",
"options",
",",
"recurse_over_arrays",
":",
"true",
")",
"end"
] | Search for International Shipping Options
@param parcel_params [Hash] parcel parameters
@return [Array] return array of shipping options | [
"Search",
"for",
"International",
"Shipping",
"Options"
] | fcb8d64e45f7ba72bab48f143ac5115b0441aced | https://github.com/etailer/parcel_api/blob/fcb8d64e45f7ba72bab48f143ac5115b0441aced/lib/parcel_api/shipping_options.rb#L34-L41 | train |
26fe/tree.rb | lib/tree_rb/input_plugins/file_system/directory_walker.rb | TreeRb.DirTreeWalker.run | def run(dirname = nil, tree_node_visitor = nil, &block)
#
# args detection
#
if dirname and dirname.respond_to?(:enter_node)
tree_node_visitor = dirname
dirname = nil
end
#
# check dirname
#
if @dirname.nil? and dirname.nil?
raise 'missing starting directory'
end
@dirname = dirname if dirname
#
# check visitor
#
if tree_node_visitor and block
raise 'cannot use block and parameter together'
end
if tree_node_visitor
@visitor = tree_node_visitor
end
if block
@visitor = TreeNodeVisitor.new(&block)
end
unless @visitor
raise 'missing visitor'
end
#
# finally starts to process
#
process_directory(File.expand_path(@dirname))
@visitor
end | ruby | def run(dirname = nil, tree_node_visitor = nil, &block)
#
# args detection
#
if dirname and dirname.respond_to?(:enter_node)
tree_node_visitor = dirname
dirname = nil
end
#
# check dirname
#
if @dirname.nil? and dirname.nil?
raise 'missing starting directory'
end
@dirname = dirname if dirname
#
# check visitor
#
if tree_node_visitor and block
raise 'cannot use block and parameter together'
end
if tree_node_visitor
@visitor = tree_node_visitor
end
if block
@visitor = TreeNodeVisitor.new(&block)
end
unless @visitor
raise 'missing visitor'
end
#
# finally starts to process
#
process_directory(File.expand_path(@dirname))
@visitor
end | [
"def",
"run",
"(",
"dirname",
"=",
"nil",
",",
"tree_node_visitor",
"=",
"nil",
",",
"&",
"block",
")",
"if",
"dirname",
"and",
"dirname",
".",
"respond_to?",
"(",
":enter_node",
")",
"tree_node_visitor",
"=",
"dirname",
"dirname",
"=",
"nil",
"end",
"if",
"@dirname",
".",
"nil?",
"and",
"dirname",
".",
"nil?",
"raise",
"'missing starting directory'",
"end",
"@dirname",
"=",
"dirname",
"if",
"dirname",
"if",
"tree_node_visitor",
"and",
"block",
"raise",
"'cannot use block and parameter together'",
"end",
"if",
"tree_node_visitor",
"@visitor",
"=",
"tree_node_visitor",
"end",
"if",
"block",
"@visitor",
"=",
"TreeNodeVisitor",
".",
"new",
"(",
"&",
"block",
")",
"end",
"unless",
"@visitor",
"raise",
"'missing visitor'",
"end",
"process_directory",
"(",
"File",
".",
"expand_path",
"(",
"@dirname",
")",
")",
"@visitor",
"end"
] | Run the visitor through the directory tree
@overload run
@overload run(dirname)
@param [String] dirname
@yield define TreeNodeVisitor
@overload run(tree_node_visitor)
@param [TreeNodeVisitor]
@yield define TreeNodeVisitor
@overload run(dirname, tree_node_visitor)
@param [String] dirname
@param [TreeNodeVisitor]
@yield define TreeNodeVisitor
@return [TreeNodeVisitor] the visitor
@example Print the contents of tmp directory
w = DirTreeWalker.new
w.run("/tmp") do
on_visit_leaf_node { |pathname| puts pathname }
end.run | [
"Run",
"the",
"visitor",
"through",
"the",
"directory",
"tree"
] | 5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b | https://github.com/26fe/tree.rb/blob/5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b/lib/tree_rb/input_plugins/file_system/directory_walker.rb#L215-L257 | train |
26fe/tree.rb | lib/tree_rb/input_plugins/file_system/directory_walker.rb | TreeRb.DirTreeWalker.process_directory | def process_directory(dirname, level=1)
begin
entries = Dir.entries(dirname).sort
rescue Errno::EACCES => e
$stderr.puts e
@visitor.cannot_enter_node(dirname, e)
return
rescue Errno::EPERM => e
$stderr.puts e
@visitor.cannot_enter_node(dirname, e)
return
rescue Errno::ENOENT => e
$stderr.puts e
@visitor.cannot_enter_node(dirname, e)
return
end
@visitor.enter_node(dirname)
entries.each do |basename|
begin
next if basename == '.' or basename == '..' # ignore always "." and ".."
pathname = File.join(dirname, basename)
if File.directory?(pathname)
if not ignore_dir?(basename) and (@max_level.nil? or @max_level > level)
process_directory(pathname, level+1)
end
else
if !!@visit_file && match?(basename) && !ignore_file?(basename)
@visitor.visit_leaf(pathname)
end
end
rescue Errno::EACCES => e
$stderr.puts e
rescue Errno::EPERM => e
$stderr.puts e
rescue Errno::ENOENT => e
$stderr.puts e
end
end
@visitor.exit_node(dirname)
end | ruby | def process_directory(dirname, level=1)
begin
entries = Dir.entries(dirname).sort
rescue Errno::EACCES => e
$stderr.puts e
@visitor.cannot_enter_node(dirname, e)
return
rescue Errno::EPERM => e
$stderr.puts e
@visitor.cannot_enter_node(dirname, e)
return
rescue Errno::ENOENT => e
$stderr.puts e
@visitor.cannot_enter_node(dirname, e)
return
end
@visitor.enter_node(dirname)
entries.each do |basename|
begin
next if basename == '.' or basename == '..' # ignore always "." and ".."
pathname = File.join(dirname, basename)
if File.directory?(pathname)
if not ignore_dir?(basename) and (@max_level.nil? or @max_level > level)
process_directory(pathname, level+1)
end
else
if !!@visit_file && match?(basename) && !ignore_file?(basename)
@visitor.visit_leaf(pathname)
end
end
rescue Errno::EACCES => e
$stderr.puts e
rescue Errno::EPERM => e
$stderr.puts e
rescue Errno::ENOENT => e
$stderr.puts e
end
end
@visitor.exit_node(dirname)
end | [
"def",
"process_directory",
"(",
"dirname",
",",
"level",
"=",
"1",
")",
"begin",
"entries",
"=",
"Dir",
".",
"entries",
"(",
"dirname",
")",
".",
"sort",
"rescue",
"Errno",
"::",
"EACCES",
"=>",
"e",
"$stderr",
".",
"puts",
"e",
"@visitor",
".",
"cannot_enter_node",
"(",
"dirname",
",",
"e",
")",
"return",
"rescue",
"Errno",
"::",
"EPERM",
"=>",
"e",
"$stderr",
".",
"puts",
"e",
"@visitor",
".",
"cannot_enter_node",
"(",
"dirname",
",",
"e",
")",
"return",
"rescue",
"Errno",
"::",
"ENOENT",
"=>",
"e",
"$stderr",
".",
"puts",
"e",
"@visitor",
".",
"cannot_enter_node",
"(",
"dirname",
",",
"e",
")",
"return",
"end",
"@visitor",
".",
"enter_node",
"(",
"dirname",
")",
"entries",
".",
"each",
"do",
"|",
"basename",
"|",
"begin",
"next",
"if",
"basename",
"==",
"'.'",
"or",
"basename",
"==",
"'..'",
"pathname",
"=",
"File",
".",
"join",
"(",
"dirname",
",",
"basename",
")",
"if",
"File",
".",
"directory?",
"(",
"pathname",
")",
"if",
"not",
"ignore_dir?",
"(",
"basename",
")",
"and",
"(",
"@max_level",
".",
"nil?",
"or",
"@max_level",
">",
"level",
")",
"process_directory",
"(",
"pathname",
",",
"level",
"+",
"1",
")",
"end",
"else",
"if",
"!",
"!",
"@visit_file",
"&&",
"match?",
"(",
"basename",
")",
"&&",
"!",
"ignore_file?",
"(",
"basename",
")",
"@visitor",
".",
"visit_leaf",
"(",
"pathname",
")",
"end",
"end",
"rescue",
"Errno",
"::",
"EACCES",
"=>",
"e",
"$stderr",
".",
"puts",
"e",
"rescue",
"Errno",
"::",
"EPERM",
"=>",
"e",
"$stderr",
".",
"puts",
"e",
"rescue",
"Errno",
"::",
"ENOENT",
"=>",
"e",
"$stderr",
".",
"puts",
"e",
"end",
"end",
"@visitor",
".",
"exit_node",
"(",
"dirname",
")",
"end"
] | recurse on other directories | [
"recurse",
"on",
"other",
"directories"
] | 5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b | https://github.com/26fe/tree.rb/blob/5ecf0cfbbc439e27c72b9676d6a1ccee8e6bb02b/lib/tree_rb/input_plugins/file_system/directory_walker.rb#L274-L317 | train |
marcmo/cxxproject | lib/cxxproject/plugin_context.rb | Cxxproject.PluginContext.cxx_plugin | def cxx_plugin(&blk)
if blk.arity != @expected_arity
return
end
case blk.arity
when 0
blk.call()
when 3
blk.call(@cxxproject2rake, @building_blocks, @log)
end
end | ruby | def cxx_plugin(&blk)
if blk.arity != @expected_arity
return
end
case blk.arity
when 0
blk.call()
when 3
blk.call(@cxxproject2rake, @building_blocks, @log)
end
end | [
"def",
"cxx_plugin",
"(",
"&",
"blk",
")",
"if",
"blk",
".",
"arity",
"!=",
"@expected_arity",
"return",
"end",
"case",
"blk",
".",
"arity",
"when",
"0",
"blk",
".",
"call",
"(",
")",
"when",
"3",
"blk",
".",
"call",
"(",
"@cxxproject2rake",
",",
"@building_blocks",
",",
"@log",
")",
"end",
"end"
] | method for plugins to get the
cxxproject2rake
building_blocks
log | [
"method",
"for",
"plugins",
"to",
"get",
"the",
"cxxproject2rake",
"building_blocks",
"log"
] | 3740a09d6a143acd96bde3d2ff79055a6b810da4 | https://github.com/marcmo/cxxproject/blob/3740a09d6a143acd96bde3d2ff79055a6b810da4/lib/cxxproject/plugin_context.rb#L37-L48 | train |
payout/podbay | lib/podbay/consul.rb | Podbay.Consul.node_healthy? | def node_healthy?(hostname, services = [], iterations = 60)
print "Waiting for #{hostname} to become healthy"
services = services.reject { |s| get_service_check(s).empty? }.freeze
iterations.times do
print '.'
checks = hostname_health_checks(hostname)
has_services = (services - checks.map { |c| c['ServiceName'] }).empty?
passing_checks = checks.all? { |c| c['Status'] == 'passing' }
if !checks.empty? && has_services && passing_checks
unless services.empty?
print " Services: #{services.join(', ').inspect} Healthy and".green
end
puts ' Node Healthy!'.green
return true
end
sleep(6)
end
false
end | ruby | def node_healthy?(hostname, services = [], iterations = 60)
print "Waiting for #{hostname} to become healthy"
services = services.reject { |s| get_service_check(s).empty? }.freeze
iterations.times do
print '.'
checks = hostname_health_checks(hostname)
has_services = (services - checks.map { |c| c['ServiceName'] }).empty?
passing_checks = checks.all? { |c| c['Status'] == 'passing' }
if !checks.empty? && has_services && passing_checks
unless services.empty?
print " Services: #{services.join(', ').inspect} Healthy and".green
end
puts ' Node Healthy!'.green
return true
end
sleep(6)
end
false
end | [
"def",
"node_healthy?",
"(",
"hostname",
",",
"services",
"=",
"[",
"]",
",",
"iterations",
"=",
"60",
")",
"print",
"\"Waiting for #{hostname} to become healthy\"",
"services",
"=",
"services",
".",
"reject",
"{",
"|",
"s",
"|",
"get_service_check",
"(",
"s",
")",
".",
"empty?",
"}",
".",
"freeze",
"iterations",
".",
"times",
"do",
"print",
"'.'",
"checks",
"=",
"hostname_health_checks",
"(",
"hostname",
")",
"has_services",
"=",
"(",
"services",
"-",
"checks",
".",
"map",
"{",
"|",
"c",
"|",
"c",
"[",
"'ServiceName'",
"]",
"}",
")",
".",
"empty?",
"passing_checks",
"=",
"checks",
".",
"all?",
"{",
"|",
"c",
"|",
"c",
"[",
"'Status'",
"]",
"==",
"'passing'",
"}",
"if",
"!",
"checks",
".",
"empty?",
"&&",
"has_services",
"&&",
"passing_checks",
"unless",
"services",
".",
"empty?",
"print",
"\" Services: #{services.join(', ').inspect} Healthy and\"",
".",
"green",
"end",
"puts",
"' Node Healthy!'",
".",
"green",
"return",
"true",
"end",
"sleep",
"(",
"6",
")",
"end",
"false",
"end"
] | Wait for all health checks on the host to become healthy.
services - services to perform health checks on (if health checks are
defined) | [
"Wait",
"for",
"all",
"health",
"checks",
"on",
"the",
"host",
"to",
"become",
"healthy",
"."
] | a17cc1db6a1f032d9d7005136e4176dbe7f3a73d | https://github.com/payout/podbay/blob/a17cc1db6a1f032d9d7005136e4176dbe7f3a73d/lib/podbay/consul.rb#L31-L56 | train |
payout/podbay | lib/podbay/consul.rb | Podbay.Consul.available_services | def available_services(index = nil)
loop do
begin
resp, nindex = _service.get_all(index: index)
return [resp.keys - ['consul'], nindex] if nindex != index
rescue Diplomat::Timeout
# Continue waiting
end
end
end | ruby | def available_services(index = nil)
loop do
begin
resp, nindex = _service.get_all(index: index)
return [resp.keys - ['consul'], nindex] if nindex != index
rescue Diplomat::Timeout
# Continue waiting
end
end
end | [
"def",
"available_services",
"(",
"index",
"=",
"nil",
")",
"loop",
"do",
"begin",
"resp",
",",
"nindex",
"=",
"_service",
".",
"get_all",
"(",
"index",
":",
"index",
")",
"return",
"[",
"resp",
".",
"keys",
"-",
"[",
"'consul'",
"]",
",",
"nindex",
"]",
"if",
"nindex",
"!=",
"index",
"rescue",
"Diplomat",
"::",
"Timeout",
"end",
"end",
"end"
] | Blocks forever waiting for updates to the list of available services. | [
"Blocks",
"forever",
"waiting",
"for",
"updates",
"to",
"the",
"list",
"of",
"available",
"services",
"."
] | a17cc1db6a1f032d9d7005136e4176dbe7f3a73d | https://github.com/payout/podbay/blob/a17cc1db6a1f032d9d7005136e4176dbe7f3a73d/lib/podbay/consul.rb#L102-L111 | train |
payout/podbay | lib/podbay/consul.rb | Podbay.Consul.service_addresses | def service_addresses(service, index = nil)
loop do
addresses, nindex = service_addresses!(service, index)
return [addresses, nindex] if addresses && nindex
end
end | ruby | def service_addresses(service, index = nil)
loop do
addresses, nindex = service_addresses!(service, index)
return [addresses, nindex] if addresses && nindex
end
end | [
"def",
"service_addresses",
"(",
"service",
",",
"index",
"=",
"nil",
")",
"loop",
"do",
"addresses",
",",
"nindex",
"=",
"service_addresses!",
"(",
"service",
",",
"index",
")",
"return",
"[",
"addresses",
",",
"nindex",
"]",
"if",
"addresses",
"&&",
"nindex",
"end",
"end"
] | Blocks forever waiting for updates to service addresses. | [
"Blocks",
"forever",
"waiting",
"for",
"updates",
"to",
"service",
"addresses",
"."
] | a17cc1db6a1f032d9d7005136e4176dbe7f3a73d | https://github.com/payout/podbay/blob/a17cc1db6a1f032d9d7005136e4176dbe7f3a73d/lib/podbay/consul.rb#L115-L120 | train |
payout/podbay | lib/podbay/consul.rb | Podbay.Consul.service_addresses! | def service_addresses!(service, index = nil)
meta = {}
resp = _service.get(service, :all, {index: index, wait: '2s'}, meta)
if (nindex = meta[:index]) != index
addresses = resp.map do |address|
{
id: address.ServiceID,
ip: address.ServiceAddress,
node: address.Node,
port: address.ServicePort
}
end
[addresses, nindex]
end
end | ruby | def service_addresses!(service, index = nil)
meta = {}
resp = _service.get(service, :all, {index: index, wait: '2s'}, meta)
if (nindex = meta[:index]) != index
addresses = resp.map do |address|
{
id: address.ServiceID,
ip: address.ServiceAddress,
node: address.Node,
port: address.ServicePort
}
end
[addresses, nindex]
end
end | [
"def",
"service_addresses!",
"(",
"service",
",",
"index",
"=",
"nil",
")",
"meta",
"=",
"{",
"}",
"resp",
"=",
"_service",
".",
"get",
"(",
"service",
",",
":all",
",",
"{",
"index",
":",
"index",
",",
"wait",
":",
"'2s'",
"}",
",",
"meta",
")",
"if",
"(",
"nindex",
"=",
"meta",
"[",
":index",
"]",
")",
"!=",
"index",
"addresses",
"=",
"resp",
".",
"map",
"do",
"|",
"address",
"|",
"{",
"id",
":",
"address",
".",
"ServiceID",
",",
"ip",
":",
"address",
".",
"ServiceAddress",
",",
"node",
":",
"address",
".",
"Node",
",",
"port",
":",
"address",
".",
"ServicePort",
"}",
"end",
"[",
"addresses",
",",
"nindex",
"]",
"end",
"end"
] | Non-blocking request for service_addresses. | [
"Non",
"-",
"blocking",
"request",
"for",
"service_addresses",
"."
] | a17cc1db6a1f032d9d7005136e4176dbe7f3a73d | https://github.com/payout/podbay/blob/a17cc1db6a1f032d9d7005136e4176dbe7f3a73d/lib/podbay/consul.rb#L124-L140 | train |
kamui/rack-accept_headers | lib/rack/accept_headers/media_type.rb | Rack::AcceptHeaders.MediaType.matches | def matches(media_type)
type, subtype, params = parse_media_type(media_type)
values.select {|v|
if v == media_type || v == '*/*'
true
else
t, s, p = parse_media_type(v)
t == type && (s == '*' || s == subtype) && (p == '' || params_match?(params, p))
end
}.sort_by {|v|
# Most specific gets precedence.
v.length
}.reverse
end | ruby | def matches(media_type)
type, subtype, params = parse_media_type(media_type)
values.select {|v|
if v == media_type || v == '*/*'
true
else
t, s, p = parse_media_type(v)
t == type && (s == '*' || s == subtype) && (p == '' || params_match?(params, p))
end
}.sort_by {|v|
# Most specific gets precedence.
v.length
}.reverse
end | [
"def",
"matches",
"(",
"media_type",
")",
"type",
",",
"subtype",
",",
"params",
"=",
"parse_media_type",
"(",
"media_type",
")",
"values",
".",
"select",
"{",
"|",
"v",
"|",
"if",
"v",
"==",
"media_type",
"||",
"v",
"==",
"'*/*'",
"true",
"else",
"t",
",",
"s",
",",
"p",
"=",
"parse_media_type",
"(",
"v",
")",
"t",
"==",
"type",
"&&",
"(",
"s",
"==",
"'*'",
"||",
"s",
"==",
"subtype",
")",
"&&",
"(",
"p",
"==",
"''",
"||",
"params_match?",
"(",
"params",
",",
"p",
")",
")",
"end",
"}",
".",
"sort_by",
"{",
"|",
"v",
"|",
"v",
".",
"length",
"}",
".",
"reverse",
"end"
] | Returns an array of media types from this header that match the given
+media_type+, ordered by precedence. | [
"Returns",
"an",
"array",
"of",
"media",
"types",
"from",
"this",
"header",
"that",
"match",
"the",
"given",
"+",
"media_type",
"+",
"ordered",
"by",
"precedence",
"."
] | 099bfbb919de86b5842c8e14be42b8b784e53f03 | https://github.com/kamui/rack-accept_headers/blob/099bfbb919de86b5842c8e14be42b8b784e53f03/lib/rack/accept_headers/media_type.rb#L27-L40 | train |
kamui/rack-accept_headers | lib/rack/accept_headers/media_type.rb | Rack::AcceptHeaders.MediaType.params_match? | def params_match?(params, match)
return true if params == match
parsed = parse_range_params(params)
parsed == parsed.merge(parse_range_params(match))
end | ruby | def params_match?(params, match)
return true if params == match
parsed = parse_range_params(params)
parsed == parsed.merge(parse_range_params(match))
end | [
"def",
"params_match?",
"(",
"params",
",",
"match",
")",
"return",
"true",
"if",
"params",
"==",
"match",
"parsed",
"=",
"parse_range_params",
"(",
"params",
")",
"parsed",
"==",
"parsed",
".",
"merge",
"(",
"parse_range_params",
"(",
"match",
")",
")",
"end"
] | Returns true if all parameters and values in +match+ are also present in
+params+. | [
"Returns",
"true",
"if",
"all",
"parameters",
"and",
"values",
"in",
"+",
"match",
"+",
"are",
"also",
"present",
"in",
"+",
"params",
"+",
"."
] | 099bfbb919de86b5842c8e14be42b8b784e53f03 | https://github.com/kamui/rack-accept_headers/blob/099bfbb919de86b5842c8e14be42b8b784e53f03/lib/rack/accept_headers/media_type.rb#L67-L71 | train |
drichert/moby | lib/moby/parts_of_speech.rb | Moby.PartsOfSpeech.words | def words(pos_name)
pos.select {|w, c| c.include?(pos_code_map.key(pos_name)) }.keys
end | ruby | def words(pos_name)
pos.select {|w, c| c.include?(pos_code_map.key(pos_name)) }.keys
end | [
"def",
"words",
"(",
"pos_name",
")",
"pos",
".",
"select",
"{",
"|",
"w",
",",
"c",
"|",
"c",
".",
"include?",
"(",
"pos_code_map",
".",
"key",
"(",
"pos_name",
")",
")",
"}",
".",
"keys",
"end"
] | Get words by pos name | [
"Get",
"words",
"by",
"pos",
"name"
] | 7fcbcaf0816832d0b0da0547204dea68cc1dcab9 | https://github.com/drichert/moby/blob/7fcbcaf0816832d0b0da0547204dea68cc1dcab9/lib/moby/parts_of_speech.rb#L69-L71 | train |
jarhart/rattler | lib/rattler/runtime/packrat_parser.rb | Rattler::Runtime.PackratParser.apply | def apply(match_method_name)
start_pos = @scanner.pos
if m = memo(match_method_name, start_pos)
recall m, match_method_name
else
m = inject_fail match_method_name, start_pos
save m, eval_rule(match_method_name)
end
end | ruby | def apply(match_method_name)
start_pos = @scanner.pos
if m = memo(match_method_name, start_pos)
recall m, match_method_name
else
m = inject_fail match_method_name, start_pos
save m, eval_rule(match_method_name)
end
end | [
"def",
"apply",
"(",
"match_method_name",
")",
"start_pos",
"=",
"@scanner",
".",
"pos",
"if",
"m",
"=",
"memo",
"(",
"match_method_name",
",",
"start_pos",
")",
"recall",
"m",
",",
"match_method_name",
"else",
"m",
"=",
"inject_fail",
"match_method_name",
",",
"start_pos",
"save",
"m",
",",
"eval_rule",
"(",
"match_method_name",
")",
"end",
"end"
] | Apply a rule by dispatching to the given match method. The result of
applying the rule is memoized so that the match method is invoked at most
once at a given parse position.
@param (see RecursiveDescentParser#apply)
@return (see RecursiveDescentParser#apply) | [
"Apply",
"a",
"rule",
"by",
"dispatching",
"to",
"the",
"given",
"match",
"method",
".",
"The",
"result",
"of",
"applying",
"the",
"rule",
"is",
"memoized",
"so",
"that",
"the",
"match",
"method",
"is",
"invoked",
"at",
"most",
"once",
"at",
"a",
"given",
"parse",
"position",
"."
] | 8b4efde2a05e9e790955bb635d4a1a9615893719 | https://github.com/jarhart/rattler/blob/8b4efde2a05e9e790955bb635d4a1a9615893719/lib/rattler/runtime/packrat_parser.rb#L29-L37 | train |
mikiobraun/jblas-ruby | lib/jblas/mixin_class.rb | JBLAS.MatrixClassMixin.from_array | def from_array(data)
n = data.length
if data.reject{|l| Numeric === l}.size == 0
a = self.new(n, 1)
(0...data.length).each do |i|
a[i, 0] = data[i]
end
return a
else
begin
lengths = data.collect{|v| v.length}
rescue
raise "All columns must be arrays"
end
raise "All columns must have equal length!" if lengths.min < lengths.max
a = self.new(n, lengths.max)
for i in 0...n
for j in 0...lengths.max
a[i,j] = data[i][j]
end
end
return a
end
end | ruby | def from_array(data)
n = data.length
if data.reject{|l| Numeric === l}.size == 0
a = self.new(n, 1)
(0...data.length).each do |i|
a[i, 0] = data[i]
end
return a
else
begin
lengths = data.collect{|v| v.length}
rescue
raise "All columns must be arrays"
end
raise "All columns must have equal length!" if lengths.min < lengths.max
a = self.new(n, lengths.max)
for i in 0...n
for j in 0...lengths.max
a[i,j] = data[i][j]
end
end
return a
end
end | [
"def",
"from_array",
"(",
"data",
")",
"n",
"=",
"data",
".",
"length",
"if",
"data",
".",
"reject",
"{",
"|",
"l",
"|",
"Numeric",
"===",
"l",
"}",
".",
"size",
"==",
"0",
"a",
"=",
"self",
".",
"new",
"(",
"n",
",",
"1",
")",
"(",
"0",
"...",
"data",
".",
"length",
")",
".",
"each",
"do",
"|",
"i",
"|",
"a",
"[",
"i",
",",
"0",
"]",
"=",
"data",
"[",
"i",
"]",
"end",
"return",
"a",
"else",
"begin",
"lengths",
"=",
"data",
".",
"collect",
"{",
"|",
"v",
"|",
"v",
".",
"length",
"}",
"rescue",
"raise",
"\"All columns must be arrays\"",
"end",
"raise",
"\"All columns must have equal length!\"",
"if",
"lengths",
".",
"min",
"<",
"lengths",
".",
"max",
"a",
"=",
"self",
".",
"new",
"(",
"n",
",",
"lengths",
".",
"max",
")",
"for",
"i",
"in",
"0",
"...",
"n",
"for",
"j",
"in",
"0",
"...",
"lengths",
".",
"max",
"a",
"[",
"i",
",",
"j",
"]",
"=",
"data",
"[",
"i",
"]",
"[",
"j",
"]",
"end",
"end",
"return",
"a",
"end",
"end"
] | Create a new matrix. There are two ways to use this function
<b>pass an array</b>::
Constructs a column vector. For example: DoubleMatrix.from_array 1, 2, 3
<b>pass an array of arrays</b>::
Constructs a matrix, inner arrays are rows. For
example: DoubleMatrix.from_array [[1,2,3],[4,5,6]]
See also [], JBLAS#mat | [
"Create",
"a",
"new",
"matrix",
".",
"There",
"are",
"two",
"ways",
"to",
"use",
"this",
"function"
] | 7233976c9e3b210e30bc36ead2b1e05ab3383fec | https://github.com/mikiobraun/jblas-ruby/blob/7233976c9e3b210e30bc36ead2b1e05ab3383fec/lib/jblas/mixin_class.rb#L55-L78 | train |
OpenBEL/bel_parser | examples/upgrade_kinase.rb | Main.TermASTGenerator.each | def each(io)
if block_given?
filter = BELParser::ASTFilter.new(
BELParser::ASTGenerator.new(io),
*TYPES)
filter.each do |results|
yield results
end
else
enum_for(:each, io)
end
end | ruby | def each(io)
if block_given?
filter = BELParser::ASTFilter.new(
BELParser::ASTGenerator.new(io),
*TYPES)
filter.each do |results|
yield results
end
else
enum_for(:each, io)
end
end | [
"def",
"each",
"(",
"io",
")",
"if",
"block_given?",
"filter",
"=",
"BELParser",
"::",
"ASTFilter",
".",
"new",
"(",
"BELParser",
"::",
"ASTGenerator",
".",
"new",
"(",
"io",
")",
",",
"*",
"TYPES",
")",
"filter",
".",
"each",
"do",
"|",
"results",
"|",
"yield",
"results",
"end",
"else",
"enum_for",
"(",
":each",
",",
"io",
")",
"end",
"end"
] | Yields Term AST to the block argument or provides an enumerator of
Term AST. | [
"Yields",
"Term",
"AST",
"to",
"the",
"block",
"argument",
"or",
"provides",
"an",
"enumerator",
"of",
"Term",
"AST",
"."
] | f0a35de93c300abff76c22e54696a83d22a4fbc9 | https://github.com/OpenBEL/bel_parser/blob/f0a35de93c300abff76c22e54696a83d22a4fbc9/examples/upgrade_kinase.rb#L20-L31 | train |
jemmyw/bisques | lib/bisques/aws_connection.rb | Bisques.AwsConnection.request | def request(method, path, query = {}, body = nil, headers = {})
AwsRequest.new(aws_http_connection).tap do |aws_request|
aws_request.credentials = credentials
aws_request.path = path
aws_request.region = region
aws_request.service = service
aws_request.method = method
aws_request.query = query
aws_request.body = body
aws_request.headers = headers
aws_request.make_request
end
end | ruby | def request(method, path, query = {}, body = nil, headers = {})
AwsRequest.new(aws_http_connection).tap do |aws_request|
aws_request.credentials = credentials
aws_request.path = path
aws_request.region = region
aws_request.service = service
aws_request.method = method
aws_request.query = query
aws_request.body = body
aws_request.headers = headers
aws_request.make_request
end
end | [
"def",
"request",
"(",
"method",
",",
"path",
",",
"query",
"=",
"{",
"}",
",",
"body",
"=",
"nil",
",",
"headers",
"=",
"{",
"}",
")",
"AwsRequest",
".",
"new",
"(",
"aws_http_connection",
")",
".",
"tap",
"do",
"|",
"aws_request",
"|",
"aws_request",
".",
"credentials",
"=",
"credentials",
"aws_request",
".",
"path",
"=",
"path",
"aws_request",
".",
"region",
"=",
"region",
"aws_request",
".",
"service",
"=",
"service",
"aws_request",
".",
"method",
"=",
"method",
"aws_request",
".",
"query",
"=",
"query",
"aws_request",
".",
"body",
"=",
"body",
"aws_request",
".",
"headers",
"=",
"headers",
"aws_request",
".",
"make_request",
"end",
"end"
] | Give the region, service and optionally the AwsCredentials.
@param [String] region the AWS region (ex. us-east-1)
@param [String] service the AWS service (ex. sqs)
@param [AwsCredentials] credentials
@example
class Sqs
include AwsConnection
def initialize(region)
super(region, 'sqs')
end
end
Perform an HTTP query to the given path using the given method (GET,
POST, PUT, DELETE). A hash of query params can be specified. A POST or
PUT body cna be specified as either a string or a hash of form params. A
hash of HTTP headers can be specified.
@param [String] method HTTP method, should be GET, POST, PUT or DELETE
@param [String] path
@param [Hash] query HTTP query params to send. Specify these as a hash, do not append them to the path.
@param [Hash,#to_s] body HTTP request body. This can be form data as a hash or a String. Only applies to POST and PUT HTTP methods.
@param [Hash] headers additional HTTP headers to send.
@return [AwsRequest] | [
"Give",
"the",
"region",
"service",
"and",
"optionally",
"the",
"AwsCredentials",
"."
] | c48ab555f07664752bcbf9e8deb99bd75cbdc41b | https://github.com/jemmyw/bisques/blob/c48ab555f07664752bcbf9e8deb99bd75cbdc41b/lib/bisques/aws_connection.rb#L70-L82 | train |
jemmyw/bisques | lib/bisques/aws_connection.rb | Bisques.AwsConnection.action | def action(action_name, path = "/", options = {})
retries = 0
begin
# If options given in place of path assume /
options, path = path, "/" if path.is_a?(Hash) && options.empty?
request(:post, path, {}, options.merge("Action" => action_name)).response.tap do |response|
unless response.success?
element = response.doc.xpath("//Error")
raise AwsActionError.new(element.xpath("Type").text, element.xpath("Code").text, element.xpath("Message").text, response.http_response.status)
end
end
rescue AwsActionError => e
if retries < 2 && (500..599).include?(e.status.to_i)
retries += 1
retry
else
raise e
end
end
end | ruby | def action(action_name, path = "/", options = {})
retries = 0
begin
# If options given in place of path assume /
options, path = path, "/" if path.is_a?(Hash) && options.empty?
request(:post, path, {}, options.merge("Action" => action_name)).response.tap do |response|
unless response.success?
element = response.doc.xpath("//Error")
raise AwsActionError.new(element.xpath("Type").text, element.xpath("Code").text, element.xpath("Message").text, response.http_response.status)
end
end
rescue AwsActionError => e
if retries < 2 && (500..599).include?(e.status.to_i)
retries += 1
retry
else
raise e
end
end
end | [
"def",
"action",
"(",
"action_name",
",",
"path",
"=",
"\"/\"",
",",
"options",
"=",
"{",
"}",
")",
"retries",
"=",
"0",
"begin",
"options",
",",
"path",
"=",
"path",
",",
"\"/\"",
"if",
"path",
".",
"is_a?",
"(",
"Hash",
")",
"&&",
"options",
".",
"empty?",
"request",
"(",
":post",
",",
"path",
",",
"{",
"}",
",",
"options",
".",
"merge",
"(",
"\"Action\"",
"=>",
"action_name",
")",
")",
".",
"response",
".",
"tap",
"do",
"|",
"response",
"|",
"unless",
"response",
".",
"success?",
"element",
"=",
"response",
".",
"doc",
".",
"xpath",
"(",
"\"//Error\"",
")",
"raise",
"AwsActionError",
".",
"new",
"(",
"element",
".",
"xpath",
"(",
"\"Type\"",
")",
".",
"text",
",",
"element",
".",
"xpath",
"(",
"\"Code\"",
")",
".",
"text",
",",
"element",
".",
"xpath",
"(",
"\"Message\"",
")",
".",
"text",
",",
"response",
".",
"http_response",
".",
"status",
")",
"end",
"end",
"rescue",
"AwsActionError",
"=>",
"e",
"if",
"retries",
"<",
"2",
"&&",
"(",
"500",
"..",
"599",
")",
".",
"include?",
"(",
"e",
".",
"status",
".",
"to_i",
")",
"retries",
"+=",
"1",
"retry",
"else",
"raise",
"e",
"end",
"end",
"end"
] | Call an AWS API with the given name at the given path. An optional hash
of options can be passed as arguments for the API call.
@note The API call will be automatically retried *once* if the returned status code is
in the 500 range.
@param [String] action_name
@param [String] path
@param [Hash] options
@return [AwsResponse]
@raise [AwsActionError] if the response is not successful. AWS error
information can be extracted from the exception. | [
"Call",
"an",
"AWS",
"API",
"with",
"the",
"given",
"name",
"at",
"the",
"given",
"path",
".",
"An",
"optional",
"hash",
"of",
"options",
"can",
"be",
"passed",
"as",
"arguments",
"for",
"the",
"API",
"call",
"."
] | c48ab555f07664752bcbf9e8deb99bd75cbdc41b | https://github.com/jemmyw/bisques/blob/c48ab555f07664752bcbf9e8deb99bd75cbdc41b/lib/bisques/aws_connection.rb#L96-L116 | train |
NullVoxPopuli/authorizable | lib/authorizable/controller.rb | Authorizable.Controller.is_authorized_for_action? | def is_authorized_for_action?
action = params[:action].to_sym
self.class.authorizable_config ||= DefaultConfig.config
if !self.class.authorizable_config[action]
action = Authorizable::Controller.alias_action(action)
end
# retrieve the settings for this particular controller action
settings_for_action = self.class.authorizable_config[action]
# continue with evaluation
result = is_authorized_for_action_with_config?(action, settings_for_action)
# if we are configured to raise exception instead of handle the error
# ourselves, raise the exception!
if Authorizable.configuration.raise_exception_on_denial? and !result
raise Authorizable::Error::NotAuthorized.new(
action: action,
subject: params[:controller]
)
end
result
end | ruby | def is_authorized_for_action?
action = params[:action].to_sym
self.class.authorizable_config ||= DefaultConfig.config
if !self.class.authorizable_config[action]
action = Authorizable::Controller.alias_action(action)
end
# retrieve the settings for this particular controller action
settings_for_action = self.class.authorizable_config[action]
# continue with evaluation
result = is_authorized_for_action_with_config?(action, settings_for_action)
# if we are configured to raise exception instead of handle the error
# ourselves, raise the exception!
if Authorizable.configuration.raise_exception_on_denial? and !result
raise Authorizable::Error::NotAuthorized.new(
action: action,
subject: params[:controller]
)
end
result
end | [
"def",
"is_authorized_for_action?",
"action",
"=",
"params",
"[",
":action",
"]",
".",
"to_sym",
"self",
".",
"class",
".",
"authorizable_config",
"||=",
"DefaultConfig",
".",
"config",
"if",
"!",
"self",
".",
"class",
".",
"authorizable_config",
"[",
"action",
"]",
"action",
"=",
"Authorizable",
"::",
"Controller",
".",
"alias_action",
"(",
"action",
")",
"end",
"settings_for_action",
"=",
"self",
".",
"class",
".",
"authorizable_config",
"[",
"action",
"]",
"result",
"=",
"is_authorized_for_action_with_config?",
"(",
"action",
",",
"settings_for_action",
")",
"if",
"Authorizable",
".",
"configuration",
".",
"raise_exception_on_denial?",
"and",
"!",
"result",
"raise",
"Authorizable",
"::",
"Error",
"::",
"NotAuthorized",
".",
"new",
"(",
"action",
":",
"action",
",",
"subject",
":",
"params",
"[",
":controller",
"]",
")",
"end",
"result",
"end"
] | check if the resource can perform the action
@raise [Authorizable::Error::NotAuthorized] if configured to raise
exception instead of handle the errors
@return [Boolean] the result of the permission evaluation
will halt controller flow | [
"check",
"if",
"the",
"resource",
"can",
"perform",
"the",
"action"
] | 6a4ef94848861bb79b0ab1454264366aed4e2db8 | https://github.com/NullVoxPopuli/authorizable/blob/6a4ef94848861bb79b0ab1454264366aed4e2db8/lib/authorizable/controller.rb#L22-L46 | train |
NullVoxPopuli/authorizable | lib/authorizable/controller.rb | Authorizable.Controller.is_authorized_for_action_with_config? | def is_authorized_for_action_with_config?(action, config)
request_may_proceed = false
return true unless config.present?
defaults = {
user: current_user,
permission: action.to_s,
message: I18n.t('authorizable.not_authorized'),
flash_type: Authorizable.configuration.flash_error
}
options = defaults.merge(config)
# run permission
request_may_proceed = evaluate_action_permission(options)
# redirect
unless request_may_proceed and request.format == :html
authorizable_respond_with(
options[:flash_type],
options[:message],
options[:redirect_path]
)
# halt
return false
end
# proceed with request execution
true
end | ruby | def is_authorized_for_action_with_config?(action, config)
request_may_proceed = false
return true unless config.present?
defaults = {
user: current_user,
permission: action.to_s,
message: I18n.t('authorizable.not_authorized'),
flash_type: Authorizable.configuration.flash_error
}
options = defaults.merge(config)
# run permission
request_may_proceed = evaluate_action_permission(options)
# redirect
unless request_may_proceed and request.format == :html
authorizable_respond_with(
options[:flash_type],
options[:message],
options[:redirect_path]
)
# halt
return false
end
# proceed with request execution
true
end | [
"def",
"is_authorized_for_action_with_config?",
"(",
"action",
",",
"config",
")",
"request_may_proceed",
"=",
"false",
"return",
"true",
"unless",
"config",
".",
"present?",
"defaults",
"=",
"{",
"user",
":",
"current_user",
",",
"permission",
":",
"action",
".",
"to_s",
",",
"message",
":",
"I18n",
".",
"t",
"(",
"'authorizable.not_authorized'",
")",
",",
"flash_type",
":",
"Authorizable",
".",
"configuration",
".",
"flash_error",
"}",
"options",
"=",
"defaults",
".",
"merge",
"(",
"config",
")",
"request_may_proceed",
"=",
"evaluate_action_permission",
"(",
"options",
")",
"unless",
"request_may_proceed",
"and",
"request",
".",
"format",
"==",
":html",
"authorizable_respond_with",
"(",
"options",
"[",
":flash_type",
"]",
",",
"options",
"[",
":message",
"]",
",",
"options",
"[",
":redirect_path",
"]",
")",
"return",
"false",
"end",
"true",
"end"
] | check if the resource can perform the action and respond
according to the specefied config
@param [Symbol] action the current controller action
@param [Hash] config the configuration for what to do with the given action
@return [Boolean] the result of the permission evaluation | [
"check",
"if",
"the",
"resource",
"can",
"perform",
"the",
"action",
"and",
"respond",
"according",
"to",
"the",
"specefied",
"config"
] | 6a4ef94848861bb79b0ab1454264366aed4e2db8 | https://github.com/NullVoxPopuli/authorizable/blob/6a4ef94848861bb79b0ab1454264366aed4e2db8/lib/authorizable/controller.rb#L54-L84 | train |
NullVoxPopuli/authorizable | lib/authorizable/controller.rb | Authorizable.Controller.evaluate_action_permission | def evaluate_action_permission(options)
# the target is the @resource
# (@event, @user, @page, whatever)
# it must exist in order to perform a permission check
# involving the object
if options[:target]
object = instance_variable_get("@#{options[:target]}")
return options[:user].can?(options[:permission], object)
else
return options[:user].can?(options[:permission])
end
end | ruby | def evaluate_action_permission(options)
# the target is the @resource
# (@event, @user, @page, whatever)
# it must exist in order to perform a permission check
# involving the object
if options[:target]
object = instance_variable_get("@#{options[:target]}")
return options[:user].can?(options[:permission], object)
else
return options[:user].can?(options[:permission])
end
end | [
"def",
"evaluate_action_permission",
"(",
"options",
")",
"if",
"options",
"[",
":target",
"]",
"object",
"=",
"instance_variable_get",
"(",
"\"@#{options[:target]}\"",
")",
"return",
"options",
"[",
":user",
"]",
".",
"can?",
"(",
"options",
"[",
":permission",
"]",
",",
"object",
")",
"else",
"return",
"options",
"[",
":user",
"]",
".",
"can?",
"(",
"options",
"[",
":permission",
"]",
")",
"end",
"end"
] | run the permission
@param [Hash] options the data for the permission
@return [Boolean] the result of the permission | [
"run",
"the",
"permission"
] | 6a4ef94848861bb79b0ab1454264366aed4e2db8 | https://github.com/NullVoxPopuli/authorizable/blob/6a4ef94848861bb79b0ab1454264366aed4e2db8/lib/authorizable/controller.rb#L90-L101 | train |
khiemns54/takenoko | lib/takenoko/attach_helper.rb | Takenoko.AttachHelper.get_drive_files_list | def get_drive_files_list(folder)
ls = Hash.new
page_token = nil
begin
(files, page_token) = folder.files("pageToken" => page_token)
files.each do |f|
ls[f.original_filename] = f
end
end while page_token
return ls
end | ruby | def get_drive_files_list(folder)
ls = Hash.new
page_token = nil
begin
(files, page_token) = folder.files("pageToken" => page_token)
files.each do |f|
ls[f.original_filename] = f
end
end while page_token
return ls
end | [
"def",
"get_drive_files_list",
"(",
"folder",
")",
"ls",
"=",
"Hash",
".",
"new",
"page_token",
"=",
"nil",
"begin",
"(",
"files",
",",
"page_token",
")",
"=",
"folder",
".",
"files",
"(",
"\"pageToken\"",
"=>",
"page_token",
")",
"files",
".",
"each",
"do",
"|",
"f",
"|",
"ls",
"[",
"f",
".",
"original_filename",
"]",
"=",
"f",
"end",
"end",
"while",
"page_token",
"return",
"ls",
"end"
] | Get all file from drive folder | [
"Get",
"all",
"file",
"from",
"drive",
"folder"
] | 5105f32fcf6b39c0e63e61935d372851de665b54 | https://github.com/khiemns54/takenoko/blob/5105f32fcf6b39c0e63e61935d372851de665b54/lib/takenoko/attach_helper.rb#L53-L63 | train |
jeanlescure/hipster_sql_to_hbase | lib/result_tree_to_hbase_converter.rb | HipsterSqlToHbase.ResultTreeToHbaseConverter.insert_sentence | def insert_sentence(hash)
thrift_method = "mutateRow"
thrift_table = hash[:into]
thrift_calls = []
hash[:values].each do |value_set|
thrift_row = SecureRandom.uuid
thrift_mutations = []
i = 0
hash[:columns].each do |col|
thrift_mutations << HBase::Mutation.new(column: col, value: value_set[i].to_s)
i += 1
end
thrift_calls << {:method => thrift_method,:arguments => [thrift_table,thrift_row,thrift_mutations,{}]}
end
HipsterSqlToHbase::ThriftCallGroup.new(thrift_calls,true)
end | ruby | def insert_sentence(hash)
thrift_method = "mutateRow"
thrift_table = hash[:into]
thrift_calls = []
hash[:values].each do |value_set|
thrift_row = SecureRandom.uuid
thrift_mutations = []
i = 0
hash[:columns].each do |col|
thrift_mutations << HBase::Mutation.new(column: col, value: value_set[i].to_s)
i += 1
end
thrift_calls << {:method => thrift_method,:arguments => [thrift_table,thrift_row,thrift_mutations,{}]}
end
HipsterSqlToHbase::ThriftCallGroup.new(thrift_calls,true)
end | [
"def",
"insert_sentence",
"(",
"hash",
")",
"thrift_method",
"=",
"\"mutateRow\"",
"thrift_table",
"=",
"hash",
"[",
":into",
"]",
"thrift_calls",
"=",
"[",
"]",
"hash",
"[",
":values",
"]",
".",
"each",
"do",
"|",
"value_set",
"|",
"thrift_row",
"=",
"SecureRandom",
".",
"uuid",
"thrift_mutations",
"=",
"[",
"]",
"i",
"=",
"0",
"hash",
"[",
":columns",
"]",
".",
"each",
"do",
"|",
"col",
"|",
"thrift_mutations",
"<<",
"HBase",
"::",
"Mutation",
".",
"new",
"(",
"column",
":",
"col",
",",
"value",
":",
"value_set",
"[",
"i",
"]",
".",
"to_s",
")",
"i",
"+=",
"1",
"end",
"thrift_calls",
"<<",
"{",
":method",
"=>",
"thrift_method",
",",
":arguments",
"=>",
"[",
"thrift_table",
",",
"thrift_row",
",",
"thrift_mutations",
",",
"{",
"}",
"]",
"}",
"end",
"HipsterSqlToHbase",
"::",
"ThriftCallGroup",
".",
"new",
"(",
"thrift_calls",
",",
"true",
")",
"end"
] | When SQL sentence is an INSERT query generate the Thrift mutations according
to the specified query values. | [
"When",
"SQL",
"sentence",
"is",
"an",
"INSERT",
"query",
"generate",
"the",
"Thrift",
"mutations",
"according",
"to",
"the",
"specified",
"query",
"values",
"."
] | eb181f2f869606a8fd68e88bde0a485051f262b8 | https://github.com/jeanlescure/hipster_sql_to_hbase/blob/eb181f2f869606a8fd68e88bde0a485051f262b8/lib/result_tree_to_hbase_converter.rb#L35-L50 | train |
jeanlescure/hipster_sql_to_hbase | lib/result_tree_to_hbase_converter.rb | HipsterSqlToHbase.ResultTreeToHbaseConverter.select_sentence | def select_sentence(hash)
thrift_method = "getRowsByScanner"
thrift_table = hash[:from]
thrift_columns = hash[:select]
thrift_filters = recurse_where(hash[:where] || [])
thrift_limit = hash[:limit]
HipsterSqlToHbase::ThriftCallGroup.new([{:method => thrift_method,:arguments => [thrift_table,thrift_columns,thrift_filters,thrift_limit,{}]}])
end | ruby | def select_sentence(hash)
thrift_method = "getRowsByScanner"
thrift_table = hash[:from]
thrift_columns = hash[:select]
thrift_filters = recurse_where(hash[:where] || [])
thrift_limit = hash[:limit]
HipsterSqlToHbase::ThriftCallGroup.new([{:method => thrift_method,:arguments => [thrift_table,thrift_columns,thrift_filters,thrift_limit,{}]}])
end | [
"def",
"select_sentence",
"(",
"hash",
")",
"thrift_method",
"=",
"\"getRowsByScanner\"",
"thrift_table",
"=",
"hash",
"[",
":from",
"]",
"thrift_columns",
"=",
"hash",
"[",
":select",
"]",
"thrift_filters",
"=",
"recurse_where",
"(",
"hash",
"[",
":where",
"]",
"||",
"[",
"]",
")",
"thrift_limit",
"=",
"hash",
"[",
":limit",
"]",
"HipsterSqlToHbase",
"::",
"ThriftCallGroup",
".",
"new",
"(",
"[",
"{",
":method",
"=>",
"thrift_method",
",",
":arguments",
"=>",
"[",
"thrift_table",
",",
"thrift_columns",
",",
"thrift_filters",
",",
"thrift_limit",
",",
"{",
"}",
"]",
"}",
"]",
")",
"end"
] | When SQL sentence is a SELECT query generate the Thrift filters according
to the specified query values. | [
"When",
"SQL",
"sentence",
"is",
"a",
"SELECT",
"query",
"generate",
"the",
"Thrift",
"filters",
"according",
"to",
"the",
"specified",
"query",
"values",
"."
] | eb181f2f869606a8fd68e88bde0a485051f262b8 | https://github.com/jeanlescure/hipster_sql_to_hbase/blob/eb181f2f869606a8fd68e88bde0a485051f262b8/lib/result_tree_to_hbase_converter.rb#L54-L62 | train |
jeanlescure/hipster_sql_to_hbase | lib/result_tree_to_hbase_converter.rb | HipsterSqlToHbase.ResultTreeToHbaseConverter.filters_from_key_value_pair | def filters_from_key_value_pair(kvp)
kvp[:qualifier] = kvp[:column].split(':')
kvp[:column] = kvp[:qualifier].shift
if (kvp[:condition].to_s != "LIKE")
"(SingleColumnValueFilter('#{kvp[:column]}','#{kvp[:qualifier].join(':')}',#{kvp[:condition]},'binary:#{kvp[:value]}',true,true))"
else
kvp[:value] = Regexp.escape(kvp[:value])
kvp[:value].sub!(/^%/,"^.*")
kvp[:value].sub!(/%$/,".*$")
while kvp[:value].match(/([^\\]{1,1})%/)
kvp[:value].sub!(/([^\\]{1,1})%/,"#{$1}.*?")
end
kvp[:value].sub!(/^_/,"^.")
kvp[:value].sub!(/_$/,".$")
while kvp[:value].match(/([^\\]{1,1})_/)
kvp[:value].sub!(/([^\\]{1,1})_/,"#{$1}.")
end
"(SingleColumnValueFilter('#{kvp[:column]}','#{kvp[:qualifier].join(':')}',=,'regexstring:#{kvp[:value]}',true,true))"
end
end | ruby | def filters_from_key_value_pair(kvp)
kvp[:qualifier] = kvp[:column].split(':')
kvp[:column] = kvp[:qualifier].shift
if (kvp[:condition].to_s != "LIKE")
"(SingleColumnValueFilter('#{kvp[:column]}','#{kvp[:qualifier].join(':')}',#{kvp[:condition]},'binary:#{kvp[:value]}',true,true))"
else
kvp[:value] = Regexp.escape(kvp[:value])
kvp[:value].sub!(/^%/,"^.*")
kvp[:value].sub!(/%$/,".*$")
while kvp[:value].match(/([^\\]{1,1})%/)
kvp[:value].sub!(/([^\\]{1,1})%/,"#{$1}.*?")
end
kvp[:value].sub!(/^_/,"^.")
kvp[:value].sub!(/_$/,".$")
while kvp[:value].match(/([^\\]{1,1})_/)
kvp[:value].sub!(/([^\\]{1,1})_/,"#{$1}.")
end
"(SingleColumnValueFilter('#{kvp[:column]}','#{kvp[:qualifier].join(':')}',=,'regexstring:#{kvp[:value]}',true,true))"
end
end | [
"def",
"filters_from_key_value_pair",
"(",
"kvp",
")",
"kvp",
"[",
":qualifier",
"]",
"=",
"kvp",
"[",
":column",
"]",
".",
"split",
"(",
"':'",
")",
"kvp",
"[",
":column",
"]",
"=",
"kvp",
"[",
":qualifier",
"]",
".",
"shift",
"if",
"(",
"kvp",
"[",
":condition",
"]",
".",
"to_s",
"!=",
"\"LIKE\"",
")",
"\"(SingleColumnValueFilter('#{kvp[:column]}','#{kvp[:qualifier].join(':')}',#{kvp[:condition]},'binary:#{kvp[:value]}',true,true))\"",
"else",
"kvp",
"[",
":value",
"]",
"=",
"Regexp",
".",
"escape",
"(",
"kvp",
"[",
":value",
"]",
")",
"kvp",
"[",
":value",
"]",
".",
"sub!",
"(",
"/",
"/",
",",
"\"^.*\"",
")",
"kvp",
"[",
":value",
"]",
".",
"sub!",
"(",
"/",
"/",
",",
"\".*$\"",
")",
"while",
"kvp",
"[",
":value",
"]",
".",
"match",
"(",
"/",
"\\\\",
"/",
")",
"kvp",
"[",
":value",
"]",
".",
"sub!",
"(",
"/",
"\\\\",
"/",
",",
"\"#{$1}.*?\"",
")",
"end",
"kvp",
"[",
":value",
"]",
".",
"sub!",
"(",
"/",
"/",
",",
"\"^.\"",
")",
"kvp",
"[",
":value",
"]",
".",
"sub!",
"(",
"/",
"/",
",",
"\".$\"",
")",
"while",
"kvp",
"[",
":value",
"]",
".",
"match",
"(",
"/",
"\\\\",
"/",
")",
"kvp",
"[",
":value",
"]",
".",
"sub!",
"(",
"/",
"\\\\",
"/",
",",
"\"#{$1}.\"",
")",
"end",
"\"(SingleColumnValueFilter('#{kvp[:column]}','#{kvp[:qualifier].join(':')}',=,'regexstring:#{kvp[:value]}',true,true))\"",
"end",
"end"
] | Generate a Thrift QualifierFilter and ValueFilter from key value pair. | [
"Generate",
"a",
"Thrift",
"QualifierFilter",
"and",
"ValueFilter",
"from",
"key",
"value",
"pair",
"."
] | eb181f2f869606a8fd68e88bde0a485051f262b8 | https://github.com/jeanlescure/hipster_sql_to_hbase/blob/eb181f2f869606a8fd68e88bde0a485051f262b8/lib/result_tree_to_hbase_converter.rb#L100-L119 | train |
JamitLabs/TMSync | lib/tmsync.rb | Tmsync.FileSearch.find_all_grouped_by_language | def find_all_grouped_by_language
all_files = Dir.glob(File.join(@base_path, '**/*'))
# apply exclude regex
found_files = all_files.select { |file_path|
file_path !~ @exclude_regex && !File.directory?(file_path)
}
# exclude empty files
found_files = found_files.select { |file_path|
content = File.open(file_path, 'r') { |f| f.read }
!content.to_s.scrub("<?>").strip.empty?
}
# apply matching regex
found_files = found_files.select { |file_path|
file_path =~ @matching_regex
}.map { |file_path|
[file_path.match(@matching_regex).captures.last, file_path]
}
result = found_files.group_by(&:first).map { |k,v| [k, v.each(&:shift).flatten] }.to_h
# replace nil key with fallback language
if !(nil_values = result[nil]).nil?
result[Tmsync::Constants::FALLBACK_LANGUAGE] = nil_values
result.delete(nil)
end
result
end | ruby | def find_all_grouped_by_language
all_files = Dir.glob(File.join(@base_path, '**/*'))
# apply exclude regex
found_files = all_files.select { |file_path|
file_path !~ @exclude_regex && !File.directory?(file_path)
}
# exclude empty files
found_files = found_files.select { |file_path|
content = File.open(file_path, 'r') { |f| f.read }
!content.to_s.scrub("<?>").strip.empty?
}
# apply matching regex
found_files = found_files.select { |file_path|
file_path =~ @matching_regex
}.map { |file_path|
[file_path.match(@matching_regex).captures.last, file_path]
}
result = found_files.group_by(&:first).map { |k,v| [k, v.each(&:shift).flatten] }.to_h
# replace nil key with fallback language
if !(nil_values = result[nil]).nil?
result[Tmsync::Constants::FALLBACK_LANGUAGE] = nil_values
result.delete(nil)
end
result
end | [
"def",
"find_all_grouped_by_language",
"all_files",
"=",
"Dir",
".",
"glob",
"(",
"File",
".",
"join",
"(",
"@base_path",
",",
"'**/*'",
")",
")",
"found_files",
"=",
"all_files",
".",
"select",
"{",
"|",
"file_path",
"|",
"file_path",
"!~",
"@exclude_regex",
"&&",
"!",
"File",
".",
"directory?",
"(",
"file_path",
")",
"}",
"found_files",
"=",
"found_files",
".",
"select",
"{",
"|",
"file_path",
"|",
"content",
"=",
"File",
".",
"open",
"(",
"file_path",
",",
"'r'",
")",
"{",
"|",
"f",
"|",
"f",
".",
"read",
"}",
"!",
"content",
".",
"to_s",
".",
"scrub",
"(",
"\"<?>\"",
")",
".",
"strip",
".",
"empty?",
"}",
"found_files",
"=",
"found_files",
".",
"select",
"{",
"|",
"file_path",
"|",
"file_path",
"=~",
"@matching_regex",
"}",
".",
"map",
"{",
"|",
"file_path",
"|",
"[",
"file_path",
".",
"match",
"(",
"@matching_regex",
")",
".",
"captures",
".",
"last",
",",
"file_path",
"]",
"}",
"result",
"=",
"found_files",
".",
"group_by",
"(",
"&",
":first",
")",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"[",
"k",
",",
"v",
".",
"each",
"(",
"&",
":shift",
")",
".",
"flatten",
"]",
"}",
".",
"to_h",
"if",
"!",
"(",
"nil_values",
"=",
"result",
"[",
"nil",
"]",
")",
".",
"nil?",
"result",
"[",
"Tmsync",
"::",
"Constants",
"::",
"FALLBACK_LANGUAGE",
"]",
"=",
"nil_values",
"result",
".",
"delete",
"(",
"nil",
")",
"end",
"result",
"end"
] | Initializes a file search object.
@param [String] base_path the path of the directory to search within
@param [String] matching_regex a regex that all localizable files match, optionally including a catch group for the language
@param [String] exclude_regex a regex to exclude some matches from matching_regex
Finds all files with corresponding language within a given directory
matching the specified regexes.
@return [Hash] a hash containing language codes as keys and all found files paths as values (so values are of type Array) | [
"Initializes",
"a",
"file",
"search",
"object",
"."
] | 4c57bfc0dcb705b56bb267b220dcadd90d3a61b4 | https://github.com/JamitLabs/TMSync/blob/4c57bfc0dcb705b56bb267b220dcadd90d3a61b4/lib/tmsync.rb#L29-L59 | train |
DomainTools/api-ruby | lib/domain_tools/request.rb | DomainTools.Request.build_url | def build_url
parts = []
uri = ""
parts << "/#{@version}" if @version
parts << "/#{@domain}" if @domain
parts << "/#{@service}" if @service
uri = parts.join("")
parts << "?"
parts << "format=#{@format}"
parts << "&#{authentication_params(uri)}"
parts << "#{format_parameters}" if @parameters
@url = parts.join("")
end | ruby | def build_url
parts = []
uri = ""
parts << "/#{@version}" if @version
parts << "/#{@domain}" if @domain
parts << "/#{@service}" if @service
uri = parts.join("")
parts << "?"
parts << "format=#{@format}"
parts << "&#{authentication_params(uri)}"
parts << "#{format_parameters}" if @parameters
@url = parts.join("")
end | [
"def",
"build_url",
"parts",
"=",
"[",
"]",
"uri",
"=",
"\"\"",
"parts",
"<<",
"\"/#{@version}\"",
"if",
"@version",
"parts",
"<<",
"\"/#{@domain}\"",
"if",
"@domain",
"parts",
"<<",
"\"/#{@service}\"",
"if",
"@service",
"uri",
"=",
"parts",
".",
"join",
"(",
"\"\"",
")",
"parts",
"<<",
"\"?\"",
"parts",
"<<",
"\"format=#{@format}\"",
"parts",
"<<",
"\"&#{authentication_params(uri)}\"",
"parts",
"<<",
"\"#{format_parameters}\"",
"if",
"@parameters",
"@url",
"=",
"parts",
".",
"join",
"(",
"\"\"",
")",
"end"
] | build service url | [
"build",
"service",
"url"
] | 8348b691e386feea824b3ae7fff93a872e5763ec | https://github.com/DomainTools/api-ruby/blob/8348b691e386feea824b3ae7fff93a872e5763ec/lib/domain_tools/request.rb#L31-L43 | train |
DomainTools/api-ruby | lib/domain_tools/request.rb | DomainTools.Request.execute | def execute(refresh=false)
return @response if @response && !refresh
validate
build_url
@done = true
DomainTools.counter!
require 'net/http'
begin
Net::HTTP.start(@host) do |http|
req = Net::HTTP::Get.new(@url)
@http = http.request(req)
@success = validate_http_status
return finalize
end
rescue DomainTools::ServiceException => e
@error = DomainTools::Error.new(self,e)
raise e.class.new(e)
end
end | ruby | def execute(refresh=false)
return @response if @response && !refresh
validate
build_url
@done = true
DomainTools.counter!
require 'net/http'
begin
Net::HTTP.start(@host) do |http|
req = Net::HTTP::Get.new(@url)
@http = http.request(req)
@success = validate_http_status
return finalize
end
rescue DomainTools::ServiceException => e
@error = DomainTools::Error.new(self,e)
raise e.class.new(e)
end
end | [
"def",
"execute",
"(",
"refresh",
"=",
"false",
")",
"return",
"@response",
"if",
"@response",
"&&",
"!",
"refresh",
"validate",
"build_url",
"@done",
"=",
"true",
"DomainTools",
".",
"counter!",
"require",
"'net/http'",
"begin",
"Net",
"::",
"HTTP",
".",
"start",
"(",
"@host",
")",
"do",
"|",
"http",
"|",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"@url",
")",
"@http",
"=",
"http",
".",
"request",
"(",
"req",
")",
"@success",
"=",
"validate_http_status",
"return",
"finalize",
"end",
"rescue",
"DomainTools",
"::",
"ServiceException",
"=>",
"e",
"@error",
"=",
"DomainTools",
"::",
"Error",
".",
"new",
"(",
"self",
",",
"e",
")",
"raise",
"e",
".",
"class",
".",
"new",
"(",
"e",
")",
"end",
"end"
] | Connect to the server and execute the request | [
"Connect",
"to",
"the",
"server",
"and",
"execute",
"the",
"request"
] | 8348b691e386feea824b3ae7fff93a872e5763ec | https://github.com/DomainTools/api-ruby/blob/8348b691e386feea824b3ae7fff93a872e5763ec/lib/domain_tools/request.rb#L78-L96 | train |
palon7/zaif-ruby | lib/zaif.rb | Zaif.API.trade | def trade(currency_code, price, amount, action, limit = nil, counter_currency_code = "jpy")
currency_pair = currency_code + "_" + counter_currency_code
params = {:currency_pair => currency_pair, :action => action, :price => price, :amount => amount}
params.store(:limit, limit) if limit
json = post_ssl(@zaif_trade_url, "trade", params)
return json
end | ruby | def trade(currency_code, price, amount, action, limit = nil, counter_currency_code = "jpy")
currency_pair = currency_code + "_" + counter_currency_code
params = {:currency_pair => currency_pair, :action => action, :price => price, :amount => amount}
params.store(:limit, limit) if limit
json = post_ssl(@zaif_trade_url, "trade", params)
return json
end | [
"def",
"trade",
"(",
"currency_code",
",",
"price",
",",
"amount",
",",
"action",
",",
"limit",
"=",
"nil",
",",
"counter_currency_code",
"=",
"\"jpy\"",
")",
"currency_pair",
"=",
"currency_code",
"+",
"\"_\"",
"+",
"counter_currency_code",
"params",
"=",
"{",
":currency_pair",
"=>",
"currency_pair",
",",
":action",
"=>",
"action",
",",
":price",
"=>",
"price",
",",
":amount",
"=>",
"amount",
"}",
"params",
".",
"store",
"(",
":limit",
",",
"limit",
")",
"if",
"limit",
"json",
"=",
"post_ssl",
"(",
"@zaif_trade_url",
",",
"\"trade\"",
",",
"params",
")",
"return",
"json",
"end"
] | Issue trade.
Need api key. | [
"Issue",
"trade",
".",
"Need",
"api",
"key",
"."
] | c0c5d2e4ba86262d48d8ecccea51f0cb5e1df6d6 | https://github.com/palon7/zaif-ruby/blob/c0c5d2e4ba86262d48d8ecccea51f0cb5e1df6d6/lib/zaif.rb#L105-L111 | train |
palon7/zaif-ruby | lib/zaif.rb | Zaif.API.bid | def bid(currency_code, price, amount, limit = nil, counter_currency_code = "jpy")
return trade(currency_code, price, amount, "bid", limit, counter_currency_code)
end | ruby | def bid(currency_code, price, amount, limit = nil, counter_currency_code = "jpy")
return trade(currency_code, price, amount, "bid", limit, counter_currency_code)
end | [
"def",
"bid",
"(",
"currency_code",
",",
"price",
",",
"amount",
",",
"limit",
"=",
"nil",
",",
"counter_currency_code",
"=",
"\"jpy\"",
")",
"return",
"trade",
"(",
"currency_code",
",",
"price",
",",
"amount",
",",
"\"bid\"",
",",
"limit",
",",
"counter_currency_code",
")",
"end"
] | Issue bid order.
Need api key. | [
"Issue",
"bid",
"order",
".",
"Need",
"api",
"key",
"."
] | c0c5d2e4ba86262d48d8ecccea51f0cb5e1df6d6 | https://github.com/palon7/zaif-ruby/blob/c0c5d2e4ba86262d48d8ecccea51f0cb5e1df6d6/lib/zaif.rb#L115-L117 | train |
palon7/zaif-ruby | lib/zaif.rb | Zaif.API.ask | def ask(currency_code, price, amount, limit = nil, counter_currency_code = "jpy")
return trade(currency_code, price, amount, "ask", limit, counter_currency_code)
end | ruby | def ask(currency_code, price, amount, limit = nil, counter_currency_code = "jpy")
return trade(currency_code, price, amount, "ask", limit, counter_currency_code)
end | [
"def",
"ask",
"(",
"currency_code",
",",
"price",
",",
"amount",
",",
"limit",
"=",
"nil",
",",
"counter_currency_code",
"=",
"\"jpy\"",
")",
"return",
"trade",
"(",
"currency_code",
",",
"price",
",",
"amount",
",",
"\"ask\"",
",",
"limit",
",",
"counter_currency_code",
")",
"end"
] | Issue ask order.
Need api key. | [
"Issue",
"ask",
"order",
".",
"Need",
"api",
"key",
"."
] | c0c5d2e4ba86262d48d8ecccea51f0cb5e1df6d6 | https://github.com/palon7/zaif-ruby/blob/c0c5d2e4ba86262d48d8ecccea51f0cb5e1df6d6/lib/zaif.rb#L121-L123 | train |
palon7/zaif-ruby | lib/zaif.rb | Zaif.API.withdraw | def withdraw(currency_code, address, amount, option = {})
option["currency"] = currency_code
option["address"] = address
option["amount"] = amount
json = post_ssl(@zaif_trade_url, "withdraw", option)
return json
end | ruby | def withdraw(currency_code, address, amount, option = {})
option["currency"] = currency_code
option["address"] = address
option["amount"] = amount
json = post_ssl(@zaif_trade_url, "withdraw", option)
return json
end | [
"def",
"withdraw",
"(",
"currency_code",
",",
"address",
",",
"amount",
",",
"option",
"=",
"{",
"}",
")",
"option",
"[",
"\"currency\"",
"]",
"=",
"currency_code",
"option",
"[",
"\"address\"",
"]",
"=",
"address",
"option",
"[",
"\"amount\"",
"]",
"=",
"amount",
"json",
"=",
"post_ssl",
"(",
"@zaif_trade_url",
",",
"\"withdraw\"",
",",
"option",
")",
"return",
"json",
"end"
] | Withdraw funds.
Need api key. | [
"Withdraw",
"funds",
".",
"Need",
"api",
"key",
"."
] | c0c5d2e4ba86262d48d8ecccea51f0cb5e1df6d6 | https://github.com/palon7/zaif-ruby/blob/c0c5d2e4ba86262d48d8ecccea51f0cb5e1df6d6/lib/zaif.rb#L134-L140 | train |
droptheplot/adminable | lib/adminable/field_collector.rb | Adminable.FieldCollector.associations | def associations
@associations ||= [].tap do |fields|
@model.reflect_on_all_associations.each do |association|
fields << resolve(association.macro, association.name)
end
end
end | ruby | def associations
@associations ||= [].tap do |fields|
@model.reflect_on_all_associations.each do |association|
fields << resolve(association.macro, association.name)
end
end
end | [
"def",
"associations",
"@associations",
"||=",
"[",
"]",
".",
"tap",
"do",
"|",
"fields",
"|",
"@model",
".",
"reflect_on_all_associations",
".",
"each",
"do",
"|",
"association",
"|",
"fields",
"<<",
"resolve",
"(",
"association",
".",
"macro",
",",
"association",
".",
"name",
")",
"end",
"end",
"end"
] | Collects fields from model associations
@return [Array] | [
"Collects",
"fields",
"from",
"model",
"associations"
] | ec5808e161a9d27f0150186e79c750242bdf7c6b | https://github.com/droptheplot/adminable/blob/ec5808e161a9d27f0150186e79c750242bdf7c6b/lib/adminable/field_collector.rb#L30-L36 | train |
mssola/cconfig | lib/cconfig/hash_utils.rb | CConfig.HashUtils.strict_merge_with_env | def strict_merge_with_env(default:, local:, prefix:)
hsh = {}
default.each do |k, v|
# The corresponding environment variable. If it's not the final value,
# then this just contains the partial prefix of the env. variable.
env = "#{prefix}_#{k}"
# If the current value is a hash, then go deeper to perform a deep
# merge, otherwise we merge the final value by respecting the order as
# specified in the documentation.
if v.is_a?(Hash)
l = local[k] || {}
hsh[k] = strict_merge_with_env(default: default[k], local: l, prefix: env)
else
hsh[k] = first_non_nil(get_env(env), local[k], v)
end
end
hsh
end | ruby | def strict_merge_with_env(default:, local:, prefix:)
hsh = {}
default.each do |k, v|
# The corresponding environment variable. If it's not the final value,
# then this just contains the partial prefix of the env. variable.
env = "#{prefix}_#{k}"
# If the current value is a hash, then go deeper to perform a deep
# merge, otherwise we merge the final value by respecting the order as
# specified in the documentation.
if v.is_a?(Hash)
l = local[k] || {}
hsh[k] = strict_merge_with_env(default: default[k], local: l, prefix: env)
else
hsh[k] = first_non_nil(get_env(env), local[k], v)
end
end
hsh
end | [
"def",
"strict_merge_with_env",
"(",
"default",
":",
",",
"local",
":",
",",
"prefix",
":",
")",
"hsh",
"=",
"{",
"}",
"default",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"env",
"=",
"\"#{prefix}_#{k}\"",
"if",
"v",
".",
"is_a?",
"(",
"Hash",
")",
"l",
"=",
"local",
"[",
"k",
"]",
"||",
"{",
"}",
"hsh",
"[",
"k",
"]",
"=",
"strict_merge_with_env",
"(",
"default",
":",
"default",
"[",
"k",
"]",
",",
"local",
":",
"l",
",",
"prefix",
":",
"env",
")",
"else",
"hsh",
"[",
"k",
"]",
"=",
"first_non_nil",
"(",
"get_env",
"(",
"env",
")",
",",
"local",
"[",
"k",
"]",
",",
"v",
")",
"end",
"end",
"hsh",
"end"
] | Applies a deep merge while respecting the values from environment
variables. A deep merge consists of a merge of all the nested elements of
the two given hashes `config` and `local`. The `config` hash is supposed
to contain all the accepted keys, and the `local` hash is a subset of it.
Moreover, let's say that we have the following hash: { "ldap" => {
"enabled" => true } }. An environment variable that can modify the value
of the previous hash has to be named `#{prefix}_LDAP_ENABLED`. The `prefix`
argument specifies how all the environment variables have to start.
Returns the merged hash, where the precedence of the merge is as follows:
1. The value of the related environment variable if set.
2. The value from the `local` hash.
3. The value from the `config` hash. | [
"Applies",
"a",
"deep",
"merge",
"while",
"respecting",
"the",
"values",
"from",
"environment",
"variables",
".",
"A",
"deep",
"merge",
"consists",
"of",
"a",
"merge",
"of",
"all",
"the",
"nested",
"elements",
"of",
"the",
"two",
"given",
"hashes",
"config",
"and",
"local",
".",
"The",
"config",
"hash",
"is",
"supposed",
"to",
"contain",
"all",
"the",
"accepted",
"keys",
"and",
"the",
"local",
"hash",
"is",
"a",
"subset",
"of",
"it",
"."
] | 793fb743cdcc064a96fb911bc17483fa0d343056 | https://github.com/mssola/cconfig/blob/793fb743cdcc064a96fb911bc17483fa0d343056/lib/cconfig/hash_utils.rb#L83-L102 | train |
mssola/cconfig | lib/cconfig/hash_utils.rb | CConfig.HashUtils.get_env | def get_env(key)
env = ENV[key.upcase]
return nil if env.nil?
# Try to convert it into a boolean value.
return true if env.casecmp("true").zero?
return false if env.casecmp("false").zero?
# Try to convert it into an integer. Otherwise just keep the string.
begin
Integer(env)
rescue ArgumentError
env
end
end | ruby | def get_env(key)
env = ENV[key.upcase]
return nil if env.nil?
# Try to convert it into a boolean value.
return true if env.casecmp("true").zero?
return false if env.casecmp("false").zero?
# Try to convert it into an integer. Otherwise just keep the string.
begin
Integer(env)
rescue ArgumentError
env
end
end | [
"def",
"get_env",
"(",
"key",
")",
"env",
"=",
"ENV",
"[",
"key",
".",
"upcase",
"]",
"return",
"nil",
"if",
"env",
".",
"nil?",
"return",
"true",
"if",
"env",
".",
"casecmp",
"(",
"\"true\"",
")",
".",
"zero?",
"return",
"false",
"if",
"env",
".",
"casecmp",
"(",
"\"false\"",
")",
".",
"zero?",
"begin",
"Integer",
"(",
"env",
")",
"rescue",
"ArgumentError",
"env",
"end",
"end"
] | Get the typed value of the specified environment variable. If it doesn't
exist, it will return nil. Otherwise, it will try to cast the fetched
value into the proper type and return it. | [
"Get",
"the",
"typed",
"value",
"of",
"the",
"specified",
"environment",
"variable",
".",
"If",
"it",
"doesn",
"t",
"exist",
"it",
"will",
"return",
"nil",
".",
"Otherwise",
"it",
"will",
"try",
"to",
"cast",
"the",
"fetched",
"value",
"into",
"the",
"proper",
"type",
"and",
"return",
"it",
"."
] | 793fb743cdcc064a96fb911bc17483fa0d343056 | https://github.com/mssola/cconfig/blob/793fb743cdcc064a96fb911bc17483fa0d343056/lib/cconfig/hash_utils.rb#L121-L135 | train |
sgillesp/taxonomite | lib/taxonomite/node.rb | Taxonomite.Node.evaluate | def evaluate(m)
return self.owner.instance_eval(m) if self.owner != nil && self.owner.respond_to?(m)
return self.instance_eval(m) if self.respond_to?(m)
nil
end | ruby | def evaluate(m)
return self.owner.instance_eval(m) if self.owner != nil && self.owner.respond_to?(m)
return self.instance_eval(m) if self.respond_to?(m)
nil
end | [
"def",
"evaluate",
"(",
"m",
")",
"return",
"self",
".",
"owner",
".",
"instance_eval",
"(",
"m",
")",
"if",
"self",
".",
"owner",
"!=",
"nil",
"&&",
"self",
".",
"owner",
".",
"respond_to?",
"(",
"m",
")",
"return",
"self",
".",
"instance_eval",
"(",
"m",
")",
"if",
"self",
".",
"respond_to?",
"(",
"m",
")",
"nil",
"end"
] | this is the associated object
evaluate a method on the owner of this node (if present). If an owner is
not present, then the method is evaluated on this object. In either case
a check is made to ensure that the object will respond_to? the method call.
If the owner exists but does not respond to the method, then the method is
tried on this node object in similar fashion.
!!! SHOULD THIS JUST OVERRIDE instance_eval ??
@param [Method] m method to call
@return [] the result of the method call, or nil if unable to evaluate | [
"this",
"is",
"the",
"associated",
"object"
] | 731b42d0dfa1f52b39d050026f49b2d205407ff8 | https://github.com/sgillesp/taxonomite/blob/731b42d0dfa1f52b39d050026f49b2d205407ff8/lib/taxonomite/node.rb#L45-L49 | train |
sgillesp/taxonomite | lib/taxonomite/node.rb | Taxonomite.Node.validate_parent | def validate_parent(parent)
raise InvalidParent.create(parent, self) unless (!parent.nil? && is_valid_parent?(parent))
parent.validate_child(self)
end | ruby | def validate_parent(parent)
raise InvalidParent.create(parent, self) unless (!parent.nil? && is_valid_parent?(parent))
parent.validate_child(self)
end | [
"def",
"validate_parent",
"(",
"parent",
")",
"raise",
"InvalidParent",
".",
"create",
"(",
"parent",
",",
"self",
")",
"unless",
"(",
"!",
"parent",
".",
"nil?",
"&&",
"is_valid_parent?",
"(",
"parent",
")",
")",
"parent",
".",
"validate_child",
"(",
"self",
")",
"end"
] | determine whether the parent is valid for this object. See description of
validate_child for more detail. This method calls validate_child to perform
the actual validation.
@param [Taxonomite::Node] parent the parent to validate
@return [Boolean] whether validation was successful | [
"determine",
"whether",
"the",
"parent",
"is",
"valid",
"for",
"this",
"object",
".",
"See",
"description",
"of",
"validate_child",
"for",
"more",
"detail",
".",
"This",
"method",
"calls",
"validate_child",
"to",
"perform",
"the",
"actual",
"validation",
"."
] | 731b42d0dfa1f52b39d050026f49b2d205407ff8 | https://github.com/sgillesp/taxonomite/blob/731b42d0dfa1f52b39d050026f49b2d205407ff8/lib/taxonomite/node.rb#L130-L133 | train |
lateral/recommender-gem | lib/lateral_recommender.rb | LateralRecommender.API.match_documents | def match_documents(mind_results, database_results, key = 'id')
return [] unless database_results
mind_results.each_with_object([]) do |result, arr|
next unless (doc = database_results.find { |s| s[key].to_s == result['document_id'].to_s })
arr << doc.attributes.merge(result)
end
end | ruby | def match_documents(mind_results, database_results, key = 'id')
return [] unless database_results
mind_results.each_with_object([]) do |result, arr|
next unless (doc = database_results.find { |s| s[key].to_s == result['document_id'].to_s })
arr << doc.attributes.merge(result)
end
end | [
"def",
"match_documents",
"(",
"mind_results",
",",
"database_results",
",",
"key",
"=",
"'id'",
")",
"return",
"[",
"]",
"unless",
"database_results",
"mind_results",
".",
"each_with_object",
"(",
"[",
"]",
")",
"do",
"|",
"result",
",",
"arr",
"|",
"next",
"unless",
"(",
"doc",
"=",
"database_results",
".",
"find",
"{",
"|",
"s",
"|",
"s",
"[",
"key",
"]",
".",
"to_s",
"==",
"result",
"[",
"'document_id'",
"]",
".",
"to_s",
"}",
")",
"arr",
"<<",
"doc",
".",
"attributes",
".",
"merge",
"(",
"result",
")",
"end",
"end"
] | Takes two result arrays and using the specified key merges the two
@param [Array] mind_results The results from the API
@param [Array] database_results The results from the database
@param [String] key The key of the database_results Hash that should match the mind_results id key
@return [Hash] An array of merged Hashes | [
"Takes",
"two",
"result",
"arrays",
"and",
"using",
"the",
"specified",
"key",
"merges",
"the",
"two"
] | ec9cdeef1d83e489abd9c8e009eacc3062e1273e | https://github.com/lateral/recommender-gem/blob/ec9cdeef1d83e489abd9c8e009eacc3062e1273e/lib/lateral_recommender.rb#L58-L64 | train |
sutajio/auth | lib/auth/helpers.rb | Auth.Helpers.generate_secret | def generate_secret
if defined?(SecureRandom)
SecureRandom.urlsafe_base64(32)
else
Base64.encode64(
Digest::SHA256.digest("#{Time.now}-#{Time.now.usec}-#{$$}-#{rand}")
).gsub('/','-').gsub('+','_').gsub('=','').strip
end
end | ruby | def generate_secret
if defined?(SecureRandom)
SecureRandom.urlsafe_base64(32)
else
Base64.encode64(
Digest::SHA256.digest("#{Time.now}-#{Time.now.usec}-#{$$}-#{rand}")
).gsub('/','-').gsub('+','_').gsub('=','').strip
end
end | [
"def",
"generate_secret",
"if",
"defined?",
"(",
"SecureRandom",
")",
"SecureRandom",
".",
"urlsafe_base64",
"(",
"32",
")",
"else",
"Base64",
".",
"encode64",
"(",
"Digest",
"::",
"SHA256",
".",
"digest",
"(",
"\"#{Time.now}-#{Time.now.usec}-#{$$}-#{rand}\"",
")",
")",
".",
"gsub",
"(",
"'/'",
",",
"'-'",
")",
".",
"gsub",
"(",
"'+'",
",",
"'_'",
")",
".",
"gsub",
"(",
"'='",
",",
"''",
")",
".",
"strip",
"end",
"end"
] | Generate a unique cryptographically secure secret | [
"Generate",
"a",
"unique",
"cryptographically",
"secure",
"secret"
] | b3d1c289a22ba90fa66adb513de9eead70df6e60 | https://github.com/sutajio/auth/blob/b3d1c289a22ba90fa66adb513de9eead70df6e60/lib/auth/helpers.rb#L13-L21 | train |
sutajio/auth | lib/auth/helpers.rb | Auth.Helpers.encrypt_password | def encrypt_password(password, salt, hash)
case hash.to_s
when 'sha256'
Digest::SHA256.hexdigest("#{password}-#{salt}")
else
raise 'Unsupported hash algorithm'
end
end | ruby | def encrypt_password(password, salt, hash)
case hash.to_s
when 'sha256'
Digest::SHA256.hexdigest("#{password}-#{salt}")
else
raise 'Unsupported hash algorithm'
end
end | [
"def",
"encrypt_password",
"(",
"password",
",",
"salt",
",",
"hash",
")",
"case",
"hash",
".",
"to_s",
"when",
"'sha256'",
"Digest",
"::",
"SHA256",
".",
"hexdigest",
"(",
"\"#{password}-#{salt}\"",
")",
"else",
"raise",
"'Unsupported hash algorithm'",
"end",
"end"
] | Obfuscate a password using a salt and a cryptographic hash function | [
"Obfuscate",
"a",
"password",
"using",
"a",
"salt",
"and",
"a",
"cryptographic",
"hash",
"function"
] | b3d1c289a22ba90fa66adb513de9eead70df6e60 | https://github.com/sutajio/auth/blob/b3d1c289a22ba90fa66adb513de9eead70df6e60/lib/auth/helpers.rb#L24-L31 | train |
sutajio/auth | lib/auth/helpers.rb | Auth.Helpers.decode_scopes | def decode_scopes(scopes)
if scopes.is_a?(Array)
scopes.map {|s| s.to_s.strip }
else
scopes.to_s.split(' ').map {|s| s.strip }
end
end | ruby | def decode_scopes(scopes)
if scopes.is_a?(Array)
scopes.map {|s| s.to_s.strip }
else
scopes.to_s.split(' ').map {|s| s.strip }
end
end | [
"def",
"decode_scopes",
"(",
"scopes",
")",
"if",
"scopes",
".",
"is_a?",
"(",
"Array",
")",
"scopes",
".",
"map",
"{",
"|",
"s",
"|",
"s",
".",
"to_s",
".",
"strip",
"}",
"else",
"scopes",
".",
"to_s",
".",
"split",
"(",
"' '",
")",
".",
"map",
"{",
"|",
"s",
"|",
"s",
".",
"strip",
"}",
"end",
"end"
] | Decode a space delimited string of security scopes and return an array | [
"Decode",
"a",
"space",
"delimited",
"string",
"of",
"security",
"scopes",
"and",
"return",
"an",
"array"
] | b3d1c289a22ba90fa66adb513de9eead70df6e60 | https://github.com/sutajio/auth/blob/b3d1c289a22ba90fa66adb513de9eead70df6e60/lib/auth/helpers.rb#L49-L55 | train |
seevibes/twitter_ads | lib/twitter_ads/rest_resource.rb | TwitterADS.RestResource.check_method | def check_method(tab_ops, prefix, method_sym, do_call, *arguments, &block)
method_sym = method_sym.id2name
verb = :get
[:post, :get, :delete, :put].each do |averb|
if method_sym.start_with? averb.id2name
verb = averb
method_sym[averb.id2name + '_'] = ''
break
end
end
if tab_ops[verb].include? method_sym.to_sym
if do_call
params = arguments.first
method = prefix + method_sym
method += "/#{params.shift}" if params.first && params.first.class != Hash
return do_request verb, method, params.shift
else
return nil
end
end
nil
end | ruby | def check_method(tab_ops, prefix, method_sym, do_call, *arguments, &block)
method_sym = method_sym.id2name
verb = :get
[:post, :get, :delete, :put].each do |averb|
if method_sym.start_with? averb.id2name
verb = averb
method_sym[averb.id2name + '_'] = ''
break
end
end
if tab_ops[verb].include? method_sym.to_sym
if do_call
params = arguments.first
method = prefix + method_sym
method += "/#{params.shift}" if params.first && params.first.class != Hash
return do_request verb, method, params.shift
else
return nil
end
end
nil
end | [
"def",
"check_method",
"(",
"tab_ops",
",",
"prefix",
",",
"method_sym",
",",
"do_call",
",",
"*",
"arguments",
",",
"&",
"block",
")",
"method_sym",
"=",
"method_sym",
".",
"id2name",
"verb",
"=",
":get",
"[",
":post",
",",
":get",
",",
":delete",
",",
":put",
"]",
".",
"each",
"do",
"|",
"averb",
"|",
"if",
"method_sym",
".",
"start_with?",
"averb",
".",
"id2name",
"verb",
"=",
"averb",
"method_sym",
"[",
"averb",
".",
"id2name",
"+",
"'_'",
"]",
"=",
"''",
"break",
"end",
"end",
"if",
"tab_ops",
"[",
"verb",
"]",
".",
"include?",
"method_sym",
".",
"to_sym",
"if",
"do_call",
"params",
"=",
"arguments",
".",
"first",
"method",
"=",
"prefix",
"+",
"method_sym",
"method",
"+=",
"\"/#{params.shift}\"",
"if",
"params",
".",
"first",
"&&",
"params",
".",
"first",
".",
"class",
"!=",
"Hash",
"return",
"do_request",
"verb",
",",
"method",
",",
"params",
".",
"shift",
"else",
"return",
"nil",
"end",
"end",
"nil",
"end"
] | Dynamic check of methods
tab_ops contain the list of allowed method and verbs
prefix the prefix to add to the method | [
"Dynamic",
"check",
"of",
"methods",
"tab_ops",
"contain",
"the",
"list",
"of",
"allowed",
"method",
"and",
"verbs",
"prefix",
"the",
"prefix",
"to",
"add",
"to",
"the",
"method"
] | f7fbc16d3f31ef2ebb8baf49c7033f119c575594 | https://github.com/seevibes/twitter_ads/blob/f7fbc16d3f31ef2ebb8baf49c7033f119c575594/lib/twitter_ads/rest_resource.rb#L64-L85 | train |
patchapps/rabbit-hutch | lib/consumer.rb | RabbitHutch.Consumer.handle_message | def handle_message(metadata, payload)
# loop through appenders and fire each as required
@consumers.each do |consumer|
action = metadata.routing_key.split('.', 2).first
if(action == "publish")
exchange = metadata.attributes[:headers]["exchange_name"]
queue = metadata.routing_key.split('.', 2).last
item = {:date => Time.now,
:exchange => exchange,
:queue => queue,
:routing_keys => metadata.attributes[:headers]["routing_keys"].inspect,
:attributes => metadata.attributes.inspect,
:payload => payload.inspect
}
consumer.log_event(item)
end
end
end | ruby | def handle_message(metadata, payload)
# loop through appenders and fire each as required
@consumers.each do |consumer|
action = metadata.routing_key.split('.', 2).first
if(action == "publish")
exchange = metadata.attributes[:headers]["exchange_name"]
queue = metadata.routing_key.split('.', 2).last
item = {:date => Time.now,
:exchange => exchange,
:queue => queue,
:routing_keys => metadata.attributes[:headers]["routing_keys"].inspect,
:attributes => metadata.attributes.inspect,
:payload => payload.inspect
}
consumer.log_event(item)
end
end
end | [
"def",
"handle_message",
"(",
"metadata",
",",
"payload",
")",
"@consumers",
".",
"each",
"do",
"|",
"consumer",
"|",
"action",
"=",
"metadata",
".",
"routing_key",
".",
"split",
"(",
"'.'",
",",
"2",
")",
".",
"first",
"if",
"(",
"action",
"==",
"\"publish\"",
")",
"exchange",
"=",
"metadata",
".",
"attributes",
"[",
":headers",
"]",
"[",
"\"exchange_name\"",
"]",
"queue",
"=",
"metadata",
".",
"routing_key",
".",
"split",
"(",
"'.'",
",",
"2",
")",
".",
"last",
"item",
"=",
"{",
":date",
"=>",
"Time",
".",
"now",
",",
":exchange",
"=>",
"exchange",
",",
":queue",
"=>",
"queue",
",",
":routing_keys",
"=>",
"metadata",
".",
"attributes",
"[",
":headers",
"]",
"[",
"\"routing_keys\"",
"]",
".",
"inspect",
",",
":attributes",
"=>",
"metadata",
".",
"attributes",
".",
"inspect",
",",
":payload",
"=>",
"payload",
".",
"inspect",
"}",
"consumer",
".",
"log_event",
"(",
"item",
")",
"end",
"end",
"end"
] | Raised on receipt of a message from RabbitMq and uses the appropriate appender | [
"Raised",
"on",
"receipt",
"of",
"a",
"message",
"from",
"RabbitMq",
"and",
"uses",
"the",
"appropriate",
"appender"
] | 42337b0ddda60b749fc2fe088f4e8dba674d198d | https://github.com/patchapps/rabbit-hutch/blob/42337b0ddda60b749fc2fe088f4e8dba674d198d/lib/consumer.rb#L13-L30 | train |
dlangevin/gxapi_rails | lib/gxapi/google_analytics.rb | Gxapi.GoogleAnalytics.get_experiments | def get_experiments
@experiments ||= begin
# fetch our data from the cache
data = Gxapi.with_error_handling do
# handle caching
self.list_experiments_from_cache
end
# turn into Gxapi::Ostructs
(data || []).collect{|data| Ostruct.new(data)}
end
end | ruby | def get_experiments
@experiments ||= begin
# fetch our data from the cache
data = Gxapi.with_error_handling do
# handle caching
self.list_experiments_from_cache
end
# turn into Gxapi::Ostructs
(data || []).collect{|data| Ostruct.new(data)}
end
end | [
"def",
"get_experiments",
"@experiments",
"||=",
"begin",
"data",
"=",
"Gxapi",
".",
"with_error_handling",
"do",
"self",
".",
"list_experiments_from_cache",
"end",
"(",
"data",
"||",
"[",
"]",
")",
".",
"collect",
"{",
"|",
"data",
"|",
"Ostruct",
".",
"new",
"(",
"data",
")",
"}",
"end",
"end"
] | return a list of all experiments
@return [Array<Gxapi::Ostruct>] | [
"return",
"a",
"list",
"of",
"all",
"experiments"
] | 21361227f0c70118b38f7fa372a18c0ae7aab810 | https://github.com/dlangevin/gxapi_rails/blob/21361227f0c70118b38f7fa372a18c0ae7aab810/lib/gxapi/google_analytics.rb#L23-L33 | train |
dlangevin/gxapi_rails | lib/gxapi/google_analytics.rb | Gxapi.GoogleAnalytics.get_variant | def get_variant(identifier)
# pull in an experiment
experiment = self.get_experiment(identifier)
if self.run_experiment?(experiment)
# select variant for the experiment
variant = self.select_variant(experiment)
# return if it it's present
return variant if variant.present?
end
# return blank value if we don't have an experiment or don't get
# a valid value
return Ostruct.new(
name: "default",
index: -1,
experiment_id: nil
)
end | ruby | def get_variant(identifier)
# pull in an experiment
experiment = self.get_experiment(identifier)
if self.run_experiment?(experiment)
# select variant for the experiment
variant = self.select_variant(experiment)
# return if it it's present
return variant if variant.present?
end
# return blank value if we don't have an experiment or don't get
# a valid value
return Ostruct.new(
name: "default",
index: -1,
experiment_id: nil
)
end | [
"def",
"get_variant",
"(",
"identifier",
")",
"experiment",
"=",
"self",
".",
"get_experiment",
"(",
"identifier",
")",
"if",
"self",
".",
"run_experiment?",
"(",
"experiment",
")",
"variant",
"=",
"self",
".",
"select_variant",
"(",
"experiment",
")",
"return",
"variant",
"if",
"variant",
".",
"present?",
"end",
"return",
"Ostruct",
".",
"new",
"(",
"name",
":",
"\"default\"",
",",
"index",
":",
"-",
"1",
",",
"experiment_id",
":",
"nil",
")",
"end"
] | get a variant for an experiment
@param identifier [String, Hash] Either the experiment name
as a String or a hash of what to look for
@return [Gxapi::Ostruct] | [
"get",
"a",
"variant",
"for",
"an",
"experiment"
] | 21361227f0c70118b38f7fa372a18c0ae7aab810 | https://github.com/dlangevin/gxapi_rails/blob/21361227f0c70118b38f7fa372a18c0ae7aab810/lib/gxapi/google_analytics.rb#L42-L59 | train |
dlangevin/gxapi_rails | lib/gxapi/google_analytics.rb | Gxapi.GoogleAnalytics.list_experiments | def list_experiments
response = self.client.execute({
api_method: self.analytics_experiments.list,
parameters: {
accountId: self.config.account_id.to_s,
profileId: self.config.profile_id.to_s,
webPropertyId: self.config.web_property_id
}
})
response.data.items.collect(&:to_hash)
end | ruby | def list_experiments
response = self.client.execute({
api_method: self.analytics_experiments.list,
parameters: {
accountId: self.config.account_id.to_s,
profileId: self.config.profile_id.to_s,
webPropertyId: self.config.web_property_id
}
})
response.data.items.collect(&:to_hash)
end | [
"def",
"list_experiments",
"response",
"=",
"self",
".",
"client",
".",
"execute",
"(",
"{",
"api_method",
":",
"self",
".",
"analytics_experiments",
".",
"list",
",",
"parameters",
":",
"{",
"accountId",
":",
"self",
".",
"config",
".",
"account_id",
".",
"to_s",
",",
"profileId",
":",
"self",
".",
"config",
".",
"profile_id",
".",
"to_s",
",",
"webPropertyId",
":",
"self",
".",
"config",
".",
"web_property_id",
"}",
"}",
")",
"response",
".",
"data",
".",
"items",
".",
"collect",
"(",
"&",
":to_hash",
")",
"end"
] | List all experiments for our account
@return [Array<Gxapi::Ostruct>] Collection of Experiment data
retrieved from Google's API | [
"List",
"all",
"experiments",
"for",
"our",
"account"
] | 21361227f0c70118b38f7fa372a18c0ae7aab810 | https://github.com/dlangevin/gxapi_rails/blob/21361227f0c70118b38f7fa372a18c0ae7aab810/lib/gxapi/google_analytics.rb#L82-L92 | train |
dlangevin/gxapi_rails | lib/gxapi/google_analytics.rb | Gxapi.GoogleAnalytics.client | def client
@client ||= begin
client = Google::APIClient.new
client.authorization = Signet::OAuth2::Client.new(
token_credential_uri: 'https://accounts.google.com/o/oauth2/token',
audience: 'https://accounts.google.com/o/oauth2/token',
scope: 'https://www.googleapis.com/auth/analytics.readonly',
issuer: Gxapi.config.google.email,
signing_key: self.get_key
)
client.authorization.fetch_access_token!
client
end
end | ruby | def client
@client ||= begin
client = Google::APIClient.new
client.authorization = Signet::OAuth2::Client.new(
token_credential_uri: 'https://accounts.google.com/o/oauth2/token',
audience: 'https://accounts.google.com/o/oauth2/token',
scope: 'https://www.googleapis.com/auth/analytics.readonly',
issuer: Gxapi.config.google.email,
signing_key: self.get_key
)
client.authorization.fetch_access_token!
client
end
end | [
"def",
"client",
"@client",
"||=",
"begin",
"client",
"=",
"Google",
"::",
"APIClient",
".",
"new",
"client",
".",
"authorization",
"=",
"Signet",
"::",
"OAuth2",
"::",
"Client",
".",
"new",
"(",
"token_credential_uri",
":",
"'https://accounts.google.com/o/oauth2/token'",
",",
"audience",
":",
"'https://accounts.google.com/o/oauth2/token'",
",",
"scope",
":",
"'https://www.googleapis.com/auth/analytics.readonly'",
",",
"issuer",
":",
"Gxapi",
".",
"config",
".",
"google",
".",
"email",
",",
"signing_key",
":",
"self",
".",
"get_key",
")",
"client",
".",
"authorization",
".",
"fetch_access_token!",
"client",
"end",
"end"
] | google api client
@return [Google::APIClient] | [
"google",
"api",
"client"
] | 21361227f0c70118b38f7fa372a18c0ae7aab810 | https://github.com/dlangevin/gxapi_rails/blob/21361227f0c70118b38f7fa372a18c0ae7aab810/lib/gxapi/google_analytics.rb#L117-L130 | train |
dlangevin/gxapi_rails | lib/gxapi/google_analytics.rb | Gxapi.GoogleAnalytics.select_variant | def select_variant(experiment)
# starts off at 0
accum = 0.0
sample = Kernel.rand
# go through our experiments and return the variation that matches
# our random value
experiment.variations.each_with_index do |variation, i|
# we want to record the index in the array for this variation
variation.index = i
variation.experiment_id = experiment.id
# add the variation's weight to accum
accum += variation.weight
# return the variation if accum is more than our random value
if sample <= accum
return variation
end
end
# default to nil
return nil
end | ruby | def select_variant(experiment)
# starts off at 0
accum = 0.0
sample = Kernel.rand
# go through our experiments and return the variation that matches
# our random value
experiment.variations.each_with_index do |variation, i|
# we want to record the index in the array for this variation
variation.index = i
variation.experiment_id = experiment.id
# add the variation's weight to accum
accum += variation.weight
# return the variation if accum is more than our random value
if sample <= accum
return variation
end
end
# default to nil
return nil
end | [
"def",
"select_variant",
"(",
"experiment",
")",
"accum",
"=",
"0.0",
"sample",
"=",
"Kernel",
".",
"rand",
"experiment",
".",
"variations",
".",
"each_with_index",
"do",
"|",
"variation",
",",
"i",
"|",
"variation",
".",
"index",
"=",
"i",
"variation",
".",
"experiment_id",
"=",
"experiment",
".",
"id",
"accum",
"+=",
"variation",
".",
"weight",
"if",
"sample",
"<=",
"accum",
"return",
"variation",
"end",
"end",
"return",
"nil",
"end"
] | Select a variant from a given experiment
@param experiment [Ostruct] The experiment to choose for
@return [Ostruct, nil] The selected variant or nil if none is
selected | [
"Select",
"a",
"variant",
"from",
"a",
"given",
"experiment"
] | 21361227f0c70118b38f7fa372a18c0ae7aab810 | https://github.com/dlangevin/gxapi_rails/blob/21361227f0c70118b38f7fa372a18c0ae7aab810/lib/gxapi/google_analytics.rb#L185-L208 | train |
emad-elsaid/command_tree | lib/command_tree/tree.rb | CommandTree.Tree.merge | def merge(subtree, prefix, name, options = {})
register(prefix, name, options)
subtree.calls.each do |key, command|
next unless command
calls["#{prefix}#{key}"] = command
end
end | ruby | def merge(subtree, prefix, name, options = {})
register(prefix, name, options)
subtree.calls.each do |key, command|
next unless command
calls["#{prefix}#{key}"] = command
end
end | [
"def",
"merge",
"(",
"subtree",
",",
"prefix",
",",
"name",
",",
"options",
"=",
"{",
"}",
")",
"register",
"(",
"prefix",
",",
"name",
",",
"options",
")",
"subtree",
".",
"calls",
".",
"each",
"do",
"|",
"key",
",",
"command",
"|",
"next",
"unless",
"command",
"calls",
"[",
"\"#{prefix}#{key}\"",
"]",
"=",
"command",
"end",
"end"
] | merge a subtree with a prefix and a name | [
"merge",
"a",
"subtree",
"with",
"a",
"prefix",
"and",
"a",
"name"
] | d30e0f00c6ff8f3c344d7e63f662a71d8abe52c0 | https://github.com/emad-elsaid/command_tree/blob/d30e0f00c6ff8f3c344d7e63f662a71d8abe52c0/lib/command_tree/tree.rb#L47-L54 | train |
postmodern/pullr | lib/pullr/local_repository.rb | Pullr.LocalRepository.scm_dir | def scm_dir
dir, scm = SCM::DIRS.find { |dir,scm| scm == @scm }
return dir
end | ruby | def scm_dir
dir, scm = SCM::DIRS.find { |dir,scm| scm == @scm }
return dir
end | [
"def",
"scm_dir",
"dir",
",",
"scm",
"=",
"SCM",
"::",
"DIRS",
".",
"find",
"{",
"|",
"dir",
",",
"scm",
"|",
"scm",
"==",
"@scm",
"}",
"return",
"dir",
"end"
] | The control directory used by the SCM.
@return [String]
The name of the control directory. | [
"The",
"control",
"directory",
"used",
"by",
"the",
"SCM",
"."
] | 96993fdbf4765a75c539bdb3c4902373458093e7 | https://github.com/postmodern/pullr/blob/96993fdbf4765a75c539bdb3c4902373458093e7/lib/pullr/local_repository.rb#L67-L71 | train |
ghn/transprt | lib/transprt/client.rb | Transprt.Client.locations | def locations(parameters)
allowed_parameters = %w(query x y type)
query = create_query(parameters, allowed_parameters)
locations = perform('locations', query)
locations['stations']
end | ruby | def locations(parameters)
allowed_parameters = %w(query x y type)
query = create_query(parameters, allowed_parameters)
locations = perform('locations', query)
locations['stations']
end | [
"def",
"locations",
"(",
"parameters",
")",
"allowed_parameters",
"=",
"%w(",
"query",
"x",
"y",
"type",
")",
"query",
"=",
"create_query",
"(",
"parameters",
",",
"allowed_parameters",
")",
"locations",
"=",
"perform",
"(",
"'locations'",
",",
"query",
")",
"locations",
"[",
"'stations'",
"]",
"end"
] | => find locations | [
"=",
">",
"find",
"locations"
] | da609d39cd1907ec86814c7c5412e889a807193c | https://github.com/ghn/transprt/blob/da609d39cd1907ec86814c7c5412e889a807193c/lib/transprt/client.rb#L20-L27 | train |
ghn/transprt | lib/transprt/client.rb | Transprt.Client.connections | def connections(parameters)
allowed_parameters = %w(from to via date time isArrivalTime
transportations limit page direct sleeper
couchette bike)
query = create_query(parameters, allowed_parameters)
locations = perform('connections', query)
locations['connections']
end | ruby | def connections(parameters)
allowed_parameters = %w(from to via date time isArrivalTime
transportations limit page direct sleeper
couchette bike)
query = create_query(parameters, allowed_parameters)
locations = perform('connections', query)
locations['connections']
end | [
"def",
"connections",
"(",
"parameters",
")",
"allowed_parameters",
"=",
"%w(",
"from",
"to",
"via",
"date",
"time",
"isArrivalTime",
"transportations",
"limit",
"page",
"direct",
"sleeper",
"couchette",
"bike",
")",
"query",
"=",
"create_query",
"(",
"parameters",
",",
"allowed_parameters",
")",
"locations",
"=",
"perform",
"(",
"'connections'",
",",
"query",
")",
"locations",
"[",
"'connections'",
"]",
"end"
] | => find connections | [
"=",
">",
"find",
"connections"
] | da609d39cd1907ec86814c7c5412e889a807193c | https://github.com/ghn/transprt/blob/da609d39cd1907ec86814c7c5412e889a807193c/lib/transprt/client.rb#L32-L41 | train |
ghn/transprt | lib/transprt/client.rb | Transprt.Client.stationboard | def stationboard(parameters)
allowed_parameters = %w(station id limit transportations datetime)
query = create_query(parameters, allowed_parameters)
locations = perform('stationboard', query)
locations['stationboard']
end | ruby | def stationboard(parameters)
allowed_parameters = %w(station id limit transportations datetime)
query = create_query(parameters, allowed_parameters)
locations = perform('stationboard', query)
locations['stationboard']
end | [
"def",
"stationboard",
"(",
"parameters",
")",
"allowed_parameters",
"=",
"%w(",
"station",
"id",
"limit",
"transportations",
"datetime",
")",
"query",
"=",
"create_query",
"(",
"parameters",
",",
"allowed_parameters",
")",
"locations",
"=",
"perform",
"(",
"'stationboard'",
",",
"query",
")",
"locations",
"[",
"'stationboard'",
"]",
"end"
] | => find station boards | [
"=",
">",
"find",
"station",
"boards"
] | da609d39cd1907ec86814c7c5412e889a807193c | https://github.com/ghn/transprt/blob/da609d39cd1907ec86814c7c5412e889a807193c/lib/transprt/client.rb#L46-L53 | train |
billychan/simple_activity | lib/simple_activity/models/activity.rb | SimpleActivity.Activity.method_missing | def method_missing(method_name, *arguments, &block)
if method_name.to_s =~ /(actor|target)_(?!type|id).*/
self.cache.try(:[], method_name.to_s)
else
super
end
end | ruby | def method_missing(method_name, *arguments, &block)
if method_name.to_s =~ /(actor|target)_(?!type|id).*/
self.cache.try(:[], method_name.to_s)
else
super
end
end | [
"def",
"method_missing",
"(",
"method_name",
",",
"*",
"arguments",
",",
"&",
"block",
")",
"if",
"method_name",
".",
"to_s",
"=~",
"/",
"/",
"self",
".",
"cache",
".",
"try",
"(",
":[]",
",",
"method_name",
".",
"to_s",
")",
"else",
"super",
"end",
"end"
] | Delegate the methods start with "actor_" or "target_" to
cached result | [
"Delegate",
"the",
"methods",
"start",
"with",
"actor_",
"or",
"target_",
"to",
"cached",
"result"
] | fd24768908393e6aeae285834902be05c7b8ce42 | https://github.com/billychan/simple_activity/blob/fd24768908393e6aeae285834902be05c7b8ce42/lib/simple_activity/models/activity.rb#L35-L41 | train |
profitbricks/profitbricks-sdk-ruby | lib/profitbricks/loadbalancer.rb | ProfitBricks.Loadbalancer.update | def update(options = {})
response = ProfitBricks.request(
method: :patch,
path: "/datacenters/#{datacenterId}/loadbalancers/#{id}",
expects: 202,
body: options.to_json
)
if response
self.requestId = response['requestId']
@properties = @properties.merge(response['properties'])
end
self
end | ruby | def update(options = {})
response = ProfitBricks.request(
method: :patch,
path: "/datacenters/#{datacenterId}/loadbalancers/#{id}",
expects: 202,
body: options.to_json
)
if response
self.requestId = response['requestId']
@properties = @properties.merge(response['properties'])
end
self
end | [
"def",
"update",
"(",
"options",
"=",
"{",
"}",
")",
"response",
"=",
"ProfitBricks",
".",
"request",
"(",
"method",
":",
":patch",
",",
"path",
":",
"\"/datacenters/#{datacenterId}/loadbalancers/#{id}\"",
",",
"expects",
":",
"202",
",",
"body",
":",
"options",
".",
"to_json",
")",
"if",
"response",
"self",
".",
"requestId",
"=",
"response",
"[",
"'requestId'",
"]",
"@properties",
"=",
"@properties",
".",
"merge",
"(",
"response",
"[",
"'properties'",
"]",
")",
"end",
"self",
"end"
] | Update the loadbalancer. | [
"Update",
"the",
"loadbalancer",
"."
] | 03a379e412b0e6c0789ed14f2449f18bda622742 | https://github.com/profitbricks/profitbricks-sdk-ruby/blob/03a379e412b0e6c0789ed14f2449f18bda622742/lib/profitbricks/loadbalancer.rb#L16-L28 | train |
jlinder/nitroapi | lib/nitro_api.rb | NitroApi.NitroApi.sign | def sign(time)
unencrypted_signature = @api_key + @secret + time + @user.to_s
to_digest = unencrypted_signature + unencrypted_signature.length.to_s
return Digest::MD5.hexdigest(to_digest)
end | ruby | def sign(time)
unencrypted_signature = @api_key + @secret + time + @user.to_s
to_digest = unencrypted_signature + unencrypted_signature.length.to_s
return Digest::MD5.hexdigest(to_digest)
end | [
"def",
"sign",
"(",
"time",
")",
"unencrypted_signature",
"=",
"@api_key",
"+",
"@secret",
"+",
"time",
"+",
"@user",
".",
"to_s",
"to_digest",
"=",
"unencrypted_signature",
"+",
"unencrypted_signature",
".",
"length",
".",
"to_s",
"return",
"Digest",
"::",
"MD5",
".",
"hexdigest",
"(",
"to_digest",
")",
"end"
] | Method for constructing a signature | [
"Method",
"for",
"constructing",
"a",
"signature"
] | 9bf51a1988e213ce0020b783d7d375fe8d418638 | https://github.com/jlinder/nitroapi/blob/9bf51a1988e213ce0020b783d7d375fe8d418638/lib/nitro_api.rb#L76-L80 | train |
jrochkind/borrow_direct | lib/borrow_direct/generate_query.rb | BorrowDirect.GenerateQuery.normalized_author | def normalized_author(author)
return "" if author.nil? || author.empty?
author = author.downcase
# Just take everything before the comma/semicolon if we have one --
# or before an "and", for stripping individuals out of 245c
# multiples.
if author =~ /\A([^,;]*)(,|\sand\s|;)/
author = $1
end
author.gsub!(/\A.*by\s*/, '')
# We want to remove some punctuation that is better
# turned into a space in the query. Along with
# any kind of unicode space, why not.
author.gsub!(PUNCT_STRIP_REGEX, ' ')
# compress any remaining whitespace
author.strip!
author.gsub!(/\s+/, ' ')
return author
end | ruby | def normalized_author(author)
return "" if author.nil? || author.empty?
author = author.downcase
# Just take everything before the comma/semicolon if we have one --
# or before an "and", for stripping individuals out of 245c
# multiples.
if author =~ /\A([^,;]*)(,|\sand\s|;)/
author = $1
end
author.gsub!(/\A.*by\s*/, '')
# We want to remove some punctuation that is better
# turned into a space in the query. Along with
# any kind of unicode space, why not.
author.gsub!(PUNCT_STRIP_REGEX, ' ')
# compress any remaining whitespace
author.strip!
author.gsub!(/\s+/, ' ')
return author
end | [
"def",
"normalized_author",
"(",
"author",
")",
"return",
"\"\"",
"if",
"author",
".",
"nil?",
"||",
"author",
".",
"empty?",
"author",
"=",
"author",
".",
"downcase",
"if",
"author",
"=~",
"/",
"\\A",
"\\s",
"\\s",
"/",
"author",
"=",
"$1",
"end",
"author",
".",
"gsub!",
"(",
"/",
"\\A",
"\\s",
"/",
",",
"''",
")",
"author",
".",
"gsub!",
"(",
"PUNCT_STRIP_REGEX",
",",
"' '",
")",
"author",
".",
"strip!",
"author",
".",
"gsub!",
"(",
"/",
"\\s",
"/",
",",
"' '",
")",
"return",
"author",
"end"
] | Lowercase, and try to get just the last name out of something
that looks like a cataloging authorized heading.
Try to remove leading 'by' stuff when we're getting a 245c | [
"Lowercase",
"and",
"try",
"to",
"get",
"just",
"the",
"last",
"name",
"out",
"of",
"something",
"that",
"looks",
"like",
"a",
"cataloging",
"authorized",
"heading",
"."
] | f2f53760e15d742a5c5584dd641f20dea315f99f | https://github.com/jrochkind/borrow_direct/blob/f2f53760e15d742a5c5584dd641f20dea315f99f/lib/borrow_direct/generate_query.rb#L129-L154 | train |
jduckett/duck_map | lib/duck_map/view_helpers.rb | DuckMap.ActionViewHelpers.sitemap_meta_keywords | def sitemap_meta_keywords
return controller.sitemap_meta_data[:keywords].blank? ? nil : tag(:meta, {name: :keywords, content: controller.sitemap_meta_data[:keywords]}, false, false)
end | ruby | def sitemap_meta_keywords
return controller.sitemap_meta_data[:keywords].blank? ? nil : tag(:meta, {name: :keywords, content: controller.sitemap_meta_data[:keywords]}, false, false)
end | [
"def",
"sitemap_meta_keywords",
"return",
"controller",
".",
"sitemap_meta_data",
"[",
":keywords",
"]",
".",
"blank?",
"?",
"nil",
":",
"tag",
"(",
":meta",
",",
"{",
"name",
":",
":keywords",
",",
"content",
":",
"controller",
".",
"sitemap_meta_data",
"[",
":keywords",
"]",
"}",
",",
"false",
",",
"false",
")",
"end"
] | Generates a keywords meta tag for use inside HTML header area.
@return [String] HTML safe keywords meta tag. | [
"Generates",
"a",
"keywords",
"meta",
"tag",
"for",
"use",
"inside",
"HTML",
"header",
"area",
"."
] | c510acfa95e8ad4afb1501366058ae88a73704df | https://github.com/jduckett/duck_map/blob/c510acfa95e8ad4afb1501366058ae88a73704df/lib/duck_map/view_helpers.rb#L54-L56 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.