input
stringlengths 109
5.2k
| output
stringlengths 7
509
|
---|---|
Summarize the following code: def check_array_collapse(data, field_def)
result = data
if !field_def[:min_occurs].nil? &&
(field_def[:max_occurs] == :unbounded ||
(!field_def[:max_occurs].nil? && field_def[:max_occurs] > 1)) &&
!(field_def[:type] =~ /MapEntry$/)
result = arrayize(result)
end
return result
end
|
Checks if the field signature allows an array and forces array structure even for a signle item .
|
Summarize the following code: def process_attributes(data, keep_xsi_type = false)
if keep_xsi_type
xsi_type = data.delete(:"@xsi:type")
data[:xsi_type] = xsi_type if xsi_type
end
data.reject! {|key, value| key.to_s.start_with?('@')}
end
|
Handles attributes received from Savon .
|
Summarize the following code: def service(name, version = nil)
name = name.to_sym
version = (version.nil?) ? api_config.default_version : version.to_sym
# Check if the combination is available.
validate_service_request(version, name)
# Try to re-use the service for this version if it was requested before.
wrapper = if @wrappers.include?(version) && @wrappers[version][name]
@wrappers[version][name]
else
@wrappers[version] ||= {}
@wrappers[version][name] = prepare_wrapper(version, name)
end
return wrapper
end
|
Obtain an API service given a version and its name .
|
Summarize the following code: def authorize(parameters = {}, &block)
parameters.each_pair do |key, value|
@credential_handler.set_credential(key, value)
end
auth_handler = get_auth_handler()
token = auth_handler.get_token()
# If token is invalid ask for a new one.
if token.nil?
begin
credentials = @credential_handler.credentials
token = auth_handler.get_token(credentials)
rescue AdsCommon::Errors::OAuth2VerificationRequired => e
verification_code = (block_given?) ? yield(e.oauth_url) : nil
# Retry with verification code if one provided.
if verification_code
@credential_handler.set_credential(
:oauth2_verification_code, verification_code)
retry
else
raise e
end
end
end
return token
end
|
Authorize with specified authentication method .
|
Summarize the following code: def save_oauth2_token(token)
raise AdsCommon::Errors::Error, "Can't save nil token" if token.nil?
AdsCommon::Utils.save_oauth2_token(
File.join(ENV['HOME'], api_config.default_config_filename), token)
end
|
Updates default configuration file to include OAuth2 token information .
|
Summarize the following code: def validate_service_request(version, service)
# Check if the current config supports the requested version.
unless api_config.has_version(version)
raise AdsCommon::Errors::Error,
"Version '%s' not recognized" % version.to_s
end
# Check if the specified version has the requested service.
unless api_config.version_has_service(version, service)
raise AdsCommon::Errors::Error,
"Version '%s' does not contain service '%s'" %
[version.to_s, service.to_s]
end
end
|
Auxiliary method to test parameters correctness for the service request .
|
Summarize the following code: def create_auth_handler()
auth_method = @config.read('authentication.method', :OAUTH2)
return case auth_method
when :OAUTH
raise AdsCommon::Errors::Error,
'OAuth authorization method is deprecated, use OAuth2 instead.'
when :OAUTH2
AdsCommon::Auth::OAuth2Handler.new(
@config,
api_config.config(:oauth_scope)
)
when :OAUTH2_SERVICE_ACCOUNT
AdsCommon::Auth::OAuth2ServiceAccountHandler.new(
@config,
api_config.config(:oauth_scope)
)
else
raise AdsCommon::Errors::Error,
"Unknown authentication method '%s'" % auth_method
end
end
|
Auxiliary method to create an authentication handler .
|
Summarize the following code: def prepare_wrapper(version, service)
api_config.do_require(version, service)
endpoint = api_config.endpoint(version, service)
interface_class_name = api_config.interface_name(version, service)
wrapper = class_for_path(interface_class_name).new(@config, endpoint)
auth_handler = get_auth_handler()
header_ns = api_config.config(:header_ns) + version.to_s
soap_handler = soap_header_handler(auth_handler, version, header_ns,
wrapper.namespace)
wrapper.header_handler = soap_handler
return wrapper
end
|
Handle loading of a single service . Creates the wrapper sets up handlers and creates an instance of it .
|
Summarize the following code: def create_default_logger()
logger = Logger.new(STDOUT)
logger.level = get_log_level_for_string(
@config.read('library.log_level', 'INFO'))
return logger
end
|
Auxiliary method to create a default Logger .
|
Summarize the following code: def load_config(provided_config = nil)
@config = (provided_config.nil?) ?
AdsCommon::Config.new(
File.join(ENV['HOME'], api_config.default_config_filename)) :
AdsCommon::Config.new(provided_config)
init_config()
end
|
Helper method to load the default configuration file or a given config .
|
Summarize the following code: def init_config()
# Set up logger.
provided_logger = @config.read('library.logger')
self.logger = (provided_logger.nil?) ?
create_default_logger() : provided_logger
# Set up default HTTPI adapter.
provided_adapter = @config.read('connection.adapter')
@config.set('connection.adapter', :httpclient) if provided_adapter.nil?
# Make sure Auth param is a symbol.
symbolize_config_value('authentication.method')
end
|
Initializes config with default values and converts existing if required .
|
Summarize the following code: def symbolize_config_value(key)
value_str = @config.read(key).to_s
if !value_str.nil? and !value_str.empty?
value = value_str.upcase.to_sym
@config.set(key, value)
end
end
|
Converts value of a config key to uppercase symbol .
|
Summarize the following code: def class_for_path(path)
path.split('::').inject(Kernel) do |scope, const_name|
scope.const_get(const_name)
end
end
|
Converts complete class path into class object .
|
Summarize the following code: def to_json
{
threads: @threads.to_json,
pipeline: @pipeline.size,
best: best.map(&:to_mnemo).join(', '),
farmer: @farmer.class.name
}
end
|
Renders the Farm into JSON to show for the end - user in front . rb .
|
Summarize the following code: def exists?(id, body)
DirItems.new(@dir).fetch.each do |f|
next unless f.start_with?("#{id}-")
return true if safe_read(File.join(@dir, f)) == body
end
false
end
|
Returns TRUE if a file for this wallet is already in the queue .
|
Summarize the following code: def exists?(details)
!@wallet.txns.find { |t| t.details.start_with?("#{PREFIX} ") && t.details == details }.nil?
end
|
Check whether this tax payment already exists in the wallet .
|
Summarize the following code: def push(id, body)
mods = @entrance.push(id, body)
return mods if @remotes.all.empty?
mods.each do |m|
next if @seen.include?(m)
@mutex.synchronize { @seen << m }
@modified.push(m)
@log.debug("Spread-push scheduled for #{m}, queue size is #{@modified.size}")
end
mods
end
|
This method is thread - safe
|
Summarize the following code: def init(id, pubkey, overwrite: false, network: 'test')
raise "File '#{path}' already exists" if File.exist?(path) && !overwrite
raise "Invalid network name '#{network}'" unless network =~ /^[a-z]{4,16}$/
FileUtils.mkdir_p(File.dirname(path))
IO.write(path, "#{network}\n#{PROTOCOL}\n#{id}\n#{pubkey.to_pub}\n\n")
@txns.flush
@head.flush
end
|
Creates an empty wallet with the specified ID and public key .
|
Summarize the following code: def balance
txns.inject(Amount::ZERO) { |sum, t| sum + t.amount }
end
|
Returns current wallet balance .
|
Summarize the following code: def sub(amount, invoice, pvt, details = '-', time: Time.now)
raise 'The amount has to be of type Amount' unless amount.is_a?(Amount)
raise "The amount can't be negative: #{amount}" if amount.negative?
raise 'The pvt has to be of type Key' unless pvt.is_a?(Key)
prefix, target = invoice.split('@')
tid = max + 1
raise 'Too many transactions already, can\'t add more' if max > 0xffff
txn = Txn.new(
tid,
time,
amount * -1,
prefix,
Id.new(target),
details
)
txn = txn.signed(pvt, id)
raise "Invalid private key for the wallet #{id}" unless Signature.new(network).valid?(key, id, txn)
add(txn)
txn
end
|
Add a payment transaction to the wallet .
|
Summarize the following code: def add(txn)
raise 'The txn has to be of type Txn' unless txn.is_a?(Txn)
raise "Wallet #{id} can't pay itself: #{txn}" if txn.bnf == id
raise "The amount can't be zero in #{id}: #{txn}" if txn.amount.zero?
if txn.amount.negative? && includes_negative?(txn.id)
raise "Negative transaction with the same ID #{txn.id} already exists in #{id}"
end
if txn.amount.positive? && includes_positive?(txn.id, txn.bnf)
raise "Positive transaction with the same ID #{txn.id} and BNF #{txn.bnf} already exists in #{id}"
end
raise "The tax payment already exists in #{id}: #{txn}" if Tax.new(self).exists?(txn.details)
File.open(path, 'a') { |f| f.print "#{txn}\n" }
@txns.flush
end
|
Add a transaction to the wallet .
|
Summarize the following code: def includes_negative?(id, bnf = nil)
raise 'The txn ID has to be of type Integer' unless id.is_a?(Integer)
!txns.find { |t| t.id == id && (bnf.nil? || t.bnf == bnf) && t.amount.negative? }.nil?
end
|
Returns TRUE if the wallet contains a payment sent with the specified ID which was sent to the specified beneficiary .
|
Summarize the following code: def includes_positive?(id, bnf)
raise 'The txn ID has to be of type Integer' unless id.is_a?(Integer)
raise 'The bnf has to be of type Id' unless bnf.is_a?(Id)
!txns.find { |t| t.id == id && t.bnf == bnf && !t.amount.negative? }.nil?
end
|
Returns TRUE if the wallet contains a payment received with the specified ID which was sent by the specified beneficiary .
|
Summarize the following code: def age
list = txns
list.empty? ? 0 : (Time.now - list.min_by(&:date).date) / (60 * 60)
end
|
Age of wallet in hours .
|
Summarize the following code: def max
negative = txns.select { |t| t.amount.negative? }
negative.empty? ? 0 : negative.max_by(&:id).id
end
|
Calculate the maximum transaction ID visible currently in the wallet . We go through them all and find the largest number . If there are no transactions zero is returned .
|
Summarize the following code: def propagate(id, _)
start = Time.now
modified = []
total = 0
network = @wallets.acq(id, &:network)
@wallets.acq(id, &:txns).select { |t| t.amount.negative? }.each do |t|
total += 1
if t.bnf == id
@log.error("Paying itself in #{id}? #{t}")
next
end
@wallets.acq(t.bnf, exclusive: true) do |target|
unless target.exists?
@log.debug("#{t.amount * -1} from #{id} to #{t.bnf}: wallet is absent")
next
end
unless target.network == network
@log.debug("#{t.amount * -1} to #{t.bnf}: network mismatch, '#{target.network}'!='#{network}'")
next
end
next if target.includes_positive?(t.id, id)
unless target.prefix?(t.prefix)
@log.debug("#{t.amount * -1} from #{id} to #{t.bnf}: wrong prefix \"#{t.prefix}\" in \"#{t}\"")
next
end
target.add(t.inverse(id))
@log.info("#{t.amount * -1} arrived to #{t.bnf}: #{t.details}")
modified << t.bnf
end
end
modified.uniq!
@log.debug("Wallet #{id} propagated successfully, #{total} txns \
in #{Age.new(start, limit: 20 + total * 0.005)}, #{modified.count} wallets affected")
modified.each do |w|
@wallets.acq(w, &:refurbish)
end
modified
end
|
Returns list of Wallet IDs which were affected
|
Summarize the following code: def exec(cmd, nohup_log)
start = Time.now
Open3.popen2e({ 'MALLOC_ARENA_MAX' => '2' }, cmd) do |stdin, stdout, thr|
nohup_log.print("Started process ##{thr.pid} from process ##{Process.pid}: #{cmd}\n")
stdin.close
until stdout.eof?
begin
line = stdout.gets
rescue IOError => e
line = Backtrace.new(e).to_s
end
nohup_log.print(line)
end
nohup_log.print("Nothing else left to read from ##{thr.pid}\n")
code = thr.value.to_i
nohup_log.print("Exit code of process ##{thr.pid} is #{code}, was alive for #{Age.new(start)}: #{cmd}\n")
code
end
end
|
Returns exit code
|
Summarize the following code: def add
raise 'Block must be given to start()' unless block_given?
latch = Concurrent::CountDownLatch.new(1)
thread = Thread.start do
Thread.current.name = @title
VerboseThread.new(@log).run do
latch.count_down
yield
end
end
latch.wait
Thread.current.thread_variable_set(
:kids,
(Thread.current.thread_variable_get(:kids) || []) + [thread]
)
@threads << thread
end
|
Add a new thread
|
Summarize the following code: def kill
if @threads.empty?
@log.debug("Thread pool \"#{@title}\" terminated with no threads")
return
end
@log.debug("Stopping \"#{@title}\" thread pool with #{@threads.count} threads: \
#{@threads.map { |t| "#{t.name}/#{t.status}" }.join(', ')}...")
start = Time.new
begin
join(0.1)
ensure
@threads.each do |t|
(t.thread_variable_get(:kids) || []).each(&:kill)
t.kill
sleep(0.001) while t.alive? # I believe it's a bug in Ruby, this line fixes it
Thread.current.thread_variable_set(
:kids,
(Thread.current.thread_variable_get(:kids) || []) - [t]
)
end
@log.debug("Thread pool \"#{@title}\" terminated all threads in #{Age.new(start)}, \
it was alive for #{Age.new(@start)}: #{@threads.map { |t| "#{t.name}/#{t.status}" }.join(', ')}")
@threads.clear
end
end
|
Kill them all immediately and close the pool
|
Summarize the following code: def to_json
@threads.map do |t|
{
name: t.name,
status: t.status,
alive: t.alive?,
vars: Hash[t.thread_variables.map { |v| [v.to_s, t.thread_variable_get(v)] }]
}
end
end
|
As a hash map
|
Summarize the following code: def to_s
@threads.map do |t|
[
"#{t.name}: status=#{t.status}; alive=#{t.alive?}",
'Vars: ' + t.thread_variables.map { |v| "#{v}=\"#{t.thread_variable_get(v)}\"" }.join('; '),
t.backtrace.nil? ? 'NO BACKTRACE' : " #{t.backtrace.join("\n ")}"
].join("\n")
end
end
|
As a text
|
Summarize the following code: def legacy(wallet, hours: 24)
raise 'You can\'t add legacy to a non-empty patch' unless @id.nil?
wallet.txns.each do |txn|
@txns << txn if txn.amount.negative? && txn.date < Time.now - hours * 60 * 60
end
end
|
Add legacy transactions first since they are negative and can t be deleted ever . This method is called by merge . rb in order to add legacy negative transactions to the patch before everything else . They are not supposed to be disputed ever .
|
Summarize the following code: def save(file, overwrite: false, allow_negative_balance: false)
raise 'You have to join at least one wallet in' if empty?
before = ''
wallet = Wallet.new(file)
before = wallet.digest if wallet.exists?
Tempfile.open([@id, Wallet::EXT]) do |f|
temp = Wallet.new(f.path)
temp.init(@id, @key, overwrite: overwrite, network: @network)
File.open(f.path, 'a') do |t|
@txns.each do |txn|
next if Id::BANNED.include?(txn.bnf.to_s)
t.print "#{txn}\n"
end
end
temp.refurbish
if temp.balance.negative? && !temp.id.root? && !allow_negative_balance
if wallet.exists?
@log.info("The balance is negative, won't merge #{temp.mnemo} on top of #{wallet.mnemo}")
else
@log.info("The balance is negative, won't save #{temp.mnemo}")
end
else
FileUtils.mkdir_p(File.dirname(file))
IO.write(file, IO.read(f.path))
end
end
before != wallet.digest
end
|
Returns TRUE if the file was actually modified
|
Summarize the following code: def clean(max: 24 * 60 * 60)
Futex.new(file, log: @log).open do
list = load
list.reject! do |s|
if s[:time] >= Time.now - max
false
else
@log.debug("Copy ##{s[:name]}/#{s[:host]}:#{s[:port]} is too old, over #{Age.new(s[:time])}")
true
end
end
save(list)
deleted = 0
files.each do |f|
next unless list.find { |s| s[:name] == File.basename(f, Copies::EXT) }.nil?
file = File.join(@dir, f)
size = File.size(file)
File.delete(file)
@log.debug("Copy at #{f} deleted: #{Size.new(size)}")
deleted += 1
end
list.select! do |s|
cp = File.join(@dir, "#{s[:name]}#{Copies::EXT}")
wallet = Wallet.new(cp)
begin
wallet.refurbish
raise "Invalid protocol #{wallet.protocol} in #{cp}" unless wallet.protocol == Zold::PROTOCOL
true
rescue StandardError => e
FileUtils.rm_rf(cp)
@log.debug("Copy at #{cp} deleted: #{Backtrace.new(e)}")
deleted += 1
false
end
end
save(list)
deleted
end
end
|
Delete all copies that are older than the max age provided in seconds .
|
Summarize the following code: def add(content, host, port, score, time: Time.now, master: false)
raise "Content can't be empty" if content.empty?
raise 'TCP port must be of type Integer' unless port.is_a?(Integer)
raise "TCP port can't be negative: #{port}" if port.negative?
raise 'Time must be of type Time' unless time.is_a?(Time)
raise "Time must be in the past: #{time}" if time > Time.now
raise 'Score must be Integer' unless score.is_a?(Integer)
raise "Score can't be negative: #{score}" if score.negative?
FileUtils.mkdir_p(@dir)
Futex.new(file, log: @log).open do
list = load
target = list.find do |s|
f = File.join(@dir, "#{s[:name]}#{Copies::EXT}")
digest = OpenSSL::Digest::SHA256.new(content).hexdigest
File.exist?(f) && OpenSSL::Digest::SHA256.file(f).hexdigest == digest
end
if target.nil?
max = DirItems.new(@dir).fetch
.select { |f| File.basename(f, Copies::EXT) =~ /^[0-9]+$/ }
.map(&:to_i)
.max
max = 0 if max.nil?
name = (max + 1).to_s
IO.write(File.join(@dir, "#{name}#{Copies::EXT}"), content)
else
name = target[:name]
end
list.reject! { |s| s[:host] == host && s[:port] == port }
list << {
name: name,
host: host,
port: port,
score: score,
time: time,
master: master
}
save(list)
name
end
end
|
Returns the name of the copy
|
Summarize the following code: def iterate(log, farm: Farm::Empty.new, threads: 1)
raise 'Log can\'t be nil' if log.nil?
raise 'Farm can\'t be nil' if farm.nil?
Hands.exec(threads, all) do |r, idx|
Thread.current.name = "remotes-#{idx}@#{r[:host]}:#{r[:port]}"
start = Time.now
best = farm.best[0]
node = RemoteNode.new(
host: r[:host],
port: r[:port],
score: best.nil? ? Score::ZERO : best,
idx: idx,
master: master?(r[:host], r[:port]),
log: log,
network: @network
)
begin
yield node
raise 'Took too long to execute' if (Time.now - start).round > @timeout
unerror(r[:host], r[:port]) if node.touched
rescue StandardError => e
error(r[:host], r[:port])
if e.is_a?(RemoteNode::CantAssert) || e.is_a?(Fetch::Error)
log.debug("#{Rainbow(node).red}: \"#{e.message.strip}\" in #{Age.new(start)}")
else
log.info("#{Rainbow(node).red}: \"#{e.message.strip}\" in #{Age.new(start)}")
log.debug(Backtrace.new(e).to_s)
end
remove(r[:host], r[:port]) if r[:errors] > TOLERANCE
end
end
end
|
Go through the list of remotes and call a provided block for each of them . See how it s used for example in fetch . rb .
|
Summarize the following code: def mark_as_unread(user)
if previous_post.nil?
read_state = postable.user_read_states.find_by(user_id: user.id)
read_state.destroy if read_state
else
postable.user_read_states.touch!(user.id, previous_post, overwrite_newer: true)
end
end
|
Marks all the posts from the given one as unread for the given user
|
Summarize the following code: def find_record(klass, id_or_record)
# Check by name because in development the Class might have been reloaded after id was initialized
id_or_record.class.name == klass.name ? id_or_record : klass.find(id_or_record)
end
|
Find a record by ID or return the passed record .
|
Summarize the following code: def moderation_state_visible_to_user?(user)
moderation_state_visible_to_all? ||
(!user.thredded_anonymous? &&
(user_id == user.id || user.thredded_can_moderate_messageboard?(messageboard)))
end
|
Whether this is visible to the given user based on the moderation state .
|
Summarize the following code: def protect! password = ''
@protected = true
password = password.to_s
if password.size == 0
@password_hash = 0
else
@password_hash = Excel::Password.password_hash password
end
end
|
Set worklist protection
|
Summarize the following code: def format_column idx, format=nil, opts={}
opts[:worksheet] = self
res = case idx
when Integer
column = nil
if format
column = Column.new(idx, format, opts)
end
@columns[idx] = column
else
idx.collect do |col| format_column col, format, opts end
end
shorten @columns
res
end
|
Sets the default Format of the column at _idx_ .
|
Summarize the following code: def update_row idx, *cells
res = if row = @rows[idx]
row[0, cells.size] = cells
row
else
Row.new self, idx, cells
end
row_updated idx, res
res
end
|
Updates the Row at _idx_ with the following arguments .
|
Summarize the following code: def merge_cells start_row, start_col, end_row, end_col
# FIXME enlarge or dup check
@merged_cells.push [start_row, end_row, start_col, end_col]
end
|
Merges multiple cells into one .
|
Summarize the following code: def formatted
copy = dup
Helpers.rcompact(@formats)
if copy.length < @formats.size
copy.concat Array.new(@formats.size - copy.length)
end
copy
end
|
Returns a copy of self with nil - values appended for empty cells that have an associated Format . This is primarily a helper - function for the writer classes .
|
Summarize the following code: def set_custom_color idx, red, green, blue
raise 'Invalid format' if [red, green, blue].find { |c| ! (0..255).include?(c) }
@palette[idx] = [red, green, blue]
end
|
Change the RGB components of the elements in the colour palette .
|
Summarize the following code: def format idx
case idx
when Integer
@formats[idx] || @default_format || Format.new
when String
@formats.find do |fmt| fmt.name == idx end
end
end
|
The Format at _idx_ or - if _idx_ is a String - the Format with name == _idx_
|
Summarize the following code: def worksheet idx
case idx
when Integer
@worksheets[idx]
when String
@worksheets.find do |sheet| sheet.name == idx end
end
end
|
The Worksheet at _idx_ or - if _idx_ is a String - the Worksheet with name == _idx_
|
Summarize the following code: def write io_path_or_writer
if io_path_or_writer.is_a? Writer
io_path_or_writer.write self
else
writer(io_path_or_writer).write(self)
end
end
|
Write this Workbook to a File IO Stream or Writer Object . The latter will make more sense once there are more than just an Excel - Writer available .
|
Summarize the following code: def _side_load(name, klass, resources)
associations = klass.associated_with(name)
associations.each do |association|
association.side_load(resources, @included[name])
end
resources.each do |resource|
loaded_associations = resource.loaded_associations
loaded_associations.each do |association|
loaded = resource.send(association[:name])
next unless loaded
_side_load(name, association[:class], to_array(loaded))
end
end
end
|
Traverses the resource looking for associations then descends into those associations and checks for applicable resources to side load
|
Summarize the following code: def <<(item)
fetch
if item.is_a?(Resource)
if item.is_a?(@resource_class)
@resources << item
else
raise "this collection is for #{@resource_class}"
end
else
@resources << wrap_resource(item, true)
end
end
|
Adds an item to this collection
|
Summarize the following code: def fetch!(reload = false)
if @resources && (!@fetchable || !reload)
return @resources
elsif association && association.options.parent && association.options.parent.new_record?
return (@resources = [])
end
@response = get_response(@query || path)
handle_response(@response.body)
@resources
end
|
Executes actual GET from API and loads resources into proper class .
|
Summarize the following code: def method_missing(name, *args, &block)
if resource_methods.include?(name)
collection_method(name, *args, &block)
elsif [].respond_to?(name, false)
array_method(name, *args, &block)
else
next_collection(name, *args, &block)
end
end
|
Sends methods to underlying array of resources .
|
Summarize the following code: def side_load(resources, side_loads)
key = "#{options.name}_id"
plural_key = "#{Inflection.singular options.name.to_s}_ids"
resources.each do |resource|
if resource.key?(plural_key) # Grab associations from child_ids field on resource
side_load_from_child_ids(resource, side_loads, plural_key)
elsif resource.key?(key) || options.singular
side_load_from_child_or_parent_id(resource, side_loads, key)
else # Grab associations from parent_id field from multiple child resources
side_load_from_parent_id(resource, side_loads, key)
end
end
end
|
Tries to place side loads onto given resources .
|
Summarize the following code: def save(options = {}, &block)
save!(options, &block)
rescue ZendeskAPI::Error::RecordInvalid => e
@errors = e.errors
false
rescue ZendeskAPI::Error::ClientError
false
end
|
Saves returning false if it fails and attaching the errors
|
Summarize the following code: def save_associations
self.class.associations.each do |association_data|
association_name = association_data[:name]
next unless send("#{association_name}_used?") && association = send(association_name)
inline_creation = association_data[:inline] == :create && new_record?
changed = association.is_a?(Collection) || association.changed?
if association.respond_to?(:save) && changed && !inline_creation && association.save
send("#{association_name}=", association) # set id/ids columns
end
if (association_data[:inline] == true || inline_creation) && changed
attributes[association_name] = association.to_param
end
end
end
|
Saves associations Takes into account inlining collections and id setting on the parent resource .
|
Summarize the following code: def reload!
response = @client.connection.get(path) do |req|
yield req if block_given?
end
handle_response(response)
attributes.clear_changes
self
end
|
Reloads a resource .
|
Summarize the following code: def create_many!(client, attributes_array, association = Association.new(:class => self))
response = client.connection.post("#{association.generate_path}/create_many") do |req|
req.body = { resource_name => attributes_array }
yield req if block_given?
end
JobStatus.new_from_response(client, response)
end
|
Creates multiple resources using the create_many endpoint .
|
Summarize the following code: def create_or_update!(client, attributes, association = Association.new(:class => self))
response = client.connection.post("#{association.generate_path}/create_or_update") do |req|
req.body = { resource_name => attributes }
yield req if block_given?
end
new_from_response(client, response, Array(association.options[:include]))
end
|
Creates or updates resource using the create_or_update endpoint .
|
Summarize the following code: def create_or_update_many!(client, attributes)
association = Association.new(:class => self)
response = client.connection.post("#{association.generate_path}/create_or_update_many") do |req|
req.body = { resource_name => attributes }
yield req if block_given?
end
JobStatus.new_from_response(client, response)
end
|
Creates or updates multiple resources using the create_or_update_many endpoint .
|
Summarize the following code: def destroy!
return false if destroyed? || new_record?
@client.connection.delete(url || path) do |req|
yield req if block_given?
end
@destroyed = true
end
|
If this resource hasn t already been deleted then do so .
|
Summarize the following code: def destroy_many!(client, ids, association = Association.new(:class => self))
response = client.connection.delete("#{association.generate_path}/destroy_many") do |req|
req.params = { :ids => ids.join(',') }
yield req if block_given?
end
JobStatus.new_from_response(client, response)
end
|
Destroys multiple resources using the destroy_many endpoint .
|
Summarize the following code: def update_many!(client, ids_or_attributes, attributes = {})
association = attributes.delete(:association) || Association.new(:class => self)
response = client.connection.put("#{association.generate_path}/update_many") do |req|
if attributes == {}
req.body = { resource_name => ids_or_attributes }
else
req.params = { :ids => ids_or_attributes.join(',') }
req.body = { singular_resource_name => attributes }
end
yield req if block_given?
end
JobStatus.new_from_response(client, response)
end
|
Updates multiple resources using the update_many endpoint .
|
Summarize the following code: def apply!(ticket = nil)
path = "#{self.path}/apply"
if ticket
path = "#{ticket.path}/#{path}"
end
response = @client.connection.get(path)
SilentMash.new(response.body.fetch("result", {}))
end
|
Returns the update to a ticket that happens when a macro will be applied .
|
Summarize the following code: def method_missing(method, *args, &block)
method = method.to_s
options = args.last.is_a?(Hash) ? args.pop : {}
@resource_cache[method] ||= { :class => nil, :cache => ZendeskAPI::LRUCache.new }
if !options.delete(:reload) && (cached = @resource_cache[method][:cache].read(options.hash))
cached
else
@resource_cache[method][:class] ||= method_as_class(method)
raise "Resource for #{method} does not exist" unless @resource_cache[method][:class]
@resource_cache[method][:cache].write(options.hash, ZendeskAPI::Collection.new(self, @resource_cache[method][:class], options))
end
end
|
Handles resources such as tickets . Any options are passed to the underlying collection except reload which disregards memoization and creates a new Collection instance .
|
Summarize the following code: def version(*versions, &block)
condition = lambda { |env|
versions.include?(env["HTTP_X_API_VERSION"])
}
with_conditions(condition, &block)
end
|
yield to a builder block in which all defined apps will only respond for the given version
|
Summarize the following code: def track_args(args)
case args
when Hash
timestamp, identity, values = args.values_at(:timestamp, :identity, :values)
when Array
values = args
when Numeric
values = [args]
end
identity ||= Vanity.context.vanity_identity rescue nil
[timestamp || Time.now, identity, values || [1]]
end
|
Parses arguments to track! method and return array with timestamp identity and array of values .
|
Summarize the following code: def render(path_or_options, locals = {})
if path_or_options.respond_to?(:keys)
render_erb(
path_or_options[:file] || path_or_options[:partial],
path_or_options[:locals]
)
else
render_erb(path_or_options, locals)
end
end
|
Render the named template . Used for reporting and the dashboard .
|
Summarize the following code: def method_missing(method, *args, &block)
%w(url_for flash).include?(method.to_s) ? ProxyEmpty.new : super
end
|
prevent certain url helper methods from failing so we can run erb templates outside of rails for reports .
|
Summarize the following code: def vanity_simple_format(text, options={})
open = "<p #{options.map { |k,v| "#{k}=\"#{CGI.escapeHTML v}\"" }.join(" ")}>"
text = open + text.gsub(/\r\n?/, "\n"). # \r\n and \r -> \n
gsub(/\n\n+/, "</p>\n\n#{open}"). # 2+ newline -> paragraph
gsub(/([^\n]\n)(?=[^\n])/, '\1<br />') + # 1 newline -> br
"</p>"
end
|
Dumbed down from Rails simple_format .
|
Summarize the following code: def experiment(name)
id = name.to_s.downcase.gsub(/\W/, "_").to_sym
Vanity.logger.warn("Deprecated: Please call experiment method with experiment identifier (a Ruby symbol)") unless id == name
experiments[id.to_sym] or raise NoExperimentError, "No experiment #{id}"
end
|
Returns the experiment . You may not have guessed but this method raises an exception if it cannot load the experiment s definition .
|
Summarize the following code: def custom_template_path_valid?
Vanity.playground.custom_templates_path &&
File.exist?(Vanity.playground.custom_templates_path) &&
!Dir[File.join(Vanity.playground.custom_templates_path, '*')].empty?
end
|
Check to make sure we set a custome path it exists and there are non - dotfiles in the directory .
|
Summarize the following code: def run
unless @executables.empty?
@config.executables = @executables
end
jobs = @jobs.flat_map do |job|
BenchmarkDriver::JobParser.parse({
type: @config.runner_type,
prelude: @prelude,
loop_count: @loop_count,
}.merge!(job))
end
BenchmarkDriver::Runner.run(jobs, config: @config)
end
|
Build jobs and run . This is NOT interface for users .
|
Summarize the following code: def get_user_configuration(opts)
opts = opts.clone
[:user_config_name, :user_config_props].each do |k|
validate_param(opts, k, true)
end
req = build_soap! do |type, builder|
if(type == :header)
else
builder.nbuild.GetUserConfiguration {|x|
x.parent.default_namespace = @default_ns
builder.user_configuration_name!(opts[:user_config_name])
builder.user_configuration_properties!(opts[:user_config_props])
}
end
end
do_soap_request(req, response_class: EwsSoapAvailabilityResponse)
end
|
The GetUserConfiguration operation gets a user configuration object from a folder .
|
Summarize the following code: def folder_shape!(folder_shape)
@nbuild.FolderShape {
@nbuild.parent.default_namespace = @default_ns
base_shape!(folder_shape[:base_shape])
if(folder_shape[:additional_properties])
additional_properties!(folder_shape[:additional_properties])
end
}
end
|
Build the FolderShape element
|
Summarize the following code: def item_shape!(item_shape)
@nbuild[NS_EWS_MESSAGES].ItemShape {
@nbuild.parent.default_namespace = @default_ns
base_shape!(item_shape[:base_shape])
mime_content!(item_shape[:include_mime_content]) if item_shape.has_key?(:include_mime_content)
body_type!(item_shape[:body_type]) if item_shape[:body_type]
if(item_shape[:additional_properties])
additional_properties!(item_shape[:additional_properties])
end
}
end
|
Build the ItemShape element
|
Summarize the following code: def indexed_page_item_view!(indexed_page_item_view)
attribs = {}
indexed_page_item_view.each_pair {|k,v| attribs[camel_case(k)] = v.to_s}
@nbuild[NS_EWS_MESSAGES].IndexedPageItemView(attribs)
end
|
Build the IndexedPageItemView element
|
Summarize the following code: def folder_ids!(fids, act_as=nil)
ns = @nbuild.parent.name.match(/subscription/i) ? NS_EWS_TYPES : NS_EWS_MESSAGES
@nbuild[ns].FolderIds {
fids.each do |fid|
fid[:act_as] = act_as if act_as != nil
dispatch_folder_id!(fid)
end
}
end
|
Build the FolderIds element
|
Summarize the following code: def distinguished_folder_id!(dfid, change_key = nil, act_as = nil)
attribs = {'Id' => dfid.to_s}
attribs['ChangeKey'] = change_key if change_key
@nbuild[NS_EWS_TYPES].DistinguishedFolderId(attribs) {
if ! act_as.nil?
mailbox!({:email_address => act_as})
end
}
end
|
Build the DistinguishedFolderId element
|
Summarize the following code: def folder_id!(fid, change_key = nil)
attribs = {'Id' => fid}
attribs['ChangeKey'] = change_key if change_key
@nbuild[NS_EWS_TYPES].FolderId(attribs)
end
|
Build the FolderId element
|
Summarize the following code: def additional_properties!(addprops)
@nbuild[NS_EWS_TYPES].AdditionalProperties {
addprops.each_pair {|k,v|
dispatch_field_uri!({k => v}, NS_EWS_TYPES)
}
}
end
|
Build the AdditionalProperties element
|
Summarize the following code: def mailbox!(mbox)
nbuild[NS_EWS_TYPES].Mailbox {
name!(mbox[:name]) if mbox[:name]
email_address!(mbox[:email_address]) if mbox[:email_address]
address!(mbox[:address]) if mbox[:address] # for Availability query
routing_type!(mbox[:routing_type]) if mbox[:routing_type]
mailbox_type!(mbox[:mailbox_type]) if mbox[:mailbox_type]
item_id!(mbox[:item_id]) if mbox[:item_id]
}
end
|
Build the Mailbox element . This element is commonly used for delegation . Typically passing an email_address is sufficient
|
Summarize the following code: def get_server_time_zones!(get_time_zone_options)
nbuild[NS_EWS_MESSAGES].GetServerTimeZones('ReturnFullTimeZoneData' => get_time_zone_options[:full]) do
if get_time_zone_options[:ids] && get_time_zone_options[:ids].any?
nbuild[NS_EWS_MESSAGES].Ids do
get_time_zone_options[:ids].each do |id|
nbuild[NS_EWS_TYPES].Id id
end
end
end
end
end
|
Request all known time_zones from server
|
Summarize the following code: def start_time_zone!(zone)
attributes = {}
attributes['Id'] = zone[:id] if zone[:id]
attributes['Name'] = zone[:name] if zone[:name]
nbuild[NS_EWS_TYPES].StartTimeZone(attributes)
end
|
Specifies an optional time zone for the start time
|
Summarize the following code: def end_time_zone!(zone)
attributes = {}
attributes['Id'] = zone[:id] if zone[:id]
attributes['Name'] = zone[:name] if zone[:name]
nbuild[NS_EWS_TYPES].EndTimeZone(attributes)
end
|
Specifies an optional time zone for the end time
|
Summarize the following code: def time_zone_definition!(zone)
attributes = {'Id' => zone[:id]}
attributes['Name'] = zone[:name] if zone[:name]
nbuild[NS_EWS_TYPES].TimeZoneDefinition(attributes)
end
|
Specify a time zone
|
Summarize the following code: def restriction!(restriction)
@nbuild[NS_EWS_MESSAGES].Restriction {
restriction.each_pair do |k,v|
self.send normalize_type(k), v
end
}
end
|
Build the Restriction element
|
Summarize the following code: def calendar_view!(cal_view)
attribs = {}
cal_view.each_pair {|k,v| attribs[camel_case(k)] = v.to_s}
@nbuild[NS_EWS_MESSAGES].CalendarView(attribs)
end
|
Build the CalendarView element
|
Summarize the following code: def contacts_view!(con_view)
attribs = {}
con_view.each_pair {|k,v| attribs[camel_case(k)] = v.to_s}
@nbuild[NS_EWS_MESSAGES].ContactsView(attribs)
end
|
Build the ContactsView element
|
Summarize the following code: def attachment_ids!(aids)
@nbuild.AttachmentIds {
@nbuild.parent.default_namespace = @default_ns
aids.each do |aid|
attachment_id!(aid)
end
}
end
|
Build the AttachmentIds element
|
Summarize the following code: def dispatch_item_id!(iid)
type = iid.keys.first
item = iid[type]
case type
when :item_id
item_id!(item)
when :occurrence_item_id
occurrence_item_id!(item)
when :recurring_master_item_id
recurring_master_item_id!(item)
else
raise EwsBadArgumentError, "Bad ItemId type. #{type}"
end
end
|
A helper method to dispatch to an ItemId OccurrenceItemId or a RecurringMasterItemId
|
Summarize the following code: def dispatch_update_type!(update)
type = update.keys.first
upd = update[type]
case type
when :append_to_item_field
append_to_item_field!(upd)
when :set_item_field
set_item_field!(upd)
when :delete_item_field
delete_item_field!(upd)
else
raise EwsBadArgumentError, "Bad Update type. #{type}"
end
end
|
A helper method to dispatch to a AppendToItemField SetItemField or DeleteItemField
|
Summarize the following code: def dispatch_field_uri!(uri, ns=NS_EWS_MESSAGES)
type = uri.keys.first
vals = uri[type].is_a?(Array) ? uri[type] : [uri[type]]
case type
when :field_uRI, :field_uri
vals.each do |val|
value = val.is_a?(Hash) ? val[type] : val
nbuild[ns].FieldURI('FieldURI' => value)
end
when :indexed_field_uRI, :indexed_field_uri
vals.each do |val|
nbuild[ns].IndexedFieldURI(
'FieldURI' => (val[:field_uRI] || val[:field_uri]),
'FieldIndex' => val[:field_index]
)
end
when :extended_field_uRI, :extended_field_uri
vals.each do |val|
nbuild[ns].ExtendedFieldURI {
nbuild.parent['DistinguishedPropertySetId'] = val[:distinguished_property_set_id] if val[:distinguished_property_set_id]
nbuild.parent['PropertySetId'] = val[:property_set_id] if val[:property_set_id]
nbuild.parent['PropertyTag'] = val[:property_tag] if val[:property_tag]
nbuild.parent['PropertyName'] = val[:property_name] if val[:property_name]
nbuild.parent['PropertyId'] = val[:property_id] if val[:property_id]
nbuild.parent['PropertyType'] = val[:property_type] if val[:property_type]
}
end
else
raise EwsBadArgumentError, "Bad URI type. #{type}"
end
end
|
A helper to dispatch to a FieldURI IndexedFieldURI or an ExtendedFieldURI
|
Summarize the following code: def dispatch_field_item!(item, ns_prefix = nil)
item.values.first[:xmlns_attribute] = ns_prefix if ns_prefix
build_xml!(item)
end
|
Insert item enforce xmlns attribute if prefix is present
|
Summarize the following code: def update_item!(updates, options = {})
item_updates = []
updates.each do |attribute, value|
item_field = FIELD_URIS[attribute][:text] if FIELD_URIS.include? attribute
field = {field_uRI: {field_uRI: item_field}}
if value.nil? && item_field
# Build DeleteItemField Change
item_updates << {delete_item_field: field}
elsif item_field
# Build SetItemField Change
item = Viewpoint::EWS::Template::CalendarItem.new(attribute => value)
# Remap attributes because ews_builder #dispatch_field_item! uses #build_xml!
item_attributes = item.to_ews_item.map do |name, value|
if value.is_a? String
{name => {text: value}}
elsif value.is_a? Hash
node = {name => {}}
value.each do |attrib_key, attrib_value|
attrib_key = camel_case(attrib_key) unless attrib_key == :text
node[name][attrib_key] = attrib_value
end
node
else
{name => value}
end
end
item_updates << {set_item_field: field.merge(calendar_item: {sub_elements: item_attributes})}
else
# Ignore unknown attribute
end
end
if item_updates.any?
data = {}
data[:conflict_resolution] = options[:conflict_resolution] || 'AutoResolve'
data[:send_meeting_invitations_or_cancellations] = options[:send_meeting_invitations_or_cancellations] || 'SendToNone'
data[:item_changes] = [{item_id: self.item_id, updates: item_updates}]
rm = ews.update_item(data).response_messages.first
if rm && rm.success?
self.get_all_properties!
self
else
raise EwsCreateItemError, "Could not update calendar item. #{rm.code}: #{rm.message_text}" unless rm
end
end
end
|
Updates the specified item attributes
|
Summarize the following code: def sync_folder_hierarchy(opts)
opts = opts.clone
req = build_soap! do |type, builder|
if(type == :header)
else
builder.nbuild.SyncFolderHierarchy {
builder.nbuild.parent.default_namespace = @default_ns
builder.folder_shape!(opts[:folder_shape])
builder.sync_folder_id!(opts[:sync_folder_id]) if opts[:sync_folder_id]
builder.sync_state!(opts[:sync_state]) if opts[:sync_state]
}
end
end
do_soap_request(req, response_class: EwsResponse)
end
|
Defines a request to synchronize a folder hierarchy on a client
|
Summarize the following code: def sync_folder_items(opts)
opts = opts.clone
req = build_soap! do |type, builder|
if(type == :header)
else
builder.nbuild.SyncFolderItems {
builder.nbuild.parent.default_namespace = @default_ns
builder.item_shape!(opts[:item_shape])
builder.sync_folder_id!(opts[:sync_folder_id]) if opts[:sync_folder_id]
builder.sync_state!(opts[:sync_state]) if opts[:sync_state]
builder.ignore!(opts[:ignore]) if opts[:ignore]
builder.max_changes_returned!(opts[:max_changes_returned])
builder.sync_scope!(opts[:sync_scope]) if opts[:sync_scope]
}
end
end
do_soap_request(req, response_class: EwsResponse)
end
|
Synchronizes items between the Exchange server and the client
|
Summarize the following code: def get_user_availability(email_address, start_time, end_time)
opts = {
mailbox_data: [ :email =>{:address => email_address} ],
free_busy_view_options: {
time_window: {start_time: start_time, end_time: end_time},
}
}
resp = (Viewpoint::EWS::EWS.instance).ews.get_user_availability(opts)
if(resp.status == 'Success')
return resp.items
else
raise EwsError, "GetUserAvailability produced an error: #{resp.code}: #{resp.message}"
end
end
|
Get information about when the user with the given email address is available .
|
Summarize the following code: def move!(new_folder)
new_folder = new_folder.id if new_folder.kind_of?(GenericFolder)
move_opts = {
:to_folder_id => {:id => new_folder},
:item_ids => [{:item_id => {:id => self.id}}]
}
resp = @ews.move_item(move_opts)
rmsg = resp.response_messages[0]
if rmsg.success?
obj = rmsg.items.first
itype = obj.keys.first
obj[itype][:elems][0][:item_id][:attribs][:id]
else
raise EwsError, "Could not move item. #{resp.code}: #{resp.message}"
end
end
|
Move this item to a new folder
|
Summarize the following code: def copy(new_folder)
new_folder = new_folder.id if new_folder.kind_of?(GenericFolder)
copy_opts = {
:to_folder_id => {:id => new_folder},
:item_ids => [{:item_id => {:id => self.id}}]
}
resp = @ews.copy_item(copy_opts)
rmsg = resp.response_messages[0]
if rmsg.success?
obj = rmsg.items.first
itype = obj.keys.first
obj[itype][:elems][0][:item_id][:attribs][:id]
else
raise EwsError, "Could not copy item. #{rmsg.response_code}: #{rmsg.message_text}"
end
end
|
Copy this item to a new folder
|
Summarize the following code: def get_item(opts = {})
args = get_item_args(opts)
resp = ews.get_item(args)
get_item_parser(resp)
end
|
Get a specific item by its ID .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.