repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
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",
".",
"realname",
"when",
"\"a\"",
"self",
".",
"authname",
"end",
"}",
"Mask",
".",
"new",
"(",
"s",
")",
"end"
] | 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",
":",
"30",
")",
"{",
"refresh",
"}",
"@monitored_timer",
".",
"start",
"end",
"@monitored",
"=",
"true",
"end"
] | 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",
".",
"handlers",
".",
"dispatch",
"(",
":online",
",",
"nil",
",",
"self",
")",
"else",
"@bot",
".",
"handlers",
".",
"dispatch",
"(",
":offline",
",",
"nil",
",",
"self",
")",
"end",
"end"
] | 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
sending_thread.kill
ping_thread.kill
end
end | 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
sending_thread.kill
ping_thread.kill
end
end | [
"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",
"sending_thread",
".",
"kill",
"ping_thread",
".",
"kill",
"end",
"end"
] | 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("locale", {:invalid => :replace, :undef => :replace})
end
end
end | 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("locale", {:invalid => :replace, :undef => :replace})
end
end
end | [
"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",
"(",
"\"locale\"",
",",
"{",
":invalid",
"=>",
":replace",
",",
":undef",
"=>",
":replace",
"}",
")",
"end",
"end",
"end"
] | 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",
".",
"new",
"(",
"name",
",",
"@bot",
")",
"end",
"end"
] | 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",
".",
"irc",
".",
"send",
"\"TOPIC #@name :#{new_topic}\"",
"end"
] | 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",
",",
"reason",
"end",
"@bot",
".",
"irc",
".",
"send",
"(",
"\"KICK #@name #{user} :#{reason}\"",
")",
"end"
] | 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.mask} #{command} #{@name} :"
text.lines.map(&:chomp).each do |line|
splitted = split_message(line, prefix, split_start, split_end)
splitted[0, (@bot.config.max_messages || splitted.size)].each do |string|
@bot.irc.send("#{command} #@name :#{string}")
end
end
end | 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.mask} #{command} #{@name} :"
text.lines.map(&:chomp).each do |line|
splitted = split_message(line, prefix, split_start, split_end)
splitted[0, (@bot.config.max_messages || splitted.size)].each do |string|
@bot.irc.send("#{command} #@name :#{string}")
end
end
end | [
"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.mask} #{command} #{@name} :\"",
"text",
".",
"lines",
".",
"map",
"(",
":chomp",
")",
".",
"each",
"do",
"|",
"line",
"|",
"splitted",
"=",
"split_message",
"(",
"line",
",",
"prefix",
",",
"split_start",
",",
"split_end",
")",
"splitted",
"[",
"0",
",",
"(",
"@bot",
".",
"config",
".",
"max_messages",
"||",
"splitted",
".",
"size",
")",
"]",
".",
"each",
"do",
"|",
"string",
"|",
"@bot",
".",
"irc",
".",
"send",
"(",
"\"#{command} #@name :#{string}\"",
")",
"end",
"end",
"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.unsync_all
end # reset state of all channels
@channels = [] # reset list of channels the bot is in
@join_handler.unregister if @join_handler
@join_timer.stop if @join_timer
join_lambda = lambda { @config.channels.each { |channel| Channel(channel).join }}
if @config.delay_joins.is_a?(Symbol)
@join_handler = join_handler = on(@config.delay_joins) {
join_handler.unregister
join_lambda.call
}
else
@join_timer = Timer.new(self, interval: @config.delay_joins, shots: 1) {
join_lambda.call
}
end
@modes = []
@loggers.info "Connecting to #{@config.server}:#{@config.port}"
@irc = IRC.new(self)
@irc.start
if @config.reconnect && !@quitting
# double the delay for each unsuccesful reconnection attempt
if @last_connection_was_successful
@reconnects = 0
@last_connection_was_successful = false
else
@reconnects += 1
end
# Throttle reconnect attempts
wait = 2**@reconnects
wait = @config.max_reconnect_delay if wait > @config.max_reconnect_delay
@loggers.info "Waiting #{wait} seconds before reconnecting"
start_time = Time.now
while !@quitting && (Time.now - start_time) < wait
sleep 1
end
end
end while @config.reconnect and not @quitting
end | 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.unsync_all
end # reset state of all channels
@channels = [] # reset list of channels the bot is in
@join_handler.unregister if @join_handler
@join_timer.stop if @join_timer
join_lambda = lambda { @config.channels.each { |channel| Channel(channel).join }}
if @config.delay_joins.is_a?(Symbol)
@join_handler = join_handler = on(@config.delay_joins) {
join_handler.unregister
join_lambda.call
}
else
@join_timer = Timer.new(self, interval: @config.delay_joins, shots: 1) {
join_lambda.call
}
end
@modes = []
@loggers.info "Connecting to #{@config.server}:#{@config.port}"
@irc = IRC.new(self)
@irc.start
if @config.reconnect && !@quitting
# double the delay for each unsuccesful reconnection attempt
if @last_connection_was_successful
@reconnects = 0
@last_connection_was_successful = false
else
@reconnects += 1
end
# Throttle reconnect attempts
wait = 2**@reconnects
wait = @config.max_reconnect_delay if wait > @config.max_reconnect_delay
@loggers.info "Waiting #{wait} seconds before reconnecting"
start_time = Time.now
while !@quitting && (Time.now - start_time) < wait
sleep 1
end
end
end while @config.reconnect and not @quitting
end | [
"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",
".",
"unsync_all",
"end",
"# reset state of all channels",
"@channels",
"=",
"[",
"]",
"# reset list of channels the bot is in",
"@join_handler",
".",
"unregister",
"if",
"@join_handler",
"@join_timer",
".",
"stop",
"if",
"@join_timer",
"join_lambda",
"=",
"lambda",
"{",
"@config",
".",
"channels",
".",
"each",
"{",
"|",
"channel",
"|",
"Channel",
"(",
"channel",
")",
".",
"join",
"}",
"}",
"if",
"@config",
".",
"delay_joins",
".",
"is_a?",
"(",
"Symbol",
")",
"@join_handler",
"=",
"join_handler",
"=",
"on",
"(",
"@config",
".",
"delay_joins",
")",
"{",
"join_handler",
".",
"unregister",
"join_lambda",
".",
"call",
"}",
"else",
"@join_timer",
"=",
"Timer",
".",
"new",
"(",
"self",
",",
"interval",
":",
"@config",
".",
"delay_joins",
",",
"shots",
":",
"1",
")",
"{",
"join_lambda",
".",
"call",
"}",
"end",
"@modes",
"=",
"[",
"]",
"@loggers",
".",
"info",
"\"Connecting to #{@config.server}:#{@config.port}\"",
"@irc",
"=",
"IRC",
".",
"new",
"(",
"self",
")",
"@irc",
".",
"start",
"if",
"@config",
".",
"reconnect",
"&&",
"!",
"@quitting",
"# double the delay for each unsuccesful reconnection attempt",
"if",
"@last_connection_was_successful",
"@reconnects",
"=",
"0",
"@last_connection_was_successful",
"=",
"false",
"else",
"@reconnects",
"+=",
"1",
"end",
"# Throttle reconnect attempts",
"wait",
"=",
"2",
"**",
"@reconnects",
"wait",
"=",
"@config",
".",
"max_reconnect_delay",
"if",
"wait",
">",
"@config",
".",
"max_reconnect_delay",
"@loggers",
".",
"info",
"\"Waiting #{wait} seconds before reconnecting\"",
"start_time",
"=",
"Time",
".",
"now",
"while",
"!",
"@quitting",
"&&",
"(",
"Time",
".",
"now",
"-",
"start_time",
")",
"<",
"wait",
"sleep",
"1",
"end",
"end",
"end",
"while",
"@config",
".",
"reconnect",
"and",
"not",
"@quitting",
"end"
] | 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 the next nick or append an
# underscore if no more nicks are left
new_index = nicks.index(base) + 1
if nicks[new_index]
new_nick = nicks[new_index]
else
new_nick = base + "_"
end
end
else
# if we have no base, try the first possible nick
new_nick = @config.nicks ? @config.nicks.first : @config.nick
end
@config.nick = new_nick
end | 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 the next nick or append an
# underscore if no more nicks are left
new_index = nicks.index(base) + 1
if nicks[new_index]
new_nick = nicks[new_index]
else
new_nick = base + "_"
end
end
else
# if we have no base, try the first possible nick
new_nick = @config.nicks ? @config.nicks.first : @config.nick
end
@config.nick = new_nick
end | [
"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 the next nick or append an",
"# underscore if no more nicks are left",
"new_index",
"=",
"nicks",
".",
"index",
"(",
"base",
")",
"+",
"1",
"if",
"nicks",
"[",
"new_index",
"]",
"new_nick",
"=",
"nicks",
"[",
"new_index",
"]",
"else",
"new_nick",
"=",
"base",
"+",
"\"_\"",
"end",
"end",
"else",
"# if we have no base, try the first possible nick",
"new_nick",
"=",
"@config",
".",
"nicks",
"?",
"@config",
".",
"nicks",
".",
"first",
":",
"@config",
".",
"nick",
"end",
"@config",
".",
"nick",
"=",
"new_nick",
"end"
] | 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",
")",
".",
"map",
"{",
"|",
"link",
"|",
"link",
".",
"options",
"[",
":as",
"]",
"?",
"{",
"link",
".",
"rel",
"=>",
"{",
"'as'",
"=>",
"link",
".",
"options",
"[",
":as",
"]",
"}",
"}",
":",
"link",
".",
"rel",
"}",
"}",
"end"
] | 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
end
end | 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
end
end | [
"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",
"end",
"end"
] | 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",
"::",
"InvalidOptions",
".",
"new",
"(",
"key",
",",
"valid_options",
")",
"end",
"end",
"true",
"end"
] | 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 = current_crumb?(path, crumb.match)
yield(Loaf::Breadcrumb[name, path, current])
end
end | 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 = current_crumb?(path, crumb.match)
yield(Loaf::Breadcrumb[name, path, current])
end
end | [
"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",
"=",
"current_crumb?",
"(",
"path",
",",
"crumb",
".",
"match",
")",
"yield",
"(",
"Loaf",
"::",
"Breadcrumb",
"[",
"name",
",",
"path",
",",
"current",
"]",
")",
"end",
"end"
] | 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",
"(",
"options",
"[",
":default",
"]",
")",
"options",
"[",
":default",
"]",
"<<",
"title",
"if",
"options",
"[",
":default",
"]",
".",
"empty?",
"I18n",
".",
"t",
"(",
"title",
".",
"to_s",
",",
"options",
")",
"end"
] | 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{hostname=foo|bar}-debian8-32"
#
# Which we can then simply split on - into:
# ["centos6", "64m{hostname=foo|bar}", "debian8", "32"]
#
# And then finally turn the | back into - now that we've
# properly decomposed the spec string:
# ["centos6", "64m{hostname=foo-bar}", "debian8", "32"]
#
# NOTE we've specifically chosen to use the pipe character |
# due to its unlikely occurrence in the user input string.
spec = String.new(layout_spec) # Copy so we can replace characters inline
within_braces = false
spec.chars.each_with_index do |char, index|
case char
when '{'
within_braces = true
when '}'
within_braces = false
when '-'
spec[index] = '|' if within_braces
end
end
tokens = spec.split('-')
tokens.map { |t| t.gsub('|', '-') }
end | 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{hostname=foo|bar}-debian8-32"
#
# Which we can then simply split on - into:
# ["centos6", "64m{hostname=foo|bar}", "debian8", "32"]
#
# And then finally turn the | back into - now that we've
# properly decomposed the spec string:
# ["centos6", "64m{hostname=foo-bar}", "debian8", "32"]
#
# NOTE we've specifically chosen to use the pipe character |
# due to its unlikely occurrence in the user input string.
spec = String.new(layout_spec) # Copy so we can replace characters inline
within_braces = false
spec.chars.each_with_index do |char, index|
case char
when '{'
within_braces = true
when '}'
within_braces = false
when '-'
spec[index] = '|' if within_braces
end
end
tokens = spec.split('-')
tokens.map { |t| t.gsub('|', '-') }
end | [
"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{hostname=foo|bar}-debian8-32\"",
"#",
"# Which we can then simply split on - into:",
"# [\"centos6\", \"64m{hostname=foo|bar}\", \"debian8\", \"32\"]",
"#",
"# And then finally turn the | back into - now that we've",
"# properly decomposed the spec string:",
"# [\"centos6\", \"64m{hostname=foo-bar}\", \"debian8\", \"32\"]",
"#",
"# NOTE we've specifically chosen to use the pipe character |",
"# due to its unlikely occurrence in the user input string.",
"spec",
"=",
"String",
".",
"new",
"(",
"layout_spec",
")",
"# Copy so we can replace characters inline",
"within_braces",
"=",
"false",
"spec",
".",
"chars",
".",
"each_with_index",
"do",
"|",
"char",
",",
"index",
"|",
"case",
"char",
"when",
"'{'",
"within_braces",
"=",
"true",
"when",
"'}'",
"within_braces",
"=",
"false",
"when",
"'-'",
"spec",
"[",
"index",
"]",
"=",
"'|'",
"if",
"within_braces",
"end",
"end",
"tokens",
"=",
"spec",
".",
"split",
"(",
"'-'",
")",
"tokens",
".",
"map",
"{",
"|",
"t",
"|",
"t",
".",
"gsub",
"(",
"'|'",
",",
"'-'",
")",
"}",
"end"
] | 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 define arbitrary key-values on a node.
@param spec [String] Well-formatted string specification of the hosts to
generate. For example `"centos6-64m-debian8-32a"`.
@returns [Array<String>] Input string split into substrings suitable for
processing by the generator. For example
`["centos6", "64m", "debian8", "32a"]`. | [
"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
# substring to determine a course of action to modify the primary
# object. The `object_depth` object tracks which current object is
# being modified, and pops it off the end of the array when that
# data structure is completed.
#
# This algorithm would also support a base array, but since there
# is no need for that functionality, we just assume the string is
# always a representation of a hash.
loop do
blob = stringscan.scan_until(/\[|{|}|\]|,/)
break if blob.nil?
if stringscan.pos() == 1
object = {}
object_depth.push(object)
next
end
current_type = object_depth[current_depth].class
current_object = object_depth[current_depth]
if blob == '['
current_object.push([])
object_depth.push(current_object.last)
current_depth = current_depth.next
next
end
if blob.start_with?('{')
current_object.push({})
object_depth.push(current_object.last)
current_depth = current_depth.next
next
end
if blob == ']' or blob == '}'
object_depth.pop
current_depth = current_depth.pred
next
end
# When there is assignment happening, we need to create a new
# corresponding data structure, add it to the object depth, and
# then change the current depth
if blob[-2] == '='
raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError unless blob.end_with?('{','[')
if blob[-1] == '{'
current_object[blob[0..-3]] = {}
else
current_object[blob[0..-3]] = []
end
object_depth.push(current_object[blob[0..-3]])
current_depth = current_depth.next
next
end
if blob[-1] == '}'
raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError if blob.count('=') != 1
key_pair = blob[0..-2].split('=')
raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError if key_pair.size != 2
key_pair.each do |element|
raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError if element.empty?
end
current_object[key_pair[0]] = key_pair[1]
object_depth.pop
current_depth = current_depth.pred
next
end
if blob == ','
next
end
if blob[-1] == ','
if current_type == Hash
key_pair = blob[0..-2].split('=')
raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError if key_pair.size != 2
key_pair.each do |element|
raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError if element.empty?
end
current_object[key_pair[0]] = key_pair[1]
next
elsif current_type == Array
current_object.push(blob[0..-2])
next
end
end
if blob[-1] == ']'
current_object.push(blob[0..-2])
object_depth.pop
current_depth = current_depth.pred
next
end
end
object
rescue Exception => e
raise BeakerHostGenerator::Exceptions::InvalidNodeSpecError,
"Malformed host settings: #{host_settings}"
end | 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
# substring to determine a course of action to modify the primary
# object. The `object_depth` object tracks which current object is
# being modified, and pops it off the end of the array when that
# data structure is completed.
#
# This algorithm would also support a base array, but since there
# is no need for that functionality, we just assume the string is
# always a representation of a hash.
loop do
blob = stringscan.scan_until(/\[|{|}|\]|,/)
break if blob.nil?
if stringscan.pos() == 1
object = {}
object_depth.push(object)
next
end
current_type = object_depth[current_depth].class
current_object = object_depth[current_depth]
if blob == '['
current_object.push([])
object_depth.push(current_object.last)
current_depth = current_depth.next
next
end
if blob.start_with?('{')
current_object.push({})
object_depth.push(current_object.last)
current_depth = current_depth.next
next
end
if blob == ']' or blob == '}'
object_depth.pop
current_depth = current_depth.pred
next
end
# When there is assignment happening, we need to create a new
# corresponding data structure, add it to the object depth, and
# then change the current depth
if blob[-2] == '='
raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError unless blob.end_with?('{','[')
if blob[-1] == '{'
current_object[blob[0..-3]] = {}
else
current_object[blob[0..-3]] = []
end
object_depth.push(current_object[blob[0..-3]])
current_depth = current_depth.next
next
end
if blob[-1] == '}'
raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError if blob.count('=') != 1
key_pair = blob[0..-2].split('=')
raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError if key_pair.size != 2
key_pair.each do |element|
raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError if element.empty?
end
current_object[key_pair[0]] = key_pair[1]
object_depth.pop
current_depth = current_depth.pred
next
end
if blob == ','
next
end
if blob[-1] == ','
if current_type == Hash
key_pair = blob[0..-2].split('=')
raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError if key_pair.size != 2
key_pair.each do |element|
raise Beaker::HostGenerator::Exceptions::InvalidNodeSpecError if element.empty?
end
current_object[key_pair[0]] = key_pair[1]
next
elsif current_type == Array
current_object.push(blob[0..-2])
next
end
end
if blob[-1] == ']'
current_object.push(blob[0..-2])
object_depth.pop
current_depth = current_depth.pred
next
end
end
object
rescue Exception => e
raise BeakerHostGenerator::Exceptions::InvalidNodeSpecError,
"Malformed host settings: #{host_settings}"
end | [
"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",
"# substring to determine a course of action to modify the primary",
"# object. The `object_depth` object tracks which current object is",
"# being modified, and pops it off the end of the array when that",
"# data structure is completed.",
"#",
"# This algorithm would also support a base array, but since there",
"# is no need for that functionality, we just assume the string is",
"# always a representation of a hash.",
"loop",
"do",
"blob",
"=",
"stringscan",
".",
"scan_until",
"(",
"/",
"\\[",
"\\]",
"/",
")",
"break",
"if",
"blob",
".",
"nil?",
"if",
"stringscan",
".",
"pos",
"(",
")",
"==",
"1",
"object",
"=",
"{",
"}",
"object_depth",
".",
"push",
"(",
"object",
")",
"next",
"end",
"current_type",
"=",
"object_depth",
"[",
"current_depth",
"]",
".",
"class",
"current_object",
"=",
"object_depth",
"[",
"current_depth",
"]",
"if",
"blob",
"==",
"'['",
"current_object",
".",
"push",
"(",
"[",
"]",
")",
"object_depth",
".",
"push",
"(",
"current_object",
".",
"last",
")",
"current_depth",
"=",
"current_depth",
".",
"next",
"next",
"end",
"if",
"blob",
".",
"start_with?",
"(",
"'{'",
")",
"current_object",
".",
"push",
"(",
"{",
"}",
")",
"object_depth",
".",
"push",
"(",
"current_object",
".",
"last",
")",
"current_depth",
"=",
"current_depth",
".",
"next",
"next",
"end",
"if",
"blob",
"==",
"']'",
"or",
"blob",
"==",
"'}'",
"object_depth",
".",
"pop",
"current_depth",
"=",
"current_depth",
".",
"pred",
"next",
"end",
"# When there is assignment happening, we need to create a new",
"# corresponding data structure, add it to the object depth, and",
"# then change the current depth",
"if",
"blob",
"[",
"-",
"2",
"]",
"==",
"'='",
"raise",
"Beaker",
"::",
"HostGenerator",
"::",
"Exceptions",
"::",
"InvalidNodeSpecError",
"unless",
"blob",
".",
"end_with?",
"(",
"'{'",
",",
"'['",
")",
"if",
"blob",
"[",
"-",
"1",
"]",
"==",
"'{'",
"current_object",
"[",
"blob",
"[",
"0",
"..",
"-",
"3",
"]",
"]",
"=",
"{",
"}",
"else",
"current_object",
"[",
"blob",
"[",
"0",
"..",
"-",
"3",
"]",
"]",
"=",
"[",
"]",
"end",
"object_depth",
".",
"push",
"(",
"current_object",
"[",
"blob",
"[",
"0",
"..",
"-",
"3",
"]",
"]",
")",
"current_depth",
"=",
"current_depth",
".",
"next",
"next",
"end",
"if",
"blob",
"[",
"-",
"1",
"]",
"==",
"'}'",
"raise",
"Beaker",
"::",
"HostGenerator",
"::",
"Exceptions",
"::",
"InvalidNodeSpecError",
"if",
"blob",
".",
"count",
"(",
"'='",
")",
"!=",
"1",
"key_pair",
"=",
"blob",
"[",
"0",
"..",
"-",
"2",
"]",
".",
"split",
"(",
"'='",
")",
"raise",
"Beaker",
"::",
"HostGenerator",
"::",
"Exceptions",
"::",
"InvalidNodeSpecError",
"if",
"key_pair",
".",
"size",
"!=",
"2",
"key_pair",
".",
"each",
"do",
"|",
"element",
"|",
"raise",
"Beaker",
"::",
"HostGenerator",
"::",
"Exceptions",
"::",
"InvalidNodeSpecError",
"if",
"element",
".",
"empty?",
"end",
"current_object",
"[",
"key_pair",
"[",
"0",
"]",
"]",
"=",
"key_pair",
"[",
"1",
"]",
"object_depth",
".",
"pop",
"current_depth",
"=",
"current_depth",
".",
"pred",
"next",
"end",
"if",
"blob",
"==",
"','",
"next",
"end",
"if",
"blob",
"[",
"-",
"1",
"]",
"==",
"','",
"if",
"current_type",
"==",
"Hash",
"key_pair",
"=",
"blob",
"[",
"0",
"..",
"-",
"2",
"]",
".",
"split",
"(",
"'='",
")",
"raise",
"Beaker",
"::",
"HostGenerator",
"::",
"Exceptions",
"::",
"InvalidNodeSpecError",
"if",
"key_pair",
".",
"size",
"!=",
"2",
"key_pair",
".",
"each",
"do",
"|",
"element",
"|",
"raise",
"Beaker",
"::",
"HostGenerator",
"::",
"Exceptions",
"::",
"InvalidNodeSpecError",
"if",
"element",
".",
"empty?",
"end",
"current_object",
"[",
"key_pair",
"[",
"0",
"]",
"]",
"=",
"key_pair",
"[",
"1",
"]",
"next",
"elsif",
"current_type",
"==",
"Array",
"current_object",
".",
"push",
"(",
"blob",
"[",
"0",
"..",
"-",
"2",
"]",
")",
"next",
"end",
"end",
"if",
"blob",
"[",
"-",
"1",
"]",
"==",
"']'",
"current_object",
".",
"push",
"(",
"blob",
"[",
"0",
"..",
"-",
"2",
"]",
")",
"object_depth",
".",
"pop",
"current_depth",
"=",
"current_depth",
".",
"pred",
"next",
"end",
"end",
"object",
"rescue",
"Exception",
"=>",
"e",
"raise",
"BeakerHostGenerator",
"::",
"Exceptions",
"::",
"InvalidNodeSpecError",
",",
"\"Malformed host settings: #{host_settings}\"",
"end"
] | 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_value},list=[[list1, list2]]}".
Whitespace is expected to be properly quoted as it will not be treated
any different than non-whitespace characters.
Throws an exception of the string is malformed in any way.
@param host_settings [String] Non-nil user input string that defines host
specific settings.
@returns [Hash{String=>String|Array|Hash}] The host_settings string as a map. | [
"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",
"."
] | 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!",
"(",
"info",
"[",
"hypervisor",
"]",
")",
"end"
] | 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 hypervisor
implementations when generating host definitions.
@param [Integer] bhg_version The version of OS info to use.
@param [String] platform The OS platform to access from the OS info map.
@param [Symbol] hypervisor The symbol representing which hypervisor submap
to extract from the general OS info map.
@example Getting CentOS 6 64-bit information for the VMPooler hypervisor
Given the OS info map looks like:
...
'centos6-64' => {
:general => { 'platform' => 'el-6-x86_64' },
:vmpooler => { 'template' => 'centos-6-x86_64' }
}
...
Then get_platform_info(0, 'centos6-64', :vmpooler) returns:
{
'platform' => 'el-6-x86_64',
'template' => 'centos-6-x86_64'
} | [
"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",
"."
] | 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",
",",
"hosts",
"|",
"templates_hosts",
"[",
"template",
"]",
"=",
"hosts",
".",
"count",
"end",
"end"
] | 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", ...},
"redhat7-64-1"=>
{"template"=>"redhat-7-x86_64", ...},
"centos6-64-2"=>
{"template"=>"centos-6-x86_64", ...}},
...
}}
Returns the following map:
{"centos-6-x86_64"=>2, "redhat-7-x86_64"=>1} | [
"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)
if nodeid[ostype] == 1 and ostype != nil
raise "Error: no nodes generated for #{ostype}"
end
ostype = token
next
end
node_info = parse_node_info_token(token)
# Build node host name
platform = "#{ostype}-#{node_info['bits']}"
host_name = "#{platform}-#{nodeid[ostype]}"
node_info['platform'] = platform
node_info['ostype'] = ostype
node_info['nodeid'] = nodeid[ostype]
host_config = base_host_config(options)
# Delegate to the hypervisor
hypervisor = BeakerHostGenerator::Hypervisor.create(node_info, options)
host_config = hypervisor.generate_node(node_info, host_config, bhg_version)
config['CONFIG'].deep_merge!(hypervisor.global_config())
# Merge in any arbitrary key-value host settings. Treat the 'hostname'
# setting specially, and don't merge it in as an arbitrary setting.
arbitrary_settings = node_info['host_settings']
host_name = arbitrary_settings.delete('hostname') if
arbitrary_settings.has_key?('hostname')
host_config.merge!(arbitrary_settings)
if PE_USE_WIN32 && ostype =~ /windows/ && node_info['bits'] == "64"
host_config['ruby_arch'] = 'x86'
host_config['install_32'] = true
end
generate_host_roles!(host_config, node_info, options)
config['HOSTS'][host_name] = host_config
nodeid[ostype] += 1
end
# Merge in global configuration settings after the hypervisor defaults
if options[:global_config]
decoded = prepare(options[:global_config])
# Support for strings without '{}' was introduced, so just double
# check here to ensure that we pass in values surrounded by '{}'.
if !decoded.start_with?('{')
decoded = "{#{decoded}}"
end
global_config = settings_string_to_map(decoded)
config['CONFIG'].deep_merge!(global_config)
end
# Munge non-string scalar values into proper data types
unstringify_values!(config)
return config
end | 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)
if nodeid[ostype] == 1 and ostype != nil
raise "Error: no nodes generated for #{ostype}"
end
ostype = token
next
end
node_info = parse_node_info_token(token)
# Build node host name
platform = "#{ostype}-#{node_info['bits']}"
host_name = "#{platform}-#{nodeid[ostype]}"
node_info['platform'] = platform
node_info['ostype'] = ostype
node_info['nodeid'] = nodeid[ostype]
host_config = base_host_config(options)
# Delegate to the hypervisor
hypervisor = BeakerHostGenerator::Hypervisor.create(node_info, options)
host_config = hypervisor.generate_node(node_info, host_config, bhg_version)
config['CONFIG'].deep_merge!(hypervisor.global_config())
# Merge in any arbitrary key-value host settings. Treat the 'hostname'
# setting specially, and don't merge it in as an arbitrary setting.
arbitrary_settings = node_info['host_settings']
host_name = arbitrary_settings.delete('hostname') if
arbitrary_settings.has_key?('hostname')
host_config.merge!(arbitrary_settings)
if PE_USE_WIN32 && ostype =~ /windows/ && node_info['bits'] == "64"
host_config['ruby_arch'] = 'x86'
host_config['install_32'] = true
end
generate_host_roles!(host_config, node_info, options)
config['HOSTS'][host_name] = host_config
nodeid[ostype] += 1
end
# Merge in global configuration settings after the hypervisor defaults
if options[:global_config]
decoded = prepare(options[:global_config])
# Support for strings without '{}' was introduced, so just double
# check here to ensure that we pass in values surrounded by '{}'.
if !decoded.start_with?('{')
decoded = "{#{decoded}}"
end
global_config = settings_string_to_map(decoded)
config['CONFIG'].deep_merge!(global_config)
end
# Munge non-string scalar values into proper data types
unstringify_values!(config)
return config
end | [
"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",
")",
"if",
"nodeid",
"[",
"ostype",
"]",
"==",
"1",
"and",
"ostype",
"!=",
"nil",
"raise",
"\"Error: no nodes generated for #{ostype}\"",
"end",
"ostype",
"=",
"token",
"next",
"end",
"node_info",
"=",
"parse_node_info_token",
"(",
"token",
")",
"# Build node host name",
"platform",
"=",
"\"#{ostype}-#{node_info['bits']}\"",
"host_name",
"=",
"\"#{platform}-#{nodeid[ostype]}\"",
"node_info",
"[",
"'platform'",
"]",
"=",
"platform",
"node_info",
"[",
"'ostype'",
"]",
"=",
"ostype",
"node_info",
"[",
"'nodeid'",
"]",
"=",
"nodeid",
"[",
"ostype",
"]",
"host_config",
"=",
"base_host_config",
"(",
"options",
")",
"# Delegate to the hypervisor",
"hypervisor",
"=",
"BeakerHostGenerator",
"::",
"Hypervisor",
".",
"create",
"(",
"node_info",
",",
"options",
")",
"host_config",
"=",
"hypervisor",
".",
"generate_node",
"(",
"node_info",
",",
"host_config",
",",
"bhg_version",
")",
"config",
"[",
"'CONFIG'",
"]",
".",
"deep_merge!",
"(",
"hypervisor",
".",
"global_config",
"(",
")",
")",
"# Merge in any arbitrary key-value host settings. Treat the 'hostname'",
"# setting specially, and don't merge it in as an arbitrary setting.",
"arbitrary_settings",
"=",
"node_info",
"[",
"'host_settings'",
"]",
"host_name",
"=",
"arbitrary_settings",
".",
"delete",
"(",
"'hostname'",
")",
"if",
"arbitrary_settings",
".",
"has_key?",
"(",
"'hostname'",
")",
"host_config",
".",
"merge!",
"(",
"arbitrary_settings",
")",
"if",
"PE_USE_WIN32",
"&&",
"ostype",
"=~",
"/",
"/",
"&&",
"node_info",
"[",
"'bits'",
"]",
"==",
"\"64\"",
"host_config",
"[",
"'ruby_arch'",
"]",
"=",
"'x86'",
"host_config",
"[",
"'install_32'",
"]",
"=",
"true",
"end",
"generate_host_roles!",
"(",
"host_config",
",",
"node_info",
",",
"options",
")",
"config",
"[",
"'HOSTS'",
"]",
"[",
"host_name",
"]",
"=",
"host_config",
"nodeid",
"[",
"ostype",
"]",
"+=",
"1",
"end",
"# Merge in global configuration settings after the hypervisor defaults",
"if",
"options",
"[",
":global_config",
"]",
"decoded",
"=",
"prepare",
"(",
"options",
"[",
":global_config",
"]",
")",
"# Support for strings without '{}' was introduced, so just double",
"# check here to ensure that we pass in values surrounded by '{}'.",
"if",
"!",
"decoded",
".",
"start_with?",
"(",
"'{'",
")",
"decoded",
"=",
"\"{#{decoded}}\"",
"end",
"global_config",
"=",
"settings_string_to_map",
"(",
"decoded",
")",
"config",
"[",
"'CONFIG'",
"]",
".",
"deep_merge!",
"(",
"global_config",
")",
"end",
"# Munge non-string scalar values into proper data types",
"unstringify_values!",
"(",
"config",
")",
"return",
"config",
"end"
] | 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
hypervisor or OS info version.
@returns [Hash] A complete Ruby map as defining the HOSTS and CONFIG
sections as required by Beaker. | [
"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] == @default_lang && lang != @active_lang
approved[url] = doc
@file_langs[url] = lang
end
approved.values
end | 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] == @default_lang && lang != @active_lang
approved[url] = doc
@file_langs[url] = lang
end
approved.values
end | [
"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",
"]",
"==",
"@default_lang",
"&&",
"lang",
"!=",
"@active_lang",
"approved",
"[",
"url",
"]",
"=",
"doc",
"@file_langs",
"[",
"url",
"]",
"=",
"lang",
"end",
"approved",
".",
"values",
"end"
] | 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_regex, url)
end
end
end | 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_regex, url)
end
end
end | [
"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_regex",
",",
"url",
")",
"end",
"end",
"end"
] | 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",
"/",
",",
"'.md+erb'",
")",
"args",
".",
"unshift",
"(",
"path",
")",
"end",
"return",
"original_extract_handler_and_format_and_variant",
"(",
"args",
")",
"end"
] | 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",
"]",
"||=",
"{",
"}",
"options",
"[",
":headers",
"]",
"=",
"@headers",
".",
"merge",
"(",
"options",
"[",
":headers",
"]",
")",
"Request",
".",
"new",
"(",
"@connection",
",",
"method",
",",
"@path_prefix",
"+",
"path",
",",
"options",
")",
".",
"request",
"end"
] | 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 the request
@param path [String] the URL (without the base domain) to make the request to
@param options [Hash] the options hash | [
"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[:params].merge(after: after_cursor)
response = @service.list(@options.merge(after: after_cursor))
end
end.lazy
end | 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[:params].merge(after: after_cursor)
response = @service.list(@options.merge(after: after_cursor))
end
end.lazy
end | [
"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",
"[",
":params",
"]",
".",
"merge",
"(",
"after",
":",
"after_cursor",
")",
"response",
"=",
"@service",
".",
"list",
"(",
"@options",
".",
"merge",
"(",
"after",
":",
"after_cursor",
")",
")",
"end",
"end",
".",
"lazy",
"end"
] | 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",
".",
"merge",
"(",
"options",
")",
"opts",
"[",
":default_headers",
"]",
"=",
"default_options",
"[",
":default_headers",
"]",
".",
"merge",
"(",
"options",
"[",
":default_headers",
"]",
")",
"opts",
"end"
] | 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, end_index)
last_match = [start_index, end_index]
end
extracted_ruby << file_text[last_match.last..-1].gsub(/./, ' ')
extracted_ruby.gsub!(/[^\S\r\n]+$/, '')
# if we replaced <%== with <%= raw, try to shift the columns back to the
# left so they match the original again
extracted_ruby.gsub!(/ raw/, 'raw')
extracted_ruby
end | 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, end_index)
last_match = [start_index, end_index]
end
extracted_ruby << file_text[last_match.last..-1].gsub(/./, ' ')
extracted_ruby.gsub!(/[^\S\r\n]+$/, '')
# if we replaced <%== with <%= raw, try to shift the columns back to the
# left so they match the original again
extracted_ruby.gsub!(/ raw/, 'raw')
extracted_ruby
end | [
"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",
",",
"end_index",
")",
"last_match",
"=",
"[",
"start_index",
",",
"end_index",
"]",
"end",
"extracted_ruby",
"<<",
"file_text",
"[",
"last_match",
".",
"last",
"..",
"-",
"1",
"]",
".",
"gsub",
"(",
"/",
"/",
",",
"' '",
")",
"extracted_ruby",
".",
"gsub!",
"(",
"/",
"\\S",
"\\r",
"\\n",
"/",
",",
"''",
")",
"# if we replaced <%== with <%= raw, try to shift the columns back to the",
"# left so they match the original again",
"extracted_ruby",
".",
"gsub!",
"(",
"/",
"/",
",",
"'raw'",
")",
"extracted_ruby",
"end"
] | 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",
"# 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"
] | 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",
"|",
"dir",
"|",
"analyze",
"(",
"dir",
",",
"files_or_dirs",
")",
"end",
"end",
"end"
] | 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['originalAmount']
transaction.originalTxnTime = options['originalTxnTime']
transaction.originalSystemTraceId = options['originalSystemTraceId']
transaction.originalSequenceNumber = options['originalSequenceNumber']
return transaction
end | 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['originalAmount']
transaction.originalTxnTime = options['originalTxnTime']
transaction.originalSystemTraceId = options['originalSystemTraceId']
transaction.originalSequenceNumber = options['originalSequenceNumber']
return transaction
end | [
"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",
"[",
"'originalAmount'",
"]",
"transaction",
".",
"originalTxnTime",
"=",
"options",
"[",
"'originalTxnTime'",
"]",
"transaction",
".",
"originalSystemTraceId",
"=",
"options",
"[",
"'originalSystemTraceId'",
"]",
"transaction",
".",
"originalSequenceNumber",
"=",
"options",
"[",
"'originalSequenceNumber'",
"]",
"return",
"transaction",
"end"
] | 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']
transaction.submerchantName = options['submerchantName']
transaction.fundsTransferId = options['fundsTransferId']
transaction.amount = options['amount']
transaction.card = Card.from_hash(options)
transaction.token = CardToken.from_hash(options,'token')
transaction.paypage = CardPaypage.from_hash(options,'paypage')
return transaction
end | 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']
transaction.submerchantName = options['submerchantName']
transaction.fundsTransferId = options['fundsTransferId']
transaction.amount = options['amount']
transaction.card = Card.from_hash(options)
transaction.token = CardToken.from_hash(options,'token')
transaction.paypage = CardPaypage.from_hash(options,'paypage')
return transaction
end | [
"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'",
"]",
"transaction",
".",
"submerchantName",
"=",
"options",
"[",
"'submerchantName'",
"]",
"transaction",
".",
"fundsTransferId",
"=",
"options",
"[",
"'fundsTransferId'",
"]",
"transaction",
".",
"amount",
"=",
"options",
"[",
"'amount'",
"]",
"transaction",
".",
"card",
"=",
"Card",
".",
"from_hash",
"(",
"options",
")",
"transaction",
".",
"token",
"=",
"CardToken",
".",
"from_hash",
"(",
"options",
",",
"'token'",
")",
"transaction",
".",
"paypage",
"=",
"CardPaypage",
".",
"from_hash",
"(",
"options",
",",
"'paypage'",
")",
"return",
"transaction",
"end"
] | 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 old time's sake
f.puts '</litleRequest>'
end
#rename the requests file
File.rename(@path_to_request, @path_to_request + COMPLETE_FILE_SUFFIX)
#we don't need the master batch file anymore
File.delete(@path_to_batches)
end | 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 old time's sake
f.puts '</litleRequest>'
end
#rename the requests file
File.rename(@path_to_request, @path_to_request + COMPLETE_FILE_SUFFIX)
#we don't need the master batch file anymore
File.delete(@path_to_batches)
end | [
"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 old time's sake",
"f",
".",
"puts",
"'</litleRequest>'",
"end",
"#rename the requests file",
"File",
".",
"rename",
"(",
"@path_to_request",
",",
"@path_to_request",
"+",
"COMPLETE_FILE_SUFFIX",
")",
"#we don't need the master batch file anymore",
"File",
".",
"delete",
"(",
"@path_to_batches",
")",
"end"
] | 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",
"tags",
"."
] | 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.to_s
self
end | 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.to_s
self
end | [
"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",
".",
"to_s",
"self",
"end"
] | 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",
")",
"# 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"
] | 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",
"[",
"k",
"]",
"+=",
"v",
"else",
"self",
"[",
"k",
"]",
"=",
"v",
"end",
"end",
"end",
"self",
"end"
] | 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 configuration hashes.
@return [Config] The final configuration value. | [
"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_token
raise "INQ_GITHUB_USERNAME environment variable is not set" \
unless gh_username
load({
"sources/github" => {
"username" => gh_username,
"token" => gh_token,
},
})
end | 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_token
raise "INQ_GITHUB_USERNAME environment variable is not set" \
unless gh_username
load({
"sources/github" => {
"username" => gh_username,
"token" => gh_token,
},
})
end | [
"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_token",
"raise",
"\"INQ_GITHUB_USERNAME environment variable is not set\"",
"unless",
"gh_username",
"load",
"(",
"{",
"\"sources/github\"",
"=>",
"{",
"\"username\"",
"=>",
"gh_username",
",",
"\"token\"",
"=>",
"gh_token",
",",
"}",
",",
"}",
")",
"end"
] | 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",
".",
"tr",
"(",
"\"/\"",
",",
"\"-\"",
")",
",",
"repository",
":",
"repository",
",",
"date",
":",
"end_date",
",",
"friendly_date",
":",
"friendly_end_date",
",",
"}",
"end"
] | 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 generates a warning, but
# we're okay with it, so we wrap it with silence_warnings {}.
filename = silence_warnings {
tmp_filename = report_config["filename"] || defaults[format]["filename"]
tmp_filename % metadata(repo)
}
directory = report_config["directory"] || defaults[format]["directory"]
file = File.join(directory, filename)
# Export +report+ to the specified +format+ with the specified
# +frontmatter+.
frontmatter = report_config["frontmatter"] || {}
if defaults.has_key?(format) && defaults[format].has_key?("frontmatter")
frontmatter = defaults[format]["frontmatter"].merge(frontmatter)
end
frontmatter = nil if frontmatter == {}
export = @reports[repo].send("to_#{format}", frontmatter)
results[file] = export
}
}
results
end | 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 generates a warning, but
# we're okay with it, so we wrap it with silence_warnings {}.
filename = silence_warnings {
tmp_filename = report_config["filename"] || defaults[format]["filename"]
tmp_filename % metadata(repo)
}
directory = report_config["directory"] || defaults[format]["directory"]
file = File.join(directory, filename)
# Export +report+ to the specified +format+ with the specified
# +frontmatter+.
frontmatter = report_config["frontmatter"] || {}
if defaults.has_key?(format) && defaults[format].has_key?("frontmatter")
frontmatter = defaults[format]["frontmatter"].merge(frontmatter)
end
frontmatter = nil if frontmatter == {}
export = @reports[repo].send("to_#{format}", frontmatter)
results[file] = export
}
}
results
end | [
"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 generates a warning, but",
"# we're okay with it, so we wrap it with silence_warnings {}.",
"filename",
"=",
"silence_warnings",
"{",
"tmp_filename",
"=",
"report_config",
"[",
"\"filename\"",
"]",
"||",
"defaults",
"[",
"format",
"]",
"[",
"\"filename\"",
"]",
"tmp_filename",
"%",
"metadata",
"(",
"repo",
")",
"}",
"directory",
"=",
"report_config",
"[",
"\"directory\"",
"]",
"||",
"defaults",
"[",
"format",
"]",
"[",
"\"directory\"",
"]",
"file",
"=",
"File",
".",
"join",
"(",
"directory",
",",
"filename",
")",
"# Export +report+ to the specified +format+ with the specified",
"# +frontmatter+.",
"frontmatter",
"=",
"report_config",
"[",
"\"frontmatter\"",
"]",
"||",
"{",
"}",
"if",
"defaults",
".",
"has_key?",
"(",
"format",
")",
"&&",
"defaults",
"[",
"format",
"]",
".",
"has_key?",
"(",
"\"frontmatter\"",
")",
"frontmatter",
"=",
"defaults",
"[",
"format",
"]",
"[",
"\"frontmatter\"",
"]",
".",
"merge",
"(",
"frontmatter",
")",
"end",
"frontmatter",
"=",
"nil",
"if",
"frontmatter",
"==",
"{",
"}",
"export",
"=",
"@reports",
"[",
"repo",
"]",
".",
"send",
"(",
"\"to_#{format}\"",
",",
"frontmatter",
")",
"results",
"[",
"file",
"]",
"=",
"export",
"}",
"}",
"results",
"end"
] | 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",
"# Check to see if precompile list has been updated",
"precompiled_assets",
"(",
"true",
")",
".",
"include?",
"(",
"logical_path",
")",
"else",
"false",
"end",
"end"
] | 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",
"(",
":logical_path",
")",
".",
"to_set",
"end"
] | 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",
"or",
"test",
"case",
"."
] | 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")
else
send "handle_#{type}", item
end
self
end | 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")
else
send "handle_#{type}", item
end
self
end | [
"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\"",
")",
"else",
"send",
"\"handle_#{type}\"",
",",
"item",
"end",
"self",
"end"
] | 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 ||= hashes.each_with_index.map do |hash, index|
weight = weights[index]
Hash[hash.map {|k, v| [k, (v * weight)]}]
end
end
@computed_values
end | 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 ||= hashes.each_with_index.map do |hash, index|
weight = weights[index]
Hash[hash.map {|k, v| [k, (v * weight)]}]
end
end
@computed_values
end | [
"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",
"||=",
"hashes",
".",
"each_with_index",
".",
"map",
"do",
"|",
"hash",
",",
"index",
"|",
"weight",
"=",
"weights",
"[",
"index",
"]",
"Hash",
"[",
"hash",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"[",
"k",
",",
"(",
"v",
"*",
"weight",
")",
"]",
"}",
"]",
"end",
"end",
"@computed_values",
"end"
] | 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::CommandError, "ERR value is not a valid float"
end | 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::CommandError, "ERR value is not a valid float"
end | [
"def",
"_floatify",
"(",
"str",
",",
"increment",
"=",
"true",
")",
"if",
"(",
"(",
"inf",
"=",
"str",
".",
"to_s",
".",
"match",
"(",
"/",
"/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",
"::",
"CommandError",
",",
"\"ERR value is not a valid float\"",
"end"
] | 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?",
"(",
"DateTime",
")",
"timeuuid_generator",
".",
"at",
"(",
"Time",
".",
"at",
"(",
"value",
".",
"to_f",
")",
")",
"else",
"Type",
"::",
"Timeuuid",
".",
"instance",
".",
"cast",
"(",
"value",
")",
"end",
"end"
] | 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",
")",
"}",
"when",
":all",
"find_all",
"(",
"options",
",",
"block",
")",
"when",
":first",
"find_first",
"(",
"options",
")",
"end",
"end"
] | 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"
The <b>command</b> may be a record index, :all, or :first.
<b>options</b> is optional and, if specified, should be a hash where the
keys correspond to column names in the database. The values will be
matched exactly with the value in the database. If you specify more
than one key, all values must match in order for the record to be
returned. The equivalent SQL would be "WHERE key1 = 'value1'
AND key2 = 'value2'".
@param [Integer, Symbol] command
@param [optional, Hash] options Hash of search parameters
@yield [optional, DBF::Record, NilClass] | [
"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",
")",
"end"
] | 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",
"<<",
"column_names",
"each",
"{",
"|",
"record",
"|",
"csv",
"<<",
"record",
".",
"to_a",
"}",
"end"
] | 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-Language`
header.
@return [Response], which responds to `status`, `headers`, and `body`. | [
"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",
"]",
"=",
"Redis",
"::",
"Namespace",
".",
"new",
"(",
"DEFAULT_NAMESPACE",
",",
"redis",
":",
"client",
")",
"end",
"end"
] | 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",
"tries",
"+=",
"1",
"retry",
"else",
"raise",
"end",
"end"
] | 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["directory"] = components_directory
if json.reject{ |key| ['lib', 'vendor'].include? key }.empty?
folders = json.keys
else
raise "Assuming a standard bower package but cannot find the required 'name' key" unless !!json['name']
folders = ['vendor']
end
folders.each do |dir|
data = json[dir]
# Assume using standard bower.json if folder name is not found
data = json if data.nil?
# Check folder existence and create?
dir = File.join(root_path, dir, "assets")
FileUtils.mkdir_p dir unless File.directory? dir
# Go in to dir to act
Dir.chdir(dir) do
# Remove old components
FileUtils.rm_rf("#{components_directory}/*") if remove_components
# Create bower.json
File.open("bower.json", "w") do |f|
f.write(data.to_json)
end
# Create .bowerrc
File.open(".bowerrc", "w") do |f|
f.write(JSON.pretty_generate(dot_bowerrc))
end
# Run command
yield if block_given?
# Remove bower.json
FileUtils.rm("bower.json")
# Remove .bowerrc
FileUtils.rm(".bowerrc")
end if data && !data["dependencies"].empty?
end
end | 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["directory"] = components_directory
if json.reject{ |key| ['lib', 'vendor'].include? key }.empty?
folders = json.keys
else
raise "Assuming a standard bower package but cannot find the required 'name' key" unless !!json['name']
folders = ['vendor']
end
folders.each do |dir|
data = json[dir]
# Assume using standard bower.json if folder name is not found
data = json if data.nil?
# Check folder existence and create?
dir = File.join(root_path, dir, "assets")
FileUtils.mkdir_p dir unless File.directory? dir
# Go in to dir to act
Dir.chdir(dir) do
# Remove old components
FileUtils.rm_rf("#{components_directory}/*") if remove_components
# Create bower.json
File.open("bower.json", "w") do |f|
f.write(data.to_json)
end
# Create .bowerrc
File.open(".bowerrc", "w") do |f|
f.write(JSON.pretty_generate(dot_bowerrc))
end
# Run command
yield if block_given?
# Remove bower.json
FileUtils.rm("bower.json")
# Remove .bowerrc
FileUtils.rm(".bowerrc")
end if data && !data["dependencies"].empty?
end
end | [
"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",
"[",
"\"directory\"",
"]",
"=",
"components_directory",
"if",
"json",
".",
"reject",
"{",
"|",
"key",
"|",
"[",
"'lib'",
",",
"'vendor'",
"]",
".",
"include?",
"key",
"}",
".",
"empty?",
"folders",
"=",
"json",
".",
"keys",
"else",
"raise",
"\"Assuming a standard bower package but cannot find the required 'name' key\"",
"unless",
"!",
"!",
"json",
"[",
"'name'",
"]",
"folders",
"=",
"[",
"'vendor'",
"]",
"end",
"folders",
".",
"each",
"do",
"|",
"dir",
"|",
"data",
"=",
"json",
"[",
"dir",
"]",
"# Assume using standard bower.json if folder name is not found",
"data",
"=",
"json",
"if",
"data",
".",
"nil?",
"# Check folder existence and create?",
"dir",
"=",
"File",
".",
"join",
"(",
"root_path",
",",
"dir",
",",
"\"assets\"",
")",
"FileUtils",
".",
"mkdir_p",
"dir",
"unless",
"File",
".",
"directory?",
"dir",
"# Go in to dir to act",
"Dir",
".",
"chdir",
"(",
"dir",
")",
"do",
"# Remove old components",
"FileUtils",
".",
"rm_rf",
"(",
"\"#{components_directory}/*\"",
")",
"if",
"remove_components",
"# Create bower.json",
"File",
".",
"open",
"(",
"\"bower.json\"",
",",
"\"w\"",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"data",
".",
"to_json",
")",
"end",
"# Create .bowerrc",
"File",
".",
"open",
"(",
"\".bowerrc\"",
",",
"\"w\"",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"JSON",
".",
"pretty_generate",
"(",
"dot_bowerrc",
")",
")",
"end",
"# Run command",
"yield",
"if",
"block_given?",
"# Remove bower.json",
"FileUtils",
".",
"rm",
"(",
"\"bower.json\"",
")",
"# Remove .bowerrc",
"FileUtils",
".",
"rm",
"(",
"\".bowerrc\"",
")",
"end",
"if",
"data",
"&&",
"!",
"data",
"[",
"\"dependencies\"",
"]",
".",
"empty?",
"end",
"end"
] | 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",
"yield",
"ensure",
"self",
".",
"fixed_shard",
"=",
"old_fixed",
"self",
".",
"current_shard",
"=",
"old_shard",
"end"
] | 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] Shard object
@param shard [String, Numeric] Raw sharding id | [
"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",
"raise",
"err",
"end",
"err",
"end",
"end",
"end"
] | 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
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
end | [
"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",
"end"
] | 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.headers.each do |line|
hdr, val = line.split(":", 2)
val.strip! unless val.nil?
if @headers.key?(hdr)
@headers[hdr] = [@headers[hdr]] unless @headers[hdr].kind_of? Array
@headers[hdr] << val
else
@headers[hdr] = val
end
end
end | 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.headers.each do |line|
hdr, val = line.split(":", 2)
val.strip! unless val.nil?
if @headers.key?(hdr)
@headers[hdr] = [@headers[hdr]] unless @headers[hdr].kind_of? Array
@headers[hdr] << val
else
@headers[hdr] = val
end
end
end | [
"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",
".",
"headers",
".",
"each",
"do",
"|",
"line",
"|",
"hdr",
",",
"val",
"=",
"line",
".",
"split",
"(",
"\":\"",
",",
"2",
")",
"val",
".",
"strip!",
"unless",
"val",
".",
"nil?",
"if",
"@headers",
".",
"key?",
"(",
"hdr",
")",
"@headers",
"[",
"hdr",
"]",
"=",
"[",
"@headers",
"[",
"hdr",
"]",
"]",
"unless",
"@headers",
"[",
"hdr",
"]",
".",
"kind_of?",
"Array",
"@headers",
"[",
"hdr",
"]",
"<<",
"val",
"else",
"@headers",
"[",
"hdr",
"]",
"=",
"val",
"end",
"end",
"end"
] | 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\"",
"Request",
"::",
"AuthAny",
"else",
"raise",
"\"#{type.inspect} is an unknown authentication type\"",
"end",
"end"
] | 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",
".",
"downcase",
".",
"to_sym",
"end"
] | 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_path)
raise ArgumentError, "Can't read or write file #{path} (permission error)"
end
else
path = nil
end
# Apparently calling this with an empty string sets the cookie file,
# but calling it with a path to a writable file sets that file to be
# the cookie jar (new cookies are written there)
add_cookie_file(path.to_s)
self
end | 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_path)
raise ArgumentError, "Can't read or write file #{path} (permission error)"
end
else
path = nil
end
# Apparently calling this with an empty string sets the cookie file,
# but calling it with a path to a writable file sets that file to be
# the cookie jar (new cookies are written there)
add_cookie_file(path.to_s)
self
end | [
"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_path",
")",
"raise",
"ArgumentError",
",",
"\"Can't read or write file #{path} (permission error)\"",
"end",
"else",
"path",
"=",
"nil",
"end",
"# Apparently calling this with an empty string sets the cookie file,",
"# but calling it with a path to a writable file sets that file to be",
"# the cookie jar (new cookies are written there)",
"add_cookie_file",
"(",
"path",
".",
"to_s",
")",
"self",
"end"
] | 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 multiple times will add more files.
@todo the cookie jar and cookie file path options should be split
@param file_path[String] path to an existing cookie jar file, or nil to store cookies in memory
@return self | [
"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",
")",
"+",
"'='",
"+",
"urlencode",
"(",
"v",
".",
"to_s",
")",
"}",
".",
"join",
"(",
"'&'",
")",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/x-www-form-urlencoded'",
"end",
"request",
"(",
":post",
",",
"url",
",",
"headers",
",",
":data",
"=>",
"data",
")",
"end"
] | 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 request body from that file
@param headers[Hash] the hash of header keys to values
@return [Patron::Response] | [
"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",
"=>",
"true",
"}",
")",
"end"
] | 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 to values
@return [Patron::Response] | [
"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_encoding = options.fetch :automatic_content_encoding, self.automatic_content_encoding
req.timeout = options.fetch :timeout, self.timeout
req.connect_timeout = options.fetch :connect_timeout, self.connect_timeout
req.dns_cache_timeout = options.fetch :dns_cache_timeout, self.dns_cache_timeout
req.low_speed_time = options.fetch :low_speed_time, self.low_speed_time
req.low_speed_limit = options.fetch :low_speed_limit, self.low_speed_limit
req.force_ipv4 = options.fetch :force_ipv4, self.force_ipv4
req.max_redirects = options.fetch :max_redirects, self.max_redirects
req.username = options.fetch :username, self.username
req.password = options.fetch :password, self.password
req.proxy = options.fetch :proxy, self.proxy
req.proxy_type = options.fetch :proxy_type, self.proxy_type
req.auth_type = options.fetch :auth_type, self.auth_type
req.insecure = options.fetch :insecure, self.insecure
req.ssl_version = options.fetch :ssl_version, self.ssl_version
req.http_version = options.fetch :http_version, self.http_version
req.cacert = options.fetch :cacert, self.cacert
req.ignore_content_length = options.fetch :ignore_content_length, self.ignore_content_length
req.buffer_size = options.fetch :buffer_size, self.buffer_size
req.download_byte_limit = options.fetch :download_byte_limit, self.download_byte_limit
req.progress_callback = options.fetch :progress_callback, self.progress_callback
req.multipart = options[:multipart]
req.upload_data = options[:data]
req.file_name = options[:file]
base_url = self.base_url.to_s
url = url.to_s
raise ArgumentError, "Empty URL" if base_url.empty? && url.empty?
uri = URI.parse(base_url.empty? ? url : File.join(base_url, url))
query = uri.query.to_s.split('&')
query += options[:query].is_a?(Hash) ? Util.build_query_pairs_from_hash(options[:query]) : options[:query].to_s.split('&')
uri.query = query.join('&')
uri.query = nil if uri.query.empty?
url = uri.to_s
req.url = url
end
end | 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_encoding = options.fetch :automatic_content_encoding, self.automatic_content_encoding
req.timeout = options.fetch :timeout, self.timeout
req.connect_timeout = options.fetch :connect_timeout, self.connect_timeout
req.dns_cache_timeout = options.fetch :dns_cache_timeout, self.dns_cache_timeout
req.low_speed_time = options.fetch :low_speed_time, self.low_speed_time
req.low_speed_limit = options.fetch :low_speed_limit, self.low_speed_limit
req.force_ipv4 = options.fetch :force_ipv4, self.force_ipv4
req.max_redirects = options.fetch :max_redirects, self.max_redirects
req.username = options.fetch :username, self.username
req.password = options.fetch :password, self.password
req.proxy = options.fetch :proxy, self.proxy
req.proxy_type = options.fetch :proxy_type, self.proxy_type
req.auth_type = options.fetch :auth_type, self.auth_type
req.insecure = options.fetch :insecure, self.insecure
req.ssl_version = options.fetch :ssl_version, self.ssl_version
req.http_version = options.fetch :http_version, self.http_version
req.cacert = options.fetch :cacert, self.cacert
req.ignore_content_length = options.fetch :ignore_content_length, self.ignore_content_length
req.buffer_size = options.fetch :buffer_size, self.buffer_size
req.download_byte_limit = options.fetch :download_byte_limit, self.download_byte_limit
req.progress_callback = options.fetch :progress_callback, self.progress_callback
req.multipart = options[:multipart]
req.upload_data = options[:data]
req.file_name = options[:file]
base_url = self.base_url.to_s
url = url.to_s
raise ArgumentError, "Empty URL" if base_url.empty? && url.empty?
uri = URI.parse(base_url.empty? ? url : File.join(base_url, url))
query = uri.query.to_s.split('&')
query += options[:query].is_a?(Hash) ? Util.build_query_pairs_from_hash(options[:query]) : options[:query].to_s.split('&')
uri.query = query.join('&')
uri.query = nil if uri.query.empty?
url = uri.to_s
req.url = url
end
end | [
"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_encoding",
"=",
"options",
".",
"fetch",
":automatic_content_encoding",
",",
"self",
".",
"automatic_content_encoding",
"req",
".",
"timeout",
"=",
"options",
".",
"fetch",
":timeout",
",",
"self",
".",
"timeout",
"req",
".",
"connect_timeout",
"=",
"options",
".",
"fetch",
":connect_timeout",
",",
"self",
".",
"connect_timeout",
"req",
".",
"dns_cache_timeout",
"=",
"options",
".",
"fetch",
":dns_cache_timeout",
",",
"self",
".",
"dns_cache_timeout",
"req",
".",
"low_speed_time",
"=",
"options",
".",
"fetch",
":low_speed_time",
",",
"self",
".",
"low_speed_time",
"req",
".",
"low_speed_limit",
"=",
"options",
".",
"fetch",
":low_speed_limit",
",",
"self",
".",
"low_speed_limit",
"req",
".",
"force_ipv4",
"=",
"options",
".",
"fetch",
":force_ipv4",
",",
"self",
".",
"force_ipv4",
"req",
".",
"max_redirects",
"=",
"options",
".",
"fetch",
":max_redirects",
",",
"self",
".",
"max_redirects",
"req",
".",
"username",
"=",
"options",
".",
"fetch",
":username",
",",
"self",
".",
"username",
"req",
".",
"password",
"=",
"options",
".",
"fetch",
":password",
",",
"self",
".",
"password",
"req",
".",
"proxy",
"=",
"options",
".",
"fetch",
":proxy",
",",
"self",
".",
"proxy",
"req",
".",
"proxy_type",
"=",
"options",
".",
"fetch",
":proxy_type",
",",
"self",
".",
"proxy_type",
"req",
".",
"auth_type",
"=",
"options",
".",
"fetch",
":auth_type",
",",
"self",
".",
"auth_type",
"req",
".",
"insecure",
"=",
"options",
".",
"fetch",
":insecure",
",",
"self",
".",
"insecure",
"req",
".",
"ssl_version",
"=",
"options",
".",
"fetch",
":ssl_version",
",",
"self",
".",
"ssl_version",
"req",
".",
"http_version",
"=",
"options",
".",
"fetch",
":http_version",
",",
"self",
".",
"http_version",
"req",
".",
"cacert",
"=",
"options",
".",
"fetch",
":cacert",
",",
"self",
".",
"cacert",
"req",
".",
"ignore_content_length",
"=",
"options",
".",
"fetch",
":ignore_content_length",
",",
"self",
".",
"ignore_content_length",
"req",
".",
"buffer_size",
"=",
"options",
".",
"fetch",
":buffer_size",
",",
"self",
".",
"buffer_size",
"req",
".",
"download_byte_limit",
"=",
"options",
".",
"fetch",
":download_byte_limit",
",",
"self",
".",
"download_byte_limit",
"req",
".",
"progress_callback",
"=",
"options",
".",
"fetch",
":progress_callback",
",",
"self",
".",
"progress_callback",
"req",
".",
"multipart",
"=",
"options",
"[",
":multipart",
"]",
"req",
".",
"upload_data",
"=",
"options",
"[",
":data",
"]",
"req",
".",
"file_name",
"=",
"options",
"[",
":file",
"]",
"base_url",
"=",
"self",
".",
"base_url",
".",
"to_s",
"url",
"=",
"url",
".",
"to_s",
"raise",
"ArgumentError",
",",
"\"Empty URL\"",
"if",
"base_url",
".",
"empty?",
"&&",
"url",
".",
"empty?",
"uri",
"=",
"URI",
".",
"parse",
"(",
"base_url",
".",
"empty?",
"?",
"url",
":",
"File",
".",
"join",
"(",
"base_url",
",",
"url",
")",
")",
"query",
"=",
"uri",
".",
"query",
".",
"to_s",
".",
"split",
"(",
"'&'",
")",
"query",
"+=",
"options",
"[",
":query",
"]",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"Util",
".",
"build_query_pairs_from_hash",
"(",
"options",
"[",
":query",
"]",
")",
":",
"options",
"[",
":query",
"]",
".",
"to_s",
".",
"split",
"(",
"'&'",
")",
"uri",
".",
"query",
"=",
"query",
".",
"join",
"(",
"'&'",
")",
"uri",
".",
"query",
"=",
"nil",
"if",
"uri",
".",
"query",
".",
"empty?",
"url",
"=",
"uri",
".",
"to_s",
"req",
".",
"url",
"=",
"url",
"end",
"end"
] | 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 hash of headers, "Accept" will be automatically set to an empty string if not provided
@param options[Hash] any overriding options (will shadow the options from the Session object)
@return [Patron::Request] the request that will be passed to ++handle_request++ | [
"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",
"."
] | 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?/) 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?/) do |match|
preserve_border_whitespaces(match, default_border: ReverseMarkdown.config.tag_border) do
match.strip.sub('~~ ', '~~').sub(' ~~', '~~')
end
end
result.gsub(/\s?\[.*?\]\s?/) do |match|
preserve_border_whitespaces(match) do
match.strip.sub('[ ', '[').sub(' ]', ']')
end
end
end | 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?/) 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?/) do |match|
preserve_border_whitespaces(match, default_border: ReverseMarkdown.config.tag_border) do
match.strip.sub('~~ ', '~~').sub(' ~~', '~~')
end
end
result.gsub(/\s?\[.*?\]\s?/) do |match|
preserve_border_whitespaces(match) do
match.strip.sub('[ ', '[').sub(' ]', ']')
end
end
end | [
"def",
"clean_tag_borders",
"(",
"string",
")",
"result",
"=",
"string",
".",
"gsub",
"(",
"/",
"\\s",
"\\*",
"\\*",
"\\s",
"/",
")",
"do",
"|",
"match",
"|",
"preserve_border_whitespaces",
"(",
"match",
",",
"default_border",
":",
"ReverseMarkdown",
".",
"config",
".",
"tag_border",
")",
"do",
"match",
".",
"strip",
".",
"sub",
"(",
"'** '",
",",
"'**'",
")",
".",
"sub",
"(",
"' **'",
",",
"'**'",
")",
"end",
"end",
"result",
"=",
"result",
".",
"gsub",
"(",
"/",
"\\s",
"\\_",
"\\_",
"\\s",
"/",
")",
"do",
"|",
"match",
"|",
"preserve_border_whitespaces",
"(",
"match",
",",
"default_border",
":",
"ReverseMarkdown",
".",
"config",
".",
"tag_border",
")",
"do",
"match",
".",
"strip",
".",
"sub",
"(",
"'__ '",
",",
"'__'",
")",
".",
"sub",
"(",
"' __'",
",",
"'__'",
")",
"end",
"end",
"result",
"=",
"result",
".",
"gsub",
"(",
"/",
"\\s",
"\\s",
"/",
")",
"do",
"|",
"match",
"|",
"preserve_border_whitespaces",
"(",
"match",
",",
"default_border",
":",
"ReverseMarkdown",
".",
"config",
".",
"tag_border",
")",
"do",
"match",
".",
"strip",
".",
"sub",
"(",
"'~~ '",
",",
"'~~'",
")",
".",
"sub",
"(",
"' ~~'",
",",
"'~~'",
")",
"end",
"end",
"result",
".",
"gsub",
"(",
"/",
"\\s",
"\\[",
"\\]",
"\\s",
"/",
")",
"do",
"|",
"match",
"|",
"preserve_border_whitespaces",
"(",
"match",
")",
"do",
"match",
".",
"strip",
".",
"sub",
"(",
"'[ '",
",",
"'['",
")",
".",
"sub",
"(",
"' ]'",
",",
"']'",
")",
"end",
"end",
"end"
] | 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",
".",
"to_h",
".",
"keys",
")",
".",
"map",
"{",
"|",
"f",
"|",
"[",
"f",
",",
"unescape",
"(",
"map",
"[",
"f",
"]",
")",
"]",
"}",
"block",
"?",
"mapped",
".",
"map",
"(",
"block",
")",
":",
"Hash",
"[",
"mapped",
"]",
"end"
] | 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']
@see Mustermann::Mapper | [
"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_method",
"=",
"recursive",
"?",
":cp_r",
":",
":cp",
"glob_map",
"(",
"map",
",",
"**",
"opts",
")",
"{",
"|",
"o",
",",
"n",
"|",
"f",
".",
"send",
"(",
"cp_method",
",",
"o",
",",
"n",
",",
"**",
"utils_opts",
")",
"}",
"end"
] | 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",
"(",
"o",
",",
"n",
",",
"**",
"utils_opts",
")",
"}",
"end"
] | 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",
"(",
"map",
",",
"**",
"opts",
")",
"{",
"|",
"o",
",",
"n",
"|",
"f",
".",
"send",
"(",
"link_method",
",",
"o",
",",
"n",
",",
"**",
"utils_opts",
")",
"}",
"end"
] | 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",
"||=",
"{",
"}",
"@glob_patterns",
"[",
"pattern",
"]",
"||=",
"GlobPattern",
".",
"generate",
"(",
"pattern",
")",
"[",
"pattern",
",",
"@glob_patterns",
"[",
"pattern",
"]",
"]",
"end"
] | 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[size..-1]
end
results = results.inject(inject_with)
with_size ? [results, string.size - substring.size] : results
end | 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[size..-1]
end
results = results.inject(inject_with)
with_size ? [results, string.size - substring.size] : results
end | [
"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",
"[",
"size",
"..",
"-",
"1",
"]",
"end",
"results",
"=",
"results",
".",
"inject",
"(",
"inject_with",
")",
"with_size",
"?",
"[",
"results",
",",
"string",
".",
"size",
"-",
"substring",
".",
"size",
"]",
":",
"results",
"end"
] | 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",
"(",
"payload",
")",
"end"
] | 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",
".",
"empty?",
"self",
".",
"class",
".",
"new",
"(",
"safe_string",
"+",
"\"|\"",
"+",
"converted",
".",
"safe_string",
",",
"**",
"options",
")",
"end"
] | 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 only happens if the sinatra pattern behaves exactly the same as a composite
would in regards to matching, parsing, expanding and template generation.
@example
pattern = Mustermann.new('/foo/:name') | Mustermann.new('/:first/:second')
pattern === '/foo/bar' # => true
pattern === '/fox/bar' # => true
pattern === '/foo' # => false
@param [Mustermann::Pattern, String] other the other pattern
@return [Mustermann::Pattern] a composite pattern
@see Mustermann::Pattern#| | [
"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::ScanResult, nil] the matched substring, nil if it didn't match | [
"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",
"(",
"r",
")",
"}",
"self",
"end"
] | 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",
",",
"length",
",",
"params",
")",
"if",
"params",
"end"
] | 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.map { |key, value| @@uri.escape(key.to_s) + "=" + @@uri.escape(value.to_s, /[^\w]/) }
separator = @string.include?(??) ? ?& : ??
@string + separator + params.join(?&)
end | 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.map { |key, value| @@uri.escape(key.to_s) + "=" + @@uri.escape(value.to_s, /[^\w]/) }
separator = @string.include?(??) ? ?& : ??
@string + separator + params.join(?&)
end | [
"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",
".",
"map",
"{",
"|",
"key",
",",
"value",
"|",
"@@uri",
".",
"escape",
"(",
"key",
".",
"to_s",
")",
"+",
"\"=\"",
"+",
"@@uri",
".",
"escape",
"(",
"value",
".",
"to_s",
",",
"/",
"\\w",
"/",
")",
"}",
"separator",
"=",
"@string",
".",
"include?",
"(",
"??",
")",
"?",
"?&",
":",
"??",
"@string",
"+",
"separator",
"+",
"params",
".",
"join",
"(",
"?&",
")",
"end"
] | 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 Mustermann::Pattern#expand
@see Mustermann::Expander | [
"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",
",",
"**",
"options",
")",
"end"
] | 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",
".",
"each",
"{",
"|",
"v",
"|",
"versions",
"[",
"v",
"]",
"=",
"subclass",
"}",
"end"
] | 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",
"ArgumentError",
",",
"'unsupported version %p'",
"%",
"version",
"unless",
"detected",
"detected",
".",
"last",
"end"
] | 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)
end | 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)
end | [
"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",
")",
"end"
] | 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",
"(",
"output",
",",
"additional_values",
":",
"@additional_values",
",",
"**",
"@options",
")",
"unless",
"output",
".",
"is_a?",
"Expander",
"@map",
"<<",
"[",
"input",
",",
"output",
"]",
"end",
"end"
] | 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", "/:foo.:format"]
}}
@overload initialize(**options)
@param options [Hash] options The options hash
@yield block for generating mappings as a hash
@yieldparam mapper [Mustermann::Mapper] the mapper instance
@example
require 'mustermann/mapper'
Mustermann::Mapper.new(type: :rails) do |mapper|
mapper["/:foo"] = ["/:foo.html", "/:foo.:format"]
end
@overload initialize(map = {}, **options)
@param map [Hash] see {#update}
@param [Hash] options The options hash
@example map before options
require 'mustermann/mapper'
Mustermann::Mapper.new("/:foo" => "/:foo.html", type: :rails)
@example map after options
require 'mustermann/mapper'
Mustermann::Mapper.new(type: :rails, "/:foo" => "/:foo.html")
Add multiple mappings.
@param map [Hash{String, Pattern: String, Pattern, Arry<String, Pattern>, Expander}] the mapping | [
"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",
"&&=",
"Hash",
"[",
"values",
".",
"merge",
"(",
"params",
")",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"[",
"k",
".",
"to_s",
",",
"v",
"]",
"}",
"]",
"expander",
".",
"expandable?",
"(",
"params",
")",
"?",
"expander",
".",
"expand",
"(",
"params",
")",
":",
"current",
"end",
"end"
] | 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",
")",
"returned_string",
"end"
] | 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 array of tokens and their frequencies | [
"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, Integer>>] An array of tokens and their lengths | [
"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",
".",
"to_f",
")",
".",
"round",
"(",
"precision",
")",
"}",
".",
"sort_by_value_desc",
"end"
] | 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] ]
@example with `precision`
Counter.new(%w[Maj. Major Major Major]).token_density(precision: 4)
# => [ ['major', .7500], ['maj', .2500] ]
@param [Integer] precision The number of decimal places to round density to
@return [Array<Array<String, Float>>] An array of tokens and their densities | [
"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",
"."
] | 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",
"{",
"|",
"token",
"|",
"filter_proc",
".",
"call",
"(",
"token",
")",
"}",
"end"
] | 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 be a string,
a regular expression, a lambda, a symbol, or an array of one or more of those types.
This allows for powerful and flexible tokenisation strategies.
If a symbol is passed, it must name a predicate method.
@example
WordsCounted::Tokeniser.new("Hello World").tokenise
# => ['hello', 'world']
@example With `pattern`
WordsCounted::Tokeniser.new("Hello-Mohamad").tokenise(pattern: /[^-]+/)
# => ['hello', 'mohamad']
@example With `exclude` as a string
WordsCounted::Tokeniser.new("Hello Sami").tokenise(exclude: "hello")
# => ['sami']
@example With `exclude` as a regexp
WordsCounted::Tokeniser.new("Hello Dani").tokenise(exclude: /hello/i)
# => ['dani']
@example With `exclude` as a lambda
WordsCounted::Tokeniser.new("Goodbye Sami").tokenise(
exclude: ->(token) { token.length > 6 }
)
# => ['sami']
@example With `exclude` as a symbol
WordsCounted::Tokeniser.new("Hello محمد").tokenise(exclude: :ascii_only?)
# => ['محمد']
@example With `exclude` as an array of strings
WordsCounted::Tokeniser.new("Goodbye Sami and hello Dani").tokenise(
exclude: ["goodbye hello"]
)
# => ['sami', 'and', dani']
@example With `exclude` as an array of regular expressions
WordsCounted::Tokeniser.new("Goodbye and hello Dani").tokenise(
exclude: [/goodbye/i, /and/i]
)
# => ['hello', 'dani']
@example With `exclude` as an array of lambdas
t = WordsCounted::Tokeniser.new("Special Agent 007")
t.tokenise(
exclude: [
->(t) { t.to_i.odd? },
->(t) { t.length > 5}
]
)
# => ['agent']
@example With `exclude` as a mixed array
t = WordsCounted::Tokeniser.new("Hello! اسماءنا هي محمد، كارولينا، سامي، وداني")
t.tokenise(
exclude: [
:ascii_only?,
/محمد/,
->(t) { t.length > 6},
"و"
]
)
# => ["هي", "سامي", "وداني"]
@param [Regexp] pattern The string to tokenise
@param [Array<String, Regexp, Lambda, Symbol>, String, Regexp, Lambda, Symbol, nil] exclude The filter to apply
@return [Array] The array of filtered tokens | [
"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.respond_to?(:to_proc)
filter.to_proc
else
raise ArgumentError,
"`filter` must be a `String`, `Regexp`, `lambda`, `Symbol`, or an `Array` of any combination of those types"
end
end | 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.respond_to?(:to_proc)
filter.to_proc
else
raise ArgumentError,
"`filter` must be a `String`, `Regexp`, `lambda`, `Symbol`, or an `Array` of any combination of those types"
end
end | [
"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",
".",
"respond_to?",
"(",
":to_proc",
")",
"filter",
".",
"to_proc",
"else",
"raise",
"ArgumentError",
",",
"\"`filter` must be a `String`, `Regexp`, `lambda`, `Symbol`, or an `Array` of any combination of those types\"",
"end",
"end"
] | 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 string, it converts the string into an array, and returns a lambda
that returns true if the token is included in the resulting array.
@see {Tokeniser#filter_proc_from_string}.
If `filter` is a an array, it creates a new array where each element of the origingal is
converted to a lambda, and returns a lambda that calls each lambda in the resulting array.
If any lambda returns true the token is excluded from the final list.
@see {Tokeniser#filter_procs_from_array}.
If `filter` is a proc, then the proc is simply called. If `filter` is a regexp, a `lambda`
is returned that checks the token for a match.
If a symbol is passed, it is converted to a proc. The symbol must name a predicate method.
This method depends on `nil` responding `to_a` with an empty array, which
avoids having to check if `exclude` was passed.
@api private | [
"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",
"."
] | 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}"}
else
path = in_file
page_ranges.push "#{file_handle}"
end
in_files.push "#{file_handle}=#{normalize_path(path)}"
file_handle.next!
end
call_pdftk in_files, 'cat', page_ranges, 'output', output
end | 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}"}
else
path = in_file
page_ranges.push "#{file_handle}"
end
in_files.push "#{file_handle}=#{normalize_path(path)}"
file_handle.next!
end
call_pdftk in_files, 'cat', page_ranges, 'output', output
end | [
"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}\"",
"}",
"else",
"path",
"=",
"in_file",
"page_ranges",
".",
"push",
"\"#{file_handle}\"",
"end",
"in_files",
".",
"push",
"\"#{file_handle}=#{normalize_path(path)}\"",
"file_handle",
".",
"next!",
"end",
"call_pdftk",
"in_files",
",",
"'cat'",
",",
"page_ranges",
",",
"'output'",
",",
"output",
"end"
] | 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 << footer
return encode_data(pdf_data)
end | 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 << footer
return encode_data(pdf_data)
end | [
"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",
"<<",
"footer",
"return",
"encode_data",
"(",
"pdf_data",
")",
"end"
] | 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.