repo stringlengths 5 58 | path stringlengths 9 168 | func_name stringlengths 9 130 | original_string stringlengths 66 10.5k | language stringclasses 1
value | code stringlengths 66 10.5k | code_tokens list | docstring stringlengths 8 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 94 266 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
cinchrb/cinch | lib/cinch/user.rb | Cinch.User.mask | def mask(s = "%n!%u@%h")
s = s.gsub(/%(.)/) {
case $1
when "n"
@name
when "u"
self.user
when "h"
self.host
when "r"
self.realname
when "a"
self.authname
end
}
Mask.new(s)
end | ruby | def mask(s = "%n!%u@%h")
s = s.gsub(/%(.)/) {
case $1
when "n"
@name
when "u"
self.user
when "h"
self.host
when "r"
self.realname
when "a"
self.authname
end
}
Mask.new(s)
end | [
"def",
"mask",
"(",
"s",
"=",
"\"%n!%u@%h\"",
")",
"s",
"=",
"s",
".",
"gsub",
"(",
"/",
"/",
")",
"{",
"case",
"$1",
"when",
"\"n\"",
"@name",
"when",
"\"u\"",
"self",
".",
"user",
"when",
"\"h\"",
"self",
".",
"host",
"when",
"\"r\"",
"self",
"... | Generates a mask for the user.
@param [String] s a pattern for generating the mask.
- %n = nickname
- %u = username
- %h = host
- %r = realname
- %a = authname
@return [Mask] | [
"Generates",
"a",
"mask",
"for",
"the",
"user",
"."
] | 2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0 | https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/user.rb#L353-L370 | train |
cinchrb/cinch | lib/cinch/user.rb | Cinch.User.monitor | def monitor
if @bot.irc.isupport["MONITOR"] > 0
@bot.irc.send "MONITOR + #@name"
else
refresh
@monitored_timer = Timer.new(@bot, interval: 30) {
refresh
}
@monitored_timer.start
end
@monitored = true
end | ruby | def monitor
if @bot.irc.isupport["MONITOR"] > 0
@bot.irc.send "MONITOR + #@name"
else
refresh
@monitored_timer = Timer.new(@bot, interval: 30) {
refresh
}
@monitored_timer.start
end
@monitored = true
end | [
"def",
"monitor",
"if",
"@bot",
".",
"irc",
".",
"isupport",
"[",
"\"MONITOR\"",
"]",
">",
"0",
"@bot",
".",
"irc",
".",
"send",
"\"MONITOR + #@name\"",
"else",
"refresh",
"@monitored_timer",
"=",
"Timer",
".",
"new",
"(",
"@bot",
",",
"interval",
":",
"... | Starts monitoring a user's online state by either using MONITOR
or periodically running WHOIS.
@since 2.0.0
@return [void]
@see #unmonitor | [
"Starts",
"monitoring",
"a",
"user",
"s",
"online",
"state",
"by",
"either",
"using",
"MONITOR",
"or",
"periodically",
"running",
"WHOIS",
"."
] | 2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0 | https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/user.rb#L387-L399 | train |
cinchrb/cinch | lib/cinch/user.rb | Cinch.User.online= | def online=(bool)
notify = self.__send__("online?_unsynced") != bool && @monitored
sync(:online?, bool, true)
return unless notify
if bool
@bot.handlers.dispatch(:online, nil, self)
else
@bot.handlers.dispatch(:offline, nil, self)
end
end | ruby | def online=(bool)
notify = self.__send__("online?_unsynced") != bool && @monitored
sync(:online?, bool, true)
return unless notify
if bool
@bot.handlers.dispatch(:online, nil, self)
else
@bot.handlers.dispatch(:offline, nil, self)
end
end | [
"def",
"online",
"=",
"(",
"bool",
")",
"notify",
"=",
"self",
".",
"__send__",
"(",
"\"online?_unsynced\"",
")",
"!=",
"bool",
"&&",
"@monitored",
"sync",
"(",
":online?",
",",
"bool",
",",
"true",
")",
"return",
"unless",
"notify",
"if",
"bool",
"@bot"... | Updates the user's online state and dispatch the correct event.
@since 2.0.0
@return [void]
@api private | [
"Updates",
"the",
"user",
"s",
"online",
"state",
"and",
"dispatch",
"the",
"correct",
"event",
"."
] | 2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0 | https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/user.rb#L462-L472 | train |
cinchrb/cinch | lib/cinch/irc.rb | Cinch.IRC.start | def start
setup
if connect
@sasl_remaining_methods = @bot.config.sasl.mechanisms.reverse
send_cap_ls
send_login
reading_thread = start_reading_thread
sending_thread = start_sending_thread
ping_thread = start_ping_thread
reading_thread.join
... | ruby | def start
setup
if connect
@sasl_remaining_methods = @bot.config.sasl.mechanisms.reverse
send_cap_ls
send_login
reading_thread = start_reading_thread
sending_thread = start_sending_thread
ping_thread = start_ping_thread
reading_thread.join
... | [
"def",
"start",
"setup",
"if",
"connect",
"@sasl_remaining_methods",
"=",
"@bot",
".",
"config",
".",
"sasl",
".",
"mechanisms",
".",
"reverse",
"send_cap_ls",
"send_login",
"reading_thread",
"=",
"start_reading_thread",
"sending_thread",
"=",
"start_sending_thread",
... | Establish a connection.
@return [void]
@since 2.0.0 | [
"Establish",
"a",
"connection",
"."
] | 2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0 | https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/irc.rb#L210-L225 | train |
cinchrb/cinch | lib/cinch/logger.rb | Cinch.Logger.log | def log(messages, event = :debug, level = event)
return unless will_log?(level)
@mutex.synchronize do
Array(messages).each do |message|
message = format_general(message)
message = format_message(message, event)
next if message.nil?
@output.puts message.encode... | ruby | def log(messages, event = :debug, level = event)
return unless will_log?(level)
@mutex.synchronize do
Array(messages).each do |message|
message = format_general(message)
message = format_message(message, event)
next if message.nil?
@output.puts message.encode... | [
"def",
"log",
"(",
"messages",
",",
"event",
"=",
":debug",
",",
"level",
"=",
"event",
")",
"return",
"unless",
"will_log?",
"(",
"level",
")",
"@mutex",
".",
"synchronize",
"do",
"Array",
"(",
"messages",
")",
".",
"each",
"do",
"|",
"message",
"|",
... | Logs a message.
@param [String, Array] messages The message(s) to log
@param [:debug, :incoming, :outgoing, :info, :warn,
:exception, :error, :fatal] event The kind of event that
triggered the message
@param [:debug, :info, :warn, :error, :fatal] level The level of the message
@return [void]
@version 2.0.0 | [
"Logs",
"a",
"message",
"."
] | 2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0 | https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/logger.rb#L110-L121 | train |
cinchrb/cinch | lib/cinch/channel_list.rb | Cinch.ChannelList.find_ensured | def find_ensured(name)
downcased_name = name.irc_downcase(@bot.irc.isupport["CASEMAPPING"])
@mutex.synchronize do
@cache[downcased_name] ||= Channel.new(name, @bot)
end
end | ruby | def find_ensured(name)
downcased_name = name.irc_downcase(@bot.irc.isupport["CASEMAPPING"])
@mutex.synchronize do
@cache[downcased_name] ||= Channel.new(name, @bot)
end
end | [
"def",
"find_ensured",
"(",
"name",
")",
"downcased_name",
"=",
"name",
".",
"irc_downcase",
"(",
"@bot",
".",
"irc",
".",
"isupport",
"[",
"\"CASEMAPPING\"",
"]",
")",
"@mutex",
".",
"synchronize",
"do",
"@cache",
"[",
"downcased_name",
"]",
"||=",
"Channel... | Finds or creates a channel.
@param [String] name name of a channel
@return [Channel]
@see Helpers#Channel | [
"Finds",
"or",
"creates",
"a",
"channel",
"."
] | 2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0 | https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/channel_list.rb#L13-L18 | train |
cinchrb/cinch | lib/cinch/channel.rb | Cinch.Channel.topic= | def topic=(new_topic)
if new_topic.size > @bot.irc.isupport["TOPICLEN"] && @bot.strict?
raise Exceptions::TopicTooLong, new_topic
end
@bot.irc.send "TOPIC #@name :#{new_topic}"
end | ruby | def topic=(new_topic)
if new_topic.size > @bot.irc.isupport["TOPICLEN"] && @bot.strict?
raise Exceptions::TopicTooLong, new_topic
end
@bot.irc.send "TOPIC #@name :#{new_topic}"
end | [
"def",
"topic",
"=",
"(",
"new_topic",
")",
"if",
"new_topic",
".",
"size",
">",
"@bot",
".",
"irc",
".",
"isupport",
"[",
"\"TOPICLEN\"",
"]",
"&&",
"@bot",
".",
"strict?",
"raise",
"Exceptions",
"::",
"TopicTooLong",
",",
"new_topic",
"end",
"@bot",
".... | Sets the topic.
@param [String] new_topic the new topic
@raise [Exceptions::TopicTooLong] Raised if the bot is operating
in {Bot#strict? strict mode} and when the new topic is too long. | [
"Sets",
"the",
"topic",
"."
] | 2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0 | https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/channel.rb#L316-L322 | train |
cinchrb/cinch | lib/cinch/channel.rb | Cinch.Channel.kick | def kick(user, reason = nil)
if reason.to_s.size > @bot.irc.isupport["KICKLEN"] && @bot.strict?
raise Exceptions::KickReasonTooLong, reason
end
@bot.irc.send("KICK #@name #{user} :#{reason}")
end | ruby | def kick(user, reason = nil)
if reason.to_s.size > @bot.irc.isupport["KICKLEN"] && @bot.strict?
raise Exceptions::KickReasonTooLong, reason
end
@bot.irc.send("KICK #@name #{user} :#{reason}")
end | [
"def",
"kick",
"(",
"user",
",",
"reason",
"=",
"nil",
")",
"if",
"reason",
".",
"to_s",
".",
"size",
">",
"@bot",
".",
"irc",
".",
"isupport",
"[",
"\"KICKLEN\"",
"]",
"&&",
"@bot",
".",
"strict?",
"raise",
"Exceptions",
"::",
"KickReasonTooLong",
","... | Kicks a user from the channel.
@param [String, User] user the user to kick
@param [String] reason a reason for the kick
@raise [Exceptions::KickReasonTooLong]
@return [void] | [
"Kicks",
"a",
"user",
"from",
"the",
"channel",
"."
] | 2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0 | https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/channel.rb#L330-L336 | train |
cinchrb/cinch | lib/cinch/channel.rb | Cinch.Channel.join | def join(key = nil)
if key.nil? and self.key != true
key = self.key
end
@bot.irc.send "JOIN #{[@name, key].compact.join(" ")}"
end | ruby | def join(key = nil)
if key.nil? and self.key != true
key = self.key
end
@bot.irc.send "JOIN #{[@name, key].compact.join(" ")}"
end | [
"def",
"join",
"(",
"key",
"=",
"nil",
")",
"if",
"key",
".",
"nil?",
"and",
"self",
".",
"key",
"!=",
"true",
"key",
"=",
"self",
".",
"key",
"end",
"@bot",
".",
"irc",
".",
"send",
"\"JOIN #{[@name, key].compact.join(\" \")}\"",
"end"
] | Joins the channel
@param [String] key the channel key, if any. If none is
specified but @key is set, @key will be used
@return [void] | [
"Joins",
"the",
"channel"
] | 2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0 | https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/channel.rb#L377-L382 | train |
cinchrb/cinch | lib/cinch/target.rb | Cinch.Target.send | def send(text, notice = false)
# TODO deprecate `notice` argument, put splitting into own
# method
text = text.to_s
split_start = @bot.config.message_split_start || ""
split_end = @bot.config.message_split_end || ""
command = notice ? "NOTICE" : "PRIVMSG"
prefix = ":#{@bot.... | ruby | def send(text, notice = false)
# TODO deprecate `notice` argument, put splitting into own
# method
text = text.to_s
split_start = @bot.config.message_split_start || ""
split_end = @bot.config.message_split_end || ""
command = notice ? "NOTICE" : "PRIVMSG"
prefix = ":#{@bot.... | [
"def",
"send",
"(",
"text",
",",
"notice",
"=",
"false",
")",
"text",
"=",
"text",
".",
"to_s",
"split_start",
"=",
"@bot",
".",
"config",
".",
"message_split_start",
"||",
"\"\"",
"split_end",
"=",
"@bot",
".",
"config",
".",
"message_split_end",
"||",
... | Sends a PRIVMSG to the target.
@param [#to_s] text the message to send
@param [Boolean] notice Use NOTICE instead of PRIVMSG?
@return [void]
@see #safe_msg
@note The aliases `msg` and `privmsg` are deprecated and will be
removed in a future version. | [
"Sends",
"a",
"PRIVMSG",
"to",
"the",
"target",
"."
] | 2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0 | https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/target.rb#L32-L48 | train |
cinchrb/cinch | lib/cinch/bot.rb | Cinch.Bot.start | def start(plugins = true)
@reconnects = 0
@plugins.register_plugins(@config.plugins.plugins) if plugins
begin
@user_list.each do |user|
user.in_whois = false
user.unsync_all
end # reset state of all users
@channel_list.each do |channel|
channel.u... | ruby | def start(plugins = true)
@reconnects = 0
@plugins.register_plugins(@config.plugins.plugins) if plugins
begin
@user_list.each do |user|
user.in_whois = false
user.unsync_all
end # reset state of all users
@channel_list.each do |channel|
channel.u... | [
"def",
"start",
"(",
"plugins",
"=",
"true",
")",
"@reconnects",
"=",
"0",
"@plugins",
".",
"register_plugins",
"(",
"@config",
".",
"plugins",
".",
"plugins",
")",
"if",
"plugins",
"begin",
"@user_list",
".",
"each",
"do",
"|",
"user",
"|",
"user",
".",... | Connects the bot to a server.
@param [Boolean] plugins Automatically register plugins from
`@config.plugins.plugins`?
@return [void] | [
"Connects",
"the",
"bot",
"to",
"a",
"server",
"."
] | 2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0 | https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/bot.rb#L237-L294 | train |
cinchrb/cinch | lib/cinch/bot.rb | Cinch.Bot.part | def part(channel, reason = nil)
channel = Channel(channel)
channel.part(reason)
channel
end | ruby | def part(channel, reason = nil)
channel = Channel(channel)
channel.part(reason)
channel
end | [
"def",
"part",
"(",
"channel",
",",
"reason",
"=",
"nil",
")",
"channel",
"=",
"Channel",
"(",
"channel",
")",
"channel",
".",
"part",
"(",
"reason",
")",
"channel",
"end"
] | Part a channel.
@param [String, Channel] channel either the name of a channel or a {Channel} object
@param [String] reason an optional reason/part message
@return [Channel] The channel that was left
@see Channel#part | [
"Part",
"a",
"channel",
"."
] | 2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0 | https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/bot.rb#L318-L323 | train |
cinchrb/cinch | lib/cinch/bot.rb | Cinch.Bot.generate_next_nick! | def generate_next_nick!(base = nil)
nicks = @config.nicks || []
if base
# if `base` is not in our list of nicks to try, assume that it's
# custom and just append an underscore
if !nicks.include?(base)
new_nick = base + "_"
else
# if we have a base, try t... | ruby | def generate_next_nick!(base = nil)
nicks = @config.nicks || []
if base
# if `base` is not in our list of nicks to try, assume that it's
# custom and just append an underscore
if !nicks.include?(base)
new_nick = base + "_"
else
# if we have a base, try t... | [
"def",
"generate_next_nick!",
"(",
"base",
"=",
"nil",
")",
"nicks",
"=",
"@config",
".",
"nicks",
"||",
"[",
"]",
"if",
"base",
"if",
"!",
"nicks",
".",
"include?",
"(",
"base",
")",
"new_nick",
"=",
"base",
"+",
"\"_\"",
"else",
"new_index",
"=",
"... | Try to create a free nick, first by cycling through all
available alternatives and then by appending underscores.
@param [String] base The base nick to start trying from
@api private
@return [String]
@since 2.0.0 | [
"Try",
"to",
"create",
"a",
"free",
"nick",
"first",
"by",
"cycling",
"through",
"all",
"available",
"alternatives",
"and",
"then",
"by",
"appending",
"underscores",
"."
] | 2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0 | https://github.com/cinchrb/cinch/blob/2e149ffcf94d0f4eb6c1566a8e39d7e6d8be4ee0/lib/cinch/bot.rb#L448-L472 | train |
cookpad/garage | lib/garage/representer.rb | Garage::Representer.ClassMethods.metadata | def metadata
{:definitions => representer_attrs.grep(Definition).map {|definition| definition.name},
:links => representer_attrs.grep(Link).map {|link| link.options[:as] ? {link.rel => {'as' => link.options[:as]}} : link.rel}
}
end | ruby | def metadata
{:definitions => representer_attrs.grep(Definition).map {|definition| definition.name},
:links => representer_attrs.grep(Link).map {|link| link.options[:as] ? {link.rel => {'as' => link.options[:as]}} : link.rel}
}
end | [
"def",
"metadata",
"{",
":definitions",
"=>",
"representer_attrs",
".",
"grep",
"(",
"Definition",
")",
".",
"map",
"{",
"|",
"definition",
"|",
"definition",
".",
"name",
"}",
",",
":links",
"=>",
"representer_attrs",
".",
"grep",
"(",
"Link",
")",
".",
... | represents the representer's schema in JSON format | [
"represents",
"the",
"representer",
"s",
"schema",
"in",
"JSON",
"format"
] | 97444551c75709f132746b3e18183e0cd0ca1a20 | https://github.com/cookpad/garage/blob/97444551c75709f132746b3e18183e0cd0ca1a20/lib/garage/representer.rb#L113-L117 | train |
cookpad/garage | lib/garage/controller_helper.rb | Garage.ControllerHelper.requested_by? | def requested_by?(resource)
user = resource.respond_to?(:owner) ? resource.owner : resource
case
when current_resource_owner.nil?
false
when !user.is_a?(current_resource_owner.class)
false
when current_resource_owner.id == user.id
true
else
false
... | ruby | def requested_by?(resource)
user = resource.respond_to?(:owner) ? resource.owner : resource
case
when current_resource_owner.nil?
false
when !user.is_a?(current_resource_owner.class)
false
when current_resource_owner.id == user.id
true
else
false
... | [
"def",
"requested_by?",
"(",
"resource",
")",
"user",
"=",
"resource",
".",
"respond_to?",
"(",
":owner",
")",
"?",
"resource",
".",
"owner",
":",
"resource",
"case",
"when",
"current_resource_owner",
".",
"nil?",
"false",
"when",
"!",
"user",
".",
"is_a?",
... | Check if the current resource is the same as the requester.
The resource must respond to `resource.id` method. | [
"Check",
"if",
"the",
"current",
"resource",
"is",
"the",
"same",
"as",
"the",
"requester",
".",
"The",
"resource",
"must",
"respond",
"to",
"resource",
".",
"id",
"method",
"."
] | 97444551c75709f132746b3e18183e0cd0ca1a20 | https://github.com/cookpad/garage/blob/97444551c75709f132746b3e18183e0cd0ca1a20/lib/garage/controller_helper.rb#L53-L65 | train |
piotrmurach/loaf | lib/loaf/options_validator.rb | Loaf.OptionsValidator.valid? | def valid?(options)
valid_options = Loaf::Configuration::VALID_ATTRIBUTES
options.each_key do |key|
unless valid_options.include?(key)
fail Loaf::InvalidOptions.new(key, valid_options)
end
end
true
end | ruby | def valid?(options)
valid_options = Loaf::Configuration::VALID_ATTRIBUTES
options.each_key do |key|
unless valid_options.include?(key)
fail Loaf::InvalidOptions.new(key, valid_options)
end
end
true
end | [
"def",
"valid?",
"(",
"options",
")",
"valid_options",
"=",
"Loaf",
"::",
"Configuration",
"::",
"VALID_ATTRIBUTES",
"options",
".",
"each_key",
"do",
"|",
"key",
"|",
"unless",
"valid_options",
".",
"include?",
"(",
"key",
")",
"fail",
"Loaf",
"::",
"Invali... | Check if options are valid or not
@param [Hash] options
@return [Boolean]
@api public | [
"Check",
"if",
"options",
"are",
"valid",
"or",
"not"
] | 001dfad8361690051be76afdea11691b2aca8f14 | https://github.com/piotrmurach/loaf/blob/001dfad8361690051be76afdea11691b2aca8f14/lib/loaf/options_validator.rb#L15-L23 | train |
piotrmurach/loaf | lib/loaf/configuration.rb | Loaf.Configuration.to_hash | def to_hash
VALID_ATTRIBUTES.reduce({}) { |acc, k| acc[k] = send(k); acc }
end | ruby | def to_hash
VALID_ATTRIBUTES.reduce({}) { |acc, k| acc[k] = send(k); acc }
end | [
"def",
"to_hash",
"VALID_ATTRIBUTES",
".",
"reduce",
"(",
"{",
"}",
")",
"{",
"|",
"acc",
",",
"k",
"|",
"acc",
"[",
"k",
"]",
"=",
"send",
"(",
"k",
")",
";",
"acc",
"}",
"end"
] | Setup this configuration
@api public
Convert all properties into hash
@return [Hash]
@api public | [
"Setup",
"this",
"configuration"
] | 001dfad8361690051be76afdea11691b2aca8f14 | https://github.com/piotrmurach/loaf/blob/001dfad8361690051be76afdea11691b2aca8f14/lib/loaf/configuration.rb#L32-L34 | train |
piotrmurach/loaf | lib/loaf/view_extensions.rb | Loaf.ViewExtensions.breadcrumb | def breadcrumb(name, url, options = {})
_breadcrumbs << Loaf::Crumb.new(name, url, options)
end | ruby | def breadcrumb(name, url, options = {})
_breadcrumbs << Loaf::Crumb.new(name, url, options)
end | [
"def",
"breadcrumb",
"(",
"name",
",",
"url",
",",
"options",
"=",
"{",
"}",
")",
"_breadcrumbs",
"<<",
"Loaf",
"::",
"Crumb",
".",
"new",
"(",
"name",
",",
"url",
",",
"options",
")",
"end"
] | Adds breadcrumbs inside view.
@param [String] name
the breadcrumb name
@param [Object] url
the breadcrumb url
@param [Hash] options
the breadcrumb options
@api public | [
"Adds",
"breadcrumbs",
"inside",
"view",
"."
] | 001dfad8361690051be76afdea11691b2aca8f14 | https://github.com/piotrmurach/loaf/blob/001dfad8361690051be76afdea11691b2aca8f14/lib/loaf/view_extensions.rb#L37-L39 | train |
piotrmurach/loaf | lib/loaf/view_extensions.rb | Loaf.ViewExtensions.breadcrumb_trail | def breadcrumb_trail(options = {})
return enum_for(:breadcrumb_trail) unless block_given?
valid?(options)
options = Loaf.configuration.to_hash.merge(options)
_breadcrumbs.each do |crumb|
name = title_for(crumb.name)
path = url_for(_expand_url(crumb.url))
current = curren... | ruby | def breadcrumb_trail(options = {})
return enum_for(:breadcrumb_trail) unless block_given?
valid?(options)
options = Loaf.configuration.to_hash.merge(options)
_breadcrumbs.each do |crumb|
name = title_for(crumb.name)
path = url_for(_expand_url(crumb.url))
current = curren... | [
"def",
"breadcrumb_trail",
"(",
"options",
"=",
"{",
"}",
")",
"return",
"enum_for",
"(",
":breadcrumb_trail",
")",
"unless",
"block_given?",
"valid?",
"(",
"options",
")",
"options",
"=",
"Loaf",
".",
"configuration",
".",
"to_hash",
".",
"merge",
"(",
"opt... | Renders breadcrumbs inside view.
@param [Hash] options
@api public | [
"Renders",
"breadcrumbs",
"inside",
"view",
"."
] | 001dfad8361690051be76afdea11691b2aca8f14 | https://github.com/piotrmurach/loaf/blob/001dfad8361690051be76afdea11691b2aca8f14/lib/loaf/view_extensions.rb#L47-L59 | train |
piotrmurach/loaf | lib/loaf/view_extensions.rb | Loaf.ViewExtensions._expand_url | def _expand_url(url)
case url
when String, Symbol
respond_to?(url) ? send(url) : url
when Proc
url.call(self)
else
url
end
end | ruby | def _expand_url(url)
case url
when String, Symbol
respond_to?(url) ? send(url) : url
when Proc
url.call(self)
else
url
end
end | [
"def",
"_expand_url",
"(",
"url",
")",
"case",
"url",
"when",
"String",
",",
"Symbol",
"respond_to?",
"(",
"url",
")",
"?",
"send",
"(",
"url",
")",
":",
"url",
"when",
"Proc",
"url",
".",
"call",
"(",
"self",
")",
"else",
"url",
"end",
"end"
] | Expand url in the current context of the view
@api private | [
"Expand",
"url",
"in",
"the",
"current",
"context",
"of",
"the",
"view"
] | 001dfad8361690051be76afdea11691b2aca8f14 | https://github.com/piotrmurach/loaf/blob/001dfad8361690051be76afdea11691b2aca8f14/lib/loaf/view_extensions.rb#L121-L130 | train |
piotrmurach/loaf | lib/loaf/translation.rb | Loaf.Translation.find_title | def find_title(title, options = {})
return title if title.nil? || title.empty?
options[:scope] ||= translation_scope
options[:default] = Array(options[:default])
options[:default] << title if options[:default].empty?
I18n.t(title.to_s, options)
end | ruby | def find_title(title, options = {})
return title if title.nil? || title.empty?
options[:scope] ||= translation_scope
options[:default] = Array(options[:default])
options[:default] << title if options[:default].empty?
I18n.t(title.to_s, options)
end | [
"def",
"find_title",
"(",
"title",
",",
"options",
"=",
"{",
"}",
")",
"return",
"title",
"if",
"title",
".",
"nil?",
"||",
"title",
".",
"empty?",
"options",
"[",
":scope",
"]",
"||=",
"translation_scope",
"options",
"[",
":default",
"]",
"=",
"Array",
... | Translate breadcrumb title
@param [String] :title
@param [Hash] options
@option options [String] :scope
The translation scope
@option options [String] :default
The default translation
@return [String]
@api public | [
"Translate",
"breadcrumb",
"title"
] | 001dfad8361690051be76afdea11691b2aca8f14 | https://github.com/piotrmurach/loaf/blob/001dfad8361690051be76afdea11691b2aca8f14/lib/loaf/translation.rb#L27-L34 | train |
puppetlabs/beaker-hostgenerator | lib/beaker-hostgenerator/parser.rb | BeakerHostGenerator.Parser.tokenize_layout | def tokenize_layout(layout_spec)
# Here we allow dashes in certain parts of the spec string
# i.e. "centos6-64m{hostname=foo-bar}-debian8-32"
# by first replacing all occurrences of - with | that exist within
# the braces {...}.
#
# So we'd end up with:
# "centos6-64m{hostnam... | ruby | def tokenize_layout(layout_spec)
# Here we allow dashes in certain parts of the spec string
# i.e. "centos6-64m{hostname=foo-bar}-debian8-32"
# by first replacing all occurrences of - with | that exist within
# the braces {...}.
#
# So we'd end up with:
# "centos6-64m{hostnam... | [
"def",
"tokenize_layout",
"(",
"layout_spec",
")",
"spec",
"=",
"String",
".",
"new",
"(",
"layout_spec",
")",
"within_braces",
"=",
"false",
"spec",
".",
"chars",
".",
"each_with_index",
"do",
"|",
"char",
",",
"index",
"|",
"case",
"char",
"when",
"'{'",... | Breaks apart the host input string into chunks suitable for processing
by the generator. Returns an array of substrings of the input spec string.
The input string is expected to be properly formatted using the dash `-`
character as a delimiter. Dashes may also be used within braces `{...}`,
which are used to defin... | [
"Breaks",
"apart",
"the",
"host",
"input",
"string",
"into",
"chunks",
"suitable",
"for",
"processing",
"by",
"the",
"generator",
".",
"Returns",
"an",
"array",
"of",
"substrings",
"of",
"the",
"input",
"spec",
"string",
"."
] | 276830215efedf00f133ddedc8b636c25d7510c4 | https://github.com/puppetlabs/beaker-hostgenerator/blob/276830215efedf00f133ddedc8b636c25d7510c4/lib/beaker-hostgenerator/parser.rb#L93-L125 | train |
puppetlabs/beaker-hostgenerator | lib/beaker-hostgenerator/parser.rb | BeakerHostGenerator.Parser.settings_string_to_map | def settings_string_to_map(host_settings)
stringscan = StringScanner.new(host_settings)
object = nil
object_depth = []
current_depth = 0
# This loop scans until the next delimiter character is found. When
# the next delimiter is recognized, there is enough context in the
# su... | ruby | def settings_string_to_map(host_settings)
stringscan = StringScanner.new(host_settings)
object = nil
object_depth = []
current_depth = 0
# This loop scans until the next delimiter character is found. When
# the next delimiter is recognized, there is enough context in the
# su... | [
"def",
"settings_string_to_map",
"(",
"host_settings",
")",
"stringscan",
"=",
"StringScanner",
".",
"new",
"(",
"host_settings",
")",
"object",
"=",
"nil",
"object_depth",
"=",
"[",
"]",
"current_depth",
"=",
"0",
"loop",
"do",
"blob",
"=",
"stringscan",
".",... | Transforms the arbitrary host settings map from a string representation
to a proper hash map data structure for merging into the host
configuration. Supports arbitrary nested hashes and arrays.
The string is expected to be of the form "{key1=value1,key2=[v2,v3],...}".
Nesting looks like "{key1={nested_key=nested_v... | [
"Transforms",
"the",
"arbitrary",
"host",
"settings",
"map",
"from",
"a",
"string",
"representation",
"to",
"a",
"proper",
"hash",
"map",
"data",
"structure",
"for",
"merging",
"into",
"the",
"host",
"configuration",
".",
"Supports",
"arbitrary",
"nested",
"hash... | 276830215efedf00f133ddedc8b636c25d7510c4 | https://github.com/puppetlabs/beaker-hostgenerator/blob/276830215efedf00f133ddedc8b636c25d7510c4/lib/beaker-hostgenerator/parser.rb#L211-L323 | train |
puppetlabs/beaker-hostgenerator | lib/beaker-hostgenerator/data.rb | BeakerHostGenerator.Data.get_platform_info | def get_platform_info(bhg_version, platform, hypervisor)
info = get_osinfo(bhg_version)[platform]
{}.deep_merge!(info[:general]).deep_merge!(info[hypervisor])
end | ruby | def get_platform_info(bhg_version, platform, hypervisor)
info = get_osinfo(bhg_version)[platform]
{}.deep_merge!(info[:general]).deep_merge!(info[hypervisor])
end | [
"def",
"get_platform_info",
"(",
"bhg_version",
",",
"platform",
",",
"hypervisor",
")",
"info",
"=",
"get_osinfo",
"(",
"bhg_version",
")",
"[",
"platform",
"]",
"{",
"}",
".",
"deep_merge!",
"(",
"info",
"[",
":general",
"]",
")",
".",
"deep_merge!",
"("... | Returns the fully parsed map of information of the specified OS platform
for the specified hypervisor. This map should be suitable for outputting
to the user as it will have the intermediate organizational branches of
the `get_osinfo` map removed.
This is intended to be the primary way to access OS info from hyper... | [
"Returns",
"the",
"fully",
"parsed",
"map",
"of",
"information",
"of",
"the",
"specified",
"OS",
"platform",
"for",
"the",
"specified",
"hypervisor",
".",
"This",
"map",
"should",
"be",
"suitable",
"for",
"outputting",
"to",
"the",
"user",
"as",
"it",
"will"... | 276830215efedf00f133ddedc8b636c25d7510c4 | https://github.com/puppetlabs/beaker-hostgenerator/blob/276830215efedf00f133ddedc8b636c25d7510c4/lib/beaker-hostgenerator/data.rb#L1768-L1771 | train |
puppetlabs/beaker-hostgenerator | lib/beaker-hostgenerator/abs_support.rb | BeakerHostGenerator.AbsSupport.extract_templates | def extract_templates(config)
templates_hosts = config['HOSTS'].values.group_by { |h| h['template'] }
templates_hosts.each do |template, hosts|
templates_hosts[template] = hosts.count
end
end | ruby | def extract_templates(config)
templates_hosts = config['HOSTS'].values.group_by { |h| h['template'] }
templates_hosts.each do |template, hosts|
templates_hosts[template] = hosts.count
end
end | [
"def",
"extract_templates",
"(",
"config",
")",
"templates_hosts",
"=",
"config",
"[",
"'HOSTS'",
"]",
".",
"values",
".",
"group_by",
"{",
"|",
"h",
"|",
"h",
"[",
"'template'",
"]",
"}",
"templates_hosts",
".",
"each",
"do",
"|",
"template",
",",
"host... | Given an existing, fully-specified host configuration, count the number of
hosts using each template, and return a map of template name to host count.
For example, given the following config (parts omitted for brevity):
{"HOSTS"=>
{"centos6-64-1"=>
{"template"=>"centos-6-x86_64", ...},
"redhat... | [
"Given",
"an",
"existing",
"fully",
"-",
"specified",
"host",
"configuration",
"count",
"the",
"number",
"of",
"hosts",
"using",
"each",
"template",
"and",
"return",
"a",
"map",
"of",
"template",
"name",
"to",
"host",
"count",
"."
] | 276830215efedf00f133ddedc8b636c25d7510c4 | https://github.com/puppetlabs/beaker-hostgenerator/blob/276830215efedf00f133ddedc8b636c25d7510c4/lib/beaker-hostgenerator/abs_support.rb#L23-L28 | train |
puppetlabs/beaker-hostgenerator | lib/beaker-hostgenerator/generator.rb | BeakerHostGenerator.Generator.generate | def generate(layout, options)
layout = prepare(layout)
tokens = tokenize_layout(layout)
config = {}.deep_merge(BASE_CONFIG)
nodeid = Hash.new(1)
ostype = nil
bhg_version = options[:osinfo_version] || 0
tokens.each do |token|
if is_ostype_token?(token, bhg_version)
... | ruby | def generate(layout, options)
layout = prepare(layout)
tokens = tokenize_layout(layout)
config = {}.deep_merge(BASE_CONFIG)
nodeid = Hash.new(1)
ostype = nil
bhg_version = options[:osinfo_version] || 0
tokens.each do |token|
if is_ostype_token?(token, bhg_version)
... | [
"def",
"generate",
"(",
"layout",
",",
"options",
")",
"layout",
"=",
"prepare",
"(",
"layout",
")",
"tokens",
"=",
"tokenize_layout",
"(",
"layout",
")",
"config",
"=",
"{",
"}",
".",
"deep_merge",
"(",
"BASE_CONFIG",
")",
"nodeid",
"=",
"Hash",
".",
... | Main host generation entry point, returns a Ruby map for the given host
specification and optional configuration.
@param layout [String] The raw hosts specification user input.
For example `"centos6-64m-redhat7-64a"`.
@param options [Hash] Global, optional configuration such as the default
... | [
"Main",
"host",
"generation",
"entry",
"point",
"returns",
"a",
"Ruby",
"map",
"for",
"the",
"given",
"host",
"specification",
"and",
"optional",
"configuration",
"."
] | 276830215efedf00f133ddedc8b636c25d7510c4 | https://github.com/puppetlabs/beaker-hostgenerator/blob/276830215efedf00f133ddedc8b636c25d7510c4/lib/beaker-hostgenerator/generator.rb#L22-L90 | train |
untra/polyglot | lib/jekyll/polyglot/patches/jekyll/site.rb | Jekyll.Site.coordinate_documents | def coordinate_documents(docs)
regex = document_url_regex
approved = {}
docs.each do |doc|
lang = doc.data['lang'] || @default_lang
url = doc.url.gsub(regex, '/')
doc.data['permalink'] = url
next if @file_langs[url] == @active_lang
next if @file_langs[url] == @d... | ruby | def coordinate_documents(docs)
regex = document_url_regex
approved = {}
docs.each do |doc|
lang = doc.data['lang'] || @default_lang
url = doc.url.gsub(regex, '/')
doc.data['permalink'] = url
next if @file_langs[url] == @active_lang
next if @file_langs[url] == @d... | [
"def",
"coordinate_documents",
"(",
"docs",
")",
"regex",
"=",
"document_url_regex",
"approved",
"=",
"{",
"}",
"docs",
".",
"each",
"do",
"|",
"doc",
"|",
"lang",
"=",
"doc",
".",
"data",
"[",
"'lang'",
"]",
"||",
"@default_lang",
"url",
"=",
"doc",
"... | assigns natural permalinks to documents and prioritizes documents with
active_lang languages over others | [
"assigns",
"natural",
"permalinks",
"to",
"documents",
"and",
"prioritizes",
"documents",
"with",
"active_lang",
"languages",
"over",
"others"
] | 23163148ba91daef1ce536b37a62c1ca67c05e84 | https://github.com/untra/polyglot/blob/23163148ba91daef1ce536b37a62c1ca67c05e84/lib/jekyll/polyglot/patches/jekyll/site.rb#L93-L106 | train |
untra/polyglot | lib/jekyll/polyglot/patches/jekyll/site.rb | Jekyll.Site.process_documents | def process_documents(docs)
return if @active_lang == @default_lang
url = config.fetch('url', false)
rel_regex = relative_url_regex
abs_regex = absolute_url_regex(url)
docs.each do |doc|
relativize_urls(doc, rel_regex)
if url
then relativize_absolute_urls(doc, abs_r... | ruby | def process_documents(docs)
return if @active_lang == @default_lang
url = config.fetch('url', false)
rel_regex = relative_url_regex
abs_regex = absolute_url_regex(url)
docs.each do |doc|
relativize_urls(doc, rel_regex)
if url
then relativize_absolute_urls(doc, abs_r... | [
"def",
"process_documents",
"(",
"docs",
")",
"return",
"if",
"@active_lang",
"==",
"@default_lang",
"url",
"=",
"config",
".",
"fetch",
"(",
"'url'",
",",
"false",
")",
"rel_regex",
"=",
"relative_url_regex",
"abs_regex",
"=",
"absolute_url_regex",
"(",
"url",
... | performs any necesarry operations on the documents before rendering them | [
"performs",
"any",
"necesarry",
"operations",
"on",
"the",
"documents",
"before",
"rendering",
"them"
] | 23163148ba91daef1ce536b37a62c1ca67c05e84 | https://github.com/untra/polyglot/blob/23163148ba91daef1ce536b37a62c1ca67c05e84/lib/jekyll/polyglot/patches/jekyll/site.rb#L109-L120 | train |
schneems/maildown | lib/maildown/ext/action_view.rb | ActionView.OptimizedFileSystemResolver.extract_handler_and_format_and_variant | def extract_handler_and_format_and_variant(*args)
if args.first.end_with?('md.erb')
path = args.shift
path = path.gsub(/\.md\.erb\z/, '.md+erb')
args.unshift(path)
end
return original_extract_handler_and_format_and_variant(*args)
end | ruby | def extract_handler_and_format_and_variant(*args)
if args.first.end_with?('md.erb')
path = args.shift
path = path.gsub(/\.md\.erb\z/, '.md+erb')
args.unshift(path)
end
return original_extract_handler_and_format_and_variant(*args)
end | [
"def",
"extract_handler_and_format_and_variant",
"(",
"*",
"args",
")",
"if",
"args",
".",
"first",
".",
"end_with?",
"(",
"'md.erb'",
")",
"path",
"=",
"args",
".",
"shift",
"path",
"=",
"path",
".",
"gsub",
"(",
"/",
"\\.",
"\\.",
"\\z",
"/",
",",
"'... | Different versions of rails have different
method signatures here, path is always first | [
"Different",
"versions",
"of",
"rails",
"have",
"different",
"method",
"signatures",
"here",
"path",
"is",
"always",
"first"
] | fc2220194dc2d32ef8313981503723a9657824ff | https://github.com/schneems/maildown/blob/fc2220194dc2d32ef8313981503723a9657824ff/lib/maildown/ext/action_view.rb#L13-L20 | train |
gocardless/gocardless-pro-ruby | lib/gocardless_pro/api_service.rb | GoCardlessPro.ApiService.make_request | def make_request(method, path, options = {})
raise ArgumentError, 'options must be a hash' unless options.is_a?(Hash)
options[:headers] ||= {}
options[:headers] = @headers.merge(options[:headers])
Request.new(@connection, method, @path_prefix + path, options).request
end | ruby | def make_request(method, path, options = {})
raise ArgumentError, 'options must be a hash' unless options.is_a?(Hash)
options[:headers] ||= {}
options[:headers] = @headers.merge(options[:headers])
Request.new(@connection, method, @path_prefix + path, options).request
end | [
"def",
"make_request",
"(",
"method",
",",
"path",
",",
"options",
"=",
"{",
"}",
")",
"raise",
"ArgumentError",
",",
"'options must be a hash'",
"unless",
"options",
".",
"is_a?",
"(",
"Hash",
")",
"options",
"[",
":headers",
"]",
"||=",
"{",
"}",
"option... | Initialize an APIService
@param url [String] the URL to make requests to
@param key [String] the API Key ID to use
@param secret [String] the API key secret to use
@param options [Hash] additional options to use when creating the service
Make a request to the API
@param method [Symbol] the method to use to make... | [
"Initialize",
"an",
"APIService"
] | 9473ecfa64eef2de6d5a404357c0db90de57efb1 | https://github.com/gocardless/gocardless-pro-ruby/blob/9473ecfa64eef2de6d5a404357c0db90de57efb1/lib/gocardless_pro/api_service.rb#L44-L49 | train |
gocardless/gocardless-pro-ruby | lib/gocardless_pro/paginator.rb | GoCardlessPro.Paginator.enumerator | def enumerator
response = get_initial_response
Enumerator.new do |yielder|
loop do
response.records.each { |item| yielder << item }
after_cursor = response.after
break if after_cursor.nil?
@options[:params] ||= {}
@options[:params] = @options[:para... | ruby | def enumerator
response = get_initial_response
Enumerator.new do |yielder|
loop do
response.records.each { |item| yielder << item }
after_cursor = response.after
break if after_cursor.nil?
@options[:params] ||= {}
@options[:params] = @options[:para... | [
"def",
"enumerator",
"response",
"=",
"get_initial_response",
"Enumerator",
".",
"new",
"do",
"|",
"yielder",
"|",
"loop",
"do",
"response",
".",
"records",
".",
"each",
"{",
"|",
"item",
"|",
"yielder",
"<<",
"item",
"}",
"after_cursor",
"=",
"response",
... | initialize a paginator
@param options [Hash]
@option options :service the service class to use to make requests to
@option options :options additional options to send with the requests
Get a lazy enumerable for listing data from the API | [
"initialize",
"a",
"paginator"
] | 9473ecfa64eef2de6d5a404357c0db90de57efb1 | https://github.com/gocardless/gocardless-pro-ruby/blob/9473ecfa64eef2de6d5a404357c0db90de57efb1/lib/gocardless_pro/paginator.rb#L14-L28 | train |
gocardless/gocardless-pro-ruby | lib/gocardless_pro/client.rb | GoCardlessPro.Client.custom_options | def custom_options(options)
return default_options if options.nil?
return default_options.merge(options) unless options[:default_headers]
opts = default_options.merge(options)
opts[:default_headers] = default_options[:default_headers].merge(options[:default_headers])
opts
end | ruby | def custom_options(options)
return default_options if options.nil?
return default_options.merge(options) unless options[:default_headers]
opts = default_options.merge(options)
opts[:default_headers] = default_options[:default_headers].merge(options[:default_headers])
opts
end | [
"def",
"custom_options",
"(",
"options",
")",
"return",
"default_options",
"if",
"options",
".",
"nil?",
"return",
"default_options",
".",
"merge",
"(",
"options",
")",
"unless",
"options",
"[",
":default_headers",
"]",
"opts",
"=",
"default_options",
".",
"merg... | Get customized options. | [
"Get",
"customized",
"options",
"."
] | 9473ecfa64eef2de6d5a404357c0db90de57efb1 | https://github.com/gocardless/gocardless-pro-ruby/blob/9473ecfa64eef2de6d5a404357c0db90de57efb1/lib/gocardless_pro/client.rb#L122-L131 | train |
ericqweinstein/ruumba | lib/ruumba/parser.rb | Ruumba.Parser.extract | def extract(contents)
file_text, matches = parse(contents)
extracted_ruby = +''
last_match = [0, 0]
matches.each do |start_index, end_index|
handle_region_before(start_index, last_match.last, file_text, extracted_ruby)
extracted_ruby << extract_match(file_text, start_index, en... | ruby | def extract(contents)
file_text, matches = parse(contents)
extracted_ruby = +''
last_match = [0, 0]
matches.each do |start_index, end_index|
handle_region_before(start_index, last_match.last, file_text, extracted_ruby)
extracted_ruby << extract_match(file_text, start_index, en... | [
"def",
"extract",
"(",
"contents",
")",
"file_text",
",",
"matches",
"=",
"parse",
"(",
"contents",
")",
"extracted_ruby",
"=",
"+",
"''",
"last_match",
"=",
"[",
"0",
",",
"0",
"]",
"matches",
".",
"each",
"do",
"|",
"start_index",
",",
"end_index",
"... | Extracts Ruby code from an ERB template.
@return [String] The extracted ruby code | [
"Extracts",
"Ruby",
"code",
"from",
"an",
"ERB",
"template",
"."
] | 9093819d011a2d9f6824d8f4c3789e34f4ff9b98 | https://github.com/ericqweinstein/ruumba/blob/9093819d011a2d9f6824d8f4c3789e34f4ff9b98/lib/ruumba/parser.rb#L13-L35 | train |
ericqweinstein/ruumba | lib/ruumba/rake_task.rb | Ruumba.RakeTask.run | def run
# Like RuboCop itself, we'll lazy load so the task
# doesn't substantially impact Rakefile load time.
require 'ruumba'
analyzer = Ruumba::Analyzer.new(@options)
puts 'Running Ruumba...'
exit(analyzer.run(@dir))
end | ruby | def run
# Like RuboCop itself, we'll lazy load so the task
# doesn't substantially impact Rakefile load time.
require 'ruumba'
analyzer = Ruumba::Analyzer.new(@options)
puts 'Running Ruumba...'
exit(analyzer.run(@dir))
end | [
"def",
"run",
"require",
"'ruumba'",
"analyzer",
"=",
"Ruumba",
"::",
"Analyzer",
".",
"new",
"(",
"@options",
")",
"puts",
"'Running Ruumba...'",
"exit",
"(",
"analyzer",
".",
"run",
"(",
"@dir",
")",
")",
"end"
] | Executes the custom Rake task.
@private | [
"Executes",
"the",
"custom",
"Rake",
"task",
"."
] | 9093819d011a2d9f6824d8f4c3789e34f4ff9b98 | https://github.com/ericqweinstein/ruumba/blob/9093819d011a2d9f6824d8f4c3789e34f4ff9b98/lib/ruumba/rake_task.rb#L31-L40 | train |
ericqweinstein/ruumba | lib/ruumba/analyzer.rb | Ruumba.Analyzer.run | def run(files_or_dirs = ARGV)
if options[:tmp_folder]
analyze(File.expand_path(options[:tmp_folder]), files_or_dirs)
else
Dir.mktmpdir do |dir|
analyze(dir, files_or_dirs)
end
end
end | ruby | def run(files_or_dirs = ARGV)
if options[:tmp_folder]
analyze(File.expand_path(options[:tmp_folder]), files_or_dirs)
else
Dir.mktmpdir do |dir|
analyze(dir, files_or_dirs)
end
end
end | [
"def",
"run",
"(",
"files_or_dirs",
"=",
"ARGV",
")",
"if",
"options",
"[",
":tmp_folder",
"]",
"analyze",
"(",
"File",
".",
"expand_path",
"(",
"options",
"[",
":tmp_folder",
"]",
")",
",",
"files_or_dirs",
")",
"else",
"Dir",
".",
"mktmpdir",
"do",
"|"... | Performs static analysis on the provided directory.
@param [Array<String>] dir The directories / files to analyze. | [
"Performs",
"static",
"analysis",
"on",
"the",
"provided",
"directory",
"."
] | 9093819d011a2d9f6824d8f4c3789e34f4ff9b98 | https://github.com/ericqweinstein/ruumba/blob/9093819d011a2d9f6824d8f4c3789e34f4ff9b98/lib/ruumba/analyzer.rb#L24-L32 | train |
mattbrictson/chandler | lib/chandler/logger.rb | Chandler.Logger.error | def error(message)
message = message.red unless message.color?
puts(stderr, message)
end | ruby | def error(message)
message = message.red unless message.color?
puts(stderr, message)
end | [
"def",
"error",
"(",
"message",
")",
"message",
"=",
"message",
".",
"red",
"unless",
"message",
".",
"color?",
"puts",
"(",
"stderr",
",",
"message",
")",
"end"
] | Logs a message to stderr. Unless otherwise specified, the message will
be printed in red. | [
"Logs",
"a",
"message",
"to",
"stderr",
".",
"Unless",
"otherwise",
"specified",
"the",
"message",
"will",
"be",
"printed",
"in",
"red",
"."
] | bb6d38ea19aa8d7a8f175384ac53f2dd1ffc620a | https://github.com/mattbrictson/chandler/blob/bb6d38ea19aa8d7a8f175384ac53f2dd1ffc620a/lib/chandler/logger.rb#L19-L22 | train |
Vantiv/litle-sdk-for-ruby | lib/LitleTransaction.rb | LitleOnline.LitleTransaction.giftCardAuth_reversal | def giftCardAuth_reversal(options)
transaction = GiftCardAuthReversal.new
transaction.litleTxnId = options['litleTxnId']
transaction.card = GiftCardCardType.from_hash(options,'card')
transaction.originalRefCode = options['originalRefCode']
transaction.originalAmount = options['originalAmou... | ruby | def giftCardAuth_reversal(options)
transaction = GiftCardAuthReversal.new
transaction.litleTxnId = options['litleTxnId']
transaction.card = GiftCardCardType.from_hash(options,'card')
transaction.originalRefCode = options['originalRefCode']
transaction.originalAmount = options['originalAmou... | [
"def",
"giftCardAuth_reversal",
"(",
"options",
")",
"transaction",
"=",
"GiftCardAuthReversal",
".",
"new",
"transaction",
".",
"litleTxnId",
"=",
"options",
"[",
"'litleTxnId'",
"]",
"transaction",
".",
"card",
"=",
"GiftCardCardType",
".",
"from_hash",
"(",
"op... | XML 11.0 | [
"XML",
"11",
".",
"0"
] | a05590c5cbab688e6ae29cf38fea0eb44aa487e2 | https://github.com/Vantiv/litle-sdk-for-ruby/blob/a05590c5cbab688e6ae29cf38fea0eb44aa487e2/lib/LitleTransaction.rb#L185-L195 | train |
Vantiv/litle-sdk-for-ruby | lib/LitleTransaction.rb | LitleOnline.LitleTransaction.fast_access_funding | def fast_access_funding(options)
transaction = FastAccessFunding.new
transaction.reportGroup = get_report_group(options)
transaction.transactionId = options['id']
transaction.customerId = options['customerId']
transaction.fundingSubmerchantId = options['fundingSubmerchantId']
tra... | ruby | def fast_access_funding(options)
transaction = FastAccessFunding.new
transaction.reportGroup = get_report_group(options)
transaction.transactionId = options['id']
transaction.customerId = options['customerId']
transaction.fundingSubmerchantId = options['fundingSubmerchantId']
tra... | [
"def",
"fast_access_funding",
"(",
"options",
")",
"transaction",
"=",
"FastAccessFunding",
".",
"new",
"transaction",
".",
"reportGroup",
"=",
"get_report_group",
"(",
"options",
")",
"transaction",
".",
"transactionId",
"=",
"options",
"[",
"'id'",
"]",
"transac... | 11.4 Begin | [
"11",
".",
"4",
"Begin"
] | a05590c5cbab688e6ae29cf38fea0eb44aa487e2 | https://github.com/Vantiv/litle-sdk-for-ruby/blob/a05590c5cbab688e6ae29cf38fea0eb44aa487e2/lib/LitleTransaction.rb#L659-L675 | train |
Vantiv/litle-sdk-for-ruby | lib/LitleRequest.rb | LitleOnline.LitleRequest.finish_request | def finish_request
File.open(@path_to_request, 'w') do |f|
#jam dat header in there
f.puts(build_request_header())
#read into the request file from the batches file
File.foreach(@path_to_batches) do |li|
f.puts li
end
#finally, let's poot in a header, for... | ruby | def finish_request
File.open(@path_to_request, 'w') do |f|
#jam dat header in there
f.puts(build_request_header())
#read into the request file from the batches file
File.foreach(@path_to_batches) do |li|
f.puts li
end
#finally, let's poot in a header, for... | [
"def",
"finish_request",
"File",
".",
"open",
"(",
"@path_to_request",
",",
"'w'",
")",
"do",
"|",
"f",
"|",
"f",
".",
"puts",
"(",
"build_request_header",
"(",
")",
")",
"File",
".",
"foreach",
"(",
"@path_to_batches",
")",
"do",
"|",
"li",
"|",
"f",
... | Called when you wish to finish adding batches to your request, this method rewrites the aggregate
batch file to the final LitleRequest xml doc with the appropos LitleRequest tags. | [
"Called",
"when",
"you",
"wish",
"to",
"finish",
"adding",
"batches",
"to",
"your",
"request",
"this",
"method",
"rewrites",
"the",
"aggregate",
"batch",
"file",
"to",
"the",
"final",
"LitleRequest",
"xml",
"doc",
"with",
"the",
"appropos",
"LitleRequest",
"ta... | a05590c5cbab688e6ae29cf38fea0eb44aa487e2 | https://github.com/Vantiv/litle-sdk-for-ruby/blob/a05590c5cbab688e6ae29cf38fea0eb44aa487e2/lib/LitleRequest.rb#L440-L457 | train |
duckinator/inq | lib/inq/cli.rb | Inq.CLI.parse | def parse(argv)
parser, options = parse_main(argv)
# Options that are mutually-exclusive with everything else.
options = {:help => true} if options[:help]
options = {:version => true} if options[:version]
validate_options!(options)
@options = options
@help_text = parser.t... | ruby | def parse(argv)
parser, options = parse_main(argv)
# Options that are mutually-exclusive with everything else.
options = {:help => true} if options[:help]
options = {:version => true} if options[:version]
validate_options!(options)
@options = options
@help_text = parser.t... | [
"def",
"parse",
"(",
"argv",
")",
"parser",
",",
"options",
"=",
"parse_main",
"(",
"argv",
")",
"options",
"=",
"{",
":help",
"=>",
"true",
"}",
"if",
"options",
"[",
":help",
"]",
"options",
"=",
"{",
":version",
"=>",
"true",
"}",
"if",
"options",... | Parses an Array of command-line arguments into an equivalent Hash.
The results of this can be used to control the behavior of the rest
of the library.
@params argv [Array] An array of command-line arguments, e.g. +ARGV+.
@return [Hash] A Hash containing data used to control Inq's behavior. | [
"Parses",
"an",
"Array",
"of",
"command",
"-",
"line",
"arguments",
"into",
"an",
"equivalent",
"Hash",
"."
] | e23a250aca4a62702cb5f3ee87cf26012e5a8344 | https://github.com/duckinator/inq/blob/e23a250aca4a62702cb5f3ee87cf26012e5a8344/lib/inq/cli.rb#L34-L47 | train |
duckinator/inq | lib/inq/config.rb | Inq.Config.load_site_configs | def load_site_configs(*files)
# Allows both:
# load_site_configs('foo', 'bar')
# load_site_configs(['foo', bar'])
# but not:
# load_site_configs(['foo'], 'bar')
files = files[0] if files.length == 1 && files[0].is_a?(Array)
load_files(*files)
end | ruby | def load_site_configs(*files)
# Allows both:
# load_site_configs('foo', 'bar')
# load_site_configs(['foo', bar'])
# but not:
# load_site_configs(['foo'], 'bar')
files = files[0] if files.length == 1 && files[0].is_a?(Array)
load_files(*files)
end | [
"def",
"load_site_configs",
"(",
"*",
"files",
")",
"files",
"=",
"files",
"[",
"0",
"]",
"if",
"files",
".",
"length",
"==",
"1",
"&&",
"files",
"[",
"0",
"]",
".",
"is_a?",
"(",
"Array",
")",
"load_files",
"(",
"*",
"files",
")",
"end"
] | Load the config files as specified via +files+.
@param files [Array<String>] The path(s) for config files.
@return [Config] The config hash. (+self+) | [
"Load",
"the",
"config",
"files",
"as",
"specified",
"via",
"+",
"files",
"+",
"."
] | e23a250aca4a62702cb5f3ee87cf26012e5a8344 | https://github.com/duckinator/inq/blob/e23a250aca4a62702cb5f3ee87cf26012e5a8344/lib/inq/config.rb#L47-L56 | train |
duckinator/inq | lib/inq/config.rb | Inq.Config.load | def load(*configs)
configs.each do |config|
config.each do |k, v|
if self[k] && self[k].is_a?(Array)
self[k] += v
else
self[k] = v
end
end
end
self
end | ruby | def load(*configs)
configs.each do |config|
config.each do |k, v|
if self[k] && self[k].is_a?(Array)
self[k] += v
else
self[k] = v
end
end
end
self
end | [
"def",
"load",
"(",
"*",
"configs",
")",
"configs",
".",
"each",
"do",
"|",
"config",
"|",
"config",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"if",
"self",
"[",
"k",
"]",
"&&",
"self",
"[",
"k",
"]",
".",
"is_a?",
"(",
"Array",
")",
"self"... | Take a collection of config hashes and cascade them, meaning values
in later ones override values in earlier ones.
E.g., this results in +{'a'=>'x', 'c'=>'d'}+:
load({'a'=>'b'}, {'c'=>'d'}, {'a'=>'x'})
And this results in +{'a'=>['b', 'c']}+:
load({'a'=>['b']}, {'a'=>['c']})
@param [Array<Hash>] The co... | [
"Take",
"a",
"collection",
"of",
"config",
"hashes",
"and",
"cascade",
"them",
"meaning",
"values",
"in",
"later",
"ones",
"override",
"values",
"in",
"earlier",
"ones",
"."
] | e23a250aca4a62702cb5f3ee87cf26012e5a8344 | https://github.com/duckinator/inq/blob/e23a250aca4a62702cb5f3ee87cf26012e5a8344/lib/inq/config.rb#L83-L95 | train |
duckinator/inq | lib/inq/config.rb | Inq.Config.load_env | def load_env
Inq::Text.puts "Using configuration from environment variables."
gh_token = ENV["INQ_GITHUB_TOKEN"] || ENV["HOWIS_GITHUB_TOKEN"]
gh_username = ENV["INQ_GITHUB_USERNAME"] || ENV["HOWIS_GITHUB_USERNAME"]
raise "INQ_GITHUB_TOKEN environment variable is not set" \
unless gh_to... | ruby | def load_env
Inq::Text.puts "Using configuration from environment variables."
gh_token = ENV["INQ_GITHUB_TOKEN"] || ENV["HOWIS_GITHUB_TOKEN"]
gh_username = ENV["INQ_GITHUB_USERNAME"] || ENV["HOWIS_GITHUB_USERNAME"]
raise "INQ_GITHUB_TOKEN environment variable is not set" \
unless gh_to... | [
"def",
"load_env",
"Inq",
"::",
"Text",
".",
"puts",
"\"Using configuration from environment variables.\"",
"gh_token",
"=",
"ENV",
"[",
"\"INQ_GITHUB_TOKEN\"",
"]",
"||",
"ENV",
"[",
"\"HOWIS_GITHUB_TOKEN\"",
"]",
"gh_username",
"=",
"ENV",
"[",
"\"INQ_GITHUB_USERNAME\... | Load config info from environment variables.
Supported environment variables:
- INQ_GITHUB_TOKEN: a GitHub authentication token.
- INQ_GITHUB_USERNAME: the GitHub username corresponding to the token.
@return [Config] The resulting configuration. | [
"Load",
"config",
"info",
"from",
"environment",
"variables",
"."
] | e23a250aca4a62702cb5f3ee87cf26012e5a8344 | https://github.com/duckinator/inq/blob/e23a250aca4a62702cb5f3ee87cf26012e5a8344/lib/inq/config.rb#L104-L121 | train |
duckinator/inq | lib/inq/date_time_helpers.rb | Inq.DateTimeHelpers.date_le | def date_le(left, right)
left = str_to_dt(left)
right = str_to_dt(right)
left <= right
end | ruby | def date_le(left, right)
left = str_to_dt(left)
right = str_to_dt(right)
left <= right
end | [
"def",
"date_le",
"(",
"left",
",",
"right",
")",
"left",
"=",
"str_to_dt",
"(",
"left",
")",
"right",
"=",
"str_to_dt",
"(",
"right",
")",
"left",
"<=",
"right",
"end"
] | Check if +left+ is less than or equal to +right+, where both are string
representations of a date.
@param left [String] A string representation of a date.
@param right [String] A string representation of a date.
@return [Boolean] True if +left+ is less-than-or-equal to +right+,
otherwise false. | [
"Check",
"if",
"+",
"left",
"+",
"is",
"less",
"than",
"or",
"equal",
"to",
"+",
"right",
"+",
"where",
"both",
"are",
"string",
"representations",
"of",
"a",
"date",
"."
] | e23a250aca4a62702cb5f3ee87cf26012e5a8344 | https://github.com/duckinator/inq/blob/e23a250aca4a62702cb5f3ee87cf26012e5a8344/lib/inq/date_time_helpers.rb#L17-L22 | train |
duckinator/inq | lib/inq/date_time_helpers.rb | Inq.DateTimeHelpers.date_ge | def date_ge(left, right)
left = str_to_dt(left)
right = str_to_dt(right)
left >= right
end | ruby | def date_ge(left, right)
left = str_to_dt(left)
right = str_to_dt(right)
left >= right
end | [
"def",
"date_ge",
"(",
"left",
",",
"right",
")",
"left",
"=",
"str_to_dt",
"(",
"left",
")",
"right",
"=",
"str_to_dt",
"(",
"right",
")",
"left",
">=",
"right",
"end"
] | Check if +left+ is greater than or equal to +right+, where both are string
representations of a date.
@param left [String] A string representation of a date.
@param right [String] A string representation of a date.
@return [Boolean] True if +left+ is greater-than-or-equal to +right+,
otherwise false. | [
"Check",
"if",
"+",
"left",
"+",
"is",
"greater",
"than",
"or",
"equal",
"to",
"+",
"right",
"+",
"where",
"both",
"are",
"string",
"representations",
"of",
"a",
"date",
"."
] | e23a250aca4a62702cb5f3ee87cf26012e5a8344 | https://github.com/duckinator/inq/blob/e23a250aca4a62702cb5f3ee87cf26012e5a8344/lib/inq/date_time_helpers.rb#L31-L36 | train |
duckinator/inq | lib/inq/report_collection.rb | Inq.ReportCollection.metadata | def metadata(repository)
end_date = DateTime.strptime(@date, "%Y-%m-%d")
friendly_end_date = end_date.strftime("%B %d, %y")
{
sanitized_repository: repository.tr("/", "-"),
repository: repository,
date: end_date,
friendly_date: friendly_end_date,
}
end | ruby | def metadata(repository)
end_date = DateTime.strptime(@date, "%Y-%m-%d")
friendly_end_date = end_date.strftime("%B %d, %y")
{
sanitized_repository: repository.tr("/", "-"),
repository: repository,
date: end_date,
friendly_date: friendly_end_date,
}
end | [
"def",
"metadata",
"(",
"repository",
")",
"end_date",
"=",
"DateTime",
".",
"strptime",
"(",
"@date",
",",
"\"%Y-%m-%d\"",
")",
"friendly_end_date",
"=",
"end_date",
".",
"strftime",
"(",
"\"%B %d, %y\"",
")",
"{",
"sanitized_repository",
":",
"repository",
"."... | Generates the metadata for the collection of Reports. | [
"Generates",
"the",
"metadata",
"for",
"the",
"collection",
"of",
"Reports",
"."
] | e23a250aca4a62702cb5f3ee87cf26012e5a8344 | https://github.com/duckinator/inq/blob/e23a250aca4a62702cb5f3ee87cf26012e5a8344/lib/inq/report_collection.rb#L28-L38 | train |
duckinator/inq | lib/inq/report_collection.rb | Inq.ReportCollection.to_h | def to_h
results = {}
defaults = @config["default_reports"] || {}
@config["repositories"].map { |repo_config|
repo = repo_config["repository"]
config = config_for(repo)
config["reports"].map { |format, report_config|
# Sometimes report_data has unused keys, which ge... | ruby | def to_h
results = {}
defaults = @config["default_reports"] || {}
@config["repositories"].map { |repo_config|
repo = repo_config["repository"]
config = config_for(repo)
config["reports"].map { |format, report_config|
# Sometimes report_data has unused keys, which ge... | [
"def",
"to_h",
"results",
"=",
"{",
"}",
"defaults",
"=",
"@config",
"[",
"\"default_reports\"",
"]",
"||",
"{",
"}",
"@config",
"[",
"\"repositories\"",
"]",
".",
"map",
"{",
"|",
"repo_config",
"|",
"repo",
"=",
"repo_config",
"[",
"\"repository\"",
"]",... | Converts a ReportCollection to a Hash.
Also good for giving programmers nightmares, I suspect. | [
"Converts",
"a",
"ReportCollection",
"to",
"a",
"Hash",
"."
] | e23a250aca4a62702cb5f3ee87cf26012e5a8344 | https://github.com/duckinator/inq/blob/e23a250aca4a62702cb5f3ee87cf26012e5a8344/lib/inq/report_collection.rb#L66-L99 | train |
duckinator/inq | lib/inq/report_collection.rb | Inq.ReportCollection.save_all | def save_all
reports = to_h
reports.each do |file, report|
File.write(file, report)
end
reports.keys
end | ruby | def save_all
reports = to_h
reports.each do |file, report|
File.write(file, report)
end
reports.keys
end | [
"def",
"save_all",
"reports",
"=",
"to_h",
"reports",
".",
"each",
"do",
"|",
"file",
",",
"report",
"|",
"File",
".",
"write",
"(",
"file",
",",
"report",
")",
"end",
"reports",
".",
"keys",
"end"
] | Save all of the reports to the corresponding files.
@return [Array<String>] An array of file paths. | [
"Save",
"all",
"of",
"the",
"reports",
"to",
"the",
"corresponding",
"files",
"."
] | e23a250aca4a62702cb5f3ee87cf26012e5a8344 | https://github.com/duckinator/inq/blob/e23a250aca4a62702cb5f3ee87cf26012e5a8344/lib/inq/report_collection.rb#L104-L111 | train |
rails/sprockets-rails | lib/sprockets/railtie.rb | Rails.Application.asset_precompiled? | def asset_precompiled?(logical_path)
if precompiled_assets.include?(logical_path)
true
elsif !config.cache_classes
# Check to see if precompile list has been updated
precompiled_assets(true).include?(logical_path)
else
false
end
end | ruby | def asset_precompiled?(logical_path)
if precompiled_assets.include?(logical_path)
true
elsif !config.cache_classes
# Check to see if precompile list has been updated
precompiled_assets(true).include?(logical_path)
else
false
end
end | [
"def",
"asset_precompiled?",
"(",
"logical_path",
")",
"if",
"precompiled_assets",
".",
"include?",
"(",
"logical_path",
")",
"true",
"elsif",
"!",
"config",
".",
"cache_classes",
"precompiled_assets",
"(",
"true",
")",
".",
"include?",
"(",
"logical_path",
")",
... | Called from asset helpers to alert you if you reference an asset URL that
isn't precompiled and hence won't be available in production. | [
"Called",
"from",
"asset",
"helpers",
"to",
"alert",
"you",
"if",
"you",
"reference",
"an",
"asset",
"URL",
"that",
"isn",
"t",
"precompiled",
"and",
"hence",
"won",
"t",
"be",
"available",
"in",
"production",
"."
] | bbfcefda3240d924260e3530f896be94cdf23034 | https://github.com/rails/sprockets-rails/blob/bbfcefda3240d924260e3530f896be94cdf23034/lib/sprockets/railtie.rb#L34-L43 | train |
rails/sprockets-rails | lib/sprockets/railtie.rb | Rails.Application.precompiled_assets | def precompiled_assets(clear_cache = false)
@precompiled_assets = nil if clear_cache
@precompiled_assets ||= assets_manifest.find(config.assets.precompile).map(&:logical_path).to_set
end | ruby | def precompiled_assets(clear_cache = false)
@precompiled_assets = nil if clear_cache
@precompiled_assets ||= assets_manifest.find(config.assets.precompile).map(&:logical_path).to_set
end | [
"def",
"precompiled_assets",
"(",
"clear_cache",
"=",
"false",
")",
"@precompiled_assets",
"=",
"nil",
"if",
"clear_cache",
"@precompiled_assets",
"||=",
"assets_manifest",
".",
"find",
"(",
"config",
".",
"assets",
".",
"precompile",
")",
".",
"map",
"(",
"&",
... | Lazy-load the precompile list so we don't cause asset compilation at app
boot time, but ensure we cache the list so we don't recompute it for each
request or test case. | [
"Lazy",
"-",
"load",
"the",
"precompile",
"list",
"so",
"we",
"don",
"t",
"cause",
"asset",
"compilation",
"at",
"app",
"boot",
"time",
"but",
"ensure",
"we",
"cache",
"the",
"list",
"so",
"we",
"don",
"t",
"recompute",
"it",
"for",
"each",
"request",
... | bbfcefda3240d924260e3530f896be94cdf23034 | https://github.com/rails/sprockets-rails/blob/bbfcefda3240d924260e3530f896be94cdf23034/lib/sprockets/railtie.rb#L48-L51 | train |
guilleiguaran/fakeredis | lib/fakeredis/sorted_set_argument_handler.rb | FakeRedis.SortedSetArgumentHandler.handle | def handle(item)
case item
when "WEIGHTS"
self.type = :weights
self.weights = []
when "AGGREGATE"
self.type = :aggregate
when nil
# This should never be called, raise a syntax error if we manage to hit it
raise(Redis::CommandError, "ERR syntax error")
... | ruby | def handle(item)
case item
when "WEIGHTS"
self.type = :weights
self.weights = []
when "AGGREGATE"
self.type = :aggregate
when nil
# This should never be called, raise a syntax error if we manage to hit it
raise(Redis::CommandError, "ERR syntax error")
... | [
"def",
"handle",
"(",
"item",
")",
"case",
"item",
"when",
"\"WEIGHTS\"",
"self",
".",
"type",
"=",
":weights",
"self",
".",
"weights",
"=",
"[",
"]",
"when",
"\"AGGREGATE\"",
"self",
".",
"type",
"=",
":aggregate",
"when",
"nil",
"raise",
"(",
"Redis",
... | Decides how to handle an item, depending on where we are in the arguments | [
"Decides",
"how",
"to",
"handle",
"an",
"item",
"depending",
"on",
"where",
"we",
"are",
"in",
"the",
"arguments"
] | df7b07f55e3b194ccb7208ed143711b2426d78c4 | https://github.com/guilleiguaran/fakeredis/blob/df7b07f55e3b194ccb7208ed143711b2426d78c4/lib/fakeredis/sorted_set_argument_handler.rb#L46-L60 | train |
guilleiguaran/fakeredis | lib/fakeredis/sorted_set_store.rb | FakeRedis.SortedSetStore.computed_values | def computed_values
unless defined?(@computed_values) && @computed_values
# Do nothing if all weights are 1, as n * 1 is n
@computed_values = hashes if weights.all? {|weight| weight == 1 }
# Otherwise, multiply the values in each hash by that hash's weighting
@computed_values ||= h... | ruby | def computed_values
unless defined?(@computed_values) && @computed_values
# Do nothing if all weights are 1, as n * 1 is n
@computed_values = hashes if weights.all? {|weight| weight == 1 }
# Otherwise, multiply the values in each hash by that hash's weighting
@computed_values ||= h... | [
"def",
"computed_values",
"unless",
"defined?",
"(",
"@computed_values",
")",
"&&",
"@computed_values",
"@computed_values",
"=",
"hashes",
"if",
"weights",
".",
"all?",
"{",
"|",
"weight",
"|",
"weight",
"==",
"1",
"}",
"@computed_values",
"||=",
"hashes",
".",
... | Apply the weightings to the hashes | [
"Apply",
"the",
"weightings",
"to",
"the",
"hashes"
] | df7b07f55e3b194ccb7208ed143711b2426d78c4 | https://github.com/guilleiguaran/fakeredis/blob/df7b07f55e3b194ccb7208ed143711b2426d78c4/lib/fakeredis/sorted_set_store.rb#L27-L38 | train |
guilleiguaran/fakeredis | lib/fakeredis/zset.rb | FakeRedis.ZSet._floatify | def _floatify(str, increment = true)
if (( inf = str.to_s.match(/^([+-])?inf/i) ))
(inf[1] == "-" ? -1.0 : 1.0) / 0.0
elsif (( number = str.to_s.match(/^\((\d+)/i) ))
number[1].to_i + (increment ? 1 : -1)
else
Float str.to_s
end
rescue ArgumentError
raise Redis:... | ruby | def _floatify(str, increment = true)
if (( inf = str.to_s.match(/^([+-])?inf/i) ))
(inf[1] == "-" ? -1.0 : 1.0) / 0.0
elsif (( number = str.to_s.match(/^\((\d+)/i) ))
number[1].to_i + (increment ? 1 : -1)
else
Float str.to_s
end
rescue ArgumentError
raise Redis:... | [
"def",
"_floatify",
"(",
"str",
",",
"increment",
"=",
"true",
")",
"if",
"(",
"(",
"inf",
"=",
"str",
".",
"to_s",
".",
"match",
"(",
"/",
"/i",
")",
")",
")",
"(",
"inf",
"[",
"1",
"]",
"==",
"\"-\"",
"?",
"-",
"1.0",
":",
"1.0",
")",
"/"... | Originally lifted from redis-rb | [
"Originally",
"lifted",
"from",
"redis",
"-",
"rb"
] | df7b07f55e3b194ccb7208ed143711b2426d78c4 | https://github.com/guilleiguaran/fakeredis/blob/df7b07f55e3b194ccb7208ed143711b2426d78c4/lib/fakeredis/zset.rb#L26-L36 | train |
cequel/cequel | lib/cequel/uuids.rb | Cequel.Uuids.uuid | def uuid(value = nil)
if value.nil?
timeuuid_generator.now
elsif value.is_a?(Time)
timeuuid_generator.at(value)
elsif value.is_a?(DateTime)
timeuuid_generator.at(Time.at(value.to_f))
else
Type::Timeuuid.instance.cast(value)
end
end | ruby | def uuid(value = nil)
if value.nil?
timeuuid_generator.now
elsif value.is_a?(Time)
timeuuid_generator.at(value)
elsif value.is_a?(DateTime)
timeuuid_generator.at(Time.at(value.to_f))
else
Type::Timeuuid.instance.cast(value)
end
end | [
"def",
"uuid",
"(",
"value",
"=",
"nil",
")",
"if",
"value",
".",
"nil?",
"timeuuid_generator",
".",
"now",
"elsif",
"value",
".",
"is_a?",
"(",
"Time",
")",
"timeuuid_generator",
".",
"at",
"(",
"value",
")",
"elsif",
"value",
".",
"is_a?",
"(",
"Date... | Create a UUID
@param value [Time,String,Integer] timestamp to assign to the UUID, or
numeric or string representation of the UUID
@return a UUID appropriate for use with Cequel | [
"Create",
"a",
"UUID"
] | 35e90199470481795f0a6e1604767d65a0f2c604 | https://github.com/cequel/cequel/blob/35e90199470481795f0a6e1604767d65a0f2c604/lib/cequel/uuids.rb#L18-L28 | train |
infused/dbf | lib/dbf/table.rb | DBF.Table.find | def find(command, options = {}, &block)
case command
when Integer
record(command)
when Array
command.map { |i| record(i) }
when :all
find_all(options, &block)
when :first
find_first(options)
end
end | ruby | def find(command, options = {}, &block)
case command
when Integer
record(command)
when Array
command.map { |i| record(i) }
when :all
find_all(options, &block)
when :first
find_first(options)
end
end | [
"def",
"find",
"(",
"command",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"case",
"command",
"when",
"Integer",
"record",
"(",
"command",
")",
"when",
"Array",
"command",
".",
"map",
"{",
"|",
"i",
"|",
"record",
"(",
"i",
")",
"}",
"... | Find records using a simple ActiveRecord-like syntax.
Examples:
table = DBF::Table.new 'mydata.dbf'
# Find record number 5
table.find(5)
# Find all records for Keith Morrison
table.find :all, first_name: "Keith", last_name: "Morrison"
# Find first record
table.find :first, first_name: "Keith"
... | [
"Find",
"records",
"using",
"a",
"simple",
"ActiveRecord",
"-",
"like",
"syntax",
"."
] | 6f60cfe100e854057f112e84fd32656f0ed7f84b | https://github.com/infused/dbf/blob/6f60cfe100e854057f112e84fd32656f0ed7f84b/lib/dbf/table.rb#L148-L159 | train |
infused/dbf | lib/dbf/table.rb | DBF.Table.record | def record(index)
seek_to_record(index)
return nil if deleted_record?
DBF::Record.new(@data.read(record_length), columns, version, @memo)
end | ruby | def record(index)
seek_to_record(index)
return nil if deleted_record?
DBF::Record.new(@data.read(record_length), columns, version, @memo)
end | [
"def",
"record",
"(",
"index",
")",
"seek_to_record",
"(",
"index",
")",
"return",
"nil",
"if",
"deleted_record?",
"DBF",
"::",
"Record",
".",
"new",
"(",
"@data",
".",
"read",
"(",
"record_length",
")",
",",
"columns",
",",
"version",
",",
"@memo",
")",... | Retrieve a record by index number.
The record will be nil if it has been deleted, but not yet pruned from
the database.
@param [Integer] index
@return [DBF::Record, NilClass] | [
"Retrieve",
"a",
"record",
"by",
"index",
"number",
".",
"The",
"record",
"will",
"be",
"nil",
"if",
"it",
"has",
"been",
"deleted",
"but",
"not",
"yet",
"pruned",
"from",
"the",
"database",
"."
] | 6f60cfe100e854057f112e84fd32656f0ed7f84b | https://github.com/infused/dbf/blob/6f60cfe100e854057f112e84fd32656f0ed7f84b/lib/dbf/table.rb#L177-L182 | train |
infused/dbf | lib/dbf/table.rb | DBF.Table.to_csv | def to_csv(path = nil)
out_io = path ? File.open(path, 'w') : $stdout
csv = CSV.new(out_io, force_quotes: true)
csv << column_names
each { |record| csv << record.to_a }
end | ruby | def to_csv(path = nil)
out_io = path ? File.open(path, 'w') : $stdout
csv = CSV.new(out_io, force_quotes: true)
csv << column_names
each { |record| csv << record.to_a }
end | [
"def",
"to_csv",
"(",
"path",
"=",
"nil",
")",
"out_io",
"=",
"path",
"?",
"File",
".",
"open",
"(",
"path",
",",
"'w'",
")",
":",
"$stdout",
"csv",
"=",
"CSV",
".",
"new",
"(",
"out_io",
",",
"force_quotes",
":",
"true",
")",
"csv",
"<<",
"colum... | Dumps all records to a CSV file. If no filename is given then CSV is
output to STDOUT.
@param [optional String] path Defaults to STDOUT | [
"Dumps",
"all",
"records",
"to",
"a",
"CSV",
"file",
".",
"If",
"no",
"filename",
"is",
"given",
"then",
"CSV",
"is",
"output",
"to",
"STDOUT",
"."
] | 6f60cfe100e854057f112e84fd32656f0ed7f84b | https://github.com/infused/dbf/blob/6f60cfe100e854057f112e84fd32656f0ed7f84b/lib/dbf/table.rb#L190-L195 | train |
deliveroo/routemaster-drain | lib/routemaster/cache.rb | Routemaster.Cache.get | def get(url, version: nil, locale: nil)
@client.get(url, headers: headers(version: version, locale: locale))
end | ruby | def get(url, version: nil, locale: nil)
@client.get(url, headers: headers(version: version, locale: locale))
end | [
"def",
"get",
"(",
"url",
",",
"version",
":",
"nil",
",",
"locale",
":",
"nil",
")",
"@client",
".",
"get",
"(",
"url",
",",
"headers",
":",
"headers",
"(",
"version",
":",
"version",
",",
"locale",
":",
"locale",
")",
")",
"end"
] | Get the response from a URL, from the cache if possible.
Stores to the cache on misses.
Different versions and locales are stored separately in the cache.
@param version [Integer] The version to pass in headers, as `Accept: application/json;v=2`
@param locale [String] The language to request in the `Accept-Langua... | [
"Get",
"the",
"response",
"from",
"a",
"URL",
"from",
"the",
"cache",
"if",
"possible",
".",
"Stores",
"to",
"the",
"cache",
"on",
"misses",
"."
] | e854e15538d672c06ea5e82d3fde8e243b8d54d5 | https://github.com/deliveroo/routemaster-drain/blob/e854e15538d672c06ea5e82d3fde8e243b8d54d5/lib/routemaster/cache.rb#L51-L53 | train |
deliveroo/routemaster-drain | lib/routemaster/redis_broker.rb | Routemaster.RedisBroker.inject | def inject(clients={})
@_injected_clients = true
clients.each_pair do |name, client|
_close_if_present(@_connections[name])
@_connections[name] = Redis::Namespace.new(DEFAULT_NAMESPACE, redis: client)
end
end | ruby | def inject(clients={})
@_injected_clients = true
clients.each_pair do |name, client|
_close_if_present(@_connections[name])
@_connections[name] = Redis::Namespace.new(DEFAULT_NAMESPACE, redis: client)
end
end | [
"def",
"inject",
"(",
"clients",
"=",
"{",
"}",
")",
"@_injected_clients",
"=",
"true",
"clients",
".",
"each_pair",
"do",
"|",
"name",
",",
"client",
"|",
"_close_if_present",
"(",
"@_connections",
"[",
"name",
"]",
")",
"@_connections",
"[",
"name",
"]",... | Allow to inject pre-built Redis clients
Before storing a new connection, ensures that any previously
set client is properly closed. | [
"Allow",
"to",
"inject",
"pre",
"-",
"built",
"Redis",
"clients"
] | e854e15538d672c06ea5e82d3fde8e243b8d54d5 | https://github.com/deliveroo/routemaster-drain/blob/e854e15538d672c06ea5e82d3fde8e243b8d54d5/lib/routemaster/redis_broker.rb#L35-L41 | train |
nevans/resque-pool | features/support/aruba_daemon_support.rb | Aruba.Api.keep_trying | def keep_trying(timeout=10, tries=0)
puts "Try: #{tries}" if @announce_env
yield
rescue RSpec::Expectations::ExpectationNotMetError
if tries < timeout
sleep 1
tries += 1
retry
else
raise
end
end | ruby | def keep_trying(timeout=10, tries=0)
puts "Try: #{tries}" if @announce_env
yield
rescue RSpec::Expectations::ExpectationNotMetError
if tries < timeout
sleep 1
tries += 1
retry
else
raise
end
end | [
"def",
"keep_trying",
"(",
"timeout",
"=",
"10",
",",
"tries",
"=",
"0",
")",
"puts",
"\"Try: #{tries}\"",
"if",
"@announce_env",
"yield",
"rescue",
"RSpec",
"::",
"Expectations",
"::",
"ExpectationNotMetError",
"if",
"tries",
"<",
"timeout",
"sleep",
"1",
"tr... | this is a horrible hack, to make sure that it's done what it needs to do
before we do our next step | [
"this",
"is",
"a",
"horrible",
"hack",
"to",
"make",
"sure",
"that",
"it",
"s",
"done",
"what",
"it",
"needs",
"to",
"do",
"before",
"we",
"do",
"our",
"next",
"step"
] | 62293e48eb75852aa3e0f5f726d158a8614e9259 | https://github.com/nevans/resque-pool/blob/62293e48eb75852aa3e0f5f726d158a8614e9259/features/support/aruba_daemon_support.rb#L11-L22 | train |
rharriso/bower-rails | lib/bower-rails/performer.rb | BowerRails.Performer.perform_command | def perform_command(remove_components = true, &block)
# Load in bower json file
txt = File.read(File.join(root_path, "bower.json"))
json = JSON.parse(txt)
# Load and merge root .bowerrc
dot_bowerrc = JSON.parse(File.read(File.join(root_path, '.bowerrc'))) rescue {}
dot_bowerrc["di... | ruby | def perform_command(remove_components = true, &block)
# Load in bower json file
txt = File.read(File.join(root_path, "bower.json"))
json = JSON.parse(txt)
# Load and merge root .bowerrc
dot_bowerrc = JSON.parse(File.read(File.join(root_path, '.bowerrc'))) rescue {}
dot_bowerrc["di... | [
"def",
"perform_command",
"(",
"remove_components",
"=",
"true",
",",
"&",
"block",
")",
"txt",
"=",
"File",
".",
"read",
"(",
"File",
".",
"join",
"(",
"root_path",
",",
"\"bower.json\"",
")",
")",
"json",
"=",
"JSON",
".",
"parse",
"(",
"txt",
")",
... | run the passed bower block in appropriate folders | [
"run",
"the",
"passed",
"bower",
"block",
"in",
"appropriate",
"folders"
] | 30c6697614149b996f8fb158290bb554990b247d | https://github.com/rharriso/bower-rails/blob/30c6697614149b996f8fb158290bb554990b247d/lib/bower-rails/performer.rb#L62-L114 | train |
drecom/activerecord-turntable | lib/active_record/turntable/connection_proxy.rb | ActiveRecord::Turntable.ConnectionProxy.with_shard | def with_shard(shard)
shard = cluster.to_shard(shard)
old_shard = current_shard
old_fixed = fixed_shard
self.current_shard = shard
self.fixed_shard = shard
yield
ensure
self.fixed_shard = old_fixed
self.current_shard = old_shard
end | ruby | def with_shard(shard)
shard = cluster.to_shard(shard)
old_shard = current_shard
old_fixed = fixed_shard
self.current_shard = shard
self.fixed_shard = shard
yield
ensure
self.fixed_shard = old_fixed
self.current_shard = old_shard
end | [
"def",
"with_shard",
"(",
"shard",
")",
"shard",
"=",
"cluster",
".",
"to_shard",
"(",
"shard",
")",
"old_shard",
"=",
"current_shard",
"old_fixed",
"=",
"fixed_shard",
"self",
".",
"current_shard",
"=",
"shard",
"self",
".",
"fixed_shard",
"=",
"shard",
"yi... | Fix connection to given shard in block
@param [ActiveRecord::Base, Symbol, ActiveRecord::Turntable::Shard, Numeric, String] shard which you want to fix
@param shard [ActiveRecord::Base] AR Object
@param shard [Symbol] shard name symbol that defined in turntable.yml
@param shard [ActiveRecord::Turntable::Shard] Shar... | [
"Fix",
"connection",
"to",
"given",
"shard",
"in",
"block"
] | 7db85be222f8345c6ed14b97a242a1e1c392992e | https://github.com/drecom/activerecord-turntable/blob/7db85be222f8345c6ed14b97a242a1e1c392992e/lib/active_record/turntable/connection_proxy.rb#L159-L170 | train |
drecom/activerecord-turntable | lib/active_record/turntable/connection_proxy.rb | ActiveRecord::Turntable.ConnectionProxy.with_all | def with_all(continue_on_error = false)
cluster.shards.map do |shard|
begin
with_shard(shard) {
yield
}
rescue Exception => err
unless continue_on_error
raise err
end
err
end
end
end | ruby | def with_all(continue_on_error = false)
cluster.shards.map do |shard|
begin
with_shard(shard) {
yield
}
rescue Exception => err
unless continue_on_error
raise err
end
err
end
end
end | [
"def",
"with_all",
"(",
"continue_on_error",
"=",
"false",
")",
"cluster",
".",
"shards",
".",
"map",
"do",
"|",
"shard",
"|",
"begin",
"with_shard",
"(",
"shard",
")",
"{",
"yield",
"}",
"rescue",
"Exception",
"=>",
"err",
"unless",
"continue_on_error",
"... | Send queries to all shards in this cluster
@param [Boolean] continue_on_error when a shard raises error, ignore exception and continue | [
"Send",
"queries",
"to",
"all",
"shards",
"in",
"this",
"cluster"
] | 7db85be222f8345c6ed14b97a242a1e1c392992e | https://github.com/drecom/activerecord-turntable/blob/7db85be222f8345c6ed14b97a242a1e1c392992e/lib/active_record/turntable/connection_proxy.rb#L201-L214 | train |
drecom/activerecord-turntable | lib/active_record/turntable/connection_proxy.rb | ActiveRecord::Turntable.ConnectionProxy.with_default_and_all | def with_default_and_all(continue_on_error = false)
([default_shard] + cluster.shards).map do |shard|
begin
with_shard(shard) {
yield
}
rescue Exception => err
unless continue_on_error
raise err
end
err
end
end... | ruby | def with_default_and_all(continue_on_error = false)
([default_shard] + cluster.shards).map do |shard|
begin
with_shard(shard) {
yield
}
rescue Exception => err
unless continue_on_error
raise err
end
err
end
end... | [
"def",
"with_default_and_all",
"(",
"continue_on_error",
"=",
"false",
")",
"(",
"[",
"default_shard",
"]",
"+",
"cluster",
".",
"shards",
")",
".",
"map",
"do",
"|",
"shard",
"|",
"begin",
"with_shard",
"(",
"shard",
")",
"{",
"yield",
"}",
"rescue",
"E... | Send queries to default connection and all shards in this cluster
@param [Boolean] continue_on_error when a shard raises error, ignore exception and continue | [
"Send",
"queries",
"to",
"default",
"connection",
"and",
"all",
"shards",
"in",
"this",
"cluster"
] | 7db85be222f8345c6ed14b97a242a1e1c392992e | https://github.com/drecom/activerecord-turntable/blob/7db85be222f8345c6ed14b97a242a1e1c392992e/lib/active_record/turntable/connection_proxy.rb#L218-L231 | train |
toland/patron | lib/patron/response.rb | Patron.Response.parse_headers | def parse_headers(header_data_for_multiple_responses)
@headers = {}
responses = Patron::HeaderParser.parse(header_data_for_multiple_responses)
last_response = responses[-1] # Only use the last response (for proxies and redirects)
@status_line = last_response.status_line
last_response.hea... | ruby | def parse_headers(header_data_for_multiple_responses)
@headers = {}
responses = Patron::HeaderParser.parse(header_data_for_multiple_responses)
last_response = responses[-1] # Only use the last response (for proxies and redirects)
@status_line = last_response.status_line
last_response.hea... | [
"def",
"parse_headers",
"(",
"header_data_for_multiple_responses",
")",
"@headers",
"=",
"{",
"}",
"responses",
"=",
"Patron",
"::",
"HeaderParser",
".",
"parse",
"(",
"header_data_for_multiple_responses",
")",
"last_response",
"=",
"responses",
"[",
"-",
"1",
"]",
... | Called by the C code to parse and set the headers | [
"Called",
"by",
"the",
"C",
"code",
"to",
"parse",
"and",
"set",
"the",
"headers"
] | c48e31cfb93d8359c8c81a9d3fb14269f24b6aac | https://github.com/toland/patron/blob/c48e31cfb93d8359c8c81a9d3fb14269f24b6aac/lib/patron/response.rb#L116-L135 | train |
toland/patron | lib/patron/request.rb | Patron.Request.auth_type= | def auth_type=(type=:basic)
@auth_type = case type
when :basic, "basic"
Request::AuthBasic
when :digest, "digest"
Request::AuthDigest
when :any, "any"
Request::AuthAny
else
raise "#{type.inspect} is an unknown authentication type"
end
end | ruby | def auth_type=(type=:basic)
@auth_type = case type
when :basic, "basic"
Request::AuthBasic
when :digest, "digest"
Request::AuthDigest
when :any, "any"
Request::AuthAny
else
raise "#{type.inspect} is an unknown authentication type"
end
end | [
"def",
"auth_type",
"=",
"(",
"type",
"=",
":basic",
")",
"@auth_type",
"=",
"case",
"type",
"when",
":basic",
",",
"\"basic\"",
"Request",
"::",
"AuthBasic",
"when",
":digest",
",",
"\"digest\"",
"Request",
"::",
"AuthDigest",
"when",
":any",
",",
"\"any\""... | Set the type of authentication to use for this request.
@param [String, Symbol]type The type of authentication to use for this request, can be one of
:basic, :digest, or :any
@example
sess.username = "foo"
sess.password = "sekrit"
sess.auth_type = :digest | [
"Set",
"the",
"type",
"of",
"authentication",
"to",
"use",
"for",
"this",
"request",
"."
] | c48e31cfb93d8359c8c81a9d3fb14269f24b6aac | https://github.com/toland/patron/blob/c48e31cfb93d8359c8c81a9d3fb14269f24b6aac/lib/patron/request.rb#L49-L60 | train |
toland/patron | lib/patron/request.rb | Patron.Request.action= | def action=(action)
if !VALID_ACTIONS.include?(action.to_s.upcase)
raise ArgumentError, "Action must be one of #{VALID_ACTIONS.join(', ')}"
end
@action = action.downcase.to_sym
end | ruby | def action=(action)
if !VALID_ACTIONS.include?(action.to_s.upcase)
raise ArgumentError, "Action must be one of #{VALID_ACTIONS.join(', ')}"
end
@action = action.downcase.to_sym
end | [
"def",
"action",
"=",
"(",
"action",
")",
"if",
"!",
"VALID_ACTIONS",
".",
"include?",
"(",
"action",
".",
"to_s",
".",
"upcase",
")",
"raise",
"ArgumentError",
",",
"\"Action must be one of #{VALID_ACTIONS.join(', ')}\"",
"end",
"@action",
"=",
"action",
".",
"... | Sets the HTTP verb for the request
@param action[String] the name of the HTTP verb | [
"Sets",
"the",
"HTTP",
"verb",
"for",
"the",
"request"
] | c48e31cfb93d8359c8c81a9d3fb14269f24b6aac | https://github.com/toland/patron/blob/c48e31cfb93d8359c8c81a9d3fb14269f24b6aac/lib/patron/request.rb#L84-L89 | train |
toland/patron | lib/patron/session.rb | Patron.Session.handle_cookies | def handle_cookies(file_path = nil)
if file_path
path = Pathname(file_path).expand_path
if !File.exists?(file_path) && !File.writable?(path.dirname)
raise ArgumentError, "Can't create file #{path} (permission error)"
elsif File.exists?(file_path) && !File.writable?(file_... | ruby | def handle_cookies(file_path = nil)
if file_path
path = Pathname(file_path).expand_path
if !File.exists?(file_path) && !File.writable?(path.dirname)
raise ArgumentError, "Can't create file #{path} (permission error)"
elsif File.exists?(file_path) && !File.writable?(file_... | [
"def",
"handle_cookies",
"(",
"file_path",
"=",
"nil",
")",
"if",
"file_path",
"path",
"=",
"Pathname",
"(",
"file_path",
")",
".",
"expand_path",
"if",
"!",
"File",
".",
"exists?",
"(",
"file_path",
")",
"&&",
"!",
"File",
".",
"writable?",
"(",
"path",... | Create a new Session object for performing requests.
@param args[Hash] options for the Session (same names as the writable attributes of the Session)
@yield self
Turn on cookie handling for this session, storing them in memory by
default or in +file+ if specified. The `file` must be readable and
writable. Calling... | [
"Create",
"a",
"new",
"Session",
"object",
"for",
"performing",
"requests",
"."
] | c48e31cfb93d8359c8c81a9d3fb14269f24b6aac | https://github.com/toland/patron/blob/c48e31cfb93d8359c8c81a9d3fb14269f24b6aac/lib/patron/session.rb#L145-L164 | train |
toland/patron | lib/patron/session.rb | Patron.Session.post | def post(url, data, headers = {})
if data.is_a?(Hash)
data = data.map {|k,v| urlencode(k.to_s) + '=' + urlencode(v.to_s) }.join('&')
headers['Content-Type'] = 'application/x-www-form-urlencoded'
end
request(:post, url, headers, :data => data)
end | ruby | def post(url, data, headers = {})
if data.is_a?(Hash)
data = data.map {|k,v| urlencode(k.to_s) + '=' + urlencode(v.to_s) }.join('&')
headers['Content-Type'] = 'application/x-www-form-urlencoded'
end
request(:post, url, headers, :data => data)
end | [
"def",
"post",
"(",
"url",
",",
"data",
",",
"headers",
"=",
"{",
"}",
")",
"if",
"data",
".",
"is_a?",
"(",
"Hash",
")",
"data",
"=",
"data",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"urlencode",
"(",
"k",
".",
"to_s",
")",
"+",
"'='",
"+... | Uploads the passed `data` to the specified `url` using an HTTP POST.
@param url[String] the URL to fetch
@param data[Hash, #to_s, #to_path] a Hash of form fields/values,
or an object that can be converted to a String
to create the request body, or an object that responds to #to_path to upload the
entire req... | [
"Uploads",
"the",
"passed",
"data",
"to",
"the",
"specified",
"url",
"using",
"an",
"HTTP",
"POST",
"."
] | c48e31cfb93d8359c8c81a9d3fb14269f24b6aac | https://github.com/toland/patron/blob/c48e31cfb93d8359c8c81a9d3fb14269f24b6aac/lib/patron/session.rb#L275-L281 | train |
toland/patron | lib/patron/session.rb | Patron.Session.post_multipart | def post_multipart(url, data, filename, headers = {})
request(:post, url, headers, {:data => data, :file => filename, :multipart => true})
end | ruby | def post_multipart(url, data, filename, headers = {})
request(:post, url, headers, {:data => data, :file => filename, :multipart => true})
end | [
"def",
"post_multipart",
"(",
"url",
",",
"data",
",",
"filename",
",",
"headers",
"=",
"{",
"}",
")",
"request",
"(",
":post",
",",
"url",
",",
"headers",
",",
"{",
":data",
"=>",
"data",
",",
":file",
"=>",
"filename",
",",
":multipart",
"=>",
"tru... | Uploads the contents of `filename` to the specified `url` using an HTTP POST,
in combination with given form fields passed in `data`.
@param url[String] the URL to fetch
@param data[Hash] hash of the form fields
@param filename[String] path to the file to be uploaded
@param headers[Hash] the hash of header keys t... | [
"Uploads",
"the",
"contents",
"of",
"filename",
"to",
"the",
"specified",
"url",
"using",
"an",
"HTTP",
"POST",
"in",
"combination",
"with",
"given",
"form",
"fields",
"passed",
"in",
"data",
"."
] | c48e31cfb93d8359c8c81a9d3fb14269f24b6aac | https://github.com/toland/patron/blob/c48e31cfb93d8359c8c81a9d3fb14269f24b6aac/lib/patron/session.rb#L302-L304 | train |
toland/patron | lib/patron/session.rb | Patron.Session.build_request | def build_request(action, url, headers, options = {})
# If the Expect header isn't set uploads are really slow
headers['Expect'] ||= ''
Request.new.tap do |req|
req.action = action
req.headers = self.headers.merge headers
req.automatic_content_en... | ruby | def build_request(action, url, headers, options = {})
# If the Expect header isn't set uploads are really slow
headers['Expect'] ||= ''
Request.new.tap do |req|
req.action = action
req.headers = self.headers.merge headers
req.automatic_content_en... | [
"def",
"build_request",
"(",
"action",
",",
"url",
",",
"headers",
",",
"options",
"=",
"{",
"}",
")",
"headers",
"[",
"'Expect'",
"]",
"||=",
"''",
"Request",
".",
"new",
".",
"tap",
"do",
"|",
"req",
"|",
"req",
".",
"action",
"=",
"action",
"req... | Builds a request object that can be used by ++handle_request++
Note that internally, ++handle_request++ uses instance variables of
the Request object, and not it's public methods.
@param action[String] the HTTP verb
@param url[#to_s] the addition to the base url component, or a complete URL
@param headers[Hash] a... | [
"Builds",
"a",
"request",
"object",
"that",
"can",
"be",
"used",
"by",
"++",
"handle_request",
"++",
"Note",
"that",
"internally",
"++",
"handle_request",
"++",
"uses",
"instance",
"variables",
"of",
"the",
"Request",
"object",
"and",
"not",
"it",
"s",
"publ... | c48e31cfb93d8359c8c81a9d3fb14269f24b6aac | https://github.com/toland/patron/blob/c48e31cfb93d8359c8c81a9d3fb14269f24b6aac/lib/patron/session.rb#L357-L400 | train |
xijo/reverse_markdown | lib/reverse_markdown/cleaner.rb | ReverseMarkdown.Cleaner.clean_tag_borders | def clean_tag_borders(string)
result = string.gsub(/\s?\*{2,}.*?\*{2,}\s?/) do |match|
preserve_border_whitespaces(match, default_border: ReverseMarkdown.config.tag_border) do
match.strip.sub('** ', '**').sub(' **', '**')
end
end
result = result.gsub(/\s?\_{2,}.*?\_{2,}\s?/)... | ruby | def clean_tag_borders(string)
result = string.gsub(/\s?\*{2,}.*?\*{2,}\s?/) do |match|
preserve_border_whitespaces(match, default_border: ReverseMarkdown.config.tag_border) do
match.strip.sub('** ', '**').sub(' **', '**')
end
end
result = result.gsub(/\s?\_{2,}.*?\_{2,}\s?/)... | [
"def",
"clean_tag_borders",
"(",
"string",
")",
"result",
"=",
"string",
".",
"gsub",
"(",
"/",
"\\s",
"\\*",
"\\*",
"\\s",
"/",
")",
"do",
"|",
"match",
"|",
"preserve_border_whitespaces",
"(",
"match",
",",
"default_border",
":",
"ReverseMarkdown",
".",
... | Find non-asterisk content that is enclosed by two or
more asterisks. Ensure that only one whitespace occurs
in the border area.
Same for underscores and brackets. | [
"Find",
"non",
"-",
"asterisk",
"content",
"that",
"is",
"enclosed",
"by",
"two",
"or",
"more",
"asterisks",
".",
"Ensure",
"that",
"only",
"one",
"whitespace",
"occurs",
"in",
"the",
"border",
"area",
".",
"Same",
"for",
"underscores",
"and",
"brackets",
... | 4a893bc6534ade98171ed4acfc8777e0f0ab7d6c | https://github.com/xijo/reverse_markdown/blob/4a893bc6534ade98171ed4acfc8777e0f0ab7d6c/lib/reverse_markdown/cleaner.rb#L32-L56 | train |
sinatra/mustermann | mustermann-contrib/lib/mustermann/file_utils.rb | Mustermann.FileUtils.glob_map | def glob_map(map = {}, **options, &block)
map = Mapper === map ? map : Mapper.new(map, **options)
mapped = glob(*map.to_h.keys).map { |f| [f, unescape(map[f])] }
block ? mapped.map(&block) : Hash[mapped]
end | ruby | def glob_map(map = {}, **options, &block)
map = Mapper === map ? map : Mapper.new(map, **options)
mapped = glob(*map.to_h.keys).map { |f| [f, unescape(map[f])] }
block ? mapped.map(&block) : Hash[mapped]
end | [
"def",
"glob_map",
"(",
"map",
"=",
"{",
"}",
",",
"**",
"options",
",",
"&",
"block",
")",
"map",
"=",
"Mapper",
"===",
"map",
"?",
"map",
":",
"Mapper",
".",
"new",
"(",
"map",
",",
"**",
"options",
")",
"mapped",
"=",
"glob",
"(",
"*",
"map"... | Allows to search for files an map these onto other strings.
@example
require 'mustermann/file_utils'
Mustermann::FileUtils.glob_map(':base.:ext' => ':base.bak.:ext') # => {'example.txt' => 'example.bak.txt'}
Mustermann::FileUtils.glob_map(':base.:ext' => :base) { |file, mapped| mapped } # => ['example']
@... | [
"Allows",
"to",
"search",
"for",
"files",
"an",
"map",
"these",
"onto",
"other",
"strings",
"."
] | 5625972edfddb3d254acd949a1a312cca5167de3 | https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/file_utils.rb#L60-L64 | train |
sinatra/mustermann | mustermann-contrib/lib/mustermann/file_utils.rb | Mustermann.FileUtils.cp | def cp(map = {}, recursive: false, **options)
utils_opts, opts = split_options(:preserve, :dereference_root, :remove_destination, **options)
cp_method = recursive ? :cp_r : :cp
glob_map(map, **opts) { |o,n| f.send(cp_method, o, n, **utils_opts) }
end | ruby | def cp(map = {}, recursive: false, **options)
utils_opts, opts = split_options(:preserve, :dereference_root, :remove_destination, **options)
cp_method = recursive ? :cp_r : :cp
glob_map(map, **opts) { |o,n| f.send(cp_method, o, n, **utils_opts) }
end | [
"def",
"cp",
"(",
"map",
"=",
"{",
"}",
",",
"recursive",
":",
"false",
",",
"**",
"options",
")",
"utils_opts",
",",
"opts",
"=",
"split_options",
"(",
":preserve",
",",
":dereference_root",
",",
":remove_destination",
",",
"**",
"options",
")",
"cp_metho... | Copies files based on a pattern mapping.
@example
require 'mustermann/file_utils'
# copies example.txt to example.bak.txt
Mustermann::FileUtils.cp(':base.:ext' => ':base.bak.:ext')
@see #glob_map | [
"Copies",
"files",
"based",
"on",
"a",
"pattern",
"mapping",
"."
] | 5625972edfddb3d254acd949a1a312cca5167de3 | https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/file_utils.rb#L75-L79 | train |
sinatra/mustermann | mustermann-contrib/lib/mustermann/file_utils.rb | Mustermann.FileUtils.mv | def mv(map = {}, **options)
utils_opts, opts = split_options(**options)
glob_map(map, **opts) { |o,n| f.mv(o, n, **utils_opts) }
end | ruby | def mv(map = {}, **options)
utils_opts, opts = split_options(**options)
glob_map(map, **opts) { |o,n| f.mv(o, n, **utils_opts) }
end | [
"def",
"mv",
"(",
"map",
"=",
"{",
"}",
",",
"**",
"options",
")",
"utils_opts",
",",
"opts",
"=",
"split_options",
"(",
"**",
"options",
")",
"glob_map",
"(",
"map",
",",
"**",
"opts",
")",
"{",
"|",
"o",
",",
"n",
"|",
"f",
".",
"mv",
"(",
... | Moves files based on a pattern mapping.
@example
require 'mustermann/file_utils'
# moves example.txt to example.bak.txt
Mustermann::FileUtils.mv(':base.:ext' => ':base.bak.:ext')
@see #glob_map | [
"Moves",
"files",
"based",
"on",
"a",
"pattern",
"mapping",
"."
] | 5625972edfddb3d254acd949a1a312cca5167de3 | https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/file_utils.rb#L104-L107 | train |
sinatra/mustermann | mustermann-contrib/lib/mustermann/file_utils.rb | Mustermann.FileUtils.ln | def ln(map = {}, symbolic: false, **options)
utils_opts, opts = split_options(**options)
link_method = symbolic ? :ln_s : :ln
glob_map(map, **opts) { |o,n| f.send(link_method, o, n, **utils_opts) }
end | ruby | def ln(map = {}, symbolic: false, **options)
utils_opts, opts = split_options(**options)
link_method = symbolic ? :ln_s : :ln
glob_map(map, **opts) { |o,n| f.send(link_method, o, n, **utils_opts) }
end | [
"def",
"ln",
"(",
"map",
"=",
"{",
"}",
",",
"symbolic",
":",
"false",
",",
"**",
"options",
")",
"utils_opts",
",",
"opts",
"=",
"split_options",
"(",
"**",
"options",
")",
"link_method",
"=",
"symbolic",
"?",
":ln_s",
":",
":ln",
"glob_map",
"(",
"... | Creates links based on a pattern mapping.
@example
require 'mustermann/file_utils'
# creates a link from bin/example to lib/example.rb
Mustermann::FileUtils.ln('lib/:name.rb' => 'bin/:name')
@see #glob_map | [
"Creates",
"links",
"based",
"on",
"a",
"pattern",
"mapping",
"."
] | 5625972edfddb3d254acd949a1a312cca5167de3 | https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/file_utils.rb#L119-L123 | train |
sinatra/mustermann | mustermann-contrib/lib/mustermann/file_utils.rb | Mustermann.FileUtils.ln_sf | def ln_sf(map = {}, **options)
ln(map, symbolic: true, force: true, **options)
end | ruby | def ln_sf(map = {}, **options)
ln(map, symbolic: true, force: true, **options)
end | [
"def",
"ln_sf",
"(",
"map",
"=",
"{",
"}",
",",
"**",
"options",
")",
"ln",
"(",
"map",
",",
"symbolic",
":",
"true",
",",
"force",
":",
"true",
",",
"**",
"options",
")",
"end"
] | Creates symbolic links based on a pattern mapping.
Overrides potentailly existing files.
@example
require 'mustermann/file_utils'
# creates a symbolic link from bin/example to lib/example.rb
Mustermann::FileUtils.ln_sf('lib/:name.rb' => 'bin/:name')
@see #glob_map | [
"Creates",
"symbolic",
"links",
"based",
"on",
"a",
"pattern",
"mapping",
".",
"Overrides",
"potentailly",
"existing",
"files",
"."
] | 5625972edfddb3d254acd949a1a312cca5167de3 | https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/file_utils.rb#L148-L150 | train |
sinatra/mustermann | mustermann-contrib/lib/mustermann/file_utils.rb | Mustermann.FileUtils.pattern_with_glob_pattern | def pattern_with_glob_pattern(*pattern, **options)
options[:uri_decode] ||= false
pattern = Mustermann.new(*pattern.flatten, **options)
@glob_patterns ||= {}
@glob_patterns[pattern] ||= GlobPattern.generate(pattern)
[pattern, @glob_patterns[pattern]]
end | ruby | def pattern_with_glob_pattern(*pattern, **options)
options[:uri_decode] ||= false
pattern = Mustermann.new(*pattern.flatten, **options)
@glob_patterns ||= {}
@glob_patterns[pattern] ||= GlobPattern.generate(pattern)
[pattern, @glob_patterns[pattern]]
end | [
"def",
"pattern_with_glob_pattern",
"(",
"*",
"pattern",
",",
"**",
"options",
")",
"options",
"[",
":uri_decode",
"]",
"||=",
"false",
"pattern",
"=",
"Mustermann",
".",
"new",
"(",
"*",
"pattern",
".",
"flatten",
",",
"**",
"options",
")",
"@glob_patterns"... | Create a Mustermann pattern from whatever the input is and turn it into
a glob pattern.
@!visibility private | [
"Create",
"a",
"Mustermann",
"pattern",
"from",
"whatever",
"the",
"input",
"is",
"and",
"turn",
"it",
"into",
"a",
"glob",
"pattern",
"."
] | 5625972edfddb3d254acd949a1a312cca5167de3 | https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/file_utils.rb#L173-L179 | train |
sinatra/mustermann | mustermann/lib/mustermann/concat.rb | Mustermann.Concat.pump | def pump(string, inject_with: :+, initial: nil, with_size: false)
substring = string
results = Array(initial)
patterns.each do |pattern|
result, size = yield(pattern, substring)
return unless result
results << result
size ||= result
substring = substring[s... | ruby | def pump(string, inject_with: :+, initial: nil, with_size: false)
substring = string
results = Array(initial)
patterns.each do |pattern|
result, size = yield(pattern, substring)
return unless result
results << result
size ||= result
substring = substring[s... | [
"def",
"pump",
"(",
"string",
",",
"inject_with",
":",
":+",
",",
"initial",
":",
"nil",
",",
"with_size",
":",
"false",
")",
"substring",
"=",
"string",
"results",
"=",
"Array",
"(",
"initial",
")",
"patterns",
".",
"each",
"do",
"|",
"pattern",
"|",
... | used to generate results for various methods by scanning through an input string
@!visibility private | [
"used",
"to",
"generate",
"results",
"for",
"various",
"methods",
"by",
"scanning",
"through",
"an",
"input",
"string"
] | 5625972edfddb3d254acd949a1a312cca5167de3 | https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann/lib/mustermann/concat.rb#L110-L124 | train |
sinatra/mustermann | mustermann/lib/mustermann/concat.rb | Mustermann.Concat.combined_ast | def combined_ast
payload = patterns.map { |p| AST::Node[:group].new(p.to_ast.payload) }
AST::Node[:root].new(payload)
end | ruby | def combined_ast
payload = patterns.map { |p| AST::Node[:group].new(p.to_ast.payload) }
AST::Node[:root].new(payload)
end | [
"def",
"combined_ast",
"payload",
"=",
"patterns",
".",
"map",
"{",
"|",
"p",
"|",
"AST",
"::",
"Node",
"[",
":group",
"]",
".",
"new",
"(",
"p",
".",
"to_ast",
".",
"payload",
")",
"}",
"AST",
"::",
"Node",
"[",
":root",
"]",
".",
"new",
"(",
... | generates one big AST from all patterns
will not check if patterns support AST generation
@!visibility private | [
"generates",
"one",
"big",
"AST",
"from",
"all",
"patterns",
"will",
"not",
"check",
"if",
"patterns",
"support",
"AST",
"generation"
] | 5625972edfddb3d254acd949a1a312cca5167de3 | https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann/lib/mustermann/concat.rb#L129-L132 | train |
sinatra/mustermann | mustermann/lib/mustermann/sinatra.rb | Mustermann.Sinatra.| | def |(other)
return super unless converted = self.class.try_convert(other, **options)
return super unless converted.names.empty? or names.empty?
self.class.new(safe_string + "|" + converted.safe_string, **options)
end | ruby | def |(other)
return super unless converted = self.class.try_convert(other, **options)
return super unless converted.names.empty? or names.empty?
self.class.new(safe_string + "|" + converted.safe_string, **options)
end | [
"def",
"|",
"(",
"other",
")",
"return",
"super",
"unless",
"converted",
"=",
"self",
".",
"class",
".",
"try_convert",
"(",
"other",
",",
"**",
"options",
")",
"return",
"super",
"unless",
"converted",
".",
"names",
".",
"empty?",
"or",
"names",
".",
... | Creates a pattern that matches any string matching either one of the patterns.
If a string is supplied, it is treated as a fully escaped Sinatra pattern.
If the other pattern is also a Sintara pattern, it might join the two to a third
sinatra pattern instead of generating a composite for efficiency reasons.
This ... | [
"Creates",
"a",
"pattern",
"that",
"matches",
"any",
"string",
"matching",
"either",
"one",
"of",
"the",
"patterns",
".",
"If",
"a",
"string",
"is",
"supplied",
"it",
"is",
"treated",
"as",
"a",
"fully",
"escaped",
"Sinatra",
"pattern",
"."
] | 5625972edfddb3d254acd949a1a312cca5167de3 | https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann/lib/mustermann/sinatra.rb#L59-L63 | train |
sinatra/mustermann | mustermann-contrib/lib/mustermann/string_scanner.rb | Mustermann.StringScanner.scan_until | def scan_until(pattern, **options)
result, prefix = check_until_with_prefix(pattern, **options)
track_result(prefix, result)
end | ruby | def scan_until(pattern, **options)
result, prefix = check_until_with_prefix(pattern, **options)
track_result(prefix, result)
end | [
"def",
"scan_until",
"(",
"pattern",
",",
"**",
"options",
")",
"result",
",",
"prefix",
"=",
"check_until_with_prefix",
"(",
"pattern",
",",
"**",
"options",
")",
"track_result",
"(",
"prefix",
",",
"result",
")",
"end"
] | Checks if the given pattern matches any substring starting at any position after the current position.
If it does, it will advance the current {#position} to the end of the substring and merges any params parsed
from the substring into {#params}.
@param (see Mustermann.new)
@return [Mustermann::StringScanner::Sca... | [
"Checks",
"if",
"the",
"given",
"pattern",
"matches",
"any",
"substring",
"starting",
"at",
"any",
"position",
"after",
"the",
"current",
"position",
"."
] | 5625972edfddb3d254acd949a1a312cca5167de3 | https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/string_scanner.rb#L173-L176 | train |
sinatra/mustermann | mustermann-contrib/lib/mustermann/string_scanner.rb | Mustermann.StringScanner.unscan | def unscan
raise ScanError, 'unscan failed: previous match record not exist' if @history.empty?
previous = @history[0..-2]
reset
previous.each { |r| track_result(*r) }
self
end | ruby | def unscan
raise ScanError, 'unscan failed: previous match record not exist' if @history.empty?
previous = @history[0..-2]
reset
previous.each { |r| track_result(*r) }
self
end | [
"def",
"unscan",
"raise",
"ScanError",
",",
"'unscan failed: previous match record not exist'",
"if",
"@history",
".",
"empty?",
"previous",
"=",
"@history",
"[",
"0",
"..",
"-",
"2",
"]",
"reset",
"previous",
".",
"each",
"{",
"|",
"r",
"|",
"track_result",
"... | Reverts the last operation that advanced the position.
Operations advancing the position: {#terminate}, {#scan}, {#scan_until}, {#getch}.
@return [Mustermann::StringScanner] the scanner itself | [
"Reverts",
"the",
"last",
"operation",
"that",
"advanced",
"the",
"position",
"."
] | 5625972edfddb3d254acd949a1a312cca5167de3 | https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/string_scanner.rb#L182-L188 | train |
sinatra/mustermann | mustermann-contrib/lib/mustermann/string_scanner.rb | Mustermann.StringScanner.check | def check(pattern, **options)
params, length = create_pattern(pattern, **options).peek_params(rest)
ScanResult.new(self, @position, length, params) if params
end | ruby | def check(pattern, **options)
params, length = create_pattern(pattern, **options).peek_params(rest)
ScanResult.new(self, @position, length, params) if params
end | [
"def",
"check",
"(",
"pattern",
",",
"**",
"options",
")",
"params",
",",
"length",
"=",
"create_pattern",
"(",
"pattern",
",",
"**",
"options",
")",
".",
"peek_params",
"(",
"rest",
")",
"ScanResult",
".",
"new",
"(",
"self",
",",
"@position",
",",
"l... | Checks if the given pattern matches any substring starting at the current position.
Does not affect {#position} or {#params}.
@param (see Mustermann.new)
@return [Mustermann::StringScanner::ScanResult, nil] the matched substring, nil if it didn't match | [
"Checks",
"if",
"the",
"given",
"pattern",
"matches",
"any",
"substring",
"starting",
"at",
"the",
"current",
"position",
"."
] | 5625972edfddb3d254acd949a1a312cca5167de3 | https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/string_scanner.rb#L196-L199 | train |
sinatra/mustermann | mustermann/lib/mustermann/identity.rb | Mustermann.Identity.expand | def expand(behavior = nil, values = {})
return to_s if values.empty? or behavior == :ignore
raise ExpandError, "cannot expand with keys %p" % values.keys.sort if behavior == :raise
raise ArgumentError, "unknown behavior %p" % behavior if behavior != :append
params = values.... | ruby | def expand(behavior = nil, values = {})
return to_s if values.empty? or behavior == :ignore
raise ExpandError, "cannot expand with keys %p" % values.keys.sort if behavior == :raise
raise ArgumentError, "unknown behavior %p" % behavior if behavior != :append
params = values.... | [
"def",
"expand",
"(",
"behavior",
"=",
"nil",
",",
"values",
"=",
"{",
"}",
")",
"return",
"to_s",
"if",
"values",
".",
"empty?",
"or",
"behavior",
"==",
":ignore",
"raise",
"ExpandError",
",",
"\"cannot expand with keys %p\"",
"%",
"values",
".",
"keys",
... | Identity patterns support expanding.
This implementation does not use {Mustermann::Expander} internally to save memory and
compilation time.
@example (see Mustermann::Pattern#expand)
@param (see Mustermann::Pattern#expand)
@return (see Mustermann::Pattern#expand)
@raise (see Mustermann::Pattern#expand)
@see Mu... | [
"Identity",
"patterns",
"support",
"expanding",
"."
] | 5625972edfddb3d254acd949a1a312cca5167de3 | https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann/lib/mustermann/identity.rb#L68-L75 | train |
sinatra/mustermann | mustermann-contrib/lib/mustermann/versions.rb | Mustermann.Versions.new | def new(*args, version: nil, **options)
return super(*args, **options) unless versions.any?
self[version].new(*args, **options)
end | ruby | def new(*args, version: nil, **options)
return super(*args, **options) unless versions.any?
self[version].new(*args, **options)
end | [
"def",
"new",
"(",
"*",
"args",
",",
"version",
":",
"nil",
",",
"**",
"options",
")",
"return",
"super",
"(",
"*",
"args",
",",
"**",
"options",
")",
"unless",
"versions",
".",
"any?",
"self",
"[",
"version",
"]",
".",
"new",
"(",
"*",
"args",
"... | Checks if class has mulitple versions available and picks one that matches the version option.
@!visibility private | [
"Checks",
"if",
"class",
"has",
"mulitple",
"versions",
"available",
"and",
"picks",
"one",
"that",
"matches",
"the",
"version",
"option",
"."
] | 5625972edfddb3d254acd949a1a312cca5167de3 | https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/versions.rb#L9-L12 | train |
sinatra/mustermann | mustermann-contrib/lib/mustermann/versions.rb | Mustermann.Versions.version | def version(*list, inherit_from: nil, &block)
superclass = self[inherit_from] || self
subclass = Class.new(superclass, &block)
list.each { |v| versions[v] = subclass }
end | ruby | def version(*list, inherit_from: nil, &block)
superclass = self[inherit_from] || self
subclass = Class.new(superclass, &block)
list.each { |v| versions[v] = subclass }
end | [
"def",
"version",
"(",
"*",
"list",
",",
"inherit_from",
":",
"nil",
",",
"&",
"block",
")",
"superclass",
"=",
"self",
"[",
"inherit_from",
"]",
"||",
"self",
"subclass",
"=",
"Class",
".",
"new",
"(",
"superclass",
",",
"&",
"block",
")",
"list",
"... | Defines a new version.
@!visibility private | [
"Defines",
"a",
"new",
"version",
"."
] | 5625972edfddb3d254acd949a1a312cca5167de3 | https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/versions.rb#L22-L26 | train |
sinatra/mustermann | mustermann-contrib/lib/mustermann/versions.rb | Mustermann.Versions.[] | def [](version)
return versions.values.last unless version
detected = versions.detect { |v,_| version.start_with?(v) }
raise ArgumentError, 'unsupported version %p' % version unless detected
detected.last
end | ruby | def [](version)
return versions.values.last unless version
detected = versions.detect { |v,_| version.start_with?(v) }
raise ArgumentError, 'unsupported version %p' % version unless detected
detected.last
end | [
"def",
"[]",
"(",
"version",
")",
"return",
"versions",
".",
"values",
".",
"last",
"unless",
"version",
"detected",
"=",
"versions",
".",
"detect",
"{",
"|",
"v",
",",
"_",
"|",
"version",
".",
"start_with?",
"(",
"v",
")",
"}",
"raise",
"ArgumentErro... | Resolve a subclass for a given version string.
@!visibility private | [
"Resolve",
"a",
"subclass",
"for",
"a",
"given",
"version",
"string",
"."
] | 5625972edfddb3d254acd949a1a312cca5167de3 | https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann-contrib/lib/mustermann/versions.rb#L30-L35 | train |
sinatra/mustermann | mustermann/lib/mustermann/caster.rb | Mustermann.Caster.cast | def cast(hash)
return hash if empty?
merge = {}
hash.delete_if do |key, value|
next unless casted = lazy.map { |e| e.cast(key, value) }.detect { |e| e }
casted = { key => casted } unless casted.respond_to? :to_hash
merge.update(casted.to_hash)
end
hash.update(merge)... | ruby | def cast(hash)
return hash if empty?
merge = {}
hash.delete_if do |key, value|
next unless casted = lazy.map { |e| e.cast(key, value) }.detect { |e| e }
casted = { key => casted } unless casted.respond_to? :to_hash
merge.update(casted.to_hash)
end
hash.update(merge)... | [
"def",
"cast",
"(",
"hash",
")",
"return",
"hash",
"if",
"empty?",
"merge",
"=",
"{",
"}",
"hash",
".",
"delete_if",
"do",
"|",
"key",
",",
"value",
"|",
"next",
"unless",
"casted",
"=",
"lazy",
".",
"map",
"{",
"|",
"e",
"|",
"e",
".",
"cast",
... | Transforms a Hash.
@param [Hash] hash pre-transform Hash
@return [Hash] post-transform Hash
@!visibility private | [
"Transforms",
"a",
"Hash",
"."
] | 5625972edfddb3d254acd949a1a312cca5167de3 | https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann/lib/mustermann/caster.rb#L45-L54 | train |
sinatra/mustermann | mustermann/lib/mustermann/mapper.rb | Mustermann.Mapper.update | def update(map)
map.to_h.each_pair do |input, output|
input = Mustermann.new(input, **@options)
output = Expander.new(*output, additional_values: @additional_values, **@options) unless output.is_a? Expander
@map << [input, output]
end
end | ruby | def update(map)
map.to_h.each_pair do |input, output|
input = Mustermann.new(input, **@options)
output = Expander.new(*output, additional_values: @additional_values, **@options) unless output.is_a? Expander
@map << [input, output]
end
end | [
"def",
"update",
"(",
"map",
")",
"map",
".",
"to_h",
".",
"each_pair",
"do",
"|",
"input",
",",
"output",
"|",
"input",
"=",
"Mustermann",
".",
"new",
"(",
"input",
",",
"**",
"@options",
")",
"output",
"=",
"Expander",
".",
"new",
"(",
"*",
"outp... | Creates a new mapper.
@overload initialize(**options)
@param options [Hash] options The options hash
@yield block for generating mappings as a hash
@yieldreturn [Hash] see {#update}
@example
require 'mustermann/mapper'
Mustermann::Mapper.new(type: :rails) {{
"/:foo" => ["/:foo.html", "/:... | [
"Creates",
"a",
"new",
"mapper",
"."
] | 5625972edfddb3d254acd949a1a312cca5167de3 | https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann/lib/mustermann/mapper.rb#L59-L65 | train |
sinatra/mustermann | mustermann/lib/mustermann/mapper.rb | Mustermann.Mapper.convert | def convert(input, values = {})
@map.inject(input) do |current, (pattern, expander)|
params = pattern.params(current)
params &&= Hash[values.merge(params).map { |k,v| [k.to_s, v] }]
expander.expandable?(params) ? expander.expand(params) : current
end
end | ruby | def convert(input, values = {})
@map.inject(input) do |current, (pattern, expander)|
params = pattern.params(current)
params &&= Hash[values.merge(params).map { |k,v| [k.to_s, v] }]
expander.expandable?(params) ? expander.expand(params) : current
end
end | [
"def",
"convert",
"(",
"input",
",",
"values",
"=",
"{",
"}",
")",
"@map",
".",
"inject",
"(",
"input",
")",
"do",
"|",
"current",
",",
"(",
"pattern",
",",
"expander",
")",
"|",
"params",
"=",
"pattern",
".",
"params",
"(",
"current",
")",
"params... | Convert a string according to mappings. You can pass in additional params.
@example mapping with and without additional parameters
mapper = Mustermann::Mapper.new("/:example" => "(/:prefix)?/:example.html") | [
"Convert",
"a",
"string",
"according",
"to",
"mappings",
".",
"You",
"can",
"pass",
"in",
"additional",
"params",
"."
] | 5625972edfddb3d254acd949a1a312cca5167de3 | https://github.com/sinatra/mustermann/blob/5625972edfddb3d254acd949a1a312cca5167de3/mustermann/lib/mustermann/mapper.rb#L77-L83 | train |
typhoeus/ethon | lib/ethon/easy.rb | Ethon.Easy.escape | def escape(value)
string_pointer = Curl.easy_escape(handle, value, value.bytesize)
returned_string = string_pointer.read_string
Curl.free(string_pointer)
returned_string
end | ruby | def escape(value)
string_pointer = Curl.easy_escape(handle, value, value.bytesize)
returned_string = string_pointer.read_string
Curl.free(string_pointer)
returned_string
end | [
"def",
"escape",
"(",
"value",
")",
"string_pointer",
"=",
"Curl",
".",
"easy_escape",
"(",
"handle",
",",
"value",
",",
"value",
".",
"bytesize",
")",
"returned_string",
"=",
"string_pointer",
".",
"read_string",
"Curl",
".",
"free",
"(",
"string_pointer",
... | Clones libcurl session handle. This means that all options that is set in
the current handle will be set on duplicated handle.
Url escapes the value.
@example Url escape.
easy.escape(value)
@param [ String ] value The value to escape.
@return [ String ] The escaped value.
@api private | [
"Clones",
"libcurl",
"session",
"handle",
".",
"This",
"means",
"that",
"all",
"options",
"that",
"is",
"set",
"in",
"the",
"current",
"handle",
"will",
"be",
"set",
"on",
"duplicated",
"handle",
".",
"Url",
"escapes",
"the",
"value",
"."
] | c5c9c6e10114c9939642be522ab05432ca7ec5d2 | https://github.com/typhoeus/ethon/blob/c5c9c6e10114c9939642be522ab05432ca7ec5d2/lib/ethon/easy.rb#L285-L290 | train |
abitdodgy/words_counted | lib/words_counted/counter.rb | WordsCounted.Counter.token_frequency | def token_frequency
tokens.each_with_object(Hash.new(0)) { |token, hash| hash[token] += 1 }.sort_by_value_desc
end | ruby | def token_frequency
tokens.each_with_object(Hash.new(0)) { |token, hash| hash[token] += 1 }.sort_by_value_desc
end | [
"def",
"token_frequency",
"tokens",
".",
"each_with_object",
"(",
"Hash",
".",
"new",
"(",
"0",
")",
")",
"{",
"|",
"token",
",",
"hash",
"|",
"hash",
"[",
"token",
"]",
"+=",
"1",
"}",
".",
"sort_by_value_desc",
"end"
] | Returns a sorted two-dimensional array where each member array is a token and its frequency.
The array is sorted by frequency in descending order.
@example
Counter.new(%w[one two two three three three]).token_frequency
# => [ ['three', 3], ['two', 2], ['one', 1] ]
@return [Array<Array<String, Integer>>] An arr... | [
"Returns",
"a",
"sorted",
"two",
"-",
"dimensional",
"array",
"where",
"each",
"member",
"array",
"is",
"a",
"token",
"and",
"its",
"frequency",
".",
"The",
"array",
"is",
"sorted",
"by",
"frequency",
"in",
"descending",
"order",
"."
] | 5f3ea74249e05f22e16e097ce7cf9b940887e0ae | https://github.com/abitdodgy/words_counted/blob/5f3ea74249e05f22e16e097ce7cf9b940887e0ae/lib/words_counted/counter.rb#L66-L68 | train |
abitdodgy/words_counted | lib/words_counted/counter.rb | WordsCounted.Counter.token_lengths | def token_lengths
tokens.uniq.each_with_object({}) { |token, hash| hash[token] = token.length }.sort_by_value_desc
end | ruby | def token_lengths
tokens.uniq.each_with_object({}) { |token, hash| hash[token] = token.length }.sort_by_value_desc
end | [
"def",
"token_lengths",
"tokens",
".",
"uniq",
".",
"each_with_object",
"(",
"{",
"}",
")",
"{",
"|",
"token",
",",
"hash",
"|",
"hash",
"[",
"token",
"]",
"=",
"token",
".",
"length",
"}",
".",
"sort_by_value_desc",
"end"
] | Returns a sorted two-dimensional array where each member array is a token and its length.
The array is sorted by length in descending order.
@example
Counter.new(%w[one two three four five]).token_lenghts
# => [ ['three', 5], ['four', 4], ['five', 4], ['one', 3], ['two', 3] ]
@return [Array<Array<String, Integ... | [
"Returns",
"a",
"sorted",
"two",
"-",
"dimensional",
"array",
"where",
"each",
"member",
"array",
"is",
"a",
"token",
"and",
"its",
"length",
".",
"The",
"array",
"is",
"sorted",
"by",
"length",
"in",
"descending",
"order",
"."
] | 5f3ea74249e05f22e16e097ce7cf9b940887e0ae | https://github.com/abitdodgy/words_counted/blob/5f3ea74249e05f22e16e097ce7cf9b940887e0ae/lib/words_counted/counter.rb#L78-L80 | train |
abitdodgy/words_counted | lib/words_counted/counter.rb | WordsCounted.Counter.token_density | def token_density(precision: 2)
token_frequency.each_with_object({}) { |(token, freq), hash|
hash[token] = (freq / token_count.to_f).round(precision)
}.sort_by_value_desc
end | ruby | def token_density(precision: 2)
token_frequency.each_with_object({}) { |(token, freq), hash|
hash[token] = (freq / token_count.to_f).round(precision)
}.sort_by_value_desc
end | [
"def",
"token_density",
"(",
"precision",
":",
"2",
")",
"token_frequency",
".",
"each_with_object",
"(",
"{",
"}",
")",
"{",
"|",
"(",
"token",
",",
"freq",
")",
",",
"hash",
"|",
"hash",
"[",
"token",
"]",
"=",
"(",
"freq",
"/",
"token_count",
".",... | Returns a sorted two-dimensional array where each member array is a token and its density
as a float, rounded to a precision of two decimal places. It accepts a precision argument
which defaults to `2`.
@example
Counter.new(%w[Maj. Major Major Major]).token_density
# => [ ['major', .75], ['maj', .25] ]
@examp... | [
"Returns",
"a",
"sorted",
"two",
"-",
"dimensional",
"array",
"where",
"each",
"member",
"array",
"is",
"a",
"token",
"and",
"its",
"density",
"as",
"a",
"float",
"rounded",
"to",
"a",
"precision",
"of",
"two",
"decimal",
"places",
".",
"It",
"accepts",
... | 5f3ea74249e05f22e16e097ce7cf9b940887e0ae | https://github.com/abitdodgy/words_counted/blob/5f3ea74249e05f22e16e097ce7cf9b940887e0ae/lib/words_counted/counter.rb#L96-L100 | train |
abitdodgy/words_counted | lib/words_counted/tokeniser.rb | WordsCounted.Tokeniser.tokenise | def tokenise(pattern: TOKEN_REGEXP, exclude: nil)
filter_proc = filter_to_proc(exclude)
@input.scan(pattern).map(&:downcase).reject { |token| filter_proc.call(token) }
end | ruby | def tokenise(pattern: TOKEN_REGEXP, exclude: nil)
filter_proc = filter_to_proc(exclude)
@input.scan(pattern).map(&:downcase).reject { |token| filter_proc.call(token) }
end | [
"def",
"tokenise",
"(",
"pattern",
":",
"TOKEN_REGEXP",
",",
"exclude",
":",
"nil",
")",
"filter_proc",
"=",
"filter_to_proc",
"(",
"exclude",
")",
"@input",
".",
"scan",
"(",
"pattern",
")",
".",
"map",
"(",
"&",
":downcase",
")",
".",
"reject",
"{",
... | Initialises state with the string to be tokenised.
@param [String] input The string to tokenise
Converts a string into an array of tokens using a regular expression.
If a regexp is not provided a default one is used. See `Tokenizer.TOKEN_REGEXP`.
Use `exclude` to remove tokens from the final list. `exclude` can... | [
"Initialises",
"state",
"with",
"the",
"string",
"to",
"be",
"tokenised",
"."
] | 5f3ea74249e05f22e16e097ce7cf9b940887e0ae | https://github.com/abitdodgy/words_counted/blob/5f3ea74249e05f22e16e097ce7cf9b940887e0ae/lib/words_counted/tokeniser.rb#L97-L100 | train |
abitdodgy/words_counted | lib/words_counted/tokeniser.rb | WordsCounted.Tokeniser.filter_to_proc | def filter_to_proc(filter)
if filter.respond_to?(:to_a)
filter_procs_from_array(filter)
elsif filter.respond_to?(:to_str)
filter_proc_from_string(filter)
elsif regexp_filter = Regexp.try_convert(filter)
->(token) {
token =~ regexp_filter
}
elsif filter.r... | ruby | def filter_to_proc(filter)
if filter.respond_to?(:to_a)
filter_procs_from_array(filter)
elsif filter.respond_to?(:to_str)
filter_proc_from_string(filter)
elsif regexp_filter = Regexp.try_convert(filter)
->(token) {
token =~ regexp_filter
}
elsif filter.r... | [
"def",
"filter_to_proc",
"(",
"filter",
")",
"if",
"filter",
".",
"respond_to?",
"(",
":to_a",
")",
"filter_procs_from_array",
"(",
"filter",
")",
"elsif",
"filter",
".",
"respond_to?",
"(",
":to_str",
")",
"filter_proc_from_string",
"(",
"filter",
")",
"elsif",... | The following methods convert any arguments into a callable object. The return value of this
lambda is then used to determine whether a token should be excluded from the final list.
`filter` can be a string, a regular expression, a lambda, a symbol, or an array
of any combination of those types.
If `filter` is a ... | [
"The",
"following",
"methods",
"convert",
"any",
"arguments",
"into",
"a",
"callable",
"object",
".",
"The",
"return",
"value",
"of",
"this",
"lambda",
"is",
"then",
"used",
"to",
"determine",
"whether",
"a",
"token",
"should",
"be",
"excluded",
"from",
"the... | 5f3ea74249e05f22e16e097ce7cf9b940887e0ae | https://github.com/abitdodgy/words_counted/blob/5f3ea74249e05f22e16e097ce7cf9b940887e0ae/lib/words_counted/tokeniser.rb#L130-L145 | train |
contentful/contentful_model | lib/contentful_model.rb | ContentfulModel.Configuration.to_hash | def to_hash
Hash[instance_variables.map { |name| [name.to_s.delete('@').to_sym, instance_variable_get(name)] }]
end | ruby | def to_hash
Hash[instance_variables.map { |name| [name.to_s.delete('@').to_sym, instance_variable_get(name)] }]
end | [
"def",
"to_hash",
"Hash",
"[",
"instance_variables",
".",
"map",
"{",
"|",
"name",
"|",
"[",
"name",
".",
"to_s",
".",
"delete",
"(",
"'@'",
")",
".",
"to_sym",
",",
"instance_variable_get",
"(",
"name",
")",
"]",
"}",
"]",
"end"
] | Return the Configuration object as a hash, with symbols as keys.
@return [Hash] | [
"Return",
"the",
"Configuration",
"object",
"as",
"a",
"hash",
"with",
"symbols",
"as",
"keys",
"."
] | b286afd939daae87fdeb1f320f43753dcaae3144 | https://github.com/contentful/contentful_model/blob/b286afd939daae87fdeb1f320f43753dcaae3144/lib/contentful_model.rb#L51-L53 | train |
jkraemer/pdf-forms | lib/pdf_forms/pdftk_wrapper.rb | PdfForms.PdftkWrapper.cat | def cat(*args)
in_files = []
page_ranges = []
file_handle = "A"
output = normalize_path args.pop
args.flatten.compact.each do |in_file|
if in_file.is_a? Hash
path = in_file.keys.first
page_ranges.push *in_file.values.first.map {|range| "#{file_handle}#{range}"}... | ruby | def cat(*args)
in_files = []
page_ranges = []
file_handle = "A"
output = normalize_path args.pop
args.flatten.compact.each do |in_file|
if in_file.is_a? Hash
path = in_file.keys.first
page_ranges.push *in_file.values.first.map {|range| "#{file_handle}#{range}"}... | [
"def",
"cat",
"(",
"*",
"args",
")",
"in_files",
"=",
"[",
"]",
"page_ranges",
"=",
"[",
"]",
"file_handle",
"=",
"\"A\"",
"output",
"=",
"normalize_path",
"args",
".",
"pop",
"args",
".",
"flatten",
".",
"compact",
".",
"each",
"do",
"|",
"in_file",
... | concatenate documents, can optionally specify page ranges
args: in_file1, {in_file2 => ["1-2", "4-10"]}, ... , in_file_n, output | [
"concatenate",
"documents",
"can",
"optionally",
"specify",
"page",
"ranges"
] | 34518c762a52494893125dad9dc504eac2f88af3 | https://github.com/jkraemer/pdf-forms/blob/34518c762a52494893125dad9dc504eac2f88af3/lib/pdf_forms/pdftk_wrapper.rb#L94-L113 | train |
jkraemer/pdf-forms | lib/pdf_forms/data_format.rb | PdfForms.DataFormat.to_pdf_data | def to_pdf_data
pdf_data = header
@data.each do |key, value|
if Hash === value
value.each do |sub_key, sub_value|
pdf_data << field("#{key}_#{sub_key}", sub_value)
end
else
pdf_data << field(key, value)
end
end
pdf_data << foote... | ruby | def to_pdf_data
pdf_data = header
@data.each do |key, value|
if Hash === value
value.each do |sub_key, sub_value|
pdf_data << field("#{key}_#{sub_key}", sub_value)
end
else
pdf_data << field(key, value)
end
end
pdf_data << foote... | [
"def",
"to_pdf_data",
"pdf_data",
"=",
"header",
"@data",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"Hash",
"===",
"value",
"value",
".",
"each",
"do",
"|",
"sub_key",
",",
"sub_value",
"|",
"pdf_data",
"<<",
"field",
"(",
"\"#{key}_#{sub_k... | generate PDF content in this data format | [
"generate",
"PDF",
"content",
"in",
"this",
"data",
"format"
] | 34518c762a52494893125dad9dc504eac2f88af3 | https://github.com/jkraemer/pdf-forms/blob/34518c762a52494893125dad9dc504eac2f88af3/lib/pdf_forms/data_format.rb#L17-L32 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.