input stringlengths 109 5.2k | output stringlengths 7 509 |
|---|---|
Summarize the following code: def blocklist(*args)
list = flatten_list_of_strings(args)
if list.nil? || list.empty?
bot.blocklist = []
else
bot.blocklist += list
end
end | specify a bot - specific blocklist of users . accepts an array or a comma - delimited string . when called any subsequent calls to search or replies will filter out these users . |
Summarize the following code: def safelist(*args)
list = flatten_list_of_strings(args)
if list.nil? || list.empty?
bot.safelist = []
else
bot.safelist += list
end
end | specify a bot - specific safelist of users . accepts an array or a comma - delimited string . when called any subsequent calls to search or replies will only act upon these users . |
Summarize the following code: def exclude(*args)
e = flatten_list_of_strings(args)
if e.nil? || e.empty?
bot.exclude = []
else
bot.exclude += e
end
end | specify list of strings we will check when deciding to respond to a tweet or not . accepts an array or a comma - delimited string . when called any subsequent calls to search or replies will filter out tweets with these strings |
Summarize the following code: def consumer_secret(s)
bot.deprecated "Setting consumer_secret outside of your config file is deprecated!", Kernel.caller.first
bot.config[:consumer_secret] = s
end | set the consumer secret |
Summarize the following code: def consumer_key(k)
bot.deprecated "Setting consumer_key outside of your config file is deprecated!", Kernel.caller.first
bot.config[:consumer_key] = k
end | set the consumer key |
Summarize the following code: def secret(s)
bot.deprecated "Setting access_token_secret outside of your config file is deprecated!", Kernel.caller.first
bot.config[:access_token_secret] = s
end | set the secret |
Summarize the following code: def token(s)
bot.deprecated "Setting access_token outside of your config file is deprecated!", Kernel.caller.first
bot.config[:access_token] = s
end | set the token |
Summarize the following code: def flatten_list_of_strings(args)
args.collect do |b|
if b.is_a?(String)
# string, split on commas and turn into array
b.split(",").collect { |s| s.strip }
else
# presumably an array
b
end
end.flatten
end | take a variable list of strings and possibly arrays and turn them into a single flat array of strings |
Summarize the following code: def favorite(id=@current_tweet)
return if require_login == false
id = id_from_tweet(id)
#:nocov:
if debug_mode?
debug "I'm in debug mode, otherwise I would favorite tweet id: #{id}"
return
end
#:nocov:
client.favorite id
... | simple wrapper for favoriting a message |
Summarize the following code: def home_timeline(*args, &block)
return unless require_login
debug "check for home_timeline tweets since #{since_id_home_timeline}"
opts = {
:since_id => since_id_home_timeline,
:count => 200
}
results = client.home_timeline(opts)
@curr... | handle the bots timeline |
Summarize the following code: def on_safelist?(s)
search = from_user(s).downcase
safelist.any? { |b| search.include?(b.downcase) }
end | Is this tweet from a user on our safelist? |
Summarize the following code: def search(queries, opts = {}, &block)
debug "check for tweets since #{since_id}"
max_tweets = opts.delete(:limit) || MAX_SEARCH_TWEETS
exact_match = if opts.key?(:exact)
opts.delete(:exact)
else
true
... | internal search code |
Summarize the following code: def tweet(txt, params = {}, original = nil)
return if require_login == false
txt = replace_variables(txt, original)
if debug_mode?
debug "I'm in debug mode, otherwise I would tweet: #{txt}"
else
debug txt
if params.has_key?(:media)
... | simple wrapper for sending a message |
Summarize the following code: def reply(txt, source, params = {})
debug txt
params = {:in_reply_to_status_id => source.id}.merge(params)
tweet txt, params, source
end | reply to a tweet |
Summarize the following code: def direct_message(txt, user=nil)
return unless require_login
if user.nil?
user = current_user
end
client.create_direct_message(user, txt)
end | send a direct message |
Summarize the following code: def direct_messages(opts = {}, &block)
return unless require_login
debug "check for DMs since #{since_id_dm}"
#
# search twitter
#
@current_tweet = nil
client.direct_messages_received(since_id:since_id_dm, count:200).each { |s|
... | check direct messages for the bot |
Summarize the following code: def get_oauth_verifier
green "****************************************"
green "****************************************"
green "**** BOT AUTH TIME! ****"
green "****************************************"
green "**********************************... | print out a message about getting a PIN from twitter then output the URL the user needs to visit to authorize |
Summarize the following code: def get_api_key
green "****************************************"
green "****************************************"
green "**** API SETUP TIME! ****"
green "****************************************"
green "**********************************... | Ask the user to get an API key from Twitter . |
Summarize the following code: def max_id_from(s)
if ! s.respond_to?(:max)
if s.respond_to?(:id)
return s.id
else
return s
end
end
sorted = s.max { |a, b| a.id.to_i <=> b.id.to_i }
sorted && sorted.id
end | given an array or object return the highest id we can find |
Summarize the following code: def slurp_file(f)
f = File.expand_path(f)
tmp = {}
if File.exist?(f)
File.open( f ) { |yf|
tmp = YAML::load( yf )
}
end
tmp.symbolize_keys! unless tmp == false
end | load in a config file |
Summarize the following code: def global_config
tmp = {}
global_config_files.each { |f|
tmp.merge!(slurp_file(f) || {})
}
tmp
end | get any config from our global config files |
Summarize the following code: def bot_config
{
:consumer_key => ENV["chatterbot_consumer_key"],
:consumer_secret => ENV["chatterbot_consumer_secret"],
:access_token => ENV["chatterbot_access_token"],
:access_token_secret => ENV["chatterbot_access_secret"] || ENV["chatterbot_access_... | bot - specific config settings |
Summarize the following code: def load_config(params={})
read_only_data = global_config.merge(bot_config).merge(params)
@config = Chatterbot::ConfigManager.new(config_file, read_only_data)
end | load in the config from the assortment of places it can be specified . |
Summarize the following code: def retweet(id=@current_tweet)
return if require_login == false || id.nil?
id = id_from_tweet(id)
#:nocov:
if debug_mode?
debug "I'm in debug mode, otherwise I would retweet with tweet id: #{id}"
return
end
#:nocov:
client.r... | simple wrapper for retweeting a message |
Summarize the following code: def run!
before_run
HANDLER_CALLS.each { |c|
if (h = @handlers[c])
send(c, *(h.opts)) do |obj|
h.call(obj)
end
end
}
after_run
end | run the bot with the REST API |
Summarize the following code: def replies(*args, &block)
return unless require_login
debug "check for replies since #{since_id_reply}"
opts = {
:since_id => since_id_reply,
:count => 200
}
results = client.mentions_timeline(opts)
@current_tweet = nil
results.... | handle replies for the bot |
Summarize the following code: def skip_me?(s)
search = s.respond_to?(:text) ? s.text : s
exclude.detect { |e| search.downcase.include?(e) } != nil
end | Based on the text of this tweet should it be skipped? |
Summarize the following code: def on_blocklist?(s)
search = if s.is_a?(Twitter::User)
s.name
elsif s.respond_to?(:user) && !s.is_a?(Twitter::NullObject)
from_user(s)
else
s
end.downcase
blocklist.any? { |b| sear... | Is this tweet from a user on our blocklist? |
Summarize the following code: def reset_since_id
config[:since_id] = 1
# do a search of recent tweets with the letter 'a' in them to
# get a rough max tweet id
result = client.search("a", since:Time.now - 10).max_by(&:id)
update_since_id(result)
end | reset the since_id for this bot to the highest since_id we can get by running a really open search and updating config with the max_id |
Summarize the following code: def generate_authorize_url(request_token)
request = consumer.create_signed_request(:get,
consumer.authorize_path, request_token,
{:oauth_callback => 'oob'})
params = request['Authorization'].sub(/^OAuth\s+/, '').split(/,\s+/).map do |param|
key, value =... | copied from t the awesome twitter cli app |
Summarize the following code: def get_screen_name(t = @access_token)
return unless @screen_name.nil?
return if t.nil?
oauth_response = t.get('/1.1/account/verify_credentials.json')
@screen_name = JSON.parse(oauth_response.body)["screen_name"]
end | query twitter for the bots screen name . we do this during the bot registration process |
Summarize the following code: def login(do_update_config=true)
if needs_api_key?
get_api_key
end
if needs_auth_token?
pin = get_oauth_verifier
return false if pin.nil?
begin
# this will throw an error that we can try and catch
@access_token = requ... | handle oauth for this request . if the client isn t authorized print out the auth URL and get a pin code back from the user If + do_update_config + is false don t udpate the bots config file after authorization . This defaults to true but chatterbot - register will pass in false because it does some other work before s... |
Summarize the following code: def reset!
registered_keys.each { |key| ClassConstants.new(key).deconstantize }
@registered_keys = []
container._container.clear
end | This method empties out the container It should ONLY be used for testing purposes |
Summarize the following code: def class_name(classname)
classname = sym_to_str(classname)
classname.split('.').map { |m| inflector.camelize(m) }.join('::')
end | Converts a namespaced symbol or string to a proper class name with modules |
Summarize the following code: def close
flush()
@deflate_buffer << @deflater.finish unless @deflater.finished?
begin
until @deflate_buffer.empty? do
@deflate_buffer.slice!(0, delegate.write(@deflate_buffer))
end
rescue Errno::EAGAIN, Errno::EINTR
retry if write_... | Closes the writer by finishing the compressed data and flushing it to the delegate . |
Summarize the following code: def to_time
second = ((0b11111 & @dos_time) ) * 2
minute = ((0b111111 << 5 & @dos_time) >> 5)
hour = ((0b11111 << 11 & @dos_time) >> 11)
day = ((0b11111 << 16 & @dos_time) >> 16)
month = ((0b1111 << 21 & @dos_time) >> 21)
yea... | Returns a Time instance which is equivalent to the time represented by this object . |
Summarize the following code: def each(&b)
raise IOError, 'non-readable archive' unless readable?
raise IOError, 'closed archive' if closed?
unless @parse_complete then
parse(@archive)
@parse_complete = true
end
@entries.each(&b)
end | Iterates through each entry of a readable ZIP archive in turn yielding each one to the given block . |
Summarize the following code: def add_entry(entry)
raise IOError, 'non-writable archive' unless writable?
raise IOError, 'closed archive' if closed?
unless entry.kind_of?(Entry) then
raise ArgumentError, 'Archive::Zip::Entry instance required'
end
@entries << entry
self
... | Adds _entry_ into a writable ZIP archive . |
Summarize the following code: def extract(destination, options = {})
raise IOError, 'non-readable archive' unless readable?
raise IOError, 'closed archive' if closed?
# Ensure that unspecified options have default values.
options[:directories] = true unless options.has_key?(:directories)
... | Extracts the contents of the archive to _destination_ where _destination_ is a path to a directory which will contain the contents of the archive . The destination path will be created if it does not already exist . |
Summarize the following code: def find_central_directory(io)
# First find the offset to the end of central directory record.
# It is expected that the variable length comment field will usually be
# empty and as a result the initial value of eocd_offset is all that is
# necessary.
#
... | Returns the file offset of the first record in the central directory . _io_ must be a seekable readable IO - like object . |
Summarize the following code: def dump(io)
bytes_written = 0
@entries.each do |entry|
bytes_written += entry.dump_local_file_record(io, bytes_written)
end
central_directory_offset = bytes_written
@entries.each do |entry|
bytes_written += entry.dump_central_file_record(io)
... | Writes all the entries of this archive to _io_ . _io_ must be a writable IO - like object providing a _write_ method . Returns the total number of bytes written . |
Summarize the following code: def view=(view)
@view = (view.respond_to?(:view_context) ? view.view_context : view)
raise 'expected view to respond to params' unless @view.respond_to?(:params)
load_cookie!
assert_cookie!
load_attributes!
# We need early access to filter and scope, t... | Once the view is assigned we initialize everything |
Summarize the following code: def show
begin
@datatable = EffectiveDatatables.find(params[:id])
@datatable.view = view_context
EffectiveDatatables.authorize!(self, :index, @datatable.collection_class)
render json: @datatable.to_json
rescue => e
EffectiveDatatables.a... | This will respond to both a GET and a POST |
Summarize the following code: def register(extention, handler = nil, &block)
handler ||= block
raise 'Handler or block required.' unless handler
@render_library[extention.to_s] = handler
handler
end | Registers a rendering extention . |
Summarize the following code: def requested_method
params['_method'.freeze] = (params['_method'.freeze] || request.request_method.downcase).to_sym
self.class._pl_params2method(params, request.env)
end | Returns the method that was called by the HTTP request . |
Summarize the following code: def send_data(data, options = {})
response.write data if data
filename = options[:filename]
# set headers
content_disposition = options[:inline] ? 'inline'.dup : 'attachment'.dup
content_disposition << "; filename=#{::File.basename(options[:file... | Sends a block of data setting a file name mime type and content disposition headers when possible . This should also be a good choice when sending large amounts of data . |
Summarize the following code: def build_feedback_edge_set(edges, fixed_edges)
edges = edges.dup
acyclic_edges = fixed_edges.dup
feedback_edge_set = []
while edges.present?
edge = edges.shift
if detect_cycle(edge, acyclic_edges)
feedback_edge_set << edge... | Builds a feedback edge set which is a set of edges creating a cycle |
Summarize the following code: def detect_cycle(edge, acyclic_edges, escalation = nil)
# Test if adding edge creates a cycle, ew will traverse the graph from edge Node, through all it's
# dependencies
starting_node = edge.second
edges = [edge] + acyclic_edges
traverse_dependecies([]... | Detects a cycle . Based on escalation returns true or raises exception if there is a cycle |
Summarize the following code: def traverse_dependecies(traversed_nodes, starting_node, current_node, edges, dependencies, escalation)
dependencies.each do |node_edge|
node = node_edge.first
traversed_nodes << node
if traversed_nodes.include?(starting_node)
if escalation == :excep... | Recursive method for traversing dependencies and finding a cycle |
Summarize the following code: def find_in_batches(batch_size: 1000, attributes_index: {})
attributes_index.each_slice(batch_size) do |batch|
yield(inventory_collection.db_collection_for_comparison_for(batch))
end
end | An iterator that can fetch batches of the AR objects based on a set of attribute_indexes |
Summarize the following code: def assign_attributes(attributes)
attributes.each do |k, v|
# We don't want timestamps or resource versions to be overwritten here, since those are driving the conditions
next if %i(resource_timestamps resource_timestamps_max resource_timestamp).include?(k)
ne... | Given hash of attributes we assign them to InventoryObject object using its public writers |
Summarize the following code: def assign_only_newest(full_row_version_attr, partial_row_version_attr, attributes, data, k, v)
# If timestamps are in play, we will set only attributes that are newer
specific_attr_timestamp = attributes[partial_row_version_attr].try(:[], k)
specific_data_timestamp = dat... | Assigns value based on the version attributes . If versions are specified it asigns attribute only if it s newer than existing attribute . |
Summarize the following code: def assign_full_row_version_attr(full_row_version_attr, attributes, data)
if attributes[full_row_version_attr] && data[full_row_version_attr]
# If both timestamps are present, store the bigger one
data[full_row_version_attr] = attributes[full_row_version_attr] if attr... | Assigns attribute representing version of the whole row |
Summarize the following code: def uniq_keys_candidates(keys)
# Find all uniq indexes that that are covering our keys
uniq_key_candidates = unique_indexes.each_with_object([]) { |i, obj| obj << i if (keys - i.columns.map(&:to_sym)).empty? }
if unique_indexes.blank? || uniq_key_candidates.blank?
... | Find candidates for unique key . Candidate must cover all columns we are passing as keys . |
Summarize the following code: def filtered_dependency_attributes
filtered_attributes = dependency_attributes
if attributes_blacklist.present?
filtered_attributes = filtered_attributes.reject { |key, _value| attributes_blacklist.include?(key) }
end
if attributes_whitelist.present?
... | List attributes causing a dependency and filters them by attributes_blacklist and attributes_whitelist |
Summarize the following code: def fixed_attributes
if model_class
presence_validators = model_class.validators.detect { |x| x.kind_of?(ActiveRecord::Validations::PresenceValidator) }
end
# Attributes that has to be always on the entity, so attributes making unique index of the record + attribu... | Attributes that are needed to be able to save the record i . e . attributes that are part of the unique index and attributes with presence validation or NOT NULL constraint |
Summarize the following code: def fixed_dependencies
fixed_attrs = fixed_attributes
filtered_dependency_attributes.each_with_object(Set.new) do |(key, value), fixed_deps|
fixed_deps.merge(value) if fixed_attrs.include?(key)
end.reject(&:saved?)
end | Returns fixed dependencies which are the ones we can t move because we wouldn t be able to save the data |
Summarize the following code: def dependency_attributes_for(inventory_collections)
attributes = Set.new
inventory_collections.each do |inventory_collection|
attributes += filtered_dependency_attributes.select { |_key, value| value.include?(inventory_collection) }.keys
end
attributes
... | Returns what attributes are causing a dependencies to certain InventoryCollection objects . |
Summarize the following code: def records_identities(records)
records = [records] unless records.respond_to?(:map)
records.map { |record| record_identity(record) }
end | Returns array of records identities |
Summarize the following code: def record_identity(record)
identity = record.try(:[], :id) || record.try(:[], "id") || record.try(:id)
raise "Cannot obtain identity of the #{record}" if identity.blank?
{
:id => identity
}
end | Returns a hash with a simple record identity |
Summarize the following code: def active_admin_settings_page(options = {}, &block)
options.assert_valid_keys(*ActiveadminSettingsCached::Options::VALID_OPTIONS)
options = ActiveadminSettingsCached::Options.options_for(options)
coercion =
ActiveadminSettingsCached::Coercions.new(options[:templ... | Declares settings function . |
Summarize the following code: def or(value=nil, &block)
return Failure(block.call(@value)) if failure? && block_given?
return Failure(value) if failure?
return self
end | If it is a Failure it will return a new Failure with the provided value |
Summarize the following code: def write_func_declaration type:, c_name:, args: [], static: true
write_func_prototype type, c_name, args, static: static
@code << ";"
new_line
end | type - Return type of the method . c_name - C Name . args - Array of Arrays containing data type and variable name . |
Summarize the following code: def range(start, limit, ratio: 8)
check_greater(start, 0)
check_greater(limit, start)
check_greater(ratio, 2)
items = []
count = start
items << count
(limit / ratio).times do
count *= ratio
break if count >= limit
items << ... | Generate a range of inputs spaced by powers . |
Summarize the following code: def measure_execution_time(data = nil, repeat: 1, &work)
inputs = data || range(1, 10_000)
times = []
inputs.each_with_index do |input, i|
GC.start
measurements = []
repeat.times do
measurements << clock_time { work.(input, i) }
... | Gather times for each input against an algorithm |
Summarize the following code: def fit_logarithmic(xs, ys)
fit(xs, ys, tran_x: ->(x) { Math.log(x) })
end | Find a line of best fit that approximates logarithmic function |
Summarize the following code: def fit_power(xs, ys)
a, b, rr = fit(xs, ys, tran_x: ->(x) { Math.log(x) },
tran_y: ->(y) { Math.log(y) })
[a, Math.exp(b), rr]
end | Finds a line of best fit that approxmimates power function |
Summarize the following code: def fit_exponential(xs, ys)
a, b, rr = fit(xs, ys, tran_y: ->(y) { Math.log(y) })
[Math.exp(a), Math.exp(b), rr]
end | Find a line of best fit that approximates exponential function |
Summarize the following code: def fit(xs, ys, tran_x: ->(x) { x }, tran_y: ->(y) { y })
eps = (10 ** -10)
n = 0
sum_x = 0.0
sum_x2 = 0.0
sum_y = 0.0
sum_y2 = 0.0
sum_xy = 0.0
xs.zip(ys).each do |x, y|
n += 1
sum_x += tran_x.(x)
... | Fit the performance measurements to construct a model with slope and intercept parameters that minimize the error . |
Summarize the following code: def fit_at(type, slope: nil, intercept: nil, n: nil)
raise ArgumentError, "Incorrect input size: #{n}" unless n > 0
case type
when :logarithmic, :log
intercept + slope * Math.log(n)
when :linear
intercept + slope * n
when :power
interc... | Take a fit and estimate behaviour at input size n |
Summarize the following code: def export(*symbols)
symbols = symbols.first if symbols.first.is_a?(Array)
__exported_symbols.concat(symbols)
end | Adds given symbols to the exported_symbols array |
Summarize the following code: def __expose!
singleton = singleton_class
singleton.private_instance_methods.each do |sym|
singleton.send(:public, sym)
end
__module_info[:private_constants].each do |sym|
const_set(sym, singleton.const_get(sym))
end
self
end | Exposes all private methods and private constants as public |
Summarize the following code: def require(paths, &block)
if @reloader
@reloader.require_dependencies(paths, &block)
else
Unreloader.expand_directory_paths(paths).each{|f| super(f)}
end
end | Add a file glob or array of file globs to monitor for changes . |
Summarize the following code: def record_dependency(dependency, *files)
if @reloader
files = Unreloader.expand_paths(files)
Unreloader.expand_paths(dependency).each do |path|
@reloader.record_dependency(path, files)
end
end
end | Records that each path in + files + depends on + dependency + . If there is a modification to + dependency + all related files will be reloaded after + dependency + is reloaded . Both + dependency + and each entry in + files + can be an array of path globs . |
Summarize the following code: def record_split_class(main_file, *files)
if @reloader
files = Unreloader.expand_paths(files)
files.each do |file|
record_dependency(file, main_file)
end
@reloader.skip_reload(files)
end
end | Record that a class is split into multiple files . + main_file + should be the main file for the class which should require all of the other files . + files + should be a list of all other files that make up the class . |
Summarize the following code: def get_queue(value)
ms = (Time.now.to_f * 1000).to_i - value.to_i
ms < 0 ? 0 : ms
end | Calculates the difference in milliseconds between the HTTP_X_REQUEST_START time and the current time . |
Summarize the following code: def decode(options = {})
decode!(options)
rescue TwoCaptcha::Error => ex
TwoCaptcha::Captcha.new
end | Create a TwoCaptcha API client . |
Summarize the following code: def upload(options = {})
args = {}
args[:body] = options[:raw64] if options[:raw64]
args[:method] = options[:method] || 'base64'
args.merge!(options)
response = request('in', :multipart, args)
unless response.match(/\AOK\|/)
fail(TwoCaptcha::E... | Upload a captcha to 2Captcha . |
Summarize the following code: def captcha(captcha_id)
response = request('res', :get, action: 'get', id: captcha_id)
decoded_captcha = TwoCaptcha::Captcha.new(id: captcha_id)
decoded_captcha.api_response = response
if response.match(/\AOK\|/)
decoded_captcha.text = response.split('|', ... | Retrieve information from an uploaded captcha . |
Summarize the following code: def load_captcha(options)
if options[:raw64]
options[:raw64]
elsif options[:raw]
Base64.encode64(options[:raw])
elsif options[:file]
Base64.encode64(options[:file].read)
elsif options[:path]
Base64.encode64(File.open(options[:path], '... | Load a captcha raw content encoded in base64 from options . |
Summarize the following code: def request(action, method = :get, payload = {})
res = TwoCaptcha::HTTP.request(
url: BASE_URL.gsub(':action', action),
timeout: timeout,
method: method,
payload: payload.merge(key: key, soft_id: 800)
)
validate_response(res)
res
... | Perform an HTTP request to the 2Captcha API . |
Summarize the following code: def validate_response(response)
if (error = TwoCaptcha::RESPONSE_ERRORS[response])
fail(error)
elsif response.to_s.empty? || response.match(/\AERROR\_/)
fail(TwoCaptcha::Error, response)
end
end | Fail if the response has errors . |
Summarize the following code: def search(options, &block)
instrument "search.github_ldap", options.dup do |payload|
result =
if options[:base]
@connection.search(options, &block)
else
search_domains.each_with_object([]) do |base, result|
rs = @conn... | Public - Search entries in the ldap server . |
Summarize the following code: def check_encryption(encryption, tls_options = {})
return unless encryption
tls_options ||= {}
case encryption.downcase.to_sym
when :ssl, :simple_tls
{ method: :simple_tls, tls_options: tls_options }
when :tls, :start_tls
{ method: :start_tls,... | Internal - Determine whether to use encryption or not . |
Summarize the following code: def configure_virtual_attributes(attributes)
@virtual_attributes = if attributes == true
VirtualAttributes.new(true)
elsif attributes.is_a?(Hash)
VirtualAttributes.new(true, attributes)
else
VirtualAttributes.new(false)
end
end | Internal - Configure virtual attributes for this server . If the option is true we ll use the default virual attributes . If it s a Hash we ll map the attributes in the hash . |
Summarize the following code: def complete? chunks
!chunks.empty? && chunks.last.id == "ENDM" && chunks.last.payload == "OK"
end | This more of an internal method use one of the static constructors instead |
Summarize the following code: def prettify(xml)
result = ''
formatter = REXML::Formatters::Pretty.new indent
formatter.compact = compact
doc = REXML::Document.new xml
formatter.write doc, result
result
end | Adds intendations and newlines to + xml + to make it more readable |
Summarize the following code: def call(worker, message, queue)
begin
yield
rescue Exception => ex
raise ex if [Interrupt, SystemExit, SignalException].include?(ex.class)
SidekiqReporter.call(ex, worker: worker, message: message, queue: queue)
raise ex
end
end | Used for Sidekiq 2 . x only |
Summarize the following code: def acquire
df = EM::DefaultDeferrable.new
@redis.lock_acquire([@key], [@token, @timeout]).callback { |success|
if (success)
EM::Hiredis.logger.debug "#{to_s} acquired"
EM.cancel_timer(@expire_timer) if @expire_timer
@expire_timer = EM.add... | Acquire the lock |
Summarize the following code: def unlock
EM.cancel_timer(@expire_timer) if @expire_timer
df = EM::DefaultDeferrable.new
@redis.lock_release([@key], [@token]).callback { |keys_removed|
if keys_removed > 0
EM::Hiredis.logger.debug "#{to_s} released"
df.succeed
else
... | Release the lock |
Summarize the following code: def redis_mock(replies = {})
begin
pid = fork do
trap("TERM") { exit }
RedisMock.start do |command, *args|
(replies[command.to_sym] || lambda { |*_| "+OK" }).call(*args)
end
end
sleep 1 # Give time for the socket to ... | Forks the current process and starts a new mock Redis server on port 6380 . |
Summarize the following code: def configure(uri_string)
uri = URI(uri_string)
if uri.scheme == "unix"
@host = uri.path
@port = nil
else
@host = uri.host
@port = uri.port
@password = uri.password
path = uri.path[1..-1]
@db = path.to_i # Empty pat... | Configure the redis connection to use |
Summarize the following code: def reconnect!(new_uri = nil)
@connection.close_connection
configure(new_uri) if new_uri
@auto_reconnect = true
EM.next_tick { reconnect_connection }
end | Disconnect then reconnect the redis connection . |
Summarize the following code: def configure_inactivity_check(trigger_secs, response_timeout)
raise ArgumentError('trigger_secs must be > 0') unless trigger_secs.to_i > 0
raise ArgumentError('response_timeout must be > 0') unless response_timeout.to_i > 0
@inactivity_trigger_secs = trigger_secs.to_i
... | Starts an inactivity checker which will ping redis if nothing has been heard on the connection for trigger_secs seconds and forces a reconnect after a further response_timeout seconds if we still don t hear anything . |
Summarize the following code: def subscribe(channel, proc = nil, &block)
if cb = proc || block
@sub_callbacks[channel] << cb
end
@subs << channel
raw_send_command(:subscribe, [channel])
return pubsub_deferrable(channel)
end | Subscribe to a pubsub channel |
Summarize the following code: def unsubscribe(channel)
@sub_callbacks.delete(channel)
@subs.delete(channel)
raw_send_command(:unsubscribe, [channel])
return pubsub_deferrable(channel)
end | Unsubscribe all callbacks for a given channel |
Summarize the following code: def unsubscribe_proc(channel, proc)
df = EM::DefaultDeferrable.new
if @sub_callbacks[channel].delete(proc)
if @sub_callbacks[channel].any?
# Succeed deferrable immediately - no need to unsubscribe
df.succeed
else
unsubscribe(channel... | Unsubscribe a given callback from a channel . Will unsubscribe from redis if there are no remaining subscriptions on this channel |
Summarize the following code: def psubscribe(pattern, proc = nil, &block)
if cb = proc || block
@psub_callbacks[pattern] << cb
end
@psubs << pattern
raw_send_command(:psubscribe, [pattern])
return pubsub_deferrable(pattern)
end | Pattern subscribe to a pubsub channel |
Summarize the following code: def punsubscribe(pattern)
@psub_callbacks.delete(pattern)
@psubs.delete(pattern)
raw_send_command(:punsubscribe, [pattern])
return pubsub_deferrable(pattern)
end | Pattern unsubscribe all callbacks for a given pattern |
Summarize the following code: def punsubscribe_proc(pattern, proc)
df = EM::DefaultDeferrable.new
if @psub_callbacks[pattern].delete(proc)
if @psub_callbacks[pattern].any?
# Succeed deferrable immediately - no need to punsubscribe
df.succeed
else
punsubscribe(pa... | Unsubscribe a given callback from a pattern . Will unsubscribe from redis if there are no remaining subscriptions on this pattern |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.