_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q13100
MetaTags.ViewHelper.title
train
def title(title = nil, headline = '') set_meta_tags(title: title) unless title.nil? headline.presence || meta_tags[:title] end
ruby
{ "resource": "" }
q13101
MetaTags.MetaTagsCollection.update
train
def update(object = {}) meta_tags = object.respond_to?(:to_meta_tags) ? object.to_meta_tags : object @meta_tags.deep_merge! normalize_open_graph(meta_tags) end
ruby
{ "resource": "" }
q13102
MetaTags.MetaTagsCollection.extract_full_title
train
def extract_full_title site_title = extract(:site) || '' title = extract_title || [] separator = extract_separator reverse = extract(:reverse) == true TextNormalizer.normalize_title(site_title, title, separator, reverse) end
ruby
{ "resource": "" }
q13103
MetaTags.MetaTagsCollection.extract_title
train
def extract_title title = extract(:title).presence return unless title title = Array(title) return title.map(&:downcase) if extract(:lowercase) == true title end
ruby
{ "resource": "" }
q13104
MetaTags.MetaTagsCollection.extract_separator
train
def extract_separator if meta_tags[:separator] == false # Special case: if separator is hidden, do not display suffix/prefix prefix = separator = suffix = '' else prefix = extract_separator_section(:prefix, ' ') separator = extract_separator_section(:separator, '|') suffix = extract_separator_section(:suffix, ' ') end delete(:separator, :prefix, :suffix) TextNormalizer.safe_join([prefix, separator, suffix], '') end
ruby
{ "resource": "" }
q13105
MetaTags.MetaTagsCollection.extract_noindex
train
def extract_noindex noindex_name, noindex_value = extract_noindex_attribute(:noindex) index_name, index_value = extract_noindex_attribute(:index) nofollow_name, nofollow_value = extract_noindex_attribute(:nofollow) follow_name, follow_value = extract_noindex_attribute(:follow) noindex_attributes = if noindex_name == follow_name && (noindex_value || follow_value) # noindex has higher priority than index and follow has higher priority than nofollow [ [noindex_name, noindex_value || index_value], [follow_name, follow_value || nofollow_value], ] else [ [index_name, index_value], [follow_name, follow_value], [noindex_name, noindex_value], [nofollow_name, nofollow_value], ] end append_noarchive_attribute group_attributes_by_key noindex_attributes end
ruby
{ "resource": "" }
q13106
MetaTags.MetaTagsCollection.extract_noindex_attribute
train
def extract_noindex_attribute(name) noindex = extract(name) noindex_name = noindex.kind_of?(String) ? noindex : 'robots' noindex_value = noindex ? name.to_s : nil [ noindex_name, noindex_value ] end
ruby
{ "resource": "" }
q13107
MetaTags.MetaTagsCollection.append_noarchive_attribute
train
def append_noarchive_attribute(noindex) noarchive_name, noarchive_value = extract_noindex_attribute :noarchive if noarchive_value if noindex[noarchive_name].blank? noindex[noarchive_name] = noarchive_value else noindex[noarchive_name] += ", #{noarchive_value}" end end noindex end
ruby
{ "resource": "" }
q13108
MetaTags.MetaTagsCollection.group_attributes_by_key
train
def group_attributes_by_key(attributes) Hash[attributes.group_by(&:first).map { |k, v| [k, v.map(&:last).tap(&:compact!).join(', ')] }] end
ruby
{ "resource": "" }
q13109
MetaTags.Tag.render
train
def render(view) view.tag(name, prepare_attributes(attributes), MetaTags.config.open_meta_tags?) end
ruby
{ "resource": "" }
q13110
MetaTags.TextNormalizer.normalize_description
train
def normalize_description(description) # description could be another object not a string, but since it probably # serves the same purpose we could just as it to convert itself to str # and continue from there description = cleanup_string(description) return '' if description.blank? truncate(description, MetaTags.config.description_limit) end
ruby
{ "resource": "" }
q13111
MetaTags.TextNormalizer.normalize_keywords
train
def normalize_keywords(keywords) keywords = cleanup_strings(keywords) return '' if keywords.blank? keywords.each(&:downcase!) if MetaTags.config.keywords_lowercase separator = cleanup_string MetaTags.config.keywords_separator, strip: false keywords = truncate_array(keywords, MetaTags.config.keywords_limit, separator) safe_join(keywords, separator) end
ruby
{ "resource": "" }
q13112
MetaTags.TextNormalizer.strip_tags
train
def strip_tags(string) if defined?(Loofah) # Instead of strip_tags we will use Loofah to strip tags from now on Loofah.fragment(string).text(encode_special_chars: false) else helpers.strip_tags(string) end end
ruby
{ "resource": "" }
q13113
MetaTags.TextNormalizer.cleanup_string
train
def cleanup_string(string, strip: true) return '' if string.nil? raise ArgumentError, 'Expected a string or an object that implements #to_str' unless string.respond_to?(:to_str) strip_tags(string.to_str).tap do |s| s.gsub!(/\s+/, ' ') s.strip! if strip end end
ruby
{ "resource": "" }
q13114
MetaTags.TextNormalizer.cleanup_strings
train
def cleanup_strings(strings, strip: true) strings = Array(strings).flatten.map! { |s| cleanup_string(s, strip: strip) } strings.reject!(&:blank?) strings end
ruby
{ "resource": "" }
q13115
MetaTags.TextNormalizer.truncate
train
def truncate(string, limit = nil, natural_separator = ' ') return string if limit.to_i == 0 # rubocop:disable Lint/NumberConversion helpers.truncate( string, length: limit, separator: natural_separator, omission: '', escape: true, ) end
ruby
{ "resource": "" }
q13116
MetaTags.TextNormalizer.truncate_array
train
def truncate_array(string_array, limit = nil, separator = '', natural_separator = ' ') return string_array if limit.nil? || limit <= 0 length = 0 result = [] string_array.each do |string| limit_left = calculate_limit_left(limit, length, result, separator) if string.length > limit_left result << truncate(string, limit_left, natural_separator) break end length += (result.any? ? separator.length : 0) + string.length result << string # No more strings will fit break if length + separator.length >= limit end result end
ruby
{ "resource": "" }
q13117
MetaTags.Renderer.render
train
def render(view) tags = [] render_charset(tags) render_title(tags) render_icon(tags) render_with_normalization(tags, :description) render_with_normalization(tags, :keywords) render_refresh(tags) render_noindex(tags) render_alternate(tags) render_open_search(tags) render_links(tags) render_hashes(tags) render_custom(tags) tags.tap(&:compact!).map! { |tag| tag.render(view) } view.safe_join tags, MetaTags.config.minify_output ? "" : "\n" end
ruby
{ "resource": "" }
q13118
MetaTags.Renderer.render_charset
train
def render_charset(tags) charset = meta_tags.extract(:charset) tags << Tag.new(:meta, charset: charset) if charset.present? end
ruby
{ "resource": "" }
q13119
MetaTags.Renderer.render_title
train
def render_title(tags) normalized_meta_tags[:title] = meta_tags.page_title normalized_meta_tags[:site] = meta_tags[:site] title = meta_tags.extract_full_title normalized_meta_tags[:full_title] = title tags << ContentTag.new(:title, content: title) if title.present? end
ruby
{ "resource": "" }
q13120
MetaTags.Renderer.render_noindex
train
def render_noindex(tags) meta_tags.extract_noindex.each do |name, content| tags << Tag.new(:meta, name: name, content: content) if content.present? end end
ruby
{ "resource": "" }
q13121
MetaTags.Renderer.render_refresh
train
def render_refresh(tags) refresh = meta_tags.extract(:refresh) tags << Tag.new(:meta, 'http-equiv' => 'refresh', content: refresh.to_s) if refresh.present? end
ruby
{ "resource": "" }
q13122
MetaTags.Renderer.render_alternate
train
def render_alternate(tags) alternate = meta_tags.extract(:alternate) return unless alternate if alternate.kind_of?(Hash) alternate.each do |hreflang, href| tags << Tag.new(:link, rel: 'alternate', href: href, hreflang: hreflang) if href.present? end elsif alternate.kind_of?(Array) alternate.each do |link_params| tags << Tag.new(:link, { rel: 'alternate' }.with_indifferent_access.merge(link_params)) end end end
ruby
{ "resource": "" }
q13123
MetaTags.Renderer.render_open_search
train
def render_open_search(tags) open_search = meta_tags.extract(:open_search) return unless open_search href = open_search[:href] title = open_search[:title] type = "application/opensearchdescription+xml" tags << Tag.new(:link, rel: 'search', type: type, href: href, title: title) if href.present? end
ruby
{ "resource": "" }
q13124
MetaTags.Renderer.render_links
train
def render_links(tags) [ :amphtml, :canonical, :prev, :next, :image_src ].each do |tag_name| href = meta_tags.extract(tag_name) if href.present? @normalized_meta_tags[tag_name] = href tags << Tag.new(:link, rel: tag_name, href: href) end end end
ruby
{ "resource": "" }
q13125
MetaTags.Renderer.render_hashes
train
def render_hashes(tags, **opts) meta_tags.meta_tags.each_key do |property| render_hash(tags, property, **opts) end end
ruby
{ "resource": "" }
q13126
MetaTags.Renderer.render_hash
train
def render_hash(tags, key, **opts) data = meta_tags.meta_tags[key] return unless data.kind_of?(Hash) process_hash(tags, key, data, **opts) meta_tags.extract(key) end
ruby
{ "resource": "" }
q13127
MetaTags.Renderer.render_custom
train
def render_custom(tags) meta_tags.meta_tags.each do |name, data| Array(data).each do |val| tags << Tag.new(:meta, configured_name_key(name) => name, content: val) end meta_tags.extract(name) end end
ruby
{ "resource": "" }
q13128
MetaTags.Renderer.process_tree
train
def process_tree(tags, property, content, **opts) method = case content when Hash :process_hash when Array :process_array else :render_tag end __send__(method, tags, property, content, **opts) end
ruby
{ "resource": "" }
q13129
AhoyEmail.Processor.trackable?
train
def trackable?(uri) uri && uri.absolute? && %w(http https).include?(uri.scheme) end
ruby
{ "resource": "" }
q13130
Geokit.IpGeocodeLookup.retrieve_location_from_cookie_or_service
train
def retrieve_location_from_cookie_or_service return GeoLoc.new(YAML.load(cookies[:geo_location])) if cookies[:geo_location] location = Geocoders::MultiGeocoder.geocode(get_ip_address) return location.success ? location : nil end
ruby
{ "resource": "" }
q13131
Protobuf.Message.to_json_hash
train
def to_json_hash result = {} @values.each_key do |field_name| value = self[field_name] field = self.class.get_field(field_name, true) # NB: to_json_hash_value should come before json_encode so as to handle # repeated fields without extra logic. hashed_value = if value.respond_to?(:to_json_hash_value) value.to_json_hash_value elsif field.respond_to?(:json_encode) field.json_encode(value) else value end result[field.name] = hashed_value end result end
ruby
{ "resource": "" }
q13132
Alipay.Client.page_execute_url
train
def page_execute_url(params) params = prepare_params(params) uri = URI(@url) uri.query = URI.encode_www_form(params) uri.to_s end
ruby
{ "resource": "" }
q13133
Alipay.Client.page_execute_form
train
def page_execute_form(params) params = prepare_params(params) html = %Q(<form id='alipaysubmit' name='alipaysubmit' action='#{@url}' method='POST'>) params.each do |key, value| html << %Q(<input type='hidden' name='#{key}' value='#{value.gsub("'", "&apos;")}'/>) end html << "<input type='submit' value='ok' style='display:none'></form>" html << "<script>document.forms['alipaysubmit'].submit();</script>" html end
ruby
{ "resource": "" }
q13134
Alipay.Client.execute
train
def execute(params) params = prepare_params(params) Net::HTTP.post_form(URI(@url), params).body end
ruby
{ "resource": "" }
q13135
Alipay.Client.sign
train
def sign(params) string = params_to_string(params) case @sign_type when 'RSA' ::Alipay::Sign::RSA.sign(@app_private_key, string) when 'RSA2' ::Alipay::Sign::RSA2.sign(@app_private_key, string) else raise "Unsupported sign_type: #{@sign_type}" end end
ruby
{ "resource": "" }
q13136
Alipay.Client.verify?
train
def verify?(params) params = Utils.stringify_keys(params) return false if params['sign_type'] != @sign_type sign = params.delete('sign') # sign_type does not use in notify sign params.delete('sign_type') string = params_to_string(params) case @sign_type when 'RSA' ::Alipay::Sign::RSA.verify?(@alipay_public_key, string, sign) when 'RSA2' ::Alipay::Sign::RSA2.verify?(@alipay_public_key, string, sign) else raise "Unsupported sign_type: #{@sign_type}" end end
ruby
{ "resource": "" }
q13137
Authlogic.Config.rw_config
train
def rw_config(key, value, default_value = nil) if value.nil? acts_as_authentic_config.include?(key) ? acts_as_authentic_config[key] : default_value else self.acts_as_authentic_config = acts_as_authentic_config.merge(key => value) value end end
ruby
{ "resource": "" }
q13138
Mutations.ModelFilter.initialize_constants!
train
def initialize_constants! @initialize_constants ||= begin class_const = options[:class] || @name.to_s.camelize class_const = class_const.constantize if class_const.is_a?(String) options[:class] = class_const if options[:builder] options[:builder] = options[:builder].constantize if options[:builder].is_a?(String) end true end unless Mutations.cache_constants? options[:class] = options[:class].to_s.constantize if options[:class] options[:builder] = options[:builder].to_s.constantize if options[:builder] end end
ruby
{ "resource": "" }
q13139
Mongo.Client.cluster_options
train
def cluster_options # We share clusters when a new client with different CRUD_OPTIONS # is requested; therefore, cluster should not be getting any of these # options upon instantiation options.reject do |key, value| CRUD_OPTIONS.include?(key.to_sym) end.merge( server_selection_semaphore: @server_selection_semaphore, # but need to put the database back in for auth... database: options[:database], # Put these options in for legacy compatibility, but note that # their values on the client and the cluster do not have to match - # applications should read these values from client, not from cluster max_read_retries: options[:max_read_retries], read_retry_interval: options[:read_retry_interval], ) end
ruby
{ "resource": "" }
q13140
Mongo.Client.with
train
def with(new_options = Options::Redacted.new) clone.tap do |client| opts = validate_options!(new_options) client.options.update(opts) Database.create(client) # We can't use the same cluster if some options that would affect it # have changed. if cluster_modifying?(opts) Cluster.create(client) end end end
ruby
{ "resource": "" }
q13141
Mongo.Client.reconnect
train
def reconnect addresses = cluster.addresses.map(&:to_s) @cluster.disconnect! rescue nil @cluster = Cluster.new(addresses, monitoring, cluster_options) true end
ruby
{ "resource": "" }
q13142
Mongo.Client.database_names
train
def database_names(filter = {}, opts = {}) list_databases(filter, true, opts).collect{ |info| info[Database::NAME] } end
ruby
{ "resource": "" }
q13143
Mongo.Client.list_databases
train
def list_databases(filter = {}, name_only = false, opts = {}) cmd = { listDatabases: 1 } cmd[:nameOnly] = !!name_only cmd[:filter] = filter unless filter.empty? use(Database::ADMIN).command(cmd, opts).first[Database::DATABASES] end
ruby
{ "resource": "" }
q13144
Mongo.Client.start_session
train
def start_session(options = {}) cluster.send(:get_session, self, options.merge(implicit: false)) || (raise Error::InvalidSession.new(Session::SESSIONS_NOT_SUPPORTED)) end
ruby
{ "resource": "" }
q13145
Mongo.DBRef.as_json
train
def as_json(*args) document = { COLLECTION => collection, ID => id } document.merge!(DATABASE => database) if database document end
ruby
{ "resource": "" }
q13146
Mongo.DBRef.to_bson
train
def to_bson(buffer = BSON::ByteBuffer.new, validating_keys = BSON::Config.validating_keys?) as_json.to_bson(buffer) end
ruby
{ "resource": "" }
q13147
Mongo.Cluster.disconnect!
train
def disconnect!(wait=false) unless @connecting || @connected return true end @periodic_executor.stop! @servers.each do |server| if server.connected? server.disconnect!(wait) publish_sdam_event( Monitoring::SERVER_CLOSED, Monitoring::Event::ServerClosed.new(server.address, topology) ) end end publish_sdam_event( Monitoring::TOPOLOGY_CLOSED, Monitoring::Event::TopologyClosed.new(topology) ) @connecting = @connected = false true end
ruby
{ "resource": "" }
q13148
Mongo.Cluster.reconnect!
train
def reconnect! @connecting = true scan! servers.each do |server| server.reconnect! end @periodic_executor.restart! @connecting = false @connected = true end
ruby
{ "resource": "" }
q13149
Mongo.Cluster.scan!
train
def scan!(sync=true) if sync servers_list.each do |server| server.scan! end else servers_list.each do |server| server.monitor.scan_semaphore.signal end end true end
ruby
{ "resource": "" }
q13150
Mongo.Cluster.update_cluster_time
train
def update_cluster_time(result) if cluster_time_doc = result.cluster_time @cluster_time_lock.synchronize do if @cluster_time.nil? @cluster_time = cluster_time_doc elsif cluster_time_doc[CLUSTER_TIME] > @cluster_time[CLUSTER_TIME] @cluster_time = cluster_time_doc end end end end
ruby
{ "resource": "" }
q13151
Mongo.Cluster.add
train
def add(host, add_options=nil) address = Address.new(host, options) if !addresses.include?(address) server = Server.new(address, self, @monitoring, event_listeners, options.merge( monitor: false)) @update_lock.synchronize { @servers.push(server) } if add_options.nil? || add_options[:monitor] != false server.start_monitoring end server end end
ruby
{ "resource": "" }
q13152
Mongo.Cluster.remove
train
def remove(host) address = Address.new(host) removed_servers = @servers.select { |s| s.address == address } @update_lock.synchronize { @servers = @servers - removed_servers } removed_servers.each do |server| if server.connected? server.disconnect! publish_sdam_event( Monitoring::SERVER_CLOSED, Monitoring::Event::ServerClosed.new(address, topology) ) end end removed_servers.any? end
ruby
{ "resource": "" }
q13153
Mongo.Address.socket
train
def socket(socket_timeout, ssl_options = {}, options = {}) create_resolver(ssl_options).socket(socket_timeout, ssl_options, options) end
ruby
{ "resource": "" }
q13154
Mongo.BulkWrite.execute
train
def execute operation_id = Monitoring.next_operation_id result_combiner = ResultCombiner.new operations = op_combiner.combine client.send(:with_session, @options) do |session| operations.each do |operation| if single_statement?(operation) write_with_retry(session, write_concern) do |server, txn_num| execute_operation( operation.keys.first, operation.values.flatten, server, operation_id, result_combiner, session, txn_num) end else legacy_write_with_retry do |server| execute_operation( operation.keys.first, operation.values.flatten, server, operation_id, result_combiner, session) end end end end result_combiner.result end
ruby
{ "resource": "" }
q13155
Mongo.SDAM.find_server
train
def find_server(client, address_str) client.cluster.servers_list.detect{ |s| s.address.to_s == address_str } end
ruby
{ "resource": "" }
q13156
Mongo.URI.apply_transform
train
def apply_transform(key, value, type) if type if respond_to?("convert_#{type}", true) send("convert_#{type}", key, value) else send(type, value) end else value end end
ruby
{ "resource": "" }
q13157
Mongo.URI.merge_uri_option
train
def merge_uri_option(target, value, name) if target.key?(name) if REPEATABLE_OPTIONS.include?(name) target[name] += value else log_warn("Repeated option key: #{name}.") end else target.merge!(name => value) end end
ruby
{ "resource": "" }
q13158
Mongo.URI.add_uri_option
train
def add_uri_option(key, strategy, value, uri_options) target = select_target(uri_options, strategy[:group]) value = apply_transform(key, value, strategy[:type]) merge_uri_option(target, value, strategy[:name]) end
ruby
{ "resource": "" }
q13159
Mongo.URI.auth_mech_props
train
def auth_mech_props(value) properties = hash_extractor('authMechanismProperties', value) if properties[:canonicalize_host_name] properties.merge!(canonicalize_host_name: %w(true TRUE).include?(properties[:canonicalize_host_name])) end properties end
ruby
{ "resource": "" }
q13160
Mongo.URI.zlib_compression_level
train
def zlib_compression_level(value) if /\A-?\d+\z/ =~ value i = value.to_i if i >= -1 && i <= 9 return i end end log_warn("#{value} is not a valid zlibCompressionLevel") nil end
ruby
{ "resource": "" }
q13161
Mongo.URI.inverse_bool
train
def inverse_bool(name, value) b = convert_bool(name, value) if b.nil? nil else !b end end
ruby
{ "resource": "" }
q13162
Mongo.URI.max_staleness
train
def max_staleness(value) if /\A\d+\z/ =~ value int = value.to_i if int >= 0 && int < 90 log_warn("max staleness must be either 0 or greater than 90: #{value}") end return int end log_warn("Invalid max staleness value: #{value}") nil end
ruby
{ "resource": "" }
q13163
Mongo.URI.hash_extractor
train
def hash_extractor(name, value) value.split(',').reduce({}) do |set, tag| k, v = tag.split(':') if v.nil? log_warn("Invalid hash value for #{name}: #{value}") return nil end set.merge(decode(k).downcase.to_sym => decode(v)) end end
ruby
{ "resource": "" }
q13164
Mongo.Cursor.each
train
def each process(@initial_result).each { |doc| yield doc } while more? return kill_cursors if exhausted? get_more.each { |doc| yield doc } end end
ruby
{ "resource": "" }
q13165
Mongo.Server.disconnect!
train
def disconnect!(wait=false) begin # For backwards compatibility we disconnect/clear the pool rather # than close it here. pool.disconnect! rescue Error::PoolClosedError # If the pool was already closed, we don't need to do anything here. end monitor.stop!(wait) @connected = false true end
ruby
{ "resource": "" }
q13166
Mongo.Server.start_monitoring
train
def start_monitoring publish_sdam_event( Monitoring::SERVER_OPENING, Monitoring::Event::ServerOpening.new(address, cluster.topology) ) if options[:monitoring_io] != false monitor.run! ObjectSpace.define_finalizer(self, self.class.finalize(monitor)) end end
ruby
{ "resource": "" }
q13167
Mongo.Server.matches_tag_set?
train
def matches_tag_set?(tag_set) tag_set.keys.all? do |k| tags[k] && tags[k] == tag_set[k] end end
ruby
{ "resource": "" }
q13168
Mongo.Server.handle_auth_failure!
train
def handle_auth_failure! yield rescue Mongo::Error::SocketTimeoutError # possibly cluster is slow, do not give up on it raise rescue Mongo::Error::SocketError # non-timeout network error unknown! pool.disconnect! raise rescue Auth::Unauthorized # auth error, keep server description and topology as they are pool.disconnect! raise end
ruby
{ "resource": "" }
q13169
Mongo.Benchmarking.load_file
train
def load_file(file_name) File.open(file_name, "r") do |f| f.each_line.collect do |line| parse_json(line) end end end
ruby
{ "resource": "" }
q13170
Mongo.Auth.get
train
def get(user) mechanism = user.mechanism raise InvalidMechanism.new(mechanism) if !SOURCES.has_key?(mechanism) SOURCES[mechanism].new(user) end
ruby
{ "resource": "" }
q13171
Mongo.Monitoring.started
train
def started(topic, event) subscribers_for(topic).each{ |subscriber| subscriber.started(event) } end
ruby
{ "resource": "" }
q13172
Mongo.Monitoring.succeeded
train
def succeeded(topic, event) subscribers_for(topic).each{ |subscriber| subscriber.succeeded(event) } end
ruby
{ "resource": "" }
q13173
Mongo.Monitoring.failed
train
def failed(topic, event) subscribers_for(topic).each{ |subscriber| subscriber.failed(event) } end
ruby
{ "resource": "" }
q13174
Mongo.WriteConcern.get
train
def get(options) return options if options.is_a?(Unacknowledged) || options.is_a?(Acknowledged) if options validate!(options) if unacknowledged?(options) Unacknowledged.new(options) else Acknowledged.new(options) end end end
ruby
{ "resource": "" }
q13175
Mongo.Database.command
train
def command(operation, opts = {}) txn_read_pref = if opts[:session] && opts[:session].in_transaction? opts[:session].txn_read_preference else nil end txn_read_pref ||= opts[:read] || ServerSelector::PRIMARY Lint.validate_underscore_read_preference(txn_read_pref) preference = ServerSelector.get(txn_read_pref) client.send(:with_session, opts) do |session| read_with_retry(session, preference) do |server| Operation::Command.new({ :selector => operation.dup, :db_name => name, :read => preference, :session => session }).execute(server) end end end
ruby
{ "resource": "" }
q13176
Mongo.Database.drop
train
def drop(options = {}) operation = { :dropDatabase => 1 } client.send(:with_session, options) do |session| Operation::DropDatabase.new({ selector: operation, db_name: name, write_concern: write_concern, session: session }).execute(next_primary) end end
ruby
{ "resource": "" }
q13177
Mongo.Socket.read
train
def read(length) handle_errors do data = read_from_socket(length) raise IOError unless (data.length > 0 || length == 0) while data.length < length chunk = read_from_socket(length - data.length) raise IOError unless (chunk.length > 0 || length == 0) data << chunk end data end end
ruby
{ "resource": "" }
q13178
Mongo.Session.end_session
train
def end_session if !ended? && @client if within_states?(TRANSACTION_IN_PROGRESS_STATE) begin abort_transaction rescue Mongo::Error end end @client.cluster.session_pool.checkin(@server_session) end ensure @server_session = nil end
ruby
{ "resource": "" }
q13179
Mongo.Session.add_txn_num!
train
def add_txn_num!(command) command.tap do |c| c[:txnNumber] = BSON::Int64.new(@server_session.txn_num) if in_transaction? end end
ruby
{ "resource": "" }
q13180
Mongo.Session.add_txn_opts!
train
def add_txn_opts!(command, read) command.tap do |c| # The read preference should be added for all read operations. if read && txn_read_pref = txn_read_preference Mongo::Lint.validate_underscore_read_preference(txn_read_pref) txn_read_pref = txn_read_pref.dup txn_read_pref[:mode] = txn_read_pref[:mode].to_s.gsub(/(_\w)/) { |match| match[1].upcase } Mongo::Lint.validate_camel_case_read_preference(txn_read_pref) c['$readPreference'] = txn_read_pref end # The read concern should be added to any command that starts a transaction. if starting_transaction? # https://jira.mongodb.org/browse/SPEC-1161: transaction's # read concern overrides collection/database/client read concerns, # even if transaction's read concern is not set. # Read concern here is the one sent to the server and may # include afterClusterTime. if rc = c[:readConcern] rc = rc.dup rc.delete(:level) end if txn_read_concern if rc rc.update(txn_read_concern) else rc = txn_read_concern.dup end end if rc.nil? || rc.empty? c.delete(:readConcern) else c[:readConcern ] = rc end end # We need to send the read concern level as a string rather than a symbol. if c[:readConcern] && c[:readConcern][:level] c[:readConcern][:level] = c[:readConcern][:level].to_s end # The write concern should be added to any abortTransaction or commitTransaction command. if (c[:abortTransaction] || c[:commitTransaction]) if @already_committed wc = BSON::Document.new(c[:writeConcern] || txn_write_concern || {}) wc.merge!(w: :majority) wc[:wtimeout] ||= 10000 c[:writeConcern] = wc elsif txn_write_concern c[:writeConcern] ||= txn_write_concern end end # A non-numeric write concern w value needs to be sent as a string rather than a symbol. if c[:writeConcern] && c[:writeConcern][:w] && c[:writeConcern][:w].is_a?(Symbol) c[:writeConcern][:w] = c[:writeConcern][:w].to_s end end end
ruby
{ "resource": "" }
q13181
Mongo.Session.validate_read_preference!
train
def validate_read_preference!(command) return unless in_transaction? && non_primary_read_preference_mode?(command) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation::INVALID_READ_PREFERENCE) end
ruby
{ "resource": "" }
q13182
Mongo.Session.start_transaction
train
def start_transaction(options = nil) if options Lint.validate_read_concern_option(options[:read_concern]) end check_if_ended! if within_states?(STARTING_TRANSACTION_STATE, TRANSACTION_IN_PROGRESS_STATE) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation::TRANSACTION_ALREADY_IN_PROGRESS) end next_txn_num @txn_options = options || @options[:default_transaction_options] || {} if txn_write_concern && WriteConcern.send(:unacknowledged?, txn_write_concern) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation::UNACKNOWLEDGED_WRITE_CONCERN) end @state = STARTING_TRANSACTION_STATE @already_committed = false end
ruby
{ "resource": "" }
q13183
Mongo.Session.commit_transaction
train
def commit_transaction(options=nil) check_if_ended! check_if_no_transaction! if within_states?(TRANSACTION_ABORTED_STATE) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation.cannot_call_after_msg( :abortTransaction, :commitTransaction)) end options ||= {} begin # If commitTransaction is called twice, we need to run the same commit # operation again, so we revert the session to the previous state. if within_states?(TRANSACTION_COMMITTED_STATE) @state = @last_commit_skipped ? STARTING_TRANSACTION_STATE : TRANSACTION_IN_PROGRESS_STATE @already_committed = true end if starting_transaction? @last_commit_skipped = true else @last_commit_skipped = false write_concern = options[:write_concern] || txn_options[:write_concern] if write_concern && !write_concern.is_a?(WriteConcern::Base) write_concern = WriteConcern.get(write_concern) end write_with_retry(self, write_concern, true) do |server, txn_num, is_retry| if is_retry if write_concern wco = write_concern.options.merge(w: :majority) wco[:wtimeout] ||= 10000 write_concern = WriteConcern.get(wco) else write_concern = WriteConcern.get(w: :majority, wtimeout: 10000) end end Operation::Command.new( selector: { commitTransaction: 1 }, db_name: 'admin', session: self, txn_num: txn_num, write_concern: write_concern, ).execute(server) end end rescue Mongo::Error::NoServerAvailable, Mongo::Error::SocketError => e e.send(:add_label, Mongo::Error::UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL) raise e rescue Mongo::Error::OperationFailure => e err_doc = e.instance_variable_get(:@result).send(:first_document) if e.write_retryable? || (err_doc['writeConcernError'] && !UNLABELED_WRITE_CONCERN_CODES.include?(err_doc['writeConcernError']['code'])) e.send(:add_label, Mongo::Error::UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL) end raise e ensure @state = TRANSACTION_COMMITTED_STATE end end
ruby
{ "resource": "" }
q13184
Mongo.Session.abort_transaction
train
def abort_transaction check_if_ended! check_if_no_transaction! if within_states?(TRANSACTION_COMMITTED_STATE) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation.cannot_call_after_msg( :commitTransaction, :abortTransaction)) end if within_states?(TRANSACTION_ABORTED_STATE) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation.cannot_call_twice_msg(:abortTransaction)) end begin unless starting_transaction? write_with_retry(self, txn_options[:write_concern], true) do |server, txn_num| Operation::Command.new( selector: { abortTransaction: 1 }, db_name: 'admin', session: self, txn_num: txn_num ).execute(server) end end @state = TRANSACTION_ABORTED_STATE rescue Mongo::Error::InvalidTransactionOperation raise rescue Mongo::Error @state = TRANSACTION_ABORTED_STATE rescue Exception @state = TRANSACTION_ABORTED_STATE raise end end
ruby
{ "resource": "" }
q13185
Mongo.Session.with_transaction
train
def with_transaction(options=nil) # Non-configurable 120 second timeout for the entire operation deadline = Time.now + 120 transaction_in_progress = false loop do commit_options = {} if options commit_options[:write_concern] = options[:write_concern] end start_transaction(options) transaction_in_progress = true begin rv = yield self rescue Exception => e if within_states?(STARTING_TRANSACTION_STATE, TRANSACTION_IN_PROGRESS_STATE) abort_transaction transaction_in_progress = false end if Time.now >= deadline transaction_in_progress = false raise end if e.is_a?(Mongo::Error) && e.label?(Mongo::Error::TRANSIENT_TRANSACTION_ERROR_LABEL) next end raise else if within_states?(TRANSACTION_ABORTED_STATE, NO_TRANSACTION_STATE, TRANSACTION_COMMITTED_STATE) transaction_in_progress = false return rv end begin commit_transaction(commit_options) transaction_in_progress = false return rv rescue Mongo::Error => e if e.label?(Mongo::Error::UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL) # WriteConcernFailed if e.is_a?(Mongo::Error::OperationFailure) && e.code == 64 && e.wtimeout? transaction_in_progress = false raise end if Time.now >= deadline transaction_in_progress = false raise end wc_options = case v = commit_options[:write_concern] when WriteConcern::Base v.options when nil {} else v end commit_options[:write_concern] = wc_options.merge(w: :majority) retry elsif e.label?(Mongo::Error::TRANSIENT_TRANSACTION_ERROR_LABEL) if Time.now >= deadline transaction_in_progress = false raise end next else transaction_in_progress = false raise end end end end ensure if transaction_in_progress log_warn('with_transaction callback altered with_transaction loop, aborting transaction') begin abort_transaction rescue Error::OperationFailure, Error::InvalidTransactionOperation end end end
ruby
{ "resource": "" }
q13186
Mongo.Session.txn_read_preference
train
def txn_read_preference rp = txn_options && txn_options[:read_preference] || @client.read_preference Mongo::Lint.validate_underscore_read_preference(rp) rp end
ruby
{ "resource": "" }
q13187
Mongo.ServerSelector.get
train
def get(preference = {}) return preference if PREFERENCES.values.include?(preference.class) Mongo::Lint.validate_underscore_read_preference(preference) PREFERENCES.fetch((preference[:mode] || :primary).to_sym).new(preference) end
ruby
{ "resource": "" }
q13188
Mongo.Retryable.read_with_retry_cursor
train
def read_with_retry_cursor(session, server_selector, view, &block) read_with_retry(session, server_selector) do |server| result = yield server Cursor.new(view, result, server, session: session) end end
ruby
{ "resource": "" }
q13189
Mongo.Retryable.read_with_retry
train
def read_with_retry(session = nil, server_selector = nil, &block) if session.nil? && server_selector.nil? # Older versions of Mongoid call read_with_retry without arguments. # This is already not correct in a MongoDB 3.6+ environment with # sessions. For compatibility we emulate the legacy driver behavior # here but upgrading Mongoid is strongly recommended. unless $_mongo_read_with_retry_warned $_mongo_read_with_retry_warned = true Logger.logger.warn("Legacy read_with_retry invocation - please update the application and/or its dependencies") end # Since we don't have a session, we cannot use the modern read retries. # And we need to select a server but we don't have a server selector. # Use PrimaryPreferred which will work as long as there is a data # bearing node in the cluster; the block may select a different server # which is fine. server_selector = ServerSelector.get(mode: :primary_preferred) legacy_read_with_retry(nil, server_selector, &block) elsif session && session.retry_reads? modern_read_with_retry(session, server_selector, &block) elsif client.max_read_retries > 0 legacy_read_with_retry(session, server_selector, &block) else server = select_server(cluster, server_selector) yield server end end
ruby
{ "resource": "" }
q13190
Mongo.Retryable.read_with_one_retry
train
def read_with_one_retry(options = nil) yield rescue Error::SocketError, Error::SocketTimeoutError => e retry_message = options && options[:retry_message] log_retry(e, message: retry_message) yield end
ruby
{ "resource": "" }
q13191
Mongo.Retryable.write_with_retry
train
def write_with_retry(session, write_concern, ending_transaction = false, &block) if ending_transaction && !session raise ArgumentError, 'Cannot end a transaction without a session' end unless ending_transaction || retry_write_allowed?(session, write_concern) return legacy_write_with_retry(nil, session, &block) end # If we are here, session is not nil. A session being nil would have # failed retry_write_allowed? check. server = cluster.next_primary unless ending_transaction || server.retry_writes? return legacy_write_with_retry(server, session, &block) end begin txn_num = session.in_transaction? ? session.txn_num : session.next_txn_num yield(server, txn_num, false) rescue Error::SocketError, Error::SocketTimeoutError => e if session.in_transaction? && !ending_transaction raise end retry_write(e, txn_num, &block) rescue Error::OperationFailure => e if (session.in_transaction? && !ending_transaction) || !e.write_retryable? raise end retry_write(e, txn_num, &block) end end
ruby
{ "resource": "" }
q13192
Mongo.Retryable.log_retry
train
def log_retry(e, options = nil) message = if options && options[:message] options[:message] else "Retry" end Logger.logger.warn "#{message} due to: #{e.class.name} #{e.message}" end
ruby
{ "resource": "" }
q13193
Mongo.Collection.create
train
def create(opts = {}) operation = { :create => name }.merge(options) operation.delete(:write) server = next_primary if (options[:collation] || options[Operation::COLLATION]) && !server.features.collation_enabled? raise Error::UnsupportedCollation.new end client.send(:with_session, opts) do |session| Operation::Create.new({ selector: operation, db_name: database.name, write_concern: write_concern, session: session }).execute(server) end end
ruby
{ "resource": "" }
q13194
Mongo.Collection.drop
train
def drop(opts = {}) client.send(:with_session, opts) do |session| Operation::Drop.new({ selector: { :drop => name }, db_name: database.name, write_concern: write_concern, session: session }).execute(next_primary) end rescue Error::OperationFailure => ex raise ex unless ex.message =~ /ns not found/ false end
ruby
{ "resource": "" }
q13195
Mongo.Collection.distinct
train
def distinct(field_name, filter = nil, options = {}) View.new(self, filter || {}, options).distinct(field_name, options) end
ruby
{ "resource": "" }
q13196
Mongo.Collection.insert_one
train
def insert_one(document, opts = {}) client.send(:with_session, opts) do |session| write_with_retry(session, write_concern) do |server, txn_num| Operation::Insert.new( :documents => [ document ], :db_name => database.name, :coll_name => name, :write_concern => write_concern, :bypass_document_validation => !!opts[:bypass_document_validation], :options => opts, :id_generator => client.options[:id_generator], :session => session, :txn_num => txn_num ).execute(server) end end end
ruby
{ "resource": "" }
q13197
Mongo.Collection.insert_many
train
def insert_many(documents, options = {}) inserts = documents.map{ |doc| { :insert_one => doc }} bulk_write(inserts, options) end
ruby
{ "resource": "" }
q13198
Mongo.Collection.replace_one
train
def replace_one(filter, replacement, options = {}) find(filter, options).replace_one(replacement, options) end
ruby
{ "resource": "" }
q13199
Mongo.Collection.update_many
train
def update_many(filter, update, options = {}) find(filter, options).update_many(update, options) end
ruby
{ "resource": "" }