_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q400
Tandem.PagesHelper.tandem_navigation_tag
train
def tandem_navigation_tag(active_page, pages_collection = nil, html_options = {}) html_options, pages_collection = pages_collection, nil if pages_collection.is_a?(Hash) html_options[:class] ||= 'nav' page_groups = (pages_collection || Page.all).inject({}) do |groups, page| if groups[page.par...
ruby
{ "resource": "" }
q401
Cryptoprocessing.Connection.get
train
def get(path, params = {}) uri = path if params.count > 0 uri += "?#{URI.encode_www_form(params)}" end headers = {} request('GET', uri, nil, headers) do |resp| if params[:fetch_all] == true && resp.body.has_key?('pagination') && resp.body['paginati...
ruby
{ "resource": "" }
q402
Cryptoprocessing.Connection.put
train
def put(path, params) headers = {} request('PUT', path, params.to_json, headers) do |resp| yield(resp) if block_given? end end
ruby
{ "resource": "" }
q403
Cryptoprocessing.Connection.post
train
def post(path, params) headers = {} request('POST', path, params.to_json, headers) do |resp| yield(resp) if block_given? end end
ruby
{ "resource": "" }
q404
Cryptoprocessing.Connection.delete
train
def delete(path, params) headers = {} request('DELETE', path, nil, headers) do |resp| yield(resp) if block_given? end end
ruby
{ "resource": "" }
q405
Pollster.Api.charts_slug_get
train
def charts_slug_get(slug, opts = {}) data, _status_code, _headers = charts_slug_get_with_http_info(slug, opts) return data end
ruby
{ "resource": "" }
q406
Pollster.Api.polls_slug_get
train
def polls_slug_get(slug, opts = {}) data, _status_code, _headers = polls_slug_get_with_http_info(slug, opts) return data end
ruby
{ "resource": "" }
q407
CurrencyConverter.XE.exchange_rate
train
def exchange_rate url = "/currencyconverter/convert/?Amount=1&From=#{from_currency.to_s.upcase}&To=#{to_currency.to_s.upcase}" uri = URI.parse('https://www.xe.com') request = Net::HTTP.new(uri.host, uri.port) request.use_ssl = true response = request.get(url) doc = Nokogiri::HTML(r...
ruby
{ "resource": "" }
q408
Krikri.Logger.log
train
def log(priority, msg) @logger.tagged(Time.now.to_s, Process.pid, to_s) do @logger.send(priority, msg) end end
ruby
{ "resource": "" }
q409
Breasal.LatLng.to_WGS84
train
def to_WGS84 if @type == :ie @a = 6377340.189 @b = 6356034.447 else @a = 6377563.396 @b = 6356256.909 end @eSquared = ((@a * @a) - (@b * @b)) / (@a * @a) @phi = deg_to_rad(@latitude) @lambda = deg_to_rad(@longitud...
ruby
{ "resource": "" }
q410
Krikri::Enrichments.TimespanSplit.populate_timespan
train
def populate_timespan(timespan) return timespan unless (timespan.begin.empty? || timespan.end.empty?) && !timespan.providedLabel.empty? parsed = parse_labels(timespan.providedLabel) return timespan if parsed.empty? parsed.each do |date| begin_date, end_date = span_from_date(date...
ruby
{ "resource": "" }
q411
Krikri::Enrichments.TimespanSplit.span_from_date
train
def span_from_date(date) return [nil, nil] if date.nil? if date.is_a?(Date) return [date, date] if date.precision == :day return [date, (date.succ - 1)] end [(date.respond_to?(:first) ? date.first : date.from), (date.respond_to?(:last) ? date.last : date.to)] end
ruby
{ "resource": "" }
q412
Krikri::Enrichments.TimespanSplit.reduce_to_largest_span
train
def reduce_to_largest_span(timespan) timespan.begin = timespan.begin.sort.first timespan.end = timespan.end.sort.last timespan end
ruby
{ "resource": "" }
q413
Krikri.Activity.run
train
def run if block_given? update_attribute(:end_time, nil) if ended? Krikri::Logger .log(:info, "Activity #{agent.constantize}-#{id} is running") set_start_time begin yield agent_instance, rdf_subject rescue => e Krikri::Logger.log(:error, "Error...
ruby
{ "resource": "" }
q414
Emailvision.Api.close_connection
train
def close_connection if connected? get.connect.close.call else return false end rescue Emailvision::Exception => e ensure invalidate_token! not connected? end
ruby
{ "resource": "" }
q415
Prowly.Interface.call
train
def call(command, params) @command = command request = Net::HTTP::Get.new(uri.request_uri + "?" + params) response = http.request(request) Response.new(response.body, response) end
ruby
{ "resource": "" }
q416
Krikri.SearchIndexDocument.aggregation
train
def aggregation agg = DPLA::MAP::Aggregation.new(id) return nil unless agg.exists? agg.get agg end
ruby
{ "resource": "" }
q417
RenderInheritable.ClassMethods.find_inheritable_template_folder
train
def find_inheritable_template_folder(view_context, name, partial, formats, param = nil) find_inheritable_template_folder_cached(view_context, name, partial, formats, param) do find_inheritable_artifact(param) do |folder| view_context.template_exists?(name, folder, partial) end en...
ruby
{ "resource": "" }
q418
RenderInheritable.ClassMethods.inheritance_lookup_path
train
def inheritance_lookup_path path = [self] until path.last == inheritable_root_controller path << path.last.superclass end path.collect(&:controller_path) end
ruby
{ "resource": "" }
q419
RenderInheritable.ClassMethods.find_inheritable_template_folder_cached
train
def find_inheritable_template_folder_cached(view_context, name, partial, formats, param = nil) prefix = inheritable_cache_get(formats, name, partial, param) return prefix if prefix prefix = yield if prefix template = view_context.find_template_without_lookup(name, prefix, p...
ruby
{ "resource": "" }
q420
RenderInheritable.ClassMethods.inheritable_cache
train
def inheritable_cache #:nodoc: # do not store keys on each access, only return default structure @inheritable_cache ||= Hash.new do |h1, k1| Hash.new do |h2, k2| Hash.new do |h3, k3| Hash.new end end end end
ruby
{ "resource": "" }
q421
RenderInheritable.ClassMethods.inheritable_cache_get
train
def inheritable_cache_get(formats, name, partial, param) prefixes = formats.collect { |format| inheritable_cache[format.to_sym][partial][name][param] } prefixes.compact! prefixes.empty? ? nil : prefixes.first end
ruby
{ "resource": "" }
q422
RenderInheritable.ClassMethods.inheritable_cache_set
train
def inheritable_cache_set(formats, name, partial, param, prefix) formats.each do |format| # assign hash default values to respective key inheritable_cache[format.to_sym] = hf = inheritable_cache[format.to_sym] hf[partial] = hp = hf[partial] hp[name] = hn = hp[name] # final...
ruby
{ "resource": "" }
q423
RenderInheritable.View.find_template_with_lookup
train
def find_template_with_lookup(name, prefix = nil, partial = false) if prefix == controller_path folder = controller.find_inheritable_template_folder(name, partial) prefix = folder if folder end find_template_without_lookup(name, prefix, partial) end
ruby
{ "resource": "" }
q424
MeterCat.Cache.add
train
def add(name, value, created_on) meter = fetch(name, nil) # If the name isn't cached, cache it and return return cache(name, value, created_on) unless meter # If the cached value is for a different day, flush it, cache the new value and return if meter.created_on != created_on fl...
ruby
{ "resource": "" }
q425
MeterCat.Cache.cache
train
def cache(name, value, created_on) meter = Meter.new(name: name, value: value, created_on: created_on, created_at: Time.now) store(name, meter) end
ruby
{ "resource": "" }
q426
Krikri.MappingDSL.add_child
train
def add_child(name, opts = {}, &block) delete_property(name) properties << ChildDeclaration.new(name, opts.delete(:class), opts, &block) end
ruby
{ "resource": "" }
q427
Krikri.MappingDSL.add_property
train
def add_property(name, value = nil, &block) delete_property(name) properties << PropertyDeclaration.new(name, value, &block) end
ruby
{ "resource": "" }
q428
Nesser.Packet.to_bytes
train
def to_bytes() packer = Packer.new() full_flags = ((@qr << 15) & 0x8000) | ((@opcode << 11) & 0x7800) | ((@flags << 7) & 0x0780) | ((@rcode << 0) & 0x000F) packer.pack('nnnnnn', @trn_id, # trn_id full_flags,...
ruby
{ "resource": "" }
q429
EspnRb.Headline.get_results
train
def get_results(resource, method) http = Net::HTTP.new("api.espn.com") request = Net::HTTP::Get.new("/#{EspnRb::API_VERSION}#{resource}#{method}?apikey=#{@api_key}") HeadlineResponse.new JSON.parse(http.request(request).body) end
ruby
{ "resource": "" }
q430
Krikri::Util.ExtendedDateParser.parse
train
def parse(date_str, allow_interval = false) str = preprocess(date_str.dup) date = parse_interval(str) if allow_interval date ||= parse_m_d_y(str) date ||= Date.edtf(str.gsub('.', '-')) date ||= partial_edtf(str) date ||= decade_hyphen(str) date ||= month_year(str) date ||...
ruby
{ "resource": "" }
q431
Krikri::Util.ExtendedDateParser.range_match
train
def range_match(str) str = str.gsub('to', '-').gsub('until', '-') regexp = %r{ ([a-zA-Z]{0,3}\s?[\d\-\/\.xu\?\~a-zA-Z]*,?\s? \d{3}[\d\-xs][s\d\-\.xu\?\~]*) \s*[-\.]+\s* ([a-zA-Z]{0,3}\s?[\d\-\/\.xu\?\~a-zA-Z]*,?\s? \d{3}[\d\-xs][s\d\-\.xu\?\~]*) }x regexp....
ruby
{ "resource": "" }
q432
Krikri::Util.ExtendedDateParser.preprocess
train
def preprocess(str) str.gsub!(/late/i, '') str.gsub!(/early/i, '') str.strip! str.gsub!(/\s+/, ' ') str.gsub!('0s', 'x') if str.match(/^[1-9]+0s$/) str.gsub!('-', 'x') if str.match(/^[1-9]+\-+$/) str end
ruby
{ "resource": "" }
q433
Krikri::Util.ExtendedDateParser.circa
train
def circa(str) run = str.gsub!(/.*c[irca\.]*/i, '') run ||= str.gsub!(/.*about/i, '') date = parse(str) if run return nil if date.nil? # The EDTF grammar does not support uncertainty on masked precision dates if date.respond_to? :uncertain! date.uncertain! elsif date....
ruby
{ "resource": "" }
q434
ShadowPuppet.Manifest.execute
train
def execute(force=false) return false if executed? && !force evaluate_recipes transaction = apply rescue Exception => e false else not transaction.any_failed? ensure @executed = true end
ruby
{ "resource": "" }
q435
ShadowPuppet.Manifest.execute!
train
def execute!(force=false) return false if executed? && !force evaluate_recipes transaction = apply rescue Exception => e raise e else not transaction.any_failed? ensure @executed = true end
ruby
{ "resource": "" }
q436
ShadowPuppet.Manifest.evaluate_recipes
train
def evaluate_recipes self.class.recipes.each do |meth, args| case arity = method(meth).arity when 1, -1 send(meth, args) else send(meth) end end end
ruby
{ "resource": "" }
q437
ShadowPuppet.Manifest.reference
train
def reference(type, title, params = {}) Puppet::Resource.new(type.name.to_s.capitalize, title.to_s) end
ruby
{ "resource": "" }
q438
ShadowPuppet.Manifest.add_resource
train
def add_resource(type, title, params = {}) catalog.add_resource(new_resource(type, title, params)) end
ruby
{ "resource": "" }
q439
Krikri.ReportsController.index
train
def index @current_provider = params[:provider] report = Krikri::ValidationReport.new report.provider_id = @current_provider @validation_reports = report.all if @current_provider @provider = Krikri::Provider.find(@current_provider) @qa_reports = Array(Krikri::QAReport.find...
ruby
{ "resource": "" }
q440
AlphaCard.Order.attributes_for_request
train
def attributes_for_request(*) attributes = filled_attributes.dup billing = attributes.delete(:billing) attributes.merge!(billing.attributes_for_request) if billing shipping = attributes.delete(:shipping) attributes.merge!(shipping.attributes_for_request) if shipping super(attribut...
ruby
{ "resource": "" }
q441
EasyRSA.Revoke.revoke!
train
def revoke!(cakey=nil, crl=nil, next_update=36000) if cakey.nil? fail EasyRSA::Revoke::MissingCARootKey, 'Please provide the root CA cert for the CRL' end # Get cert details if it's in a file unless cakey.is_a? OpenSSL::PKey::RSA if cakey.include?('BEGIN RSA PRIVATE KEY'...
ruby
{ "resource": "" }
q442
Dux.Enum.with_return_type
train
def with_return_type(value) if value.nil? && allow_nil? if allow_nil? nil else # :nocov: raise ArgumentError, "Cannot return `nil` without allow_nil: true" # :nocov: end elsif @return_type == :symbol value.to_sym elsif @return_typ...
ruby
{ "resource": "" }
q443
Dux.Enum.valid_fallback?
train
def valid_fallback?(fallback) return true if fallback.nil? && allow_nil? return true if include? fallback false end
ruby
{ "resource": "" }
q444
Dux.Enum.set_default
train
def set_default(fallback) if valid_fallback?(fallback) || fallback == NO_DEFAULT @default = fallback else raise InvalidFallback, "Cannot set #{fallback.inspect} as default", caller end end
ruby
{ "resource": "" }
q445
ActiveProfiling.GCStatistics.gc_statistics
train
def gc_statistics(*args) options = Rails.application.config.active_profiling.gc_statistics.merge(args.extract_options!) result, gc_report = gc_statistics_report(options) do yield end ActiveSupport::Notifications.instrument('gc_statistics.active_profiling', { :report => gc_repor...
ruby
{ "resource": "" }
q446
Zack.Server.process_request
train
def process_request(control, sym, args) instance = factory.call(control) instance.send(sym, *args) end
ruby
{ "resource": "" }
q447
Zack.Server.exception_handling
train
def exception_handling(exception_handler, control) begin yield rescue => exception # If we have an exception handler, it gets handed all the exceptions. # No exceptions stop the operation. if exception_handler exception_handler.call(exception, control) ...
ruby
{ "resource": "" }
q448
Krikri::LDP.RdfSource.save_with_provenance
train
def save_with_provenance(activity_uri) predicate = exists? ? REVISED_URI : GENERATED_URI self << RDF::Statement(self, predicate, activity_uri) save end
ruby
{ "resource": "" }
q449
Krikri.EntityConsumer.assign_generator_activity!
train
def assign_generator_activity!(opts) if opts.include?(:generator_uri) generator_uri = opts.delete(:generator_uri) @entity_source = @generator_activity = Krikri::Activity.from_uri(generator_uri) end end
ruby
{ "resource": "" }
q450
DeepClonable.InstanceMethods.deep_vars
train
def deep_vars instance_variables.select do |var| value = instance_variable_get(var) value.kind_of?(Array) or value.kind_of?(Hash) or value.kind_of?(DeepClonable::InstanceMethods) end end
ruby
{ "resource": "" }
q451
GoogleReaderApi.Api.post_request
train
def post_request(url,args) uri = URI.parse(url) req = Net::HTTP::Post.new(uri.path) req.set_form_data(args) request(uri,req) end
ruby
{ "resource": "" }
q452
Rubinius.Tuple.swap
train
def swap(a, b) temp = at(a) put a, at(b) put b, temp end
ruby
{ "resource": "" }
q453
Vnstat.Utils.system_call
train
def system_call(*args) result = SystemCall.call(*args) return result.success_result if result.success? return yield(result.error_result) if block_given? result.error_result end
ruby
{ "resource": "" }
q454
Splib.Monitor.signal
train
def signal synchronize do while(t = @threads.shift) if(t && t.alive? && t.stop?) t.wakeup break else next end end end end
ruby
{ "resource": "" }
q455
Splib.Monitor.broadcast
train
def broadcast synchronize do @threads.dup.each do |t| t.wakeup if t.alive? && t.stop? end end end
ruby
{ "resource": "" }
q456
Splib.Monitor.try_lock
train
def try_lock locked = false Thread.exclusive do clean unless(locked?(false)) do_lock locked = true else locked = owner?(Thread.current) end end locked end
ruby
{ "resource": "" }
q457
Splib.Monitor.clean
train
def clean @locks.delete_if{|t|!t.alive?} if(@lock_owner && !@lock_owner.alive?) @lock_owner = @locks.empty? ? nil : @locks.shift @lock_owner.wakeup if @lock_owner && !owner?(Thread.current) end end
ruby
{ "resource": "" }
q458
Splib.Monitor.do_unlock
train
def do_unlock unless(owner?(Thread.current)) raise ThreadError.new("Thread #{Thread.current} is not the current owner: #{@lock_owner}") end Thread.exclusive do @locks.delete_if{|t|!t.alive?} unless(@locks.empty?) old_owner = @lock_owner @lock_owner = @locks....
ruby
{ "resource": "" }
q459
Splib.Monitor.start_timer
train
def start_timer @timer = Thread.new do begin until(@stop) do cur = [] t = 0.0 Thread.exclusive do t = @timers.values.min cur = @timers.dup end t = 0.0 if !t.nil? && t < 0.0 a = 0.0 beg...
ruby
{ "resource": "" }
q460
AlphaCard.Resource.attributes_for_request
train
def attributes_for_request(attrs = filled_attributes) return attrs if self.class::ORIGIN_TRANSACTION_VARIABLES.empty? attrs.each_with_object({}) do |(attr, value), request_attrs| request_attrs[self.class::ORIGIN_TRANSACTION_VARIABLES.fetch(attr, attr)] = value end end
ruby
{ "resource": "" }
q461
AlphaCard.Resource.validate_required_attributes!
train
def validate_required_attributes! unless required_attributes? blank_attribute = required_attributes.detect { |attr| self[attr].nil? || self[attr].empty? } raise ValidationError, "#{blank_attribute} can't be blank" end end
ruby
{ "resource": "" }
q462
Elastics.UtilityMethods.dump_one
train
def dump_one(*vars) refresh_index(*vars) document = search_by_id({:params => {:_source => '*'}}, *vars) document.delete('_score') document end
ruby
{ "resource": "" }
q463
Elastics.UtilityMethods.post_bulk_collection
train
def post_bulk_collection(collection, options={}) raise ArgumentError, "Array expected as :collection, got #{collection.inspect}" \ unless collection.is_a?(Array) bulk_string = '' collection.each do |d| bulk_string << build_bulk_string(d, options) end post_bulk_string(:b...
ruby
{ "resource": "" }
q464
DictionaryRB.Dictionary.examples
train
def examples @doc ||= Nokogiri::HTML(open(PREFIX + CGI::escape(@word))) @example_results ||= @doc.css('.exsentences').map{ |x| x.text.strip }.reject(&:empty?).flatten @example_results #to prevent above computations on repeated call on object end
ruby
{ "resource": "" }
q465
DictionaryRB.Dictionary.similar_words
train
def similar_words @doc ||= Nokogiri::HTML(open(PREFIX + CGI::escape(@word))) @similar_words = @doc.css("#relatedwords .fla a").map(&:text).reject(&:empty?) @similar_words end
ruby
{ "resource": "" }
q466
Krikri.RandomSearchIndexDocumentBuilder.query_params
train
def query_params params = { :id => '*:*', :sort => "random_#{rand(9999)} desc", :rows => 1 } return params unless provider_id.present? provider = RDF::URI(Krikri::Provider.base_uri) / provider_id params[:fq] = "provider_id:\"#{provider}\"" params end
ruby
{ "resource": "" }
q467
Krikri.RecordsHelper.random_record_id
train
def random_record_id(provider_id) doc = Krikri::RandomSearchIndexDocumentBuilder.new do self.provider_id = provider_id end.document doc.present? ? local_name(doc.id) : nil end
ruby
{ "resource": "" }
q468
Sprockets.Pathname.find
train
def find(location, kind = :file) location = File.join(absolute_location, location) File.send("#{kind}?", location) ? Pathname.new(environment, location) : nil end
ruby
{ "resource": "" }
q469
Krikri.SearchResultsHelperBehavior.render_enriched_record
train
def render_enriched_record(document) agg = document.aggregation return error_msg('Aggregation not found.') unless agg.present? JSON.pretty_generate(agg.to_jsonld['@graph']) end
ruby
{ "resource": "" }
q470
Krikri.SearchResultsHelperBehavior.render_original_record
train
def render_original_record(document) agg = document.aggregation return error_msg('Aggregation not found.') unless agg.present? begin original_record = agg.original_record rescue StandardError => e logger.error e.message return error_msg(e.message) end return...
ruby
{ "resource": "" }
q471
CookieAlert.CookiesController.cookie_accepted
train
def cookie_accepted # Get the visitor's current page URL or, if nil?, default to the application root. Resue block needed for bots visitor_current_url = begin cookies.signed[CookieAlert.config.cookie_name.to_sym].split(CookieAlert.config.cookie_value_text_separator)[1] rescue main_ap...
ruby
{ "resource": "" }
q472
TerminalChess.Board.check?
train
def check?(color, proposed_manifest = @piece_locations, recurse_for_checkmate = false) enemy_attack_vectors = {} player_attack_vectors = {} king_loc = [] enemy_color = opposing_color(color) proposed_manifest.each do |piece, details| if details[:color] == enemy_color ...
ruby
{ "resource": "" }
q473
Cryptoprocessing.Account.transactions
train
def transactions(options = {}) agent.transactions(self['id'], options) do |data, resp| yield(data, resp) if block_given? end end
ruby
{ "resource": "" }
q474
Cryptoprocessing.Account.transactions_by_address
train
def transactions_by_address(address, options = {}) agent.transactions_by_address(self['id'], address, options) do |data, resp| yield(data, resp) if block_given? end end
ruby
{ "resource": "" }
q475
Vnstat.InterfaceCollection.[]
train
def [](id) interfaces_hash.fetch(id.to_s) do raise UnknownInterface.new(id.to_s), "Unknown interface: #{id}" end end
ruby
{ "resource": "" }
q476
EasyRSA.Certificate.gen_subject
train
def gen_subject subject_name = "/C=#{EasyRSA::Config.country}" subject_name += "/ST=#{EasyRSA::Config.state}" unless !EasyRSA::Config.state || EasyRSA::Config.state.empty? subject_name += "/L=#{EasyRSA::Config.city}" subject_name += "/O=#{EasyRSA::Config.company}" subject_name +=...
ruby
{ "resource": "" }
q477
Vnstat.Interface.nick=
train
def nick=(nick) success = Utils.call_executable_returning_status( '-i', id, '--nick', nick, '--update' ) unless success raise Error, "Unable to set nickname for interface (#{id}). " \ 'Please make sure the vnstat daemon is not running while ' \ '...
ruby
{ "resource": "" }
q478
WampRails.Client.open
train
def open # Create the background thread self.thread = Thread.new do EM.tick_loop do unless self.cmd_queue.empty? command = self.cmd_queue.pop self._execute_command(command) end end self.wamp.open end end
ruby
{ "resource": "" }
q479
WampRails.Client.add_procedure
train
def add_procedure(procedure, klass, options=nil) options ||= {} raise WampRails::Error.new('"add_procedure" must be called BEFORE "open"') if self.thread self.registrations << WampRails::Command::Register.new(procedure, klass, options, self) end
ruby
{ "resource": "" }
q480
WampRails.Client.add_subscription
train
def add_subscription(topic, klass, options=nil) options ||= {} raise WampRails::Error.new('"add_subscription" must be called BEFORE "open"') if self.thread self.subscriptions << WampRails::Command::Subscribe.new(topic, klass, options, self) end
ruby
{ "resource": "" }
q481
WampRails.Client.call
train
def call(procedure, args=nil, kwargs=nil, options={}, &callback) command = WampRails::Command::Call.new(procedure, args, kwargs, options, self) self._queue_command(command, callback) end
ruby
{ "resource": "" }
q482
WampRails.Client.publish
train
def publish(topic, args=nil, kwargs=nil, options={}, &callback) command = WampRails::Command::Publish.new(topic, args, kwargs, options, self) self._queue_command(command, callback) end
ruby
{ "resource": "" }
q483
WampRails.Client.register
train
def register(procedure, klass, options={}, &callback) command = WampRails::Command::Register.new(procedure, klass, options, self) self._queue_command(command, callback) end
ruby
{ "resource": "" }
q484
WampRails.Client.subscribe
train
def subscribe(topic, klass, options={}, &callback) command = WampRails::Command::Subscribe.new(topic, klass, options, self) self._queue_command(command, callback) end
ruby
{ "resource": "" }
q485
WampRails.Client._queue_command
train
def _queue_command(command, callback=nil) # If the current thread is the EM thread, execute the command. Else put it in the queue if self.thread == Thread.current self._execute_command(command) else self.cmd_queue.push(command) end # If the callback is defined, block unt...
ruby
{ "resource": "" }
q486
Elastics.LiveReindex.track_external_change
train
def track_external_change(app_id, action, document) return unless Conf.redis Conf.redis.rpush("#{KEYS[:changes]}-#{app_id}", MultiJson.encode([action, document])) end
ruby
{ "resource": "" }
q487
Appium.Lint.report
train
def report data return nil if data.nil? || data.empty? result = '' data.each do |file_name, analysis| rel_path = File.join('.', File.expand_path(file_name).sub(Dir.pwd, '')) result += "\n#{rel_path}\n" analysis.each do |line_number, warning| result += " #{line_number...
ruby
{ "resource": "" }
q488
Dux.Blankness.blankish?
train
def blankish?(value) case value when nil, false true when Dux[:nan?] true when String, Symbol value.empty? || value =~ WHITESPACE_ONLY when Dux[:blank?] value.blank? when Hash value.empty? when Array, Enumerable Dux.attempt(value,...
ruby
{ "resource": "" }
q489
Krikri.QAQueryClient.build_optional_patterns
train
def build_optional_patterns(predicates) return [[TYPE, predicates, VALUE]] unless predicates.is_a? Enumerable var1 = TYPE patterns = predicates.each_with_object([]) do |predicate, ps| var2 = (ps.count == predicates.size - 1) ? VALUE : "obj#{ps.count}".to_sym ps << [v...
ruby
{ "resource": "" }
q490
TerminalChess.Move.possible_moves
train
def possible_moves(p1, manifest, castling = false) return [] if manifest[p1][:type].nil? allowed = [] type = manifest[p1][:type] my_color = manifest[p1][:color] constants(manifest, my_color, type) return [] if unoccupied?(p1) if type == :king allowed += [mov...
ruby
{ "resource": "" }
q491
TerminalChess.Move.move_pawn
train
def move_pawn(p1) col = get_col_from_index(p1) valid = [] # Piece color defines direction of travel. Enemy presence defines # the validity of diagonal movements if Move.color == :red valid << (p1 - 8) if unoccupied?(p1 - 8) valid << (p1 - 7) if piece_color(p1 - 7) == Move....
ruby
{ "resource": "" }
q492
TerminalChess.Move.move_knight
train
def move_knight(p1) row = get_row_from_index(p1) col = get_col_from_index(p1) valid = [] valid_moves_no_friendly_fire = [] # Valid knight moves based on its board position valid << (p1 + 17) if row < 7 && col < 8 valid << (p1 + 15) if row < 7 && col > 1 valid << (p1 + 1...
ruby
{ "resource": "" }
q493
ActsAsScd.ClassMethods.find_by_identity
train
def find_by_identity(identity, at_date=nil) # (at_date.nil? ? current : at(at_date)).where(IDENTITY_COLUMN=>identity).first if at_date.nil? q = current else q = at(at_date) end q = q.where(IDENTITY_COLUMN=>identity) q.first end
ruby
{ "resource": "" }
q494
ActsAsScd.ClassMethods.create_identity
train
def create_identity(attributes, start=nil) start ||= START_OF_TIME create(attributes.merge(START_COLUMN=>start || START_OF_TIME)) end
ruby
{ "resource": "" }
q495
EasyRSA.CA.gen_issuer
train
def gen_issuer name = "/C=#{EasyRSA::Config.country}" name += "/ST=#{EasyRSA::Config.state}" unless !EasyRSA::Config.state || EasyRSA::Config.state.empty? name += "/L=#{EasyRSA::Config.city}" name += "/O=#{EasyRSA::Config.company}" name += "/OU=#{EasyRSA::Config.orgunit}" ...
ruby
{ "resource": "" }
q496
EasyRSA.CA.add_extensions
train
def add_extensions ef = OpenSSL::X509::ExtensionFactory.new ef.subject_certificate = @ca_cert ef.issuer_certificate = @ca_cert @ca_cert.add_extension ef.create_extension('subjectKeyIdentifier', 'hash') @ca_cert.add_extension ef.create_extension('basicConstraints', 'CA:TRUE', tru...
ruby
{ "resource": "" }
q497
SortingTableFor.TableBuilder.render_tbody
train
def render_tbody if @lines and @lines.size > 0 return Tools::html_safe(content_tag(:tbody, render_total_entries + Tools::html_safe(@lines.collect { |line| line.render_line }.join))) return Tools::html_safe(content_tag(:tr, content_tag(:td, I18n.t(:total_entries, :scope => :sorting_table_for, :valu...
ruby
{ "resource": "" }
q498
SortingTableFor.TableBuilder.render_total_entries
train
def render_total_entries if self.show_total_entries total_entries = @collection.total_entries rescue @collection.size header_total_cells = @header_line ? @header_line.total_cells : 0 max_cells = (@lines.first.total_cells > header_total_cells) ? @lines.first.total_cells : header_total_cells...
ruby
{ "resource": "" }
q499
Krikri.SearchIndex.bulk_update_from_activity
train
def bulk_update_from_activity(activity) all_aggs = entities_as_json_hashes(activity) agg_batches = bulk_update_batches(all_aggs) agg_batches.each do |batch| index_with_error_handling(activity) { bulk_add(batch) } end end
ruby
{ "resource": "" }