_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 30
4.3k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q27300 | Woodhouse::Worker.ClassMethods.method_missing | test | def method_missing(method, *args, &block)
if method.to_s =~ /^asynch?_(.*)/
if instance_methods(false).detect{|meth| meth.to_s | ruby | {
"resource": ""
} |
q27301 | Woodhouse.Layout.add_node | test | def add_node(node)
if node.respond_to?(:to_sym)
node = Woodhouse::Layout::Node.new(node.to_sym) | ruby | {
"resource": ""
} |
q27302 | Woodhouse.Layout.node | test | def node(name)
name = name.to_sym
@nodes.detect{|node|
| ruby | {
"resource": ""
} |
q27303 | Scheherazade.CharacterBuilder.canonical | test | def canonical(attribute_list)
case attribute_list
when nil then {}
when Hash then attribute_list
when Array
attribute_list.map do |attributes|
case attributes
when Symbol
{attributes => AUTO}
when Hash
attributes
else
raise "Unexpected | ruby | {
"resource": ""
} |
q27304 | Scheherazade.Story.imagine | test | def imagine(character_or_model, attributes = nil)
character = to_character(character_or_model)
prev, @building = @building, [] # because method might be re-entrant
CharacterBuilder.new(character).build(attributes) do |ar|
ar.save!
# While errors on records associated with :has_many will prevent records
# from being saved, they won't for :belongs_to, so:
@building.each do |built|
| ruby | {
"resource": ""
} |
q27305 | Scheherazade.Story.with | test | def with(temp_current)
keys = temp_current.keys.map{|k| to_character(k)}
previous_values = current.values_at(*keys)
current.merge!(Hash[keys.zip(temp_current.values)])
| ruby | {
"resource": ""
} |
q27306 | DeferrableGratification.Primitives.failure | test | def failure(exception_class_or_message, message_or_nil = nil)
blank.tap do |d|
d.fail(
case exception_class_or_message
when Exception
raise ArgumentError, "can't specify both exception and message" if message_or_nil
exception_class_or_message
when Class
| ruby | {
"resource": ""
} |
q27307 | FantasticRobot.Request::SendAudio.file_length | test | def file_length
if self.audio.is_a?(File) && self.audio.size > MAX_FILE_SIZE
self.errors.add | ruby | {
"resource": ""
} |
q27308 | FantasticRobot.Connection.api_call | test | def api_call method, payload
raise ArgumentError, "API method not specified." if method.blank?
payload ||= {}
res = @conn.post method.to_s, payload
| ruby | {
"resource": ""
} |
q27309 | Oedipus.Index.multi_search | test | def multi_search(queries)
unless queries.kind_of?(Hash)
raise ArgumentError, "Argument must be a Hash of named queries (#{queries.class} given)"
end
stmts = []
bind_values = []
queries.each do |key, args|
str, *values = @builder.select(*extract_query_data(args))
| ruby | {
"resource": ""
} |
q27310 | Whereabouts.ClassMethods.has_whereabouts | test | def has_whereabouts klass=:address, *args
options = args.extract_options!
# extend Address with class name if not defined.
unless klass == :address || Object.const_defined?(klass.to_s.camelize)
create_address_class(klass.to_s.camelize)
end
# Set the has_one relationship and accepts_nested_attributes_for.
has_one klass, :as => :addressable, :dependent => :destroy
accepts_nested_attributes_for klass
# Define a singleton on the class that returns an array
# that includes the address fields to validate presence of
# or an empty array
if options[:validate] && options[:validate].is_a?(Array)
validators = options[:validate]
set_validators(klass, validators)
else
| ruby | {
"resource": ""
} |
q27311 | Whereabouts.ClassMethods.set_validators | test | def set_validators klass, fields=[]
_single = validate_singleton_for(klass)
klass.to_s.camelize.constantize.class_eval do
fields.each do |f|
validates_presence_of f,
| ruby | {
"resource": ""
} |
q27312 | Whereabouts.ClassMethods.create_address_class | test | def create_address_class(class_name, &block)
klass = Class.new Address, &block
| ruby | {
"resource": ""
} |
q27313 | Qwirk.Worker.event_loop | test | def event_loop
Qwirk.logger.debug "#{self}: Starting receive loop"
@start_worker_time = Time.now
until @stopped || (config.stopped? && @impl.ready_to_stop?)
Qwirk.logger.debug "#{self}: Waiting for read"
@start_read_time = Time.now
msg = @impl.receive_message
if msg
@start_processing_time = Time.now
Qwirk.logger.debug {"#{self}: Done waiting for read in #{@start_processing_time - @start_read_time} seconds"}
delta = config.timer.measure do
@processing_mutex.synchronize do
on_message(msg)
@impl.acknowledge_message(msg)
end
| ruby | {
"resource": ""
} |
q27314 | ActiveRecord.Base.arel_attributes_values | test | def arel_attributes_values(include_primary_key = true, include_readonly_attributes = true, attribute_names = @attributes.keys)
attrs = {}
attribute_names.each do |name|
if (column = column_for_attribute(name)) && (include_primary_key || !column.primary)
if include_readonly_attributes || (!include_readonly_attributes && !self.class.readonly_attributes.include?(name))
| ruby | {
"resource": ""
} |
q27315 | Bugzilla.Bugzilla.requires_version | test | def requires_version(cmd, version_)
v = check_version(version_)
raise NoMethodError, format('%s | ruby | {
"resource": ""
} |
q27316 | Clacks.Service.run | test | def run
begin
Clacks.logger.info "Clacks v#{Clacks::VERSION} started"
if Clacks.config[:pop3]
run_pop3
elsif Clacks.config[:imap]
run_imap
else
| ruby | {
"resource": ""
} |
q27317 | Clacks.Service.imap_validate_options | test | def imap_validate_options(options)
options ||= {}
options[:mailbox] ||= 'INBOX'
options[:count] ||= 5
options[:order] ||= :asc
options[:what] ||= :first
options[:keys] ||= 'ALL'
| ruby | {
"resource": ""
} |
q27318 | Clacks.Service.imap_find | test | def imap_find(imap)
options = Clacks.config[:find_options]
delete_after_find = options[:delete_after_find]
begin
break if stopping?
uids = imap.uid_search(options[:keys] || 'ALL')
uids.reverse! if options[:what].to_sym == :last
uids = uids.first(options[:count]) if options[:count].is_a?(Integer)
uids.reverse! if (options[:what].to_sym == :last && options[:order].to_sym == :asc) ||
(options[:what].to_sym != :last && options[:order].to_sym == :desc)
processed = 0
expunge = false
uids.each do |uid|
break if stopping?
source = imap.uid_fetch(uid, ['RFC822']).first.attr['RFC822']
mail = nil
begin
mail = Mail.new(source)
mail.mark_for_delete = true if delete_after_find
Clacks.config[:on_mail].call(mail)
rescue StandardError => e
Clacks.logger.error(e.message)
Clacks.logger.error(e.backtrace)
end
| ruby | {
"resource": ""
} |
q27319 | Ric.Colors.rainbow | test | def rainbow(str)
i=0
ret = ''
str=str.to_s
while(i < str.length)
ch = str[i]
palette = $color_db[0][i % $color_db[0].length ]
| ruby | {
"resource": ""
} |
q27320 | SecretSharing.Prime.large_enough_prime | test | def large_enough_prime(input)
standard_primes.each do |prime|
return prime if prime > input
end
| ruby | {
"resource": ""
} |
q27321 | SentenceBuilder.SentenceNode.enhance_content | test | def enhance_content(value, separator = ', ') | ruby | {
"resource": ""
} |
q27322 | SecretSharing.Charset.i_to_s | test | def i_to_s(input)
if !input.is_a?(Integer) || input < 0
fail NotPositiveInteger, "input must be a non-negative integer"
end
output = ""
while input > 0
input, | ruby | {
"resource": ""
} |
q27323 | SecretSharing.Charset.s_to_i | test | def s_to_i(string)
string.chars.reduce(0) do |output, char|
| ruby | {
"resource": ""
} |
q27324 | SecretSharing.Charset.char_to_codepoint | test | def char_to_codepoint(c)
codepoint = charset.index c
if codepoint.nil?
fail | ruby | {
"resource": ""
} |
q27325 | SecretSharing.Charset.subset? | test | def subset?(string)
(Set.new(string.chars) | ruby | {
"resource": ""
} |
q27326 | SecretSharing.Polynomial.points | test | def points(num_points, prime)
intercept = @coefficients[0] # the first coefficient is the intercept
(1..num_points).map do |x| | ruby | {
"resource": ""
} |
q27327 | Mead.EadValidator.validate! | test | def validate!
files = Dir.glob(File.join(@directory, '*.xml')).sort
threads = []
files.map do |path|
threads << Thread.new(path) do |path_t|
eadid = File.basename(path_t, '.xml')
begin
ead = Mead::Ead.new({:file => File.open(path_t), | ruby | {
"resource": ""
} |
q27328 | ActionCableNotifications.Model.notify_create | test | def notify_create
self.ChannelPublications.each do |publication, options|
if options[:actions].include? :create
# Checks if records is within scope before broadcasting
records = self.class.scoped_collection(options[:scope])
if options[:scope]==:all or record_within_scope(records) | ruby | {
"resource": ""
} |
q27329 | ActionCableNotifications.Model.notify_update | test | def notify_update
# Get model changes
if self.respond_to?(:saved_changes) # For Rails >= 5.1
changes = self.saved_changes.transform_values(&:second)
else # For Rails < 5.1
changes = self.changes.transform_values(&:second)
end
# Checks if there are changes in the model
if !changes.empty?
self.ChannelPublications.each do |publication, options|
if options[:actions].include? :update
# Checks if previous record was within scope
record = record_within_scope(options[:records])
was_in_scope = record.present?
options[:records].delete(record) if was_in_scope
# Checks if current record is within scope
if options[:track_scope_changes]==true
is_in_scope = false
if options[:scope]==:all
record = self
| ruby | {
"resource": ""
} |
q27330 | ActionCableNotifications.Model.notify_destroy | test | def notify_destroy
self.ChannelPublications.each do |publication, options|
if options[:scope]==:all or options[:actions].include? :destroy
# Checks if record is within scope before broadcasting
if options[:scope]==:all or record_within_scope(self.class.scoped_collection(options[:scope])).present?
| ruby | {
"resource": ""
} |
q27331 | Clacks.Configurator.logger | test | def logger(obj)
%w(debug info warn error fatal level).each do |m|
next if obj.respond_to?(m)
raise | ruby | {
"resource": ""
} |
q27332 | CurrencySpy.ScraperBase.fetch_rates | test | def fetch_rates
if self.class.superclass.eql?(Object)
raise Exception.new("This method should be invoked from CurrencySpy::Scraper sub class")
else
check_currency_code_validity
rate_results = {}
RATE_DATA.each do |rate|
symbol = rate.to_sym
| ruby | {
"resource": ""
} |
q27333 | FormatEngine.SpecInfo.parse | test | def parse(target)
#Handle the width option if specified.
if (width = fmt.width) > 0
head, tail = src[0...width], src[width..-1] || ""
else
head, tail = src, ""
end
#Do the parse on the input string or regex.
@prematch, @match, @postmatch = | ruby | {
"resource": ""
} |
q27334 | FormatEngine.SpecInfo.grab | test | def grab
width = fmt.width
if width > 0
result, @src = src[0...width], src[width..-1] || ""
elsif width == 0
result, @src = src[0...1], src[1..-1] || ""
elsif width == -1
result, @src = src, ""
| ruby | {
"resource": ""
} |
q27335 | Bugzilla.Bug.get_comments | test | def get_comments(bugs)
params = {}
# TODO
# this construction should be refactored to a method
params['ids'] = case bugs
when Array
bugs
when Integer || String
[bugs]
else
raise ArgumentError, format('Unknown type of arguments: %s', bugs.class)
end
result = comments(params)
# not supporting comment_ids. so drop "comments".
ret = result['bugs']
| ruby | {
"resource": ""
} |
q27336 | Qwirk.Manager.save_persist_state | test | def save_persist_state
return unless @persist_file
new_persist_options = {}
BaseWorker.worker_classes.each do |worker_class|
worker_class.each_config(@adapter_factory.worker_config_class) do |config_name, ignored_extended_worker_config_class, default_options|
static_options = default_options.merge(@worker_options[config_name] || {})
worker_config = self[config_name]
hash = {}
# Only store off the config values that are specifically different from default values or values set in the workers.yml file
# Then updates to these values will be allowed w/o being hardcoded to an old default value.
worker_config.bean_get_attributes do |attribute_info|
if attribute_info.attribute[:config_item] && attribute_info.ancestry.size == 1
| ruby | {
"resource": ""
} |
q27337 | Caramelize.RedmineWiki.read_pages | test | def read_pages
# get all projects
results_projects = database.query("SELECT id, identifier, name FROM projects;")
results_projects.each do |row_project|
#collect all namespaces
namespaces << OpenStruct.new(identifier: row_project["identifier"], name: row_project["name"])
end
# get all wikis
results_wikis = database.query("SELECT id, project_id FROM wikis;")
# get all lemmas
results_pages = database.query("SELECT id, title, wiki_id FROM wiki_pages;")
results_pages.each do |row_page|
results_contents = database.query("SELECT * FROM wiki_content_versions WHERE page_id='#{row_page["id"]}' ORDER BY updated_on;")
# get wiki for page
wiki_row = nil
project_row = nil
results_wikis.each do |wiki|
wiki_row = wiki if wiki["id"] == row_page["wiki_id"]
end
if wiki_row
# get project from wiki-id
results_projects.each do |project|
project_row = project if project["id"] == wiki_row["project_id"]
end
end
project_identifier = project_row ? project_row["identifier"] + '/' : ""
title = project_identifier + row_page["title"]
titles << title
@latest_revisions = {}
results_contents.each do |row_content|
| ruby | {
"resource": ""
} |
q27338 | Qwirk.PublishHandle.read_response | test | def read_response(timeout, &block)
raise "Invalid call to read_response for #{@producer}, not setup for responding" unless @producer.response_options
# Creates a block for reading the responses for a given message_id (adapter_info). The block will be passed an object
# that responds to timeout_read(timeout) with a [original_message_id, response_message, worker_name] tri or nil if no message is read.
# This is used in the RPC mechanism where a publish might wait for 1 or more workers to respond.
@producer.impl.with_response(@adapter_info) do |consumer|
if block_given?
return read_multiple_response(consumer, timeout, &block)
else
| ruby | {
"resource": ""
} |
q27339 | RakeCommandFilter.CommandDefinition.add_filter | test | def add_filter(id, pattern, &block)
filter | ruby | {
"resource": ""
} |
q27340 | Mixml.Selection.write | test | def write(template = nil)
if not template.nil? then
template = template.to_mixml_template
end
each_node do |node|
if template.nil? then
| ruby | {
"resource": ""
} |
q27341 | Mixml.Selection.replace | test | def replace(template)
template = template.to_mixml_template
each_node do |node|
| ruby | {
"resource": ""
} |
q27342 | Mixml.Selection.rename | test | def rename(template)
template = template.to_mixml_template
each_node do |node|
| ruby | {
"resource": ""
} |
q27343 | Caramelize.GollumOutput.commit_revision | test | def commit_revision(page, markup)
gollum_page = gollum.page(page.title)
if gollum_page
gollum.update_page(gollum_page, gollum_page.name, gollum_page.format, page.body, build_commit(page))
| ruby | {
"resource": ""
} |
q27344 | Caramelize.GollumOutput.commit_history | test | def commit_history(revisions, options = {}, &block)
options[:markup] = :markdown if !options[:markup] # target markup
revisions.each_with_index do |page, index|
# call debug output from outside
| ruby | {
"resource": ""
} |
q27345 | FormatEngine.FormatSpec.scan_spec | test | def scan_spec(fmt_string)
until fmt_string.empty?
if (match_data = PARSE_REGEX.match(fmt_string))
mid = match_data.to_s
pre = match_data.pre_match
@specs << FormatLiteral.new(pre) unless pre.empty?
@specs << case
when match_data[:var] then FormatVariable.new(mid)
when match_data[:set] then FormatSet.new(mid)
when match_data[:rgx] then FormatRgx.new(mid)
when match_data[:per] then FormatLiteral.new("\%")
| ruby | {
"resource": ""
} |
q27346 | Caramelize.TracConverter.to_textile | test | def to_textile str
body = body.dup
body.gsub!(/\r/, '')
body.gsub!(/\{\{\{([^\n]+?)\}\}\}/, '@\1@')
body.gsub!(/\{\{\{\n#!([^\n]+?)(.+?)\}\}\}/m, '<pre><code class="\1">\2</code></pre>')
body.gsub!(/\{\{\{(.+?)\}\}\}/m, '<pre>\1</pre>')
# macro
body.gsub!(/\[\[BR\]\]/, '')
body.gsub!(/\[\[PageOutline.*\]\]/, '{{toc}}')
body.gsub!(/\[\[Image\((.+?)\)\]\]/, '!\1!')
# header
body.gsub!(/=====\s(.+?)\s=====/, "h5. #{'\1'} \n\n")
body.gsub!(/====\s(.+?)\s====/, "h4. #{'\1'} \n\n")
body.gsub!(/===\s(.+?)\s===/, "h3. #{'\1'} \n\n")
body.gsub!(/==\s(.+?)\s==/, "h2. #{'\1'} \n\n")
body.gsub!(/=\s(.+?)\s=[\s\n]*/, "h1. #{'\1'} \n\n")
# table
body.gsub!(/\|\|/, "|")
# link
body.gsub!(/\[(http[^\s\[\]]+)\s([^\[\]]+)\]/, ' "\2":\1' )
| ruby | {
"resource": ""
} |
q27347 | Ric.Debug.debug2 | test | def debug2(s, opts = {} )
out = opts.fetch(:out, $stdout)
tag = opts.fetch(:tag, '_DFLT_')
really_write = opts.fetch(:really_write, true) # you can prevent ANY debug setting this to false
write_always = opts.fetch(:write_always, false)
raise "ERROR: ':tags' must be an array in debug(), maybe you meant to use :tag?" if ( opts[:tags] && opts[:tags].class != Array )
final_str = "#RDeb#{write_always ? '!' : ''}[#{opts[:tag] || '-'}] #{s}"
final_str = "\033[1;30m" +final_str + "\033[0m" if | ruby | {
"resource": ""
} |
q27348 | BarkestSsh.SecureShell.exec | test | def exec(command, options={}, &block)
raise ConnectionClosed.new('Connection is closed.') unless @channel
options = {
on_non_zero_exit_code: :default
}.merge(options || {})
options[:on_non_zero_exit_code] = @options[:on_non_zero_exit_code] if options[:on_non_zero_exit_code] == :default
push_buffer # store the current buffer and start a fresh buffer
# buffer while also passing data to the supplied block.
if block_given?
buffer_input( &block )
end
# send the command and wait for the prompt to return.
@channel.send_data command + "\n"
wait_for_prompt
# | ruby | {
"resource": ""
} |
q27349 | BarkestSsh.SecureShell.upload | test | def upload(local_file, remote_file)
raise ConnectionClosed.new('Connection | ruby | {
"resource": ""
} |
q27350 | BarkestSsh.SecureShell.download | test | def download(remote_file, local_file)
raise ConnectionClosed.new('Connection is closed.') unless @ssh
| ruby | {
"resource": ""
} |
q27351 | BarkestSsh.SecureShell.write_file | test | def write_file(remote_file, data)
raise ConnectionClosed.new('Connection is closed.') unless @ssh
| ruby | {
"resource": ""
} |
q27352 | GpsUtils.Point.distance | test | def distance(other)
unless other.is_a? Point
raise ArgumentError.new 'other must be a Point.'
end
dlng = GpsUtils::to_radians(other.lng - @lng)
dlat = GpsUtils::to_radians(other.lat - @lat)
x = dlng * | ruby | {
"resource": ""
} |
q27353 | GpsUtils.BoundingBox.cover? | test | def cover?(point)
p = [point.lat - @nw.lat, point.lng - @se.lng]
p21x = p[0] * @p21
p41x = p[1] * @p41
0 < | ruby | {
"resource": ""
} |
q27354 | MongoMapperExt.Paginator.send | test | def send(method, *args, &block)
if respond_to?(method)
super
else
| ruby | {
"resource": ""
} |
q27355 | RakeCommandFilter.LineFilterResult.output | test | def output(elapsed)
case @result
when MATCH_SUCCESS
color = :green
header = 'OK'
when MATCH_FAILURE
color = :red
header = 'FAIL'
when MATCH_WARNING
color = :light_red
header = 'WARN'
end
header | ruby | {
"resource": ""
} |
q27356 | Bugzilla.User.get_userinfo | test | def get_userinfo(user)
p = {}
ids = []
names = []
if user.is_a?(Array)
user.each do |u|
names << u if u.is_a?(String)
id << u if u.is_a?(Integer)
end
elsif user.is_a?(String)
names << user
elsif user.is_a?(Integer)
| ruby | {
"resource": ""
} |
q27357 | Dreader.Engine.options | test | def options &block
options = Options.new
| ruby | {
"resource": ""
} |
q27358 | Dreader.Engine.column | test | def column name, &block
column = Column.new
column.instance_eval(&block) | ruby | {
"resource": ""
} |
q27359 | Dreader.Engine.bulk_declare | test | def bulk_declare hash, &block
hash.keys.each do |key|
column = Column.new
column.colref hash[key]
if block
| ruby | {
"resource": ""
} |
q27360 | Dreader.Engine.read | test | def read args = {}
if args.class == Hash
hash = @options.merge(args)
else
puts "dreader error at #{__callee__}: this function takes a Hash as input"
exit
end
spreadsheet = Dreader::Engine.open_spreadsheet (hash[:filename])
sheet = spreadsheet.sheet(hash[:sheet] || 0)
@table = Array.new
@errors = Array.new
first_row = hash[:first_row] || 1
last_row = hash[:last_row] || sheet.last_row
(first_row..last_row).each do |row_number|
r = Hash.new
@colspec.each_with_index do |colspec, index|
cell = sheet.cell(row_number, colspec[:colref])
colname = colspec[:name]
r[colname] = Hash.new
r[colname][:row_number] = row_number
r[colname][:col_number] = colspec[:colref]
begin
r[colname][:value] = value = colspec[:process] ? colspec[:process].call(cell) : cell
rescue => e
puts "dreader error at #{__callee__}: 'process' specification for :#{colname} raised an exception at row #{row_number} (col #{index + 1}, value: #{cell})"
raise e
end
begin
| ruby | {
"resource": ""
} |
q27361 | Omelette.Util.backtrace_lineno_for_config | test | def backtrace_lineno_for_config(file_path, exception)
# For a SyntaxError, we really need to grep it from the
# exception message, it really appears to be nowhere else. Ugh.
if exception.kind_of? SyntaxError
if m = /:(\d+):/.match(exception.message)
return m[1].to_i
end
end
# Otherwise we try to fish it out of the backtrace, first
# line matching the config file path.
# exception.backtrace_locations exists in MRI 2.1+, which makes
# our task a lot easier. But not yet in JRuby 1.7.x, so we got to
# handle the old way of having to parse the strings in backtrace too.
if (exception.respond_to?(:backtrace_locations) &&
exception.backtrace_locations &&
exception.backtrace_locations.length > 0)
| ruby | {
"resource": ""
} |
q27362 | Omelette.Util.backtrace_from_config | test | def backtrace_from_config(file_path, exception)
filtered_trace = []
found = false
# MRI 2.1+ has exception.backtrace_locations which makes
# this a lot easier, but JRuby 1.7.x doesn't yet, so we
# need to do it both ways.
if (exception.respond_to?(:backtrace_locations) &&
exception.backtrace_locations &&
| ruby | {
"resource": ""
} |
q27363 | Omelette.Util.drain_queue | test | def drain_queue(queue)
result = []
queue_size = queue.size
begin
queue_size.times do
result | ruby | {
"resource": ""
} |
q27364 | SentenceBuilder.Builder.get_hash | test | def get_hash(params = {}, sorted = true)
| ruby | {
"resource": ""
} |
q27365 | SentenceBuilder.Builder.get_sentence | test | def get_sentence(params = {}, sorted = true, separator = ' ')
build_sentence_from_hash(get_hash(params, | ruby | {
"resource": ""
} |
q27366 | SentenceBuilder.Builder.get_nodes | test | def get_nodes(sorted = true)
SentenceBuilder::Helper.to_boolean(sorted) | ruby | {
"resource": ""
} |
q27367 | SentenceBuilder.Builder.build_sentence_from_hash | test | def build_sentence_from_hash(nodes)
result = []
nodes.each do |node|
# This node does not appear in params
if node[:current_value].nil?
| ruby | {
"resource": ""
} |
q27368 | Caramelize.WikkaWiki.read_pages | test | def read_pages
sql = "SELECT id, tag, body, time, latest, user, note FROM wikka_pages ORDER BY time;"
results = database.query(sql)
results.each do |row|
titles << row["tag"]
author = authors[row["user"]]
page = Page.new({:id => row["id"],
:title => row["tag"],
:body => row["body"],
:markup => :wikka,
:latest => row["latest"] == "Y",
:time => row["time"],
| ruby | {
"resource": ""
} |
q27369 | Filterable.ClassMethods.filter | test | def filter(params)
results = where(nil)
params.each do |key, value|
| ruby | {
"resource": ""
} |
q27370 | Trimark.Client.sites | test | def sites
response = conn.get("#{base_url}/site", {}, query_headers)
body = JSON.parse(response.body)
body.map { |b| Site.new(b) }
rescue | ruby | {
"resource": ""
} |
q27371 | Trimark.Client.site_query | test | def site_query(*args)
response = conn.get(url_picker(*args), {}, query_headers)
if response.body['SiteId'] || response.body['PointId']
JSON.parse(response.body)
else | ruby | {
"resource": ""
} |
q27372 | CurrencySpy.Walutomat.rate_time | test | def rate_time
regexp = Regexp.new(currency_code)
page.search("//span[@name='pair']").each do |td|
if regexp.match(td.content)
| ruby | {
"resource": ""
} |
q27373 | Logue.Logger.outfile= | test | def outfile= f
io = f.kind_of?(IO) ? f : File.new(f, "w")
| ruby | {
"resource": ""
} |
q27374 | Logue.Logger.log | test | def log msg = "", obj = nil, level: Level::DEBUG, classname: nil, &blk
log_frames msg, | ruby | {
"resource": ""
} |
q27375 | Watir.OptionGroup.options | test | def options
option_hash = {}
my_labels = option_names
my_inputs = option_fields
my_labels.count.times do |index|
| ruby | {
"resource": ""
} |
q27376 | Watir.OptionGroup.selected_options | test | def selected_options
selected = []
my_labels = option_names
inputs.each_with_index do |field, index|
| ruby | {
"resource": ""
} |
q27377 | ActionCableNotifications.Channel.transmit_packet | test | def transmit_packet(packet, options={})
# Default options
options = {
cache: false
}.merge(options)
packet = packet.as_json.deep_symbolize_keys
| ruby | {
"resource": ""
} |
q27378 | RBeautify.BlockStart.strict_ancestor_of? | test | def strict_ancestor_of?(block_start)
block_start && block_start.parent && (self == block_start.parent | ruby | {
"resource": ""
} |
q27379 | BuiltInData.ClassMethods.built_in_object_ids | test | def built_in_object_ids
@built_in_object_ids ||= Hash.new do |hash, key|
| ruby | {
"resource": ""
} |
q27380 | Clacks.Command.daemonize | test | def daemonize(safe = true)
$stdin.reopen '/dev/null'
# Fork and have the parent exit.
# This makes the shell or boot script think the command is done.
# Also, the child process is guaranteed not to be a process group
# leader (a prerequisite for setsid next)
exit if fork
# Call setsid to create a new session. This does three things:
# - The process becomes a session leader of a new session
# - The process becomes the process group leader of a new process group
# - The process has no controlling terminal
Process.setsid
# Fork again and have the parent exit.
# This guarantes that | ruby | {
"resource": ""
} |
q27381 | Clacks.Command.reopen_io | test | def reopen_io(io, path)
io.reopen(::File.open(path, "ab")) if | ruby | {
"resource": ""
} |
q27382 | Clacks.Command.running? | test | def running?(path)
wpid = ::File.read(path).to_i
return if wpid <= 0
Process.kill(0, wpid)
wpid
| ruby | {
"resource": ""
} |
q27383 | Clacks.Command.write_pid | test | def write_pid(pid)
::File.open(pid, 'w') { |f| f.write("#{Process.pid}") }
at_exit { | ruby | {
"resource": ""
} |
q27384 | Mead.Identifier.parse_mead | test | def parse_mead(*args)
parts = @mead.split('-')
args.each_with_index do |field, i|
| ruby | {
"resource": ""
} |
q27385 | Mixml.Tool.load | test | def load(*file_names)
file_names.flatten.each do |file_name|
xml = File.open(file_name, 'r') do |file|
Nokogiri::XML(file) do |config|
if @pretty then
config.default_xml.noblanks
| ruby | {
"resource": ""
} |
q27386 | Mixml.Tool.save_all | test | def save_all
output_all do |document, options|
File.open(document.name, 'w') do |file|
| ruby | {
"resource": ""
} |
q27387 | Mixml.Tool.print_all | test | def print_all
output_all do |document, options|
if @documents.size > 1 then
puts '-' * document.name.length
puts document.name
| ruby | {
"resource": ""
} |
q27388 | Mixml.Tool.work | test | def work(*file_names, &block)
remove_all
file_names.each do |file_name|
load(file_name)
if not block.nil? then
| ruby | {
"resource": ""
} |
q27389 | Mixml.Tool.xpath | test | def xpath(*paths, &block)
nodesets = []
process do |xml|
nodesets << xml.xpath(*paths)
end
selection = Selection.new(nodesets)
| ruby | {
"resource": ""
} |
q27390 | Mixml.Tool.css | test | def css(*selectors, &block)
nodesets = []
process do |xml|
nodesets << xml.css(*selectors)
end
selection = Selection.new(nodesets)
| ruby | {
"resource": ""
} |
q27391 | Mixml.Tool.execute | test | def execute(program = nil, &block)
if not program.nil? then
instance_eval(program)
| ruby | {
"resource": ""
} |
q27392 | Mixml.Tool.with_nodes | test | def with_nodes(selection)
selection.nodesets.each do |nodeset|
nodeset.each do |node|
| ruby | {
"resource": ""
} |
q27393 | TagFormatter.Formatter.tagify | test | def tagify input
output = input.dup
raise StandardError, "@tags is empty!" if @tags.empty? #improve on this
| ruby | {
"resource": ""
} |
q27394 | Watir.Container.option_group | test | def option_group(*args)
selector = if args.first.respond_to?(:elements)
args.first
else
| ruby | {
"resource": ""
} |
q27395 | Caramelize::CLI.CreateCommand.execute | test | def execute(args)
# create dummy config file
target_file = @config_file.nil? ? "caramel.rb" : @config_file
FileUtils.cp(File.dirname(__FILE__) +"/../caramel.rb", target_file)
if | ruby | {
"resource": ""
} |
q27396 | OscMacheteRails.Workflow.has_machete_workflow_of | test | def has_machete_workflow_of(jobs_active_record_relation_symbol)
# yes, this is magic mimicked from http://guides.rubyonrails.org/plugins.html
# and http://yehudakatz.com/2009/11/12/better-ruby-idioms/
cattr_accessor :jobs_active_record_relation_symbol
self.jobs_active_record_relation_symbol = jobs_active_record_relation_symbol
# separate modules to group common methods for readability purposes
# both builder methods and status methods need the jobs relation | ruby | {
"resource": ""
} |
q27397 | Qwirk.Task.check_retry | test | def check_retry
if @finished_publishing && @pending_hash.empty? && @exception_count > 0 && (@retry || @auto_retry)
# If we're just doing auto_retry but nothing succeeded last time, then don't run again
return if !@retry && @auto_retry && @exception_count == @exceptions_per_run.last
Qwirk.logger.info "#{self}: Retrying exception records, exception count = #{@exception_count}"
@exceptions_per_run << @exception_count
@exception_count = 0
@finished_publishing = false
@fail_thread = Thread.new(@exceptions_per_run.last) do |count|
begin
java.lang.Thread.current_thread.name = "Qwirk fail task: #{task_id}"
while !@stopped && (count > 0) && | ruby | {
"resource": ""
} |
q27398 | Mixml.Application.run | test | def run
program :name, 'mixml'
program :version, Mixml::VERSION
program :description, 'XML helper tool'
$tool = Mixml::Tool.new
global_option('-p', '--pretty', 'Pretty print output') do |value|
$tool.pretty = value
end
global_option('-i', '--inplace', 'Replace the processed files with the new files') do |value|
$tool.save = value
$tool.print = !value
end
global_option('-q', '--quiet', 'Do not print nodes') do |value|
$tool.print = !value
end
command :pretty do |c|
c.description = 'Pretty print XML files'
c.action do |args, options|
$tool.pretty = true
$tool.work(args)
end
end
modify_command :write do |c|
| ruby | {
"resource": ""
} |
q27399 | Koi.Command.list | test | def list entities = @db.list
out
entities = entities.is_a?(Fixnum) ? @db.list[0...entities] : entities
entities.reject {|e| e[:status] == :removed }.each_with_index do |e, i|
out " [#{i}]".blue +
"#{e.sticky?? " + ".bold : " "}" +
e[:title].underline +
" #{e[:tags].join(' ')}".cyan
| ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.