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 , curre...
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 e...
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 , tar...
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 . se...
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_mod...
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 ...
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...
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...
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? ( ...
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 = Be...
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.ro...
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 ...
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 ( " " ) , { :pg...
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...
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 tra...
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 ...
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 ] <...
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_mes...
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 #{q...
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} #{kl...
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...
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_inver...
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 . noti...
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? e...
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 ...
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 ] . ...
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 ...
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...
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 associatio...
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 ( se...
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_h...
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 low...
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 ...
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 .