_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q26200
NewRelicManagement.Client.get_server_name
validation
def get_server_name(server, exact = true) ret = nr_api.get(url('servers'), 'filter[name]' => server).body return ret['servers'] unless exact ret['servers'].find { |x| x['name'].casecmp(server).zero? } rescue NoMethodError nil end
ruby
{ "resource": "" }
q26201
NewRelicManagement.Client.get_servers_labeled
validation
def get_servers_labeled(labels) label_query = Array(labels).reject { |x| !x.include?(':') }.join(';') return [] unless label_query nr_api.get(url('servers'), 'filter[labels]' => label_query).body end
ruby
{ "resource": "" }
q26202
Isimud.EventObserver.observe_events
validation
def observe_events(client) return unless enable_listener? queue = create_queue(client) client.subscribe(queue) do |message| event = Event.parse(message) handle_event(event) end end
ruby
{ "resource": "" }
q26203
Isimud.BunnyClient.bind
validation
def bind(queue_name, exchange_name, *routing_keys, &block) queue = create_queue(queue_name, exchange_name, queue_options: {durable: true}, routing_keys: routing_keys) subscribe(queue, &block) if block_given? end
ruby
{ "resource": "" }
q26204
Isimud.BunnyClient.create_queue
validation
def create_queue(queue_name, exchange_name, options = {}) queue_options = options[:queue_options] || {durable: true} routing_keys = options[:routing_keys] || [] log "Isimud::BunnyClient: create_queue #{queue_name}: queue_options=#{queue_options.inspect}" queue = find_queue(queue_name, queue_opt...
ruby
{ "resource": "" }
q26205
Isimud.BunnyClient.subscribe
validation
def subscribe(queue, options = {}, &block) queue.subscribe(options.merge(manual_ack: true)) do |delivery_info, properties, payload| current_channel = delivery_info.channel begin log "Isimud: queue #{queue.name} received #{properties[:message_id]} routing_key: #{delivery_info.routing_key}...
ruby
{ "resource": "" }
q26206
Isimud.BunnyClient.channel
validation
def channel if (channel = Thread.current[CHANNEL_KEY]).try(:open?) channel else new_channel = connection.channel new_channel.confirm_select new_channel.prefetch(Isimud.prefetch_count) if Isimud.prefetch_count Thread.current[CHANNEL_KEY] = new_channel end end
ruby
{ "resource": "" }
q26207
Isimud.BunnyClient.publish
validation
def publish(exchange, routing_key, payload, options = {}) log "Isimud::BunnyClient#publish: exchange=#{exchange} routing_key=#{routing_key}", :debug channel.topic(exchange, durable: true).publish(payload, options.merge(routing_key: routing_key, persistent: true)) end
ruby
{ "resource": "" }
q26208
MrPoole.Commands.post
validation
def post(opts) opts = @helper.ensure_open_struct(opts) date = @helper.get_date_stamp # still want to escape any garbage in the slug slug = if opts.slug.nil? || opts.slug.empty? opts.title else opts.slug end slug = @helper.get_slug_fo...
ruby
{ "resource": "" }
q26209
MrPoole.Commands.draft
validation
def draft(opts) opts = @helper.ensure_open_struct(opts) # the drafts folder might not exist yet...create it just in case FileUtils.mkdir_p(DRAFTS_FOLDER) slug = if opts.slug.nil? || opts.slug.empty? opts.title else opts.slug end slu...
ruby
{ "resource": "" }
q26210
MrPoole.Commands.publish
validation
def publish(draftpath, opts={}) opts = @helper.ensure_open_struct(opts) tail = File.basename(draftpath) begin infile = File.open(draftpath, "r") rescue Errno::ENOENT @helper.bad_path(draftpath) end date = @helper.get_date_stamp time = @helper.get_time_stamp ...
ruby
{ "resource": "" }
q26211
Luck.ANSIDriver.terminal_size
validation
def terminal_size rows, cols = 25, 80 buf = [0, 0, 0, 0].pack("SSSS") if $stdout.ioctl(TIOCGWINSZ, buf) >= 0 then rows, cols, row_pixels, col_pixels = buf.unpack("SSSS") end return [rows, cols] end
ruby
{ "resource": "" }
q26212
Luck.ANSIDriver.prepare_modes
validation
def prepare_modes buf = [0, 0, 0, 0, 0, 0, ''].pack("IIIICCA*") $stdout.ioctl(TCGETS, buf) @old_modes = buf.unpack("IIIICCA*") new_modes = @old_modes.clone new_modes[3] &= ~ECHO # echo off new_modes[3] &= ~ICANON # one char @ a time $stdout.ioctl(TCSETS, new_modes.pack("IIIICCA*")) print...
ruby
{ "resource": "" }
q26213
CanCanCan.Masquerade.extract_subjects
validation
def extract_subjects(subject) return extract_subjects(subject.to_permission_instance) if subject.respond_to? :to_permission_instance return subject[:any] if subject.is_a? Hash and subject.key? :any [subject] end
ruby
{ "resource": "" }
q26214
NewRelicManagement.Controller.daemon
validation
def daemon # rubocop: disable AbcSize, MethodLength # => Windows Workaround (https://github.com/bdwyertech/newrelic-management/issues/1) ENV['TZ'] = 'UTC' if OS.windows? && !ENV['TZ'] scheduler = Rufus::Scheduler.new Notifier.msg('Daemonizing Process') # => Alerts Management alerts...
ruby
{ "resource": "" }
q26215
NewRelicManagement.Controller.run
validation
def run daemon if Config.daemonize # => Manage Alerts Manager.manage_alerts # => Manage Manager.remove_nonreporting_servers(Config.cleanup_age) if Config.cleanup end
ruby
{ "resource": "" }
q26216
MrPoole.Helper.ensure_jekyll_dir
validation
def ensure_jekyll_dir @orig_dir = Dir.pwd start_path = Pathname.new(@orig_dir) ok = File.exists?('./_posts') new_path = nil # if it doesn't exist, check for a custom source dir in _config.yml if !ok check_custom_src_dir! ok = File.exists?('./_posts') new_pat...
ruby
{ "resource": "" }
q26217
MrPoole.Helper.get_layout
validation
def get_layout(layout_path) if layout_path.nil? contents = "---\n" contents << "title:\n" contents << "layout: post\n" contents << "date:\n" contents << "---\n" ext = nil else begin contents = File.open(layout_path, "r").read() ex...
ruby
{ "resource": "" }
q26218
MrPoole.Helper.gen_usage
validation
def gen_usage puts 'Usage:' puts ' poole [ACTION] [ARG]' puts '' puts 'Actions:' puts ' draft Create a new draft in _drafts with title SLUG' puts ' post Create a new timestamped post in _posts with title SLUG' puts ' publish Publish the draft with SLUG, timest...
ruby
{ "resource": "" }
q26219
NewRelicManagement.Notifier.msg
validation
def msg(message, subtitle = message, title = 'NewRelic Management') # => Stdout Messages terminal_notification(message, subtitle) return if Config.silent # => Pretty GUI Messages osx_notification(message, subtitle, title) if OS.x? end
ruby
{ "resource": "" }
q26220
NewRelicManagement.Notifier.osx_notification
validation
def osx_notification(message, subtitle, title) TerminalNotifier.notify(message, title: title, subtitle: subtitle) end
ruby
{ "resource": "" }
q26221
SFST.RegularTransducer.analyze
validation
def analyze(string, options = {}) x = [] @fst._analyze(string) do |a| if options[:symbol_sequence] x << a.map { |s| s.match(/^<(.*)>$/) ? $1.to_sym : s } else x << a.join end end x end
ruby
{ "resource": "" }
q26222
SFST.RegularTransducer.generate
validation
def generate(string) x = [] @fst._generate(string) { |a| x << a.join } x end
ruby
{ "resource": "" }
q26223
NewRelicManagement.CLI.configure
validation
def configure(argv = ARGV) # => Parse CLI Configuration cli = Options.new cli.parse_options(argv) # => Parse JSON Config File (If Specified and Exists) json_config = Util.parse_json(cli.config[:config_file] || Config.config_file) # => Merge Configuration (CLI Wins) config = [...
ruby
{ "resource": "" }
q26224
Spectro.Compiler.missing_specs_from_file
validation
def missing_specs_from_file(path) Spectro::Spec::Parser.parse(path).select do |spec| index_spec = Spectro::Database.index[path] && Spectro::Database.index[path][spec.signature.name] index_spec.nil? || index_spec['spec_md5'] != spec.md5 end end
ruby
{ "resource": "" }
q26225
NewRelicManagement.Manager.remove_nonreporting_servers
validation
def remove_nonreporting_servers(keeptime = nil) list_nonreporting_servers.each do |server| next if keeptime && Time.parse(server[:last_reported_at]) >= Time.now - ChronicDuration.parse(keeptime) Notifier.msg(server[:name], 'Removing Stale, Non-Reporting Server') Client.delete_server(server...
ruby
{ "resource": "" }
q26226
NewRelicManagement.Manager.find_excluded
validation
def find_excluded(excluded) result = [] Array(excluded).each do |exclude| if exclude.include?(':') find_labeled(exclude).each { |x| result << x } next end res = Client.get_server(exclude) result << res['id'] if res end result end
ruby
{ "resource": "" }
q26227
TwilioContactable.Contactable.send_sms_confirmation!
validation
def send_sms_confirmation! return false if _TC_sms_blocked return true if sms_confirmed? return false if _TC_phone_number.blank? format_phone_number confirmation_code = TwilioContactable.confirmation_code(self, :sms) # Use this class' confirmation_message method if it # exis...
ruby
{ "resource": "" }
q26228
TwilioContactable.Contactable.send_voice_confirmation!
validation
def send_voice_confirmation! return false if _TC_voice_blocked return true if voice_confirmed? return false if _TC_phone_number.blank? format_phone_number confirmation_code = TwilioContactable.confirmation_code(self, :voice) response = TwilioContactable::Gateway.initiate_voice_cal...
ruby
{ "resource": "" }
q26229
TerminalHelpers.Validations.validate
validation
def validate(value, format, raise_error=false) unless FORMATS.key?(format) raise FormatError, "Invalid data format: #{format}" end result = value =~ FORMATS[format] ? true : false if raise_error && !result raise ValidationError, "Invalid value \"#{value}\" for #{format}" en...
ruby
{ "resource": "" }
q26230
XFTP.Client.call
validation
def call(url, settings, &block) uri = URI.parse(url) klass = adapter_class(uri.scheme) session = klass.new(uri, settings.deep_dup) session.start(&block) end
ruby
{ "resource": "" }
q26231
MiamiDadeGeo.GeoAttributeClient.all_fields
validation
def all_fields(table, field_name, value) body = savon. call(:get_all_fields_records_given_a_field_name_and_value, message: { 'strFeatureClassOrTableName' => table, 'strFieldNameToSearchOn' => field_name, 'strValueOfFieldToS...
ruby
{ "resource": "" }
q26232
Validation.Adjustment.WHEN
validation
def WHEN(condition, adjuster) unless Validation.conditionable? condition raise TypeError, 'wrong object for condition' end unless Validation.adjustable? adjuster raise TypeError, 'wrong object for adjuster' end ->v{_valid?(condition, v) ? adjuster.call(v) : v} end
ruby
{ "resource": "" }
q26233
Validation.Adjustment.INJECT
validation
def INJECT(adjuster1, adjuster2, *adjusters) adjusters = [adjuster1, adjuster2, *adjusters] unless adjusters.all?{|f|adjustable? f} raise TypeError, 'wrong object for adjuster' end ->v{ adjusters.reduce(v){|ret, adjuster|adjuster.call ret} } end
ruby
{ "resource": "" }
q26234
Validation.Adjustment.PARSE
validation
def PARSE(parser) if !::Integer.equal?(parser) and !parser.respond_to?(:parse) raise TypeError, 'wrong object for parser' end ->v{ if ::Integer.equal? parser ::Kernel.Integer v else parser.parse( case v when String v ...
ruby
{ "resource": "" }
q26235
RFormSpec.Window.get_class
validation
def get_class(name) @class_list = get_class_list @class_list.select {|x| x.include?(name)}.collect{|y| y.strip} end
ruby
{ "resource": "" }
q26236
Megam.Scmmanager.connection
validation
def connection @options[:path] =API_REST + @options[:path] @options[:headers] = HEADERS.merge({ 'X-Megam-Date' => Time.now.strftime("%Y-%m-%d %H:%M") }).merge(@options[:headers]) text.info("HTTP Request Data:") text.msg("> HTTP #{@options[:scheme]}://#{@options[:host]}") @o...
ruby
{ "resource": "" }
q26237
QuackConcurrency.SafeSleeper.wake_deadline
validation
def wake_deadline(start_time, timeout) timeout = process_timeout(timeout) deadline = start_time + timeout if timeout end
ruby
{ "resource": "" }
q26238
MirExtensions.HelperExtensions.crud_links
validation
def crud_links(model, instance_name, actions, args={}) _html = "" _options = args.keys.empty? ? '' : ", #{args.map{|k,v| ":#{k} => #{v}"}}" if use_crud_icons if actions.include?(:show) _html << eval("link_to image_tag('/images/icons/view.png', :class => 'crud_icon'), model, :title...
ruby
{ "resource": "" }
q26239
MirExtensions.HelperExtensions.obfuscated_link_to
validation
def obfuscated_link_to(path, image, label, args={}) _html = %{<form action="#{path}" method="get" class="obfuscated_link">} _html << %{ <fieldset><input alt="#{label}" src="#{image}" type="image" /></fieldset>} args.each{ |k,v| _html << %{ <div><input id="#{k.to_s}" name="#{k}" type="hidden" value="#...
ruby
{ "resource": "" }
q26240
MirExtensions.HelperExtensions.required_field_helper
validation
def required_field_helper( model, element, html ) if model && ! model.errors.empty? && element.is_required return content_tag( :div, html, :class => 'fieldWithErrors' ) else return html end end
ruby
{ "resource": "" }
q26241
MirExtensions.HelperExtensions.select_tag_for_filter
validation
def select_tag_for_filter(model, nvpairs, params) return unless model && nvpairs && ! nvpairs.empty? options = { :query => params[:query] } _url = url_for(eval("#{model}_url(options)")) _html = %{<label for="show">Show:</label><br />} _html << %{<select name="show" id="show" onchange="wind...
ruby
{ "resource": "" }
q26242
MirExtensions.HelperExtensions.sort_link
validation
def sort_link(model, field, params, html_options={}) if (field.to_sym == params[:by] || field == params[:by]) && params[:dir] == "ASC" classname = "arrow-asc" dir = "DESC" elsif (field.to_sym == params[:by] || field == params[:by]) classname = "arrow-desc" dir = "ASC" e...
ruby
{ "resource": "" }
q26243
MirExtensions.HelperExtensions.tag_for_label_with_inline_help
validation
def tag_for_label_with_inline_help( label_text, field_id, help_text ) _html = "" _html << %{<label for="#{field_id}">#{label_text}} _html << %{<img src="/images/icons/help_icon.png" onclick="$('#{field_id}_help').toggle();" class='inline_icon' />} _html << %{</label><br />} _html << %{<div...
ruby
{ "resource": "" }
q26244
RFormSpec.Driver.key_press
validation
def key_press(keys) dump_caller_stack if keys =~ /^Ctrl\+([A-Z])$/ filtered_keys = "^+#{$1}" elsif keys =~ /^Ctrl\+Shift\+([A-Z])$/ filtered_keys = "^+#{$1.downcase}" elsif keys =~ /^Alt+([A-Z])$/ filtered_keys = "!+#{$1}" elsif keys =~ /^Alt\+Shift\+([a-z])$...
ruby
{ "resource": "" }
q26245
RFormSpec.Driver.open_file_dialog
validation
def open_file_dialog(title, filepath, text="") wait_and_focus_window(title) dialog = RFormSpec::OpenFileDialog.new(title, text) dialog.enter_filepath(filepath) sleep 1 dialog.click_open end
ruby
{ "resource": "" }
q26246
ByebugCleaner.ArgumentParser.parse
validation
def parse(args) # The options specified on the command line will be collected in # *options*. @options = Options.new opt_parser = OptionParser.new do |parser| @options.define_options(parser) end opt_parser.parse!(args) @options end
ruby
{ "resource": "" }
q26247
Rgc.GitAttributes.add
validation
def add(path) str = "#{path} filter=rgc diff=rgc" if content.include?(str) abort "`#{str}\n` is already included in #{@location}." end File.open(@location, 'a') do |f| f.write("#{str}\n") end rescue Errno::ENOENT abort "File #{@location} does not exists." res...
ruby
{ "resource": "" }
q26248
ActiveMigration.Base.run
validation
def run logger.info("#{self.class.to_s} is starting.") count_options = self.class.legacy_find_options.dup count_options.delete(:order) count_options.delete(:group) count_options.delete(:limit) count_options.delete(:offset) @num_of_records = self.class.legacy_model.count(count_o...
ruby
{ "resource": "" }
q26249
Simplec.Page.parents
validation
def parents page, parents = self, Array.new while page.parent page = page.parent parents << page end parents end
ruby
{ "resource": "" }
q26250
Simplec.Page.extract_search_text
validation
def extract_search_text(*attributes) Array(attributes).map { |meth| Nokogiri::HTML(self.send(meth)).xpath("//text()"). map {|node| text = node.text; text.try(:strip!); text}.join(" ") }.reject(&:blank?).join("\n") end
ruby
{ "resource": "" }
q26251
Simplec.Page.set_query_attributes!
validation
def set_query_attributes! attr_names = self.class.search_query_attributes.map(&:to_s) self.query = attr_names.inject({}) { |memo, attr| memo[attr] = self.send(attr) memo } end
ruby
{ "resource": "" }
q26252
Bixby.Agent.manager_ws_uri
validation
def manager_ws_uri # convert manager uri to websocket uri = URI.parse(manager_uri) uri.scheme = (uri.scheme == "https" ? "wss" : "ws") uri.path = "/wsapi" return uri.to_s end
ruby
{ "resource": "" }
q26253
ForemanHook.HostRename.parse_config
validation
def parse_config(conffile = nil) conffile ||= Dir.glob([ "/etc/foreman_hooks-host_rename/settings.yaml", "#{confdir}/settings.yaml"])[0] raise "Could not locate the configuration file" if conffile.nil? # Parse the configuration file config = { hook_user: 'foreman', ...
ruby
{ "resource": "" }
q26254
ForemanHook.HostRename.check_script
validation
def check_script(path) binary=path.split(' ')[0] raise "#{path} does not exist" unless File.exist? binary raise "#{path} is not executable" unless File.executable? binary path end
ruby
{ "resource": "" }
q26255
ForemanHook.HostRename.sync_host_table
validation
def sync_host_table uri = foreman_uri('/hosts?per_page=9999999') debug "Loading hosts from #{uri}" json = RestClient.get uri debug "Got JSON: #{json}" JSON.parse(json)['results'].each do |rec| @db.execute "insert into host (id,name) values ( ?, ? )", rec['id'], r...
ruby
{ "resource": "" }
q26256
ForemanHook.HostRename.initialize_database
validation
def initialize_database @db = SQLite3::Database.new @database_path File.chmod 0600, @database_path begin @db.execute 'drop table if exists host;' @db.execute <<-SQL create table host ( id INT, name varchar(254) ); SQL ...
ruby
{ "resource": "" }
q26257
ForemanHook.HostRename.execute_hook_action
validation
def execute_hook_action @rename = false name = @rec['host']['name'] id = @rec['host']['id'] case @action when 'create' sql = "insert into host (id, name) values (?, ?)" params = [id, name] when 'update' # Check if we are renaming the host @old_nam...
ruby
{ "resource": "" }
q26258
RedisAssist.Base.read_list
validation
def read_list(name) opts = self.class.persisted_attrs[name] if !lists[name] && opts[:default] opts[:default] else send("#{name}=", lists[name].value) if lists[name].is_a?(Redis::Future) lists[name] end end
ruby
{ "resource": "" }
q26259
RedisAssist.Base.read_hash
validation
def read_hash(name) opts = self.class.persisted_attrs[name] if !hashes[name] && opts[:default] opts[:default] else self.send("#{name}=", hashes[name].value) if hashes[name].is_a?(Redis::Future) hashes[name] end end
ruby
{ "resource": "" }
q26260
RedisAssist.Base.write_attribute
validation
def write_attribute(name, val) if attributes.is_a?(Redis::Future) value = attributes.value self.attributes = value ? Hash[*self.class.fields.keys.zip(value).flatten] : {} end attributes[name] = self.class.transform(:to, name, val) end
ruby
{ "resource": "" }
q26261
RedisAssist.Base.write_list
validation
def write_list(name, val) raise "RedisAssist: tried to store a #{val.class.name} as Array" unless val.is_a?(Array) lists[name] = val end
ruby
{ "resource": "" }
q26262
RedisAssist.Base.write_hash
validation
def write_hash(name, val) raise "RedisAssist: tried to store a #{val.class.name} as Hash" unless val.is_a?(Hash) hashes[name] = val end
ruby
{ "resource": "" }
q26263
RedisAssist.Base.update_columns
validation
def update_columns(attrs) redis.multi do attrs.each do |attr, value| if self.class.fields.has_key?(attr) write_attribute(attr, value) redis.hset(key_for(:attributes), attr, self.class.transform(:to, attr, value)) unless new_record? end if self.class...
ruby
{ "resource": "" }
q26264
Minican.ControllerAdditions.filter_authorized!
validation
def filter_authorized!(method, objects, user = current_user) object_array = Array(objects) object_array.select do |object| policy = policy_for(object) policy.can?(method, user) end end
ruby
{ "resource": "" }
q26265
Minican.ControllerAdditions.can?
validation
def can?(method, object, user = current_user) policy = policy_for(object) policy.can?(method, user) end
ruby
{ "resource": "" }
q26266
DogeCoin.Client.nethash
validation
def nethash interval = 500, start = 0, stop = false suffixe = stop ? "/#{stop}" : '' JSON.parse(call_blockchain_api("nethash/#{interval}/#{start}#{suffixe}?format=json")) end
ruby
{ "resource": "" }
q26267
RedisAssist.Finders.last
validation
def last(limit=1, offset=0) from = offset to = from + limit - 1 members = redis.zrange(index_key_for(:id), (to * -1) + -1, (from * -1) + -1).reverse find(limit > 1 ? members : members.first) end
ruby
{ "resource": "" }
q26268
RedisAssist.Finders.find
validation
def find(ids, opts={}) ids.is_a?(Array) ? find_by_ids(ids, opts) : find_by_id(ids, opts) end
ruby
{ "resource": "" }
q26269
RedisAssist.Finders.find_in_batches
validation
def find_in_batches(options={}) start = options[:start] || 0 marker = start batch_size = options[:batch_size] || 500 record_ids = redis.zrange(index_key_for(:id), marker, marker + batch_size - 1) while record_ids.length > 0 records_count = record_ids.length ...
ruby
{ "resource": "" }
q26270
ActiveMigration.KeyMapper.load_keymap
validation
def load_keymap(map) #:nodoc: @maps ||= Hash.new if @maps[map].nil? && File.file?(File.join(self.storage_path, map.to_s + "_map.yml")) @maps[map] = YAML.load(File.open(File.join(self.storage_path, map.to_s + "_map.yml"))) logger.debug("#{self.class.to_s} lazy loaded #{map} successfully.") ...
ruby
{ "resource": "" }
q26271
ActiveMigration.KeyMapper.mapped_key
validation
def mapped_key(map, key) load_keymap(map.to_s) @maps[map.to_s][handle_composite(key)] end
ruby
{ "resource": "" }
q26272
Parallel.ProcessorCount.processor_count
validation
def processor_count @processor_count ||= begin os_name = RbConfig::CONFIG["target_os"] if os_name =~ /mingw|mswin/ require 'win32ole' result = WIN32OLE.connect("winmgmts://").ExecQuery( "select NumberOfLogicalProcessors from Win32_Processor") result.to_enu...
ruby
{ "resource": "" }
q26273
Parallel.ProcessorCount.physical_processor_count
validation
def physical_processor_count @physical_processor_count ||= begin ppc = case RbConfig::CONFIG["target_os"] when /darwin1/ IO.popen("/usr/sbin/sysctl -n hw.physicalcpu").read.to_i when /linux/ cores = {} # unique physical ID / core ID combinations phy = 0 ...
ruby
{ "resource": "" }
q26274
RubyReportable.Report.valid?
validation
def valid?(options = {}) options = {:input => {}}.merge(options) errors = [] # initial sandbox sandbox = _source(options) # add in inputs sandbox[:inputs] = options[:input] validity = @filters.map do |filter_name, filter| # find input for given filter sandbo...
ruby
{ "resource": "" }
q26275
ElapsedWatch.EventCollection.reload
validation
def reload() self.clear self.concat File.read(event_file).split(/\r?\n/).map{|e| Event.new(e)} end
ruby
{ "resource": "" }
q26276
Mongoid.Followable.followee_of?
validation
def followee_of?(model) 0 < self.followers.by_model(model).limit(1).count * model.followees.by_model(self).limit(1).count end
ruby
{ "resource": "" }
q26277
Mongoid.Followable.ever_followed
validation
def ever_followed follow = [] self.followed_history.each do |h| follow << h.split('_')[0].constantize.find(h.split('_')[1]) end follow end
ruby
{ "resource": "" }
q26278
QuackConcurrency.ConditionVariable.wait
validation
def wait(mutex, timeout = nil) validate_mutex(mutex) validate_timeout(timeout) waitable = waitable_for_current_thread @mutex.synchronize do @waitables.push(waitable) @waitables_to_resume.push(waitable) end waitable.wait(mutex, timeout) self end
ruby
{ "resource": "" }
q26279
QuackConcurrency.ConditionVariable.validate_timeout
validation
def validate_timeout(timeout) unless timeout == nil raise TypeError, "'timeout' must be nil or a Numeric" unless timeout.is_a?(Numeric) raise ArgumentError, "'timeout' must not be negative" if timeout.negative? end end
ruby
{ "resource": "" }
q26280
Deas::Erubis.TemplateEngine.render
validation
def render(template_name, view_handler, locals, &content) self.erb_source.render(template_name, render_locals(view_handler, locals), &content) end
ruby
{ "resource": "" }
q26281
SpreadsheetAgent.Agent.run_entry
validation
def run_entry entry = get_entry() output = ''; @keys.keys.select { |k| @config['key_fields'][k] && @keys[k] }.each do |key| output += [ key, @keys[key] ].join(' ') + " " end unless entry $stderr.puts "#{ output } is not supported on #{ @page_name }" if @debug retur...
ruby
{ "resource": "" }
q26282
KevinsPropietaryBrain.Brain.pick
validation
def pick(number, *cards) ordered = cards.flatten.map do |card| i = card_preference.map { |preference| card.type == preference }.index(true) {card: card, index: i} end ordered.sort_by { |h| h[:index] || 99 }.first(number).map {|h| h[:card] } end
ruby
{ "resource": "" }
q26283
KevinsPropietaryBrain.Brain.discard
validation
def discard ordered = player.hand.map do |card| i = card_preference.map { |preference| card.type == preference }.index(true) {card: card, index: i} end ordered.sort_by { |h| h[:index] || 99 }.last.try(:fetch, :card) end
ruby
{ "resource": "" }
q26284
KevinsPropietaryBrain.Brain.play
validation
def play bangs_played = 0 while !player.hand.find_all(&:draws_cards?).empty? player.hand.find_all(&:draws_cards?).each {|card| player.play_card(card)} end play_guns player.hand.each do |card| target = find_target(card) next if skippable?(card, target, bangs_played) ...
ruby
{ "resource": "" }
q26285
QuackConcurrency.Mutex.sleep
validation
def sleep(timeout = nil) validate_timeout(timeout) unlock do if timeout == nil || timeout == Float::INFINITY elapsed_time = (timer { Thread.stop }).round else elapsed_time = Kernel.sleep(timeout) end end end
ruby
{ "resource": "" }
q26286
QuackConcurrency.Mutex.temporarily_release
validation
def temporarily_release(&block) raise ArgumentError, 'no block given' unless block_given? unlock begin return_value = yield lock rescue Exception lock_immediately raise end return_value end
ruby
{ "resource": "" }
q26287
QuackConcurrency.Mutex.timer
validation
def timer(&block) start_time = Time.now yield(start_time) time_elapsed = Time.now - start_time end
ruby
{ "resource": "" }
q26288
CapybaraRails.Selenium.wait
validation
def wait continue = false trap "SIGINT" do puts "Continuing..." continue = true end puts "Waiting. Press ^C to continue test..." wait_until(3600) { continue } trap "SIGINT", "DEFAULT" end
ruby
{ "resource": "" }
q26289
Quickl.RubyTools.optional_args_block_call
validation
def optional_args_block_call(block, args) if RUBY_VERSION >= "1.9.0" if block.arity == 0 block.call else block.call(*args) end else block.call(*args) end end
ruby
{ "resource": "" }
q26290
Quickl.RubyTools.extract_file_rdoc
validation
def extract_file_rdoc(file, from = nil, reverse = false) lines = File.readlines(file) if from.nil? and reverse lines = lines.reverse elsif !reverse lines = lines[(from || 0)..-1] else lines = lines[0...(from || -1)].reverse end doc, started = [], false ...
ruby
{ "resource": "" }
q26291
ToughGuy.Query.select
validation
def select(fields) if (fields == []) || (fields.nil?) fields = [:_id] end clone.tap {|q| q.options[:fields] = fields} end
ruby
{ "resource": "" }
q26292
ToughGuy.Query.set_pagination_info
validation
def set_pagination_info(page_no, page_size, record_count) @current_page = page_no @per_page = page_size @total_count = record_count @total_pages = (record_count / page_size.to_f).ceil extend PaginationMethods self end
ruby
{ "resource": "" }
q26293
EchoUploads.Model.echo_uploads_data=
validation
def echo_uploads_data=(data) parsed = JSON.parse Base64.decode64(data) # parsed will look like: # { 'attr1' => [ {'id' => 1, 'key' => 'abc...'} ] } unless parsed.is_a? Hash raise ArgumentError, "Invalid JSON structure in: #{parsed.inspect}" end parsed.each do |attr, attr_data...
ruby
{ "resource": "" }
q26294
Mongoid.Follower.follower_of?
validation
def follower_of?(model) 0 < self.followees.by_model(model).limit(1).count * model.followers.by_model(self).limit(1).count end
ruby
{ "resource": "" }
q26295
Mongoid.Follower.follow
validation
def follow(*models) models.each do |model| unless model == self or self.follower_of?(model) or model.followee_of?(self) or self.cannot_follow.include?(model.class.name) or model.cannot_followed.include?(self.class.name) model.followers.create!(:f_type => self.class.name, :f_id => self.id.to_s) ...
ruby
{ "resource": "" }
q26296
Mongoid.Follower.unfollow
validation
def unfollow(*models) models.each do |model| unless model == self or !self.follower_of?(model) or !model.followee_of?(self) or self.cannot_follow.include?(model.class.name) or model.cannot_followed.include?(self.class.name) model.followers.by_model(self).first.destroy self.followees.by...
ruby
{ "resource": "" }
q26297
Mongoid.Follower.ever_follow
validation
def ever_follow follow = [] self.follow_history.each do |h| follow << h.split('_')[0].constantize.find(h.split('_')[1]) end follow end
ruby
{ "resource": "" }
q26298
QuackConcurrency.Queue.pop
validation
def pop(non_block = false) @pop_mutex.lock do @mutex.synchronize do if empty? return if closed? raise ThreadError if non_block @mutex.unlock @waiter.wait @mutex.lock return if closed? end @items.shift ...
ruby
{ "resource": "" }
q26299
Grenache.Base.lookup
validation
def lookup(key, opts={}, &block) unless addr = cache.has?(key) addr = link.send('lookup', key, opts, &block) cache.save(key, addr) end yield addr if block_given? addr end
ruby
{ "resource": "" }