_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q26000 | Turntabler.Room.sticker_placements= | validation | def sticker_placements=(user_placements)
user_placements.each do |user_id, placements|
listener(user_id).attributes = {'placements' => placements}
end
end | ruby | {
"resource": ""
} |
q26001 | Turntabler.Song.skip | validation | def skip
assert_current_song
api('room.stop_song', :songid => id, :djid => played_by.id, :roomid => room.id, :section => room.section)
true
end | ruby | {
"resource": ""
} |
q26002 | Turntabler.Song.vote | validation | def vote(direction = :up)
assert_current_song
api('room.vote',
:roomid => room.id,
:section => room.section,
:val => direction,
:songid => id,
:vh => digest("#{room.id}#{direction}#{id}"),
:th => digest(rand),
:ph => digest(rand)
)
true
end | ruby | {
"resource": ""
} |
q26003 | Turntabler.Song.snag | validation | def snag
assert_current_song
sh = digest(rand)
api('snag.add',
:djid => room.current_dj.id,
:songid => id,
:roomid => room.id,
:section => room.section,
:site => 'queue',
:location => 'board',
:in_queue => 'false',
:blocked => 'false',
:vh => digest([client.user.id, room.current_dj.id, id, room.id, 'queue', 'board', 'false', 'false', sh] * '/'),
:sh => sh,
:fh => digest(rand)
)
true
end | ruby | {
"resource": ""
} |
q26004 | Turntabler.Song.add | validation | def add(options = {})
assert_valid_keys(options, :playlist, :index)
options = {:playlist => playlist.id, :index => 0}.merge(options)
# Create a copy of the song so that the playlist can get set properly
song = dup
song.attributes = {:playlist => options[:playlist]}
playlist, index = song.playlist, options[:index]
api('playlist.add', :playlist_name => playlist.id, :song_dict => {:fileid => id}, :index => index)
playlist.songs.insert(index, song) if playlist.loaded?
true
end | ruby | {
"resource": ""
} |
q26005 | Turntabler.Song.move | validation | def move(to_index)
api('playlist.reorder', :playlist_name => playlist.id, :index_from => index, :index_to => to_index)
playlist.songs.insert(to_index, playlist.songs.delete(self))
true
end | ruby | {
"resource": ""
} |
q26006 | CaTissue.StorageTypeHolder.add_child_type | validation | def add_child_type(type)
case type
when CaTissue::StorageType then add_storage_type(type)
when CaTissue::SpecimenArrayType then add_specimen_array_type(type)
when String then add_specimen_class(type)
else raise ArgumentError.new("Storage type child not supported - #{type}")
end
self
end | ruby | {
"resource": ""
} |
q26007 | CaTissue.StorageTypeHolder.copy_child_types | validation | def copy_child_types(other)
child_storage_types.merge!(other.child_storage_types)
child_specimen_array_types.merge!(other.child_specimen_array_types)
child_specimen_classes.merge!(other.child_specimen_classes)
end | ruby | {
"resource": ""
} |
q26008 | Steamd.Cli.generate | validation | def generate
opts = CliOptions.new(options) # options is built by Thor
gen = CodeGenerator.new(opts.input, opts.output)
gen.generate
end | ruby | {
"resource": ""
} |
q26009 | Steamd.Parser.load! | validation | def load!
return if loaded?
Treetop.load("#{Steamd.grammar_dir}/shared.treetop")
Dir.glob("#{Steamd.grammar_dir}/*.treetop") do |file|
Treetop.load(file)
end
@parser = SteamdParser.new
true
end | ruby | {
"resource": ""
} |
q26010 | Steamd.Parser.parse | validation | def parse(io)
io.rewind
raise NotLoadedError, 'load before parsing (#load!)' if @parser.nil?
data = strip_comments_and_obsolete_tags!(io)
@tree = @parser.parse(data)
raise_parser_error! if @tree.nil?
true
end | ruby | {
"resource": ""
} |
q26011 | Steamd.Parser.imports | validation | def imports
raise StreamNotParsed, 'you must parse first' if @tree.nil?
imports = statements.select do |node|
node.is_a?(ImportStatement)
end
imports.map(&:to_hash)
end | ruby | {
"resource": ""
} |
q26012 | Steamd.Parser.classes | validation | def classes
raise StreamNotParsed, 'you must parse first' if @tree.nil?
classes = statements.select do |node|
node.is_a?(ClassStatement)
end
classes.map(&:to_hash)
end | ruby | {
"resource": ""
} |
q26013 | Steamd.Parser.enums | validation | def enums
raise StreamNotParsed, 'you must parse first' if @tree.nil?
enums = statements.select do |node|
node.is_a?(EnumStatement)
end
enums.map(&:to_hash)
end | ruby | {
"resource": ""
} |
q26014 | MiniAether.XmlParser.pull_to_start | validation | def pull_to_start(name)
loop do
res = pull
raise NotFoundError if res.event_type == :end_document
next if res.start_element? && res[0] == name.to_s
end
end | ruby | {
"resource": ""
} |
q26015 | MiniAether.XmlParser.pull_text_until_end | validation | def pull_text_until_end
texts = []
loop do
res = pull
break unless res.text?
texts << res[0]
end
texts.join
end | ruby | {
"resource": ""
} |
q26016 | Comparison.Presenter.dom_classes | validation | def dom_classes
if positive?
t 'comparison.dom_classes.positive',
default: %i[comparison.classes.positive]
elsif negative?
t 'comparison.dom_classes.negative',
default: %i[comparison.classes.negative]
else
t 'comparison.dom_classes.nochange',
default: %i[comparison.classes.nochange]
end
end | ruby | {
"resource": ""
} |
q26017 | Sycsvpro.ColumnTypeFilter.process | validation | def process(object, options={})
filtered = super(object, options)
return nil if filtered.nil?
values = filtered.split(';')
values.each_with_index do |value, index|
if types[index] == 'n'
if value =~ /\./
number_value = value.to_f
else
number_value = value.to_i
end
values[index] = number_value
elsif types[index] == 'd'
if value.strip.empty?
date = Date.strptime('9999-9-9', '%Y-%m-%d')
else
begin
date = Date.strptime(value, date_format)
rescue
puts "Error #{value}, #{index}"
end
end
values[index] = date
end
end
values
end | ruby | {
"resource": ""
} |
q26018 | Blower.Logger.log | validation | def log (level, message, quiet: false, &block)
if !quiet && (LEVELS.index(level) >= LEVELS.index(Logger.level))
synchronize do
message = message.to_s.colorize(COLORS[level]) if level
message.split("\n").each do |line|
STDERR.puts " " * Logger.indent + @prefix + line
end
end
with_indent(&block) if block
elsif block
block.()
end
end | ruby | {
"resource": ""
} |
q26019 | CaTissue.User.role_id= | validation | def role_id=(value)
# value as an integer (nil is zero)
value_i = value.to_i
# set the Bug #66 work-around i.v.
@role_id = value_i.zero? ? nil : value_i
# value as a String (if non-nil)
value_s = @role_id.to_s if @role_id
# call Java with a String
setRoleId(value_s)
end | ruby | {
"resource": ""
} |
q26020 | SecondHandler.FbGroupPost.get_content | validation | def get_content (&func)
data = Array.new
@feed.to_a.each do |single_post|
begin
if func.nil?
data << clean_post_content(single_post, &@message_parser)
else
data << clean_post_content(single_post, &func)
end
rescue
end
end
data
end | ruby | {
"resource": ""
} |
q26021 | CaTissue.ControlledValueFinder.controlled_value | validation | def controlled_value(value)
return if value.blank?
ControlledValues.instance.find(@attribute, value) or
raise ControlledValueError.new("#{@attribute} value '#{value}' is not a recognized controlled value.")
end | ruby | {
"resource": ""
} |
q26022 | Cratus.Config.defaults | validation | def defaults
{
group_dn_attribute: :cn,
group_member_attribute: :member,
group_description_attribute: :description,
group_objectclass: :group,
group_basedn: 'ou=groups,dc=example,dc=com',
group_memberof_attribute: :memberOf,
user_dn_attribute: :samaccountname,
user_objectclass: :user,
user_basedn: 'ou=users,dc=example,dc=com',
user_account_control_attribute: :userAccountControl,
user_department_attribute: :department,
user_lockout_attribute: :lockouttime,
user_mail_attribute: :mail,
user_displayname_attribute: :displayName,
user_memberof_attribute: :memberOf,
host: 'ldap.example.com', port: 389,
basedn: 'dc=example,dc=com',
username: 'username',
password: 'p@assedWard!',
include_distribution_groups: true
}
end | ruby | {
"resource": ""
} |
q26023 | Mako.SubscriptionListWriter.append_and_write | validation | def append_and_write
contents = append_and_render
File.open(destination, 'w+', encoding: 'utf-8') do |f|
f.write(contents)
end
end | ruby | {
"resource": ""
} |
q26024 | Mako.SubscriptionListWriter.render_opml | validation | def render_opml(list)
document = Nokogiri::XML(list.load_list)
feeds.each do |feed_url|
node = "<outline xmlUrl='#{feed_url}' />\n"
document.xpath("//outline[@text='Subscriptions']").last.add_child node
end
formatted_no_decl = Nokogiri::XML::Node::SaveOptions::FORMAT +
Nokogiri::XML::Node::SaveOptions::NO_DECLARATION
document.to_xml(encoding: 'utf-8', save_with: formatted_no_decl)
end | ruby | {
"resource": ""
} |
q26025 | Sycsvpro.Calculator.execute | validation | def execute
processed_header = false
File.open(outfile, 'w') do |out|
File.open(infile).each_with_index do |line, index|
next if line.chomp.empty? || unstring(line).chomp.split(';').empty?
unless processed_header
header_row = header.process(line.chomp)
header_row = @write_filter.process(header_row) unless @final_header
out.puts header_row unless header_row.nil? or header_row.empty?
processed_header = true
next
end
next if row_filter.process(line, row: index).nil?
@columns = unstring(line).chomp.split(';')
formulae.each do |col, formula|
@columns[col.to_i] = eval(formula)
end
out.puts @write_filter.process(@columns.join(';'))
@columns.each_with_index do |column, index|
column = 0 unless column.to_s =~ /^[\d\.,]*$/
if @sum_row[index]
@sum_row[index] += to_number column
else
@sum_row[index] = to_number column
end
end if add_sum_row
end
out.puts @write_filter.process(@sum_row.join(';')) if add_sum_row
end
end | ruby | {
"resource": ""
} |
q26026 | Sycsvpro.Calculator.to_date | validation | def to_date(value)
if value.nil? or value.strip.empty?
nil
else
Date.strptime(value, date_format)
end
end | ruby | {
"resource": ""
} |
q26027 | Cratus.Group.add_user | validation | def add_user(user)
raise 'InvalidUser' unless user.respond_to?(:dn)
direct_members = @raw_ldap_data[Cratus.config.group_member_attribute]
return true if direct_members.include?(user.dn)
direct_members << user.dn
Cratus::LDAP.replace_attribute(
dn,
Cratus.config.group_member_attribute,
direct_members.uniq
)
end | ruby | {
"resource": ""
} |
q26028 | CaTissue.Annotator.create_annotation_service | validation | def create_annotation_service(mod, name)
@integrator = Annotation::Integrator.new(mod)
Annotation::AnnotationService.new(@database, name, @integrator)
end | ruby | {
"resource": ""
} |
q26029 | CaTissue.Person.name | validation | def name
middle = middle_name if respond_to?(:middle_name)
Name.new(last_name, first_name, middle) if last_name
end | ruby | {
"resource": ""
} |
q26030 | CaTissue.Person.name= | validation | def name=(value)
value = Name.parse(value) if String === value
# a missing name is equivalent to an empty name for our purposes here
value = Name.new(nil, nil) if value.nil?
unless Name === value then
raise ArgumentError.new("Name argument type invalid; expected <#{Name}>, found <#{value.class}>")
end
self.first_name = value.first
self.last_name = value.last
self.middle_name = value.middle if respond_to?(:middle_name)
end | ruby | {
"resource": ""
} |
q26031 | CaTissue.ControlledValues.find | validation | def find(public_id_or_alias, value, recursive=false)
pid = ControlledValue.standard_public_id(public_id_or_alias)
value_cv_hash = @pid_value_cv_hash[pid]
cv = value_cv_hash[value]
if recursive then
fetch_descendants(cv, value_cv_hash)
end
cv
end | ruby | {
"resource": ""
} |
q26032 | CaTissue.ControlledValues.create | validation | def create(cv)
if cv.public_id.nil? then
raise ArgumentError.new("Controlled value create is missing a public id")
end
if cv.value.nil? then
raise ArgumentError.new("Controlled value create is missing a value")
end
cv.identifier ||= next_id
logger.debug { "Creating controlled value #{cv} in the database..." }
@executor.transact(INSERT_STMT, cv.identifier, cv.parent_identifier, cv.public_id, cv.value)
logger.debug { "Controlled value #{cv.public_id} #{cv.value} created with identifier #{cv.identifier}" }
@pid_value_cv_hash[cv.public_id][cv.value] = cv
end | ruby | {
"resource": ""
} |
q26033 | CaTissue.ControlledValues.delete | validation | def delete(cv)
@executor.transact do |dbh|
sth = dbh.prepare(DELETE_STMT)
delete_recursive(cv, sth)
sth.finish
end
end | ruby | {
"resource": ""
} |
q26034 | CaTissue.ControlledValues.make_controlled_value | validation | def make_controlled_value(value_hash)
cv = ControlledValue.new(value_hash[:value], value_hash[:parent])
cv.identifier = value_hash[:identifier]
cv.public_id = value_hash[:public_id]
cv
end | ruby | {
"resource": ""
} |
q26035 | Blower.Context.with | validation | def with (hash, quiet: false)
old_values = data.values_at(hash.keys)
log.debug "with #{hash}", quiet: quiet do
set hash
yield
end
ensure
hash.keys.each.with_index do |key, i|
@data[key] = old_values[i]
end
end | ruby | {
"resource": ""
} |
q26036 | Blower.Context.on | validation | def on (*hosts, quiet: false)
let :@hosts => hosts.flatten do
log.info "on #{@hosts.map(&:name).join(", ")}", quiet: quiet do
yield
end
end
end | ruby | {
"resource": ""
} |
q26037 | Blower.Context.as | validation | def as (user, quiet: false)
let :@user => user do
log.info "as #{user}", quiet: quiet do
yield
end
end
end | ruby | {
"resource": ""
} |
q26038 | Blower.Context.sh | validation | def sh (command, as: user, on: hosts, quiet: false, once: nil)
self.once once, quiet: quiet do
log.info "sh #{command}", quiet: quiet do
hash_map(hosts) do |host|
host.sh command, as: as, quiet: quiet
end
end
end
end | ruby | {
"resource": ""
} |
q26039 | Blower.Context.cp | validation | def cp (from, to, as: user, on: hosts, quiet: false, once: nil)
self.once once, quiet: quiet do
log.info "cp: #{from} -> #{to}", quiet: quiet do
Dir.chdir File.dirname(file) do
hash_map(hosts) do |host|
host.cp from, to, as: as, quiet: quiet
end
end
end
end
end | ruby | {
"resource": ""
} |
q26040 | Blower.Context.read | validation | def read (filename, as: user, on: hosts, quiet: false)
log.info "read: #{filename}", quiet: quiet do
hash_map(hosts) do |host|
host.read filename, as: as
end
end
end | ruby | {
"resource": ""
} |
q26041 | Blower.Context.write | validation | def write (string, to, as: user, on: hosts, quiet: false, once: nil)
self.once once, quiet: quiet do
log.info "write: #{string.bytesize} bytes -> #{to}", quiet: quiet do
hash_map(hosts) do |host|
host.write string, to, as: as, quiet: quiet
end
end
end
end | ruby | {
"resource": ""
} |
q26042 | Blower.Context.ping | validation | def ping (on: hosts, quiet: false)
log.info "ping", quiet: quiet do
hash_map(hosts) do |host|
host.ping
end
end
end | ruby | {
"resource": ""
} |
q26043 | Blower.Context.once | validation | def once (key, store: "/var/cache/blower.json", quiet: false)
return yield unless key
log.info "once: #{key}", quiet: quiet do
hash_map(hosts) do |host|
done = begin
JSON.parse(host.read(store, quiet: true))
rescue => e
{}
end
unless done[key]
on [host] do
yield
end
done[key] = true
host.write(done.to_json, store, quiet: true)
end
end
end
end | ruby | {
"resource": ""
} |
q26044 | Turntabler.AuthorizedUser.update | validation | def update(attributes = {})
assert_valid_keys(attributes, :name, :status, :laptop_name, :twitter_id, :facebook_url, :website, :about, :top_artists, :hangout)
# Update status
status = attributes.delete(:status)
update_status(status) if status
# Update laptop
laptop_name = attributes.delete(:laptop_name)
update_laptop(laptop_name) if laptop_name
# Update profile with remaining data
update_profile(attributes) if attributes.any?
true
end | ruby | {
"resource": ""
} |
q26045 | Turntabler.AuthorizedUser.buddies | validation | def buddies
data = api('user.get_buddies')
data['buddies'].map {|id| User.new(client, :_id => id)}
end | ruby | {
"resource": ""
} |
q26046 | Turntabler.AuthorizedUser.fan_of | validation | def fan_of
data = api('user.get_fan_of')
data['fanof'].map {|id| User.new(client, :_id => id)}
end | ruby | {
"resource": ""
} |
q26047 | Turntabler.AuthorizedUser.fans | validation | def fans
data = api('user.get_fans')
data['fans'].map {|id| User.new(client, :_id => id)}
end | ruby | {
"resource": ""
} |
q26048 | Turntabler.AuthorizedUser.stickers_purchased | validation | def stickers_purchased
data = api('sticker.get_purchased_stickers')
data['stickers'].map {|sticker_id| Sticker.new(client, :_id => sticker_id)}
end | ruby | {
"resource": ""
} |
q26049 | Turntabler.AuthorizedUser.blocks | validation | def blocks
data = api('block.list_all')
data['blocks'].map {|attrs| User.new(client, attrs['block']['blocked'])}
end | ruby | {
"resource": ""
} |
q26050 | Turntabler.AuthorizedUser.update_profile | validation | def update_profile(attributes = {})
assert_valid_keys(attributes, :name, :twitter_id, :facebook_url, :website, :about, :top_artists, :hangout)
# Convert attribute names over to their Turntable equivalent
{:twitter_id => :twitter, :facebook_url => :facebook, :top_artists => :topartists}.each do |from, to|
attributes[to] = attributes.delete(from) if attributes[from]
end
api('user.modify_profile', attributes)
self.attributes = attributes
true
end | ruby | {
"resource": ""
} |
q26051 | Turntabler.AuthorizedUser.update_laptop | validation | def update_laptop(name)
assert_valid_values(name, *%w(mac pc linux chrome iphone cake intel android))
api('user.modify', :laptop => name)
self.attributes = {'laptop' => name}
true
end | ruby | {
"resource": ""
} |
q26052 | Turntabler.AuthorizedUser.update_status | validation | def update_status(status = self.status)
assert_valid_values(status, *%w(available unavailable away))
now = Time.now.to_i
result = api('presence.update', :status => status)
client.reset_keepalive(result['interval'])
client.clock_delta = ((now + Time.now.to_i) / 2 - result['now']).round
self.attributes = {'status' => status}
true
end | ruby | {
"resource": ""
} |
q26053 | Plasper.Plasper.<< | validation | def <<(input)
if input.index(/\s+/).nil?
word = normalize_word input
self.word = word unless word == ''
elsif input.scan(SENTENCE_DELIMITER).length < 2
self.sentence = input.gsub(SENTENCE_DELIMITER, '')
else
self.passage = input
end
end | ruby | {
"resource": ""
} |
q26054 | Plasper.Plasper.weighted | validation | def weighted(type, group)
if @weights[type].has_key?(group)
selector = WeightedSelect::Selector.new @weights[type][group]
selector.select
end
end | ruby | {
"resource": ""
} |
q26055 | Turntabler.Handler.run | validation | def run(event)
if conditions_match?(event.data)
# Run the block for each individual result
event.results.each do |args|
begin
@block.call(*args)
rescue StandardError => ex
logger.error(([ex.message] + ex.backtrace) * "\n")
end
end
true
else
false
end
end | ruby | {
"resource": ""
} |
q26056 | Turntabler.Handler.conditions_match? | validation | def conditions_match?(data)
if conditions
conditions.all? {|(key, value)| data[key] == value}
else
true
end
end | ruby | {
"resource": ""
} |
q26057 | CaTissue.Container.add | validation | def add(storable, *coordinate)
validate_type(storable)
loc = create_location(coordinate)
pos = storable.position || storable.position_class.new
pos.location = loc
pos.occupant = storable
pos.holder = self
logger.debug { "Added #{storable.qp} to #{qp} at #{loc.coordinate}." }
update_full_flag
self
end | ruby | {
"resource": ""
} |
q26058 | CaTissue.Container.copy_container_type_capacity | validation | def copy_container_type_capacity
return unless container_type and container_type.capacity
self.capacity = cpc = container_type.capacity.copy(:rows, :columns)
logger.debug { "Initialized #{qp} capacity from #{container_type.qp} capacity #{cpc}." }
update_full_flag
cpc
end | ruby | {
"resource": ""
} |
q26059 | Turntabler.Preferences.load | validation | def load
data = api('user.get_prefs')
self.attributes = data['result'].inject({}) do |result, (preference, value, *)|
result[preference] = value
result
end
super
end | ruby | {
"resource": ""
} |
q26060 | Sycsvpro.Extractor.execute | validation | def execute
File.open(out_file, 'w') do |o|
File.new(in_file, 'r').each_with_index do |line, index|
extraction = col_filter.process(row_filter.process(line.chomp, row: index))
o.puts extraction unless extraction.nil?
end
end
end | ruby | {
"resource": ""
} |
q26061 | Sightstone.TeamModule.teams | validation | def teams(summoner, optional={})
region = optional[:region] || @sightstone.region
id = if summoner.is_a? Summoner
summoner.id
else
summoner
end
uri = "https://prod.api.pvp.net/api/lol/#{region}/v2.2/team/by-summoner/#{id}"
response = _get_api_response(uri)
_parse_response(response) { |resp|
data = JSON.parse(resp)
teams = []
data.each do |team|
teams << Team.new(team)
end
if block_given?
yield teams
else
return teams
end
}
end | ruby | {
"resource": ""
} |
q26062 | Plans.Publish.get_doctype | validation | def get_doctype(path)
doc_type = nil
begin
metadata = YAML.load_file(path + 'template.yml')
doc_type = metadata['type']
if doc_type.nil?
say 'Type value not found. Check template.yml in the document directory', :red
say 'Make sure there is an entry `type: DOC_TYPE` in the file.'
say " #{path}"
raise_error('DOC_TYPE not found in template.yml')
end
rescue Errno::ENOENT # File not found
say 'No template.yml found in the document directory. Did you forget to add it?', :red
say 'Did you run the command in the directory where the document is located?'
say " #{path}"
raise_error('template.yml not found')
end
return doc_type
end | ruby | {
"resource": ""
} |
q26063 | Sycsvpro.Allocator.execute | validation | def execute
allocation = {}
File.open(infile).each_with_index do |line, index|
row = row_filter.process(line, row: index)
next if row.nil? or row.empty?
key = key_filter.process(row)
allocation[key] = [] if allocation[key].nil?
allocation[key] << col_filter.process(row).split(';')
end
File.open(outfile, 'w') do |out|
allocation.each do |key, values|
out.puts "#{key};#{values.flatten.uniq.sort.join(';')}"
end
end
end | ruby | {
"resource": ""
} |
q26064 | BaseDataTypes.Vector.span_to | validation | def span_to(spanner)
Vector.new((@x - spanner.x).abs, (@y - spanner.y).abs)
end | ruby | {
"resource": ""
} |
q26065 | Mako.Core.build | validation | def build
log_configuration_information
if subscription_list.empty?
Mako.logger.warn 'No feeds were found in your subscriptions file. Please add feeds and try again.'
return
end
log_time do
request_and_build_feeds
renderers.each do |renderer|
renderer_instance = renderer.new(bound: self)
writer.new(renderer: renderer_instance,
destination: File.expand_path(renderer_instance.file_path, Mako.config.destination)).write
end
end
end | ruby | {
"resource": ""
} |
q26066 | Mako.Core.log_configuration_information | validation | def log_configuration_information
Mako.logger.info "Configuration File: #{Mako.config.config_file}"
Mako.logger.info "Theme: #{Mako.config.theme}"
Mako.logger.info "Destination: #{Mako.config.destination}"
end | ruby | {
"resource": ""
} |
q26067 | Mako.Core.log_time | validation | def log_time
Mako.logger.info 'Generating...'
start_time = Time.now.to_f
yield
generation_time = Time.now.to_f - start_time
Mako.logger.info "done in #{generation_time} seconds"
end | ruby | {
"resource": ""
} |
q26068 | Sycsvpro.SpreadSheetBuilder.execute | validation | def execute
result = eval(operation)
if outfile
if result.is_a?(SpreadSheet)
result.write(outfile)
else
puts
puts "Warning: Result is no spread sheet and not written to file!"
puts " To view the result use -p flag" unless print
end
end
if print
puts
puts "Operation"
puts "---------"
operation.split(';').each { |o| puts o }
puts
puts "Result"
puts "------"
if result.nil? || result.empty?
puts result.inspect
else
puts result
end
puts
end
end | ruby | {
"resource": ""
} |
q26069 | Sycsvpro.SpreadSheetBuilder.create_operands | validation | def create_operands(opts)
files = opts[:files].split(',')
rlabels = opts[:rlabels].split(',').collect { |l| l.upcase == "TRUE" }
clabels = opts[:clabels].split(',').collect { |l| l.upcase == "TRUE" }
operands = {}
opts[:aliases].split(',').each_with_index do |a,i|
operands[a] = SpreadSheet.new(file: files[i], ds: opts[:ds],
equalize: opts[:equalize],
r: rlabels[i], c: clabels[i])
end
operands
end | ruby | {
"resource": ""
} |
q26070 | Turntabler.Connection.publish | validation | def publish(params)
params[:msgid] = message_id = next_message_id
params = @default_params.merge(params)
logger.debug "Message sent: #{params.inspect}"
if HTTP_APIS.include?(params[:api])
publish_to_http(params)
else
publish_to_socket(params)
end
# Add timeout handler
EventMachine.add_timer(@timeout) do
dispatch('msgid' => message_id, 'command' => 'response_received', 'error' => 'timed out')
end if @timeout
message_id
end | ruby | {
"resource": ""
} |
q26071 | Turntabler.Connection.publish_to_socket | validation | def publish_to_socket(params)
message = params.is_a?(String) ? params : params.to_json
data = "~m~#{message.length}~m~#{message}"
@socket.send(data)
end | ruby | {
"resource": ""
} |
q26072 | Turntabler.Connection.publish_to_http | validation | def publish_to_http(params)
api = params.delete(:api)
message_id = params[:msgid]
http = EventMachine::HttpRequest.new("http://turntable.fm/api/#{api}").get(:query => params)
if http.response_header.status == 200
# Command executed properly: parse the results
success, data = JSON.parse(http.response)
data = {'result' => data} unless data.is_a?(Hash)
message = data.merge('success' => success)
else
# Command failed to run
message = {'success' => false, 'error' => http.error}
end
message.merge!('msgid' => message_id)
# Run the message handler
event = Faye::WebSocket::API::Event.new('message', :data => "~m~#{Time.now.to_i}~m~#{JSON.generate(message)}")
on_message(event)
end | ruby | {
"resource": ""
} |
q26073 | Turntabler.Connection.on_message | validation | def on_message(event)
data = event.data
response = data.match(/~m~\d*~m~(.*)/)[1]
message =
case response
when /no_session/
{'command' => 'no_session'}
when /(~h~[0-9]+)/
# Send the heartbeat command back to the server
publish_to_socket($1)
{'command' => 'heartbeat'}
else
JSON.parse(response)
end
message['command'] = 'response_received' if message['msgid']
logger.debug "Message received: #{message.inspect}"
dispatch(message)
end | ruby | {
"resource": ""
} |
q26074 | CaTissue.ContainerType.add_defaults_local | validation | def add_defaults_local
super
self.capacity ||= Capacity.new.add_defaults
self.row_label ||= capacity.rows && capacity.rows > 0 ? 'Row' : 'Unused'
self.column_label ||= capacity.columns && capacity.columns > 0 ? 'Column' : 'Unused'
end | ruby | {
"resource": ""
} |
q26075 | Blower.Host.ping | validation | def ping ()
log.debug "Pinging"
Timeout.timeout(1) do
TCPSocket.new(address, 22).close
end
true
rescue Timeout::Error, Errno::ECONNREFUSED
fail "Failed to ping #{self}"
end | ruby | {
"resource": ""
} |
q26076 | Blower.Host.cp | validation | def cp (froms, to, as: nil, quiet: false)
as ||= @user
output = ""
synchronize do
[froms].flatten.each do |from|
if from.is_a?(String)
to += "/" if to[-1] != "/" && from.is_a?(Array)
command = ["rsync", "-e", ssh_command, "-r"]
command += [*from, "#{as}@#{@address}:#{to}"]
log.trace command.shelljoin, quiet: quiet
IO.popen(command, in: :close, err: %i(child out)) do |io|
until io.eof?
begin
output << io.read_nonblock(100)
rescue IO::WaitReadable
IO.select([io])
retry
end
end
io.close
if !$?.success?
log.fatal "exit status #{$?.exitstatus}: #{command}", quiet: quiet
log.fatal output, quiet: quiet
fail "failed to copy files"
end
end
elsif from.respond_to?(:read)
cmd = "echo #{Base64.strict_encode64(from.read).shellescape} | base64 -d > #{to.shellescape}"
sh cmd, quiet: quiet
else
fail "Don't know how to copy a #{from.class}: #{from}"
end
end
end
true
end | ruby | {
"resource": ""
} |
q26077 | Blower.Host.write | validation | def write (string, to, as: nil, quiet: false)
cp StringIO.new(string), to, as: as, quiet: quiet
end | ruby | {
"resource": ""
} |
q26078 | Blower.Host.read | validation | def read (filename, as: nil, quiet: false)
Base64.decode64 sh("cat #{filename.shellescape} | base64", as: as, quiet: quiet)
end | ruby | {
"resource": ""
} |
q26079 | Blower.Host.sh | validation | def sh (command, as: nil, quiet: false)
as ||= @user
output = ""
synchronize do
log.debug "sh #{command}", quiet: quiet
result = nil
ch = ssh(as).open_channel do |ch|
ch.request_pty do |ch, success|
"failed to acquire pty" unless success
ch.exec(command) do |_, success|
fail "failed to execute command" unless success
ch.on_data do |_, data|
log.trace "received #{data.bytesize} bytes stdout", quiet: quiet
output << data
end
ch.on_extended_data do |_, _, data|
log.trace "received #{data.bytesize} bytes stderr", quiet: quiet
output << data.colorize(:red)
end
ch.on_request("exit-status") do |_, data|
result = data.read_long
log.trace "received exit-status #{result}", quiet: quiet
end
end
end
end
ch.wait
fail FailedCommand, output if result != 0
output
end
end | ruby | {
"resource": ""
} |
q26080 | CaTissue.SpecimenArrayType.can_hold_child? | validation | def can_hold_child?(storable)
Specimen === storable and storable.specimen_class == specimen_class and specimen_types.include?(storable.specimen_type)
end | ruby | {
"resource": ""
} |
q26081 | Sycsvpro.Aggregator.process_aggregation | validation | def process_aggregation
File.new(infile).each_with_index do |line, index|
result = col_filter.process(row_filter.process(line.chomp, row: index))
unless result.nil? or result.empty?
if heading.empty? and not headerless
heading << result.split(';')
next
else
@sum_col = [result.split(';').size, sum_col].max
end
key_values[result] += 1
sums[sum_col_title] += 1
end
end
heading.flatten!
heading[sum_col] = sum_col_title
end | ruby | {
"resource": ""
} |
q26082 | Sycsvpro.Aggregator.write_result | validation | def write_result
sum_line = [sum_row_title]
(heading.size - 2).times { sum_line << "" }
sum_line << sums[sum_col_title]
row = 0;
File.open(outfile, 'w') do |out|
out.puts sum_line.join(';') if row == sum_row ; row += 1
out.puts heading.join(';')
key_values.each do |k, v|
out.puts sum_line.join(';') if row == sum_row ; row += 1
out.puts [k, v].join(';')
end
end
end | ruby | {
"resource": ""
} |
q26083 | Sycsvpro.Aggregator.init_sum_scheme | validation | def init_sum_scheme(sum_scheme)
row_scheme, col_scheme = sum_scheme.split(',') unless sum_scheme.nil?
unless row_scheme.nil?
@sum_row_title, @sum_row = row_scheme.split(':') unless row_scheme.empty?
end
@sum_row.nil? ? @sum_row = 0 : @sum_row = @sum_row.to_i
@sum_row_title = 'Total' if @sum_row_title.nil?
col_scheme.nil? ? @sum_col_title = 'Total' : @sum_col_title = col_scheme
@sum_col = 0
end | ruby | {
"resource": ""
} |
q26084 | Morf::Caster.ClassMethods.attributes | validation | def attributes(&block)
raise ArgumentError, "You should provide block" unless block_given?
attributes = Morf::AttributesParser.parse(&block)
self.class_variable_set(:@@attributes, attributes)
end | ruby | {
"resource": ""
} |
q26085 | MiniAether.ResolverImpl.resolve | validation | def resolve(dep_hashes, repos)
logger.info 'resolving dependencies'
session = MavenRepositorySystemSession.new
local_repo = LocalRepository.new(local_repository_path)
local_manager = @system.newLocalRepositoryManager(local_repo)
session.setLocalRepositoryManager(local_manager)
collect_req = CollectRequest.new
dep_hashes.each do |hash|
dep = Dependency.new new_artifact(hash), 'compile'
collect_req.addDependency dep
logger.debug 'requested {}', dep
end
repos.each do |uri|
repo = RemoteRepository.new(uri.object_id.to_s, 'default', uri)
collect_req.addRepository repo
logger.info 'added repository {}', repo.getUrl
enabled = []
enabled << 'releases' if repo.getPolicy(false).isEnabled
enabled << 'snapshots' if repo.getPolicy(true).isEnabled
logger.debug '{}', enabled.join('+')
end
node = @system.collectDependencies(session, collect_req).getRoot
dependency_req = DependencyRequest.new(node, nil)
@system.resolveDependencies(session, dependency_req)
nlg = PreorderNodeListGenerator.new
node.accept nlg
if logger.isDebugEnabled
total_size = 0
nlg.getArtifacts(false).each do |artifact|
file = artifact.file
size = File.stat(artifact.file.absolute_path).size
total_size += size
logger.debug("Using %0.2f %s" % [size/MiB_PER_BYTE, artifact])
end
logger.debug(' -----')
logger.debug(" %0.2f MiB total" % [total_size/MiB_PER_BYTE])
else
nlg.getArtifacts(false).each do |artifact|
logger.info 'Using {}', artifact
end
end
nlg.getFiles.map{|e| e.to_s }
end | ruby | {
"resource": ""
} |
q26086 | RubyGo.Board.place | validation | def place(stone)
x, y = stone.to_coord
internal_board[y][x] = stone
end | ruby | {
"resource": ""
} |
q26087 | Plasper.Options.parse | validation | def parse(argv)
OptionParser.new do |options|
usage_and_help options
assign_text_file options
assign_weights_file options
assign_output_file options
begin
options.parse argv
rescue OptionParser::ParseError => error
STDERR.puts error.message, "\n", options
exit(-1)
end
end
end | ruby | {
"resource": ""
} |
q26088 | ActiveBugzilla.Service.execute | validation | def execute(command, params)
params[:Bugzilla_login] ||= username
params[:Bugzilla_password] ||= password
self.last_command = command_string(command, params)
xmlrpc_client.call(command, params)
end | ruby | {
"resource": ""
} |
q26089 | Sightstone.LeagueModule.leagues | validation | def leagues(summoner, optional={})
region = optional[:region] || @sightstone.region
id = if summoner.is_a? Summoner
summoner.id
else
summoner
end
uri = "https://prod.api.pvp.net/api/lol/#{region}/v2.3/league/by-summoner/#{id}"
response = _get_api_response(uri)
_parse_response(response) { |resp|
data = JSON.parse(resp)
leagues = []
data.each do |league|
leagues << League.new(league)
end
if block_given?
yield leagues
else
return leagues
end
}
end | ruby | {
"resource": ""
} |
q26090 | Sightstone.LeagueModule.league_entries | validation | def league_entries(summoner, optional={})
region = optional[:region] || @sightstone.region
id = if summoner.is_a? Summoner
summoner.id
else
summoner
end
uri = "https://prod.api.pvp.net/api/lol/#{region}/v2.3/league/by-summoner/#{id}/entry"
response = _get_api_response(uri)
_parse_response(response) { |resp|
data = JSON.parse(resp)
entries = []
data.each do |entry|
entries << LeagueItem.new(entry)
end
if block_given?
yield entries
else
return entries
end
}
end | ruby | {
"resource": ""
} |
q26091 | Turntabler.Sticker.place | validation | def place(top, left, angle)
api('sticker.place', :placement => [:sticker_id => id, :top => top, :left => left, :angle => angle], :is_dj => client.user.dj?, :roomid => room.id, :section => room.section)
true
end | ruby | {
"resource": ""
} |
q26092 | Mako.FeedFinder.find | validation | def find
request_uris.map do |request|
if request[:body].nil?
request[:uri]
else
html = Nokogiri::HTML(request[:body])
potential_feed_uris = html.xpath(XPATHS.detect { |path| !html.xpath(path).empty? })
if potential_feed_uris.empty?
Mako.errors.add_error "Could not find feed for #{request[:uri]}"
next
end
uri_string = potential_feed_uris.first.value
feed_uri = URI.parse(uri_string)
feed_uri.absolutize!(request[:uri])
end
end.compact
end | ruby | {
"resource": ""
} |
q26093 | CaTissue.SpecimenCollectionGroup.collection_status= | validation | def collection_status=(value)
if value == 'Complete' then
specimens.each { |spc| spc.collection_status = 'Collected' if spc.pending? }
end
setCollectionStatus(value)
end | ruby | {
"resource": ""
} |
q26094 | CaTissue.SpecimenCollectionGroup.make_default_consent_tier_statuses | validation | def make_default_consent_tier_statuses
return if registration.nil? or registration.consent_tier_responses.empty?
# the consent tiers
ctses = consent_tier_statuses.map { |cts| cts.consent_tier }
# ensure that there is a CT status for each consent tier
registration.consent_tier_responses.each do |ctr|
ct = ctr.consent_tier
# skip if there is a status for the response tier
next if ctses.include?(ct)
# make a new status
cts = CaTissue::ConsentTierStatus.new(:consent_tier => ct)
cts.add_defaults
consent_tier_statuses << cts
logger.debug { "Made default #{qp} #{cts.qp} for consent tier #{ct.qp}." }
end
end | ruby | {
"resource": ""
} |
q26095 | CaTissue.SpecimenCollectionGroup.default_collection_event | validation | def default_collection_event
return if registration.nil?
pcl = registration.protocol || return
# if no protocol event, then add the default event
pcl.add_defaults if pcl.events.empty?
ev = pcl.sorted_events.first || return
logger.debug { "Default #{qp} collection event is the registration protocol #{pcl.qp} first event #{ev.qp}." }
ev
end | ruby | {
"resource": ""
} |
q26096 | CaTissue.SpecimenCollectionGroup.default_receiver | validation | def default_receiver
cep = collection_event_parameters
cltr = cep.user if cep
return cltr if cltr
cp = collection_protocol || return
rcv = cp.coordinators.first
return rcv if rcv or cp.fetched?
# Try to fetch the CP coordinator
return cp.coordinators.first if cp.find
# CP does not exist; add the CP defaults and retry
cp.add_defaults
cp.coordinators.first
end | ruby | {
"resource": ""
} |
q26097 | CaTissue.Specimen.decrement_derived_quantity | validation | def decrement_derived_quantity(child)
return unless specimen_type == child.specimen_type and child.initial_quantity
if available_quantity.nil? then
raise Jinx::ValidationError.new("Derived specimen has an initial quantity #{child.initial_quantity} but the parent is missing an available quantity")
elsif (available_quantity - child.initial_quantity).abs < 0.00000001 then
# rounding error
self.available_quantity = 0.0
elsif child.initial_quantity <= available_quantity then
self.available_quantity -= child.initial_quantity
else
raise Jinx::ValidationError.new("Derived specimen initial quantity #{child.initial_quantity} exceeds parent available quantity #{available_quantity}")
end
end | ruby | {
"resource": ""
} |
q26098 | CaTissue.Database.update_changed_dependent | validation | def update_changed_dependent(owner, property, dependent, autogenerated)
# Save the changed collectible event parameters directly rather than via a cascade.
if CollectibleEventParameters === dependent then
logger.debug { "Work around a caTissue bug by resaving the collected #{owner} #{dependent} directly rather than via a cascade..." }
update_from_template(dependent)
elsif CaTissue::User === owner and property.attribute == :address then
update_user_address(owner, dependent)
elsif CaTissue::Specimen === owner and CaTissue::Specimen === dependent then
logger.debug { "Work around caTissue bug to update #{dependent} separately after the parent #{owner} update..." }
prepare_specimen_for_update(dependent)
update_from_template(dependent)
logger.debug { "Updated the #{owner} child #{dependent}." }
elsif CaTissue::ConsentTierStatus === dependent then
update_from_template(owner)
else
super
end
end | ruby | {
"resource": ""
} |
q26099 | CaTissue.Database.update_user_address | validation | def update_user_address(user, address)
logger.debug { "Work around caTissue prohibition of #{user} address #{address} update by creating a new address record for a dummy user..." }
address.identifier = nil
perform(:create, address) { create_object(address) }
logger.debug { "Worked around caTissue address update bug by swizzling the #{user} address #{address} identifier." }
perform(:update, user) { update_object(user) }
user
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.