idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
17,800
def backup_levels ( loggers ) synchronize do loggers . each do | name | outputter = Log4r :: Outputter [ name ] if outputter @original_outputter_levels [ name ] ||= outputter . level else logger = Lumber . find_or_create_logger ( name ) @original_levels [ name ] ||= logger . level end end end end
Backs up original values of logger levels before we overwrite them This is better in local memory since we shouldn t reset loggers that we haven t set
17,801
def restore_levels synchronize do @original_outputter_levels . each do | name , level | outputter = Log4r :: Outputter [ name ] outputter . level = level if outputter . level != level end @original_outputter_levels . clear @original_levels . each do | name , level | logger = Lumber . find_or_create_logger ( name ) logg...
Restores original values of logger levels after expiration
17,802
def method_missing ( method , * args ) if ( i = dimension_method_names . find_index ( method ) ) define_singleton_method ( method ) do dimensions [ i ] end send ( method ) elsif ( i = metric_method_names . find_index ( method ) ) define_singleton_method ( method ) do convert_metric ( i ) end send ( method ) else super ...
Define and call methods to return the value of the dimensions and metrics in the report .
17,803
def convert_metric ( i ) case report . metric_type ( i ) when "INTEGER" metrics [ i ] . to_i when "FLOAT" , "PERCENT" metrics [ i ] . to_f when "CURRENCY" metrics [ i ] . to_f when "TIME" metrics [ i ] . to_f else metric [ i ] end end
Convert metric to the right type .
17,804
def []= ( indexes , value ) indexes = [ indexes ] unless indexes . is_a? ( Range ) indexes . each do | index | process_non_terminals ( index ) if @map . has_key? ( index ) fail MiniTermKME , "Duplicate entry #{index.inspect}" end @map [ index ] = [ value , index ] end end
Set up the keystroke mapper . Add a map entry
17,805
def process_non_terminals ( index ) seq = "" index . chop . chars . each do | char | seq << char if @map . has_key? ( seq ) && @map [ seq ] fail MiniTermKME , "Ambiguous entry #{index.inspect}" end @map [ seq ] = false end end
Handle the preamble characters in the command sequence .
17,806
def wrap ( data ) "<?xml version=\"1.0\" encoding=\"UTF-8\"?><env:Envelope xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\"><env:Body>" . tap do | soap_envelope | unless data . blank? soap_envelope << ( data . is_a? ( Hash ) ? Gyoku . xml ( data ) : data ) end soap_envelope << "</env:Body></env:Envelope>" end en...
Builds an XML document around request data
17,807
def bud ( opts = { } ) opts = { atomic : @atomic , backtracking : @backtracking , bound : @_bound , strip : @strip , case_insensitive : @case_insensitive , multiline : @multiline , not_extended : @not_extended , normalize_whitespace : @normalize_whitespace , symbols : @symbols , name : @name , vet : @vet && opts [ :sym...
returns a new pattern matcher differing from the original only in the options specified
17,808
def pattern ( list , opts = { } ) return '(?!)' unless list . any? return bud ( opts ) . pattern list unless opts . empty? list = list . compact . map ( & :to_s ) . select { | s | s . length > 0 } list . map! ( & :strip ) . select! { | s | s . length > 0 } if strip list . map! { | s | s . gsub %r/ \s / , ' ' } if norma...
converst list into a string representing a regex pattern suitable for inclusion in a larger regex
17,809
def possible_responses ( search_other = false ) { } . tap do | hash | survey_response_answers . each do | sra | sa_row = ( sra . row_survey_answer_id ? SurveyAnswer . find ( sra . row_survey_answer_id ) : nil ) sa_col = ( sra . col_survey_answer_id ? SurveyAnswer . find ( sra . col_survey_answer_id ) : nil ) sa_col_cho...
for reference when searching listing all possible responses is logical but it is impossible to track all survey response answers that match the desired answer . therefore we only track one example and later find all similar response answers based on the question strategy
17,810
def http_post ( url , headers , bodies ) uri = URI . parse ( url ) http = Net :: HTTP . new ( uri . host , uri . port ) http . use_ssl = ( uri . scheme == 'https' ) http . open_timeout = options [ :open_timeout ] http . read_timeout = options [ :read_timeout ] http . verify_mode = OpenSSL :: SSL :: VERIFY_NONE if optio...
Override this method to use your favorite HTTP library . This method receives an array of bodies . It is intended that each element of the array be transmitted as a separate POST request _not_ that the bodies be concatenated and sent as one request .
17,811
def translate ( context , hash ) raise ArgumentError . new ( 'did not pass a hash for the context' ) unless context . is_a? ( Hash ) raise ArgumentError . new ( 'cannot provide include hash in context' ) if context [ :hash ] struct = StructContext . new ( context , hash ) translate = lambda { | t | MapMethods . send ( ...
Generates the set of migrations by parsing the passed in block
17,812
def check_nil_or_empty ( required_param_names = [ ] , params ) required_param_names . each { | p | if params [ p ] . nil? || params [ p ] . empty? raise Hoiio :: RequestError . new "Param " << p << " is missing" end } end
Utility methods Check if any required parameter is missing in params hash
17,813
def check_for_mutual_exclusivity ( required_param_names = [ ] , params ) i = 0 required_param_names . each { | p | if ! params [ p ] . nil? && ! params [ p ] . empty? i += 1 end } if i == 0 raise Hoiio :: RequestError . new "All required params are missing" elsif i > 1 raise Hoiio :: RequestError . new "More than 1 req...
Check that only 1 required parameter is needed for specific API calls
17,814
def render_partial ( file_name ) file_to_render = "#{@input_folder}/partials/#{file_name.to_s}.haml" if @scope scope_file = "#{@input_folder}/partials/#{@scope.to_s}_#{file_name.to_s}.haml" file_to_render = scope_file if File . exists? scope_file end if File . exists? file_to_render partial = Haml :: Engine . new ( Fil...
This function is no different from the copyright_year function above . It just uses some conventions to render another template file when it s called .
17,815
def access_token @access_token ||= ShakeTheCounter :: Authentication . renew_access_token ( client_id : id , client_secret : secret , refresh_token : refresh_token ) [ "access_token" ] end
Retrieves a new authentication token to use for this client or reuse the same one from memory .
17,816
def call ( path , http_method : :get , body : { } , header : { } ) header [ :authorization ] = "Bearer #{access_token}" return ShakeTheCounter :: API . call ( path , http_method : http_method , body : body , header : header ) end
Make an API with access_token
17,817
def start_payment ( reservation_key ) path = "reservation/#{reservation_key}/payment" result = call ( path , http_method : :post ) if result . code . to_i == 200 return true else raise ShakeTheCounterError . new "Payment failed" end end
Send a message to STC that a payment has started .
17,818
def to_hash ( ) ret_hash = { } self . class . json_attributes . each do | attrib | ret_hash [ attrib ] = self . send ( attrib . to_s . underscore ) end return ret_hash end
see attributes_to_pull_from_json for the order if creating yourself
17,819
def ask @fd . print full_message disable_echo if @secret input = _ask return input if valid ( input ) check_counter ask ensure enable_echo if @secret end
Build new prompt object and set defaults
17,820
def valid ( input ) return true unless @validation _ , method = VALIDATIONS . find { | klass , _ | @validation . is_a? klass } return @validation . send ( method , input ) if method raise "Supported validation type not provided #{@validation.class}" end
Validate user input
17,821
def _ask input = STDIN . gets . chomp input = @default if input . empty? && @default @fd . puts if @secret input end
Parse user input
17,822
def check_arguments ( params , * args ) contains = true args . each do | arg | contains = false unless params . key? arg . to_sym end contains end
checks if all args are keys into the hash
17,823
def prepare_json ( params = { } ) json = { } params . each do | key , value | value = prepare_json ( value ) if value . is_a? ( Hash ) json [ camelize ( key ) ] = value end json end
prepares all json payloads before sending to hyper
17,824
def each_tile level size = tile_size level ( 0 ... size ) . each do | y | ( 0 ... size ) . each do | x | yield ( x , y ) if block_given? end end end
Builds the x y pairs and returns these pairs in block
17,825
def each_tile_with_index level idx = 0 size = tile_size level ( 0 ... size ) . each do | y | ( 0 ... size ) . each do | x | yield ( x , y , idx ) if block_given? idx += 1 end end end
Builds the x y index pairs and returns these pairs in block
17,826
def parse ( message ) @result = { } @scanner = StringScanner . new ( message . strip ) begin lines rescue ParserError => pe error_msg = "SimplePoParser::ParserError" error_msg += pe . message error_msg += "\nParseing result before error: '#{@result}'" error_msg += "\nSimplePoParser filtered backtrace: SimplePoParser::P...
parse a single message of the PO format .
17,827
def msgctxt begin if @scanner . scan ( / / ) skip_whitespace text = message_line add_result ( :msgctxt , text ) message_multiline ( :msgctxt ) if text . empty? end msgid rescue PoSyntaxError => pe raise PoSyntaxError , "Syntax error in msgctxt\n" + pe . message , pe . backtrace end end
matches the msgctxt line and will continue to check for msgid afterwards
17,828
def msgid begin if @scanner . scan ( / / ) skip_whitespace text = message_line add_result ( :msgid , text ) message_multiline ( :msgid ) if text . empty? if msgid_plural msgstr_plural else msgstr end else err_msg = "Message without msgid is not allowed." err_msg += "The Line started unexpectedly with #{@scanner.peek(10...
matches the msgid line . Will check for optional msgid_plural . Will advance to msgstr or msgstr_plural based on msgid_plural
17,829
def msgid_plural begin if @scanner . scan ( / / ) skip_whitespace text = message_line add_result ( :msgid_plural , text ) message_multiline ( :msgid_plural ) if text . empty? true else false end rescue PoSyntaxError => pe raise PoSyntaxError , "Syntax error in msgid\n" + pe . message , pe . backtrace end end
matches the msgid_plural line .
17,830
def msgstr begin if @scanner . scan ( / / ) skip_whitespace text = message_line add_result ( :msgstr , text ) message_multiline ( :msgstr ) if text . empty? skip_whitespace raise PoSyntaxError , "Unexpected content after expected message end #{@scanner.peek(10).inspect}" unless @scanner . eos? else raise PoSyntaxError ...
parses the msgstr singular line
17,831
def msgstr_plural ( num = 0 ) begin msgstr_key = @scanner . scan ( / \[ \d \] / ) if msgstr_key msgstr_num = msgstr_key . match ( / \d / ) [ 0 ] . to_i raise PoSyntaxError , "Bad 'msgstr[index]' index." if msgstr_num != num skip_whitespace text = message_line add_result ( msgstr_key , text ) message_multiline ( msgstr_...
parses the msgstr plural lines
17,832
def previous_comments begin if @scanner . scan ( / / ) if @scanner . scan ( / / ) if @scanner . scan ( / / ) key = :previous_msgid_plural else key = :previous_msgid end elsif @scanner . scan ( / / ) key = :previous_msgctxt else raise PoSyntaxError , "Previous comment type #{("msg" + @scanner.peek(10)).inspect} unknown....
parses previous comments which provide additional information on fuzzy matching
17,833
def previous_multiline ( key ) begin if @scanner . scan ( / \| \p / ) @scanner . pos = @scanner . pos - 1 add_result ( key , message_line ) previous_multiline ( key ) end rescue PoSyntaxError => pe raise PoSyntaxError , "Syntax error in previous_multiline\n" + pe . message , pe . backtrace end end
parses the multiline messages of the previous comment lines
17,834
def message_multiline ( key ) begin skip_whitespace if @scanner . check ( / / ) add_result ( key , message_line ) message_multiline ( key ) end rescue PoSyntaxError => pe raise PoSyntaxError , "Syntax error in message_multiline with key '#{key}'\n" + pe . message , pe . backtrace end end
parses a multiline message
17,835
def message_line begin if @scanner . getch == '"' text = message_text unless @scanner . getch == '"' err_msg = "The message text '#{text}' must be finished with the double quote character '\"'." raise PoSyntaxError , err_msg end skip_whitespace unless end_of_line err_msg = "There should be only whitespace until the end...
identifies a message line and returns it s text or raises an error
17,836
def add_result ( key , text ) if @result [ key ] if @result [ key ] . is_a? Array @result [ key ] . push ( text ) else @result [ key ] = [ @result [ key ] , text ] end else @result [ key ] = text end end
adds text to the given key in results creates an array if the given key already has a result
17,837
def resolve_tag_repo_ref! ( tag ) return unless tag . has_repo? repo = core . repo_manager . find_repository ( tag . repo ) if tag . has_ref? === false if repo . has_package_versions? tag . set_ref repo . latest_package_version else tag . set_ref repo . current_ref end else unless repo . has_ref? ( tag . ref ) new_ref ...
Resolve tag s ref
17,838
def register_features ( with_features ) Thread . new do features = [ ] features = with_features . each do | feature | features . push ( key : feature [ :key ] , variants : feature [ :variants ] , failoverVariant : feature [ :failover_variant ] ) end send_event 'Register Features' , :put , '/api/sdk/v1/register' , featu...
register features are not queued and go straight out
17,839
def each return enum_for ( :each ) unless block_given? pointer = self loop do break if pointer . null? yield pointer pointer = pointer . next end end
Exposes the linked list structure in an Enumerable - compatible format
17,840
def comment_line ( comment ) if comment . match ( ProbeDockProbe :: Annotation :: ANNOTATION_REGEXP ) if @current_feature_started @annotation = ProbeDockProbe :: Annotation . new ( comment ) else @feature_annotation = ProbeDockProbe :: Annotation . new ( comment ) end end end
Called for each comment line
17,841
def is? ( type ) return false if type . to_s . empty? expected_types = Array . wrap ( type ) . map ( & :to_s ) content_type && expected_types . select do | t | content_type . select { | ct | ct . start_with? ( t ) } end . any? end
Initialise a UrlInfo for a particular URL
17,842
def esr9_format_account_id ( account_id ) ( pre , main , post ) = account_id . split ( '-' ) sprintf ( '%02i%06i%1i' , pre . to_i , main . to_i , post . to_i ) end
Formats an account number for ESR
17,843
def config if @config . nil? if defined? Rails configure ( Rails . root . join ( 'config' , 'ldap_groups_lookup.yml' ) . to_s ) else configure ( File . join ( __dir__ , '..' , '..' , 'config' , 'ldap_groups_lookup.yml' ) . to_s ) end end @config end
Loads LDAP host and authentication configuration
17,844
def clear invalid_keys = all_keys . select { | key | key . include? ( @scope . table_name . downcase ) } invalid_keys . each { | key | Rails . cache . delete ( key ) } Rails . cache . write ( list_key , all_keys - invalid_keys ) end
Clear out any count caches which have SQL that includes the scopes table
17,845
def analyze ( target_user ) user = read_user ( target_user ) articles = read_articles ( target_user ) calc_power_levels ( user , articles ) end
Generate QiitaScouter markdown file .
17,846
def simulator_information re = / \( \. \. \) \[ \] /m @simulators . select { | simulator_data | simulator_data . include? ( 'iPhone' ) && ! simulator_data . include? ( 'Apple Watch' ) } . map { | simulator_data | simulator_data . match ( re ) . to_s . tr ( '()[]' , '' ) . split } [ 0 , ENV [ 'THREADS' ] . to_i ] end
Filter simulator data
17,847
def measure ( labels = { } ) start_time = Time . now unless block_given? raise NoBlockError , "No block passed to #{self.class}#measure" end @requests . increment ( labels , 1 ) @mutex . synchronize { @current . set ( labels , ( @current . get ( labels ) || 0 ) + 1 ) } res_labels = labels . dup begin yield ( res_labels...
Create a new request instrumentation package .
17,848
def values begin @collector . call ( self ) . tap do | results | unless results . is_a? ( Hash ) @logger . error ( progname ) { "Collector proc did not return a hash, got #{results.inspect}" } @errors_metric . increment ( class : "NotAHashError" ) return { } end results . keys . each { | labelset | @validator . validat...
Retrieve a complete set of labels and values for the metric .
17,849
def validate_type ( type ) unless %i{ gauge counter histogram summary } . include? ( type ) raise ArgumentError , "type must be one of :gauge, :counter, :histogram, or :summary (got #{type.inspect})" end end
Make sure that the type we were passed is one Prometheus is known to accept .
17,850
def search_chatter_feeds ( object_type , query_string , binding , limit = 100 ) return get_all_chatter_feeds_with_attachments ( nil , object_type , binding , 'no-attachment-for-search' , limit , false , query_string ) end
find all chatter feeds based on object_type query_string and given binding
17,851
def with ( * features ) pos , neg = mangle_args ( * features ) self . class . new ( Hash [ @sets . select do | key , val | ! key . intersection ( pos ) . empty? end ] ) . without_any ( neg ) end
Return an instance of Sounds whose sets include any of the given features .
17,852
def with_all ( * features ) pos , neg = mangle_args ( * features ) self . class . new ( Hash [ @sets . select do | key , val | pos . subset? ( key ) end ] ) . without_any ( neg ) end
Return feature sets that include all of the given features
17,853
def without ( * features ) features = setify ( * features ) self . class . new Hash [ @sets . select { | key , val | ! features . subset? ( key ) } ] end
Return an instance of Sounds whose sets exclude any of the given features .
17,854
def without_any ( * features ) features = setify ( * features ) self . class . new Hash [ @sets . select { | key , val | key . intersection ( features ) . empty? } ] end
Return an instance of Sounds whose sets exclude all of the given features .
17,855
def check_resource_params ( options = { } ) resource_name = options [ :name ] || controller_name . singularize resource_class = options [ :class ] || "Hicube::#{resource_name.singularize.camelize}" . classify . constantize unless params . key? ( resource_name ) notify :error , :: I18n . t ( 'messages.resource.missing_p...
Check resource params are present based on the current controller name .
17,856
def order_params desc = ! desc? p = grid . params . dup if ordered? p [ :desc ] = desc else p = p . merge order : name , desc : desc end grid . scoped_params p end
if current params contain order for this column then revert direction else add order_params for this column to current params
17,857
def characteristics return @characteristics if @characteristics hsh = Hash . new do | _ , key | if characterization = subject . class . characterization [ key ] Curation . new nil , characterization end end hsh . extend LooseEquality @characteristics = hsh end
Create a Curator .
17,858
def []= ( key , value ) characteristics [ key ] = Curation . new value , subject . class . characterization [ key ] end
Store a late - defined characteristic with a Charisma wrapper .
17,859
def detailed_units ( all_levels = false ) mag = @magnitude prev_units = self . units units = { } loop do compound = false prev_units . each_pair do | dim , ( unit , mul ) | ud = Units . unit ( unit ) if ud . decomposition compound = true mag *= ud . decomposition . magnitude ud . decomposition . units . each_pair do | ...
decompose compound units
17,860
def insert ( text ) raise "must be passed string" unless text . is_a? ( String ) snippet = Snippet . new_text ( core , text ) snippet . snippet_tags . each do | tag_info | visit tag_info [ :tag ] end context = Context . new ( nil ) insert_func ( snippet , context ) . join ( $/ ) end
Insert snippets to given text
17,861
def insert_by_tag_and_context! ( inserter , snippet , context , tag ) raise "must be passed snippet" unless snippet . is_a? ( Snippet ) src = insert_func ( snippet , context , tag ) options [ :margin_top ] . times { inserter . insert "" } inserter . insert tag . to_snippet_tag unless snippet . no_tag? inserter . insert...
Insert snippet by tag and context
17,862
def insert_depended_snippets! ( inserter , snippet , context , tag ) raise "must be passed snippet" unless snippet . is_a? ( Snippet ) dep_tags = deps_resolver . find ( snippet , context , tag ) dep_tags = sort_dep_tags_by_dep ( dep_tags ) dep_tags . each do | tag_info | sub_t = tag_info [ :tag ] sub_c = tag_info [ :co...
Insert depended snippet
17,863
def sort_dep_tags_by_dep ( dep_tags ) dep_tags_index = { } dep_tags . each . with_index do | tag_info , k | tag = tag_info [ :tag ] dep_tags_index [ tag . to_path ] = k end dep_tags_hash = TSortableHash . new dep_tags . each do | tag_info | tag = tag_info [ :tag ] . to_path dep_ind = dep_tags_index [ tag ] dep_tags_has...
Sort by dependency
17,864
def create ( label ) create_atomic ( label . to_s ) or create_composite ( label . to_s ) or raise MeasurementError . new ( "Unit '#{label}' not found" ) end
Returns the unit with the given label . Creates a new unit if necessary .
17,865
def slice_atomic_unit ( str ) label = '' str . scan ( / / ) do | chunk | label << chunk unit = create_atomic ( label ) return label , unit if unit end raise MeasurementError . new ( "Unit '#{str}' not found" ) end
Returns the Unit which matches the str prefix .
17,866
def match_scalar ( label ) label = label . to_sym Factor . detect do | factor | return factor if factor . label == label or factor . abbreviation == label end end
Returns the Factor which matches the label or nil if no match .
17,867
def suffix? ( suffix , text ) len = suffix . length len <= text . length and suffix == text [ - len , len ] end
Returns whether text ends in suffix .
17,868
def write new = get new [ @note ] = @token File . open ( @file , 'w' , 0o0600 ) { | fh | fh . write new . to_yaml } end
Create new Config object either ephemerally or from a file
17,869
def fetch ( resource , params = { } ) method = :get page = 1 params [ :page ] = page partial = request ( resource , method , params ) while partial . is_a? ( Array ) && ! partial . empty? results ||= [ ] results += partial page += 1 params [ :page ] = page partial = request ( resource , method , params ) end results = ...
fetch all pages of results
17,870
def fetch_by_id ( model , id , filters = { } ) get_resource ( "/v1/public/#{model}/#{id}" , filters ) if model_exists? ( model ) && validate_filters ( filters ) end
fetch a record by id
17,871
def processing_hint_str number , level total = ( @ts . tile_size ( level ) ** 2 ) . to_s now = ( number + 1 ) . to_s . rjust ( total . length , " " ) "#{now}/#{total}" end
Format a beautiful hint string
17,872
def patch ( campaign_id , opts = { } ) campaign = get ( campaign_id : campaign_id ) . first opts = NO_CHANGE_VALUES . merge ( affiliate_id : campaign . fetch ( :affiliate ) . fetch ( :affiliate_id ) , media_type_id : campaign . fetch ( :media_type ) . fetch ( :media_type_id ) , offer_contract_id : campaign . fetch ( :o...
The default for display_link_type_id is Fallback in Cake which doesn t have an ID and hence cannot be set via the API . In order to not change it it has to be absent from the request .
17,873
def call ( step_name ) vars = nil step = steps . find { | s | vars = s [ :pattern ] . match ( step_name ) } raise "Undefined step '#{ step_name }'" unless step if vars . length > 1 step [ :block ] . call ( * vars [ 1 .. - 1 ] ) else step [ :block ] . call end end
The step_name variable below is a string that may or may not match the regex pattern of one of the hashes in the steps array .
17,874
def equivalent? ( other_uri ) other = Gitable :: URI . parse_when_valid ( other_uri ) return false unless other return false unless normalized_host . to_s == other . normalized_host . to_s if github? || bitbucket? org_project == other . org_project else normalized_path . sub ( / \/ / , '' ) == other . normalized_path ....
Detect if two URIs are equivalent versions of the same uri .
17,875
def counters! the_counters = { processing : 0 } names = @lifecycle . states . keys results = RedisRds :: Object . connection . multi do self . class :: STATES_TERMINAL . each { | name | get_list ( name ) . size } names . each { | name | get_list ( name ) . size } @processing . getall end ( self . class :: STATES_TERMIN...
fetches counters atomically
17,876
def link_to_previous_page ( scope , name , options = { } , & block ) prev_page = Kaminari :: Helpers :: PrevPage . new self , options . reverse_merge ( :current_page => scope . current_page ) link_to_if scope . prev_page . present? , name , prev_page . url , options . except ( :params , :param_name ) . reverse_merge ( ...
A simple Twitter like pagination link that creates a link to the previous page .
17,877
def link_to_next_page ( scope , name , options = { } , & block ) next_page = Kaminari :: Helpers :: NextPage . new self , options . reverse_merge ( :current_page => scope . current_page ) link_to_if scope . next_page . present? , name , next_page . url , options . except ( :params , :param_name ) . reverse_merge ( :rel...
A simple Twitter like pagination link that creates a link to the next page .
17,878
def rel_next_prev_link_tags ( scope , options = { } ) next_page = Kaminari :: Helpers :: NextPage . new self , options . reverse_merge ( :current_page => scope . current_page ) prev_page = Kaminari :: Helpers :: PrevPage . new self , options . reverse_merge ( :current_page => scope . current_page ) output = String . ne...
Renders rel = next and rel = prev links to be used in the head .
17,879
def ratio ( rgb1 , rgb2 ) raise InvalidColorError , rgb1 unless valid_rgb? ( rgb1 ) raise InvalidColorError , rgb2 unless valid_rgb? ( rgb2 ) srgb1 = rgb_to_srgba ( rgb1 ) srgb2 = rgb_to_srgba ( rgb2 ) l1 = srgb_lightness ( srgb1 ) l2 = srgb_lightness ( srgb2 ) l1 > l2 ? ( l1 + 0.05 ) / ( l2 + 0.05 ) : ( l2 + 0.05 ) / ...
Calculate contast ratio beetween RGB1 and RGB2 .
17,880
def relative_luminance ( rgb ) raise InvalidColorError , rgb unless valid_rgb? ( rgb ) srgb = rgb_to_srgba ( rgb ) srgb_lightness ( srgb ) end
Calculate the relative luminance for an rgb color
17,881
def rgb_to_srgba ( rgb ) rgb << rgb if rgb . size == 3 [ rgb . slice ( 0 , 2 ) . to_i ( 16 ) / 255.0 , rgb . slice ( 2 , 2 ) . to_i ( 16 ) / 255.0 , rgb . slice ( 4 , 2 ) . to_i ( 16 ) / 255.0 ] end
Convert RGB color to sRGB .
17,882
def srgb_lightness ( srgb ) r , g , b = srgb 0.2126 * ( r <= 0.03928 ? r / 12.92 : ( ( r + 0.055 ) / 1.055 ) ** 2.4 ) + 0.7152 * ( g <= 0.03928 ? g / 12.92 : ( ( g + 0.055 ) / 1.055 ) ** 2.4 ) + 0.0722 * ( b <= 0.03928 ? b / 12.92 : ( ( b + 0.055 ) / 1.055 ) ** 2.4 ) end
Calculate lightness for sRGB color .
17,883
def run @op_mutex . synchronize do return AlreadyRunningError if @server @server_thread = Thread . new do @op_mutex . synchronize do begin wrapped_logger = Frankenstein :: Server :: WEBrickLogger . new ( logger : @logger , progname : "Frankenstein::Server" ) @server = WEBrick :: HTTPServer . new ( Logger : wrapped_logg...
Create a new server instance .
17,884
def assign_message_type_values ( values ) values . each do | key , value | public_send ( key , value ) if respond_to? ( key ) end end
Assign the given hash where each key is a message type and the value is a hash of options for that message type .
17,885
def run ( connection ) connection . public_send ( verb , path ) do | request | request . params = params request . headers [ :content_type ] = Command :: JSON_CONTENT_TYPE request . body = MultiJson . dump ( body ) end end
Run request on connection
17,886
def validate errors = { } call_validators do | name , message | errors [ name ] ||= [ ] errors [ name ] << to_error ( message ) end errors end
Validates all properties based on configured validators .
17,887
def load_capabilities ( caps ) device = @server . device_data unless device . nil? caps [ :caps ] [ :udid ] = device . fetch ( 'udid' , nil ) caps [ :caps ] [ :platformVersion ] = device . fetch ( 'os' , caps [ :caps ] [ :platformVersion ] ) caps [ :caps ] [ :deviceName ] = device . fetch ( 'name' , caps [ :caps ] [ :d...
Load capabilities based on current device data
17,888
def initialize_appium ( ** args ) platform = args [ :platform ] caps = args [ :caps ] platform = ENV [ 'platform' ] if platform . nil? if platform . nil? puts 'Platform not found in environment variable' exit end caps = Appium . load_appium_txt file : File . new ( "#{Dir.pwd}/appium-#{platform}.txt" ) if caps . nil? if...
Load appium text file if available and attempt to start the driver platform is either android or ios otherwise read from ENV caps is mapping of appium capabilities
17,889
def setup_signal_handler ( ios_pid = nil , android_pid = nil ) Signal . trap ( 'INT' ) do Process . kill ( 'INT' , ios_pid ) unless ios_pid . nil? Process . kill ( 'INT' , android_pid ) unless android_pid . nil? kill_process 'appium' kill_process 'selenium' exit 1 end end
Define a signal handler for SIGINT
17,890
def execute_specs ( platform , threads , spec_path , parallel = false ) command = if parallel "platform=#{platform} parallel_rspec -n #{threads} #{spec_path}" else "platform=#{platform} rspec #{spec_path} --tag #{platform}" end puts "Executing #{command}" exec command end
Decide whether to execute specs in parallel or not
17,891
def setup ( platform , file_path , threads , parallel ) spec_path = 'spec/' spec_path = file_path . to_s unless file_path . nil? puts "SPEC PATH:#{spec_path}" unless %w[ ios android ] . include? platform puts "Invalid platform #{platform}" exit end execute_specs platform , threads , spec_path , parallel end
Define Spec path validate platform and execute specs
17,892
def start ( ** args ) platform = args [ :platform ] file_path = args [ :file_path ] if ENV [ 'platform' ] . nil? if platform . nil? puts 'No platform detected in environment and none passed to start...' exit end ENV [ 'platform' ] = platform end sleep 3 ios_port = 4725 android_port = 4727 default_port = 4725 platform =...
Fire necessary appium server instances and Selenium grid server if needed .
17,893
def execute uri = URI . parse ( "https://analyticsreporting.googleapis.com/v4/reports:batchGet" ) https = Net :: HTTP . new ( uri . host , uri . port ) https . use_ssl = true request = Net :: HTTP :: Post . new ( uri . request_uri , "Content-Type" => "application/json" , "Authorization" => "Bearer #{access_token}" ) re...
Create a Query object .
17,894
def stringify_keys ( object ) case object when Hash object . each_with_object ( { } ) do | ( key , value ) , result | result [ key . to_s ] = stringify_keys ( value ) end when Array object . map { | e | stringify_keys ( e ) } else object end end
The keys have to be strings to get converted to a GA query . Adapted from Rails .
17,895
def raise_status_error message = format ( 'expected response stati: %s but got: %s, remote message: %s' , expected_response_stati , response . status , remote_message . inspect ) fail ProtocolError , message end
Raise remote status error
17,896
def sections return @sections if @sections @sections = [ ] path = "event/#{event.key}/performance/#{key}/sections/#{event.client.language_code}" result = event . client . call ( path , http_method : :get ) for section in result @sections << ShakeTheCounter :: Section . new ( section , performance : self ) end return @s...
Sets up a new event
17,897
def method_missing ( method , * args , & block ) raise ArgumentError . new ( "wrong number of arguments (#{args.size} for 1)" ) if args . size != 1 raise NoMethodError . new ( "Undefined translation method #{method}" ) unless MapMethods . respond_to? ( method ) @maps << { name : method , field : args [ 0 ] , block : bl...
Figures out which translations are done for each version .
17,898
def mention_users mentions ||= begin regex = / \w / self . body . scan ( regex ) . flatten end mentioned_users ||= User . where ( username : mentions ) if mentioned_users . any? mentioned_users . each do | i | FiatNotifications :: Notification :: CreateNotificationJob . set ( wait : 5 . seconds ) . perform_later ( self...
Ideally this would be polymorphic - enabled
17,899
def assign_attributes ( new_attributes ) if ! new_attributes . respond_to? ( :stringify_keys ) raise ArgumentError , "When assigning attributes, you must pass a hash as an argument." end return if new_attributes . nil? || new_attributes . empty? attributes = new_attributes . stringify_keys _assign_attributes ( attribut...
Allows you to set all the attributes by passing in a hash of attributes with keys matching the attribute names .