_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q23200
|
Android.Apk.digest
|
train
|
def digest(type = :sha1)
case type
when :sha1
Digest::SHA1.hexdigest(@bindata)
when :sha256
Digest::SHA256.hexdigest(@bindata)
when :md5
Digest::MD5.hexdigest(@bindata)
else
raise ArgumentError
end
end
|
ruby
|
{
"resource": ""
}
|
q23201
|
Android.Apk.entry
|
train
|
def entry(name)
entry = @zip.find_entry(name)
raise NotFoundError, "'#{name}'" if entry.nil?
return entry
end
|
ruby
|
{
"resource": ""
}
|
q23202
|
Android.Apk.find
|
train
|
def find(&block)
found = []
self.each_file do |name, data|
ret = block.call(name, data)
found << name if ret
end
found
end
|
ruby
|
{
"resource": ""
}
|
q23203
|
Android.Apk.icon
|
train
|
def icon
icon_id = @manifest.doc.elements['/manifest/application'].attributes['icon']
if /^@(\w+\/\w+)|(0x[0-9a-fA-F]{8})$/ =~ icon_id
drawables = @resource.find(icon_id)
Hash[drawables.map {|name| [name, file(name)] }]
else
{ icon_id => file(icon_id) } # ugh!: not tested!!
end
end
|
ruby
|
{
"resource": ""
}
|
q23204
|
Android.Apk.signs
|
train
|
def signs
signs = {}
self.each_file do |path, data|
# find META-INF/xxx.{RSA|DSA}
next unless path =~ /^META-INF\// && data.unpack("CC") == [0x30, 0x82]
signs[path] = OpenSSL::PKCS7.new(data)
end
signs
end
|
ruby
|
{
"resource": ""
}
|
q23205
|
Android.Apk.certificates
|
train
|
def certificates
return Hash[self.signs.map{|path, sign| [path, sign.certificates.first] }]
end
|
ruby
|
{
"resource": ""
}
|
q23206
|
Android.Manifest.version_name
|
train
|
def version_name(lang=nil)
vername = @doc.root.attributes['versionName']
unless @rsc.nil?
if /^@(\w+\/\w+)|(0x[0-9a-fA-F]{8})$/ =~ vername
opts = {}
opts[:lang] = lang unless lang.nil?
vername = @rsc.find(vername, opts)
end
end
vername
end
|
ruby
|
{
"resource": ""
}
|
q23207
|
Android.Manifest.to_xml
|
train
|
def to_xml(indent=4)
xml =''
formatter = REXML::Formatters::Pretty.new(indent)
formatter.write(@doc.root, xml)
xml
end
|
ruby
|
{
"resource": ""
}
|
q23208
|
Android.AXMLParser.parse_attribute
|
train
|
def parse_attribute
ns_id, name_id, val_str_id, flags, val = @io.read(4*5).unpack("V*")
key = @strings[name_id]
unless ns_id == 0xFFFFFFFF
ns = @strings[ns_id]
prefix = ns.sub(/.*\//,'')
unless @ns.include? ns
@ns << ns
@doc.root.add_namespace(prefix, ns)
end
key = "#{prefix}:#{key}"
end
value = convert_value(val_str_id, flags, val)
return key, value
end
|
ruby
|
{
"resource": ""
}
|
q23209
|
PageValidations.HTMLValidation.each_exception
|
train
|
def each_exception
Dir.chdir(@data_folder)
Dir.glob("*.exceptions.txt").each do |file|
if File.open(File.join(@data_folder, file), 'r').read != ''
yield HTMLValidationResult.load_from_files(file.gsub('.exceptions.txt',''))
end
end
end
|
ruby
|
{
"resource": ""
}
|
q23210
|
Rumonade.Monad.map_with_monad
|
train
|
def map_with_monad(lam = nil, &blk)
bind { |v| self.class.unit((lam || blk).call(v)) }
end
|
ruby
|
{
"resource": ""
}
|
q23211
|
Rumonade.Monad.select
|
train
|
def select(lam = nil, &blk)
bind { |x| (lam || blk).call(x) ? self.class.unit(x) : self.class.empty }
end
|
ruby
|
{
"resource": ""
}
|
q23212
|
HMAC.Signer.generate_signature
|
train
|
def generate_signature(params)
secret = params.delete(:secret)
# jruby stumbles over empty secrets, we regard them as invalid anyways, so we return an empty digest if no scret was given
if '' == secret.to_s
nil
else
OpenSSL::HMAC.hexdigest(algorithm, secret, canonical_representation(params))
end
end
|
ruby
|
{
"resource": ""
}
|
q23213
|
HMAC.Signer.validate_url_signature
|
train
|
def validate_url_signature(url, secret, opts = {})
opts = default_opts.merge(opts)
opts[:query_based] = true
uri = parse_url(url)
query_values = Rack::Utils.parse_nested_query(uri.query)
return false unless query_values
auth_params = query_values.delete(opts[:auth_param])
return false unless auth_params
date = auth_params["date"]
nonce = auth_params["nonce"]
validate_signature(auth_params["signature"], :secret => secret, :method => "GET", :path => uri.path, :date => date, :nonce => nonce, :query => query_values, :headers => {})
end
|
ruby
|
{
"resource": ""
}
|
q23214
|
HMAC.Signer.canonical_representation
|
train
|
def canonical_representation(params)
rep = ""
rep << "#{params[:method].upcase}\n"
rep << "date:#{params[:date]}\n"
rep << "nonce:#{params[:nonce]}\n"
(params[:headers] || {}).sort.each do |pair|
name,value = *pair
rep << "#{name.downcase}:#{value}\n"
end
rep << params[:path]
p = (params[:query] || {}).dup
if !p.empty?
query = p.sort.map do |key, value|
"%{key}=%{value}" % {
:key => Rack::Utils.unescape(key.to_s),
:value => Rack::Utils.unescape(value.to_s)
}
end.join("&")
rep << "?#{query}"
end
rep
end
|
ruby
|
{
"resource": ""
}
|
q23215
|
HMAC.Signer.sign_request
|
train
|
def sign_request(url, secret, opts = {})
opts = default_opts.merge(opts)
uri = parse_url(url)
headers = opts[:headers] || {}
date = opts[:date] || Time.now.gmtime
date = date.gmtime.strftime('%a, %d %b %Y %T GMT') if date.respond_to? :strftime
method = opts[:method] ? opts[:method].to_s.upcase : "GET"
query_values = Rack::Utils.parse_nested_query(uri.query)
if query_values
query_values.delete_if do |k,v|
opts[:ignore_params].one? { |param| (k == param) || (k == param.to_s) }
end
end
signature = generate_signature(:secret => secret, :method => method, :path => uri.path, :date => date, :nonce => opts[:nonce], :query => query_values, :headers => opts[:headers], :ignore_params => opts[:ignore_params])
if opts[:query_based]
auth_params = opts[:extra_auth_params].merge({
"date" => date,
"signature" => signature
})
auth_params[:nonce] = opts[:nonce] unless opts[:nonce].nil?
query_values ||= {}
query_values[opts[:auth_param]] = auth_params
uri.query = Rack::Utils.build_nested_query(query_values)
else
headers[opts[:auth_header]] = opts[:auth_header_format] % opts.merge({:signature => signature})
headers[opts[:nonce_header]] = opts[:nonce] unless opts[:nonce].nil?
if opts[:use_alternate_date_header]
headers[opts[:alternate_date_header]] = date
else
headers["Date"] = date
end
end
[headers, uri.to_s]
end
|
ruby
|
{
"resource": ""
}
|
q23216
|
HMAC.Signer.sign_url
|
train
|
def sign_url(url, secret, opts = {})
opts = default_opts.merge(opts)
opts[:query_based] = true
headers, url = *sign_request(url, secret, opts)
url
end
|
ruby
|
{
"resource": ""
}
|
q23217
|
Playful.Device.start
|
train
|
def start
EM.synchrony do
web_server = Thin::Server.start('0.0.0.0', 3000) do
use Rack::CommonLogger
use Rack::ShowExceptions
map '/presentation' do
use Rack::Lint
run Rack::Lobster.new
end
end
# Do advertisement
# Listen for subscribers
end
end
|
ruby
|
{
"resource": ""
}
|
q23218
|
Satyr.Report.stacktrace
|
train
|
def stacktrace
stacktrace = @struct[:stacktrace]
return nil if stacktrace.null?
# There's no sr_stacktrace_dup in libsatyr.so.3, we've got to find out
# the type ourselves.
dup = case @struct[:type]
when :core
Satyr::FFI.sr_core_stacktrace_dup(stacktrace)
when :python
Satyr::FFI.sr_python_stacktrace_dup(stacktrace)
when :kerneloops
Satyr::FFI.sr_koops_stacktrace_dup(stacktrace)
when :java
Satyr::FFI.sr_java_stacktrace_dup(stacktrace)
when :gdb
Satyr::FFI.sr_gdb_stacktrace_dup(stacktrace)
else
raise SatyrError, "Invalid report type"
end
raise SatyrError, "Failed to obtain stacktrace" if dup.null?
Stacktrace.send(:new, dup)
end
|
ruby
|
{
"resource": ""
}
|
q23219
|
Satyr.Stacktrace.find_crash_thread
|
train
|
def find_crash_thread
pointer = Satyr::FFI.sr_stacktrace_find_crash_thread @struct.to_ptr
raise SatyrError, "Could not find crash thread" if pointer.null?
dup = Satyr::FFI.sr_thread_dup(pointer)
raise SatyrError, "Failed to duplicate thread" if dup.null?
Thread.send(:new, dup)
end
|
ruby
|
{
"resource": ""
}
|
q23220
|
Rumonade.Option.get_or_else
|
train
|
def get_or_else(val_or_lam = nil, &blk)
v_or_f = val_or_lam || blk
if !empty? then value else (v_or_f.respond_to?(:call) ? v_or_f.call : v_or_f) end
end
|
ruby
|
{
"resource": ""
}
|
q23221
|
Subroutine.Op.inherit_errors
|
train
|
def inherit_errors(error_object)
error_object = error_object.errors if error_object.respond_to?(:errors)
error_object.each do |k, v|
next if _error_ignores[k.to_sym]
if respond_to?(k)
errors.add(k, v)
elsif _error_map[k.to_sym]
errors.add(_error_map[k.to_sym], v)
else
errors.add(:base, error_object.full_message(k, v))
end
end
false
end
|
ruby
|
{
"resource": ""
}
|
q23222
|
Subroutine.Op.sanitize_params
|
train
|
def sanitize_params(inputs)
out = {}.with_indifferent_access
_fields.each_pair do |field, config|
next unless inputs.key?(field)
out[field] = ::Subroutine::TypeCaster.cast(inputs[field], config)
end
out
end
|
ruby
|
{
"resource": ""
}
|
q23223
|
Rumonade.PartialFunction.or_else
|
train
|
def or_else(other)
PartialFunction.new(lambda { |x| self.defined_at?(x) || other.defined_at?(x) },
lambda { |x| if self.defined_at?(x) then self.call(x) else other.call(x) end })
end
|
ruby
|
{
"resource": ""
}
|
q23224
|
Rumonade.PartialFunction.and_then
|
train
|
def and_then(func)
PartialFunction.new(@defined_at_proc, lambda { |x| func.call(self.call(x)) })
end
|
ruby
|
{
"resource": ""
}
|
q23225
|
Uploadcare.RawApi.request
|
train
|
def request(method = :get, path = '/files/', params = {})
response = @api_connection.send method, path, params
response.body
end
|
ruby
|
{
"resource": ""
}
|
q23226
|
Uploadcare.UploadingApi.upload
|
train
|
def upload(object, options = {})
if file?(object) then upload_file(object, options)
elsif object.is_a?(Array) then upload_files(object, options)
elsif object.is_a?(String) then upload_url(object, options)
else
raise ArgumentError, "Expected input to be a file/Array/URL, given: `#{object}`"
end
end
|
ruby
|
{
"resource": ""
}
|
q23227
|
Uploadcare.UploadingApi.upload_files
|
train
|
def upload_files(files, options = {})
data = upload_params(options).for_file_upload(files)
response = @upload_connection.post('/base/', data)
response.body.values.map! { |f| Uploadcare::Api::File.new(self, f) }
end
|
ruby
|
{
"resource": ""
}
|
q23228
|
Uploadcare.UploadingApi.upload_url
|
train
|
def upload_url(url, options = {})
params = upload_params(options).for_url_upload(url)
token = request_file_upload(params)
upload_status = poll_upload_result(token)
if upload_status['status'] == 'error'
raise ArgumentError.new(upload_status['error'])
end
Uploadcare::Api::File.new(self, upload_status['file_id'])
end
|
ruby
|
{
"resource": ""
}
|
q23229
|
OandaAPI.Throttling.restore_original_new_method
|
train
|
def restore_original_new_method(klass)
klass.define_singleton_method :new do |*args, &block|
Throttling.original_new_method(klass).bind(klass).call *args, &block
end
end
|
ruby
|
{
"resource": ""
}
|
q23230
|
OandaAPI.Throttling.throttle_connection_rate
|
train
|
def throttle_connection_rate
now = Time.now
delta = now - (last_new_connection_at || now)
_throttle(delta, now) if delta < OandaAPI.configuration.min_new_connection_interval &&
OandaAPI.configuration.use_request_throttling?
self.last_new_connection_at = Time.now
end
|
ruby
|
{
"resource": ""
}
|
q23231
|
RailsBootstrapHelpers::Renderers.AbstractLinkRenderer.append_class
|
train
|
def append_class (cls)
return unless cls
if c = html_options["class"]
html_options["class"] << " " + cls.to_s
else
if c = has_option?("class")
c << " " + cls.to_s
cls = c
end
html_options["class"] = cls.to_s
end
end
|
ruby
|
{
"resource": ""
}
|
q23232
|
Darrrr.RecoveryProvider.countersign_token
|
train
|
def countersign_token(token:, context: nil, options: 0x00)
begin
account_provider = RecoveryToken.account_provider_issuer(token)
rescue RecoveryTokenSerializationError, UnknownProviderError
raise TokenFormatError, "Could not determine provider"
end
counter_recovery_token = RecoveryToken.build(
issuer: self,
audience: account_provider,
type: COUNTERSIGNED_RECOVERY_TOKEN_TYPE,
options: options,
)
counter_recovery_token.data = token
seal(counter_recovery_token, context)
end
|
ruby
|
{
"resource": ""
}
|
q23233
|
Darrrr.RecoveryProvider.validate_recovery_token!
|
train
|
def validate_recovery_token!(token, context = {})
errors = []
# 1. Authenticate the User. The exact nature of how the Recovery Provider authenticates the User is beyond the scope of this specification.
# handled in before_filter
# 4. Retrieve the Account Provider configuration as described in Section 2 using the issuer field of the token as the subject.
begin
account_provider = RecoveryToken.account_provider_issuer(token)
rescue RecoveryTokenSerializationError, UnknownProviderError, TokenFormatError => e
raise RecoveryTokenError, "Could not determine provider: #{e.message}"
end
# 2. Parse the token.
# 3. Validate that the version value is 0.
# 5. Validate the signature over the token according to processing rules for the algorithm implied by the version.
begin
recovery_token = account_provider.unseal(token, context)
rescue CryptoError => e
raise RecoveryTokenError.new("Unable to verify signature of token")
rescue TokenFormatError => e
raise RecoveryTokenError.new(e.message)
end
# 6. Validate that the audience field of the token identifies an origin which the provider considers itself authoritative for. (Often the audience will be same-origin with the Recovery Provider, but other values may be acceptable, e.g. "https://mail.example.com" and "https://social.example.com" may be acceptable audiences for "https://recovery.example.com".)
unless self.origin == recovery_token.audience
raise RecoveryTokenError.new("Unnacceptable audience")
end
if DateTime.parse(recovery_token.issued_time).utc < (Time.now - CLOCK_SKEW).utc
raise RecoveryTokenError.new("Issued at time is too far in the past")
end
recovery_token
end
|
ruby
|
{
"resource": ""
}
|
q23234
|
Darrrr.AccountProvider.generate_recovery_token
|
train
|
def generate_recovery_token(data:, audience:, context: nil, options: 0x00)
token = RecoveryToken.build(issuer: self, audience: audience, type: RECOVERY_TOKEN_TYPE, options: options)
token.data = self.encryptor.encrypt(data, self, context)
[token, seal(token, context)]
end
|
ruby
|
{
"resource": ""
}
|
q23235
|
Darrrr.AccountProvider.dangerous_unverified_recovery_token
|
train
|
def dangerous_unverified_recovery_token(countersigned_token)
parsed_countersigned_token = RecoveryToken.parse(Base64.strict_decode64(countersigned_token))
RecoveryToken.parse(parsed_countersigned_token.data)
end
|
ruby
|
{
"resource": ""
}
|
q23236
|
Darrrr.AccountProvider.validate_countersigned_recovery_token!
|
train
|
def validate_countersigned_recovery_token!(countersigned_token, context = {})
# 5. Validate the the issuer field is present in the token,
# and that it matches the audience field in the original countersigned token.
begin
recovery_provider = RecoveryToken.recovery_provider_issuer(Base64.strict_decode64(countersigned_token))
rescue RecoveryTokenSerializationError => e
raise CountersignedTokenError.new("Countersigned token is invalid: " + e.message, :countersigned_token_parse_error)
rescue UnknownProviderError => e
raise CountersignedTokenError.new(e.message, :recovery_token_invalid_issuer)
end
# 1. Parse the countersigned-token.
# 2. Validate that the version field is 0.
# 7. Retrieve the current Recovery Provider configuration as described in Section 2.
# 8. Validate that the counter-signed token signature validates with a current element of the countersign-pubkeys-secp256r1 array.
begin
parsed_countersigned_token = recovery_provider.unseal(Base64.strict_decode64(countersigned_token), context)
rescue TokenFormatError => e
raise CountersignedTokenError.new(e.message, :countersigned_invalid_token_version)
rescue CryptoError
raise CountersignedTokenError.new("Countersigned token has an invalid signature", :countersigned_invalid_signature)
end
# 3. De-serialize the original recovery token from the data field.
# 4. Validate the signature on the original recovery token.
begin
recovery_token = self.unseal(parsed_countersigned_token.data, context)
rescue RecoveryTokenSerializationError => e
raise CountersignedTokenError.new("Nested recovery token is invalid: " + e.message, :recovery_token_token_parse_error)
rescue TokenFormatError => e
raise CountersignedTokenError.new("Nested recovery token format error: #{e.message}", :recovery_token_invalid_token_type)
rescue CryptoError
raise CountersignedTokenError.new("Nested recovery token has an invalid signature", :recovery_token_invalid_signature)
end
# 5. Validate the the issuer field is present in the countersigned-token,
# and that it matches the audience field in the original token.
countersigned_token_issuer = parsed_countersigned_token.issuer
if countersigned_token_issuer.blank? || countersigned_token_issuer != recovery_token.audience || recovery_provider.origin != countersigned_token_issuer
raise CountersignedTokenError.new("Validate the the issuer field is present in the countersigned-token, and that it matches the audience field in the original token", :recovery_token_invalid_issuer)
end
# 6. Validate the token binding for the countersigned token, if present.
# (the token binding for the inner token is not relevant)
# TODO not required, to be implemented later
# 9. Decrypt the data field from the original recovery token and parse its information, if present.
# no decryption here is attempted. Attempts to call `decode` will just fail.
# 10. Apply any additional processing which provider-specific data in the opaque data portion may indicate is necessary.
begin
if DateTime.parse(parsed_countersigned_token.issued_time).utc < (Time.now - CLOCK_SKEW).utc
raise CountersignedTokenError.new("Countersigned recovery token issued at time is too far in the past", :stale_token)
end
rescue ArgumentError
raise CountersignedTokenError.new("Invalid countersigned token issued time", :invalid_issued_time)
end
recovery_token
end
|
ruby
|
{
"resource": ""
}
|
q23237
|
Darrrr.CryptoHelper.seal
|
train
|
def seal(token, context = nil)
raise RuntimeError, "signing private key must be set" unless self.instance_variable_get(:@signing_private_key)
binary_token = token.to_binary_s
signature = self.encryptor.sign(binary_token, self.instance_variable_get(:@signing_private_key), self, context)
Base64.strict_encode64([binary_token, signature].join)
end
|
ruby
|
{
"resource": ""
}
|
q23238
|
Darrrr.CryptoHelper.unseal
|
train
|
def unseal(token_and_signature, context = nil)
token = RecoveryToken.parse(token_and_signature)
unless token.version.to_i == PROTOCOL_VERSION
raise TokenFormatError, "Version field must be #{PROTOCOL_VERSION}"
end
token_data, signature = partition_signed_token(token_and_signature, token)
self.unseal_keys(context).each do |key|
return token if self.encryptor.verify(token_data, signature, key, self, context)
end
raise CryptoError, "Recovery token signature was invalid"
end
|
ruby
|
{
"resource": ""
}
|
q23239
|
RSpec.Repeat.repeat
|
train
|
def repeat(ex, count, options = {})
Repeater.new(count, options).run(ex, self)
end
|
ruby
|
{
"resource": ""
}
|
q23240
|
AmCharts.Chart.method_missing
|
train
|
def method_missing(name, *args, &block)
return type.send(name) if type if name.to_s.end_with?('?')
@settings.send(name, *args, &block)
end
|
ruby
|
{
"resource": ""
}
|
q23241
|
Rye.Rap.add_stderr
|
train
|
def add_stderr(*args)
args = args.flatten.compact
args = args.first.split($/) if args.size == 1
@stderr ||= []
@stderr << args
@stderr.flatten!
self
end
|
ruby
|
{
"resource": ""
}
|
q23242
|
RecordCache.Dispatcher.parse
|
train
|
def parse(options)
# find the record store, possibly based on the :store option
store = record_store(options.delete(:store))
# dispatch the parse call to all known strategies
Dispatcher.strategy_classes.map{ |klass| klass.parse(@base, store, options) }.flatten.compact.each do |strategy|
raise "Multiple record cache definitions found for '#{strategy.attribute}' on #{@base.name}" if @strategy_by_attribute[strategy.attribute]
# and keep track of all strategies
@strategy_by_attribute[strategy.attribute] = strategy
end
# make sure the strategies are ordered again on next call to +ordered_strategies+
@ordered_strategies = nil
end
|
ruby
|
{
"resource": ""
}
|
q23243
|
RecordCache.Dispatcher.invalidate
|
train
|
def invalidate(strategy, value = nil)
(value = strategy; strategy = :id) unless strategy.is_a?(Symbol)
# call the invalidate method of the chosen strategy
@strategy_by_attribute[strategy].invalidate(value) if @strategy_by_attribute[strategy]
end
|
ruby
|
{
"resource": ""
}
|
q23244
|
Rye.Set.run_command
|
train
|
def run_command(meth, *args, &block)
runner = @parallel ? :run_command_parallel : :run_command_serial
self.send(runner, meth, *args, &block)
end
|
ruby
|
{
"resource": ""
}
|
q23245
|
Rye.Set.run_command_parallel
|
train
|
def run_command_parallel(meth, *args, &block)
debug "P: #{meth} on #{@boxes.size} boxes (#{@boxes.collect {|b| b.host }.join(', ')})"
threads = []
raps = Rye::Rap.new(self)
(@boxes || []).each do |box|
threads << Thread.new do
Thread.current[:rap] = box.send(meth, *args, &block) # Store the result in the thread
end
end
threads.each do |t|
Kernel.sleep 0.03 # Give the thread some breathing room
begin
t.join # Wait for the thread to finish
rescue Exception => ex
# Store the exception in the result
raps << Rap.new(self, [ex])
next
end
raps << t[:rap] # Grab the result
end
raps
end
|
ruby
|
{
"resource": ""
}
|
q23246
|
Rye.Set.run_command_serial
|
train
|
def run_command_serial(meth, *args, &block)
debug "S: #{meth} on #{@boxes.size} boxes (#{@boxes.collect {|b| b.host }.join(', ')})"
raps = Rye::Rap.new(self)
(@boxes || []).each do |box|
raps << box.send(meth, *args, &block)
end
raps
end
|
ruby
|
{
"resource": ""
}
|
q23247
|
ActiveRecord::ConnectionAdapters.PostgreSQLAdapter.quote
|
train
|
def quote(value, column = nil)
if value.kind_of?(GeoRuby::SimpleFeatures::Geometry)
"'#{value.as_hex_ewkb}'"
else
original_quote(value,column)
end
end
|
ruby
|
{
"resource": ""
}
|
q23248
|
ActiveRecord::ConnectionAdapters.PostgreSQLAdapter.add_index
|
train
|
def add_index(table_name, column_name, options = {})
column_names = Array(column_name)
index_name = index_name(table_name, :column => column_names)
if Hash === options # legacy support, since this param was a string
index_type = options[:unique] ? "UNIQUE" : ""
index_name = options[:name] || index_name
index_method = options[:spatial] ? 'USING GIST' : ""
else
index_type = options
end
quoted_column_names = column_names.map { |e| quote_column_name(e) }.join(", ")
execute "CREATE #{index_type} INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} #{index_method} (#{quoted_column_names})"
end
|
ruby
|
{
"resource": ""
}
|
q23249
|
Rye.Box.ostype
|
train
|
def ostype
return @rye_ostype if @rye_ostype # simple cache
os = self.quietly { uname.first } rescue nil
os ||= 'unknown'
os &&= os.downcase
@rye_ostype = os
end
|
ruby
|
{
"resource": ""
}
|
q23250
|
Rye.Box.unsafely
|
train
|
def unsafely(*args, &block)
previous_state = @rye_safe
disable_safe_mode
ret = self.instance_exec *args, &block
@rye_safe = previous_state
ret
end
|
ruby
|
{
"resource": ""
}
|
q23251
|
Rye.Box.quietly
|
train
|
def quietly(*args, &block)
previous_state = @rye_quiet
enable_quiet_mode
ret = self.instance_exec *args, &block
@rye_quiet = previous_state
ret
end
|
ruby
|
{
"resource": ""
}
|
q23252
|
Rye.Box.sudo
|
train
|
def sudo(*args, &block)
if block.nil?
run_command('sudo', args);
else
previous_state = @rye_sudo
enable_sudo
ret = self.instance_exec *args, &block
@rye_sudo = previous_state
ret
end
end
|
ruby
|
{
"resource": ""
}
|
q23253
|
Rye.Box.prepend_env
|
train
|
def prepend_env(cmd)
return cmd unless @rye_current_environment_variables.is_a?(Hash)
env = ''
@rye_current_environment_variables.each_pair do |n,v|
env << "export #{n}=#{Escape.shell_single_word(v)}; "
end
[env, cmd].join(' ')
end
|
ruby
|
{
"resource": ""
}
|
q23254
|
Rye.Box.run_command
|
train
|
def run_command(*args, &blk)
debug "run_command"
cmd, args = prep_args(*args)
#p [:run_command, cmd, blk.nil?]
connect if !@rye_ssh || @rye_ssh.closed?
raise Rye::NotConnected, @rye_host unless @rye_ssh && !@rye_ssh.closed?
cmd_clean = Rye.escape(@rye_safe, cmd, args)
# This following is the command we'll actually execute. cmd_clean
# can be used for logging, otherwise the output is confusing.
cmd_internal = prepend_env(cmd_clean)
# Add the current working directory before the command if supplied.
# The command will otherwise run in the user's home directory.
if @rye_current_working_directory
cwd = Rye.escape(@rye_safe, 'cd', @rye_current_working_directory)
cmd_internal = '(%s; %s)' % [cwd, cmd_internal]
end
# ditto (same explanation as cwd)
if @rye_current_umask
cwd = Rye.escape(@rye_safe, 'umask', @rye_current_umask)
cmd_internal = [cwd, cmd_internal].join(' && ')
end
## NOTE: Do not raise a CommandNotFound exception in this method.
# We want it to be possible to define methods to a single instance
# of Rye::Box. i.e. def rbox.rm()...
# can? returns the methods in Rye::Cmd so it would incorrectly
# return false. We could use self.respond_to? but it's possible
# to get a name collision. I could write a work around but I think
# this is good enough for now.
## raise Rye::CommandNotFound unless self.can?(cmd)
begin
debug "COMMAND: #{cmd_internal}"
if !@rye_quiet && @rye_pre_command_hook.is_a?(Proc)
@rye_pre_command_hook.call(cmd_clean, user, host, nickname)
end
rap = Rye::Rap.new(self)
rap.cmd = cmd_clean
channel = net_ssh_exec!(cmd_internal, &blk)
channel[:stderr].position = 0
channel[:stdout].position = 0
if channel[:exception]
rap = channel[:exception].rap
else
rap.add_stdout(channel[:stdout].read || '')
rap.add_stderr(channel[:stderr].read || '')
rap.add_exit_status(channel[:exit_status])
rap.exit_signal = channel[:exit_signal]
end
debug "RESULT: %s " % [rap.inspect]
# It seems a convention for various commands to return -1
# when something only mildly concerning happens. (ls even
# returns -1 for apparently no reason sometimes). Anyway,
# the real errors are the ones that are greater than zero.
raise Rye::Err.new(rap) if rap.exit_status != 0
rescue Exception => ex
return rap if @rye_quiet
choice = nil
@rye_exception_hook.each_pair do |klass,act|
next unless ex.kind_of? klass
choice = act.call(ex, cmd_clean, user, host, nickname)
break
end
if choice == :retry
retry
elsif choice == :skip
# do nothing
elsif choice == :interactive && !@rye_shell
@rye_shell = true
previous_state = @rye_sudo
disable_sudo
bash
@rye_sudo = previous_state
@rye_shell = false
elsif !ex.is_a?(Interrupt)
raise ex, ex.message
end
end
if !@rye_quiet && @rye_post_command_hook.is_a?(Proc)
@rye_post_command_hook.call(rap)
end
rap
end
|
ruby
|
{
"resource": ""
}
|
q23255
|
RecordCache.Query.where_values
|
train
|
def where_values(attribute, type = :integer)
return @where_values[attribute] if @where_values.key?(attribute)
@where_values[attribute] ||= array_of_values(@wheres[attribute], type)
end
|
ruby
|
{
"resource": ""
}
|
q23256
|
RecordCache.Query.where_value
|
train
|
def where_value(attribute, type = :integer)
values = where_values(attribute, type)
return nil unless values && values.size == 1
values.first
end
|
ruby
|
{
"resource": ""
}
|
q23257
|
Rye.Cmd.file_append
|
train
|
def file_append(filepath, newcontent, backup=false)
content = StringIO.new
if self.file_exists?(filepath)
self.cp filepath, "#{filepath}-previous" if backup
content = self.file_download filepath
end
if newcontent.is_a?(StringIO)
newcontent.rewind
content.puts newcontent.read
else
content.puts newcontent
end
self.file_upload content, filepath
end
|
ruby
|
{
"resource": ""
}
|
q23258
|
Rye.Cmd.file_write
|
train
|
def file_write(filepath, newcontent, backup=false)
if self.file_exists?(filepath)
self.cp filepath, "#{filepath}-previous" if backup
end
content = StringIO.new
content.puts newcontent
self.file_upload content, filepath
end
|
ruby
|
{
"resource": ""
}
|
q23259
|
Rye.Cmd.template_upload
|
train
|
def template_upload(*paths)
remote_path = paths.pop
templates = []
paths.collect! do |path|
if StringIO === path
path.rewind
template = Rye::Tpl.new(path.read, "inline-template")
elsif String === path
raise "No such file: #{Dir.pwd}/#{path}" unless File.exists?(path)
template = Rye::Tpl.new(File.read(path), File.basename(path))
end
template.result!(binding)
templates << template
template.path
end
paths << remote_path
ret = self.file_upload *paths
templates.each { |template|
tmp_path = File.join(remote_path, File.basename(template.path))
if file_exists?(tmp_path)
mv tmp_path, File.join(remote_path, template.basename)
end
template.delete
}
ret
end
|
ruby
|
{
"resource": ""
}
|
q23260
|
Rye.Cmd.file_exists?
|
train
|
def file_exists?(path)
begin
ret = self.quietly { ls(path) }
rescue Rye::Err => ex
ret = ex.rap
end
# "ls" returns a 0 exit code regardless of success in Linux
# But on OSX exit code is 1. This is why we look at STDERR.
!(ret.exit_status > 0) || ret.stderr.empty?
end
|
ruby
|
{
"resource": ""
}
|
q23261
|
Rye.Hop.fetch_port
|
train
|
def fetch_port(host, port = 22, localport = nil)
connect unless @rye_ssh
if localport.nil?
port_used = next_port
else
port_used = localport
end
# i would like to check if the port and host
# are already an active_locals forward, but that
# info does not get returned, and trusting the localport
# is not enough information, so lets just set up a new one
@rye_ssh.forward.local(port_used, host, port)
return port_used
end
|
ruby
|
{
"resource": ""
}
|
q23262
|
Rye.Hop.connect
|
train
|
def connect(reconnect=true)
raise Rye::NoHost unless @rye_host
return if @rye_ssh && !reconnect
disconnect if @rye_ssh
if @rye_via
debug "Opening connection to #{@rye_host} as #{@rye_user}, via #{@rye_via.host}"
else
debug "Opening connection to #{@rye_host} as #{@rye_user}"
end
highline = HighLine.new # Used for password prompt
retried = 0
@rye_opts[:keys].compact! # A quick fix in Windows. TODO: Why is there a nil?
begin
if @rye_via
# tell the +Rye::Hop+ what and where to setup,
# it returns the local port used
@rye_localport = @rye_via.fetch_port(@rye_host, @rye_opts[:port].nil? ? 22 : @rye_opts[:port] )
@rye_ssh = Net::SSH.start("localhost", @rye_user, @rye_opts.merge(:port => @rye_localport) || {})
else
@rye_ssh = Net::SSH.start(@rye_host, @rye_user, @rye_opts || {})
end
debug "starting the port forward thread"
port_loop
rescue Net::SSH::HostKeyMismatch => ex
STDERR.puts ex.message
print "\a" if @rye_info # Ring the bell
if highline.ask("Continue? ").strip.match(/\Ay|yes|sure|ya\z/i)
@rye_opts[:paranoid] = false
retry
else
raise ex
end
rescue Net::SSH::AuthenticationFailed => ex
print "\a" if retried == 0 && @rye_info # Ring the bell once
retried += 1
if STDIN.tty? && retried <= 3
STDERR.puts "Passwordless login failed for #{@rye_user}"
@rye_opts[:password] = highline.ask("Password: ") { |q| q.echo = '' }.strip
@rye_opts[:auth_methods] ||= []
@rye_opts[:auth_methods].push *['keyboard-interactive', 'password']
retry
else
raise ex
end
end
# We add :auth_methods (a Net::SSH joint) to force asking for a
# password if the initial (key-based) authentication fails. We
# need to delete the key from @rye_opts otherwise it lingers until
# the next connection (if we switch_user is called for example).
@rye_opts.delete :auth_methods if @rye_opts.has_key?(:auth_methods)
self
end
|
ruby
|
{
"resource": ""
}
|
q23263
|
Rye.Hop.remove_hops!
|
train
|
def remove_hops!
return unless @rye_ssh && @rye_ssh.forward.active_locals.count > 0
@rye_ssh.forward.active_locals.each {|fport, fhost|
@rye_ssh.forward.cancel_local(fport, fhost)
}
if !@rye_ssh.channels.empty?
@rye_ssh.channels.each {|channel|
channel[-1].close
}
end
return @rye_ssh.forward.active_locals.count
end
|
ruby
|
{
"resource": ""
}
|
q23264
|
Rye.Hop.disconnect
|
train
|
def disconnect
return unless @rye_ssh && !@rye_ssh.closed?
begin
debug "removing active forwards"
remove_hops!
debug "killing port_loop @rye_port_thread"
@rye_port_thread.kill
if @rye_ssh.busy?;
info "Is something still running? (ctrl-C to exit)"
Timeout::timeout(10) do
@rye_ssh.loop(0.3) { @rye_ssh.busy?; }
end
end
debug "Closing connection to #{@rye_ssh.host}"
@rye_ssh.close
if @rye_via
debug "disconnecting Hop #{@rye_via.host}"
@rye_via.disconnect
end
rescue SystemCallError, Timeout::Error => ex
error "Rye::Hop: Disconnect timeout (#{ex.message})"
debug ex.backtrace
rescue Interrupt
debug "Exiting..."
end
end
|
ruby
|
{
"resource": ""
}
|
q23265
|
Rye.Hop.next_port
|
train
|
def next_port
port = @next_port
@next_port -= 1
@next_port = MAX_PORT if @next_port < MIN_PORT
# check if the port is in use, if so get the next_port
begin
TCPSocket.new '127.0.0.1', port
rescue Errno::EADDRINUSE
next_port()
rescue Errno::ECONNREFUSED
port
else
next_port()
end
end
|
ruby
|
{
"resource": ""
}
|
q23266
|
RecordCache.VersionStore.current_multi
|
train
|
def current_multi(id_key_map)
current_versions = @store.read_multi(*(id_key_map.values))
Hash[id_key_map.map{ |id, key| [id, current_versions[key]] }]
end
|
ruby
|
{
"resource": ""
}
|
q23267
|
Synvert.CLI.run
|
train
|
def run(args)
run_option_parser(args)
case @options[:command]
when 'list'
load_rewriters
list_available_rewriters
when 'open'
open_rewriter
when 'query'
load_rewriters
query_available_rewriters
when 'show'
load_rewriters
show_rewriter
when 'sync'
sync_snippets
else
load_rewriters
@options[:snippet_names].each do |snippet_name|
puts "===== #{snippet_name} started ====="
group, name = snippet_name.split('/')
rewriter = Core::Rewriter.call group, name
rewriter.warnings.each do |warning|
puts '[Warn] ' + warning.message
end
puts rewriter.todo if rewriter.todo
puts "===== #{snippet_name} done ====="
end
end
true
rescue SystemExit
true
rescue Parser::SyntaxError => e
puts "Syntax error: #{e.message}"
puts "file #{e.diagnostic.location.source_buffer.name}"
puts "line #{e.diagnostic.location.line}"
false
rescue Synvert::Core::RewriterNotFound => e
puts e.message
false
end
|
ruby
|
{
"resource": ""
}
|
q23268
|
Synvert.CLI.run_option_parser
|
train
|
def run_option_parser(args)
optparse = OptionParser.new do |opts|
opts.banner = 'Usage: synvert [project_path]'
opts.on '-d', '--load SNIPPET_PATHS', 'load custom snippets, snippet paths can be local file path or remote http url' do |snippet_paths|
@options[:custom_snippet_paths] = snippet_paths.split(',').map(&:strip)
end
opts.on '-l', '--list', 'list all available snippets' do
@options[:command] = 'list'
end
opts.on '-o', '--open SNIPPET_NAME', 'Open a snippet' do |snippet_name|
@options[:command] = 'open'
@options[:snippet_name] = snippet_name
end
opts.on '-q', '--query QUERY', 'query specified snippets' do |query|
@options[:command] = 'query'
@options[:query] = query
end
opts.on '--skip FILE_PATTERNS', 'skip specified files or directories, separated by comma, e.g. app/models/post.rb,vendor/plugins/**/*.rb' do |file_patterns|
@options[:skip_file_patterns] = file_patterns.split(',')
end
opts.on '-s', '--show SNIPPET_NAME', 'show specified snippet description, SNIPPET_NAME is combined by group and name, e.g. ruby/new_hash_syntax' do |snippet_name|
@options[:command] = 'show'
@options[:snippet_name] = snippet_name
end
opts.on '--sync', 'sync snippets' do
@options[:command] = 'sync'
end
opts.on '-r', '--run SNIPPET_NAMES', 'run specified snippets, each SNIPPET_NAME is combined by group and name, e.g. ruby/new_hash_syntax,ruby/new_lambda_syntax' do |snippet_names|
@options[:snippet_names] = snippet_names.split(',').map(&:strip)
end
opts.on '-v', '--version', 'show this version' do
puts Core::VERSION
exit
end
end
paths = optparse.parse(args)
Core::Configuration.instance.set :path, paths.first || Dir.pwd
if @options[:skip_file_patterns] && !@options[:skip_file_patterns].empty?
skip_files = @options[:skip_file_patterns].map do |file_pattern|
full_file_pattern = File.join(Core::Configuration.instance.get(:path), file_pattern)
Dir.glob(full_file_pattern)
end.flatten
Core::Configuration.instance.set :skip_files, skip_files
end
end
|
ruby
|
{
"resource": ""
}
|
q23269
|
Synvert.CLI.load_rewriters
|
train
|
def load_rewriters
Dir.glob(File.join(default_snippets_path, 'lib/**/*.rb')).each { |file| require file }
@options[:custom_snippet_paths].each do |snippet_path|
if snippet_path =~ /^http/
uri = URI.parse snippet_path
eval(uri.read)
else
require snippet_path
end
end
rescue
FileUtils.rm_rf default_snippets_path
retry
end
|
ruby
|
{
"resource": ""
}
|
q23270
|
Synvert.CLI.list_available_rewriters
|
train
|
def list_available_rewriters
if Core::Rewriter.availables.empty?
puts 'There is no snippet under ~/.synvert, please run `synvert --sync` to fetch snippets.'
else
Core::Rewriter.availables.each do |group, rewriters|
puts group
rewriters.each do |name, rewriter|
puts ' ' + name
end
end
puts
end
end
|
ruby
|
{
"resource": ""
}
|
q23271
|
Synvert.CLI.open_rewriter
|
train
|
def open_rewriter
editor = [ENV['SYNVERT_EDITOR'], ENV['EDITOR']].find { |e| !e.nil? && !e.empty? }
return puts 'To open a synvert snippet, set $EDITOR or $SYNVERT_EDITOR' unless editor
path = File.expand_path(File.join(default_snippets_path, "lib/#{@options[:snippet_name]}.rb"))
if File.exist? path
system editor, path
else
puts "Can't run #{editor} #{path}"
end
end
|
ruby
|
{
"resource": ""
}
|
q23272
|
Synvert.CLI.query_available_rewriters
|
train
|
def query_available_rewriters
Core::Rewriter.availables.each do |group, rewriters|
if group.include? @options[:query]
puts group
rewriters.each do |name, rewriter|
puts ' ' + name
end
elsif rewriters.keys.any? { |name| name.include? @options[:query] }
puts group
rewriters.each do |name, rewriter|
puts ' ' + name if name.include?(@options[:query])
end
end
end
puts
end
|
ruby
|
{
"resource": ""
}
|
q23273
|
Synvert.CLI.show_rewriter
|
train
|
def show_rewriter
group, name = @options[:snippet_name].split('/')
rewriter = Core::Rewriter.fetch(group, name)
if rewriter
rewriter.process_with_sandbox
puts rewriter.description
rewriter.sub_snippets.each do |sub_rewriter|
puts
puts '=' * 80
puts "snippet: #{sub_rewriter.name}"
puts '=' * 80
puts sub_rewriter.description
end
else
puts "snippet #{@options[:snippet_name]} not found"
end
end
|
ruby
|
{
"resource": ""
}
|
q23274
|
Jiralicious.Session.request
|
train
|
def request(method, *options)
response_handler = if options.last.is_a?(Hash) && options.last[:handler]
options.last.delete(:handler)
else
handler
end
self.class.base_uri Jiralicious.uri
before_request if respond_to?(:before_request)
response = self.class.send(method, *options)
after_request(response) if respond_to?(:after_request)
response_handler.call(response)
end
|
ruby
|
{
"resource": ""
}
|
q23275
|
Staypuft.Deployment.update_hostgroup_list
|
train
|
def update_hostgroup_list
old_deployment_role_hostgroups = deployment_role_hostgroups.to_a
new_deployment_role_hostgroups = layout.layout_roles.map do |layout_role|
deployment_role_hostgroup = deployment_role_hostgroups.where(:role_id => layout_role.role).first_or_initialize do |drh|
drh.hostgroup = Hostgroup.new(name: layout_role.role.name, parent: hostgroup)
end
deployment_role_hostgroup.hostgroup.add_puppetclasses_from_resource(layout_role.role)
layout_role.role.services.each do |service|
deployment_role_hostgroup.hostgroup.add_puppetclasses_from_resource(service)
end
# deployment_role_hostgroup.hostgroup.save!
deployment_role_hostgroup.deploy_order = layout_role.deploy_order
deployment_role_hostgroup.save!
deployment_role_hostgroup
end
# delete any prior mappings that remain
(old_deployment_role_hostgroups - new_deployment_role_hostgroups).each &:destroy
end
|
ruby
|
{
"resource": ""
}
|
q23276
|
Jiralicious.Version.update
|
train
|
def update(details)
details.each do |k, v|
send("#{k}=", v)
end
self.class.update(version_key, details)
end
|
ruby
|
{
"resource": ""
}
|
q23277
|
Jiralicious.OauthSession.get_secret
|
train
|
def get_secret
if Jiralicious.oauth_secret.nil?
IO.read(Jiralicious.config_path + Jiralicious.oauth_secret_filename)
else
Jiralicious.oauth_secret
end
end
|
ruby
|
{
"resource": ""
}
|
q23278
|
Jiralicious.OauthSession.handler
|
train
|
def handler
proc do |response|
case response.code
when 200..204
response
else
message = response.body
message = message["errorMessages"].join('\n') if message.is_a?(Hash)
Jiralicious::JiraError.new(message)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q23279
|
Jiralicious.CookieSession.after_request
|
train
|
def after_request(response)
unless @authenticating
if captcha_required(response) # rubocop:disable Style/GuardClause
raise Jiralicious::CaptchaRequired, "Captacha is required. Try logging into Jira via the web interface"
elsif cookie_invalid(response)
# Can usually be fixed by logging in again
clear_session
raise Jiralicious::CookieExpired
end
end
@authenticating = false
end
|
ruby
|
{
"resource": ""
}
|
q23280
|
Jiralicious.CookieSession.login
|
train
|
def login
@authenticating = true
handler = proc do |response|
if response.code == 200
@session = response["session"]
@login_info = response["loginInfo"]
self.class.cookies(session["name"] => session["value"])
else
clear_session
case response.code
when 401 then
raise Jiralicious::InvalidLogin, "Invalid login"
when 403
raise Jiralicious::CaptchaRequired, "Captacha is required. Try logging into Jira via the web interface"
else
# Give Net::HTTP reason
raise Jiralicious::JiraError, response
end
end
end
request(
:post, "/rest/auth/latest/session",
body: {
username: Jiralicious.username,
password: Jiralicious.password
}.to_json,
handler: handler
)
end
|
ruby
|
{
"resource": ""
}
|
q23281
|
Jiralicious.CookieSession.logout
|
train
|
def logout
handler = proc do
if response.code == 204
clear_session
else
case response.code
when 401 then
raise Jiralicious::NotLoggedIn, "Not logged in"
else
# Give Net::HTTP reason
raise Jiralicious::JiraError, response
end
end
end
request(:delete, "/rest/auth/latest/session", handler: handler)
end
|
ruby
|
{
"resource": ""
}
|
q23282
|
Jiralicious.Issue.save
|
train
|
def save
if loaded?
self.class.update(@fields.format_for_update, jira_key)
else
response = self.class.create(@fields.format_for_create)
self.jira_key = response.parsed_response["key"]
end
jira_key
end
|
ruby
|
{
"resource": ""
}
|
q23283
|
Danger.DangerEslint.lint_results
|
train
|
def lint_results
bin = eslint_path
raise 'eslint is not installed' unless bin
return run_lint(bin, '.') unless filtering
((git.modified_files - git.deleted_files) + git.added_files)
.select { |f| f.end_with? '.js' }
.map { |f| f.gsub("#{Dir.pwd}/", '') }
.map { |f| run_lint(bin, f).first }
end
|
ruby
|
{
"resource": ""
}
|
q23284
|
Danger.DangerEslint.send_comment
|
train
|
def send_comment(results)
dir = "#{Dir.pwd}/"
results['messages'].each do |r|
filename = results['filePath'].gsub(dir, '')
method = r['severity'] > 1 ? 'fail' : 'warn'
send(method, r['message'], file: filename, line: r['line'])
end
end
|
ruby
|
{
"resource": ""
}
|
q23285
|
Jiralicious.Component.update
|
train
|
def update(details)
details.each do |k, v|
send("#{k}=", v)
end
self.class.update(component_key, details)
end
|
ruby
|
{
"resource": ""
}
|
q23286
|
Jiralicious.Base.method_missing
|
train
|
def method_missing(meth, *args, &block)
if !loaded?
self.loaded = true
reload
send(meth, *args, &block)
else
super
end
end
|
ruby
|
{
"resource": ""
}
|
q23287
|
Jiralicious.Configuration.options
|
train
|
def options
VALID_OPTIONS.inject({}) do |option, key|
option.merge!(key => send(key))
end
end
|
ruby
|
{
"resource": ""
}
|
q23288
|
Jiralicious.Configuration.reset
|
train
|
def reset
self.username = DEFAULT_USERNAME
self.password = DEFAULT_PASSWORD
self.uri = DEFAULT_URI
self.api_version = DEFAULT_API_VERSION
self.auth_type = DEFAULT_AUTH_TYPE
self.project = nil
self.oauth_secret = nil
self.oauth_secret_filename = nil
self.oauth_pass_phrase = nil
self.oauth_consumer_key = nil
self.config_path = nil
end
|
ruby
|
{
"resource": ""
}
|
q23289
|
Jiralicious.Configuration.load_yml
|
train
|
def load_yml(yml_file, mode = nil)
if File.exist?(yml_file)
yml_cfg = OpenStruct.new(YAML.load_file(yml_file))
if mode.nil? || mode =~ /production/i
yml_cfg.jira.each do |k, v|
instance_variable_set("@#{k}", v)
end
else
yml_cfg.send(mode).each do |k, v|
instance_variable_set("@#{k}", v)
end
end
else
reset
end
end
|
ruby
|
{
"resource": ""
}
|
q23290
|
Staypuft.InterfaceAssigner.unassign_physical
|
train
|
def unassign_physical(interface)
interface.ip = nil if interface.subnet.ipam?
interface.subnet_id = nil
unless interface.save
@errors.push(interface.errors.full_messages)
end
end
|
ruby
|
{
"resource": ""
}
|
q23291
|
Humidifier.Loader.load
|
train
|
def load
parsed = JSON.parse(File.read(SPECPATH))
structs = StructureContainer.new(parsed['PropertyTypes'])
parsed['ResourceTypes'].each do |key, spec|
match = key.match(/\A(\w+)::(\w+)::(\w+)\z/)
register(match[1], match[2], match[3], spec, structs.search(key))
end
end
|
ruby
|
{
"resource": ""
}
|
q23292
|
ActiveRecord.Base.find_each_with_progress
|
train
|
def find_each_with_progress(options = {})
Progress.start(name.tableize, count(options)) do
find_each do |model|
Progress.step do
yield model
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q23293
|
ActiveRecord.Base.find_in_batches_with_progress
|
train
|
def find_in_batches_with_progress(options = {})
Progress.start(name.tableize, count(options)) do
find_in_batches do |batch|
Progress.step batch.length do
yield batch
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q23294
|
Humidifier.Resource.method_missing
|
train
|
def method_missing(name, *args)
if !valid_accessor?(name)
super
elsif self.class.prop?(name.to_s)
self.class.build_property_reader(name)
send(name)
else
self.class.build_property_writer(name)
send(name, args.first)
end
end
|
ruby
|
{
"resource": ""
}
|
q23295
|
Humidifier.Resource.update
|
train
|
def update(properties, raw = false)
properties.each do |property, value|
update_property(property, value, raw)
end
end
|
ruby
|
{
"resource": ""
}
|
q23296
|
Humidifier.Resource.update_property
|
train
|
def update_property(property, value, raw = false)
property = property.to_s
property = validate_property(property, raw)
value = validate_value(property, value, raw)
properties[property] = value
end
|
ruby
|
{
"resource": ""
}
|
q23297
|
Panda.Scope.find_by_path
|
train
|
def find_by_path(url, map={})
object = find_object_by_path(url, map)
if object.is_a?(Array)
object.map{|o| klass.new(o.merge('cloud_id' => cloud.id))}
elsif object['id']
klass.new(object.merge('cloud_id' => cloud.id))
else
raise APIError.new(object)
end
end
|
ruby
|
{
"resource": ""
}
|
q23298
|
Impala.Connection.open
|
train
|
def open
return if @connected
socket = Thrift::Socket.new(@host, @port, @options[:timeout])
if @options[:kerberos]
@transport = SASLTransport.new(socket, :GSSAPI, @options[:kerberos])
elsif @options[:sasl]
@transport = SASLTransport.new(socket, :PLAIN, @options[:sasl])
else
@transport = Thrift::BufferedTransport.new(socket)
end
@transport.open
proto = Thrift::BinaryProtocol.new(@transport)
@service = Protocol::ImpalaService::Client.new(proto)
@connected = true
end
|
ruby
|
{
"resource": ""
}
|
q23299
|
Impala.Connection.execute
|
train
|
def execute(query, query_options = {})
raise ConnectionError.new("Connection closed") unless open?
handle = send_query(query, query_options)
check_result(handle)
Cursor.new(handle, @service)
end
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.