_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q16300 | Xcake.Target.copy_files_build_phase | train | def copy_files_build_phase(name, &block)
phase = CopyFilesBuildPhase.new(&block)
phase.name = name
build_phases << phase
phase
end | ruby | {
"resource": ""
} |
q16301 | Xcake.Target.pre_shell_script_build_phase | train | def pre_shell_script_build_phase(name, script, &block)
phase = ShellScriptBuildPhase.new(&block)
phase.name = name
phase.script = script
pinned_build_phases << phase
phase
end | ruby | {
"resource": ""
} |
q16302 | Xcake.Target.shell_script_build_phase | train | def shell_script_build_phase(name, script, &block)
phase = ShellScriptBuildPhase.new(&block)
phase.name = name
phase.script = script
build_phases << phase
phase
end | ruby | {
"resource": ""
} |
q16303 | Xcake.Target.build_rule | train | def build_rule(name, file_type, output_files, output_files_compiler_flags, script, &block)
rule = BuildRule.new(&block)
rule.name = name
rule.file_type = file_type
rule.output_files = output_files
rule.output_files_compiler_flags = output_files_compiler_flags
rule.script = script
build_rules << rule
rule
end | ruby | {
"resource": ""
} |
q16304 | Xcake.Configurable.configuration | train | def configuration(name, type)
default_settings = default_settings_for_type(type)
configurations = configurations_of_type(type)
build_configuration = if name.nil?
configurations.first
else
configurations.detect do |c|
c.name == name.to_s
end
end
if build_configuration.nil?
name = type.to_s.capitalize if name.nil?
build_configuration = Configuration.new(name) do |b|
b.type = type
b.settings.merge!(default_settings)
yield(b) if block_given?
end
@configurations ||= []
@configurations << build_configuration
end
build_configuration
end | ruby | {
"resource": ""
} |
q16305 | Xcake.Project.application_for | train | def application_for(platform, deployment_target, language = :objc)
target do |t|
t.type = :application
t.platform = platform
t.deployment_target = deployment_target
t.language = language
yield(t) if block_given?
end
end | ruby | {
"resource": ""
} |
q16306 | Xcake.Project.extension_for | train | def extension_for(host_target)
target = target do |t|
t.type = :app_extension
t.platform = host_target.platform
t.deployment_target = host_target.deployment_target
t.language = host_target.language
end
host_target.target_dependencies << target
yield(target) if block_given?
target
end | ruby | {
"resource": ""
} |
q16307 | Xcake.Project.watch_app_for | train | def watch_app_for(host_target, deployment_target, language = :objc)
watch_app_target = target do |t|
t.name = "#{host_target.name}-Watch"
t.type = :watch2_app
t.platform = :watchos
t.deployment_target = deployment_target
t.language = language
end
watch_extension_target = target do |t|
t.name = "#{host_target.name}-Watch Extension"
t.type = :watch2_extension
t.platform = :watchos
t.deployment_target = deployment_target
t.language = language
end
host_target.target_dependencies << watch_app_target
watch_app_target.target_dependencies << watch_extension_target
yield(watch_app_target, watch_extension_target) if block_given?
nil
end | ruby | {
"resource": ""
} |
q16308 | Xcake.Target.default_system_frameworks_for | train | def default_system_frameworks_for(platform)
case platform
when :ios
%w(Foundation UIKit)
when :osx
%w(Cocoa)
when :tvos
%w(Foundation UIKit)
when :watchos
%w(Foundation UIKit WatchKit)
else
abort 'Platform not supported!'
end
end | ruby | {
"resource": ""
} |
q16309 | StatefulEnum.StateInspector.possible_states | train | def possible_states
col = @stateful_enum.instance_variable_get :@column
possible_events.flat_map {|e| e.instance_variable_get(:@transitions)[@model_instance.send(col).to_sym].first }
end | ruby | {
"resource": ""
} |
q16310 | TZInfo.Timezone.to_local | train | def to_local(time)
raise ArgumentError, 'time must be specified' unless time
Timestamp.for(time) do |ts|
TimestampWithOffset.set_timezone_offset(ts, period_for(ts).offset)
end
end | ruby | {
"resource": ""
} |
q16311 | TZInfo.Timezone.utc_to_local | train | def utc_to_local(utc_time)
raise ArgumentError, 'utc_time must be specified' unless utc_time
Timestamp.for(utc_time, :treat_as_utc) do |ts|
to_local(ts)
end
end | ruby | {
"resource": ""
} |
q16312 | TZInfo.Timezone.local_to_utc | train | def local_to_utc(local_time, dst = Timezone.default_dst)
raise ArgumentError, 'local_time must be specified' unless local_time
Timestamp.for(local_time, :ignore) do |ts|
period = if block_given?
period_for_local(ts, dst) {|periods| yield periods }
else
period_for_local(ts, dst)
end
ts.add_and_set_utc_offset(-period.observed_utc_offset, :utc)
end
end | ruby | {
"resource": ""
} |
q16313 | TZInfo.DataSource.try_with_encoding | train | def try_with_encoding(string, encoding)
result = yield string
return result if result
unless encoding == string.encoding
string = string.encode(encoding)
yield string
end
end | ruby | {
"resource": ""
} |
q16314 | InvisibleCaptcha.ViewHelpers.invisible_captcha | train | def invisible_captcha(honeypot = nil, scope = nil, options = {})
if InvisibleCaptcha.timestamp_enabled
session[:invisible_captcha_timestamp] = Time.zone.now.iso8601
end
build_invisible_captcha(honeypot, scope, options)
end | ruby | {
"resource": ""
} |
q16315 | Slop.Result.fetch | train | def fetch(flag)
o = option(flag)
if o.nil?
cleaned_key = clean_key(flag)
raise UnknownOption.new("option not found: '#{cleaned_key}'", "#{cleaned_key}")
else
o.value
end
end | ruby | {
"resource": ""
} |
q16316 | Slop.Result.[]= | train | def []=(flag, value)
if o = option(flag)
o.value = value
else
raise ArgumentError, "no option with flag `#{flag}'"
end
end | ruby | {
"resource": ""
} |
q16317 | Slop.Result.option | train | def option(flag)
options.find do |o|
o.flags.any? { |f| clean_key(f) == clean_key(flag) }
end
end | ruby | {
"resource": ""
} |
q16318 | Slop.Result.to_hash | train | def to_hash
Hash[options.reject(&:null?).map { |o| [o.key, o.value] }]
end | ruby | {
"resource": ""
} |
q16319 | Slop.Parser.try_process | train | def try_process(flag, arg)
if option = matching_option(flag)
process(option, arg)
elsif flag.start_with?("--no-") && option = matching_option(flag.sub("no-", ""))
process(option, false)
elsif flag =~ /\A-[^-]{2,}/
try_process_smashed_arg(flag) || try_process_grouped_flags(flag, arg)
else
if flag.start_with?("-") && !suppress_errors?
raise UnknownOption.new("unknown option `#{flag}'", "#{flag}")
end
end
end | ruby | {
"resource": ""
} |
q16320 | Slop.Option.key | train | def key
key = config[:key] || flags.last.sub(/\A--?/, '')
key = key.tr '-', '_' if underscore_flags?
key.to_sym
end | ruby | {
"resource": ""
} |
q16321 | Slop.Options.separator | train | def separator(string = "")
if separators[options.size]
separators[-1] += "\n#{string}"
else
separators[options.size] = string
end
end | ruby | {
"resource": ""
} |
q16322 | Slop.Options.method_missing | train | def method_missing(name, *args, **config, &block)
if respond_to_missing?(name)
config[:type] = name
on(*args, config, &block)
else
super
end
end | ruby | {
"resource": ""
} |
q16323 | Guard.RSpecFormatter.write_summary | train | def write_summary(duration, total, failures, pending)
_write do |f|
f.puts _message(total, failures, pending, duration)
f.puts _failed_paths.join("\n") if failures > 0
end
end | ruby | {
"resource": ""
} |
q16324 | PryRemote.Server.run | train | def run
if PryNav.current_remote_server
raise 'Already running a pry-remote session!'
else
PryNav.current_remote_server = self
end
setup
Pry.start @object, {
:input => client.input_proxy,
:output => client.output,
:pry_remote => true
}
end | ruby | {
"resource": ""
} |
q16325 | StateMachine.Transition.pausable | train | def pausable
begin
halted = !catch(:halt) { yield; true }
rescue Exception => error
raise unless @resume_block
end
if @resume_block
@resume_block.call(halted, error)
else
halted
end
end | ruby | {
"resource": ""
} |
q16326 | StateMachine.Event.transition | train | def transition(options)
raise ArgumentError, 'Must specify as least one transition requirement' if options.empty?
# Only a certain subset of explicit options are allowed for transition
# requirements
assert_valid_keys(options, :from, :to, :except_from, :except_to, :if, :unless) if (options.keys - [:from, :to, :on, :except_from, :except_to, :except_on, :if, :unless]).empty?
branches << branch = Branch.new(options.merge(:on => name))
@known_states |= branch.known_states
branch
end | ruby | {
"resource": ""
} |
q16327 | StateMachine.StateContext.transition | train | def transition(options)
assert_valid_keys(options, :from, :to, :on, :if, :unless)
raise ArgumentError, 'Must specify :on event' unless options[:on]
raise ArgumentError, 'Must specify either :to or :from state' unless !options[:to] ^ !options[:from]
machine.transition(options.merge(options[:to] ? {:from => state.name} : {:to => state.name}))
end | ruby | {
"resource": ""
} |
q16328 | StateMachine.NodeCollection.initialize_copy | train | def initialize_copy(orig) #:nodoc:
super
nodes = @nodes
contexts = @contexts
@nodes = []
@contexts = []
@indices = @indices.inject({}) {|indices, (name, *)| indices[name] = {}; indices}
# Add nodes *prior* to copying over the contexts so that they don't get
# evaluated multiple times
concat(nodes.map {|n| n.dup})
@contexts = contexts.dup
end | ruby | {
"resource": ""
} |
q16329 | StateMachine.NodeCollection.context | train | def context(nodes, &block)
nodes = nodes.first.is_a?(Matcher) ? nodes.first : WhitelistMatcher.new(nodes)
@contexts << context = {:nodes => nodes, :block => block}
# Evaluate the new context for existing nodes
each {|node| eval_context(context, node)}
context
end | ruby | {
"resource": ""
} |
q16330 | StateMachine.Machine.owner_class= | train | def owner_class=(klass)
@owner_class = klass
# Create modules for extending the class with state/event-specific methods
@helper_modules = helper_modules = {:instance => HelperModule.new(self, :instance), :class => HelperModule.new(self, :class)}
owner_class.class_eval do
extend helper_modules[:class]
include helper_modules[:instance]
end
# Add class-/instance-level methods to the owner class for state initialization
unless owner_class < StateMachine::InstanceMethods
owner_class.class_eval do
extend StateMachine::ClassMethods
include StateMachine::InstanceMethods
end
define_state_initializer if @initialize_state
end
# Record this machine as matched to the name in the current owner class.
# This will override any machines mapped to the same name in any superclasses.
owner_class.state_machines[name] = self
end | ruby | {
"resource": ""
} |
q16331 | StateMachine.Callback.run_methods | train | def run_methods(object, context = {}, index = 0, *args, &block)
if type == :around
if current_method = @methods[index]
yielded = false
evaluate_method(object, current_method, *args) do
yielded = true
run_methods(object, context, index + 1, *args, &block)
end
throw :halt unless yielded
else
yield if block_given?
end
else
@methods.each do |method|
result = evaluate_method(object, method, *args)
throw :halt if @terminator && @terminator.call(result)
end
end
end | ruby | {
"resource": ""
} |
q16332 | Capybara::Poltergeist.WebSocketServer.accept | train | def accept
@socket = server.accept
@messages = {}
@driver = ::WebSocket::Driver.server(self)
@driver.on(:connect) { |_event| @driver.start }
@driver.on(:message) do |event|
command_id = JSON.parse(event.data)['command_id']
@messages[command_id] = event.data
end
end | ruby | {
"resource": ""
} |
q16333 | Capybara::Poltergeist.WebSocketServer.send | train | def send(cmd_id, message, accept_timeout = nil)
accept unless connected?
driver.text(message)
receive(cmd_id, accept_timeout)
rescue Errno::EWOULDBLOCK
raise TimeoutError, message
end | ruby | {
"resource": ""
} |
q16334 | ActiveType.Util.using_single_table_inheritance? | train | def using_single_table_inheritance?(klass, record)
inheritance_column = klass.inheritance_column
record[inheritance_column].present? && record.has_attribute?(inheritance_column)
end | ruby | {
"resource": ""
} |
q16335 | Cheffish.NodeProperties.tag | train | def tag(*tags)
attribute "tags" do |existing_tags|
existing_tags ||= []
tags.each do |tag|
if !existing_tags.include?(tag.to_s)
existing_tags << tag.to_s
end
end
existing_tags
end
end | ruby | {
"resource": ""
} |
q16336 | InlineSvg::TransformPipeline::Transformations.Transformation.with_svg | train | def with_svg(doc)
doc = Nokogiri::XML::Document.parse(
doc.to_html(encoding: "UTF-8"), nil, "UTF-8"
)
svg = doc.at_css "svg"
yield svg if svg && block_given?
doc
end | ruby | {
"resource": ""
} |
q16337 | InlineSvg.CachedAssetFile.named | train | def named(asset_name)
assets[key_for_asset(asset_name)] or
raise InlineSvg::AssetFile::FileNotFound.new("Asset not found: #{asset_name}")
end | ruby | {
"resource": ""
} |
q16338 | PDF.Reader.doc_strings_to_utf8 | train | def doc_strings_to_utf8(obj)
case obj
when ::Hash then
{}.tap { |new_hash|
obj.each do |key, value|
new_hash[key] = doc_strings_to_utf8(value)
end
}
when Array then
obj.map { |item| doc_strings_to_utf8(item) }
when String then
if obj[0,2].unpack("C*") == [254, 255]
utf16_to_utf8(obj)
else
pdfdoc_to_utf8(obj)
end
else
@objects.deref(obj)
end
end | ruby | {
"resource": ""
} |
q16339 | ExtractImages.Tiff.save_group_four | train | def save_group_four(filename)
k = stream.hash[:DecodeParms][:K]
h = stream.hash[:Height]
w = stream.hash[:Width]
bpc = stream.hash[:BitsPerComponent]
mask = stream.hash[:ImageMask]
len = stream.hash[:Length]
cols = stream.hash[:DecodeParms][:Columns]
puts "#{filename}: h=#{h}, w=#{w}, bpc=#{bpc}, mask=#{mask}, len=#{len}, cols=#{cols}, k=#{k}"
# Synthesize a TIFF header
long_tag = lambda {|tag, value| [ tag, 4, 1, value ].pack( "ssII" ) }
short_tag = lambda {|tag, value| [ tag, 3, 1, value ].pack( "ssII" ) }
# header = byte order, version magic, offset of directory, directory count,
# followed by a series of tags containing metadata: 259 is a magic number for
# the compression type; 273 is the offset of the image data.
tiff = [ 73, 73, 42, 8, 5 ].pack("ccsIs") \
+ short_tag.call( 256, cols ) \
+ short_tag.call( 257, h ) \
+ short_tag.call( 259, 4 ) \
+ long_tag.call( 273, (10 + (5*12) + 4) ) \
+ long_tag.call( 279, len) \
+ [0].pack("I") \
+ stream.data
File.open(filename, "wb") { |file| file.write tiff }
end | ruby | {
"resource": ""
} |
q16340 | ActiveModel.Observer.disabled_for? | train | def disabled_for?(object) #:nodoc:
klass = object.class
return false unless klass.respond_to?(:observers)
klass.observers.disabled_for?(self)
end | ruby | {
"resource": ""
} |
q16341 | RubyUnits.Unit.copy | train | def copy(from)
@scalar = from.scalar
@numerator = from.numerator
@denominator = from.denominator
@base = from.base?
@signature = from.signature
@base_scalar = from.base_scalar
@unit_name = begin
from.unit_name
rescue
nil
end
self
end | ruby | {
"resource": ""
} |
q16342 | RubyUnits.Unit.base? | train | def base?
return @base if defined? @base
@base = (@numerator + @denominator)
.compact
.uniq
.map { |unit| RubyUnits::Unit.definition(unit) }
.all? { |element| element.unity? || element.base? }
@base
end | ruby | {
"resource": ""
} |
q16343 | RubyUnits.Unit.to_base | train | def to_base
return self if base?
if @@unit_map[units] =~ /\A<(?:temp|deg)[CRF]>\Z/
@signature = @@kinds.key(:temperature)
base = if temperature?
convert_to('tempK')
elsif degree?
convert_to('degK')
end
return base
end
cached = (begin
(@@base_unit_cache[units] * scalar)
rescue
nil
end)
return cached if cached
num = []
den = []
q = Rational(1)
@numerator.compact.each do |num_unit|
if @@prefix_values[num_unit]
q *= @@prefix_values[num_unit]
else
q *= @@unit_values[num_unit][:scalar] if @@unit_values[num_unit]
num << @@unit_values[num_unit][:numerator] if @@unit_values[num_unit] && @@unit_values[num_unit][:numerator]
den << @@unit_values[num_unit][:denominator] if @@unit_values[num_unit] && @@unit_values[num_unit][:denominator]
end
end
@denominator.compact.each do |num_unit|
if @@prefix_values[num_unit]
q /= @@prefix_values[num_unit]
else
q /= @@unit_values[num_unit][:scalar] if @@unit_values[num_unit]
den << @@unit_values[num_unit][:numerator] if @@unit_values[num_unit] && @@unit_values[num_unit][:numerator]
num << @@unit_values[num_unit][:denominator] if @@unit_values[num_unit] && @@unit_values[num_unit][:denominator]
end
end
num = num.flatten.compact
den = den.flatten.compact
num = UNITY_ARRAY if num.empty?
base = RubyUnits::Unit.new(RubyUnits::Unit.eliminate_terms(q, num, den))
@@base_unit_cache[units] = base
base * @scalar
end | ruby | {
"resource": ""
} |
q16344 | RubyUnits.Unit.to_s | train | def to_s(target_units = nil)
out = @output[target_units]
return out if out
separator = RubyUnits.configuration.separator
case target_units
when :ft
inches = convert_to('in').scalar.to_int
out = "#{(inches / 12).truncate}\'#{(inches % 12).round}\""
when :lbs
ounces = convert_to('oz').scalar.to_int
out = "#{(ounces / 16).truncate}#{separator}lbs, #{(ounces % 16).round}#{separator}oz"
when :stone
pounds = convert_to('lbs').scalar.to_int
out = "#{(pounds / 14).truncate}#{separator}stone, #{(pounds % 14).round}#{separator}lb"
when String
out = case target_units.strip
when /\A\s*\Z/ # whitespace only
''
when /(%[\-+\.\w#]+)\s*(.+)*/ # format string like '%0.2f in'
begin
if Regexp.last_match(2) # unit specified, need to convert
convert_to(Regexp.last_match(2)).to_s(Regexp.last_match(1))
else
"#{Regexp.last_match(1) % @scalar}#{separator}#{Regexp.last_match(2) || units}".strip
end
rescue # parse it like a strftime format string
(DateTime.new(0) + self).strftime(target_units)
end
when /(\S+)/ # unit only 'mm' or '1/mm'
convert_to(Regexp.last_match(1)).to_s
else
raise 'unhandled case'
end
else
out = case @scalar
when Complex
"#{@scalar}#{separator}#{units}"
when Rational
"#{@scalar == @scalar.to_i ? @scalar.to_i : @scalar}#{separator}#{units}"
else
"#{'%g' % @scalar}#{separator}#{units}"
end.strip
end
@output[target_units] = out
out
end | ruby | {
"resource": ""
} |
q16345 | RubyUnits.Unit.=~ | train | def =~(other)
case other
when Unit
signature == other.signature
else
begin
x, y = coerce(other)
return x =~ y
rescue ArgumentError
return false
end
end
end | ruby | {
"resource": ""
} |
q16346 | RubyUnits.Unit.+ | train | def +(other)
case other
when Unit
if zero?
other.dup
elsif self =~ other
raise ArgumentError, 'Cannot add two temperatures' if [self, other].all?(&:temperature?)
if [self, other].any?(&:temperature?)
if temperature?
RubyUnits::Unit.new(scalar: (scalar + other.convert_to(temperature_scale).scalar), numerator: @numerator, denominator: @denominator, signature: @signature)
else
RubyUnits::Unit.new(scalar: (other.scalar + convert_to(other.temperature_scale).scalar), numerator: other.numerator, denominator: other.denominator, signature: other.signature)
end
else
RubyUnits::Unit.new(scalar: (base_scalar + other.base_scalar), numerator: base.numerator, denominator: base.denominator, signature: @signature).convert_to(self)
end
else
raise ArgumentError, "Incompatible Units ('#{self}' not compatible with '#{other}')"
end
when Date, Time
raise ArgumentError, 'Date and Time objects represent fixed points in time and cannot be added to a Unit'
else
x, y = coerce(other)
y + x
end
end | ruby | {
"resource": ""
} |
q16347 | RubyUnits.Unit.* | train | def *(other)
case other
when Unit
raise ArgumentError, 'Cannot multiply by temperatures' if [other, self].any?(&:temperature?)
opts = RubyUnits::Unit.eliminate_terms(@scalar * other.scalar, @numerator + other.numerator, @denominator + other.denominator)
opts[:signature] = @signature + other.signature
RubyUnits::Unit.new(opts)
when Numeric
RubyUnits::Unit.new(scalar: @scalar * other, numerator: @numerator, denominator: @denominator, signature: @signature)
else
x, y = coerce(other)
x * y
end
end | ruby | {
"resource": ""
} |
q16348 | RubyUnits.Unit./ | train | def /(other)
case other
when Unit
raise ZeroDivisionError if other.zero?
raise ArgumentError, 'Cannot divide with temperatures' if [other, self].any?(&:temperature?)
sc = Rational(@scalar, other.scalar)
sc = sc.numerator if sc.denominator == 1
opts = RubyUnits::Unit.eliminate_terms(sc, @numerator + other.denominator, @denominator + other.numerator)
opts[:signature] = @signature - other.signature
RubyUnits::Unit.new(opts)
when Numeric
raise ZeroDivisionError if other.zero?
sc = Rational(@scalar, other)
sc = sc.numerator if sc.denominator == 1
RubyUnits::Unit.new(scalar: sc, numerator: @numerator, denominator: @denominator, signature: @signature)
else
x, y = coerce(other)
y / x
end
end | ruby | {
"resource": ""
} |
q16349 | RubyUnits.Unit.divmod | train | def divmod(other)
raise ArgumentError, "Incompatible Units ('#{self}' not compatible with '#{other}')" unless self =~ other
return scalar.divmod(other.scalar) if units == other.units
to_base.scalar.divmod(other.to_base.scalar)
end | ruby | {
"resource": ""
} |
q16350 | RubyUnits.Unit.** | train | def **(other)
raise ArgumentError, 'Cannot raise a temperature to a power' if temperature?
if other.is_a?(Numeric)
return inverse if other == -1
return self if other == 1
return 1 if other.zero?
end
case other
when Rational
return power(other.numerator).root(other.denominator)
when Integer
return power(other)
when Float
return self**other.to_i if other == other.to_i
valid = (1..9).map { |n| Rational(1, n) }
raise ArgumentError, 'Not a n-th root (1..9), use 1/n' unless valid.include? other.abs
return root(Rational(1, other).to_int)
when Complex
raise ArgumentError, 'exponentiation of complex numbers is not supported.'
else
raise ArgumentError, 'Invalid Exponent'
end
end | ruby | {
"resource": ""
} |
q16351 | RubyUnits.Unit.power | train | def power(n)
raise ArgumentError, 'Cannot raise a temperature to a power' if temperature?
raise ArgumentError, 'Exponent must an Integer' unless n.is_a?(Integer)
return inverse if n == -1
return 1 if n.zero?
return self if n == 1
return (1..(n - 1).to_i).inject(self) { |acc, _elem| acc * self } if n >= 0
(1..-(n - 1).to_i).inject(self) { |acc, _elem| acc / self }
end | ruby | {
"resource": ""
} |
q16352 | RubyUnits.Unit.units | train | def units(with_prefix: true)
return '' if @numerator == UNITY_ARRAY && @denominator == UNITY_ARRAY
output_numerator = ['1']
output_denominator = []
num = @numerator.clone.compact
den = @denominator.clone.compact
unless num == UNITY_ARRAY
definitions = num.map { |element| RubyUnits::Unit.definition(element) }
definitions.reject!(&:prefix?) unless with_prefix
# there is a bug in jruby 9.1.6.0's implementation of chunk_while
# see https://github.com/jruby/jruby/issues/4410
# TODO: fix this after jruby fixes their bug.
definitions = if definitions.respond_to?(:chunk_while) && RUBY_ENGINE != 'jruby'
definitions.chunk_while { |defn, _| defn.prefix? }.to_a
else # chunk_while is new to ruby 2.3+, so fallback to less efficient methods for older ruby
result = []
enumerator = definitions.to_enum
loop do
first = enumerator.next
result << (first.prefix? ? [first, enumerator.next] : [first])
end
result
end
output_numerator = definitions.map { |element| element.map(&:display_name).join }
end
unless den == UNITY_ARRAY
definitions = den.map { |element| RubyUnits::Unit.definition(element) }
definitions.reject!(&:prefix?) unless with_prefix
# there is a bug in jruby 9.1.6.0's implementation of chunk_while
# see https://github.com/jruby/jruby/issues/4410
# TODO: fix this after jruby fixes their bug.
definitions = if definitions.respond_to?(:chunk_while) && RUBY_ENGINE != 'jruby'
definitions.chunk_while { |defn, _| defn.prefix? }.to_a
else # chunk_while is new to ruby 2.3+, so fallback to less efficient methods for older ruby
result = []
enumerator = definitions.to_enum
loop do
first = enumerator.next
result << (first.prefix? ? [first, enumerator.next] : [first])
end
result
end
output_denominator = definitions.map { |element| element.map(&:display_name).join }
end
on = output_numerator
.uniq
.map { |x| [x, output_numerator.count(x)] }
.map { |element, power| (element.to_s.strip + (power > 1 ? "^#{power}" : '')) }
od = output_denominator
.uniq
.map { |x| [x, output_denominator.count(x)] }
.map { |element, power| (element.to_s.strip + (power > 1 ? "^#{power}" : '')) }
"#{on.join('*')}#{od.empty? ? '' : '/' + od.join('*')}".strip
end | ruby | {
"resource": ""
} |
q16353 | RubyUnits.Unit.coerce | train | def coerce(other)
return [other.to_unit, self] if other.respond_to? :to_unit
case other
when Unit
[other, self]
else
[RubyUnits::Unit.new(other), self]
end
end | ruby | {
"resource": ""
} |
q16354 | RubyUnits.Unit.best_prefix | train | def best_prefix
return to_base if scalar.zero?
best_prefix = if kind == :information
@@prefix_values.key(2**((Math.log(base_scalar, 2) / 10.0).floor * 10))
else
@@prefix_values.key(10**((Math.log10(base_scalar) / 3.0).floor * 3))
end
to(RubyUnits::Unit.new(@@prefix_map.key(best_prefix) + units(with_prefix: false)))
end | ruby | {
"resource": ""
} |
q16355 | RubyUnits.Unit.unit_signature_vector | train | def unit_signature_vector
return to_base.unit_signature_vector unless base?
vector = Array.new(SIGNATURE_VECTOR.size, 0)
# it's possible to have a kind that misses the array... kinds like :counting
# are more like prefixes, so don't use them to calculate the vector
@numerator.map { |element| RubyUnits::Unit.definition(element) }.each do |definition|
index = SIGNATURE_VECTOR.index(definition.kind)
vector[index] += 1 if index
end
@denominator.map { |element| RubyUnits::Unit.definition(element) }.each do |definition|
index = SIGNATURE_VECTOR.index(definition.kind)
vector[index] -= 1 if index
end
raise ArgumentError, 'Power out of range (-20 < net power of a unit < 20)' if vector.any? { |x| x.abs >= 20 }
vector
end | ruby | {
"resource": ""
} |
q16356 | RubyUnits.Unit.unit_signature | train | def unit_signature
return @signature unless @signature.nil?
vector = unit_signature_vector
vector.each_with_index { |item, index| vector[index] = item * 20**index }
@signature = vector.inject(0) { |acc, elem| acc + elem }
@signature
end | ruby | {
"resource": ""
} |
q16357 | ActsAsFavoritor.FavoritorLib.parent_class_name | train | def parent_class_name(obj)
unless DEFAULT_PARENTS.include? obj.class.superclass
return obj.class.base_class.name
end
obj.class.name
end | ruby | {
"resource": ""
} |
q16358 | Moneta.OptionSupport.with | train | def with(options = nil, &block)
adapter = self
if block
builder = Builder.new(&block)
builder.adapter(adapter)
adapter = builder.build.last
end
options ? OptionMerger.new(adapter, options) : adapter
end | ruby | {
"resource": ""
} |
q16359 | Moneta.Defaults.fetch | train | def fetch(key, default = nil, options = nil)
if block_given?
raise ArgumentError, 'Only one argument accepted if block is given' if options
result = load(key, default || {})
result == nil ? yield(key) : result
else
result = load(key, options || {})
result == nil ? default : result
end
end | ruby | {
"resource": ""
} |
q16360 | Moneta.Defaults.slice | train | def slice(*keys, **options)
keys.zip(values_at(*keys, **options)).reject do |_, value|
value == nil
end
end | ruby | {
"resource": ""
} |
q16361 | Moneta.ExpiresSupport.expires_at | train | def expires_at(options, default = @default_expires)
value = expires_value(options, default)
Numeric === value ? Time.now + value : value
end | ruby | {
"resource": ""
} |
q16362 | Moneta.ExpiresSupport.expires_value | train | def expires_value(options, default = @default_expires)
case value = options[:expires]
when 0, false
false
when nil
default ? default.to_r : nil
when Numeric
value = value.to_r
raise ArgumentError, ":expires must be a positive value, got #{value}" if value < 0
value
else
raise ArgumentError, ":expires must be Numeric or false, got #{value.inspect}"
end
end | ruby | {
"resource": ""
} |
q16363 | Moneta.Builder.use | train | def use(proxy, options = {}, &block)
proxy = Moneta.const_get(proxy) if Symbol === proxy
raise ArgumentError, 'You must give a Class or a Symbol' unless Class === proxy
@proxies.unshift [proxy, options, block]
nil
end | ruby | {
"resource": ""
} |
q16364 | Moneta.Builder.adapter | train | def adapter(adapter, options = {}, &block)
case adapter
when Symbol
use(Adapters.const_get(adapter), options, &block)
when Class
use(adapter, options, &block)
else
raise ArgumentError, 'Adapter must be a Moneta store' unless adapter.respond_to?(:load) && adapter.respond_to?(:store)
raise ArgumentError, 'No options allowed' unless options.empty?
@proxies.unshift adapter
nil
end
end | ruby | {
"resource": ""
} |
q16365 | Moneta.Server.run | train | def run
raise 'Already running' if @running
@stop = false
@running = true
begin
until @stop
mainloop
end
ensure
File.unlink(@socket) if @socket
@ios.each{ |io| io.close rescue nil }
end
end | ruby | {
"resource": ""
} |
q16366 | Erubi.CaptureEndEngine.handle | train | def handle(indicator, code, tailch, rspace, lspace)
case indicator
when '|=', '|=='
rspace = nil if tailch && !tailch.empty?
add_text(lspace) if lspace
escape_capture = !((indicator == '|=') ^ @escape_capture)
src << "begin; (#{@bufstack} ||= []) << #{@bufvar}; #{@bufvar} = #{@bufval}; #{@bufstack}.last << #{@escapefunc if escape_capture}((" << code
add_text(rspace) if rspace
when '|'
rspace = nil if tailch && !tailch.empty?
add_text(lspace) if lspace
result = @yield_returns_buffer ? " #{@bufvar}; " : ""
src << result << code << ")).to_s; ensure; #{@bufvar} = #{@bufstack}.pop; end;"
add_text(rspace) if rspace
else
super
end
end | ruby | {
"resource": ""
} |
q16367 | Win32.Certstore.open | train | def open(store_name)
certstore_handler = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, nil, CERT_SYSTEM_STORE_LOCAL_MACHINE, wstring(store_name))
unless certstore_handler
last_error = FFI::LastError.error
raise SystemCallError.new("Unable to open the Certificate Store `#{store_name}`.", last_error)
end
add_finalizer(certstore_handler)
certstore_handler
end | ruby | {
"resource": ""
} |
q16368 | Temple.Utils.empty_exp? | train | def empty_exp?(exp)
case exp[0]
when :multi
exp[1..-1].all? {|e| empty_exp?(e) }
when :newline
true
else
false
end
end | ruby | {
"resource": ""
} |
q16369 | Mixlib.Log.loggers_to_close | train | def loggers_to_close
loggers_to_close = []
all_loggers.each do |logger|
# unfortunately Logger does not provide access to the logdev
# via public API. In order to reduce amount of impact and
# handle only File type log devices I had to use this method
# to get access to it.
next unless (logdev = logger.instance_variable_get(:"@logdev"))
loggers_to_close << logger if logdev.filename
end
loggers_to_close
end | ruby | {
"resource": ""
} |
q16370 | Support.Formats.normalize_json | train | def normalize_json(json)
json = json.to_json unless json.is_a?(String)
JSON.parse(json)
end | ruby | {
"resource": ""
} |
q16371 | Travis.Features.active? | train | def active?(feature, repository)
feature_active?(feature) or
(rollout.active?(feature, repository.owner) or
repository_active?(feature, repository))
end | ruby | {
"resource": ""
} |
q16372 | Travis.Features.owner_active? | train | def owner_active?(feature, owner)
redis.sismember(owner_key(feature, owner), owner.id)
end | ruby | {
"resource": ""
} |
q16373 | Travis.AdvisoryLocks.exclusive | train | def exclusive(timeout = 30)
give_up_at = Time.now + timeout if timeout
while timeout.nil? || Time.now < give_up_at do
if obtained_lock?
return yield
else
# Randomizing sleep time may help reduce contention.
sleep(rand(0.1..0.2))
end
end
ensure
release_lock unless transactional
end | ruby | {
"resource": ""
} |
q16374 | Unparser.CLI.exit_status | train | def exit_status
effective_sources.each do |source|
next if @ignore.include?(source)
process_source(source)
break if @fail_fast && !@success
end
@success ? EXIT_SUCCESS : EXIT_FAILURE
end | ruby | {
"resource": ""
} |
q16375 | Unparser.CLI.effective_sources | train | def effective_sources
if @start_with
reject = true
@sources.reject do |source|
if reject && source.eql?(@start_with)
reject = false
end
reject
end
else
@sources
end
end | ruby | {
"resource": ""
} |
q16376 | Unparser.CLI.sources | train | def sources(file_name)
files =
if File.directory?(file_name)
Dir.glob(File.join(file_name, '**/*.rb')).sort
elsif File.file?(file_name)
[file_name]
else
Dir.glob(file_name).sort
end
files.map(&Source::File.method(:new))
end | ruby | {
"resource": ""
} |
q16377 | Unparser.DSL.define_child | train | def define_child(name, index)
define_method(name) do
children.at(index)
end
private name
end | ruby | {
"resource": ""
} |
q16378 | Unparser.DSL.define_group | train | def define_group(name, range)
define_method(name) do
children[range]
end
private(name)
memoize(name)
end | ruby | {
"resource": ""
} |
q16379 | Unparser.DSL.children | train | def children(*names)
define_remaining_children(names)
names.each_with_index do |name, index|
define_child(name, index)
end
end | ruby | {
"resource": ""
} |
q16380 | Unparser.Preprocessor.visited_children | train | def visited_children
children.map do |node|
if node.is_a?(Parser::AST::Node)
visit(node)
else
node
end
end
end | ruby | {
"resource": ""
} |
q16381 | Unparser.Emitter.write_to_buffer | train | def write_to_buffer
emit_comments_before if buffer.fresh_line?
dispatch
comments.consume(node)
emit_eof_comments if parent.is_a?(Root)
self
end | ruby | {
"resource": ""
} |
q16382 | Unparser.Emitter.visit | train | def visit(node)
emitter = emitter(node)
conditional_parentheses(!emitter.terminated?) do
emitter.write_to_buffer
end
end | ruby | {
"resource": ""
} |
q16383 | Unparser.Emitter.delimited | train | def delimited(nodes, &block)
return if nodes.empty?
block ||= method(:visit)
head, *tail = nodes
block.call(head)
tail.each do |node|
write(DEFAULT_DELIMITER)
block.call(node)
end
end | ruby | {
"resource": ""
} |
q16384 | Unparser.Emitter.emit_comments_before | train | def emit_comments_before(source_part = :expression)
comments_before = comments.take_before(node, source_part)
return if comments_before.empty?
emit_comments(comments_before)
buffer.nl
end | ruby | {
"resource": ""
} |
q16385 | Unparser.Emitter.emit_eof_comments | train | def emit_eof_comments
emit_eol_comments
comments_left = comments.take_all
return if comments_left.empty?
buffer.nl
emit_comments(comments_left)
end | ruby | {
"resource": ""
} |
q16386 | Unparser.Emitter.emit_comments | train | def emit_comments(comments)
max = comments.size - 1
comments.each_with_index do |comment, index|
if comment.type.equal?(:document)
buffer.append_without_prefix(comment.text.chomp)
else
write(comment.text)
end
buffer.nl if index < max
end
end | ruby | {
"resource": ""
} |
q16387 | Unparser.Emitter.emit_body | train | def emit_body(body = body())
unless body
buffer.indent
nl
buffer.unindent
return
end
visit_indented(body)
end | ruby | {
"resource": ""
} |
q16388 | Unparser.Comments.take_before | train | def take_before(node, source_part)
range = source_range(node, source_part)
if range
take_while { |comment| comment.location.expression.end_pos <= range.begin_pos }
else
EMPTY_ARRAY
end
end | ruby | {
"resource": ""
} |
q16389 | Unparser.Comments.unshift_documents | train | def unshift_documents(comments)
doc_comments, other_comments = comments.partition(&:document?)
doc_comments.reverse_each { |comment| @comments.unshift(comment) }
other_comments
end | ruby | {
"resource": ""
} |
q16390 | Appbundler.App.copy_bundler_env | train | def copy_bundler_env
gem_path = installed_spec.gem_dir
# If we're already using that directory, don't copy (it won't work anyway)
return if gem_path == File.dirname(gemfile_lock)
FileUtils.install(gemfile_lock, gem_path, mode: 0644)
if File.exist?(dot_bundle_dir) && File.directory?(dot_bundle_dir)
FileUtils.cp_r(dot_bundle_dir, gem_path)
FileUtils.chmod_R("ugo+rX", File.join(gem_path, ".bundle"))
end
end | ruby | {
"resource": ""
} |
q16391 | Appbundler.App.write_merged_lockfiles | train | def write_merged_lockfiles(without: [])
unless external_lockfile?
copy_bundler_env
return
end
# handle external lockfile
Tempfile.open(".appbundler-gemfile", app_dir) do |t|
t.puts "source 'https://rubygems.org'"
locked_gems = {}
gemfile_lock_specs.each do |s|
# next if SHITLIST.include?(s.name)
spec = safe_resolve_local_gem(s)
next if spec.nil?
case s.source
when Bundler::Source::Path
locked_gems[spec.name] = %Q{gem "#{spec.name}", path: "#{spec.gem_dir}"}
when Bundler::Source::Rubygems
# FIXME: should add the spec.version as a gem requirement below
locked_gems[spec.name] = %Q{gem "#{spec.name}", "= #{spec.version}"}
when Bundler::Source::Git
raise "FIXME: appbundler needs a patch to support Git gems"
else
raise "appbundler doens't know this source type"
end
end
seen_gems = {}
t.puts "# GEMS FROM GEMFILE:"
requested_dependencies(without).each do |dep|
next if SHITLIST.include?(dep.name)
if locked_gems[dep.name]
t.puts locked_gems[dep.name]
else
string = %Q{gem "#{dep.name}", #{requirement_to_str(dep.requirement)}}
string << %Q{, platform: #{dep.platforms}} unless dep.platforms.empty?
t.puts string
end
seen_gems[dep.name] = true
end
t.puts "# GEMS FROM LOCKFILE: "
locked_gems.each do |name, line|
next if SHITLIST.include?(name)
next if seen_gems[name]
t.puts line
end
t.close
puts IO.read(t.path) # debugging
Dir.chdir(app_dir) do
FileUtils.rm_f "#{app_dir}/Gemfile.lock"
Bundler.with_clean_env do
so = Mixlib::ShellOut.new("bundle lock", env: { "BUNDLE_GEMFILE" => t.path })
so.run_command
so.error!
end
FileUtils.mv t.path, "#{app_dir}/Gemfile"
end
end
"#{app_dir}/Gemfile"
end | ruby | {
"resource": ""
} |
q16392 | RipperTags.VimFormatter.with_output | train | def with_output
super do |out|
out.puts header
@queued_write = []
yield out
@queued_write.sort.each do |line|
out.puts(line)
end
end
end | ruby | {
"resource": ""
} |
q16393 | RipperTags.Parser.on_command_call | train | def on_command_call(*args)
if args.last && :args == args.last[0]
args_add = args.pop
call = on_call(*args)
on_method_add_arg(call, args_add)
else
super
end
end | ruby | {
"resource": ""
} |
q16394 | RipperTags.Visitor.on_assign | train | def on_assign(name, rhs, line, *junk)
return unless name =~ /^[A-Z]/ && junk.empty?
if rhs && :call == rhs[0] && rhs[1] && "#{rhs[1][0]}.#{rhs[2]}" =~ /^(Class|Module|Struct)\.new$/
kind = $1 == 'Module' ? :module : :class
superclass = $1 == 'Class' ? rhs[3] : nil
superclass.flatten! if superclass
return on_module_or_class(kind, [name, line], superclass, rhs[4])
end
namespace = @namespace
if name.include?('::')
parts = name.split('::')
name = parts.pop
namespace = namespace + parts
end
process(rhs)
emit_tag :constant, line,
:name => name,
:full_name => (namespace + [name]).join('::'),
:class => namespace.join('::')
end | ruby | {
"resource": ""
} |
q16395 | Lit.I18nBackend.store_translations | train | def store_translations(locale, data, options = {})
super
ActiveRecord::Base.transaction do
store_item(locale, data)
end if store_items? && valid_locale?(locale)
end | ruby | {
"resource": ""
} |
q16396 | Lit.Cache.fallback_localization | train | def fallback_localization(locale, key_without_locale)
value = nil
return nil unless fallbacks = ::Rails.application.config.i18n.fallbacks
keys = fallbacks == true ? @locale_cache.keys : fallbacks
keys.map(&:to_s).each do |lc|
if lc != locale.locale && value.nil?
nk = "#{lc}.#{key_without_locale}"
v = localizations[nk]
value = v if v.present? && value.nil?
end
end
value
end | ruby | {
"resource": ""
} |
q16397 | Lit.Cache.fallback_to_default | train | def fallback_to_default(localization_key, localization)
localization_key.localizations.where.not(default_value: nil). \
where.not(id: localization.id).first&.default_value
end | ruby | {
"resource": ""
} |
q16398 | Lit.CloudTranslation.translate | train | def translate(text:, from: nil, to:, **opts)
provider.translate(text: text, from: from, to: to, **opts)
end | ruby | {
"resource": ""
} |
q16399 | Lit.CloudTranslation.configure | train | def configure(&block)
unless provider
raise 'Translation provider not selected yet. Use `Lit::CloudTranslation' \
'.provider = PROVIDER_KLASS` before calling #configure.'
end
provider.tap do |p|
p.configure(&block)
end
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.