_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q9600
Aker::Authorities.Composite.poll
train
def poll(method, *args) authorities.select { |a| a.respond_to?(method) }.collect { |a| [a.send(method, *args), a] } end
ruby
{ "resource": "" }
q9601
Megaphone.Client.publish!
train
def publish!(topic, subtopic, schema, partition_key, payload) event = Event.new(topic, subtopic, origin, schema, partition_key, payload) raise MegaphoneInvalidEventError.new(event.errors.join(', ')) unless event.valid? unless logger.post(topic, event.to_hash) if transient_error?(logger.last_error) raise MegaphoneMessageDelayWarning.new(logger.last_error.message, event.stream_id) else raise MegaphoneUnavailableError.new(logger.last_error.message, event.stream_id) end end end
ruby
{ "resource": "" }
q9602
Npolar::Api::Client.NpolarApiCommand.run
train
def run @client = JsonApiClient.new(uri) @client.log = log @client.header = header @client.param = parameters if param[:concurrency] @client.concurrency = param[:concurrency].to_i end if param[:slice] @client.slice = param[:slice].to_i end if uri =~ /\w+[:]\w+[@]/ username, password = URI.parse(uri).userinfo.split(":") @client.username = username @client.password = password end if param[:auth] # Force authorization @client.authorization = true end method = param[:method].upcase response = nil case method when "DELETE" response = delete when "GET" response = get when "HEAD" response = head when "PATCH" response = patch when "POST" if data.is_a? Dir raise "Not implemented" else response = post(data) end when "PUT" response = put(data) else raise ArgumentError, "Unsupported HTTP method: #{param[:method]}" end #Loop dirs? if not response.nil? and (response.respond_to? :body or response.is_a? Array) if response.is_a? Array responses = response else responses = [response] end i = 0 responses.each do | response | i += 1 log.debug "#{method} #{response.uri.path} [#{i}] Total time: #{response.total_time}"+ " DNS time: #{response.namelookup_time}"+ " Connect time: #{response.connect_time}"+ " Pre-transer time: #{response.pretransfer_time}" if "HEAD" == method or headers? puts response.response_headers end unless param[:join] puts response.body end end statuses = responses.map {|r| r.code }.uniq status = statuses.map {|code| { code => responses.select {|r| code == r.code }.size } }.to_json.gsub(/["{}\[\]]/, "") real_responses_size = responses.select {|r| r.code >= 100 }.size log.info "Status(es): #{status}, request(s): #{responses.size}, response(s): #{real_responses_size}" else raise "Invalid response: #{response}" end if param[:join] joined = responses.map {|r| JSON.parse(r.body) } puts joined.to_json end end
ruby
{ "resource": "" }
q9603
Vigilem::Core::Hooks.ConditionalHook.enumerate
train
def enumerate(args={}, &block) passed, failed = [], [] hook = self super do |callback| if hook.condition.call(*callback.options[:condition_args]) hook.passed << callback callback.evaluate(args[:context], *args[:args], &args[:block]) else hook.failed << callback end end end
ruby
{ "resource": "" }
q9604
Poltergeist::ScreenshotOverview.Manager.add_image_from_rspec
train
def add_image_from_rspec(argument, example, url_path) blob = caller.find{|i| i[ example.file_path.gsub(/:\d*|^\./,"") ]} file_with_line = blob.split(":")[0,2].join(":") filename = [example.description, argument, file_with_line, SecureRandom.hex(6) ].join(" ").gsub(/\W+/,"_") + ".jpg" full_name = File.join(Poltergeist::ScreenshotOverview.target_directory, filename ) FileUtils.mkdir_p Poltergeist::ScreenshotOverview.target_directory describe = example.metadata[:example_group][:description_args] @files << Screenshot.new({ :url => url_path, :argument => argument, :local_image => filename, :full_path => full_name, :group_description => describe, :example_description => example.description, :file_with_line => file_with_line }) full_name end
ruby
{ "resource": "" }
q9605
AudioVision.Client.get
train
def get(path, params={}) connection.get do |request| request.url path request.params = params end end
ruby
{ "resource": "" }
q9606
TodoLint.ConfigFile.read_config_file
train
def read_config_file(file) @config_hash = YAML.load_file(file) @starting_path = File.expand_path(File.split(file).first) @config_options = {} load_tags load_file_exclusions load_extension_inclusions config_options end
ruby
{ "resource": "" }
q9607
TodoLint.ConfigFile.load_file_exclusions
train
def load_file_exclusions return unless config_hash["Exclude Files"] config_options[:excluded_files] = [] config_hash["Exclude Files"].each do |short_file| config_options[:excluded_files] << File.join(starting_path, short_file) end end
ruby
{ "resource": "" }
q9608
TodoLint.ConfigFile.load_tags
train
def load_tags config_options[:tags] = {} return unless config_hash["Tags"] config_hash["Tags"].each do |tag, due_date| unless due_date.is_a? Date raise ArgumentError, "#{due_date} is not a date" end config_options[:tags]["##{tag}"] = DueDate.new(due_date) end end
ruby
{ "resource": "" }
q9609
Automodel.SchemaInspector.columns
train
def columns(table_name) table_name = table_name.to_s @columns ||= {} @columns[table_name] ||= if @registration[:columns].present? @registration[:columns].call(@connection, table_name) else @connection.columns(table_name) end end
ruby
{ "resource": "" }
q9610
Automodel.SchemaInspector.primary_key
train
def primary_key(table_name) table_name = table_name.to_s @primary_keys ||= {} @primary_keys[table_name] ||= if @registration[:primary_key].present? @registration[:primary_key].call(@connection, table_name) else @connection.primary_key(table_name) end end
ruby
{ "resource": "" }
q9611
Automodel.SchemaInspector.foreign_keys
train
def foreign_keys(table_name) table_name = table_name.to_s @foreign_keys ||= {} @foreign_keys[table_name] ||= begin if @registration[:foreign_keys].present? @registration[:foreign_keys].call(@connection, table_name) else begin @connection.foreign_keys(table_name) rescue ::NoMethodError, ::NotImplementedError ## Not all ActiveRecord adapters support `#foreign_keys`. When this happens, we'll make ## a best-effort attempt to intuit relationships from the table and column names. ## columns(table_name).map do |column| id_pattern = %r{(?:_id|Id)$} next unless column.name =~ id_pattern target_table = column.name.sub(id_pattern, '') next unless target_table.in? tables target_column = primary_key(qualified_name(target_table, context: table_name)) next unless target_column.in? ['id', 'Id', 'ID', column.name] ActiveRecord::ConnectionAdapters::ForeignKeyDefinition.new( table_name.split('.').last, target_table, name: "FK_#{SecureRandom.uuid.delete('-')}", column: column.name, primary_key: target_column, on_update: nil, on_delete: nil ) end.compact end end end end
ruby
{ "resource": "" }
q9612
Naming.NameSet.others
train
def others(array) array.select{|elt| not(any?{|name| elt.kind_of?(name)})} end
ruby
{ "resource": "" }
q9613
Tay.ManifestGenerator.spec_as_json
train
def spec_as_json json = { :name => spec.name, :version => spec.version, :manifest_version => calculate_manifest_version } json[:description] = spec.description if spec.description json[:icons] = spec.icons json[:default_locale] = spec.default_locale if spec.default_locale json[:browser_action] = action_as_json(spec.browser_action) if spec.browser_action json[:page_action] = action_as_json(spec.page_action) if spec.page_action json[:app] = packaged_app_as_json if spec.packaged_app if spec.background_page json[:background] = { :page => spec.background_page } end unless spec.background_scripts.empty? json[:background] = { :scripts => spec.background_scripts } end json[:chrome_url_overrides] = spec.overriden_pages unless spec.overriden_pages.empty? json[:content_scripts] = content_scripts_as_json unless spec.content_scripts.empty? json[:content_security_policy] = spec.content_security_policy if spec.content_security_policy json[:homepage_url] = spec.homepage if spec.homepage json[:incognito] = spec.incognito_mode if spec.incognito_mode json[:intents] = web_intents_as_json unless spec.web_intents.empty? json[:minimum_chrome_version] = spec.minimum_chrome_version if spec.minimum_chrome_version json[:nacl_modules] = nacl_modules_as_json unless spec.nacl_modules.empty? json[:offline_enabled] = spec.offline_enabled unless spec.offline_enabled.nil? json[:omnibox] = spec.omnibox_keyword if spec.omnibox_keyword json[:options_page] = spec.options_page if spec.options_page json[:permissions] = spec.permissions unless spec.permissions.empty? json[:requirements] = requirements_as_json if has_requirements? json[:update_url] = spec.update_url if spec.update_url json[:web_accessible_resources] = spec.web_accessible_resources unless spec.web_accessible_resources.empty? json end
ruby
{ "resource": "" }
q9614
Tay.ManifestGenerator.action_as_json
train
def action_as_json(action) json = {} json[:default_title] = action.title if action.title json[:default_icon] = action.icon if action.icon json[:default_popup] = action.popup if action.popup json end
ruby
{ "resource": "" }
q9615
Tay.ManifestGenerator.packaged_app_as_json
train
def packaged_app_as_json app = spec.packaged_app json = { :local_path => app.page } unless app.container.nil? json[:container] = app.container if app.container == 'panel' json[:width] = app.width json[:height] = app.height end end { :launch => json } end
ruby
{ "resource": "" }
q9616
Tay.ManifestGenerator.content_scripts_as_json
train
def content_scripts_as_json spec.content_scripts.map do |cs| cs_json = { :matches => cs.include_patterns } cs_json[:exclude_matches] = cs.exclude_patterns unless cs.exclude_patterns.empty? cs_json[:run_at] = cs.run_at if cs.run_at cs_json[:all_frames] = cs.all_frames unless cs.all_frames.nil? cs_json[:css] = cs.stylesheets unless cs.stylesheets.empty? cs_json[:js] = cs.javascripts unless cs.javascripts.empty? cs_json end end
ruby
{ "resource": "" }
q9617
Tay.ManifestGenerator.web_intents_as_json
train
def web_intents_as_json spec.web_intents.map do |wi| { :action => wi.action, :title => wi.title, :href => wi.href, :types => wi.types, :disposition => wi.disposition } end end
ruby
{ "resource": "" }
q9618
Logsly::Logging182::Appenders.Email.canonical_write
train
def canonical_write( str ) ### build a mail header for RFC 822 rfc822msg = "From: #{@from}\n" rfc822msg << "To: #{@to.join(",")}\n" rfc822msg << "Subject: #{@subject}\n" rfc822msg << "Date: #{Time.new.rfc822}\n" rfc822msg << "Message-Id: <#{"%.8f" % Time.now.to_f}@#{@domain}>\n\n" rfc822msg = rfc822msg.force_encoding(encoding) if encoding and rfc822msg.encoding != encoding rfc822msg << str ### send email smtp = Net::SMTP.new(@address, @port) smtp.enable_starttls_auto if @enable_starttls_auto and smtp.respond_to? :enable_starttls_auto smtp.start(@domain, @user_name, @password, @authentication) { |s| s.sendmail(rfc822msg, @from, @to) } self rescue StandardError, TimeoutError => err self.level = :off ::Logsly::Logging182.log_internal {'e-mail notifications have been disabled'} ::Logsly::Logging182.log_internal(-2) {err} end
ruby
{ "resource": "" }
q9619
SeleniumStandaloneDSL.Base.click
train
def click(selector, find_by: :link_text) sleep Random.new.rand(1..2) with_frame do @driver.find_element(find_by, selector).click end sleep Random.new.rand(1..2) end
ruby
{ "resource": "" }
q9620
BlogBasic.BlogPost.replace_blog_image_tags
train
def replace_blog_image_tags @resaving = true self.body.gsub!(/[{]blog_image:upload[0-9]+:[a-zA-Z]+[}]/) do |image_tag| random_id, size = image_tag.scan(/upload([0-9]+)[:]([a-zA-Z]+)/).flatten new_id = random_id matching_image = self.blog_images.reject {|bi| !bi.random_id || bi.random_id != random_id }.first if matching_image new_id = matching_image.id end "{blog_image:#{new_id}:#{size}}" end self.save @resaving = false return true end
ruby
{ "resource": "" }
q9621
Versed.Schedule.incomplete_tasks
train
def incomplete_tasks # TODO: refactor with reject incomplete = [] categories.each { |c| incomplete << c if c.incomplete? } incomplete.sort_by { |c| [-c.percent_incomplete, -c.total_min_incomplete] } end
ruby
{ "resource": "" }
q9622
Versed.Schedule.category_ids
train
def category_ids(entries) category_ids = [] entries.each do |day, tasks| category_ids += tasks.keys end category_ids.uniq end
ruby
{ "resource": "" }
q9623
VCSToolkit.Merge.combine_diffs
train
def combine_diffs(diff_one, diff_two) Hash.new { |hash, key| hash[key] = [[], []] }.tap do |combined_diff| diff_one.each do |change| combined_diff[change.old_position].first << change end diff_two.each do |change| combined_diff[change.old_position].last << change end end end
ruby
{ "resource": "" }
q9624
SDL4R.Tag.children_values
train
def children_values(name = nil) children_values = [] each_child(false, name) { |child| case child.values.size when 0 children_values << nil when 1 children_values << child.value else children_values << child.values end } return children_values end
ruby
{ "resource": "" }
q9625
SDL4R.Tag.each_child
train
def each_child(recursive = false, namespace = nil, name = :DEFAULT, &block) if name == :DEFAULT name = namespace namespace = nil end @children.each do |child| if (name.nil? or child.name == name) and (namespace.nil? or child.namespace == namespace) yield child end child.children(recursive, namespace, name, &block) if recursive end return nil end
ruby
{ "resource": "" }
q9626
SDL4R.Tag.remove_value
train
def remove_value(v) index = @values.index(v) if index return !@values.delete_at(index).nil? else return false end end
ruby
{ "resource": "" }
q9627
SDL4R.Tag.has_attribute?
train
def has_attribute?(namespace = nil, key = nil) namespace, key = to_nns namespace, key if namespace or key attributes = @attributesByNamespace[namespace] return attributes.nil? ? false : attributes.has_key?(key) else attributes { return true } return false end end
ruby
{ "resource": "" }
q9628
SDL4R.Tag.each_attribute
train
def each_attribute(namespace = nil, &block) # :yields: namespace, key, value if namespace.nil? @attributesByNamespace.each_key { |a_namespace| each_attribute(a_namespace, &block) } else attributes = @attributesByNamespace[namespace] unless attributes.nil? attributes.each_pair do |key, value| yield namespace, key, value end end end end
ruby
{ "resource": "" }
q9629
SDL4R.Tag.namespace=
train
def namespace=(a_namespace) a_namespace = a_namespace.to_s SDL4R.validate_identifier(a_namespace) unless a_namespace.empty? @namespace = a_namespace end
ruby
{ "resource": "" }
q9630
SDL4R.Tag.read
train
def read(input) if input.is_a? String read_from_io(true) { StringIO.new(input) } elsif input.is_a? Pathname read_from_io(true) { input.open("r:UTF-8") } elsif input.is_a? URI read_from_io(true) { input.open } else read_from_io(false) { input } end return self end
ruby
{ "resource": "" }
q9631
SDL4R.Tag.read_from_io
train
def read_from_io(close_io) io = yield begin Parser.new(io).parse.each do |tag| add_child(tag) end ensure if close_io io.close rescue IOError end end end
ruby
{ "resource": "" }
q9632
SDL4R.Tag.children_to_string
train
def children_to_string(line_prefix = "", s = "") @children.each do |child| s << child.to_string(line_prefix) << $/ end return s end
ruby
{ "resource": "" }
q9633
Cyclical.Occurrence.list_occurrences
train
def list_occurrences(from, direction = :forward, &block) raise ArgumentError, "From #{from} not matching the rule #{@rule} and start time #{@start_time}" unless @rule.match?(from, @start_time) results = [] n, current = init_loop(from, direction) loop do # Rails.logger.debug("Listing occurrences of #{@rule}, going #{direction.to_s}, current: #{current}") # break on schedule span limits return results unless (current >= @start_time) && (@rule.stop.nil? || current < @rule.stop) && (@rule.count.nil? || (n -= 1) >= 0) # break on block condition return results unless yield current results << current # step if direction == :forward current = @rule.next(current, @start_time) else current = @rule.previous(current, @start_time) end end end
ruby
{ "resource": "" }
q9634
ICU.Team.add_member
train
def add_member(number) pnum = number.to_i raise "'#{number}' is not a valid as a team member player number" if pnum == 0 && !number.to_s.match(/^[^\d]*0/) raise "can't add duplicate player number #{pnum} to team '#{@name}'" if @members.include?(pnum) @members.push(pnum) end
ruby
{ "resource": "" }
q9635
ICU.Team.renumber
train
def renumber(map) @members.each_with_index do |pnum, index| raise "player number #{pnum} not found in renumbering hash" unless map[pnum] @members[index] = map[pnum] end self end
ruby
{ "resource": "" }
q9636
Cany.Dependency.define_on_distro_release
train
def define_on_distro_release(distro, release, name, version=nil) distro_releases[[distro, release]] << [name, version] end
ruby
{ "resource": "" }
q9637
XivelyConnector.Connection.set_httparty_options
train
def set_httparty_options(options={}) if options[:ssl_ca_file] ssl_ca_file opts[:ssl_ca_file] if options[:pem_cert_pass] pem File.read(options[:pem_cert]), options[:pem_cert_pass] else pem File.read(options[:pem_cert]) end end end
ruby
{ "resource": "" }
q9638
NSICloudooo.Client.granulate
train
def granulate(options = {}) @request_data = Hash.new if options[:doc_link] insert_download_data options else file_data = {:doc => options[:file], :filename => options[:filename]} @request_data.merge! file_data end insert_callback_data options request = prepare_request :POST, @request_data.to_json execute_request(request) end
ruby
{ "resource": "" }
q9639
Scalaroid.JSONReqList.add_write
train
def add_write(key, value, binary = false) if (@is_commit) raise RuntimeError.new('No further request supported after a commit!') end @requests << {'write' => {key => JSONConnection.encode_value(value, binary)}} self end
ruby
{ "resource": "" }
q9640
Scalaroid.JSONReqList.add_add_del_on_list
train
def add_add_del_on_list(key, to_add, to_remove) if (@is_commit) raise RuntimeError.new('No further request supported after a commit!') end @requests << {'add_del_on_list' => {'key' => key, 'add' => to_add, 'del'=> to_remove}} self end
ruby
{ "resource": "" }
q9641
Handcart.ControllerAdditions.allow_or_reject
train
def allow_or_reject # We assume the the rejection action is going to be on the public controller # since we wouldn't want to forward the rejection to the handcart my_rejection_url = main_app.url_for({ # subdomain: '', host: Handcart::DomainConstraint.default_constraint.domain, controller: @rejection_url.split("#").first, action: @rejection_url.split("#").last, trailing_slash: false, }) # See if they have enable IP blocking if they respond to that. if current_handcart.respond_to?(:enable_ip_blocking?) truthiness = current_handcart.enable_ip_blocking? else # Default to true truthiness = true end if truthiness ip_address = current_handcart.ip_addresses.permitted.find_by_address(request.remote_ip) if ip_address if Handcart.ip_authorization.strategy.is_in_range?(ip_address.address, current_handcart) # Do nothing, let them login else # # The strategy doesn't match redirect_to my_rejection_url end else # No IP Address was found redirect_to my_rejection_url end else # Do nothing, blocking mode is disabled end end
ruby
{ "resource": "" }
q9642
Palimpsest.Environment.copy
train
def copy(destination: site.path, mirror: false) fail 'Must specify a destination' if destination.nil? exclude = options[:copy_exclude] exclude.concat config[:persistent] unless config[:persistent].nil? Utils.copy_directory directory, destination, exclude: exclude, mirror: mirror self end
ruby
{ "resource": "" }
q9643
Palimpsest.Environment.populate
train
def populate(from: :auto) return if populated fail "Cannot populate without 'site'" if site.nil? case from when :auto if site.respond_to?(:repository) ? site.repository : nil populate from: :repository else populate from: :source end when :repository fail "Cannot populate without 'reference'" if reference.empty? repo.extract directory, reference: reference @populated = true when :source source = site.source.nil? ? '.' : site.source Utils.copy_directory source, directory, exclude: options[:copy_exclude] @populated = true end self end
ruby
{ "resource": "" }
q9644
Palimpsest.Environment.validate_config
train
def validate_config message = 'bad path in config' # Checks the option in the asset key. def validate_asset_options(opts) opts.each do |k, v| fail 'bad option in config' if k == :sprockets_options fail message if k == :output && !Utils.safe_path?(v) end end @config[:excludes].each do |v| fail message unless Utils.safe_path? v end unless @config[:excludes].nil? @config[:external].each do |k, v| next if k == :server v.each do |repo| fail message unless Utils.safe_path? repo[1] end unless v.nil? end unless @config[:external].nil? @config[:components].each do |k, v| # process @config[:components][:base] then go to the next option if k == :base fail message unless Utils.safe_path? v next end unless v.nil? # process @config[:components][:paths] if k == :paths v.each do |path| fail message unless Utils.safe_path? path[0] fail message unless Utils.safe_path? path[1] end end end unless @config[:components].nil? @config[:assets].each do |k, v| # process @config[:assets][:options] then go to the next option if k == :options validate_asset_options v next end unless v.nil? # process @config[:assets][:sources] then go to the next option if k == :sources v.each_with_index do |source, _| fail message unless Utils.safe_path? source end next end # process each asset type in @config[:assets] v.each do |asset_key, asset_value| # process :options if asset_key == :options validate_asset_options asset_value next end unless asset_value.nil? # process each asset path asset_value.each_with_index do |path, _| fail message unless Utils.safe_path? path end if asset_key == :paths end end unless @config[:assets].nil? @config end
ruby
{ "resource": "" }
q9645
Redstruct.TimeSeries.get
train
def get(options = {}) lower = nil upper = nil if options[:in].nil? lower = options[:after].nil? ? '-inf' : coerce_time_milli(options[:after]) upper = options[:before].nil? ? '+inf' : [0, coerce_time_milli(options[:before])].max else lower = coerce_time_milli(options[:in].begin) upper = coerce_time_milli(options[:in].end) upper = "(#{upper}" if options[:in].exclude_end? end argv = [expires_at, lower, upper] unless options[:limit].nil? limit = options[:limit].to_i raise ArgumentError, 'limit must be positive' unless limit.positive? argv.push(limit, [0, options[:offset].to_i].max) end events = get_script(keys: @event_list.key, argv: argv) return events.map(&method(:remove_event_id)) end
ruby
{ "resource": "" }
q9646
Spirit.Logger.record
train
def record(action, *args) msg = '' msg << color(ACTION_COLORS[action]) msg << action_padding(action) + action.to_s msg << color(:clear) msg << ' ' + args.join(' ') info msg end
ruby
{ "resource": "" }
q9647
Spirit.Logger.max_action_length
train
def max_action_length @max_action_length ||= actions.reduce(0) { |m, a| [m, a.to_s.length].max } end
ruby
{ "resource": "" }
q9648
ViewFu.BrowserDetect.browser_name
train
def browser_name @browser_name ||= begin ua = request.user_agent.to_s.downcase if ua.index('msie') && !ua.index('opera') && !ua.index('webtv') 'ie'+ua[ua.index('msie')+5].chr elsif ua.index('gecko/') 'gecko' elsif ua.index('opera') 'opera' elsif ua.index('konqueror') 'konqueror' elsif ua.index('iphone') 'iphone' elsif ua.index('applewebkit/') 'safari' elsif ua.index('mozilla/') 'gecko' else "" end end end
ruby
{ "resource": "" }
q9649
Empyrean.ConfigLoader.load
train
def load(file) if File.exist? file symbolize_keys(YAML.load_file(File.expand_path('.', file))) else {} end end
ruby
{ "resource": "" }
q9650
Empyrean.ConfigLoader.load_config
train
def load_config(file = @options.config) config = load(file) config[:timezone_difference] = 0 if config[:timezone_difference].nil? config[:mentions] = {} if config[:mentions].nil? config[:mentions][:enabled] = true if config[:mentions][:enabled].nil? config[:mentions][:top] = 10 if config[:mentions][:top].nil? config[:mentions][:notop] = 20 if config[:mentions][:notop].nil? config[:clients] = {} if config[:clients].nil? config[:clients][:enabled] = true if config[:clients][:enabled].nil? config[:clients][:top] = 10 if config[:clients][:top].nil? config[:clients][:notop] = 20 if config[:clients][:notop].nil? config[:hashtags] = {} if config[:hashtags].nil? config[:hashtags][:enabled] = true if config[:hashtags][:enabled].nil? config[:hashtags][:top] = 10 if config[:hashtags][:top].nil? config[:hashtags][:notop] = 20 if config[:hashtags][:notop].nil? config[:smileys] = {} if config[:smileys].nil? config[:smileys][:enabled] = true if config[:smileys][:enabled].nil? config[:smileys][:top] = 10 if config[:smileys][:top].nil? config[:smileys][:notop] = 0 if config[:smileys][:notop].nil? config[:ignored_users] = [] if config[:ignored_users].nil? config[:renamed_users] = [] if config[:renamed_users].nil? args_override config end
ruby
{ "resource": "" }
q9651
ProjectEulerCli.ArchiveViewer.display_recent
train
def display_recent load_recent puts (Problem.total).downto(Problem.total - 9) do |i| puts "#{i} - #{Problem[i].title}" end end
ruby
{ "resource": "" }
q9652
ProjectEulerCli.ArchiveViewer.display_page
train
def display_page(page) load_page(page) puts start = (page - 1) * Page::LENGTH + 1 start.upto(start + Page::LENGTH - 1) do |i| puts "#{i} - #{Problem[i].title}" unless i >= Problem.total - 9 end end
ruby
{ "resource": "" }
q9653
ProjectEulerCli.ArchiveViewer.display_problem
train
def display_problem(id) load_problem_details(id) puts puts "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" puts puts Problem[id].title.upcase puts "Problem #{id}" puts puts Problem[id].published puts Problem[id].solved_by puts Problem[id].difficulty if id < Problem.total - 9 puts puts "https://projecteuler.net/problem=#{id}" puts puts "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" end
ruby
{ "resource": "" }
q9654
RFGraph.Auth.authorize
train
def authorize(callback_url, code) data = open("#{BASE_URL}/oauth/access_token?client_id=#{app_id}&redirect_uri=#{CGI.escape callback_url}&client_secret=#{app_secret}&code=#{CGI.escape code}").read # The expiration date is not necessarily set, as the app might have # requested offline_access to the data match_data = data.match(/expires=([^&]+)/) @expires = match_data && match_data[1] || nil # Extract the access token @access_token = data.match(/access_token=([^&]+)/)[1] end
ruby
{ "resource": "" }
q9655
ActionDispatch::Routing.Mapper.devise_for
train
def devise_for(*resources) @devise_finalized = false options = resources.extract_options! options[:as] ||= @scope[:as] if @scope[:as].present? options[:module] ||= @scope[:module] if @scope[:module].present? options[:path_prefix] ||= @scope[:path] if @scope[:path].present? options[:path_names] = (@scope[:path_names] || {}).merge(options[:path_names] || {}) options[:constraints] = (@scope[:constraints] || {}).merge(options[:constraints] || {}) options[:defaults] = (@scope[:defaults] || {}).merge(options[:defaults] || {}) options[:options] = @scope[:options] || {} options[:options][:format] = false if options[:format] == false resources.map!(&:to_sym) resources.each do |resource| mapping = Devise.add_mapping(resource, options) begin raise_no_devise_method_error!(mapping.class_name) unless mapping.to.respond_to?(:devise) rescue NameError => e raise unless mapping.class_name == resource.to_s.classify warn "[WARNING] You provided devise_for #{resource.inspect} but there is " << "no model #{mapping.class_name} defined in your application" next rescue NoMethodError => e raise unless e.message.include?("undefined method `devise'") raise_no_devise_method_error!(mapping.class_name) end routes = mapping.used_routes devise_scope mapping.name do if block_given? ActiveSupport::Deprecation.warn "Passing a block to devise_for is deprecated. " \ "Please remove the block from devise_for (only the block, the call to " \ "devise_for must still exist) and call devise_scope :#{mapping.name} do ... end " \ "with the block instead", caller yield end with_devise_exclusive_scope mapping.fullpath, mapping.name, options do routes.each { |mod| send("devise_#{mod}", mapping, mapping.controllers) } end end end end
ruby
{ "resource": "" }
q9656
Ponder.ChannelList.remove
train
def remove(channel_or_channel_name) @mutex.synchronize do if channel_or_channel_name.is_a?(String) channel_or_channel_name = find(channel_or_channel_name) end @channels.delete(channel_or_channel_name) end end
ruby
{ "resource": "" }
q9657
Ponder.ChannelList.remove_user
train
def remove_user(nick) @mutex.synchronize do channels = Set.new @channels.each do |channel| if channel.remove_user(nick) channels << channel end end channels end end
ruby
{ "resource": "" }
q9658
Ponder.ChannelList.users
train
def users users = Set.new @channels.each do |channel| users.merge channel.users end users end
ruby
{ "resource": "" }
q9659
Pingback.Client.ping
train
def ping(source_uri, target_uri) header = request_header target_uri pingback_server = header['X-Pingback'] unless pingback_server doc = Nokogiri::HTML(request_all(target_uri).body) link = doc.xpath('//link[@rel="pingback"]/attribute::href').first pingback_server = URI.escape(link.content) if link end raise InvalidTargetException unless pingback_server send_pingback pingback_server, source_uri, target_uri end
ruby
{ "resource": "" }
q9660
SimpleMetarParser.Wind.decode_wind
train
def decode_wind(s) if s =~ /(\d{3})(\d{2})G?(\d{2})?(KT|MPS|KMH)/ # different units wind = case $4 when "KT" then $2.to_f * KNOTS_TO_METERS_PER_SECOND when "MPS" then $2.to_f when "KMH" then $2.to_f * KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND else nil end wind_max = case $4 when "KT" then $3.to_f * KNOTS_TO_METERS_PER_SECOND when "MPS" then $3.to_f when "KMH" then $3.to_f * KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND else nil end # wind_max is not less than normal wind if wind_max < wind or wind_max.nil? wind_max = wind end @winds << { :wind => wind, :wind_max => wind_max, :wind_direction => $1.to_i } end # variable/unknown direction if s =~ /VRB(\d{2})(KT|MPS|KMH)/ wind = case $2 when "KT" then $1.to_f * KNOTS_TO_METERS_PER_SECOND when "MPS" then $1.to_f when "KMH" then $1.to_f * KILOMETERS_PER_HOUR_TO_METERS_PER_SECOND else nil end @winds << { :wind => wind } end end
ruby
{ "resource": "" }
q9661
SimpleMetarParser.Wind.recalculate_winds
train
def recalculate_winds wind_sum = @winds.collect { |w| w[:wind] }.inject(0) { |b, i| b + i } @wind = wind_sum.to_f / @winds.size if @winds.size == 1 @wind_direction = @winds.first[:wind_direction] else @wind_direction = nil end end
ruby
{ "resource": "" }
q9662
Fwissr.Registry.add_source
train
def add_source(source) @semaphore.synchronize do @sources << source end if @registry.frozen? # already frozen, must reload everything self.reload! else @semaphore.synchronize do Fwissr.merge_conf!(@registry, source.get_conf) end end self.ensure_refresh_thread end
ruby
{ "resource": "" }
q9663
Fwissr.Registry.get
train
def get(key) # split key key_ary = key.split('/') # remove first empty part key_ary.shift if (key_ary.first == '') cur_hash = self.registry key_ary.each do |key_part| cur_hash = cur_hash[key_part] return nil if cur_hash.nil? end cur_hash end
ruby
{ "resource": "" }
q9664
ActiveModel.Hints.hints_for
train
def hints_for(attribute) result = Array.new @base.class.validators_on(attribute).map do |v| validator = v.class.to_s.split('::').last.underscore.gsub('_validator','') if v.options[:message].is_a?(Symbol) message_key = [validator, v.options[:message]].join('.') # if a message was supplied as a symbol, we use it instead result << generate_message(attribute, message_key, v.options) else message_key = validator message_key = [validator, ".must_be_a_number"].join('.') if validator == 'numericality' # create an option for numericality; the way YAML works a key (numericality) with subkeys (greater_than, etc etc) can not have a string itself. So we create a subkey for numericality result << generate_message(attribute, message_key, v.options) unless VALIDATORS_WITHOUT_MAIN_KEYS.include?(validator) v.options.each do |o| if MESSAGES_FOR_OPTIONS.include?(o.first.to_s) count = o.last count = (o.last.to_sentence if %w(inclusion exclusion).include?(validator)) rescue o.last result << generate_message(attribute, [ validator, o.first.to_s ].join('.'), { :count => count } ) end end end end result end
ruby
{ "resource": "" }
q9665
DohDb.Handle.select
train
def select(statement, build_arg = nil) result_set = generic_query(statement) DohDb.logger.call('result', "selected #{result_set.size} rows") rows = get_row_builder(build_arg).build_rows(result_set) rows end
ruby
{ "resource": "" }
q9666
DohDb.Handle.select_row
train
def select_row(statement, build_arg = nil) rows = select(statement, build_arg) raise UnexpectedQueryResult, "selected #{rows.size} rows; expected 1" unless rows.size == 1 rows[0] end
ruby
{ "resource": "" }
q9667
DohDb.Handle.select_optional_row
train
def select_optional_row(statement, build_arg = nil) rows = select(statement, build_arg) raise UnexpectedQueryResult, "selected #{rows.size} rows; expected 0 or 1" if rows.size > 1 if rows.empty? then nil else rows[0] end end
ruby
{ "resource": "" }
q9668
DohDb.Handle.select_transpose
train
def select_transpose(statement, build_arg = nil) rows = select(statement, build_arg) return {} if rows.empty? field_count = rows.first.size if field_count < 2 raise UnexpectedQueryResult, "must select at least 2 fields in order to transpose" elsif field_count == 2 Doh.array_to_hash(rows) { |row| [row.at(0), row.at(1)] } else key_field = rows.first.keys.first Doh.array_to_hash(rows) do |row| value = row.to_h value.delete(key_field) [row.at(0), value] end end end
ruby
{ "resource": "" }
q9669
Redstruct.Hash.get
train
def get(*keys) return self.connection.hget(@key, keys.first) if keys.size == 1 return self.connection.mapped_hmget(@key, *keys).reject { |_, v| v.nil? } end
ruby
{ "resource": "" }
q9670
Redstruct.Hash.set
train
def set(key, value, overwrite: true) result = if overwrite self.connection.hset(@key, key, value) else self.connection.hsetnx(@key, key, value) end return coerce_bool(result) end
ruby
{ "resource": "" }
q9671
Redstruct.Hash.increment
train
def increment(key, by: 1) if by.is_a?(Float) self.connection.hincrbyfloat(@key, key, by.to_f).to_f else self.connection.hincrby(@key, key, by.to_i).to_i end end
ruby
{ "resource": "" }
q9672
ControllerExtensions.UrlExt.url_for
train
def url_for(options = {}) options = case options when String uri = Addressable::URI.new uri.query_values = @hash_of_additional_params options + (options.index('?').nil? ? '?' : '&') + "#{uri.query}" when Hash options.reverse_merge(@hash_of_additional_params || {}) else options end super end
ruby
{ "resource": "" }
q9673
Aker.Group.include?
train
def include?(other) other_name = case other when Group; other.name; else other.to_s; end self.find { |g| g.name.downcase == other_name.downcase } end
ruby
{ "resource": "" }
q9674
Aker.Group.marshal_load
train
def marshal_load(dumped_tree_array) nodes = { } for node_hash in dumped_tree_array do name = node_hash[:name] parent_name = node_hash[:parent] content = Marshal.load(node_hash[:content]) if parent_name then nodes[name] = current_node = self.class.new(name, content) nodes[parent_name].add current_node else # This is the root node, hence initialize self. initialize(name, content) nodes[name] = self # Add self to the list of nodes end end end
ruby
{ "resource": "" }
q9675
SycLink.Chrome.read
train
def read serialized = File.read(path) extract_links(JSON.parse(serialized)).flatten.each_slice(4).to_a end
ruby
{ "resource": "" }
q9676
SycLink.Chrome.extract_children
train
def extract_children(tag, children) children.map do |child| if child["children"] extract_children("#{tag},#{child['name']}", child["children"]) else [child["url"], child["name"], "", tag] end end end
ruby
{ "resource": "" }
q9677
Handlebarer.Template.evaluate
train
def evaluate(scope, locals, &block) c = Handlebarer::Compiler.new c.compile(data) end
ruby
{ "resource": "" }
q9678
PutText.Cmdline.run
train
def run(args) options = parse_args(args) po_file = Extractor.new.extract(options[:path]) if options[:output_file] with_output_file(options[:output_file]) { |f| po_file.write_to(f) } else po_file.write_to(STDOUT) end rescue => e error(e) end
ruby
{ "resource": "" }
q9679
GroupDocsComparisonCloud.ChangesApi.put_changes_document_stream_with_http_info
train
def put_changes_document_stream_with_http_info(request) raise ArgumentError, 'Incorrect request type' unless request.is_a? PutChangesDocumentStreamRequest @api_client.config.logger.debug 'Calling API: ChangesApi.put_changes_document_stream ...' if @api_client.config.debugging # resource path local_var_path = '/comparison/compareDocuments/changes/stream' # query parameters query_params = {} # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml']) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(request.request) data, status_code, headers = @api_client.call_api(:PUT, local_var_path, header_params: header_params, query_params: query_params, form_params: form_params, body: post_body, access_token: get_access_token, return_type: 'File') if @api_client.config.debugging @api_client.config.logger.debug "API called: ChangesApi#put_changes_document_stream\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end [data, status_code, headers] end
ruby
{ "resource": "" }
q9680
GroupDocsComparisonCloud.ChangesApi.put_changes_images_with_http_info
train
def put_changes_images_with_http_info(request) raise ArgumentError, 'Incorrect request type' unless request.is_a? PutChangesImagesRequest @api_client.config.logger.debug 'Calling API: ChangesApi.put_changes_images ...' if @api_client.config.debugging # resource path local_var_path = '/comparison/compareDocuments/changes/images' # query parameters query_params = {} if local_var_path.include? ('{' + downcase_first_letter('OutFolder') + '}') local_var_path = local_var_path.sub('{' + downcase_first_letter('OutFolder') + '}', request.out_folder.to_s) else query_params[downcase_first_letter('OutFolder')] = request.out_folder unless request.out_folder.nil? end # header parameters header_params = {} # HTTP header 'Accept' (if needed) header_params['Accept'] = @api_client.select_header_accept(['application/json', 'application/xml']) # HTTP header 'Content-Type' header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml']) # form parameters form_params = {} # http body (model) post_body = @api_client.object_to_http_body(request.request) data, status_code, headers = @api_client.call_api(:PUT, local_var_path, header_params: header_params, query_params: query_params, form_params: form_params, body: post_body, access_token: get_access_token, return_type: 'Array<Link>') if @api_client.config.debugging @api_client.config.logger.debug "API called: ChangesApi#put_changes_images\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" end [data, status_code, headers] end
ruby
{ "resource": "" }
q9681
BoxGrinder.ApplianceDefinitionHelper.read_definitions
train
def read_definitions(definition, content_type = nil) @appliance_parser.load_schemas if File.exists?(definition) definition_file_extension = File.extname(definition) appliance_config = case definition_file_extension when '.appl', '.yml', '.yaml' @appliance_parser.parse_definition(definition) else unless content_type.nil? case content_type when 'application/x-yaml', 'text/yaml' @appliance_parser.parse_definition(definition) end end end return if appliance_config.nil? @appliance_configs << appliance_config appliances = [] @appliance_configs.each { |config| appliances << config.name } appliance_config.appliances.reverse.each do |appliance_name| read_definitions("#{File.dirname(definition)}/#{appliance_name}#{definition_file_extension}") unless appliances.include?(appliance_name) end unless appliance_config.appliances.nil? or !appliance_config.appliances.is_a?(Array) else # Assuming that the definition is provided as string @appliance_configs << @appliance_parser.parse_definition(definition, false) end end
ruby
{ "resource": "" }
q9682
Aker::Rack.Authenticate.call
train
def call(env) configuration = configuration(env) warden = env['warden'] if interactive?(env) warden.authenticate(configuration.ui_mode) else warden.authenticate(*configuration.api_modes) end env['aker.check'] = Facade.new(configuration, warden.user) @app.call(env) end
ruby
{ "resource": "" }
q9683
Localization.Middleware.locale_from_url
train
def locale_from_url path_info = nil @locale_set ||= begin @locale ||= (match = (path_info || @env['PATH_INFO']).match(locale_pattern)) ? match[1] : nil @env['PATH_INFO'] = match[2] if match && @env.try(:fetch, 'PATH_INFO') true end @locale end
ruby
{ "resource": "" }
q9684
HasPrice.Price.method_missing
train
def method_missing(meth, *args, &blk) value = select{|k,v| k.underscore == meth.to_s}.first if !value super elsif value.last.is_a?(Hash) self.class[value.last] else value.last end end
ruby
{ "resource": "" }
q9685
Qtc.Client.get
train
def get(path, params = nil, headers = {}) response = http_client.get(request_uri(path), params, request_headers(headers)) if response.status == 200 parse_response(response) else handle_error_response(response) end end
ruby
{ "resource": "" }
q9686
Chronic.Handler.match
train
def match(tokens, definitions) token_index = 0 @pattern.each do |element| name = element.to_s optional = name[-1, 1] == '?' name = name.chop if optional case element when Symbol if tags_match?(name, tokens, token_index) token_index += 1 next else if optional next else return false end end when String return true if optional && token_index == tokens.size if definitions.key?(name.to_sym) sub_handlers = definitions[name.to_sym] else raise ChronicPain, "Invalid subset #{name} specified" end sub_handlers.each do |sub_handler| return true if sub_handler.match(tokens[token_index..tokens.size], definitions) end else raise ChronicPain, "Invalid match type: #{element.class}" end end return false if token_index != tokens.size return true end
ruby
{ "resource": "" }
q9687
Triton.Messenger.add_listener
train
def add_listener(type, once=false, &callback) listener = Listener.new(type, callback, once) listeners[type] ||= [] listeners[type] << listener emit(:new_listener, self, type, once, callback) listener end
ruby
{ "resource": "" }
q9688
Triton.Messenger.remove_listener
train
def remove_listener(listener) type = listener.type if listeners.has_key? type listeners[type].delete(listener) listeners.delete(type) if listeners[type].empty? end end
ruby
{ "resource": "" }
q9689
Triton.Messenger.emit
train
def emit(type, sender=nil, *args) listeners[type].each { |l| l.fire(sender, *args) } if listeners.has_key? type end
ruby
{ "resource": "" }
q9690
Analysand.ChangeWatcher.changes_feed_uri
train
def changes_feed_uri query = { 'feed' => 'continuous', 'heartbeat' => '10000' } customize_query(query) uri = (@db.respond_to?(:uri) ? @db.uri : URI(@db)).dup uri.path += '/_changes' uri.query = build_query(query) uri end
ruby
{ "resource": "" }
q9691
Analysand.ChangeWatcher.waiter_for
train
def waiter_for(id) @waiting[id] = true Waiter.new do loop do break true if !@waiting[id] sleep 0.1 end end end
ruby
{ "resource": "" }
q9692
Guard.RSpectacle.reload
train
def reload Dir.glob('**/*.rb').each { |file| Reloader.reload_file(file) } self.last_run_passed = true self.rerun_specs = [] end
ruby
{ "resource": "" }
q9693
ActiveRecord.CounterCache.reset_counters
train
def reset_counters(id, *counters) object = find(id) counters.each do |association| has_many_association = reflect_on_association(association.to_sym) if has_many_association.options[:as] has_many_association.options[:as].to_s.classify else self.name end if has_many_association.is_a? ActiveRecord::Reflection::ThroughReflection has_many_association = has_many_association.through_reflection end foreign_key = has_many_association.foreign_key.to_s child_class = has_many_association.klass belongs_to = child_class.reflect_on_all_associations(:belongs_to) reflection = belongs_to.find { |e| e.foreign_key.to_s == foreign_key && e.options[:counter_cache].present? } counter_name = reflection.counter_cache_column stmt = unscoped.where(arel_table[primary_key].eq(object.id)).arel.compile_update({ arel_table[counter_name] => object.send(association).count }) connection.update stmt end return true end
ruby
{ "resource": "" }
q9694
DealRedemptions.Admin::RedeemCodesController.build_search_query
train
def build_search_query string = params[:search].split ' ' redeem_codes = DealRedemptions::RedeemCode.arel_table companies = DealRedemptions::Company.arel_table query = redeem_codes.project( redeem_codes[:id], redeem_codes[:company_id], redeem_codes[:code], redeem_codes[:status], redeem_codes[:created_at] ) .join(companies) .on(redeem_codes[:company_id] .eq(companies[:id])) string.each do |s| query.where(redeem_codes[:code].matches("%#{s}%")) end query.to_sql end
ruby
{ "resource": "" }
q9695
Mango.Runner.create
train
def create(path) self.destination_root = path copy_file(".gitignore") copy_file("config.ru") copy_file("Gemfile") copy_file("Procfile") copy_file("README.md") copy_content copy_themes end
ruby
{ "resource": "" }
q9696
Raca.Server.details
train
def details data = servers_client.get(server_path, json_headers).body JSON.parse(data)['server'] end
ruby
{ "resource": "" }
q9697
CrateAPI.Crates.add
train
def add(name) response = JSON.parse(CrateAPI::Base.call("#{CrateAPI::Base::CRATES_URL}/#{CRATE_ACTIONS[:add]}", :post, {:body => {:name => name}})) raise CrateLimitReachedError, response["message"] unless response["status"] != "failure" end
ruby
{ "resource": "" }
q9698
Oshpark.Client.authenticate
train
def authenticate email, credentials={} if password = credentials[:with_password] refresh_token email: email, password: password elsif secret = credentials[:with_api_secret] api_key = OpenSSL::Digest::SHA256.new("#{email}:#{secret}:#{token.token}").to_s refresh_token email: email, api_key: api_key else raise ArgumentError, "Must provide either `with_password` or `with_api_secret` arguments." end end
ruby
{ "resource": "" }
q9699
Oshpark.Client.pricing
train
def pricing width, height, pcb_layers, quantity = nil post_request "pricing", {width_in_mils: width, height_in_mils: height, pcb_layers: pcb_layers, quantity: quantity} end
ruby
{ "resource": "" }