_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q14900 | Gruf.Error.attach_to_call | train | def attach_to_call(active_call)
metadata[Gruf.error_metadata_key.to_sym] = serialize if Gruf.append_server_errors_to_trailing_metadata
return self if metadata.empty? || !active_call || !active_call.respond_to?(:output_metadata)
# Check if we've overflown the maximum size of output metadata. If so,
# log a warning and replace the metadata with something smaller to avoid
# resource exhausted errors.
if metadata.inspect.size > MAX_METADATA_SIZE
code = METADATA_SIZE_EXCEEDED_CODE
msg = METADATA_SIZE_EXCEEDED_MSG
logger.warn "#{code}: #{msg} Original error: #{to_h.inspect}"
err = Gruf::Error.new(code: :internal, app_code: code, message: msg)
return err.attach_to_call(active_call)
end
active_call.output_metadata.update(metadata)
self
end | ruby | {
"resource": ""
} |
q14901 | Gruf.Error.to_h | train | def to_h
{
code: code,
app_code: app_code,
message: message,
field_errors: field_errors.map(&:to_h),
debug_info: debug_info.to_h
}
end | ruby | {
"resource": ""
} |
q14902 | Gruf.Error.serializer_class | train | def serializer_class
if Gruf.error_serializer
Gruf.error_serializer.is_a?(Class) ? Gruf.error_serializer : Gruf.error_serializer.to_s.constantize
else
Gruf::Serializers::Errors::Json
end
end | ruby | {
"resource": ""
} |
q14903 | Gruf.Server.server | train | def server
@server_mu.synchronize do
@server ||= begin
# For backward compatibility, we allow these options to be passed directly
# in the Gruf::Server options, or via Gruf.rpc_server_options.
server_options = {
pool_size: options.fetch(:pool_size, Gruf.rpc_server_options[:pool_size]),
max_waiting_requests: options.fetch(:max_waiting_requests, Gruf.rpc_server_options[:max_waiting_requests]),
poll_period: options.fetch(:poll_period, Gruf.rpc_server_options[:poll_period]),
pool_keep_alive: options.fetch(:pool_keep_alive, Gruf.rpc_server_options[:pool_keep_alive]),
connect_md_proc: options.fetch(:connect_md_proc, Gruf.rpc_server_options[:connect_md_proc]),
server_args: options.fetch(:server_args, Gruf.rpc_server_options[:server_args])
}
server = if @event_listener_proc
server_options[:event_listener_proc] = @event_listener_proc
Gruf::InstrumentableGrpcServer.new(server_options)
else
GRPC::RpcServer.new(server_options)
end
@port = server.add_http2_port(@hostname, ssl_credentials)
@services.each { |s| server.handle(s) }
server
end
end
end | ruby | {
"resource": ""
} |
q14904 | Gruf.Server.start! | train | def start!
update_proc_title(:starting)
server_thread = Thread.new do
logger.info { "Starting gruf server at #{@hostname}..." }
server.run
end
stop_server_thread = Thread.new do
loop do
break if @stop_server
@stop_server_mu.synchronize { @stop_server_cv.wait(@stop_server_mu, 10) }
end
logger.info { 'Shutting down...' }
server.stop
end
server.wait_till_running
@started = true
update_proc_title(:serving)
stop_server_thread.join
server_thread.join
@started = false
update_proc_title(:stopped)
logger.info { 'Goodbye!' }
end | ruby | {
"resource": ""
} |
q14905 | Gruf.Server.insert_interceptor_before | train | def insert_interceptor_before(before_class, interceptor_class, opts = {})
raise ServerAlreadyStartedError if @started
@interceptors.insert_before(before_class, interceptor_class, opts)
end | ruby | {
"resource": ""
} |
q14906 | Gruf.Server.insert_interceptor_after | train | def insert_interceptor_after(after_class, interceptor_class, opts = {})
raise ServerAlreadyStartedError if @started
@interceptors.insert_after(after_class, interceptor_class, opts)
end | ruby | {
"resource": ""
} |
q14907 | Gruf.Configuration.options | train | def options
opts = {}
VALID_CONFIG_KEYS.each_key do |k|
opts.merge!(k => send(k))
end
opts
end | ruby | {
"resource": ""
} |
q14908 | Gruf.Configuration.reset | train | def reset
VALID_CONFIG_KEYS.each do |k, v|
send((k.to_s + '='), v)
end
self.interceptors = Gruf::Interceptors::Registry.new
self.root_path = Rails.root.to_s.chomp('/') if defined?(Rails)
if defined?(Rails) && Rails.logger
self.logger = Rails.logger
else
require 'logger'
self.logger = ::Logger.new(STDOUT)
end
self.grpc_logger = logger if grpc_logger.nil?
self.ssl_crt_file = "#{root_path}config/ssl/#{environment}.crt"
self.ssl_key_file = "#{root_path}config/ssl/#{environment}.key"
self.controllers_path = root_path.to_s.empty? ? 'app/rpc' : "#{root_path}/app/rpc"
if use_default_interceptors
interceptors.use(Gruf::Interceptors::ActiveRecord::ConnectionReset)
interceptors.use(Gruf::Interceptors::Instrumentation::OutputMetadataTimer)
end
options
end | ruby | {
"resource": ""
} |
q14909 | SimpleTokenAuthentication.ExceptionFallbackHandler.fallback! | train | def fallback!(controller, entity)
throw(:warden, scope: entity.name_underscore.to_sym) if controller.send("current_#{entity.name_underscore}").nil?
end | ruby | {
"resource": ""
} |
q14910 | Train::Transports.SSH.verify_host_key_option | train | def verify_host_key_option
current_net_ssh = Net::SSH::Version::CURRENT
new_option_version = Net::SSH::Version[4, 2, 0]
current_net_ssh >= new_option_version ? :verify_host_key : :paranoid
end | ruby | {
"resource": ""
} |
q14911 | Train::Transports.SSH.create_new_connection | train | def create_new_connection(options, &block)
if defined?(@connection)
logger.debug("[SSH] shutting previous connection #{@connection}")
@connection.close
end
@connection_options = options
conn = Connection.new(options, &block)
# Cisco IOS requires a special implementation of `Net:SSH`. This uses the
# SSH transport to identify the platform, but then replaces SSHConnection
# with a CiscoIOSConnection in order to behave as expected for the user.
if defined?(conn.platform.cisco_ios?) && conn.platform.cisco_ios?
ios_options = {}
ios_options[:host] = @options[:host]
ios_options[:user] = @options[:user]
# The enable password is used to elevate privileges on Cisco devices
# We will also support the sudo password field for the same purpose
# for the interim. # TODO
ios_options[:enable_password] = @options[:enable_password] || @options[:sudo_password]
ios_options[:logger] = @options[:logger]
ios_options.merge!(@connection_options)
conn = CiscoIOSConnection.new(ios_options)
end
@connection = conn unless conn.nil?
end | ruby | {
"resource": ""
} |
q14912 | Train.File.perform_checksum_ruby | train | def perform_checksum_ruby(method)
# This is used to skip attempting other checksum methods. If this is set
# then we know all other methods have failed.
@ruby_checksum_fallback = true
case method
when :md5
res = Digest::MD5.new
when :sha256
res = Digest::SHA256.new
end
res.update(content)
res.hexdigest
rescue TypeError => _
nil
end | ruby | {
"resource": ""
} |
q14913 | Train::Transports.WinRM.create_new_connection | train | def create_new_connection(options, &block)
if @connection
logger.debug("[WinRM] shutting previous connection #{@connection}")
@connection.close
end
@connection_options = options
@connection = Connection.new(options, &block)
end | ruby | {
"resource": ""
} |
q14914 | Train::Platforms.Common.in_family | train | def in_family(family)
if self.class == Train::Platforms::Family && @name == family
fail "Unable to add family #{@name} to itself: '#{@name}.in_family(#{family})'"
end
# add family to the family list
family = Train::Platforms.family(family)
family.children[self] = @condition
@families[family] = @condition
@condition = nil
self
end | ruby | {
"resource": ""
} |
q14915 | Train::Extras.LinuxCommand.sudo_wrap | train | def sudo_wrap(cmd)
return cmd unless @sudo
return cmd if @user == 'root'
res = (@sudo_command || 'sudo') + ' '
res = "#{safe_string(@sudo_password + "\n")} | #{res}-S " unless @sudo_password.nil?
res << @sudo_options.to_s + ' ' unless @sudo_options.nil?
res + cmd
end | ruby | {
"resource": ""
} |
q14916 | Train::Extras.WindowsCommand.powershell_wrap | train | def powershell_wrap(cmd)
shell = @shell_command || 'powershell'
# Prevent progress stream from leaking into stderr
script = "$ProgressPreference='SilentlyContinue';" + cmd
# Encode script so PowerShell can use it
script = script.encode('UTF-16LE', 'UTF-8')
base64_script = Base64.strict_encode64(script)
cmd = "#{shell} -NoProfile -EncodedCommand #{base64_script}"
cmd
end | ruby | {
"resource": ""
} |
q14917 | Train::Platforms::Detect.Scanner.scan | train | def scan
# start with the platform/families who have no families (the top levels)
top = Train::Platforms.top_platforms
top.each do |_name, plat|
# we are doing a instance_eval here to make sure we have the proper
# context with all the detect helper methods
next unless instance_eval(&plat.detect) == true
# if we have a match start looking at the children
plat_result = scan_children(plat)
next if plat_result.nil?
# return platform to backend
@family_hierarchy << plat.name
return get_platform(plat_result)
end
fail Train::PlatformDetectionFailed, 'Sorry, we are unable to detect your platform'
end | ruby | {
"resource": ""
} |
q14918 | Train::Platforms.Platform.add_platform_methods | train | def add_platform_methods
# Redo clean name if there is a detect override
clean_name(force: true) unless @platform[:name].nil?
# Add in family methods
family_list = Train::Platforms.families
family_list.each_value do |k|
next if respond_to?(k.name + '?')
define_singleton_method(k.name + '?') do
family_hierarchy.include?(k.name)
end
end
# Helper methods for direct platform info
@platform.each_key do |m|
next if respond_to?(m)
define_singleton_method(m) do
@platform[m]
end
end
# Create method for name if its not already true
m = name + '?'
return if respond_to?(m)
define_singleton_method(m) do
true
end
end | ruby | {
"resource": ""
} |
q14919 | Train::Platforms::Detect::Helpers.Windows.read_wmic | train | def read_wmic
res = @backend.run_command('wmic os get * /format:list')
if res.exit_status == 0
sys_info = {}
res.stdout.lines.each { |line|
m = /^\s*([^=]*?)\s*=\s*(.*?)\s*$/.match(line)
sys_info[m[1].to_sym] = m[2] unless m.nil? || m[1].nil?
}
@platform[:release] = sys_info[:Version]
# additional info on windows
@platform[:build] = sys_info[:BuildNumber]
@platform[:name] = sys_info[:Caption]
@platform[:name] = @platform[:name].gsub('Microsoft', '').strip unless @platform[:name].empty?
@platform[:arch] = read_wmic_cpu
end
end | ruby | {
"resource": ""
} |
q14920 | Train::Platforms::Detect::Helpers.Windows.read_wmic_cpu | train | def read_wmic_cpu
res = @backend.run_command('wmic cpu get architecture /format:list')
if res.exit_status == 0
sys_info = {}
res.stdout.lines.each { |line|
m = /^\s*([^=]*?)\s*=\s*(.*?)\s*$/.match(line)
sys_info[m[1].to_sym] = m[2] unless m.nil? || m[1].nil?
}
end
# This converts `wmic os get architecture` output to a normal standard
# https://msdn.microsoft.com/en-us/library/aa394373(VS.85).aspx
arch_map = {
0 => 'i386',
1 => 'mips',
2 => 'alpha',
3 => 'powerpc',
5 => 'arm',
6 => 'ia64',
9 => 'x86_64',
}
# The value of `wmic cpu get architecture` is always a number between 0-9
arch_number = sys_info[:Architecture].to_i
arch_map[arch_number]
end | ruby | {
"resource": ""
} |
q14921 | Train::Platforms::Detect::Helpers.Windows.windows_uuid | train | def windows_uuid
uuid = windows_uuid_from_chef
uuid = windows_uuid_from_machine_file if uuid.nil?
uuid = windows_uuid_from_wmic if uuid.nil?
uuid = windows_uuid_from_registry if uuid.nil?
raise Train::TransportError, 'Cannot find a UUID for your node.' if uuid.nil?
uuid
end | ruby | {
"resource": ""
} |
q14922 | TrainPlugins::LocalRot13.Platform.platform | train | def platform
# If you are declaring a new platform, you will need to tell
# Train a bit about it.
# If you were defining a cloud API, you should say you are a member
# of the cloud family.
# This plugin makes up a new platform. Train (or rather InSpec) only
# know how to read files on Windows and Un*x (MacOS is a kind of Un*x),
# so we'll say we're part of those families.
Train::Platforms.name('local-rot13').in_family('unix')
Train::Platforms.name('local-rot13').in_family('windows')
# When you know you will only ever run on your dedicated platform
# (for example, a plugin named train-aws would only run on the AWS
# API, which we report as the 'aws' platform).
# force_platform! lets you bypass platform detection.
# The options to this are not currently documented completely.
# Use release to report a version number. You might use the version
# of the plugin, or a version of an important underlying SDK, or a
# version of a remote API.
force_platform!('local-rot13', release: TrainPlugins::LocalRot13::VERSION)
end | ruby | {
"resource": ""
} |
q14923 | Train::Platforms::Detect::Helpers.OSCommon.uuid_from_command | train | def uuid_from_command
return unless @platform[:uuid_command]
result = @backend.run_command(@platform[:uuid_command])
uuid_from_string(result.stdout.chomp) if result.exit_status.zero? && !result.stdout.empty?
end | ruby | {
"resource": ""
} |
q14924 | Train::Platforms::Detect::Helpers.OSCommon.uuid_from_string | train | def uuid_from_string(string)
hash = Digest::SHA1.new
hash.update(string)
ary = hash.digest.unpack('NnnnnN')
ary[2] = (ary[2] & 0x0FFF) | (5 << 12)
ary[3] = (ary[3] & 0x3FFF) | 0x8000
# rubocop:disable Style/FormatString
'%08x-%04x-%04x-%04x-%04x%08x' % ary
end | ruby | {
"resource": ""
} |
q14925 | RSpotify.Category.playlists | train | def playlists(limit: 20, offset: 0, **options)
url = "browse/categories/#{@id}/playlists"\
"?limit=#{limit}&offset=#{offset}"
options.each do |option, value|
url << "&#{option}=#{value}"
end
response = RSpotify.get(url)
return response if RSpotify.raw_response
response['playlists']['items'].map { |i| Playlist.new i }
end | ruby | {
"resource": ""
} |
q14926 | RSpotify.Player.play | train | def play(device_id = nil, params = {})
url = "me/player/play"
url = device_id.nil? ? url : "#{url}?device_id=#{device_id}"
User.oauth_put(@user.id, url, params.to_json)
end | ruby | {
"resource": ""
} |
q14927 | RSpotify.Player.repeat | train | def repeat(device_id: nil, state: "context")
url = "me/player/repeat"
url += "?state=#{state}"
url += "&device_id=#{device_id}" if device_id
User.oauth_put(@user.id, url, {})
end | ruby | {
"resource": ""
} |
q14928 | RSpotify.Player.shuffle | train | def shuffle(device_id: nil, state: true)
url = "me/player/shuffle"
url += "?state=#{state}"
url += "&device_id=#{device_id}" if device_id
User.oauth_put(@user.id, url, {})
end | ruby | {
"resource": ""
} |
q14929 | RSpotify.Album.tracks | train | def tracks(limit: 50, offset: 0, market: nil)
last_track = offset + limit - 1
if @tracks_cache && last_track < 50 && !RSpotify.raw_response
return @tracks_cache[offset..last_track]
end
url = "albums/#{@id}/tracks?limit=#{limit}&offset=#{offset}"
url << "&market=#{market}" if market
response = RSpotify.get(url)
json = RSpotify.raw_response ? JSON.parse(response) : response
tracks = json['items'].map { |i| Track.new i }
@tracks_cache = tracks if limit == 50 && offset == 0
return response if RSpotify.raw_response
tracks
end | ruby | {
"resource": ""
} |
q14930 | RSpotify.Artist.albums | train | def albums(limit: 20, offset: 0, **filters)
url = "artists/#{@id}/albums?limit=#{limit}&offset=#{offset}"
filters.each do |filter_name, filter_value|
url << "&#{filter_name}=#{filter_value}"
end
response = RSpotify.get(url)
return response if RSpotify.raw_response
response['items'].map { |i| Album.new i }
end | ruby | {
"resource": ""
} |
q14931 | RSpotify.Artist.top_tracks | train | def top_tracks(country)
return @top_tracks[country] unless @top_tracks[country].nil? || RSpotify.raw_response
response = RSpotify.get("artists/#{@id}/top-tracks?country=#{country}")
return response if RSpotify.raw_response
@top_tracks[country] = response['tracks'].map { |t| Track.new t }
end | ruby | {
"resource": ""
} |
q14932 | RSpotify.Playlist.tracks | train | def tracks(limit: 100, offset: 0, market: nil)
last_track = offset + limit - 1
if @tracks_cache && last_track < 100 && !RSpotify.raw_response
return @tracks_cache[offset..last_track]
end
url = "#{@href}/tracks?limit=#{limit}&offset=#{offset}"
url << "&market=#{market}" if market
response = RSpotify.resolve_auth_request(@owner.id, url)
json = RSpotify.raw_response ? JSON.parse(response) : response
tracks = json['items'].select { |i| i['track'] }
@tracks_added_at = hash_for(tracks, 'added_at') do |added_at|
Time.parse added_at
end
@tracks_added_by = hash_for(tracks, 'added_by') do |added_by|
User.new added_by
end
@tracks_is_local = hash_for(tracks, 'is_local') do |is_local|
is_local
end
tracks.map! { |t| Track.new t['track'] }
@tracks_cache = tracks if limit == 100 && offset == 0
return response if RSpotify.raw_response
tracks
end | ruby | {
"resource": ""
} |
q14933 | RSpotify.User.playlists | train | def playlists(limit: 20, offset: 0)
url = "users/#{@id}/playlists?limit=#{limit}&offset=#{offset}"
response = RSpotify.resolve_auth_request(@id, url)
return response if RSpotify.raw_response
response['items'].map { |i| Playlist.new i }
end | ruby | {
"resource": ""
} |
q14934 | RSpotify.User.to_hash | train | def to_hash
pairs = instance_variables.map do |var|
[var.to_s.delete('@'), instance_variable_get(var)]
end
Hash[pairs]
end | ruby | {
"resource": ""
} |
q14935 | RSpotify.User.devices | train | def devices
url = "me/player/devices"
response = RSpotify.resolve_auth_request(@id, url)
return response if RSpotify.raw_response
response['devices'].map { |i| Device.new i }
end | ruby | {
"resource": ""
} |
q14936 | Xcov.IgnoreHandler.relative_path | train | def relative_path path
require 'pathname'
full_path = Pathname.new(path).realpath # /full/path/to/project/where/is/file.extension
base_path = Pathname.new(source_directory).realpath # /full/path/to/project/
full_path.relative_path_from(base_path).to_s # where/is/file.extension
end | ruby | {
"resource": ""
} |
q14937 | FastlaneCore.Project.targets | train | def targets
project_path = get_project_path
return [] if project_path.nil?
proj = Xcodeproj::Project.open(project_path)
proj.targets.map do |target|
target.name
end
end | ruby | {
"resource": ""
} |
q14938 | Octopress.Page.content | train | def content
# Handle case where user passes the full path
#
file = @options['template'] || default_template
if file
file.sub!(/^_templates\//, '')
file = File.join(site.source, '_templates', file) if file
if File.exist? file
parse_template File.open(file).read.encode('UTF-8')
elsif @options['template']
abort "No #{@options['type']} template found at #{file}"
else
parse_template default_front_matter
end
else
parse_template default_front_matter
end
end | ruby | {
"resource": ""
} |
q14939 | Octopress.Page.parse_template | train | def parse_template(input)
if @config['titlecase']
@options['title'].titlecase!
end
vars = @options.dup
# Allow templates to use slug
#
vars['slug'] = title_slug
# Allow templates to use date fragments
#
date = Time.parse(vars['date'] || Time.now.iso8601)
vars['date'] = date.iso8601
vars['year'] = date.year
vars['month'] = date.strftime('%m')
vars['day'] = date.strftime('%d')
vars['ymd'] = date.strftime('%Y-%m-%d')
# If possible only parse the YAML front matter.
# If YAML front-matter dashes aren't present parse the whole
# template and add dashes.
#
parsed = if input =~ /\A-{3}\s+(.+?)\s+-{3}(.+)?/m
input = $1
content = $2
input << default_front_matter(input)
else
content = ''
end
template = Liquid::Template.parse(input)
"---\n#{template.render(vars).strip}\n---\n#{content}"
end | ruby | {
"resource": ""
} |
q14940 | Octopress.Page.title_slug | train | def title_slug
value = (@options['slug'] || @options['title']).downcase
value.gsub!(/[^\x00-\x7F]/u, '')
value.gsub!(/(&|&)+/, 'and')
value.gsub!(/[']+/, '')
value.gsub!(/\W+/, ' ')
value.strip!
value.gsub!(' ', '-')
value
end | ruby | {
"resource": ""
} |
q14941 | PoisePython.Utils.module_to_path | train | def module_to_path(mod, base=nil)
path = mod.gsub(/\./, ::File::SEPARATOR) + '.py'
path = ::File.join(base, path) if base
path
end | ruby | {
"resource": ""
} |
q14942 | NIO.Selector.deregister | train | def deregister(io)
@lock.synchronize do
monitor = @selectables.delete IO.try_convert(io)
monitor.close(false) if monitor && !monitor.closed?
monitor
end
end | ruby | {
"resource": ""
} |
q14943 | NIO.Selector.select | train | def select(timeout = nil)
selected_monitors = Set.new
@lock.synchronize do
readers = [@wakeup]
writers = []
@selectables.each do |io, monitor|
readers << io if monitor.interests == :r || monitor.interests == :rw
writers << io if monitor.interests == :w || monitor.interests == :rw
monitor.readiness = nil
end
ready_readers, ready_writers = Kernel.select(readers, writers, [], timeout)
return unless ready_readers # timeout
ready_readers.each do |io|
if io == @wakeup
# Clear all wakeup signals we've received by reading them
# Wakeups should have level triggered behavior
@wakeup.read(@wakeup.stat.size)
else
monitor = @selectables[io]
monitor.readiness = :r
selected_monitors << monitor
end
end
ready_writers.each do |io|
monitor = @selectables[io]
monitor.readiness = monitor.readiness == :r ? :rw : :w
selected_monitors << monitor
end
end
if block_given?
selected_monitors.each { |m| yield m }
selected_monitors.size
else
selected_monitors.to_a
end
end | ruby | {
"resource": ""
} |
q14944 | NIO.ByteBuffer.position= | train | def position=(new_position)
raise ArgumentError, "negative position given" if new_position < 0
raise ArgumentError, "specified position exceeds capacity" if new_position > @capacity
@mark = nil if @mark && @mark > new_position
@position = new_position
end | ruby | {
"resource": ""
} |
q14945 | NIO.ByteBuffer.limit= | train | def limit=(new_limit)
raise ArgumentError, "negative limit given" if new_limit < 0
raise ArgumentError, "specified limit exceeds capacity" if new_limit > @capacity
@position = new_limit if @position > new_limit
@mark = nil if @mark && @mark > new_limit
@limit = new_limit
end | ruby | {
"resource": ""
} |
q14946 | NIO.ByteBuffer.get | train | def get(length = remaining)
raise ArgumentError, "negative length given" if length < 0
raise UnderflowError, "not enough data in buffer" if length > @limit - @position
result = @buffer[@position...length]
@position += length
result
end | ruby | {
"resource": ""
} |
q14947 | NIO.ByteBuffer.put | train | def put(str)
raise TypeError, "expected String, got #{str.class}" unless str.respond_to?(:to_str)
str = str.to_str
raise OverflowError, "buffer is full" if str.length > @limit - @position
@buffer[@position...str.length] = str
@position += str.length
self
end | ruby | {
"resource": ""
} |
q14948 | NIO.ByteBuffer.read_from | train | def read_from(io)
nbytes = @limit - @position
raise OverflowError, "buffer is full" if nbytes.zero?
bytes_read = IO.try_convert(io).read_nonblock(nbytes, exception: false)
return 0 if bytes_read == :wait_readable
self << bytes_read
bytes_read.length
end | ruby | {
"resource": ""
} |
q14949 | Money::RatesStore.StoreWithHistoricalDataSupport.transaction | train | def transaction(force_sync = false, &block)
# Ruby 1.9.3 does not support @mutex.owned?
if @mutex.respond_to?(:owned?)
force_sync = false if @mutex.locked? && @mutex.owned?
else
# If we allowed this in Ruby 1.9.3, it might possibly cause recursive
# locking within the same thread.
force_sync = false
end
if !force_sync && (@in_transaction || options[:without_mutex])
block.call self
else
@mutex.synchronize do
@in_transaction = true
result = block.call
@in_transaction = false
result
end
end
end | ruby | {
"resource": ""
} |
q14950 | HTTPI.Request.query= | train | def query=(query)
raise ArgumentError, "Invalid URL: #{self.url}" unless self.url.respond_to?(:query)
if query.kind_of?(Hash)
query = build_query_from_hash(query)
end
query = query.to_s unless query.is_a?(String)
self.url.query = query
end | ruby | {
"resource": ""
} |
q14951 | HTTPI.Request.mass_assign | train | def mass_assign(args)
ATTRIBUTES.each { |key| send("#{key}=", args[key]) if args[key] }
end | ruby | {
"resource": ""
} |
q14952 | HTTPI.Request.normalize_url! | train | def normalize_url!(url)
raise ArgumentError, "Invalid URL: #{url}" unless url.to_s =~ /^http|socks/
url.kind_of?(URI) ? url : URI(url)
end | ruby | {
"resource": ""
} |
q14953 | HTTPI.Dime.configure_record | train | def configure_record(record, bytes)
byte = bytes.shift
record.version = (byte >> 3) & 31 # 5 bits DIME format version (always 1)
record.first = (byte >> 2) & 1 # 1 bit Set if this is the first part in the message
record.last = (byte >> 1) & 1 # 1 bit Set if this is the last part in the message
record.chunked = byte & 1 # 1 bit This file is broken into chunked parts
record.type_format = (bytes.shift >> 4) & 15 # 4 bits Type of file in the part (1 for binary data, 2 for XML)
# 4 bits Reserved (skipped in the above command)
end | ruby | {
"resource": ""
} |
q14954 | HTTPI.Dime.big_endian_lengths | train | def big_endian_lengths(bytes)
lengths = [] # we can't use a hash since the order will be screwed in Ruby 1.8
lengths << [:options, (bytes.shift << 8) | bytes.shift] # 2 bytes Length of the "options" field
lengths << [:id, (bytes.shift << 8) | bytes.shift] # 2 bytes Length of the "ID" or "name" field
lengths << [:type, (bytes.shift << 8) | bytes.shift] # 2 bytes Length of the "type" field
lengths << [:data, (bytes.shift << 24) | (bytes.shift << 16) | (bytes.shift << 8) | bytes.shift] # 4 bytes Size of the included file
lengths
end | ruby | {
"resource": ""
} |
q14955 | HTTPI.Dime.read_data | train | def read_data(record, bytes, attribute_set)
attribute, length = attribute_set
content = bytes.slice!(0, length).pack('C*')
if attribute == :data && record.type_format == BINARY
content = StringIO.new(content)
end
record.send "#{attribute.to_s}=", content
bytes.slice!(0, 4 - (length & 3)) if (length & 3) != 0
end | ruby | {
"resource": ""
} |
q14956 | HTTPI.Response.decoded_gzip_body | train | def decoded_gzip_body
unless gzip = Zlib::GzipReader.new(StringIO.new(raw_body))
raise ArgumentError, "Unable to create Zlib::GzipReader"
end
gzip.read
ensure
gzip.close if gzip
end | ruby | {
"resource": ""
} |
q14957 | HTTPI.Response.decoded_dime_body | train | def decoded_dime_body(body = nil)
dime = Dime.new(body || raw_body)
self.attachments = dime.binary_records
dime.xml_records.first.data
end | ruby | {
"resource": ""
} |
q14958 | Adhearsion.Initializer.load_lib_folder | train | def load_lib_folder
return false if Adhearsion.config.core.lib.nil?
lib_folder = [Adhearsion.config.core.root, Adhearsion.config.core.lib].join '/'
return false unless File.directory? lib_folder
$LOAD_PATH.unshift lib_folder
Dir.chdir lib_folder do
rbfiles = File.join "**", "*.rb"
Dir.glob(rbfiles).each do |file|
require "#{lib_folder}/#{file}"
end
end
true
end | ruby | {
"resource": ""
} |
q14959 | Adhearsion.Call.tag | train | def tag(label)
abort ArgumentError.new "Tag must be a String or Symbol" unless [String, Symbol].include?(label.class)
@tags << label
end | ruby | {
"resource": ""
} |
q14960 | Adhearsion.Call.wait_for_end | train | def wait_for_end(timeout = nil)
if end_reason
end_reason
else
@end_blocker.wait(timeout)
end
rescue Celluloid::ConditionError => e
abort e
end | ruby | {
"resource": ""
} |
q14961 | Adhearsion.Call.on_joined | train | def on_joined(target = nil, &block)
register_event_handler Adhearsion::Event::Joined, *guards_for_target(target) do |event|
block.call event
end
end | ruby | {
"resource": ""
} |
q14962 | Adhearsion.Call.on_unjoined | train | def on_unjoined(target = nil, &block)
register_event_handler Adhearsion::Event::Unjoined, *guards_for_target(target), &block
end | ruby | {
"resource": ""
} |
q14963 | Adhearsion.Call.redirect | train | def redirect(to, headers = nil)
write_and_await_response Adhearsion::Rayo::Command::Redirect.new(to: to, headers: headers)
rescue Adhearsion::ProtocolError => e
abort e
end | ruby | {
"resource": ""
} |
q14964 | Adhearsion.Call.join | train | def join(target, options = {})
logger.debug "Joining to #{target}"
joined_condition = CountDownLatch.new(1)
on_joined target do
joined_condition.countdown!
end
unjoined_condition = CountDownLatch.new(1)
on_unjoined target do
unjoined_condition.countdown!
end
on_end do
joined_condition.countdown!
unjoined_condition.countdown!
end
command = Adhearsion::Rayo::Command::Join.new options.merge(join_options_with_target(target))
write_and_await_response command
{command: command, joined_condition: joined_condition, unjoined_condition: unjoined_condition}
rescue Adhearsion::ProtocolError => e
abort e
end | ruby | {
"resource": ""
} |
q14965 | Adhearsion.Call.unjoin | train | def unjoin(target = nil)
logger.info "Unjoining from #{target}"
command = Adhearsion::Rayo::Command::Unjoin.new join_options_with_target(target)
write_and_await_response command
rescue Adhearsion::ProtocolError => e
abort e
end | ruby | {
"resource": ""
} |
q14966 | Adhearsion.Call.send_message | train | def send_message(body, options = {})
logger.debug "Sending message: #{body}"
client.send_message id, domain, body, options
end | ruby | {
"resource": ""
} |
q14967 | Adhearsion.Call.execute_controller | train | def execute_controller(controller = nil, completion_callback = nil, &block)
raise ArgumentError, "Cannot supply a controller and a block at the same time" if controller && block_given?
controller ||= CallController.new current_actor, &block
logger.info "Executing controller #{controller.class}"
controller.bg_exec completion_callback
end | ruby | {
"resource": ""
} |
q14968 | Adhearsion.Statistics.dump | train | def dump
Dump.new timestamp: Time.now, call_counts: dump_call_counts, calls_by_route: dump_calls_by_route
end | ruby | {
"resource": ""
} |
q14969 | Adhearsion.CallController.invoke | train | def invoke(controller_class, metadata = nil)
controller = controller_class.new call, metadata
controller.run
end | ruby | {
"resource": ""
} |
q14970 | Adhearsion.CallController.stop_all_components | train | def stop_all_components
logger.info "Stopping all controller components"
@active_components.each do |component|
begin
component.stop!
rescue Adhearsion::Rayo::Component::InvalidActionError
end
end
end | ruby | {
"resource": ""
} |
q14971 | Adhearsion.Configuration.method_missing | train | def method_missing(method_name, *args, &block)
config = Loquacious::Configuration.for method_name, &block
raise Adhearsion::Configuration::ConfigurationError.new "Invalid plugin #{method_name}" if config.nil?
config
end | ruby | {
"resource": ""
} |
q14972 | Adhearsion.Console.run | train | def run
if jruby? || cruby_with_readline?
set_prompt
Pry.config.command_prefix = "%"
logger.info "Launching Adhearsion Console"
@pry_thread = Thread.current
pry
logger.info "Adhearsion Console exiting"
else
logger.error "Unable to launch Adhearsion Console: This version of Ruby is using libedit. You must use readline for the console to work."
end
end | ruby | {
"resource": ""
} |
q14973 | Adhearsion.OutboundCall.dial | train | def dial(to, options = {})
options = options.dup
options[:to] = to
if options[:timeout]
wait_timeout = options[:timeout]
options[:timeout] = options[:timeout] * 1000
else
wait_timeout = 60
end
uri = client.new_call_uri
options[:uri] = uri
@dial_command = Adhearsion::Rayo::Command::Dial.new(options)
ref = Adhearsion::Rayo::Ref.new uri: uri
@transport = ref.scheme
@id = ref.call_id
@domain = ref.domain
Adhearsion.active_calls << current_actor
write_and_await_response(@dial_command, wait_timeout, true).tap do |dial_command|
@start_time = dial_command.timestamp.to_time
if @dial_command.uri != self.uri
logger.warn "Requested call URI (#{uri}) was not respected. Tracking by new URI #{self.uri}. This might cause a race in event handling, please upgrade your Rayo server."
Adhearsion.active_calls << current_actor
Adhearsion.active_calls.delete(@id)
end
Adhearsion::Events.trigger :call_dialed, current_actor
end
rescue
clear_from_active_calls
raise
end | ruby | {
"resource": ""
} |
q14974 | Sass::Tree.RuleNode.add_rules | train | def add_rules(node)
@rule = Sass::Util.strip_string_array(
Sass::Util.merge_adjacent_strings(@rule + ["\n"] + node.rule))
try_to_parse_non_interpolated_rules
end | ruby | {
"resource": ""
} |
q14975 | Sass.Util.map_vals | train | def map_vals(hash)
# We don't delegate to map_hash for performance here
# because map_hash does more than is necessary.
rv = hash.class.new
hash = hash.as_stored if hash.is_a?(NormalizedMap)
hash.each do |k, v|
rv[k] = yield(v)
end
rv
end | ruby | {
"resource": ""
} |
q14976 | Sass.Util.map_hash | train | def map_hash(hash)
# Copy and modify is more performant than mapping to an array and using
# to_hash on the result.
rv = hash.class.new
hash.each do |k, v|
new_key, new_value = yield(k, v)
new_key = hash.denormalize(new_key) if hash.is_a?(NormalizedMap) && new_key == k
rv[new_key] = new_value
end
rv
end | ruby | {
"resource": ""
} |
q14977 | Sass.Util.powerset | train | def powerset(arr)
arr.inject([Set.new].to_set) do |powerset, el|
new_powerset = Set.new
powerset.each do |subset|
new_powerset << subset
new_powerset << subset + [el]
end
new_powerset
end
end | ruby | {
"resource": ""
} |
q14978 | Sass.Util.restrict | train | def restrict(value, range)
[[value, range.first].max, range.last].min
end | ruby | {
"resource": ""
} |
q14979 | Sass.Util.merge_adjacent_strings | train | def merge_adjacent_strings(arr)
# Optimize for the common case of one element
return arr if arr.size < 2
arr.inject([]) do |a, e|
if e.is_a?(String)
if a.last.is_a?(String)
a.last << e
else
a << e.dup
end
else
a << e
end
a
end
end | ruby | {
"resource": ""
} |
q14980 | Sass.Util.replace_subseq | train | def replace_subseq(arr, subseq, replacement)
new = []
matched = []
i = 0
arr.each do |elem|
if elem != subseq[i]
new.push(*matched)
matched = []
i = 0
new << elem
next
end
if i == subseq.length - 1
matched = []
i = 0
new.push(*replacement)
else
matched << elem
i += 1
end
end
new.push(*matched)
new
end | ruby | {
"resource": ""
} |
q14981 | Sass.Util.substitute | train | def substitute(ary, from, to)
res = ary.dup
i = 0
while i < res.size
if res[i...i + from.size] == from
res[i...i + from.size] = to
end
i += 1
end
res
end | ruby | {
"resource": ""
} |
q14982 | Sass.Util.paths | train | def paths(arrs)
arrs.inject([[]]) do |paths, arr|
arr.map {|e| paths.map {|path| path + [e]}}.flatten(1)
end
end | ruby | {
"resource": ""
} |
q14983 | Sass.Util.lcs | train | def lcs(x, y, &block)
x = [nil, *x]
y = [nil, *y]
block ||= proc {|a, b| a == b && a}
lcs_backtrace(lcs_table(x, y, &block), x, y, x.size - 1, y.size - 1, &block)
end | ruby | {
"resource": ""
} |
q14984 | Sass.Util.caller_info | train | def caller_info(entry = nil)
# JRuby evaluates `caller` incorrectly when it's in an actual default argument.
entry ||= caller[1]
info = entry.scan(/^((?:[A-Za-z]:)?.*?):(-?.*?)(?::.*`(.+)')?$/).first
info[1] = info[1].to_i
# This is added by Rubinius to designate a block, but we don't care about it.
info[2].sub!(/ \{\}\Z/, '') if info[2]
info
end | ruby | {
"resource": ""
} |
q14985 | Sass.Util.version_gt | train | def version_gt(v1, v2)
# Construct an array to make sure the shorter version is padded with nil
Array.new([v1.length, v2.length].max).zip(v1.split("."), v2.split(".")) do |_, p1, p2|
p1 ||= "0"
p2 ||= "0"
release1 = p1 =~ /^[0-9]+$/
release2 = p2 =~ /^[0-9]+$/
if release1 && release2
# Integer comparison if both are full releases
p1, p2 = p1.to_i, p2.to_i
next if p1 == p2
return p1 > p2
elsif !release1 && !release2
# String comparison if both are prereleases
next if p1 == p2
return p1 > p2
else
# If only one is a release, that one is newer
return release1
end
end
end | ruby | {
"resource": ""
} |
q14986 | Sass.Util.deprecated | train | def deprecated(obj, message = nil)
obj_class = obj.is_a?(Class) ? "#{obj}." : "#{obj.class}#"
full_message = "DEPRECATION WARNING: #{obj_class}#{caller_info[2]} " +
"will be removed in a future version of Sass.#{("\n" + message) if message}"
Sass::Util.sass_warn full_message
end | ruby | {
"resource": ""
} |
q14987 | Sass.Util.silence_sass_warnings | train | def silence_sass_warnings
old_level, Sass.logger.log_level = Sass.logger.log_level, :error
yield
ensure
Sass.logger.log_level = old_level
end | ruby | {
"resource": ""
} |
q14988 | Sass.Util.rails_root | train | def rails_root
if defined?(::Rails.root)
return ::Rails.root.to_s if ::Rails.root
raise "ERROR: Rails.root is nil!"
end
return RAILS_ROOT.to_s if defined?(RAILS_ROOT)
nil
end | ruby | {
"resource": ""
} |
q14989 | Sass.Util.ap_geq? | train | def ap_geq?(version)
# The ActionPack module is always loaded automatically in Rails >= 3
return false unless defined?(ActionPack) && defined?(ActionPack::VERSION) &&
defined?(ActionPack::VERSION::STRING)
version_geq(ActionPack::VERSION::STRING, version)
end | ruby | {
"resource": ""
} |
q14990 | Sass.Util.glob | train | def glob(path)
path = path.tr('\\', '/') if windows?
if block_given?
Dir.glob(path) {|f| yield(f)}
else
Dir.glob(path)
end
end | ruby | {
"resource": ""
} |
q14991 | Sass.Util.realpath | train | def realpath(path)
path = Pathname.new(path) unless path.is_a?(Pathname)
# Explicitly DON'T run #pathname here. We don't want to convert
# to Windows directory separators because we're comparing these
# against the paths returned by Listen, which use forward
# slashes everywhere.
begin
path.realpath
rescue SystemCallError
# If [path] doesn't actually exist, don't bail, just
# return the original.
path
end
end | ruby | {
"resource": ""
} |
q14992 | Sass.Util.relative_path_from | train | def relative_path_from(path, from)
pathname(path.to_s).relative_path_from(pathname(from.to_s))
rescue NoMethodError => e
raise e unless e.name == :zero?
# Work around https://github.com/ruby/ruby/pull/713.
path = path.to_s
from = from.to_s
raise ArgumentError("Incompatible path encodings: #{path.inspect} is #{path.encoding}, " +
"#{from.inspect} is #{from.encoding}")
end | ruby | {
"resource": ""
} |
q14993 | Sass.Util.extract! | train | def extract!(array)
out = []
array.reject! do |e|
next false unless yield e
out << e
true
end
out
end | ruby | {
"resource": ""
} |
q14994 | Sass.Util.with_extracted_values | train | def with_extracted_values(arr)
str, vals = extract_values(arr)
str = yield str
inject_values(str, vals)
end | ruby | {
"resource": ""
} |
q14995 | Sass.Util.json_escape_string | train | def json_escape_string(s)
return s if s !~ /["\\\b\f\n\r\t]/
result = ""
s.split("").each do |c|
case c
when '"', "\\"
result << "\\" << c
when "\n" then result << "\\n"
when "\t" then result << "\\t"
when "\r" then result << "\\r"
when "\f" then result << "\\f"
when "\b" then result << "\\b"
else
result << c
end
end
result
end | ruby | {
"resource": ""
} |
q14996 | Sass.Util.json_value_of | train | def json_value_of(v)
case v
when Integer
v.to_s
when String
"\"" + json_escape_string(v) + "\""
when Array
"[" + v.map {|x| json_value_of(x)}.join(",") + "]"
when NilClass
"null"
when TrueClass
"true"
when FalseClass
"false"
else
raise ArgumentError.new("Unknown type: #{v.class.name}")
end
end | ruby | {
"resource": ""
} |
q14997 | Sass.Util.atomic_create_and_write_file | train | def atomic_create_and_write_file(filename, perms = 0666)
require 'tempfile'
tmpfile = Tempfile.new(File.basename(filename), File.dirname(filename))
tmpfile.binmode if tmpfile.respond_to?(:binmode)
result = yield tmpfile
tmpfile.close
ATOMIC_WRITE_MUTEX.synchronize do
begin
File.chmod(perms & ~File.umask, tmpfile.path)
rescue Errno::EPERM
# If we don't have permissions to chmod the file, don't let that crash
# the compilation. See issue 1215.
end
File.rename tmpfile.path, filename
end
result
ensure
# close and remove the tempfile if it still exists,
# presumably due to an error during write
tmpfile.close if tmpfile
tmpfile.unlink if tmpfile
end | ruby | {
"resource": ""
} |
q14998 | Sass::Script::Value.Map.options= | train | def options=(options)
super
value.each do |k, v|
k.options = options
v.options = options
end
end | ruby | {
"resource": ""
} |
q14999 | Sass::Script::Tree.Node.perform | train | def perform(environment)
_perform(environment)
rescue Sass::SyntaxError => e
e.modify_backtrace(:line => line)
raise e
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.