_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q7000
|
RDSBackup.Job.send_mail
|
train
|
def send_mail
return unless @options[:email]
@log.info "Emailing #{@options[:email]}..."
begin
RDSBackup::Email.new(self).send!
@log.info "Email sent to #{@options[:email]} for job #{backup_id}"
rescue Exception => e
@log.warn "Error sending email: #{e.message.split("\n").first}"
end
end
|
ruby
|
{
"resource": ""
}
|
q7001
|
ChefWorkflow.ChefHelper.perform_search
|
train
|
def perform_search(type, query)
Chef::Search::Query.new.search(type, query).first.map(&:name)
end
|
ruby
|
{
"resource": ""
}
|
q7002
|
KeyTree.Tree.keys
|
train
|
def keys
@hash.deep.each_with_object([]) do |(key_path, value), result|
result << key_path.to_key_path unless value.is_a?(Hash)
end
end
|
ruby
|
{
"resource": ""
}
|
q7003
|
YMDT.Base.invoke
|
train
|
def invoke(command, params={})
command_string = compile_command(command, params)
output_command(command_string)
execute(command_string, params)
end
|
ruby
|
{
"resource": ""
}
|
q7004
|
YMDT.Base.output_command
|
train
|
def output_command(command_string)
$stdout.puts
$stdout.puts StringMasker.new(command_string, :username => username, :password => password).to_s
end
|
ruby
|
{
"resource": ""
}
|
q7005
|
YMDT.Base.execute
|
train
|
def execute(command, params={})
unless params[:dry_run]
if params[:return]
System.execute(command, :return => true)
else
$stdout.puts
System.execute(command)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q7006
|
Spidercrawl.Page.doc
|
train
|
def doc
@document = Nokogiri::HTML(@body)
rescue Exception => e
puts e.inspect
puts e.backtrace
end
|
ruby
|
{
"resource": ""
}
|
q7007
|
Spidercrawl.Page.links
|
train
|
def links
@links = doc.css('a').map { |link| link['href'].to_s }.uniq.delete_if { |href| href.empty? }.map { |url| absolutify(url.strip) }
end
|
ruby
|
{
"resource": ""
}
|
q7008
|
Spidercrawl.Page.images
|
train
|
def images
@images = doc.css('img').map { |img| img['src'].to_s }.uniq.delete_if { |src| src.empty? }.map { |url| absolutify(url.strip) }
end
|
ruby
|
{
"resource": ""
}
|
q7009
|
Spidercrawl.Page.text
|
train
|
def text
temp_doc = doc
temp_doc.css('script, noscript, style, link').each { |node| node.remove }
@text = temp_doc.css('body').text.split("\n").collect { |line| line.strip }.join("\n")
end
|
ruby
|
{
"resource": ""
}
|
q7010
|
Connfu.Dispatcher.set_channels!
|
train
|
def set_channels!(message) # :doc:
channel_type = message.channel_type
# select channels with the same channel_type as the incoming message
channels = @app_channels.select { |channel| channel["channel_type"].eql?(channel_type) }
# filter channels
case message.channel_type
when "twitter" # filter by from or to account
channels = channels.select { |channel|
channel["accounts"].select { |item|
item["name"].eql?(message.from) or item["name"].eql?(message.to)
}.length > 0
}
when "voice" # filter by did
channels = channels.select { |channel|
channel["uid"].eql?(message.channel_name)
#channel["phones"].select{|item|
# item["phone_number"].eql?(message.to)
#}.length > 0
}
when "sms"
channels = channels.select { |channel|
channel["phones"].select{|item|
item["phone_number"].eql?(message.to)
}.length > 0
}
when "rss"
channels = channels.select { |channel|
channel["uri"].eql?(message.channel_name)
}
else
logger.warn("This code should not be executed because the first select should avoid this")
logger.info("Unexpected message: #{message.channel_type}")
channels = []
end
# get only the channel unique identifier
channels = channels.map { |channel| channel["uid"] }
logger.debug "Setting channels in the incoming message to #{channels}"
message.channel_name = channels
end
|
ruby
|
{
"resource": ""
}
|
q7011
|
Connfu.Dispatcher.process_message
|
train
|
def process_message(message)
logger.info("Calling event #{message.message_type} in the channel #{message.channel_type}")
@listener_channels[message.channel_type.to_sym].message(message.message_type.to_sym, message)
end
|
ruby
|
{
"resource": ""
}
|
q7012
|
TheArrayComparator.Comparator.add_check
|
train
|
def add_check(data, type, keywords, options = {})
t = type.to_sym
fail Exceptions::UnknownCheckType, "Unknown check type \":#{t}\" given. Did you register it in advance?" unless comparators.key?(t)
opts = {
exceptions: [],
tag: ''
}.merge options
sample = Sample.new(data, keywords, opts[:exceptions], opts[:tag])
strategy_klass = comparators[t]
check = Check.new(strategy_klass, sample)
@cache[:checks].add check
end
|
ruby
|
{
"resource": ""
}
|
q7013
|
TheArrayComparator.Comparator.result
|
train
|
def result
if @cache[:checks].new_objects?
@cache[:checks].stored_objects.each do |c|
@result = Result.new(c.sample) unless c.success?
end
end
@result
end
|
ruby
|
{
"resource": ""
}
|
q7014
|
Family.Parent.migrate
|
train
|
def migrate(row, migrated)
super
if spouse then
spouse.household = migrated.detect { |m| Household === m }
end
end
|
ruby
|
{
"resource": ""
}
|
q7015
|
Aims.Timings.add!
|
train
|
def add!(timings)
timings.descriptions.each{|d|
add_cpu_time(d, timings.cpu_time(d))
add_wall_time(d, timings.wall_time(d))
}
end
|
ruby
|
{
"resource": ""
}
|
q7016
|
Aims.AimsOutput.total_energy
|
train
|
def total_energy
etot = self.geometry_steps.collect{|gs| gs.total_energy }.compact.last
if etot.nil?
Float::NAN
else
etot
end
end
|
ruby
|
{
"resource": ""
}
|
q7017
|
Gogetit.ExecutionHooks.method_added
|
train
|
def method_added(method_name)
# do nothing if the method that was added was an actual hook method, or
# if it already had hooks added to it
return if hooks.include?(method_name) || hooked_methods.include?(method_name)
add_hooks_to(method_name)
end
|
ruby
|
{
"resource": ""
}
|
q7018
|
NForm.Hashable.hash_of
|
train
|
def hash_of(*keys)
keys.each.with_object({}){|k,h| h[k] = send(k) }
end
|
ruby
|
{
"resource": ""
}
|
q7019
|
Yargi.ElementSet.set_mark
|
train
|
def set_mark(key, value, dup=true)
self.each {|elm| elm.set_mark(key, (dup and not(Symbol===value)) ? value.dup : value)}
end
|
ruby
|
{
"resource": ""
}
|
q7020
|
BigIndex.Model.rebuild_index
|
train
|
def rebuild_index(options={}, finder_options={})
logger.info "=== Rebuilding index for: #{self.index_type}" unless options[:silent]
if options[:drop]
logger.info "Dropping index for: #{self.index_type}" unless options[:silent]
index_adapter.drop_index(self)
end
finder_options[:batch_size] ||= 100
finder_options[:view] ||= :all
finder_options[:bypass_index] = true
options[:batch_size] ||= 100
options[:commit] = true unless options.has_key?(:commit)
options[:optimize] = true unless options.has_key?(:optimize)
logger.info "Offset: #{finder_options[:offset]}" unless options[:silent]
logger.info "Stop row: #{finder_options[:stop_row]}" unless options[:silent]
buffer = []
items_processed = 0
loop = 0
# Depending on whether the model has a scan or find method, use that.
# scan is from Bigrecord models, and find is from Activerecord.
if self.respond_to?(:scan)
self.scan(finder_options) do |r|
items_processed += 1
buffer << r
if buffer.size > options[:batch_size]
loop += 1
index_adapter.process_index_batch(buffer, loop, options)
buffer.clear
end
end
index_adapter.process_index_batch(buffer, loop, options) unless buffer.empty?
elsif self.respond_to?(:find)
ar_options = {:limit => finder_options[:batch_size]}
while
loop += 1
buffer = self.find_without_index(:all, ar_options)
break if buffer.empty?
items_processed += buffer.size
index_adapter.process_index_batch(buffer, loop, options)
break if buffer.size < finder_options[:batch_size]
buffer.clear
ar_options[:offset] = (loop * finder_options[:batch_size])+1
end
else
raise "Your model needs at least a scan() or find() method"
end
if items_processed > 0
logger.info "Index for #{self.index_type} has been rebuilt (#{items_processed} records)." unless options[:silent]
else
logger.info "Nothing to index for #{self.index_type}." unless options[:silent]
end
logger.info "=== Finished rebuilding index for: #{self.index_type}" unless options[:silent]
return items_processed
end
|
ruby
|
{
"resource": ""
}
|
q7021
|
BigIndex.Model.index
|
train
|
def index(*params, &block)
index_field = IndexField.new(params, block)
add_index_field(index_field)
# Create the attribute finder method
define_finder index_field[:finder_name]
end
|
ruby
|
{
"resource": ""
}
|
q7022
|
HtmlMockup.Server.application
|
train
|
def application
return @app if @app
@stack.use Rack::HtmlValidator if self.options[:validate]
@stack.run Rack::HtmlMockup.new(self.project)
@app = @stack
end
|
ruby
|
{
"resource": ""
}
|
q7023
|
Unobservable.ModuleSupport.define_event
|
train
|
def define_event(name, args = {})
args = {:create_method => true}.merge(args)
name = name.to_sym
if args[:create_method]
define_method name do
return event(name)
end
end
@unobservable_instance_events ||= Set.new
if @unobservable_instance_events.include? name
return false
else
@unobservable_instance_events.add name
return true
end
end
|
ruby
|
{
"resource": ""
}
|
q7024
|
Unobservable.ModuleSupport.attr_event
|
train
|
def attr_event(*names)
args = (names[-1].is_a? Hash) ? names.pop : {}
names.each {|n| define_event(n, args) }
return nil
end
|
ruby
|
{
"resource": ""
}
|
q7025
|
Unobservable.Support.singleton_events
|
train
|
def singleton_events(all = true)
if all
contributors = self.singleton_class.included_modules
contributors -= self.class.included_modules
contributors.push self.singleton_class
Unobservable.collect_instance_events_defined_by(contributors)
else
Unobservable.collect_instance_events_defined_by([self.singleton_class])
end
end
|
ruby
|
{
"resource": ""
}
|
q7026
|
Unobservable.Support.event
|
train
|
def event(name)
@unobservable_events_map ||= {}
e = @unobservable_events_map[name]
if not e
if self.events.include? name
e = Event.new
@unobservable_events_map[name] = e
else
raise NameError, "Undefined event: #{name}"
end
end
return e
end
|
ruby
|
{
"resource": ""
}
|
q7027
|
Unobservable.Event.register
|
train
|
def register(*args, &block)
h = Unobservable.handler_for(*args, &block)
@handlers << h
return h
end
|
ruby
|
{
"resource": ""
}
|
q7028
|
Unobservable.Event.unregister
|
train
|
def unregister(*args, &block)
h = Unobservable.handler_for(*args, &block)
index = @handlers.index(h)
if index
@handlers.slice!(index)
return h
else
return nil
end
end
|
ruby
|
{
"resource": ""
}
|
q7029
|
Roroacms.ViewHelper.is_month_archive?
|
train
|
def is_month_archive?
segments = params[:slug].split('/')
(get_type_by_url == 'AR' && !segments[2].blank? && segments[3].blank?) ? true : false
end
|
ruby
|
{
"resource": ""
}
|
q7030
|
Roroacms.ViewHelper.is_year_archive?
|
train
|
def is_year_archive?
segments = params[:slug].split('/')
(get_type_by_url == 'AR' && !segments[1].blank? && segments[2].blank? && segments[3].blank?) ? true : false
end
|
ruby
|
{
"resource": ""
}
|
q7031
|
Roroacms.ViewHelper.is_homepage?
|
train
|
def is_homepage?
return false if (!defined?(@content.length).blank? || @content.blank?)
@content.id == Setting.get('home_page').to_i ? true : false
end
|
ruby
|
{
"resource": ""
}
|
q7032
|
Roroacms.ViewHelper.obtain_comments_form
|
train
|
def obtain_comments_form
if Setting.get('article_comments') == 'Y'
type = Setting.get('article_comment_type')
@new_comment = Comment.new
if File.exists?("#{Rails.root}/app/views/themes/#{current_theme}/comments_form." + get_theme_ext)
render(:template => "themes/#{current_theme}/comments_form." + get_theme_ext , :layout => nil, :locals => { type: type }).to_s
else
render :inline => 'comments_form.html.erb does not exist in current theme'
end
end
end
|
ruby
|
{
"resource": ""
}
|
q7033
|
Roroacms.ViewHelper.obtain_term_type
|
train
|
def obtain_term_type
return nil if params[:slug].blank?
segments = params[:slug].split('/')
if !segments[1].blank?
term = TermAnatomy.where(:taxonomy => segments[1]).last
term.taxonomy if !term.blank?
else
nil
end
end
|
ruby
|
{
"resource": ""
}
|
q7034
|
Pushfile.Data.mimetype
|
train
|
def mimetype(path)
extension = File.basename(path).split('.')[-1]
Rack::Mime.mime_type(".#{extension}")
end
|
ruby
|
{
"resource": ""
}
|
q7035
|
Snapshotify.Scraper.process
|
train
|
def process document
return unless document.valid
# If we're debugging, output the canonical_url
emitter.log(document.url.canonical_url.colorize(:green))
# Attach the emitter to the document
document.emitter = emitter
# enqueue any other pages being linked to
enqueue(document.links)
# rewrite all absolute links, asset urls, etc
# to use local, relative paths
# document.rewrite
# Write the document to file
document.write!
# Mark this document's canonical_url as processed
processed_urls << document.url.canonical_url
end
|
ruby
|
{
"resource": ""
}
|
q7036
|
Snapshotify.Scraper.enqueue
|
train
|
def enqueue links
# Loop over each document
links.each_with_index do |document, index|
next unless can_be_enqueued?(document)
emitter.log("> Enqueueing: #{document.url.canonical_url}")
unprocessed_documents << document
unprocessed_urls << document.url.canonical_url
end
end
|
ruby
|
{
"resource": ""
}
|
q7037
|
Snapshotify.Scraper.can_be_enqueued?
|
train
|
def can_be_enqueued?(document)
archivable?(document) &&
# ensure the next document is on an allowable domain
valid_domains.include?(document.url.host) &&
# ensure the next document hasn't been processed yet
!processed_urls.include?(document.url.canonical_url) &&
# ensure the next document hasn't been enqueued yet
!unprocessed_urls.include?(document.url.canonical_url)
end
|
ruby
|
{
"resource": ""
}
|
q7038
|
Snapshotify.Scraper.archivable?
|
train
|
def archivable?(document)
# check if the document is likely to be a html page
archivable_document = document.url.valid
# check of the document hasn't already been evaluated and discarded
has_been_marked_as_invalid = self.invalid_urls.include?(document.url.raw_url)
# Add the dpcument to the list of needed
if !archivable_document && !has_been_marked_as_invalid
emitter.warning("> Invalid URL: #{document.url.raw_url}")
invalid_urls << document.url.raw_url
end
archivable_document
end
|
ruby
|
{
"resource": ""
}
|
q7039
|
AMQP.SpecHelper.done
|
train
|
def done(delay=nil)
super(delay) do
yield if block_given?
EM.next_tick do
run_em_hooks :amqp_after
if AMQP.conn and not AMQP.closing
AMQP.stop_connection do
AMQP.cleanup_state
finish_em_loop
end
else
AMQP.cleanup_state
finish_em_loop
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q7040
|
BarkestCore.UserManager.primary_source
|
train
|
def primary_source
return :ldap if using_ldap? && !using_db?
return :db if using_db? && !using_ldap?
source = @options[:primary_source]
source = source.to_sym if source.is_a?(String)
return source if [:ldap, :db].include?(source)
return :ldap if using_ldap?
:db
end
|
ruby
|
{
"resource": ""
}
|
q7041
|
BarkestCore.UserManager.authenticate
|
train
|
def authenticate(email, password, client_ip)
return nil unless email && BarkestCore::EmailTester.valid_email?(email, false)
email = email.downcase
sources.each do |source|
if source == :ldap
entry = @ldap.search(filter: "(&(objectClass=user)(mail=#{email}))")
if entry && entry.count == 1 # we found a match.
user = User.find_by(email: email, ldap: true)
# make sure it authenticates correctly.
entry = @ldap.bind_as(filter: "(&(objectClass=user)(mail=#{email}))", password: password)
# do not allow authenticating against the DB now.
unless entry && entry.count == 1
add_failure_to user || email, '(LDAP) failed to authenticate', client_ip
return nil
end
# load the user and return.
user = load_ldap_user(entry.first, true, client_ip)
unless user.enabled?
add_failure_to user, '(LDAP) account disabled', client_ip
return nil
end
add_success_to user, '(LDAP)', client_ip
return user
end
else
user = User.find_by(email: email)
if user
# user must be enabled, cannot be LDAP, and the password must match.
if user.ldap?
add_failure_to user, '(DB) cannot authenticate LDAP user', client_ip
return nil
end
unless user.enabled?
add_failure_to user, '(DB) account disabled', client_ip
return nil
end
if user.authenticate(password)
add_success_to user, '(DB)', client_ip
return user
else
add_failure_to user, '(DB) invalid password', client_ip
return nil
end
end
end
end
add_failure_to email, 'invalid email', client_ip
nil
end
|
ruby
|
{
"resource": ""
}
|
q7042
|
BarkestCore.UserManager.ldap_system_admin_groups
|
train
|
def ldap_system_admin_groups
@ldap_system_admin_groups ||=
begin
val = @options[:ldap_system_admin_groups]
val.blank? ? [] : val.strip.gsub(',', ';').split(';').map{|v| v.strip.upcase}
end
end
|
ruby
|
{
"resource": ""
}
|
q7043
|
Serf.Serfer.call
|
train
|
def call(parcel)
# 1. Execute interactor
response_kind, response_message, response_headers = interactor.call parcel
# 2. Extract a possible version embedded in the response_kind.
# This is sugar syntax for kind and version.
if response_kind
kind_part, version_part = response_kind.split '#', 2
response_kind = kind_part if version_part
if version_part
response_headers ||= {}
response_headers[:version] = version_part
end
end
# 3. Return a new response parcel with:
# a. uuids set from parent parcel
# b. kind set to response kind
# c. the message set to response_message
# d. add extra headers to the parcel
return parcel_factory.create(
parent: parcel,
kind: response_kind,
message: response_message,
headers: response_headers)
end
|
ruby
|
{
"resource": ""
}
|
q7044
|
PivotalApi.Client.me
|
train
|
def me
data = get("/me").body
Resources::Me.new({ client: self }.merge(data))
end
|
ruby
|
{
"resource": ""
}
|
q7045
|
Numerals.Format::Symbols.regexp
|
train
|
def regexp(*args)
options = args.pop if args.last.is_a?(Hash)
options ||= {}
symbols = args
digits = symbols.delete(:digits)
grouped_digits = symbols.delete(:grouped_digits)
symbols = symbols.map { |s|
s.is_a?(Symbol) ? send(s) : s
}
if grouped_digits
symbols += [group_separator, insignificant_digit]
elsif digits
symbols += [insignificant_digit]
end
if digits || grouped_digits
symbols += @digits.digits(options)
end
regexp_group(symbols, options)
end
|
ruby
|
{
"resource": ""
}
|
q7046
|
Octopress.Filters.expand_url
|
train
|
def expand_url(input, url=nil)
url ||= root
url = if input.start_with?("http", url)
input
else
File.join(url, input)
end
smart_slash(url)
end
|
ruby
|
{
"resource": ""
}
|
q7047
|
JsonRspecMatchMaker.Base.expand_definition
|
train
|
def expand_definition(definition)
return definition if definition.is_a? Hash
definition.each_with_object({}) do |key, result|
if key.is_a? String
result[key] = :default
elsif key.is_a? Hash
result.merge!(expand_sub_definitions(key))
end
end
end
|
ruby
|
{
"resource": ""
}
|
q7048
|
JsonRspecMatchMaker.Base.expand_sub_definitions
|
train
|
def expand_sub_definitions(sub_definitions)
sub_definitions.each_with_object({}) do |(subkey, value), result|
result[subkey] = value
next if value.respond_to? :call
result[subkey][:attributes] = expand_definition(value[:attributes])
end
end
|
ruby
|
{
"resource": ""
}
|
q7049
|
JsonRspecMatchMaker.Base.check_definition
|
train
|
def check_definition(definition, current_expected, current_key = nil)
definition.each do |error_key, match_def|
if match_def.is_a? Hash
key = [current_key, error_key].compact.join('.')
check_each(key, match_def, current_expected)
else
check_values(current_key, error_key, match_def, current_expected)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q7050
|
JsonRspecMatchMaker.Base.check_each
|
train
|
def check_each(error_key, each_definition, current_expected)
enumerable = each_definition[:each].call(current_expected)
enumerable.each_with_index do |each_instance, idx|
full_key = [error_key, idx].join('.')
check_definition(each_definition[:attributes], each_instance, full_key)
end
end
|
ruby
|
{
"resource": ""
}
|
q7051
|
JsonRspecMatchMaker.Base.check_values
|
train
|
def check_values(key_prefix, error_key, match_function, expected_instance = expected)
expected_value = ExpectedValue.new(match_function, expected_instance, error_key, @prefix)
target_value = TargetValue.new([key_prefix, error_key].compact.join('.'), target)
add_error(expected_value, target_value) unless expected_value == target_value
end
|
ruby
|
{
"resource": ""
}
|
q7052
|
UsBankHolidays.DateMethods.add_banking_days
|
train
|
def add_banking_days(days)
day = self
if days > 0
days.times { day = day.next_banking_day }
elsif days < 0
(-days).times { day = day.previous_banking_day }
end
day
end
|
ruby
|
{
"resource": ""
}
|
q7053
|
BBLib.FuzzyMatcher.similarity
|
train
|
def similarity(string_a, string_b)
string_a, string_b = prep_strings(string_a, string_b)
return 100.0 if string_a == string_b
score = 0
total_weight = algorithms.values.inject { |sum, weight| sum + weight }
algorithms.each do |algorithm, weight|
next unless weight.positive?
score+= string_a.send("#{algorithm}_similarity", string_b) * weight
end
score / total_weight
end
|
ruby
|
{
"resource": ""
}
|
q7054
|
BBLib.FuzzyMatcher.best_match
|
train
|
def best_match(string_a, *string_b)
similarities(string_a, *string_b).max_by { |_k, v| v }[0]
end
|
ruby
|
{
"resource": ""
}
|
q7055
|
BBLib.FuzzyMatcher.similarities
|
train
|
def similarities(string_a, *string_b)
[*string_b].map { |word| [word, matches[word] = similarity(string_a, word)] }
end
|
ruby
|
{
"resource": ""
}
|
q7056
|
ReindeerETL::Transforms.SimpleTransforms.st_only_cols
|
train
|
def st_only_cols dict
(dict.keys.to_set - @only_cols).each{|col|dict.delete(col)}
dict
end
|
ruby
|
{
"resource": ""
}
|
q7057
|
ReindeerETL::Transforms.SimpleTransforms.st_require_cols
|
train
|
def st_require_cols dict
dcols = dict.keys.to_set
unless @require_cols.subset? dict.keys.to_set
missing_cols = (@require_cols - dcols).to_a
raise ReindeerETL::Errors::RecordInvalid.new("Missing required columns: #{missing_cols}")
end
end
|
ruby
|
{
"resource": ""
}
|
q7058
|
ActiveResource.Errors.from_array
|
train
|
def from_array(messages, save_cache=false)
clear unless save_cache
messages.each do |msg|
add msg[0], msg[1]
end
end
|
ruby
|
{
"resource": ""
}
|
q7059
|
IRCSupport.Modes.parse_modes
|
train
|
def parse_modes(modes)
mode_changes = []
modes.scan(/[-+]\w+/).each do |modegroup|
set, modegroup = modegroup.split '', 2
set = set == '+' ? true : false
modegroup.split('').each do |mode|
mode_changes << { set: set, mode: mode }
end
end
return mode_changes
end
|
ruby
|
{
"resource": ""
}
|
q7060
|
IRCSupport.Modes.parse_channel_modes
|
train
|
def parse_channel_modes(modes, opts = {})
chanmodes = opts[:chanmodes] || {
'A' => %w{b e I}.to_set,
'B' => %w{k}.to_set,
'C' => %w{l}.to_set,
'D' => %w{i m n p s t a q r}.to_set,
}
statmodes = opts[:statmodes] || %w{o h v}.to_set
mode_changes = []
modelist, *args = modes
parse_modes(modelist).each do |mode_change|
set, mode = mode_change[:set], mode_change[:mode]
case
when chanmodes["A"].include?(mode) || chanmodes["B"].include?(mode)
mode_changes << {
mode: mode,
set: set,
argument: args.shift
}
when chanmodes["C"].include?(mode)
mode_changes << {
mode: mode,
set: set,
argument: args.shift.to_i
}
when chanmodes["D"].include?(mode)
mode_changes << {
mode: mode,
set: set,
}
else
raise ArgumentError, "Unknown mode: #{mode}"
end
end
return mode_changes
end
|
ruby
|
{
"resource": ""
}
|
q7061
|
IRCSupport.Modes.condense_modes
|
train
|
def condense_modes(modes)
action = nil
result = ''
modes.split(//).each do |mode|
if mode =~ /[+-]/ and (!action or mode != action)
result += mode
action = mode
next
end
result += mode if mode =~ /[^+-]/
end
result.sub!(/[+-]\z/, '')
return result
end
|
ruby
|
{
"resource": ""
}
|
q7062
|
IRCSupport.Modes.diff_modes
|
train
|
def diff_modes(before, after)
before_modes = before.split(//)
after_modes = after.split(//)
removed = before_modes - after_modes
added = after_modes - before_modes
result = removed.map { |m| '-' + m }.join
result << added.map { |m| '+' + m }.join
return condense_modes(result)
end
|
ruby
|
{
"resource": ""
}
|
q7063
|
Jinx.JavaProperty.infer_collection_type_from_name
|
train
|
def infer_collection_type_from_name
# the property name
pname = @property_descriptor.name
# The potential class name is the capitalized property name without a 'Collection' suffix.
cname = pname.capitalize_first.sub(/Collection$/, '')
jname = [@declarer.parent_module, cname].join('::')
klass = eval jname rescue nil
if klass then logger.debug { "Inferred #{declarer.qp} #{self} collection domain type #{klass.qp} from the property name." } end
klass
end
|
ruby
|
{
"resource": ""
}
|
q7064
|
Nucleon.Environment.define_plugin_types
|
train
|
def define_plugin_types(namespace, type_info)
if type_info.is_a?(Hash)
type_info.each do |plugin_type, default_provider|
define_plugin_type(namespace, plugin_type, default_provider)
end
end
self
end
|
ruby
|
{
"resource": ""
}
|
q7065
|
Nucleon.Environment.loaded_plugin
|
train
|
def loaded_plugin(namespace, plugin_type, provider)
get([ :load_info, namespace, sanitize_id(plugin_type), sanitize_id(provider) ], nil)
end
|
ruby
|
{
"resource": ""
}
|
q7066
|
Nucleon.Environment.loaded_plugins
|
train
|
def loaded_plugins(namespace = nil, plugin_type = nil, provider = nil, default = {})
load_info = get_hash(:load_info)
namespace = namespace.to_sym if namespace
plugin_type = sanitize_id(plugin_type) if plugin_type
provider = sanitize_id(provider) if provider
results = default
if namespace && load_info.has_key?(namespace)
if plugin_type && load_info[namespace].has_key?(plugin_type)
if provider && load_info[namespace][plugin_type].has_key?(provider)
results = load_info[namespace][plugin_type][provider]
elsif ! provider
results = load_info[namespace][plugin_type]
end
elsif ! plugin_type
results = load_info[namespace]
end
elsif ! namespace
results = load_info
end
results
end
|
ruby
|
{
"resource": ""
}
|
q7067
|
Nucleon.Environment.plugin_has_provider?
|
train
|
def plugin_has_provider?(namespace, plugin_type, provider)
get_hash([ :load_info, namespace, sanitize_id(plugin_type) ]).has_key?(sanitize_id(provider))
end
|
ruby
|
{
"resource": ""
}
|
q7068
|
Nucleon.Environment.get_plugin
|
train
|
def get_plugin(namespace, plugin_type, plugin_name)
namespace = namespace.to_sym
plugin_type = sanitize_id(plugin_type)
instances = get_hash([ :active_info, namespace, plugin_type ])
instance_ids = array(@instance_map.get([ namespace, plugin_type, plugin_name.to_s.to_sym ]))
if instance_ids.size
return instances[instance_ids[0]]
end
nil
end
|
ruby
|
{
"resource": ""
}
|
q7069
|
Nucleon.Environment.remove_plugin
|
train
|
def remove_plugin(namespace, plugin_type, instance_name, &code) # :yields: plugin
plugin = delete([ :active_info, namespace, sanitize_id(plugin_type), instance_name ])
code.call(plugin) if code && plugin
plugin
end
|
ruby
|
{
"resource": ""
}
|
q7070
|
Nucleon.Environment.active_plugins
|
train
|
def active_plugins(namespace = nil, plugin_type = nil, provider = nil)
active_info = get_hash(:active_info)
namespace = namespace.to_sym if namespace
plugin_type = sanitize_id(plugin_type) if plugin_type
provider = sanitize_id(provider) if provider
results = {}
if namespace && active_info.has_key?(namespace)
if plugin_type && active_info[namespace].has_key?(plugin_type)
if provider && ! active_info[namespace][plugin_type].keys.empty?
active_info[namespace][plugin_type].each do |instance_name, plugin|
plugin = active_info[namespace][plugin_type][instance_name]
results[instance_name] = plugin if plugin.plugin_provider == provider
end
elsif ! provider
results = active_info[namespace][plugin_type]
end
elsif ! plugin_type
results = active_info[namespace]
end
elsif ! namespace
results = active_info
end
results
end
|
ruby
|
{
"resource": ""
}
|
q7071
|
Nucleon.Environment.class_const
|
train
|
def class_const(name, separator = '::')
components = class_name(name, separator, TRUE)
constant = Object
components.each do |component|
constant = constant.const_defined?(component) ?
constant.const_get(component) :
constant.const_missing(component)
end
constant
end
|
ruby
|
{
"resource": ""
}
|
q7072
|
Nucleon.Environment.sanitize_class
|
train
|
def sanitize_class(class_component)
class_component.to_s.split('_').collect {|elem| elem.slice(0,1).capitalize + elem.slice(1..-1) }.join('')
end
|
ruby
|
{
"resource": ""
}
|
q7073
|
Nucleon.Environment.provider_class
|
train
|
def provider_class(namespace, plugin_type, provider)
class_const([ sanitize_class(namespace), sanitize_class(plugin_type), provider ])
end
|
ruby
|
{
"resource": ""
}
|
q7074
|
Bebox.RoleWizard.create_new_role
|
train
|
def create_new_role(project_root, role_name)
# Check if the role name is valid
return error _('wizard.role.invalid_name')%{words: Bebox::RESERVED_WORDS.join(', ')} unless valid_puppet_class_name?(role_name)
# Check if the role exist
return error(_('wizard.role.name_exist')%{role: role_name}) if role_exists?(project_root, role_name)
# Role creation
role = Bebox::Role.new(role_name, project_root)
output = role.create
ok _('wizard.role.creation_success')
return output
end
|
ruby
|
{
"resource": ""
}
|
q7075
|
Bebox.RoleWizard.remove_role
|
train
|
def remove_role(project_root)
# Choose a role from the availables
roles = Bebox::Role.list(project_root)
# Get a role if exist.
if roles.count > 0
role_name = choose_option(roles, _('wizard.role.choose_deletion_role'))
else
return error _('wizard.role.no_deletion_roles')
end
# Ask for deletion confirmation
return warn(_('wizard.no_changes')) unless confirm_action?(_('wizard.role.confirm_deletion'))
# Role deletion
role = Bebox::Role.new(role_name, project_root)
output = role.remove
ok _('wizard.role.deletion_success')
return output
end
|
ruby
|
{
"resource": ""
}
|
q7076
|
Bebox.RoleWizard.add_profile
|
train
|
def add_profile(project_root)
roles = Bebox::Role.list(project_root)
profiles = Bebox::Profile.list(project_root)
role = choose_option(roles, _('wizard.choose_role'))
profile = choose_option(profiles, _('wizard.role.choose_add_profile'))
if Bebox::Role.profile_in_role?(project_root, role, profile)
warn _('wizard.role.profile_exist')%{profile: profile, role: role}
output = false
else
output = Bebox::Role.add_profile(project_root, role, profile)
ok _('wizard.role.add_profile_success')%{profile: profile, role: role}
end
return output
end
|
ruby
|
{
"resource": ""
}
|
q7077
|
Bullring.DrubiedProcess.connect_to_process!
|
train
|
def connect_to_process!
Bullring.logger.debug{"#{caller_name}: Connecting to process..."}
if !process_port_active?
Bullring.logger.debug {"#{caller_name}: Spawning process..."}
# Spawn the process in its own process group so it stays alive even if this process dies
pid = Process.spawn([@options[:process][:command], @options[:process][:args]].flatten.join(" "), {:pgroup => true})
Process.detach(pid)
time_sleeping = 0
while (!process_port_active?)
sleep(0.2)
if (time_sleeping += 0.2) > @options[:process][:max_bringup_time]
Bullring.logger.error {"#{caller_name}: Timed out waiting to bring up the process"}
raise StandardError, "#{caller_name}: Timed out waiting to bring up the process", caller
end
end
end
if !@local_service.nil?
@local_service.stop_service
Bullring.logger.debug {"#{caller_name}: Stopped local service on #{@local_service.uri}"}
end
@local_service = DRb.start_service "druby://127.0.0.1:0"
Bullring.logger.debug {"#{caller_name}: Started local service on #{@local_service.uri}"}
@process = DRbObject.new nil, "druby://#{host}:#{port}"
@after_connect_block.call(@process) if !@after_connect_block.nil?
end
|
ruby
|
{
"resource": ""
}
|
q7078
|
RecaptchaMailhide.ActionViewHelper.recaptcha_mailhide
|
train
|
def recaptcha_mailhide(*args, &block)
options = args.extract_options!
raise ArgumentError, "at least one argument is required (not counting options)" if args.empty?
if block_given?
url = RecaptchaMailhide.url_for(args.first)
link_to(url, recaptcha_mailhide_options(url, options), &block)
else
if args.length == 1
content = truncate_email(args.first, options)
url = RecaptchaMailhide.url_for(args.first)
else
content = args.first
url = RecaptchaMailhide.url_for(args.second)
end
link_to(content, url, recaptcha_mailhide_options(url, options))
end
end
|
ruby
|
{
"resource": ""
}
|
q7079
|
AgileZen.Projects.projects
|
train
|
def projects(options={})
response = connection.get do |req|
req.url "/api/v1/projects", options
end
response.body
end
|
ruby
|
{
"resource": ""
}
|
q7080
|
LitePage.ElementFactory.def_elements
|
train
|
def def_elements(root_elem_var_name, element_definitions = {})
element_definitions.each do |name, definition|
define_method(name) do |other_selectors = {}|
definition[1].merge!(other_selectors)
instance_variable_get(root_elem_var_name.to_sym).send(*definition)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q7081
|
Halffare.PriceSbb.price_scale
|
train
|
def price_scale(definition, order)
return definition['scale'][price_paid][0] * order.price, definition['scale'][price_paid][1] * order.price
end
|
ruby
|
{
"resource": ""
}
|
q7082
|
Halffare.PriceSbb.price_set
|
train
|
def price_set(definition, order)
if order.price != definition['set'][price_paid]
log_order(order)
log_error 'order matched but price differs; ignoring this order.'
p order
p definition
return 0, 0
else
return definition['set']['half'], definition['set']['full']
end
end
|
ruby
|
{
"resource": ""
}
|
q7083
|
Halffare.PriceSbb.price_choices
|
train
|
def price_choices(definition, order)
# auto select
definition['choices'].each { |name,prices| return prices['half'], prices['full'] if prices[price_paid] == order.price }
return price_guess_get(order) if @force_guess_fallback
choose do |menu|
menu.prompt = "\nSelect the choice that applies to your travels? "
log_info "\n"
definition['choices'].each do |name,prices|
menu.choice "#{name} (half-fare: #{currency(prices['half'])}, full: #{currency(prices['full'])})" do
end
end
menu.choice "…or enter manually" do ask_for_price(order) end
end
end
|
ruby
|
{
"resource": ""
}
|
q7084
|
Halffare.PriceSbb.ask_for_price
|
train
|
def ask_for_price(order)
guesshalf, guessfull = price_guess_get(order)
if !Halffare.debug
# was already logged
log_order(order)
end
if @halffare
other = ask("What would have been the full price? ", Float) { |q| q.default = guessfull }
return order.price, other
else
other = ask("What would have been the half-fare price? ", Float) { |q| q.default = guesshalf }
return other, order.price
end
end
|
ruby
|
{
"resource": ""
}
|
q7085
|
Aims.Volume.bounding_box
|
train
|
def bounding_box
unless @bbox
p = @points[0]
minX = p[0]
maxX = p[0]
minY = p[1]
maxY = p[1]
minZ = p[2]
maxZ = p[2]
@points.each{|p|
minX = p[0] if p[0] < minX
maxX = p[0] if p[0] > maxX
minY = p[1] if p[1] < minY
maxY = p[1] if p[1] > maxY
minZ = p[2] if p[2] < minZ
maxZ = p[2] if p[2] > maxZ
}
@max = Vector[maxX, maxY,maxZ]
@min = Vector[minX, minY, minZ]
@bbox = Volume.new([Plane.new(-1,0,0, minX, minY, minZ),
Plane.new(0,-1,0, minX, minY, minZ),
Plane.new(0,0,-1, minX, minY, minZ),
Plane.new(1,0,0, maxX, maxY, maxZ),
Plane.new(0,1,0, maxX, maxY, maxZ),
Plane.new(0,0,1, maxX, maxY, maxZ)])
end
@bbox
end
|
ruby
|
{
"resource": ""
}
|
q7086
|
Aims.Volume.contains_point
|
train
|
def contains_point(x,y,z)
behind = true
@planes.each{|p|
behind = (0 >= p.distance_to_point(x,y,z))
break if not behind
}
return behind
end
|
ruby
|
{
"resource": ""
}
|
q7087
|
BitCore.ContentModule.provider
|
train
|
def provider(position)
content_providers.find_by(position: position) ||
ContentProviders::Null.new(self, position)
end
|
ruby
|
{
"resource": ""
}
|
q7088
|
TriglavClient.JobsApi.create_or_update_job
|
train
|
def create_or_update_job(job, opts = {})
data, _status_code, _headers = create_or_update_job_with_http_info(job, opts)
return data
end
|
ruby
|
{
"resource": ""
}
|
q7089
|
TriglavClient.JobsApi.get_job
|
train
|
def get_job(id_or_uri, opts = {})
data, _status_code, _headers = get_job_with_http_info(id_or_uri, opts)
return data
end
|
ruby
|
{
"resource": ""
}
|
q7090
|
Rubble.Environment.server
|
train
|
def server(*names, &block)
names.each do |name|
server = @tool.provide_server(name)
scope = Scope.new(self, server)
if not block.nil? then
Docile.dsl_eval(scope, &block)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q7091
|
Bebox.WizardsHelper.confirm_action?
|
train
|
def confirm_action?(message)
require 'highline/import'
quest message
response = ask(highline_quest('(y/n)')) do |q|
q.default = "n"
end
return response == 'y' ? true : false
end
|
ruby
|
{
"resource": ""
}
|
q7092
|
Bebox.WizardsHelper.write_input
|
train
|
def write_input(message, default=nil, validator=nil, not_valid_message=nil)
require 'highline/import'
response = ask(highline_quest(message)) do |q|
q.default = default if default
q.validate = /\.(.*)/ if validator
q.responses[:not_valid] = highline_warn(not_valid_message) if not_valid_message
end
return response
end
|
ruby
|
{
"resource": ""
}
|
q7093
|
Bebox.WizardsHelper.choose_option
|
train
|
def choose_option(options, question)
require 'highline/import'
choose do |menu|
menu.header = title(question)
options.each do |option|
menu.choice(option)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q7094
|
Bebox.WizardsHelper.valid_puppet_class_name?
|
train
|
def valid_puppet_class_name?(name)
valid_name = (name =~ /\A[a-z][a-z0-9_]*\Z/).nil? ? false : true
valid_name && !Bebox::RESERVED_WORDS.include?(name)
end
|
ruby
|
{
"resource": ""
}
|
q7095
|
Quicky.Timer.loop_for
|
train
|
def loop_for(name, seconds, options={}, &blk)
end_at = Time.now + seconds
if options[:warmup]
options[:warmup].times do |i|
#puts "Warming up... #{i}"
yield i
end
end
i = 0
while Time.now < end_at
time_i(i, name, options, &blk)
i += 1
end
end
|
ruby
|
{
"resource": ""
}
|
q7096
|
CellularMap.Zone.relative
|
train
|
def relative(x, y)
if x.respond_to?(:to_i) && y.respond_to?(:to_i)
[@x.min + x.to_i, @y.min + y.to_i]
else
x, y = rangeize(x, y)
[ (@x.min + x.min)..(@x.min + x.max),
(@y.min + y.min)..(@y.min + y.max) ]
end
end
|
ruby
|
{
"resource": ""
}
|
q7097
|
CellularMap.Zone.rangeize
|
train
|
def rangeize(x, y)
[x, y].collect { |i| i.respond_to?(:to_i) ? (i.to_i..i.to_i) : i }
end
|
ruby
|
{
"resource": ""
}
|
q7098
|
Jinx.Inverse.set_attribute_inverse
|
train
|
def set_attribute_inverse(attribute, inverse)
prop = property(attribute)
# the standard attribute
pa = prop.attribute
# return if inverse is already set
return if prop.inverse == inverse
# the default inverse
inverse ||= prop.type.detect_inverse_attribute(self)
# If the attribute is not declared by this class, then make a new attribute
# metadata specialized for this class.
unless prop.declarer == self then
prop = restrict_attribute_inverse(prop, inverse)
end
logger.debug { "Setting #{qp}.#{pa} inverse to #{inverse}..." }
# the inverse attribute meta-data
inv_prop = prop.type.property(inverse)
# If the attribute is the many side of a 1:M relation, then delegate to the one side.
if prop.collection? and not inv_prop.collection? then
return prop.type.set_attribute_inverse(inverse, pa)
end
# This class must be the same as or a subclass of the inverse attribute type.
unless self <= inv_prop.type then
raise TypeError.new("Cannot set #{qp}.#{pa} inverse to #{prop.type.qp}.#{pa} with incompatible type #{inv_prop.type.qp}")
end
# Set the inverse in the attribute metadata.
prop.inverse = inverse
# If attribute is the one side of a 1:M or non-reflexive 1:1 relation, then add the inverse updater.
unless prop.collection? then
# Inject adding to the inverse collection into the attribute writer method.
add_inverse_updater(pa)
unless prop.type == inv_prop.type or inv_prop.collection? then
prop.type.delegate_writer_to_inverse(inverse, pa)
end
end
logger.debug { "Set #{qp}.#{pa} inverse to #{inverse}." }
end
|
ruby
|
{
"resource": ""
}
|
q7099
|
Jinx.Inverse.clear_inverse
|
train
|
def clear_inverse(property)
# the inverse property
ip = property.inverse_property || return
# If the property is a collection and the inverse is not, then delegate to
# the inverse.
if property.collection? then
return ip.declarer.clear_inverse(ip) unless ip.collection?
else
# Restore the property reader and writer to the Java reader and writer, resp.
alias_property_accessors(property)
end
# Unset the inverse.
property.inverse = nil
end
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.