_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q9400 | Activr.Registry.classes_from_path | train | def classes_from_path(dir_path)
Dir["#{dir_path}/*.rb"].sort.inject({ }) do |memo, file_path|
klass = File.basename(file_path, '.rb').camelize.constantize
if !memo[klass.kind].nil?
raise "Kind #{klass.kind} already used by class #{memo[klass.kind]} so can't use it for class #{klass}"
end
memo[klass.kind] = klass
memo
end
end | ruby | {
"resource": ""
} |
q9401 | SycLink.InternetExplorer.read | train | def read
files = Dir.glob(File.join(path, "**/*"))
regex = Regexp.new("(?<=#{path}).*")
files.map do |file|
unless ((File.directory? file) || (File.extname(file).upcase != ".URL"))
url = File.read(file).scan(/(?<=\nURL=)(.*)$/).flatten.first.chomp
name = url_name(File.basename(file, ".*"))
description = ""
tag = extract_tags(File.dirname(file).scan(regex))
[url, name, description, tag]
end
end.compact
end | ruby | {
"resource": ""
} |
q9402 | GMath3D.::Matrix.multi_new | train | def multi_new(rhs)
if(rhs.kind_of?(Vector3))
ans = self.multi_inner(rhs.to_column_vector)
return Vector3.new(ans[0,0], ans[1,0], ans[2,0])
end
multi_inner(rhs)
end | ruby | {
"resource": ""
} |
q9403 | LatoBlog.Tag.check_meta_permalink | train | def check_meta_permalink
candidate = (self.meta_permalink ? self.meta_permalink : self.title.parameterize)
accepted = nil
counter = 0
while accepted.nil?
if LatoBlog::Tag.find_by(meta_permalink: candidate)
counter += 1
candidate = "#{candidate}-#{counter}"
else
accepted = candidate
end
end
self.meta_permalink = accepted
end | ruby | {
"resource": ""
} |
q9404 | LatoBlog.Tag.check_lato_blog_tag_parent | train | def check_lato_blog_tag_parent
tag_parent = LatoBlog::TagParent.find_by(id: lato_blog_tag_parent_id)
if !tag_parent
errors.add('Tag parent', 'not exist for the tag')
throw :abort
return
end
same_language_tag = tag_parent.tags.find_by(meta_language: meta_language)
if same_language_tag && same_language_tag.id != id
errors.add('Tag parent', 'has another tag for the same language')
throw :abort
return
end
end | ruby | {
"resource": ""
} |
q9405 | Tinycert.Request.prepare_params | train | def prepare_params p
results = {}
# Build a new hash with string keys
p.each { |k, v| results[k.to_s] = v }
# Sort nested structures
results.sort.to_h
end | ruby | {
"resource": ""
} |
q9406 | ProgneTapera::EnumList.ClassMethods.enum_constants | train | def enum_constants
constants.select { |constant|
value = const_get constant
value.is_a? ProgneTapera::EnumItem
}
end | ruby | {
"resource": ""
} |
q9407 | ChronuscopClient.Configuration.load_yaml_configuration | train | def load_yaml_configuration
yaml_config = YAML.load_file("#{@rails_root_dir}/config/chronuscop.yml")
@redis_db_number = yaml_config[@rails_environment]['redis_db_number']
@redis_server_port = yaml_config[@rails_environment]['redis_server_port']
@project_number = yaml_config[@rails_environment]['project_number']
@api_token = yaml_config[@rails_environment]['api_token']
@chronuscop_server_address = yaml_config[@rails_environment]['chronuscop_server_address']
@sync_time_interval = yaml_config[@rails_environment]['sync_time_interval']
end | ruby | {
"resource": ""
} |
q9408 | Ponder.User.whois | train | def whois
connected do
fiber = Fiber.current
callbacks = {}
# User is online.
callbacks[311] = @thaum.on(311) do |event_data|
nick = event_data[:params].split(' ')[1]
if nick.downcase == @nick.downcase
@online = true
# TODO: Add properties.
end
end
# User is not online.
callbacks[401] = @thaum.on(401) do |event_data|
nick = event_data[:params].split(' ')[1]
if nick.downcase == @nick.downcase
@online = false
fiber.resume
end
end
# End of WHOIS.
callbacks[318] = @thaum.on(318) do |event_data|
nick = event_data[:params].split(' ')[1]
if nick.downcase == @nick.downcase
fiber.resume
end
end
raw "WHOIS #{@nick}"
Fiber.yield
callbacks.each do |type, callback|
@thaum.callbacks[type].delete(callback)
end
end
self
end | ruby | {
"resource": ""
} |
q9409 | Lazymodel.Base.attributes | train | def attributes
_attributes.inject(HashWithIndifferentAccess.new) do |hash, attribute|
hash.update attribute => send(attribute)
end
end | ruby | {
"resource": ""
} |
q9410 | Joinable.PermissionsAttributeWrapper.permission_attributes= | train | def permission_attributes=(permissions)
self.permissions = [] # Reset permissions in anticipation for re-population
permissions.each do |key, value|
key, value = key.dup, value.dup
# Component Permissions
if key.ends_with? "_permissions"
grant_permissions(value)
# Singular Permission
elsif key.chomp! "_permission"
grant_permissions(key) if value.to_i != 0
end
end
end | ruby | {
"resource": ""
} |
q9411 | Joinable.PermissionsAttributeWrapper.has_permission? | train | def has_permission?(*levels)
if levels.all? { |level| permissions.include? level.to_sym }
return true
else
return false
end
end | ruby | {
"resource": ""
} |
q9412 | Joinable.PermissionsAttributeWrapper.method_missing | train | def method_missing(method_name, *args, &block)
# NOTE: As of Rails 4, respond_to? must be checked inside the case statement otherwise it breaks regular AR attribute accessors
case method_name.to_s
when /.+_permissions/
return component_permissions_reader(method_name) if respond_to?(:joinable_type) && joinable_type.present?
when /.+_permission/
return single_permission_reader(method_name) if respond_to?(:joinable_type) && joinable_type.present?
end
super
end | ruby | {
"resource": ""
} |
q9413 | Joinable.PermissionsAttributeWrapper.verify_and_sort_permissions | train | def verify_and_sort_permissions
# DefaultPermissionSet is allowed to have blank permissions (private joinable), the other models need at least find and view
self.permissions += [:find, :view] unless is_a?(DefaultPermissionSet)
raise "Invalid permissions: #{(permissions - allowed_permissions).inspect}. Must be one of #{allowed_permissions.inspect}" unless permissions.all? {|permission| allowed_permissions.include? permission}
self.permissions = permissions.uniq.sort_by { |permission| allowed_permissions.index(permission) }
end | ruby | {
"resource": ""
} |
q9414 | RSpec.Approvals.verify | train | def verify( options={}, &block )
approval = Git::Approvals::Approval.new( approval_path, options )
approval.diff( block.call ) do |err|
::RSpec::Expectations.fail_with err
end
rescue Errno::ENOENT => e
::RSpec::Expectations.fail_with e.message
EOS
end | ruby | {
"resource": ""
} |
q9415 | RSpec.Approvals.approval_filename | train | def approval_filename
parts = [ example, *example.example_group.parent_groups ].map do |ex|
Git::Approvals::Utils.filenamify ex.description
end
File.join parts.to_a.reverse
end | ruby | {
"resource": ""
} |
q9416 | Octo.Trends.aggregate_and_create | train | def aggregate_and_create(oftype, ts = Time.now.floor)
Octo::Enterprise.each do |enterprise|
calculate(enterprise.id, oftype, ts)
end
end | ruby | {
"resource": ""
} |
q9417 | Octo.Trends.aggregate! | train | def aggregate!(ts = Time.now.floor)
aggregate_and_create(Octo::Counter::TYPE_MINUTE, ts)
end | ruby | {
"resource": ""
} |
q9418 | Octo.Trends.calculate | train | def calculate(enterprise_id, trend_type, ts = Time.now.floor)
args = {
enterprise_id: enterprise_id,
ts: ts,
type: trend_type
}
klass = @trend_for.constantize
hitsResult = klass.public_send(:where, args)
trends = hitsResult.map { |h| counter2trend(h) }
# group trends as per the time of their happening and rank them on their
# score
grouped_trends = trends.group_by { |x| x.ts }
grouped_trends.each do |_ts, trendlist|
sorted_trendlist = trendlist.sort_by { |x| x.score }
sorted_trendlist.each_with_index do |trend, index|
trend.rank = index
trend.type = trend_type
trend.save!
end
end
end | ruby | {
"resource": ""
} |
q9419 | Octo.Trends.get_trending | train | def get_trending(enterprise_id, type, opts={})
ts = opts.fetch(:ts, Time.now.floor)
args = {
enterprise_id: enterprise_id,
ts: opts.fetch(:ts, Time.now.floor),
type: type
}
res = where(args).limit(opts.fetch(:limit, DEFAULT_COUNT))
enterprise = Octo::Enterprise.find_by_id(enterprise_id)
if res.count == 0 and enterprise.fakedata?
Octo.logger.info 'Beginning to fake data'
res = []
if ts.class == Range
ts_begin = ts.begin
ts_end = ts.end
ts_begin.to(ts_end, 1.day).each do |_ts|
3.times do |rank|
items = @trend_class.constantize.send(:where, {enterprise_id: enterprise_id}).first(10)
if items.count > 0
uid = items.shuffle.pop.unique_id
_args = args.merge( ts: _ts, rank: rank, score: rank+1, uid: uid )
res << self.new(_args).save!
end
end
end
elsif ts.class == Time
3.times do |rank|
uid = 0
items = @trend_class.constantize.send(:where, {enterprise_id: enterprise_id}).first(10)
if items.count > 0
uid = items.shuffle.pop.unique_id
_args = args.merge( rank: rank, score: rank+1, uid: uid )
res << self.new(_args).save!
end
end
end
end
res.map do |r|
clazz = @trend_class.constantize
clazz.public_send(:recreate_from, r)
end
end | ruby | {
"resource": ""
} |
q9420 | Octo.Trends.counter2trend | train | def counter2trend(counter)
self.new({
enterprise: counter.enterprise,
score: score(counter.divergence),
uid: counter.uid,
ts: counter.ts
})
end | ruby | {
"resource": ""
} |
q9421 | Uninhibited.Formatter.example_pending | train | def example_pending(example)
if example_group.metadata[:feature] && example.metadata[:skipped]
@skipped_examples << pending_examples.delete(example)
@skipped_count += 1
output.puts cyan("#{current_indentation}#{example.description}")
else
super
end
end | ruby | {
"resource": ""
} |
q9422 | Uninhibited.Formatter.summary_line | train | def summary_line(example_count, failure_count, pending_count)
pending_count -= skipped_count
summary = pluralize(example_count, "example")
summary << " ("
summary << red(pluralize(failure_count, "failure"))
summary << ", " << yellow("#{pending_count} pending") if pending_count > 0
summary << ", " << cyan("#{skipped_count} skipped") if skipped_count > 0
summary << ")"
summary
end | ruby | {
"resource": ""
} |
q9423 | PayuLatam.SubscriptionInterceptor.run | train | def run
PayuLatam::SubscriptionService.new(context.params, context.current_user).call
rescue => exception
fail!(exception.message)
end | ruby | {
"resource": ""
} |
q9424 | Logsly::Logging182::Stats.Sampler.coalesce | train | def coalesce( other )
@sum += other.sum
@sumsq += other.sumsq
if other.num > 0
@min = other.min if @min > other.min
@max = other.max if @max < other.max
@last = other.last
end
@num += other.num
end | ruby | {
"resource": ""
} |
q9425 | Logsly::Logging182::Stats.Sampler.sample | train | def sample( s )
@sum += s
@sumsq += s * s
if @num == 0
@min = @max = s
else
@min = s if @min > s
@max = s if @max < s
end
@num += 1
@last = s
end | ruby | {
"resource": ""
} |
q9426 | Logsly::Logging182::Stats.Sampler.sd | train | def sd
return 0.0 if num < 2
# (sqrt( ((s).sumsq - ( (s).sum * (s).sum / (s).num)) / ((s).num-1) ))
begin
return Math.sqrt( (sumsq - ( sum * sum / num)) / (num-1) )
rescue Errno::EDOM
return 0.0
end
end | ruby | {
"resource": ""
} |
q9427 | Logsly::Logging182::Stats.Tracker.coalesce | train | def coalesce( other )
sync {
other.stats.each do |name,sampler|
stats[name].coalesce(sampler)
end
}
end | ruby | {
"resource": ""
} |
q9428 | Logsly::Logging182::Stats.Tracker.time | train | def time( event )
sync {stats[event].mark}
yield
ensure
sync {stats[event].tick}
end | ruby | {
"resource": ""
} |
q9429 | Logsly::Logging182::Stats.Tracker.periodically_run | train | def periodically_run( period, &block )
raise ArgumentError, 'a runner already exists' unless @runner.nil?
@runner = Thread.new do
start = stop = Time.now.to_f
loop do
seconds = period - (stop-start)
seconds = period if seconds <= 0
sleep seconds
start = Time.now.to_f
break if Thread.current[:stop] == true
if @mutex then @mutex.synchronize(&block)
else block.call end
stop = Time.now.to_f
end
end
end | ruby | {
"resource": ""
} |
q9430 | Palimpsest.Assets.write | train | def write(target, gzip: options[:gzip], hash: options[:hash])
asset = assets[target]
return if asset.nil?
name = hash ? asset.digest_path : asset.logical_path.to_s
name = File.join(options[:output], name) unless options[:output].nil?
path = name
path = File.join(directory, path) unless directory.nil?
write(target, gzip: gzip, hash: false) if hash == :also_unhashed
asset.write_to "#{path}.gz", compress: true if gzip
asset.write_to path
name
end | ruby | {
"resource": ""
} |
q9431 | BreadcrumbTrail.Breadcrumb.computed_path | train | def computed_path(context)
@_path ||= case @path
when String, Hash
@path
when Symbol
context.public_send(@path) # todo
when Proc
context.instance_exec(&@path)
else
raise ArgumentError,
"Expected one of String, Symbol, or Proc, " \
"got #{@path.class}"
end
end | ruby | {
"resource": ""
} |
q9432 | BreadcrumbTrail.Breadcrumb.computed_name | train | def computed_name(context)
@_name ||= case @name
when String
@name
when Symbol
I18n.translate(@name)
when Proc
context.instance_exec(&@name)
when nil
computed_path(context)
else
raise ArgumentError,
"Expected one of String, Symbol, or Proc, " \
"got #{@name.class}"
end
end | ruby | {
"resource": ""
} |
q9433 | SycLink.Firefox.read | train | def read
bookmark_file = Dir.glob(File.expand_path(path)).shift
raise "Did not find file #{path}" unless bookmark_file
db = SQLite3::Database.new(path)
import = db.execute(QUERY_STRING)
end | ruby | {
"resource": ""
} |
q9434 | SycLink.Firefox.rows | train | def rows
read.map do |row|
a = row[0]; b = row[1]; c = row[2]; d = row[3]; e = row[4]; f = row[5]
[a,
b || c,
(d || '').gsub("\n", ' '),
[e, f].join(',').gsub(/^,|,$/, '')]
end
end | ruby | {
"resource": ""
} |
q9435 | FaviconParty.Image.to_png | train | def to_png
return @png_data if !@png_data.nil?
image = minimagick_image
image.resize '16x16!'
image.format 'png'
image.strip
@png_data = image.to_blob
raise FaviconParty::InvalidData.new("Empty png") if @png_data.empty?
@png_data
end | ruby | {
"resource": ""
} |
q9436 | Palimpsest.Repo.extract_repo | train | def extract_repo(path, destination, reference)
fail 'Git not installed' unless Utils.command? 'git'
Dir.chdir path do
system "git archive #{reference} | tar -x -C #{destination}"
end
end | ruby | {
"resource": ""
} |
q9437 | BreadcrumbTrail.BlockBuilder.call | train | def call
buffer = ActiveSupport::SafeBuffer.new
@breadcrumbs.each do |breadcrumb|
buffer << @block.call(breadcrumb.computed(@context))
end
buffer
end | ruby | {
"resource": ""
} |
q9438 | BreadcrumbTrail.HTMLBuilder.call | train | def call
outer_tag = @options.fetch(:outer, "ol")
inner_tag = @options.fetch(:inner, "li")
outer = tag(outer_tag,
@options.fetch(:outer_options, nil),
true) if outer_tag
inner = tag(inner_tag,
@options.fetch(:inner_options, nil),
true) if inner_tag
buffer = ActiveSupport::SafeBuffer.new
buffer.safe_concat(outer) if outer_tag
@breadcrumbs.each do |breadcrumb|
buffer.safe_concat(inner) if inner_tag
buffer << link_to(breadcrumb.computed_name(@context),
breadcrumb.computed_path(@context),
breadcrumb.options)
buffer.safe_concat("</#{inner_tag}>") if inner_tag
end
buffer.safe_concat("</#{outer_tag}>") if outer_tag
buffer
end | ruby | {
"resource": ""
} |
q9439 | Swift.FiberConnectionPool.acquire | train | def acquire id, fiber
if conn = @available.pop
@reserved[id] = conn
else
Fiber.yield @pending.push(fiber)
acquire(id, fiber)
end
end | ruby | {
"resource": ""
} |
q9440 | Swift.FiberConnectionPool.method_missing | train | def method_missing method, *args, &blk
__reserve__ do |conn|
if @trace
conn.trace(@trace) {conn.__send__(method, *args, &blk)}
else
conn.__send__(method, *args, &blk)
end
end
end | ruby | {
"resource": ""
} |
q9441 | LegoNXT::LowLevel.UsbConnection.transmit! | train | def transmit! bits
bytes_sent = @handle.bulk_transfer dataOut: bits, endpoint: USB_ENDPOINT_OUT
bytes_sent == bits.length
end | ruby | {
"resource": ""
} |
q9442 | LegoNXT::LowLevel.UsbConnection.transceive | train | def transceive bits
raise ::LegoNXT::BadOpCodeError unless bytestring(DirectOps::REQUIRE_RESPONSE, SystemOps::REQUIRE_RESPONSE).include? bits[0]
raise ::LegoNXT::TransmitError unless transmit! bits
bytes_received = @handle.bulk_transfer dataIn: 64, endpoint: USB_ENDPOINT_IN
return bytes_received
end | ruby | {
"resource": ""
} |
q9443 | LegoNXT::LowLevel.UsbConnection.open | train | def open
context = LIBUSB::Context.new
device = context.devices(:idVendor => LEGO_VENDOR_ID, :idProduct => NXT_PRODUCT_ID).first
raise ::LegoNXT::NoDeviceError.new("Please make sure the device is plugged in and powered on") if device.nil?
@handle = device.open
@handle.claim_interface(0)
end | ruby | {
"resource": ""
} |
q9444 | Gricer.RequestsController.handle_special_fields | train | def handle_special_fields
if ['referer_host', 'referer_path', 'referer_params', 'search_engine', 'search_query'].include?(params[:field])
@items = @items.only_first_in_session
end
if ['search_engine', 'search_query'].include?(params[:field])
@items = @items.without_nil_in params[:field]
end
if params[:field] == 'entry_path'
params[:field] = 'path'
@items = @items.only_first_in_session
end
super
end | ruby | {
"resource": ""
} |
q9445 | StixSchemaSpy.Node.referenced_element | train | def referenced_element
ref = @xml.attributes['ref'].value
@referenced_element ||= if ref =~ /:/
prefix, element = ref.split(':')
schema.find_element(element) || schema.find_attribute("@#{element}") if schema = Schema.find(prefix)
else
self.schema.find_element(ref) || self.schema.find_attribute("@#{ref}")
end
end | ruby | {
"resource": ""
} |
q9446 | HasPrice.PriceBuilder.item | train | def item(price, item_name)
@current_nesting_level[item_name.to_s] = price.respond_to?(:to_hash) ? price.to_hash : price.to_i
end | ruby | {
"resource": ""
} |
q9447 | HasPrice.PriceBuilder.group | train | def group(group_name, &block)
group_key = group_name.to_s
@current_nesting_level[group_key] ||= {}
if block_given?
within_group(group_key) do
instance_eval &block
end
end
end | ruby | {
"resource": ""
} |
q9448 | Kat.Search.query= | train | def query=(search_term)
@search_term =
case search_term
when nil, '' then []
when String, Symbol then [search_term]
when Array then search_term.flatten.select { |e| [String, Symbol].include? e.class }
else fail ArgumentError, 'search_term must be a String, Symbol or Array. ' \
"#{ search_term.inspect } given."
end
build_query
end | ruby | {
"resource": ""
} |
q9449 | Kat.Search.options= | train | def options=(options)
fail ArgumentError, 'options must be a Hash. ' \
"#{ options.inspect } given." unless options.is_a?(Hash)
@options.merge! options
build_query
end | ruby | {
"resource": ""
} |
q9450 | Kat.Search.build_query | train | def build_query
@query = @search_term.dup
@pages = -1
@results = []
@query << "\"#{ @options[:exact] }\"" if @options[:exact]
@query << @options[:or].join(' OR ') unless @options[:or].nil? or @options[:or].empty?
@query += @options[:without].map { |s| "-#{ s }" } if @options[:without]
@query += inputs.select { |k, v| @options[k] }.map { |k, v| "#{ k }:#{ @options[k] }" }
@query += checks.select { |k, v| @options[k] }.map { |k, v| "#{ k }:1" }
byzantine = selects.select do |k, v|
(v[:id].to_s[/^.*_id$/] && @options[k].to_s.to_i > 0) ||
(v[:id].to_s[/^[^_]+$/] && @options[k])
end
@query += byzantine.map { |k, v| "#{ v[:id] }:#{ @options[k] }" }
end | ruby | {
"resource": ""
} |
q9451 | Kat.Search.results_column | train | def results_column(name)
@results.compact.map do |rs|
rs.map { |r| r[name] || r[name[0...-1].intern] }
end.flatten
end | ruby | {
"resource": ""
} |
q9452 | Aker.User.full_name | train | def full_name
display_name_parts = [first_name, last_name].compact
if display_name_parts.empty?
username
else
display_name_parts.join(' ')
end
end | ruby | {
"resource": ""
} |
q9453 | EasyPartials.HelperAdditions.concat_partial | train | def concat_partial(partial, *args, &block)
rendered = invoke_partial partial, *args, &block
concat rendered
end | ruby | {
"resource": ""
} |
q9454 | Aker::Authorities.Static.valid_credentials? | train | def valid_credentials?(kind, *credentials)
found_username =
(all_credentials(kind).detect { |c| c[:credentials] == credentials } || {})[:username]
@users[found_username]
end | ruby | {
"resource": ""
} |
q9455 | Aker::Authorities.Static.load! | train | def load!(io)
doc = YAML.load(io)
return self unless doc
(doc["groups"] || {}).each do |portal, top_level_groups|
@groups[portal.to_sym] = top_level_groups.collect { |group_data| build_group(group_data) }
end
(doc["users"] || {}).each do |username, config|
attr_keys = config.keys - ["password", "portals", "identifiers"]
valid_credentials!(:user, username, config["password"]) do |u|
attr_keys.each do |k|
begin
u.send("#{k}=", config[k])
rescue NoMethodError
raise NoMethodError, "#{k} is not a recognized user attribute"
end
end
portal_data = config["portals"] || []
portals_and_groups_from_yaml(portal_data) do |portal, group, affiliate_ids|
u.default_portal = portal unless u.default_portal
u.in_portal!(portal)
if group
if affiliate_ids
u.in_group!(portal, group, :affiliate_ids => affiliate_ids)
else
u.in_group!(portal, group)
end
end
end
(config["identifiers"] || {}).each do |ident, value|
u.identifiers[ident.to_sym] = value
end
end
end
self
end | ruby | {
"resource": ""
} |
q9456 | Reaction.Client.broadcast | train | def broadcast(name, message, opts={})
# encapsulation
encap = { n: name,
m: message,
t: opts[:to] || /.*/,
e: opts[:except] || []
}
EM.next_tick {
@faye.publish BROADCAST, Base64.urlsafe_encode64(Marshal.dump(encap))
}
end | ruby | {
"resource": ""
} |
q9457 | Manage.ResourceHelper.action_link | train | def action_link(scope, link_data)
value = nil
case link_data
when Proc
value = link_data.call(scope)
when Hash
relation = link_data.keys.first
entity = Fields::Reader.field_value(scope, relation)
unless entity.present?
return ''
end
if link_data[relation][:label_field].present?
value = field_value(scope, link_data[relation][:label_field])
elsif link_data[relation][:label].present?
value = link_data[relation][:label]
end
path = entity.class.name.dasherize.pluralize.downcase
return link_to value, [scope.public_send(relation)]
when *[Symbol, String]
relation = link_data.to_s
assocation = scope.class.reflect_on_association(link_data.to_sym)
raise "assocation #{link_data} not found on #{scope.class}" unless assocation
if assocation.options[:class_name].present?
rel_name = scope.class.reflect_on_association(link_data.to_sym).options[:class_name]
relation = rel_name.downcase.dasherize.pluralize
end
if scope.class.reflect_on_association(link_data.to_sym).options[:as].present?
key = scope.class.reflect_on_association(link_data.to_sym).options[:as].to_s + '_id'
else
key = scope.class.name.downcase.dasherize + '_id'
end
return "<a href=\"#{relation}?f%5B#{key}%5D=#{scope.id}\">#{resource_class.human_attribute_name(link_data.to_s)}</a>".html_safe
else
raise 'Unsupported link data'
end
end | ruby | {
"resource": ""
} |
q9458 | Addresslogic.ClassMethods.apply_addresslogic | train | def apply_addresslogic(options = {})
n = options[:namespace]
options[:fields] ||= [
"#{n}street1".to_sym,
"#{n}street2".to_sym,
["#{n}city".to_sym, ["#{n}state".to_sym, "#{n}zip".to_sym]],
"#{n}country".to_sym
]
self.addresslogic_options = options
include Addresslogic::InstanceMethods
end | ruby | {
"resource": ""
} |
q9459 | Yargraph.UndirectedGraph.hamiltonian_cycles_dynamic_programming | train | def hamiltonian_cycles_dynamic_programming(operational_limit=nil)
stack = DS::Stack.new
return [] if @vertices.empty?
origin_vertex = @vertices.to_a[0]
hamiltonians = []
num_operations = 0
# This hash keeps track of subproblems that have already been
# solved. ie is there a path through vertices that ends in the
# endpoint
# Hash of [vertex_set,endpoint] => Array of Path objects.
# If no path is found, then the key is false
# The endpoint is not stored in the vertex set to make the programming
# easier.
dp_cache = {}
# First problem is the whole problem. We get the Hamiltonian paths,
# and then after reject those paths that are not cycles.
initial_vertex_set = Set.new(@vertices.reject{|v| v==origin_vertex})
initial_problem = [initial_vertex_set, origin_vertex]
stack.push initial_problem
while next_problem = stack.pop
vertices = next_problem[0]
destination = next_problem[1]
if dp_cache[next_problem]
# No need to do anything - problem already solved
elsif vertices.empty?
# The bottom of the problem. Only return a path
# if there is an edge between the destination and the origin
# node
if edge?(destination, origin_vertex)
path = Path.new [destination]
dp_cache[next_problem] = [path]
else
# Reached dead end
dp_cache[next_problem] = false
end
else
# This is an unsolved problem and there are at least 2 vertices in the vertex set.
# Work out which vertices in the set are neighbours
neighs = Set.new neighbours(destination)
possibilities = neighs.intersection(vertices)
if possibilities.length > 0
# There is still the possibility to go further into this unsolved problem
subproblems_unsolved = []
subproblems = []
possibilities.each do |new_destination|
new_vertex_set = Set.new(vertices.to_a.reject{|v| v==new_destination})
subproblem = [new_vertex_set, new_destination]
subproblems.push subproblem
if !dp_cache.key?(subproblem)
subproblems_unsolved.push subproblem
end
end
# if solved all the subproblems, then we can make a decision about this problem
if subproblems_unsolved.empty?
answers = []
subproblems.each do |problem|
paths = dp_cache[problem]
if paths == false
# Nothing to see here
else
# Add the found sub-paths to the set of answers
paths.each do |path|
answers.push Path.new(path+[destination])
end
end
end
if answers.empty?
# No paths have been found here
dp_cache[next_problem] = false
else
dp_cache[next_problem] = answers
end
else
# More problems to be solved before a decision can be made
stack.push next_problem #We have only delayed solving this problem, need to keep going in the future
subproblems_unsolved.each do |prob|
unless operational_limit.nil?
num_operations += 1
raise OperationalLimitReachedException if num_operations > operational_limit
end
stack.push prob
end
end
else
# No neighbours in the set, so reached a dead end, can go no further
dp_cache[next_problem] = false
end
end
end
if block_given?
dp_cache[initial_problem].each do |hpath|
yield hpath
end
return
else
return dp_cache[initial_problem]
end
end | ruby | {
"resource": ""
} |
q9460 | Overcloud.Node.introspect_node | train | def introspect_node(node_uuid)
workflow = 'tripleo.baremetal.v1.introspect'
input = { node_uuids: [node_uuid] }
execute_workflow(workflow, input, false)
end | ruby | {
"resource": ""
} |
q9461 | SiteAnalyzer.Site.add_pages_for_scan! | train | def add_pages_for_scan!
@pages_for_scan = []
@bad_pages = []
@pages.each do |page|
@bad_pages << page.page_url unless page.page_a_tags
next unless page.page_a_tags
page.home_a.each do |link|
@pages_for_scan << link
end
end
end | ruby | {
"resource": ""
} |
q9462 | SiteAnalyzer.Site.add_page | train | def add_page(url)
unless robot_txt_allowed?(url)
@scanned_pages << url
return nil
end
page = Page.new(url)
@pages << page
@scanned_pages << url
end | ruby | {
"resource": ""
} |
q9463 | SiteAnalyzer.Site.all_titles | train | def all_titles
result = []
@pages.each do |page|
result << [page.page_url, page.all_titles] if page.page_a_tags
end
result
end | ruby | {
"resource": ""
} |
q9464 | SiteAnalyzer.Site.all_descriptions | train | def all_descriptions
result = []
@pages.each do |page|
result << [page.page_url, page.meta_desc_content] if page.page_a_tags
end
result
end | ruby | {
"resource": ""
} |
q9465 | SiteAnalyzer.Site.all_h2 | train | def all_h2
result = []
@pages.each do |page|
result << [page.page_url, page.h2_text] unless page.page_a_tags
end
result
end | ruby | {
"resource": ""
} |
q9466 | SiteAnalyzer.Site.all_a | train | def all_a
result = []
@pages.each do |page|
next unless page.page_a_tags
page.page_a_tags.compact.each do |tag|
tag[0] = '-' unless tag[0]
tag[1] = '-' unless tag[1]
tag[2] = '-' unless tag[2]
result << [page.page_url, tag[0], tag[1], tag[2]]
end
end
result.compact
end | ruby | {
"resource": ""
} |
q9467 | SiteAnalyzer.Site.convert_to_valid | train | def convert_to_valid(url)
return nil if url =~ /.jpg$/i
url.insert(0, @main_url.first(5)) if url.start_with? '//'
link = URI(url)
main_page = URI(@main_url)
if link && link.scheme && link.scheme.empty?
link.scheme = main_page.scheme
elsif link.nil?
return nil
end
if link.scheme =~ /^http/
request = link.to_s
else
request = nil
end
request
rescue
link
end | ruby | {
"resource": ""
} |
q9468 | Sawaal.Selections.read_char | train | def read_char
input = $stdin.getch
return input unless input == "\e"
begin
Timeout.timeout(0.01) do
input += $stdin.getch
input += $stdin.getch
end
rescue Timeout::Error
# ignored
end
input
end | ruby | {
"resource": ""
} |
q9469 | TodoLint.Reporter.number_of_spaces | train | def number_of_spaces
todo.character_number - 1 - (todo.line.length - todo.line.lstrip.length)
end | ruby | {
"resource": ""
} |
q9470 | Swift.Adapter.create | train | def create record, resources
result = [resources].flatten.map do |resource|
resource = record.new(resource) unless resource.kind_of?(record)
result = execute(command_create(record), *resource.tuple.values_at(*record.header.insertable))
resource.tuple[record.header.serial] = result.insert_id if record.header.serial
resource
end
resources.kind_of?(Array) ? result : result.first
end | ruby | {
"resource": ""
} |
q9471 | Swift.Adapter.update | train | def update record, resources
result = [resources].flatten.map do |resource|
resource = record.new(resource) unless resource.kind_of?(record)
keys = resource.tuple.values_at(*record.header.keys)
# TODO: Name the key field(s) missing.
raise ArgumentError, "#{record} resource has incomplete key: #{resource.inspect}" \
unless keys.select(&:nil?).empty?
execute(command_update(record), *resource.tuple.values_at(*record.header.updatable), *keys)
resource
end
resources.kind_of?(Array) ? result : result.first
end | ruby | {
"resource": ""
} |
q9472 | Swift.Adapter.delete | train | def delete record, resources
result = [resources].flatten.map do |resource|
resource = record.new(resource) unless resource.kind_of?(record)
keys = resource.tuple.values_at(*record.header.keys)
# TODO: Name the key field(s) missing.
raise ArgumentError, "#{record} resource has incomplete key: #{resource.inspect}" \
unless keys.select(&:nil?).empty?
if result = execute(command_delete(record), *keys)
resource.freeze
end
result
end
resources.kind_of?(Array) ? result : result.first
end | ruby | {
"resource": ""
} |
q9473 | Swift.Adapter.prepare | train | def prepare record = nil, command
record ? Statement.new(record, command) : db.prepare(command)
end | ruby | {
"resource": ""
} |
q9474 | Swift.Adapter.execute | train | def execute command, *bind
start = Time.now
record, command = command, bind.shift if command.kind_of?(Class) && command < Record
record ? Result.new(record, db.execute(command, *bind)) : db.execute(command, *bind)
ensure
log_command(start, command, bind) if @trace
end | ruby | {
"resource": ""
} |
q9475 | Troy.Page.method_missing | train | def method_missing(name, *args, &block)
return meta[name.to_s] if meta.key?(name.to_s)
super
end | ruby | {
"resource": ""
} |
q9476 | Troy.Page.render | train | def render
ExtensionMatcher.new(path)
.default { content }
.on("html") { compress render_erb }
.on("md") { compress render_erb }
.on("erb") { compress render_erb }
.match
end | ruby | {
"resource": ""
} |
q9477 | Troy.Page.save_to | train | def save_to(path)
File.open(path, "w") do |file|
I18n.with_locale(meta.locale) do
file << render
end
end
end | ruby | {
"resource": ""
} |
q9478 | ZeevexThreadsafe::ThreadLocals.InstanceMethods._thread_local_clean | train | def _thread_local_clean
ids = Thread.list.map &:object_id
(@_thread_local_threads.keys - ids).each { |key| @_thread_local_threads.delete(key) }
end | ruby | {
"resource": ""
} |
q9479 | CaRuby.Properties.[]= | train | def []=(key, value)
return super if has_key?(key)
alt = alternate_key(key)
has_key?(alt) ? super(alt, value) : super
end | ruby | {
"resource": ""
} |
q9480 | CaRuby.Properties.load_properties | train | def load_properties(file)
raise ConfigurationError.new("Properties file not found: #{File.expand_path(file)}") unless File.exists?(file)
properties = {}
begin
YAML.load_file(file).each { |key, value| properties[key.to_sym] = value }
rescue
raise ConfigurationError.new("Could not read properties file #{file}: " + $!)
end
# Uncomment the following line to print detail properties.
#logger.debug { "#{file} properties:\n#{properties.pp_s}" }
# parse comma-delimited string values of array properties into arrays
@array_properties.each do |key|
value = properties[key]
if String === value then
properties[key] = value.split(/,\s*/)
end
end
# if the key is a merge property key, then perform a deep merge.
# otherwise, do a shallow merge of the property value into this property hash.
deep, shallow = properties.split { |key, value| @merge_properties.include?(key) }
merge!(deep, :deep)
merge!(shallow)
end | ruby | {
"resource": ""
} |
q9481 | SycLink.Infrastructure.copy_file_if_missing | train | def copy_file_if_missing(file, to_directory)
unless File.exists? File.join(to_directory, File.basename(file))
FileUtils.cp(file, to_directory)
end
end | ruby | {
"resource": ""
} |
q9482 | SycLink.Infrastructure.load_config | train | def load_config(file)
unless File.exists? file
File.open(file, 'w') do |f|
YAML.dump({ default_website: 'default' }, f)
end
end
YAML.load_file(file)
end | ruby | {
"resource": ""
} |
q9483 | RailsViewHelpers.DatetimeHelper.datetime_to_s | train | def datetime_to_s(date_or_datetime, format)
return '' if date_or_datetime.blank?
return date_or_datetime.to_s(format) if date_or_datetime.instance_of?(Date)
date_or_datetime.localtime.to_s(format)
end | ruby | {
"resource": ""
} |
q9484 | Authpwn.HttpTokenControllerInstanceMethods.authenticate_using_http_token | train | def authenticate_using_http_token
return if current_user
authenticate_with_http_token do |token_code, options|
auth = Tokens::Api.authenticate token_code
# NOTE: Setting the instance variable directly bypasses the session
# setup. Tokens are generally used in API contexts, so the session
# cookie would get ignored anyway.
@current_user = auth unless auth.kind_of? Symbol
end
end | ruby | {
"resource": ""
} |
q9485 | XES.Document.format | train | def format
raise FormatError.new(self) unless formattable?
REXML::Document.new.tap do |doc|
doc << REXML::XMLDecl.new
doc.elements << @log.format
end
end | ruby | {
"resource": ""
} |
q9486 | Polyseerio.Request.execute | train | def execute(method, *args)
new_args = args
@pre_request.each do |middleware|
new_args = middleware.call(*new_args)
end
path = new_args.empty? ? '' : new_args.shift
req = proc do ||
@resource[path].send(method, *new_args)
end
post = proc do |result|
@post_request.each do |middleware|
result = middleware.call(result)
end
result
end
Concurrent::Promise.new(&req).on_success(&post)
end | ruby | {
"resource": ""
} |
q9487 | ThumbnailHoverEffect.Image.render | train | def render(parameters = {})
has_thumbnail = parameters.fetch(:has_thumbnail, true)
effect_number = parameters.fetch(:effect_number, false)
thumbnail_template = self.get_template(effect_number)
if has_thumbnail
@attributes.map { |key, value| thumbnail_template["###{key}##"] &&= value }
thumbnail_template.gsub!('##url##', @url).html_safe
else
self.to_s.html_safe
end
end | ruby | {
"resource": ""
} |
q9488 | Geo.Itudes.distance | train | def distance other, units = :km
o = Itudes.new other
raise ArgumentError.new "operand must be lat-/longitudable" if (o.latitude.nil? || o.longitude.nil?)
dlat = Itudes.radians(o.latitude - @latitude)
dlon = Itudes.radians(o.longitude - @longitude)
lat1 = Itudes.radians(@latitude)
lat2 = Itudes.radians(o.latitude);
a = Math::sin(dlat/2)**2 + Math::sin(dlon/2)**2 * Math::cos(lat1) * Math::cos(lat2)
(RADIUS[units] * 2.0 * Math::atan2(Math.sqrt(a), Math.sqrt(1-a))).abs
end | ruby | {
"resource": ""
} |
q9489 | Checkdin.Promotions.promotions | train | def promotions(options={})
response = connection.get do |req|
req.url "promotions", options
end
return_error_or_body(response)
end | ruby | {
"resource": ""
} |
q9490 | Checkdin.Promotions.promotion_votes_leaderboard | train | def promotion_votes_leaderboard(id, options={})
response = connection.get do |req|
req.url "promotions/#{id}/votes_leaderboard", options
end
return_error_or_body(response)
end | ruby | {
"resource": ""
} |
q9491 | Fishbans.PlayerSkins.get_player_image | train | def get_player_image(username, type, size)
url = "http://i.fishbans.com/#{type}/#{username}/#{size}"
response = get(url, false)
ChunkyPNG::Image.from_blob(response.body)
end | ruby | {
"resource": ""
} |
q9492 | CopyCsv.ClassMethods.write_to_csv | train | def write_to_csv(file_name, mode = "w")
File.open(file_name, mode) do |file|
all.copy_csv(file)
end
end | ruby | {
"resource": ""
} |
q9493 | Gricer.BaseController.process_stats | train | def process_stats
@items = basic_collection
handle_special_fields
data = {
alternatives: [
{
type: 'spread',
uri: url_for(action: "spread_stats", field: params[:field], filters: params[:filters], only_path: true)
},
{
type: 'process'
}
],
from: @stat_from.to_time.utc.to_i * 1000,
thru: @stat_thru.to_time.utc.to_i * 1000,
step: @stat_step.to_i * 1000,
data: @items.stat(params[:field], @stat_from, @stat_thru, @stat_step)
}
if further_details.keys.include? params[:field]
filters = (params[:filters] || {})
filters[params[:field]] = '%{self}'
data[:detail_uri] = url_for(action: "process_stats", field: further_details[params[:field]], filters: filters, only_path: true)
end
render json: data
end | ruby | {
"resource": ""
} |
q9494 | Gricer.BaseController.spread_stats | train | def spread_stats
@items = basic_collection.between_dates(@stat_from, @stat_thru)
handle_special_fields
data = {
alternatives: [
{
type: 'spread'
},
{
type: 'process',
uri: url_for(action: "process_stats", field: params[:field], filters: params[:filters], only_path: true)
}
],
from: @stat_from.to_time.utc.to_i * 1000,
thru: @stat_thru.to_time.utc.to_i * 1000,
total: @items.count(:id),
data: @items.count_by(params[:field])
}
if further_details.keys.include? params[:field]
filters = (params[:filters] || {})
filters[params[:field]] = '%{self}'
data[:detail_uri] = url_for(action: "spread_stats", field: further_details[params[:field]], filters: filters, only_path: true)
end
render json: data
end | ruby | {
"resource": ""
} |
q9495 | Gricer.BaseController.guess_from_thru | train | def guess_from_thru
begin
@stat_thru = Time.parse(params[:thru]).to_date
rescue
end
begin
@stat_from = Time.parse(params[:from]).to_date
rescue
end
if @stat_from.nil?
if @stat_thru.nil?
@stat_thru = Time.now.localtime.to_date - 1.day
end
@stat_from = @stat_thru - 1.week + 1.day
else
if @stat_thru.nil?
@stat_thru = @stat_from + 1.week - 1.day
end
end
@stat_step = 1.day
duration = @stat_thru - @stat_from
if duration < 90
@stat_step = 12.hours
end
if duration < 30
@stat_step = 6.hour
end
if duration < 10
@stat_step = 1.hour
end
#if @stat_thru - @stat_from > 12.month
# @stat_step = 4.week
#end
end | ruby | {
"resource": ""
} |
q9496 | PutText.POFile.write_to | train | def write_to(io)
deduplicate
io.write(@header_entry.to_s)
@entries.each do |entry|
io.write("\n")
io.write(entry.to_s)
end
end | ruby | {
"resource": ""
} |
q9497 | CaRuby.Cache.clear | train | def clear
if @sticky.empty? then
@ckh.clear
else
@ckh.each { |klass, ch| ch.clear unless @sticky.include?(klass) }
end
end | ruby | {
"resource": ""
} |
q9498 | HS.Chapter.find_module | train | def find_module(slug)
modules.find { |m| m.slug.to_s == slug.to_s }
end | ruby | {
"resource": ""
} |
q9499 | LolitaPaypal.TransactionsController.answer | train | def answer
if request.post?
if ipn_notify.acknowledge
LolitaPaypal::Transaction.create_transaction(ipn_notify, payment_from_ipn, request)
end
render nothing: true
else
if payment_from_ipn
redirect_to payment_from_ipn.paypal_return_path
else
render text: I18n.t('lolita_paypal.wrong_request'), status: 400
end
end
ensure
LolitaPaypal.logger.info("[#{session_id}][#{payment_from_ipn && payment_from_ipn.id}][answer] #{params}")
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.