_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q27000 | Rstruct.Packable.read | test | def read(raw, predecessors=nil)
if raw.respond_to?(:read)
raw = raw.read(self.sizeof())
end
if raw.size < self.sizeof()
raise(ReadError, "Expected #{self.sizeof} bytes, but only got #{raw.size} bytes")
end
vals =
if @unpack_cb
@unpack_cb.call(raw, predecessors)
else
raw.unpack(self.format)
end
return(self.claim_value(vals, predecessors))
end | ruby | {
"resource": ""
} |
q27001 | Rstruct.Packable.pack_value | test | def pack_value(val, obj=nil)
begin
if @pack_cb
@pack_cb.call(val, obj)
else
varray = val.is_a?(Array) ? val : [val]
varray.pack(self.format)
end
rescue => e
raise(PackError, "Error packing #{val.inspect} as type #{self.name.inspect} -- #{e.class} -> #{e}")
end
end | ruby | {
"resource": ""
} |
q27002 | RSpec.Matchers.method_missing | test | def method_missing(sym, *args, &block)
#
# Note: Be sure that the symbol does not contain the word "test". test
# is a private method on Ruby objects and will cause the Be and Has
# matches to fail.
#
return Lebowski::RSpec::Matchers::Be.new(sym, *args) if sym.to_s =~ /^be_/
return Lebowski::RSpec::Matchers::Has.new(sym, *args) if sym.to_s =~ /^have_/
return Lebowski::RSpec::Operators::That.new(sym, *args) if sym.to_s =~ /^that_/
super
end | ruby | {
"resource": ""
} |
q27003 | Jektify.Generator.static_files | test | def static_files
source = File.dirname(ENGINE.assets_path)
asset_files.map do |file|
dir = File.dirname(file)
file_name = File.basename(file)
Jekyll::StaticFile.new @site, source, dir, file_name
end
end | ruby | {
"resource": ""
} |
q27004 | Jektify.Generator.asset_files | test | def asset_files
asset_files = []
Find.find(ENGINE.assets_path).each do |path|
next if File.directory?(path)
next if path.include?(ENGINE.stylesheets_sass_path)
asset_files << path.sub(ENGINE.assets_path, 'assets')
end
asset_files
end | ruby | {
"resource": ""
} |
q27005 | Paypal.Report.daily | test | def daily(time = Date.today, page_size = 50)
time = time.strftime("%Y-%m-%d") unless time.is_a?(String)
report_id = run_report_request('DailyActivityReport', {'report_date' => time}, page_size)
meta_data = get_meta_data_request(report_id)
data = []
meta_data["numberOfPages"].to_i.times do |page_num|
data += get_data_request(report_id, page_num + 1) #it's zero indexed
end
data
end | ruby | {
"resource": ""
} |
q27006 | Paypal.Report.run_report_request | test | def run_report_request(report_name, report_params = {}, page_size = 50)
response = request 'runReportRequest' do |xml|
xml.reportName report_name
report_params.each do |name, value|
xml.reportParam do
xml.paramName name
xml.paramValue value
end
end
xml.pageSize page_size
end
response.elements["runReportResponse/reportId"].get_text.value
end | ruby | {
"resource": ""
} |
q27007 | UniqueGenerator.ClassMethods.generate_unique | test | def generate_unique(length = 32, &blk)
unique = generate_random(length)
unique = generate_random(length) until blk.call(unique)
unique
end | ruby | {
"resource": ""
} |
q27008 | Paperback.Document.draw_paperback | test | def draw_paperback(qr_code:, sixword_lines:, sixword_bytes:, labels:,
passphrase_sha: nil, passphrase_len: nil,
sixword_font_size: nil, base64_content: nil,
base64_bytes: nil)
unless qr_code.is_a?(RQRCode::QRCode)
raise ArgumentError.new('qr_code must be RQRCode::QRCode')
end
# Header & QR code page
pdf.font('Times-Roman')
debug_draw_axes
draw_header(labels: labels, passphrase_sha: passphrase_sha,
passphrase_len: passphrase_len)
add_newline
draw_qr_code(qr_modules: qr_code.modules)
pdf.stroke_color '000000'
pdf.fill_color '000000'
# Sixword page
pdf.start_new_page
draw_sixword(lines: sixword_lines, sixword_bytes: sixword_bytes,
font_size: sixword_font_size,
is_encrypted: passphrase_len)
if base64_content
draw_base64(b64_content: base64_content, b64_bytes: base64_bytes,
is_encrypted: passphrase_len)
end
pdf.number_pages('<page> of <total>', align: :right,
at: [pdf.bounds.right - 100, -2])
end | ruby | {
"resource": ""
} |
q27009 | Danger.DangerXcov.produce_report | test | def produce_report(*args)
# Check xcov availability, install it if needed
`gem install xcov` unless xcov_available?
unless xcov_available?
puts "xcov is not available on this machine"
return
end
require "xcov"
require "fastlane_core"
# Init Xcov
config = FastlaneCore::Configuration.create(Xcov::Options.available_options, convert_options(args.first))
Xcov.config = config
Xcov.ignore_handler = Xcov::IgnoreHandler.new
# Init project
manager = Xcov::Manager.new(config)
# Parse .xccoverage
report_json = manager.parse_xccoverage
# Map and process report
process_report(Xcov::Report.map(report_json))
end | ruby | {
"resource": ""
} |
q27010 | Danger.DangerXcov.output_report | test | def output_report(report)
# Create markdown
report_markdown = report.markdown_value
# Send markdown
markdown(report_markdown)
# Notify failure if minimum coverage hasn't been reached
threshold = Xcov.config[:minimum_coverage_percentage].to_i
if !threshold.nil? && (report.coverage * 100) < threshold
fail("Code coverage under minimum of #{threshold}%")
end
end | ruby | {
"resource": ""
} |
q27011 | Danger.DangerXcov.process_report | test | def process_report(report)
file_names = @dangerfile.git.modified_files.map { |file| File.basename(file) }
file_names += @dangerfile.git.added_files.map { |file| File.basename(file) }
report.targets.each do |target|
target.files = target.files.select { |file| file_names.include?(file.name) }
end
report
end | ruby | {
"resource": ""
} |
q27012 | Digest.CRC16QT.update | test | def update(data)
data.each_byte do |b|
b = revert_byte(b) if REVERSE_DATA
@crc = ((@table[((@crc >> 8) ^ b) & 0xff] ^ (@crc << 8)) & 0xffff)
end
return self
end | ruby | {
"resource": ""
} |
q27013 | XingApi.Client.request | test | def request(http_verb, url, options = {})
full_url = url + hash_to_params(options)
handle(access_token.request(http_verb, full_url))
end | ruby | {
"resource": ""
} |
q27014 | Dummer.Random.string | test | def string(opts = {})
length, any, value = (opts[:length] || 8), opts[:any], opts[:value]
if value
string = value.to_s
Proc.new { string }
elsif any
Proc.new { self.any(any) }
else
Proc.new { Array.new(length){@chars[rand(@chars.size-1)]}.join }
end
end | ruby | {
"resource": ""
} |
q27015 | MultiExiftool.Values.convert | test | def convert tag, val
return val unless val.kind_of?(String)
case tag
when 'partofset', 'track'
return val
end
case val
when REGEXP_TIMESTAMP
year, month, day, hour, minute = $~.captures[0,5].map {|cap| cap.to_i}
if month == 0 || day == 0
return nil
end
second = $6.to_f
zone = $7
zone = '+00:00' if zone == 'Z'
Time.new(year, month, day, hour, minute, second, zone)
when REGEXP_RATIONAL
return val if $2.to_i == 0
Rational($1, $2)
else
val
end
end | ruby | {
"resource": ""
} |
q27016 | MultiExiftool.Values.to_h | test | def to_h
@values.inject(Hash.new) do |h, a|
tag, val = a
h[Values.tag_map[tag]] = convert(Values.unify_tag(tag), val)
h
end
end | ruby | {
"resource": ""
} |
q27017 | Guard.Dsl.n | test | def n(msg, title='', image=nil)
Compat::UI.notify(msg, :title => title, :image => image)
end | ruby | {
"resource": ""
} |
q27018 | Guard.Dsl.eager | test | def eager(command)
require 'pty'
begin
PTY.spawn command do |r, w, pid|
begin
$stdout.puts
r.each {|line| print line }
rescue Errno::EIO
# the process has finished
end
end
rescue PTY::ChildExited
$stdout.puts "The child process exited!"
end
end | ruby | {
"resource": ""
} |
q27019 | SqlTracker.Report.wrap_list | test | def wrap_list(list, width)
list.map do |text|
wrap_text(text, width)
end.flatten
end | ruby | {
"resource": ""
} |
q27020 | SqlTracker.Handler.save | test | def save
return if @data.empty?
output = {}
output[:data] = @data
output[:generated_at] = Time.now.to_s
output[:started_at] = @started_at
output[:format_version] = '1.0'
output[:rails_version] = Rails.version
output[:rails_path] = Rails.root.to_s
FileUtils.mkdir_p(@config.output_path)
filename = "sql_tracker-#{Process.pid}-#{Time.now.to_i}.json"
File.open(File.join(@config.output_path, filename), 'w') do |f|
f.write JSON.dump(output)
end
end | ruby | {
"resource": ""
} |
q27021 | Ref.AbstractReferenceValueMap.delete | test | def delete(key)
ref = @references.delete(key)
if ref
keys_to_id = @references_to_keys_map[ref.referenced_object_id]
if keys_to_id
keys_to_id.delete(key)
@references_to_keys_map.delete(ref.referenced_object_id) if keys_to_id.empty?
end
ref.object
else
nil
end
end | ruby | {
"resource": ""
} |
q27022 | Ref.AbstractReferenceValueMap.merge | test | def merge(other_hash, &block)
to_h.merge(other_hash, &block).reduce(self.class.new) do |map, pair|
map[pair.first] = pair.last
map
end
end | ruby | {
"resource": ""
} |
q27023 | Ref.SoftReference.add_strong_reference | test | def add_strong_reference(obj) #:nodoc:
@@lock.synchronize do
@@strong_references.last[obj] = true
unless @@gc_flag_set
@@gc_flag_set = true
ObjectSpace.define_finalizer(Object.new, @@finalizer)
end
end
end | ruby | {
"resource": ""
} |
q27024 | Ref.WeakReference.object | test | def object #:nodoc:
@ref.__getobj__
rescue => e
# Jruby implementation uses RefError while MRI uses WeakRef::RefError
if (defined?(RefError) && e.is_a?(RefError)) || (defined?(::WeakRef::RefError) && e.is_a?(::WeakRef::RefError))
nil
else
raise e
end
end | ruby | {
"resource": ""
} |
q27025 | Ref.AbstractReferenceKeyMap.delete | test | def delete(key)
@lock.synchronize do
rkey = ref_key(key)
if rkey
@references_to_keys_map.delete(rkey)
@values.delete(rkey)
else
nil
end
end
end | ruby | {
"resource": ""
} |
q27026 | Ref.ReferenceQueue.monitor | test | def monitor(reference)
obj = reference.object
if obj
@lock.synchronize do
@references[reference.referenced_object_id] = reference
end
ObjectSpace.define_finalizer(obj, @finalizer)
else
push(reference)
end
end | ruby | {
"resource": ""
} |
q27027 | Nimbu.Authentication.client | test | def client(options={})
@client ||= ::OAuth2::Client.new(client_id, client_secret,
{
:site => options.fetch(:site) { Nimbu.site },
:authorize_url => 'login/oauth/authorize',
:token_url => 'login/oauth/access_token',
:ssl => { :verify => false }
}
)
end | ruby | {
"resource": ""
} |
q27028 | Nimbu.Connection.default_middleware | test | def default_middleware(options={})
Proc.new do |builder|
unless options[:with_attachments]
builder.use Nimbu::Request::Json
end
builder.use Faraday::Request::Multipart
builder.use Faraday::Request::UrlEncoded
builder.use Nimbu::Request::OAuth2, oauth_token if oauth_token?
builder.use Nimbu::Request::BasicAuth, authentication if basic_authed?
builder.use Nimbu::Request::UserAgent
builder.use Nimbu::Request::SiteHeader, subdomain
builder.use Nimbu::Request::ContentLocale, content_locale
builder.use Faraday::Response::Logger if ENV['DEBUG']
builder.use Nimbu::Response::RaiseError
unless options[:raw]
builder.use Nimbu::Response::Mashify
builder.use Nimbu::Response::Json
end
builder.adapter adapter
end
end | ruby | {
"resource": ""
} |
q27029 | SmartAdapters.Delegator.load | test | def load
unless valid_params?
raise SmartAdapters::Exceptions::InvalidRequestParamsException
end
unless valid_format?
raise SmartAdapters::Exceptions::InvalidRequestFormatException
end
adapter_finder.new(request_manager)
end | ruby | {
"resource": ""
} |
q27030 | Exceptions.Resource.error | test | def error
{
error: {
model: self.object["model"],
model_human: self.object["model_human"],
attribute: self.object["attribute"],
attribute_human: self.object["attribute_human"],
field: self.object["field"],
message: self.object["message"],
full_message: "#{self.object["full_message"]}"
}
}
end | ruby | {
"resource": ""
} |
q27031 | Nimbu.Endpoint.setup | test | def setup(options={})
options.each do |k,v|
self.set(k,v,true)
end
options = Nimbu.options.merge(options)
self.current_options = options
Configuration.keys.each do |key|
send("#{key}=", options[key])
end
process_basic_auth(options[:basic_auth])
end | ruby | {
"resource": ""
} |
q27032 | Nimbu.Endpoint.arguments | test | def arguments(args=(not_set = true), options={}, &block)
if not_set
@arguments
else
@arguments = Arguments.new(self, options).parse(*args, &block)
end
end | ruby | {
"resource": ""
} |
q27033 | Nimbu.Configuration.reset! | test | def reset!
self.client_id = DEFAULT_CLIENT_ID
self.client_secret = DEFAULT_CLIENT_SECRET
self.oauth_token = DEFAULT_OAUTH_TOKEN
self.endpoint = DEFAULT_ENDPOINT
self.site = DEFAULT_SITE
self.ssl = DEFAULT_SSL
self.user_agent = DEFAULT_USER_AGENT
self.connection_options = DEFAULT_CONNECTION_OPTIONS
self.mime_type = DEFAULT_MIME_TYPE
self.login = DEFAULT_LOGIN
self.password = DEFAULT_PASSWORD
self.basic_auth = DEFAULT_BASIC_AUTH
self.auto_pagination = DEFAULT_AUTO_PAGINATION
self.content_locale = DEFAULT_CONTENT_LOCALE
self.adapter = DEFAULT_ADAPTER
self.subdomain = DEFAULT_SUBDOMAIN
self
end | ruby | {
"resource": ""
} |
q27034 | OpenBEL.Helpers.invalid_fts_filters | test | def invalid_fts_filters(filters)
filters.select { |filter|
category, name, value = filter.values_at('category', 'name', 'value')
category == 'fts' && name == 'search' && value.to_s.length <= 1
}.map { |invalid_fts_filter|
error = <<-MSG.gsub(/^\s+/, '').strip
Full-text search filter values must be larger than one.
MSG
invalid_fts_filter.merge(:error => error)
}
end | ruby | {
"resource": ""
} |
q27035 | Parameters.ModuleMethods.extended | test | def extended(object)
each_param do |param|
object.params[param.name] = param.to_instance(object)
end
end | ruby | {
"resource": ""
} |
q27036 | Parameters.ClassMethods.params= | test | def params=(values)
values.each do |name,value|
if has_param?(name)
get_param(name).value = case value
when Parameters::ClassParam,
Parameters::InstanceParam
value.value
else
value
end
end
end
end | ruby | {
"resource": ""
} |
q27037 | Parameters.ClassMethods.parameter | test | def parameter(name,options={})
name = name.to_sym
# define the reader class method for the parameter
meta_def(name) do
get_param(name).value
end
# define the writer class method for the parameter
meta_def("#{name}=") do |value|
get_param(name).value = value
end
# define the ? method, to determine if the parameter is set
meta_def("#{name}?") do
!!get_param(name).value
end
# define the reader instance methods for the parameter
define_method(name) do
get_param(name).value
end
# define the writter instance methods for the parameter
define_method("#{name}=") do |value|
get_param(name).value = value
end
# define the ? method, to determine if the parameter is set
define_method("#{name}?") do
!!get_param(name).value
end
# create the new parameter
new_param = Parameters::ClassParam.new(
name,
options[:type],
options[:description],
options[:default]
)
# add the parameter to the class params list
params[name] = new_param
return new_param
end | ruby | {
"resource": ""
} |
q27038 | Parameters.ClassMethods.has_param? | test | def has_param?(name)
name = name.to_sym
ancestors.each do |ancestor|
if ancestor.included_modules.include?(Parameters)
return true if ancestor.params.has_key?(name)
end
end
return false
end | ruby | {
"resource": ""
} |
q27039 | Parameters.ClassMethods.get_param | test | def get_param(name)
name = name.to_sym
ancestors.each do |ancestor|
if ancestor.included_modules.include?(Parameters)
if ancestor.params.has_key?(name)
return ancestor.params[name]
end
end
end
raise(Parameters::ParamNotFound,"parameter #{name.to_s.dump} was not found in class #{self}")
end | ruby | {
"resource": ""
} |
q27040 | Parameters.ClassMethods.set_param | test | def set_param(name,value)
name = name.to_sym
ancestors.each do |ancestor|
if ancestor.included_modules.include?(Parameters)
if ancestor.params.has_key?(name)
return ancestor.params[name].set(value)
end
end
end
raise(Parameters::ParamNotFound,"parameter #{name.to_s.dump} was not found in class #{self}")
end | ruby | {
"resource": ""
} |
q27041 | Parameters.ClassMethods.each_param | test | def each_param(&block)
ancestors.reverse_each do |ancestor|
if ancestor.included_modules.include?(Parameters)
ancestor.params.each_value(&block)
end
end
return self
end | ruby | {
"resource": ""
} |
q27042 | DataMapper.Transaction.link | test | def link(*things)
unless none?
raise "Illegal state for link: #{state}"
end
things.each do |thing|
case thing
when DataMapper::Adapters::AbstractAdapter
@adapters[thing] = :none
when DataMapper::Repository
link(thing.adapter)
when DataMapper::Model
link(*thing.repositories)
when DataMapper::Resource
link(thing.model)
when Array
link(*thing)
else
raise "Unknown argument to #{self.class}#link: #{thing.inspect} (#{thing.class})"
end
end
if block_given?
commit { |*block_args| yield(*block_args) }
else
self
end
end | ruby | {
"resource": ""
} |
q27043 | DataMapper.Transaction.commit | test | def commit
if block_given?
unless none?
raise "Illegal state for commit with block: #{state}"
end
begin
self.begin
rval = within { |*block_args| yield(*block_args) }
rescue Exception => exception
if begin?
rollback
end
raise exception
ensure
unless exception
if begin?
commit
end
return rval
end
end
else
unless begin?
raise "Illegal state for commit without block: #{state}"
end
each_adapter(:commit_adapter, [:log_fatal_transaction_breakage])
each_adapter(:close_adapter, [:log_fatal_transaction_breakage])
self.state = :commit
end
end | ruby | {
"resource": ""
} |
q27044 | DataMapper.Transaction.within | test | def within
unless block_given?
raise 'No block provided'
end
unless begin?
raise "Illegal state for within: #{state}"
end
adapters = @adapters
adapters.each_key do |adapter|
adapter.push_transaction(self)
end
begin
yield self
ensure
adapters.each_key do |adapter|
adapter.pop_transaction
end
end
end | ruby | {
"resource": ""
} |
q27045 | WebSocket.Parser.next_message | test | def next_message
read_header if @state == :header
read_payload_length if @state == :payload_length
read_mask_key if @state == :mask
read_payload if @state == :payload
@state == :complete ? process_frame! : nil
rescue StandardError => ex
if @on_error
@on_error.call(ex.message)
else
raise ex
end
end | ruby | {
"resource": ""
} |
q27046 | QueryReport.Helper.reporter | test | def reporter(query, options={}, &block)
@report ||= QueryReport::Report.new(params, view_context, options)
@report.query = query
@report.instance_eval &block
render_report(options) unless options[:skip_rendering]
@report
end | ruby | {
"resource": ""
} |
q27047 | FoundationFormBuilder.Rails.infer_type | test | def infer_type(field_name)
case field_name
when :email, :time_zone
field_name
when %r{(\b|_)password(\b|_)}
:password
else
type_mappings = {text: :textarea}
db_type = @object.column_for_attribute(field_name).type
case db_type
when :text
:textarea
when :decimal, :integer, :float
:numeric
else
db_type
end
end
end | ruby | {
"resource": ""
} |
q27048 | ActiveRecordSurvey.Node.validate_instance_node | test | def validate_instance_node(instance_node)
# Basically this cache is messed up? Why? TODO.
# Reloading in the spec seems to fix this... but... this could be a booby trap for others
#self.node_validations(true)
# Check the validations on this node against the instance_node
validations_passed = !self.node_validations.collect { |node_validation|
node_validation.validate_instance_node(instance_node, self)
}.include?(false)
# More complex....
# Recureses to the parent node to check
# This is to validate Node::Question since they don't have instance_nodes directly to validate them
parent_validations_passed = !self.survey.node_maps.select { |i| i.node == self}.collect { |node_map|
if node_map.parent
node_map.parent.node.validate_parent_instance_node(instance_node, self)
# Hit top node
else
true
end
}.include?(false)
validations_passed && parent_validations_passed
end | ruby | {
"resource": ""
} |
q27049 | ActiveRecordSurvey.Node.instance_node_path_to_root? | test | def instance_node_path_to_root?(instance_node)
instance_nodes = instance_node.instance.instance_nodes.select { |i| i.node == self }
# if ::ActiveRecordSurvey::Node::Answer but no votes, not a valid path
if self.class.ancestors.include?(::ActiveRecordSurvey::Node::Answer) &&
(instance_nodes.length === 0)
return false
end
# if ::ActiveRecordSurvey::Node::Question but no answers, so needs at least one vote directly on itself
if self.class.ancestors.include?(::ActiveRecordSurvey::Node::Question) &&
(self.answers.length === 0) &&
(instance_nodes.length === 0)
return false
end
# Start at each node_map of this node
# Find the parent node ma
paths = self.survey.node_maps.select { |i| i.node == self }.collect { |node_map|
# There is another level to traverse
if node_map.parent
node_map.parent.node.instance_node_path_to_root?(instance_node)
# This is the root node - we made it!
else
true
end
}
# If recursion reports back to have at least one valid path to root
paths.include?(true)
end | ruby | {
"resource": ""
} |
q27050 | ActiveRecordSurvey.Node.build_link | test | def build_link(to_node)
# build_link only accepts a to_node that inherits from Question
if !to_node.class.ancestors.include?(::ActiveRecordSurvey::Node::Question)
raise ArgumentError.new "to_node must inherit from ::ActiveRecordSurvey::Node::Question"
end
if self.survey.nil?
raise ArgumentError.new "A survey is required before calling #build_link"
end
from_node_maps = self.survey.node_maps.select { |i| i.node == self && !i.marked_for_destruction? }
# Answer has already got a question - throw error
if from_node_maps.select { |i|
i.children.length > 0
}.length > 0
raise RuntimeError.new "This node has already been linked"
end
# Because we need something to clone - filter this further below
to_node_maps = self.survey.node_maps.select { |i| i.node == to_node && !i.marked_for_destruction? }
if to_node_maps.first.nil?
to_node_maps << self.survey.node_maps.build(:survey => self.survey, :node => to_node)
end
# Ensure we can through each possible path of getting to this answer
to_node_map = to_node_maps.first
to_node_map.survey = self.survey # required due to voodoo - we want to use the same survey with the same object_id
# We only want node maps that aren't linked somewhere
to_node_maps = to_node_maps.select { |i| i.parent.nil? }
while to_node_maps.length < from_node_maps.length do
to_node_maps.push(to_node_map.recursive_clone)
end
# Link unused node_maps to the new parents
from_node_maps.each_with_index { |from_node_map, index|
from_node_map.children << to_node_maps[index]
}
# Ensure no infinite loops were created
from_node_maps.each { |node_map|
# There is a path from Q -> A that is a loop
if node_map.has_infinite_loop?
raise RuntimeError.new "Infinite loop detected"
end
}
end | ruby | {
"resource": ""
} |
q27051 | ActiveRecordSurvey.Node.before_destroy_rebuild_node_map | test | def before_destroy_rebuild_node_map
# All the node_maps from this node
self.survey.node_maps.select { |i|
i.node == self
}.each { |node_map|
# Remap all of this nodes children to the parent
node_map.children.each { |child|
node_map.parent.children << child
}
}
true
end | ruby | {
"resource": ""
} |
q27052 | ActiveRecordSurvey.Node::Answer::Scale.validate_instance_node | test | def validate_instance_node(instance_node)
# super - all validations on this node pass
super &&
(instance_node.value.to_s.empty? || !instance_node.value.to_s.match(/^(\d+(\.\d+)?)$/).nil?)
end | ruby | {
"resource": ""
} |
q27053 | ActiveRecordSurvey.Node::Answer::Scale.is_answered_for_instance? | test | def is_answered_for_instance?(instance)
if instance_node = self.instance_node_for_instance(instance)
# Answered if not empty and > 0
!instance_node.value.to_s.empty? && instance_node.value.to_i >= 0
else
false
end
end | ruby | {
"resource": ""
} |
q27054 | ActiveRecordSurvey.Node::Answer::Text.is_answered_for_instance? | test | def is_answered_for_instance?(instance)
if instance_node = self.instance_node_for_instance(instance)
# Answered if has text
instance_node.value.to_s.strip.length > 0
else
false
end
end | ruby | {
"resource": ""
} |
q27055 | ActiveRecordSurvey.NodeMap.recursive_clone | test | def recursive_clone
node_map = self.survey.node_maps.build(:survey => self.survey, :node => self.node)
self.survey.node_maps.select { |i| i.parent == self && !i.marked_for_destruction? }.each { |child_node|
child_node.survey = self.survey # required due to voodoo - we want to use the same survey with the same object_id
node_map.children << child_node.recursive_clone
}
node_map
end | ruby | {
"resource": ""
} |
q27056 | ActiveRecordSurvey.NodeMap.ancestors_until_node_not_ancestor_of | test | def ancestors_until_node_not_ancestor_of(klass)
if !self.parent || !self.node.class.ancestors.include?(klass)
return []
end
[self] + self.parent.ancestors_until_node_not_ancestor_of(klass)
end | ruby | {
"resource": ""
} |
q27057 | ActiveRecordSurvey.NodeMap.children_until_node_not_ancestor_of | test | def children_until_node_not_ancestor_of(klass)
if !self.node.class.ancestors.include?(klass)
return []
end
[self] + self.children.collect { |i|
i.children_until_node_not_ancestor_of(klass)
}
end | ruby | {
"resource": ""
} |
q27058 | ActiveRecordSurvey.NodeMap.has_infinite_loop? | test | def has_infinite_loop?(path = [])
self.survey.node_maps.select { |i| i.parent == self && !i.marked_for_destruction? }.each { |i|
# Detect infinite loop
if path.include?(self.node) || i.has_infinite_loop?(path.clone.push(self.node))
return true
end
}
path.include?(self.node)
end | ruby | {
"resource": ""
} |
q27059 | ActiveRecordSurvey.NodeValidation::MinimumValue.validate_instance_node | test | def validate_instance_node(instance_node, answer_node = nil)
is_valid = (!instance_node.value.to_s.empty? && instance_node.value.to_f >= self.value.to_f)
instance_node.errors[:base] << { :nodes => { answer_node.id => ["MINIMUM_VALUE"] } } if !is_valid
is_valid
end | ruby | {
"resource": ""
} |
q27060 | ActiveRecordSurvey.NodeValidation::MinimumAnswer.validate_instance_node | test | def validate_instance_node(instance_node, question_node = nil)
# Only makes sense for questions to have minimum answers
if !question_node.class.ancestors.include?(::ActiveRecordSurvey::Node::Question)
return false
end
instance = instance_node.instance
# Go through the node_map of this node
total_answered = question_node.node_maps.collect { |question_node_map|
# Get all children until a childs node isn't an answer
question_node_map.children.collect { |i|
i.children_until_node_not_ancestor_of(::ActiveRecordSurvey::Node::Answer)
}.flatten.collect { |i|
i.node.is_answered_for_instance?(instance)
}
}.flatten.select { |i| i }.count
is_valid = (total_answered >= self.value.to_i)
instance_node.errors[:base] << { :nodes => { question_node.id => ["MINIMUM_ANSWER"] } } if !is_valid
is_valid
end | ruby | {
"resource": ""
} |
q27061 | ActiveRecordSurvey.Node::Answer.validate_node | test | def validate_node(instance)
# Ensure each parent node to this node (the goal here is to hit a question node) is valid
!self.survey.node_maps.select { |i|
i.node == self
}.collect { |node_map|
node_map.parent.node.validate_node(instance)
}.include?(false)
end | ruby | {
"resource": ""
} |
q27062 | ActiveRecordSurvey.Node::Answer.question | test | def question
self.survey.node_maps.select { |i|
i.node == self
}.collect { |node_map|
if node_map.parent && node_map.parent.node
# Question is not the next parent - recurse!
if node_map.parent.node.class.ancestors.include?(::ActiveRecordSurvey::Node::Answer)
node_map.parent.node.question
else
node_map.parent.node
end
# Root already
else
nil
end
}.first
end | ruby | {
"resource": ""
} |
q27063 | ActiveRecordSurvey.Node::Answer.next_question | test | def next_question
self.survey.node_maps.select { |i|
i.node == self && !i.marked_for_destruction?
}.each { |answer_node_map|
answer_node_map.children.each { |child|
if !child.node.nil? && !child.marked_for_destruction?
if child.node.class.ancestors.include?(::ActiveRecordSurvey::Node::Question)
return child.node
elsif child.node.class.ancestors.include?(::ActiveRecordSurvey::Node::Answer)
return child.node.next_question
end
else
return nil
end
}
}
return nil
end | ruby | {
"resource": ""
} |
q27064 | ActiveRecordSurvey.Node::Answer.remove_link | test | def remove_link
# not linked to a question - nothing to remove!
return true if (question = self.next_question).nil?
count = 0
to_remove = []
self.survey.node_maps.each { |node_map|
if node_map.node == question
if count > 0
to_remove.concat(node_map.self_and_descendants)
else
node_map.parent = nil
node_map.move_to_root unless node_map.new_record?
end
count = count + 1
end
if node_map.node == self
node_map.children = []
end
}
self.survey.node_maps.each { |node_map|
if to_remove.include?(node_map)
node_map.parent = nil
node_map.mark_for_destruction
end
}
end | ruby | {
"resource": ""
} |
q27065 | ActiveRecordSurvey.Node::Answer.sibling_index | test | def sibling_index
node_maps = self.survey.node_maps
if node_map = node_maps.select { |i| i.node == self }.first
parent = node_map.parent
children = node_maps.select { |i| i.parent && i.parent.node === parent.node }
children.each_with_index { |nm, i|
if nm == node_map
return i
end
}
end
end | ruby | {
"resource": ""
} |
q27066 | ActiveRecordSurvey.Node::Answer.move_up | test | def move_up
self.survey.node_maps.select { |i|
i.node == self
}.collect { |node_map|
begin
node_map.move_left
rescue
end
}
end | ruby | {
"resource": ""
} |
q27067 | ActiveRecordSurvey.Node::Answer.move_down | test | def move_down
self.survey.node_maps.select { |i|
i.node == self
}.collect { |node_map|
begin
node_map.move_right
rescue
end
}
end | ruby | {
"resource": ""
} |
q27068 | ActiveRecordSurvey.Node::Answer::Rank.validate_instance_node | test | def validate_instance_node(instance_node)
# super - all validations on this node pass
super &&
(instance_node.value.to_s.empty? || !instance_node.value.to_s.match(/^\d+$/).nil?) &&
(instance_node.value.to_s.empty? || instance_node.value.to_i >= 1) &&
instance_node.value.to_i <= self.max_rank
end | ruby | {
"resource": ""
} |
q27069 | ActiveRecordSurvey.Node::Answer::Rank.num_above | test | def num_above
count = 0
self.node_maps.each { |i|
# Parent is one of us as well - include it and check its parents
if i.parent.node.class.ancestors.include?(self.class)
count = count + 1 + i.parent.node.num_above
end
}
count
end | ruby | {
"resource": ""
} |
q27070 | ActiveRecordSurvey.Node::Answer::Rank.num_below | test | def num_below
count = 0
self.node_maps.each { |node_map|
node_map.children.each { |child|
# Child is one of us as well - include it and check its children
if child.node.class.ancestors.include?(self.class)
count = count + 1 + child.node.num_below
end
}
}
count
end | ruby | {
"resource": ""
} |
q27071 | ActiveRecordSurvey.NodeValidation::MaximumLength.validate_instance_node | test | def validate_instance_node(instance_node, answer_node = nil)
is_valid = (self.value.to_i >= instance_node.value.to_s.length.to_i)
instance_node.errors[:base] << { :nodes => { answer_node.id => ["MAXIMUM_LENGTH"] } } if !is_valid
is_valid
end | ruby | {
"resource": ""
} |
q27072 | ActiveRecordSurvey.Survey.build_first_question | test | def build_first_question(question_node)
if !question_node.class.ancestors.include?(::ActiveRecordSurvey::Node::Question)
raise ArgumentError.new "must inherit from ::ActiveRecordSurvey::Node::Question"
end
question_node_maps = self.node_maps.select { |i| i.node == question_node && !i.marked_for_destruction? }
# No node_maps exist yet from this question
if question_node_maps.length === 0
# Build our first node-map
question_node_maps << self.node_maps.build(:node => question_node, :survey => self)
end
end | ruby | {
"resource": ""
} |
q27073 | ActiveRecordSurvey.Survey.edges | test | def edges
self.node_maps.select { |i| !i.marked_for_destruction? }.select { |i|
i.node && i.parent
}.collect { |i|
{
:source => i.parent.node.id,
:target => i.node.id,
}
}.uniq
end | ruby | {
"resource": ""
} |
q27074 | ActiveRecordSurvey.Node::Question.validate_parent_instance_node | test | def validate_parent_instance_node(instance_node, child_node)
!self.node_validations.collect { |node_validation|
node_validation.validate_instance_node(instance_node, self)
}.include?(false)
end | ruby | {
"resource": ""
} |
q27075 | ActiveRecordSurvey.Node::Question.update_question_type | test | def update_question_type(klass)
if self.next_questions.length > 0
raise RuntimeError.new "No questions can follow when changing the question type"
end
nm = self.survey.node_maps
answers = self.answers.collect { |answer|
nm.select { |i|
i.node == answer
}
}.flatten.uniq.collect { |answer_node_map|
node = answer_node_map.node
answer_node_map.send((answer_node_map.new_record?)? :destroy : :mark_for_destruction)
node
}.collect { |answer|
answer.type = klass.to_s
answer = answer.becomes(klass)
answer.save if !answer.new_record?
answer
}.uniq
answers.each { |answer|
answer.survey = self.survey
self.build_answer(answer)
}
end | ruby | {
"resource": ""
} |
q27076 | ActiveRecordSurvey.Node::Question.remove_answer | test | def remove_answer(answer_node)
# A survey must either be passed or already present in self.node_maps
if self.survey.nil?
raise ArgumentError.new "A survey must be passed if ActiveRecordSurvey::Node::Question is not yet added to a survey"
end
if !answer_node.class.ancestors.include?(::ActiveRecordSurvey::Node::Answer)
raise ArgumentError.new "::ActiveRecordSurvey::Node::Answer not passed"
end
# Cannot mix answer types
# Check if not match existing - throw error
if !self.answers.include?(answer_node)
raise ArgumentError.new "Answer not linked to question"
end
answer_node.send(:remove_answer, self)
end | ruby | {
"resource": ""
} |
q27077 | ActiveRecordSurvey.Node::Question.build_answer | test | def build_answer(answer_node)
# A survey must either be passed or already present in self.node_maps
if self.survey.nil?
raise ArgumentError.new "A survey must be passed if ActiveRecordSurvey::Node::Question is not yet added to a survey"
end
# Cannot mix answer types
# Check if not match existing - throw error
if !self.answers.select { |answer|
answer.class != answer_node.class
}.empty?
raise ArgumentError.new "Cannot mix answer types on question"
end
# Answers actually define how they're built off the parent node
if answer_node.send(:build_answer, self)
# If any questions existed directly following this question, insert after this answer
self.survey.node_maps.select { |i|
i.node == answer_node && !i.marked_for_destruction?
}.each { |answer_node_map|
self.survey.node_maps.select { |j|
# Same parent
# Is a question
!j.marked_for_destruction? &&
j.parent == answer_node_map.parent && j.node.class.ancestors.include?(::ActiveRecordSurvey::Node::Question)
}.each { |j|
answer_node_map.survey = self.survey
j.survey = self.survey
answer_node_map.children << j
}
}
true
end
end | ruby | {
"resource": ""
} |
q27078 | ActiveRecordSurvey.Node::Question.remove_link | test | def remove_link
return true if (questions = self.next_questions).length === 0
# Remove the link to any direct questions
self.survey.node_maps.select { |i|
i.node == self
}.each { |node_map|
self.survey.node_maps.select { |j|
node_map.children.include?(j)
}.each { |child|
if child.node.class.ancestors.include?(::ActiveRecordSurvey::Node::Question)
child.parent = nil
child.send((child.new_record?)? :destroy : :mark_for_destruction )
end
}
}
# remove link any answeres that have questions
self.answers.collect { |i|
i.remove_link
}
end | ruby | {
"resource": ""
} |
q27079 | ActiveRecordSurvey.Node::Question.before_destroy_rebuild_node_map | test | def before_destroy_rebuild_node_map
self.survey.node_maps.select { |i|
i.node == self
}.each { |node_map|
# Remap all of this nodes children to the parent
node_map.children.each { |child|
if !child.node.class.ancestors.include?(::ActiveRecordSurvey::Node::Answer)
node_map.parent.children << child
end
}
}
true
end | ruby | {
"resource": ""
} |
q27080 | Tabletastic.Helper.table_for | test | def table_for(collection, *args, &block)
block = Tabletastic.default_table_block unless block_given?
klass = default_class_for(collection)
options = args.extract_options!
initialize_html_options(options, klass)
result = capture { block.call(TableBuilder.new(collection, klass, self)) }
content_tag(:table, result, options[:html])
end | ruby | {
"resource": ""
} |
q27081 | Tabletastic.Helper.default_class_for | test | def default_class_for(collection)
if collection.respond_to?(:klass) # ActiveRecord::Relation
collection.klass
elsif !collection.empty?
collection.first.class
end
end | ruby | {
"resource": ""
} |
q27082 | Metro.EventDictionary.events_for_targets | test | def events_for_targets(*list)
found_events = Array(list).flatten.compact.map {|s| events_for_target(s) }.flatten.compact
found_events
end | ruby | {
"resource": ""
} |
q27083 | Metro.View.writer | test | def writer
@writer ||= begin
writer_matching_existing_parser = supported_writers.find { |writer| writer.format == format }
writer_matching_existing_parser || default_writer
end
end | ruby | {
"resource": ""
} |
q27084 | Metro.HasAnimations.animate | test | def animate(actor_or_actor_name,options,&block)
options[:actor] = actor(actor_or_actor_name)
options[:context] = self
animation_group = SceneAnimation.build options, &block
enqueue animation_group
end | ruby | {
"resource": ""
} |
q27085 | Metro.EventRelay.on_mouse_movement | test | def on_mouse_movement(*args,&block)
options = (args.last.is_a?(Hash) ? args.pop : {})
@mouse_movement_actions << ( block || lambda { |instance| send(options[:do]) } )
end | ruby | {
"resource": ""
} |
q27086 | Metro.EventRelay.notification | test | def notification(param,&block)
custom_notifications[param.to_sym] = custom_notifications[param.to_sym] + [ block ]
end | ruby | {
"resource": ""
} |
q27087 | Metro.EventRelay.fire_events_for_held_buttons | test | def fire_events_for_held_buttons
held_actions.each do |key,action|
execute_block_for_target(&action) if window and window.button_down?(key)
end
end | ruby | {
"resource": ""
} |
q27088 | Metro.EventRelay.fire_events_for_notification | test | def fire_events_for_notification(event,sender)
notification_actions = custom_notifications[event]
notification_actions.each do |action|
_fire_event_for_notification(event,sender,action)
end
end | ruby | {
"resource": ""
} |
q27089 | Metro.EventRelay._fire_event_for_notification | test | def _fire_event_for_notification(event,sender,action)
if action.arity == 2
target.instance_exec(sender,event,&action)
elsif action.arity == 1
target.instance_exec(sender,&action)
else
target.instance_eval(&action)
end
end | ruby | {
"resource": ""
} |
q27090 | Metro.Models.add | test | def add(model)
all_models_for(model).each do |model|
models_hash[model.to_s] = model.to_s
name_with_slashes = model.model_name
models_hash[name_with_slashes] = model.to_s
name_with_colons = name_with_slashes.gsub('/','::')
models_hash[name_with_colons] = model.to_s
end
end | ruby | {
"resource": ""
} |
q27091 | Metro.ImplicitAnimation.after_initialize | test | def after_initialize
to.each do |attribute,final|
start = actor.send(attribute)
animations.push build_animation_step(attribute,start,final)
end
end | ruby | {
"resource": ""
} |
q27092 | Metro.EventStateManager.fire_events_for_notification | test | def fire_events_for_notification(event,sender)
current_state.each {|cs| cs.fire_events_for_notification(event,sender) }
end | ruby | {
"resource": ""
} |
q27093 | Metro.EventStateManager.add_events_for_target | test | def add_events_for_target(target,events)
relay = EventRelay.new(target,window)
events.each do |target_event|
relay.send target_event.event, *target_event.buttons, &target_event.block
end
current_state.push relay
end | ruby | {
"resource": ""
} |
q27094 | Metro.Controls.method_missing | test | def method_missing(name,*params,&block)
options = params.find {|param| param.is_a? Hash }
define_control(name,options)
end | ruby | {
"resource": ""
} |
q27095 | Metro.Game.start! | test | def start!
@window = Window.new width, height, fullscreen?
window.caption = name
window.scene = Scenes.generate(first_scene)
window.show
end | ruby | {
"resource": ""
} |
q27096 | Metro.FadeTransitionScene.show | test | def show
rectangle.color = starting_color
color = final_color
animate :rectangle, to: { red: color.red,
green: color.green,
blue: color.blue,
alpha: color.alpha },
interval: interval do
transition_to next_scene
end
end | ruby | {
"resource": ""
} |
q27097 | Tabletastic.TableBuilder.data | test | def data(*args, &block) # :yields: tablebody
options = args.extract_options!
if block_given?
yield self
else
@table_fields = args.empty? ? orm_fields : args.collect {|f| TableField.new(f.to_sym)}
end
action_cells(options[:actions], options[:action_prefix])
["\n", head, "\n", body, "\n"].join("").html_safe
end | ruby | {
"resource": ""
} |
q27098 | Tabletastic.TableBuilder.cell | test | def cell(*args, &proc)
options = args.extract_options!
options.merge!(:klass => klass)
args << options
@table_fields << TableField.new(*args, &proc)
# Since this will likely be called with <%= %> (aka 'concat'), explicitly return an
# empty string; this suppresses unwanted output
return ""
end | ruby | {
"resource": ""
} |
q27099 | Tabletastic.TableBuilder.action_cells | test | def action_cells(actions, prefix = nil)
return if actions.blank?
actions = [actions] if !actions.respond_to?(:each)
actions = [:show, :edit, :destroy] if actions == [:all]
actions.each do |action|
action_link(action.to_sym, prefix)
end
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.