_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_options) bind_routing_keys(queue, exchange_name, routing_keys) if routing_keys.any? queue end
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}", :debug Thread.current['isimud_queue_name'] = queue.name Thread.current['isimud_delivery_info'] = delivery_info Thread.current['isimud_properties'] = properties block.call(payload) if current_channel.open? log "Isimud: queue #{queue.name} finished with #{properties[:message_id]}, acknowledging", :debug current_channel.ack(delivery_info.delivery_tag) else log "Isimud: queue #{queue.name} unable to acknowledge #{properties[:message_id]}", :warn end rescue => e log("Isimud: queue #{queue.name} error processing #{properties[:message_id]} payload #{payload.inspect}: #{e.class.name} #{e.message}\n #{e.backtrace.join("\n ")}", :warn) retry_status = run_exception_handlers(e) log "Isimud: rejecting #{properties[:message_id]} requeue=#{retry_status}", :warn current_channel.open? && current_channel.reject(delivery_info.delivery_tag, retry_status) end end end
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_for(slug) # put the metadata into the layout header head, ext = @helper.get_layout(opts.layout) head.sub!(/^title:\s*$/, "title: #{opts.title}") head.sub!(/^date:\s*$/, "date: #{date}") ext ||= @ext path = File.join(POSTS_FOLDER, "#{date}-#{slug}.#{ext}") f = File.open(path, "w") f.write(head) f.close @helper.open_in_editor(path) # open file if config key set path # return the path, in case we want to do anything useful end
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 slug = @helper.get_slug_for(slug) # put the metadata into the layout header head, ext = @helper.get_layout(opts.layout) head.sub!(/^title:\s*$/, "title: #{opts.title}") head.sub!(/^date:\s*$/, "date: #{@helper.get_date_stamp}") ext ||= @ext path = File.join(DRAFTS_FOLDER, "#{slug}.#{ext}") f = File.open(path, "w") f.write(head) f.close @helper.open_in_editor(path) # open file if config key set path # return the path, in case we want to do anything useful end
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 outpath = File.join(POSTS_FOLDER, "#{date}-#{tail}") outfile = File.open(outpath, "w") infile.each_line do |line| line.sub!(/^date:.*$/, "date: #{date} #{time}\n") unless opts.keep_timestamp outfile.write(line) end infile.close outfile.close FileUtils.rm(draftpath) unless opts.keep_draft outpath end
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 "\e[2J" # clear screen print "\e[H" # go home print "\e[?47h" # kick xterm into the alt screen print "\e[?1000h" # kindly ask for mouse positions to make up for it self.cursor = false flush end
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_interval = Config.alert_management_interval scheduler.every alerts_interval, overlap: false do Manager.manage_alerts end # => Cleanup Stale Servers if Config.cleanup cleanup_interval = Config.cleanup_interval cleanup_age = Config.cleanup_age scheduler.every cleanup_interval, overlap: false do Manager.remove_nonreporting_servers(cleanup_age) end end # => Join the Current Thread to the Scheduler Thread scheduler.join end
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_path = Pathname.new(Dir.pwd) end if ok return (new_path ? new_path.relative_path_from(start_path) : '.') else puts 'ERROR: Cannot locate _posts directory. Double check to make sure' puts ' that you are in a jekyll directory.' exit end end
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() ext = layout_path.match(/\.(.*?)$/)[1] rescue Errno::ENOENT bad_path(layout_path) end end return contents, ext end
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, timestamping appropriately' puts ' unpublish Move a post to _drafts, untimestamping appropriately' exit end
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 = [json_config, cli.config].compact.reduce(:merge) # => Apply Configuration config.each { |k, v| Config.send("#{k}=", v) } end
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[:id]) end end
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 # exists, otherwise use the generic message message = (self.class.respond_to?(:confirmation_message) ? self.class : TwilioContactable).confirmation_message(confirmation_code) if message.to_s.size > 160 raise ArgumentError, "SMS Confirmation Message is too long. Limit it to 160 characters of unescaped text." end response = TwilioContactable::Gateway.deliver_sms(message, _TC_formatted_phone_number) if response.success? update_twilio_contactable_sms_confirmation confirmation_code end response end
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_call(self, _TC_formatted_phone_number) if response.success? update_twilio_contactable_voice_confirmation confirmation_code end response end
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}" end result end
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, 'strValueOfFieldToSearchOn' => value }). body resp = body[:get_all_fields_records_given_a_field_name_and_value_response] rslt = resp[:get_all_fields_records_given_a_field_name_and_value_result] polys = rslt[:diffgram][:document_element][:municipality_poly] poly = if polys.is_a? Array polys.first elsif polys.is_a? Hash polys else fail "Unexpected polys #{polys.class.name}, wanted Array or Hash" end end
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 when ->_{v.respond_to? :to_str} v.to_str when ->_{v.respond_to? :read} v.read else raise TypeError, 'wrong object for parsing source' end ) end } end
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]}") @options.each do |key, value| text.msg("> #{key}: #{value}") end text.info("End HTTP Request Data.") http = Net::HTTP.new(@options[:host], @options[:port]) http end
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 => 'View'#{_options}") end if actions.include?(:edit) _html << eval("link_to image_tag('/images/icons/edit.png', :class => 'crud_icon'), edit_#{instance_name}_path(model), :title => 'Edit'#{_options}") end if actions.include?(:delete) _html << eval("link_to image_tag('/images/icons/delete.png', :class => 'crud_icon'), model, :confirm => 'Are you sure? This action cannot be undone.', :method => :delete, :title => 'Delete'#{_options}") end else if actions.include?(:show) _html << eval("link_to 'View', model, :title => 'View', :class => 'crud_link'#{_options}") end if actions.include?(:edit) _html << eval("link_to 'Edit', edit_#{instance_name}_path(model), :title => 'Edit', :class => 'crud_link'#{_options}") end if actions.include?(:delete) _html << eval("link_to 'Delete', model, :confirm => 'Are you sure? This action cannot be undone.', :method => :delete, :title => 'Delete', :class => 'crud_link'#{_options}") end end _html end
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="#{v}" /></div>} } _html << %{</form>} _html end
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="window.location='#{_url}' + '?show=' + this.value">} nvpairs.each do |pair| _html << %{<option value="#{pair[:scope]}"} if params[:show] == pair[:scope] || ((params[:show].nil? || params[:show].empty?) && pair[:scope] == "all") _html << %{ selected="selected"} end _html << %{>#{pair[:label]}} _html << %{</option>} end _html << %{</select>} end
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" else dir = "ASC" end options = { :anchor => html_options[:anchor] || nil, :by => field, :dir => dir, :query => params[:query], :show => params[:show] } options[:show] = params[:show] unless params[:show].blank? || params[:show] == 'all' html_options = { :class => "#{classname} #{html_options[:class]}", :style => "color: white; font-weight: #{params[:by] == field ? "bold" : "normal"}; #{html_options[:style]}", :title => "Sort by this field" } field_name = params[:labels] && params[:labels][field] ? params[:labels][field] : field.titleize _link = model.is_a?(Symbol) ? eval("#{model}_url(options)") : "/#{model}?#{options.to_params}" link_to(field_name, _link, html_options) end
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 class="inline_help" id="#{field_id}_help" style="display: none;">} _html << %{<p>#{help_text}</p>} _html << %{</div>} _html end
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])$/ filtered_keys = "!+#{$1.downcase}" else filtered_keys = keys end filtered_keys = keys.gsub("Alt+", "!+").gsub("Ctrl+", "^+") RFormSpec::Keyboard.press(filtered_keys) sleep 0.5 end
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." rescue Errno::EACCES abort "File #{@location} is not accessible for writing." end
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_options) if self.class.legacy_find_options[:limit] && (@num_of_records > self.class.legacy_find_options[:limit]) run_in_batches @num_of_records else run_normal end logger.info("#{self.class.to_s} migrated all #{@num_of_records} records successfully.") end
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', database_path: '/var/tmp/foreman_hooks-host_rename.db', log_path: '/var/tmp/foreman_hooks-host_rename.log', log_level: 'warn', rename_hook_command: '/bin/true', }.merge(symbolize(YAML.load(File.read(conffile)))) config.each do |k,v| instance_variable_set("@#{k}",v) end # Validate the schema document = Kwalify::Yaml.load_file(conffile) schema = Kwalify::Yaml.load_file("#{confdir}/schema.yaml") validator = Kwalify::Validator.new(schema) errors = validator.validate(document) if errors && !errors.empty? puts "WARNING: The following errors were found in #{conffile}:" for e in errors puts "[#{e.path}] #{e.message}" end raise "Errors in the configuration file" end check_script @rename_hook_command end
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'], rec['name'] end end
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 sync_host_table rescue File.unlink @database_path raise end end
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_name = @db.get_first_row('select name from host where id = ?', id) @old_name = @old_name[0] unless @old_name.nil? if @old_name.nil? warn 'received an update for a non-existent host' else @rename = @old_name != name end debug "checking for a rename: old=#{@old_name} new=#{name} rename?=#{@rename}" sql = 'update host set name = ? where id = ?' params = [name, id] when 'destroy' sql = 'delete from host where id = ?' params = [id] else raise ArgumentError, "unsupported action: #{ARGV[0]}" end debug "updating database; id=#{id} name=#{name} sql=#{sql}" stm = @db.prepare sql stm.bind_params *params stm.execute end
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.lists.has_key?(attr) write_list(attr, value) unless new_record? redis.del(key_for(attr)) redis.rpush(key_for(attr), value) unless value.empty? end end if self.class.hashes.has_key?(attr) write_hash(attr, value) unless new_record? hash_as_args = hash_to_redis(value) redis.hmset(key_for(attr), *hash_as_args) end end end end end
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 marker += records_count records = find(record_ids) yield records break if records_count < batch_size record_ids = redis.zrange(index_key_for(:id), marker, marker + batch_size - 1) end end
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.") end end
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_enum.collect(&:NumberOfLogicalProcessors).reduce(:+) elsif File.readable?("/proc/cpuinfo") IO.read("/proc/cpuinfo").scan(/^processor/).size elsif File.executable?("/usr/bin/hwprefs") IO.popen("/usr/bin/hwprefs thread_count").read.to_i elsif File.executable?("/usr/sbin/psrinfo") IO.popen("/usr/sbin/psrinfo").read.scan(/^.*on-*line/).size elsif File.executable?("/usr/sbin/ioscan") IO.popen("/usr/sbin/ioscan -kC processor") do |out| out.read.scan(/^.*processor/).size end elsif File.executable?("/usr/sbin/pmcycles") IO.popen("/usr/sbin/pmcycles -m").read.count("\n") elsif File.executable?("/usr/sbin/lsdev") IO.popen("/usr/sbin/lsdev -Cc processor -S 1").read.count("\n") elsif File.executable?("/usr/sbin/sysconf") and os_name =~ /irix/i IO.popen("/usr/sbin/sysconf NPROC_ONLN").read.to_i elsif File.executable?("/usr/sbin/sysctl") IO.popen("/usr/sbin/sysctl -n hw.ncpu").read.to_i elsif File.executable?("/sbin/sysctl") IO.popen("/sbin/sysctl -n hw.ncpu").read.to_i else $stderr.puts "Unknown platform: " + RbConfig::CONFIG["target_os"] $stderr.puts "Assuming 1 processor." 1 end end end
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 IO.read("/proc/cpuinfo").scan(/^physical id.*|^core id.*/) do |ln| if ln.start_with?("physical") phy = ln[/\d+/] elsif ln.start_with?("core") cid = phy + ":" + ln[/\d+/] cores[cid] = true if not cores[cid] end end cores.count when /mswin|mingw/ require 'win32ole' result_set = WIN32OLE.connect("winmgmts://").ExecQuery( "select NumberOfCores from Win32_Processor") result_set.to_enum.collect(&:NumberOfCores).reduce(:+) else processor_count end # fall back to logical count if physical info is invalid ppc > 0 ? ppc : processor_count end end
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 sandbox[:input] = options[:input][filter[:key]] if options[:input].is_a?(Hash) filter_validity = filter[:valid].nil? || sandbox.instance_eval(&filter[:valid]) if filter_validity == false # Ignore an empty filter unless it's required if !sandbox[:input].to_s.blank? errors << "#{filter_name} is invalid." false else if sandbox[:input].to_s.blank? && !filter[:require].blank? errors << "#{filter_name} is required." false else true end end elsif filter_validity == true if sandbox[:input].to_s.blank? && !filter[:require].blank? errors << "#{filter_name} is required." false else true end elsif !filter_validity.nil? && !filter_validity[:status].nil? && filter_validity[:status] == false # Ignore an empty filter unless it's required or the error is forced. if !sandbox[:input].to_s.blank? || filter_validity[:force_error] == true errors << filter_validity[:errors] false else if sandbox[:input].to_s.blank? && !filter[:require].blank? errors << "#{filter_name} is required." false else true end end end end return {:status => !validity.include?(false), :errors => errors} end
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 return end unless entry['ready'] == "1" $stderr.puts "#{ output } is not ready to run #{ @agent_name }" if @debug return false, entry end if entry['complete'] == "1" $stderr.puts "All goals are completed for #{ output }" if @debug return false, entry end if entry[@agent_name] (status, running_hostname) = entry[@agent_name].split(':') case status when 'r' $stderr.puts " #{ output } is already running #{ @agent_name } on #{ running_hostname }" if @debug return false, entry when "1" $stderr.puts " #{ output } has already run #{ @agent_name }" if @debug return false, entry when 'F' $stderr.puts " #{ output } has already Failed #{ @agent_name }" if @debug return false, entry end end if @prerequisites @prerequisites.each do |prereq_field| unless entry[prereq_field] == "1" $stderr.puts " #{ output } has not finished #{ prereq_field }" if @debug return false, entry end end end # first attempt to set the hostname of the machine as the value of the agent hostname = Socket.gethostname; begin entry.update @agent_name => "r:#{ hostname }" @worksheet.save rescue GoogleDrive::Error # this is a collision, which is to be treated as if it is not runnable $stderr.puts " #{ output } lost #{ @agent_name } on #{hostname}" if @debug return false, entry end sleep 3 begin @worksheet.reload rescue GoogleDrive::Error # this is a collision, which is to be treated as if it is not runnable $stderr.puts " #{ output } lost #{ @agent_name } on #{hostname}" if @debug return false, entry end check = entry[@agent_name] (status, running_hostname) = check.split(':') if hostname == running_hostname return true, entry end $stderr.puts " #{ output } lost #{ @agent_name } on #{hostname}" if @debug return false, entry end
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) bangs_played += 1 if card.type == Card.bang_card player.play_card(card, target, :hand) end end
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 lines.each{|line| if /^\s*[#]/ =~ line doc << line started = true elsif started break end } doc = reverse ? doc.reverse[0..-1] : doc[0..-1] doc = doc.join("\n") doc.gsub(/^\s*[#] ?/, "") end
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| # If the :map option was passed, there may be multiple variants of the uploaded # file. Even if not, attr_data is still a one-element array. unless attr_data.is_a? Array raise ArgumentError, "Invalid JSON structure in: #{parsed.inspect}" end attr_data.each do |variant_data| unless variant_data.is_a? Hash raise ArgumentError, "Invalid JSON structure in: #{parsed.inspect}" end if meta = ::EchoUploads::File.where( id: variant_data['id'], key: variant_data['key'], temporary: true ).first if send("#{attr}_tmp_metadata").nil? send "#{attr}_tmp_metadata=", [] end send("#{attr}_tmp_metadata") << meta end end end end
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) model.followed_history << self.class.name + '_' + self.id.to_s model.save self.followees.create!(:f_type => model.class.name, :f_id => model.id.to_s) self.follow_history << model.class.name + '_' + model.id.to_s self.save end end end
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_model(model).first.destroy end end end
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 end end end
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": "" }