input
stringlengths 109
5.2k
| output
stringlengths 7
509
|
|---|---|
Summarize the following code: def raw_send_command(sym, args)
if @connected
@connection.send_command(sym, args)
else
callback do
@connection.send_command(sym, args)
end
end
return nil
end
|
Send a command to redis without adding a deferrable for it . This is useful for commands for which replies work or need to be treated differently
|
Summarize the following code: def batch_search(searches, additional_headers = {})
url_friendly_searches = searches.each_with_index.map do |search, index|
{ index => search }
end
searches_query = { search: url_friendly_searches }
request_url = "#{base_url}/batch_search.json?#{Rack::Utils.build_nested_query(searches_query)}"
get_json(request_url, additional_headers)
end
|
Perform a batch search .
|
Summarize the following code: def search_enum(args, page_size: 100, additional_headers: {})
Enumerator.new do |yielder|
(0..Float::INFINITY).step(page_size).each do |index|
search_params = args.merge(start: index.to_i, count: page_size)
results = search(search_params, additional_headers).to_h.fetch('results', [])
results.each do |result|
yielder << result
end
if results.count < page_size
break
end
end
end
end
|
Perform a search returning the results as an enumerator .
|
Summarize the following code: def advanced_search(args)
raise ArgumentError.new("Args cannot be blank") if args.nil? || args.empty?
request_path = "#{base_url}/advanced_search?#{Rack::Utils.build_nested_query(args)}"
get_json(request_path)
end
|
Advanced search .
|
Summarize the following code: def process_request(request)
request['User-Agent'] = @user_agent
request['Content-Type'] = 'application/json'
request['X-BitPay-Plugin-Info'] = 'Rubylib' + VERSION
begin
response = @https.request request
rescue => error
raise BitPay::ConnectionError, "#{error.message}"
end
if response.kind_of? Net::HTTPSuccess
return JSON.parse(response.body)
elsif JSON.parse(response.body)["error"]
raise(BitPayError, "#{response.code}: #{JSON.parse(response.body)['error']}")
else
raise BitPayError, "#{response.code}: #{JSON.parse(response.body)}"
end
end
|
Processes HTTP Request and returns parsed response Otherwise throws error
|
Summarize the following code: def refresh_tokens
response = get(path: 'tokens')["data"]
token_array = response || {}
tokens = {}
token_array.each do |t|
tokens[t.keys.first] = t.values.first
end
@tokens = tokens
return tokens
end
|
Fetches the tokens hash from the server and updates
|
Summarize the following code: def fixtures_class
if defined?(ActiveRecord::FixtureSet)
ActiveRecord::FixtureSet
elsif defined?(ActiveRecord::Fixtures)
ActiveRecord::Fixtures
else
::Fixtures
end
end
|
Rails 3 . 0 and 3 . 1 + support
|
Summarize the following code: def sns?
json_body.is_a?(Hash) && (%w[Message Type TopicArn MessageId] - json_body.keys).empty?
end
|
Just because a message was recieved via SQS doesn t mean it was originally broadcast via SNS
|
Summarize the following code: def to_s(format = 'dd/mm/yyyy')
SUPPORTED_FIELDS.collect do |k,v|
next unless current = instance_variable_get("@#{k}")
field = v.keys.first
case current.class.to_s
when "Time", "Date", "DateTime"
"#{field}#{DateFormat.new(format).format(current)}"
when "Float"
"#{field}#{'%.2f'%current}"
when "String"
current.split("\n").collect {|x| "#{field}#{x}" }
else
"#{field}#{current}"
end
end.concat(@splits.collect{|s| s.to_s}).flatten.compact.join("\n")
end
|
Returns a representation of the transaction as it would appear in a qif file .
|
Summarize the following code: def verify_digests!
references.each do |reference|
node = referenced_node(reference.uri)
canoned = node.canonicalize(C14N, reference.namespaces)
digest = reference.digest_method.digest(canoned)
if digest != reference.decoded_digest_value
raise SignatureError.new("Reference validation error: Digest mismatch for #{reference.uri}")
end
end
end
|
Tests that the document content has not been edited
|
Summarize the following code: def referenced_node(id)
nodes = document.xpath("//*[@ID='#{id}']")
if nodes.size != 1
raise SignatureError.new("Reference validation error: Invalid element references", "Expected 1 element with id #{id}, found #{nodes.size}")
end
nodes.first
end
|
Looks up node by id checks that there s only a single node with a given id
|
Summarize the following code: def verify!
if signature.missing? && assertion.signature.missing?
raise Samlr::SignatureError.new("Neither response nor assertion signed with a certificate")
end
signature.verify! unless signature.missing?
assertion.verify!
true
end
|
The verification process assumes that all signatures are enveloped . Since this process is destructive the document needs to verify itself first and then any signed assertions
|
Summarize the following code: def decode_definition_and_options(definition_and_options)
# Only a hash (commands)
if definition_and_options.size == 1 && definition_and_options.first.is_a?(Hash)
options = definition_and_options.first.each_with_object({}) do |(key, value), current_options|
current_options[key] = definition_and_options.first.delete(key) if key.is_a?(Symbol)
end
# If there is an empty hash left, we remove it, so it's not considered commands.
#
definition_and_options = [] if definition_and_options.first.empty?
# Options passed
elsif definition_and_options.last.is_a?(Hash)
options = definition_and_options.pop
# No options passed
else
options = {}
end
[definition_and_options, options]
end
|
This is trivial to define with named arguments however Ruby 2 . 6 removed the support for mixing strings and symbols as argument keys so we re forced to perform manual decoding . The complexity of this code supports the rationale for the removal of the functionality .
|
Summarize the following code: def complete(execution_target, source_commandline=ENV.fetch('COMP_LINE'), cursor_position=ENV.fetch('COMP_POINT').to_i)
commandline_processor = CommandlineProcessor.process_commandline(source_commandline, cursor_position, @switches_definition)
if commandline_processor.completing_an_option?
complete_option(commandline_processor, execution_target)
elsif commandline_processor.parsing_error?
return
else # completing_a_value?
complete_value(commandline_processor, execution_target)
end
end
|
Currently any completion suffix is ignored and stripped .
|
Summarize the following code: def report(path, report_url = '', delimiter = %r{\/java\/|\/kotlin\/})
setup
classes = classes(delimiter)
parser = Jacoco::SAXParser.new(classes)
Nokogiri::XML::SAX::Parser.new(parser).parse(File.open(path))
total_covered = total_coverage(path)
report_markdown = "### JaCoCO Code Coverage #{total_covered[:covered]}% #{total_covered[:status]}\n"
report_markdown << "| Class | Covered | Meta | Status |\n"
report_markdown << "|:---|:---:|:---:|:---:|\n"
class_coverage_above_minimum = markdown_class(parser, report_markdown, report_url)
markdown(report_markdown)
report_fails(class_coverage_above_minimum, total_covered)
end
|
This is a fast report based on SAX parser
|
Summarize the following code: def classes(delimiter)
git = @dangerfile.git
affected_files = git.modified_files + git.added_files
affected_files.select { |file| files_extension.reduce(false) { |state, el| state || file.end_with?(el) } }
.map { |file| file.split('.').first.split(delimiter)[1] }
end
|
Select modified and added files in this PR
|
Summarize the following code: def report_class(jacoco_class)
counter = coverage_counter(jacoco_class)
coverage = (counter.covered.fdiv(counter.covered + counter.missed) * 100).floor
required_coverage = minimum_class_coverage_map[jacoco_class.name]
required_coverage = minimum_class_coverage_percentage if required_coverage.nil?
status = coverage_status(coverage, required_coverage)
{
covered: coverage,
status: status,
required_coverage_percentage: required_coverage
}
end
|
It returns a specific class code coverage and an emoji status as well
|
Summarize the following code: def total_coverage(report_path)
jacoco_report = Nokogiri::XML(File.open(report_path))
report = jacoco_report.xpath('report/counter').select { |item| item['type'] == 'INSTRUCTION' }
missed_instructions = report.first['missed'].to_f
covered_instructions = report.first['covered'].to_f
total_instructions = missed_instructions + covered_instructions
covered_percentage = (covered_instructions * 100 / total_instructions).round(2)
coverage_status = coverage_status(covered_percentage, minimum_project_coverage_percentage)
{
covered: covered_percentage,
status: coverage_status
}
end
|
It returns total of project code coverage and an emoji status as well
|
Summarize the following code: def rewindable(request)
input = request.getInputStream
@options[:rewindable] ?
Rack::RewindableInput.new(input.to_io.binmode) :
RewindableInputStream.new(input).to_io.binmode
end
|
Wraps the Java InputStream for the level of Rack compliance desired .
|
Summarize the following code: def servlet_to_rack(request)
# The Rack request that we will pass on.
env = Hash.new
# Map Servlet bits to Rack bits.
env['REQUEST_METHOD'] = request.getMethod
env['QUERY_STRING'] = request.getQueryString.to_s
env['SERVER_NAME'] = request.getServerName
env['SERVER_PORT'] = request.getServerPort.to_s
env['rack.version'] = Rack::VERSION
env['rack.url_scheme'] = request.getScheme
env['HTTP_VERSION'] = request.getProtocol
env["SERVER_PROTOCOL"] = request.getProtocol
env['REMOTE_ADDR'] = request.getRemoteAddr
env['REMOTE_HOST'] = request.getRemoteHost
# request.getPathInfo seems to be blank, so we're using the URI.
env['REQUEST_PATH'] = request.getRequestURI
env['PATH_INFO'] = request.getRequestURI
env['SCRIPT_NAME'] = ""
# Rack says URI, but it hands off a URL.
env['REQUEST_URI'] = request.getRequestURL.to_s
# Java chops off the query string, but a Rack application will
# expect it, so we'll add it back if present
env['REQUEST_URI'] << "?#{env['QUERY_STRING']}" \
if env['QUERY_STRING']
# JRuby is like the matrix, only there's no spoon or fork().
env['rack.multiprocess'] = false
env['rack.multithread'] = true
env['rack.run_once'] = false
# The input stream is a wrapper around the Java InputStream.
env['rack.input'] = @server.rewindable(request)
# Force encoding if we're on Ruby 1.9
env['rack.input'].set_encoding(Encoding.find("ASCII-8BIT")) \
if env['rack.input'].respond_to?(:set_encoding)
# Populate the HTTP headers.
request.getHeaderNames.each do |header_name|
header = header_name.to_s.upcase.tr('-', '_')
env["HTTP_#{header}"] = request.getHeader(header_name)
end
# Rack Weirdness: HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH
# both need to have the HTTP_ part dropped.
env["CONTENT_TYPE"] = env.delete("HTTP_CONTENT_TYPE") \
if env["HTTP_CONTENT_TYPE"]
env["CONTENT_LENGTH"] = env.delete("HTTP_CONTENT_LENGTH") \
if env["HTTP_CONTENT_LENGTH"]
# Route errors through the logger.
env['rack.errors'] ||= @server.logger
env['rack.logger'] ||= @server.logger
# All done, hand back the Rack request.
return(env)
end
|
Turns a Servlet request into a Rack request hash .
|
Summarize the following code: def handle_exceptions(response)
begin
yield
rescue => error
message = "Exception: #{error}"
message << "\n#{error.backtrace.join("\n")}" \
if (error.respond_to?(:backtrace))
Server.logger.error(message)
return if response.isCommitted
response.reset
response.setStatus(500)
end
end
|
Handle exceptions returning a generic 500 error response .
|
Summarize the following code: def find_files_for_reload
paths = [ './', *$LOAD_PATH ].uniq
[ $0, *$LOADED_FEATURES ].uniq.map do |file|
next if file =~ /\.(so|bundle)$/
yield(find(file, paths))
end
end
|
Walk through the list of every file we ve loaded .
|
Summarize the following code: def find(file, paths)
if(Pathname.new(file).absolute?)
return unless (timestamp = mtime(file))
@logger.debug("Found #{file}")
[ file, timestamp ]
else
paths.each do |path|
fullpath = File.expand_path((File.join(path, file)))
next unless (timestamp = mtime(fullpath))
@logger.debug("Found #{file} in #{fullpath}")
return([ fullpath, timestamp ])
end
return(nil)
end
end
|
Takes a relative or absolute + file + name a couple possible + paths + that the + file + might reside in . Returns a tuple of the full path where the file was found and its modification time or nil if not found .
|
Summarize the following code: def mtime(file)
begin
return unless file
stat = File.stat(file)
stat.file? ? stat.mtime.to_i : nil
rescue Errno::ENOENT, Errno::ENOTDIR, Errno::ESRCH
nil
end
end
|
Returns the modification time of _file_ .
|
Summarize the following code: def find(id)
build(resource_gateway.json_show(id))
rescue RestClient::ResourceNotFound
raise NoSuchModelError, "Can't find any #{endpoint} with id \"#{id}\""
end
|
Fetch a model from the server by its ID .
|
Summarize the following code: def authorization_code_url(options)
URL.new(options.merge(
path: "/api/v1/oauth2/authorize",
params: {
response_type: "code",
approve: "true",
client_id: client_id,
},
)).to_s
end
|
Return a new Authenticator instance .
|
Summarize the following code: def current_user(options)
access_token = options.fetch(:access_token)
subdomain = options.fetch(:subdomain)
user_url = URL.new(options.merge(
params: {
access_token: access_token,
},
path: "/api/v1/profiles/me",
)).to_s
response = RestClient.get(
user_url,
accept: :json,
)
build_profile(
access_token,
subdomain,
JSON.parse(response)["profiles"].first
)
end
|
Return the profile of the user accessing the API .
|
Summarize the following code: def save!
if persisted?
update(to_h)
else
self.id = resource_gateway.create(to_h)
end
self
rescue RestClient::Exception => e
raise_failed_request_error(e)
end
|
Try to persist the current object to the server by creating a new resource or updating an existing one . Raise an error if the object can t be saved .
|
Summarize the following code: def update(attributes)
attributes.each do |key, value|
self[key] = value
end
begin
resource_gateway.update(id, attributes)
rescue RestClient::Exception => e
raise_failed_request_error(e)
end
self
end
|
Update the attributes of this model . Assign the attributes according to the hash then persist those changes on the server .
|
Summarize the following code: def text(name, locator)
define_method("#{name}") do
adapter.text(locator).value
end
define_method("#{name}=") do |text|
adapter.text(locator).set text
end
define_method("clear_#{name}") do
adapter.text(locator).clear
end
define_method("enter_#{name}") do |text|
adapter.text(locator).enter text
end
define_method("#{name}_view") do
adapter.text(locator).view
end
end
|
Generates methods to enter text into a text field get its value and clear the text field
|
Summarize the following code: def button(name, locator)
define_method("#{name}") do |&block|
adapter.button(locator).click &block
end
define_method("#{name}_value") do
adapter.button(locator).value
end
define_method("#{name}_view") do
adapter.button(locator).view
end
end
|
Generates methods to click on a button as well as get the value of the button text
|
Summarize the following code: def combo_box(name, locator)
define_method("#{name}") do
adapter.combo(locator).value
end
define_method("clear_#{name}") do |item|
adapter.combo(locator).clear item
end
define_method("#{name}_selections") do
adapter.combo(locator).values
end
define_method("#{name}=") do |item|
adapter.combo(locator).set item
end
alias_method "select_#{name}", "#{name}="
define_method("#{name}_options") do
adapter.combo(locator).options
end
define_method("#{name}_view") do
adapter.combo(locator).view
end
end
|
Generates methods to get the value of a combo box set the selected item by both index and value as well as to see the available options
|
Summarize the following code: def radio(name, locator)
define_method("#{name}") do
adapter.radio(locator).set
end
define_method("#{name}?") do
adapter.radio(locator).set?
end
define_method("#{name}_view") do
adapter.radio(locator).view
end
end
|
Generates methods to set a radio button as well as see if one is selected
|
Summarize the following code: def label(name, locator)
define_method("#{name}") do
adapter.label(locator).value
end
define_method("#{name}_view") do
adapter.label(locator).view
end
end
|
Generates methods to get the value of a label control
|
Summarize the following code: def link(name, locator)
define_method("#{name}_text") do
adapter.link(locator).value
end
define_method("click_#{name}") do
adapter.link(locator).click
end
define_method("#{name}_view") do
adapter.link(locator).view
end
end
|
Generates methods to work with link controls
|
Summarize the following code: def menu_item(name, locator)
define_method("#{name}") do
adapter.menu_item(locator).select
end
define_method("click_#{name}") do
adapter.menu_item(locator).click
end
end
|
Generates methods to work with menu items
|
Summarize the following code: def table(name, locator)
define_method("#{name}") do
adapter.table(locator)
end
define_method("#{name}=") do |which_item|
adapter.table(locator).select which_item
end
define_method("add_#{name}") do |hash_info|
adapter.table(locator).add hash_info
end
define_method("select_#{name}") do |hash_info|
adapter.table(locator).select hash_info
end
define_method("find_#{name}") do |hash_info|
adapter.table(locator).find_row_with hash_info
end
define_method("clear_#{name}") do |hash_info|
adapter.table(locator).clear hash_info
end
define_method("#{name}_headers") do
adapter.table(locator).headers
end
define_method("#{name}_view") do
adapter.table(locator).view
end
end
|
Generates methods for working with table or list view controls
|
Summarize the following code: def tree_view(name, locator)
define_method("#{name}") do
adapter.tree_view(locator).value
end
define_method("#{name}=") do |which_item|
adapter.tree_view(locator).select which_item
end
define_method("#{name}_items") do
adapter.tree_view(locator).items
end
define_method("expand_#{name}_item") do |which_item|
adapter.tree_view(locator).expand which_item
end
define_method("collapse_#{name}_item") do |which_item|
adapter.tree_view(locator).collapse which_item
end
define_method("#{name}_view") do
adapter.tree_view(locator).view
end
end
|
Generates methods for working with tree view controls
|
Summarize the following code: def spinner(name, locator)
define_method(name) do
adapter.spinner(locator).value
end
define_method("#{name}=") do |value|
adapter.spinner(locator).value = value
end
define_method("increment_#{name}") do
adapter.spinner(locator).increment
end
define_method("decrement_#{name}") do
adapter.spinner(locator).decrement
end
define_method("#{name}_view") do
adapter.spinner(locator).view
end
end
|
Generates methods for working with spinner controls
|
Summarize the following code: def tabs(name, locator)
define_method(name) do
adapter.tab_control(locator).value
end
define_method("#{name}=") do |which|
adapter.tab_control(locator).selected_tab = which
end
define_method("#{name}_items") do
adapter.tab_control(locator).items
end
define_method("#{name}_view") do
adapter.tab_control(locator)
end
end
|
Generates methods for working with tab controls
|
Summarize the following code: def display_flash_messages(closable: true, key_matching: {})
key_matching = DEFAULT_KEY_MATCHING.merge(key_matching)
key_matching.default = :primary
capture do
flash.each do |key, value|
next if ignored_key?(key.to_sym)
alert_class = key_matching[key.to_sym]
concat alert_box(value, alert_class, closable)
end
end
end
|
Displays the flash messages found in ActionDispatch s + flash + hash using Foundation s + callout + component .
|
Summarize the following code: def refunds
response = Charge.get(URI.parse(PinPayment.api_url).tap{|uri| uri.path = "/1/charges/#{token}/refunds" })
response.map{|x| Refund.new(x.delete('token'), x) }
end
|
Fetches all refunds of your charge using the pin API .
|
Summarize the following code: def update email, account_or_token = nil
attributes = self.class.attributes - [:token, :created_at]
options = self.class.parse_options_for_request(attributes, email: email, bank_account: account_or_token)
response = self.class.put(URI.parse(PinPayment.api_url).tap{|uri| uri.path = "/1/recipients/#{token}" }, options)
self.email = response['email']
self.bank_account = response['bank_account']
self
end
|
Update a recipient using the pin API .
|
Summarize the following code: def update email, card_or_token = nil
attributes = self.class.attributes - [:token, :created_at]
options = self.class.parse_options_for_request(attributes, email: email, card: card_or_token)
response = self.class.put(URI.parse(PinPayment.api_url).tap{|uri| uri.path = "/1/customers/#{token}" }, options)
self.email = response['email']
self.card = response['card']
self
end
|
Update a customer using the pin API .
|
Summarize the following code: def ls(mask = '', raise = true)
ls_items = []
mask = '"' + mask + '"' if mask.include? ' '
output = exec 'ls ' + mask
output.lines.each do |line|
ls_item = LsItem.from_line(line)
ls_items << ls_item if ls_item
end
ls_items
rescue Client::RuntimeError => e
raise e if raise
[]
end
|
List contents of a remote directory
|
Summarize the following code: def put(from, to, overwrite = false, raise = true)
ls_items = ls to, false
if !overwrite && !ls_items.empty?
raise Client::RuntimeError, "File [#{to}] already exist"
end
from = '"' + from + '"' if from.include? ' '
to = '"' + to + '"' if to.include? ' '
exec 'put ' + from + ' ' + to
true
rescue Client::RuntimeError => e
raise e if raise
false
end
|
Upload a local file
|
Summarize the following code: def write(content, to, overwrite = false, raise = true)
# This is just a hack around +put+
tempfile = Tempfile.new
tempfile.write content
tempfile.close
put tempfile.path, to, overwrite, raise
end
|
Writes content to remote file
|
Summarize the following code: def del(path, raise = true)
path = '"' + path + '"' if path.include? ' '
exec 'del ' + path
true
rescue Client::RuntimeError => e
raise e if raise
false
end
|
Delete a remote file
|
Summarize the following code: def get(from, to = nil, overwrite = false, raise = true)
# Create a new tempfile but delete it
# The tempfile.path should be free to use now
tempfile = Tempfile.new
to ||= tempfile.path
tempfile.unlink
if !overwrite && File.exist?(to)
raise Client::RuntimeError, "File [#{to}] already exist locally"
end
from = '"' + from + '"' if from.include? ' '
exec 'get ' + from + ' ' + to
to
rescue Client::RuntimeError => e
raise e if raise
false
end
|
Receive a file from the smb server to local . If + to + was not passed a tempfile will be generated .
|
Summarize the following code: def read(from, overwrite = false, raise = true)
tempfile = Tempfile.new
to = tempfile.path
tempfile.unlink
get from, to, overwrite, raise
File.read to
end
|
Reads a remote file and return its content
|
Summarize the following code: def exec(cmd)
# Send command
@write1.puts cmd
# Wait for response
text = @read2.read
# Close previous pipe
@read2.close
# Create new pipe
@read2, @write2 = IO.pipe
# Raise at the end to support continuing
raise Client::RuntimeError, text if text.start_with? 'NT_STATUS_'
text
end
|
Execute a smbclient command
|
Summarize the following code: def connect
# Run +@executable+ in a separate thread to talk to hin asynchronously
Thread.start do
# Spawn the actual +@executable+ pty with +input+ and +output+ handle
begin
PTY.spawn(@executable + ' ' + params) do |output, input, pid|
@pid = pid
output.sync = true
input.sync = true
# Write inputs to pty from +exec+ method
Thread.start do
while (line = @read1.readline)
input.puts line
end
end
# Wait for responses ending with input prompt
loop do
output.expect(/smb: \\>$/) { |text| handle_response text }
end
end
rescue Errno::EIO => e
unless @shutdown_in_progress
if @connection_established
raise StandardError, "Unexpected error: [#{e.message}]"
else
raise Client::ConnectionError, 'Cannot connect to SMB server'
end
end
end
end
end
|
Connect to the server using separate threads and pipe for communications
|
Summarize the following code: def to_all_parts
me = DeepClone.clone(self)
me.disable_id_attribute
@relations << DocumentRelation.new(type: "partOf", identifier: nil, url: nil, bibitem: me)
@title.each(&:remove_part)
@abstract = []
@docidentifier.each(&:remove_part)
@docidentifier.each(&:all_parts)
@all_parts = true
end
|
remove title part components and abstract
|
Summarize the following code: def valid?
# @todo Check that each state is connected.
# Iterate through each states to verify the graph
# is not disjoint.
@transitions.each do |key, val|
@alphabet.each do |a|
return false unless @transitions[key].has_key? a.to_s
end
end
return true
end
|
Verifies that the initialized DFA is valid . Checks that each state has a transition for each symbol in the alphabet .
|
Summarize the following code: def feed(input)
head = @start.to_s
input.each_char { |symbol| head = @transitions[head][symbol] }
accept = is_accept_state? head
resp = {
input: input,
accept: accept,
head: head
}
resp
end
|
Runs the input on the machine and returns a Hash describing the machine s final state after running .
|
Summarize the following code: def create_scanner(start_row=nil, end_row=nil, *columns, &block)
columns = (columns.length > 0) ? columns : column_families.keys
sid = call :scannerOpenWithStop, start_row.to_s, end_row.to_s, columns
Scanner.new @client, sid, &block
end
|
pass in no params to scan whole table
|
Summarize the following code: def transition(read, write, move)
if read == @memory[@head]
@memory[@head] = write
case move
when 'R'
# Move right
@memory << '@' if @memory[@head + 1]
@head += 1
when 'L'
# Move left
@memory.unshift('@') if @head == 0
@head -= 1
end
return true
else
return false
end
end
|
Creates a new tape .
|
Summarize the following code: def feed(input)
heads, @stack, accept = [@start], [], false
# Move any initial e-transitions
eTrans = transition(@start, '&') if has_transition?(@start, '&')
heads += eTrans
puts "initial heads: #{heads}"
puts "initial stack: #{@stack}"
# Iterate through each symbol of input string
input.each_char do |symbol|
newHeads = []
puts "Reading symbol: #{symbol}"
heads.each do |head|
puts "At head #{head}"
# Check if head can transition read symbol
# Head dies if no transition for symbol
if has_transition?(head, symbol)
puts "Head #{head} transitions #{symbol}"
puts "stack: #{@stack}"
transition(head, symbol).each { |t| newHeads << t }
puts "heads: #{newHeads}"
puts "stack: #{@stack}"
end
end
heads = newHeads
break if heads.empty?
end
puts "Loop finished"
accept = includes_accept_state? heads
puts "heads: #{heads}"
puts "stack: #{stack}"
puts "accept: #{accept}"
resp = {
input: input,
accept: accept,
heads: heads,
stack: stack
}
end
|
Initialize a PDA object . Runs the input on the machine and returns a Hash describing the machine s final state after running .
|
Summarize the following code: def has_transition?(state, symbol)
return false unless @transitions.has_key? state
if @transitions[state].has_key? symbol
actions = @transitions[state][symbol]
return false if actions['pop'] && @stack.last != actions['pop']
return true
else
return false
end
end
|
Determines whether or not any transition states exist given a beginning state and input symbol pair .
|
Summarize the following code: def to_hash
self.class.attribute_names.inject({}) do |hash, name|
val = format_value(send(name.underscore))
val.empty? ? hash : hash.merge(format_key(name) => val)
end
end
|
Formats all attributes into a hash of parameters .
|
Summarize the following code: def format_value(val)
case val
when AmazonFlexPay::Model
val.to_hash
when Time
val.utc.strftime('%Y-%m-%dT%H:%M:%SZ')
when TrueClass, FalseClass
val.to_s.capitalize
when Array
val.join(',')
else
val.to_s
end
end
|
Formats times and booleans as Amazon desires them .
|
Summarize the following code: def assign(hash)
hash.each do |k, v|
send("#{k.to_s.underscore}=", v.respond_to?(:strip) ? v.strip : v)
end
end
|
Allows easy initialization for a model by assigning attributes from a hash .
|
Summarize the following code: def edit_token_pipeline(caller_reference, return_url, options = {})
cbui EditToken.new(options.merge(:caller_reference => caller_reference, :return_url => return_url))
end
|
Creates a pipeline that may be used to change the payment method of a token .
|
Summarize the following code: def multi_use_pipeline(caller_reference, return_url, options = {})
cbui MultiUse.new(options.merge(:caller_reference => caller_reference, :return_url => return_url))
end
|
Creates a pipeline that will authorize you to send money _from_ the user multiple times .
|
Summarize the following code: def recipient_pipeline(caller_reference, return_url, options = {})
cbui Recipient.new(options.merge(:caller_reference => caller_reference, :return_url => return_url))
end
|
Creates a pipeline that will authorize you to send money _to_ the user .
|
Summarize the following code: def single_use_pipeline(caller_reference, return_url, options = {})
cbui SingleUse.new(options.merge(:caller_reference => caller_reference, :return_url => return_url))
end
|
Creates a pipeline that will authorize you to send money _from_ the user one time .
|
Summarize the following code: def to_param
params = to_hash.merge(
'callerKey' => AmazonFlexPay.access_key,
'signatureVersion' => 2,
'signatureMethod' => 'HmacSHA256'
)
params['signature'] = AmazonFlexPay.sign(AmazonFlexPay.pipeline_endpoint, params)
AmazonFlexPay::Util.query_string(params)
end
|
Converts the Pipeline object into parameters and signs them .
|
Summarize the following code: def get_account_activity(start_date, end_date, options = {})
submit GetAccountActivity.new(options.merge(:start_date => start_date, :end_date => end_date))
end
|
Searches through transactions on your account . Helpful if you want to compare vs your own records or print an admin report .
|
Summarize the following code: def refund(transaction_id, caller_reference, options = {})
submit Refund.new(options.merge(:transaction_id => transaction_id, :caller_reference => caller_reference))
end
|
Refunds a transaction . By default it will refund the entire transaction but you can provide an amount for partial refunds .
|
Summarize the following code: def verify_request(request)
verify_signature(
# url without query string
request.protocol + request.host_with_port + request.path,
# raw parameters
request.get? ? request.query_string : request.raw_post
)
end
|
This is how you verify IPNs and pipeline responses . Pass the entire request object .
|
Summarize the following code: def submit(request)
url = request.to_url
ActiveSupport::Notifications.instrument("amazon_flex_pay.api", :action => request.action_name, :request => url) do |payload|
begin
http = RestClient.get(url)
payload[:response] = http.body
payload[:code] = http.code
response = request.class::Response.from_xml(http.body)
response.request = request
response
rescue RestClient::BadRequest, RestClient::Unauthorized, RestClient::Forbidden => e
payload[:response] = e.http_body
payload[:code] = e.http_code
er = AmazonFlexPay::API::BaseRequest::ErrorResponse.from_xml(e.response.body)
klass = AmazonFlexPay::API.const_get(er.errors.first.code)
raise klass.new(er.errors.first.code, er.errors.first.message, er.request_id, request)
end
end
end
|
This compiles an API request object into a URL sends it to Amazon and processes the response .
|
Summarize the following code: def save
return false unless valid?
self.last_result_set = if persisted?
self.class.requestor.update(self)
else
self.class.requestor.create(self)
end
if last_result_set.has_errors?
fill_errors
false
else
self.errors.clear if self.errors
mark_as_persisted!
if updated = last_result_set.first
self.attributes = updated.attributes
self.links.attributes = updated.links.attributes
self.relationships.attributes = updated.relationships.attributes
clear_changes_information
end
true
end
end
|
Commit the current changes to the resource to the remote server . If the resource was previously loaded from the server we will try to update the record . Otherwise if it s a new record then we will try to create it
|
Summarize the following code: def destroy
self.last_result_set = self.class.requestor.destroy(self)
if last_result_set.has_errors?
fill_errors
false
else
self.attributes.clear
true
end
end
|
Try to destroy this resource
|
Summarize the following code: def redi_search_schema(schema)
@schema = schema.to_a.flatten
@fields = schema.keys
@model = self.name.constantize
@index_name = @model.to_s
@score = 1
end
|
will configure the RediSearch for the specific model
|
Summarize the following code: def ft_search_count(args)
ft_search(args).first
rescue Exception => e
Rails.logger.error e if defined? Rails
return e.message
end
|
number of records found for keywords
|
Summarize the following code: def ft_add_all
@model.all.each {|record| ft_add(record: record) }
ft_optimize
rescue Exception => e
Rails.logger.error e if defined? Rails
return e.message
end
|
index all records in specific model
|
Summarize the following code: def ft_add record:
fields = []
@fields.each { |field| fields.push(field, record.send(field)) }
REDI_SEARCH.call('FT.ADD', @index_name, record.to_global_id.to_s, @score,
'REPLACE',
'FIELDS', fields
#'NOSAVE', 'PAYLOAD', 'LANGUAGE'
)
rescue Exception => e
Rails.logger.error e if defined? Rails
return e.message
end
|
index specific record
|
Summarize the following code: def ft_addhash redis_key:
REDI_SEARCH.call('FT.ADDHASH', @index_name, redis_key, @score, 'REPLACE')
rescue Exception => e
Rails.logger.error e if defined? Rails
return e.message
end
|
index existing Hash
|
Summarize the following code: def ft_del_all
@model.all.each {|record| ft_del(record: record) }
ft_optimize
rescue Exception => e
Rails.logger.error e if defined? Rails
return e.message
end
|
delete all records in specific model
|
Summarize the following code: def ft_del record:
doc_id = record.to_global_id
REDI_SEARCH.call('FT.DEL', @index_name, doc_id)
rescue Exception => e
Rails.logger.error e if defined? Rails
return e.message
end
|
delete specific document from index
|
Summarize the following code: def ft_info
REDI_SEARCH.call('FT.INFO', @index_name)
rescue Exception => e
Rails.logger.error e if defined? Rails
return e.message
end
|
get info about specific index
|
Summarize the following code: def ft_sugadd_all (attribute:)
@model.all.each {|record| ft_sugadd(record: record, attribute: attribute) }
rescue Exception => e
Rails.logger.error e if defined? Rails
return e.message
end
|
add all values for a model attribute to autocomplete
|
Summarize the following code: def ft_sugadd (record:, attribute:, score: 1)
# => combine model with attribute to create unique key like user_name
key = "#{@model.to_s}:#{attribute}"
string = record.send(attribute)
REDI_SEARCH.call('FT.SUGADD', key, string, score)
# => INCR
rescue Exception => e
Rails.logger.error e if defined? Rails
return e.message
end
|
add string to autocomplete dictionary
|
Summarize the following code: def ft_sugget (attribute:, prefix:)
key = "#{@model}:#{attribute}"
REDI_SEARCH.call('FT.SUGGET', key, prefix)
rescue Exception => e
Rails.logger.error e if defined? Rails
return e.message
end
|
query dictionary for suggestion
|
Summarize the following code: def ft_sugdel_all (attribute:)
@model.all.each {|record| ft_sugdel(record: record, attribute: attribute) }
rescue Exception => e
Rails.logger.error e if defined? Rails
return e.message
end
|
delete all values for a model attribute to autocomplete
|
Summarize the following code: def ft_suglen (attribute:)
key = "#{@model}:#{attribute}"
REDI_SEARCH.call('FT.SUGLEN', key)
rescue Exception => e
Rails.logger.error e if defined? Rails
return e.message
end
|
size of dictionary
|
Summarize the following code: def run
normalize_count = 0
if generate_gitattributes?
output_options = {:prefix => '# DO NOT EDIT: File is auto-generated', :normalize => true}
new_gitattributes = generate_gitattributes!
new_content = new_gitattributes.as_file_contents(output_options)
old_content = File.exist?(@attributes.attributes_file) ? IO.read(@attributes.attributes_file) : nil
if new_content != old_content
@attributes = new_gitattributes
if check_only?
puts 'Non-normalized .gitattributes file'
else
puts 'Fixing: .gitattributes'
@attributes.write(output_options)
end
normalize_count += 1
end
end
files = {}
collect_file_attributes(files)
files.each_pair do |filename, config|
full_filename = "#{@base_directory}/#{filename}"
original_bin_content = File.binread(full_filename)
encoding = config[:encoding].nil? ? 'utf-8' : config[:encoding].gsub(/^UTF/,'utf-')
content = File.read(full_filename, :encoding => "bom|#{encoding}")
content =
config[:dos] ?
clean_dos_whitespace(filename, content, config[:eofnl], config[:allow_empty]) :
clean_whitespace(filename, content, config[:eofnl], config[:allow_empty])
if config[:nodupnl]
while content.gsub!(/\n\n\n/, "\n\n")
# Keep removing duplicate new lines till they have gone
end
end
if content.bytes != original_bin_content.bytes
normalize_count += 1
if check_only?
puts "Non-normalized whitespace in #{filename}"
else
puts "Fixing: #{filename}"
File.open(full_filename, 'wb') do |out|
out.write content
end
end
end
end
normalize_count
end
|
Run normalization process across directory . Return the number of files that need normalization
|
Summarize the following code: def in_dir(dir, &block)
original_dir = Dir.pwd
begin
Dir.chdir(dir)
block.call
ensure
Dir.chdir(original_dir)
end
end
|
Evaluate block after changing directory to specified directory
|
Summarize the following code: def validate_token(access_token)
validator = Fridge.configuration.validator
validator.call(access_token) && access_token
rescue
false
end
|
Validates token and returns the token or nil
|
Summarize the following code: def validate_token!(access_token)
validator = Fridge.configuration.validator
if validator.call(access_token)
access_token
else
raise InvalidToken, 'Rejected by validator'
end
end
|
Validates token and raises an exception if invalid
|
Summarize the following code: def update(new_email_address, name, custom_fields, resubscribe,
consent_to_track, restart_subscription_based_autoresponders=false)
options = {
:query => { :email => @email_address },
:body => {
:EmailAddress => new_email_address,
:Name => name,
:CustomFields => custom_fields,
:Resubscribe => resubscribe,
:RestartSubscriptionBasedAutoresponders =>
restart_subscription_based_autoresponders,
:ConsentToTrack => consent_to_track }.to_json }
put "/subscribers/#{@list_id}.json", options
# Update @email_address, so this object can continue to be used reliably
@email_address = new_email_address
end
|
Updates any aspect of a subscriber including email address name and custom field data if supplied .
|
Summarize the following code: def history
options = { :query => { :email => @email_address } }
response = cs_get "/subscribers/#{@list_id}/history.json", options
response.map{|item| Hashie::Mash.new(item)}
end
|
Gets the historical record of this subscriber s trackable actions .
|
Summarize the following code: def subscribers(date="", page=1, page_size=1000, order_field="email",
order_direction="asc", include_tracking_preference=false)
options = { :query => {
:date => date,
:page => page,
:pagesize => page_size,
:orderfield => order_field,
:orderdirection => order_direction,
:includetrackingpreference => include_tracking_preference } }
response = get "active", options
Hashie::Mash.new(response)
end
|
Gets the active subscribers in this segment .
|
Summarize the following code: def update(name, html_url, zip_url)
options = { :body => {
:Name => name,
:HtmlPageURL => html_url,
:ZipFileURL => zip_url }.to_json }
put "/templates/#{template_id}.json", options
end
|
Updates this email template .
|
Summarize the following code: def clients
response = get('/clients.json')
response.map{|item| Hashie::Mash.new(item)}
end
|
Gets your clients .
|
Summarize the following code: def administrators
response = get('/admins.json')
response.map{|item| Hashie::Mash.new(item)}
end
|
Gets the administrators for the account .
|
Summarize the following code: def set_primary_contact(email)
options = { :query => { :email => email } }
response = put("/primarycontact.json", options)
Hashie::Mash.new(response)
end
|
Set the primary contect for the account .
|
Summarize the following code: def create_custom_field(field_name, data_type, options=[],
visible_in_preference_center=true)
options = { :body => {
:FieldName => field_name,
:DataType => data_type,
:Options => options,
:VisibleInPreferenceCenter => visible_in_preference_center }.to_json }
response = post "customfields", options
response.parsed_response
end
|
Creates a new custom field for this list . field_name - String representing the name to be given to the field data_type - String representing the data type of the field . Valid data types are Text Number MultiSelectOne MultiSelectMany Date Country and USState . options - Array of Strings representing the options for the field if it is of type MultiSelectOne or MultiSelectMany . visible_in_preference_center - Boolean indicating whether or not the field should be visible in the subscriber preference center
|
Summarize the following code: def update_custom_field(custom_field_key, field_name,
visible_in_preference_center)
custom_field_key = CGI.escape(custom_field_key)
options = { :body => {
:FieldName => field_name,
:VisibleInPreferenceCenter => visible_in_preference_center }.to_json }
response = put "customfields/#{custom_field_key}", options
response.parsed_response
end
|
Updates a custom field belonging to this list . custom_field_key - String which represents the key for the custom field field_name - String representing the name to be given to the field visible_in_preference_center - Boolean indicating whether or not the field should be visible in the subscriber preference center
|
Summarize the following code: def update_custom_field_options(custom_field_key, new_options,
keep_existing_options)
custom_field_key = CGI.escape(custom_field_key)
options = { :body => {
:Options => new_options,
:KeepExistingOptions => keep_existing_options }.to_json }
put "customfields/#{custom_field_key}/options", options
end
|
Updates the options of a multi - optioned custom field on this list .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.