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 |
---|---|---|---|---|---|---|---|---|---|---|---|
meew0/discordrb | lib/discordrb/cache.rb | Discordrb.Cache.ensure_channel | def ensure_channel(data, server = nil)
if @channels.include?(data['id'].to_i)
@channels[data['id'].to_i]
else
@channels[data['id'].to_i] = Channel.new(data, self, server)
end
end | ruby | def ensure_channel(data, server = nil)
if @channels.include?(data['id'].to_i)
@channels[data['id'].to_i]
else
@channels[data['id'].to_i] = Channel.new(data, self, server)
end
end | [
"def",
"ensure_channel",
"(",
"data",
",",
"server",
"=",
"nil",
")",
"if",
"@channels",
".",
"include?",
"(",
"data",
"[",
"'id'",
"]",
".",
"to_i",
")",
"@channels",
"[",
"data",
"[",
"'id'",
"]",
".",
"to_i",
"]",
"else",
"@channels",
"[",
"data",
"[",
"'id'",
"]",
".",
"to_i",
"]",
"=",
"Channel",
".",
"new",
"(",
"data",
",",
"self",
",",
"server",
")",
"end",
"end"
] | Ensures a given channel object is cached and if not, cache it from the given data hash.
@param data [Hash] A data hash representing a channel.
@param server [Server, nil] The server the channel is on, if known.
@return [Channel] the channel represented by the data hash. | [
"Ensures",
"a",
"given",
"channel",
"object",
"is",
"cached",
"and",
"if",
"not",
"cache",
"it",
"from",
"the",
"given",
"data",
"hash",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/cache.rb#L172-L178 | train |
meew0/discordrb | lib/discordrb/cache.rb | Discordrb.Cache.invite | def invite(invite)
code = resolve_invite_code(invite)
Invite.new(JSON.parse(API::Invite.resolve(token, code)), self)
end | ruby | def invite(invite)
code = resolve_invite_code(invite)
Invite.new(JSON.parse(API::Invite.resolve(token, code)), self)
end | [
"def",
"invite",
"(",
"invite",
")",
"code",
"=",
"resolve_invite_code",
"(",
"invite",
")",
"Invite",
".",
"new",
"(",
"JSON",
".",
"parse",
"(",
"API",
"::",
"Invite",
".",
"resolve",
"(",
"token",
",",
"code",
")",
")",
",",
"self",
")",
"end"
] | Gets information about an invite.
@param invite [String, Invite] The invite to join. For possible formats see {#resolve_invite_code}.
@return [Invite] The invite with information about the given invite URL. | [
"Gets",
"information",
"about",
"an",
"invite",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/cache.rb#L204-L207 | train |
meew0/discordrb | lib/discordrb/cache.rb | Discordrb.Cache.find_channel | def find_channel(channel_name, server_name = nil, type: nil)
results = []
if /<#(?<id>\d+)>?/ =~ channel_name
# Check for channel mentions separately
return [channel(id)]
end
@servers.values.each do |server|
server.channels.each do |channel|
results << channel if channel.name == channel_name && (server_name || server.name) == server.name && (!type || (channel.type == type))
end
end
results
end | ruby | def find_channel(channel_name, server_name = nil, type: nil)
results = []
if /<#(?<id>\d+)>?/ =~ channel_name
# Check for channel mentions separately
return [channel(id)]
end
@servers.values.each do |server|
server.channels.each do |channel|
results << channel if channel.name == channel_name && (server_name || server.name) == server.name && (!type || (channel.type == type))
end
end
results
end | [
"def",
"find_channel",
"(",
"channel_name",
",",
"server_name",
"=",
"nil",
",",
"type",
":",
"nil",
")",
"results",
"=",
"[",
"]",
"if",
"/",
"\\d",
"/",
"=~",
"channel_name",
"# Check for channel mentions separately",
"return",
"[",
"channel",
"(",
"id",
")",
"]",
"end",
"@servers",
".",
"values",
".",
"each",
"do",
"|",
"server",
"|",
"server",
".",
"channels",
".",
"each",
"do",
"|",
"channel",
"|",
"results",
"<<",
"channel",
"if",
"channel",
".",
"name",
"==",
"channel_name",
"&&",
"(",
"server_name",
"||",
"server",
".",
"name",
")",
"==",
"server",
".",
"name",
"&&",
"(",
"!",
"type",
"||",
"(",
"channel",
".",
"type",
"==",
"type",
")",
")",
"end",
"end",
"results",
"end"
] | Finds a channel given its name and optionally the name of the server it is in.
@param channel_name [String] The channel to search for.
@param server_name [String] The server to search for, or `nil` if only the channel should be searched for.
@param type [Integer, nil] The type of channel to search for (0: text, 1: private, 2: voice, 3: group), or `nil` if any type of
channel should be searched for
@return [Array<Channel>] The array of channels that were found. May be empty if none were found. | [
"Finds",
"a",
"channel",
"given",
"its",
"name",
"and",
"optionally",
"the",
"name",
"of",
"the",
"server",
"it",
"is",
"in",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/cache.rb#L215-L230 | train |
meew0/discordrb | lib/discordrb/cache.rb | Discordrb.Cache.find_user | def find_user(username, discrim = nil)
users = @users.values.find_all { |e| e.username == username }
return users.find { |u| u.discrim == discrim } if discrim
users
end | ruby | def find_user(username, discrim = nil)
users = @users.values.find_all { |e| e.username == username }
return users.find { |u| u.discrim == discrim } if discrim
users
end | [
"def",
"find_user",
"(",
"username",
",",
"discrim",
"=",
"nil",
")",
"users",
"=",
"@users",
".",
"values",
".",
"find_all",
"{",
"|",
"e",
"|",
"e",
".",
"username",
"==",
"username",
"}",
"return",
"users",
".",
"find",
"{",
"|",
"u",
"|",
"u",
".",
"discrim",
"==",
"discrim",
"}",
"if",
"discrim",
"users",
"end"
] | Finds a user given its username or username & discriminator.
@overload find_user(username)
Find all cached users with a certain username.
@param username [String] The username to look for.
@return [Array<User>] The array of users that were found. May be empty if none were found.
@overload find_user(username, discrim)
Find a cached user with a certain username and discriminator.
Find a user by name and discriminator
@param username [String] The username to look for.
@param discrim [String] The user's discriminator
@return [User, nil] The user that was found, or `nil` if none was found
@note This method only searches through users that have been cached. Users that have not yet been cached
by the bot but still share a connection with the user (mutual server) will not be found.
@example Find users by name
bot.find_user('z64') #=> Array<User>
@example Find a user by name and discriminator
bot.find_user('z64', '2639') #=> User | [
"Finds",
"a",
"user",
"given",
"its",
"username",
"or",
"username",
"&",
"discriminator",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/cache.rb#L249-L254 | train |
meew0/discordrb | lib/discordrb/data/message.rb | Discordrb.Message.edit | def edit(new_content, new_embed = nil)
response = API::Channel.edit_message(@bot.token, @channel.id, @id, new_content, [], new_embed ? new_embed.to_hash : nil)
Message.new(JSON.parse(response), @bot)
end | ruby | def edit(new_content, new_embed = nil)
response = API::Channel.edit_message(@bot.token, @channel.id, @id, new_content, [], new_embed ? new_embed.to_hash : nil)
Message.new(JSON.parse(response), @bot)
end | [
"def",
"edit",
"(",
"new_content",
",",
"new_embed",
"=",
"nil",
")",
"response",
"=",
"API",
"::",
"Channel",
".",
"edit_message",
"(",
"@bot",
".",
"token",
",",
"@channel",
".",
"id",
",",
"@id",
",",
"new_content",
",",
"[",
"]",
",",
"new_embed",
"?",
"new_embed",
".",
"to_hash",
":",
"nil",
")",
"Message",
".",
"new",
"(",
"JSON",
".",
"parse",
"(",
"response",
")",
",",
"@bot",
")",
"end"
] | Edits this message to have the specified content instead.
You can only edit your own messages.
@param new_content [String] the new content the message should have.
@param new_embed [Hash, Discordrb::Webhooks::Embed, nil] The new embed the message should have. If `nil` the message will be changed to have no embed.
@return [Message] the resulting message. | [
"Edits",
"this",
"message",
"to",
"have",
"the",
"specified",
"content",
"instead",
".",
"You",
"can",
"only",
"edit",
"your",
"own",
"messages",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/message.rb#L155-L158 | train |
meew0/discordrb | lib/discordrb/data/message.rb | Discordrb.Message.create_reaction | def create_reaction(reaction)
reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction)
API::Channel.create_reaction(@bot.token, @channel.id, @id, reaction)
nil
end | ruby | def create_reaction(reaction)
reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction)
API::Channel.create_reaction(@bot.token, @channel.id, @id, reaction)
nil
end | [
"def",
"create_reaction",
"(",
"reaction",
")",
"reaction",
"=",
"reaction",
".",
"to_reaction",
"if",
"reaction",
".",
"respond_to?",
"(",
":to_reaction",
")",
"API",
"::",
"Channel",
".",
"create_reaction",
"(",
"@bot",
".",
"token",
",",
"@channel",
".",
"id",
",",
"@id",
",",
"reaction",
")",
"nil",
"end"
] | Reacts to a message.
@param reaction [String, #to_reaction] the unicode emoji or {Emoji} | [
"Reacts",
"to",
"a",
"message",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/message.rb#L243-L247 | train |
meew0/discordrb | lib/discordrb/data/message.rb | Discordrb.Message.reacted_with | def reacted_with(reaction, limit: 100)
reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction)
paginator = Paginator.new(limit, :down) do |last_page|
after_id = last_page.last.id if last_page
last_page = JSON.parse(API::Channel.get_reactions(@bot.token, @channel.id, @id, reaction, nil, after_id, limit))
last_page.map { |d| User.new(d, @bot) }
end
paginator.to_a
end | ruby | def reacted_with(reaction, limit: 100)
reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction)
paginator = Paginator.new(limit, :down) do |last_page|
after_id = last_page.last.id if last_page
last_page = JSON.parse(API::Channel.get_reactions(@bot.token, @channel.id, @id, reaction, nil, after_id, limit))
last_page.map { |d| User.new(d, @bot) }
end
paginator.to_a
end | [
"def",
"reacted_with",
"(",
"reaction",
",",
"limit",
":",
"100",
")",
"reaction",
"=",
"reaction",
".",
"to_reaction",
"if",
"reaction",
".",
"respond_to?",
"(",
":to_reaction",
")",
"paginator",
"=",
"Paginator",
".",
"new",
"(",
"limit",
",",
":down",
")",
"do",
"|",
"last_page",
"|",
"after_id",
"=",
"last_page",
".",
"last",
".",
"id",
"if",
"last_page",
"last_page",
"=",
"JSON",
".",
"parse",
"(",
"API",
"::",
"Channel",
".",
"get_reactions",
"(",
"@bot",
".",
"token",
",",
"@channel",
".",
"id",
",",
"@id",
",",
"reaction",
",",
"nil",
",",
"after_id",
",",
"limit",
")",
")",
"last_page",
".",
"map",
"{",
"|",
"d",
"|",
"User",
".",
"new",
"(",
"d",
",",
"@bot",
")",
"}",
"end",
"paginator",
".",
"to_a",
"end"
] | Returns the list of users who reacted with a certain reaction.
@param reaction [String, #to_reaction] the unicode emoji or {Emoji}
@param limit [Integer] the limit of how many users to retrieve. `nil` will return all users
@example Get all the users that reacted with a thumbsup.
thumbs_up_reactions = message.reacted_with("\u{1F44D}")
@return [Array<User>] the users who used this reaction | [
"Returns",
"the",
"list",
"of",
"users",
"who",
"reacted",
"with",
"a",
"certain",
"reaction",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/message.rb#L257-L265 | train |
meew0/discordrb | lib/discordrb/data/message.rb | Discordrb.Message.delete_reaction | def delete_reaction(user, reaction)
reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction)
API::Channel.delete_user_reaction(@bot.token, @channel.id, @id, reaction, user.resolve_id)
end | ruby | def delete_reaction(user, reaction)
reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction)
API::Channel.delete_user_reaction(@bot.token, @channel.id, @id, reaction, user.resolve_id)
end | [
"def",
"delete_reaction",
"(",
"user",
",",
"reaction",
")",
"reaction",
"=",
"reaction",
".",
"to_reaction",
"if",
"reaction",
".",
"respond_to?",
"(",
":to_reaction",
")",
"API",
"::",
"Channel",
".",
"delete_user_reaction",
"(",
"@bot",
".",
"token",
",",
"@channel",
".",
"id",
",",
"@id",
",",
"reaction",
",",
"user",
".",
"resolve_id",
")",
"end"
] | Deletes a reaction made by a user on this message.
@param user [User, #resolve_id] the user who used this reaction
@param reaction [String, #to_reaction] the reaction to remove | [
"Deletes",
"a",
"reaction",
"made",
"by",
"a",
"user",
"on",
"this",
"message",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/message.rb#L270-L273 | train |
meew0/discordrb | lib/discordrb/data/message.rb | Discordrb.Message.delete_own_reaction | def delete_own_reaction(reaction)
reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction)
API::Channel.delete_own_reaction(@bot.token, @channel.id, @id, reaction)
end | ruby | def delete_own_reaction(reaction)
reaction = reaction.to_reaction if reaction.respond_to?(:to_reaction)
API::Channel.delete_own_reaction(@bot.token, @channel.id, @id, reaction)
end | [
"def",
"delete_own_reaction",
"(",
"reaction",
")",
"reaction",
"=",
"reaction",
".",
"to_reaction",
"if",
"reaction",
".",
"respond_to?",
"(",
":to_reaction",
")",
"API",
"::",
"Channel",
".",
"delete_own_reaction",
"(",
"@bot",
".",
"token",
",",
"@channel",
".",
"id",
",",
"@id",
",",
"reaction",
")",
"end"
] | Deletes this client's reaction on this message.
@param reaction [String, #to_reaction] the reaction to remove | [
"Deletes",
"this",
"client",
"s",
"reaction",
"on",
"this",
"message",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/message.rb#L277-L280 | train |
meew0/discordrb | lib/discordrb/data/audit_logs.rb | Discordrb.AuditLogs.process_users | def process_users(users)
users.each do |element|
user = User.new(element, @bot)
@users[user.id] = user
end
end | ruby | def process_users(users)
users.each do |element|
user = User.new(element, @bot)
@users[user.id] = user
end
end | [
"def",
"process_users",
"(",
"users",
")",
"users",
".",
"each",
"do",
"|",
"element",
"|",
"user",
"=",
"User",
".",
"new",
"(",
"element",
",",
"@bot",
")",
"@users",
"[",
"user",
".",
"id",
"]",
"=",
"user",
"end",
"end"
] | Process user objects given by the request
@note For internal use only
@!visibility private | [
"Process",
"user",
"objects",
"given",
"by",
"the",
"request"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/audit_logs.rb#L268-L273 | train |
meew0/discordrb | lib/discordrb/data/audit_logs.rb | Discordrb.AuditLogs.process_webhooks | def process_webhooks(webhooks)
webhooks.each do |element|
webhook = Webhook.new(element, @bot)
@webhooks[webhook.id] = webhook
end
end | ruby | def process_webhooks(webhooks)
webhooks.each do |element|
webhook = Webhook.new(element, @bot)
@webhooks[webhook.id] = webhook
end
end | [
"def",
"process_webhooks",
"(",
"webhooks",
")",
"webhooks",
".",
"each",
"do",
"|",
"element",
"|",
"webhook",
"=",
"Webhook",
".",
"new",
"(",
"element",
",",
"@bot",
")",
"@webhooks",
"[",
"webhook",
".",
"id",
"]",
"=",
"webhook",
"end",
"end"
] | Process webhook objects given by the request
@note For internal use only
@!visibility private | [
"Process",
"webhook",
"objects",
"given",
"by",
"the",
"request"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/audit_logs.rb#L278-L283 | train |
meew0/discordrb | lib/discordrb/commands/parser.rb | Discordrb::Commands.CommandChain.execute | def execute(event)
old_chain = @chain
@bot.debug 'Executing bare chain'
result = execute_bare(event)
@chain_args ||= []
@bot.debug "Found chain args #{@chain_args}, preliminary result #{result}"
@chain_args.each do |arg|
case arg.first
when 'repeat'
new_result = ''
executed_chain = divide_chain(old_chain).last
arg[1].to_i.times do
chain_result = CommandChain.new(executed_chain, @bot).execute(event)
new_result += chain_result if chain_result
end
result = new_result
# TODO: more chain arguments
end
end
result
end | ruby | def execute(event)
old_chain = @chain
@bot.debug 'Executing bare chain'
result = execute_bare(event)
@chain_args ||= []
@bot.debug "Found chain args #{@chain_args}, preliminary result #{result}"
@chain_args.each do |arg|
case arg.first
when 'repeat'
new_result = ''
executed_chain = divide_chain(old_chain).last
arg[1].to_i.times do
chain_result = CommandChain.new(executed_chain, @bot).execute(event)
new_result += chain_result if chain_result
end
result = new_result
# TODO: more chain arguments
end
end
result
end | [
"def",
"execute",
"(",
"event",
")",
"old_chain",
"=",
"@chain",
"@bot",
".",
"debug",
"'Executing bare chain'",
"result",
"=",
"execute_bare",
"(",
"event",
")",
"@chain_args",
"||=",
"[",
"]",
"@bot",
".",
"debug",
"\"Found chain args #{@chain_args}, preliminary result #{result}\"",
"@chain_args",
".",
"each",
"do",
"|",
"arg",
"|",
"case",
"arg",
".",
"first",
"when",
"'repeat'",
"new_result",
"=",
"''",
"executed_chain",
"=",
"divide_chain",
"(",
"old_chain",
")",
".",
"last",
"arg",
"[",
"1",
"]",
".",
"to_i",
".",
"times",
"do",
"chain_result",
"=",
"CommandChain",
".",
"new",
"(",
"executed_chain",
",",
"@bot",
")",
".",
"execute",
"(",
"event",
")",
"new_result",
"+=",
"chain_result",
"if",
"chain_result",
"end",
"result",
"=",
"new_result",
"# TODO: more chain arguments",
"end",
"end",
"result",
"end"
] | Divides the command chain into chain arguments and command chain, then executes them both.
@param event [CommandEvent] The event to execute the command with.
@return [String] the result of the command chain execution. | [
"Divides",
"the",
"command",
"chain",
"into",
"chain",
"arguments",
"and",
"command",
"chain",
"then",
"executes",
"them",
"both",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/commands/parser.rb#L278-L304 | train |
meew0/discordrb | lib/discordrb/data/role.rb | Discordrb.Role.update_from | def update_from(other)
@permissions = other.permissions
@name = other.name
@hoist = other.hoist
@colour = other.colour
@position = other.position
@managed = other.managed
end | ruby | def update_from(other)
@permissions = other.permissions
@name = other.name
@hoist = other.hoist
@colour = other.colour
@position = other.position
@managed = other.managed
end | [
"def",
"update_from",
"(",
"other",
")",
"@permissions",
"=",
"other",
".",
"permissions",
"@name",
"=",
"other",
".",
"name",
"@hoist",
"=",
"other",
".",
"hoist",
"@colour",
"=",
"other",
".",
"colour",
"@position",
"=",
"other",
".",
"position",
"@managed",
"=",
"other",
".",
"managed",
"end"
] | Updates the data cache from another Role object
@note For internal use only
@!visibility private | [
"Updates",
"the",
"data",
"cache",
"from",
"another",
"Role",
"object"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/role.rb#L88-L95 | train |
meew0/discordrb | lib/discordrb/data/role.rb | Discordrb.Role.update_data | def update_data(new_data)
@name = new_data[:name] || new_data['name'] || @name
@hoist = new_data['hoist'] unless new_data['hoist'].nil?
@hoist = new_data[:hoist] unless new_data[:hoist].nil?
@colour = new_data[:colour] || (new_data['color'] ? ColourRGB.new(new_data['color']) : @colour)
end | ruby | def update_data(new_data)
@name = new_data[:name] || new_data['name'] || @name
@hoist = new_data['hoist'] unless new_data['hoist'].nil?
@hoist = new_data[:hoist] unless new_data[:hoist].nil?
@colour = new_data[:colour] || (new_data['color'] ? ColourRGB.new(new_data['color']) : @colour)
end | [
"def",
"update_data",
"(",
"new_data",
")",
"@name",
"=",
"new_data",
"[",
":name",
"]",
"||",
"new_data",
"[",
"'name'",
"]",
"||",
"@name",
"@hoist",
"=",
"new_data",
"[",
"'hoist'",
"]",
"unless",
"new_data",
"[",
"'hoist'",
"]",
".",
"nil?",
"@hoist",
"=",
"new_data",
"[",
":hoist",
"]",
"unless",
"new_data",
"[",
":hoist",
"]",
".",
"nil?",
"@colour",
"=",
"new_data",
"[",
":colour",
"]",
"||",
"(",
"new_data",
"[",
"'color'",
"]",
"?",
"ColourRGB",
".",
"new",
"(",
"new_data",
"[",
"'color'",
"]",
")",
":",
"@colour",
")",
"end"
] | Updates the data cache from a hash containing data
@note For internal use only
@!visibility private | [
"Updates",
"the",
"data",
"cache",
"from",
"a",
"hash",
"containing",
"data"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/role.rb#L100-L105 | train |
meew0/discordrb | lib/discordrb/data/role.rb | Discordrb.Role.packed= | def packed=(packed, update_perms = true)
update_role_data(permissions: packed)
@permissions.bits = packed if update_perms
end | ruby | def packed=(packed, update_perms = true)
update_role_data(permissions: packed)
@permissions.bits = packed if update_perms
end | [
"def",
"packed",
"=",
"(",
"packed",
",",
"update_perms",
"=",
"true",
")",
"update_role_data",
"(",
"permissions",
":",
"packed",
")",
"@permissions",
".",
"bits",
"=",
"packed",
"if",
"update_perms",
"end"
] | Changes this role's permissions to a fixed bitfield. This allows setting multiple permissions at once with just
one API call.
Information on how this bitfield is structured can be found at
https://discordapp.com/developers/docs/topics/permissions.
@example Remove all permissions from a role
role.packed = 0
@param packed [Integer] A bitfield with the desired permissions value.
@param update_perms [true, false] Whether the internal data should also be updated. This should always be true
when calling externally. | [
"Changes",
"this",
"role",
"s",
"permissions",
"to",
"a",
"fixed",
"bitfield",
".",
"This",
"allows",
"setting",
"multiple",
"permissions",
"at",
"once",
"with",
"just",
"one",
"API",
"call",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/role.rb#L143-L146 | train |
meew0/discordrb | lib/discordrb/data/role.rb | Discordrb.Role.sort_above | def sort_above(other = nil)
other = @server.role(other.resolve_id) if other
roles = @server.roles.sort_by(&:position)
roles.delete_at(@position)
index = other ? roles.index { |role| role.id == other.id } + 1 : 1
roles.insert(index, self)
updated_roles = roles.map.with_index { |role, position| { id: role.id, position: position } }
@server.update_role_positions(updated_roles)
index
end | ruby | def sort_above(other = nil)
other = @server.role(other.resolve_id) if other
roles = @server.roles.sort_by(&:position)
roles.delete_at(@position)
index = other ? roles.index { |role| role.id == other.id } + 1 : 1
roles.insert(index, self)
updated_roles = roles.map.with_index { |role, position| { id: role.id, position: position } }
@server.update_role_positions(updated_roles)
index
end | [
"def",
"sort_above",
"(",
"other",
"=",
"nil",
")",
"other",
"=",
"@server",
".",
"role",
"(",
"other",
".",
"resolve_id",
")",
"if",
"other",
"roles",
"=",
"@server",
".",
"roles",
".",
"sort_by",
"(",
":position",
")",
"roles",
".",
"delete_at",
"(",
"@position",
")",
"index",
"=",
"other",
"?",
"roles",
".",
"index",
"{",
"|",
"role",
"|",
"role",
".",
"id",
"==",
"other",
".",
"id",
"}",
"+",
"1",
":",
"1",
"roles",
".",
"insert",
"(",
"index",
",",
"self",
")",
"updated_roles",
"=",
"roles",
".",
"map",
".",
"with_index",
"{",
"|",
"role",
",",
"position",
"|",
"{",
"id",
":",
"role",
".",
"id",
",",
"position",
":",
"position",
"}",
"}",
"@server",
".",
"update_role_positions",
"(",
"updated_roles",
")",
"index",
"end"
] | Moves this role above another role in the list.
@param other [Role, #resolve_id, nil] The role above which this role should be moved. If it is `nil`,
the role will be moved above the @everyone role.
@return [Integer] the new position of this role | [
"Moves",
"this",
"role",
"above",
"another",
"role",
"in",
"the",
"list",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/role.rb#L152-L163 | train |
meew0/discordrb | lib/discordrb/data/member.rb | Discordrb.Member.set_roles | def set_roles(role, reason = nil)
role_ids = role_id_array(role)
API::Server.update_member(@bot.token, @server.id, @user.id, roles: role_ids, reason: reason)
end | ruby | def set_roles(role, reason = nil)
role_ids = role_id_array(role)
API::Server.update_member(@bot.token, @server.id, @user.id, roles: role_ids, reason: reason)
end | [
"def",
"set_roles",
"(",
"role",
",",
"reason",
"=",
"nil",
")",
"role_ids",
"=",
"role_id_array",
"(",
"role",
")",
"API",
"::",
"Server",
".",
"update_member",
"(",
"@bot",
".",
"token",
",",
"@server",
".",
"id",
",",
"@user",
".",
"id",
",",
"roles",
":",
"role_ids",
",",
"reason",
":",
"reason",
")",
"end"
] | Bulk sets a member's roles.
@param role [Role, Array<Role>] The role(s) to set.
@param reason [String] The reason the user's roles are being changed. | [
"Bulk",
"sets",
"a",
"member",
"s",
"roles",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/member.rb#L94-L97 | train |
meew0/discordrb | lib/discordrb/data/member.rb | Discordrb.Member.modify_roles | def modify_roles(add, remove, reason = nil)
add_role_ids = role_id_array(add)
remove_role_ids = role_id_array(remove)
old_role_ids = @roles.map(&:id)
new_role_ids = (old_role_ids - remove_role_ids + add_role_ids).uniq
API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids, reason: reason)
end | ruby | def modify_roles(add, remove, reason = nil)
add_role_ids = role_id_array(add)
remove_role_ids = role_id_array(remove)
old_role_ids = @roles.map(&:id)
new_role_ids = (old_role_ids - remove_role_ids + add_role_ids).uniq
API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids, reason: reason)
end | [
"def",
"modify_roles",
"(",
"add",
",",
"remove",
",",
"reason",
"=",
"nil",
")",
"add_role_ids",
"=",
"role_id_array",
"(",
"add",
")",
"remove_role_ids",
"=",
"role_id_array",
"(",
"remove",
")",
"old_role_ids",
"=",
"@roles",
".",
"map",
"(",
":id",
")",
"new_role_ids",
"=",
"(",
"old_role_ids",
"-",
"remove_role_ids",
"+",
"add_role_ids",
")",
".",
"uniq",
"API",
"::",
"Server",
".",
"update_member",
"(",
"@bot",
".",
"token",
",",
"@server",
".",
"id",
",",
"@user",
".",
"id",
",",
"roles",
":",
"new_role_ids",
",",
"reason",
":",
"reason",
")",
"end"
] | Adds and removes roles from a member.
@param add [Role, Array<Role>] The role(s) to add.
@param remove [Role, Array<Role>] The role(s) to remove.
@param reason [String] The reason the user's roles are being changed.
@example Remove the 'Member' role from a user, and add the 'Muted' role to them.
to_add = server.roles.find {|role| role.name == 'Muted'}
to_remove = server.roles.find {|role| role.name == 'Member'}
member.modify_roles(to_add, to_remove) | [
"Adds",
"and",
"removes",
"roles",
"from",
"a",
"member",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/member.rb#L107-L114 | train |
meew0/discordrb | lib/discordrb/data/member.rb | Discordrb.Member.add_role | def add_role(role, reason = nil)
role_ids = role_id_array(role)
if role_ids.count == 1
API::Server.add_member_role(@bot.token, @server.id, @user.id, role_ids[0], reason)
else
old_role_ids = @roles.map(&:id)
new_role_ids = (old_role_ids + role_ids).uniq
API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids, reason: reason)
end
end | ruby | def add_role(role, reason = nil)
role_ids = role_id_array(role)
if role_ids.count == 1
API::Server.add_member_role(@bot.token, @server.id, @user.id, role_ids[0], reason)
else
old_role_ids = @roles.map(&:id)
new_role_ids = (old_role_ids + role_ids).uniq
API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids, reason: reason)
end
end | [
"def",
"add_role",
"(",
"role",
",",
"reason",
"=",
"nil",
")",
"role_ids",
"=",
"role_id_array",
"(",
"role",
")",
"if",
"role_ids",
".",
"count",
"==",
"1",
"API",
"::",
"Server",
".",
"add_member_role",
"(",
"@bot",
".",
"token",
",",
"@server",
".",
"id",
",",
"@user",
".",
"id",
",",
"role_ids",
"[",
"0",
"]",
",",
"reason",
")",
"else",
"old_role_ids",
"=",
"@roles",
".",
"map",
"(",
":id",
")",
"new_role_ids",
"=",
"(",
"old_role_ids",
"+",
"role_ids",
")",
".",
"uniq",
"API",
"::",
"Server",
".",
"update_member",
"(",
"@bot",
".",
"token",
",",
"@server",
".",
"id",
",",
"@user",
".",
"id",
",",
"roles",
":",
"new_role_ids",
",",
"reason",
":",
"reason",
")",
"end",
"end"
] | Adds one or more roles to this member.
@param role [Role, Array<Role, #resolve_id>, #resolve_id] The role(s) to add.
@param reason [String] The reason the user's roles are being changed. | [
"Adds",
"one",
"or",
"more",
"roles",
"to",
"this",
"member",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/member.rb#L119-L129 | train |
meew0/discordrb | lib/discordrb/data/member.rb | Discordrb.Member.remove_role | def remove_role(role, reason = nil)
role_ids = role_id_array(role)
if role_ids.count == 1
API::Server.remove_member_role(@bot.token, @server.id, @user.id, role_ids[0], reason)
else
old_role_ids = @roles.map(&:id)
new_role_ids = old_role_ids.reject { |i| role_ids.include?(i) }
API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids, reason: reason)
end
end | ruby | def remove_role(role, reason = nil)
role_ids = role_id_array(role)
if role_ids.count == 1
API::Server.remove_member_role(@bot.token, @server.id, @user.id, role_ids[0], reason)
else
old_role_ids = @roles.map(&:id)
new_role_ids = old_role_ids.reject { |i| role_ids.include?(i) }
API::Server.update_member(@bot.token, @server.id, @user.id, roles: new_role_ids, reason: reason)
end
end | [
"def",
"remove_role",
"(",
"role",
",",
"reason",
"=",
"nil",
")",
"role_ids",
"=",
"role_id_array",
"(",
"role",
")",
"if",
"role_ids",
".",
"count",
"==",
"1",
"API",
"::",
"Server",
".",
"remove_member_role",
"(",
"@bot",
".",
"token",
",",
"@server",
".",
"id",
",",
"@user",
".",
"id",
",",
"role_ids",
"[",
"0",
"]",
",",
"reason",
")",
"else",
"old_role_ids",
"=",
"@roles",
".",
"map",
"(",
":id",
")",
"new_role_ids",
"=",
"old_role_ids",
".",
"reject",
"{",
"|",
"i",
"|",
"role_ids",
".",
"include?",
"(",
"i",
")",
"}",
"API",
"::",
"Server",
".",
"update_member",
"(",
"@bot",
".",
"token",
",",
"@server",
".",
"id",
",",
"@user",
".",
"id",
",",
"roles",
":",
"new_role_ids",
",",
"reason",
":",
"reason",
")",
"end",
"end"
] | Removes one or more roles from this member.
@param role [Role, Array<Role>] The role(s) to remove.
@param reason [String] The reason the user's roles are being changed. | [
"Removes",
"one",
"or",
"more",
"roles",
"from",
"this",
"member",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/member.rb#L134-L144 | train |
meew0/discordrb | lib/discordrb/data/member.rb | Discordrb.Member.set_nick | def set_nick(nick, reason = nil)
# Discord uses the empty string to signify 'no nickname' so we convert nil into that
nick ||= ''
if @user.current_bot?
API::User.change_own_nickname(@bot.token, @server.id, nick, reason)
else
API::Server.update_member(@bot.token, @server.id, @user.id, nick: nick, reason: nil)
end
end | ruby | def set_nick(nick, reason = nil)
# Discord uses the empty string to signify 'no nickname' so we convert nil into that
nick ||= ''
if @user.current_bot?
API::User.change_own_nickname(@bot.token, @server.id, nick, reason)
else
API::Server.update_member(@bot.token, @server.id, @user.id, nick: nick, reason: nil)
end
end | [
"def",
"set_nick",
"(",
"nick",
",",
"reason",
"=",
"nil",
")",
"# Discord uses the empty string to signify 'no nickname' so we convert nil into that",
"nick",
"||=",
"''",
"if",
"@user",
".",
"current_bot?",
"API",
"::",
"User",
".",
"change_own_nickname",
"(",
"@bot",
".",
"token",
",",
"@server",
".",
"id",
",",
"nick",
",",
"reason",
")",
"else",
"API",
"::",
"Server",
".",
"update_member",
"(",
"@bot",
".",
"token",
",",
"@server",
".",
"id",
",",
"@user",
".",
"id",
",",
"nick",
":",
"nick",
",",
"reason",
":",
"nil",
")",
"end",
"end"
] | Sets or resets this member's nickname. Requires the Change Nickname permission for the bot itself and Manage
Nicknames for other users.
@param nick [String, nil] The string to set the nickname to, or nil if it should be reset.
@param reason [String] The reason the user's nickname is being changed. | [
"Sets",
"or",
"resets",
"this",
"member",
"s",
"nickname",
".",
"Requires",
"the",
"Change",
"Nickname",
"permission",
"for",
"the",
"bot",
"itself",
"and",
"Manage",
"Nicknames",
"for",
"other",
"users",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/member.rb#L207-L216 | train |
meew0/discordrb | lib/discordrb/data/member.rb | Discordrb.Member.update_roles | def update_roles(role_ids)
@roles = []
role_ids.each do |id|
# It is posible for members to have roles that do not exist
# on the server any longer. See https://github.com/meew0/discordrb/issues/371
role = @server.role(id)
@roles << role if role
end
end | ruby | def update_roles(role_ids)
@roles = []
role_ids.each do |id|
# It is posible for members to have roles that do not exist
# on the server any longer. See https://github.com/meew0/discordrb/issues/371
role = @server.role(id)
@roles << role if role
end
end | [
"def",
"update_roles",
"(",
"role_ids",
")",
"@roles",
"=",
"[",
"]",
"role_ids",
".",
"each",
"do",
"|",
"id",
"|",
"# It is posible for members to have roles that do not exist",
"# on the server any longer. See https://github.com/meew0/discordrb/issues/371",
"role",
"=",
"@server",
".",
"role",
"(",
"id",
")",
"@roles",
"<<",
"role",
"if",
"role",
"end",
"end"
] | Update this member's roles
@note For internal use only.
@!visibility private | [
"Update",
"this",
"member",
"s",
"roles"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/member.rb#L228-L236 | train |
meew0/discordrb | lib/discordrb/commands/command_bot.rb | Discordrb::Commands.CommandBot.execute_command | def execute_command(name, event, arguments, chained = false, check_permissions = true)
debug("Executing command #{name} with arguments #{arguments}")
return unless @commands
command = @commands[name]
command = command.aliased_command if command.is_a?(CommandAlias)
return unless !check_permissions || channels?(event.channel, @attributes[:channels]) ||
(command && !command.attributes[:channels].nil?)
unless command
event.respond @attributes[:command_doesnt_exist_message].gsub('%command%', name.to_s) if @attributes[:command_doesnt_exist_message]
return
end
return unless !check_permissions || channels?(event.channel, command.attributes[:channels])
arguments = arg_check(arguments, command.attributes[:arg_types], event.server) if check_permissions
if (check_permissions &&
permission?(event.author, command.attributes[:permission_level], event.server) &&
required_permissions?(event.author, command.attributes[:required_permissions], event.channel) &&
required_roles?(event.author, command.attributes[:required_roles]) &&
allowed_roles?(event.author, command.attributes[:allowed_roles])) ||
!check_permissions
event.command = command
result = command.call(event, arguments, chained, check_permissions)
stringify(result)
else
event.respond command.attributes[:permission_message].gsub('%name%', name.to_s) if command.attributes[:permission_message]
nil
end
rescue Discordrb::Errors::NoPermission
event.respond @attributes[:no_permission_message] unless @attributes[:no_permission_message].nil?
raise
end | ruby | def execute_command(name, event, arguments, chained = false, check_permissions = true)
debug("Executing command #{name} with arguments #{arguments}")
return unless @commands
command = @commands[name]
command = command.aliased_command if command.is_a?(CommandAlias)
return unless !check_permissions || channels?(event.channel, @attributes[:channels]) ||
(command && !command.attributes[:channels].nil?)
unless command
event.respond @attributes[:command_doesnt_exist_message].gsub('%command%', name.to_s) if @attributes[:command_doesnt_exist_message]
return
end
return unless !check_permissions || channels?(event.channel, command.attributes[:channels])
arguments = arg_check(arguments, command.attributes[:arg_types], event.server) if check_permissions
if (check_permissions &&
permission?(event.author, command.attributes[:permission_level], event.server) &&
required_permissions?(event.author, command.attributes[:required_permissions], event.channel) &&
required_roles?(event.author, command.attributes[:required_roles]) &&
allowed_roles?(event.author, command.attributes[:allowed_roles])) ||
!check_permissions
event.command = command
result = command.call(event, arguments, chained, check_permissions)
stringify(result)
else
event.respond command.attributes[:permission_message].gsub('%name%', name.to_s) if command.attributes[:permission_message]
nil
end
rescue Discordrb::Errors::NoPermission
event.respond @attributes[:no_permission_message] unless @attributes[:no_permission_message].nil?
raise
end | [
"def",
"execute_command",
"(",
"name",
",",
"event",
",",
"arguments",
",",
"chained",
"=",
"false",
",",
"check_permissions",
"=",
"true",
")",
"debug",
"(",
"\"Executing command #{name} with arguments #{arguments}\"",
")",
"return",
"unless",
"@commands",
"command",
"=",
"@commands",
"[",
"name",
"]",
"command",
"=",
"command",
".",
"aliased_command",
"if",
"command",
".",
"is_a?",
"(",
"CommandAlias",
")",
"return",
"unless",
"!",
"check_permissions",
"||",
"channels?",
"(",
"event",
".",
"channel",
",",
"@attributes",
"[",
":channels",
"]",
")",
"||",
"(",
"command",
"&&",
"!",
"command",
".",
"attributes",
"[",
":channels",
"]",
".",
"nil?",
")",
"unless",
"command",
"event",
".",
"respond",
"@attributes",
"[",
":command_doesnt_exist_message",
"]",
".",
"gsub",
"(",
"'%command%'",
",",
"name",
".",
"to_s",
")",
"if",
"@attributes",
"[",
":command_doesnt_exist_message",
"]",
"return",
"end",
"return",
"unless",
"!",
"check_permissions",
"||",
"channels?",
"(",
"event",
".",
"channel",
",",
"command",
".",
"attributes",
"[",
":channels",
"]",
")",
"arguments",
"=",
"arg_check",
"(",
"arguments",
",",
"command",
".",
"attributes",
"[",
":arg_types",
"]",
",",
"event",
".",
"server",
")",
"if",
"check_permissions",
"if",
"(",
"check_permissions",
"&&",
"permission?",
"(",
"event",
".",
"author",
",",
"command",
".",
"attributes",
"[",
":permission_level",
"]",
",",
"event",
".",
"server",
")",
"&&",
"required_permissions?",
"(",
"event",
".",
"author",
",",
"command",
".",
"attributes",
"[",
":required_permissions",
"]",
",",
"event",
".",
"channel",
")",
"&&",
"required_roles?",
"(",
"event",
".",
"author",
",",
"command",
".",
"attributes",
"[",
":required_roles",
"]",
")",
"&&",
"allowed_roles?",
"(",
"event",
".",
"author",
",",
"command",
".",
"attributes",
"[",
":allowed_roles",
"]",
")",
")",
"||",
"!",
"check_permissions",
"event",
".",
"command",
"=",
"command",
"result",
"=",
"command",
".",
"call",
"(",
"event",
",",
"arguments",
",",
"chained",
",",
"check_permissions",
")",
"stringify",
"(",
"result",
")",
"else",
"event",
".",
"respond",
"command",
".",
"attributes",
"[",
":permission_message",
"]",
".",
"gsub",
"(",
"'%name%'",
",",
"name",
".",
"to_s",
")",
"if",
"command",
".",
"attributes",
"[",
":permission_message",
"]",
"nil",
"end",
"rescue",
"Discordrb",
"::",
"Errors",
"::",
"NoPermission",
"event",
".",
"respond",
"@attributes",
"[",
":no_permission_message",
"]",
"unless",
"@attributes",
"[",
":no_permission_message",
"]",
".",
"nil?",
"raise",
"end"
] | Executes a particular command on the bot. Mostly useful for internal stuff, but one can never know.
@param name [Symbol] The command to execute.
@param event [CommandEvent] The event to pass to the command.
@param arguments [Array<String>] The arguments to pass to the command.
@param chained [true, false] Whether or not it should be executed as part of a command chain. If this is false,
commands that have chain_usable set to false will not work.
@param check_permissions [true, false] Whether permission parameters such as `required_permission` or
`permission_level` should be checked.
@return [String, nil] the command's result, if there is any. | [
"Executes",
"a",
"particular",
"command",
"on",
"the",
"bot",
".",
"Mostly",
"useful",
"for",
"internal",
"stuff",
"but",
"one",
"can",
"never",
"know",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/commands/command_bot.rb#L208-L240 | train |
meew0/discordrb | lib/discordrb/commands/command_bot.rb | Discordrb::Commands.CommandBot.simple_execute | def simple_execute(chain, event)
return nil if chain.empty?
args = chain.split(' ')
execute_command(args[0].to_sym, event, args[1..-1])
end | ruby | def simple_execute(chain, event)
return nil if chain.empty?
args = chain.split(' ')
execute_command(args[0].to_sym, event, args[1..-1])
end | [
"def",
"simple_execute",
"(",
"chain",
",",
"event",
")",
"return",
"nil",
"if",
"chain",
".",
"empty?",
"args",
"=",
"chain",
".",
"split",
"(",
"' '",
")",
"execute_command",
"(",
"args",
"[",
"0",
"]",
".",
"to_sym",
",",
"event",
",",
"args",
"[",
"1",
"..",
"-",
"1",
"]",
")",
"end"
] | Executes a command in a simple manner, without command chains or permissions.
@param chain [String] The command with its arguments separated by spaces.
@param event [CommandEvent] The event to pass to the command.
@return [String, nil] the command's result, if there is any. | [
"Executes",
"a",
"command",
"in",
"a",
"simple",
"manner",
"without",
"command",
"chains",
"or",
"permissions",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/commands/command_bot.rb#L327-L332 | train |
meew0/discordrb | lib/discordrb/commands/command_bot.rb | Discordrb::Commands.CommandBot.permission? | def permission?(user, level, server)
determined_level = if user.webhook? || server.nil?
0
else
user.roles.reduce(0) do |memo, role|
[@permissions[:roles][role.id] || 0, memo].max
end
end
[@permissions[:users][user.id] || 0, determined_level].max >= level
end | ruby | def permission?(user, level, server)
determined_level = if user.webhook? || server.nil?
0
else
user.roles.reduce(0) do |memo, role|
[@permissions[:roles][role.id] || 0, memo].max
end
end
[@permissions[:users][user.id] || 0, determined_level].max >= level
end | [
"def",
"permission?",
"(",
"user",
",",
"level",
",",
"server",
")",
"determined_level",
"=",
"if",
"user",
".",
"webhook?",
"||",
"server",
".",
"nil?",
"0",
"else",
"user",
".",
"roles",
".",
"reduce",
"(",
"0",
")",
"do",
"|",
"memo",
",",
"role",
"|",
"[",
"@permissions",
"[",
":roles",
"]",
"[",
"role",
".",
"id",
"]",
"||",
"0",
",",
"memo",
"]",
".",
"max",
"end",
"end",
"[",
"@permissions",
"[",
":users",
"]",
"[",
"user",
".",
"id",
"]",
"||",
"0",
",",
"determined_level",
"]",
".",
"max",
">=",
"level",
"end"
] | Check if a user has permission to do something
@param user [User] The user to check
@param level [Integer] The minimum permission level the user should have (inclusive)
@param server [Server] The server on which to check
@return [true, false] whether or not the user has the given permission | [
"Check",
"if",
"a",
"user",
"has",
"permission",
"to",
"do",
"something"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/commands/command_bot.rb#L353-L363 | train |
meew0/discordrb | lib/discordrb/commands/command_bot.rb | Discordrb::Commands.CommandBot.create_message | def create_message(data)
message = Discordrb::Message.new(data, self)
return message if message.from_bot? && !@should_parse_self
return message if message.webhook? && !@attributes[:webhook_commands]
unless message.author
Discordrb::LOGGER.warn("Received a message (#{message.inspect}) with nil author! Ignoring, please report this if you can")
return
end
event = CommandEvent.new(message, self)
chain = trigger?(message)
return message unless chain
# Don't allow spaces between the prefix and the command
if chain.start_with?(' ') && !@attributes[:spaces_allowed]
debug('Chain starts with a space')
return message
end
if chain.strip.empty?
debug('Chain is empty')
return message
end
execute_chain(chain, event)
# Return the message so it doesn't get parsed again during the rest of the dispatch handling
message
end | ruby | def create_message(data)
message = Discordrb::Message.new(data, self)
return message if message.from_bot? && !@should_parse_self
return message if message.webhook? && !@attributes[:webhook_commands]
unless message.author
Discordrb::LOGGER.warn("Received a message (#{message.inspect}) with nil author! Ignoring, please report this if you can")
return
end
event = CommandEvent.new(message, self)
chain = trigger?(message)
return message unless chain
# Don't allow spaces between the prefix and the command
if chain.start_with?(' ') && !@attributes[:spaces_allowed]
debug('Chain starts with a space')
return message
end
if chain.strip.empty?
debug('Chain is empty')
return message
end
execute_chain(chain, event)
# Return the message so it doesn't get parsed again during the rest of the dispatch handling
message
end | [
"def",
"create_message",
"(",
"data",
")",
"message",
"=",
"Discordrb",
"::",
"Message",
".",
"new",
"(",
"data",
",",
"self",
")",
"return",
"message",
"if",
"message",
".",
"from_bot?",
"&&",
"!",
"@should_parse_self",
"return",
"message",
"if",
"message",
".",
"webhook?",
"&&",
"!",
"@attributes",
"[",
":webhook_commands",
"]",
"unless",
"message",
".",
"author",
"Discordrb",
"::",
"LOGGER",
".",
"warn",
"(",
"\"Received a message (#{message.inspect}) with nil author! Ignoring, please report this if you can\"",
")",
"return",
"end",
"event",
"=",
"CommandEvent",
".",
"new",
"(",
"message",
",",
"self",
")",
"chain",
"=",
"trigger?",
"(",
"message",
")",
"return",
"message",
"unless",
"chain",
"# Don't allow spaces between the prefix and the command",
"if",
"chain",
".",
"start_with?",
"(",
"' '",
")",
"&&",
"!",
"@attributes",
"[",
":spaces_allowed",
"]",
"debug",
"(",
"'Chain starts with a space'",
")",
"return",
"message",
"end",
"if",
"chain",
".",
"strip",
".",
"empty?",
"debug",
"(",
"'Chain is empty'",
")",
"return",
"message",
"end",
"execute_chain",
"(",
"chain",
",",
"event",
")",
"# Return the message so it doesn't get parsed again during the rest of the dispatch handling",
"message",
"end"
] | Internal handler for MESSAGE_CREATE that is overwritten to allow for command handling | [
"Internal",
"handler",
"for",
"MESSAGE_CREATE",
"that",
"is",
"overwritten",
"to",
"allow",
"for",
"command",
"handling"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/commands/command_bot.rb#L393-L423 | train |
meew0/discordrb | lib/discordrb/commands/command_bot.rb | Discordrb::Commands.CommandBot.trigger? | def trigger?(message)
if @prefix.is_a? String
standard_prefix_trigger(message.content, @prefix)
elsif @prefix.is_a? Array
@prefix.map { |e| standard_prefix_trigger(message.content, e) }.reduce { |m, e| m || e }
elsif @prefix.respond_to? :call
@prefix.call(message)
end
end | ruby | def trigger?(message)
if @prefix.is_a? String
standard_prefix_trigger(message.content, @prefix)
elsif @prefix.is_a? Array
@prefix.map { |e| standard_prefix_trigger(message.content, e) }.reduce { |m, e| m || e }
elsif @prefix.respond_to? :call
@prefix.call(message)
end
end | [
"def",
"trigger?",
"(",
"message",
")",
"if",
"@prefix",
".",
"is_a?",
"String",
"standard_prefix_trigger",
"(",
"message",
".",
"content",
",",
"@prefix",
")",
"elsif",
"@prefix",
".",
"is_a?",
"Array",
"@prefix",
".",
"map",
"{",
"|",
"e",
"|",
"standard_prefix_trigger",
"(",
"message",
".",
"content",
",",
"e",
")",
"}",
".",
"reduce",
"{",
"|",
"m",
",",
"e",
"|",
"m",
"||",
"e",
"}",
"elsif",
"@prefix",
".",
"respond_to?",
":call",
"@prefix",
".",
"call",
"(",
"message",
")",
"end",
"end"
] | Check whether a message should trigger command execution, and if it does, return the raw chain | [
"Check",
"whether",
"a",
"message",
"should",
"trigger",
"command",
"execution",
"and",
"if",
"it",
"does",
"return",
"the",
"raw",
"chain"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/commands/command_bot.rb#L426-L434 | train |
meew0/discordrb | lib/discordrb/voice/voice_bot.rb | Discordrb::Voice.VoiceBot.stop_playing | def stop_playing(wait_for_confirmation = false)
@was_playing_before = @playing
@speaking = false
@playing = false
sleep IDEAL_LENGTH / 1000.0 if @was_playing_before
return unless wait_for_confirmation
@has_stopped_playing = false
sleep IDEAL_LENGTH / 1000.0 until @has_stopped_playing
@has_stopped_playing = false
end | ruby | def stop_playing(wait_for_confirmation = false)
@was_playing_before = @playing
@speaking = false
@playing = false
sleep IDEAL_LENGTH / 1000.0 if @was_playing_before
return unless wait_for_confirmation
@has_stopped_playing = false
sleep IDEAL_LENGTH / 1000.0 until @has_stopped_playing
@has_stopped_playing = false
end | [
"def",
"stop_playing",
"(",
"wait_for_confirmation",
"=",
"false",
")",
"@was_playing_before",
"=",
"@playing",
"@speaking",
"=",
"false",
"@playing",
"=",
"false",
"sleep",
"IDEAL_LENGTH",
"/",
"1000.0",
"if",
"@was_playing_before",
"return",
"unless",
"wait_for_confirmation",
"@has_stopped_playing",
"=",
"false",
"sleep",
"IDEAL_LENGTH",
"/",
"1000.0",
"until",
"@has_stopped_playing",
"@has_stopped_playing",
"=",
"false",
"end"
] | Stops the current playback entirely.
@param wait_for_confirmation [true, false] Whether the method should wait for confirmation from the playback
method that the playback has actually stopped. | [
"Stops",
"the",
"current",
"playback",
"entirely",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/voice/voice_bot.rb#L157-L168 | train |
meew0/discordrb | lib/discordrb/voice/voice_bot.rb | Discordrb::Voice.VoiceBot.play_dca | def play_dca(file)
stop_playing(true) if @playing
@bot.debug "Reading DCA file #{file}"
input_stream = File.open(file)
magic = input_stream.read(4)
raise ArgumentError, 'Not a DCA1 file! The file might have been corrupted, please recreate it.' unless magic == 'DCA1'
# Read the metadata header, then read the metadata and discard it as we don't care about it
metadata_header = input_stream.read(4).unpack1('l<')
input_stream.read(metadata_header)
# Play the data, without re-encoding it to opus
play_internal do
begin
# Read header
header_str = input_stream.read(2)
unless header_str
@bot.debug 'Finished DCA parsing (header is nil)'
next :stop
end
header = header_str.unpack1('s<')
raise 'Negative header in DCA file! Your file is likely corrupted.' if header.negative?
rescue EOFError
@bot.debug 'Finished DCA parsing (EOFError)'
next :stop
end
# Read bytes
input_stream.read(header)
end
end | ruby | def play_dca(file)
stop_playing(true) if @playing
@bot.debug "Reading DCA file #{file}"
input_stream = File.open(file)
magic = input_stream.read(4)
raise ArgumentError, 'Not a DCA1 file! The file might have been corrupted, please recreate it.' unless magic == 'DCA1'
# Read the metadata header, then read the metadata and discard it as we don't care about it
metadata_header = input_stream.read(4).unpack1('l<')
input_stream.read(metadata_header)
# Play the data, without re-encoding it to opus
play_internal do
begin
# Read header
header_str = input_stream.read(2)
unless header_str
@bot.debug 'Finished DCA parsing (header is nil)'
next :stop
end
header = header_str.unpack1('s<')
raise 'Negative header in DCA file! Your file is likely corrupted.' if header.negative?
rescue EOFError
@bot.debug 'Finished DCA parsing (EOFError)'
next :stop
end
# Read bytes
input_stream.read(header)
end
end | [
"def",
"play_dca",
"(",
"file",
")",
"stop_playing",
"(",
"true",
")",
"if",
"@playing",
"@bot",
".",
"debug",
"\"Reading DCA file #{file}\"",
"input_stream",
"=",
"File",
".",
"open",
"(",
"file",
")",
"magic",
"=",
"input_stream",
".",
"read",
"(",
"4",
")",
"raise",
"ArgumentError",
",",
"'Not a DCA1 file! The file might have been corrupted, please recreate it.'",
"unless",
"magic",
"==",
"'DCA1'",
"# Read the metadata header, then read the metadata and discard it as we don't care about it",
"metadata_header",
"=",
"input_stream",
".",
"read",
"(",
"4",
")",
".",
"unpack1",
"(",
"'l<'",
")",
"input_stream",
".",
"read",
"(",
"metadata_header",
")",
"# Play the data, without re-encoding it to opus",
"play_internal",
"do",
"begin",
"# Read header",
"header_str",
"=",
"input_stream",
".",
"read",
"(",
"2",
")",
"unless",
"header_str",
"@bot",
".",
"debug",
"'Finished DCA parsing (header is nil)'",
"next",
":stop",
"end",
"header",
"=",
"header_str",
".",
"unpack1",
"(",
"'s<'",
")",
"raise",
"'Negative header in DCA file! Your file is likely corrupted.'",
"if",
"header",
".",
"negative?",
"rescue",
"EOFError",
"@bot",
".",
"debug",
"'Finished DCA parsing (EOFError)'",
"next",
":stop",
"end",
"# Read bytes",
"input_stream",
".",
"read",
"(",
"header",
")",
"end",
"end"
] | Plays a stream of audio data in the DCA format. This format has the advantage that no recoding has to be
done - the file contains the data exactly as Discord needs it.
@note DCA playback will not be affected by the volume modifier ({#volume}) because the modifier operates on raw
PCM, not opus data. Modifying the volume of DCA data would involve decoding it, multiplying the samples and
re-encoding it, which defeats its entire purpose (no recoding).
@see https://github.com/bwmarrin/dca
@see #play | [
"Plays",
"a",
"stream",
"of",
"audio",
"data",
"in",
"the",
"DCA",
"format",
".",
"This",
"format",
"has",
"the",
"advantage",
"that",
"no",
"recoding",
"has",
"to",
"be",
"done",
"-",
"the",
"file",
"contains",
"the",
"data",
"exactly",
"as",
"Discord",
"needs",
"it",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/voice/voice_bot.rb#L255-L290 | train |
meew0/discordrb | lib/discordrb/voice/voice_bot.rb | Discordrb::Voice.VoiceBot.play_internal | def play_internal
count = 0
@playing = true
# Default play length (ms), will be adjusted later
@length = IDEAL_LENGTH
self.speaking = true
loop do
# Starting from the tenth packet, perform length adjustment every 100 packets (2 seconds)
should_adjust_this_packet = (count % @adjust_interval == @adjust_offset)
# If we should adjust, start now
@length_adjust = Time.now.nsec if should_adjust_this_packet
break unless @playing
# If we should skip, get some data, discard it and go to the next iteration
if @skips.positive?
@skips -= 1
yield
next
end
# Track packet count, sequence and time (Discord requires this)
count += 1
increment_packet_headers
# Get packet data
buf = yield
# Stop doing anything if the stop signal was sent
break if buf == :stop
# Proceed to the next packet if we got nil
next unless buf
# Track intermediate adjustment so we can measure how much encoding contributes to the total time
@intermediate_adjust = Time.now.nsec if should_adjust_this_packet
# Send the packet
@udp.send_audio(buf, @sequence, @time)
# Set the stream time (for tracking how long we've been playing)
@stream_time = count * @length / 1000
if @length_override # Don't do adjustment because the user has manually specified an override value
@length = @length_override
elsif @length_adjust # Perform length adjustment
# Define the time once so it doesn't get inaccurate
now = Time.now.nsec
# Difference between length_adjust and now in ms
ms_diff = (now - @length_adjust) / 1_000_000.0
if ms_diff >= 0
@length = if @adjust_average
(IDEAL_LENGTH - ms_diff + @length) / 2.0
else
IDEAL_LENGTH - ms_diff
end
# Track the time it took to encode
encode_ms = (@intermediate_adjust - @length_adjust) / 1_000_000.0
@bot.debug("Length adjustment: new length #{@length} (measured #{ms_diff}, #{(100 * encode_ms) / ms_diff}% encoding)") if @adjust_debug
end
@length_adjust = nil
end
# If paused, wait
sleep 0.1 while @paused
if @length.positive?
# Wait `length` ms, then send the next packet
sleep @length / 1000.0
else
Discordrb::LOGGER.warn('Audio encoding and sending together took longer than Discord expects one packet to be (20 ms)! This may be indicative of network problems.')
end
end
@bot.debug('Sending five silent frames to clear out buffers')
5.times do
increment_packet_headers
@udp.send_audio(Encoder::OPUS_SILENCE, @sequence, @time)
# Length adjustments don't matter here, we can just wait 20 ms since nobody is going to hear it anyway
sleep IDEAL_LENGTH / 1000.0
end
@bot.debug('Performing final cleanup after stream ended')
# Final cleanup
stop_playing
# Notify any stop_playing methods running right now that we have actually stopped
@has_stopped_playing = true
end | ruby | def play_internal
count = 0
@playing = true
# Default play length (ms), will be adjusted later
@length = IDEAL_LENGTH
self.speaking = true
loop do
# Starting from the tenth packet, perform length adjustment every 100 packets (2 seconds)
should_adjust_this_packet = (count % @adjust_interval == @adjust_offset)
# If we should adjust, start now
@length_adjust = Time.now.nsec if should_adjust_this_packet
break unless @playing
# If we should skip, get some data, discard it and go to the next iteration
if @skips.positive?
@skips -= 1
yield
next
end
# Track packet count, sequence and time (Discord requires this)
count += 1
increment_packet_headers
# Get packet data
buf = yield
# Stop doing anything if the stop signal was sent
break if buf == :stop
# Proceed to the next packet if we got nil
next unless buf
# Track intermediate adjustment so we can measure how much encoding contributes to the total time
@intermediate_adjust = Time.now.nsec if should_adjust_this_packet
# Send the packet
@udp.send_audio(buf, @sequence, @time)
# Set the stream time (for tracking how long we've been playing)
@stream_time = count * @length / 1000
if @length_override # Don't do adjustment because the user has manually specified an override value
@length = @length_override
elsif @length_adjust # Perform length adjustment
# Define the time once so it doesn't get inaccurate
now = Time.now.nsec
# Difference between length_adjust and now in ms
ms_diff = (now - @length_adjust) / 1_000_000.0
if ms_diff >= 0
@length = if @adjust_average
(IDEAL_LENGTH - ms_diff + @length) / 2.0
else
IDEAL_LENGTH - ms_diff
end
# Track the time it took to encode
encode_ms = (@intermediate_adjust - @length_adjust) / 1_000_000.0
@bot.debug("Length adjustment: new length #{@length} (measured #{ms_diff}, #{(100 * encode_ms) / ms_diff}% encoding)") if @adjust_debug
end
@length_adjust = nil
end
# If paused, wait
sleep 0.1 while @paused
if @length.positive?
# Wait `length` ms, then send the next packet
sleep @length / 1000.0
else
Discordrb::LOGGER.warn('Audio encoding and sending together took longer than Discord expects one packet to be (20 ms)! This may be indicative of network problems.')
end
end
@bot.debug('Sending five silent frames to clear out buffers')
5.times do
increment_packet_headers
@udp.send_audio(Encoder::OPUS_SILENCE, @sequence, @time)
# Length adjustments don't matter here, we can just wait 20 ms since nobody is going to hear it anyway
sleep IDEAL_LENGTH / 1000.0
end
@bot.debug('Performing final cleanup after stream ended')
# Final cleanup
stop_playing
# Notify any stop_playing methods running right now that we have actually stopped
@has_stopped_playing = true
end | [
"def",
"play_internal",
"count",
"=",
"0",
"@playing",
"=",
"true",
"# Default play length (ms), will be adjusted later",
"@length",
"=",
"IDEAL_LENGTH",
"self",
".",
"speaking",
"=",
"true",
"loop",
"do",
"# Starting from the tenth packet, perform length adjustment every 100 packets (2 seconds)",
"should_adjust_this_packet",
"=",
"(",
"count",
"%",
"@adjust_interval",
"==",
"@adjust_offset",
")",
"# If we should adjust, start now",
"@length_adjust",
"=",
"Time",
".",
"now",
".",
"nsec",
"if",
"should_adjust_this_packet",
"break",
"unless",
"@playing",
"# If we should skip, get some data, discard it and go to the next iteration",
"if",
"@skips",
".",
"positive?",
"@skips",
"-=",
"1",
"yield",
"next",
"end",
"# Track packet count, sequence and time (Discord requires this)",
"count",
"+=",
"1",
"increment_packet_headers",
"# Get packet data",
"buf",
"=",
"yield",
"# Stop doing anything if the stop signal was sent",
"break",
"if",
"buf",
"==",
":stop",
"# Proceed to the next packet if we got nil",
"next",
"unless",
"buf",
"# Track intermediate adjustment so we can measure how much encoding contributes to the total time",
"@intermediate_adjust",
"=",
"Time",
".",
"now",
".",
"nsec",
"if",
"should_adjust_this_packet",
"# Send the packet",
"@udp",
".",
"send_audio",
"(",
"buf",
",",
"@sequence",
",",
"@time",
")",
"# Set the stream time (for tracking how long we've been playing)",
"@stream_time",
"=",
"count",
"*",
"@length",
"/",
"1000",
"if",
"@length_override",
"# Don't do adjustment because the user has manually specified an override value",
"@length",
"=",
"@length_override",
"elsif",
"@length_adjust",
"# Perform length adjustment",
"# Define the time once so it doesn't get inaccurate",
"now",
"=",
"Time",
".",
"now",
".",
"nsec",
"# Difference between length_adjust and now in ms",
"ms_diff",
"=",
"(",
"now",
"-",
"@length_adjust",
")",
"/",
"1_000_000.0",
"if",
"ms_diff",
">=",
"0",
"@length",
"=",
"if",
"@adjust_average",
"(",
"IDEAL_LENGTH",
"-",
"ms_diff",
"+",
"@length",
")",
"/",
"2.0",
"else",
"IDEAL_LENGTH",
"-",
"ms_diff",
"end",
"# Track the time it took to encode",
"encode_ms",
"=",
"(",
"@intermediate_adjust",
"-",
"@length_adjust",
")",
"/",
"1_000_000.0",
"@bot",
".",
"debug",
"(",
"\"Length adjustment: new length #{@length} (measured #{ms_diff}, #{(100 * encode_ms) / ms_diff}% encoding)\"",
")",
"if",
"@adjust_debug",
"end",
"@length_adjust",
"=",
"nil",
"end",
"# If paused, wait",
"sleep",
"0.1",
"while",
"@paused",
"if",
"@length",
".",
"positive?",
"# Wait `length` ms, then send the next packet",
"sleep",
"@length",
"/",
"1000.0",
"else",
"Discordrb",
"::",
"LOGGER",
".",
"warn",
"(",
"'Audio encoding and sending together took longer than Discord expects one packet to be (20 ms)! This may be indicative of network problems.'",
")",
"end",
"end",
"@bot",
".",
"debug",
"(",
"'Sending five silent frames to clear out buffers'",
")",
"5",
".",
"times",
"do",
"increment_packet_headers",
"@udp",
".",
"send_audio",
"(",
"Encoder",
"::",
"OPUS_SILENCE",
",",
"@sequence",
",",
"@time",
")",
"# Length adjustments don't matter here, we can just wait 20 ms since nobody is going to hear it anyway",
"sleep",
"IDEAL_LENGTH",
"/",
"1000.0",
"end",
"@bot",
".",
"debug",
"(",
"'Performing final cleanup after stream ended'",
")",
"# Final cleanup",
"stop_playing",
"# Notify any stop_playing methods running right now that we have actually stopped",
"@has_stopped_playing",
"=",
"true",
"end"
] | Plays the data from the @io stream as Discord requires it | [
"Plays",
"the",
"data",
"from",
"the"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/voice/voice_bot.rb#L297-L393 | train |
meew0/discordrb | lib/discordrb/webhooks/client.rb | Discordrb::Webhooks.Client.execute | def execute(builder = nil, wait = false)
raise TypeError, 'builder needs to be nil or like a Discordrb::Webhooks::Builder!' unless
builder.respond_to?(:file) && builder.respond_to?(:to_multipart_hash) || builder.respond_to?(:to_json_hash) || builder.nil?
builder ||= Builder.new
yield builder if block_given?
if builder.file
post_multipart(builder, wait)
else
post_json(builder, wait)
end
end | ruby | def execute(builder = nil, wait = false)
raise TypeError, 'builder needs to be nil or like a Discordrb::Webhooks::Builder!' unless
builder.respond_to?(:file) && builder.respond_to?(:to_multipart_hash) || builder.respond_to?(:to_json_hash) || builder.nil?
builder ||= Builder.new
yield builder if block_given?
if builder.file
post_multipart(builder, wait)
else
post_json(builder, wait)
end
end | [
"def",
"execute",
"(",
"builder",
"=",
"nil",
",",
"wait",
"=",
"false",
")",
"raise",
"TypeError",
",",
"'builder needs to be nil or like a Discordrb::Webhooks::Builder!'",
"unless",
"builder",
".",
"respond_to?",
"(",
":file",
")",
"&&",
"builder",
".",
"respond_to?",
"(",
":to_multipart_hash",
")",
"||",
"builder",
".",
"respond_to?",
"(",
":to_json_hash",
")",
"||",
"builder",
".",
"nil?",
"builder",
"||=",
"Builder",
".",
"new",
"yield",
"builder",
"if",
"block_given?",
"if",
"builder",
".",
"file",
"post_multipart",
"(",
"builder",
",",
"wait",
")",
"else",
"post_json",
"(",
"builder",
",",
"wait",
")",
"end",
"end"
] | Create a new webhook
@param url [String] The URL to post messages to.
@param id [Integer] The webhook's ID. Will only be used if `url` is not
set.
@param token [String] The webhook's authorisation token. Will only be used
if `url` is not set.
Executes the webhook this client points to with the given data.
@param builder [Builder, nil] The builder to start out with, or nil if one should be created anew.
@param wait [true, false] Whether Discord should wait for the message to be successfully received by clients, or
whether it should return immediately after sending the message.
@yield [builder] Gives the builder to the block to add additional steps, or to do the entire building process.
@yieldparam builder [Builder] The builder given as a parameter which is used as the initial step to start from.
@example Execute the webhook with an already existing builder
builder = Discordrb::Webhooks::Builder.new # ...
client.execute(builder)
@example Execute the webhook by building a new message
client.execute do |builder|
builder.content = 'Testing'
builder.username = 'discordrb'
builder.add_embed do |embed|
embed.timestamp = Time.now
embed.title = 'Testing'
embed.image = Discordrb::Webhooks::EmbedImage.new(url: 'https://i.imgur.com/PcMltU7.jpg')
end
end
@return [RestClient::Response] the response returned by Discord. | [
"Create",
"a",
"new",
"webhook"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/webhooks/client.rb#L41-L54 | train |
meew0/discordrb | lib/discordrb/await.rb | Discordrb.Await.match | def match(event)
dummy_handler = EventContainer.handler_class(@type).new(@attributes, @bot)
return [nil, nil] unless event.instance_of?(@type) && dummy_handler.matches?(event)
should_delete = nil
should_delete = true if (@block && @block.call(event) != false) || !@block
[@key, should_delete]
end | ruby | def match(event)
dummy_handler = EventContainer.handler_class(@type).new(@attributes, @bot)
return [nil, nil] unless event.instance_of?(@type) && dummy_handler.matches?(event)
should_delete = nil
should_delete = true if (@block && @block.call(event) != false) || !@block
[@key, should_delete]
end | [
"def",
"match",
"(",
"event",
")",
"dummy_handler",
"=",
"EventContainer",
".",
"handler_class",
"(",
"@type",
")",
".",
"new",
"(",
"@attributes",
",",
"@bot",
")",
"return",
"[",
"nil",
",",
"nil",
"]",
"unless",
"event",
".",
"instance_of?",
"(",
"@type",
")",
"&&",
"dummy_handler",
".",
"matches?",
"(",
"event",
")",
"should_delete",
"=",
"nil",
"should_delete",
"=",
"true",
"if",
"(",
"@block",
"&&",
"@block",
".",
"call",
"(",
"event",
")",
"!=",
"false",
")",
"||",
"!",
"@block",
"[",
"@key",
",",
"should_delete",
"]",
"end"
] | Makes a new await. For internal use only.
@!visibility private
Checks whether the await can be triggered by the given event, and if it can, execute the block
and return its result along with this await's key.
@param event [Event] An event to check for.
@return [Array] This await's key and whether or not it should be deleted. If there was no match, both are nil. | [
"Makes",
"a",
"new",
"await",
".",
"For",
"internal",
"use",
"only",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/await.rb#L42-L50 | train |
meew0/discordrb | lib/discordrb/events/message.rb | Discordrb::Events.Respondable.drain_into | def drain_into(result)
return if result.is_a?(Discordrb::Message)
result = (@saved_message.nil? ? '' : @saved_message.to_s) + (result.nil? ? '' : result.to_s)
drain
result
end | ruby | def drain_into(result)
return if result.is_a?(Discordrb::Message)
result = (@saved_message.nil? ? '' : @saved_message.to_s) + (result.nil? ? '' : result.to_s)
drain
result
end | [
"def",
"drain_into",
"(",
"result",
")",
"return",
"if",
"result",
".",
"is_a?",
"(",
"Discordrb",
"::",
"Message",
")",
"result",
"=",
"(",
"@saved_message",
".",
"nil?",
"?",
"''",
":",
"@saved_message",
".",
"to_s",
")",
"+",
"(",
"result",
".",
"nil?",
"?",
"''",
":",
"result",
".",
"to_s",
")",
"drain",
"result",
"end"
] | Drains the currently saved message into a result string. This prepends it before that string, clears the saved
message and returns the concatenation.
@param result [String] The result string to drain into.
@return [String] a string formed by concatenating the saved message and the argument. | [
"Drains",
"the",
"currently",
"saved",
"message",
"into",
"a",
"result",
"string",
".",
"This",
"prepends",
"it",
"before",
"that",
"string",
"clears",
"the",
"saved",
"message",
"and",
"returns",
"the",
"concatenation",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/events/message.rb#L62-L68 | train |
meew0/discordrb | lib/discordrb/events/message.rb | Discordrb::Events.MessageEvent.attach_file | def attach_file(file, filename: nil, spoiler: nil)
raise ArgumentError, 'Argument is not a file!' unless file.is_a?(File)
@file = file
@filename = filename
@file_spoiler = spoiler
nil
end | ruby | def attach_file(file, filename: nil, spoiler: nil)
raise ArgumentError, 'Argument is not a file!' unless file.is_a?(File)
@file = file
@filename = filename
@file_spoiler = spoiler
nil
end | [
"def",
"attach_file",
"(",
"file",
",",
"filename",
":",
"nil",
",",
"spoiler",
":",
"nil",
")",
"raise",
"ArgumentError",
",",
"'Argument is not a file!'",
"unless",
"file",
".",
"is_a?",
"(",
"File",
")",
"@file",
"=",
"file",
"@filename",
"=",
"filename",
"@file_spoiler",
"=",
"spoiler",
"nil",
"end"
] | Attaches a file to the message event and converts the message into
a caption.
@param file [File] The file to be attached
@param filename [String] Overrides the filename of the uploaded file
@param spoiler [true, false] Whether or not this file should appear as a spoiler. | [
"Attaches",
"a",
"file",
"to",
"the",
"message",
"event",
"and",
"converts",
"the",
"message",
"into",
"a",
"caption",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/events/message.rb#L142-L149 | train |
meew0/discordrb | lib/discordrb/data/server.rb | Discordrb.Server.role | def role(id)
id = id.resolve_id
@roles.find { |e| e.id == id }
end | ruby | def role(id)
id = id.resolve_id
@roles.find { |e| e.id == id }
end | [
"def",
"role",
"(",
"id",
")",
"id",
"=",
"id",
".",
"resolve_id",
"@roles",
".",
"find",
"{",
"|",
"e",
"|",
"e",
".",
"id",
"==",
"id",
"}",
"end"
] | Gets a role on this server based on its ID.
@param id [Integer, String, #resolve_id] The role ID to look for. | [
"Gets",
"a",
"role",
"on",
"this",
"server",
"based",
"on",
"its",
"ID",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L114-L117 | train |
meew0/discordrb | lib/discordrb/data/server.rb | Discordrb.Server.member | def member(id, request = true)
id = id.resolve_id
return @members[id] if member_cached?(id)
return nil unless request
member = @bot.member(self, id)
@members[id] = member unless member.nil?
rescue StandardError
nil
end | ruby | def member(id, request = true)
id = id.resolve_id
return @members[id] if member_cached?(id)
return nil unless request
member = @bot.member(self, id)
@members[id] = member unless member.nil?
rescue StandardError
nil
end | [
"def",
"member",
"(",
"id",
",",
"request",
"=",
"true",
")",
"id",
"=",
"id",
".",
"resolve_id",
"return",
"@members",
"[",
"id",
"]",
"if",
"member_cached?",
"(",
"id",
")",
"return",
"nil",
"unless",
"request",
"member",
"=",
"@bot",
".",
"member",
"(",
"self",
",",
"id",
")",
"@members",
"[",
"id",
"]",
"=",
"member",
"unless",
"member",
".",
"nil?",
"rescue",
"StandardError",
"nil",
"end"
] | Gets a member on this server based on user ID
@param id [Integer] The user ID to look for
@param request [true, false] Whether the member should be requested from Discord if it's not cached | [
"Gets",
"a",
"member",
"on",
"this",
"server",
"based",
"on",
"user",
"ID"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L122-L131 | train |
meew0/discordrb | lib/discordrb/data/server.rb | Discordrb.Server.prune_count | def prune_count(days)
raise ArgumentError, 'Days must be between 1 and 30' unless days.between?(1, 30)
response = JSON.parse API::Server.prune_count(@bot.token, @id, days)
response['pruned']
end | ruby | def prune_count(days)
raise ArgumentError, 'Days must be between 1 and 30' unless days.between?(1, 30)
response = JSON.parse API::Server.prune_count(@bot.token, @id, days)
response['pruned']
end | [
"def",
"prune_count",
"(",
"days",
")",
"raise",
"ArgumentError",
",",
"'Days must be between 1 and 30'",
"unless",
"days",
".",
"between?",
"(",
"1",
",",
"30",
")",
"response",
"=",
"JSON",
".",
"parse",
"API",
"::",
"Server",
".",
"prune_count",
"(",
"@bot",
".",
"token",
",",
"@id",
",",
"days",
")",
"response",
"[",
"'pruned'",
"]",
"end"
] | Returns the amount of members that are candidates for pruning
@param days [Integer] the number of days to consider for inactivity
@return [Integer] number of members to be removed
@raise [ArgumentError] if days is not between 1 and 30 (inclusive) | [
"Returns",
"the",
"amount",
"of",
"members",
"that",
"are",
"candidates",
"for",
"pruning"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L276-L281 | train |
meew0/discordrb | lib/discordrb/data/server.rb | Discordrb.Server.delete_role | def delete_role(role_id)
@roles.reject! { |r| r.id == role_id }
@members.each do |_, member|
new_roles = member.roles.reject { |r| r.id == role_id }
member.update_roles(new_roles)
end
@channels.each do |channel|
overwrites = channel.permission_overwrites.reject { |id, _| id == role_id }
channel.update_overwrites(overwrites)
end
end | ruby | def delete_role(role_id)
@roles.reject! { |r| r.id == role_id }
@members.each do |_, member|
new_roles = member.roles.reject { |r| r.id == role_id }
member.update_roles(new_roles)
end
@channels.each do |channel|
overwrites = channel.permission_overwrites.reject { |id, _| id == role_id }
channel.update_overwrites(overwrites)
end
end | [
"def",
"delete_role",
"(",
"role_id",
")",
"@roles",
".",
"reject!",
"{",
"|",
"r",
"|",
"r",
".",
"id",
"==",
"role_id",
"}",
"@members",
".",
"each",
"do",
"|",
"_",
",",
"member",
"|",
"new_roles",
"=",
"member",
".",
"roles",
".",
"reject",
"{",
"|",
"r",
"|",
"r",
".",
"id",
"==",
"role_id",
"}",
"member",
".",
"update_roles",
"(",
"new_roles",
")",
"end",
"@channels",
".",
"each",
"do",
"|",
"channel",
"|",
"overwrites",
"=",
"channel",
".",
"permission_overwrites",
".",
"reject",
"{",
"|",
"id",
",",
"_",
"|",
"id",
"==",
"role_id",
"}",
"channel",
".",
"update_overwrites",
"(",
"overwrites",
")",
"end",
"end"
] | Removes a role from the role cache
@note For internal use only
@!visibility private | [
"Removes",
"a",
"role",
"from",
"the",
"role",
"cache"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L365-L375 | train |
meew0/discordrb | lib/discordrb/data/server.rb | Discordrb.Server.update_role_positions | def update_role_positions(role_positions)
response = JSON.parse(API::Server.update_role_positions(@bot.token, @id, role_positions))
response.each do |data|
updated_role = Role.new(data, @bot, self)
role(updated_role.id).update_from(updated_role)
end
end | ruby | def update_role_positions(role_positions)
response = JSON.parse(API::Server.update_role_positions(@bot.token, @id, role_positions))
response.each do |data|
updated_role = Role.new(data, @bot, self)
role(updated_role.id).update_from(updated_role)
end
end | [
"def",
"update_role_positions",
"(",
"role_positions",
")",
"response",
"=",
"JSON",
".",
"parse",
"(",
"API",
"::",
"Server",
".",
"update_role_positions",
"(",
"@bot",
".",
"token",
",",
"@id",
",",
"role_positions",
")",
")",
"response",
".",
"each",
"do",
"|",
"data",
"|",
"updated_role",
"=",
"Role",
".",
"new",
"(",
"data",
",",
"@bot",
",",
"self",
")",
"role",
"(",
"updated_role",
".",
"id",
")",
".",
"update_from",
"(",
"updated_role",
")",
"end",
"end"
] | Updates the positions of all roles on the server
@note For internal use only
@!visibility private | [
"Updates",
"the",
"positions",
"of",
"all",
"roles",
"on",
"the",
"server"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L380-L386 | train |
meew0/discordrb | lib/discordrb/data/server.rb | Discordrb.Server.update_voice_state | def update_voice_state(data)
user_id = data['user_id'].to_i
if data['channel_id']
unless @voice_states[user_id]
# Create a new voice state for the user
@voice_states[user_id] = VoiceState.new(user_id)
end
# Update the existing voice state (or the one we just created)
channel = @channels_by_id[data['channel_id'].to_i]
@voice_states[user_id].update(
channel,
data['mute'],
data['deaf'],
data['self_mute'],
data['self_deaf']
)
else
# The user is not in a voice channel anymore, so delete its voice state
@voice_states.delete(user_id)
end
end | ruby | def update_voice_state(data)
user_id = data['user_id'].to_i
if data['channel_id']
unless @voice_states[user_id]
# Create a new voice state for the user
@voice_states[user_id] = VoiceState.new(user_id)
end
# Update the existing voice state (or the one we just created)
channel = @channels_by_id[data['channel_id'].to_i]
@voice_states[user_id].update(
channel,
data['mute'],
data['deaf'],
data['self_mute'],
data['self_deaf']
)
else
# The user is not in a voice channel anymore, so delete its voice state
@voice_states.delete(user_id)
end
end | [
"def",
"update_voice_state",
"(",
"data",
")",
"user_id",
"=",
"data",
"[",
"'user_id'",
"]",
".",
"to_i",
"if",
"data",
"[",
"'channel_id'",
"]",
"unless",
"@voice_states",
"[",
"user_id",
"]",
"# Create a new voice state for the user",
"@voice_states",
"[",
"user_id",
"]",
"=",
"VoiceState",
".",
"new",
"(",
"user_id",
")",
"end",
"# Update the existing voice state (or the one we just created)",
"channel",
"=",
"@channels_by_id",
"[",
"data",
"[",
"'channel_id'",
"]",
".",
"to_i",
"]",
"@voice_states",
"[",
"user_id",
"]",
".",
"update",
"(",
"channel",
",",
"data",
"[",
"'mute'",
"]",
",",
"data",
"[",
"'deaf'",
"]",
",",
"data",
"[",
"'self_mute'",
"]",
",",
"data",
"[",
"'self_deaf'",
"]",
")",
"else",
"# The user is not in a voice channel anymore, so delete its voice state",
"@voice_states",
".",
"delete",
"(",
"user_id",
")",
"end",
"end"
] | Updates a member's voice state
@note For internal use only
@!visibility private | [
"Updates",
"a",
"member",
"s",
"voice",
"state"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L421-L443 | train |
meew0/discordrb | lib/discordrb/data/server.rb | Discordrb.Server.create_role | def create_role(name: 'new role', colour: 0, hoist: false, mentionable: false, permissions: 104_324_161, reason: nil)
colour = colour.respond_to?(:combined) ? colour.combined : colour
permissions = if permissions.is_a?(Array)
Permissions.bits(permissions)
elsif permissions.respond_to?(:bits)
permissions.bits
else
permissions
end
response = API::Server.create_role(@bot.token, @id, name, colour, hoist, mentionable, permissions, reason)
role = Role.new(JSON.parse(response), @bot, self)
@roles << role
role
end | ruby | def create_role(name: 'new role', colour: 0, hoist: false, mentionable: false, permissions: 104_324_161, reason: nil)
colour = colour.respond_to?(:combined) ? colour.combined : colour
permissions = if permissions.is_a?(Array)
Permissions.bits(permissions)
elsif permissions.respond_to?(:bits)
permissions.bits
else
permissions
end
response = API::Server.create_role(@bot.token, @id, name, colour, hoist, mentionable, permissions, reason)
role = Role.new(JSON.parse(response), @bot, self)
@roles << role
role
end | [
"def",
"create_role",
"(",
"name",
":",
"'new role'",
",",
"colour",
":",
"0",
",",
"hoist",
":",
"false",
",",
"mentionable",
":",
"false",
",",
"permissions",
":",
"104_324_161",
",",
"reason",
":",
"nil",
")",
"colour",
"=",
"colour",
".",
"respond_to?",
"(",
":combined",
")",
"?",
"colour",
".",
"combined",
":",
"colour",
"permissions",
"=",
"if",
"permissions",
".",
"is_a?",
"(",
"Array",
")",
"Permissions",
".",
"bits",
"(",
"permissions",
")",
"elsif",
"permissions",
".",
"respond_to?",
"(",
":bits",
")",
"permissions",
".",
"bits",
"else",
"permissions",
"end",
"response",
"=",
"API",
"::",
"Server",
".",
"create_role",
"(",
"@bot",
".",
"token",
",",
"@id",
",",
"name",
",",
"colour",
",",
"hoist",
",",
"mentionable",
",",
"permissions",
",",
"reason",
")",
"role",
"=",
"Role",
".",
"new",
"(",
"JSON",
".",
"parse",
"(",
"response",
")",
",",
"@bot",
",",
"self",
")",
"@roles",
"<<",
"role",
"role",
"end"
] | Creates a role on this server which can then be modified. It will be initialized
with the regular role defaults the client uses unless specified, i.e. name is "new role",
permissions are the default, colour is the default etc.
@param name [String] Name of the role to create
@param colour [Integer, ColourRGB, #combined] The roles colour
@param hoist [true, false]
@param mentionable [true, false]
@param permissions [Integer, Array<Symbol>, Permissions, #bits] The permissions to write to the new role.
@param reason [String] The reason the for the creation of this role.
@return [Role] the created role. | [
"Creates",
"a",
"role",
"on",
"this",
"server",
"which",
"can",
"then",
"be",
"modified",
".",
"It",
"will",
"be",
"initialized",
"with",
"the",
"regular",
"role",
"defaults",
"the",
"client",
"uses",
"unless",
"specified",
"i",
".",
"e",
".",
"name",
"is",
"new",
"role",
"permissions",
"are",
"the",
"default",
"colour",
"is",
"the",
"default",
"etc",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L484-L500 | train |
meew0/discordrb | lib/discordrb/data/server.rb | Discordrb.Server.add_emoji | def add_emoji(name, image, roles = [], reason: nil)
image_string = image
if image.respond_to? :read
image_string = 'data:image/jpg;base64,'
image_string += Base64.strict_encode64(image.read)
end
data = JSON.parse(API::Server.add_emoji(@bot.token, @id, image_string, name, roles.map(&:resolve_id), reason))
new_emoji = Emoji.new(data)
@emoji[new_emoji.id] = new_emoji
end | ruby | def add_emoji(name, image, roles = [], reason: nil)
image_string = image
if image.respond_to? :read
image_string = 'data:image/jpg;base64,'
image_string += Base64.strict_encode64(image.read)
end
data = JSON.parse(API::Server.add_emoji(@bot.token, @id, image_string, name, roles.map(&:resolve_id), reason))
new_emoji = Emoji.new(data)
@emoji[new_emoji.id] = new_emoji
end | [
"def",
"add_emoji",
"(",
"name",
",",
"image",
",",
"roles",
"=",
"[",
"]",
",",
"reason",
":",
"nil",
")",
"image_string",
"=",
"image",
"if",
"image",
".",
"respond_to?",
":read",
"image_string",
"=",
"'data:image/jpg;base64,'",
"image_string",
"+=",
"Base64",
".",
"strict_encode64",
"(",
"image",
".",
"read",
")",
"end",
"data",
"=",
"JSON",
".",
"parse",
"(",
"API",
"::",
"Server",
".",
"add_emoji",
"(",
"@bot",
".",
"token",
",",
"@id",
",",
"image_string",
",",
"name",
",",
"roles",
".",
"map",
"(",
":resolve_id",
")",
",",
"reason",
")",
")",
"new_emoji",
"=",
"Emoji",
".",
"new",
"(",
"data",
")",
"@emoji",
"[",
"new_emoji",
".",
"id",
"]",
"=",
"new_emoji",
"end"
] | Adds a new custom emoji on this server.
@param name [String] The name of emoji to create.
@param image [String, #read] A base64 encoded string with the image data, or an object that responds to `#read`, such as `File`.
@param roles [Array<Role, String, Integer>] An array of roles, or role IDs to be whitelisted for this emoji.
@param reason [String] The reason the for the creation of this emoji.
@return [Emoji] The emoji that has been added. | [
"Adds",
"a",
"new",
"custom",
"emoji",
"on",
"this",
"server",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L508-L518 | train |
meew0/discordrb | lib/discordrb/data/server.rb | Discordrb.Server.delete_emoji | def delete_emoji(emoji, reason: nil)
API::Server.delete_emoji(@bot.token, @id, emoji.resolve_id, reason)
end | ruby | def delete_emoji(emoji, reason: nil)
API::Server.delete_emoji(@bot.token, @id, emoji.resolve_id, reason)
end | [
"def",
"delete_emoji",
"(",
"emoji",
",",
"reason",
":",
"nil",
")",
"API",
"::",
"Server",
".",
"delete_emoji",
"(",
"@bot",
".",
"token",
",",
"@id",
",",
"emoji",
".",
"resolve_id",
",",
"reason",
")",
"end"
] | Delete a custom emoji on this server
@param emoji [Emoji, Integer, String] The emoji or emoji ID to be deleted.
@param reason [String] The reason the for the deletion of this emoji. | [
"Delete",
"a",
"custom",
"emoji",
"on",
"this",
"server"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L523-L525 | train |
meew0/discordrb | lib/discordrb/data/server.rb | Discordrb.Server.ban | def ban(user, message_days = 0, reason: nil)
API::Server.ban_user(@bot.token, @id, user.resolve_id, message_days, reason)
end | ruby | def ban(user, message_days = 0, reason: nil)
API::Server.ban_user(@bot.token, @id, user.resolve_id, message_days, reason)
end | [
"def",
"ban",
"(",
"user",
",",
"message_days",
"=",
"0",
",",
"reason",
":",
"nil",
")",
"API",
"::",
"Server",
".",
"ban_user",
"(",
"@bot",
".",
"token",
",",
"@id",
",",
"user",
".",
"resolve_id",
",",
"message_days",
",",
"reason",
")",
"end"
] | Bans a user from this server.
@param user [User, #resolve_id] The user to ban.
@param message_days [Integer] How many days worth of messages sent by the user should be deleted.
@param reason [String] The reason the user is being banned. | [
"Bans",
"a",
"user",
"from",
"this",
"server",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L552-L554 | train |
meew0/discordrb | lib/discordrb/data/server.rb | Discordrb.Server.unban | def unban(user, reason = nil)
API::Server.unban_user(@bot.token, @id, user.resolve_id, reason)
end | ruby | def unban(user, reason = nil)
API::Server.unban_user(@bot.token, @id, user.resolve_id, reason)
end | [
"def",
"unban",
"(",
"user",
",",
"reason",
"=",
"nil",
")",
"API",
"::",
"Server",
".",
"unban_user",
"(",
"@bot",
".",
"token",
",",
"@id",
",",
"user",
".",
"resolve_id",
",",
"reason",
")",
"end"
] | Unbans a previously banned user from this server.
@param user [User, #resolve_id] The user to unban.
@param reason [String] The reason the user is being unbanned. | [
"Unbans",
"a",
"previously",
"banned",
"user",
"from",
"this",
"server",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L559-L561 | train |
meew0/discordrb | lib/discordrb/data/server.rb | Discordrb.Server.kick | def kick(user, reason = nil)
API::Server.remove_member(@bot.token, @id, user.resolve_id, reason)
end | ruby | def kick(user, reason = nil)
API::Server.remove_member(@bot.token, @id, user.resolve_id, reason)
end | [
"def",
"kick",
"(",
"user",
",",
"reason",
"=",
"nil",
")",
"API",
"::",
"Server",
".",
"remove_member",
"(",
"@bot",
".",
"token",
",",
"@id",
",",
"user",
".",
"resolve_id",
",",
"reason",
")",
"end"
] | Kicks a user from this server.
@param user [User, #resolve_id] The user to kick.
@param reason [String] The reason the user is being kicked. | [
"Kicks",
"a",
"user",
"from",
"this",
"server",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L566-L568 | train |
meew0/discordrb | lib/discordrb/data/server.rb | Discordrb.Server.move | def move(user, channel)
API::Server.update_member(@bot.token, @id, user.resolve_id, channel_id: channel.resolve_id)
end | ruby | def move(user, channel)
API::Server.update_member(@bot.token, @id, user.resolve_id, channel_id: channel.resolve_id)
end | [
"def",
"move",
"(",
"user",
",",
"channel",
")",
"API",
"::",
"Server",
".",
"update_member",
"(",
"@bot",
".",
"token",
",",
"@id",
",",
"user",
".",
"resolve_id",
",",
"channel_id",
":",
"channel",
".",
"resolve_id",
")",
"end"
] | Forcibly moves a user into a different voice channel. Only works if the bot has the permission needed.
@param user [User, #resolve_id] The user to move.
@param channel [Channel, #resolve_id] The voice channel to move into. | [
"Forcibly",
"moves",
"a",
"user",
"into",
"a",
"different",
"voice",
"channel",
".",
"Only",
"works",
"if",
"the",
"bot",
"has",
"the",
"permission",
"needed",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L573-L575 | train |
meew0/discordrb | lib/discordrb/data/server.rb | Discordrb.Server.icon= | def icon=(icon)
if icon.respond_to? :read
icon_string = 'data:image/jpg;base64,'
icon_string += Base64.strict_encode64(icon.read)
update_server_data(icon_id: icon_string)
else
update_server_data(icon_id: icon)
end
end | ruby | def icon=(icon)
if icon.respond_to? :read
icon_string = 'data:image/jpg;base64,'
icon_string += Base64.strict_encode64(icon.read)
update_server_data(icon_id: icon_string)
else
update_server_data(icon_id: icon)
end
end | [
"def",
"icon",
"=",
"(",
"icon",
")",
"if",
"icon",
".",
"respond_to?",
":read",
"icon_string",
"=",
"'data:image/jpg;base64,'",
"icon_string",
"+=",
"Base64",
".",
"strict_encode64",
"(",
"icon",
".",
"read",
")",
"update_server_data",
"(",
"icon_id",
":",
"icon_string",
")",
"else",
"update_server_data",
"(",
"icon_id",
":",
"icon",
")",
"end",
"end"
] | Sets the server's icon.
@param icon [String, #read] The new icon, in base64-encoded JPG format. | [
"Sets",
"the",
"server",
"s",
"icon",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L623-L631 | train |
meew0/discordrb | lib/discordrb/data/server.rb | Discordrb.Server.verification_level= | def verification_level=(level)
level = VERIFICATION_LEVELS[level] if level.is_a?(Symbol)
update_server_data(verification_level: level)
end | ruby | def verification_level=(level)
level = VERIFICATION_LEVELS[level] if level.is_a?(Symbol)
update_server_data(verification_level: level)
end | [
"def",
"verification_level",
"=",
"(",
"level",
")",
"level",
"=",
"VERIFICATION_LEVELS",
"[",
"level",
"]",
"if",
"level",
".",
"is_a?",
"(",
"Symbol",
")",
"update_server_data",
"(",
"verification_level",
":",
"level",
")",
"end"
] | Sets the verification level of the server
@param level [Integer, Symbol] The verification level from 0-4 or Symbol (see {VERIFICATION_LEVELS}) | [
"Sets",
"the",
"verification",
"level",
"of",
"the",
"server"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L667-L671 | train |
meew0/discordrb | lib/discordrb/data/server.rb | Discordrb.Server.default_message_notifications= | def default_message_notifications=(notification_level)
notification_level = NOTIFICATION_LEVELS[notification_level] if notification_level.is_a?(Symbol)
update_server_data(default_message_notifications: notification_level)
end | ruby | def default_message_notifications=(notification_level)
notification_level = NOTIFICATION_LEVELS[notification_level] if notification_level.is_a?(Symbol)
update_server_data(default_message_notifications: notification_level)
end | [
"def",
"default_message_notifications",
"=",
"(",
"notification_level",
")",
"notification_level",
"=",
"NOTIFICATION_LEVELS",
"[",
"notification_level",
"]",
"if",
"notification_level",
".",
"is_a?",
"(",
"Symbol",
")",
"update_server_data",
"(",
"default_message_notifications",
":",
"notification_level",
")",
"end"
] | Sets the default message notification level
@param notification_level [Integer, Symbol] The default message notificiation 0-1 or Symbol (see {NOTIFICATION_LEVELS}) | [
"Sets",
"the",
"default",
"message",
"notification",
"level"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L686-L690 | train |
meew0/discordrb | lib/discordrb/data/server.rb | Discordrb.Server.explicit_content_filter= | def explicit_content_filter=(filter_level)
filter_level = FILTER_LEVELS[filter_level] if filter_level.is_a?(Symbol)
update_server_data(explicit_content_filter: filter_level)
end | ruby | def explicit_content_filter=(filter_level)
filter_level = FILTER_LEVELS[filter_level] if filter_level.is_a?(Symbol)
update_server_data(explicit_content_filter: filter_level)
end | [
"def",
"explicit_content_filter",
"=",
"(",
"filter_level",
")",
"filter_level",
"=",
"FILTER_LEVELS",
"[",
"filter_level",
"]",
"if",
"filter_level",
".",
"is_a?",
"(",
"Symbol",
")",
"update_server_data",
"(",
"explicit_content_filter",
":",
"filter_level",
")",
"end"
] | Sets the server content filter.
@param filter_level [Integer, Symbol] The content filter from 0-2 or Symbol (see {FILTER_LEVELS}) | [
"Sets",
"the",
"server",
"content",
"filter",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L716-L720 | train |
meew0/discordrb | lib/discordrb/data/server.rb | Discordrb.Server.webhooks | def webhooks
webhooks = JSON.parse(API::Server.webhooks(@bot.token, @id))
webhooks.map { |webhook| Webhook.new(webhook, @bot) }
end | ruby | def webhooks
webhooks = JSON.parse(API::Server.webhooks(@bot.token, @id))
webhooks.map { |webhook| Webhook.new(webhook, @bot) }
end | [
"def",
"webhooks",
"webhooks",
"=",
"JSON",
".",
"parse",
"(",
"API",
"::",
"Server",
".",
"webhooks",
"(",
"@bot",
".",
"token",
",",
"@id",
")",
")",
"webhooks",
".",
"map",
"{",
"|",
"webhook",
"|",
"Webhook",
".",
"new",
"(",
"webhook",
",",
"@bot",
")",
"}",
"end"
] | Requests a list of Webhooks on the server.
@return [Array<Webhook>] webhooks on the server. | [
"Requests",
"a",
"list",
"of",
"Webhooks",
"on",
"the",
"server",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L732-L735 | train |
meew0/discordrb | lib/discordrb/data/server.rb | Discordrb.Server.invites | def invites
invites = JSON.parse(API::Server.invites(@bot.token, @id))
invites.map { |invite| Invite.new(invite, @bot) }
end | ruby | def invites
invites = JSON.parse(API::Server.invites(@bot.token, @id))
invites.map { |invite| Invite.new(invite, @bot) }
end | [
"def",
"invites",
"invites",
"=",
"JSON",
".",
"parse",
"(",
"API",
"::",
"Server",
".",
"invites",
"(",
"@bot",
".",
"token",
",",
"@id",
")",
")",
"invites",
".",
"map",
"{",
"|",
"invite",
"|",
"Invite",
".",
"new",
"(",
"invite",
",",
"@bot",
")",
"}",
"end"
] | Requests a list of Invites to the server.
@return [Array<Invite>] invites to the server. | [
"Requests",
"a",
"list",
"of",
"Invites",
"to",
"the",
"server",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L739-L742 | train |
meew0/discordrb | lib/discordrb/data/server.rb | Discordrb.Server.process_chunk | def process_chunk(members)
process_members(members)
@processed_chunk_members += members.length
LOGGER.debug("Processed one chunk on server #{@id} - length #{members.length}")
# Don't bother with the rest of the method if it's not truly the last packet
return unless @processed_chunk_members == @member_count
LOGGER.debug("Finished chunking server #{@id}")
# Reset everything to normal
@chunked = true
@processed_chunk_members = 0
end | ruby | def process_chunk(members)
process_members(members)
@processed_chunk_members += members.length
LOGGER.debug("Processed one chunk on server #{@id} - length #{members.length}")
# Don't bother with the rest of the method if it's not truly the last packet
return unless @processed_chunk_members == @member_count
LOGGER.debug("Finished chunking server #{@id}")
# Reset everything to normal
@chunked = true
@processed_chunk_members = 0
end | [
"def",
"process_chunk",
"(",
"members",
")",
"process_members",
"(",
"members",
")",
"@processed_chunk_members",
"+=",
"members",
".",
"length",
"LOGGER",
".",
"debug",
"(",
"\"Processed one chunk on server #{@id} - length #{members.length}\"",
")",
"# Don't bother with the rest of the method if it's not truly the last packet",
"return",
"unless",
"@processed_chunk_members",
"==",
"@member_count",
"LOGGER",
".",
"debug",
"(",
"\"Finished chunking server #{@id}\"",
")",
"# Reset everything to normal",
"@chunked",
"=",
"true",
"@processed_chunk_members",
"=",
"0",
"end"
] | Processes a GUILD_MEMBERS_CHUNK packet, specifically the members field
@note For internal use only
@!visibility private | [
"Processes",
"a",
"GUILD_MEMBERS_CHUNK",
"packet",
"specifically",
"the",
"members",
"field"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/server.rb#L747-L760 | train |
meew0/discordrb | lib/discordrb/voice/encoder.rb | Discordrb::Voice.Encoder.adjust_volume | def adjust_volume(buf, mult)
# We don't need to adjust anything if the buf is nil so just return in that case
return unless buf
# buf is s16le so use 's<' for signed, 16 bit, LE
result = buf.unpack('s<*').map do |sample|
sample *= mult
# clamp to s16 range
[32_767, [-32_768, sample].max].min
end
# After modification, make it s16le again
result.pack('s<*')
end | ruby | def adjust_volume(buf, mult)
# We don't need to adjust anything if the buf is nil so just return in that case
return unless buf
# buf is s16le so use 's<' for signed, 16 bit, LE
result = buf.unpack('s<*').map do |sample|
sample *= mult
# clamp to s16 range
[32_767, [-32_768, sample].max].min
end
# After modification, make it s16le again
result.pack('s<*')
end | [
"def",
"adjust_volume",
"(",
"buf",
",",
"mult",
")",
"# We don't need to adjust anything if the buf is nil so just return in that case",
"return",
"unless",
"buf",
"# buf is s16le so use 's<' for signed, 16 bit, LE",
"result",
"=",
"buf",
".",
"unpack",
"(",
"'s<*'",
")",
".",
"map",
"do",
"|",
"sample",
"|",
"sample",
"*=",
"mult",
"# clamp to s16 range",
"[",
"32_767",
",",
"[",
"-",
"32_768",
",",
"sample",
"]",
".",
"max",
"]",
".",
"min",
"end",
"# After modification, make it s16le again",
"result",
".",
"pack",
"(",
"'s<*'",
")",
"end"
] | Adjusts the volume of a given buffer of s16le PCM data.
@param buf [String] An unencoded PCM (s16le) buffer.
@param mult [Float] The volume multiplier, 1 for same volume.
@return [String] The buffer with adjusted volume, s16le again | [
"Adjusts",
"the",
"volume",
"of",
"a",
"given",
"buffer",
"of",
"s16le",
"PCM",
"data",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/voice/encoder.rb#L57-L71 | train |
meew0/discordrb | lib/discordrb/commands/container.rb | Discordrb::Commands.CommandContainer.command | def command(name, attributes = {}, &block)
@commands ||= {}
if name.is_a? Array
new_command = nil
name.each do |e|
new_command = Command.new(e, attributes, &block)
@commands[e] = new_command
end
new_command
else
new_command = Command.new(name, attributes, &block)
new_command.attributes[:aliases].each do |aliased_name|
@commands[aliased_name] = CommandAlias.new(aliased_name, new_command)
end
@commands[name] = new_command
end
end | ruby | def command(name, attributes = {}, &block)
@commands ||= {}
if name.is_a? Array
new_command = nil
name.each do |e|
new_command = Command.new(e, attributes, &block)
@commands[e] = new_command
end
new_command
else
new_command = Command.new(name, attributes, &block)
new_command.attributes[:aliases].each do |aliased_name|
@commands[aliased_name] = CommandAlias.new(aliased_name, new_command)
end
@commands[name] = new_command
end
end | [
"def",
"command",
"(",
"name",
",",
"attributes",
"=",
"{",
"}",
",",
"&",
"block",
")",
"@commands",
"||=",
"{",
"}",
"if",
"name",
".",
"is_a?",
"Array",
"new_command",
"=",
"nil",
"name",
".",
"each",
"do",
"|",
"e",
"|",
"new_command",
"=",
"Command",
".",
"new",
"(",
"e",
",",
"attributes",
",",
"block",
")",
"@commands",
"[",
"e",
"]",
"=",
"new_command",
"end",
"new_command",
"else",
"new_command",
"=",
"Command",
".",
"new",
"(",
"name",
",",
"attributes",
",",
"block",
")",
"new_command",
".",
"attributes",
"[",
":aliases",
"]",
".",
"each",
"do",
"|",
"aliased_name",
"|",
"@commands",
"[",
"aliased_name",
"]",
"=",
"CommandAlias",
".",
"new",
"(",
"aliased_name",
",",
"new_command",
")",
"end",
"@commands",
"[",
"name",
"]",
"=",
"new_command",
"end",
"end"
] | Adds a new command to the container.
@param name [Symbol, Array<Symbol>] The name of the command to add, or an array of multiple names for the command
@param attributes [Hash] The attributes to initialize the command with.
@option attributes [Integer] :permission_level The minimum permission level that can use this command, inclusive.
See {CommandBot#set_user_permission} and {CommandBot#set_role_permission}.
@option attributes [String, false] :permission_message Message to display when a user does not have sufficient
permissions to execute a command. %name% in the message will be replaced with the name of the command. Disable
the message by setting this option to false.
@option attributes [Array<Symbol>] :required_permissions Discord action permissions (e.g. `:kick_members`) that
should be required to use this command. See {Discordrb::Permissions::FLAGS} for a list.
@option attributes [Array<Role>, Array<#resolve_id>] :required_roles Roles that user must have to use this command
(user must have all of them).
@option attributes [Array<Role>, Array<#resolve_id>] :allowed_roles Roles that user should have to use this command
(user should have at least one of them).
@option attributes [Array<String, Integer, Channel>] :channels The channels that this command can be used on. An
empty array indicates it can be used on any channel. Supersedes the command bot attribute.
@option attributes [true, false] :chain_usable Whether this command is able to be used inside of a command chain
or sub-chain. Typically used for administrative commands that shouldn't be done carelessly.
@option attributes [true, false] :help_available Whether this command is visible in the help command. See the
:help_command attribute of {CommandBot#initialize}.
@option attributes [String] :description A short description of what this command does. Will be shown in the help
command if the user asks for it.
@option attributes [String] :usage A short description of how this command should be used. Will be displayed in
the help command or if the user uses it wrong.
@option attributes [Array<Class>] :arg_types An array of argument classes which will be used for type-checking.
Hard-coded for some native classes, but can be used with any class that implements static
method `from_argument`.
@option attributes [Integer] :min_args The minimum number of arguments this command should have. If a user
attempts to call the command with fewer arguments, the usage information will be displayed, if it exists.
@option attributes [Integer] :max_args The maximum number of arguments the command should have.
@option attributes [String] :rate_limit_message The message that should be displayed if the command hits a rate
limit. None if unspecified or nil. %time% in the message will be replaced with the time in seconds when the
command will be available again.
@option attributes [Symbol] :bucket The rate limit bucket that should be used for rate limiting. No rate limiting
will be done if unspecified or nil.
@option attributes [String, #call] :rescue A string to respond with, or a block to be called in the event an exception
is raised internally. If given a String, `%exception%` will be substituted with the exception's `#message`. If given
a `Proc`, it will be passed the `CommandEvent` along with the `Exception`.
@yield The block is executed when the command is executed.
@yieldparam event [CommandEvent] The event of the message that contained the command.
@note `LocalJumpError`s are rescued from internally, giving bots the opportunity to use `return` or `break` in
their blocks without propagating an exception.
@return [Command] The command that was added.
@deprecated The command name argument will no longer support arrays in the next release.
Use the `aliases` attribute instead. | [
"Adds",
"a",
"new",
"command",
"to",
"the",
"container",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/commands/container.rb#L60-L78 | train |
meew0/discordrb | lib/discordrb/data/profile.rb | Discordrb.Profile.avatar= | def avatar=(avatar)
if avatar.respond_to? :read
# Set the file to binary mode if supported, so we don't get problems with Windows
avatar.binmode if avatar.respond_to?(:binmode)
avatar_string = 'data:image/jpg;base64,'
avatar_string += Base64.strict_encode64(avatar.read)
update_profile_data(avatar: avatar_string)
else
update_profile_data(avatar: avatar)
end
end | ruby | def avatar=(avatar)
if avatar.respond_to? :read
# Set the file to binary mode if supported, so we don't get problems with Windows
avatar.binmode if avatar.respond_to?(:binmode)
avatar_string = 'data:image/jpg;base64,'
avatar_string += Base64.strict_encode64(avatar.read)
update_profile_data(avatar: avatar_string)
else
update_profile_data(avatar: avatar)
end
end | [
"def",
"avatar",
"=",
"(",
"avatar",
")",
"if",
"avatar",
".",
"respond_to?",
":read",
"# Set the file to binary mode if supported, so we don't get problems with Windows",
"avatar",
".",
"binmode",
"if",
"avatar",
".",
"respond_to?",
"(",
":binmode",
")",
"avatar_string",
"=",
"'data:image/jpg;base64,'",
"avatar_string",
"+=",
"Base64",
".",
"strict_encode64",
"(",
"avatar",
".",
"read",
")",
"update_profile_data",
"(",
"avatar",
":",
"avatar_string",
")",
"else",
"update_profile_data",
"(",
"avatar",
":",
"avatar",
")",
"end",
"end"
] | Changes the bot's avatar.
@param avatar [String, #read] A JPG file to be used as the avatar, either
something readable (e.g. File Object) or as a data URL. | [
"Changes",
"the",
"bot",
"s",
"avatar",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/data/profile.rb#L28-L39 | train |
meew0/discordrb | lib/discordrb/voice/network.rb | Discordrb::Voice.VoiceUDP.connect | def connect(endpoint, port, ssrc)
@endpoint = endpoint
@endpoint = @endpoint[6..-1] if @endpoint.start_with? 'wss://'
@endpoint = @endpoint.gsub(':80', '') # The endpoint may contain a port, we don't want that
@endpoint = Resolv.getaddress @endpoint
@port = port
@ssrc = ssrc
end | ruby | def connect(endpoint, port, ssrc)
@endpoint = endpoint
@endpoint = @endpoint[6..-1] if @endpoint.start_with? 'wss://'
@endpoint = @endpoint.gsub(':80', '') # The endpoint may contain a port, we don't want that
@endpoint = Resolv.getaddress @endpoint
@port = port
@ssrc = ssrc
end | [
"def",
"connect",
"(",
"endpoint",
",",
"port",
",",
"ssrc",
")",
"@endpoint",
"=",
"endpoint",
"@endpoint",
"=",
"@endpoint",
"[",
"6",
"..",
"-",
"1",
"]",
"if",
"@endpoint",
".",
"start_with?",
"'wss://'",
"@endpoint",
"=",
"@endpoint",
".",
"gsub",
"(",
"':80'",
",",
"''",
")",
"# The endpoint may contain a port, we don't want that",
"@endpoint",
"=",
"Resolv",
".",
"getaddress",
"@endpoint",
"@port",
"=",
"port",
"@ssrc",
"=",
"ssrc",
"end"
] | Creates a new UDP connection. Only creates a socket as the discovery reply may come before the data is
initialized.
Initializes the UDP socket with data obtained from opcode 2.
@param endpoint [String] The voice endpoint to connect to.
@param port [Integer] The port to connect to.
@param ssrc [Integer] The Super Secret Relay Code (SSRC). Discord uses this to identify different voice users
on the same endpoint. | [
"Creates",
"a",
"new",
"UDP",
"connection",
".",
"Only",
"creates",
"a",
"socket",
"as",
"the",
"discovery",
"reply",
"may",
"come",
"before",
"the",
"data",
"is",
"initialized",
".",
"Initializes",
"the",
"UDP",
"socket",
"with",
"data",
"obtained",
"from",
"opcode",
"2",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/voice/network.rb#L50-L58 | train |
meew0/discordrb | lib/discordrb/voice/network.rb | Discordrb::Voice.VoiceUDP.receive_discovery_reply | def receive_discovery_reply
# Wait for a UDP message
message = @socket.recv(70)
ip = message[4..-3].delete("\0")
port = message[-2..-1].to_i
[ip, port]
end | ruby | def receive_discovery_reply
# Wait for a UDP message
message = @socket.recv(70)
ip = message[4..-3].delete("\0")
port = message[-2..-1].to_i
[ip, port]
end | [
"def",
"receive_discovery_reply",
"# Wait for a UDP message",
"message",
"=",
"@socket",
".",
"recv",
"(",
"70",
")",
"ip",
"=",
"message",
"[",
"4",
"..",
"-",
"3",
"]",
".",
"delete",
"(",
"\"\\0\"",
")",
"port",
"=",
"message",
"[",
"-",
"2",
"..",
"-",
"1",
"]",
".",
"to_i",
"[",
"ip",
",",
"port",
"]",
"end"
] | Waits for a UDP discovery reply, and returns the sent data.
@return [Array(String, Integer)] the IP and port received from the discovery reply. | [
"Waits",
"for",
"a",
"UDP",
"discovery",
"reply",
"and",
"returns",
"the",
"sent",
"data",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/voice/network.rb#L62-L68 | train |
meew0/discordrb | lib/discordrb/voice/network.rb | Discordrb::Voice.VoiceUDP.send_audio | def send_audio(buf, sequence, time)
# Header of the audio packet
header = [0x80, 0x78, sequence, time, @ssrc].pack('CCnNN')
# Encrypt data, if necessary
buf = encrypt_audio(header, buf) if encrypted?
send_packet(header + buf)
end | ruby | def send_audio(buf, sequence, time)
# Header of the audio packet
header = [0x80, 0x78, sequence, time, @ssrc].pack('CCnNN')
# Encrypt data, if necessary
buf = encrypt_audio(header, buf) if encrypted?
send_packet(header + buf)
end | [
"def",
"send_audio",
"(",
"buf",
",",
"sequence",
",",
"time",
")",
"# Header of the audio packet",
"header",
"=",
"[",
"0x80",
",",
"0x78",
",",
"sequence",
",",
"time",
",",
"@ssrc",
"]",
".",
"pack",
"(",
"'CCnNN'",
")",
"# Encrypt data, if necessary",
"buf",
"=",
"encrypt_audio",
"(",
"header",
",",
"buf",
")",
"if",
"encrypted?",
"send_packet",
"(",
"header",
"+",
"buf",
")",
"end"
] | Makes an audio packet from a buffer and sends it to Discord.
@param buf [String] The audio data to send, must be exactly one Opus frame
@param sequence [Integer] The packet sequence number, incremented by one for subsequent packets
@param time [Integer] When this packet should be played back, in no particular unit (essentially just the
sequence number multiplied by 960) | [
"Makes",
"an",
"audio",
"packet",
"from",
"a",
"buffer",
"and",
"sends",
"it",
"to",
"Discord",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/voice/network.rb#L75-L83 | train |
meew0/discordrb | lib/discordrb/voice/network.rb | Discordrb::Voice.VoiceUDP.encrypt_audio | def encrypt_audio(header, buf)
raise 'No secret key found, despite encryption being enabled!' unless @secret_key
box = RbNaCl::SecretBox.new(@secret_key)
# The nonce is the header of the voice packet with 12 null bytes appended
nonce = header + ([0] * 12).pack('C*')
box.encrypt(nonce, buf)
end | ruby | def encrypt_audio(header, buf)
raise 'No secret key found, despite encryption being enabled!' unless @secret_key
box = RbNaCl::SecretBox.new(@secret_key)
# The nonce is the header of the voice packet with 12 null bytes appended
nonce = header + ([0] * 12).pack('C*')
box.encrypt(nonce, buf)
end | [
"def",
"encrypt_audio",
"(",
"header",
",",
"buf",
")",
"raise",
"'No secret key found, despite encryption being enabled!'",
"unless",
"@secret_key",
"box",
"=",
"RbNaCl",
"::",
"SecretBox",
".",
"new",
"(",
"@secret_key",
")",
"# The nonce is the header of the voice packet with 12 null bytes appended",
"nonce",
"=",
"header",
"+",
"(",
"[",
"0",
"]",
"*",
"12",
")",
".",
"pack",
"(",
"'C*'",
")",
"box",
".",
"encrypt",
"(",
"nonce",
",",
"buf",
")",
"end"
] | Encrypts audio data using RbNaCl
@param header [String] The header of the packet, to be used as the nonce
@param buf [String] The encoded audio data to be encrypted
@return [String] the audio data, encrypted | [
"Encrypts",
"audio",
"data",
"using",
"RbNaCl"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/voice/network.rb#L101-L110 | train |
meew0/discordrb | lib/discordrb/commands/rate_limiter.rb | Discordrb::Commands.RateLimiter.rate_limited? | def rate_limited?(key, thing, increment: 1)
# Check whether the bucket actually exists
return false unless @buckets && @buckets[key]
@buckets[key].rate_limited?(thing, increment: increment)
end | ruby | def rate_limited?(key, thing, increment: 1)
# Check whether the bucket actually exists
return false unless @buckets && @buckets[key]
@buckets[key].rate_limited?(thing, increment: increment)
end | [
"def",
"rate_limited?",
"(",
"key",
",",
"thing",
",",
"increment",
":",
"1",
")",
"# Check whether the bucket actually exists",
"return",
"false",
"unless",
"@buckets",
"&&",
"@buckets",
"[",
"key",
"]",
"@buckets",
"[",
"key",
"]",
".",
"rate_limited?",
"(",
"thing",
",",
"increment",
":",
"increment",
")",
"end"
] | Performs a rate limit request.
@param key [Symbol] Which bucket to perform the request for.
@param thing [#resolve_id, Integer, Symbol] What should be rate-limited.
@param increment (see Bucket#rate_limited?)
@see Bucket#rate_limited?
@return [Integer, false] How much time to wait or false if the request succeeded. | [
"Performs",
"a",
"rate",
"limit",
"request",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/commands/rate_limiter.rb#L112-L117 | train |
meew0/discordrb | lib/discordrb/commands/rate_limiter.rb | Discordrb::Commands.Bucket.clean | def clean(rate_limit_time = nil)
rate_limit_time ||= Time.now
@bucket.delete_if do |_, limit_hash|
# Time limit has not run out
return false if @time_span && rate_limit_time < (limit_hash[:set_time] + @time_span)
# Delay has not run out
return false if @delay && rate_limit_time < (limit_hash[:last_time] + @delay)
true
end
end | ruby | def clean(rate_limit_time = nil)
rate_limit_time ||= Time.now
@bucket.delete_if do |_, limit_hash|
# Time limit has not run out
return false if @time_span && rate_limit_time < (limit_hash[:set_time] + @time_span)
# Delay has not run out
return false if @delay && rate_limit_time < (limit_hash[:last_time] + @delay)
true
end
end | [
"def",
"clean",
"(",
"rate_limit_time",
"=",
"nil",
")",
"rate_limit_time",
"||=",
"Time",
".",
"now",
"@bucket",
".",
"delete_if",
"do",
"|",
"_",
",",
"limit_hash",
"|",
"# Time limit has not run out",
"return",
"false",
"if",
"@time_span",
"&&",
"rate_limit_time",
"<",
"(",
"limit_hash",
"[",
":set_time",
"]",
"+",
"@time_span",
")",
"# Delay has not run out",
"return",
"false",
"if",
"@delay",
"&&",
"rate_limit_time",
"<",
"(",
"limit_hash",
"[",
":last_time",
"]",
"+",
"@delay",
")",
"true",
"end",
"end"
] | Makes a new bucket
@param limit [Integer, nil] How many requests the user may perform in the given time_span, or nil if there should be no limit.
@param time_span [Integer, nil] The time span after which the request count is reset, in seconds, or nil if the bucket should never be reset. (If this is nil, limit should be nil too)
@param delay [Integer, nil] The delay for which the user has to wait after performing a request, in seconds, or nil if the user shouldn't have to wait.
Cleans the bucket, removing all elements that aren't necessary anymore
@param rate_limit_time [Time] The time to base the cleaning on, only useful for testing. | [
"Makes",
"a",
"new",
"bucket"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/commands/rate_limiter.rb#L23-L35 | train |
meew0/discordrb | lib/discordrb/commands/rate_limiter.rb | Discordrb::Commands.Bucket.rate_limited? | def rate_limited?(thing, rate_limit_time = nil, increment: 1)
key = resolve_key thing
limit_hash = @bucket[key]
# First case: limit_hash doesn't exist yet
unless limit_hash
@bucket[key] = {
last_time: Time.now,
set_time: Time.now,
count: increment
}
return false
end
# Define the time at which we're being rate limited once so it doesn't get inaccurate
rate_limit_time ||= Time.now
if @limit && (limit_hash[:count] + increment) > @limit
# Second case: Count is over the limit and the time has not run out yet
return (limit_hash[:set_time] + @time_span) - rate_limit_time if @time_span && rate_limit_time < (limit_hash[:set_time] + @time_span)
# Third case: Count is over the limit but the time has run out
# Don't return anything here because there may still be delay-based limiting
limit_hash[:set_time] = rate_limit_time
limit_hash[:count] = 0
end
if @delay && rate_limit_time < (limit_hash[:last_time] + @delay)
# Fourth case: we're being delayed
(limit_hash[:last_time] + @delay) - rate_limit_time
else
# Fifth case: no rate limiting at all! Increment the count, set the last_time, and return false
limit_hash[:last_time] = rate_limit_time
limit_hash[:count] += increment
false
end
end | ruby | def rate_limited?(thing, rate_limit_time = nil, increment: 1)
key = resolve_key thing
limit_hash = @bucket[key]
# First case: limit_hash doesn't exist yet
unless limit_hash
@bucket[key] = {
last_time: Time.now,
set_time: Time.now,
count: increment
}
return false
end
# Define the time at which we're being rate limited once so it doesn't get inaccurate
rate_limit_time ||= Time.now
if @limit && (limit_hash[:count] + increment) > @limit
# Second case: Count is over the limit and the time has not run out yet
return (limit_hash[:set_time] + @time_span) - rate_limit_time if @time_span && rate_limit_time < (limit_hash[:set_time] + @time_span)
# Third case: Count is over the limit but the time has run out
# Don't return anything here because there may still be delay-based limiting
limit_hash[:set_time] = rate_limit_time
limit_hash[:count] = 0
end
if @delay && rate_limit_time < (limit_hash[:last_time] + @delay)
# Fourth case: we're being delayed
(limit_hash[:last_time] + @delay) - rate_limit_time
else
# Fifth case: no rate limiting at all! Increment the count, set the last_time, and return false
limit_hash[:last_time] = rate_limit_time
limit_hash[:count] += increment
false
end
end | [
"def",
"rate_limited?",
"(",
"thing",
",",
"rate_limit_time",
"=",
"nil",
",",
"increment",
":",
"1",
")",
"key",
"=",
"resolve_key",
"thing",
"limit_hash",
"=",
"@bucket",
"[",
"key",
"]",
"# First case: limit_hash doesn't exist yet",
"unless",
"limit_hash",
"@bucket",
"[",
"key",
"]",
"=",
"{",
"last_time",
":",
"Time",
".",
"now",
",",
"set_time",
":",
"Time",
".",
"now",
",",
"count",
":",
"increment",
"}",
"return",
"false",
"end",
"# Define the time at which we're being rate limited once so it doesn't get inaccurate",
"rate_limit_time",
"||=",
"Time",
".",
"now",
"if",
"@limit",
"&&",
"(",
"limit_hash",
"[",
":count",
"]",
"+",
"increment",
")",
">",
"@limit",
"# Second case: Count is over the limit and the time has not run out yet",
"return",
"(",
"limit_hash",
"[",
":set_time",
"]",
"+",
"@time_span",
")",
"-",
"rate_limit_time",
"if",
"@time_span",
"&&",
"rate_limit_time",
"<",
"(",
"limit_hash",
"[",
":set_time",
"]",
"+",
"@time_span",
")",
"# Third case: Count is over the limit but the time has run out",
"# Don't return anything here because there may still be delay-based limiting",
"limit_hash",
"[",
":set_time",
"]",
"=",
"rate_limit_time",
"limit_hash",
"[",
":count",
"]",
"=",
"0",
"end",
"if",
"@delay",
"&&",
"rate_limit_time",
"<",
"(",
"limit_hash",
"[",
":last_time",
"]",
"+",
"@delay",
")",
"# Fourth case: we're being delayed",
"(",
"limit_hash",
"[",
":last_time",
"]",
"+",
"@delay",
")",
"-",
"rate_limit_time",
"else",
"# Fifth case: no rate limiting at all! Increment the count, set the last_time, and return false",
"limit_hash",
"[",
":last_time",
"]",
"=",
"rate_limit_time",
"limit_hash",
"[",
":count",
"]",
"+=",
"increment",
"false",
"end",
"end"
] | Performs a rate limiting request
@param thing [#resolve_id, Integer, Symbol] The particular thing that should be rate-limited (usually a user/channel, but you can also choose arbitrary integers or symbols)
@param rate_limit_time [Time] The time to base the rate limiting on, only useful for testing.
@param increment [Integer] How much to increment the rate-limit counter. Default is 1.
@return [Integer, false] the waiting time until the next request, in seconds, or false if the request succeeded | [
"Performs",
"a",
"rate",
"limiting",
"request"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/commands/rate_limiter.rb#L42-L79 | train |
meew0/discordrb | lib/discordrb/gateway.rb | Discordrb.Gateway.run_async | def run_async
@ws_thread = Thread.new do
Thread.current[:discordrb_name] = 'websocket'
connect_loop
LOGGER.warn('The WS loop exited! Not sure if this is a good thing')
end
LOGGER.debug('WS thread created! Now waiting for confirmation that everything worked')
sleep(0.5) until @ws_success
LOGGER.debug('Confirmation received! Exiting run.')
end | ruby | def run_async
@ws_thread = Thread.new do
Thread.current[:discordrb_name] = 'websocket'
connect_loop
LOGGER.warn('The WS loop exited! Not sure if this is a good thing')
end
LOGGER.debug('WS thread created! Now waiting for confirmation that everything worked')
sleep(0.5) until @ws_success
LOGGER.debug('Confirmation received! Exiting run.')
end | [
"def",
"run_async",
"@ws_thread",
"=",
"Thread",
".",
"new",
"do",
"Thread",
".",
"current",
"[",
":discordrb_name",
"]",
"=",
"'websocket'",
"connect_loop",
"LOGGER",
".",
"warn",
"(",
"'The WS loop exited! Not sure if this is a good thing'",
")",
"end",
"LOGGER",
".",
"debug",
"(",
"'WS thread created! Now waiting for confirmation that everything worked'",
")",
"sleep",
"(",
"0.5",
")",
"until",
"@ws_success",
"LOGGER",
".",
"debug",
"(",
"'Confirmation received! Exiting run.'",
")",
"end"
] | Connect to the gateway server in a separate thread | [
"Connect",
"to",
"the",
"gateway",
"server",
"in",
"a",
"separate",
"thread"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/gateway.rb#L163-L173 | train |
meew0/discordrb | lib/discordrb/gateway.rb | Discordrb.Gateway.send_packet | def send_packet(opcode, packet)
data = {
op: opcode,
d: packet
}
send(data.to_json)
end | ruby | def send_packet(opcode, packet)
data = {
op: opcode,
d: packet
}
send(data.to_json)
end | [
"def",
"send_packet",
"(",
"opcode",
",",
"packet",
")",
"data",
"=",
"{",
"op",
":",
"opcode",
",",
"d",
":",
"packet",
"}",
"send",
"(",
"data",
".",
"to_json",
")",
"end"
] | Sends a custom packet over the connection. This can be useful to implement future yet unimplemented functionality
or for testing. You probably shouldn't use this unless you know what you're doing.
@param opcode [Integer] The opcode the packet should be sent as. Can be one of {Opcodes} or a custom value if
necessary.
@param packet [Object] Some arbitrary JSON-serialisable data that should be sent as the `d` field. | [
"Sends",
"a",
"custom",
"packet",
"over",
"the",
"connection",
".",
"This",
"can",
"be",
"useful",
"to",
"implement",
"future",
"yet",
"unimplemented",
"functionality",
"or",
"for",
"testing",
".",
"You",
"probably",
"shouldn",
"t",
"use",
"this",
"unless",
"you",
"know",
"what",
"you",
"re",
"doing",
"."
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/gateway.rb#L406-L413 | train |
meew0/discordrb | lib/discordrb/gateway.rb | Discordrb.Gateway.obtain_socket | def obtain_socket(uri)
socket = TCPSocket.new(uri.host, uri.port || socket_port(uri))
if secure_uri?(uri)
ctx = OpenSSL::SSL::SSLContext.new
if ENV['DISCORDRB_SSL_VERIFY_NONE']
ctx.ssl_version = 'SSLv23'
ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE # use VERIFY_PEER for verification
cert_store = OpenSSL::X509::Store.new
cert_store.set_default_paths
ctx.cert_store = cert_store
else
ctx.set_params ssl_version: :TLSv1_2
end
socket = OpenSSL::SSL::SSLSocket.new(socket, ctx)
socket.connect
end
socket
end | ruby | def obtain_socket(uri)
socket = TCPSocket.new(uri.host, uri.port || socket_port(uri))
if secure_uri?(uri)
ctx = OpenSSL::SSL::SSLContext.new
if ENV['DISCORDRB_SSL_VERIFY_NONE']
ctx.ssl_version = 'SSLv23'
ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE # use VERIFY_PEER for verification
cert_store = OpenSSL::X509::Store.new
cert_store.set_default_paths
ctx.cert_store = cert_store
else
ctx.set_params ssl_version: :TLSv1_2
end
socket = OpenSSL::SSL::SSLSocket.new(socket, ctx)
socket.connect
end
socket
end | [
"def",
"obtain_socket",
"(",
"uri",
")",
"socket",
"=",
"TCPSocket",
".",
"new",
"(",
"uri",
".",
"host",
",",
"uri",
".",
"port",
"||",
"socket_port",
"(",
"uri",
")",
")",
"if",
"secure_uri?",
"(",
"uri",
")",
"ctx",
"=",
"OpenSSL",
"::",
"SSL",
"::",
"SSLContext",
".",
"new",
"if",
"ENV",
"[",
"'DISCORDRB_SSL_VERIFY_NONE'",
"]",
"ctx",
".",
"ssl_version",
"=",
"'SSLv23'",
"ctx",
".",
"verify_mode",
"=",
"OpenSSL",
"::",
"SSL",
"::",
"VERIFY_NONE",
"# use VERIFY_PEER for verification",
"cert_store",
"=",
"OpenSSL",
"::",
"X509",
"::",
"Store",
".",
"new",
"cert_store",
".",
"set_default_paths",
"ctx",
".",
"cert_store",
"=",
"cert_store",
"else",
"ctx",
".",
"set_params",
"ssl_version",
":",
":TLSv1_2",
"end",
"socket",
"=",
"OpenSSL",
"::",
"SSL",
"::",
"SSLSocket",
".",
"new",
"(",
"socket",
",",
"ctx",
")",
"socket",
".",
"connect",
"end",
"socket",
"end"
] | Create and connect a socket using a URI | [
"Create",
"and",
"connect",
"a",
"socket",
"using",
"a",
"URI"
] | 764298a1ff0be69a1853b510d736f21c2b91a2fe | https://github.com/meew0/discordrb/blob/764298a1ff0be69a1853b510d736f21c2b91a2fe/lib/discordrb/gateway.rb#L489-L511 | train |
interagent/committee | lib/committee/schema_validator/hyper_schema/response_validator.rb | Committee.SchemaValidator::HyperSchema::ResponseValidator.target_schema | def target_schema(link)
if link.target_schema
link.target_schema
elsif legacy_hyper_schema_rel?(link)
link.parent
end
end | ruby | def target_schema(link)
if link.target_schema
link.target_schema
elsif legacy_hyper_schema_rel?(link)
link.parent
end
end | [
"def",
"target_schema",
"(",
"link",
")",
"if",
"link",
".",
"target_schema",
"link",
".",
"target_schema",
"elsif",
"legacy_hyper_schema_rel?",
"(",
"link",
")",
"link",
".",
"parent",
"end",
"end"
] | Gets the target schema of a link. This is normally just the standard
response schema, but we allow some legacy behavior for hyper-schema links
tagged with rel=instances to instead use the schema of their parent
resource. | [
"Gets",
"the",
"target",
"schema",
"of",
"a",
"link",
".",
"This",
"is",
"normally",
"just",
"the",
"standard",
"response",
"schema",
"but",
"we",
"allow",
"some",
"legacy",
"behavior",
"for",
"hyper",
"-",
"schema",
"links",
"tagged",
"with",
"rel",
"=",
"instances",
"to",
"instead",
"use",
"the",
"schema",
"of",
"their",
"parent",
"resource",
"."
] | 810fadcea1bc1c529627d47325c1008b5c33b0a4 | https://github.com/interagent/committee/blob/810fadcea1bc1c529627d47325c1008b5c33b0a4/lib/committee/schema_validator/hyper_schema/response_validator.rb#L69-L75 | train |
ffaker/ffaker | lib/ffaker/name_mx.rb | FFaker.NameMX.name | def name(gender = :any)
case gender
when :any then rand(0..1) == 0 ? name(:male) : name(:female)
when :male then fetch_sample(MALE_FIRST_NAMES)
when :female then fetch_sample(FEMALE_FIRST_NAMES)
else raise ArgumentError, 'Invalid gender, must be one of :any, :male, :female'
end
end | ruby | def name(gender = :any)
case gender
when :any then rand(0..1) == 0 ? name(:male) : name(:female)
when :male then fetch_sample(MALE_FIRST_NAMES)
when :female then fetch_sample(FEMALE_FIRST_NAMES)
else raise ArgumentError, 'Invalid gender, must be one of :any, :male, :female'
end
end | [
"def",
"name",
"(",
"gender",
"=",
":any",
")",
"case",
"gender",
"when",
":any",
"then",
"rand",
"(",
"0",
"..",
"1",
")",
"==",
"0",
"?",
"name",
"(",
":male",
")",
":",
"name",
"(",
":female",
")",
"when",
":male",
"then",
"fetch_sample",
"(",
"MALE_FIRST_NAMES",
")",
"when",
":female",
"then",
"fetch_sample",
"(",
"FEMALE_FIRST_NAMES",
")",
"else",
"raise",
"ArgumentError",
",",
"'Invalid gender, must be one of :any, :male, :female'",
"end",
"end"
] | A single name according to gender parameter | [
"A",
"single",
"name",
"according",
"to",
"gender",
"parameter"
] | 9570ac54874fec66a99b9c86401fb878f1e3e951 | https://github.com/ffaker/ffaker/blob/9570ac54874fec66a99b9c86401fb878f1e3e951/lib/ffaker/name_mx.rb#L71-L78 | train |
ffaker/ffaker | lib/ffaker/phone_number_de.rb | FFaker.PhoneNumberDE.mobile_prefix | def mobile_prefix(leading_zero = true)
mobile_prefix = '1' + rand(5..7).to_s + rand(0..9).to_s
mobile_prefix = '0' + mobile_prefix if leading_zero
mobile_prefix
end | ruby | def mobile_prefix(leading_zero = true)
mobile_prefix = '1' + rand(5..7).to_s + rand(0..9).to_s
mobile_prefix = '0' + mobile_prefix if leading_zero
mobile_prefix
end | [
"def",
"mobile_prefix",
"(",
"leading_zero",
"=",
"true",
")",
"mobile_prefix",
"=",
"'1'",
"+",
"rand",
"(",
"5",
"..",
"7",
")",
".",
"to_s",
"+",
"rand",
"(",
"0",
"..",
"9",
")",
".",
"to_s",
"mobile_prefix",
"=",
"'0'",
"+",
"mobile_prefix",
"if",
"leading_zero",
"mobile_prefix",
"end"
] | Mobile prefixes are in the 015x, 016x, 017x ranges | [
"Mobile",
"prefixes",
"are",
"in",
"the",
"015x",
"016x",
"017x",
"ranges"
] | 9570ac54874fec66a99b9c86401fb878f1e3e951 | https://github.com/ffaker/ffaker/blob/9570ac54874fec66a99b9c86401fb878f1e3e951/lib/ffaker/phone_number_de.rb#L10-L14 | train |
minimagick/minimagick | lib/mini_magick/image.rb | MiniMagick.Image.validate! | def validate!
identify
rescue MiniMagick::Error => error
raise MiniMagick::Invalid, error.message
end | ruby | def validate!
identify
rescue MiniMagick::Error => error
raise MiniMagick::Invalid, error.message
end | [
"def",
"validate!",
"identify",
"rescue",
"MiniMagick",
"::",
"Error",
"=>",
"error",
"raise",
"MiniMagick",
"::",
"Invalid",
",",
"error",
".",
"message",
"end"
] | Runs `identify` on the current image, and raises an error if it doesn't
pass.
@raise [MiniMagick::Invalid] | [
"Runs",
"identify",
"on",
"the",
"current",
"image",
"and",
"raises",
"an",
"error",
"if",
"it",
"doesn",
"t",
"pass",
"."
] | d484786f35e91f107836d3c86aca61d50a35820b | https://github.com/minimagick/minimagick/blob/d484786f35e91f107836d3c86aca61d50a35820b/lib/mini_magick/image.rb#L205-L209 | train |
minimagick/minimagick | lib/mini_magick/image.rb | MiniMagick.Image.format | def format(format, page = 0, read_opts={})
if @tempfile
new_tempfile = MiniMagick::Utilities.tempfile(".#{format}")
new_path = new_tempfile.path
else
new_path = Pathname(path).sub_ext(".#{format}").to_s
end
input_path = path.dup
input_path << "[#{page}]" if page && !layer?
MiniMagick::Tool::Convert.new do |convert|
read_opts.each do |opt, val|
convert.send(opt.to_s, val)
end
convert << input_path
yield convert if block_given?
convert << new_path
end
if @tempfile
destroy!
@tempfile = new_tempfile
else
File.delete(path) unless path == new_path || layer?
end
path.replace new_path
@info.clear
self
end | ruby | def format(format, page = 0, read_opts={})
if @tempfile
new_tempfile = MiniMagick::Utilities.tempfile(".#{format}")
new_path = new_tempfile.path
else
new_path = Pathname(path).sub_ext(".#{format}").to_s
end
input_path = path.dup
input_path << "[#{page}]" if page && !layer?
MiniMagick::Tool::Convert.new do |convert|
read_opts.each do |opt, val|
convert.send(opt.to_s, val)
end
convert << input_path
yield convert if block_given?
convert << new_path
end
if @tempfile
destroy!
@tempfile = new_tempfile
else
File.delete(path) unless path == new_path || layer?
end
path.replace new_path
@info.clear
self
end | [
"def",
"format",
"(",
"format",
",",
"page",
"=",
"0",
",",
"read_opts",
"=",
"{",
"}",
")",
"if",
"@tempfile",
"new_tempfile",
"=",
"MiniMagick",
"::",
"Utilities",
".",
"tempfile",
"(",
"\".#{format}\"",
")",
"new_path",
"=",
"new_tempfile",
".",
"path",
"else",
"new_path",
"=",
"Pathname",
"(",
"path",
")",
".",
"sub_ext",
"(",
"\".#{format}\"",
")",
".",
"to_s",
"end",
"input_path",
"=",
"path",
".",
"dup",
"input_path",
"<<",
"\"[#{page}]\"",
"if",
"page",
"&&",
"!",
"layer?",
"MiniMagick",
"::",
"Tool",
"::",
"Convert",
".",
"new",
"do",
"|",
"convert",
"|",
"read_opts",
".",
"each",
"do",
"|",
"opt",
",",
"val",
"|",
"convert",
".",
"send",
"(",
"opt",
".",
"to_s",
",",
"val",
")",
"end",
"convert",
"<<",
"input_path",
"yield",
"convert",
"if",
"block_given?",
"convert",
"<<",
"new_path",
"end",
"if",
"@tempfile",
"destroy!",
"@tempfile",
"=",
"new_tempfile",
"else",
"File",
".",
"delete",
"(",
"path",
")",
"unless",
"path",
"==",
"new_path",
"||",
"layer?",
"end",
"path",
".",
"replace",
"new_path",
"@info",
".",
"clear",
"self",
"end"
] | This is used to change the format of the image. That is, from "tiff to
jpg" or something like that. Once you run it, the instance is pointing to
a new file with a new extension!
*DANGER*: This renames the file that the instance is pointing to. So, if
you manually opened the file with Image.new(file_path)... Then that file
is DELETED! If you used Image.open(file) then you are OK. The original
file will still be there. But, any changes to it might not be...
Formatting an animation into a non-animated type will result in
ImageMagick creating multiple pages (starting with 0). You can choose
which page you want to manipulate. We default to the first page.
If you would like to convert between animated formats, pass nil as your
page and ImageMagick will copy all of the pages.
@param format [String] The target format... Like 'jpg', 'gif', 'tiff' etc.
@param page [Integer] If this is an animated gif, say which 'page' you
want with an integer. Default 0 will convert only the first page; 'nil'
will convert all pages.
@param read_opts [Hash] Any read options to be passed to ImageMagick
for example: image.format('jpg', page, {density: '300'})
@yield [MiniMagick::Tool::Convert] It optionally yields the command,
if you want to add something.
@return [self] | [
"This",
"is",
"used",
"to",
"change",
"the",
"format",
"of",
"the",
"image",
".",
"That",
"is",
"from",
"tiff",
"to",
"jpg",
"or",
"something",
"like",
"that",
".",
"Once",
"you",
"run",
"it",
"the",
"instance",
"is",
"pointing",
"to",
"a",
"new",
"file",
"with",
"a",
"new",
"extension!"
] | d484786f35e91f107836d3c86aca61d50a35820b | https://github.com/minimagick/minimagick/blob/d484786f35e91f107836d3c86aca61d50a35820b/lib/mini_magick/image.rb#L395-L426 | train |
minimagick/minimagick | lib/mini_magick/image.rb | MiniMagick.Image.identify | def identify
MiniMagick::Tool::Identify.new do |builder|
yield builder if block_given?
builder << path
end
end | ruby | def identify
MiniMagick::Tool::Identify.new do |builder|
yield builder if block_given?
builder << path
end
end | [
"def",
"identify",
"MiniMagick",
"::",
"Tool",
"::",
"Identify",
".",
"new",
"do",
"|",
"builder",
"|",
"yield",
"builder",
"if",
"block_given?",
"builder",
"<<",
"path",
"end",
"end"
] | Runs `identify` on itself. Accepts an optional block for adding more
options to `identify`.
@example
image = MiniMagick::Image.open("image.jpg")
image.identify do |b|
b.verbose
end # runs `identify -verbose image.jpg`
@return [String] Output from `identify`
@yield [MiniMagick::Tool::Identify] | [
"Runs",
"identify",
"on",
"itself",
".",
"Accepts",
"an",
"optional",
"block",
"for",
"adding",
"more",
"options",
"to",
"identify",
"."
] | d484786f35e91f107836d3c86aca61d50a35820b | https://github.com/minimagick/minimagick/blob/d484786f35e91f107836d3c86aca61d50a35820b/lib/mini_magick/image.rb#L547-L552 | train |
excon/excon | lib/excon/utils.rb | Excon.Utils.redact | def redact(datum)
datum = datum.dup
if datum.has_key?(:headers) && datum[:headers].has_key?('Authorization')
datum[:headers] = datum[:headers].dup
datum[:headers]['Authorization'] = REDACTED
end
if datum.has_key?(:password)
datum[:password] = REDACTED
end
datum
end | ruby | def redact(datum)
datum = datum.dup
if datum.has_key?(:headers) && datum[:headers].has_key?('Authorization')
datum[:headers] = datum[:headers].dup
datum[:headers]['Authorization'] = REDACTED
end
if datum.has_key?(:password)
datum[:password] = REDACTED
end
datum
end | [
"def",
"redact",
"(",
"datum",
")",
"datum",
"=",
"datum",
".",
"dup",
"if",
"datum",
".",
"has_key?",
"(",
":headers",
")",
"&&",
"datum",
"[",
":headers",
"]",
".",
"has_key?",
"(",
"'Authorization'",
")",
"datum",
"[",
":headers",
"]",
"=",
"datum",
"[",
":headers",
"]",
".",
"dup",
"datum",
"[",
":headers",
"]",
"[",
"'Authorization'",
"]",
"=",
"REDACTED",
"end",
"if",
"datum",
".",
"has_key?",
"(",
":password",
")",
"datum",
"[",
":password",
"]",
"=",
"REDACTED",
"end",
"datum",
"end"
] | Redact sensitive info from provided data | [
"Redact",
"sensitive",
"info",
"from",
"provided",
"data"
] | d4975a8a5b49d5901a769b289fb5054a6d064f6d | https://github.com/excon/excon/blob/d4975a8a5b49d5901a769b289fb5054a6d064f6d/lib/excon/utils.rb#L31-L41 | train |
excon/excon | lib/excon/utils.rb | Excon.Utils.split_header_value | def split_header_value(str)
return [] if str.nil?
str = str.dup.strip
binary_encode(str)
str.scan(%r'\G((?:"(?:\\.|[^"])+?"|[^",]+)+)
(?:,\s*|\Z)'xn).flatten
end | ruby | def split_header_value(str)
return [] if str.nil?
str = str.dup.strip
binary_encode(str)
str.scan(%r'\G((?:"(?:\\.|[^"])+?"|[^",]+)+)
(?:,\s*|\Z)'xn).flatten
end | [
"def",
"split_header_value",
"(",
"str",
")",
"return",
"[",
"]",
"if",
"str",
".",
"nil?",
"str",
"=",
"str",
".",
"dup",
".",
"strip",
"binary_encode",
"(",
"str",
")",
"str",
".",
"scan",
"(",
"%r'",
"\\G",
"\\\\",
"\\s",
"\\Z",
"'xn",
")",
".",
"flatten",
"end"
] | Splits a header value +str+ according to HTTP specification. | [
"Splits",
"a",
"header",
"value",
"+",
"str",
"+",
"according",
"to",
"HTTP",
"specification",
"."
] | d4975a8a5b49d5901a769b289fb5054a6d064f6d | https://github.com/excon/excon/blob/d4975a8a5b49d5901a769b289fb5054a6d064f6d/lib/excon/utils.rb#L78-L84 | train |
excon/excon | lib/excon/utils.rb | Excon.Utils.escape_uri | def escape_uri(str)
str = str.dup
binary_encode(str)
str.gsub(UNESCAPED) { "%%%02X" % $1[0].ord }
end | ruby | def escape_uri(str)
str = str.dup
binary_encode(str)
str.gsub(UNESCAPED) { "%%%02X" % $1[0].ord }
end | [
"def",
"escape_uri",
"(",
"str",
")",
"str",
"=",
"str",
".",
"dup",
"binary_encode",
"(",
"str",
")",
"str",
".",
"gsub",
"(",
"UNESCAPED",
")",
"{",
"\"%%%02X\"",
"%",
"$1",
"[",
"0",
"]",
".",
"ord",
"}",
"end"
] | Escapes HTTP reserved and unwise characters in +str+ | [
"Escapes",
"HTTP",
"reserved",
"and",
"unwise",
"characters",
"in",
"+",
"str",
"+"
] | d4975a8a5b49d5901a769b289fb5054a6d064f6d | https://github.com/excon/excon/blob/d4975a8a5b49d5901a769b289fb5054a6d064f6d/lib/excon/utils.rb#L87-L91 | train |
excon/excon | lib/excon/utils.rb | Excon.Utils.unescape_uri | def unescape_uri(str)
str = str.dup
binary_encode(str)
str.gsub(ESCAPED) { $1.hex.chr }
end | ruby | def unescape_uri(str)
str = str.dup
binary_encode(str)
str.gsub(ESCAPED) { $1.hex.chr }
end | [
"def",
"unescape_uri",
"(",
"str",
")",
"str",
"=",
"str",
".",
"dup",
"binary_encode",
"(",
"str",
")",
"str",
".",
"gsub",
"(",
"ESCAPED",
")",
"{",
"$1",
".",
"hex",
".",
"chr",
"}",
"end"
] | Unescapes HTTP reserved and unwise characters in +str+ | [
"Unescapes",
"HTTP",
"reserved",
"and",
"unwise",
"characters",
"in",
"+",
"str",
"+"
] | d4975a8a5b49d5901a769b289fb5054a6d064f6d | https://github.com/excon/excon/blob/d4975a8a5b49d5901a769b289fb5054a6d064f6d/lib/excon/utils.rb#L94-L98 | train |
excon/excon | lib/excon/utils.rb | Excon.Utils.unescape_form | def unescape_form(str)
str = str.dup
binary_encode(str)
str.gsub!(/\+/, ' ')
str.gsub(ESCAPED) { $1.hex.chr }
end | ruby | def unescape_form(str)
str = str.dup
binary_encode(str)
str.gsub!(/\+/, ' ')
str.gsub(ESCAPED) { $1.hex.chr }
end | [
"def",
"unescape_form",
"(",
"str",
")",
"str",
"=",
"str",
".",
"dup",
"binary_encode",
"(",
"str",
")",
"str",
".",
"gsub!",
"(",
"/",
"\\+",
"/",
",",
"' '",
")",
"str",
".",
"gsub",
"(",
"ESCAPED",
")",
"{",
"$1",
".",
"hex",
".",
"chr",
"}",
"end"
] | Unescape form encoded values in +str+ | [
"Unescape",
"form",
"encoded",
"values",
"in",
"+",
"str",
"+"
] | d4975a8a5b49d5901a769b289fb5054a6d064f6d | https://github.com/excon/excon/blob/d4975a8a5b49d5901a769b289fb5054a6d064f6d/lib/excon/utils.rb#L101-L106 | train |
excon/excon | lib/excon/connection.rb | Excon.Connection.request | def request(params={}, &block)
# @data has defaults, merge in new params to override
datum = @data.merge(params)
datum[:headers] = @data[:headers].merge(datum[:headers] || {})
validate_params(:request, params, datum[:middlewares])
# If the user passed in new middleware, we want to validate that the original connection parameters
# are still valid with the provided middleware.
if params[:middlewares]
validate_params(:connection, @data, datum[:middlewares])
end
if datum[:user] || datum[:password]
user, pass = Utils.unescape_uri(datum[:user].to_s), Utils.unescape_uri(datum[:password].to_s)
datum[:headers]['Authorization'] ||= 'Basic ' + ["#{user}:#{pass}"].pack('m').delete(Excon::CR_NL)
end
if datum[:scheme] == UNIX
datum[:headers]['Host'] ||= ''
else
datum[:headers]['Host'] ||= datum[:host] + port_string(datum)
end
# if path is empty or doesn't start with '/', insert one
unless datum[:path][0, 1] == '/'
datum[:path] = datum[:path].dup.insert(0, '/')
end
if block_given?
Excon.display_warning('Excon requests with a block are deprecated, pass :response_block instead.')
datum[:response_block] = Proc.new
end
datum[:connection] = self
datum[:stack] = datum[:middlewares].map do |middleware|
lambda {|stack| middleware.new(stack)}
end.reverse.inject(self) do |middlewares, middleware|
middleware.call(middlewares)
end
datum = datum[:stack].request_call(datum)
unless datum[:pipeline]
datum = response(datum)
if datum[:persistent]
if key = datum[:response][:headers].keys.detect {|k| k.casecmp('Connection') == 0 }
if datum[:response][:headers][key].casecmp('close') == 0
reset
end
end
else
reset
end
Excon::Response.new(datum[:response])
else
datum
end
rescue => error
reset
# If we didn't get far enough to initialize datum and the middleware stack, just raise
raise error if !datum
datum[:error] = error
if datum[:stack]
datum[:stack].error_call(datum)
else
raise error
end
end | ruby | def request(params={}, &block)
# @data has defaults, merge in new params to override
datum = @data.merge(params)
datum[:headers] = @data[:headers].merge(datum[:headers] || {})
validate_params(:request, params, datum[:middlewares])
# If the user passed in new middleware, we want to validate that the original connection parameters
# are still valid with the provided middleware.
if params[:middlewares]
validate_params(:connection, @data, datum[:middlewares])
end
if datum[:user] || datum[:password]
user, pass = Utils.unescape_uri(datum[:user].to_s), Utils.unescape_uri(datum[:password].to_s)
datum[:headers]['Authorization'] ||= 'Basic ' + ["#{user}:#{pass}"].pack('m').delete(Excon::CR_NL)
end
if datum[:scheme] == UNIX
datum[:headers]['Host'] ||= ''
else
datum[:headers]['Host'] ||= datum[:host] + port_string(datum)
end
# if path is empty or doesn't start with '/', insert one
unless datum[:path][0, 1] == '/'
datum[:path] = datum[:path].dup.insert(0, '/')
end
if block_given?
Excon.display_warning('Excon requests with a block are deprecated, pass :response_block instead.')
datum[:response_block] = Proc.new
end
datum[:connection] = self
datum[:stack] = datum[:middlewares].map do |middleware|
lambda {|stack| middleware.new(stack)}
end.reverse.inject(self) do |middlewares, middleware|
middleware.call(middlewares)
end
datum = datum[:stack].request_call(datum)
unless datum[:pipeline]
datum = response(datum)
if datum[:persistent]
if key = datum[:response][:headers].keys.detect {|k| k.casecmp('Connection') == 0 }
if datum[:response][:headers][key].casecmp('close') == 0
reset
end
end
else
reset
end
Excon::Response.new(datum[:response])
else
datum
end
rescue => error
reset
# If we didn't get far enough to initialize datum and the middleware stack, just raise
raise error if !datum
datum[:error] = error
if datum[:stack]
datum[:stack].error_call(datum)
else
raise error
end
end | [
"def",
"request",
"(",
"params",
"=",
"{",
"}",
",",
"&",
"block",
")",
"# @data has defaults, merge in new params to override",
"datum",
"=",
"@data",
".",
"merge",
"(",
"params",
")",
"datum",
"[",
":headers",
"]",
"=",
"@data",
"[",
":headers",
"]",
".",
"merge",
"(",
"datum",
"[",
":headers",
"]",
"||",
"{",
"}",
")",
"validate_params",
"(",
":request",
",",
"params",
",",
"datum",
"[",
":middlewares",
"]",
")",
"# If the user passed in new middleware, we want to validate that the original connection parameters",
"# are still valid with the provided middleware.",
"if",
"params",
"[",
":middlewares",
"]",
"validate_params",
"(",
":connection",
",",
"@data",
",",
"datum",
"[",
":middlewares",
"]",
")",
"end",
"if",
"datum",
"[",
":user",
"]",
"||",
"datum",
"[",
":password",
"]",
"user",
",",
"pass",
"=",
"Utils",
".",
"unescape_uri",
"(",
"datum",
"[",
":user",
"]",
".",
"to_s",
")",
",",
"Utils",
".",
"unescape_uri",
"(",
"datum",
"[",
":password",
"]",
".",
"to_s",
")",
"datum",
"[",
":headers",
"]",
"[",
"'Authorization'",
"]",
"||=",
"'Basic '",
"+",
"[",
"\"#{user}:#{pass}\"",
"]",
".",
"pack",
"(",
"'m'",
")",
".",
"delete",
"(",
"Excon",
"::",
"CR_NL",
")",
"end",
"if",
"datum",
"[",
":scheme",
"]",
"==",
"UNIX",
"datum",
"[",
":headers",
"]",
"[",
"'Host'",
"]",
"||=",
"''",
"else",
"datum",
"[",
":headers",
"]",
"[",
"'Host'",
"]",
"||=",
"datum",
"[",
":host",
"]",
"+",
"port_string",
"(",
"datum",
")",
"end",
"# if path is empty or doesn't start with '/', insert one",
"unless",
"datum",
"[",
":path",
"]",
"[",
"0",
",",
"1",
"]",
"==",
"'/'",
"datum",
"[",
":path",
"]",
"=",
"datum",
"[",
":path",
"]",
".",
"dup",
".",
"insert",
"(",
"0",
",",
"'/'",
")",
"end",
"if",
"block_given?",
"Excon",
".",
"display_warning",
"(",
"'Excon requests with a block are deprecated, pass :response_block instead.'",
")",
"datum",
"[",
":response_block",
"]",
"=",
"Proc",
".",
"new",
"end",
"datum",
"[",
":connection",
"]",
"=",
"self",
"datum",
"[",
":stack",
"]",
"=",
"datum",
"[",
":middlewares",
"]",
".",
"map",
"do",
"|",
"middleware",
"|",
"lambda",
"{",
"|",
"stack",
"|",
"middleware",
".",
"new",
"(",
"stack",
")",
"}",
"end",
".",
"reverse",
".",
"inject",
"(",
"self",
")",
"do",
"|",
"middlewares",
",",
"middleware",
"|",
"middleware",
".",
"call",
"(",
"middlewares",
")",
"end",
"datum",
"=",
"datum",
"[",
":stack",
"]",
".",
"request_call",
"(",
"datum",
")",
"unless",
"datum",
"[",
":pipeline",
"]",
"datum",
"=",
"response",
"(",
"datum",
")",
"if",
"datum",
"[",
":persistent",
"]",
"if",
"key",
"=",
"datum",
"[",
":response",
"]",
"[",
":headers",
"]",
".",
"keys",
".",
"detect",
"{",
"|",
"k",
"|",
"k",
".",
"casecmp",
"(",
"'Connection'",
")",
"==",
"0",
"}",
"if",
"datum",
"[",
":response",
"]",
"[",
":headers",
"]",
"[",
"key",
"]",
".",
"casecmp",
"(",
"'close'",
")",
"==",
"0",
"reset",
"end",
"end",
"else",
"reset",
"end",
"Excon",
"::",
"Response",
".",
"new",
"(",
"datum",
"[",
":response",
"]",
")",
"else",
"datum",
"end",
"rescue",
"=>",
"error",
"reset",
"# If we didn't get far enough to initialize datum and the middleware stack, just raise",
"raise",
"error",
"if",
"!",
"datum",
"datum",
"[",
":error",
"]",
"=",
"error",
"if",
"datum",
"[",
":stack",
"]",
"datum",
"[",
":stack",
"]",
".",
"error_call",
"(",
"datum",
")",
"else",
"raise",
"error",
"end",
"end"
] | Sends the supplied request to the destination host.
@yield [chunk] @see Response#self.parse
@param [Hash<Symbol, >] params One or more optional params, override defaults set in Connection.new
@option params [String] :body text to be sent over a socket
@option params [Hash<Symbol, String>] :headers The default headers to supply in a request
@option params [String] :path appears after 'scheme://host:port/'
@option params [Hash] :query appended to the 'scheme://host:port/path/' in the form of '?key=value' | [
"Sends",
"the",
"supplied",
"request",
"to",
"the",
"destination",
"host",
"."
] | d4975a8a5b49d5901a769b289fb5054a6d064f6d | https://github.com/excon/excon/blob/d4975a8a5b49d5901a769b289fb5054a6d064f6d/lib/excon/connection.rb#L230-L301 | train |
excon/excon | lib/excon/connection.rb | Excon.Connection.requests | def requests(pipeline_params)
pipeline_params.each {|params| params.merge!(:pipeline => true, :persistent => true) }
pipeline_params.last.merge!(:persistent => @data[:persistent])
responses = pipeline_params.map do |params|
request(params)
end.map do |datum|
Excon::Response.new(response(datum)[:response])
end
if @data[:persistent]
if key = responses.last[:headers].keys.detect {|k| k.casecmp('Connection') == 0 }
if responses.last[:headers][key].casecmp('close') == 0
reset
end
end
else
reset
end
responses
end | ruby | def requests(pipeline_params)
pipeline_params.each {|params| params.merge!(:pipeline => true, :persistent => true) }
pipeline_params.last.merge!(:persistent => @data[:persistent])
responses = pipeline_params.map do |params|
request(params)
end.map do |datum|
Excon::Response.new(response(datum)[:response])
end
if @data[:persistent]
if key = responses.last[:headers].keys.detect {|k| k.casecmp('Connection') == 0 }
if responses.last[:headers][key].casecmp('close') == 0
reset
end
end
else
reset
end
responses
end | [
"def",
"requests",
"(",
"pipeline_params",
")",
"pipeline_params",
".",
"each",
"{",
"|",
"params",
"|",
"params",
".",
"merge!",
"(",
":pipeline",
"=>",
"true",
",",
":persistent",
"=>",
"true",
")",
"}",
"pipeline_params",
".",
"last",
".",
"merge!",
"(",
":persistent",
"=>",
"@data",
"[",
":persistent",
"]",
")",
"responses",
"=",
"pipeline_params",
".",
"map",
"do",
"|",
"params",
"|",
"request",
"(",
"params",
")",
"end",
".",
"map",
"do",
"|",
"datum",
"|",
"Excon",
"::",
"Response",
".",
"new",
"(",
"response",
"(",
"datum",
")",
"[",
":response",
"]",
")",
"end",
"if",
"@data",
"[",
":persistent",
"]",
"if",
"key",
"=",
"responses",
".",
"last",
"[",
":headers",
"]",
".",
"keys",
".",
"detect",
"{",
"|",
"k",
"|",
"k",
".",
"casecmp",
"(",
"'Connection'",
")",
"==",
"0",
"}",
"if",
"responses",
".",
"last",
"[",
":headers",
"]",
"[",
"key",
"]",
".",
"casecmp",
"(",
"'close'",
")",
"==",
"0",
"reset",
"end",
"end",
"else",
"reset",
"end",
"responses",
"end"
] | Sends the supplied requests to the destination host using pipelining.
@pipeline_params [Array<Hash>] pipeline_params An array of one or more optional params, override defaults set in Connection.new, see #request for details | [
"Sends",
"the",
"supplied",
"requests",
"to",
"the",
"destination",
"host",
"using",
"pipelining",
"."
] | d4975a8a5b49d5901a769b289fb5054a6d064f6d | https://github.com/excon/excon/blob/d4975a8a5b49d5901a769b289fb5054a6d064f6d/lib/excon/connection.rb#L305-L326 | train |
excon/excon | lib/excon/connection.rb | Excon.Connection.batch_requests | def batch_requests(pipeline_params, limit = nil)
limit ||= Process.respond_to?(:getrlimit) ? Process.getrlimit(:NOFILE).first : 256
responses = []
pipeline_params.each_slice(limit) do |params|
responses.concat(requests(params))
end
responses
end | ruby | def batch_requests(pipeline_params, limit = nil)
limit ||= Process.respond_to?(:getrlimit) ? Process.getrlimit(:NOFILE).first : 256
responses = []
pipeline_params.each_slice(limit) do |params|
responses.concat(requests(params))
end
responses
end | [
"def",
"batch_requests",
"(",
"pipeline_params",
",",
"limit",
"=",
"nil",
")",
"limit",
"||=",
"Process",
".",
"respond_to?",
"(",
":getrlimit",
")",
"?",
"Process",
".",
"getrlimit",
"(",
":NOFILE",
")",
".",
"first",
":",
"256",
"responses",
"=",
"[",
"]",
"pipeline_params",
".",
"each_slice",
"(",
"limit",
")",
"do",
"|",
"params",
"|",
"responses",
".",
"concat",
"(",
"requests",
"(",
"params",
")",
")",
"end",
"responses",
"end"
] | Sends the supplied requests to the destination host using pipelining in
batches of @limit [Numeric] requests. This is your soft file descriptor
limit by default, typically 256.
@pipeline_params [Array<Hash>] pipeline_params An array of one or more optional params, override defaults set in Connection.new, see #request for details | [
"Sends",
"the",
"supplied",
"requests",
"to",
"the",
"destination",
"host",
"using",
"pipelining",
"in",
"batches",
"of"
] | d4975a8a5b49d5901a769b289fb5054a6d064f6d | https://github.com/excon/excon/blob/d4975a8a5b49d5901a769b289fb5054a6d064f6d/lib/excon/connection.rb#L332-L341 | train |
cucumber/aruba | lib/aruba/console.rb | Aruba.Console.start | def start
# Start IRB with current context:
# http://stackoverflow.com/questions/4189818/how-to-run-irb-start-in-context-of-current-class
ARGV.clear
IRB.setup nil
IRB.conf[:IRB_NAME] = 'aruba'
IRB.conf[:PROMPT] = {}
IRB.conf[:PROMPT][:ARUBA] = {
PROMPT_I: '%N:%03n:%i> ',
PROMPT_S: '%N:%03n:%i%l ',
PROMPT_C: '%N:%03n:%i* ',
RETURN: "# => %s\n"
}
IRB.conf[:PROMPT_MODE] = :ARUBA
IRB.conf[:RC] = false
require 'irb/completion'
require 'irb/ext/save-history'
IRB.conf[:READLINE] = true
IRB.conf[:SAVE_HISTORY] = 1000
IRB.conf[:HISTORY_FILE] = Aruba.config.console_history_file
context = Class.new do
include Aruba::Api
include Aruba::Console::Help
def initialize
setup_aruba
end
def inspect
'nil'
end
end
irb = IRB::Irb.new(IRB::WorkSpace.new(context.new))
IRB.conf[:MAIN_CONTEXT] = irb.context
trap("SIGINT") do
irb.signal_handle
end
begin
catch(:IRB_EXIT) do
irb.eval_input
end
ensure
IRB.irb_at_exit
end
end | ruby | def start
# Start IRB with current context:
# http://stackoverflow.com/questions/4189818/how-to-run-irb-start-in-context-of-current-class
ARGV.clear
IRB.setup nil
IRB.conf[:IRB_NAME] = 'aruba'
IRB.conf[:PROMPT] = {}
IRB.conf[:PROMPT][:ARUBA] = {
PROMPT_I: '%N:%03n:%i> ',
PROMPT_S: '%N:%03n:%i%l ',
PROMPT_C: '%N:%03n:%i* ',
RETURN: "# => %s\n"
}
IRB.conf[:PROMPT_MODE] = :ARUBA
IRB.conf[:RC] = false
require 'irb/completion'
require 'irb/ext/save-history'
IRB.conf[:READLINE] = true
IRB.conf[:SAVE_HISTORY] = 1000
IRB.conf[:HISTORY_FILE] = Aruba.config.console_history_file
context = Class.new do
include Aruba::Api
include Aruba::Console::Help
def initialize
setup_aruba
end
def inspect
'nil'
end
end
irb = IRB::Irb.new(IRB::WorkSpace.new(context.new))
IRB.conf[:MAIN_CONTEXT] = irb.context
trap("SIGINT") do
irb.signal_handle
end
begin
catch(:IRB_EXIT) do
irb.eval_input
end
ensure
IRB.irb_at_exit
end
end | [
"def",
"start",
"# Start IRB with current context:",
"# http://stackoverflow.com/questions/4189818/how-to-run-irb-start-in-context-of-current-class",
"ARGV",
".",
"clear",
"IRB",
".",
"setup",
"nil",
"IRB",
".",
"conf",
"[",
":IRB_NAME",
"]",
"=",
"'aruba'",
"IRB",
".",
"conf",
"[",
":PROMPT",
"]",
"=",
"{",
"}",
"IRB",
".",
"conf",
"[",
":PROMPT",
"]",
"[",
":ARUBA",
"]",
"=",
"{",
"PROMPT_I",
":",
"'%N:%03n:%i> '",
",",
"PROMPT_S",
":",
"'%N:%03n:%i%l '",
",",
"PROMPT_C",
":",
"'%N:%03n:%i* '",
",",
"RETURN",
":",
"\"# => %s\\n\"",
"}",
"IRB",
".",
"conf",
"[",
":PROMPT_MODE",
"]",
"=",
":ARUBA",
"IRB",
".",
"conf",
"[",
":RC",
"]",
"=",
"false",
"require",
"'irb/completion'",
"require",
"'irb/ext/save-history'",
"IRB",
".",
"conf",
"[",
":READLINE",
"]",
"=",
"true",
"IRB",
".",
"conf",
"[",
":SAVE_HISTORY",
"]",
"=",
"1000",
"IRB",
".",
"conf",
"[",
":HISTORY_FILE",
"]",
"=",
"Aruba",
".",
"config",
".",
"console_history_file",
"context",
"=",
"Class",
".",
"new",
"do",
"include",
"Aruba",
"::",
"Api",
"include",
"Aruba",
"::",
"Console",
"::",
"Help",
"def",
"initialize",
"setup_aruba",
"end",
"def",
"inspect",
"'nil'",
"end",
"end",
"irb",
"=",
"IRB",
"::",
"Irb",
".",
"new",
"(",
"IRB",
"::",
"WorkSpace",
".",
"new",
"(",
"context",
".",
"new",
")",
")",
"IRB",
".",
"conf",
"[",
":MAIN_CONTEXT",
"]",
"=",
"irb",
".",
"context",
"trap",
"(",
"\"SIGINT\"",
")",
"do",
"irb",
".",
"signal_handle",
"end",
"begin",
"catch",
"(",
":IRB_EXIT",
")",
"do",
"irb",
".",
"eval_input",
"end",
"ensure",
"IRB",
".",
"irb_at_exit",
"end",
"end"
] | Start the aruba console
rubocop:disable Metrics/MethodLength | [
"Start",
"the",
"aruba",
"console"
] | add17615322f575588aef1fccce875396cdf36e9 | https://github.com/cucumber/aruba/blob/add17615322f575588aef1fccce875396cdf36e9/lib/aruba/console.rb#L13-L65 | train |
cucumber/aruba | lib/aruba/basic_configuration.rb | Aruba.BasicConfiguration.make_copy | def make_copy
obj = self.dup
obj.local_options = Marshal.load(Marshal.dump(local_options))
obj.hooks = @hooks
obj
end | ruby | def make_copy
obj = self.dup
obj.local_options = Marshal.load(Marshal.dump(local_options))
obj.hooks = @hooks
obj
end | [
"def",
"make_copy",
"obj",
"=",
"self",
".",
"dup",
"obj",
".",
"local_options",
"=",
"Marshal",
".",
"load",
"(",
"Marshal",
".",
"dump",
"(",
"local_options",
")",
")",
"obj",
".",
"hooks",
"=",
"@hooks",
"obj",
"end"
] | Make deep dup copy of configuration | [
"Make",
"deep",
"dup",
"copy",
"of",
"configuration"
] | add17615322f575588aef1fccce875396cdf36e9 | https://github.com/cucumber/aruba/blob/add17615322f575588aef1fccce875396cdf36e9/lib/aruba/basic_configuration.rb#L116-L122 | train |
cucumber/aruba | lib/aruba/basic_configuration.rb | Aruba.BasicConfiguration.before | def before(name, context = proc {}, *args, &block)
name = format('%s_%s', 'before_', name.to_s).to_sym
if block_given?
@hooks.append(name, block)
self
else
@hooks.execute(name, context, *args)
end
end | ruby | def before(name, context = proc {}, *args, &block)
name = format('%s_%s', 'before_', name.to_s).to_sym
if block_given?
@hooks.append(name, block)
self
else
@hooks.execute(name, context, *args)
end
end | [
"def",
"before",
"(",
"name",
",",
"context",
"=",
"proc",
"{",
"}",
",",
"*",
"args",
",",
"&",
"block",
")",
"name",
"=",
"format",
"(",
"'%s_%s'",
",",
"'before_'",
",",
"name",
".",
"to_s",
")",
".",
"to_sym",
"if",
"block_given?",
"@hooks",
".",
"append",
"(",
"name",
",",
"block",
")",
"self",
"else",
"@hooks",
".",
"execute",
"(",
"name",
",",
"context",
",",
"args",
")",
"end",
"end"
] | Define or run before-hook
@param [Symbol, String] name
The name of the hook
@param [Proc] context
The context a hook should run in. This is a runtime only option.
@param [Array] args
Arguments for the run of hook. This is a runtime only option.
@yield
The code block which should be run. This is a configure time only option | [
"Define",
"or",
"run",
"before",
"-",
"hook"
] | add17615322f575588aef1fccce875396cdf36e9 | https://github.com/cucumber/aruba/blob/add17615322f575588aef1fccce875396cdf36e9/lib/aruba/basic_configuration.rb#L137-L147 | train |
cucumber/aruba | lib/aruba/event_bus.rb | Aruba.EventBus.notify | def notify(event)
fail NoEventError, 'Please pass an event object, not a class' if event.is_a?(Class)
@handlers[event.class.to_s].each { |handler| handler.call(event) }
end | ruby | def notify(event)
fail NoEventError, 'Please pass an event object, not a class' if event.is_a?(Class)
@handlers[event.class.to_s].each { |handler| handler.call(event) }
end | [
"def",
"notify",
"(",
"event",
")",
"fail",
"NoEventError",
",",
"'Please pass an event object, not a class'",
"if",
"event",
".",
"is_a?",
"(",
"Class",
")",
"@handlers",
"[",
"event",
".",
"class",
".",
"to_s",
"]",
".",
"each",
"{",
"|",
"handler",
"|",
"handler",
".",
"call",
"(",
"event",
")",
"}",
"end"
] | Broadcast an event
@param [Object] event
An object of registered event class. This object is passed to the event
handler. | [
"Broadcast",
"an",
"event"
] | add17615322f575588aef1fccce875396cdf36e9 | https://github.com/cucumber/aruba/blob/add17615322f575588aef1fccce875396cdf36e9/lib/aruba/event_bus.rb#L53-L57 | train |
cucumber/aruba | lib/aruba/runtime.rb | Aruba.Runtime.fixtures_directory | def fixtures_directory
@fixtures_directory ||= begin
candidates = config.fixtures_directories.map { |dir| File.join(root_directory, dir) }
directory = candidates.find { |d| Aruba.platform.directory? d }
fail "No existing fixtures directory found in #{candidates.map { |d| format('"%s"', d) }.join(', ')}." unless directory
directory
end
fail %(Fixtures directory "#{@fixtures_directory}" is not a directory) unless Aruba.platform.directory?(@fixtures_directory)
ArubaPath.new(@fixtures_directory)
end | ruby | def fixtures_directory
@fixtures_directory ||= begin
candidates = config.fixtures_directories.map { |dir| File.join(root_directory, dir) }
directory = candidates.find { |d| Aruba.platform.directory? d }
fail "No existing fixtures directory found in #{candidates.map { |d| format('"%s"', d) }.join(', ')}." unless directory
directory
end
fail %(Fixtures directory "#{@fixtures_directory}" is not a directory) unless Aruba.platform.directory?(@fixtures_directory)
ArubaPath.new(@fixtures_directory)
end | [
"def",
"fixtures_directory",
"@fixtures_directory",
"||=",
"begin",
"candidates",
"=",
"config",
".",
"fixtures_directories",
".",
"map",
"{",
"|",
"dir",
"|",
"File",
".",
"join",
"(",
"root_directory",
",",
"dir",
")",
"}",
"directory",
"=",
"candidates",
".",
"find",
"{",
"|",
"d",
"|",
"Aruba",
".",
"platform",
".",
"directory?",
"d",
"}",
"fail",
"\"No existing fixtures directory found in #{candidates.map { |d| format('\"%s\"', d) }.join(', ')}.\"",
"unless",
"directory",
"directory",
"end",
"fail",
"%(Fixtures directory \"#{@fixtures_directory}\" is not a directory)",
"unless",
"Aruba",
".",
"platform",
".",
"directory?",
"(",
"@fixtures_directory",
")",
"ArubaPath",
".",
"new",
"(",
"@fixtures_directory",
")",
"end"
] | The path to the directory which contains fixtures
You might want to overwrite this method to place your data else where.
@return [ArubaPath]
The directory to where your fixtures are stored | [
"The",
"path",
"to",
"the",
"directory",
"which",
"contains",
"fixtures",
"You",
"might",
"want",
"to",
"overwrite",
"this",
"method",
"to",
"place",
"your",
"data",
"else",
"where",
"."
] | add17615322f575588aef1fccce875396cdf36e9 | https://github.com/cucumber/aruba/blob/add17615322f575588aef1fccce875396cdf36e9/lib/aruba/runtime.rb#L79-L91 | train |
cucumber/aruba | lib/aruba/initializer.rb | Aruba.Initializer.call | def call(test_framework)
begin
initializers.find { |i| i.match? test_framework }.start [], {}
rescue ArgumentError => e
$stderr.puts e.message
exit 0
end
Initializers::CommonInitializer.start [], {}
end | ruby | def call(test_framework)
begin
initializers.find { |i| i.match? test_framework }.start [], {}
rescue ArgumentError => e
$stderr.puts e.message
exit 0
end
Initializers::CommonInitializer.start [], {}
end | [
"def",
"call",
"(",
"test_framework",
")",
"begin",
"initializers",
".",
"find",
"{",
"|",
"i",
"|",
"i",
".",
"match?",
"test_framework",
"}",
".",
"start",
"[",
"]",
",",
"{",
"}",
"rescue",
"ArgumentError",
"=>",
"e",
"$stderr",
".",
"puts",
"e",
".",
"message",
"exit",
"0",
"end",
"Initializers",
"::",
"CommonInitializer",
".",
"start",
"[",
"]",
",",
"{",
"}",
"end"
] | Create files etc. | [
"Create",
"files",
"etc",
"."
] | add17615322f575588aef1fccce875396cdf36e9 | https://github.com/cucumber/aruba/blob/add17615322f575588aef1fccce875396cdf36e9/lib/aruba/initializer.rb#L201-L210 | train |
cucumber/aruba | lib/aruba/hooks.rb | Aruba.Hooks.append | def append(label, block)
if store.key?(label.to_sym) && store[label.to_sym].respond_to?(:<<)
store[label.to_sym] << block
else
store[label.to_sym] = []
store[label.to_sym] << block
end
end | ruby | def append(label, block)
if store.key?(label.to_sym) && store[label.to_sym].respond_to?(:<<)
store[label.to_sym] << block
else
store[label.to_sym] = []
store[label.to_sym] << block
end
end | [
"def",
"append",
"(",
"label",
",",
"block",
")",
"if",
"store",
".",
"key?",
"(",
"label",
".",
"to_sym",
")",
"&&",
"store",
"[",
"label",
".",
"to_sym",
"]",
".",
"respond_to?",
"(",
":<<",
")",
"store",
"[",
"label",
".",
"to_sym",
"]",
"<<",
"block",
"else",
"store",
"[",
"label",
".",
"to_sym",
"]",
"=",
"[",
"]",
"store",
"[",
"label",
".",
"to_sym",
"]",
"<<",
"block",
"end",
"end"
] | Create store
Add new hook
@param [String, Symbol] label
The name of the hook
@param [Proc] block
The block which should be run for the hook | [
"Create",
"store",
"Add",
"new",
"hook"
] | add17615322f575588aef1fccce875396cdf36e9 | https://github.com/cucumber/aruba/blob/add17615322f575588aef1fccce875396cdf36e9/lib/aruba/hooks.rb#L23-L30 | train |
dblock/fui | lib/fui/finder.rb | Fui.Finder.find | def find(path)
results = []
Find.find(path) do |fpath|
if FileTest.directory?(fpath)
next unless ignores
ignores.each do |ignore|
next unless fpath.include?(ignore.realpath.to_s)
puts "Ignoring Directory: #{fpath}" if options[:verbose]
Find.prune
end
end
results << fpath if yield fpath
end
results
end | ruby | def find(path)
results = []
Find.find(path) do |fpath|
if FileTest.directory?(fpath)
next unless ignores
ignores.each do |ignore|
next unless fpath.include?(ignore.realpath.to_s)
puts "Ignoring Directory: #{fpath}" if options[:verbose]
Find.prune
end
end
results << fpath if yield fpath
end
results
end | [
"def",
"find",
"(",
"path",
")",
"results",
"=",
"[",
"]",
"Find",
".",
"find",
"(",
"path",
")",
"do",
"|",
"fpath",
"|",
"if",
"FileTest",
".",
"directory?",
"(",
"fpath",
")",
"next",
"unless",
"ignores",
"ignores",
".",
"each",
"do",
"|",
"ignore",
"|",
"next",
"unless",
"fpath",
".",
"include?",
"(",
"ignore",
".",
"realpath",
".",
"to_s",
")",
"puts",
"\"Ignoring Directory: #{fpath}\"",
"if",
"options",
"[",
":verbose",
"]",
"Find",
".",
"prune",
"end",
"end",
"results",
"<<",
"fpath",
"if",
"yield",
"fpath",
"end",
"results",
"end"
] | Find all files for which the block yields. | [
"Find",
"all",
"files",
"for",
"which",
"the",
"block",
"yields",
"."
] | f71efcad7c046849670ae67e8cfb3303ec3e3c7a | https://github.com/dblock/fui/blob/f71efcad7c046849670ae67e8cfb3303ec3e3c7a/lib/fui/finder.rb#L54-L70 | train |
mhenrixon/sidekiq-unique-jobs | lib/sidekiq_unique_jobs/util.rb | SidekiqUniqueJobs.Util.keys | def keys(pattern = SCAN_PATTERN, count = DEFAULT_COUNT)
return redis(&:keys) if pattern.nil?
redis { |conn| conn.scan_each(match: prefix(pattern), count: count).to_a }
end | ruby | def keys(pattern = SCAN_PATTERN, count = DEFAULT_COUNT)
return redis(&:keys) if pattern.nil?
redis { |conn| conn.scan_each(match: prefix(pattern), count: count).to_a }
end | [
"def",
"keys",
"(",
"pattern",
"=",
"SCAN_PATTERN",
",",
"count",
"=",
"DEFAULT_COUNT",
")",
"return",
"redis",
"(",
":keys",
")",
"if",
"pattern",
".",
"nil?",
"redis",
"{",
"|",
"conn",
"|",
"conn",
".",
"scan_each",
"(",
"match",
":",
"prefix",
"(",
"pattern",
")",
",",
"count",
":",
"count",
")",
".",
"to_a",
"}",
"end"
] | Find unique keys in redis
@param [String] pattern a pattern to scan for in redis
@param [Integer] count the maximum number of keys to delete
@return [Array<String>] an array with active unique keys | [
"Find",
"unique",
"keys",
"in",
"redis"
] | 2944b97c720528f53962ccfd17d43ac939a77f46 | https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/util.rb#L21-L25 | train |
mhenrixon/sidekiq-unique-jobs | lib/sidekiq_unique_jobs/util.rb | SidekiqUniqueJobs.Util.keys_with_ttl | def keys_with_ttl(pattern = SCAN_PATTERN, count = DEFAULT_COUNT)
hash = {}
redis do |conn|
conn.scan_each(match: prefix(pattern), count: count).each do |key|
hash[key] = conn.ttl(key)
end
end
hash
end | ruby | def keys_with_ttl(pattern = SCAN_PATTERN, count = DEFAULT_COUNT)
hash = {}
redis do |conn|
conn.scan_each(match: prefix(pattern), count: count).each do |key|
hash[key] = conn.ttl(key)
end
end
hash
end | [
"def",
"keys_with_ttl",
"(",
"pattern",
"=",
"SCAN_PATTERN",
",",
"count",
"=",
"DEFAULT_COUNT",
")",
"hash",
"=",
"{",
"}",
"redis",
"do",
"|",
"conn",
"|",
"conn",
".",
"scan_each",
"(",
"match",
":",
"prefix",
"(",
"pattern",
")",
",",
"count",
":",
"count",
")",
".",
"each",
"do",
"|",
"key",
"|",
"hash",
"[",
"key",
"]",
"=",
"conn",
".",
"ttl",
"(",
"key",
")",
"end",
"end",
"hash",
"end"
] | Find unique keys with ttl
@param [String] pattern a pattern to scan for in redis
@param [Integer] count the maximum number of keys to delete
@return [Hash<String, Integer>] a hash with active unique keys and corresponding ttl | [
"Find",
"unique",
"keys",
"with",
"ttl"
] | 2944b97c720528f53962ccfd17d43ac939a77f46 | https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/util.rb#L31-L39 | train |
mhenrixon/sidekiq-unique-jobs | lib/sidekiq_unique_jobs/util.rb | SidekiqUniqueJobs.Util.del | def del(pattern = SCAN_PATTERN, count = 0)
raise ArgumentError, "Please provide a number of keys to delete greater than zero" if count.zero?
pattern = suffix(pattern)
log_debug { "Deleting keys by: #{pattern}" }
keys, time = timed { keys(pattern, count) }
key_size = keys.size
log_debug { "#{key_size} keys found in #{time} sec." }
_, time = timed { batch_delete(keys) }
log_debug { "Deleted #{key_size} keys in #{time} sec." }
key_size
end | ruby | def del(pattern = SCAN_PATTERN, count = 0)
raise ArgumentError, "Please provide a number of keys to delete greater than zero" if count.zero?
pattern = suffix(pattern)
log_debug { "Deleting keys by: #{pattern}" }
keys, time = timed { keys(pattern, count) }
key_size = keys.size
log_debug { "#{key_size} keys found in #{time} sec." }
_, time = timed { batch_delete(keys) }
log_debug { "Deleted #{key_size} keys in #{time} sec." }
key_size
end | [
"def",
"del",
"(",
"pattern",
"=",
"SCAN_PATTERN",
",",
"count",
"=",
"0",
")",
"raise",
"ArgumentError",
",",
"\"Please provide a number of keys to delete greater than zero\"",
"if",
"count",
".",
"zero?",
"pattern",
"=",
"suffix",
"(",
"pattern",
")",
"log_debug",
"{",
"\"Deleting keys by: #{pattern}\"",
"}",
"keys",
",",
"time",
"=",
"timed",
"{",
"keys",
"(",
"pattern",
",",
"count",
")",
"}",
"key_size",
"=",
"keys",
".",
"size",
"log_debug",
"{",
"\"#{key_size} keys found in #{time} sec.\"",
"}",
"_",
",",
"time",
"=",
"timed",
"{",
"batch_delete",
"(",
"keys",
")",
"}",
"log_debug",
"{",
"\"Deleted #{key_size} keys in #{time} sec.\"",
"}",
"key_size",
"end"
] | Deletes unique keys from redis
@param [String] pattern a pattern to scan for in redis
@param [Integer] count the maximum number of keys to delete
@return [Integer] the number of keys deleted | [
"Deletes",
"unique",
"keys",
"from",
"redis"
] | 2944b97c720528f53962ccfd17d43ac939a77f46 | https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/util.rb#L46-L59 | train |
mhenrixon/sidekiq-unique-jobs | lib/sidekiq_unique_jobs/unlockable.rb | SidekiqUniqueJobs.Unlockable.unlock | def unlock(item)
SidekiqUniqueJobs::UniqueArgs.digest(item)
SidekiqUniqueJobs::Locksmith.new(item).unlock
end | ruby | def unlock(item)
SidekiqUniqueJobs::UniqueArgs.digest(item)
SidekiqUniqueJobs::Locksmith.new(item).unlock
end | [
"def",
"unlock",
"(",
"item",
")",
"SidekiqUniqueJobs",
"::",
"UniqueArgs",
".",
"digest",
"(",
"item",
")",
"SidekiqUniqueJobs",
"::",
"Locksmith",
".",
"new",
"(",
"item",
")",
".",
"unlock",
"end"
] | Unlocks a job.
@param [Hash] item a Sidekiq job hash | [
"Unlocks",
"a",
"job",
"."
] | 2944b97c720528f53962ccfd17d43ac939a77f46 | https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/unlockable.rb#L13-L16 | train |
mhenrixon/sidekiq-unique-jobs | lib/sidekiq_unique_jobs/unlockable.rb | SidekiqUniqueJobs.Unlockable.delete | def delete(item)
SidekiqUniqueJobs::UniqueArgs.digest(item)
SidekiqUniqueJobs::Locksmith.new(item).delete!
end | ruby | def delete(item)
SidekiqUniqueJobs::UniqueArgs.digest(item)
SidekiqUniqueJobs::Locksmith.new(item).delete!
end | [
"def",
"delete",
"(",
"item",
")",
"SidekiqUniqueJobs",
"::",
"UniqueArgs",
".",
"digest",
"(",
"item",
")",
"SidekiqUniqueJobs",
"::",
"Locksmith",
".",
"new",
"(",
"item",
")",
".",
"delete!",
"end"
] | Deletes a lock regardless of if it was locked or not.
This is good for situations when a job is locked by another item
@param [Hash] item a Sidekiq job hash | [
"Deletes",
"a",
"lock",
"regardless",
"of",
"if",
"it",
"was",
"locked",
"or",
"not",
"."
] | 2944b97c720528f53962ccfd17d43ac939a77f46 | https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/unlockable.rb#L22-L25 | train |
mhenrixon/sidekiq-unique-jobs | lib/sidekiq_unique_jobs/scripts.rb | SidekiqUniqueJobs.Scripts.call | def call(file_name, redis_pool, options = {})
execute_script(file_name, redis_pool, options)
rescue Redis::CommandError => ex
handle_error(ex, file_name) do
call(file_name, redis_pool, options)
end
end | ruby | def call(file_name, redis_pool, options = {})
execute_script(file_name, redis_pool, options)
rescue Redis::CommandError => ex
handle_error(ex, file_name) do
call(file_name, redis_pool, options)
end
end | [
"def",
"call",
"(",
"file_name",
",",
"redis_pool",
",",
"options",
"=",
"{",
"}",
")",
"execute_script",
"(",
"file_name",
",",
"redis_pool",
",",
"options",
")",
"rescue",
"Redis",
"::",
"CommandError",
"=>",
"ex",
"handle_error",
"(",
"ex",
",",
"file_name",
")",
"do",
"call",
"(",
"file_name",
",",
"redis_pool",
",",
"options",
")",
"end",
"end"
] | Call a lua script with the provided file_name
@note this method is recursive if we need to load a lua script
that wasn't previously loaded.
@param [Symbol] file_name the name of the lua script
@param [Sidekiq::RedisConnection, ConnectionPool] redis_pool the redis connection
@param [Hash] options arguments to pass to the script file
@option options [Array] :keys the array of keys to pass to the script
@option options [Array] :argv the array of arguments to pass to the script
@return value from script | [
"Call",
"a",
"lua",
"script",
"with",
"the",
"provided",
"file_name"
] | 2944b97c720528f53962ccfd17d43ac939a77f46 | https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/scripts.rb#L33-L39 | train |
mhenrixon/sidekiq-unique-jobs | lib/sidekiq_unique_jobs/scripts.rb | SidekiqUniqueJobs.Scripts.execute_script | def execute_script(file_name, redis_pool, options = {})
redis(redis_pool) do |conn|
sha = script_sha(conn, file_name)
conn.evalsha(sha, options)
end
end | ruby | def execute_script(file_name, redis_pool, options = {})
redis(redis_pool) do |conn|
sha = script_sha(conn, file_name)
conn.evalsha(sha, options)
end
end | [
"def",
"execute_script",
"(",
"file_name",
",",
"redis_pool",
",",
"options",
"=",
"{",
"}",
")",
"redis",
"(",
"redis_pool",
")",
"do",
"|",
"conn",
"|",
"sha",
"=",
"script_sha",
"(",
"conn",
",",
"file_name",
")",
"conn",
".",
"evalsha",
"(",
"sha",
",",
"options",
")",
"end",
"end"
] | Execute the script file
@param [Symbol] file_name the name of the lua script
@param [Sidekiq::RedisConnection, ConnectionPool] redis_pool the redis connection
@param [Hash] options arguments to pass to the script file
@option options [Array] :keys the array of keys to pass to the script
@option options [Array] :argv the array of arguments to pass to the script
@return value from script (evalsha) | [
"Execute",
"the",
"script",
"file"
] | 2944b97c720528f53962ccfd17d43ac939a77f46 | https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/scripts.rb#L52-L57 | train |
mhenrixon/sidekiq-unique-jobs | lib/sidekiq_unique_jobs/scripts.rb | SidekiqUniqueJobs.Scripts.script_sha | def script_sha(conn, file_name)
if (sha = SCRIPT_SHAS.get(file_name))
return sha
end
sha = conn.script(:load, script_source(file_name))
SCRIPT_SHAS.put(file_name, sha)
sha
end | ruby | def script_sha(conn, file_name)
if (sha = SCRIPT_SHAS.get(file_name))
return sha
end
sha = conn.script(:load, script_source(file_name))
SCRIPT_SHAS.put(file_name, sha)
sha
end | [
"def",
"script_sha",
"(",
"conn",
",",
"file_name",
")",
"if",
"(",
"sha",
"=",
"SCRIPT_SHAS",
".",
"get",
"(",
"file_name",
")",
")",
"return",
"sha",
"end",
"sha",
"=",
"conn",
".",
"script",
"(",
":load",
",",
"script_source",
"(",
"file_name",
")",
")",
"SCRIPT_SHAS",
".",
"put",
"(",
"file_name",
",",
"sha",
")",
"sha",
"end"
] | Return sha of already loaded lua script or load it and return the sha
@param [Sidekiq::RedisConnection] conn the redis connection
@param [Symbol] file_name the name of the lua script
@return [String] sha of the script file
@return [String] the sha of the script | [
"Return",
"sha",
"of",
"already",
"loaded",
"lua",
"script",
"or",
"load",
"it",
"and",
"return",
"the",
"sha"
] | 2944b97c720528f53962ccfd17d43ac939a77f46 | https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/scripts.rb#L68-L76 | train |
mhenrixon/sidekiq-unique-jobs | lib/sidekiq_unique_jobs/scripts.rb | SidekiqUniqueJobs.Scripts.handle_error | def handle_error(ex, file_name)
if ex.message == "NOSCRIPT No matching script. Please use EVAL."
SCRIPT_SHAS.delete(file_name)
return yield if block_given?
end
raise ScriptError, file_name: file_name, source_exception: ex
end | ruby | def handle_error(ex, file_name)
if ex.message == "NOSCRIPT No matching script. Please use EVAL."
SCRIPT_SHAS.delete(file_name)
return yield if block_given?
end
raise ScriptError, file_name: file_name, source_exception: ex
end | [
"def",
"handle_error",
"(",
"ex",
",",
"file_name",
")",
"if",
"ex",
".",
"message",
"==",
"\"NOSCRIPT No matching script. Please use EVAL.\"",
"SCRIPT_SHAS",
".",
"delete",
"(",
"file_name",
")",
"return",
"yield",
"if",
"block_given?",
"end",
"raise",
"ScriptError",
",",
"file_name",
":",
"file_name",
",",
"source_exception",
":",
"ex",
"end"
] | Handle errors to allow retrying errors that need retrying
@param [Redis::CommandError] ex exception to handle
@param [Symbol] file_name the name of the lua script
@return [void]
@yieldreturn [void] yields back to the caller when NOSCRIPT is raised | [
"Handle",
"errors",
"to",
"allow",
"retrying",
"errors",
"that",
"need",
"retrying"
] | 2944b97c720528f53962ccfd17d43ac939a77f46 | https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/scripts.rb#L87-L94 | train |
mhenrixon/sidekiq-unique-jobs | lib/sidekiq_unique_jobs/locksmith.rb | SidekiqUniqueJobs.Locksmith.delete! | def delete!
Scripts.call(
:delete,
redis_pool,
keys: [exists_key, grabbed_key, available_key, version_key, UNIQUE_SET, unique_digest],
)
end | ruby | def delete!
Scripts.call(
:delete,
redis_pool,
keys: [exists_key, grabbed_key, available_key, version_key, UNIQUE_SET, unique_digest],
)
end | [
"def",
"delete!",
"Scripts",
".",
"call",
"(",
":delete",
",",
"redis_pool",
",",
"keys",
":",
"[",
"exists_key",
",",
"grabbed_key",
",",
"available_key",
",",
"version_key",
",",
"UNIQUE_SET",
",",
"unique_digest",
"]",
",",
")",
"end"
] | Deletes the lock regardless of if it has a ttl set | [
"Deletes",
"the",
"lock",
"regardless",
"of",
"if",
"it",
"has",
"a",
"ttl",
"set"
] | 2944b97c720528f53962ccfd17d43ac939a77f46 | https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/locksmith.rb#L43-L49 | train |
mhenrixon/sidekiq-unique-jobs | lib/sidekiq_unique_jobs/locksmith.rb | SidekiqUniqueJobs.Locksmith.lock | def lock(timeout = nil, &block)
Scripts.call(:lock, redis_pool,
keys: [exists_key, grabbed_key, available_key, UNIQUE_SET, unique_digest],
argv: [jid, ttl, lock_type])
grab_token(timeout) do |token|
touch_grabbed_token(token)
return_token_or_block_value(token, &block)
end
end | ruby | def lock(timeout = nil, &block)
Scripts.call(:lock, redis_pool,
keys: [exists_key, grabbed_key, available_key, UNIQUE_SET, unique_digest],
argv: [jid, ttl, lock_type])
grab_token(timeout) do |token|
touch_grabbed_token(token)
return_token_or_block_value(token, &block)
end
end | [
"def",
"lock",
"(",
"timeout",
"=",
"nil",
",",
"&",
"block",
")",
"Scripts",
".",
"call",
"(",
":lock",
",",
"redis_pool",
",",
"keys",
":",
"[",
"exists_key",
",",
"grabbed_key",
",",
"available_key",
",",
"UNIQUE_SET",
",",
"unique_digest",
"]",
",",
"argv",
":",
"[",
"jid",
",",
"ttl",
",",
"lock_type",
"]",
")",
"grab_token",
"(",
"timeout",
")",
"do",
"|",
"token",
"|",
"touch_grabbed_token",
"(",
"token",
")",
"return_token_or_block_value",
"(",
"token",
",",
"block",
")",
"end",
"end"
] | Create a lock for the item
@param [Integer] timeout the number of seconds to wait for a lock.
@return [String] the Sidekiq job_id (jid) | [
"Create",
"a",
"lock",
"for",
"the",
"item"
] | 2944b97c720528f53962ccfd17d43ac939a77f46 | https://github.com/mhenrixon/sidekiq-unique-jobs/blob/2944b97c720528f53962ccfd17d43ac939a77f46/lib/sidekiq_unique_jobs/locksmith.rb#L58-L67 | train |
Subsets and Splits