_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3
values | text stringlengths 66 10.5k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q700 | RightScale.PlannedVolume.is_valid? | train | def is_valid?
result = false == is_blank?(@volume_id) &&
false == is_blank?(@device_name) &&
false == is_blank?(@volume_status) &&
false == is_blank?(@mount_points) &&
nil == @mount_points.find { |mount_point| is_blank?(mount_point) }
return result... | ruby | {
"resource": ""
} |
q701 | RightScale.Agent.run | train | def run
Log.init(@identity, @options[:log_path], :print => true)
Log.level = @options[:log_level] if @options[:log_level]
RightSupport::Log::Mixin.default_logger = Log
ErrorTracker.init(self, @options[:agent_name], :shard_id => @options[:shard_id], :trace_level => TRACE_LEVEL,
... | ruby | {
"resource": ""
} |
q702 | RightScale.Agent.connect | train | def connect(host, port, index, priority = nil, force = false)
@connect_request_stats.update("connect b#{index}")
even_if = " even if already connected" if force
Log.info("Connecting to broker at host #{host.inspect} port #{port.inspect} " +
"index #{index.inspect} priority #{priority.in... | ruby | {
"resource": ""
} |
q703 | RightScale.Agent.disconnect | train | def disconnect(host, port, remove = false)
and_remove = " and removing" if remove
Log.info("Disconnecting#{and_remove} broker at host #{host.inspect} port #{port.inspect}")
Log.info("Current broker configuration: #{@client.status.inspect}")
id = RightAMQP::HABrokerClient.identity(host, port)
... | ruby | {
"resource": ""
} |
q704 | RightScale.Agent.connect_failed | train | def connect_failed(ids)
aliases = @client.aliases(ids).join(", ")
@connect_request_stats.update("enroll failed #{aliases}")
result = nil
begin
Log.info("Received indication that service initialization for this agent for brokers #{ids.inspect} has failed")
connected = @client.conn... | ruby | {
"resource": ""
} |
q705 | RightScale.Agent.terminate | train | def terminate(reason = nil, exception = nil)
begin
@history.update("stop") if @history
ErrorTracker.log(self, "[stop] Terminating because #{reason}", exception) if reason
if exception.is_a?(Exception)
h = @history.analyze_service
if h[:last_crashed]
delay = ... | ruby | {
"resource": ""
} |
q706 | RightScale.Agent.stats | train | def stats(options = {})
now = Time.now
reset = options[:reset]
stats = {
"name" => @agent_name,
"identity" => @identity,
"hostname" => Socket.gethostname,
"memory" => Platform.process.resident_set_size,
"version" => Agen... | ruby | {
"resource": ""
} |
q707 | RightScale.Agent.agent_stats | train | def agent_stats(reset = false)
stats = {
"request failures" => @request_failure_stats.all,
"response failures" => @response_failure_stats.all
}.merge(ErrorTracker.stats(reset))
if @mode != :http
stats["connect requests"] = @connect_request_stats.all
stats["non-deliveri... | ruby | {
"resource": ""
} |
q708 | RightScale.Agent.reset_agent_stats | train | def reset_agent_stats
@connect_request_stats = RightSupport::Stats::Activity.new(measure_rate = false)
@non_delivery_stats = RightSupport::Stats::Activity.new
@request_failure_stats = RightSupport::Stats::Activity.new
@response_failure_stats = RightSupport::Stats::Activity.new
true
end | ruby | {
"resource": ""
} |
q709 | RightScale.Agent.set_configuration | train | def set_configuration(opts)
@options = DEFAULT_OPTIONS.clone
@options.update(opts)
AgentConfig.root_dir = @options[:root_dir]
AgentConfig.pid_dir = @options[:pid_dir]
@options[:log_path] = false
if @options[:daemonize] || @options[:log_dir]
@options[:log_path] = (@options[:... | ruby | {
"resource": ""
} |
q710 | RightScale.Agent.handle_event | train | def handle_event(event)
if event.is_a?(Hash)
if ["Push", "Request"].include?(event[:type])
# Use next_tick to ensure that on main reactor thread
# so that any data access is thread safe
EM_S.next_tick do
begin
if (result = @dispatcher.dispatch(event_... | ruby | {
"resource": ""
} |
q711 | RightScale.Agent.event_to_packet | train | def event_to_packet(event)
packet = nil
case event[:type]
when "Push"
packet = RightScale::Push.new(event[:path], event[:data], {:from => event[:from], :token => event[:uuid]})
packet.expires_at = event[:expires_at].to_i if event.has_key?(:expires_at)
packet.skewed_by = event[:... | ruby | {
"resource": ""
} |
q712 | RightScale.Agent.result_to_event | train | def result_to_event(result)
{ :type => "Result",
:from => result.from,
:data => {
:result => result.results,
:duration => result.duration,
:request_uuid => result.token,
:request_from => result.request_from } }
end | ruby | {
"resource": ""
} |
q713 | RightScale.Agent.create_dispatchers | train | def create_dispatchers
cache = DispatchedCache.new(@identity) if @options[:dup_check]
@dispatcher = Dispatcher.new(self, cache)
@queues.inject({}) { |dispatchers, queue| dispatchers[queue] = @dispatcher; dispatchers }
end | ruby | {
"resource": ""
} |
q714 | RightScale.Agent.load_actors | train | def load_actors
# Load agent's configured actors
actors = (@options[:actors] || []).clone
Log.info("[setup] Agent #{@identity} with actors #{actors.inspect}")
actors_dirs = AgentConfig.actors_dirs
actors_dirs.each do |dir|
Dir["#{dir}/*.rb"].each do |file|
actor = File.ba... | ruby | {
"resource": ""
} |
q715 | RightScale.Agent.setup_http | train | def setup_http(auth_client)
@auth_client = auth_client
if @mode == :http
RightHttpClient.init(@auth_client, @options.merge(:retry_enabled => true))
@client = RightHttpClient.instance
end
true
end | ruby | {
"resource": ""
} |
q716 | RightScale.Agent.setup_status | train | def setup_status
@status = {}
if @client
if @mode == :http
@status = @client.status { |type, state| update_status(type, state) }.dup
else
@client.connection_status { |state| update_status(:broker, state) }
@status[:broker] = :connected
@status[:auth] =... | ruby | {
"resource": ""
} |
q717 | RightScale.Agent.setup_non_delivery | train | def setup_non_delivery
@client.non_delivery do |reason, type, token, from, to|
begin
@non_delivery_stats.update(type)
reason = case reason
when "NO_ROUTE" then OperationResult::NO_ROUTE_TO_TARGET
when "NO_CONSUMERS" then OperationResult::TARGET_NOT_CONNECTED
... | ruby | {
"resource": ""
} |
q718 | RightScale.Agent.setup_queue | train | def setup_queue(name, ids = nil)
queue = {:name => name, :options => {:durable => true, :no_declare => @options[:secure]}}
filter = [:from, :tags, :tries, :persistent]
options = {:ack => true, Push => filter, Request => filter, Result => [:from], :brokers => ids}
@client.subscribe(queue, nil, op... | ruby | {
"resource": ""
} |
q719 | RightScale.Agent.handle_packet | train | def handle_packet(queue, packet, header)
begin
# Continue to dispatch/ack requests even when terminating otherwise will block results
# Ideally would reject requests when terminating but broker client does not yet support that
case packet
when Push, Request then dispatch_request(pa... | ruby | {
"resource": ""
} |
q720 | RightScale.Agent.dispatch_request | train | def dispatch_request(request, queue)
begin
if (dispatcher = @dispatchers[queue])
if (result = dispatcher.dispatch(request))
exchange = {:type => :queue, :name => request.reply_to, :options => {:durable => true, :no_declare => @options[:secure]}}
@client.publish(exchange, ... | ruby | {
"resource": ""
} |
q721 | RightScale.Agent.deliver_response | train | def deliver_response(result)
begin
@sender.handle_response(result)
rescue StandardError => e
ErrorTracker.log(self, "Failed to deliver response #{result.trace}", e)
@response_failure_stats.update(e.class.name)
end
true
end | ruby | {
"resource": ""
} |
q722 | RightScale.Agent.finish_setup | train | def finish_setup
@client.failed.each do |id|
p = {:agent_identity => @identity}
p[:host], p[:port], p[:id], p[:priority] = @client.identity_parts(id)
@sender.send_push("/registrar/connect", p)
end
true
end | ruby | {
"resource": ""
} |
q723 | RightScale.Agent.publish_stats | train | def publish_stats
s = stats({}).content
if @mode == :http
@client.notify({:type => "Stats", :from => @identity, :data => s}, nil)
else
exchange = {:type => :topic, :name => "stats", :options => {:no_declare => true}}
@client.publish(exchange, Stats.new(s, @identity), :no_log =>... | ruby | {
"resource": ""
} |
q724 | RightScale.Agent.stop_gracefully | train | def stop_gracefully(timeout)
if @mode == :http
@client.close
else
@client.unusable.each { |id| @client.close_one(id, propagate = false) }
end
finish_terminating(timeout)
end | ruby | {
"resource": ""
} |
q725 | RightScale.Agent.finish_terminating | train | def finish_terminating(timeout)
if @sender
request_count, request_age = @sender.terminate
finish = lambda do
request_count, request_age = @sender.terminate
Log.info("[stop] The following #{request_count} requests initiated as recently as #{request_age} " +
"... | ruby | {
"resource": ""
} |
q726 | RightScale.CommandClient.send_command | train | def send_command(options, verbose=false, timeout=20, &handler)
return if @closing
@last_timeout = timeout
manage_em = !EM.reactor_running?
response_handler = lambda do
EM.stop if manage_em
handler.call(@response) if handler && @response
@pending -= 1
@close_handle... | ruby | {
"resource": ""
} |
q727 | RightScale.PidFile.check | train | def check
if pid = read_pid[:pid]
if process_running?(pid)
raise AlreadyRunning.new("#{@pid_file} already exists and process is running (pid: #{pid})")
else
Log.info("Removing stale pid file: #{@pid_file}")
remove
end
end
true
end | ruby | {
"resource": ""
} |
q728 | RightScale.PidFile.write | train | def write
begin
FileUtils.mkdir_p(@pid_dir)
open(@pid_file,'w') { |f| f.write(Process.pid) }
File.chmod(0644, @pid_file)
rescue StandardError => e
ErrorTracker.log(self, "Failed to create PID file", e, nil, :caller)
raise
end
true
end | ruby | {
"resource": ""
} |
q729 | RightScale.PidFile.set_command_options | train | def set_command_options(options)
content = { :listen_port => options[:listen_port], :cookie => options[:cookie] }
# This is requried to preserve cookie value to be saved as string,
# and not as escaped binary data
content[:cookie].force_encoding('utf-8')
open(@cookie_file,'w') { |f| f.writ... | ruby | {
"resource": ""
} |
q730 | RightScale.PidFile.read_pid | train | def read_pid
content = {}
if exists?
open(@pid_file,'r') { |f| content[:pid] = f.read.to_i }
open(@cookie_file,'r') do |f|
command_options = (YAML.load(f.read) rescue {}) || {}
content.merge!(command_options)
end if File.readable?(@cookie_file)
end
con... | ruby | {
"resource": ""
} |
q731 | RightScale.Packet.to_msgpack | train | def to_msgpack(*a)
msg = {
'msgpack_class' => self.class.name,
'data' => instance_variables.inject({}) do |m, ivar|
name = ivar.to_s.sub(/@/, '')
m[name] = instance_variable_get(ivar) unless NOT_SERIALIZED.include?(name)
... | ruby | {
"resource": ""
} |
q732 | RightScale.Packet.to_json | train | def to_json(*a)
# Hack to override RightScale namespace with Nanite for downward compatibility
class_name = self.class.name
if class_name =~ /^RightScale::(.*)/
class_name = "Nanite::" + Regexp.last_match(1)
end
js = {
'json_class' => class_name,
'data' => in... | ruby | {
"resource": ""
} |
q733 | RightScale.Packet.enough_precision | train | def enough_precision(value)
scale = [1.0, 10.0, 100.0, 1000.0, 10000.0, 100000.0]
enough = lambda { |v| (v >= 10.0 ? 0 :
(v >= 1.0 ? 1 :
(v >= 0.1 ? 2 :
(v >= 0.01 ? 3 :
(v > 0.001 ? 4... | ruby | {
"resource": ""
} |
q734 | RightScale.Packet.ids_to_s | train | def ids_to_s(ids)
if ids.is_a?(Array)
s = ids.each { |i| id_to_s(i) }.join(', ')
s.size > 1000 ? "[#{s[0, 1000]}...]" : "[#{s}]"
else
id_to_s(ids)
end
end | ruby | {
"resource": ""
} |
q735 | RightScale.Packet.trace | train | def trace
audit_id = self.respond_to?(:payload) && payload.is_a?(Hash) && (payload['audit_id'] || payload[:audit_id])
tok = self.respond_to?(:token) && token
tr = "<#{audit_id || nil}> <#{tok}>"
end | ruby | {
"resource": ""
} |
q736 | RightScale.RouterClient.push | train | def push(type, payload, target, options = {})
params = {
:type => type,
:payload => payload,
:target => target }
make_request(:post, "/push", params, type.split("/")[2], options)
end | ruby | {
"resource": ""
} |
q737 | RightScale.RouterClient.request | train | def request(type, payload, target, options = {})
params = {
:type => type,
:payload => payload,
:target => target }
make_request(:post, "/request", params, type.split("/")[2], options)
end | ruby | {
"resource": ""
} |
q738 | RightScale.RouterClient.notify | train | def notify(event, routing_keys)
event[:uuid] ||= RightSupport::Data::UUID.generate
event[:version] ||= AgentConfig.protocol_version
params = {:event => event}
params[:routing_keys] = routing_keys if routing_keys
if @websocket
path = event[:path] ? " #{event[:path]}" : ""
to... | ruby | {
"resource": ""
} |
q739 | RightScale.RouterClient.listen | train | def listen(routing_keys, &handler)
raise ArgumentError, "Block missing" unless block_given?
@event_uuids = nil
@listen_interval = 0
@listen_state = :choose
@listen_failures = 0
@connect_interval = CONNECT_INTERVAL
@reconnect_interval = RECONNECT_INTERVAL
listen_loop(rou... | ruby | {
"resource": ""
} |
q740 | RightScale.RouterClient.listen_loop | train | def listen_loop(routing_keys, &handler)
@listen_timer = nil
begin
# Perform listen action based on current state
case @listen_state
when :choose
# Choose listen method or continue as is if already listening
# or want to delay choosing
choose_listen_meth... | ruby | {
"resource": ""
} |
q741 | RightScale.RouterClient.listen_loop_wait | train | def listen_loop_wait(started_at, interval, routing_keys, &handler)
if @listen_interval == 0
EM_S.next_tick { listen_loop(routing_keys, &handler) }
else
@listen_timer = EM_S::Timer.new(interval) do
remaining = @listen_interval - (Time.now - started_at)
if remaining > 0
... | ruby | {
"resource": ""
} |
q742 | RightScale.RouterClient.update_listen_state | train | def update_listen_state(state, interval = 0)
if state == :cancel
@listen_timer.cancel if @listen_timer
@listen_timer = nil
@listen_state = state
elsif [:choose, :check, :connect, :long_poll, :wait].include?(state)
@listen_checks = 0 if state == :check && @listen_state != :che... | ruby | {
"resource": ""
} |
q743 | RightScale.RouterClient.try_connect | train | def try_connect(routing_keys, &handler)
connect(routing_keys, &handler)
update_listen_state(:check, 1)
rescue Exception => e
ErrorTracker.log(self, "Failed creating WebSocket", e, nil, :caller)
backoff_connect_interval
update_listen_state(:long_poll)
end | ruby | {
"resource": ""
} |
q744 | RightScale.RouterClient.connect | train | def connect(routing_keys, &handler)
raise ArgumentError, "Block missing" unless block_given?
@attempted_connect_at = Time.now
@close_code = @close_reason = nil
# Initialize use of proxy if defined
if (v = BalancedHttpClient::PROXY_ENVIRONMENT_VARIABLES.detect { |v| ENV.has_key?(v) })
... | ruby | {
"resource": ""
} |
q745 | RightScale.RouterClient.try_long_poll | train | def try_long_poll(routing_keys, event_uuids, &handler)
begin
long_poll(routing_keys, event_uuids, &handler)
rescue Exception => e
e
end
end | ruby | {
"resource": ""
} |
q746 | RightScale.RouterClient.try_deferred_long_poll | train | def try_deferred_long_poll(routing_keys, event_uuids, &handler)
# Proc for running long-poll in EM defer thread since this is a blocking call
@defer_operation_proc = Proc.new { try_long_poll(routing_keys, event_uuids, &handler) }
# Proc that runs in main EM reactor thread to handle result from above ... | ruby | {
"resource": ""
} |
q747 | RightScale.RouterClient.long_poll | train | def long_poll(routing_keys, ack, &handler)
raise ArgumentError, "Block missing" unless block_given?
params = {
:wait_time => @options[:listen_timeout] - 5,
:timestamp => Time.now.to_f }
params[:routing_keys] = routing_keys if routing_keys
params[:ack] = ack if ack && ack.any?
... | ruby | {
"resource": ""
} |
q748 | RightScale.RouterClient.process_long_poll | train | def process_long_poll(result)
case result
when Exceptions::Unauthorized, Exceptions::ConnectivityFailure, Exceptions::RetryableError, Exceptions::InternalServerError
# Reset connect_interval otherwise long-poll and WebSocket connect attempts will continue to backoff
@connect_interval = CONNE... | ruby | {
"resource": ""
} |
q749 | RightScale.BaseRetryClient.init | train | def init(type, auth_client, options)
raise ArgumentError, "Auth client does not support server type #{type.inspect}" unless auth_client.respond_to?(type.to_s + "_url")
raise ArgumentError, ":api_version option missing" unless options[:api_version]
@type = type
@auth_client = auth_client
@h... | ruby | {
"resource": ""
} |
q750 | RightScale.BaseRetryClient.create_http_client | train | def create_http_client
close_http_client("reconnecting")
url = @auth_client.send(@type.to_s + "_url")
Log.info("Connecting to #{@options[:server_name]} via #{url.inspect}")
options = {:server_name => @options[:server_name]}
options[:api_version] = @options[:api_version] if @options[:api_ve... | ruby | {
"resource": ""
} |
q751 | RightScale.BaseRetryClient.close_http_client | train | def close_http_client(reason)
@http_client.close(reason) if @http_client
true
rescue StandardError => e
ErrorTracker.log(self, "Failed closing connection", e)
false
end | ruby | {
"resource": ""
} |
q752 | RightScale.BaseRetryClient.check_health | train | def check_health
begin
@http_client.check_health
self.state = :connected
rescue BalancedHttpClient::NotResponding => e
ErrorTracker.log(self, "Failed #{@options[:server_name]} health check", e.nested_exception)
self.state = :disconnected
rescue StandardError => e
... | ruby | {
"resource": ""
} |
q753 | RightScale.BaseRetryClient.reconnect | train | def reconnect
unless @reconnecting
@reconnecting = true
if EM.reactor_running?
@stats["reconnects"].update("initiate")
@reconnect_timer = EM_S::PeriodicTimer.new(rand(@options[:reconnect_interval])) do
begin
reconnect_once
rescue Exception... | ruby | {
"resource": ""
} |
q754 | RightScale.BaseRetryClient.make_request | train | def make_request(verb, path, params = {}, type = nil, options = {})
raise Exceptions::Terminating if state == :closed
started_at = Time.now
time_to_live = (options[:time_to_live] && options[:time_to_live] > 0) ? options[:time_to_live] : nil
expires_at = started_at + [time_to_live || @options[:re... | ruby | {
"resource": ""
} |
q755 | RightScale.BaseRetryClient.handle_exception | train | def handle_exception(exception, type, request_uuid, expires_at, attempts)
result = request_uuid
if exception.respond_to?(:http_code)
case exception.http_code
when 301, 302 # MovedPermanently, Found
handle_redirect(exception, type, request_uuid)
when 401 # Unauthorized
... | ruby | {
"resource": ""
} |
q756 | RightScale.BaseRetryClient.handle_redirect | train | def handle_redirect(redirect, type, request_uuid)
Log.info("Received REDIRECT #{redirect} for #{type} request <#{request_uuid}>")
if redirect.respond_to?(:response) && (location = redirect.response.headers[:location]) && !location.empty?
Log.info("Requesting auth client to handle redirect to #{locat... | ruby | {
"resource": ""
} |
q757 | RightScale.BaseRetryClient.handle_retry_with | train | def handle_retry_with(retry_result, type, request_uuid, expires_at, attempts)
case (interval = retry_interval(expires_at, attempts, 1))
when nil
@stats["request failures"].update("#{type} - retry")
raise Exceptions::RetryableError.new(retry_result.http_body, retry_result)
when 0
... | ruby | {
"resource": ""
} |
q758 | RightScale.BaseRetryClient.handle_not_responding | train | def handle_not_responding(not_responding, type, request_uuid, expires_at, attempts)
case (interval = retry_interval(expires_at, attempts))
when nil
@stats["request failures"].update("#{type} - no result")
self.state = :disconnected
raise Exceptions::ConnectivityFailure.new(not_respon... | ruby | {
"resource": ""
} |
q759 | RightScale.BaseRetryClient.retry_interval | train | def retry_interval(expires_at, attempts, max_retries = nil)
if @options[:retry_enabled]
if max_retries.nil? || attempts <= max_retries
interval = @options[:retry_intervals][attempts - 1] || @options[:retry_intervals][-1]
((Time.now + interval) < expires_at) ? interval : 0
else
... | ruby | {
"resource": ""
} |
q760 | RightScale.BaseRetryClient.wait | train | def wait(interval)
if @options[:non_blocking]
fiber = Fiber.current
EM.add_timer(interval) { fiber.resume }
Fiber.yield
else
sleep(interval)
end
true
end | ruby | {
"resource": ""
} |
q761 | RightScale.RetryableRequest.handle_response | train | def handle_response(r)
return true if @done
@raw_response = r
res = result_from(r)
if res.success?
if @cancel_timer
@cancel_timer.cancel
@cancel_timer = nil
end
@done = true
succeed(res.content)
else
reason = res.content
i... | ruby | {
"resource": ""
} |
q762 | RightScale.SecureSerializer.dump | train | def dump(obj, encrypt = nil)
must_encrypt = encrypt || @encrypt
serialize_format = if obj.respond_to?(:send_version) && can_handle_msgpack_result?(obj.send_version)
@serializer.format
else
:json
end
encode_format = serialize_format == :json ? :pem : :der
msg = @serial... | ruby | {
"resource": ""
} |
q763 | RightScale.SecureSerializer.load | train | def load(msg, id = nil)
msg = @serializer.load(msg)
sig = Signature.from_data(msg['signature'])
certs = @store.get_signer(msg['id'])
raise MissingCertificate.new("Could not find a certificate for signer #{msg['id']}") unless certs
certs = [ certs ] unless certs.respond_to?(:any?)
ra... | ruby | {
"resource": ""
} |
q764 | RightScale.RightScriptAttachment.fill_out | train | def fill_out(session)
session['scope'] = "attachments"
if @digest
session['resource'] = @digest
else
session['resource'] = to_hash
session['url'] = @url
session['etag'] = @etag
end
@token = session.to_s
end | ruby | {
"resource": ""
} |
q765 | RightScale.CommandParser.parse_chunk | train | def parse_chunk(chunk)
@buildup << chunk
chunks = @buildup.split(CommandSerializer::SEPARATOR, -1)
if (do_call = chunks.size > 1)
commands = []
(0..chunks.size - 2).each do |i|
begin
commands << CommandSerializer.load(chunks[i])
rescue StandardError => e... | ruby | {
"resource": ""
} |
q766 | RightScale.SpecHelper.issue_cert | train | def issue_cert
test_dn = { 'C' => 'US',
'ST' => 'California',
'L' => 'Santa Barbara',
'O' => 'Agent',
'OU' => 'Certification Services',
'CN' => 'Agent test' }
dn = DistinguishedName.new(test_dn)
key = RsaKeyPa... | ruby | {
"resource": ""
} |
q767 | RightScale.Dispatcher.dispatch | train | def dispatch(request)
token = request.token
actor, method, idempotent = route(request)
received_at = @request_stats.update(method, (token if request.is_a?(Request)))
if (dup = duplicate?(request, method, idempotent))
raise DuplicateRequest, dup
end
unless (result = expired?(r... | ruby | {
"resource": ""
} |
q768 | RightScale.Dispatcher.stats | train | def stats(reset = false)
stats = {
"dispatched cache" => (@dispatched_cache.stats if @dispatched_cache),
"dispatch failures" => @dispatch_failure_stats.all,
"rejects" => @reject_stats.all,
"requests" => @request_stats.all
}
reset_stats if reset
... | ruby | {
"resource": ""
} |
q769 | RightScale.Dispatcher.expired? | train | def expired?(request, method)
if (expires_at = request.expires_at) && expires_at > 0 && (now = Time.now.to_i) >= expires_at
@reject_stats.update("expired (#{method})")
Log.info("REJECT EXPIRED <#{request.token}> from #{request.from} TTL #{RightSupport::Stats.elapsed(now - expires_at)} ago")
... | ruby | {
"resource": ""
} |
q770 | RightScale.Dispatcher.duplicate? | train | def duplicate?(request, method, idempotent)
if !idempotent && @dispatched_cache
if (serviced_by = @dispatched_cache.serviced_by(request.token))
from_retry = ""
else
from_retry = "retry "
request.tries.each { |t| break if (serviced_by = @dispatched_cache.serviced_by(t)... | ruby | {
"resource": ""
} |
q771 | RightScale.Dispatcher.route | train | def route(request)
prefix, method = request.type.split('/')[1..-1]
method ||= :index
method = method.to_sym
actor = @registry.actor_for(prefix)
if actor.nil? || !actor.respond_to?(method)
raise InvalidRequestType, "Unknown actor or method for dispatching request <#{request.token}> ... | ruby | {
"resource": ""
} |
q772 | RightScale.Dispatcher.perform | train | def perform(request, actor, method, idempotent)
@dispatched_cache.store(request.token) if @dispatched_cache && !idempotent
if actor.method(method).arity.abs == 1
actor.send(method, request.payload)
else
actor.send(method, request.payload, request)
end
rescue StandardError => ... | ruby | {
"resource": ""
} |
q773 | RightScale.Certificate.save | train | def save(file)
File.open(file, "w") do |f|
f.write(@raw_cert.to_pem)
end
true
end | ruby | {
"resource": ""
} |
q774 | RightScale.History.load | train | def load
events = []
File.open(@history, "r") { |f| events = f.readlines.map { |l| JSON.legacy_load(l) } } if File.readable?(@history)
events
end | ruby | {
"resource": ""
} |
q775 | RightScale.ApiClient.map_request | train | def map_request(type, payload, options)
verb, path = API_MAP[type]
raise ArgumentError, "Unsupported request type: #{type}" if path.nil?
actor, action = type.split("/")[1..-1]
path, params, request_options = parameterize(actor, action, payload, path)
if action == "query_tags"
map_q... | ruby | {
"resource": ""
} |
q776 | RightScale.ApiClient.map_response | train | def map_response(response, path)
case path
when "/audit_entries"
# Convert returned audit entry href to audit ID
response.sub!(/^.*\/api\/audit_entries\//, "") if response.is_a?(String)
when "/tags/by_resource", "/tags/by_tag"
# Extract tags for each instance resource from resp... | ruby | {
"resource": ""
} |
q777 | RightScale.ApiClient.map_query_tags | train | def map_query_tags(verb, params, action, options)
response = {}
hrefs = params[:resource_hrefs] || []
hrefs.concat(query_by_tag(verb, params[:tags], action, options)) if params[:tags]
response = query_by_resource(verb, hrefs, action, options) if hrefs.any?
response
end | ruby | {
"resource": ""
} |
q778 | RightScale.ApiClient.query_by_tag | train | def query_by_tag(verb, tags, action, options)
path = "/tags/by_tag"
params = {:tags => tags, :match_all => false, :resource_type => "instances"}
map_response(make_request(verb, path, params, action, options), path).keys
end | ruby | {
"resource": ""
} |
q779 | RightScale.ApiClient.query_by_resource | train | def query_by_resource(verb, hrefs, action, options)
path = "/tags/by_resource"
params = {:resource_hrefs => hrefs}
map_response(make_request(verb, path, params, action, options), path)
end | ruby | {
"resource": ""
} |
q780 | RightScale.ApiClient.parameterize | train | def parameterize(actor, action, payload, path)
options = {}
params = {}
if actor == "auditor"
path = path.sub(/:id/, payload[:audit_id].to_s || "")
params = parameterize_audit(action, payload)
options = {:filter_params => AUDIT_FILTER_PARAMS}
elsif actor == "router" && ac... | ruby | {
"resource": ""
} |
q781 | RightScale.ApiClient.parameterize_audit | train | def parameterize_audit(action, payload)
params = {}
summary = non_blank(payload[:summary])
detail = non_blank(payload[:detail])
case action
when "create_entry"
params[:audit_entry] = {:auditee_href => @self_href}
params[:audit_entry][:summary] = truncate(summary, MAX_AUDIT_... | ruby | {
"resource": ""
} |
q782 | RightScale.ApiClient.truncate | train | def truncate(value, max_length)
raise ArgumentError, "max_length must be greater than 3" if max_length <= 3
if value.is_a?(String) && value.bytesize > max_length
max_truncated = max_length - 3
truncated = value[0, max_truncated]
while truncated.bytesize > max_truncated do
t... | ruby | {
"resource": ""
} |
q783 | Kirigami.Image.cut! | train | def cut!
create_backup_copy
MiniMagick::Tool::Mogrify.new do |mogrify|
mogrify.resize(max_size)
mogrify.strip
if jpeg?
mogrify.colorspace(Kirigami.config.jpeg_colorspace)
mogrify.sampling_factor(Kirigami.config.jpeg_sampling_factor)
mogrify.interlace(Kir... | ruby | {
"resource": ""
} |
q784 | Dataflow.SchemaMixin.infer_schema | train | def infer_schema(samples_count: 0, extended: false)
if db_backend == :postgresql
# Experimental
sch = db_adapter.client.schema(read_dataset_name).to_h
sch = sch.reject{ |k, v| k == :_id }.map { |k,v| [k, {type: v[:type].to_s}] }.to_h
self.inferred_schema = sch
save
... | ruby | {
"resource": ""
} |
q785 | Mumukit.Assistant.assist_with | train | def assist_with(submission)
@rules
.select { |it| it.matches?(submission) }
.map { |it| it.message_for(submission.attemps_count) }
end | ruby | {
"resource": ""
} |
q786 | DeepMerge.RailsCompat.ko_deeper_merge! | train | def ko_deeper_merge!(source, options = {})
default_opts = {:knockout_prefix => "--", :preserve_unmergeables => false}
DeepMerge::deep_merge!(source, self, default_opts.merge(options))
end | ruby | {
"resource": ""
} |
q787 | ActiveRecord.DeprecatedFinders.with_exclusive_scope | train | def with_exclusive_scope(method_scoping = {}, &block)
if method_scoping.values.any? { |e| e.is_a?(ActiveRecord::Relation) }
raise ArgumentError, <<-MSG
New finder API can not be used with_exclusive_scope. You can either call unscoped to get an anonymous scope not bound to the default_scope:
User.unscoped... | ruby | {
"resource": ""
} |
q788 | Gnuplot.Plot.set | train | def set ( var, value = "" )
value = "\"#{value}\"" if QUOTED.include? var unless value =~ /^'.*'$/
@settings << [ :set, var, value ]
end | ruby | {
"resource": ""
} |
q789 | JOSE.JWT.merge | train | def merge(object)
object = case object
when JOSE::Map, Hash
object
when String
JOSE.decode(object)
when JOSE::JWT
object.to_map
else
raise ArgumentError, "'object' must be a Hash, String, or JOSE::JWT"
end
return JOSE::JWT.from_map(self.to_map.me... | ruby | {
"resource": ""
} |
q790 | JOSE.JWK.block_encrypt | train | def block_encrypt(plain_text, jwe = nil)
jwe ||= block_encryptor
return JOSE::JWE.block_encrypt(self, plain_text, jwe)
end | ruby | {
"resource": ""
} |
q791 | JOSE.JWK.box_decrypt | train | def box_decrypt(encrypted, public_jwk = nil)
if public_jwk
return JOSE::JWE.block_decrypt([public_jwk, self], encrypted)
else
return JOSE::JWE.block_decrypt(self, encrypted)
end
end | ruby | {
"resource": ""
} |
q792 | JOSE.JWK.box_encrypt | train | def box_encrypt(plain_text, jwk_secret = nil, jwe = nil)
epk_secret = nil
jwk_public = self
if jwk_secret.nil?
epk_secret = jwk_secret = jwk_public.generate_key
end
if not jwk_secret.is_a?(JOSE::JWK)
jwk_secret = JOSE::JWK.from(jwk_secret)
end
if jwe.nil?
... | ruby | {
"resource": ""
} |
q793 | JOSE.JWK.shared_secret | train | def shared_secret(other_jwk)
other_jwk = from(other_jwk) if not other_jwk.is_a?(JOSE::JWK)
raise ArgumentError, "key types must match" if other_jwk.kty.class != kty.class
raise ArgumentError, "key type does not support shared secret computations" if not kty.respond_to?(:derive_key)
return kty.de... | ruby | {
"resource": ""
} |
q794 | JOSE.JWK.sign | train | def sign(plain_text, jws = nil, header = nil)
jws ||= signer
return JOSE::JWS.sign(self, plain_text, jws, header)
end | ruby | {
"resource": ""
} |
q795 | JOSE.JWS.sign | train | def sign(jwk, plain_text, header = nil)
protected_binary = JOSE.urlsafe_encode64(to_binary)
payload = JOSE.urlsafe_encode64(plain_text)
signing_input = signing_input(plain_text, protected_binary)
signature = JOSE.urlsafe_encode64(alg.sign(jwk, signing_input))
return signature_to_map(payloa... | ruby | {
"resource": ""
} |
q796 | JOSE.JWS.verify | train | def verify(jwk, plain_text, signature, protected_binary = nil)
protected_binary ||= JOSE.urlsafe_encode64(to_binary)
signing_input = signing_input(plain_text, protected_binary)
return alg.verify(jwk, signing_input, signature), plain_text, self
end | ruby | {
"resource": ""
} |
q797 | JOSE.JWA.supports | train | def supports
jwe_enc = __jwe_enc_support_check__([
'A128GCM',
'A192GCM',
'A256GCM',
'A128CBC-HS256',
'A192CBC-HS384',
'A256CBC-HS512'
])
jwe_alg = __jwe_alg_support_check__([
['A128GCMKW', :block],
['A192GCMKW', :block],
['A256GCM... | ruby | {
"resource": ""
} |
q798 | JOSE.JWE.block_decrypt | train | def block_decrypt(key, aad, cipher_text, cipher_tag, encrypted_key, iv)
cek = key_decrypt(key, encrypted_key)
return uncompress(enc.block_decrypt([aad, cipher_text, cipher_tag], cek, iv))
end | ruby | {
"resource": ""
} |
q799 | JOSE.JWE.block_encrypt | train | def block_encrypt(key, block, cek = nil, iv = nil)
jwe = self
if cek.nil?
cek, jwe = next_cek(key)
end
iv ||= jwe.next_iv
aad, plain_text = block
if plain_text.nil?
plain_text = aad
aad = nil
end
encrypted_key, jwe = jwe.key_encrypt(key, cek)
... | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.