_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q5200
|
Biopsy.Target.method_missing
|
train
|
def method_missing(method, *args, &block)
const_methods = @constructor.class.instance_methods(false)
if const_methods.include? method
return @constructor.send(method, *args, &block)
else
super
end
end
|
ruby
|
{
"resource": ""
}
|
q5201
|
Biopsy.Target.respond_to?
|
train
|
def respond_to?(method, *args, &block)
const_methods = @constructor.class.instance_methods(false)
if const_methods.include? method
true
else
super
end
end
|
ruby
|
{
"resource": ""
}
|
q5202
|
BadFruit.Base.get_movie_info
|
train
|
def get_movie_info(movie_id, action)
url = nil
case action
when "details"
url = "#{MOVIE_DETAIL_BASE_URL}/#{movie_id}.json?apikey=#{@api_key}"
when "reviews"
url = "#{MOVIE_DETAIL_BASE_URL}/#{movie_id}/reviews.json?apikey=#{@api_key}"
when "cast"
url = "#{MOVIE_DETAIL_BASE_URL}/#{movie_id}/cast.json?apikey=#{@api_key}"
when "main"
url = "#{MOVIE_DETAIL_BASE_URL}/#{movie_id}.json?apikey=#{@api_key}"
else
puts "Not a valid action"
return
end
return get(url)
end
|
ruby
|
{
"resource": ""
}
|
q5203
|
BadFruit.Base.get_lists_action
|
train
|
def get_lists_action(action)
url = nil
case action
when "new_releases"
url = "#{LISTS_DETAIL_BASE_URL}/dvds/new_releases.json?apikey=#{@api_key}"
when "opening"
url = "#{LISTS_DETAIL_BASE_URL}/movies/opening.json?apikey=#{@api_key}"
when "upcoming"
url = "#{LISTS_DETAIL_BASE_URL}/movies/upcoming.json?apikey=#{@api_key}"
when "in_theaters"
url = "#{LISTS_DETAIL_BASE_URL}/movies/in_theaters.json?apikey=#{@api_key}"
when "current_releases"
url = "#{LISTS_DETAIL_BASE_URL}/dvds/current_releases.json?apikey=#{@api_key}"
when "upcoming_dvds"
url = "#{LISTS_DETAIL_BASE_URL}/dvds/upcoming.json?apikey=#{@api_key}"
when "top_rentals"
url = "#{LISTS_DETAIL_BASE_URL}/dvds/top_rentals.json?apikey=#{@api_key}"
else
puts "Not a valid action"
return
end
return get(url)
end
|
ruby
|
{
"resource": ""
}
|
q5204
|
BadFruit.Base.parse_movies_array
|
train
|
def parse_movies_array(hash)
moviesArray = Array.new
hash["movies"].each do |movie|
moviesArray.push(Movie.new(movie, self))
end
return moviesArray
end
|
ruby
|
{
"resource": ""
}
|
q5205
|
BadFruit.Base.parse_actors_array
|
train
|
def parse_actors_array(hash)
actorsArray = Array.new
hash["cast"].each do |actor|
actorsArray.push(Actor.new(actor))
end
return actorsArray
end
|
ruby
|
{
"resource": ""
}
|
q5206
|
BadFruit.Base.get
|
train
|
def get(url)
data = nil
resp = HTTParty.get(url)
if resp.code == 200
return resp.body
end
end
|
ruby
|
{
"resource": ""
}
|
q5207
|
Chatrix.Client.sync!
|
train
|
def sync!
events = @matrix.sync since: @since
process_sync events
rescue ApiError => err
broadcast(:sync_error, err)
end
|
ruby
|
{
"resource": ""
}
|
q5208
|
Chatrix.Client.process_sync
|
train
|
def process_sync(events)
return unless events.is_a? Hash
@since = events['next_batch']
broadcast(:sync, events)
@rooms.process_events events['rooms'] if events.key? 'rooms'
end
|
ruby
|
{
"resource": ""
}
|
q5209
|
Auth.ApplicationHelper.get_signed_in_scope
|
train
|
def get_signed_in_scope
if signed_in?
Devise.mappings.keys.each do |res|
l = send "#{res.to_s}_signed_in?"
if send "#{res.to_s}_signed_in?"
return res.to_s
end
end
end
return 'user'
end
|
ruby
|
{
"resource": ""
}
|
q5210
|
Auth.ApplicationHelper.resource_in_navbar?
|
train
|
def resource_in_navbar?(resource)
return false unless resource
return (Auth.configuration.auth_resources[resource.class.name][:nav_bar] && Auth.configuration.enable_sign_in_modals)
end
|
ruby
|
{
"resource": ""
}
|
q5211
|
Rubikon.HasArguments.<<
|
train
|
def <<(arg)
raise ExtraArgumentError.new(@name) unless more_args?
if @arg_names.size > @args.size
name = @arg_names[@args.size]
if @max_arg_count == -1 && @arg_names.size == @args.size + 1
@args[name] = [arg]
else
@args[name] = arg
end
elsif !@arg_names.empty? && @max_arg_count == -1
@args[@arg_names.last] << arg
else
@args[@args.size] = arg
end
end
|
ruby
|
{
"resource": ""
}
|
q5212
|
Rubikon.HasArguments.check_args
|
train
|
def check_args
raise MissingArgumentError.new(@name) unless args_full?
unless @arg_values.empty?
@args.each do |name, arg|
if @arg_values.key? name
arg = [arg] unless arg.is_a? Array
arg.each do |a|
unless a =~ @arg_values[name]
raise UnexpectedArgumentError.new(a)
end
end
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q5213
|
Rubikon.HasArguments.method_missing
|
train
|
def method_missing(name, *args, &block)
if args.empty? && !block_given? && @arg_names.include?(name)
@args[name]
else
super
end
end
|
ruby
|
{
"resource": ""
}
|
q5214
|
Pubsubstub.Subscription.fetch_scrollback
|
train
|
def fetch_scrollback(last_event_id)
event_sent = false
if last_event_id
channels.each do |channel|
channel.scrollback(since: last_event_id).each do |event|
event_sent = true
queue.push(event)
end
end
end
queue.push(Pubsubstub.heartbeat_event) unless event_sent
end
|
ruby
|
{
"resource": ""
}
|
q5215
|
GosuEnhanced.Region.contains?
|
train
|
def contains?(col, row = nil)
return contains_point?(col) if col.respond_to? :x
col.between?(left, left + width - 1) &&
row.between?(top, top + height - 1)
end
|
ruby
|
{
"resource": ""
}
|
q5216
|
GosuEnhanced.Region.draw
|
train
|
def draw(surface, z_order, colour)
surface.draw_rectangle(position, size, z_order, colour)
end
|
ruby
|
{
"resource": ""
}
|
q5217
|
GosuEnhanced.Region.contains_point?
|
train
|
def contains_point?(pt)
pt.x.between?(left, left + width - 1) &&
pt.y.between?(top, top + height - 1)
end
|
ruby
|
{
"resource": ""
}
|
q5218
|
Biopsy.Experiment.select_algorithm
|
train
|
def select_algorithm
return if algorithm
max = Settings.instance.sweep_cutoff
n = @target.count_parameter_permutations
if n < max
@algorithm = ParameterSweeper.new(@target.parameters, @id)
else
@algorithm = TabuSearch.new(@target.parameters, @id)
end
end
|
ruby
|
{
"resource": ""
}
|
q5219
|
Biopsy.Experiment.run
|
train
|
def run
start_time = Time.now
in_progress = true
@algorithm.setup @start
@current_params = @start
max_scores = @target.count_parameter_permutations
while in_progress
run_iteration
# update the best result
best = @best
@best = @algorithm.best
ptext = @best[:parameters].each_pair.map{ |k, v| "#{k}:#{v}" }.join(", ")
if @best &&
@best.key?(:score) &&
best &&
best.key?(:score) &&
@best[:score] > best[:score]
unless @verbosity == :silent
puts "found a new best score: #{@best[:score]} "+
"for parameters #{ptext}"
end
end
# have we finished?
in_progress = [email protected]? && @scores.size < max_scores
if in_progress && !(@timelimit.nil?)
in_progress = (Time.now - start_time < @timelimit)
end
end
@algorithm.write_data if @algorithm.respond_to? :write_data
unless @verbosity == :silent
puts "found optimum score: #{@best[:score]} for parameters "+
"#{@best[:parameters]} in #{@iteration_count} iterations."
end
return @best
end
|
ruby
|
{
"resource": ""
}
|
q5220
|
Biopsy.Experiment.create_tempdir
|
train
|
def create_tempdir
token = loop do
# generate random dirnames until we find one that
# doesn't exist
test_token = SecureRandom.hex
break test_token unless File.exist? test_token
end
Dir.mkdir(token)
@last_tempdir = token
token
end
|
ruby
|
{
"resource": ""
}
|
q5221
|
Biopsy.Experiment.set_id
|
train
|
def set_id id
@id = id
if @id.nil?
t = Time.now
parts = %w[y m d H M S Z].map{ |p| t.strftime "%#{p}" }
@id = "experiment_#{parts.join('_')}"
end
end
|
ruby
|
{
"resource": ""
}
|
q5222
|
Racket.Registry.register
|
train
|
def register(key, proc = nil, &block)
Helper.register(obj: self, key: key, proc: proc, block: block)
end
|
ruby
|
{
"resource": ""
}
|
q5223
|
Racket.Registry.register_singleton
|
train
|
def register_singleton(key, proc = nil, &block)
Helper.register_singleton(obj: self, key: key, proc: proc, block: block)
end
|
ruby
|
{
"resource": ""
}
|
q5224
|
DataMapper.Model.generate
|
train
|
def generate(name = default_fauxture_name, attributes = {})
name, attributes = default_fauxture_name, name if name.is_a? Hash
Sweatshop.create(self, name, attributes)
end
|
ruby
|
{
"resource": ""
}
|
q5225
|
DataMapper.Model.make
|
train
|
def make(name = default_fauxture_name, attributes = {})
name, attributes = default_fauxture_name, name if name.is_a? Hash
Sweatshop.make(self, name, attributes)
end
|
ruby
|
{
"resource": ""
}
|
q5226
|
DeploYML.Project.environment
|
train
|
def environment(name=:production)
name = name.to_sym
unless @environments[name]
raise(UnknownEnvironment,"unknown environment: #{name}",caller)
end
return @environments[name]
end
|
ruby
|
{
"resource": ""
}
|
q5227
|
DeploYML.Project.load_configuration
|
train
|
def load_configuration(path)
config = YAML.load_file(path)
unless config.kind_of?(Hash)
raise(InvalidConfig,"DeploYML file #{path.dump} does not contain a Hash",caller)
end
return config
end
|
ruby
|
{
"resource": ""
}
|
q5228
|
DeploYML.Project.load_environments!
|
train
|
def load_environments!
base_config = infer_configuration
if File.file?(@config_file)
base_config.merge!(load_configuration(@config_file))
end
@environments = {}
if File.directory?(@environments_dir)
Dir.glob(File.join(@environments_dir,'*.yml')) do |path|
config = base_config.merge(load_configuration(path))
name = File.basename(path).sub(/\.yml$/,'').to_sym
@environments[name] = Environment.new(name,config)
end
else
@environments[:production] = Environment.new(:production,base_config)
end
end
|
ruby
|
{
"resource": ""
}
|
q5229
|
Cogbot.Bot.start
|
train
|
def start
# prepare config
config = {}
begin
config = YAML::load_file(CONFIG_FILE)
rescue Exception => e
load 'lib/cogbot/setup.rb'
config['main'] = Cogbot::Setup.init
end
# prepare daemon
Daemons.daemonize(
:app_name => 'cogbot',
:dir_mode => :normal,
:log_dir => LOG_DIR,
:log_output => true,
:dir => CONFIG_DIR
)
# checkout plugins
plugins = []
config['main']['plugins'].each do |p|
if File.exists?(File.join(ROOT_DIR, 'plugins', "#{p}.rb"))
require File.join(ROOT_DIR, 'plugins', p)
plugins.push Cinch::Plugins.const_get(p.camelize)
end
end
# create bot
bot = Cinch::Bot.new do
configure do |c|
c.server = config['main']['server']
c.ssl.use = ( config['main']['ssl'] == 'true' )
c.nick = config['main']['nick']
c.user = config['main']['nick']
c.realname = config['main']['nick']
c.channels = config['main']['channels']
c.sasl.username = config['main']['sasl_user']
c.sasl.password = config['main']['sasl_pass']
c.options = { 'cogconf' => config }
c.plugins.prefix = config['main']['prefix']
c.plugins.plugins = plugins
end
on :message, 'hi' do |m|
m.reply "Hello, #{m.user.nick}"
end
end
bot.loggers.debug(plugins.inspect)
Signal.trap('TERM') { EM.stop }
EM.run do
EM.defer { bot.start }
if config['server']
EM.add_timer(3) do
EM.start_server(
config['server']['ip'],
config['server']['port'],
Server,
bot
)
end
end
end
bot.quit
end
|
ruby
|
{
"resource": ""
}
|
q5230
|
Cogbot.Bot.stop
|
train
|
def stop
pid_file = File.join(CONFIG_DIR, 'cogbot.pid')
pid = File.read(pid_file).to_i if File.exist?(pid_file)
Process.kill('TERM', pid)
end
|
ruby
|
{
"resource": ""
}
|
q5231
|
Polisher.VersionedDependencies.dependency_versions
|
train
|
def dependency_versions(args = {}, &bl)
versions = {}
args = {:recursive => true, :dev_deps => true, :versions => versions}.merge(args)
deps.each do |dep|
gem = Polisher::Gem.retrieve(dep.name)
versions.merge!(gem.versions(args, &bl))
end
versions
end
|
ruby
|
{
"resource": ""
}
|
q5232
|
Polisher.VersionedDependencies.dependency_tree
|
train
|
def dependency_tree(args = {}, &bl)
dependencies = {}
args = {:recursive => true,
:dev_deps => true,
:matching => :latest,
:dependencies => dependencies}.merge(args)
process = []
deps.each do |dep|
resolved = nil
begin
resolved = Polisher::Gem.matching(dep, args[:matching])
rescue
end
yield self, dep, resolved
process << resolved unless resolved.nil?
end
process.each { |dep|
dependencies.merge!(dep.dependency_tree(args, &bl))
}
dependencies
end
|
ruby
|
{
"resource": ""
}
|
q5233
|
Polisher.VersionedDependencies.missing_dependencies
|
train
|
def missing_dependencies
missing = []
dependency_versions(:recursive => false).each do |pkg, target_versions|
found = false
target_versions.each do |_target, versions|
dependency = dependency_for(pkg)
found = versions.any? { |version| dependency.match?(pkg, version) }
end
missing << pkg unless found
end
missing
end
|
ruby
|
{
"resource": ""
}
|
q5234
|
Polisher.VersionedDependencies.dependency_states
|
train
|
def dependency_states
states = {}
deps.each do |dep|
gem = Polisher::Gem.new :name => dep.name
states.merge! dep.name => gem.state(:check => dep)
end
states
end
|
ruby
|
{
"resource": ""
}
|
q5235
|
Push0r.Queue.add
|
train
|
def add(message)
@services.each do |service|
if service.can_send?(message)
if @queued_messages[service].nil?
@queued_messages[service] = []
end
@queued_messages[service] << message
return true
end
end
return false
end
|
ruby
|
{
"resource": ""
}
|
q5236
|
Push0r.Queue.flush
|
train
|
def flush
failed_messages = []
new_token_messages = []
@queued_messages.each do |service, messages|
service.init_push
messages.each do |message|
service.send(message)
end
(failed, new_token) = service.end_push
failed_messages += failed
new_token_messages += new_token
end
@queued_messages = {}
return FlushResult.new(failed_messages, new_token_messages)
end
|
ruby
|
{
"resource": ""
}
|
q5237
|
DeploYML.Configuration.normalize_hash
|
train
|
def normalize_hash(hash)
new_hash = {}
hash.each do |key,value|
new_hash[key.to_sym] = normalize(value)
end
return new_hash
end
|
ruby
|
{
"resource": ""
}
|
q5238
|
DeploYML.Configuration.normalize
|
train
|
def normalize(value)
case value
when Hash
normalize_hash(value)
when Array
normalize_array(value)
else
value
end
end
|
ruby
|
{
"resource": ""
}
|
q5239
|
DeploYML.Configuration.parse_server
|
train
|
def parse_server(server)
name = nil
options = {}
case server
when Symbol, String
name = server.to_sym
when Hash
unless server.has_key?(:name)
raise(MissingOption,"the 'server' option must contain a 'name' option for which server to use",caller)
end
if server.has_key?(:name)
name = server[:name].to_sym
end
if server.has_key?(:options)
options.merge!(server[:options])
end
end
return [name, options]
end
|
ruby
|
{
"resource": ""
}
|
q5240
|
DeploYML.Configuration.parse_address
|
train
|
def parse_address(address)
case address
when Hash
Addressable::URI.new(address)
when String
Addressable::URI.parse(address)
else
raise(InvalidConfig,"invalid address: #{address.inspect}",caller)
end
end
|
ruby
|
{
"resource": ""
}
|
q5241
|
DeploYML.Configuration.parse_dest
|
train
|
def parse_dest(dest)
case dest
when Array
dest.map { |address| parse_address(address) }
else
parse_address(dest)
end
end
|
ruby
|
{
"resource": ""
}
|
q5242
|
DeploYML.Configuration.parse_commands
|
train
|
def parse_commands(command)
case command
when Array
command.map { |line| line.to_s }
when String
command.enum_for(:each_line).map { |line| line.chomp }
else
raise(InvalidConfig,"commands must be an Array or a String")
end
end
|
ruby
|
{
"resource": ""
}
|
q5243
|
BadFruit.Movie.reviews
|
train
|
def reviews
data = JSON.parse(@badfruit.get_movie_info(@id, "reviews"))
reviews = Array.new
data["reviews"].each do |review|
reviews.push(Review.new(review))
end
return reviews
end
|
ruby
|
{
"resource": ""
}
|
q5244
|
ConfigCurator.Collection.units
|
train
|
def units
@units ||= {}.tap do |u|
UNIT_TYPES.each do |type|
k = type.to_s.pluralize.to_sym
u[k] = []
next unless manifest
next if manifest[k].nil?
manifest[k].each { |v| u[k] << create_unit(type, attributes: v) }
end
end
end
|
ruby
|
{
"resource": ""
}
|
q5245
|
ConfigCurator.Collection.install
|
train
|
def install
return false unless install? quiet: !(logger.level == Logger::DEBUG)
UNIT_TYPES.each do |type|
units[type.to_s.pluralize.to_sym].each do |unit|
return nil unless install_unit(unit, type)
end
end
true
end
|
ruby
|
{
"resource": ""
}
|
q5246
|
ConfigCurator.Collection.install?
|
train
|
def install?(quiet: false)
result = true
UNIT_TYPES.each do |type|
units[type.to_s.pluralize.to_sym].each do |unit|
result = install_unit?(unit, type, quiet) ? result : false
end
end
result
end
|
ruby
|
{
"resource": ""
}
|
q5247
|
ConfigCurator.Collection.create_unit
|
train
|
def create_unit(type, attributes: {})
"#{self.class.name.split('::').first}::#{type.to_s.camelize}".constantize
.new(options: unit_options, logger: logger).tap do |unit|
{src: :source, dst: :destination}.each do |k, v|
unit.send "#{v}=".to_sym, attributes[k] unless attributes[k].nil?
end
UNIT_ATTRIBUTES[type].each do |v|
unit.send "#{v}=".to_sym, defaults[v] unless defaults[v].nil?
unit.send "#{v}=".to_sym, attributes[v] unless attributes[v].nil?
end
end
end
|
ruby
|
{
"resource": ""
}
|
q5248
|
ConfigCurator.Collection.unit_options
|
train
|
def unit_options
options = {}
return options unless manifest
%i(root package_tool).each do |k|
options[k] = manifest[k] unless manifest[k].nil?
end
options
end
|
ruby
|
{
"resource": ""
}
|
q5249
|
ConfigCurator.Collection.install_unit
|
train
|
def install_unit(unit, type, quiet = false)
success = unit.install
logger.info do
"Installed #{type_name(type)}: #{unit.source} => #{unit.destination_path}"
end unless quiet || !success
return true
rescue Unit::InstallFailed => e
logger.fatal { "Halting install! Install attempt failed for #{type_name(type)}: #{e}" }
return false
end
|
ruby
|
{
"resource": ""
}
|
q5250
|
ConfigCurator.Collection.install_unit?
|
train
|
def install_unit?(unit, type, quiet = false)
unit.install?
logger.info do
"Testing install for #{type_name(type)}:" \
" #{unit.source} => #{unit.destination_path}"
end unless quiet
return true
rescue Unit::InstallFailed => e
logger.error { "Cannot install #{type_name(type)}: #{e}" }
return false
end
|
ruby
|
{
"resource": ""
}
|
q5251
|
Bcome::Registry::Command.Shortcut.execute
|
train
|
def execute(node, arguments) ## We'll add in arguments later
if run_as_pseudo_tty?
node.pseudo_tty command
else
node.run command
end
rescue Interrupt
puts "\nExiting gracefully from interrupt\n".warning
end
|
ruby
|
{
"resource": ""
}
|
q5252
|
Assemblotron.Controller.process_options
|
train
|
def process_options options
options = options.clone
[:left, :right].each do |key|
if options.key?(key) && !(options[key].nil?)
options[key] = File.expand_path options[key]
end
end
options
end
|
ruby
|
{
"resource": ""
}
|
q5253
|
Assemblotron.Controller.run
|
train
|
def run
if @options[:list_assemblers]
puts @assemblerman.list_assemblers
return
elsif @options[:install_assemblers]
@assemblerman.install_assemblers(@options[:install_assemblers])
return
end
if (@options[:left].nil? || @options[:right].nil?)
logger.error "Reads must be provided with --left and --right"
logger.error "Try --help for command-line help"
exit(1)
end
unless (@options[:timelimit].nil?)
logger.info "Time limit set to #{@options[:timelimit]}"
end
subsample_input
res = @assemblerman.run_all_assemblers @options
write_metadata res
merge_assemblies res
end
|
ruby
|
{
"resource": ""
}
|
q5254
|
Assemblotron.Controller.init_settings
|
train
|
def init_settings
s = Biopsy::Settings.instance
s.set_defaults
libdir = File.dirname(__FILE__)
s.target_dir = [File.join(libdir, 'assemblers/')]
s.objectives_dir = [File.join(libdir, 'objectives/')]
logger.debug "initialised Biopsy settings"
end
|
ruby
|
{
"resource": ""
}
|
q5255
|
Assemblotron.Controller.write_metadata
|
train
|
def write_metadata res
File.open(@options[:output_parameters], 'wb') do |f|
f.write(JSON.pretty_generate(res))
end
end
|
ruby
|
{
"resource": ""
}
|
q5256
|
Assemblotron.Controller.subsample_input
|
train
|
def subsample_input
if @options[:skip_subsample]
logger.info "Skipping subsample step (--skip-subsample is on)"
@options[:left_subset] = @options[:left]
@options[:right_subset] = @options[:right]
return
end
logger.info "Subsampling reads"
seed = @options[:seed]
seed = Time.now.to_i if seed == -1
logger.info "Using random seed #{seed}"
l = @options[:left]
r = @options[:right]
size = @options[:subsample_size]
sampler = Sampler.new
if @options[:sampler] == "stream"
ls, rs = sampler.sample_stream(l, r, size, seed)
elsif @options[:sampler] == "graph"
ls, rs = sampler.sample_graph(l, r, size, seed)
else
logger.error "sampler #{@options[:sampler]} was not a valid choice"
logger.error "please user --help to see the options"
exit 1
end
@options[:left_subset] = ls
@options[:right_subset] = rs
end
|
ruby
|
{
"resource": ""
}
|
q5257
|
Assemblotron.Controller.merge_assemblies
|
train
|
def merge_assemblies res
l = @options[:left]
r = @options[:right]
transfuse = Transfuse::Transfuse.new(@options[:threads], false)
assemblies = res.each_value.map { |assembler| assember[:final] }
scores = transfuse.transrate(assemblies, l, r)
filtered = transfuse.filter(assemblies, scores)
cat = transfuse.concatenate filtered
transfuse.load_fasta cat
clusters = transfuse.cluster cat
best = transfuse.select_contigs(clusters, scores)
transfuse.output_contigs(best, cat, 'merged.fa')
end
|
ruby
|
{
"resource": ""
}
|
q5258
|
Biopsy.Settings.all_settings
|
train
|
def all_settings
settings = {}
instance_variables.each do |var|
key = var[1..-1]
settings[key] = self.instance_variable_get(var)
end
settings
end
|
ruby
|
{
"resource": ""
}
|
q5259
|
Gosu.Window.draw_rectangle
|
train
|
def draw_rectangle(point, size, z_index, colour)
left = point.x
top = point.y
width = size.width
height = size.height
draw_quad(
left, top, colour,
left + width, top, colour,
left + width, top + height, colour,
left, top + height, colour,
z_index)
end
|
ruby
|
{
"resource": ""
}
|
q5260
|
Gosu.Window.draw_simple_line
|
train
|
def draw_simple_line(p1, p2, z_index, colour)
draw_line(p1.x, p1.y, colour, p2.x, p2.y, colour, z_index)
end
|
ruby
|
{
"resource": ""
}
|
q5261
|
Gosu.Font.centred_in
|
train
|
def centred_in(text, rect)
size = measure(text)
Point((rect.width - size.width) / 2, (rect.height - size.height) / 2)
end
|
ruby
|
{
"resource": ""
}
|
q5262
|
BrB.Request.new_brb_out_request
|
train
|
def new_brb_out_request(meth, *args, &blck)
Thread.current[:brb_nb_out] ||= 0
Thread.current[:brb_nb_out] += 1
raise BrBCallbackWithBlockingMethodException.new if is_brb_request_blocking?(meth) and block_given?
block = (is_brb_request_blocking?(meth) or block_given?) ? Thread.current.to_s.to_sym : nil
if block
args << block
args << Thread.current[:brb_nb_out]
end
if block_given?
# Simulate a method with _block in order to make BrB send the answer
meth = "#{meth}_block".to_sym
end
args.size > 0 ? brb_send([MessageRequestCode, meth, args]) : brb_send([MessageRequestCode, meth])
if block_given?
# Declare the callback
declare_callback(block, Thread.current[:brb_nb_out], &blck)
elsif block # Block until the request return
#TimeMonitor.instance.watch_thread!(@timeout_rcv_value || 45)
begin
r = recv(block, Thread.current[:brb_nb_out], &blck)
rescue Exception => e
raise e
ensure
#TimeMonitor.instance.remove_thread!
end
if r.kind_of? Exception
raise r
end
return r
end
nil
end
|
ruby
|
{
"resource": ""
}
|
q5263
|
BrB.Request.new_brb_in_request
|
train
|
def new_brb_in_request(meth, *args)
if is_brb_request_blocking?(meth)
m = meth.to_s
m = m[0, m.size - 6].to_sym
idrequest = args.pop
thread = args.pop
begin
r = ((args.size > 0) ? @object.send(m, *args) : @object.send(m))
brb_send([ReturnCode, r, thread, idrequest])
rescue Exception => e
brb_send([ReturnCode, e, thread, idrequest])
BrB.logger.error e.to_s
BrB.logger.error e.backtrace.join("\n")
#raise e
end
else
begin
(args.size > 0) ? @object.send(meth, *args) : @object.send(meth)
rescue Exception => e
BrB.logger.error "#{e.to_s} => By calling #{meth} on #{@object.class} with args : #{args.inspect}"
BrB.logger.error e.backtrace.join("\n")
raise e
end
end
end
|
ruby
|
{
"resource": ""
}
|
q5264
|
Polisher.GemDiff.diff
|
train
|
def diff(other)
require_dep! 'awesome_spawn'
require_cmd! diff_cmd
out = nil
begin
this_dir = unpack
other_dir = if other.is_a?(Polisher::Gem)
other.unpack
elsif other.is_a?(Polisher::Git::Repo)
other.path
else
other
end
result = AwesomeSpawn.run("#{diff_cmd} -r #{this_dir} #{other_dir}")
out = result.output.gsub("#{this_dir}", 'a').gsub("#{other_dir}", 'b')
rescue
ensure
FileUtils.rm_rf this_dir unless this_dir.nil?
FileUtils.rm_rf other_dir unless other_dir.nil? ||
!other.is_a?(Polisher::Gem)
end
out
end
|
ruby
|
{
"resource": ""
}
|
q5265
|
Passbook.RegistrationsController.push_token
|
train
|
def push_token
return params[:pushToken] if params.include?(:pushToken)
if request && request.body
request.body.rewind
json_body = JSON.parse(request.body.read)
if json_body['pushToken']
json_body['pushToken']
end
end
end
|
ruby
|
{
"resource": ""
}
|
q5266
|
Siba.Generator.generate
|
train
|
def generate
siba_file.run_this do
file_path = @name.gsub /\.yml$/, ""
file_path += ".yml"
file_path = siba_file.file_expand_path file_path
if siba_file.file_file?(file_path) || siba_file.file_directory?(file_path)
raise Siba::Error, "Options file already exists: #{file_path}"
end
options_data = []
Siba::Plugins::PLUGINS_HASH.each do |category, types|
type = nil
if types.size > 1
max_type_length = types.keys.max do |a,b|
a.length <=> b.length
end.length + 5
siba_kernel.puts "\nChoose #{category} plugin:"
types.keys.each_index do |i|
type = types.keys[i]
siba_kernel.puts " #{i+1}. #{Siba::Plugins.plugin_type_and_description(category, type, max_type_length)}"
end
type = Siba::Generator.get_plugin_user_choice types.keys
if type.nil?
siba_kernel.puts "Cancelled by user"
return
end
unless Siba::InstalledPlugins.installed? category, type
siba_kernel.puts Siba::InstalledPlugins.install_gem_message(category, type)
return
end
else
type = types.keys.first
end
options = Siba::Generator.load_plugin_yaml_content category, type
unless options =~ /^\s*type:/
options = "type: #{type}\n" + options
end
options.gsub! /^/, " "
options = "#{category}:\n" + options
options_data << options
end
file_data = options_data.join("\n")
file_data = "# SIBA options file\n" + file_data
dest_dir = File.dirname file_path
siba_file.file_utils_mkpath(dest_dir) unless siba_file.file_directory?(dest_dir)
Siba::FileHelper.write file_path, file_data
file_path
end
end
|
ruby
|
{
"resource": ""
}
|
q5267
|
Sanscript.Transliterate.add_brahmic_scheme
|
train
|
def add_brahmic_scheme(name, scheme)
name = name.to_sym
scheme = scheme.deep_dup
@schemes[name] = IceNine.deep_freeze(scheme)
@brahmic_schemes.add(name)
@scheme_names.add(name)
scheme
end
|
ruby
|
{
"resource": ""
}
|
q5268
|
Sanscript.Transliterate.add_roman_scheme
|
train
|
def add_roman_scheme(name, scheme)
name = name.to_sym
scheme = scheme.deep_dup
scheme[:vowel_marks] = scheme[:vowels][1..-1] unless scheme.key?(:vowel_marks)
@schemes[name] = IceNine.deep_freeze(scheme)
@roman_schemes.add(name)
@scheme_names.add(name)
scheme
end
|
ruby
|
{
"resource": ""
}
|
q5269
|
Sanscript.Transliterate.transliterate
|
train
|
def transliterate(data, from, to, **opts)
from = from.to_sym
to = to.to_sym
return data if from == to
raise SchemeNotSupportedError, from unless @schemes.key?(from)
raise SchemeNotSupportedError, to unless @schemes.key?(to)
data = data.to_str.dup
options = @defaults.merge(opts)
map = make_map(from, to)
data.gsub!(/(<.*?>)/, "##\\1##") if options[:skip_sgml]
# Easy way out for "{\m+}", "\", and ".h".
if from == :itrans
data.gsub!(/\{\\m\+\}/, ".h.N")
data.gsub!(/\.h/, "")
data.gsub!(/\\([^'`_]|$)/, "##\\1##")
end
if map[:from_roman?]
transliterate_roman(data, map, options)
else
transliterate_brahmic(data, map)
end
end
|
ruby
|
{
"resource": ""
}
|
q5270
|
DeploYML.LocalShell.run
|
train
|
def run(program,*arguments)
program = program.to_s
arguments = arguments.map { |arg| arg.to_s }
system(program,*arguments)
end
|
ruby
|
{
"resource": ""
}
|
q5271
|
ThorSsh.RemoteFile.mkdir_p
|
train
|
def mkdir_p(path)
stdout, stderr, _, _ = exec("mkdir -p #{path.inspect}", :with_codes => true)
if stderr =~ /Permission denied/
base.say_status :permission_error, stderr, :red
raise PermissionError, "unable to create directory #{path}"
end
end
|
ruby
|
{
"resource": ""
}
|
q5272
|
LatoCore.Cell.validate_args
|
train
|
def validate_args(args: {}, requested_args: [], default_args: {})
requested_args.each do |requested_arg|
raise "Cell must have #{requested_arg} argument" if args[requested_arg] == nil
end
default_args.each do |key, value|
args[key] = value if args[key] == nil
end
args
end
|
ruby
|
{
"resource": ""
}
|
q5273
|
ConfigCurator.Utils.command?
|
train
|
def command?(command)
MakeMakefile::Logging.instance_variable_set :@logfile, File::NULL
MakeMakefile::Logging.quiet = true
MakeMakefile.find_executable command.to_s
end
|
ruby
|
{
"resource": ""
}
|
q5274
|
ResourcesController.Specification.find_resource
|
train
|
def find_resource(controller)
(controller.enclosing_resource ? controller.enclosing_resource.send(source) : klass).find controller.params[key]
end
|
ruby
|
{
"resource": ""
}
|
q5275
|
ResourcesController.SingletonSpecification.find_resource
|
train
|
def find_resource(controller)
ResourcesController.raise_cant_find_singleton(name, klass) unless controller.enclosing_resource
controller.enclosing_resource.send(source)
end
|
ruby
|
{
"resource": ""
}
|
q5276
|
DeploYML.CLI.find_root
|
train
|
def find_root
Pathname.pwd.ascend do |root|
config_dir = root.join(Project::CONFIG_DIR)
if config_dir.directory?
config_file = config_dir.join(Project::CONFIG_FILE)
return root if config_file.file?
environments_dir = config_dir.join(Project::ENVIRONMENTS_DIR)
return root if environments_dir.directory?
end
end
shell.say "Could not find '#{Project::CONFIG_FILE}' in any parent directories", :red
exit -1
end
|
ruby
|
{
"resource": ""
}
|
q5277
|
Biopsy.ObjectiveHandler.dimension_reduce
|
train
|
def dimension_reduce(results)
# calculate the weighted Euclidean distance from optimal
# d(p, q) = \sqrt{(p_1 - q_1)^2 + (p_2 - q_2)^2+...+(p_n - q_n)^2}
# here the max value is sqrt(n) where n is no. of results,
# min value (optimum) is 0
total = 0
results.each_value do |value|
o = value[:optimum]
w = value[:weighting]
a = value[:result]
m = value[:max]
total += w * (((o - a) / m)**2) if m != 0
end
Math.sqrt(total) / results.length
end
|
ruby
|
{
"resource": ""
}
|
q5278
|
GroupMe.Bots.bot_post
|
train
|
def bot_post(id, text, options = {})
data = {
:bot_id => id,
:text => text
}
data[:options] = options if options.any?
post('/bots/post', data).status == 202
end
|
ruby
|
{
"resource": ""
}
|
q5279
|
GroupMe.Bots.create_bot
|
train
|
def create_bot(name, group_id, options = {})
data = {
:bot => options.merge(:name => name, :group_id => group_id)
}
post('/bots', data)
end
|
ruby
|
{
"resource": ""
}
|
q5280
|
AwsSesNewsletters.NewslettersSender.preview_to
|
train
|
def preview_to(recipient)
@newsletter = build_newsletter
mail = build_mail
mail.to = recipient.email
replace_and_send_mail_safely(mail, recipient)
end
|
ruby
|
{
"resource": ""
}
|
q5281
|
AwsSesNewsletters.NewslettersSender.send_emails
|
train
|
def send_emails
mail = build_mail
get_recipients do |recipient|
unless EmailResponse.exists?(email: recipient.email) # bounces & complaints
mail.to = recipient.email
replace_and_send_mail_safely(mail, recipient)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q5282
|
AwsSesNewsletters.NewslettersSender.replace_and_send_mail_safely
|
train
|
def replace_and_send_mail_safely(mail, recipient)
html_body = mail.html_part.body.raw_source
do_custom_replacements_for(mail, recipient)
send_raw_email_safely(mail)
mail.html_part.body = html_body
end
|
ruby
|
{
"resource": ""
}
|
q5283
|
AwsSesNewsletters.NewslettersSender.build_mail
|
train
|
def build_mail
AwsSesNewsletters::MailBuilder.new(
from: newsletter.from,
subject: newsletter.subject,
html_body: newsletter.html_body,
images: get_images,
).build
end
|
ruby
|
{
"resource": ""
}
|
q5284
|
Auth::Concerns::Shopping::PaymentConcern.ClassMethods.get_discount_payments
|
train
|
def get_discount_payments(cart_id)
discount_payments = Auth.configuration.payment_class.constantize.where(:cart_id => cart_id, :discount_id.nin => ["", nil], :payment_status => 1)
discount_payments
end
|
ruby
|
{
"resource": ""
}
|
q5285
|
Auth::Concerns::Shopping::PaymentConcern.ClassMethods.get_sum_of_discount_payments
|
train
|
def get_sum_of_discount_payments(cart_id)
sum_of_discount_payments = 0
get_discount_payments(cart_id).each do |dp|
sum_of_discount_payments+= dp.amount
end
sum_of_discount_payments
end
|
ruby
|
{
"resource": ""
}
|
q5286
|
LatoCore.Interface::General.core__read_yaml
|
train
|
def core__read_yaml(file_path)
# return nil if file not exist
return unless File.exist?(file_path)
config_file = File.read(file_path)
# return yaml data
return YAML.safe_load(config_file).with_indifferent_access
rescue
nil
end
|
ruby
|
{
"resource": ""
}
|
q5287
|
LatoCore.Interface::General.core__paginate_array
|
train
|
def core__paginate_array(array, per_page, page)
start = (page - 1) * per_page
array[start, per_page]
end
|
ruby
|
{
"resource": ""
}
|
q5288
|
LatoCore.Interface::General.core__add_param_to_url
|
train
|
def core__add_param_to_url(url, param_name, param_value)
uri = URI(url)
params = URI.decode_www_form(uri.query || "") << [param_name, param_value]
uri.query = URI.encode_www_form(params)
uri.to_s
end
|
ruby
|
{
"resource": ""
}
|
q5289
|
Polisher.CheckerLoader.targets
|
train
|
def targets
@targets ||= Dir.glob(File.join(target_dir, '*.rb'))
.collect { |t| t.gsub("#{target_dir}/", '').gsub('.rb', '').intern }
end
|
ruby
|
{
"resource": ""
}
|
q5290
|
Polisher.CheckerLoader.load_target
|
train
|
def load_target(target)
raise ArgumentError, target unless targets.include?(target)
require "polisher/adaptors/version_checker/#{target}"
tm = target_module(target)
@target_modules ||= []
@target_modules << tm
include tm
end
|
ruby
|
{
"resource": ""
}
|
q5291
|
Auth::Concerns::ActivityConcern.ClassMethods.activities_from_to
|
train
|
def activities_from_to(query,default_from,default_to)
defaults = {"range" => {"from" => default_from, "to" => default_to}}
query = defaults.deep_merge(query)
##default from and to assigned here.
from = query["range"]["from"].to_i
to = query["range"]["to"].to_i
if from >= to
query["range"]["from"] = default_from
query["range"]["to"] = default_to
end
return query
end
|
ruby
|
{
"resource": ""
}
|
q5292
|
Auth::Concerns::ActivityConcern.ClassMethods.activities_fields
|
train
|
def activities_fields(query)
defaults = {"only" => Object.const_get(name).fields.keys}
query = defaults.deep_merge(query)
only = ((Object.const_get(name).fields.keys & query["only"]) + ["created_at"])
query["only"] = only
return query
end
|
ruby
|
{
"resource": ""
}
|
q5293
|
Prometheus.PluginDSL.start
|
train
|
def start
if File.exists? CONFIG_PATH
if Config.missing_configurables.size > 0
Prometheus::ConfigCommands.new.invoke :repair
else
super
end
else
Prometheus::ConfigCommands.new.invoke :edit
end
end
|
ruby
|
{
"resource": ""
}
|
q5294
|
Chatrix.Users.[]
|
train
|
def [](id)
return @users[id] if id.start_with? '@'
res = @users.find { |_, u| u.displayname == id }
res.last if res.respond_to? :last
end
|
ruby
|
{
"resource": ""
}
|
q5295
|
Chatrix.Users.process_power_levels
|
train
|
def process_power_levels(room, data)
data.each do |id, level|
get_user(id).process_power_level room, level
end
end
|
ruby
|
{
"resource": ""
}
|
q5296
|
Chatrix.Users.process_invite
|
train
|
def process_invite(room, event)
sender = get_user(event['sender'])
invitee = get_user(event['state_key'])
invitee.process_invite room, sender, event
end
|
ruby
|
{
"resource": ""
}
|
q5297
|
Chatrix.Users.get_user
|
train
|
def get_user(id)
return @users[id] if @users.key? id
user = User.new id
@users[id] = user
broadcast(:added, user)
user
end
|
ruby
|
{
"resource": ""
}
|
q5298
|
ResourcesController.ClassMethods.nested_in
|
train
|
def nested_in(*names, &block)
options = names.extract_options!
raise ArgumentError, "when giving more than one nesting, you may not specify options or a block" if names.length > 1 and (block_given? or options.length > 0)
# convert :polymorphic option to '?'
if options.delete(:polymorphic)
raise ArgumentError, "when specifying :polymorphic => true, no block or other options may be given" if block_given? or options.length > 0
names = ["?#{names.first}"]
end
# ignore first '*' if it has already been specified by :load_enclosing == true
names.shift if specifications == ['*'] && names.first == '*'
names.each do |name|
ensure_sane_wildcard if name == '*'
specifications << (name.to_s =~ /^(\*|\?(.*))$/ ? name.to_s : Specification.new(name, options, &block))
end
end
|
ruby
|
{
"resource": ""
}
|
q5299
|
ResourcesController.ClassMethods.ensure_sane_wildcard
|
train
|
def ensure_sane_wildcard
idx = specifications.length
while (idx -= 1) >= 0
if specifications[idx] == '*'
raise ArgumentError, "Can only specify one wildcard '*' in between resource specifications"
elsif specifications[idx].is_a?(Specification)
break
end
end
true
end
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.