idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
21,800
def filelists fl = [ ] @repomd . xpath ( "/xmlns:repomd/xmlns:data[@type=\"filelists\"]/xmlns:location" ) . each do | f | fl << File . join ( @url , f [ 'href' ] ) end fl end
Rasises exception if can t retrieve repomd . xml
21,801
def rewrite_request_block ( auth_type = "ST3DAUTH" ) REXML :: XPath . first ( @request_xml , "//Request" ) . attributes [ "Type" ] = auth_type ops = REXML :: XPath . first ( @request_xml , "//Operation" ) [ "TermUrl" , "MerchantName" ] . each { | e | ops . delete_element e } customer_info = REXML :: XPath . first ( @re...
Rewrites the request according to the response coming from SecureTrading according to the required auth_type This only applies if the inital request was a ST3DCARDQUERY It deletes elements which are not needed for the subsequent request and adds the required additional information if an ST3DAUTH is needed
21,802
def clean print 'Are you sure you want to clean this project directory? (Y|n): ' confirm = $stdin . gets . chomp if confirm != 'Y' && confirm != 'n' puts 'Please enter Y or n' elsif confirm == 'Y' path = options [ :directory ] || Dir . pwd Builder . clean path end end
Cleans out the specified directory
21,803
def wrap ( http_response ) OpenStruct . new . tap do | obj | obj . code = http_response . code . to_i obj . body = http_response . body obj . headers = { } http_response . each_header { | k , v | obj . headers [ k ] = v } end end
HTTPI doesn t support multipart posts . We can work around it by using another gem and handing off something that looks like a HTTPI response
21,804
def clause_valid? if @clause . is_a? ( Hash ) @clause . flatten . find do | e | return true unless ( / \b \b \b \b / ) . match ( e ) . nil? end else return true unless @clause . split . empty? end end
Creates an OrderParser instance based on a clause argument . The instance can then be parsed into a valid ReQON string for queries
21,805
def parse_hash direction = clause . values . first field = clause . keys . first . to_s [ "$order_by" , [ "$#{direction}" , field ] ] end
Parses a hash clause
21,806
def parse_string direction = clause . split [ 1 ] field = clause . split [ 0 ] direction = "asc" unless %w( asc desc ) . include? ( direction ) [ "$order_by" , [ "$#{direction}" , field ] ] end
Parses a string clause defaults direction to asc if missing or invalid
21,807
def run @client . suspended_tickets . each do | suspended_ticket | if should_delete? ( suspended_ticket ) log . info "Deleting: #{suspended_ticket.subject}" suspended_ticket . destroy else log . info "Keeping: #{suspended_ticket.subject}" end end end
Array with delete subjects . Defined in config file
21,808
def summary if @summary . nil? match = Command :: SummaryMatcher . match documentation match . captures . first . strip if match else @summary end end
Returns a short summary for this Command
21,809
def set_color ( opts = { } ) color = Color . new ( opts ) response = put ( 'state' , color . to_h ) response_successful? ( response ) end
Sets the color for the lightbulp .
21,810
def store_state response = get success = ! ! ( response . body =~ %r( ) ) data = JSON . parse ( response . body ) if success @state = data . fetch ( 'state' ) delete_forbidden_stats success end
Stores the current state of the lightbulp .
21,811
def perform ( id , method , * args ) if id begin self . class . find ( id ) . send ( method , * args ) rescue ActiveRecord :: RecordNotFound end else self . class . send ( method , * args ) end end
This will be called by a worker when a job needs to be processed
21,812
def is_subset? ( array1 , array2 ) result = array1 & array2 ( array2 . length == result . length ) end
Checks to see if array2 is subset of array1
21,813
def gitolite_friendly ( permission ) if permission . empty? return nil elsif permission . match ( / / ) return "RW+" elsif permission . match ( / / ) return "RW+" elsif permission . match ( / / ) return 'R' else return nil end end
Converts permission to gitolite friendly permission
21,814
def create_new_environment ( project_root , environment_name ) return error ( _ ( 'wizard.environment.name_exist' ) % { environment : environment_name } ) if Bebox :: Environment . environment_exists? ( project_root , environment_name ) environment = Bebox :: Environment . new ( environment_name , project_root ) output...
Create a new environment
21,815
def remove_environment ( project_root , environment_name ) return error ( _ ( 'wizard.environment.name_not_exist' ) % { environment : environment_name } ) unless Bebox :: Environment . environment_exists? ( project_root , environment_name ) return warn ( _ ( 'wizard.no_changes' ) ) unless confirm_action? ( _ ( 'wizard....
Removes an existing environment
21,816
def write_cache compressed . tap { | c | File . atomic_write ( cache_path ) { | f | f . write ( c ) } } end
Store in cache
21,817
def compressed @compressed ||= case @type when 'css' Sass :: Engine . new ( joined , :syntax => :scss , :cache => false , :style => :compressed ) . render rescue joined when 'js' Uglifier . compile ( joined , :mangle => false , :comments => :none ) rescue joined end end
Compressed joined files
21,818
def joined @joined ||= files . map { | f | File . read ( File . join ( :: Asset . path , @type , f ) ) } . join end
All files joined
21,819
def locations ( params = { } ) args = [ :query , :lat , :lon , :count ] params . each do | k , v | if ! args . include? ( k ) raise ArgumentError . new 'Search term not allowed: ' + k . to_s end end if ! params . include? ( :query ) raise ArgumentError . new '"query" term with location name is required' end results = g...
search for locations
21,820
def restaurants ( params = { } ) args = [ :entity_id , :entity_type , :q , :start , :count , :lat , :lon , :radius , :cuisines , :establishment_type , :collection_id , :category , :sort , :order , :start , :count ] params . each do | k , v | if ! args . include? ( k ) raise ArgumentError . new 'Search term not allowed:...
general search for restaurants
21,821
def get ( object , options = { } ) if options [ :all_pages ] options . delete ( :all_pages ) options [ :page ] = 1 out = [ ] begin data = get ( object , options ) out = out | data options [ :page ] += 1 end while data . count >= 100 return out else if options [ :id ] resp = @connection . get "#{object}/#{options[:id]}"...
Sets up a client
21,822
def matches_mask_array ( masks , strings , casemapping = :rfc1459 ) results = { } masks . each do | mask | strings . each do | string | if matches_mask ( mask , string , casemapping ) results [ mask ] ||= [ ] results [ mask ] << string end end end return results end
Match strings to multiple IRC masks .
21,823
def merge! ( scope ) @options . merge! ( scope . options ) @attributes += scope . attributes @associations . merge! ( scope . associations ) @attributes . uniq! self end
Merges data with given scope .
21,824
def _association ( args , default_options = { } ) return if options . nil? options = args . first if options . is_a? ( Hash ) options = { } . merge ( options ) name = options . keys . first properties = options . delete ( name ) @associations [ name ] = default_options . merge ( { :include => properties } ) . merge ( o...
Duplicates scope .
21,825
def get ( request_path , klass ) response = session . send_request ( 'GET' , path + request_path ) data = response . fetch ( klass . tag ) resource = klass . new ( data . merge ( parent : self ) ) resource . assign_errors ( response ) resource end
Fetch and instantiate a single resource from a path .
21,826
def reload response = session . send_request ( 'GET' , path ) assign_attributes ( response . fetch ( self . class . tag ) ) assign_errors ( response ) self end
Fetch and update this resource from a path .
21,827
def compose ( * enumerables ) res = [ ] enumerables . map ( & :size ) . max . times do tupla = [ ] for enumerable in enumerables tupla << enumerable . shift end res << ( block_given? ? yield ( tupla ) : tupla ) end res end
torna un array on cada element es una tupla formada per un element de cada enumerable . Si se li passa un bloc se li passa al bloc cada tupla i el resultat del bloc s emmagatzema a l array tornat .
21,828
def field ( display , pattern , opts = { } , & block ) actions << lambda { action_for ( :field , { display : display , pattern : pattern } , opts , & block ) } end
Get a field on current page .
21,829
def encrypt ( message ) raise Error , "data must not be empty" if message . to_s . strip . empty? @cipher . reset @cipher . encrypt aes_key = @cipher . random_key aes_iv = @cipher . random_iv encrypted = @cipher . update ( message ) + @cipher . final rsa_encrypted_aes_key = @rsa . public_encrypt ( aes_key ) rsa_encrypt...
1 . Generate random AES key to encrypt message 2 . Use Public Key from the Private key to encrypt AES Key 3 . Prepend encrypted AES key to the encrypted message
21,830
def decrypt ( message , hash : nil ) message = Base64 . decode64 ( message ) hmac = message [ 0 .. 63 ] case when hash && hmac != hash raise Error , "Provided hash mismatch for encrypted file!" when hmac != hmac_signature ( message [ 64 .. - 1 ] ) raise Error , "HMAC signature mismatch for encrypted file!" end rsa_encr...
0 . Base64 decode the encrypted message 1 . Split the string in to the AES key and the encrypted message 2 . Decrypt the AES key using the private key 3 . Decrypt the message using the AES key
21,831
def titulo ( titulo ) tit = titulo . split ( ' ' ) tit . each do | word | if word . length > 3 word . capitalize! else word . downcase! end if word == tit [ 0 ] word . capitalize! end @titulo = tit . join ( ' ' ) end def editorial ( editorial ) @editorial = editorial end def publicacion ( publicacion ) @publicacion = p...
Metodo para guardar el titulo de la referencia
21,832
def to_s string = "" string << @autor << " (" << Date :: MONTHNAMES [ get_publicacion . month ] << " " << get_publicacion . day . to_s << ", " << get_publicacion . year . to_s << "). " << @titulo << ". " << @editorial << ", pp. " << @formato << ", " << @paginas . to_s << " paginas" << "." end
Metodo que nos devuelve la referencia del articulo periodistico formateado
21,833
def to_s string = "" string << @autor << " (" << Date :: MONTHNAMES [ get_publicacion . month ] << " " << get_publicacion . day . to_s << ", " << get_publicacion . year . to_s << "). " << @titulo << @formato << ". " << @editorial << ": " << @edicion << ". Disponible en: " << @url << " (" << Date :: MONTHNAMES [ get_fec...
Metodo que nos devuelve la referencia del documento electronico formateado
21,834
def nest_path_within_parent ( path , params ) return path unless params_include_parent_resource_id? ( params ) params . symbolize_keys! parent_resource = parent_resource_name ( params ) parent_id = params . delete ( parent_resource_param ( params ) ) . try ( :to_s ) File . join ( * [ parent_resource , parent_id , path ...
Nest a given resource path within a parent resource .
21,835
def dispatch name , namespace = nil responses = Hash . new namespaces_to_search = namespace ? [ namespace ] : namespaces namespaces_to_search . each do | namespace | responses [ namespace ] ||= Hash . new responses [ namespace ] [ name ] = @registered_callbacks [ namespace ] [ name ] . call if @registered_callbacks [ n...
Dispatch message to given callback . All named callbacks matching the name will be run in all namespaces in indeterminate order
21,836
def registered? name registration_map = namespaces . map do | namespace | registered_in_namespace? name , namespace end registration_map . any? end
Query if a callback of given name is registered in any namespace
21,837
def read_all_tags ( taglib , id3v2_frames , id3v1_tag = nil , ** opts ) frames = [ ] id3v2_frames . each { | frame_id | frames += id3v2_frames ( taglib , frame_id ) } data = [ ] if frames . empty? data << id3v1_tag ( taglib , id3v1_tag ) unless id3v1_tag . nil? else frames . each { | frame | data << data_from_frame ( f...
gets data from each frame id given only falls back to the id3v1 tag if no id3v2 frames were found
21,838
def run ( suite , type , options = { } ) @conf = Conf . instance reporter = Reporter . new ( type ) reporter . header suite . each do | test | case type when :test run_test ( test ) if expected_exists? ( test ) when :generate if expected_exists? ( test ) run_test ( test , true ) if options [ :overwrite ] else run_test ...
Run a suite of tests
21,839
def cmp_output ( test ) if test . expected_out_exists? && test . expected_err_exists? cmp_out ( test ) cmp_err ( test ) return :success if ( test . out_result && test . err_result ) elsif test . expected_out_exists? cmp_out ( test ) return :success if test . out_result else cmp_err ( test ) return :success if test . er...
Compare the result and expected output of a test that has been run
21,840
def cmp_out ( test ) test . out_result = FileUtils . cmp ( test . expected_out_path , test . result_out_path ) end
Compare a tests expected and result stdout Sets the result of the comparison to out_result in the test
21,841
def cmp_err ( test ) test . err_result = FileUtils . cmp ( test . expected_err_path , test . result_err_path ) end
Compare a tests expected and result stderr Sets the result of the comparison to err_result in the test
21,842
def default_root_key ( object_class ) if ( serializer = ScopedSerializer . find_serializer_by_class ( object_class ) ) root_key = serializer . find_scope ( :default ) . options [ :root ] end if root_key root_key . to_s elsif object_class . respond_to? ( :model_name ) object_class . model_name . element else object_clas...
Tries to find the default root key .
21,843
def post ( delay , * args , & task ) raise ArgumentError , 'no block given' unless block_given? delay = TimerSet . calculate_delay! ( delay ) mutex . synchronize do return false unless running? if ( delay ) <= 0.01 @task_executor . post ( * args , & task ) else @queue . push ( Task . new ( Garcon . monotonic_time + del...
Create a new set of timed tasks .
21,844
def process_tasks loop do task = mutex . synchronize { @queue . peek } break unless task now = Garcon . monotonic_time diff = task . time - now if diff <= 0 task = mutex . synchronize { @queue . pop } @task_executor . post ( * task . args , & task . op ) else mutex . synchronize do @condition . wait ( mutex , [ diff , ...
Run a loop and execute tasks in the scheduled order and at the approximate scheduled time . If no tasks remain the thread will exit gracefully so that garbage collection can occur . If there are no ready tasks it will sleep for up to 60 seconds waiting for the next scheduled task .
21,845
def create @admin = Admin . new ( administrator_params ) respond_to do | format | if @admin . save profile_images ( params , @admin ) Emailer . profile ( @admin ) . deliver format . html { redirect_to admin_administrators_path , notice : I18n . t ( "controllers.admin.administrators.create.flash.success" ) } else format...
actually create the new admin with the given param data
21,846
def edit @admin = current_admin . id == params [ :id ] . to_i ? @current_admin : Admin . find ( params [ :id ] ) set_title ( I18n . t ( "controllers.admin.administrators.edit.title" , username : @admin . username ) ) add_breadcrumb I18n . t ( "controllers.admin.administrators.edit.breadcrumb" ) @action = 'update' if @a...
get and disply certain admin
21,847
def update @admin = Admin . find ( params [ :id ] ) @admin . deal_with_cover params respond_to do | format | admin_passed = if params [ :admin ] [ :password ] . blank? @admin . update_without_password ( administrator_params ) else @admin . update_attributes ( administrator_params ) end if admin_passed clear_cache profi...
update the admins object
21,848
def destroy @admin = Admin . find ( params [ :id ] ) @admin . destroy if @admin . overlord == 'N' respond_to do | format | format . html { redirect_to admin_administrators_path , notice : I18n . t ( "controllers.admin.administrators.destroy.flash.success" ) } end end
Delete the admin one thing to remember is you are not allowed to destory the overlord . You are only allowed to destroy yourself unless you are the overlord .
21,849
def exec ( * commands ) ret = '' commands . each { | cmd | ret += shell . exec ( cmd ) } ret + shell . exec ( 'exec' ) end
Creates the wrapper executing the pfSense shell .
21,850
def set_config_section ( section_name , values , message = '' ) current_values = get_config_section ( section_name ) changes = generate_config_changes ( "$config[#{section_name.to_s.inspect}]" , current_values , values ) if changes &. any? if message . to_s . strip == '' message = "Updating #{section_name} section." en...
Sets a configuration section to the pfSense device .
21,851
def enable_cert_auth ( public_key = '~/.ssh/id_rsa.pub' ) cert_regex = / \/ \/ \/ \S /m unless public_key =~ cert_regex public_key = File . expand_path ( public_key ) if File . exist? ( public_key ) public_key = File . read ( public_key ) . to_s . strip else raise Shells :: PfSenseCommon :: PublicKeyNotFound end raise ...
Enabled public key authentication for the current pfSense user .
21,852
def glyph ( name , size = nil ) size = size . to_s . downcase if %w( small smaller big bigger ) . include? ( size ) size = ' glyph-' + size else size = '' end "<i class=\"glyphicon glyphicon-#{h name}#{size}\"></i>" . html_safe end
Creates a glyph icon using the specified + name + and + size + .
21,853
def list_option ( name , description , ** config ) add_option Clin :: OptionList . new ( name , description , ** config ) end
Add a list option .
21,854
def list_flag_option ( name , description , ** config ) add_option Clin :: OptionList . new ( name , description , ** config . merge ( argument : false ) ) end
Add a list options that don t take arguments Same as . list_option but set + argument + to false
21,855
def general_option ( option_cls , config = { } ) option_cls = option_cls . constantize if option_cls . is_a? String @general_options [ option_cls ] = option_cls . new ( config ) end
Add a general option
21,856
def remove_general_option ( option_cls ) option_cls = option_cls . constantize if option_cls . is_a? String @general_options . delete ( option_cls ) end
Remove a general option Might be useful if a parent added the option but is not needed in this child .
21,857
def option_defaults out = { } @specific_options . each do | option | option . load_default ( out ) end @general_options . each do | _cls , option | out . merge! option . class . option_defaults end out end
To be called inside OptionParser block Extract the option in the command line using the OptionParser and map it to the out map .
21,858
def add_all_lights all_lights = [ ] overview [ "lights" ] . each do | id , light | all_lights << add_light ( id . to_i , light [ "name" ] ) end all_lights end
loop through the available lights and make corresponding objects
21,859
def table_for ( model_class , records , html = { } , & block ) Table . new ( self , model_class , records , html , block ) . render end
Create a html table for records using model class for naming things .
21,860
def uniquify_attributes ( attributes ) attributes . each do | ka | oldval = send ( ka ) next unless String === oldval newval = UniquifierCache . instance . get ( self , oldval ) set_property_value ( ka , newval ) logger . debug { "Reset #{qp} #{ka} from #{oldval} to unique value #{newval}." } end end
Makes this domain object s String values for the given attributes unique .
21,861
def store key , value h = hash ( key ) hi = ( h % num_hashes ) @hashes [ hi ] ||= "" header = build_header ( key . length , value . length ) @io . syswrite ( header + key + value ) size = header . size + key . size + value . size @hashes [ hi ] += [ h , @pos ] . pack ( "ww" ) @pos += size end
Store value under key .
21,862
def png_to_sizes ( input_filename , sizes_array , output_dirname = nil , append_filenames = APPEND_FILE_FORMAT , force_overwrite = false , clear = true , force_clear = false ) basename = File . basename ( input_filename , '.*' ) output_dirname ||= File . join ( File . expand_path ( File . dirname ( input_filename ) ) ,...
resize PNG file and write new sizes to directory
21,863
def qp qph = { } each { | k , v | qph [ k . qp ] = v . qp } qph . pp_s end
qp short for quick - print prints this Hasher with a filter that calls qp on each key and value .
21,864
def update options = self . class . merge_options ( ) options . merge! ( { :body => self . to_xml } ) response = self . class . put ( self . href , options ) begin self . class . check_status_code ( response ) rescue return false end return true end
Updates the object on server after attributes have been set . Returns boolean if successful
21,865
def delete options = self . class . merge_options ( ) response = self . class . delete ( self . href , options ) begin self . class . check_status_code ( response ) rescue return false end return true end
Destroys Cashboard object on the server . Returns boolean upon success .
21,866
def to_xml ( options = { } ) options [ :indent ] ||= 2 xml = options [ :builder ] ||= Builder :: XmlMarkup . new ( :indent => options [ :indent ] ) xml . instruct! unless options [ :skip_instruct ] obj_name = self . class . resource_name . singularize obj_attrs = self . marshal_dump xml . tag! ( obj_name ) do obj_attrs...
Utilizes ActiveSupport to turn our objects into XML that we can pass back to the server .
21,867
def delete ( element_key ) parameter = { basic_auth : @auth } response = self . class . delete ( "/elements/#{element_key}" , parameter ) unless response . success? puts "Could not save element: #{response.headers['x-errordescription']}" end response end
Deletes an element with the key It returns the http response .
21,868
def notes ( element_key ) parameter = { basic_auth : @auth } response = self . class . get ( "/elements/#{element_key}/notes" , parameter ) if response . success? search_response_header = SearchResponseHeader . new ( response ) search_response_header . elementList end end
It returns the notes of an element if anything are given Notes list can be empty It returns nil if no element with this elementKey was found
21,869
def note_handler @_note_handler = NoteHandler . new ( keytechkit . base_url , keytechkit . username , keytechkit . password ) if @_note_handler . nil? @_note_handler end
Returns Notes resource . Every Element can have zero one or more notes . You can notes only access in context of its element which ownes the notes
21,870
def file_handler @_element_file_handler = ElementFileHandler . new ( keytechkit . base_url , keytechkit . username , keytechkit . password ) if @_element_file_handler . nil? @_element_file_handler end
Returns the file object . Every element can have a Masterfile and one or more preview files
21,871
def to_hash ret = { } self . each_pair do | k , v | ret [ k ] = v . to_hash ( ) end ret end
returns results in a straight up hash .
21,872
def merge! ( rh ) rh . each_pair do | k , v | if self . has_key? ( k ) self [ k ] . merge! ( v ) else self [ k ] = v end end end
merges multiple ResultsHash s
21,873
def titleize ( word ) humanized = humanize ( underscore ( word ) ) humanized . reverse . gsub ( / /) { | a tch| m tch.c a pitalize } r e verse end
Capitalizes all the words and replaces some characters in the string to create a nicer looking title . + titleize + is meant for creating pretty output . It is not used in the Rails internals .
21,874
def attributes fields . each_with_object ( HashWithIndifferentAccess . new ) do | field , acc | acc [ field . alias ] = field . value end end
Initializes new instance of Filter class . Returns list of filter attributes .
21,875
def get_type_by_url return 'P' if params [ :slug ] . blank? segments = params [ :slug ] . split ( '/' ) url = params [ :slug ] article_url = Setting . get ( 'articles_slug' ) category_url = Setting . get ( 'category_slug' ) tag_url = Setting . get ( 'tag_slug' ) status = "(post_status = 'Published' AND post_date <= CUR...
returns that type of page that you are currenly viewing
21,876
def hear ( message , params = { } ) raise ArgumentError , "`message` must respond to :channel" unless message . respond_to? ( :channel ) raise ArgumentError , "`message` must respond to :sender" unless message . respond_to? ( :sender ) listeners . hear ( message ) . each do | match | event = Houston :: Conversations ::...
Matches a message against all listeners and invokes the first listener that mathes
21,877
def execute ( & block ) result = false raise ArgumentError , "missing block" unless block_given? begin open ( lockfile , 'w' ) do | f | result = lock ( f , File :: LOCK_EX | File :: LOCK_NB ) do | f | yield end end ensure FileUtils . rm ( lockfile ) if ( result && File . exists? ( lockfile ) ) end result end
Creates a new Mutex
21,878
def to_bytes self . sender ||= :pc self . receiver ||= 1 bytes = [ ] bytes . concat [ 0x00 ] * 5 bytes . concat [ 0x01 ] bytes . concat self . sender . to_bytes bytes . concat self . receiver . to_bytes bytes . concat [ 0x02 ] bytes . concat string_to_ascii_bytes ( command_code ) bytes . concat command_payload_bytes by...
Returns a byte array representing this command appropriate for sending to the sign s serial port
21,879
def records if ! @records @io . seek ( 44 , IO :: SEEK_SET ) records = [ ] header . record_count . times do records << ResourceRecord . read ( @io ) end @records = records end @records end
Reads the list of records from the resource file .
21,880
def data ( rec ) @io . seek ( rec . data_offset , IO :: SEEK_SET ) @io . read ( rec . data_length ) end
Reads the data for a given record .
21,881
def compute_checksum ( & block ) crc = CRC . new file_size = header . file_size @io . seek ( 8 , IO :: SEEK_SET ) pos = 8 length = 4096 - 8 buf = nil while true buf = @io . read ( length , buf ) break if ! buf crc . update ( buf ) pos += buf . size block . call ( pos ) if block length = 4096 end crc . crc end
Computes the checksum for the resource file .
21,882
def build_task_template b = binding ERB . new ( Woro :: TaskHelper . read_template_file ) . result ( b ) end
Read template and inject new name
21,883
def authorize! ( * group_list ) begin unless logged_in? store_location raise_not_logged_in "You need to login to access '#{request.fullpath}'." , 'nobody is logged in' end group_list ||= [ ] group_list . delete false group_list . delete '' if group_list . include? ( true ) unless system_admin? if show_denial_reason? fl...
Authorize the current action .
21,884
def selector_matches? ( selector ) selector . any? do | group | group . keys . all? do | key | input_has_key? ( key ) && ( @input [ key ] == group [ key ] || group [ key ] . nil? ) end end end
REFACTOR to selector class
21,885
def ready_for_challenge ( domain , dns_challenge ) record = "#{dns_challenge.record_name}.#{domain}" challenge_value = dns_challenge . record_content txt_value = Resolv :: DNS . open do | dns | records = dns . getresources ( record , Resolv :: DNS :: Resource :: IN :: TXT ) ; records . empty? ? nil : records . map ( & ...
Check if TXT value has been set correctly
21,886
def check_existing_pid return false unless pid_file_exists? pid = read_pid fail 'Existing process found.' if pid > 0 && pid_exists? ( pid ) delete_pid end
Check if process exists then fail otherwise clean up .
21,887
def trap_default_signals Signal . trap ( 'INT' ) do puts 'Interrupted. Terminating process...' exit end Signal . trap ( 'HUP' ) do puts 'SIGHUP - Terminating process...' exit end Signal . trap ( 'TERM' ) do puts 'SIGTERM - Terminating process...' exit end end
Trap common signals as default .
21,888
def links doc . xpath ( '//a' ) . map do | element | element . attribute ( 'href' ) end . compact . map ( & :value ) . map do | href | Snapshotify :: Document . new ( href , url ) end . compact end
Initialize the document with a URL and the parent page this URL was included on in case of assets Find the links in a page and extract all the hrefs
21,889
def write! writer = Snapshotify :: Writer . new ( self ) writer . emitter = emitter writer . write end
Write a document to file
21,890
def option ( option , * args ) options = args . pop if args . last . is_a? ( Hash ) options ||= { } raise "Invalid number of arguments (0 or 1 expected)" if args . size > 1 return unless @shell . applicable? ( options ) value = args . shift || options [ :value ] if options [ :os_prefix ] option = @shell . option_switch...
Add an option to the command .
21,891
def os_option ( option , * args ) options = args . pop if args . last . is_a? ( Hash ) options ||= { } args . push options . merge ( os_prefix : true ) option option , * args end
An + os_option + has automatically a OS - dependent prefix
21,892
def argument ( value , options = { } ) return unless @shell . applicable? ( options ) value = value . to_s if @shell . requires_escaping? ( value ) value = @shell . escape_value ( value ) end @command << ' ' << value @last_arg = :argument end
Add an unquoted argument to the command . This is not useful for commands executed directly since the arguments are note interpreted by a shell in that case .
21,893
def run ( options = { } ) @output = @status = @error_output = @error = nil if options [ :direct ] command = @shell . split ( @command ) else command = [ @command ] end stdin_data = options [ :stdin_data ] || @input if stdin_data command << { stdin_data : stdin_data } end begin case options [ :error_output ] when :mix @...
Execute the command .
21,894
def interactive_parser ( ) puts 'Press <Enter> to exit...' loop do str = interactive_input ( ) break if str == "" str . bytes . each do | c | parse ( c . chr ) puts 'parser: ' + @parserstate puts 'symbol: ' + interactive_output ( c . chr ) . to_s puts 'state: ' + @chain . last . statename puts end end end
Run parser machine for check in interactive mode .
21,895
def attributes ( * args , & block ) options = args . extract_options! options [ :html ] ||= { } if args . first and args . first . is_a? String options [ :name ] = args . shift end if options [ :for ] . blank? attributes_for ( record , args , options , & block ) else for_value = if options [ :for ] . is_a? Symbol recor...
Creates block of attributes with optional header . Attributes are surrounded with ordered list .
21,896
def attribute ( * args , & block ) options = args . extract_options! options . reverse_merge! ( Attrtastic . default_options ) options [ :html ] ||= { } method = args . shift html_label_class = [ "label" , options [ :html ] [ :label_class ] ] . compact . join ( " " ) html_value_class = [ "value" , options [ :html ] [ :...
Creates list entry for single record attribute
21,897
def collection get_collection_ivar || begin chain = end_of_association_chain chain = apply_scopes ( chain ) if params [ :search ] chain = chain . search ( params [ :search ] . to_s . downcase , match : :all ) end if params [ :page ] per_page = params [ :perPage ] || 20 chain = chain . page ( params [ :page ] ) . per ( ...
add support for scopes search and pagination
21,898
def get_resource_version resource = get_resource_ivar version = params [ :version ] . try ( :to_i ) if version && version > 0 && version < resource . version resource . undo ( nil , from : version + 1 , to : resource . version ) resource . version = version end return resource end
add support for history
21,899
def - ( other ) other = other . to_key_path raise KeyError unless prefix? ( other ) super ( other . length ) end
Returns a key path without the leading + prefix +