idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
20,500
def summary_print ( formatted = false ) errors = 0 warnings = 0 findings . each { | finding | if finding . failure errors += 1 else warnings += 1 end } if errors == 0 && warnings == 0 result = "#{FORMATTING_CHECKMARK} PASSED with no warning" . colorize ( :green ) elsif errors == 0 result = "#{FORMATTING_WARNING} PASSED with #{warnings} warning" . colorize ( :yellow ) elsif warnings == 0 result = "#{FORMATTING_BALL} FAILED with #{errors} error" . colorize ( :red ) else result = "#{FORMATTING_BALL} FAILED with #{errors} error and #{warnings} warning" . colorize ( :red ) end if formatted result else result [ result . index ( ' ' ) + 1 .. result . length ] end end
Get statistic information about findings
20,501
def gravatar_url ( options = { } ) raise ArgumentError , "The size parameter must be an integer" if options [ :size ] && ! options [ :size ] . is_a? ( Integer ) response = api_response ( "user-information" ) hash = response [ "user_information" ] [ "gravatar" ] return nil if hash . nil? return build_gravatar_url ( hash , options ) end
Returns the Gravatar image URL using the Gravatar hash from the user s information .
20,502
def slice ( object , options = { } , & block ) slicer = HtmlSlicer :: Helpers :: Slicer . new self , object . options . reverse_merge ( options ) . reverse_merge ( :current_slice => object . current_slice , :slice_number => object . slice_number , :remote => false ) slicer . to_s end
A helper that renders the pagination links .
20,503
def save ( dir = Dir . pwd , options = { } ) prefix = options [ :prefix ] if options . key? ( :prefix ) write_file ( File . join ( dir , "#{prefix}#{lang}.yml" ) , options ) end
Save the file
20,504
def compact_of ( values = { } , path = KeyPath . new ) result = { } values . each_with_index do | ( i , v ) | path . move_to ( i ) if v . is_a? ( Hash ) result . merge! ( compact_of ( v , path ) ) else result [ path . to_s ] = v end path . leave end result end
Covert to a flatten hash
20,505
def tree_of ( values ) result = { } current = result values . each do | k , v | keys = k . to_s . split ( '.' ) last_key = keys . pop keys . each do | ks | current = if current . key? ( ks ) current [ ks ] else current [ ks ] = { } current [ ks ] end end current [ last_key ] = v current = result end result end
Returning the flattened structure to the tree structure
20,506
def collapsible_content ( options = { } , & blk ) options = { title : options } if options . is_a? ( String ) content = capture ( & blk ) if blk . present? content ||= options [ :content ] options [ :collapsed ] = true unless options . has_key? ( :collapsed ) classes = Array . wrap ( options [ :class ] ) | [ "collapsible-container" , options [ :collapsed ] ? 'collapsed' : nil ] title_tag = content_tag ( :div , "<span></span>#{options[:title]}" . html_safe , class : 'collapsible-title' ) content_tag ( :div , title_tag + content_tag ( :div , content , class : 'collapsible-content' ) , class : classes ) end
This is a wrapper to create collapsible content .
20,507
def attribute ( name , ** opts , & block ) raise AttributorException , "Attribute names must be symbols, got: #{name.inspect}" unless name . is_a? :: Symbol attribute = schema . attributes . fetch ( name ) do raise "Displaying :#{name} is not allowed in view :#{self.name} of #{schema}. This attribute does not exist in the mediatype" end if block_given? type = attribute . type @contents [ name ] = if type < Attributor :: Collection CollectionView . new ( name , type . member_attribute . type , & block ) else View . new ( name , attribute , & block ) end else type = attribute . type if type < Attributor :: Collection is_collection = true type = type . member_attribute . type end if type < Praxis :: Blueprint view_name = opts [ :view ] || :default view = type . views . fetch ( view_name ) do raise "view with name '#{view_name.inspect}' is not defined in #{type}" end @contents [ name ] = if is_collection Praxis :: CollectionView . new ( view_name , type , view ) else view end else @contents [ name ] = attribute end end end
Why did we need this again?
20,508
def save ( attrs = nil ) raise "a Hash of attributes to save must be specified" unless attrs && attrs . is_a? ( Hash ) raise "folder must be set prior to saving attributes" unless folder @asset . attributes . merge! ( attrs ) contents = { } if File . exists? ( folder ) contents = load_contents ( folder ) raise "expected contents to be a hash" unless contents . is_a? ( Hash ) end contents = contents . merge! ( attrs ) write_contents ( folder , contents ) end
Save specific attributes to an asset configuration file . Only the param attrs and the current contents of the config file are saved . Parent asset configurations are not saved .
20,509
def load ( ds = nil ) @folder ||= ds contents = load_contents ( folder ) parent = contents . delete ( :parent ) || parent if parent parent_folder = File . join ( parent ) unless Pathname . new ( parent_folder ) . absolute? base_folder = File . dirname ( folder ) parent_folder = File . join ( base_folder , parent_folder ) end logger . debug "AssetConfiguration loading parent: #{parent_folder}" parent_configuration = RepoManager :: AssetConfiguration . new ( asset ) begin parent_configuration . load ( parent_folder ) rescue Exception => e logger . warn "AssetConfiguration parent configuration load failed on: '#{parent_folder}' with: '#{e.message}'" end end @asset . attributes . merge! ( contents ) @asset . create_accessors ( @asset . attributes [ :user_attributes ] ) @asset end
load an asset from a configuration folder
20,510
def load_contents ( asset_folder ) file = File . join ( asset_folder , 'asset.conf' ) if File . exists? ( file ) contents = YAML . load ( ERB . new ( File . open ( file , "rb" ) . read ) . result ( @asset . get_binding ) ) if contents && contents . is_a? ( Hash ) contents . recursively_symbolize_keys! else { } end else { } end end
load the raw contents from an asset_folder ignore parents
20,511
def write_contents ( asset_folder , contents ) contents . recursively_stringify_keys! FileUtils . mkdir ( asset_folder ) unless File . exists? ( asset_folder ) filename = File . join ( asset_folder , 'asset.conf' ) File . open ( filename , "w" ) do | f | f . write ( contents . to_conf ) end end
write raw contents to an asset_folder
20,512
def to_xml return nil if title . nil? || body . nil? xml = "" xml << "<d:entry id=\"#{self.id}\" d:title=\"#{self.title}\">\n" @index . each do | i | xml << "\t<d:index d:value=\"#{i}\" d:title=\"#{title}\" " xml << "d:yomi=\"#{yomi}\"" if ! self . yomi . nil? xml << "/>\n" end xml << "\t<div>\n" xml << "\t\t#{@body}\n" xml << "\t</div>\n" xml << "</d:entry>\n" return xml end
Generates xml for the Entry object .
20,513
def location_media ( location_id , request_parameters : { limit : 1000 } , limit : 10 ) location = extract_location_media ( location_id , request_parameters : request_parameters ) paging_info = location . paging_info while location . total_media_count < limit && paging_info [ :has_next_page ] do request_opts = { } . merge ( request_parameters ) if paging_info && paging_info [ :end_cursor ] request_opts [ :max_id ] = paging_info [ :end_cursor ] end next_page_location = extract_location_media ( location_id , request_parameters : request_opts ) location . add_media ( next_page_location . media ) paging_info = next_page_location . paging_info location end location end
returns a location with media attached for the given location id
20,514
def extract_location_media ( location_id , request_parameters : { } ) uri = "explore/locations/#{location_id}/" data = request ( uri : uri , parameters : request_parameters ) body = data . body [ :location ] location = Entities :: Location . new attrs = %i[ name lat lng id ] attrs . each do | attribute | location . send ( "#{attribute}=" , body [ attribute ] ) end media = { } body [ :media ] . fetch ( :nodes , [ ] ) . each do | medium | media [ medium [ :id ] ] = Entities :: MediumNode . new ( medium ) end location . media = media . values location . top_posts = body [ :top_posts ] . fetch ( :nodes , [ ] ) . map { | d | Entities :: MediumNode . new ( d ) } location . paging_info = body [ :media ] . fetch ( :page_info , { } ) location end
performs the actual request to the API .
20,515
def request ( uri : , request_options : { } , parameters : { } ) opts = { uri : uri , request_options : request_options , parameters : @default_parameters . merge ( parameters ) } parse_response ( http_service . perform_request ( opts ) ) end
perform the actual request . receives a URI as argument . Optional parameters and request parameter options can be passed .
20,516
def parse_response ( response ) OpenStruct . new ( raw_response : response , body : JSON . parse ( response . body , symbolize_names : true ) ) end
parses the raw response by the remote . returns an object with a raw_response as method and the parsed body associated .
20,517
def default_options { :host => host , :port => port , :path_prefix => path_prefix , :use_ssl => use_ssl , :request_style => request_style , :num_retries => num_retries , :timeout => timeout , :extra_env => extra_env , :http_adapter => http_adapter , :stubs => stubs , :return_full_response => return_full_response , :additional_middlewares => self . additional_middlewares } end
Construct our default options based upon the class methods
20,518
def instrument ( type , name , opts = { } ) txn = :: HeimdallApm :: TransactionManager . current segment = :: HeimdallApm :: Segment . new ( type , name ) txn . start_segment ( segment ) yield ensure txn . stop_segment end
Insruments block passed to the method into the current transaction .
20,519
def names ( filter = nil ) inject ( [ ] ) do | mem , spec | case filter when :visible mem << spec . name if spec . visible? end mem end . sort end
Return a convenient sorted list of all generator names .
20,520
def each Dir [ "#{path}/[a-z]*" ] . each do | dir | if File . directory? ( dir ) yield Spec . new ( File . basename ( dir ) , dir , label ) end end end
Yield each eligible subdirectory .
20,521
def each generator_full_paths . each do | generator | yield Spec . new ( File . basename ( generator ) . sub ( / / , '' ) , File . dirname ( generator ) , label ) end end
Yield each generator within rails_generator subdirectories .
20,522
def secure_match? ( token ) ActiveSupport :: SecurityUtils . secure_compare ( :: Digest :: SHA256 . hexdigest ( token ) , :: Digest :: SHA256 . hexdigest ( verification_token ) ) end
Compare the tokens in a time - constant manner to mitigate timing attacks .
20,523
def render * arguments if @_mxit_emulator output = render_to_string * arguments output = MxitRails :: Styles . add_emoticons output super :inline => output else super * arguments end end
Override render method so as to inject emoticons etc
20,524
def user_code_request_uri ( redirect_uri , state , scopes ) if scopes . empty? raise MxitApi :: Exception . new ( "No scopes were provided." ) end parameters = { :response_type => "code" , :client_id => @client_id , :redirect_uri => redirect_uri , :state => state , :scope => scopes . join ( ' ' ) } path = MXIT_AUTH_CODE_URI + "?#{URI.encode_www_form(parameters)}" end
The user s response to the authorisation code request will be redirected to redirect_uri . If the request was successful there will be a code request parameter ; otherwise error .
20,525
def message ( client_id , string , reliable = false , channel = ChannelManager :: CHAT ) GameOverseer :: ENetServer . instance . transmit ( client_id , string , reliable , channel ) end
Send a message to a specific client
20,526
def broadcast ( string , reliable = false , channel = ChannelManager :: CHAT ) GameOverseer :: ENetServer . instance . broadcast ( string , reliable , channel ) end
Send a message to all connected clients
20,527
def row_class report_columns = viable_report_columns @row_class ||= Class . new do report_columns . each do | report_column | attr_accessor report_column . column_name . to_sym end def initialize params = { } params . each { | key , value | send "#{key}=" , value } end def [] ( key ) self . send key end end end
This ephemeral class allows us to create a row object that has the same attributes as the AR response to the query including all the custom columns defined in the resource class report config . currently only used for the summary row since we can t get that in the same AR query and have to add it to the collection after the query returns .
20,528
def report_filter_params Hash [ * viable_report_filters . map { | filter | filter . filter_match_params } . flatten ] . merge ( order : self . sorter ) end
These are the built - in filter params that define this report . They are merged at a later step with the runtime params entered by the user for a specific report run . nb . the sorter column here may be overridden by a runtime sort if requested by the user .
20,529
def custom_filters self . resource_class . report_filter_options . select { | filter | viable_report_filters . map ( & :filter_name ) . exclude? filter . param } end
These are the filters available at runtime ie . not including the ones set to define this report . If updating the report this is the set available to add as new report definition filters .
20,530
def available_columns column_options . reject { | column | viable_report_columns . map ( & :column_name ) . include? column . name . to_s } end
This is the set of columns not chosed to use in the report . These are the ones available to add when updating a report .
20,531
def each_sat return to_enum ( :each_sat ) unless block_given? sat_loop ( self ) do | sat , solver | yield sat negated_vars = sat . terms . map do | t | t . is_a? ( NotTerm ) ? t . terms [ 0 ] : ~ t end solver << PropLogic . all_or ( * negated_vars ) end end
loop with each satisfied terms .
20,532
def fetch_app_version ( options ) metadata = AppRepo :: Uploader . new ( options ) . download_manifest_only FastlaneCore :: UI . command_output ( 'TODO: Parse version out from metadata' ) puts JSON . pretty_generate ( metadata ) unless metadata . nil? FastlaneCore :: UI . important ( 'TODO: parse out the bundle-version' ) metadata [ 'bundle-version' ] end
Fetches remote app version from metadata
20,533
def format ( event ) buff = "%5s" % ( event . data . is_a? ( Array ) ? event . data . first : event . name ) buff << ": " buff << format_object ( event . data . is_a? ( Array ) ? event . data . last : event . data ) buff << ( event . tracer . nil? ? "" : " (#{event.tracer.join('/')})" ) buff << "\n" buff end
= begin rdoc If event is an Array the output is adapted .
20,534
def valid_api_key? ( api_key = nil ) api_key ||= @api_key return false if api_key . empty? res = client . get ( "/api/#{@api_version}/user/#{api_key}/user-information" ) return false if ! res . success? || res . body . has_key? ( "error" ) return true end
Initialize a client which will be used to communicate with WaniKani .
20,535
def client Faraday . new ( url : Wanikani :: API_ENDPOINT ) do | conn | conn . response :json , :content_type => / \b / conn . adapter Faraday . default_adapter end end
Sets up the HTTP client for communicating with the WaniKani API .
20,536
def api_response ( resource , optional_arg = nil ) raise ArgumentError , "You must define a resource to query WaniKani" if resource . nil? || resource . empty? begin res = client . get ( "/api/#{@api_version}/user/#{@api_key}/#{resource}/#{optional_arg}" ) if ! res . success? || res . body . has_key? ( "error" ) raise_exception ( res ) else return res . body end rescue => error raise Exception , "There was an error: #{error.message}" end end
Contacts the WaniKani API and returns the data specified .
20,537
def raise_exception ( response ) raise Wanikani :: InvalidKey , "The API key used for this request is invalid." and return if response . status == 401 message = if response . body . is_a? ( Hash ) and response . body . has_key? ( "error" ) response . body [ "error" ] [ "message" ] else "Status code: #{response.status}" end raise Wanikani :: Exception , "There was an error fetching the data from WaniKani (#{message})" end
Handles exceptions according to the API response .
20,538
def [] ( key ) if ! @fields . has_key? ( key ) && ! @fseq . empty? while true @fseq = @fseq . skip_whitespace if @fseq . first == 125 @fseq = @fseq . skip_byte ( 125 ) . skip_whitespace break end new_key , new_value = read_field_and_consume @fields [ new_key ] = new_value break if new_key == key end end @fields [ key ] end
Access a field lazily parsing if not yet parsed
20,539
def [] ( i ) if @elements . size <= i && ! @eseq . empty? while true @eseq = @eseq . skip_whitespace if @eseq . first == 93 @eseq = @eseq . skip_byte ( 93 ) . skip_whitespace break end new_value = read_value_and_consume @elements << new_value break if @elements . size > i end end @elements [ i ] end
Access an element lazily parsing if not yet parsed
20,540
def configuration ( configuration_file = nil ) return @configuration if @configuration logger . debug "getting repo_manager configuration" app_options = { } app_options [ :config ] = configuration_file || options [ :config ] @configuration = :: RepoManager :: Settings . new ( nil , app_options ) end
main repo_manager configuration setttings file
20,541
def request ( method , action , params = { } , options = { } ) options [ :call_chain ] = _path_array options [ :action ] = action @requester . send ( method , _path ( action ) , params , options ) end
Each endpoint needs to have a requester in order to ... make ... uh ... requests . Generic request wrapper
20,542
def _build_and_attach_node ( endpoint_class , method_name = nil ) endpoint_instance = endpoint_class . new ( @requester , method_name , self ) method_name ||= endpoint_class . name . demodulize . underscore self . instance_variable_set ( "@#{method_name}" , endpoint_instance ) self . define_singleton_method ( method_name . to_s ) { endpoint_instance } endpoint_instance end
Create an endpoint instance and foist it upon this node Not private but not part of the public interface for an endpoint
20,543
def _endpoint_chain chain = [ ] node = self while node . is_a? ( BaseEndpoint ) chain << node node = node . parent end chain . reverse end
Get the parent chain that led to this endpoint
20,544
def perform_request ( request_options : { } , parameters : { } , uri : ) args = parameters request_options = request_options . merge ( faraday_options ) connection = Faraday . new ( faraday_options ) do | faraday | faraday . adapter Faraday . default_adapter end connection . get ( uri , args ) end
performs the actual http request
20,545
def write_game_balance write_single_file ( "analyze" ) dir = File . join ( "analyze" , parser_name ) dir = File . join ( dir , @field . to_s ) if @field write_analyzed ( dir ) end
Writing if GameBalance
20,546
def write_analyzed ( dir ) FileUtils . mkdir_p ( dir ) attributes . each do | a , v | path = File . join ( dir , a . to_s ) s = "Count|Value\n" + v . map { | e | "#{e[:count]}|#{e[:value]}" } . join ( "\n" ) File . open ( "#{path}.csv" , 'w' ) { | f | f . write ( s ) } end end
Writing multiple files to given dir .
20,547
def attributes return @attributes if @attributes unsorted = Hash . new { | h , k | h [ k ] = Hash . new ( 0 ) } snapshots . each do | attributes | attributes = attributes [ @field ] if @field attributes . each do | h | h . each { | attribute , value | unsorted [ attribute ] [ value ] += 1 } end end @attributes = Hash . new { | h , k | h [ k ] = [ ] } unsorted . each do | name , h | h . each do | value , count | @attributes [ name ] << { :value => value , :count => count } end @attributes [ name ] . sort! { | x , y | y [ :count ] <=> x [ :count ] } end return @attributes end
Return analyzed attributes
20,548
def to_s extras_s = extras_to_s key_s = self [ :key ] . to_s value_s = self [ :value ] . to_s self [ :extras_length ] = extras_s . length self [ :key_length ] = key_s . length self [ :total_body_length ] = extras_s . length + key_s . length + value_s . length header_to_s + extras_s + key_s + value_s end
Serialize for wire
20,549
def remove_from_cart_link ( item ) link_to ( mongoid_cart . remove_item_path ( item : { type : item . class . to_s , id : item . _id } ) , { class : "btn btn-default" } ) do ( tag :i , class : 'fa fa-cart-plus' ) . concat ( 'Remove from cart' ) end end
link_to mongoid_cart . remove_item_path
20,550
def add_to_cart_link ( item ) link_to ( mongoid_cart . add_item_path ( item : { type : item . class . to_s , id : item . _id } ) , { class : "btn btn-default" } ) do ( tag :i , class : 'fa fa-cart-plus' ) . concat ( 'Add to cart' ) end end
link_to mongoid_cart . add_item_path
20,551
def stats ( contents = { } , & callback ) send_request Request :: Stats . new ( contents ) do | result | callback . call result if result [ :status ] == Errors :: NO_ERROR && result [ :key ] != '' :proceed end end end
Callback will be called multiple times
20,552
def to_base ( other_base ) if other_base == @radix dup else normalization = exact? ? :exact : :approximate Numeral . from_quotient to_quotient , base : other_base , normalize : normalization end end
Convert a Numeral to a different base
20,553
def approximate! ( number_of_digits = nil ) if number_of_digits . nil? if exact? && ! repeating? @repeat = nil end else expand! number_of_digits @digits . truncate! number_of_digits @repeat = nil end self end
Expand to the specified number of digits then truncate and remove repetitions . If no number of digits is given then it will be converted to approximate numeral only if it is not repeating .
20,554
def flatten ( translations , current_scope = nil ) translations . each_with_object ( { } ) do | ( key , value ) , memo | scope = current_scope ? join ( current_scope , key ) : key . to_s if value . is_a? ( Hash ) memo . merge! ( flatten ( value , scope ) ) else memo [ scope ] = value end end end
Recurrently flattens hash by converting its keys to fully scoped ones .
20,555
def cross_join ( locales , keys ) locales . flat_map do | locale | keys . map { | key | join ( locale , key ) } end end
Combines each locale with all keys .
20,556
def create_column ( data , column ) data [ :columns ] [ column ] = { } res = data [ :columns ] [ column ] analyzers . each do | analyzer | analyzer_class = analyzer [ :class ] res [ analyzer [ :name ] ] = { class : analyzer_class . new , results : create_results ( analyzer_class ) } end res end
Create column analyzers
20,557
def update_numeric_results ( ac , ar , val ) cval = ac . convert ( val ) ar [ :min ] = cval if ar [ :min ] . nil? || cval < ar [ :min ] ar [ :max ] = cval if ar [ :max ] . nil? || cval > ar [ :max ] end
Update numeric results
20,558
def link_to_page ( page , paginated_set , options = { } , html_options = { } ) page_parameter = peiji_san_option ( :page_parameter , options ) pageable_params = respond_to? ( :controller ) ? controller . params : self . params url_options = ( page == 1 ? pageable_params . except ( page_parameter ) : pageable_params . merge ( page_parameter => page ) ) anchor = peiji_san_option ( :anchor , options ) url_options [ :anchor ] = anchor if anchor html_options [ :class ] = peiji_san_option ( :current_class , options ) if paginated_set . current_page? ( page ) normalized_url_options = if respond_to? ( :controller ) url_for ( url_options ) else root_path = env [ 'PATH_INFO' ] . blank? ? "/" : env [ "PATH_INFO" ] url_for ( root_path , url_options ) end link_to page , normalized_url_options , html_options end
Creates a link using + link_to + for a page in a pagination collection . If the specified page is the current page then its class will be current .
20,559
def pages_to_link_to ( paginated_set , options = { } ) current , last = paginated_set . current_page , paginated_set . page_count max = peiji_san_option ( :max_visible , options ) separator = peiji_san_option ( :separator , options ) if last <= max ( 1 .. last ) . to_a elsif current <= ( ( max / 2 ) + 1 ) ( 1 .. ( max - 2 ) ) . to_a + [ separator , last ] elsif current >= ( last - ( max / 2 ) ) [ 1 , separator , * ( ( last - ( max - 3 ) ) .. last ) ] else offset = ( max - 4 ) / 2 [ 1 , separator ] + ( ( current - offset ) .. ( current + offset ) ) . to_a + [ separator , last ] end end
Returns an array of pages to link to . This array includes the separator so make sure to keep this in mind when iterating over the array and creating links .
20,560
def devices send ( :devdetails ) do | body | body [ :devdetails ] . collect { | attrs | attrs . delete ( :devdetails ) attrs [ :variant ] = attrs . delete ( :name ) . downcase attrs } end end
Initializes a new Client for executing commands .
20,561
def send ( command , * parameters , & block ) socket = TCPSocket . open ( host , port ) socket . puts command_json ( command , * parameters ) parse ( socket . gets , & block ) ensure socket . close if socket . respond_to? ( :close ) end
Sends the supplied command with optionally supplied parameters to the service and returns the result if any .
20,562
def output_errors ( title , options = { } , fields = nil , flash_only = false ) fields = [ fields ] unless fields . is_a? ( Array ) flash_html = render ( :partial => 'shared/flash_messages' ) flash . clear css_class = "class=\"#{options[:class] || 'error'}\"" unless options [ :class ] . nil? field_errors = render ( :partial => 'shared/field_error' , :collection => fields ) if flash_only || ( ! flash_html . empty? && field_errors . empty? ) render ( :partial => 'shared/flash_error_box' , :locals => { :flash_html => flash_html , :css_class => css_class } ) elsif ! field_errors . empty? render ( :partial => 'shared/error_box' , :locals => { :title => title , :flash_html => flash_html , :field_errors => field_errors , :css_class => css_class , :extra_html => options [ :extra_html ] } ) else '' end end
Output flash and object errors
20,563
def output_admin_messages ( fields = nil , title = '' , options = { :class => 'notify-box' } , flash_only = false ) output_errors_ajax ( 'admin-messages' , title , options , fields , flash_only ) end
Output a page update that will display messages in the flash
20,564
def pagination_number_list ( 0 ... page_button_count ) . to_a . map do | n | link_number = n + page_number_offset number_span ( link_number ) end . join ( ' ' ) end
List of number links for the number range between next and previous
20,565
def add_observer ( observer = nil , func = :update , & block ) if observer . nil? && block . nil? raise ArgumentError , 'should pass observer as a first argument or block' elsif observer && block raise ArgumentError . new ( 'cannot provide both an observer and a block' ) end if block observer = block func = :call end begin @mutex . lock new_observers = @observers . dup new_observers [ observer ] = func @observers = new_observers observer ensure @mutex . unlock end end
Adds an observer to this set . If a block is passed the observer will be created by this method and no other params should be passed
20,566
def parse ( data ) rss = SimpleRSS . parse data news = Array . new rss . items . each do | item | news_item = NewsItem . new ( item . title , item . link , item . description . force_encoding ( "UTF-8" ) , item . pubDate ) news . push news_item end unless @limit . nil? news . take ( @limit ) else news end end
Parses raw data and returns news items
20,567
def columns_indeces_to_drop columns result = [ ] headers = @table [ 0 ] headers . each_with_index do | header , i | result << i unless columns . include? header end result end
Returns the column indeces to drop to make this table have the given columns
20,568
def dry_up row return row unless @previous_row row . clone . tap do | result | row . length . times do | i | if can_dry? ( @headers [ i ] ) && row [ i ] == @previous_row [ i ] result [ i ] = '' else break end end end end
Returns a dried up version of the given row based on the row that came before in the table
20,569
def fetch ( data , keys , default = nil , format = false ) if keys . is_a? ( String ) || keys . is_a? ( Symbol ) keys = [ keys ] end keys = keys . flatten . compact key = keys . shift if data . has_key? ( key ) value = data [ key ] if keys . empty? return filter ( value , format ) else return fetch ( data [ key ] , keys , default , format ) if data [ key ] . is_a? ( Hash ) end end return filter ( default , format ) end
Recursively fetch value for key path in the configuration object .
20,570
def modify ( data , keys , value = nil , delete_nil = false , & block ) if keys . is_a? ( String ) || keys . is_a? ( Symbol ) keys = [ keys ] end keys = keys . flatten . compact key = keys . shift has_key = data . has_key? ( key ) existing = { :key => key , :value => ( has_key ? data [ key ] : nil ) } if keys . empty? if value . nil? && delete_nil data . delete ( key ) if has_key else value = symbol_map ( value ) if value . is_a? ( Hash ) data [ key ] = block ? block . call ( key , value , existing [ :value ] ) : value end else data [ key ] = { } unless has_key if data [ key ] . is_a? ( Hash ) existing = modify ( data [ key ] , keys , value , delete_nil , & block ) else existing [ :value ] = nil end end return existing end
Modify value for key path in the configuration object .
20,571
def get ( keys , default = nil , format = false ) return fetch ( @properties , symbol_array ( array ( keys ) . flatten ) , default , format ) end
Fetch value for key path in the configuration object .
20,572
def set ( keys , value , delete_nil = false , & code ) modify ( @properties , symbol_array ( array ( keys ) . flatten ) , value , delete_nil , & code ) return self end
Set value for key path in the configuration object .
20,573
def append ( keys , value ) modify ( @properties , symbol_array ( array ( keys ) . flatten ) , value , false ) do | key , processed_value , existing | if existing . is_a? ( Array ) [ existing , processed_value ] . flatten else [ processed_value ] end end return self end
Append a value for an array key path in the configuration object .
20,574
def prepend ( keys , value , reverse = false ) modify ( @properties , symbol_array ( array ( keys ) . flatten ) , value , false ) do | key , processed_value , existing | processed_value = processed_value . reverse if reverse && processed_value . is_a? ( Array ) if existing . is_a? ( Array ) [ processed_value , existing ] . flatten else [ processed_value ] end end return self end
Prepend a value to an array key path in the configuration object .
20,575
def delete ( keys , default = nil ) existing = modify ( @properties , symbol_array ( array ( keys ) . flatten ) , nil , true ) return existing [ :value ] unless existing [ :value ] . nil? return default end
Delete key path from the configuration object .
20,576
def defaults ( defaults , options = { } ) config = Config . new ( options ) . set ( :import_type , :default ) return import_base ( defaults , config ) end
Set default property values in the configuration object if they don t exist .
20,577
def symbol_array ( array ) result = [ ] array . each do | item | result << item . to_sym unless item . nil? end result end
Return a symbolized array
20,578
def signup params plan = params . delete ( :plan ) lines = params . delete ( :lines ) || [ ] _customer_ = Stripe :: Customer . create ( params ) lines . each do | ( amount , desc ) | _customer_ . add_invoice_item ( { currency : 'usd' , amount : amount , description : desc } ) end _customer_ . update_subscription ( { plan : plan } ) StripeLocal :: Customer . create _customer_ . to_hash . reverse_merge ( { model_id : self . id } ) end
== this is the primary interface for subscribing .
20,579
def simple ( name = nil ) workbook . add_worksheet ( name : name || 'Sheet 1' ) do | sheet | yield sheet , workbook . predefined_styles if block_given? sheet . add_row end end
Creates a simple workbook with one sheet .
20,580
def predefined_styles @predefined_styles ||= begin tmp = { } styles do | s | tmp = { bold : s . add_style ( b : true , alignment : { vertical : :top } ) , date : s . add_style ( format_code : 'mm/dd/yyyy' , alignment : { vertical : :top } ) , float : s . add_style ( format_code : '#,##0.00' , alignment : { vertical : :top } ) , integer : s . add_style ( format_code : '#,##0' , alignment : { vertical : :top } ) , percent : s . add_style ( num_fmt : 9 , alignment : { vertical : :top } ) , currency : s . add_style ( num_fmt : 7 , alignment : { vertical : :top } ) , text : s . add_style ( format_code : '@' , alignment : { vertical : :top } ) , wrapped : s . add_style ( alignment : { wrap_text : true , vertical : :top } ) , normal : s . add_style ( alignment : { vertical : :top } ) } end tmp end end
Gets the predefined style list .
20,581
def add_combined_row ( row_data , keys = [ :value , :style , :type ] ) val_index = keys . index ( :value ) || keys . index ( 'value' ) style_index = keys . index ( :style ) || keys . index ( 'style' ) type_index = keys . index ( :type ) || keys . index ( 'type' ) raise ArgumentError . new ( 'Missing :value key' ) unless val_index values = row_data . map { | v | v . is_a? ( Array ) ? v [ val_index ] : v } styles = style_index ? row_data . map { | v | v . is_a? ( Array ) ? v [ style_index ] : nil } : [ ] types = type_index ? row_data . map { | v | v . is_a? ( Array ) ? v [ type_index ] : nil } : [ ] styles . each_with_index do | style , index | if style . is_a? ( String ) || style . is_a? ( Symbol ) styles [ index ] = workbook . predefined_styles [ style . to_sym ] end end add_row values , style : styles , types : types end
Adds a row to the worksheet with combined data .
20,582
def join ( source , target , * fields , & block ) FileUtils . rm_rf OUTPUT sf = File . expand_path ( "#{source}.csv" , File . dirname ( __FILE__ ) ) tf = File . expand_path ( "#{target}.csv" , File . dirname ( __FILE__ ) ) Jinx :: CsvIO . join ( sf , :to => tf , :for => fields , :as => OUTPUT , & block ) if File . exists? ( OUTPUT ) then File . readlines ( OUTPUT ) . map do | line | line . chomp . split ( ',' ) . map { | s | s unless s . blank? } end else Array :: EMPTY_ARRAY end end
Joins the given source fixture to the target fixture on the specified fields .
20,583
def state_select ( method , options = { } , html_options = { } , additional_state = nil ) country_id_field_name = options . delete ( :country_id ) || 'country_id' country_id = get_instance_object_value ( country_id_field_name ) @states = country_id . nil? ? [ ] : ( additional_state ? [ additional_state ] : [ ] ) + State . find ( :all , :conditions => [ "country_id = ?" , country_id ] , :order => "name asc" ) self . menu_select ( method , I18n . t ( 'muck.engine.choose_state' ) , @states , options . merge ( :prompt => I18n . t ( 'muck.engine.select_state_prompt' ) , :wrapper_id => 'states-container' ) , html_options . merge ( :id => 'states' ) ) end
creates a select control with states . Default id is states . If retain is passed for the class value the value of this control will be written into a cookie with the key states .
20,584
def country_select ( method , options = { } , html_options = { } , additional_country = nil ) @countries ||= ( additional_country ? [ additional_country ] : [ ] ) + Country . find ( :all , :order => 'sort, name asc' ) self . menu_select ( method , I18n . t ( 'muck.engine.choose_country' ) , @countries , options . merge ( :prompt => I18n . t ( 'muck.engine.select_country_prompt' ) , :wrapper_id => 'countries-container' ) , html_options . merge ( :id => 'countries' ) ) end
creates a select control with countries . Default id is countries . If retain is passed for the class value the value of this control will be written into a cookie with the key countries .
20,585
def language_select ( method , options = { } , html_options = { } , additional_language = nil ) @languages ||= ( additional_language ? [ additional_language ] : [ ] ) + Language . find ( :all , :order => 'name asc' ) self . menu_select ( method , I18n . t ( 'muck.engine.choose_language' ) , @languages , options . merge ( :prompt => I18n . t ( 'muck.engine.select_language_prompt' ) , :wrapper_id => 'languages-container' ) , html_options . merge ( :id => 'languages' ) ) end
creates a select control with languages . Default id is languages . If retain is passed for the class value the value of this control will be written into a cookie with the key languages .
20,586
def add_success_to ( user , message , client_ip ) Incline :: Log :: info "LOGIN(#{user}) SUCCESS FROM #{client_ip}: #{message}" purge_old_history_for user user . login_histories . create ( ip_address : client_ip , successful : true , message : message ) end
Logs a success message for a user .
20,587
def credential = cr if File . exist? ( cr ) && File . file? ( cr ) cr = File . read cr end @credential = case cr when Hash , ActiveSupport :: HashWithIndifferentAccess cr when String JSON . parse cr else raise "Invalid data type" end end
File name or json string or hash
20,588
def method_missing ( method , * args , & blk ) if app_should_handle_method? method app . send ( method , * args , & blk ) else super end end
copied from the URL implementation ... weird but I want to have classes not methods for this
20,589
def require_super_admin unless @current_user . super_admin? text = "#{I18n.t("authentication.permission_denied.heading")}: #{I18n.t("authentication.permission_denied.message")}" set_flash_message ( text , :error , false ) if defined? ( flash ) && flash redirect_or_popup_to_default_sign_in_page ( false ) end end
This method is usually used as a before filter from admin controllers to ensure that the logged in user is a super admin
20,590
def render ( * args ) name = get_template_name ( * args ) locals = args . last . is_a? ( Hash ) ? args . last : { } template_file = self . class . find_template ( name ) ext = template_file . split ( '.' ) . last orig_buffer = @output_buffer @output_buffer = Curtain :: OutputBuffer . new case ext when 'slim' template = :: Slim :: Template . new ( template_file , :buffer => '@output_buffer' , :use_html_safe => true , :disable_capture => true , :generator => Temple :: Generators :: RailsOutputBuffer ) when 'erb' template = :: Curtain :: ErubisTemplate . new ( template_file , :buffer => '@output_buffer' , :use_html_safe => true , :disable_capture => true , :generator => Temple :: Generators :: RailsOutputBuffer ) else raise "Curtain cannot process .#{ext} templates" end template . render ( self , variables . merge ( locals ) ) @output_buffer ensure @output_buffer = orig_buffer end
Renders the template
20,591
def [] ( x , y ) if x . respond_to? ( :to_i ) && y . respond_to? ( :to_i ) Cell . new ( x , y , self ) else Zone . new ( x , y , self ) end end
Accessing a cell or a zone .
20,592
def []= ( x , y , content ) if content . nil? @store . delete ( [ x , y ] ) && nil else @store [ [ x , y ] ] = content end end
Putting new content in a cell .
20,593
def create_new_node ( project_root , environment ) hostname = ask_not_existing_hostname ( project_root , environment ) ip = ask_ip ( environment ) node = Bebox :: Node . new ( environment , project_root , hostname , ip ) output = node . create ok _ ( 'wizard.node.creation_success' ) return output end
Create a new node
20,594
def remove_node ( project_root , environment , hostname ) nodes = Bebox :: Node . list ( project_root , environment , 'nodes' ) if nodes . count > 0 hostname = choose_option ( nodes , _ ( 'wizard.node.choose_node' ) ) else error _ ( 'wizard.node.no_nodes' ) % { environment : environment } return true end return warn ( _ ( 'wizard.no_changes' ) ) unless confirm_action? ( _ ( 'wizard.node.confirm_deletion' ) ) node = Bebox :: Node . new ( environment , project_root , hostname , nil ) output = node . remove ok _ ( 'wizard.node.deletion_success' ) return output end
Removes an existing node
20,595
def set_role ( project_root , environment ) roles = Bebox :: Role . list ( project_root ) nodes = Bebox :: Node . list ( project_root , environment , 'nodes' ) node = choose_option ( nodes , _ ( 'wizard.choose_node' ) ) role = choose_option ( roles , _ ( 'wizard.choose_role' ) ) output = Bebox :: Provision . associate_node_role ( project_root , environment , node , role ) ok _ ( 'wizard.node.role_set_success' ) return output end
Associate a role with a node in a environment
20,596
def prepare ( project_root , environment ) nodes_to_prepare = check_nodes_to_prepare ( project_root , environment ) if nodes_to_prepare . count > 0 title _ ( 'wizard.node.prepare_title' ) nodes_to_prepare . each { | node | msg ( node . hostname ) } linebreak Bebox :: Node . regenerate_deploy_file ( project_root , environment , nodes_to_prepare ) up_vagrant_machines ( project_root , nodes_to_prepare ) if environment == 'vagrant' nodes_to_prepare . each do | node | node . prepare ok _ ( 'wizard.node.preparation_success' ) end else warn _ ( 'wizard.node.no_prepare_nodes' ) end return true end
Prepare the nodes in a environment
20,597
def check_nodes_to_prepare ( project_root , environment ) nodes_to_prepare = [ ] nodes = Bebox :: Node . nodes_in_environment ( project_root , environment , 'nodes' ) prepared_nodes = Bebox :: Node . list ( project_root , environment , 'prepared_nodes' ) nodes . each do | node | if prepared_nodes . include? ( node . hostname ) message = _ ( 'wizard.node.confirm_preparation' ) % { hostname : node . hostname , start : node . checkpoint_parameter_from_file ( 'prepared_nodes' , 'started_at' ) , end : node . checkpoint_parameter_from_file ( 'prepared_nodes' , 'finished_at' ) } nodes_to_prepare << node if confirm_action? ( message ) else nodes_to_prepare << node end end nodes_to_prepare end
Check the nodes already prepared and ask confirmation to re - do - it
20,598
def ask_not_existing_hostname ( project_root , environment ) hostname = ask_hostname ( project_root , environment ) if node_exists? ( project_root , environment , hostname ) error _ ( 'wizard.node.hostname_exist' ) ask_hostname ( project_root , environment ) else return hostname end end
Keep asking for a hostname that not exist
20,599
def ask_ip ( environment ) ip = write_input ( _ ( 'wizard.node.ask_ip' ) , nil , / \. / , _ ( 'wizard.node.valid_ip' ) ) return ip if environment != 'vagrant' if free_ip? ( ip ) return ip else error _ ( 'wizard.node.non_free_ip' ) ask_ip ( environment ) end end
Ask for the ip until is valid