id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
21,800
ryanong/spy
lib/spy/subroutine.rb
Spy.Subroutine.invoke
def invoke(object, args, block, called_from) check_arity!(args.size) if base_object.is_a? Class result = if @plan check_for_too_many_arguments!(@plan) @plan.call(object, *args, &block) end else result = if @plan check_for_too_many_arguments!(@plan) @plan.call(*args, &block) end end ensure calls << CallLog.new(object, called_from, args, block, result) end
ruby
def invoke(object, args, block, called_from) check_arity!(args.size) if base_object.is_a? Class result = if @plan check_for_too_many_arguments!(@plan) @plan.call(object, *args, &block) end else result = if @plan check_for_too_many_arguments!(@plan) @plan.call(*args, &block) end end ensure calls << CallLog.new(object, called_from, args, block, result) end
[ "def", "invoke", "(", "object", ",", "args", ",", "block", ",", "called_from", ")", "check_arity!", "(", "args", ".", "size", ")", "if", "base_object", ".", "is_a?", "Class", "result", "=", "if", "@plan", "check_for_too_many_arguments!", "(", "@plan", ")", "@plan", ".", "call", "(", "object", ",", "args", ",", "block", ")", "end", "else", "result", "=", "if", "@plan", "check_for_too_many_arguments!", "(", "@plan", ")", "@plan", ".", "call", "(", "args", ",", "block", ")", "end", "end", "ensure", "calls", "<<", "CallLog", ".", "new", "(", "object", ",", "called_from", ",", "args", ",", "block", ",", "result", ")", "end" ]
invoke that the method has been called. You really shouldn't use this method.
[ "invoke", "that", "the", "method", "has", "been", "called", ".", "You", "really", "shouldn", "t", "use", "this", "method", "." ]
54ec54b604333c8991ab8d6df0a96fe57364f65c
https://github.com/ryanong/spy/blob/54ec54b604333c8991ab8d6df0a96fe57364f65c/lib/spy/subroutine.rb#L226-L242
21,801
ryanong/spy
lib/spy/agency.rb
Spy.Agency.recruit
def recruit(spy) raise AlreadyStubbedError if @spies[spy.object_id] check_spy!(spy) @spies[spy.object_id] = spy end
ruby
def recruit(spy) raise AlreadyStubbedError if @spies[spy.object_id] check_spy!(spy) @spies[spy.object_id] = spy end
[ "def", "recruit", "(", "spy", ")", "raise", "AlreadyStubbedError", "if", "@spies", "[", "spy", ".", "object_id", "]", "check_spy!", "(", "spy", ")", "@spies", "[", "spy", ".", "object_id", "]", "=", "spy", "end" ]
Record that a spy was initialized and hooked @param spy [Subroutine, Constant, Double] @return [spy]
[ "Record", "that", "a", "spy", "was", "initialized", "and", "hooked" ]
54ec54b604333c8991ab8d6df0a96fe57364f65c
https://github.com/ryanong/spy/blob/54ec54b604333c8991ab8d6df0a96fe57364f65c/lib/spy/agency.rb#L23-L27
21,802
ryanong/spy
lib/spy/constant.rb
Spy.Constant.hook
def hook(opts = {}) opts[:force] ||= false Nest.fetch(base_module).add(self) Agency.instance.recruit(self) @previously_defined = currently_defined? if previously_defined? || !opts[:force] @original_value = base_module.const_get(constant_name, false) end and_return(@new_value) self end
ruby
def hook(opts = {}) opts[:force] ||= false Nest.fetch(base_module).add(self) Agency.instance.recruit(self) @previously_defined = currently_defined? if previously_defined? || !opts[:force] @original_value = base_module.const_get(constant_name, false) end and_return(@new_value) self end
[ "def", "hook", "(", "opts", "=", "{", "}", ")", "opts", "[", ":force", "]", "||=", "false", "Nest", ".", "fetch", "(", "base_module", ")", ".", "add", "(", "self", ")", "Agency", ".", "instance", ".", "recruit", "(", "self", ")", "@previously_defined", "=", "currently_defined?", "if", "previously_defined?", "||", "!", "opts", "[", ":force", "]", "@original_value", "=", "base_module", ".", "const_get", "(", "constant_name", ",", "false", ")", "end", "and_return", "(", "@new_value", ")", "self", "end" ]
stashes the original constant then overwrites it with nil @param opts [Hash{force => false}] set :force => true if you want it to ignore if the constant exists @return [self]
[ "stashes", "the", "original", "constant", "then", "overwrites", "it", "with", "nil" ]
54ec54b604333c8991ab8d6df0a96fe57364f65c
https://github.com/ryanong/spy/blob/54ec54b604333c8991ab8d6df0a96fe57364f65c/lib/spy/constant.rb#L33-L44
21,803
ryanong/spy
lib/spy/constant.rb
Spy.Constant.unhook
def unhook Nest.get(base_module).remove(self) Agency.instance.retire(self) and_return(@original_value) if previously_defined? @original_value = @previously_defined = nil self end
ruby
def unhook Nest.get(base_module).remove(self) Agency.instance.retire(self) and_return(@original_value) if previously_defined? @original_value = @previously_defined = nil self end
[ "def", "unhook", "Nest", ".", "get", "(", "base_module", ")", ".", "remove", "(", "self", ")", "Agency", ".", "instance", ".", "retire", "(", "self", ")", "and_return", "(", "@original_value", ")", "if", "previously_defined?", "@original_value", "=", "@previously_defined", "=", "nil", "self", "end" ]
restores the original value of the constant or unsets it if it was unset @return [self]
[ "restores", "the", "original", "value", "of", "the", "constant", "or", "unsets", "it", "if", "it", "was", "unset" ]
54ec54b604333c8991ab8d6df0a96fe57364f65c
https://github.com/ryanong/spy/blob/54ec54b604333c8991ab8d6df0a96fe57364f65c/lib/spy/constant.rb#L48-L56
21,804
ryanong/spy
lib/spy/mock.rb
Spy.Mock.method
def method(method_name) new_method = super parameters = new_method.parameters if parameters.size >= 1 && parameters.last.last == :mock_method self.class.instance_method(method_name).bind(self) else new_method end end
ruby
def method(method_name) new_method = super parameters = new_method.parameters if parameters.size >= 1 && parameters.last.last == :mock_method self.class.instance_method(method_name).bind(self) else new_method end end
[ "def", "method", "(", "method_name", ")", "new_method", "=", "super", "parameters", "=", "new_method", ".", "parameters", "if", "parameters", ".", "size", ">=", "1", "&&", "parameters", ".", "last", ".", "last", "==", ":mock_method", "self", ".", "class", ".", "instance_method", "(", "method_name", ")", ".", "bind", "(", "self", ")", "else", "new_method", "end", "end" ]
returns the original class method if the current method is a mock_method @param method_name [Symbol, String] @return [Method]
[ "returns", "the", "original", "class", "method", "if", "the", "current", "method", "is", "a", "mock_method" ]
54ec54b604333c8991ab8d6df0a96fe57364f65c
https://github.com/ryanong/spy/blob/54ec54b604333c8991ab8d6df0a96fe57364f65c/lib/spy/mock.rb#L26-L34
21,805
cheezy/te3270
lib/te3270/accessors.rb
TE3270.Accessors.text_field
def text_field(name, row, column, length, editable=true) define_method(name) do platform.get_string(row, column, length) end define_method("#{name}=") do |value| platform.put_string(value, row, column) end if editable end
ruby
def text_field(name, row, column, length, editable=true) define_method(name) do platform.get_string(row, column, length) end define_method("#{name}=") do |value| platform.put_string(value, row, column) end if editable end
[ "def", "text_field", "(", "name", ",", "row", ",", "column", ",", "length", ",", "editable", "=", "true", ")", "define_method", "(", "name", ")", "do", "platform", ".", "get_string", "(", "row", ",", "column", ",", "length", ")", "end", "define_method", "(", "\"#{name}=\"", ")", "do", "|", "value", "|", "platform", ".", "put_string", "(", "value", ",", "row", ",", "column", ")", "end", "if", "editable", "end" ]
adds two methods to the screen object - one to set text in a text field, another to retrieve text from a text field. @example text_field(:first_name, 23,45,20) # will generate 'first_name', 'first_name=' method @param [String] the name used for the generated methods @param [FixedNum] row number of the location @param [FixedNum] column number of the location @param [FixedNum] length of the text field @param [true|false] editable is by default true
[ "adds", "two", "methods", "to", "the", "screen", "object", "-", "one", "to", "set", "text", "in", "a", "text", "field", "another", "to", "retrieve", "text", "from", "a", "text", "field", "." ]
35d4d3a83b67fff757645c381844577717b7c8be
https://github.com/cheezy/te3270/blob/35d4d3a83b67fff757645c381844577717b7c8be/lib/te3270/accessors.rb#L19-L27
21,806
cheezy/te3270
lib/te3270/screen_populator.rb
TE3270.ScreenPopulator.populate_screen_with
def populate_screen_with(hsh) hsh.each do |key, value| self.send("#{key}=", value) if self.respond_to? "#{key}=".to_sym end end
ruby
def populate_screen_with(hsh) hsh.each do |key, value| self.send("#{key}=", value) if self.respond_to? "#{key}=".to_sym end end
[ "def", "populate_screen_with", "(", "hsh", ")", "hsh", ".", "each", "do", "|", "key", ",", "value", "|", "self", ".", "send", "(", "\"#{key}=\"", ",", "value", ")", "if", "self", ".", "respond_to?", "\"#{key}=\"", ".", "to_sym", "end", "end" ]
This method will populate all matched screen text fields from the Hash passed as an argument. The way it find an element is by matching the Hash key to the name you provided when declaring the text field on your screen. @example class ExampleScreen include TE3270 text_field(:username, 1, 2, 20) end ... @emulator = TE3270::emulator_for :quick3270 example_screen = ExampleScreen.new(@emulator) example_screen.populate_screen_with :username => 'a name' @param [Hash] hsh the data to use to populate this screen.
[ "This", "method", "will", "populate", "all", "matched", "screen", "text", "fields", "from", "the", "Hash", "passed", "as", "an", "argument", ".", "The", "way", "it", "find", "an", "element", "is", "by", "matching", "the", "Hash", "key", "to", "the", "name", "you", "provided", "when", "declaring", "the", "text", "field", "on", "your", "screen", "." ]
35d4d3a83b67fff757645c381844577717b7c8be
https://github.com/cheezy/te3270/blob/35d4d3a83b67fff757645c381844577717b7c8be/lib/te3270/screen_populator.rb#L26-L30
21,807
ucnv/aviglitch
lib/aviglitch/frames.rb
AviGlitch.Frames.size_of
def size_of frame_type detection = "is_#{frame_type.to_s.sub(/frames$/, 'frame')}?" @meta.select { |m| Frame.new(nil, m[:id], m[:flag]).send detection }.size end
ruby
def size_of frame_type detection = "is_#{frame_type.to_s.sub(/frames$/, 'frame')}?" @meta.select { |m| Frame.new(nil, m[:id], m[:flag]).send detection }.size end
[ "def", "size_of", "frame_type", "detection", "=", "\"is_#{frame_type.to_s.sub(/frames$/, 'frame')}?\"", "@meta", ".", "select", "{", "|", "m", "|", "Frame", ".", "new", "(", "nil", ",", "m", "[", ":id", "]", ",", "m", "[", ":flag", "]", ")", ".", "send", "detection", "}", ".", "size", "end" ]
Returns the number of the specific +frame_type+.
[ "Returns", "the", "number", "of", "the", "specific", "+", "frame_type", "+", "." ]
0a1def05827a70a792092e09f388066edbc570a8
https://github.com/ucnv/aviglitch/blob/0a1def05827a70a792092e09f388066edbc570a8/lib/aviglitch/frames.rb#L84-L89
21,808
ucnv/aviglitch
lib/aviglitch/frames.rb
AviGlitch.Frames.concat
def concat other_frames raise TypeError unless other_frames.kind_of?(Frames) # data this_data = Tempfile.new 'this', binmode: true self.frames_data_as_io this_data other_data = Tempfile.new 'other', binmode: true other_frames.frames_data_as_io other_data this_size = this_data.size other_data.rewind while d = other_data.read(BUFFER_SIZE) do this_data.print d end other_data.close! # meta other_meta = other_frames.meta.collect do |m| x = m.dup x[:offset] += this_size x end @meta.concat other_meta # close overwrite this_data this_data.close! self end
ruby
def concat other_frames raise TypeError unless other_frames.kind_of?(Frames) # data this_data = Tempfile.new 'this', binmode: true self.frames_data_as_io this_data other_data = Tempfile.new 'other', binmode: true other_frames.frames_data_as_io other_data this_size = this_data.size other_data.rewind while d = other_data.read(BUFFER_SIZE) do this_data.print d end other_data.close! # meta other_meta = other_frames.meta.collect do |m| x = m.dup x[:offset] += this_size x end @meta.concat other_meta # close overwrite this_data this_data.close! self end
[ "def", "concat", "other_frames", "raise", "TypeError", "unless", "other_frames", ".", "kind_of?", "(", "Frames", ")", "# data", "this_data", "=", "Tempfile", ".", "new", "'this'", ",", "binmode", ":", "true", "self", ".", "frames_data_as_io", "this_data", "other_data", "=", "Tempfile", ".", "new", "'other'", ",", "binmode", ":", "true", "other_frames", ".", "frames_data_as_io", "other_data", "this_size", "=", "this_data", ".", "size", "other_data", ".", "rewind", "while", "d", "=", "other_data", ".", "read", "(", "BUFFER_SIZE", ")", "do", "this_data", ".", "print", "d", "end", "other_data", ".", "close!", "# meta", "other_meta", "=", "other_frames", ".", "meta", ".", "collect", "do", "|", "m", "|", "x", "=", "m", ".", "dup", "x", "[", ":offset", "]", "+=", "this_size", "x", "end", "@meta", ".", "concat", "other_meta", "# close", "overwrite", "this_data", "this_data", ".", "close!", "self", "end" ]
Appends the frames in the other Frames into the tail of self. It is destructive like Array does.
[ "Appends", "the", "frames", "in", "the", "other", "Frames", "into", "the", "tail", "of", "self", ".", "It", "is", "destructive", "like", "Array", "does", "." ]
0a1def05827a70a792092e09f388066edbc570a8
https://github.com/ucnv/aviglitch/blob/0a1def05827a70a792092e09f388066edbc570a8/lib/aviglitch/frames.rb#L163-L187
21,809
ucnv/aviglitch
lib/aviglitch/frames.rb
AviGlitch.Frames.*
def * times result = self.slice 0, 0 frames = self.slice 0..-1 times.times do result.concat frames end result end
ruby
def * times result = self.slice 0, 0 frames = self.slice 0..-1 times.times do result.concat frames end result end
[ "def", "*", "times", "result", "=", "self", ".", "slice", "0", ",", "0", "frames", "=", "self", ".", "slice", "0", "..", "-", "1", "times", ".", "times", "do", "result", ".", "concat", "frames", "end", "result", "end" ]
Returns the new Frames as a +times+ times repeated concatenation of the original Frames.
[ "Returns", "the", "new", "Frames", "as", "a", "+", "times", "+", "times", "repeated", "concatenation", "of", "the", "original", "Frames", "." ]
0a1def05827a70a792092e09f388066edbc570a8
https://github.com/ucnv/aviglitch/blob/0a1def05827a70a792092e09f388066edbc570a8/lib/aviglitch/frames.rb#L200-L207
21,810
ucnv/aviglitch
lib/aviglitch/frames.rb
AviGlitch.Frames.slice
def slice *args b, l = get_beginning_and_length *args if l.nil? self.at b else e = b + l - 1 r = self.to_avi r.frames.each_with_index do |f, i| unless i >= b && i <= e f.data = nil end end r.frames end end
ruby
def slice *args b, l = get_beginning_and_length *args if l.nil? self.at b else e = b + l - 1 r = self.to_avi r.frames.each_with_index do |f, i| unless i >= b && i <= e f.data = nil end end r.frames end end
[ "def", "slice", "*", "args", "b", ",", "l", "=", "get_beginning_and_length", "args", "if", "l", ".", "nil?", "self", ".", "at", "b", "else", "e", "=", "b", "+", "l", "-", "1", "r", "=", "self", ".", "to_avi", "r", ".", "frames", ".", "each_with_index", "do", "|", "f", ",", "i", "|", "unless", "i", ">=", "b", "&&", "i", "<=", "e", "f", ".", "data", "=", "nil", "end", "end", "r", ".", "frames", "end", "end" ]
Returns the Frame object at the given index or returns new Frames object that sliced with the given index and length or with the Range. Just like Array.
[ "Returns", "the", "Frame", "object", "at", "the", "given", "index", "or", "returns", "new", "Frames", "object", "that", "sliced", "with", "the", "given", "index", "and", "length", "or", "with", "the", "Range", ".", "Just", "like", "Array", "." ]
0a1def05827a70a792092e09f388066edbc570a8
https://github.com/ucnv/aviglitch/blob/0a1def05827a70a792092e09f388066edbc570a8/lib/aviglitch/frames.rb#L214-L228
21,811
ucnv/aviglitch
lib/aviglitch/frames.rb
AviGlitch.Frames.at
def at n m = @meta[n] return nil if m.nil? @io.pos = @pos_of_movi + m[:offset] + 8 frame = Frame.new(@io.read(m[:size]), m[:id], m[:flag]) @io.rewind frame end
ruby
def at n m = @meta[n] return nil if m.nil? @io.pos = @pos_of_movi + m[:offset] + 8 frame = Frame.new(@io.read(m[:size]), m[:id], m[:flag]) @io.rewind frame end
[ "def", "at", "n", "m", "=", "@meta", "[", "n", "]", "return", "nil", "if", "m", ".", "nil?", "@io", ".", "pos", "=", "@pos_of_movi", "+", "m", "[", ":offset", "]", "+", "8", "frame", "=", "Frame", ".", "new", "(", "@io", ".", "read", "(", "m", "[", ":size", "]", ")", ",", "m", "[", ":id", "]", ",", "m", "[", ":flag", "]", ")", "@io", ".", "rewind", "frame", "end" ]
Returns one Frame object at the given index.
[ "Returns", "one", "Frame", "object", "at", "the", "given", "index", "." ]
0a1def05827a70a792092e09f388066edbc570a8
https://github.com/ucnv/aviglitch/blob/0a1def05827a70a792092e09f388066edbc570a8/lib/aviglitch/frames.rb#L273-L280
21,812
ucnv/aviglitch
lib/aviglitch/frames.rb
AviGlitch.Frames.push
def push frame raise TypeError unless frame.kind_of? Frame # data this_data = Tempfile.new 'this', binmode: true self.frames_data_as_io this_data this_size = this_data.size this_data.print frame.id this_data.print [frame.data.size].pack('V') this_data.print frame.data this_data.print "\000" if frame.data.size % 2 == 1 # meta @meta << { :id => frame.id, :flag => frame.flag, :offset => this_size + 4, # 4 for 'movi' :size => frame.data.size, } # close overwrite this_data this_data.close! self end
ruby
def push frame raise TypeError unless frame.kind_of? Frame # data this_data = Tempfile.new 'this', binmode: true self.frames_data_as_io this_data this_size = this_data.size this_data.print frame.id this_data.print [frame.data.size].pack('V') this_data.print frame.data this_data.print "\000" if frame.data.size % 2 == 1 # meta @meta << { :id => frame.id, :flag => frame.flag, :offset => this_size + 4, # 4 for 'movi' :size => frame.data.size, } # close overwrite this_data this_data.close! self end
[ "def", "push", "frame", "raise", "TypeError", "unless", "frame", ".", "kind_of?", "Frame", "# data", "this_data", "=", "Tempfile", ".", "new", "'this'", ",", "binmode", ":", "true", "self", ".", "frames_data_as_io", "this_data", "this_size", "=", "this_data", ".", "size", "this_data", ".", "print", "frame", ".", "id", "this_data", ".", "print", "[", "frame", ".", "data", ".", "size", "]", ".", "pack", "(", "'V'", ")", "this_data", ".", "print", "frame", ".", "data", "this_data", ".", "print", "\"\\000\"", "if", "frame", ".", "data", ".", "size", "%", "2", "==", "1", "# meta", "@meta", "<<", "{", ":id", "=>", "frame", ".", "id", ",", ":flag", "=>", "frame", ".", "flag", ",", ":offset", "=>", "this_size", "+", "4", ",", "# 4 for 'movi'", ":size", "=>", "frame", ".", "data", ".", "size", ",", "}", "# close", "overwrite", "this_data", "this_data", ".", "close!", "self", "end" ]
Appends the given Frame into the tail of self.
[ "Appends", "the", "given", "Frame", "into", "the", "tail", "of", "self", "." ]
0a1def05827a70a792092e09f388066edbc570a8
https://github.com/ucnv/aviglitch/blob/0a1def05827a70a792092e09f388066edbc570a8/lib/aviglitch/frames.rb#L296-L317
21,813
ucnv/aviglitch
lib/aviglitch/frames.rb
AviGlitch.Frames.insert
def insert n, *args new_frames = self.slice(0, n) args.each do |f| new_frames.push f end new_frames.concat self.slice(n..-1) self.clear self.concat new_frames self end
ruby
def insert n, *args new_frames = self.slice(0, n) args.each do |f| new_frames.push f end new_frames.concat self.slice(n..-1) self.clear self.concat new_frames self end
[ "def", "insert", "n", ",", "*", "args", "new_frames", "=", "self", ".", "slice", "(", "0", ",", "n", ")", "args", ".", "each", "do", "|", "f", "|", "new_frames", ".", "push", "f", "end", "new_frames", ".", "concat", "self", ".", "slice", "(", "n", "..", "-", "1", ")", "self", ".", "clear", "self", ".", "concat", "new_frames", "self", "end" ]
Inserts the given Frame objects into the given index.
[ "Inserts", "the", "given", "Frame", "objects", "into", "the", "given", "index", "." ]
0a1def05827a70a792092e09f388066edbc570a8
https://github.com/ucnv/aviglitch/blob/0a1def05827a70a792092e09f388066edbc570a8/lib/aviglitch/frames.rb#L325-L335
21,814
ucnv/aviglitch
lib/aviglitch/frames.rb
AviGlitch.Frames.mutate_keyframes_into_deltaframes!
def mutate_keyframes_into_deltaframes! range = nil range = 0..self.size if range.nil? self.each_with_index do |frame, i| if range.include? i frame.flag = 0 if frame.is_keyframe? end end self end
ruby
def mutate_keyframes_into_deltaframes! range = nil range = 0..self.size if range.nil? self.each_with_index do |frame, i| if range.include? i frame.flag = 0 if frame.is_keyframe? end end self end
[ "def", "mutate_keyframes_into_deltaframes!", "range", "=", "nil", "range", "=", "0", "..", "self", ".", "size", "if", "range", ".", "nil?", "self", ".", "each_with_index", "do", "|", "frame", ",", "i", "|", "if", "range", ".", "include?", "i", "frame", ".", "flag", "=", "0", "if", "frame", ".", "is_keyframe?", "end", "end", "self", "end" ]
Mutates keyframes into deltaframes at given range, or all.
[ "Mutates", "keyframes", "into", "deltaframes", "at", "given", "range", "or", "all", "." ]
0a1def05827a70a792092e09f388066edbc570a8
https://github.com/ucnv/aviglitch/blob/0a1def05827a70a792092e09f388066edbc570a8/lib/aviglitch/frames.rb#L345-L353
21,815
ucnv/aviglitch
lib/aviglitch/base.rb
AviGlitch.Base.glitch
def glitch target = :all, &block # :yield: data if block_given? @frames.each do |frame| if valid_target? target, frame frame.data = yield frame.data end end self else self.enum_for :glitch, target end end
ruby
def glitch target = :all, &block # :yield: data if block_given? @frames.each do |frame| if valid_target? target, frame frame.data = yield frame.data end end self else self.enum_for :glitch, target end end
[ "def", "glitch", "target", "=", ":all", ",", "&", "block", "# :yield: data", "if", "block_given?", "@frames", ".", "each", "do", "|", "frame", "|", "if", "valid_target?", "target", ",", "frame", "frame", ".", "data", "=", "yield", "frame", ".", "data", "end", "end", "self", "else", "self", ".", "enum_for", ":glitch", ",", "target", "end", "end" ]
Glitches each frame data. It is a convenient method to iterate each frame. The argument +target+ takes symbols listed below: [<tt>:keyframe</tt> or <tt>:iframe</tt>] select video key frames (aka I-frame) [<tt>:deltaframe</tt> or <tt>:pframe</tt>] select video delta frames (difference frames) [<tt>:videoframe</tt>] select both of keyframe and deltaframe [<tt>:audioframe</tt>] select audio frames [<tt>:all</tt>] select all frames It also requires a block. In the block, you take the frame data as a String parameter. To modify the data, simply return a modified data. Without a block it returns Enumerator, with a block it returns +self+.
[ "Glitches", "each", "frame", "data", ".", "It", "is", "a", "convenient", "method", "to", "iterate", "each", "frame", "." ]
0a1def05827a70a792092e09f388066edbc570a8
https://github.com/ucnv/aviglitch/blob/0a1def05827a70a792092e09f388066edbc570a8/lib/aviglitch/base.rb#L62-L73
21,816
ucnv/aviglitch
lib/aviglitch/base.rb
AviGlitch.Base.glitch_with_index
def glitch_with_index target = :all, &block # :yield: data, index if block_given? self.glitch(target).with_index do |x, i| yield x, i end self else self.glitch target end end
ruby
def glitch_with_index target = :all, &block # :yield: data, index if block_given? self.glitch(target).with_index do |x, i| yield x, i end self else self.glitch target end end
[ "def", "glitch_with_index", "target", "=", ":all", ",", "&", "block", "# :yield: data, index", "if", "block_given?", "self", ".", "glitch", "(", "target", ")", ".", "with_index", "do", "|", "x", ",", "i", "|", "yield", "x", ",", "i", "end", "self", "else", "self", ".", "glitch", "target", "end", "end" ]
Do glitch with index.
[ "Do", "glitch", "with", "index", "." ]
0a1def05827a70a792092e09f388066edbc570a8
https://github.com/ucnv/aviglitch/blob/0a1def05827a70a792092e09f388066edbc570a8/lib/aviglitch/base.rb#L77-L86
21,817
ucnv/aviglitch
lib/aviglitch/base.rb
AviGlitch.Base.has_keyframe?
def has_keyframe? result = false self.frames.each do |f| if f.is_keyframe? result = true break end end result end
ruby
def has_keyframe? result = false self.frames.each do |f| if f.is_keyframe? result = true break end end result end
[ "def", "has_keyframe?", "result", "=", "false", "self", ".", "frames", ".", "each", "do", "|", "f", "|", "if", "f", ".", "is_keyframe?", "result", "=", "true", "break", "end", "end", "result", "end" ]
Check if it has keyframes.
[ "Check", "if", "it", "has", "keyframes", "." ]
0a1def05827a70a792092e09f388066edbc570a8
https://github.com/ucnv/aviglitch/blob/0a1def05827a70a792092e09f388066edbc570a8/lib/aviglitch/base.rb#L98-L107
21,818
ucnv/aviglitch
lib/aviglitch/base.rb
AviGlitch.Base.frames=
def frames= other raise TypeError unless other.kind_of?(Frames) @frames.clear @frames.concat other end
ruby
def frames= other raise TypeError unless other.kind_of?(Frames) @frames.clear @frames.concat other end
[ "def", "frames", "=", "other", "raise", "TypeError", "unless", "other", ".", "kind_of?", "(", "Frames", ")", "@frames", ".", "clear", "@frames", ".", "concat", "other", "end" ]
Swaps the frames with other Frames data.
[ "Swaps", "the", "frames", "with", "other", "Frames", "data", "." ]
0a1def05827a70a792092e09f388066edbc570a8
https://github.com/ucnv/aviglitch/blob/0a1def05827a70a792092e09f388066edbc570a8/lib/aviglitch/base.rb#L121-L125
21,819
piotrmurach/tty-file
lib/tty/file.rb
TTY.File.binary?
def binary?(relative_path) bytes = ::File.new(relative_path).size bytes = 2**12 if bytes > 2**12 buffer = ::File.read(relative_path, bytes, 0) || '' buffer = buffer.force_encoding(Encoding.default_external) begin return buffer !~ /\A[\s[[:print:]]]*\z/m rescue ArgumentError => error return true if error.message =~ /invalid byte sequence/ raise end end
ruby
def binary?(relative_path) bytes = ::File.new(relative_path).size bytes = 2**12 if bytes > 2**12 buffer = ::File.read(relative_path, bytes, 0) || '' buffer = buffer.force_encoding(Encoding.default_external) begin return buffer !~ /\A[\s[[:print:]]]*\z/m rescue ArgumentError => error return true if error.message =~ /invalid byte sequence/ raise end end
[ "def", "binary?", "(", "relative_path", ")", "bytes", "=", "::", "File", ".", "new", "(", "relative_path", ")", ".", "size", "bytes", "=", "2", "**", "12", "if", "bytes", ">", "2", "**", "12", "buffer", "=", "::", "File", ".", "read", "(", "relative_path", ",", "bytes", ",", "0", ")", "||", "''", "buffer", "=", "buffer", ".", "force_encoding", "(", "Encoding", ".", "default_external", ")", "begin", "return", "buffer", "!~", "/", "\\A", "\\s", "\\z", "/m", "rescue", "ArgumentError", "=>", "error", "return", "true", "if", "error", ".", "message", "=~", "/", "/", "raise", "end", "end" ]
Check if file is binary @param [String, Pathname] relative_path the path to file to check @example binary?('Gemfile') # => false @example binary?('image.jpg') # => true @return [Boolean] Returns `true` if the file is binary, `false` otherwise @api public
[ "Check", "if", "file", "is", "binary" ]
575a78a654d74fad2cb5abe06d798ee46293ba0a
https://github.com/piotrmurach/tty-file/blob/575a78a654d74fad2cb5abe06d798ee46293ba0a/lib/tty/file.rb#L53-L64
21,820
piotrmurach/tty-file
lib/tty/file.rb
TTY.File.checksum_file
def checksum_file(source, *args, **options) mode = args.size.zero? ? 'sha256' : args.pop digester = DigestFile.new(source, mode, options) digester.call unless options[:noop] end
ruby
def checksum_file(source, *args, **options) mode = args.size.zero? ? 'sha256' : args.pop digester = DigestFile.new(source, mode, options) digester.call unless options[:noop] end
[ "def", "checksum_file", "(", "source", ",", "*", "args", ",", "**", "options", ")", "mode", "=", "args", ".", "size", ".", "zero?", "?", "'sha256'", ":", "args", ".", "pop", "digester", "=", "DigestFile", ".", "new", "(", "source", ",", "mode", ",", "options", ")", "digester", ".", "call", "unless", "options", "[", ":noop", "]", "end" ]
Create checksum for a file, io or string objects @param [File, IO, String, Pathname] source the source to generate checksum for @param [String] mode @param [Hash[Symbol]] options @option options [String] :noop No operation @example checksum_file('/path/to/file') @example checksum_file('Some string content', 'md5') @return [String] the generated hex value @api public
[ "Create", "checksum", "for", "a", "file", "io", "or", "string", "objects" ]
575a78a654d74fad2cb5abe06d798ee46293ba0a
https://github.com/piotrmurach/tty-file/blob/575a78a654d74fad2cb5abe06d798ee46293ba0a/lib/tty/file.rb#L86-L90
21,821
piotrmurach/tty-file
lib/tty/file.rb
TTY.File.chmod
def chmod(relative_path, permissions, **options) mode = ::File.lstat(relative_path).mode if permissions.to_s =~ /\d+/ mode = permissions else permissions.scan(/[ugoa][+-=][rwx]+/) do |setting| who, action = setting[0], setting[1] setting[2..setting.size].each_byte do |perm| mask = const_get("#{who.upcase}_#{perm.chr.upcase}") (action == '+') ? mode |= mask : mode ^= mask end end end log_status(:chmod, relative_path, options.fetch(:verbose, true), options.fetch(:color, :green)) ::FileUtils.chmod_R(mode, relative_path) unless options[:noop] end
ruby
def chmod(relative_path, permissions, **options) mode = ::File.lstat(relative_path).mode if permissions.to_s =~ /\d+/ mode = permissions else permissions.scan(/[ugoa][+-=][rwx]+/) do |setting| who, action = setting[0], setting[1] setting[2..setting.size].each_byte do |perm| mask = const_get("#{who.upcase}_#{perm.chr.upcase}") (action == '+') ? mode |= mask : mode ^= mask end end end log_status(:chmod, relative_path, options.fetch(:verbose, true), options.fetch(:color, :green)) ::FileUtils.chmod_R(mode, relative_path) unless options[:noop] end
[ "def", "chmod", "(", "relative_path", ",", "permissions", ",", "**", "options", ")", "mode", "=", "::", "File", ".", "lstat", "(", "relative_path", ")", ".", "mode", "if", "permissions", ".", "to_s", "=~", "/", "\\d", "/", "mode", "=", "permissions", "else", "permissions", ".", "scan", "(", "/", "/", ")", "do", "|", "setting", "|", "who", ",", "action", "=", "setting", "[", "0", "]", ",", "setting", "[", "1", "]", "setting", "[", "2", "..", "setting", ".", "size", "]", ".", "each_byte", "do", "|", "perm", "|", "mask", "=", "const_get", "(", "\"#{who.upcase}_#{perm.chr.upcase}\"", ")", "(", "action", "==", "'+'", ")", "?", "mode", "|=", "mask", ":", "mode", "^=", "mask", "end", "end", "end", "log_status", "(", ":chmod", ",", "relative_path", ",", "options", ".", "fetch", "(", ":verbose", ",", "true", ")", ",", "options", ".", "fetch", "(", ":color", ",", ":green", ")", ")", "::", "FileUtils", ".", "chmod_R", "(", "mode", ",", "relative_path", ")", "unless", "options", "[", ":noop", "]", "end" ]
Change file permissions @param [String, Pathname] relative_path @param [Integer,String] permisssions @param [Hash[Symbol]] options @option options [Symbol] :noop @option options [Symbol] :verbose @option options [Symbol] :force @example chmod('Gemfile', 0755) @example chmod('Gemilfe', TTY::File::U_R | TTY::File::U_W) @example chmod('Gemfile', 'u+x,g+x') @api public
[ "Change", "file", "permissions" ]
575a78a654d74fad2cb5abe06d798ee46293ba0a
https://github.com/piotrmurach/tty-file/blob/575a78a654d74fad2cb5abe06d798ee46293ba0a/lib/tty/file.rb#L112-L128
21,822
piotrmurach/tty-file
lib/tty/file.rb
TTY.File.create_directory
def create_directory(destination, *args, **options) parent = args.size.nonzero? ? args.pop : nil if destination.is_a?(String) || destination.is_a?(Pathname) destination = { destination.to_s => [] } end destination.each do |dir, files| path = parent.nil? ? dir : ::File.join(parent, dir) unless ::File.exist?(path) ::FileUtils.mkdir_p(path) log_status(:create, path, options.fetch(:verbose, true), options.fetch(:color, :green)) end files.each do |filename, contents| if filename.respond_to?(:each_pair) create_directory(filename, path, options) else create_file(::File.join(path, filename), contents, options) end end end end
ruby
def create_directory(destination, *args, **options) parent = args.size.nonzero? ? args.pop : nil if destination.is_a?(String) || destination.is_a?(Pathname) destination = { destination.to_s => [] } end destination.each do |dir, files| path = parent.nil? ? dir : ::File.join(parent, dir) unless ::File.exist?(path) ::FileUtils.mkdir_p(path) log_status(:create, path, options.fetch(:verbose, true), options.fetch(:color, :green)) end files.each do |filename, contents| if filename.respond_to?(:each_pair) create_directory(filename, path, options) else create_file(::File.join(path, filename), contents, options) end end end end
[ "def", "create_directory", "(", "destination", ",", "*", "args", ",", "**", "options", ")", "parent", "=", "args", ".", "size", ".", "nonzero?", "?", "args", ".", "pop", ":", "nil", "if", "destination", ".", "is_a?", "(", "String", ")", "||", "destination", ".", "is_a?", "(", "Pathname", ")", "destination", "=", "{", "destination", ".", "to_s", "=>", "[", "]", "}", "end", "destination", ".", "each", "do", "|", "dir", ",", "files", "|", "path", "=", "parent", ".", "nil?", "?", "dir", ":", "::", "File", ".", "join", "(", "parent", ",", "dir", ")", "unless", "::", "File", ".", "exist?", "(", "path", ")", "::", "FileUtils", ".", "mkdir_p", "(", "path", ")", "log_status", "(", ":create", ",", "path", ",", "options", ".", "fetch", "(", ":verbose", ",", "true", ")", ",", "options", ".", "fetch", "(", ":color", ",", ":green", ")", ")", "end", "files", ".", "each", "do", "|", "filename", ",", "contents", "|", "if", "filename", ".", "respond_to?", "(", ":each_pair", ")", "create_directory", "(", "filename", ",", "path", ",", "options", ")", "else", "create_file", "(", "::", "File", ".", "join", "(", "path", ",", "filename", ")", ",", "contents", ",", "options", ")", "end", "end", "end", "end" ]
Create directory structure @param [String, Pathname, Hash] destination the path or data structure describing directory tree @example create_directory('/path/to/dir') @example tree = 'app' => [ 'README.md', ['Gemfile', "gem 'tty-file'"], 'lib' => [ 'cli.rb', ['file_utils.rb', "require 'tty-file'"] ] 'spec' => [] ] create_directory(tree) @return [void] @api public
[ "Create", "directory", "structure" ]
575a78a654d74fad2cb5abe06d798ee46293ba0a
https://github.com/piotrmurach/tty-file/blob/575a78a654d74fad2cb5abe06d798ee46293ba0a/lib/tty/file.rb#L156-L178
21,823
piotrmurach/tty-file
lib/tty/file.rb
TTY.File.create_file
def create_file(relative_path, *args, **options, &block) relative_path = relative_path.to_s content = block_given? ? block[] : args.join CreateFile.new(self, relative_path, content, options).call end
ruby
def create_file(relative_path, *args, **options, &block) relative_path = relative_path.to_s content = block_given? ? block[] : args.join CreateFile.new(self, relative_path, content, options).call end
[ "def", "create_file", "(", "relative_path", ",", "*", "args", ",", "**", "options", ",", "&", "block", ")", "relative_path", "=", "relative_path", ".", "to_s", "content", "=", "block_given?", "?", "block", "[", "]", ":", "args", ".", "join", "CreateFile", ".", "new", "(", "self", ",", "relative_path", ",", "content", ",", "options", ")", ".", "call", "end" ]
Create new file if doesn't exist @param [String, Pathname] relative_path @param [String|nil] content the content to add to file @param [Hash] options @option options [Symbol] :force forces ovewrite if conflict present @example create_file('doc/README.md', '# Title header') @example create_file 'doc/README.md' do '# Title Header' end @api public
[ "Create", "new", "file", "if", "doesn", "t", "exist" ]
575a78a654d74fad2cb5abe06d798ee46293ba0a
https://github.com/piotrmurach/tty-file/blob/575a78a654d74fad2cb5abe06d798ee46293ba0a/lib/tty/file.rb#L202-L207
21,824
piotrmurach/tty-file
lib/tty/file.rb
TTY.File.copy_file
def copy_file(source_path, *args, **options, &block) source_path = source_path.to_s dest_path = (args.first || source_path).to_s.sub(/\.erb$/, '') ctx = if (vars = options[:context]) vars.instance_eval('binding') else instance_eval('binding') end create_file(dest_path, options) do version = ERB.version.scan(/\d+\.\d+\.\d+/)[0] template = if version.to_f >= 2.2 ERB.new(::File.binread(source_path), trim_mode: "-", eoutvar: "@output_buffer") else ERB.new(::File.binread(source_path), nil, "-", "@output_buffer") end content = template.result(ctx) content = block[content] if block content end return unless options[:preserve] copy_metadata(source_path, dest_path, options) end
ruby
def copy_file(source_path, *args, **options, &block) source_path = source_path.to_s dest_path = (args.first || source_path).to_s.sub(/\.erb$/, '') ctx = if (vars = options[:context]) vars.instance_eval('binding') else instance_eval('binding') end create_file(dest_path, options) do version = ERB.version.scan(/\d+\.\d+\.\d+/)[0] template = if version.to_f >= 2.2 ERB.new(::File.binread(source_path), trim_mode: "-", eoutvar: "@output_buffer") else ERB.new(::File.binread(source_path), nil, "-", "@output_buffer") end content = template.result(ctx) content = block[content] if block content end return unless options[:preserve] copy_metadata(source_path, dest_path, options) end
[ "def", "copy_file", "(", "source_path", ",", "*", "args", ",", "**", "options", ",", "&", "block", ")", "source_path", "=", "source_path", ".", "to_s", "dest_path", "=", "(", "args", ".", "first", "||", "source_path", ")", ".", "to_s", ".", "sub", "(", "/", "\\.", "/", ",", "''", ")", "ctx", "=", "if", "(", "vars", "=", "options", "[", ":context", "]", ")", "vars", ".", "instance_eval", "(", "'binding'", ")", "else", "instance_eval", "(", "'binding'", ")", "end", "create_file", "(", "dest_path", ",", "options", ")", "do", "version", "=", "ERB", ".", "version", ".", "scan", "(", "/", "\\d", "\\.", "\\d", "\\.", "\\d", "/", ")", "[", "0", "]", "template", "=", "if", "version", ".", "to_f", ">=", "2.2", "ERB", ".", "new", "(", "::", "File", ".", "binread", "(", "source_path", ")", ",", "trim_mode", ":", "\"-\"", ",", "eoutvar", ":", "\"@output_buffer\"", ")", "else", "ERB", ".", "new", "(", "::", "File", ".", "binread", "(", "source_path", ")", ",", "nil", ",", "\"-\"", ",", "\"@output_buffer\"", ")", "end", "content", "=", "template", ".", "result", "(", "ctx", ")", "content", "=", "block", "[", "content", "]", "if", "block", "content", "end", "return", "unless", "options", "[", ":preserve", "]", "copy_metadata", "(", "source_path", ",", "dest_path", ",", "options", ")", "end" ]
Copy file from the relative source to the relative destination running it through ERB. @example copy_file 'templates/test.rb', 'app/test.rb' @example vars = OpenStruct.new vars[:name] = 'foo' copy_file 'templates/%name%.rb', 'app/%name%.rb', context: vars @param [String, Pathname] source_path @param [Hash] options @option options [Symbol] :context the binding to use for the template @option options [Symbol] :preserve If true, the owner, group, permissions and modified time are preserved on the copied file, defaults to false. @option options [Symbol] :noop If true do not execute the action. @option options [Symbol] :verbose If true log the action status to stdout @api public
[ "Copy", "file", "from", "the", "relative", "source", "to", "the", "relative", "destination", "running", "it", "through", "ERB", "." ]
575a78a654d74fad2cb5abe06d798ee46293ba0a
https://github.com/piotrmurach/tty-file/blob/575a78a654d74fad2cb5abe06d798ee46293ba0a/lib/tty/file.rb#L237-L260
21,825
piotrmurach/tty-file
lib/tty/file.rb
TTY.File.copy_metadata
def copy_metadata(src_path, dest_path, **options) stats = ::File.lstat(src_path) ::File.utime(stats.atime, stats.mtime, dest_path) chmod(dest_path, stats.mode, options) end
ruby
def copy_metadata(src_path, dest_path, **options) stats = ::File.lstat(src_path) ::File.utime(stats.atime, stats.mtime, dest_path) chmod(dest_path, stats.mode, options) end
[ "def", "copy_metadata", "(", "src_path", ",", "dest_path", ",", "**", "options", ")", "stats", "=", "::", "File", ".", "lstat", "(", "src_path", ")", "::", "File", ".", "utime", "(", "stats", ".", "atime", ",", "stats", ".", "mtime", ",", "dest_path", ")", "chmod", "(", "dest_path", ",", "stats", ".", "mode", ",", "options", ")", "end" ]
Copy file metadata @param [String] src_path the source file path @param [String] dest_path the destination file path @api public
[ "Copy", "file", "metadata" ]
575a78a654d74fad2cb5abe06d798ee46293ba0a
https://github.com/piotrmurach/tty-file/blob/575a78a654d74fad2cb5abe06d798ee46293ba0a/lib/tty/file.rb#L271-L275
21,826
piotrmurach/tty-file
lib/tty/file.rb
TTY.File.copy_directory
def copy_directory(source_path, *args, **options, &block) source_path = source_path.to_s check_path(source_path) source = escape_glob_path(source_path) dest_path = (args.first || source).to_s opts = {recursive: true}.merge(options) pattern = opts[:recursive] ? ::File.join(source, '**') : source glob_pattern = ::File.join(pattern, '*') Dir.glob(glob_pattern, ::File::FNM_DOTMATCH).sort.each do |file_source| next if ::File.directory?(file_source) next if opts[:exclude] && file_source.match(opts[:exclude]) dest = ::File.join(dest_path, file_source.gsub(source_path, '.')) file_dest = ::Pathname.new(dest).cleanpath.to_s copy_file(file_source, file_dest, **options, &block) end end
ruby
def copy_directory(source_path, *args, **options, &block) source_path = source_path.to_s check_path(source_path) source = escape_glob_path(source_path) dest_path = (args.first || source).to_s opts = {recursive: true}.merge(options) pattern = opts[:recursive] ? ::File.join(source, '**') : source glob_pattern = ::File.join(pattern, '*') Dir.glob(glob_pattern, ::File::FNM_DOTMATCH).sort.each do |file_source| next if ::File.directory?(file_source) next if opts[:exclude] && file_source.match(opts[:exclude]) dest = ::File.join(dest_path, file_source.gsub(source_path, '.')) file_dest = ::Pathname.new(dest).cleanpath.to_s copy_file(file_source, file_dest, **options, &block) end end
[ "def", "copy_directory", "(", "source_path", ",", "*", "args", ",", "**", "options", ",", "&", "block", ")", "source_path", "=", "source_path", ".", "to_s", "check_path", "(", "source_path", ")", "source", "=", "escape_glob_path", "(", "source_path", ")", "dest_path", "=", "(", "args", ".", "first", "||", "source", ")", ".", "to_s", "opts", "=", "{", "recursive", ":", "true", "}", ".", "merge", "(", "options", ")", "pattern", "=", "opts", "[", ":recursive", "]", "?", "::", "File", ".", "join", "(", "source", ",", "'**'", ")", ":", "source", "glob_pattern", "=", "::", "File", ".", "join", "(", "pattern", ",", "'*'", ")", "Dir", ".", "glob", "(", "glob_pattern", ",", "::", "File", "::", "FNM_DOTMATCH", ")", ".", "sort", ".", "each", "do", "|", "file_source", "|", "next", "if", "::", "File", ".", "directory?", "(", "file_source", ")", "next", "if", "opts", "[", ":exclude", "]", "&&", "file_source", ".", "match", "(", "opts", "[", ":exclude", "]", ")", "dest", "=", "::", "File", ".", "join", "(", "dest_path", ",", "file_source", ".", "gsub", "(", "source_path", ",", "'.'", ")", ")", "file_dest", "=", "::", "Pathname", ".", "new", "(", "dest", ")", ".", "cleanpath", ".", "to_s", "copy_file", "(", "file_source", ",", "file_dest", ",", "**", "options", ",", "block", ")", "end", "end" ]
Copy directory recursively from source to destination path Any files names wrapped within % sign will be expanded by executing corresponding method and inserting its value. Assuming the following directory structure: app/ %name%.rb command.rb.erb README.md Invoking: copy_directory("app", "new_app") The following directory structure should be created where name resolves to 'cli' value: new_app/ cli.rb command.rb README @param [String, Pathname] source_path @param [Hash[Symbol]] options @option options [Symbol] :preserve If true, the owner, group, permissions and modified time are preserved on the copied file, defaults to false. @option options [Symbol] :recursive If false, copies only top level files, defaults to true. @option options [Symbol] :exclude A regex that specifies files to ignore when copying. @example copy_directory("app", "new_app", recursive: false) copy_directory("app", "new_app", exclude: /docs/) @api public
[ "Copy", "directory", "recursively", "from", "source", "to", "destination", "path" ]
575a78a654d74fad2cb5abe06d798ee46293ba0a
https://github.com/piotrmurach/tty-file/blob/575a78a654d74fad2cb5abe06d798ee46293ba0a/lib/tty/file.rb#L314-L332
21,827
piotrmurach/tty-file
lib/tty/file.rb
TTY.File.diff
def diff(path_a, path_b, **options) threshold = options[:threshold] || 10_000_000 output = [] open_tempfile_if_missing(path_a) do |file_a| if ::File.size(file_a) > threshold raise ArgumentError, "(file size of #{file_a.path} exceeds #{threshold} bytes, diff output suppressed)" end if binary?(file_a) raise ArgumentError, "(#{file_a.path} is binary, diff output suppressed)" end open_tempfile_if_missing(path_b) do |file_b| if binary?(file_b) raise ArgumentError, "(#{file_a.path} is binary, diff output suppressed)" end if ::File.size(file_b) > threshold return "(file size of #{file_b.path} exceeds #{threshold} bytes, diff output suppressed)" end log_status(:diff, "#{file_a.path} - #{file_b.path}", options.fetch(:verbose, true), options.fetch(:color, :green)) return output.join if options[:noop] block_size = file_a.lstat.blksize while !file_a.eof? && !file_b.eof? output << Differ.new(file_a.read(block_size), file_b.read(block_size), options).call end end end output.join end
ruby
def diff(path_a, path_b, **options) threshold = options[:threshold] || 10_000_000 output = [] open_tempfile_if_missing(path_a) do |file_a| if ::File.size(file_a) > threshold raise ArgumentError, "(file size of #{file_a.path} exceeds #{threshold} bytes, diff output suppressed)" end if binary?(file_a) raise ArgumentError, "(#{file_a.path} is binary, diff output suppressed)" end open_tempfile_if_missing(path_b) do |file_b| if binary?(file_b) raise ArgumentError, "(#{file_a.path} is binary, diff output suppressed)" end if ::File.size(file_b) > threshold return "(file size of #{file_b.path} exceeds #{threshold} bytes, diff output suppressed)" end log_status(:diff, "#{file_a.path} - #{file_b.path}", options.fetch(:verbose, true), options.fetch(:color, :green)) return output.join if options[:noop] block_size = file_a.lstat.blksize while !file_a.eof? && !file_b.eof? output << Differ.new(file_a.read(block_size), file_b.read(block_size), options).call end end end output.join end
[ "def", "diff", "(", "path_a", ",", "path_b", ",", "**", "options", ")", "threshold", "=", "options", "[", ":threshold", "]", "||", "10_000_000", "output", "=", "[", "]", "open_tempfile_if_missing", "(", "path_a", ")", "do", "|", "file_a", "|", "if", "::", "File", ".", "size", "(", "file_a", ")", ">", "threshold", "raise", "ArgumentError", ",", "\"(file size of #{file_a.path} exceeds #{threshold} bytes, diff output suppressed)\"", "end", "if", "binary?", "(", "file_a", ")", "raise", "ArgumentError", ",", "\"(#{file_a.path} is binary, diff output suppressed)\"", "end", "open_tempfile_if_missing", "(", "path_b", ")", "do", "|", "file_b", "|", "if", "binary?", "(", "file_b", ")", "raise", "ArgumentError", ",", "\"(#{file_a.path} is binary, diff output suppressed)\"", "end", "if", "::", "File", ".", "size", "(", "file_b", ")", ">", "threshold", "return", "\"(file size of #{file_b.path} exceeds #{threshold} bytes, diff output suppressed)\"", "end", "log_status", "(", ":diff", ",", "\"#{file_a.path} - #{file_b.path}\"", ",", "options", ".", "fetch", "(", ":verbose", ",", "true", ")", ",", "options", ".", "fetch", "(", ":color", ",", ":green", ")", ")", "return", "output", ".", "join", "if", "options", "[", ":noop", "]", "block_size", "=", "file_a", ".", "lstat", ".", "blksize", "while", "!", "file_a", ".", "eof?", "&&", "!", "file_b", ".", "eof?", "output", "<<", "Differ", ".", "new", "(", "file_a", ".", "read", "(", "block_size", ")", ",", "file_b", ".", "read", "(", "block_size", ")", ",", "options", ")", ".", "call", "end", "end", "end", "output", ".", "join", "end" ]
Diff files line by line @param [String, Pathname] path_a @param [String, Pathname] path_b @param [Hash[Symbol]] options @option options [Symbol] :format the diffining output format @option options [Symbol] :context_lines the number of extra lines for the context @option options [Symbol] :threshold maximum file size in bytes @example diff(file_a, file_b, format: :old) @api public
[ "Diff", "files", "line", "by", "line" ]
575a78a654d74fad2cb5abe06d798ee46293ba0a
https://github.com/piotrmurach/tty-file/blob/575a78a654d74fad2cb5abe06d798ee46293ba0a/lib/tty/file.rb#L354-L386
21,828
piotrmurach/tty-file
lib/tty/file.rb
TTY.File.download_file
def download_file(uri, *args, **options, &block) uri = uri.to_s dest_path = (args.first || ::File.basename(uri)).to_s unless uri =~ %r{^https?\://} copy_file(uri, dest_path, options) return end content = DownloadFile.new(uri, dest_path, options).call if block_given? content = (block.arity.nonzero? ? block[content] : block[]) end create_file(dest_path, content, options) end
ruby
def download_file(uri, *args, **options, &block) uri = uri.to_s dest_path = (args.first || ::File.basename(uri)).to_s unless uri =~ %r{^https?\://} copy_file(uri, dest_path, options) return end content = DownloadFile.new(uri, dest_path, options).call if block_given? content = (block.arity.nonzero? ? block[content] : block[]) end create_file(dest_path, content, options) end
[ "def", "download_file", "(", "uri", ",", "*", "args", ",", "**", "options", ",", "&", "block", ")", "uri", "=", "uri", ".", "to_s", "dest_path", "=", "(", "args", ".", "first", "||", "::", "File", ".", "basename", "(", "uri", ")", ")", ".", "to_s", "unless", "uri", "=~", "%r{", "\\:", "}", "copy_file", "(", "uri", ",", "dest_path", ",", "options", ")", "return", "end", "content", "=", "DownloadFile", ".", "new", "(", "uri", ",", "dest_path", ",", "options", ")", ".", "call", "if", "block_given?", "content", "=", "(", "block", ".", "arity", ".", "nonzero?", "?", "block", "[", "content", "]", ":", "block", "[", "]", ")", "end", "create_file", "(", "dest_path", ",", "content", ",", "options", ")", "end" ]
Download the content from a given address and save at the given relative destination. If block is provided in place of destination, the content of of the uri is yielded. @param [String, Pathname] uri the URI address @param [String, Pathname] dest the relative path to save @param [Hash[Symbol]] options @param options [Symbol] :limit the limit of redirects @example download_file("https://gist.github.com/4701967", "doc/benchmarks") @example download_file("https://gist.github.com/4701967") do |content| content.gsub("\n", " ") end @api public
[ "Download", "the", "content", "from", "a", "given", "address", "and", "save", "at", "the", "given", "relative", "destination", ".", "If", "block", "is", "provided", "in", "place", "of", "destination", "the", "content", "of", "of", "the", "uri", "is", "yielded", "." ]
575a78a654d74fad2cb5abe06d798ee46293ba0a
https://github.com/piotrmurach/tty-file/blob/575a78a654d74fad2cb5abe06d798ee46293ba0a/lib/tty/file.rb#L415-L431
21,829
piotrmurach/tty-file
lib/tty/file.rb
TTY.File.prepend_to_file
def prepend_to_file(relative_path, *args, **options, &block) log_status(:prepend, relative_path, options.fetch(:verbose, true), options.fetch(:color, :green)) options.merge!(before: /\A/, verbose: false) inject_into_file(relative_path, *(args << options), &block) end
ruby
def prepend_to_file(relative_path, *args, **options, &block) log_status(:prepend, relative_path, options.fetch(:verbose, true), options.fetch(:color, :green)) options.merge!(before: /\A/, verbose: false) inject_into_file(relative_path, *(args << options), &block) end
[ "def", "prepend_to_file", "(", "relative_path", ",", "*", "args", ",", "**", "options", ",", "&", "block", ")", "log_status", "(", ":prepend", ",", "relative_path", ",", "options", ".", "fetch", "(", ":verbose", ",", "true", ")", ",", "options", ".", "fetch", "(", ":color", ",", ":green", ")", ")", "options", ".", "merge!", "(", "before", ":", "/", "\\A", "/", ",", "verbose", ":", "false", ")", "inject_into_file", "(", "relative_path", ",", "(", "args", "<<", "options", ")", ",", "block", ")", "end" ]
Prepend to a file @param [String, Pathname] relative_path @param [Array[String]] content the content to preped to file @example prepend_to_file('Gemfile', "gem 'tty'") @example prepend_to_file('Gemfile') do "gem 'tty'" end @api public
[ "Prepend", "to", "a", "file" ]
575a78a654d74fad2cb5abe06d798ee46293ba0a
https://github.com/piotrmurach/tty-file/blob/575a78a654d74fad2cb5abe06d798ee46293ba0a/lib/tty/file.rb#L452-L457
21,830
piotrmurach/tty-file
lib/tty/file.rb
TTY.File.append_to_file
def append_to_file(relative_path, *args, **options, &block) log_status(:append, relative_path, options.fetch(:verbose, true), options.fetch(:color, :green)) options.merge!(after: /\z/, verbose: false) inject_into_file(relative_path, *(args << options), &block) end
ruby
def append_to_file(relative_path, *args, **options, &block) log_status(:append, relative_path, options.fetch(:verbose, true), options.fetch(:color, :green)) options.merge!(after: /\z/, verbose: false) inject_into_file(relative_path, *(args << options), &block) end
[ "def", "append_to_file", "(", "relative_path", ",", "*", "args", ",", "**", "options", ",", "&", "block", ")", "log_status", "(", ":append", ",", "relative_path", ",", "options", ".", "fetch", "(", ":verbose", ",", "true", ")", ",", "options", ".", "fetch", "(", ":color", ",", ":green", ")", ")", "options", ".", "merge!", "(", "after", ":", "/", "\\z", "/", ",", "verbose", ":", "false", ")", "inject_into_file", "(", "relative_path", ",", "(", "args", "<<", "options", ")", ",", "block", ")", "end" ]
Append to a file @param [String, Pathname] relative_path @param [Array[String]] content the content to append to file @example append_to_file('Gemfile', "gem 'tty'") @example append_to_file('Gemfile') do "gem 'tty'" end @api public
[ "Append", "to", "a", "file" ]
575a78a654d74fad2cb5abe06d798ee46293ba0a
https://github.com/piotrmurach/tty-file/blob/575a78a654d74fad2cb5abe06d798ee46293ba0a/lib/tty/file.rb#L483-L488
21,831
piotrmurach/tty-file
lib/tty/file.rb
TTY.File.safe_append_to_file
def safe_append_to_file(relative_path, *args, **options, &block) append_to_file(relative_path, *args, **(options.merge(force: false)), &block) end
ruby
def safe_append_to_file(relative_path, *args, **options, &block) append_to_file(relative_path, *args, **(options.merge(force: false)), &block) end
[ "def", "safe_append_to_file", "(", "relative_path", ",", "*", "args", ",", "**", "options", ",", "&", "block", ")", "append_to_file", "(", "relative_path", ",", "args", ",", "**", "(", "options", ".", "merge", "(", "force", ":", "false", ")", ")", ",", "block", ")", "end" ]
Safely append to file checking if content is not already present @api public
[ "Safely", "append", "to", "file", "checking", "if", "content", "is", "not", "already", "present" ]
575a78a654d74fad2cb5abe06d798ee46293ba0a
https://github.com/piotrmurach/tty-file/blob/575a78a654d74fad2cb5abe06d798ee46293ba0a/lib/tty/file.rb#L497-L499
21,832
piotrmurach/tty-file
lib/tty/file.rb
TTY.File.remove_file
def remove_file(relative_path, *args, **options) relative_path = relative_path.to_s log_status(:remove, relative_path, options.fetch(:verbose, true), options.fetch(:color, :red)) return if options[:noop] || !::File.exist?(relative_path) ::FileUtils.rm_r(relative_path, force: options[:force], secure: options.fetch(:secure, true)) end
ruby
def remove_file(relative_path, *args, **options) relative_path = relative_path.to_s log_status(:remove, relative_path, options.fetch(:verbose, true), options.fetch(:color, :red)) return if options[:noop] || !::File.exist?(relative_path) ::FileUtils.rm_r(relative_path, force: options[:force], secure: options.fetch(:secure, true)) end
[ "def", "remove_file", "(", "relative_path", ",", "*", "args", ",", "**", "options", ")", "relative_path", "=", "relative_path", ".", "to_s", "log_status", "(", ":remove", ",", "relative_path", ",", "options", ".", "fetch", "(", ":verbose", ",", "true", ")", ",", "options", ".", "fetch", "(", ":color", ",", ":red", ")", ")", "return", "if", "options", "[", ":noop", "]", "||", "!", "::", "File", ".", "exist?", "(", "relative_path", ")", "::", "FileUtils", ".", "rm_r", "(", "relative_path", ",", "force", ":", "options", "[", ":force", "]", ",", "secure", ":", "options", ".", "fetch", "(", ":secure", ",", "true", ")", ")", "end" ]
Remove a file or a directory at specified relative path. @param [String, Pathname] relative_path @param [Hash[:Symbol]] options @option options [Symbol] :noop pretend removing file @option options [Symbol] :force remove file ignoring errors @option options [Symbol] :verbose log status @option options [Symbol] :secure for secure removing @example remove_file 'doc/README.md' @api public
[ "Remove", "a", "file", "or", "a", "directory", "at", "specified", "relative", "path", "." ]
575a78a654d74fad2cb5abe06d798ee46293ba0a
https://github.com/piotrmurach/tty-file/blob/575a78a654d74fad2cb5abe06d798ee46293ba0a/lib/tty/file.rb#L628-L637
21,833
piotrmurach/tty-file
lib/tty/file.rb
TTY.File.tail_file
def tail_file(relative_path, num_lines = 10, **options, &block) file = ::File.open(relative_path) chunk_size = options.fetch(:chunk_size, 512) line_sep = $/ lines = [] newline_count = 0 ReadBackwardFile.new(file, chunk_size).each_chunk do |chunk| # look for newline index counting from right of chunk while (nl_index = chunk.rindex(line_sep, (nl_index || chunk.size) - 1)) newline_count += 1 break if newline_count > num_lines || nl_index.zero? end if newline_count > num_lines lines.insert(0, chunk[(nl_index + 1)..-1]) break else lines.insert(0, chunk) end end lines.join.split(line_sep).each(&block).to_a end
ruby
def tail_file(relative_path, num_lines = 10, **options, &block) file = ::File.open(relative_path) chunk_size = options.fetch(:chunk_size, 512) line_sep = $/ lines = [] newline_count = 0 ReadBackwardFile.new(file, chunk_size).each_chunk do |chunk| # look for newline index counting from right of chunk while (nl_index = chunk.rindex(line_sep, (nl_index || chunk.size) - 1)) newline_count += 1 break if newline_count > num_lines || nl_index.zero? end if newline_count > num_lines lines.insert(0, chunk[(nl_index + 1)..-1]) break else lines.insert(0, chunk) end end lines.join.split(line_sep).each(&block).to_a end
[ "def", "tail_file", "(", "relative_path", ",", "num_lines", "=", "10", ",", "**", "options", ",", "&", "block", ")", "file", "=", "::", "File", ".", "open", "(", "relative_path", ")", "chunk_size", "=", "options", ".", "fetch", "(", ":chunk_size", ",", "512", ")", "line_sep", "=", "$/", "lines", "=", "[", "]", "newline_count", "=", "0", "ReadBackwardFile", ".", "new", "(", "file", ",", "chunk_size", ")", ".", "each_chunk", "do", "|", "chunk", "|", "# look for newline index counting from right of chunk", "while", "(", "nl_index", "=", "chunk", ".", "rindex", "(", "line_sep", ",", "(", "nl_index", "||", "chunk", ".", "size", ")", "-", "1", ")", ")", "newline_count", "+=", "1", "break", "if", "newline_count", ">", "num_lines", "||", "nl_index", ".", "zero?", "end", "if", "newline_count", ">", "num_lines", "lines", ".", "insert", "(", "0", ",", "chunk", "[", "(", "nl_index", "+", "1", ")", "..", "-", "1", "]", ")", "break", "else", "lines", ".", "insert", "(", "0", ",", "chunk", ")", "end", "end", "lines", ".", "join", ".", "split", "(", "line_sep", ")", ".", "each", "(", "block", ")", ".", "to_a", "end" ]
Provide the last number of lines from a file @param [String, Pathname] relative_path the relative path to a file @param [Integer] num_lines the number of lines to return from file @example tail_file 'filename' # => ['line 19', 'line20', ... ] @example tail_file 'filename', 15 # => ['line 19', 'line20', ... ] @return [Array[String]] @api public
[ "Provide", "the", "last", "number", "of", "lines", "from", "a", "file" ]
575a78a654d74fad2cb5abe06d798ee46293ba0a
https://github.com/piotrmurach/tty-file/blob/575a78a654d74fad2cb5abe06d798ee46293ba0a/lib/tty/file.rb#L659-L682
21,834
piotrmurach/tty-file
lib/tty/file.rb
TTY.File.log_status
def log_status(cmd, message, verbose, color = false) return unless verbose cmd = cmd.to_s.rjust(12) if color i = cmd.index(/[a-z]/) cmd = cmd[0...i] + decorate(cmd[i..-1], color) end message = "#{cmd} #{message}" message += "\n" unless message.end_with?("\n") @output.print(message) @output.flush end
ruby
def log_status(cmd, message, verbose, color = false) return unless verbose cmd = cmd.to_s.rjust(12) if color i = cmd.index(/[a-z]/) cmd = cmd[0...i] + decorate(cmd[i..-1], color) end message = "#{cmd} #{message}" message += "\n" unless message.end_with?("\n") @output.print(message) @output.flush end
[ "def", "log_status", "(", "cmd", ",", "message", ",", "verbose", ",", "color", "=", "false", ")", "return", "unless", "verbose", "cmd", "=", "cmd", ".", "to_s", ".", "rjust", "(", "12", ")", "if", "color", "i", "=", "cmd", ".", "index", "(", "/", "/", ")", "cmd", "=", "cmd", "[", "0", "...", "i", "]", "+", "decorate", "(", "cmd", "[", "i", "..", "-", "1", "]", ",", "color", ")", "end", "message", "=", "\"#{cmd} #{message}\"", "message", "+=", "\"\\n\"", "unless", "message", ".", "end_with?", "(", "\"\\n\"", ")", "@output", ".", "print", "(", "message", ")", "@output", ".", "flush", "end" ]
Log file operation @api private
[ "Log", "file", "operation" ]
575a78a654d74fad2cb5abe06d798ee46293ba0a
https://github.com/piotrmurach/tty-file/blob/575a78a654d74fad2cb5abe06d798ee46293ba0a/lib/tty/file.rb#L725-L739
21,835
piotrmurach/tty-file
lib/tty/file.rb
TTY.File.open_tempfile_if_missing
def open_tempfile_if_missing(object, &block) if ::FileTest.file?(object) ::File.open(object, &block) else tempfile = Tempfile.new('tty-file-diff') tempfile << object tempfile.rewind block[tempfile] unless tempfile.nil? tempfile.close tempfile.unlink end end end
ruby
def open_tempfile_if_missing(object, &block) if ::FileTest.file?(object) ::File.open(object, &block) else tempfile = Tempfile.new('tty-file-diff') tempfile << object tempfile.rewind block[tempfile] unless tempfile.nil? tempfile.close tempfile.unlink end end end
[ "def", "open_tempfile_if_missing", "(", "object", ",", "&", "block", ")", "if", "::", "FileTest", ".", "file?", "(", "object", ")", "::", "File", ".", "open", "(", "object", ",", "block", ")", "else", "tempfile", "=", "Tempfile", ".", "new", "(", "'tty-file-diff'", ")", "tempfile", "<<", "object", "tempfile", ".", "rewind", "block", "[", "tempfile", "]", "unless", "tempfile", ".", "nil?", "tempfile", ".", "close", "tempfile", ".", "unlink", "end", "end", "end" ]
If content is not a path to a file, create a tempfile and open it instead. @param [String] object a path to file or content @api private
[ "If", "content", "is", "not", "a", "path", "to", "a", "file", "create", "a", "tempfile", "and", "open", "it", "instead", "." ]
575a78a654d74fad2cb5abe06d798ee46293ba0a
https://github.com/piotrmurach/tty-file/blob/575a78a654d74fad2cb5abe06d798ee46293ba0a/lib/tty/file.rb#L749-L764
21,836
mitchellh/virtualbox
lib/virtualbox/snapshot.rb
VirtualBox.Snapshot.load_relationship
def load_relationship(name) populate_relationship(:parent, interface.parent) populate_relationship(:machine, interface.machine) populate_relationship(:children, interface.children) end
ruby
def load_relationship(name) populate_relationship(:parent, interface.parent) populate_relationship(:machine, interface.machine) populate_relationship(:children, interface.children) end
[ "def", "load_relationship", "(", "name", ")", "populate_relationship", "(", ":parent", ",", "interface", ".", "parent", ")", "populate_relationship", "(", ":machine", ",", "interface", ".", "machine", ")", "populate_relationship", "(", ":children", ",", "interface", ".", "children", ")", "end" ]
Loads the lazy relationships. **This method should only be called internally.**
[ "Loads", "the", "lazy", "relationships", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/snapshot.rb#L145-L149
21,837
mitchellh/virtualbox
lib/virtualbox/snapshot.rb
VirtualBox.Snapshot.restore
def restore(&block) machine.with_open_session do |session| session.console.restore_snapshot(interface).wait(&block) end end
ruby
def restore(&block) machine.with_open_session do |session| session.console.restore_snapshot(interface).wait(&block) end end
[ "def", "restore", "(", "&", "block", ")", "machine", ".", "with_open_session", "do", "|", "session", "|", "session", ".", "console", ".", "restore_snapshot", "(", "interface", ")", ".", "wait", "(", "block", ")", "end", "end" ]
Restore a snapshot. This will restore this snapshot's virtual machine to the state that this snapshot represents. This method will block while the restore occurs. If a block is given to the function, it will be yielded with a progress object which can be used to track the progress of the operation.
[ "Restore", "a", "snapshot", ".", "This", "will", "restore", "this", "snapshot", "s", "virtual", "machine", "to", "the", "state", "that", "this", "snapshot", "represents", ".", "This", "method", "will", "block", "while", "the", "restore", "occurs", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/snapshot.rb#L165-L169
21,838
mitchellh/virtualbox
lib/virtualbox/snapshot.rb
VirtualBox.Snapshot.destroy
def destroy(&block) machine.with_open_session do |session| session.console.delete_snapshot(uuid).wait(&block) end end
ruby
def destroy(&block) machine.with_open_session do |session| session.console.delete_snapshot(uuid).wait(&block) end end
[ "def", "destroy", "(", "&", "block", ")", "machine", ".", "with_open_session", "do", "|", "session", "|", "session", ".", "console", ".", "delete_snapshot", "(", "uuid", ")", ".", "wait", "(", "block", ")", "end", "end" ]
Destroy a snapshot. This will physically remove the snapshot. Once this method is called, there is no undo. If this snapshot is a parent of other snapshots, the differencing image of this snapshot will be merged with the child snapshots so no data is lost. This process can sometimes take some time. This method will block while this process occurs. If a block is given to the function, it will be yielded with a progress object which can be used to track the progress of the operation.
[ "Destroy", "a", "snapshot", ".", "This", "will", "physically", "remove", "the", "snapshot", ".", "Once", "this", "method", "is", "called", "there", "is", "no", "undo", ".", "If", "this", "snapshot", "is", "a", "parent", "of", "other", "snapshots", "the", "differencing", "image", "of", "this", "snapshot", "will", "be", "merged", "with", "the", "child", "snapshots", "so", "no", "data", "is", "lost", ".", "This", "process", "can", "sometimes", "take", "some", "time", ".", "This", "method", "will", "block", "while", "this", "process", "occurs", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/snapshot.rb#L179-L183
21,839
mitchellh/virtualbox
lib/virtualbox/vm.rb
VirtualBox.VM.validate
def validate super validates_presence_of :name, :os_type_id, :memory_size, :vram_size, :cpu_count validates_numericality_of :memory_balloon_size, :monitor_count validates_inclusion_of :accelerate_3d_enabled, :accelerate_2d_video_enabled, :teleporter_enabled, :in => [true, false] if !errors_on(:name) # Only validate the name if the name has no errors already vms_of_same_name = self.class.find(name) add_error(:name, 'must not be used by another virtual machine.') if vms_of_same_name && vms_of_same_name.uuid != uuid end validates_inclusion_of :os_type_id, :in => VirtualBox::Global.global.lib.virtualbox.guest_os_types.collect { |os| os.id } min_guest_ram, max_guest_ram = Global.global.system_properties.min_guest_ram, Global.global.system_properties.max_guest_ram validates_inclusion_of :memory_size, :in => (min_guest_ram..max_guest_ram), :message => "must be between #{min_guest_ram} and #{max_guest_ram}." validates_inclusion_of :memory_balloon_size, :in => (0..max_guest_ram), :message => "must be between 0 and #{max_guest_ram}." min_guest_vram, max_guest_vram = Global.global.system_properties.min_guest_vram, Global.global.system_properties.max_guest_vram validates_inclusion_of :vram_size, :in => (min_guest_vram..max_guest_vram), :message => "must be between #{min_guest_vram} and #{max_guest_vram}." min_guest_cpu_count, max_guest_cpu_count = Global.global.system_properties.min_guest_cpu_count, Global.global.system_properties.max_guest_cpu_count validates_inclusion_of :cpu_count, :in => (min_guest_cpu_count..max_guest_cpu_count), :message => "must be between #{min_guest_cpu_count} and #{max_guest_cpu_count}." validates_inclusion_of :clipboard_mode, :in => COM::Util.versioned_interface(:ClipboardMode).map validates_inclusion_of :firmware_type, :in => COM::Util.versioned_interface(:FirmwareType).map end
ruby
def validate super validates_presence_of :name, :os_type_id, :memory_size, :vram_size, :cpu_count validates_numericality_of :memory_balloon_size, :monitor_count validates_inclusion_of :accelerate_3d_enabled, :accelerate_2d_video_enabled, :teleporter_enabled, :in => [true, false] if !errors_on(:name) # Only validate the name if the name has no errors already vms_of_same_name = self.class.find(name) add_error(:name, 'must not be used by another virtual machine.') if vms_of_same_name && vms_of_same_name.uuid != uuid end validates_inclusion_of :os_type_id, :in => VirtualBox::Global.global.lib.virtualbox.guest_os_types.collect { |os| os.id } min_guest_ram, max_guest_ram = Global.global.system_properties.min_guest_ram, Global.global.system_properties.max_guest_ram validates_inclusion_of :memory_size, :in => (min_guest_ram..max_guest_ram), :message => "must be between #{min_guest_ram} and #{max_guest_ram}." validates_inclusion_of :memory_balloon_size, :in => (0..max_guest_ram), :message => "must be between 0 and #{max_guest_ram}." min_guest_vram, max_guest_vram = Global.global.system_properties.min_guest_vram, Global.global.system_properties.max_guest_vram validates_inclusion_of :vram_size, :in => (min_guest_vram..max_guest_vram), :message => "must be between #{min_guest_vram} and #{max_guest_vram}." min_guest_cpu_count, max_guest_cpu_count = Global.global.system_properties.min_guest_cpu_count, Global.global.system_properties.max_guest_cpu_count validates_inclusion_of :cpu_count, :in => (min_guest_cpu_count..max_guest_cpu_count), :message => "must be between #{min_guest_cpu_count} and #{max_guest_cpu_count}." validates_inclusion_of :clipboard_mode, :in => COM::Util.versioned_interface(:ClipboardMode).map validates_inclusion_of :firmware_type, :in => COM::Util.versioned_interface(:FirmwareType).map end
[ "def", "validate", "super", "validates_presence_of", ":name", ",", ":os_type_id", ",", ":memory_size", ",", ":vram_size", ",", ":cpu_count", "validates_numericality_of", ":memory_balloon_size", ",", ":monitor_count", "validates_inclusion_of", ":accelerate_3d_enabled", ",", ":accelerate_2d_video_enabled", ",", ":teleporter_enabled", ",", ":in", "=>", "[", "true", ",", "false", "]", "if", "!", "errors_on", "(", ":name", ")", "# Only validate the name if the name has no errors already", "vms_of_same_name", "=", "self", ".", "class", ".", "find", "(", "name", ")", "add_error", "(", ":name", ",", "'must not be used by another virtual machine.'", ")", "if", "vms_of_same_name", "&&", "vms_of_same_name", ".", "uuid", "!=", "uuid", "end", "validates_inclusion_of", ":os_type_id", ",", ":in", "=>", "VirtualBox", "::", "Global", ".", "global", ".", "lib", ".", "virtualbox", ".", "guest_os_types", ".", "collect", "{", "|", "os", "|", "os", ".", "id", "}", "min_guest_ram", ",", "max_guest_ram", "=", "Global", ".", "global", ".", "system_properties", ".", "min_guest_ram", ",", "Global", ".", "global", ".", "system_properties", ".", "max_guest_ram", "validates_inclusion_of", ":memory_size", ",", ":in", "=>", "(", "min_guest_ram", "..", "max_guest_ram", ")", ",", ":message", "=>", "\"must be between #{min_guest_ram} and #{max_guest_ram}.\"", "validates_inclusion_of", ":memory_balloon_size", ",", ":in", "=>", "(", "0", "..", "max_guest_ram", ")", ",", ":message", "=>", "\"must be between 0 and #{max_guest_ram}.\"", "min_guest_vram", ",", "max_guest_vram", "=", "Global", ".", "global", ".", "system_properties", ".", "min_guest_vram", ",", "Global", ".", "global", ".", "system_properties", ".", "max_guest_vram", "validates_inclusion_of", ":vram_size", ",", ":in", "=>", "(", "min_guest_vram", "..", "max_guest_vram", ")", ",", ":message", "=>", "\"must be between #{min_guest_vram} and #{max_guest_vram}.\"", "min_guest_cpu_count", ",", "max_guest_cpu_count", "=", "Global", ".", "global", ".", "system_properties", ".", "min_guest_cpu_count", ",", "Global", ".", "global", ".", "system_properties", ".", "max_guest_cpu_count", "validates_inclusion_of", ":cpu_count", ",", ":in", "=>", "(", "min_guest_cpu_count", "..", "max_guest_cpu_count", ")", ",", ":message", "=>", "\"must be between #{min_guest_cpu_count} and #{max_guest_cpu_count}.\"", "validates_inclusion_of", ":clipboard_mode", ",", ":in", "=>", "COM", "::", "Util", ".", "versioned_interface", "(", ":ClipboardMode", ")", ".", "map", "validates_inclusion_of", ":firmware_type", ",", ":in", "=>", "COM", "::", "Util", ".", "versioned_interface", "(", ":FirmwareType", ")", ".", "map", "end" ]
Validates the virtual machine
[ "Validates", "the", "virtual", "machine" ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/vm.rb#L311-L338
21,840
mitchellh/virtualbox
lib/virtualbox/vm.rb
VirtualBox.VM.root_snapshot
def root_snapshot return nil if current_snapshot.nil? current = current_snapshot current = current.parent while current.parent != nil current end
ruby
def root_snapshot return nil if current_snapshot.nil? current = current_snapshot current = current.parent while current.parent != nil current end
[ "def", "root_snapshot", "return", "nil", "if", "current_snapshot", ".", "nil?", "current", "=", "current_snapshot", "current", "=", "current", ".", "parent", "while", "current", ".", "parent", "!=", "nil", "current", "end" ]
Returns the root snapshot of this virtual machine. This root snapshot can be used to traverse the tree of snapshots. @return [Snapshot]
[ "Returns", "the", "root", "snapshot", "of", "this", "virtual", "machine", ".", "This", "root", "snapshot", "can", "be", "used", "to", "traverse", "the", "tree", "of", "snapshots", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/vm.rb#L369-L375
21,841
mitchellh/virtualbox
lib/virtualbox/vm.rb
VirtualBox.VM.find_snapshot
def find_snapshot(name) find_helper = lambda do |name, root| return nil if root.nil? return root if root.name == name || root.uuid == name root.children.each do |child| result = find_helper.call(name, child) return result unless result.nil? end nil end find_helper.call(name, root_snapshot) end
ruby
def find_snapshot(name) find_helper = lambda do |name, root| return nil if root.nil? return root if root.name == name || root.uuid == name root.children.each do |child| result = find_helper.call(name, child) return result unless result.nil? end nil end find_helper.call(name, root_snapshot) end
[ "def", "find_snapshot", "(", "name", ")", "find_helper", "=", "lambda", "do", "|", "name", ",", "root", "|", "return", "nil", "if", "root", ".", "nil?", "return", "root", "if", "root", ".", "name", "==", "name", "||", "root", ".", "uuid", "==", "name", "root", ".", "children", ".", "each", "do", "|", "child", "|", "result", "=", "find_helper", ".", "call", "(", "name", ",", "child", ")", "return", "result", "unless", "result", ".", "nil?", "end", "nil", "end", "find_helper", ".", "call", "(", "name", ",", "root_snapshot", ")", "end" ]
Find a snapshot by name or UUID. This allows you to find a snapshot by a given name, rather than having to resort to traversing the entire tree structure manually.
[ "Find", "a", "snapshot", "by", "name", "or", "UUID", ".", "This", "allows", "you", "to", "find", "a", "snapshot", "by", "a", "given", "name", "rather", "than", "having", "to", "resort", "to", "traversing", "the", "entire", "tree", "structure", "manually", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/vm.rb#L380-L394
21,842
mitchellh/virtualbox
lib/virtualbox/vm.rb
VirtualBox.VM.with_open_session
def with_open_session(mode=:write) # Set the session up session = Lib.lib.session close_session = false if session.state != :open # Open up a session for this virtual machine interface.lock_machine(session, mode) # Mark the session to be closed close_session = true end # Yield the block with the session yield session if block_given? # Close the session if close_session # Save these settings only if we're closing and only if the state # is not saved, since that doesn't allow the machine to be saved. session.machine.save_settings if mode == :write && session.machine.state != :saved # Close the session session.unlock_machine end rescue Exception # Close the session so we don't get locked out. We use a rescue block # here instead of an "ensure" since we ONLY want this to occur if an # exception is raised. Otherwise, we may or may not close the session, # depending how deeply nested this call to `with_open_session` is. # (see close_session boolean above) session.unlock_machine if session.state == :open # Reraise the exception, we're not actually catching it to handle it raise end
ruby
def with_open_session(mode=:write) # Set the session up session = Lib.lib.session close_session = false if session.state != :open # Open up a session for this virtual machine interface.lock_machine(session, mode) # Mark the session to be closed close_session = true end # Yield the block with the session yield session if block_given? # Close the session if close_session # Save these settings only if we're closing and only if the state # is not saved, since that doesn't allow the machine to be saved. session.machine.save_settings if mode == :write && session.machine.state != :saved # Close the session session.unlock_machine end rescue Exception # Close the session so we don't get locked out. We use a rescue block # here instead of an "ensure" since we ONLY want this to occur if an # exception is raised. Otherwise, we may or may not close the session, # depending how deeply nested this call to `with_open_session` is. # (see close_session boolean above) session.unlock_machine if session.state == :open # Reraise the exception, we're not actually catching it to handle it raise end
[ "def", "with_open_session", "(", "mode", "=", ":write", ")", "# Set the session up", "session", "=", "Lib", ".", "lib", ".", "session", "close_session", "=", "false", "if", "session", ".", "state", "!=", ":open", "# Open up a session for this virtual machine", "interface", ".", "lock_machine", "(", "session", ",", "mode", ")", "# Mark the session to be closed", "close_session", "=", "true", "end", "# Yield the block with the session", "yield", "session", "if", "block_given?", "# Close the session", "if", "close_session", "# Save these settings only if we're closing and only if the state", "# is not saved, since that doesn't allow the machine to be saved.", "session", ".", "machine", ".", "save_settings", "if", "mode", "==", ":write", "&&", "session", ".", "machine", ".", "state", "!=", ":saved", "# Close the session", "session", ".", "unlock_machine", "end", "rescue", "Exception", "# Close the session so we don't get locked out. We use a rescue block", "# here instead of an \"ensure\" since we ONLY want this to occur if an", "# exception is raised. Otherwise, we may or may not close the session,", "# depending how deeply nested this call to `with_open_session` is.", "# (see close_session boolean above)", "session", ".", "unlock_machine", "if", "session", ".", "state", "==", ":open", "# Reraise the exception, we're not actually catching it to handle it", "raise", "end" ]
Opens a direct session with the machine this VM represents and yields the session object to a block. Many of the VirtualBox's settings can only be modified with an open session on a machine. An open session is similar to a write-lock. Once the session is completed, it must be closed, which this method does as well.
[ "Opens", "a", "direct", "session", "with", "the", "machine", "this", "VM", "represents", "and", "yields", "the", "session", "object", "to", "a", "block", ".", "Many", "of", "the", "VirtualBox", "s", "settings", "can", "only", "be", "modified", "with", "an", "open", "session", "on", "a", "machine", ".", "An", "open", "session", "is", "similar", "to", "a", "write", "-", "lock", ".", "Once", "the", "session", "is", "completed", "it", "must", "be", "closed", "which", "this", "method", "does", "as", "well", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/vm.rb#L401-L437
21,843
mitchellh/virtualbox
lib/virtualbox/vm.rb
VirtualBox.VM.export
def export(filename, options = {}, &block) app = Appliance.new app.path = filename app.add_machine(self, options) app.export(&block) end
ruby
def export(filename, options = {}, &block) app = Appliance.new app.path = filename app.add_machine(self, options) app.export(&block) end
[ "def", "export", "(", "filename", ",", "options", "=", "{", "}", ",", "&", "block", ")", "app", "=", "Appliance", ".", "new", "app", ".", "path", "=", "filename", "app", ".", "add_machine", "(", "self", ",", "options", ")", "app", ".", "export", "(", "block", ")", "end" ]
Exports a virtual machine. The virtual machine will be exported to the specified OVF file name. This directory will also have the `mf` file which contains the file checksums and also the virtual drives of the machine. Export also supports an additional options hash which can contain information that will be embedded with the virtual machine. View below for more information on the available options. This method will block until the export is complete, which takes about 60 to 90 seconds on my 2.2 GHz 2009 model MacBook Pro. If a block is given to the method, then it will be yielded with the progress of the operation. @param [String] filename The file (not directory) to save the exported OVF file. This directory will also receive the checksum file and virtual disks.
[ "Exports", "a", "virtual", "machine", ".", "The", "virtual", "machine", "will", "be", "exported", "to", "the", "specified", "OVF", "file", "name", ".", "This", "directory", "will", "also", "have", "the", "mf", "file", "which", "contains", "the", "file", "checksums", "and", "also", "the", "virtual", "drives", "of", "the", "machine", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/vm.rb#L457-L462
21,844
mitchellh/virtualbox
lib/virtualbox/vm.rb
VirtualBox.VM.take_snapshot
def take_snapshot(name, description="", &block) with_open_session do |session| session.console.take_snapshot(name, description).wait(&block) end end
ruby
def take_snapshot(name, description="", &block) with_open_session do |session| session.console.take_snapshot(name, description).wait(&block) end end
[ "def", "take_snapshot", "(", "name", ",", "description", "=", "\"\"", ",", "&", "block", ")", "with_open_session", "do", "|", "session", "|", "session", ".", "console", ".", "take_snapshot", "(", "name", ",", "description", ")", ".", "wait", "(", "block", ")", "end", "end" ]
Take a snapshot of the current state of the machine. This method can be called while the VM is running and also while it is powered off. This method will block while the snapshot is being taken. If a block is given to this method, it will yield with a progress object which can be used to get the progress of the operation. @param [String] name Name of the snapshot. @param [String] description Description of the snapshot.
[ "Take", "a", "snapshot", "of", "the", "current", "state", "of", "the", "machine", ".", "This", "method", "can", "be", "called", "while", "the", "VM", "is", "running", "and", "also", "while", "it", "is", "powered", "off", ".", "This", "method", "will", "block", "while", "the", "snapshot", "is", "being", "taken", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/vm.rb#L473-L477
21,845
mitchellh/virtualbox
lib/virtualbox/vm.rb
VirtualBox.VM.get_boot_order
def get_boot_order(interface, key) max_boot = Global.global.system_properties.max_boot_position (1..max_boot).inject([]) do |order, position| order << interface.get_boot_order(position) order end end
ruby
def get_boot_order(interface, key) max_boot = Global.global.system_properties.max_boot_position (1..max_boot).inject([]) do |order, position| order << interface.get_boot_order(position) order end end
[ "def", "get_boot_order", "(", "interface", ",", "key", ")", "max_boot", "=", "Global", ".", "global", ".", "system_properties", ".", "max_boot_position", "(", "1", "..", "max_boot", ")", ".", "inject", "(", "[", "]", ")", "do", "|", "order", ",", "position", "|", "order", "<<", "interface", ".", "get_boot_order", "(", "position", ")", "order", "end", "end" ]
Loads the boot order for this virtual machine. This method should never be called directly. Instead, use the `boot_order` attribute to read and modify the boot order.
[ "Loads", "the", "boot", "order", "for", "this", "virtual", "machine", ".", "This", "method", "should", "never", "be", "called", "directly", ".", "Instead", "use", "the", "boot_order", "attribute", "to", "read", "and", "modify", "the", "boot", "order", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/vm.rb#L648-L655
21,846
mitchellh/virtualbox
lib/virtualbox/vm.rb
VirtualBox.VM.set_boot_order
def set_boot_order(interface, key, value) max_boot = Global.global.system_properties.max_boot_position value = value.dup value.concat(Array.new(max_boot - value.size)) if value.size < max_boot (1..max_boot).each do |position| interface.set_boot_order(position, value[position - 1]) end end
ruby
def set_boot_order(interface, key, value) max_boot = Global.global.system_properties.max_boot_position value = value.dup value.concat(Array.new(max_boot - value.size)) if value.size < max_boot (1..max_boot).each do |position| interface.set_boot_order(position, value[position - 1]) end end
[ "def", "set_boot_order", "(", "interface", ",", "key", ",", "value", ")", "max_boot", "=", "Global", ".", "global", ".", "system_properties", ".", "max_boot_position", "value", "=", "value", ".", "dup", "value", ".", "concat", "(", "Array", ".", "new", "(", "max_boot", "-", "value", ".", "size", ")", ")", "if", "value", ".", "size", "<", "max_boot", "(", "1", "..", "max_boot", ")", ".", "each", "do", "|", "position", "|", "interface", ".", "set_boot_order", "(", "position", ",", "value", "[", "position", "-", "1", "]", ")", "end", "end" ]
Sets the boot order for this virtual machine. This method should never be called directly. Instead, modify the `boot_order` array.
[ "Sets", "the", "boot", "order", "for", "this", "virtual", "machine", ".", "This", "method", "should", "never", "be", "called", "directly", ".", "Instead", "modify", "the", "boot_order", "array", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/vm.rb#L659-L667
21,847
mitchellh/virtualbox
lib/virtualbox/appliance.rb
VirtualBox.Appliance.initialize_from_path
def initialize_from_path(path) # Read in the data from the path interface.read(path).wait_for_completion(-1) # Interpret the data to fill in the interface properties interface.interpret # Load the interface attributes load_interface_attributes(interface) # Fill in the virtual systems populate_relationship(:virtual_systems, interface.virtual_system_descriptions) # Should be an existing record existing_record! end
ruby
def initialize_from_path(path) # Read in the data from the path interface.read(path).wait_for_completion(-1) # Interpret the data to fill in the interface properties interface.interpret # Load the interface attributes load_interface_attributes(interface) # Fill in the virtual systems populate_relationship(:virtual_systems, interface.virtual_system_descriptions) # Should be an existing record existing_record! end
[ "def", "initialize_from_path", "(", "path", ")", "# Read in the data from the path", "interface", ".", "read", "(", "path", ")", ".", "wait_for_completion", "(", "-", "1", ")", "# Interpret the data to fill in the interface properties", "interface", ".", "interpret", "# Load the interface attributes", "load_interface_attributes", "(", "interface", ")", "# Fill in the virtual systems", "populate_relationship", "(", ":virtual_systems", ",", "interface", ".", "virtual_system_descriptions", ")", "# Should be an existing record", "existing_record!", "end" ]
Initializes this Appliance instance from a path to an OVF file. This sets up the relationships and so on. @param [String] path Path to the OVF file.
[ "Initializes", "this", "Appliance", "instance", "from", "a", "path", "to", "an", "OVF", "file", ".", "This", "sets", "up", "the", "relationships", "and", "so", "on", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/appliance.rb#L23-L38
21,848
mitchellh/virtualbox
lib/virtualbox/appliance.rb
VirtualBox.Appliance.add_machine
def add_machine(vm, options = {}) sys_desc = vm.interface.export(interface, path) options.each do |key, value| sys_desc.add_description(key, value, value) end end
ruby
def add_machine(vm, options = {}) sys_desc = vm.interface.export(interface, path) options.each do |key, value| sys_desc.add_description(key, value, value) end end
[ "def", "add_machine", "(", "vm", ",", "options", "=", "{", "}", ")", "sys_desc", "=", "vm", ".", "interface", ".", "export", "(", "interface", ",", "path", ")", "options", ".", "each", "do", "|", "key", ",", "value", "|", "sys_desc", ".", "add_description", "(", "key", ",", "value", ",", "value", ")", "end", "end" ]
Adds a VM to the appliance
[ "Adds", "a", "VM", "to", "the", "appliance" ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/appliance.rb#L55-L60
21,849
mitchellh/virtualbox
lib/virtualbox/extra_data.rb
VirtualBox.ExtraData.save
def save changes.each do |key, value| interface.set_extra_data(key.to_s, value[1].to_s) clear_dirty!(key) if value[1].nil? # Remove the key from the hash altogether hash_delete(key.to_s) end end end
ruby
def save changes.each do |key, value| interface.set_extra_data(key.to_s, value[1].to_s) clear_dirty!(key) if value[1].nil? # Remove the key from the hash altogether hash_delete(key.to_s) end end end
[ "def", "save", "changes", ".", "each", "do", "|", "key", ",", "value", "|", "interface", ".", "set_extra_data", "(", "key", ".", "to_s", ",", "value", "[", "1", "]", ".", "to_s", ")", "clear_dirty!", "(", "key", ")", "if", "value", "[", "1", "]", ".", "nil?", "# Remove the key from the hash altogether", "hash_delete", "(", "key", ".", "to_s", ")", "end", "end", "end" ]
Saves extra data. This method does the same thing for both new and existing extra data, since virtualbox will overwrite old data or create it if it doesn't exist. @param [Boolean] raise_errors If true, {Exceptions::CommandFailedException} will be raised if the command failed. @return [Boolean] True if command was successful, false otherwise.
[ "Saves", "extra", "data", ".", "This", "method", "does", "the", "same", "thing", "for", "both", "new", "and", "existing", "extra", "data", "since", "virtualbox", "will", "overwrite", "old", "data", "or", "create", "it", "if", "it", "doesn", "t", "exist", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/extra_data.rb#L106-L117
21,850
mitchellh/virtualbox
lib/virtualbox/nat_engine.rb
VirtualBox.NATEngine.initialize_attributes
def initialize_attributes(parent, inat) write_attribute(:parent, parent) write_attribute(:interface, inat) # Load the interface attributes associated with this model load_interface_attributes(inat) populate_relationships(inat) # Clear dirty and set as existing clear_dirty! existing_record! end
ruby
def initialize_attributes(parent, inat) write_attribute(:parent, parent) write_attribute(:interface, inat) # Load the interface attributes associated with this model load_interface_attributes(inat) populate_relationships(inat) # Clear dirty and set as existing clear_dirty! existing_record! end
[ "def", "initialize_attributes", "(", "parent", ",", "inat", ")", "write_attribute", "(", ":parent", ",", "parent", ")", "write_attribute", "(", ":interface", ",", "inat", ")", "# Load the interface attributes associated with this model", "load_interface_attributes", "(", "inat", ")", "populate_relationships", "(", "inat", ")", "# Clear dirty and set as existing", "clear_dirty!", "existing_record!", "end" ]
Initializes the attributes of an existing NAT engine.
[ "Initializes", "the", "attributes", "of", "an", "existing", "NAT", "engine", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/nat_engine.rb#L44-L55
21,851
mitchellh/virtualbox
lib/virtualbox/host_network_interface.rb
VirtualBox.HostNetworkInterface.dhcp_server
def dhcp_server(create_if_not_found=true) return nil if interface_type != :host_only # Try to find the dhcp server in the list of DHCP servers. dhcp_name = "HostInterfaceNetworking-#{name}" result = parent.parent.dhcp_servers.find do |dhcp| dhcp.network_name == dhcp_name end # If no DHCP server is found, create one result = parent.parent.dhcp_servers.create(dhcp_name) if result.nil? && create_if_not_found result end
ruby
def dhcp_server(create_if_not_found=true) return nil if interface_type != :host_only # Try to find the dhcp server in the list of DHCP servers. dhcp_name = "HostInterfaceNetworking-#{name}" result = parent.parent.dhcp_servers.find do |dhcp| dhcp.network_name == dhcp_name end # If no DHCP server is found, create one result = parent.parent.dhcp_servers.create(dhcp_name) if result.nil? && create_if_not_found result end
[ "def", "dhcp_server", "(", "create_if_not_found", "=", "true", ")", "return", "nil", "if", "interface_type", "!=", ":host_only", "# Try to find the dhcp server in the list of DHCP servers.", "dhcp_name", "=", "\"HostInterfaceNetworking-#{name}\"", "result", "=", "parent", ".", "parent", ".", "dhcp_servers", ".", "find", "do", "|", "dhcp", "|", "dhcp", ".", "network_name", "==", "dhcp_name", "end", "# If no DHCP server is found, create one", "result", "=", "parent", ".", "parent", ".", "dhcp_servers", ".", "create", "(", "dhcp_name", ")", "if", "result", ".", "nil?", "&&", "create_if_not_found", "result", "end" ]
Gets the DHCP server associated with the network interface. Only host only network interfaces have dhcp servers. If a DHCP server doesn't exist for this network interface, one will be created.
[ "Gets", "the", "DHCP", "server", "associated", "with", "the", "network", "interface", ".", "Only", "host", "only", "network", "interfaces", "have", "dhcp", "servers", ".", "If", "a", "DHCP", "server", "doesn", "t", "exist", "for", "this", "network", "interface", "one", "will", "be", "created", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/host_network_interface.rb#L75-L87
21,852
mitchellh/virtualbox
lib/virtualbox/host_network_interface.rb
VirtualBox.HostNetworkInterface.attached_vms
def attached_vms parent.parent.vms.find_all do |vm| next if !vm.accessible? result = vm.network_adapters.find do |adapter| adapter.enabled? && adapter.host_only_interface == name end !result.nil? end end
ruby
def attached_vms parent.parent.vms.find_all do |vm| next if !vm.accessible? result = vm.network_adapters.find do |adapter| adapter.enabled? && adapter.host_only_interface == name end !result.nil? end end
[ "def", "attached_vms", "parent", ".", "parent", ".", "vms", ".", "find_all", "do", "|", "vm", "|", "next", "if", "!", "vm", ".", "accessible?", "result", "=", "vm", ".", "network_adapters", ".", "find", "do", "|", "adapter", "|", "adapter", ".", "enabled?", "&&", "adapter", ".", "host_only_interface", "==", "name", "end", "!", "result", ".", "nil?", "end", "end" ]
Gets the VMs which have an adapter which is attached to this network interface.
[ "Gets", "the", "VMs", "which", "have", "an", "adapter", "which", "is", "attached", "to", "this", "network", "interface", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/host_network_interface.rb#L91-L101
21,853
mitchellh/virtualbox
lib/virtualbox/host_network_interface.rb
VirtualBox.HostNetworkInterface.enable_static
def enable_static(ip, netmask=nil) netmask ||= network_mask interface.enable_static_ip_config(ip, netmask) reload end
ruby
def enable_static(ip, netmask=nil) netmask ||= network_mask interface.enable_static_ip_config(ip, netmask) reload end
[ "def", "enable_static", "(", "ip", ",", "netmask", "=", "nil", ")", "netmask", "||=", "network_mask", "interface", ".", "enable_static_ip_config", "(", "ip", ",", "netmask", ")", "reload", "end" ]
Sets up the static IPV4 configuration for the host only network interface. This allows the caller to set the IPV4 address of the interface as well as the netmask.
[ "Sets", "up", "the", "static", "IPV4", "configuration", "for", "the", "host", "only", "network", "interface", ".", "This", "allows", "the", "caller", "to", "set", "the", "IPV4", "address", "of", "the", "interface", "as", "well", "as", "the", "netmask", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/host_network_interface.rb#L106-L111
21,854
mitchellh/virtualbox
lib/virtualbox/dhcp_server.rb
VirtualBox.DHCPServer.destroy
def destroy parent.lib.virtualbox.remove_dhcp_server(interface) parent_collection.delete(self, true) true end
ruby
def destroy parent.lib.virtualbox.remove_dhcp_server(interface) parent_collection.delete(self, true) true end
[ "def", "destroy", "parent", ".", "lib", ".", "virtualbox", ".", "remove_dhcp_server", "(", "interface", ")", "parent_collection", ".", "delete", "(", "self", ",", "true", ")", "true", "end" ]
Removes the DHCP server.
[ "Removes", "the", "DHCP", "server", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/dhcp_server.rb#L73-L77
21,855
mitchellh/virtualbox
lib/virtualbox/dhcp_server.rb
VirtualBox.DHCPServer.host_network
def host_network return nil unless network_name =~ /^HostInterfaceNetworking-(.+?)$/ parent.host.network_interfaces.detect do |i| i.interface_type == :host_only && i.name == $1.to_s end end
ruby
def host_network return nil unless network_name =~ /^HostInterfaceNetworking-(.+?)$/ parent.host.network_interfaces.detect do |i| i.interface_type == :host_only && i.name == $1.to_s end end
[ "def", "host_network", "return", "nil", "unless", "network_name", "=~", "/", "/", "parent", ".", "host", ".", "network_interfaces", ".", "detect", "do", "|", "i", "|", "i", ".", "interface_type", "==", ":host_only", "&&", "i", ".", "name", "==", "$1", ".", "to_s", "end", "end" ]
Returns the host network associated with this DHCP server, if it exists.
[ "Returns", "the", "host", "network", "associated", "with", "this", "DHCP", "server", "if", "it", "exists", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/dhcp_server.rb#L81-L87
21,856
mitchellh/virtualbox
lib/virtualbox/shared_folder.rb
VirtualBox.SharedFolder.save
def save return true if !new_record? && !changed? raise Exceptions::ValidationFailedException.new(errors) if !valid? if !new_record? # If its not a new record, any changes will require a new shared # folder to be created, so we first destroy it then recreate it. destroy(false) end create end
ruby
def save return true if !new_record? && !changed? raise Exceptions::ValidationFailedException.new(errors) if !valid? if !new_record? # If its not a new record, any changes will require a new shared # folder to be created, so we first destroy it then recreate it. destroy(false) end create end
[ "def", "save", "return", "true", "if", "!", "new_record?", "&&", "!", "changed?", "raise", "Exceptions", "::", "ValidationFailedException", ".", "new", "(", "errors", ")", "if", "!", "valid?", "if", "!", "new_record?", "# If its not a new record, any changes will require a new shared", "# folder to be created, so we first destroy it then recreate it.", "destroy", "(", "false", ")", "end", "create", "end" ]
Saves or creates a shared folder.
[ "Saves", "or", "creates", "a", "shared", "folder", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/shared_folder.rb#L164-L175
21,857
mitchellh/virtualbox
lib/virtualbox/shared_folder.rb
VirtualBox.SharedFolder.added_to_relationship
def added_to_relationship(proxy) was_clean = parent.nil? && !changed? write_attribute(:parent, proxy.parent) write_attribute(:parent_collection, proxy) # This keeps existing records not dirty when added to collection clear_dirty! if !new_record? && was_clean end
ruby
def added_to_relationship(proxy) was_clean = parent.nil? && !changed? write_attribute(:parent, proxy.parent) write_attribute(:parent_collection, proxy) # This keeps existing records not dirty when added to collection clear_dirty! if !new_record? && was_clean end
[ "def", "added_to_relationship", "(", "proxy", ")", "was_clean", "=", "parent", ".", "nil?", "&&", "!", "changed?", "write_attribute", "(", ":parent", ",", "proxy", ".", "parent", ")", "write_attribute", "(", ":parent_collection", ",", "proxy", ")", "# This keeps existing records not dirty when added to collection", "clear_dirty!", "if", "!", "new_record?", "&&", "was_clean", "end" ]
Relationship callback when added to a collection. This is automatically called by any relationship collection when this object is added.
[ "Relationship", "callback", "when", "added", "to", "a", "collection", ".", "This", "is", "automatically", "called", "by", "any", "relationship", "collection", "when", "this", "object", "is", "added", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/shared_folder.rb#L193-L201
21,858
mitchellh/virtualbox
lib/virtualbox/shared_folder.rb
VirtualBox.SharedFolder.destroy
def destroy(update_collection=true) parent.with_open_session do |session| machine = session.machine machine.remove_shared_folder(name) end # Remove it from it's parent collection parent_collection.delete(self, true) if parent_collection && update_collection # Mark as a new record so if it is saved again, it will create it new_record! end
ruby
def destroy(update_collection=true) parent.with_open_session do |session| machine = session.machine machine.remove_shared_folder(name) end # Remove it from it's parent collection parent_collection.delete(self, true) if parent_collection && update_collection # Mark as a new record so if it is saved again, it will create it new_record! end
[ "def", "destroy", "(", "update_collection", "=", "true", ")", "parent", ".", "with_open_session", "do", "|", "session", "|", "machine", "=", "session", ".", "machine", "machine", ".", "remove_shared_folder", "(", "name", ")", "end", "# Remove it from it's parent collection", "parent_collection", ".", "delete", "(", "self", ",", "true", ")", "if", "parent_collection", "&&", "update_collection", "# Mark as a new record so if it is saved again, it will create it", "new_record!", "end" ]
Destroys the shared folder. This doesn't actually delete the folder from the host system. Instead, it simply removes the mapping to the virtual machine, meaning it will no longer be possible to mount it from within the virtual machine.
[ "Destroys", "the", "shared", "folder", ".", "This", "doesn", "t", "actually", "delete", "the", "folder", "from", "the", "host", "system", ".", "Instead", "it", "simply", "removes", "the", "mapping", "to", "the", "virtual", "machine", "meaning", "it", "will", "no", "longer", "be", "possible", "to", "mount", "it", "from", "within", "the", "virtual", "machine", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/shared_folder.rb#L207-L218
21,859
mitchellh/virtualbox
lib/virtualbox/abstract_model.rb
VirtualBox.AbstractModel.errors
def errors self.class.relationships.inject(super) do |acc, data| name, options = data if options && options[:klass].respond_to?(:errors_for_relationship) errors = options[:klass].errors_for_relationship(self, relationship_data[name]) acc.merge!(name => errors) if errors && !errors.empty? end acc end end
ruby
def errors self.class.relationships.inject(super) do |acc, data| name, options = data if options && options[:klass].respond_to?(:errors_for_relationship) errors = options[:klass].errors_for_relationship(self, relationship_data[name]) acc.merge!(name => errors) if errors && !errors.empty? end acc end end
[ "def", "errors", "self", ".", "class", ".", "relationships", ".", "inject", "(", "super", ")", "do", "|", "acc", ",", "data", "|", "name", ",", "options", "=", "data", "if", "options", "&&", "options", "[", ":klass", "]", ".", "respond_to?", "(", ":errors_for_relationship", ")", "errors", "=", "options", "[", ":klass", "]", ".", "errors_for_relationship", "(", "self", ",", "relationship_data", "[", "name", "]", ")", "acc", ".", "merge!", "(", "name", "=>", "errors", ")", "if", "errors", "&&", "!", "errors", ".", "empty?", "end", "acc", "end", "end" ]
Returns the errors for a model.
[ "Returns", "the", "errors", "for", "a", "model", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/abstract_model.rb#L78-L89
21,860
mitchellh/virtualbox
lib/virtualbox/abstract_model.rb
VirtualBox.AbstractModel.validate
def validate(*args) # First clear all previous errors clear_errors # Then do the validations failed = false self.class.relationships.each do |name, options| next unless options && options[:klass].respond_to?(:validate_relationship) failed = true if !options[:klass].validate_relationship(self, relationship_data[name], *args) end return !failed end
ruby
def validate(*args) # First clear all previous errors clear_errors # Then do the validations failed = false self.class.relationships.each do |name, options| next unless options && options[:klass].respond_to?(:validate_relationship) failed = true if !options[:klass].validate_relationship(self, relationship_data[name], *args) end return !failed end
[ "def", "validate", "(", "*", "args", ")", "# First clear all previous errors", "clear_errors", "# Then do the validations", "failed", "=", "false", "self", ".", "class", ".", "relationships", ".", "each", "do", "|", "name", ",", "options", "|", "next", "unless", "options", "&&", "options", "[", ":klass", "]", ".", "respond_to?", "(", ":validate_relationship", ")", "failed", "=", "true", "if", "!", "options", "[", ":klass", "]", ".", "validate_relationship", "(", "self", ",", "relationship_data", "[", "name", "]", ",", "args", ")", "end", "return", "!", "failed", "end" ]
Validates the model and relationships.
[ "Validates", "the", "model", "and", "relationships", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/abstract_model.rb#L92-L104
21,861
mitchellh/virtualbox
lib/virtualbox/abstract_model.rb
VirtualBox.AbstractModel.save
def save(*args) # Go through changed attributes and call save_attribute for # those only changes.each do |key, values| save_attribute(key, values[1], *args) end # Go through and only save the loaded relationships, since # only those would be modified. self.class.relationships.each do |name, options| save_relationship(name, *args) end # No longer a new record @new_record = false true end
ruby
def save(*args) # Go through changed attributes and call save_attribute for # those only changes.each do |key, values| save_attribute(key, values[1], *args) end # Go through and only save the loaded relationships, since # only those would be modified. self.class.relationships.each do |name, options| save_relationship(name, *args) end # No longer a new record @new_record = false true end
[ "def", "save", "(", "*", "args", ")", "# Go through changed attributes and call save_attribute for", "# those only", "changes", ".", "each", "do", "|", "key", ",", "values", "|", "save_attribute", "(", "key", ",", "values", "[", "1", "]", ",", "args", ")", "end", "# Go through and only save the loaded relationships, since", "# only those would be modified.", "self", ".", "class", ".", "relationships", ".", "each", "do", "|", "name", ",", "options", "|", "save_relationship", "(", "name", ",", "args", ")", "end", "# No longer a new record", "@new_record", "=", "false", "true", "end" ]
Saves the model attributes and relationships. The method can be passed any arbitrary arguments, which are implementation specific (see {VM#save}, which does this).
[ "Saves", "the", "model", "attributes", "and", "relationships", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/abstract_model.rb#L110-L127
21,862
mitchellh/virtualbox
lib/virtualbox/forwarded_port.rb
VirtualBox.ForwardedPort.device
def device # Return the current or default value if it is: # * an existing record, since it was already mucked with, no need to # modify it again # * device setting changed, since we should return what the user set # it to # * If the parent is nil, since we can't infer the type without a parent return read_attribute(:device) if !new_record? || device_changed? || parent.nil? device_map = { :Am79C970A => "pcnet", :Am79C973 => "pcnet", :I82540EM => "e1000", :I82543GC => "e1000", :I82545EM => "e1000" } return device_map[parent.network_adapters[0].adapter_type] end
ruby
def device # Return the current or default value if it is: # * an existing record, since it was already mucked with, no need to # modify it again # * device setting changed, since we should return what the user set # it to # * If the parent is nil, since we can't infer the type without a parent return read_attribute(:device) if !new_record? || device_changed? || parent.nil? device_map = { :Am79C970A => "pcnet", :Am79C973 => "pcnet", :I82540EM => "e1000", :I82543GC => "e1000", :I82545EM => "e1000" } return device_map[parent.network_adapters[0].adapter_type] end
[ "def", "device", "# Return the current or default value if it is:", "# * an existing record, since it was already mucked with, no need to", "# modify it again", "# * device setting changed, since we should return what the user set", "# it to", "# * If the parent is nil, since we can't infer the type without a parent", "return", "read_attribute", "(", ":device", ")", "if", "!", "new_record?", "||", "device_changed?", "||", "parent", ".", "nil?", "device_map", "=", "{", ":Am79C970A", "=>", "\"pcnet\"", ",", ":Am79C973", "=>", "\"pcnet\"", ",", ":I82540EM", "=>", "\"e1000\"", ",", ":I82543GC", "=>", "\"e1000\"", ",", ":I82545EM", "=>", "\"e1000\"", "}", "return", "device_map", "[", "parent", ".", "network_adapters", "[", "0", "]", ".", "adapter_type", "]", "end" ]
Retrieves the device for the forwarded port. This tries to "do the right thing" depending on the first NIC of the VM parent by either setting the forwarded port type to "pcnet" or "e1000." If the device was already set manually, this method will simply return that value instead. @return [String] Device type for the forwarded port
[ "Retrieves", "the", "device", "for", "the", "forwarded", "port", ".", "This", "tries", "to", "do", "the", "right", "thing", "depending", "on", "the", "first", "NIC", "of", "the", "VM", "parent", "by", "either", "setting", "the", "forwarded", "port", "type", "to", "pcnet", "or", "e1000", ".", "If", "the", "device", "was", "already", "set", "manually", "this", "method", "will", "simply", "return", "that", "value", "instead", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/forwarded_port.rb#L144-L162
21,863
mitchellh/virtualbox
features/support/helpers.rb
VirtualBox.IntegrationHelpers.snapshot_map
def snapshot_map(snapshots, &block) applier = lambda do |snapshot| return if !snapshot || snapshot.empty? snapshot[:children].each do |child| applier.call(child) end block.call(snapshot) end applier.call(snapshots) end
ruby
def snapshot_map(snapshots, &block) applier = lambda do |snapshot| return if !snapshot || snapshot.empty? snapshot[:children].each do |child| applier.call(child) end block.call(snapshot) end applier.call(snapshots) end
[ "def", "snapshot_map", "(", "snapshots", ",", "&", "block", ")", "applier", "=", "lambda", "do", "|", "snapshot", "|", "return", "if", "!", "snapshot", "||", "snapshot", ".", "empty?", "snapshot", "[", ":children", "]", ".", "each", "do", "|", "child", "|", "applier", ".", "call", "(", "child", ")", "end", "block", ".", "call", "(", "snapshot", ")", "end", "applier", ".", "call", "(", "snapshots", ")", "end" ]
Applies a function to every snapshot.
[ "Applies", "a", "function", "to", "every", "snapshot", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/features/support/helpers.rb#L22-L34
21,864
mitchellh/virtualbox
lib/virtualbox/hard_drive.rb
VirtualBox.HardDrive.validate
def validate super medium_formats = Global.global.system_properties.medium_formats.collect { |mf| mf.id } validates_inclusion_of :format, :in => medium_formats, :message => "must be one of the following: #{medium_formats.join(', ')}." validates_presence_of :location max_vdi_size = Global.global.system_properties.info_vdi_size validates_inclusion_of :logical_size, :in => (0..max_vdi_size), :message => "must be between 0 and #{max_vdi_size}." end
ruby
def validate super medium_formats = Global.global.system_properties.medium_formats.collect { |mf| mf.id } validates_inclusion_of :format, :in => medium_formats, :message => "must be one of the following: #{medium_formats.join(', ')}." validates_presence_of :location max_vdi_size = Global.global.system_properties.info_vdi_size validates_inclusion_of :logical_size, :in => (0..max_vdi_size), :message => "must be between 0 and #{max_vdi_size}." end
[ "def", "validate", "super", "medium_formats", "=", "Global", ".", "global", ".", "system_properties", ".", "medium_formats", ".", "collect", "{", "|", "mf", "|", "mf", ".", "id", "}", "validates_inclusion_of", ":format", ",", ":in", "=>", "medium_formats", ",", ":message", "=>", "\"must be one of the following: #{medium_formats.join(', ')}.\"", "validates_presence_of", ":location", "max_vdi_size", "=", "Global", ".", "global", ".", "system_properties", ".", "info_vdi_size", "validates_inclusion_of", ":logical_size", ",", ":in", "=>", "(", "0", "..", "max_vdi_size", ")", ",", ":message", "=>", "\"must be between 0 and #{max_vdi_size}.\"", "end" ]
Validates a hard drive for the minimum attributes required to create or save.
[ "Validates", "a", "hard", "drive", "for", "the", "minimum", "attributes", "required", "to", "create", "or", "save", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/hard_drive.rb#L129-L139
21,865
mitchellh/virtualbox
lib/virtualbox/hard_drive.rb
VirtualBox.HardDrive.create
def create return false unless new_record? raise Exceptions::ValidationFailedException.new(errors) if !valid? # Create the new Hard Disk medium new_medium = create_hard_disk_medium(location, format) # Create the storage on the host system new_medium.create_base_storage(logical_size, :standard).wait_for_completion(-1) # Update the current Hard Drive instance with the uuid and # other attributes assigned after storage was written write_attribute(:interface, new_medium) initialize_attributes(new_medium) # If the uuid is present, then everything worked uuid && !uuid.to_s.empty? end
ruby
def create return false unless new_record? raise Exceptions::ValidationFailedException.new(errors) if !valid? # Create the new Hard Disk medium new_medium = create_hard_disk_medium(location, format) # Create the storage on the host system new_medium.create_base_storage(logical_size, :standard).wait_for_completion(-1) # Update the current Hard Drive instance with the uuid and # other attributes assigned after storage was written write_attribute(:interface, new_medium) initialize_attributes(new_medium) # If the uuid is present, then everything worked uuid && !uuid.to_s.empty? end
[ "def", "create", "return", "false", "unless", "new_record?", "raise", "Exceptions", "::", "ValidationFailedException", ".", "new", "(", "errors", ")", "if", "!", "valid?", "# Create the new Hard Disk medium", "new_medium", "=", "create_hard_disk_medium", "(", "location", ",", "format", ")", "# Create the storage on the host system", "new_medium", ".", "create_base_storage", "(", "logical_size", ",", ":standard", ")", ".", "wait_for_completion", "(", "-", "1", ")", "# Update the current Hard Drive instance with the uuid and", "# other attributes assigned after storage was written", "write_attribute", "(", ":interface", ",", "new_medium", ")", "initialize_attributes", "(", "new_medium", ")", "# If the uuid is present, then everything worked", "uuid", "&&", "!", "uuid", ".", "to_s", ".", "empty?", "end" ]
Clone hard drive, possibly also converting formats. All formats supported by your local VirtualBox installation are supported here. If no format is specified, the systems default will be used. @param [String] outputfile The output file. This can be a full path or just a filename. If its just a filename, it will be placed in the default hard drives directory. Should not be present already. @param [String] format The format to convert to. If not present, the systems default will be used. @return [HardDrive] The new, cloned hard drive, or nil on failure. Creates a new hard drive. **This method should NEVER be called. Call {#save} instead.** @return [Boolean] True if command was successful, false otherwise.
[ "Clone", "hard", "drive", "possibly", "also", "converting", "formats", ".", "All", "formats", "supported", "by", "your", "local", "VirtualBox", "installation", "are", "supported", "here", ".", "If", "no", "format", "is", "specified", "the", "systems", "default", "will", "be", "used", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/hard_drive.rb#L206-L223
21,866
mitchellh/virtualbox
lib/virtualbox/hard_drive.rb
VirtualBox.HardDrive.save
def save return true if !new_record? && !changed? raise Exceptions::ValidationFailedException.new(errors) if !valid? if new_record? create # Create a new hard drive else # Mediums like Hard Drives are not updatable, they need to be recreated # Because Hard Drives contain info and paritions, it's easier to error # out now than try and do some complicated logic msg = "Hard Drives cannot be updated. You need to create one from scratch." raise Exceptions::MediumNotUpdatableException.new(msg) end end
ruby
def save return true if !new_record? && !changed? raise Exceptions::ValidationFailedException.new(errors) if !valid? if new_record? create # Create a new hard drive else # Mediums like Hard Drives are not updatable, they need to be recreated # Because Hard Drives contain info and paritions, it's easier to error # out now than try and do some complicated logic msg = "Hard Drives cannot be updated. You need to create one from scratch." raise Exceptions::MediumNotUpdatableException.new(msg) end end
[ "def", "save", "return", "true", "if", "!", "new_record?", "&&", "!", "changed?", "raise", "Exceptions", "::", "ValidationFailedException", ".", "new", "(", "errors", ")", "if", "!", "valid?", "if", "new_record?", "create", "# Create a new hard drive", "else", "# Mediums like Hard Drives are not updatable, they need to be recreated", "# Because Hard Drives contain info and paritions, it's easier to error", "# out now than try and do some complicated logic", "msg", "=", "\"Hard Drives cannot be updated. You need to create one from scratch.\"", "raise", "Exceptions", "::", "MediumNotUpdatableException", ".", "new", "(", "msg", ")", "end", "end" ]
Saves the hard drive object. If the hard drive is new, this will create a new hard drive. Otherwise, it will save any other details about the existing hard drive. Currently, **saving existing hard drives does nothing**. This is a limitation of VirtualBox, rather than the library itself. @return [Boolean] True if command was successful, false otherwise.
[ "Saves", "the", "hard", "drive", "object", ".", "If", "the", "hard", "drive", "is", "new", "this", "will", "create", "a", "new", "hard", "drive", ".", "Otherwise", "it", "will", "save", "any", "other", "details", "about", "the", "existing", "hard", "drive", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/hard_drive.rb#L233-L246
21,867
mitchellh/virtualbox
lib/virtualbox/network_adapter.rb
VirtualBox.NetworkAdapter.initialize_attributes
def initialize_attributes(parent, inetwork) # Set the parent and interface write_attribute(:parent, parent) write_attribute(:interface, inetwork) # Load the interface attributes load_interface_attributes(inetwork) # Clear dirtiness, since this should only be called initially and # therefore shouldn't affect dirtiness clear_dirty! # But this is an existing record existing_record! end
ruby
def initialize_attributes(parent, inetwork) # Set the parent and interface write_attribute(:parent, parent) write_attribute(:interface, inetwork) # Load the interface attributes load_interface_attributes(inetwork) # Clear dirtiness, since this should only be called initially and # therefore shouldn't affect dirtiness clear_dirty! # But this is an existing record existing_record! end
[ "def", "initialize_attributes", "(", "parent", ",", "inetwork", ")", "# Set the parent and interface", "write_attribute", "(", ":parent", ",", "parent", ")", "write_attribute", "(", ":interface", ",", "inetwork", ")", "# Load the interface attributes", "load_interface_attributes", "(", "inetwork", ")", "# Clear dirtiness, since this should only be called initially and", "# therefore shouldn't affect dirtiness", "clear_dirty!", "# But this is an existing record", "existing_record!", "end" ]
Initializes the attributes of an existing shared folder.
[ "Initializes", "the", "attributes", "of", "an", "existing", "shared", "folder", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/network_adapter.rb#L103-L117
21,868
mitchellh/virtualbox
lib/virtualbox/network_adapter.rb
VirtualBox.NetworkAdapter.host_interface_object
def host_interface_object VirtualBox::Global.global.host.network_interfaces.find do |ni| ni.name == host_only_interface end end
ruby
def host_interface_object VirtualBox::Global.global.host.network_interfaces.find do |ni| ni.name == host_only_interface end end
[ "def", "host_interface_object", "VirtualBox", "::", "Global", ".", "global", ".", "host", ".", "network_interfaces", ".", "find", "do", "|", "ni", "|", "ni", ".", "name", "==", "host_only_interface", "end", "end" ]
Gets the host interface object associated with the class if it exists.
[ "Gets", "the", "host", "interface", "object", "associated", "with", "the", "class", "if", "it", "exists", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/network_adapter.rb#L128-L132
21,869
mitchellh/virtualbox
lib/virtualbox/network_adapter.rb
VirtualBox.NetworkAdapter.bridged_interface_object
def bridged_interface_object VirtualBox::Global.global.host.network_interfaces.find do |ni| ni.name == bridged_interface end end
ruby
def bridged_interface_object VirtualBox::Global.global.host.network_interfaces.find do |ni| ni.name == bridged_interface end end
[ "def", "bridged_interface_object", "VirtualBox", "::", "Global", ".", "global", ".", "host", ".", "network_interfaces", ".", "find", "do", "|", "ni", "|", "ni", ".", "name", "==", "bridged_interface", "end", "end" ]
Gets the bridged interface object associated with the class if it exists.
[ "Gets", "the", "bridged", "interface", "object", "associated", "with", "the", "class", "if", "it", "exists", "." ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/network_adapter.rb#L136-L140
21,870
mitchellh/virtualbox
lib/virtualbox/network_adapter.rb
VirtualBox.NetworkAdapter.modify_adapter
def modify_adapter parent_machine.with_open_session do |session| machine = session.machine yield machine.get_network_adapter(slot) end end
ruby
def modify_adapter parent_machine.with_open_session do |session| machine = session.machine yield machine.get_network_adapter(slot) end end
[ "def", "modify_adapter", "parent_machine", ".", "with_open_session", "do", "|", "session", "|", "machine", "=", "session", ".", "machine", "yield", "machine", ".", "get_network_adapter", "(", "slot", ")", "end", "end" ]
Opens a session, yields the adapter and then saves the machine at the end
[ "Opens", "a", "session", "yields", "the", "adapter", "and", "then", "saves", "the", "machine", "at", "the", "end" ]
5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24
https://github.com/mitchellh/virtualbox/blob/5d5dfb649077dc72846ca4cd7eb76ea9bbc99b24/lib/virtualbox/network_adapter.rb#L152-L157
21,871
opal/opal-jquery
lib/opal/jquery/rspec.rb
Browser.RSpecHelpers.html
def html(html_string='') html = %Q{<div id="opal-jquery-test-div">#{html_string}</div>} before do @_spec_html = Element.parse(html) @_spec_html.append_to_body end after { @_spec_html.remove } end
ruby
def html(html_string='') html = %Q{<div id="opal-jquery-test-div">#{html_string}</div>} before do @_spec_html = Element.parse(html) @_spec_html.append_to_body end after { @_spec_html.remove } end
[ "def", "html", "(", "html_string", "=", "''", ")", "html", "=", "%Q{<div id=\"opal-jquery-test-div\">#{html_string}</div>}", "before", "do", "@_spec_html", "=", "Element", ".", "parse", "(", "html", ")", "@_spec_html", ".", "append_to_body", "end", "after", "{", "@_spec_html", ".", "remove", "}", "end" ]
Add some html code to the body tag ready for testing. This will be added before each test, then removed after each test. It is convenient for adding html setup quickly. The code is wrapped inside a div, which is directly inside the body element. describe "DOM feature" do html <<-HTML <div id="foo"></div> HTML it "foo should exist" do Document["#foo"] end end @param [String] html_string html content to add
[ "Add", "some", "html", "code", "to", "the", "body", "tag", "ready", "for", "testing", ".", "This", "will", "be", "added", "before", "each", "test", "then", "removed", "after", "each", "test", ".", "It", "is", "convenient", "for", "adding", "html", "setup", "quickly", ".", "The", "code", "is", "wrapped", "inside", "a", "div", "which", "is", "directly", "inside", "the", "body", "element", "." ]
a00b5546520e3872470962c7392eb1a1a4236112
https://github.com/opal/opal-jquery/blob/a00b5546520e3872470962c7392eb1a1a4236112/lib/opal/jquery/rspec.rb#L50-L59
21,872
oleganza/btcruby
lib/btcruby/script/script.rb
BTC.Script.versioned_script?
def versioned_script? return chunks.size == 1 && chunks[0].pushdata? && chunks[0].canonical? && chunks[0].pushdata.bytesize > 2 end
ruby
def versioned_script? return chunks.size == 1 && chunks[0].pushdata? && chunks[0].canonical? && chunks[0].pushdata.bytesize > 2 end
[ "def", "versioned_script?", "return", "chunks", ".", "size", "==", "1", "&&", "chunks", "[", "0", "]", ".", "pushdata?", "&&", "chunks", "[", "0", "]", ".", "canonical?", "&&", "chunks", "[", "0", "]", ".", "pushdata", ".", "bytesize", ">", "2", "end" ]
Returns true if this is an output script wrapped in a versioned pushdata for segwit softfork.
[ "Returns", "true", "if", "this", "is", "an", "output", "script", "wrapped", "in", "a", "versioned", "pushdata", "for", "segwit", "softfork", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/script/script.rb#L94-L99
21,873
oleganza/btcruby
lib/btcruby/script/script.rb
BTC.Script.open_assets_marker?
def open_assets_marker? return false if !op_return_data_only_script? data = op_return_data return false if !data || data.bytesize < 6 if data[0, AssetMarker::PREFIX_V1.bytesize] == AssetMarker::PREFIX_V1 return true end false end
ruby
def open_assets_marker? return false if !op_return_data_only_script? data = op_return_data return false if !data || data.bytesize < 6 if data[0, AssetMarker::PREFIX_V1.bytesize] == AssetMarker::PREFIX_V1 return true end false end
[ "def", "open_assets_marker?", "return", "false", "if", "!", "op_return_data_only_script?", "data", "=", "op_return_data", "return", "false", "if", "!", "data", "||", "data", ".", "bytesize", "<", "6", "if", "data", "[", "0", ",", "AssetMarker", "::", "PREFIX_V1", ".", "bytesize", "]", "==", "AssetMarker", "::", "PREFIX_V1", "return", "true", "end", "false", "end" ]
Returns `true` if this script may be a valid OpenAssets marker. Only checks the prefix and minimal length, does not validate the content. Use this method to quickly filter out non-asset transactions.
[ "Returns", "true", "if", "this", "script", "may", "be", "a", "valid", "OpenAssets", "marker", ".", "Only", "checks", "the", "prefix", "and", "minimal", "length", "does", "not", "validate", "the", "content", ".", "Use", "this", "method", "to", "quickly", "filter", "out", "non", "-", "asset", "transactions", "." ]
0aa0231a29dfc3c9f7fc54b39686aed10b6d9808
https://github.com/oleganza/btcruby/blob/0aa0231a29dfc3c9f7fc54b39686aed10b6d9808/lib/btcruby/script/script.rb#L236-L244
21,874
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?", "# 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" ]
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
21,875
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
21,876
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
21,877
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
21,878
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\"", "# 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" ]
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
21,879
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", ")", "# 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" ]
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
21,880
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
21,881
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
21,882
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 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" ]
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
21,883
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", "# TODO: parse other styles", "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
21,884
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", "# TODO: support other styles", "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
21,885
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", "# 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" ]
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
21,886
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", "# 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" ]
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
21,887
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
21,888
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
21,889
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
21,890
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
21,891
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
21,892
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", ")", "# 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" ]
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
21,893
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
21,894
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", ")", "}", "# [[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" ]
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
21,895
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", "# 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" ]
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
21,896
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
21,897
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", ")", "# 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" ]
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
21,898
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
21,899
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