repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
infosimples/deathbycaptcha | lib/deathbycaptcha/client/socket.rb | DeathByCaptcha.Client::Socket.create_socket | def create_socket
socket = ::Socket.new(::Socket::AF_INET, ::Socket::SOCK_STREAM, 0)
sockaddr = ::Socket.sockaddr_in(PORTS.sample, self.hostname)
begin # emulate blocking connect
socket.connect_nonblock(sockaddr)
rescue IO::WaitWritable
IO.select(nil, [socket]) # wait 3-way handshake completion
begin
socket.connect_nonblock(sockaddr) # check connection failure
rescue Errno::EISCONN
end
end
socket
end | ruby | def create_socket
socket = ::Socket.new(::Socket::AF_INET, ::Socket::SOCK_STREAM, 0)
sockaddr = ::Socket.sockaddr_in(PORTS.sample, self.hostname)
begin # emulate blocking connect
socket.connect_nonblock(sockaddr)
rescue IO::WaitWritable
IO.select(nil, [socket]) # wait 3-way handshake completion
begin
socket.connect_nonblock(sockaddr) # check connection failure
rescue Errno::EISCONN
end
end
socket
end | [
"def",
"create_socket",
"socket",
"=",
"::",
"Socket",
".",
"new",
"(",
"::",
"Socket",
"::",
"AF_INET",
",",
"::",
"Socket",
"::",
"SOCK_STREAM",
",",
"0",
")",
"sockaddr",
"=",
"::",
"Socket",
".",
"sockaddr_in",
"(",
"PORTS",
".",
"sample",
",",
"self",
".",
"hostname",
")",
"begin",
"socket",
".",
"connect_nonblock",
"(",
"sockaddr",
")",
"rescue",
"IO",
"::",
"WaitWritable",
"IO",
".",
"select",
"(",
"nil",
",",
"[",
"socket",
"]",
")",
"begin",
"socket",
".",
"connect_nonblock",
"(",
"sockaddr",
")",
"rescue",
"Errno",
"::",
"EISCONN",
"end",
"end",
"socket",
"end"
]
| Create a new socket connection with DeathByCaptcha API.
This method is necessary because Ruby 1.9.7 doesn't support connection
timeout and only Ruby 2.2.0 fixes a bug with unsafe sockets threads.
In Ruby >= 2.2.0, this could be implemented as simply as:
::Socket.tcp(HOST, PORTS.sample, connect_timeout: 0) | [
"Create",
"a",
"new",
"socket",
"connection",
"with",
"DeathByCaptcha",
"API",
".",
"This",
"method",
"is",
"necessary",
"because",
"Ruby",
"1",
".",
"9",
".",
"7",
"doesn",
"t",
"support",
"connection",
"timeout",
"and",
"only",
"Ruby",
"2",
".",
"2",
".",
"0",
"fixes",
"a",
"bug",
"with",
"unsafe",
"sockets",
"threads",
"."
]
| b6fc9503025b24adaffb8c28843995a7f1715cb7 | https://github.com/infosimples/deathbycaptcha/blob/b6fc9503025b24adaffb8c28843995a7f1715cb7/lib/deathbycaptcha/client/socket.rb#L116-L129 | train |
infosimples/deathbycaptcha | lib/deathbycaptcha/client/http.rb | DeathByCaptcha.Client::HTTP.perform | def perform(action, method = :get, payload = {})
payload.merge!(username: self.username, password: self.password)
headers = { 'User-Agent' => DeathByCaptcha::API_VERSION }
if method == :post
uri = URI("http://#{self.hostname}/api/#{action}")
req = Net::HTTP::Post.new(uri.request_uri, headers)
req.set_form_data(payload)
elsif method == :post_multipart
uri = URI("http://#{self.hostname}/api/#{action}")
req = Net::HTTP::Post.new(uri.request_uri, headers)
boundary, body = prepare_multipart_data(payload)
req.content_type = "multipart/form-data; boundary=#{boundary}"
req.body = body
else
uri = URI("http://#{self.hostname}/api/#{action}?#{URI.encode_www_form(payload)}")
req = Net::HTTP::Get.new(uri.request_uri, headers)
end
res = Net::HTTP.start(uri.hostname, uri.port) do |http|
http.request(req)
end
case res
when Net::HTTPSuccess, Net::HTTPSeeOther
Hash[URI.decode_www_form(res.body)]
when Net::HTTPForbidden
raise DeathByCaptcha::APIForbidden
when Net::HTTPBadRequest
raise DeathByCaptcha::APIBadRequest
when Net::HTTPRequestEntityTooLarge
raise DeathByCaptcha::APICaptchaTooLarge
when Net::HTTPServiceUnavailable
raise DeathByCaptcha::APIServiceUnavailable
else
raise DeathByCaptcha::APIResponseError.new(res.body)
end
end | ruby | def perform(action, method = :get, payload = {})
payload.merge!(username: self.username, password: self.password)
headers = { 'User-Agent' => DeathByCaptcha::API_VERSION }
if method == :post
uri = URI("http://#{self.hostname}/api/#{action}")
req = Net::HTTP::Post.new(uri.request_uri, headers)
req.set_form_data(payload)
elsif method == :post_multipart
uri = URI("http://#{self.hostname}/api/#{action}")
req = Net::HTTP::Post.new(uri.request_uri, headers)
boundary, body = prepare_multipart_data(payload)
req.content_type = "multipart/form-data; boundary=#{boundary}"
req.body = body
else
uri = URI("http://#{self.hostname}/api/#{action}?#{URI.encode_www_form(payload)}")
req = Net::HTTP::Get.new(uri.request_uri, headers)
end
res = Net::HTTP.start(uri.hostname, uri.port) do |http|
http.request(req)
end
case res
when Net::HTTPSuccess, Net::HTTPSeeOther
Hash[URI.decode_www_form(res.body)]
when Net::HTTPForbidden
raise DeathByCaptcha::APIForbidden
when Net::HTTPBadRequest
raise DeathByCaptcha::APIBadRequest
when Net::HTTPRequestEntityTooLarge
raise DeathByCaptcha::APICaptchaTooLarge
when Net::HTTPServiceUnavailable
raise DeathByCaptcha::APIServiceUnavailable
else
raise DeathByCaptcha::APIResponseError.new(res.body)
end
end | [
"def",
"perform",
"(",
"action",
",",
"method",
"=",
":get",
",",
"payload",
"=",
"{",
"}",
")",
"payload",
".",
"merge!",
"(",
"username",
":",
"self",
".",
"username",
",",
"password",
":",
"self",
".",
"password",
")",
"headers",
"=",
"{",
"'User-Agent'",
"=>",
"DeathByCaptcha",
"::",
"API_VERSION",
"}",
"if",
"method",
"==",
":post",
"uri",
"=",
"URI",
"(",
"\"http://#{self.hostname}/api/#{action}\"",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"uri",
".",
"request_uri",
",",
"headers",
")",
"req",
".",
"set_form_data",
"(",
"payload",
")",
"elsif",
"method",
"==",
":post_multipart",
"uri",
"=",
"URI",
"(",
"\"http://#{self.hostname}/api/#{action}\"",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Post",
".",
"new",
"(",
"uri",
".",
"request_uri",
",",
"headers",
")",
"boundary",
",",
"body",
"=",
"prepare_multipart_data",
"(",
"payload",
")",
"req",
".",
"content_type",
"=",
"\"multipart/form-data; boundary=#{boundary}\"",
"req",
".",
"body",
"=",
"body",
"else",
"uri",
"=",
"URI",
"(",
"\"http://#{self.hostname}/api/#{action}?#{URI.encode_www_form(payload)}\"",
")",
"req",
"=",
"Net",
"::",
"HTTP",
"::",
"Get",
".",
"new",
"(",
"uri",
".",
"request_uri",
",",
"headers",
")",
"end",
"res",
"=",
"Net",
"::",
"HTTP",
".",
"start",
"(",
"uri",
".",
"hostname",
",",
"uri",
".",
"port",
")",
"do",
"|",
"http",
"|",
"http",
".",
"request",
"(",
"req",
")",
"end",
"case",
"res",
"when",
"Net",
"::",
"HTTPSuccess",
",",
"Net",
"::",
"HTTPSeeOther",
"Hash",
"[",
"URI",
".",
"decode_www_form",
"(",
"res",
".",
"body",
")",
"]",
"when",
"Net",
"::",
"HTTPForbidden",
"raise",
"DeathByCaptcha",
"::",
"APIForbidden",
"when",
"Net",
"::",
"HTTPBadRequest",
"raise",
"DeathByCaptcha",
"::",
"APIBadRequest",
"when",
"Net",
"::",
"HTTPRequestEntityTooLarge",
"raise",
"DeathByCaptcha",
"::",
"APICaptchaTooLarge",
"when",
"Net",
"::",
"HTTPServiceUnavailable",
"raise",
"DeathByCaptcha",
"::",
"APIServiceUnavailable",
"else",
"raise",
"DeathByCaptcha",
"::",
"APIResponseError",
".",
"new",
"(",
"res",
".",
"body",
")",
"end",
"end"
]
| Perform an HTTP request to the DeathByCaptcha API.
@param [String] action API method name.
@param [Symbol] method HTTP method (:get, :post, :post_multipart).
@param [Hash] payload Data to be sent through the HTTP request.
@return [Hash] Response from the DeathByCaptcha API. | [
"Perform",
"an",
"HTTP",
"request",
"to",
"the",
"DeathByCaptcha",
"API",
"."
]
| b6fc9503025b24adaffb8c28843995a7f1715cb7 | https://github.com/infosimples/deathbycaptcha/blob/b6fc9503025b24adaffb8c28843995a7f1715cb7/lib/deathbycaptcha/client/http.rb#L86-L125 | train |
phcdevworks/phc-contactor | app/controllers/phccontactor/messages_controller.rb | Phccontactor.MessagesController.create | def create
@message = Message.new(message_params)
if @message.valid?
MessageMailer.message_me(@message).deliver_now
redirect_to new_message_path, notice: "Thank you for your message."
else
render :new
end
end | ruby | def create
@message = Message.new(message_params)
if @message.valid?
MessageMailer.message_me(@message).deliver_now
redirect_to new_message_path, notice: "Thank you for your message."
else
render :new
end
end | [
"def",
"create",
"@message",
"=",
"Message",
".",
"new",
"(",
"message_params",
")",
"if",
"@message",
".",
"valid?",
"MessageMailer",
".",
"message_me",
"(",
"@message",
")",
".",
"deliver_now",
"redirect_to",
"new_message_path",
",",
"notice",
":",
"\"Thank you for your message.\"",
"else",
"render",
":new",
"end",
"end"
]
| Create Message from Info Entered | [
"Create",
"Message",
"from",
"Info",
"Entered"
]
| f7aaa1311cba592347a674c0198d86bc7c4660a7 | https://github.com/phcdevworks/phc-contactor/blob/f7aaa1311cba592347a674c0198d86bc7c4660a7/app/controllers/phccontactor/messages_controller.rb#L12-L21 | train |
phcdevworks/phc-contactor | app/mailers/phccontactor/message_mailer.rb | Phccontactor.MessageMailer.message_me | def message_me(msg)
@msg = msg
mail from: @msg.email, subject: @msg.subject, body: @msg.content
end | ruby | def message_me(msg)
@msg = msg
mail from: @msg.email, subject: @msg.subject, body: @msg.content
end | [
"def",
"message_me",
"(",
"msg",
")",
"@msg",
"=",
"msg",
"mail",
"from",
":",
"@msg",
".",
"email",
",",
"subject",
":",
"@msg",
".",
"subject",
",",
"body",
":",
"@msg",
".",
"content",
"end"
]
| Put Togther Messange | [
"Put",
"Togther",
"Messange"
]
| f7aaa1311cba592347a674c0198d86bc7c4660a7 | https://github.com/phcdevworks/phc-contactor/blob/f7aaa1311cba592347a674c0198d86bc7c4660a7/app/mailers/phccontactor/message_mailer.rb#L8-L11 | train |
gsamokovarov/rvt | lib/rvt/slave.rb | RVT.Slave.send_input | def send_input(input)
raise ArgumentError if input.nil? or input.try(:empty?)
input.each_char { |char| @input.putc(char) }
end | ruby | def send_input(input)
raise ArgumentError if input.nil? or input.try(:empty?)
input.each_char { |char| @input.putc(char) }
end | [
"def",
"send_input",
"(",
"input",
")",
"raise",
"ArgumentError",
"if",
"input",
".",
"nil?",
"or",
"input",
".",
"try",
"(",
":empty?",
")",
"input",
".",
"each_char",
"{",
"|",
"char",
"|",
"@input",
".",
"putc",
"(",
"char",
")",
"}",
"end"
]
| Sends input to the slave process STDIN.
Returns immediately. | [
"Sends",
"input",
"to",
"the",
"slave",
"process",
"STDIN",
"."
]
| 5fc5e331c250696acaab4a1812fdd12c3e08d8d4 | https://github.com/gsamokovarov/rvt/blob/5fc5e331c250696acaab4a1812fdd12c3e08d8d4/lib/rvt/slave.rb#L58-L61 | train |
gsamokovarov/rvt | lib/rvt/slave.rb | RVT.Slave.pending_output | def pending_output(chunk_len = 49152)
# Returns nil if there is no pending output.
return unless pending_output?
pending = String.new
while chunk = @output.read_nonblock(chunk_len)
pending << chunk
end
pending.force_encoding('UTF-8')
rescue IO::WaitReadable
pending.force_encoding('UTF-8')
rescue
raise Closed if READING_ON_CLOSED_END_ERRORS.any? { |exc| $!.is_a?(exc) }
end | ruby | def pending_output(chunk_len = 49152)
# Returns nil if there is no pending output.
return unless pending_output?
pending = String.new
while chunk = @output.read_nonblock(chunk_len)
pending << chunk
end
pending.force_encoding('UTF-8')
rescue IO::WaitReadable
pending.force_encoding('UTF-8')
rescue
raise Closed if READING_ON_CLOSED_END_ERRORS.any? { |exc| $!.is_a?(exc) }
end | [
"def",
"pending_output",
"(",
"chunk_len",
"=",
"49152",
")",
"return",
"unless",
"pending_output?",
"pending",
"=",
"String",
".",
"new",
"while",
"chunk",
"=",
"@output",
".",
"read_nonblock",
"(",
"chunk_len",
")",
"pending",
"<<",
"chunk",
"end",
"pending",
".",
"force_encoding",
"(",
"'UTF-8'",
")",
"rescue",
"IO",
"::",
"WaitReadable",
"pending",
".",
"force_encoding",
"(",
"'UTF-8'",
")",
"rescue",
"raise",
"Closed",
"if",
"READING_ON_CLOSED_END_ERRORS",
".",
"any?",
"{",
"|",
"exc",
"|",
"$!",
".",
"is_a?",
"(",
"exc",
")",
"}",
"end"
]
| Gets the pending output of the process.
The pending output is read in an non blocking way by chunks, in the size
of +chunk_len+. By default, +chunk_len+ is 49152 bytes.
Returns +nil+, if there is no pending output at the moment. Otherwise,
returns the output that hasn't been read since the last invocation.
Raises Errno:EIO on closed output stream. This can happen if the
underlying process exits. | [
"Gets",
"the",
"pending",
"output",
"of",
"the",
"process",
"."
]
| 5fc5e331c250696acaab4a1812fdd12c3e08d8d4 | https://github.com/gsamokovarov/rvt/blob/5fc5e331c250696acaab4a1812fdd12c3e08d8d4/lib/rvt/slave.rb#L83-L96 | train |
gocardless/gocardless-legacy-ruby | lib/gocardless/utils.rb | GoCardless.Utils.flatten_params | def flatten_params(obj, ns=nil)
case obj
when Hash
pairs = obj.map { |k,v| flatten_params(v, ns ? "#{ns}[#{k}]" : k) }
pairs.empty? ? [] : pairs.inject(&:+)
when Array
obj.map { |v| flatten_params(v, "#{ns}[]") }.inject(&:+) || []
when Time
[[ns.to_s, iso_format_time(obj)]]
else
[[ns.to_s, obj.to_s]]
end
end | ruby | def flatten_params(obj, ns=nil)
case obj
when Hash
pairs = obj.map { |k,v| flatten_params(v, ns ? "#{ns}[#{k}]" : k) }
pairs.empty? ? [] : pairs.inject(&:+)
when Array
obj.map { |v| flatten_params(v, "#{ns}[]") }.inject(&:+) || []
when Time
[[ns.to_s, iso_format_time(obj)]]
else
[[ns.to_s, obj.to_s]]
end
end | [
"def",
"flatten_params",
"(",
"obj",
",",
"ns",
"=",
"nil",
")",
"case",
"obj",
"when",
"Hash",
"pairs",
"=",
"obj",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"flatten_params",
"(",
"v",
",",
"ns",
"?",
"\"#{ns}[#{k}]\"",
":",
"k",
")",
"}",
"pairs",
".",
"empty?",
"?",
"[",
"]",
":",
"pairs",
".",
"inject",
"(",
"&",
":+",
")",
"when",
"Array",
"obj",
".",
"map",
"{",
"|",
"v",
"|",
"flatten_params",
"(",
"v",
",",
"\"#{ns}[]\"",
")",
"}",
".",
"inject",
"(",
"&",
":+",
")",
"||",
"[",
"]",
"when",
"Time",
"[",
"[",
"ns",
".",
"to_s",
",",
"iso_format_time",
"(",
"obj",
")",
"]",
"]",
"else",
"[",
"[",
"ns",
".",
"to_s",
",",
"obj",
".",
"to_s",
"]",
"]",
"end",
"end"
]
| Flatten a hash containing nested hashes and arrays to a non-nested array
of key-value pairs.
Examples:
flatten_params(a: 'b')
# => [['a', 'b']]
flatten_params(a: ['b', 'c'])
# => [['a[]', 'b'], ['a[]', 'c']]
flatten_params(a: {b: 'c'})
# => [['a[b]', 'c']]
@param [Hash] obj the hash to flatten
@return [Array] an array of key-value pairs (arrays of two strings) | [
"Flatten",
"a",
"hash",
"containing",
"nested",
"hashes",
"and",
"arrays",
"to",
"a",
"non",
"-",
"nested",
"array",
"of",
"key",
"-",
"value",
"pairs",
"."
]
| cf141f235eec43909ba68866c283803f84d6bc89 | https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/utils.rb#L58-L70 | train |
gocardless/gocardless-legacy-ruby | lib/gocardless/utils.rb | GoCardless.Utils.iso_format_time | def iso_format_time(time)
return time unless time.is_a? Time or time.is_a? Date
time = time.getutc if time.is_a? Time
time = time.new_offset(0) if time.is_a? DateTime
time.strftime('%Y-%m-%dT%H:%M:%SZ')
end | ruby | def iso_format_time(time)
return time unless time.is_a? Time or time.is_a? Date
time = time.getutc if time.is_a? Time
time = time.new_offset(0) if time.is_a? DateTime
time.strftime('%Y-%m-%dT%H:%M:%SZ')
end | [
"def",
"iso_format_time",
"(",
"time",
")",
"return",
"time",
"unless",
"time",
".",
"is_a?",
"Time",
"or",
"time",
".",
"is_a?",
"Date",
"time",
"=",
"time",
".",
"getutc",
"if",
"time",
".",
"is_a?",
"Time",
"time",
"=",
"time",
".",
"new_offset",
"(",
"0",
")",
"if",
"time",
".",
"is_a?",
"DateTime",
"time",
".",
"strftime",
"(",
"'%Y-%m-%dT%H:%M:%SZ'",
")",
"end"
]
| Format a Time object according to ISO 8601, and convert to UTC.
@param [Time] time the time object to format
@return [String] the ISO-formatted time | [
"Format",
"a",
"Time",
"object",
"according",
"to",
"ISO",
"8601",
"and",
"convert",
"to",
"UTC",
"."
]
| cf141f235eec43909ba68866c283803f84d6bc89 | https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/utils.rb#L120-L125 | train |
gocardless/gocardless-legacy-ruby | lib/gocardless/utils.rb | GoCardless.Utils.stringify_times | def stringify_times(obj)
case obj
when Hash
Hash[obj.map { |k,v| [k, stringify_times(v)] }]
when Array
obj.map { |v| stringify_times(v) }
else
iso_format_time(obj)
end
end | ruby | def stringify_times(obj)
case obj
when Hash
Hash[obj.map { |k,v| [k, stringify_times(v)] }]
when Array
obj.map { |v| stringify_times(v) }
else
iso_format_time(obj)
end
end | [
"def",
"stringify_times",
"(",
"obj",
")",
"case",
"obj",
"when",
"Hash",
"Hash",
"[",
"obj",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"[",
"k",
",",
"stringify_times",
"(",
"v",
")",
"]",
"}",
"]",
"when",
"Array",
"obj",
".",
"map",
"{",
"|",
"v",
"|",
"stringify_times",
"(",
"v",
")",
"}",
"else",
"iso_format_time",
"(",
"obj",
")",
"end",
"end"
]
| Recursively ISO format all time and date values.
@param [Hash] obj the object containing date or time objects
@return [Hash] the object with ISO-formatted time stings | [
"Recursively",
"ISO",
"format",
"all",
"time",
"and",
"date",
"values",
"."
]
| cf141f235eec43909ba68866c283803f84d6bc89 | https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/utils.rb#L131-L140 | train |
gocardless/gocardless-legacy-ruby | lib/gocardless/paginator.rb | GoCardless.Paginator.load_page | def load_page(page_num)
params = @query.merge(pagination_params(page_num))
response = @client.api_request(:get, @path, :params => params)
metadata = parse_metadata(response)
@num_records, @num_pages = metadata['records'], metadata['pages']
Page.new(@resource_class, response.parsed, metadata['links'])
end | ruby | def load_page(page_num)
params = @query.merge(pagination_params(page_num))
response = @client.api_request(:get, @path, :params => params)
metadata = parse_metadata(response)
@num_records, @num_pages = metadata['records'], metadata['pages']
Page.new(@resource_class, response.parsed, metadata['links'])
end | [
"def",
"load_page",
"(",
"page_num",
")",
"params",
"=",
"@query",
".",
"merge",
"(",
"pagination_params",
"(",
"page_num",
")",
")",
"response",
"=",
"@client",
".",
"api_request",
"(",
":get",
",",
"@path",
",",
":params",
"=>",
"params",
")",
"metadata",
"=",
"parse_metadata",
"(",
"response",
")",
"@num_records",
",",
"@num_pages",
"=",
"metadata",
"[",
"'records'",
"]",
",",
"metadata",
"[",
"'pages'",
"]",
"Page",
".",
"new",
"(",
"@resource_class",
",",
"response",
".",
"parsed",
",",
"metadata",
"[",
"'links'",
"]",
")",
"end"
]
| Fetch and return a single page. | [
"Fetch",
"and",
"return",
"a",
"single",
"page",
"."
]
| cf141f235eec43909ba68866c283803f84d6bc89 | https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/paginator.rb#L35-L43 | train |
gocardless/gocardless-legacy-ruby | lib/gocardless/paginator.rb | GoCardless.Paginator.each_page | def each_page
page_obj = load_page(1)
loop do
yield page_obj
break unless page_obj.has_next?
page_obj = load_page(page_obj.next_page)
end
end | ruby | def each_page
page_obj = load_page(1)
loop do
yield page_obj
break unless page_obj.has_next?
page_obj = load_page(page_obj.next_page)
end
end | [
"def",
"each_page",
"page_obj",
"=",
"load_page",
"(",
"1",
")",
"loop",
"do",
"yield",
"page_obj",
"break",
"unless",
"page_obj",
".",
"has_next?",
"page_obj",
"=",
"load_page",
"(",
"page_obj",
".",
"next_page",
")",
"end",
"end"
]
| Fetch and yield each page of results. | [
"Fetch",
"and",
"yield",
"each",
"page",
"of",
"results",
"."
]
| cf141f235eec43909ba68866c283803f84d6bc89 | https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/paginator.rb#L55-L62 | train |
gocardless/gocardless-legacy-ruby | lib/gocardless/client.rb | GoCardless.Client.authorize_url | def authorize_url(options)
raise ArgumentError, ':redirect_uri required' unless options[:redirect_uri]
params = {
:client_id => @app_id,
:response_type => 'code',
:scope => 'manage_merchant'
}
# Faraday doesn't flatten params in this case (Faraday issue #115)
options = Hash[Utils.flatten_params(options)]
@oauth_client.authorize_url(params.merge(options))
end | ruby | def authorize_url(options)
raise ArgumentError, ':redirect_uri required' unless options[:redirect_uri]
params = {
:client_id => @app_id,
:response_type => 'code',
:scope => 'manage_merchant'
}
# Faraday doesn't flatten params in this case (Faraday issue #115)
options = Hash[Utils.flatten_params(options)]
@oauth_client.authorize_url(params.merge(options))
end | [
"def",
"authorize_url",
"(",
"options",
")",
"raise",
"ArgumentError",
",",
"':redirect_uri required'",
"unless",
"options",
"[",
":redirect_uri",
"]",
"params",
"=",
"{",
":client_id",
"=>",
"@app_id",
",",
":response_type",
"=>",
"'code'",
",",
":scope",
"=>",
"'manage_merchant'",
"}",
"options",
"=",
"Hash",
"[",
"Utils",
".",
"flatten_params",
"(",
"options",
")",
"]",
"@oauth_client",
".",
"authorize_url",
"(",
"params",
".",
"merge",
"(",
"options",
")",
")",
"end"
]
| Generate the OAuth authorize url
@param [Hash] options parameters to be included in the url.
+:redirect_uri+ is required.
@return [String] the authorize url | [
"Generate",
"the",
"OAuth",
"authorize",
"url"
]
| cf141f235eec43909ba68866c283803f84d6bc89 | https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/client.rb#L47-L57 | train |
gocardless/gocardless-legacy-ruby | lib/gocardless/client.rb | GoCardless.Client.fetch_access_token | def fetch_access_token(auth_code, options)
raise ArgumentError, ':redirect_uri required' unless options[:redirect_uri]
# Exchange the auth code for an access token
@access_token = @oauth_client.auth_code.get_token(auth_code, options)
# Use the scope to figure out which merchant we're managing
scope = @access_token.params[:scope] || @access_token.params['scope']
set_merchant_id_from_scope(scope)
self.scoped_access_token
end | ruby | def fetch_access_token(auth_code, options)
raise ArgumentError, ':redirect_uri required' unless options[:redirect_uri]
# Exchange the auth code for an access token
@access_token = @oauth_client.auth_code.get_token(auth_code, options)
# Use the scope to figure out which merchant we're managing
scope = @access_token.params[:scope] || @access_token.params['scope']
set_merchant_id_from_scope(scope)
self.scoped_access_token
end | [
"def",
"fetch_access_token",
"(",
"auth_code",
",",
"options",
")",
"raise",
"ArgumentError",
",",
"':redirect_uri required'",
"unless",
"options",
"[",
":redirect_uri",
"]",
"@access_token",
"=",
"@oauth_client",
".",
"auth_code",
".",
"get_token",
"(",
"auth_code",
",",
"options",
")",
"scope",
"=",
"@access_token",
".",
"params",
"[",
":scope",
"]",
"||",
"@access_token",
".",
"params",
"[",
"'scope'",
"]",
"set_merchant_id_from_scope",
"(",
"scope",
")",
"self",
".",
"scoped_access_token",
"end"
]
| Exchange the authorization code for an access token
@param [String] auth_code to exchange for the access_token
@return [String] the access_token required to make API calls to resources | [
"Exchange",
"the",
"authorization",
"code",
"for",
"an",
"access",
"token"
]
| cf141f235eec43909ba68866c283803f84d6bc89 | https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/client.rb#L64-L74 | train |
gocardless/gocardless-legacy-ruby | lib/gocardless/client.rb | GoCardless.Client.access_token= | def access_token=(token)
token, scope = token.sub(/^bearer\s+/i, '').split(' ', 2)
if scope
warn "[DEPRECATION] (gocardless-ruby) merchant_id is now a separate " +
"attribute, the manage_merchant scope should no longer be " +
"included in the 'token' attribute. See http://git.io/G9y37Q " +
"for more info."
else
scope = ''
end
@access_token = OAuth2::AccessToken.new(@oauth_client, token)
@access_token.params['scope'] = scope
set_merchant_id_from_scope(scope) unless @merchant_id
end | ruby | def access_token=(token)
token, scope = token.sub(/^bearer\s+/i, '').split(' ', 2)
if scope
warn "[DEPRECATION] (gocardless-ruby) merchant_id is now a separate " +
"attribute, the manage_merchant scope should no longer be " +
"included in the 'token' attribute. See http://git.io/G9y37Q " +
"for more info."
else
scope = ''
end
@access_token = OAuth2::AccessToken.new(@oauth_client, token)
@access_token.params['scope'] = scope
set_merchant_id_from_scope(scope) unless @merchant_id
end | [
"def",
"access_token",
"=",
"(",
"token",
")",
"token",
",",
"scope",
"=",
"token",
".",
"sub",
"(",
"/",
"\\s",
"/i",
",",
"''",
")",
".",
"split",
"(",
"' '",
",",
"2",
")",
"if",
"scope",
"warn",
"\"[DEPRECATION] (gocardless-ruby) merchant_id is now a separate \"",
"+",
"\"attribute, the manage_merchant scope should no longer be \"",
"+",
"\"included in the 'token' attribute. See http://git.io/G9y37Q \"",
"+",
"\"for more info.\"",
"else",
"scope",
"=",
"''",
"end",
"@access_token",
"=",
"OAuth2",
"::",
"AccessToken",
".",
"new",
"(",
"@oauth_client",
",",
"token",
")",
"@access_token",
".",
"params",
"[",
"'scope'",
"]",
"=",
"scope",
"set_merchant_id_from_scope",
"(",
"scope",
")",
"unless",
"@merchant_id",
"end"
]
| Set the client's access token
@param [String] token a string with format <code>"#{token}"</code>
(as returned by {#access_token}) | [
"Set",
"the",
"client",
"s",
"access",
"token"
]
| cf141f235eec43909ba68866c283803f84d6bc89 | https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/client.rb#L105-L120 | train |
gocardless/gocardless-legacy-ruby | lib/gocardless/client.rb | GoCardless.Client.set_merchant_id_from_scope | def set_merchant_id_from_scope(scope)
perm = scope.split.select {|p| p.start_with?('manage_merchant:') }.first
@merchant_id = perm.split(':')[1] if perm
end | ruby | def set_merchant_id_from_scope(scope)
perm = scope.split.select {|p| p.start_with?('manage_merchant:') }.first
@merchant_id = perm.split(':')[1] if perm
end | [
"def",
"set_merchant_id_from_scope",
"(",
"scope",
")",
"perm",
"=",
"scope",
".",
"split",
".",
"select",
"{",
"|",
"p",
"|",
"p",
".",
"start_with?",
"(",
"'manage_merchant:'",
")",
"}",
".",
"first",
"@merchant_id",
"=",
"perm",
".",
"split",
"(",
"':'",
")",
"[",
"1",
"]",
"if",
"perm",
"end"
]
| Pull the merchant id out of the access scope | [
"Pull",
"the",
"merchant",
"id",
"out",
"of",
"the",
"access",
"scope"
]
| cf141f235eec43909ba68866c283803f84d6bc89 | https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/client.rb#L349-L352 | train |
gocardless/gocardless-legacy-ruby | lib/gocardless/client.rb | GoCardless.Client.request | def request(method, path, opts = {})
raise ClientError, 'Access token missing' unless @access_token
opts[:headers] = {} if opts[:headers].nil?
opts[:headers]['Accept'] = 'application/json'
opts[:headers]['Content-Type'] = 'application/json' unless method == :get
opts[:headers]['User-Agent'] = user_agent
opts[:body] = MultiJson.encode(opts[:data]) if !opts[:data].nil?
path = URI.encode(path)
# Reset the URL in case the environment / base URL has been changed.
@oauth_client.site = base_url
header_keys = opts[:headers].keys.map(&:to_s)
if header_keys.map(&:downcase).include?('authorization')
@oauth_client.request(method, path, opts)
else
@access_token.send(method, path, opts)
end
rescue OAuth2::Error => err
raise GoCardless::ApiError.new(err.response)
end | ruby | def request(method, path, opts = {})
raise ClientError, 'Access token missing' unless @access_token
opts[:headers] = {} if opts[:headers].nil?
opts[:headers]['Accept'] = 'application/json'
opts[:headers]['Content-Type'] = 'application/json' unless method == :get
opts[:headers]['User-Agent'] = user_agent
opts[:body] = MultiJson.encode(opts[:data]) if !opts[:data].nil?
path = URI.encode(path)
# Reset the URL in case the environment / base URL has been changed.
@oauth_client.site = base_url
header_keys = opts[:headers].keys.map(&:to_s)
if header_keys.map(&:downcase).include?('authorization')
@oauth_client.request(method, path, opts)
else
@access_token.send(method, path, opts)
end
rescue OAuth2::Error => err
raise GoCardless::ApiError.new(err.response)
end | [
"def",
"request",
"(",
"method",
",",
"path",
",",
"opts",
"=",
"{",
"}",
")",
"raise",
"ClientError",
",",
"'Access token missing'",
"unless",
"@access_token",
"opts",
"[",
":headers",
"]",
"=",
"{",
"}",
"if",
"opts",
"[",
":headers",
"]",
".",
"nil?",
"opts",
"[",
":headers",
"]",
"[",
"'Accept'",
"]",
"=",
"'application/json'",
"opts",
"[",
":headers",
"]",
"[",
"'Content-Type'",
"]",
"=",
"'application/json'",
"unless",
"method",
"==",
":get",
"opts",
"[",
":headers",
"]",
"[",
"'User-Agent'",
"]",
"=",
"user_agent",
"opts",
"[",
":body",
"]",
"=",
"MultiJson",
".",
"encode",
"(",
"opts",
"[",
":data",
"]",
")",
"if",
"!",
"opts",
"[",
":data",
"]",
".",
"nil?",
"path",
"=",
"URI",
".",
"encode",
"(",
"path",
")",
"@oauth_client",
".",
"site",
"=",
"base_url",
"header_keys",
"=",
"opts",
"[",
":headers",
"]",
".",
"keys",
".",
"map",
"(",
"&",
":to_s",
")",
"if",
"header_keys",
".",
"map",
"(",
"&",
":downcase",
")",
".",
"include?",
"(",
"'authorization'",
")",
"@oauth_client",
".",
"request",
"(",
"method",
",",
"path",
",",
"opts",
")",
"else",
"@access_token",
".",
"send",
"(",
"method",
",",
"path",
",",
"opts",
")",
"end",
"rescue",
"OAuth2",
"::",
"Error",
"=>",
"err",
"raise",
"GoCardless",
"::",
"ApiError",
".",
"new",
"(",
"err",
".",
"response",
")",
"end"
]
| Send a request to the GoCardless API servers
@param [Symbol] method the HTTP method to use (e.g. +:get+, +:post+)
@param [String] path the path fragment of the URL
@option [Hash] opts query string parameters | [
"Send",
"a",
"request",
"to",
"the",
"GoCardless",
"API",
"servers"
]
| cf141f235eec43909ba68866c283803f84d6bc89 | https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/client.rb#L359-L380 | train |
gocardless/gocardless-legacy-ruby | lib/gocardless/client.rb | GoCardless.Client.prepare_params | def prepare_params(params)
# Create a new hash in case is a HashWithIndifferentAccess (keys are
# always a String)
params = Utils.symbolize_keys(Hash[params])
# Only pull out the relevant parameters, other won't be included in the
# signature so will cause false negatives
keys = [:resource_id, :resource_type, :resource_uri, :state, :signature]
params = Hash[params.select { |k,v| keys.include? k }]
(keys - [:state]).each do |key|
raise ArgumentError, "Parameters missing #{key}" if !params.key?(key)
end
params
end | ruby | def prepare_params(params)
# Create a new hash in case is a HashWithIndifferentAccess (keys are
# always a String)
params = Utils.symbolize_keys(Hash[params])
# Only pull out the relevant parameters, other won't be included in the
# signature so will cause false negatives
keys = [:resource_id, :resource_type, :resource_uri, :state, :signature]
params = Hash[params.select { |k,v| keys.include? k }]
(keys - [:state]).each do |key|
raise ArgumentError, "Parameters missing #{key}" if !params.key?(key)
end
params
end | [
"def",
"prepare_params",
"(",
"params",
")",
"params",
"=",
"Utils",
".",
"symbolize_keys",
"(",
"Hash",
"[",
"params",
"]",
")",
"keys",
"=",
"[",
":resource_id",
",",
":resource_type",
",",
":resource_uri",
",",
":state",
",",
":signature",
"]",
"params",
"=",
"Hash",
"[",
"params",
".",
"select",
"{",
"|",
"k",
",",
"v",
"|",
"keys",
".",
"include?",
"k",
"}",
"]",
"(",
"keys",
"-",
"[",
":state",
"]",
")",
".",
"each",
"do",
"|",
"key",
"|",
"raise",
"ArgumentError",
",",
"\"Parameters missing #{key}\"",
"if",
"!",
"params",
".",
"key?",
"(",
"key",
")",
"end",
"params",
"end"
]
| Prepare a Hash of parameters for signing. Presence of required
parameters is checked and the others are discarded.
@param [Hash] params the parameters to be prepared for signing
@return [Hash] the prepared parameters | [
"Prepare",
"a",
"Hash",
"of",
"parameters",
"for",
"signing",
".",
"Presence",
"of",
"required",
"parameters",
"is",
"checked",
"and",
"the",
"others",
"are",
"discarded",
"."
]
| cf141f235eec43909ba68866c283803f84d6bc89 | https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/client.rb#L400-L412 | train |
gocardless/gocardless-legacy-ruby | lib/gocardless/client.rb | GoCardless.Client.new_limit_url | def new_limit_url(type, limit_params)
url = URI.parse("#{base_url}/connect/#{type}s/new")
limit_params[:merchant_id] = merchant_id
redirect_uri = limit_params.delete(:redirect_uri)
cancel_uri = limit_params.delete(:cancel_uri)
state = limit_params.delete(:state)
params = {
:nonce => generate_nonce,
:timestamp => Time.now.getutc.strftime('%Y-%m-%dT%H:%M:%SZ'),
:client_id => @app_id,
type => limit_params,
}
params[:redirect_uri] = redirect_uri unless redirect_uri.nil?
params[:cancel_uri] = cancel_uri unless cancel_uri.nil?
params[:state] = state unless state.nil?
sign_params(params)
url.query = Utils.normalize_params(params)
url.to_s
end | ruby | def new_limit_url(type, limit_params)
url = URI.parse("#{base_url}/connect/#{type}s/new")
limit_params[:merchant_id] = merchant_id
redirect_uri = limit_params.delete(:redirect_uri)
cancel_uri = limit_params.delete(:cancel_uri)
state = limit_params.delete(:state)
params = {
:nonce => generate_nonce,
:timestamp => Time.now.getutc.strftime('%Y-%m-%dT%H:%M:%SZ'),
:client_id => @app_id,
type => limit_params,
}
params[:redirect_uri] = redirect_uri unless redirect_uri.nil?
params[:cancel_uri] = cancel_uri unless cancel_uri.nil?
params[:state] = state unless state.nil?
sign_params(params)
url.query = Utils.normalize_params(params)
url.to_s
end | [
"def",
"new_limit_url",
"(",
"type",
",",
"limit_params",
")",
"url",
"=",
"URI",
".",
"parse",
"(",
"\"#{base_url}/connect/#{type}s/new\"",
")",
"limit_params",
"[",
":merchant_id",
"]",
"=",
"merchant_id",
"redirect_uri",
"=",
"limit_params",
".",
"delete",
"(",
":redirect_uri",
")",
"cancel_uri",
"=",
"limit_params",
".",
"delete",
"(",
":cancel_uri",
")",
"state",
"=",
"limit_params",
".",
"delete",
"(",
":state",
")",
"params",
"=",
"{",
":nonce",
"=>",
"generate_nonce",
",",
":timestamp",
"=>",
"Time",
".",
"now",
".",
"getutc",
".",
"strftime",
"(",
"'%Y-%m-%dT%H:%M:%SZ'",
")",
",",
":client_id",
"=>",
"@app_id",
",",
"type",
"=>",
"limit_params",
",",
"}",
"params",
"[",
":redirect_uri",
"]",
"=",
"redirect_uri",
"unless",
"redirect_uri",
".",
"nil?",
"params",
"[",
":cancel_uri",
"]",
"=",
"cancel_uri",
"unless",
"cancel_uri",
".",
"nil?",
"params",
"[",
":state",
"]",
"=",
"state",
"unless",
"state",
".",
"nil?",
"sign_params",
"(",
"params",
")",
"url",
".",
"query",
"=",
"Utils",
".",
"normalize_params",
"(",
"params",
")",
"url",
".",
"to_s",
"end"
]
| Generate the URL for creating a limit of type +type+, including the
provided params, nonce, timestamp and signature
@param [Symbol] type the limit type (+:subscription+, etc)
@param [Hash] params the bill parameters
@return [String] the generated URL | [
"Generate",
"the",
"URL",
"for",
"creating",
"a",
"limit",
"of",
"type",
"+",
"type",
"+",
"including",
"the",
"provided",
"params",
"nonce",
"timestamp",
"and",
"signature"
]
| cf141f235eec43909ba68866c283803f84d6bc89 | https://github.com/gocardless/gocardless-legacy-ruby/blob/cf141f235eec43909ba68866c283803f84d6bc89/lib/gocardless/client.rb#L438-L460 | train |
apotonick/hooks | lib/hooks/hook.rb | Hooks.Hook.run | def run(scope, *args)
inject(Results.new) do |results, callback|
executed = execute_callback(scope, callback, *args)
return results.halted! unless continue_execution?(executed)
results << executed
end
end | ruby | def run(scope, *args)
inject(Results.new) do |results, callback|
executed = execute_callback(scope, callback, *args)
return results.halted! unless continue_execution?(executed)
results << executed
end
end | [
"def",
"run",
"(",
"scope",
",",
"*",
"args",
")",
"inject",
"(",
"Results",
".",
"new",
")",
"do",
"|",
"results",
",",
"callback",
"|",
"executed",
"=",
"execute_callback",
"(",
"scope",
",",
"callback",
",",
"*",
"args",
")",
"return",
"results",
".",
"halted!",
"unless",
"continue_execution?",
"(",
"executed",
")",
"results",
"<<",
"executed",
"end",
"end"
]
| The chain contains the return values of the executed callbacks.
Example:
class Person
define_hook :before_eating
before_eating :wash_hands
before_eating :locate_food
before_eating :sit_down
def wash_hands; :washed_hands; end
def locate_food; :located_food; false; end
def sit_down; :sat_down; end
end
result = person.run_hook(:before_eating)
result.chain #=> [:washed_hands, false, :sat_down]
If <tt>:halts_on_falsey</tt> is enabled:
class Person
define_hook :before_eating, :halts_on_falsey => true
# ...
end
result = person.run_hook(:before_eating)
result.chain #=> [:washed_hands] | [
"The",
"chain",
"contains",
"the",
"return",
"values",
"of",
"the",
"executed",
"callbacks",
"."
]
| b30e91e9b71ffc248d952ac6f5cdaef9fc577763 | https://github.com/apotonick/hooks/blob/b30e91e9b71ffc248d952ac6f5cdaef9fc577763/lib/hooks/hook.rb#L38-L45 | train |
piotrmurach/tty-color | lib/tty/color.rb | TTY.Color.command? | def command?(cmd)
!!system(cmd, out: ::File::NULL, err: ::File::NULL)
end | ruby | def command?(cmd)
!!system(cmd, out: ::File::NULL, err: ::File::NULL)
end | [
"def",
"command?",
"(",
"cmd",
")",
"!",
"!",
"system",
"(",
"cmd",
",",
"out",
":",
"::",
"File",
"::",
"NULL",
",",
"err",
":",
"::",
"File",
"::",
"NULL",
")",
"end"
]
| Check if command can be run
@return [Boolean]
@api public | [
"Check",
"if",
"command",
"can",
"be",
"run"
]
| 2447896bb667908bddffb03bfe3c2b0f963554e3 | https://github.com/piotrmurach/tty-color/blob/2447896bb667908bddffb03bfe3c2b0f963554e3/lib/tty/color.rb#L56-L58 | train |
ryanong/spy | lib/spy/nest.rb | Spy.Nest.remove | def remove(spy)
if @constant_spies[spy.constant_name] == spy
@constant_spies.delete(spy.constant_name)
else
raise NoSpyError, "#{spy.constant_name} was not stubbed on #{base_module.name}"
end
self
end | ruby | def remove(spy)
if @constant_spies[spy.constant_name] == spy
@constant_spies.delete(spy.constant_name)
else
raise NoSpyError, "#{spy.constant_name} was not stubbed on #{base_module.name}"
end
self
end | [
"def",
"remove",
"(",
"spy",
")",
"if",
"@constant_spies",
"[",
"spy",
".",
"constant_name",
"]",
"==",
"spy",
"@constant_spies",
".",
"delete",
"(",
"spy",
".",
"constant_name",
")",
"else",
"raise",
"NoSpyError",
",",
"\"#{spy.constant_name} was not stubbed on #{base_module.name}\"",
"end",
"self",
"end"
]
| removes the spy from the records
@param spy [Constant]
@return [self] | [
"removes",
"the",
"spy",
"from",
"the",
"records"
]
| 54ec54b604333c8991ab8d6df0a96fe57364f65c | https://github.com/ryanong/spy/blob/54ec54b604333c8991ab8d6df0a96fe57364f65c/lib/spy/nest.rb#L35-L42 | train |
ryanong/spy | lib/spy/subroutine.rb | Spy.Subroutine.hook | def hook(opts = {})
raise AlreadyHookedError, "#{base_object} method '#{method_name}' has already been hooked" if self.class.get(base_object, method_name, singleton_method)
@hook_opts = opts
@original_method_visibility = method_visibility_of(method_name)
hook_opts[:visibility] ||= original_method_visibility
if original_method_visibility || !hook_opts[:force]
@original_method = current_method
end
if original_method && original_method.owner == base_object
original_method.owner.send(:remove_method, method_name)
end
if singleton_method
base_object.define_singleton_method(method_name, override_method)
else
base_object.define_method(method_name, override_method)
end
if [:public, :protected, :private].include? hook_opts[:visibility]
method_owner.send(hook_opts[:visibility], method_name)
end
Agency.instance.recruit(self)
@was_hooked = true
self
end | ruby | def hook(opts = {})
raise AlreadyHookedError, "#{base_object} method '#{method_name}' has already been hooked" if self.class.get(base_object, method_name, singleton_method)
@hook_opts = opts
@original_method_visibility = method_visibility_of(method_name)
hook_opts[:visibility] ||= original_method_visibility
if original_method_visibility || !hook_opts[:force]
@original_method = current_method
end
if original_method && original_method.owner == base_object
original_method.owner.send(:remove_method, method_name)
end
if singleton_method
base_object.define_singleton_method(method_name, override_method)
else
base_object.define_method(method_name, override_method)
end
if [:public, :protected, :private].include? hook_opts[:visibility]
method_owner.send(hook_opts[:visibility], method_name)
end
Agency.instance.recruit(self)
@was_hooked = true
self
end | [
"def",
"hook",
"(",
"opts",
"=",
"{",
"}",
")",
"raise",
"AlreadyHookedError",
",",
"\"#{base_object} method '#{method_name}' has already been hooked\"",
"if",
"self",
".",
"class",
".",
"get",
"(",
"base_object",
",",
"method_name",
",",
"singleton_method",
")",
"@hook_opts",
"=",
"opts",
"@original_method_visibility",
"=",
"method_visibility_of",
"(",
"method_name",
")",
"hook_opts",
"[",
":visibility",
"]",
"||=",
"original_method_visibility",
"if",
"original_method_visibility",
"||",
"!",
"hook_opts",
"[",
":force",
"]",
"@original_method",
"=",
"current_method",
"end",
"if",
"original_method",
"&&",
"original_method",
".",
"owner",
"==",
"base_object",
"original_method",
".",
"owner",
".",
"send",
"(",
":remove_method",
",",
"method_name",
")",
"end",
"if",
"singleton_method",
"base_object",
".",
"define_singleton_method",
"(",
"method_name",
",",
"override_method",
")",
"else",
"base_object",
".",
"define_method",
"(",
"method_name",
",",
"override_method",
")",
"end",
"if",
"[",
":public",
",",
":protected",
",",
":private",
"]",
".",
"include?",
"hook_opts",
"[",
":visibility",
"]",
"method_owner",
".",
"send",
"(",
"hook_opts",
"[",
":visibility",
"]",
",",
"method_name",
")",
"end",
"Agency",
".",
"instance",
".",
"recruit",
"(",
"self",
")",
"@was_hooked",
"=",
"true",
"self",
"end"
]
| set what object and method the spy should watch
@param object
@param method_name <Symbol>
@param singleton_method <Boolean> spy on the singleton method or the normal method
hooks the method into the object and stashes original method if it exists
@param [Hash] opts what do do when hooking into a method
@option opts [Boolean] force (false) if set to true will hook the method even if it doesn't exist
@option opts [Symbol<:public, :protected, :private>] visibility overrides visibility with whatever method is given
@return [self] | [
"set",
"what",
"object",
"and",
"method",
"the",
"spy",
"should",
"watch"
]
| 54ec54b604333c8991ab8d6df0a96fe57364f65c | https://github.com/ryanong/spy/blob/54ec54b604333c8991ab8d6df0a96fe57364f65c/lib/spy/subroutine.rb#L44-L72 | train |
ryanong/spy | lib/spy/subroutine.rb | Spy.Subroutine.unhook | def unhook
raise NeverHookedError, "'#{method_name}' method has not been hooked" unless hooked?
method_owner.send(:remove_method, method_name)
if original_method && method_owner == original_method.owner
original_method.owner.send(:define_method, method_name, original_method)
original_method.owner.send(original_method_visibility, method_name) if original_method_visibility
end
clear_method!
Agency.instance.retire(self)
self
end | ruby | def unhook
raise NeverHookedError, "'#{method_name}' method has not been hooked" unless hooked?
method_owner.send(:remove_method, method_name)
if original_method && method_owner == original_method.owner
original_method.owner.send(:define_method, method_name, original_method)
original_method.owner.send(original_method_visibility, method_name) if original_method_visibility
end
clear_method!
Agency.instance.retire(self)
self
end | [
"def",
"unhook",
"raise",
"NeverHookedError",
",",
"\"'#{method_name}' method has not been hooked\"",
"unless",
"hooked?",
"method_owner",
".",
"send",
"(",
":remove_method",
",",
"method_name",
")",
"if",
"original_method",
"&&",
"method_owner",
"==",
"original_method",
".",
"owner",
"original_method",
".",
"owner",
".",
"send",
"(",
":define_method",
",",
"method_name",
",",
"original_method",
")",
"original_method",
".",
"owner",
".",
"send",
"(",
"original_method_visibility",
",",
"method_name",
")",
"if",
"original_method_visibility",
"end",
"clear_method!",
"Agency",
".",
"instance",
".",
"retire",
"(",
"self",
")",
"self",
"end"
]
| unhooks method from object
@return [self] | [
"unhooks",
"method",
"from",
"object"
]
| 54ec54b604333c8991ab8d6df0a96fe57364f65c | https://github.com/ryanong/spy/blob/54ec54b604333c8991ab8d6df0a96fe57364f65c/lib/spy/subroutine.rb#L76-L88 | train |
ryanong/spy | lib/spy/subroutine.rb | Spy.Subroutine.and_yield | def and_yield(*args)
yield eval_context = Object.new if block_given?
@plan = Proc.new do |&block|
eval_context.instance_exec(*args, &block)
end
self
end | ruby | def and_yield(*args)
yield eval_context = Object.new if block_given?
@plan = Proc.new do |&block|
eval_context.instance_exec(*args, &block)
end
self
end | [
"def",
"and_yield",
"(",
"*",
"args",
")",
"yield",
"eval_context",
"=",
"Object",
".",
"new",
"if",
"block_given?",
"@plan",
"=",
"Proc",
".",
"new",
"do",
"|",
"&",
"block",
"|",
"eval_context",
".",
"instance_exec",
"(",
"*",
"args",
",",
"&",
"block",
")",
"end",
"self",
"end"
]
| Tells the object to yield one or more args to a block when the message is received.
@return [self] | [
"Tells",
"the",
"object",
"to",
"yield",
"one",
"or",
"more",
"args",
"to",
"a",
"block",
"when",
"the",
"message",
"is",
"received",
"."
]
| 54ec54b604333c8991ab8d6df0a96fe57364f65c | https://github.com/ryanong/spy/blob/54ec54b604333c8991ab8d6df0a96fe57364f65c/lib/spy/subroutine.rb#L134-L140 | train |
ryanong/spy | lib/spy/subroutine.rb | Spy.Subroutine.and_call_through | def and_call_through
if @base_object.is_a? Class
@plan = Proc.new do |object, *args, &block|
if original_method
if original_method.is_a? UnboundMethod
bound_method = original_method.bind(object)
bound_method.call(*args, &block)
else
original_method.call(*args, &block)
end
else
base_object.send(:method_missing, method_name, *args, &block)
end
end
else
@plan = Proc.new do |*args, &block|
if original_method
original_method.call(*args, &block)
else
base_object.send(:method_missing, method_name, *args, &block)
end
end
end
self
end | ruby | def and_call_through
if @base_object.is_a? Class
@plan = Proc.new do |object, *args, &block|
if original_method
if original_method.is_a? UnboundMethod
bound_method = original_method.bind(object)
bound_method.call(*args, &block)
else
original_method.call(*args, &block)
end
else
base_object.send(:method_missing, method_name, *args, &block)
end
end
else
@plan = Proc.new do |*args, &block|
if original_method
original_method.call(*args, &block)
else
base_object.send(:method_missing, method_name, *args, &block)
end
end
end
self
end | [
"def",
"and_call_through",
"if",
"@base_object",
".",
"is_a?",
"Class",
"@plan",
"=",
"Proc",
".",
"new",
"do",
"|",
"object",
",",
"*",
"args",
",",
"&",
"block",
"|",
"if",
"original_method",
"if",
"original_method",
".",
"is_a?",
"UnboundMethod",
"bound_method",
"=",
"original_method",
".",
"bind",
"(",
"object",
")",
"bound_method",
".",
"call",
"(",
"*",
"args",
",",
"&",
"block",
")",
"else",
"original_method",
".",
"call",
"(",
"*",
"args",
",",
"&",
"block",
")",
"end",
"else",
"base_object",
".",
"send",
"(",
":method_missing",
",",
"method_name",
",",
"*",
"args",
",",
"&",
"block",
")",
"end",
"end",
"else",
"@plan",
"=",
"Proc",
".",
"new",
"do",
"|",
"*",
"args",
",",
"&",
"block",
"|",
"if",
"original_method",
"original_method",
".",
"call",
"(",
"*",
"args",
",",
"&",
"block",
")",
"else",
"base_object",
".",
"send",
"(",
":method_missing",
",",
"method_name",
",",
"*",
"args",
",",
"&",
"block",
")",
"end",
"end",
"end",
"self",
"end"
]
| tells the spy to call the original method
@return [self] | [
"tells",
"the",
"spy",
"to",
"call",
"the",
"original",
"method"
]
| 54ec54b604333c8991ab8d6df0a96fe57364f65c | https://github.com/ryanong/spy/blob/54ec54b604333c8991ab8d6df0a96fe57364f65c/lib/spy/subroutine.rb#L144-L169 | train |
ryanong/spy | lib/spy/subroutine.rb | Spy.Subroutine.has_been_called_with? | def has_been_called_with?(*args)
raise NeverHookedError unless @was_hooked
match = block_given? ? Proc.new : proc { |call| call.args == args }
calls.any?(&match)
end | ruby | def has_been_called_with?(*args)
raise NeverHookedError unless @was_hooked
match = block_given? ? Proc.new : proc { |call| call.args == args }
calls.any?(&match)
end | [
"def",
"has_been_called_with?",
"(",
"*",
"args",
")",
"raise",
"NeverHookedError",
"unless",
"@was_hooked",
"match",
"=",
"block_given?",
"?",
"Proc",
".",
"new",
":",
"proc",
"{",
"|",
"call",
"|",
"call",
".",
"args",
"==",
"args",
"}",
"calls",
".",
"any?",
"(",
"&",
"match",
")",
"end"
]
| check if the method was called with the exact arguments
@param args Arguments that should have been sent to the method
@return [Boolean] | [
"check",
"if",
"the",
"method",
"was",
"called",
"with",
"the",
"exact",
"arguments"
]
| 54ec54b604333c8991ab8d6df0a96fe57364f65c | https://github.com/ryanong/spy/blob/54ec54b604333c8991ab8d6df0a96fe57364f65c/lib/spy/subroutine.rb#L218-L222 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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",
")",
"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!",
"other_meta",
"=",
"other_frames",
".",
"meta",
".",
"collect",
"do",
"|",
"m",
"|",
"x",
"=",
"m",
".",
"dup",
"x",
"[",
":offset",
"]",
"+=",
"this_size",
"x",
"end",
"@meta",
".",
"concat",
"other_meta",
"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 | train |
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 | train |
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 | train |
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 | train |
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",
"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",
"<<",
"{",
":id",
"=>",
"frame",
".",
"id",
",",
":flag",
"=>",
"frame",
".",
"flag",
",",
":offset",
"=>",
"this_size",
"+",
"4",
",",
":size",
"=>",
"frame",
".",
"data",
".",
"size",
",",
"}",
"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 | train |
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 | train |
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 | train |
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",
"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 | train |
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",
"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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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",
"|",
"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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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",
")",
"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 | train |
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 | train |
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 | train |
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",
")",
"session",
"=",
"Lib",
".",
"lib",
".",
"session",
"close_session",
"=",
"false",
"if",
"session",
".",
"state",
"!=",
":open",
"interface",
".",
"lock_machine",
"(",
"session",
",",
"mode",
")",
"close_session",
"=",
"true",
"end",
"yield",
"session",
"if",
"block_given?",
"if",
"close_session",
"session",
".",
"machine",
".",
"save_settings",
"if",
"mode",
"==",
":write",
"&&",
"session",
".",
"machine",
".",
"state",
"!=",
":saved",
"session",
".",
"unlock_machine",
"end",
"rescue",
"Exception",
"session",
".",
"unlock_machine",
"if",
"session",
".",
"state",
"==",
":open",
"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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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",
")",
"interface",
".",
"read",
"(",
"path",
")",
".",
"wait_for_completion",
"(",
"-",
"1",
")",
"interface",
".",
"interpret",
"load_interface_attributes",
"(",
"interface",
")",
"populate_relationship",
"(",
":virtual_systems",
",",
"interface",
".",
"virtual_system_descriptions",
")",
"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 | train |
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 | train |
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?",
"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 | train |
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_interface_attributes",
"(",
"inat",
")",
"populate_relationships",
"(",
"inat",
")",
"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 | train |
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",
"dhcp_name",
"=",
"\"HostInterfaceNetworking-#{name}\"",
"result",
"=",
"parent",
".",
"parent",
".",
"dhcp_servers",
".",
"find",
"do",
"|",
"dhcp",
"|",
"dhcp",
".",
"network_name",
"==",
"dhcp_name",
"end",
"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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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?",
"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 | train |
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",
")",
"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 | train |
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",
"parent_collection",
".",
"delete",
"(",
"self",
",",
"true",
")",
"if",
"parent_collection",
"&&",
"update_collection",
"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 | train |
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 | train |
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",
")",
"clear_errors",
"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 | train |
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",
")",
"changes",
".",
"each",
"do",
"|",
"key",
",",
"values",
"|",
"save_attribute",
"(",
"key",
",",
"values",
"[",
"1",
"]",
",",
"*",
"args",
")",
"end",
"self",
".",
"class",
".",
"relationships",
".",
"each",
"do",
"|",
"name",
",",
"options",
"|",
"save_relationship",
"(",
"name",
",",
"*",
"args",
")",
"end",
"@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 | train |
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",
"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 | train |
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 | train |
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 | train |
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?",
"new_medium",
"=",
"create_hard_disk_medium",
"(",
"location",
",",
"format",
")",
"new_medium",
".",
"create_base_storage",
"(",
"logical_size",
",",
":standard",
")",
".",
"wait_for_completion",
"(",
"-",
"1",
")",
"write_attribute",
"(",
":interface",
",",
"new_medium",
")",
"initialize_attributes",
"(",
"new_medium",
")",
"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 | train |
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",
"else",
"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 | train |
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",
")",
"write_attribute",
"(",
":parent",
",",
"parent",
")",
"write_attribute",
"(",
":interface",
",",
"inetwork",
")",
"load_interface_attributes",
"(",
"inetwork",
")",
"clear_dirty!",
"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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
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 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.