_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q20800
Hpe3parSdk.Client.get_ip_ports
train
def get_ip_ports(state = nil) begin @port.get_ip_ports(state) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
{ "resource": "" }
q20801
Hpe3parSdk.Client.get_cpgs
train
def get_cpgs begin @cpg.get_cpgs rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
{ "resource": "" }
q20802
Hpe3parSdk.Client.get_cpg
train
def get_cpg(name) begin @cpg.get_cpg(name) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
{ "resource": "" }
q20803
Hpe3parSdk.Client.create_cpg
train
def create_cpg(name, optional = nil) begin @cpg.create_cpg(name, optional) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
{ "resource": "" }
q20804
Hpe3parSdk.Client.modify_cpg
train
def modify_cpg(name, cpg_mods) begin @cpg.modify_cpg(name, cpg_mods) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
{ "resource": "" }
q20805
Hpe3parSdk.Client.get_cpg_available_space
train
def get_cpg_available_space(name) begin @cpg.get_cpg_available_space(name) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
{ "resource": "" }
q20806
Hpe3parSdk.Client.delete_cpg
train
def delete_cpg(name) begin @cpg.delete_cpg(name) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
{ "resource": "" }
q20807
Hpe3parSdk.Client.get_online_physical_copy_status
train
def get_online_physical_copy_status(name) begin @volume.get_online_physical_copy_status(name) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
{ "resource": "" }
q20808
Hpe3parSdk.Client.stop_offline_physical_copy
train
def stop_offline_physical_copy(name) begin @volume.stop_offline_physical_copy(name) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
{ "resource": "" }
q20809
Hpe3parSdk.Client.stop_online_physical_copy
train
def stop_online_physical_copy(name) begin @volume.stop_online_physical_copy(name) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
{ "resource": "" }
q20810
Hpe3parSdk.Client.resync_physical_copy
train
def resync_physical_copy(name) begin @volume.resync_physical_copy(name) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
{ "resource": "" }
q20811
Hpe3parSdk.Client.wait_for_task_to_end
train
def wait_for_task_to_end(task_id, poll_rate_secs = 15) begin @task.wait_for_task_to_end(task_id, poll_rate_secs) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
{ "resource": "" }
q20812
Hpe3parSdk.Client.cancel_task
train
def cancel_task(task_id) begin @task.cancel_task(task_id) rescue => ex Util.log_exception(ex, caller_locations(1, 1)[0].label) raise ex end end
ruby
{ "resource": "" }
q20813
Hpe3parSdk.Client.logout
train
def logout unless @log_file_path.nil? if Hpe3parSdk.logger != nil Hpe3parSdk.logger.close Hpe3parSdk.logger = nil end end begin @http.unauthenticate rescue Hpe3parSdk::HPE3PARException => ex #Do nothing end end
ruby
{ "resource": "" }
q20814
HealthMonitor.BuiltInChecks.ey_agent_check
train
def ey_agent_check results = { :description => 'Run ey-agent to monitor haproxy and monitor' } agent_results = JSON.load( `sudo ey-agent` ) results.update( :message => agent_results.inspect, :status => agent_results && agent_results.any?{|k,v| v == 'down' } ) rescue => e return results.update( :status => :failure, :exception => e ) end
ruby
{ "resource": "" }
q20815
HealthMonitor.HealthMonitoring.monitor_health
train
def monitor_health find_features @results = @features.inject({}) do |results, feature_name| results[ feature_name ] = monitor_health_of( feature_name ) results end healthy? ? on_healthy : on_unhealthy render_health end
ruby
{ "resource": "" }
q20816
HealthMonitor.HealthMonitoring.render_health
train
def render_health return if performed? respond_to do |format| format.html { render_health_html } format.js { render_health_json } format.xml { render_health_xml } end end
ruby
{ "resource": "" }
q20817
HealthMonitor.HealthMonitoring.find_features
train
def find_features @features = if params[ :only ] params[ :only ].to_s.split( "," ).collect( &:to_sym ).uniq elsif skip = params[ :skip ] || params[ :exclude ] monitored_features.keys - skip.to_s.split( "," ).collect( &:to_sym ) else monitored_features.keys end end
ruby
{ "resource": "" }
q20818
VMC::App.Start.switch_mode
train
def switch_mode(app, mode) mode = nil if mode == "none" mode = "run" if mode == "" # no value given return false if app.debug == mode if mode.nil? with_progress("Removing debug mode") do app.debug = nil app.stop! if app.started? end return true end with_progress("Switching mode to #{c(mode, :name)}") do |s| app.debug = mode app.stop! if app.started? end end
ruby
{ "resource": "" }
q20819
XClarityClient.ManagementMixin.add_listname_on_body
train
def add_listname_on_body(resource, body) body.kind_of?(Array) ? process_body_as_array(resource, body) : process_body_as_hash(resource, body) end
ruby
{ "resource": "" }
q20820
XClarityClient.ManagementMixin.any_listname_of
train
def any_listname_of(resource) if resource::LIST_NAME.kind_of?(Array) resource::LIST_NAME.first # If is an array, any listname can be use else resource::LIST_NAME # If is not an array, just return the listname of resource end end
ruby
{ "resource": "" }
q20821
XClarityClient.ManagementMixin.process_body_as_hash
train
def process_body_as_hash(resource, body) result = body if resource::LIST_NAME.kind_of? Array # search which list name is present on body list_name = resource::LIST_NAME.find { |name| body.keys.include?(name) && body[name].kind_of?(Array) } else list_name = any_listname_of(resource) end result = {list_name => [body]} unless body.has_key? list_name # for the cases where body represents a single resource return list_name, result end
ruby
{ "resource": "" }
q20822
XClarityClient.UserManagement.mount_response_change_password
train
def mount_response_change_password(response) response = JSON.parse(response.body) { changed: response['response']['changed'], message: response['messages'].first['explanation'] } end
ruby
{ "resource": "" }
q20823
Markaby.Builder.capture
train
def capture(&block) @streams.push(@builder.target = Stream.new) @builder.level += 1 str = instance_eval(&block) str = @streams.last.join if @streams.last.any? @streams.pop @builder.level -= 1 @builder.target = @streams.last str end
ruby
{ "resource": "" }
q20824
Markaby.Builder.tag!
train
def tag!(tag, *args, &block) ele_id = nil # TODO: Move this logic to the tagset so that the tagset itself can validate + raise when invalid if @auto_validation && @tagset if !@tagset.tagset.has_key?(tag) raise InvalidXhtmlError, "no element `#{tag}' for #{tagset.doctype}" elsif args.last.respond_to?(:to_hash) attrs = args.last.to_hash if @tagset.forms.include?(tag) && attrs[:id] attrs[:name] ||= attrs[:id] end attrs.each do |k, v| atname = k.to_s.downcase.intern unless k =~ /:/ or @tagset.tagset[tag].include?(atname) or (@tagset == Markaby::HTML5 && atname.to_s =~ /^data-/) raise InvalidXhtmlError, "no attribute `#{k}' on #{tag} elements" end if atname == :id ele_id = v.to_s if @used_ids.has_key? ele_id raise InvalidXhtmlError, "id `#{ele_id}' already used (id's must be unique)." end end if AttrsBoolean.include? atname if v attrs[k] = atname.to_s else attrs.delete k end end end end end if block str = capture(&block) block = proc { text(str) } end f = fragment { @builder.tag!(tag, *args, &block) } @used_ids[ele_id] = f if ele_id f end
ruby
{ "resource": "" }
q20825
XClarityClient.UpdateCompManagement.add_uri
train
def add_uri(force_update_mode, onerror_mode, uri) fmode = force_update_mode.nil? uri += '&forceUpdateMode=' + force_update_mode unless fmode uri += '&onErrorMode=' + onerror_mode unless onerror_mode.nil? uri end
ruby
{ "resource": "" }
q20826
RestFtpDaemon.JobQueue.jobs_with_status
train
def jobs_with_status status # No status filter: return all execept queued if status.empty? @jobs.reject { |job| job.status == JOB_STATUS_QUEUED } # Status filtering: only those jobs else @jobs.select { |job| job.status == status.to_s } end end
ruby
{ "resource": "" }
q20827
RestFtpDaemon.Job.debug_value_utf8
train
def debug_value_utf8 value case value when Symbol return value.to_s.force_encoding(Encoding::UTF_8) when String return value.dup.force_encoding(Encoding::UTF_8) if value.is_a? String else return value end end
ruby
{ "resource": "" }
q20828
Canard.UserModel.has_roles_mask_accessors?
train
def has_roles_mask_accessors? instance_method_names = instance_methods.map { |method_name| method_name.to_s } [roles_attribute_name.to_s, "#{roles_attribute_name}="].all? do |accessor| instance_method_names.include?(accessor) end end
ruby
{ "resource": "" }
q20829
Shwedagon.App.create_new_post
train
def create_new_post(params) post_title = params['post']['title'] post_date = (Time.now).strftime("%Y-%m-%d") content = yaml_data(post_title).to_yaml + "---\n" + params[:post][:content] post_file = (post_date + " " + post_title).to_url + '.md' file = File.join(jekyll_site.source, *%w[_posts], post_file) File.open(file, 'w') { |file| file.write(content)} post_file end
ruby
{ "resource": "" }
q20830
Shwedagon.App.merge_config
train
def merge_config(yaml, params) if params['post'].has_key? 'yaml' params['post']['yaml'].each do |key, value| if value == 'true' yaml[key] = true elsif value == 'false' yaml[key] = false else yaml[key] = value end end end yaml end
ruby
{ "resource": "" }
q20831
Shwedagon.App.update_post
train
def update_post(params) post_file = params[:post][:name] post = jekyll_post(post_file) yaml_config = merge_config(post.data, params) write_post_contents(params[:post][:content], yaml_config, post_file) post_file end
ruby
{ "resource": "" }
q20832
Shwedagon.App.jekyll_site
train
def jekyll_site if not @site # Supress stdout original_stdout = $stdout $stdout = File.new('/tmp/null.txt', 'w') config = Jekyll.configuration({'source' => cloned_repo_path}) @site = Jekyll::Site.new(config) @site.read $stdout = original_stdout end @site end
ruby
{ "resource": "" }
q20833
Shwedagon.App.posts_template_data
train
def posts_template_data(post_items) if post_items.nil? return [] end template_data = post_items.map do |post| { :title => post.data['title'], :filename => post.name, :date => post.date } end template_data.sort! { |x,y| y[:date] <=> x[:date] } template_data end
ruby
{ "resource": "" }
q20834
Nimbus.Application.nimbus_exception_handling
train
def nimbus_exception_handling begin yield rescue SystemExit => ex raise rescue Nimbus::Error => ex display_error_message(ex) Nimbus.stop rescue Exception => ex display_error_message(ex) Nimbus.stop end end
ruby
{ "resource": "" }
q20835
Nimbus.RegressionTree.seed
train
def seed(all_individuals, individuals_sample, ids_fenotypes) super @structure = build_node individuals_sample, Nimbus::LossFunctions.average(individuals_sample, @id_to_fenotype) end
ruby
{ "resource": "" }
q20836
Nimbus.Configuration.load
train
def load(config_file = DEFAULTS[:config_file]) user_config_params = {} dirname = Dir.pwd if File.exists?(File.expand_path(config_file, Dir.pwd)) begin config_file_path = File.expand_path config_file, Dir.pwd user_config_params = Psych.load(File.open(config_file_path)) dirname = File.dirname config_file_path rescue ArgumentError => e raise Nimbus::WrongFormatFileError, "It was not posible to parse the config file (#{config_file}): \r\n#{e.message} " end end if user_config_params['input'] @training_file = File.expand_path(user_config_params['input']['training'], dirname) if user_config_params['input']['training'] @testing_file = File.expand_path(user_config_params['input']['testing' ], dirname) if user_config_params['input']['testing'] @forest_file = File.expand_path(user_config_params['input']['forest' ], dirname) if user_config_params['input']['forest'] @classes = user_config_params['input']['classes'] if user_config_params['input']['classes'] else @training_file = File.expand_path(DEFAULTS[:training_file], Dir.pwd) if File.exists? File.expand_path(DEFAULTS[:training_file], Dir.pwd) @testing_file = File.expand_path(DEFAULTS[:testing_file ], Dir.pwd) if File.exists? File.expand_path(DEFAULTS[:testing_file ], Dir.pwd) @forest_file = File.expand_path(DEFAULTS[:forest_file ], Dir.pwd) if File.exists? File.expand_path(DEFAULTS[:forest_file ], Dir.pwd) end @do_training = true unless @training_file.nil? @do_testing = true unless @testing_file.nil? @classes = @classes.map{|c| c.to_s.strip} if @classes if @do_testing && !@do_training && !@forest_file raise Nimbus::InputFileError, "There is not random forest data (training file not defined, and forest file not found)." end if user_config_params['forest'] @forest_size = user_config_params['forest']['forest_size'].to_i if user_config_params['forest']['forest_size'] @tree_SNP_total_count = user_config_params['forest']['SNP_total_count'].to_i if user_config_params['forest']['SNP_total_count'] @tree_SNP_sample_size = user_config_params['forest']['SNP_sample_size_mtry'].to_i if user_config_params['forest']['SNP_sample_size_mtry'] @tree_node_min_size = user_config_params['forest']['node_min_size'].to_i if user_config_params['forest']['node_min_size'] @do_importances = user_config_params['forest']['var_importances'].to_s.strip.downcase @do_importances = (@do_importances != 'no' && @do_importances != 'false') end check_configuration log_configuration end
ruby
{ "resource": "" }
q20837
Alchemy.User.fullname
train
def fullname(options = {}) if lastname.blank? && firstname.blank? login else options = {:flipped => false}.merge(options) fullname = options[:flipped] ? "#{lastname}, #{firstname}" : "#{firstname} #{lastname}" fullname.squeeze(" ").strip end end
ruby
{ "resource": "" }
q20838
Alchemy.User.deliver_welcome_mail
train
def deliver_welcome_mail if has_role?('author') || has_role?('editor') || has_role?('admin') Notifications.alchemy_user_created(self).deliver_later else Notifications.member_created(self).deliver_later end end
ruby
{ "resource": "" }
q20839
Alchemy.UserSessionsController.after_sign_out_path_for
train
def after_sign_out_path_for(resource_or_scope) if request.referer.blank? || request.referer.to_s =~ /admin/ root_path else request.referer end end
ruby
{ "resource": "" }
q20840
Nimbus.Forest.traverse_regression_forest
train
def traverse_regression_forest @predictions = {} prediction_count = trees.size @options.read_testing_data{|individual| individual_prediction = 0.0 trees.each do |t| individual_prediction = (individual_prediction + Nimbus::Tree.traverse(t, individual.snp_list)).round(5) end @predictions[individual.id] = (individual_prediction / prediction_count).round(5) } end
ruby
{ "resource": "" }
q20841
Relaton.Db.docid_type
train
def docid_type(code) stdclass = standard_class(code) or return [nil, code] prefix, code = strip_id_wrapper(code, stdclass) [@registry.processors[stdclass].idtype, code] end
ruby
{ "resource": "" }
q20842
Relaton.Db.to_xml
train
def to_xml db = @local_db || @db || return Nokogiri::XML::Builder.new(encoding: "UTF-8") do |xml| xml.documents do xml.parent.add_child db.all.join(" ") end end.to_xml end
ruby
{ "resource": "" }
q20843
Relaton.Db.new_bib_entry
train
def new_bib_entry(code, year, opts, stdclass) bib = @registry.processors[stdclass].get(code, year, opts) bib = bib.to_xml if bib.respond_to? :to_xml bib = "not_found #{Date.today}" if bib.nil? || bib.empty? bib end
ruby
{ "resource": "" }
q20844
Relaton.DbCache.all
train
def all Dir.glob("#{@dir}/**/*.xml").sort.map do |f| File.read(f, encoding: "utf-8") end end
ruby
{ "resource": "" }
q20845
Telephony.Call.terminate_conversation_and_all_call_legs
train
def terminate_conversation_and_all_call_legs(trace_only = false) if self.conversation Rails.logger.info "zestphone: ** Terminating all linked calls and conversation **" Rails.logger.info "zestphone: conversation - (pre) state: #{self.conversation.state}" Rails.logger.info "zestphone: conversation - (pre) details: #{self.conversation.inspect}" Rails.logger.info "zestphone: calls - (pre) states: #{self.conversation.calls.map(&:state)}" Rails.logger.info "zestphone: calls - (pre) details: #{self.conversation.calls.map(&:inspect)}" unless trace_only self.conversation.calls.each do |c| c.terminate end self.conversation.terminate end else # Conversation not found - terminate the current call anyway Rails.logger.info "zestphone: call - details: #{self.inspect}" self.terminate unless trace_only end end
ruby
{ "resource": "" }
q20846
Phaxio.Resource.populate_attributes
train
def populate_attributes self.class.normal_attribute_list.each do |normal_attribute| self.public_send "#{normal_attribute}=", raw_data[normal_attribute] end self.class.time_attribute_list.each do |time_attribute| time = raw_data[time_attribute] time = Time.parse(time) if !time.nil? self.public_send "#{time_attribute}=", time end self.class.collection_attribute_mappings.each do |collection_attribute, klass| collection = raw_data[collection_attribute] || [] collection = {'data' => collection} collection = klass.response_collection(collection) self.public_send "#{collection_attribute}=", collection end end
ruby
{ "resource": "" }
q20847
MaterializePagination.ViewHelpers.will_paginate
train
def will_paginate(collection_or_options = nil, options = {}) if collection_or_options.is_a? Hash options, collection_or_options = collection_or_options, nil end unless options[:renderer] options = options.merge :renderer => MaterializePagination::Rails end super *[collection_or_options, options].compact end
ruby
{ "resource": "" }
q20848
DataType.Base.structure_changes_from
train
def structure_changes_from(current_structure = nil) new_structure = column if current_structure # General RDBMS data loss scenarios if new_structure[:limit] && current_structure[:limit].to_i != new_structure[:limit].to_i || new_structure[:type] != current_structure[:type] || !new_structure[:default].nil? && column_default_changed?(current_structure[:default], new_structure[:default]) column else nil # No changes end else column end end
ruby
{ "resource": "" }
q20849
SalesforceArSync.SalesforceSync.salesforce_attributes_to_set
train
def salesforce_attributes_to_set(attributes = {}) {}.tap do |hash| # loop through the hash of attributes from the outbound message, and compare to our sf mappings and # create a reversed hash of value's and key's to pass to update_attributes attributes.each do |key, value| # make sure our sync_mapping contains the salesforce attribute AND that our object has a setter for it hash[self.class.salesforce_sync_attribute_mapping[key.to_s].to_sym] = value if self.class.salesforce_sync_attribute_mapping.include?(key.to_s) && self.respond_to?("#{self.class.salesforce_sync_attribute_mapping[key.to_s]}=") end # remove the web_id from hash if it exists, as we don't want to modify a web_id hash.delete(:id) if hash[:id] # update the sf_updated_at field with the system mod stamp from sf hash[:salesforce_updated_at] = attributes[:SystemModstamp] # incase we looked up via the WebId__c, we should set the salesforce_id hash[:salesforce_id] = attributes[self.class.salesforce_id_attribute_name] end end
ruby
{ "resource": "" }
q20850
SalesforceArSync.SalesforceSync.salesforce_process_update
train
def salesforce_process_update(attributes = {}) attributes_to_update = salesforce_attributes_to_set(self.new_record? ? attributes : salesforce_empty_attributes.merge(attributes)) # only merge empty attributes for updates, so we don't overwrite the default create attributes attributes_to_update.each_pair do |k, v| self.send("#{k}=", v) end # we don't want to keep going in a endless loop. SF has just updated these values. self.salesforce_skip_sync = true self.save! end
ruby
{ "resource": "" }
q20851
SalesforceArSync.SalesforceSync.system_mod_stamp
train
def system_mod_stamp hash = JSON.parse(SF_CLIENT.http_get("/services/data/v#{SF_CLIENT.version}/query", :q => "SELECT SystemModstamp FROM #{salesforce_object_name} WHERE Id = '#{salesforce_id}'").body) hash["records"].first.try(:[], "SystemModstamp") end
ruby
{ "resource": "" }
q20852
SalesforceArSync.SalesforceSync.salesforce_attributes_to_update
train
def salesforce_attributes_to_update(include_all = false) {}.tap do |hash| self.class.salesforce_sync_attribute_mapping.each do |key, value| if self.respond_to?(value) #Checkboxes in SFDC Cannot be nil. Here we check for boolean field type and set nil values to be false attribute_value = self.send(value) if is_boolean?(value) && attribute_value.nil? attribute_value = false end hash[key] = attribute_value if include_all || salesforce_should_update_attribute?(value) end end end end
ruby
{ "resource": "" }
q20853
SalesforceArSync.SalesforceSync.salesforce_perform_async_call?
train
def salesforce_perform_async_call? return false if salesforce_attributes_to_update.empty? || self.class.salesforce_async_attributes.empty? salesforce_attributes_to_update.keys.all? {|key| self.class.salesforce_async_attributes.include?(key) } && salesforce_id.present? end
ruby
{ "resource": "" }
q20854
SalesforceArSync.SalesforceSync.salesforce_sync
train
def salesforce_sync return if self.salesforce_skip_sync? if salesforce_perform_async_call? Delayed::Job.enqueue(SalesforceArSync::SalesforceObjectSync.new(self.class.salesforce_web_class_name, salesforce_id, salesforce_attributes_to_update), :priority => 50) else if salesforce_object_exists? salesforce_update_object(salesforce_attributes_to_update) if salesforce_attributes_to_update.present? else salesforce_create_object(salesforce_attributes_to_update(!new_record?)) if salesforce_id.nil? end end rescue Exception => ex self.errors[:base] << ex.message return false end
ruby
{ "resource": "" }
q20855
SalesforceArSync.SoapMessageController.validate_ip_ranges
train
def validate_ip_ranges raise ActionController::RoutingError.new('Not Found') unless SalesforceArSync::IPConstraint.new.matches?(request) end
ruby
{ "resource": "" }
q20856
ApiClient.Scope.request
train
def request(method, path, options = {}) options = options.dup raw = raw? || options.delete(:raw) params(options) response = connection.send method, path, (@raw_body || @params), @headers raw ? response : @scopeable.parse(response) end
ruby
{ "resource": "" }
q20857
GovukSchemas.RandomExample.payload
train
def payload payload = @random_generator.payload # ensure the base payload is valid errors = validation_errors_for(payload) raise InvalidContentGenerated, error_message(payload, errors) if errors.any? if block_given? payload = yield(payload) # check the payload again after customisation errors = validation_errors_for(payload) raise InvalidContentGenerated, error_message(payload, errors, true) if errors.any? end payload end
ruby
{ "resource": "" }
q20858
HideMyAss.IP.decode
train
def decode(elements) elements.each do |element| # Remove elements with CSS style "none" if !TAGS.include?(element.name) || (element["style"] && element["style"] =~ /none/) element.children.remove # Get rid of decoy children elsif element["class"] decoys.each do |decoy| element.children.remove if decoy.include?(element["class"]) end end end elements end
ruby
{ "resource": "" }
q20859
Ambry.AbstractKeySet.count
train
def count(&block) return keys.count unless block_given? proxy = HashProxy.new keys.inject(0) do |count, key| proxy.with(mapper[key], &block) ? count.succ : count end end
ruby
{ "resource": "" }
q20860
IntervalTree.Tree.center
train
def center(intervals) i = intervals.reduce([intervals.first.first, intervals.first.last]) { |acc, int| [[acc.first, int.first].min, [acc.last, int.last].max] } i.first + (i.last - i.first) / 2 end
ruby
{ "resource": "" }
q20861
Ambry.HashProxy.method_missing
train
def method_missing(symbol) if hash.key?(symbol) hash[symbol] elsif hash.key?(symbol.to_s) hash[symbol.to_s] else raise NoMethodError end end
ruby
{ "resource": "" }
q20862
Ambry.HashProxy.[]
train
def [](key) if hash.key?(key) then hash[key] elsif hash.key?(key.to_sym) then hash[key.to_sym] elsif hash.key?(key.to_s) then hash[key.to_s] end end
ruby
{ "resource": "" }
q20863
Ambry.Mapper.[]=
train
def []=(key, value) @lock.synchronize do @indexes = {} if value.id_changed? hash.delete value.to_id(true) end saved = hash[key] = value.to_hash.freeze adapter.save_database if @options[:sync] saved end end
ruby
{ "resource": "" }
q20864
Caboose.Invoice.authorize_and_capture
train
def authorize_and_capture resp = StdClass.new if self.financial_status == Invoice::FINANCIAL_STATUS_CAPTURED resp.error = "Funds for this invoice have already been captured." else sc = self.site.store_config case sc.pp_name when StoreConfig::PAYMENT_PROCESSOR_STRIPE Stripe.api_key = sc.stripe_secret_key.strip bt = nil begin c = Stripe::Charge.create( :amount => (self.total * 100).to_i, :currency => 'usd', :customer => self.customer.stripe_customer_id, :capture => true, :metadata => { :invoice_id => self.id }, :statement_descriptor => "#{self.site.description.truncate(22)}" ) rescue Exception => ex resp.error = "Error during capture process\n#{ex.message}" end if resp.error.nil? InvoiceTransaction.create( :invoice_id => self.id, :transaction_id => c.id, :transaction_type => InvoiceTransaction::TYPE_AUTHCAP, :payment_processor => sc.pp_name, :amount => c.amount / 100.0, :captured => true, :date_processed => DateTime.now.utc, :success => c.status == 'succeeded' ) if c.status == 'succeeded' self.financial_status = Invoice::FINANCIAL_STATUS_CAPTURED self.save resp.success = true else resp.error = "Error capturing funds." end end end end return resp end
ruby
{ "resource": "" }
q20865
Caboose.Invoice.void
train
def void resp = StdClass.new t = InvoiceTransaction.where(:invoice_id => self.id, :transaction_type => InvoiceTransaction::TYPE_AUTHORIZE, :success => true).first if self.financial_status == Invoice::FINANCIAL_STATUS_CAPTURED resp.error = "This invoice has already been captured, you will need to refund instead" elsif t.nil? resp.error = "This invoice doesn't seem to be authorized." else sc = self.site.store_config ot = Caboose::InvoiceTransaction.new( :invoice_id => self.id, :date_processed => DateTime.now.utc, :transaction_type => InvoiceTransaction::TYPE_VOID, :payment_processor => sc.pp_name, :amount => self.total ) case sc.pp_name when 'authorize.net' response = AuthorizeNet::SIM::Transaction.new( sc.authnet_api_login_id, sc.authnet_api_transaction_key, self.total, :transaction_type => InvoiceTransaction::TYPE_VOID, :transaction_id => t.transaction_id, :test => sc.pp_testing ) self.update_attributes( :financial_status => Invoice::FINANCIAL_STATUS_VOIDED, :status => Invoice::STATUS_CANCELED ) self.save # TODO: Add the variant quantities invoiceed back resp.success = "Invoice voided successfully" ot.success = response.response_code && response.response_code == '1' ot.transaction_id = response.transaction_id #ot.auth_code = response.authorization_code ot.response_code = response.response_code ot.save when 'stripe' # TODO: Implement void invoice for strip when 'payscape' # TODO: Implement void invoice for payscape end end return resp end
ruby
{ "resource": "" }
q20866
Beaker.Vmpooler.add_tags
train
def add_tags(host) host[:host_tags].merge( 'beaker_version' => Beaker::Version::STRING, 'jenkins_build_url' => @options[:jenkins_build_url], 'department' => @options[:department], 'project' => @options[:project], 'created_by' => @options[:created_by], 'name' => host.name, 'roles' => host.host_hash[:roles].join(', ') ) end
ruby
{ "resource": "" }
q20867
Caboose.Subscription.create_invoices
train
def create_invoices self.calculate_date_started_full if self.date_started_full.nil? v = self.variant interval = case v.subscription_interval when Variant::SUBSCRIPTION_INTERVAL_MONTHLY then 1.month when Variant::SUBSCRIPTION_INTERVAL_YEARLY then 1.year end sc = v.product.site.store_config unit_price = v.clearance && v.clearance_price ? v.clearance_price : (v.on_sale? ? v.sale_price : v.price) # Special case if the subscription starts on specific day if v.subscription_start_on_day && (Date.today > self.date_started_full) li = self.line_items.where("date_starts = ? date_ends = ?", self.date_started, self.date_started_full - 1.day).first if li.nil? prorated_unit_price = unit_price + 0.00 if v.subscription_prorate prorated_unit_price = case v.subscription_prorate_method when Variant::SUBSCRIPTION_PRORATE_METHOD_FLAT then v.subscription_prorate_flat_amount when Variant::SUBSCRIPTION_PRORATE_METHOD_PERCENTAGE then unit_price * ((self.date_started_full - self.date_started).to_f / ((self.date_started_full + interval) - self.date_started_full).to_f) when Variant::SUBSCRIPTION_PRORATE_METHOD_CUSTOM then self.custom_prorate end end invoice = Caboose::Invoice.create( :site_id => v.product.site_id, :status => Caboose::Invoice::STATUS_PENDING, :financial_status => Caboose::Invoice::STATUS_PENDING, :date_created => DateTime.now, :payment_terms => sc.default_payment_terms, :invoice_number => sc.next_invoice_number ) LineItem.create( :invoice_id => invoice.id, :variant_id => v.id, :quantity => 1, :unit_price => prorated_unit_price, :subtotal => prorated_unit_price, :status => 'pending', :subscription_id => self.id, :date_starts => d, :date_ends => d + interval - 1.day ) invoice.calculate invoice.save end end d2 = self.date_started_full + 1.day - 1.day while d2 <= Date.today do d2 = d2 + interval end d = self.date_started + 1.day - 1.day while d <= d2 do # See if an invoice has already been created for today li = self.line_items.where("date_starts = ? AND date_ends = ?", d, d + interval - 1.day).first if li.nil? invoice = Caboose::Invoice.create( :site_id => v.product.site_id, :customer_id => self.user_id, :status => Caboose::Invoice::STATUS_PENDING, :financial_status => Caboose::Invoice::STATUS_PENDING, :date_created => DateTime.now, :payment_terms => sc.default_payment_terms, :invoice_number => sc.next_invoice_number ) LineItem.create( :invoice_id => invoice.id, :variant_id => v.id, :quantity => 1, :unit_price => unit_price, :subtotal => unit_price, :status => 'pending', :subscription_id => self.id, :date_starts => d, :date_ends => d + interval - 1.day ) invoice.calculate invoice.save end d = d + interval end return true end
ruby
{ "resource": "" }
q20868
Caboose.InvoicePackage.activemerchant_package
train
def activemerchant_package sc = self.invoice.site.store_config weight = 0.0 self.line_items.each{ |li| weight = weight + (li.variant.weight * li.quantity) } weight = weight * 0.035274 if sc.weight_unit == StoreConfig::WEIGHT_UNIT_METRIC # grams to ounces sp = self.shipping_package dimensions = [sp.outside_length, sp.outside_width, sp.outside_height] if sc.length_unit == StoreConfig::LENGTH_UNIT_METRIC # cm to inches dimensions[0] = dimensions[0] / 2.54 dimensions[1] = dimensions[0] / 2.54 dimensions[2] = dimensions[0] / 2.54 end return ActiveShipping::Package.new(weight, dimensions, :units => :imperial, :container => :variable) end
ruby
{ "resource": "" }
q20869
Caboose.ShippingPackage.boxes
train
def boxes(rigid_variants) stackable = {} nonstackable = [] rigid_variants.each do |v| sgid = v.product.stackable_group_id if sgid stackable[sgid] = [] if stackable[sgid].nil? stackable[sgid] << v else nonstackable << [v.length, v.width, v.height] end end stackable.each do |sgid, arr| sg = arr[0].product.stackable_group l = 0.0 w = 0.0 h = 0.0 arr.each do |v| if l+sg.extra_length >= sg.max_length || w+sg.extra_width >= sg.max_width || h+sg.extra_height >= sg.max_height nonstackable << [l, w, h] l = 0.0 w = 0.0 h = 0.0 end if l == 0.0 l = v.length w = v.width h = v.height else l = l + sg.extra_length w = w + sg.extra_width h = h + sg.extra_height end end nonstackable << [l, w, h] if l > 0 end return nonstackable end
ruby
{ "resource": "" }
q20870
Caboose.ApplicationController.init_cart
train
def init_cart # Check if the cart ID is defined and that it exists in the database create_new_invoice = false if session[:cart_id] @invoice = Caboose::Invoice.where(:id => session[:cart_id]).first create_new_invoice = true if @invoice.nil? || @invoice.status != 'cart' else create_new_invoice = true end if create_new_invoice # Create an invoice to associate with the session @invoice = Caboose::Invoice.new @invoice.site_id = @site ? @site.id : nil @invoice.status = Caboose::Invoice::STATUS_CART @invoice.financial_status = Caboose::Invoice::STATUS_PENDING @invoice.date_created = DateTime.now @invoice.referring_site = request.env['HTTP_REFERER'] @invoice.landing_page = request.fullpath @invoice.landing_page_ref = params[:ref] || nil @invoice.payment_terms = @site.store_config.default_payment_terms @invoice.save InvoiceLog.create( :invoice_id => @invoice.id, :user_id => logged_in_user.id, :date_logged => DateTime.now.utc, :invoice_action => InvoiceLog::ACTION_INVOICE_CREATED ) # Save the cart ID in the session session[:cart_id] = @invoice.id end end
ruby
{ "resource": "" }
q20871
Caboose.ApplicationController.parse_url_params
train
def parse_url_params return if !Caboose.use_url_params url = "#{request.fullpath}" url[0] = "" if url.starts_with?('/') url = url.split('?')[0] if url.include?('?') arr = url.split('/') i = arr.count - 1 while i >= 1 do k = arr[i-1] v = arr[i] if v && v.length > 0 v = v.gsub('%20', ' ') params[k] = v end i = i-2 end end
ruby
{ "resource": "" }
q20872
Caboose.ApplicationController.login_user
train
def login_user(user, remember = false) session["app_user"] = Caboose::StdClass.new({ :id => user.id , :site_id => user.site_id , :first_name => user.first_name , :last_name => user.last_name , :username => user.username , :email => user.email }) cookies.permanent[:caboose_user_id] = user.id if remember end
ruby
{ "resource": "" }
q20873
Caboose.ApplicationController.logged_in?
train
def logged_in? validate_token validate_cookie return true if !session["app_user"].nil? && session["app_user"] != false && session["app_user"].id != -1 && session["app_user"].id != User.logged_out_user_id(@site.id) return false end
ruby
{ "resource": "" }
q20874
Caboose.ApplicationController.validate_token
train
def validate_token token = params[:token] return false if token.nil? user = User.validate_token(token) return false if user.nil? login_user(user) return true end
ruby
{ "resource": "" }
q20875
Caboose.ApplicationController.validate_cookie
train
def validate_cookie if cookies[:caboose_user_id] user = User.where(:id => cookies[:caboose_user_id]).first if user login_user(user) return true end end return false end
ruby
{ "resource": "" }
q20876
Caboose.ApplicationController.reject_param
train
def reject_param(url, param) arr = url.split('?') return url if (arr.count == 1) qs = arr[1].split('&').reject { |pair| pair.split(/[=;]/).first == param } url2 = arr[0] url2 += "?" + qs.join('&') if qs.count > 0 return url2 end
ruby
{ "resource": "" }
q20877
Caboose.ApplicationController.under_construction_or_forwarding_domain?
train
def under_construction_or_forwarding_domain? d = Caboose::Domain.where(:domain => request.host_with_port).first if d.nil? Caboose.log("Could not find domain for #{request.host_with_port}\nAdd this domain to the caboose site.") elsif d.under_construction == true if d.site.under_construction_html && d.site.under_construction_html.strip.length > 0 render :text => d.site.under_construction_html else render :file => 'caboose/application/under_construction', :layout => false end return true # See if we're on a forwarding domain elsif d.primary == false && d.forward_to_primary == true pd = d.site.primary_domain if pd && pd.domain != request.host url = "#{request.protocol}#{pd.domain}" if d.forward_to_uri && d.forward_to_uri.strip.length > 0 url << d.forward_to_uri elsif request.fullpath && request.fullpath.strip.length > 0 && request.fullpath.strip != '/' url << request.fullpath end redirect_to url return true end # Check for a 301 redirect else new_url = PermanentRedirect.match(@site.id, request.fullpath) if new_url redirect_to new_url, :status => 301 return true end end return false end
ruby
{ "resource": "" }
q20878
Caboose.CheckoutController.shipping_json
train
def shipping_json render :json => { :error => 'Not logged in.' } and return if !logged_in? render :json => { :error => 'No shippable items.' } and return if !@invoice.has_shippable_items? render :json => { :error => 'Empty shipping address.' } and return if @invoice.shipping_address.nil? @invoice.calculate #ops = @invoice.invoice_packages #if params[:recalculate_invoice_packages] || ops.count == 0 # # Remove any invoice packages # LineItem.where(:invoice_id => @invoice.id).update_all(:invoice_package_id => nil) # InvoicePackage.where(:invoice_id => @invoice.id).destroy_all # # # Calculate what shipping packages we'll need # InvoicePackage.create_for_invoice(@invoice) #end # Now get the rates for those packages rates = ShippingCalculator.rates(@invoice) render :json => rates end
ruby
{ "resource": "" }
q20879
Caboose.CheckoutController.update_stripe_details
train
def update_stripe_details render :json => false and return if !logged_in? sc = @site.store_config Stripe.api_key = sc.stripe_secret_key.strip u = logged_in_user c = nil if u.stripe_customer_id c = Stripe::Customer.retrieve(u.stripe_customer_id) begin c.source = params[:token] c.save rescue c = nil end end if c.nil? c = Stripe::Customer.create( :source => params[:token], :email => u.email, :metadata => { :user_id => u.id } ) end u.stripe_customer_id = c.id u.card_last4 = params[:card][:last4] u.card_brand = params[:card][:brand] u.card_exp_month = params[:card][:exp_month] u.card_exp_year = params[:card][:exp_year] u.save render :json => { :success => true, :customer_id => u.stripe_customer_id, :card_last4 => u.card_last4, :card_brand => u.card_brand, :card_exp_month => u.card_exp_month, :card_exp_year => u.card_exp_year } end
ruby
{ "resource": "" }
q20880
Caboose.InvoicesMailer.fulfillment_new_invoice
train
def fulfillment_new_invoice(invoice) @invoice = invoice sc = invoice.site.store_config mail(:to => sc.fulfillment_email, :subject => 'New Order') end
ruby
{ "resource": "" }
q20881
Caboose.InvoicesMailer.shipping_invoice_ready
train
def shipping_invoice_ready(invoice) @invoice = invoice sc = invoice.site.store_config mail(:to => sc.shipping_email, :subject => 'Order ready for shipping') end
ruby
{ "resource": "" }
q20882
XapianDb.DocumentBlueprint.accessors_module
train
def accessors_module return @accessors_module unless @accessors_module.nil? @accessors_module = Module.new # Add the accessors for the indexed class and the score @accessors_module.instance_eval do define_method :indexed_class do self.values[0].value end define_method :score do @score end define_method :attributes do blueprint = XapianDb::DocumentBlueprint.blueprint_for indexed_class blueprint.attribute_names.inject({}) { |hash, attr| hash.tap { |hash| hash[attr.to_s] = self.send attr } } end end # Add an accessor for each attribute attribute_names.each do |attribute| index = DocumentBlueprint.value_number_for(attribute) codec = XapianDb::TypeCodec.codec_for @type_map[attribute] @accessors_module.instance_eval do define_method attribute do codec.decode self.value(index) end end end # Let the adapter add its document helper methods (if any) _adapter.add_doc_helper_methods_to(@accessors_module) @accessors_module end
ruby
{ "resource": "" }
q20883
XapianDb.DocumentBlueprint.attribute
train
def attribute(name, options={}, &block) raise ArgumentError.new("You cannot use #{name} as an attribute name since it is a reserved method name of Xapian::Document") if reserved_method_name?(name) do_not_index = options.delete(:index) == false @type_map[name] = (options.delete(:as) || :string) if block_given? @attributes_hash[name] = {:block => block}.merge(options) else @attributes_hash[name] = options end self.index(name, options, &block) unless do_not_index end
ruby
{ "resource": "" }
q20884
XapianDb.DocumentBlueprint.attributes
train
def attributes(*attributes) attributes.each do |attr| raise ArgumentError.new("You cannot use #{attr} as an attribute name since it is a reserved method name of Xapian::Document") if reserved_method_name?(attr) @attributes_hash[attr] = {} @type_map[attr] = :string self.index attr end end
ruby
{ "resource": "" }
q20885
XapianDb.DocumentBlueprint.index
train
def index(*args, &block) case args.size when 1 @indexed_methods_hash[args.first] = IndexOptions.new(:weight => 1, :block => block) when 2 # Is it a method name with options? if args.last.is_a? Hash options = args.last assert_valid_keys options, :weight, :prefixed, :no_split @indexed_methods_hash[args.first] = IndexOptions.new(options.merge(:block => block)) else add_indexes_from args end else # multiple arguments add_indexes_from args end end
ruby
{ "resource": "" }
q20886
XapianDb.DocumentBlueprint.natural_sort_order
train
def natural_sort_order(name=nil, &block) raise ArgumentError.new("natural_sort_order accepts a method name or a block, but not both") if name && block @_natural_sort_order = name || block end
ruby
{ "resource": "" }
q20887
XapianDb.Config.database
train
def database(path) # If the current database is a persistent database, we must release the # database and run the garbage collector to remove the write lock if @_database.is_a?(XapianDb::PersistentDatabase) @_database = nil GC.start end if path.to_sym == :memory @_database = XapianDb.create_db else begin @_database = XapianDb.open_db :path => path rescue IOError @_database = XapianDb.create_db :path => path end end end
ruby
{ "resource": "" }
q20888
XapianDb.Config.adapter
train
def adapter(type) begin @_adapter = XapianDb::Adapters.const_get("#{camelize(type.to_s)}Adapter") rescue NameError require File.dirname(__FILE__) + "/adapters/#{type}_adapter" @_adapter = XapianDb::Adapters.const_get("#{camelize(type.to_s)}Adapter") end end
ruby
{ "resource": "" }
q20889
XapianDb.Config.writer
train
def writer(type) # We try to guess the writer name begin require File.dirname(__FILE__) + "/index_writers/#{type}_writer" @_writer = XapianDb::IndexWriters.const_get("#{camelize(type.to_s)}Writer") rescue LoadError puts "XapianDb: cannot load #{type} writer; see README for supported writers and how to install neccessary queue infrastructure" raise end end
ruby
{ "resource": "" }
q20890
XapianDb.Config.language
train
def language(lang) lang ||= :none @_stemmer = XapianDb::Repositories::Stemmer.stemmer_for lang @_stopper = lang == :none ? nil : XapianDb::Repositories::Stopper.stopper_for(lang) end
ruby
{ "resource": "" }
q20891
XapianDb.Utilities.assert_valid_keys
train
def assert_valid_keys(hash, *valid_keys) unknown_keys = hash.keys - [valid_keys].flatten raise(ArgumentError, "Unsupported option(s) detected: #{unknown_keys.join(", ")}") unless unknown_keys.empty? end
ruby
{ "resource": "" }
q20892
Mocha.API.assert_received
train
def assert_received(mock, expected_method_name) matcher = have_received(expected_method_name) yield(matcher) if block_given? assert matcher.matches?(mock), matcher.failure_message end
ruby
{ "resource": "" }
q20893
XapianDb.Resultset.decorate
train
def decorate(match) klass_name = match.document.values[0].value blueprint = XapianDb::DocumentBlueprint.blueprint_for klass_name match.document.extend blueprint.accessors_module match.document.instance_variable_set :@score, match.percent match end
ruby
{ "resource": "" }
q20894
XapianDb.Database.delete_docs_of_class
train
def delete_docs_of_class(klass) writer.delete_document("C#{klass}") if klass.respond_to? :descendants klass.descendants.each do |subclass| writer.delete_document("C#{subclass}") end end true end
ruby
{ "resource": "" }
q20895
XapianDb.Database.search
train
def search(expression, options={}) opts = {:sort_decending => false}.merge(options) @query_parser ||= QueryParser.new(self) query = @query_parser.parse(expression) # If we do not have a valid query we return an empty result set return Resultset.new(nil, opts) unless query start = Time.now enquiry = Xapian::Enquire.new(reader) enquiry.query = query sort_indices = opts.delete :sort_indices sort_decending = opts.delete :sort_decending order = opts.delete :order raise ArgumentError.new "you can't use sort_indices and order, only one of them" if sort_indices && order if order sort_indices = order.map{ |attr_name| XapianDb::DocumentBlueprint.value_number_for attr_name.to_sym } end sorter = Xapian::MultiValueKeyMaker.new if sort_indices sort_indices.each { |index| sorter.add_value index } enquiry.set_sort_by_key_then_relevance(sorter, sort_decending) else sorter.add_value DocumentBlueprint.value_number_for(:natural_sort_order) enquiry.set_sort_by_relevance_then_key sorter, false end opts[:spelling_suggestion] = @query_parser.spelling_suggestion opts[:db_size] = self.size retries = 0 begin result = Resultset.new(enquiry, opts) rescue IOError => ex raise unless ex.message =~ /DatabaseModifiedError: / raise if retries >= 5 sleep 0.1 retries += 1 Rails.logger.warn "XapianDb: DatabaseModifiedError, retry #{retries}" if defined?(Rails) @reader.reopen retry end Rails.logger.debug "XapianDb search (#{(Time.now - start) * 1000}ms) #{expression}" if defined?(Rails) result end
ruby
{ "resource": "" }
q20896
XapianDb.Database.facets
train
def facets(attribute, expression) # return an empty hash if no search expression is given return {} if expression.nil? || expression.strip.empty? value_number = XapianDb::DocumentBlueprint.value_number_for(attribute) @query_parser ||= QueryParser.new(self) query = @query_parser.parse(expression) enquiry = Xapian::Enquire.new(reader) enquiry.query = query enquiry.collapse_key = value_number facets = {} enquiry.mset(0, size).matches.each do |match| facet_value = match.document.value(value_number) # We must add 1 to the collapse_count since collapse_count means # "how many other matches are there?" facets[facet_value] = match.collapse_count + 1 end facets end
ruby
{ "resource": "" }
q20897
XapianDb.Indexer.store_fields
train
def store_fields # class name of the object goes to position 0 @xapian_doc.add_value 0, @obj.class.name # natural sort order goes to position 1 if @blueprint._natural_sort_order.is_a? Proc sort_value = @obj.instance_eval &@blueprint._natural_sort_order else sort_value = @obj.send @blueprint._natural_sort_order end @xapian_doc.add_value 1, sort_value.to_s @blueprint.attribute_names.each do |attribute| block = @blueprint.block_for_attribute attribute if block value = @obj.instance_eval &block else value = @obj.send attribute end codec = XapianDb::TypeCodec.codec_for @blueprint.type_map[attribute] encoded_string = codec.encode value @xapian_doc.add_value DocumentBlueprint.value_number_for(attribute), encoded_string unless encoded_string.nil? end end
ruby
{ "resource": "" }
q20898
XapianDb.Indexer.index_text
train
def index_text term_generator = Xapian::TermGenerator.new term_generator.database = @database.writer term_generator.document = @xapian_doc if XapianDb::Config.stemmer term_generator.stemmer = XapianDb::Config.stemmer term_generator.stopper = XapianDb::Config.stopper if XapianDb::Config.stopper # Enable the creation of a spelling dictionary if the database is not in memory term_generator.set_flags Xapian::TermGenerator::FLAG_SPELLING if @database.is_a? XapianDb::PersistentDatabase end # Index the primary key as a unique term @xapian_doc.add_term("Q#{@obj.xapian_id}") # Index the class with the field name term_generator.index_text("#{@obj.class}".downcase, 1, "XINDEXED_CLASS") @xapian_doc.add_term("C#{@obj.class}") @blueprint.indexed_method_names.each do |method| options = @blueprint.options_for_indexed_method method if options.block obj = @obj.instance_eval(&options.block) else obj = @obj.send(method) end unless obj.nil? values = get_values_to_index_from obj values.each do |value| terms = value.to_s.downcase terms = @blueprint.preprocess_terms.call(terms) if @blueprint.preprocess_terms terms = split(terms) if XapianDb::Config.term_splitter_count > 0 && !options.no_split # Add value with field name term_generator.index_text(terms, options.weight, "X#{method.upcase}") if options.prefixed # Add value without field name term_generator.index_text(terms, options.weight) end end end terms_to_ignore = @xapian_doc.terms.select{ |term| term.term.length < XapianDb::Config.term_min_length } terms_to_ignore.each { |term| @xapian_doc.remove_term term.term } end
ruby
{ "resource": "" }
q20899
XapianDb.Indexer.get_values_to_index_from
train
def get_values_to_index_from(obj) # if it's an array, we collect the values for its elements recursive if obj.is_a? Array return obj.map { |element| get_values_to_index_from element }.flatten.compact end # if the object responds to attributes and attributes is a hash, # we use the attributes values (works well for active_record and datamapper objects) return obj.attributes.values.compact if obj.respond_to?(:attributes) && obj.attributes.is_a?(Hash) # The object is unkown and will be indexed by its to_s method; if to_s retruns nil, we # will not index it obj.to_s.nil? ? [] : [obj] end
ruby
{ "resource": "" }