_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 66
10.5k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q25900 | MotionModel.InputHelpers.bind | validation | def bind
raise ModelNotSetError.new("You must set the model before binding it.") unless @model
fields do |field|
view_obj = self.view.viewWithTag(field.tag)
@model.send("#{field.name}=".to_sym, view_obj.text) if view_obj.respond_to?(:text)
end
end | ruby | {
"resource": ""
} |
q25901 | MotionModel.InputHelpers.handle_keyboard_will_hide | validation | def handle_keyboard_will_hide(notification)
return unless @table
if UIEdgeInsetsEqualToEdgeInsets(@table.contentInset, UIEdgeInsetsZero)
return
end
animationCurve = notification.userInfo.valueForKey(UIKeyboardAnimationCurveUserInfoKey)
animationDuration = notification.userInfo.valueForKey(UIKeyboardAnimationDurationUserInfoKey)
UIView.beginAnimations("changeTableViewContentInset", context:nil)
UIView.setAnimationDuration(animationDuration)
UIView.setAnimationCurve(animationCurve)
@table.contentInset = UIEdgeInsetsZero;
UIView.commitAnimations
end | ruby | {
"resource": ""
} |
q25902 | CubaApi.Utils.no_body | validation | def no_body( status )
res.status = ::Rack::Utils.status_code( status )
res.write ::Rack::Utils::HTTP_STATUS_CODES[ res.status ]
res['Content-Type' ] = 'text/plain'
end | ruby | {
"resource": ""
} |
q25903 | Rack.Fraction.call | validation | def call(env)
if rand(1..100) <= @percent
if @modify == :response
# status, headers, body
response = @handler.call(*@app.call(env))
else # :env
modified_env = @handler.call(env) || env
response = @app.call(modified_env)
end
else
response = @app.call(env)
end
response
end | ruby | {
"resource": ""
} |
q25904 | Muster.Results.filtered | validation | def filtered
return self if filters.empty?
filtered_results = filters.each_with_object({}) do |(key, options), results|
results[key] = filter(key, *options)
end
self.class.new(filtered_results)
end | ruby | {
"resource": ""
} |
q25905 | Muster.Results.filter | validation | def filter(key, *options)
if options.present? && options.first.instance_of?(Hash)
options = options.first.with_indifferent_access
if options.key?(:only)
return filter_only_values(key, options[:only])
elsif options.key?(:except)
return filter_excluded_values(key, options[:except])
end
else
return fetch(key, *options)
end
end | ruby | {
"resource": ""
} |
q25906 | SyntaxFile.Controller.modify_metadata | validation | def modify_metadata
# Force all variables to be strings.
if @all_vars_as_string
@variables.each do |var|
var.is_string_var = true
var.is_double_var = false
var.implied_decimals = 0
end
end
# If the user wants to rectangularize hierarchical data, the
# select_vars_by_record_type option is required.
@select_vars_by_record_type = true if @rectangularize
# Remove any variables not belonging to the declared record types.
if @select_vars_by_record_type
rt_lookup = rec_type_lookup_hash()
@variables = @variables.find_all { |var| var.is_common_var or rt_lookup[var.record_type] }
end
end | ruby | {
"resource": ""
} |
q25907 | SyntaxFile.Controller.validate_metadata | validation | def validate_metadata (check = {})
bad_metadata('no variables') if @variables.empty?
if @rectangularize
msg = 'the rectangularize option requires data_structure=hier'
bad_metadata(msg) unless @data_structure == 'hier'
end
if @data_structure == 'hier' or @select_vars_by_record_type
bad_metadata('no record types') if @record_types.empty?
msg = 'record types must be unique'
bad_metadata(msg) unless rec_type_lookup_hash.keys.size == @record_types.size
msg = 'all variables must have a record type'
bad_metadata(msg) unless @variables.find { |var| var.record_type.length == 0 }.nil?
msg = 'with no common variables, every record type needs at least one variable ('
if @variables.find { |var| var.is_common_var }.nil?
@record_types.each do |rt|
next if get_vars_by_record_type(rt).size > 0
bad_metadata(msg + rt + ')')
end
end
end
if @data_structure == 'hier'
bad_metadata('no record type variable') if record_type_var.nil?
end
return if check[:minimal]
@variables.each do |v|
v.start_column = v.start_column.to_i
v.width = v.width.to_i
v.implied_decimals = v.implied_decimals.to_i
bad_metadata("#{v.name}, start_column" ) unless v.start_column > 0
bad_metadata("#{v.name}, width" ) unless v.width > 0
bad_metadata("#{v.name}, implied_decimals") unless v.implied_decimals >= 0
end
end | ruby | {
"resource": ""
} |
q25908 | ::ArJdbc.Teradata._execute | validation | def _execute(sql, name = nil)
if self.class.select?(sql)
result = @connection.execute_query(sql)
result.map! do |r|
new_hash = {}
r.each_pair do |k, v|
new_hash.merge!({ k.downcase => v })
end
new_hash
end if self.class.lowercase_schema_reflection
result
elsif self.class.insert?(sql)
(@connection.execute_insert(sql) || last_insert_id(_table_name_from_insert(sql))).to_i
else
@connection.execute_update(sql)
end
end | ruby | {
"resource": ""
} |
q25909 | ::ArJdbc.Teradata.primary_keys | validation | def primary_keys(table)
if self.class.lowercase_schema_reflection
@connection.primary_keys(table).map do |key|
key.downcase
end
else
@connection.primary_keys(table)
end
end | ruby | {
"resource": ""
} |
q25910 | ::ArJdbc.Teradata.change_column | validation | def change_column(table_name, column_name, type, options = {}) #:nodoc:
change_column_sql = "ALTER TABLE #{quote_table_name(table_name)} " <<
"ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit])}"
add_column_options!(change_column_sql, options)
execute(change_column_sql)
end | ruby | {
"resource": ""
} |
q25911 | SyntaxFile.Maker.labelable_values | validation | def labelable_values (var)
# For non-string variables, only values that look
# like integers can be labeled.
return var.values if var.is_string_var
var.values.find_all { |val| val.value.to_s =~ /^\-?\d+$/ }
end | ruby | {
"resource": ""
} |
q25912 | Ohm.Model.update_ttl | validation | def update_ttl new_ttl=nil
# Load default if no new ttl is specified
new_ttl = self._default_expire if new_ttl.nil?
# Make sure we have a valid value
new_ttl = -1 if !new_ttl.to_i.is_a?(Fixnum) || new_ttl.to_i < 0
# Update indices
Ohm.redis.expire(self.key, new_ttl)
Ohm.redis.expire("#{self.key}:_indices", new_ttl)
end | ruby | {
"resource": ""
} |
q25913 | Sipwizard.Relation.hash_to_query | validation | def hash_to_query(h)
h = Hash[h.map{|k,v| [k, "\"#{v}\""]}]
Rack::Utils.unescape Rack::Utils.build_query(h)
end | ruby | {
"resource": ""
} |
q25914 | AkamaiCloudletManager.PolicyVersion.existing_rules | validation | def existing_rules
request = Net::HTTP::Get.new URI.join(@base_uri.to_s, "cloudlets/api/v2/policies/#{@policy_id}/versions/#{@version_id}?omitRules=false&matchRuleFormat=1.0").to_s
response = @http_host.request(request)
response.body
end | ruby | {
"resource": ""
} |
q25915 | AkamaiCloudletManager.PolicyVersion.create | validation | def create(clone_from_version_id)
request = Net::HTTP::Post.new(
URI.join(
@base_uri.to_s,
"cloudlets/api/v2/policies/#{@policy_id}/versions?includeRules=false&matchRuleFormat=1.0&cloneVersion=#{clone_from_version_id}"
).to_s,
{ 'Content-Type' => 'application/json'}
)
response = @http_host.request(request)
response.body
end | ruby | {
"resource": ""
} |
q25916 | AkamaiCloudletManager.PolicyVersion.activate | validation | def activate(network)
request = Net::HTTP::Post.new(
URI.join(
@base_uri.to_s,
"/cloudlets/api/v2/policies/#{@policy_id}/versions/#{@version_id}/activations"
).to_s,
{ 'Content-Type' => 'application/json'}
)
request.body = {
"network": network
}.to_json
response = @http_host.request(request)
response.body
end | ruby | {
"resource": ""
} |
q25917 | AkamaiCloudletManager.PolicyVersion.update | validation | def update(options = {}, existing_rules = [])
request = Net::HTTP::Put.new(
URI.join(@base_uri.to_s, "cloudlets/api/v2/policies/#{@policy_id}/versions/#{@version_id}?omitRules=false&matchRuleFormat=1.0").to_s,
{ 'Content-Type' => 'application/json'}
)
rules = generate_path_rules(options) + generate_cookie_rules(options) + existing_rules
if rules.empty?
puts "No rules to apply, please check syntax"
return
end
request.body = {
matchRules: rules
}.to_json
response = @http_host.request(request)
response.body
end | ruby | {
"resource": ""
} |
q25918 | AkamaiCloudletManager.Origin.list | validation | def list(type)
request = Net::HTTP::Get.new URI.join(@base_uri.to_s, "cloudlets/api/v2/origins?type=#{type}").to_s
response = @http_host.request(request)
response.body
end | ruby | {
"resource": ""
} |
q25919 | InoxConverter.Converter.convert | validation | def convert(valueToConvert, firstUnit, secondUnit)
# First Step
finalValue = valueToConvert.round(10)
# Second Step
firstUnitResultant = getInDictionary(firstUnit)
if firstUnitResultant.nil?
raise NotImplementedError.new("#{firstUnit} isn't recognized by InoxConverter")
end
finalValue *= firstUnitResultant.round(10)
# Third step
secondUnitResultant = getInDictionary(secondUnit)
if secondUnitResultant.nil?
raise NotImplementedError.new("#{secondUnit} isn't recognized by InoxConverter")
end
finalValue /= secondUnitResultant.round(10)
# Fourth step
return finalValue.round(10)
end | ruby | {
"resource": ""
} |
q25920 | MemeCaptain.Caption.wrap | validation | def wrap(num_lines)
cleaned = gsub(/\s+/, ' ').strip
chars_per_line = cleaned.size / num_lines.to_f
lines = []
cleaned.split.each do |word|
if lines.empty?
lines << word
else
if (lines[-1].size + 1 + word.size) <= chars_per_line ||
lines.size >= num_lines
lines[-1] << ' ' unless lines[-1].empty?
lines[-1] << word
else
lines << word
end
end
end
Caption.new(lines.join("\n"))
end | ruby | {
"resource": ""
} |
q25921 | Api.Api.consume_api | validation | def consume_api
@dados = RestClient::Request.execute(method: :get, url: 'https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote')
hash_local = Hash.new
@hash_local = Hash.from_xml(@dados)
end | ruby | {
"resource": ""
} |
q25922 | Api.Api.treat_data | validation | def treat_data
@hash_inter = Hash.new
@hash = Hash.new
if validate_api_return
@hash_inter = @hash_local['list']['resources']['resource']
@hash_inter.each do |cout|
simbol_string = cout['field'][0].to_s
simbol = simbol_string.split("/")
@hash[simbol[1]] = cout['field'][1].to_f
end
else
@data = false
end
end | ruby | {
"resource": ""
} |
q25923 | Api.Api.convert_currency | validation | def convert_currency(valueToConvert, firstUnit, secondUnit)
dictionary_api
if validate_usd_unit(firstUnit) && validate_usd_unit(secondUnit)
return valueToConvert
elsif validate_usd_unit(firstUnit) && validate_usd_unit(secondUnit) == false
if validate_currency_unit(secondUnit)
finalValue = valueToConvert * @hash[secondUnit]
return finalValue
else
return 0
end
elsif validate_usd_unit(firstUnit) == false && validate_usd_unit(secondUnit)
if validate_currency_unit(firstUnit)
finalValue = valueToConvert / @hash[firstUnit]
return finalValue
else
return 0
end
else
if data_validate_api(firstUnit, secondUnit)
finalValue = (valueToConvert / @hash[firstUnit]) * @hash[secondUnit]
return finalValue
else
return 0
end
end
end | ruby | {
"resource": ""
} |
q25924 | HolyGrail.XhrProxy.request | validation | def request(info, data="")
context.instance_eval do
xhr(info["method"].downcase, info["url"], data)
@response.body.to_s
end
end | ruby | {
"resource": ""
} |
q25925 | HolyGrail.Extensions.js | validation | def js(code)
XhrProxy.context = self
@__page ||= Harmony::Page.new(XHR_MOCK_SCRIPT + rewrite_script_paths(@response.body.to_s))
Harmony::Page::Window::BASE_RUNTIME.wait
@__page.execute_js(code)
end | ruby | {
"resource": ""
} |
q25926 | MemeCaptain.Draw.calc_pointsize | validation | def calc_pointsize(width, height, text, min_pointsize)
current_pointsize = min_pointsize
metrics = nil
loop {
self.pointsize = current_pointsize
last_metrics = metrics
metrics = get_multiline_type_metrics(text)
if metrics.width + stroke_padding > width or
metrics.height + stroke_padding > height
if current_pointsize > min_pointsize
current_pointsize -= 1
metrics = last_metrics
end
break
else
current_pointsize += 1
end
}
[current_pointsize, metrics]
end | ruby | {
"resource": ""
} |
q25927 | InoxConverter.CurrencyAdapter.convert | validation | def convert(valueToConvert, firstUnit, secondUnit)
@api = Api::Api.new
@api.convert_currency(valueToConvert, firstUnit, secondUnit)
end | ruby | {
"resource": ""
} |
q25928 | Entrez.QueryLimit.respect_query_limit | validation | def respect_query_limit
now = Time.now.to_f
three_requests_ago = request_times[-3]
request_times << now
return unless three_requests_ago
time_for_last_3_requeests = now - three_requests_ago
enough_time_has_passed = time_for_last_3_requeests >= 1.0
unless enough_time_has_passed
sleep_time = 1 - time_for_last_3_requeests
STDERR.puts "sleeping #{sleep_time}"
sleep(sleep_time)
end
end | ruby | {
"resource": ""
} |
q25929 | Jekyll.RamlSchemaGenerator.insert_schemas | validation | def insert_schemas(obj)
if obj.is_a?(Array)
obj.map!{|method| insert_schemas(method)}
elsif obj.is_a?(Hash)
@current_method = obj['method'] if obj.include?('method')
obj.each { |k, v| obj[k] = insert_schemas(v)}
if obj.include?('body')
if obj['body'].fetch('application/x-www-form-urlencoded', {}).include?('formParameters')
if insert_json_schema?(obj)
insert_json_schema(obj, generate_json_schema(obj))
end
end
end
end
obj
end | ruby | {
"resource": ""
} |
q25930 | Messaging.Client.declare_exchange | validation | def declare_exchange(channel, name, type, options = {})
exchange =
# Check if default options need to be supplied to a non-default delcaration
if default_exchange?(name)
channel.default_exchange
else
channel.send(type, name, options)
end
log.debug("Exchange #{exchange.name.inspect} declared")
exchange
end | ruby | {
"resource": ""
} |
q25931 | Messaging.Client.declare_queue | validation | def declare_queue(channel, exchange, name, key, options = {})
channel.queue(name, options) do |queue|
# Check if additional bindings are needed
unless default_exchange?(exchange.name)
queue.bind(exchange, { :routing_key => key })
end
log.debug("Queue #{queue.name.inspect} bound to #{exchange.name.inspect}")
end
end | ruby | {
"resource": ""
} |
q25932 | Messaging.Client.disconnect | validation | def disconnect
channels.each do |chan|
chan.close
end
connections.each do |conn|
conn.disconnect
end
end | ruby | {
"resource": ""
} |
q25933 | Env.Variables.home | validation | def home
# logic adapted from Gem.find_home.
path = if (env['HOME'] || env['USERPROFILE'])
env['HOME'] || env['USERPROFILE']
elsif (env['HOMEDRIVE'] && env['HOMEPATH'])
"#{env['HOMEDRIVE']}#{env['HOMEPATH']}"
else
begin
File.expand_path('~')
rescue
if File::ALT_SEPARATOR
'C:/'
else
'/'
end
end
end
return Pathname.new(path)
end | ruby | {
"resource": ""
} |
q25934 | Env.Variables.parse_paths | validation | def parse_paths(paths)
if paths
paths.split(File::PATH_SEPARATOR).map do |path|
Pathname.new(path)
end
else
[]
end
end | ruby | {
"resource": ""
} |
q25935 | Timely.WeekDays.weekdays_int | validation | def weekdays_int
int = 0
WEEKDAY_KEYS.each.with_index do |day, index|
int += 2 ** index if @weekdays[day]
end
int
end | ruby | {
"resource": ""
} |
q25936 | Timely.TrackableDateSet.do_once | validation | def do_once(action_name, opts={})
return if action_applied?(action_name)
result = yield
job_done = opts[:job_done_when].blank? || opts[:job_done_when].call(result)
apply_action(action_name) if job_done
end | ruby | {
"resource": ""
} |
q25937 | Jekyll.ResourcePage.add_schema_hashes | validation | def add_schema_hashes(obj, key=nil)
if obj.is_a?(Array)
obj.map! { |method| add_schema_hashes(method) }
elsif obj.is_a?(Hash)
obj.each { |k, v| obj[k] = add_schema_hashes(v, k)}
if obj.include?("schema")
case key
when 'application/json'
obj['schema_hash'] = JSON.parse(obj['schema'])
refactor_object = lambda do |lam_obj|
lam_obj['properties'].each do |name, param|
param['displayName'] = name
param['required'] = true if lam_obj.fetch('required', []).include?(name)
if param.include?('example') and ['object', 'array'].include?(param['type'])
param['example'] = JSON.pretty_generate(JSON.parse(param['example']))
elsif param.include?('properties')
param['properties'] = JSON.pretty_generate(param['properties'])
elsif param.include?('items')
param['items'] = JSON.pretty_generate(param['items'])
end
lam_obj['properties'][name] = param
end
lam_obj
end
if obj['schema_hash'].include?('properties')
obj['schema_hash'] = refactor_object.call(obj['schema_hash'])
end
if obj['schema_hash'].include?('items') and obj['schema_hash']['items'].include?('properties')
obj['schema_hash']['items'] = refactor_object.call(obj['schema_hash']['items'])
end
end
end
end
obj
end | ruby | {
"resource": ""
} |
q25938 | Timely.Extensions.weekdays_field | validation | def weekdays_field(attribute, options={})
db_field = options[:db_field] || attribute.to_s + '_bit_array'
self.composed_of(attribute,
:class_name => "::Timely::WeekDays",
:mapping => [[db_field, 'weekdays_int']],
:converter => Proc.new {|field| ::Timely::WeekDays.new(field)}
)
end | ruby | {
"resource": ""
} |
q25939 | PaperTrailAudit.Model.calculate_audit_for | validation | def calculate_audit_for(param)
#Gets all flattened attribute lists
#objects are a hash of
#{attributes: object attributes, whodunnit: paper_trail whodunnit which caused the object to be in this state}
objects = [{attributes: self.attributes, whodunnit: self.paper_trail.originator},
self.versions.map {|e| {attributes: YAML.load(e.object), whodunnit: e.paper_trail_originator} if e.object}.compact].flatten
#rejecting objects with no update time, orders by the updated at times in ascending order
objects = objects.select {|e| e[:attributes]["updated_at"]}.sort_by {|e| e[:attributes]["updated_at"]}
result = []
#Add the initial state if the first element has a value
if(objects.count > 0 && !objects.first[:attributes][param.to_s].nil?)
result << PaperTrailAudit::Change.new({old_value: nil,
new_value: objects.first[:attributes][param.to_s],
time: objects.first[:attributes]["updated_at"],
whodunnit: objects.first[:whodunnit]
})
end
objects.each_cons(2) do |a,b|
if a[:attributes][param.to_s] != b[:attributes][param.to_s]
result << PaperTrailAudit::Change.new({old_value: a[:attributes][param.to_s],
new_value: b[:attributes][param.to_s],
time: b[:attributes]["updated_at"],
whodunnit: b[:whodunnit]
})
end
end
result
end | ruby | {
"resource": ""
} |
q25940 | Sycsvpro.Analyzer.result | validation | def result
rows = File.readlines(file)
result = Result.new
unless rows.empty?
row_number = 0
row_number += 1 while rows[row_number].chomp.empty?
result.cols = rows[row_number].chomp.split(';')
result.col_count = result.cols.size
row_number += 1
row_number += 1 while rows[row_number].chomp.empty?
result.row_count = rows.size - 1
result.sample_row = rows[row_number].chomp
end
result
end | ruby | {
"resource": ""
} |
q25941 | Galena.Seed.populate | validation | def populate
galena = CaTissue::Institution.new(:name => 'Galena University')
addr = CaTissue::Address.new(
:city => 'Galena', :state => 'Illinois', :country => 'United States', :zipCode => '37544',
:street => '411 Basin St', :phoneNumber => '311-555-5555')
dept = CaTissue::Department.new(:name => 'Pathology')
crg = CaTissue::CancerResearchGroup.new(:name => 'Don Thomas Cancer Center')
coord = CaTissue::User.new(
:email_address => 'corey.nator@galena.edu',
:last_name => 'Nator', :first_name => 'Corey', :address => addr.copy,
:institution => galena, :department => dept, :cancer_research_group => crg)
@hospital = CaTissue::Site.new(
:site_type => CaTissue::Site::SiteType::COLLECTION, :name => 'Galena Hospital',
:address => addr.copy, :coordinator => coord)
@tissue_bank = CaTissue::Site.new(
:site_type => CaTissue::Site::SiteType::REPOSITORY, :name => 'Galena Tissue Bank',
:address => addr.copy, :coordinator => coord)
pi = CaTissue::User.new(
:email_address => 'vesta.gator@galena.edu',
:last_name => 'Gator', :first_name => 'Vesta', :address => addr.copy,
:institution => galena, :department => dept, :cancer_research_group => crg)
@surgeon = CaTissue::User.new(
:email_address => 'serge.on@galena.edu',
:first_name => 'Serge', :last_name => 'On', :address => addr.copy,
:institution => galena, :department => dept, :cancer_research_group => crg)
@protocol = CaTissue::CollectionProtocol.new(:title => 'Galena Migration',
:principal_investigator => pi, :sites => [@tissue_bank])
# CPE has default 1.0 event point and label
cpe = CaTissue::CollectionProtocolEvent.new(
:collection_protocol => @protocol,
:event_point => 1.0
)
# The sole specimen requirement. Setting the requirement collection_event attribute to a CPE automatically
# sets the CPE requirement inverse attribute in caRuby.
CaTissue::TissueSpecimenRequirement.new(:collection_event => cpe, :specimen_type => 'Fixed Tissue')
# the storage container type hierarchy
@freezer_type = CaTissue::StorageType.new(
:name => 'Galena Freezer',
:columns => 10, :rows => 1,
:column_label => 'Rack'
)
rack_type = CaTissue::StorageType.new(:name => 'Galena Rack', :columns => 10, :rows => 10)
@box_type = CaTissue::StorageType.new(:name => 'Galena Box', :columns => 10, :rows => 10)
@freezer_type << rack_type
rack_type << @box_type
@box_type << 'Tissue'
# the example tissue box
@box = @box_type.new_container(:name => 'Galena Box 1')
end | ruby | {
"resource": ""
} |
q25942 | Sycsvpro.ScriptList.execute | validation | def execute
scripts = Dir.glob(File.join(@script_dir, @script_file))
scripts.each do |script|
list[script] = []
if show_methods
list[script] = retrieve_methods(script)
end
end
list
end | ruby | {
"resource": ""
} |
q25943 | Sycsvpro.ScriptList.retrieve_methods | validation | def retrieve_methods(script)
code = File.read(script)
methods = code.scan(/((#.*\s)*def.*\s|def.*\s)/)
result = []
methods.each do |method|
result << method[0]
end
result
end | ruby | {
"resource": ""
} |
q25944 | Turntabler.Client.close | validation | def close(allow_reconnect = false)
if @connection
# Disable reconnects if specified
reconnect = @reconnect
@reconnect = reconnect && allow_reconnect
# Clean up timers / connections
@keepalive_timer.cancel if @keepalive_timer
@keepalive_timer = nil
@connection.close
# Revert change to reconnect config once the final signal is received
wait do |&resume|
on(:session_ended, :once => true) { resume.call }
end
@reconnect = reconnect
end
true
end | ruby | {
"resource": ""
} |
q25945 | Turntabler.Client.api | validation | def api(command, params = {})
raise(ConnectionError, 'Connection is not open') unless @connection && @connection.connected?
message_id = @connection.publish(params.merge(:api => command))
# Wait until we get a response for the given message
data = wait do |&resume|
on(:response_received, :once => true, :if => {'msgid' => message_id}) {|data| resume.call(data)}
end
if data['success']
data
else
error = data['error'] || data['err']
raise APIError, "Command \"#{command}\" failed with message: \"#{error}\""
end
end | ruby | {
"resource": ""
} |
q25946 | Turntabler.Client.on | validation | def on(event, options = {}, &block)
event = event.to_sym
@event_handlers[event] ||= []
@event_handlers[event] << Handler.new(event, options, &block)
true
end | ruby | {
"resource": ""
} |
q25947 | Turntabler.Client.user_by_name | validation | def user_by_name(name)
data = api('user.get_id', :name => name)
user = self.user(data['userid'])
user.attributes = {'name' => name}
user
end | ruby | {
"resource": ""
} |
q25948 | Turntabler.Client.avatars | validation | def avatars
data = api('user.available_avatars')
avatars = []
data['avatars'].each do |avatar_group|
avatar_group['avatarids'].each do |avatar_id|
avatars << Avatar.new(self, :_id => avatar_id, :min => avatar_group['min'], :acl => avatar_group['acl'])
end
end
avatars
end | ruby | {
"resource": ""
} |
q25949 | Turntabler.Client.search_song | validation | def search_song(query, options = {})
assert_valid_keys(options, :artist, :duration, :page)
options = {:page => 1}.merge(options)
raise(APIError, 'User must be in a room to search for songs') unless room
if artist = options[:artist]
query = "title: #{query}"
query << " artist: #{artist}"
end
query << " duration: #{options[:duration]}" if options[:duration]
api('file.search', :query => query, :page => options[:page])
conditions = {'query' => query}
# Time out if the response takes too long
EventMachine.add_timer(@timeout) do
trigger(:search_failed, conditions)
end if @timeout
# Wait for the async callback
songs = wait do |&resume|
on(:search_completed, :once => true, :if => conditions) {|songs| resume.call(songs)}
on(:search_failed, :once => true, :if => conditions) { resume.call }
end
# Clean up any leftover handlers
@event_handlers[:search_completed].delete_if {|handler| handler.conditions == conditions}
@event_handlers[:search_failed].delete_if {|handler| handler.conditions == conditions}
songs || raise(APIError, 'Search failed to complete')
end | ruby | {
"resource": ""
} |
q25950 | Turntabler.Client.trigger | validation | def trigger(command, *args)
command = command.to_sym if command
if Event.command?(command)
event = Event.new(self, command, args)
handlers = @event_handlers[event.name] || []
handlers.each do |handler|
success = handler.run(event)
handlers.delete(handler) if success && handler.once
end
end
true
end | ruby | {
"resource": ""
} |
q25951 | Turntabler.Client.reset_keepalive | validation | def reset_keepalive(interval = 10)
if !@keepalive_timer || @keepalive_interval != interval
@keepalive_interval = interval
# Periodically update the user's status to remain available
@keepalive_timer.cancel if @keepalive_timer
@keepalive_timer = EM::Synchrony.add_periodic_timer(interval) do
Turntabler.run { user.update(:status => user.status) }
end
end
end | ruby | {
"resource": ""
} |
q25952 | Turntabler.Client.on_session_missing | validation | def on_session_missing
user.authenticate
user.fan_of
user.update(:status => user.status)
reset_keepalive
end | ruby | {
"resource": ""
} |
q25953 | Turntabler.Client.on_session_ended | validation | def on_session_ended
url = @connection.url
room = @room
@connection = nil
@room = nil
# Automatically reconnect to the room / server if allowed
if @reconnect
reconnect_from(Exception) do
room ? room.enter : connect(url)
trigger(:reconnected)
end
end
end | ruby | {
"resource": ""
} |
q25954 | Turntabler.Client.reconnect_from | validation | def reconnect_from(*exceptions)
begin
yield
rescue *exceptions => ex
if @reconnect
logger.debug "Connection failed: #{ex.message}"
EM::Synchrony.sleep(@reconnect_wait)
logger.debug 'Attempting to reconnect'
retry
else
raise
end
end
end | ruby | {
"resource": ""
} |
q25955 | Turntabler.Client.wait | validation | def wait(&block)
fiber = Fiber.current
# Resume the fiber when a response is received
allow_resume = true
block.call do |*args|
fiber.resume(*args) if allow_resume
end
# Attempt to pause the fiber until a response is received
begin
Fiber.yield
rescue FiberError => ex
allow_resume = false
raise Error, 'Turntabler APIs cannot be called from root fiber; use Turntabler.run { ... } instead'
end
end | ruby | {
"resource": ""
} |
q25956 | Viewable.PagePresenter.tree | validation | def tree(root_depth: 1, sitemap: false, nav_class: 'tree')
return if m.parent_at_depth(root_depth).nil?
@sitemap = sitemap
h.content_tag :nav, class: nav_class do
h.concat render_tree_master_ul(m.parent_at_depth(root_depth))
end
end | ruby | {
"resource": ""
} |
q25957 | Viewable.PagePresenter.breadcrumbs | validation | def breadcrumbs(root_depth: 0, last_page_title: nil, nav_class: 'breadcrumbs', div_class: 'scrollable')
return if m.parent_at_depth(root_depth).nil?
h.content_tag :nav, class: nav_class do
h.concat h.content_tag(:div, breadcrumbs_ul(breadcrumbs_list(root_depth, last_page_title)), class: div_class)
end
end | ruby | {
"resource": ""
} |
q25958 | CaTissue.Resource.tolerant_match? | validation | def tolerant_match?(other, attributes)
attributes.all? { |pa| Resource.tolerant_value_match?(send(pa), other.send(pa)) }
end | ruby | {
"resource": ""
} |
q25959 | Mako.FeedConstructor.parse_and_create | validation | def parse_and_create
parsed_feed = parse_feed
return false unless parsed_feed
feed = create_feed(parsed_feed)
create_articles(feed, parsed_feed)
feed
end | ruby | {
"resource": ""
} |
q25960 | Mako.FeedConstructor.entry_summary | validation | def entry_summary(entry)
!entry.content || entry.content.empty? ? entry.summary : entry.content
end | ruby | {
"resource": ""
} |
q25961 | ScopedAttrAccessible.Sanitizer.normalize_scope | validation | def normalize_scope(object, context)
return object if object.is_a?(Symbol)
# 1. Process recognizers, looking for a match.
@scope_recognizers.each_pair do |name, recognizers|
return name if recognizers.any? { |r| lambda(&r).call(context, object) }
end
# 2. Process converters, finding a result.
@scope_converters.each do |converter|
scope = lambda(&converter).call(context, object)
return normalize_scope(scope, converter) unless scope.nil?
end
# 3. Fall back to default
return :default
end | ruby | {
"resource": ""
} |
q25962 | Turntabler.PlaylistDirectory.build | validation | def build(attrs)
playlist = Playlist.new(client, attrs)
# Update existing in cache or cache a new playlist
if existing = @playlists[playlist.id]
playlist = existing
playlist.attributes = attrs
else
@playlists[playlist.id] = playlist
end
playlist
end | ruby | {
"resource": ""
} |
q25963 | MapKit.ZoomLevel.set_center_coordinates | validation | def set_center_coordinates(center_coordinate, zoom_level, animated = false)
# clamp large numbers to 18
zoom_level = [zoom_level, 18].min
# use the zoom level to compute the region
span = self.class.coordinate_span_with_map_view(self, center_coordinate, zoom_level)
region = CoordinateRegion.new(center_coordinate, span)
# set the region like normal
self.setRegion(region.api, animated: animated)
end | ruby | {
"resource": ""
} |
q25964 | MapKit.ZoomLevel.set_map_lat_lon | validation | def set_map_lat_lon(latitude, longitude, zoom_level, animated = false)
coordinate = LocationCoordinate.new(latitude, longitude)
set_center_coordinates(coordinate, zoom_level, animated)
end | ruby | {
"resource": ""
} |
q25965 | MapKit.ZoomLevel.zoom_level | validation | def zoom_level
region = self.region
center_pixel = region.center.to_pixel_space
top_left_pixel = (region.center - (region.span / 2)).to_pixel_space
scaled_map_width = (center_pixel.x - top_left_pixel.x) * 2
map_size_in_pixels = MapSize.new(self.bounds.size)
zoom_scale = scaled_map_width / map_size_in_pixels.width
zoom_exponent = log(zoom_scale) / log(2)
20 - zoom_exponent
end | ruby | {
"resource": ""
} |
q25966 | CaTissue.TransferEventParameters.from= | validation | def from=(location)
if location then
self.from_container = location.container
self.from_row = location.row
self.from_column = location.column
end
location
end | ruby | {
"resource": ""
} |
q25967 | CaTissue.TransferEventParameters.to= | validation | def to=(location)
if location.nil? then raise ArgumentError.new("Specimen cannot be moved to an empty location") end
self.to_container = location.container
self.to_row = location.row
self.to_column = location.column
end | ruby | {
"resource": ""
} |
q25968 | Steamd.CliOptions.input | validation | def input
o = if @input.nil?
Steamd.language_dir
else
@input
end
raise 'input must be a directory' unless File.directory?(o)
File.expand_path(o)
end | ruby | {
"resource": ""
} |
q25969 | Steamd.CliOptions.output | validation | def output
o = if @output.nil?
'./lib/steamd'
else
@output
end
raise 'output must be a directory' unless File.directory?(o)
File.expand_path(o)
end | ruby | {
"resource": ""
} |
q25970 | Sightstone.GameModule.recent | validation | def recent(summoner, optional={})
region = optional[:region] || @sightstone.region
id = if summoner.is_a? Summoner
summoner.id
else
summoner
end
uri = "https://prod.api.pvp.net/api/lol/#{region}/v1.3/game/by-summoner/#{id}/recent"
response = _get_api_response(uri)
_parse_response(response) { |resp|
data = JSON.parse(resp)
history = MatchHistory.new(data)
if block_given?
yield history
else
return history
end
}
end | ruby | {
"resource": ""
} |
q25971 | Cratus.User.disable | validation | def disable
if enabled?
Cratus::LDAP.replace_attribute(
dn,
Cratus.config.user_account_control_attribute,
['514']
)
refresh
else
true
end
end | ruby | {
"resource": ""
} |
q25972 | Cratus.User.enable | validation | def enable
if disabled?
Cratus::LDAP.replace_attribute(
dn,
Cratus.config.user_account_control_attribute,
['512']
)
refresh
else
true
end
end | ruby | {
"resource": ""
} |
q25973 | Cratus.User.unlock | validation | def unlock
if locked? && enabled?
Cratus::LDAP.replace_attribute(
dn,
Cratus.config.user_lockout_attribute,
['0']
)
refresh
elsif disabled?
false
else
true
end
end | ruby | {
"resource": ""
} |
q25974 | CaTissue.SpecimenPosition.saver_proxy | validation | def saver_proxy
# Look for a transfer event that matches the position.
xfr = specimen.event_parameters.detect do |sep|
CaTissue::TransferEventParameters === sep and sep.to == location
end
# Create a new transfer event, if necessary.
xfr ||= CaTissue::TransferEventParameters.new(:specimen => specimen, :to => location)
# If this position changed, then copy the original position to the transfer event from attributes.
if snapshot and changed? then
xfr.from_storage_container = snapshot[:storage_container]
xfr.from_position_dimension_one = snapshot[:position_dimension_one]
xfr.from_position_dimension_two = snapshot[:position_dimension_two]
end
xfr
end | ruby | {
"resource": ""
} |
q25975 | Steamd.CodeGenerator.generate | validation | def generate
make_output_directory
files.each do |file|
File.write("#{@output}/#{File.basename(file, '.*')}.rb",
Steamd::Generator::Ruby.new(file).run)
end
end | ruby | {
"resource": ""
} |
q25976 | YahooContentAnalysis.Configuration.reset! | validation | def reset!
self.api_key = DEFAULT_API_KEY
self.api_secret = DEFAULT_API_SECRET
self.adapter = DEFAULT_ADAPTER
self.endpoint = DEFAULT_ENDPOINT
self.user_agent = DEFAULT_USER_AGENT
self.format = DEFAULT_FORMAT
self.max = DEFAULT_MAX
self.related_entities = DEFAULT_RELATED_ENTITIES
self.show_metadata = DEFAULT_SHOW_METADATA
self.enable_categorizer = DEFAULT_ENABLE_CATEGORIZER
self.unique = DEFAULT_UNIQUE
self
end | ruby | {
"resource": ""
} |
q25977 | Sycsvpro.Merger.execute | validation | def execute
File.open(outfile, 'w') do |out|
out.puts "#{';' unless @key.empty?}#{header_cols.join(';')}"
files.each do |file|
@current_key = create_current_key
@current_source_header = @source_header.shift
processed_header = false
File.open(file).each_with_index do |line, index|
next if line.chomp.empty?
unless processed_header
create_file_header unstring(line).split(';')
processed_header = true
next
end
out.puts create_line unstring(line).split(';')
end
end
end
end | ruby | {
"resource": ""
} |
q25978 | Sycsvpro.Merger.create_file_header | validation | def create_file_header(columns)
columns.each_with_index do |c,i|
next if i == @current_key
columns[i] = c.scan(Regexp.new(@current_source_header)).flatten[0]
end
@file_header = @current_key ? [@current_key.to_i] : []
header_cols.each do |h|
@file_header << columns.index(h)
end
@file_header.compact!
end | ruby | {
"resource": ""
} |
q25979 | CaTissue.ConsentTierStatus.statement_match? | validation | def statement_match?(other)
ct = consent_tier
oct = other.consent_tier
ct.nil? or oct.nil? or ct.identifier == oct.identifier or ct.statement == oct.statement
end | ruby | {
"resource": ""
} |
q25980 | Sycsvpro.ColumnFilter.process | validation | def process(object, options={})
return nil if object.nil? or object.empty?
object = object.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
object += " " if object =~ /;$/
return object if filter.empty? and pivot.empty?
filtered = object.split(';').values_at(*filter.flatten.uniq)
pivot_each_column(object.split(';')) do |column, match|
filtered << column if match
end
if !filtered.last.nil? and filtered.last.empty?
filtered.compact.join(';') + " "
else
filtered.compact.join(';')
end
end | ruby | {
"resource": ""
} |
q25981 | CaTissue.StorageContainer.add | validation | def add(storable, *coordinate)
return add_local(storable, *coordinate) unless coordinate.empty?
add_to_existing_container(storable) or add_to_new_subcontainer(storable) or out_of_bounds(storable)
self
end | ruby | {
"resource": ""
} |
q25982 | CaTissue.StorageContainer.find_subcontainer | validation | def find_subcontainer(name, type)
logger.debug { "Finding box with name #{name}..." }
ctr = CaTissue::StorageContainer.new(:name => name)
if ctr.find then
logger.debug { "Container found: #{ctr}." }
else
logger.debug { "Container not found: #{name}." }
create_subcontainer(name, type)
end
box
end | ruby | {
"resource": ""
} |
q25983 | CaTissue.StorageContainer.add_to_existing_container | validation | def add_to_existing_container(storable)
if storage_type.nil? then
raise Jinx::ValidationError.new("Cannot add #{storable.qp} to #{qp} with missing storage type")
end
# the subcontainers in column, row sort order
scs = subcontainers.sort { |sc1, sc2| sc1.position.coordinate <=> sc2.position.coordinate }
logger.debug { "Looking for a #{self} subcontainer from among #{scs.pp_s} to place #{storable.qp}..." } unless scs.empty?
# The first subcontainer that can hold the storable is preferred.
sc = scs.detect do |sc|
# Check for circular reference. This occurred as a result of the caTissue bug described
# in CaTissue::Database#query_object. The work-around circumvents the bug for now, but
# it doesn't hurt to check again.
if identifier and sc.identifier == identifier then
raise Jinx::ValidationError.new("#{self} has a circular containment reference to subcontainer #{sc}")
end
# No circular reference; add to subcontainer if possible.
sc.add_to_existing_container(storable) if StorageContainer === sc
end
if sc then
logger.debug { "#{self} subcontainer #{sc} stored #{storable.qp}." }
self
elsif can_hold_child?(storable) then
logger.debug { "#{self} can hold #{storable.qp}." }
add_local(storable)
else
logger.debug { "Neither #{self} of type #{storage_type.name} nor its subcontainers can hold #{storable.qp}." }
nil
end
end | ruby | {
"resource": ""
} |
q25984 | CaTissue.StorageContainer.add_to_new_subcontainer | validation | def add_to_new_subcontainer(storable)
# the subcontainers in column, row sort order
scs = subcontainers.sort { |sc1, sc2| sc1.position.coordinate <=> sc2.position.coordinate }
logger.debug { "Looking for a #{self} subcontainer #{scs} to place a new #{storable.qp} container..." } unless scs.empty?
# The first subcontainer that can hold the new subcontainer is preferred.
sc = scs.detect { |sc| sc.add_to_new_subcontainer(storable) if StorageContainer === sc }
if sc then
logger.debug { "#{self} subcontainer #{sc} stored #{storable.qp}." }
self
elsif not full? then
logger.debug { "Creating a subcontainer in #{self} of type #{storage_type} to hold #{storable.qp}..." }
create_subcontainer_for(storable)
end
end | ruby | {
"resource": ""
} |
q25985 | CaTissue.StorageContainer.type_path_to | validation | def type_path_to(storable)
shortest = nil
holds_storage_types.each do |st|
stp = st.path_to(storable) || next
shortest = stp if shortest.nil? or stp.size < shortest.size
end
shortest
end | ruby | {
"resource": ""
} |
q25986 | Turntabler.Resource.attributes= | validation | def attributes=(attributes)
if attributes
attributes.each do |attribute, value|
attribute = attribute.to_s
if attribute == 'metadata'
self.attributes = value
else
__send__("#{attribute}=", value) if respond_to?("#{attribute}=", true)
end
end
end
end | ruby | {
"resource": ""
} |
q25987 | Turntabler.Avatar.available? | validation | def available?
client.user.points >= minimum_points && (!acl || client.user.acl >= acl)
end | ruby | {
"resource": ""
} |
q25988 | Turntabler.Avatar.set | validation | def set
api('user.set_avatar', :avatarid => id)
client.user.attributes = {'avatarid' => id}
client.user.avatar.attributes = {'min' => minimum_points, 'acl' => acl}
true
end | ruby | {
"resource": ""
} |
q25989 | Sightstone.ChampionModule.champions | validation | def champions(optional={})
region = optional[:region] || @sightstone.region
free_to_play = optional[:free_to_play] || false
uri = "https://prod.api.pvp.net/api/lol/#{region}/v1.1/champion"
response = _get_api_response(uri, {'freeToPlay' => free_to_play})
_parse_response(response) { |resp|
data = JSON.parse(resp)
champions = []
data['champions'].each do |champ|
champions << Champion.new(champ)
end
if block_given?
yield champions
else
return champions
end
}
end | ruby | {
"resource": ""
} |
q25990 | MetaManager.Taggable.meta_tag | validation | def meta_tag(attr_name, options={})
key = normalize_meta_tag_name(attr_name)
cached_meta_tags[key] ||= self.meta_tags.detect {|t| t.name == key}
cached_meta_tags[key] ||= self.meta_tags.build(:name => key) if options[:build]
cached_meta_tags[key]
end | ruby | {
"resource": ""
} |
q25991 | Sycsvpro.Mapper.init_col_filter | validation | def init_col_filter(columns, source)
if columns.nil?
File.open(source, 'r').each do |line|
line = unstring(line)
next if line.empty?
line += ' ' if line =~ /;$/
size = line.split(';').size
columns = "0-#{size-1}"
break
end
end
ColumnFilter.new(columns).filter.flatten
end | ruby | {
"resource": ""
} |
q25992 | CaTissue.Metadata.add_annotation | validation | def add_annotation(name, opts={})
# the module symbol
mod_sym = name.camelize.to_sym
# the module spec defaults
pkg = opts[:package] ||= name.underscore
svc = opts[:service] ||= name.underscore
grp = opts[:group] ||= pkg
pxy_nm = opts[:proxy_name] || "#{self.name.demodulize}RecordEntry"
self.annotation_proxy_class_name = pxy_nm
# add the annotation entry
@ann_spec_hash ||= {}
@ann_spec_hash[mod_sym] = opts
logger.info("Added #{qp} annotation #{name} with module #{mod_sym}, package #{pkg}, service #{svc} and group #{grp}.")
end | ruby | {
"resource": ""
} |
q25993 | CaTissue.Metadata.load_local_annotations | validation | def load_local_annotations
return Array::EMPTY_ARRAY if @ann_spec_hash.nil?
# an annotated class has a hook entity id
initialize_annotation_holder
# build the annotations
@ann_spec_hash.map { |name, opts| import_annotation(name, opts) }
end | ruby | {
"resource": ""
} |
q25994 | CaTissue.Metadata.import_annotation | validation | def import_annotation(name, opts)
logger.debug { "Importing #{qp} annotation #{name}..." }
# Make the annotation module class scoped by this Annotatable class.
class_eval("module #{name}; end")
mod = const_get(name)
# Append the AnnotationModule methods.
mod.extend(Annotation::Importer)
# Build the annnotation module.
mod.initialize_annotation(self, opts) { |pxy| create_proxy_attribute(mod, pxy) }
mod
end | ruby | {
"resource": ""
} |
q25995 | CMS.ViewablesController.create | validation | def create
current_count = UniqueKey.where(list_key_params).count
if params[:max] == 'Infinity' || current_count < params[:max].to_i
unique_key = list_key_params.merge(position: current_count + 1)
viewable = UniqueKey.create_localized_viewable!(unique_key)
if unique_key[:viewable_type] != 'Viewable::Block'
path = rails_admin.edit_path(model_name: unique_key[:viewable_type].to_s.underscore.gsub('/', '~'), id: viewable.id)
redirect_to path
else
redirect_to :back
end
else
redirect_to :back
end
end | ruby | {
"resource": ""
} |
q25996 | Sycsvpro.Header.process | validation | def process(line, values = true)
return "" if @header_cols.empty? && @insert_cols.empty?
header_patterns = {}
@row_cols = unstring(line).split(';')
if @header_cols[0] == '*'
@header_cols[0] = @row_cols
else
@header_cols.each_with_index do |h,i|
if h =~ /^\(?c\d+(?:[=~]{,2}).*$/
if col = eval(h)
last_eval = $1
unless @header_cols.index(last_eval) || @header_cols.index(col)
if values
@header_cols[i] = (h =~ /^\(?c\d+=~/) ? last_eval : col
header_patterns[i+1] = h if h =~ /^\(?c\d+[=~+-.]{1,2}/
else
@header_cols[i] = col if h =~ /^\(?c\d+$/
end
end
end
else
@header_cols[i] = h
end
end
end
insert_header_cols
header_patterns.each { |i,h| @header_cols.insert(i,h) }
to_s
end | ruby | {
"resource": ""
} |
q25997 | Turntabler.Room.load | validation | def load(options = {})
assert_valid_keys(options, :song_log)
options = {:song_log => false}.merge(options)
# Use a client that is connected on the same url this room is hosted on
client = @client.url == url ? @client : Turntabler::Client.new(@client.user.id, @client.user.auth, :url => url, :timeout => @client.timeout)
begin
data = api('room.info', :extended => options[:song_log])
self.attributes = data['room'].merge('users' => data['users'])
super()
ensure
# Close the client if it was only opened for use in this API call
client.close if client != @client
end
end | ruby | {
"resource": ""
} |
q25998 | Turntabler.Room.attributes= | validation | def attributes=(attrs)
if attrs
super('users' => attrs.delete('users')) if attrs['users']
super
# Set room-level attributes that are specific to the song
song_attributes = attrs['metadata'] && attrs['metadata'].select {|key, value| %w(upvotes downvotes votelog).include?(key)}
current_song.attributes = song_attributes if @current_song
end
end | ruby | {
"resource": ""
} |
q25999 | Turntabler.Room.enter | validation | def enter
if client.room != self
# Leave the old room
client.room.leave if client.room
# Connect and register with this room
client.connect(url)
begin
client.room = self
data = api('room.register', :section => nil)
self.attributes = {'section' => data['section']}
rescue Exception
client.room = nil
raise
end
end
true
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.