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
partition
stringclasses
1 value
oleganza/btcruby
lib/btcruby/script/script.rb
BTC.Script.simulated_signature_script
def simulated_signature_script(strict: true) if public_key_hash_script? # assuming non-compressed pubkeys to be conservative return Script.new << Script.simulated_signature(hashtype: SIGHASH_ALL) << Script.simulated_uncompressed_pubkey elsif public_key_script? return Script.new << Script.simulated_signature(hashtype: SIGHASH_ALL) elsif script_hash_script? && !strict # This is a wild approximation, but works well if most p2sh scripts are 2-of-3 multisig scripts. # If you have a very particular smart contract scheme you should not use TransactionBuilder which estimates fees this way. return Script.new << OP_0 << [Script.simulated_signature(hashtype: SIGHASH_ALL)]*2 << Script.simulated_multisig_script(2,3).data elsif multisig_script? return Script.new << OP_0 << [Script.simulated_signature(hashtype: SIGHASH_ALL)]*self.multisig_signatures_required else return nil end end
ruby
def simulated_signature_script(strict: true) if public_key_hash_script? # assuming non-compressed pubkeys to be conservative return Script.new << Script.simulated_signature(hashtype: SIGHASH_ALL) << Script.simulated_uncompressed_pubkey elsif public_key_script? return Script.new << Script.simulated_signature(hashtype: SIGHASH_ALL) elsif script_hash_script? && !strict # This is a wild approximation, but works well if most p2sh scripts are 2-of-3 multisig scripts. # If you have a very particular smart contract scheme you should not use TransactionBuilder which estimates fees this way. return Script.new << OP_0 << [Script.simulated_signature(hashtype: SIGHASH_ALL)]*2 << Script.simulated_multisig_script(2,3).data elsif multisig_script? return Script.new << OP_0 << [Script.simulated_signature(hashtype: SIGHASH_ALL)]*self.multisig_signatures_required else return nil end end
[ "def", "simulated_signature_script", "(", "strict", ":", "true", ")", "if", "public_key_hash_script?", "return", "Script", ".", "new", "<<", "Script", ".", "simulated_signature", "(", "hashtype", ":", "SIGHASH_ALL", ")", "<<", "Script", ".", "simulated_uncompressed_pubkey", "elsif", "public_key_script?", "return", "Script", ".", "new", "<<", "Script", ".", "simulated_signature", "(", "hashtype", ":", "SIGHASH_ALL", ")", "elsif", "script_hash_script?", "&&", "!", "strict", "return", "Script", ".", "new", "<<", "OP_0", "<<", "[", "Script", ".", "simulated_signature", "(", "hashtype", ":", "SIGHASH_ALL", ")", "]", "*", "2", "<<", "Script", ".", "simulated_multisig_script", "(", "2", ",", "3", ")", ".", "data", "elsif", "multisig_script?", "return", "Script", ".", "new", "<<", "OP_0", "<<", "[", "Script", ".", "simulated_signature", "(", "hashtype", ":", "SIGHASH_ALL", ")", "]", "*", "self", ".", "multisig_signatures_required", "else", "return", "nil", "end", "end" ]
Returns a dummy script matching this script on the input with the same size as an intended signature script. Only a few standard script types are supported. Set `strict` to false to allow imprecise guess for P2SH script. Returns nil if could not determine a matching script.
[ "Returns", "a", "dummy", "script", "matching", "this", "script", "on", "the", "input", "with", "the", "same", "size", "as", "an", "intended", "signature", "script", ".", "Only", "a", "few", "standard", "script", "types", "are", "supported", ".", "Set", "strict", "to", "false", "to", "allow", "imprecise", "guess", "for", "P2SH", "script", ".", "Returns", "nil", "if", "could", "not", "determine", "a", "matching", "script", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/script/script.rb#L344-L362
train
oleganza/btcruby
lib/btcruby/script/script.rb
BTC.Script.append_pushdata
def append_pushdata(data, opcode: nil) raise ArgumentError, "No data provided" if !data encoded_pushdata = self.class.encode_pushdata(data, opcode: opcode) if !encoded_pushdata raise ArgumentError, "Cannot encode pushdata with opcode #{opcode}" end @chunks << ScriptChunk.new(encoded_pushdata) return self end
ruby
def append_pushdata(data, opcode: nil) raise ArgumentError, "No data provided" if !data encoded_pushdata = self.class.encode_pushdata(data, opcode: opcode) if !encoded_pushdata raise ArgumentError, "Cannot encode pushdata with opcode #{opcode}" end @chunks << ScriptChunk.new(encoded_pushdata) return self end
[ "def", "append_pushdata", "(", "data", ",", "opcode", ":", "nil", ")", "raise", "ArgumentError", ",", "\"No data provided\"", "if", "!", "data", "encoded_pushdata", "=", "self", ".", "class", ".", "encode_pushdata", "(", "data", ",", "opcode", ":", "opcode", ")", "if", "!", "encoded_pushdata", "raise", "ArgumentError", ",", "\"Cannot encode pushdata with opcode #{opcode}\"", "end", "@chunks", "<<", "ScriptChunk", ".", "new", "(", "encoded_pushdata", ")", "return", "self", "end" ]
Appends a pushdata opcode with the most compact encoding. Optional opcode may be equal to OP_PUSHDATA1, OP_PUSHDATA2, or OP_PUSHDATA4. ArgumentError is raised if opcode does not represent a given data length.
[ "Appends", "a", "pushdata", "opcode", "with", "the", "most", "compact", "encoding", ".", "Optional", "opcode", "may", "be", "equal", "to", "OP_PUSHDATA1", "OP_PUSHDATA2", "or", "OP_PUSHDATA4", ".", "ArgumentError", "is", "raised", "if", "opcode", "does", "not", "represent", "a", "given", "data", "length", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/script/script.rb#L405-L413
train
oleganza/btcruby
lib/btcruby/script/script.rb
BTC.Script.delete_opcode
def delete_opcode(opcode) @chunks = @chunks.inject([]) do |list, chunk| list << chunk if chunk.opcode != opcode list end return self end
ruby
def delete_opcode(opcode) @chunks = @chunks.inject([]) do |list, chunk| list << chunk if chunk.opcode != opcode list end return self end
[ "def", "delete_opcode", "(", "opcode", ")", "@chunks", "=", "@chunks", ".", "inject", "(", "[", "]", ")", "do", "|", "list", ",", "chunk", "|", "list", "<<", "chunk", "if", "chunk", ".", "opcode", "!=", "opcode", "list", "end", "return", "self", "end" ]
Removes all occurences of opcode. Typically it's OP_CODESEPARATOR.
[ "Removes", "all", "occurences", "of", "opcode", ".", "Typically", "it", "s", "OP_CODESEPARATOR", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/script/script.rb#L416-L422
train
oleganza/btcruby
lib/btcruby/script/script.rb
BTC.Script.delete_pushdata
def delete_pushdata(pushdata) @chunks = @chunks.inject([]) do |list, chunk| list << chunk if chunk.pushdata != pushdata list end return self end
ruby
def delete_pushdata(pushdata) @chunks = @chunks.inject([]) do |list, chunk| list << chunk if chunk.pushdata != pushdata list end return self end
[ "def", "delete_pushdata", "(", "pushdata", ")", "@chunks", "=", "@chunks", ".", "inject", "(", "[", "]", ")", "do", "|", "list", ",", "chunk", "|", "list", "<<", "chunk", "if", "chunk", ".", "pushdata", "!=", "pushdata", "list", "end", "return", "self", "end" ]
Removes all occurences of a given pushdata.
[ "Removes", "all", "occurences", "of", "a", "given", "pushdata", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/script/script.rb#L425-L431
train
oleganza/btcruby
lib/btcruby/script/script.rb
BTC.Script.find_and_delete
def find_and_delete(subscript) subscript.is_a?(Script) or raise ArgumentError,"Argument must be an instance of BTC::Script" # Replacing [a b a] # Script: a b b a b a b a c # Result: a b b b a c subscriptsize = subscript.chunks.size buf = [] i = 0 result = Script.new chunks.each do |chunk| if chunk == subscript.chunks[i] buf << chunk i+=1 if i == subscriptsize # matched the whole subscript i = 0 buf.clear end else i = 0 result << buf result << chunk end end result end
ruby
def find_and_delete(subscript) subscript.is_a?(Script) or raise ArgumentError,"Argument must be an instance of BTC::Script" # Replacing [a b a] # Script: a b b a b a b a c # Result: a b b b a c subscriptsize = subscript.chunks.size buf = [] i = 0 result = Script.new chunks.each do |chunk| if chunk == subscript.chunks[i] buf << chunk i+=1 if i == subscriptsize # matched the whole subscript i = 0 buf.clear end else i = 0 result << buf result << chunk end end result end
[ "def", "find_and_delete", "(", "subscript", ")", "subscript", ".", "is_a?", "(", "Script", ")", "or", "raise", "ArgumentError", ",", "\"Argument must be an instance of BTC::Script\"", "subscriptsize", "=", "subscript", ".", "chunks", ".", "size", "buf", "=", "[", "]", "i", "=", "0", "result", "=", "Script", ".", "new", "chunks", ".", "each", "do", "|", "chunk", "|", "if", "chunk", "==", "subscript", ".", "chunks", "[", "i", "]", "buf", "<<", "chunk", "i", "+=", "1", "if", "i", "==", "subscriptsize", "i", "=", "0", "buf", ".", "clear", "end", "else", "i", "=", "0", "result", "<<", "buf", "result", "<<", "chunk", "end", "end", "result", "end" ]
Removes chunks matching subscript byte-for-byte and returns a new script instance with subscript removed. So if pushdata items are encoded differently, they won't match. Consensus-critical code.
[ "Removes", "chunks", "matching", "subscript", "byte", "-", "for", "-", "byte", "and", "returns", "a", "new", "script", "instance", "with", "subscript", "removed", ".", "So", "if", "pushdata", "items", "are", "encoded", "differently", "they", "won", "t", "match", ".", "Consensus", "-", "critical", "code", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/script/script.rb#L481-L505
train
oleganza/btcruby
lib/btcruby/open_assets/asset_transaction_output.rb
BTC.AssetTransactionOutput.parse_assets_data
def parse_assets_data(data, offset: 0) v, len = WireFormat.read_uint8(data: data, offset: offset) raise ArgumentError, "Invalid data: verified flag" if !v asset_hash, len = WireFormat.read_string(data: data, offset: len) # empty or 20 bytes raise ArgumentError, "Invalid data: asset hash" if !asset_hash value, len = WireFormat.read_int64le(data: data, offset: len) raise ArgumentError, "Invalid data: value" if !value @verified = (v == 1) @asset_id = asset_hash.bytesize > 0 ? AssetID.new(hash: asset_hash) : nil @value = value len end
ruby
def parse_assets_data(data, offset: 0) v, len = WireFormat.read_uint8(data: data, offset: offset) raise ArgumentError, "Invalid data: verified flag" if !v asset_hash, len = WireFormat.read_string(data: data, offset: len) # empty or 20 bytes raise ArgumentError, "Invalid data: asset hash" if !asset_hash value, len = WireFormat.read_int64le(data: data, offset: len) raise ArgumentError, "Invalid data: value" if !value @verified = (v == 1) @asset_id = asset_hash.bytesize > 0 ? AssetID.new(hash: asset_hash) : nil @value = value len end
[ "def", "parse_assets_data", "(", "data", ",", "offset", ":", "0", ")", "v", ",", "len", "=", "WireFormat", ".", "read_uint8", "(", "data", ":", "data", ",", "offset", ":", "offset", ")", "raise", "ArgumentError", ",", "\"Invalid data: verified flag\"", "if", "!", "v", "asset_hash", ",", "len", "=", "WireFormat", ".", "read_string", "(", "data", ":", "data", ",", "offset", ":", "len", ")", "raise", "ArgumentError", ",", "\"Invalid data: asset hash\"", "if", "!", "asset_hash", "value", ",", "len", "=", "WireFormat", ".", "read_int64le", "(", "data", ":", "data", ",", "offset", ":", "len", ")", "raise", "ArgumentError", ",", "\"Invalid data: value\"", "if", "!", "value", "@verified", "=", "(", "v", "==", "1", ")", "@asset_id", "=", "asset_hash", ".", "bytesize", ">", "0", "?", "AssetID", ".", "new", "(", "hash", ":", "asset_hash", ")", ":", "nil", "@value", "=", "value", "len", "end" ]
Returns total length read
[ "Returns", "total", "length", "read" ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/open_assets/asset_transaction_output.rb#L123-L134
train
oleganza/btcruby
lib/btcruby/base58.rb
BTC.Base58.base58_from_data
def base58_from_data(data) raise ArgumentError, "Data is missing" if !data leading_zeroes = 0 int = 0 base = 1 data.bytes.reverse_each do |byte| if byte == 0 leading_zeroes += 1 else leading_zeroes = 0 int += base*byte end base *= 256 end return ("1"*leading_zeroes) + base58_from_int(int) end
ruby
def base58_from_data(data) raise ArgumentError, "Data is missing" if !data leading_zeroes = 0 int = 0 base = 1 data.bytes.reverse_each do |byte| if byte == 0 leading_zeroes += 1 else leading_zeroes = 0 int += base*byte end base *= 256 end return ("1"*leading_zeroes) + base58_from_int(int) end
[ "def", "base58_from_data", "(", "data", ")", "raise", "ArgumentError", ",", "\"Data is missing\"", "if", "!", "data", "leading_zeroes", "=", "0", "int", "=", "0", "base", "=", "1", "data", ".", "bytes", ".", "reverse_each", "do", "|", "byte", "|", "if", "byte", "==", "0", "leading_zeroes", "+=", "1", "else", "leading_zeroes", "=", "0", "int", "+=", "base", "*", "byte", "end", "base", "*=", "256", "end", "return", "(", "\"1\"", "*", "leading_zeroes", ")", "+", "base58_from_int", "(", "int", ")", "end" ]
Converts binary string into its Base58 representation. If string is empty returns an empty string. If string is nil raises ArgumentError
[ "Converts", "binary", "string", "into", "its", "Base58", "representation", ".", "If", "string", "is", "empty", "returns", "an", "empty", "string", ".", "If", "string", "is", "nil", "raises", "ArgumentError" ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/base58.rb#L23-L38
train
oleganza/btcruby
lib/btcruby/base58.rb
BTC.Base58.data_from_base58
def data_from_base58(string) raise ArgumentError, "String is missing" if !string int = int_from_base58(string) bytes = [] while int > 0 remainder = int % 256 int = int / 256 bytes.unshift(remainder) end data = BTC::Data.data_from_bytes(bytes) byte_for_1 = "1".bytes.first BTC::Data.ensure_ascii_compatible_encoding(string).bytes.each do |byte| break if byte != byte_for_1 data = "\x00" + data end data end
ruby
def data_from_base58(string) raise ArgumentError, "String is missing" if !string int = int_from_base58(string) bytes = [] while int > 0 remainder = int % 256 int = int / 256 bytes.unshift(remainder) end data = BTC::Data.data_from_bytes(bytes) byte_for_1 = "1".bytes.first BTC::Data.ensure_ascii_compatible_encoding(string).bytes.each do |byte| break if byte != byte_for_1 data = "\x00" + data end data end
[ "def", "data_from_base58", "(", "string", ")", "raise", "ArgumentError", ",", "\"String is missing\"", "if", "!", "string", "int", "=", "int_from_base58", "(", "string", ")", "bytes", "=", "[", "]", "while", "int", ">", "0", "remainder", "=", "int", "%", "256", "int", "=", "int", "/", "256", "bytes", ".", "unshift", "(", "remainder", ")", "end", "data", "=", "BTC", "::", "Data", ".", "data_from_bytes", "(", "bytes", ")", "byte_for_1", "=", "\"1\"", ".", "bytes", ".", "first", "BTC", "::", "Data", ".", "ensure_ascii_compatible_encoding", "(", "string", ")", ".", "bytes", ".", "each", "do", "|", "byte", "|", "break", "if", "byte", "!=", "byte_for_1", "data", "=", "\"\\x00\"", "+", "data", "end", "data", "end" ]
Converts binary string into its Base58 representation. If string is empty returns an empty string. If string is nil raises ArgumentError.
[ "Converts", "binary", "string", "into", "its", "Base58", "representation", ".", "If", "string", "is", "empty", "returns", "an", "empty", "string", ".", "If", "string", "is", "nil", "raises", "ArgumentError", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/base58.rb#L43-L59
train
oleganza/btcruby
lib/btcruby/transaction_builder.rb
BTC.TransactionBuilder.compute_fee_for_transaction
def compute_fee_for_transaction(tx, fee_rate) # Return mining fee if set manually return fee if fee # Compute fees for this tx by composing a tx with properly sized dummy signatures. simulated_tx = tx.dup simulated_tx.inputs.each do |txin| txout_script = txin.transaction_output.script txin.signature_script = txout_script.simulated_signature_script(strict: false) || txout_script end return simulated_tx.compute_fee(fee_rate: fee_rate) end
ruby
def compute_fee_for_transaction(tx, fee_rate) # Return mining fee if set manually return fee if fee # Compute fees for this tx by composing a tx with properly sized dummy signatures. simulated_tx = tx.dup simulated_tx.inputs.each do |txin| txout_script = txin.transaction_output.script txin.signature_script = txout_script.simulated_signature_script(strict: false) || txout_script end return simulated_tx.compute_fee(fee_rate: fee_rate) end
[ "def", "compute_fee_for_transaction", "(", "tx", ",", "fee_rate", ")", "return", "fee", "if", "fee", "simulated_tx", "=", "tx", ".", "dup", "simulated_tx", ".", "inputs", ".", "each", "do", "|", "txin", "|", "txout_script", "=", "txin", ".", "transaction_output", ".", "script", "txin", ".", "signature_script", "=", "txout_script", ".", "simulated_signature_script", "(", "strict", ":", "false", ")", "||", "txout_script", "end", "return", "simulated_tx", ".", "compute_fee", "(", "fee_rate", ":", "fee_rate", ")", "end" ]
Helper to compute total fee for a given transaction. Simulates signatures to estimate final size.
[ "Helper", "to", "compute", "total", "fee", "for", "a", "given", "transaction", ".", "Simulates", "signatures", "to", "estimate", "final", "size", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/transaction_builder.rb#L380-L390
train
oleganza/btcruby
lib/btcruby/currency_formatter.rb
BTC.CurrencyFormatter.string_from_number
def string_from_number(number) if @style == :btc number = number.to_i return "#{number / BTC::COIN}.#{'%08d' % [number % BTC::COIN]}".gsub(/0+$/,"").gsub(/\.$/,".0") elsif @style == :btc_long number = number.to_i return "#{number / BTC::COIN}.#{'%08d' % [number % BTC::COIN]}" else # TODO: parse other styles raise "Not implemented" end end
ruby
def string_from_number(number) if @style == :btc number = number.to_i return "#{number / BTC::COIN}.#{'%08d' % [number % BTC::COIN]}".gsub(/0+$/,"").gsub(/\.$/,".0") elsif @style == :btc_long number = number.to_i return "#{number / BTC::COIN}.#{'%08d' % [number % BTC::COIN]}" else # TODO: parse other styles raise "Not implemented" end end
[ "def", "string_from_number", "(", "number", ")", "if", "@style", "==", ":btc", "number", "=", "number", ".", "to_i", "return", "\"#{number / BTC::COIN}.#{'%08d' % [number % BTC::COIN]}\"", ".", "gsub", "(", "/", "/", ",", "\"\"", ")", ".", "gsub", "(", "/", "\\.", "/", ",", "\".0\"", ")", "elsif", "@style", "==", ":btc_long", "number", "=", "number", ".", "to_i", "return", "\"#{number / BTC::COIN}.#{'%08d' % [number % BTC::COIN]}\"", "else", "raise", "\"Not implemented\"", "end", "end" ]
Returns formatted string for an amount in satoshis.
[ "Returns", "formatted", "string", "for", "an", "amount", "in", "satoshis", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/currency_formatter.rb#L34-L45
train
oleganza/btcruby
lib/btcruby/currency_formatter.rb
BTC.CurrencyFormatter.number_from_string
def number_from_string(string) bd = BigDecimal.new(string) if @style == :btc || @style == :btc_long return (bd * BTC::COIN).to_i else # TODO: support other styles raise "Not Implemented" end end
ruby
def number_from_string(string) bd = BigDecimal.new(string) if @style == :btc || @style == :btc_long return (bd * BTC::COIN).to_i else # TODO: support other styles raise "Not Implemented" end end
[ "def", "number_from_string", "(", "string", ")", "bd", "=", "BigDecimal", ".", "new", "(", "string", ")", "if", "@style", "==", ":btc", "||", "@style", "==", ":btc_long", "return", "(", "bd", "*", "BTC", "::", "COIN", ")", ".", "to_i", "else", "raise", "\"Not Implemented\"", "end", "end" ]
Returns amount of satoshis parsed from a formatted string according to style attribute.
[ "Returns", "amount", "of", "satoshis", "parsed", "from", "a", "formatted", "string", "according", "to", "style", "attribute", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/currency_formatter.rb#L48-L56
train
oleganza/btcruby
lib/btcruby/open_assets/asset_processor.rb
BTC.AssetProcessor.partial_verify_asset_transaction
def partial_verify_asset_transaction(asset_transaction) raise ArgumentError, "Asset Transaction is missing" if !asset_transaction # 1. Verify issuing transactions and collect transfer outputs cache_transactions do if !verify_issues(asset_transaction) return nil end # No transfer outputs, this transaction is verified. # If there are assets on some inputs, they are destroyed. if asset_transaction.transfer_outputs.size == 0 # We keep inputs unverified to indicate that they were not even processed. return [] end # 2. Fetch parent transactions to verify. # * Verify inputs from non-OpenAsset transactions. # * Return OA transactions for verification. # * Link each input to its OA transaction output. prev_unverified_atxs_by_hash = {} asset_transaction.inputs.each do |ain| txin = ain.transaction_input # Ask source if it has a cached verified transaction for this input. prev_atx = @source.verified_asset_transaction_for_hash(txin.previous_hash) if prev_atx BTC::Invariant(prev_atx.verified?, "Cached verified tx must be fully verified") end prev_atx ||= prev_unverified_atxs_by_hash[txin.previous_hash] if !prev_atx prev_tx = transaction_for_input(txin) if !prev_tx Diagnostics.current.add_message("Failed to load previous transaction for input #{ain.index}: #{txin.previous_id}") return nil end begin prev_atx = AssetTransaction.new(transaction: prev_tx) prev_unverified_atxs_by_hash[prev_atx.transaction_hash] = prev_atx rescue FormatError => e # Previous transaction is not a valid Open Assets transaction, # so we mark the input as uncolored and verified as such. ain.asset_id = nil ain.value = nil ain.verified = true end end # Remember a reference to this transaction so we can validate the whole `asset_transaction` when all previous ones are set and verified. ain.previous_asset_transaction = prev_atx end # each input # Return all unverified transactions. # Note: this won't include the already verified one. prev_unverified_atxs_by_hash.values end end
ruby
def partial_verify_asset_transaction(asset_transaction) raise ArgumentError, "Asset Transaction is missing" if !asset_transaction # 1. Verify issuing transactions and collect transfer outputs cache_transactions do if !verify_issues(asset_transaction) return nil end # No transfer outputs, this transaction is verified. # If there are assets on some inputs, they are destroyed. if asset_transaction.transfer_outputs.size == 0 # We keep inputs unverified to indicate that they were not even processed. return [] end # 2. Fetch parent transactions to verify. # * Verify inputs from non-OpenAsset transactions. # * Return OA transactions for verification. # * Link each input to its OA transaction output. prev_unverified_atxs_by_hash = {} asset_transaction.inputs.each do |ain| txin = ain.transaction_input # Ask source if it has a cached verified transaction for this input. prev_atx = @source.verified_asset_transaction_for_hash(txin.previous_hash) if prev_atx BTC::Invariant(prev_atx.verified?, "Cached verified tx must be fully verified") end prev_atx ||= prev_unverified_atxs_by_hash[txin.previous_hash] if !prev_atx prev_tx = transaction_for_input(txin) if !prev_tx Diagnostics.current.add_message("Failed to load previous transaction for input #{ain.index}: #{txin.previous_id}") return nil end begin prev_atx = AssetTransaction.new(transaction: prev_tx) prev_unverified_atxs_by_hash[prev_atx.transaction_hash] = prev_atx rescue FormatError => e # Previous transaction is not a valid Open Assets transaction, # so we mark the input as uncolored and verified as such. ain.asset_id = nil ain.value = nil ain.verified = true end end # Remember a reference to this transaction so we can validate the whole `asset_transaction` when all previous ones are set and verified. ain.previous_asset_transaction = prev_atx end # each input # Return all unverified transactions. # Note: this won't include the already verified one. prev_unverified_atxs_by_hash.values end end
[ "def", "partial_verify_asset_transaction", "(", "asset_transaction", ")", "raise", "ArgumentError", ",", "\"Asset Transaction is missing\"", "if", "!", "asset_transaction", "cache_transactions", "do", "if", "!", "verify_issues", "(", "asset_transaction", ")", "return", "nil", "end", "if", "asset_transaction", ".", "transfer_outputs", ".", "size", "==", "0", "return", "[", "]", "end", "prev_unverified_atxs_by_hash", "=", "{", "}", "asset_transaction", ".", "inputs", ".", "each", "do", "|", "ain", "|", "txin", "=", "ain", ".", "transaction_input", "prev_atx", "=", "@source", ".", "verified_asset_transaction_for_hash", "(", "txin", ".", "previous_hash", ")", "if", "prev_atx", "BTC", "::", "Invariant", "(", "prev_atx", ".", "verified?", ",", "\"Cached verified tx must be fully verified\"", ")", "end", "prev_atx", "||=", "prev_unverified_atxs_by_hash", "[", "txin", ".", "previous_hash", "]", "if", "!", "prev_atx", "prev_tx", "=", "transaction_for_input", "(", "txin", ")", "if", "!", "prev_tx", "Diagnostics", ".", "current", ".", "add_message", "(", "\"Failed to load previous transaction for input #{ain.index}: #{txin.previous_id}\"", ")", "return", "nil", "end", "begin", "prev_atx", "=", "AssetTransaction", ".", "new", "(", "transaction", ":", "prev_tx", ")", "prev_unverified_atxs_by_hash", "[", "prev_atx", ".", "transaction_hash", "]", "=", "prev_atx", "rescue", "FormatError", "=>", "e", "ain", ".", "asset_id", "=", "nil", "ain", ".", "value", "=", "nil", "ain", ".", "verified", "=", "true", "end", "end", "ain", ".", "previous_asset_transaction", "=", "prev_atx", "end", "prev_unverified_atxs_by_hash", ".", "values", "end", "end" ]
Returns a list of asset transactions remaining to verify. Returns an empty array if verification succeeded and there is nothing more to verify. Returns `nil` if verification failed.
[ "Returns", "a", "list", "of", "asset", "transactions", "remaining", "to", "verify", ".", "Returns", "an", "empty", "array", "if", "verification", "succeeded", "and", "there", "is", "nothing", "more", "to", "verify", ".", "Returns", "nil", "if", "verification", "failed", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/open_assets/asset_processor.rb#L116-L170
train
oleganza/btcruby
lib/btcruby/open_assets/asset_processor.rb
BTC.AssetProcessor.verify_issues
def verify_issues(asset_transaction) previous_txout = nil # fetch only when we have > 0 issue outputs asset_transaction.outputs.each do |aout| if !aout.verified? if aout.value && aout.value > 0 if aout.issue? previous_txout ||= transaction_output_for_input(asset_transaction.inputs[0].transaction_input) if !previous_txout Diagnostics.current.add_message("Failed to assign AssetID to issue output #{aout.index}: can't find output for input #0") return false end aout.asset_id = AssetID.new(script: previous_txout.script, network: self.network) # Output issues some known asset and amount and therefore it is verified. aout.verified = true else # Transfer outputs must be matched with known asset ids on the inputs. end else # Output without a value is uncolored. aout.asset_id = nil aout.value = nil aout.verified = true end end end true end
ruby
def verify_issues(asset_transaction) previous_txout = nil # fetch only when we have > 0 issue outputs asset_transaction.outputs.each do |aout| if !aout.verified? if aout.value && aout.value > 0 if aout.issue? previous_txout ||= transaction_output_for_input(asset_transaction.inputs[0].transaction_input) if !previous_txout Diagnostics.current.add_message("Failed to assign AssetID to issue output #{aout.index}: can't find output for input #0") return false end aout.asset_id = AssetID.new(script: previous_txout.script, network: self.network) # Output issues some known asset and amount and therefore it is verified. aout.verified = true else # Transfer outputs must be matched with known asset ids on the inputs. end else # Output without a value is uncolored. aout.asset_id = nil aout.value = nil aout.verified = true end end end true end
[ "def", "verify_issues", "(", "asset_transaction", ")", "previous_txout", "=", "nil", "asset_transaction", ".", "outputs", ".", "each", "do", "|", "aout", "|", "if", "!", "aout", ".", "verified?", "if", "aout", ".", "value", "&&", "aout", ".", "value", ">", "0", "if", "aout", ".", "issue?", "previous_txout", "||=", "transaction_output_for_input", "(", "asset_transaction", ".", "inputs", "[", "0", "]", ".", "transaction_input", ")", "if", "!", "previous_txout", "Diagnostics", ".", "current", ".", "add_message", "(", "\"Failed to assign AssetID to issue output #{aout.index}: can't find output for input #0\"", ")", "return", "false", "end", "aout", ".", "asset_id", "=", "AssetID", ".", "new", "(", "script", ":", "previous_txout", ".", "script", ",", "network", ":", "self", ".", "network", ")", "aout", ".", "verified", "=", "true", "else", "end", "else", "aout", ".", "asset_id", "=", "nil", "aout", ".", "value", "=", "nil", "aout", ".", "verified", "=", "true", "end", "end", "end", "true", "end" ]
Attempts to verify issues. Fetches parent transactions to determine AssetID. Returns `true` if verified all issue outputs. Returns `false` if previous tx defining AssetID is not found.
[ "Attempts", "to", "verify", "issues", ".", "Fetches", "parent", "transactions", "to", "determine", "AssetID", ".", "Returns", "true", "if", "verified", "all", "issue", "outputs", ".", "Returns", "false", "if", "previous", "tx", "defining", "AssetID", "is", "not", "found", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/open_assets/asset_processor.rb#L175-L201
train
oleganza/btcruby
lib/btcruby/proof_of_work.rb
BTC.ProofOfWork.target_from_bits
def target_from_bits(bits) exponent = ((bits >> 24) & 0xff) mantissa = bits & 0x7fffff mantissa *= -1 if (bits & 0x800000) > 0 (mantissa * (256**(exponent-3))).to_i end
ruby
def target_from_bits(bits) exponent = ((bits >> 24) & 0xff) mantissa = bits & 0x7fffff mantissa *= -1 if (bits & 0x800000) > 0 (mantissa * (256**(exponent-3))).to_i end
[ "def", "target_from_bits", "(", "bits", ")", "exponent", "=", "(", "(", "bits", ">>", "24", ")", "&", "0xff", ")", "mantissa", "=", "bits", "&", "0x7fffff", "mantissa", "*=", "-", "1", "if", "(", "bits", "&", "0x800000", ")", ">", "0", "(", "mantissa", "*", "(", "256", "**", "(", "exponent", "-", "3", ")", ")", ")", ".", "to_i", "end" ]
Converts 32-bit compact representation to a 256-bit integer. int32 -> bigint
[ "Converts", "32", "-", "bit", "compact", "representation", "to", "a", "256", "-", "bit", "integer", ".", "int32", "-", ">", "bigint" ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/proof_of_work.rb#L53-L58
train
oleganza/btcruby
lib/btcruby/proof_of_work.rb
BTC.ProofOfWork.hash_from_target
def hash_from_target(target) bytes = [] while target > 0 bytes << (target % 256) target /= 256 end BTC::Data.data_from_bytes(bytes).ljust(32, "\x00".b) end
ruby
def hash_from_target(target) bytes = [] while target > 0 bytes << (target % 256) target /= 256 end BTC::Data.data_from_bytes(bytes).ljust(32, "\x00".b) end
[ "def", "hash_from_target", "(", "target", ")", "bytes", "=", "[", "]", "while", "target", ">", "0", "bytes", "<<", "(", "target", "%", "256", ")", "target", "/=", "256", "end", "BTC", "::", "Data", ".", "data_from_bytes", "(", "bytes", ")", ".", "ljust", "(", "32", ",", "\"\\x00\"", ".", "b", ")", "end" ]
Converts target integer to a binary 32-byte hash. bigint -> hash256
[ "Converts", "target", "integer", "to", "a", "binary", "32", "-", "byte", "hash", ".", "bigint", "-", ">", "hash256" ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/proof_of_work.rb#L93-L100
train
oleganza/btcruby
lib/btcruby/mnemonic.rb
BTC.Mnemonic.print_addresses
def print_addresses(range: 0..100, network: BTC::Network.mainnet, account: 0) kc = keychain.bip44_keychain(network: network).bip44_account_keychain(account) puts "Addresses for account #{account} on #{network.name}" puts "Account xpub: #{kc.xpub}" puts "Account external xpub: #{kc.bip44_external_keychain.xpub}" puts "Index".ljust(10) + "External Address".ljust(40) + "Internal Address".ljust(40) range.each do |i| s = "" s << "#{i}".ljust(10) s << kc.bip44_external_keychain.derived_key(i).address.to_s.ljust(40) s << kc.bip44_internal_keychain.derived_key(i).address.to_s.ljust(40) puts s end end
ruby
def print_addresses(range: 0..100, network: BTC::Network.mainnet, account: 0) kc = keychain.bip44_keychain(network: network).bip44_account_keychain(account) puts "Addresses for account #{account} on #{network.name}" puts "Account xpub: #{kc.xpub}" puts "Account external xpub: #{kc.bip44_external_keychain.xpub}" puts "Index".ljust(10) + "External Address".ljust(40) + "Internal Address".ljust(40) range.each do |i| s = "" s << "#{i}".ljust(10) s << kc.bip44_external_keychain.derived_key(i).address.to_s.ljust(40) s << kc.bip44_internal_keychain.derived_key(i).address.to_s.ljust(40) puts s end end
[ "def", "print_addresses", "(", "range", ":", "0", "..", "100", ",", "network", ":", "BTC", "::", "Network", ".", "mainnet", ",", "account", ":", "0", ")", "kc", "=", "keychain", ".", "bip44_keychain", "(", "network", ":", "network", ")", ".", "bip44_account_keychain", "(", "account", ")", "puts", "\"Addresses for account #{account} on #{network.name}\"", "puts", "\"Account xpub: #{kc.xpub}\"", "puts", "\"Account external xpub: #{kc.bip44_external_keychain.xpub}\"", "puts", "\"Index\"", ".", "ljust", "(", "10", ")", "+", "\"External Address\"", ".", "ljust", "(", "40", ")", "+", "\"Internal Address\"", ".", "ljust", "(", "40", ")", "range", ".", "each", "do", "|", "i", "|", "s", "=", "\"\"", "s", "<<", "\"#{i}\"", ".", "ljust", "(", "10", ")", "s", "<<", "kc", ".", "bip44_external_keychain", ".", "derived_key", "(", "i", ")", ".", "address", ".", "to_s", ".", "ljust", "(", "40", ")", "s", "<<", "kc", ".", "bip44_internal_keychain", ".", "derived_key", "(", "i", ")", ".", "address", ".", "to_s", ".", "ljust", "(", "40", ")", "puts", "s", "end", "end" ]
For manual testing
[ "For", "manual", "testing" ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/mnemonic.rb#L49-L62
train
oleganza/btcruby
lib/btcruby/script/opcode.rb
BTC.Opcode.opcode_for_small_integer
def opcode_for_small_integer(small_int) raise ArgumentError, "small_int must not be nil" if !small_int return OP_0 if small_int == 0 return OP_1NEGATE if small_int == -1 if small_int >= 1 && small_int <= 16 return OP_1 + (small_int - 1) end return OP_INVALIDOPCODE end
ruby
def opcode_for_small_integer(small_int) raise ArgumentError, "small_int must not be nil" if !small_int return OP_0 if small_int == 0 return OP_1NEGATE if small_int == -1 if small_int >= 1 && small_int <= 16 return OP_1 + (small_int - 1) end return OP_INVALIDOPCODE end
[ "def", "opcode_for_small_integer", "(", "small_int", ")", "raise", "ArgumentError", ",", "\"small_int must not be nil\"", "if", "!", "small_int", "return", "OP_0", "if", "small_int", "==", "0", "return", "OP_1NEGATE", "if", "small_int", "==", "-", "1", "if", "small_int", ">=", "1", "&&", "small_int", "<=", "16", "return", "OP_1", "+", "(", "small_int", "-", "1", ")", "end", "return", "OP_INVALIDOPCODE", "end" ]
Returns OP_1NEGATE, OP_0 .. OP_16 for ints from -1 to 16. Returns OP_INVALIDOPCODE for other ints.
[ "Returns", "OP_1NEGATE", "OP_0", "..", "OP_16", "for", "ints", "from", "-", "1", "to", "16", ".", "Returns", "OP_INVALIDOPCODE", "for", "other", "ints", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/script/opcode.rb#L19-L27
train
oleganza/btcruby
lib/btcruby/diagnostics.rb
BTC.Diagnostics.record
def record(&block) recording_groups << Array.new last_group = nil begin yield ensure last_group = recording_groups.pop end last_group end
ruby
def record(&block) recording_groups << Array.new last_group = nil begin yield ensure last_group = recording_groups.pop end last_group end
[ "def", "record", "(", "&", "block", ")", "recording_groups", "<<", "Array", ".", "new", "last_group", "=", "nil", "begin", "yield", "ensure", "last_group", "=", "recording_groups", ".", "pop", "end", "last_group", "end" ]
Begins recording of series of messages and returns all recorded events. If there is no record block on any level, messages are not accumulated, but only last_message is updated. Returns a list of all recorded messages.
[ "Begins", "recording", "of", "series", "of", "messages", "and", "returns", "all", "recorded", "events", ".", "If", "there", "is", "no", "record", "block", "on", "any", "level", "messages", "are", "not", "accumulated", "but", "only", "last_message", "is", "updated", ".", "Returns", "a", "list", "of", "all", "recorded", "messages", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/diagnostics.rb#L17-L26
train
oleganza/btcruby
lib/btcruby/diagnostics.rb
BTC.Diagnostics.add_message
def add_message(message, info: nil) self.last_message = message self.last_info = info self.last_item = Item.new(message, info) # add to each recording group recording_groups.each do |group| group << Item.new(message, info) end @uniq_trace_streams.each do |stream| stream.puts message end return self end
ruby
def add_message(message, info: nil) self.last_message = message self.last_info = info self.last_item = Item.new(message, info) # add to each recording group recording_groups.each do |group| group << Item.new(message, info) end @uniq_trace_streams.each do |stream| stream.puts message end return self end
[ "def", "add_message", "(", "message", ",", "info", ":", "nil", ")", "self", ".", "last_message", "=", "message", "self", ".", "last_info", "=", "info", "self", ".", "last_item", "=", "Item", ".", "new", "(", "message", ",", "info", ")", "recording_groups", ".", "each", "do", "|", "group", "|", "group", "<<", "Item", ".", "new", "(", "message", ",", "info", ")", "end", "@uniq_trace_streams", ".", "each", "do", "|", "stream", "|", "stream", ".", "puts", "message", "end", "return", "self", "end" ]
Adds a diagnostic message. Use it to record warnings and reasons for errors. Do not use when the input is nil - code that have produced that nil could have already recorded a specific message for that.
[ "Adds", "a", "diagnostic", "message", ".", "Use", "it", "to", "record", "warnings", "and", "reasons", "for", "errors", ".", "Do", "not", "use", "when", "the", "input", "is", "nil", "-", "code", "that", "have", "produced", "that", "nil", "could", "have", "already", "recorded", "a", "specific", "message", "for", "that", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/diagnostics.rb#L49-L64
train
oleganza/btcruby
lib/btcruby/extensions.rb
BTC.StringExtensions.to_wif
def to_wif(network: nil, public_key_compressed: nil) BTC::WIF.new(private_key: self, network: network, public_key_compressed: public_key_compressed).to_s end
ruby
def to_wif(network: nil, public_key_compressed: nil) BTC::WIF.new(private_key: self, network: network, public_key_compressed: public_key_compressed).to_s end
[ "def", "to_wif", "(", "network", ":", "nil", ",", "public_key_compressed", ":", "nil", ")", "BTC", "::", "WIF", ".", "new", "(", "private_key", ":", "self", ",", "network", ":", "network", ",", "public_key_compressed", ":", "public_key_compressed", ")", ".", "to_s", "end" ]
Converts binary string as a private key to a WIF Base58 format.
[ "Converts", "binary", "string", "as", "a", "private", "key", "to", "a", "WIF", "Base58", "format", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/extensions.rb#L5-L7
train
oleganza/btcruby
lib/btcruby/ssss.rb
BTC.SecretSharing.restore
def restore(shares) prime = @order shares = shares.dup.uniq raise "No shares provided" if shares.size == 0 points = shares.map{|s| point_from_string(s) } # [[m,x,y],...] ms = points.map{|p| p[0]}.uniq xs = points.map{|p| p[1]}.uniq raise "Shares do not use the same M value" if ms.size > 1 m = ms.first raise "All shares must have unique X values" if xs.size != points.size raise "Number of shares should be M or more" if points.size < m points = points[0, m] # make sure we have exactly M points y = 0 points.size.times do |formula| # 0..(m-1) # Multiply the numerator across the top and denominators across the bottom to do Lagrange's interpolation numerator = 1 denominator = 1 points.size.times do |count| # 0..(m-1) if formula != count # skip element with i == j startposition = points[formula][1] nextposition = points[count][1] numerator = (numerator * -nextposition) % prime denominator = (denominator * (startposition - nextposition)) % prime end end value = points[formula][2] y = (prime + y + (value * numerator * modinv(denominator, prime))) % prime end return be_from_int(y) end
ruby
def restore(shares) prime = @order shares = shares.dup.uniq raise "No shares provided" if shares.size == 0 points = shares.map{|s| point_from_string(s) } # [[m,x,y],...] ms = points.map{|p| p[0]}.uniq xs = points.map{|p| p[1]}.uniq raise "Shares do not use the same M value" if ms.size > 1 m = ms.first raise "All shares must have unique X values" if xs.size != points.size raise "Number of shares should be M or more" if points.size < m points = points[0, m] # make sure we have exactly M points y = 0 points.size.times do |formula| # 0..(m-1) # Multiply the numerator across the top and denominators across the bottom to do Lagrange's interpolation numerator = 1 denominator = 1 points.size.times do |count| # 0..(m-1) if formula != count # skip element with i == j startposition = points[formula][1] nextposition = points[count][1] numerator = (numerator * -nextposition) % prime denominator = (denominator * (startposition - nextposition)) % prime end end value = points[formula][2] y = (prime + y + (value * numerator * modinv(denominator, prime))) % prime end return be_from_int(y) end
[ "def", "restore", "(", "shares", ")", "prime", "=", "@order", "shares", "=", "shares", ".", "dup", ".", "uniq", "raise", "\"No shares provided\"", "if", "shares", ".", "size", "==", "0", "points", "=", "shares", ".", "map", "{", "|", "s", "|", "point_from_string", "(", "s", ")", "}", "ms", "=", "points", ".", "map", "{", "|", "p", "|", "p", "[", "0", "]", "}", ".", "uniq", "xs", "=", "points", ".", "map", "{", "|", "p", "|", "p", "[", "1", "]", "}", ".", "uniq", "raise", "\"Shares do not use the same M value\"", "if", "ms", ".", "size", ">", "1", "m", "=", "ms", ".", "first", "raise", "\"All shares must have unique X values\"", "if", "xs", ".", "size", "!=", "points", ".", "size", "raise", "\"Number of shares should be M or more\"", "if", "points", ".", "size", "<", "m", "points", "=", "points", "[", "0", ",", "m", "]", "y", "=", "0", "points", ".", "size", ".", "times", "do", "|", "formula", "|", "numerator", "=", "1", "denominator", "=", "1", "points", ".", "size", ".", "times", "do", "|", "count", "|", "if", "formula", "!=", "count", "startposition", "=", "points", "[", "formula", "]", "[", "1", "]", "nextposition", "=", "points", "[", "count", "]", "[", "1", "]", "numerator", "=", "(", "numerator", "*", "-", "nextposition", ")", "%", "prime", "denominator", "=", "(", "denominator", "*", "(", "startposition", "-", "nextposition", ")", ")", "%", "prime", "end", "end", "value", "=", "points", "[", "formula", "]", "[", "2", "]", "y", "=", "(", "prime", "+", "y", "+", "(", "value", "*", "numerator", "*", "modinv", "(", "denominator", ",", "prime", ")", ")", ")", "%", "prime", "end", "return", "be_from_int", "(", "y", ")", "end" ]
Transforms M 17-byte binary strings into original secret 16-byte binary string. Each share string must be well-formed.
[ "Transforms", "M", "17", "-", "byte", "binary", "strings", "into", "original", "secret", "16", "-", "byte", "binary", "string", ".", "Each", "share", "string", "must", "be", "well", "-", "formed", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/ssss.rb#L73-L102
train
oleganza/btcruby
lib/btcruby/open_assets/asset_transaction_builder.rb
BTC.AssetTransactionBuilder.issue_asset
def issue_asset(source_script: nil, source_output: nil, amount: nil, script: nil, address: nil) raise ArgumentError, "Either `source_script` or `source_output` must be specified" if !source_script && !source_output raise ArgumentError, "Both `source_script` and `source_output` cannot be specified" if source_script && source_output raise ArgumentError, "Either `script` or `address` must be specified" if !script && !address raise ArgumentError, "Both `script` and `address` cannot be specified" if script && address raise ArgumentError, "Amount must be greater than zero" if !amount || amount <= 0 if source_output && (!source_output.index || !source_output.transaction_hash) raise ArgumentError, "If `source_output` is specified, it must have valid `transaction_hash` and `index` attributes" end script ||= AssetAddress.parse(address).script # Ensure source output is a verified asset output. if source_output if source_output.is_a?(AssetTransactionOutput) raise ArgumentError, "Must be verified asset output to spend" if !source_output.verified? else source_output = AssetTransactionOutput.new(transaction_output: source_output, verified: true) end end # Set either the script or output only once. # All the remaining issuances must use the same script or output. if !self.issuing_asset_script && !self.issuing_asset_output self.issuing_asset_script = source_script self.issuing_asset_output = source_output else if self.issuing_asset_script != source_script || self.issuing_asset_output != source_output raise ArgumentError, "Can't issue more assets from a different source script or source output" end end self.issued_assets << {amount: amount, script: script} end
ruby
def issue_asset(source_script: nil, source_output: nil, amount: nil, script: nil, address: nil) raise ArgumentError, "Either `source_script` or `source_output` must be specified" if !source_script && !source_output raise ArgumentError, "Both `source_script` and `source_output` cannot be specified" if source_script && source_output raise ArgumentError, "Either `script` or `address` must be specified" if !script && !address raise ArgumentError, "Both `script` and `address` cannot be specified" if script && address raise ArgumentError, "Amount must be greater than zero" if !amount || amount <= 0 if source_output && (!source_output.index || !source_output.transaction_hash) raise ArgumentError, "If `source_output` is specified, it must have valid `transaction_hash` and `index` attributes" end script ||= AssetAddress.parse(address).script # Ensure source output is a verified asset output. if source_output if source_output.is_a?(AssetTransactionOutput) raise ArgumentError, "Must be verified asset output to spend" if !source_output.verified? else source_output = AssetTransactionOutput.new(transaction_output: source_output, verified: true) end end # Set either the script or output only once. # All the remaining issuances must use the same script or output. if !self.issuing_asset_script && !self.issuing_asset_output self.issuing_asset_script = source_script self.issuing_asset_output = source_output else if self.issuing_asset_script != source_script || self.issuing_asset_output != source_output raise ArgumentError, "Can't issue more assets from a different source script or source output" end end self.issued_assets << {amount: amount, script: script} end
[ "def", "issue_asset", "(", "source_script", ":", "nil", ",", "source_output", ":", "nil", ",", "amount", ":", "nil", ",", "script", ":", "nil", ",", "address", ":", "nil", ")", "raise", "ArgumentError", ",", "\"Either `source_script` or `source_output` must be specified\"", "if", "!", "source_script", "&&", "!", "source_output", "raise", "ArgumentError", ",", "\"Both `source_script` and `source_output` cannot be specified\"", "if", "source_script", "&&", "source_output", "raise", "ArgumentError", ",", "\"Either `script` or `address` must be specified\"", "if", "!", "script", "&&", "!", "address", "raise", "ArgumentError", ",", "\"Both `script` and `address` cannot be specified\"", "if", "script", "&&", "address", "raise", "ArgumentError", ",", "\"Amount must be greater than zero\"", "if", "!", "amount", "||", "amount", "<=", "0", "if", "source_output", "&&", "(", "!", "source_output", ".", "index", "||", "!", "source_output", ".", "transaction_hash", ")", "raise", "ArgumentError", ",", "\"If `source_output` is specified, it must have valid `transaction_hash` and `index` attributes\"", "end", "script", "||=", "AssetAddress", ".", "parse", "(", "address", ")", ".", "script", "if", "source_output", "if", "source_output", ".", "is_a?", "(", "AssetTransactionOutput", ")", "raise", "ArgumentError", ",", "\"Must be verified asset output to spend\"", "if", "!", "source_output", ".", "verified?", "else", "source_output", "=", "AssetTransactionOutput", ".", "new", "(", "transaction_output", ":", "source_output", ",", "verified", ":", "true", ")", "end", "end", "if", "!", "self", ".", "issuing_asset_script", "&&", "!", "self", ".", "issuing_asset_output", "self", ".", "issuing_asset_script", "=", "source_script", "self", ".", "issuing_asset_output", "=", "source_output", "else", "if", "self", ".", "issuing_asset_script", "!=", "source_script", "||", "self", ".", "issuing_asset_output", "!=", "source_output", "raise", "ArgumentError", ",", "\"Can't issue more assets from a different source script or source output\"", "end", "end", "self", ".", "issued_assets", "<<", "{", "amount", ":", "amount", ",", "script", ":", "script", "}", "end" ]
Adds an issuance of some assets. If `script` is specified, it is used to create an intermediate base transaction. If `output` is specified, it must be a valid spendable output with `transaction_id` and `index`. It can be regular TransactionOutput or verified AssetTransactionOutput. `amount` must be > 0 - number of units to be issued
[ "Adds", "an", "issuance", "of", "some", "assets", ".", "If", "script", "is", "specified", "it", "is", "used", "to", "create", "an", "intermediate", "base", "transaction", ".", "If", "output", "is", "specified", "it", "must", "be", "a", "valid", "spendable", "output", "with", "transaction_id", "and", "index", ".", "It", "can", "be", "regular", "TransactionOutput", "or", "verified", "AssetTransactionOutput", ".", "amount", "must", "be", ">", "0", "-", "number", "of", "units", "to", "be", "issued" ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/open_assets/asset_transaction_builder.rb#L63-L96
train
oleganza/btcruby
lib/btcruby/open_assets/asset_transaction_builder.rb
BTC.AssetTransactionBuilder.send_bitcoin
def send_bitcoin(output: nil, amount: nil, script: nil, address: nil) if !output raise ArgumentError, "Either `script` or `address` must be specified" if !script && !address raise ArgumentError, "Amount must be specified (>= 0)" if (!amount || amount < 0) script ||= address.public_address.script if address output = TransactionOutput.new(value: amount, script: script) end self.bitcoin_outputs << output end
ruby
def send_bitcoin(output: nil, amount: nil, script: nil, address: nil) if !output raise ArgumentError, "Either `script` or `address` must be specified" if !script && !address raise ArgumentError, "Amount must be specified (>= 0)" if (!amount || amount < 0) script ||= address.public_address.script if address output = TransactionOutput.new(value: amount, script: script) end self.bitcoin_outputs << output end
[ "def", "send_bitcoin", "(", "output", ":", "nil", ",", "amount", ":", "nil", ",", "script", ":", "nil", ",", "address", ":", "nil", ")", "if", "!", "output", "raise", "ArgumentError", ",", "\"Either `script` or `address` must be specified\"", "if", "!", "script", "&&", "!", "address", "raise", "ArgumentError", ",", "\"Amount must be specified (>= 0)\"", "if", "(", "!", "amount", "||", "amount", "<", "0", ")", "script", "||=", "address", ".", "public_address", ".", "script", "if", "address", "output", "=", "TransactionOutput", ".", "new", "(", "value", ":", "amount", ",", "script", ":", "script", ")", "end", "self", ".", "bitcoin_outputs", "<<", "output", "end" ]
Adds a normal payment output. Typically used for transfer
[ "Adds", "a", "normal", "payment", "output", ".", "Typically", "used", "for", "transfer" ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/open_assets/asset_transaction_builder.rb#L119-L127
train
oleganza/btcruby
lib/btcruby/script/cltv_extension.rb
BTC.CLTVExtension.handle_opcode
def handle_opcode(interpreter: nil, opcode: nil) # We are not supposed to handle any other opcodes here. return false if opcode != OP_CHECKLOCKTIMEVERIFY if interpreter.stack.size < 1 return interpreter.set_error(SCRIPT_ERR_INVALID_STACK_OPERATION) end # Note that elsewhere numeric opcodes are limited to # operands in the range -2**31+1 to 2**31-1, however it is # legal for opcodes to produce results exceeding that # range. This limitation is implemented by CScriptNum's # default 4-byte limit. # # If we kept to that limit we'd have a year 2038 problem, # even though the nLockTime field in transactions # themselves is uint32 which only becomes meaningless # after the year 2106. # # Thus as a special case we tell CScriptNum to accept up # to 5-byte bignums, which are good until 2**39-1, well # beyond the 2**32-1 limit of the nLockTime field itself. locktime = interpreter.cast_to_number(interpreter.stack.last, max_size: @locktime_max_size) # In the rare event that the argument may be < 0 due to # some arithmetic being done first, you can always use # 0 MAX CHECKLOCKTIMEVERIFY. if locktime < 0 return interpreter.set_error(SCRIPT_ERR_NEGATIVE_LOCKTIME) end # Actually compare the specified lock time with the transaction. checker = @lock_time_checker || interpreter.signature_checker if !checker.check_lock_time(locktime) return interpreter.set_error(SCRIPT_ERR_UNSATISFIED_LOCKTIME) end return true end
ruby
def handle_opcode(interpreter: nil, opcode: nil) # We are not supposed to handle any other opcodes here. return false if opcode != OP_CHECKLOCKTIMEVERIFY if interpreter.stack.size < 1 return interpreter.set_error(SCRIPT_ERR_INVALID_STACK_OPERATION) end # Note that elsewhere numeric opcodes are limited to # operands in the range -2**31+1 to 2**31-1, however it is # legal for opcodes to produce results exceeding that # range. This limitation is implemented by CScriptNum's # default 4-byte limit. # # If we kept to that limit we'd have a year 2038 problem, # even though the nLockTime field in transactions # themselves is uint32 which only becomes meaningless # after the year 2106. # # Thus as a special case we tell CScriptNum to accept up # to 5-byte bignums, which are good until 2**39-1, well # beyond the 2**32-1 limit of the nLockTime field itself. locktime = interpreter.cast_to_number(interpreter.stack.last, max_size: @locktime_max_size) # In the rare event that the argument may be < 0 due to # some arithmetic being done first, you can always use # 0 MAX CHECKLOCKTIMEVERIFY. if locktime < 0 return interpreter.set_error(SCRIPT_ERR_NEGATIVE_LOCKTIME) end # Actually compare the specified lock time with the transaction. checker = @lock_time_checker || interpreter.signature_checker if !checker.check_lock_time(locktime) return interpreter.set_error(SCRIPT_ERR_UNSATISFIED_LOCKTIME) end return true end
[ "def", "handle_opcode", "(", "interpreter", ":", "nil", ",", "opcode", ":", "nil", ")", "return", "false", "if", "opcode", "!=", "OP_CHECKLOCKTIMEVERIFY", "if", "interpreter", ".", "stack", ".", "size", "<", "1", "return", "interpreter", ".", "set_error", "(", "SCRIPT_ERR_INVALID_STACK_OPERATION", ")", "end", "locktime", "=", "interpreter", ".", "cast_to_number", "(", "interpreter", ".", "stack", ".", "last", ",", "max_size", ":", "@locktime_max_size", ")", "if", "locktime", "<", "0", "return", "interpreter", ".", "set_error", "(", "SCRIPT_ERR_NEGATIVE_LOCKTIME", ")", "end", "checker", "=", "@lock_time_checker", "||", "interpreter", ".", "signature_checker", "if", "!", "checker", ".", "check_lock_time", "(", "locktime", ")", "return", "interpreter", ".", "set_error", "(", "SCRIPT_ERR_UNSATISFIED_LOCKTIME", ")", "end", "return", "true", "end" ]
Returns `false` if failed to execute the opcode.
[ "Returns", "false", "if", "failed", "to", "execute", "the", "opcode", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/script/cltv_extension.rb#L22-L60
train
oleganza/btcruby
lib/btcruby/transaction_input.rb
BTC.TransactionInput.init_with_stream
def init_with_stream(stream) if stream.eof? raise ArgumentError, "Can't parse transaction input from stream because it is already closed." end if !(@previous_hash = stream.read(32)) || @previous_hash.bytesize != 32 raise ArgumentError, "Failed to read 32-byte previous_hash from stream." end if !(@previous_index = BTC::WireFormat.read_uint32le(stream: stream).first) raise ArgumentError, "Failed to read previous_index from stream." end is_coinbase = (@previous_hash == ZERO_HASH256 && @previous_index == INVALID_INDEX) if !(scriptdata = BTC::WireFormat.read_string(stream: stream).first) raise ArgumentError, "Failed to read signature_script data from stream." end @coinbase_data = nil @signature_script = nil if is_coinbase @coinbase_data = scriptdata else @signature_script = BTC::Script.new(data: scriptdata) end if !(@sequence = BTC::WireFormat.read_uint32le(stream: stream).first) raise ArgumentError, "Failed to read sequence from stream." end end
ruby
def init_with_stream(stream) if stream.eof? raise ArgumentError, "Can't parse transaction input from stream because it is already closed." end if !(@previous_hash = stream.read(32)) || @previous_hash.bytesize != 32 raise ArgumentError, "Failed to read 32-byte previous_hash from stream." end if !(@previous_index = BTC::WireFormat.read_uint32le(stream: stream).first) raise ArgumentError, "Failed to read previous_index from stream." end is_coinbase = (@previous_hash == ZERO_HASH256 && @previous_index == INVALID_INDEX) if !(scriptdata = BTC::WireFormat.read_string(stream: stream).first) raise ArgumentError, "Failed to read signature_script data from stream." end @coinbase_data = nil @signature_script = nil if is_coinbase @coinbase_data = scriptdata else @signature_script = BTC::Script.new(data: scriptdata) end if !(@sequence = BTC::WireFormat.read_uint32le(stream: stream).first) raise ArgumentError, "Failed to read sequence from stream." end end
[ "def", "init_with_stream", "(", "stream", ")", "if", "stream", ".", "eof?", "raise", "ArgumentError", ",", "\"Can't parse transaction input from stream because it is already closed.\"", "end", "if", "!", "(", "@previous_hash", "=", "stream", ".", "read", "(", "32", ")", ")", "||", "@previous_hash", ".", "bytesize", "!=", "32", "raise", "ArgumentError", ",", "\"Failed to read 32-byte previous_hash from stream.\"", "end", "if", "!", "(", "@previous_index", "=", "BTC", "::", "WireFormat", ".", "read_uint32le", "(", "stream", ":", "stream", ")", ".", "first", ")", "raise", "ArgumentError", ",", "\"Failed to read previous_index from stream.\"", "end", "is_coinbase", "=", "(", "@previous_hash", "==", "ZERO_HASH256", "&&", "@previous_index", "==", "INVALID_INDEX", ")", "if", "!", "(", "scriptdata", "=", "BTC", "::", "WireFormat", ".", "read_string", "(", "stream", ":", "stream", ")", ".", "first", ")", "raise", "ArgumentError", ",", "\"Failed to read signature_script data from stream.\"", "end", "@coinbase_data", "=", "nil", "@signature_script", "=", "nil", "if", "is_coinbase", "@coinbase_data", "=", "scriptdata", "else", "@signature_script", "=", "BTC", "::", "Script", ".", "new", "(", "data", ":", "scriptdata", ")", "end", "if", "!", "(", "@sequence", "=", "BTC", "::", "WireFormat", ".", "read_uint32le", "(", "stream", ":", "stream", ")", ".", "first", ")", "raise", "ArgumentError", ",", "\"Failed to read sequence from stream.\"", "end", "end" ]
Initializes transaction input with its attributes. Every attribute has a valid default value.
[ "Initializes", "transaction", "input", "with", "its", "attributes", ".", "Every", "attribute", "has", "a", "valid", "default", "value", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/transaction_input.rb#L101-L132
train
oleganza/btcruby
lib/btcruby/transaction.rb
BTC.Transaction.init_with_components
def init_with_components(version: CURRENT_VERSION, inputs: [], outputs: [], lock_time: 0) @version = version || CURRENT_VERSION @inputs = inputs || [] @outputs = outputs || [] @lock_time = lock_time || 0 @inputs.each_with_index do |txin, i| txin.transaction = self txin.index = i end @outputs.each_with_index do |txout, i| txout.transaction = self txout.index = i end end
ruby
def init_with_components(version: CURRENT_VERSION, inputs: [], outputs: [], lock_time: 0) @version = version || CURRENT_VERSION @inputs = inputs || [] @outputs = outputs || [] @lock_time = lock_time || 0 @inputs.each_with_index do |txin, i| txin.transaction = self txin.index = i end @outputs.each_with_index do |txout, i| txout.transaction = self txout.index = i end end
[ "def", "init_with_components", "(", "version", ":", "CURRENT_VERSION", ",", "inputs", ":", "[", "]", ",", "outputs", ":", "[", "]", ",", "lock_time", ":", "0", ")", "@version", "=", "version", "||", "CURRENT_VERSION", "@inputs", "=", "inputs", "||", "[", "]", "@outputs", "=", "outputs", "||", "[", "]", "@lock_time", "=", "lock_time", "||", "0", "@inputs", ".", "each_with_index", "do", "|", "txin", ",", "i", "|", "txin", ".", "transaction", "=", "self", "txin", ".", "index", "=", "i", "end", "@outputs", ".", "each_with_index", "do", "|", "txout", ",", "i", "|", "txout", ".", "transaction", "=", "self", "txout", ".", "index", "=", "i", "end", "end" ]
Initializes transaction with its attributes. Every attribute has a valid default value.
[ "Initializes", "transaction", "with", "its", "attributes", ".", "Every", "attribute", "has", "a", "valid", "default", "value", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/transaction.rb#L119-L132
train
oleganza/btcruby
lib/btcruby/transaction.rb
BTC.Transaction.add_input
def add_input(txin) raise ArgumentError, "Input is missing" if !txin if !(txin.transaction == nil || txin.transaction == self) raise ArgumentError, "Can't add an input to a transaction when it references another transaction" # sanity check end txin.transaction = self txin.index = @inputs.size @inputs << txin self end
ruby
def add_input(txin) raise ArgumentError, "Input is missing" if !txin if !(txin.transaction == nil || txin.transaction == self) raise ArgumentError, "Can't add an input to a transaction when it references another transaction" # sanity check end txin.transaction = self txin.index = @inputs.size @inputs << txin self end
[ "def", "add_input", "(", "txin", ")", "raise", "ArgumentError", ",", "\"Input is missing\"", "if", "!", "txin", "if", "!", "(", "txin", ".", "transaction", "==", "nil", "||", "txin", ".", "transaction", "==", "self", ")", "raise", "ArgumentError", ",", "\"Can't add an input to a transaction when it references another transaction\"", "end", "txin", ".", "transaction", "=", "self", "txin", ".", "index", "=", "@inputs", ".", "size", "@inputs", "<<", "txin", "self", "end" ]
Adds another input to the transaction.
[ "Adds", "another", "input", "to", "the", "transaction", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/transaction.rb#L208-L217
train
oleganza/btcruby
lib/btcruby/data.rb
BTC.Data.data_from_hex
def data_from_hex(hex_string) raise ArgumentError, "Hex string is missing" if !hex_string hex_string = hex_string.strip data = [hex_string].pack(HEX_PACK_CODE) if hex_from_data(data) != hex_string.downcase # invalid hex string was detected raise FormatError, "Hex string is invalid: #{hex_string.inspect}" end return data end
ruby
def data_from_hex(hex_string) raise ArgumentError, "Hex string is missing" if !hex_string hex_string = hex_string.strip data = [hex_string].pack(HEX_PACK_CODE) if hex_from_data(data) != hex_string.downcase # invalid hex string was detected raise FormatError, "Hex string is invalid: #{hex_string.inspect}" end return data end
[ "def", "data_from_hex", "(", "hex_string", ")", "raise", "ArgumentError", ",", "\"Hex string is missing\"", "if", "!", "hex_string", "hex_string", "=", "hex_string", ".", "strip", "data", "=", "[", "hex_string", "]", ".", "pack", "(", "HEX_PACK_CODE", ")", "if", "hex_from_data", "(", "data", ")", "!=", "hex_string", ".", "downcase", "raise", "FormatError", ",", "\"Hex string is invalid: #{hex_string.inspect}\"", "end", "return", "data", "end" ]
Converts hexadecimal string to a binary data string.
[ "Converts", "hexadecimal", "string", "to", "a", "binary", "data", "string", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/data.rb#L22-L30
train
oleganza/btcruby
lib/btcruby/openssl.rb
BTC.OpenSSL.regenerate_keypair
def regenerate_keypair(private_key, public_key_compressed: false) autorelease do |pool| eckey = pool.new_ec_key priv_bn = pool.new_bn(private_key) pub_key = pool.new_ec_point EC_POINT_mul(self.group, pub_key, priv_bn, nil, nil, pool.bn_ctx) EC_KEY_set_private_key(eckey, priv_bn) EC_KEY_set_public_key(eckey, pub_key) length = i2d_ECPrivateKey(eckey, nil) buf = FFI::MemoryPointer.new(:uint8, length) if i2d_ECPrivateKey(eckey, pointer_to_pointer(buf)) == length # We have a full DER representation of private key, it contains a length # of a private key at offset 8 and private key at offset 9. size = buf.get_array_of_uint8(8, 1)[0] private_key2 = buf.get_array_of_uint8(9, size).pack("C*").rjust(32, "\x00") else raise BTCError, "OpenSSL failed to convert private key to DER format" end if private_key2 != private_key raise BTCError, "OpenSSL somehow regenerated a wrong private key." end EC_KEY_set_conv_form(eckey, public_key_compressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED); length = i2o_ECPublicKey(eckey, nil) buf = FFI::MemoryPointer.new(:uint8, length) if i2o_ECPublicKey(eckey, pointer_to_pointer(buf)) == length public_key = buf.read_string(length) else raise BTCError, "OpenSSL failed to regenerate a public key." end [ private_key2, public_key ] end end
ruby
def regenerate_keypair(private_key, public_key_compressed: false) autorelease do |pool| eckey = pool.new_ec_key priv_bn = pool.new_bn(private_key) pub_key = pool.new_ec_point EC_POINT_mul(self.group, pub_key, priv_bn, nil, nil, pool.bn_ctx) EC_KEY_set_private_key(eckey, priv_bn) EC_KEY_set_public_key(eckey, pub_key) length = i2d_ECPrivateKey(eckey, nil) buf = FFI::MemoryPointer.new(:uint8, length) if i2d_ECPrivateKey(eckey, pointer_to_pointer(buf)) == length # We have a full DER representation of private key, it contains a length # of a private key at offset 8 and private key at offset 9. size = buf.get_array_of_uint8(8, 1)[0] private_key2 = buf.get_array_of_uint8(9, size).pack("C*").rjust(32, "\x00") else raise BTCError, "OpenSSL failed to convert private key to DER format" end if private_key2 != private_key raise BTCError, "OpenSSL somehow regenerated a wrong private key." end EC_KEY_set_conv_form(eckey, public_key_compressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED); length = i2o_ECPublicKey(eckey, nil) buf = FFI::MemoryPointer.new(:uint8, length) if i2o_ECPublicKey(eckey, pointer_to_pointer(buf)) == length public_key = buf.read_string(length) else raise BTCError, "OpenSSL failed to regenerate a public key." end [ private_key2, public_key ] end end
[ "def", "regenerate_keypair", "(", "private_key", ",", "public_key_compressed", ":", "false", ")", "autorelease", "do", "|", "pool", "|", "eckey", "=", "pool", ".", "new_ec_key", "priv_bn", "=", "pool", ".", "new_bn", "(", "private_key", ")", "pub_key", "=", "pool", ".", "new_ec_point", "EC_POINT_mul", "(", "self", ".", "group", ",", "pub_key", ",", "priv_bn", ",", "nil", ",", "nil", ",", "pool", ".", "bn_ctx", ")", "EC_KEY_set_private_key", "(", "eckey", ",", "priv_bn", ")", "EC_KEY_set_public_key", "(", "eckey", ",", "pub_key", ")", "length", "=", "i2d_ECPrivateKey", "(", "eckey", ",", "nil", ")", "buf", "=", "FFI", "::", "MemoryPointer", ".", "new", "(", ":uint8", ",", "length", ")", "if", "i2d_ECPrivateKey", "(", "eckey", ",", "pointer_to_pointer", "(", "buf", ")", ")", "==", "length", "size", "=", "buf", ".", "get_array_of_uint8", "(", "8", ",", "1", ")", "[", "0", "]", "private_key2", "=", "buf", ".", "get_array_of_uint8", "(", "9", ",", "size", ")", ".", "pack", "(", "\"C*\"", ")", ".", "rjust", "(", "32", ",", "\"\\x00\"", ")", "else", "raise", "BTCError", ",", "\"OpenSSL failed to convert private key to DER format\"", "end", "if", "private_key2", "!=", "private_key", "raise", "BTCError", ",", "\"OpenSSL somehow regenerated a wrong private key.\"", "end", "EC_KEY_set_conv_form", "(", "eckey", ",", "public_key_compressed", "?", "POINT_CONVERSION_COMPRESSED", ":", "POINT_CONVERSION_UNCOMPRESSED", ")", ";", "length", "=", "i2o_ECPublicKey", "(", "eckey", ",", "nil", ")", "buf", "=", "FFI", "::", "MemoryPointer", ".", "new", "(", ":uint8", ",", "length", ")", "if", "i2o_ECPublicKey", "(", "eckey", ",", "pointer_to_pointer", "(", "buf", ")", ")", "==", "length", "public_key", "=", "buf", ".", "read_string", "(", "length", ")", "else", "raise", "BTCError", ",", "\"OpenSSL failed to regenerate a public key.\"", "end", "[", "private_key2", ",", "public_key", "]", "end", "end" ]
Returns a pair of private key, public key
[ "Returns", "a", "pair", "of", "private", "key", "public", "key" ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/openssl.rb#L174-L214
train
oleganza/btcruby
lib/btcruby/openssl.rb
BTC.OpenSSL.private_key_from_der_format
def private_key_from_der_format(der_key) raise ArgumentError, "Missing DER private key" if !der_key prepare_if_needed buf = FFI::MemoryPointer.from_string(der_key) ec_key = d2i_ECPrivateKey(nil, pointer_to_pointer(buf), buf.size-1) if ec_key.null? raise BTCError, "OpenSSL failed to create EC_KEY with DER private key" end bn = EC_KEY_get0_private_key(ec_key) BN_bn2bin(bn, buf) buf.read_string(32) end
ruby
def private_key_from_der_format(der_key) raise ArgumentError, "Missing DER private key" if !der_key prepare_if_needed buf = FFI::MemoryPointer.from_string(der_key) ec_key = d2i_ECPrivateKey(nil, pointer_to_pointer(buf), buf.size-1) if ec_key.null? raise BTCError, "OpenSSL failed to create EC_KEY with DER private key" end bn = EC_KEY_get0_private_key(ec_key) BN_bn2bin(bn, buf) buf.read_string(32) end
[ "def", "private_key_from_der_format", "(", "der_key", ")", "raise", "ArgumentError", ",", "\"Missing DER private key\"", "if", "!", "der_key", "prepare_if_needed", "buf", "=", "FFI", "::", "MemoryPointer", ".", "from_string", "(", "der_key", ")", "ec_key", "=", "d2i_ECPrivateKey", "(", "nil", ",", "pointer_to_pointer", "(", "buf", ")", ",", "buf", ".", "size", "-", "1", ")", "if", "ec_key", ".", "null?", "raise", "BTCError", ",", "\"OpenSSL failed to create EC_KEY with DER private key\"", "end", "bn", "=", "EC_KEY_get0_private_key", "(", "ec_key", ")", "BN_bn2bin", "(", "bn", ",", "buf", ")", "buf", ".", "read_string", "(", "32", ")", "end" ]
extract private key from uncompressed DER format
[ "extract", "private", "key", "from", "uncompressed", "DER", "format" ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/openssl.rb#L440-L453
train
oleganza/btcruby
lib/btcruby/openssl.rb
BTC.OpenSSL.data_from_bn
def data_from_bn(bn, min_length: nil, required_length: nil) raise ArgumentError, "Missing big number" if !bn length = BN_num_bytes(bn) buf = FFI::MemoryPointer.from_string("\x00"*length) BN_bn2bin(bn, buf) s = buf.read_string(length) s = s.rjust(min_length, "\x00") if min_length if required_length && s.bytesize != required_length raise BTCError, "Non-matching length of the number: #{s.bytesize} bytes vs required #{required_length}" end s end
ruby
def data_from_bn(bn, min_length: nil, required_length: nil) raise ArgumentError, "Missing big number" if !bn length = BN_num_bytes(bn) buf = FFI::MemoryPointer.from_string("\x00"*length) BN_bn2bin(bn, buf) s = buf.read_string(length) s = s.rjust(min_length, "\x00") if min_length if required_length && s.bytesize != required_length raise BTCError, "Non-matching length of the number: #{s.bytesize} bytes vs required #{required_length}" end s end
[ "def", "data_from_bn", "(", "bn", ",", "min_length", ":", "nil", ",", "required_length", ":", "nil", ")", "raise", "ArgumentError", ",", "\"Missing big number\"", "if", "!", "bn", "length", "=", "BN_num_bytes", "(", "bn", ")", "buf", "=", "FFI", "::", "MemoryPointer", ".", "from_string", "(", "\"\\x00\"", "*", "length", ")", "BN_bn2bin", "(", "bn", ",", "buf", ")", "s", "=", "buf", ".", "read_string", "(", "length", ")", "s", "=", "s", ".", "rjust", "(", "min_length", ",", "\"\\x00\"", ")", "if", "min_length", "if", "required_length", "&&", "s", ".", "bytesize", "!=", "required_length", "raise", "BTCError", ",", "\"Non-matching length of the number: #{s.bytesize} bytes vs required #{required_length}\"", "end", "s", "end" ]
Returns data from bignum
[ "Returns", "data", "from", "bignum" ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/openssl.rb#L456-L468
train
oleganza/btcruby
lib/btcruby/wire_format.rb
BTC.WireFormat.encode_varint
def encode_varint(i) raise ArgumentError, "int must be present" if !i raise ArgumentError, "int must be non-negative" if i < 0 buf = if i < 0xfd [i].pack("C") elsif i <= 0xffff [0xfd, i].pack("Cv") elsif i <= 0xffffffff [0xfe, i].pack("CV") elsif i <= 0xffffffffffffffff [0xff, i].pack("CQ<") else raise ArgumentError, "Does not support integers larger 0xffffffffffffffff (i = 0x#{i.to_s(16)})" end buf end
ruby
def encode_varint(i) raise ArgumentError, "int must be present" if !i raise ArgumentError, "int must be non-negative" if i < 0 buf = if i < 0xfd [i].pack("C") elsif i <= 0xffff [0xfd, i].pack("Cv") elsif i <= 0xffffffff [0xfe, i].pack("CV") elsif i <= 0xffffffffffffffff [0xff, i].pack("CQ<") else raise ArgumentError, "Does not support integers larger 0xffffffffffffffff (i = 0x#{i.to_s(16)})" end buf end
[ "def", "encode_varint", "(", "i", ")", "raise", "ArgumentError", ",", "\"int must be present\"", "if", "!", "i", "raise", "ArgumentError", ",", "\"int must be non-negative\"", "if", "i", "<", "0", "buf", "=", "if", "i", "<", "0xfd", "[", "i", "]", ".", "pack", "(", "\"C\"", ")", "elsif", "i", "<=", "0xffff", "[", "0xfd", ",", "i", "]", ".", "pack", "(", "\"Cv\"", ")", "elsif", "i", "<=", "0xffffffff", "[", "0xfe", ",", "i", "]", ".", "pack", "(", "\"CV\"", ")", "elsif", "i", "<=", "0xffffffffffffffff", "[", "0xff", ",", "i", "]", ".", "pack", "(", "\"CQ<\"", ")", "else", "raise", "ArgumentError", ",", "\"Does not support integers larger 0xffffffffffffffff (i = 0x#{i.to_s(16)})\"", "end", "buf", "end" ]
read_varint Encodes integer and returns its binary varint representation.
[ "read_varint", "Encodes", "integer", "and", "returns", "its", "binary", "varint", "representation", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/wire_format.rb#L101-L118
train
oleganza/btcruby
lib/btcruby/wire_format.rb
BTC.WireFormat.write_varint
def write_varint(i, data: nil, stream: nil) buf = encode_varint(i) data << buf if data stream.write(buf) if stream buf end
ruby
def write_varint(i, data: nil, stream: nil) buf = encode_varint(i) data << buf if data stream.write(buf) if stream buf end
[ "def", "write_varint", "(", "i", ",", "data", ":", "nil", ",", "stream", ":", "nil", ")", "buf", "=", "encode_varint", "(", "i", ")", "data", "<<", "buf", "if", "data", "stream", ".", "write", "(", "buf", ")", "if", "stream", "buf", "end" ]
Encodes integer and returns its binary varint representation. If data is given, appends to a data. If stream is given, writes to a stream.
[ "Encodes", "integer", "and", "returns", "its", "binary", "varint", "representation", ".", "If", "data", "is", "given", "appends", "to", "a", "data", ".", "If", "stream", "is", "given", "writes", "to", "a", "stream", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/wire_format.rb#L123-L128
train
oleganza/btcruby
lib/btcruby/wire_format.rb
BTC.WireFormat.encode_string
def encode_string(string) raise ArgumentError, "String must be present" if !string encode_varint(string.bytesize) + BTC::Data.ensure_binary_encoding(string) end
ruby
def encode_string(string) raise ArgumentError, "String must be present" if !string encode_varint(string.bytesize) + BTC::Data.ensure_binary_encoding(string) end
[ "def", "encode_string", "(", "string", ")", "raise", "ArgumentError", ",", "\"String must be present\"", "if", "!", "string", "encode_varint", "(", "string", ".", "bytesize", ")", "+", "BTC", "::", "Data", ".", "ensure_binary_encoding", "(", "string", ")", "end" ]
Returns the binary representation of the var-length string.
[ "Returns", "the", "binary", "representation", "of", "the", "var", "-", "length", "string", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/wire_format.rb#L166-L169
train
oleganza/btcruby
lib/btcruby/wire_format.rb
BTC.WireFormat.write_string
def write_string(string, data: nil, stream: nil) raise ArgumentError, "String must be present" if !string intbuf = write_varint(string.bytesize, data: data, stream: stream) stringbuf = BTC::Data.ensure_binary_encoding(string) data << stringbuf if data stream.write(stringbuf) if stream intbuf + stringbuf end
ruby
def write_string(string, data: nil, stream: nil) raise ArgumentError, "String must be present" if !string intbuf = write_varint(string.bytesize, data: data, stream: stream) stringbuf = BTC::Data.ensure_binary_encoding(string) data << stringbuf if data stream.write(stringbuf) if stream intbuf + stringbuf end
[ "def", "write_string", "(", "string", ",", "data", ":", "nil", ",", "stream", ":", "nil", ")", "raise", "ArgumentError", ",", "\"String must be present\"", "if", "!", "string", "intbuf", "=", "write_varint", "(", "string", ".", "bytesize", ",", "data", ":", "data", ",", "stream", ":", "stream", ")", "stringbuf", "=", "BTC", "::", "Data", ".", "ensure_binary_encoding", "(", "string", ")", "data", "<<", "stringbuf", "if", "data", "stream", ".", "write", "(", "stringbuf", ")", "if", "stream", "intbuf", "+", "stringbuf", "end" ]
Writes variable-length string to a data buffer or IO stream. If data is given, appends to a data. If stream is given, writes to a stream. Returns the binary representation of the var-length string.
[ "Writes", "variable", "-", "length", "string", "to", "a", "data", "buffer", "or", "IO", "stream", ".", "If", "data", "is", "given", "appends", "to", "a", "data", ".", "If", "stream", "is", "given", "writes", "to", "a", "stream", ".", "Returns", "the", "binary", "representation", "of", "the", "var", "-", "length", "string", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/wire_format.rb#L175-L186
train
oleganza/btcruby
lib/btcruby/wire_format.rb
BTC.WireFormat.read_array
def read_array(data: nil, stream: nil, offset: 0) count, len = read_varint(data: data, stream: stream, offset: offset) return [nil, len] if !count (0...count).map do |i| yield end end
ruby
def read_array(data: nil, stream: nil, offset: 0) count, len = read_varint(data: data, stream: stream, offset: offset) return [nil, len] if !count (0...count).map do |i| yield end end
[ "def", "read_array", "(", "data", ":", "nil", ",", "stream", ":", "nil", ",", "offset", ":", "0", ")", "count", ",", "len", "=", "read_varint", "(", "data", ":", "data", ",", "stream", ":", "stream", ",", "offset", ":", "offset", ")", "return", "[", "nil", ",", "len", "]", "if", "!", "count", "(", "0", "...", "count", ")", ".", "map", "do", "|", "i", "|", "yield", "end", "end" ]
Reads varint length prefix, then calls the block appropriate number of times to read the items. Returns an array of items.
[ "Reads", "varint", "length", "prefix", "then", "calls", "the", "block", "appropriate", "number", "of", "times", "to", "read", "the", "items", ".", "Returns", "an", "array", "of", "items", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/wire_format.rb#L191-L197
train
oleganza/btcruby
lib/btcruby/wire_format.rb
BTC.WireFormat.encode_uleb128
def encode_uleb128(value) raise ArgumentError, "Signed integers are not supported" if value < 0 return "\x00" if value == 0 bytes = [] while value != 0 byte = value & 0b01111111 # 0x7f value >>= 7 if value != 0 byte |= 0b10000000 # 0x80 end bytes << byte end return BTC::Data.data_from_bytes(bytes) end
ruby
def encode_uleb128(value) raise ArgumentError, "Signed integers are not supported" if value < 0 return "\x00" if value == 0 bytes = [] while value != 0 byte = value & 0b01111111 # 0x7f value >>= 7 if value != 0 byte |= 0b10000000 # 0x80 end bytes << byte end return BTC::Data.data_from_bytes(bytes) end
[ "def", "encode_uleb128", "(", "value", ")", "raise", "ArgumentError", ",", "\"Signed integers are not supported\"", "if", "value", "<", "0", "return", "\"\\x00\"", "if", "value", "==", "0", "bytes", "=", "[", "]", "while", "value", "!=", "0", "byte", "=", "value", "&", "0b01111111", "value", ">>=", "7", "if", "value", "!=", "0", "byte", "|=", "0b10000000", "end", "bytes", "<<", "byte", "end", "return", "BTC", "::", "Data", ".", "data_from_bytes", "(", "bytes", ")", "end" ]
Encodes an unsigned integer using LEB128.
[ "Encodes", "an", "unsigned", "integer", "using", "LEB128", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/wire_format.rb#L263-L276
train
oleganza/btcruby
lib/btcruby/wire_format.rb
BTC.WireFormat.write_uleb128
def write_uleb128(value, data: nil, stream: nil) raise ArgumentError, "Integer must be present" if !value buf = encode_uleb128(value) data << buf if data stream.write(buf) if stream buf end
ruby
def write_uleb128(value, data: nil, stream: nil) raise ArgumentError, "Integer must be present" if !value buf = encode_uleb128(value) data << buf if data stream.write(buf) if stream buf end
[ "def", "write_uleb128", "(", "value", ",", "data", ":", "nil", ",", "stream", ":", "nil", ")", "raise", "ArgumentError", ",", "\"Integer must be present\"", "if", "!", "value", "buf", "=", "encode_uleb128", "(", "value", ")", "data", "<<", "buf", "if", "data", "stream", ".", "write", "(", "buf", ")", "if", "stream", "buf", "end" ]
Writes an unsigned integer encoded in LEB128 to a data buffer or a stream. Returns LEB128-encoded binary string.
[ "Writes", "an", "unsigned", "integer", "encoded", "in", "LEB128", "to", "a", "data", "buffer", "or", "a", "stream", ".", "Returns", "LEB128", "-", "encoded", "binary", "string", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/wire_format.rb#L280-L286
train
pluginaweek/preferences
lib/preferences.rb
Preferences.InstanceMethods.preferences
def preferences(group = nil) preferences = preferences_group(group) unless preferences_group_loaded?(group) group_id, group_type = Preference.split_group(group) find_preferences(:group_id => group_id, :group_type => group_type).each do |preference| preferences[preference.name] = preference.value unless preferences.include?(preference.name) end # Add defaults preference_definitions.each do |name, definition| preferences[name] = definition.default_value(group_type) unless preferences.include?(name) end end preferences.inject({}) do |typed_preferences, (name, value)| typed_preferences[name] = value.nil? ? value : preference_definitions[name].type_cast(value) typed_preferences end end
ruby
def preferences(group = nil) preferences = preferences_group(group) unless preferences_group_loaded?(group) group_id, group_type = Preference.split_group(group) find_preferences(:group_id => group_id, :group_type => group_type).each do |preference| preferences[preference.name] = preference.value unless preferences.include?(preference.name) end # Add defaults preference_definitions.each do |name, definition| preferences[name] = definition.default_value(group_type) unless preferences.include?(name) end end preferences.inject({}) do |typed_preferences, (name, value)| typed_preferences[name] = value.nil? ? value : preference_definitions[name].type_cast(value) typed_preferences end end
[ "def", "preferences", "(", "group", "=", "nil", ")", "preferences", "=", "preferences_group", "(", "group", ")", "unless", "preferences_group_loaded?", "(", "group", ")", "group_id", ",", "group_type", "=", "Preference", ".", "split_group", "(", "group", ")", "find_preferences", "(", ":group_id", "=>", "group_id", ",", ":group_type", "=>", "group_type", ")", ".", "each", "do", "|", "preference", "|", "preferences", "[", "preference", ".", "name", "]", "=", "preference", ".", "value", "unless", "preferences", ".", "include?", "(", "preference", ".", "name", ")", "end", "preference_definitions", ".", "each", "do", "|", "name", ",", "definition", "|", "preferences", "[", "name", "]", "=", "definition", ".", "default_value", "(", "group_type", ")", "unless", "preferences", ".", "include?", "(", "name", ")", "end", "end", "preferences", ".", "inject", "(", "{", "}", ")", "do", "|", "typed_preferences", ",", "(", "name", ",", "value", ")", "|", "typed_preferences", "[", "name", "]", "=", "value", ".", "nil?", "?", "value", ":", "preference_definitions", "[", "name", "]", ".", "type_cast", "(", "value", ")", "typed_preferences", "end", "end" ]
Finds all preferences, including defaults, for the current record. If looking up custom group preferences, then this will include all default preferences within that particular group as well. == Examples A user with no stored values: user = User.find(:first) user.preferences => {"language"=>"English", "color"=>nil} A user with stored values for a particular group: user.preferred_color = 'red', :cars user.preferences(:cars) => {"language=>"English", "color"=>"red"}
[ "Finds", "all", "preferences", "including", "defaults", "for", "the", "current", "record", ".", "If", "looking", "up", "custom", "group", "preferences", "then", "this", "will", "include", "all", "default", "preferences", "within", "that", "particular", "group", "as", "well", "." ]
949894e579eb705e208c70af05179c16a65fd406
https://github.com/pluginaweek/preferences/blob/949894e579eb705e208c70af05179c16a65fd406/lib/preferences.rb#L305-L324
train
pluginaweek/preferences
lib/preferences.rb
Preferences.InstanceMethods.preferred?
def preferred?(name, group = nil) name = name.to_s assert_valid_preference(name) value = preferred(name, group) preference_definitions[name].query(value) end
ruby
def preferred?(name, group = nil) name = name.to_s assert_valid_preference(name) value = preferred(name, group) preference_definitions[name].query(value) end
[ "def", "preferred?", "(", "name", ",", "group", "=", "nil", ")", "name", "=", "name", ".", "to_s", "assert_valid_preference", "(", "name", ")", "value", "=", "preferred", "(", "name", ",", "group", ")", "preference_definitions", "[", "name", "]", ".", "query", "(", "value", ")", "end" ]
Queries whether or not a value is present for the given preference. This is dependent on how the value is type-casted. == Examples class User < ActiveRecord::Base preference :color, :string, :default => 'red' end user = User.create user.preferred(:color) # => "red" user.preferred?(:color) # => true user.preferred?(:color, 'cars') # => true user.preferred?(:color, Car.first) # => true user.write_preference(:color, nil) user.preferred(:color) # => nil user.preferred?(:color) # => false
[ "Queries", "whether", "or", "not", "a", "value", "is", "present", "for", "the", "given", "preference", ".", "This", "is", "dependent", "on", "how", "the", "value", "is", "type", "-", "casted", "." ]
949894e579eb705e208c70af05179c16a65fd406
https://github.com/pluginaweek/preferences/blob/949894e579eb705e208c70af05179c16a65fd406/lib/preferences.rb#L344-L350
train
pluginaweek/preferences
lib/preferences.rb
Preferences.InstanceMethods.preferred
def preferred(name, group = nil) name = name.to_s assert_valid_preference(name) if preferences_group(group).include?(name) # Value for this group/name has been written, but not saved yet: # grab from the pending values value = preferences_group(group)[name] else # Grab the first preference; if it doesn't exist, use the default value group_id, group_type = Preference.split_group(group) preference = find_preferences(:name => name, :group_id => group_id, :group_type => group_type).first unless preferences_group_loaded?(group) value = preference ? preference.value : preference_definitions[name].default_value(group_type) preferences_group(group)[name] = value end definition = preference_definitions[name] value = definition.type_cast(value) unless value.nil? value end
ruby
def preferred(name, group = nil) name = name.to_s assert_valid_preference(name) if preferences_group(group).include?(name) # Value for this group/name has been written, but not saved yet: # grab from the pending values value = preferences_group(group)[name] else # Grab the first preference; if it doesn't exist, use the default value group_id, group_type = Preference.split_group(group) preference = find_preferences(:name => name, :group_id => group_id, :group_type => group_type).first unless preferences_group_loaded?(group) value = preference ? preference.value : preference_definitions[name].default_value(group_type) preferences_group(group)[name] = value end definition = preference_definitions[name] value = definition.type_cast(value) unless value.nil? value end
[ "def", "preferred", "(", "name", ",", "group", "=", "nil", ")", "name", "=", "name", ".", "to_s", "assert_valid_preference", "(", "name", ")", "if", "preferences_group", "(", "group", ")", ".", "include?", "(", "name", ")", "value", "=", "preferences_group", "(", "group", ")", "[", "name", "]", "else", "group_id", ",", "group_type", "=", "Preference", ".", "split_group", "(", "group", ")", "preference", "=", "find_preferences", "(", ":name", "=>", "name", ",", ":group_id", "=>", "group_id", ",", ":group_type", "=>", "group_type", ")", ".", "first", "unless", "preferences_group_loaded?", "(", "group", ")", "value", "=", "preference", "?", "preference", ".", "value", ":", "preference_definitions", "[", "name", "]", ".", "default_value", "(", "group_type", ")", "preferences_group", "(", "group", ")", "[", "name", "]", "=", "value", "end", "definition", "=", "preference_definitions", "[", "name", "]", "value", "=", "definition", ".", "type_cast", "(", "value", ")", "unless", "value", ".", "nil?", "value", "end" ]
Gets the actual value stored for the given preference, or the default value if nothing is present. == Examples class User < ActiveRecord::Base preference :color, :string, :default => 'red' end user = User.create user.preferred(:color) # => "red" user.preferred(:color, 'cars') # => "red" user.preferred(:color, Car.first) # => "red" user.write_preference(:color, 'blue') user.preferred(:color) # => "blue"
[ "Gets", "the", "actual", "value", "stored", "for", "the", "given", "preference", "or", "the", "default", "value", "if", "nothing", "is", "present", "." ]
949894e579eb705e208c70af05179c16a65fd406
https://github.com/pluginaweek/preferences/blob/949894e579eb705e208c70af05179c16a65fd406/lib/preferences.rb#L369-L389
train
pluginaweek/preferences
lib/preferences.rb
Preferences.InstanceMethods.preference_changes
def preference_changes(group = nil) preferences_changed(group).inject({}) do |changes, preference| changes[preference] = preference_change(preference, group) changes end end
ruby
def preference_changes(group = nil) preferences_changed(group).inject({}) do |changes, preference| changes[preference] = preference_change(preference, group) changes end end
[ "def", "preference_changes", "(", "group", "=", "nil", ")", "preferences_changed", "(", "group", ")", ".", "inject", "(", "{", "}", ")", "do", "|", "changes", ",", "preference", "|", "changes", "[", "preference", "]", "=", "preference_change", "(", "preference", ",", "group", ")", "changes", "end", "end" ]
A map of the preferences that have changed in the current object. == Examples user = User.find(:first) user.preferred(:color) # => nil user.preference_changes # => {} user.write_preference(:color, 'red') user.preference_changes # => {"color" => [nil, "red"]} user.save user.preference_changes # => {} # Groups user.preferred(:color, :car) # => nil user.preference_changes(:car) # => {} user.write_preference(:color, 'red', :car) user.preference_changes(:car) # => {"color" => [nil, "red"]}
[ "A", "map", "of", "the", "preferences", "that", "have", "changed", "in", "the", "current", "object", "." ]
949894e579eb705e208c70af05179c16a65fd406
https://github.com/pluginaweek/preferences/blob/949894e579eb705e208c70af05179c16a65fd406/lib/preferences.rb#L481-L486
train
pluginaweek/preferences
lib/preferences.rb
Preferences.InstanceMethods.preference_was
def preference_was(name, group) preference_changed?(name, group) ? preferences_changed_group(group)[name] : preferred(name, group) end
ruby
def preference_was(name, group) preference_changed?(name, group) ? preferences_changed_group(group)[name] : preferred(name, group) end
[ "def", "preference_was", "(", "name", ",", "group", ")", "preference_changed?", "(", "name", ",", "group", ")", "?", "preferences_changed_group", "(", "group", ")", "[", "name", "]", ":", "preferred", "(", "name", ",", "group", ")", "end" ]
Gets the last saved value for the given preference
[ "Gets", "the", "last", "saved", "value", "for", "the", "given", "preference" ]
949894e579eb705e208c70af05179c16a65fd406
https://github.com/pluginaweek/preferences/blob/949894e579eb705e208c70af05179c16a65fd406/lib/preferences.rb#L545-L547
train
pluginaweek/preferences
lib/preferences.rb
Preferences.InstanceMethods.reset_preference!
def reset_preference!(name, group) write_preference(name, preferences_changed_group(group)[name], group) if preference_changed?(name, group) end
ruby
def reset_preference!(name, group) write_preference(name, preferences_changed_group(group)[name], group) if preference_changed?(name, group) end
[ "def", "reset_preference!", "(", "name", ",", "group", ")", "write_preference", "(", "name", ",", "preferences_changed_group", "(", "group", ")", "[", "name", "]", ",", "group", ")", "if", "preference_changed?", "(", "name", ",", "group", ")", "end" ]
Reverts any unsaved changes to the given preference
[ "Reverts", "any", "unsaved", "changes", "to", "the", "given", "preference" ]
949894e579eb705e208c70af05179c16a65fd406
https://github.com/pluginaweek/preferences/blob/949894e579eb705e208c70af05179c16a65fd406/lib/preferences.rb#L556-L558
train
pluginaweek/preferences
lib/preferences.rb
Preferences.InstanceMethods.preference_value_changed?
def preference_value_changed?(name, old, value) definition = preference_definitions[name] if definition.type == :integer && (old.nil? || old == 0) # For nullable numeric columns, NULL gets stored in database for blank (i.e. '') values. # Hence we don't record it as a change if the value changes from nil to ''. # If an old value of 0 is set to '' we want this to get changed to nil as otherwise it'll # be typecast back to 0 (''.to_i => 0) value = nil if value.blank? else value = definition.type_cast(value) end old != value end
ruby
def preference_value_changed?(name, old, value) definition = preference_definitions[name] if definition.type == :integer && (old.nil? || old == 0) # For nullable numeric columns, NULL gets stored in database for blank (i.e. '') values. # Hence we don't record it as a change if the value changes from nil to ''. # If an old value of 0 is set to '' we want this to get changed to nil as otherwise it'll # be typecast back to 0 (''.to_i => 0) value = nil if value.blank? else value = definition.type_cast(value) end old != value end
[ "def", "preference_value_changed?", "(", "name", ",", "old", ",", "value", ")", "definition", "=", "preference_definitions", "[", "name", "]", "if", "definition", ".", "type", "==", ":integer", "&&", "(", "old", ".", "nil?", "||", "old", "==", "0", ")", "value", "=", "nil", "if", "value", ".", "blank?", "else", "value", "=", "definition", ".", "type_cast", "(", "value", ")", "end", "old", "!=", "value", "end" ]
Determines whether the old value is different from the new value for the given preference. This will use the typecasted value to determine equality.
[ "Determines", "whether", "the", "old", "value", "is", "different", "from", "the", "new", "value", "for", "the", "given", "preference", ".", "This", "will", "use", "the", "typecasted", "value", "to", "determine", "equality", "." ]
949894e579eb705e208c70af05179c16a65fd406
https://github.com/pluginaweek/preferences/blob/949894e579eb705e208c70af05179c16a65fd406/lib/preferences.rb#L563-L576
train
pluginaweek/preferences
lib/preferences.rb
Preferences.InstanceMethods.find_preferences
def find_preferences(attributes) if stored_preferences.loaded? stored_preferences.select do |preference| attributes.all? {|attribute, value| preference[attribute] == value} end else stored_preferences.find(:all, :conditions => attributes) end end
ruby
def find_preferences(attributes) if stored_preferences.loaded? stored_preferences.select do |preference| attributes.all? {|attribute, value| preference[attribute] == value} end else stored_preferences.find(:all, :conditions => attributes) end end
[ "def", "find_preferences", "(", "attributes", ")", "if", "stored_preferences", ".", "loaded?", "stored_preferences", ".", "select", "do", "|", "preference", "|", "attributes", ".", "all?", "{", "|", "attribute", ",", "value", "|", "preference", "[", "attribute", "]", "==", "value", "}", "end", "else", "stored_preferences", ".", "find", "(", ":all", ",", ":conditions", "=>", "attributes", ")", "end", "end" ]
Finds all stored preferences with the given attributes. This will do a smart lookup by looking at the in-memory collection if it was eager- loaded.
[ "Finds", "all", "stored", "preferences", "with", "the", "given", "attributes", ".", "This", "will", "do", "a", "smart", "lookup", "by", "looking", "at", "the", "in", "-", "memory", "collection", "if", "it", "was", "eager", "-", "loaded", "." ]
949894e579eb705e208c70af05179c16a65fd406
https://github.com/pluginaweek/preferences/blob/949894e579eb705e208c70af05179c16a65fd406/lib/preferences.rb#L601-L609
train
mvidner/ruby-dbus
lib/dbus/proxy_object.rb
DBus.ProxyObject.[]
def [](intfname) introspect unless introspected ifc = @interfaces[intfname] raise DBus::Error, "no such interface `#{intfname}' on object `#{@path}'" unless ifc ifc end
ruby
def [](intfname) introspect unless introspected ifc = @interfaces[intfname] raise DBus::Error, "no such interface `#{intfname}' on object `#{@path}'" unless ifc ifc end
[ "def", "[]", "(", "intfname", ")", "introspect", "unless", "introspected", "ifc", "=", "@interfaces", "[", "intfname", "]", "raise", "DBus", "::", "Error", ",", "\"no such interface `#{intfname}' on object `#{@path}'\"", "unless", "ifc", "ifc", "end" ]
Retrieves an interface of the proxy object @param [String] intfname @return [ProxyObjectInterface]
[ "Retrieves", "an", "interface", "of", "the", "proxy", "object" ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/proxy_object.rb#L55-L60
train
mvidner/ruby-dbus
lib/dbus/proxy_object_interface.rb
DBus.ProxyObjectInterface.define_method_from_descriptor
def define_method_from_descriptor(m) m.params.each do |fpar| par = fpar.type # This is the signature validity check Type::Parser.new(par).parse end singleton_class.class_eval do define_method m.name do |*args, &reply_handler| if m.params.size != args.size raise ArgumentError, "wrong number of arguments (#{args.size} for #{m.params.size})" end msg = Message.new(Message::METHOD_CALL) msg.path = @object.path msg.interface = @name msg.destination = @object.destination msg.member = m.name msg.sender = @object.bus.unique_name m.params.each do |fpar| par = fpar.type msg.add_param(par, args.shift) end ret = @object.bus.send_sync_or_async(msg, &reply_handler) if ret.nil? || @object.api.proxy_method_returns_array ret else m.rets.size == 1 ? ret.first : ret end end end @methods[m.name] = m end
ruby
def define_method_from_descriptor(m) m.params.each do |fpar| par = fpar.type # This is the signature validity check Type::Parser.new(par).parse end singleton_class.class_eval do define_method m.name do |*args, &reply_handler| if m.params.size != args.size raise ArgumentError, "wrong number of arguments (#{args.size} for #{m.params.size})" end msg = Message.new(Message::METHOD_CALL) msg.path = @object.path msg.interface = @name msg.destination = @object.destination msg.member = m.name msg.sender = @object.bus.unique_name m.params.each do |fpar| par = fpar.type msg.add_param(par, args.shift) end ret = @object.bus.send_sync_or_async(msg, &reply_handler) if ret.nil? || @object.api.proxy_method_returns_array ret else m.rets.size == 1 ? ret.first : ret end end end @methods[m.name] = m end
[ "def", "define_method_from_descriptor", "(", "m", ")", "m", ".", "params", ".", "each", "do", "|", "fpar", "|", "par", "=", "fpar", ".", "type", "Type", "::", "Parser", ".", "new", "(", "par", ")", ".", "parse", "end", "singleton_class", ".", "class_eval", "do", "define_method", "m", ".", "name", "do", "|", "*", "args", ",", "&", "reply_handler", "|", "if", "m", ".", "params", ".", "size", "!=", "args", ".", "size", "raise", "ArgumentError", ",", "\"wrong number of arguments (#{args.size} for #{m.params.size})\"", "end", "msg", "=", "Message", ".", "new", "(", "Message", "::", "METHOD_CALL", ")", "msg", ".", "path", "=", "@object", ".", "path", "msg", ".", "interface", "=", "@name", "msg", ".", "destination", "=", "@object", ".", "destination", "msg", ".", "member", "=", "m", ".", "name", "msg", ".", "sender", "=", "@object", ".", "bus", ".", "unique_name", "m", ".", "params", ".", "each", "do", "|", "fpar", "|", "par", "=", "fpar", ".", "type", "msg", ".", "add_param", "(", "par", ",", "args", ".", "shift", ")", "end", "ret", "=", "@object", ".", "bus", ".", "send_sync_or_async", "(", "msg", ",", "&", "reply_handler", ")", "if", "ret", ".", "nil?", "||", "@object", ".", "api", ".", "proxy_method_returns_array", "ret", "else", "m", ".", "rets", ".", "size", "==", "1", "?", "ret", ".", "first", ":", "ret", "end", "end", "end", "@methods", "[", "m", ".", "name", "]", "=", "m", "end" ]
Defines a method on the interface from the Method descriptor _m_.
[ "Defines", "a", "method", "on", "the", "interface", "from", "the", "Method", "descriptor", "_m_", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/proxy_object_interface.rb#L40-L73
train
mvidner/ruby-dbus
lib/dbus/proxy_object_interface.rb
DBus.ProxyObjectInterface.define
def define(m) if m.is_a?(Method) define_method_from_descriptor(m) elsif m.is_a?(Signal) define_signal_from_descriptor(m) end end
ruby
def define(m) if m.is_a?(Method) define_method_from_descriptor(m) elsif m.is_a?(Signal) define_signal_from_descriptor(m) end end
[ "def", "define", "(", "m", ")", "if", "m", ".", "is_a?", "(", "Method", ")", "define_method_from_descriptor", "(", "m", ")", "elsif", "m", ".", "is_a?", "(", "Signal", ")", "define_signal_from_descriptor", "(", "m", ")", "end", "end" ]
Defines a signal or method based on the descriptor _m_.
[ "Defines", "a", "signal", "or", "method", "based", "on", "the", "descriptor", "_m_", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/proxy_object_interface.rb#L81-L87
train
mvidner/ruby-dbus
lib/dbus/proxy_object_interface.rb
DBus.ProxyObjectInterface.define_method
def define_method(methodname, prototype) m = Method.new(methodname) m.from_prototype(prototype) define(m) end
ruby
def define_method(methodname, prototype) m = Method.new(methodname) m.from_prototype(prototype) define(m) end
[ "def", "define_method", "(", "methodname", ",", "prototype", ")", "m", "=", "Method", ".", "new", "(", "methodname", ")", "m", ".", "from_prototype", "(", "prototype", ")", "define", "(", "m", ")", "end" ]
Defines a proxied method on the interface.
[ "Defines", "a", "proxied", "method", "on", "the", "interface", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/proxy_object_interface.rb#L90-L94
train
mvidner/ruby-dbus
lib/dbus/proxy_object_interface.rb
DBus.ProxyObjectInterface.[]
def [](propname) ret = object[PROPERTY_INTERFACE].Get(name, propname) # this method always returns the single property if @object.api.proxy_method_returns_array ret[0] else ret end end
ruby
def [](propname) ret = object[PROPERTY_INTERFACE].Get(name, propname) # this method always returns the single property if @object.api.proxy_method_returns_array ret[0] else ret end end
[ "def", "[]", "(", "propname", ")", "ret", "=", "object", "[", "PROPERTY_INTERFACE", "]", ".", "Get", "(", "name", ",", "propname", ")", "if", "@object", ".", "api", ".", "proxy_method_returns_array", "ret", "[", "0", "]", "else", "ret", "end", "end" ]
Read a property. @param propname [String]
[ "Read", "a", "property", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/proxy_object_interface.rb#L116-L124
train
mvidner/ruby-dbus
lib/dbus/proxy_object_interface.rb
DBus.ProxyObjectInterface.all_properties
def all_properties ret = object[PROPERTY_INTERFACE].GetAll(name) # this method always returns the single property if @object.api.proxy_method_returns_array ret[0] else ret end end
ruby
def all_properties ret = object[PROPERTY_INTERFACE].GetAll(name) # this method always returns the single property if @object.api.proxy_method_returns_array ret[0] else ret end end
[ "def", "all_properties", "ret", "=", "object", "[", "PROPERTY_INTERFACE", "]", ".", "GetAll", "(", "name", ")", "if", "@object", ".", "api", ".", "proxy_method_returns_array", "ret", "[", "0", "]", "else", "ret", "end", "end" ]
Read all properties at once, as a hash. @return [Hash{String}]
[ "Read", "all", "properties", "at", "once", "as", "a", "hash", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/proxy_object_interface.rb#L135-L143
train
mvidner/ruby-dbus
lib/dbus/message_queue.rb
DBus.MessageQueue.connect
def connect addresses = @address.split ";" # connect to first one that succeeds worked = addresses.find do |a| transport, keyvaluestring = a.split ":" kv_list = keyvaluestring.split "," kv_hash = {} kv_list.each do |kv| key, escaped_value = kv.split "=" value = escaped_value.gsub(/%(..)/) { |_m| [Regexp.last_match(1)].pack "H2" } kv_hash[key] = value end case transport when "unix" connect_to_unix kv_hash when "tcp" connect_to_tcp kv_hash when "launchd" connect_to_launchd kv_hash else # ignore, report? end end worked # returns the address that worked or nil. # how to report failure? end
ruby
def connect addresses = @address.split ";" # connect to first one that succeeds worked = addresses.find do |a| transport, keyvaluestring = a.split ":" kv_list = keyvaluestring.split "," kv_hash = {} kv_list.each do |kv| key, escaped_value = kv.split "=" value = escaped_value.gsub(/%(..)/) { |_m| [Regexp.last_match(1)].pack "H2" } kv_hash[key] = value end case transport when "unix" connect_to_unix kv_hash when "tcp" connect_to_tcp kv_hash when "launchd" connect_to_launchd kv_hash else # ignore, report? end end worked # returns the address that worked or nil. # how to report failure? end
[ "def", "connect", "addresses", "=", "@address", ".", "split", "\";\"", "worked", "=", "addresses", ".", "find", "do", "|", "a", "|", "transport", ",", "keyvaluestring", "=", "a", ".", "split", "\":\"", "kv_list", "=", "keyvaluestring", ".", "split", "\",\"", "kv_hash", "=", "{", "}", "kv_list", ".", "each", "do", "|", "kv", "|", "key", ",", "escaped_value", "=", "kv", ".", "split", "\"=\"", "value", "=", "escaped_value", ".", "gsub", "(", "/", "/", ")", "{", "|", "_m", "|", "[", "Regexp", ".", "last_match", "(", "1", ")", "]", ".", "pack", "\"H2\"", "}", "kv_hash", "[", "key", "]", "=", "value", "end", "case", "transport", "when", "\"unix\"", "connect_to_unix", "kv_hash", "when", "\"tcp\"", "connect_to_tcp", "kv_hash", "when", "\"launchd\"", "connect_to_launchd", "kv_hash", "else", "end", "end", "worked", "end" ]
Connect to the bus and initialize the connection.
[ "Connect", "to", "the", "bus", "and", "initialize", "the", "connection", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/message_queue.rb#L53-L79
train
mvidner/ruby-dbus
lib/dbus/message_queue.rb
DBus.MessageQueue.connect_to_tcp
def connect_to_tcp(params) # check if the path is sufficient if params.key?("host") && params.key?("port") begin # initialize the tcp socket @socket = TCPSocket.new(params["host"], params["port"].to_i) @socket.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) init_connection @is_tcp = true rescue Exception => e puts "Oops:", e puts "Error: Could not establish connection to: #{@path}, will now exit." exit(1) # a little harsh end else # Danger, Will Robinson: the specified "path" is not usable puts "Error: supplied path: #{@path}, unusable! sorry." end end
ruby
def connect_to_tcp(params) # check if the path is sufficient if params.key?("host") && params.key?("port") begin # initialize the tcp socket @socket = TCPSocket.new(params["host"], params["port"].to_i) @socket.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) init_connection @is_tcp = true rescue Exception => e puts "Oops:", e puts "Error: Could not establish connection to: #{@path}, will now exit." exit(1) # a little harsh end else # Danger, Will Robinson: the specified "path" is not usable puts "Error: supplied path: #{@path}, unusable! sorry." end end
[ "def", "connect_to_tcp", "(", "params", ")", "if", "params", ".", "key?", "(", "\"host\"", ")", "&&", "params", ".", "key?", "(", "\"port\"", ")", "begin", "@socket", "=", "TCPSocket", ".", "new", "(", "params", "[", "\"host\"", "]", ",", "params", "[", "\"port\"", "]", ".", "to_i", ")", "@socket", ".", "fcntl", "(", "Fcntl", "::", "F_SETFD", ",", "Fcntl", "::", "FD_CLOEXEC", ")", "init_connection", "@is_tcp", "=", "true", "rescue", "Exception", "=>", "e", "puts", "\"Oops:\"", ",", "e", "puts", "\"Error: Could not establish connection to: #{@path}, will now exit.\"", "exit", "(", "1", ")", "end", "else", "puts", "\"Error: supplied path: #{@path}, unusable! sorry.\"", "end", "end" ]
Connect to a bus over tcp and initialize the connection.
[ "Connect", "to", "a", "bus", "over", "tcp", "and", "initialize", "the", "connection", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/message_queue.rb#L82-L100
train
mvidner/ruby-dbus
lib/dbus/message_queue.rb
DBus.MessageQueue.connect_to_unix
def connect_to_unix(params) @socket = Socket.new(Socket::Constants::PF_UNIX, Socket::Constants::SOCK_STREAM, 0) @socket.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) if !params["abstract"].nil? sockaddr = if HOST_END == LIL_END "\1\0\0#{params["abstract"]}" else "\0\1\0#{params["abstract"]}" end elsif !params["path"].nil? sockaddr = Socket.pack_sockaddr_un(params["path"]) end @socket.connect(sockaddr) init_connection end
ruby
def connect_to_unix(params) @socket = Socket.new(Socket::Constants::PF_UNIX, Socket::Constants::SOCK_STREAM, 0) @socket.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) if !params["abstract"].nil? sockaddr = if HOST_END == LIL_END "\1\0\0#{params["abstract"]}" else "\0\1\0#{params["abstract"]}" end elsif !params["path"].nil? sockaddr = Socket.pack_sockaddr_un(params["path"]) end @socket.connect(sockaddr) init_connection end
[ "def", "connect_to_unix", "(", "params", ")", "@socket", "=", "Socket", ".", "new", "(", "Socket", "::", "Constants", "::", "PF_UNIX", ",", "Socket", "::", "Constants", "::", "SOCK_STREAM", ",", "0", ")", "@socket", ".", "fcntl", "(", "Fcntl", "::", "F_SETFD", ",", "Fcntl", "::", "FD_CLOEXEC", ")", "if", "!", "params", "[", "\"abstract\"", "]", ".", "nil?", "sockaddr", "=", "if", "HOST_END", "==", "LIL_END", "\"\\1\\0\\0#{params[\"abstract\"]}\"", "else", "\"\\0\\1\\0#{params[\"abstract\"]}\"", "end", "elsif", "!", "params", "[", "\"path\"", "]", ".", "nil?", "sockaddr", "=", "Socket", ".", "pack_sockaddr_un", "(", "params", "[", "\"path\"", "]", ")", "end", "@socket", ".", "connect", "(", "sockaddr", ")", "init_connection", "end" ]
Connect to an abstract unix bus and initialize the connection.
[ "Connect", "to", "an", "abstract", "unix", "bus", "and", "initialize", "the", "connection", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/message_queue.rb#L103-L117
train
mvidner/ruby-dbus
lib/dbus/message.rb
DBus.Message.add_param
def add_param(type, val) type = type.chr if type.is_a?(Integer) @signature += type.to_s @params << [type, val] end
ruby
def add_param(type, val) type = type.chr if type.is_a?(Integer) @signature += type.to_s @params << [type, val] end
[ "def", "add_param", "(", "type", ",", "val", ")", "type", "=", "type", ".", "chr", "if", "type", ".", "is_a?", "(", "Integer", ")", "@signature", "+=", "type", ".", "to_s", "@params", "<<", "[", "type", ",", "val", "]", "end" ]
Add a parameter _val_ of type _type_ to the message.
[ "Add", "a", "parameter", "_val_", "of", "type", "_type_", "to", "the", "message", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/message.rb#L128-L132
train
mvidner/ruby-dbus
lib/dbus/message.rb
DBus.Message.marshall
def marshall if @path == "/org/freedesktop/DBus/Local" raise InvalidDestinationName end params = PacketMarshaller.new @params.each do |param| params.append(param[0], param[1]) end @body_length = params.packet.bytesize marshaller = PacketMarshaller.new marshaller.append(Type::BYTE, HOST_END) marshaller.append(Type::BYTE, @message_type) marshaller.append(Type::BYTE, @flags) marshaller.append(Type::BYTE, @protocol) marshaller.append(Type::UINT32, @body_length) marshaller.append(Type::UINT32, @serial) headers = [] headers << [PATH, ["o", @path]] if @path headers << [INTERFACE, ["s", @interface]] if @interface headers << [MEMBER, ["s", @member]] if @member headers << [ERROR_NAME, ["s", @error_name]] if @error_name headers << [REPLY_SERIAL, ["u", @reply_serial]] if @reply_serial headers << [DESTINATION, ["s", @destination]] if @destination # SENDER is not sent, the message bus fills it in instead headers << [SIGNATURE, ["g", @signature]] if @signature != "" marshaller.append("a(yv)", headers) marshaller.align(8) @params.each do |param| marshaller.append(param[0], param[1]) end marshaller.packet end
ruby
def marshall if @path == "/org/freedesktop/DBus/Local" raise InvalidDestinationName end params = PacketMarshaller.new @params.each do |param| params.append(param[0], param[1]) end @body_length = params.packet.bytesize marshaller = PacketMarshaller.new marshaller.append(Type::BYTE, HOST_END) marshaller.append(Type::BYTE, @message_type) marshaller.append(Type::BYTE, @flags) marshaller.append(Type::BYTE, @protocol) marshaller.append(Type::UINT32, @body_length) marshaller.append(Type::UINT32, @serial) headers = [] headers << [PATH, ["o", @path]] if @path headers << [INTERFACE, ["s", @interface]] if @interface headers << [MEMBER, ["s", @member]] if @member headers << [ERROR_NAME, ["s", @error_name]] if @error_name headers << [REPLY_SERIAL, ["u", @reply_serial]] if @reply_serial headers << [DESTINATION, ["s", @destination]] if @destination # SENDER is not sent, the message bus fills it in instead headers << [SIGNATURE, ["g", @signature]] if @signature != "" marshaller.append("a(yv)", headers) marshaller.align(8) @params.each do |param| marshaller.append(param[0], param[1]) end marshaller.packet end
[ "def", "marshall", "if", "@path", "==", "\"/org/freedesktop/DBus/Local\"", "raise", "InvalidDestinationName", "end", "params", "=", "PacketMarshaller", ".", "new", "@params", ".", "each", "do", "|", "param", "|", "params", ".", "append", "(", "param", "[", "0", "]", ",", "param", "[", "1", "]", ")", "end", "@body_length", "=", "params", ".", "packet", ".", "bytesize", "marshaller", "=", "PacketMarshaller", ".", "new", "marshaller", ".", "append", "(", "Type", "::", "BYTE", ",", "HOST_END", ")", "marshaller", ".", "append", "(", "Type", "::", "BYTE", ",", "@message_type", ")", "marshaller", ".", "append", "(", "Type", "::", "BYTE", ",", "@flags", ")", "marshaller", ".", "append", "(", "Type", "::", "BYTE", ",", "@protocol", ")", "marshaller", ".", "append", "(", "Type", "::", "UINT32", ",", "@body_length", ")", "marshaller", ".", "append", "(", "Type", "::", "UINT32", ",", "@serial", ")", "headers", "=", "[", "]", "headers", "<<", "[", "PATH", ",", "[", "\"o\"", ",", "@path", "]", "]", "if", "@path", "headers", "<<", "[", "INTERFACE", ",", "[", "\"s\"", ",", "@interface", "]", "]", "if", "@interface", "headers", "<<", "[", "MEMBER", ",", "[", "\"s\"", ",", "@member", "]", "]", "if", "@member", "headers", "<<", "[", "ERROR_NAME", ",", "[", "\"s\"", ",", "@error_name", "]", "]", "if", "@error_name", "headers", "<<", "[", "REPLY_SERIAL", ",", "[", "\"u\"", ",", "@reply_serial", "]", "]", "if", "@reply_serial", "headers", "<<", "[", "DESTINATION", ",", "[", "\"s\"", ",", "@destination", "]", "]", "if", "@destination", "headers", "<<", "[", "SIGNATURE", ",", "[", "\"g\"", ",", "@signature", "]", "]", "if", "@signature", "!=", "\"\"", "marshaller", ".", "append", "(", "\"a(yv)\"", ",", "headers", ")", "marshaller", ".", "align", "(", "8", ")", "@params", ".", "each", "do", "|", "param", "|", "marshaller", ".", "append", "(", "param", "[", "0", "]", ",", "param", "[", "1", "]", ")", "end", "marshaller", ".", "packet", "end" ]
Marshall the message with its current set parameters and return it in a packet form.
[ "Marshall", "the", "message", "with", "its", "current", "set", "parameters", "and", "return", "it", "in", "a", "packet", "form", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/message.rb#L150-L185
train
mvidner/ruby-dbus
lib/dbus/message.rb
DBus.Message.unmarshall_buffer
def unmarshall_buffer(buf) buf = buf.dup endianness = if buf[0] == "l" LIL_END else BIG_END end pu = PacketUnmarshaller.new(buf, endianness) mdata = pu.unmarshall(MESSAGE_SIGNATURE) _, @message_type, @flags, @protocol, @body_length, @serial, headers = mdata headers.each do |struct| case struct[0] when PATH @path = struct[1] when INTERFACE @interface = struct[1] when MEMBER @member = struct[1] when ERROR_NAME @error_name = struct[1] when REPLY_SERIAL @reply_serial = struct[1] when DESTINATION @destination = struct[1] when SENDER @sender = struct[1] when SIGNATURE @signature = struct[1] end end pu.align(8) if @body_length > 0 && @signature @params = pu.unmarshall(@signature, @body_length) end [self, pu.idx] end
ruby
def unmarshall_buffer(buf) buf = buf.dup endianness = if buf[0] == "l" LIL_END else BIG_END end pu = PacketUnmarshaller.new(buf, endianness) mdata = pu.unmarshall(MESSAGE_SIGNATURE) _, @message_type, @flags, @protocol, @body_length, @serial, headers = mdata headers.each do |struct| case struct[0] when PATH @path = struct[1] when INTERFACE @interface = struct[1] when MEMBER @member = struct[1] when ERROR_NAME @error_name = struct[1] when REPLY_SERIAL @reply_serial = struct[1] when DESTINATION @destination = struct[1] when SENDER @sender = struct[1] when SIGNATURE @signature = struct[1] end end pu.align(8) if @body_length > 0 && @signature @params = pu.unmarshall(@signature, @body_length) end [self, pu.idx] end
[ "def", "unmarshall_buffer", "(", "buf", ")", "buf", "=", "buf", ".", "dup", "endianness", "=", "if", "buf", "[", "0", "]", "==", "\"l\"", "LIL_END", "else", "BIG_END", "end", "pu", "=", "PacketUnmarshaller", ".", "new", "(", "buf", ",", "endianness", ")", "mdata", "=", "pu", ".", "unmarshall", "(", "MESSAGE_SIGNATURE", ")", "_", ",", "@message_type", ",", "@flags", ",", "@protocol", ",", "@body_length", ",", "@serial", ",", "headers", "=", "mdata", "headers", ".", "each", "do", "|", "struct", "|", "case", "struct", "[", "0", "]", "when", "PATH", "@path", "=", "struct", "[", "1", "]", "when", "INTERFACE", "@interface", "=", "struct", "[", "1", "]", "when", "MEMBER", "@member", "=", "struct", "[", "1", "]", "when", "ERROR_NAME", "@error_name", "=", "struct", "[", "1", "]", "when", "REPLY_SERIAL", "@reply_serial", "=", "struct", "[", "1", "]", "when", "DESTINATION", "@destination", "=", "struct", "[", "1", "]", "when", "SENDER", "@sender", "=", "struct", "[", "1", "]", "when", "SIGNATURE", "@signature", "=", "struct", "[", "1", "]", "end", "end", "pu", ".", "align", "(", "8", ")", "if", "@body_length", ">", "0", "&&", "@signature", "@params", "=", "pu", ".", "unmarshall", "(", "@signature", ",", "@body_length", ")", "end", "[", "self", ",", "pu", ".", "idx", "]", "end" ]
Unmarshall a packet contained in the buffer _buf_ and set the parameters of the message object according the data found in the buffer. @return [Array(Message,Integer)] the detected message (self) and the index pointer of the buffer where the message data ended.
[ "Unmarshall", "a", "packet", "contained", "in", "the", "buffer", "_buf_", "and", "set", "the", "parameters", "of", "the", "message", "object", "according", "the", "data", "found", "in", "the", "buffer", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/message.rb#L193-L230
train
mvidner/ruby-dbus
lib/dbus/message.rb
DBus.Message.annotate_exception
def annotate_exception(ex) new_ex = ex.exception("#{ex}; caused by #{self}") new_ex.set_backtrace(ex.backtrace) new_ex end
ruby
def annotate_exception(ex) new_ex = ex.exception("#{ex}; caused by #{self}") new_ex.set_backtrace(ex.backtrace) new_ex end
[ "def", "annotate_exception", "(", "ex", ")", "new_ex", "=", "ex", ".", "exception", "(", "\"#{ex}; caused by #{self}\"", ")", "new_ex", ".", "set_backtrace", "(", "ex", ".", "backtrace", ")", "new_ex", "end" ]
Make a new exception from ex, mark it as being caused by this message @api private
[ "Make", "a", "new", "exception", "from", "ex", "mark", "it", "as", "being", "caused", "by", "this", "message" ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/message.rb#L234-L238
train
mvidner/ruby-dbus
lib/dbus/marshall.rb
DBus.PacketUnmarshaller.unmarshall
def unmarshall(signature, len = nil) if !len.nil? if @buffy.bytesize < @idx + len raise IncompleteBufferException end end sigtree = Type::Parser.new(signature).parse ret = [] sigtree.each do |elem| ret << do_parse(elem) end ret end
ruby
def unmarshall(signature, len = nil) if !len.nil? if @buffy.bytesize < @idx + len raise IncompleteBufferException end end sigtree = Type::Parser.new(signature).parse ret = [] sigtree.each do |elem| ret << do_parse(elem) end ret end
[ "def", "unmarshall", "(", "signature", ",", "len", "=", "nil", ")", "if", "!", "len", ".", "nil?", "if", "@buffy", ".", "bytesize", "<", "@idx", "+", "len", "raise", "IncompleteBufferException", "end", "end", "sigtree", "=", "Type", "::", "Parser", ".", "new", "(", "signature", ")", ".", "parse", "ret", "=", "[", "]", "sigtree", ".", "each", "do", "|", "elem", "|", "ret", "<<", "do_parse", "(", "elem", ")", "end", "ret", "end" ]
Create a new unmarshaller for the given data _buffer_ and _endianness_. Unmarshall the buffer for a given _signature_ and length _len_. Return an array of unmarshalled objects
[ "Create", "a", "new", "unmarshaller", "for", "the", "given", "data", "_buffer_", "and", "_endianness_", ".", "Unmarshall", "the", "buffer", "for", "a", "given", "_signature_", "and", "length", "_len_", ".", "Return", "an", "array", "of", "unmarshalled", "objects" ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/marshall.rb#L53-L65
train
mvidner/ruby-dbus
lib/dbus/marshall.rb
DBus.PacketUnmarshaller.align
def align(a) case a when 1 nil when 2, 4, 8 bits = a - 1 @idx = @idx + bits & ~bits raise IncompleteBufferException if @idx > @buffy.bytesize else raise "Unsupported alignment #{a}" end end
ruby
def align(a) case a when 1 nil when 2, 4, 8 bits = a - 1 @idx = @idx + bits & ~bits raise IncompleteBufferException if @idx > @buffy.bytesize else raise "Unsupported alignment #{a}" end end
[ "def", "align", "(", "a", ")", "case", "a", "when", "1", "nil", "when", "2", ",", "4", ",", "8", "bits", "=", "a", "-", "1", "@idx", "=", "@idx", "+", "bits", "&", "~", "bits", "raise", "IncompleteBufferException", "if", "@idx", ">", "@buffy", ".", "bytesize", "else", "raise", "\"Unsupported alignment #{a}\"", "end", "end" ]
Align the pointer index on a byte index of _a_, where a must be 1, 2, 4 or 8.
[ "Align", "the", "pointer", "index", "on", "a", "byte", "index", "of", "_a_", "where", "a", "must", "be", "1", "2", "4", "or", "8", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/marshall.rb#L69-L80
train
mvidner/ruby-dbus
lib/dbus/marshall.rb
DBus.PacketUnmarshaller.read
def read(nbytes) raise IncompleteBufferException if @idx + nbytes > @buffy.bytesize ret = @buffy.slice(@idx, nbytes) @idx += nbytes ret end
ruby
def read(nbytes) raise IncompleteBufferException if @idx + nbytes > @buffy.bytesize ret = @buffy.slice(@idx, nbytes) @idx += nbytes ret end
[ "def", "read", "(", "nbytes", ")", "raise", "IncompleteBufferException", "if", "@idx", "+", "nbytes", ">", "@buffy", ".", "bytesize", "ret", "=", "@buffy", ".", "slice", "(", "@idx", ",", "nbytes", ")", "@idx", "+=", "nbytes", "ret", "end" ]
Retrieve the next _nbytes_ number of bytes from the buffer.
[ "Retrieve", "the", "next", "_nbytes_", "number", "of", "bytes", "from", "the", "buffer", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/marshall.rb#L88-L93
train
mvidner/ruby-dbus
lib/dbus/marshall.rb
DBus.PacketUnmarshaller.read_string
def read_string align(4) str_sz = read(4).unpack(@uint32)[0] ret = @buffy.slice(@idx, str_sz) raise IncompleteBufferException if @idx + str_sz + 1 > @buffy.bytesize @idx += str_sz if @buffy[@idx].ord != 0 raise InvalidPacketException, "String is not nul-terminated" end @idx += 1 # no exception, see check above ret end
ruby
def read_string align(4) str_sz = read(4).unpack(@uint32)[0] ret = @buffy.slice(@idx, str_sz) raise IncompleteBufferException if @idx + str_sz + 1 > @buffy.bytesize @idx += str_sz if @buffy[@idx].ord != 0 raise InvalidPacketException, "String is not nul-terminated" end @idx += 1 # no exception, see check above ret end
[ "def", "read_string", "align", "(", "4", ")", "str_sz", "=", "read", "(", "4", ")", ".", "unpack", "(", "@uint32", ")", "[", "0", "]", "ret", "=", "@buffy", ".", "slice", "(", "@idx", ",", "str_sz", ")", "raise", "IncompleteBufferException", "if", "@idx", "+", "str_sz", "+", "1", ">", "@buffy", ".", "bytesize", "@idx", "+=", "str_sz", "if", "@buffy", "[", "@idx", "]", ".", "ord", "!=", "0", "raise", "InvalidPacketException", ",", "\"String is not nul-terminated\"", "end", "@idx", "+=", "1", "ret", "end" ]
Read the string length and string itself from the buffer. Return the string.
[ "Read", "the", "string", "length", "and", "string", "itself", "from", "the", "buffer", ".", "Return", "the", "string", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/marshall.rb#L97-L109
train
mvidner/ruby-dbus
lib/dbus/marshall.rb
DBus.PacketUnmarshaller.read_signature
def read_signature str_sz = read(1).unpack("C")[0] ret = @buffy.slice(@idx, str_sz) raise IncompleteBufferException if @idx + str_sz + 1 >= @buffy.bytesize @idx += str_sz if @buffy[@idx].ord != 0 raise InvalidPacketException, "Type is not nul-terminated" end @idx += 1 # no exception, see check above ret end
ruby
def read_signature str_sz = read(1).unpack("C")[0] ret = @buffy.slice(@idx, str_sz) raise IncompleteBufferException if @idx + str_sz + 1 >= @buffy.bytesize @idx += str_sz if @buffy[@idx].ord != 0 raise InvalidPacketException, "Type is not nul-terminated" end @idx += 1 # no exception, see check above ret end
[ "def", "read_signature", "str_sz", "=", "read", "(", "1", ")", ".", "unpack", "(", "\"C\"", ")", "[", "0", "]", "ret", "=", "@buffy", ".", "slice", "(", "@idx", ",", "str_sz", ")", "raise", "IncompleteBufferException", "if", "@idx", "+", "str_sz", "+", "1", ">=", "@buffy", ".", "bytesize", "@idx", "+=", "str_sz", "if", "@buffy", "[", "@idx", "]", ".", "ord", "!=", "0", "raise", "InvalidPacketException", ",", "\"Type is not nul-terminated\"", "end", "@idx", "+=", "1", "ret", "end" ]
Read the signature length and signature itself from the buffer. Return the signature.
[ "Read", "the", "signature", "length", "and", "signature", "itself", "from", "the", "buffer", ".", "Return", "the", "signature", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/marshall.rb#L113-L124
train
mvidner/ruby-dbus
lib/dbus/marshall.rb
DBus.PacketMarshaller.num_align
def num_align(n, a) case a when 1, 2, 4, 8 bits = a - 1 n + bits & ~bits else raise "Unsupported alignment" end end
ruby
def num_align(n, a) case a when 1, 2, 4, 8 bits = a - 1 n + bits & ~bits else raise "Unsupported alignment" end end
[ "def", "num_align", "(", "n", ",", "a", ")", "case", "a", "when", "1", ",", "2", ",", "4", ",", "8", "bits", "=", "a", "-", "1", "n", "+", "bits", "&", "~", "bits", "else", "raise", "\"Unsupported alignment\"", "end", "end" ]
Create a new marshaller, setting the current packet to the empty packet. Round _n_ up to the specified power of two, _a_
[ "Create", "a", "new", "marshaller", "setting", "the", "current", "packet", "to", "the", "empty", "packet", ".", "Round", "_n_", "up", "to", "the", "specified", "power", "of", "two", "_a_" ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/marshall.rb#L247-L255
train
mvidner/ruby-dbus
lib/dbus/marshall.rb
DBus.PacketMarshaller.array
def array(type) # Thanks to Peter Rullmann for this line align(4) sizeidx = @packet.bytesize @packet += "ABCD" align(type.alignment) contentidx = @packet.bytesize yield sz = @packet.bytesize - contentidx raise InvalidPacketException if sz > 67_108_864 @packet[sizeidx...sizeidx + 4] = [sz].pack("L") end
ruby
def array(type) # Thanks to Peter Rullmann for this line align(4) sizeidx = @packet.bytesize @packet += "ABCD" align(type.alignment) contentidx = @packet.bytesize yield sz = @packet.bytesize - contentidx raise InvalidPacketException if sz > 67_108_864 @packet[sizeidx...sizeidx + 4] = [sz].pack("L") end
[ "def", "array", "(", "type", ")", "align", "(", "4", ")", "sizeidx", "=", "@packet", ".", "bytesize", "@packet", "+=", "\"ABCD\"", "align", "(", "type", ".", "alignment", ")", "contentidx", "=", "@packet", ".", "bytesize", "yield", "sz", "=", "@packet", ".", "bytesize", "-", "contentidx", "raise", "InvalidPacketException", "if", "sz", ">", "67_108_864", "@packet", "[", "sizeidx", "...", "sizeidx", "+", "4", "]", "=", "[", "sz", "]", ".", "pack", "(", "\"L\"", ")", "end" ]
Append the array type _type_ to the packet and allow for appending the child elements.
[ "Append", "the", "array", "type", "_type_", "to", "the", "packet", "and", "allow", "for", "appending", "the", "child", "elements", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/marshall.rb#L275-L286
train
mvidner/ruby-dbus
lib/dbus/bus.rb
DBus.Service.object
def object(path, api: ApiOptions::A0) node = get_node(path, _create = true) if node.object.nil? || node.object.api != api node.object = ProxyObject.new( @bus, @name, path, api: api ) end node.object end
ruby
def object(path, api: ApiOptions::A0) node = get_node(path, _create = true) if node.object.nil? || node.object.api != api node.object = ProxyObject.new( @bus, @name, path, api: api ) end node.object end
[ "def", "object", "(", "path", ",", "api", ":", "ApiOptions", "::", "A0", ")", "node", "=", "get_node", "(", "path", ",", "_create", "=", "true", ")", "if", "node", ".", "object", ".", "nil?", "||", "node", ".", "object", ".", "api", "!=", "api", "node", ".", "object", "=", "ProxyObject", ".", "new", "(", "@bus", ",", "@name", ",", "path", ",", "api", ":", "api", ")", "end", "node", ".", "object", "end" ]
Retrieves an object at the given _path_ whose methods always return an array. @return [ProxyObject]
[ "Retrieves", "an", "object", "at", "the", "given", "_path_", "whose", "methods", "always", "return", "an", "array", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/bus.rb#L59-L68
train
mvidner/ruby-dbus
lib/dbus/bus.rb
DBus.Service.get_node
def get_node(path, create = false) n = @root path.sub(%r{^/}, "").split("/").each do |elem| if !(n[elem]) return nil if !create n[elem] = Node.new(elem) end n = n[elem] end if n.nil? DBus.logger.debug "Warning, unknown object #{path}" end n end
ruby
def get_node(path, create = false) n = @root path.sub(%r{^/}, "").split("/").each do |elem| if !(n[elem]) return nil if !create n[elem] = Node.new(elem) end n = n[elem] end if n.nil? DBus.logger.debug "Warning, unknown object #{path}" end n end
[ "def", "get_node", "(", "path", ",", "create", "=", "false", ")", "n", "=", "@root", "path", ".", "sub", "(", "%r{", "}", ",", "\"\"", ")", ".", "split", "(", "\"/\"", ")", ".", "each", "do", "|", "elem", "|", "if", "!", "(", "n", "[", "elem", "]", ")", "return", "nil", "if", "!", "create", "n", "[", "elem", "]", "=", "Node", ".", "new", "(", "elem", ")", "end", "n", "=", "n", "[", "elem", "]", "end", "if", "n", ".", "nil?", "DBus", ".", "logger", ".", "debug", "\"Warning, unknown object #{path}\"", "end", "n", "end" ]
Get the object node corresponding to the given _path_. if _create_ is true, the the nodes in the path are created if they do not already exist.
[ "Get", "the", "object", "node", "corresponding", "to", "the", "given", "_path_", ".", "if", "_create_", "is", "true", "the", "the", "nodes", "in", "the", "path", "are", "created", "if", "they", "do", "not", "already", "exist", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/bus.rb#L94-L107
train
mvidner/ruby-dbus
lib/dbus/bus.rb
DBus.Service.rec_introspect
def rec_introspect(node, path) xml = bus.introspect_data(@name, path) intfs, subnodes = IntrospectXMLParser.new(xml).parse subnodes.each do |nodename| subnode = node[nodename] = Node.new(nodename) subpath = if path == "/" "/" + nodename else path + "/" + nodename end rec_introspect(subnode, subpath) end return if intfs.empty? node.object = ProxyObjectFactory.new(xml, @bus, @name, path).build end
ruby
def rec_introspect(node, path) xml = bus.introspect_data(@name, path) intfs, subnodes = IntrospectXMLParser.new(xml).parse subnodes.each do |nodename| subnode = node[nodename] = Node.new(nodename) subpath = if path == "/" "/" + nodename else path + "/" + nodename end rec_introspect(subnode, subpath) end return if intfs.empty? node.object = ProxyObjectFactory.new(xml, @bus, @name, path).build end
[ "def", "rec_introspect", "(", "node", ",", "path", ")", "xml", "=", "bus", ".", "introspect_data", "(", "@name", ",", "path", ")", "intfs", ",", "subnodes", "=", "IntrospectXMLParser", ".", "new", "(", "xml", ")", ".", "parse", "subnodes", ".", "each", "do", "|", "nodename", "|", "subnode", "=", "node", "[", "nodename", "]", "=", "Node", ".", "new", "(", "nodename", ")", "subpath", "=", "if", "path", "==", "\"/\"", "\"/\"", "+", "nodename", "else", "path", "+", "\"/\"", "+", "nodename", "end", "rec_introspect", "(", "subnode", ",", "subpath", ")", "end", "return", "if", "intfs", ".", "empty?", "node", ".", "object", "=", "ProxyObjectFactory", ".", "new", "(", "xml", ",", "@bus", ",", "@name", ",", "path", ")", ".", "build", "end" ]
Perform a recursive retrospection on the given current _node_ on the given _path_.
[ "Perform", "a", "recursive", "retrospection", "on", "the", "given", "current", "_node_", "on", "the", "given", "_path_", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/bus.rb#L117-L131
train
mvidner/ruby-dbus
lib/dbus/bus.rb
DBus.Node.to_xml
def to_xml xml = '<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd"> <node> ' each_pair do |k, _v| xml += "<node name=\"#{k}\" />" end if @object @object.intfs.each_pair do |_k, v| xml += %(<interface name="#{v.name}">\n) v.methods.each_value { |m| xml += m.to_xml } v.signals.each_value { |m| xml += m.to_xml } xml += "</interface>\n" end end xml += "</node>" xml end
ruby
def to_xml xml = '<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd"> <node> ' each_pair do |k, _v| xml += "<node name=\"#{k}\" />" end if @object @object.intfs.each_pair do |_k, v| xml += %(<interface name="#{v.name}">\n) v.methods.each_value { |m| xml += m.to_xml } v.signals.each_value { |m| xml += m.to_xml } xml += "</interface>\n" end end xml += "</node>" xml end
[ "def", "to_xml", "xml", "=", "'<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\"><node>'", "each_pair", "do", "|", "k", ",", "_v", "|", "xml", "+=", "\"<node name=\\\"#{k}\\\" />\"", "end", "if", "@object", "@object", ".", "intfs", ".", "each_pair", "do", "|", "_k", ",", "v", "|", "xml", "+=", "%(<interface name=\"#{v.name}\">\\n)", "v", ".", "methods", ".", "each_value", "{", "|", "m", "|", "xml", "+=", "m", ".", "to_xml", "}", "v", ".", "signals", ".", "each_value", "{", "|", "m", "|", "xml", "+=", "m", ".", "to_xml", "}", "xml", "+=", "\"</interface>\\n\"", "end", "end", "xml", "+=", "\"</node>\"", "xml", "end" ]
Create a new node with a given _name_. Return an XML string representation of the node. It is shallow, not recursing into subnodes
[ "Create", "a", "new", "node", "with", "a", "given", "_name_", ".", "Return", "an", "XML", "string", "representation", "of", "the", "node", ".", "It", "is", "shallow", "not", "recursing", "into", "subnodes" ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/bus.rb#L151-L169
train
mvidner/ruby-dbus
lib/dbus/bus.rb
DBus.Connection.glibize
def glibize require "glib2" # Circumvent a ruby-glib bug @channels ||= [] gio = GLib::IOChannel.new(@message_queue.socket.fileno) @channels << gio gio.add_watch(GLib::IOChannel::IN) do |_c, _ch| dispatch_message_queue true end end
ruby
def glibize require "glib2" # Circumvent a ruby-glib bug @channels ||= [] gio = GLib::IOChannel.new(@message_queue.socket.fileno) @channels << gio gio.add_watch(GLib::IOChannel::IN) do |_c, _ch| dispatch_message_queue true end end
[ "def", "glibize", "require", "\"glib2\"", "@channels", "||=", "[", "]", "gio", "=", "GLib", "::", "IOChannel", ".", "new", "(", "@message_queue", ".", "socket", ".", "fileno", ")", "@channels", "<<", "gio", "gio", ".", "add_watch", "(", "GLib", "::", "IOChannel", "::", "IN", ")", "do", "|", "_c", ",", "_ch", "|", "dispatch_message_queue", "true", "end", "end" ]
Tell a bus to register itself on the glib main loop
[ "Tell", "a", "bus", "to", "register", "itself", "on", "the", "glib", "main", "loop" ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/bus.rb#L225-L236
train
mvidner/ruby-dbus
lib/dbus/bus.rb
DBus.Connection.request_service
def request_service(name) # Use RequestName, but asynchronously! # A synchronous call would not work with service activation, where # method calls to be serviced arrive before the reply for RequestName # (Ticket#29). proxy.RequestName(name, NAME_FLAG_REPLACE_EXISTING) do |rmsg, r| # check and report errors first raise rmsg if rmsg.is_a?(Error) raise NameRequestError unless r == REQUEST_NAME_REPLY_PRIMARY_OWNER end @service = Service.new(name, self) @service end
ruby
def request_service(name) # Use RequestName, but asynchronously! # A synchronous call would not work with service activation, where # method calls to be serviced arrive before the reply for RequestName # (Ticket#29). proxy.RequestName(name, NAME_FLAG_REPLACE_EXISTING) do |rmsg, r| # check and report errors first raise rmsg if rmsg.is_a?(Error) raise NameRequestError unless r == REQUEST_NAME_REPLY_PRIMARY_OWNER end @service = Service.new(name, self) @service end
[ "def", "request_service", "(", "name", ")", "proxy", ".", "RequestName", "(", "name", ",", "NAME_FLAG_REPLACE_EXISTING", ")", "do", "|", "rmsg", ",", "r", "|", "raise", "rmsg", "if", "rmsg", ".", "is_a?", "(", "Error", ")", "raise", "NameRequestError", "unless", "r", "==", "REQUEST_NAME_REPLY_PRIMARY_OWNER", "end", "@service", "=", "Service", ".", "new", "(", "name", ",", "self", ")", "@service", "end" ]
Attempt to request a service _name_. FIXME, NameRequestError cannot really be rescued as it will be raised when dispatching a later call. Rework the API to better match the spec. @return [Service]
[ "Attempt", "to", "request", "a", "service", "_name_", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/bus.rb#L407-L419
train
mvidner/ruby-dbus
lib/dbus/bus.rb
DBus.Connection.proxy
def proxy if @proxy.nil? path = "/org/freedesktop/DBus" dest = "org.freedesktop.DBus" pof = DBus::ProxyObjectFactory.new( DBUSXMLINTRO, self, dest, path, api: ApiOptions::A0 ) @proxy = pof.build["org.freedesktop.DBus"] end @proxy end
ruby
def proxy if @proxy.nil? path = "/org/freedesktop/DBus" dest = "org.freedesktop.DBus" pof = DBus::ProxyObjectFactory.new( DBUSXMLINTRO, self, dest, path, api: ApiOptions::A0 ) @proxy = pof.build["org.freedesktop.DBus"] end @proxy end
[ "def", "proxy", "if", "@proxy", ".", "nil?", "path", "=", "\"/org/freedesktop/DBus\"", "dest", "=", "\"org.freedesktop.DBus\"", "pof", "=", "DBus", "::", "ProxyObjectFactory", ".", "new", "(", "DBUSXMLINTRO", ",", "self", ",", "dest", ",", "path", ",", "api", ":", "ApiOptions", "::", "A0", ")", "@proxy", "=", "pof", ".", "build", "[", "\"org.freedesktop.DBus\"", "]", "end", "@proxy", "end" ]
Set up a ProxyObject for the bus itself, since the bus is introspectable. @return [ProxyObject] that always returns an array ({DBus::ApiOptions#proxy_method_returns_array}) Returns the object.
[ "Set", "up", "a", "ProxyObject", "for", "the", "bus", "itself", "since", "the", "bus", "is", "introspectable", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/bus.rb#L425-L436
train
mvidner/ruby-dbus
lib/dbus/bus.rb
DBus.Connection.add_match
def add_match(mr, &slot) # check this is a signal. mrs = mr.to_s DBus.logger.debug "#{@signal_matchrules.size} rules, adding #{mrs.inspect}" # don't ask for the same match if we override it unless @signal_matchrules.key?(mrs) DBus.logger.debug "Asked for a new match" proxy.AddMatch(mrs) end @signal_matchrules[mrs] = slot end
ruby
def add_match(mr, &slot) # check this is a signal. mrs = mr.to_s DBus.logger.debug "#{@signal_matchrules.size} rules, adding #{mrs.inspect}" # don't ask for the same match if we override it unless @signal_matchrules.key?(mrs) DBus.logger.debug "Asked for a new match" proxy.AddMatch(mrs) end @signal_matchrules[mrs] = slot end
[ "def", "add_match", "(", "mr", ",", "&", "slot", ")", "mrs", "=", "mr", ".", "to_s", "DBus", ".", "logger", ".", "debug", "\"#{@signal_matchrules.size} rules, adding #{mrs.inspect}\"", "unless", "@signal_matchrules", ".", "key?", "(", "mrs", ")", "DBus", ".", "logger", ".", "debug", "\"Asked for a new match\"", "proxy", ".", "AddMatch", "(", "mrs", ")", "end", "@signal_matchrules", "[", "mrs", "]", "=", "slot", "end" ]
Asks bus to send us messages matching mr, and execute slot when received
[ "Asks", "bus", "to", "send", "us", "messages", "matching", "mr", "and", "execute", "slot", "when", "received" ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/bus.rb#L477-L487
train
mvidner/ruby-dbus
lib/dbus/bus.rb
DBus.Connection.send_hello
def send_hello m = Message.new(DBus::Message::METHOD_CALL) m.path = "/org/freedesktop/DBus" m.destination = "org.freedesktop.DBus" m.interface = "org.freedesktop.DBus" m.member = "Hello" send_sync(m) do |rmsg| @unique_name = rmsg.destination DBus.logger.debug "Got hello reply. Our unique_name is #{@unique_name}" end @service = Service.new(@unique_name, self) end
ruby
def send_hello m = Message.new(DBus::Message::METHOD_CALL) m.path = "/org/freedesktop/DBus" m.destination = "org.freedesktop.DBus" m.interface = "org.freedesktop.DBus" m.member = "Hello" send_sync(m) do |rmsg| @unique_name = rmsg.destination DBus.logger.debug "Got hello reply. Our unique_name is #{@unique_name}" end @service = Service.new(@unique_name, self) end
[ "def", "send_hello", "m", "=", "Message", ".", "new", "(", "DBus", "::", "Message", "::", "METHOD_CALL", ")", "m", ".", "path", "=", "\"/org/freedesktop/DBus\"", "m", ".", "destination", "=", "\"org.freedesktop.DBus\"", "m", ".", "interface", "=", "\"org.freedesktop.DBus\"", "m", ".", "member", "=", "\"Hello\"", "send_sync", "(", "m", ")", "do", "|", "rmsg", "|", "@unique_name", "=", "rmsg", ".", "destination", "DBus", ".", "logger", ".", "debug", "\"Got hello reply. Our unique_name is #{@unique_name}\"", "end", "@service", "=", "Service", ".", "new", "(", "@unique_name", ",", "self", ")", "end" ]
Send a hello messages to the bus to let it know we are here.
[ "Send", "a", "hello", "messages", "to", "the", "bus", "to", "let", "it", "know", "we", "are", "here", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/bus.rb#L584-L595
train
mvidner/ruby-dbus
lib/dbus/bus.rb
DBus.Main.run
def run # before blocking, empty the buffers # https://bugzilla.novell.com/show_bug.cgi?id=537401 @buses.each_value do |b| while (m = b.message_queue.message_from_buffer_nonblock) b.process(m) end end while !@quitting && [email protected]? ready = IO.select(@buses.keys, [], [], 5) # timeout 5 seconds next unless ready # timeout exceeds so continue unless quitting ready.first.each do |socket| b = @buses[socket] begin b.message_queue.buffer_from_socket_nonblock rescue EOFError, SystemCallError @buses.delete socket # this bus died next end while (m = b.message_queue.message_from_buffer_nonblock) b.process(m) end end end end
ruby
def run # before blocking, empty the buffers # https://bugzilla.novell.com/show_bug.cgi?id=537401 @buses.each_value do |b| while (m = b.message_queue.message_from_buffer_nonblock) b.process(m) end end while !@quitting && [email protected]? ready = IO.select(@buses.keys, [], [], 5) # timeout 5 seconds next unless ready # timeout exceeds so continue unless quitting ready.first.each do |socket| b = @buses[socket] begin b.message_queue.buffer_from_socket_nonblock rescue EOFError, SystemCallError @buses.delete socket # this bus died next end while (m = b.message_queue.message_from_buffer_nonblock) b.process(m) end end end end
[ "def", "run", "@buses", ".", "each_value", "do", "|", "b", "|", "while", "(", "m", "=", "b", ".", "message_queue", ".", "message_from_buffer_nonblock", ")", "b", ".", "process", "(", "m", ")", "end", "end", "while", "!", "@quitting", "&&", "!", "@buses", ".", "empty?", "ready", "=", "IO", ".", "select", "(", "@buses", ".", "keys", ",", "[", "]", ",", "[", "]", ",", "5", ")", "next", "unless", "ready", "ready", ".", "first", ".", "each", "do", "|", "socket", "|", "b", "=", "@buses", "[", "socket", "]", "begin", "b", ".", "message_queue", ".", "buffer_from_socket_nonblock", "rescue", "EOFError", ",", "SystemCallError", "@buses", ".", "delete", "socket", "next", "end", "while", "(", "m", "=", "b", ".", "message_queue", ".", "message_from_buffer_nonblock", ")", "b", ".", "process", "(", "m", ")", "end", "end", "end", "end" ]
Run the main loop. This is a blocking call!
[ "Run", "the", "main", "loop", ".", "This", "is", "a", "blocking", "call!" ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/bus.rb#L717-L741
train
mvidner/ruby-dbus
lib/dbus/auth.rb
DBus.External.authenticate
def authenticate # Take the user id (eg integer 1000) make a string out of it "1000", take # each character and determin hex value "1" => 0x31, "0" => 0x30. You # obtain for "1000" => 31303030 This is what the server is expecting. # Why? I dunno. How did I come to that conclusion? by looking at rbus # code. I have no idea how he found that out. Process.uid.to_s.split(//).map { |d| d.ord.to_s(16) }.join end
ruby
def authenticate # Take the user id (eg integer 1000) make a string out of it "1000", take # each character and determin hex value "1" => 0x31, "0" => 0x30. You # obtain for "1000" => 31303030 This is what the server is expecting. # Why? I dunno. How did I come to that conclusion? by looking at rbus # code. I have no idea how he found that out. Process.uid.to_s.split(//).map { |d| d.ord.to_s(16) }.join end
[ "def", "authenticate", "Process", ".", "uid", ".", "to_s", ".", "split", "(", "/", "/", ")", ".", "map", "{", "|", "d", "|", "d", ".", "ord", ".", "to_s", "(", "16", ")", "}", ".", "join", "end" ]
Performs the authentication.
[ "Performs", "the", "authentication", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/auth.rb#L36-L43
train
mvidner/ruby-dbus
lib/dbus/auth.rb
DBus.DBusCookieSHA1.hex_decode
def hex_decode(encoded) encoded.scan(/[[:xdigit:]]{2}/).map { |h| h.hex.chr }.join end
ruby
def hex_decode(encoded) encoded.scan(/[[:xdigit:]]{2}/).map { |h| h.hex.chr }.join end
[ "def", "hex_decode", "(", "encoded", ")", "encoded", ".", "scan", "(", "/", "/", ")", ".", "map", "{", "|", "h", "|", "h", ".", "hex", ".", "chr", "}", ".", "join", "end" ]
decode hex to plain
[ "decode", "hex", "to", "plain" ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/auth.rb#L107-L109
train
mvidner/ruby-dbus
lib/dbus/auth.rb
DBus.Client.authenticate
def authenticate if RbConfig::CONFIG["target_os"] =~ /freebsd/ @socket.sendmsg(0.chr, 0, nil, [:SOCKET, :SCM_CREDS, ""]) else @socket.write(0.chr) end next_authenticator @state = :Starting while @state != :Authenticated r = next_state return r if !r end true end
ruby
def authenticate if RbConfig::CONFIG["target_os"] =~ /freebsd/ @socket.sendmsg(0.chr, 0, nil, [:SOCKET, :SCM_CREDS, ""]) else @socket.write(0.chr) end next_authenticator @state = :Starting while @state != :Authenticated r = next_state return r if !r end true end
[ "def", "authenticate", "if", "RbConfig", "::", "CONFIG", "[", "\"target_os\"", "]", "=~", "/", "/", "@socket", ".", "sendmsg", "(", "0", ".", "chr", ",", "0", ",", "nil", ",", "[", ":SOCKET", ",", ":SCM_CREDS", ",", "\"\"", "]", ")", "else", "@socket", ".", "write", "(", "0", ".", "chr", ")", "end", "next_authenticator", "@state", "=", ":Starting", "while", "@state", "!=", ":Authenticated", "r", "=", "next_state", "return", "r", "if", "!", "r", "end", "true", "end" ]
Create a new authentication client. Start the authentication process.
[ "Create", "a", "new", "authentication", "client", ".", "Start", "the", "authentication", "process", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/auth.rb#L126-L139
train
mvidner/ruby-dbus
lib/dbus/auth.rb
DBus.Client.next_authenticator
def next_authenticator raise AuthenticationFailed if @auth_list.empty? @authenticator = @auth_list.shift.new auth_msg = ["AUTH", @authenticator.name, @authenticator.authenticate] DBus.logger.debug "auth_msg: #{auth_msg.inspect}" send(auth_msg) rescue AuthenticationFailed @socket.close raise end
ruby
def next_authenticator raise AuthenticationFailed if @auth_list.empty? @authenticator = @auth_list.shift.new auth_msg = ["AUTH", @authenticator.name, @authenticator.authenticate] DBus.logger.debug "auth_msg: #{auth_msg.inspect}" send(auth_msg) rescue AuthenticationFailed @socket.close raise end
[ "def", "next_authenticator", "raise", "AuthenticationFailed", "if", "@auth_list", ".", "empty?", "@authenticator", "=", "@auth_list", ".", "shift", ".", "new", "auth_msg", "=", "[", "\"AUTH\"", ",", "@authenticator", ".", "name", ",", "@authenticator", ".", "authenticate", "]", "DBus", ".", "logger", ".", "debug", "\"auth_msg: #{auth_msg.inspect}\"", "send", "(", "auth_msg", ")", "rescue", "AuthenticationFailed", "@socket", ".", "close", "raise", "end" ]
Try authentication using the next authenticator.
[ "Try", "authentication", "using", "the", "next", "authenticator", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/auth.rb#L155-L164
train
mvidner/ruby-dbus
lib/dbus/introspect.rb
DBus.Interface.validate_name
def validate_name(name) raise InvalidIntrospectionData if name.bytesize > 255 raise InvalidIntrospectionData if name =~ /^\./ || name =~ /\.$/ raise InvalidIntrospectionData if name =~ /\.\./ raise InvalidIntrospectionData if name !~ /\./ name.split(".").each do |element| raise InvalidIntrospectionData if element !~ INTERFACE_ELEMENT_RE end end
ruby
def validate_name(name) raise InvalidIntrospectionData if name.bytesize > 255 raise InvalidIntrospectionData if name =~ /^\./ || name =~ /\.$/ raise InvalidIntrospectionData if name =~ /\.\./ raise InvalidIntrospectionData if name !~ /\./ name.split(".").each do |element| raise InvalidIntrospectionData if element !~ INTERFACE_ELEMENT_RE end end
[ "def", "validate_name", "(", "name", ")", "raise", "InvalidIntrospectionData", "if", "name", ".", "bytesize", ">", "255", "raise", "InvalidIntrospectionData", "if", "name", "=~", "/", "\\.", "/", "||", "name", "=~", "/", "\\.", "/", "raise", "InvalidIntrospectionData", "if", "name", "=~", "/", "\\.", "\\.", "/", "raise", "InvalidIntrospectionData", "if", "name", "!~", "/", "\\.", "/", "name", ".", "split", "(", "\".\"", ")", ".", "each", "do", "|", "element", "|", "raise", "InvalidIntrospectionData", "if", "element", "!~", "INTERFACE_ELEMENT_RE", "end", "end" ]
Creates a new interface with a given _name_. Validates a service _name_.
[ "Creates", "a", "new", "interface", "with", "a", "given", "_name_", ".", "Validates", "a", "service", "_name_", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/introspect.rb#L49-L57
train
mvidner/ruby-dbus
lib/dbus/introspect.rb
DBus.Interface.define
def define(m) if m.is_a?(Method) @methods[m.name.to_sym] = m elsif m.is_a?(Signal) @signals[m.name.to_sym] = m end end
ruby
def define(m) if m.is_a?(Method) @methods[m.name.to_sym] = m elsif m.is_a?(Signal) @signals[m.name.to_sym] = m end end
[ "def", "define", "(", "m", ")", "if", "m", ".", "is_a?", "(", "Method", ")", "@methods", "[", "m", ".", "name", ".", "to_sym", "]", "=", "m", "elsif", "m", ".", "is_a?", "(", "Signal", ")", "@signals", "[", "m", ".", "name", ".", "to_sym", "]", "=", "m", "end", "end" ]
Helper method for defining a method _m_.
[ "Helper", "method", "for", "defining", "a", "method", "_m_", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/introspect.rb#L60-L66
train
mvidner/ruby-dbus
lib/dbus/introspect.rb
DBus.Interface.define_method
def define_method(id, prototype) m = Method.new(id) m.from_prototype(prototype) define(m) end
ruby
def define_method(id, prototype) m = Method.new(id) m.from_prototype(prototype) define(m) end
[ "def", "define_method", "(", "id", ",", "prototype", ")", "m", "=", "Method", ".", "new", "(", "id", ")", "m", ".", "from_prototype", "(", "prototype", ")", "define", "(", "m", ")", "end" ]
Defines a method with name _id_ and a given _prototype_ in the interface.
[ "Defines", "a", "method", "with", "name", "_id_", "and", "a", "given", "_prototype_", "in", "the", "interface", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/introspect.rb#L71-L75
train
mvidner/ruby-dbus
lib/dbus/introspect.rb
DBus.Method.from_prototype
def from_prototype(prototype) prototype.split(/, */).each do |arg| arg = arg.split(" ") raise InvalidClassDefinition if arg.size != 2 dir, arg = arg if arg =~ /:/ arg = arg.split(":") name, sig = arg else sig = arg end case dir when "in" add_fparam(name, sig) when "out" add_return(name, sig) end end self end
ruby
def from_prototype(prototype) prototype.split(/, */).each do |arg| arg = arg.split(" ") raise InvalidClassDefinition if arg.size != 2 dir, arg = arg if arg =~ /:/ arg = arg.split(":") name, sig = arg else sig = arg end case dir when "in" add_fparam(name, sig) when "out" add_return(name, sig) end end self end
[ "def", "from_prototype", "(", "prototype", ")", "prototype", ".", "split", "(", "/", "/", ")", ".", "each", "do", "|", "arg", "|", "arg", "=", "arg", ".", "split", "(", "\" \"", ")", "raise", "InvalidClassDefinition", "if", "arg", ".", "size", "!=", "2", "dir", ",", "arg", "=", "arg", "if", "arg", "=~", "/", "/", "arg", "=", "arg", ".", "split", "(", "\":\"", ")", "name", ",", "sig", "=", "arg", "else", "sig", "=", "arg", "end", "case", "dir", "when", "\"in\"", "add_fparam", "(", "name", ",", "sig", ")", "when", "\"out\"", "add_return", "(", "name", ",", "sig", ")", "end", "end", "self", "end" ]
Add parameter types by parsing the given _prototype_.
[ "Add", "parameter", "types", "by", "parsing", "the", "given", "_prototype_", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/introspect.rb#L151-L170
train
mvidner/ruby-dbus
lib/dbus/introspect.rb
DBus.Method.to_xml
def to_xml xml = %(<method name="#{@name}">\n) @params.each do |param| name = param.name ? %(name="#{param.name}" ) : "" xml += %(<arg #{name}direction="in" type="#{param.type}"/>\n) end @rets.each do |param| name = param.name ? %(name="#{param.name}" ) : "" xml += %(<arg #{name}direction="out" type="#{param.type}"/>\n) end xml += %(</method>\n) xml end
ruby
def to_xml xml = %(<method name="#{@name}">\n) @params.each do |param| name = param.name ? %(name="#{param.name}" ) : "" xml += %(<arg #{name}direction="in" type="#{param.type}"/>\n) end @rets.each do |param| name = param.name ? %(name="#{param.name}" ) : "" xml += %(<arg #{name}direction="out" type="#{param.type}"/>\n) end xml += %(</method>\n) xml end
[ "def", "to_xml", "xml", "=", "%(<method name=\"#{@name}\">\\n)", "@params", ".", "each", "do", "|", "param", "|", "name", "=", "param", ".", "name", "?", "%(name=\"#{param.name}\" )", ":", "\"\"", "xml", "+=", "%(<arg #{name}direction=\"in\" type=\"#{param.type}\"/>\\n)", "end", "@rets", ".", "each", "do", "|", "param", "|", "name", "=", "param", ".", "name", "?", "%(name=\"#{param.name}\" )", ":", "\"\"", "xml", "+=", "%(<arg #{name}direction=\"out\" type=\"#{param.type}\"/>\\n)", "end", "xml", "+=", "%(</method>\\n)", "xml", "end" ]
Return an XML string representation of the method interface elment.
[ "Return", "an", "XML", "string", "representation", "of", "the", "method", "interface", "elment", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/introspect.rb#L173-L185
train
mvidner/ruby-dbus
lib/dbus/introspect.rb
DBus.Signal.from_prototype
def from_prototype(prototype) prototype.split(/, */).each do |arg| if arg =~ /:/ arg = arg.split(":") name, sig = arg else sig = arg end add_fparam(name, sig) end self end
ruby
def from_prototype(prototype) prototype.split(/, */).each do |arg| if arg =~ /:/ arg = arg.split(":") name, sig = arg else sig = arg end add_fparam(name, sig) end self end
[ "def", "from_prototype", "(", "prototype", ")", "prototype", ".", "split", "(", "/", "/", ")", ".", "each", "do", "|", "arg", "|", "if", "arg", "=~", "/", "/", "arg", "=", "arg", ".", "split", "(", "\":\"", ")", "name", ",", "sig", "=", "arg", "else", "sig", "=", "arg", "end", "add_fparam", "(", "name", ",", "sig", ")", "end", "self", "end" ]
Add parameter types based on the given _prototype_.
[ "Add", "parameter", "types", "based", "on", "the", "given", "_prototype_", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/introspect.rb#L193-L204
train
mvidner/ruby-dbus
lib/dbus/introspect.rb
DBus.Signal.to_xml
def to_xml xml = %(<signal name="#{@name}">\n) @params.each do |param| name = param.name ? %(name="#{param.name}" ) : "" xml += %(<arg #{name}type="#{param.type}"/>\n) end xml += %(</signal>\n) xml end
ruby
def to_xml xml = %(<signal name="#{@name}">\n) @params.each do |param| name = param.name ? %(name="#{param.name}" ) : "" xml += %(<arg #{name}type="#{param.type}"/>\n) end xml += %(</signal>\n) xml end
[ "def", "to_xml", "xml", "=", "%(<signal name=\"#{@name}\">\\n)", "@params", ".", "each", "do", "|", "param", "|", "name", "=", "param", ".", "name", "?", "%(name=\"#{param.name}\" )", ":", "\"\"", "xml", "+=", "%(<arg #{name}type=\"#{param.type}\"/>\\n)", "end", "xml", "+=", "%(</signal>\\n)", "xml", "end" ]
Return an XML string representation of the signal interface elment.
[ "Return", "an", "XML", "string", "representation", "of", "the", "signal", "interface", "elment", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/introspect.rb#L207-L215
train
mvidner/ruby-dbus
lib/dbus/matchrule.rb
DBus.MatchRule.from_s
def from_s(str) str.split(",").each do |eq| next unless eq =~ /^(.*)='([^']*)'$/ # " name = Regexp.last_match(1) val = Regexp.last_match(2) raise MatchRuleException, name unless FILTERS.member?(name.to_sym) method(name + "=").call(val) end self end
ruby
def from_s(str) str.split(",").each do |eq| next unless eq =~ /^(.*)='([^']*)'$/ # " name = Regexp.last_match(1) val = Regexp.last_match(2) raise MatchRuleException, name unless FILTERS.member?(name.to_sym) method(name + "=").call(val) end self end
[ "def", "from_s", "(", "str", ")", "str", ".", "split", "(", "\",\"", ")", ".", "each", "do", "|", "eq", "|", "next", "unless", "eq", "=~", "/", "/", "name", "=", "Regexp", ".", "last_match", "(", "1", ")", "val", "=", "Regexp", ".", "last_match", "(", "2", ")", "raise", "MatchRuleException", ",", "name", "unless", "FILTERS", ".", "member?", "(", "name", ".", "to_sym", ")", "method", "(", "name", "+", "\"=\"", ")", ".", "call", "(", "val", ")", "end", "self", "end" ]
Parses a match rule string _s_ and sets the filters on the object.
[ "Parses", "a", "match", "rule", "string", "_s_", "and", "sets", "the", "filters", "on", "the", "object", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/matchrule.rb#L58-L68
train
mvidner/ruby-dbus
lib/dbus/matchrule.rb
DBus.MatchRule.from_signal
def from_signal(intf, signal) signal = signal.name unless signal.is_a?(String) self.type = "signal" self.interface = intf.name self.member = signal self.path = intf.object.path self end
ruby
def from_signal(intf, signal) signal = signal.name unless signal.is_a?(String) self.type = "signal" self.interface = intf.name self.member = signal self.path = intf.object.path self end
[ "def", "from_signal", "(", "intf", ",", "signal", ")", "signal", "=", "signal", ".", "name", "unless", "signal", ".", "is_a?", "(", "String", ")", "self", ".", "type", "=", "\"signal\"", "self", ".", "interface", "=", "intf", ".", "name", "self", ".", "member", "=", "signal", "self", ".", "path", "=", "intf", ".", "object", ".", "path", "self", "end" ]
Sets the match rule to filter for the given _signal_ and the given interface _intf_.
[ "Sets", "the", "match", "rule", "to", "filter", "for", "the", "given", "_signal_", "and", "the", "given", "interface", "_intf_", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/matchrule.rb#L72-L79
train
mvidner/ruby-dbus
lib/dbus/matchrule.rb
DBus.MatchRule.match
def match(msg) if @type if { Message::SIGNAL => "signal", Message::METHOD_CALL => "method_call", Message::METHOD_RETURN => "method_return", Message::ERROR => "error" }[msg.message_type] != @type return false end end return false if @interface && @interface != msg.interface return false if @member && @member != msg.member return false if @path && @path != msg.path # FIXME: sender and destination are ignored true end
ruby
def match(msg) if @type if { Message::SIGNAL => "signal", Message::METHOD_CALL => "method_call", Message::METHOD_RETURN => "method_return", Message::ERROR => "error" }[msg.message_type] != @type return false end end return false if @interface && @interface != msg.interface return false if @member && @member != msg.member return false if @path && @path != msg.path # FIXME: sender and destination are ignored true end
[ "def", "match", "(", "msg", ")", "if", "@type", "if", "{", "Message", "::", "SIGNAL", "=>", "\"signal\"", ",", "Message", "::", "METHOD_CALL", "=>", "\"method_call\"", ",", "Message", "::", "METHOD_RETURN", "=>", "\"method_return\"", ",", "Message", "::", "ERROR", "=>", "\"error\"", "}", "[", "msg", ".", "message_type", "]", "!=", "@type", "return", "false", "end", "end", "return", "false", "if", "@interface", "&&", "@interface", "!=", "msg", ".", "interface", "return", "false", "if", "@member", "&&", "@member", "!=", "msg", ".", "member", "return", "false", "if", "@path", "&&", "@path", "!=", "msg", ".", "path", "true", "end" ]
Determines whether a message _msg_ matches the match rule.
[ "Determines", "whether", "a", "message", "_msg_", "matches", "the", "match", "rule", "." ]
336f1871bf0f6a0669391fb2bcf7f3a003ec97c9
https://github.com/mvidner/ruby-dbus/blob/336f1871bf0f6a0669391fb2bcf7f3a003ec97c9/lib/dbus/matchrule.rb#L82-L95
train
capitalone/screen-object
appium/lib/screen-object/accessors.rb
ScreenObject.Accessors.button
def button(name, locator) # generates method for clicking button. # this method will not return any value. # @example click on 'Submit' button. # button(:login_button,"xpath~//UIButtonField") # def click_login_button # login_button # This will click on the button. # end define_method(name) do ScreenObject::AppElements::Button.new(locator).tap end # generates method for checking the existence of the button. # this method will return true or false based on object displayed or not. # @example check if 'Submit' button exists on the screen. # button(:login_button,"xpath~//UIButtonField") # DSL to check existence of login button # def check_login_button # login_button? # This will return true or false based on existence of button. # end define_method("#{name}?") do ScreenObject::AppElements::Button.new(locator).exists? end # generates method for checking if button is enabled. # this method will return true if button is enabled otherwise false. # @example check if 'Submit' button enabled on the screen. # button(:login_button,"xpath~//UIButtonField") # DSL to check if button is enabled or not # def enable_login_button # login_button_enabled? # This will return true or false if button is enabled or disabled. # end define_method("#{name}_enabled?") do ScreenObject::AppElements::Button.new(locator).enabled? end # generates method for getting text for value attribute. # this method will return the text containing into value attribute. # @example To retrieve text from value attribute of the defined object i.e. 'Submit' button. # button(:login_button,"xpath~//UIButtonField") # DSL to retrieve text for value attribute. # def value_login_button # login_button_value # This will return the text of the value attribute of the 'Submit' button object. # end define_method("#{name}_value") do ScreenObject::AppElements::Button.new(locator).value end # generates method for scrolling on the screen and click on the button. # this should be used for iOS platform. # scroll to the first element with exact target static text or name. # this method will not return any value. # button(:login_button,"xpath~//UIButtonField") # def scroll_button # login_button_scroll # This will not return any value. It will scroll on the screen until object found and click # on the object i.e. button. This is iOS specific method and should not be used for android application # end define_method("#{name}_scroll") do # direction = options[:direction] || 'down' ScreenObject::AppElements::Button.new(locator).scroll_for_element_click end # generates method for scrolling on iOS application screen and click on button. This method should be used when button text is dynamic.. # this should be used for iOS platform. # scroll to the first element with exact target dynamic text or name. # this method will not return any value. # @param [text] is the actual text of the button containing. # DSL to scroll on iOS application screen and click on button. This method should be used when button text is dynamic.. # button(:login_button,"UIButtonField") # button API should have class name as shown in this example. # OR # button(:login_button,"UIButtonField/UIButtonFieldtext") # button API should have class name as shown in this example. # def scroll_button # login_button_scroll_dynamic(text) # This will not return any value. we need to pass button text or name as parameter. # It will scroll on the screen until object with same name found and click on # the object i.e. button. This is iOS specific method and should not be used # for android application. # end define_method("#{name}_scroll_dynamic") do |text| # direction = options[:direction] || 'down' ScreenObject::AppElements::Button.new(locator).scroll_for_dynamic_element_click(text) end # generates method for scrolling on Android application screen and click on button. This method should be used when button text is static... # this should be used for Android platform. # scroll to the first element containing target static text or name. # this method will not return any value. # DSL to scroll on Android application screen and click on button. This method should be used when button text is static... # @param [text] is the actual text of the button containing. # button(:login_button,"xpath~//UIButtonField") # def scroll_button # login_button_scroll_(text) # This will not return any value. we need to pass button text or # name[containing targeted text or name] as parameter.It will scroll on the # screen until object with same name found and click on the # object i.e. button. This is Android specific method and should not be used # for iOS application. This method matches with containing text for the # button on the screen and click on it. # end define_method("#{name}_scroll_") do |text| ScreenObject::AppElements::Button.new(locator).click_text(text) end # generates method for scrolling on Android application screen and click on button. This method should be used when button text is dynamic...... # this should be used for Android platform. # scroll to the first element containing target dynamic text or name. # this method will not return any value. # DSL to scroll on Android application screen and click on button. This method should be used when button text is dynamic...... # @param [text] is the actual text of the button containing. # button(:login_button,"UIButtonField") # button API should have class name as shown in this example. # OR # button(:login_button,"UIButtonField/UIButtonFieldtext") # button API should have class name as shown in this example. # # def scroll_button # login_button_scroll_dynamic_(text) # This will not return any value. we need to pass button text or name # [containing targeted text or name] as parameter.It will scroll on the screen # until object with same name found and click on the object i.e. button. # This is Android specific method and should not be used for iOS application. # This method matches with containing text for the button on the screen and click on it. # # end define_method("#{name}_scroll_dynamic_") do |text| ScreenObject::AppElements::Button.new(locator).click_dynamic_text(text) end # generates method for scrolling on the screen and click on the button. # this should be used for Android platform. # scroll to the first element with exact target static text or name. # this method will not return any value. # DSL to scroll on Android application screen and click on button. This method should be used when button text is static. it matches with exact text. # @param [text] is the actual text of the button containing. # button(:login_button,"xpath~//UIButtonField") # def scroll_button # login_button_scroll_exact_(text) # This will not return any value. we need to pass button text or name # [EXACT text or name] as parameter. It will scroll on the screen until # object with same name found and click on the object i.e. button. # This is Android specific method and should not be used for iOS application. # This method matches with exact text for the button on the screen and click on it. # # end define_method("#{name}_scroll_exact_") do |text| ScreenObject::AppElements::Button.new(locator).click_exact_text(text) end #generates method for scrolling on the screen and click on the button. #This should be used for Android platform. # Scroll to the first element with exact target dynamic text or name. # this method will not return any value. # DSL to scroll on Android application screen and click on button. This method should be used when button text is dynamic. it matches with exact text. # @param [text] is the actual text of the button containing. # button(:login_button,"UIButtonField") # button API should have class name as shown in this example. # OR # button(:login_button,"UIButtonField/UIButtonFieldtext") # button API should have class name as shown in this example. # def scroll_button # login_button_scroll_dynamic_exact_(text) # This will not return any value. we need to pass button text or name # [EXACT text or name] as parameter. It will scroll on the screen until object # with same name found and click on the object i.e. button. This is Android specific # method and should not be used for iOS application. This method matches with exact # text for the button on the screen and click on it. # # end define_method("#{name}_scroll_dynamic_exact_") do |text| ScreenObject::AppElements::Button.new(locator).click_dynamic_exact_text(text) end end
ruby
def button(name, locator) # generates method for clicking button. # this method will not return any value. # @example click on 'Submit' button. # button(:login_button,"xpath~//UIButtonField") # def click_login_button # login_button # This will click on the button. # end define_method(name) do ScreenObject::AppElements::Button.new(locator).tap end # generates method for checking the existence of the button. # this method will return true or false based on object displayed or not. # @example check if 'Submit' button exists on the screen. # button(:login_button,"xpath~//UIButtonField") # DSL to check existence of login button # def check_login_button # login_button? # This will return true or false based on existence of button. # end define_method("#{name}?") do ScreenObject::AppElements::Button.new(locator).exists? end # generates method for checking if button is enabled. # this method will return true if button is enabled otherwise false. # @example check if 'Submit' button enabled on the screen. # button(:login_button,"xpath~//UIButtonField") # DSL to check if button is enabled or not # def enable_login_button # login_button_enabled? # This will return true or false if button is enabled or disabled. # end define_method("#{name}_enabled?") do ScreenObject::AppElements::Button.new(locator).enabled? end # generates method for getting text for value attribute. # this method will return the text containing into value attribute. # @example To retrieve text from value attribute of the defined object i.e. 'Submit' button. # button(:login_button,"xpath~//UIButtonField") # DSL to retrieve text for value attribute. # def value_login_button # login_button_value # This will return the text of the value attribute of the 'Submit' button object. # end define_method("#{name}_value") do ScreenObject::AppElements::Button.new(locator).value end # generates method for scrolling on the screen and click on the button. # this should be used for iOS platform. # scroll to the first element with exact target static text or name. # this method will not return any value. # button(:login_button,"xpath~//UIButtonField") # def scroll_button # login_button_scroll # This will not return any value. It will scroll on the screen until object found and click # on the object i.e. button. This is iOS specific method and should not be used for android application # end define_method("#{name}_scroll") do # direction = options[:direction] || 'down' ScreenObject::AppElements::Button.new(locator).scroll_for_element_click end # generates method for scrolling on iOS application screen and click on button. This method should be used when button text is dynamic.. # this should be used for iOS platform. # scroll to the first element with exact target dynamic text or name. # this method will not return any value. # @param [text] is the actual text of the button containing. # DSL to scroll on iOS application screen and click on button. This method should be used when button text is dynamic.. # button(:login_button,"UIButtonField") # button API should have class name as shown in this example. # OR # button(:login_button,"UIButtonField/UIButtonFieldtext") # button API should have class name as shown in this example. # def scroll_button # login_button_scroll_dynamic(text) # This will not return any value. we need to pass button text or name as parameter. # It will scroll on the screen until object with same name found and click on # the object i.e. button. This is iOS specific method and should not be used # for android application. # end define_method("#{name}_scroll_dynamic") do |text| # direction = options[:direction] || 'down' ScreenObject::AppElements::Button.new(locator).scroll_for_dynamic_element_click(text) end # generates method for scrolling on Android application screen and click on button. This method should be used when button text is static... # this should be used for Android platform. # scroll to the first element containing target static text or name. # this method will not return any value. # DSL to scroll on Android application screen and click on button. This method should be used when button text is static... # @param [text] is the actual text of the button containing. # button(:login_button,"xpath~//UIButtonField") # def scroll_button # login_button_scroll_(text) # This will not return any value. we need to pass button text or # name[containing targeted text or name] as parameter.It will scroll on the # screen until object with same name found and click on the # object i.e. button. This is Android specific method and should not be used # for iOS application. This method matches with containing text for the # button on the screen and click on it. # end define_method("#{name}_scroll_") do |text| ScreenObject::AppElements::Button.new(locator).click_text(text) end # generates method for scrolling on Android application screen and click on button. This method should be used when button text is dynamic...... # this should be used for Android platform. # scroll to the first element containing target dynamic text or name. # this method will not return any value. # DSL to scroll on Android application screen and click on button. This method should be used when button text is dynamic...... # @param [text] is the actual text of the button containing. # button(:login_button,"UIButtonField") # button API should have class name as shown in this example. # OR # button(:login_button,"UIButtonField/UIButtonFieldtext") # button API should have class name as shown in this example. # # def scroll_button # login_button_scroll_dynamic_(text) # This will not return any value. we need to pass button text or name # [containing targeted text or name] as parameter.It will scroll on the screen # until object with same name found and click on the object i.e. button. # This is Android specific method and should not be used for iOS application. # This method matches with containing text for the button on the screen and click on it. # # end define_method("#{name}_scroll_dynamic_") do |text| ScreenObject::AppElements::Button.new(locator).click_dynamic_text(text) end # generates method for scrolling on the screen and click on the button. # this should be used for Android platform. # scroll to the first element with exact target static text or name. # this method will not return any value. # DSL to scroll on Android application screen and click on button. This method should be used when button text is static. it matches with exact text. # @param [text] is the actual text of the button containing. # button(:login_button,"xpath~//UIButtonField") # def scroll_button # login_button_scroll_exact_(text) # This will not return any value. we need to pass button text or name # [EXACT text or name] as parameter. It will scroll on the screen until # object with same name found and click on the object i.e. button. # This is Android specific method and should not be used for iOS application. # This method matches with exact text for the button on the screen and click on it. # # end define_method("#{name}_scroll_exact_") do |text| ScreenObject::AppElements::Button.new(locator).click_exact_text(text) end #generates method for scrolling on the screen and click on the button. #This should be used for Android platform. # Scroll to the first element with exact target dynamic text or name. # this method will not return any value. # DSL to scroll on Android application screen and click on button. This method should be used when button text is dynamic. it matches with exact text. # @param [text] is the actual text of the button containing. # button(:login_button,"UIButtonField") # button API should have class name as shown in this example. # OR # button(:login_button,"UIButtonField/UIButtonFieldtext") # button API should have class name as shown in this example. # def scroll_button # login_button_scroll_dynamic_exact_(text) # This will not return any value. we need to pass button text or name # [EXACT text or name] as parameter. It will scroll on the screen until object # with same name found and click on the object i.e. button. This is Android specific # method and should not be used for iOS application. This method matches with exact # text for the button on the screen and click on it. # # end define_method("#{name}_scroll_dynamic_exact_") do |text| ScreenObject::AppElements::Button.new(locator).click_dynamic_exact_text(text) end end
[ "def", "button", "(", "name", ",", "locator", ")", "define_method", "(", "name", ")", "do", "ScreenObject", "::", "AppElements", "::", "Button", ".", "new", "(", "locator", ")", ".", "tap", "end", "define_method", "(", "\"#{name}?\"", ")", "do", "ScreenObject", "::", "AppElements", "::", "Button", ".", "new", "(", "locator", ")", ".", "exists?", "end", "define_method", "(", "\"#{name}_enabled?\"", ")", "do", "ScreenObject", "::", "AppElements", "::", "Button", ".", "new", "(", "locator", ")", ".", "enabled?", "end", "define_method", "(", "\"#{name}_value\"", ")", "do", "ScreenObject", "::", "AppElements", "::", "Button", ".", "new", "(", "locator", ")", ".", "value", "end", "define_method", "(", "\"#{name}_scroll\"", ")", "do", "ScreenObject", "::", "AppElements", "::", "Button", ".", "new", "(", "locator", ")", ".", "scroll_for_element_click", "end", "define_method", "(", "\"#{name}_scroll_dynamic\"", ")", "do", "|", "text", "|", "ScreenObject", "::", "AppElements", "::", "Button", ".", "new", "(", "locator", ")", ".", "scroll_for_dynamic_element_click", "(", "text", ")", "end", "define_method", "(", "\"#{name}_scroll_\"", ")", "do", "|", "text", "|", "ScreenObject", "::", "AppElements", "::", "Button", ".", "new", "(", "locator", ")", ".", "click_text", "(", "text", ")", "end", "define_method", "(", "\"#{name}_scroll_dynamic_\"", ")", "do", "|", "text", "|", "ScreenObject", "::", "AppElements", "::", "Button", ".", "new", "(", "locator", ")", ".", "click_dynamic_text", "(", "text", ")", "end", "define_method", "(", "\"#{name}_scroll_exact_\"", ")", "do", "|", "text", "|", "ScreenObject", "::", "AppElements", "::", "Button", ".", "new", "(", "locator", ")", ".", "click_exact_text", "(", "text", ")", "end", "define_method", "(", "\"#{name}_scroll_dynamic_exact_\"", ")", "do", "|", "text", "|", "ScreenObject", "::", "AppElements", "::", "Button", ".", "new", "(", "locator", ")", ".", "click_dynamic_exact_text", "(", "text", ")", "end", "end" ]
Button class generates all the methods related to different operations that can be performed on the button.
[ "Button", "class", "generates", "all", "the", "methods", "related", "to", "different", "operations", "that", "can", "be", "performed", "on", "the", "button", "." ]
9e206b09db3957c98b35502acb6549e5d0290f74
https://github.com/capitalone/screen-object/blob/9e206b09db3957c98b35502acb6549e5d0290f74/appium/lib/screen-object/accessors.rb#L28-L192
train
capitalone/screen-object
appium/lib/screen-object/accessors.rb
ScreenObject.Accessors.checkbox
def checkbox(name, locator) # generates method for checking the checkbox object. # this will not return any value # @example check if 'remember me' checkbox is not checked. # checkbox(:remember_me,"xpath~//UICheckBox") # DSL to check the 'remember me' check box. # def check_remember_me_checkbox # check_remember_me # This method will check the check box. # end define_method("check_#{name}") do ScreenObject::AppElements::CheckBox.new(locator).check end # generates method for un-checking the checkbox. # this will not return any value # @example uncheck if 'remember me' check box is checked. # DSL to uncheck remember me check box # def uncheck_remember_me_check_box # uncheck_remember_me # This method will uncheck the check box if it's checked. # end define_method("uncheck_#{name}") do ScreenObject::AppElements::CheckBox.new(locator).uncheck end # generates method for checking the existence of object. # this will return true or false based on object is displayed or not. # @example check if 'remember me' check box exists on the screen. # def exist_remember_me_check_box # remember_me? # This method is used to return true or false based on 'remember me' check box exist. # end define_method("#{name}?") do ScreenObject::AppElements::CheckBox.new(locator).exists? end # generates method for checking if checkbox is already checked. # this will return true if checkbox is checked. # @example check if 'remember me' check box is not checked. # def exist_remember_me_check_box # remember_me? # This method is used to return true or false based on 'remember me' check box exist. # end define_method("#{name}_checked?") do ScreenObject::AppElements::CheckBox.new(locator).checked? end end
ruby
def checkbox(name, locator) # generates method for checking the checkbox object. # this will not return any value # @example check if 'remember me' checkbox is not checked. # checkbox(:remember_me,"xpath~//UICheckBox") # DSL to check the 'remember me' check box. # def check_remember_me_checkbox # check_remember_me # This method will check the check box. # end define_method("check_#{name}") do ScreenObject::AppElements::CheckBox.new(locator).check end # generates method for un-checking the checkbox. # this will not return any value # @example uncheck if 'remember me' check box is checked. # DSL to uncheck remember me check box # def uncheck_remember_me_check_box # uncheck_remember_me # This method will uncheck the check box if it's checked. # end define_method("uncheck_#{name}") do ScreenObject::AppElements::CheckBox.new(locator).uncheck end # generates method for checking the existence of object. # this will return true or false based on object is displayed or not. # @example check if 'remember me' check box exists on the screen. # def exist_remember_me_check_box # remember_me? # This method is used to return true or false based on 'remember me' check box exist. # end define_method("#{name}?") do ScreenObject::AppElements::CheckBox.new(locator).exists? end # generates method for checking if checkbox is already checked. # this will return true if checkbox is checked. # @example check if 'remember me' check box is not checked. # def exist_remember_me_check_box # remember_me? # This method is used to return true or false based on 'remember me' check box exist. # end define_method("#{name}_checked?") do ScreenObject::AppElements::CheckBox.new(locator).checked? end end
[ "def", "checkbox", "(", "name", ",", "locator", ")", "define_method", "(", "\"check_#{name}\"", ")", "do", "ScreenObject", "::", "AppElements", "::", "CheckBox", ".", "new", "(", "locator", ")", ".", "check", "end", "define_method", "(", "\"uncheck_#{name}\"", ")", "do", "ScreenObject", "::", "AppElements", "::", "CheckBox", ".", "new", "(", "locator", ")", ".", "uncheck", "end", "define_method", "(", "\"#{name}?\"", ")", "do", "ScreenObject", "::", "AppElements", "::", "CheckBox", ".", "new", "(", "locator", ")", ".", "exists?", "end", "define_method", "(", "\"#{name}_checked?\"", ")", "do", "ScreenObject", "::", "AppElements", "::", "CheckBox", ".", "new", "(", "locator", ")", ".", "checked?", "end", "end" ]
end of button class. Checkbox class generates all the methods related to different operations that can be performed on the check box on the screen.
[ "end", "of", "button", "class", ".", "Checkbox", "class", "generates", "all", "the", "methods", "related", "to", "different", "operations", "that", "can", "be", "performed", "on", "the", "check", "box", "on", "the", "screen", "." ]
9e206b09db3957c98b35502acb6549e5d0290f74
https://github.com/capitalone/screen-object/blob/9e206b09db3957c98b35502acb6549e5d0290f74/appium/lib/screen-object/accessors.rb#L195-L240
train
capitalone/screen-object
appium/lib/screen-object/accessors.rb
ScreenObject.Accessors.text
def text(name,locator) # generates method for clicking button. # this method will not return any value. # @example click on 'Submit' button. # button(:login_button,"xpath~//UIButtonField") # def click_login_button # login_button # This will click on the button. # end define_method(name) do ScreenObject::AppElements::Text.new(locator).tap end # generates method for checking if text exists on the screen. # this will return true or false based on if text is available or not # @example check if 'Welcome' text is displayed on the page # text(:welcome_text,"xpath~//UITextField") # # DSL for clicking the Welcome text. # def verify_welcome_text # welcome_text? # This will check if object exists and return true.. # end define_method("#{name}?") do ScreenObject::AppElements::Text.new(locator).exists? end # generates method for clicking on text object. # this will NOT return any value. # @example check if 'Welcome' text is displayed on the page # text(:welcome_text,"xpath~//UITextField") # DSL for clicking the Welcome text. # def click_welcome_text # welcome_text # This will click on the Welcome text on the screen. # end define_method("#{name}") do ScreenObject::AppElements::Text.new(locator).click end # generates method for retrieving text of the object. # this will return value of text attribute of the object. # @example retrieve text of 'Welcome' object on the page. # text(:welcome_text,"xpath~//UITextField") # DSL to retrieve text of the attribute text. # def get_welcome_text # welcome_text_text # This will return text of value of attribute 'text'. # end define_method("#{name}_text") do ScreenObject::AppElements::Text.new(locator).text end # generates method for checking dynamic text object. # this will return true or false based on object is displayed or not. # @example check if 'Welcome' text is displayed on the page # @param [text] is the actual text of the button containing. # suppose 'Welcome guest' text appears on the screen for non logged in user and it changes when user logged in on the screen and appears as 'Welcome <guest_name>'. this would be treated as dynamic text since it would be changing based on guest name. # DSL to check if the text that is sent as argument exists on the screen. Returns true or false # text(:welcome_guest,"xpath~//UITextField") # def dynamic_welcome_guest(Welcome_<guest_name>) # welcome_text_dynamic?(welcome_<guest_name>) # This will return true or false based welcome text exists on the screen. # end define_method("#{name}_dynamic?") do |text| ScreenObject::AppElements::Text.new(locator).dynamic_text_exists?(text) end # generates method for retrieving text of the value attribute of the object. # this will return text of value attribute of the object. # @example retrieve text of the 'Welcome' text. # text(:welcome_text,"xpath~//UITextField") # DSL to retrieve text of the attribute text. # def get_welcome_text # welcome_text_value # This will return text of value of attribute 'text'. # end define_method("#{name}_value") do ScreenObject::AppElements::Text.new(locator).value end # generates method for checking dynamic text object. # this will return actual test for an object. # @example check if 'Welcome' text is displayed on the page # @param [text] is the actual text of the button containing. # suppose 'Welcome guest' text appears on the screen for non logged in user and it changes when user logged in on the screen and appears as 'Welcome <guest_name>'. this would be treated as dynamic text since it would be changing based on guest name. # DSL to check if the text that is sent as argument exists on the screen. Returns true or false # text(:welcome_guest,"xpath~//UITextField") # def dynamic_welcome_guest(Welcome_<guest_name>) # welcome_text_dynamic?(welcome_<guest_name>) # This will return true or false based welcome text exists on the screen. # end define_method("#{name}_dynamic_text") do |text| ScreenObject::AppElements::Text.new(locator).dynamic_text(text) end end
ruby
def text(name,locator) # generates method for clicking button. # this method will not return any value. # @example click on 'Submit' button. # button(:login_button,"xpath~//UIButtonField") # def click_login_button # login_button # This will click on the button. # end define_method(name) do ScreenObject::AppElements::Text.new(locator).tap end # generates method for checking if text exists on the screen. # this will return true or false based on if text is available or not # @example check if 'Welcome' text is displayed on the page # text(:welcome_text,"xpath~//UITextField") # # DSL for clicking the Welcome text. # def verify_welcome_text # welcome_text? # This will check if object exists and return true.. # end define_method("#{name}?") do ScreenObject::AppElements::Text.new(locator).exists? end # generates method for clicking on text object. # this will NOT return any value. # @example check if 'Welcome' text is displayed on the page # text(:welcome_text,"xpath~//UITextField") # DSL for clicking the Welcome text. # def click_welcome_text # welcome_text # This will click on the Welcome text on the screen. # end define_method("#{name}") do ScreenObject::AppElements::Text.new(locator).click end # generates method for retrieving text of the object. # this will return value of text attribute of the object. # @example retrieve text of 'Welcome' object on the page. # text(:welcome_text,"xpath~//UITextField") # DSL to retrieve text of the attribute text. # def get_welcome_text # welcome_text_text # This will return text of value of attribute 'text'. # end define_method("#{name}_text") do ScreenObject::AppElements::Text.new(locator).text end # generates method for checking dynamic text object. # this will return true or false based on object is displayed or not. # @example check if 'Welcome' text is displayed on the page # @param [text] is the actual text of the button containing. # suppose 'Welcome guest' text appears on the screen for non logged in user and it changes when user logged in on the screen and appears as 'Welcome <guest_name>'. this would be treated as dynamic text since it would be changing based on guest name. # DSL to check if the text that is sent as argument exists on the screen. Returns true or false # text(:welcome_guest,"xpath~//UITextField") # def dynamic_welcome_guest(Welcome_<guest_name>) # welcome_text_dynamic?(welcome_<guest_name>) # This will return true or false based welcome text exists on the screen. # end define_method("#{name}_dynamic?") do |text| ScreenObject::AppElements::Text.new(locator).dynamic_text_exists?(text) end # generates method for retrieving text of the value attribute of the object. # this will return text of value attribute of the object. # @example retrieve text of the 'Welcome' text. # text(:welcome_text,"xpath~//UITextField") # DSL to retrieve text of the attribute text. # def get_welcome_text # welcome_text_value # This will return text of value of attribute 'text'. # end define_method("#{name}_value") do ScreenObject::AppElements::Text.new(locator).value end # generates method for checking dynamic text object. # this will return actual test for an object. # @example check if 'Welcome' text is displayed on the page # @param [text] is the actual text of the button containing. # suppose 'Welcome guest' text appears on the screen for non logged in user and it changes when user logged in on the screen and appears as 'Welcome <guest_name>'. this would be treated as dynamic text since it would be changing based on guest name. # DSL to check if the text that is sent as argument exists on the screen. Returns true or false # text(:welcome_guest,"xpath~//UITextField") # def dynamic_welcome_guest(Welcome_<guest_name>) # welcome_text_dynamic?(welcome_<guest_name>) # This will return true or false based welcome text exists on the screen. # end define_method("#{name}_dynamic_text") do |text| ScreenObject::AppElements::Text.new(locator).dynamic_text(text) end end
[ "def", "text", "(", "name", ",", "locator", ")", "define_method", "(", "name", ")", "do", "ScreenObject", "::", "AppElements", "::", "Text", ".", "new", "(", "locator", ")", ".", "tap", "end", "define_method", "(", "\"#{name}?\"", ")", "do", "ScreenObject", "::", "AppElements", "::", "Text", ".", "new", "(", "locator", ")", ".", "exists?", "end", "define_method", "(", "\"#{name}\"", ")", "do", "ScreenObject", "::", "AppElements", "::", "Text", ".", "new", "(", "locator", ")", ".", "click", "end", "define_method", "(", "\"#{name}_text\"", ")", "do", "ScreenObject", "::", "AppElements", "::", "Text", ".", "new", "(", "locator", ")", ".", "text", "end", "define_method", "(", "\"#{name}_dynamic?\"", ")", "do", "|", "text", "|", "ScreenObject", "::", "AppElements", "::", "Text", ".", "new", "(", "locator", ")", ".", "dynamic_text_exists?", "(", "text", ")", "end", "define_method", "(", "\"#{name}_value\"", ")", "do", "ScreenObject", "::", "AppElements", "::", "Text", ".", "new", "(", "locator", ")", ".", "value", "end", "define_method", "(", "\"#{name}_dynamic_text\"", ")", "do", "|", "text", "|", "ScreenObject", "::", "AppElements", "::", "Text", ".", "new", "(", "locator", ")", ".", "dynamic_text", "(", "text", ")", "end", "end" ]
Text class generates all the methods related to different operations that can be performed on the text object on the screen.
[ "Text", "class", "generates", "all", "the", "methods", "related", "to", "different", "operations", "that", "can", "be", "performed", "on", "the", "text", "object", "on", "the", "screen", "." ]
9e206b09db3957c98b35502acb6549e5d0290f74
https://github.com/capitalone/screen-object/blob/9e206b09db3957c98b35502acb6549e5d0290f74/appium/lib/screen-object/accessors.rb#L244-L334
train
capitalone/screen-object
appium/lib/screen-object/accessors.rb
ScreenObject.Accessors.text_field
def text_field(name,locator) # generates method for setting text into text field. # There is no return value for this method. # @example setting username field. # DSL for entering text in username text field. # def set_username_text_field(username) # self.username=username # This method will enter text into username text field. # end define_method("#{name}=") do |text| ScreenObject::AppElements::TextField.new(locator).text=(text) end # generates method for comparing expected and actual text. # this will return text of text attribute of the object. # @example retrieve text of the 'username' text field. # text_field(:username,"xpath~//UITextField") # DSL to retrieve text of the attribute text. # def get_welcome_text # username_text # This will return text containing in text field attribute. # end define_method("#{name}") do ScreenObject::AppElements::TextField.new(locator).text end # generates method for clear pre populated text from the text field. # this will not return any value. # @example clear text of the username text field. # text_field(:username,"xpath~//UITextField") # DSL to clear the text of the text field. # def clear_text # clear_username # This will clear the pre populated user name text field. # end define_method("clear_#{name}") do ScreenObject::AppElements::TextField.new(locator).clear end # generates method for checking if text_field exists on the screen. # this will return true or false based on if text field is available or not # @example check if 'username' text field is displayed on the page # text_field(:username,"xpath~//UITextField") # # DSL for clicking the username text. # def exists_username # username? # This will return if object exists on the screen. # end define_method("#{name}?") do ScreenObject::AppElements::TextField.new(locator).exists? end # generates method for retrieving text of the value attribute of the object. # this will return text of value attribute of the object. # @example retrieve text of the 'username' text_field. # text_field(:username,"xpath~//UITextField") # DSL to retrieve text of the attribute text. # def get_username_text # username_value # This will return text of value of attribute 'text'. # end define_method("#{name}_value") do ScreenObject::AppElements::TextField.new(locator).value end # generates method for checking if button is enabled. # this method will return true if button is enabled otherwise false. # @example check if 'Submit' button enabled on the screen. # button(:login_button,"xpath~//UIButtonField") # DSL to check if button is enabled or not # def enable_login_button # login_button_enabled? # This will return true or false if button is enabled or disabled. # end define_method("#{name}_enabled?") do ScreenObject::AppElements::TextField.new(locator).enabled? end end
ruby
def text_field(name,locator) # generates method for setting text into text field. # There is no return value for this method. # @example setting username field. # DSL for entering text in username text field. # def set_username_text_field(username) # self.username=username # This method will enter text into username text field. # end define_method("#{name}=") do |text| ScreenObject::AppElements::TextField.new(locator).text=(text) end # generates method for comparing expected and actual text. # this will return text of text attribute of the object. # @example retrieve text of the 'username' text field. # text_field(:username,"xpath~//UITextField") # DSL to retrieve text of the attribute text. # def get_welcome_text # username_text # This will return text containing in text field attribute. # end define_method("#{name}") do ScreenObject::AppElements::TextField.new(locator).text end # generates method for clear pre populated text from the text field. # this will not return any value. # @example clear text of the username text field. # text_field(:username,"xpath~//UITextField") # DSL to clear the text of the text field. # def clear_text # clear_username # This will clear the pre populated user name text field. # end define_method("clear_#{name}") do ScreenObject::AppElements::TextField.new(locator).clear end # generates method for checking if text_field exists on the screen. # this will return true or false based on if text field is available or not # @example check if 'username' text field is displayed on the page # text_field(:username,"xpath~//UITextField") # # DSL for clicking the username text. # def exists_username # username? # This will return if object exists on the screen. # end define_method("#{name}?") do ScreenObject::AppElements::TextField.new(locator).exists? end # generates method for retrieving text of the value attribute of the object. # this will return text of value attribute of the object. # @example retrieve text of the 'username' text_field. # text_field(:username,"xpath~//UITextField") # DSL to retrieve text of the attribute text. # def get_username_text # username_value # This will return text of value of attribute 'text'. # end define_method("#{name}_value") do ScreenObject::AppElements::TextField.new(locator).value end # generates method for checking if button is enabled. # this method will return true if button is enabled otherwise false. # @example check if 'Submit' button enabled on the screen. # button(:login_button,"xpath~//UIButtonField") # DSL to check if button is enabled or not # def enable_login_button # login_button_enabled? # This will return true or false if button is enabled or disabled. # end define_method("#{name}_enabled?") do ScreenObject::AppElements::TextField.new(locator).enabled? end end
[ "def", "text_field", "(", "name", ",", "locator", ")", "define_method", "(", "\"#{name}=\"", ")", "do", "|", "text", "|", "ScreenObject", "::", "AppElements", "::", "TextField", ".", "new", "(", "locator", ")", ".", "text", "=", "(", "text", ")", "end", "define_method", "(", "\"#{name}\"", ")", "do", "ScreenObject", "::", "AppElements", "::", "TextField", ".", "new", "(", "locator", ")", ".", "text", "end", "define_method", "(", "\"clear_#{name}\"", ")", "do", "ScreenObject", "::", "AppElements", "::", "TextField", ".", "new", "(", "locator", ")", ".", "clear", "end", "define_method", "(", "\"#{name}?\"", ")", "do", "ScreenObject", "::", "AppElements", "::", "TextField", ".", "new", "(", "locator", ")", ".", "exists?", "end", "define_method", "(", "\"#{name}_value\"", ")", "do", "ScreenObject", "::", "AppElements", "::", "TextField", ".", "new", "(", "locator", ")", ".", "value", "end", "define_method", "(", "\"#{name}_enabled?\"", ")", "do", "ScreenObject", "::", "AppElements", "::", "TextField", ".", "new", "(", "locator", ")", ".", "enabled?", "end", "end" ]
text_field class generates all the methods related to different operations that can be performed on the text_field object on the screen.
[ "text_field", "class", "generates", "all", "the", "methods", "related", "to", "different", "operations", "that", "can", "be", "performed", "on", "the", "text_field", "object", "on", "the", "screen", "." ]
9e206b09db3957c98b35502acb6549e5d0290f74
https://github.com/capitalone/screen-object/blob/9e206b09db3957c98b35502acb6549e5d0290f74/appium/lib/screen-object/accessors.rb#L337-L411
train
capitalone/screen-object
appium/lib/screen-object/accessors.rb
ScreenObject.Accessors.image
def image(name,locator) # generates method for checking the existence of the image. # this will return true or false based on if image is available or not # @example check if 'logo' image is displayed on the page # text(:logo,"xpath~//UITextField") # DSL for clicking the logo image. # def click_logo # logo # This will click on the logo text on the screen. # end define_method("#{name}?") do ScreenObject::AppElements::Image.new(locator).exists? end #generates method for clicking image # this will not return any value. # @example clicking on logo image. # text(:logo,"xpath~//UITextField") # DSL for clicking the logo image. # def click_logo # logo # This will click on the logo text on the screen. # end define_method("#{name}") do ScreenObject::AppElements::Image.new(locator).click end end
ruby
def image(name,locator) # generates method for checking the existence of the image. # this will return true or false based on if image is available or not # @example check if 'logo' image is displayed on the page # text(:logo,"xpath~//UITextField") # DSL for clicking the logo image. # def click_logo # logo # This will click on the logo text on the screen. # end define_method("#{name}?") do ScreenObject::AppElements::Image.new(locator).exists? end #generates method for clicking image # this will not return any value. # @example clicking on logo image. # text(:logo,"xpath~//UITextField") # DSL for clicking the logo image. # def click_logo # logo # This will click on the logo text on the screen. # end define_method("#{name}") do ScreenObject::AppElements::Image.new(locator).click end end
[ "def", "image", "(", "name", ",", "locator", ")", "define_method", "(", "\"#{name}?\"", ")", "do", "ScreenObject", "::", "AppElements", "::", "Image", ".", "new", "(", "locator", ")", ".", "exists?", "end", "define_method", "(", "\"#{name}\"", ")", "do", "ScreenObject", "::", "AppElements", "::", "Image", ".", "new", "(", "locator", ")", ".", "click", "end", "end" ]
Image class generates all the methods related to different operations that can be performed on the image object on the screen.
[ "Image", "class", "generates", "all", "the", "methods", "related", "to", "different", "operations", "that", "can", "be", "performed", "on", "the", "image", "object", "on", "the", "screen", "." ]
9e206b09db3957c98b35502acb6549e5d0290f74
https://github.com/capitalone/screen-object/blob/9e206b09db3957c98b35502acb6549e5d0290f74/appium/lib/screen-object/accessors.rb#L415-L440
train
capitalone/screen-object
appium/lib/screen-object/accessors.rb
ScreenObject.Accessors.table
def table(name, locator) #generates method for counting total no of cells in table define_method("#{name}_cell_count") do ScreenObject::AppElements::Table.new(locator).cell_count end end
ruby
def table(name, locator) #generates method for counting total no of cells in table define_method("#{name}_cell_count") do ScreenObject::AppElements::Table.new(locator).cell_count end end
[ "def", "table", "(", "name", ",", "locator", ")", "define_method", "(", "\"#{name}_cell_count\"", ")", "do", "ScreenObject", "::", "AppElements", "::", "Table", ".", "new", "(", "locator", ")", ".", "cell_count", "end", "end" ]
table class generates all the methods related to different operations that can be performed on the table object on the screen.
[ "table", "class", "generates", "all", "the", "methods", "related", "to", "different", "operations", "that", "can", "be", "performed", "on", "the", "table", "object", "on", "the", "screen", "." ]
9e206b09db3957c98b35502acb6549e5d0290f74
https://github.com/capitalone/screen-object/blob/9e206b09db3957c98b35502acb6549e5d0290f74/appium/lib/screen-object/accessors.rb#L443-L448
train
maoueh/nugrant
lib/nugrant/bag.rb
Nugrant.Bag.__convert_value
def __convert_value(value) case # Converts Hash to Bag instance when value.kind_of?(Hash) Bag.new(value, @__config) # Converts Array elements to Bag instances if needed when value.kind_of?(Array) value.map(&self.method(:__convert_value)) # Keeps as-is other elements else value end end
ruby
def __convert_value(value) case # Converts Hash to Bag instance when value.kind_of?(Hash) Bag.new(value, @__config) # Converts Array elements to Bag instances if needed when value.kind_of?(Array) value.map(&self.method(:__convert_value)) # Keeps as-is other elements else value end end
[ "def", "__convert_value", "(", "value", ")", "case", "when", "value", ".", "kind_of?", "(", "Hash", ")", "Bag", ".", "new", "(", "value", ",", "@__config", ")", "when", "value", ".", "kind_of?", "(", "Array", ")", "value", ".", "map", "(", "&", "self", ".", "method", "(", ":__convert_value", ")", ")", "else", "value", "end", "end" ]
This function change value convertible to Bag into actual Bag. This trick enable deeply using all Bag functionalities and also ensures at the same time a deeply preventive copy since a new instance is created for this nested structure. In addition, it also transforms array elements of type Hash into Bag instance also. This enable indifferent access inside arrays also. @param value The value to convert to bag if necessary @return The converted value
[ "This", "function", "change", "value", "convertible", "to", "Bag", "into", "actual", "Bag", ".", "This", "trick", "enable", "deeply", "using", "all", "Bag", "functionalities", "and", "also", "ensures", "at", "the", "same", "time", "a", "deeply", "preventive", "copy", "since", "a", "new", "instance", "is", "created", "for", "this", "nested", "structure", "." ]
06186127a7dbe49a3018b077da3f5405a604aa0b
https://github.com/maoueh/nugrant/blob/06186127a7dbe49a3018b077da3f5405a604aa0b/lib/nugrant/bag.rb#L188-L202
train
pepabo/furik
lib/furik/pull_requests.rb
Furik.PullRequests.pull_requests
def pull_requests(repo_name) org_name = org_name_from(repo_name) unless @block if @org_name == org_name print '-' else puts '' print "#{org_name} -" @org_name = org_name end end issues = @client.issues(repo_name, creator: @login, state: 'open'). select { |issue| issue.pull_request } issues.concat @client.issues(repo_name, creator: @login, state: 'closed'). select { |issue| issue.pull_request } @block.call(repo_name, issues) if @block issues rescue Octokit::ClientError rescue => e puts e end
ruby
def pull_requests(repo_name) org_name = org_name_from(repo_name) unless @block if @org_name == org_name print '-' else puts '' print "#{org_name} -" @org_name = org_name end end issues = @client.issues(repo_name, creator: @login, state: 'open'). select { |issue| issue.pull_request } issues.concat @client.issues(repo_name, creator: @login, state: 'closed'). select { |issue| issue.pull_request } @block.call(repo_name, issues) if @block issues rescue Octokit::ClientError rescue => e puts e end
[ "def", "pull_requests", "(", "repo_name", ")", "org_name", "=", "org_name_from", "(", "repo_name", ")", "unless", "@block", "if", "@org_name", "==", "org_name", "print", "'-'", "else", "puts", "''", "print", "\"#{org_name} -\"", "@org_name", "=", "org_name", "end", "end", "issues", "=", "@client", ".", "issues", "(", "repo_name", ",", "creator", ":", "@login", ",", "state", ":", "'open'", ")", ".", "select", "{", "|", "issue", "|", "issue", ".", "pull_request", "}", "issues", ".", "concat", "@client", ".", "issues", "(", "repo_name", ",", "creator", ":", "@login", ",", "state", ":", "'closed'", ")", ".", "select", "{", "|", "issue", "|", "issue", ".", "pull_request", "}", "@block", ".", "call", "(", "repo_name", ",", "issues", ")", "if", "@block", "issues", "rescue", "Octokit", "::", "ClientError", "rescue", "=>", "e", "puts", "e", "end" ]
Use the issues api so specify the creator
[ "Use", "the", "issues", "api", "so", "specify", "the", "creator" ]
b2b17d9ab7dbed51f6de8023331dc72e3c856ed5
https://github.com/pepabo/furik/blob/b2b17d9ab7dbed51f6de8023331dc72e3c856ed5/lib/furik/pull_requests.rb#L38-L62
train
darkskyapp/darksky-ruby
lib/darksky/api.rb
Darksky.API.precipitation
def precipitation(latitudes_longitudes_times, options = {}) return if latitudes_longitudes_times.size % 3 != 0 params = [] latitudes_longitudes_times.each_slice(3) do |data| params << data.join(',') end response = Typhoeus::Request.get("#{DARKSKY_API_URL}/precipitation/#{@api_key}/#{params.join(';')}", DEFAULT_OPTIONS.dup.merge(options)) JSON.parse(response.body) if response.code == 200 end
ruby
def precipitation(latitudes_longitudes_times, options = {}) return if latitudes_longitudes_times.size % 3 != 0 params = [] latitudes_longitudes_times.each_slice(3) do |data| params << data.join(',') end response = Typhoeus::Request.get("#{DARKSKY_API_URL}/precipitation/#{@api_key}/#{params.join(';')}", DEFAULT_OPTIONS.dup.merge(options)) JSON.parse(response.body) if response.code == 200 end
[ "def", "precipitation", "(", "latitudes_longitudes_times", ",", "options", "=", "{", "}", ")", "return", "if", "latitudes_longitudes_times", ".", "size", "%", "3", "!=", "0", "params", "=", "[", "]", "latitudes_longitudes_times", ".", "each_slice", "(", "3", ")", "do", "|", "data", "|", "params", "<<", "data", ".", "join", "(", "','", ")", "end", "response", "=", "Typhoeus", "::", "Request", ".", "get", "(", "\"#{DARKSKY_API_URL}/precipitation/#{@api_key}/#{params.join(';')}\"", ",", "DEFAULT_OPTIONS", ".", "dup", ".", "merge", "(", "options", ")", ")", "JSON", ".", "parse", "(", "response", ".", "body", ")", "if", "response", ".", "code", "==", "200", "end" ]
Returns forecasts for a collection of arbitrary points. @param latitudes_longitudes_times [Array] Triplets of latitude, longitude and time. Example: ['42.7','-73.6',1325607100,'42.0','-73.0',1325607791] @param option [Hash] (Optional) Options to be passed to the Typhoeus::Request
[ "Returns", "forecasts", "for", "a", "collection", "of", "arbitrary", "points", "." ]
8cee1e294f3b0f465545d61f68cf74afd76159ce
https://github.com/darkskyapp/darksky-ruby/blob/8cee1e294f3b0f465545d61f68cf74afd76159ce/lib/darksky/api.rb#L41-L49
train
darkskyapp/darksky-ruby
lib/darksky/api.rb
Darksky.API.interesting
def interesting(options = {}) response = Typhoeus::Request.get("#{DARKSKY_API_URL}/interesting/#{@api_key}", DEFAULT_OPTIONS.dup.merge(options)) JSON.parse(response.body) if response.code == 200 end
ruby
def interesting(options = {}) response = Typhoeus::Request.get("#{DARKSKY_API_URL}/interesting/#{@api_key}", DEFAULT_OPTIONS.dup.merge(options)) JSON.parse(response.body) if response.code == 200 end
[ "def", "interesting", "(", "options", "=", "{", "}", ")", "response", "=", "Typhoeus", "::", "Request", ".", "get", "(", "\"#{DARKSKY_API_URL}/interesting/#{@api_key}\"", ",", "DEFAULT_OPTIONS", ".", "dup", ".", "merge", "(", "options", ")", ")", "JSON", ".", "parse", "(", "response", ".", "body", ")", "if", "response", ".", "code", "==", "200", "end" ]
Returns a list of interesting storms happening right now. @param option [Hash] (Optional) Options to be passed to the Typhoeus::Request
[ "Returns", "a", "list", "of", "interesting", "storms", "happening", "right", "now", "." ]
8cee1e294f3b0f465545d61f68cf74afd76159ce
https://github.com/darkskyapp/darksky-ruby/blob/8cee1e294f3b0f465545d61f68cf74afd76159ce/lib/darksky/api.rb#L54-L57
train