id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
22,200
ckruse/CFPropertyList
lib/cfpropertylist/rbBinaryCFPropertyList.rb
CFPropertyList.Binary.read_binary_string
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
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
[ "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" ]
Read a binary string value
[ "Read", "a", "binary", "string", "value" ]
fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134
https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L208-L212
22,201
ckruse/CFPropertyList
lib/cfpropertylist/rbBinaryCFPropertyList.rb
CFPropertyList.Binary.read_binary_unicode_string
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_table.has_key?(buff) CFString.new(Binary.charset_convert(buff,"UTF-16BE","UTF-8")) end
ruby
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_table.has_key?(buff) CFString.new(Binary.charset_convert(buff,"UTF-16BE","UTF-8")) end
[ "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_table", ".", "has_key?", "(", "buff", ")", "CFString", ".", "new", "(", "Binary", ".", "charset_convert", "(", "buff", ",", "\"UTF-16BE\"", ",", "\"UTF-8\"", ")", ")", "end" ]
Read a unicode string value, coded as UTF-16BE
[ "Read", "a", "unicode", "string", "value", "coded", "as", "UTF", "-", "16BE" ]
fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134
https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L245-L253
22,202
ckruse/CFPropertyList
lib/cfpropertylist/rbBinaryCFPropertyList.rb
CFPropertyList.Binary.read_binary_array
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) do |i| object = read_binary_object_at(fname,fd,objects[i]) ary.push object end end CFArray.new(ary) end
ruby
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) do |i| object = read_binary_object_at(fname,fd,objects[i]) ary.push object end end CFArray.new(ary) end
[ "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", ")", "do", "|", "i", "|", "object", "=", "read_binary_object_at", "(", "fname", ",", "fd", ",", "objects", "[", "i", "]", ")", "ary", ".", "push", "object", "end", "end", "CFArray", ".", "new", "(", "ary", ")", "end" ]
Read an binary array value, including contained objects
[ "Read", "an", "binary", "array", "value", "including", "contained", "objects" ]
fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134
https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L267-L283
22,203
ckruse/CFPropertyList
lib/cfpropertylist/rbBinaryCFPropertyList.rb
CFPropertyList.Binary.read_binary_dict
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 = unpack_with_size(@object_ref_size, buff) # read real keys and objects 0.upto(length-1) do |i| key = read_binary_object_at(fname,fd,keys[i]) object = read_binary_object_at(fname,fd,objects[i]) dict[key.value] = object end end CFDictionary.new(dict) end
ruby
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 = unpack_with_size(@object_ref_size, buff) # read real keys and objects 0.upto(length-1) do |i| key = read_binary_object_at(fname,fd,keys[i]) object = read_binary_object_at(fname,fd,objects[i]) dict[key.value] = object end end CFDictionary.new(dict) end
[ "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", "=", "unpack_with_size", "(", "@object_ref_size", ",", "buff", ")", "# read real keys and objects", "0", ".", "upto", "(", "length", "-", "1", ")", "do", "|", "i", "|", "key", "=", "read_binary_object_at", "(", "fname", ",", "fd", ",", "keys", "[", "i", "]", ")", "object", "=", "read_binary_object_at", "(", "fname", ",", "fd", ",", "objects", "[", "i", "]", ")", "dict", "[", "key", ".", "value", "]", "=", "object", "end", "end", "CFDictionary", ".", "new", "(", "dict", ")", "end" ]
Read a dictionary value, including contained objects
[ "Read", "a", "dictionary", "value", "including", "contained", "objects" ]
fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134
https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L287-L308
22,204
ckruse/CFPropertyList
lib/cfpropertylist/rbBinaryCFPropertyList.rb
CFPropertyList.Binary.read_binary_object
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_length = read_binary_object(fname,fd) object_length = object_length.value end case object_type when '0' # null, false, true, fillbyte read_binary_null_type(object_length) when '1' # integer read_binary_int(fname,fd,object_length) when '2' # real read_binary_real(fname,fd,object_length) when '3' # date read_binary_date(fname,fd,object_length) when '4' # data read_binary_data(fname,fd,object_length) when '5' # byte string, usually utf8 encoded read_binary_string(fname,fd,object_length) when '6' # unicode string (utf16be) read_binary_unicode_string(fname,fd,object_length) when '8' CFUid.new(read_binary_int(fname, fd, object_length).value) when 'a' # array read_binary_array(fname,fd,object_length) when 'd' # dictionary read_binary_dict(fname,fd,object_length) end end
ruby
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_length = read_binary_object(fname,fd) object_length = object_length.value end case object_type when '0' # null, false, true, fillbyte read_binary_null_type(object_length) when '1' # integer read_binary_int(fname,fd,object_length) when '2' # real read_binary_real(fname,fd,object_length) when '3' # date read_binary_date(fname,fd,object_length) when '4' # data read_binary_data(fname,fd,object_length) when '5' # byte string, usually utf8 encoded read_binary_string(fname,fd,object_length) when '6' # unicode string (utf16be) read_binary_unicode_string(fname,fd,object_length) when '8' CFUid.new(read_binary_int(fname, fd, object_length).value) when 'a' # array read_binary_array(fname,fd,object_length) when 'd' # dictionary read_binary_dict(fname,fd,object_length) end end
[ "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_length", "=", "read_binary_object", "(", "fname", ",", "fd", ")", "object_length", "=", "object_length", ".", "value", "end", "case", "object_type", "when", "'0'", "# null, false, true, fillbyte", "read_binary_null_type", "(", "object_length", ")", "when", "'1'", "# integer", "read_binary_int", "(", "fname", ",", "fd", ",", "object_length", ")", "when", "'2'", "# real", "read_binary_real", "(", "fname", ",", "fd", ",", "object_length", ")", "when", "'3'", "# date", "read_binary_date", "(", "fname", ",", "fd", ",", "object_length", ")", "when", "'4'", "# data", "read_binary_data", "(", "fname", ",", "fd", ",", "object_length", ")", "when", "'5'", "# byte string, usually utf8 encoded", "read_binary_string", "(", "fname", ",", "fd", ",", "object_length", ")", "when", "'6'", "# unicode string (utf16be)", "read_binary_unicode_string", "(", "fname", ",", "fd", ",", "object_length", ")", "when", "'8'", "CFUid", ".", "new", "(", "read_binary_int", "(", "fname", ",", "fd", ",", "object_length", ")", ".", "value", ")", "when", "'a'", "# array", "read_binary_array", "(", "fname", ",", "fd", ",", "object_length", ")", "when", "'d'", "# dictionary", "read_binary_dict", "(", "fname", ",", "fd", ",", "object_length", ")", "end", "end" ]
Read an object type byte, decode it and delegate to the correct reader function
[ "Read", "an", "object", "type", "byte", "decode", "it", "and", "delegate", "to", "the", "correct", "reader", "function" ]
fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134
https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L313-L350
22,205
ckruse/CFPropertyList
lib/cfpropertylist/rbBinaryCFPropertyList.rb
CFPropertyList.Binary.string_to_binary
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.respond_to?("encode") @object_table[@written_object_count] = bdata << val else bdata = Binary.type_bytes(0b0101,val.bytesize) @object_table[@written_object_count] = bdata << val end @written_object_count += 1 @written_object_count - 1 end end
ruby
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.respond_to?("encode") @object_table[@written_object_count] = bdata << val else bdata = Binary.type_bytes(0b0101,val.bytesize) @object_table[@written_object_count] = bdata << val end @written_object_count += 1 @written_object_count - 1 end end
[ "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", ".", "respond_to?", "(", "\"encode\"", ")", "@object_table", "[", "@written_object_count", "]", "=", "bdata", "<<", "val", "else", "bdata", "=", "Binary", ".", "type_bytes", "(", "0b0101", ",", "val", ".", "bytesize", ")", "@object_table", "[", "@written_object_count", "]", "=", "bdata", "<<", "val", "end", "@written_object_count", "+=", "1", "@written_object_count", "-", "1", "end", "end" ]
Uniques and transforms a string value to binary format and adds it to the object table
[ "Uniques", "and", "transforms", "a", "string", "value", "to", "binary", "format", "and", "adds", "it", "to", "the", "object", "table" ]
fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134
https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L450-L468
22,206
ckruse/CFPropertyList
lib/cfpropertylist/rbBinaryCFPropertyList.rb
CFPropertyList.Binary.int_to_binary
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 += 1 if value > 0x7FFFFFFFFFFFFFFF # 8 byte unsigned integer, stored in lower half of 16 bytes nbytes = 3 if value < 0 # signed integers always stored in 8 bytes Binary.type_bytes(0b0001, nbytes) << if nbytes < 4 [value].pack(["C", "n", "N", "q>"][nbytes]) else # nbytes == 4 [0,value].pack("Q>Q>") end end
ruby
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 += 1 if value > 0x7FFFFFFFFFFFFFFF # 8 byte unsigned integer, stored in lower half of 16 bytes nbytes = 3 if value < 0 # signed integers always stored in 8 bytes Binary.type_bytes(0b0001, nbytes) << if nbytes < 4 [value].pack(["C", "n", "N", "q>"][nbytes]) else # nbytes == 4 [0,value].pack("Q>Q>") end end
[ "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", "+=", "1", "if", "value", ">", "0x7FFFFFFFFFFFFFFF", "# 8 byte unsigned integer, stored in lower half of 16 bytes", "nbytes", "=", "3", "if", "value", "<", "0", "# signed integers always stored in 8 bytes", "Binary", ".", "type_bytes", "(", "0b0001", ",", "nbytes", ")", "<<", "if", "nbytes", "<", "4", "[", "value", "]", ".", "pack", "(", "[", "\"C\"", ",", "\"n\"", ",", "\"N\"", ",", "\"q>\"", "]", "[", "nbytes", "]", ")", "else", "# nbytes == 4", "[", "0", ",", "value", "]", ".", "pack", "(", "\"Q>Q>\"", ")", "end", "end" ]
Codes an integer to binary format
[ "Codes", "an", "integer", "to", "binary", "format" ]
fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134
https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L471-L486
22,207
ckruse/CFPropertyList
lib/cfpropertylist/rbBinaryCFPropertyList.rb
CFPropertyList.Binary.num_to_binary
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
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
[ "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" ]
Converts a numeric value to binary and adds it to the object table
[ "Converts", "a", "numeric", "value", "to", "binary", "and", "adds", "it", "to", "the", "object", "table" ]
fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134
https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L494-L504
22,208
ckruse/CFPropertyList
lib/cfpropertylist/rbBinaryCFPropertyList.rb
CFPropertyList.Binary.array_to_binary
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(@object_refs), values) @object_table[saved_object_count] = bdata saved_object_count end
ruby
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(@object_refs), values) @object_table[saved_object_count] = bdata saved_object_count end
[ "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", "(", "@object_refs", ")", ",", "values", ")", "@object_table", "[", "saved_object_count", "]", "=", "bdata", "saved_object_count", "end" ]
Convert array to binary format and add it to the object table
[ "Convert", "array", "to", "binary", "format", "and", "add", "it", "to", "the", "object", "table" ]
fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134
https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L561-L573
22,209
ckruse/CFPropertyList
lib/cfpropertylist/rbBinaryCFPropertyList.rb
CFPropertyList.Binary.dict_to_binary
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) }) bdata = Binary.type_bytes(0b1101,val.value.size) << Binary.pack_int_array_with_size(object_ref_size(@object_refs), keys_and_values) @object_table[saved_object_count] = bdata return saved_object_count end
ruby
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) }) bdata = Binary.type_bytes(0b1101,val.value.size) << Binary.pack_int_array_with_size(object_ref_size(@object_refs), keys_and_values) @object_table[saved_object_count] = bdata return saved_object_count end
[ "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", ")", "}", ")", "bdata", "=", "Binary", ".", "type_bytes", "(", "0b1101", ",", "val", ".", "value", ".", "size", ")", "<<", "Binary", ".", "pack_int_array_with_size", "(", "object_ref_size", "(", "@object_refs", ")", ",", "keys_and_values", ")", "@object_table", "[", "saved_object_count", "]", "=", "bdata", "return", "saved_object_count", "end" ]
Convert dictionary to binary format and add it to the object table
[ "Convert", "dictionary", "to", "binary", "format", "and", "add", "it", "to", "the", "object", "table" ]
fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134
https://github.com/ckruse/CFPropertyList/blob/fa05fa4d0078a61c7b67f3ed5e50a3ca223e2134/lib/cfpropertylist/rbBinaryCFPropertyList.rb#L576-L590
22,210
qoobaa/s3
lib/s3/connection.rb
S3.Connection.request
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-slash (/) and explicitly legal URL characters path = Addressable::URI.escape(path) if params params = params.is_a?(String) ? params : self.class.parse_params(params) path << "?#{params}" end request = Request.new(@chunk_size, method.to_s.upcase, !!body, method.to_s.upcase != "HEAD", path) headers = self.class.parse_headers(headers) headers.each do |key, value| request[key] = value end if body if body.respond_to?(:read) request.body_stream = body else request.body = body end request.content_length = body.respond_to?(:lstat) ? body.stat.size : body.size end send_request(host, request) end
ruby
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-slash (/) and explicitly legal URL characters path = Addressable::URI.escape(path) if params params = params.is_a?(String) ? params : self.class.parse_params(params) path << "?#{params}" end request = Request.new(@chunk_size, method.to_s.upcase, !!body, method.to_s.upcase != "HEAD", path) headers = self.class.parse_headers(headers) headers.each do |key, value| request[key] = value end if body if body.respond_to?(:read) request.body_stream = body else request.body = body end request.content_length = body.respond_to?(:lstat) ? body.stat.size : body.size end send_request(host, request) end
[ "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-slash (/) and explicitly legal URL characters", "path", "=", "Addressable", "::", "URI", ".", "escape", "(", "path", ")", "if", "params", "params", "=", "params", ".", "is_a?", "(", "String", ")", "?", "params", ":", "self", ".", "class", ".", "parse_params", "(", "params", ")", "path", "<<", "\"?#{params}\"", "end", "request", "=", "Request", ".", "new", "(", "@chunk_size", ",", "method", ".", "to_s", ".", "upcase", ",", "!", "!", "body", ",", "method", ".", "to_s", ".", "upcase", "!=", "\"HEAD\"", ",", "path", ")", "headers", "=", "self", ".", "class", ".", "parse_headers", "(", "headers", ")", "headers", ".", "each", "do", "|", "key", ",", "value", "|", "request", "[", "key", "]", "=", "value", "end", "if", "body", "if", "body", ".", "respond_to?", "(", ":read", ")", "request", ".", "body_stream", "=", "body", "else", "request", ".", "body", "=", "body", "end", "request", ".", "content_length", "=", "body", ".", "respond_to?", "(", ":lstat", ")", "?", "body", ".", "stat", ".", "size", ":", "body", ".", "size", "end", "send_request", "(", "host", ",", "request", ")", "end" ]
Creates new connection object. ==== Options * <tt>:access_key_id</tt> - Access key id (REQUIRED) * <tt>:secret_access_key</tt> - Secret access key (REQUIRED) * <tt>:use_ssl</tt> - Use https or http protocol (false by default) * <tt>:debug</tt> - Display debug information on the STDOUT (false by default) * <tt>:timeout</tt> - Timeout to use by the Net::HTTP object (60 by default) * <tt>:proxy</tt> - Hash for Net::HTTP Proxy settings { :host => "proxy.mydomain.com", :port => "80, :user => "user_a", :password => "secret" } * <tt>:chunk_size</tt> - Size of a chunk when streaming (1048576 (1 MiB) by default) Makes request with given HTTP method, sets missing parameters, adds signature to request header and returns response object (Net::HTTPResponse) ==== Parameters * <tt>method</tt> - HTTP Method symbol, can be <tt>:get</tt>, <tt>:put</tt>, <tt>:delete</tt> ==== Options: * <tt>:host</tt> - Hostname to connecto to, defaults to <tt>s3.amazonaws.com</tt> * <tt>:path</tt> - path to send request to (REQUIRED) * <tt>:body</tt> - Request body, only meaningful for <tt>:put</tt> request * <tt>:params</tt> - Parameters to add to query string for request, can be String or Hash * <tt>:headers</tt> - Hash of headers fields to add to request header ==== Returns Net::HTTPResponse object -- response from the server
[ "Creates", "new", "connection", "object", "." ]
2c1960a0b012f6ad1c9d1e5baf49c4148b5472fa
https://github.com/qoobaa/s3/blob/2c1960a0b012f6ad1c9d1e5baf49c4148b5472fa/lib/s3/connection.rb#L56-L89
22,211
qoobaa/s3
lib/s3/parser.rb
S3.Parser.parse_acl
def parse_acl(xml) grants = {} rexml_document(xml).elements.each("AccessControlPolicy/AccessControlList/Grant") do |grant| grants.merge!(extract_grantee(grant)) end grants end
ruby
def parse_acl(xml) grants = {} rexml_document(xml).elements.each("AccessControlPolicy/AccessControlList/Grant") do |grant| grants.merge!(extract_grantee(grant)) end grants end
[ "def", "parse_acl", "(", "xml", ")", "grants", "=", "{", "}", "rexml_document", "(", "xml", ")", ".", "elements", ".", "each", "(", "\"AccessControlPolicy/AccessControlList/Grant\"", ")", "do", "|", "grant", "|", "grants", ".", "merge!", "(", "extract_grantee", "(", "grant", ")", ")", "end", "grants", "end" ]
Parse acl response and return hash with grantee and their permissions
[ "Parse", "acl", "response", "and", "return", "hash", "with", "grantee", "and", "their", "permissions" ]
2c1960a0b012f6ad1c9d1e5baf49c4148b5472fa
https://github.com/qoobaa/s3/blob/2c1960a0b012f6ad1c9d1e5baf49c4148b5472fa/lib/s3/parser.rb#L54-L60
22,212
qoobaa/s3
lib/s3/object.rb
S3.Object.temporary_url
def temporary_url(expires_at = Time.now + 3600) signature = Signature.generate_temporary_url_signature(:bucket => name, :resource => key, :expires_at => expires_at, :secret_access_key => secret_access_key) "#{url}?AWSAccessKeyId=#{self.bucket.service.access_key_id}&Expires=#{expires_at.to_i.to_s}&Signature=#{signature}" end
ruby
def temporary_url(expires_at = Time.now + 3600) signature = Signature.generate_temporary_url_signature(:bucket => name, :resource => key, :expires_at => expires_at, :secret_access_key => secret_access_key) "#{url}?AWSAccessKeyId=#{self.bucket.service.access_key_id}&Expires=#{expires_at.to_i.to_s}&Signature=#{signature}" end
[ "def", "temporary_url", "(", "expires_at", "=", "Time", ".", "now", "+", "3600", ")", "signature", "=", "Signature", ".", "generate_temporary_url_signature", "(", ":bucket", "=>", "name", ",", ":resource", "=>", "key", ",", ":expires_at", "=>", "expires_at", ",", ":secret_access_key", "=>", "secret_access_key", ")", "\"#{url}?AWSAccessKeyId=#{self.bucket.service.access_key_id}&Expires=#{expires_at.to_i.to_s}&Signature=#{signature}\"", "end" ]
Returns a temporary url to the object that expires on the timestamp given. Defaults to one hour expire time.
[ "Returns", "a", "temporary", "url", "to", "the", "object", "that", "expires", "on", "the", "timestamp", "given", ".", "Defaults", "to", "one", "hour", "expire", "time", "." ]
2c1960a0b012f6ad1c9d1e5baf49c4148b5472fa
https://github.com/qoobaa/s3/blob/2c1960a0b012f6ad1c9d1e5baf49c4148b5472fa/lib/s3/object.rb#L126-L133
22,213
qoobaa/s3
lib/s3/bucket.rb
S3.Bucket.save
def save(options = {}) options = {:location => options} unless options.is_a?(Hash) create_bucket_configuration(options) true end
ruby
def save(options = {}) options = {:location => options} unless options.is_a?(Hash) create_bucket_configuration(options) true end
[ "def", "save", "(", "options", "=", "{", "}", ")", "options", "=", "{", ":location", "=>", "options", "}", "unless", "options", ".", "is_a?", "(", "Hash", ")", "create_bucket_configuration", "(", "options", ")", "true", "end" ]
Saves the newly built bucket. ==== Options * <tt>:location</tt> - location of the bucket (<tt>:eu</tt> or <tt>us</tt>) * Any other options are passed through to Connection#request
[ "Saves", "the", "newly", "built", "bucket", "." ]
2c1960a0b012f6ad1c9d1e5baf49c4148b5472fa
https://github.com/qoobaa/s3/blob/2c1960a0b012f6ad1c9d1e5baf49c4148b5472fa/lib/s3/bucket.rb#L85-L89
22,214
AtelierConvivialite/webtranslateit
lib/web_translate_it/string.rb
WebTranslateIt.String.translation_for
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/#{locale}/translations.yaml") WebTranslateIt::Util.add_fields(request) begin response = Util.handle_response(Connection.http_connection.request(request), true, true) hash = YAML.load(response) return nil if hash.empty? translation = WebTranslateIt::Translation.new(hash) return translation rescue Timeout::Error puts "Request timeout. Will retry in 5 seconds." if (tries -= 1) > 0 sleep(5) retry else success = false end end success end
ruby
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/#{locale}/translations.yaml") WebTranslateIt::Util.add_fields(request) begin response = Util.handle_response(Connection.http_connection.request(request), true, true) hash = YAML.load(response) return nil if hash.empty? translation = WebTranslateIt::Translation.new(hash) return translation rescue Timeout::Error puts "Request timeout. Will retry in 5 seconds." if (tries -= 1) > 0 sleep(5) retry else success = false end end success end
[ "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/#{locale}/translations.yaml\"", ")", "WebTranslateIt", "::", "Util", ".", "add_fields", "(", "request", ")", "begin", "response", "=", "Util", ".", "handle_response", "(", "Connection", ".", "http_connection", ".", "request", "(", "request", ")", ",", "true", ",", "true", ")", "hash", "=", "YAML", ".", "load", "(", "response", ")", "return", "nil", "if", "hash", ".", "empty?", "translation", "=", "WebTranslateIt", "::", "Translation", ".", "new", "(", "hash", ")", "return", "translation", "rescue", "Timeout", "::", "Error", "puts", "\"Request timeout. Will retry in 5 seconds.\"", "if", "(", "tries", "-=", "1", ")", ">", "0", "sleep", "(", "5", ")", "retry", "else", "success", "=", "false", "end", "end", "success", "end" ]
Gets a Translation for a String Implementation Example: WebTranslateIt::Connection.new('secret_api_token') do string = WebTranslateIt::String.find(1234) puts string.translation_for("fr") #=> A Translation object end
[ "Gets", "a", "Translation", "for", "a", "String" ]
6dcae8eec5386dbb8047c2518971aa461d9b3456
https://github.com/AtelierConvivialite/webtranslateit/blob/6dcae8eec5386dbb8047c2518971aa461d9b3456/lib/web_translate_it/string.rb#L183-L208
22,215
AtelierConvivialite/webtranslateit
lib/web_translate_it/translation_file.rb
WebTranslateIt.TranslationFile.fetch
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.remote_checksum != self.local_checksum begin request = Net::HTTP::Get.new(api_url) WebTranslateIt::Util.add_fields(request) FileUtils.mkpath(self.file_path.split('/')[0..-2].join('/')) unless File.exist?(self.file_path) or self.file_path.split('/')[0..-2].join('/') == "" begin response = http_connection.request(request) File.open(self.file_path, 'wb'){ |file| file << response.body } if response.code.to_i == 200 display.push Util.handle_response(response) rescue Timeout::Error puts StringUtil.failure("Request timeout. Will retry in 5 seconds.") if (tries -= 1) > 0 sleep(5) retry else success = false end rescue display.push StringUtil.failure("An error occured: #{$!}") success = false end end else display.push StringUtil.success("Skipped") end print ArrayUtil.to_columns(display) return success end
ruby
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.remote_checksum != self.local_checksum begin request = Net::HTTP::Get.new(api_url) WebTranslateIt::Util.add_fields(request) FileUtils.mkpath(self.file_path.split('/')[0..-2].join('/')) unless File.exist?(self.file_path) or self.file_path.split('/')[0..-2].join('/') == "" begin response = http_connection.request(request) File.open(self.file_path, 'wb'){ |file| file << response.body } if response.code.to_i == 200 display.push Util.handle_response(response) rescue Timeout::Error puts StringUtil.failure("Request timeout. Will retry in 5 seconds.") if (tries -= 1) > 0 sleep(5) retry else success = false end rescue display.push StringUtil.failure("An error occured: #{$!}") success = false end end else display.push StringUtil.success("Skipped") end print ArrayUtil.to_columns(display) return success end
[ "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", ".", "remote_checksum", "!=", "self", ".", "local_checksum", "begin", "request", "=", "Net", "::", "HTTP", "::", "Get", ".", "new", "(", "api_url", ")", "WebTranslateIt", "::", "Util", ".", "add_fields", "(", "request", ")", "FileUtils", ".", "mkpath", "(", "self", ".", "file_path", ".", "split", "(", "'/'", ")", "[", "0", "..", "-", "2", "]", ".", "join", "(", "'/'", ")", ")", "unless", "File", ".", "exist?", "(", "self", ".", "file_path", ")", "or", "self", ".", "file_path", ".", "split", "(", "'/'", ")", "[", "0", "..", "-", "2", "]", ".", "join", "(", "'/'", ")", "==", "\"\"", "begin", "response", "=", "http_connection", ".", "request", "(", "request", ")", "File", ".", "open", "(", "self", ".", "file_path", ",", "'wb'", ")", "{", "|", "file", "|", "file", "<<", "response", ".", "body", "}", "if", "response", ".", "code", ".", "to_i", "==", "200", "display", ".", "push", "Util", ".", "handle_response", "(", "response", ")", "rescue", "Timeout", "::", "Error", "puts", "StringUtil", ".", "failure", "(", "\"Request timeout. Will retry in 5 seconds.\"", ")", "if", "(", "tries", "-=", "1", ")", ">", "0", "sleep", "(", "5", ")", "retry", "else", "success", "=", "false", "end", "rescue", "display", ".", "push", "StringUtil", ".", "failure", "(", "\"An error occured: #{$!}\"", ")", "success", "=", "false", "end", "end", "else", "display", ".", "push", "StringUtil", ".", "success", "(", "\"Skipped\"", ")", "end", "print", "ArrayUtil", ".", "to_columns", "(", "display", ")", "return", "success", "end" ]
Fetch a language file. By default it will make a conditional GET Request, using the `If-Modified-Since` tag. You can force the method to re-download your file by passing `true` as a second argument Example of implementation: configuration = WebTranslateIt::Configuration.new file = configuration.files.first file.fetch # the first time, will return the content of the language file with a status 200 OK file.fetch # returns nothing, with a status 304 Not Modified file.fetch(true) # force to re-download the file, will return the content of the file with a 200 OK
[ "Fetch", "a", "language", "file", ".", "By", "default", "it", "will", "make", "a", "conditional", "GET", "Request", "using", "the", "If", "-", "Modified", "-", "Since", "tag", ".", "You", "can", "force", "the", "method", "to", "re", "-", "download", "your", "file", "by", "passing", "true", "as", "a", "second", "argument" ]
6dcae8eec5386dbb8047c2518971aa461d9b3456
https://github.com/AtelierConvivialite/webtranslateit/blob/6dcae8eec5386dbb8047c2518971aa461d9b3456/lib/web_translate_it/translation_file.rb#L39-L72
22,216
AtelierConvivialite/webtranslateit
lib/web_translate_it/translation_file.rb
WebTranslateIt.TranslationFile.upload
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(self.remote_checksum.to_s)}" if File.exists?(self.file_path) if force or self.remote_checksum != self.local_checksum File.open(self.file_path) do |file| begin request = Net::HTTP::Put::Multipart.new(api_url, {"file" => UploadIO.new(file, "text/plain", file.path), "merge" => merge, "ignore_missing" => ignore_missing, "label" => label, "low_priority" => low_priority, "minor_changes" => minor_changes }) WebTranslateIt::Util.add_fields(request) display.push Util.handle_response(http_connection.request(request)) rescue Timeout::Error puts StringUtil.failure("Request timeout. Will retry in 5 seconds.") if (tries -= 1) > 0 sleep(5) retry else success = false end rescue display.push StringUtil.failure("An error occured: #{$!}") success = false end end else display.push StringUtil.success("Skipped") end puts ArrayUtil.to_columns(display) else puts StringUtil.failure("Can't push #{self.file_path}. File doesn't exist.") end return success end
ruby
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(self.remote_checksum.to_s)}" if File.exists?(self.file_path) if force or self.remote_checksum != self.local_checksum File.open(self.file_path) do |file| begin request = Net::HTTP::Put::Multipart.new(api_url, {"file" => UploadIO.new(file, "text/plain", file.path), "merge" => merge, "ignore_missing" => ignore_missing, "label" => label, "low_priority" => low_priority, "minor_changes" => minor_changes }) WebTranslateIt::Util.add_fields(request) display.push Util.handle_response(http_connection.request(request)) rescue Timeout::Error puts StringUtil.failure("Request timeout. Will retry in 5 seconds.") if (tries -= 1) > 0 sleep(5) retry else success = false end rescue display.push StringUtil.failure("An error occured: #{$!}") success = false end end else display.push StringUtil.success("Skipped") end puts ArrayUtil.to_columns(display) else puts StringUtil.failure("Can't push #{self.file_path}. File doesn't exist.") end return success end
[ "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(self.remote_checksum.to_s)}\"", "if", "File", ".", "exists?", "(", "self", ".", "file_path", ")", "if", "force", "or", "self", ".", "remote_checksum", "!=", "self", ".", "local_checksum", "File", ".", "open", "(", "self", ".", "file_path", ")", "do", "|", "file", "|", "begin", "request", "=", "Net", "::", "HTTP", "::", "Put", "::", "Multipart", ".", "new", "(", "api_url", ",", "{", "\"file\"", "=>", "UploadIO", ".", "new", "(", "file", ",", "\"text/plain\"", ",", "file", ".", "path", ")", ",", "\"merge\"", "=>", "merge", ",", "\"ignore_missing\"", "=>", "ignore_missing", ",", "\"label\"", "=>", "label", ",", "\"low_priority\"", "=>", "low_priority", ",", "\"minor_changes\"", "=>", "minor_changes", "}", ")", "WebTranslateIt", "::", "Util", ".", "add_fields", "(", "request", ")", "display", ".", "push", "Util", ".", "handle_response", "(", "http_connection", ".", "request", "(", "request", ")", ")", "rescue", "Timeout", "::", "Error", "puts", "StringUtil", ".", "failure", "(", "\"Request timeout. Will retry in 5 seconds.\"", ")", "if", "(", "tries", "-=", "1", ")", ">", "0", "sleep", "(", "5", ")", "retry", "else", "success", "=", "false", "end", "rescue", "display", ".", "push", "StringUtil", ".", "failure", "(", "\"An error occured: #{$!}\"", ")", "success", "=", "false", "end", "end", "else", "display", ".", "push", "StringUtil", ".", "success", "(", "\"Skipped\"", ")", "end", "puts", "ArrayUtil", ".", "to_columns", "(", "display", ")", "else", "puts", "StringUtil", ".", "failure", "(", "\"Can't push #{self.file_path}. File doesn't exist.\"", ")", "end", "return", "success", "end" ]
Update a language file to Web Translate It by performing a PUT Request. Example of implementation: configuration = WebTranslateIt::Configuration.new locale = configuration.locales.first file = configuration.files.first file.upload # should respond the HTTP code 202 Accepted Note that the request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. This is due to the fact that language file imports are handled by background processing.
[ "Update", "a", "language", "file", "to", "Web", "Translate", "It", "by", "performing", "a", "PUT", "Request", "." ]
6dcae8eec5386dbb8047c2518971aa461d9b3456
https://github.com/AtelierConvivialite/webtranslateit/blob/6dcae8eec5386dbb8047c2518971aa461d9b3456/lib/web_translate_it/translation_file.rb#L85-L119
22,217
AtelierConvivialite/webtranslateit
lib/web_translate_it/translation_file.rb
WebTranslateIt.TranslationFile.create
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 request = Net::HTTP::Post::Multipart.new(api_url_for_create, { "name" => self.file_path, "file" => UploadIO.new(file, "text/plain", file.path), "low_priority" => low_priority }) WebTranslateIt::Util.add_fields(request) display.push Util.handle_response(http_connection.request(request)) puts ArrayUtil.to_columns(display) rescue Timeout::Error puts StringUtil.failure("Request timeout. Will retry in 5 seconds.") if (tries -= 1) > 0 sleep(5) retry else success = false end rescue display.push StringUtil.failure("An error occured: #{$!}") success = false end end else puts StringUtil.failure("\nFile #{self.file_path} doesn't exist!") end return success end
ruby
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 request = Net::HTTP::Post::Multipart.new(api_url_for_create, { "name" => self.file_path, "file" => UploadIO.new(file, "text/plain", file.path), "low_priority" => low_priority }) WebTranslateIt::Util.add_fields(request) display.push Util.handle_response(http_connection.request(request)) puts ArrayUtil.to_columns(display) rescue Timeout::Error puts StringUtil.failure("Request timeout. Will retry in 5 seconds.") if (tries -= 1) > 0 sleep(5) retry else success = false end rescue display.push StringUtil.failure("An error occured: #{$!}") success = false end end else puts StringUtil.failure("\nFile #{self.file_path} doesn't exist!") end return success end
[ "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", "request", "=", "Net", "::", "HTTP", "::", "Post", "::", "Multipart", ".", "new", "(", "api_url_for_create", ",", "{", "\"name\"", "=>", "self", ".", "file_path", ",", "\"file\"", "=>", "UploadIO", ".", "new", "(", "file", ",", "\"text/plain\"", ",", "file", ".", "path", ")", ",", "\"low_priority\"", "=>", "low_priority", "}", ")", "WebTranslateIt", "::", "Util", ".", "add_fields", "(", "request", ")", "display", ".", "push", "Util", ".", "handle_response", "(", "http_connection", ".", "request", "(", "request", ")", ")", "puts", "ArrayUtil", ".", "to_columns", "(", "display", ")", "rescue", "Timeout", "::", "Error", "puts", "StringUtil", ".", "failure", "(", "\"Request timeout. Will retry in 5 seconds.\"", ")", "if", "(", "tries", "-=", "1", ")", ">", "0", "sleep", "(", "5", ")", "retry", "else", "success", "=", "false", "end", "rescue", "display", ".", "push", "StringUtil", ".", "failure", "(", "\"An error occured: #{$!}\"", ")", "success", "=", "false", "end", "end", "else", "puts", "StringUtil", ".", "failure", "(", "\"\\nFile #{self.file_path} doesn't exist!\"", ")", "end", "return", "success", "end" ]
Create a master language file to Web Translate It by performing a POST Request. Example of implementation: configuration = WebTranslateIt::Configuration.new file = TranslationFile.new(nil, file_path, nil, configuration.api_key) file.create # should respond the HTTP code 201 Created Note that the request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. This is due to the fact that language file imports are handled by background processing.
[ "Create", "a", "master", "language", "file", "to", "Web", "Translate", "It", "by", "performing", "a", "POST", "Request", "." ]
6dcae8eec5386dbb8047c2518971aa461d9b3456
https://github.com/AtelierConvivialite/webtranslateit/blob/6dcae8eec5386dbb8047c2518971aa461d9b3456/lib/web_translate_it/translation_file.rb#L132-L162
22,218
AtelierConvivialite/webtranslateit
lib/web_translate_it/translation_file.rb
WebTranslateIt.TranslationFile.delete
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(request) display.push Util.handle_response(http_connection.request(request)) puts ArrayUtil.to_columns(display) rescue Timeout::Error puts StringUtil.failure("Request timeout. Will retry in 5 seconds.") if (tries -= 1) > 0 sleep(5) retry else success = false end rescue display.push StringUtil.failure("An error occured: #{$!}") success = false end end else puts StringUtil.failure("\nFile #{self.file_path} doesn't exist!") end return success end
ruby
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(request) display.push Util.handle_response(http_connection.request(request)) puts ArrayUtil.to_columns(display) rescue Timeout::Error puts StringUtil.failure("Request timeout. Will retry in 5 seconds.") if (tries -= 1) > 0 sleep(5) retry else success = false end rescue display.push StringUtil.failure("An error occured: #{$!}") success = false end end else puts StringUtil.failure("\nFile #{self.file_path} doesn't exist!") end return success end
[ "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", "(", "request", ")", "display", ".", "push", "Util", ".", "handle_response", "(", "http_connection", ".", "request", "(", "request", ")", ")", "puts", "ArrayUtil", ".", "to_columns", "(", "display", ")", "rescue", "Timeout", "::", "Error", "puts", "StringUtil", ".", "failure", "(", "\"Request timeout. Will retry in 5 seconds.\"", ")", "if", "(", "tries", "-=", "1", ")", ">", "0", "sleep", "(", "5", ")", "retry", "else", "success", "=", "false", "end", "rescue", "display", ".", "push", "StringUtil", ".", "failure", "(", "\"An error occured: #{$!}\"", ")", "success", "=", "false", "end", "end", "else", "puts", "StringUtil", ".", "failure", "(", "\"\\nFile #{self.file_path} doesn't exist!\"", ")", "end", "return", "success", "end" ]
Delete a master language file from Web Translate It by performing a DELETE Request.
[ "Delete", "a", "master", "language", "file", "from", "Web", "Translate", "It", "by", "performing", "a", "DELETE", "Request", "." ]
6dcae8eec5386dbb8047c2518971aa461d9b3456
https://github.com/AtelierConvivialite/webtranslateit/blob/6dcae8eec5386dbb8047c2518971aa461d9b3456/lib/web_translate_it/translation_file.rb#L166-L195
22,219
stephenb/sendgrid
lib/sendgrid.rb
SendGrid.ClassMethods.sendgrid_enable
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
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
[ "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" ]
Enables a default option for all emails. See documentation for details. Supported options: * :opentrack * :clicktrack * :ganalytics * :gravatar * :subscriptiontrack * :footer * :spamcheck
[ "Enables", "a", "default", "option", "for", "all", "emails", ".", "See", "documentation", "for", "details", "." ]
8b718643d02ba1cd957b8a7835dd9d75c3681ac7
https://github.com/stephenb/sendgrid/blob/8b718643d02ba1cd957b8a7835dd9d75c3681ac7/lib/sendgrid.rb#L66-L69
22,220
ruby-concurrency/thread_safe
lib/thread_safe/atomic_reference_cache_backend.rb
ThreadSafe.AtomicReferenceCacheBackend.clear
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 current_table_size = current_table.size elsif Node.locked_hash?(node_hash) decrement_size(deleted_count) # opportunistically update count deleted_count = 0 node.try_await_lock(current_table, i) else current_table.try_lock_via_hash(i, node, node_hash) do begin deleted_count += 1 if NULL != node.value # recheck under lock node.value = nil end while node = node.next current_table.volatile_set(i, nil) i += 1 end end end decrement_size(deleted_count) self end
ruby
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 current_table_size = current_table.size elsif Node.locked_hash?(node_hash) decrement_size(deleted_count) # opportunistically update count deleted_count = 0 node.try_await_lock(current_table, i) else current_table.try_lock_via_hash(i, node, node_hash) do begin deleted_count += 1 if NULL != node.value # recheck under lock node.value = nil end while node = node.next current_table.volatile_set(i, nil) i += 1 end end end decrement_size(deleted_count) self end
[ "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", "current_table_size", "=", "current_table", ".", "size", "elsif", "Node", ".", "locked_hash?", "(", "node_hash", ")", "decrement_size", "(", "deleted_count", ")", "# opportunistically update count", "deleted_count", "=", "0", "node", ".", "try_await_lock", "(", "current_table", ",", "i", ")", "else", "current_table", ".", "try_lock_via_hash", "(", "i", ",", "node", ",", "node_hash", ")", "do", "begin", "deleted_count", "+=", "1", "if", "NULL", "!=", "node", ".", "value", "# recheck under lock", "node", ".", "value", "=", "nil", "end", "while", "node", "=", "node", ".", "next", "current_table", ".", "volatile_set", "(", "i", ",", "nil", ")", "i", "+=", "1", "end", "end", "end", "decrement_size", "(", "deleted_count", ")", "self", "end" ]
Implementation for clear. Steps through each bin, removing all nodes.
[ "Implementation", "for", "clear", ".", "Steps", "through", "each", "bin", "removing", "all", "nodes", "." ]
39fc4a490c7ed881657ea49cd37d293de13b6d4e
https://github.com/ruby-concurrency/thread_safe/blob/39fc4a490c7ed881657ea49cd37d293de13b6d4e/lib/thread_safe/atomic_reference_cache_backend.rb#L529-L556
22,221
ruby-concurrency/thread_safe
lib/thread_safe/atomic_reference_cache_backend.rb
ThreadSafe.AtomicReferenceCacheBackend.initialize_table
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 current_table = self.table = Table.new(initial_size) initial_size - (initial_size >> 2) # 75% load factor end end end current_table end
ruby
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 current_table = self.table = Table.new(initial_size) initial_size - (initial_size >> 2) # 75% load factor end end end current_table end
[ "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", "current_table", "=", "self", ".", "table", "=", "Table", ".", "new", "(", "initial_size", ")", "initial_size", "-", "(", "initial_size", ">>", "2", ")", "# 75% load factor", "end", "end", "end", "current_table", "end" ]
Initializes table, using the size recorded in +size_control+.
[ "Initializes", "table", "using", "the", "size", "recorded", "in", "+", "size_control", "+", "." ]
39fc4a490c7ed881657ea49cd37d293de13b6d4e
https://github.com/ruby-concurrency/thread_safe/blob/39fc4a490c7ed881657ea49cd37d293de13b6d4e/lib/thread_safe/atomic_reference_cache_backend.rb#L761-L774
22,222
ruby-concurrency/thread_safe
lib/thread_safe/atomic_reference_cache_backend.rb
ThreadSafe.AtomicReferenceCacheBackend.check_for_resize
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) - (table_size >> 1) # 75% load factor end end end
ruby
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) - (table_size >> 1) # 75% load factor end end end
[ "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", ")", "-", "(", "table_size", ">>", "1", ")", "# 75% load factor", "end", "end", "end" ]
If table is too small and not already resizing, creates next table and transfers bins. Rechecks occupancy after a transfer to see if another resize is already needed because resizings are lagging additions.
[ "If", "table", "is", "too", "small", "and", "not", "already", "resizing", "creates", "next", "table", "and", "transfers", "bins", ".", "Rechecks", "occupancy", "after", "a", "transfer", "to", "see", "if", "another", "resize", "is", "already", "needed", "because", "resizings", "are", "lagging", "additions", "." ]
39fc4a490c7ed881657ea49cd37d293de13b6d4e
https://github.com/ruby-concurrency/thread_safe/blob/39fc4a490c7ed881657ea49cd37d293de13b6d4e/lib/thread_safe/atomic_reference_cache_backend.rb#L779-L786
22,223
ruby-concurrency/thread_safe
lib/thread_safe/atomic_reference_cache_backend.rb
ThreadSafe.AtomicReferenceCacheBackend.split_old_bin
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
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
[ "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" ]
Splits a normal bin with list headed by e into lo and hi parts; installs in given table.
[ "Splits", "a", "normal", "bin", "with", "list", "headed", "by", "e", "into", "lo", "and", "hi", "parts", ";", "installs", "in", "given", "table", "." ]
39fc4a490c7ed881657ea49cd37d293de13b6d4e
https://github.com/ruby-concurrency/thread_safe/blob/39fc4a490c7ed881657ea49cd37d293de13b6d4e/lib/thread_safe/atomic_reference_cache_backend.rb#L860-L865
22,224
knife-block/knife-block
lib/chef/knife/block.rb
GreenAndSecure.BlockList.run
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
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
[ "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" ]
list the available environments
[ "list", "the", "available", "environments" ]
9ee7f991c7f8400b608e65f6dffa0bd4cf1b2524
https://github.com/knife-block/knife-block/blob/9ee7f991c7f8400b608e65f6dffa0bd4cf1b2524/lib/chef/knife/block.rb#L144-L154
22,225
sidoh/alexa_verifier
lib/alexa_verifier/verifier.rb
AlexaVerifier.Verifier.valid?
def valid?(request) begin valid!(request) rescue AlexaVerifier::BaseError => e puts e return false end true end
ruby
def valid?(request) begin valid!(request) rescue AlexaVerifier::BaseError => e puts e return false end true end
[ "def", "valid?", "(", "request", ")", "begin", "valid!", "(", "request", ")", "rescue", "AlexaVerifier", "::", "BaseError", "=>", "e", "puts", "e", "return", "false", "end", "true", "end" ]
Validate a request object from Rack. Return a boolean. @param [Rack::Request::Env] request a Rack HTTP Request @return [Boolean] is the request valid?
[ "Validate", "a", "request", "object", "from", "Rack", ".", "Return", "a", "boolean", "." ]
bfb49d091cfbef661f9b1ff7a858cb5d9d09f473
https://github.com/sidoh/alexa_verifier/blob/bfb49d091cfbef661f9b1ff7a858cb5d9d09f473/lib/alexa_verifier/verifier.rb#L49-L59
22,226
sidoh/alexa_verifier
lib/alexa_verifier/verifier.rb
AlexaVerifier.Verifier.check_that_request_is_timely
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_s) >= (Time.now - REQUEST_THRESHOLD)) raise AlexaVerifier::InvalidRequestError, "Request is from more than #{REQUEST_THRESHOLD} seconds ago" unless request_is_timely end
ruby
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_s) >= (Time.now - REQUEST_THRESHOLD)) raise AlexaVerifier::InvalidRequestError, "Request is from more than #{REQUEST_THRESHOLD} seconds ago" unless request_is_timely end
[ "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_s", ")", ">=", "(", "Time", ".", "now", "-", "REQUEST_THRESHOLD", ")", ")", "raise", "AlexaVerifier", "::", "InvalidRequestError", ",", "\"Request is from more than #{REQUEST_THRESHOLD} seconds ago\"", "unless", "request_is_timely", "end" ]
Prevent replays of requests by checking that they are timely. @param [String] raw_body the raw body of our https request @raise [AlexaVerifier::InvalidRequestError] raised when the timestamp is not timely, or is not set
[ "Prevent", "replays", "of", "requests", "by", "checking", "that", "they", "are", "timely", "." ]
bfb49d091cfbef661f9b1ff7a858cb5d9d09f473
https://github.com/sidoh/alexa_verifier/blob/bfb49d091cfbef661f9b1ff7a858cb5d9d09f473/lib/alexa_verifier/verifier.rb#L80-L87
22,227
sidoh/alexa_verifier
lib/alexa_verifier/verifier.rb
AlexaVerifier.Verifier.check_that_request_is_valid
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!(certificate, chain) if @configuration.verify_certificate? check_that_request_was_signed(certificate.public_key, request, raw_body) if @configuration.verify_signature? rescue AlexaVerifier::InvalidCertificateError, AlexaVerifier::InvalidRequestError => error # We don't want to cache a certificate that fails our checks as it could lock us out of valid requests for the cache length AlexaVerifier::CertificateStore.delete(signature_certificate_url) raise error end end
ruby
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!(certificate, chain) if @configuration.verify_certificate? check_that_request_was_signed(certificate.public_key, request, raw_body) if @configuration.verify_signature? rescue AlexaVerifier::InvalidCertificateError, AlexaVerifier::InvalidRequestError => error # We don't want to cache a certificate that fails our checks as it could lock us out of valid requests for the cache length AlexaVerifier::CertificateStore.delete(signature_certificate_url) raise error end end
[ "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!", "(", "certificate", ",", "chain", ")", "if", "@configuration", ".", "verify_certificate?", "check_that_request_was_signed", "(", "certificate", ".", "public_key", ",", "request", ",", "raw_body", ")", "if", "@configuration", ".", "verify_signature?", "rescue", "AlexaVerifier", "::", "InvalidCertificateError", ",", "AlexaVerifier", "::", "InvalidRequestError", "=>", "error", "# We don't want to cache a certificate that fails our checks as it could lock us out of valid requests for the cache length", "AlexaVerifier", "::", "CertificateStore", ".", "delete", "(", "signature_certificate_url", ")", "raise", "error", "end", "end" ]
Check that our request is valid. @param [String] signature_certificate_url the url for our signing certificate @param [Rack::Request::Env] request the request object @param [String] raw_body the raw body of our https request
[ "Check", "that", "our", "request", "is", "valid", "." ]
bfb49d091cfbef661f9b1ff7a858cb5d9d09f473
https://github.com/sidoh/alexa_verifier/blob/bfb49d091cfbef661f9b1ff7a858cb5d9d09f473/lib/alexa_verifier/verifier.rb#L94-L107
22,228
sidoh/alexa_verifier
lib/alexa_verifier/verifier.rb
AlexaVerifier.Verifier.check_that_request_was_signed
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 not match certificate provided' unless signed_by_certificate end
ruby
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 not match certificate provided' unless signed_by_certificate end
[ "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 not match certificate provided'", "unless", "signed_by_certificate", "end" ]
Check that our request was signed by a given public key. @param [OpenSSL::PKey::PKey] certificate_public_key the public key we are checking @param [Rack::Request::Env] request the request object we are checking @param [String] raw_body the raw body of our https request @raise [AlexaVerifier::InvalidRequestError] raised if our signature does not match the certificate provided
[ "Check", "that", "our", "request", "was", "signed", "by", "a", "given", "public", "key", "." ]
bfb49d091cfbef661f9b1ff7a858cb5d9d09f473
https://github.com/sidoh/alexa_verifier/blob/bfb49d091cfbef661f9b1ff7a858cb5d9d09f473/lib/alexa_verifier/verifier.rb#L115-L123
22,229
kevinrood/teamcity_formatter
lib/team_city_formatter/formatter.rb
TeamCityFormatter.Formatter.before_feature_element
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("unsupported feature element `#{cuke_feature_element.class.name}`") end end
ruby
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("unsupported feature element `#{cuke_feature_element.class.name}`") end end
[ "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", "(", "\"unsupported feature element `#{cuke_feature_element.class.name}`\"", ")", "end", "end" ]
this method gets called before a scenario or scenario outline we dispatch to our own more specific methods
[ "this", "method", "gets", "called", "before", "a", "scenario", "or", "scenario", "outline", "we", "dispatch", "to", "our", "own", "more", "specific", "methods" ]
d4f2e35b508479b6469f3a7e1d1779948abb4ccb
https://github.com/kevinrood/teamcity_formatter/blob/d4f2e35b508479b6469f3a7e1d1779948abb4ccb/lib/team_city_formatter/formatter.rb#L30-L38
22,230
kevinrood/teamcity_formatter
lib/team_city_formatter/formatter.rb
TeamCityFormatter.Formatter.after_feature_element
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) else raise("unsupported feature element `#{cuke_feature_element.class.name}`") end @exception = nil @scenario = nil @scenario_outline = nil end
ruby
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) else raise("unsupported feature element `#{cuke_feature_element.class.name}`") end @exception = nil @scenario = nil @scenario_outline = nil end
[ "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", ")", "else", "raise", "(", "\"unsupported feature element `#{cuke_feature_element.class.name}`\"", ")", "end", "@exception", "=", "nil", "@scenario", "=", "nil", "@scenario_outline", "=", "nil", "end" ]
this method gets called after a scenario or scenario outline we dispatch to our own more specific methods
[ "this", "method", "gets", "called", "after", "a", "scenario", "or", "scenario", "outline", "we", "dispatch", "to", "our", "own", "more", "specific", "methods" ]
d4f2e35b508479b6469f3a7e1d1779948abb4ccb
https://github.com/kevinrood/teamcity_formatter/blob/d4f2e35b508479b6469f3a7e1d1779948abb4ccb/lib/team_city_formatter/formatter.rb#L42-L54
22,231
kevinrood/teamcity_formatter
lib/team_city_formatter/formatter.rb
TeamCityFormatter.Formatter.before_table_row
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_values == cuke_table_row.values } test_name = scenario_outline_test_name(@scenario_outline.name, example.column_values) @logger.test_started(test_name) end end end
ruby
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_values == cuke_table_row.values } test_name = scenario_outline_test_name(@scenario_outline.name, example.column_values) @logger.test_started(test_name) end end end
[ "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_values", "==", "cuke_table_row", ".", "values", "}", "test_name", "=", "scenario_outline_test_name", "(", "@scenario_outline", ".", "name", ",", "example", ".", "column_values", ")", "@logger", ".", "test_started", "(", "test_name", ")", "end", "end", "end" ]
this method is called before a scenario outline row OR step data table row
[ "this", "method", "is", "called", "before", "a", "scenario", "outline", "row", "OR", "step", "data", "table", "row" ]
d4f2e35b508479b6469f3a7e1d1779948abb4ccb
https://github.com/kevinrood/teamcity_formatter/blob/d4f2e35b508479b6469f3a7e1d1779948abb4ccb/lib/team_city_formatter/formatter.rb#L57-L66
22,232
kevinrood/teamcity_formatter
lib/team_city_formatter/formatter.rb
TeamCityFormatter.Formatter.after_table_row
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 # the exception could have been raised in a background section exception = (@exception || cuke_table_row.exception) example = @scenario_outline.examples.find { |example| example.column_values == cuke_table_row.cells } test_name = scenario_outline_test_name(@scenario_outline.name, example.column_values) if exception if exception.is_a? ::Cucumber::Pending @logger.test_ignored(test_name, 'Pending test') else @logger.test_failed(test_name, exception) end end @logger.test_finished(test_name) @exception = nil end end end
ruby
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 # the exception could have been raised in a background section exception = (@exception || cuke_table_row.exception) example = @scenario_outline.examples.find { |example| example.column_values == cuke_table_row.cells } test_name = scenario_outline_test_name(@scenario_outline.name, example.column_values) if exception if exception.is_a? ::Cucumber::Pending @logger.test_ignored(test_name, 'Pending test') else @logger.test_failed(test_name, exception) end end @logger.test_finished(test_name) @exception = nil end end end
[ "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", "# the exception could have been raised in a background section", "exception", "=", "(", "@exception", "||", "cuke_table_row", ".", "exception", ")", "example", "=", "@scenario_outline", ".", "examples", ".", "find", "{", "|", "example", "|", "example", ".", "column_values", "==", "cuke_table_row", ".", "cells", "}", "test_name", "=", "scenario_outline_test_name", "(", "@scenario_outline", ".", "name", ",", "example", ".", "column_values", ")", "if", "exception", "if", "exception", ".", "is_a?", "::", "Cucumber", "::", "Pending", "@logger", ".", "test_ignored", "(", "test_name", ",", "'Pending test'", ")", "else", "@logger", ".", "test_failed", "(", "test_name", ",", "exception", ")", "end", "end", "@logger", ".", "test_finished", "(", "test_name", ")", "@exception", "=", "nil", "end", "end", "end" ]
this method is called after a scenario outline row OR step data table row
[ "this", "method", "is", "called", "after", "a", "scenario", "outline", "row", "OR", "step", "data", "table", "row" ]
d4f2e35b508479b6469f3a7e1d1779948abb4ccb
https://github.com/kevinrood/teamcity_formatter/blob/d4f2e35b508479b6469f3a7e1d1779948abb4ccb/lib/team_city_formatter/formatter.rb#L69-L90
22,233
weppos/tabs_on_rails
lib/tabs_on_rails/tabs.rb
TabsOnRails.Tabs.render
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 html << @context.capture(self, &block) html << close_tabs(close_tabs_options).to_s end.html_safe end
ruby
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 html << @context.capture(self, &block) html << close_tabs(close_tabs_options).to_s end.html_safe end
[ "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", "html", "<<", "@context", ".", "capture", "(", "self", ",", "block", ")", "html", "<<", "close_tabs", "(", "close_tabs_options", ")", ".", "to_s", "end", ".", "html_safe", "end" ]
Renders the tab stack using the current builder. Returns the String HTML content.
[ "Renders", "the", "tab", "stack", "using", "the", "current", "builder", "." ]
ccd1c1027dc73ba261a558147e53be43de9dc1e6
https://github.com/weppos/tabs_on_rails/blob/ccd1c1027dc73ba261a558147e53be43de9dc1e6/lib/tabs_on_rails/tabs.rb#L50-L62
22,234
0sc/activestorage-cloudinary-service
lib/active_storage/service/cloudinary_service.rb
ActiveStorage.Service::CloudinaryService.download
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 end end
ruby
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 end end
[ "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", "end", "end" ]
Return the content of the file at the +key+.
[ "Return", "the", "content", "of", "the", "file", "at", "the", "+", "key", "+", "." ]
df27e24bac8f7642627ccd44c0ad3c4231f32973
https://github.com/0sc/activestorage-cloudinary-service/blob/df27e24bac8f7642627ccd44c0ad3c4231f32973/lib/active_storage/service/cloudinary_service.rb#L29-L41
22,235
0sc/activestorage-cloudinary-service
lib/active_storage/service/cloudinary_service.rb
ActiveStorage.Service::CloudinaryService.download_chunk
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
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
[ "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" ]
Return the partial content in the byte +range+ of the file at the +key+.
[ "Return", "the", "partial", "content", "in", "the", "byte", "+", "range", "+", "of", "the", "file", "at", "the", "+", "key", "+", "." ]
df27e24bac8f7642627ccd44c0ad3c4231f32973
https://github.com/0sc/activestorage-cloudinary-service/blob/df27e24bac8f7642627ccd44c0ad3c4231f32973/lib/active_storage/service/cloudinary_service.rb#L44-L49
22,236
0sc/activestorage-cloudinary-service
lib/active_storage/service/cloudinary_service.rb
ActiveStorage.Service::CloudinaryService.url_for_direct_upload
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, resource_type: 'auto' } # FIXME: Cloudinary Ruby SDK does't expose an api for signed upload url # The expected url is similar to the private_download_url # with download replaced with upload signed_download_url_for_public_id(key, options) .sub(/download/, 'upload') end end
ruby
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, resource_type: 'auto' } # FIXME: Cloudinary Ruby SDK does't expose an api for signed upload url # The expected url is similar to the private_download_url # with download replaced with upload signed_download_url_for_public_id(key, options) .sub(/download/, 'upload') end end
[ "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", ",", "resource_type", ":", "'auto'", "}", "# FIXME: Cloudinary Ruby SDK does't expose an api for signed upload url", "# The expected url is similar to the private_download_url", "# with download replaced with upload", "signed_download_url_for_public_id", "(", "key", ",", "options", ")", ".", "sub", "(", "/", "/", ",", "'upload'", ")", "end", "end" ]
Returns a signed, temporary URL that a direct upload file can be PUT to on the +key+. The URL will be valid for the amount of seconds specified in +expires_in+. You must also provide the +content_type+, +content_length+, and +checksum+ of the file that will be uploaded. All these attributes will be validated by the service upon upload.
[ "Returns", "a", "signed", "temporary", "URL", "that", "a", "direct", "upload", "file", "can", "be", "PUT", "to", "on", "the", "+", "key", "+", ".", "The", "URL", "will", "be", "valid", "for", "the", "amount", "of", "seconds", "specified", "in", "+", "expires_in", "+", ".", "You", "must", "also", "provide", "the", "+", "content_type", "+", "+", "content_length", "+", "and", "+", "checksum", "+", "of", "the", "file", "that", "will", "be", "uploaded", ".", "All", "these", "attributes", "will", "be", "validated", "by", "the", "service", "upon", "upload", "." ]
df27e24bac8f7642627ccd44c0ad3c4231f32973
https://github.com/0sc/activestorage-cloudinary-service/blob/df27e24bac8f7642627ccd44c0ad3c4231f32973/lib/active_storage/service/cloudinary_service.rb#L91-L107
22,237
ali-sheiba/opta_sd
lib/opta_sd/core.rb
OptaSD.Core.parse_json
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
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
[ "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" ]
Parse JSON Response
[ "Parse", "JSON", "Response" ]
eddba8e9c13b35717b37facd2906cfe1bb5ef771
https://github.com/ali-sheiba/opta_sd/blob/eddba8e9c13b35717b37facd2906cfe1bb5ef771/lib/opta_sd/core.rb#L30-L34
22,238
ali-sheiba/opta_sd
lib/opta_sd/core.rb
OptaSD.Core.parse_xml
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
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
[ "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" ]
Parse XML Response
[ "Parse", "XML", "Response" ]
eddba8e9c13b35717b37facd2906cfe1bb5ef771
https://github.com/ali-sheiba/opta_sd/blob/eddba8e9c13b35717b37facd2906cfe1bb5ef771/lib/opta_sd/core.rb#L37-L41
22,239
reiseburo/hermann
lib/hermann/producer.rb
Hermann.Producer.push
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? @children << result end # Reaping children on the push just to make sure that it does get # called correctly and we don't leak memory reap_children else # Ticking reactor to make sure that we don't inadvertantly let the # librdkafka callback queue overflow tick_reactor result = create_result @internal.push_single(value, topic, opts[:partition_key].to_s, result) end return result end
ruby
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? @children << result end # Reaping children on the push just to make sure that it does get # called correctly and we don't leak memory reap_children else # Ticking reactor to make sure that we don't inadvertantly let the # librdkafka callback queue overflow tick_reactor result = create_result @internal.push_single(value, topic, opts[:partition_key].to_s, result) end return result end
[ "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?", "@children", "<<", "result", "end", "# Reaping children on the push just to make sure that it does get", "# called correctly and we don't leak memory", "reap_children", "else", "# Ticking reactor to make sure that we don't inadvertantly let the", "# librdkafka callback queue overflow", "tick_reactor", "result", "=", "create_result", "@internal", ".", "push_single", "(", "value", ",", "topic", ",", "opts", "[", ":partition_key", "]", ".", "to_s", ",", "result", ")", "end", "return", "result", "end" ]
Push a value onto the Kafka topic passed to this +Producer+ @param [Object] value A single object to push @param [Hash] opts to pass to push method @option opts [String] :topic The topic to push messages to :partition_key The string to partition by @return [Hermann::Result] A future-like object which will store the result from the broker
[ "Push", "a", "value", "onto", "the", "Kafka", "topic", "passed", "to", "this", "+", "Producer", "+" ]
d822ae541aabc24c2fd211f7ef5efba37179ed98
https://github.com/reiseburo/hermann/blob/d822ae541aabc24c2fd211f7ef5efba37179ed98/lib/hermann/producer.rb#L57-L82
22,240
reiseburo/hermann
lib/hermann/producer.rb
Hermann.Producer.tick_reactor
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?) # Propagate errors to the remaining children child.internal_set_error(ex) end end # Reaping the children at this point will also reap any children marked # as errored by an exception out of #execute_tick return reap_children end
ruby
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?) # Propagate errors to the remaining children child.internal_set_error(ex) end end # Reaping the children at this point will also reap any children marked # as errored by an exception out of #execute_tick return reap_children end
[ "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?", ")", "# Propagate errors to the remaining children", "child", ".", "internal_set_error", "(", "ex", ")", "end", "end", "# Reaping the children at this point will also reap any children marked", "# as errored by an exception out of #execute_tick", "return", "reap_children", "end" ]
Tick the underlying librdkafka reacter and clean up any unreaped but reapable children results @param [FixNum] timeout Seconds to block on the internal reactor @return [FixNum] Number of +Hermann::Result+ children reaped
[ "Tick", "the", "underlying", "librdkafka", "reacter", "and", "clean", "up", "any", "unreaped", "but", "reapable", "children", "results" ]
d822ae541aabc24c2fd211f7ef5efba37179ed98
https://github.com/reiseburo/hermann/blob/d822ae541aabc24c2fd211f7ef5efba37179ed98/lib/hermann/producer.rb#L98-L115
22,241
reiseburo/hermann
lib/hermann/producer.rb
Hermann.Producer.execute_tick
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 break if events > 0 sleep 0.5 end end end
ruby
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 break if events > 0 sleep 0.5 end end end
[ "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", "break", "if", "events", ">", "0", "sleep", "0.5", "end", "end", "end" ]
Perform the actual reactor tick @raises [StandardError] in case of underlying failures in librdkafka
[ "Perform", "the", "actual", "reactor", "tick" ]
d822ae541aabc24c2fd211f7ef5efba37179ed98
https://github.com/reiseburo/hermann/blob/d822ae541aabc24c2fd211f7ef5efba37179ed98/lib/hermann/producer.rb#L140-L153
22,242
chaadow/activestorage-openstack
lib/active_storage/service/open_stack_service.rb
ActiveStorage.Service::OpenStackService.change_content_type
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
def change_content_type(key, content_type) client.post_object(container, key, 'Content-Type' => content_type) true rescue Fog::OpenStack::Storage::NotFound false end
[ "def", "change_content_type", "(", "key", ",", "content_type", ")", "client", ".", "post_object", "(", "container", ",", "key", ",", "'Content-Type'", "=>", "content_type", ")", "true", "rescue", "Fog", "::", "OpenStack", "::", "Storage", "::", "NotFound", "false", "end" ]
Non-standard method to change the content type of an existing object
[ "Non", "-", "standard", "method", "to", "change", "the", "content", "type", "of", "an", "existing", "object" ]
91f002351b35d19e1ce3a372221b6da324390a35
https://github.com/chaadow/activestorage-openstack/blob/91f002351b35d19e1ce3a372221b6da324390a35/lib/active_storage/service/open_stack_service.rb#L120-L127
22,243
reidmorrison/jruby-jms
lib/jms/oracle_a_q_connection_factory.rb
JMS.OracleAQConnectionFactory.create_connection
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 Qualified name causes a Java exception #cf = oracle.jms.AQjmsFactory.getConnectionFactory(@url, java.util.Properties.new) cf = AQjmsFactory.getConnectionFactory(@url, java.util.Properties.new) if username cf.createConnection(@username, @password) else cf.createConnection() end end
ruby
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 Qualified name causes a Java exception #cf = oracle.jms.AQjmsFactory.getConnectionFactory(@url, java.util.Properties.new) cf = AQjmsFactory.getConnectionFactory(@url, java.util.Properties.new) if username cf.createConnection(@username, @password) else cf.createConnection() end end
[ "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 Qualified name causes a Java exception", "#cf = oracle.jms.AQjmsFactory.getConnectionFactory(@url, java.util.Properties.new)", "cf", "=", "AQjmsFactory", ".", "getConnectionFactory", "(", "@url", ",", "java", ".", "util", ".", "Properties", ".", "new", ")", "if", "username", "cf", ".", "createConnection", "(", "@username", ",", "@password", ")", "else", "cf", ".", "createConnection", "(", ")", "end", "end" ]
Creates a connection per standard JMS 1.1 techniques from the Oracle AQ JMS Interface
[ "Creates", "a", "connection", "per", "standard", "JMS", "1", ".", "1", "techniques", "from", "the", "Oracle", "AQ", "JMS", "Interface" ]
cdc2ce1daf643474110146a7505dad5e427030d3
https://github.com/reidmorrison/jruby-jms/blob/cdc2ce1daf643474110146a7505dad5e427030d3/lib/jms/oracle_a_q_connection_factory.rb#L11-L28
22,244
reidmorrison/jruby-jms
lib/jms/session_pool.rb
JMS.SessionPool.session
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 end
ruby
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 end
[ "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", "end" ]
Obtain a session from the pool and pass it to the supplied block The session is automatically returned to the pool once the block completes In the event a JMS Exception is thrown the session will be closed and removed from the pool to prevent re-using sessions that are no longer valid
[ "Obtain", "a", "session", "from", "the", "pool", "and", "pass", "it", "to", "the", "supplied", "block", "The", "session", "is", "automatically", "returned", "to", "the", "pool", "once", "the", "block", "completes" ]
cdc2ce1daf643474110146a7505dad5e427030d3
https://github.com/reidmorrison/jruby-jms/blob/cdc2ce1daf643474110146a7505dad5e427030d3/lib/jms/session_pool.rb#L66-L79
22,245
reidmorrison/jruby-jms
lib/jms/session_pool.rb
JMS.SessionPool.consumer
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
def consumer(params, &block) session do |s| begin consumer = s.consumer(params) block.call(s, consumer) ensure consumer.close if consumer end end end
[ "def", "consumer", "(", "params", ",", "&", "block", ")", "session", "do", "|", "s", "|", "begin", "consumer", "=", "s", ".", "consumer", "(", "params", ")", "block", ".", "call", "(", "s", ",", "consumer", ")", "ensure", "consumer", ".", "close", "if", "consumer", "end", "end", "end" ]
Obtain a session from the pool and create a MessageConsumer. Pass both into the supplied block. Once the block is complete the consumer is closed and the session is returned to the pool. Parameters: queue_name: [String] Name of the Queue to return [Symbol] Create temporary queue Mandatory unless :topic_name is supplied Or, topic_name: [String] Name of the Topic to write to or subscribe to [Symbol] Create temporary topic Mandatory unless :queue_name is supplied Or, destination: [javaxJms::Destination] Destination to use selector: Filter which messages should be returned from the queue Default: All messages no_local: Determine whether messages published by its own connection should be delivered to it Default: false Example session_pool.consumer(queue_name: 'MyQueue') do |session, consumer| message = consumer.receive(timeout) puts message.data if message end
[ "Obtain", "a", "session", "from", "the", "pool", "and", "create", "a", "MessageConsumer", ".", "Pass", "both", "into", "the", "supplied", "block", ".", "Once", "the", "block", "is", "complete", "the", "consumer", "is", "closed", "and", "the", "session", "is", "returned", "to", "the", "pool", "." ]
cdc2ce1daf643474110146a7505dad5e427030d3
https://github.com/reidmorrison/jruby-jms/blob/cdc2ce1daf643474110146a7505dad5e427030d3/lib/jms/session_pool.rb#L108-L117
22,246
reidmorrison/jruby-jms
lib/jms/session_pool.rb
JMS.SessionPool.producer
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
def producer(params, &block) session do |s| begin producer = s.producer(params) block.call(s, producer) ensure producer.close if producer end end end
[ "def", "producer", "(", "params", ",", "&", "block", ")", "session", "do", "|", "s", "|", "begin", "producer", "=", "s", ".", "producer", "(", "params", ")", "block", ".", "call", "(", "s", ",", "producer", ")", "ensure", "producer", ".", "close", "if", "producer", "end", "end", "end" ]
Obtain a session from the pool and create a MessageProducer. Pass both into the supplied block. Once the block is complete the producer is closed and the session is returned to the pool. Parameters: queue_name: [String] Name of the Queue to return [Symbol] Create temporary queue Mandatory unless :topic_name is supplied Or, topic_name: [String] Name of the Topic to write to or subscribe to [Symbol] Create temporary topic Mandatory unless :queue_name is supplied Or, destination: [javaxJms::Destination] Destination to use Example session_pool.producer(queue_name: 'ExampleQueue') do |session, producer| producer.send(session.message("Hello World")) end
[ "Obtain", "a", "session", "from", "the", "pool", "and", "create", "a", "MessageProducer", ".", "Pass", "both", "into", "the", "supplied", "block", ".", "Once", "the", "block", "is", "complete", "the", "producer", "is", "closed", "and", "the", "session", "is", "returned", "to", "the", "pool", "." ]
cdc2ce1daf643474110146a7505dad5e427030d3
https://github.com/reidmorrison/jruby-jms/blob/cdc2ce1daf643474110146a7505dad5e427030d3/lib/jms/session_pool.rb#L139-L148
22,247
reidmorrison/jruby-jms
lib/jms/connection.rb
JMS.Connection.fetch_dependencies
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 'jms/imports' require 'jms/message_listener_impl' require 'jms/message' require 'jms/text_message' require 'jms/map_message' require 'jms/bytes_message' require 'jms/object_message' require 'jms/session' require 'jms/message_consumer' require 'jms/message_producer' require 'jms/queue_browser' end
ruby
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 'jms/imports' require 'jms/message_listener_impl' require 'jms/message' require 'jms/text_message' require 'jms/map_message' require 'jms/bytes_message' require 'jms/object_message' require 'jms/session' require 'jms/message_consumer' require 'jms/message_producer' require 'jms/queue_browser' end
[ "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", "'jms/imports'", "require", "'jms/message_listener_impl'", "require", "'jms/message'", "require", "'jms/text_message'", "require", "'jms/map_message'", "require", "'jms/bytes_message'", "require", "'jms/object_message'", "require", "'jms/session'", "require", "'jms/message_consumer'", "require", "'jms/message_producer'", "require", "'jms/queue_browser'", "end" ]
Load the required jar files for this JMS Provider and load JRuby extensions for those classes Rather than copying the JMS jar files into the JRuby lib, load them on demand. JRuby JMS extensions are only loaded once the jar files have been loaded. Can be called multiple times if required, although it would not be performant to do so regularly. Parameter: jar_list is an Array of the path and filenames to jar files to load for this JMS Provider Returns nil
[ "Load", "the", "required", "jar", "files", "for", "this", "JMS", "Provider", "and", "load", "JRuby", "extensions", "for", "those", "classes" ]
cdc2ce1daf643474110146a7505dad5e427030d3
https://github.com/reidmorrison/jruby-jms/blob/cdc2ce1daf643474110146a7505dad5e427030d3/lib/jms/connection.rb#L89-L111
22,248
reidmorrison/jruby-jms
lib/jms/connection.rb
JMS.Connection.session
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
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
[ "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" ]
Create a session over this connection. It is recommended to create separate sessions for each thread If a block of code is passed in, it will be called and then the session is automatically closed on completion of the code block Parameters: transacted: [true|false] Determines whether transactions are supported within this session. I.e. Whether commit or rollback can be called Default: false Note: :options below are ignored if this value is set to :true options: any of the JMS::Session constants: Note: :options are ignored if transacted: true JMS::Session::AUTO_ACKNOWLEDGE With this acknowledgment mode, the session automatically acknowledges a client's receipt of a message either when the session has successfully returned from a call to receive or when the message listener the session has called to process the message successfully returns. JMS::Session::CLIENT_ACKNOWLEDGE With this acknowledgment mode, the client acknowledges a consumed message by calling the message's acknowledge method. JMS::Session::DUPS_OK_ACKNOWLEDGE This acknowledgment mode instructs the session to lazily acknowledge the delivery of messages. JMS::Session::SESSION_TRANSACTED This value is returned from the method getAcknowledgeMode if the session is transacted. Default: JMS::Session::AUTO_ACKNOWLEDGE
[ "Create", "a", "session", "over", "this", "connection", ".", "It", "is", "recommended", "to", "create", "separate", "sessions", "for", "each", "thread", "If", "a", "block", "of", "code", "is", "passed", "in", "it", "will", "be", "called", "and", "then", "the", "session", "is", "automatically", "closed", "on", "completion", "of", "the", "code", "block" ]
cdc2ce1daf643474110146a7505dad5e427030d3
https://github.com/reidmorrison/jruby-jms/blob/cdc2ce1daf643474110146a7505dad5e427030d3/lib/jms/connection.rb#L254-L262
22,249
reidmorrison/jruby-jms
lib/jms/connection.rb
JMS.Connection.create_session
def create_session(params={}) transacted = params[:transacted] || false options = params[:options] || JMS::Session::AUTO_ACKNOWLEDGE @jms_connection.create_session(transacted, options) end
ruby
def create_session(params={}) transacted = params[:transacted] || false options = params[:options] || JMS::Session::AUTO_ACKNOWLEDGE @jms_connection.create_session(transacted, options) end
[ "def", "create_session", "(", "params", "=", "{", "}", ")", "transacted", "=", "params", "[", ":transacted", "]", "||", "false", "options", "=", "params", "[", ":options", "]", "||", "JMS", "::", "Session", "::", "AUTO_ACKNOWLEDGE", "@jms_connection", ".", "create_session", "(", "transacted", ",", "options", ")", "end" ]
Create a session over this connection. It is recommended to create separate sessions for each thread Note: Remember to call close on the returned session when it is no longer needed. Rather use JMS::Connection#session with a block whenever possible Parameters: transacted: true or false Determines whether transactions are supported within this session. I.e. Whether commit or rollback can be called Default: false Note: :options below are ignored if this value is set to :true options: any of the JMS::Session constants: Note: :options are ignored if transacted: true JMS::Session::AUTO_ACKNOWLEDGE With this acknowledgment mode, the session automatically acknowledges a client's receipt of a message either when the session has successfully returned from a call to receive or when the message listener the session has called to process the message successfully returns. JMS::Session::CLIENT_ACKNOWLEDGE With this acknowledgment mode, the client acknowledges a consumed message by calling the message's acknowledge method. JMS::Session::DUPS_OK_ACKNOWLEDGE This acknowledgment mode instructs the session to lazily acknowledge the delivery of messages. JMS::Session::SESSION_TRANSACTED This value is returned from the method getAcknowledgeMode if the session is transacted. Default: JMS::Session::AUTO_ACKNOWLEDGE
[ "Create", "a", "session", "over", "this", "connection", ".", "It", "is", "recommended", "to", "create", "separate", "sessions", "for", "each", "thread" ]
cdc2ce1daf643474110146a7505dad5e427030d3
https://github.com/reidmorrison/jruby-jms/blob/cdc2ce1daf643474110146a7505dad5e427030d3/lib/jms/connection.rb#L296-L300
22,250
reidmorrison/jruby-jms
lib/jms/connection.rb
JMS.Connection.on_message
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(params) if session.transacted? consumer.on_message(params) do |message| begin block.call(message) ? session.commit : session.rollback rescue => exc session.rollback throw exc end end else consumer.on_message(params, &block) end @consumers << consumer @sessions << session end end
ruby
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(params) if session.transacted? consumer.on_message(params) do |message| begin block.call(message) ? session.commit : session.rollback rescue => exc session.rollback throw exc end end else consumer.on_message(params, &block) end @consumers << consumer @sessions << session end end
[ "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", "(", "params", ")", "if", "session", ".", "transacted?", "consumer", ".", "on_message", "(", "params", ")", "do", "|", "message", "|", "begin", "block", ".", "call", "(", "message", ")", "?", "session", ".", "commit", ":", "session", ".", "rollback", "rescue", "=>", "exc", "session", ".", "rollback", "throw", "exc", "end", "end", "else", "consumer", ".", "on_message", "(", "params", ",", "block", ")", "end", "@consumers", "<<", "consumer", "@sessions", "<<", "session", "end", "end" ]
Receive messages in a separate thread when they arrive Allows messages to be received Asynchronously in a separate thread. This method will return to the caller before messages are processed. It is then the callers responsibility to keep the program active so that messages can then be processed. Session Parameters: transacted: true or false Determines whether transactions are supported within this session. I.e. Whether commit or rollback can be called Default: false Note: :options below are ignored if this value is set to :true options: any of the JMS::Session constants: Note: :options are ignored if transacted: true JMS::Session::AUTO_ACKNOWLEDGE With this acknowledgment mode, the session automatically acknowledges a client's receipt of a message either when the session has successfully returned from a call to receive or when the message listener the session has called to process the message successfully returns. JMS::Session::CLIENT_ACKNOWLEDGE With this acknowledgment mode, the client acknowledges a consumed message by calling the message's acknowledge method. JMS::Session::DUPS_OK_ACKNOWLEDGE This acknowledgment mode instructs the session to lazily acknowledge the delivery of messages. JMS::Session::SESSION_TRANSACTED This value is returned from the method getAcknowledgeMode if the session is transacted. Default: JMS::Session::AUTO_ACKNOWLEDGE :session_count : Number of sessions to create, each with their own consumer which in turn will call the supplied code block. Note: The supplied block must be thread safe since it will be called by several threads at the same time. I.e. Don't change instance variables etc. without the necessary semaphores etc. Default: 1 Consumer Parameters: queue_name: String: Name of the Queue to return Symbol: temporary: Create temporary queue Mandatory unless :topic_name is supplied Or, topic_name: String: Name of the Topic to write to or subscribe to Symbol: temporary: Create temporary topic Mandatory unless :queue_name is supplied Or, destination:Explicit javaxJms::Destination to use selector: Filter which messages should be returned from the queue Default: All messages no_local: Determine whether messages published by its own connection should be delivered to the supplied block Default: false :statistics Capture statistics on how many messages have been read true : This method will capture statistics on the number of messages received and the time it took to process them. The timer starts when each() is called and finishes when either the last message was received, or when Destination::statistics is called. In this case MessageConsumer::statistics can be called several times during processing without affecting the end time. Also, the start time and message count is not reset until MessageConsumer::each is called again with statistics: true Usage: For transacted sessions the block supplied must return either true or false: true => The session is committed false => The session is rolled back Any Exception => The session is rolled back Note: Separately invoke Connection#on_exception so that connection failures can be handled since on_message will Not be called if the connection is lost
[ "Receive", "messages", "in", "a", "separate", "thread", "when", "they", "arrive" ]
cdc2ce1daf643474110146a7505dad5e427030d3
https://github.com/reidmorrison/jruby-jms/blob/cdc2ce1daf643474110146a7505dad5e427030d3/lib/jms/connection.rb#L441-L463
22,251
reidmorrison/jruby-jms
lib/jms/message_listener_impl.rb
JMS.MessageListenerImpl.statistics
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, messages_per_second: (@message_count/duration).to_i } end
ruby
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, messages_per_second: (@message_count/duration).to_i } end
[ "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", ",", "messages_per_second", ":", "(", "@message_count", "/", "duration", ")", ".", "to_i", "}", "end" ]
Return Statistics gathered for this listener
[ "Return", "Statistics", "gathered", "for", "this", "listener" ]
cdc2ce1daf643474110146a7505dad5e427030d3
https://github.com/reidmorrison/jruby-jms/blob/cdc2ce1daf643474110146a7505dad5e427030d3/lib/jms/message_listener_impl.rb#L53-L61
22,252
cloudfoundry-attic/cf
lib/micro/plugin.rb
CFMicro.McfCommand.override
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
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
[ "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" ]
override with command line arguments and yield the block in case the option isn't set
[ "override", "with", "command", "line", "arguments", "and", "yield", "the", "block", "in", "case", "the", "option", "isn", "t", "set" ]
2b47b522e9d5600876ebfd6465d5575265dcc601
https://github.com/cloudfoundry-attic/cf/blob/2b47b522e9d5600876ebfd6465d5575265dcc601/lib/micro/plugin.rb#L153-L160
22,253
cloudfoundry-attic/cf
lib/manifests/loader/resolver.rb
CFManifests.Resolver.resolve_lexically
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 String val.gsub(/\$\{([^\}]+)\}/) do resolve_symbol(resolver, $1, ctx) end else val end end
ruby
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 String val.gsub(/\$\{([^\}]+)\}/) do resolve_symbol(resolver, $1, ctx) end else val end end
[ "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", "String", "val", ".", "gsub", "(", "/", "\\$", "\\{", "\\}", "\\}", "/", ")", "do", "resolve_symbol", "(", "resolver", ",", "$1", ",", "ctx", ")", "end", "else", "val", "end", "end" ]
resolve symbols, with hashes introducing new lexical symbols
[ "resolve", "symbols", "with", "hashes", "introducing", "new", "lexical", "symbols" ]
2b47b522e9d5600876ebfd6465d5575265dcc601
https://github.com/cloudfoundry-attic/cf/blob/2b47b522e9d5600876ebfd6465d5575265dcc601/lib/manifests/loader/resolver.rb#L16-L37
22,254
cloudfoundry-attic/cf
lib/manifests/loader/resolver.rb
CFManifests.Resolver.resolve_symbol
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
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
[ "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" ]
resolve a symbol to its value, and then resolve that value
[ "resolve", "a", "symbol", "to", "its", "value", "and", "then", "resolve", "that", "value" ]
2b47b522e9d5600876ebfd6465d5575265dcc601
https://github.com/cloudfoundry-attic/cf/blob/2b47b522e9d5600876ebfd6465d5575265dcc601/lib/manifests/loader/resolver.rb#L40-L49
22,255
cloudfoundry-attic/cf
lib/manifests/loader/resolver.rb
CFManifests.Resolver.find_symbol
def find_symbol(sym, ctx) ctx.each do |h| if val = resolve_in(h, sym) return val end end nil end
ruby
def find_symbol(sym, ctx) ctx.each do |h| if val = resolve_in(h, sym) return val end end nil end
[ "def", "find_symbol", "(", "sym", ",", "ctx", ")", "ctx", ".", "each", "do", "|", "h", "|", "if", "val", "=", "resolve_in", "(", "h", ",", "sym", ")", "return", "val", "end", "end", "nil", "end" ]
search for a symbol introduced in the lexical context
[ "search", "for", "a", "symbol", "introduced", "in", "the", "lexical", "context" ]
2b47b522e9d5600876ebfd6465d5575265dcc601
https://github.com/cloudfoundry-attic/cf/blob/2b47b522e9d5600876ebfd6465d5575265dcc601/lib/manifests/loader/resolver.rb#L52-L60
22,256
cloudfoundry-attic/cf
lib/manifests/loader/resolver.rb
CFManifests.Resolver.find_in_hash
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
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
[ "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" ]
helper for following a path of values in a hash
[ "helper", "for", "following", "a", "path", "of", "values", "in", "a", "hash" ]
2b47b522e9d5600876ebfd6465d5575265dcc601
https://github.com/cloudfoundry-attic/cf/blob/2b47b522e9d5600876ebfd6465d5575265dcc601/lib/manifests/loader/resolver.rb#L69-L77
22,257
cloudfoundry-attic/cf
lib/manifests/loader/builder.rb
CFManifests.Builder.build
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
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
[ "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" ]
parse a manifest and merge with its inherited manifests
[ "parse", "a", "manifest", "and", "merge", "with", "its", "inherited", "manifests" ]
2b47b522e9d5600876ebfd6465d5575265dcc601
https://github.com/cloudfoundry-attic/cf/blob/2b47b522e9d5600876ebfd6465d5575265dcc601/lib/manifests/loader/builder.rb#L6-L17
22,258
cloudfoundry-attic/cf
lib/manifests/loader/builder.rb
CFManifests.Builder.merge_manifest
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
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
[ "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" ]
deep hash merge
[ "deep", "hash", "merge" ]
2b47b522e9d5600876ebfd6465d5575265dcc601
https://github.com/cloudfoundry-attic/cf/blob/2b47b522e9d5600876ebfd6465d5575265dcc601/lib/manifests/loader/builder.rb#L27-L37
22,259
plu/simctl
lib/simctl/list.rb
SimCtl.List.where
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 end end matches end end
ruby
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 end end matches end end
[ "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", "end", "end", "matches", "end", "end" ]
Filters an array of objects by a given hash. The keys of the hash must be methods implemented by the objects. The values of the hash are compared to the values the object returns when calling the methods. @param filter [Hash] the filters that should be applied @return [Array] the filtered array.
[ "Filters", "an", "array", "of", "objects", "by", "a", "given", "hash", ".", "The", "keys", "of", "the", "hash", "must", "be", "methods", "implemented", "by", "the", "objects", ".", "The", "values", "of", "the", "hash", "are", "compared", "to", "the", "values", "the", "object", "returns", "when", "calling", "the", "methods", "." ]
7f64887935d0a6a3caa0630e167f7b3711b67857
https://github.com/plu/simctl/blob/7f64887935d0a6a3caa0630e167f7b3711b67857/lib/simctl/list.rb#L10-L24
22,260
plu/simctl
lib/simctl/device.rb
SimCtl.Device.reload
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
def reload device = SimCtl.device(udid: udid) device.instance_variables.each do |ivar| instance_variable_set(ivar, device.instance_variable_get(ivar)) end end
[ "def", "reload", "device", "=", "SimCtl", ".", "device", "(", "udid", ":", "udid", ")", "device", ".", "instance_variables", ".", "each", "do", "|", "ivar", "|", "instance_variable_set", "(", "ivar", ",", "device", ".", "instance_variable_get", "(", "ivar", ")", ")", "end", "end" ]
Reloads the device information @return [void]
[ "Reloads", "the", "device", "information" ]
7f64887935d0a6a3caa0630e167f7b3711b67857
https://github.com/plu/simctl/blob/7f64887935d0a6a3caa0630e167f7b3711b67857/lib/simctl/device.rb#L131-L136
22,261
plu/simctl
lib/simctl/device.rb
SimCtl.Device.wait
def wait(timeout = SimCtl.default_timeout) Timeout.timeout(timeout) do loop do break if yield SimCtl.device(udid: udid) end end reload end
ruby
def wait(timeout = SimCtl.default_timeout) Timeout.timeout(timeout) do loop do break if yield SimCtl.device(udid: udid) end end reload end
[ "def", "wait", "(", "timeout", "=", "SimCtl", ".", "default_timeout", ")", "Timeout", ".", "timeout", "(", "timeout", ")", "do", "loop", "do", "break", "if", "yield", "SimCtl", ".", "device", "(", "udid", ":", "udid", ")", "end", "end", "reload", "end" ]
Reloads the device until the given block returns true @return [void]
[ "Reloads", "the", "device", "until", "the", "given", "block", "returns", "true" ]
7f64887935d0a6a3caa0630e167f7b3711b67857
https://github.com/plu/simctl/blob/7f64887935d0a6a3caa0630e167f7b3711b67857/lib/simctl/device.rb#L204-L211
22,262
plu/simctl
lib/simctl/device_settings.rb
SimCtl.DeviceSettings.disable_keyboard_helpers
def disable_keyboard_helpers edit_plist(path.preferences_plist) do |plist| %w[ KeyboardAllowPaddle KeyboardAssistant KeyboardAutocapitalization KeyboardAutocorrection KeyboardCapsLock KeyboardCheckSpelling KeyboardPeriodShortcut KeyboardPrediction KeyboardShowPredictionBar ].each do |key| plist[key] = false end end end
ruby
def disable_keyboard_helpers edit_plist(path.preferences_plist) do |plist| %w[ KeyboardAllowPaddle KeyboardAssistant KeyboardAutocapitalization KeyboardAutocorrection KeyboardCapsLock KeyboardCheckSpelling KeyboardPeriodShortcut KeyboardPrediction KeyboardShowPredictionBar ].each do |key| plist[key] = false end end end
[ "def", "disable_keyboard_helpers", "edit_plist", "(", "path", ".", "preferences_plist", ")", "do", "|", "plist", "|", "%w[", "KeyboardAllowPaddle", "KeyboardAssistant", "KeyboardAutocapitalization", "KeyboardAutocorrection", "KeyboardCapsLock", "KeyboardCheckSpelling", "KeyboardPeriodShortcut", "KeyboardPrediction", "KeyboardShowPredictionBar", "]", ".", "each", "do", "|", "key", "|", "plist", "[", "key", "]", "=", "false", "end", "end", "end" ]
Disables the keyboard helpers @return [void]
[ "Disables", "the", "keyboard", "helpers" ]
7f64887935d0a6a3caa0630e167f7b3711b67857
https://github.com/plu/simctl/blob/7f64887935d0a6a3caa0630e167f7b3711b67857/lib/simctl/device_settings.rb#L14-L30
22,263
plu/simctl
lib/simctl/device_settings.rb
SimCtl.DeviceSettings.set_language
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
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
[ "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" ]
Sets the device language @return [void]
[ "Sets", "the", "device", "language" ]
7f64887935d0a6a3caa0630e167f7b3711b67857
https://github.com/plu/simctl/blob/7f64887935d0a6a3caa0630e167f7b3711b67857/lib/simctl/device_settings.rb#L53-L59
22,264
dicom/ruby-dicom
lib/dicom/parent.rb
DICOM.Parent.count_all
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
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
[ "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" ]
Gives the total number of elements connected to this parent. This count includes all the elements contained in any possible child elements. @return [Integer] The total number of child elements connected to this parent
[ "Gives", "the", "total", "number", "of", "elements", "connected", "to", "this", "parent", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/parent.rb#L109-L116
22,265
dicom/ruby-dicom
lib/dicom/parent.rb
DICOM.Parent.delete
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.delete(tag_or_index) end end
ruby
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.delete(tag_or_index) end end
[ "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", ".", "delete", "(", "tag_or_index", ")", "end", "end" ]
Deletes the specified element from this parent. @param [String, Integer] tag_or_index a ruby-dicom tag string or item index @param [Hash] options the options used for deleting the element option options [Boolean] :no_follow when true, the method does not update the parent attribute of the child that is deleted @example Delete an Element from a DObject instance dcm.delete("0008,0090") @example Delete Item 1 from a Sequence dcm["3006,0020"].delete(1)
[ "Deletes", "the", "specified", "element", "from", "this", "parent", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/parent.rb#L128-L136
22,266
dicom/ruby-dicom
lib/dicom/parent.rb
DICOM.Parent.delete_group
def delete_group(group_string) group_elements = group(group_string) group_elements.each do |element| delete(element.tag) end end
ruby
def delete_group(group_string) group_elements = group(group_string) group_elements.each do |element| delete(element.tag) end end
[ "def", "delete_group", "(", "group_string", ")", "group_elements", "=", "group", "(", "group_string", ")", "group_elements", ".", "each", "do", "|", "element", "|", "delete", "(", "element", ".", "tag", ")", "end", "end" ]
Deletes all elements of the specified group from this parent. @param [String] group_string a group string (the first 4 characters of a tag string) @example Delete the File Meta Group of a DICOM object dcm.delete_group("0002")
[ "Deletes", "all", "elements", "of", "the", "specified", "group", "from", "this", "parent", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/parent.rb#L152-L157
22,267
dicom/ruby-dicom
lib/dicom/parent.rb
DICOM.Parent.encode_children
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
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
[ "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" ]
Re-encodes the binary data strings of all child Element instances. This also includes all the elements contained in any possible child elements. @note This method is only intended for internal library use, but for technical reasons (the fact that is called between instances of different classes), can't be made private. @param [Boolean] old_endian the previous endianness of the elements/DObject instance (used for decoding values from binary)
[ "Re", "-", "encodes", "the", "binary", "data", "strings", "of", "all", "child", "Element", "instances", ".", "This", "also", "includes", "all", "the", "elements", "contained", "in", "any", "possible", "child", "elements", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/parent.rb#L241-L250
22,268
dicom/ruby-dicom
lib/dicom/parent.rb
DICOM.Parent.group
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
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
[ "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" ]
Returns an array of all child elements that belongs to the specified group. @param [String] group_string a group string (the first 4 characters of a tag string) @return [Array<Element, Item, Sequence>] the matching child elements (an empty array if no children matches)
[ "Returns", "an", "array", "of", "all", "child", "elements", "that", "belongs", "to", "the", "specified", "group", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/parent.rb#L272-L279
22,269
dicom/ruby-dicom
lib/dicom/parent.rb
DICOM.Parent.handle_print
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_symbol = "| " children.each_with_index do |element, i| n_parents = element.parents.length # Formatting: Index i_s = s*(max_digits-(index).to_s.length) # Formatting: Name (and Tag) if element.tag == ITEM_TAG # Add index numbers to the Item names: name = "#{element.name} (\##{i})" else name = element.name end n_s = s*(max_name-name.length) # Formatting: Tag tag = "#{visualization.join}#{element.tag}" t_s = s*((max_generations-1)*2+9-tag.length) # Formatting: Length l_s = s*(max_length-element.length.to_s.length) # Formatting Value: if element.is_a?(Element) value = element.value.to_s else value = "" end if options[:value_max] value = "#{value[0..(options[:value_max]-3)]}.." if value.length > options[:value_max] end elements << "#{i_s}#{index} #{tag}#{t_s} #{name}#{n_s} #{element.vr} #{l_s}#{element.length} #{value}" index += 1 # If we have child elements, print those elements recursively: if element.children? if n_parents > 1 child_visualization = Array.new child_visualization.replace(visualization) if element == children.first if children.length == 1 # Last item: child_visualization.insert(n_parents-2, last_item_symbol) else # More items follows: child_visualization.insert(n_parents-2, nonlast_item_symbol) end elsif element == children.last # Last item: child_visualization[n_parents-2] = last_item_symbol child_visualization.insert(-1, hook_symbol) else # Neither first nor last (more items follows): child_visualization.insert(n_parents-2, nonlast_item_symbol) end elsif n_parents == 1 child_visualization = Array.new(1, hook_symbol) else child_visualization = Array.new end new_elements, index = element.handle_print(index, max_digits, max_name, max_length, max_generations, child_visualization, options) elements << new_elements end end return elements.flatten, index end
ruby
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_symbol = "| " children.each_with_index do |element, i| n_parents = element.parents.length # Formatting: Index i_s = s*(max_digits-(index).to_s.length) # Formatting: Name (and Tag) if element.tag == ITEM_TAG # Add index numbers to the Item names: name = "#{element.name} (\##{i})" else name = element.name end n_s = s*(max_name-name.length) # Formatting: Tag tag = "#{visualization.join}#{element.tag}" t_s = s*((max_generations-1)*2+9-tag.length) # Formatting: Length l_s = s*(max_length-element.length.to_s.length) # Formatting Value: if element.is_a?(Element) value = element.value.to_s else value = "" end if options[:value_max] value = "#{value[0..(options[:value_max]-3)]}.." if value.length > options[:value_max] end elements << "#{i_s}#{index} #{tag}#{t_s} #{name}#{n_s} #{element.vr} #{l_s}#{element.length} #{value}" index += 1 # If we have child elements, print those elements recursively: if element.children? if n_parents > 1 child_visualization = Array.new child_visualization.replace(visualization) if element == children.first if children.length == 1 # Last item: child_visualization.insert(n_parents-2, last_item_symbol) else # More items follows: child_visualization.insert(n_parents-2, nonlast_item_symbol) end elsif element == children.last # Last item: child_visualization[n_parents-2] = last_item_symbol child_visualization.insert(-1, hook_symbol) else # Neither first nor last (more items follows): child_visualization.insert(n_parents-2, nonlast_item_symbol) end elsif n_parents == 1 child_visualization = Array.new(1, hook_symbol) else child_visualization = Array.new end new_elements, index = element.handle_print(index, max_digits, max_name, max_length, max_generations, child_visualization, options) elements << new_elements end end return elements.flatten, index end
[ "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_symbol", "=", "\"| \"", "children", ".", "each_with_index", "do", "|", "element", ",", "i", "|", "n_parents", "=", "element", ".", "parents", ".", "length", "# Formatting: Index", "i_s", "=", "s", "(", "max_digits", "-", "(", "index", ")", ".", "to_s", ".", "length", ")", "# Formatting: Name (and Tag)", "if", "element", ".", "tag", "==", "ITEM_TAG", "# Add index numbers to the Item names:", "name", "=", "\"#{element.name} (\\##{i})\"", "else", "name", "=", "element", ".", "name", "end", "n_s", "=", "s", "(", "max_name", "-", "name", ".", "length", ")", "# Formatting: Tag", "tag", "=", "\"#{visualization.join}#{element.tag}\"", "t_s", "=", "s", "(", "(", "max_generations", "-", "1", ")", "*", "2", "+", "9", "-", "tag", ".", "length", ")", "# Formatting: Length", "l_s", "=", "s", "(", "max_length", "-", "element", ".", "length", ".", "to_s", ".", "length", ")", "# Formatting Value:", "if", "element", ".", "is_a?", "(", "Element", ")", "value", "=", "element", ".", "value", ".", "to_s", "else", "value", "=", "\"\"", "end", "if", "options", "[", ":value_max", "]", "value", "=", "\"#{value[0..(options[:value_max]-3)]}..\"", "if", "value", ".", "length", ">", "options", "[", ":value_max", "]", "end", "elements", "<<", "\"#{i_s}#{index} #{tag}#{t_s} #{name}#{n_s} #{element.vr} #{l_s}#{element.length} #{value}\"", "index", "+=", "1", "# If we have child elements, print those elements recursively:", "if", "element", ".", "children?", "if", "n_parents", ">", "1", "child_visualization", "=", "Array", ".", "new", "child_visualization", ".", "replace", "(", "visualization", ")", "if", "element", "==", "children", ".", "first", "if", "children", ".", "length", "==", "1", "# Last item:", "child_visualization", ".", "insert", "(", "n_parents", "-", "2", ",", "last_item_symbol", ")", "else", "# More items follows:", "child_visualization", ".", "insert", "(", "n_parents", "-", "2", ",", "nonlast_item_symbol", ")", "end", "elsif", "element", "==", "children", ".", "last", "# Last item:", "child_visualization", "[", "n_parents", "-", "2", "]", "=", "last_item_symbol", "child_visualization", ".", "insert", "(", "-", "1", ",", "hook_symbol", ")", "else", "# Neither first nor last (more items follows):", "child_visualization", ".", "insert", "(", "n_parents", "-", "2", ",", "nonlast_item_symbol", ")", "end", "elsif", "n_parents", "==", "1", "child_visualization", "=", "Array", ".", "new", "(", "1", ",", "hook_symbol", ")", "else", "child_visualization", "=", "Array", ".", "new", "end", "new_elements", ",", "index", "=", "element", ".", "handle_print", "(", "index", ",", "max_digits", ",", "max_name", ",", "max_length", ",", "max_generations", ",", "child_visualization", ",", "options", ")", "elements", "<<", "new_elements", "end", "end", "return", "elements", ".", "flatten", ",", "index", "end" ]
Gathers the desired information from the selected data elements and processes this information to make a text output which is nicely formatted. @note This method is only intended for internal library use, but for technical reasons (the fact that is called between instances of different classes), can't be made private. The method is used by the print() method to construct its text output. @param [Integer] index the index which is given to the first child of this parent @param [Integer] max_digits the maximum number of digits in the index of an element (in reality the number of digits of the last element) @param [Integer] max_name the maximum number of characters in the name of any element to be printed @param [Integer] max_length the maximum number of digits in the length of an element @param [Integer] max_generations the maximum number of generations of children for this parent @param [Integer] visualization an array of string symbols which visualizes the tree structure that the children of this particular parent belongs to (for no visualization, an empty array is passed) @param [Hash] options the options to use when processing the print information @option options [Integer] :value_max if a value max length is specified, the element values which exceeds this are trimmed @return [Array] a text array and an index of the last element
[ "Gathers", "the", "desired", "information", "from", "the", "selected", "data", "elements", "and", "processes", "this", "information", "to", "make", "a", "text", "output", "which", "is", "nicely", "formatted", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/parent.rb#L298-L364
22,270
dicom/ruby-dicom
lib/dicom/parent.rb
DICOM.Parent.max_lengths
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_generations = max_gc if max_gc > max_generations end n_length = element.name.length l_length = element.length.to_s.length generations = element.parents.length max_name = n_length if n_length > max_name max_length = l_length if l_length > max_length max_generations = generations if generations > max_generations end return max_name, max_length, max_generations end
ruby
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_generations = max_gc if max_gc > max_generations end n_length = element.name.length l_length = element.length.to_s.length generations = element.parents.length max_name = n_length if n_length > max_name max_length = l_length if l_length > max_length max_generations = generations if generations > max_generations end return max_name, max_length, max_generations end
[ "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_generations", "=", "max_gc", "if", "max_gc", ">", "max_generations", "end", "n_length", "=", "element", ".", "name", ".", "length", "l_length", "=", "element", ".", "length", ".", "to_s", ".", "length", "generations", "=", "element", ".", "parents", ".", "length", "max_name", "=", "n_length", "if", "n_length", ">", "max_name", "max_length", "=", "l_length", "if", "l_length", ">", "max_length", "max_generations", "=", "generations", "if", "generations", ">", "max_generations", "end", "return", "max_name", ",", "max_length", ",", "max_generations", "end" ]
Finds and returns the maximum character lengths of name and length which occurs for any child element, as well as the maximum number of generations of elements. @note This method is only intended for internal library use, but for technical reasons (the fact that is called between instances of different classes), can't be made private. The method is used by the print() method to achieve a proper format in its output.
[ "Finds", "and", "returns", "the", "maximum", "character", "lengths", "of", "name", "and", "length", "which", "occurs", "for", "any", "child", "element", "as", "well", "as", "the", "maximum", "number", "of", "generations", "of", "elements", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/parent.rb#L421-L440
22,271
dicom/ruby-dicom
lib/dicom/parent.rb
DICOM.Parent.method_missing
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 == '=' # Assignment: unless args.length==0 || args[0].nil? # What kind of element to create? if tag == 'FFFE,E000' return self.add_item elsif LIBRARY.element(tag).vr == 'SQ' return self.add(Sequence.new(tag)) else return self.add(Element.new(tag, *args)) end else return self.delete(tag) end else # Retrieval: return self[tag] end end # Forward to Object#method_missing: super end
ruby
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 == '=' # Assignment: unless args.length==0 || args[0].nil? # What kind of element to create? if tag == 'FFFE,E000' return self.add_item elsif LIBRARY.element(tag).vr == 'SQ' return self.add(Sequence.new(tag)) else return self.add(Element.new(tag, *args)) end else return self.delete(tag) end else # Retrieval: return self[tag] end end # Forward to Object#method_missing: super end
[ "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", "==", "'='", "# Assignment:", "unless", "args", ".", "length", "==", "0", "||", "args", "[", "0", "]", ".", "nil?", "# What kind of element to create?", "if", "tag", "==", "'FFFE,E000'", "return", "self", ".", "add_item", "elsif", "LIBRARY", ".", "element", "(", "tag", ")", ".", "vr", "==", "'SQ'", "return", "self", ".", "add", "(", "Sequence", ".", "new", "(", "tag", ")", ")", "else", "return", "self", ".", "add", "(", "Element", ".", "new", "(", "tag", ",", "args", ")", ")", "end", "else", "return", "self", ".", "delete", "(", "tag", ")", "end", "else", "# Retrieval:", "return", "self", "[", "tag", "]", "end", "end", "# Forward to Object#method_missing:", "super", "end" ]
Handles missing methods, which in our case is intended to be dynamic method names matching DICOM elements in the dictionary. When a dynamic method name is matched against a DICOM element, this method: * Returns the element if the method name suggests an element retrieval, and the element exists. * Returns nil if the method name suggests an element retrieval, but the element doesn't exist. * Returns a boolean, if the method name suggests a query (?), based on whether the matched element exists or not. * When the method name suggests assignment (=), an element is created with the supplied arguments, or if the argument is nil, the element is deleted. * When a dynamic method name is not matched against a DICOM element, and the method is not defined by the parent, a NoMethodError is raised. @param [Symbol] sym a method name
[ "Handles", "missing", "methods", "which", "in", "our", "case", "is", "intended", "to", "be", "dynamic", "method", "names", "matching", "DICOM", "elements", "in", "the", "dictionary", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/parent.rb#L455-L485
22,272
dicom/ruby-dicom
lib/dicom/parent.rb
DICOM.Parent.print
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 optimized? elements = Array.new # We first gather some properties that is necessary to produce a nicely formatted printout (max_lengths, count_all), # then the actual information is gathered (handle_print), # and lastly, we pass this information on to the methods which print the output (print_file or print_screen). if count > 0 max_name, max_length, max_generations = max_lengths max_digits = count_all.to_s.length visualization = Array.new elements, index = handle_print(start_index=1, max_digits, max_name, max_length, max_generations, visualization, options) if options[:file] print_file(elements, options[:file]) else print_screen(elements) end else puts "Notice: Object #{self} is empty (contains no data elements)!" end return elements end
ruby
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 optimized? elements = Array.new # We first gather some properties that is necessary to produce a nicely formatted printout (max_lengths, count_all), # then the actual information is gathered (handle_print), # and lastly, we pass this information on to the methods which print the output (print_file or print_screen). if count > 0 max_name, max_length, max_generations = max_lengths max_digits = count_all.to_s.length visualization = Array.new elements, index = handle_print(start_index=1, max_digits, max_name, max_length, max_generations, visualization, options) if options[:file] print_file(elements, options[:file]) else print_screen(elements) end else puts "Notice: Object #{self} is empty (contains no data elements)!" end return elements end
[ "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 optimized?", "elements", "=", "Array", ".", "new", "# We first gather some properties that is necessary to produce a nicely formatted printout (max_lengths, count_all),", "# then the actual information is gathered (handle_print),", "# and lastly, we pass this information on to the methods which print the output (print_file or print_screen).", "if", "count", ">", "0", "max_name", ",", "max_length", ",", "max_generations", "=", "max_lengths", "max_digits", "=", "count_all", ".", "to_s", ".", "length", "visualization", "=", "Array", ".", "new", "elements", ",", "index", "=", "handle_print", "(", "start_index", "=", "1", ",", "max_digits", ",", "max_name", ",", "max_length", ",", "max_generations", ",", "visualization", ",", "options", ")", "if", "options", "[", ":file", "]", "print_file", "(", "elements", ",", "options", "[", ":file", "]", ")", "else", "print_screen", "(", "elements", ")", "end", "else", "puts", "\"Notice: Object #{self} is empty (contains no data elements)!\"", "end", "return", "elements", "end" ]
Prints all child elementals of this particular parent. Information such as tag, parent-child relationship, name, vr, length and value is gathered for each element and processed to produce a nicely formatted output. @param [Hash] options the options to use for handling the printout option options [Integer] :value_max if a value max length is specified, the element values which exceeds this are trimmed option options [String] :file if a file path is specified, the output is printed to this file instead of being printed to the screen @return [Array<String>] an array of formatted element string lines @example Print a DObject instance to screen dcm.print @example Print the DObject to the screen, but specify a 25 character value cutoff to produce better-looking results dcm.print(:value_max => 25) @example Print to a text file the elements that belong to a specific Sequence dcm["3006,0020"].print(:file => "dicom.txt")
[ "Prints", "all", "child", "elementals", "of", "this", "particular", "parent", ".", "Information", "such", "as", "tag", "parent", "-", "child", "relationship", "name", "vr", "length", "and", "value", "is", "gathered", "for", "each", "element", "and", "processed", "to", "produce", "a", "nicely", "formatted", "output", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/parent.rb#L502-L523
22,273
dicom/ruby-dicom
lib/dicom/parent.rb
DICOM.Parent.to_hash
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? hash_key = child.tag elsif child.is_a?(Item) hash_key = "Item #{child.index}" else hash_key = child.send(DICOM.key_representation) end if child.is_a?(Element) as_hash[hash_key] = child.to_hash[hash_key] else as_hash[hash_key] = child.to_hash end end end return as_hash end
ruby
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? hash_key = child.tag elsif child.is_a?(Item) hash_key = "Item #{child.index}" else hash_key = child.send(DICOM.key_representation) end if child.is_a?(Element) as_hash[hash_key] = child.to_hash[hash_key] else as_hash[hash_key] = child.to_hash end end end return as_hash end
[ "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?", "hash_key", "=", "child", ".", "tag", "elsif", "child", ".", "is_a?", "(", "Item", ")", "hash_key", "=", "\"Item #{child.index}\"", "else", "hash_key", "=", "child", ".", "send", "(", "DICOM", ".", "key_representation", ")", "end", "if", "child", ".", "is_a?", "(", "Element", ")", "as_hash", "[", "hash_key", "]", "=", "child", ".", "to_hash", "[", "hash_key", "]", "else", "as_hash", "[", "hash_key", "]", "=", "child", ".", "to_hash", "end", "end", "end", "return", "as_hash", "end" ]
Builds a nested hash containing all children of this parent. Keys are determined by the key_representation attribute, and data element values are used as values. * For private elements, the tag is used for key instead of the key representation, as private tags lacks names. * For child-less parents, the key_representation attribute is used as value. @return [Hash] a nested hash containing key & value pairs of all children
[ "Builds", "a", "nested", "hash", "containing", "all", "children", "of", "this", "parent", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/parent.rb#L585-L610
22,274
dicom/ruby-dicom
lib/dicom/parent.rb
DICOM.Parent.value
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 else return nil end end
ruby
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 else return nil end end
[ "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", "else", "return", "nil", "end", "end" ]
Gives the value of a specific Element child of this parent. * Only Element instances have values. Parent elements like Sequence and Item have no value themselves. * If the specified tag is that of a parent element, an exception is raised. @param [String] tag a tag string which identifies the child Element @return [String, Integer, Float, NilClass] an element value (or nil, if no element is matched) @example Get the patient's name value name = dcm.value("0010,0010") @example Get the Frame of Reference UID from the first item in the Referenced Frame of Reference Sequence uid = dcm["3006,0010"][0].value("0020,0052")
[ "Gives", "the", "value", "of", "a", "specific", "Element", "child", "of", "this", "parent", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/parent.rb#L640-L651
22,275
dicom/ruby-dicom
lib/dicom/parent.rb
DICOM.Parent.check_key
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_index}") if tag_or_index < 0 else logger.warn("Parent##{method} called with an unexpected argument. Expected String or Integer, got: #{tag_or_index.class}") end end
ruby
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_index}") if tag_or_index < 0 else logger.warn("Parent##{method} called with an unexpected argument. Expected String or Integer, got: #{tag_or_index.class}") end end
[ "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_index}\"", ")", "if", "tag_or_index", "<", "0", "else", "logger", ".", "warn", "(", "\"Parent##{method} called with an unexpected argument. Expected String or Integer, got: #{tag_or_index.class}\"", ")", "end", "end" ]
Checks the given key argument and logs a warning if an obviously incorrect key argument is used. @param [String, Integer] tag_or_index the tag string or item index indentifying a given elemental @param [Symbol] method a representation of the method calling this method
[ "Checks", "the", "given", "key", "argument", "and", "logs", "a", "warning", "if", "an", "obviously", "incorrect", "key", "argument", "is", "used", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/parent.rb#L663-L671
22,276
dicom/ruby-dicom
lib/dicom/link.rb
DICOM.Link.await_release
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]}). Expected a release request. Closing the connection.") handle_abort(false) else logger.error("Timed out while waiting for a release request. Closing the connection.") end stop_session else # Properly release the association: handle_release end end
ruby
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]}). Expected a release request. Closing the connection.") handle_abort(false) else logger.error("Timed out while waiting for a release request. Closing the connection.") end stop_session else # Properly release the association: handle_release end end
[ "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]}). Expected a release request. Closing the connection.\"", ")", "handle_abort", "(", "false", ")", "else", "logger", ".", "error", "(", "\"Timed out while waiting for a release request. Closing the connection.\"", ")", "end", "stop_session", "else", "# Properly release the association:", "handle_release", "end", "end" ]
Creates a Link instance, which is used by both DClient and DServer to handle network communication. === Parameters * <tt>options</tt> -- A hash of parameters. === Options * <tt>:ae</tt> -- String. The name of the client (application entity). * <tt>:file_handler</tt> -- A customized FileHandler class to use instead of the default FileHandler. * <tt>:host_ae</tt> -- String. The name of the server (application entity). * <tt>:max_package_size</tt> -- Integer. The maximum allowed size of network packages (in bytes). * <tt>:timeout</tt> -- Integer. The maximum period to wait for an answer before aborting the communication. Waits for an SCU to issue a release request, and answers it by launching the handle_release method. If invalid or no message is received, the connection is closed.
[ "Creates", "a", "Link", "instance", "which", "is", "used", "by", "both", "DClient", "and", "DServer", "to", "handle", "network", "communication", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/link.rb#L57-L73
22,277
dicom/ruby-dicom
lib/dicom/link.rb
DICOM.Link.build_association_request
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 appearance', the header is built last, but is put first in the message) append_application_context append_presentation_contexts(presentation_contexts, ITEM_PRESENTATION_CONTEXT_REQUEST, request=true) append_user_information(user_info) # Header must be built last, because we need to know the length of the other components. append_association_header(PDU_ASSOCIATION_REQUEST, @host_ae) end
ruby
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 appearance', the header is built last, but is put first in the message) append_application_context append_presentation_contexts(presentation_contexts, ITEM_PRESENTATION_CONTEXT_REQUEST, request=true) append_user_information(user_info) # Header must be built last, because we need to know the length of the other components. append_association_header(PDU_ASSOCIATION_REQUEST, @host_ae) end
[ "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 appearance', the header is built last, but is put first in the message)", "append_application_context", "append_presentation_contexts", "(", "presentation_contexts", ",", "ITEM_PRESENTATION_CONTEXT_REQUEST", ",", "request", "=", "true", ")", "append_user_information", "(", "user_info", ")", "# Header must be built last, because we need to know the length of the other components.", "append_association_header", "(", "PDU_ASSOCIATION_REQUEST", ",", "@host_ae", ")", "end" ]
Builds the binary string which is sent as the association request. === Parameters * <tt>presentation_contexts</tt> -- A hash containing abstract_syntaxes, presentation context ids and transfer syntaxes. * <tt>user_info</tt> -- A user information items array.
[ "Builds", "the", "binary", "string", "which", "is", "sent", "as", "the", "association", "request", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/link.rb#L167-L179
22,278
dicom/ruby-dicom
lib/dicom/link.rb
DICOM.Link.build_command_fragment
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) @outgoing.add_last(@outgoing.encode_tag(element[0])) # Encode the value first, so we know its length: value = @outgoing.encode_value(element[2], element[1]) # Length (2 bytes) @outgoing.encode_last(value.length, "US") # Reserved (2 bytes) @outgoing.encode_last("0000", "HEX") # Value (variable length) @outgoing.add_last(value) end # The rest of the command fragment will be buildt in reverse, all the time # putting the elements first in the outgoing binary string. # Group length item: # Value (4 bytes) @outgoing.encode_first(@outgoing.string.length, "UL") # Reserved (2 bytes) @outgoing.encode_first("0000", "HEX") # Length (2 bytes) @outgoing.encode_first(4, "US") # Tag (4 bytes) @outgoing.add_first(@outgoing.encode_tag("0000,0000")) # Big endian encoding from now on: @outgoing.endian = @net_endian # Flags (1 byte) @outgoing.encode_first(flags, "HEX") # Presentation context ID (1 byte) @outgoing.encode_first(context, "BY") # Length (of remaining data) (4 bytes) @outgoing.encode_first(@outgoing.string.length, "UL") # PRESENTATION DATA VALUE (the above) append_header(pdu) end
ruby
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) @outgoing.add_last(@outgoing.encode_tag(element[0])) # Encode the value first, so we know its length: value = @outgoing.encode_value(element[2], element[1]) # Length (2 bytes) @outgoing.encode_last(value.length, "US") # Reserved (2 bytes) @outgoing.encode_last("0000", "HEX") # Value (variable length) @outgoing.add_last(value) end # The rest of the command fragment will be buildt in reverse, all the time # putting the elements first in the outgoing binary string. # Group length item: # Value (4 bytes) @outgoing.encode_first(@outgoing.string.length, "UL") # Reserved (2 bytes) @outgoing.encode_first("0000", "HEX") # Length (2 bytes) @outgoing.encode_first(4, "US") # Tag (4 bytes) @outgoing.add_first(@outgoing.encode_tag("0000,0000")) # Big endian encoding from now on: @outgoing.endian = @net_endian # Flags (1 byte) @outgoing.encode_first(flags, "HEX") # Presentation context ID (1 byte) @outgoing.encode_first(context, "BY") # Length (of remaining data) (4 bytes) @outgoing.encode_first(@outgoing.string.length, "UL") # PRESENTATION DATA VALUE (the above) append_header(pdu) end
[ "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)", "@outgoing", ".", "add_last", "(", "@outgoing", ".", "encode_tag", "(", "element", "[", "0", "]", ")", ")", "# Encode the value first, so we know its length:", "value", "=", "@outgoing", ".", "encode_value", "(", "element", "[", "2", "]", ",", "element", "[", "1", "]", ")", "# Length (2 bytes)", "@outgoing", ".", "encode_last", "(", "value", ".", "length", ",", "\"US\"", ")", "# Reserved (2 bytes)", "@outgoing", ".", "encode_last", "(", "\"0000\"", ",", "\"HEX\"", ")", "# Value (variable length)", "@outgoing", ".", "add_last", "(", "value", ")", "end", "# The rest of the command fragment will be buildt in reverse, all the time", "# putting the elements first in the outgoing binary string.", "# Group length item:", "# Value (4 bytes)", "@outgoing", ".", "encode_first", "(", "@outgoing", ".", "string", ".", "length", ",", "\"UL\"", ")", "# Reserved (2 bytes)", "@outgoing", ".", "encode_first", "(", "\"0000\"", ",", "\"HEX\"", ")", "# Length (2 bytes)", "@outgoing", ".", "encode_first", "(", "4", ",", "\"US\"", ")", "# Tag (4 bytes)", "@outgoing", ".", "add_first", "(", "@outgoing", ".", "encode_tag", "(", "\"0000,0000\"", ")", ")", "# Big endian encoding from now on:", "@outgoing", ".", "endian", "=", "@net_endian", "# Flags (1 byte)", "@outgoing", ".", "encode_first", "(", "flags", ",", "\"HEX\"", ")", "# Presentation context ID (1 byte)", "@outgoing", ".", "encode_first", "(", "context", ",", "\"BY\"", ")", "# Length (of remaining data) (4 bytes)", "@outgoing", ".", "encode_first", "(", "@outgoing", ".", "string", ".", "length", ",", "\"UL\"", ")", "# PRESENTATION DATA VALUE (the above)", "append_header", "(", "pdu", ")", "end" ]
Builds the binary string which is sent as a command fragment. === Parameters * <tt>pdu</tt> -- The command fragment's PDU string. * <tt>context</tt> -- Presentation context ID byte (references a presentation context from the association). * <tt>flags</tt> -- The flag string, which identifies if this is the last command fragment or not. * <tt>command_elements</tt> -- An array of command elements.
[ "Builds", "the", "binary", "string", "which", "is", "sent", "as", "a", "command", "fragment", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/link.rb#L190-L229
22,279
dicom/ruby-dicom
lib/dicom/link.rb
DICOM.Link.build_data_fragment
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 binary string: @outgoing.reset # Build the last part first, the Data items: data_elements.each do |element| # Encode all tags (even tags which are empty): # Tag (4 bytes) @outgoing.add_last(@outgoing.encode_tag(element[0])) # Encode the value in advance of putting it into the message, so we know its length: vr = LIBRARY.element(element[0]).vr value = @outgoing.encode_value(element[1], vr) if @explicit # Type (VR) (2 bytes) @outgoing.encode_last(vr, "STR") # Length (2 bytes) @outgoing.encode_last(value.length, "US") else # Implicit: # Length (4 bytes) @outgoing.encode_last(value.length, "UL") end # Value (variable length) @outgoing.add_last(value) end # The rest of the data fragment will be built in reverse, all the time # putting the elements first in the outgoing binary string. # Big endian encoding from now on: @outgoing.endian = @net_endian # Flags (1 byte) @outgoing.encode_first("02", "HEX") # Data, last fragment (identifier) # Presentation context ID (1 byte) @outgoing.encode_first(presentation_context_id, "BY") # Length (of remaining data) (4 bytes) @outgoing.encode_first(@outgoing.string.length, "UL") # PRESENTATION DATA VALUE (the above) append_header(PDU_DATA) end
ruby
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 binary string: @outgoing.reset # Build the last part first, the Data items: data_elements.each do |element| # Encode all tags (even tags which are empty): # Tag (4 bytes) @outgoing.add_last(@outgoing.encode_tag(element[0])) # Encode the value in advance of putting it into the message, so we know its length: vr = LIBRARY.element(element[0]).vr value = @outgoing.encode_value(element[1], vr) if @explicit # Type (VR) (2 bytes) @outgoing.encode_last(vr, "STR") # Length (2 bytes) @outgoing.encode_last(value.length, "US") else # Implicit: # Length (4 bytes) @outgoing.encode_last(value.length, "UL") end # Value (variable length) @outgoing.add_last(value) end # The rest of the data fragment will be built in reverse, all the time # putting the elements first in the outgoing binary string. # Big endian encoding from now on: @outgoing.endian = @net_endian # Flags (1 byte) @outgoing.encode_first("02", "HEX") # Data, last fragment (identifier) # Presentation context ID (1 byte) @outgoing.encode_first(presentation_context_id, "BY") # Length (of remaining data) (4 bytes) @outgoing.encode_first(@outgoing.string.length, "UL") # PRESENTATION DATA VALUE (the above) append_header(PDU_DATA) end
[ "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 binary string:", "@outgoing", ".", "reset", "# Build the last part first, the Data items:", "data_elements", ".", "each", "do", "|", "element", "|", "# Encode all tags (even tags which are empty):", "# Tag (4 bytes)", "@outgoing", ".", "add_last", "(", "@outgoing", ".", "encode_tag", "(", "element", "[", "0", "]", ")", ")", "# Encode the value in advance of putting it into the message, so we know its length:", "vr", "=", "LIBRARY", ".", "element", "(", "element", "[", "0", "]", ")", ".", "vr", "value", "=", "@outgoing", ".", "encode_value", "(", "element", "[", "1", "]", ",", "vr", ")", "if", "@explicit", "# Type (VR) (2 bytes)", "@outgoing", ".", "encode_last", "(", "vr", ",", "\"STR\"", ")", "# Length (2 bytes)", "@outgoing", ".", "encode_last", "(", "value", ".", "length", ",", "\"US\"", ")", "else", "# Implicit:", "# Length (4 bytes)", "@outgoing", ".", "encode_last", "(", "value", ".", "length", ",", "\"UL\"", ")", "end", "# Value (variable length)", "@outgoing", ".", "add_last", "(", "value", ")", "end", "# The rest of the data fragment will be built in reverse, all the time", "# putting the elements first in the outgoing binary string.", "# Big endian encoding from now on:", "@outgoing", ".", "endian", "=", "@net_endian", "# Flags (1 byte)", "@outgoing", ".", "encode_first", "(", "\"02\"", ",", "\"HEX\"", ")", "# Data, last fragment (identifier)", "# Presentation context ID (1 byte)", "@outgoing", ".", "encode_first", "(", "presentation_context_id", ",", "\"BY\"", ")", "# Length (of remaining data) (4 bytes)", "@outgoing", ".", "encode_first", "(", "@outgoing", ".", "string", ".", "length", ",", "\"UL\"", ")", "# PRESENTATION DATA VALUE (the above)", "append_header", "(", "PDU_DATA", ")", "end" ]
Builds the binary string which is sent as a data fragment. === Notes * The style of encoding will depend on whether we have an implicit or explicit transfer syntax. === Parameters * <tt>data_elements</tt> -- An array of data elements. * <tt>presentation_context_id</tt> -- Presentation context ID byte (references a presentation context from the association).
[ "Builds", "the", "binary", "string", "which", "is", "sent", "as", "a", "data", "fragment", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/link.rb#L242-L282
22,280
dicom/ruby-dicom
lib/dicom/link.rb
DICOM.Link.build_storage_fragment
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) # Flags (1 byte) @outgoing.encode_first(flags, "HEX") # Context ID (1 byte) @outgoing.encode_first(context, "BY") # PDV Length (of remaining data) (4 bytes) @outgoing.encode_first(@outgoing.string.length, "UL") # PRESENTATION DATA VALUE (the above) append_header(pdu) end
ruby
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) # Flags (1 byte) @outgoing.encode_first(flags, "HEX") # Context ID (1 byte) @outgoing.encode_first(context, "BY") # PDV Length (of remaining data) (4 bytes) @outgoing.encode_first(@outgoing.string.length, "UL") # PRESENTATION DATA VALUE (the above) append_header(pdu) end
[ "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", ")", "# Flags (1 byte)", "@outgoing", ".", "encode_first", "(", "flags", ",", "\"HEX\"", ")", "# Context ID (1 byte)", "@outgoing", ".", "encode_first", "(", "context", ",", "\"BY\"", ")", "# PDV Length (of remaining data) (4 bytes)", "@outgoing", ".", "encode_first", "(", "@outgoing", ".", "string", ".", "length", ",", "\"UL\"", ")", "# PRESENTATION DATA VALUE (the above)", "append_header", "(", "pdu", ")", "end" ]
Builds the binary string which makes up a C-STORE data fragment. === Parameters * <tt>pdu</tt> -- The data fragment's PDU string. * <tt>context</tt> -- Presentation context ID byte (references a presentation context from the association). * <tt>flags</tt> -- The flag string, which identifies if this is the last data fragment or not. * <tt>body</tt> -- A pre-encoded binary string (typicall a segment of a DICOM file to be transmitted).
[ "Builds", "the", "binary", "string", "which", "makes", "up", "a", "C", "-", "STORE", "data", "fragment", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/link.rb#L317-L333
22,281
dicom/ruby-dicom
lib/dicom/link.rb
DICOM.Link.forward_to_interpret
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_association_reject(message) when PDU_DATA info = interpret_command_and_data(message, file) when PDU_RELEASE_REQUEST info = interpret_release_request(message) when PDU_RELEASE_RESPONSE info = interpret_release_response(message) when PDU_ABORT info = interpret_abort(message) else info = {:valid => false} logger.error("An unknown PDU type was received in the incoming transmission. Can not decode this message. (PDU: #{pdu})") end return info end
ruby
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_association_reject(message) when PDU_DATA info = interpret_command_and_data(message, file) when PDU_RELEASE_REQUEST info = interpret_release_request(message) when PDU_RELEASE_RESPONSE info = interpret_release_response(message) when PDU_ABORT info = interpret_abort(message) else info = {:valid => false} logger.error("An unknown PDU type was received in the incoming transmission. Can not decode this message. (PDU: #{pdu})") end return info end
[ "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_association_reject", "(", "message", ")", "when", "PDU_DATA", "info", "=", "interpret_command_and_data", "(", "message", ",", "file", ")", "when", "PDU_RELEASE_REQUEST", "info", "=", "interpret_release_request", "(", "message", ")", "when", "PDU_RELEASE_RESPONSE", "info", "=", "interpret_release_response", "(", "message", ")", "when", "PDU_ABORT", "info", "=", "interpret_abort", "(", "message", ")", "else", "info", "=", "{", ":valid", "=>", "false", "}", "logger", ".", "error", "(", "\"An unknown PDU type was received in the incoming transmission. Can not decode this message. (PDU: #{pdu})\"", ")", "end", "return", "info", "end" ]
Delegates an incoming message to its appropriate interpreter method, based on its pdu type. Returns the interpreted information hash. === Parameters * <tt>message</tt> -- The binary message string. * <tt>pdu</tt> -- The PDU string of the message. * <tt>file</tt> -- A boolean used to inform whether an incoming data fragment is part of a DICOM file reception or not.
[ "Delegates", "an", "incoming", "message", "to", "its", "appropriate", "interpreter", "method", "based", "on", "its", "pdu", "type", ".", "Returns", "the", "interpreted", "information", "hash", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/link.rb#L344-L365
22,282
dicom/ruby-dicom
lib/dicom/link.rb
DICOM.Link.handle_incoming_data
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 = Array.new # Proceed to extract data from the captured segments: segments.each do |info| if info[:valid] # Determine if it is command or data: if info[:presentation_context_flag] == DATA_MORE_FRAGMENTS @data_results << info[:results] single_file_data << info[:bin] elsif info[:presentation_context_flag] == DATA_LAST_FRAGMENT @data_results << info[:results] single_file_data << info[:bin] # Join the recorded data binary strings together to make a DICOM file binary string and put it in our files Array: files << single_file_data.join single_file_data = Array.new elsif info[:presentation_context_flag] == COMMAND_LAST_FRAGMENT @command_results << info[:results] @presentation_context_id = info[:presentation_context_id] # Does this actually do anything useful? file_transfer_syntaxes << @presentation_contexts[info[:presentation_context_id]] end end end # Process the received files using the customizable FileHandler class: success, messages = @file_handler.receive_files(path, files, file_transfer_syntaxes) return success, messages end
ruby
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 = Array.new # Proceed to extract data from the captured segments: segments.each do |info| if info[:valid] # Determine if it is command or data: if info[:presentation_context_flag] == DATA_MORE_FRAGMENTS @data_results << info[:results] single_file_data << info[:bin] elsif info[:presentation_context_flag] == DATA_LAST_FRAGMENT @data_results << info[:results] single_file_data << info[:bin] # Join the recorded data binary strings together to make a DICOM file binary string and put it in our files Array: files << single_file_data.join single_file_data = Array.new elsif info[:presentation_context_flag] == COMMAND_LAST_FRAGMENT @command_results << info[:results] @presentation_context_id = info[:presentation_context_id] # Does this actually do anything useful? file_transfer_syntaxes << @presentation_contexts[info[:presentation_context_id]] end end end # Process the received files using the customizable FileHandler class: success, messages = @file_handler.receive_files(path, files, file_transfer_syntaxes) return success, messages end
[ "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", "=", "Array", ".", "new", "# Proceed to extract data from the captured segments:", "segments", ".", "each", "do", "|", "info", "|", "if", "info", "[", ":valid", "]", "# Determine if it is command or data:", "if", "info", "[", ":presentation_context_flag", "]", "==", "DATA_MORE_FRAGMENTS", "@data_results", "<<", "info", "[", ":results", "]", "single_file_data", "<<", "info", "[", ":bin", "]", "elsif", "info", "[", ":presentation_context_flag", "]", "==", "DATA_LAST_FRAGMENT", "@data_results", "<<", "info", "[", ":results", "]", "single_file_data", "<<", "info", "[", ":bin", "]", "# Join the recorded data binary strings together to make a DICOM file binary string and put it in our files Array:", "files", "<<", "single_file_data", ".", "join", "single_file_data", "=", "Array", ".", "new", "elsif", "info", "[", ":presentation_context_flag", "]", "==", "COMMAND_LAST_FRAGMENT", "@command_results", "<<", "info", "[", ":results", "]", "@presentation_context_id", "=", "info", "[", ":presentation_context_id", "]", "# Does this actually do anything useful?", "file_transfer_syntaxes", "<<", "@presentation_contexts", "[", "info", "[", ":presentation_context_id", "]", "]", "end", "end", "end", "# Process the received files using the customizable FileHandler class:", "success", ",", "messages", "=", "@file_handler", ".", "receive_files", "(", "path", ",", "files", ",", "file_transfer_syntaxes", ")", "return", "success", ",", "messages", "end" ]
Processes incoming command & data fragments for the DServer. Returns a success boolean and an array of status messages. === Notes The incoming traffic will in most cases be: A C-STORE-RQ (command fragment) followed by a bunch of data fragments. However, it may also be a C-ECHO-RQ command fragment, which is used to test connections. === Parameters * <tt>path</tt> -- The path used to save incoming DICOM files. -- FIXME: The code which handles incoming data isnt quite satisfactory. It would probably be wise to rewrite it at some stage to clean up the code somewhat. Probably a better handling of command requests (and their corresponding data fragments) would be a good idea.
[ "Processes", "incoming", "command", "&", "data", "fragments", "for", "the", "DServer", ".", "Returns", "a", "success", "boolean", "and", "an", "array", "of", "status", "messages", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/link.rb#L410-L442
22,283
dicom/ruby-dicom
lib/dicom/link.rb
DICOM.Link.handle_response
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["0000,0100"])] # Message ID Being Responded To: command_elements << ["0000,0120", "US", @command_request["0000,0110"]] # Data Set Type: command_elements << ["0000,0800", "US", NO_DATA_SET_PRESENT] # Status: command_elements << ["0000,0900", "US", SUCCESS] # Affected SOP Instance UID: command_elements << ["0000,1000", "UI", @command_request["0000,1000"]] if @command_request["0000,1000"] build_command_fragment(PDU_DATA, @presentation_context_id, COMMAND_LAST_FRAGMENT, command_elements) transmit end
ruby
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["0000,0100"])] # Message ID Being Responded To: command_elements << ["0000,0120", "US", @command_request["0000,0110"]] # Data Set Type: command_elements << ["0000,0800", "US", NO_DATA_SET_PRESENT] # Status: command_elements << ["0000,0900", "US", SUCCESS] # Affected SOP Instance UID: command_elements << ["0000,1000", "UI", @command_request["0000,1000"]] if @command_request["0000,1000"] build_command_fragment(PDU_DATA, @presentation_context_id, COMMAND_LAST_FRAGMENT, command_elements) transmit end
[ "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", "[", "\"0000,0100\"", "]", ")", "]", "# Message ID Being Responded To:", "command_elements", "<<", "[", "\"0000,0120\"", ",", "\"US\"", ",", "@command_request", "[", "\"0000,0110\"", "]", "]", "# Data Set Type:", "command_elements", "<<", "[", "\"0000,0800\"", ",", "\"US\"", ",", "NO_DATA_SET_PRESENT", "]", "# Status:", "command_elements", "<<", "[", "\"0000,0900\"", ",", "\"US\"", ",", "SUCCESS", "]", "# Affected SOP Instance UID:", "command_elements", "<<", "[", "\"0000,1000\"", ",", "\"UI\"", ",", "@command_request", "[", "\"0000,1000\"", "]", "]", "if", "@command_request", "[", "\"0000,1000\"", "]", "build_command_fragment", "(", "PDU_DATA", ",", "@presentation_context_id", ",", "COMMAND_LAST_FRAGMENT", ",", "command_elements", ")", "transmit", "end" ]
Handles the command fragment response. === Notes This is usually a C-STORE-RSP which follows the (successful) reception of a DICOM file, but may also be a C-ECHO-RSP in response to an echo request.
[ "Handles", "the", "command", "fragment", "response", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/link.rb#L472-L489
22,284
dicom/ruby-dicom
lib/dicom/link.rb
DICOM.Link.interpret
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. msg = Stream.new(message, @net_endian) # PDU type ( 1 byte) pdu = msg.decode(1, "HEX") # Reserved (1 byte) msg.skip(1) # Length of remaining data (4 bytes) specified_length = msg.decode(4, "UL") # Analyze the remaining length of the message versurs the specified_length value: if msg.rest_length > specified_length # If the remaining length of the string itself is bigger than this specified_length value, # then it seems that we have another message appended in our incoming transmission. fragment = msg.extract(specified_length) info = forward_to_interpret(fragment, pdu, file) info[:pdu] = pdu segments << info # It is possible that a fragment contains both a command and a data fragment. If so, we need to make sure we collect all the information: if info[:rest_string] additional_info = forward_to_interpret(info[:rest_string], pdu, file) segments << additional_info end # The information gathered from the interpretation is appended to a segments array, # and in the case of a recursive call some special logic is needed to build this array in the expected fashion. remaining_segments = interpret(msg.rest_string, file) remaining_segments.each do |remaining| segments << remaining end elsif msg.rest_length == specified_length # Proceed to analyze the rest of the message: fragment = msg.extract(specified_length) info = forward_to_interpret(fragment, pdu, file) info[:pdu] = pdu segments << info # It is possible that a fragment contains both a command and a data fragment. If so, we need to make sure we collect all the information: if info[:rest_string] additional_info = forward_to_interpret(info[:rest_string], pdu, file) segments << additional_info end else # Length of the message is less than what is specified in the message. Need to listen for more. This is hopefully handled properly now. #logger.error("Error. The length of the received message (#{msg.rest_length}) is smaller than what it claims (#{specified_length}). Aborting.") @first_part = msg.string end else # Assume that this is only the start of the message, and add it to the next incoming string: @first_part = message end return segments end
ruby
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. msg = Stream.new(message, @net_endian) # PDU type ( 1 byte) pdu = msg.decode(1, "HEX") # Reserved (1 byte) msg.skip(1) # Length of remaining data (4 bytes) specified_length = msg.decode(4, "UL") # Analyze the remaining length of the message versurs the specified_length value: if msg.rest_length > specified_length # If the remaining length of the string itself is bigger than this specified_length value, # then it seems that we have another message appended in our incoming transmission. fragment = msg.extract(specified_length) info = forward_to_interpret(fragment, pdu, file) info[:pdu] = pdu segments << info # It is possible that a fragment contains both a command and a data fragment. If so, we need to make sure we collect all the information: if info[:rest_string] additional_info = forward_to_interpret(info[:rest_string], pdu, file) segments << additional_info end # The information gathered from the interpretation is appended to a segments array, # and in the case of a recursive call some special logic is needed to build this array in the expected fashion. remaining_segments = interpret(msg.rest_string, file) remaining_segments.each do |remaining| segments << remaining end elsif msg.rest_length == specified_length # Proceed to analyze the rest of the message: fragment = msg.extract(specified_length) info = forward_to_interpret(fragment, pdu, file) info[:pdu] = pdu segments << info # It is possible that a fragment contains both a command and a data fragment. If so, we need to make sure we collect all the information: if info[:rest_string] additional_info = forward_to_interpret(info[:rest_string], pdu, file) segments << additional_info end else # Length of the message is less than what is specified in the message. Need to listen for more. This is hopefully handled properly now. #logger.error("Error. The length of the received message (#{msg.rest_length}) is smaller than what it claims (#{specified_length}). Aborting.") @first_part = msg.string end else # Assume that this is only the start of the message, and add it to the next incoming string: @first_part = message end return segments end
[ "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.", "msg", "=", "Stream", ".", "new", "(", "message", ",", "@net_endian", ")", "# PDU type ( 1 byte)", "pdu", "=", "msg", ".", "decode", "(", "1", ",", "\"HEX\"", ")", "# Reserved (1 byte)", "msg", ".", "skip", "(", "1", ")", "# Length of remaining data (4 bytes)", "specified_length", "=", "msg", ".", "decode", "(", "4", ",", "\"UL\"", ")", "# Analyze the remaining length of the message versurs the specified_length value:", "if", "msg", ".", "rest_length", ">", "specified_length", "# If the remaining length of the string itself is bigger than this specified_length value,", "# then it seems that we have another message appended in our incoming transmission.", "fragment", "=", "msg", ".", "extract", "(", "specified_length", ")", "info", "=", "forward_to_interpret", "(", "fragment", ",", "pdu", ",", "file", ")", "info", "[", ":pdu", "]", "=", "pdu", "segments", "<<", "info", "# It is possible that a fragment contains both a command and a data fragment. If so, we need to make sure we collect all the information:", "if", "info", "[", ":rest_string", "]", "additional_info", "=", "forward_to_interpret", "(", "info", "[", ":rest_string", "]", ",", "pdu", ",", "file", ")", "segments", "<<", "additional_info", "end", "# The information gathered from the interpretation is appended to a segments array,", "# and in the case of a recursive call some special logic is needed to build this array in the expected fashion.", "remaining_segments", "=", "interpret", "(", "msg", ".", "rest_string", ",", "file", ")", "remaining_segments", ".", "each", "do", "|", "remaining", "|", "segments", "<<", "remaining", "end", "elsif", "msg", ".", "rest_length", "==", "specified_length", "# Proceed to analyze the rest of the message:", "fragment", "=", "msg", ".", "extract", "(", "specified_length", ")", "info", "=", "forward_to_interpret", "(", "fragment", ",", "pdu", ",", "file", ")", "info", "[", ":pdu", "]", "=", "pdu", "segments", "<<", "info", "# It is possible that a fragment contains both a command and a data fragment. If so, we need to make sure we collect all the information:", "if", "info", "[", ":rest_string", "]", "additional_info", "=", "forward_to_interpret", "(", "info", "[", ":rest_string", "]", ",", "pdu", ",", "file", ")", "segments", "<<", "additional_info", "end", "else", "# Length of the message is less than what is specified in the message. Need to listen for more. This is hopefully handled properly now.", "#logger.error(\"Error. The length of the received message (#{msg.rest_length}) is smaller than what it claims (#{specified_length}). Aborting.\")", "@first_part", "=", "msg", ".", "string", "end", "else", "# Assume that this is only the start of the message, and add it to the next incoming string:", "@first_part", "=", "message", "end", "return", "segments", "end" ]
Decodes the header of an incoming message, analyzes its real length versus expected length, and handles any deviations to make sure that message strings are split up appropriately before they are being forwarded to interpretation. Returns an array of information hashes. === Parameters * <tt>message</tt> -- The binary message string. * <tt>file</tt> -- A boolean used to inform whether an incoming data fragment is part of a DICOM file reception or not. -- FIXME: This method is rather complex and doesnt feature the best readability. A rewrite that is able to simplify it would be lovely.
[ "Decodes", "the", "header", "of", "an", "incoming", "message", "analyzes", "its", "real", "length", "versus", "expected", "length", "and", "handles", "any", "deviations", "to", "make", "sure", "that", "message", "strings", "are", "split", "up", "appropriately", "before", "they", "are", "being", "forwarded", "to", "interpretation", ".", "Returns", "an", "array", "of", "information", "hashes", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/link.rb#L503-L559
22,285
dicom/ruby-dicom
lib/dicom/link.rb
DICOM.Link.interpret_abort
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 results: process_source(info[:source]) process_reason(info[:reason]) stop_receiving @abort = true info[:valid] = true return info end
ruby
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 results: process_source(info[:source]) process_reason(info[:reason]) stop_receiving @abort = true info[:valid] = true return info end
[ "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 results:", "process_source", "(", "info", "[", ":source", "]", ")", "process_reason", "(", "info", "[", ":reason", "]", ")", "stop_receiving", "@abort", "=", "true", "info", "[", ":valid", "]", "=", "true", "return", "info", "end" ]
Decodes the message received when the remote node wishes to abort the session. Returns the processed information hash. === Parameters * <tt>message</tt> -- The binary message string.
[ "Decodes", "the", "message", "received", "when", "the", "remote", "node", "wishes", "to", "abort", "the", "session", ".", "Returns", "the", "processed", "information", "hash", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/link.rb#L568-L584
22,286
dicom/ruby-dicom
lib/dicom/link.rb
DICOM.Link.interpret_association_reject
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.decode(1, "BY") # Reason (1 byte) info[:reason] = msg.decode(1, "BY") logger.warn("ASSOCIATE Request was rejected by the host. Error codes: Result: #{info[:result]}, Source: #{info[:source]}, Reason: #{info[:reason]} (See DICOM PS3.8: Table 9-21 for details.)") stop_receiving info[:valid] = true return info end
ruby
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.decode(1, "BY") # Reason (1 byte) info[:reason] = msg.decode(1, "BY") logger.warn("ASSOCIATE Request was rejected by the host. Error codes: Result: #{info[:result]}, Source: #{info[:source]}, Reason: #{info[:reason]} (See DICOM PS3.8: Table 9-21 for details.)") stop_receiving info[:valid] = true return info end
[ "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", ".", "decode", "(", "1", ",", "\"BY\"", ")", "# Reason (1 byte)", "info", "[", ":reason", "]", "=", "msg", ".", "decode", "(", "1", ",", "\"BY\"", ")", "logger", ".", "warn", "(", "\"ASSOCIATE Request was rejected by the host. Error codes: Result: #{info[:result]}, Source: #{info[:source]}, Reason: #{info[:reason]} (See DICOM PS3.8: Table 9-21 for details.)\"", ")", "stop_receiving", "info", "[", ":valid", "]", "=", "true", "return", "info", "end" ]
Decodes the association reject message and extracts the error reasons given. Returns the processed information hash. === Parameters * <tt>message</tt> -- The binary message string.
[ "Decodes", "the", "association", "reject", "message", "and", "extracts", "the", "error", "reasons", "given", ".", "Returns", "the", "processed", "information", "hash", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/link.rb#L716-L731
22,287
dicom/ruby-dicom
lib/dicom/link.rb
DICOM.Link.interpret_release_request
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
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
[ "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" ]
Decodes the message received in the release request and calls the handle_release method. Returns the processed information hash. === Parameters * <tt>message</tt> -- The binary message string.
[ "Decodes", "the", "message", "received", "in", "the", "release", "request", "and", "calls", "the", "handle_release", "method", ".", "Returns", "the", "processed", "information", "hash", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/link.rb#L999-L1007
22,288
dicom/ruby-dicom
lib/dicom/link.rb
DICOM.Link.interpret_release_response
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
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
[ "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" ]
Decodes the message received in the release response and closes the connection. Returns the processed information hash. === Parameters * <tt>message</tt> -- The binary message string.
[ "Decodes", "the", "message", "received", "in", "the", "release", "response", "and", "closes", "the", "connection", ".", "Returns", "the", "processed", "information", "hash", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/link.rb#L1016-L1024
22,289
dicom/ruby-dicom
lib/dicom/link.rb
DICOM.Link.receive_multiple_transmissions
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 append the current data to our segments array, which will be returned. data = receive_transmission(@min_length) current_segments = interpret(data, file) if current_segments current_segments.each do |cs| segments << cs end end end segments << {:valid => false} unless segments return segments end
ruby
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 append the current data to our segments array, which will be returned. data = receive_transmission(@min_length) current_segments = interpret(data, file) if current_segments current_segments.each do |cs| segments << cs end end end segments << {:valid => false} unless segments return segments end
[ "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 append the current data to our segments array, which will be returned.", "data", "=", "receive_transmission", "(", "@min_length", ")", "current_segments", "=", "interpret", "(", "data", ",", "file", ")", "if", "current_segments", "current_segments", ".", "each", "do", "|", "cs", "|", "segments", "<<", "cs", "end", "end", "end", "segments", "<<", "{", ":valid", "=>", "false", "}", "unless", "segments", "return", "segments", "end" ]
Handles the reception of multiple incoming transmissions. Returns an array of interpreted message information hashes. === Parameters * <tt>file</tt> -- A boolean used to inform whether an incoming data fragment is part of a DICOM file reception or not.
[ "Handles", "the", "reception", "of", "multiple", "incoming", "transmissions", ".", "Returns", "an", "array", "of", "interpreted", "message", "information", "hashes", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/link.rb#L1033-L1051
22,290
dicom/ruby-dicom
lib/dicom/link.rb
DICOM.Link.receive_single_transmission
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
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
[ "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" ]
Handles the reception of a single, expected incoming transmission and returns the interpreted, received data.
[ "Handles", "the", "reception", "of", "a", "single", "expected", "incoming", "transmission", "and", "returns", "the", "interpreted", "received", "data", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/link.rb#L1055-L1061
22,291
dicom/ruby-dicom
lib/dicom/link.rb
DICOM.Link.process_reason
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") when "04" logger.error("Reason specified for abort: Unrecognized PDU parameter") when "05" logger.error("Reason specified for abort: Unexpected PDU parameter") when "06" logger.error("Reason specified for abort: Invalid PDU parameter value") else logger.error("Reason specified for abort: Unknown reason (Error code: #{reason})") end end
ruby
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") when "04" logger.error("Reason specified for abort: Unrecognized PDU parameter") when "05" logger.error("Reason specified for abort: Unexpected PDU parameter") when "06" logger.error("Reason specified for abort: Invalid PDU parameter value") else logger.error("Reason specified for abort: Unknown reason (Error code: #{reason})") end end
[ "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\"", ")", "when", "\"04\"", "logger", ".", "error", "(", "\"Reason specified for abort: Unrecognized PDU parameter\"", ")", "when", "\"05\"", "logger", ".", "error", "(", "\"Reason specified for abort: Unexpected PDU parameter\"", ")", "when", "\"06\"", "logger", ".", "error", "(", "\"Reason specified for abort: Invalid PDU parameter value\"", ")", "else", "logger", ".", "error", "(", "\"Reason specified for abort: Unknown reason (Error code: #{reason})\"", ")", "end", "end" ]
Processes the value of the reason byte received in the association abort, and prints an explanation of the error. === Parameters * <tt>reason</tt> -- String. Reason code for an error that has occured.
[ "Processes", "the", "value", "of", "the", "reason", "byte", "received", "in", "the", "association", "abort", "and", "prints", "an", "explanation", "of", "the", "error", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/link.rb#L1278-L1295
22,292
dicom/ruby-dicom
lib/dicom/link.rb
DICOM.Link.process_result
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, reason: 'No reason (provider rejection)'") when 3 logger.warn("DICOM Request was rejected by the host, reason: 'Abstract syntax not supported'") when 4 logger.warn("DICOM Request was rejected by the host, reason: 'Transfer syntaxes not supported'") else logger.warn("DICOM Request was rejected by the host, reason: 'UNKNOWN (#{result})' (Illegal reason provided)") end end end
ruby
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, reason: 'No reason (provider rejection)'") when 3 logger.warn("DICOM Request was rejected by the host, reason: 'Abstract syntax not supported'") when 4 logger.warn("DICOM Request was rejected by the host, reason: 'Transfer syntaxes not supported'") else logger.warn("DICOM Request was rejected by the host, reason: 'UNKNOWN (#{result})' (Illegal reason provided)") end end end
[ "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, reason: 'No reason (provider rejection)'\"", ")", "when", "3", "logger", ".", "warn", "(", "\"DICOM Request was rejected by the host, reason: 'Abstract syntax not supported'\"", ")", "when", "4", "logger", ".", "warn", "(", "\"DICOM Request was rejected by the host, reason: 'Transfer syntaxes not supported'\"", ")", "else", "logger", ".", "warn", "(", "\"DICOM Request was rejected by the host, reason: 'UNKNOWN (#{result})' (Illegal reason provided)\"", ")", "end", "end", "end" ]
Processes the value of the result byte received in the association response. Prints an explanation if an error is indicated. === Notes A value other than 0 indicates an error. === Parameters * <tt>result</tt> -- Integer. The result code from an association response.
[ "Processes", "the", "value", "of", "the", "result", "byte", "received", "in", "the", "association", "response", ".", "Prints", "an", "explanation", "if", "an", "error", "is", "indicated", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/link.rb#L1308-L1324
22,293
dicom/ruby-dicom
lib/dicom/link.rb
DICOM.Link.receive_transmission
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 answer was too short: unless min_length == 0 if data.length < min_length addition = receive_transmission_data data = data + addition if addition end end else # It seems there was no incoming message and the operation timed out. # Convert the variable to an empty string. data = "" end data end
ruby
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 answer was too short: unless min_length == 0 if data.length < min_length addition = receive_transmission_data data = data + addition if addition end end else # It seems there was no incoming message and the operation timed out. # Convert the variable to an empty string. data = "" end data end
[ "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 answer was too short:", "unless", "min_length", "==", "0", "if", "data", ".", "length", "<", "min_length", "addition", "=", "receive_transmission_data", "data", "=", "data", "+", "addition", "if", "addition", "end", "end", "else", "# It seems there was no incoming message and the operation timed out.", "# Convert the variable to an empty string.", "data", "=", "\"\"", "end", "data", "end" ]
Handles an incoming network transmission. Returns the binary string data received. === Notes If a minimum length has been specified, and a message is received which is shorter than this length, the method will keep listening for more incoming network packets to append. === Parameters * <tt>min_length</tt> -- Integer. The minimum possible length of a valid incoming transmission.
[ "Handles", "an", "incoming", "network", "transmission", ".", "Returns", "the", "binary", "string", "data", "received", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/link.rb#L1402-L1420
22,294
dicom/ruby-dicom
lib/dicom/link.rb
DICOM.Link.receive_transmission_data
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 data end
ruby
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 data end
[ "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", "data", "end" ]
Receives the data from an incoming network transmission. Returns the binary string data received.
[ "Receives", "the", "data", "from", "an", "incoming", "network", "transmission", ".", "Returns", "the", "binary", "string", "data", "received", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/link.rb#L1425-L1435
22,295
dicom/ruby-dicom
lib/dicom/link.rb
DICOM.Link.set_transfer_syntax
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 encountered: #{@transfer_syntax} Will try to continue, but errors may occur.") unless ts end
ruby
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 encountered: #{@transfer_syntax} Will try to continue, but errors may occur.") unless ts end
[ "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 encountered: #{@transfer_syntax} Will try to continue, but errors may occur.\"", ")", "unless", "ts", "end" ]
Set instance variables related to a transfer syntax. === Parameters * <tt>syntax</tt> -- A transfer syntax string.
[ "Set", "instance", "variables", "related", "to", "a", "transfer", "syntax", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/link.rb#L1457-L1464
22,296
dicom/ruby-dicom
lib/dicom/item.rb
DICOM.Item.bin=
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 @value = nil @length = @bin.length end
ruby
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 @value = nil @length = @bin.length end
[ "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", "@value", "=", "nil", "@length", "=", "@bin", ".", "length", "end" ]
Sets the binary string that the Item will contain. @param [String] new_bin a binary string of encoded data @example Insert a custom jpeg in the (encapsulated) pixel data element (in it's first pixel data item) dcm['7FE0,0010'][1].children.first.bin = jpeg_binary_string
[ "Sets", "the", "binary", "string", "that", "the", "Item", "will", "contain", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/item.rb#L79-L89
22,297
dicom/ruby-dicom
lib/dicom/image_processor.rb
DICOM.ImageProcessor.decompress
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
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
[ "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" ]
Creates image objects from one or more compressed, binary string blobs. @param [Array<String>, String] blobs binary string blob(s) containing compressed pixel data @return [Array<MagickImage>, FalseClass] - an array of images, or false (if decompression failed)
[ "Creates", "image", "objects", "from", "one", "or", "more", "compressed", "binary", "string", "blobs", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/image_processor.rb#L13-L21
22,298
dicom/ruby-dicom
lib/dicom/image_processor.rb
DICOM.ImageProcessor.import_pixels
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
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
[ "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" ]
Creates an image object from a binary string blob. @param [String] blob binary string blob containing pixel data @param [Integer] columns the number of columns @param [Integer] rows the number of rows @param [Integer] depth the bit depth of the encoded pixel data @param [String] photometry a code describing the photometry of the pixel data (e.g. 'MONOCHROME1' or 'COLOR') @return [MagickImage] a Magick image object
[ "Creates", "an", "image", "object", "from", "a", "binary", "string", "blob", "." ]
3ffcfe21edc8dcd31298f945781990789fc832ab
https://github.com/dicom/ruby-dicom/blob/3ffcfe21edc8dcd31298f945781990789fc832ab/lib/dicom/image_processor.rb#L43-L46
22,299
calabash/calabash
lib/calabash/location.rb
Calabash.Location.coordinates_for_place
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
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
[ "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" ]
Get the latitude and longitude for a certain place, resolved via Google maps api. This hash can be used in `set_location`. @example cal.coordinates_for_place('The little mermaid, Copenhagen') # => {:latitude => 55.6760968, :longitude => 12.5683371} @return [Hash] Latitude and longitude for the given place @raise [RuntimeError] If the place cannot be found
[ "Get", "the", "latitude", "and", "longitude", "for", "a", "certain", "place", "resolved", "via", "Google", "maps", "api", ".", "This", "hash", "can", "be", "used", "in", "set_location", "." ]
fac1ce9fcff6e2460c6e72a9b89d93a91a1bc745
https://github.com/calabash/calabash/blob/fac1ce9fcff6e2460c6e72a9b89d93a91a1bc745/lib/calabash/location.rb#L39-L48