_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3
values | text stringlengths 66 10.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q6000 | Garcon.RubyExecutor.post | train | def post(*args, &task)
raise ArgumentError.new('no block given') unless block_given?
mutex.synchronize do
# If the executor is shut down, reject this task
return handle_fallback(*args, &task) unless running?
execute(*args, &task)
true
end
end | ruby | {
"resource": ""
} |
q6001 | Garcon.RubyExecutor.kill | train | def kill
mutex.synchronize do
break if shutdown?
stop_event.set
kill_execution
stopped_event.set
end
true
end | ruby | {
"resource": ""
} |
q6002 | Taxamatch.Base.taxamatch | train | def taxamatch(str1, str2, return_boolean = true)
preparsed_1 = @parser.parse(str1)
preparsed_2 = @parser.parse(str2)
match = taxamatch_preparsed(preparsed_1, preparsed_2) rescue nil
return_boolean ? (!!match && match['match']) : match
end | ruby | {
"resource": ""
} |
q6003 | Taxamatch.Base.taxamatch_preparsed | train | def taxamatch_preparsed(preparsed_1, preparsed_2)
result = nil
if preparsed_1[:uninomial] && preparsed_2[:uninomial]
result = match_uninomial(preparsed_1, preparsed_2)
end
if preparsed_1[:genus] && preparsed_2[:genus]
result = match_multinomial(preparsed_1, preparsed_2)
e... | ruby | {
"resource": ""
} |
q6004 | CLIntegracon.Configuration.hook_into | train | def hook_into test_framework
adapter = self.class.adapters[test_framework]
raise ArgumentError.new "No adapter for test framework #{test_framework}" if adapter.nil?
require adapter
end | ruby | {
"resource": ""
} |
q6005 | Gazette.Client.parse_response_for | train | def parse_response_for(response)
case response
when Net::HTTPOK, Net::HTTPCreated then return Response::Success.new(response)
when Net::HTTPForbidden then raise Response::InvalidCredentials
when Net::HTTPInternalServerError then raise Response::ServerError
else raise Response::Unkn... | ruby | {
"resource": ""
} |
q6006 | Gazette.Client.request | train | def request(method, params = {})
http = Net::HTTP.new(Api::ADDRESS, (@https ? 443 : 80))
http.use_ssl = @https
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new(Api::ENDPOINT+method.to_s)
request.basic_auth @username, @password
request.set_form_data(params)
... | ruby | {
"resource": ""
} |
q6007 | ICU.RatedTournament.rate! | train | def rate!(opt={})
# The original algorithm (version 0).
max_iterations = [30, 1]
phase_2_bonuses = true
update_bonuses = false
threshold = 0.5
# New versions of the algorithm.
version = opt[:version].to_i
if version >= 1
# See http://ratings.icu.ie/articl... | ruby | {
"resource": ""
} |
q6008 | ICU.RatedTournament.calculate_bonuses | train | def calculate_bonuses
@player.values.select{ |p| p.respond_to?(:bonus) }.inject(0) { |t,p| t + (p.calculate_bonus ? 1 : 0) }
end | ruby | {
"resource": ""
} |
q6009 | Jinx.Migratable.migrate_references | train | def migrate_references(row, migrated, target, proc_hash=nil)
# migrate the owner
migratable__migrate_owner(row, migrated, target, proc_hash)
# migrate the remaining attributes
migratable__set_nonowner_references(migratable_independent_attributes, row, migrated, proc_hash)
migratable__set_n... | ruby | {
"resource": ""
} |
q6010 | Progress.Progress::Bar.tick | train | def tick(step = nil)
if step.nil?
@current += 1
else
@current = step
end
percent = @current.to_f/ @max.to_f
if percent - @last_report > 1.to_f/@num_reports.to_f
report
@last_report=percent
end
nil
end | ruby | {
"resource": ""
} |
q6011 | Progress.Progress::Bar.report | train | def report
percent = @current.to_f/ @max.to_f
percent = 0.001 if percent < 0.001
if @desc != ""
indicator = @desc + ": "
else
indicator = "Progress "
end
indicator += "["
10.times{|i|
if i < percent * 10 then
indicator += "."
else
... | ruby | {
"resource": ""
} |
q6012 | I18n::Processes.SplitKey.key_parts | train | def key_parts(key, &block)
return enum_for(:key_parts, key) unless block
nesting = PARENS
counts = PARENS_ZEROS # dup'd later if key contains parenthesis
delim = '.'
from = to = 0
key.each_char do |char|
if char == delim && PARENS_ZEROS == counts
block.yield k... | ruby | {
"resource": ""
} |
q6013 | Lightstreamer.Subscription.process_stream_data | train | def process_stream_data(line)
return true if process_update_message UpdateMessage.parse(line, id, items, fields)
return true if process_overflow_message OverflowMessage.parse(line, id, items)
return true if process_end_of_snapshot_message EndOfSnapshotMessage.parse(line, id, items)
end | ruby | {
"resource": ""
} |
q6014 | Lightstreamer.Subscription.control_request_options | train | def control_request_options(action, options = nil)
case action.to_sym
when :start
start_control_request_options options
when :unsilence
{ LS_session: @session.session_id, LS_op: :start, LS_table: id }
when :stop
{ LS_session: @session.session_id, LS_op: :delete, LS_table:... | ruby | {
"resource": ""
} |
q6015 | Chaintown.Steps.inherited | train | def inherited(subclass)
[:steps, :failed_steps].each do |inheritable_attribute|
instance_var = "@#{inheritable_attribute}"
subclass.instance_variable_set(instance_var, instance_variable_get(instance_var).dup || [])
end
end | ruby | {
"resource": ""
} |
q6016 | MovingsignApi.Sign.show_text | train | def show_text(text, options = {})
cmd = WriteTextCommand.new
cmd.display_pause = options[:display_pause] if options[:display_pause]
cmd.text = text
send_command cmd
end | ruby | {
"resource": ""
} |
q6017 | MovingsignApi.Sign.send_command | train | def send_command(command)
SerialPort.open(self.device_path, 9600, 8, 1) do |port|
# flush anything existing on the port
port.flush
flush_read_buffer(port)
byte_string = command.to_bytes.pack('C*')
begin
while byte_string && byte_string.length != 0
co... | ruby | {
"resource": ""
} |
q6018 | Aims.Wurtzite.get_bulk | train | def get_bulk
# The lattice constant
a = lattice_const
c = 1.63299*a # sqrt(8/3)a
# The atoms on a HCP
as1 = Atom.new(0,0,0,'As')
as2 = as1.displace(0.5*a, 0.33333*a, 0.5*c)
ga1 = Atom.new(0.0, 0.0, c*0.386, 'Ga')
ga2 = ga1.displace(0.5*a,0.33333*a, 0.5*c)
# The l... | ruby | {
"resource": ""
} |
q6019 | TriglavClient.JobMessagesApi.fetch_job_messages | train | def fetch_job_messages(offset, job_id, opts = {})
data, _status_code, _headers = fetch_job_messages_with_http_info(offset, job_id, opts)
return data
end | ruby | {
"resource": ""
} |
q6020 | Roroacms.AdminController.authorize_admin_access | train | def authorize_admin_access
Setting.reload_settings
if !check_controller_against_user(params[:controller].sub('roroacms/admin/', '')) && params[:controller] != 'roroacms/admin/dashboard' && params[:controller].include?('roroacms')
redirect_to admin_path, flash: { error: I18n.t("controllers.admin.misc... | ruby | {
"resource": ""
} |
q6021 | Jinx.Introspector.wrap_java_property | train | def wrap_java_property(property)
pd = property.property_descriptor
if pd.property_type == Java::JavaLang::String.java_class then
wrap_java_string_property(property)
elsif pd.property_type == Java::JavaUtil::Date.java_class then
wrap_java_date_property(property)
end
end | ruby | {
"resource": ""
} |
q6022 | Jinx.Introspector.wrap_java_string_property | train | def wrap_java_string_property(property)
ra, wa = property.accessors
jra, jwa = property.java_accessors
# filter the attribute writer
define_method(wa) do |value|
stdval = Math.numeric?(value) ? value.to_s : value
send(jwa, stdval)
end
logger.debug { "Filtered #{qp} #{... | ruby | {
"resource": ""
} |
q6023 | Jinx.Introspector.wrap_java_date_property | train | def wrap_java_date_property(property)
ra, wa = property.accessors
jra, jwa = property.java_accessors
# filter the attribute reader
define_method(ra) do
value = send(jra)
Java::JavaUtil::Date === value ? value.to_ruby_date : value
end
# filter the attribu... | ruby | {
"resource": ""
} |
q6024 | Jinx.Introspector.alias_property_accessors | train | def alias_property_accessors(property)
# the Java reader and writer accessor method symbols
jra, jwa = property.java_accessors
# strip the Java reader and writer is/get/set prefix and make a symbol
alias_method(property.reader, jra)
alias_method(property.writer, jwa)
end | ruby | {
"resource": ""
} |
q6025 | Jinx.Introspector.add_java_property | train | def add_java_property(pd)
# make the attribute metadata
prop = create_java_property(pd)
add_property(prop)
# the property name is an alias for the standard attribute
pa = prop.attribute
# the Java property name as an attribute symbol
ja = pd.name.to_sym
delegate_to_proper... | ruby | {
"resource": ""
} |
q6026 | Jinx.Introspector.delegate_to_property | train | def delegate_to_property(aliaz, property)
ra, wa = property.accessors
if aliaz == ra then raise MetadataError.new("Cannot delegate #{self} #{aliaz} to itself.") end
define_method(aliaz) { send(ra) }
define_method("#{aliaz}=".to_sym) { |value| send(wa, value) }
register_property_alias(aliaz... | ruby | {
"resource": ""
} |
q6027 | Tara.Archive.create | train | def create
Dir.mktmpdir do |tmp_dir|
project_dir = Pathname.new(@config[:app_dir])
package_dir = Pathname.new(tmp_dir)
build_dir = Pathname.new(@config[:build_dir])
copy_source(project_dir, package_dir)
copy_executables(project_dir, package_dir)
create_gem_shims(pac... | ruby | {
"resource": ""
} |
q6028 | RightAMQP.HABrokerClient.identity_parts | train | def identity_parts(id)
@brokers.each do |b|
return [b.host, b.port, b.index, priority(b.identity)] if b.identity == id || b.alias == id
end
[nil, nil, nil, nil]
end | ruby | {
"resource": ""
} |
q6029 | RightAMQP.HABrokerClient.get | train | def get(id)
@brokers.each { |b| return b.identity if b.identity == id || b.alias == id }
nil
end | ruby | {
"resource": ""
} |
q6030 | RightAMQP.HABrokerClient.connected | train | def connected
@brokers.inject([]) { |c, b| if b.connected? then c << b.identity else c end }
end | ruby | {
"resource": ""
} |
q6031 | RightAMQP.HABrokerClient.failed | train | def failed
@brokers.inject([]) { |c, b| b.failed? ? c << b.identity : c }
end | ruby | {
"resource": ""
} |
q6032 | RightAMQP.HABrokerClient.connect | train | def connect(host, port, index, priority = nil, force = false, &blk)
identity = self.class.identity(host, port)
existing = @brokers_hash[identity]
if existing && existing.usable? && !force
logger.info("Ignored request to reconnect #{identity} because already #{existing.status.to_s}")
fa... | ruby | {
"resource": ""
} |
q6033 | RightAMQP.HABrokerClient.subscribe | train | def subscribe(queue, exchange = nil, options = {}, &blk)
identities = []
brokers = options.delete(:brokers)
each(:usable, brokers) { |b| identities << b.identity if b.subscribe(queue, exchange, options, &blk) }
logger.info("Could not subscribe to queue #{queue.inspect} on exchange #{exchange.ins... | ruby | {
"resource": ""
} |
q6034 | RightAMQP.HABrokerClient.unsubscribe | train | def unsubscribe(queue_names, timeout = nil, &blk)
count = each(:usable).inject(0) do |c, b|
c + b.queues.inject(0) { |c, q| c + (queue_names.include?(q.name) ? 1 : 0) }
end
if count == 0
blk.call if blk
else
handler = CountedDeferrable.new(count, timeout)
handler.... | ruby | {
"resource": ""
} |
q6035 | RightAMQP.HABrokerClient.queue_status | train | def queue_status(queue_names, timeout = nil, &blk)
count = 0
status = {}
each(:connected) { |b| b.queues.each { |q| count += 1 if queue_names.include?(q.name) } }
if count == 0
blk.call(status) if blk
else
handler = CountedDeferrable.new(count, timeout)
handler.call... | ruby | {
"resource": ""
} |
q6036 | RightAMQP.HABrokerClient.publish | train | def publish(exchange, packet, options = {})
identities = []
no_serialize = options[:no_serialize] || @serializer.nil?
message = if no_serialize then packet else @serializer.dump(packet) end
brokers = use(options)
brokers.each do |b|
if b.publish(exchange, packet, message, options.m... | ruby | {
"resource": ""
} |
q6037 | RightAMQP.HABrokerClient.delete | train | def delete(name, options = {})
identities = []
u = usable
brokers = options.delete(:brokers)
((brokers || u) & u).each { |i| identities << i if (b = @brokers_hash[i]) && b.delete(name, options) }
identities
end | ruby | {
"resource": ""
} |
q6038 | RightAMQP.HABrokerClient.delete_amqp_resources | train | def delete_amqp_resources(name, options = {})
identities = []
u = usable
((options[:brokers] || u) & u).each { |i| identities << i if (b = @brokers_hash[i]) && b.delete_amqp_resources(:queue, name) }
identities
end | ruby | {
"resource": ""
} |
q6039 | RightAMQP.HABrokerClient.remove | train | def remove(host, port, &blk)
identity = self.class.identity(host, port)
if broker = @brokers_hash[identity]
logger.info("Removing #{identity}, alias #{broker.alias} from broker list")
broker.close(propagate = true, normal = true, log = false)
@brokers_hash.delete(identity)
@b... | ruby | {
"resource": ""
} |
q6040 | RightAMQP.HABrokerClient.declare_unusable | train | def declare_unusable(identities)
identities.each do |id|
broker = @brokers_hash[id]
raise Exception, "Cannot mark unknown broker #{id} unusable" unless broker
broker.close(propagate = true, normal = false, log = false)
end
end | ruby | {
"resource": ""
} |
q6041 | RightAMQP.HABrokerClient.close | train | def close(&blk)
if @closed
blk.call if blk
else
@closed = true
@connection_status = {}
handler = CountedDeferrable.new(@brokers.size)
handler.callback { blk.call if blk }
@brokers.each do |b|
begin
b.close(propagate = false) { handler.com... | ruby | {
"resource": ""
} |
q6042 | RightAMQP.HABrokerClient.close_one | train | def close_one(identity, propagate = true, &blk)
broker = @brokers_hash[identity]
raise Exception, "Cannot close unknown broker #{identity}" unless broker
broker.close(propagate, &blk)
true
end | ruby | {
"resource": ""
} |
q6043 | RightAMQP.HABrokerClient.connection_status | train | def connection_status(options = {}, &callback)
id = generate_id
@connection_status[id] = {:boundary => options[:boundary], :brokers => options[:brokers], :callback => callback}
if timeout = options[:one_off]
@connection_status[id][:timer] = EM::Timer.new(timeout) do
if @connection_st... | ruby | {
"resource": ""
} |
q6044 | RightAMQP.HABrokerClient.reset_stats | train | def reset_stats
@return_stats = RightSupport::Stats::Activity.new
@non_delivery_stats = RightSupport::Stats::Activity.new
@exception_stats = @options[:exception_stats] || RightSupport::Stats::Exceptions.new(self, @options[:exception_callback])
true
end | ruby | {
"resource": ""
} |
q6045 | RightAMQP.HABrokerClient.connect_all | train | def connect_all
self.class.addresses(@options[:host], @options[:port]).map do |a|
identity = self.class.identity(a[:host], a[:port])
BrokerClient.new(identity, a, @serializer, @exception_stats, @non_delivery_stats, @options, nil)
end
end | ruby | {
"resource": ""
} |
q6046 | RightAMQP.HABrokerClient.priority | train | def priority(identity)
priority = 0
@brokers.each do |b|
break if b.identity == identity
priority += 1
end
priority
end | ruby | {
"resource": ""
} |
q6047 | RightAMQP.HABrokerClient.each | train | def each(status, identities = nil)
choices = if identities && !identities.empty?
identities.inject([]) { |c, i| if b = @brokers_hash[i] then c << b else c end }
else
@brokers
end
choices.select do |b|
if b.send("#{status}?".to_sym)
yield(b) if block_given?
... | ruby | {
"resource": ""
} |
q6048 | RightAMQP.HABrokerClient.use | train | def use(options)
choices = []
select = options[:order]
if options[:brokers] && !options[:brokers].empty?
options[:brokers].each do |identity|
if choice = @brokers_hash[identity]
choices << choice
else
logger.exception("Invalid broker identity #{ident... | ruby | {
"resource": ""
} |
q6049 | RightAMQP.HABrokerClient.handle_return | train | def handle_return(identity, to, reason, message)
@brokers_hash[identity].update_status(:stopping) if reason == "ACCESS_REFUSED"
if context = @published.fetch(message)
@return_stats.update("#{alias_(identity)} (#{reason.to_s.downcase})")
context.record_failure(identity)
name = contex... | ruby | {
"resource": ""
} |
q6050 | Evvnt.Attributes.method_missing | train | def method_missing(method_name, *args)
setter = method_name.to_s.ends_with?('=')
attr_name = method_name.to_s.gsub(/=$/, "")
if setter
attributes[attr_name] = args.first
else
attributes[attr_name]
end
end | ruby | {
"resource": ""
} |
q6051 | Jinx.MatchVisitor.visit | train | def visit(source, target, &block)
# clear the match hashes
@matches.clear
@id_mtchs.clear
# seed the matches with the top-level source => target
add_match(source, target)
# Visit the source reference.
super(source) { |src| visit_matched(src, &block) }
end | ruby | {
"resource": ""
} |
q6052 | Jinx.MatchVisitor.visit_matched | train | def visit_matched(source)
tgt = @matches[source] || return
# Match the unvisited matchable references, if any.
if @matchable then
mas = @matchable.call(source) - attributes_to_visit(source)
mas.each { |ma| match_reference(source, tgt, ma) }
end
block_given? ? yield(source, ... | ruby | {
"resource": ""
} |
q6053 | Jinx.MatchVisitor.match_reference | train | def match_reference(source, target, attribute)
srcs = source.send(attribute).to_enum
tgts = target.send(attribute).to_enum
# the match targets
mtchd_tgts = Set.new
# capture the matched targets and the the unmatched sources
unmtchd_srcs = srcs.reject do |src|
# the pri... | ruby | {
"resource": ""
} |
q6054 | HtmlMockup.Extractor.extract_source_from_file | train | def extract_source_from_file(file_path, env = {})
source = HtmlMockup::Template.open(file_path, :partials_path => self.project.partial_path, :layouts_path => self.project.layouts_path).render(env.dup)
if @options[:url_relativize]
source = relativize_urls(source, file_path)
end
so... | ruby | {
"resource": ""
} |
q6055 | ActionController.Serialization.build_json_serializer | train | def build_json_serializer(object, options={})
ScopedSerializer.for(object, { :scope => serializer_scope, :super => true }.merge(options.merge(default_serializer_options)))
end | ruby | {
"resource": ""
} |
q6056 | Formatter.Number.format | train | def format(number)
case number
when Float then format_float(number)
when Integer then format_integer(number)
else fail ArgumentError
end
end | ruby | {
"resource": ""
} |
q6057 | Arnold.NodeManager.remove_stale_symlinks | train | def remove_stale_symlinks(path)
Dir.glob("#{path}/*").each { |f| File.unlink(f) if not File.exist?(f) }
end | ruby | {
"resource": ""
} |
q6058 | Connfu.Listener.start | train | def start(queue = nil)
queue.nil? and queue = @queue
logger.debug "Listener starts..."
@thread = Thread.new {
# listen to connFu
@connfu_stream.start_listening
}
while continue do
logger.debug "Waiting for a message from connFu stream"
message = @connfu_st... | ruby | {
"resource": ""
} |
q6059 | Jinx.Resource.owner= | train | def owner=(obj)
if obj.nil? then
op, ov = effective_owner_property_value || return
else
op = self.class.owner_properties.detect { |prop| prop.type === obj }
end
if op.nil? then raise NoMethodError.new("#{self.class.qp} does not have an owner attribute for #{obj}") end
set_p... | ruby | {
"resource": ""
} |
q6060 | Jinx.Resource.references | train | def references(attributes=nil)
attributes ||= self.class.domain_attributes
attributes.map { |pa| send(pa) }.flatten.compact
end | ruby | {
"resource": ""
} |
q6061 | Jinx.Resource.direct_dependents | train | def direct_dependents(attribute)
deps = send(attribute)
case deps
when Enumerable then deps
when nil then Array::EMPTY_ARRAY
else [deps]
end
end | ruby | {
"resource": ""
} |
q6062 | Jinx.Resource.match_in | train | def match_in(others)
# trivial case: self is in others
return self if others.include?(self)
# filter for the same type
unless others.all? { |other| self.class === other } then
others = others.filter { |other| self.class === other }
end
# match on primary, secondary or alterna... | ruby | {
"resource": ""
} |
q6063 | Jinx.Resource.visit_path | train | def visit_path(*path, &operator)
visitor = ReferencePathVisitor.new(self.class, path)
visitor.visit(self, &operator)
end | ruby | {
"resource": ""
} |
q6064 | Jinx.Resource.printable_content | train | def printable_content(attributes=nil, &reference_printer)
attributes ||= printworthy_attributes
vh = value_hash(attributes)
vh.transform_value { |value| printable_value(value, &reference_printer) }
end | ruby | {
"resource": ""
} |
q6065 | Jinx.Resource.validate_mandatory_attributes | train | def validate_mandatory_attributes
invalid = missing_mandatory_attributes
unless invalid.empty? then
logger.error("Validation of #{qp} unsuccessful - missing #{invalid.join(', ')}:\n#{dump}")
raise ValidationError.new("Required attribute value missing for #{self}: #{invalid.join(', ')}")
... | ruby | {
"resource": ""
} |
q6066 | Jinx.Resource.validate_owner | train | def validate_owner
# If there is an unambigous owner, then we are done.
return unless owner.nil?
# If there is more than one owner attribute, then check that there is at most one
# unambiguous owner reference. The owner method returns nil if the owner is ambiguous.
if self.class.owner_attr... | ruby | {
"resource": ""
} |
q6067 | Jinx.Resource.printable_value | train | def printable_value(value, &reference_printer)
Jinx::Collector.on(value) do |item|
if Resource === item then
block_given? ? yield(item) : printable_value(item) { |ref| ReferencePrinter.new(ref) }
else
item
end
end
end | ruby | {
"resource": ""
} |
q6068 | Jinx.Resource.printworthy_attributes | train | def printworthy_attributes
if self.class.primary_key_attributes.all? { |pa| !!send(pa) } then
self.class.primary_key_attributes
elsif not self.class.secondary_key_attributes.empty? then
self.class.secondary_key_attributes
elsif not self.class.nondomain_java_attributes.empty? then
... | ruby | {
"resource": ""
} |
q6069 | Jinx.Resource.empty_value | train | def empty_value(attribute)
type = java_type(attribute) || return
if type.primitive? then
type.name == 'boolean' ? false : 0
else
self.class.empty_value(attribute)
end
end | ruby | {
"resource": ""
} |
q6070 | Jinx.Resource.java_type | train | def java_type(attribute)
prop = self.class.property(attribute)
prop.property_descriptor.attribute_type if JavaProperty === prop
end | ruby | {
"resource": ""
} |
q6071 | Jinx.Resource.match_unique_object_with_attributes | train | def match_unique_object_with_attributes(others, attributes)
vh = value_hash(attributes)
return if vh.empty? or vh.size < attributes.size
matches = others.select do |other|
self.class == other.class and
vh.all? { |pa, v| other.matches_attribute_value?(pa, v) }
end
matches.... | ruby | {
"resource": ""
} |
q6072 | Jinx.Resource.non_id_search_attribute_values | train | def non_id_search_attribute_values
# if there is a secondary key, then search on those attributes.
# otherwise, search on all attributes.
key_props = self.class.secondary_key_attributes
pas = key_props.empty? ? self.class.nondomain_java_attributes : key_props
# associate the values
a... | ruby | {
"resource": ""
} |
q6073 | Incline::Extensions.ActionControllerBase.render_csv | train | def render_csv(filename = nil, view_name = nil)
filename ||= params[:action]
view_name ||= params[:action]
filename.downcase!
filename += '.csv' unless filename[-4..-1] == '.csv'
headers['Content-Type'] = 'text/csv'
headers['Content-Disposition'] = "attachment; filename=\"#{filenam... | ruby | {
"resource": ""
} |
q6074 | Incline::Extensions.ActionControllerBase.authorize! | train | def authorize!(*accepted_groups) #:doc:
begin
# an authenticated user must exist.
unless logged_in?
store_location
if (auth_url = ::Incline::UserManager.begin_external_authentication(request))
::Incline::Log.debug 'Redirecting for external authentication.'
... | ruby | {
"resource": ""
} |
q6075 | Incline::Extensions.ActionControllerBase.valid_user? | train | def valid_user? #:doc:
if require_admin_for_request?
authorize! true
elsif require_anon_for_request?
if logged_in?
flash[:warning] = 'The specified action cannot be performed while logged in.'
redirect_to incline.user_path(current_user)
end
elsif allow_anon_... | ruby | {
"resource": ""
} |
q6076 | AWS.ProfileParser.get | train | def get(profile='default')
raise 'Config File does not exist' unless File.exists?(@file)
@credentials = parse if @credentials.nil?
raise 'The profile is not specified in the config file' unless @credentials.has_key?(profile)
@credentials[profile]
end | ruby | {
"resource": ""
} |
q6077 | Detroit.Gem.build | train | def build
trace "gem build #{gemspec}"
spec = load_gemspec
package = ::Gem::Package.build(spec)
mkdir_p(pkgdir) unless File.directory?(pkgdir)
mv(package, pkgdir)
end | ruby | {
"resource": ""
} |
q6078 | Detroit.Gem.create_gemspec | train | def create_gemspec(file=nil)
file = gemspec if !file
#require 'gemdo/gemspec'
yaml = project.to_gemspec.to_yaml
File.open(file, 'w') do |f|
f << yaml
end
status File.basename(file) + " updated."
return file
end | ruby | {
"resource": ""
} |
q6079 | Detroit.Gem.lookup_gemspec | train | def lookup_gemspec
dot_gemspec = (project.root + '.gemspec').to_s
if File.exist?(dot_gemspec)
dot_gemspec.to_s
else
project.metadata.name + '.gemspec'
end
end | ruby | {
"resource": ""
} |
q6080 | Detroit.Gem.load_gemspec | train | def load_gemspec
file = gemspec
if yaml?(file)
::Gem::Specification.from_yaml(File.new(file))
else
::Gem::Specification.load(file)
end
end | ruby | {
"resource": ""
} |
q6081 | Detroit.Gem.yaml? | train | def yaml?(file)
line = open(file) { |f| line = f.gets }
line.index "!ruby/object:Gem::Specification"
end | ruby | {
"resource": ""
} |
q6082 | Ruta.Handlers.default | train | def default
handler_name = @handler_name
proc {
comp = @context.elements[handler_name][:content]
if comp.kind_of?(Proc)
comp.call
else
Context.wipe handler_name
Context.render comp, handler_name
end
}
end | ruby | {
"resource": ""
} |
q6083 | Retry.Engine.do | train | def do(delay: nil, exceptions: nil, handlers: nil, tries: nil, &block)
Retry.do(delay: delay || self.delay,
exceptions: exceptions || self.exceptions,
handlers: handlers || self.handlers,
tries: tries || self.tries,
&block)
end | ruby | {
"resource": ""
} |
q6084 | Hornetseye.Node.fmod_with_float | train | def fmod_with_float( other )
other = Node.match( other, typecode ).new other unless other.matched?
if typecode < FLOAT_ or other.typecode < FLOAT_
fmod other
else
fmod_without_float other
end
end | ruby | {
"resource": ""
} |
q6085 | Hornetseye.Node.to_type | train | def to_type(dest)
if dimension == 0 and variables.empty?
target = typecode.to_type dest
target.new(simplify.get).simplify
else
key = "to_#{dest.to_s.downcase}"
Hornetseye::ElementWise( proc { |x| x.to_type dest }, key,
proc { |t| t.to_type des... | ruby | {
"resource": ""
} |
q6086 | Hornetseye.Node.to_type_with_rgb | train | def to_type_with_rgb(dest)
if typecode < RGB_
if dest < FLOAT_
lazy { r * 0.299 + g * 0.587 + b * 0.114 }.to_type dest
elsif dest < INT_
lazy { (r * 0.299 + g * 0.587 + b * 0.114).round }.to_type dest
else
to_type_without_rgb dest
end
else
... | ruby | {
"resource": ""
} |
q6087 | Hornetseye.Node.reshape | train | def reshape(*ret_shape)
target_size = ret_shape.inject 1, :*
if target_size != size
raise "Target is of size #{target_size} but should be of size #{size}"
end
Hornetseye::MultiArray(typecode, ret_shape.size).
new *(ret_shape + [:memory => memorise.memory])
end | ruby | {
"resource": ""
} |
q6088 | Hornetseye.Node.conditional | train | def conditional(a, b)
a = Node.match(a, b.matched? ? b : nil).new a unless a.matched?
b = Node.match(b, a.matched? ? a : nil).new b unless b.matched?
if dimension == 0 and variables.empty? and
a.dimension == 0 and a.variables.empty? and
b.dimension == 0 and b.variables.empty?
t... | ruby | {
"resource": ""
} |
q6089 | Hornetseye.Node.transpose | train | def transpose(*order)
if (0 ... dimension).to_a != order.sort
raise 'Each array index must be specified exactly once!'
end
term = self
variables = shape.reverse.collect do |i|
var = Variable.new Hornetseye::INDEX( i )
term = term.element var
var
end.reverse
... | ruby | {
"resource": ""
} |
q6090 | Hornetseye.Node.unroll | train | def unroll( n = 1 )
if n < 0
roll -n
else
order = ( 0 ... dimension ).to_a
n.times { order = [ order.last ] + order[ 0 ... -1 ] }
transpose *order
end
end | ruby | {
"resource": ""
} |
q6091 | Hornetseye.Node.collect | train | def collect(&action)
var = Variable.new typecode
block = action.call var
conversion = proc { |t| t.to_type action.call(Variable.new(t.typecode)).typecode }
Hornetseye::ElementWise( action, block.to_s, conversion ).new( self ).force
end | ruby | {
"resource": ""
} |
q6092 | Hornetseye.Node.inject | train | def inject(*args, &action)
options = args.last.is_a?(Hash) ? args.pop : {}
unless action or options[:block]
unless [1, 2].member? args.size
raise "Inject expected 1 or 2 arguments but got #{args.size}"
end
initial, symbol = args[-2], args[-1]
action = proc { |a,b| ... | ruby | {
"resource": ""
} |
q6093 | Hornetseye.Node.range | train | def range( initial = nil )
min( initial ? initial.min : nil ) .. max( initial ? initial.max : nil )
end | ruby | {
"resource": ""
} |
q6094 | Hornetseye.Node.normalise | train | def normalise( range = 0 .. 0xFF )
if range.exclude_end?
raise "Normalisation does not support ranges with end value " +
"excluded (such as #{range})"
end
lower, upper = min, max
if lower.is_a? RGB or upper.is_a? RGB
current = [ lower.r, lower.g, lower.b ].min ..
... | ruby | {
"resource": ""
} |
q6095 | Hornetseye.Node.clip | train | def clip( range = 0 .. 0xFF )
if range.exclude_end?
raise "Clipping does not support ranges with end value " +
"excluded (such as #{range})"
end
collect { |x| x.major( range.begin ).minor range.end }
end | ruby | {
"resource": ""
} |
q6096 | Hornetseye.Node.stretch | train | def stretch(from = 0 .. 0xFF, to = 0 .. 0xFF)
if from.exclude_end?
raise "Stretching does not support ranges with end value " +
"excluded (such as #{from})"
end
if to.exclude_end?
raise "Stretching does not support ranges with end value " +
"excluded (such a... | ruby | {
"resource": ""
} |
q6097 | Hornetseye.Node.diagonal | train | def diagonal( initial = nil, options = {} )
if dimension == 0
demand
else
if initial
initial = Node.match( initial ).new initial unless initial.matched?
initial_typecode = initial.typecode
else
initial_typecode = typecode
end
index0 = Var... | ruby | {
"resource": ""
} |
q6098 | Hornetseye.Node.table | train | def table( filter, &action )
filter = Node.match( filter, typecode ).new filter unless filter.matched?
if filter.dimension > dimension
raise "Filter has #{filter.dimension} dimension(s) but should " +
"not have more than #{dimension}"
end
filter = Hornetseye::lazy( 1 ) { fi... | ruby | {
"resource": ""
} |
q6099 | Hornetseye.Node.convolve | train | def convolve( filter )
filter = Node.match( filter, typecode ).new filter unless filter.matched?
array = self
(dimension - filter.dimension).times { array = array.roll }
array.table(filter) { |a,b| a * b }.diagonal { |s,x| s + x }
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.