idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
21,700
def expand_definition ( definition ) return definition if definition . is_a? Hash definition . each_with_object ( { } ) do | key , result | if key . is_a? String result [ key ] = :default elsif key . is_a? Hash result . merge! ( expand_sub_definitions ( key ) ) end end end
expands simple arrays into full hash definitions
21,701
def expand_sub_definitions ( sub_definitions ) sub_definitions . each_with_object ( { } ) do | ( subkey , value ) , result | result [ subkey ] = value next if value . respond_to? :call result [ subkey ] [ :attributes ] = expand_definition ( value [ :attributes ] ) end end
expands nested simple definition into a full hash
21,702
def check_definition ( definition , current_expected , current_key = nil ) definition . each do | error_key , match_def | if match_def . is_a? Hash key = [ current_key , error_key ] . compact . join ( '.' ) check_each ( key , match_def , current_expected ) else check_values ( current_key , error_key , match_def , current_expected ) end end end
Walks through the match definition collecting errors for each field
21,703
def check_each ( error_key , each_definition , current_expected ) enumerable = each_definition [ :each ] . call ( current_expected ) enumerable . each_with_index do | each_instance , idx | full_key = [ error_key , idx ] . join ( '.' ) check_definition ( each_definition [ :attributes ] , each_instance , full_key ) end end
Iterates through a list of objects while checking fields
21,704
def check_values ( key_prefix , error_key , match_function , expected_instance = expected ) expected_value = ExpectedValue . new ( match_function , expected_instance , error_key , @prefix ) target_value = TargetValue . new ( [ key_prefix , error_key ] . compact . join ( '.' ) , target ) add_error ( expected_value , target_value ) unless expected_value == target_value end
Checks fields on a single instance
21,705
def add_banking_days ( days ) day = self if days > 0 days . times { day = day . next_banking_day } elsif days < 0 ( - days ) . times { day = day . previous_banking_day } end day end
Adds the given number of banking days i . e . bank holidays don t count . If days is negative subtracts the given number of banking days . If days is zero returns self .
21,706
def similarity ( string_a , string_b ) string_a , string_b = prep_strings ( string_a , string_b ) return 100.0 if string_a == string_b score = 0 total_weight = algorithms . values . inject { | sum , weight | sum + weight } algorithms . each do | algorithm , weight | next unless weight . positive? score += string_a . send ( "#{algorithm}_similarity" , string_b ) * weight end score / total_weight end
Calculates a percentage match between string a and string b .
21,707
def best_match ( string_a , * string_b ) similarities ( string_a , * string_b ) . max_by { | _k , v | v } [ 0 ] end
Returns the best match from array b to string a based on percent .
21,708
def similarities ( string_a , * string_b ) [ * string_b ] . map { | word | [ word , matches [ word ] = similarity ( string_a , word ) ] } end
Returns a hash of array b with the percentage match to a . If sort is true the hash is sorted desc by match percent .
21,709
def st_only_cols dict ( dict . keys . to_set - @only_cols ) . each { | col | dict . delete ( col ) } dict end
Filter out everything except these columns
21,710
def st_require_cols dict dcols = dict . keys . to_set unless @require_cols . subset? dict . keys . to_set missing_cols = ( @require_cols - dcols ) . to_a raise ReindeerETL :: Errors :: RecordInvalid . new ( "Missing required columns: #{missing_cols}" ) end end
require these columns
21,711
def from_array ( messages , save_cache = false ) clear unless save_cache messages . each do | msg | add msg [ 0 ] , msg [ 1 ] end end
Patched cause we dont need no attribute name magic .. and its just simpler orig version is looking up the humanized name of the attribute in the error message which we dont supply = > only field name is used in returned error msg
21,712
def parse_modes ( modes ) mode_changes = [ ] modes . scan ( / \w / ) . each do | modegroup | set , modegroup = modegroup . split '' , 2 set = set == '+' ? true : false modegroup . split ( '' ) . each do | mode | mode_changes << { set : set , mode : mode } end end return mode_changes end
Parse mode changes .
21,713
def parse_channel_modes ( modes , opts = { } ) chanmodes = opts [ :chanmodes ] || { 'A' => %w{ b e I } . to_set , 'B' => %w{ k } . to_set , 'C' => %w{ l } . to_set , 'D' => %w{ i m n p s t a q r } . to_set , } statmodes = opts [ :statmodes ] || %w{ o h v } . to_set mode_changes = [ ] modelist , * args = modes parse_modes ( modelist ) . each do | mode_change | set , mode = mode_change [ :set ] , mode_change [ :mode ] case when chanmodes [ "A" ] . include? ( mode ) || chanmodes [ "B" ] . include? ( mode ) mode_changes << { mode : mode , set : set , argument : args . shift } when chanmodes [ "C" ] . include? ( mode ) mode_changes << { mode : mode , set : set , argument : args . shift . to_i } when chanmodes [ "D" ] . include? ( mode ) mode_changes << { mode : mode , set : set , } else raise ArgumentError , "Unknown mode: #{mode}" end end return mode_changes end
Parse channel mode changes .
21,714
def condense_modes ( modes ) action = nil result = '' modes . split ( / / ) . each do | mode | if mode =~ / / and ( ! action or mode != action ) result += mode action = mode next end result += mode if mode =~ / / end result . sub! ( / \z / , '' ) return result end
Condense mode string by removing duplicates .
21,715
def diff_modes ( before , after ) before_modes = before . split ( / / ) after_modes = after . split ( / / ) removed = before_modes - after_modes added = after_modes - before_modes result = removed . map { | m | '-' + m } . join result << added . map { | m | '+' + m } . join return condense_modes ( result ) end
Calculate the difference between two mode strings .
21,716
def infer_collection_type_from_name pname = @property_descriptor . name cname = pname . capitalize_first . sub ( / / , '' ) jname = [ @declarer . parent_module , cname ] . join ( '::' ) klass = eval jname rescue nil if klass then logger . debug { "Inferred #{declarer.qp} #{self} collection domain type #{klass.qp} from the property name." } end klass end
Returns the domain type for this property s collection Java property descriptor name . By convention Jinx domain collection propertys often begin with a domain type name and end in Collection . This method strips the Collection suffix and checks whether the prefix is a domain class .
21,717
def define_plugin_types ( namespace , type_info ) if type_info . is_a? ( Hash ) type_info . each do | plugin_type , default_provider | define_plugin_type ( namespace , plugin_type , default_provider ) end end self end
Define one or more new plugin types in a specified namespace .
21,718
def loaded_plugin ( namespace , plugin_type , provider ) get ( [ :load_info , namespace , sanitize_id ( plugin_type ) , sanitize_id ( provider ) ] , nil ) end
Return the load information for a specified plugin provider if it exists
21,719
def loaded_plugins ( namespace = nil , plugin_type = nil , provider = nil , default = { } ) load_info = get_hash ( :load_info ) namespace = namespace . to_sym if namespace plugin_type = sanitize_id ( plugin_type ) if plugin_type provider = sanitize_id ( provider ) if provider results = default if namespace && load_info . has_key? ( namespace ) if plugin_type && load_info [ namespace ] . has_key? ( plugin_type ) if provider && load_info [ namespace ] [ plugin_type ] . has_key? ( provider ) results = load_info [ namespace ] [ plugin_type ] [ provider ] elsif ! provider results = load_info [ namespace ] [ plugin_type ] end elsif ! plugin_type results = load_info [ namespace ] end elsif ! namespace results = load_info end results end
Return the load information for namespaces plugin types providers if it exists
21,720
def plugin_has_provider? ( namespace , plugin_type , provider ) get_hash ( [ :load_info , namespace , sanitize_id ( plugin_type ) ] ) . has_key? ( sanitize_id ( provider ) ) end
Check if a specified plugin provider has been loaded
21,721
def get_plugin ( namespace , plugin_type , plugin_name ) namespace = namespace . to_sym plugin_type = sanitize_id ( plugin_type ) instances = get_hash ( [ :active_info , namespace , plugin_type ] ) instance_ids = array ( @instance_map . get ( [ namespace , plugin_type , plugin_name . to_s . to_sym ] ) ) if instance_ids . size return instances [ instance_ids [ 0 ] ] end nil end
Return a plugin instance by name if it exists
21,722
def remove_plugin ( namespace , plugin_type , instance_name , & code ) plugin = delete ( [ :active_info , namespace , sanitize_id ( plugin_type ) , instance_name ] ) code . call ( plugin ) if code && plugin plugin end
Remove a plugin instance from the environment
21,723
def active_plugins ( namespace = nil , plugin_type = nil , provider = nil ) active_info = get_hash ( :active_info ) namespace = namespace . to_sym if namespace plugin_type = sanitize_id ( plugin_type ) if plugin_type provider = sanitize_id ( provider ) if provider results = { } if namespace && active_info . has_key? ( namespace ) if plugin_type && active_info [ namespace ] . has_key? ( plugin_type ) if provider && ! active_info [ namespace ] [ plugin_type ] . keys . empty? active_info [ namespace ] [ plugin_type ] . each do | instance_name , plugin | plugin = active_info [ namespace ] [ plugin_type ] [ instance_name ] results [ instance_name ] = plugin if plugin . plugin_provider == provider end elsif ! provider results = active_info [ namespace ] [ plugin_type ] end elsif ! plugin_type results = active_info [ namespace ] end elsif ! namespace results = active_info end results end
Return active plugins for namespaces plugin types providers if specified
21,724
def class_const ( name , separator = '::' ) components = class_name ( name , separator , TRUE ) constant = Object components . each do | component | constant = constant . const_defined? ( component ) ? constant . const_get ( component ) : constant . const_missing ( component ) end constant end
Return a fully formed class name as a machine usable constant
21,725
def sanitize_class ( class_component ) class_component . to_s . split ( '_' ) . collect { | elem | elem . slice ( 0 , 1 ) . capitalize + elem . slice ( 1 .. - 1 ) } . join ( '' ) end
Sanitize a class identifier for internal use .
21,726
def provider_class ( namespace , plugin_type , provider ) class_const ( [ sanitize_class ( namespace ) , sanitize_class ( plugin_type ) , provider ] ) end
Return a class constant representing a plugin provider class generated from namespace plugin_type and provider name .
21,727
def create_new_role ( project_root , role_name ) return error _ ( 'wizard.role.invalid_name' ) % { words : Bebox :: RESERVED_WORDS . join ( ', ' ) } unless valid_puppet_class_name? ( role_name ) return error ( _ ( 'wizard.role.name_exist' ) % { role : role_name } ) if role_exists? ( project_root , role_name ) role = Bebox :: Role . new ( role_name , project_root ) output = role . create ok _ ( 'wizard.role.creation_success' ) return output end
Create a new role
21,728
def remove_role ( project_root ) roles = Bebox :: Role . list ( project_root ) if roles . count > 0 role_name = choose_option ( roles , _ ( 'wizard.role.choose_deletion_role' ) ) else return error _ ( 'wizard.role.no_deletion_roles' ) end return warn ( _ ( 'wizard.no_changes' ) ) unless confirm_action? ( _ ( 'wizard.role.confirm_deletion' ) ) role = Bebox :: Role . new ( role_name , project_root ) output = role . remove ok _ ( 'wizard.role.deletion_success' ) return output end
Removes an existing role
21,729
def add_profile ( project_root ) roles = Bebox :: Role . list ( project_root ) profiles = Bebox :: Profile . list ( project_root ) role = choose_option ( roles , _ ( 'wizard.choose_role' ) ) profile = choose_option ( profiles , _ ( 'wizard.role.choose_add_profile' ) ) if Bebox :: Role . profile_in_role? ( project_root , role , profile ) warn _ ( 'wizard.role.profile_exist' ) % { profile : profile , role : role } output = false else output = Bebox :: Role . add_profile ( project_root , role , profile ) ok _ ( 'wizard.role.add_profile_success' ) % { profile : profile , role : role } end return output end
Add a profile to a role
21,730
def connect_to_process! Bullring . logger . debug { "#{caller_name}: Connecting to process..." } if ! process_port_active? Bullring . logger . debug { "#{caller_name}: Spawning process..." } pid = Process . spawn ( [ @options [ :process ] [ :command ] , @options [ :process ] [ :args ] ] . flatten . join ( " " ) , { :pgroup => true } ) Process . detach ( pid ) time_sleeping = 0 while ( ! process_port_active? ) sleep ( 0.2 ) if ( time_sleeping += 0.2 ) > @options [ :process ] [ :max_bringup_time ] Bullring . logger . error { "#{caller_name}: Timed out waiting to bring up the process" } raise StandardError , "#{caller_name}: Timed out waiting to bring up the process" , caller end end end if ! @local_service . nil? @local_service . stop_service Bullring . logger . debug { "#{caller_name}: Stopped local service on #{@local_service.uri}" } end @local_service = DRb . start_service "druby://127.0.0.1:0" Bullring . logger . debug { "#{caller_name}: Started local service on #{@local_service.uri}" } @process = DRbObject . new nil , "druby://#{host}:#{port}" @after_connect_block . call ( @process ) if ! @after_connect_block . nil? end
Creates a druby connection to the process starting it up if necessary
21,731
def recaptcha_mailhide ( * args , & block ) options = args . extract_options! raise ArgumentError , "at least one argument is required (not counting options)" if args . empty? if block_given? url = RecaptchaMailhide . url_for ( args . first ) link_to ( url , recaptcha_mailhide_options ( url , options ) , & block ) else if args . length == 1 content = truncate_email ( args . first , options ) url = RecaptchaMailhide . url_for ( args . first ) else content = args . first url = RecaptchaMailhide . url_for ( args . second ) end link_to ( content , url , recaptcha_mailhide_options ( url , options ) ) end end
Generates a link tag to a ReCAPTCHA Mailhide URL for the given email address .
21,732
def projects ( options = { } ) response = connection . get do | req | req . url "/api/v1/projects" , options end response . body end
Retrieve information for all projects .
21,733
def def_elements ( root_elem_var_name , element_definitions = { } ) element_definitions . each do | name , definition | define_method ( name ) do | other_selectors = { } | definition [ 1 ] . merge! ( other_selectors ) instance_variable_get ( root_elem_var_name . to_sym ) . send ( * definition ) end end end
Provides convenient method for concisely defining element getters
21,734
def price_scale ( definition , order ) return definition [ 'scale' ] [ price_paid ] [ 0 ] * order . price , definition [ 'scale' ] [ price_paid ] [ 1 ] * order . price end
Calculates the prices according to the scale definition .
21,735
def price_set ( definition , order ) if order . price != definition [ 'set' ] [ price_paid ] log_order ( order ) log_error 'order matched but price differs; ignoring this order.' p order p definition return 0 , 0 else return definition [ 'set' ] [ 'half' ] , definition [ 'set' ] [ 'full' ] end end
Calculates the prices according to the set definition .
21,736
def price_choices ( definition , order ) definition [ 'choices' ] . each { | name , prices | return prices [ 'half' ] , prices [ 'full' ] if prices [ price_paid ] == order . price } return price_guess_get ( order ) if @force_guess_fallback choose do | menu | menu . prompt = "\nSelect the choice that applies to your travels? " log_info "\n" definition [ 'choices' ] . each do | name , prices | menu . choice "#{name} (half-fare: #{currency(prices['half'])}, full: #{currency(prices['full'])})" do end end menu . choice "…or enter manually" d a k_for_price(o r der) e d end end
Calculates the prices according to the choices definition .
21,737
def ask_for_price ( order ) guesshalf , guessfull = price_guess_get ( order ) if ! Halffare . debug log_order ( order ) end if @halffare other = ask ( "What would have been the full price? " , Float ) { | q | q . default = guessfull } return order . price , other else other = ask ( "What would have been the half-fare price? " , Float ) { | q | q . default = guesshalf } return other , order . price end end
Ask the user for the price .
21,738
def bounding_box unless @bbox p = @points [ 0 ] minX = p [ 0 ] maxX = p [ 0 ] minY = p [ 1 ] maxY = p [ 1 ] minZ = p [ 2 ] maxZ = p [ 2 ] @points . each { | p | minX = p [ 0 ] if p [ 0 ] < minX maxX = p [ 0 ] if p [ 0 ] > maxX minY = p [ 1 ] if p [ 1 ] < minY maxY = p [ 1 ] if p [ 1 ] > maxY minZ = p [ 2 ] if p [ 2 ] < minZ maxZ = p [ 2 ] if p [ 2 ] > maxZ } @max = Vector [ maxX , maxY , maxZ ] @min = Vector [ minX , minY , minZ ] @bbox = Volume . new ( [ Plane . new ( - 1 , 0 , 0 , minX , minY , minZ ) , Plane . new ( 0 , - 1 , 0 , minX , minY , minZ ) , Plane . new ( 0 , 0 , - 1 , minX , minY , minZ ) , Plane . new ( 1 , 0 , 0 , maxX , maxY , maxZ ) , Plane . new ( 0 , 1 , 0 , maxX , maxY , maxZ ) , Plane . new ( 0 , 0 , 1 , maxX , maxY , maxZ ) ] ) end @bbox end
Return the bounding box for this volume
21,739
def contains_point ( x , y , z ) behind = true @planes . each { | p | behind = ( 0 >= p . distance_to_point ( x , y , z ) ) break if not behind } return behind end
A volume contains a point if it lies behind all the planes
21,740
def provider ( position ) content_providers . find_by ( position : position ) || ContentProviders :: Null . new ( self , position ) end
Returns the ContentProvider at the given position or a Null ContentProvider if none exists .
21,741
def create_or_update_job ( job , opts = { } ) data , _status_code , _headers = create_or_update_job_with_http_info ( job , opts ) return data end
Creates or Updates a single job
21,742
def get_job ( id_or_uri , opts = { } ) data , _status_code , _headers = get_job_with_http_info ( id_or_uri , opts ) return data end
Returns a single job
21,743
def server ( * names , & block ) names . each do | name | server = @tool . provide_server ( name ) scope = Scope . new ( self , server ) if not block . nil? then Docile . dsl_eval ( scope , & block ) end end end
Action statt plan
21,744
def confirm_action? ( message ) require 'highline/import' quest message response = ask ( highline_quest ( '(y/n)' ) ) do | q | q . default = "n" end return response == 'y' ? true : false end
Ask for confirmation of any action
21,745
def write_input ( message , default = nil , validator = nil , not_valid_message = nil ) require 'highline/import' response = ask ( highline_quest ( message ) ) do | q | q . default = default if default q . validate = / \. / if validator q . responses [ :not_valid ] = highline_warn ( not_valid_message ) if not_valid_message end return response end
Ask to write some input with validation
21,746
def choose_option ( options , question ) require 'highline/import' choose do | menu | menu . header = title ( question ) options . each do | option | menu . choice ( option ) end end end
Asks to choose an option
21,747
def valid_puppet_class_name? ( name ) valid_name = ( name =~ / \A \Z / ) . nil? ? false : true valid_name && ! Bebox :: RESERVED_WORDS . include? ( name ) end
Check if the puppet resource has a valid name
21,748
def loop_for ( name , seconds , options = { } , & blk ) end_at = Time . now + seconds if options [ :warmup ] options [ :warmup ] . times do | i | yield i end end i = 0 while Time . now < end_at time_i ( i , name , options , & blk ) i += 1 end end
will loop for number of seconds
21,749
def relative ( x , y ) if x . respond_to? ( :to_i ) && y . respond_to? ( :to_i ) [ @x . min + x . to_i , @y . min + y . to_i ] else x , y = rangeize ( x , y ) [ ( @x . min + x . min ) .. ( @x . min + x . max ) , ( @y . min + y . min ) .. ( @y . min + y . max ) ] end end
Converts coordinates to coordinates relative to inside the map .
21,750
def rangeize ( x , y ) [ x , y ] . collect { | i | i . respond_to? ( :to_i ) ? ( i . to_i .. i . to_i ) : i } end
Converts given coordinates to ranges if necessary .
21,751
def set_attribute_inverse ( attribute , inverse ) prop = property ( attribute ) pa = prop . attribute return if prop . inverse == inverse inverse ||= prop . type . detect_inverse_attribute ( self ) unless prop . declarer == self then prop = restrict_attribute_inverse ( prop , inverse ) end logger . debug { "Setting #{qp}.#{pa} inverse to #{inverse}..." } inv_prop = prop . type . property ( inverse ) if prop . collection? and not inv_prop . collection? then return prop . type . set_attribute_inverse ( inverse , pa ) end unless self <= inv_prop . type then raise TypeError . new ( "Cannot set #{qp}.#{pa} inverse to #{prop.type.qp}.#{pa} with incompatible type #{inv_prop.type.qp}" ) end prop . inverse = inverse unless prop . collection? then add_inverse_updater ( pa ) unless prop . type == inv_prop . type or inv_prop . collection? then prop . type . delegate_writer_to_inverse ( inverse , pa ) end end logger . debug { "Set #{qp}.#{pa} inverse to #{inverse}." } end
Sets the given bi - directional association attribute s inverse .
21,752
def clear_inverse ( property ) ip = property . inverse_property || return if property . collection? then return ip . declarer . clear_inverse ( ip ) unless ip . collection? else alias_property_accessors ( property ) end property . inverse = nil end
Clears the property inverse if there is one .
21,753
def detect_inverse_attribute ( klass ) candidates = domain_attributes . compose { | prop | klass <= prop . type and prop . inverse . nil? } pa = detect_inverse_attribute_from_candidates ( klass , candidates ) if pa then logger . debug { "#{qp} #{klass.qp} inverse attribute is #{pa}." } else logger . debug { "#{qp} #{klass.qp} inverse attribute was not detected." } end pa end
Detects an unambiguous attribute which refers to the given referencing class . If there is exactly one attribute with the given return type then that attribute is chosen . Otherwise the attribute whose name matches the underscored referencing class name is chosen if any .
21,754
def delegate_writer_to_inverse ( attribute , inverse ) prop = property ( attribute ) inv_prop = prop . inverse_property || return logger . debug { "Delegating #{qp}.#{attribute} update to the inverse #{prop.type.qp}.#{inv_prop}..." } redefine_method ( prop . writer ) do | old_writer | lambda { | dep | set_inverse ( dep , old_writer , inv_prop . writer ) } end end
Redefines the attribute writer method to delegate to its inverse writer . This is done to enforce inverse integrity .
21,755
def restrict_attribute_inverse ( prop , inverse ) logger . debug { "Restricting #{prop.declarer.qp}.#{prop} to #{qp} with inverse #{inverse}..." } rst_prop = prop . restrict ( self , :inverse => inverse ) logger . debug { "Restricted #{prop.declarer.qp}.#{prop} to #{qp} with inverse #{inverse}." } rst_prop end
Copies the given attribute metadata from its declarer to this class . The new attribute metadata has the same attribute access methods but the declarer is this class and the inverse is the given inverse attribute .
21,756
def add_inverse_updater ( attribute ) prop = property ( attribute ) rdr , wtr = prop . accessors inv_prop = prop . inverse_property inv_rdr , inv_wtr = inv_accessors = inv_prop . accessors redefine_method ( wtr ) do | old_wtr | accessors = [ rdr , old_wtr ] if inv_prop . collection? then lambda { | other | add_to_inverse_collection ( other , accessors , inv_rdr ) } else lambda { | other | set_inversible_noncollection_attribute ( other , accessors , inv_wtr ) } end end logger . debug { "Injected inverse #{inv_prop} updater into #{qp}.#{attribute} writer method #{wtr}." } end
Modifies the given attribute writer method to update the given inverse .
21,757
def login url = 'https://www.epicmix.com/vailresorts/sites/epicmix/api/mobile/authenticate.ashx' options = { :query => { :loginID => username , :password => password } } response = HTTParty . post ( url , options ) token_from ( response ) end
Initializes and logs in to Epicmix Login to epic mix
21,758
def season_stats url = 'https://www.epicmix.com/vailresorts/sites/epicmix/api/mobile/userstats.ashx' options = { :timetype => 'season' , :token => token } response = HTTParty . get ( url , :query => options , :headers => headers ) JSON . parse ( response . body ) [ 'seasonStats' ] end
Gets all your season stats
21,759
def min_length? ( value , length ) has_min_length = coerce_bool ( value . length >= length ) unless has_min_length @error = "Error, expected value to have at least #{length} characters, got: #{value.length}" end has_min_length end
Returns + true + if the value has at least the specified length
21,760
def max_length? ( value , length ) has_max_length = coerce_bool ( value . length <= length ) unless has_max_length @error = "Error, expected value to have at most #{length} characters, got: #{value.length}" end has_max_length end
Returns + true + if the value has at most the specified length
21,761
def exact_length? ( value , length ) has_exact_length = coerce_bool ( value . length == length ) unless has_exact_length @error = "Error, expected value to have exactly #{length} characters, got: #{value.length}" end has_exact_length end
Returns + true + if the value has exactly the specified length
21,762
def create email = params [ :beta_invite ] [ :email ] beta_invite = BetaInvite . new ( email : email , token : SecureRandom . hex ( 10 ) ) if beta_invite . save flash [ :success ] = "#{email} has been registered for beta invite" if BetaInviteSetup . send_email_to_admins BetaInvite :: BetaInviteNotificationMailer . notify_admins ( BetaInviteSetup . from_email , BetaInviteSetup . admin_emails , email , BetaInvite . count ) . deliver end if BetaInviteSetup . send_thank_you_email BetaInvite :: BetaInviteNotificationMailer . thank_user ( BetaInviteSetup . from_email , email ) . deliver end redirect_to beta_invites_path else flash [ :alert ] = beta_invite . errors . full_messages redirect_to new_beta_invite_path end end
Save the email and a randomly generated token
21,763
def stop if ( @runner . nil? && @stop ) raise NotRunning . new elsif ( @runner . nil? || ! @runner . alive? ) @stop = true @runner = nil else @stop = true if ( @runner ) @runner . raise Resync . new if @runner . alive? && @runner . stop? @runner . join ( 0.05 ) if @runner @runner . kill if @runner && @runner . alive? end @runner = nil end nil end
stop the watcher
21,764
def watch until ( @stop ) begin resultset = Kernel . select ( @sockets . keys , nil , nil , nil ) for sock in resultset [ 0 ] string = sock . gets if ( sock . closed? || string . nil? ) if ( @sockets [ sock ] [ :closed ] ) @sockets [ sock ] [ :closed ] . each do | pr | pr [ 1 ] . call ( * ( [ sock ] + pr [ 0 ] ) ) end end @sockets . delete ( sock ) else string = clean? ? do_clean ( string ) : string process ( string . dup , sock ) end end rescue Resync end end @runner = nil end
Watch the sockets and send strings for processing
21,765
def command_in_path? ( command ) found = ENV [ 'PATH' ] . split ( File :: PATH_SEPARATOR ) . map do | p | File . exist? ( File . join ( p , command ) ) end found . include? ( true ) end
Checks in PATH returns true if the command is found .
21,766
def pretty_inspect io = StringIO . new formatter = Formatter . new ( io ) pretty_dump ( formatter ) io . rewind io . read end
Return pretty inspection
21,767
def method_missing ( method_name , * args , & block ) if self . has_key? ( method_name . to_s ) self . [] ( method_name , & block ) elsif self . body . respond_to? ( method_name ) self . body . send ( method_name , * args , & block ) elsif self . request [ :api ] . respond_to? ( method_name ) self . request [ :api ] . send ( method_name , * args , & block ) else super end end
Coerce any method calls for body attributes
21,768
def update ( side , flds = nil ) raise ArgumentError , 'The side to update must be :l or :r' unless [ :l , :r ] . include? ( side ) target , source = ( side == :l ) ? [ :l , :r ] : [ :r , :l ] flds ||= fields target_obj = self . send ( "#{target}_obj" ) source_obj = self . send ( "#{source}_obj" ) flds . each do | fld | target_name = fld . send ( "#{target}_name" ) source_name = fld . send ( "#{source}_name" ) old_val = target_obj . send ( target_name ) rescue 'empty' new_val = if fld . transition? cur_trans = fld . send ( "#{target}_trans" ) eval "#{cur_trans} source_obj.send( source_name )" else source_obj . send ( source_name ) end target_obj . send ( "#{target_name}=" , new_val ) log << "#{target_name} was: #{old_val} updated from: #{source_name} with value: #{new_val}" end end
Update a side with the values from the other side . Populates the log with updated fields and values .
21,769
def ignorable? @ignorable ||= path . each_filename do | path_component | project . config . ignore_patterns . each do | pattern | return true if File . fnmatch ( pattern , path_component ) end end end
Consider whether this input can be ignored .
21,770
def render ( context , locals = { } , & block ) return file . read if ! template? ensure_loaded pipeline . inject ( @template_text ) do | text , processor | template = processor . new ( file . to_s , @template_start_line ) { text } template . render ( context , locals , & block ) end end
Render this input using Tilt
21,771
def load @load_time = Time . now @meta = { } if template? logger . debug "loading #{path}" file . open do | io | read_meta ( io ) @template_start_line = io . lineno + 1 @template_text = io . read end end end
Read input file extracting YAML meta - data header and template content .
21,772
def process_hash_row ( hsh ) if @headers . any? keys_or_values = hsh . values @row_id = hsh [ :row_id ] else keys_or_values = hsh . keys . map ( & :to_s ) end file_line = keys_or_values . join ( ',' ) validated_line = utf_filter ( check_utf ( file_line ) ) res = line_parse ( validated_line ) res end
process_hash_row - helper VALIDATE HASHES Converts hash keys and vals into parsed line .
21,773
def line_parse ( validated_line ) return unless validated_line row = validated_line . split ( ',' ) return unless row . any? if @headers . empty? @headers = row else @data_hash . merge! ( row_to_hsh ( row ) ) @valid_rows << @data_hash end end
line_parse - helper VALIDATE HASHES Parses line to row then updates final results .
21,774
def wait_for_prompt ( silence_timeout = nil , command_timeout = nil , timeout_error = true ) raise Shells :: NotRunning unless running? silence_timeout ||= options [ :silence_timeout ] command_timeout ||= options [ :command_timeout ] nudged_at = nil nudge_count = 0 silence_timeout = silence_timeout . to_s . to_f unless silence_timeout . is_a? ( Numeric ) nudge_seconds = if silence_timeout > 0 ( silence_timeout / 3.0 ) else 0 end command_timeout = command_timeout . to_s . to_f unless command_timeout . is_a? ( Numeric ) timeout = if command_timeout > 0 Time . now + command_timeout else nil end until output =~ prompt_match && ! wait_for_output Thread . pass last_response = last_output if nudge_seconds > 0 && ( Time . now - last_response ) > nudge_seconds nudge_count = ( nudged_at . nil? || nudged_at < last_response ) ? 1 : ( nudge_count + 1 ) if nudge_count > 2 raise Shells :: SilenceTimeout if timeout_error debug ' > silence timeout' return false else nudged_at = Time . now queue_input line_ending self . last_output = nudged_at end end if timeout && Time . now > timeout raise Shells :: CommandTimeout if timeout_error debug ' > command timeout' return false end end pos = ( output =~ prompt_match ) if output [ pos - 1 ] != "\n" self . output = output [ 0 ... pos ] + "\n" + output [ pos .. - 1 ] end if stdout [ - 1 ] != "\n" self . stdout += "\n" end true end
Waits for the prompt to appear at the end of the output .
21,775
def temporary_prompt ( prompt ) raise Shells :: NotRunning unless running? old_prompt = prompt_match begin self . prompt_match = prompt yield if block_given? ensure self . prompt_match = old_prompt end end
Sets the prompt to the value temporarily for execution of the code block .
21,776
def next_migration_string ( padding = 3 ) @s = ( ! @s . nil? ) ? @s . to_i + 1 : if ActiveRecord :: Base . timestamped_migrations Time . now . utc . strftime ( "%Y%m%d%H%M%S" ) else "%.#{padding}d" % next_migration_number end end
the loop through migrations happens so fast that they all have the same timestamp which won t work when you actually try to migrate . All the timestamps MUST be unique .
21,777
def interpret_color ( color ) if color . is_a? String color = color [ - 2 .. - 1 ] << color [ 2 .. 3 ] << color [ 0 .. 1 ] color = color . to_i ( 16 ) end color end
Converts the input to an RGB color represented by an integer
21,778
def listen begin clear_view @router . route unless Input . quit? reset if Input . reset? end until Input . quit? end
Runs the application loop . Clears the system view each iteration . Calls route on the router instance .
21,779
def format_message ( severity , datetime , progname , msg ) if String === msg then msg . inject ( '' ) { | s , line | s << super ( severity , datetime , progname , line . chomp ) } else super end end
Writes msg to the log device . Each line in msg is formatted separately .
21,780
def each_pair ( type , default = nil ) real_hash . each_key ( ) { | key | value = fetch ( key , type , default ) if ( ! value . nil? ) yield ( key , value ) end } end
Enumerates the key value pairs in the has .
21,781
def each_match ( regex , type , default = nil ) real_hash . each_key ( ) { | key | if ( matchinfo = regex . match ( key ) ) value = fetch ( key , type , default ) if ( ! value . nil? ) yield ( matchinfo , value ) end end } end
Enumerates keys that match a regex passing the match object and the value .
21,782
def attributes_hash attributes = @scope . attributes . collect do | attr | value = fetch_property ( attr ) if value . kind_of? ( BigDecimal ) value = value . to_f end [ attr , value ] end Hash [ attributes ] end
Collects attributes for serialization . Attributes can be overwritten in the serializer .
21,783
def associations_hash hash = { } @scope . associations . each do | association , options | hash . merge! ( render_association ( association , options ) ) end hash end
Collects associations for serialization . Associations can be overwritten in the serializer .
21,784
def render_association ( association_data , options = { } ) hash = { } if association_data . is_a? ( Hash ) association_data . each do | association , association_options | data = render_association ( association , options . merge ( :include => association_options ) ) hash . merge! ( data ) if data end elsif association_data . is_a? ( Array ) association_data . each do | option | data = render_association ( option ) hash . merge! ( data ) if data end else if options [ :preload ] includes = options [ :preload ] == true ? options [ :include ] : options [ :preload ] end if ( object = fetch_association ( association_data , includes ) ) data = ScopedSerializer . for ( object , options . merge ( :associations => options [ :include ] ) ) . as_json hash . merge! ( data ) if data end end hash end
Renders a specific association .
21,785
def fetch_property ( property ) return nil unless property unless respond_to? ( property ) object = @resource . send ( property ) else object = send ( property ) end end
Fetches property from the serializer or resource . This method makes it possible to overwrite defined attributes or associations .
21,786
def fetch_association ( name , includes = nil ) association = fetch_property ( name ) if includes . present? && ! @resource . association ( name ) . loaded? association . includes ( includes ) else association end end
Fetches association and eager loads data . Doesn t eager load when includes is empty or when the association has already been loaded .
21,787
def execute ( * components ) execute_transforms if components . empty? || components . include? ( :transforms ) execute_sub_jobs if components . empty? || components . include? ( :sub_jobs ) execute_load_targets if components . empty? || components . include? ( :load_targets ) self end
Execute the specified components of the job .
21,788
def load ( username ) options = { } options [ :basic_auth ] = @auth response = self . class . get ( "/user/#{username}" , options ) if response . success? self . response = response parse_response self else raise response . response end end
Returns a updated user object username = key of user
21,789
def add_dependent_property ( property , * flags ) logger . debug { "Marking #{qp}.#{property} as a dependent attribute of type #{property.type.qp}..." } flags << :dependent unless flags . include? ( :dependent ) property . qualify ( * flags ) inv = property . inverse inv_type = property . type inv_type . add_owner ( self , property . attribute , inv ) if inv then logger . debug "Marked #{qp}.#{property} as a dependent attribute with inverse #{inv_type.qp}.#{inv}." else logger . debug "Marked #{qp}.#{property} as a uni-directional dependent attribute." end end
Adds the given property as a dependent .
21,790
def add_owner ( klass , inverse , attribute = nil ) if inverse . nil? then raise ValidationError . new ( "Owner #{klass.qp} missing dependent attribute for dependent #{qp}" ) end logger . debug { "Adding #{qp} owner #{klass.qp}#{' attribute ' + attribute.to_s if attribute} with inverse #{inverse}..." } if @owner_prop_hash then raise MetadataError . new ( "Can't add #{qp} owner #{klass.qp} after dependencies have been accessed" ) end attribute ||= detect_owner_attribute ( klass , inverse ) hash = local_owner_property_hash if hash [ klass ] then raise MetadataError . new ( "Cannot set #{qp} owner attribute to #{attribute or 'nil'} since it is already set to #{hash[klass]}" ) end prop = property ( attribute ) if attribute hash [ klass ] = prop if attribute . nil? then logger . debug { "#{qp} owner #{klass.qp} has unidirectional dependent attribute #{inverse}." } return end local_owner_properties << prop unless prop . inverse then set_attribute_inverse ( attribute , inverse ) end prop . qualify ( :owner ) unless prop . owner? rdr , wtr = prop . accessors redefine_method ( wtr ) do | old_wtr | lambda do | ref | prev = send ( rdr ) send ( old_wtr , ref ) if prev and prev != ref then if ref . nil? then logger . warn ( "Unset the #{self} owner #{attribute} #{prev}." ) elsif ref . key != prev . key then logger . warn ( "Reset the #{self} owner #{attribute} from #{prev} to #{ref}." ) end end ref end end logger . debug { "Injected owner change warning into #{qp}.#{attribute} writer method #{wtr}." } logger . debug { "#{qp} owner #{klass.qp} attribute is #{attribute} with inverse #{inverse}." } end
Adds the given owner class to this dependent class . This method must be called before any dependent attribute is accessed . If the attribute is given then the attribute inverse is set . Otherwise if there is not already an owner attribute then a new owner attribute is created . The name of the new attribute is the lower - case demodulized owner class name .
21,791
def add_owner_attribute ( attribute ) prop = property ( attribute ) otype = prop . type hash = local_owner_property_hash if hash . include? ( otype ) then oa = hash [ otype ] unless oa . nil? then raise MetadataError . new ( "Cannot set #{qp} owner attribute to #{attribute} since it is already set to #{oa}" ) end hash [ otype ] = prop else add_owner ( otype , prop . inverse , attribute ) end end
Adds the given attribute as an owner . This method is called when a new attribute is added that references an existing owner .
21,792
def method_instance lazy_var :@method_instance do logger . catch . warn ( "Failed to get method" , instance : instance , method_name : method_name , ) do instance . method method_name end end end
Construct a new AbstractMethodError .
21,793
def get_user_and_check ( user ) user_full = @octokit . user ( user ) { username : user_full [ :login ] , avatar : user_full [ :avatar_url ] } rescue Octokit :: NotFound return false end
Gets the Octokit and colors for the program .
21,794
def get_forks_stars_watchers ( repository ) { forks : @octokit . forks ( repository ) . length , stars : @octokit . stargazers ( repository ) . length , watchers : @octokit . subscribers ( repository ) . length } end
Gets the number of forkers stargazers and watchers .
21,795
def get_followers_following ( username ) { following : @octokit . following ( username ) . length , followers : @octokit . followers ( username ) . length } end
Gets the number of followers and users followed by the user .
21,796
def get_user_langs ( username ) repos = get_user_repos ( username ) langs = { } repos [ :public ] . each do | r | next if repos [ :forks ] . include? r repo_langs = @octokit . languages ( r ) repo_langs . each do | l , b | if langs [ l ] . nil? langs [ l ] = b else langs [ l ] += b end end end langs end
Gets the langauges and their bytes for the user .
21,797
def get_org_langs ( username ) org_repos = get_org_repos ( username ) langs = { } org_repos [ :public ] . each do | r | next if org_repos [ :forks ] . include? r repo_langs = @octokit . languages ( r ) repo_langs . each do | l , b | if langs [ l ] . nil? langs [ l ] = b else langs [ l ] += b end end end langs end
Gets the languages and their bytes for the user s organizations .
21,798
def get_color_for_language ( lang ) color_lang = @colors [ lang ] color = color_lang [ 'color' ] if color_lang . nil? || color . nil? return StringUtility . random_color_six else return color end end
Gets the defined color for the language .
21,799
def get_language_percentages ( langs ) total = 0 langs . each { | _ , b | total += b } lang_percents = { } langs . each do | l , b | percent = self . class . calculate_percent ( b , total . to_f ) lang_percents [ l ] = percent . round ( 2 ) end lang_percents end
Gets the percentages for each language in a hash .