id
int32 0
24.9k
| repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
|
|---|---|---|---|---|---|---|---|---|---|---|---|
14,900
|
bigcommerce/gruf
|
lib/gruf/error.rb
|
Gruf.Error.attach_to_call
|
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
|
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
|
[
"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"
] |
Update the trailing metadata on the given gRPC call, including the error payload if configured
to do so.
@param [GRPC::ActiveCall] active_call The marshalled gRPC call
@return [Error] Return the error itself after updating metadata on the given gRPC call.
In the case of a metadata overflow error, we replace the current error with
a new one that won't cause a low-level http2 error.
|
[
"Update",
"the",
"trailing",
"metadata",
"on",
"the",
"given",
"gRPC",
"call",
"including",
"the",
"error",
"payload",
"if",
"configured",
"to",
"do",
"so",
"."
] |
9e438b174df81845c8100302da671721d5a112c5
|
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/error.rb#L151-L168
|
14,901
|
bigcommerce/gruf
|
lib/gruf/error.rb
|
Gruf.Error.to_h
|
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
|
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
|
[
"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"
] |
Return the error represented in Hash form
@return [Hash] The error as a hash
|
[
"Return",
"the",
"error",
"represented",
"in",
"Hash",
"form"
] |
9e438b174df81845c8100302da671721d5a112c5
|
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/error.rb#L186-L194
|
14,902
|
bigcommerce/gruf
|
lib/gruf/error.rb
|
Gruf.Error.serializer_class
|
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
|
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
|
[
"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"
] |
Return the error serializer being used for gruf
@return [Gruf::Serializers::Errors::Base]
|
[
"Return",
"the",
"error",
"serializer",
"being",
"used",
"for",
"gruf"
] |
9e438b174df81845c8100302da671721d5a112c5
|
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/error.rb#L213-L219
|
14,903
|
bigcommerce/gruf
|
lib/gruf/server.rb
|
Gruf.Server.server
|
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
|
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
|
[
"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"
] |
Initialize the server and load and setup the services
@param [Hash] opts
@return [GRPC::RpcServer] The GRPC server running
|
[
"Initialize",
"the",
"server",
"and",
"load",
"and",
"setup",
"the",
"services"
] |
9e438b174df81845c8100302da671721d5a112c5
|
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/server.rb#L56-L82
|
14,904
|
bigcommerce/gruf
|
lib/gruf/server.rb
|
Gruf.Server.start!
|
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
|
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
|
[
"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"
] |
Start the gRPC server
:nocov:
|
[
"Start",
"the",
"gRPC",
"server"
] |
9e438b174df81845c8100302da671721d5a112c5
|
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/server.rb#L88-L115
|
14,905
|
bigcommerce/gruf
|
lib/gruf/server.rb
|
Gruf.Server.insert_interceptor_before
|
def insert_interceptor_before(before_class, interceptor_class, opts = {})
raise ServerAlreadyStartedError if @started
@interceptors.insert_before(before_class, interceptor_class, opts)
end
|
ruby
|
def insert_interceptor_before(before_class, interceptor_class, opts = {})
raise ServerAlreadyStartedError if @started
@interceptors.insert_before(before_class, interceptor_class, opts)
end
|
[
"def",
"insert_interceptor_before",
"(",
"before_class",
",",
"interceptor_class",
",",
"opts",
"=",
"{",
"}",
")",
"raise",
"ServerAlreadyStartedError",
"if",
"@started",
"@interceptors",
".",
"insert_before",
"(",
"before_class",
",",
"interceptor_class",
",",
"opts",
")",
"end"
] |
Insert an interceptor before another in the currently registered order of execution
@param [Class] before_class The interceptor that you want to add the new interceptor before
@param [Class] interceptor_class The Interceptor to add to the registry
@param [Hash] opts A hash of options for the interceptor
|
[
"Insert",
"an",
"interceptor",
"before",
"another",
"in",
"the",
"currently",
"registered",
"order",
"of",
"execution"
] |
9e438b174df81845c8100302da671721d5a112c5
|
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/server.rb#L150-L154
|
14,906
|
bigcommerce/gruf
|
lib/gruf/server.rb
|
Gruf.Server.insert_interceptor_after
|
def insert_interceptor_after(after_class, interceptor_class, opts = {})
raise ServerAlreadyStartedError if @started
@interceptors.insert_after(after_class, interceptor_class, opts)
end
|
ruby
|
def insert_interceptor_after(after_class, interceptor_class, opts = {})
raise ServerAlreadyStartedError if @started
@interceptors.insert_after(after_class, interceptor_class, opts)
end
|
[
"def",
"insert_interceptor_after",
"(",
"after_class",
",",
"interceptor_class",
",",
"opts",
"=",
"{",
"}",
")",
"raise",
"ServerAlreadyStartedError",
"if",
"@started",
"@interceptors",
".",
"insert_after",
"(",
"after_class",
",",
"interceptor_class",
",",
"opts",
")",
"end"
] |
Insert an interceptor after another in the currently registered order of execution
@param [Class] after_class The interceptor that you want to add the new interceptor after
@param [Class] interceptor_class The Interceptor to add to the registry
@param [Hash] opts A hash of options for the interceptor
|
[
"Insert",
"an",
"interceptor",
"after",
"another",
"in",
"the",
"currently",
"registered",
"order",
"of",
"execution"
] |
9e438b174df81845c8100302da671721d5a112c5
|
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/server.rb#L163-L167
|
14,907
|
bigcommerce/gruf
|
lib/gruf/configuration.rb
|
Gruf.Configuration.options
|
def options
opts = {}
VALID_CONFIG_KEYS.each_key do |k|
opts.merge!(k => send(k))
end
opts
end
|
ruby
|
def options
opts = {}
VALID_CONFIG_KEYS.each_key do |k|
opts.merge!(k => send(k))
end
opts
end
|
[
"def",
"options",
"opts",
"=",
"{",
"}",
"VALID_CONFIG_KEYS",
".",
"each_key",
"do",
"|",
"k",
"|",
"opts",
".",
"merge!",
"(",
"k",
"=>",
"send",
"(",
"k",
")",
")",
"end",
"opts",
"end"
] |
Return the current configuration options as a Hash
@return [Hash] The configuration for gruf, represented as a Hash
|
[
"Return",
"the",
"current",
"configuration",
"options",
"as",
"a",
"Hash"
] |
9e438b174df81845c8100302da671721d5a112c5
|
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/configuration.rb#L84-L90
|
14,908
|
bigcommerce/gruf
|
lib/gruf/configuration.rb
|
Gruf.Configuration.reset
|
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
|
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
|
[
"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"
] |
Set the default configuration onto the extended class
@return [Hash] options The reset options hash
|
[
"Set",
"the",
"default",
"configuration",
"onto",
"the",
"extended",
"class"
] |
9e438b174df81845c8100302da671721d5a112c5
|
https://github.com/bigcommerce/gruf/blob/9e438b174df81845c8100302da671721d5a112c5/lib/gruf/configuration.rb#L97-L118
|
14,909
|
gonzalo-bulnes/simple_token_authentication
|
lib/simple_token_authentication/exception_fallback_handler.rb
|
SimpleTokenAuthentication.ExceptionFallbackHandler.fallback!
|
def fallback!(controller, entity)
throw(:warden, scope: entity.name_underscore.to_sym) if controller.send("current_#{entity.name_underscore}").nil?
end
|
ruby
|
def fallback!(controller, entity)
throw(:warden, scope: entity.name_underscore.to_sym) if controller.send("current_#{entity.name_underscore}").nil?
end
|
[
"def",
"fallback!",
"(",
"controller",
",",
"entity",
")",
"throw",
"(",
":warden",
",",
"scope",
":",
"entity",
".",
"name_underscore",
".",
"to_sym",
")",
"if",
"controller",
".",
"send",
"(",
"\"current_#{entity.name_underscore}\"",
")",
".",
"nil?",
"end"
] |
Notifies the failure of authentication to Warden in the same Devise does.
Does result in an HTTP 401 response in a Devise context.
|
[
"Notifies",
"the",
"failure",
"of",
"authentication",
"to",
"Warden",
"in",
"the",
"same",
"Devise",
"does",
".",
"Does",
"result",
"in",
"an",
"HTTP",
"401",
"response",
"in",
"a",
"Devise",
"context",
"."
] |
2ea7d13e155bf7d7da22a69e3e884e94d05a8dae
|
https://github.com/gonzalo-bulnes/simple_token_authentication/blob/2ea7d13e155bf7d7da22a69e3e884e94d05a8dae/lib/simple_token_authentication/exception_fallback_handler.rb#L7-L9
|
14,910
|
inspec/train
|
lib/train/transports/ssh.rb
|
Train::Transports.SSH.verify_host_key_option
|
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
|
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
|
[
"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"
] |
Returns the correct host-key-verification option key to use depending
on what version of net-ssh is in use. In net-ssh <= 4.1, the supported
parameter is `paranoid` but in 4.2, it became `verify_host_key`
`verify_host_key` does not work in <= 4.1, and `paranoid` throws
deprecation warnings in >= 4.2.
While the "right thing" to do would be to pin train's dependency on
net-ssh to ~> 4.2, this will prevent InSpec from being used in
Chef v12 because of it pinning to a v3 of net-ssh.
|
[
"Returns",
"the",
"correct",
"host",
"-",
"key",
"-",
"verification",
"option",
"key",
"to",
"use",
"depending",
"on",
"what",
"version",
"of",
"net",
"-",
"ssh",
"is",
"in",
"use",
".",
"In",
"net",
"-",
"ssh",
"<",
"=",
"4",
".",
"1",
"the",
"supported",
"parameter",
"is",
"paranoid",
"but",
"in",
"4",
".",
"2",
"it",
"became",
"verify_host_key"
] |
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
|
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/transports/ssh.rb#L189-L194
|
14,911
|
inspec/train
|
lib/train/transports/ssh.rb
|
Train::Transports.SSH.create_new_connection
|
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
|
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
|
[
"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"
] |
Creates a new SSH Connection instance and save it for potential future
reuse.
@param options [Hash] conneciton options
@return [Ssh::Connection] an SSH Connection instance
@api private
|
[
"Creates",
"a",
"new",
"SSH",
"Connection",
"instance",
"and",
"save",
"it",
"for",
"potential",
"future",
"reuse",
"."
] |
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
|
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/transports/ssh.rb#L231-L257
|
14,912
|
inspec/train
|
lib/train/file.rb
|
Train.File.perform_checksum_ruby
|
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
|
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
|
[
"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"
] |
This pulls the content of the file to the machine running Train and uses
Digest to perform the checksum. This is less efficient than using remote
system binaries and can lead to incorrect results due to encoding.
|
[
"This",
"pulls",
"the",
"content",
"of",
"the",
"file",
"to",
"the",
"machine",
"running",
"Train",
"and",
"uses",
"Digest",
"to",
"perform",
"the",
"checksum",
".",
"This",
"is",
"less",
"efficient",
"than",
"using",
"remote",
"system",
"binaries",
"and",
"can",
"lead",
"to",
"incorrect",
"results",
"due",
"to",
"encoding",
"."
] |
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
|
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/file.rb#L193-L208
|
14,913
|
inspec/train
|
lib/train/transports/winrm.rb
|
Train::Transports.WinRM.create_new_connection
|
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
|
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
|
[
"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"
] |
Creates a new WinRM Connection instance and save it for potential
future reuse.
@param options [Hash] conneciton options
@return [WinRM::Connection] a WinRM Connection instance
@api private
|
[
"Creates",
"a",
"new",
"WinRM",
"Connection",
"instance",
"and",
"save",
"it",
"for",
"potential",
"future",
"reuse",
"."
] |
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
|
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/transports/winrm.rb#L146-L154
|
14,914
|
inspec/train
|
lib/train/platforms/common.rb
|
Train::Platforms.Common.in_family
|
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
|
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
|
[
"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"
] |
Add a family connection. This will create a family
if it does not exist and add a child relationship.
|
[
"Add",
"a",
"family",
"connection",
".",
"This",
"will",
"create",
"a",
"family",
"if",
"it",
"does",
"not",
"exist",
"and",
"add",
"a",
"child",
"relationship",
"."
] |
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
|
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/platforms/common.rb#L7-L19
|
14,915
|
inspec/train
|
lib/train/extras/command_wrapper.rb
|
Train::Extras.LinuxCommand.sudo_wrap
|
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
|
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
|
[
"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"
] |
wrap the cmd in a sudo command
|
[
"wrap",
"the",
"cmd",
"in",
"a",
"sudo",
"command"
] |
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
|
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/extras/command_wrapper.rb#L92-L103
|
14,916
|
inspec/train
|
lib/train/extras/command_wrapper.rb
|
Train::Extras.WindowsCommand.powershell_wrap
|
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
|
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
|
[
"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"
] |
Wrap the cmd in an encoded command to allow pipes and quotes
|
[
"Wrap",
"the",
"cmd",
"in",
"an",
"encoded",
"command",
"to",
"allow",
"pipes",
"and",
"quotes"
] |
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
|
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/extras/command_wrapper.rb#L145-L157
|
14,917
|
inspec/train
|
lib/train/platforms/detect/scanner.rb
|
Train::Platforms::Detect.Scanner.scan
|
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
|
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
|
[
"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"
] |
Main detect method to scan all platforms for a match
@return Train::Platform instance or error if none found
|
[
"Main",
"detect",
"method",
"to",
"scan",
"all",
"platforms",
"for",
"a",
"match"
] |
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
|
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/platforms/detect/scanner.rb#L24-L42
|
14,918
|
inspec/train
|
lib/train/platforms/platform.rb
|
Train::Platforms.Platform.add_platform_methods
|
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
|
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
|
[
"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"
] |
Add generic family? and platform methods to an existing platform
This is done later to add any custom
families/properties that were created
|
[
"Add",
"generic",
"family?",
"and",
"platform",
"methods",
"to",
"an",
"existing",
"platform"
] |
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
|
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/platforms/platform.rb#L80-L107
|
14,919
|
inspec/train
|
lib/train/platforms/detect/helpers/os_windows.rb
|
Train::Platforms::Detect::Helpers.Windows.read_wmic
|
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
|
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
|
[
"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"
] |
reads os name and version from wmic
@see https://msdn.microsoft.com/en-us/library/bb742610.aspx#EEAA
Thanks to Matt Wrock (https://github.com/mwrock) for this hint
|
[
"reads",
"os",
"name",
"and",
"version",
"from",
"wmic"
] |
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
|
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/platforms/detect/helpers/os_windows.rb#L33-L49
|
14,920
|
inspec/train
|
lib/train/platforms/detect/helpers/os_windows.rb
|
Train::Platforms::Detect::Helpers.Windows.read_wmic_cpu
|
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
|
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
|
[
"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"
] |
`OSArchitecture` from `read_wmic` does not match a normal standard
For example, `x86_64` shows as `64-bit`
|
[
"OSArchitecture",
"from",
"read_wmic",
"does",
"not",
"match",
"a",
"normal",
"standard",
"For",
"example",
"x86_64",
"shows",
"as",
"64",
"-",
"bit"
] |
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
|
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/platforms/detect/helpers/os_windows.rb#L53-L78
|
14,921
|
inspec/train
|
lib/train/platforms/detect/helpers/os_windows.rb
|
Train::Platforms::Detect::Helpers.Windows.windows_uuid
|
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
|
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
|
[
"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"
] |
This method scans the target os for a unique uuid to use
|
[
"This",
"method",
"scans",
"the",
"target",
"os",
"for",
"a",
"unique",
"uuid",
"to",
"use"
] |
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
|
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/platforms/detect/helpers/os_windows.rb#L81-L88
|
14,922
|
inspec/train
|
examples/plugins/train-local-rot13/lib/train-local-rot13/platform.rb
|
TrainPlugins::LocalRot13.Platform.platform
|
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
|
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
|
[
"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"
] |
The method `platform` is called when platform detection is
about to be performed. Train core defines a sophisticated
system for platform detection, but for most plugins, you'll
only ever run on the special platform for which you are targeting.
|
[
"The",
"method",
"platform",
"is",
"called",
"when",
"platform",
"detection",
"is",
"about",
"to",
"be",
"performed",
".",
"Train",
"core",
"defines",
"a",
"sophisticated",
"system",
"for",
"platform",
"detection",
"but",
"for",
"most",
"plugins",
"you",
"ll",
"only",
"ever",
"run",
"on",
"the",
"special",
"platform",
"for",
"which",
"you",
"are",
"targeting",
"."
] |
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
|
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/examples/plugins/train-local-rot13/lib/train-local-rot13/platform.rb#L14-L36
|
14,923
|
inspec/train
|
lib/train/platforms/detect/helpers/os_common.rb
|
Train::Platforms::Detect::Helpers.OSCommon.uuid_from_command
|
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
|
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
|
[
"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"
] |
This takes a command from the platform detect block to run.
We expect the command to return a unique identifier which
we turn into a UUID.
|
[
"This",
"takes",
"a",
"command",
"from",
"the",
"platform",
"detect",
"block",
"to",
"run",
".",
"We",
"expect",
"the",
"command",
"to",
"return",
"a",
"unique",
"identifier",
"which",
"we",
"turn",
"into",
"a",
"UUID",
"."
] |
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
|
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/platforms/detect/helpers/os_common.rb#L125-L129
|
14,924
|
inspec/train
|
lib/train/platforms/detect/helpers/os_common.rb
|
Train::Platforms::Detect::Helpers.OSCommon.uuid_from_string
|
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
|
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
|
[
"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"
] |
This hashes the passed string into SHA1.
Then it downgrades the 160bit SHA1 to a 128bit
then we format it as a valid UUIDv5.
|
[
"This",
"hashes",
"the",
"passed",
"string",
"into",
"SHA1",
".",
"Then",
"it",
"downgrades",
"the",
"160bit",
"SHA1",
"to",
"a",
"128bit",
"then",
"we",
"format",
"it",
"as",
"a",
"valid",
"UUIDv5",
"."
] |
ec41c1f1e6f38f6ab1c335955651064eaeb7028f
|
https://github.com/inspec/train/blob/ec41c1f1e6f38f6ab1c335955651064eaeb7028f/lib/train/platforms/detect/helpers/os_common.rb#L134-L142
|
14,925
|
guilhermesad/rspotify
|
lib/rspotify/category.rb
|
RSpotify.Category.playlists
|
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
|
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
|
[
"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"
] |
Get a list of Spotify playlists tagged with a particular category.
@param limit [Integer] Maximum number of playlists to return. Maximum: 50. Default: 20.
@param offset [Integer] The index of the first playlist to return. Use with limit to get the next set of playlists. Default: 0.
@param country [String] Optional. A country: an {http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 ISO 3166-1 alpha-2 country code}. Provide this parameter if you want to narrow the list of returned playlists to those relevant to a particular country. If omitted, the returned playlists will be globally relevant.
@return [Array<Playlist>]
@example
playlists = category.playlists
playlists = category.playlists(country: 'BR')
playlists = category.playlists(limit: 10, offset: 20)
|
[
"Get",
"a",
"list",
"of",
"Spotify",
"playlists",
"tagged",
"with",
"a",
"particular",
"category",
"."
] |
02db6f0f2730b69f6bfcc362435f553ebeaa2eab
|
https://github.com/guilhermesad/rspotify/blob/02db6f0f2730b69f6bfcc362435f553ebeaa2eab/lib/rspotify/category.rb#L89-L100
|
14,926
|
guilhermesad/rspotify
|
lib/rspotify/player.rb
|
RSpotify.Player.play
|
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
|
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
|
[
"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"
] |
Play the user's currently active player or specific device
If `device_id` is not passed, the currently active spotify app will be triggered
@example
player = user.player
player.play
|
[
"Play",
"the",
"user",
"s",
"currently",
"active",
"player",
"or",
"specific",
"device",
"If",
"device_id",
"is",
"not",
"passed",
"the",
"currently",
"active",
"spotify",
"app",
"will",
"be",
"triggered"
] |
02db6f0f2730b69f6bfcc362435f553ebeaa2eab
|
https://github.com/guilhermesad/rspotify/blob/02db6f0f2730b69f6bfcc362435f553ebeaa2eab/lib/rspotify/player.rb#L66-L71
|
14,927
|
guilhermesad/rspotify
|
lib/rspotify/player.rb
|
RSpotify.Player.repeat
|
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
|
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
|
[
"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"
] |
Toggle the current user's player repeat status.
If `device_id` is not passed, the currently active spotify app will be triggered.
If `state` is not passed, the currently active context will be set to repeat.
@see https://developer.spotify.com/documentation/web-api/reference/player/set-repeat-mode-on-users-playback/
@param [String] device_id the ID of the device to set the repeat state on.
@param [String] state the repeat state. Defaults to the current play context.
@example
player = user.player
player.repeat(state: 'track')
|
[
"Toggle",
"the",
"current",
"user",
"s",
"player",
"repeat",
"status",
".",
"If",
"device_id",
"is",
"not",
"passed",
"the",
"currently",
"active",
"spotify",
"app",
"will",
"be",
"triggered",
".",
"If",
"state",
"is",
"not",
"passed",
"the",
"currently",
"active",
"context",
"will",
"be",
"set",
"to",
"repeat",
"."
] |
02db6f0f2730b69f6bfcc362435f553ebeaa2eab
|
https://github.com/guilhermesad/rspotify/blob/02db6f0f2730b69f6bfcc362435f553ebeaa2eab/lib/rspotify/player.rb#L85-L91
|
14,928
|
guilhermesad/rspotify
|
lib/rspotify/player.rb
|
RSpotify.Player.shuffle
|
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
|
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
|
[
"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"
] |
Toggle the current user's shuffle status.
If `device_id` is not passed, the currently active spotify app will be triggered.
If `state` is not passed, shuffle mode will be turned on.
@see https://developer.spotify.com/documentation/web-api/reference/player/toggle-shuffle-for-users-playback/
@param [String] device_id the ID of the device to set the shuffle state on.
@param [String] state the shuffle state. Defaults to turning the shuffle behavior on.
@example
player = user.player
player.shuffle(state: false)
|
[
"Toggle",
"the",
"current",
"user",
"s",
"shuffle",
"status",
".",
"If",
"device_id",
"is",
"not",
"passed",
"the",
"currently",
"active",
"spotify",
"app",
"will",
"be",
"triggered",
".",
"If",
"state",
"is",
"not",
"passed",
"shuffle",
"mode",
"will",
"be",
"turned",
"on",
"."
] |
02db6f0f2730b69f6bfcc362435f553ebeaa2eab
|
https://github.com/guilhermesad/rspotify/blob/02db6f0f2730b69f6bfcc362435f553ebeaa2eab/lib/rspotify/player.rb#L115-L121
|
14,929
|
guilhermesad/rspotify
|
lib/rspotify/album.rb
|
RSpotify.Album.tracks
|
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
|
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
|
[
"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"
] |
Returns array of tracks from the album
@param limit [Integer] Maximum number of tracks to return. Maximum: 50. Default: 50.
@param offset [Integer] The index of the first track to return. Use with limit to get the next set of objects. Default: 0.
@param market [String] Optional. An {http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 ISO 3166-1 alpha-2 country code}. Default: nil.
@return [Array<Track>]
@example
album = RSpotify::Album.find('41vPD50kQ7JeamkxQW7Vuy')
album.tracks.first.name #=> "Do I Wanna Know?"
|
[
"Returns",
"array",
"of",
"tracks",
"from",
"the",
"album"
] |
02db6f0f2730b69f6bfcc362435f553ebeaa2eab
|
https://github.com/guilhermesad/rspotify/blob/02db6f0f2730b69f6bfcc362435f553ebeaa2eab/lib/rspotify/album.rb#L111-L127
|
14,930
|
guilhermesad/rspotify
|
lib/rspotify/artist.rb
|
RSpotify.Artist.albums
|
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
|
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
|
[
"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"
] |
Returns array of albums from artist
@param limit [Integer] Maximum number of albums to return. Maximum: 50. Default: 20.
@param offset [Integer] The index of the first album to return. Use with limit to get the next set of albums. Default: 0.
@param album_type [String] Optional. A comma-separated list of keywords that will be used to filter the response. If not supplied, all album types will be returned. Valid values are: album; single; appears_on; compilation.
@param market [String] Optional. (synonym: country). An {http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 ISO 3166-1 alpha-2 country code}. Supply this parameter to limit the response to one particular geographical market. If not supplied, results will be returned for all markets. Note if you do not provide this field, you are likely to get duplicate results per album, one for each market in which the album is available.
@return [Array<Album>]
@example
artist.albums
artist.albums(album_type: 'single,compilation')
artist.albums(limit: 50, country: 'US')
|
[
"Returns",
"array",
"of",
"albums",
"from",
"artist"
] |
02db6f0f2730b69f6bfcc362435f553ebeaa2eab
|
https://github.com/guilhermesad/rspotify/blob/02db6f0f2730b69f6bfcc362435f553ebeaa2eab/lib/rspotify/artist.rb#L69-L78
|
14,931
|
guilhermesad/rspotify
|
lib/rspotify/artist.rb
|
RSpotify.Artist.top_tracks
|
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
|
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
|
[
"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"
] |
Returns artist's 10 top tracks by country.
@param country [Symbol] An {http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 ISO 3166-1 alpha-2 country code}
@return [Array<Track>]
@example
top_tracks = artist.top_tracks(:US)
top_tracks.class #=> Array
top_tracks.size #=> 10
top_tracks.first.class #=> RSpotify::Track
|
[
"Returns",
"artist",
"s",
"10",
"top",
"tracks",
"by",
"country",
"."
] |
02db6f0f2730b69f6bfcc362435f553ebeaa2eab
|
https://github.com/guilhermesad/rspotify/blob/02db6f0f2730b69f6bfcc362435f553ebeaa2eab/lib/rspotify/artist.rb#L108-L114
|
14,932
|
guilhermesad/rspotify
|
lib/rspotify/playlist.rb
|
RSpotify.Playlist.tracks
|
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
|
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
|
[
"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"
] |
Returns array of tracks from the playlist
@param limit [Integer] Maximum number of tracks to return. Maximum: 100. Default: 100.
@param offset [Integer] The index of the first track to return. Use with limit to get the next set of objects. Default: 0.
@param market [String] Optional. An {https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 ISO 3166-1 alpha-2 country code}. Provide this parameter if you want to apply Track Relinking
@return [Array<Track>]
@example
playlist = RSpotify::Playlist.find('wizzler', '00wHcTN0zQiun4xri9pmvX')
playlist.tracks.first.name #=> "Main Theme from Star Wars - Instrumental"
|
[
"Returns",
"array",
"of",
"tracks",
"from",
"the",
"playlist"
] |
02db6f0f2730b69f6bfcc362435f553ebeaa2eab
|
https://github.com/guilhermesad/rspotify/blob/02db6f0f2730b69f6bfcc362435f553ebeaa2eab/lib/rspotify/playlist.rb#L255-L284
|
14,933
|
guilhermesad/rspotify
|
lib/rspotify/user.rb
|
RSpotify.User.playlists
|
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
|
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
|
[
"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"
] |
Returns all playlists from user
@param limit [Integer] Maximum number of playlists to return. Maximum: 50. Minimum: 1. Default: 20.
@param offset [Integer] The index of the first playlist to return. Use with limit to get the next set of playlists. Default: 0.
@return [Array<Playlist>]
@example
playlists = user.playlists
playlists.class #=> Array
playlists.first.class #=> RSpotify::Playlist
playlists.first.name #=> "Movie Soundtrack Masterpieces"
|
[
"Returns",
"all",
"playlists",
"from",
"user"
] |
02db6f0f2730b69f6bfcc362435f553ebeaa2eab
|
https://github.com/guilhermesad/rspotify/blob/02db6f0f2730b69f6bfcc362435f553ebeaa2eab/lib/rspotify/user.rb#L255-L260
|
14,934
|
guilhermesad/rspotify
|
lib/rspotify/user.rb
|
RSpotify.User.to_hash
|
def to_hash
pairs = instance_variables.map do |var|
[var.to_s.delete('@'), instance_variable_get(var)]
end
Hash[pairs]
end
|
ruby
|
def to_hash
pairs = instance_variables.map do |var|
[var.to_s.delete('@'), instance_variable_get(var)]
end
Hash[pairs]
end
|
[
"def",
"to_hash",
"pairs",
"=",
"instance_variables",
".",
"map",
"do",
"|",
"var",
"|",
"[",
"var",
".",
"to_s",
".",
"delete",
"(",
"'@'",
")",
",",
"instance_variable_get",
"(",
"var",
")",
"]",
"end",
"Hash",
"[",
"pairs",
"]",
"end"
] |
Returns a hash containing all user attributes
|
[
"Returns",
"a",
"hash",
"containing",
"all",
"user",
"attributes"
] |
02db6f0f2730b69f6bfcc362435f553ebeaa2eab
|
https://github.com/guilhermesad/rspotify/blob/02db6f0f2730b69f6bfcc362435f553ebeaa2eab/lib/rspotify/user.rb#L410-L415
|
14,935
|
guilhermesad/rspotify
|
lib/rspotify/user.rb
|
RSpotify.User.devices
|
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
|
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
|
[
"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"
] |
Returns the user's available devices
@return [Array<Device>]
@example
devices = user.devices
devices.first.id #=> "5fbb3ba6aa454b5534c4ba43a8c7e8e45a63ad0e"
|
[
"Returns",
"the",
"user",
"s",
"available",
"devices"
] |
02db6f0f2730b69f6bfcc362435f553ebeaa2eab
|
https://github.com/guilhermesad/rspotify/blob/02db6f0f2730b69f6bfcc362435f553ebeaa2eab/lib/rspotify/user.rb#L493-L499
|
14,936
|
nakiostudio/xcov
|
lib/xcov/ignore_handler.rb
|
Xcov.IgnoreHandler.relative_path
|
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
|
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
|
[
"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"
] |
Auxiliary methods
Returns a relative path against `source_directory`.
|
[
"Auxiliary",
"methods",
"Returns",
"a",
"relative",
"path",
"against",
"source_directory",
"."
] |
9fb0e043438fcc636db964fe6ca547162a170b73
|
https://github.com/nakiostudio/xcov/blob/9fb0e043438fcc636db964fe6ca547162a170b73/lib/xcov/ignore_handler.rb#L52-L59
|
14,937
|
nakiostudio/xcov
|
lib/xcov/project_extensions.rb
|
FastlaneCore.Project.targets
|
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
|
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
|
[
"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"
] |
Returns project targets
|
[
"Returns",
"project",
"targets"
] |
9fb0e043438fcc636db964fe6ca547162a170b73
|
https://github.com/nakiostudio/xcov/blob/9fb0e043438fcc636db964fe6ca547162a170b73/lib/xcov/project_extensions.rb#L8-L17
|
14,938
|
octopress/octopress
|
lib/octopress/page.rb
|
Octopress.Page.content
|
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
|
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
|
[
"def",
"content",
"# Handle case where user passes the full path",
"#",
"file",
"=",
"@options",
"[",
"'template'",
"]",
"||",
"default_template",
"if",
"file",
"file",
".",
"sub!",
"(",
"/",
"\\/",
"/",
",",
"''",
")",
"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"
] |
Load the user provided or default template for a new post or page.
|
[
"Load",
"the",
"user",
"provided",
"or",
"default",
"template",
"for",
"a",
"new",
"post",
"or",
"page",
"."
] |
af048361405919605d50fc45e2e1fd0c7eb02703
|
https://github.com/octopress/octopress/blob/af048361405919605d50fc45e2e1fd0c7eb02703/lib/octopress/page.rb#L126-L145
|
14,939
|
octopress/octopress
|
lib/octopress/page.rb
|
Octopress.Page.parse_template
|
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
|
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
|
[
"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",
"\\s",
"\\s",
"/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"
] |
Render Liquid vars in YAML front-matter.
|
[
"Render",
"Liquid",
"vars",
"in",
"YAML",
"front",
"-",
"matter",
"."
] |
af048361405919605d50fc45e2e1fd0c7eb02703
|
https://github.com/octopress/octopress/blob/af048361405919605d50fc45e2e1fd0c7eb02703/lib/octopress/page.rb#L152-L188
|
14,940
|
octopress/octopress
|
lib/octopress/page.rb
|
Octopress.Page.title_slug
|
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
|
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
|
[
"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"
] |
Returns a string which is url compatible.
|
[
"Returns",
"a",
"string",
"which",
"is",
"url",
"compatible",
"."
] |
af048361405919605d50fc45e2e1fd0c7eb02703
|
https://github.com/octopress/octopress/blob/af048361405919605d50fc45e2e1fd0c7eb02703/lib/octopress/page.rb#L212-L221
|
14,941
|
poise/poise-python
|
lib/poise_python/utils.rb
|
PoisePython.Utils.module_to_path
|
def module_to_path(mod, base=nil)
path = mod.gsub(/\./, ::File::SEPARATOR) + '.py'
path = ::File.join(base, path) if base
path
end
|
ruby
|
def module_to_path(mod, base=nil)
path = mod.gsub(/\./, ::File::SEPARATOR) + '.py'
path = ::File.join(base, path) if base
path
end
|
[
"def",
"module_to_path",
"(",
"mod",
",",
"base",
"=",
"nil",
")",
"path",
"=",
"mod",
".",
"gsub",
"(",
"/",
"\\.",
"/",
",",
"::",
"File",
"::",
"SEPARATOR",
")",
"+",
"'.py'",
"path",
"=",
"::",
"File",
".",
"join",
"(",
"base",
",",
"path",
")",
"if",
"base",
"path",
"end"
] |
Convert a Python dotted module name to a path.
@param mod [String] Dotted module name.
@param base [String] Optional base path to treat the file as relative to.
@return [String]
|
[
"Convert",
"a",
"Python",
"dotted",
"module",
"name",
"to",
"a",
"path",
"."
] |
eeb0fc0ee50e8baef15ab4f91601994e5b40a272
|
https://github.com/poise/poise-python/blob/eeb0fc0ee50e8baef15ab4f91601994e5b40a272/lib/poise_python/utils.rb#L57-L61
|
14,942
|
socketry/nio4r
|
lib/nio/selector.rb
|
NIO.Selector.deregister
|
def deregister(io)
@lock.synchronize do
monitor = @selectables.delete IO.try_convert(io)
monitor.close(false) if monitor && !monitor.closed?
monitor
end
end
|
ruby
|
def deregister(io)
@lock.synchronize do
monitor = @selectables.delete IO.try_convert(io)
monitor.close(false) if monitor && !monitor.closed?
monitor
end
end
|
[
"def",
"deregister",
"(",
"io",
")",
"@lock",
".",
"synchronize",
"do",
"monitor",
"=",
"@selectables",
".",
"delete",
"IO",
".",
"try_convert",
"(",
"io",
")",
"monitor",
".",
"close",
"(",
"false",
")",
"if",
"monitor",
"&&",
"!",
"monitor",
".",
"closed?",
"monitor",
"end",
"end"
] |
Deregister the given IO object from the selector
|
[
"Deregister",
"the",
"given",
"IO",
"object",
"from",
"the",
"selector"
] |
2ec5fcadd8564deb57b9dc47a2073bd7c86c906f
|
https://github.com/socketry/nio4r/blob/2ec5fcadd8564deb57b9dc47a2073bd7c86c906f/lib/nio/selector.rb#L65-L71
|
14,943
|
socketry/nio4r
|
lib/nio/selector.rb
|
NIO.Selector.select
|
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
|
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
|
[
"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"
] |
Select which monitors are ready
|
[
"Select",
"which",
"monitors",
"are",
"ready"
] |
2ec5fcadd8564deb57b9dc47a2073bd7c86c906f
|
https://github.com/socketry/nio4r/blob/2ec5fcadd8564deb57b9dc47a2073bd7c86c906f/lib/nio/selector.rb#L79-L120
|
14,944
|
socketry/nio4r
|
lib/nio/bytebuffer.rb
|
NIO.ByteBuffer.position=
|
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
|
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
|
[
"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"
] |
Set the position to the given value. New position must be less than limit.
Preserves mark if it's less than the new position, otherwise clears it.
@param new_position [Integer] position in the buffer
@raise [ArgumentError] new position was invalid
|
[
"Set",
"the",
"position",
"to",
"the",
"given",
"value",
".",
"New",
"position",
"must",
"be",
"less",
"than",
"limit",
".",
"Preserves",
"mark",
"if",
"it",
"s",
"less",
"than",
"the",
"new",
"position",
"otherwise",
"clears",
"it",
"."
] |
2ec5fcadd8564deb57b9dc47a2073bd7c86c906f
|
https://github.com/socketry/nio4r/blob/2ec5fcadd8564deb57b9dc47a2073bd7c86c906f/lib/nio/bytebuffer.rb#L47-L53
|
14,945
|
socketry/nio4r
|
lib/nio/bytebuffer.rb
|
NIO.ByteBuffer.limit=
|
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
|
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
|
[
"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"
] |
Set the limit to the given value. New limit must be less than capacity.
Preserves limit and mark if they're less than the new limit, otherwise
sets position to the new limit and clears the mark.
@param new_limit [Integer] position in the buffer
@raise [ArgumentError] new limit was invalid
|
[
"Set",
"the",
"limit",
"to",
"the",
"given",
"value",
".",
"New",
"limit",
"must",
"be",
"less",
"than",
"capacity",
".",
"Preserves",
"limit",
"and",
"mark",
"if",
"they",
"re",
"less",
"than",
"the",
"new",
"limit",
"otherwise",
"sets",
"position",
"to",
"the",
"new",
"limit",
"and",
"clears",
"the",
"mark",
"."
] |
2ec5fcadd8564deb57b9dc47a2073bd7c86c906f
|
https://github.com/socketry/nio4r/blob/2ec5fcadd8564deb57b9dc47a2073bd7c86c906f/lib/nio/bytebuffer.rb#L62-L69
|
14,946
|
socketry/nio4r
|
lib/nio/bytebuffer.rb
|
NIO.ByteBuffer.get
|
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
|
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
|
[
"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"
] |
Obtain the requested number of bytes from the buffer, advancing the position.
If no length is given, all remaining bytes are consumed.
@raise [NIO::ByteBuffer::UnderflowError] not enough data remaining in buffer
@return [String] bytes read from buffer
|
[
"Obtain",
"the",
"requested",
"number",
"of",
"bytes",
"from",
"the",
"buffer",
"advancing",
"the",
"position",
".",
"If",
"no",
"length",
"is",
"given",
"all",
"remaining",
"bytes",
"are",
"consumed",
"."
] |
2ec5fcadd8564deb57b9dc47a2073bd7c86c906f
|
https://github.com/socketry/nio4r/blob/2ec5fcadd8564deb57b9dc47a2073bd7c86c906f/lib/nio/bytebuffer.rb#L91-L98
|
14,947
|
socketry/nio4r
|
lib/nio/bytebuffer.rb
|
NIO.ByteBuffer.put
|
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
|
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
|
[
"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"
] |
Add a String to the buffer
@param str [#to_str] data to add to the buffer
@raise [TypeError] given a non-string type
@raise [NIO::ByteBuffer::OverflowError] buffer is full
@return [self]
|
[
"Add",
"a",
"String",
"to",
"the",
"buffer"
] |
2ec5fcadd8564deb57b9dc47a2073bd7c86c906f
|
https://github.com/socketry/nio4r/blob/2ec5fcadd8564deb57b9dc47a2073bd7c86c906f/lib/nio/bytebuffer.rb#L120-L128
|
14,948
|
socketry/nio4r
|
lib/nio/bytebuffer.rb
|
NIO.ByteBuffer.read_from
|
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
|
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
|
[
"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"
] |
Perform a non-blocking read from the given IO object into the buffer
Reads as much data as is immediately available and returns
@param [IO] Ruby IO object to read from
@return [Integer] number of bytes read (0 if none were available)
|
[
"Perform",
"a",
"non",
"-",
"blocking",
"read",
"from",
"the",
"given",
"IO",
"object",
"into",
"the",
"buffer",
"Reads",
"as",
"much",
"data",
"as",
"is",
"immediately",
"available",
"and",
"returns"
] |
2ec5fcadd8564deb57b9dc47a2073bd7c86c906f
|
https://github.com/socketry/nio4r/blob/2ec5fcadd8564deb57b9dc47a2073bd7c86c906f/lib/nio/bytebuffer.rb#L137-L146
|
14,949
|
RubyMoney/eu_central_bank
|
lib/money/rates_store/store_with_historical_data_support.rb
|
Money::RatesStore.StoreWithHistoricalDataSupport.transaction
|
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
|
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
|
[
"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"
] |
Wraps block execution in a thread-safe transaction
|
[
"Wraps",
"block",
"execution",
"in",
"a",
"thread",
"-",
"safe",
"transaction"
] |
63487df637c66f4cce3f04683dba23b423304a5d
|
https://github.com/RubyMoney/eu_central_bank/blob/63487df637c66f4cce3f04683dba23b423304a5d/lib/money/rates_store/store_with_historical_data_support.rb#L14-L33
|
14,950
|
savonrb/httpi
|
lib/httpi/request.rb
|
HTTPI.Request.query=
|
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
|
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
|
[
"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"
] |
Sets the +query+ from +url+. Raises an +ArgumentError+ unless the +url+ is valid.
|
[
"Sets",
"the",
"+",
"query",
"+",
"from",
"+",
"url",
"+",
".",
"Raises",
"an",
"+",
"ArgumentError",
"+",
"unless",
"the",
"+",
"url",
"+",
"is",
"valid",
"."
] |
2fbd6b14a0a04ed21572251580a9a4c987396e4b
|
https://github.com/savonrb/httpi/blob/2fbd6b14a0a04ed21572251580a9a4c987396e4b/lib/httpi/request.rb#L35-L42
|
14,951
|
savonrb/httpi
|
lib/httpi/request.rb
|
HTTPI.Request.mass_assign
|
def mass_assign(args)
ATTRIBUTES.each { |key| send("#{key}=", args[key]) if args[key] }
end
|
ruby
|
def mass_assign(args)
ATTRIBUTES.each { |key| send("#{key}=", args[key]) if args[key] }
end
|
[
"def",
"mass_assign",
"(",
"args",
")",
"ATTRIBUTES",
".",
"each",
"{",
"|",
"key",
"|",
"send",
"(",
"\"#{key}=\"",
",",
"args",
"[",
"key",
"]",
")",
"if",
"args",
"[",
"key",
"]",
"}",
"end"
] |
Expects a Hash of +args+ to assign.
|
[
"Expects",
"a",
"Hash",
"of",
"+",
"args",
"+",
"to",
"assign",
"."
] |
2fbd6b14a0a04ed21572251580a9a4c987396e4b
|
https://github.com/savonrb/httpi/blob/2fbd6b14a0a04ed21572251580a9a4c987396e4b/lib/httpi/request.rb#L122-L124
|
14,952
|
savonrb/httpi
|
lib/httpi/request.rb
|
HTTPI.Request.normalize_url!
|
def normalize_url!(url)
raise ArgumentError, "Invalid URL: #{url}" unless url.to_s =~ /^http|socks/
url.kind_of?(URI) ? url : URI(url)
end
|
ruby
|
def normalize_url!(url)
raise ArgumentError, "Invalid URL: #{url}" unless url.to_s =~ /^http|socks/
url.kind_of?(URI) ? url : URI(url)
end
|
[
"def",
"normalize_url!",
"(",
"url",
")",
"raise",
"ArgumentError",
",",
"\"Invalid URL: #{url}\"",
"unless",
"url",
".",
"to_s",
"=~",
"/",
"/",
"url",
".",
"kind_of?",
"(",
"URI",
")",
"?",
"url",
":",
"URI",
"(",
"url",
")",
"end"
] |
Expects a +url+, validates its validity and returns a +URI+ object.
|
[
"Expects",
"a",
"+",
"url",
"+",
"validates",
"its",
"validity",
"and",
"returns",
"a",
"+",
"URI",
"+",
"object",
"."
] |
2fbd6b14a0a04ed21572251580a9a4c987396e4b
|
https://github.com/savonrb/httpi/blob/2fbd6b14a0a04ed21572251580a9a4c987396e4b/lib/httpi/request.rb#L148-L151
|
14,953
|
savonrb/httpi
|
lib/httpi/dime.rb
|
HTTPI.Dime.configure_record
|
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
|
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
|
[
"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"
] |
Shift out bitfields for the first fields.
|
[
"Shift",
"out",
"bitfields",
"for",
"the",
"first",
"fields",
"."
] |
2fbd6b14a0a04ed21572251580a9a4c987396e4b
|
https://github.com/savonrb/httpi/blob/2fbd6b14a0a04ed21572251580a9a4c987396e4b/lib/httpi/dime.rb#L29-L38
|
14,954
|
savonrb/httpi
|
lib/httpi/dime.rb
|
HTTPI.Dime.big_endian_lengths
|
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
|
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
|
[
"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"
] |
Fetch big-endian lengths.
|
[
"Fetch",
"big",
"-",
"endian",
"lengths",
"."
] |
2fbd6b14a0a04ed21572251580a9a4c987396e4b
|
https://github.com/savonrb/httpi/blob/2fbd6b14a0a04ed21572251580a9a4c987396e4b/lib/httpi/dime.rb#L41-L48
|
14,955
|
savonrb/httpi
|
lib/httpi/dime.rb
|
HTTPI.Dime.read_data
|
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
|
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
|
[
"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"
] |
Read in padded data.
|
[
"Read",
"in",
"padded",
"data",
"."
] |
2fbd6b14a0a04ed21572251580a9a4c987396e4b
|
https://github.com/savonrb/httpi/blob/2fbd6b14a0a04ed21572251580a9a4c987396e4b/lib/httpi/dime.rb#L51-L61
|
14,956
|
savonrb/httpi
|
lib/httpi/response.rb
|
HTTPI.Response.decoded_gzip_body
|
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
|
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
|
[
"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"
] |
Returns the gzip decoded response body.
|
[
"Returns",
"the",
"gzip",
"decoded",
"response",
"body",
"."
] |
2fbd6b14a0a04ed21572251580a9a4c987396e4b
|
https://github.com/savonrb/httpi/blob/2fbd6b14a0a04ed21572251580a9a4c987396e4b/lib/httpi/response.rb#L81-L88
|
14,957
|
savonrb/httpi
|
lib/httpi/response.rb
|
HTTPI.Response.decoded_dime_body
|
def decoded_dime_body(body = nil)
dime = Dime.new(body || raw_body)
self.attachments = dime.binary_records
dime.xml_records.first.data
end
|
ruby
|
def decoded_dime_body(body = nil)
dime = Dime.new(body || raw_body)
self.attachments = dime.binary_records
dime.xml_records.first.data
end
|
[
"def",
"decoded_dime_body",
"(",
"body",
"=",
"nil",
")",
"dime",
"=",
"Dime",
".",
"new",
"(",
"body",
"||",
"raw_body",
")",
"self",
".",
"attachments",
"=",
"dime",
".",
"binary_records",
"dime",
".",
"xml_records",
".",
"first",
".",
"data",
"end"
] |
Returns the DIME decoded response body.
|
[
"Returns",
"the",
"DIME",
"decoded",
"response",
"body",
"."
] |
2fbd6b14a0a04ed21572251580a9a4c987396e4b
|
https://github.com/savonrb/httpi/blob/2fbd6b14a0a04ed21572251580a9a4c987396e4b/lib/httpi/response.rb#L91-L95
|
14,958
|
adhearsion/adhearsion
|
lib/adhearsion/initializer.rb
|
Adhearsion.Initializer.load_lib_folder
|
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
|
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
|
[
"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"
] |
Loads files in application lib folder
@return [Boolean] if files have been loaded (lib folder is configured to not nil and actually exists)
|
[
"Loads",
"files",
"in",
"application",
"lib",
"folder"
] |
73beca70000671fa89dfc056e8c62bd839c5417a
|
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/initializer.rb#L129-L144
|
14,959
|
adhearsion/adhearsion
|
lib/adhearsion/call.rb
|
Adhearsion.Call.tag
|
def tag(label)
abort ArgumentError.new "Tag must be a String or Symbol" unless [String, Symbol].include?(label.class)
@tags << label
end
|
ruby
|
def tag(label)
abort ArgumentError.new "Tag must be a String or Symbol" unless [String, Symbol].include?(label.class)
@tags << label
end
|
[
"def",
"tag",
"(",
"label",
")",
"abort",
"ArgumentError",
".",
"new",
"\"Tag must be a String or Symbol\"",
"unless",
"[",
"String",
",",
"Symbol",
"]",
".",
"include?",
"(",
"label",
".",
"class",
")",
"@tags",
"<<",
"label",
"end"
] |
Tag a call with an arbitrary label
@param [String, Symbol] label String or Symbol with which to tag this call
|
[
"Tag",
"a",
"call",
"with",
"an",
"arbitrary",
"label"
] |
73beca70000671fa89dfc056e8c62bd839c5417a
|
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/call.rb#L139-L142
|
14,960
|
adhearsion/adhearsion
|
lib/adhearsion/call.rb
|
Adhearsion.Call.wait_for_end
|
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
|
def wait_for_end(timeout = nil)
if end_reason
end_reason
else
@end_blocker.wait(timeout)
end
rescue Celluloid::ConditionError => e
abort e
end
|
[
"def",
"wait_for_end",
"(",
"timeout",
"=",
"nil",
")",
"if",
"end_reason",
"end_reason",
"else",
"@end_blocker",
".",
"wait",
"(",
"timeout",
")",
"end",
"rescue",
"Celluloid",
"::",
"ConditionError",
"=>",
"e",
"abort",
"e",
"end"
] |
Wait for the call to end. Returns immediately if the call has already ended, else blocks until it does so.
@param [Integer, nil] timeout a timeout after which to unblock, returning `:timeout`
@return [Symbol] the reason for the call ending
@raises [Celluloid::ConditionError] in case of a specified timeout expiring
|
[
"Wait",
"for",
"the",
"call",
"to",
"end",
".",
"Returns",
"immediately",
"if",
"the",
"call",
"has",
"already",
"ended",
"else",
"blocks",
"until",
"it",
"does",
"so",
"."
] |
73beca70000671fa89dfc056e8c62bd839c5417a
|
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/call.rb#L176-L184
|
14,961
|
adhearsion/adhearsion
|
lib/adhearsion/call.rb
|
Adhearsion.Call.on_joined
|
def on_joined(target = nil, &block)
register_event_handler Adhearsion::Event::Joined, *guards_for_target(target) do |event|
block.call event
end
end
|
ruby
|
def on_joined(target = nil, &block)
register_event_handler Adhearsion::Event::Joined, *guards_for_target(target) do |event|
block.call event
end
end
|
[
"def",
"on_joined",
"(",
"target",
"=",
"nil",
",",
"&",
"block",
")",
"register_event_handler",
"Adhearsion",
"::",
"Event",
"::",
"Joined",
",",
"guards_for_target",
"(",
"target",
")",
"do",
"|",
"event",
"|",
"block",
".",
"call",
"event",
"end",
"end"
] |
Registers a callback for when this call is joined to another call or a mixer
@param [Call, String, Hash, nil] target the target to guard on. May be a Call object, a call ID (String, Hash) or a mixer name (Hash)
@option target [String] call_uri The call ID to guard on
@option target [String] mixer_name The mixer name to guard on
|
[
"Registers",
"a",
"callback",
"for",
"when",
"this",
"call",
"is",
"joined",
"to",
"another",
"call",
"or",
"a",
"mixer"
] |
73beca70000671fa89dfc056e8c62bd839c5417a
|
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/call.rb#L287-L291
|
14,962
|
adhearsion/adhearsion
|
lib/adhearsion/call.rb
|
Adhearsion.Call.on_unjoined
|
def on_unjoined(target = nil, &block)
register_event_handler Adhearsion::Event::Unjoined, *guards_for_target(target), &block
end
|
ruby
|
def on_unjoined(target = nil, &block)
register_event_handler Adhearsion::Event::Unjoined, *guards_for_target(target), &block
end
|
[
"def",
"on_unjoined",
"(",
"target",
"=",
"nil",
",",
"&",
"block",
")",
"register_event_handler",
"Adhearsion",
"::",
"Event",
"::",
"Unjoined",
",",
"guards_for_target",
"(",
"target",
")",
",",
"block",
"end"
] |
Registers a callback for when this call is unjoined from another call or a mixer
@param [Call, String, Hash, nil] target the target to guard on. May be a Call object, a call ID (String, Hash) or a mixer name (Hash)
@option target [String] call_uri The call ID to guard on
@option target [String] mixer_name The mixer name to guard on
|
[
"Registers",
"a",
"callback",
"for",
"when",
"this",
"call",
"is",
"unjoined",
"from",
"another",
"call",
"or",
"a",
"mixer"
] |
73beca70000671fa89dfc056e8c62bd839c5417a
|
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/call.rb#L300-L302
|
14,963
|
adhearsion/adhearsion
|
lib/adhearsion/call.rb
|
Adhearsion.Call.redirect
|
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
|
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
|
[
"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"
] |
Redirect the call to some other target system.
If the redirect is successful, the call will be released from the
telephony engine and Adhearsion will lose control of the call.
Note that for the common case, this will result in a SIP 302 or
SIP REFER, which provides the caller with a new URI to dial. As such,
the redirect target cannot be any telephony-engine specific address
(such as sofia/gateway, agent/101, or SIP/mypeer); instead it should be a
fully-qualified external SIP URI that the caller can independently reach.
@param [String] to the target to redirect to, eg a SIP URI
@param [Hash, optional] headers a set of headers to send along with the redirect instruction
|
[
"Redirect",
"the",
"call",
"to",
"some",
"other",
"target",
"system",
"."
] |
73beca70000671fa89dfc056e8c62bd839c5417a
|
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/call.rb#L354-L358
|
14,964
|
adhearsion/adhearsion
|
lib/adhearsion/call.rb
|
Adhearsion.Call.join
|
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
|
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
|
[
"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"
] |
Joins this call to another call or a mixer
@param [Call, String, Hash] target the target to join to. May be a Call object, a call ID (String, Hash) or a mixer name (Hash)
@option target [String] call_uri The call ID to join to
@option target [String] mixer_name The mixer to join to
@param [Hash, Optional] options further options to be joined with
@return [Hash] where :command is the issued command, :joined_waiter is a #wait responder which is triggered when the join is complete, and :unjoined_waiter is a #wait responder which is triggered when the entities are unjoined
|
[
"Joins",
"this",
"call",
"to",
"another",
"call",
"or",
"a",
"mixer"
] |
73beca70000671fa89dfc056e8c62bd839c5417a
|
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/call.rb#L384-L407
|
14,965
|
adhearsion/adhearsion
|
lib/adhearsion/call.rb
|
Adhearsion.Call.unjoin
|
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
|
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
|
[
"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"
] |
Unjoins this call from another call or a mixer
@param [Call, String, Hash, nil] target the target to unjoin from. May be a Call object, a call ID (String, Hash), a mixer name (Hash) or missing to unjoin from every existing join (nil)
@option target [String] call_uri The call ID to unjoin from
@option target [String] mixer_name The mixer to unjoin from
|
[
"Unjoins",
"this",
"call",
"from",
"another",
"call",
"or",
"a",
"mixer"
] |
73beca70000671fa89dfc056e8c62bd839c5417a
|
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/call.rb#L416-L422
|
14,966
|
adhearsion/adhearsion
|
lib/adhearsion/call.rb
|
Adhearsion.Call.send_message
|
def send_message(body, options = {})
logger.debug "Sending message: #{body}"
client.send_message id, domain, body, options
end
|
ruby
|
def send_message(body, options = {})
logger.debug "Sending message: #{body}"
client.send_message id, domain, body, options
end
|
[
"def",
"send_message",
"(",
"body",
",",
"options",
"=",
"{",
"}",
")",
"logger",
".",
"debug",
"\"Sending message: #{body}\"",
"client",
".",
"send_message",
"id",
",",
"domain",
",",
"body",
",",
"options",
"end"
] |
Sends a message to the caller
@param [String] body The message text.
@param [Hash, Optional] options The message options.
@option options [String] subject The message subject.
|
[
"Sends",
"a",
"message",
"to",
"the",
"caller"
] |
73beca70000671fa89dfc056e8c62bd839c5417a
|
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/call.rb#L535-L538
|
14,967
|
adhearsion/adhearsion
|
lib/adhearsion/call.rb
|
Adhearsion.Call.execute_controller
|
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
|
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
|
[
"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"
] |
Execute a call controller asynchronously against this call.
To block and wait until the controller completes, call `#join` on the result of this method.
@param [Adhearsion::CallController] controller an instance of a controller initialized for this call
@param [Proc] a callback to be executed when the controller finishes execution
@yield execute the current block as the body of a controller by specifying no controller instance
@return [Celluloid::ThreadHandle]
|
[
"Execute",
"a",
"call",
"controller",
"asynchronously",
"against",
"this",
"call",
"."
] |
73beca70000671fa89dfc056e8c62bd839c5417a
|
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/call.rb#L565-L570
|
14,968
|
adhearsion/adhearsion
|
lib/adhearsion/statistics.rb
|
Adhearsion.Statistics.dump
|
def dump
Dump.new timestamp: Time.now, call_counts: dump_call_counts, calls_by_route: dump_calls_by_route
end
|
ruby
|
def dump
Dump.new timestamp: Time.now, call_counts: dump_call_counts, calls_by_route: dump_calls_by_route
end
|
[
"def",
"dump",
"Dump",
".",
"new",
"timestamp",
":",
"Time",
".",
"now",
",",
"call_counts",
":",
"dump_call_counts",
",",
"calls_by_route",
":",
"dump_calls_by_route",
"end"
] |
Create a point-time dump of process statistics
@return [Adhearsion::Statistics::Dump]
|
[
"Create",
"a",
"point",
"-",
"time",
"dump",
"of",
"process",
"statistics"
] |
73beca70000671fa89dfc056e8c62bd839c5417a
|
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/statistics.rb#L53-L55
|
14,969
|
adhearsion/adhearsion
|
lib/adhearsion/call_controller.rb
|
Adhearsion.CallController.invoke
|
def invoke(controller_class, metadata = nil)
controller = controller_class.new call, metadata
controller.run
end
|
ruby
|
def invoke(controller_class, metadata = nil)
controller = controller_class.new call, metadata
controller.run
end
|
[
"def",
"invoke",
"(",
"controller_class",
",",
"metadata",
"=",
"nil",
")",
"controller",
"=",
"controller_class",
".",
"new",
"call",
",",
"metadata",
"controller",
".",
"run",
"end"
] |
Invoke another controller class within this controller, returning to this context on completion.
@param [Class] controller_class The class of controller to execute
@param [Hash] metadata generic key-value storage applicable to the controller
@return The return value of the controller's run method
|
[
"Invoke",
"another",
"controller",
"class",
"within",
"this",
"controller",
"returning",
"to",
"this",
"context",
"on",
"completion",
"."
] |
73beca70000671fa89dfc056e8c62bd839c5417a
|
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/call_controller.rb#L151-L154
|
14,970
|
adhearsion/adhearsion
|
lib/adhearsion/call_controller.rb
|
Adhearsion.CallController.stop_all_components
|
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
|
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
|
[
"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"
] |
Stop execution of all the components currently running in the controller.
|
[
"Stop",
"execution",
"of",
"all",
"the",
"components",
"currently",
"running",
"in",
"the",
"controller",
"."
] |
73beca70000671fa89dfc056e8c62bd839c5417a
|
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/call_controller.rb#L169-L177
|
14,971
|
adhearsion/adhearsion
|
lib/adhearsion/configuration.rb
|
Adhearsion.Configuration.method_missing
|
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
|
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
|
[
"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"
] |
Wrapper to access to a specific configuration object
Adhearsion.config.foo => returns the configuration object associated to the foo plugin
|
[
"Wrapper",
"to",
"access",
"to",
"a",
"specific",
"configuration",
"object"
] |
73beca70000671fa89dfc056e8c62bd839c5417a
|
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/configuration.rb#L147-L151
|
14,972
|
adhearsion/adhearsion
|
lib/adhearsion/console.rb
|
Adhearsion.Console.run
|
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
|
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
|
[
"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"
] |
Start the Adhearsion console
|
[
"Start",
"the",
"Adhearsion",
"console"
] |
73beca70000671fa89dfc056e8c62bd839c5417a
|
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/console.rb#L33-L44
|
14,973
|
adhearsion/adhearsion
|
lib/adhearsion/outbound_call.rb
|
Adhearsion.OutboundCall.dial
|
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
|
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
|
[
"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"
] |
Dial out an existing outbound call
@param [String] to the URI of the party to dial
@param [Hash] options modifier options
@option options [String, Optional] :from what to set the Caller ID to
@option options [Integer, Optional] :timeout in seconds
@option options [Hash, Optional] :headers SIP headers to attach to
the new call.
|
[
"Dial",
"out",
"an",
"existing",
"outbound",
"call"
] |
73beca70000671fa89dfc056e8c62bd839c5417a
|
https://github.com/adhearsion/adhearsion/blob/73beca70000671fa89dfc056e8c62bd839c5417a/lib/adhearsion/outbound_call.rb#L74-L108
|
14,974
|
sass/ruby-sass
|
lib/sass/tree/rule_node.rb
|
Sass::Tree.RuleNode.add_rules
|
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
|
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
|
[
"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"
] |
Compares the contents of two rules.
@param other [Object] The object to compare with
@return [Boolean] Whether or not this node and the other object
are the same
Adds another {RuleNode}'s rules to this one's.
@param node [RuleNode] The other node
|
[
"Compares",
"the",
"contents",
"of",
"two",
"rules",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/tree/rule_node.rb#L104-L108
|
14,975
|
sass/ruby-sass
|
lib/sass/util.rb
|
Sass.Util.map_vals
|
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
|
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
|
[
"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"
] |
Maps the values in a hash according to a block.
@example
map_values({:foo => "bar", :baz => "bang"}) {|v| v.to_sym}
#=> {:foo => :bar, :baz => :bang}
@param hash [Hash] The hash to map
@yield [value] A block in which the values are transformed
@yieldparam value [Object] The value that should be mapped
@yieldreturn [Object] The new value for the value
@return [Hash] The mapped hash
@see #map_keys
@see #map_hash
|
[
"Maps",
"the",
"values",
"in",
"a",
"hash",
"according",
"to",
"a",
"block",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/util.rb#L64-L73
|
14,976
|
sass/ruby-sass
|
lib/sass/util.rb
|
Sass.Util.map_hash
|
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
|
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
|
[
"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"
] |
Maps the key-value pairs of a hash according to a block.
@example
map_hash({:foo => "bar", :baz => "bang"}) {|k, v| [k.to_s, v.to_sym]}
#=> {"foo" => :bar, "baz" => :bang}
@param hash [Hash] The hash to map
@yield [key, value] A block in which the key-value pairs are transformed
@yieldparam [key] The hash key
@yieldparam [value] The hash value
@yieldreturn [(Object, Object)] The new value for the `[key, value]` pair
@return [Hash] The mapped hash
@see #map_keys
@see #map_vals
|
[
"Maps",
"the",
"key",
"-",
"value",
"pairs",
"of",
"a",
"hash",
"according",
"to",
"a",
"block",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/util.rb#L88-L98
|
14,977
|
sass/ruby-sass
|
lib/sass/util.rb
|
Sass.Util.powerset
|
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
|
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
|
[
"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"
] |
Computes the powerset of the given array.
This is the set of all subsets of the array.
@example
powerset([1, 2, 3]) #=>
Set[Set[], Set[1], Set[2], Set[3], Set[1, 2], Set[2, 3], Set[1, 3], Set[1, 2, 3]]
@param arr [Enumerable]
@return [Set<Set>] The subsets of `arr`
|
[
"Computes",
"the",
"powerset",
"of",
"the",
"given",
"array",
".",
"This",
"is",
"the",
"set",
"of",
"all",
"subsets",
"of",
"the",
"array",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/util.rb#L108-L117
|
14,978
|
sass/ruby-sass
|
lib/sass/util.rb
|
Sass.Util.restrict
|
def restrict(value, range)
[[value, range.first].max, range.last].min
end
|
ruby
|
def restrict(value, range)
[[value, range.first].max, range.last].min
end
|
[
"def",
"restrict",
"(",
"value",
",",
"range",
")",
"[",
"[",
"value",
",",
"range",
".",
"first",
"]",
".",
"max",
",",
"range",
".",
"last",
"]",
".",
"min",
"end"
] |
Restricts a number to falling within a given range.
Returns the number if it falls within the range,
or the closest value in the range if it doesn't.
@param value [Numeric]
@param range [Range<Numeric>]
@return [Numeric]
|
[
"Restricts",
"a",
"number",
"to",
"falling",
"within",
"a",
"given",
"range",
".",
"Returns",
"the",
"number",
"if",
"it",
"falls",
"within",
"the",
"range",
"or",
"the",
"closest",
"value",
"in",
"the",
"range",
"if",
"it",
"doesn",
"t",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/util.rb#L126-L128
|
14,979
|
sass/ruby-sass
|
lib/sass/util.rb
|
Sass.Util.merge_adjacent_strings
|
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
|
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
|
[
"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"
] |
Concatenates all strings that are adjacent in an array,
while leaving other elements as they are.
@example
merge_adjacent_strings([1, "foo", "bar", 2, "baz"])
#=> [1, "foobar", 2, "baz"]
@param arr [Array]
@return [Array] The enumerable with strings merged
|
[
"Concatenates",
"all",
"strings",
"that",
"are",
"adjacent",
"in",
"an",
"array",
"while",
"leaving",
"other",
"elements",
"as",
"they",
"are",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/util.rb#L155-L170
|
14,980
|
sass/ruby-sass
|
lib/sass/util.rb
|
Sass.Util.replace_subseq
|
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
|
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
|
[
"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"
] |
Non-destructively replaces all occurrences of a subsequence in an array
with another subsequence.
@example
replace_subseq([1, 2, 3, 4, 5], [2, 3], [:a, :b])
#=> [1, :a, :b, 4, 5]
@param arr [Array] The array whose subsequences will be replaced.
@param subseq [Array] The subsequence to find and replace.
@param replacement [Array] The sequence that `subseq` will be replaced with.
@return [Array] `arr` with `subseq` replaced with `replacement`.
|
[
"Non",
"-",
"destructively",
"replaces",
"all",
"occurrences",
"of",
"a",
"subsequence",
"in",
"an",
"array",
"with",
"another",
"subsequence",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/util.rb#L183-L207
|
14,981
|
sass/ruby-sass
|
lib/sass/util.rb
|
Sass.Util.substitute
|
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
|
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
|
[
"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"
] |
Substitutes a sub-array of one array with another sub-array.
@param ary [Array] The array in which to make the substitution
@param from [Array] The sequence of elements to replace with `to`
@param to [Array] The sequence of elements to replace `from` with
|
[
"Substitutes",
"a",
"sub",
"-",
"array",
"of",
"one",
"array",
"with",
"another",
"sub",
"-",
"array",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/util.rb#L237-L247
|
14,982
|
sass/ruby-sass
|
lib/sass/util.rb
|
Sass.Util.paths
|
def paths(arrs)
arrs.inject([[]]) do |paths, arr|
arr.map {|e| paths.map {|path| path + [e]}}.flatten(1)
end
end
|
ruby
|
def paths(arrs)
arrs.inject([[]]) do |paths, arr|
arr.map {|e| paths.map {|path| path + [e]}}.flatten(1)
end
end
|
[
"def",
"paths",
"(",
"arrs",
")",
"arrs",
".",
"inject",
"(",
"[",
"[",
"]",
"]",
")",
"do",
"|",
"paths",
",",
"arr",
"|",
"arr",
".",
"map",
"{",
"|",
"e",
"|",
"paths",
".",
"map",
"{",
"|",
"path",
"|",
"path",
"+",
"[",
"e",
"]",
"}",
"}",
".",
"flatten",
"(",
"1",
")",
"end",
"end"
] |
Return an array of all possible paths through the given arrays.
@param arrs [Array<Array>]
@return [Array<Arrays>]
@example
paths([[1, 2], [3, 4], [5]]) #=>
# [[1, 3, 5],
# [2, 3, 5],
# [1, 4, 5],
# [2, 4, 5]]
|
[
"Return",
"an",
"array",
"of",
"all",
"possible",
"paths",
"through",
"the",
"given",
"arrays",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/util.rb#L321-L325
|
14,983
|
sass/ruby-sass
|
lib/sass/util.rb
|
Sass.Util.lcs
|
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
|
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
|
[
"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"
] |
Computes a single longest common subsequence for `x` and `y`.
If there are more than one longest common subsequences,
the one returned is that which starts first in `x`.
@param x [Array]
@param y [Array]
@yield [a, b] An optional block to use in place of a check for equality
between elements of `x` and `y`.
@yieldreturn [Object, nil] If the two values register as equal,
this will return the value to use in the LCS array.
@return [Array] The LCS
|
[
"Computes",
"a",
"single",
"longest",
"common",
"subsequence",
"for",
"x",
"and",
"y",
".",
"If",
"there",
"are",
"more",
"than",
"one",
"longest",
"common",
"subsequences",
"the",
"one",
"returned",
"is",
"that",
"which",
"starts",
"first",
"in",
"x",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/util.rb#L338-L343
|
14,984
|
sass/ruby-sass
|
lib/sass/util.rb
|
Sass.Util.caller_info
|
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
|
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
|
[
"def",
"caller_info",
"(",
"entry",
"=",
"nil",
")",
"# JRuby evaluates `caller` incorrectly when it's in an actual default argument.",
"entry",
"||=",
"caller",
"[",
"1",
"]",
"info",
"=",
"entry",
".",
"scan",
"(",
"/",
"/",
")",
".",
"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"
] |
Returns information about the caller of the previous method.
@param entry [String] An entry in the `#caller` list, or a similarly formatted string
@return [[String, Integer, (String, nil)]]
An array containing the filename, line, and method name of the caller.
The method name may be nil
|
[
"Returns",
"information",
"about",
"the",
"caller",
"of",
"the",
"previous",
"method",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/util.rb#L439-L447
|
14,985
|
sass/ruby-sass
|
lib/sass/util.rb
|
Sass.Util.version_gt
|
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
|
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
|
[
"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",
"=~",
"/",
"/",
"release2",
"=",
"p2",
"=~",
"/",
"/",
"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"
] |
Returns whether one version string represents a more recent version than another.
@param v1 [String] A version string.
@param v2 [String] Another version string.
@return [Boolean]
|
[
"Returns",
"whether",
"one",
"version",
"string",
"represents",
"a",
"more",
"recent",
"version",
"than",
"another",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/util.rb#L454-L475
|
14,986
|
sass/ruby-sass
|
lib/sass/util.rb
|
Sass.Util.deprecated
|
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
|
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
|
[
"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"
] |
Prints a deprecation warning for the caller method.
@param obj [Object] `self`
@param message [String] A message describing what to do instead.
|
[
"Prints",
"a",
"deprecation",
"warning",
"for",
"the",
"caller",
"method",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/util.rb#L499-L504
|
14,987
|
sass/ruby-sass
|
lib/sass/util.rb
|
Sass.Util.silence_sass_warnings
|
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
|
def silence_sass_warnings
old_level, Sass.logger.log_level = Sass.logger.log_level, :error
yield
ensure
Sass.logger.log_level = old_level
end
|
[
"def",
"silence_sass_warnings",
"old_level",
",",
"Sass",
".",
"logger",
".",
"log_level",
"=",
"Sass",
".",
"logger",
".",
"log_level",
",",
":error",
"yield",
"ensure",
"Sass",
".",
"logger",
".",
"log_level",
"=",
"old_level",
"end"
] |
Silences all Sass warnings within a block.
@yield A block in which no Sass warnings will be printed
|
[
"Silences",
"all",
"Sass",
"warnings",
"within",
"a",
"block",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/util.rb#L509-L514
|
14,988
|
sass/ruby-sass
|
lib/sass/util.rb
|
Sass.Util.rails_root
|
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
|
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
|
[
"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"
] |
Cross Rails Version Compatibility
Returns the root of the Rails application,
if this is running in a Rails context.
Returns `nil` if no such root is defined.
@return [String, nil]
|
[
"Cross",
"Rails",
"Version",
"Compatibility",
"Returns",
"the",
"root",
"of",
"the",
"Rails",
"application",
"if",
"this",
"is",
"running",
"in",
"a",
"Rails",
"context",
".",
"Returns",
"nil",
"if",
"no",
"such",
"root",
"is",
"defined",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/util.rb#L530-L537
|
14,989
|
sass/ruby-sass
|
lib/sass/util.rb
|
Sass.Util.ap_geq?
|
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
|
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
|
[
"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"
] |
Returns whether this environment is using ActionPack
of a version greater than or equal to that specified.
@param version [String] The string version number to check against.
Should be greater than or equal to Rails 3,
because otherwise ActionPack::VERSION isn't autoloaded
@return [Boolean]
|
[
"Returns",
"whether",
"this",
"environment",
"is",
"using",
"ActionPack",
"of",
"a",
"version",
"greater",
"than",
"or",
"equal",
"to",
"that",
"specified",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/util.rb#L565-L571
|
14,990
|
sass/ruby-sass
|
lib/sass/util.rb
|
Sass.Util.glob
|
def glob(path)
path = path.tr('\\', '/') if windows?
if block_given?
Dir.glob(path) {|f| yield(f)}
else
Dir.glob(path)
end
end
|
ruby
|
def glob(path)
path = path.tr('\\', '/') if windows?
if block_given?
Dir.glob(path) {|f| yield(f)}
else
Dir.glob(path)
end
end
|
[
"def",
"glob",
"(",
"path",
")",
"path",
"=",
"path",
".",
"tr",
"(",
"'\\\\'",
",",
"'/'",
")",
"if",
"windows?",
"if",
"block_given?",
"Dir",
".",
"glob",
"(",
"path",
")",
"{",
"|",
"f",
"|",
"yield",
"(",
"f",
")",
"}",
"else",
"Dir",
".",
"glob",
"(",
"path",
")",
"end",
"end"
] |
Like `Dir.glob`, but works with backslash-separated paths on Windows.
@param path [String]
|
[
"Like",
"Dir",
".",
"glob",
"but",
"works",
"with",
"backslash",
"-",
"separated",
"paths",
"on",
"Windows",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/util.rb#L633-L640
|
14,991
|
sass/ruby-sass
|
lib/sass/util.rb
|
Sass.Util.realpath
|
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
|
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
|
[
"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"
] |
Returns `path` with all symlinks resolved.
@param path [String, Pathname]
@return [Pathname]
|
[
"Returns",
"path",
"with",
"all",
"symlinks",
"resolved",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/util.rb#L671-L685
|
14,992
|
sass/ruby-sass
|
lib/sass/util.rb
|
Sass.Util.relative_path_from
|
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
|
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
|
[
"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"
] |
Returns `path` relative to `from`.
This is like `Pathname#relative_path_from` except it accepts both strings
and pathnames, it handles Windows path separators correctly, and it throws
an error rather than crashing if the paths use different encodings
(https://github.com/ruby/ruby/pull/713).
@param path [String, Pathname]
@param from [String, Pathname]
@return [Pathname?]
|
[
"Returns",
"path",
"relative",
"to",
"from",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/util.rb#L697-L707
|
14,993
|
sass/ruby-sass
|
lib/sass/util.rb
|
Sass.Util.extract!
|
def extract!(array)
out = []
array.reject! do |e|
next false unless yield e
out << e
true
end
out
end
|
ruby
|
def extract!(array)
out = []
array.reject! do |e|
next false unless yield e
out << e
true
end
out
end
|
[
"def",
"extract!",
"(",
"array",
")",
"out",
"=",
"[",
"]",
"array",
".",
"reject!",
"do",
"|",
"e",
"|",
"next",
"false",
"unless",
"yield",
"e",
"out",
"<<",
"e",
"true",
"end",
"out",
"end"
] |
Destructively removes all elements from an array that match a block, and
returns the removed elements.
@param array [Array] The array from which to remove elements.
@yield [el] Called for each element.
@yieldparam el [*] The element to test.
@yieldreturn [Boolean] Whether or not to extract the element.
@return [Array] The extracted elements.
|
[
"Destructively",
"removes",
"all",
"elements",
"from",
"an",
"array",
"that",
"match",
"a",
"block",
"and",
"returns",
"the",
"removed",
"elements",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/util.rb#L832-L840
|
14,994
|
sass/ruby-sass
|
lib/sass/util.rb
|
Sass.Util.with_extracted_values
|
def with_extracted_values(arr)
str, vals = extract_values(arr)
str = yield str
inject_values(str, vals)
end
|
ruby
|
def with_extracted_values(arr)
str, vals = extract_values(arr)
str = yield str
inject_values(str, vals)
end
|
[
"def",
"with_extracted_values",
"(",
"arr",
")",
"str",
",",
"vals",
"=",
"extract_values",
"(",
"arr",
")",
"str",
"=",
"yield",
"str",
"inject_values",
"(",
"str",
",",
"vals",
")",
"end"
] |
Allows modifications to be performed on the string form
of an array containing both strings and non-strings.
@param arr [Array] The array from which values are extracted.
@yield [str] A block in which string manipulation can be done to the array.
@yieldparam str [String] The string form of `arr`.
@yieldreturn [String] The modified string.
@return [Array] The modified, interpolated array.
|
[
"Allows",
"modifications",
"to",
"be",
"performed",
"on",
"the",
"string",
"form",
"of",
"an",
"array",
"containing",
"both",
"strings",
"and",
"non",
"-",
"strings",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/util.rb#L920-L924
|
14,995
|
sass/ruby-sass
|
lib/sass/util.rb
|
Sass.Util.json_escape_string
|
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
|
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
|
[
"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"
] |
Escapes certain characters so that the result can be used
as the JSON string value. Returns the original string if
no escaping is necessary.
@param s [String] The string to be escaped
@return [String] The escaped string
|
[
"Escapes",
"certain",
"characters",
"so",
"that",
"the",
"result",
"can",
"be",
"used",
"as",
"the",
"JSON",
"string",
"value",
".",
"Returns",
"the",
"original",
"string",
"if",
"no",
"escaping",
"is",
"necessary",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/util.rb#L940-L958
|
14,996
|
sass/ruby-sass
|
lib/sass/util.rb
|
Sass.Util.json_value_of
|
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
|
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
|
[
"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"
] |
Converts the argument into a valid JSON value.
@param v [Integer, String, Array, Boolean, nil]
@return [String]
|
[
"Converts",
"the",
"argument",
"into",
"a",
"valid",
"JSON",
"value",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/util.rb#L964-L981
|
14,997
|
sass/ruby-sass
|
lib/sass/util.rb
|
Sass.Util.atomic_create_and_write_file
|
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
|
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
|
[
"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"
] |
This creates a temp file and yields it for writing. When the
write is complete, the file is moved into the desired location.
The atomicity of this operation is provided by the filesystem's
rename operation.
@param filename [String] The file to write to.
@param perms [Integer] The permissions used for creating this file.
Will be masked by the process umask. Defaults to readable/writeable
by all users however the umask usually changes this to only be writable
by the process's user.
@yieldparam tmpfile [Tempfile] The temp file that can be written to.
@return The value returned by the block.
|
[
"This",
"creates",
"a",
"temp",
"file",
"and",
"yields",
"it",
"for",
"writing",
".",
"When",
"the",
"write",
"is",
"complete",
"the",
"file",
"is",
"moved",
"into",
"the",
"desired",
"location",
".",
"The",
"atomicity",
"of",
"this",
"operation",
"is",
"provided",
"by",
"the",
"filesystem",
"s",
"rename",
"operation",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/util.rb#L1054-L1075
|
14,998
|
sass/ruby-sass
|
lib/sass/script/value/map.rb
|
Sass::Script::Value.Map.options=
|
def options=(options)
super
value.each do |k, v|
k.options = options
v.options = options
end
end
|
ruby
|
def options=(options)
super
value.each do |k, v|
k.options = options
v.options = options
end
end
|
[
"def",
"options",
"=",
"(",
"options",
")",
"super",
"value",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"k",
".",
"options",
"=",
"options",
"v",
".",
"options",
"=",
"options",
"end",
"end"
] |
Creates a new map.
@param hash [Hash<Node, Node>]
@see Value#options=
|
[
"Creates",
"a",
"new",
"map",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/script/value/map.rb#L19-L25
|
14,999
|
sass/ruby-sass
|
lib/sass/script/tree/node.rb
|
Sass::Script::Tree.Node.perform
|
def perform(environment)
_perform(environment)
rescue Sass::SyntaxError => e
e.modify_backtrace(:line => line)
raise e
end
|
ruby
|
def perform(environment)
_perform(environment)
rescue Sass::SyntaxError => e
e.modify_backtrace(:line => line)
raise e
end
|
[
"def",
"perform",
"(",
"environment",
")",
"_perform",
"(",
"environment",
")",
"rescue",
"Sass",
"::",
"SyntaxError",
"=>",
"e",
"e",
".",
"modify_backtrace",
"(",
":line",
"=>",
"line",
")",
"raise",
"e",
"end"
] |
Evaluates the node.
\{#perform} shouldn't be overridden directly;
instead, override \{#\_perform}.
@param environment [Sass::Environment] The environment in which to evaluate the SassScript
@return [Sass::Script::Value] The SassScript object that is the value of the SassScript
|
[
"Evaluates",
"the",
"node",
"."
] |
7a50eae567260a23d3bbf4d5aaf1a76db43dec32
|
https://github.com/sass/ruby-sass/blob/7a50eae567260a23d3bbf4d5aaf1a76db43dec32/lib/sass/script/tree/node.rb#L49-L54
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.