idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
2,800 | def commit_data ( sha ) sha = sha . to_s cdata = command_lines ( 'cat-file' , [ 'commit' , sha ] ) process_commit_data ( cdata , sha , 0 ) end | returns useful array of raw commit object data |
2,801 | def read_tree ( treeish , opts = { } ) arr_opts = [ ] arr_opts << "--prefix=#{opts[:prefix]}" if opts [ :prefix ] arr_opts += [ treeish ] command ( 'read-tree' , arr_opts ) end | reads a tree into the current index file |
2,802 | def archive ( sha , file = nil , opts = { } ) opts [ :format ] ||= 'zip' if opts [ :format ] == 'tgz' opts [ :format ] = 'tar' opts [ :add_gzip ] = true end if ! file tempfile = Tempfile . new ( 'archive' ) file = tempfile . path tempfile . close! end arr_opts = [ ] arr_opts << "--format=#{opts[:format]}" if opts [ :format ] arr_opts << "--prefix=#{opts[:prefix]}" if opts [ :prefix ] arr_opts << "--remote=#{opts[:remote]}" if opts [ :remote ] arr_opts << sha arr_opts << '--' << opts [ :path ] if opts [ :path ] command ( 'archive' , arr_opts , true , ( opts [ :add_gzip ] ? '| gzip' : '' ) + " > #{escape file}" ) return file end | creates an archive file |
2,803 | def current_command_version output = command ( 'version' , [ ] , false ) version = output [ / \d \. \d \. \d / ] version . split ( '.' ) . collect { | i | i . to_i } end | returns the current version of git as an Array of Fixnums . |
2,804 | def log_common_options ( opts ) arr_opts = [ ] arr_opts << "-#{opts[:count]}" if opts [ :count ] arr_opts << "--no-color" arr_opts << "--since=#{opts[:since]}" if opts [ :since ] . is_a? String arr_opts << "--until=#{opts[:until]}" if opts [ :until ] . is_a? String arr_opts << "--grep=#{opts[:grep]}" if opts [ :grep ] . is_a? String arr_opts << "--author=#{opts[:author]}" if opts [ :author ] . is_a? String arr_opts << "#{opts[:between][0].to_s}..#{opts[:between][1].to_s}" if ( opts [ :between ] && opts [ :between ] . size == 2 ) arr_opts end | Returns an array holding the common options for the log commands |
2,805 | def log_path_options ( opts ) arr_opts = [ ] arr_opts << opts [ :object ] if opts [ :object ] . is_a? String arr_opts << '--' << opts [ :path_limiter ] if opts [ :path_limiter ] arr_opts end | Retrurns an array holding path options for the log commands |
2,806 | def is_local_branch? ( branch ) branch_names = self . branches . local . map { | b | b . name } branch_names . include? ( branch ) end | returns + true + if the branch exists locally |
2,807 | def is_remote_branch? ( branch ) branch_names = self . branches . remote . map { | b | b . name } branch_names . include? ( branch ) end | returns + true + if the branch exists remotely |
2,808 | def is_branch? ( branch ) branch_names = self . branches . map { | b | b . name } branch_names . include? ( branch ) end | returns + true + if the branch exists |
2,809 | def commit_all ( message , opts = { } ) opts = { :add_all => true } . merge ( opts ) self . lib . commit ( message , opts ) end | commits all pending changes in the index file to the git repository but automatically adds all modified files without having to explicitly calling |
2,810 | def with_index ( new_index ) old_index = @index set_index ( new_index , false ) return_value = yield @index set_index ( old_index ) return_value end | LOWER LEVEL INDEX OPERATIONS |
2,811 | def rows_generator include_meta_data = false , use_simple_rows_format = false path = if @sheetfile . start_with? "/xl/" or @sheetfile . start_with? "xl/" then @sheetfile else "xl/#{@sheetfile}" end if @book . files . file . exist? ( path ) opener = Nokogiri :: XML :: Reader :: TYPE_ELEMENT closer = Nokogiri :: XML :: Reader :: TYPE_END_ELEMENT Enumerator . new do | y | row , cells , cell = nil , { } , nil cell_type = nil cell_style_idx = nil @book . files . file . open ( path ) do | xml | Nokogiri :: XML :: Reader . from_io ( xml ) . each do | node | if ( node . name . eql? 'row' ) and ( node . node_type . eql? opener ) row = node . attributes row [ 'cells' ] = Hash . new cells = Hash . new y << ( include_meta_data ? row : cells ) if node . self_closing? elsif ( node . name . eql? 'row' ) and ( node . node_type . eql? closer ) processed_cells = fill_in_empty_cells ( cells , row [ 'r' ] , cell , use_simple_rows_format ) if @images_present processed_cells . each do | cell_name , cell_value | next unless cell_value . nil? processed_cells [ cell_name ] = images_at ( cell_name ) end end row [ 'cells' ] = processed_cells y << ( include_meta_data ? row : processed_cells ) elsif ( node . name . eql? 'c' ) and ( node . node_type . eql? opener ) cell_type = node . attributes [ 't' ] cell_style_idx = node . attributes [ 's' ] cell = node . attributes [ 'r' ] elsif ( [ 'v' , 't' ] . include? node . name ) and ( node . node_type . eql? opener ) unless cell . nil? node . read cells [ ( use_simple_rows_format ? cell . tr ( "0-9" , "" ) : cell ) ] = convert ( node . value , cell_type , cell_style_idx ) end end end end end end end | Returns a hash per row that includes the cell ids and values . Empty cells will be also included in the hash with a nil value . |
2,812 | def fill_in_empty_cells ( cells , row_number , last_col , use_simple_rows_format ) new_cells = Hash . new unless cells . empty? last_col = last_col . gsub ( row_number , '' ) ( "A" .. last_col ) . to_a . each do | column | id = use_simple_rows_format ? "#{column}" : "#{column}#{row_number}" new_cells [ id ] = cells [ id ] end end new_cells end | The unzipped XML file does not contain any node for empty cells . Empty cells are being padded in using this function |
2,813 | def extract_drawing_filepath sheet_filepath = "xl/#{@sheetfile}" drawing = parse_xml ( sheet_filepath ) . css ( 'drawing' ) . first return if drawing . nil? drawing_rid = drawing . attributes [ 'id' ] . value sheet_rels_filepath = expand_to_rels_path ( sheet_filepath ) parse_xml ( sheet_rels_filepath ) . css ( "Relationship[@Id='#{drawing_rid}']" ) . first . attributes [ 'Target' ] . value end | Find drawing filepath for the current sheet . Sheet xml contains drawing relationship ID . Sheet relationships xml contains drawing file s location . |
2,814 | def log ( level , * args ) return 'disabled' unless enabled? message , exception , extra , context = extract_arguments ( args ) use_exception_level_filters = use_exception_level_filters? ( extra ) return 'ignored' if ignored? ( exception , use_exception_level_filters ) begin status = call_before_process ( :level => level , :exception => exception , :message => message , :extra => extra ) return 'ignored' if status == 'ignored' rescue Rollbar :: Ignore return 'ignored' end level = lookup_exception_level ( level , exception , use_exception_level_filters ) begin report ( level , message , exception , extra , context ) rescue StandardError , SystemStackError => e report_internal_error ( e ) 'error' end end | Sends a report to Rollbar . |
2,815 | def process_from_async_handler ( payload ) payload = Rollbar :: JSON . load ( payload ) if payload . is_a? ( String ) item = Item . build_with ( payload , :notifier => self , :configuration => configuration , :logger => logger ) Rollbar . silenced do begin process_item ( item ) rescue StandardError => e report_internal_error ( e ) raise end end end | We will reraise exceptions in this method so async queues can retry the job or in general handle an error report some way . |
2,816 | def report_internal_error ( exception ) log_error '[Rollbar] Reporting internal error encountered while sending data to Rollbar.' configuration . execute_hook ( :on_report_internal_error , exception ) begin item = build_item ( 'error' , nil , exception , { :internal => true } , nil ) rescue StandardError => e send_failsafe ( 'build_item in exception_data' , e ) log_error "[Rollbar] Exception: #{exception}" return end begin process_item ( item ) rescue StandardError => e send_failsafe ( 'error in process_item' , e ) log_error "[Rollbar] Item: #{item}" return end begin log_instance_link ( item [ 'data' ] ) rescue StandardError => e send_failsafe ( 'error logging instance link' , e ) log_error "[Rollbar] Item: #{item}" return end end | Reports an internal error in the Rollbar library . This will be reported within the configured Rollbar project . We ll first attempt to provide a report including the exception traceback . If that fails we ll fall back to a more static failsafe response . |
2,817 | def build_item ( level , message , exception , extra , context ) options = { :level => level , :message => message , :exception => exception , :extra => extra , :configuration => configuration , :logger => logger , :scope => scope_object , :notifier => self , :context => context } item = Item . new ( options ) item . build item end | Payload building functions |
2,818 | def bind ( var , typ , force : false ) raise RuntimeError , "Can't update variable with fixed type" if ! force && @env [ var ] && @env [ var ] [ :fixed ] result = Env . new result . env = @env . merge ( var => { type : typ , fixed : false } ) return result end | force should only be used with care! currently only used when type is being refined to a subtype in a lexical scope |
2,819 | def merge ( other ) result = Env . new result . env = @env . merge ( other . env ) return result end | merges bindings in self with bindings in other preferring bindings in other if there is a common key |
2,820 | def match ( other ) other = other . type if other . instance_of? AnnotatedArgType return true if other . instance_of? WildQuery return false unless other . instance_of? MethodType return false unless @ret . match ( other . ret ) if @block == nil return false unless other . block == nil else return false if other . block == nil return false unless @block . match ( other . block ) end states = [ [ 0 , 0 ] ] until states . empty? s_arg , o_arg = states . pop return true if s_arg == @args . size && o_arg == other . args . size next if s_arg >= @args . size if @args [ s_arg ] . instance_of? DotsQuery then if o_arg == other . args . size states << [ s_arg + 1 , o_arg ] else states << [ s_arg + 1 , o_arg + 1 ] states << [ s_arg , o_arg + 1 ] end else next if o_arg == other . args . size s_arg_t = @args [ s_arg ] s_arg_t = s_arg_t . type if s_arg_t . instance_of? AnnotatedArgType o_arg_t = other . args [ o_arg ] o_arg_t = o_arg_t . type if o_arg_t . instance_of? AnnotatedArgType next unless s_arg_t . match ( o_arg_t ) states << [ s_arg + 1 , o_arg + 1 ] end end return false end | other may not be a query |
2,821 | def tinymce ( config = :default , options = { } ) javascript_tag ( nonce : true ) do unless @_tinymce_configurations_added concat tinymce_configurations_javascript concat "\n" @_tinymce_configurations_added = true end concat tinymce_javascript ( config , options ) end end | Initializes TinyMCE on the current page based on the global configuration . |
2,822 | def tinymce_javascript ( config = :default , options = { } ) options , config = config , :default if config . is_a? ( Hash ) options = Configuration . new ( options ) "TinyMCERails.initialize('#{config}', #{options.to_javascript});" . html_safe end | Returns the JavaScript code required to initialize TinyMCE . |
2,823 | def tinymce_configurations_javascript ( options = { } ) javascript = [ ] TinyMCE :: Rails . each_configuration do | name , config | config = config . merge ( options ) if options . present? javascript << "TinyMCERails.configuration.#{name} = #{config.to_javascript};" . html_safe end safe_join ( javascript , "\n" ) end | Returns the JavaScript code for initializing each configuration defined within tinymce . yml . |
2,824 | def devise_verification_code ( mapping , controllers ) resource :paranoid_verification_code , only : [ :show , :update ] , path : mapping . path_names [ :verification_code ] , controller : controllers [ :paranoid_verification_code ] end | route for handle paranoid verification |
2,825 | def password_too_old? return false if new_record? return false unless password_expiration_enabled? return false if expire_password_on_demand? password_changed_at < expire_password_after . seconds . ago end | Is this password older than the configured expiration timeout? |
2,826 | def title ( title = nil , headline = '' ) set_meta_tags ( title : title ) unless title . nil? headline . presence || meta_tags [ :title ] end | Set the page title and return it back . |
2,827 | 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 | Recursively merges a Hash of meta tag attributes into current list . |
2,828 | 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 | Extracts full page title and deletes all related meta tags . |
2,829 | def extract_title title = extract ( :title ) . presence return unless title title = Array ( title ) return title . map ( & :downcase ) if extract ( :lowercase ) == true title end | Extracts page title as an array of segments without site title and separators . |
2,830 | def extract_separator if meta_tags [ :separator ] == false 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 | Extracts title separator as a string . |
2,831 | 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_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 | Extracts noindex settings as a Hash mapping noindex tag name to value . |
2,832 | 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 | Extracts noindex attribute name and value without deleting it from meta tags list . |
2,833 | 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 | Append noarchive attribute if it present . |
2,834 | def group_attributes_by_key ( attributes ) Hash [ attributes . group_by ( & :first ) . map { | k , v | [ k , v . map ( & :last ) . tap ( & :compact! ) . join ( ', ' ) ] } ] end | Convert array of arrays to hashes and concatenate values |
2,835 | def render ( view ) view . tag ( name , prepare_attributes ( attributes ) , MetaTags . config . open_meta_tags? ) end | Initializes a new instance of Tag class . |
2,836 | def normalize_description ( description ) description = cleanup_string ( description ) return '' if description . blank? truncate ( description , MetaTags . config . description_limit ) end | Normalize description value . |
2,837 | 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 | Normalize keywords value . |
2,838 | def strip_tags ( string ) if defined? ( Loofah ) Loofah . fragment ( string ) . text ( encode_special_chars : false ) else helpers . strip_tags ( string ) end end | Strips all HTML tags from the + html + including comments . |
2,839 | 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 | Removes HTML tags and squashes down all the spaces . |
2,840 | def cleanup_strings ( strings , strip : true ) strings = Array ( strings ) . flatten . map! { | s | cleanup_string ( s , strip : strip ) } strings . reject! ( & :blank? ) strings end | Cleans multiple strings up . |
2,841 | def truncate ( string , limit = nil , natural_separator = ' ' ) return string if limit . to_i == 0 helpers . truncate ( string , length : limit , separator : natural_separator , omission : '' , escape : true , ) end | Truncates a string to a specific limit . Return string without truncation when limit 0 or nil |
2,842 | 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 break if length + separator . length >= limit end result end | Truncates a string to a specific limit . |
2,843 | 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 | Initialized a new instance of Renderer . |
2,844 | def render_charset ( tags ) charset = meta_tags . extract ( :charset ) tags << Tag . new ( :meta , charset : charset ) if charset . present? end | Renders charset tag . |
2,845 | 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 | Renders title tag . |
2,846 | 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 | Renders noindex and nofollow meta tags . |
2,847 | def render_refresh ( tags ) refresh = meta_tags . extract ( :refresh ) tags << Tag . new ( :meta , 'http-equiv' => 'refresh' , content : refresh . to_s ) if refresh . present? end | Renders refresh meta tag . |
2,848 | 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 | Renders alternate link tags . |
2,849 | 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 | Renders open_search link tag . |
2,850 | 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 | Renders links . |
2,851 | def render_hashes ( tags , ** opts ) meta_tags . meta_tags . each_key do | property | render_hash ( tags , property , ** opts ) end end | Renders complex hash objects . |
2,852 | 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 | Renders a complex hash object by key . |
2,853 | 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 | Renders custom meta tags . |
2,854 | 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 | Recursive method to process all the hashes and arrays on meta tags |
2,855 | def trackable? ( uri ) uri && uri . absolute? && %w( http https ) . include? ( uri . scheme ) end | Filter trackable URIs i . e . absolute one with http |
2,856 | 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 | Uses the stored location value from the cookie if it exists . If no cookie exists calls out to the web service to get the location . |
2,857 | def to_json_hash result = { } @values . each_key do | field_name | value = self [ field_name ] field = self . class . get_field ( field_name , true ) 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 | Return a hash - representation of the given fields for this message type that is safe to convert to JSON . |
2,858 | def page_execute_url ( params ) params = prepare_params ( params ) uri = URI ( @url ) uri . query = URI . encode_www_form ( params ) uri . to_s end | Generate a url that use to redirect user to Alipay payment page . |
2,859 | 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("'", "'")}'/>) end html << "<input type='submit' value='ok' style='display:none'></form>" html << "<script>document.forms['alipaysubmit'].submit();</script>" html end | Generate a form string that use to render in view and auto POST to Alipay server . |
2,860 | def execute ( params ) params = prepare_params ( params ) Net :: HTTP . post_form ( URI ( @url ) , params ) . body end | Immediately make a API request to Alipay and return response body . |
2,861 | 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 | Generate sign for params . |
2,862 | def verify? ( params ) params = Utils . stringify_keys ( params ) return false if params [ 'sign_type' ] != @sign_type sign = params . delete ( '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 | Verify Alipay notification . |
2,863 | 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 | This is a one - liner method to write a config setting read the config setting and also set a default value for the setting . |
2,864 | 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 | Initialize the model class and builder |
2,865 | def cluster_options options . reject do | key , value | CRUD_OPTIONS . include? ( key . to_sym ) end . merge ( server_selection_semaphore : @server_selection_semaphore , database : options [ :database ] , max_read_retries : options [ :max_read_retries ] , read_retry_interval : options [ :read_retry_interval ] , ) end | Get the hash value of the client . |
2,866 | def with ( new_options = Options :: Redacted . new ) clone . tap do | client | opts = validate_options! ( new_options ) client . options . update ( opts ) Database . create ( client ) if cluster_modifying? ( opts ) Cluster . create ( client ) end end end | Creates a new client with the passed options merged over the existing options of this client . Useful for one - offs to change specific options without altering the original client . |
2,867 | def reconnect addresses = cluster . addresses . map ( & :to_s ) @cluster . disconnect! rescue nil @cluster = Cluster . new ( addresses , monitoring , cluster_options ) true end | Reconnect the client . |
2,868 | def database_names ( filter = { } , opts = { } ) list_databases ( filter , true , opts ) . collect { | info | info [ Database :: NAME ] } end | Get the names of all databases . |
2,869 | 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 | Get info for each database . |
2,870 | def start_session ( options = { } ) cluster . send ( :get_session , self , options . merge ( implicit : false ) ) || ( raise Error :: InvalidSession . new ( Session :: SESSIONS_NOT_SUPPORTED ) ) end | Start a session . |
2,871 | def as_json ( * args ) document = { COLLECTION => collection , ID => id } document . merge! ( DATABASE => database ) if database document end | Get the DBRef as a JSON document |
2,872 | def to_bson ( buffer = BSON :: ByteBuffer . new , validating_keys = BSON :: Config . validating_keys? ) as_json . to_bson ( buffer ) end | Instantiate a new DBRef . |
2,873 | 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 | Disconnect all servers . |
2,874 | def reconnect! @connecting = true scan! servers . each do | server | server . reconnect! end @periodic_executor . restart! @connecting = false @connected = true end | Reconnect all servers . |
2,875 | 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 | Force a scan of all known servers in the cluster . |
2,876 | 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 | Update the max cluster time seen in a response . |
2,877 | 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 | Add a server to the cluster with the provided address . Useful in auto - discovery of new servers when an existing server executes an ismaster and potentially non - configured servers were included . |
2,878 | 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 | Remove the server from the cluster for the provided address if it exists . |
2,879 | def socket ( socket_timeout , ssl_options = { } , options = { } ) create_resolver ( ssl_options ) . socket ( socket_timeout , ssl_options , options ) end | Get a socket for the provided address given the options . |
2,880 | 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 | Execute the bulk write operation . |
2,881 | def find_server ( client , address_str ) client . cluster . servers_list . detect { | s | s . address . to_s == address_str } end | Convenience helper to find a server by it s URI . |
2,882 | 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 | Applies URI value transformation by either using the default cast or a transformation appropriate for the given type . |
2,883 | 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 | Merges a new option into the target . |
2,884 | 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 | Adds an option to the uri options hash via the supplied strategy . |
2,885 | 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 | Auth mechanism properties extractor . |
2,886 | 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 | Parses the zlib compression level . |
2,887 | def inverse_bool ( name , value ) b = convert_bool ( name , value ) if b . nil? nil else ! b end end | Parses a boolean value and returns its inverse . |
2,888 | 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 | Parses the max staleness value which must be either 0 or an integer greater or equal to 90 . |
2,889 | 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 | Extract values from the string and put them into a nested hash . |
2,890 | def each process ( @initial_result ) . each { | doc | yield doc } while more? return kill_cursors if exhausted? get_more . each { | doc | yield doc } end end | Iterate through documents returned from the query . |
2,891 | def disconnect! ( wait = false ) begin pool . disconnect! rescue Error :: PoolClosedError end monitor . stop! ( wait ) @connected = false true end | Disconnect the server from the connection . |
2,892 | 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 | Start monitoring the server . |
2,893 | def matches_tag_set? ( tag_set ) tag_set . keys . all? do | k | tags [ k ] && tags [ k ] == tag_set [ k ] end end | Determine if the provided tags are a subset of the server s tags . |
2,894 | def handle_auth_failure! yield rescue Mongo :: Error :: SocketTimeoutError raise rescue Mongo :: Error :: SocketError unknown! pool . disconnect! raise rescue Auth :: Unauthorized pool . disconnect! raise end | Handle authentication failure . |
2,895 | def load_file ( file_name ) File . open ( file_name , "r" ) do | f | f . each_line . collect do | line | parse_json ( line ) end end end | Load a json file and represent each document as a Hash . |
2,896 | def get ( user ) mechanism = user . mechanism raise InvalidMechanism . new ( mechanism ) if ! SOURCES . has_key? ( mechanism ) SOURCES [ mechanism ] . new ( user ) end | Get the authorization strategy for the provided auth mechanism . |
2,897 | def started ( topic , event ) subscribers_for ( topic ) . each { | subscriber | subscriber . started ( event ) } end | Publish a started event . |
2,898 | def succeeded ( topic , event ) subscribers_for ( topic ) . each { | subscriber | subscriber . succeeded ( event ) } end | Publish a succeeded event . |
2,899 | def failed ( topic , event ) subscribers_for ( topic ) . each { | subscriber | subscriber . failed ( event ) } end | Publish a failed event . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.