_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q22300
DICOM.Anonymizer.anonymize
train
def anonymize(dicom) dicom = Array[dicom] unless dicom.respond_to?(:to_ary) if @tags.length > 0 prepare_anonymization dicom.each do |dcm| anonymize_dcm(dcm.to_dcm) end else logger.warn("No tags have been selected for anonymization. Aborting anonymization.") end # Save the audit trail (if used): @audit_trail.write(@audit_trail_file) if @audit_trail logger.info("Anonymization complete.") dicom end
ruby
{ "resource": "" }
q22301
DICOM.Anonymizer.delete_tag
train
def delete_tag(tag) raise ArgumentError, "Expected String, got #{tag.class}." unless tag.is_a?(String) raise ArgumentError, "Expected a valid tag of format 'GGGG,EEEE', got #{tag}." unless tag.tag? @delete[tag] = true end
ruby
{ "resource": "" }
q22302
DICOM.Anonymizer.set_tag
train
def set_tag(tag, options={}) raise ArgumentError, "Expected String, got #{tag.class}." unless tag.is_a?(String) raise ArgumentError, "Expected a valid tag of format 'GGGG,EEEE', got #{tag}." unless tag.tag? pos = @tags.index(tag) if pos # Update existing values: @values[pos] = options[:value] if options[:value] @enumerations[pos] = options[:enum] if options[:enum] != nil else # Add new elements: @tags << tag @values << (options[:value] ? options[:value] : default_value(tag)) @enumerations << (options[:enum] ? options[:enum] : false) end end
ruby
{ "resource": "" }
q22303
DICOM.Anonymizer.value
train
def value(tag) raise ArgumentError, "Expected String, got #{tag.class}." unless tag.is_a?(String) raise ArgumentError, "Expected a valid tag of format 'GGGG,EEEE', got #{tag}." unless tag.tag? pos = @tags.index(tag) if pos return @values[pos] else logger.warn("The specified tag (#{tag}) was not found in the list of tags to be anonymized.") return nil end end
ruby
{ "resource": "" }
q22304
DICOM.Anonymizer.anonymize_dcm
train
def anonymize_dcm(dcm) # Extract the data element parents to investigate: parents = element_parents(dcm) parents.each do |parent| # Anonymize the desired tags: @tags.each_index do |j| if parent.exists?(@tags[j]) element = parent[@tags[j]] if element.is_a?(Element) if @blank value = '' elsif @enumeration old_value = element.value # Only launch enumeration logic if there is an actual value to the data element: if old_value value = enumerated_value(old_value, j) else value = '' end else # Use the value that has been set for this tag: value = @values[j] end element.value = value end end end # Delete elements marked for deletion: @delete.each_key do |tag| parent.delete(tag) if parent.exists?(tag) end end # General DICOM object manipulation: # Add a Patient Identity Removed attribute (as per # DICOM PS 3.15, Annex E, E.1.1 De-Identifier, point 6): dcm.add(Element.new('0012,0062', 'YES')) # Add a De-Identification Method Code Sequence Item: dcm.add(Sequence.new('0012,0064')) unless dcm.exists?('0012,0064') i = dcm['0012,0064'].add_item i.add(Element.new('0012,0063', 'De-identified by the ruby-dicom Anonymizer')) # FIXME: At some point we should add a set of de-indentification method codes, as per # DICOM PS 3.16 CID 7050 which corresponds to the settings chosen for the anonymizer. # Delete the old File Meta Information group (as per # DICOM PS 3.15, Annex E, E.1.1 De-Identifier, point 7): dcm.delete_group('0002') # Handle UIDs if requested: replace_uids(parents) if @uid # Delete private tags if indicated: dcm.delete_private if @delete_private end
ruby
{ "resource": "" }
q22305
DICOM.Anonymizer.anonymize_file
train
def anonymize_file(file) # Temporarily adjust the ruby-dicom log threshold (to suppress messages from the DObject class): @original_level = logger.level logger.level = @logger_level dcm = DObject.read(file) logger.level = @original_level anonymize_dcm(dcm) dcm end
ruby
{ "resource": "" }
q22306
DICOM.Anonymizer.default_value
train
def default_value(tag) name, vr = LIBRARY.name_and_vr(tag) conversion = VALUE_CONVERSION[vr] case conversion when :to_i then return 0 when :to_f then return 0.0 else # Assume type is string and return an empty string: return '' end end
ruby
{ "resource": "" }
q22307
DICOM.Anonymizer.destination
train
def destination(dcm) # Separate the path from the source file string: file_start = dcm.source.rindex(File.basename(dcm.source)) if file_start == 0 source_dir = "." else source_dir = dcm.source[0..(file_start-1)] end source_folders = source_dir.split(File::SEPARATOR) target_folders = @write_path.split(File::SEPARATOR) # If the first element is the current dir symbol, get rid of it: source_folders.delete('.') # Check for equalness of folder names in a range limited by the shortest array: common_length = [source_folders.length, target_folders.length].min uncommon_index = nil common_length.times do |i| if target_folders[i] != source_folders[i] uncommon_index = i break end end # Create the output path by joining the two paths together using the determined index: append_path = uncommon_index ? source_folders[uncommon_index..-1] : nil [target_folders, append_path].compact.join(File::SEPARATOR) end
ruby
{ "resource": "" }
q22308
DICOM.Anonymizer.enumerated_value
train
def enumerated_value(original, j) # Is enumeration requested for this tag? if @enumerations[j] if @audit_trail # Check if the UID has been encountered already: replacement = @audit_trail.replacement(@tags[j], at_value(original)) unless replacement # This original value has not been encountered yet. Determine the index to use. index = @audit_trail.records(@tags[j]).length + 1 # Create the replacement value: if @values[j].is_a?(String) replacement = @values[j] + index.to_s else replacement = @values[j] + index end # Add this tag record to the audit trail: @audit_trail.add_record(@tags[j], at_value(original), replacement) end else # Retrieve earlier used anonymization values: previous_old = @enum_old_hash[@tags[j]] previous_new = @enum_new_hash[@tags[j]] p_index = previous_old.length if previous_old.index(original) == nil # Current value has not been encountered before: replacement = @values[j]+(p_index + 1).to_s # Store value in array (and hash): previous_old << original previous_new << replacement @enum_old_hash[@tags[j]] = previous_old @enum_new_hash[@tags[j]] = previous_new else # Current value has been observed before: replacement = previous_new[previous_old.index(original)] end end else replacement = @values[j] end return replacement end
ruby
{ "resource": "" }
q22309
DICOM.Anonymizer.replace_uids
train
def replace_uids(parents) parents.each do |parent| parent.each_element do |element| if element.vr == ('UI') and !@static_uids[element.tag] original = element.value if original && original.length > 0 # We have a UID value, go ahead and replace it: if @audit_trail # Check if the UID has been encountered already: replacement = @audit_trail.replacement('uids', original) unless replacement # The UID has not been stored previously. Generate a new one: replacement = DICOM.generate_uid(@uid_root, prefix(element.tag)) # Add this tag record to the audit trail: @audit_trail.add_record('uids', original, replacement) end # Replace the UID in the DICOM object: element.value = replacement else # We don't care about preserving UID relations. Just insert a custom UID: element.value = DICOM.generate_uid(@uid_root, prefix(element.tag)) end end end end end end
ruby
{ "resource": "" }
q22310
DICOM.Anonymizer.set_defaults
train
def set_defaults # Some UIDs should not be remapped even if uid anonymization has been requested: @static_uids = { # Private related: '0002,0100' => true, '0004,1432' => true, # Coding scheme related: '0008,010C' => true, '0008,010D' => true, # Transfer syntax related: '0002,0010' => true, '0400,0010' => true, '0400,0510' => true, '0004,1512' => true, # SOP class related: '0000,0002' => true, '0000,0003' => true, '0002,0002' => true, '0004,1510' => true, '0004,151A' => true, '0008,0016' => true, '0008,001A' => true, '0008,001B' => true, '0008,0062' => true, '0008,1150' => true, '0008,115A' => true } # Sets up default tags that will be anonymized, along with default replacement values and enumeration settings. # This data is stored in 3 separate instance arrays for tags, values and enumeration. data = [ ['0008,0012', '20000101', false], # Instance Creation Date ['0008,0013', '000000.00', false], # Instance Creation Time ['0008,0020', '20000101', false], # Study Date ['0008,0021', '20000101', false], # Series Date ['0008,0022', '20000101', false], # Acquisition Date ['0008,0023', '20000101', false], # Image Date ['0008,0030', '000000.00', false], # Study Time ['0008,0031', '000000.00', false], # Series Time ['0008,0032', '000000.00', false], # Acquisition Time ['0008,0033', '000000.00', false], # Image Time ['0008,0050', '', true], # Accession Number ['0008,0080', 'Institution', true], # Institution name ['0008,0081', 'Address', true], # Institution Address ['0008,0090', 'Physician', true], # Referring Physician's name ['0008,1010', 'Station', true], # Station name ['0008,1040', 'Department', true], # Institutional Department name ['0008,1070', 'Operator', true], # Operator's Name ['0010,0010', 'Patient', true], # Patient's name ['0010,0020', 'ID', true], # Patient's ID ['0010,0030', '20000101', false], # Patient's Birth Date ['0010,0040', 'O', false], # Patient's Sex ['0010,1010', '', false], # Patient's Age ['0020,4000', '', false], # Image Comments ].transpose @tags = data[0] @values = data[1] @enumerations = data[2] # Tags to be deleted completely during anonymization: @delete = Hash.new end
ruby
{ "resource": "" }
q22311
DICOM.Anonymizer.write
train
def write(dcm) if @write_path # The DICOM object is to be written to a separate directory. If the # original and the new directories have a common root, this is taken into # consideration when determining the object's write path: path = destination(dcm) if @random_file_name file_name = "#{SecureRandom.hex(16)}.dcm" else file_name = File.basename(dcm.source) end dcm.write(File.join(path, file_name)) else # The original DICOM file is overwritten with the anonymized DICOM object: dcm.write(dcm.source) end end
ruby
{ "resource": "" }
q22312
DICOM.Element.value=
train
def value=(new_value) if VALUE_CONVERSION[@vr] == :to_s # Unless this is actually the Character Set data element, # get the character set (note that it may not be available): character_set = (@tag != '0008,0005' && top_parent.is_a?(DObject)) ? top_parent.value('0008,0005') : nil # Convert to [DObject encoding] from [input string encoding]: # In most cases the DObject encoding is IS0-8859-1 (ISO_IR 100), but if # it is not specified in the DICOM object, or if the specified string # is not recognized, ASCII-8BIT is assumed. @value = new_value.to_s.encode(ENCODING_NAME[character_set], new_value.to_s.encoding.name) @bin = encode(@value) else # We may have an array (of numbers) which needs to be passed directly to # the encode method instead of being forced into a numerical: if new_value.is_a?(Array) @value = new_value @bin = encode(@value) else @value = new_value.send(VALUE_CONVERSION[@vr]) @bin = encode(@value) end end @length = @bin.length end
ruby
{ "resource": "" }
q22313
Calabash.ConsoleHelpers.console_attach
train
def console_attach(uia_strategy=nil) Calabash::Application.default = Calabash::IOS::Application.default_from_environment identifier = Calabash::IOS::Device.default_identifier_for_application(Calabash::Application.default) server = Calabash::IOS::Server.default device = Calabash::IOS::Device.new(identifier, server) Calabash::Device.default = device begin Calabash::Internal.with_current_target(required_os: :ios) {|target| target.ensure_test_server_ready({:timeout => 4})} rescue RuntimeError => e if e.to_s == 'Calabash server did not respond' raise RuntimeError, 'You can only attach to a running Calabash iOS App' else raise e end end run_loop_device = device.send(:run_loop_device) result = Calabash::Internal.with_current_target(required_os: :ios) {|target| target.send(:attach_to_run_loop, run_loop_device, uia_strategy)} result[:application] = Calabash::Application.default result end
ruby
{ "resource": "" }
q22314
Calabash.Device.pan_between
train
def pan_between(query_from, query_to, options={}) ensure_query_class_or_nil(query_from) ensure_query_class_or_nil(query_to) gesture_options = options.dup gesture_options[:timeout] ||= Calabash::Gestures::DEFAULT_GESTURE_WAIT_TIMEOUT _pan_between(query_from, query_to, gesture_options) end
ruby
{ "resource": "" }
q22315
Calabash.Device.flick_between
train
def flick_between(query_from, query_to, options={}) ensure_query_class_or_nil(query_from) ensure_query_class_or_nil(query_to) gesture_options = options.dup gesture_options[:timeout] ||= Calabash::Gestures::DEFAULT_GESTURE_WAIT_TIMEOUT _flick_between(query_from, query_to, gesture_options) end
ruby
{ "resource": "" }
q22316
Calabash.Web.evaluate_javascript_in
train
def evaluate_javascript_in(query, javascript) wait_for_view(query, timeout: Calabash::Gestures::DEFAULT_GESTURE_WAIT_TIMEOUT) _evaluate_javascript_in(query, javascript) end
ruby
{ "resource": "" }
q22317
Calabash.Text.wait_for_keyboard
train
def wait_for_keyboard(timeout: nil) keyboard_timeout = keyboard_wait_timeout(timeout) message = "Timed out after #{keyboard_timeout} seconds waiting for the keyboard to appear" wait_for(message, timeout: keyboard_timeout) do keyboard_visible? end end
ruby
{ "resource": "" }
q22318
Calabash.Text.wait_for_no_keyboard
train
def wait_for_no_keyboard(timeout: nil) keyboard_timeout = keyboard_wait_timeout(timeout) message = "Timed out after #{keyboard_timeout} seconds waiting for the keyboard to disappear" wait_for(message, timeout: keyboard_timeout) do !keyboard_visible? end end
ruby
{ "resource": "" }
q22319
DICOM.DClient.find_series
train
def find_series(query_params={}) # Study Root Query/Retrieve Information Model - FIND: set_default_presentation_context("1.2.840.10008.5.1.4.1.2.2.1") # Every query attribute with a value != nil (required) will be sent in the dicom query. # The query parameters with nil-value (optional) are left out unless specified. default_query_params = { "0008,0052" => "SERIES", # Query/Retrieve Level: "SERIES" "0008,0060" => "", # Modality "0020,000E" => "", # Series Instance UID "0020,0011" => "" # Series Number } # Raising an error if a non-tag query attribute is used: query_params.keys.each do |tag| raise ArgumentError, "The supplied tag (#{tag}) is not valid. It must be a string of the form 'GGGG,EEEE'." unless tag.is_a?(String) && tag.tag? end # Set up the query parameters and carry out the C-FIND: set_data_elements(default_query_params.merge(query_params)) perform_find return @data_results end
ruby
{ "resource": "" }
q22320
DICOM.DClient.move_image
train
def move_image(destination, options={}) # Study Root Query/Retrieve Information Model - MOVE: set_default_presentation_context("1.2.840.10008.5.1.4.1.2.2.2") # Transfer the current options to the data_elements hash: set_command_fragment_move(destination) # Prepare data elements for this operation: set_data_fragment_move_image set_data_options(options) perform_move end
ruby
{ "resource": "" }
q22321
DICOM.DClient.move_study
train
def move_study(destination, options={}) # Study Root Query/Retrieve Information Model - MOVE: set_default_presentation_context("1.2.840.10008.5.1.4.1.2.2.2") # Transfer the current options to the data_elements hash: set_command_fragment_move(destination) # Prepare data elements for this operation: set_data_fragment_move_study set_data_options(options) perform_move end
ruby
{ "resource": "" }
q22322
DICOM.DClient.available_transfer_syntaxes
train
def available_transfer_syntaxes(transfer_syntax) case transfer_syntax when IMPLICIT_LITTLE_ENDIAN return [IMPLICIT_LITTLE_ENDIAN, EXPLICIT_LITTLE_ENDIAN] when EXPLICIT_LITTLE_ENDIAN return [EXPLICIT_LITTLE_ENDIAN, IMPLICIT_LITTLE_ENDIAN] when EXPLICIT_BIG_ENDIAN return [EXPLICIT_BIG_ENDIAN, IMPLICIT_LITTLE_ENDIAN] else # Compression: return [transfer_syntax] end end
ruby
{ "resource": "" }
q22323
DICOM.DClient.establish_association
train
def establish_association # Reset some variables: @association = false @request_approved = false # Initiate the association: @link.build_association_request(@presentation_contexts, @user_information) @link.start_session(@host_ip, @port) @link.transmit info = @link.receive_multiple_transmissions.first # Interpret the results: if info && info[:valid] if info[:pdu] == PDU_ASSOCIATION_ACCEPT # Values of importance are extracted and put into instance variables: @association = true @max_pdu_length = info[:max_pdu_length] logger.info("Association successfully negotiated with host #{@host_ae} (#{@host_ip}).") # Check if all our presentation contexts was accepted by the host: process_presentation_context_response(info[:pc]) else logger.error("Association was denied from host #{@host_ae} (#{@host_ip})!") end end end
ruby
{ "resource": "" }
q22324
DICOM.DClient.establish_release
train
def establish_release @release = false if @abort @link.stop_session logger.info("Association has been closed. (#{@host_ae}, #{@host_ip})") else unless @link.session.closed? @link.build_release_request @link.transmit info = @link.receive_single_transmission.first @link.stop_session if info[:pdu] == PDU_RELEASE_RESPONSE logger.info("Association released properly from host #{@host_ae}.") else logger.error("Association released from host #{@host_ae}, but a release response was not registered.") end else logger.error("Connection was closed by the host (for some unknown reason) before the association could be released properly.") end end @abort = false end
ruby
{ "resource": "" }
q22325
DICOM.DClient.load_files
train
def load_files(files_or_objects) files_or_objects = [files_or_objects] unless files_or_objects.is_a?(Array) status = true message = "" objects = Array.new abstracts = Array.new id = 1 @presentation_contexts = Hash.new files_or_objects.each do |file_or_object| if file_or_object.is_a?(String) # Temporarily increase the log threshold to suppress messages from the DObject class: client_level = logger.level logger.level = Logger::FATAL dcm = DObject.read(file_or_object) # Reset the logg threshold: logger.level = client_level if dcm.read_success # Load the DICOM object: objects << dcm else status = false message = "Failed to read a DObject from this file: #{file_or_object}" end elsif file_or_object.is_a?(DObject) # Load the DICOM object and its abstract syntax: abstracts << file_or_object.value("0008,0016") objects << file_or_object else status = false message = "Array contains invalid object: #{file_or_object.class}." end end # Extract available transfer syntaxes for the various sop classes found amongst these objects syntaxes = Hash.new objects.each do |dcm| sop_class = dcm.value("0008,0016") if sop_class transfer_syntaxes = available_transfer_syntaxes(dcm.transfer_syntax) if syntaxes[sop_class] syntaxes[sop_class] << transfer_syntaxes else syntaxes[sop_class] = transfer_syntaxes end else status = false message = "Missing SOP Class UID. Unable to transmit DICOM object" end # Extract the unique variations of SOP Class and syntaxes and construct the presentation context hash: syntaxes.each_pair do |sop_class, ts| selected_transfer_syntaxes = ts.flatten.uniq @presentation_contexts[sop_class] = Hash.new selected_transfer_syntaxes.each do |syntax| @presentation_contexts[sop_class][id] = {:transfer_syntaxes => [syntax]} id += 2 end end end return objects, status, message end
ruby
{ "resource": "" }
q22326
DICOM.DClient.perform_echo
train
def perform_echo # Open a DICOM link: establish_association if association_established? if request_approved? # Continue with our echo, since the request was accepted. # Set the query command elements array: set_command_fragment_echo @link.build_command_fragment(PDU_DATA, presentation_context_id, COMMAND_LAST_FRAGMENT, @command_elements) @link.transmit # Listen for incoming responses and interpret them individually, until we have received the last command fragment. segments = @link.receive_multiple_transmissions process_returned_data(segments) # Print stuff to screen? end # Close the DICOM link: establish_release end end
ruby
{ "resource": "" }
q22327
DICOM.DClient.perform_get
train
def perform_get(path) # Open a DICOM link: establish_association if association_established? if request_approved? # Continue with our operation, since the request was accepted. @link.build_command_fragment(PDU_DATA, presentation_context_id, COMMAND_LAST_FRAGMENT, @command_elements) @link.transmit @link.build_data_fragment(@data_elements, presentation_context_id) @link.transmit # Listen for incoming file data: success = @link.handle_incoming_data(path) if success # Send confirmation response: @link.handle_response end end # Close the DICOM link: establish_release end end
ruby
{ "resource": "" }
q22328
DICOM.DClient.perform_send
train
def perform_send(objects) objects.each_with_index do |dcm, index| # Gather necessary information from the object (SOP Class & Instance UID): sop_class = dcm.value("0008,0016") sop_instance = dcm.value("0008,0018") if sop_class and sop_instance # Only send the image if its sop_class has been accepted by the receiver: if @approved_syntaxes[sop_class] # Set the command array to be used: message_id = index + 1 set_command_fragment_store(sop_class, sop_instance, message_id) # Find context id and transfer syntax: presentation_context_id = @approved_syntaxes[sop_class][0] selected_transfer_syntax = @approved_syntaxes[sop_class][1] # Encode our DICOM object to a binary string which is split up in pieces, sufficiently small to fit within the specified maximum pdu length: # Set the transfer syntax of the DICOM object equal to the one accepted by the SCP: dcm.transfer_syntax = selected_transfer_syntax # Remove the Meta group, since it doesn't belong in a DICOM file transfer: dcm.delete_group(META_GROUP) max_header_length = 14 data_packages = dcm.encode_segments(@max_pdu_length - max_header_length, selected_transfer_syntax) @link.build_command_fragment(PDU_DATA, presentation_context_id, COMMAND_LAST_FRAGMENT, @command_elements) @link.transmit # Transmit all but the last data strings: last_data_package = data_packages.pop data_packages.each do |data_package| @link.build_storage_fragment(PDU_DATA, presentation_context_id, DATA_MORE_FRAGMENTS, data_package) @link.transmit end # Transmit the last data string: @link.build_storage_fragment(PDU_DATA, presentation_context_id, DATA_LAST_FRAGMENT, last_data_package) @link.transmit # Receive confirmation response: segments = @link.receive_single_transmission process_returned_data(segments) end else logger.error("Unable to extract SOP Class UID and/or SOP Instance UID for this DICOM object. File will not be sent to its destination.") end end end
ruby
{ "resource": "" }
q22329
DICOM.DClient.process_presentation_context_response
train
def process_presentation_context_response(presentation_contexts) # Storing approved syntaxes in an Hash with the syntax as key and the value being an array with presentation context ID and the transfer syntax chosen by the SCP. @approved_syntaxes = Hash.new rejected = Hash.new # Reset the presentation context instance variable: @link.presentation_contexts = Hash.new accepted_pc = 0 presentation_contexts.each do |pc| # Determine what abstract syntax this particular presentation context's id corresponds to: id = pc[:presentation_context_id] raise "Error! Even presentation context ID received in the association response. This is not allowed according to the DICOM standard!" if id.even? abstract_syntax = find_abstract_syntax(id) if pc[:result] == 0 accepted_pc += 1 @approved_syntaxes[abstract_syntax] = [id, pc[:transfer_syntax]] @link.presentation_contexts[id] = pc[:transfer_syntax] else rejected[abstract_syntax] = [id, pc[:transfer_syntax]] end end if rejected.length == 0 @request_approved = true if @approved_syntaxes.length == 1 and presentation_contexts.length == 1 logger.info("The presentation context was accepted by host #{@host_ae}.") else logger.info("All #{presentation_contexts.length} presentation contexts were accepted by host #{@host_ae} (#{@host_ip}).") end else # We still consider the request 'approved' if at least one context were accepted: @request_approved = true if @approved_syntaxes.length > 0 logger.error("One or more of your presentation contexts were denied by host #{@host_ae}!") @approved_syntaxes.each_pair do |key, value| sntx_k = (LIBRARY.uid(key) ? LIBRARY.uid(key).name : 'Unknown UID!') sntx_v = (LIBRARY.uid(value[1]) ? LIBRARY.uid(value[1]).name : 'Unknown UID!') logger.info("APPROVED: #{sntx_k} (#{sntx_v})") end rejected.each_pair do |key, value| sntx_k = (LIBRARY.uid(key) ? LIBRARY.uid(key).name : 'Unknown UID!') sntx_v = (LIBRARY.uid(value[1]) ? LIBRARY.uid(value[1]).name : 'Unknown UID!') logger.error("REJECTED: #{sntx_k} (#{sntx_v})") end end end
ruby
{ "resource": "" }
q22330
DICOM.DClient.process_returned_data
train
def process_returned_data(segments) # Reset command results arrays: @command_results = Array.new @data_results = Array.new # Try to extract data: segments.each do |info| if info[:valid] # Determine if it is command or data: if info[:presentation_context_flag] == COMMAND_LAST_FRAGMENT @command_results << info[:results] elsif info[:presentation_context_flag] == DATA_LAST_FRAGMENT @data_results << info[:results] end end end end
ruby
{ "resource": "" }
q22331
DICOM.DClient.set_default_presentation_context
train
def set_default_presentation_context(abstract_syntax) raise ArgumentError, "Expected String, got #{abstract_syntax.class}" unless abstract_syntax.is_a?(String) id = 1 transfer_syntaxes = [IMPLICIT_LITTLE_ENDIAN, EXPLICIT_LITTLE_ENDIAN, EXPLICIT_BIG_ENDIAN] item = {:transfer_syntaxes => transfer_syntaxes} pc = {id => item} @presentation_contexts = {abstract_syntax => pc} end
ruby
{ "resource": "" }
q22332
DICOM.DClient.set_data_elements
train
def set_data_elements(options) @data_elements = [] options.keys.sort.each do |tag| @data_elements << [ tag, options[tag] ] unless options[tag].nil? end end
ruby
{ "resource": "" }
q22333
Calabash.ConsoleHelpers.reload_git_files
train
def reload_git_files files_to_reload = (`git status`.lines.grep(/modified/).map{|l| l.split(" ").last.gsub('../', '')} + `git ls-files --others --exclude-standard`.lines).map(&:chomp) $LOADED_FEATURES.each do |file| files_to_reload.each do |reload_name| if file.end_with?(reload_name) puts "LOADING #{file}" load file break end end end true end
ruby
{ "resource": "" }
q22334
Calabash.ConsoleHelpers.cal_methods
train
def cal_methods c = Class.new(BasicObject) do include Calabash end ConsoleHelpers.puts_unbound_methods(c, 'cal.') true end
ruby
{ "resource": "" }
q22335
Calabash.ConsoleHelpers.cal_method
train
def cal_method(method) c = Class.new(BasicObject) do include Calabash end ConsoleHelpers.puts_unbound_method(c, method.to_sym, 'cal.') true end
ruby
{ "resource": "" }
q22336
Calabash.ConsoleHelpers.cal_ios_methods
train
def cal_ios_methods c = Class.new(BasicObject) do include Calabash::IOSInternal end ConsoleHelpers.puts_unbound_methods(c, 'cal_ios.') true end
ruby
{ "resource": "" }
q22337
Calabash.ConsoleHelpers.cal_android_methods
train
def cal_android_methods c = Class.new(BasicObject) do include Calabash::AndroidInternal end ConsoleHelpers.puts_unbound_methods(c, 'cal_android.') true end
ruby
{ "resource": "" }
q22338
Calabash.ConsoleHelpers.tree
train
def tree ConsoleHelpers.dump(Calabash::Internal.with_current_target {|target| target.dump}) true end
ruby
{ "resource": "" }
q22339
Calabash.ConsoleHelpers.verbose
train
def verbose if Calabash::Logger.log_levels.include?(:debug) puts Color.blue('Debug logging is already turned on.') else Calabash::Logger.log_levels << :debug puts Color.blue('Turned on debug logging.') end true end
ruby
{ "resource": "" }
q22340
Calabash.ConsoleHelpers.quiet
train
def quiet if Calabash::Logger.log_levels.include?(:debug) puts Color.blue('Turned off debug logging.') Calabash::Logger.log_levels.delete(:debug) else puts Color.blue('Debug logging is already turned off.') end true end
ruby
{ "resource": "" }
q22341
DICOM.Stream.decode
train
def decode(length, type) raise ArgumentError, "Invalid argument length. Expected Integer, got #{length.class}" unless length.is_a?(Integer) raise ArgumentError, "Invalid argument type. Expected string, got #{type.class}" unless type.is_a?(String) value = nil if (@index + length) <= @string.length # There are sufficient bytes remaining to extract the value: if type == 'AT' # We need to guard ourselves against the case where a string contains an invalid 'AT' value: if length == 4 value = decode_tag else # Invalid. Just return nil. skip(length) end else # Decode the binary string and return value: value = @string.slice(@index, length).unpack(vr_to_str(type)) # If the result is an array of one element, return the element instead of the array. # If result is contained in a multi-element array, the original array is returned. if value.length == 1 value = value[0] # If value is a string, strip away possible trailing whitespace: value = value.rstrip if value.is_a?(String) end # Update our position in the string: skip(length) end end value end
ruby
{ "resource": "" }
q22342
DICOM.Stream.decode_tag
train
def decode_tag length = 4 tag = nil if (@index + length) <= @string.length # There are sufficient bytes remaining to extract a full tag: str = @string.slice(@index, length).unpack(@hex)[0].upcase if @equal_endian tag = "#{str[2..3]}#{str[0..1]},#{str[6..7]}#{str[4..5]}" else tag = "#{str[0..3]},#{str[4..7]}" end # Update our position in the string: skip(length) end tag end
ruby
{ "resource": "" }
q22343
DICOM.Stream.encode
train
def encode(value, type) raise ArgumentError, "Invalid argument type. Expected string, got #{type.class}" unless type.is_a?(String) value = [value] unless value.is_a?(Array) return value.pack(vr_to_str(type)) end
ruby
{ "resource": "" }
q22344
DICOM.Stream.encode_string_with_trailing_spaces
train
def encode_string_with_trailing_spaces(string, target_length) length = string.length if length < target_length return "#{[string].pack(@str)}#{['20'*(target_length-length)].pack(@hex)}" elsif length == target_length return [string].pack(@str) else raise "The specified string is longer than the allowed maximum length (String: #{string}, Target length: #{target_length})." end end
ruby
{ "resource": "" }
q22345
DICOM.Stream.encode_value
train
def encode_value(value, vr) if vr == 'AT' bin = encode_tag(value) else # Make sure the value is in an array: value = [value] unless value.is_a?(Array) # Get the proper pack string: type = vr_to_str(vr) # Encode: bin = value.pack(type) # Add an empty byte if the resulting binary has an odd length: bin = "#{bin}#{@pad_byte[vr]}" if bin.length.odd? end return bin end
ruby
{ "resource": "" }
q22346
Calabash.Interactions.backdoor
train
def backdoor(name, *arguments) Calabash::Internal.with_current_target {|target| target.backdoor(name, *arguments)} end
ruby
{ "resource": "" }
q22347
DICOM.DServer.add_abstract_syntax
train
def add_abstract_syntax(uid) lib_uid = LIBRARY.uid(uid) raise "Invalid/unknown UID: #{uid}" unless lib_uid @accepted_abstract_syntaxes[uid] = lib_uid.name end
ruby
{ "resource": "" }
q22348
DICOM.DServer.add_transfer_syntax
train
def add_transfer_syntax(uid) lib_uid = LIBRARY.uid(uid) raise "Invalid/unknown UID: #{uid}" unless lib_uid @accepted_transfer_syntaxes[uid] = lib_uid.name end
ruby
{ "resource": "" }
q22349
DICOM.DServer.print_abstract_syntaxes
train
def print_abstract_syntaxes # Determine length of longest key to ensure pretty print: max_uid = @accepted_abstract_syntaxes.keys.collect{|k| k.length}.max puts "Abstract syntaxes which are accepted by this SCP:" @accepted_abstract_syntaxes.sort.each do |pair| puts "#{pair[0]}#{' '*(max_uid-pair[0].length)} #{pair[1]}" end end
ruby
{ "resource": "" }
q22350
Calabash.Wait.wait_for_view
train
def wait_for_view(query, timeout: Calabash::Wait.default_options[:timeout], timeout_message: nil, retry_frequency: Calabash::Wait.default_options[:retry_frequency]) if query.nil? raise ArgumentError, 'Query cannot be nil' end timeout_message ||= lambda do |wait_options| "Waited #{wait_options[:timeout]} seconds for #{Wait.parse_query_list(query)} to match a view" end wait_for(timeout_message, timeout: timeout, retry_frequency: retry_frequency, exception_class: ViewNotFoundError) do result = query(query) !result.empty? && result end.first end
ruby
{ "resource": "" }
q22351
Calabash.Wait.wait_for_views
train
def wait_for_views(*queries, timeout: Calabash::Wait.default_options[:timeout], timeout_message: nil, retry_frequency: Calabash::Wait.default_options[:retry_frequency]) if queries.nil? || queries.any?(&:nil?) raise ArgumentError, 'Query cannot be nil' end timeout_message ||= lambda do |wait_options| "Waited #{wait_options[:timeout]} seconds for #{Wait.parse_query_list(queries)} to each match a view" end wait_for(timeout_message, timeout: timeout, retry_frequency: retry_frequency, exception_class: ViewNotFoundError) do views_exist?(*queries) end # Do not return the value of views_exist?(queries) as it clutters # a console environment true end
ruby
{ "resource": "" }
q22352
Calabash.Wait.wait_for_no_view
train
def wait_for_no_view(query, timeout: Calabash::Wait.default_options[:timeout], timeout_message: nil, retry_frequency: Calabash::Wait.default_options[:retry_frequency]) if query.nil? raise ArgumentError, 'Query cannot be nil' end timeout_message ||= lambda do |wait_options| "Waited #{wait_options[:timeout]} seconds for #{Wait.parse_query_list(query)} to not match any view" end wait_for(timeout_message, timeout: timeout, retry_frequency: retry_frequency, exception_class: ViewFoundError) do !view_exists?(query) end end
ruby
{ "resource": "" }
q22353
Calabash.Wait.wait_for_no_views
train
def wait_for_no_views(*queries, timeout: Calabash::Wait.default_options[:timeout], timeout_message: nil, retry_frequency: Calabash::Wait.default_options[:retry_frequency]) if queries.nil? || queries.any?(&:nil?) raise ArgumentError, 'Query cannot be nil' end timeout_message ||= lambda do |wait_options| "Waited #{wait_options[:timeout]} seconds for #{Wait.parse_query_list(queries)} to each not match any view" end wait_for(timeout_message, timeout: timeout, retry_frequency: retry_frequency, exception_class: ViewFoundError) do !views_exist?(*queries) end end
ruby
{ "resource": "" }
q22354
Calabash.Wait.view_exists?
train
def view_exists?(query) if query.nil? raise ArgumentError, 'Query cannot be nil' end result = query(query) !result.empty? end
ruby
{ "resource": "" }
q22355
Calabash.Wait.views_exist?
train
def views_exist?(*queries) if queries.nil? || queries.any?(&:nil?) raise ArgumentError, 'Query cannot be nil' end results = queries.map{|query| view_exists?(query)} results.all? end
ruby
{ "resource": "" }
q22356
Calabash.Wait.expect_view
train
def expect_view(query) if query.nil? raise ArgumentError, 'Query cannot be nil' end unless view_exists?(query) raise ViewNotFoundError, "No view matched #{Wait.parse_query_list(query)}" end true end
ruby
{ "resource": "" }
q22357
Calabash.Wait.expect_views
train
def expect_views(*queries) if queries.nil? || queries.any?(&:nil?) raise ArgumentError, 'Query cannot be nil' end unless views_exist?(*queries) raise ViewNotFoundError, "Not all queries #{Wait.parse_query_list(queries)} matched a view" end true end
ruby
{ "resource": "" }
q22358
Calabash.Wait.do_not_expect_view
train
def do_not_expect_view(query) if query.nil? raise ArgumentError, 'Query cannot be nil' end if view_exists?(query) raise ViewFoundError, "A view matched #{Wait.parse_query_list(query)}" end true end
ruby
{ "resource": "" }
q22359
Calabash.Wait.do_not_expect_views
train
def do_not_expect_views(*queries) if queries.nil? || queries.any?(&:nil?) raise ArgumentError, 'Query cannot be nil' end if queries.map{|query| view_exists?(query)}.any? raise ViewFoundError, "Some views matched #{Wait.parse_query_list(queries)}" end true end
ruby
{ "resource": "" }
q22360
Calabash.Wait.wait_for_text
train
def wait_for_text(text, timeout: Calabash::Wait.default_options[:timeout], timeout_message: nil, retry_frequency: Calabash::Wait.default_options[:retry_frequency]) wait_for_view("* {text CONTAINS[c] '#{text}'}", timeout: timeout, timeout_message: timeout_message, retry_frequency: retry_frequency) end
ruby
{ "resource": "" }
q22361
Calabash.Wait.wait_for_no_text
train
def wait_for_no_text(text, timeout: Calabash::Wait.default_options[:timeout], timeout_message: nil, retry_frequency: Calabash::Wait.default_options[:retry_frequency]) wait_for_no_view("* {text CONTAINS[c] '#{text}'}", timeout: timeout, timeout_message: timeout_message, retry_frequency: retry_frequency) end
ruby
{ "resource": "" }
q22362
DICOM.AuditTrail.add_record
train
def add_record(tag, original, replacement) @dictionary[tag] = Hash.new unless @dictionary.key?(tag) @dictionary[tag][original] = replacement end
ruby
{ "resource": "" }
q22363
DICOM.AuditTrail.original
train
def original(tag, replacement) original = nil if @dictionary.key?(tag) original = @dictionary[tag].key(replacement) end return original end
ruby
{ "resource": "" }
q22364
DICOM.AuditTrail.replacement
train
def replacement(tag, original) replacement = nil replacement = @dictionary[tag][original] if @dictionary.key?(tag) return replacement end
ruby
{ "resource": "" }
q22365
DICOM.DObject.encode_segments
train
def encode_segments(max_size, transfer_syntax=IMPLICIT_LITTLE_ENDIAN) raise ArgumentError, "Invalid argument. Expected an Integer, got #{max_size.class}." unless max_size.is_a?(Integer) raise ArgumentError, "Argument too low (#{max_size}), please specify a bigger Integer." unless max_size > 16 raise "Can not encode binary segments for an empty DICOM object." if children.length == 0 encode_in_segments(max_size, :syntax => transfer_syntax) end
ruby
{ "resource": "" }
q22366
DICOM.DObject.summary
train
def summary # FIXME: Perhaps this method should be split up in one or two separate methods # which just builds the information arrays, and a third method for printing this to the screen. sys_info = Array.new info = Array.new # Version of Ruby DICOM used: sys_info << "Ruby DICOM version: #{VERSION}" # System endian: cpu = (CPU_ENDIAN ? "Big Endian" : "Little Endian") sys_info << "Byte Order (CPU): #{cpu}" # Source (file name): if @source if @source == :str source = "Binary string #{@read_success ? '(successfully parsed)' : '(failed to parse)'}" else source = "File #{@read_success ? '(successfully read)' : '(failed to read)'}: #{@source}" end else source = 'Created from scratch' end info << "Source: #{source}" # Modality: modality = (LIBRARY.uid(value('0008,0016')) ? LIBRARY.uid(value('0008,0016')).name : "SOP Class unknown or not specified!") info << "Modality: #{modality}" # Meta header presence (Simply check for the presence of the transfer syntax data element), VR and byte order: ts_status = self['0002,0010'] ? '' : ' (Assumed)' ts = LIBRARY.uid(transfer_syntax) explicit = ts ? ts.explicit? : true endian = ts ? ts.big_endian? : false meta_comment = ts ? "" : " (But unknown/invalid transfer syntax: #{transfer_syntax})" info << "Meta Header: #{self['0002,0010'] ? 'Yes' : 'No'}#{meta_comment}" info << "Value Representation: #{explicit ? 'Explicit' : 'Implicit'}#{ts_status}" info << "Byte Order (File): #{endian ? 'Big Endian' : 'Little Endian'}#{ts_status}" # Pixel data: pixels = self[PIXEL_TAG] unless pixels info << "Pixel Data: No" else info << "Pixel Data: Yes" # Image size: cols = (exists?("0028,0011") ? self["0028,0011"].value : "Columns missing") rows = (exists?("0028,0010") ? self["0028,0010"].value : "Rows missing") info << "Image Size: #{cols}*#{rows}" # Frames: frames = value("0028,0008") || "1" unless frames == "1" or frames == 1 # Encapsulated or 3D pixel data: if pixels.is_a?(Element) frames = frames.to_s + " (3D Pixel Data)" else frames = frames.to_s + " (Encapsulated Multiframe Image)" end end info << "Number of frames: #{frames}" # Color: colors = (exists?("0028,0004") ? self["0028,0004"].value : "Not specified") info << "Photometry: #{colors}" # Compression: compression = (ts ? (ts.compressed_pixels? ? ts.name : 'No') : 'No' ) info << "Compression: #{compression}#{ts_status}" # Pixel bits (allocated): bits = (exists?("0028,0100") ? self["0028,0100"].value : "Not specified") info << "Bits per Pixel: #{bits}" end # Print the DICOM object's key properties: separator = "-------------------------------------------" puts "System Properties:" puts separator + "\n" puts sys_info puts "\n" puts "DICOM Object Properties:" puts separator puts info puts separator return info end
ruby
{ "resource": "" }
q22367
DICOM.DObject.transfer_syntax=
train
def transfer_syntax=(new_syntax) # Verify old and new transfer syntax: new_uid = LIBRARY.uid(new_syntax) old_uid = LIBRARY.uid(transfer_syntax) raise ArgumentError, "Invalid/unknown transfer syntax specified: #{new_syntax}" unless new_uid && new_uid.transfer_syntax? raise ArgumentError, "Invalid/unknown existing transfer syntax: #{new_syntax} Unable to reliably handle byte order encoding. Modify the transfer syntax element directly instead." unless old_uid && old_uid.transfer_syntax? # Set the new transfer syntax: if exists?("0002,0010") self["0002,0010"].value = new_syntax else add(Element.new("0002,0010", new_syntax)) end # Update our Stream instance with the new encoding: @stream.endian = new_uid.big_endian? # If endianness is changed, re-encode elements (only elements depending on endianness will actually be re-encoded): encode_children(old_uid.big_endian?) if old_uid.big_endian? != new_uid.big_endian? end
ruby
{ "resource": "" }
q22368
DICOM.DObject.write
train
def write(file_name, options={}) raise ArgumentError, "Invalid file_name. Expected String, got #{file_name.class}." unless file_name.is_a?(String) @include_empty_parents = options[:include_empty_parents] insert_missing_meta unless options[:ignore_meta] write_elements(:file_name => file_name, :signature => true, :syntax => transfer_syntax) end
ruby
{ "resource": "" }
q22369
DICOM.DObject.meta_group_length
train
def meta_group_length group_length = 0 meta_elements = group(META_GROUP) tag = 4 vr = 2 meta_elements.each do |element| case element.vr when "OB","OW","OF","SQ","UN","UT" length = 6 else length = 2 end group_length += tag + vr + length + element.bin.length end group_length end
ruby
{ "resource": "" }
q22370
DICOM.ImageItem.add_element
train
def add_element(tag, value, options={}) add(e = Element.new(tag, value, options)) e end
ruby
{ "resource": "" }
q22371
DICOM.ImageItem.add_sequence
train
def add_sequence(tag, options={}) add(s = Sequence.new(tag, options)) s end
ruby
{ "resource": "" }
q22372
DICOM.ImageItem.color?
train
def color? # "Photometric Interpretation" is contained in the data element "0028,0004": begin photometric = photometry if photometric.include?('COLOR') or photometric.include?('RGB') or photometric.include?('YBR') return true else return false end rescue return false end end
ruby
{ "resource": "" }
q22373
DICOM.ImageItem.decode_pixels
train
def decode_pixels(bin, stream=@stream) raise ArgumentError, "Expected String, got #{bin.class}." unless bin.is_a?(String) pixels = false # We need to know what kind of bith depth and integer type the pixel data is saved with: bit_depth_element = self['0028,0100'] pixel_representation_element = self['0028,0103'] if bit_depth_element and pixel_representation_element # Load the binary pixel data to the Stream instance: stream.set_string(bin) template = template_string(bit_depth_element.value.to_i) pixels = stream.decode_all(template) if template else raise "The Element specifying Bit Depth (0028,0100) is missing. Unable to decode pixel data." unless bit_depth_element raise "The Element specifying Pixel Representation (0028,0103) is missing. Unable to decode pixel data." unless pixel_representation_element end return pixels end
ruby
{ "resource": "" }
q22374
DICOM.ImageItem.encode_pixels
train
def encode_pixels(pixels, stream=@stream) raise ArgumentError, "Expected Array, got #{pixels.class}." unless pixels.is_a?(Array) bin = false # We need to know what kind of bith depth and integer type the pixel data is saved with: bit_depth_element = self['0028,0100'] pixel_representation_element = self['0028,0103'] if bit_depth_element and pixel_representation_element template = template_string(bit_depth_element.value.to_i) bin = stream.encode(pixels, template) if template else raise "The Element specifying Bit Depth (0028,0100) is missing. Unable to encode the pixel data." unless bit_depth_element raise "The Element specifying Pixel Representation (0028,0103) is missing. Unable to encode the pixel data." unless pixel_representation_element end return bin end
ruby
{ "resource": "" }
q22375
DICOM.ImageItem.images
train
def images(options={}) images = Array.new if exists?(PIXEL_TAG) # Gather the pixel data strings, and pick a single frame if indicated by options: strings = image_strings(split_to_frames=true) strings = [strings[options[:frame]]] if options[:frame] if compression? # Decompress, either to numbers (RLE) or to an image object (image based compressions): if [TXS_RLE].include?(transfer_syntax) pixel_frames = Array.new strings.each {|string| pixel_frames << decode_rle(num_cols, num_rows, string)} else images = decompress(strings) || Array.new logger.warn("Decompressing pixel values has failed (unsupported transfer syntax: '#{transfer_syntax}' - #{LIBRARY.uid(transfer_syntax) ? LIBRARY.uid(transfer_syntax).name : 'Unknown transfer syntax!'})") unless images.length > 0 end else # Uncompressed: Decode to numbers. pixel_frames = Array.new strings.each {|string| pixel_frames << decode_pixels(string)} end if pixel_frames images = Array.new pixel_frames.each do |pixels| # Pixel values and pixel order may need to be rearranged if we have color data: pixels = process_colors(pixels) if color? if pixels images << read_image(pixels, num_cols, num_rows, options) else logger.warn("Processing pixel values for this particular color mode failed, unable to construct image(s).") end end end end return images end
ruby
{ "resource": "" }
q22376
DICOM.ImageItem.image_to_file
train
def image_to_file(file) raise ArgumentError, "Expected #{String}, got #{file.class}." unless file.is_a?(String) # Split the file name in case of multiple fragments: parts = file.split('.') if parts.length > 1 base = parts[0..-2].join extension = '.' + parts.last else base = file extension = '' end # Get the binary image strings and dump them to the file(s): images = image_strings images.each_index do |i| if images.length == 1 f = File.new(file, 'wb') else f = File.new("#{base}-#{i}#{extension}", 'wb') end f.write(images[i]) f.close end end
ruby
{ "resource": "" }
q22377
DICOM.ImageItem.pixels
train
def pixels(options={}) pixels = nil if exists?(PIXEL_TAG) # For now we only support returning pixel data of the first frame, if the image is located in multiple pixel data items: if compression? pixels = decompress(image_strings.first) else pixels = decode_pixels(image_strings.first) end if pixels # Remap the image from pixel values to presentation values if the user has requested this: if options[:remap] or options[:level] if options[:narray] # Use numerical array (faster): pixels = process_presentation_values_narray(pixels, -65535, 65535, options[:level]).to_a else # Use standard Ruby array (slower): pixels = process_presentation_values(pixels, -65535, 65535, options[:level]) end end else logger.warn("Decompressing the Pixel Data failed. Pixel values can not be extracted.") end end return pixels end
ruby
{ "resource": "" }
q22378
DICOM.ImageItem.decode_rle
train
def decode_rle(cols, rows, string) # FIXME: Remove cols and rows (were only added for debugging). pixels = Array.new # RLE header specifying the number of segments: header = string[0...64].unpack('L*') image_segments = Array.new # Extracting all start and endpoints of the different segments: header.each_index do |n| if n == 0 # This one need no processing. elsif n == header[0] # It's the last one image_segments << [header[n], -1] break else image_segments << [header[n], header[n + 1] - 1] end end # Iterate over each segment and extract pixel data: image_segments.each do |range| segment_data = Array.new next_bytes = -1 next_multiplier = 0 # Iterate this segment's pixel string: string[range[0]..range[1]].each_byte do |b| if next_multiplier > 0 next_multiplier.times { segment_data << b } next_multiplier = 0 elsif next_bytes > 0 segment_data << b next_bytes -= 1 elsif b <= 127 next_bytes = b + 1 else # Explaining the 257 at this point is a little bit complicate. Basically it has something # to do with the algorithm described in the DICOM standard and that the value -1 as uint8 is 255. # TODO: Is this architectur safe or does it only work on Intel systems??? next_multiplier = 257 - b end end # Verify that the RLE decoding has executed properly: throw "Size mismatch #{segment_data.size} != #{rows * cols}" if segment_data.size != rows * cols pixels += segment_data end return pixels end
ruby
{ "resource": "" }
q22379
DICOM.ImageItem.process_presentation_values
train
def process_presentation_values(pixel_data, min_allowed, max_allowed, level=nil) # Process pixel data for presentation according to the image information in the DICOM object: center, width, intercept, slope = window_level_values # Have image leveling been requested? if level # If custom values are specified in an array, use those. If not, the default values from the DICOM object are used: if level.is_a?(Array) center = level[0] width = level[1] end else center, width = false, false end # PixelOutput = slope * pixel_values + intercept if intercept != 0 or slope != 1 pixel_data.collect!{|x| (slope * x) + intercept} end # Contrast enhancement by black and white thresholding: if center and width low = center - width/2 high = center + width/2 pixel_data.each_index do |i| if pixel_data[i] < low pixel_data[i] = low elsif pixel_data[i] > high pixel_data[i] = high end end end # Need to introduce an offset? min_pixel_value = pixel_data.min if min_allowed if min_pixel_value < min_allowed offset = min_pixel_value.abs pixel_data.collect!{|x| x + offset} end end # Downscale pixel range? max_pixel_value = pixel_data.max if max_allowed if max_pixel_value > max_allowed factor = (max_pixel_value.to_f/max_allowed.to_f).ceil pixel_data.collect!{|x| x / factor} end end return pixel_data end
ruby
{ "resource": "" }
q22380
DICOM.ImageItem.process_presentation_values_narray
train
def process_presentation_values_narray(pixel_data, min_allowed, max_allowed, level=nil) # Process pixel data for presentation according to the image information in the DICOM object: center, width, intercept, slope = window_level_values # Have image leveling been requested? if level # If custom values are specified in an array, use those. If not, the default values from the DICOM object are used: if level.is_a?(Array) center = level[0] width = level[1] end else center, width = false, false end # Need to convert to NArray? if pixel_data.is_a?(Array) n_arr = Numo::NArray[*pixel_data] else n_arr = pixel_data end # Remap: # PixelOutput = slope * pixel_values + intercept if intercept != 0 or slope != 1 n_arr = slope * n_arr + intercept end # Contrast enhancement by black and white thresholding: if center and width low = center - width/2 high = center + width/2 n_arr[n_arr < low] = low n_arr[n_arr > high] = high end # Need to introduce an offset? min_pixel_value = n_arr.min if min_allowed if min_pixel_value < min_allowed offset = min_pixel_value.abs n_arr = n_arr + offset end end # Downscale pixel range? max_pixel_value = n_arr.max if max_allowed if max_pixel_value > max_allowed factor = (max_pixel_value.to_f/max_allowed.to_f).ceil n_arr = n_arr / factor end end return n_arr end
ruby
{ "resource": "" }
q22381
DICOM.ImageItem.read_image
train
def read_image(pixel_data, columns, rows, options={}) raise ArgumentError, "Expected Array for pixel_data, got #{pixel_data.class}" unless pixel_data.is_a?(Array) raise ArgumentError, "Expected Integer for columns, got #{columns.class}" unless columns.is_a?(Integer) raise ArgumentError, "Expected Rows for columns, got #{rows.class}" unless rows.is_a?(Integer) raise ArgumentError, "Size of pixel_data must be at least equal to columns*rows. Got #{columns}*#{rows}=#{columns*rows}, which is less than the array size #{pixel_data.length}" if columns * rows > pixel_data.length # Remap the image from pixel values to presentation values if the user has requested this: if options[:remap] or options[:level] # How to perform the remapping? NArray (fast) or Ruby Array (slow)? if options[:narray] == true pixel_data = process_presentation_values_narray(pixel_data, 0, 65535, options[:level]).to_a else pixel_data = process_presentation_values(pixel_data, 0, 65535, options[:level]) end else # No remapping, but make sure that we pass on unsigned pixel values to the image processor: pixel_data = pixel_data.to_unsigned(bit_depth) if signed_pixels? end image = import_pixels(pixel_data.to_blob(actual_bit_depth), columns, rows, actual_bit_depth, photometry) return image end
ruby
{ "resource": "" }
q22382
DICOM.ImageItem.window_level_values
train
def window_level_values center = (self['0028,1050'].is_a?(Element) == true ? self['0028,1050'].value.to_i : nil) width = (self['0028,1051'].is_a?(Element) == true ? self['0028,1051'].value.to_i : nil) intercept = (self['0028,1052'].is_a?(Element) == true ? self['0028,1052'].value.to_i : 0) slope = (self['0028,1053'].is_a?(Element) == true ? self['0028,1053'].value.to_i : 1) return center, width, intercept, slope end
ruby
{ "resource": "" }
q22383
DICOM.ImageItem.write_pixels
train
def write_pixels(bin) if self.exists?(PIXEL_TAG) # Update existing Data Element: self[PIXEL_TAG].bin = bin else # Create new Data Element: pixel_element = Element.new(PIXEL_TAG, bin, :encoded => true, :parent => self) end end
ruby
{ "resource": "" }
q22384
DICOM.Parent.parse
train
def parse(bin, syntax, switched=false, explicit=true) raise ArgumentError, "Invalid argument 'bin'. Expected String, got #{bin.class}." unless bin.is_a?(String) raise ArgumentError, "Invalid argument 'syntax'. Expected String, got #{syntax.class}." unless syntax.is_a?(String) read(bin, signature=false, :syntax => syntax, :switched => switched, :explicit => explicit) end
ruby
{ "resource": "" }
q22385
DICOM.Parent.check_duplicate
train
def check_duplicate(tag, elemental) if @current_parent[tag] gp = @current_parent.parent ? "#{@current_parent.parent.representation} => " : '' p = @current_parent.representation logger.warn("Duplicate #{elemental} (#{tag}) detected at level: #{gp}#{p}") end end
ruby
{ "resource": "" }
q22386
DICOM.Parent.check_header
train
def check_header # According to the official DICOM standard, a DICOM file shall contain 128 consequtive (zero) bytes, # followed by 4 bytes that spell the string 'DICM'. Apparently, some providers seems to skip this in their DICOM files. # Check that the string is long enough to contain a valid header: if @str.length < 132 # This does not seem to be a valid DICOM string and so we return. return nil else @stream.skip(128) # Next 4 bytes should spell "DICM": identifier = @stream.decode(4, "STR") @header_length += 132 if identifier != "DICM" then # Header signature is not valid (we will still try to parse it is a DICOM string though): logger.warn("This string does not contain the expected DICOM header. Will try to parse the string anyway (assuming a missing header).") # As the string is not conforming to the DICOM standard, it is possible that it does not contain a # transfer syntax element, and as such, we attempt to choose the most probable encoding values here: @explicit = false return false else # Header signature is valid: @signature = true return true end end end
ruby
{ "resource": "" }
q22387
DICOM.Parent.process_data_element
train
def process_data_element # FIXME: This method has grown a bit messy and isn't very pleasant to read. Cleanup possible? # After having been into a possible unknown sequence with undefined length, we may need to reset # explicitness from implicit to explicit: if !@original_explicit.nil? && @explicitness_reset_parent == @current_parent @explicit = @original_explicit end # STEP 1: # Attempt to read data element tag: tag = read_tag # Return nil if we have (naturally) reached the end of the data string. return nil unless tag # STEP 2: # Access library to retrieve the data element name and VR from the tag we just read: # (Note: VR will be overwritten in the next step if the DICOM string contains VR (explicit encoding)) name, vr = LIBRARY.name_and_vr(tag) # STEP 3: # Read VR (if it exists) and the length value: vr, length = read_vr_length(vr,tag) level_vr = vr # STEP 4: # Reading value of data element. # Special handling needed for items in encapsulated image data: if @enc_image and tag == ITEM_TAG # The first item appearing after the image element is a 'normal' item, the rest hold image data. # Note that the first item will contain data if there are multiple images, and so must be read. vr = "OW" # how about alternatives like OB? # Modify name of item if this is an item that holds pixel data: if @current_element.tag != PIXEL_TAG name = PIXEL_ITEM_NAME end end # Read the binary string of the element: bin = read_bin(length) if length > 0 # Read the value of the element (if it contains data, and it is not a sequence or ordinary item): if length > 0 and vr != "SQ" and tag != ITEM_TAG # Read the element's processed value: value = read_value(vr, length) else # Data element has no value (data). value = nil # Special case: Check if pixel data element is sequenced: if tag == PIXEL_TAG # Change name and vr of pixel data element if it does not contain data itself: name = ENCAPSULATED_PIXEL_NAME level_vr = "SQ" @enc_image = true end end # Create an Element from the gathered data: # if vr is UN ("unknown") and length is -1, treat as a sequence (sec. 6.2.2 of DICOM standard) if level_vr == "SQ" or tag == ITEM_TAG or (level_vr == "UN" and length == -1) if level_vr == "SQ" or (level_vr == "UN" and length == -1) check_duplicate(tag, 'Sequence') # If we get an unknown sequence with undefined length, we must switch to implicit for decoding its content: if level_vr == "UN" and length == -1 @original_explicit = @explicit @explicit = false @explicitness_reset_parent = @current_parent end unless @current_parent[tag] and !@overwrite @current_element = Sequence.new(tag, :length => length, :name => name, :parent => @current_parent, :vr => vr) else # We have skipped a sequence. This means that any following children # of this sequence must be skipped as well. We solve this by creating an 'orphaned' # sequence that has a parent defined, but does not add itself to this parent: @current_element = Sequence.new(tag, :length => length, :name => name, :vr => vr) @current_element.set_parent(@current_parent) end elsif tag == ITEM_TAG # Create an Item: if @enc_image @current_element = Item.new(:bin => bin, :length => length, :name => name, :parent => @current_parent, :vr => vr) else @current_element = Item.new(:length => length, :name => name, :parent => @current_parent, :vr => vr) end end # Common operations on the two types of parent elements: if length == 0 and @enc_image # Set as parent. Exceptions when parent will not be set: # Item/Sequence has zero length & Item is a pixel item (which contains pixels, not child elements). @current_parent = @current_element elsif length != 0 @current_parent = @current_element unless name == PIXEL_ITEM_NAME end # If length is specified (no delimitation items), load a new DRead instance to read these child elements # and load them into the current sequence. The exception is when we have a pixel data item. if length > 0 and not @enc_image @current_element.parse(bin, @transfer_syntax, switched=@switched, @explicit) @current_parent = @current_parent.parent return false unless @read_success end elsif DELIMITER_TAGS.include?(tag) # We do not create an element for the delimiter items. # The occurance of such a tag indicates that a sequence or item has ended, and the parent must be changed: @current_parent = @current_parent.parent else check_duplicate(tag, 'Element') unless @current_parent[tag] and !@overwrite @current_element = Element.new(tag, value, :bin => bin, :name => name, :parent => @current_parent, :vr => vr) # Check that the data stream didn't end abruptly: raise "The actual length of the value (#{@current_element.bin.length}) does not match its specified length (#{length}) for Data Element #{@current_element.tag}" if length != @current_element.bin.length end end # Return true to indicate success: return true end
ruby
{ "resource": "" }
q22388
DICOM.Parent.read
train
def read(string, signature=true, options={}) # (Re)Set variables: @str = string @overwrite = options[:overwrite] # Presence of the official DICOM signature: @signature = false # Default explicitness of start of DICOM string (if undefined it defaults to true): @explicit = options[:explicit].nil? ? true : options[:explicit] # Default endianness of start of DICOM string is little endian: @str_endian = false # A switch of endianness may occur after the initial meta group, an this needs to be monitored: @switched_endian = false # Explicitness of the remaining groups after the initial 0002 group: @rest_explicit = false # Endianness of the remaining groups after the first group: @rest_endian = false # When the string switch from group 0002 to a later group we will update encoding values, and this switch will keep track of that: @switched = options[:switched] ? options[:switched] : false # Keeping track of the data element parent status while parsing the DICOM string: @current_parent = self # Keeping track of what is the current data element: @current_element = self # Items contained under the pixel data element may contain data directly, so we need a variable to keep track of this: @enc_image = false # Assume header size is zero bytes until otherwise is determined: @header_length = 0 # Assume string will be read successfully and toggle it later if we experience otherwise: @read_success = true # Our encoding instance: @stream = Stream.new(@str, @str_endian) # If a transfer syntax has been specified as an option for a DICOM object, # make sure that it makes it into the object: if options[:syntax] @transfer_syntax = options[:syntax] Element.new("0002,0010", options[:syntax], :parent => self) if self.is_a?(DObject) end # Check for header information if indicated: if signature # Read and verify the DICOM header: header = check_header # If the string is without the expected header, we will attempt # to read data elements from the very start of the string: if header == false @stream.skip(-132) elsif header.nil? # Not a valid DICOM string, return: @read_success = false return end end # Run a loop which parses Data Elements, one by one, until the end of the data string is reached: data_element = true while data_element do # Using a rescue clause since processing Data Elements can cause errors when parsing an invalid DICOM string. begin # Extracting Data element information (nil is returned if end of the string is encountered in a normal way). data_element = process_data_element rescue Exception => msg # The parse algorithm crashed. Set data_element as false to break # the loop and toggle the success boolean to indicate failure. @read_success = false data_element = false # Output the raised message as a warning: logger.warn(msg.to_s) # Ouput the backtrace as debug information: logger.debug(msg.backtrace) # Explain the failure as an error: logger.error("Parsing a Data Element has failed. This is likely caused by an invalid DICOM encoding.") end end end
ruby
{ "resource": "" }
q22389
DICOM.Parent.add_with_segmentation
train
def add_with_segmentation(string) # As the encoded DICOM string will be cut in multiple, smaller pieces, we need to monitor the length of our encoded strings: if (string.length + @stream.length) > @max_size split_and_add(string) elsif (30 + @stream.length) > @max_size # End the current segment, and start on a new segment for this string. @segments << @stream.export @stream.add_last(string) else # We are nowhere near the limit, simply add the string: @stream.add_last(string) end end
ruby
{ "resource": "" }
q22390
DICOM.Parent.check_encapsulated_image
train
def check_encapsulated_image(element) # If DICOM object contains encapsulated pixel data, we need some special handling for its items: if element.tag == PIXEL_TAG and element.parent.is_a?(DObject) @enc_image = true if element.length <= 0 end end
ruby
{ "resource": "" }
q22391
DICOM.Parent.encode_in_segments
train
def encode_in_segments(max_size, options={}) @max_size = max_size @transfer_syntax = options[:syntax] # Until a DICOM write has completed successfully the status is 'unsuccessful': @write_success = false # Default explicitness of start of DICOM file: @explicit = true # Default endianness of start of DICOM files (little endian): @str_endian = false # When the file switch from group 0002 to a later group we will update encoding values, and this switch will keep track of that: @switched = false # Items contained under the Pixel Data element needs some special attention to write correctly: @enc_image = false # Create a Stream instance to handle the encoding of content to a binary string: @stream = Stream.new(nil, @str_endian) @segments = Array.new write_data_elements(children) # Extract the remaining string in our stream instance to our array of strings: @segments << @stream.export # Mark this write session as successful: @write_success = true return @segments end
ruby
{ "resource": "" }
q22392
DICOM.Parent.split_and_add
train
def split_and_add(string) # Duplicate the string as not to ruin the binary of the data element with our slicing: segment = string.dup append = segment.slice!(0, @max_size-@stream.length) # Clear out the stream along with a small part of the string: @segments << @stream.export + append if (30 + segment.length) > @max_size # The remaining part of the string is bigger than the max limit, fill up more segments: # How many full segments will this string fill? number = (segment.length/@max_size.to_f).floor start_index = 0 number.times { @segments << segment.slice(start_index, @max_size) start_index += @max_size } # The remaining part is added to the stream: @stream.add_last(segment.slice(start_index, segment.length - start_index)) else # The rest of the string is small enough that it can be added to the stream: @stream.add_last(segment) end end
ruby
{ "resource": "" }
q22393
DICOM.Parent.write_data_element
train
def write_data_element(element) # Step 1: Write tag: write_tag(element.tag) # Step 2: Write [VR] and value length: write_vr_length(element.tag, element.vr, element.length) # Step 3: Write value (Insert the already encoded binary string): write_value(element.bin) check_encapsulated_image(element) end
ruby
{ "resource": "" }
q22394
DICOM.Parent.write_delimiter
train
def write_delimiter(element) delimiter_tag = (element.tag == ITEM_TAG ? ITEM_DELIMITER : SEQUENCE_DELIMITER) write_tag(delimiter_tag) write_vr_length(delimiter_tag, ITEM_VR, 0) end
ruby
{ "resource": "" }
q22395
DICOM.Parent.write_elements
train
def write_elements(options={}) # Check if we are able to create given file: open_file(options[:file_name]) # Go ahead and write if the file was opened successfully: if @file # Initiate necessary variables: @transfer_syntax = options[:syntax] # Until a DICOM write has completed successfully the status is 'unsuccessful': @write_success = false # Default explicitness of start of DICOM file: @explicit = true # Default endianness of start of DICOM files (little endian): @str_endian = false # When the file switch from group 0002 to a later group we will update encoding values, and this switch will keep track of that: @switched = false # Items contained under the Pixel Data element needs some special attention to write correctly: @enc_image = false # Create a Stream instance to handle the encoding of content to a binary string: @stream = Stream.new(nil, @str_endian) # Tell the Stream instance which file to write to: @stream.set_file(@file) # Write the DICOM signature: write_signature if options[:signature] write_data_elements(children) # As file has been written successfully, it can be closed. @file.close # Mark this write session as successful: @write_success = true end end
ruby
{ "resource": "" }
q22396
DICOM.Elemental.stream
train
def stream if top_parent.is_a?(DObject) return top_parent.stream else return Stream.new(nil, file_endian=false) end end
ruby
{ "resource": "" }
q22397
DICOM.DLibrary.add_element
train
def add_element(element) raise ArgumentError, "Invalid argument 'element'. Expected DictionaryElement, got #{element.class}" unless element.is_a?(DictionaryElement) # We store the elements in a hash with tag as key and the element instance as value: @elements[element.tag] = element # Populate the method conversion hashes with element data: method = element.name.to_element_method @methods_from_names[element.name] = method @names_from_methods[method] = element.name end
ruby
{ "resource": "" }
q22398
DICOM.DLibrary.add_element_dictionary
train
def add_element_dictionary(file) File.open(file, :encoding => 'utf-8').each do |record| fields = record.split("\t") add_element(DictionaryElement.new(fields[0], fields[1], fields[2].split(","), fields[3].rstrip, fields[4].rstrip)) end end
ruby
{ "resource": "" }
q22399
DICOM.DLibrary.add_uid_dictionary
train
def add_uid_dictionary(file) File.open(file, :encoding => 'utf-8').each do |record| fields = record.split("\t") add_uid(UID.new(fields[0], fields[1], fields[2].rstrip, fields[3].rstrip)) end end
ruby
{ "resource": "" }