_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q2400 | Rley.ParseForestVisitor.traverse_children | train | def traverse_children(aParentNode)
children = aParentNode.children
broadcast(:before_subnodes, aParentNode, children)
# Let's proceed with the visit of children
children.each_with_index do |a_node, i|
edge_sign = aParentNode.signatures[i]
if a_node.kind_of?(SPPF::CompositeNode)
push_node(a_node, edge_sign)
access_paths = node_accesses[a_node]
last_path = legs.last[-1]
path_reused = access_paths.include?(last_path)
unless path_reused
node_accesses[a_node].push(last_path)
a_node.accept(self)
end
pop_node
else
a_node.accept(self)
end
end
broadcast(:after_subnodes, aParentNode, children)
end | ruby | {
"resource": ""
} |
q2401 | Celerity.ElementCollection.[] | train | def [](n)
if @elements && @elements[n - Celerity.index_offset]
element_class.new(@container, :object, @elements[n - Celerity.index_offset])
else
iterator_object(n - Celerity.index_offset)
end
end | ruby | {
"resource": ""
} |
q2402 | Celerity.SelectList.selected? | train | def selected?(value)
assert_exists
raise UnknownObjectException, "unknown option with value #{value.inspect} for select_list #{@conditions.inspect}" unless include?(value)
!!@object.getOptions.find { |e| matches_option?(e, value) && e.isSelected }
end | ruby | {
"resource": ""
} |
q2403 | Celerity.Container.contains_text | train | def contains_text(expected_text)
assert_exists
return nil unless respond_to? :text
case expected_text
when Regexp
text() =~ expected_text
when String
text().index(expected_text)
else
raise TypeError, "expected String or Regexp, got #{expected_text.inspect}:#{expected_text.class}"
end
end | ruby | {
"resource": ""
} |
q2404 | Rley.Engine.parse | train | def parse(aTokenizer)
tokens = []
aTokenizer.each do |a_token|
next unless a_token
term_name = a_token.terminal
term_symb = grammar.name2symbol[term_name]
a_token.instance_variable_set(:@terminal, term_symb)
tokens << a_token
end
parser = build_parser(grammar)
parser.gf_graph.diagnose if configuration.diagnose
result = parser.parse(tokens)
result.tidy_up!
return result
end | ruby | {
"resource": ""
} |
q2405 | Rley.Engine.to_ptree | train | def to_ptree(aRawParse)
factory = ParseRep::ParseTreeFactory.new(aRawParse)
if configuration.repr_builder == :default
result = factory.create(nil)
else
result = factory.create(configuration.repr_builder)
end
return result
end | ruby | {
"resource": ""
} |
q2406 | Rley.Engine.to_pforest | train | def to_pforest(aRawParse)
factory = ParseRep::ParseForestFactory.new(aRawParse)
if configuration.repr_builder == :default
result = factory.create(nil)
else
result = factory.create(configuration.repr_builder)
end
return result
end | ruby | {
"resource": ""
} |
q2407 | Celerity.ElementLocator.with_nullpointer_retry | train | def with_nullpointer_retry(max_retries = 3)
tries = 0
yield
rescue java.lang.NullPointerException => e
raise e if tries >= max_retries
tries += 1
warn "warning: celerity caught #{e} - retry ##{tries}"
retry
end | ruby | {
"resource": ""
} |
q2408 | Celerity.ClickableElement.click_and_attach | train | def click_and_attach
assert_exists_and_enabled
browser = Browser.new(@browser.options.dup)
browser.webclient.set_cookie_manager(
@browser.webclient.get_cookie_manager
) # hirobumi: we do want cookies as well.
@browser.disable_event_listener do
rescue_status_code_exception { browser.page = @object.click }
end
browser
end | ruby | {
"resource": ""
} |
q2409 | Erlang.Map.value? | train | def value?(value)
value = Erlang.from(value)
each { |k,v| return true if value == v }
return false
end | ruby | {
"resource": ""
} |
q2410 | Erlang.Map.get | train | def get(key)
key = Erlang.from(key)
entry = @trie.get(key)
if entry
return entry[1]
elsif @default
return @default.call(key)
end
end | ruby | {
"resource": ""
} |
q2411 | Erlang.Map.fetch | train | def fetch(key, default = Undefined)
key = Erlang.from(key)
entry = @trie.get(key)
if entry
return entry[1]
elsif block_given?
return yield(key)
elsif not Undefined.equal?(default)
return Erlang.from(default)
else
raise KeyError, "key not found: #{key.inspect}"
end
end | ruby | {
"resource": ""
} |
q2412 | Erlang.Map.slice | train | def slice(*wanted)
trie = Trie.new(0)
wanted.each { |key|
key = Erlang.from(key)
trie.put!(key, get(key)) if key?(key)
}
return self.class.alloc(trie, @default)
end | ruby | {
"resource": ""
} |
q2413 | Hive.Worker.poll_queue | train | def poll_queue
@job = reserve_job
if @job.nil?
@log.info('No job found')
else
@log.info('Job starting')
begin
@current_job_start_time = Time.now
execute_job
rescue => e
@log.info("Error running test: #{e.message}\n : #{e.backtrace.join("\n :")}")
end
cleanup
end
end | ruby | {
"resource": ""
} |
q2414 | Hive.Worker.reserve_job | train | def reserve_job
@log.info "Trying to reserve job for queues: #{@queues.join(', ')}"
job = job_message_klass.reserve(@queues, reservation_details)
@log.debug "Job: #{job.inspect}"
raise InvalidJobReservationError.new("Invalid Job Reserved") if ! (job.nil? || job.valid?)
job
end | ruby | {
"resource": ""
} |
q2415 | Hive.Worker.diagnostics | train | def diagnostics
retn = true
protect
retn = @diagnostic_runner.run if !@diagnostic_runner.nil?
unprotect
@log.info('Diagnostics failed') if not retn
status = device_status
status = set_device_status('happy') if status == 'busy'
raise DeviceNotReady.new("Current device status: '#{status}'") if status != 'happy'
retn
end | ruby | {
"resource": ""
} |
q2416 | Hive.Worker.upload_files | train | def upload_files(job, *paths)
@log.info("Uploading assets")
paths.each do |path|
@log.info("Uploading files from #{path}")
Dir.foreach(path) do |item|
@log.info("File: #{item}")
next if item == '.' or item == '..'
begin
artifact = job.report_artifact("#{path}/#{item}")
@log.info("Artifact uploaded: #{artifact.attributes.to_s}")
rescue => e
@log.error("Error uploading artifact #{item}: #{e.message}")
@log.error(" : #{e.backtrace.join("\n : ")}")
end
end
end
end | ruby | {
"resource": ""
} |
q2417 | Hive.Worker.checkout_code | train | def checkout_code(repository, checkout_directory, branch)
CodeCache.repo(repository).checkout(:head, checkout_directory, branch) or raise "Unable to checkout repository #{repository}"
end | ruby | {
"resource": ""
} |
q2418 | Remedy.Characters.gremlins | train | def gremlins
{
space: "\u2420",
tab: "\u21B9",
carriage_return: "\u23CE",
line_feed: "\u240A",
control_c: "\u2404",
control_d: "\u2403",
control_r: "\u2412",
escape: "\u238B",
backspace: "\u2408",
delete: "\u232B",
up: "\u2191",
down: "\u2193",
left: "\u2190",
right: "\u2192"
}
end | ruby | {
"resource": ""
} |
q2419 | Erlang.Bitstring.bitslice | train | def bitslice(arg, length = (missing_length = true))
if missing_length
if arg.is_a?(Range)
from, to = arg.begin, arg.end
from += bitsize if from < 0
return nil if from < 0
to += bitsize if to < 0
to += 1 if !arg.exclude_end?
length = to - from
length = 0 if length < 0
length = bitsize - from if (from + length) > bitsize
return nil if length < 0
l8 = length.div(8)
l1 = length % 8
pad = 8 - l1
enum = each_bit
skip = from
enum = enum.drop_while {
if skip > 0
skip -= 1
next true
else
next false
end
}
head = enum.take(length)
if l1 == 0
return Erlang::Binary[[head.join].pack(BIT_PACK)]
else
tail = head[-l1..-1]
head = head[0...-l1]
tail = ([0] * pad).concat(tail)
return Erlang::Bitstring[[[head.join, tail.join].join].pack(BIT_PACK), bits: l1]
end
else
arg += bitsize if arg < 0
return nil if arg < 0
return nil if arg >= bitsize
a8 = arg.div(8)
a1 = arg % 8
byte = @data.getbyte(a8)
return nil if byte.nil?
return (byte >> ((@bits - a1 - 1) & 7)) & 1
end
else
return nil if length < 0
arg += bitsize if arg < 0
return nil if arg < 0
length = bitsize - arg if (arg + length) > bitsize
return nil if length < 0
l8 = length.div(8)
l1 = length % 8
pad = 8 - l1
enum = each_bit
skip = arg
enum = enum.drop_while {
if skip > 0
skip -= 1
next true
else
next false
end
}
head = enum.take(length)
if l1 == 0
return Erlang::Binary[[head.join].pack(BIT_PACK)]
else
tail = head[-l1..-1]
head = head[0...-l1]
tail = ([0] * pad).concat(tail)
return Erlang::Bitstring[[[head.join, tail.join].join].pack(BIT_PACK), bits: l1]
end
end
end | ruby | {
"resource": ""
} |
q2420 | Erlang.Bitstring.each_bit | train | def each_bit
return enum_for(:each_bit) unless block_given?
index = 0
headbits = (self.bytesize - 1) * 8
skipbits = 8 - @bits
@data.each_byte do |byte|
loop do
break if index == @bitsize
if index >= headbits
bit = (byte >> (7 - ((index + skipbits) & 7))) & 1
else
bit = (byte >> (7 - (index & 7))) & 1
end
yield bit
index += 1
break if (index & 7) == 0
end
end
return self
end | ruby | {
"resource": ""
} |
q2421 | Capybara::ChromeDevTools.DriverExtensions.start_crmux! | train | def start_crmux!(opts)
self.chrome_debugging_port = find_free_port(Capybara::ChromeDevTools.preferred_port)
self.crmux_listen_port = find_free_port(chrome_debugging_port + 1)
opts[:options].args << "--remote-debugging-port=#{chrome_debugging_port}"
#opts[:options].add_preference 'debuggerAddress', "127.0.0.1:#{crmux_listen_port}"
@debug_crmux = true
command = "npx crmux #{'-d' if @debug_crmux} \
--port=#{chrome_debugging_port} \
--listen=#{crmux_listen_port}"
puts %(command: #{command}) if Capybara::ChromeDevTools.verbose >= 3
if @debug_crmux
spawn_opts = {[:out, :err] => 'log/crmux.log'}
else
spawn_opts = {}
end
@crmux_pid = spawn(command, spawn_opts)
puts %(Started crmux [pid #{@crmux_pid}], listening at http://localhost:#{crmux_listen_port}, connected to localhost:#{chrome_debugging_port})
# You can also get the part later with: page.driver.browser.capabilities["goog:chromeOptions"]["debuggerAddress"]
sleep 0.1
at_exit do
puts "Killing crmux process #{@crmux_pid}..." if Capybara::ChromeDevTools.verbose >= 1
Process.kill 'TERM', @crmux_pid
end
end | ruby | {
"resource": ""
} |
q2422 | Hive.Device.start | train | def start
parent_pid = Process.pid
@worker_pid = Process.fork do
object = Object
@worker_class.split('::').each { |sub| object = object.const_get(sub) }
object.new(@options.merge('parent_pid' => parent_pid, 'device_identity' => self.identity, 'port_allocator' => self.port_allocator, 'hive_id' => Hive.hive_mind.device_details['id']))
end
Process.detach @worker_pid
Hive.logger.info("Worker started with pid #{@worker_pid}")
end | ruby | {
"resource": ""
} |
q2423 | Hive.Device.stop | train | def stop
protect_file = File.expand_path("#{@worker_pid}.protect", PIDS_DIRECTORY)
Hive.logger.debug("Checking for protected file: #{protect_file}")
if File.exists? File.expand_path("#{@worker_pid}.protect", PIDS_DIRECTORY)
Hive.logger.debug("PID #{@worker_pid} is protected")
false
else
@stop_count = @stop_count.nil? ? 0 : @stop_count + 1
if self.running?
if @stop_count < 30
Hive.logger.info("Attempting to terminate process #{@worker_pid} [#{@stop_count}]")
Process.kill 'TERM', @worker_pid
else
Hive.logger.info("Killing process #{@worker_pid}")
Process.kill 'KILL', @worker_pid if self.running?
end
end
if self.running?
false
else
@worker_pid = nil
@stop_count = nil
true
end
end
end | ruby | {
"resource": ""
} |
q2424 | Tqdm.Printer.padded_line | train | def padded_line(iteration, elapsed_time)
meter_line = line(iteration, elapsed_time)
pad_size = [@last_printed_length - meter_line.size, 0].max
@last_printed_length = meter_line.size
meter_line + ' ' * pad_size
end | ruby | {
"resource": ""
} |
q2425 | Erlang.Tuple.put | train | def put(index, element = yield(get(index)))
raise IndexError, "index #{index} outside of tuple bounds" if index < -@size
element = Erlang.from(element)
index += @size if index < 0
if index > @size
suffix = Array.new(index - @size, nil)
suffix << element
return replace_suffix(@size, suffix)
else
return update_root(index, element)
end
end | ruby | {
"resource": ""
} |
q2426 | Erlang.Tuple.fetch | train | def fetch(index, default = (missing_default = true))
if index >= -@size && index < @size
return get(index)
elsif block_given?
return Erlang.from(yield(index))
elsif !missing_default
return Erlang.from(default)
else
raise IndexError, "index #{index} outside of tuple bounds"
end
end | ruby | {
"resource": ""
} |
q2427 | Erlang.Tuple.slice | train | def slice(arg, length = (missing_length = true))
if missing_length
if arg.is_a?(Range)
from, to = arg.begin, arg.end
from += @size if from < 0
to += @size if to < 0
to += 1 if !arg.exclude_end?
length = to - from
length = 0 if length < 0
return subsequence(from, length)
else
return get(arg)
end
else
arg += @size if arg < 0
return subsequence(arg, length)
end
end | ruby | {
"resource": ""
} |
q2428 | Erlang.Tuple.insert | train | def insert(index, *elements)
raise IndexError if index < -@size
index += @size if index < 0
elements = elements.map { |element| Erlang.from(element) }
if index < @size
suffix = flatten_suffix(@root, @levels * BITS_PER_LEVEL, index, [])
suffix.unshift(*elements)
elsif index == @size
suffix = elements
else
suffix = Array.new(index - @size, nil).concat(elements)
index = @size
end
return replace_suffix(index, suffix)
end | ruby | {
"resource": ""
} |
q2429 | Erlang.Tuple.delete_at | train | def delete_at(index)
return self if index >= @size || index < -@size
index += @size if index < 0
suffix = flatten_suffix(@root, @levels * BITS_PER_LEVEL, index, [])
return replace_suffix(index, suffix.tap { |a| a.shift })
end | ruby | {
"resource": ""
} |
q2430 | Erlang.Tuple.select | train | def select
return enum_for(:select) unless block_given?
return reduce(self.class.empty) { |tuple, element| yield(element) ? tuple.add(element) : tuple }
end | ruby | {
"resource": ""
} |
q2431 | Erlang.Tuple.shuffle | train | def shuffle
return self.class.new(((array = to_a).frozen? ? array.shuffle : array.shuffle!).freeze)
end | ruby | {
"resource": ""
} |
q2432 | Erlang.Tuple.reverse | train | def reverse
return self.class.new(((array = to_a).frozen? ? array.reverse : array.reverse!).freeze)
end | ruby | {
"resource": ""
} |
q2433 | Erlang.Tuple.rotate | train | def rotate(count = 1)
return self if (count % @size) == 0
return self.class.new(((array = to_a).frozen? ? array.rotate(count) : array.rotate!(count)).freeze)
end | ruby | {
"resource": ""
} |
q2434 | Erlang.Tuple.sort | train | def sort(&comparator)
comparator = Erlang.method(:compare) unless block_given?
array = super(&comparator)
return self.class.new(array)
end | ruby | {
"resource": ""
} |
q2435 | Erlang.Tuple.drop | train | def drop(n)
return self if n == 0
return self.class.empty if n >= @size
raise ArgumentError, "attempt to drop negative size" if n < 0
return self.class.new(flatten_suffix(@root, @levels * BITS_PER_LEVEL, n, []))
end | ruby | {
"resource": ""
} |
q2436 | Erlang.Tuple.* | train | def *(times)
return self.class.empty if times == 0
return self if times == 1
result = (to_a * times)
return result.is_a?(Array) ? self.class.new(result) : result
end | ruby | {
"resource": ""
} |
q2437 | Erlang.Tuple.combination | train | def combination(n)
return enum_for(:combination, n) if not block_given?
return self if n < 0 || @size < n
if n == 0
yield []
elsif n == 1
each { |element| yield [element] }
elsif n == @size
yield self.to_a
else
combos = lambda do |result,index,remaining|
while @size - index > remaining
if remaining == 1
yield result.dup << get(index)
else
combos[result.dup << get(index), index+1, remaining-1]
end
index += 1
end
index.upto(@size-1) { |i| result << get(i) }
yield result
end
combos[[], 0, n]
end
return self
end | ruby | {
"resource": ""
} |
q2438 | Erlang.Tuple.repeated_combination | train | def repeated_combination(n)
return enum_for(:repeated_combination, n) if not block_given?
if n < 0
# yield nothing
elsif n == 0
yield []
elsif n == 1
each { |element| yield [element] }
elsif @size == 0
# yield nothing
else
combos = lambda do |result,index,remaining|
while index < @size-1
if remaining == 1
yield result.dup << get(index)
else
combos[result.dup << get(index), index, remaining-1]
end
index += 1
end
element = get(index)
remaining.times { result << element }
yield result
end
combos[[], 0, n]
end
return self
end | ruby | {
"resource": ""
} |
q2439 | Erlang.Tuple.permutation | train | def permutation(n = @size)
return enum_for(:permutation, n) if not block_given?
if n < 0 || @size < n
# yield nothing
elsif n == 0
yield []
elsif n == 1
each { |element| yield [element] }
else
used, result = [], []
perms = lambda do |index|
0.upto(@size-1) do |i|
if !used[i]
result[index] = get(i)
if index < n-1
used[i] = true
perms[index+1]
used[i] = false
else
yield result.dup
end
end
end
end
perms[0]
end
return self
end | ruby | {
"resource": ""
} |
q2440 | Erlang.Tuple.product | train | def product(*tuples)
tuples = tuples.map { |tuple| Erlang.from(tuple) }
# if no tuples passed, return "product" as in result of multiplying all elements
return super if tuples.empty?
tuples.unshift(self)
if tuples.any?(&:empty?)
return block_given? ? self : []
end
counters = Array.new(tuples.size, 0)
bump_counters = lambda do
i = tuples.size-1
counters[i] += 1
while counters[i] == tuples[i].size
counters[i] = 0
i -= 1
return true if i == -1 # we are done
counters[i] += 1
end
false # not done yet
end
build_array = lambda do
array = []
counters.each_with_index { |index,i| array << tuples[i][index] }
array
end
if block_given?
while true
yield build_array[]
return self if bump_counters[]
end
else
result = []
while true
result << build_array[]
return result if bump_counters[]
end
end
end | ruby | {
"resource": ""
} |
q2441 | Erlang.Tuple.rindex | train | def rindex(obj = (missing_arg = true))
obj = Erlang.from(obj)
i = @size - 1
if missing_arg
if block_given?
reverse_each { |element| return i if yield element; i -= 1 }
return nil
else
return enum_for(:rindex)
end
else
reverse_each { |element| return i if element == obj; i -= 1 }
return nil
end
end | ruby | {
"resource": ""
} |
q2442 | Erlang.Enumerable.partition | train | def partition
return enum_for(:partition) if not block_given?
a,b = super
return Erlang::Tuple[self.class.new(a), self.class.new(b)]
end | ruby | {
"resource": ""
} |
q2443 | Erlang.Enumerable.inspect | train | def inspect
result = "#{self.class}["
each_with_index { |obj, i| result << ', ' if i > 0; result << obj.inspect }
return result << "]"
end | ruby | {
"resource": ""
} |
q2444 | Erlang.List.each | train | def each
raise Erlang::ImproperListError if improper?
return to_enum unless block_given?
list = self
until list.empty?
yield(list.head)
list = list.tail
end
return self
end | ruby | {
"resource": ""
} |
q2445 | Erlang.List.flat_map | train | def flat_map(&block)
raise Erlang::ImproperListError if improper?
return enum_for(:flat_map) unless block_given?
return self if empty?
out = tail = Erlang::Cons.allocate
list = self
until list.empty?
head_list = Erlang::List.from_enum(yield(list.head))
if head_list.empty?
list = list.tail
elsif list.tail.empty?
tail.instance_variable_set(:@head, head_list.head)
tail.instance_variable_set(:@tail, head_list.tail)
tail.immutable!
list = list.tail
else
new_node = Erlang::Cons.allocate
new_node.instance_variable_set(:@improper, false)
tail.instance_variable_set(:@head, head_list.head)
tail.instance_variable_set(:@tail, head_list.tail + new_node)
tail.immutable!
list = list.tail
tail = new_node
end
end
if not tail.immutable?
tail.instance_variable_set(:@tail, Erlang::Nil)
tail.immutable!
end
if out === tail and not out.tail.kind_of?(Erlang::List)
return out.tail
else
return out
end
end | ruby | {
"resource": ""
} |
q2446 | Erlang.List.select | train | def select(&block)
raise Erlang::ImproperListError if improper?
return enum_for(:select) unless block_given?
out = tail = Erlang::Cons.allocate
list = self
while !list.empty?
if yield(list.head)
new_node = Erlang::Cons.allocate
new_node.instance_variable_set(:@head, list.head)
new_node.instance_variable_set(:@improper, false)
tail.instance_variable_set(:@tail, new_node)
tail.instance_variable_set(:@improper, false)
tail.immutable!
tail = new_node
list = list.tail
else
list = list.tail
end
end
if not tail.immutable?
tail.instance_variable_set(:@tail, Erlang::Nil)
tail.immutable!
end
return out.tail
end | ruby | {
"resource": ""
} |
q2447 | Erlang.List.drop_while | train | def drop_while(&block)
raise Erlang::ImproperListError if improper?
return enum_for(:drop_while) unless block_given?
list = self
list = list.tail while !list.empty? && yield(list.head)
return list
end | ruby | {
"resource": ""
} |
q2448 | Erlang.List.pop | train | def pop
raise Erlang::ImproperListError if improper?
return self if empty?
new_size = size - 1
return Erlang::List.new(head, tail.take(new_size - 1)) if new_size >= 1
return Erlang::Nil
end | ruby | {
"resource": ""
} |
q2449 | Erlang.List.drop | train | def drop(number)
raise Erlang::ImproperListError if improper?
list = self
while !list.empty? && number > 0
number -= 1
list = list.tail
end
return list
end | ruby | {
"resource": ""
} |
q2450 | Erlang.List.append | train | def append(other)
# raise Erlang::ImproperListError if improper?
other = Erlang.from(other)
return self if not improper? and Erlang.is_list(other) and other.empty?
return other if Erlang.is_list(other) and empty?
is_improper = Erlang.is_list(other) ? other.improper? : true
out = tail = Erlang::Cons.allocate
list = self
until list.empty?
new_node = Erlang::Cons.allocate
new_node.instance_variable_set(:@head, list.head)
new_node.instance_variable_set(:@improper, is_improper)
tail.instance_variable_set(:@tail, new_node)
tail.instance_variable_set(:@improper, is_improper)
tail.immutable!
tail = new_node
if not Erlang.is_list(list.tail)
new_node = Erlang::Cons.allocate
new_node.instance_variable_set(:@head, list.tail)
new_node.instance_variable_set(:@improper, is_improper)
tail.instance_variable_set(:@tail, new_node)
tail.instance_variable_set(:@improper, is_improper)
tail.immutable!
tail = new_node
list = Erlang::Nil
else
list = list.tail
end
end
if not tail.immutable?
tail.instance_variable_set(:@tail, other)
tail.immutable!
end
return out.tail
end | ruby | {
"resource": ""
} |
q2451 | Erlang.List.transpose | train | def transpose
raise Erlang::ImproperListError if improper?
return Erlang::Nil if empty?
return Erlang::Nil if any? { |list| list.empty? }
heads, tails = Erlang::Nil, Erlang::Nil
reverse_each { |list| heads, tails = heads.cons(list.head), tails.cons(list.tail) }
return Erlang::Cons.new(heads, tails.transpose)
end | ruby | {
"resource": ""
} |
q2452 | Erlang.List.rotate | train | def rotate(count = 1)
raise Erlang::ImproperListError if improper?
raise TypeError, "expected Integer" if not count.is_a?(Integer)
return self if empty? || (count % size) == 0
count = (count >= 0) ? count % size : (size - (~count % size) - 1)
return drop(count).append(take(count))
end | ruby | {
"resource": ""
} |
q2453 | Erlang.List.sort | train | def sort(&comparator)
comparator = Erlang.method(:compare) unless block_given?
array = super(&comparator)
return List.from_enum(array)
end | ruby | {
"resource": ""
} |
q2454 | Erlang.List.intersperse | train | def intersperse(sep)
raise Erlang::ImproperListError if improper?
return self if tail.empty?
sep = Erlang.from(sep)
out = tail = Erlang::Cons.allocate
list = self
until list.empty?
new_node = Erlang::Cons.allocate
new_node.instance_variable_set(:@head, list.head)
new_node.instance_variable_set(:@improper, false)
if not list.tail.empty?
sep_node = Erlang::Cons.allocate
sep_node.instance_variable_set(:@head, sep)
sep_node.instance_variable_set(:@improper, false)
new_node.instance_variable_set(:@tail, sep_node)
new_node.immutable!
end
tail.instance_variable_set(:@tail, new_node)
tail.instance_variable_set(:@improper, false)
tail.immutable!
if list.tail.empty?
tail = new_node
else
tail = new_node.tail
end
list = list.tail
end
if not tail.immutable?
tail.instance_variable_set(:@tail, Erlang::Nil)
tail.immutable!
end
return out.tail
end | ruby | {
"resource": ""
} |
q2455 | Erlang.List.union | train | def union(other)
raise Erlang::ImproperListError if improper?
other = Erlang.from(other)
raise ArgumentError, "other must be of Erlang::List type" if not Erlang.is_list(other)
raise Erlang::ImproperListError if other.improper?
items = ::Set.new
return _uniq(items).append(other._uniq(items))
end | ruby | {
"resource": ""
} |
q2456 | Erlang.List.init | train | def init
raise Erlang::ImproperListError if improper?
return Erlang::Nil if tail.empty?
out = tail = Erlang::Cons.allocate
list = self
until list.tail.empty?
new_node = Erlang::Cons.allocate
new_node.instance_variable_set(:@head, list.head)
new_node.instance_variable_set(:@improper, false)
tail.instance_variable_set(:@tail, new_node)
tail.instance_variable_set(:@improper, false)
tail.immutable!
tail = new_node
list = list.tail
end
if not tail.immutable?
tail.instance_variable_set(:@tail, Erlang::Nil)
tail.immutable!
end
return out.tail
end | ruby | {
"resource": ""
} |
q2457 | Erlang.List.last | train | def last(allow_improper = false)
if allow_improper and improper?
list = self
list = list.tail while list.tail.kind_of?(Erlang::List)
return list.tail
else
raise Erlang::ImproperListError if improper?
list = self
list = list.tail until list.tail.empty?
return list.head
end
end | ruby | {
"resource": ""
} |
q2458 | Erlang.List.tails | train | def tails
raise Erlang::ImproperListError if improper?
return self if empty?
out = tail = Erlang::Cons.allocate
list = self
until list.empty?
new_node = Erlang::Cons.allocate
new_node.instance_variable_set(:@head, list)
new_node.instance_variable_set(:@improper, false)
tail.instance_variable_set(:@tail, new_node)
list = list.tail
tail = new_node
end
tail.instance_variable_set(:@tail, Erlang::Nil)
return out.tail
end | ruby | {
"resource": ""
} |
q2459 | Erlang.List.inits | train | def inits
raise Erlang::ImproperListError if improper?
return self if empty?
prev = nil
return map do |head|
if prev.nil?
Erlang::List.from_enum(prev = [head])
else
Erlang::List.from_enum(prev.push(head))
end
end
end | ruby | {
"resource": ""
} |
q2460 | Erlang.List.combination | train | def combination(n)
raise Erlang::ImproperListError if improper?
return Erlang::Cons.new(Erlang::Nil) if n == 0
return self if empty?
return tail.combination(n - 1).map { |list| list.cons(head) }.append(tail.combination(n))
end | ruby | {
"resource": ""
} |
q2461 | Erlang.List.chunk | train | def chunk(number)
raise Erlang::ImproperListError if improper?
return self if empty?
out = tail = Erlang::Cons.allocate
list = self
until list.empty?
first, list = list.split_at(number)
new_node = Erlang::Cons.allocate
new_node.instance_variable_set(:@head, first)
new_node.instance_variable_set(:@improper, false)
tail.instance_variable_set(:@tail, new_node)
tail.instance_variable_set(:@improper, false)
tail.immutable!
tail = new_node
end
if not tail.immutable?
tail.instance_variable_set(:@tail, Erlang::Nil)
tail.immutable!
end
return out.tail
end | ruby | {
"resource": ""
} |
q2462 | Erlang.List.flatten | train | def flatten
raise Erlang::ImproperListError if improper?
return self if empty?
out = tail = Erlang::Cons.allocate
list = self
until list.empty?
if list.head.is_a?(Erlang::Cons)
list = list.head.append(list.tail)
elsif Erlang::Nil.equal?(list.head)
list = list.tail
else
new_node = Erlang::Cons.allocate
new_node.instance_variable_set(:@head, list.head)
new_node.instance_variable_set(:@improper, false)
tail.instance_variable_set(:@tail, new_node)
tail.immutable!
list = list.tail
tail = new_node
end
end
if not tail.immutable?
tail.instance_variable_set(:@tail, Erlang::Nil)
tail.immutable!
end
return out.tail
end | ruby | {
"resource": ""
} |
q2463 | Erlang.List.slice | train | def slice(arg, length = (missing_length = true))
raise Erlang::ImproperListError if improper?
if missing_length
if arg.is_a?(Range)
from, to = arg.begin, arg.end
from += size if from < 0
return nil if from < 0
to += size if to < 0
to += 1 if !arg.exclude_end?
length = to - from
length = 0 if length < 0
list = self
while from > 0
return nil if list.empty?
list = list.tail
from -= 1
end
return list.take(length)
else
return at(arg)
end
else
return nil if length < 0
arg += size if arg < 0
return nil if arg < 0
list = self
while arg > 0
return nil if list.empty?
list = list.tail
arg -= 1
end
return list.take(length)
end
end | ruby | {
"resource": ""
} |
q2464 | Erlang.List.indices | train | def indices(object = Erlang::Undefined, i = 0, &block)
raise Erlang::ImproperListError if improper?
object = Erlang.from(object) if object != Erlang::Undefined
return indices { |item| item == object } if not block_given?
return Erlang::Nil if empty?
out = tail = Erlang::Cons.allocate
list = self
until list.empty?
if yield(list.head)
new_node = Erlang::Cons.allocate
new_node.instance_variable_set(:@head, i)
new_node.instance_variable_set(:@improper, false)
tail.instance_variable_set(:@tail, new_node)
tail.instance_variable_set(:@improper, false)
tail.immutable!
tail = new_node
list = list.tail
else
list = list.tail
end
i += 1
end
if not tail.immutable?
tail.instance_variable_set(:@tail, Erlang::Nil)
tail.immutable!
end
return out.tail
end | ruby | {
"resource": ""
} |
q2465 | Erlang.List.merge | train | def merge(&comparator)
raise Erlang::ImproperListError if improper?
return merge_by unless block_given?
sorted = reject(&:empty?).sort do |a, b|
yield(a.head, b.head)
end
return Erlang::Nil if sorted.empty?
return Erlang::Cons.new(sorted.head.head, sorted.tail.cons(sorted.head.tail).merge(&comparator))
end | ruby | {
"resource": ""
} |
q2466 | Erlang.List.insert | train | def insert(index, *items)
raise Erlang::ImproperListError if improper?
if index == 0
return Erlang::List.from_enum(items).append(self)
elsif index > 0
out = tail = Erlang::Cons.allocate
list = self
while index > 0
new_node = Erlang::Cons.allocate
new_node.instance_variable_set(:@head, list.head)
new_node.instance_variable_set(:@improper, false)
tail.instance_variable_set(:@tail, new_node)
tail.instance_variable_set(:@improper, false)
tail.immutable!
tail = new_node
list = list.tail
index -= 1
end
if not tail.immutable?
tail.instance_variable_set(:@tail, Erlang::List.from_enum(items).append(list))
tail.immutable!
end
return out.tail
else
raise IndexError if index < -size
return insert(index + size, *items)
end
end | ruby | {
"resource": ""
} |
q2467 | Erlang.List.delete_at | train | def delete_at(index)
raise Erlang::ImproperListError if improper?
if index == 0
tail
elsif index < 0
index += size if index < 0
return self if index < 0
delete_at(index)
else
out = tail = Erlang::Cons.allocate
list = self
while index > 0
new_node = Erlang::Cons.allocate
new_node.instance_variable_set(:@head, list.head)
new_node.instance_variable_set(:@improper, false)
tail.instance_variable_set(:@tail, new_node)
tail.instance_variable_set(:@improper, false)
tail.immutable!
tail = new_node
list = list.tail
index -= 1
end
if not tail.immutable?
tail.instance_variable_set(:@tail, list.tail)
tail.immutable!
end
return out.tail
end
end | ruby | {
"resource": ""
} |
q2468 | Erlang.List.permutation | train | def permutation(length = size, &block)
raise Erlang::ImproperListError if improper?
return enum_for(:permutation, length) if not block_given?
if length == 0
yield Erlang::Nil
elsif length == 1
each { |obj| yield Erlang::Cons.new(obj, Erlang::Nil) }
elsif not empty?
if length < size
tail.permutation(length, &block)
end
tail.permutation(length-1) do |p|
0.upto(length-1) do |i|
left,right = p.split_at(i)
yield left.append(right.cons(head))
end
end
end
return self
end | ruby | {
"resource": ""
} |
q2469 | Erlang.List.partition | train | def partition(&block)
raise Erlang::ImproperListError if improper?
return enum_for(:partition) if not block_given?
left = left_tail = Erlang::Cons.allocate
right = right_tail = Erlang::Cons.allocate
list = self
while !list.empty?
if yield(list.head)
new_node = Erlang::Cons.allocate
new_node.instance_variable_set(:@head, list.head)
new_node.instance_variable_set(:@improper, false)
left_tail.instance_variable_set(:@tail, new_node)
left_tail.instance_variable_set(:@improper, false)
left_tail.immutable!
left_tail = new_node
list = list.tail
else
new_node = Erlang::Cons.allocate
new_node.instance_variable_set(:@head, list.head)
new_node.instance_variable_set(:@improper, false)
right_tail.instance_variable_set(:@tail, new_node)
right_tail.instance_variable_set(:@improper, false)
right_tail.immutable!
right_tail = new_node
list = list.tail
end
end
if not left_tail.immutable?
left_tail.instance_variable_set(:@tail, Erlang::Nil)
left_tail.immutable!
end
if not right_tail.immutable?
right_tail.instance_variable_set(:@tail, Erlang::Nil)
right_tail.immutable!
end
return Erlang::Tuple[left.tail, right.tail]
end | ruby | {
"resource": ""
} |
q2470 | Erlang.List.inspect | train | def inspect
if improper?
result = 'Erlang::List['
list = to_proper_list
list.each_with_index { |obj, i| result << ', ' if i > 0; result << obj.inspect }
result << ']'
result << " + #{last(true).inspect}"
return result
else
result = '['
list = self
list.each_with_index { |obj, i| result << ', ' if i > 0; result << obj.inspect }
result << ']'
return result
end
end | ruby | {
"resource": ""
} |
q2471 | Erlang.Binary.copy | train | def copy(n = 1)
raise ArgumentError, 'n must be a non-negative Integer' if not n.is_a?(::Integer) or n < 0
return self if n == 1
return Erlang::Binary[(@data * n)]
end | ruby | {
"resource": ""
} |
q2472 | Erlang.Binary.each_bit | train | def each_bit
return enum_for(:each_bit) unless block_given?
index = 0
bitsize = self.bitsize
@data.each_byte do |byte|
loop do
break if index == bitsize
bit = (byte >> (7 - (index & 7))) & 1
yield bit
index += 1
break if (index & 7) == 0
end
end
return self
end | ruby | {
"resource": ""
} |
q2473 | Erlang.Binary.part | train | def part(position, length)
raise ArgumentError, 'position must be an Integer' if not position.is_a?(::Integer)
raise ArgumentError, 'length must be a non-negative Integer' if not length.is_a?(::Integer) or length < 0
return Erlang::Binary[@data.byteslice(position, length)]
end | ruby | {
"resource": ""
} |
q2474 | Culerity.RemoteBrowserProxy.wait_until | train | def wait_until time_to_wait=30, &block
time_limit = Time.now + time_to_wait
until block.call
if Time.now > time_limit
raise "wait_until timeout after #{time_to_wait} seconds"
end
sleep 0.1
end
true
end | ruby | {
"resource": ""
} |
q2475 | Culerity.RemoteBrowserProxy.confirm | train | def confirm(bool, &block)
blk = "lambda { #{bool} }"
self.send_remote(:add_listener, :confirm) { blk }
block.call
self.send_remote(:remove_listener, :confirm, lambda {blk})
end | ruby | {
"resource": ""
} |
q2476 | Pixiv.Page.bind | train | def bind(client)
if self.class.const_defined?(:WithClient)
mod = self.class.const_get(:WithClient)
else
mod = Page::WithClient
end
unless singleton_class.include?(mod)
extend(mod)
end
self.client = client
self
end | ruby | {
"resource": ""
} |
q2477 | Pixiv.Client.login | train | def login(pixiv_id, password)
doc = agent.get("https://accounts.pixiv.net/login?lang=ja&source=pc&view_type=page")
return if doc && doc.body =~ /logout/
form = doc.forms_with(action: '/login').first
puts doc.body and raise Error::LoginFailed, 'login form is not available' unless form
form.pixiv_id = pixiv_id
form.password = password
doc = agent.submit(form)
raise Error::LoginFailed unless doc && doc.body =~ /logout/
@member_id = member_id_from_mypage(doc)
end | ruby | {
"resource": ""
} |
q2478 | Pixiv.Client.download_illust | train | def download_illust(illust, io_or_filename, size = :original)
size = {:s => :small, :m => :medium, :o => :original}[size] || size
url = illust.__send__("#{size}_image_url")
referer = case size
when :small then nil
when :medium then illust.url
when :original then illust.url
else raise ArgumentError, "unknown size `#{size}`"
end
save_to = io_or_filename
if save_to.is_a?(Array)
save_to = filename_from_pattern(save_to, illust, url)
end
FileUtils.mkdir_p(File.dirname(save_to)) unless save_to.respond_to?(:write)
@agent.download(url, save_to, [], referer)
end | ruby | {
"resource": ""
} |
q2479 | Pixiv.Client.download_manga | train | def download_manga(illust, pattern, &block)
action = DownloadActionRegistry.new(&block)
illust.original_image_urls.each_with_index do |url, n|
begin
action.before_each.call(url, n) if action.before_each
filename = filename_from_pattern(pattern, illust, url)
FileUtils.mkdir_p(File.dirname(filename))
@agent.download(url, filename, [], illust.original_image_referer)
action.after_each.call(url, n) if action.after_each
rescue
action.on_error ? action.on_error.call($!) : raise
end
end
end | ruby | {
"resource": ""
} |
q2480 | Pixiv.Client.filename_from_pattern | train | def filename_from_pattern(pattern, illust, url)
pattern.map {|i|
if i == :image_name
name = File.basename(url)
if name =~ /\.(\w+)\?\d+$/
name += '.' + $1
end
name
elsif i.is_a?(Symbol) then illust.send(i)
elsif i.respond_to?(:call) then i.call(illust)
else i
end
}.join('')
end | ruby | {
"resource": ""
} |
q2481 | DNS.Zone.soa | train | def soa
# return the first SOA we find in the records array.
rr = @records.find { |rr| rr.type == "SOA" }
return rr if rr
# otherwise create a new SOA
rr = DNS::Zone::RR::SOA.new
rr.serial = Time.now.utc.strftime("%Y%m%d01")
rr.refresh_ttl = '3h'
rr.retry_ttl = '15m'
rr.expiry_ttl = '4w'
rr.minimum_ttl = '30m'
# store and return new SOA
@records << rr
return rr
end | ruby | {
"resource": ""
} |
q2482 | DNS.Zone.dump_pretty | train | def dump_pretty
content = []
last_type = "SOA"
sorted_records.each do |rr|
content << '' if last_type != rr.type
content << rr.dump
last_type = rr.type
end
content.join("\n") << "\n"
end | ruby | {
"resource": ""
} |
q2483 | DNS.Zone.sorted_records | train | def sorted_records
# pull out RRs we want to stick near the top
top_rrs = {}
top = %w{SOA NS MX SPF TXT}
top.each { |t| top_rrs[t] = @records.select { |rr| rr.type == t } }
remaining = @records.reject { |rr| top.include?(rr.type) }
# sort remaining RRs by type, alphabeticly
remaining.sort! { |a,b| a.type <=> b.type }
top_rrs.values.flatten + remaining
end | ruby | {
"resource": ""
} |
q2484 | Erlang.Associable.update_in | train | def update_in(*key_path, &block)
if key_path.empty?
raise ArgumentError, "must have at least one key in path"
end
key = key_path[0]
if key_path.size == 1
new_value = block.call(fetch(key, nil))
else
value = fetch(key, EmptyMap)
new_value = value.update_in(*key_path[1..-1], &block)
end
return put(key, new_value)
end | ruby | {
"resource": ""
} |
q2485 | Erlang.Associable.dig | train | def dig(key, *rest)
value = get(key)
if rest.empty? || value.nil?
return value
elsif value.respond_to?(:dig)
return value.dig(*rest)
end
end | ruby | {
"resource": ""
} |
q2486 | Pandata.Scraper.download_all_data | train | def download_all_data(url)
next_data_indices = {}
while next_data_indices
html = Downloader.read_page(url)
# Sometimes Pandora returns the same next_data_indices as the previous page.
# If we don't check for this, an infinite loop occurs.
# This problem occurs with tconrad.
prev_next_data_indices = next_data_indices
next_data_indices = @parser.get_next_data_indices(html)
next_data_indices = false if prev_next_data_indices == next_data_indices
url = yield(html, next_data_indices)
end
end | ruby | {
"resource": ""
} |
q2487 | Pandata.Scraper.get_url | train | def get_url(data_name, next_data_indices = {})
if next_data_indices.empty?
next_data_indices = { nextStartIndex: 0, nextLikeStartIndex: 0, nextThumbStartIndex: 0 }
else
next_data_indices = next_data_indices.dup
end
next_data_indices[:webname] = @webname
next_data_indices[:pat] = Downloader.get_pat
DATA_FEED_URLS[data_name] % next_data_indices
end | ruby | {
"resource": ""
} |
q2488 | Masq.Account.yubikey_authenticated? | train | def yubikey_authenticated?(otp)
if yubico_identity? && Account.verify_yubico_otp(otp)
(Account.extract_yubico_identity_from_otp(otp) == yubico_identity)
else
false
end
end | ruby | {
"resource": ""
} |
q2489 | Vcard.DirectoryInfo.[] | train | def [](name)
enum_by_name(name).each { |f| return f.value if f.value != ""}
enum_by_name(name).each { |f| return f.value }
nil
end | ruby | {
"resource": ""
} |
q2490 | Vcard.DirectoryInfo.push_unique | train | def push_unique(field)
push(field) unless @fields.detect { |f| f.name? field.name }
self
end | ruby | {
"resource": ""
} |
q2491 | Vcard.DirectoryInfo.delete | train | def delete(field)
case
when field.name?("BEGIN"), field.name?("END")
raise ArgumentError, "Cannot delete BEGIN or END fields."
else
@fields.delete field
end
self
end | ruby | {
"resource": ""
} |
q2492 | RandomData.Numbers.number | train | def number(n)
n.is_a?(Range) ? n.to_a.rand : rand(n)
end | ruby | {
"resource": ""
} |
q2493 | CSSModules.Rewrite.rewrite_css | train | def rewrite_css(css_module_code)
# Parse incoming CSS into an AST
css_root = Sass::SCSS::CssParser.new(css_module_code, "(CSSModules)", 1).parse
Sass::Tree::Visitors::SetOptions.visit(css_root, {})
ModuleVisitor.visit(css_root)
css_root.render
end | ruby | {
"resource": ""
} |
q2494 | RandomData.Grammar.grammatical_construct | train | def grammatical_construct(grammar, what=nil)
output = ""
if what.nil?
case grammar
when Hash
a_key = grammar.keys.sort_by{rand}[0]
output += grammatical_construct(grammar, a_key)
when Array
grammar.each do |item|
output += grammatical_construct(item)
end
when String
output += grammar
end
else
rhs = grammar[what]
case rhs
when Array
rhs.each do |item|
case item
when Symbol
output += grammatical_construct(grammar,item)
when String
output += item
when Hash
output += grammatical_construct(item)
else
raise "#{item.inspect} must be a symbol or string or Hash"
end
end
when Hash
output+= grammatical_construct(rhs)
when Symbol
output += grammatical_construct(rhs)
when String
output += rhs
else
raise "#{rhs.inspect} must be a symbol, string, Array or Hash"
end
end
return output
end | ruby | {
"resource": ""
} |
q2495 | GoogleStaticMapsHelper.Location.endpoints_for_circle_with_radius | train | def endpoints_for_circle_with_radius(radius, steps = 30)
raise ArgumentError, "Number of points has to be in range of 1..360!" unless (1..360).include? steps
points = []
steps.times do |i|
points << endpoint(radius, i * 360 / steps)
end
points << points.first
points
end | ruby | {
"resource": ""
} |
q2496 | RandomData.Names.companyname | train | def companyname
num = rand(5)
if num == 0
num = 1
end
final = num.times.collect { @@lastnames.rand.capitalize }
if final.count == 1
"#{final.first} #{@@company_types.rand}, #{@@incorporation_types.rand}"
else
incorporation_type = rand(17) % 2 == 0 ? @@incorporation_types.rand : nil
company_type = rand(17) % 2 == 0 ? @@company_types.rand : nil
trailer = company_type.nil? ? "" : " #{company_type}"
trailer << ", #{incorporation_type}" unless incorporation_type.nil?
"#{final[0..-1].join(', ')} & #{final.last}#{trailer}"
end
end | ruby | {
"resource": ""
} |
q2497 | OpenGraphReader.Builder.base | train | def base
base = Base.new
type = @parser.graph.fetch("og:type", "website").downcase
validate_type type
@parser.graph.each do |property|
build_property base, property
end
synthesize_required_properties base
drop_empty_children base
validate base
base
end | ruby | {
"resource": ""
} |
q2498 | Masq.ApplicationHelper.nav | train | def nav(name, url, pages = nil, active = false)
content_tag :li, link_to(name, url), :class => (active || (pages && active_page?(pages)) ? 'act' : nil)
end | ruby | {
"resource": ""
} |
q2499 | Masq.ApplicationHelper.active_page? | train | def active_page?(pages = {})
is_active = pages.include?(params[:controller])
is_active = pages[params[:controller]].include?(params[:action]) if is_active && !pages[params[:controller]].empty?
is_active
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.