_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q11200 | Backup.Model.database | train | def database(name, database_id = nil, &block)
@databases << get_class_from_scope(Database, name)
.new(self, database_id, &block)
end | ruby | {
"resource": ""
} |
q11201 | Backup.Model.store_with | train | def store_with(name, storage_id = nil, &block)
@storages << get_class_from_scope(Storage, name)
.new(self, storage_id, &block)
end | ruby | {
"resource": ""
} |
q11202 | Backup.Model.sync_with | train | def sync_with(name, syncer_id = nil, &block)
@syncers << get_class_from_scope(Syncer, name).new(syncer_id, &block)
end | ruby | {
"resource": ""
} |
q11203 | Backup.Model.split_into_chunks_of | train | def split_into_chunks_of(chunk_size, suffix_length = 3)
if chunk_size.is_a?(Integer) && suffix_length.is_a?(Integer)
@splitter = Splitter.new(self, chunk_size, suffix_length)
else
raise Error, <<-EOS
Invalid arguments for #split_into_chunks_of()
+chunk_size+ (and optional +suffix_length+) must be Integers.
EOS
end
end | ruby | {
"resource": ""
} |
q11204 | Backup.Model.perform! | train | def perform!
@started_at = Time.now.utc
@time = package.time = started_at.strftime("%Y.%m.%d.%H.%M.%S")
log!(:started)
before_hook
procedures.each do |procedure|
procedure.is_a?(Proc) ? procedure.call : procedure.each(&:perform!)
end
syncers.each(&:perform!)
rescue Interrupt
@interrupted = true
raise
rescue Exception => err
@exception = err
ensure
unless @interrupted
set_exit_status
@finished_at = Time.now.utc
log!(:finished)
after_hook
end
end | ruby | {
"resource": ""
} |
q11205 | Backup.Model.procedures | train | def procedures
return [] unless databases.any? || archives.any?
[-> { prepare! }, databases, archives,
-> { package! }, -> { store! }, -> { clean! }]
end | ruby | {
"resource": ""
} |
q11206 | Backup.Model.store! | train | def store!
storage_results = storages.map do |storage|
begin
storage.perform!
rescue => ex
ex
end
end
first_exception, *other_exceptions = storage_results.select { |result| result.is_a? Exception }
if first_exception
other_exceptions.each do |exception|
Logger.error exception.to_s
Logger.error exception.backtrace.join('\n')
end
raise first_exception
else
true
end
end | ruby | {
"resource": ""
} |
q11207 | Backup.Model.log! | train | def log!(action)
case action
when :started
Logger.info "Performing Backup for '#{label} (#{trigger})'!\n" \
"[ backup #{VERSION} : #{RUBY_DESCRIPTION} ]"
when :finished
if exit_status > 1
ex = exit_status == 2 ? Error : FatalError
err = ex.wrap(exception, "Backup for #{label} (#{trigger}) Failed!")
Logger.error err
Logger.error "\nBacktrace:\n\s\s" + err.backtrace.join("\n\s\s") + "\n\n"
Cleaner.warnings(self)
else
msg = "Backup for '#{label} (#{trigger})' "
if exit_status == 1
msg << "Completed Successfully (with Warnings) in #{duration}"
Logger.warn msg
else
msg << "Completed Successfully in #{duration}"
Logger.info msg
end
end
end
end | ruby | {
"resource": ""
} |
q11208 | Backup.Splitter.after_packaging | train | def after_packaging
suffixes = chunk_suffixes
first_suffix = "a" * suffix_length
if suffixes == [first_suffix]
FileUtils.mv(
File.join(Config.tmp_path, "#{package.basename}-#{first_suffix}"),
File.join(Config.tmp_path, package.basename)
)
else
package.chunk_suffixes = suffixes
end
end | ruby | {
"resource": ""
} |
q11209 | Sorcery.Model.include_required_submodules! | train | def include_required_submodules!
class_eval do
@sorcery_config.submodules = ::Sorcery::Controller::Config.submodules
@sorcery_config.submodules.each do |mod|
# TODO: Is there a cleaner way to handle missing submodules?
# rubocop:disable Lint/HandleExceptions
begin
include Submodules.const_get(mod.to_s.split('_').map(&:capitalize).join)
rescue NameError
# don't stop on a missing submodule. Needed because some submodules are only defined
# in the controller side.
end
# rubocop:enable Lint/HandleExceptions
end
end
end | ruby | {
"resource": ""
} |
q11210 | Sorcery.Model.init_orm_hooks! | train | def init_orm_hooks!
sorcery_adapter.define_callback :before, :validation, :encrypt_password, if: proc { |record|
record.send(sorcery_config.password_attribute_name).present?
}
sorcery_adapter.define_callback :after, :save, :clear_virtual_password, if: proc { |record|
record.send(sorcery_config.password_attribute_name).present?
}
attr_accessor sorcery_config.password_attribute_name
end | ruby | {
"resource": ""
} |
q11211 | Chewy.Query.explain | train | def explain(value = nil)
chain { criteria.update_request_options explain: (value.nil? ? true : value) }
end | ruby | {
"resource": ""
} |
q11212 | Chewy.Query.limit | train | def limit(value = nil, &block)
chain { criteria.update_request_options size: block || Integer(value) }
end | ruby | {
"resource": ""
} |
q11213 | Chewy.Query.offset | train | def offset(value = nil, &block)
chain { criteria.update_request_options from: block || Integer(value) }
end | ruby | {
"resource": ""
} |
q11214 | Chewy.Query.facets | train | def facets(params = nil)
raise RemovedFeature, 'removed in elasticsearch 2.0' if Runtime.version >= '2.0'
if params
chain { criteria.update_facets params }
else
_response['facets'] || {}
end
end | ruby | {
"resource": ""
} |
q11215 | Chewy.Query.script_score | train | def script_score(script, options = {})
scoring = {script_score: {script: script}.merge(options)}
chain { criteria.update_scores scoring }
end | ruby | {
"resource": ""
} |
q11216 | Chewy.Query.boost_factor | train | def boost_factor(factor, options = {})
scoring = options.merge(boost_factor: factor.to_i)
chain { criteria.update_scores scoring }
end | ruby | {
"resource": ""
} |
q11217 | Chewy.Query.random_score | train | def random_score(seed = Time.now, options = {})
scoring = options.merge(random_score: {seed: seed.to_i})
chain { criteria.update_scores scoring }
end | ruby | {
"resource": ""
} |
q11218 | Chewy.Query.field_value_factor | train | def field_value_factor(settings, options = {})
scoring = options.merge(field_value_factor: settings)
chain { criteria.update_scores scoring }
end | ruby | {
"resource": ""
} |
q11219 | Chewy.Query.decay | train | def decay(function, field, options = {})
field_options = options.extract!(:origin, :scale, :offset, :decay).delete_if { |_, v| v.nil? }
scoring = options.merge(function => {
field => field_options
})
chain { criteria.update_scores scoring }
end | ruby | {
"resource": ""
} |
q11220 | Chewy.Query.aggregations | train | def aggregations(params = nil)
@_named_aggs ||= _build_named_aggs
@_fully_qualified_named_aggs ||= _build_fqn_aggs
if params
params = {params => @_named_aggs[params]} if params.is_a?(Symbol)
params = {params => _get_fully_qualified_named_agg(params)} if params.is_a?(String) && params =~ /\A\S+#\S+\.\S+\z/
chain { criteria.update_aggregations params }
else
_response['aggregations'] || {}
end
end | ruby | {
"resource": ""
} |
q11221 | Chewy.Query._build_named_aggs | train | def _build_named_aggs
named_aggs = {}
@_indexes.each do |index|
index.types.each do |type|
type._agg_defs.each do |agg_name, prc|
named_aggs[agg_name] = prc.call
end
end
end
named_aggs
end | ruby | {
"resource": ""
} |
q11222 | Chewy.Query.delete_all | train | def delete_all
if Runtime.version >= '2.0'
plugins = Chewy.client.nodes.info(plugins: true)['nodes'].values.map { |item| item['plugins'] }.flatten
raise PluginMissing, 'install delete-by-query plugin' unless plugins.find { |item| item['name'] == 'delete-by-query' }
end
request = chain { criteria.update_options simple: true }.send(:_request)
ActiveSupport::Notifications.instrument 'delete_query.chewy',
request: request, indexes: _indexes, types: _types,
index: _indexes.one? ? _indexes.first : _indexes,
type: _types.one? ? _types.first : _types do
if Runtime.version >= '2.0'
path = Elasticsearch::API::Utils.__pathify(
Elasticsearch::API::Utils.__listify(request[:index]),
Elasticsearch::API::Utils.__listify(request[:type]),
'/_query'
)
Chewy.client.perform_request(Elasticsearch::API::HTTP_DELETE, path, {}, request[:body]).body
else
Chewy.client.delete_by_query(request)
end
end
end | ruby | {
"resource": ""
} |
q11223 | Chewy.Query.find | train | def find(*ids)
results = chain { criteria.update_options simple: true }.filter { _id == ids.flatten }.to_a
raise Chewy::DocumentNotFound, "Could not find documents for ids #{ids.flatten}" if results.empty?
ids.one? && !ids.first.is_a?(Array) ? results.first : results
end | ruby | {
"resource": ""
} |
q11224 | Acceptance.BoltCommandHelper.bolt_command_on | train | def bolt_command_on(host, command, flags = {}, opts = {})
bolt_command = command.dup
flags.each { |k, v| bolt_command << " #{k} #{v}" }
case host['platform']
when /windows/
execute_powershell_script_on(host, bolt_command, opts)
when /osx/
# Ensure Bolt runs with UTF-8 under macOS. Otherwise we get issues with
# UTF-8 content in task results.
env = 'source /etc/profile ~/.bash_profile ~/.bash_login ~/.profile && env LANG=en_US.UTF-8'
on(host, env + ' ' + bolt_command)
else
on(host, bolt_command, opts)
end
end | ruby | {
"resource": ""
} |
q11225 | Bolt.Applicator.count_statements | train | def count_statements(ast)
case ast
when Puppet::Pops::Model::Program
count_statements(ast.body)
when Puppet::Pops::Model::BlockExpression
ast.statements.count
else
1
end
end | ruby | {
"resource": ""
} |
q11226 | BoltServer.FileCache.create_cache_dir | train | def create_cache_dir(sha)
file_dir = File.join(@cache_dir, sha)
@cache_dir_mutex.with_read_lock do
# mkdir_p doesn't error if the file exists
FileUtils.mkdir_p(file_dir, mode: 0o750)
FileUtils.touch(file_dir)
end
file_dir
end | ruby | {
"resource": ""
} |
q11227 | BoltServer.FileCache.update_file | train | def update_file(file_data)
sha = file_data['sha256']
file_dir = create_cache_dir(file_data['sha256'])
file_path = File.join(file_dir, File.basename(file_data['filename']))
if check_file(file_path, sha)
@logger.debug("Using prexisting task file: #{file_path}")
return file_path
end
@logger.debug("Queueing download for: #{file_path}")
serial_execute { download_file(file_path, sha, file_data['uri']) }
end | ruby | {
"resource": ""
} |
q11228 | PlanExecutor.Executor.as_resultset | train | def as_resultset(targets)
result_array = begin
yield
rescue StandardError => e
@logger.warn(e)
# CODEREVIEW how should we fail if there's an error?
Array(Bolt::Result.from_exception(targets[0], e))
end
Bolt::ResultSet.new(result_array)
end | ruby | {
"resource": ""
} |
q11229 | Bolt.Executor.queue_execute | train | def queue_execute(targets)
targets.group_by(&:transport).flat_map do |protocol, protocol_targets|
transport = transport(protocol)
report_transport(transport, protocol_targets.count)
transport.batches(protocol_targets).flat_map do |batch|
batch_promises = Array(batch).each_with_object({}) do |target, h|
h[target] = Concurrent::Promise.new(executor: :immediate)
end
# Pass this argument through to avoid retaining a reference to a
# local variable that will change on the next iteration of the loop.
@pool.post(batch_promises) do |result_promises|
begin
results = yield transport, batch
Array(results).each do |result|
result_promises[result.target].set(result)
end
# NotImplementedError can be thrown if the transport is not implemented improperly
rescue StandardError, NotImplementedError => e
result_promises.each do |target, promise|
# If an exception happens while running, the result won't be logged
# by the CLI. Log a warning, as this is probably a problem with the transport.
# If batch_* commands are used from the Base transport, then exceptions
# normally shouldn't reach here.
@logger.warn(e)
promise.set(Bolt::Result.from_exception(target, e))
end
ensure
# Make absolutely sure every promise gets a result to avoid a
# deadlock. Use whatever exception is causing this block to
# execute, or generate one if we somehow got here without an
# exception and some promise is still missing a result.
result_promises.each do |target, promise|
next if promise.fulfilled?
error = $ERROR_INFO || Bolt::Error.new("No result was returned for #{target.uri}",
"puppetlabs.bolt/missing-result-error")
promise.set(Bolt::Result.from_exception(target, error))
end
end
end
batch_promises.values
end
end
end | ruby | {
"resource": ""
} |
q11230 | Bolt.PAL.parse_manifest | train | def parse_manifest(code, filename)
Puppet::Pops::Parser::EvaluatingParser.new.parse_string(code, filename)
rescue Puppet::Error => e
raise Bolt::PAL::PALError, "Failed to parse manifest: #{e}"
end | ruby | {
"resource": ""
} |
q11231 | Bolt.PAL.plan_hash | train | def plan_hash(plan_name, plan)
elements = plan.params_type.elements || []
parameters = elements.each_with_object({}) do |param, acc|
type = if param.value_type.is_a?(Puppet::Pops::Types::PTypeAliasType)
param.value_type.name
else
param.value_type.to_s
end
acc[param.name] = { 'type' => type }
acc[param.name]['default_value'] = nil if param.key_type.is_a?(Puppet::Pops::Types::POptionalType)
end
{
'name' => plan_name,
'parameters' => parameters
}
end | ruby | {
"resource": ""
} |
q11232 | Bolt.PAL.list_modules | train | def list_modules
internal_module_groups = { BOLTLIB_PATH => 'Plan Language Modules',
MODULES_PATH => 'Packaged Modules' }
in_bolt_compiler do
# NOTE: Can replace map+to_h with transform_values when Ruby 2.4
# is the minimum supported version.
Puppet.lookup(:current_environment).modules_by_path.map do |path, modules|
module_group = internal_module_groups[path]
values = modules.map do |mod|
mod_info = { name: (mod.forge_name || mod.name),
version: mod.version }
mod_info[:internal_module_group] = module_group unless module_group.nil?
mod_info
end
[path, values]
end.to_h
end
end | ruby | {
"resource": ""
} |
q11233 | Bolt.Target.update_conf | train | def update_conf(conf)
@protocol = conf[:transport]
t_conf = conf[:transports][transport.to_sym] || {}
# Override url methods
@user = t_conf['user']
@password = t_conf['password']
@port = t_conf['port']
@host = t_conf['host']
# Preserve everything in options so we can easily create copies of a Target.
@options = t_conf.merge(@options)
self
end | ruby | {
"resource": ""
} |
q11234 | BoltSpec.Plans.config | train | def config
@config ||= begin
conf = Bolt::Config.new(Bolt::Boltdir.new('.'), {})
conf.modulepath = [modulepath].flatten
conf
end
end | ruby | {
"resource": ""
} |
q11235 | Bolt.R10KLogProxy.to_bolt_level | train | def to_bolt_level(level_num)
level_str = Log4r::LNAMES[level_num]&.downcase || 'debug'
if level_str =~ /debug/
:debug
else
level_str.to_sym
end
end | ruby | {
"resource": ""
} |
q11236 | Bolt.Inventory.update_target | train | def update_target(target)
data = @groups.data_for(target.name)
data ||= {}
unless data['config']
@logger.debug("Did not find config for #{target.name} in inventory")
data['config'] = {}
end
data = self.class.localhost_defaults(data) if target.name == 'localhost'
# These should only get set from the inventory if they have not yet
# been instantiated
set_vars_from_hash(target.name, data['vars']) unless @target_vars[target.name]
set_facts(target.name, data['facts']) unless @target_facts[target.name]
data['features']&.each { |feature| set_feature(target, feature) } unless @target_features[target.name]
# Use Config object to ensure config section is treated consistently with config file
conf = @config.deep_clone
conf.update_from_inventory(data['config'])
conf.validate
target.update_conf(conf.transport_conf)
unless target.transport.nil? || Bolt::TRANSPORTS.include?(target.transport.to_sym)
raise Bolt::UnknownTransportError.new(target.transport, target.uri)
end
target
end | ruby | {
"resource": ""
} |
q11237 | Byebug.Breakpoint.inspect | train | def inspect
meths = %w[id pos source expr hit_condition hit_count hit_value enabled?]
values = meths.map { |field| "#{field}: #{send(field)}" }.join(", ")
"#<Byebug::Breakpoint #{values}>"
end | ruby | {
"resource": ""
} |
q11238 | Byebug.CommandProcessor.repl | train | def repl
until @proceed
cmd = interface.read_command(prompt)
return if cmd.nil?
next if cmd == ""
run_cmd(cmd)
end
end | ruby | {
"resource": ""
} |
q11239 | Byebug.CommandProcessor.run_auto_cmds | train | def run_auto_cmds(run_level)
safely do
auto_cmds_for(run_level).each { |cmd| cmd.new(self).execute }
end
end | ruby | {
"resource": ""
} |
q11240 | Byebug.CommandProcessor.run_cmd | train | def run_cmd(input)
safely do
command = command_list.match(input)
return command.new(self, input).execute if command
puts safe_inspect(multiple_thread_eval(input))
end
end | ruby | {
"resource": ""
} |
q11241 | Byebug.History.restore | train | def restore
return unless File.exist?(Setting[:histfile])
File.readlines(Setting[:histfile]).reverse_each { |l| push(l.chomp) }
end | ruby | {
"resource": ""
} |
q11242 | Byebug.History.save | train | def save
n_cmds = Setting[:histsize] > size ? size : Setting[:histsize]
File.open(Setting[:histfile], "w") do |file|
n_cmds.times { file.puts(pop) }
end
clear
end | ruby | {
"resource": ""
} |
q11243 | Byebug.History.to_s | train | def to_s(n_cmds)
show_size = n_cmds ? specific_max_size(n_cmds) : default_max_size
commands = buffer.last(show_size)
last_ids(show_size).zip(commands).map do |l|
format("%<position>5d %<command>s", position: l[0], command: l[1])
end.join("\n") + "\n"
end | ruby | {
"resource": ""
} |
q11244 | Byebug.History.ignore? | train | def ignore?(buf)
return true if /^\s*$/ =~ buf
return false if Readline::HISTORY.empty?
buffer[Readline::HISTORY.length - 1] == buf
end | ruby | {
"resource": ""
} |
q11245 | Byebug.Subcommands.execute | train | def execute
subcmd_name = @match[1]
return puts(help) unless subcmd_name
subcmd = subcommand_list.match(subcmd_name)
raise CommandNotFound.new(subcmd_name, self.class) unless subcmd
subcmd.new(processor, arguments).execute
end | ruby | {
"resource": ""
} |
q11246 | Byebug.Frame.locals | train | def locals
return [] unless _binding
_binding.local_variables.each_with_object({}) do |e, a|
a[e] = _binding.local_variable_get(e)
a
end
end | ruby | {
"resource": ""
} |
q11247 | Byebug.Frame.deco_args | train | def deco_args
return "" if args.empty?
my_args = args.map do |arg|
prefix, default = prefix_and_default(arg[0])
kls = use_short_style?(arg) ? "" : "##{locals[arg[1]].class}"
"#{prefix}#{arg[1] || default}#{kls}"
end
"(#{my_args.join(', ')})"
end | ruby | {
"resource": ""
} |
q11248 | Byebug.Context.stack_size | train | def stack_size
return 0 unless backtrace
backtrace.drop_while { |l| ignored_file?(l.first.path) }
.take_while { |l| !ignored_file?(l.first.path) }
.size
end | ruby | {
"resource": ""
} |
q11249 | Byebug.ListCommand.range | train | def range(input)
return auto_range(@match[1] || "+") unless input
b, e = parse_range(input)
raise("Invalid line range") unless valid_range?(b, e)
[b, e]
end | ruby | {
"resource": ""
} |
q11250 | Byebug.ListCommand.auto_range | train | def auto_range(direction)
prev_line = processor.prev_line
if direction == "=" || prev_line.nil?
source_file_formatter.range_around(frame.line)
else
source_file_formatter.range_from(move(prev_line, size, direction))
end
end | ruby | {
"resource": ""
} |
q11251 | Byebug.ListCommand.display_lines | train | def display_lines(min, max)
puts "\n[#{min}, #{max}] in #{frame.file}"
puts source_file_formatter.lines(min, max).join
end | ruby | {
"resource": ""
} |
q11252 | Byebug.Runner.run | train | def run
Byebug.mode = :standalone
option_parser.order!($ARGV)
return if non_script_option? || error_in_script?
$PROGRAM_NAME = program
Byebug.run_init_script if init_script
loop do
debug_program
break if quit
ControlProcessor.new(nil, interface).process_commands
end
end | ruby | {
"resource": ""
} |
q11253 | Byebug.Runner.option_parser | train | def option_parser
@option_parser ||= OptionParser.new(banner, 25) do |opts|
opts.banner = banner
OptionSetter.new(self, opts).setup
end
end | ruby | {
"resource": ""
} |
q11254 | Byebug.Interface.read_input | train | def read_input(prompt, save_hist = true)
line = prepare_input(prompt)
return unless line
history.push(line) if save_hist
command_queue.concat(split_commands(line))
command_queue.shift
end | ruby | {
"resource": ""
} |
q11255 | Licensee.License.raw_content | train | def raw_content
return if pseudo_license?
unless File.exist?(path)
raise Licensee::InvalidLicense, "'#{key}' is not a valid license key"
end
@raw_content ||= File.read(path, encoding: 'utf-8')
end | ruby | {
"resource": ""
} |
q11256 | Licensee.ContentHelper.similarity | train | def similarity(other)
overlap = (wordset & other.wordset).size
total = wordset.size + other.wordset.size
100.0 * (overlap * 2.0 / total)
end | ruby | {
"resource": ""
} |
q11257 | Licensee.ContentHelper.content_without_title_and_version | train | def content_without_title_and_version
@content_without_title_and_version ||= begin
@_content = nil
ops = %i[html hrs comments markdown_headings title version]
ops.each { |op| strip(op) }
_content
end
end | ruby | {
"resource": ""
} |
q11258 | DeviseTokenAuth.PasswordsController.edit | train | def edit
# if a user is not found, return nil
@resource = resource_class.with_reset_password_token(resource_params[:reset_password_token])
if @resource && @resource.reset_password_period_valid?
client_id, token = @resource.create_token
# ensure that user is confirmed
@resource.skip_confirmation! if confirmable_enabled? && !@resource.confirmed_at
# allow user to change password once without current_password
@resource.allow_password_change = true if recoverable_enabled?
@resource.save!
yield @resource if block_given?
redirect_header_options = { reset_password: true }
redirect_headers = build_redirect_headers(token,
client_id,
redirect_header_options)
redirect_to(@resource.build_auth_url(@redirect_url,
redirect_headers))
else
render_edit_error
end
end | ruby | {
"resource": ""
} |
q11259 | DeviseTokenAuth.UnlocksController.create | train | def create
return render_create_error_missing_email unless resource_params[:email]
@email = get_case_insensitive_field_from_resource_params(:email)
@resource = find_resource(:email, @email)
if @resource
yield @resource if block_given?
@resource.send_unlock_instructions(
email: @email,
provider: 'email',
client_config: params[:config_name]
)
if @resource.errors.empty?
return render_create_success
else
render_create_error @resource.errors
end
else
render_not_found_error
end
end | ruby | {
"resource": ""
} |
q11260 | DeviseTokenAuth.OmniauthCallbacksController.redirect_callbacks | train | def redirect_callbacks
# derive target redirect route from 'resource_class' param, which was set
# before authentication.
devise_mapping = get_devise_mapping
redirect_route = get_redirect_route(devise_mapping)
# preserve omniauth info for success route. ignore 'extra' in twitter
# auth response to avoid CookieOverflow.
session['dta.omniauth.auth'] = request.env['omniauth.auth'].except('extra')
session['dta.omniauth.params'] = request.env['omniauth.params']
redirect_to redirect_route
end | ruby | {
"resource": ""
} |
q11261 | DeviseTokenAuth.OmniauthCallbacksController.omniauth_params | train | def omniauth_params
unless defined?(@_omniauth_params)
if request.env['omniauth.params'] && request.env['omniauth.params'].any?
@_omniauth_params = request.env['omniauth.params']
elsif session['dta.omniauth.params'] && session['dta.omniauth.params'].any?
@_omniauth_params ||= session.delete('dta.omniauth.params')
@_omniauth_params
elsif params['omniauth_window_type']
@_omniauth_params = params.slice('omniauth_window_type', 'auth_origin_url', 'resource_class', 'origin')
else
@_omniauth_params = {}
end
end
@_omniauth_params
end | ruby | {
"resource": ""
} |
q11262 | DeviseTokenAuth.OmniauthCallbacksController.assign_provider_attrs | train | def assign_provider_attrs(user, auth_hash)
attrs = auth_hash['info'].slice(*user.attribute_names)
user.assign_attributes(attrs)
end | ruby | {
"resource": ""
} |
q11263 | DeviseTokenAuth.OmniauthCallbacksController.whitelisted_params | train | def whitelisted_params
whitelist = params_for_resource(:sign_up)
whitelist.inject({}) do |coll, key|
param = omniauth_params[key.to_s]
coll[key] = param if param
coll
end
end | ruby | {
"resource": ""
} |
q11264 | Danger.TeamCity.bitbucket_pr_from_env | train | def bitbucket_pr_from_env(env)
branch_name = env["BITBUCKET_BRANCH_NAME"]
repo_slug = env["BITBUCKET_REPO_SLUG"]
begin
Danger::RequestSources::BitbucketCloudAPI.new(repo_slug, nil, branch_name, env).pull_request_id
rescue
raise "Failed to find a pull request for branch \"#{branch_name}\" on Bitbucket."
end
end | ruby | {
"resource": ""
} |
q11265 | Danger.GemsResolver.paths | train | def paths
relative_paths = gem_names.flat_map do |plugin|
Dir.glob("vendor/gems/ruby/*/gems/#{plugin}*/lib/**/**/**/**.rb")
end
relative_paths.map { |path| File.join(dir, path) }
end | ruby | {
"resource": ""
} |
q11266 | Danger.Executor.validate_pr! | train | def validate_pr!(cork, fail_if_no_pr)
unless EnvironmentManager.pr?(system_env)
ci_name = EnvironmentManager.local_ci_source(system_env).name.split("::").last
msg = "Not a #{ci_name} Pull Request - skipping `danger` run. "
# circle won't run danger properly if the commit is pushed and build runs before the PR exists
# https://danger.systems/guides/troubleshooting.html#circle-ci-doesnt-run-my-build-consistently
# the best solution is to enable `fail_if_no_pr`, and then re-run the job once the PR is up
if ci_name == "CircleCI"
msg << "If you only created the PR recently, try re-running your workflow."
end
cork.puts msg.strip.yellow
exit(fail_if_no_pr ? 1 : 0)
end
end | ruby | {
"resource": ""
} |
q11267 | Danger.PluginLinter.print_summary | train | def print_summary(ui)
# Print whether it passed/failed at the top
if failed?
ui.puts "\n[!] Failed\n".red
else
ui.notice "Passed"
end
# A generic proc to handle the similarities between
# errors and warnings.
do_rules = proc do |name, rules|
unless rules.empty?
ui.puts ""
ui.section(name.bold) do
rules.each do |rule|
title = rule.title.bold + " - #{rule.object_applied_to}"
subtitles = [rule.description, link(rule.ref)]
subtitles += [rule.metadata[:files].join(":")] if rule.metadata[:files]
ui.labeled(title, subtitles)
ui.puts ""
end
end
end
end
# Run the rules
do_rules.call("Errors".red, errors)
do_rules.call("Warnings".yellow, warnings)
end | ruby | {
"resource": ""
} |
q11268 | Danger.PluginLinter.class_rules | train | def class_rules
[
Rule.new(:error, 4..6, "Description Markdown", "Above your class you need documentation that covers the scope, and the usage of your plugin.", proc do |json|
json[:body_md] && json[:body_md].empty?
end),
Rule.new(:warning, 30, "Tags", "This plugin does not include `@tags tag1, tag2` and thus will be harder to find in search.", proc do |json|
json[:tags] && json[:tags].empty?
end),
Rule.new(:warning, 29, "References", "Ideally, you have a reference implementation of your plugin that you can show to people, add `@see org/repo` to have the site auto link it.", proc do |json|
json[:see] && json[:see].empty?
end),
Rule.new(:error, 8..27, "Examples", "You should include some examples of common use-cases for your plugin.", proc do |json|
json[:example_code] && json[:example_code].empty?
end)
]
end | ruby | {
"resource": ""
} |
q11269 | Danger.PluginLinter.method_rules | train | def method_rules
[
Rule.new(:error, 40..41, "Description", "You should include a description for your method.", proc do |json|
json[:body_md] && json[:body_md].empty?
end),
Rule.new(:warning, 43..45, "Params", "You should give a 'type' for the param, yes, ruby is duck-typey but it's useful for newbies to the language, use `@param [Type] name`.", proc do |json|
json[:param_couplets] && json[:param_couplets].flat_map(&:values).include?(nil)
end),
Rule.new(:warning, 43..45, "Unknown Param", "You should give a 'type' for the param, yes, ruby is duck-typey but it's useful for newbies to the language, use `@param [Type] name`.", proc do |json|
json[:param_couplets] && json[:param_couplets].flat_map(&:values).include?("Unknown")
end),
Rule.new(:warning, 46, "Return Type", "If the function has no useful return value, use ` @return [void]` - this will be ignored by documentation generators.", proc do |json|
return_hash = json[:tags].find { |tag| tag[:name] == "return" }
!(return_hash && return_hash[:types] && !return_hash[:types].first.empty?)
end)
]
end | ruby | {
"resource": ""
} |
q11270 | Danger.PluginLinter.link | train | def link(ref)
if ref.kind_of?(Range)
"@see - " + "https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb#L#{ref.min}#-L#{ref.max}".blue
elsif ref.kind_of?(Integer)
"@see - " + "https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb#L#{ref}".blue
else
"@see - " + "https://github.com/dbgrandi/danger-prose/blob/v2.0.0/lib/danger_plugin.rb".blue
end
end | ruby | {
"resource": ""
} |
q11271 | Danger.PluginFileResolver.resolve | train | def resolve
if !refs.nil? and refs.select { |ref| File.file? ref }.any?
paths = refs.select { |ref| File.file? ref }.map { |path| File.expand_path(path) }
elsif refs and refs.kind_of? Array
paths, gems = GemsResolver.new(refs).call
else
paths = Dir.glob(File.join(".", "lib/**/*.rb")).map { |path| File.expand_path(path) }
end
{ paths: paths, gems: gems || [] }
end | ruby | {
"resource": ""
} |
q11272 | Danger.CircleAPI.pull_request_url | train | def pull_request_url(env)
url = env["CI_PULL_REQUEST"]
if url.nil? && !env["CIRCLE_PROJECT_USERNAME"].nil? && !env["CIRCLE_PROJECT_REPONAME"].nil?
repo_slug = env["CIRCLE_PROJECT_USERNAME"] + "/" + env["CIRCLE_PROJECT_REPONAME"]
if !env["CIRCLE_PR_NUMBER"].nil?
host = env["DANGER_GITHUB_HOST"] || "github.com"
url = "https://" + host + "/" + repo_slug + "/pull/" + env["CIRCLE_PR_NUMBER"]
else
token = env["DANGER_CIRCLE_CI_API_TOKEN"]
url = fetch_pull_request_url(repo_slug, env["CIRCLE_BUILD_NUM"], token)
end
end
url
end | ruby | {
"resource": ""
} |
q11273 | Danger.CircleAPI.fetch_pull_request_url | train | def fetch_pull_request_url(repo_slug, build_number, token)
build_json = fetch_build(repo_slug, build_number, token)
pull_requests = build_json[:pull_requests]
return nil unless pull_requests.first
pull_requests.first[:url]
end | ruby | {
"resource": ""
} |
q11274 | Danger.CircleAPI.fetch_build | train | def fetch_build(repo_slug, build_number, token)
url = "project/#{repo_slug}/#{build_number}"
params = { "circle-token" => token }
response = client.get url, params, accept: "application/json"
json = JSON.parse(response.body, symbolize_names: true)
json
end | ruby | {
"resource": ""
} |
q11275 | Danger.DangerfileDangerPlugin.validate_file_contains_plugin! | train | def validate_file_contains_plugin!(file)
plugin_count_was = Danger::Plugin.all_plugins.length
yield
if Danger::Plugin.all_plugins.length == plugin_count_was
raise("#{file} doesn't contain any valid danger plugins.")
end
end | ruby | {
"resource": ""
} |
q11276 | Danger.Dangerfile.print_known_info | train | def print_known_info
rows = []
rows += method_values_for_plugin_hashes(core_dsl_attributes)
rows << ["---", "---"]
rows += method_values_for_plugin_hashes(external_dsl_attributes)
rows << ["---", "---"]
rows << ["SCM", env.scm.class]
rows << ["Source", env.ci_source.class]
rows << ["Requests", env.request_source.class]
rows << ["Base Commit", env.meta_info_for_base]
rows << ["Head Commit", env.meta_info_for_head]
params = {}
params[:rows] = rows.each { |current| current[0] = current[0].yellow }
params[:title] = "Danger v#{Danger::VERSION}\nDSL Attributes".green
ui.section("Info:") do
ui.puts
table = Terminal::Table.new(params)
table.align_column(0, :right)
ui.puts table
ui.puts
end
end | ruby | {
"resource": ""
} |
q11277 | Danger.DSLError.message | train | def message
@message ||= begin
description, stacktrace = parse.values_at(:description, :stacktrace)
msg = description
msg = msg.red if msg.respond_to?(:red)
msg << stacktrace if stacktrace
msg
end
end | ruby | {
"resource": ""
} |
q11278 | Synapse.Synapse.run | train | def run
log.info "synapse: starting..."
statsd_increment('synapse.start')
# start all the watchers
statsd_time('synapse.watchers.start.time') do
@service_watchers.map do |watcher|
begin
watcher.start
statsd_increment("synapse.watcher.start", ['start_result:success', "watcher_name:#{watcher.name}"])
rescue Exception => e
statsd_increment("synapse.watcher.start", ['start_result:fail', "watcher_name:#{watcher.name}", "exception_name:#{e.class.name}", "exception_message:#{e.message}"])
raise e
end
end
end
statsd_time('synapse.main_loop.elapsed_time') do
# main loop
loops = 0
loop do
@service_watchers.each do |w|
alive = w.ping?
statsd_increment('synapse.watcher.ping.count', ["watcher_name:#{w.name}", "ping_result:#{alive ? "success" : "failure"}"])
raise "synapse: service watcher #{w.name} failed ping!" unless alive
end
if @config_updated
@config_updated = false
statsd_increment('synapse.config.update')
@config_generators.each do |config_generator|
log.info "synapse: configuring #{config_generator.name}"
begin
config_generator.update_config(@service_watchers)
rescue StandardError => e
statsd_increment("synapse.config.update_failed", ["config_name:#{config_generator.name}"])
log.error "synapse: update config failed for config #{config_generator.name} with exception #{e}"
raise e
end
end
end
sleep 1
@config_generators.each do |config_generator|
config_generator.tick(@service_watchers)
end
loops += 1
log.debug "synapse: still running at #{Time.now}" if (loops % 60) == 0
end
end
rescue StandardError => e
statsd_increment('synapse.stop', ['stop_avenue:abort', 'stop_location:main_loop', "exception_name:#{e.class.name}", "exception_message:#{e.message}"])
log.error "synapse: encountered unexpected exception #{e.inspect} in main thread"
raise e
ensure
log.warn "synapse: exiting; sending stop signal to all watchers"
# stop all the watchers
@service_watchers.map do |w|
begin
w.stop
statsd_increment("synapse.watcher.stop", ['stop_avenue:clean', 'stop_location:main_loop', "watcher_name:#{w.name}"])
rescue Exception => e
statsd_increment("synapse.watcher.stop", ['stop_avenue:exception', 'stop_location:main_loop', "watcher_name:#{w.name}", "exception_name:#{e.class.name}", "exception_message:#{e.message}"])
raise e
end
end
statsd_increment('synapse.stop', ['stop_avenue:clean', 'stop_location:main_loop'])
end | ruby | {
"resource": ""
} |
q11279 | Ahoy.DatabaseStore.visit_or_create | train | def visit_or_create(started_at: nil)
ahoy.track_visit(started_at: started_at) if !visit && Ahoy.server_side_visits
visit
end | ruby | {
"resource": ""
} |
q11280 | Ahoy.Tracker.track | train | def track(name, properties = {}, options = {})
if exclude?
debug "Event excluded"
elsif missing_params?
debug "Missing required parameters"
else
data = {
visit_token: visit_token,
user_id: user.try(:id),
name: name.to_s,
properties: properties,
time: trusted_time(options[:time]),
event_id: options[:id] || generate_id
}.select { |_, v| v }
@store.track_event(data)
end
true
rescue => e
report_exception(e)
end | ruby | {
"resource": ""
} |
q11281 | Ransack.Constants.escape_wildcards | train | def escape_wildcards(unescaped)
case ActiveRecord::Base.connection.adapter_name
when "Mysql2".freeze, "PostgreSQL".freeze
# Necessary for PostgreSQL and MySQL
unescaped.to_s.gsub(/([\\%_.])/, '\\\\\\1')
else
unescaped
end
end | ruby | {
"resource": ""
} |
q11282 | AASM.Base.attribute_name | train | def attribute_name(column_name=nil)
if column_name
@state_machine.config.column = column_name.to_sym
else
@state_machine.config.column ||= :aasm_state
end
@state_machine.config.column
end | ruby | {
"resource": ""
} |
q11283 | AASM.Localizer.i18n_klass | train | def i18n_klass(klass)
klass.model_name.respond_to?(:i18n_key) ? klass.model_name.i18n_key : klass.name.underscore
end | ruby | {
"resource": ""
} |
q11284 | AASM.ClassMethods.aasm | train | def aasm(*args, &block)
if args[0].is_a?(Symbol) || args[0].is_a?(String)
# using custom name
state_machine_name = args[0].to_sym
options = args[1] || {}
else
# using the default state_machine_name
state_machine_name = :default
options = args[0] || {}
end
AASM::StateMachineStore.fetch(self, true).register(state_machine_name, AASM::StateMachine.new(state_machine_name))
# use a default despite the DSL configuration default.
# this is because configuration hasn't been setup for the AASM class but we are accessing a DSL option already for the class.
aasm_klass = options[:with_klass] || AASM::Base
raise ArgumentError, "The class #{aasm_klass} must inherit from AASM::Base!" unless aasm_klass.ancestors.include?(AASM::Base)
@aasm ||= Concurrent::Map.new
if @aasm[state_machine_name]
# make sure to use provided options
options.each do |key, value|
@aasm[state_machine_name].state_machine.config.send("#{key}=", value)
end
else
# create a new base
@aasm[state_machine_name] = aasm_klass.new(
self,
state_machine_name,
AASM::StateMachineStore.fetch(self, true).machine(state_machine_name),
options
)
end
@aasm[state_machine_name].instance_eval(&block) if block # new DSL
@aasm[state_machine_name]
end | ruby | {
"resource": ""
} |
q11285 | AASM::Core.Event.may_fire? | train | def may_fire?(obj, to_state=::AASM::NO_VALUE, *args)
_fire(obj, {:test_only => true}, to_state, *args) # true indicates test firing
end | ruby | {
"resource": ""
} |
q11286 | SymmetricEncryption.Config.config | train | def config
@config ||= begin
raise(ConfigError, "Cannot find config file: #{file_name}") unless File.exist?(file_name)
env_config = YAML.load(ERB.new(File.new(file_name).read).result)[env]
raise(ConfigError, "Cannot find environment: #{env} in config file: #{file_name}") unless env_config
env_config = self.class.send(:deep_symbolize_keys, env_config)
self.class.send(:migrate_old_formats!, env_config)
end
end | ruby | {
"resource": ""
} |
q11287 | SymmetricEncryption.Writer.close | train | def close(close_child_stream = true)
return if closed?
if size.positive?
final = @stream_cipher.final
@ios.write(final) unless final.empty?
end
@ios.close if close_child_stream
@closed = true
end | ruby | {
"resource": ""
} |
q11288 | SymmetricEncryption.Cipher.encrypt | train | def encrypt(str, random_iv: SymmetricEncryption.randomize_iv?, compress: false, header: always_add_header)
return if str.nil?
str = str.to_s
return str if str.empty?
encrypted = binary_encrypt(str, random_iv: random_iv, compress: compress, header: header)
encode(encrypted)
end | ruby | {
"resource": ""
} |
q11289 | SymmetricEncryption.Cipher.decrypt | train | def decrypt(str)
decoded = decode(str)
return unless decoded
return decoded if decoded.empty?
decrypted = binary_decrypt(decoded)
# Try to force result to UTF-8 encoding, but if it is not valid, force it back to Binary
decrypted.force_encoding(SymmetricEncryption::BINARY_ENCODING) unless decrypted.force_encoding(SymmetricEncryption::UTF8_ENCODING).valid_encoding?
decrypted
end | ruby | {
"resource": ""
} |
q11290 | SymmetricEncryption.Cipher.binary_encrypt | train | def binary_encrypt(str, random_iv: SymmetricEncryption.randomize_iv?, compress: false, header: always_add_header)
return if str.nil?
string = str.to_s
return string if string.empty?
# Header required when adding a random_iv or compressing
header = Header.new(version: version, compress: compress) if header || random_iv || compress
# Creates a new OpenSSL::Cipher with every call so that this call is thread-safe.
openssl_cipher = ::OpenSSL::Cipher.new(cipher_name)
openssl_cipher.encrypt
openssl_cipher.key = @key
result =
if header
if random_iv
openssl_cipher.iv = header.iv = openssl_cipher.random_iv
elsif iv
openssl_cipher.iv = iv
end
header.to_s + openssl_cipher.update(compress ? Zlib::Deflate.deflate(string) : string)
else
openssl_cipher.iv = iv if iv
openssl_cipher.update(string)
end
result << openssl_cipher.final
end | ruby | {
"resource": ""
} |
q11291 | SymmetricEncryption.Header.read_string | train | def read_string(buffer, offset)
# TODO: Length check
# Exception when
# - offset exceeds length of buffer
# byteslice truncates when too long, but returns nil when start is beyond end of buffer
len = buffer.byteslice(offset, 2).unpack('v').first
offset += 2
out = buffer.byteslice(offset, len)
[out, offset + len]
end | ruby | {
"resource": ""
} |
q11292 | SymmetricEncryption.Reader.gets | train | def gets(sep_string, length = nil)
return read(length) if sep_string.nil?
# Read more data until we get the sep_string
while (index = @read_buffer.index(sep_string)).nil? && !@ios.eof?
break if length && @read_buffer.length >= length
read_block
end
index ||= -1
data = @read_buffer.slice!(0..index)
@pos += data.length
return nil if data.empty? && eof?
data
end | ruby | {
"resource": ""
} |
q11293 | SymmetricEncryption.Reader.read_header | train | def read_header
@pos = 0
# Read first block and check for the header
buf = @ios.read(@buffer_size, @output_buffer ||= ''.b)
# Use cipher specified in header, or global cipher if it has no header
iv, key, cipher_name, cipher = nil
header = Header.new
if header.parse!(buf)
@header_present = true
@compressed = header.compressed?
@version = header.version
cipher = header.cipher
cipher_name = header.cipher_name || cipher.cipher_name
key = header.key
iv = header.iv
else
@header_present = false
@compressed = nil
cipher = SymmetricEncryption.cipher(@version)
cipher_name = cipher.cipher_name
end
@stream_cipher = ::OpenSSL::Cipher.new(cipher_name)
@stream_cipher.decrypt
@stream_cipher.key = key || cipher.send(:key)
@stream_cipher.iv = iv || cipher.iv
decrypt(buf)
end | ruby | {
"resource": ""
} |
q11294 | Braintree.ResourceCollection.each | train | def each(&block)
@ids.each_slice(@page_size) do |page_of_ids|
resources = @paging_block.call(page_of_ids)
resources.each(&block)
end
end | ruby | {
"resource": ""
} |
q11295 | Audited.Audit.revision | train | def revision
clazz = auditable_type.constantize
(clazz.find_by_id(auditable_id) || clazz.new).tap do |m|
self.class.assign_revision_attributes(m, self.class.reconstruct_attributes(ancestors).merge(audit_version: version))
end
end | ruby | {
"resource": ""
} |
q11296 | Audited.Audit.new_attributes | train | def new_attributes
(audited_changes || {}).inject({}.with_indifferent_access) do |attrs, (attr, values)|
attrs[attr] = values.is_a?(Array) ? values.last : values
attrs
end
end | ruby | {
"resource": ""
} |
q11297 | Audited.Audit.old_attributes | train | def old_attributes
(audited_changes || {}).inject({}.with_indifferent_access) do |attrs, (attr, values)|
attrs[attr] = Array(values).first
attrs
end
end | ruby | {
"resource": ""
} |
q11298 | Audited.Audit.undo | train | def undo
case action
when 'create'
# destroys a newly created record
auditable.destroy!
when 'destroy'
# creates a new record with the destroyed record attributes
auditable_type.constantize.create!(audited_changes)
when 'update'
# changes back attributes
auditable.update_attributes!(audited_changes.transform_values(&:first))
else
raise StandardError, "invalid action given #{action}"
end
end | ruby | {
"resource": ""
} |
q11299 | Audited.Audit.user_as_string= | train | def user_as_string=(user)
# reset both either way
self.user_as_model = self.username = nil
user.is_a?(::ActiveRecord::Base) ?
self.user_as_model = user :
self.username = user
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.