_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
30
4.3k
language
stringclasses
1 value
meta_information
dict
q9000
Redstruct.Factory.delete
train
def delete(options = {}) return each({ match: '*', count: 500, max_iterations: 1_000_000, batch_size: 500 }.merge(options))
ruby
{ "resource": "" }
q9001
Redstruct.Factory.script
train
def script(script, **options) return Redstruct::Script.new(script:
ruby
{ "resource": "" }
q9002
FocuspointRails.UploaderAdditions.crop_with_focuspoint
train
def crop_with_focuspoint(width = nil, height = nil) if self.respond_to? "resize_to_limit" begin x = model.focus_x || 0 y = -(model.focus_y || 0) manipulate! do |img| orig_w = img['width'] orig_h = img['height'] ratio = width.to_f / height...
ruby
{ "resource": "" }
q9003
Breeze.Veur.report
train
def report(title, columns, rows) table = capture_table([columns] + rows) title = "=== #{title} " title <<
ruby
{ "resource": "" }
q9004
Breeze.Veur.capture_table
train
def capture_table(table) return 'none' if table.size == 1 # the first row is for column titles $stdout = StringIO.new # start capturing the output print_table(table.map{ |row| row.map(&:to_s) })
ruby
{ "resource": "" }
q9005
AndFeathers.Archive.to_io
train
def to_io(package_type, traversal = :each) package_type.open do |package| package.add_directory(@initial_version) send(traversal) do |child| case child when File
ruby
{ "resource": "" }
q9006
Truty.Conversion.czech_html
train
def czech_html(input) coder = HTMLEntities.new encoded = coder.encode(input,
ruby
{ "resource": "" }
q9007
FreelingClient.Client.call
train
def call(text) output = [] file = Tempfile.new('foo', encoding: 'utf-8') begin file.write(text) file.close stdin, stdout, stderr = Open3.popen3(command(file.path)) Timeout::timeout(@timeout) { until (line =
ruby
{ "resource": "" }
q9008
Cathode.Version.action?
train
def action?(resource, action) resource = resource.to_sym action = action.to_sym return false unless resource?(resource)
ruby
{ "resource": "" }
q9009
MARC.MARC4J.marc4j_to_rubymarc
train
def marc4j_to_rubymarc(marc4j) rmarc = MARC::Record.new rmarc.leader = marc4j.getLeader.marshal marc4j.getControlFields.each do |marc4j_control| rmarc.append( MARC::ControlField.new(marc4j_control.getTag(), marc4j_control.getData ) ) end marc4j.getDataFields.each do |marc4j_data...
ruby
{ "resource": "" }
q9010
MARC.MARC4J.rubymarc_to_marc4j
train
def rubymarc_to_marc4j(rmarc) marc4j = @factory.newRecord(rmarc.leader) rmarc.each do |f| if f.is_a? MARC::ControlField new_field = @factory.newControlField(f.tag, f.value) else new_field = @factory.new_data_field(f.tag, f.indicator1.ord, f.indicator2.ord) f.eac...
ruby
{ "resource": "" }
q9011
MARC.MARC4J.require_marc4j_jar
train
def require_marc4j_jar(jardir) unless defined? JRUBY_VERSION raise LoadError.new, "MARC::MARC4J requires the use of JRuby", nil end if jardir Dir.glob("#{jardir}/*.jar") do |x| require x
ruby
{ "resource": "" }
q9012
Temppath.Generator.mkdir
train
def mkdir(option={}) mode = option[:mode] || 0700
ruby
{ "resource": "" }
q9013
Temppath.Generator.touch
train
def touch(option={}) mode = option[:mode] || 0600
ruby
{ "resource": "" }
q9014
VoterLove.Voter.up_vote
train
def up_vote(votable) is_votable?(votable) vote = get_vote(votable) if vote if vote.up_vote raise Exceptions::AlreadyVotedError.new(true) else vote.up_vote = true votable.down_votes -= 1
ruby
{ "resource": "" }
q9015
VoterLove.Voter.up_vote!
train
def up_vote!(votable) begin up_vote(votable) success = true rescue
ruby
{ "resource": "" }
q9016
VoterLove.Voter.down_vote!
train
def down_vote!(votable) begin down_vote(votable) success = true rescue
ruby
{ "resource": "" }
q9017
VoterLove.Voter.up_voted?
train
def up_voted?(votable) is_votable?(votable) vote = get_vote(votable) return false if vote.nil? return true
ruby
{ "resource": "" }
q9018
Spirit.Manifest.check_types
train
def check_types(key='root', expected=TYPES, actual=self, opts={}) bad_type(key, expected, actual, opts) unless actual.is_a? expected.class
ruby
{ "resource": "" }
q9019
Cellula.WolframCodeRule.next_generation_cell
train
def next_generation_cell(left, middle, right) case [left, middle, right] when [1,1,1] then @binary_string[0].to_i when [1,1,0] then @binary_string[1].to_i when [1,0,1] then @binary_string[2].to_i when [1,0,0] then @binary_string[3].to_i
ruby
{ "resource": "" }
q9020
JiraIssues.JiraIssueMapper.call
train
def call(issue) status = decode_status(issue) { key: issue.key, type: issue.issuetype.name, priority: issue.priority.name,
ruby
{ "resource": "" }
q9021
AndFeathers.Directory.path
train
def path if @parent ::File.join(@parent.path, name) else if name != '.'
ruby
{ "resource": "" }
q9022
AndFeathers.Directory.|
train
def |(other) if !other.is_a?(Directory) raise ArgumentError, "#{other} is not a Directory" end dup.tap do |directory| other.files.each do |file| directory.add_file(file.dup) end other.directories.each do |new_directory| existing_directory = @direct...
ruby
{ "resource": "" }
q9023
AndFeathers.Directory.each
train
def each(&block) files.each(&block) directories.each do |subdirectory|
ruby
{ "resource": "" }
q9024
Characterizable.BetterHash.slice
train
def slice(*keep) inject(Characterizable::BetterHash.new) do |memo, ary| if keep.include?(ary[0])
ruby
{ "resource": "" }
q9025
QueueToTheFuture.Job.method_missing
train
def method_missing(*args, &block) Thread.pass until defined?(@result) case @result when Exception def self.method_missing(*args, &block); raise @result; end else
ruby
{ "resource": "" }
q9026
EnumerateBy.MacroMethods.enumerate_by
train
def enumerate_by(attribute = :name, options = {}) options.reverse_merge!(:cache => true) options.assert_valid_keys(:cache) extend EnumerateBy::ClassMethods extend EnumerateBy::Bootstrapped include EnumerateBy::InstanceMethods # The attribute representing a record's enum...
ruby
{ "resource": "" }
q9027
EnumerateBy.ClassMethods.typecast_enumerator
train
def typecast_enumerator(enumerator) if enumerator.is_a?(Array) enumerator.flatten! enumerator.map! {|value| typecast_enumerator(value)} enumerator
ruby
{ "resource": "" }
q9028
Humpyard.Page.root_elements
train
def root_elements(yield_name = 'main') # my own elements ret = elements.where('container_id IS NULL and page_yield_name = ?', yield_name.to_s).order('position ASC') # sibling shared elements unless siblings.empty? ret += Humpyard::Element.where('container_id IS NULL and page_id in (?) an...
ruby
{ "resource": "" }
q9029
Humpyard.Page.child_pages
train
def child_pages options={} if content_data.is_humpyard_dynamic_page? content_data.child_pages else if options[:single_root] and is_root_page? Page.where(["parent_id = ?
ruby
{ "resource": "" }
q9030
Humpyard.Page.last_modified
train
def last_modified options = {} changed_at = [Time.zone.at(::File.new("#{Rails.root}").mtime), created_at, updated_at, modified_at] if(options[:include_pages])
ruby
{ "resource": "" }
q9031
Dragonfly.DropboxDataStore.url_for
train
def url_for(path, opts = {}) path = absolute(path)
ruby
{ "resource": "" }
q9032
BoardGameGrid.Square.attribute_match?
train
def attribute_match?(attribute, value) hash_obj_matcher = lambda do |obj, k, v| value = obj.send(k) if !value.nil? && v.is_a?(Hash)
ruby
{ "resource": "" }
q9033
Dio.ModuleBase.included
train
def included(base) my_injector = injector injector_holder = Module.new do define_method :__dio_injector__ do
ruby
{ "resource": "" }
q9034
Smsified.OneAPI.send_sms
train
def send_sms(options) raise ArgumentError, 'an options Hash is required' if !options.instance_of?(Hash) raise ArgumentError, ':sender_address is required' if options[:sender_address].nil? && @sender_address.nil? raise ArgumentError, ':address is required' if options[:address].nil? raise Argument...
ruby
{ "resource": "" }
q9035
Smsified.OneAPI.method_missing
train
def method_missing(method, *args) if method.to_s.match /subscription/ if args.size == 2 @subscriptions.send method, args[0], args[1] else @subscriptions.send method, args[0] end else if method == :delivery_status || method == :retrieve_sms || method
ruby
{ "resource": "" }
q9036
Aker::Authorities.AutomaticAccess.amplify!
train
def amplify!(user) user.portals << @portal unless user.portals.include?(@portal)
ruby
{ "resource": "" }
q9037
SimpleMetarParser.Metar.decode
train
def decode self.raw_splits.each do |split| self.modules.each do |m|
ruby
{ "resource": "" }
q9038
Domain.Factory.sbyc
train
def sbyc(super_domain = Object, &pred) Class.new(super_domain){
ruby
{ "resource": "" }
q9039
Wireless.SynchronizedStore.get_or_create
train
def get_or_create(key) @lock.synchronize do if @store.include?(key) @store[key] elsif block_given? @store[key] = yield else # XXX don't expose the receiver as this class is an internal # implementation detail
ruby
{ "resource": "" }
q9040
UnlockGateway.Controller.transition_state
train
def transition_state(state) authorize @contribution @initiative = @contribution.initiative @user = @contribution.user state = state.to_sym transition = @contribution.transition_by_state(state) initial_state = @contribution.state_name resource_name = @contribution.class.model_na...
ruby
{ "resource": "" }
q9041
Machined.CLI.rack_options
train
def rack_options # :nodoc: symbolized_options(:port, :host, :server, :daemonize, :pid).tap do |rack_options| rack_options[:environment] = environment rack_options[:Port] = rack_options.delete :port
ruby
{ "resource": "" }
q9042
Machined.CLI.symbolized_options
train
def symbolized_options(*keys) # :nodoc: @symbolized_options ||= begin opts = {}.merge(options) opts.merge! saved_options if saved_options?
ruby
{ "resource": "" }
q9043
LookUpTable.ClassMethods.look_up_table
train
def look_up_table(lut_key, options = {}, &block) options = { :batch_size => 10000, :prefix => "#{self.name}/", :read_on_init => false,
ruby
{ "resource": "" }
q9044
LookUpTable.ClassMethods.lut
train
def lut(lut_key = nil, lut_item_key = nil) @lut ||= {} if lut_key.nil? hash = {} self.lut_keys.each { |key| hash[key] = self.lut(key) } #
ruby
{ "resource": "" }
q9045
LookUpTable.ClassMethods.lut_reload
train
def lut_reload(lut_key = nil) if lut_key lut_reset(lut_key) lut(lut_key) else
ruby
{ "resource": "" }
q9046
LookUpTable.ClassMethods.lut_read
train
def lut_read(name) return nil unless options = lut_options(name)# HACK if options[:use_cache] lut_read_from_cache(name)
ruby
{ "resource": "" }
q9047
ActiveHarmony.SynchronizerConfiguration.synchronizable_for_types
train
def synchronizable_for_types(types) @synchronizable_fields.select do |field_description|
ruby
{ "resource": "" }
q9048
Measurement.Base.to_s
train
def to_s(unit = nil, precision = 0) if unit.to_s =~ /_and_/ units = unit.to_s.split('_and_').map do |unit| self.class.fetch_scale(unit)
ruby
{ "resource": "" }
q9049
MatchyMatchy.MatchList.<<
train
def <<(match) if include?(match) match.reject! else @matches << match @matches.sort!
ruby
{ "resource": "" }
q9050
MethodInfo.AncestorMethodStructure.method_owner
train
def method_owner(method_symbol) # Under normal circumstances just calling @object.method(method_symbol) would work, # but this will go wrong if the
ruby
{ "resource": "" }
q9051
PhpFpmDocker.Launcher.parse_config
train
def parse_config # rubocop:disable MethodLength # Test for file usability fail "Config file '#{@config_path}' not found"\ unless @config_path.file? fail "Config file '#{@config_path}' not readable"\ unless @config_path.readable? @ini_file = IniFile.load(@config_path) begin ...
ruby
{ "resource": "" }
q9052
PhpFpmDocker.Launcher.pools_config_content_from_file
train
def pools_config_content_from_file(config_path) ini_file = IniFile.load(config_path) ret_val = [] ini_file.each_section do |section|
ruby
{ "resource": "" }
q9053
PhpFpmDocker.Launcher.pools_config_contents
train
def pools_config_contents ret_val = [] # Loop over Dir[@pools_directory.join('*.conf').to_s].each do |config_path|
ruby
{ "resource": "" }
q9054
PhpFpmDocker.Launcher.pools_from_config
train
def pools_from_config configs = {} pools_config_contents.each do |section| # Hash section name and content d = Digest::SHA2.new(256) hash = d.reset.update(section[0]).update(section[1].to_s).to_s
ruby
{ "resource": "" }
q9055
Tkar.Primitives.polybox
train
def polybox args, key_args dx, dy = args # return a proc to make the info needed to instantiate/update proc do |tkaroid, cos_r, sin_r| x = tkaroid.x y = tkaroid.y params = tkaroid.params ex = dx[params] rescue dx ey = dy[params] rescue dy points...
ruby
{ "resource": "" }
q9056
Redlander.ModelProxy.delete_all
train
def delete_all(pattern = {}) result = true each(pattern) { |st|
ruby
{ "resource": "" }
q9057
Redlander.ModelProxy.find
train
def find(scope, pattern = {}) case scope when :first each(pattern).first
ruby
{ "resource": "" }
q9058
CodeCache.Repo.location_in_cache
train
def location_in_cache( revision = nil ) begin elements = [cache, repo_type, split_url, revision].flatten.compact.collect { |i| i.to_s } File.join( elements )
ruby
{ "resource": "" }
q9059
Mango.ContentPage.method_missing
train
def method_missing(method_name, *args, &block) key
ruby
{ "resource": "" }
q9060
Kawaii.ContentManager.load_image
train
def load_image(path, tileable = false) if !@images[path] @images[path] = Gosu::Image.new(@window,
ruby
{ "resource": "" }
q9061
MustacheRender.Mustache.partial
train
def partial(name) name = self.class.generate_template_name name, config.file_template_extension # return self.read_template_from_media name, media @_cached_partials ||= {}
ruby
{ "resource": "" }
q9062
HasPrice.HasPrice.has_price
train
def has_price(options = {}, &block) attribute = options[:attribute] || :price free = !block_given? && options[:free] define_method attribute.to_sym do
ruby
{ "resource": "" }
q9063
Octo.Scheduler.schedule_counters
train
def schedule_counters counter_classes = [ Octo::ProductHit, Octo::CategoryHit, Octo::TagHit, Octo::ApiHit, Octo::NewsfeedHit ] counter_classes.each do |clazz| clazz.send(:get_typecounters).each do |counter| name = [clazz, counter].join('::') ...
ruby
{ "resource": "" }
q9064
Hosties.HasAttributes.have_attributes
train
def have_attributes(attr, *more) sum = (more << attr) sum.each do |name| raise ArgumentError, "Reserved attribute
ruby
{ "resource": "" }
q9065
Hosties.HasAttributes.where
train
def where(name) # Must define the attributes before constraining them raise ArgumentError, "Unknown attribute: #{name}" unless
ruby
{ "resource": "" }
q9066
Hosties.HasAttributes.valid?
train
def valid?(name, value) if @constraints.include? name then
ruby
{ "resource": "" }
q9067
XBeeRuby.XBee.open
train
def open @serial ||= SerialPort.new @port, @rate @serial_input = Enumerator.new { |y| loop do
ruby
{ "resource": "" }
q9068
UseCaseValidations.ClassMethods.inherited
train
def inherited(base) dup = _validators.dup
ruby
{ "resource": "" }
q9069
MaRuKu.Section.numerate
train
def numerate(a=[]) self.section_number = a section_children.each_with_index do |c,i| c.numerate(a.clone.push(i+1)) end
ruby
{ "resource": "" }
q9070
ActsAsFeatured.ClassMethods.acts_as_featured
train
def acts_as_featured(attribute, options = {}) cattr_accessor :featured_attribute cattr_accessor :featured_attribute_scope self.featured_attribute = attribute self.featured_attribute_scope = options[:scope] || false if scope_name = options[:create_scope] scope_name = attribute if ...
ruby
{ "resource": "" }
q9071
TodoLint.Judge.make_charge
train
def make_charge if !todo.annotated? "Missing due date annotation" elsif todo.due_date.overdue? &&
ruby
{ "resource": "" }
q9072
XivelyConnector.Datastream.<<
train
def <<(measurement) # Make sure the value provided is a datapoint datapoint = cast_to_datapoint(measurement) # If only_save_changes is true, ignore datapoints whose value is the same as the current value if only_save_changes and BigDecimal.new(datapoint.value) == BigDecimal.new(current_value) ...
ruby
{ "resource": "" }
q9073
XivelyConnector.Datastream.cast_to_datapoint
train
def cast_to_datapoint(measurement, at=Time.now()) @logger.debug "cast_to_datapoint(#{measurement.inspect})" if measurement.is_a?(Xively::Datapoint) return measurement elsif measurement.is_a?(Hash)
ruby
{ "resource": "" }
q9074
XivelyConnector.Datastream.save_datapoints
train
def save_datapoints @logger.debug "Saving #{datapoints.size} datapoints to the #{id} datastream" response = XivelyConnector.connection.post("/v2/feeds/#{device.id}/datastreams/#{id}/datapoints", :body => {:datapoints => datapoints}.to_json)
ruby
{ "resource": "" }
q9075
Coach4rb.Client.put
train
def put(url, payload, options={}, &block) http_options = options.merge(@basic_options) if block_given?
ruby
{ "resource": "" }
q9076
Coach4rb.Client.delete
train
def delete(url, options={}, &block) http_options = options.merge(@basic_options) if block_given?
ruby
{ "resource": "" }
q9077
ObjectAttorney.ClassMethods.inherited
train
def inherited(base) base.allegations = allegations.clone
ruby
{ "resource": "" }
q9078
Rexport.ExportMethods.to_s
train
def to_s String.new.tap do |result| result << header * '|' << "\n" records.each do |record|
ruby
{ "resource": "" }
q9079
Rexport.ExportMethods.to_csv
train
def to_csv(objects = nil) seed_records(objects) unless objects.nil? CSV.generate do |csv| csv << header
ruby
{ "resource": "" }
q9080
Rexport.ExportMethods.get_klass_from_path
train
def get_klass_from_path(path, klass = export_model) return klass unless (association_name = path.shift) get_klass_from_path(path,
ruby
{ "resource": "" }
q9081
Diffable.InstanceMethods.diff
train
def diff(other) check_class_compatibility(self, other) self_attribs = self.get_attributes(self.class.excluded_fields) other_attribs = other.get_attributes(other.class.excluded_fields) change = compare_objects(self_attribs, other_attribs, self, other) #the last bit - no...
ruby
{ "resource": "" }
q9082
Diffable.InstanceMethods.get_attributes
train
def get_attributes(excluded) attribs = attributes.dup attribs.delete_if { |key, value|
ruby
{ "resource": "" }
q9083
Diffable.InstanceMethods.reflected_names
train
def reflected_names(obj) classes = obj.reflections class_names = [] classes.each do |key, cl| if eval(cl.class_name).respond_to?("diffable") \
ruby
{ "resource": "" }
q9084
PayuLatam.SubscriptionService.plan
train
def plan # si el usuario no tiene plan_id en su modelo, se le asigna el plan_id seleccionado en el formulario # recordar que ese plan_id llega en los params del contexto y por tanto tenemos acceso a el # como variable de clase @plan_id if @current_user.plan_id.nil? if @plan_id.nil? ...
ruby
{ "resource": "" }
q9085
PayuLatam.SubscriptionService.create_card
train
def create_card raise StandardError, 'Cliente null' if @client.nil? # la instancia de card recibe como parametro el @client al que se le va asociar la tarjeta card = PayuLatam::Card.new(@client) # hay un metodo card_params que genera el objeto a enviar con los datos correctos # se asignan ...
ruby
{ "resource": "" }
q9086
PayuLatam.SubscriptionService.find_card
train
def find_card @client.remove_cards card = PayuLatam::Card.new(@client) # info de payu card.load(
ruby
{ "resource": "" }
q9087
DataMapper.Paginator.limit
train
def limit options = {} # Remove this key if we come from limit_page method. page = options.delete :page query = options.dup collection = new_collection scoped_query( options = { :limit => options[:limit], :offset => options[:offset], :order => [options[:order]]
ruby
{ "resource": "" }
q9088
DataMapper.Paginator.limit_page
train
def limit_page page = nil, options = {} if page.is_a?( Hash ) options = page else options[:page] = page.to_i end options[:page] = options[:page].to_i > 0 ? options[:page] : DataMapper::Paginator.default[:page] options[:limit] = options[:limit].to_i || DataMapper::Paginator...
ruby
{ "resource": "" }
q9089
DataMapper.Paginator.calculate_total_records
train
def calculate_total_records query # Remove those keys from the query query.delete :page query.delete :limit query.delete :offset
ruby
{ "resource": "" }
q9090
NetworkExecutive.ScheduledProgram.+
train
def +( other_program ) raise ArgumentError if @program.class != other_program.class additional_duration = other_program.duration + 1 program.duration += additional_duration
ruby
{ "resource": "" }
q9091
Kharon.Processor.before_all
train
def before_all(key, options) required(key) if (options.has_key?(:required) and options[:required] == true) if options.has_key?(:dependencies)
ruby
{ "resource": "" }
q9092
Kharon.Processor.store
train
def store(key, process, options = {}) unless (options.has_key?(:extract) and options[:extract] == false) if validator.datas.has_key?(key) value = ((options.has_key?(:cast) and options[:cast] == false) ? validator.datas[key] : process.call(validator.datas[key])) if(options.has_key?(:in)...
ruby
{ "resource": "" }
q9093
Kharon.Processor.raise_type_error
train
def raise_type_error(key, type) raise_error(type:
ruby
{ "resource": "" }
q9094
Kharon.Processor.required
train
def required(key) raise_error(type: "required",
ruby
{ "resource": "" }
q9095
Kharon.Processor.dependency
train
def dependency(key, dependency) raise_error(type: "dependency", key: "key", needed: dependency)
ruby
{ "resource": "" }
q9096
Kharon.Processor.is_typed?
train
def is_typed?(key, type) return (!validator.datas.has_key?(key)
ruby
{ "resource": "" }
q9097
Kharon.Processor.in_array?
train
def in_array?(key, values) raise_error(type: "array.in", key: key, supposed: values, value: validator.datas[key]) unless
ruby
{ "resource": "" }
q9098
Kharon.Processor.equals_to?
train
def equals_to?(key, value) raise_error(type: "equals", key: key, supposed: value, found:
ruby
{ "resource": "" }
q9099
Kharon.Processor.match?
train
def match?(key, regex) return (!validator.datas.has_key?(key)
ruby
{ "resource": "" }