_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q21800
Spy.Subroutine.invoke
train
def invoke(object, args, block, called_from) check_arity!(args.size) if base_object.is_a? Class result = if @plan check_for_too_many_arguments!(@plan) @plan.call(object, *args, &block) end else result = if @plan check_for_too_many_arguments!(@plan) @plan.call(*args, &block) end end ensure calls << CallLog.new(object, called_from, args, block, result) end
ruby
{ "resource": "" }
q21801
Spy.Agency.recruit
train
def recruit(spy) raise AlreadyStubbedError if @spies[spy.object_id] check_spy!(spy) @spies[spy.object_id] = spy end
ruby
{ "resource": "" }
q21802
Spy.Constant.hook
train
def hook(opts = {}) opts[:force] ||= false Nest.fetch(base_module).add(self) Agency.instance.recruit(self) @previously_defined = currently_defined? if previously_defined? || !opts[:force] @original_value = base_module.const_get(constant_name, false) end and_return(@new_value) self end
ruby
{ "resource": "" }
q21803
Spy.Constant.unhook
train
def unhook Nest.get(base_module).remove(self) Agency.instance.retire(self) and_return(@original_value) if previously_defined? @original_value = @previously_defined = nil self end
ruby
{ "resource": "" }
q21804
Spy.Mock.method
train
def method(method_name) new_method = super parameters = new_method.parameters if parameters.size >= 1 && parameters.last.last == :mock_method self.class.instance_method(method_name).bind(self) else new_method end end
ruby
{ "resource": "" }
q21805
TE3270.Accessors.text_field
train
def text_field(name, row, column, length, editable=true) define_method(name) do platform.get_string(row, column, length) end define_method("#{name}=") do |value| platform.put_string(value, row, column) end if editable end
ruby
{ "resource": "" }
q21806
TE3270.ScreenPopulator.populate_screen_with
train
def populate_screen_with(hsh) hsh.each do |key, value| self.send("#{key}=", value) if self.respond_to? "#{key}=".to_sym end end
ruby
{ "resource": "" }
q21807
AviGlitch.Frames.size_of
train
def size_of frame_type detection = "is_#{frame_type.to_s.sub(/frames$/, 'frame')}?" @meta.select { |m| Frame.new(nil, m[:id], m[:flag]).send detection }.size end
ruby
{ "resource": "" }
q21808
AviGlitch.Frames.concat
train
def concat other_frames raise TypeError unless other_frames.kind_of?(Frames) # data this_data = Tempfile.new 'this', binmode: true self.frames_data_as_io this_data other_data = Tempfile.new 'other', binmode: true other_frames.frames_data_as_io other_data this_size = this_data.size other_data.rewind while d = other_data.read(BUFFER_SIZE) do this_data.print d end other_data.close! # meta other_meta = other_frames.meta.collect do |m| x = m.dup x[:offset] += this_size x end @meta.concat other_meta # close overwrite this_data this_data.close! self end
ruby
{ "resource": "" }
q21809
AviGlitch.Frames.*
train
def * times result = self.slice 0, 0 frames = self.slice 0..-1 times.times do result.concat frames end result end
ruby
{ "resource": "" }
q21810
AviGlitch.Frames.slice
train
def slice *args b, l = get_beginning_and_length *args if l.nil? self.at b else e = b + l - 1 r = self.to_avi r.frames.each_with_index do |f, i| unless i >= b && i <= e f.data = nil end end r.frames end end
ruby
{ "resource": "" }
q21811
AviGlitch.Frames.at
train
def at n m = @meta[n] return nil if m.nil? @io.pos = @pos_of_movi + m[:offset] + 8 frame = Frame.new(@io.read(m[:size]), m[:id], m[:flag]) @io.rewind frame end
ruby
{ "resource": "" }
q21812
AviGlitch.Frames.push
train
def push frame raise TypeError unless frame.kind_of? Frame # data this_data = Tempfile.new 'this', binmode: true self.frames_data_as_io this_data this_size = this_data.size this_data.print frame.id this_data.print [frame.data.size].pack('V') this_data.print frame.data this_data.print "\000" if frame.data.size % 2 == 1 # meta @meta << { :id => frame.id, :flag => frame.flag, :offset => this_size + 4, # 4 for 'movi' :size => frame.data.size, } # close overwrite this_data this_data.close! self end
ruby
{ "resource": "" }
q21813
AviGlitch.Frames.insert
train
def insert n, *args new_frames = self.slice(0, n) args.each do |f| new_frames.push f end new_frames.concat self.slice(n..-1) self.clear self.concat new_frames self end
ruby
{ "resource": "" }
q21814
AviGlitch.Frames.mutate_keyframes_into_deltaframes!
train
def mutate_keyframes_into_deltaframes! range = nil range = 0..self.size if range.nil? self.each_with_index do |frame, i| if range.include? i frame.flag = 0 if frame.is_keyframe? end end self end
ruby
{ "resource": "" }
q21815
AviGlitch.Base.glitch
train
def glitch target = :all, &block # :yield: data if block_given? @frames.each do |frame| if valid_target? target, frame frame.data = yield frame.data end end self else self.enum_for :glitch, target end end
ruby
{ "resource": "" }
q21816
AviGlitch.Base.glitch_with_index
train
def glitch_with_index target = :all, &block # :yield: data, index if block_given? self.glitch(target).with_index do |x, i| yield x, i end self else self.glitch target end end
ruby
{ "resource": "" }
q21817
AviGlitch.Base.has_keyframe?
train
def has_keyframe? result = false self.frames.each do |f| if f.is_keyframe? result = true break end end result end
ruby
{ "resource": "" }
q21818
AviGlitch.Base.frames=
train
def frames= other raise TypeError unless other.kind_of?(Frames) @frames.clear @frames.concat other end
ruby
{ "resource": "" }
q21819
TTY.File.binary?
train
def binary?(relative_path) bytes = ::File.new(relative_path).size bytes = 2**12 if bytes > 2**12 buffer = ::File.read(relative_path, bytes, 0) || '' buffer = buffer.force_encoding(Encoding.default_external) begin return buffer !~ /\A[\s[[:print:]]]*\z/m rescue ArgumentError => error return true if error.message =~ /invalid byte sequence/ raise end end
ruby
{ "resource": "" }
q21820
TTY.File.checksum_file
train
def checksum_file(source, *args, **options) mode = args.size.zero? ? 'sha256' : args.pop digester = DigestFile.new(source, mode, options) digester.call unless options[:noop] end
ruby
{ "resource": "" }
q21821
TTY.File.chmod
train
def chmod(relative_path, permissions, **options) mode = ::File.lstat(relative_path).mode if permissions.to_s =~ /\d+/ mode = permissions else permissions.scan(/[ugoa][+-=][rwx]+/) do |setting| who, action = setting[0], setting[1] setting[2..setting.size].each_byte do |perm| mask = const_get("#{who.upcase}_#{perm.chr.upcase}") (action == '+') ? mode |= mask : mode ^= mask end end end log_status(:chmod, relative_path, options.fetch(:verbose, true), options.fetch(:color, :green)) ::FileUtils.chmod_R(mode, relative_path) unless options[:noop] end
ruby
{ "resource": "" }
q21822
TTY.File.create_directory
train
def create_directory(destination, *args, **options) parent = args.size.nonzero? ? args.pop : nil if destination.is_a?(String) || destination.is_a?(Pathname) destination = { destination.to_s => [] } end destination.each do |dir, files| path = parent.nil? ? dir : ::File.join(parent, dir) unless ::File.exist?(path) ::FileUtils.mkdir_p(path) log_status(:create, path, options.fetch(:verbose, true), options.fetch(:color, :green)) end files.each do |filename, contents| if filename.respond_to?(:each_pair) create_directory(filename, path, options) else create_file(::File.join(path, filename), contents, options) end end end end
ruby
{ "resource": "" }
q21823
TTY.File.create_file
train
def create_file(relative_path, *args, **options, &block) relative_path = relative_path.to_s content = block_given? ? block[] : args.join CreateFile.new(self, relative_path, content, options).call end
ruby
{ "resource": "" }
q21824
TTY.File.copy_file
train
def copy_file(source_path, *args, **options, &block) source_path = source_path.to_s dest_path = (args.first || source_path).to_s.sub(/\.erb$/, '') ctx = if (vars = options[:context]) vars.instance_eval('binding') else instance_eval('binding') end create_file(dest_path, options) do version = ERB.version.scan(/\d+\.\d+\.\d+/)[0] template = if version.to_f >= 2.2 ERB.new(::File.binread(source_path), trim_mode: "-", eoutvar: "@output_buffer") else ERB.new(::File.binread(source_path), nil, "-", "@output_buffer") end content = template.result(ctx) content = block[content] if block content end return unless options[:preserve] copy_metadata(source_path, dest_path, options) end
ruby
{ "resource": "" }
q21825
TTY.File.copy_metadata
train
def copy_metadata(src_path, dest_path, **options) stats = ::File.lstat(src_path) ::File.utime(stats.atime, stats.mtime, dest_path) chmod(dest_path, stats.mode, options) end
ruby
{ "resource": "" }
q21826
TTY.File.copy_directory
train
def copy_directory(source_path, *args, **options, &block) source_path = source_path.to_s check_path(source_path) source = escape_glob_path(source_path) dest_path = (args.first || source).to_s opts = {recursive: true}.merge(options) pattern = opts[:recursive] ? ::File.join(source, '**') : source glob_pattern = ::File.join(pattern, '*') Dir.glob(glob_pattern, ::File::FNM_DOTMATCH).sort.each do |file_source| next if ::File.directory?(file_source) next if opts[:exclude] && file_source.match(opts[:exclude]) dest = ::File.join(dest_path, file_source.gsub(source_path, '.')) file_dest = ::Pathname.new(dest).cleanpath.to_s copy_file(file_source, file_dest, **options, &block) end end
ruby
{ "resource": "" }
q21827
TTY.File.diff
train
def diff(path_a, path_b, **options) threshold = options[:threshold] || 10_000_000 output = [] open_tempfile_if_missing(path_a) do |file_a| if ::File.size(file_a) > threshold raise ArgumentError, "(file size of #{file_a.path} exceeds #{threshold} bytes, diff output suppressed)" end if binary?(file_a) raise ArgumentError, "(#{file_a.path} is binary, diff output suppressed)" end open_tempfile_if_missing(path_b) do |file_b| if binary?(file_b) raise ArgumentError, "(#{file_a.path} is binary, diff output suppressed)" end if ::File.size(file_b) > threshold return "(file size of #{file_b.path} exceeds #{threshold} bytes, diff output suppressed)" end log_status(:diff, "#{file_a.path} - #{file_b.path}", options.fetch(:verbose, true), options.fetch(:color, :green)) return output.join if options[:noop] block_size = file_a.lstat.blksize while !file_a.eof? && !file_b.eof? output << Differ.new(file_a.read(block_size), file_b.read(block_size), options).call end end end output.join end
ruby
{ "resource": "" }
q21828
TTY.File.download_file
train
def download_file(uri, *args, **options, &block) uri = uri.to_s dest_path = (args.first || ::File.basename(uri)).to_s unless uri =~ %r{^https?\://} copy_file(uri, dest_path, options) return end content = DownloadFile.new(uri, dest_path, options).call if block_given? content = (block.arity.nonzero? ? block[content] : block[]) end create_file(dest_path, content, options) end
ruby
{ "resource": "" }
q21829
TTY.File.prepend_to_file
train
def prepend_to_file(relative_path, *args, **options, &block) log_status(:prepend, relative_path, options.fetch(:verbose, true), options.fetch(:color, :green)) options.merge!(before: /\A/, verbose: false) inject_into_file(relative_path, *(args << options), &block) end
ruby
{ "resource": "" }
q21830
TTY.File.append_to_file
train
def append_to_file(relative_path, *args, **options, &block) log_status(:append, relative_path, options.fetch(:verbose, true), options.fetch(:color, :green)) options.merge!(after: /\z/, verbose: false) inject_into_file(relative_path, *(args << options), &block) end
ruby
{ "resource": "" }
q21831
TTY.File.safe_append_to_file
train
def safe_append_to_file(relative_path, *args, **options, &block) append_to_file(relative_path, *args, **(options.merge(force: false)), &block) end
ruby
{ "resource": "" }
q21832
TTY.File.remove_file
train
def remove_file(relative_path, *args, **options) relative_path = relative_path.to_s log_status(:remove, relative_path, options.fetch(:verbose, true), options.fetch(:color, :red)) return if options[:noop] || !::File.exist?(relative_path) ::FileUtils.rm_r(relative_path, force: options[:force], secure: options.fetch(:secure, true)) end
ruby
{ "resource": "" }
q21833
TTY.File.tail_file
train
def tail_file(relative_path, num_lines = 10, **options, &block) file = ::File.open(relative_path) chunk_size = options.fetch(:chunk_size, 512) line_sep = $/ lines = [] newline_count = 0 ReadBackwardFile.new(file, chunk_size).each_chunk do |chunk| # look for newline index counting from right of chunk while (nl_index = chunk.rindex(line_sep, (nl_index || chunk.size) - 1)) newline_count += 1 break if newline_count > num_lines || nl_index.zero? end if newline_count > num_lines lines.insert(0, chunk[(nl_index + 1)..-1]) break else lines.insert(0, chunk) end end lines.join.split(line_sep).each(&block).to_a end
ruby
{ "resource": "" }
q21834
TTY.File.log_status
train
def log_status(cmd, message, verbose, color = false) return unless verbose cmd = cmd.to_s.rjust(12) if color i = cmd.index(/[a-z]/) cmd = cmd[0...i] + decorate(cmd[i..-1], color) end message = "#{cmd} #{message}" message += "\n" unless message.end_with?("\n") @output.print(message) @output.flush end
ruby
{ "resource": "" }
q21835
TTY.File.open_tempfile_if_missing
train
def open_tempfile_if_missing(object, &block) if ::FileTest.file?(object) ::File.open(object, &block) else tempfile = Tempfile.new('tty-file-diff') tempfile << object tempfile.rewind block[tempfile] unless tempfile.nil? tempfile.close tempfile.unlink end end end
ruby
{ "resource": "" }
q21836
VirtualBox.Snapshot.load_relationship
train
def load_relationship(name) populate_relationship(:parent, interface.parent) populate_relationship(:machine, interface.machine) populate_relationship(:children, interface.children) end
ruby
{ "resource": "" }
q21837
VirtualBox.Snapshot.restore
train
def restore(&block) machine.with_open_session do |session| session.console.restore_snapshot(interface).wait(&block) end end
ruby
{ "resource": "" }
q21838
VirtualBox.Snapshot.destroy
train
def destroy(&block) machine.with_open_session do |session| session.console.delete_snapshot(uuid).wait(&block) end end
ruby
{ "resource": "" }
q21839
VirtualBox.VM.validate
train
def validate super validates_presence_of :name, :os_type_id, :memory_size, :vram_size, :cpu_count validates_numericality_of :memory_balloon_size, :monitor_count validates_inclusion_of :accelerate_3d_enabled, :accelerate_2d_video_enabled, :teleporter_enabled, :in => [true, false] if !errors_on(:name) # Only validate the name if the name has no errors already vms_of_same_name = self.class.find(name) add_error(:name, 'must not be used by another virtual machine.') if vms_of_same_name && vms_of_same_name.uuid != uuid end validates_inclusion_of :os_type_id, :in => VirtualBox::Global.global.lib.virtualbox.guest_os_types.collect { |os| os.id } min_guest_ram, max_guest_ram = Global.global.system_properties.min_guest_ram, Global.global.system_properties.max_guest_ram validates_inclusion_of :memory_size, :in => (min_guest_ram..max_guest_ram), :message => "must be between #{min_guest_ram} and #{max_guest_ram}." validates_inclusion_of :memory_balloon_size, :in => (0..max_guest_ram), :message => "must be between 0 and #{max_guest_ram}." min_guest_vram, max_guest_vram = Global.global.system_properties.min_guest_vram, Global.global.system_properties.max_guest_vram validates_inclusion_of :vram_size, :in => (min_guest_vram..max_guest_vram), :message => "must be between #{min_guest_vram} and #{max_guest_vram}." min_guest_cpu_count, max_guest_cpu_count = Global.global.system_properties.min_guest_cpu_count, Global.global.system_properties.max_guest_cpu_count validates_inclusion_of :cpu_count, :in => (min_guest_cpu_count..max_guest_cpu_count), :message => "must be between #{min_guest_cpu_count} and #{max_guest_cpu_count}." validates_inclusion_of :clipboard_mode, :in => COM::Util.versioned_interface(:ClipboardMode).map validates_inclusion_of :firmware_type, :in => COM::Util.versioned_interface(:FirmwareType).map end
ruby
{ "resource": "" }
q21840
VirtualBox.VM.root_snapshot
train
def root_snapshot return nil if current_snapshot.nil? current = current_snapshot current = current.parent while current.parent != nil current end
ruby
{ "resource": "" }
q21841
VirtualBox.VM.find_snapshot
train
def find_snapshot(name) find_helper = lambda do |name, root| return nil if root.nil? return root if root.name == name || root.uuid == name root.children.each do |child| result = find_helper.call(name, child) return result unless result.nil? end nil end find_helper.call(name, root_snapshot) end
ruby
{ "resource": "" }
q21842
VirtualBox.VM.with_open_session
train
def with_open_session(mode=:write) # Set the session up session = Lib.lib.session close_session = false if session.state != :open # Open up a session for this virtual machine interface.lock_machine(session, mode) # Mark the session to be closed close_session = true end # Yield the block with the session yield session if block_given? # Close the session if close_session # Save these settings only if we're closing and only if the state # is not saved, since that doesn't allow the machine to be saved. session.machine.save_settings if mode == :write && session.machine.state != :saved # Close the session session.unlock_machine end rescue Exception # Close the session so we don't get locked out. We use a rescue block # here instead of an "ensure" since we ONLY want this to occur if an # exception is raised. Otherwise, we may or may not close the session, # depending how deeply nested this call to `with_open_session` is. # (see close_session boolean above) session.unlock_machine if session.state == :open # Reraise the exception, we're not actually catching it to handle it raise end
ruby
{ "resource": "" }
q21843
VirtualBox.VM.export
train
def export(filename, options = {}, &block) app = Appliance.new app.path = filename app.add_machine(self, options) app.export(&block) end
ruby
{ "resource": "" }
q21844
VirtualBox.VM.take_snapshot
train
def take_snapshot(name, description="", &block) with_open_session do |session| session.console.take_snapshot(name, description).wait(&block) end end
ruby
{ "resource": "" }
q21845
VirtualBox.VM.get_boot_order
train
def get_boot_order(interface, key) max_boot = Global.global.system_properties.max_boot_position (1..max_boot).inject([]) do |order, position| order << interface.get_boot_order(position) order end end
ruby
{ "resource": "" }
q21846
VirtualBox.VM.set_boot_order
train
def set_boot_order(interface, key, value) max_boot = Global.global.system_properties.max_boot_position value = value.dup value.concat(Array.new(max_boot - value.size)) if value.size < max_boot (1..max_boot).each do |position| interface.set_boot_order(position, value[position - 1]) end end
ruby
{ "resource": "" }
q21847
VirtualBox.Appliance.initialize_from_path
train
def initialize_from_path(path) # Read in the data from the path interface.read(path).wait_for_completion(-1) # Interpret the data to fill in the interface properties interface.interpret # Load the interface attributes load_interface_attributes(interface) # Fill in the virtual systems populate_relationship(:virtual_systems, interface.virtual_system_descriptions) # Should be an existing record existing_record! end
ruby
{ "resource": "" }
q21848
VirtualBox.Appliance.add_machine
train
def add_machine(vm, options = {}) sys_desc = vm.interface.export(interface, path) options.each do |key, value| sys_desc.add_description(key, value, value) end end
ruby
{ "resource": "" }
q21849
VirtualBox.ExtraData.save
train
def save changes.each do |key, value| interface.set_extra_data(key.to_s, value[1].to_s) clear_dirty!(key) if value[1].nil? # Remove the key from the hash altogether hash_delete(key.to_s) end end end
ruby
{ "resource": "" }
q21850
VirtualBox.NATEngine.initialize_attributes
train
def initialize_attributes(parent, inat) write_attribute(:parent, parent) write_attribute(:interface, inat) # Load the interface attributes associated with this model load_interface_attributes(inat) populate_relationships(inat) # Clear dirty and set as existing clear_dirty! existing_record! end
ruby
{ "resource": "" }
q21851
VirtualBox.HostNetworkInterface.dhcp_server
train
def dhcp_server(create_if_not_found=true) return nil if interface_type != :host_only # Try to find the dhcp server in the list of DHCP servers. dhcp_name = "HostInterfaceNetworking-#{name}" result = parent.parent.dhcp_servers.find do |dhcp| dhcp.network_name == dhcp_name end # If no DHCP server is found, create one result = parent.parent.dhcp_servers.create(dhcp_name) if result.nil? && create_if_not_found result end
ruby
{ "resource": "" }
q21852
VirtualBox.HostNetworkInterface.attached_vms
train
def attached_vms parent.parent.vms.find_all do |vm| next if !vm.accessible? result = vm.network_adapters.find do |adapter| adapter.enabled? && adapter.host_only_interface == name end !result.nil? end end
ruby
{ "resource": "" }
q21853
VirtualBox.HostNetworkInterface.enable_static
train
def enable_static(ip, netmask=nil) netmask ||= network_mask interface.enable_static_ip_config(ip, netmask) reload end
ruby
{ "resource": "" }
q21854
VirtualBox.DHCPServer.destroy
train
def destroy parent.lib.virtualbox.remove_dhcp_server(interface) parent_collection.delete(self, true) true end
ruby
{ "resource": "" }
q21855
VirtualBox.DHCPServer.host_network
train
def host_network return nil unless network_name =~ /^HostInterfaceNetworking-(.+?)$/ parent.host.network_interfaces.detect do |i| i.interface_type == :host_only && i.name == $1.to_s end end
ruby
{ "resource": "" }
q21856
VirtualBox.SharedFolder.save
train
def save return true if !new_record? && !changed? raise Exceptions::ValidationFailedException.new(errors) if !valid? if !new_record? # If its not a new record, any changes will require a new shared # folder to be created, so we first destroy it then recreate it. destroy(false) end create end
ruby
{ "resource": "" }
q21857
VirtualBox.SharedFolder.added_to_relationship
train
def added_to_relationship(proxy) was_clean = parent.nil? && !changed? write_attribute(:parent, proxy.parent) write_attribute(:parent_collection, proxy) # This keeps existing records not dirty when added to collection clear_dirty! if !new_record? && was_clean end
ruby
{ "resource": "" }
q21858
VirtualBox.SharedFolder.destroy
train
def destroy(update_collection=true) parent.with_open_session do |session| machine = session.machine machine.remove_shared_folder(name) end # Remove it from it's parent collection parent_collection.delete(self, true) if parent_collection && update_collection # Mark as a new record so if it is saved again, it will create it new_record! end
ruby
{ "resource": "" }
q21859
VirtualBox.AbstractModel.errors
train
def errors self.class.relationships.inject(super) do |acc, data| name, options = data if options && options[:klass].respond_to?(:errors_for_relationship) errors = options[:klass].errors_for_relationship(self, relationship_data[name]) acc.merge!(name => errors) if errors && !errors.empty? end acc end end
ruby
{ "resource": "" }
q21860
VirtualBox.AbstractModel.validate
train
def validate(*args) # First clear all previous errors clear_errors # Then do the validations failed = false self.class.relationships.each do |name, options| next unless options && options[:klass].respond_to?(:validate_relationship) failed = true if !options[:klass].validate_relationship(self, relationship_data[name], *args) end return !failed end
ruby
{ "resource": "" }
q21861
VirtualBox.AbstractModel.save
train
def save(*args) # Go through changed attributes and call save_attribute for # those only changes.each do |key, values| save_attribute(key, values[1], *args) end # Go through and only save the loaded relationships, since # only those would be modified. self.class.relationships.each do |name, options| save_relationship(name, *args) end # No longer a new record @new_record = false true end
ruby
{ "resource": "" }
q21862
VirtualBox.ForwardedPort.device
train
def device # Return the current or default value if it is: # * an existing record, since it was already mucked with, no need to # modify it again # * device setting changed, since we should return what the user set # it to # * If the parent is nil, since we can't infer the type without a parent return read_attribute(:device) if !new_record? || device_changed? || parent.nil? device_map = { :Am79C970A => "pcnet", :Am79C973 => "pcnet", :I82540EM => "e1000", :I82543GC => "e1000", :I82545EM => "e1000" } return device_map[parent.network_adapters[0].adapter_type] end
ruby
{ "resource": "" }
q21863
VirtualBox.IntegrationHelpers.snapshot_map
train
def snapshot_map(snapshots, &block) applier = lambda do |snapshot| return if !snapshot || snapshot.empty? snapshot[:children].each do |child| applier.call(child) end block.call(snapshot) end applier.call(snapshots) end
ruby
{ "resource": "" }
q21864
VirtualBox.HardDrive.validate
train
def validate super medium_formats = Global.global.system_properties.medium_formats.collect { |mf| mf.id } validates_inclusion_of :format, :in => medium_formats, :message => "must be one of the following: #{medium_formats.join(', ')}." validates_presence_of :location max_vdi_size = Global.global.system_properties.info_vdi_size validates_inclusion_of :logical_size, :in => (0..max_vdi_size), :message => "must be between 0 and #{max_vdi_size}." end
ruby
{ "resource": "" }
q21865
VirtualBox.HardDrive.create
train
def create return false unless new_record? raise Exceptions::ValidationFailedException.new(errors) if !valid? # Create the new Hard Disk medium new_medium = create_hard_disk_medium(location, format) # Create the storage on the host system new_medium.create_base_storage(logical_size, :standard).wait_for_completion(-1) # Update the current Hard Drive instance with the uuid and # other attributes assigned after storage was written write_attribute(:interface, new_medium) initialize_attributes(new_medium) # If the uuid is present, then everything worked uuid && !uuid.to_s.empty? end
ruby
{ "resource": "" }
q21866
VirtualBox.HardDrive.save
train
def save return true if !new_record? && !changed? raise Exceptions::ValidationFailedException.new(errors) if !valid? if new_record? create # Create a new hard drive else # Mediums like Hard Drives are not updatable, they need to be recreated # Because Hard Drives contain info and paritions, it's easier to error # out now than try and do some complicated logic msg = "Hard Drives cannot be updated. You need to create one from scratch." raise Exceptions::MediumNotUpdatableException.new(msg) end end
ruby
{ "resource": "" }
q21867
VirtualBox.NetworkAdapter.initialize_attributes
train
def initialize_attributes(parent, inetwork) # Set the parent and interface write_attribute(:parent, parent) write_attribute(:interface, inetwork) # Load the interface attributes load_interface_attributes(inetwork) # Clear dirtiness, since this should only be called initially and # therefore shouldn't affect dirtiness clear_dirty! # But this is an existing record existing_record! end
ruby
{ "resource": "" }
q21868
VirtualBox.NetworkAdapter.host_interface_object
train
def host_interface_object VirtualBox::Global.global.host.network_interfaces.find do |ni| ni.name == host_only_interface end end
ruby
{ "resource": "" }
q21869
VirtualBox.NetworkAdapter.bridged_interface_object
train
def bridged_interface_object VirtualBox::Global.global.host.network_interfaces.find do |ni| ni.name == bridged_interface end end
ruby
{ "resource": "" }
q21870
VirtualBox.NetworkAdapter.modify_adapter
train
def modify_adapter parent_machine.with_open_session do |session| machine = session.machine yield machine.get_network_adapter(slot) end end
ruby
{ "resource": "" }
q21871
Browser.RSpecHelpers.html
train
def html(html_string='') html = %Q{<div id="opal-jquery-test-div">#{html_string}</div>} before do @_spec_html = Element.parse(html) @_spec_html.append_to_body end after { @_spec_html.remove } end
ruby
{ "resource": "" }
q21872
BTC.Script.versioned_script?
train
def versioned_script? return chunks.size == 1 && chunks[0].pushdata? && chunks[0].canonical? && chunks[0].pushdata.bytesize > 2 end
ruby
{ "resource": "" }
q21873
BTC.Script.open_assets_marker?
train
def open_assets_marker? return false if !op_return_data_only_script? data = op_return_data return false if !data || data.bytesize < 6 if data[0, AssetMarker::PREFIX_V1.bytesize] == AssetMarker::PREFIX_V1 return true end false end
ruby
{ "resource": "" }
q21874
BTC.Script.simulated_signature_script
train
def simulated_signature_script(strict: true) if public_key_hash_script? # assuming non-compressed pubkeys to be conservative return Script.new << Script.simulated_signature(hashtype: SIGHASH_ALL) << Script.simulated_uncompressed_pubkey elsif public_key_script? return Script.new << Script.simulated_signature(hashtype: SIGHASH_ALL) elsif script_hash_script? && !strict # This is a wild approximation, but works well if most p2sh scripts are 2-of-3 multisig scripts. # If you have a very particular smart contract scheme you should not use TransactionBuilder which estimates fees this way. return Script.new << OP_0 << [Script.simulated_signature(hashtype: SIGHASH_ALL)]*2 << Script.simulated_multisig_script(2,3).data elsif multisig_script? return Script.new << OP_0 << [Script.simulated_signature(hashtype: SIGHASH_ALL)]*self.multisig_signatures_required else return nil end end
ruby
{ "resource": "" }
q21875
BTC.Script.append_pushdata
train
def append_pushdata(data, opcode: nil) raise ArgumentError, "No data provided" if !data encoded_pushdata = self.class.encode_pushdata(data, opcode: opcode) if !encoded_pushdata raise ArgumentError, "Cannot encode pushdata with opcode #{opcode}" end @chunks << ScriptChunk.new(encoded_pushdata) return self end
ruby
{ "resource": "" }
q21876
BTC.Script.delete_opcode
train
def delete_opcode(opcode) @chunks = @chunks.inject([]) do |list, chunk| list << chunk if chunk.opcode != opcode list end return self end
ruby
{ "resource": "" }
q21877
BTC.Script.delete_pushdata
train
def delete_pushdata(pushdata) @chunks = @chunks.inject([]) do |list, chunk| list << chunk if chunk.pushdata != pushdata list end return self end
ruby
{ "resource": "" }
q21878
BTC.Script.find_and_delete
train
def find_and_delete(subscript) subscript.is_a?(Script) or raise ArgumentError,"Argument must be an instance of BTC::Script" # Replacing [a b a] # Script: a b b a b a b a c # Result: a b b b a c subscriptsize = subscript.chunks.size buf = [] i = 0 result = Script.new chunks.each do |chunk| if chunk == subscript.chunks[i] buf << chunk i+=1 if i == subscriptsize # matched the whole subscript i = 0 buf.clear end else i = 0 result << buf result << chunk end end result end
ruby
{ "resource": "" }
q21879
BTC.AssetTransactionOutput.parse_assets_data
train
def parse_assets_data(data, offset: 0) v, len = WireFormat.read_uint8(data: data, offset: offset) raise ArgumentError, "Invalid data: verified flag" if !v asset_hash, len = WireFormat.read_string(data: data, offset: len) # empty or 20 bytes raise ArgumentError, "Invalid data: asset hash" if !asset_hash value, len = WireFormat.read_int64le(data: data, offset: len) raise ArgumentError, "Invalid data: value" if !value @verified = (v == 1) @asset_id = asset_hash.bytesize > 0 ? AssetID.new(hash: asset_hash) : nil @value = value len end
ruby
{ "resource": "" }
q21880
BTC.Base58.base58_from_data
train
def base58_from_data(data) raise ArgumentError, "Data is missing" if !data leading_zeroes = 0 int = 0 base = 1 data.bytes.reverse_each do |byte| if byte == 0 leading_zeroes += 1 else leading_zeroes = 0 int += base*byte end base *= 256 end return ("1"*leading_zeroes) + base58_from_int(int) end
ruby
{ "resource": "" }
q21881
BTC.Base58.data_from_base58
train
def data_from_base58(string) raise ArgumentError, "String is missing" if !string int = int_from_base58(string) bytes = [] while int > 0 remainder = int % 256 int = int / 256 bytes.unshift(remainder) end data = BTC::Data.data_from_bytes(bytes) byte_for_1 = "1".bytes.first BTC::Data.ensure_ascii_compatible_encoding(string).bytes.each do |byte| break if byte != byte_for_1 data = "\x00" + data end data end
ruby
{ "resource": "" }
q21882
BTC.TransactionBuilder.compute_fee_for_transaction
train
def compute_fee_for_transaction(tx, fee_rate) # Return mining fee if set manually return fee if fee # Compute fees for this tx by composing a tx with properly sized dummy signatures. simulated_tx = tx.dup simulated_tx.inputs.each do |txin| txout_script = txin.transaction_output.script txin.signature_script = txout_script.simulated_signature_script(strict: false) || txout_script end return simulated_tx.compute_fee(fee_rate: fee_rate) end
ruby
{ "resource": "" }
q21883
BTC.CurrencyFormatter.string_from_number
train
def string_from_number(number) if @style == :btc number = number.to_i return "#{number / BTC::COIN}.#{'%08d' % [number % BTC::COIN]}".gsub(/0+$/,"").gsub(/\.$/,".0") elsif @style == :btc_long number = number.to_i return "#{number / BTC::COIN}.#{'%08d' % [number % BTC::COIN]}" else # TODO: parse other styles raise "Not implemented" end end
ruby
{ "resource": "" }
q21884
BTC.CurrencyFormatter.number_from_string
train
def number_from_string(string) bd = BigDecimal.new(string) if @style == :btc || @style == :btc_long return (bd * BTC::COIN).to_i else # TODO: support other styles raise "Not Implemented" end end
ruby
{ "resource": "" }
q21885
BTC.AssetProcessor.partial_verify_asset_transaction
train
def partial_verify_asset_transaction(asset_transaction) raise ArgumentError, "Asset Transaction is missing" if !asset_transaction # 1. Verify issuing transactions and collect transfer outputs cache_transactions do if !verify_issues(asset_transaction) return nil end # No transfer outputs, this transaction is verified. # If there are assets on some inputs, they are destroyed. if asset_transaction.transfer_outputs.size == 0 # We keep inputs unverified to indicate that they were not even processed. return [] end # 2. Fetch parent transactions to verify. # * Verify inputs from non-OpenAsset transactions. # * Return OA transactions for verification. # * Link each input to its OA transaction output. prev_unverified_atxs_by_hash = {} asset_transaction.inputs.each do |ain| txin = ain.transaction_input # Ask source if it has a cached verified transaction for this input. prev_atx = @source.verified_asset_transaction_for_hash(txin.previous_hash) if prev_atx BTC::Invariant(prev_atx.verified?, "Cached verified tx must be fully verified") end prev_atx ||= prev_unverified_atxs_by_hash[txin.previous_hash] if !prev_atx prev_tx = transaction_for_input(txin) if !prev_tx Diagnostics.current.add_message("Failed to load previous transaction for input #{ain.index}: #{txin.previous_id}") return nil end begin prev_atx = AssetTransaction.new(transaction: prev_tx) prev_unverified_atxs_by_hash[prev_atx.transaction_hash] = prev_atx rescue FormatError => e # Previous transaction is not a valid Open Assets transaction, # so we mark the input as uncolored and verified as such. ain.asset_id = nil ain.value = nil ain.verified = true end end # Remember a reference to this transaction so we can validate the whole `asset_transaction` when all previous ones are set and verified. ain.previous_asset_transaction = prev_atx end # each input # Return all unverified transactions. # Note: this won't include the already verified one. prev_unverified_atxs_by_hash.values end end
ruby
{ "resource": "" }
q21886
BTC.AssetProcessor.verify_issues
train
def verify_issues(asset_transaction) previous_txout = nil # fetch only when we have > 0 issue outputs asset_transaction.outputs.each do |aout| if !aout.verified? if aout.value && aout.value > 0 if aout.issue? previous_txout ||= transaction_output_for_input(asset_transaction.inputs[0].transaction_input) if !previous_txout Diagnostics.current.add_message("Failed to assign AssetID to issue output #{aout.index}: can't find output for input #0") return false end aout.asset_id = AssetID.new(script: previous_txout.script, network: self.network) # Output issues some known asset and amount and therefore it is verified. aout.verified = true else # Transfer outputs must be matched with known asset ids on the inputs. end else # Output without a value is uncolored. aout.asset_id = nil aout.value = nil aout.verified = true end end end true end
ruby
{ "resource": "" }
q21887
BTC.ProofOfWork.target_from_bits
train
def target_from_bits(bits) exponent = ((bits >> 24) & 0xff) mantissa = bits & 0x7fffff mantissa *= -1 if (bits & 0x800000) > 0 (mantissa * (256**(exponent-3))).to_i end
ruby
{ "resource": "" }
q21888
BTC.ProofOfWork.hash_from_target
train
def hash_from_target(target) bytes = [] while target > 0 bytes << (target % 256) target /= 256 end BTC::Data.data_from_bytes(bytes).ljust(32, "\x00".b) end
ruby
{ "resource": "" }
q21889
BTC.Mnemonic.print_addresses
train
def print_addresses(range: 0..100, network: BTC::Network.mainnet, account: 0) kc = keychain.bip44_keychain(network: network).bip44_account_keychain(account) puts "Addresses for account #{account} on #{network.name}" puts "Account xpub: #{kc.xpub}" puts "Account external xpub: #{kc.bip44_external_keychain.xpub}" puts "Index".ljust(10) + "External Address".ljust(40) + "Internal Address".ljust(40) range.each do |i| s = "" s << "#{i}".ljust(10) s << kc.bip44_external_keychain.derived_key(i).address.to_s.ljust(40) s << kc.bip44_internal_keychain.derived_key(i).address.to_s.ljust(40) puts s end end
ruby
{ "resource": "" }
q21890
BTC.Opcode.opcode_for_small_integer
train
def opcode_for_small_integer(small_int) raise ArgumentError, "small_int must not be nil" if !small_int return OP_0 if small_int == 0 return OP_1NEGATE if small_int == -1 if small_int >= 1 && small_int <= 16 return OP_1 + (small_int - 1) end return OP_INVALIDOPCODE end
ruby
{ "resource": "" }
q21891
BTC.Diagnostics.record
train
def record(&block) recording_groups << Array.new last_group = nil begin yield ensure last_group = recording_groups.pop end last_group end
ruby
{ "resource": "" }
q21892
BTC.Diagnostics.add_message
train
def add_message(message, info: nil) self.last_message = message self.last_info = info self.last_item = Item.new(message, info) # add to each recording group recording_groups.each do |group| group << Item.new(message, info) end @uniq_trace_streams.each do |stream| stream.puts message end return self end
ruby
{ "resource": "" }
q21893
BTC.StringExtensions.to_wif
train
def to_wif(network: nil, public_key_compressed: nil) BTC::WIF.new(private_key: self, network: network, public_key_compressed: public_key_compressed).to_s end
ruby
{ "resource": "" }
q21894
BTC.SecretSharing.restore
train
def restore(shares) prime = @order shares = shares.dup.uniq raise "No shares provided" if shares.size == 0 points = shares.map{|s| point_from_string(s) } # [[m,x,y],...] ms = points.map{|p| p[0]}.uniq xs = points.map{|p| p[1]}.uniq raise "Shares do not use the same M value" if ms.size > 1 m = ms.first raise "All shares must have unique X values" if xs.size != points.size raise "Number of shares should be M or more" if points.size < m points = points[0, m] # make sure we have exactly M points y = 0 points.size.times do |formula| # 0..(m-1) # Multiply the numerator across the top and denominators across the bottom to do Lagrange's interpolation numerator = 1 denominator = 1 points.size.times do |count| # 0..(m-1) if formula != count # skip element with i == j startposition = points[formula][1] nextposition = points[count][1] numerator = (numerator * -nextposition) % prime denominator = (denominator * (startposition - nextposition)) % prime end end value = points[formula][2] y = (prime + y + (value * numerator * modinv(denominator, prime))) % prime end return be_from_int(y) end
ruby
{ "resource": "" }
q21895
BTC.AssetTransactionBuilder.issue_asset
train
def issue_asset(source_script: nil, source_output: nil, amount: nil, script: nil, address: nil) raise ArgumentError, "Either `source_script` or `source_output` must be specified" if !source_script && !source_output raise ArgumentError, "Both `source_script` and `source_output` cannot be specified" if source_script && source_output raise ArgumentError, "Either `script` or `address` must be specified" if !script && !address raise ArgumentError, "Both `script` and `address` cannot be specified" if script && address raise ArgumentError, "Amount must be greater than zero" if !amount || amount <= 0 if source_output && (!source_output.index || !source_output.transaction_hash) raise ArgumentError, "If `source_output` is specified, it must have valid `transaction_hash` and `index` attributes" end script ||= AssetAddress.parse(address).script # Ensure source output is a verified asset output. if source_output if source_output.is_a?(AssetTransactionOutput) raise ArgumentError, "Must be verified asset output to spend" if !source_output.verified? else source_output = AssetTransactionOutput.new(transaction_output: source_output, verified: true) end end # Set either the script or output only once. # All the remaining issuances must use the same script or output. if !self.issuing_asset_script && !self.issuing_asset_output self.issuing_asset_script = source_script self.issuing_asset_output = source_output else if self.issuing_asset_script != source_script || self.issuing_asset_output != source_output raise ArgumentError, "Can't issue more assets from a different source script or source output" end end self.issued_assets << {amount: amount, script: script} end
ruby
{ "resource": "" }
q21896
BTC.AssetTransactionBuilder.send_bitcoin
train
def send_bitcoin(output: nil, amount: nil, script: nil, address: nil) if !output raise ArgumentError, "Either `script` or `address` must be specified" if !script && !address raise ArgumentError, "Amount must be specified (>= 0)" if (!amount || amount < 0) script ||= address.public_address.script if address output = TransactionOutput.new(value: amount, script: script) end self.bitcoin_outputs << output end
ruby
{ "resource": "" }
q21897
BTC.CLTVExtension.handle_opcode
train
def handle_opcode(interpreter: nil, opcode: nil) # We are not supposed to handle any other opcodes here. return false if opcode != OP_CHECKLOCKTIMEVERIFY if interpreter.stack.size < 1 return interpreter.set_error(SCRIPT_ERR_INVALID_STACK_OPERATION) end # Note that elsewhere numeric opcodes are limited to # operands in the range -2**31+1 to 2**31-1, however it is # legal for opcodes to produce results exceeding that # range. This limitation is implemented by CScriptNum's # default 4-byte limit. # # If we kept to that limit we'd have a year 2038 problem, # even though the nLockTime field in transactions # themselves is uint32 which only becomes meaningless # after the year 2106. # # Thus as a special case we tell CScriptNum to accept up # to 5-byte bignums, which are good until 2**39-1, well # beyond the 2**32-1 limit of the nLockTime field itself. locktime = interpreter.cast_to_number(interpreter.stack.last, max_size: @locktime_max_size) # In the rare event that the argument may be < 0 due to # some arithmetic being done first, you can always use # 0 MAX CHECKLOCKTIMEVERIFY. if locktime < 0 return interpreter.set_error(SCRIPT_ERR_NEGATIVE_LOCKTIME) end # Actually compare the specified lock time with the transaction. checker = @lock_time_checker || interpreter.signature_checker if !checker.check_lock_time(locktime) return interpreter.set_error(SCRIPT_ERR_UNSATISFIED_LOCKTIME) end return true end
ruby
{ "resource": "" }
q21898
BTC.TransactionInput.init_with_stream
train
def init_with_stream(stream) if stream.eof? raise ArgumentError, "Can't parse transaction input from stream because it is already closed." end if !(@previous_hash = stream.read(32)) || @previous_hash.bytesize != 32 raise ArgumentError, "Failed to read 32-byte previous_hash from stream." end if !(@previous_index = BTC::WireFormat.read_uint32le(stream: stream).first) raise ArgumentError, "Failed to read previous_index from stream." end is_coinbase = (@previous_hash == ZERO_HASH256 && @previous_index == INVALID_INDEX) if !(scriptdata = BTC::WireFormat.read_string(stream: stream).first) raise ArgumentError, "Failed to read signature_script data from stream." end @coinbase_data = nil @signature_script = nil if is_coinbase @coinbase_data = scriptdata else @signature_script = BTC::Script.new(data: scriptdata) end if !(@sequence = BTC::WireFormat.read_uint32le(stream: stream).first) raise ArgumentError, "Failed to read sequence from stream." end end
ruby
{ "resource": "" }
q21899
BTC.Transaction.init_with_components
train
def init_with_components(version: CURRENT_VERSION, inputs: [], outputs: [], lock_time: 0) @version = version || CURRENT_VERSION @inputs = inputs || [] @outputs = outputs || [] @lock_time = lock_time || 0 @inputs.each_with_index do |txin, i| txin.transaction = self txin.index = i end @outputs.each_with_index do |txout, i| txout.transaction = self txout.index = i end end
ruby
{ "resource": "" }