idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
7,300
def authorize_action_for ( authority_resource , * options ) authority_action = self . class . authority_action_map [ action_name . to_sym ] if authority_action . nil? raise MissingAction . new ( "No authority action defined for #{action_name}" ) end Authority . enforce ( authority_action , authority_resource , authorit...
To be run in a before_filter ; ensure this controller action is allowed for the user Can be used directly within a controller action as well given an instance or class with or without options to delegate to the authorizer .
7,301
def authority_forbidden ( error ) Authority . logger . warn ( error . message ) render :file => Rails . root . join ( 'public' , '403.html' ) , :status => 403 , :layout => false end
Renders a static file to minimize the chances of further errors .
7,302
def run_authorization_check if instance_authority_resource . is_a? ( Array ) authorize_action_for ( * instance_authority_resource , * authority_arguments ) else authorize_action_for ( instance_authority_resource , * authority_arguments ) end end
The before_filter that will be setup to run when the class method authorize_actions_for is called
7,303
def search ( query ) get ( '/v1/search' . freeze , { q : query } ) rescue => e logger . warn "API v1 - Search failed #{e.backtrace}" { 'results' => catalog ( query ) } end
Since the Registry API v2 does not support a search the v1 endpoint is used Newer registries will fail the v2 catalog endpoint is used
7,304
def as ( type_symbol ) return case type_symbol . to_sym when :string , :text , :integer , :float , :datetime self . send ( "#{type_symbol}_value" . to_sym ) when :date self . datetime_value . nil? ? nil : self . datetime_value . to_date when :time self . datetime_value . nil? ? nil : self . datetime_value . to_time els...
Returns the response as a particular response_class type
7,305
def method_missing ( missing_method , * args , & block ) method_name , reference_identifier = missing_method . to_s . split ( "_" , 2 ) type = full ( method_name ) Surveyor :: Parser . raise_error ( "\"#{type}\" is not a surveyor method." ) if ! %w( survey survey_translation survey_section question_group question depen...
This method_missing does all the heavy lifting for the DSL
7,306
def validate [ 'from' , 'to' ] . each do | s | raise Error , "'#{s}' must be a valid IMAP URI (e.g. imap://example.com)" unless fetch ( s ) =~ IMAP :: REGEX_URI end unless Logger :: LEVELS . has_key? ( verbosity . to_sym ) raise Error , "'verbosity' must be one of: #{Logger::LEVELS.keys.join(', ')}" end if exclude_file...
Validates the config and resolves conflicting settings .
7,307
def cache_config @cached = { } @lookup . reverse . each do | c | c . each { | k , v | @cached [ k ] = config_merge ( @cached [ k ] || { } , v ) } end end
Merges configs such that those earlier in the lookup chain override those later in the chain .
7,308
def safely safe_connect retries = 0 begin yield rescue Errno :: ECONNABORTED , Errno :: ECONNRESET , Errno :: ENOTCONN , Errno :: EPIPE , Errno :: ETIMEDOUT , IOError , Net :: IMAP :: ByeResponseError , OpenSSL :: SSL :: SSLError => e raise unless ( retries += 1 ) <= @options [ :max_retries ] warning "#{e.class.name}: ...
Connect if necessary execute the given block retry if a recoverable error occurs die if an unrecoverable error occurs .
7,309
def uri_mailbox mb = @uri . path [ 1 .. - 1 ] mb . nil? || mb . empty? ? nil : CGI . unescape ( mb ) end
Gets the IMAP mailbox specified in the URI or + nil + if none .
7,310
def check_quirks return unless @conn && @conn . greeting . kind_of? ( Net :: IMAP :: UntaggedResponse ) && @conn . greeting . data . kind_of? ( Net :: IMAP :: ResponseText ) if @conn . greeting . data . text =~ / / @quirks [ :gmail ] = true debug "looks like Gmail" elsif host =~ / \. \. \. / @quirks [ :yahoo ] = true d...
Tries to identify server implementations with certain quirks that we ll need to work around .
7,311
def set_object id = params [ :id ] @object = resource . friendly . find ( id ) rescue NoMethodError @object = resource . find ( id ) ensure authorize! action_to_cancancan , @object end
Common setup to stablish which object this request is querying
7,312
def set_records authorize! :read , resource . name . underscore . to_sym @records = request_collection . ransack ( parsed_query ) . result @object = request_collection . new key_scope_records reorder_records if params [ :sort ] . present? select_fields if params [ :select ] . present? include_relations if params [ :inc...
Used to setup the records from the selected resource that are going to be rendered if authorized
7,313
def index_json if params [ :group ] . present? @records . group ( params [ :group ] [ :by ] . split ( ',' ) ) . send ( :calculate , params [ :group ] [ :calculate ] , params [ :group ] [ :field ] ) else collection_response end end
The response for index action which can be a pagination of a record collection or a grouped count of attributes
7,314
def request_metadata { uuid : request . uuid , url : request . original_url , headers : request . env . select { | key , _v | key =~ / / } , ip : request . remote_ip } end
Information that gets inserted on register_api_request as auditing data about the request . Returns a Hash with UUID URL HTTP Headers and IP
7,315
def build_permissions ( opts = { } ) permission = opts [ :permission ] . to_sym clearances = opts [ :clearance ] if clearances == true can permission , :all else clearances . to_h . each do | klass , clearance | klass_module = klass . underscore . singularize . to_sym klass = klass . classify . constantize can permissi...
Method that initializes CanCanCan with the scope of permissions based on current key from request
7,316
def define ( spec , ** opts , & block ) name , parent = spec . is_a? ( Hash ) ? spec . flatten ( 1 ) : spec if registry . key? ( name ) raise ArgumentError , "#{name.inspect} factory has been already defined" end builder = if parent extend_builder ( name , registry [ parent ] , & block ) else relation_name = opts . fet...
Define a new builder
7,317
def struct_namespace ( namespace = Undefined ) if namespace . equal? ( Undefined ) options [ :struct_namespace ] else with ( struct_namespace : namespace ) end end
Get factories with a custom struct namespace
7,318
def hour ( system = :twenty_four_hour ) hour = self . to_duration . to_units ( :hour , :minute , :second ) . fetch ( :hour ) if system == :twelve_hour if hour == 0 12 elsif hour > 12 hour - 12 else hour end elsif ( system == :twenty_four_hour ) hour else raise ArgumentError , "system should be :twelve_hour or :twenty_f...
Get the hour of the WallClock .
7,319
def after ( time ) time = time . to_time prev_day = time . mday prev_month = time . month prev_year = time . year units = self . to_units ( :years , :months , :days , :seconds ) date_in_month = self . class . build_date ( prev_year + units [ :years ] , prev_month + units [ :months ] , prev_day ) date = date_in_month + ...
Returns the time self later than the given time .
7,320
def to_unit ( unit ) unit_details = self . class . resolve_unit ( unit ) if unit_details . has_key? ( :seconds ) seconds = self . normalize . get ( :seconds ) self . class . div ( seconds , unit_details . fetch ( :seconds ) ) elsif unit_details . has_key? ( :months ) months = self . denormalize . get ( :months ) self ....
Convert the duration to a given unit .
7,321
def - ( other ) case other when 0 self when Duration Duration . new ( seconds : @seconds - other . get ( :seconds ) , months : @months - other . get ( :months ) ) else raise ArgumentError , "Cannot subtract #{other.inspect} from Duration #{self}" end end
Subtract two durations .
7,322
def * ( other ) case other when Integer Duration . new ( seconds : @seconds * other , months : @months * other ) else raise ArgumentError , "Cannot multiply Duration #{self} by #{other.inspect}" end end
Multiply a duration by a scalar .
7,323
def to_s ( format = :long , options = nil ) format = case format when Symbol FORMATS . fetch ( format ) when Hash FORMATS . fetch ( :long ) . merge ( format ) else raise ArgumentError , "Expected #{format.inspect} to be a Symbol or Hash" end format = format . merge ( options || { } ) count = if format [ :count ] . nil?...
Convert a duration to a human - readable string .
7,324
def to_rounded_s ( format = :min_long , options = nil ) format = case format when Symbol FORMATS . fetch ( format ) when Hash FORMATS . fetch ( :long ) . merge ( format ) else raise ArgumentError , "Expected #{format.inspect} to be a Symbol or Hash" end format = format . merge ( Hash ( options ) ) places = format [ :co...
Convert a Duration to a human - readable string using a rounded value .
7,325
def select_params ( api : , from : ) rest_api = get ( api ) return from if rest_api . nil? rest_api . select_params ( from : from ) end
Given an API descriptor name and a set of request parameters select those params that are accepted by the API endpoint .
7,326
def valid_param? ( api : , param : ) rest_api = get ( api ) return true if rest_api . nil? rest_api . valid_param? ( param ) end
Given an API descriptor name and a single request parameter returns true if the parameter is valid for the given API . This method always returns true if the API is unknown .
7,327
def select_parts ( api : , from : ) rest_api = get ( api ) return from if rest_api . nil? rest_api . select_parts ( from : from ) end
Given an API descriptor name and a set of request path parts select those parts that are accepted by the API endpoint .
7,328
def valid_part? ( api : , part : ) rest_api = get ( api ) return true if rest_api . nil? rest_api . valid_part? ( part ) end
Given an API descriptor name and a single path part returns true if the path part is valid for the given API . This method always returns true if the API is unknown .
7,329
def select_common_params ( from : ) return from if @common_params . empty? from . select { | k , v | valid_common_param? ( k ) } end
Select the common request parameters from the given params .
7,330
def validate_params! ( api : , params : ) rest_api = get ( api ) return params if rest_api . nil? params . keys . each do | key | unless rest_api . valid_param? ( key ) || valid_common_param? ( key ) raise :: Elastomer :: Client :: IllegalArgument , "'#{key}' is not a valid parameter for the '#{api}' API" end end param...
Given an API descriptor name and a set of request parameters ensure that all the request parameters are valid for the API endpoint . If an invalid parameter is found then an IllegalArgument exception is raised .
7,331
def multi_search ( body = nil , params = nil ) if block_given? params , body = ( body || { } ) , nil yield msearch_obj = MultiSearch . new ( self , params ) msearch_obj . call else raise "multi_search request body cannot be nil" if body . nil? params ||= { } response = self . post "{/index}{/type}/_msearch" , params . ...
Execute an array of searches in bulk . Results are returned in an array in the order the queries were sent .
7,332
def multi_percolate ( body = nil , params = nil ) if block_given? params , body = ( body || { } ) , nil yield mpercolate_obj = MultiPercolate . new ( self , params ) mpercolate_obj . call else raise "multi_percolate request body cannot be nil" if body . nil? params ||= { } response = self . post "{/index}{/type}/_mperc...
Execute an array of percolate actions in bulk . Results are returned in an array in the order the actions were sent .
7,333
def bulk ( body = nil , params = nil ) if block_given? params , body = ( body || { } ) , nil yield bulk_obj = Bulk . new ( self , params ) bulk_obj . call else raise "bulk request body cannot be nil" if body . nil? params ||= { } response = self . post "{/index}{/type}/_bulk" , params . merge ( body : body , action : "...
The bulk method can be used in two ways . Without a block the method will perform an API call and it requires a bulk request body and optional request parameters . If given a block the method will use a Bulk instance to assemble the operations called in the block into a bulk request and dispatch it at the end of the bl...
7,334
def bulk_stream_responses ( ops , params = { } ) bulk_obj = Bulk . new ( self , params ) Enumerator . new do | yielder | ops . each do | action , * args | response = bulk_obj . send ( action , * args ) yielder . yield response unless response . nil? end response = bulk_obj . call yielder . yield response unless respons...
Stream bulk actions from an Enumerator .
7,335
def bulk_stream_items ( ops , params = { } ) stats = { "took" => 0 , "errors" => false , "success" => 0 , "failure" => 0 } bulk_stream_responses ( ops , params ) . each do | response | stats [ "took" ] += response [ "took" ] stats [ "errors" ] |= response [ "errors" ] response [ "items" ] . each do | item | if is_ok? (...
Stream bulk actions from an Enumerator and passes the response items to the given block .
7,336
def identifier @identifier ||= begin uri = @representor_hash . href || self . object_id protocol = @representor_hash . protocol || ( uri == self . object_id ? UNKNOWN_PROTOCOL : DEFAULT_PROTOCOL ) PROTOCOL_TEMPLATE % [ protocol , uri ] end end
The URI for the object
7,337
def symbolize_keys ( hash ) Hash [ hash . map { | ( k , v ) | [ k . to_sym , v ] } ] end
Accepts a hash and returns a new hash with symbolized keys
7,338
def deserialize_embedded ( builder , media ) make_embedded_resource = -> ( x ) { self . class . new ( x ) . to_representor_hash . to_h } ( media [ EMBEDDED_KEY ] || { } ) . each do | name , value | resource_hash = map_or_apply ( make_embedded_resource , value ) builder = builder . add_embedded ( name , resource_hash ) ...
embedded resources are under _embedded in the original document similarly to links they can contain an array or a single embedded resource . An embedded resource is a full document so we create a new HaleDeserializer for each .
7,339
def add_attribute ( name , value , options = { } ) new_representor_hash = RepresentorHash . new ( deep_dup ( @representor_hash . to_h ) ) new_representor_hash . attributes [ name ] = options . merge ( { value : value } ) RepresentorBuilder . new ( new_representor_hash ) end
Adds an attribute to the Representor . We are creating a hash where the keys are the names of the attributes
7,340
def add_transition ( rel , href , options = { } ) new_representor_hash = RepresentorHash . new ( deep_dup ( @representor_hash . to_h ) ) options = symbolize_keys ( options ) options . delete ( :method ) if options [ :method ] == Transition :: DEFAULT_METHOD link_values = options . merge ( { href : href , rel : rel } ) ...
Adds a transition to the Representor each transition is a hash of values The transition collection is an Array
7,341
def add_transition_array ( rel , array_of_hashes ) array_of_hashes . reduce ( RepresentorBuilder . new ( @representor_hash ) ) do | memo , transition | transition = symbolize_keys ( transition ) href = transition . delete ( :href ) memo = memo . add_transition ( rel , href , transition ) end end
Adds directly an array to our array of transitions
7,342
def _create_record if self . class . custom_create_method run_callbacks ( :create ) do if self . record_timestamps current_time = current_time_from_proper_timezone all_timestamp_attributes_in_model . each do | column | if respond_to? ( column ) && respond_to? ( "#{column}=" ) && self . send ( column ) . nil? write_attr...
Creates a record with custom create method and returns its id .
7,343
def _update_record ( attribute_names = @attributes . keys ) if self . class . custom_update_method run_callbacks ( :update ) do if should_record_timestamps? current_time = current_time_from_proper_timezone timestamp_attributes_for_update_in_model . each do | column | column = column . to_s next if will_save_change_to_a...
Updates the associated record with custom update method Returns the number of affected rows .
7,344
def redeem account_or_code , currency = nil , extra_opts = { } return false unless link? :redeem account_code = if account_or_code . is_a? Account account_or_code . account_code else account_or_code end redemption_options = { :account_code => account_code , :currency => currency || Recurly . default_currency } . merge ...
Redeem a coupon with a given account or account code .
7,345
def generate ( amount ) builder = XML . new ( "<coupon/>" ) builder . add_element 'number_of_unique_codes' , amount resp = follow_link ( :generate , :body => builder . to_s ) Pager . new ( Recurly :: Coupon , uri : resp [ 'location' ] , parent : self , etag : resp [ 'ETag' ] ) end
Generate unique coupon codes on the server . This is based on the unique_template_code .
7,346
def redeem! ( account_code , currency = nil ) redemption = redeem ( account_code , currency ) raise Invalid . new ( self ) unless redemption && redemption . persisted? redemption end
Redeem a coupon on the given account code
7,347
def read_attribute ( key ) key = key . to_s if attributes . key? key value = attributes [ key ] elsif links . key? ( key ) && self . class . reflect_on_association ( key ) value = attributes [ key ] = follow_link key end value end
The value of a specified attribute lazily fetching any defined association .
7,348
def write_attribute ( key , value ) if changed_attributes . key? ( key = key . to_s ) changed_attributes . delete key if changed_attributes [ key ] == value elsif self [ key ] != value changed_attributes [ key ] = self [ key ] end association = self . class . find_association ( key ) if association value = fetch_associ...
Sets the value of a specified attribute .
7,349
def attributes = ( attributes = { } ) attributes . each_pair { | k , v | respond_to? ( name = "#{k}=" ) and send ( name , v ) or self [ k ] = v } end
Apply a given hash of attributes to a record .
7,350
def follow_link ( key , options = { } ) if link = links [ key = key . to_s ] response = API . send link [ :method ] , link [ :href ] , options [ :body ] , options if resource_class = link [ :resource_class ] response = resource_class . from_response response response . attributes [ self . class . member_name ] = self e...
Fetch the value of a link by following the associated href .
7,351
def to_xml ( options = { } ) builder = options [ :builder ] || XML . new ( "<#{self.class.member_name}/>" ) xml_keys . each { | key | value = respond_to? ( key ) ? send ( key ) : self [ key ] node = builder . add_element key case value when Resource , Subscription :: AddOns value . to_xml options . merge ( :builder => ...
Serializes the record to XML .
7,352
def save if new_record? || changed? clear_errors @response = API . send ( persisted? ? :put : :post , path , to_xml ) reload response persist! true end true rescue API :: UnprocessableEntity => e apply_errors e Transaction :: Error . validate! e , ( self if is_a? ( Transaction ) ) false end
Attempts to save the record returning the success of the request .
7,353
def destroy return false unless persisted? @response = API . delete uri @destroyed = true rescue API :: NotFound => e raise NotFound , e . description end
Attempts to destroy the record .
7,354
def invoice! ( attrs = { } ) InvoiceCollection . from_response API . post ( invoices . uri , attrs . empty? ? nil : Invoice . to_xml ( attrs ) ) rescue Recurly :: API :: UnprocessableEntity => e raise Invalid , e . message end
Creates an invoice from the pending charges on the account . Raises an error if it fails .
7,355
def build_invoice InvoiceCollection . from_response API . post ( "#{invoices.uri}/preview" ) rescue Recurly :: API :: UnprocessableEntity => e raise Invalid , e . message end
Builds an invoice from the pending charges on the account but does not persist the invoice . Raises an error if it fails .
7,356
def verify_cvv! ( verification_value ) bi = BillingInfo . new ( verification_value : verification_value ) bi . uri = "#{path}/billing_info/verify_cvv" bi . save! bi end
Verify a cvv code for the account s billing info .
7,357
def enter_offline_payment ( attrs = { } ) Transaction . from_response API . post ( "#{uri}/transactions" , attrs . empty? ? nil : Transaction . to_xml ( attrs ) ) rescue Recurly :: API :: UnprocessableEntity => e raise Invalid , e . message end
Posts an offline payment on this invoice
7,358
def preview clear_errors @response = API . send ( :post , "#{path}/preview" , to_xml ) reload response rescue API :: UnprocessableEntity => e apply_errors e end
Preview the GiftCard . Runs and validates the GiftCard but does not persist it . Errors are applied to the GiftCard if there are any errors .
7,359
def postpone next_renewal_date , bulk = false return false unless link? :postpone reload follow_link ( :postpone , :params => { :next_renewal_date => next_renewal_date , :bulk => bulk } ) true end
Postpone a subscription s renewal date .
7,360
def update_notes ( notes ) return false unless link? :notes self . attributes = notes reload follow_link ( :notes , body : to_xml ) true end
Update the notes sections of the subscription . This endpoint also allows you to update the custom fields .
7,361
def pause ( remaining_pause_cycles ) builder = XML . new ( "<subscription/>" ) builder . add_element ( 'remaining_pause_cycles' , remaining_pause_cycles ) reload API . put ( "#{uri}/pause" , builder . to_s ) true end
Pauses a subscription or cancels a scheduled pause .
7,362
def add_element name , value = nil value = value . respond_to? ( :xmlschema ) ? value . xmlschema : value . to_s XML . new super ( name , value ) end
Adds an element to the root .
7,363
def add_from_catalog ( catalog , test_module ) coverable_resources = catalog . to_a . reject { | resource | ! test_module . nil? && filter_resource? ( resource , test_module ) } coverable_resources . each do | resource | add ( resource ) end end
add all resources from catalog declared in module test_module
7,364
def filter_resource? ( resource , test_module ) if @filters . include? ( resource . to_s ) return true end if resource . type == 'Class' module_name = resource . title . split ( '::' ) . first . downcase if module_name != test_module return true end end if resource . file paths = module_paths ( test_module ) unless pat...
Should this resource be excluded from coverage reports?
7,365
def module_paths ( test_module ) adapter = RSpec . configuration . adapter paths = adapter . modulepath . map do | dir | File . join ( dir , test_module , 'manifests' ) end paths << adapter . manifest if adapter . manifest paths end
Find all paths that may contain testable resources for a module .
7,366
def build_compiler node_name = nodename ( :function ) fact_values = facts_hash ( node_name ) trusted_values = trusted_facts_hash ( node_name ) HieraPuppet . instance_variable_set ( '@hiera' , nil ) if defined? HieraPuppet Puppet [ :code ] = pre_cond node_facts = Puppet :: Node :: Facts . new ( node_name , fact_values ....
get a compiler with an attached compiled catalog
7,367
def device_to_data ( device_id , pos , len ) dev_blk = device_block ( pos ) dev_off = device_block_offset ( pos ) data_map = data_mapping . map_for ( device_id ) total_len = 0 data_blks = [ ] num_data_blks = ( len / data_block_size ) . to_i + 1 0 . upto ( num_data_blks - 1 ) do | i | current_blk = dev_blk + i blk_len =...
Return array of tuples device block ids data block ids addresses and lengths to read from them to read the specified device offset & length .
7,368
def loadAttributes ( attribType ) result = [ ] @list . each do | ad | next unless ad [ 'attrib_type' ] == attribType result += @boot_sector . mftEntry ( ad [ 'mft' ] ) . loadAttributes ( attribType ) end result end
Load attributes of requested type
7,369
def read ( bytes = @length ) return nil if @pos >= @length bytes = @length - @pos if bytes . nil? bytes = @length - @pos if @pos + bytes > @length out = @data [ @pos , bytes ] if @data . kind_of? ( String ) out = @data . read ( bytes ) if @data . kind_of? ( NTFS :: DataRun ) @pos += out . size out end
This now behaves exactly like a normal read .
7,370
def getNextCluster ( clus ) nxt = getFatEntry ( clus ) return nil if nxt > CC_END_OF_CHAIN raise "Damaged cluster in cluster chain" if nxt == CC_DAMAGED [ nxt , getCluster ( nxt ) ] end
Gets data for the next cluster given current or nil if end .
7,371
def countContigClusters ( clus ) cur = clus ; nxt = 0 loop do nxt = getFatEntry ( cur ) break if nxt != cur + 1 cur = nxt ; redo end raise "Damaged cluster in cluster chain" if nxt == CC_DAMAGED cur - clus + 1 end
Count the number of continuous clusters from some beginning cluster .
7,372
def wipeChain ( clus ) loop do nxt = getFatEntry ( clus ) putFatEntry ( clus , 0 ) break if nxt == 0 break if nxt == CC_DAMAGED break if nxt > CC_END_OF_CHAIN clus = nxt end end
Deallocate all clusters on a chain from a starting cluster number .
7,373
def writeClusters ( start , buf , len = buf . length ) clus = start ; num , leftover = len . divmod ( @bytesPerCluster ) ; num += 1 if leftover > 0 0 . upto ( num - 1 ) do | offset | local = buf [ offset * @bytesPerCluster , @bytesPerCluster ] if local . length < @bytesPerCluster then local += ( "\0" * ( @bytesPerClust...
Start from defined cluster number and write data following allocated cluster chain .
7,374
def putFatEntry ( clus , value ) raise "DONT TOUCH THIS CLUSTER: #{clus}" if clus < 3 @stream . seek ( @fatBase + FAT_ENTRY_SIZE * clus ) @stream . write ( [ value ] . pack ( 'L' ) , FAT_ENTRY_SIZE ) end
Write a FAT entry for a cluster .
7,375
def clusterInfo return @clusterInfo unless @clusterInfo . nil? ad = mftEntry ( 6 ) . attributeData data = ad . read ( ad . length ) ad . rewind c = data . unpack ( "b#{data.length * 8}" ) [ 0 ] nclusters = c . length on = c . count ( "1" ) uclusters = on fclusters = c . length - on @clusterInfo = { "total" => nclusters...
From File System Forensic Analysis by Brian Carrier
7,376
def mftRecToBytePos ( recno ) return mftLoc if recno == 0 start = fragTable [ 0 ] ; last_clusters = 0 ; target_cluster = recno * @bytesPerFileRec / @bytesPerCluster if ( recno > @bytesPerCluster / @bytesPerFileRec ) && ( fragTable . size > 2 ) total_clusters = 0 fragTable . each_slice ( 2 ) do | vcn , len | start = vcn...
Use data run to convert mft record number to byte pos .
7,377
def dump out = "\#<#{self.class}:0x#{'%08x' % object_id}>\n" out << " Mft Ref : seq #{@refMft[0]}, entry #{@refMft[1]}\n" out << " Length : #{@length}\n" out << " Content : #{@contentLen}\n" out << " Flags : 0x#{'%08x' % @flags}\n" out << @afn . dump if @contentLen > 0 out << " Child ref: #{@child}\n" if NTFS :...
Dumps object .
7,378
def globEntriesByHashTree ents_by_name = { } offset = 0 2 . times do de = DirectoryEntry . new ( @data [ offset .. - 1 ] , @sb . isNewDirEnt? ) ents_by_name [ de . name ] ||= [ ] ents_by_name [ de . name ] << de offset += 12 end $log . info ( "Ext4::Directory.globEntriesByHashTree (inode=#{@inodeNum}) >>\n#{@data[0, 25...
If the inode has the IF_HASH_INDEX bit set then the first directory block is to be interpreted as the root of an HTree index .
7,379
def dump out = "" out << "Page #{current}\n" out << " type: #{MiqBdbPage.type2string(ptype)}\n" out << " prev: #{prev}\n" out << " next: #{@header['next_pgno']}\n" out << " log seq num: file=#{@header['lsn_file']} offset=#{@header['lsn_offset']}\n" out << " level: #{...
Dump page statistics like db_dump .
7,380
def find ( name ) log_prefix = "MIQ(NTFS::IndexRoot.find)" name = name . downcase $log . debug "#{log_prefix} Searching for [#{name}]" if DEBUG_TRACE_FIND if @foundEntries . key? ( name ) $log . debug "#{log_prefix} Found [#{name}] (cached)" if DEBUG_TRACE_FIND return @foundEntries [ name ] end found = findInEntries ( ...
Find a name in this index .
7,381
def globNames @globNames = globEntries . collect { | e | e . namespace == NTFS :: FileName :: NS_DOS ? nil : e . name . downcase } . compact if @globNames . nil? @globNames end
Return all names in this index as a sorted string array .
7,382
def getKey ( k ) return nil if k > @nitems || k <= 0 pos = SIZEOF_BLOCK_HEADER + ( SIZEOF_KEY * ( k - 1 ) ) keydata = @data [ pos , SIZEOF_KEY ] data2key ( keydata ) end
Keys are 1 - based
7,383
def getPointer ( p ) return nil if p > @nitems || p < 0 pos = SIZEOF_BLOCK_HEADER + ( SIZEOF_KEY * @nitems ) + ( SIZEOF_POINTER * p ) ptrdata = @data [ pos , SIZEOF_POINTER ] POINTER . decode ( ptrdata ) end
Pointers are 0 - based
7,384
def dump out = "\n" out += "Type : #{@bs['desc_type']}\n" out += "Record ID : #{@bs['id']}\n" out += "Version : #{@bs['version']}\n" out += "System ID : #{@bs['system_id'].strip}\n" out += "Volume ID : #{@volName}\n" out += "Vol space size : #{@bs["vol_space_size#{@suff}"]} (sector...
This is a raw dump with no character set conversion .
7,385
def bmap_btree_record_to_block_pointers ( record , block_pointers_length ) block_pointers = [ ] block_pointers << 0 while ( block_pointers_length + block_pointers . length ) < record . start_offset 1 . upto ( record . block_count ) { | i | block_pointers << record . start_block + i - 1 } @block_offset += record . block...
This method is used for both extents and BTree leaf nodes
7,386
def procRPM ( dbDir ) $log . debug "Processing RPM package database" rpmp = MiqRpmPackages . new ( @fs , File . join ( dbDir , "Packages" ) ) rpmp . each { | p | @packages << p } rpmp . close end
Client - side RPM DB processing .
7,387
def procConary ( dbFile ) $log . debug "Processing Conary package database" rpmp = MiqConaryPackages . new ( @fs , dbFile ) rpmp . each { | p | @packages << p } rpmp . close end
Conary DB processing
7,388
def os_product_suite ( hash ) eid = hash . delete ( :edition_id ) ps = hash . delete ( :product_suite ) if eid . nil? && ! hash [ :product_name ] . nil? ps = ps . to_s . split ( "\n" ) if ps . length > 1 && ! hash [ :product_name ] . include? ( ps . first ) hash [ :product_name ] = "#{hash[:product_name].strip} #{ps.fi...
Parse product edition and append to product_name if needed .
7,389
def add_filter ( detach_with_id , filter_code ) raise WiceGridException . new ( "Detached ID #{detach_with_id} is already used!" ) if @filters . key? detach_with_id @filters [ detach_with_id ] = filter_code end
stores HTML code for a detached filter
7,390
def filter_for ( detach_with_id ) unless @filters . key? detach_with_id if @return_empty_strings_for_nonexistent_filters return '' else raise WiceGridException . new ( "No filter with Detached ID '#{detach_with_id}'!" ) end end unless @filters [ detach_with_id ] raise WiceGridException . new ( "Filter with Detached ID ...
returns HTML code for a detached filter
7,391
def export_grid_if_requested ( opts = { } ) grid = self . wice_grid_instances . detect ( & :output_csv? ) if grid template_name = opts [ grid . name ] || opts [ grid . name . intern ] template_name ||= grid . name + '_grid' temp_filename = render_to_string ( partial : template_name ) temp_filename = temp_filename . str...
+ export_grid_if_requested + is a controller method which should be called at the end of each action containing grids with enabled CSV export .
7,392
def wice_grid_custom_filter_params ( opts = { } ) options = { grid_name : 'grid' , attribute : nil , model : nil , value : nil } options . merge! ( opts ) [ :attribute , :value ] . each do | key | raise :: Wice :: WiceGridArgumentError . new ( "wice_grid_custom_filter_params: :#{key} is a mandatory argument" ) unless o...
+ wice_grid_custom_filter_params + generates HTTP parameters understood by WiceGrid custom filters . Combined with Rails route helpers it allows to generate links leading to grids with pre - selected custom filters .
7,393
def dump_filter_parameters_as_hidden_fields ( grid ) unless grid . is_a? WiceGrid raise WiceGridArgumentError . new ( 'dump_filter_parameters_as_hidden_fields: the parameter must be a WiceGrid instance.' ) end grid . get_state_as_parameter_value_pairs ( true ) . collect do | param_name , value | hidden_field_tag ( para...
This method dumps all HTTP parameters related to filtering and ordering of a certain grid as hidden form fields . This might be required if you want to keep the state of a grid while reloading the page using other forms .
7,394
def filter_and_order_state_as_hash ( grid ) { grid . name => { 'f' => grid . status [ :f ] , 'order' => grid . status [ :order ] , 'order_direction' => grid . status [ :order_direction ] } } end
This method dumps all HTTP parameters related to filtering and ordering of a certain grid in the form of a hash . This might be required if you want to keep the state of a grid while reloading the page using Rails routing helpers .
7,395
def scaffolded_grid ( grid_obj , opts = { } ) unless grid_obj . is_a? WiceGrid raise WiceGridArgumentError . new ( 'scaffolded_grid: the parameter must be a WiceGrid instance.' ) end columns = grid_obj . klass . column_names if opts [ :reject_attributes ] . is_a? Proc columns = columns . reject { | c | opts [ :reject_a...
secret but stupid weapon - takes an ActiveRecord and using reflection tries to build all the column clauses by itself . WiceGrid is not a scaffolding solution I hate scaffolding and how certain idiots associate scaffolding with Rails so I do not document this method to avoid contributing to this misunderstanding .
7,396
def action_column ( opts = { } , & block ) if @action_column_present raise Wice :: WiceGridException . new ( 'There can be only one action column in a WiceGrid' ) end options = { param_name : :selected , html : { } , select_all_buttons : true , object_property : :id , html_check_box : true } opts . assert_valid_keys ( ...
Adds a column with checkboxes for each record . Useful for actions with multiple records for example deleting selected records . Please note that + action_column + only creates the checkboxes and the Select All and Deselect All buttons and the form itelf as well as processing the parameters should be taken care of by t...
7,397
def distinct_values_for_column ( column ) column . model . select ( "distinct #{column.name}" ) . order ( "#{column.name} asc" ) . collect do | ar | ar [ column . name ] end . reject ( & :blank? ) . map { | i | [ i , i ] } end
with this variant we get even those values which do not appear in the resultset
7,398
def grid ( grid , opts = { } , & block ) raise WiceGridArgumentError . new ( 'Missing block for the grid helper.' ' For detached filters use first define_grid with the same API as grid, ' 'then grid_filter to add filters, and then render_grid to actually show the grid' ) if block . nil? define_grid ( grid , opts , & bl...
View helper for rendering the grid .
7,399
def smart_listing_for name , * args , & block raise ArgumentError , "Missing block" unless block_given? name = name . to_sym options = args . extract_options! bare = options . delete ( :bare ) builder = Builder . new ( name , @smart_listings [ name ] , self , options , block ) output = "" data = { } data [ smart_listin...
Outputs smart list container