_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3
values | text stringlengths 66 10.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q9100 | Kharon.Processor.contains? | train | def contains?(key, values, required_values)
raise_error(type: "contains.values", required: required_values, key: key) if (values & required_values) != required_values
end | ruby | {
"resource": ""
} |
q9101 | Kharon.Processor.has_keys? | train | def has_keys?(key, required_keys)
raise_error(type: "contains.keys", required: required_keys, key: key) if (validator.datas[key].keys & required_keys) != required_keys
end | ruby | {
"resource": ""
} |
q9102 | LatoBlog.Interface::Tags.blog__clean_tag_parents | train | def blog__clean_tag_parents
tag_parents = LatoBlog::TagParent.all
tag_parents.map { |tp| tp.destroy if tp.tags.empty? }
end | ruby | {
"resource": ""
} |
q9103 | LatoBlog.Interface::Tags.blog__get_tags | train | def blog__get_tags(
order: nil,
language: nil,
search: nil,
page: nil,
per_page: nil
)
tags = LatoBlog::Tag.all
# apply filters
order = order && order == 'ASC' ? 'ASC' : 'DESC'
tags = _tags_filter_by_order(tags, order)
tags = _tags_filter_by_language(tags... | ruby | {
"resource": ""
} |
q9104 | LatoBlog.Interface::Tags.blog__get_category | train | def blog__get_category(id: nil, permalink: nil)
return {} unless id || permalink
if id
category = LatoBlog::Category.find_by(id: id.to_i)
else
category = LatoBlog::Category.find_by(meta_permalink: permalink)
end
category.serialize
end | ruby | {
"resource": ""
} |
q9105 | Redstruct.Set.random | train | def random(count: 1)
list = self.connection.srandmember(@key, count)
return nil if list.nil?
return count == 1 ? list[0] : ::Set.new(list)
end | ruby | {
"resource": ""
} |
q9106 | Redstruct.Set.difference | train | def difference(other, dest: nil)
destination = coerce_destination(dest)
results = if destination.nil?
::Set.new(self.connection.sdiff(@key, other.key))
else
self.connection.sdiffstore(destination.key, @key, other.key)
end
return results
end | ruby | {
"resource": ""
} |
q9107 | Redstruct.Set.intersection | train | def intersection(other, dest: nil)
destination = coerce_destination(dest)
results = if destination.nil?
::Set.new(self.connection.sinter(@key, other.key))
else
self.connection.sinterstore(destination.key, @key, other.key)
end
return results
end | ruby | {
"resource": ""
} |
q9108 | Redstruct.Set.union | train | def union(other, dest: nil)
destination = coerce_destination(dest)
results = if destination.nil?
::Set.new(self.connection.sunion(@key, other.key))
else
self.connection.sunionstore(destination.key, @key, other.key)
end
return results
end | ruby | {
"resource": ""
} |
q9109 | ExecEnv.Env.exec | train | def exec (*args, &block)
if @scope
@scope.instance_variables.each do |name|
instance_variable_set(name, @scope.instance_variable_get(name))
end
end
@ivars.each do |name, value|
instance_variable_set(name, value)
end
instance_exec(*args, &block)
... | ruby | {
"resource": ""
} |
q9110 | Scrapah.Scraper.process_appropriate | train | def process_appropriate(doc,cmd)
return process_regex(doc,cmd) if(cmd.is_a? Regexp)
return process_proc(doc,cmd) if(cmd.is_a? Proc)
if cmd.is_a?(String)
return process_xpath(doc,cmd) if cmd.start_with?("x|")
return process_css(doc,cmd) if cmd.start_with?("c|")
end
nil
end | ruby | {
"resource": ""
} |
q9111 | Derelict.Connection.validate! | train | def validate!
logger.debug "Starting validation for #{description}"
raise NotFound.new path unless File.exists? path
logger.info "Successfully validated #{description}"
self
end | ruby | {
"resource": ""
} |
q9112 | Seedsv.CsvSeed.seed_model | train | def seed_model(model_class, options={})
if model_class.count == 0 or options[:force]
table_name = options[:file_name] || model_class.table_name
puts "Seeding #{model_class.to_s.pluralize}..."
csv_file = @@csv_class.open(Rails.root + "db/csv/#{table_name}.csv", :headers => true)
see... | ruby | {
"resource": ""
} |
q9113 | Seedsv.CsvSeed.seed_from_csv | train | def seed_from_csv(migration_class, csv_file)
migration_class.transaction do
csv_file.each do |line_values|
record = migration_class.new
line_values.to_hash.keys.map{|attribute| record.send("#{attribute.strip}=",line_values[attribute].strip) rescue nil}
record.save(:validate =... | ruby | {
"resource": ""
} |
q9114 | Edoors.Particle.add_dsts | train | def add_dsts *dsts
dsts.each do |dst|
if dst.empty? or dst==Edoors::ACT_SEP or dst[0]==Edoors::PATH_SEP \
or dst=~/\/\?/ or dst=~/\/{2,}/ or dst=~/\s+/
raise Edoors::Exception.new "destination #{dst} is not acceptable"
end
... | ruby | {
"resource": ""
} |
q9115 | Edoors.Particle.set_dst! | train | def set_dst! a, d
@action = a
if d.is_a? Edoors::Iota
@dst = d
else
@dst = nil
_split_path! d
end
end | ruby | {
"resource": ""
} |
q9116 | Edoors.Particle.apply_link! | train | def apply_link! lnk
init! lnk.door
clear_dsts!
add_dsts *lnk.dsts
set_link_keys *lnk.keys
end | ruby | {
"resource": ""
} |
q9117 | Edoors.Particle.set_link_keys | train | def set_link_keys *args
@link_keys.clear if not @link_keys.empty?
args.compact!
args.each do |lf|
@link_keys << lf
end
@link_value = @payload.select { |k,v| @link_keys.include? k }
end | ruby | {
"resource": ""
} |
q9118 | Edoors.Particle.link_with? | train | def link_with? link
return true if link.value.nil?
link.value.keys.inject({}) { |h,k| h[k]=@payload[k] if @payload.has_key?(k); h }.eql? link.value
end | ruby | {
"resource": ""
} |
q9119 | Edoors.Particle.clear_merged! | train | def clear_merged! r=false
@merged.each do |p|
p.clear_merged! r
r.release_p p if r
end
@merged.clear
end | ruby | {
"resource": ""
} |
q9120 | PlayOverwatch.Scraper.sr | train | def sr
comp_div = @player_page.css('.competitive-rank > .h5')
return -1 if comp_div.empty?
content = comp_div.first.content
content.to_i if Integer(content) rescue -1
end | ruby | {
"resource": ""
} |
q9121 | PlayOverwatch.Scraper.main_qp | train | def main_qp
hero_img = hidden_mains_style.content.scan(/\.quickplay {.+?url\((.+?)\);/mis).flatten.first
hero_img.scan(/\/hero\/(.+?)\/career/i).flatten.first
end | ruby | {
"resource": ""
} |
q9122 | PlayOverwatch.Scraper.main_comp | train | def main_comp
hero_img = hidden_mains_style.content.scan(/\.competitive {.+?url\((.+?)\);/mis).flatten.first
hero_img.scan(/\/hero\/(.+?)\/career/i).flatten.first
end | ruby | {
"resource": ""
} |
q9123 | Spear.Request.to_xml | train | def to_xml(body)
root = @api_options[:root_element].nil? ? 'Request' : @api_options[:root_element]
body.to_xml(root: root, skip_instruct: true, skip_types: true)
end | ruby | {
"resource": ""
} |
q9124 | Ripl::Profiles.Runner.parse_option | train | def parse_option( option, argv )
if option =~ /(?:-p|--profile)=?(.*)/
Ripl::Profiles.load( ($1.empty? ? argv.shift.to_s : $1).split(':') )
else
super
end
end | ruby | {
"resource": ""
} |
q9125 | NewTime.NewTime.convert | train | def convert(point)
today = Date.new(year, month, day)
new_seconds = seconds + fractional + (minutes + hours * 60) * 60
# During daylight hours?
if hours >= 6 && hours < 18
start = NewTime.sunrise(today, point)
finish = NewTime.sunset(today, point)
new_start_hour = 6
... | ruby | {
"resource": ""
} |
q9126 | Smsified.Reporting.delivery_status | train | def delivery_status(options)
raise ArgumentError, 'an options Hash is required' if !options.instance_of?(Hash)
raise ArgumentError, ':sender_address is required' if options[:sender_address].nil? && @sender_address.nil?
options[:sender_address] = options[:sender_address] || @sender_address
... | ruby | {
"resource": ""
} |
q9127 | Disqussion.Threads.list | train | def list(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
response = get('threads/list', options)
end | ruby | {
"resource": ""
} |
q9128 | Disqussion.Threads.listPosts | train | def listPosts(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
thread = args.first
options.merge!(:thread => thread) if ([:ident, :link] & options.keys).empty?
response = get('threads/listPosts', options)
end | ruby | {
"resource": ""
} |
q9129 | Disqussion.Threads.remove | train | def remove(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
thread = args.first
options.merge!(:thread => thread) if ([:ident, :link] & options.keys).empty?
response = post('threads/remove', options)
end | ruby | {
"resource": ""
} |
q9130 | Ruote.MongoDbStorage.dump | train | def dump(type)
get_many(type).map{|d|d.to_s}.sort.join("\n")
end | ruby | {
"resource": ""
} |
q9131 | Kelp.Field.select_or_fill | train | def select_or_fill(field, value)
case field_type(field)
when :select
begin
select(value, :from => field)
rescue Capybara::ElementNotFound
raise Kelp::OptionNotFound,
"Field '#{field}' has no option '#{value}'"
end
when :fillable_field
fil... | ruby | {
"resource": ""
} |
q9132 | Kelp.Field.field_should_be_empty | train | def field_should_be_empty(field, scope={})
in_scope(scope) do
_field = nice_find_field(field)
if !(_field.nil? || _field.value.nil? || _field.value.strip == '')
raise Kelp::Unexpected,
"Expected field '#{field}' to be empty, but value is '#{_field.value}'"
end
e... | ruby | {
"resource": ""
} |
q9133 | Kelp.Field.field_value | train | def field_value(field)
element = find_field(field)
value = (element.tag_name == 'textarea') ? element.text : element.value
# If field value is an Array, take the first item
if value.class == Array
value = value.first
end
return value.to_s
end | ruby | {
"resource": ""
} |
q9134 | Kelp.Field.fields_should_contain | train | def fields_should_contain(field_values, scope={})
in_scope(scope) do
field_values.each do |field, value|
_field = find_field(field)
# For nil/empty, check for nil field or nil value
if value.nil? or value.strip.empty?
field_should_be_empty(field)
# If fi... | ruby | {
"resource": ""
} |
q9135 | Kelp.Field.field_type | train | def field_type(field)
select = all(:select, field).count
fillable = all(:fillable_field, field).count
count = select + fillable
case count
when 0
raise Kelp::FieldNotFound,
"No field with id, name, or label '#{field}' found"
when 1
return select > 0 ? :sele... | ruby | {
"resource": ""
} |
q9136 | Octo.KafkaBridge.create_message | train | def create_message(message)
begin
@producer.produce(JSON.dump(message), topic: @topic)
rescue Kafka::BufferOverflow
Octo.logger.error 'Buffer Overflow. Sleeping for 1s'
sleep 1
retry
end
end | ruby | {
"resource": ""
} |
q9137 | ActsAsReferred.InstanceMethods.create_referrer | train | def create_referrer
# will not respond to _get_reqref unless
# reqref injected in application-controller
#
if self.respond_to?(:_get_reqref)
if struct = _get_reqref
self.create_referee(
origin: struct.referrer_url,
request: ... | ruby | {
"resource": ""
} |
q9138 | Baha.Config.init_docker! | train | def init_docker!
Docker.options = @options
set_docker_url
LOG.debug { "Docker URL: #{Docker.url}"}
LOG.debug { "Docker Options: #{Docker.options.inspect}"}
Docker.validate_version!
end | ruby | {
"resource": ""
} |
q9139 | Logsly::Logging182::Appenders.Buffering.immediate_at= | train | def immediate_at=( level )
@immediate.clear
# get the immediate levels -- no buffering occurs at these levels, and
# a log message is written to the logging destination immediately
immediate_at =
case level
when String; level.split(',').map {|x| x.strip}
when Array; leve... | ruby | {
"resource": ""
} |
q9140 | MIPPeR.LinExpr.add | train | def add(other)
case other
when LinExpr
@terms.merge!(other.terms) { |_, c1, c2| c1 + c2 }
when Variable
if @terms.key? other
@terms[other] += 1.0
else
@terms[other] = 1.0
end
else
fail TypeError
end
self
end | ruby | {
"resource": ""
} |
q9141 | MIPPeR.LinExpr.inspect | train | def inspect
@terms.map do |var, coeff|
# Skip if the coefficient is zero or the value is zero
value = var.value
next if coeff == 0 || value == 0 || value == false
coeff == 1 ? var.name : "#{var.name} * #{coeff}"
end.compact.join(' + ')
end | ruby | {
"resource": ""
} |
q9142 | NsOptions.Option.value | train | def value
val = self.lazy_proc?(@value) ? self.coerce(@value.call) : @value
val.respond_to?(:returned_value) ? val.returned_value : val
end | ruby | {
"resource": ""
} |
q9143 | Demolisher.Node.method_missing | train | def method_missing(meth, *args, &block) # :nodoc:
xpath = _xpath_for_element(meth.to_s, args.shift)
return nil if xpath.empty?
if block_given?
xpath.each_with_index do |node, idx|
@nodes.push(node)
case block.arity
when 1
yield idx
when 2
... | ruby | {
"resource": ""
} |
q9144 | XML.Mapping.write_xml | train | def write_xml(options = { mapping: :_default })
xml = save_to_xml(options)
formatter = REXML::Formatters::Pretty.new
formatter.compact = true
io = ::StringIO.new
formatter.write(xml, io)
io.string
end | ruby | {
"resource": ""
} |
q9145 | CertMunger.ClassMethods.to_cert | train | def to_cert(raw_cert)
logger.debug "CertMunger raw_cert:\n#{raw_cert}"
new_cert = build_cert(raw_cert)
logger.debug "CertMunger reformatted_cert:\n#{new_cert}"
logger.debug 'Returning OpenSSL::X509::Certificate.new on new_cert'
OpenSSL::X509::Certificate.new new_cert
end | ruby | {
"resource": ""
} |
q9146 | CertMunger.ClassMethods.build_cert | train | def build_cert(raw_cert)
tmp_cert = ['-----BEGIN CERTIFICATE-----']
cert_contents = if raw_cert.lines.count == 1
one_line_contents(raw_cert)
else
multi_line_contents(raw_cert)
end
tmp_cert << cert_contents.flat... | ruby | {
"resource": ""
} |
q9147 | CertMunger.ClassMethods.multi_line_contents | train | def multi_line_contents(raw_cert)
cert_contents = raw_cert.split(/[-](.*)[-]/)[2]
cert_contents.lines.map do |line|
line.lstrip.squeeze(' ').split(' ')
end
end | ruby | {
"resource": ""
} |
q9148 | Love.ResourceURI.append_query | train | def append_query(base_uri, added_params = {})
base_params = base_uri.query ? CGI.parse(base_uri.query) : {}
get_params = base_params.merge(added_params.stringify_keys)
base_uri.dup.tap do |uri|
assignments = get_params.map do |k, v|
case v
when Array; v.map { |val| "#{::C... | ruby | {
"resource": ""
} |
q9149 | Love.Client.connection | train | def connection
@connection ||= Net::HTTP.new(TENDER_API_HOST, Net::HTTP.https_default_port).tap do |http|
http.use_ssl = true
# http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.start
end
end | ruby | {
"resource": ""
} |
q9150 | Love.Client.paged_each | train | def paged_each(uri, list_key, options = {}, &block)
query_params = {}
query_params[:since] = options[:since].to_date.to_s(:db) if options[:since]
query_params[:page] = [options[:start_page].to_i, 1].max rescue 1
results = []
initial_result = get(append_query(uri, query_params))
# D... | ruby | {
"resource": ""
} |
q9151 | QuickDry.QuickDryController.serialize | train | def serialize stuff
if stuff.is_a? Array or stuff.is_a? ActiveRecord::Relation
json = render_to_string json:QuickDryArraySerializer.new(stuff, root:get_model.model_name.route_key )
hash = JSON.parse(json)
temp = []
if hash[get_model.model_name.route_key].first.has_key? get_model.model_name.route_key
... | ruby | {
"resource": ""
} |
q9152 | QuickDry.QuickDryController.get_paged_search_results | train | def get_paged_search_results(params,user:nil,model:nil)
params[:per_page] = 10 if params[:per_page].blank?
params[:page] = 1 if params[:page].blank?
# a ghetto user check, but for some reason a devise user is not a devise user...
user = User.new if user.blank? or !user.class.to_s == User.to_s
# get the ... | ruby | {
"resource": ""
} |
q9153 | SimpleCommander.UI.converse | train | def converse(prompt, responses = {})
i, commands = 0, responses.map { |_key, value| value.inspect }.join(',')
statement = responses.inject '' do |inner_statement, (key, value)|
inner_statement <<
(
(i += 1) == 1 ?
%(if response is "#{value}" then\n) :
%(else if ... | ruby | {
"resource": ""
} |
q9154 | RailsIdentity.ApplicationHelper.authorized_for? | train | def authorized_for?(obj)
logger.debug("Checking to see if authorized to access object")
if @auth_user.nil?
# :nocov:
return false
# :nocov:
elsif @auth_user.role >= Roles::ADMIN
return true
elsif obj.is_a? User
return obj == @auth_user
else
r... | ruby | {
"resource": ""
} |
q9155 | RailsIdentity.ApplicationHelper.get_token_payload | train | def get_token_payload(token)
# Attempt to decode without verifying. May raise DecodeError.
decoded = JWT.decode token, nil, false
payload = decoded[0]
# At this point, we know that the token is not expired and
# well formatted. Find out if the payload is well defined.
i... | ruby | {
"resource": ""
} |
q9156 | RailsIdentity.ApplicationHelper.verify_token | train | def verify_token(token)
logger.debug("Verifying token: #{token}")
# First get the payload of the token. This will also verify whether
# or not the token is welformed.
payload = get_token_payload(token)
# Next, the payload should define user UUID and session UUID.
user_u... | ruby | {
"resource": ""
} |
q9157 | RailsIdentity.ApplicationHelper.get_token | train | def get_token(required_role: Roles::PUBLIC)
token = params[:token]
# Look up the cache. If present, use it and skip the verification.
# Use token itself (and not a session UUID) as part of the key so
# it can be considered *verified*.
@auth_session = Cache.get(kind: :session, to... | ruby | {
"resource": ""
} |
q9158 | RailsIdentity.ApplicationHelper.get_api_key | train | def get_api_key(required_role: Roles::PUBLIC)
api_key = params[:api_key]
if api_key.nil?
# This case is not likely, but as a safeguard in case migration
# has not gone well.
# :nocov:
raise UNAUTHORIZED_ERROR, "Invalid api key"
# :nocov:
end
... | ruby | {
"resource": ""
} |
q9159 | RailsIdentity.ApplicationHelper.get_auth | train | def get_auth(required_role: Roles::USER)
if params[:token]
get_token(required_role: required_role)
else
get_api_key(required_role: required_role)
end
end | ruby | {
"resource": ""
} |
q9160 | Disqussion.Reactions.details | train | def details(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
if args.length == 2
options.merge!(:reaction => args[0])
options.merge!(:forum => args[1])
response = get('reactions/details', options)
else
puts "#{Kernel.caller.first}: Reactions.details expects 2 argu... | ruby | {
"resource": ""
} |
q9161 | BiolaLogs.ControllerExtensions.append_info_to_payload | train | def append_info_to_payload(payload)
super
payload[:session_id] = request.session_options[:id]
payload[:uuid] = request.uuid
payload[:host] = request.host
end | ruby | {
"resource": ""
} |
q9162 | GemFootprintAnalyzer.ChildContext.start | train | def start
RequireSpy.spy_require(transport)
error = try_require(require_string)
return transport.done_and_wait_for_ack unless error
transport.exit_with_error(error)
exit(1)
end | ruby | {
"resource": ""
} |
q9163 | Gumdrop.SpecialContentList.find | train | def find(uri)
_try_variations_of(uri) do |path|
content= get path
return [content] unless content.nil?
end unless uri.nil?
[]
end | ruby | {
"resource": ""
} |
q9164 | Bixby.JsonRequest.to_s | train | def to_s(include_params=true)
s = []
s << "JsonRequest:#{self.object_id}"
s << " operation: #{self.operation}"
s << " params: " + MultiJson.dump(self.params) if include_params
s.join("\n")
end | ruby | {
"resource": ""
} |
q9165 | BalancingAct.Server.valid_params? | train | def valid_params?(name, size)
return raise TypeError.new("A 'name' should be a string") if name.class != String
return raise TypeError.new("A 'size' should be an integer") if size.class != Integer
true
end | ruby | {
"resource": ""
} |
q9166 | RsUserPolicy.AuditLog.add_entry | train | def add_entry(email, account, action, changes)
@audit_log[email] = [] unless audit_log[email]
@audit_log[email] << {
:account => account,
:action => action,
:changes => changes
}
end | ruby | {
"resource": ""
} |
q9167 | Slackdraft.Base.send! | train | def send!
# Send the request
request = HTTParty.post(self.target, :body => {
:payload => generate_payload.to_json
})
unless request.code.eql? 200
false
end
true
end | ruby | {
"resource": ""
} |
q9168 | Templatr.Template.common_fields_attributes= | train | def common_fields_attributes=(nested_attributes)
nested_attributes.values.each do |attributes|
common_field = common_fields.find {|field| field.id.to_s == attributes[:id] && attributes[:id].present? } || common_fields.build
assign_to_or_mark_for_destruction(common_field, attributes, true, {})
... | ruby | {
"resource": ""
} |
q9169 | ChromeDebugger.Document.start_time | train | def start_time
@start_time ||= @events.select { |event|
event.is_a?(RequestWillBeSent)
}.select { |event|
event.request['url'] == @url
}.map { |event|
event.timestamp
}.first
end | ruby | {
"resource": ""
} |
q9170 | ChromeDebugger.Document.encoded_bytes | train | def encoded_bytes(resource_type)
@events.select {|e|
e.is_a?(ResponseReceived) && e.resource_type == resource_type
}.map { |e|
e.request_id
}.map { |request_id|
data_received_for_request(request_id)
}.flatten.inject(0) { |bytes_sum, n| bytes_sum + n.encoded_data_length }
... | ruby | {
"resource": ""
} |
q9171 | ChromeDebugger.Document.bytes | train | def bytes(resource_type)
@events.select {|e|
e.is_a?(ResponseReceived) && e.resource_type == resource_type
}.map { |e|
e.request_id
}.map { |request_id|
data_received_for_request(request_id)
}.flatten.inject(0) { |bytes_sum, n| bytes_sum + n.data_length }
end | ruby | {
"resource": ""
} |
q9172 | ChromeDebugger.Document.request_count_by_resource | train | def request_count_by_resource(resource_type)
@events.select {|n|
n.is_a?(ResponseReceived) && n.resource_type == resource_type
}.size
end | ruby | {
"resource": ""
} |
q9173 | Scholar.Search.to_hash | train | def to_hash
hash = {}
instance_variables.each do |v|
hash[v.to_s[1..-1].to_sym] = instance_variable_get(v)
end
hash[:results].each do |c|
hash[:results][hash[:results].index(c)] = c.to_hash
end
hash
end | ruby | {
"resource": ""
} |
q9174 | SlackBotManager.Commands.on_close | train | def on_close(data, *args)
options = args.extract_options!
options[:code] ||= (data && data.code) || '1000'
disconnect
fail SlackBotManager::ConnectionRateLimited if %w(1008 429).include?(options[:code].to_s)
end | ruby | {
"resource": ""
} |
q9175 | OxMlk.ClassMethods.ox_attr | train | def ox_attr(name,o={},&block)
new_attr = Attr.new(name, o.reverse_merge(:tag_proc => @tag_proc),&block)
@ox_attrs << new_attr
ox_accessor new_attr.accessor
end | ruby | {
"resource": ""
} |
q9176 | OxMlk.ClassMethods.ox_elem | train | def ox_elem(name,o={},&block)
new_elem = Elem.new(name, o.reverse_merge(:tag_proc => @tag_proc),&block)
@ox_elems << new_elem
ox_accessor new_elem.accessor
end | ruby | {
"resource": ""
} |
q9177 | OxMlk.ClassMethods.ox_tag | train | def ox_tag(tag=nil,&block)
raise 'you can only set tag or a block, not both.' if tag && block
@base_tag ||= self.to_s.split('::').last
@ox_tag ||= case tag
when String
tag
when Proc, Symbol, nil
@tag_proc = (block || tag || :to_s).to_proc
@tag_proc.call(@base_tag) ... | ruby | {
"resource": ""
} |
q9178 | OxMlk.ClassMethods.from_xml | train | def from_xml(data)
xml = XML::Node.from(data)
raise 'invalid XML' unless xml.name == ox_tag
returning new do |ox|
(ox_attrs + ox_elems).each {|e| ox.send(e.setter,e.from_xml(xml))}
ox.send(:after_parse) if ox.respond_to?(:after_parse)
end
end | ruby | {
"resource": ""
} |
q9179 | OxMlk.ClassMethods.to_xml | train | def to_xml(data)
ox = XML::Node.new(ox_tag)
wrappers = {}
ox_elems.each do |elem|
if elem.in
wrappers[elem.in] ||= XML::Node.new elem.in
elem.to_xml(data).each {|e| wrappers[elem.in] << e}
else
elem.to_xml(data).each {|e| ox << e}
end
... | ruby | {
"resource": ""
} |
q9180 | Probably.Distribution.pick | train | def pick
tst = rand
sum = 0
@map.each do |value, prob|
sum += prob
return value,prob if tst < sum
end
return nil
end | ruby | {
"resource": ""
} |
q9181 | Probably.Distribution.variance | train | def variance
expected = self.expectation
@map.reduce(0) {|sum, (value,p)|
tmp = (value.to_f - expectation)
sum + tmp * tmp * p
}
end | ruby | {
"resource": ""
} |
q9182 | Smoke.Origin.transform | train | def transform(*keys)
raise ArgumentError, "requires a block" unless block_given?
keys.each do |key|
items.each do |item|
item[key] = yield(item[key]) || item[key]
end
end
end | ruby | {
"resource": ""
} |
q9183 | Smoke.Origin.method_missing | train | def method_missing(symbol, *args, &block)
ivar = "@#{symbol}"
if args.empty?
return instance_variable_get(ivar) || super
else
instance_variable_set(ivar, args.pop)
end
return self
end | ruby | {
"resource": ""
} |
q9184 | Smoke.Origin.sort | train | def sort(key)
@items = @items.sort_by{|i| i[key] }
rescue NoMethodError => e
Smoke.log.info "You're trying to sort by \"#{key}\" but it does not exist in your item set"
end | ruby | {
"resource": ""
} |
q9185 | Smoke.Origin.keep | train | def keep(key, matcher)
@items.reject! {|i| (i[key] =~ matcher) ? false : true }
end | ruby | {
"resource": ""
} |
q9186 | Smoke.Origin.discard | train | def discard(key, matcher)
@items.reject! {|i| (i[key] =~ matcher) ? true : false }
end | ruby | {
"resource": ""
} |
q9187 | Roy.Context.prepare! | train | def prepare!(env)
@env = env
@request = Rack::Request.new(env)
@response = Rack::Response.new
@headers = @response.header
@params = @request.GET.merge(@request.POST)
@params.default_proc = proc do |hash, key|
hash[key.to_s] if Symbol === key
end
end | ruby | {
"resource": ""
} |
q9188 | Slackdraft.Attachment.generate_attachment | train | def generate_attachment
payload = {}
payload[:fallback] = self.fallback unless self.fallback.nil?
payload[:color] = self.color unless self.color.nil?
payload[:pretext] = self.pretext unless self.pretext.nil?
payload[:author_name] = self.author_name unles... | ruby | {
"resource": ""
} |
q9189 | DCPU16.Screen.frame | train | def frame
return @frame if @frame
chars = []
# 4 corners
chars << Char.new(0x23, @x_offset - 1, @y_offset - 1) # TopLeft
chars << Char.new(0x23, @x_offset + @width, @y_offset - 1) # TopRight
chars << Char.new(0x23, @x_offset - 1, @y_offset + @height) #... | ruby | {
"resource": ""
} |
q9190 | DCPU16.Screen.update | train | def update(offset, value)
return unless (memory_offset..memory_offset_end).include?(offset)
@to_s = nil
diff = offset - @memory_offset
h = diff / @width
w = diff % @width
@chars[diff] = Char.new(value, w + @x_offset, h + @y_offset)
print @chars[diff]
changed
... | ruby | {
"resource": ""
} |
q9191 | Bumbleworks.Configuration.add_storage_adapter | train | def add_storage_adapter(adapter)
raise ArgumentError, "#{adapter} is not a Bumbleworks storage adapter" unless
[:driver, :use?, :new_storage, :allow_history_storage?, :storage_class, :display_name].all? { |m| adapter.respond_to?(m) }
@storage_adapters << adapter
@storage_adapters
end | ruby | {
"resource": ""
} |
q9192 | Bumbleworks.Configuration.storage_adapter | train | def storage_adapter
@storage_adapter ||= begin
all_adapters = storage_adapters
raise UndefinedSetting, "No storage adapters configured" if all_adapters.empty?
adapter = all_adapters.detect do |potential_adapter|
potential_adapter.use?(storage)
end
raise UndefinedS... | ruby | {
"resource": ""
} |
q9193 | Bumbleworks.Configuration.look_up_configured_path | train | def look_up_configured_path(path_type, options = {})
return @cached_paths[path_type] if @cached_paths.has_key?(path_type)
if user_defined_path = user_configured_path(path_type)
if path_resolves?(user_defined_path, :file => options[:file])
return user_defined_path
else
rai... | ruby | {
"resource": ""
} |
q9194 | HashKeywordArgs.Hash.keyword_args | train | def keyword_args(*args)
argshash = args[-1].is_a?(Hash) ? args.pop : {}
argshash = args.hashify(:optional).merge(argshash)
others_OK = argshash.delete(:OTHERS)
ret = {}
# defaults, required, and checked
required = []
check = {}
argshash.each do |key, val|
# const... | ruby | {
"resource": ""
} |
q9195 | ActionPager.Pager.near_pages | train | def near_pages
@near_pages ||= begin
if current_page <= near + 1
upper_page = shown_page_count >= last_page ? last_page : shown_page_count
1..upper_page
elsif current_page >= last_page - near - 1
bottom_page = last_page - shown_page_count + 1
(bottom_page > ... | ruby | {
"resource": ""
} |
q9196 | WallLeecher.Leecher.prep_file | train | def prep_file(url, dir)
parts = url.split('/')
File.join(dir, parts[-1])
end | ruby | {
"resource": ""
} |
q9197 | WallLeecher.Fetcher.get | train | def get
schedule do
inc_io
@@log.info("Requesting: #{@url}")
http = EM::HttpRequest.new(@url).get :redirects => 5
http.callback do |h|
succeed http.response
dec_io
end
http.headers do |headers|
... | ruby | {
"resource": ""
} |
q9198 | Npolar::Api::Client.JsonApiClient.valid | train | def valid(condition=true)
all.select {|d| condition == valid?(d) }.map {|d| model.class.new(d)}
end | ruby | {
"resource": ""
} |
q9199 | Npolar::Api::Client.JsonApiClient.multi_request | train | def multi_request(method, paths, body=nil, param=nil, header=nil)
@multi = true
# Response storage, if not already set
if @responses.nil?
@responses = []
end
# Handle one or many paths
if paths.is_a? String or paths.is_a? URI
paths = [paths]
end
# Handl... | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.