_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q5400
GuessHtmlEncoding.HTMLScanner.charset_from_meta_content
train
def charset_from_meta_content(string) charset_match = string.match(/charset\s*\=\s*(.+)/i) if charset_match charset_value = charset_match[1] charset_value[/\A\"(.*)\"/, 1] || charset_value[/\A\'(.*)\'/, 1] || charset_value[/(.*)[\s;]/, 1] || charset_value[/(.*)/, ...
ruby
{ "resource": "" }
q5401
GuessHtmlEncoding.HTMLScanner.attribute_value
train
def attribute_value(string) attribute_value = '' position = 0 length = string.length while position < length # x09 (ASCII TAB), 0x0A (ASCII LF), 0x0C (ASCII FF), 0x0D (ASCII CR), or 0x20 (ASCII space) then advance position to the next byte, then, repeat this step. if str...
ruby
{ "resource": "" }
q5402
OQGraph.Node.create_edge_to_and_from
train
def create_edge_to_and_from(other, weight = 1.0) self.class.edge_class.create!(:from_id => id, :to_id => other.id, :weight => weight) self.class.edge_class.create!(:from_id => other.id, :to_id => id, :weight => weight) end
ruby
{ "resource": "" }
q5403
OQGraph.Node.path_weight_to
train
def path_weight_to(other) shortest_path_to(other,:method => :djikstra).map{|edge| edge.weight.to_f}.sum end
ruby
{ "resource": "" }
q5404
GuiGeo.Rectangle.bound
train
def bound(val) case val when Rectangle then r = val.clone r.size = r.size.min(size) r.loc = r.loc.bound(loc, loc + size - val.size) r when Point then (val-loc).bound(point, size) + loc else raise ArgumentError.new("wrong type: (#{val.class}) - Rectangle or Point expected") en...
ruby
{ "resource": "" }
q5405
GuiGeo.Rectangle.disjoint
train
def disjoint(b) return self if !b || contains(b) return b if b.contains(self) return self,b unless overlaps?(b) tl_contained = contains?(b.tl) ? 1 : 0 tr_contained = contains?(b.tr) ? 1 : 0 bl_contained = contains?(b.bl) ? 1 : 0 br_contained = contains?(b.br) ? 1 : 0 sum = tl_contained +...
ruby
{ "resource": "" }
q5406
PogoPlug.Client.version
train
def version response = get('/getVersion', {}, false) ApiVersion.new(response.body['version'], response.body['builddate']) end
ruby
{ "resource": "" }
q5407
PogoPlug.Client.devices
train
def devices response = get('/listDevices') devices = [] response.body['devices'].each do |d| devices << Device.from_json(d, @token, @logger) end devices end
ruby
{ "resource": "" }
q5408
PogoPlug.Client.services
train
def services(device_id=nil, shared=false) params = { shared: shared } params[:deviceid] = device_id unless device_id.nil? response = get('/listServices', params) services = [] response.body['services'].each do |s| services << Service.from_json(s, @token, @logger) end s...
ruby
{ "resource": "" }
q5409
Serif.FileDigest.render
train
def render(context) return "" unless ENV["ENV"] == "production" full_path = File.join(context["site"]["__directory"], @path.strip) return @prefix + DIGEST_CACHE[full_path] if DIGEST_CACHE[full_path] digest = Digest::MD5.hexdigest(File.read(full_path)) DIGEST_CACHE[full_path] = digest ...
ruby
{ "resource": "" }
q5410
Substation.Dispatcher.call
train
def call(name, input) fetch(name).call(Request.new(name, env, input)) end
ruby
{ "resource": "" }
q5411
QnAMaker.Client.create_kb
train
def create_kb(name, qna_pairs = [], urls = []) response = @http.post( "#{BASE_URL}/create", json: { name: name, qnaPairs: qna_pairs.map { |pair| { question: pair[0], answer: pair[1] } }, urls: urls } ) case response.code when 201 QnA...
ruby
{ "resource": "" }
q5412
MongoDoc.Index.index
train
def index(*args) options_and_fields = args.extract_options! if args.any? collection.create_index(args.first, options_and_fields) else fields = options_and_fields.except(*OPTIONS) options = options_and_fields.slice(*OPTIONS) collection.create_index(to_mongo_direction(fie...
ruby
{ "resource": "" }
q5413
Rubikon.ProgressBar.+
train
def +(value = 1) return if (value <= 0) || (@value == @maximum) @value += value old_progress = @progress add_progress = ((@value - @progress / @factor) * @factor).round @progress += add_progress if @progress > @size @progress = @size add_progress = @size - old_progre...
ruby
{ "resource": "" }
q5414
Borrower.PublicAPI.put
train
def put content, destination, on_conflict=:overwrite if on_conflict != :overwrite && Content::Item.new( destination ).exists? case on_conflict when :skip then return when :prompt then input = Util.get_input "a file already exists at #{destination}\noverwrite? (y|n): " ...
ruby
{ "resource": "" }
q5415
Ciphers.Caesar.encipher
train
def encipher(message,shift) assert_valid_shift!(shift) real_shift = convert_shift(shift) message.split("").map do|char| mod = (char =~ /[a-z]/) ? 123 : 91 offset = (char =~ /[a-z]/) ? 97 : 65 (char =~ /[^a-zA-Z]/) ? char : CryptBuffer(char).add(real_shift, m...
ruby
{ "resource": "" }
q5416
PogoPlug.ServiceClient.create_entity
train
def create_entity(file, io = nil, properties = {}) params = { deviceid: @device_id, serviceid: @service_id, filename: file.name, type: file.type }.merge(properties) params[:parentid] = file.parent_id unless file.parent_id.nil? if params[:properties] params[:properties] = params[:properties].t...
ruby
{ "resource": "" }
q5417
Assemblotron.AssemblerManager.load_assemblers
train
def load_assemblers Biopsy::Settings.instance.target_dir.each do |dir| Dir.chdir dir do Dir['*.yml'].each do |file| name = File.basename(file, '.yml') target = Assembler.new target.load_by_name name unless System.match? target.bindeps[:url] ...
ruby
{ "resource": "" }
q5418
Assemblotron.AssemblerManager.assembler_names
train
def assembler_names a = [] @assemblers.each do |t| a << t.name a << t.shortname if t.shortname end a end
ruby
{ "resource": "" }
q5419
Assemblotron.AssemblerManager.list_assemblers
train
def list_assemblers str = "" if @assemblers.empty? str << "\nNo assemblers are currently installed! Please install some.\n" else str << <<-EOS Installed assemblers are listed below. Shortnames are shown in brackets if available. Assemblers installed: EOS @assemblers.each ...
ruby
{ "resource": "" }
q5420
Assemblotron.AssemblerManager.get_assembler
train
def get_assembler assembler ret = @assemblers.find do |a| a.name == assembler || a.shortname == assembler end raise "couldn't find assembler #{assembler}" if ret.nil? ret end
ruby
{ "resource": "" }
q5421
Assemblotron.AssemblerManager.run_all_assemblers
train
def run_all_assemblers options res = {} subset = false unless options[:assemblers] == 'all' subset = options[:assemblers].split(',') missing = [] subset.each do |choice| missing < choice unless @assemblers.any do |a| a.name == choice || a.shortname == cho...
ruby
{ "resource": "" }
q5422
Assemblotron.AssemblerManager.run_assembler
train
def run_assembler assembler # run the optimisation opts = @options.clone opts[:left] = opts[:left_subset] opts[:right] = opts[:right_subset] if @options[:optimiser] == 'sweep' logger.info("Using full parameter sweep optimiser") algorithm = Biopsy::ParameterSweeper.new(assem...
ruby
{ "resource": "" }
q5423
Chatrix.Rooms.[]
train
def [](id) return @rooms[id] if id.start_with? '!' if id.start_with? '#' res = @rooms.find { |_, r| r.canonical_alias == id } return res.last if res.respond_to? :last end res = @rooms.find { |_, r| r.name == id } res.last if res.respond_to? :last end
ruby
{ "resource": "" }
q5424
Chatrix.Rooms.process_events
train
def process_events(events) process_join events['join'] if events.key? 'join' process_invite events['invite'] if events.key? 'invite' process_leave events['leave'] if events.key? 'leave' end
ruby
{ "resource": "" }
q5425
Chatrix.Rooms.get_room
train
def get_room(id) return @rooms[id] if @rooms.key? id room = Room.new id, @users, @matrix @rooms[id] = room broadcast(:added, room) room end
ruby
{ "resource": "" }
q5426
Chatrix.Rooms.process_join
train
def process_join(events) events.each do |room, data| get_room(room).process_join data end end
ruby
{ "resource": "" }
q5427
Chatrix.Rooms.process_invite
train
def process_invite(events) events.each do |room, data| get_room(room).process_invite data end end
ruby
{ "resource": "" }
q5428
Chatrix.Rooms.process_leave
train
def process_leave(events) events.each do |room, data| get_room(room).process_leave data end end
ruby
{ "resource": "" }
q5429
ResourcesController.Helper.method_missing
train
def method_missing(method, *args, &block) if controller.resource_named_route_helper_method?(method) self.class.send(:delegate, method, :to => :controller) controller.send(method, *args) else super(method, *args, &block) end end
ruby
{ "resource": "" }
q5430
LatoCore.Widgets::Index::Cell.generate_table_head
train
def generate_table_head labels = [] if @args[:head] && @args[:head].length > 0 # manage case with custom head labels = [] if @args[:actions_on_start] && @show_row_actions labels.push(LANGUAGES[:lato_core][:mixed][:actions]) end @args[:head]....
ruby
{ "resource": "" }
q5431
LatoCore.Widgets::Index::Cell.generate_table_rows
train
def generate_table_rows table_rows = [] if @args[:columns] && @args[:columns].length > 0 # manage case with custom columns table_rows = generate_table_rows_from_columns_functions(@args[:columns]) elsif @records && @records.length > 0 # manage case without custom co...
ruby
{ "resource": "" }
q5432
LatoCore.Widgets::Index::Cell.generate_table_rows_from_columns_functions
train
def generate_table_rows_from_columns_functions columns_functions table_rows = [] @records.each do |record| labels = [] # add actions to row columns if @args[:actions_on_start] && @show_row_actions labels.push(generate_actions_bottongroup_for_record(record)) ...
ruby
{ "resource": "" }
q5433
LatoCore.Widgets::Index::Cell.generate_actions_bottongroup_for_record
train
def generate_actions_bottongroup_for_record record action_buttons = [] action_buttons.push(generate_show_button(record.id)) if @args[:actions][:show] action_buttons.push(generate_edit_button(record.id)) if @args[:actions][:edit] action_buttons.push(generate_delete_button(record.id)) if @...
ruby
{ "resource": "" }
q5434
LatoCore.Widgets::Index::Cell.generate_delete_button
train
def generate_delete_button record_id return unless @args[:index_url] url = @args[:index_url].end_with?('/') ? "#{@args[:index_url].gsub(/\?.*/, '')}#{record_id}" : "#{@args[:index_url].gsub(/\?.*/, '')}/#{record_id}" return LatoCore::Elements::Button::Cell.new(label: LANGUAGES[:lato_core][:mixed...
ruby
{ "resource": "" }
q5435
LatoCore.Widgets::Index::Cell.generate_new_button
train
def generate_new_button return unless @args[:index_url] url = "#{@args[:index_url].gsub(/\?.*/, '')}/new" return LatoCore::Elements::Button::Cell.new(label: LANGUAGES[:lato_core][:mixed][:new], url: url, icon: 'plus') end
ruby
{ "resource": "" }
q5436
LatoCore.Widgets::Index::Cell.generate_search_input
train
def generate_search_input search_placeholder = '' if @args[:records].is_a?(Hash) search_placeholder = @args[:records][:search_key].is_a?(Array) ? @args[:records][:search_key].to_sentence : @args[:records][:search_key].humanize end search_value = @args[:records].is_a?(Hash) ? @a...
ruby
{ "resource": "" }
q5437
LatoCore.Widgets::Index::Cell.generate_search_submit
train
def generate_search_submit return LatoCore::Elements::Button::Cell.new(label: ' ', icon: 'search', type: 'submit', icon_align: 'right') end
ruby
{ "resource": "" }
q5438
ConfigCurator.ConfigFile.install_file
train
def install_file FileUtils.mkdir_p File.dirname(destination_path) FileUtils.copy source_path, destination_path, preserve: true end
ruby
{ "resource": "" }
q5439
Algebra.Polynomial.need_paren_in_coeff?
train
def need_paren_in_coeff? if constant? c = @coeff[0] if c.respond_to?(:need_paren_in_coeff?) c.need_paren_in_coeff? elsif c.is_a?(Numeric) false else true end elsif !monomial? true else false end end
ruby
{ "resource": "" }
q5440
ExpressPigeon.Messages.reports
train
def reports(from_id, start_date = nil, end_date = nil) params = [] if from_id params << "from_id=#{from_id}" end if start_date and not end_date raise 'must include both start_date and end_date' end if end_date and not start_date raise 'must include both star...
ruby
{ "resource": "" }
q5441
QnAMaker.Client.train_kb
train
def train_kb(feedback_records = []) feedback_records = feedback_records.map do |record| { userId: record[0], userQuestion: record[1], kbQuestion: record[2], kbAnswer: record[3] } end response = @http.patch( "#{BASE_URL}/#{@knowledgebase_id}/train", ...
ruby
{ "resource": "" }
q5442
TSparser.AribTime.convert_mjd_to_date
train
def convert_mjd_to_date(mjd) y_ = ((mjd - 15078.2) / 365.25).to_i m_ = ((mjd - 14956.1 - (y_ * 365.25).to_i) / 30.6001).to_i d = mjd - 14956 - (y_ * 365.25).to_i - (m_ * 30.6001).to_i k = (m_ == 14 || m_ == 15) ? 1 : 0 y = y_ + k m = m_ - 1 - k * 12 return Date.new(1...
ruby
{ "resource": "" }
q5443
Substation.Chain.call
train
def call(request) reduce(request) { |result, processor| begin response = processor.call(result) return response unless processor.success?(response) processor.result(response) rescue => exception return on_exception(request, result.data, exception) en...
ruby
{ "resource": "" }
q5444
Substation.Chain.on_exception
train
def on_exception(state, data, exception) response = self.class.exception_response(state, data, exception) exception_chain.call(response) end
ruby
{ "resource": "" }
q5445
EISCP.Receiver.update_state
train
def update_state Thread.new do Dictionary.commands.each do |zone, commands| Dictionary.commands[zone].each do |command, info| info[:values].each do |value, _| if value == 'QSTN' send(Parser.parse(command + "QSTN")) # If we send any faster...
ruby
{ "resource": "" }
q5446
SweetNotifications.ControllerRuntime.controller_runtime
train
def controller_runtime(name, log_subscriber) runtime_attr = "#{name.to_s.underscore}_runtime".to_sym Module.new do extend ActiveSupport::Concern attr_internal runtime_attr protected define_method :process_action do |action, *args| log_subscriber.reset_runtime ...
ruby
{ "resource": "" }
q5447
LatoCore.Interface::Apihelpers.core__send_request_success
train
def core__send_request_success(payload) response = { result: true, error_message: nil } response[:payload] = payload if payload render json: response end
ruby
{ "resource": "" }
q5448
LatoCore.Interface::Apihelpers.core__send_request_fail
train
def core__send_request_fail(error, payload: nil) response = { result: false, error_message: error } response[:payload] = payload if payload render json: response end
ruby
{ "resource": "" }
q5449
Siba.SibaFile.shell_ok?
train
def shell_ok?(command) # Using Open3 instead of `` or system("cmd") in order to hide stderr output sout, status = Open3.capture2e command return status.to_i == 0 rescue return false end
ruby
{ "resource": "" }
q5450
Disclaimer.Document.modify_via_segment_holder_acts_as_list_method
train
def modify_via_segment_holder_acts_as_list_method(method, segment) segment_holder = segment_holder_for(segment) raise segment_not_associated_message(method, segment) unless segment_holder segment_holder.send(method) end
ruby
{ "resource": "" }
q5451
MongoDoc.Document.update
train
def update(attrs, safe = false) self.attributes = attrs if new_record? _root.send(:_save, safe) if _root _save(safe) else _update_attributes(converted_attributes(attrs), safe) end end
ruby
{ "resource": "" }
q5452
QnAMaker.Client.download_kb
train
def download_kb response = @http.get( "#{BASE_URL}/#{@knowledgebase_id}" ) case response.code when 200 response.parse when 400 raise BadArgumentError, response.parse['error']['message'].join(' ') when 401 raise UnauthorizedError, response.parse['error...
ruby
{ "resource": "" }
q5453
Bcome::Orchestration.InteractiveTerraform.form_var_string
train
def form_var_string terraform_vars = terraform_metadata ec2_credentials = @node.network_driver.raw_fog_credentials cleaned_data = terraform_vars.select{|k,v| !v.is_a?(Hash) && !v.is_a?(Array) } # we can't yet handle nested terraform metadata on the command line so no arrays or hash...
ruby
{ "resource": "" }
q5454
Polisher.GemFiles.has_file_satisfied_by?
train
def has_file_satisfied_by?(spec_file) file_paths.any? { |gem_file| RPM::Spec.file_satisfies?(spec_file, gem_file) } end
ruby
{ "resource": "" }
q5455
Polisher.GemFiles.unpack
train
def unpack(&bl) dir = nil pkg = ::Gem::Installer.new gem_path, :unpack => true if bl Dir.mktmpdir do |tmpdir| pkg.unpack tmpdir bl.call tmpdir end else dir = Dir.mktmpdir pkg.unpack dir end dir end
ruby
{ "resource": "" }
q5456
Polisher.GemFiles.each_file
train
def each_file(&bl) unpack do |dir| Pathname.new(dir).find do |path| next if path.to_s == dir.to_s pathstr = path.to_s.gsub("#{dir}/", '') bl.call pathstr unless pathstr.blank? end end end
ruby
{ "resource": "" }
q5457
ConfigCurator.Component.install_component
train
def install_component if (backend != :stdlib && command?('rsync')) || backend == :rsync FileUtils.mkdir_p destination_path cmd = [command?('rsync'), '-rtc', '--del', '--links', "#{source_path}/", destination_path] logger.debug { "Running command: #{cmd.join ' '}" } system(*cmd) ...
ruby
{ "resource": "" }
q5458
ConfigCurator.Component.set_mode
train
def set_mode chmod = command? 'chmod' find = command? 'find' return unless chmod && find {fmode: 'f', dmode: 'd'}.each do |k, v| next if send(k).nil? cmd = [find, destination_path, '-type', v, '-exec'] cmd.concat [chmod, send(k).to_s(8), '{}', '+'] logger.debug ...
ruby
{ "resource": "" }
q5459
ConfigCurator.Component.set_owner
train
def set_owner return unless owner || group chown = command? 'chown' return unless chown cmd = [chown, '-R', "#{owner}:#{group}", destination_path] logger.debug { "Running command: #{cmd.join ' '}" } system(*cmd) end
ruby
{ "resource": "" }
q5460
Pokerstats.HandStatistics.calculate_player_position
train
def calculate_player_position screen_name @cached_player_position = {} @player_hashes.sort!{|a,b| button_relative_seat(a) <=> button_relative_seat(b)} @player_hashes = [@player_hashes.pop] + @player_hashes unless @player_hashes.first[:seat] == @button_player_index @player_hashes.each_with_index{...
ruby
{ "resource": "" }
q5461
Pokerstats.HandStatistics.betting_order?
train
def betting_order?(screen_name_first, screen_name_second) if button?(screen_name_first) false elsif button?(screen_name_second) true else position(screen_name_first) < position(screen_name_second) end end
ruby
{ "resource": "" }
q5462
Paginator.Pager.page
train
def page(number) number = (n = number.to_i) > 0 ? n : 1 Page.new(self, number, lambda { offset = (number - 1) * @per_page args = [offset] args << @per_page if @select.arity == 2 @select.call(*args) }) end
ruby
{ "resource": "" }
q5463
Auth.Mailgun.add_webhook_identifier_to_email
train
def add_webhook_identifier_to_email(email) email.message.mailgun_variables = {} email.message.mailgun_variables["webhook_identifier"] = BSON::ObjectId.new.to_s email end
ruby
{ "resource": "" }
q5464
DeploYML.Shell.ruby
train
def ruby(program,*arguments) command = [program, *arguments] # assume that `.rb` scripts do not have a `#!/usr/bin/env ruby` command.unshift('ruby') if program[-3,3] == '.rb' # if the environment uses bundler, run all ruby commands via `bundle exec` if (@environment && @environment.bundl...
ruby
{ "resource": "" }
q5465
DeploYML.Shell.shellescape
train
def shellescape(str) # An empty argument will be skipped, so return empty quotes. return "''" if str.empty? str = str.dup # Process as a single byte sequence because not all shell # implementations are multibyte aware. str.gsub!(/([^A-Za-z0-9_\-.,:\/@\n])/n, "\\\\\\1") # A L...
ruby
{ "resource": "" }
q5466
DeploYML.Shell.rake_task
train
def rake_task(name,*arguments) name = name.to_s unless arguments.empty? name += ('[' + arguments.join(',') + ']') end return name end
ruby
{ "resource": "" }
q5467
TSparser.Binary.read_byte_as_integer
train
def read_byte_as_integer(bytelen) unless bit_pointer % 8 == 0 raise BinaryException.new("Bit pointer must be pointing start of byte. " + "But now pointing #{bit_pointer}.") end if self.length - bit_pointer/8 < bytelen raise BinaryException.new("Rest of...
ruby
{ "resource": "" }
q5468
TSparser.Binary.read_one_bit
train
def read_one_bit unless self.length * 8 - bit_pointer > 0 raise BinaryException.new("Readable buffer doesn't exist" + "(#{self.length * 8 - bit_pointer}bit exists).") end response = to_i(bit_pointer/8)[7 - bit_pointer%8] bit_pointer_inc(1) return r...
ruby
{ "resource": "" }
q5469
TSparser.Binary.read_bit_as_binary
train
def read_bit_as_binary(bitlen) unless bit_pointer % 8 == 0 raise BinaryException.new("Bit pointer must be pointing start of byte. " + "But now pointing #{bit_pointer}.") end unless bitlen % 8 == 0 raise BinaryException.new("Arg must be integer of multi...
ruby
{ "resource": "" }
q5470
Bcome::Registry::Command.External.execute
train
def execute(node, arguments) full_command = construct_full_command(node, arguments) begin puts "\n(external) > #{full_command}".bc_blue + "\n\n" system(full_command) rescue Interrupt puts "\nExiting gracefully from interrupt\n".warning end end
ruby
{ "resource": "" }
q5471
Opto.Group.option
train
def option(option_name) if option_name.to_s.include?('.') parts = option_name.to_s.split('.') var_name = parts.pop group = parts.inject(self) do |base, part| grp = base.option(part).value if grp.nil? raise NameError, "No such group: #{base.name}.#{part}" ...
ruby
{ "resource": "" }
q5472
GovKit::ActsAsNoteworthy.ActMethods.acts_as_noteworthy
train
def acts_as_noteworthy(options={}) class_inheritable_accessor :options self.options = options unless included_modules.include? InstanceMethods instance_eval do has_many :mentions, :as => :owner, :order => 'date desc' with_options :as => :owner, :class_name => "Mention" do...
ruby
{ "resource": "" }
q5473
GovKit::ActsAsNoteworthy.InstanceMethods.raw_mentions
train
def raw_mentions opts = self.options.clone attributes = opts.delete(:with) if opts[:geo] opts[:geo] = self.instance_eval("#{opts[:geo]}") end query = [] attributes.each do |attr| query << self.instance_eval("#{attr}") end { :google_news => GovKi...
ruby
{ "resource": "" }
q5474
QnAMaker.Client.publish_kb
train
def publish_kb response = @http.put( "#{BASE_URL}/#{@knowledgebase_id}" ) case response.code when 204 nil when 400 raise BadArgumentError, response.parse['error']['message'].join(' ') when 401 raise UnauthorizedError, response.parse['error']['message'...
ruby
{ "resource": "" }
q5475
Push0r.ApnsPushMessage.simple
train
def simple(alert_text = nil, sound = nil, badge = nil, category = nil) new_payload = {aps: {}} if alert_text new_payload[:aps][:alert] = alert_text end if sound new_payload[:aps][:sound] = sound end if badge new_payload[:aps][:badge] = badge end if...
ruby
{ "resource": "" }
q5476
LatoCore.Interface::Cells.core__widgets_index
train
def core__widgets_index(records, search: nil, pagination: 50) response = { records: records, total: records.length, per_page: pagination, search: '', search_key: search, sort: '', sort_dir: 'ASC', pagination: 1, } # manage search i...
ruby
{ "resource": "" }
q5477
Configurable.ClassMethods.remove_config
train
def remove_config(key, options={}) unless config_registry.has_key?(key) raise NameError.new("#{key.inspect} is not a config on #{self}") end options = { :reader => true, :writer => true }.merge(options) config = config_registry.delete(key) reset_...
ruby
{ "resource": "" }
q5478
Configurable.ClassMethods.undef_config
train
def undef_config(key, options={}) unless configs.has_key?(key) raise NameError.new("#{key.inspect} is not a config on #{self}") end options = { :reader => true, :writer => true }.merge(options) config = configs[key] config_registry[key] = nil ...
ruby
{ "resource": "" }
q5479
Configurable.ClassMethods.remove_config_type
train
def remove_config_type(name) unless config_type_registry.has_key?(name) raise NameError.new("#{name.inspect} is not a config_type on #{self}") end config_type = config_type_registry.delete(name) reset_config_types config_type end
ruby
{ "resource": "" }
q5480
Configurable.ClassMethods.undef_config_type
train
def undef_config_type(name) unless config_types.has_key?(name) raise NameError.new("#{name.inspect} is not a config_type on #{self}") end config_type = config_type_registry[name] config_type_registry[name] = nil reset_config_types config_type end
ruby
{ "resource": "" }
q5481
Configurable.ClassMethods.check_infinite_nest
train
def check_infinite_nest(klass) # :nodoc: raise "infinite nest detected" if klass == self klass.configs.each_value do |config| if config.type.kind_of?(NestType) check_infinite_nest(config.type.configurable.class) end end end
ruby
{ "resource": "" }
q5482
SweetNotifications.LogSubscriber.message
train
def message(event, label, body) @odd = !@odd label_color = @odd ? odd_color : even_color format( ' %s (%.2fms) %s', color(label, label_color, true), event.duration, color(body, nil, !@odd) ) end
ruby
{ "resource": "" }
q5483
DeploYML.RemoteShell.join
train
def join commands = [] @history.each do |command| program = command[0] arguments = command[1..-1].map { |word| shellescape(word.to_s) } commands << [program, *arguments].join(' ') end return commands.join(' && ') end
ruby
{ "resource": "" }
q5484
DeploYML.RemoteShell.ssh_uri
train
def ssh_uri unless @uri.host raise(InvalidConfig,"URI does not have a host: #{@uri}",caller) end new_uri = @uri.host new_uri = "#{@uri.user}@#{new_uri}" if @uri.user return new_uri end
ruby
{ "resource": "" }
q5485
DeploYML.RemoteShell.ssh
train
def ssh(*arguments) options = [] # Add the -p option if an alternate destination port is given if @uri.port options += ['-p', @uri.port.to_s] end # append the SSH URI options << ssh_uri # append the additional arguments arguments.each { |arg| options << arg.to_...
ruby
{ "resource": "" }
q5486
ConfHelpers.ClassMethods.conf_attr
train
def conf_attr(name, opts = {}) @conf_attrs ||= [] @conf_attrs << name default = opts[:default] accumulate = opts[:accumulate] send(:define_singleton_method, name) do |*args| nvar = "@#{name}".intern current = instance_variable_get(nvar) envk = "POLISHER_#{na...
ruby
{ "resource": "" }
q5487
AridCache.Helpers.lookup
train
def lookup(object, key, opts, &block) if !block.nil? define(object, key, opts, &block) elsif key =~ /(.*)_count$/ if AridCache.store.has?(object, $1) method_for_cached(object, $1, :fetch_count, key) elsif object.respond_to?(key) define(object, key, opts, :fetch_co...
ruby
{ "resource": "" }
q5488
AridCache.Helpers.define
train
def define(object, key, opts, fetch_method=:fetch, method_name=nil, &block) # FIXME: Pass default options to store.add # Pass nil in for now until we get the cache_ calls working. # This means that the first time you define a dynamic cache # (by passing in a block), the options you used are not...
ruby
{ "resource": "" }
q5489
AridCache.Helpers.class_name
train
def class_name(object, *modifiers) name = object.is_a?(Class) ? object.name : object.class.name name = 'AnonymousClass' if name.nil? while modifier = modifiers.shift case modifier when :downcase name = name.downcase when :pluralize name = AridCache::Inflecto...
ruby
{ "resource": "" }
q5490
Trust.Permissions.authorized?
train
def authorized? trace 'authorized?', 0, "@user: #{@user.inspect}, @action: #{@action.inspect}, @klass: #{@klass.inspect}, @subject: #{@subject.inspect}, @parent: #{@parent.inspect}" if params_handler = (user && (permission_by_role || permission_by_member_role)) params_handler = params_handler_defaul...
ruby
{ "resource": "" }
q5491
Trust.Permissions.permission_by_member_role
train
def permission_by_member_role m = members_role trace 'authorize_by_member_role?', 0, "#{user.try(:name)}:#{m}" p = member_permissions[m] trace 'authorize_by_role?', 1, "permissions: #{p.inspect}" p && authorization(p) end
ruby
{ "resource": "" }
q5492
Polisher.GemState.state
train
def state(args = {}) return :available if koji_state(args) == :available state = distgit_state(args) return :needs_repo if state == :missing_repo return :needs_branch if state == :missing_branch return :needs_spec if state == :missing_spec return :needs_build if state == :avail...
ruby
{ "resource": "" }
q5493
Verku.SourceList.entries
train
def entries Dir.entries(source).sort.each_with_object([]) do |entry, buffer| buffer << source.join(entry) if valid_entry?(entry) end end
ruby
{ "resource": "" }
q5494
Verku.SourceList.valid_directory?
train
def valid_directory?(entry) File.directory?(source.join(entry)) && !IGNORE_DIR.include?(File.basename(entry)) end
ruby
{ "resource": "" }
q5495
Verku.SourceList.valid_file?
train
def valid_file?(entry) ext = File.extname(entry).gsub(/\./, "").downcase File.file?(source.join(entry)) && EXTENSIONS.include?(ext) && entry !~ IGNORE_FILES end
ruby
{ "resource": "" }
q5496
HungryForm.Form.validate
train
def validate is_valid = true pages.each do |page| # Loop through pages to get all errors is_valid = false if page.invalid? end is_valid end
ruby
{ "resource": "" }
q5497
HungryForm.Form.values
train
def values active_elements = elements.select do |_, el| el.is_a? Elements::Base::ActiveElement end active_elements.each_with_object({}) do |(name, el), o| o[name.to_sym] = el.value end end
ruby
{ "resource": "" }
q5498
ConfigCurator.CLI.install
train
def install(manifest = 'manifest.yml') unless File.exist? manifest logger.fatal { "Manifest file '#{manifest}' does not exist." } return false end collection.load_manifest manifest result = options[:dryrun] ? collection.install? : collection.install msg = install_message(...
ruby
{ "resource": "" }
q5499
Attached.ClassMethods.number_to_size
train
def number_to_size(number, options = {}) return if number == 0.0 / 1.0 return if number == 1.0 / 0.0 singular = options[:singular] || 1 base = options[:base] || 1024 units = options[:units] || ["byte", "kilobyte", "megabyte", "gigabyte", "terabyte", "petabyte"] expone...
ruby
{ "resource": "" }