_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 30
4.3k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q25200
|
Spidr.Agent.visit?
|
validation
|
def visit?(url)
!visited?(url) &&
visit_scheme?(url.scheme) &&
visit_host?(url.host) &&
visit_port?(url.port) &&
visit_link?(url.to_s) &&
|
ruby
|
{
"resource": ""
}
|
q25201
|
Spidr.Rules.accept?
|
validation
|
def accept?(data)
unless @accept.empty?
@accept.any? { |rule| test_data(data,rule)
|
ruby
|
{
"resource": ""
}
|
q25202
|
Spidr.Agent.every_html_doc
|
validation
|
def every_html_doc
every_page do |page|
if (block_given? && page.html?)
if (doc = page.doc)
|
ruby
|
{
"resource": ""
}
|
q25203
|
Spidr.Agent.every_xml_doc
|
validation
|
def every_xml_doc
every_page do |page|
if (block_given? && page.xml?)
if (doc = page.doc)
|
ruby
|
{
"resource": ""
}
|
q25204
|
Spidr.Agent.every_rss_doc
|
validation
|
def every_rss_doc
every_page do |page|
if (block_given? && page.rss?)
if (doc = page.doc)
|
ruby
|
{
"resource": ""
}
|
q25205
|
Spidr.Agent.every_atom_doc
|
validation
|
def every_atom_doc
every_page do |page|
if (block_given? && page.atom?)
if (doc = page.doc)
|
ruby
|
{
"resource": ""
}
|
q25206
|
Spidr.Agent.initialize_filters
|
validation
|
def initialize_filters(options={})
@schemes = []
if options[:schemes]
self.schemes = options[:schemes]
else
@schemes << 'http'
begin
require 'net/https'
@schemes << 'https'
rescue Gem::LoadError => e
raise(e)
rescue ::LoadError
warn "Warning: cannot load 'net/https', https support disabled"
end
end
@host_rules = Rules.new(
accept: options[:hosts],
reject: options[:ignore_hosts]
)
@port_rules = Rules.new(
accept: options[:ports],
reject: options[:ignore_ports]
)
|
ruby
|
{
"resource": ""
}
|
q25207
|
Spidr.Page.each_meta_redirect
|
validation
|
def each_meta_redirect
return enum_for(__method__) unless block_given?
if (html? && doc)
search('//meta[@http-equiv and @content]').each do |node|
if node.get_attribute('http-equiv') =~ /refresh/i
content = node.get_attribute('content')
|
ruby
|
{
"resource": ""
}
|
q25208
|
Spidr.Page.each_redirect
|
validation
|
def each_redirect(&block)
return enum_for(__method__) unless block
if (locations = @response.get_fields('Location'))
# Location headers override any
|
ruby
|
{
"resource": ""
}
|
q25209
|
Spidr.Page.each_link
|
validation
|
def each_link
return enum_for(__method__) unless block_given?
filter = lambda { |url|
yield url unless (url.nil? || url.empty?)
}
each_redirect(&filter) if is_redirect?
if (html? && doc)
doc.search('//a[@href]').each do |a|
filter.call(a.get_attribute('href'))
end
|
ruby
|
{
"resource": ""
}
|
q25210
|
Spidr.Page.each_url
|
validation
|
def each_url
return enum_for(__method__) unless block_given?
|
ruby
|
{
"resource": ""
}
|
q25211
|
Spidr.Page.to_absolute
|
validation
|
def to_absolute(link)
link = link.to_s
new_url = begin
url.merge(link)
rescue Exception
return
end
if (!new_url.opaque) && (path = new_url.path)
# ensure that paths begin with a leading '/' for URI::FTP
if (new_url.scheme == 'ftp' && !path.start_with?('/'))
path.insert(0,'/')
|
ruby
|
{
"resource": ""
}
|
q25212
|
Roar.HttpVerbs.post
|
validation
|
def post(options={}, &block)
response = http.post_uri(options.merge(:body => serialize),
|
ruby
|
{
"resource": ""
}
|
q25213
|
Roar.HttpVerbs.get
|
validation
|
def get(options={}, &block)
response = http.get_uri(options, &block)
|
ruby
|
{
"resource": ""
}
|
q25214
|
Roar.HttpVerbs.put
|
validation
|
def put(options={}, &block)
response = http.put_uri(options.merge(:body
|
ruby
|
{
"resource": ""
}
|
q25215
|
Chain.Query.each
|
validation
|
def each
page = fetch(@first_query)
loop do
if page['items'].empty? # we consume this array as we iterate
break if page['last_page']
page = fetch(page['next'])
# The second predicate (empty?) *should* be redundant, but we check it
# anyway as
|
ruby
|
{
"resource": ""
}
|
q25216
|
Chain.HSMSigner.sign
|
validation
|
def sign(tx_template)
return tx_template if @xpubs_by_signer.empty?
@xpubs_by_signer.each do |signer_conn, xpubs|
tx_template = signer_conn.singleton_batch_request(
'/sign-transaction',
|
ruby
|
{
"resource": ""
}
|
q25217
|
Chain.HSMSigner.sign_batch
|
validation
|
def sign_batch(tx_templates)
if @xpubs_by_signer.empty?
# Treat all templates as if signed successfully.
successes = tx_templates.each_with_index.reduce({}) do |memo, (t, i)|
memo[i] = t
memo
end
BatchResponse.new(successes: successes)
end
# We need to work towards a single, final BatchResponse that uses the
# original indexes. For the next cycle, we should retain only those
# templates for which the most recent sign response was successful, and
# maintain a mapping of each template's index in the upcoming request
# to its original index.
orig_index = (0...tx_templates.size).to_a
errors = {}
@xpubs_by_signer.each do |signer_conn, xpubs|
next_tx_templates = []
next_orig_index = []
batch = signer_conn.batch_request(
'/sign-transaction',
transactions: tx_templates,
xpubs: xpubs,
) { |item| Transaction::Template.new(item) }
batch.successes.each do |i, template|
next_tx_templates << template
next_orig_index << orig_index[i]
|
ruby
|
{
"resource": ""
}
|
q25218
|
FHIR.Client.set_no_auth
|
validation
|
def set_no_auth
FHIR.logger.info 'Configuring the client to use no authentication.'
@use_oauth2_auth = false
@use_basic_auth = false
@security_headers
|
ruby
|
{
"resource": ""
}
|
q25219
|
FHIR.Client.set_basic_auth
|
validation
|
def set_basic_auth(client, secret)
FHIR.logger.info 'Configuring the client to use HTTP Basic authentication.'
token = Base64.encode64("#{client}:#{secret}")
|
ruby
|
{
"resource": ""
}
|
q25220
|
FHIR.Client.set_bearer_token
|
validation
|
def set_bearer_token(token)
FHIR.logger.info 'Configuring the client to use Bearer Token authentication.'
value = "Bearer #{token}"
@security_headers = { 'Authorization' => value }
|
ruby
|
{
"resource": ""
}
|
q25221
|
FHIR.Client.request_payload
|
validation
|
def request_payload(resource, headers)
if headers
format_specified = headers['Content-Type']
if format_specified.nil?
resource.to_xml
elsif format_specified.downcase.include?('xml')
resource.to_xml
|
ruby
|
{
"resource": ""
}
|
q25222
|
IPAddress.IPv4.split
|
validation
|
def split(subnets=2)
unless (1..(2**@prefix.host_prefix)).include? subnets
raise ArgumentError, "Value #{subnets} out of range"
end
networks
|
ruby
|
{
"resource": ""
}
|
q25223
|
IPAddress.IPv4.supernet
|
validation
|
def supernet(new_prefix)
raise ArgumentError, "New prefix must be smaller than existing prefix" if new_prefix >= @prefix.to_i
|
ruby
|
{
"resource": ""
}
|
q25224
|
IPAddress.IPv4.subnet
|
validation
|
def subnet(subprefix)
unless ((@prefix.to_i)..32).include? subprefix
raise ArgumentError, "New prefix must be between #@prefix and 32"
end
Array.new(2**([email protected]_i))
|
ruby
|
{
"resource": ""
}
|
q25225
|
IPAddress.Prefix.-
|
validation
|
def -(oth)
if oth.is_a? Integer
self.prefix -
|
ruby
|
{
"resource": ""
}
|
q25226
|
Chatterbot.DSL.bot
|
validation
|
def bot
return @bot unless @bot.nil?
@bot_command = nil
#
# parse any command-line options and use them to initialize the bot
#
params = {}
#:nocov:
opts = OptionParser.new
opts.banner = "Usage: #{File.basename($0)} [options]"
opts.separator ""
opts.separator "Specific options:"
opts.on('-c', '--config [ARG]', "Specify a config file to use") { |c| ENV["chatterbot_config"] = c }
opts.on('-t', '--test', "Run the bot without actually sending any tweets") { params[:debug_mode] = true }
opts.on('-v', '--verbose', "verbose output to stdout") { params[:verbose] = true }
opts.on('--dry-run', "Run the bot in test mode, and also don't update the database") { params[:debug_mode] = true ; params[:no_update] = true }
opts.on('-r', '--reset', "Reset your bot to ignore old tweets") {
@bot_command = :reset_since_id_counters
}
|
ruby
|
{
"resource": ""
}
|
q25227
|
Chatterbot.DSL.blocklist
|
validation
|
def blocklist(*args)
list = flatten_list_of_strings(args)
if list.nil?
|
ruby
|
{
"resource": ""
}
|
q25228
|
Chatterbot.DSL.safelist
|
validation
|
def safelist(*args)
list = flatten_list_of_strings(args)
if list.nil?
|
ruby
|
{
"resource": ""
}
|
q25229
|
Chatterbot.DSL.exclude
|
validation
|
def exclude(*args)
e = flatten_list_of_strings(args)
if e.nil? || e.empty?
bot.exclude = []
|
ruby
|
{
"resource": ""
}
|
q25230
|
Chatterbot.DSL.consumer_secret
|
validation
|
def consumer_secret(s)
bot.deprecated "Setting consumer_secret outside of your config file
|
ruby
|
{
"resource": ""
}
|
q25231
|
Chatterbot.DSL.consumer_key
|
validation
|
def consumer_key(k)
bot.deprecated "Setting consumer_key outside
|
ruby
|
{
"resource": ""
}
|
q25232
|
Chatterbot.DSL.secret
|
validation
|
def secret(s)
bot.deprecated "Setting access_token_secret outside of your config file
|
ruby
|
{
"resource": ""
}
|
q25233
|
Chatterbot.DSL.token
|
validation
|
def token(s)
bot.deprecated "Setting access_token outside of your config file is
|
ruby
|
{
"resource": ""
}
|
q25234
|
Chatterbot.DSL.flatten_list_of_strings
|
validation
|
def flatten_list_of_strings(args)
args.collect do |b|
if b.is_a?(String)
# string, split on commas and turn into array
b.split(",").collect { |s|
|
ruby
|
{
"resource": ""
}
|
q25235
|
Chatterbot.Favorite.favorite
|
validation
|
def favorite(id=@current_tweet)
return if require_login == false
id = id_from_tweet(id)
#:nocov:
if debug_mode?
debug "I'm
|
ruby
|
{
"resource": ""
}
|
q25236
|
Chatterbot.HomeTimeline.home_timeline
|
validation
|
def home_timeline(*args, &block)
return unless require_login
debug "check for home_timeline tweets since #{since_id_home_timeline}"
opts = {
:since_id => since_id_home_timeline,
:count => 200
}
results = client.home_timeline(opts)
@current_tweet = nil
|
ruby
|
{
"resource": ""
}
|
q25237
|
Chatterbot.Safelist.on_safelist?
|
validation
|
def on_safelist?(s)
search = from_user(s).downcase
safelist.any? { |b|
|
ruby
|
{
"resource": ""
}
|
q25238
|
Chatterbot.Search.search
|
validation
|
def search(queries, opts = {}, &block)
debug "check for tweets since #{since_id}"
max_tweets = opts.delete(:limit) || MAX_SEARCH_TWEETS
exact_match = if opts.key?(:exact)
opts.delete(:exact)
else
true
end
if queries.is_a?(String)
queries = [
queries
|
ruby
|
{
"resource": ""
}
|
q25239
|
Chatterbot.Tweet.tweet
|
validation
|
def tweet(txt, params = {}, original = nil)
return if require_login == false
txt = replace_variables(txt, original)
if debug_mode?
debug "I'm in debug mode, otherwise I would tweet: #{txt}"
else
debug txt
|
ruby
|
{
"resource": ""
}
|
q25240
|
Chatterbot.Tweet.reply
|
validation
|
def reply(txt, source, params = {})
debug txt
params
|
ruby
|
{
"resource": ""
}
|
q25241
|
Chatterbot.DirectMessages.direct_message
|
validation
|
def direct_message(txt, user=nil)
return unless require_login
if user.nil?
user = current_user
|
ruby
|
{
"resource": ""
}
|
q25242
|
Chatterbot.DirectMessages.direct_messages
|
validation
|
def direct_messages(opts = {}, &block)
return unless require_login
debug "check for DMs since #{since_id_dm}"
#
# search twitter
#
@current_tweet = nil
client.direct_messages_received(since_id:since_id_dm, count:200).each { |s|
update_since_id_dm(s)
debug s.text
if has_safelist? && !on_safelist?(s.sender)
debug "skipping because user
|
ruby
|
{
"resource": ""
}
|
q25243
|
Chatterbot.UI.get_oauth_verifier
|
validation
|
def get_oauth_verifier
green "****************************************"
green "****************************************"
green "**** BOT AUTH TIME! ****"
green "****************************************"
green "****************************************"
puts "You need to authorize your bot with Twitter.\n\nPlease login to Twitter under the bot's account. When you're ready, hit Enter.\n\nYour browser will open with the following URL, where you can authorize the bot.\n\n"
url = request_token.authorize_url
puts url
puts "\nIf that doesn't work, you can open the URL in your browser manually."
puts "\n\nHit enter to start.\n\n"
|
ruby
|
{
"resource": ""
}
|
q25244
|
Chatterbot.UI.get_api_key
|
validation
|
def get_api_key
green "****************************************"
green "****************************************"
green "**** API SETUP TIME! ****"
green "****************************************"
green "****************************************"
puts "\n\nWelcome to Chatterbot. Let's walk through the steps to get a bot running.\n\n"
#
# At this point, we don't have any API credentials at all for
# this bot, but it's possible the user has already setup an app.
# Let's ask!
#
puts "Hey, looks like you need to get an API key from Twitter before you can get started.\n\n"
app_already_exists = ask_yes_no("Have you already set up an app with Twitter?")
if app_already_exists
puts "Terrific! Let's get your bot running!\n\n"
else
puts "OK, I can help with that!\n\n"
send_to_app_creation
end
print "\n\nPaste the 'Consumer Key' here: "
STDOUT.flush
config[:consumer_key] = STDIN.readline.chomp.strip
print "Paste the 'Consumer Secret' here: "
STDOUT.flush
config[:consumer_secret] = STDIN.readline.chomp.strip
puts "\n\nNow it's time to authorize your bot!\n\n"
if ! app_already_exists && ask_yes_no("Do you want to authorize a bot using the account that created the app?")
puts "OK,
|
ruby
|
{
"resource": ""
}
|
q25245
|
Chatterbot.Config.max_id_from
|
validation
|
def max_id_from(s)
if ! s.respond_to?(:max)
if s.respond_to?(:id)
return s.id
else
return s
end
|
ruby
|
{
"resource": ""
}
|
q25246
|
Chatterbot.Config.slurp_file
|
validation
|
def slurp_file(f)
f = File.expand_path(f)
tmp = {}
if File.exist?(f)
|
ruby
|
{
"resource": ""
}
|
q25247
|
Chatterbot.Config.global_config
|
validation
|
def global_config
tmp = {}
global_config_files.each { |f|
|
ruby
|
{
"resource": ""
}
|
q25248
|
Chatterbot.Config.bot_config
|
validation
|
def bot_config
{
:consumer_key => ENV["chatterbot_consumer_key"],
:consumer_secret => ENV["chatterbot_consumer_secret"],
:access_token => ENV["chatterbot_access_token"],
|
ruby
|
{
"resource": ""
}
|
q25249
|
Chatterbot.Config.load_config
|
validation
|
def load_config(params={})
read_only_data = global_config.merge(bot_config).merge(params)
|
ruby
|
{
"resource": ""
}
|
q25250
|
Chatterbot.Retweet.retweet
|
validation
|
def retweet(id=@current_tweet)
return if require_login == false || id.nil?
id = id_from_tweet(id)
#:nocov:
if debug_mode?
debug "I'm
|
ruby
|
{
"resource": ""
}
|
q25251
|
Chatterbot.Bot.run!
|
validation
|
def run!
before_run
HANDLER_CALLS.each { |c|
if (h = @handlers[c])
send(c, *(h.opts)) do |obj|
|
ruby
|
{
"resource": ""
}
|
q25252
|
Chatterbot.Reply.replies
|
validation
|
def replies(*args, &block)
return unless require_login
debug "check for replies since #{since_id_reply}"
opts = {
:since_id => since_id_reply,
:count => 200
}
results = client.mentions_timeline(opts)
@current_tweet = nil
results.each { |s|
|
ruby
|
{
"resource": ""
}
|
q25253
|
Chatterbot.Blocklist.skip_me?
|
validation
|
def skip_me?(s)
search = s.respond_to?(:text) ? s.text : s
exclude.detect
|
ruby
|
{
"resource": ""
}
|
q25254
|
Chatterbot.Blocklist.on_blocklist?
|
validation
|
def on_blocklist?(s)
search = if s.is_a?(Twitter::User)
s.name
elsif s.respond_to?(:user) && !s.is_a?(Twitter::NullObject)
from_user(s)
else
|
ruby
|
{
"resource": ""
}
|
q25255
|
Chatterbot.Client.reset_since_id
|
validation
|
def reset_since_id
config[:since_id] = 1
# do a search of recent tweets with the letter 'a' in them to
# get a rough max tweet id
|
ruby
|
{
"resource": ""
}
|
q25256
|
Chatterbot.Client.generate_authorize_url
|
validation
|
def generate_authorize_url(request_token)
request = consumer.create_signed_request(:get,
consumer.authorize_path, request_token,
{:oauth_callback => 'oob'})
params = request['Authorization'].sub(/^OAuth\s+/, '').split(/,\s+/).map do |param|
|
ruby
|
{
"resource": ""
}
|
q25257
|
Chatterbot.Client.get_screen_name
|
validation
|
def get_screen_name(t = @access_token)
return unless @screen_name.nil?
return if t.nil?
oauth_response =
|
ruby
|
{
"resource": ""
}
|
q25258
|
Chatterbot.Client.login
|
validation
|
def login(do_update_config=true)
if needs_api_key?
get_api_key
end
if needs_auth_token?
pin = get_oauth_verifier
return false if pin.nil?
begin
# this will throw an error that we can try and catch
@access_token = request_token.get_access_token(:oauth_verifier => pin.chomp)
get_screen_name
self.config[:access_token] = @access_token.token
|
ruby
|
{
"resource": ""
}
|
q25259
|
Voom.ContainerMethods.reset!
|
validation
|
def reset!
registered_keys.each { |key| ClassConstants.new(key).deconstantize
|
ruby
|
{
"resource": ""
}
|
q25260
|
Voom.Symbol.class_name
|
validation
|
def class_name(classname)
classname = sym_to_str(classname)
|
ruby
|
{
"resource": ""
}
|
q25261
|
Zlib.ZWriter.close
|
validation
|
def close
flush()
@deflate_buffer << @deflater.finish unless @deflater.finished?
begin
until @deflate_buffer.empty? do
@deflate_buffer.slice!(0, delegate.write(@deflate_buffer))
end
rescue Errno::EAGAIN, Errno::EINTR
retry if write_ready?
end
|
ruby
|
{
"resource": ""
}
|
q25262
|
Archive.DOSTime.to_time
|
validation
|
def to_time
second = ((0b11111 & @dos_time) ) * 2
minute = ((0b111111 << 5 & @dos_time) >> 5)
hour = ((0b11111 << 11 & @dos_time) >> 11)
day = ((0b11111 << 16 & @dos_time) >> 16)
month = ((0b1111 <<
|
ruby
|
{
"resource": ""
}
|
q25263
|
Archive.Zip.each
|
validation
|
def each(&b)
raise IOError, 'non-readable archive' unless readable?
raise IOError, 'closed archive' if closed?
unless @parse_complete then
|
ruby
|
{
"resource": ""
}
|
q25264
|
Archive.Zip.add_entry
|
validation
|
def add_entry(entry)
raise IOError, 'non-writable archive' unless writable?
raise IOError, 'closed archive' if closed?
unless entry.kind_of?(Entry) then
|
ruby
|
{
"resource": ""
}
|
q25265
|
Archive.Zip.extract
|
validation
|
def extract(destination, options = {})
raise IOError, 'non-readable archive' unless readable?
raise IOError, 'closed archive' if closed?
# Ensure that unspecified options have default values.
options[:directories] = true unless options.has_key?(:directories)
options[:symlinks] = false unless options.has_key?(:symlinks)
options[:overwrite] = :all unless options[:overwrite] == :older ||
options[:overwrite] == :never
options[:create] = true unless options.has_key?(:create)
options[:flatten] = false unless options.has_key?(:flatten)
# Flattening the archive structure implies that directory entries are
# skipped.
options[:directories] = false if options[:flatten]
# First extract all non-directory entries.
directories = []
each do |entry|
# Compute the target file path.
file_path = entry.zip_path
file_path = File.basename(file_path) if options[:flatten]
file_path = File.join(destination, file_path)
# Cache some information about the file path.
file_exists = File.exist?(file_path)
file_mtime = File.mtime(file_path) if file_exists
begin
# Skip this entry if so directed.
if (! file_exists && ! options[:create]) ||
(file_exists &&
(options[:overwrite] == :never ||
options[:overwrite] == :older && entry.mtime <= file_mtime)) ||
(! options[:exclude].nil? && options[:exclude][entry]) then
next
end
# Set the decryption key for the entry.
if options[:password].kind_of?(String) then
entry.password = options[:password]
elsif ! options[:password].nil? then
entry.password = options[:password][entry]
end
if entry.directory? then
# Record the directories as they are encountered.
directories << entry
elsif entry.file? || (entry.symlink? && options[:symlinks]) then
# Extract files and symlinks.
entry.extract(
|
ruby
|
{
"resource": ""
}
|
q25266
|
Archive.Zip.find_central_directory
|
validation
|
def find_central_directory(io)
# First find the offset to the end of central directory record.
# It is expected that the variable length comment field will usually be
# empty and as a result the initial value of eocd_offset is all that is
# necessary.
#
# NOTE: A cleverly crafted comment could throw this thing off if the
# comment itself looks like a valid end of central directory record.
eocd_offset = -22
loop do
io.seek(eocd_offset, IO::SEEK_END)
if IOExtensions.read_exactly(io, 4) == EOCD_SIGNATURE then
|
ruby
|
{
"resource": ""
}
|
q25267
|
Archive.Zip.dump
|
validation
|
def dump(io)
bytes_written = 0
@entries.each do |entry|
bytes_written += entry.dump_local_file_record(io, bytes_written)
end
central_directory_offset = bytes_written
@entries.each do |entry|
bytes_written += entry.dump_central_file_record(io)
end
central_directory_length = bytes_written - central_directory_offset
bytes_written += io.write(EOCD_SIGNATURE)
bytes_written += io.write(
[
0,
0,
@entries.length,
|
ruby
|
{
"resource": ""
}
|
q25268
|
Effective.Datatable.view=
|
validation
|
def view=(view)
@view = (view.respond_to?(:view_context) ? view.view_context : view)
raise 'expected view to respond to params' unless @view.respond_to?(:params)
load_cookie!
assert_cookie!
load_attributes!
# We need early access to filter and scope, to define defaults from the model first
# This means filters do knows about attributes but not about columns.
initialize_filters if respond_to?(:initialize_filters)
load_filters!
load_state!
# Bulk actions called first so it can add the bulk_actions_col first
initialize_bulk_actions if respond_to?(:initialize_bulk_actions)
# Now we initialize all the columns. columns knows about attributes and filters and scope
initialize_datatable if respond_to?(:initialize_datatable)
load_columns!
# Execute any additional DSL methods
initialize_charts if respond_to?(:initialize_charts)
|
ruby
|
{
"resource": ""
}
|
q25269
|
Effective.DatatablesController.show
|
validation
|
def show
begin
@datatable = EffectiveDatatables.find(params[:id])
@datatable.view = view_context
EffectiveDatatables.authorize!(self, :index, @datatable.collection_class)
|
ruby
|
{
"resource": ""
}
|
q25270
|
Plezi.Renderer.register
|
validation
|
def register(extention, handler = nil, &block)
handler ||= block
raise 'Handler
|
ruby
|
{
"resource": ""
}
|
q25271
|
Plezi.Controller.requested_method
|
validation
|
def requested_method
params['_method'.freeze] = (params['_method'.freeze] || request.request_method.downcase).to_sym
|
ruby
|
{
"resource": ""
}
|
q25272
|
Plezi.Controller.send_data
|
validation
|
def send_data(data, options = {})
response.write data if data
filename = options[:filename]
# set headers
content_disposition = options[:inline] ? 'inline'.dup : 'attachment'.dup
content_disposition << "; filename=#{::File.basename(options[:filename])}" if filename
cont_type = (options[:mime] ||=
|
ruby
|
{
"resource": ""
}
|
q25273
|
InventoryRefresh.Graph.build_feedback_edge_set
|
validation
|
def build_feedback_edge_set(edges, fixed_edges)
edges = edges.dup
acyclic_edges = fixed_edges.dup
feedback_edge_set = []
while edges.present?
edge = edges.shift
if detect_cycle(edge, acyclic_edges)
|
ruby
|
{
"resource": ""
}
|
q25274
|
InventoryRefresh.Graph.detect_cycle
|
validation
|
def detect_cycle(edge, acyclic_edges, escalation = nil)
# Test if adding edge creates a cycle, ew will traverse the graph from edge Node, through all it's
# dependencies
starting_node = edge.second
edges = [edge] +
|
ruby
|
{
"resource": ""
}
|
q25275
|
InventoryRefresh.Graph.traverse_dependecies
|
validation
|
def traverse_dependecies(traversed_nodes, starting_node, current_node, edges, dependencies, escalation)
dependencies.each do |node_edge|
node = node_edge.first
traversed_nodes << node
if traversed_nodes.include?(starting_node)
if escalation == :exception
raise "Cycle from #{current_node} to #{node}, starting from #{starting_node} passing
|
ruby
|
{
"resource": ""
}
|
q25276
|
InventoryRefresh.ApplicationRecordIterator.find_in_batches
|
validation
|
def find_in_batches(batch_size: 1000, attributes_index: {})
attributes_index.each_slice(batch_size) do |batch|
|
ruby
|
{
"resource": ""
}
|
q25277
|
InventoryRefresh.InventoryObject.assign_attributes
|
validation
|
def assign_attributes(attributes)
attributes.each do |k, v|
# We don't want timestamps or resource versions to be overwritten here, since those are driving the conditions
next if %i(resource_timestamps resource_timestamps_max resource_timestamp).include?(k)
next if %i(resource_counters resource_counters_max resource_counter).include?(k)
if data[:resource_timestamp] && attributes[:resource_timestamp]
|
ruby
|
{
"resource": ""
}
|
q25278
|
InventoryRefresh.InventoryObject.assign_only_newest
|
validation
|
def assign_only_newest(full_row_version_attr, partial_row_version_attr, attributes, data, k, v)
# If timestamps are in play, we will set only attributes that are newer
specific_attr_timestamp = attributes[partial_row_version_attr].try(:[], k)
specific_data_timestamp = data[partial_row_version_attr].try(:[], k)
assign = if !specific_attr_timestamp
# Data have no timestamp, we will ignore the check
true
elsif specific_attr_timestamp && !specific_data_timestamp
# Data specific timestamp is nil and we have new specific timestamp
if data.key?(k)
if attributes[full_row_version_attr] >= data[full_row_version_attr]
# We can save if the full timestamp is bigger, if the data already contains the attribute
true
end
else
|
ruby
|
{
"resource": ""
}
|
q25279
|
InventoryRefresh.InventoryObject.assign_full_row_version_attr
|
validation
|
def assign_full_row_version_attr(full_row_version_attr, attributes, data)
if attributes[full_row_version_attr] && data[full_row_version_attr]
# If both timestamps are present, store the bigger one
data[full_row_version_attr] =
|
ruby
|
{
"resource": ""
}
|
q25280
|
InventoryRefresh.InventoryCollection.uniq_keys_candidates
|
validation
|
def uniq_keys_candidates(keys)
# Find all uniq indexes that that are covering our keys
uniq_key_candidates = unique_indexes.each_with_object([]) { |i, obj| obj << i if (keys - i.columns.map(&:to_sym)).empty? }
if unique_indexes.blank? || uniq_key_candidates.blank?
|
ruby
|
{
"resource": ""
}
|
q25281
|
InventoryRefresh.InventoryCollection.filtered_dependency_attributes
|
validation
|
def filtered_dependency_attributes
filtered_attributes = dependency_attributes
if attributes_blacklist.present?
filtered_attributes = filtered_attributes.reject { |key, _value| attributes_blacklist.include?(key) }
end
|
ruby
|
{
"resource": ""
}
|
q25282
|
InventoryRefresh.InventoryCollection.fixed_attributes
|
validation
|
def fixed_attributes
if model_class
presence_validators = model_class.validators.detect { |x| x.kind_of?(ActiveRecord::Validations::PresenceValidator) }
end
# Attributes that has
|
ruby
|
{
"resource": ""
}
|
q25283
|
InventoryRefresh.InventoryCollection.fixed_dependencies
|
validation
|
def fixed_dependencies
fixed_attrs = fixed_attributes
filtered_dependency_attributes.each_with_object(Set.new) do |(key, value), fixed_deps|
|
ruby
|
{
"resource": ""
}
|
q25284
|
InventoryRefresh.InventoryCollection.dependency_attributes_for
|
validation
|
def dependency_attributes_for(inventory_collections)
attributes = Set.new
inventory_collections.each do |inventory_collection|
attributes
|
ruby
|
{
"resource": ""
}
|
q25285
|
InventoryRefresh.InventoryCollection.records_identities
|
validation
|
def records_identities(records)
records = [records] unless
|
ruby
|
{
"resource": ""
}
|
q25286
|
InventoryRefresh.InventoryCollection.record_identity
|
validation
|
def record_identity(record)
identity = record.try(:[], :id) || record.try(:[], "id") || record.try(:id)
raise "Cannot
|
ruby
|
{
"resource": ""
}
|
q25287
|
ActiveadminSettingsCached.DSL.active_admin_settings_page
|
validation
|
def active_admin_settings_page(options = {}, &block)
options.assert_valid_keys(*ActiveadminSettingsCached::Options::VALID_OPTIONS)
options = ActiveadminSettingsCached::Options.options_for(options)
coercion =
ActiveadminSettingsCached::Coercions.new(options[:template_object].defaults, options[:template_object].display)
content title: options[:title] do
render partial: options[:template], locals: { settings_model: options[:template_object] }
end
page_action :update, method: :post do
settings_params = params.require(:settings).permit!
coercion.cast_params(settings_params) do |name, value|
options[:template_object].save(name, value)
end
|
ruby
|
{
"resource": ""
}
|
q25288
|
Monadic.Either.or
|
validation
|
def or(value=nil, &block)
return Failure(block.call(@value)) if failure? && block_given?
|
ruby
|
{
"resource": ""
}
|
q25289
|
Rubex.CodeWriter.write_func_declaration
|
validation
|
def write_func_declaration type:, c_name:, args: [], static: true
|
ruby
|
{
"resource": ""
}
|
q25290
|
Benchmark.Trend.range
|
validation
|
def range(start, limit, ratio: 8)
check_greater(start, 0)
check_greater(limit, start)
check_greater(ratio, 2)
items = []
count = start
items << count
(limit / ratio).times do
|
ruby
|
{
"resource": ""
}
|
q25291
|
Benchmark.Trend.measure_execution_time
|
validation
|
def measure_execution_time(data = nil, repeat: 1, &work)
inputs = data || range(1, 10_000)
times = []
inputs.each_with_index do |input, i|
GC.start
measurements = []
repeat.times do
|
ruby
|
{
"resource": ""
}
|
q25292
|
Benchmark.Trend.fit_logarithmic
|
validation
|
def fit_logarithmic(xs, ys)
|
ruby
|
{
"resource": ""
}
|
q25293
|
Benchmark.Trend.fit_power
|
validation
|
def fit_power(xs, ys)
a, b, rr = fit(xs, ys, tran_x: ->(x) { Math.log(x) },
|
ruby
|
{
"resource": ""
}
|
q25294
|
Benchmark.Trend.fit_exponential
|
validation
|
def fit_exponential(xs, ys)
a, b, rr = fit(xs, ys, tran_y: ->(y) { Math.log(y) })
|
ruby
|
{
"resource": ""
}
|
q25295
|
Benchmark.Trend.fit
|
validation
|
def fit(xs, ys, tran_x: ->(x) { x }, tran_y: ->(y) { y })
eps = (10 ** -10)
n = 0
sum_x = 0.0
sum_x2 = 0.0
sum_y = 0.0
sum_y2 = 0.0
sum_xy = 0.0
xs.zip(ys).each do |x, y|
n += 1
sum_x += tran_x.(x)
sum_y += tran_y.(y)
sum_x2 += tran_x.(x) ** 2
sum_y2 += tran_y.(y) ** 2
sum_xy += tran_x.(x) * tran_y.(y)
end
txy = n * sum_xy - sum_x * sum_y
tx = n * sum_x2 - sum_x ** 2
ty = n * sum_y2 - sum_y ** 2
is_linear = tran_x.(Math::E) * tran_y.(Math::E) == Math::E ** 2
|
ruby
|
{
"resource": ""
}
|
q25296
|
Benchmark.Trend.fit_at
|
validation
|
def fit_at(type, slope: nil, intercept: nil, n: nil)
raise ArgumentError, "Incorrect input size: #{n}" unless n > 0
case type
when :logarithmic, :log
intercept + slope * Math.log(n)
when :linear
intercept + slope * n
when :power
|
ruby
|
{
"resource": ""
}
|
q25297
|
Modulation.ModuleMixin.export
|
validation
|
def export(*symbols)
symbols = symbols.first if
|
ruby
|
{
"resource": ""
}
|
q25298
|
Modulation.ModuleMixin.__expose!
|
validation
|
def __expose!
singleton = singleton_class
singleton.private_instance_methods.each do |sym|
singleton.send(:public, sym)
end
|
ruby
|
{
"resource": ""
}
|
q25299
|
Rack.Unreloader.require
|
validation
|
def require(paths, &block)
if @reloader
@reloader.require_dependencies(paths, &block)
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.