idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
24,100
def group ( group_name , & block ) group_key = group_name . to_s @current_nesting_level [ group_key ] ||= { } if block_given? within_group ( group_key ) do instance_eval & block end end end
Adds price group to the current nesting level of price definition . Groups are useful for price breakdown categorization and easy subtotal values .
24,101
def query = ( search_term ) @search_term = case search_term when nil , '' then [ ] when String , Symbol then [ search_term ] when Array then search_term . flatten . select { | e | [ String , Symbol ] . include? e . class } else fail ArgumentError , 'search_term must be a String, Symbol or Array. ' "#{ search_term.inspe...
Change the search term triggering a query rebuild and clearing past results .
24,102
def options = ( options ) fail ArgumentError , 'options must be a Hash. ' "#{ options.inspect } given." unless options . is_a? ( Hash ) @options . merge! options build_query end
Change search options with a hash triggering a query string rebuild and clearing past results .
24,103
def build_query @query = @search_term . dup @pages = - 1 @results = [ ] @query << "\"#{ @options[:exact] }\"" if @options [ :exact ] @query << @options [ :or ] . join ( ' OR ' ) unless @options [ :or ] . nil? or @options [ :or ] . empty? @query += @options [ :without ] . map { | s | "-#{ s }" } if @options [ :without ]...
Clear out the query and rebuild it from the various stored options . Also clears out the results set and sets pages back to - 1
24,104
def results_column ( name ) @results . compact . map do | rs | rs . map { | r | r [ name ] || r [ name [ 0 ... - 1 ] . intern ] } end . flatten end
Fetch a list of values from the results set given by name
24,105
def full_name display_name_parts = [ first_name , last_name ] . compact if display_name_parts . empty? username else display_name_parts . join ( ' ' ) end end
A display - friendly name for this user . Uses first_name and last_name if available otherwise it just uses the username .
24,106
def concat_partial ( partial , * args , & block ) rendered = invoke_partial partial , * args , & block concat rendered end
Used to create nice templated tags while keeping the html out of our helpers . Additionally this can be invoked implicitly by invoking the partial as a method with _ prepended to the name .
24,107
def valid_credentials? ( kind , * credentials ) found_username = ( all_credentials ( kind ) . detect { | c | c [ :credentials ] == credentials } || { } ) [ :username ] @users [ found_username ] end
AUTHORITY API IMPLEMENTATION
24,108
def load! ( io ) doc = YAML . load ( io ) return self unless doc ( doc [ "groups" ] || { } ) . each do | portal , top_level_groups | @groups [ portal . to_sym ] = top_level_groups . collect { | group_data | build_group ( group_data ) } end ( doc [ "users" ] || { } ) . each do | username , config | attr_keys = config . ...
Loads a YAML doc and uses its contents to initialize the authority s authentication and authorization data .
24,109
def broadcast ( name , message , opts = { } ) encap = { n : name , m : message , t : opts [ :to ] || / / , e : opts [ :except ] || [ ] } EM . next_tick { @faye . publish BROADCAST , Base64 . urlsafe_encode64 ( Marshal . dump ( encap ) ) } end
Creates a new reaction client .
24,110
def action_link ( scope , link_data ) value = nil case link_data when Proc value = link_data . call ( scope ) when Hash relation = link_data . keys . first entity = Fields :: Reader . field_value ( scope , relation ) unless entity . present? return '' end if link_data [ relation ] [ :label_field ] . present? value = fi...
to customise the actions for a resource define a list of actions
24,111
def apply_addresslogic ( options = { } ) n = options [ :namespace ] options [ :fields ] ||= [ "#{n}street1" . to_sym , "#{n}street2" . to_sym , [ "#{n}city" . to_sym , [ "#{n}state" . to_sym , "#{n}zip" . to_sym ] ] , "#{n}country" . to_sym ] self . addresslogic_options = options include Addresslogic :: InstanceMethods...
Mixes in useful methods for handling addresses .
24,112
def hamiltonian_cycles_dynamic_programming ( operational_limit = nil ) stack = DS :: Stack . new return [ ] if @vertices . empty? origin_vertex = @vertices . to_a [ 0 ] hamiltonians = [ ] num_operations = 0 dp_cache = { } initial_vertex_set = Set . new ( @vertices . reject { | v | v == origin_vertex } ) initial_problem...
Use dynamic programming to find all the Hamiltonian cycles in this graph
24,113
def introspect_node ( node_uuid ) workflow = 'tripleo.baremetal.v1.introspect' input = { node_uuids : [ node_uuid ] } execute_workflow ( workflow , input , false ) end
THESE METHODS ARE TEMPORARY UNTIL IRONIC - DISCOVERD IS ADDED TO OPENSTACK AND KEYSTONE
24,114
def add_pages_for_scan! @pages_for_scan = [ ] @bad_pages = [ ] @pages . each do | page | @bad_pages << page . page_url unless page . page_a_tags next unless page . page_a_tags page . home_a . each do | link | @pages_for_scan << link end end end
add pages for scan array also add bad pages to bad_pages array
24,115
def add_page ( url ) unless robot_txt_allowed? ( url ) @scanned_pages << url return nil end page = Page . new ( url ) @pages << page @scanned_pages << url end
create Page and add to to site
24,116
def all_titles result = [ ] @pages . each do | page | result << [ page . page_url , page . all_titles ] if page . page_a_tags end result end
get all titles on site and return array of them
24,117
def all_descriptions result = [ ] @pages . each do | page | result << [ page . page_url , page . meta_desc_content ] if page . page_a_tags end result end
get all meta description tags content and return it as array
24,118
def all_h2 result = [ ] @pages . each do | page | result << [ page . page_url , page . h2_text ] unless page . page_a_tags end result end
get all h2 tags and return array of it
24,119
def all_a result = [ ] @pages . each do | page | next unless page . page_a_tags page . page_a_tags . compact . each do | tag | tag [ 0 ] = '-' unless tag [ 0 ] tag [ 1 ] = '-' unless tag [ 1 ] tag [ 2 ] = '-' unless tag [ 2 ] result << [ page . page_url , tag [ 0 ] , tag [ 1 ] , tag [ 2 ] ] end end result . compact end
get all a tags and return array of it
24,120
def convert_to_valid ( url ) return nil if url =~ / /i url . insert ( 0 , @main_url . first ( 5 ) ) if url . start_with? '//' link = URI ( url ) main_page = URI ( @main_url ) if link && link . scheme && link . scheme . empty? link . scheme = main_page . scheme elsif link . nil? return nil end if link . scheme =~ / / re...
check url and try to convert it to valid remove . jpg links add scheme to url
24,121
def read_char input = $stdin . getch return input unless input == "\e" begin Timeout . timeout ( 0.01 ) do input += $stdin . getch input += $stdin . getch end rescue Timeout :: Error end input end
Reads keypresses from the user including 2 and 3 escape character sequences .
24,122
def number_of_spaces todo . character_number - 1 - ( todo . line . length - todo . line . lstrip . length ) end
How many spaces before the carets should there be?
24,123
def create record , resources result = [ resources ] . flatten . map do | resource | resource = record . new ( resource ) unless resource . kind_of? ( record ) result = execute ( command_create ( record ) , * resource . tuple . values_at ( * record . header . insertable ) ) resource . tuple [ record . header . serial ]...
Create one or more .
24,124
def update record , resources result = [ resources ] . flatten . map do | resource | resource = record . new ( resource ) unless resource . kind_of? ( record ) keys = resource . tuple . values_at ( * record . header . keys ) raise ArgumentError , "#{record} resource has incomplete key: #{resource.inspect}" unless keys ...
Update one or more .
24,125
def delete record , resources result = [ resources ] . flatten . map do | resource | resource = record . new ( resource ) unless resource . kind_of? ( record ) keys = resource . tuple . values_at ( * record . header . keys ) raise ArgumentError , "#{record} resource has incomplete key: #{resource.inspect}" unless keys ...
Delete one or more .
24,126
def prepare record = nil , command record ? Statement . new ( record , command ) : db . prepare ( command ) end
Create a server side prepared statement
24,127
def execute command , * bind start = Time . now record , command = command , bind . shift if command . kind_of? ( Class ) && command < Record record ? Result . new ( record , db . execute ( command , * bind ) ) : db . execute ( command , * bind ) ensure log_command ( start , command , bind ) if @trace end
Execute a command using the underlying concrete adapter .
24,128
def method_missing ( name , * args , & block ) return meta [ name . to_s ] if meta . key? ( name . to_s ) super end
Initialize a new page which can be simply rendered or persisted to the filesystem .
24,129
def render ExtensionMatcher . new ( path ) . default { content } . on ( "html" ) { compress render_erb } . on ( "md" ) { compress render_erb } . on ( "erb" ) { compress render_erb } . match end
Render the current page .
24,130
def save_to ( path ) File . open ( path , "w" ) do | file | I18n . with_locale ( meta . locale ) do file << render end end end
Save current page to the specified path .
24,131
def _thread_local_clean ids = Thread . list . map & :object_id ( @_thread_local_threads . keys - ids ) . each { | key | @_thread_local_threads . delete ( key ) } end
remove the thread local maps for threads that are no longer active . likely to be painful if many threads are running .
24,132
def []= ( key , value ) return super if has_key? ( key ) alt = alternate_key ( key ) has_key? ( alt ) ? super ( alt , value ) : super end
Returns the property value for the key . If there is no key entry but there is an alternate key entry then alternate key entry is set .
24,133
def load_properties ( file ) raise ConfigurationError . new ( "Properties file not found: #{File.expand_path(file)}" ) unless File . exists? ( file ) properties = { } begin YAML . load_file ( file ) . each { | key , value | properties [ key . to_sym ] = value } rescue raise ConfigurationError . new ( "Could not read pr...
Loads the specified properties file replacing any existing properties .
24,134
def copy_file_if_missing ( file , to_directory ) unless File . exists? File . join ( to_directory , File . basename ( file ) ) FileUtils . cp ( file , to_directory ) end end
Copies a file to a target directory
24,135
def load_config ( file ) unless File . exists? file File . open ( file , 'w' ) do | f | YAML . dump ( { default_website : 'default' } , f ) end end YAML . load_file ( file ) end
Loads the configuration from a file
24,136
def datetime_to_s ( date_or_datetime , format ) return '' if date_or_datetime . blank? return date_or_datetime . to_s ( format ) if date_or_datetime . instance_of? ( Date ) date_or_datetime . localtime . to_s ( format ) end
Return _date_or_datetime_ converted to _format_ .
24,137
def authenticate_using_http_token return if current_user authenticate_with_http_token do | token_code , options | auth = Tokens :: Api . authenticate token_code @current_user = auth unless auth . kind_of? Symbol end end
The before_action that implements authenticates_using_http_token .
24,138
def format raise FormatError . new ( self ) unless formattable? REXML :: Document . new . tap do | doc | doc << REXML :: XMLDecl . new doc . elements << @log . format end end
Format as a XML document .
24,139
def execute ( method , * args ) new_args = args @pre_request . each do | middleware | new_args = middleware . call ( * new_args ) end path = new_args . empty? ? '' : new_args . shift req = proc do | | @resource [ path ] . send ( method , * new_args ) end post = proc do | result | @post_request . each do | middleware | ...
Execute a request using pre post and reject middleware .
24,140
def render ( parameters = { } ) has_thumbnail = parameters . fetch ( :has_thumbnail , true ) effect_number = parameters . fetch ( :effect_number , false ) thumbnail_template = self . get_template ( effect_number ) if has_thumbnail @attributes . map { | key , value | thumbnail_template [ "###{key}##" ] &&= value } thumb...
rendering image with thumbnail effect applied
24,141
def distance other , units = :km o = Itudes . new other raise ArgumentError . new "operand must be lat-/longitudable" if ( o . latitude . nil? || o . longitude . nil? ) dlat = Itudes . radians ( o . latitude - @latitude ) dlon = Itudes . radians ( o . longitude - @longitude ) lat1 = Itudes . radians ( @latitude ) lat2 ...
Calculates distance between two points on the Earth .
24,142
def promotions ( options = { } ) response = connection . get do | req | req . url "promotions" , options end return_error_or_body ( response ) end
Get a list of all promotions for the authenticating client .
24,143
def promotion_votes_leaderboard ( id , options = { } ) response = connection . get do | req | req . url "promotions/#{id}/votes_leaderboard" , options end return_error_or_body ( response ) end
Get a list of activities for a promotion ordered by the number of votes they have received
24,144
def get_player_image ( username , type , size ) url = "http://i.fishbans.com/#{type}/#{username}/#{size}" response = get ( url , false ) ChunkyPNG :: Image . from_blob ( response . body ) end
Gets the player image for the type .
24,145
def write_to_csv ( file_name , mode = "w" ) File . open ( file_name , mode ) do | file | all . copy_csv ( file ) end end
Opens the file provided and writes the relation to it as a CSV .
24,146
def process_stats @items = basic_collection handle_special_fields data = { alternatives : [ { type : 'spread' , uri : url_for ( action : "spread_stats" , field : params [ :field ] , filters : params [ :filters ] , only_path : true ) } , { type : 'process' } ] , from : @stat_from . to_time . utc . to_i * 1000 , thru : @...
This action generates a JSON for a process statistics .
24,147
def spread_stats @items = basic_collection . between_dates ( @stat_from , @stat_thru ) handle_special_fields data = { alternatives : [ { type : 'spread' } , { type : 'process' , uri : url_for ( action : "process_stats" , field : params [ :field ] , filters : params [ :filters ] , only_path : true ) } ] , from : @stat_f...
This action generates a JSON for a spread statistics .
24,148
def guess_from_thru begin @stat_thru = Time . parse ( params [ :thru ] ) . to_date rescue end begin @stat_from = Time . parse ( params [ :from ] ) . to_date rescue end if @stat_from . nil? if @stat_thru . nil? @stat_thru = Time . now . localtime . to_date - 1 . day end @stat_from = @stat_thru - 1 . week + 1 . day else ...
Guess for which time range to display statistics
24,149
def write_to ( io ) deduplicate io . write ( @header_entry . to_s ) @entries . each do | entry | io . write ( "\n" ) io . write ( entry . to_s ) end end
Write the contents of this file to the specified IO object .
24,150
def clear if @sticky . empty? then @ckh . clear else @ckh . each { | klass , ch | ch . clear unless @sticky . include? ( klass ) } end end
Clears the non - sticky class caches .
24,151
def find_module ( slug ) modules . find { | m | m . slug . to_s == slug . to_s } end
Tries to find module in this chapter by module slug .
24,152
def answer if request . post? if ipn_notify . acknowledge LolitaPaypal :: Transaction . create_transaction ( ipn_notify , payment_from_ipn , request ) end render nothing : true else if payment_from_ipn redirect_to payment_from_ipn . paypal_return_path else render text : I18n . t ( 'lolita_paypal.wrong_request' ) , stat...
process ipn request POST is sent from paypal and will create transaction GET is a redirect from paypal and will redirect back to return_path
24,153
def set_active_payment @payment ||= session [ :payment_data ] [ :billing_class ] . constantize . find ( session [ :payment_data ] [ :billing_id ] ) rescue render text : I18n . t ( 'lolita_paypal.wrong_request' ) , status : 400 end
returns current payment instance from session
24,154
def headers ( file ) Array . new ( CSV . open ( file , & :readline ) . size ) { | i | i . to_s } end
reads the first line of the CSV file returns the columns indices as an array
24,155
def use_all_templates Utils . available_templates . each do | ext , template | next if engines ( ext ) register_engine ext , template end end
Loops through the available Tilt templates and registers them as processor engines for Sprockets . By default Sprockets cherry picks templates that work for web assets . We need to allow use of Haml Markdown etc .
24,156
def run_callbacks_for ( name , args , reverse ) callbacks_for ( name , reverse ) . map do | block | run_callback ( block , args ) end end
Run specific callbacks .
24,157
def _determine_path path = File . expand_path ( '../..' , __FILE__ ) non_announcer_caller = caller . find { | c | ! c . start_with? ( path ) } unless non_announcer_caller raise Errors :: SubscriptionError , "Could not find non-Announcer caller" end non_announcer_caller end
Determines the file path of the ruby code defining the subscription . It s important that this is called from within the initializer to get the desired effect .
24,158
def _generate_identifier index = _path . rindex ( / \d / ) - 1 path = _path [ 0 .. index ] raise Errors :: SubscriptionError , "Invalid path: #{path}" unless File . exists? ( path ) Digest :: MD5 . hexdigest ( "#{path}:#{event_name}:#{name}" ) . to_sym end
Generates a unique identifier for this subscription which will be used to serialize it .
24,159
def _evaluate_priority_int ( int ) raise Errors :: InvalidPriorityError , int unless int > 0 && int <= config . max_priority int end
Evaluate an integer as a priority .
24,160
def _evaluate_priority_symbol ( sym ) if ( priority = _symbol_to_priority ( sym ) ) _evaluate_priority ( priority ) else raise Errors :: InvalidPriorityError , sym . inspect end end
Evaluate a symbol as a priority .
24,161
def _evaluate_priority_nil priority = config . default_priority if priority _evaluate_priority ( priority ) else raise Errors :: InvalidPriorityError , priority . inspect end end
Evaluate nil as a priority .
24,162
def encrypt_request ( payment_request ) variables = payment_request . request_variables . reverse_merge ( { 'notify_url' => answer_paypal_url ( protocol : 'https' ) } ) LolitaPaypal :: Request . encrypt_for_paypal variables ensure LolitaPaypal . logger . info "[#{payment_request.payment_id}] #{variables}" end
returns encrypted request variables
24,163
def read_config_file c = clone config = YAML . load_file ( File . join ( DEFAULTS [ :source ] , "config.yml" ) ) unless config . is_a? Hash raise ArgumentError . new ( "Configuration file: invalid #{file}" ) end c . merge ( config ) rescue SystemCallError raise LoadError , "Configuration file: not found #{file}" end
load YAML file .
24,164
def path_with_slashes ( path ) path = '/' + path unless path . start_with? ( '/' ) path << '/' unless path . end_with? ( '/' ) path end
Adds leading and trailing slashes if none are present
24,165
def votes ( options = { } ) response = connection . get do | req | req . url "votes" , options end return_error_or_body ( response ) end
Get a list of all votes for the authenticating client .
24,166
def create ( global_options , options ) status , body = client_create ( global_options , options ) if status == 201 save_message ( 'Client' : [ 'created!' ] ) true else save_message ( body ) false end end
Creates a new client on fenton server by sending a post request with json from the command line to create the client
24,167
def create_with_organization ( global_options , options ) create ( global_options , options ) if Organization . new . create ( global_options , name : options [ :username ] , key : options [ :username ] ) save_message ( 'Organization' : [ 'created!' ] ) true else save_message ( 'Organization' : [ 'not created!' ] ) fal...
Calls create new client then creates an organization for that client via a post request with json from the command line
24,168
def client_json ( options ) { client : { username : options [ :username ] , name : options [ :name ] , email : options [ :email ] , public_key : File . read ( options [ :public_key ] ) } } . to_json end
Formulates the client json for the post request
24,169
def perform! ( email , password , & block ) login_required CaTissue :: Database . current . open ( email , password , & block ) end
Runs the given caTissue operation block with the given caTissue credentials .
24,170
def publish ( channel , value ) redis = Attention . redis . call yield redis if block_given? redis . publish channel , payload_for ( value ) end
Publishes the value to the channel
24,171
def payload_for ( value ) case value when Array , Hash JSON . dump value else value end rescue value end
Converts published values to JSON if possible
24,172
def custom_valid? @provider . validations . each do | key , value | return false unless payload [ key ] == value end true end
Check custom validations defined into provider
24,173
def rsa_decode kid = header [ 'kid' ] try = false begin rsa = @provider . keys [ kid ] raise KidNotFound , 'kid not found into provider keys' unless rsa JWT . decode ( @jwt , rsa . public_key , true , algorithm : 'RS256' ) rescue JWT :: VerificationError , KidNotFound raise if try @provider . load_keys try = true retry...
Decodes the JWT with the signed secret
24,174
def run_hook ( hook_name , * args , & block ) hooks . find { | hook | hook . name == hook_name } . run ( self , * args , & block ) end
class level finds a hook by that name and runs it
24,175
def vocab_values type = Schema . find ( self . schema . prefix , stix_version ) . find_type ( name . gsub ( "Vocab" , "Enum" ) ) if type type . enumeration_values else raise "Unable to find corresponding enumeration for vocabulary" end end
Only valid for vocabularies Returns a list of possible values for that vocabulary
24,176
def fetch assert_has_uri! response = client . get clean_uri , query : { start : 0 , size : 10000 } update_attributes! filter_response_body ( JSON . parse ( response . body ) ) self end
Fetch an entity based on its uri . Each entity containing a valid uri will be retrievable through this method
24,177
def to_msgpack ( pk = nil ) case pk when MessagePack :: Packer pk . write_array_header ( 6 ) pk . write @client_id pk . write @local_tick pk . write @global_tick pk . write @delta pk . write @tags pk . write @blob return pk else MessagePack . pack ( self , pk ) end end
Call with Packer nil or IO . If + pk + is nil returns string . If + pk + is a Packer returns the Packer which will need to be flushed . If + pk + is IO returns nil .
24,178
def attributes self . class :: ATTRIBUTES_NAMES . inject ( { } ) do | attribs , attrib_name | value = self . send ( attrib_name ) attribs [ attrib_name ] = value unless value . nil? attribs end end
Return all attributes as a hash
24,179
def odba_cut_connection ( remove_object ) odba_potentials . each { | name | var = instance_variable_get ( name ) if ( var . eql? ( remove_object ) ) instance_variable_set ( name , nil ) end } end
Removes all connections to another persistable . This method is called by the Cache server when _remove_object_ is deleted from the database
24,180
def odba_take_snapshot @odba_snapshot_level ||= 0 snapshot_level = @odba_snapshot_level . next current_level = [ self ] tree_level = 0 while ( ! current_level . empty? ) tree_level += 1 obj_count = 0 next_level = [ ] current_level . each { | item | if ( item . odba_unsaved? ( snapshot_level ) ) obj_count += 1 next_leve...
Recursively stores all connected Persistables .
24,181
def to_hash hash = { } instance_variables . each do | v | hash [ v . to_s [ 1 .. - 1 ] . to_sym ] = instance_variable_get ( v ) end hash end
Creates a new Citation from the given attributes .
24,182
def deprecation_notice ( version , config = { } ) handler = Notifaction :: Type :: Terminal . new handler . warning ( "Deprecated as of #{version}, current #{Notifaction::VERSION}" , config ) handler . quit_soft end
Alert the user that the method they ve called is not supported
24,183
def compose_sql ( * statement ) raise PreparedStatementInvalid , "Statement is blank!" if statement . blank? if statement . is_a? ( Array ) if statement . size == 1 compose_sql_array ( statement . first ) else compose_sql_array ( statement ) end else statement end end
Accepts multiple arguments an array or string of SQL and composes them
24,184
def compose_sql_array ( ary ) statement , * values = ary if values . first . is_a? ( Hash ) and statement =~ / \w / replace_named_bind_variables ( statement , values . first ) elsif statement . include? ( '?' ) replace_bind_variables ( statement , values ) else statement % values . collect { | value | client . escape (...
Accepts an array of conditions . The array has each value sanitized and interpolated into the SQL statement .
24,185
def serialize serialized = { } serialized [ :id ] = id serialized [ :title ] = title serialized [ :meta_language ] = meta_language serialized [ :meta_permalink ] = meta_permalink serialized [ :other_informations ] = serialize_other_informations serialized end
This function serializes a complete version of the tag .
24,186
def delete_dest ( path ) file = Ichiban :: ProjectFile . from_abs ( path ) if file and file . has_dest? dest = file . dest else dest = nil end if dest and File . exist? ( dest ) FileUtils . rm ( dest ) end Ichiban . logger . deletion ( path , dest ) end
Deletes a file s associated destination file if any .
24,187
def delete ( options = { } ) raise Couchbase :: Error :: MissingId , 'missing id attribute' unless @id model . bucket . delete ( @id , options ) @id = nil @meta = nil self end
Delete this object from the bucket
24,188
def reload raise Couchbase :: Error :: MissingId , 'missing id attribute' unless @id pristine = model . find ( @id ) update_attributes ( pristine . attributes ) @meta [ :cas ] = pristine . meta [ :cas ] self end
Reload all the model attributes from the bucket
24,189
def perform uri = URI ( url ) response = Net :: HTTP . start ( uri . hostname , uri . port , :use_ssl => uri . scheme == 'https' ) { | http | Orchestrate . config . logger . debug "Performing #{method.to_s.upcase} request to \"#{url}\"" http . request ( request ( uri ) ) } Response . new ( response ) end
Sets the universal attributes from the params ; any additional attributes are set from the block .
24,190
def aggregate_sum ( aggr ) sum = { } aggr . each do | ts , counterVals | sum [ ts ] = { } unless sum . has_key? ts counterVals . each do | obj , count | if obj . respond_to? ( :enterprise_id ) eid = obj . public_send ( :enterprise_id ) . to_s sum [ ts ] [ eid ] = sum [ ts ] . fetch ( eid , 0 ) + count end end end sum e...
Aggregates to find the sum of all counters for an enterprise at a time
24,191
def add_to_list if in_list? move_to_bottom else list_class . transaction do ids = lock_list! last_position = ids . size if persisted? update_position last_position + 1 else set_position last_position + 1 end end end end
Add the item to the end of the list
24,192
def render_post_fields ( post ) post_fields = post . post_fields . visibles . roots . order ( 'position ASC' ) render 'lato_blog/back/posts/shared/fields' , post_fields : post_fields end
This function render the partial used to render post fields for a specific post .
24,193
def render_post_field ( post_field , key_parent = 'fields' ) key = "#{key_parent}[#{post_field.id}]" case post_field . typology when 'text' render_post_field_text ( post_field , key ) when 'textarea' render_post_field_textarea ( post_field , key ) when 'datetime' render_post_field_datetime ( post_field , key ) when 'ed...
This function render a single post field .
24,194
def get ( url ) begin uri = URI . parse ( url . strip ) rescue URI :: InvalidURIError uri = URI . parse ( URI . escape ( url . strip ) ) end fixture = "#{File.dirname(__FILE__)}/../fixtures#{uri.path}" File . read ( fixture ) if File . exist? ( fixture ) end
Read in fixture file instead of url
24,195
def renumber ( map ) raise "player number #{@num} not found in renumbering hash" unless map [ @num ] self . num = map [ @num ] @results . each { | r | r . renumber ( map ) } self end
Renumber the player according to the supplied hash . Return self .
24,196
def merge ( other ) raise "cannot merge two players that are not equal" unless self == other [ :id , :fide_id , :rating , :fide_rating , :title , :fed , :gender ] . each do | m | self . send ( "#{m}=" , other . send ( m ) ) unless self . send ( m ) end end
Loose equality test . Passes if the names match and the federations are not different . Strict equality test . Passes if the playes are loosly equal and also if their IDs rating gender and title are not different . Merge in some of the details of another player .
24,197
def start! ( port ) Rack :: Handler . get ( WEBRICK ) . run ( self , Port : port ) do | s | @server = s at_exit { stop! } [ :INT , :TERM ] . each do | signal | old = trap ( signal ) do stop! old . call if old . respond_to? ( :call ) end end end end
Starts serving the app .
24,198
def run_executable ( tags , executable , options = { } ) options = { :executable_type => "auto" , :right_script_revision => "latest" , :tag_match_strategy => "all" , :inputs => { } , :update_inputs => [ ] } . merge ( options ) execute_params = { } tags = [ tags ] unless tags . is_a? ( Array ) options [ :update_inputs ]...
Initializes a new RunExecutable
24,199
def right_script_revision_from_lineage ( lineage , revision = "latest" ) right_script = nil if revision == "latest" latest_script = lineage . max_by { | rs | rs . revision } right_script = latest_script else desired_script = lineage . select { | rs | rs . revision == revision } if desired_script . length == 0 raise Exc...
Gets the specified revision of a RightScript from it s lineage