input stringlengths 109 5.2k | output stringlengths 7 509 |
|---|---|
Summarize the following code: def set_vm_disk_info(vmid, disk_info={})
get_response, headers = __get_disk_info(vmid)
if disk_info[:add]
data = add_disk(get_response, disk_info)
else
data = edit_disk(get_response, disk_info)
end
params = {
'method' => :put,
... | Set information about Disks |
Summarize the following code: def set_vm_cpus(vmid, cpu_number)
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmid}/virtualHardwareSection/cpu"
}
get_response, headers = send_request(params)
# Change attributes from the previous invocation
get_response.css("rasd|E... | Set VM CPUs |
Summarize the following code: def set_vm_ram(vmid, memory_size)
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmid}/virtualHardwareSection/memory"
}
get_response, headers = send_request(params)
# Change attributes from the previous invocation
get_response.css("ras... | Set VM RAM |
Summarize the following code: def edit_vm_network(vmId, network, config={})
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmId}/networkConnectionSection"
}
netconfig_response, headers = send_request(params)
if config[:primary_index]
node = netconfig_response.css... | Edit VM Network Config |
Summarize the following code: def add_vm_network(vmId, network, config={})
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmId}/networkConnectionSection"
}
netconfig_response, headers = send_request(params)
parent_section = netconfig_response.css('NetworkConnectionSectio... | Add a new network to a VM |
Summarize the following code: def delete_vm_network(vmId, network)
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmId}/networkConnectionSection"
}
netconfig_response, headers = send_request(params)
picked_network = netconfig_response.css("NetworkConnection").select do |... | Remove an existing network |
Summarize the following code: def set_vm_guest_customization(vmid, computer_name, config={})
builder = Nokogiri::XML::Builder.new do |xml|
xml.GuestCustomizationSection(
"xmlns" => "http://www.vmware.com/vcloud/v1.5",
"xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1") {
xml['... | Set VM Guest Customization Config |
Summarize the following code: def get_vm(vmId)
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmId}"
}
response, headers = send_request(params)
vm_name = response.css('Vm').attribute("name")
vm_name = vm_name.text unless vm_name.nil?
status = convert_vapp_st... | Fetch details about a given VM |
Summarize the following code: def get_vm_by_name(organization, vdcName, vAppName, vmName)
result = nil
get_vapp_by_name(organization, vdcName, vAppName)[:vms_hash].each do |key, values|
if key.downcase == vmName.downcase
result = get_vm(values[:id])
end
end
result
... | Friendly helper method to fetch a vApp by name - Organization object - Organization VDC Name - vApp Name - VM Name |
Summarize the following code: def poweroff_vm(vmId)
builder = Nokogiri::XML::Builder.new do |xml|
xml.UndeployVAppParams(
"xmlns" => "http://www.vmware.com/vcloud/v1.5") {
xml.UndeployPowerAction 'powerOff'
}
end
params = {
'method' => :post,
'command' => "... | Shutdown a given vm |
Summarize the following code: def acquire_ticket_vm(vmId)
params = {
'method' => :post,
'command' => "/vApp/vm-#{vmId}/screen/action/acquireTicket"
}
response, headers = send_request(params)
screen_ticket = response.css("ScreenTicket").text
result = {}
if screen_... | Retrieve a screen ticket that you can use with the VMRC browser plug - in to gain access to the console of a running VM . |
Summarize the following code: def get_network(networkId)
response = get_base_network(networkId)
name = response.css('OrgVdcNetwork').attribute('name').text
description = response.css("Description").first
description = description.text unless description.nil?
gateway = response.css('Gate... | Fetch details about a given Org VDC network |
Summarize the following code: def get_organizations
params = {
'method' => :get,
'command' => '/org'
}
response, headers = send_request(params)
orgs = response.css('OrgList Org')
results = {}
orgs.each do |org|
results[org['name']] = org['href'].gsub(/.*\/or... | Fetch existing organizations and their IDs |
Summarize the following code: def get_tasks_list(id)
params = {
'method' => :get,
'command' => "/tasksList/#{id}"
}
response, headers = send_request(params)
tasks = []
response.css('Task').each do |task|
id = task['href'].gsub(/.*\/task\//, "")
operation ... | Fetch tasks from a given task list |
Summarize the following code: def get_vdc_id_by_name(organization, vdcName)
result = nil
organization[:vdcs].each do |vdc|
if vdc[0].downcase == vdcName.downcase
result = vdc[1]
end
end
result
end | Friendly helper method to fetch a Organization VDC Id by name - Organization object - Organization VDC Name |
Summarize the following code: def get_vdc_by_name(organization, vdcName)
result = nil
organization[:vdcs].each do |vdc|
if vdc[0].downcase == vdcName.downcase
result = get_vdc(vdc[1])
end
end
result
end | Friendly helper method to fetch a Organization VDC by name - Organization object - Organization VDC Name |
Summarize the following code: def add!(container)
### add container's providers ###
# internally providers are added in reverse order (last one first)
# so at runtime you it's easy and fast to grab the latest provider
# so when adding now, we have to reverse the providers to get them in the orig... | adding existing containers - related methods |
Summarize the following code: def get_provider(id, opts = {})
# get all matching providers
matching_provider_args = providers.find_all{|args| args.first == id}
# sort providers on priority, form high to low
matching_provider_args.sort! do |args_a, args_b|
# we want to sort from high prio... | returns the requested provider as a Provider object |
Summarize the following code: def call!(env)
@env = env.dup
status, @headers, response = @app.call(@env)
if should_clean?
@headers.delete('Content-Length')
response = Rack::Response.new(
tidy_markup(response.respond_to?(:body) ? response.body : response),
stat... | thread safe version using shallow copy of env |
Summarize the following code: def for *classes, &proc
classes.each { |receiver_class| ForClassContext.new(self, receiver_class).instance_eval &proc }
end | For class context |
Summarize the following code: def evaluate name, receiver, args, call = nil, context = nil
matcher = Support::Matcher.new self, name, receiver, args
matcher.match.new(receiver, call, context).send name, *args
end | Evaluate or cast |
Summarize the following code: def progress(message, &block)
spinner = %w[/ - \\ |].cycle
print "\e[90m#{message}... \e[0m"
result = observing_thread(block, 0.5, 0.1) do
print "\r\e[90m#{message}... #{spinner.next} \e[0m"
end
puts "\r\e[90m#{message}... OK\e[0m"
result
res... | Runs a block in the background and displays a spinner until it completes . |
Summarize the following code: def tableize(rows, &block)
rows = rows.map(&block) if block
widths = max_length_of_each_column(rows)
rows.map do |row|
row.zip(widths).map { |value, width| value.ljust(width) }.join(" ")
end
end | Given a two - dimensional Array of strings representing a table of data translate each row into a single string by joining the values with whitespace such that all the columns are nicely aligned . |
Summarize the following code: def observing_thread(callable, initial_wait, periodic_wait)
thread = Thread.new(&callable)
wait_for_exit(thread, initial_wait)
loop do
break if wait_for_exit(thread, periodic_wait)
yield
end
thread.value
end | Starts the callable in a background thread and waits for it to complete . If the callable fails with an exception it will be raised here . Otherwise the main thread is paused for an initial_wait time in seconds and subsequently for periodic_wait repeatedly until the thread completes . After each wait yield is called to... |
Summarize the following code: def all
requester = Rescuetime::Requester
host = HOST
parse_response requester.get(host, params)
end | Performs the rescuetime query and returns an array or csv response . |
Summarize the following code: def format(format)
# Guard: fail if the passed format isn't on the whitelist
format = format.to_s
formatters.all.include?(format) || raise(Errors::InvalidFormatError)
@format = format
self
end | Sets the report format to a valid type |
Summarize the following code: def parse_response(body)
report = CSV.new(body,
headers: true,
header_converters: :symbol,
converters: :all)
format = @format.to_s.downcase
report_formatter = formatters.find(format)
re... | Parses a response from the string response body to the desired format . |
Summarize the following code: def find(name)
formatter = formatters.find do |f|
standardize(f.name) == standardize(name)
end
formatter || raise(Rescuetime::Errors::InvalidFormatError)
end | Returns the formatter with the specified name or if not found raises an exception |
Summarize the following code: def order_by(order, interval: nil)
# set order and intervals as symbols
order = order.to_s
interval = interval ? interval.to_s : nil
# guards against invalid order or interval
unless valid_order? order
raise Errors::InvalidQueryError, "#{order} is ... | Specifies the ordering and the interval of the returned Rescuetime report . For example the results can be ordered by time activity rank or member ; The results can be returned in intervals spanning a month a week a day an hour or 5 - minutes . |
Summarize the following code: def where(name: nil, document: nil)
# Stand-in for required keyword arguments
name || raise(ArgumentError, 'missing keyword: name')
add_to_query restrict_thing: name,
restrict_thingy: document
end | Limits the Rescuetime report to specific activities and documents . The name option limits the results to those where name is an exact match ; this can be used on the overview activity and category report . The document option limits the specific document title ; this is only available on the activity report . |
Summarize the following code: def add_to_query(**terms)
if is_a? Rescuetime::Collection
self << terms
self
else
Rescuetime::Collection.new(BASE_PARAMS, state, terms)
end
end | Adds terms to the Rescuetime collection query |
Summarize the following code: def valid_credentials?
return false unless api_key?
!activities.all.nil?
rescue Rescuetime::Errors::InvalidCredentialsError
false
end | Returns true if the provided api key is valid . Performs a request to the Rescuetime API . |
Summarize the following code: def load_formatter_files(local_path: LOCAL_FORMATTER_PATH)
# require all formatters, local and configured
paths = Rescuetime.configuration.formatter_paths << local_path
paths.each do |path|
Dir[File.expand_path(path, __FILE__)].each { |file| require file }
e... | Requires all formatter files determined by the local path for formatters plus any additional paths set in the Rescuetime configuration . |
Summarize the following code: def parse
self.class.rules.each do |target, (selector, delegate, plural)|
if plural
send(target).concat @doc.search(selector).map { |i| parse_result(i, delegate) }
else
send("#{target}=", parse_result(@doc.at(selector), delegate))
end
... | Initialize the parser with a document Parse the document and save values returned by selectors |
Summarize the following code: def to_hash
converter = lambda { |obj| obj.respond_to?(:to_hash) ? obj.to_hash : obj }
self.class.rules.keys.inject({}) do |hash, name|
value = send(name)
hash[name.to_sym] = Array === value ? value.map(&converter) : converter[value]
hash
end
e... | Dump the extracted data into a hash with symbolized keys |
Summarize the following code: def parse_result(node, delegate)
if delegate
method = delegate.is_a?(Proc) ? delegate : delegate.method(delegate.respond_to?(:call) ? :call : :parse)
method.arity == 1 ? method[node] : method[node, self]
else
node
end unless node.nil?
end | delegate is optional but should respond to call or parse |
Summarize the following code: def get_document(url)
URI === url ? Nokogiri::HTML::Document.parse(open(url), url.to_s, 'UTF-8') : url
rescue OpenURI::HTTPError
$stderr.puts "ERROR opening #{url}"
Nokogiri('')
end | open web pages with UTF - 8 encoding |
Summarize the following code: def subject
unless @subject
subject = mail.subject.strip rescue ""
ignores = config['ignore']['text/plain']
if ignores && ignores.detect{|s| s == subject}
@subject = ""
else
@subject = transform_text('text/plain', subject).last
... | Return the Subject for this message returns for default carrier subject such as Multimedia message for ATT&T carrier . |
Summarize the following code: def ignore_media?(type, part)
ignores = config['ignore'][type] || []
ignore = ignores.detect{ |test| filename?(part) == test}
ignore ||= ignores.detect{ |test| filename?(part) =~ test if test.is_a?(Regexp) }
ignore ||= ignores.detect{ |test| part.body.decoded.stri... | Helper for process template method to determine if media contained in a part should be ignored . Producers should override this method to return true for media such as images that are advertising carrier logos etc . See the ignore section in the discussion of the built - in configuration . |
Summarize the following code: def process_media(part)
# Mail body auto-magically decodes quoted
# printable for text/html type.
file = temp_file(part)
if part.part_type? =~ /^text\// ||
part.part_type? == 'application/smil'
type, content = transform_text_part(part)
else
... | Helper for process template method to decode the part based on its type and write its content to a temporary file . Returns path to temporary file that holds the content . Parts with a main type of text will have their contents transformed with a call to transform_text |
Summarize the following code: def process_part(part)
return if ignore_media?(part.part_type?, part)
type, file = process_media(part)
add_file(type, file) unless type.nil? || file.nil?
end | Helper to decide if a part should be kept or ignored |
Summarize the following code: def transform_text(type, text)
return type, text if !config['transform'] || !(transforms = config['transform'][type])
if RUBY_VERSION < "1.9"
require 'iconv'
ic = Iconv.new('UTF-8', 'ISO-8859-1')
text = ic.iconv(text)
text << ic.iconv(nil)
... | Helper for process_media template method to transform text . See the transform section in the discussion of the built - in configuration . |
Summarize the following code: def transform_text_part(part)
type = part.part_type?
text = part.body.decoded.strip
transform_text(type, text)
end | Helper for process_media template method to transform text . |
Summarize the following code: def temp_file(part)
file_name = filename?(part)
File.expand_path(File.join(msg_tmp_dir(),File.basename(file_name)))
end | Helper for process template method to name a temporary filepath based on information in the part . This version attempts to honor the name of the media as labeled in the part header and creates a unique temporary directory for writing the file so filename collision does not occur . Consumers of this method expect the d... |
Summarize the following code: def add_file(type, file)
media[type] = [] unless media[type]
media[type] << file
end | Helper to add a file to the media hash . |
Summarize the following code: def msg_tmp_dir
@dir_count += 1
dir = File.expand_path(File.join(@media_dir, "#{@dir_count}"))
FileUtils.mkdir_p(dir)
dir
end | Helper to temp_file to create a unique temporary directory that is a child of tmp_dir This version is based on the message_id of the mail . |
Summarize the following code: def filename?(part)
name = part.filename
if (name.nil? || name.empty?)
if part.content_id && (matched = /^<(.+)>$/.match(part.content_id))
name = matched[1]
else
name = "#{Time.now.to_f}.#{self.default_ext(part.part_type?)}"
end
... | returns a filename declared for a part or a default if its not defined |
Summarize the following code: def type_from_filename(filename)
ext = filename.split('.').last
ent = MMS2R::EXT.detect{|k,v| v == ext}
ent.nil? ? nil : ent.first
end | guess content type from filename |
Summarize the following code: def prefetch_primary_key?(table_name = nil)
return true if table_name.nil?
table_name = table_name.to_s
primary_keys(table_name.to_s).size == 0
end | If true next_sequence_value is called before each insert statement to set the record s primary key . By default DB2 for i supports IDENTITY_VAL_LOCAL for tables that have one primary key . |
Summarize the following code: def execute_and_auto_confirm(sql, name = nil)
begin
execute_system_command('CHGJOB INQMSGRPY(*SYSRPYL)')
execute_system_command("ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY('I')")
rescue Exception => e
raise unauthorized_error_message("CHGJOB INQMSGRPY(*SY... | Holy moly batman! all this to tell AS400 yes i am sure |
Summarize the following code: def get_transfer(type)
type = type[0].upcase + type[1..-1]
try_require(type)
Transfer.const_get(type).new(@options, @files)
end | Creates an instance for the transfer type and return it |
Summarize the following code: def peek(aheadCount=1)
history = []
aheadCount.times { history << @input.getc }
history.reverse.each { |chr| @input.ungetc(chr) }
return history.last.chr
end | Get the next character without getting it . |
Summarize the following code: def captureOutput(output, didFinishProcessingPhoto: photo, error: error)
if error
error_callback.call(error)
else
@capture_callback.call(photo.fileDataRepresentation)
end
end | iOS 11 + AVCapturePhotoCaptureDelegate method |
Summarize the following code: def captureOutput(output, didFinishProcessingPhotoSampleBuffer: photo_sample_buffer, previewPhotoSampleBuffer: preview_photo_sample_buffer, resolvedSettings: resolved_settings, bracketSettings: bracket_settings, error: error)
if error
error_callback.call(error)
else
jpe... | iOS 10 AVCapturePhotoCaptureDelegate method |
Summarize the following code: def save_to_assets_library(jpeg_data, &block)
assets_library.writeImageDataToSavedPhotosAlbum(jpeg_data, metadata: nil, completionBlock: -> (asset_url, error) {
error ? error_callback.call(error) : block.call(asset_url)
})
end | iOS 4 - 8 |
Summarize the following code: def save_to_photo_library(jpeg_data, &block)
photo_library.performChanges(-> {
image = UIImage.imageWithData(jpeg_data)
PHAssetChangeRequest.creationRequestForAssetFromImage(image)
}, completionHandler: -> (success, error) {
if error
error_callback.call(er... | iOS 8 + |
Summarize the following code: def update_video_orientation!
photo_output.connectionWithMediaType(AVMediaTypeVideo).tap do |connection|
device_orientation = UIDevice.currentDevice.orientation
video_orientation = orientation_mapping.fetch(device_orientation, AVCaptureVideoOrientationPortrait)
conn... | iOS 10 + |
Summarize the following code: def select_levels(data, backtrack, kmin, kmax)
return kmin if kmin == kmax
method = :normal # "uniform" or "normal"
kopt = kmin
base = 1 # The position of first element in x: 1 or 0.
n = data.size - base
max_bic = 0.0
for k in kmin... | Choose an optimal number of levels between Kmin and Kmax |
Summarize the following code: def full_feature(value=true)
return unless value
@config.formulize
@config.event = (@config.event + [:call, :return]).uniq
@config.import_return_to_call = true
@config.show_additional_attrs = [:path, :lineno]
# JSON serialize trigger many problems when h... | todo . value equal 10 may not be a good params |
Summarize the following code: def stack(name = nil, opts = {})
if self::StackMiddleware._mwares[name] && mw = self::StackMiddleware._mwares[name]
unless mw.stack == self
mw = self::StackMiddleware._mwares[name] = self::StackMiddleware._mwares[name].dup
end
mw
else
s... | Useful for adding additional information into your middleware stack definition |
Summarize the following code: def use(middleware, *_args, &block)
stack(middleware).use(middleware, *_args, &block)
end | Adds middleware to the current stack definition |
Summarize the following code: def attribute_lookup(assoc)
group_data = @map[assoc.group.to_sym]
return nil unless group_data
attribute = group_data[assoc.type.to_sym]
return attribute
end | Extracts the attribute definition for a given association |
Summarize the following code: def translate_association(assoc)
attribute = attribute_lookup(assoc)
return unless attribute
# Make sure we properly handle destroyed values by forcing them to an
# empty association. We keep their state up to this point because the
# caller may be using the... | Maps an association to the attribute its data will be tied |
Summarize the following code: def add_association_to_attribute_map(attribute, assoc)
current = @attributes[attribute]
# If there's already a value, we can safely ignore the empty association
return if current && assoc.blank?
case current
when nil then @attributes[attribute] = [assoc... | Adds the given association to an array of associations for the given attribute |
Summarize the following code: def store_associations_on_object(object, attribute, associations)
values = associations.collect do |assoc|
assoc.internal.blank? ? assoc.value : assoc.internal
end
# Clean up values
values.compact!
case values.length
when 0 then values = nil
... | Stores all association data on the object at the given attribute . Associations with internal data use that instead of value . If only one association is present it is extracted from the array and stored as - is . |
Summarize the following code: def setup_form(group, type, attr_definition)
attr_trans = single_attribute_translator.new(
source: @source,
form: @form,
group: group,
type: type,
attribute_definition: attr_definition
)
attr_trans.add_associations_to_form
end | Sets up translation state instance to hold various attributes that need to be passed around and calls helpers to build the necessary associations and attach them to the form . |
Summarize the following code: def mount(mounted_app, path, options = {})
mounted_app = MountedApplication.new(mounted_app, path, options)
self.class.mounted_applications << mounted_app
mounted_app
end | Mounts an application in the router as a sub application in the url space . This will route directly to the sub application and skip any middlewares etc defined on a stack |
Summarize the following code: def assign_tp_self_caches(tp_ins)
unless tp_self_caches.find { |tp_cache| tp_cache.object_id.equal? tp_ins.self.object_id }
tp_self_caches.push tp_ins.self
end
end | include? will evaluate |
Summarize the following code: def set_log(stream = Pancake.configuration.log_stream,
log_level = Pancake.configuration.log_level,
delimiter = Pancake.configuration.log_delimiter,
auto_flush = Pancake.configuration.log_auto_flush)
@buffer = []
@delimiter ... | To initialize the logger you create a new object proxies to set_log . |
Summarize the following code: def dirs_for(name, opts = {})
if _load_paths[name].blank?
[]
else
result = []
invert = !!opts[:invert]
load_paths = invert ? _load_paths[name].reverse : _load_paths[name]
roots.each do |root|
load_paths.each do |paths, glob|
... | Provides the directories or raw paths that are associated with a given name . |
Summarize the following code: def paths_for(name, opts = {})
result = []
dirs_and_glob_for(name, opts).each do |path, glob|
next if glob.nil?
paths = Dir[File.join(path, glob)]
paths = paths.reverse if opts[:invert]
paths.each do |full_path|
result << [path, full_pa... | Provides an expanded globbed list of paths and files for a given name . |
Summarize the following code: def unique_paths_for(name, opts = {})
tally = {}
output = []
paths_for(name, opts).reverse.each do |ary|
tally[ary[1]] ||= ary[0]
output << ary if tally[ary[1]] == ary[0]
end
output.reverse
end | Provides an expanded globbed list of paths and files for a given name . The result includes only the last matched file of a given sub path and name . |
Summarize the following code: def build_association(value)
association = @form.create_association(
group: @group.to_s,
type: @type.to_s,
value: value
)
# Since the associations are fake, we just set persistence to the parent
# object's value
association.persisted = @source.persist... | Builds a single association with the given data |
Summarize the following code: def block_it?(tp)
if @cond.track_params
return true if negative_check(tp)
if positives_check(tp)
return !tp.binding.eval('local_variables').any? do |v|
tp.binding.local_variable_get(v).object_id == @cond.track_params
end
end
... | to improve performance we didnt assign tp as instance variable |
Summarize the following code: def classify(value)
raise ArgumentError, "value: #{value} must be in data array" unless @data.include?(value)
bounds[1..-1].index { |bound| value <= bound }
end | Returns zero based index of cluster which a value belongs to value must be in data array |
Summarize the following code: def intervals
first, *rest = bounds.each_cons(2).to_a
[first, *rest.map {|lower, upper| [data[data.rindex(lower) + 1] , upper] }]
end | Returns inclusive interval limits |
Summarize the following code: def matrices
rows = data.size
cols = n_classes
# in the original implementation, these matrices are referred to
# as `LC` and `OP`
# * lower_class_limits (LC): optimal lower class limits
# * variance_combinations (OP): optimal variance combinatio... | Compute the matrices required for Jenks breaks . These matrices can be used for any classing of data with classes < = n_classes |
Summarize the following code: def fetch(title, year = "", tomatoes = false, plot = "short")
res = network.call({ t: title, y: year, tomatoes: tomatoes, plot: plot })
if res[:data]["Response"] == "False"
{ status: 404 }
else
{ status: res[:code], movie: parse_movie(res[:data]) }
... | fetchs a movie with a given title set tomatoes to true if you want to get the rotten tomatoes ranking set plot to full if you want to have the full long plot |
Summarize the following code: def find(id, tomatoes = false, plot = "short")
res = network.call({ i: id, tomatoes: tomatoes, plot: plot })
if res[:data]["Response"] == "False"
{ status: 404 }
else
{ status: res[:code], movie: parse_movie(res[:data]) }
end
end | fetches a movie by IMDB id set tomatoes to true if you want to get the rotten tomatoes ranking set plot to full if you want to have the full long plot |
Summarize the following code: def options
VALID_CONFIG_OPTIONS.inject({}) do |option, key|
option.merge!(key => send(key))
end
end | Create a hash of configuration options and their values . |
Summarize the following code: def create_user(options={})
user=User.new(options)
user.validate_for_create!
body = user_hash(user.to_hash)
response=oauth_access_token.post('/v1/users', body: body)
User.new(response.parsed)
end | Create a user from the options |
Summarize the following code: def update_user(options={})
user=User.new(options)
user.validate!
response=oauth_access_token.put("/v1/users/#{user.id}", body: user_hash(user.to_hash))
User.new(response.parsed)
end | Update an existing user |
Summarize the following code: def find_user_by_email(email)
response = oauth_access_token.get('/v1/users', params: { email: email })
user = response.parsed.first
if user
user=User.new(user)
end
user
end | Find a user by email |
Summarize the following code: def sign_out_url(redirect_url=nil)
auth_server_url = Addressable::URI.parse(endpoint)
auth_server_url.path = '/users/sign_out'
auth_server_url.query_values = {redirect_url: redirect_url} if redirect_url
auth_server_url.to_s
end | Return the URL for signing out of the auth server . Clients should redirect to this URL to globally sign out . |
Summarize the following code: def list_users
response=oauth_access_token.get("/v1/users")
response.parsed.collect { |parsed_user| User.new(parsed_user) }
end | Return all users from the remote service |
Summarize the following code: def list_roles
response = oauth_access_token.get('/v1/roles')
response.parsed.collect { |parsed_role| Role.new(parsed_role) }
end | Return all user roles from the remote service |
Summarize the following code: def bookmark(*args)
if args[0].is_a? Array
Drop.create(:bookmarks, args)
else
url, name = args[0], (args[1] || "")
Drop.create(:bookmark, {:name => name, :redirect_url => url})
end
end | Create one or more new bookmark drops . |
Summarize the following code: def rename(id, name = "")
drop = Drop.find(id)
drop.update(:name => name)
end | Change the name of the drop . |
Summarize the following code: def privacy(id, privacy = false)
drop = Drop.find(id)
drop.update(:private => privacy)
end | Modify a drop with a private URL to have a public URL or vice versa . |
Summarize the following code: def load(attributes = {})
attributes.each do |key, val|
if key =~ /^.*_at$/ and val
# if this is a date/time key and it's not nil, try to parse it first
# as DateTime, then as Date only
begin
dt = DateTime.strptime(val, "%Y-%m-%dT%H:%... | Sets the attributes for object . |
Summarize the following code: def load_environment(env=RACK_ENV)
# Load the default which can be overwritten or extended by specific
# env config files.
require File.join(root_path, 'config', 'environments', 'default.rb')
env_file = File.join(root_path, "config", "environments", "#{env}.rb")
... | Loads an environment specific config if available the config file is where the logger should be set if it was not we are using stdout . |
Summarize the following code: def load_apis
Dir.glob(File.join(root_path, "api", "**", "*.rb")).each do |api|
require api
end
end | DSL routes are located in the api folder |
Summarize the following code: def run
status = Status.new(name)
runner = (async ? AsyncRunner : SyncRunner).new do
t = Time.now
begin
@check.call(status)
rescue Exception => e
status.fail("#{name} error: #{e.inspect}")
end
status.time = Time.now - ... | Create a new filter to run a status check . The name is used for display purposes . Run a status the status check . This method keeps track of the time it took to run the check and will trap any unexpected exceptions and report them as failures . |
Summarize the following code: def call(env)
if @app.nil? || env[PATH_INFO] == @route_path
statuses = []
t = Time.now
statuses = Filter.run_filters(@filters)
render(statuses, Time.now - t)
else
@app.call(env)
end
end | Create a new handler . This method can take a block which will yield itself so it can be configured . |
Summarize the following code: def check (name, *options_or_check, &block)
raise ArgumentError("Too many arguments to #{self.class.name}#check") if options_or_check.size > 2
check = nil
options = {:async => true}
unless options_or_check.empty?
if options_or_check[0].is_a?(Hash)
... | Add a status check to the handler . |
Summarize the following code: def lookup_check(name, options) #:nodoc:
check_class_name = "#{name.to_s.gsub(/(^|_)([a-z])/){|m| m.sub('_', '').upcase}}Check"
check = nil
if IsItWorking.const_defined?(check_class_name)
check_class = IsItWorking.const_get(check_class_name)
chec... | Lookup a status check filter from the name and arguments |
Summarize the following code: def render(statuses, elapsed_time) #:nodoc:
fail = statuses.all?{|s| s.success?}
headers = {
"Content-Type" => "text/plain; charset=utf8",
"Cache-Control" => "no-cache",
"Date" => Time.now.httpdate,
}
messages = []
... | Output the plain text response from calling all the filters . |
Summarize the following code: def call(status)
begin
ping(@host, @port)
status.ok("#{@alias} is accepting connections on port #{@port.inspect}")
rescue Errno::ECONNREFUSED
status.fail("#{@alias} is not accepting connections on port #{@port.inspect}")
rescue SocketError => e
... | Check if a host is reachable and accepting connections on a specified port . |
Summarize the following code: def respond_to? method, include_private = false
true if bootstrap_admin_config.respond_to? method
super method, include_private
end | self responds_to bootstrap_admin_config methods via method_missing! |
Summarize the following code: def instantiate_http #:nodoc:
http_class = nil
if @proxy && @proxy[:host]
http_class = Net::HTTP::Proxy(@proxy[:host], @proxy[:port], @proxy[:username], @proxy[:password])
else
http_class = Net::HTTP
end
http = http_class.new(@u... | Create an HTTP object with the options set . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.