_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q22200
CFPropertyList.Binary.read_binary_string
train
def read_binary_string(fname,fd,length) buff = read_fd fd, length @unique_table[buff] = true unless @unique_table.has_key?(buff) CFString.new(buff) end
ruby
{ "resource": "" }
q22201
CFPropertyList.Binary.read_binary_unicode_string
train
def read_binary_unicode_string(fname,fd,length) # The problem is: we get the length of the string IN CHARACTERS; # since a char in UTF-16 can be 16 or 32 bit long, we don't really know # how long the string is in bytes buff = fd.read(2*length) @unique_table[buff] = true unless @unique_tab...
ruby
{ "resource": "" }
q22202
CFPropertyList.Binary.read_binary_array
train
def read_binary_array(fname,fd,length) ary = [] # first: read object refs if(length != 0) buff = fd.read(length * @object_ref_size) objects = unpack_with_size(@object_ref_size, buff) #buff.unpack(@object_ref_size == 1 ? "C*" : "n*") # now: read objects 0.upto(length-1...
ruby
{ "resource": "" }
q22203
CFPropertyList.Binary.read_binary_dict
train
def read_binary_dict(fname,fd,length) dict = {} # first: read keys if(length != 0) then buff = fd.read(length * @object_ref_size) keys = unpack_with_size(@object_ref_size, buff) # second: read object refs buff = fd.read(length * @object_ref_size) objects = unp...
ruby
{ "resource": "" }
q22204
CFPropertyList.Binary.read_binary_object
train
def read_binary_object(fname,fd) # first: read the marker byte buff = fd.read(1) object_length = buff.unpack("C*") object_length = object_length[0] & 0xF buff = buff.unpack("H*") object_type = buff[0][0].chr if(object_type != "0" && object_length == 15) then object_l...
ruby
{ "resource": "" }
q22205
CFPropertyList.Binary.string_to_binary
train
def string_to_binary(val) val = val.to_s @unique_table[val] ||= begin if !Binary.ascii_string?(val) val = Binary.charset_convert(val,"UTF-8","UTF-16BE") bdata = Binary.type_bytes(0b0110, Binary.charset_strlen(val,"UTF-16BE")) val.force_encoding("ASCII-8BIT") if val.re...
ruby
{ "resource": "" }
q22206
CFPropertyList.Binary.int_to_binary
train
def int_to_binary(value) # Note: nbytes is actually an exponent. number of bytes = 2**nbytes. nbytes = 0 nbytes = 1 if value > 0xFF # 1 byte unsigned integer nbytes += 1 if value > 0xFFFF # 4 byte unsigned integer nbytes += 1 if value > 0xFFFFFFFF # 8 byte unsigned integer nbytes +...
ruby
{ "resource": "" }
q22207
CFPropertyList.Binary.num_to_binary
train
def num_to_binary(value) @object_table[@written_object_count] = if value.is_a?(CFInteger) int_to_binary(value.value) else real_to_binary(value.value) end @written_object_count += 1 @written_object_count - 1 end
ruby
{ "resource": "" }
q22208
CFPropertyList.Binary.array_to_binary
train
def array_to_binary(val) saved_object_count = @written_object_count @written_object_count += 1 #@object_refs += val.value.size values = val.value.map { |v| v.to_binary(self) } bdata = Binary.type_bytes(0b1010, val.value.size) << Binary.pack_int_array_with_size(object_ref_size(@obj...
ruby
{ "resource": "" }
q22209
CFPropertyList.Binary.dict_to_binary
train
def dict_to_binary(val) saved_object_count = @written_object_count @written_object_count += 1 #@object_refs += val.value.keys.size * 2 keys_and_values = val.value.keys.map { |k| CFString.new(k).to_binary(self) } keys_and_values.concat(val.value.values.map { |v| v.to_binary(self) }) ...
ruby
{ "resource": "" }
q22210
S3.Connection.request
train
def request(method, options) host = options.fetch(:host, S3.host) path = options.fetch(:path) body = options.fetch(:body, nil) params = options.fetch(:params, {}) headers = options.fetch(:headers, {}) # Must be done before adding params # Encodes all characters except forward-...
ruby
{ "resource": "" }
q22211
S3.Parser.parse_acl
train
def parse_acl(xml) grants = {} rexml_document(xml).elements.each("AccessControlPolicy/AccessControlList/Grant") do |grant| grants.merge!(extract_grantee(grant)) end grants end
ruby
{ "resource": "" }
q22212
S3.Object.temporary_url
train
def temporary_url(expires_at = Time.now + 3600) signature = Signature.generate_temporary_url_signature(:bucket => name, :resource => key, :expires_at => expires_at, ...
ruby
{ "resource": "" }
q22213
S3.Bucket.save
train
def save(options = {}) options = {:location => options} unless options.is_a?(Hash) create_bucket_configuration(options) true end
ruby
{ "resource": "" }
q22214
WebTranslateIt.String.translation_for
train
def translation_for(locale) success = true tries ||= 3 translation = self.translations.detect{ |t| t.locale == locale } return translation if translation return nil if self.new_record request = Net::HTTP::Get.new("/api/projects/#{Connection.api_key}/strings/#{self.id}/locales/#{local...
ruby
{ "resource": "" }
q22215
WebTranslateIt.TranslationFile.fetch
train
def fetch(http_connection, force = false) success = true tries ||= 3 display = [] display.push(self.file_path) display.push "#{StringUtil.checksumify(self.local_checksum.to_s)}..#{StringUtil.checksumify(self.remote_checksum.to_s)}" if !File.exist?(self.file_path) or force or self.rem...
ruby
{ "resource": "" }
q22216
WebTranslateIt.TranslationFile.upload
train
def upload(http_connection, merge=false, ignore_missing=false, label=nil, low_priority=false, minor_changes=false, force=false) success = true tries ||= 3 display = [] display.push(self.file_path) display.push "#{StringUtil.checksumify(self.local_checksum.to_s)}..#{StringUtil.checksumify(s...
ruby
{ "resource": "" }
q22217
WebTranslateIt.TranslationFile.create
train
def create(http_connection, low_priority=false) success = true tries ||= 3 display = [] display.push file_path display.push "#{StringUtil.checksumify(self.local_checksum.to_s)}..[ ]" if File.exists?(self.file_path) File.open(self.file_path) do |file| begin ...
ruby
{ "resource": "" }
q22218
WebTranslateIt.TranslationFile.delete
train
def delete(http_connection) success = true tries ||= 3 display = [] display.push file_path if File.exists?(self.file_path) File.open(self.file_path) do |file| begin request = Net::HTTP::Delete.new(api_url_for_delete) WebTranslateIt::Util.add_fields...
ruby
{ "resource": "" }
q22219
SendGrid.ClassMethods.sendgrid_enable
train
def sendgrid_enable(*options) self.default_sg_options = Array.new unless self.default_sg_options options.each { |option| self.default_sg_options << option if VALID_OPTIONS.include?(option) } end
ruby
{ "resource": "" }
q22220
ThreadSafe.AtomicReferenceCacheBackend.clear
train
def clear return self unless current_table = table current_table_size = current_table.size deleted_count = i = 0 while i < current_table_size if !(node = current_table.volatile_get(i)) i += 1 elsif (node_hash = node.hash) == MOVED current_table = node.key...
ruby
{ "resource": "" }
q22221
ThreadSafe.AtomicReferenceCacheBackend.initialize_table
train
def initialize_table until current_table ||= table if (size_ctrl = size_control) == NOW_RESIZING Thread.pass # lost initialization race; just spin else try_in_resize_lock(current_table, size_ctrl) do initial_size = size_ctrl > 0 ? size_ctrl : DEFAULT_CAPACITY ...
ruby
{ "resource": "" }
q22222
ThreadSafe.AtomicReferenceCacheBackend.check_for_resize
train
def check_for_resize while (current_table = table) && MAX_CAPACITY > (table_size = current_table.size) && NOW_RESIZING != (size_ctrl = size_control) && size_ctrl < @counter.sum try_in_resize_lock(current_table, size_ctrl) do self.table = rebuild(current_table) (table_size << 1) - (tabl...
ruby
{ "resource": "" }
q22223
ThreadSafe.AtomicReferenceCacheBackend.split_old_bin
train
def split_old_bin(table, new_table, i, node, node_hash, forwarder) table.try_lock_via_hash(i, node, node_hash) do split_bin(new_table, i, node, node_hash) table.volatile_set(i, forwarder) end end
ruby
{ "resource": "" }
q22224
GreenAndSecure.BlockList.run
train
def run GreenAndSecure::check_block_setup puts "The available chef servers are:" servers.each do |server| if server == current_server then puts "\t* #{server} [ Currently Selected ]" else puts "\t* #{server}" end end end
ruby
{ "resource": "" }
q22225
AlexaVerifier.Verifier.valid?
train
def valid?(request) begin valid!(request) rescue AlexaVerifier::BaseError => e puts e return false end true end
ruby
{ "resource": "" }
q22226
AlexaVerifier.Verifier.check_that_request_is_timely
train
def check_that_request_is_timely(raw_body) request_json = JSON.parse(raw_body) raise AlexaVerifier::InvalidRequestError, 'Timestamp field not present in request' if request_json.fetch('request', {}).fetch('timestamp', nil).nil? request_is_timely = (Time.parse(request_json['request']['timestamp'].to_...
ruby
{ "resource": "" }
q22227
AlexaVerifier.Verifier.check_that_request_is_valid
train
def check_that_request_is_valid(signature_certificate_url, request, raw_body) certificate, chain = AlexaVerifier::CertificateStore.fetch(signature_certificate_url) if @configuration.verify_certificate? || @configuration.verify_signature? begin AlexaVerifier::Verifier::CertificateVerifier.valid!(cer...
ruby
{ "resource": "" }
q22228
AlexaVerifier.Verifier.check_that_request_was_signed
train
def check_that_request_was_signed(certificate_public_key, request, raw_body) signed_by_certificate = certificate_public_key.verify( OpenSSL::Digest::SHA1.new, Base64.decode64(request.env['HTTP_SIGNATURE']), raw_body ) raise AlexaVerifier::InvalidRequestError, 'Signature does n...
ruby
{ "resource": "" }
q22229
TeamCityFormatter.Formatter.before_feature_element
train
def before_feature_element(cuke_feature_element) if cuke_feature_element.is_a?(Cucumber::Core::Ast::Scenario) before_scenario(cuke_feature_element) elsif cuke_feature_element.is_a?(Cucumber::Core::Ast::ScenarioOutline) before_scenario_outline(cuke_feature_element) else raise("u...
ruby
{ "resource": "" }
q22230
TeamCityFormatter.Formatter.after_feature_element
train
def after_feature_element(cuke_feature_element) if cuke_feature_element.is_a?(Cucumber::Formatter::LegacyApi::Ast::Scenario) after_scenario(cuke_feature_element) elsif cuke_feature_element.is_a?(Cucumber::Formatter::LegacyApi::Ast::ScenarioOutline) after_scenario_outline(cuke_feature_element...
ruby
{ "resource": "" }
q22231
TeamCityFormatter.Formatter.before_table_row
train
def before_table_row(cuke_table_row) if cuke_table_row.is_a?(Cucumber::Formatter::LegacyApi::ExampleTableRow) is_not_header_row = (@scenario_outline.example_column_names != cuke_table_row.values) if is_not_header_row example = @scenario_outline.examples.find { |example| example.column_va...
ruby
{ "resource": "" }
q22232
TeamCityFormatter.Formatter.after_table_row
train
def after_table_row(cuke_table_row) if cuke_table_row.is_a?(Cucumber::Formatter::LegacyApi::Ast::ExampleTableRow) is_not_header_row = (@scenario_outline.example_column_names != cuke_table_row.cells) if is_not_header_row # treat scenario-level exception as example exception # th...
ruby
{ "resource": "" }
q22233
TabsOnRails.Tabs.render
train
def render(&block) raise LocalJumpError, "no block given" unless block_given? options = @options.dup open_tabs_options = options.delete(:open_tabs) || {} close_tabs_options = options.delete(:close_tabs) || {} "".tap do |html| html << open_tabs(open_tabs_options).to_s ht...
ruby
{ "resource": "" }
q22234
ActiveStorage.Service::CloudinaryService.download
train
def download(key, &block) source = cloudinary_url_for_key(key) if block_given? instrument :streaming_download, key: key do stream_download(source, &block) end else instrument :download, key: key do Cloudinary::Downloader.download(source) end e...
ruby
{ "resource": "" }
q22235
ActiveStorage.Service::CloudinaryService.download_chunk
train
def download_chunk(key, range) instrument :download_chunk, key: key, range: range do source = cloudinary_url_for_key(key) download_range(source, range) end end
ruby
{ "resource": "" }
q22236
ActiveStorage.Service::CloudinaryService.url_for_direct_upload
train
def url_for_direct_upload(key, expires_in:, content_type:, content_length:, checksum:) instrument :url_for_direct_upload, key: key do options = { expires_in: expires_in, content_type: content_type, content_length: content_length, checksum: checksum, resour...
ruby
{ "resource": "" }
q22237
OptaSD.Core.parse_json
train
def parse_json(response) data = JSON.parse(response) fail OptaSD::Error.new(data), ErrorMessage.get_message(data['errorCode'].to_i) if data['errorCode'] data end
ruby
{ "resource": "" }
q22238
OptaSD.Core.parse_xml
train
def parse_xml(response) data = Nokogiri::XML(response) do |config| config.strict.noblanks end fail OptaSD::Error.new(xml_error_to_hast(data)), ErrorMessage.get_message(data.children.first.content.to_i) if data.css('errorCode').first.present? data end
ruby
{ "resource": "" }
q22239
Hermann.Producer.push
train
def push(value, opts={}) topic = opts[:topic] || @topic result = nil if value.kind_of? Array return value.map { |e| self.push(e, opts) } end if Hermann.jruby? result = @internal.push_single(value, topic, opts[:partition_key], nil) unless result.nil? @chi...
ruby
{ "resource": "" }
q22240
Hermann.Producer.tick_reactor
train
def tick_reactor(timeout=0) begin execute_tick(rounded_timeout(timeout)) rescue StandardError => ex @children.each do |child| # Skip over any children that should already be reaped for other # reasons next if (Hermann.jruby? ? child.fulfilled? : child.completed?...
ruby
{ "resource": "" }
q22241
Hermann.Producer.execute_tick
train
def execute_tick(timeout) if timeout == 0 @internal.tick(0) else (timeout * 2).times do # We're going to Thread#sleep in Ruby to avoid a # pthread_cond_timedwait(3) inside of librdkafka events = @internal.tick(0) # If we find events, break out early ...
ruby
{ "resource": "" }
q22242
ActiveStorage.Service::OpenStackService.change_content_type
train
def change_content_type(key, content_type) client.post_object(container, key, 'Content-Type' => content_type) true rescue Fog::OpenStack::Storage::NotFound false end
ruby
{ "resource": "" }
q22243
JMS.OracleAQConnectionFactory.create_connection
train
def create_connection(*args) # Since username and password are not assigned (see lib/jms/connection.rb:200) # and connection_factory.create_connection expects 2 arguments when username is not null ... if args.length == 2 @username = args[0] @password = args[1] end # Full Q...
ruby
{ "resource": "" }
q22244
JMS.SessionPool.session
train
def session(&block) s = nil begin s = @pool.checkout block.call(s) rescue javax.jms.JMSException => e s.close rescue nil @pool.remove(s) s = nil # Do not check back in since we have removed it raise e ensure @pool.checkin(s) if s end ...
ruby
{ "resource": "" }
q22245
JMS.SessionPool.consumer
train
def consumer(params, &block) session do |s| begin consumer = s.consumer(params) block.call(s, consumer) ensure consumer.close if consumer end end end
ruby
{ "resource": "" }
q22246
JMS.SessionPool.producer
train
def producer(params, &block) session do |s| begin producer = s.producer(params) block.call(s, producer) ensure producer.close if producer end end end
ruby
{ "resource": "" }
q22247
JMS.Connection.fetch_dependencies
train
def fetch_dependencies(jar_list) jar_list.each do |jar| logger.debug "Loading Jar File:#{jar}" begin require jar rescue Exception => exc logger.error "Failed to Load Jar File:#{jar}", exc end end if jar_list require 'jms/mq_workaround' require...
ruby
{ "resource": "" }
q22248
JMS.Connection.session
train
def session(params={}, &block) raise(ArgumentError, 'Missing mandatory Block when calling JMS::Connection#session') unless block session = self.create_session(params) begin block.call(session) ensure session.close end end
ruby
{ "resource": "" }
q22249
JMS.Connection.create_session
train
def create_session(params={}) transacted = params[:transacted] || false options = params[:options] || JMS::Session::AUTO_ACKNOWLEDGE @jms_connection.create_session(transacted, options) end
ruby
{ "resource": "" }
q22250
JMS.Connection.on_message
train
def on_message(params, &block) raise 'JMS::Connection must be connected prior to calling JMS::Connection::on_message' unless @sessions && @consumers consumer_count = params[:session_count] || 1 consumer_count.times do session = self.create_session(params) consumer = session.consumer(...
ruby
{ "resource": "" }
q22251
JMS.MessageListenerImpl.statistics
train
def statistics raise(ArgumentError, 'First call MessageConsumer::on_message with statistics: true before calling MessageConsumer::statistics()') unless @message_count duration = (@last_time || Time.now) - @start_time { messages: @message_count, duration: duration,...
ruby
{ "resource": "" }
q22252
CFMicro.McfCommand.override
train
def override(config, option, escape=false, &blk) # override if given on the command line if opt = input[option] opt = CFMicro.escape_path(opt) if escape config[option] = opt end config[option] = yield unless config[option] end
ruby
{ "resource": "" }
q22253
CFManifests.Resolver.resolve_lexically
train
def resolve_lexically(resolver, val, ctx) case val when Hash new = {} val.each do |k, v| new[k] = resolve_lexically(resolver, v, [val] + ctx) end new when Array val.collect do |v| resolve_lexically(resolver, v, ctx) end when S...
ruby
{ "resource": "" }
q22254
CFManifests.Resolver.resolve_symbol
train
def resolve_symbol(resolver, sym, ctx) if found = find_symbol(sym.to_sym, ctx) resolve_lexically(resolver, found, ctx) found elsif dynamic = resolver.resolve_symbol(sym) dynamic else fail("Unknown symbol in manifest: #{sym}") end end
ruby
{ "resource": "" }
q22255
CFManifests.Resolver.find_symbol
train
def find_symbol(sym, ctx) ctx.each do |h| if val = resolve_in(h, sym) return val end end nil end
ruby
{ "resource": "" }
q22256
CFManifests.Resolver.find_in_hash
train
def find_in_hash(hash, where) what = hash where.each do |x| return nil unless what.is_a?(Hash) what = what[x] end what end
ruby
{ "resource": "" }
q22257
CFManifests.Builder.build
train
def build(file) manifest = YAML.load_file file raise CFManifests::InvalidManifest.new(file) unless manifest Array(manifest["inherit"]).each do |path| manifest = merge_parent(path, manifest) end manifest.delete("inherit") manifest end
ruby
{ "resource": "" }
q22258
CFManifests.Builder.merge_manifest
train
def merge_manifest(parent, child) merge = proc do |_, old, new| if new.is_a?(Hash) && old.is_a?(Hash) old.merge(new, &merge) else new end end parent.merge(child, &merge) end
ruby
{ "resource": "" }
q22259
SimCtl.List.where
train
def where(filter) return self if filter.nil? select do |item| matches = true filter.each do |key, value| matches &= case value when Regexp item.send(key) =~ value else item.send(key) == value ...
ruby
{ "resource": "" }
q22260
SimCtl.Device.reload
train
def reload device = SimCtl.device(udid: udid) device.instance_variables.each do |ivar| instance_variable_set(ivar, device.instance_variable_get(ivar)) end end
ruby
{ "resource": "" }
q22261
SimCtl.Device.wait
train
def wait(timeout = SimCtl.default_timeout) Timeout.timeout(timeout) do loop do break if yield SimCtl.device(udid: udid) end end reload end
ruby
{ "resource": "" }
q22262
SimCtl.DeviceSettings.disable_keyboard_helpers
train
def disable_keyboard_helpers edit_plist(path.preferences_plist) do |plist| %w[ KeyboardAllowPaddle KeyboardAssistant KeyboardAutocapitalization KeyboardAutocorrection KeyboardCapsLock KeyboardCheckSpelling KeyboardPeriodShortcut ...
ruby
{ "resource": "" }
q22263
SimCtl.DeviceSettings.set_language
train
def set_language(language) edit_plist(path.global_preferences_plist) do |plist| key = 'AppleLanguages' plist[key] = [] unless plist.key?(key) plist[key].unshift(language).uniq! end end
ruby
{ "resource": "" }
q22264
DICOM.Parent.count_all
train
def count_all # Iterate over all elements, and repeat recursively for all elements which themselves contain children. total_count = count @tags.each_value do |value| total_count += value.count_all if value.children? end return total_count end
ruby
{ "resource": "" }
q22265
DICOM.Parent.delete
train
def delete(tag_or_index, options={}) check_key(tag_or_index, :delete) # We need to delete the specified child element's parent reference in addition to removing it from the tag Hash. element = self[tag_or_index] if element element.parent = nil unless options[:no_follow] @tags.del...
ruby
{ "resource": "" }
q22266
DICOM.Parent.delete_group
train
def delete_group(group_string) group_elements = group(group_string) group_elements.each do |element| delete(element.tag) end end
ruby
{ "resource": "" }
q22267
DICOM.Parent.encode_children
train
def encode_children(old_endian) # Cycle through all levels of children recursively: children.each do |element| if element.children? element.encode_children(old_endian) elsif element.is_a?(Element) encode_child(element, old_endian) end end end
ruby
{ "resource": "" }
q22268
DICOM.Parent.group
train
def group(group_string) raise ArgumentError, "Expected String, got #{group_string.class}." unless group_string.is_a?(String) found = Array.new children.each do |child| found << child if child.tag.group == group_string.upcase end return found end
ruby
{ "resource": "" }
q22269
DICOM.Parent.handle_print
train
def handle_print(index, max_digits, max_name, max_length, max_generations, visualization, options={}) # FIXME: This method is somewhat complex, and some simplification, if possible, wouldn't hurt. elements = Array.new s = " " hook_symbol = "|_" last_item_symbol = " " nonlast_item_sy...
ruby
{ "resource": "" }
q22270
DICOM.Parent.max_lengths
train
def max_lengths max_name = 0 max_length = 0 max_generations = 0 children.each do |element| if element.children? max_nc, max_lc, max_gc = element.max_lengths max_name = max_nc if max_nc > max_name max_length = max_lc if max_lc > max_length max_gener...
ruby
{ "resource": "" }
q22271
DICOM.Parent.method_missing
train
def method_missing(sym, *args, &block) s = sym.to_s action = s[-1] # Try to match the method against a tag from the dictionary: tag = LIBRARY.as_tag(s) || LIBRARY.as_tag(s[0..-2]) if tag if action == '?' # Query: return self.exists?(tag) elsif action == ...
ruby
{ "resource": "" }
q22272
DICOM.Parent.print
train
def print(options={}) # FIXME: Perhaps a :children => false option would be a good idea (to avoid lengthy printouts in cases where this would be desirable)? # FIXME: Speed. The new print algorithm may seem to be slower than the old one (observed on complex, hiearchical DICOM files). Perhaps it can be optimi...
ruby
{ "resource": "" }
q22273
DICOM.Parent.to_hash
train
def to_hash as_hash = Hash.new unless children? if self.is_a?(DObject) as_hash = {} else as_hash[(self.tag.private?) ? self.tag : self.send(DICOM.key_representation)] = nil end else children.each do |child| if child.tag.private? ...
ruby
{ "resource": "" }
q22274
DICOM.Parent.value
train
def value(tag) check_key(tag, :value) if exists?(tag) if self[tag].is_parent? raise ArgumentError, "Illegal parameter '#{tag}'. Parent elements, like the referenced '#{@tags[tag].class}', have no value. Only Element tags are valid." else return self[tag].value end...
ruby
{ "resource": "" }
q22275
DICOM.Parent.check_key
train
def check_key(tag_or_index, method) if tag_or_index.is_a?(String) logger.warn("Parent##{method} called with an invalid tag argument: #{tag_or_index}") unless tag_or_index.tag? elsif tag_or_index.is_a?(Integer) logger.warn("Parent##{method} called with a negative Integer argument: #{tag_or_in...
ruby
{ "resource": "" }
q22276
DICOM.Link.await_release
train
def await_release segments = receive_single_transmission info = segments.first if info[:pdu] != PDU_RELEASE_REQUEST # For some reason we didn't get our expected release request. Determine why: if info[:valid] logger.error("Unexpected message type received (PDU: #{info[:pdu]})...
ruby
{ "resource": "" }
q22277
DICOM.Link.build_association_request
train
def build_association_request(presentation_contexts, user_info) # Big endian encoding: @outgoing.endian = @net_endian # Clear the outgoing binary string: @outgoing.reset # Note: The order of which these components are built is not arbitrary. # (The first three are built 'in order of ...
ruby
{ "resource": "" }
q22278
DICOM.Link.build_command_fragment
train
def build_command_fragment(pdu, context, flags, command_elements) # Little endian encoding: @outgoing.endian = @data_endian # Clear the outgoing binary string: @outgoing.reset # Build the last part first, the Command items: command_elements.each do |element| # Tag (4 bytes) ...
ruby
{ "resource": "" }
q22279
DICOM.Link.build_data_fragment
train
def build_data_fragment(data_elements, presentation_context_id) # Set the transfer syntax to be used for encoding the data fragment: set_transfer_syntax(@presentation_contexts[presentation_context_id]) # Endianness of data fragment: @outgoing.endian = @data_endian # Clear the outgoing bina...
ruby
{ "resource": "" }
q22280
DICOM.Link.build_storage_fragment
train
def build_storage_fragment(pdu, context, flags, body) # Big endian encoding: @outgoing.endian = @net_endian # Clear the outgoing binary string: @outgoing.reset # Build in reverse, putting elements in front of the binary string: # Insert the data (body): @outgoing.add_last(body)...
ruby
{ "resource": "" }
q22281
DICOM.Link.forward_to_interpret
train
def forward_to_interpret(message, pdu, file=nil) case pdu when PDU_ASSOCIATION_REQUEST info = interpret_association_request(message) when PDU_ASSOCIATION_ACCEPT info = interpret_association_accept(message) when PDU_ASSOCIATION_REJECT info = interpret_associati...
ruby
{ "resource": "" }
q22282
DICOM.Link.handle_incoming_data
train
def handle_incoming_data(path) # Wait for incoming data: segments = receive_multiple_transmissions(file=true) # Reset command results arrays: @command_results = Array.new @data_results = Array.new file_transfer_syntaxes = Array.new files = Array.new single_file_data = Arr...
ruby
{ "resource": "" }
q22283
DICOM.Link.handle_response
train
def handle_response # Need to construct the command elements array: command_elements = Array.new # SOP Class UID: command_elements << ["0000,0002", "UI", @command_request["0000,0002"]] # Command Field: command_elements << ["0000,0100", "US", command_field_response(@command_request["0...
ruby
{ "resource": "" }
q22284
DICOM.Link.interpret
train
def interpret(message, file=nil) if @first_part message = @first_part + message @first_part = nil end segments = Array.new # If the message is at least 8 bytes we can start decoding it: if message.length > 8 # Create a new Stream instance to handle this response. ...
ruby
{ "resource": "" }
q22285
DICOM.Link.interpret_abort
train
def interpret_abort(message) info = Hash.new msg = Stream.new(message, @net_endian) # Reserved (2 bytes) reserved_bytes = msg.skip(2) # Source (1 byte) info[:source] = msg.decode(1, "HEX") # Reason/Diag. (1 byte) info[:reason] = msg.decode(1, "HEX") # Analyse the re...
ruby
{ "resource": "" }
q22286
DICOM.Link.interpret_association_reject
train
def interpret_association_reject(message) info = Hash.new msg = Stream.new(message, @net_endian) # Reserved (1 byte) msg.skip(1) # Result (1 byte) info[:result] = msg.decode(1, "BY") # 1 for permanent and 2 for transient rejection # Source (1 byte) info[:source] = msg.dec...
ruby
{ "resource": "" }
q22287
DICOM.Link.interpret_release_request
train
def interpret_release_request(message) info = Hash.new msg = Stream.new(message, @net_endian) # Reserved (4 bytes) reserved_bytes = msg.decode(4, "HEX") handle_release info[:valid] = true return info end
ruby
{ "resource": "" }
q22288
DICOM.Link.interpret_release_response
train
def interpret_release_response(message) info = Hash.new msg = Stream.new(message, @net_endian) # Reserved (4 bytes) reserved_bytes = msg.decode(4, "HEX") stop_receiving info[:valid] = true return info end
ruby
{ "resource": "" }
q22289
DICOM.Link.receive_multiple_transmissions
train
def receive_multiple_transmissions(file=nil) # FIXME: The code which waits for incoming network packets seems to be very CPU intensive. # Perhaps there is a more elegant way to wait for incoming messages? # @listen = true segments = Array.new while @listen # Receive data and ...
ruby
{ "resource": "" }
q22290
DICOM.Link.receive_single_transmission
train
def receive_single_transmission min_length = 8 data = receive_transmission(min_length) segments = interpret(data) segments << {:valid => false} unless segments.length > 0 return segments end
ruby
{ "resource": "" }
q22291
DICOM.Link.process_reason
train
def process_reason(reason) case reason when "00" logger.error("Reason specified for abort: Reason not specified") when "01" logger.error("Reason specified for abort: Unrecognized PDU") when "02" logger.error("Reason specified for abort: Unexpected PDU") ...
ruby
{ "resource": "" }
q22292
DICOM.Link.process_result
train
def process_result(result) unless result == 0 # Analyse the result and report what is wrong: case result when 1 logger.warn("DICOM Request was rejected by the host, reason: 'User-rejection'") when 2 logger.warn("DICOM Request was rejected by the host, re...
ruby
{ "resource": "" }
q22293
DICOM.Link.receive_transmission
train
def receive_transmission(min_length=0) data = receive_transmission_data # Check the nature of the received data variable: if data # Sometimes the incoming transmission may be broken up into smaller pieces: # Unless a short answer is expected, we will continue to listen if the first ans...
ruby
{ "resource": "" }
q22294
DICOM.Link.receive_transmission_data
train
def receive_transmission_data data = false response = IO.select([@session], nil, nil, @timeout) if response.nil? logger.error("No answer was received within the specified timeout period. Aborting.") stop_receiving else data = @session.recv(@max_receive_size) end ...
ruby
{ "resource": "" }
q22295
DICOM.Link.set_transfer_syntax
train
def set_transfer_syntax(syntax) @transfer_syntax = syntax # Query the library with our particular transfer syntax string: ts = LIBRARY.uid(@transfer_syntax) @explicit = ts ? ts.explicit? : true @data_endian = ts ? ts.big_endian? : false logger.warn("Invalid/unknown transfer syntax en...
ruby
{ "resource": "" }
q22296
DICOM.Item.bin=
train
def bin=(new_bin) raise ArgumentError, "Invalid parameter type. String was expected, got #{new_bin.class}." unless new_bin.is_a?(String) # Add an empty byte at the end if the length of the binary is odd: if new_bin.length.odd? @bin = new_bin + "\x00" else @bin = new_bin end...
ruby
{ "resource": "" }
q22297
DICOM.ImageProcessor.decompress
train
def decompress(blobs) raise ArgumentError, "Expected Array or String, got #{blobs.class}." unless [String, Array].include?(blobs.class) blobs = [blobs] unless blobs.is_a?(Array) begin return image_module.decompress(blobs) rescue return false end end
ruby
{ "resource": "" }
q22298
DICOM.ImageProcessor.import_pixels
train
def import_pixels(blob, columns, rows, depth, photometry) raise ArgumentError, "Expected String, got #{blob.class}." unless blob.is_a?(String) image_module.import_pixels(blob, columns, rows, depth, photometry) end
ruby
{ "resource": "" }
q22299
Calabash.Location.coordinates_for_place
train
def coordinates_for_place(place_name) result = Geocoder.search(place_name) if result.empty? raise "No result found for '#{place}'" end {latitude: result.first.latitude, longitude: result.first.longitude} end
ruby
{ "resource": "" }