_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
30
4.3k
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.parent_id.to_s] groups[page.parent_id.to_s] << page else groups[page.parent_id.to_s] = [page] end groups end # generate must be in scope for the iterate proc declaration, but must be defined below iterate, so that iterate is recursively in scope generate = nil iterate = Proc.new do |parent_id| #very important to delete the group from the collection, or it is possible users can create looping relationships (page_groups.delete(parent_id.to_s) || {}).inject(''.html_safe) do |buffer, page|
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['pagination']['next_uri'] != nil params[:starting_after] = resp.body['data'].last['id']
ruby
{ "resource": "" }
q402
Cryptoprocessing.Connection.put
train
def put(path, params) headers = {} request('PUT', path, params.to_json, headers) do |resp|
ruby
{ "resource": "" }
q403
Cryptoprocessing.Connection.post
train
def post(path, params) headers = {} request('POST', path, params.to_json, headers) do |resp|
ruby
{ "resource": "" }
q404
Cryptoprocessing.Connection.delete
train
def delete(path, params) headers = {} request('DELETE', path, nil, headers) do |resp|
ruby
{ "resource": "" }
q405
Pollster.Api.charts_slug_get
train
def charts_slug_get(slug, opts = {}) data, _status_code, _headers =
ruby
{ "resource": "" }
q406
Pollster.Api.polls_slug_get
train
def polls_slug_get(slug, opts = {}) data, _status_code, _headers =
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(response.body) result = doc.css('span.uccResultAmount').text
ruby
{ "resource": "" }
q408
Krikri.Logger.log
train
def log(priority, msg) @logger.tagged(Time.now.to_s, Process.pid, to_s) do
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(@longitude) @v = @a / (Math.sqrt(1 - @eSquared * sin_pow_2(@phi))) @H = 0 @x = (@v + @H) * Math.cos(@phi) * Math.cos(@lambda) @y = (@v + @H) * Math.cos(@phi) * Math.sin(@lambda) @z = ((1 - @eSquared) * @v + @H) * Math.sin(@phi) @tx = 446.448 @ty = -124.157 @tz = 542.060 @s = -0.0000204894 @rx = deg_to_rad( 0.00004172222) @ry = deg_to_rad( 0.00006861111) @rz = deg_to_rad( 0.00023391666) @xB = @tx + (@x * (1 + @s)) + (-@rx * @y) + (@ry * @z) @yB = @ty + (@rz * @x) + (@y * (1 + @s)) + (-@rx * @z) @zB = @tz + (-@ry * @x) + (@rx * @y) + (@z
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)]
ruby
{ "resource": "" }
q412
Krikri::Enrichments.TimespanSplit.reduce_to_largest_span
train
def reduce_to_largest_span(timespan) timespan.begin = timespan.begin.sort.first
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
ruby
{ "resource": "" }
q414
Emailvision.Api.close_connection
train
def close_connection if connected? get.connect.close.call else return false end rescue
ruby
{ "resource": "" }
q415
Prowly.Interface.call
train
def call(command, params) @command = command request = Net::HTTP::Get.new(uri.request_uri + "?" + params)
ruby
{ "resource": "" }
q416
Krikri.SearchIndexDocument.aggregation
train
def aggregation agg = DPLA::MAP::Aggregation.new(id) return nil unless
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,
ruby
{ "resource": "" }
q418
RenderInheritable.ClassMethods.inheritance_lookup_path
train
def inheritance_lookup_path path = [self] until path.last == inheritable_root_controller path
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
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|
ruby
{ "resource": "" }
q421
RenderInheritable.ClassMethods.inheritable_cache_get
train
def inheritable_cache_get(formats, name, partial, param) prefixes = formats.collect { |format|
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]
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)
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 flush(name)
ruby
{ "resource": "" }
q425
MeterCat.Cache.cache
train
def cache(name, value, created_on) meter = Meter.new(name: name, value: value, created_on: created_on,
ruby
{ "resource": "" }
q426
Krikri.MappingDSL.add_child
train
def add_child(name, opts = {}, &block) delete_property(name)
ruby
{ "resource": "" }
q427
Krikri.MappingDSL.add_property
train
def add_property(name, value = nil, &block) delete_property(name)
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, # qr, opcode, flags, rcode @questions.length(), # qdcount @answers.length(), # ancount 0,
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_ke
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 ||= decade_s(str) date ||= hyphenated_partial_range(str)
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*
ruby
{ "resource": "" }
q432
Krikri::Util.ExtendedDateParser.preprocess
train
def preprocess(str) str.gsub!(/late/i, '') str.gsub!(/early/i, '') str.strip! str.gsub!(/\s+/, ' ')
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.is_a? EDTF::Interval # Interval uncertainty is scoped to the begin and
ruby
{ "resource": "" }
q434
ShadowPuppet.Manifest.execute
train
def execute(force=false) return false if executed? && !force evaluate_recipes transaction = apply rescue Exception => e false
ruby
{ "resource": "" }
q435
ShadowPuppet.Manifest.execute!
train
def execute!(force=false) return false if executed? && !force evaluate_recipes transaction = apply rescue Exception => e raise
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
ruby
{ "resource": "" }
q437
ShadowPuppet.Manifest.reference
train
def reference(type, title, params = {})
ruby
{ "resource": "" }
q438
ShadowPuppet.Manifest.add_resource
train
def add_resource(type, title, params = {})
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
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
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') cakey = OpenSSL::PKey::RSA.new cakey else begin cakey = OpenSSL::PKey::RSA.new File.read cakey rescue OpenSSL::PKey::RSAError => e fail EasyRSA::Revoke::InvalidCARootPrivateKey, 'This is not a valid Private key file.' end end end # This is not a private key unless cakey.private? fail EasyRSA::Revoke::InvalidCARootPrivateKey, 'This is not a valid Private key file.' end # Create or load the CRL unless crl.nil? begin @crl = OpenSSL::X509::CRL.new crl rescue fail
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
ruby
{ "resource": "" }
q443
Dux.Enum.valid_fallback?
train
def valid_fallback?(fallback) return true if fallback.nil? && allow_nil? return
ruby
{ "resource": "" }
q444
Dux.Enum.set_default
train
def set_default(fallback) if valid_fallback?(fallback) || fallback == NO_DEFAULT @default = fallback else
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
ruby
{ "resource": "" }
q446
Zack.Server.process_request
train
def process_request(control, sym, args) instance
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
ruby
{ "resource": "" }
q448
Krikri::LDP.RdfSource.save_with_provenance
train
def save_with_provenance(activity_uri) predicate = exists? ? REVISED_URI : GENERATED_URI self
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 =
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)
ruby
{ "resource": "" }
q451
GoogleReaderApi.Api.post_request
train
def post_request(url,args) uri = URI.parse(url) req
ruby
{ "resource": "" }
q452
Rubinius.Tuple.swap
train
def swap(a, b) temp = at(a) put a, at(b)
ruby
{ "resource": "" }
q453
Vnstat.Utils.system_call
train
def system_call(*args) result = SystemCall.call(*args) return result.success_result if result.success? return
ruby
{ "resource": "" }
q454
Splib.Monitor.signal
train
def signal synchronize do while(t = @threads.shift) if(t && t.alive? && t.stop?) t.wakeup break
ruby
{ "resource": "" }
q455
Splib.Monitor.broadcast
train
def broadcast synchronize do @threads.dup.each do |t|
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
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
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
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 begin a = Splib.sleep(t) rescue Wakeup # do nothing of importance ensure next if t.nil? Thread.exclusive do cur.each_pair do |thread, value| value -= a if(value <= 0.0)
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|
ruby
{ "resource": "" }
q461
AlphaCard.Resource.validate_required_attributes!
train
def validate_required_attributes! unless required_attributes? blank_attribute = required_attributes.detect {
ruby
{ "resource": "" }
q462
Elastics.UtilityMethods.dump_one
train
def dump_one(*vars) refresh_index(*vars) document = search_by_id({:params
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
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
ruby
{ "resource": "" }
q465
DictionaryRB.Dictionary.similar_words
train
def similar_words @doc ||= Nokogiri::HTML(open(PREFIX + CGI::escape(@word))) @similar_words = @doc.css("#relatedwords
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?
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
ruby
{ "resource": "" }
q468
Sprockets.Pathname.find
train
def find(location, kind = :file) location = File.join(absolute_location,
ruby
{ "resource": "" }
q469
Krikri.SearchResultsHelperBehavior.render_enriched_record
train
def render_enriched_record(document) agg = document.aggregation return error_msg('Aggregation not found.') unless
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)
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_app.root_path end # Set the Cookie value to 'accepted' if CookieAlert.config.cookie_type == 'permanent' # Set a permanent cookie cookies.permanent.signed[CookieAlert.config.cookie_name.to_sym] = 'accepted' elsif CookieAlert.config.cookie_type == 'fixed_duration' # Set a fixed duration cookie cookies.permanent.signed[CookieAlert.config.cookie_name.to_sym] = { value: 'accepted', expires: CookieAlert.config.num_days_until_cookie_expires.days.from_now } else # Set a session cookie
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 enemy_attack_vectors[piece] = possible_moves(piece, proposed_manifest) elsif details[:color] == color begin player_attack_vectors[piece] = possible_moves(piece, proposed_manifest) rescue # TODO: Fix possible_moves() so it doesn't throw exceptions # This happens because it is searching board for where pieces # will be, as as a result some pieces are nil end end king_loc = piece if details[:color] == color && details[:type] == :king
ruby
{ "resource": "" }
q473
Cryptoprocessing.Account.transactions
train
def transactions(options = {}) agent.transactions(self['id'], options) do |data, resp|
ruby
{ "resource": "" }
q474
Cryptoprocessing.Account.transactions_by_address
train
def transactions_by_address(address, options = {}) agent.transactions_by_address(self['id'],
ruby
{ "resource": "" }
q475
Vnstat.InterfaceCollection.[]
train
def [](id) interfaces_hash.fetch(id.to_s) do raise UnknownInterface.new(id.to_s),
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}"
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
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
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
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
ruby
{ "resource": "" }
q481
WampRails.Client.call
train
def call(procedure, args=nil, kwargs=nil, options={}, &callback) command =
ruby
{ "resource": "" }
q482
WampRails.Client.publish
train
def publish(topic, args=nil, kwargs=nil, options={}, &callback) command = WampRails::Command::Publish.new(topic, args, kwargs,
ruby
{ "resource": "" }
q483
WampRails.Client.register
train
def register(procedure, klass, options={}, &callback) command = WampRails::Command::Register.new(procedure, klass, options,
ruby
{ "resource": "" }
q484
WampRails.Client.subscribe
train
def subscribe(topic, klass, options={}, &callback) command = WampRails::Command::Subscribe.new(topic, klass, options,
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,
ruby
{ "resource": "" }
q486
Elastics.LiveReindex.track_external_change
train
def track_external_change(app_id, action, document) return unless Conf.redis
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, ''))
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?
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 =
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 += [move_lateral(p1, 1)].flatten allowed += [move_diagonal(p1, 1)].flatten
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.enemy_color && col < 8 valid << (p1 - 9) if piece_color(p1 - 9) == Move.enemy_color && col > 1 # Only if the pieces is unmoved, can it move forward two rows valid << (p1 - 16) if !Move.pieces[p1][:moved] && unoccupied?(p1 - 8) && unoccupied?(p1 - 16) elsif Move.color == :black valid <<
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 + 10) if row < 8 && col < 7 valid << (p1 + 6) if row < 8 && col > 2 valid << (p1 - 6) if row > 1 && col < 7 valid << (p1 - 10) if row > 1 && col > 2 valid << (p1 - 15) if row > 2 && col < 8
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 =
ruby
{ "resource": "" }
q494
ActsAsScd.ClassMethods.create_identity
train
def create_identity(attributes, start=nil) start ||= START_OF_TIME
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}" name += "/CN=#{EasyRSA::Config.server}" name += "/name=#{EasyRSA::Config.name}" unless !EasyRSA::Config.name || EasyRSA::Config.name.empty? name +=
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')
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)))
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 =
ruby
{ "resource": "" }