_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q5500
CivicSIPSdk.Client.exchange_code
train
def exchange_code(jwt_token:) json_body_str = JSON.generate('authToken' => jwt_token) response = HTTParty.post( "#{BASE_URL}/#{@config.env}/#{AUTH_CODE_PATH}", headers: { 'Content-Type' => MIMETYPE_JSON, 'Accept' => MIMETYPE_JSON, 'Content-Length' => json_body_str.size.to_s, 'Authorization' => authorization_header(body: json_body_str) }, body: json_body_str ) unless response.code == 200 raise StandardError.new( "Failed to exchange JWT token. HTTP status: #{response.code}, response body: #{response.body}" ) end res_payload = JSON.parse(response.body) extract_user_data(response: res_payload) end
ruby
{ "resource": "" }
q5501
Opto.Option.skip?
train
def skip? return false unless has_group? return true if group.any_true?(skip_if) return true unless group.all_true?(only_if) false end
ruby
{ "resource": "" }
q5502
Opto.Option.resolvers
train
def resolvers @resolvers ||= from.merge(default: self).map { |origin, hint| { origin: origin, hint: hint, resolver: ((has_group? && group.resolvers[origin]) || Resolver.for(origin)) } } end
ruby
{ "resource": "" }
q5503
Goalie.CustomErrorPages.rescue_action_locally
train
def rescue_action_locally(request, exception) # TODO this should probably move to the controller, that is, have # http error codes map directly to controller actions, then let # controller handle different exception classes however it wants rescue_actions = Hash.new('diagnostics') rescue_actions.update({ 'ActionView::MissingTemplate' => 'missing_template', 'ActionController::RoutingError' => 'routing_error', 'AbstractController::ActionNotFound' => 'unknown_action', 'ActionView::Template::Error' => 'template_error' }) error_params = { :request => request, :exception => exception, :application_trace => application_trace(exception), :framework_trace => framework_trace(exception), :full_trace => full_trace(exception) } request.env['goalie.error_params'] = error_params action = rescue_actions[exception.class.name] response = LocalErrorsController.action(action).call(request.env).last render(status_code(exception), response.body) end
ruby
{ "resource": "" }
q5504
GovKit.Resource.find_resource_in_modules
train
def find_resource_in_modules(resource_name, ancestors) if namespace = ancestors.detect { |a| a.constants.include?(resource_name.to_sym) } return namespace.const_get(resource_name) else raise NameError, "Namespace for #{namespace} not found" end end
ruby
{ "resource": "" }
q5505
GovKit.Resource.find_or_create_resource_for
train
def find_or_create_resource_for(name) resource_name = name.to_s.gsub(/^[_\-+]/,'').gsub(/^(\-?\d)/, "n#{$1}").gsub(/(\s|-)/, '').camelize if self.class.parents.size > 1 find_resource_in_modules(resource_name, self.class.parents) else self.class.const_get(resource_name) end rescue NameError if self.class.const_defined?(resource_name) resource = self.class.const_get(resource_name) else resource = self.class.const_set(resource_name, Class.new(GovKit::Resource)) end resource end
ruby
{ "resource": "" }
q5506
Rubikon.ArgumentVector.command!
train
def command!(commands) command = nil command_index = 0 each_with_index do |arg, i| break if arg == '--' command = commands[arg.to_sym] unless command.nil? command_index = i delete_at i break end end delete '--' command ||= commands[:__default] return command, command_index end
ruby
{ "resource": "" }
q5507
Rubikon.ArgumentVector.expand!
train
def expand! each_with_index do |arg, i| next if !arg.start_with?('-') self[i] = arg.split('=', 2) next if arg.start_with?('--') self[i] = arg[1..-1].split('').uniq.map { |a| '-' + a } end flatten! end
ruby
{ "resource": "" }
q5508
Rubikon.ArgumentVector.params!
train
def params!(params, pos = 0) active_params = [] to_delete = [] each_with_index do |arg, i| next if i < pos || arg.nil? || !arg.start_with?('-') param = params[(arg.start_with?('--') ? arg[2..-1] : arg[1..1]).to_sym] unless param.nil? to_delete << i scoped_args! param, i + 1 if param.is_a? Option active_params << param end end to_delete.reverse.each { |i| delete_at i } active_params end
ruby
{ "resource": "" }
q5509
Rubikon.ArgumentVector.scoped_args!
train
def scoped_args!(has_args, pos = 0) to_delete = [] each_with_index do |arg, i| next if i < pos break if arg.start_with?('-') || !has_args.send(:more_args?) to_delete << i has_args.send(:<<, arg) end to_delete.reverse.each { |i| delete_at i } end
ruby
{ "resource": "" }
q5510
Amb.ClassMethods.solve
train
def solve(failure_message = "No solution.") amb = self.new yield(amb) rescue Amb::ExhaustedError => ex puts puts "#{amb.branches_count} branches explored." if $DEBUG amb.report(failure_message) end
ruby
{ "resource": "" }
q5511
Amb.ClassMethods.solve_all
train
def solve_all(failure_message = "No more solutions.") amb = self.new yield(amb) amb.failure rescue Amb::ExhaustedError => ex puts puts "#{amb.branches_count} branches explored." if $DEBUG amb.report(failure_message) end
ruby
{ "resource": "" }
q5512
Analyzers.EcbStringAppender.calculate_block_size
train
def calculate_block_size char_amount = 1 base_length = @oracle.encipher(DUMMY * char_amount).length result = nil (1..MAX_KNOWN_BLOCK_LENGTH).each do |length| new_length = @oracle.encipher(DUMMY * char_amount).length if new_length > base_length result = new_length - base_length break end char_amount += 1 end result end
ruby
{ "resource": "" }
q5513
KonoUtils.Encoder.string_encoder
train
def string_encoder return string if string.valid_encoding? str = string Encoding.list.each do |e| begin str.force_encoding(e.name) tmp_string = str.encode('UTF-8') return tmp_string if tmp_string.valid_encoding? rescue Rails.logger.debug { "Rescue -> #{e.name}" } if defined?(::Rails) end end impossible_encoding string end
ruby
{ "resource": "" }
q5514
Push0r.ApnsService.get_feedback
train
def get_feedback tokens = [] begin setup_ssl(true) rescue SocketError => e puts "Error: #{e}" return tokens end if IO.select([@ssl], nil, nil, 1) while (line = @ssl.read(38)) f = line.unpack('N1n1H64') time = Time.at(f[0]) token = f[2].scan(/.{8}/).join(' ') tokens << token end end close_ssl return tokens end
ruby
{ "resource": "" }
q5515
LatoCore.Elements::Pagination::Cell.generate_page_link
train
def generate_page_link page_number url = core__add_param_to_url(@args[:url], @args[:param], page_number) if @args[:extra_params] @args[:extra_params].each do |key, value| url = core__add_param_to_url(url, key, value) end end url end
ruby
{ "resource": "" }
q5516
GosuEnhanced.Size.inflate!
train
def inflate!(by_w, by_h = nil) return inflate_by_size(by_w) if by_w.respond_to? :width validate(by_w, by_h) @width += by_w @height += by_h self end
ruby
{ "resource": "" }
q5517
GosuEnhanced.Size.deflate!
train
def deflate!(by_w, by_h = nil) if by_w.respond_to? :width inflate!(-by_w.width, -by_w.height) else inflate!(-by_w, -by_h) end end
ruby
{ "resource": "" }
q5518
GosuEnhanced.Size.inflate_by_size
train
def inflate_by_size(sz) width = sz.width height = sz.height validate(width, height) @width += width @height += height self end
ruby
{ "resource": "" }
q5519
LatoCore.Interface::Application.core__get_application_gems
train
def core__get_application_gems gems = {} Bundler.load.specs.each do |spec| gems[spec.name] = spec.version end gems end
ruby
{ "resource": "" }
q5520
LatoCore.Interface::Application.core__get_application_logo_sidebar_path
train
def core__get_application_logo_sidebar_path dir = "#{core__get_application_root_path}/app/assets/images/lato/" if File.exist?("#{dir}/logo_sidebar.svg") return 'lato/logo_sidebar.svg' elsif File.exist?("#{dir}/logo_sidebar.png") return 'lato/logo_sidebar.png' elsif File.exist?("#{dir}/logo_sidebar.jpg") return 'lato/logo_sidebar.jpg' elsif File.exist?("#{dir}/logo_sidebar.gif") return 'lato/logo_sidebar.gif' end core__get_application_logo_path end
ruby
{ "resource": "" }
q5521
Rubikon.Command.help
train
def help(show_usage = true) help = '' if show_usage help << " #{name}" if name != :__default @params.values.uniq.sort_by {|a| a.name.to_s }.each do |param| help << ' [' ([param.name] + param.aliases).each_with_index do |name, index| name = name.to_s help << '|' if index > 0 help << '-' if name.size > 1 help << "-#{name}" end help << ' ...' if param.is_a?(Option) help << ']' end end help << "\n\n#{description}" unless description.nil? help_flags = {} help_options = {} params.each_value do |param| if param.is_a? Flag help_flags[param.name.to_s] = param else help_options[param.name.to_s] = param end end param_name = lambda { |name| "#{name.size > 1 ? '-' : ' '}-#{name}" } unless help_flags.empty? && help_options.empty? max_param_length = (help_flags.keys + help_options.keys). max_by { |a| a.size }.size + 2 end unless help_flags.empty? help << "\n\nFlags:" help_flags.sort_by { |name, param| name }.each do |name, param| help << "\n #{param_name.call(name).ljust(max_param_length)}" help << " #{param.description}" unless param.description.nil? end end unless help_options.empty? help << "\n\nOptions:\n" help_options.sort_by { |name, param| name }.each do |name, param| help << " #{param_name.call(name).ljust(max_param_length)} ..." help << " #{param.description}" unless param.description.nil? help << "\n" end end help end
ruby
{ "resource": "" }
q5522
Rubikon.Command.add_param
train
def add_param(parameter) if parameter.is_a? Hash parameter.each do |alias_name, name| alias_name = alias_name.to_sym name = name.to_sym parameter = @params[name] if parameter.nil? @params[alias_name] = name else parameter.aliases << alias_name @params[alias_name] = parameter end end else raise ArgumentError unless parameter.is_a? Parameter @params.each do |name, param| if param == parameter.name parameter.aliases << name @params[name] = parameter end end @params[parameter.name] = parameter end end
ruby
{ "resource": "" }
q5523
Rubikon.Command.method_missing
train
def method_missing(name, *args, &block) if args.empty? && !block_given? if @params.key?(name) return @params[name] else active_params.each do |param| return param.send(name) if param.respond_to_missing?(name) end end end super end
ruby
{ "resource": "" }
q5524
Rubikon.Command.reset
train
def reset super @params.values.uniq.each do |param| param.send(:reset) if param.is_a? Parameter end end
ruby
{ "resource": "" }
q5525
Rubikon.Command.respond_to_missing?
train
def respond_to_missing?(name, include_private = false) @params.key?(name) || active_params.any? { |param| param.respond_to_missing?(name) } || super end
ruby
{ "resource": "" }
q5526
Attached.Attatcher.validations
train
def validations name = @name @klass.send(:validates_each, name) do |record, attr, value| record.send(name).errors.each do |error| record.errors.add(name, error) end end end
ruby
{ "resource": "" }
q5527
OmniAuth.Strategy.on_any_path?
train
def on_any_path?(paths) path_found = false paths.each do |path| path_found = on_path?(path) ? true : path_found end return path_found end
ruby
{ "resource": "" }
q5528
Attached.Attachment.save
train
def save self.queue.each do |style, file| path = self.path(style) self.storage.save(file, path) if file and path end self.purge.each do |path| self.storage.destroy(path) end @purge = [] @queue = {} end
ruby
{ "resource": "" }
q5529
Attached.Attachment.destroy
train
def destroy if attached? self.storage.destroy(self.path) self.styles.each do |style, options| self.storage.destroy(self.path(style)) end end @purge = [] @queue = {} end
ruby
{ "resource": "" }
q5530
Attached.Attachment.url
train
def url(style = self.default) path = self.path(style) host = self.host host = self.aliases[path.hash % self.aliases.count] unless self.aliases.empty? return "#{host}#{path}" end
ruby
{ "resource": "" }
q5531
Attached.Attachment.path
train
def path(style = self.default) path = self.attached? ? @path.clone : @missing.clone path.gsub!(/:name/, name.to_s) path.gsub!(/:style/, style.to_s) path.gsub!(/:extension/, extension(style).to_s) path.gsub!(/:identifier/, identifier(style).to_s) return path end
ruby
{ "resource": "" }
q5532
GameOverseer.ClientManager.add
train
def add(client_id, ip_address) @clients << {client_id: client_id, ip_address: ip_address} GameOverseer::Services.client_connected(client_id, ip_address) GameOverseer::Console.log("ClientManager> client with id '#{client_id}' connected") end
ruby
{ "resource": "" }
q5533
GameOverseer.ClientManager.remove
train
def remove(client_id) @clients.each do |hash| if hash[:client_id] == client_id @clients.delete(hash) GameOverseer::Services.client_disconnected(client_id) GameOverseer::Console.log("ClientManager> client with id '#{client_id}' disconnected") end end end
ruby
{ "resource": "" }
q5534
Cassie::Schema::Migration::DSL.TableOperations.create_table
train
def create_table(table_name, options = {}) table_definition = TableDefinition.new table_definition.define_primary_keys(options[:primary_keys]) if options[:primary_keys] table_definition.define_partition_keys(options[:partition_keys]) if options[:partition_keys] table_definition.define_options(options[:options]) if options[:options] yield table_definition if block_given? announce_operation "create_table(#{table_name})" create_cql = "CREATE TABLE #{table_name} (" create_cql << table_definition.to_create_cql create_cql << ")" create_cql << table_definition.options announce_suboperation create_cql execute create_cql end
ruby
{ "resource": "" }
q5535
GameOverseer.ENetServer.transmit
train
def transmit(client_id, message, reliable = false, channel = ChannelManager::CHAT) @server.send_packet(client_id, message, reliable, channel) end
ruby
{ "resource": "" }
q5536
GameOverseer.ENetServer.broadcast
train
def broadcast(message, reliable = false, channel = ChannelManager::CHAT) @server.broadcast_packet(message, reliable, channel) end
ruby
{ "resource": "" }
q5537
FalkorLib.Versioning.bump
train
def bump(oldversion, level) major = minor = patch = 0 if oldversion =~ /^(\d+)\.(\d+)\.(\d+)$/ major = Regexp.last_match(1).to_i minor = Regexp.last_match(2).to_i patch = Regexp.last_match(3).to_i end case level.to_sym when :major major += 1 minor = 0 patch = 0 when :minor minor += 1 patch = 0 when :patch patch += 1 end version = [major, minor, patch].compact.join('.') version end
ruby
{ "resource": "" }
q5538
Apidiesel.Dsl.expects
train
def expects(&block) builder = ExpectationBuilder.new builder.instance_eval(&block) parameter_validations.concat builder.parameter_validations parameters_to_filter.concat builder.parameters_to_filter end
ruby
{ "resource": "" }
q5539
Apidiesel.Dsl.responds_with
train
def responds_with(**args, &block) builder = FilterBuilder.new builder.instance_eval(&block) response_filters.concat(builder.response_filters) response_formatters.concat(builder.response_formatters) if args[:unnested_hash] response_formatters << lambda do |_, response| if response.is_a?(Hash) && response.keys.length == 1 response.values.first else response end end end end
ruby
{ "resource": "" }
q5540
FalkorLib.Common.really_continue?
train
def really_continue?(default_answer = 'Yes') return if FalkorLib.config[:no_interaction] pattern = (default_answer =~ /yes/i) ? '(Y|n)' : '(y|N)' answer = ask( cyan("=> Do you really want to continue #{pattern}?"), default_answer) exit 0 if answer =~ /n.*/i end
ruby
{ "resource": "" }
q5541
FalkorLib.Common.nice_execute
train
def nice_execute(cmd) puts bold("[Running] #{cmd.gsub(/^\s*/, ' ')}") stdout, stderr, exit_status = Open3.capture3( cmd ) unless stdout.empty? stdout.each_line do |line| print "** [out] #{line}" $stdout.flush end end unless stderr.empty? stderr.each_line do |line| $stderr.print red("** [err] #{line}") $stderr.flush end end exit_status end
ruby
{ "resource": "" }
q5542
FalkorLib.Common.execute_in_dir
train
def execute_in_dir(path, cmd) exit_status = 0 Dir.chdir(path) do exit_status = run %( #{cmd} ) end exit_status end
ruby
{ "resource": "" }
q5543
FalkorLib.Common.exec_or_exit
train
def exec_or_exit(cmd) status = execute(cmd) if (status.to_i.nonzero?) error("The command '#{cmd}' failed with exit status #{status.to_i}") end status end
ruby
{ "resource": "" }
q5544
FalkorLib.Common.select_from
train
def select_from(list, text = 'Select the index', default_idx = 0, raw_list = list) error "list and raw_list differs in size" if list.size != raw_list.size l = list raw_l = raw_list if list.is_a?(Array) l = raw_l = { 0 => 'Exit' } list.each_with_index do |e, idx| l[idx + 1] = e raw_l[idx + 1] = raw_list[idx] end end puts l.to_yaml answer = ask("=> #{text}", default_idx.to_s) raise SystemExit, 'exiting selection' if answer == '0' raise RangeError, 'Undefined index' if Integer(answer) >= l.length raw_l[Integer(answer)] end
ruby
{ "resource": "" }
q5545
FalkorLib.Common.init_rvm
train
def init_rvm(rootdir = Dir.pwd, gemset = '') rvm_files = { :version => File.join(rootdir, '.ruby-version'), :gemset => File.join(rootdir, '.ruby-gemset') } unless File.exist?( (rvm_files[:version]).to_s) v = select_from(FalkorLib.config[:rvm][:rubies], "Select RVM ruby to configure for this directory", 3) File.open( rvm_files[:version], 'w') do |f| f.puts v end end unless File.exist?( (rvm_files[:gemset]).to_s) g = (gemset.empty?) ? ask("Enter RVM gemset name for this directory", File.basename(rootdir)) : gemset File.open( rvm_files[:gemset], 'w') do |f| f.puts g end end end
ruby
{ "resource": "" }
q5546
FalkorLib.Bootstrap.select_licence
train
def select_licence(default_licence = FalkorLib::Config::Bootstrap::DEFAULTS[:metadata][:license], _options = {}) list_license = FalkorLib::Config::Bootstrap::DEFAULTS[:licenses].keys idx = list_license.index(default_licence) unless default_licence.nil? select_from(list_license, 'Select the license index for this project:', (idx.nil?) ? 1 : idx + 1) #licence end
ruby
{ "resource": "" }
q5547
FalkorLib.Bootstrap.license
train
def license(dir = Dir.pwd, license = FalkorLib::Config::Bootstrap::DEFAULTS[:metadata][:license], authors = '', options = { :filename => 'LICENSE' }) return if ((license.empty?) or (license == 'none') or (license =~ /^CC/)) return unless FalkorLib::Config::Bootstrap::DEFAULTS[:licenses].keys.include?( license ) info "Generate the #{license} licence file" path = normalized_path(dir) use_git = FalkorLib::Git.init?(path) rootdir = (use_git) ? FalkorLib::Git.rootdir(path) : path Dir.chdir( rootdir ) do run %( licgen #{license.downcase} #{authors} ) run %( mv LICENSE #{options[:filename]} ) if( options[:filename] and options[:filename] != 'LICENSE') end end
ruby
{ "resource": "" }
q5548
FalkorLib.Bootstrap.guess_project_config
train
def guess_project_config(dir = Dir.pwd, options = {}) path = normalized_path(dir) use_git = FalkorLib::Git.init?(path) rootdir = (use_git) ? FalkorLib::Git.rootdir(path) : path local_config = FalkorLib::Config.get(rootdir, :local) return local_config[:project] if local_config[:project] # Otherwise, guess the rest of the configuration config = FalkorLib::Config::Bootstrap::DEFAULTS[:metadata].clone # Apply options (if provided) [ :name, :forge ].each do |k| config[k.to_sym] = options[k.to_sym] if options[k.to_sym] end config[:name] = ask("\tProject name: ", get_project_name(dir)) if config[:name].empty? if (use_git) config[:origin] = FalkorLib::Git.config('remote.origin.url') if config[:origin] =~ /((gforge|gitlab|github)[\.\w_-]+)[:\d\/]+(\w*)/ config[:forge] = Regexp.last_match(2).to_sym config[:by] = Regexp.last_match(3) elsif config[:forge].empty? config[:forge] = select_forge(config[:forge]).to_sym end end forges = FalkorLib::Config::Bootstrap::DEFAULTS[:forge][ config[:forge].to_sym ] default_source = case config[:forge] when :gforge 'https://' + forges[:url] + "/projects/" + config[:name].downcase when :github, :gitlab 'https://' + forges[:url] + "/" + config[:by] + "/" + config[:name].downcase else "" end config[:source] = config[:project_page] = default_source config[:issues_url] = "#{config[:project_page]}/issues" config[:license] = select_licence if config[:license].empty? [ :summary ].each do |k| config[k.to_sym] = ask( "\t" + Kernel.format("Project %-20s", k.to_s)) end config[:description] = config[:summary] config[:gitflow] = FalkorLib::GitFlow.guess_gitflow_config(rootdir) config[:make] = File.exists?(File.join(rootdir, 'Makefile')) config[:rake] = File.exists?(File.join(rootdir, 'Rakefile')) config end
ruby
{ "resource": "" }
q5549
Opee.Collector.collect
train
def collect(job, path_id=nil) key = job_key(job) token = @cache[key] token = update_token(job, token, path_id) if complete?(job, token) @cache.delete(key) keep_going(job) else @cache[key] = token end end
ruby
{ "resource": "" }
q5550
Opee.Collector.update_token
train
def update_token(job, token, path_id) raise NotImplementedError.new("neither Collector.update_token() nor Job.update_token() are implemented") unless job.respond_to?(:update_token) job.update_token(token, path_id) end
ruby
{ "resource": "" }
q5551
Opee.Collector.complete?
train
def complete?(job, token) raise NotImplementedError.new("neither Collector.complete?() nor Job.complete?() are implemented") unless job.respond_to?(:complete?) job.complete?(token) end
ruby
{ "resource": "" }
q5552
YellowApi.Config.reset
train
def reset self.apikey = DEFAULT_APIKEY self.endpoint = DEFAULT_ENDPOINT self.sandbox_endpoint = DEFAULT_SANDBOX_ENDPOINT self.sandbox_enabled = DEFAULT_SANDBOX_ENABLED self.fmt = DEFAULT_FMT end
ruby
{ "resource": "" }
q5553
Shart.Sync.upload
train
def upload(&block) @source.files.each do |key, file| object = @target.files.create({ :key => key, :body => file, :public => true, :cache_control => 'max-age=0' # Disable cache on S3 so that future sharts are visible if folks web browsers. }) block.call file, object end end
ruby
{ "resource": "" }
q5554
Shart.Sync.clean
train
def clean(&block) @target.files.each do |object| unless @source.files.include? object.key block.call(object) object.destroy end end end
ruby
{ "resource": "" }
q5555
RakeOE.KeyValueReader.add
train
def add(key, value) if @env.has_key?(key) @env[key] += value else set(key,value) end end
ruby
{ "resource": "" }
q5556
RakeOE.BinaryBase.handle_qt
train
def handle_qt unless tc.qt.check_once puts '### WARN: QT prerequisites not complete!' end @settings['ADD_CFLAGS'] += tc.qt.cflags @settings['ADD_CXXFLAGS'] += tc.qt.cflags @settings['ADD_LDFLAGS'] += tc.qt.ldflags @settings['ADD_LIBS'] += tc.qt.libs end
ruby
{ "resource": "" }
q5557
RakeOE.BinaryBase.src_directories
train
def src_directories(main_dir, sub_dirs, params={}) if params[:subdir_only] all_dirs=[] else all_dirs = [main_dir] end sub_dirs.each do |dir| all_dirs << "#{main_dir}/#{dir}" end all_dirs.compact end
ruby
{ "resource": "" }
q5558
RakeOE.BinaryBase.lib_incs
train
def lib_incs(libs=[]) includes = Array.new libs.each do |name, param| lib_includes = PrjFileCache.exported_lib_incs(name) includes += lib_includes if lib_includes.any? end includes end
ruby
{ "resource": "" }
q5559
RakeOE.BinaryBase.search_files
train
def search_files(directories, extensions) extensions.each_with_object([]) do |ext, obj| directories.each do |dir| obj << FileList["#{dir}/*#{ext}"] end end.flatten.compact end
ruby
{ "resource": "" }
q5560
RakeOE.BinaryBase.find_files_relative
train
def find_files_relative(directory, files) return [] unless files.any? files.each_with_object([]) do |file, obj| path = "#{directory}/#{file}" obj << path if File.exist?(path) end end
ruby
{ "resource": "" }
q5561
RakeOE.BinaryBase.read_prj_settings
train
def read_prj_settings(file) unless File.file?(file) file = File.dirname(__FILE__)+'/prj.rake' end KeyValueReader.new(file) end
ruby
{ "resource": "" }
q5562
RakeOE.BinaryBase.load_deps
train
def load_deps(deps) deps.each do |file| if File.file?(file) Rake::MakefileLoader.new.load(file) end end end
ruby
{ "resource": "" }
q5563
RakeOE.BinaryBase.obj_to_source
train
def obj_to_source(obj, source_dir, obj_dir) stub = obj.gsub(obj_dir, source_dir).ext('') src = stub_to_src(stub) return src if src raise "No matching source for #{obj} found." end
ruby
{ "resource": "" }
q5564
RakeOE.BinaryBase.dep_to_source
train
def dep_to_source(dep, source_dir, dep_dir) stub = dep.gsub(dep_dir, source_dir).ext('') src = stub_to_src(stub) return src if src raise "No matching source for #{dep} found." end
ruby
{ "resource": "" }
q5565
RakeOE.BinaryBase.platform_flags_fixup
train
def platform_flags_fixup(libs) libs[:all].each do |lib| ps = tc.platform_settings_for(lib) unless ps.empty? @settings['ADD_CFLAGS'] += " #{ps[:CFLAGS]}" if ps[:CFLAGS] @settings['ADD_CXXFLAGS'] += " #{ps[:CXXFLAGS]}" if ps[:CXXFLAGS] # remove all -lXX settings from ps[:LDFLAGS] and use rest for @settings['ADD_LDFLAGS'], # -lXX is set in Toolchain#linker_line_for @settings['ADD_LDFLAGS'] += ps[:LDFLAGS].gsub(/(\s|^)+-l\S+/, '') if ps[:LDFLAGS] end end end
ruby
{ "resource": "" }
q5566
RakeOE.BinaryBase.search_libs
train
def search_libs(settings) # get all libs specified in ADD_LIBS search_libs = settings['ADD_LIBS'].split our_lib_deps = [] search_libs.each do |lib| our_lib_deps << lib deps_of_lib = @@all_libs_and_deps[lib] if deps_of_lib our_lib_deps += deps_of_lib end end our_lib_deps.uniq! # match libs found by toolchain solibs_local = [] alibs_local = [] our_lib_deps.each do |lib| if PrjFileCache.contain?('LIB', lib) alibs_local << lib elsif PrjFileCache.contain?('SOLIB', lib) solibs_local << lib end end local_libs = (alibs_local + solibs_local) || [] # return value is a hash { :local => local_libs, :local_alibs => alibs_local, :local_solibs => solibs_local, :all => our_lib_deps } end
ruby
{ "resource": "" }
q5567
RakeOE.BinaryBase.paths_of_libs
train
def paths_of_libs(some_libs) local_libs = Array.new some_libs.each do |lib| if PrjFileCache.contain?('LIB', lib) local_libs << "#{tc.settings['LIB_OUT']}/lib#{lib}.a" elsif PrjFileCache.contain?('SOLIB', lib) local_libs << "#{tc.settings['LIB_OUT']}/lib#{lib}.so" end end local_libs end
ruby
{ "resource": "" }
q5568
RakeOE.BinaryBase.paths_of_local_libs
train
def paths_of_local_libs local_libs = Array.new each_local_lib() do |lib| if PrjFileCache.contain?('LIB', lib) local_libs << "#{tc.settings['LIB_OUT']}/lib#{lib}.a" elsif PrjFileCache.contain?('SOLIB', lib) local_libs << "#{tc.settings['LIB_OUT']}/lib#{lib}.so" end end local_libs end
ruby
{ "resource": "" }
q5569
Cassie::Statements.Statement.to_cql
train
def to_cql if statement.respond_to?(:cql) && statement.respond_to?(:params) Cassie::Support::StatementParser.new(statement).to_cql else statement.to_s end end
ruby
{ "resource": "" }
q5570
OpenID.GoogleDiscovery.discover_user
train
def discover_user(domain, claimed_id) url = fetch_host_meta(domain) if url.nil? return nil # Not a Google Apps domain end xrds = fetch_xrds(domain, url) user_url, authority = get_user_xrds_url(xrds, claimed_id) user_xrds = fetch_xrds(authority, user_url, false) return if user_xrds.nil? endpoints = OpenID::OpenIDServiceEndpoint.from_xrds(claimed_id, user_xrds) return [claimed_id, OpenID.get_op_or_user_services(endpoints)] end
ruby
{ "resource": "" }
q5571
OpenID.GoogleDiscovery.discover_site
train
def discover_site(domain) url = fetch_host_meta(domain) if url.nil? return nil # Not a Google Apps domain end xrds = fetch_xrds(domain, url) unless xrds.nil? endpoints = OpenID::OpenIDServiceEndpoint.from_xrds(domain, xrds) return [domain, OpenID.get_op_or_user_services(endpoints)] end return nil end
ruby
{ "resource": "" }
q5572
OpenID.GoogleDiscovery.fetch_host_meta
train
def fetch_host_meta(domain) cached_value = get_cache(domain) return cached_value unless cached_value.nil? host_meta_url = "https://www.google.com/accounts/o8/.well-known/host-meta?hd=#{CGI::escape(domain)}" http_resp = OpenID.fetch(host_meta_url) if http_resp.code != "200" and http_resp.code != "206" return nil end matches = /Link: <(.*)>/.match( http_resp.body ) if matches.nil? return nil end put_cache(domain, matches[1]) return matches[1] end
ruby
{ "resource": "" }
q5573
OpenID.GoogleDiscovery.fetch_xrds
train
def fetch_xrds(authority, url, cache=true) return if url.nil? cached_xrds = get_cache(url) return cached_xrds unless cached_xrds.nil? http_resp = OpenID.fetch(url) return if http_resp.code != "200" and http_resp.code != "206" body = http_resp.body signature = http_resp["Signature"] signed_by = SimpleSign.verify(body, signature) if !signed_by.casecmp(authority) or !signed_by.casecmp('hosted-id.google.com') return false # Signed, but not by the right domain. end # Everything is OK if cache put_cache(url, body) end return body end
ruby
{ "resource": "" }
q5574
OpenID.GoogleDiscovery.get_user_xrds_url
train
def get_user_xrds_url(xrds, claimed_id) types_to_match = ['http://www.iana.org/assignments/relation/describedby'] services = OpenID::Yadis::apply_filter(claimed_id, xrds) services.each do | service | if service.match_types(types_to_match) template = REXML::XPath.first(service.service_element, '//openid:URITemplate', NAMESPACES) authority = REXML::XPath.first(service.service_element, '//openid:NextAuthority', NAMESPACES) url = template.text.gsub('{%uri}', CGI::escape(claimed_id)) return [url, authority.text] end end end
ruby
{ "resource": "" }
q5575
Pipeline.Builder.build_operation_chain
train
def build_operation_chain(stack) empty_op = EmptyOperation.new(nil) stack.reverse.reduce(empty_op) do |next_op, current_op| klass, args, block = current_op if Class === klass klass.new(next_op, *args, &block) elsif Proc === klass lambda do |env| next_op.call(klass.call(env, *args)) end else raise StandardError, "Invalid operation, doesn't respond to `call`: #{klass.inspect}" end end end
ruby
{ "resource": "" }
q5576
RepoManager.BaseAsset.method_missing
train
def method_missing(name, *args, &block) return attributes[name.to_sym] if attributes.include?(name.to_sym) return super end
ruby
{ "resource": "" }
q5577
Arbre.Element.helper_method
train
def helper_method(name, *args, &block) if name.match /_path$/ helpers.send(name, *args, &block) elsif (const_get([name, 'engine'].join('/').classify) rescue nil) helpers.send(name, *args, &block) else current_arbre_element.add_child helpers.send(name, *args, &block) end end
ruby
{ "resource": "" }
q5578
Todonotes.Todonotes.log2file
train
def log2file(filename = File.basename($0) + '.todo', level = Log4r::ALL) @logger.add( Log4r::FileOutputter.new('ToDo', :filename => filename, :level => level, :formatter => FixmeFormatter )) end
ruby
{ "resource": "" }
q5579
Cobbler.Base.save
train
def save unless [ :handle, :new, :modify, :save ].all?{|method| api_methods[method] } raise "Not all necessary api methods are defined to process this action!" end entry = self.class.find_one(name) self.class.in_transaction(true) do |token| if entry entryid = self.class.make_call(api_methods[:handle],name,token) else entryid = self.class.make_call(api_methods[:new],token) self.class.make_call(api_methods[:modify],entryid,'name', name, token) end cobbler_record_fields.each do |field| field_s = field.to_s if !locked_fields.include?(field) && user_definitions.has_key?(field_s) self.class.make_call(api_methods[:modify],entryid,field_s, user_definitions[field_s], token) end end cobbler_collections_store_callbacks.each do |callback| send(callback,entryid,token) end self.class.make_call(api_methods[:save],entryid,token) end end
ruby
{ "resource": "" }
q5580
Cobbler.Base.remove
train
def remove raise "Not all necessary api methods are defined to process this action!" unless api_methods[:remove] self.class.in_transaction(true) do |token| self.class.make_call(api_methods[:remove],name,token) end end
ruby
{ "resource": "" }
q5581
Cobbler.Base.copy
train
def copy(newname) raise "Not all necessary api methods are defined to process this action!" unless api_methods[:copy] entry = self.class.find_one(name) if entry self.class.in_transaction(true) do |token| entryid = self.class.make_call(api_methods[:handle],name,token) self.class.make_call(api_methods[:copy],entryid,newname,token) end end end
ruby
{ "resource": "" }
q5582
AppRepo.Setup.generate_apprepo_file
train
def generate_apprepo_file(_apprepo_path, options) # v = options[:app].latest_version # generate_apprepo_file(v, File.join(apprepo_path, 'manifest.json')) # Generate the final Repofile here gem_path = Helper.gem_path('apprepo') apprepo = File.read("#{gem_path}/../assets/RepofileDefault") apprepo.gsub!('[[APP_IDENTIFIER]]', options[:app].bundle_id) apprepo.gsub!('[[APPREPO_IPA_PATH]]', options[:app].file_path) apprepo.gsub!('[[APP_VERSION]]', options[:app].version) apprepo.gsub!('[[APP_NAME]]', options[:app].name) # apprepo (was deliver) end
ruby
{ "resource": "" }
q5583
ActsAsNestedInterval.ClassMethods.rebuild_nested_interval_tree!
train
def rebuild_nested_interval_tree! # temporary changes skip_callback :update, :before, :update_nested_interval old_default_scopes = default_scopes # save to revert later default_scope ->{ where("#{quoted_table_name}.lftq > 0") } # use lft1 > 0 as a "migrated?" flag # zero all intervals update_hash = {lftp: 0, lftq: 0} update_hash[:rgtp] = 0 if columns_hash["rgtp"] update_hash[:rgtq] = 0 if columns_hash["rgtq"] update_hash[:lft] = 0 if columns_hash["lft"] update_hash[:rgt] = 0 if columns_hash["rgt"] update_all update_hash # recompute intervals with a recursive lambda clear_cache! update_subtree = ->(node){ node.create_nested_interval node.save node.class.unscoped.where(nested_interval.foreign_key => node.id).find_each &update_subtree } unscoped.roots.find_each &update_subtree # revert changes set_callback :update, :before, :update_nested_interval self.default_scopes = old_default_scopes end
ruby
{ "resource": "" }
q5584
CLIUtils.Pref.deliver
train
def deliver(default = nil) # Design decision: the pre-prompt behavior # gets evaluated *once*, not every time the # user gets prompted. This prevents multiple # evaluations when bad options are provided. _eval_pre if @pre valid_option_chosen = false until valid_option_chosen response = messenger.prompt(@prompt_text, default) if validate(response) valid_option_chosen = true @answer = evaluate_behaviors(response) _eval_post if @post else messenger.error(@last_error_message) end end end
ruby
{ "resource": "" }
q5585
CLIUtils.Pref.evaluate_behaviors
train
def evaluate_behaviors(text) modified_text = text if @behavior_objects @behavior_objects.each do |b| modified_text = b.evaluate(modified_text) end end modified_text end
ruby
{ "resource": "" }
q5586
CLIUtils.Pref._check_validators
train
def _check_validators(text) ret = true if @validator_objects @validator_objects.each do |v| v.validate(text) unless v.is_valid @last_error_message = v.message ret = false end end end ret end
ruby
{ "resource": "" }
q5587
CLIUtils.Pref._init_action
train
def _init_action(action_hash) obj = _load_asset(ASSET_TYPE_ACTION, action_hash[:name]) obj.parameters = action_hash[:parameters] obj end
ruby
{ "resource": "" }
q5588
CLIUtils.Pref._init_and_add_behavior
train
def _init_and_add_behavior(behavior_hash) obj = _load_asset(ASSET_TYPE_BEHAVIOR, behavior_hash[:name]) unless obj.nil? obj.parameters = behavior_hash[:parameters] @behavior_objects << obj end end
ruby
{ "resource": "" }
q5589
ISE.Symbol.each_attribute
train
def each_attribute #If we weren't passed a block, return an enumerator referencing this function. return enum_for(:each_attribute) unless block_given? #Yield each of the known attributes in turn. @xml.css("symbol attr").each do |attr| yield attr.attribute('name').value, attr.attribute('value').value end end
ruby
{ "resource": "" }
q5590
ISE.Symbol.set_pin_name
train
def set_pin_name(node, name) return unless node.name == "pin" #Change the name of any pin-label "text attributes" that reference the given pin. original_name = get_pin_name(node) #Retrieve a collection of all attributes that match the pin's original name... pin_labels = @xml.css("symbol graph attrtext[attrname=\"PinName\"][type=\"pin #{original_name}\"]") #And modify them so they now match the new node's name. pin_labels.each { |pin| pin.attribute('type').value = "pin #{name}" } #Finally, set the name of the node itself. node.attribute("name").value = name end
ruby
{ "resource": "" }
q5591
ISE.Symbol.set_pin_width!
train
def set_pin_width!(node, width) #Get the components of the given bus' name. _, left, right = parse_pin_name(get_pin_name(node)) #If the pin wasn't initially a bus, make it one. left ||= 0 right ||= 0 #If our right bound is greater than our left one, adjust it. if right > left right = left + width - 1 #Otherwise, adjust the left width. else left = right + width - 1 end #Set the pin's bounds. set_pin_bounds!(node, left, right) end
ruby
{ "resource": "" }
q5592
Praxis.Blueprint.render
train
def render(view_name = nil, context: Attributor::DEFAULT_ROOT_CONTEXT, renderer: Renderer.new, **opts) if !view_name.nil? warn 'DEPRECATED: please do not pass the view name as the first parameter in Blueprint.render, pass through the view: named param instead.' elsif opts.key?(:view) view_name = opts[:view] end fields = opts[:fields] view_name = :default if view_name.nil? && fields.nil? if view_name unless (view = self.class.views[view_name]) raise "view with name '#{view_name.inspect}' is not defined in #{self.class}" end return view.render(self, context: context, renderer: renderer) end # Accept a simple array of fields, and transform it to a 1-level hash with true values if fields.is_a? Array fields = fields.each_with_object({}) { |field, hash| hash[field] = true } end # expand fields expanded_fields = FieldExpander.expand(self.class, fields) renderer.render(self, expanded_fields, context: context) end
ruby
{ "resource": "" }
q5593
Cassie::Schema::Migration::DSL.ColumnOperations.add_column
train
def add_column(table_name, column_name, type, options = {}) table_definition = TableDefinition.new if !table_definition.respond_to?(type) raise Errors::MigrationDefinitionError("Type '#{type}' is not valid for cassandra migration.") end table_definition.send(type, column_name, options) announce_operation "add_column(#{column_name}, #{type})" cql = "ALTER TABLE #{table_name} ADD " cql << table_definition.to_add_column_cql announce_suboperation cql execute cql end
ruby
{ "resource": "" }
q5594
ServerSentEvents.Client.listen
train
def listen Net::HTTP.start(@address.host, @address.port) do |http| # TODO(@tadeboro): Add support for adding custom headers (auth) http.request(Net::HTTP::Get.new(@address)) do |response| # TODO(@tadeboro): Handle non-200 here response.read_body do |chunk| @parser.push(chunk).each { |e| yield(e) } end end end end
ruby
{ "resource": "" }
q5595
Wanikani.SRS.srs_distribution
train
def srs_distribution(item_type = "all") raise ArgumentError, "Please use a valid SRS type (or none for all types)" if !ITEM_TYPES.include?(item_type) response = api_response("srs-distribution") srs_distribution = response["requested_information"] return srs_distribution if item_type == "all" return srs_distribution[item_type] end
ruby
{ "resource": "" }
q5596
Wanikani.SRS.srs_items_by_type
train
def srs_items_by_type(item_type) raise ArgumentError, "Please use a valid SRS type." if !ITEM_TYPES.include?(item_type) || item_type == "all" items_by_type = [] %w(radicals kanji vocabulary).each do |type| items = send("#{type}_list") items.reject! { |item| item["user_specific"].nil? || item["user_specific"]["srs"] != item_type }.map! do |item| item.merge!("type" => (type == 'radicals' ? 'radical' : type)) end items_by_type << items end items_by_type.flatten end
ruby
{ "resource": "" }
q5597
Opee.Queue.add
train
def add(job) if @workers.empty? @work_queue.insert(0, job) else worker = @workers.pop() ask_worker(worker, job) end end
ruby
{ "resource": "" }
q5598
Opee.Queue.ready
train
def ready(worker) if @work_queue.empty? @workers.insert(0, worker) unless @workers.include?(worker) else job = @work_queue.pop() @add_thread.wakeup() unless @add_thread.nil? ask_worker(worker, job) end end
ruby
{ "resource": "" }
q5599
Saddle.Requester.post
train
def post(url, data={}, options={}) response = connection.post do |req| req.saddle_options = options req.url(url) req.body = data end handle_response(response) end
ruby
{ "resource": "" }