_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q25700
|
SourceRoute.TraceFilter.block_it?
|
validation
|
def block_it?(tp)
if @cond.track_params
return true if negative_check(tp)
if positives_check(tp)
return !tp.binding.eval('local_variables').any? do |v|
tp.binding.local_variable_get(v).object_id == @cond.track_params
end
end
else
return true if negative_check(tp)
return false if positives_check(tp)
end
true # default is blocked the tp
end
|
ruby
|
{
"resource": ""
}
|
q25701
|
OnedClusterer.Clusterer.classify
|
validation
|
def classify(value)
raise ArgumentError, "value: #{value} must be in data array" unless @data.include?(value)
bounds[1..-1].index { |bound| value <= bound }
end
|
ruby
|
{
"resource": ""
}
|
q25702
|
OnedClusterer.Clusterer.intervals
|
validation
|
def intervals
first, *rest = bounds.each_cons(2).to_a
[first, *rest.map {|lower, upper| [data[data.rindex(lower) + 1] , upper] }]
end
|
ruby
|
{
"resource": ""
}
|
q25703
|
OnedClusterer.Jenks.matrices
|
validation
|
def matrices
rows = data.size
cols = n_classes
# in the original implementation, these matrices are referred to
# as `LC` and `OP`
# * lower_class_limits (LC): optimal lower class limits
# * variance_combinations (OP): optimal variance combinations for all classes
lower_class_limits = *Matrix.zero(rows + 1, cols + 1)
variance_combinations = *Matrix.zero(rows + 1, cols + 1)
# the variance, as computed at each step in the calculation
variance = 0
for i in 1..cols
lower_class_limits[1][i] = 1
variance_combinations[1][i] = 0
for j in 2..rows
variance_combinations[j][i] = Float::INFINITY
end
end
for l in 2..rows
sum = 0 # `SZ` originally. this is the sum of the values seen thus far when calculating variance.
sum_squares = 0 # `ZSQ` originally. the sum of squares of values seen thus far
w = 0 # `WT` originally. This is the number of data points considered so far.
for m in 1..l
lower_class_limit = l - m + 1 # `III` originally
val = data[lower_class_limit - 1]
# here we're estimating variance for each potential classing
# of the data, for each potential number of classes. `w`
# is the number of data points considered so far.
w += 1
# increase the current sum and sum-of-squares
sum += val
sum_squares += (val ** 2)
# the variance at this point in the sequence is the difference
# between the sum of squares and the total x 2, over the number
# of samples.
variance = sum_squares - (sum ** 2) / w
i4 = lower_class_limit - 1 # `IV` originally
if i4 != 0
for j in 2..cols
# if adding this element to an existing class
# will increase its variance beyond the limit, break
# the class at this point, setting the lower_class_limit
# at this point.
if variance_combinations[l][j] >= (variance + variance_combinations[i4][j - 1])
lower_class_limits[l][j] = lower_class_limit
variance_combinations[l][j] = variance +
variance_combinations[i4][j - 1]
end
end
end
end
lower_class_limits[l][1] = 1
variance_combinations[l][1] = variance
end
[lower_class_limits, variance_combinations]
end
|
ruby
|
{
"resource": ""
}
|
q25704
|
Omdb.Api.fetch
|
validation
|
def fetch(title, year = "", tomatoes = false, plot = "short")
res = network.call({ t: title, y: year, tomatoes: tomatoes, plot: plot })
if res[:data]["Response"] == "False"
{ status: 404 }
else
{ status: res[:code], movie: parse_movie(res[:data]) }
end
end
|
ruby
|
{
"resource": ""
}
|
q25705
|
Omdb.Api.find
|
validation
|
def find(id, tomatoes = false, plot = "short")
res = network.call({ i: id, tomatoes: tomatoes, plot: plot })
if res[:data]["Response"] == "False"
{ status: 404 }
else
{ status: res[:code], movie: parse_movie(res[:data]) }
end
end
|
ruby
|
{
"resource": ""
}
|
q25706
|
G5AuthenticationClient.Configuration.options
|
validation
|
def options
VALID_CONFIG_OPTIONS.inject({}) do |option, key|
option.merge!(key => send(key))
end
end
|
ruby
|
{
"resource": ""
}
|
q25707
|
G5AuthenticationClient.Client.create_user
|
validation
|
def create_user(options={})
user=User.new(options)
user.validate_for_create!
body = user_hash(user.to_hash)
response=oauth_access_token.post('/v1/users', body: body)
User.new(response.parsed)
end
|
ruby
|
{
"resource": ""
}
|
q25708
|
G5AuthenticationClient.Client.update_user
|
validation
|
def update_user(options={})
user=User.new(options)
user.validate!
response=oauth_access_token.put("/v1/users/#{user.id}", body: user_hash(user.to_hash))
User.new(response.parsed)
end
|
ruby
|
{
"resource": ""
}
|
q25709
|
G5AuthenticationClient.Client.find_user_by_email
|
validation
|
def find_user_by_email(email)
response = oauth_access_token.get('/v1/users', params: { email: email })
user = response.parsed.first
if user
user=User.new(user)
end
user
end
|
ruby
|
{
"resource": ""
}
|
q25710
|
G5AuthenticationClient.Client.sign_out_url
|
validation
|
def sign_out_url(redirect_url=nil)
auth_server_url = Addressable::URI.parse(endpoint)
auth_server_url.path = '/users/sign_out'
auth_server_url.query_values = {redirect_url: redirect_url} if redirect_url
auth_server_url.to_s
end
|
ruby
|
{
"resource": ""
}
|
q25711
|
G5AuthenticationClient.Client.list_users
|
validation
|
def list_users
response=oauth_access_token.get("/v1/users")
response.parsed.collect { |parsed_user| User.new(parsed_user) }
end
|
ruby
|
{
"resource": ""
}
|
q25712
|
G5AuthenticationClient.Client.list_roles
|
validation
|
def list_roles
response = oauth_access_token.get('/v1/roles')
response.parsed.collect { |parsed_role| Role.new(parsed_role) }
end
|
ruby
|
{
"resource": ""
}
|
q25713
|
CloudApp.Client.bookmark
|
validation
|
def bookmark(*args)
if args[0].is_a? Array
Drop.create(:bookmarks, args)
else
url, name = args[0], (args[1] || "")
Drop.create(:bookmark, {:name => name, :redirect_url => url})
end
end
|
ruby
|
{
"resource": ""
}
|
q25714
|
CloudApp.Client.rename
|
validation
|
def rename(id, name = "")
drop = Drop.find(id)
drop.update(:name => name)
end
|
ruby
|
{
"resource": ""
}
|
q25715
|
CloudApp.Client.privacy
|
validation
|
def privacy(id, privacy = false)
drop = Drop.find(id)
drop.update(:private => privacy)
end
|
ruby
|
{
"resource": ""
}
|
q25716
|
CloudApp.Base.load
|
validation
|
def load(attributes = {})
attributes.each do |key, val|
if key =~ /^.*_at$/ and val
# if this is a date/time key and it's not nil, try to parse it first
# as DateTime, then as Date only
begin
dt = DateTime.strptime(val, "%Y-%m-%dT%H:%M:%SZ")
newval = Time.utc(dt.year, dt.month, dt.day, dt.hour, dt.min, dt.sec)
rescue ArgumentError => ex
newval = DateTime.strptime(val, "%Y-%m-%d")
end
self.instance_variable_set("@#{key}", newval)
else
self.instance_variable_set("@#{key}", val)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q25717
|
WDSinatra.AppLoader.load_environment
|
validation
|
def load_environment(env=RACK_ENV)
# Load the default which can be overwritten or extended by specific
# env config files.
require File.join(root_path, 'config', 'environments', 'default.rb')
env_file = File.join(root_path, "config", "environments", "#{env}.rb")
if File.exist?(env_file)
require env_file
else
debug_msg = "Environment file: #{env_file} couldn't be found, using only the default environment config instead." unless env == 'development'
end
# making sure we have a LOGGER constant defined.
unless Object.const_defined?(:LOGGER)
Object.const_set(:LOGGER, Logger.new($stdout))
end
LOGGER.debug(debug_msg) if debug_msg
end
|
ruby
|
{
"resource": ""
}
|
q25718
|
WDSinatra.AppLoader.load_apis
|
validation
|
def load_apis
Dir.glob(File.join(root_path, "api", "**", "*.rb")).each do |api|
require api
end
end
|
ruby
|
{
"resource": ""
}
|
q25719
|
IsItWorking.Filter.run
|
validation
|
def run
status = Status.new(name)
runner = (async ? AsyncRunner : SyncRunner).new do
t = Time.now
begin
@check.call(status)
rescue Exception => e
status.fail("#{name} error: #{e.inspect}")
end
status.time = Time.now - t
end
runner.filter_status = status
runner
end
|
ruby
|
{
"resource": ""
}
|
q25720
|
IsItWorking.Handler.call
|
validation
|
def call(env)
if @app.nil? || env[PATH_INFO] == @route_path
statuses = []
t = Time.now
statuses = Filter.run_filters(@filters)
render(statuses, Time.now - t)
else
@app.call(env)
end
end
|
ruby
|
{
"resource": ""
}
|
q25721
|
IsItWorking.Handler.check
|
validation
|
def check (name, *options_or_check, &block)
raise ArgumentError("Too many arguments to #{self.class.name}#check") if options_or_check.size > 2
check = nil
options = {:async => true}
unless options_or_check.empty?
if options_or_check[0].is_a?(Hash)
options = options.merge(options_or_check[0])
else
check = options_or_check[0]
end
if options_or_check[1].is_a?(Hash)
options = options.merge(options_or_check[1])
end
end
unless check
if block
check = block
else
check = lookup_check(name, options)
end
end
@filters << Filter.new(name, check, options[:async])
end
|
ruby
|
{
"resource": ""
}
|
q25722
|
IsItWorking.Handler.lookup_check
|
validation
|
def lookup_check(name, options) #:nodoc:
check_class_name = "#{name.to_s.gsub(/(^|_)([a-z])/){|m| m.sub('_', '').upcase}}Check"
check = nil
if IsItWorking.const_defined?(check_class_name)
check_class = IsItWorking.const_get(check_class_name)
check = check_class.new(options)
else
raise ArgumentError.new("Check not defined #{check_class_name}")
end
check
end
|
ruby
|
{
"resource": ""
}
|
q25723
|
IsItWorking.Handler.render
|
validation
|
def render(statuses, elapsed_time) #:nodoc:
fail = statuses.all?{|s| s.success?}
headers = {
"Content-Type" => "text/plain; charset=utf8",
"Cache-Control" => "no-cache",
"Date" => Time.now.httpdate,
}
messages = []
statuses.each do |status|
status.messages.each do |m|
messages << "#{m.ok? ? 'OK: ' : 'FAIL:'} #{status.name} - #{m.message} (#{status.time ? sprintf('%0.000f', status.time * 1000) : '?'}ms)"
end
end
info = []
info << "Host: #{@hostname}" unless @hostname.size == 0
info << "PID: #{$$}"
info << "Timestamp: #{Time.now.iso8601}"
info << "Elapsed Time: #{(elapsed_time * 1000).round}ms"
code = (fail ? 200 : 500)
[code, headers, [info.join("\n"), "\n\n", messages.join("\n")]]
end
|
ruby
|
{
"resource": ""
}
|
q25724
|
IsItWorking.PingCheck.call
|
validation
|
def call(status)
begin
ping(@host, @port)
status.ok("#{@alias} is accepting connections on port #{@port.inspect}")
rescue Errno::ECONNREFUSED
status.fail("#{@alias} is not accepting connections on port #{@port.inspect}")
rescue SocketError => e
status.fail("connection to #{@alias} on port #{@port.inspect} failed with '#{e.message}'")
rescue Timeout::Error
status.fail("#{@alias} did not respond on port #{@port.inspect} within #{@timeout} seconds")
end
end
|
ruby
|
{
"resource": ""
}
|
q25725
|
BootstrapAdmin.ControllerHelpers.respond_to?
|
validation
|
def respond_to? method, include_private = false
true if bootstrap_admin_config.respond_to? method
super method, include_private
end
|
ruby
|
{
"resource": ""
}
|
q25726
|
IsItWorking.UrlCheck.instantiate_http
|
validation
|
def instantiate_http #:nodoc:
http_class = nil
if @proxy && @proxy[:host]
http_class = Net::HTTP::Proxy(@proxy[:host], @proxy[:port], @proxy[:username], @proxy[:password])
else
http_class = Net::HTTP
end
http = http_class.new(@uri.host, @uri.port)
if @uri.scheme == 'https'
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
end
http.open_timeout = @open_timeout
http.read_timeout = @read_timeout
return http
end
|
ruby
|
{
"resource": ""
}
|
q25727
|
IsItWorking.UrlCheck.perform_http_request
|
validation
|
def perform_http_request #:nodoc:
request = Net::HTTP::Get.new(@uri.request_uri, @headers)
request.basic_auth(@username, @password) if @username || @password
http = instantiate_http
http.start do
http.request(request)
end
end
|
ruby
|
{
"resource": ""
}
|
q25728
|
Ftdi.Context.usb_open
|
validation
|
def usb_open(vendor, product)
raise ArgumentError.new('vendor should be Fixnum') unless vendor.kind_of?(Fixnum)
raise ArgumentError.new('product should be Fixnum') unless product.kind_of?(Fixnum)
check_result(Ftdi.ftdi_usb_open(ctx, vendor, product))
end
|
ruby
|
{
"resource": ""
}
|
q25729
|
Ftdi.Context.usb_open_desc
|
validation
|
def usb_open_desc(vendor, product, description, serial)
raise ArgumentError.new('vendor should be Fixnum') unless vendor.kind_of?(Fixnum)
raise ArgumentError.new('product should be Fixnum') unless product.kind_of?(Fixnum)
check_result(Ftdi.ftdi_usb_open_desc(ctx, vendor, product, description, serial))
end
|
ruby
|
{
"resource": ""
}
|
q25730
|
Ftdi.Context.usb_open_desc_index
|
validation
|
def usb_open_desc_index(vendor, product, description, serial, index)
raise ArgumentError.new('vendor should be Fixnum') unless vendor.kind_of?(Fixnum)
raise ArgumentError.new('product should be Fixnum') unless product.kind_of?(Fixnum)
raise ArgumentError.new('index should be Fixnum') unless index.kind_of?(Fixnum)
raise ArgumentError.new('index should be greater than or equal to zero') if index < 0
check_result(Ftdi.ftdi_usb_open_desc_index(ctx, vendor, product, description, serial, index))
end
|
ruby
|
{
"resource": ""
}
|
q25731
|
Ftdi.Context.baudrate=
|
validation
|
def baudrate=(new_baudrate)
raise ArgumentError.new('baudrate should be Fixnum') unless new_baudrate.kind_of?(Fixnum)
check_result(Ftdi.ftdi_set_baudrate(ctx, new_baudrate))
end
|
ruby
|
{
"resource": ""
}
|
q25732
|
Ftdi.Context.write_data_chunksize
|
validation
|
def write_data_chunksize
p = FFI::MemoryPointer.new(:uint, 1)
check_result(Ftdi.ftdi_write_data_get_chunksize(ctx, p))
p.read_uint
end
|
ruby
|
{
"resource": ""
}
|
q25733
|
Ftdi.Context.write_data
|
validation
|
def write_data(bytes)
bytes = bytes.pack('c*') if bytes.respond_to?(:pack)
size = bytes.respond_to?(:bytesize) ? bytes.bytesize : bytes.size
mem_buf = FFI::MemoryPointer.new(:char, size)
mem_buf.put_bytes(0, bytes)
bytes_written = Ftdi.ftdi_write_data(ctx, mem_buf, size)
check_result(bytes_written)
bytes_written
end
|
ruby
|
{
"resource": ""
}
|
q25734
|
Ftdi.Context.read_data_chunksize
|
validation
|
def read_data_chunksize
p = FFI::MemoryPointer.new(:uint, 1)
check_result(Ftdi.ftdi_read_data_get_chunksize(ctx, p))
p.read_uint
end
|
ruby
|
{
"resource": ""
}
|
q25735
|
Ftdi.Context.read_data
|
validation
|
def read_data
chunksize = read_data_chunksize
p = FFI::MemoryPointer.new(:char, chunksize)
bytes_read = Ftdi.ftdi_read_data(ctx, p, chunksize)
check_result(bytes_read)
r = p.read_bytes(bytes_read)
r.force_encoding("ASCII-8BIT") if r.respond_to?(:force_encoding)
r
end
|
ruby
|
{
"resource": ""
}
|
q25736
|
Ftdi.Context.read_pins
|
validation
|
def read_pins
p = FFI::MemoryPointer.new(:uchar, 1)
check_result(Ftdi.ftdi_read_pins(ctx, p))
p.read_uchar
end
|
ruby
|
{
"resource": ""
}
|
q25737
|
Geos::GoogleMaps::Api2.Geometry.to_g_marker_api2
|
validation
|
def to_g_marker_api2(marker_options = {}, options = {})
klass = if options[:short_class]
'GMarker'
else
'google.maps.Marker'
end
opts = Geos::Helper.camelize_keys(marker_options)
"new #{klass}(#{self.centroid.to_g_lat_lng(options)}, #{opts.to_json})"
end
|
ruby
|
{
"resource": ""
}
|
q25738
|
Geos::GoogleMaps::Api2.CoordinateSequence.to_g_polyline_api2
|
validation
|
def to_g_polyline_api2(polyline_options = {}, options = {})
klass = if options[:short_class]
'GPolyline'
else
'google.maps.Polyline'
end
poly_opts = if polyline_options[:polyline_options]
Geos::Helper.camelize_keys(polyline_options[:polyline_options])
end
args = [
(polyline_options[:color] ? "'#{Geos::Helper.escape_javascript(polyline_options[:color])}'" : 'null'),
(polyline_options[:weight] || 'null'),
(polyline_options[:opacity] || 'null'),
(poly_opts ? poly_opts.to_json : 'null')
].join(', ')
"new #{klass}([#{self.to_g_lat_lng(options).join(', ')}], #{args})"
end
|
ruby
|
{
"resource": ""
}
|
q25739
|
Geos::GoogleMaps::Api2.CoordinateSequence.to_g_polygon_api2
|
validation
|
def to_g_polygon_api2(polygon_options = {}, options = {})
klass = if options[:short_class]
'GPolygon'
else
'google.maps.Polygon'
end
poly_opts = if polygon_options[:polygon_options]
Geos::Helper.camelize_keys(polygon_options[:polygon_options])
end
args = [
(polygon_options[:stroke_color] ? "'#{Geos::Helper.escape_javascript(polygon_options[:stroke_color])}'" : 'null'),
(polygon_options[:stroke_weight] || 'null'),
(polygon_options[:stroke_opacity] || 'null'),
(polygon_options[:fill_color] ? "'#{Geos::Helper.escape_javascript(polygon_options[:fill_color])}'" : 'null'),
(polygon_options[:fill_opacity] || 'null'),
(poly_opts ? poly_opts.to_json : 'null')
].join(', ')
"new #{klass}([#{self.to_g_lat_lng_api2(options).join(', ')}], #{args})"
end
|
ruby
|
{
"resource": ""
}
|
q25740
|
Geos.Geometry.to_bbox
|
validation
|
def to_bbox(long_or_short_names = :long)
case long_or_short_names
when :long
{
:north => self.north,
:east => self.east,
:south => self.south,
:west => self.west
}
when :short
{
:n => self.north,
:e => self.east,
:s => self.south,
:w => self.west
}
else
raise ArgumentError.new("Expected either :long or :short for long_or_short_names argument")
end
end
|
ruby
|
{
"resource": ""
}
|
q25741
|
Geos.Point.to_georss
|
validation
|
def to_georss(*args)
xml = Geos::Helper.xml_options(*args)[0]
xml.georss(:where) do
xml.gml(:Point) do
xml.gml(:pos, "#{self.lat} #{self.lng}")
end
end
end
|
ruby
|
{
"resource": ""
}
|
q25742
|
Geos::GoogleMaps.Api3::Geometry.to_g_marker_api3
|
validation
|
def to_g_marker_api3(marker_options = {}, options = {})
options = {
:escape => [],
:lat_lng_options => {}
}.merge(options)
opts = Geos::Helper.camelize_keys(marker_options)
opts[:position] = self.centroid.to_g_lat_lng(options[:lat_lng_options])
json = Geos::Helper.escape_json(opts, Geos::GoogleMaps::Api3Constants::UNESCAPED_MARKER_OPTIONS - options[:escape])
"new google.maps.Marker(#{json})"
end
|
ruby
|
{
"resource": ""
}
|
q25743
|
Geos::GoogleMaps.Api3::CoordinateSequence.to_g_polyline_api3
|
validation
|
def to_g_polyline_api3(polyline_options = {}, options = {})
options = {
:escape => [],
:lat_lng_options => {}
}.merge(options)
opts = Geos::Helper.camelize_keys(polyline_options)
opts[:path] = "[#{self.to_g_lat_lng_api3(options[:lat_lng_options]).join(', ')}]"
json = Geos::Helper.escape_json(opts, Geos::GoogleMaps::Api3Constants::UNESCAPED_POLY_OPTIONS - options[:escape])
"new google.maps.Polyline(#{json})"
end
|
ruby
|
{
"resource": ""
}
|
q25744
|
Geos.CoordinateSequence.to_georss
|
validation
|
def to_georss(*args)
xml = Geos::Helper.xml_options(*args)[0]
xml.georss(:where) do
xml.gml(:LineString) do
xml.gml(:posList) do
xml << self.to_a.collect do |p|
"#{p[1]} #{p[0]}"
end.join(' ')
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q25745
|
SolidusImportProducts.ProcessRow.convert_to_price
|
validation
|
def convert_to_price(price_str)
raise SolidusImportProducts::Exception::InvalidPrice unless price_str
punt = price_str.index('.')
coma = price_str.index(',')
if !coma.nil? && !punt.nil?
price_str.gsub!(punt < coma ? '.' : ',', '')
end
price_str.tr(',', '.').to_f
end
|
ruby
|
{
"resource": ""
}
|
q25746
|
SynchronizedModel.Support.matches
|
validation
|
def matches(regexp, word)
if regexp.respond_to?(:match?)
regexp.match?(word)
else
regexp.match(word)
end
end
|
ruby
|
{
"resource": ""
}
|
q25747
|
Geos.Polygon.dump_points
|
validation
|
def dump_points(cur_path = [])
points = [ self.exterior_ring.dump_points ]
self.interior_rings.each do |ring|
points.push(ring.dump_points)
end
cur_path.concat(points)
end
|
ruby
|
{
"resource": ""
}
|
q25748
|
PruneAr.ForeignKeyHandler.generate_belongs_to_foreign_key_name
|
validation
|
def generate_belongs_to_foreign_key_name(assoc)
source = assoc.source_table[0..7]
column = assoc.foreign_key_column[0..7]
destination = assoc.destination_table[0..7]
"fk_#{source}_#{column}_#{destination}_#{SecureRandom.hex}"
end
|
ruby
|
{
"resource": ""
}
|
q25749
|
EGPRates.CIB.raw_exchange_rates
|
validation
|
def raw_exchange_rates
req = Net::HTTP::Post.new(@uri, 'Content-Type' => 'application/json')
req.body = { lang: :en }.to_json
response = Net::HTTP.start(@uri.hostname, @uri.port) do |http|
http.request(req)
end
fail ResponseError, response.code unless response.is_a? Net::HTTPSuccess
response = JSON.parse(response.body)
# CIB provide 6 currencies only
unless response['d'] && response['d'].size >= 6
fail ResponseError, "Unknown JSON #{response}"
end
response
rescue JSON::ParserError
raise ResponseError, "Unknown JSON: #{response.body}"
end
|
ruby
|
{
"resource": ""
}
|
q25750
|
Respect.FormatValidator.validate_ipv4_addr
|
validation
|
def validate_ipv4_addr(value)
ipaddr = IPAddr.new(value)
unless ipaddr.ipv4?
raise ValidationError, "IP address '#{value}' is not IPv4"
end
ipaddr
rescue ArgumentError => e
raise ValidationError, "invalid IPv4 address '#{value}' - #{e.message}"
end
|
ruby
|
{
"resource": ""
}
|
q25751
|
Respect.FormatValidator.validate_ipv6_addr
|
validation
|
def validate_ipv6_addr(value)
ipaddr = IPAddr.new(value)
unless ipaddr.ipv6?
raise ValidationError, "IP address '#{value}' is not IPv6"
end
ipaddr
rescue ArgumentError => e
raise ValidationError, "invalid IPv6 address '#{value}' - #{e.message}"
end
|
ruby
|
{
"resource": ""
}
|
q25752
|
LazyLazer.InternalModel.to_h
|
validation
|
def to_h(strict: false)
todo = @key_metadata.keys - @cache.keys
todo.each_with_object({}) do |key, hsh|
loaded_key = (strict ? load_key_strict(key) : load_key_lenient(key))
hsh[key] = loaded_key if exists_locally?(key)
end
end
|
ruby
|
{
"resource": ""
}
|
q25753
|
LazyLazer.InternalModel.exists_locally?
|
validation
|
def exists_locally?(key_name)
return true if @cache.key?(key_name) || @writethrough.key?(key_name)
meta = ensure_metadata_exists(key_name)
@source.key?(meta.source_key)
end
|
ruby
|
{
"resource": ""
}
|
q25754
|
LazyLazer.InternalModel.write_attribute
|
validation
|
def write_attribute(key_name, new_value)
meta = ensure_metadata_exists(key_name)
@source.delete(meta.source_key)
@writethrough[key_name] = @cache[key_name] = new_value
end
|
ruby
|
{
"resource": ""
}
|
q25755
|
LazyLazer.InternalModel.delete_attribute
|
validation
|
def delete_attribute(key_name)
key_name_sym = key_name.to_sym
meta = ensure_metadata_exists(key_name_sym)
@cache.delete(key_name)
@writethrough.delete(key_name)
@source.delete(meta.source_key)
nil
end
|
ruby
|
{
"resource": ""
}
|
q25756
|
LazyLazer.InternalModel.verify_required!
|
validation
|
def verify_required!
@key_metadata.required_properties.each do |key_name|
next if @source.key?(@key_metadata.get(key_name).source_key)
raise RequiredAttribute, "#{@parent} requires `#{key_name}`"
end
end
|
ruby
|
{
"resource": ""
}
|
q25757
|
LazyLazer.InternalModel.transform_value
|
validation
|
def transform_value(value, transform)
case transform
when nil
value
when Proc
@parent.instance_exec(value, &transform)
when Symbol
value.public_send(transform)
end
end
|
ruby
|
{
"resource": ""
}
|
q25758
|
EGPRates.Bank.response
|
validation
|
def response
response = Net::HTTP.get_response(@uri)
if response.is_a? Net::HTTPRedirection
response = Net::HTTP.get_response(URI.parse(response['location']))
end
fail ResponseError, response.code unless response.is_a? Net::HTTPSuccess
response
end
|
ruby
|
{
"resource": ""
}
|
q25759
|
EGPRates.ADIB.currencies
|
validation
|
def currencies(table_rows)
table_rows.lazy.map do |e|
e.css('img').map { |img| img.attribute('src').value }
end.force.flatten
end
|
ruby
|
{
"resource": ""
}
|
q25760
|
LazyLazer.KeyMetadataStore.add
|
validation
|
def add(key, meta)
@collection[key] = meta
if meta.required?
@required_properties << key
else
@required_properties.delete(key)
end
meta
end
|
ruby
|
{
"resource": ""
}
|
q25761
|
Respect.HasConstraints.validate_constraints
|
validation
|
def validate_constraints(value)
options.each do |option, arg|
if validator_class = Respect.validator_for(option)
validator_class.new(arg).validate(value)
end
end
end
|
ruby
|
{
"resource": ""
}
|
q25762
|
Respect.HasConstraints.validate
|
validation
|
def validate(object)
sanitized_object = validate_type(object)
validate_constraints(sanitized_object) unless sanitized_object.nil? && allow_nil?
self.sanitized_object = sanitized_object
true
rescue ValidationError => e
# Reset sanitized object.
self.sanitized_object = nil
raise e
end
|
ruby
|
{
"resource": ""
}
|
q25763
|
Respect.HashSchema.[]=
|
validation
|
def []=(name, schema)
case name
when Symbol, String, Regexp
if @properties.has_key?(name)
raise InvalidSchemaError, "property '#{name}' already defined"
end
@properties[name] = schema
else
raise InvalidSchemaError, "unsupported property name type #{name}:#{name.class}"
end
end
|
ruby
|
{
"resource": ""
}
|
q25764
|
Respect.HashDef.[]=
|
validation
|
def []=(key, value)
case value
when String
string(key, equal_to: value.to_s)
else
any(key, equal_to: value.to_s)
end
end
|
ruby
|
{
"resource": ""
}
|
q25765
|
GoogleHolidayCalendar.Calendar.holiday?
|
validation
|
def holiday?(arg)
date = to_date(arg)
holidays(start_date: date, end_date: date + 1.day, limit: 1).length > 0
end
|
ruby
|
{
"resource": ""
}
|
q25766
|
Choice.Parser.arrayize_arguments
|
validation
|
def arrayize_arguments(args)
# Go through trailing arguments and suck them in if they don't seem
# to have an owner.
array = []
until args.empty? || args.first.match(/^-/)
array << args.shift
end
array
end
|
ruby
|
{
"resource": ""
}
|
q25767
|
Choice.Option.to_a
|
validation
|
def to_a
[
required,
short,
long,
desc,
default,
filter,
action,
cast,
valid,
validate
].compact
end
|
ruby
|
{
"resource": ""
}
|
q25768
|
Choice.Option.to_h
|
validation
|
def to_h
{
"required" => required,
"short" => short,
"long" => long,
"desc" => desc,
"default" => default,
"filter" => filter,
"action" => action,
"cast" => cast,
"valid" => valid,
"validate" => validate
}.reject {|k, v| v.nil? }
end
|
ruby
|
{
"resource": ""
}
|
q25769
|
EventHub.Configuration.parse_options
|
validation
|
def parse_options(argv = ARGV)
@config_file = File.join(Dir.getwd, 'config', "#{@name}.json")
OptionParser.new do |opts|
note = 'Define environment'
opts.on('-e', '--environment ENVIRONMENT', note) do |environment|
@environment = environment
end
opts.on('-d', '--detached', 'Run processor detached as a daemon') do
@detached = true
end
note = 'Define configuration file'
opts.on('-c', '--config CONFIG', note) do |config|
@config_file = config
end
end.parse!(argv)
true
rescue OptionParser::InvalidOption => e
EventHub.logger.warn("Argument Parsing: #{e}")
false
rescue OptionParser::MissingArgument => e
EventHub.logger.warn("Argument Parsing: #{e}")
false
end
|
ruby
|
{
"resource": ""
}
|
q25770
|
EventHub.Configuration.load!
|
validation
|
def load!(args = {})
# for better rspec testing
@config_file = args[:config_file] if args[:config_file]
@environment = args[:environment] if args[:environment]
new_data = {}
begin
new_data = JSON.parse(File.read(@config_file), symbolize_names: true)
rescue => e
EventHub.logger.warn("Exception while loading configuration file: #{e}")
EventHub.logger.info('Using default configuration values')
end
deep_merge!(@config_data, default_configuration)
new_data = new_data[@environment.to_sym]
deep_merge!(@config_data, new_data)
end
|
ruby
|
{
"resource": ""
}
|
q25771
|
Vidibus.Words.keywords
|
validation
|
def keywords(limit = 20)
@keywords ||= {}
@keywords[limit] ||= begin
list = []
count = 0
_stopwords = Vidibus::Words.stopwords(*locales)
for word in sort
clean = word.permalink.gsub('-','')
unless _stopwords.include?(clean)
list << word
count += 1
break if count >= limit
end
end
list
end
end
|
ruby
|
{
"resource": ""
}
|
q25772
|
ONIX.Normaliser.next_tempfile
|
validation
|
def next_tempfile
p = nil
Tempfile.open("onix") do |tf|
p = tf.path
tf.close!
end
p
end
|
ruby
|
{
"resource": ""
}
|
q25773
|
ONIX.Reader.each
|
validation
|
def each(&block)
@reader.each do |node|
if @reader.node_type == 1 && @reader.name == "Product"
str = @reader.outer_xml
if str.nil?
yield @product_klass.new
else
yield @product_klass.from_xml(str)
end
end
end
end
|
ruby
|
{
"resource": ""
}
|
q25774
|
ONIX.APAProduct.title
|
validation
|
def title
composite = product.titles.first
if composite.nil?
nil
else
composite.title_text || composite.title_without_prefix
end
end
|
ruby
|
{
"resource": ""
}
|
q25775
|
ONIX.APAProduct.title=
|
validation
|
def title=(str)
composite = product.titles.first
if composite.nil?
composite = ONIX::Title.new
composite.title_type = 1
product.titles << composite
end
composite.title_text = str
end
|
ruby
|
{
"resource": ""
}
|
q25776
|
ONIX.APAProduct.subtitle=
|
validation
|
def subtitle=(str)
composite = product.titles.first
if composite.nil?
composite = ONIX::Title.new
composite.title_type = 1
product.titles << composite
end
composite.subtitle = str
end
|
ruby
|
{
"resource": ""
}
|
q25777
|
ONIX.APAProduct.bic_subjects
|
validation
|
def bic_subjects
subjects = product.subjects.select { |sub| sub.subject_scheme_id.to_i == 12 }
subjects.collect { |sub| sub.subject_code}
end
|
ruby
|
{
"resource": ""
}
|
q25778
|
ONIX.APAProduct.imprint=
|
validation
|
def imprint=(str)
composite = product.imprints.first
if composite.nil?
composite = ONIX::Imprint.new
product.imprints << composite
end
composite.imprint_name = str
end
|
ruby
|
{
"resource": ""
}
|
q25779
|
ONIX.APAProduct.sales_restriction_type=
|
validation
|
def sales_restriction_type=(type)
composite = product.sales_restrictions.first
if composite.nil?
composite = ONIX::SalesRestriction.new
product.sales_restrictions << composite
end
composite.sales_restriction_type = type
end
|
ruby
|
{
"resource": ""
}
|
q25780
|
ONIX.APAProduct.on_order
|
validation
|
def on_order
supply = find_or_create_supply_detail
composite = supply.stock.first
if composite.nil?
composite = ONIX::Stock.new
supply.stock << composite
end
composite.on_order
end
|
ruby
|
{
"resource": ""
}
|
q25781
|
ONIX.APAProduct.proprietry_discount_code_for_rrp
|
validation
|
def proprietry_discount_code_for_rrp
price = price_get(2)
return nil if price.nil?
discount = price.discounts_coded.find { |disc| disc.discount_code_type == 2 }
discount.andand.discount_code
end
|
ruby
|
{
"resource": ""
}
|
q25782
|
ONIX.APAProduct.proprietry_discount_code_for_rrp=
|
validation
|
def proprietry_discount_code_for_rrp=(code)
price = price_get(2)
if price.nil?
self.rrp_inc_sales_tax = 0
price = price_get(2)
end
discount = price.discounts_coded.find { |disc| disc.discount_code_type == 2 }
if discount.nil?
discount = ONIX::DiscountCoded.new
discount.discount_code_type = 2
price.discounts_coded << discount
end
discount.discount_code = code
end
|
ruby
|
{
"resource": ""
}
|
q25783
|
ONIX.APAProduct.add_subject
|
validation
|
def add_subject(str, type = "12")
subject = ::ONIX::Subject.new
subject.subject_scheme_id = type.to_i
subject.subject_code = str
product.subjects << subject
end
|
ruby
|
{
"resource": ""
}
|
q25784
|
ONIX.APAProduct.measurement_set
|
validation
|
def measurement_set(type, value, unit)
measure = measurement(type)
# create a new isbn record if we need to
if measure.nil?
measure = ONIX::Measure.new
measure.measure_type_code = type
product.measurements << measure
end
# store the new value
measure.measurement = value
measure.measure_unit_code = unit.to_s
end
|
ruby
|
{
"resource": ""
}
|
q25785
|
ONIX.APAProduct.price_get
|
validation
|
def price_get(type)
supply = find_or_create_supply_detail
if type.nil?
supply.prices.first
else
supply.prices.find { |p| p.price_type_code == type }
end
end
|
ruby
|
{
"resource": ""
}
|
q25786
|
ONIX.APAProduct.price_set
|
validation
|
def price_set(type, num)
p = price_get(type)
# create a new isbn record if we need to
if p.nil?
supply = find_or_create_supply_detail
p = ONIX::Price.new
p.price_type_code = type
supply.prices << p
end
# store the new value
p.price_amount = num
end
|
ruby
|
{
"resource": ""
}
|
q25787
|
ONIX.APAProduct.other_text_set
|
validation
|
def other_text_set(type, value)
text = other_text(type)
if text.nil?
text = ONIX::OtherText.new
text.text_type_code = type
product.text << text
end
# store the new value
text.text = value.to_s
end
|
ruby
|
{
"resource": ""
}
|
q25788
|
ONIX.APAProduct.website_set
|
validation
|
def website_set(type, value)
site = website(type)
# create a new website record if we need to
if site.nil?
site = ONIX::Website.new
site.website_role = type
product.websites << site
end
site.website_link = value.to_s
end
|
ruby
|
{
"resource": ""
}
|
q25789
|
Popular.Popular.befriend
|
validation
|
def befriend new_friend
run_callbacks :befriend do
friendships.create friend_id: new_friend.id, friend_type: new_friend.class.name
end
end
|
ruby
|
{
"resource": ""
}
|
q25790
|
Popular.Popular.befriend!
|
validation
|
def befriend! new_friend
run_callbacks :befriend do
friendships.create! friend_id: new_friend.id, friend_type: new_friend.class.name
end
end
|
ruby
|
{
"resource": ""
}
|
q25791
|
Popular.Popular.unfriend
|
validation
|
def unfriend friend
run_callbacks :unfriend do
friendships
.where( friend_type: friend.class.name )
.where( friend_id: friend.id )
.first.destroy
end
end
|
ruby
|
{
"resource": ""
}
|
q25792
|
TimecopConsole.ControllerMethods.handle_timecop_offset
|
validation
|
def handle_timecop_offset
# Establish now
if session[TimecopConsole::SESSION_KEY_NAME].present?
Rails.logger.debug "[timecop-console] Time traveling to #{session[TimecopConsole::SESSION_KEY_NAME].to_s}"
Timecop.travel(session[TimecopConsole::SESSION_KEY_NAME])
else
Timecop.return
end
# Run the intended action
yield
if session[TimecopConsole::SESSION_KEY_NAME].present?
# we want to continue to slide time forward, even if it's only 3 seconds at a time.
# this ensures that subsequent calls during the same "time travel" actually pass time
adjusted_time = Time.now + 3
Rails.logger.debug "[timecop-console] Resetting session to: #{adjusted_time}"
session[TimecopConsole::SESSION_KEY_NAME] = adjusted_time
end
end
|
ruby
|
{
"resource": ""
}
|
q25793
|
CodeMetrics.StatsDirectories.default_app_directories
|
validation
|
def default_app_directories
StatDirectory.from_list([
%w(Controllers app/controllers),
%w(Helpers app/helpers),
%w(Models app/models),
%w(Mailers app/mailers),
%w(Javascripts app/assets/javascripts),
%w(Libraries lib),
%w(APIs app/apis)
], @root)
end
|
ruby
|
{
"resource": ""
}
|
q25794
|
CodeMetrics.StatsDirectories.collect_directories
|
validation
|
def collect_directories(glob_pattern, file_pattern='')
Pathname.glob(glob_pattern).select{|f| f.basename.to_s.include?(file_pattern) }.map(&:dirname).uniq.map(&:realpath)
end
|
ruby
|
{
"resource": ""
}
|
q25795
|
Ws2812.Basic.[]=
|
validation
|
def []=(index, color)
if index.respond_to?(:to_a)
index.to_a.each do |i|
check_index(i)
ws2811_led_set(@channel, i, color.to_i)
end
else
check_index(index)
ws2811_led_set(@channel, index, color.to_i)
end
end
|
ruby
|
{
"resource": ""
}
|
q25796
|
Ws2812.Basic.set
|
validation
|
def set(index, r, g, b)
check_index(index)
self[index] = Color.new(r, g, b)
end
|
ruby
|
{
"resource": ""
}
|
q25797
|
Ws2812.Basic.[]
|
validation
|
def [](index)
if index.respond_to?(:to_a)
index.to_a.map do |i|
check_index(i)
Color.from_i(ws2811_led_get(@channel, i))
end
else
check_index(index)
Color.from_i(ws2811_led_get(@channel, index))
end
end
|
ruby
|
{
"resource": ""
}
|
q25798
|
ChefFS.Config.format_path
|
validation
|
def format_path(entry)
server_path = entry.path
if base_path && server_path[0,base_path.length] == base_path
if server_path == base_path
return "."
elsif server_path[base_path.length,1] == "/"
return server_path[base_path.length + 1, server_path.length - base_path.length - 1]
elsif base_path == "/" && server_path[0,1] == "/"
return server_path[1, server_path.length - 1]
end
end
server_path
end
|
ruby
|
{
"resource": ""
}
|
q25799
|
ChefFS.FilePattern.exact_path
|
validation
|
def exact_path
return nil if has_double_star || exact_parts.any? { |part| part.nil? }
result = ChefFS::PathUtils::join(*exact_parts)
is_absolute ? ChefFS::PathUtils::join('', result) : result
end
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.