idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
24,400
def get_lb_hostname_input lb_hostname_input = "text:" fe_servers . each do | fe | timeout = 30 loopcounter = 0 begin if fe . settings [ 'private-dns-name' ] == nil raise "FATAL: private DNS name is empty" if loopcounter > 10 sleep ( timeout ) loopcounter += 1 next end lb_hostname_input << fe . settings [ 'private-dns-name' ] + " " done = true end while ! done end lb_hostname_input end
returns String with all the private dns of the Front End servers used for setting the LB_HOSTNAME input .
24,401
def config_for ( environment = :development ) if self . config . present? env_config = self . config [ environment . to_s ] else env_config = { 'host' => ENV [ 'RIAK_HOST' ] , 'http_port' => ENV [ 'RIAK_HTTP_PORT' ] , 'pb_port' => ENV [ 'RIAK_PB_PORT' ] } end env_config end
Return a configuration hash for a given environment
24,402
def parse_response ( object ) LOG . debug ( "response is #{object}" ) case object when :: Net :: HTTPUnauthorized :: File . delete ( ACCESS_TOKEN ) raise 'user revoked oauth connection' when :: Net :: HTTPOK then object . body end end
parse an response
24,403
def addressable apply_schema :street_address_1 , String apply_schema :street_address_2 , String apply_schema :city , String apply_schema :state , String apply_schema :zip_code , String apply_schema :country , String end
Provides a common set of address fields such as street_address_1 street_address_2 city state zip_code and country as String fields .
24,404
def merge_into_snapshot ( other ) if @snapshot . nil? then raise ValidationError . new ( "Cannot merge #{other.qp} content into #{qp} snapshot, since #{qp} does not have a snapshot." ) end delta = diff ( other ) dvh = delta . transform_value { | d | d . last } return if dvh . empty? logger . debug { "#{qp} differs from database content #{other.qp} as follows: #{delta.filter_on_key { |pa| dvh.has_key?(pa) }.qp}" } logger . debug { "Setting #{qp} snapshot values from other #{other.qp} values to reflect the database state: #{dvh.qp}..." } @snapshot . merge! ( dvh ) end
Merges the other domain object non - domain attribute values into this domain object s snapshot An existing snapshot value is replaced by the corresponding other attribute value .
24,405
def add_lazy_loader ( loader , attributes = nil ) if identifier . nil? then raise ValidationError . new ( "Cannot add lazy loader to an unfetched domain object: #{self}" ) end attributes ||= loadable_attributes return if attributes . empty? pas = attributes . select { | pa | inject_lazy_loader ( pa ) } logger . debug { "Lazy loader added to #{qp} attributes #{pas.to_series}." } unless pas . empty? end
Lazy loads the attributes . If a block is given to this method then the attributes are determined by calling the block with this Persistable as a parameter . Otherwise the default attributes are the unfetched domain attributes .
24,406
def remove_lazy_loader ( attribute = nil ) if attribute . nil? then return self . class . domain_attributes . each { | pa | remove_lazy_loader ( pa ) } end reader , writer = self . class . property ( attribute ) . accessors disable_singleton_method ( reader ) disable_singleton_method ( writer ) end
Disables lazy loading of the specified attribute . Lazy loaded is disabled for all attributes if no attribute is specified . This method is a no - op if this Persistable does not have a lazy loader .
24,407
def fetch_saved? return false if identifier ag_attrs = self . class . autogenerated_attributes return false if ag_attrs . empty? ag_attrs . any? { | pa | not send ( pa ) . nil_or_empty? } end
Returns whether this domain object must be fetched to reflect the database state . This default implementation returns whether this domain object was created and there are any autogenerated attributes . Subclasses can override to relax or restrict the condition .
24,408
def inject_lazy_loader ( attribute ) return false if attribute_loaded? ( attribute ) reader , writer = self . class . property ( attribute ) . accessors instance_eval "def #{reader}; load_reference(:#{attribute}); end" instance_eval "def #{writer}(value); remove_lazy_loader(:#{attribute}); super; end" true end
Adds this Persistable lazy loader to the given attribute unless the attribute already holds a fetched reference .
24,409
def load_reference ( attribute ) ldr = database . lazy_loader return transient_value ( attribute ) unless ldr . enabled? remove_lazy_loader ( attribute ) merged = ldr . load ( self , attribute ) pa = self . class . property ( attribute ) if pa . dependent? then oattr = pa . inverse if oattr then merged . enumerate do | dep | if dep . fetched? then dep . snapshot [ oattr ] = self logger . debug { "Updated the #{qp} fetched #{attribute} dependent #{dep.qp} snapshot with #{oattr} value #{qp}." } end end end end merged end
Loads the reference attribute database value into this Persistable .
24,410
def disable_singleton_method ( name_or_sym ) return unless singleton_methods . include? ( name_or_sym . to_s ) method = self . method ( name_or_sym . to_sym ) method . unbind if singleton_methods . include? ( name_or_sym . to_s ) then args = ( 1 .. method . arity ) . map { | argnum | "arg#{argnum}" } . join ( ', ' ) instance_eval "def #{name_or_sym}(#{args}); super; end" end end
Disables the given singleton attribute accessor method .
24,411
def sass ( sassfile , mediatype = "all" ) render_style Sass :: Engine . new ( open_file ( find_file ( sassfile , SASS ) ) ) . render , mediatype end
renders sass files
24,412
def scss ( scssfile , mediatype = "all" ) render_style Sass :: Engine . new ( open_file ( find_file ( scssfile , SCSS ) ) , :syntax => :scss ) . render , mediatype end
renders scss files
24,413
def call program_information configure_global_option directory_global_option command ( :initialize ) { | c | InitializeCommand . define ( self , c ) } command ( :bench ) { | c | BenchCommand . define ( self , c ) } command ( :build ) { | c | BuildCommand . define ( self , c ) } command ( :serve ) { | c | ServeCommand . define ( self , c ) } alias_command ( :init , :initialize ) default_command ( :build ) run! end
Defines and runs the command line interface .
24,414
def program_information program :name , "Brandish" program :version , Brandish :: VERSION program :help_formatter , :compact program :help_paging , false program :description , "A multi-format document generator." program :help , "Author" , "Jeremy Rodi <jeremy.rodi@medcat.me>" program :help , "License" , "MIT License Copyright (c) 2017 Jeremy Rodi" end
The program information . This is for use with Commander .
24,415
def progress ( array , & block ) width = $terminal . terminal_size [ 0 ] - PROGRESS_WIDTH options = PROGRESS_OPTIONS . merge ( width : width ) super ( array , options , & block ) end
Creates a progress bar on the terminal based off of the given array . This mostly passes everything on to the progress method provided by Commander but with a few options added .
24,416
def fill @matrix [ 0 ] [ 0 ] = 0 1 . upto ( @rows - 1 ) { | i | @matrix [ i ] [ 0 ] = @matrix [ i - 1 ] [ 0 ] + @scoring . score_delete ( @seq1 [ i ] ) } 1 . upto ( @cols - 1 ) { | j | @matrix [ 0 ] [ j ] = @matrix [ 0 ] [ j - 1 ] + @scoring . score_insert ( @seq2 [ j ] ) } 1 . upto ( @rows - 1 ) do | i | prv_row = @matrix [ i - 1 ] cur_row = @matrix [ i ] 1 . upto ( @cols - 1 ) do | j | seq1_obj = @seq1 [ i - 1 ] seq2_obj = @seq2 [ j - 1 ] score_align = prv_row [ j - 1 ] + @scoring . score_align ( seq1_obj , seq2_obj ) score_delete = prv_row [ j ] + @scoring . score_delete ( seq1_obj ) score_insert = cur_row [ j - 1 ] + @scoring . score_insert ( seq2_obj ) max = max3 ( score_align , score_delete , score_insert ) @matrix [ i ] [ j ] = max end end end
Fills the matrix with the alignment map .
24,417
def traceback i = @rows - 1 j = @cols - 1 while ( i > 0 && j > 0 ) score = @matrix [ i ] [ j ] seq1_obj = @seq1 [ i - 1 ] seq2_obj = @seq2 [ j - 1 ] score_align = @matrix [ i - 1 ] [ j - 1 ] + @scoring . score_align ( seq1_obj , seq2_obj ) score_delete = @matrix [ i - 1 ] [ j ] + @scoring . score_delete ( seq1_obj ) score_insert = @matrix [ i ] [ j - 1 ] + @scoring . score_insert ( seq2_obj ) flags = 0 need_select = false if score == score_align flags = :align i -= 1 j -= 1 elsif score == score_delete flags = :delete i -= 1 else flags = :insert j -= 1 end yield ( i , j , flags ) end while i > 0 i -= 1 yield ( i , j , :delete ) end while j > 0 j -= 1 yield ( i , j , :insert ) end end
fill Traces backward finding the alignment .
24,418
def checkout response = gateway . purchase ( payment . price , currency : payment . currency . to_s , client_ip_addr : request . remote_ip , description : payment . description , language : payment . first_data_language ) if response [ :transaction_id ] trx = LolitaFirstData :: Transaction . add ( payment , request , response ) redirect_to gateway . redirect_url ( trx . transaction_id ) else if request . xhr? || ! request . referer render text : I18n . t ( 'fd.purchase_failed' ) , status : 400 else flash [ :error ] = I18n . t ( 'fd.purchase_failed' ) redirect_to :back end end ensure LolitaFirstData . logger . info ( "[#{session_id}][#{payment.id}][checkout] #{response}" ) end
We get transaction_id from FirstData and if ok then we redirect to web interface
24,419
def answer if trx = LolitaFirstData :: Transaction . where ( transaction_id : params [ :trans_id ] ) . first response = gateway . result ( params [ :trans_id ] , client_ip_addr : request . remote_ip ) trx . process_result ( response ) redirect_to trx . return_path else render text : I18n . t ( 'fd.wrong_request' ) , status : 400 end ensure if trx LolitaFirstData . logger . info ( "[#{session_id}][#{trx.paymentable_id}][answer] #{response}" ) end end
there we land after returning from FirstData server then we get transactions result and redirect to your given finish path
24,420
def flot_array ( metrics ) replace = false hash = Hash . new if metrics . nil? || metrics . first . nil? || metrics . first . movingaverage . nil? replace = true metrics = Metric . aggregate_daily_moving_averages ( 0 , "WHERE fulldate > SUBDATE((SELECT fulldate FROM heart_metrics WHERE movingaverage = 0 ORDER BY fulldate desc LIMIT 1), 3)" ) end if metrics . first . nil? return '' end movingaverage = metrics . first . movingaverage extraMeasurements = '' label_suffix = '' if replace == true extraMeasurements = "lines : { show : false, fill : false }," label_suffix = '' else if movingaverage . to_i > 0 extraMeasurements = 'points : { show : false, symbol : "circle" }, lines : { show : true, fill : false },' label_suffix = " [MA:#{movingaverage}] " end end metrics . first . attributes . sort . each do | att , value | next unless value . respond_to? :to_f next if value . is_a? Time extraSettings = extraMeasurements label = t ( att ) + label_suffix hash [ att ] = "#{att} : {#{extraSettings} label : '#{label}', data : [" end metrics . each do | metric | metric . attributes . sort . each do | att , value | next unless value . respond_to? :to_f next if value . is_a? Time hash [ att ] = "#{hash[att]} [#{to_flot_time(metric.fulldate)}, #{value}]," end end metrics . first . attributes . sort . each do | att , value | next unless value . respond_to? :to_f next if value . is_a? Time hash [ att ] = "#{hash[att]} ], att_name : \"#{att}\",}," end flotdata = "flotData_#{movingaverage} : {" hash . each { | key , value | flotdata += value + "\n" } flotdata += "}," flotdata end
Creates javascript objects to use as hashes for flot graph data series + labels
24,421
def evaluate ( context , * args , & block ) self . result = if block context . define_singleton_method ( :__callback__ , & self ) ret = context . send :__callback__ , * args , & block context . class_eval { send :remove_method , :__callback__ } ret else context . instance_exec ( * args , & self ) end end
evaluates the Callback in the specified context
24,422
def define_attribute ( name , type ) _name = name . gsub ( ":" , "_" ) define_method ( _name ) do var = instance_variables . include? ( :@meta ) ? :@meta : :@attributes instance_variable_get ( var ) . find do | attribute | attribute . key == name end . tap { | x | return x . value if x } end define_method ( "%s=" % _name ) do | value | var = instance_variables . include? ( :@meta ) ? :@meta : :@attributes instance_variable_get ( var ) . tap do | attributes | if elt = __send__ ( _name ) attributes . delete ( elt ) end attributes << XES . send ( type , name , value ) end end end
Define an attribute accessor .
24,423
def with_tempfile ( fname = nil , & _block ) Tempfile . open ( "tmp" ) do | f | yield f . path , f . path . shellescape FileUtils . cp ( f . path , fname ) unless fname . nil? end end
Create and manage a temp file replacing fname with the temp file if fname is provided .
24,424
def write_file ( file_name , file_contents ) contents = file_contents . flatten . select { | line | line } . join ( "\n" ) File . open ( file_name , "w" ) do | fh | fh . write ( contents ) fh . write ( "\n" ) end end
Write an array of strings to a file adding newline separators and ensuring a trailing newline at the end of a file .
24,425
def munge_options ( options ) keys_to_munge = [ :build_directory , :tayfile ] munged = { } options . keys . each do | key | if keys_to_munge . include? ( key ) new_key = key . to_s . gsub ( / / , '-' ) end munged [ new_key || key ] = options [ key ] end munged end
We re using Tay s CLI helpers and they expect string optiopns with dashes rather than symbols and underscores . So munge!
24,426
def read_attribute ( attribute ) if block_given? element = yield else element = send ( "#{attribute}?" ) end tag = element . tag_name input_field? ( tag ) ? element . value : element . text end
Searches the record for the specified attribute and returns the text content . This method is called when you access an attribute of a record
24,427
def write_attribute ( attribute , value ) element = send ( "#{attribute}?" ) tag = element . tag_name case tag when 'textarea' , 'input' then element . set ( value ) when 'select' then element . select ( value ) else raise NotInputField end element end
Searches the record for the specified attribute and sets the value of the attribute This method is called when you set an attribute of a record
24,428
def request = ( request ) self . user_ip = request . remote_ip self . user_agent = request . env [ 'HTTP_USER_AGENT' ] self . referrer = request . env [ 'HTTP_REFERER' ] end
Used to set more tracking for akismet
24,429
def delete_all @loaded_constants . each do | const_name | if Object . const_defined? ( const_name ) Object . send ( :remove_const , const_name ) end end Ichiban :: HTMLCompiler :: Context . clear_user_defined_helpers end
Calls Object . remove_const on all tracked modules . Also clears the compiler s list of user - defined helpers .
24,430
def expand_attribute_names_for_aggregates ( attribute_names ) attribute_names . map { | attribute_name | unless ( aggregation = reflect_on_aggregation ( attribute_name . to_sym ) ) . nil? aggregate_mapping ( aggregation ) . map do | field_attr , _ | field_attr . to_sym end else attribute_name . to_sym end } . flatten end
Similar in purpose to + expand_hash_conditions_for_aggregates + .
24,431
def build_report output "Running benchmark report..." REQUESTS . each do | name , params , times | self . benchmark_service ( name , params , times , false ) end output "Done running benchmark report" end
4 decimal places
24,432
def parse! unless @type . nil? || VALID_TASKS . include? ( @type ) raise TaskList :: Exceptions :: InvalidTaskTypeError . new type : @type end @files . each { | f | parsef! file : f } end
Parse all the collected files to find tasks and populate the tasks hash
24,433
def method_missing ( method , * args ) if method . to_s . starts_with? "*" condition_name = method . to_s . split ( "*" ) [ 1 ] . to_sym conditions = self . class . scram_conditions if conditions && ! conditions [ condition_name ] . nil? return conditions [ condition_name ] . call ( self ) end end super end
Methods starting with an asterisk are tested for DSL defined conditions
24,434
def compute_source_path ( source , dir , ext ) source = rewrite_extension ( source , dir , ext ) if ext File . join ( config . assets_dir , dir , source ) end
Return the filesystem path for the source
24,435
def cleanup ( site , stitch ) files = stitch . all_files . map { | f | File . absolute_path ( f ) } files . concat stitch . deleted if files . size > 0 site . static_files . clone . each do | sf | if sf . kind_of? ( Jekyll :: StaticFile ) and files . include? sf . path site . static_files . delete ( sf ) end end end end
Remove files from Jekyll s static_files array
24,436
def get_id_from_token ( token ) storage . get_all ( tokens_key ) . each { | id , t | return id if t == token } false end
Given a token get id from tokens list
24,437
def exec ( * args ) args . flatten! Cany . logger . info args . join ( ' ' ) unless system ( * args ) raise CommandExecutionFailed . new args end end
API to use inside the recipe
24,438
def factory ( name , klass = nil , & block ) @registry [ name . to_sym ] = Resolver :: Factory . new ( block || klass ) end
Registers a dependency which is resolved every time its value is fetched .
24,439
def singleton ( name , klass = nil , & block ) @registry [ name . to_sym ] = Resolver :: Singleton . new ( block || klass ) end
Registers a dependency which is only resolved the first time its value is fetched . On subsequent fetches the cached value is returned .
24,440
def mixin ( args ) if args . is_a? ( Array ) args = { @default_visibility => args } elsif ! args . is_a? ( Hash ) raise ArgumentError , "invalid mixin argument: expected array or hash, got: #{args.class}" end args = DEFAULT_EXPORTS . merge ( args ) . each_with_object ( { } ) do | ( key , exports ) , merged | exports = [ exports ] unless exports . is_a? ( Array ) merged [ key ] = exports . reduce ( { } ) do | a , b | a . merge ( b . is_a? ( Hash ) ? b : { b => b } ) end end @module_cache . get! ( args ) { module_for ( args ) } end
Takes an array or hash specifying the dependencies to export and returns a module which defines getters for those dependencies .
24,441
def module_for ( args ) registry = self mod = Module . new args . each do | visibility , exports | exports . each do | dependency_name , method_name | mod . send ( :define_method , method_name ) do registry . fetch ( dependency_name ) end mod . send ( visibility , method_name ) end end mod end
Create a module with the specified exports
24,442
def cli ( cmd_str , attrs = { format : 'text' } ) reply = rpc . command ( cmd_str , attrs ) reply . respond_to? ( :text ) ? reply . text : reply end
execute CLI commands over NETCONF transport returns plain text rather than XML by default
24,443
def apply_configuration ( config , attrs = { format : 'text' } ) rpc . lock_configuration rpc . load_configuration ( config , attrs ) rpc . commit_configuration rpc . unlock_configuration end
Simplifies applying configuration to a Junos device . Uses Junos NETCONF extensions to apply the configuration . Returns to the previous committed config if any arror occurs
24,444
def << ( patch ) known_patch = @patches [ patch . name ] if known_patch . nil? @patches [ patch . name ] = patch elsif patch . content != known_patch . content raise ContradictionError , [ known_patch , patch ] end end
Adds a patch to the set . Raises ContradictionError in case if patch set already contains a patch with the same name and different content .
24,445
def patch_signature ( name ) row = @db [ :tdp_patch ] . select ( :signature ) . where ( name : name ) . first row . nil? ? nil : row [ :signature ] end
Looks up a signature of a patch by its name .
24,446
def << ( filename ) if File . directory? ( filename ) Dir . foreach ( filename ) do | x | self << File . join ( filename , x ) unless x . start_with? ( '.' ) end elsif TDP . patch_file? ( filename ) @patches << Patch . new ( filename ) end end
Creates a new Engine object .
24,447
def plan ref = @dao . applied_patches @patches . select do | patch | signature = ref [ patch . name ] next false if signature == patch . signature next true if signature . nil? || patch . volatile? raise MismatchError , patch end end
Produces an ordered list of patches that need to be applied .
24,448
def validate_compatible validate_upgradable @patches . each do | patch | signature = @dao . patch_signature ( patch . name ) next if signature == patch . signature raise NotAppliedError , patch if signature . nil? raise MismatchError , patch end end
Validates that all patches are applied to the database .
24,449
def run_unified_application_check ( dns_name , port = 8000 ) url_base = "#{dns_name}:#{port}" behavior ( :test_http_response , "html serving succeeded" , "#{url_base}/index.html" , port ) behavior ( :test_http_response , "configuration=succeeded" , "#{url_base}/appserver/" , port ) behavior ( :test_http_response , "I am in the db" , "#{url_base}/dbread/" , port ) behavior ( :test_http_response , "hostname=" , "#{url_base}/serverid/" , port ) end
this is where ALL the generic application server checks live this could get rather long but for now it s a single method with a sequence of checks
24,450
def validate! ( sender , time : monotonic_timestamp ) key = session_key sender last_observed = @session . fetch ( key ) { raise UnknownSender , sender } raise InvalidSender , sender if expired? last_observed , time , @timeout @session [ key ] = time nil end
Renews the given sender if it is still valid within the session and raises an exception otherwise .
24,451
def new core__set_header_active_page_title ( LANGUAGES [ :lato_blog ] [ :pages ] [ :tags_new ] ) @tag = LatoBlog :: Tag . new if params [ :language ] set_current_language params [ :language ] end if params [ :parent ] @tag_parent = LatoBlog :: TagParent . find_by ( id : params [ :parent ] ) end end
This function shows the view to create a new tag .
24,452
def create @tag = LatoBlog :: Tag . new ( new_tag_params ) if ! @tag . save flash [ :danger ] = @tag . errors . full_messages . to_sentence redirect_to lato_blog . new_tag_path return end flash [ :success ] = LANGUAGES [ :lato_blog ] [ :flashes ] [ :tag_create_success ] redirect_to lato_blog . tag_path ( @tag . id ) end
This function creates a new tag .
24,453
def edit core__set_header_active_page_title ( LANGUAGES [ :lato_blog ] [ :pages ] [ :tags_edit ] ) @tag = LatoBlog :: Tag . find_by ( id : params [ :id ] ) return unless check_tag_presence if @tag . meta_language != cookies [ :lato_blog__current_language ] set_current_language @tag . meta_language end end
This function show the view to edit a tag .
24,454
def update @tag = LatoBlog :: Tag . find_by ( id : params [ :id ] ) return unless check_tag_presence if ! @tag . update ( edit_tag_params ) flash [ :danger ] = @tag . errors . full_messages . to_sentence redirect_to lato_blog . edit_tag_path ( @tag . id ) return end flash [ :success ] = LANGUAGES [ :lato_blog ] [ :flashes ] [ :tag_update_success ] redirect_to lato_blog . tag_path ( @tag . id ) end
This function updates a tag .
24,455
def destroy @tag = LatoBlog :: Tag . find_by ( id : params [ :id ] ) return unless check_tag_presence if ! @tag . destroy flash [ :danger ] = @tag . tag_parent . errors . full_messages . to_sentence redirect_to lato_blog . edit_tag_path ( @tag . id ) return end flash [ :success ] = LANGUAGES [ :lato_blog ] [ :flashes ] [ :tag_destroy_success ] redirect_to lato_blog . categories_path ( status : 'deleted' ) end
This function destroyes a tag .
24,456
def parse_gem ( init_lib ) init_path = init_lib init_file = File . read ( init_lib ) current_file = "" init_file . each_line do | line | if line . strip =~ / / parser = RubyParser . new sexp = parser . parse ( line ) call = sexp [ 2 ] unless call == :require current_file += line next end require_type = sexp [ 3 ] [ 1 ] [ 0 ] library = sexp [ 3 ] [ 1 ] [ 1 ] if require_type == :str && library . match ( @gem_name ) full_rb_path = File . join ( [ @lib_folder , "#{library}.rb" ] ) unless @require_libs . include? ( full_rb_path ) file_index = @require_libs . index ( init_lib ) insert_index = file_index @require_libs . insert insert_index , full_rb_path parse_gem ( full_rb_path ) end else current_file += "# FIXME: #require is not supported in RubyMotion\n" current_file += "# #{line}" next end current_file += "# #{line}" next elsif line . strip =~ / / parser = RubyParser . new sexp = parser . parse ( line ) call = sexp [ 2 ] unless call == :autoload current_file += line next end require_type = sexp [ 3 ] [ 2 ] [ 0 ] library = sexp [ 3 ] [ 2 ] [ 1 ] full_rb_path = File . join ( [ @lib_folder , "#{library}.rb" ] ) unless @require_libs . include? ( full_rb_path ) file_index = @require_libs . index ( init_lib ) insert_index = file_index @require_libs . insert insert_index , full_rb_path parse_gem ( full_rb_path ) end current_file += "# #{line}" next elsif line . strip =~ / / current_file += "# FIXME: Cannot eval strings in RubyMotion. \n" current_file += "# Rewrite to use a block.. inbuilt hack will run \n" current_file += "# Change this: \n" current_file += "# eval %Q{ \n" current_file += '# def #{c}(string = nil) ' + "\n" current_file += "# To this \n" current_file += "# eval do \n" current_file += "# define_method(c) do |string| \n" current_file += "#{line}" next elsif line . strip =~ / / current_file += "# FIXME: binding is not supported in RubyMotion.\n" current_file += "#{line}" next end current_file += line end File . open ( init_lib , 'w' ) { | f | f . write ( current_file ) } end
def simulate! puts simulator not implemented ... end
24,457
def start channel . prefetch ( 10 ) queue . subscribe ( manual_ack : true , exclusive : false ) do | delivery_info , metadata , payload | begin body = JSON . parse ( payload ) . with_indifferent_access status = run ( body ) rescue => e status = :error end if status == :ok channel . ack ( delivery_info . delivery_tag ) elsif status == :retry channel . reject ( delivery_info . delivery_tag , true ) else channel . reject ( delivery_info . delivery_tag , false ) end end wait_for_threads end
Method which kick start the consumer process thread
24,458
def process_options ( options ) options . each do | key , value | key = key . to_s fail OptionException , "No Option #{key}" unless self . class . options [ key ] opt = send ( "#{key}" ) opt . value = value fail OptionException , "Bad value for option #{key}" unless opt . valid? end validate_required_options end
Processes given parameter into the defined options previously declared includes validation for types and any custom validators delcared
24,459
def write ( str ) while ! str . empty? pre , mid , str = str . partition ( "\n" ) write_str ( pre ) unless pre . empty? writeln unless mid . empty? end end
Set up the initial values . Write out a general string with page pauses .
24,460
def write_str ( str ) loop do len = str . length if @chars + len < chars_per_line $pause_output_out . write ( str ) @chars += len return else tipping_point = chars_per_line - @chars $pause_output_out . write ( str [ 0 , tipping_point ] ) count_lines str = ( str [ tipping_point .. - 1 ] ) end end end
Write out a simple string with no embedded new - lines .
24,461
def pause msg = pause_message $pause_output_out . write ( msg ) MiniTerm . raw do | term | result = term . get_raw_char term . flush result end ensure $pause_output_out . write ( "\r" + " " * msg . length + "\r" ) end
Pause waiting for the user .
24,462
def concurrent_map threads = services . map { | s | Thread . new { yield s } } threads . each ( & :join ) threads . map ( & :value ) end
Used to allow performing API requests in parallal instead of series
24,463
def occurrence_at ( time ) real_duration = duration - 1 range = [ time - real_duration , time ] start_time = proxy . occurrences_between ( range [ 0 ] , range [ 1 ] ) . first end_time = start_time + real_duration Occurrence . new start_time , real_duration , end_time end
Returns the scheduled occurrence that matches the specified time
24,464
def files_in ( directories ) files = [ ] Find . find ( * directories ) do | path | unless File . directory? ( path ) or File . symlink? ( path ) files << File . expand_path ( path ) end end files . uniq end
Returns the list of files in the directories provided
24,465
def size_of ( directories ) size = 0 files_in ( directories ) . each do | f | size += File . size ( f ) end size end
Returns the total size of the directories provided
24,466
def setup_dns ( domain ) owner = @deployment . href @dns = SharedDns . new ( domain ) raise "Unable to reserve DNS" unless @dns . reserve_dns ( owner ) @dns . set_dns_inputs ( @deployment ) end
uses SharedDns to find an available set of DNS records and sets them on the deployment
24,467
def find_minion_by_name ( minion_name , raise_error = true ) raise ( 'Minion not specified.' ) if minion_name . nil? || minion_name . empty? return { minion_name => minions_filtered [ minion_name ] } if minions [ minion_name ] minions . each do | key , value | return { key => value } if key . start_with? ( minion_name ) end raise ( "Not found: #{minion_name} in #{stage_name}." ) if raise_error nil end
find node by full node_name or by matching prefix of node_name
24,468
def method_missing ( name , * arguments , & block ) if respond_to? name if arguments . count == 1 processors [ name ] . process ( arguments [ 0 ] ) elsif arguments . count == 2 processors [ name ] . process ( arguments [ 0 ] , arguments [ 1 ] ) end else super end end
Constructor of the classe receiving the datas to validate and filter .
24,469
def cloud_request ( request , & block ) Net :: HTTP . start ( @hostname , 443 , use_ssl : true , read_timeout : 120 ) do | http | request [ 'X-Auth-Token' ] = @account . auth_token request [ 'User-Agent' ] = "raca 0.4.4 (http://rubygems.org/gems/raca)" response = http . request ( request , & block ) if response . is_a? ( Net :: HTTPSuccess ) response else raise_on_error ( request , response ) end end end
perform an HTTP request to rackpsace .
24,470
def method_missing ( method , * params , & block ) @endpoint_parts << method . to_s @endpoint_parts << params @endpoint_parts = @endpoint_parts . flatten! block &. call self || super end
Overrides ruby s method_missing to allow creation of URLs through method calls .
24,471
def output_value_to_column_value ( v ) if v . kind_of? ( Array ) if v . length == 0 nil elsif v . length == 1 v . first elsif v . first . kind_of? ( String ) v . join ( @internal_delimiter ) else raise ArgumentError . new ( "Traject::SequelWriter, multiple non-String values provided: #{v}" ) end else v end end
Traject context . output_hash values are arrays . turn them into good column values joining strings if needed .
24,472
def run ( klass , method ) command_info_module = klass :: CommandInfo . const_get ( camelize ( method ) ) if seeking_command_help? ( @current_args ) puts "\nPurpose: #{command_description(command_info_module)}\n" respond_with_command_help ( command_info_module ) return end valid_args = command_valid_args ( command_info_module ) if ! valid_args? ( valid_args ) handle_invalid_args ( command_info_module ) return end klass . new ( @current_args . dup ) . send ( method ) end
Call a method on a klass with certain arguments . Will validate arguments first before calling method .
24,473
def valid_args? ( accepted_arg_formats ) valid_args = false accepted_arg_formats . each { | format | if format . empty? && @current_args . empty? valid_args = true else passed_in_args = @current_args . clone format . each_with_index { | arg , i | passed_in_args [ i ] = arg if CMD_BLACKLIST . include? ( arg ) } @invalid_args = passed_in_args - format - [ nil ] valid_args = true if passed_in_args == format end } valid_args end
Check if passed - in arguments are valid for a specific format
24,474
def handle_invalid_args ( command_info_module ) if ! @invalid_args . empty? message = 'Invalid argument' message += 's' if @invalid_args . length > 1 args = @invalid_args . map { | arg | "\"#{arg}\"" } . join ( ', ' ) puts " ! #{message}: #{args}" else puts " ! Invalid command usage" end respond_with_command_help ( command_info_module ) end
Respond to the user in the instance of invalid arguments .
24,475
def create_commands_map command_file_paths . each do | file | require file basename = get_basename_from_file ( file ) klass_name = camelize ( basename ) command_klass = Conify :: Command . const_get ( klass_name ) manually_added_methods ( command_klass ) . each { | method | register_command ( basename , method . to_s , command_klass , global : basename == 'global' ) } end end
Create a commands map to respond to conify help with .
24,476
def usage_info ( map ) keys = map . keys commands_column_width = keys . max_by ( & :length ) . length + 1 commands_column_width += 2 if commands_column_width < 12 keys . map { | key | command = " #{key}" command += ( ' ' * ( commands_column_width - key . length + 1 ) ) command += "# #{map[key][:description]}" command } . sort_by { | k | k . downcase } . join ( "\n" ) end
Format a map of commands into help output format
24,477
def get_basename_from_file ( file ) basename = Pathname . new ( file ) . basename . to_s basename [ 0 .. ( basename . rindex ( '.' ) - 1 ) ] end
Return just the basename for a file no extensions .
24,478
def command_file_paths abstract_file = File . join ( File . dirname ( __FILE__ ) , 'command' , 'abstract_command.rb' ) Dir [ File . join ( File . dirname ( __FILE__ ) , 'command' , '*.rb' ) ] - [ abstract_file ] end
Feturn an array of all command file paths with the exception of abstract_command . rb
24,479
def register_command ( basename , action , command_class , global : false ) command = global ? action : ( action == 'index' ? basename : "#{basename}:#{action}" ) command_info_module = command_class :: CommandInfo . const_get ( camelize ( action ) ) commands [ command ] = { description : command_description ( command_info_module ) } end
register a command s info to the
24,480
def tableize_code ( str , lang = '' ) table = '<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers">' code = '' str . lines . each_with_index do | line , index | table += "<span class='line-number'>#{index+1}</span>\n" code += "<span class='line'>#{line}</span>" end table += "</pre></td><td class='code'><pre><code class='#{lang}'>#{code}</code></pre></td></tr></table></div>" end
taken from octopress
24,481
def save validate! body = { box : to_hash } body [ :box ] . delete ( :versions ) begin response = Atlas . client . put ( url_builder . box_url , body : body ) rescue Atlas :: Errors :: NotFoundError body [ :box ] . replace_key! ( :private , :is_private ) response = Atlas . client . post ( "/boxes" , body : body ) end versions . each ( & :save ) if versions update_with_response ( response , [ :versions ] ) end
Save the box .
24,482
def build_mapping ( values ) { } . tap do | hash | values . each_with_index { | key , index | hash [ key ] = ( 0b1 << index ) } end end
Builds internal bitwise key - value mapping it add a zero value needed for bits operations . Each sym get a power of 2 value
24,483
def shorten ( input ) if input . is_a? ( String ) return create_url ( input ) elsif input . is_a? ( Array ) result = { } input . each do | inp | result [ inp ] = create_url ( inp ) end return result else raise ArgumentError . new ( 'Shorten requires either a url or an array of urls' ) end end
Creates a new instance to shorten Firefly URLs
24,484
def create_url ( long_url ) begin options = { :query => { :url => long_url , :api_key => @api_key } } result = HTTParty . post ( @firefly_url + '/api/add' , options ) if result =~ / /i raise "Permission denied. Is your API Key set correctly?" if result . status = 401 else return result end end end
Shortend + long_url + and returns the short_url on success
24,485
def camel ( value ) case value when Hash then value . deep_transform_keys! { | key | camel ( key ) } when Symbol then camel ( value . to_s ) . to_sym when String then StringSupport . camel ( value ) else value end end
Transforms values to UpperCamelCase or PascalCase .
24,486
def camel_lower ( value ) case value when Hash then value . deep_transform_keys! { | key | camel_lower ( key ) } when Symbol then camel_lower ( value . to_s ) . to_sym when String then StringSupport . camel_lower ( value ) else value end end
Transforms values to camelCase .
24,487
def dash ( value ) case value when Hash then value . deep_transform_keys! { | key | dash ( key ) } when Symbol then dash ( value . to_s ) . to_sym when String then StringSupport . dash ( value ) else value end end
Transforms values to dashed - case . This is the default case for the JsonApi adapter .
24,488
def underscore ( value ) case value when Hash then value . deep_transform_keys! { | key | underscore ( key ) } when Symbol then underscore ( value . to_s ) . to_sym when String then StringSupport . underscore ( value ) else value end end
Transforms values to underscore_case . This is the default case for deserialization in the JsonApi adapter .
24,489
def find_by ( param ) if param . key? ( :city ) perform ( param [ :city ] . sub ( ' ' , '-' ) ) elsif param . key? ( :lat ) && param . key? ( :lng ) perform ( "lat=#{param[:lat]}lng=#{param[:lng]}" ) end end
= > find weather by city or by gps position
24,490
def right_header? ( expected , actual ) expected . inject ( true ) do | memo , ( k , v ) | memo && v == actual [ k ] end end
Checks for request comes with right header .
24,491
def parse ( args ) @options = { :report => false } OptionParser . new do | parser | parser . banner = "Usage: todo_lint [options] [files]" add_config_options parser exclude_file_options parser include_extension_options parser report_version parser report_report_options parser end . parse! ( args ) options [ :files ] = args options end
Parses command line options into an options hash
24,492
def exclude_file_options ( parser ) parser . on ( "-e" , "--exclude file1,..." , Array , "List of file names to exclude" ) do | files_list | options [ :excluded_files ] = [ ] files_list . each do | short_file | options [ :excluded_files ] << File . expand_path ( short_file ) end end end
Adds the excluded file options to the options hash
24,493
def has_any? subject , & block found = subjects . include? subject yield if found && block found end
test if a particular category has a certain subject
24,494
def input_attributes ( value ) params = { :id => input_id , :type => type , :name => name , :value => value } if type == 'checkbox' then params [ :value ] ||= self . value params [ :checked ] = true if default end params end
Parses the given field specification .
24,495
def geo_location ( c1 , c2 = nil , c3 = nil ) if c1 . class != GeoLocationSelector selector = GeoLocationSelector . new selector . address do address c1 city c2 country c3 end else selector = c1 end soap_message = service . geo_location . get ( credentials , selector . to_xml ) add_counters ( soap_message . counters ) end
Call geo location adwords service
24,496
def update_all ( updates , conditions = nil , options = { } ) IdentityMap . repository [ symbolized_base_class ] . clear if IdentityMap . enabled? if conditions || options . present? where ( conditions ) . apply_finder_options ( options . slice ( :limit , :order ) ) . update_all ( updates ) else stmt = Arel :: UpdateManager . new ( arel . engine ) stmt . set Arel . sql ( @klass . send ( :sanitize_sql_for_assignment , updates ) ) stmt . table ( table ) stmt . key = table [ primary_key ] if joins_values . any? @klass . connection . join_to_update ( stmt , arel ) else stmt . take ( arel . limit ) stmt . order ( * arel . orders ) stmt . wheres = arel . constraints end @klass . connection . update stmt , 'SQL' , bind_values end end
Updates all records with details given if they match a set of conditions supplied limits and order can also be supplied . This method constructs a single SQL UPDATE statement and sends it straight to the database . It does not instantiate the involved models and it does not trigger Active Record callbacks or validations .
24,497
def export ( * methods ) methods . flatten . map do | method | case value = ( eval ( "self.#{method}" , binding ) rescue nil ) when Date , Time value . strftime ( "%m/%d/%y" ) when TrueClass 'Y' when FalseClass 'N' else value . to_s end end end
Return an array of formatted export values for the passed methods
24,498
def reload config . cache . clear if config . cache . respond_to? ( :clear ) ActiveSupport :: Dependencies . clear if defined? ( ActiveSupport :: Dependencies ) current_config = config . marshal_dump . dup current_config . merge! :skip_bundle => true initialize current_config end
Reloads the environment . This will re - evaluate the config file & clear the current cache .
24,499
def remove_sprocket ( name ) if sprocket = get_sprocket ( name ) sprockets . delete sprocket set_sprocket ( name , nil ) end end
Removes the sprocket with the given name . This is useful if you don t need one of the default Sprockets .