idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
20,600
def transactions raw_transactions = @agent . get ( "https://wwws.mint.com/transactionDownload.event?" ) . body transos = [ ] raw_transactions . split ( "\n" ) . each_with_index do | line , index | if index > 1 line_array = line . split ( "," ) transaction = { :date => Date . strptime ( remove_quotes ( line_array [ 0 ] ) , '%m/%d/%Y' ) , :description => remove_quotes ( line_array [ 1 ] ) , :original_description => remove_quotes ( line_array [ 2 ] ) , :amount => remove_quotes ( line_array [ 3 ] ) . to_f , :type => remove_quotes ( line_array [ 4 ] ) , :category => remove_quotes ( line_array [ 5 ] ) , :account => remove_quotes ( line_array [ 6 ] ) , :labels => remove_quotes ( line_array [ 7 ] ) , :notes => remove_quotes ( line_array [ 8 ] ) } transos << transaction if block_given? yield transaction end end end transos end
login to my account get all the transactions
20,601
def set_with_string ( config ) if File . exists? ( config ) set_with_yaml ( File . read ( config ) ) else set_with_yaml ( config ) end end
String should be either a filename or YAML
20,602
def remove_from_list begin matching_results_ids = session [ :matching_results_ids ] matching_results_ids . delete ( params [ :remove_id ] . to_i ) session [ :matching_results_ids ] = matching_results_ids render :nothing => true rescue render :nothing => true , :status => 500 end end
assumes matching_results_ids in the session drops a given remove_id from the session variable
20,603
def restore_to_list begin matching_results_ids = session [ :matching_results_ids ] session [ :matching_results_ids ] = matching_results_ids << params [ :restore_id ] . to_i render :nothing => true rescue render :nothing => true , :status => 500 end end
assumes matching_results_ids in the session puts back a given restore_id in the session variable
20,604
def sub_context id , ref , attribs = { } @sub_contexts << ref self . elements [ id ] = { attributes : attribs , type : :sub_context , content : ref , } end
mount a context as a sub context here
20,605
def call ( word , opts ) validate_opts! ( opts ) driver = Smartdict :: Core :: DriverManager . find ( opts [ :driver ] ) translation_model = Models :: Translation . find ( word , opts [ :from_lang ] , opts [ :to_lang ] , opts [ :driver ] ) unless translation_model translation = driver . translate ( word , opts [ :from_lang ] , opts [ :to_lang ] ) translation_model = Models :: Translation . create_from_struct ( translation ) end log_query ( translation_model ) if opts [ :log ] translation_model . to_struct end
Just to make the interface compatible
20,606
def process_attributes ( attrs = nil ) if attrs errors = [ ] attributes = attrs . class . new attributes . permit! if attrs . respond_to? ( :permitted? ) && attrs . permitted? multi_parameter_attributes = { } attrs . each_pair do | key , value | if key =~ / \A \( \( \d \) / key , index = $1 , $2 . to_i ( multi_parameter_attributes [ key ] ||= { } ) [ index ] = value . empty? ? nil : value . send ( "to_#{$3}" ) else attributes [ key ] = value end end multi_parameter_attributes . each_pair do | key , values | begin values = ( values . keys . min .. values . keys . max ) . map { | i | values [ i ] } field = self . class . fields [ database_field_name ( key ) ] attributes [ key ] = instantiate_object ( field , values ) rescue => e errors << Errors :: AttributeAssignmentError . new ( "error on assignment #{values.inspect} to #{key}" , e , key ) end end unless errors . empty? raise Errors :: MultiparameterAssignmentErrors . new ( errors ) , "#{errors.size} error(s) on assignment of multiparameter attributes" end super ( attributes ) else super end end
Process the provided attributes casting them to their proper values if a field exists for them on the document . This will be limited to only the attributes provided in the suppied + Hash + so that no extra nil values get put into the document s attributes .
20,607
def load ( data ) init_kms ( @kms_opt ) @logger . info "Writing file #{data} to S3 #{@bucket_name} as #{@remote_path}" s3 . bucket ( @bucket_name ) . object ( @remote_path ) . upload_file ( data , encrypt_args ) true end
Copies data to S3
20,608
def build_skeleton ( dirs , path = @path ) dirs . each { | node | if node . kind_of? ( Hash ) && ! node . empty? ( ) node . each_pair { | dir , content | dir = replace_tags ( dir ) puts 'Creating directory ' + File . join ( path , dir ) Dir . mkdir ( File . join ( path , dir ) ) if content . kind_of? ( Array ) && ! content . empty? ( ) build_skeleton ( content , File . join ( path , dir ) ) end } elsif node . kind_of? ( Array ) && ! node . empty? ( ) node . each { | file | write_file ( file , path ) } end } end
Builds the directory structure
20,609
def write_file ( file , path ) if @template . includes . has_key? ( file ) begin content = Includes . copy_include ( @template . includes [ file ] , @template . path ) file = replace_tags ( file ) rescue TypeError => e puts e . message exit end else file = replace_tags ( file ) puts 'Creating blank file: ' + File . join ( path , file ) content = '' end File . open ( File . join ( path , file ) , 'w' ) { | f | f . write ( replace_tags ( content ) ) } end
Checks if file is listed in the includes list and if so copies it from the given location . If not it creates a blank file .
20,610
def execute_tasks ( tasks , template_path ) if File . exists? ( File . expand_path ( File . join ( template_path , 'tasks.rb' ) ) ) load File . expand_path ( File . join ( template_path , 'tasks.rb' ) ) end tasks . each { | task | puts 'Running Task: ' + task task = replace_tags ( task ) ; options = task . split ( ', ' ) action = options . slice! ( 0 ) if ( Tasks . respond_to? ( action ) ) Tasks . send action , options . join ( ', ' ) else send action , options . join ( ', ' ) end } end
Parses the task string and runs the task .
20,611
def assign ( value ) if @value . respond_to? :assign @value . assign value . simplify . get else @value = value . simplify . get end value end
Store a value in this native element
20,612
def store ( value ) result = value . simplify self . class . target . new ( result . get ) . write @value result end
Store new value in this pointer
20,613
def define_value ( short_name , long_name , description , flag , default_value , validate = nil ) short_name = short_name . to_s long_name = long_name . to_s if ( short_name . length != 1 ) raise ArgumentError , "Short name must be one character long (#{short_name})" end if ( long_name . length < 2 ) raise ArgumentError , "Long name must be more than one character long (#{long_name})" end info = Info . new ( short_name , long_name , description , flag , default_value , nil , validate ) @options [ long_name ] = info @options [ short_name ] = info @order . push ( info ) method_name = long_name . gsub ( '-' , '_' ) method_name << "?" if ( flag ) ( class << self ; self ; end ) . class_eval do define_method ( method_name . to_sym ) do return @options [ long_name ] . value || @options [ long_name ] . default_value end end return self end
If a block is passed in it is given self .
20,614
def argument ( short_name , long_name , description , default_value , validate = nil , & block ) return define_value ( short_name , long_name , description , false , default_value , validate || block ) end
This defines a command line argument that takes a value .
20,615
def flag ( short_name , long_name , description , & block ) return define_value ( short_name , long_name , description , true , false , block ) end
This defines a command line argument that s either on or off based on the presense of the flag .
20,616
def create remove_unwanted_keys validation = Setting . manual_validation ( params ) respond_to do | format | if validation . blank? Setting . save_data ( params ) clear_cache format . html { redirect_to administrator_setup_index_path , notice : I18n . t ( "controllers.admin.setup.general.success" ) } else format . html { @settings = params @settings [ 'errors' ] = validation render action : "index" } end end end
Create the settings for the Admin panel to work!
20,617
def create_user @admin = Admin . new ( administrator_params ) @admin . access_level = 'admin' @admin . overlord = 'Y' respond_to do | format | if @admin . save Setting . save_data ( { setup_complete : 'Y' } ) clear_cache session [ :setup_complete ] = true format . html { redirect_to admin_path , notice : I18n . t ( "controllers.admin.setup.general.success" ) } else format . html { render action : "administrator" } end end end
create a new admin user
20,618
def compare ( & diff_block ) FileUtils . cp_r ( "#{temp_transformed_path}/." , temp_raw_path ) transform_paths! glob_all ( after_path ) . each do | relative_path | expected = after_path + relative_path next unless expected . file? next if context . ignores? ( relative_path ) block = context . preprocessors_for ( relative_path ) . first diff = diff_files ( expected , relative_path , & block ) diff_block . call diff end end
Compares the expected and produced directory by using the rules defined in the context
20,619
def check_unexpected_files ( & block ) expected_files = glob_all after_path produced_files = glob_all unexpected_files = produced_files - expected_files unexpected_files . select! { | path | path . file? } unexpected_files . reject! { | path | context . ignores? ( path ) } block . call unexpected_files end
Compares the expected and produced directory by using the rules defined in the context for unexpected files .
20,620
def prepare! context . prepare! temp_path . rmtree if temp_path . exist? temp_path . mkdir temp_raw_path . mkdir temp_transformed_path . mkdir end
Prepare the temporary directory
20,621
def copy_files! destination = temp_transformed_path if has_base? FileUtils . cp_r ( "#{base_spec.temp_raw_path}/." , destination ) end begin FileUtils . cp_r ( "#{before_path}/." , destination ) rescue Errno :: ENOENT => e raise e unless has_base? end end
Copies the before subdirectory of the given tests folder in the raw directory .
20,622
def transform_paths! glob_all . each do | path | context . transformers_for ( path ) . each do | transformer | transformer . call ( path ) if path . exist? end path . rmtree if context . ignores? ( path ) && path . exist? end end
Applies the in the context configured transformations .
20,623
def glob_all ( path = nil ) Dir . chdir path || '.' do Pathname . glob ( "**/*" , context . include_hidden_files? ? File :: FNM_DOTMATCH : 0 ) . sort . reject do | p | %w( . .. ) . include? ( p . basename . to_s ) end end end
Searches recursively for all files and take care for including hidden files if this is configured in the context .
20,624
def diff_files ( expected , relative_path , & block ) produced = temp_transformed_path + relative_path Diff . new ( expected , produced , relative_path , & block ) end
Compares two files to check if they are identical and produces a clear diff to highlight the differences .
20,625
def klass_from_predicate ( predicate ) field_name = field_from_predicate ( predicate ) return unless field_name relation = relations [ field_name ] return unless relation relation . class_name . constantize end
Retrieve the class for a relation based on its defined RDF predicate
20,626
def field_from_predicate ( predicate ) defined_prop = resource_class . properties . find { | _field_name , term | term . predicate == predicate } return unless defined_prop defined_prop . first end
Retrieve the attribute name for a field or relation based on its defined RDF predicate
20,627
def update_relation ( field_name , * obj ) return unless obj obj . map! { | item | item . is_a? ( RDF :: URI ) ? Ladder :: Resource . from_uri ( item ) : item } relation = send ( field_name ) if Mongoid :: Relations :: Targets :: Enumerable == relation . class obj . map { | item | relation . send ( :push , item ) unless relation . include? item } else send ( "#{field_name}=" , obj . size > 1 ? obj : obj . first ) end end
Set values on a defined relation
20,628
def update_field ( field_name , * obj ) return unless obj if fields [ field_name ] && fields [ field_name ] . localized? trans = { } obj . each do | item | lang = item . is_a? ( RDF :: Literal ) && item . has_language? ? item . language . to_s : I18n . locale . to_s value = item . is_a? ( RDF :: URI ) ? item . to_s : item . object trans [ lang ] = trans [ lang ] ? [ * trans [ lang ] ] << value : value end send ( "#{field_name}_translations=" , trans ) unless trans . empty? else objects = obj . map { | item | item . is_a? ( RDF :: URI ) ? item . to_s : item . object } send ( "#{field_name}=" , objects . size > 1 ? objects : objects . first ) end end
Set values on a field ; this will cast values from RDF types to persistable Mongoid types
20,629
def cast_value ( value , opts = { } ) case value when Array value . map { | v | cast_value ( v , opts ) } when String cast_uri = RDF :: URI . new ( value ) cast_uri . valid? ? cast_uri : RDF :: Literal . new ( value , opts ) when Time value . midnight == value ? RDF :: Literal . new ( value . to_date ) : RDF :: Literal . new ( value . to_datetime ) else RDF :: Literal . new ( value , opts ) end end
Cast values from Mongoid types to RDF types
20,630
def data @grid_file ||= self . class . grid . get ( id ) if persisted? return @grid_file . data if @grid_file file . rewind if file . respond_to? :rewind file . read end
Output content of object from stored file or readable input
20,631
def to_human Incline :: Extensions :: Numeric :: SHORT_SCALE . each do | ( num , label ) | if self >= num s = ( '%.2f' % ( ( self . to_f / num ) + 0.0001 ) ) . gsub ( / \. \z / , '' ) return "#{s} #{label}" end end if self . is_a? ( :: Rational ) if self . denominator == 1 return self . numerator . to_s end return self . to_s elsif self . is_a? ( :: Integer ) return self . to_s end ( '%.2f' % ( self . to_f + 0.0001 ) ) . gsub ( / \. \z / , '' ) end
Formats the number using the short scale for any number over 1 million .
20,632
def generate_sunippets sunippet_define = read_sunippetdefine dsl = Dsl . new dsl . instance_eval sunippet_define output_methods ( dsl ) output_requires ( dsl ) end
generate sublime text2 sunippets from Sunippetdefine
20,633
def count ( event , number = 1 ) ActiveMetrics :: Collector . record ( event , { metric : 'count' , value : number } ) end
Count log lines are used to submit increments to Librato .
20,634
def measure ( event , value = 0 ) if block_given? time = Time . now value = yield delta = Time . now - time ActiveMetrics :: Collector . record ( event , { metric : 'measure' , value : delta } ) value else ActiveMetrics :: Collector . record ( event , { metric : 'measure' , value : value } ) end end
Measure log lines are used to submit individual measurements that comprise a statistical distribution . The most common use case are timings i . e . latency measurements but it can also be used to represent non - temporal distributions such as counts .
20,635
def messenger_received_message ( message_string ) begin message = Messages . from_json ( message_string ) rescue ProtocolError @scheduler . receive ( :invalid_message ) return end case message when Messages :: CallRequest then @scheduler . receive ( :call_request_message , message ) when Messages :: CallResponse then @scheduler . receive ( :call_response_message , message ) when Messages :: Compatibility then @scheduler . receive ( :compatibility_message , message ) when Messages :: Forget then @scheduler . receive ( :forget_message , message ) when Messages :: Initialization then @scheduler . receive ( :initialization_message , message ) when Messages :: Shutdown then @scheduler . receive ( :shutdown_message ) end end
Submit a message from the messenger . The thread will wait its turn if another event is being processed .
20,636
def add ( value , options = { } ) options [ :duplication_filter ] = :do_not_add unless options . key? ( :duplication_filter ) path = get_array if path . member? ( value ) case options [ :duplication_filter ] when :do_not_add , :deny return when :remove_existing path . delete! ( value ) when :none else raise WrongOptionError , "Unknown :duplication_filter!" end end case options [ :where ] when :start , :left path . unshift value when :end , :right path . push value else raise WrongOptionError , "Unknown :where!" end set_array ( path ) end
Adds value to the path
20,637
def with_reg ( access_mask = Win32 :: Registry :: Constants :: KEY_ALL_ACCESS , & block ) @hkey . open ( @reg_path , access_mask , & block ) end
Execute block with the current reg settings
20,638
def valid_with_associates? ( context = nil ) valid_without_associates? ( context ) self . class . associates . each do | associate | model = send ( associate . name ) model . valid? ( context ) model . errors . each_entry do | attribute , message | if associate . dependent_names . include? ( attribute . to_s ) next elsif respond_to? ( attribute ) errors . add ( attribute , message ) else errors . add ( :base , model . errors . full_messages_for ( attribute ) ) end end end errors . messages . values . each ( & :uniq! ) errors . none? end
Runs the model validations plus the associated models validations and merges each messages in the errors hash
20,639
def say ( msg , sym = '...' , loud = false , indent = 0 ) return false if Conf [ :quiet ] return false if loud && ! Conf [ :verbose ] unless msg == '' time = "" if Conf [ :timed ] time = Timer . time . to_s . ljust ( 4 , '0' ) time = time + " " end indent = " " * indent indent = " " if indent == "" puts "#{time}#{sym}#{indent}#{msg}" else puts end end
Write + msg + to standard output according to verbosity settings . Not meant to be used directly
20,640
def load_troopfile! ( options ) if troopfile? eval troopfile . read @loaded = true load_environment! set options else raise Trooper :: NoConfigurationFileError , "No Configuration file (#{self[:file_name]}) can be found!" end end
loads the troopfile and sets the environment up
20,641
def load ( pattern = nil ) tests = [ ] Find . find @@conf . test_root do | path | next if File . directory? path if pattern next unless rel_path ( path ) . match ( pattern ) end next if File . basename ( path ) . match ( / \. / ) next if ignored? ( path ) tests << Test . new ( path ) end return tests end
Create a test suite
20,642
def ignored? ( path ) @@conf . ignore . each do | ignore | return true if rel_path ( path ) . match ( ignore ) end return false end
Checks all ignore patterns against a given relative path
20,643
def save ( value ) write value . values . pack ( value . typecode . directive ) value end
Write typed value to memory
20,644
def create Setting . where ( "setting_name = 'theme_folder'" ) . update_all ( 'setting' => params [ :theme ] ) Setting . reload_settings respond_to do | format | format . html { redirect_to admin_themes_path , notice : I18n . t ( "controllers.admin.themes.create.flash.success" ) } end end
update the currently used theme
20,645
def destroy destory_theme params [ :id ] respond_to do | format | format . html { redirect_to admin_themes_path , notice : I18n . t ( "controllers.admin.themes.destroy.flash.success" ) } end end
remove the theme from the theme folder stopping any future usage .
20,646
def sentence sections = [ ] 1 . upto ( rand ( 5 ) + 1 ) do sections << ( words ( rand ( 9 ) + 3 ) . join ( " " ) ) end s = sections . join ( ", " ) return s . capitalize + ".?!" . slice ( rand ( 3 ) , 1 ) end
Returns a randomly generated sentence of lorem ipsum text . The first word is capitalized and the sentence ends in either a period or question mark . Commas are added at random .
20,647
def create_new_project ( project_name ) ( error ( _ ( 'wizard.project.name_exist' ) ) ; return false ) if project_exists? ( Dir . pwd , project_name ) bebox_boxes_setup current_box = choose_box ( get_existing_boxes ) vagrant_box_base = "#{BEBOX_BOXES_PATH}/#{get_valid_box_uri(current_box)}" vagrant_box_provider = choose_option ( %w{ virtualbox vmware } , _ ( 'wizard.project.choose_box_provider' ) ) default_environments = %w{ vagrant staging production } project = Bebox :: Project . new ( project_name , vagrant_box_base , Dir . pwd , vagrant_box_provider , default_environments ) output = project . create ok _ ( 'wizard.project.creation_success' ) % { project_name : project_name } return output end
Asks for the project parameters and create the project skeleton
20,648
def uri_valid? ( vbox_uri ) require 'uri' uri = URI . parse ( vbox_uri ) %w{ http https } . include? ( uri . scheme ) ? http_uri_valid? ( uri ) : file_uri_valid? ( uri ) end
Validate uri download or local box existence
20,649
def get_existing_boxes expanded_directory = File . expand_path ( "#{BEBOX_BOXES_PATH}" ) boxes = Dir [ "#{expanded_directory}/*" ] . reject { | f | File . directory? f } boxes . map { | box | box . split ( '/' ) . last } end
Obtain the current boxes downloaded or linked in the bebox user home
20,650
def choose_box ( boxes ) other_box_message = _ ( 'wizard.project.download_select_box' ) boxes << other_box_message current_box = choose_option ( boxes , _ ( 'wizard.project.choose_box' ) ) current_box = ( current_box == other_box_message ) ? nil : current_box end
Asks to choose an existing box in the bebox boxes directory
20,651
def download_box ( uri ) require 'net/http' require 'uri' url = uri . path Net :: HTTP . start ( uri . host ) do | http | response = http . request_head ( URI . escape ( url ) ) write_remote_file ( uri , http , response ) end end
Download a box by the specified uri
20,652
def handle_fallback ( * args ) case @fallback_policy when :abort raise RejectedExecutionError when :discard false when :caller_runs begin yield ( * args ) rescue => e Chef :: Log . debug "Caught exception => #{e}" end true else fail "Unknown fallback policy #{@fallback_policy}" end end
Handler which executes the fallback_policy once the queue size reaches max_queue .
20,653
def post ( * args , & task ) raise ArgumentError . new ( 'no block given' ) unless block_given? mutex . synchronize do return handle_fallback ( * args , & task ) unless running? execute ( * args , & task ) true end end
Submit a task to the executor for asynchronous processing .
20,654
def kill mutex . synchronize do break if shutdown? stop_event . set kill_execution stopped_event . set end true end
Begin an immediate shutdown . In - progress tasks will be allowed to complete but enqueued tasks will be dismissed and no new tasks will be accepted . Has no additional effect if the thread pool is not running .
20,655
def taxamatch ( str1 , str2 , return_boolean = true ) preparsed_1 = @parser . parse ( str1 ) preparsed_2 = @parser . parse ( str2 ) match = taxamatch_preparsed ( preparsed_1 , preparsed_2 ) rescue nil return_boolean ? ( ! ! match && match [ 'match' ] ) : match end
takes two scientific names and returns true if names match and false if they don t
20,656
def taxamatch_preparsed ( preparsed_1 , preparsed_2 ) result = nil if preparsed_1 [ :uninomial ] && preparsed_2 [ :uninomial ] result = match_uninomial ( preparsed_1 , preparsed_2 ) end if preparsed_1 [ :genus ] && preparsed_2 [ :genus ] result = match_multinomial ( preparsed_1 , preparsed_2 ) end if result && result [ 'match' ] result [ 'match' ] = match_authors ( preparsed_1 , preparsed_2 ) == - 1 ? false : true end return result end
takes two hashes of parsed scientific names analyses them and returns back this function is useful when species strings are preparsed .
20,657
def hook_into test_framework adapter = self . class . adapters [ test_framework ] raise ArgumentError . new "No adapter for test framework #{test_framework}" if adapter . nil? require adapter end
Hook this gem in a test framework by a supported adapter
20,658
def parse_response_for ( response ) case response when Net :: HTTPOK , Net :: HTTPCreated then return Response :: Success . new ( response ) when Net :: HTTPForbidden then raise Response :: InvalidCredentials when Net :: HTTPInternalServerError then raise Response :: ServerError else raise Response :: UnknownError end end
Handles the response from Instapaper .
20,659
def request ( method , params = { } ) http = Net :: HTTP . new ( Api :: ADDRESS , ( @https ? 443 : 80 ) ) http . use_ssl = @https http . verify_mode = OpenSSL :: SSL :: VERIFY_NONE request = Net :: HTTP :: Post . new ( Api :: ENDPOINT + method . to_s ) request . basic_auth @username , @password request . set_form_data ( params ) http . start { http . request ( request ) } end
Actually heads out to the internet and performs the request
20,660
def rate! ( opt = { } ) max_iterations = [ 30 , 1 ] phase_2_bonuses = true update_bonuses = false threshold = 0.5 version = opt [ :version ] . to_i if version >= 1 max_iterations [ 1 ] = 30 end if version >= 2 phase_2_bonuses = false update_bonuses = true threshold = 0.1 end if version >= 3 max_iterations = [ 50 , 50 ] end players . each { | p | p . reset } @iterations1 = performance_ratings ( max_iterations [ 0 ] , threshold ) players . each { | p | p . rate! } if ! no_bonuses && calculate_bonuses > 0 players . each { | p | p . rate! ( update_bonuses ) } @iterations2 = performance_ratings ( max_iterations [ 1 ] , threshold ) calculate_bonuses if phase_2_bonuses else @iterations2 = 0 end end
Rate the tournament . Called after all players and results have been added .
20,661
def calculate_bonuses @player . values . select { | p | p . respond_to? ( :bonus ) } . inject ( 0 ) { | t , p | t + ( p . calculate_bonus ? 1 : 0 ) } end
Calculate bonuses for all players and return the number who got one .
20,662
def migrate_references ( row , migrated , target , proc_hash = nil ) migratable__migrate_owner ( row , migrated , target , proc_hash ) migratable__set_nonowner_references ( migratable_independent_attributes , row , migrated , proc_hash ) migratable__set_nonowner_references ( self . class . unidirectional_dependent_attributes , row , migrated , proc_hash ) end
Migrates this domain object s migratable references . This method is called by the Migrator and should not be overridden by subclasses . Subclasses tailor individual reference attribute migration by defining a + migrate_ + _attribute_ method for the _attribute_ to modify .
20,663
def tick ( step = nil ) if step . nil? @current += 1 else @current = step end percent = @current . to_f / @max . to_f if percent - @last_report > 1 . to_f / @num_reports . to_f report @last_report = percent end nil end
Creates a new instance . Max is the total number of iterations of the loop . The depth represents how many other loops are above this one this information is used to find the place to print the progress report .
20,664
def report percent = @current . to_f / @max . to_f percent = 0.001 if percent < 0.001 if @desc != "" indicator = @desc + ": " else indicator = "Progress " end indicator += "[" 10 . times { | i | if i < percent * 10 then indicator += "." else indicator += " " end } indicator += "] done #{(percent * 100).to_i}% " eta = ( Time . now - @time ) / percent * ( 1 - percent ) eta = eta . to_i eta = [ eta / 3600 , eta / 60 % 60 , eta % 60 ] . map { | t | "%02i" % t } . join ( ':' ) used = ( Time . now - @time ) . to_i used = [ used / 3600 , used / 60 % 60 , used % 60 ] . map { | t | "%02i" % t } . join ( ':' ) indicator += " (Time left #{eta} seconds) (Started #{used} seconds ago)" STDERR . print ( "\033[#{@depth + 1}F\033[2K" + indicator + "\n\033[#{@depth + 2}E" ) end
Prints de progress report . It backs up as many lines as the meters depth . Prints the progress as a line of dots a percentage time spent and time left . And then goes moves the cursor back to its original line . Everything is printed to stderr .
20,665
def key_parts ( key , & block ) return enum_for ( :key_parts , key ) unless block nesting = PARENS counts = PARENS_ZEROS delim = '.' from = to = 0 key . each_char do | char | if char == delim && PARENS_ZEROS == counts block . yield key [ from ... to ] from = to = ( to + 1 ) else nest_i , nest_inc = nesting [ char ] if nest_i counts = counts . dup if counts . frozen? counts [ nest_i ] += nest_inc end to += 1 end end block . yield ( key [ from ... to ] ) if from < to && to <= key . length true end
yield each key part dots inside braces or parenthesis are not split on
20,666
def process_stream_data ( line ) return true if process_update_message UpdateMessage . parse ( line , id , items , fields ) return true if process_overflow_message OverflowMessage . parse ( line , id , items ) return true if process_end_of_snapshot_message EndOfSnapshotMessage . parse ( line , id , items ) end
Processes a line of stream data if it is relevant to this subscription . This method is thread - safe and is intended to be called by the session s processing thread .
20,667
def control_request_options ( action , options = nil ) case action . to_sym when :start start_control_request_options options when :unsilence { LS_session : @session . session_id , LS_op : :start , LS_table : id } when :stop { LS_session : @session . session_id , LS_op : :delete , LS_table : id } end end
Returns the control request arguments to use to perform the specified action on this subscription .
20,668
def inherited ( subclass ) [ :steps , :failed_steps ] . each do | inheritable_attribute | instance_var = "@#{inheritable_attribute}" subclass . instance_variable_set ( instance_var , instance_variable_get ( instance_var ) . dup || [ ] ) end end
Callback assure that we add steps from parent class
20,669
def show_text ( text , options = { } ) cmd = WriteTextCommand . new cmd . display_pause = options [ :display_pause ] if options [ :display_pause ] cmd . text = text send_command cmd end
Displays the given text on the board .
20,670
def send_command ( command ) SerialPort . open ( self . device_path , 9600 , 8 , 1 ) do | port | port . flush flush_read_buffer ( port ) byte_string = command . to_bytes . pack ( 'C*' ) begin while byte_string && byte_string . length != 0 count = port . write_nonblock ( byte_string ) byte_string = byte_string [ count , - 1 ] port . flush end rescue IO :: WaitWritable if IO . select ( [ ] , [ port ] , [ ] , 5 ) retry else raise IOError , "Timeout writing command to #{self.device_path}" end end got_eot = false got_soh = false loop do begin c = port . read_nonblock ( 1 ) case c when "\x04" if ! got_eot got_eot = true else raise IOError , "Got EOT reply twice from #{self.device_path}" end when "\x01" if got_eot if ! got_soh got_soh = true break else raise IOError , "Got SOH twice from #{self.device_path}" end else raise IOError , "Got SOH before EOT from #{self.device_path}" end end rescue IO :: WaitReadable if IO . select ( [ port ] , [ ] , [ ] , 3 ) retry else raise IOError , "Timeout waiting for command reply from #{self.device_path}. EOT:#{got_eot} SOH:#{got_soh}" end end end end self end
Sends the specified Movingsign command to this sign s serial port
20,671
def get_bulk a = lattice_const c = 1.63299 * a as1 = Atom . new ( 0 , 0 , 0 , 'As' ) as2 = as1 . displace ( 0.5 * a , 0.33333 * a , 0.5 * c ) ga1 = Atom . new ( 0.0 , 0.0 , c * 0.386 , 'Ga' ) ga2 = ga1 . displace ( 0.5 * a , 0.33333 * a , 0.5 * c ) v1 = Vector [ 1.0 , 0.0 , 0.0 ] * a v2 = Vector [ 0.5 , 0.5 * sqrt ( 3 ) , 0.0 ] * a v3 = Vector [ 0.0 , 0.0 , 1.0 ] * c wz = Geometry . new ( [ as1 , ga1 , as2 , ga2 ] , [ v1 , v2 , v3 ] ) return wz end
Initialize the wurtzite Geometry cation and anion are the atomic species occupying the two different sub - lattices . lattice_const specifies the lattice constant
20,672
def fetch_job_messages ( offset , job_id , opts = { } ) data , _status_code , _headers = fetch_job_messages_with_http_info ( offset , job_id , opts ) return data end
Fetch Job messages
20,673
def authorize_admin_access Setting . reload_settings if ! check_controller_against_user ( params [ :controller ] . sub ( 'roroacms/admin/' , '' ) ) && params [ :controller ] != 'roroacms/admin/dashboard' && params [ :controller ] . include? ( 'roroacms' ) redirect_to admin_path , flash : { error : I18n . t ( "controllers.admin.misc.authorize_admin_access_error" ) } end end
checks to see if the admin logged in has the necesary rights if not it will redirect them with an error message
20,674
def wrap_java_property ( property ) pd = property . property_descriptor if pd . property_type == Java :: JavaLang :: String . java_class then wrap_java_string_property ( property ) elsif pd . property_type == Java :: JavaUtil :: Date . java_class then wrap_java_date_property ( property ) end end
Adds a filter to the given property access methods if it is a String or Date .
20,675
def wrap_java_string_property ( property ) ra , wa = property . accessors jra , jwa = property . java_accessors define_method ( wa ) do | value | stdval = Math . numeric? ( value ) ? value . to_s : value send ( jwa , stdval ) end logger . debug { "Filtered #{qp} #{wa} method with non-String -> String converter." } end
Adds a number - > string filter to the given String property Ruby access methods .
20,676
def wrap_java_date_property ( property ) ra , wa = property . accessors jra , jwa = property . java_accessors define_method ( ra ) do value = send ( jra ) Java :: JavaUtil :: Date === value ? value . to_ruby_date : value end define_method ( wa ) do | value | value = Java :: JavaUtil :: Date . from_ruby_date ( value ) if :: Date === value send ( jwa , value ) end logger . debug { "Filtered #{qp} #{ra} and #{wa} methods with Java Date <-> Ruby Date converter." } end
Adds a Java - Ruby Date filter to the given Date property Ruby access methods . The reader returns a Ruby date . The writer sets a Java date .
20,677
def alias_property_accessors ( property ) jra , jwa = property . java_accessors alias_method ( property . reader , jra ) alias_method ( property . writer , jwa ) end
Aliases the given Ruby property reader and writer to its underlying Java property reader and writer resp .
20,678
def add_java_property ( pd ) prop = create_java_property ( pd ) add_property ( prop ) pa = prop . attribute ja = pd . name . to_sym delegate_to_property ( ja , prop ) unless prop . reader == ja prop end
Makes a standard attribute for the given property descriptor . Adds a camelized Java - like alias to the standard attribute .
20,679
def delegate_to_property ( aliaz , property ) ra , wa = property . accessors if aliaz == ra then raise MetadataError . new ( "Cannot delegate #{self} #{aliaz} to itself." ) end define_method ( aliaz ) { send ( ra ) } define_method ( "#{aliaz}=" . to_sym ) { | value | send ( wa , value ) } register_property_alias ( aliaz , property . attribute ) end
Defines methods _aliaz_ and _aliaz = _ which calls the standard _attribute_ and _attribute = _ accessor methods resp . Calling rather than aliasing the attribute accessor allows the aliaz accessor to reflect a change to the attribute accessor .
20,680
def create Dir . mktmpdir do | tmp_dir | project_dir = Pathname . new ( @config [ :app_dir ] ) package_dir = Pathname . new ( tmp_dir ) build_dir = Pathname . new ( @config [ :build_dir ] ) copy_source ( project_dir , package_dir ) copy_executables ( project_dir , package_dir ) create_gem_shims ( package_dir ) install_dependencies ( package_dir , fetcher ) Dir . chdir ( tmp_dir ) do create_archive ( build_dir ) end File . join ( build_dir , @config [ :archive_name ] ) end end
Create an archive using the instance s configuration .
20,681
def identity_parts ( id ) @brokers . each do | b | return [ b . host , b . port , b . index , priority ( b . identity ) ] if b . identity == id || b . alias == id end [ nil , nil , nil , nil ] end
Break broker serialized identity down into individual parts if exists
20,682
def get ( id ) @brokers . each { | b | return b . identity if b . identity == id || b . alias == id } nil end
Get broker serialized identity if client exists
20,683
def connected @brokers . inject ( [ ] ) { | c , b | if b . connected? then c << b . identity else c end } end
Get serialized identity of connected brokers
20,684
def failed @brokers . inject ( [ ] ) { | c , b | b . failed? ? c << b . identity : c } end
Get serialized identity of failed broker clients i . e . ones that were never successfully connected not ones that are just disconnected
20,685
def connect ( host , port , index , priority = nil , force = false , & blk ) identity = self . class . identity ( host , port ) existing = @brokers_hash [ identity ] if existing && existing . usable? && ! force logger . info ( "Ignored request to reconnect #{identity} because already #{existing.status.to_s}" ) false else old_identity = identity @brokers . each do | b | if index == b . index old_identity = b . identity break end end unless existing address = { :host => host , :port => port , :index => index } broker = BrokerClient . new ( identity , address , @serializer , @exception_stats , @non_delivery_stats , @options , existing ) p = priority ( old_identity ) if priority && priority < p @brokers . insert ( priority , broker ) elsif priority && priority > p logger . info ( "Reduced priority setting for broker #{identity} from #{priority} to #{p} to avoid gap in list" ) @brokers . insert ( p , broker ) else @brokers [ p ] . close if @brokers [ p ] @brokers [ p ] = broker end @brokers_hash [ identity ] = broker yield broker . identity if block_given? true end end
Make new connection to broker at specified address unless already connected or currently connecting
20,686
def subscribe ( queue , exchange = nil , options = { } , & blk ) identities = [ ] brokers = options . delete ( :brokers ) each ( :usable , brokers ) { | b | identities << b . identity if b . subscribe ( queue , exchange , options , & blk ) } logger . info ( "Could not subscribe to queue #{queue.inspect} on exchange #{exchange.inspect} " + "on brokers #{each(:usable, brokers).inspect} when selected #{brokers.inspect} " + "from usable #{usable.inspect}" ) if identities . empty? identities end
Subscribe an AMQP queue to an AMQP exchange on all broker clients that are connected or still connecting Allow connecting here because subscribing may happen before all have confirmed connected Do not wait for confirmation from broker client that subscription is complete When a message is received acknowledge unserialize and log it as specified If the message is unserialized and it is not of the right type it is dropped after logging a warning
20,687
def unsubscribe ( queue_names , timeout = nil , & blk ) count = each ( :usable ) . inject ( 0 ) do | c , b | c + b . queues . inject ( 0 ) { | c , q | c + ( queue_names . include? ( q . name ) ? 1 : 0 ) } end if count == 0 blk . call if blk else handler = CountedDeferrable . new ( count , timeout ) handler . callback { blk . call if blk } each ( :usable ) { | b | b . unsubscribe ( queue_names ) { handler . completed_one } } end true end
Unsubscribe from the specified queues on usable broker clients Silently ignore unknown queues
20,688
def queue_status ( queue_names , timeout = nil , & blk ) count = 0 status = { } each ( :connected ) { | b | b . queues . each { | q | count += 1 if queue_names . include? ( q . name ) } } if count == 0 blk . call ( status ) if blk else handler = CountedDeferrable . new ( count , timeout ) handler . callback { blk . call ( status ) if blk } each ( :connected ) do | b | if b . queue_status ( queue_names ) do | name , messages , consumers | ( status [ name ] ||= { } ) [ b . identity ] = { :messages => messages , :consumers => consumers } handler . completed_one end else b . queues . each { | q | handler . completed_one if queue_names . include? ( q . name ) } end end end true end
Check status of specified queues for connected brokers Silently ignore unknown queues If a queue whose status is being checked does not exist the associated broker connection will fail and be unusable
20,689
def publish ( exchange , packet , options = { } ) identities = [ ] no_serialize = options [ :no_serialize ] || @serializer . nil? message = if no_serialize then packet else @serializer . dump ( packet ) end brokers = use ( options ) brokers . each do | b | if b . publish ( exchange , packet , message , options . merge ( :no_serialize => no_serialize ) ) identities << b . identity if options [ :mandatory ] && ! no_serialize context = Context . new ( packet , options , brokers . map { | b | b . identity } ) @published . store ( message , context ) end break unless options [ :fanout ] end end if identities . empty? selected = "selected " if options [ :brokers ] list = aliases ( brokers . map { | b | b . identity } ) . join ( ", " ) raise NoConnectedBrokers , "None of #{selected}brokers [#{list}] are usable for publishing" end identities end
Publish message to AMQP exchange of first connected broker
20,690
def delete ( name , options = { } ) identities = [ ] u = usable brokers = options . delete ( :brokers ) ( ( brokers || u ) & u ) . each { | i | identities << i if ( b = @brokers_hash [ i ] ) && b . delete ( name , options ) } identities end
Delete queue in all usable brokers or all selected brokers that are usable
20,691
def delete_amqp_resources ( name , options = { } ) identities = [ ] u = usable ( ( options [ :brokers ] || u ) & u ) . each { | i | identities << i if ( b = @brokers_hash [ i ] ) && b . delete_amqp_resources ( :queue , name ) } identities end
Delete queue resources from AMQP in all usable brokers
20,692
def remove ( host , port , & blk ) identity = self . class . identity ( host , port ) if broker = @brokers_hash [ identity ] logger . info ( "Removing #{identity}, alias #{broker.alias} from broker list" ) broker . close ( propagate = true , normal = true , log = false ) @brokers_hash . delete ( identity ) @brokers . reject! { | b | b . identity == identity } yield identity if block_given? else logger . info ( "Ignored request to remove #{identity} from broker list because unknown" ) identity = nil end identity end
Remove a broker client from the configuration Invoke connection status callbacks only if connection is not already disabled There is no check whether this is the last usable broker client
20,693
def declare_unusable ( identities ) identities . each do | id | broker = @brokers_hash [ id ] raise Exception , "Cannot mark unknown broker #{id} unusable" unless broker broker . close ( propagate = true , normal = false , log = false ) end end
Declare a broker client as unusable
20,694
def close ( & blk ) if @closed blk . call if blk else @closed = true @connection_status = { } handler = CountedDeferrable . new ( @brokers . size ) handler . callback { blk . call if blk } @brokers . each do | b | begin b . close ( propagate = false ) { handler . completed_one } rescue StandardError => e handler . completed_one logger . exception ( "Failed to close broker #{b.alias}" , e , :trace ) @exception_stats . track ( "close" , e ) end end end true end
Close all broker client connections
20,695
def close_one ( identity , propagate = true , & blk ) broker = @brokers_hash [ identity ] raise Exception , "Cannot close unknown broker #{identity}" unless broker broker . close ( propagate , & blk ) true end
Close an individual broker client connection
20,696
def connection_status ( options = { } , & callback ) id = generate_id @connection_status [ id ] = { :boundary => options [ :boundary ] , :brokers => options [ :brokers ] , :callback => callback } if timeout = options [ :one_off ] @connection_status [ id ] [ :timer ] = EM :: Timer . new ( timeout ) do if @connection_status [ id ] if @connection_status [ id ] [ :callback ] . arity == 2 @connection_status [ id ] [ :callback ] . call ( :timeout , nil ) else @connection_status [ id ] [ :callback ] . call ( :timeout ) end @connection_status . delete ( id ) end end end id end
Register callback to be activated when there is a change in connection status Can be called more than once without affecting previous callbacks
20,697
def reset_stats @return_stats = RightSupport :: Stats :: Activity . new @non_delivery_stats = RightSupport :: Stats :: Activity . new @exception_stats = @options [ :exception_stats ] || RightSupport :: Stats :: Exceptions . new ( self , @options [ :exception_callback ] ) true end
Reset broker client statistics Do not reset disconnect and failure stats because they might then be inconsistent with underlying connection status
20,698
def connect_all self . class . addresses ( @options [ :host ] , @options [ :port ] ) . map do | a | identity = self . class . identity ( a [ :host ] , a [ :port ] ) BrokerClient . new ( identity , a , @serializer , @exception_stats , @non_delivery_stats , @options , nil ) end end
Connect to all configured brokers
20,699
def priority ( identity ) priority = 0 @brokers . each do | b | break if b . identity == identity priority += 1 end priority end
Determine priority of broker If broker not found assign next available priority